def intersect(self, query): """ Extracts relevant patterns to the query and intersects their indices returns set of atoms ids """ # put query in tmp atomspace, check if there are relevant patterns tmp = create_child_atomspace(self.pattern_space) q = tmp.add_atom(rename(tmp, self.pattern_space, query)) # check query for exact match: exact_match = execute_atom(tmp, tmp.add_link(types.BindLink, [q, q])) for m in exact_match.out: return self._index[self.pattern_space.add_link( types.BindLink, [m, m])] # no exact match: search among all patterns # todo: search subgraphs res_set = None for pat, idx in self._index.items(): # pattern is relevant if it matches query match = execute_atom(tmp, pat) for m in match.out: if hash(m) == hash(q): if res_set is None: res_set = idx else: res_set = res_set.intersection(idx) return res_set
def calculate_marginals(internal_atomspace): factors_link = GetLink( TypedVariableLink(VariableNode('$F'), TypeNode('ConceptNode')), get_factor_predicate(VariableNode('$F'))) factors = execute_atom(internal_atomspace, factors_link) for factor in factors.get_out(): variables_link = GetLink( TypedVariableLink(VariableNode('$V'), TypeNode('ConceptNode')), get_edge_predicate(factor, VariableNode('$V'))) variables = execute_atom(internal_atomspace, variables_link) for variable in variables.get_out(): # Multiply one in and one out message for each message_variable_factor = get_message_predicate(variable, factor) message_factor_variable = get_message_predicate(factor, variable) message_in = message_variable_factor.get_value( key_message()).value() message_out = message_factor_variable.get_value( key_message()).value() marginalization = np.dot(message_in, message_out) return marginalization break break
def show_results(): # Show all messages all_messages_rule = GetLink( VariableList( TypedVariableLink(VariableNode('$V1'), TypeNode('ConceptNode')), TypedVariableLink(VariableNode('$V2'), TypeNode('ConceptNode'))), get_message(VariableNode('$V1'), VariableNode('$V2'))) all_messages = execute_atom(atomspace, all_messages_rule) print("messages:") for listLink in all_messages.get_out(): v1 = listLink.get_out()[0] v2 = listLink.get_out()[1] value = get_message(v1, v2).get_value(MESSAGE_KEY) print(' message:', v1.name, v2.name, value.to_list()) # Show all nodes all_nodes_rule = GetLink( TypedVariableLink(VariableNode('$V1'), TypeNode('ConceptNode')), get_node(VariableNode('$V1'))) all_nodes = execute_atom(atomspace, all_nodes_rule) print("nodes:") for vertex in all_nodes.get_out(): value = get_node(vertex).get_value(MESSAGE_KEY) print(' node:', vertex.name, value.to_list())
def test_tmp_atomspace(self): ListLink(ConceptNode("foo"), ConceptNode("bar")) get = GetLink( VariableNode("x"), AndLink( PresentLink(ListLink(ConceptNode("foo"), (VariableNode("x")))), EvaluationLink( GroundedPredicateNode("py: test_functions.func_one"), ListLink(VariableNode("x"))), EvaluationLink( GroundedPredicateNode("py: test_functions.func_two"), ListLink(VariableNode("x"))))) result = execute_atom(self.atomspace, get) self.assertFalse(result.out) self.assertFalse( self.atomspace.is_node_in_atomspace(types.ConceptNode, 'barleycorn')) test_functions.func_one_result = TruthValue(1, 1) result = execute_atom(self.atomspace, get) self.assertTrue(result.out) # still should not be in the current namespace self.assertFalse( self.atomspace.is_node_in_atomspace(types.ConceptNode, 'barleycorn'))
def test_init_factor_graph_implication_link_product_rule3(self): a = ConceptNode("A") b = ConceptNode("B") c = ConceptNode("C") d = ConceptNode("D") implication = ImplicationLink(ListLink(a, b, c), d) implication_probability = [[[[0.9, 0.1], [0.8, 0.2]], [[0.7, 0.3], [0.6, 0.4]]], [[[0.9, 0.1], [0.8, 0.2]], [[0.7, 0.3], [0.6, 0.4]]]] # implication.set_value(key_probability(), PtrValue(Probability(implication_probability))) implication.set_value(key_probability(), PtrValue(implication_probability)) child_atomspace = self.create_child_atomspace() execute_atom(child_atomspace, init_factor_graph_implication_link_product_rule()) # check domain self.check_domain_value(ConceptNode("Variable-A"), 2) self.check_domain_value(ConceptNode("Variable-B"), 2) self.check_domain_value(ConceptNode("Variable-C"), 2) self.check_domain_value(ConceptNode("Variable-D"), 2) # check probability tensors self.check_tensor_value(ConceptNode("Factor-A-B-C-D"), implication_probability) self.delete_child_atomspace()
def run_message_passing_ure(): res = execute_atom(atomspace, directed_message_edge_creation_rule) res = execute_atom(atomspace, create_initial_messages_rule) fc_message_sending_rule_name = DefinedSchemaNode("fc-message-sending-rule") DefineLink(fc_message_sending_rule_name, create_messages_rule) fc_message_sending_rbs = ConceptNode("fc-message-sending-rule") InheritanceLink(fc_message_sending_rbs, ConceptNode("URE")) MemberLink(fc_message_sending_rule_name, fc_message_sending_rbs) # Set URE maximum-iterations from opencog.scheme_wrapper import scheme_eval execute_code = \ ''' (use-modules (opencog rule-engine)) (ure-set-num-parameter (ConceptNode "fc-message-sending-rbs") "URE:maximum-iterations" 30) ''' scheme_eval(atomspace, execute_code) # chainer = ForwardChainer(atomspace, # ConceptNode("fc-message-sending-rule"), # SetLink()) # log.set_level('FINE') # chainer = ForwardChainer(atomspace, # ConceptNode("fc-message-sending-rule"), # get_message(VariableNode("$V1"), VariableNode("$V2")), # VariableList( # TypedVariableLink(VariableNode("$V1"), TypeNode("ConceptNode")), # TypedVariableLink(VariableNode("$V2"), TypeNode("ConceptNode"))) # ) # chainer = BackwardChainer(atomspace, # ConceptNode("fc-message-sending-rule"), # get_message(VariableNode("$V1"), VariableNode("$V2"))) chainer = BackwardChainer( atomspace, ConceptNode("fc-message-sending-rule"), get_message(VariableNode("$V1"), VariableNode("$V2")), VariableList( TypedVariableLink(VariableNode("$V1"), TypeNode("ConceptNode")), TypedVariableLink(VariableNode("$V2"), TypeNode("ConceptNode")))) chainer.do_chain() results = chainer.get_results() log.set_level('INFO') res = execute_atom(atomspace, create_node_value_rule)
def test_add_atom_from_grounded_schema_node(self): test_as = AtomSpace() execute_atom( test_as, ExecutionOutputLink(GroundedSchemaNode("py:add_new_link"), ListLink())) self.assertTrue( test_as.is_link_in_atomspace(types.InheritanceLink, [ test_as.add_node(types.ConceptNode, "cat"), test_as.add_node(types.ConceptNode, "animal") ]))
def run_message_passing(): res = execute_atom(atomspace, directed_message_edge_creation_rule) # print("create directed graph") # print(res) res = execute_atom(atomspace, create_initial_messages_rule) # print('send initial messages') # print(res) res = execute_atom(atomspace, create_messages_rule) res = execute_atom(atomspace, create_messages_rule) # print('send messages') # print(res) res = execute_atom(atomspace, create_node_value_rule) # print(res) pass
def query_parts_for_donation(device): query = BindLink( VariableNode("X"), EvaluationLink(PredicateNode('partof'), ListLink(VariableNode('X'), device)), VariableNode('X')) global space return execute_atom(space, query)
def test_call_grounded_object_no_arguments(self): exec_link = ApplyLink( MethodOfLink(GroundedObjectNode("obj", TestObject("obj")), ConceptNode("no_return_value")), ListLink()) result = execute_atom(self.space, exec_link) self.assertEqual(result, None)
def compute_prob(self, data, label): """ Accepts batch with features and labels, returns probability of labels """ # 1) create NumberNodes # 2) compute possible pairs of NumberNodes # 3) compute probability of earch pair # 4) compute total probability with tmp_atomspace(self.atomspace) as atomspace: inp1 = InputModule(ConceptNode("img1"), data[0].reshape([1, 1, 28, 28])) inp2 = InputModule(ConceptNode("img2"), data[1].reshape([1, 1, 28, 28])) pairs = execute_atom( atomspace, self.get_query(str(int(label.sum())), atomspace)) lst = [] for pair in pairs.out: lst.append( self.sum_prob.execute( self.digit_prob.execute( self.mnist.execute(inp1.execute()), pair.out[0]), self.digit_prob.execute( self.mnist.execute(inp2.execute()), pair.out[1]))) sum_query = self.torch_sum.execute(*lst) result = self.execute_atom(sum_query) return result
def update_index(self, atomspace, data, idx): for pat in self._index.keys(): match = execute_atom(atomspace, pat) # patterns can match patterns, so check: for m in match.out: if m == data: self._index[pat].add(idx)
def execute_atom(self, atom, atomspace=None): if atomspace is None: atomspace = create_child_atomspace(self.atomspace) result = execute_atom(atomspace, atom) value = get_value(result) atomspace.clear() # todo: use ValueOfLink to get tensor value return value
def test_init_factor_graph_implication_link_product_rule2(self): self.init_factor_graph_implication_link_product_rule2() child_atomspace = self.create_child_atomspace() execute_atom(child_atomspace, init_factor_graph_implication_link_product_rule()) # check domain self.check_domain_value(ConceptNode("Variable-A"), 1) self.check_domain_value(ConceptNode("Variable-B"), 2) self.check_domain_value(ConceptNode("Variable-C"), 3) # check probability tensors self.check_tensor_value(ConceptNode("Factor-A-B-C"), self.implication_probability) self.delete_child_atomspace()
def execute_atom(self, atom, atomspace=None): if atomspace is None: atomspace = create_child_atomspace(self.atomspace) result = execute_atom(atomspace, atom) value = get_cached_value(result) self.clear_cache() atomspace.clear() return value
def test_execute_atom(self): result = execute_atom( self.atomspace, ExecutionOutputLink( GroundedSchemaNode("py: test_functions.add_link"), ListLink(ConceptNode("one"), ConceptNode("two")))) list_link = ListLink(ConceptNode("one"), ConceptNode("two")) self.assertEquals(result, list_link)
def test_too_many_args(self): atom1 = ConceptNode("atom1") exec_link = ExecutionOutputLink( GroundedSchemaNode("py:return_concept"), ListLink(atom1, atom1)) try: result = execute_atom(self.space, exec_link) self.assertFalse("call should fail") except RuntimeError as e: self.assertTrue("but 2 were given" in str(e))
def test_too_few_args(self): atom1 = ConceptNode("atom1") exec_link = ExecutionOutputLink(GroundedSchemaNode("py:return_concept"), ListLink()) try: result = execute_atom(self.space, exec_link) self.assertFalse("call should fail") except RuntimeError as e: self.assertTrue("missing 1 required positional argument" in str(e))
def test_too_few_args(self): atom1 = ConceptNode("atom1") exec_link = ExecutionOutputLink( GroundedSchemaNode("py:return_concept"), ListLink()) try: result = execute_atom(self.space, exec_link) self.assertFalse("call should fail") except RuntimeError as e: self.assertTrue("missing 1 required positional argument" in str(e))
def test_call_grounded_object_predicate_two_args(self): exec_link = ApplyLink( MethodOfLink(GroundedObjectNode("obj", TestObject("obj")), ConceptNode("get_second")), ListLink(ConceptNode("first"), ConceptNode("second"))) result = execute_atom(self.space, exec_link) self.assertEqual(result, ConceptNode("second"))
def test_too_many_args(self): atom1 = ConceptNode("atom1") exec_link = ExecutionOutputLink(GroundedSchemaNode("py:return_concept"), ListLink(atom1, atom1)) try: result = execute_atom(self.space, exec_link) self.assertFalse("call should fail") except RuntimeError as e: self.assertTrue("but 2 were given" in str(e))
def test_call_grounded_object_call(self): exec_link = ApplyLink( MethodOfLink(GroundedObjectNode("obj", TestObject("obj")), ConceptNode("get_argument")), ListLink(ConceptNode("arg"))) result = execute_atom(self.space, exec_link) self.assertEqual(result, ConceptNode("arg"))
def test_call_grounded_object_return_tv(self): exec_link = ApplyLink( MethodOfLink( GroundedObjectNode("obj", TestObject("obj")), ConceptNode("return_tv")), ListLink()) result = execute_atom(self.space, exec_link) self.assertEqual(result, TruthValue(0.5, 0.6))
def get_neigbours(v): neighbour_nodes_rule = BindLink( TypedVariableLink(VariableNode('$V'), TypeNode('ConceptNode')), AndLink( # Pattern clauses get_directed_message_edge(VariableNode('$V'), v)), VariableNode('$V')) return execute_atom(atomspace, neighbour_nodes_rule)
def test_do_execute_value(self): key = PredicateNode("key") atom = ConceptNode("atom") atom.set_value(key, FloatValue([1, 2, 3])) value_of_link = ValueOfLink(atom, key) value = execute_atom(atomspace, value_of_link) self.assertEqual(FloatValue([1, 2, 3]), value) self.assertEqual([1, 2, 3], value.to_list())
def test_call_grounded_object_without_arguments_wrapping(self): exec_link = ApplyLink( MethodOfLink( GroundedObjectNode("obj", TestObject("obj"), unwrap_args=True), ConceptNode("plain_multiply")), ListLink(GroundedObjectNode("a", 6), GroundedObjectNode("b", 7))) result = execute_atom(self.space, exec_link) self.assertEqual(result.get_object(), 42)
def test_grounded_cond(self): grounded_cond = CondLink( EvaluationLink(GroundedPredicateNode("py:grounded_cond1"), ListLink()), NumberNode('1'), EvaluationLink(GroundedPredicateNode("py:grounded_cond2"), ListLink()), NumberNode('2')) result = execute_atom(self.space, grounded_cond) baz = NumberNode("2") print("got %s", result) print("expected %s\n", baz) self.assertTrue(result == baz)
def run_program(self, features, program): self.atomspace = pushAtomspace(self.atomspace) self._add_scene_atom(features) eval_link, left, inheritance_set = tbd_helpers.return_prog( commands=tuple(reversed(program)), atomspace=self.atomspace) bind_link = tbd_helpers.build_bind_link(self.atomspace, eval_link, inheritance_set) result = execute_atom(self.atomspace, bind_link) answer = self.argmax(result) self.atomspace = popAtomspace(self.atomspace) return answer
def update_index_dual_link(self, content): # doesn't work d = tmp.add_link(types.DualLink, [content]) # result is a set of conditional parts from pattens(GetLinks) pattern_set = execute_atom(tmp, d) # todo: create a new pattern assert len(pattern_set.out) for pattern in pattern_set.out: get_link = self.pattern_space.add_link(types.GetLink, pattern) self._index[get_link].add(data)
def get_neigbours_except(v1, v2): neighbour_nodes_rule = BindLink( TypedVariableLink(VariableNode('$V'), TypeNode('ConceptNode')), AndLink( # Preconditions NotLink(EqualLink(VariableNode('$V'), v2)), # Pattern clauses get_directed_message_edge(VariableNode('$V'), v1)), VariableNode('$V')) return execute_atom(atomspace, neighbour_nodes_rule)
def test_init_factor_graph_implication_link_product_rule2_given_b_c(self): self.init_factor_graph_implication_link_product_rule2() child_atomspace = self.create_child_atomspace() ConceptNode("B").set_value(key_evidence(), PtrValue(0)) ConceptNode("C").set_value(key_evidence(), PtrValue(2)) execute_atom(child_atomspace, init_factor_graph_implication_link_product_rule()) # check domain self.check_domain_value(ConceptNode("Variable-A"), 1) self.check_domain_value(ConceptNode("Variable-B"), 1) self.check_domain_value(ConceptNode("Variable-C"), 1) # check probability tensors self.check_tensor_value(ConceptNode("Factor-A-B-C"), np.array([0.7])) self.delete_child_atomspace()
def test_do_execute_atom(self): (DefineLink( DefinedSchemaNode('add'), LambdaLink(VariableList(VariableNode('$X'), VariableNode('$Y')), PlusLink(VariableNode('$X'), VariableNode('$Y'))))) res = execute_atom( self.atomspace, ExecutionOutputLink(DefinedSchemaNode('add'), ListLink(NumberNode("3"), NumberNode("4")))) self.assertEqual(NumberNode("7"), res)
def test_execute_atom(self): result = execute_atom(self.atomspace, ExecutionOutputLink( GroundedSchemaNode("py: test_functions.add_link"), ListLink( ConceptNode("one"), ConceptNode("two") ) ) ) list_link = ListLink( ConceptNode("one"), ConceptNode("two") ) self.assertEquals(result, list_link)
result = bindlink(atomspace, bindlink_handle) assert_true(result is not None and result.value() > 0) # Check the ending atomspace size, it should have added one SetLink. ending_size = atomspace.size() assert_equals(ending_size, starting_size + 1) # The SetLink should have three items in it. atom = atomspace[result] assert_equals(atom.arity, 3) assert_equals(atom.type, types.SetLink) result = execute_atom(atomspace, ExecutionOutputLink( GroundedSchemaNode("py: add_link"), ListLink( ConceptNode("one"), ConceptNode("two") ) ) ) list_link = ListLink( ConceptNode("one"), ConceptNode("two") ) assert_equals(result, list_link) finalize_opencog() del atomspace
def test_correct_argcount(self): atom1 = ConceptNode("atom1") exec_link = ExecutionOutputLink(GroundedSchemaNode("py:return_concept"), ListLink(atom1)) result = execute_atom(self.space, exec_link) self.assertTrue(result.name == "test")
@staticmethod def static_check(x1): print("Entering static method with\n", x1) return x1 def forward(self, x1, x2): print("Entering LocalClass with\n", x1, x2) return x1 nn = LocalClass() # local function exlof = ExecutionOutputLink( GroundedSchemaNode("py:local_func"), ListLink(ConceptNode("aa"), ConceptNode("bb"), ConceptNode("cc"))) assert execute_atom(a, exlof) == ConceptNode("cc"), "Failed while calling local function" # local object exloc = ExecutionOutputLink( GroundedSchemaNode("py:nn.forward"), ListLink(ConceptNode("aa"), ConceptNode("bb"))) assert execute_atom(a, exloc) == ConceptNode("aa"), "Failed while calling local object method" # static method exst = ExecutionOutputLink( GroundedSchemaNode("py:LocalClass.static_check"), ListLink(ConceptNode("aa"))) assert execute_atom(a, exst) == ConceptNode("aa"), "Failed while calling static class method"
def test_bindlink(self): atom = execute_atom(self.atomspace, self.bindlink_atom) print("Bindlink found: " + str(atom)) self._check_result_setlink(atom, 3)
def test_satisfying_set(self): atom = execute_atom(self.atomspace, self.getlink_atom) self._check_result_setlink(atom, 3)