OverviewFilesCommitsIssuesDocsReleasesPeers

opencog-rocca commits / f6d25b0

Updates to enable visualization of the cogscms in each cycle.
f6d25b0d14c71cd52cdbe4184ea965aeb5e0e611
by Hedra <tanksh24@gmail.com> · 2022-06-06T23:03:08.000Z

Changed files (2) +159 -88

rocca/agents/core.py +29 -15
……@@ -212,6 +212,9 @@ class OpencogAgent:
212212 # patterns).
213213 self.miner_maximum_variables = 8
214214
215 # Enable posting cogscms and selected action to the visualizer.
216 self.visualize_cogscm = False
217
215218 def __del__(self):
216219 self.env.close()
217220
……@@ -792,7 +795,6 @@ class OpencogAgent:
792795
793796 add_to_atomspace(new_cogscms, self.cogscms_atomspace)
794797 self.cognitive_schematics.update(new_cogscms)
795 post_to_restapi_scheme_endpoint(new_cogscms, PORT=5001)
796798
797799 def learn(self):
798800 """Discover patterns in the world and in itself."""
……@@ -1558,7 +1560,6 @@ class OpencogAgent:
15581560 self.cycle_count, atoms_to_scheme_str(obs_record)
15591561 )
15601562 )
1561 post_to_restapi_scheme_endpoint(obs_record)
15621563
15631564 # Make the goal for that iteration
15641565 goal = self.make_goal()
……@@ -1577,7 +1578,6 @@ class OpencogAgent:
15771578 self.cycle_count, len(cogscms), atoms_to_scheme_str(cogscms)
15781579 )
15791580 )
1580 post_to_restapi_scheme_endpoint(cogscms)
15811581
15821582 # Deduce the action distribution
15831583 mxmdl = self.deduce(cogscms)
……@@ -1610,7 +1610,6 @@ class OpencogAgent:
16101610 self.cycle_count, atom_to_scheme_str(action)
16111611 )
16121612 )
1613 post_to_restapi_scheme_endpoint(action_record)
16141613
16151614 # Increment the counter for that action and log it
16161615 self.action_counter[action] += 1
……@@ -1621,6 +1620,25 @@ class OpencogAgent:
16211620 self.action_counter_to_str(),
16221621 )
16231622 )
1623 if self.visualize_cogscm:
1624 obs = " ".join([str(i) for i in obs_record]) if self.cycle_count > 0 else ""
1625 if cogscm:
1626 msg = "cogscm: {} \r\nSelected Action: {}".format(
1627 to_human_readable_str(cogscm), to_human_readable_str(action)
1628 )
1629 obs_cogscm_act = obs + str(cogscm) + str(action_record)
1630 else:
1631 msg = "cogscm: N/A \r\nSelected Action: {}".format(
1632 to_human_readable_str(action)
1633 )
1634 obs_cogscm_act = obs + str(action_record)
1635
1636 vis_cogscm_info = {
1637 "cogscm": obs_cogscm_act,
1638 "cycle": self.cycle_count,
1639 "msg": msg,
1640 }
1641 post_to_restapi_scheme_endpoint(vis_cogscm_info)
16241642
16251643 # Increase the step count and run the next step of the environment
16261644 self.cycle_count += 1
……@@ -1651,7 +1669,6 @@ class OpencogAgent:
16511669 self.cycle_count, atom_to_scheme_str(reward_record)
16521670 )
16531671 )
1654 post_to_restapi_scheme_endpoint(action_record)
16551672
16561673 return done
16571674
……@@ -1911,7 +1928,7 @@ class MixtureModel:
19111928 def weighted_probability(self, w8: float, pblt: float) -> float:
19121929 """Return the weighted probability using X."""
19131930
1914 return pblt * w8**self.weight_influence
1931 return pblt * w8 ** self.weight_influence
19151932
19161933 def infer_data_set_size(self, cogscms: list[Atom], total_count: int) -> None:
19171934 """Infer the data set size (universe size).
……@@ -2162,15 +2179,12 @@ class MixtureModel:
21622179 cogscm = act_w8_cogscm_w8d_pblt[2]
21632180 pblt = act_w8_cogscm_w8d_pblt[3]
21642181 w8d_pblt = act_w8_cogscm_w8d_pblt[4]
2165 return (
2166 indent
2167 + "{}: (weight={}, cogscm={}, probability={}, weighted probability={})".format(
2168 to_human_readable_str(action),
2169 weight,
2170 atom_to_idstr(cogscm),
2171 pblt,
2172 w8d_pblt,
2173 )
2182 return indent + "{}: (weight={}, cogscm={}, probability={}, weighted probability={})".format(
2183 to_human_readable_str(action),
2184 weight,
2185 atom_to_idstr(cogscm),
2186 pblt,
2187 w8d_pblt,
21742188 )
21752189
21762190 def act_w8_cogscm_w8d_pblt_seq_to_str(
rocca/agents/utils.py +130 -73
……@@ -39,9 +39,10 @@ from opencog.type_constructors import (
3939)
4040from opencog.utilities import get_free_variables, load_file
4141
42from requests import post
42from requests import post, get, delete
4343import json
4444import re
45import time
4546
4647#############
4748# Constants #
……@@ -62,78 +63,6 @@ agent_log.set_component("Agent")
6263#############
6364
6465
65def pre_process_atoms(exp):
66 # Processing empty variableset
67 exp = re.sub(r"\(VariableSet\)", "", exp)
68 exp = re.sub(r"\(VariableSet\s*\)", "", exp)
69 # exp = re.sub(r'back', '', exp, flags=re.IGNORECASE)
70
71 # Processing szlinks
72 exp = re.sub(r";.*\n", "\n", exp, flags=re.MULTILINE)
73 exp = re.sub(r"\(ZLink\s+", "(ZLink", exp)
74 exp = re.sub(r"\)\s+\)", "))", exp)
75 exp = re.sub(r"\)\s+\)", "))", exp)
76
77 starting_indices_slinks = [m.start() for m in re.finditer("SLink", exp)]
78 starting_indices_zlinks = [m.start() for m in re.finditer("ZLink", exp)]
79
80 for i in range(len(starting_indices_zlinks)):
81 # Get the index of its preceding zlink
82 index_preceding_zlink = -1 if i == 0 else starting_indices_zlinks[i - 1]
83 # Count the number of its parent links and the index of the start of its parent slink
84 parent_count = 0
85 index_parent_slink = 0
86 for p in starting_indices_slinks:
87 if p < starting_indices_zlinks[i] and p > index_preceding_zlink:
88 parent_count += 1
89 if parent_count == 1:
90 index_parent_slink = p
91 if p > starting_indices_zlinks[i]:
92 break
93 # Form the new string
94 if parent_count == 0:
95 # ='s are added and removed later to keep the length of the string exp the same while other szlinks are processed.
96 # This will keep previously calculated sz indices valid
97 exp = (
98 exp[0 : starting_indices_zlinks[i] - 1]
99 + "=" * 7
100 + exp[starting_indices_zlinks[i] + 6 :]
101 )
102 else:
103 len_szlinks = (
104 (starting_indices_zlinks[i] + 4 + 1 + parent_count + 1 - 1)
105 - (index_parent_slink - 1)
106 + 1
107 )
108 len_time_node = len('(TimeNode "' + str(parent_count) + '")')
109 # "`" is added and removed later to keep the length of the string exp the same while other szlinks are processed.
110 # This will keep previously calculated sz indices valid
111 exp = (
112 exp[0 : index_parent_slink - 1]
113 + '(TimeNode "'
114 + str(parent_count)
115 + '")'
116 + "`" * (len_szlinks - len_time_node)
117 + exp[starting_indices_zlinks[i] + 4 + 1 + parent_count + 1 :]
118 )
119
120 exp = exp.replace("=" * 7, '(TimeNode "0")')
121 exp = exp.replace("`", "")
122 return exp
123
124
125def post_to_restapi_scheme_endpoint(cogscm, PORT=5000, IP_ADDRESS="127.0.0.1"):
126 """Post data to the visualizer"""
127 uri = "http://" + IP_ADDRESS + ":" + str(PORT) + "/api/v1.1/"
128 headers = {"content-type": "application/json"}
129
130 # Execute scheme command
131 # command = {'command': '(ConceptNode "cat")'}
132 if cogscm:
133 command = {"command": pre_process_atoms(str(cogscm))}
134 post_response = post(uri + "scheme", data=json.dumps(command), headers=headers)
135
136
13766def add_to_atomspace(atoms: set[Atom] | list[Atom], atomspace: AtomSpace) -> None:
13867 """Add all atoms to the atomspace."""
13968
……@@ -1365,6 +1294,134 @@ def load_atomspace(
13651294 return False
13661295
13671296
1297def pre_process_atoms(exp):
1298 # Processing empty variableset
1299 exp = re.sub(r"\(VariableSet\)", "", exp)
1300 exp = re.sub(r"\(VariableSet\s*\)", "", exp)
1301 # exp = re.sub(r'back', '', exp, flags=re.IGNORECASE)
1302
1303 # Processing szlinks
1304 exp = re.sub(r";.*\n", "\n", exp, flags=re.MULTILINE)
1305 exp = re.sub(r"\(ZLink\s+", "(ZLink", exp)
1306 exp = re.sub(r"\)\s+\)", "))", exp)
1307 exp = re.sub(r"\)\s+\)", "))", exp)
1308
1309 starting_indices_slinks = [m.start() for m in re.finditer("SLink", exp)]
1310 starting_indices_zlinks = [m.start() for m in re.finditer("ZLink", exp)]
1311
1312 for i in range(len(starting_indices_zlinks)):
1313 # Get the index of its preceding zlink
1314 index_preceding_zlink = -1 if i == 0 else starting_indices_zlinks[i - 1]
1315 # Count the number of its parent links and the index of the start of its parent slink
1316 parent_count = 0
1317 index_parent_slink = 0
1318 for p in starting_indices_slinks:
1319 if p < starting_indices_zlinks[i] and p > index_preceding_zlink:
1320 parent_count += 1
1321 if parent_count == 1:
1322 index_parent_slink = p
1323 if p > starting_indices_zlinks[i]:
1324 break
1325 # Form the new string
1326 if parent_count == 0:
1327 # ='s are added and removed later to keep the length of the string exp
1328 # the same while other szlinks are processed.
1329 # This will keep previously calculated sz indices valid
1330 exp = (
1331 exp[0 : starting_indices_zlinks[i] - 1]
1332 + "=" * 7
1333 + exp[starting_indices_zlinks[i] + 6 :]
1334 )
1335 else:
1336 len_szlinks = (
1337 (starting_indices_zlinks[i] + 4 + 1 + parent_count + 1 - 1)
1338 - (index_parent_slink - 1)
1339 + 1
1340 )
1341 len_time_node = len('(TimeNode "' + str(parent_count) + '")')
1342 # "`" is added and removed later to keep the length of the string exp
1343 # the same while other szlinks are processed.
1344 # This will keep previously calculated sz indices valid
1345 exp = (
1346 exp[0 : index_parent_slink - 1]
1347 + '(TimeNode "'
1348 + str(parent_count)
1349 + '")'
1350 + "`" * (len_szlinks - len_time_node)
1351 + exp[starting_indices_zlinks[i] + 4 + 1 + parent_count + 1 :]
1352 )
1353
1354 exp = exp.replace("=" * 7, '(TimeNode "0")')
1355 exp = exp.replace("`", "")
1356 return exp
1357
1358
1359def post_to_restapi_scheme_endpoint(
1360 cogscm_info, PORT=5000, IP_ADDRESS="127.0.0.1", cogscm_as=False
1361):
1362 """
1363 Visualize cognitive schema and selected action in each cycle.
1364
1365 cogscm_as: an atomspace containing cognitive schema.
1366 cogscm_info: a dictionary containing
1367 - The discovered cognitive schema cogscm
1368 - human readable form msg
1369 - cycle count
1370
1371 """
1372 # Post data to the visualizer
1373 uri = "http://" + IP_ADDRESS + ":" + str(PORT) + "/api/v1.1/"
1374 headers = {"content-type": "application/json"}
1375
1376 if cogscm_as:
1377 execute_command("(clear)", uri, headers)
1378 all_cogscms = cogscm_as.get_atoms_by_type(
1379 types.BackPredictiveImplicationScopeLink
1380 )
1381 print("Discovered {} cogscms".format(len(all_cogscms)))
1382
1383 for bpi in all_cogscms:
1384 bpi = """
1385 {} (ConceptNode "cogscm:{}")""".format(
1386 bpi, to_human_readable_str(bpi)
1387 )
1388 bpi = pre_process_atoms(str(bpi))
1389 execute_command(bpi, uri, headers)
1390 time.sleep(5)
1391 else:
1392 cogscm = cogscm_info["cogscm"]
1393 cycle = cogscm_info["cycle"]
1394 msg = cogscm_info["msg"]
1395
1396 if cycle > 49:
1397 # clear the visualizer atomspace
1398 execute_command("(clear)", uri, headers)
1399 else:
1400 # update the current selected action
1401 get_response = get(uri + "atoms", params={"type": "ConceptNode"})
1402 for atom in get_response.json()["result"]["atoms"]:
1403 if "cogscm:" in atom["name"]:
1404 delete_response = delete(uri + "atoms/" + str(atom["handle"]))
1405
1406 cogscm = """
1407 {} (ConceptNode "{}")
1408 """.format(
1409 cogscm, msg
1410 )
1411 cogscm = pre_process_atoms(str(cogscm))
1412 execute_command(cogscm, uri, headers)
1413 time.sleep(5)
1414
1415
1416def execute_command(scheme_command, uri, headers):
1417 """
1418 Execute scheme command
1419 command = {'command': '(ConceptNode "cat")'}
1420 """
1421 command = {"command": scheme_command}
1422 post_response = post(uri + "scheme", data=json.dumps(command), headers=headers)
1423
1424
13681425class MinerLogger:
13691426
13701427 """Quick and dirty miner logger Python bindings"""