def control_av_in_atomspace(self):
        """Called in the main loop to update av
        For now we control av in this way:
        if new block appeared or old block disappeared:
        (e.g. finding such atom structures
            EvaluationLink
                PredicateNode "new_block"
                StructureNode "objXX"
        )
            increase its av
            remove the new block/ disappeared predicate
        for all block:
            decrease their av
        """
        new_handle = bindlink(self._atomspace,
                              BindLink(
                                  VariableNode("$x"),
                                  EvaluationLink(
                                      PredicateNode("new_block"),
                                      VariableNode("$x")
                                  ),
                                  EvaluationLink(
                                      PredicateNode("new_block"),
                                      VariableNode("$x")
                                  )
                              ).h)
        new_atom = Atom(new_handle, self._atomspace)
        disappeared_handle = bindlink(self._atomspace,
                                      BindLink(
                                          VariableNode("$x"),
                                          EvaluationLink(
                                              PredicateNode("disappeared"),
                                              VariableNode("$x")
                                          ),
                                          EvaluationLink(
                                              PredicateNode("disappeared"),
                                              VariableNode("$x")
                                          )
                                      ).h)
        disappeared_atom = Atom(disappeared_handle, self._atomspace)
        all_eval_links = new_atom.out + disappeared_atom.out
        print "Found %s new blocks." % len(new_atom.out)
        print "Found %s disappeared blocks." % len(disappeared_atom.out)
        for eval_link in all_eval_links:
            # TODO: This next line needs to be more specific rather than just
            # selecting the first link.
            atom = eval_link.out[1]
            cur_sti = atom.av['sti']

            # TODO: Make the 200 a constant, this occurs one other place.
            self._atomspace.set_av(atom.h, sti=cur_sti + 200)
            self._atomspace.remove(eval_link)
        print len(self._atomspace.get_atoms_by_type(types.StructureNode)), " Structure Nodes in AtomSpace."
        for block in self._atomspace.get_atoms_by_type(types.StructureNode):
            cur_sti = block.av['sti']
            self._atomspace.set_av(
                block.h, sti=max(
                    cur_sti - 10, cur_sti / 1.36471))
示例#2
0
def init_factor_graph_concept_node():
    bind_link = BindLink(
        TypedVariableLink(VariableNode('$V'), TypeNode('ConceptNode')),
        EvaluationLink(GroundedPredicateNode('py: eval_has_dv'),
                       ListLink(VariableNode('$V'))),
        ExecutionOutputLink(
            GroundedSchemaNode('py: init_factor_graph_concept_node_formula'),
            ListLink(VariableNode('$V'))))
    bindlink(atomspace, bind_link)
示例#3
0
    def control_av_in_atomspace(self):
        """Called in the main loop to update av
        For now we control av in this way:
        if new block appeared or old block disappeared:
        (e.g. finding such atom structures
            EvaluationLink
                PredicateNode "new_block"
                StructureNode "objXX"
        )
            increase its av
            remove the new block/ disappeared predicate
        for all block:
            decrease their av
        """
        new_atom = bindlink(self._atomspace,
                              BindLink(
                                  VariableNode("$x"),
                                  EvaluationLink(
                                      PredicateNode("new_block"),
                                      VariableNode("$x")
                                  ),
                                  EvaluationLink(
                                      PredicateNode("new_block"),
                                      VariableNode("$x")
                                  )
                              ))
        disappeared_atom = bindlink(self._atomspace,
                                      BindLink(
                                          VariableNode("$x"),
                                          EvaluationLink(
                                              PredicateNode("disappeared"),
                                              VariableNode("$x")
                                          ),
                                          EvaluationLink(
                                              PredicateNode("disappeared"),
                                              VariableNode("$x")
                                          )
                                      ))
        all_eval_links = new_atom.out + disappeared_atom.out
        print "Found %s new blocks." % len(new_atom.out)
        print "Found %s disappeared blocks." % len(disappeared_atom.out)
        for eval_link in all_eval_links:
            # TODO: This next line needs to be more specific rather than just
            # selecting the first link.
            atom = eval_link.out[1]
            cur_sti = atom.av['sti']

            # TODO: Make the 200 a constant, this occurs one other place.
            self._atomspace.set_av(atom, sti=cur_sti + 200)
            self._atomspace.remove(eval_link)
        print len(self._atomspace.get_atoms_by_type(types.StructureNode)), " Structure Nodes in AtomSpace."
        for block in self._atomspace.get_atoms_by_type(types.StructureNode):
            cur_sti = block.av['sti']
            self._atomspace.set_av(
                block, sti=max(
                    cur_sti - 10, cur_sti / 1.36471))
 def control_av_in_atomspace(self):
     """Called in the main loop to update av
     For now we control av in this way:
     if new block appeared or old block disappeared:
     (e.g. finding such atom structures
         EvaluationLink
             PredicateNode "new_block"
             StructureNode "objXX"
     )
         increase its av
         remove the new block/ disappeared predicate
     for all block:
         decrease their av
     """
     new_handle = bindlink(self._atomspace,
                           BindLink(
                               VariableNode("$x"),
                               EvaluationLink(
                                   PredicateNode("new_block"),
                                   VariableNode("$x")
                               ),
                               EvaluationLink(
                                   PredicateNode("new_block"),
                                   VariableNode("$x")
                               )
                           ).h)
     new_atom = Atom(new_handle, self._atomspace)
     disappeared_handle = bindlink(self._atomspace,
                                   BindLink(
                                       VariableNode("$x"),
                                       EvaluationLink(
                                           PredicateNode("disappeared"),
                                           VariableNode("$x")
                                       ),
                                       EvaluationLink(
                                           PredicateNode("disappeared"),
                                           VariableNode("$x")
                                       )
                                   ).h)
     disappeared_atom = Atom(disappeared_handle, self._atomspace)
     all_eval_links = new_atom.out + disappeared_atom.out
     print "Found %s new blocks." % len(new_atom.out)
     print "Found %s disappeared blocks." % len(disappeared_atom.out)
     for eval_link in all_eval_links:
         atom = eval_link.out[1]
         cur_sti = atom.av['sti']
         #print cur_sti
         self._atomspace.set_av(atom.h, sti=cur_sti + 5)
         #print atom
         self._atomspace.remove(eval_link)
     print len(self._atomspace.get_atoms_by_type(types.StructureNode)), " Structure Nodes in AtomSpace."
     for block in self._atomspace.get_atoms_by_type(types.StructureNode):
         cur_sti = block.av['sti']
         self._atomspace.set_av(block.h, sti=cur_sti - 1)
示例#5
0
 def control_av_in_atomspace(self):
     """Called in the main loop to update av
     For now we control av in this way:
     if new block appeared or old block disappeared:
     (e.g. finding such atom structures
         EvaluationLink
             PredicateNode "new_block"
             StructureNode "objXX"
     )
         increase its av
         remove the new block/ disappeared predicate
     for all block:
         decrease their av
     """
     new_handle = bindlink(self._atomspace,
                           BindLink(
                               VariableNode("$x"),
                               EvaluationLink(
                                   PredicateNode("new_block"),
                                   VariableNode("$x")
                               ),
                               EvaluationLink(
                                   PredicateNode("new_block"),
                                   VariableNode("$x")
                               )
                           ).h)
     new_atom = Atom(new_handle, self._atomspace)
     disappeared_handle = bindlink(self._atomspace,
                                   BindLink(
                                       VariableNode("$x"),
                                       EvaluationLink(
                                           PredicateNode("disappeared"),
                                           VariableNode("$x")
                                       ),
                                       EvaluationLink(
                                           PredicateNode("disappeared"),
                                           VariableNode("$x")
                                       )
                                   ).h)
     disappeared_atom = Atom(disappeared_handle, self._atomspace)
     all_eval_links = new_atom.out + disappeared_atom.out
     for eval_link in all_eval_links:
         atom = eval_link.out[1]
         cur_sti = atom.av['sti']
         print cur_sti
         self._atomspace.set_av(atom.h, sti=cur_sti + 5)
         print atom
         self._atomspace.remove(eval_link)
     for block in self._atomspace.get_atoms_by_type(types.StructureNode):
         cur_sti = block.av['sti']
         self._atomspace.set_av(block.h, sti=cur_sti - 1)
         print block
示例#6
0
文件: bio.py 项目: stjordanis/agi-bio
    def get_members_of_old(self, geneset):
        """
        deprecated: using python instead of pattern matcher now b/c it's faster
        """
        # cache members of geneset
        if geneset not in self.set_members_dict:
            bindlink_query = \
                '''
                (BindLink
                    (VariableNode "$member")
                    (ImplicationLink
                        (MemberLink
                            (VariableNode "$member")
                            (ConceptNode {0}))
                        (VariableNode "$member")))
            '''.format('"' + geneset.name.strip() + '"')
            bindlink_h = scheme_eval_h(self.atomspace, bindlink_query)
            results_h = bindlink(self.a, bindlink_h)
            genes = self.set_members_dict[geneset] \
                = set(atoms_in_listlink_h(self.a, results_h))

            # or, using scheme (cog-bind) method
            # self.set_members_dict[geneset] = set(scheme_eval_list(
            #     self.a,'(get_members_of "' + geneset.name + '")'))
        else:
            genes = self.set_members_dict[geneset]
        return genes
示例#7
0
def get_predicate(atomspace, predicate_name, target_node, num_of_val):
    if num_of_val == 1:
        var = VariableNode("$x")
    elif num_of_val > 1:
        var_nodes = []
        for i in range(num_of_val):
            var_nodes.append(VariableNode(str(i)))
        var = VariableList(*var_nodes)
    else:
        return None
    result_set = bindlink(
        atomspace,
        BindLink(
            var,
            EvaluationLink(PredicateNode(predicate_name),
                           ListLink(target_node, var)), var))
    try:
        result_set_out = result_set.out[0]
        if result_set_out.type == types.ListLink:
            result_list = result_set_out.out
            return result_list
        else:
            return result_set_out
    except IndexError as e:
        print "get predicate err: get no result %s" % e
        return None
示例#8
0
文件: bio.py 项目: ceefour/agi-bio
    def get_members_of_old(self, geneset):
        """
        deprecated: using python instead of pattern matcher now b/c it's faster
        """
        # cache members of geneset
        if geneset not in self.set_members_dict:
            bindlink_query = \
                '''
                (BindLink
                    (VariableNode "$member")
                    (ImplicationLink
                        (MemberLink
                            (VariableNode "$member")
                            (ConceptNode {0}))
                        (VariableNode "$member")))
            '''.format('"' + geneset.name.strip() + '"')
            bindlink_h = scheme_eval_h(self.atomspace, bindlink_query)
            results_h = bindlink(self.a, bindlink_h)
            genes = self.set_members_dict[geneset] \
                = set(atoms_in_listlink_h(self.a, results_h))

            # or, using scheme (cog-bind) method
            # self.set_members_dict[geneset] = set(scheme_eval_list(
            #     self.a,'(get_members_of "' + geneset.name + '")'))
        else:
            genes = self.set_members_dict[geneset]
        return genes
def get_predicate(atomspace, predicate_name, target_node, num_of_val):
    if num_of_val == 1:
        var = VariableNode("$x")
    elif num_of_val > 1:        
        var_nodes = []
        for i in range(num_of_val):
            var_nodes.append(VariableNode(str(i)))
        var = VariableList(*var_nodes)
    else:
        return None
    result_set = bindlink(atomspace, 
                          BindLink(
                              var,
                              EvaluationLink(
                                  PredicateNode(predicate_name),
                                  ListLink(
                                      target_node,
                                      var
                                  )
                              ),
                              var
                          ).h
                      )
    try:
        result_set_out = Atom(result_set, atomspace).out[0]
        if atomspace.get_type(result_set_out.h) == types.ListLink:
            result_list = result_set_out.out
            return result_list
        else:
            return result_set_out
    except IndexError, e:
        print "get predicate err: get no result %s" % e
        return None        
示例#10
0
def show_edges():
    bind_link = BindLink(
        VariableList(
            TypedVariableLink(VariableNode('$F'), TypeNode('ConceptNode')),
            TypedVariableLink(VariableNode('$V'), TypeNode('ConceptNode'))),
        get_edge_predicate(VariableNode('$F'), VariableNode('$V')),
        get_edge_predicate(VariableNode('$F'), VariableNode('$V')))
    print(bindlink(atomspace, bind_link))
示例#11
0
 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 = bindlink.bindlink(self.atomspace, bind_link)
     answer = self.argmax(result)
     self.atomspace = popAtomspace(self.atomspace)
     return answer
示例#12
0
def init_factor_graph_implication_link():
    bind_link = BindLink(
        VariableList(
            TypedVariableLink(VariableNode('$V1'), TypeNode('ConceptNode')),
            TypedVariableLink(VariableNode('$V2'), TypeNode('ConceptNode'))),
        AndLink(
            # Preconditions
            EvaluationLink(
                GroundedPredicateNode('py: eval_has_dv'),
                ListLink(
                    ImplicationLink(VariableNode('$V1'),
                                    VariableNode('$V2')))),
            # Pattern clauses
            ImplicationLink(VariableNode('$V1'), VariableNode('$V2'))),
        ExecutionOutputLink(
            GroundedSchemaNode(
                'py: init_factor_graph_implication_link_formula'),
            ListLink(ImplicationLink(VariableNode('$V1'), VariableNode('$V2')),
                     VariableNode('$V1'), VariableNode('$V2'))))
    bindlink(atomspace, bind_link)
示例#13
0
def send_message_factor_variable():
    bind_link = BindLink(
        VariableList(
            TypedVariableLink(VariableNode('$F'), TypeNode('ConceptNode')),
            TypedVariableLink(VariableNode('$V'), TypeNode('ConceptNode'))),
        AndLink(
            NotLink(
                EvaluationLink(
                    GroundedPredicateNode('py: eval_has_value'),
                    ListLink(
                        get_edge_predicate(VariableNode('$F'),
                                           VariableNode('$V')),
                        MESSAGE_FACTOR_VARIABLE_KEY))),
            EvaluationLink(
                GroundedPredicateNode('py: can_send_message_factor_variable'),
                ListLink(VariableNode('$F'), VariableNode('$V'))),
            # Pattern clauses
            EvaluationLink(FACTOR_KEY, VariableNode('$F')),
            EvaluationLink(VARIABLE_KEY, VariableNode('$V')),
            get_edge_predicate(VariableNode('$F'), VariableNode('$V'))),
        ExecutionOutputLink(
            GroundedSchemaNode('py: send_message_factor_variable_formula'),
            ListLink(VariableNode('$F'), VariableNode('$V'))))
    bindlink(atomspace, bind_link)
def get_variable_domain(variable):
    # TBD: check also number of evidences

    bind_link = BindLink(
        VariableList(VariableNode("$type"), VariableNode("$value")),
        AndLink(InheritanceLink(variable, VariableNode("$type")),
                InheritanceLink(VariableNode("$type"),
                                VariableNode("$value"))),
        VariableNode("$value"))

    values_link = bindlink(atomspace, bind_link)
    values = list(map(lambda node: node.name, values_link.out))
    values.sort()

    return values
示例#15
0
    def test_bindlink(self):

        # Remember the starting atomspace size.
        starting_size = self.atomspace.size()

        # Run bindlink.
        atom = bindlink(self.atomspace, self.bindlink_atom)
        self.assertTrue(atom is not None and atom.value() > 0)

        # Check the ending atomspace size, it should have added one SetLink.
        ending_size = self.atomspace.size()
        self.assertEquals(ending_size, starting_size + 1)

        # The SetLink should have three items in it.
        self.assertEquals(atom.arity, 3)
        self.assertEquals(atom.type, types.SetLink)
示例#16
0
    def test_bindlink(self):

        # Remember the starting atomspace size.
        starting_size = self.atomspace.size()

        # Run bindlink.
        atom = bindlink(self.atomspace, self.bindlink_atom)
        self.assertTrue(atom is not None and atom.value() > 0)

        # Check the ending atomspace size, it should have added one SetLink.
        ending_size = self.atomspace.size()
        self.assertEquals(ending_size, starting_size + 1)

        # The SetLink should have three items in it.
        self.assertEquals(atom.arity, 3)
        self.assertEquals(atom.type, types.SetLink)
示例#17
0
def get_all_neighbors_variables(factor):
    """
    Find all variables which are connected with the given factor.
    This method is used for Factor tensor message multiplication to skip position
    of the variable the message is sent to.

    :param factor: factor in factor graph
    :return: the SetLink which contains a list of all variables connected to the factor.
    """
    bind_link = BindLink(
        VariableNode('$V'),
        AndLink(get_variable_predicate(VariableNode('$V')),
                get_edge_predicate(factor, VariableNode('$V'))),
        VariableNode('$V'))

    factors_link = bindlink(atomspace, bind_link)
    return factors_link
示例#18
0
def get_neighbors_factors(variable, exclude_factor):
    """
    Find all but exclude_factor factors which are connected with the given variable.

    :param variable: variable in factor graph
    :param exclude_factor: the factor that must must be excluded from the result.
    :return: the SetLink which contains a list of factors except the given factor.
    """
    bind_link = BindLink(
        VariableNode('$F'),
        AndLink(get_factor_predicate(VariableNode('$F')),
                get_edge_predicate(VariableNode('$F'), variable),
                NotLink(EqualLink(exclude_factor, VariableNode('$F')))),
        VariableNode('$F'))

    factors_link = bindlink(atomspace, bind_link)
    return factors_link
示例#19
0
def get_neighbors_variables(factor, exclude_variable):
    """
    Find all but exclude_variable variables which are connected with the given factor.

    :param factor: factor in factor graph
    :param exclude_variable: the variable that must must be excluded from the result.
    :return: the SetLink which contains a list of variables except the given variable.
    """
    bind_link = BindLink(
        VariableNode('$V'),
        AndLink(get_variable_predicate(VariableNode('$V')),
                get_edge_predicate(factor, VariableNode('$V')),
                NotLink(EqualLink(exclude_variable, VariableNode('$V')))),
        VariableNode('$V'))

    factors_link = bindlink(atomspace, bind_link)
    return factors_link
示例#20
0
    def test_bindlink(self):

        # Remember the starting atomspace size.
        starting_size = self.atomspace.size()

        # Run bindlink.
        result = bindlink(self.atomspace, self.bindlink_handle)
        self.assertTrue(result is not None and result.value() > 0)

        # Check the ending atomspace size, it should have added one ListLink.
        ending_size = self.atomspace.size()
        self.assertEquals(ending_size, starting_size + 1)

        # The ListLink should have three items in it.
        atom = self.atomspace[result]
        self.assertEquals(atom.arity, 3)
        self.assertEquals(atom.type, types.ListLink)
示例#21
0
# change the atomspace.
starting_size = atomspace.size()

# Run bindlink.
result = stub_bindlink(atomspace, bindlink_handle)
assert_true(result is not None and result.value() > 0)

# Check the ending atomspace size, it should be the same.
ending_size = atomspace.size()
assert_equals(ending_size, starting_size)

# Remember the starting atomspace size.
starting_size = atomspace.size()

# Run bindlink.
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"))))
示例#22
0
initialize_opencog(atomspace)

inp = InputModule(ConceptNode("image"), torch.tensor([1.]))
InheritanceLink(ConceptNode("red"), ConceptNode("color"))
InheritanceLink(ConceptNode("green"), ConceptNode("color"))
net1 = AttentionModule(ConceptNode("red"))
net2 = AttentionModule(ConceptNode("green"))

# direct execution proceeds as usual
print(net1(inp()))

# execution from Atomese
prog1 = net1.Exec(inp.Exec())
print(prog1)
print(get_cached_value(execute_atom(atomspace, prog1)))

prog2 = net2.Exec(inp.Exec())
print(get_cached_value(execute_atom(atomspace, prog2)))

bl = BindLink(
    #TypedVariableNode(VariableNode("$X"), TypeNode("ConceptNode")),
    VariableNode("$X"),
    AndLink(
        InheritanceLink(VariableNode("$X"), ConceptNode("color")),
        cogModule.Evaluate(
            VariableNode("$X"),
            inp.Exec())  #inp.Exec() == cogModule.Execute(ConceptNode("image"))
    ),
    VariableNode("$X"))
bindlink(atomspace, bl)
    def generate_action(self):
        """ generate and execute the action by behavior tree

        Now (20150822) we generate action by such a behavior tree:

        If target block found in atomspace:
            If target block is attractive(sti is large enough):
                move to the near place of the target block
        else:
            moving 2 units toward yaw = 90 degree

        For testing, we set a target block(gold, which block id is 14)
        And we assume the world is superflat world so we only need to move on
        x-y direction.
        Note that because the behavior of GSN/GPN,
        we have to import all schemas(action_schemas.py)
        in the main script(opencog_initializer.py).
        Or it will fail to find the function name.

        TODO:
            Build random action function: It's for the 'else' part
                in above behavior tree. This will make the bot behaves more
                naturally.
            Add pathfinding technique: so the bot can calculate the procedure to
                get to the destination.
                it will be able to move to any place he wants.
                (ex. place block to jump to a higher place)
                In Opencog there has been an OCPlanner implementation.
                It should be possible to migrate the old code.
            More higher level ways to making decision: For now it's just testing
                so we only use a simple behavior tree to demo. But in general,
                we should regard these behavior tree as lower level schemas.
                And we should use a higher level cognition ways(e.g. OpenPsi)
                to decide what behavior tree we want to execute.
        """
        result = bindlink(self._atomspace,
                          BindLink(
                              VariableNode("$block"),
                              AndLink(
                                  EvaluationLink(
                                      PredicateNode("material"),
                                      ListLink(
                                          VariableNode("$block"),
                                          ConceptNode("14")
                                      )
                                  ),
                                  EvaluationLink(
                                      GroundedPredicateNode("py: action_schemas.is_attractive"),
                                      ListLink(
                                          VariableNode("$block")
                                      )
                                  ),
                                  EvaluationLink(
                                      GroundedPredicateNode("py: action_schemas.move_toward_block"),
                                      ListLink(
                                          VariableNode("$block")

                                      )
                                  )
                              ),
                              VariableNode("$block")
                          ).h
                      )
        print "action_gen: result", Atom(result, self._atomspace)
        
        if self._atomspace.get_outgoing(result) == []:
            print "action_gen: no result, random walk."

            evaluate_atom(self._atomspace,
                             EvaluationLink(
                                 GroundedPredicateNode("py: action_schemas.set_relative_move"),
                                 ListLink(
                                     NumberNode("90"),
                                     NumberNode("2"),
                                     ConceptNode("jump")
                                 )
                             )
                         )

        print "action_gen end"
示例#24
0
    def generate_action(self):
        # TODO: This documantation is outdated.
        """ generate and execute the action by behavior tree

        Now (20150822) we generate action by such a behavior tree:

        If target block found in atomspace:
            If target block is attractive(sti is large enough):
                move to the near place of the target block
        else:
            moving 2 units toward yaw = 90 degree

        For testing, we set a target block(gold, which block id is 14)
        And we assume the world is superflat world so we only need to move on
        x-y direction.
        Note that because the behavior of GSN/GPN,
        we have to import all schemas(action_schemas.py)
        in the main script(opencog_initializer.py).
        Or it will fail to find the function name.

        TODO:
            Build random action function: It's for the 'else' part
                in above behavior tree. This will make the bot behaves more
                naturally.
            Add pathfinding technique: so the bot can calculate the procedure to
                get to the destination.
                it will be able to move to any place he wants.
                (ex. place block to jump to a higher place)
                In Opencog there has been an OCPlanner implementation.
                It should be possible to migrate the old code.
            More higher level ways to making decision: For now it's just testing
                so we only use a simple behavior tree to demo. But in general,
                we should regard these behavior tree as lower level schemas.
                And we should use a higher level cognition ways(e.g. OpenPsi)
                to decide what behavior tree we want to execute.
        """

        # The goal_sucess_rate represents how well a given strategy is working
        # toward achieving the success of the overall goal it is trying to
        # achieve.  This sucess rate defaults to 0 here, and during the main
        # goal execution the result is something that is furthering the goal
        # then it can set this to a higher value.  The more successful we are
        # in satisfying a certain goal, the more likely we are to continue
        # doing this thing, i.e. if we are in the process of doing something
        # that takes time and are making progress, don't switch to some other
        # goal right in the middle of that.
        goal_success_rate = 0.0

        # Read the current goal from atomspace
        goal = bindlink(
            self._atomspace,
            BindLink(
                VariableList(
                    TypedVariableLink(VariableNode("$goal"),
                                      TypeNode("ConceptNode")), ),
                Link(ConceptNode("CURRENT_GOAL"), VariableNode("$goal")),
                VariableNode("$goal")))

        goal_name = goal.out[0].name
        print "goal_name: ", goal_name

        #######################################################################
        #                           Main Action Tree
        #######################################################################
        # This if - elif chain is the main action generation code for the bot.
        # The chain of if statements here branches off of the currently
        # selected goal.  Inside each if block is code which should further
        # advance that particular goal for the bot.  So for example, on the
        # gather resources goal, the code looks through the bot's memory for
        # blocks which are wood/ore/etc and then travels to one of them and
        # mines it out.
        if goal_name == "Gather resources":
            print "action_gen: gather resources."
            # Find resources:
            # This bindlink looks through all of the blocks currently in the bot's
            # memory about the world and returns a list of all the ones that are
            # just the base wood type (i.e. what trees are made out of, not planks,
            # slabs, buttons, etc).
            result = bindlink(
                self._atomspace,
                BindLink(
                    VariableList(
                        TypedVariableLink(VariableNode("$block"),
                                          TypeNode("StructureNode")),
                        TypedVariableLink(VariableNode("$material"),
                                          TypeNode("ConceptNode")),
                    ),
                    AndLink(
                        EvaluationLink(
                            PredicateNode("material"),
                            ListLink(VariableNode("$block"),
                                     VariableNode("$material"))),
                        EvaluationLink(
                            PredicateNode("be"),
                            ListLink(VariableNode("$material"),
                                     ConceptNode("WOOD_BLOCK"))),
                        EvaluationLink(
                            GroundedPredicateNode(
                                "py: action_schemas.is_attractive"),
                            ListLink(VariableNode("$block"))),
                        EvaluationLink(
                            GroundedPredicateNode(
                                "py: action_schemas.dig_block"),
                            ListLink(VariableNode("$block")))),
                    VariableNode("$block")))
            print "action_gen: result", result

            # If we sucessfully mined out a block of wood we have been very
            # successful in fulfilling this goal and should continue to try to
            # mine more unless something else really urgent comes up.  If we
            # failed, then we should try to find something else to do.
            if result.out != []:
                goal_success_rate = 5.0
            else:
                goal_success_rate = -5.0

        elif goal_name == "Explore":
            print "action_gen: random walk."

            # Random walk:
            # Choose a random direction and walk a short distance in that direction and
            # either execute a normal walk or a walk + jump in that direction.
            evaluate_atom(
                self._atomspace,
                EvaluationLink(
                    GroundedPredicateNode(
                        "py: action_schemas.set_relative_move"),
                    ListLink(
                        RandomChoiceLink(
                            NumberNode("0"),
                            NumberNode("45"),
                            NumberNode("90"),
                            NumberNode("135"),
                            NumberNode("180"),
                            NumberNode("225"),
                            NumberNode("270"),
                            NumberNode("315"),
                        ),
                        RandomChoiceLink(
                            NumberNode("1"),
                            NumberNode("2"),
                            NumberNode("3"),
                            NumberNode("4"),
                        ), ConceptNode("jump"))))

            goal_success_rate = 1.0

        elif goal_name == "Look around":
            print "action_gen: look around."

            # Random walk:
            # Choose a random direction and walk 1 block in that direction and
            # either execute a normal walk or a walk + jump in that direction.
            evaluate_atom(
                self._atomspace,
                EvaluationLink(
                    GroundedPredicateNode(
                        "py: action_schemas.set_relative_look"),
                    ListLink(
                        RandomChoiceLink(
                            NumberNode("0"),
                            NumberNode("90"),
                            NumberNode("180"),
                            NumberNode("270"),
                        ), NumberNode("0"))))

            goal_success_rate = 0.5

        else:
            # If we got here then there was no handler coded yet for the
            # currently selected goal.  Return a very negative
            # goal_success_rate so that we switch to another goal since
            # standing around doing nothing is not productive.
            goal_success_rate = -20.0

        # Decide whether or not we should change the current goal, or if we
        # should keep doing the same thing in the next time step.
        print "It has been %s time steps since the goal was changed." % self.steps_since_goal_change

        # Make it more and more likely to change the current goal depending on
        # how long we have been on the current goal.
        if random.normalvariate(0.0, 1.0) >= 1.5 - 0.1 * \
                self.steps_since_goal_change + 0.1 * goal_success_rate:
            print "\n\n\n\t\t\tChanging current goal\n\n\n"
            self.steps_since_goal_change = 1

            # Get the full list of all the goals in the atomspace
            goal_atoms = bindlink(
                self._atomspace,
                BindLink(
                    TypedVariableLink(VariableNode("$goal"),
                                      TypeNode("ConceptNode")),
                    EvaluationLink(
                        PredicateNode("be"),
                        ListLink(ConceptNode("GOAL"), VariableNode("$goal")),
                    ), VariableNode("$goal")))

            # print "All goals: ", goal_atoms_list
            goal_atoms_list = goal_atoms.out

            # TODO: This should be done in atomese.
            random_goal = goal_atoms_list[random.randint(
                0,
                len(goal_atoms_list) - 1)]
            print "Random goal: ", random_goal

            # delete the existing CURRENT_GOAL link and then
            # create a new one pointing to the newly chosen goal.
            self._atomspace.remove(
                Link(ConceptNode("CURRENT_GOAL"), ConceptNode(goal_name)))
            self._atomspace.add_link(
                types.Link, (ConceptNode("CURRENT_GOAL"), random_goal))
        else:
            self.steps_since_goal_change += 1

        print "action_gen end"
    def generate_action(self):
        """ generate and execute the action by behavior tree

        Now (20150822) we generate action by such a behavior tree:

        If target block found in atomspace:
            If target block is attractive(sti is large enough):
                move to the near place of the target block
        else:
            moving 2 units toward yaw = 90 degree

        For testing, we set a target block(gold, which block id is 14)
        And we assume the world is superflat world so we only need to move on
        x-y direction.
        Note that because the behavior of GSN/GPN,
        we have to import all schemas(action_schemas.py)
        in the main script(opencog_initializer.py).
        Or it will fail to find the function name.

        TODO:
            Build random action function: It's for the 'else' part
                in above behavior tree. This will make the bot behaves more
                naturally.
            Add pathfinding technique: so the bot can calculate the procedure to
                get to the destination.
                it will be able to move to any place he wants.
                (ex. place block to jump to a higher place)
                In Opencog there has been an OCPlanner implementation.
                It should be possible to migrate the old code.
            More higher level ways to making decision: For now it's just testing
                so we only use a simple behavior tree to demo. But in general,
                we should regard these behavior tree as lower level schemas.
                And we should use a higher level cognition ways(e.g. OpenPsi)
                to decide what behavior tree we want to execute.
        """

        result = bindlink(self._atomspace,
                          BindLink(
                              VariableList(
                                  TypedVariableLink(
                                      VariableNode("$block"),
                                      TypeNode("StructureNode")
                                  ),
                                  TypedVariableLink(
                                      VariableNode("$material"),
                                      TypeNode("ConceptNode")
                                  ),
                              ),

                              AndLink(
                                  EvaluationLink(
                                      PredicateNode("material"),
                                      ListLink(
                                          VariableNode("$block"),
                                          VariableNode("$material")
                                      )
                                  ),
                                  EvaluationLink(
                                      PredicateNode("be"),
                                      ListLink(
                                          VariableNode("$material"),
                                          ConceptNode("WOOD_BLOCK")
                                      )
                                  ),
                                  EvaluationLink(
                                     GroundedPredicateNode("py: action_schemas.is_attractive"),
                                     ListLink(
                                        VariableNode("$block")
                                     )
                                  ),
                                  EvaluationLink(
                                      GroundedPredicateNode("py: action_schemas.dig_block"),
                                      ListLink(
                                          VariableNode("$block")
                                      )
                                  )
                              ),
                              VariableNode("$block")
                          ).h
                      )
        print "action_gen: result", Atom(result, self._atomspace)

        if self._atomspace.get_outgoing(result) == []:
            print "action_gen: no result, random walk."

            evaluate_atom(self._atomspace,
                             EvaluationLink(
                                 GroundedPredicateNode("py: action_schemas.set_relative_move"),
                                 ListLink(
                                     RandomChoiceLink(
                                         NumberNode("0"),
                                         NumberNode("90"),
                                         NumberNode("180"),
                                         NumberNode("270"),
                                         ),
                                     NumberNode("1"),
                                     ConceptNode("jump")
                                 )
                             )
                         )

        print "action_gen end"
示例#26
0
def test_bind(atomspace, prep_atom):
    n = 10000
    for i in xrange(n):
        result = bindlink(atomspace, prep_atom)
    return n
示例#27
0
 def test_bindlink(self):
     atom = bindlink(self.atomspace, self.bindlink_atom)
     self._check_result_setlink(atom, 3)
示例#28
0
 def test_bindlink(self):
     atom = bindlink(self.atomspace, self.bindlink_atom)
     self._check_result_setlink(atom, 3)
示例#29
0
# change the atomspace.
starting_size = atomspace.size()

# Run bindlink.
result = stub_bindlink(atomspace, bindlink_atom)
assert_true(result is not None)

# Check the ending atomspace size, it should be the same.
ending_size = atomspace.size()
assert_equals(ending_size, starting_size)

# Remember the starting atomspace size.
starting_size = atomspace.size()

# Run bindlink.
result = bindlink(atomspace, bindlink_atom)
assert_true(result is not None)

# 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.
assert_equals(result.arity, 3)
assert_equals(result.type, types.SetLink)

result = execute_atom(atomspace, 
        ExecutionOutputLink( 
            GroundedSchemaNode("py: add_link"),
            ListLink(
                ConceptNode("one"),
示例#30
0
def test_bind(atomspace, prep_atom):
    n = 10000
    for i in xrange(n):
        result = bindlink(atomspace, prep_atom)
    return n
示例#31
0
# change the atomspace.
starting_size = atomspace.size()

# Run bindlink.
result = stub_bindlink(atomspace, bindlink_atom)
assert_true(result is not None)

# Check the ending atomspace size, it should be the same.
ending_size = atomspace.size()
assert_equals(ending_size, starting_size)

# Remember the starting atomspace size.
starting_size = atomspace.size()

# Run bindlink.
result = bindlink(atomspace, bindlink_atom)
assert_true(result is not None)

# 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.
assert_equals(result.arity, 3)
assert_equals(result.type, types.SetLink)

result = execute_atom(
    atomspace,
    ExecutionOutputLink(GroundedSchemaNode("py: add_link"),
                        ListLink(ConceptNode("one"), ConceptNode("two"))))
list_link = ListLink(ConceptNode("one"), ConceptNode("two"))
示例#32
0
    def generate_action(self):
        # TODO: This documantation is outdated.
        """ generate and execute the action by behavior tree

        Now (20150822) we generate action by such a behavior tree:

        If target block found in atomspace:
            If target block is attractive(sti is large enough):
                move to the near place of the target block
        else:
            moving 2 units toward yaw = 90 degree

        For testing, we set a target block(gold, which block id is 14)
        And we assume the world is superflat world so we only need to move on
        x-y direction.
        Note that because the behavior of GSN/GPN,
        we have to import all schemas(action_schemas.py)
        in the main script(opencog_initializer.py).
        Or it will fail to find the function name.

        TODO:
            Build random action function: It's for the 'else' part
                in above behavior tree. This will make the bot behaves more
                naturally.
            Add pathfinding technique: so the bot can calculate the procedure to
                get to the destination.
                it will be able to move to any place he wants.
                (ex. place block to jump to a higher place)
                In Opencog there has been an OCPlanner implementation.
                It should be possible to migrate the old code.
            More higher level ways to making decision: For now it's just testing
                so we only use a simple behavior tree to demo. But in general,
                we should regard these behavior tree as lower level schemas.
                And we should use a higher level cognition ways(e.g. OpenPsi)
                to decide what behavior tree we want to execute.
        """

        # The goal_sucess_rate represents how well a given strategy is working
        # toward achieving the success of the overall goal it is trying to
        # achieve.  This sucess rate defaults to 0 here, and during the main
        # goal execution the result is something that is furthering the goal
        # then it can set this to a higher value.  The more successful we are
        # in satisfying a certain goal, the more likely we are to continue
        # doing this thing, i.e. if we are in the process of doing something
        # that takes time and are making progress, don't switch to some other
        # goal right in the middle of that.
        goal_success_rate = 0.0

        # Read the current goal from atomspace
        goal = bindlink(self._atomspace,
                        BindLink(
                            VariableList(
                                TypedVariableLink(
                                    VariableNode("$goal"),
                                    TypeNode("ConceptNode")
                                ),
                            ),

                            Link(
                                ConceptNode("CURRENT_GOAL"),
                                VariableNode("$goal")
                            ),
                            VariableNode("$goal")
                        )
                        )

        goal_name = goal.out[0].name
        print "goal_name: ", goal_name

        #######################################################################
        #                           Main Action Tree
        #######################################################################
        # This if - elif chain is the main action generation code for the bot.
        # The chain of if statements here branches off of the currently
        # selected goal.  Inside each if block is code which should further
        # advance that particular goal for the bot.  So for example, on the
        # gather resources goal, the code looks through the bot's memory for
        # blocks which are wood/ore/etc and then travels to one of them and
        # mines it out.
        if goal_name == "Gather resources":
            print "action_gen: gather resources."
            # Find resources:
            # This bindlink looks through all of the blocks currently in the bot's
            # memory about the world and returns a list of all the ones that are
            # just the base wood type (i.e. what trees are made out of, not planks,
            # slabs, buttons, etc).
            result = bindlink(self._atomspace,
                              BindLink(
                                  VariableList(
                                      TypedVariableLink(
                                          VariableNode("$block"),
                                          TypeNode("StructureNode")
                                      ),
                                      TypedVariableLink(
                                          VariableNode("$material"),
                                          TypeNode("ConceptNode")
                                      ),
                                  ),

                                  AndLink(
                                      EvaluationLink(
                                          PredicateNode("material"),
                                          ListLink(
                                              VariableNode("$block"),
                                              VariableNode("$material")
                                          )
                                      ),
                                      EvaluationLink(
                                          PredicateNode("be"),
                                          ListLink(
                                              VariableNode("$material"),
                                              ConceptNode("WOOD_BLOCK")
                                          )
                                      ),
                                      EvaluationLink(
                                          GroundedPredicateNode(
                                              "py: action_schemas.is_attractive"),
                                          ListLink(
                                              VariableNode("$block")
                                          )
                                      ),
                                      EvaluationLink(
                                          GroundedPredicateNode(
                                              "py: action_schemas.dig_block"),
                                          ListLink(
                                              VariableNode("$block")
                                          )
                                      )
                                  ),
                                  VariableNode("$block")
                              )
                              )
            print "action_gen: result", result

            # If we sucessfully mined out a block of wood we have been very
            # successful in fulfilling this goal and should continue to try to
            # mine more unless something else really urgent comes up.  If we
            # failed, then we should try to find something else to do.
            if result.out != []:
                goal_success_rate = 5.0
            else:
                goal_success_rate = -5.0

        elif goal_name == "Explore":
            print "action_gen: random walk."

            # Random walk:
            # Choose a random direction and walk a short distance in that direction and
            # either execute a normal walk or a walk + jump in that direction.
            evaluate_atom(self._atomspace,
                          EvaluationLink(
                              GroundedPredicateNode(
                                  "py: action_schemas.set_relative_move"),
                              ListLink(
                                  RandomChoiceLink(
                                      NumberNode("0"),
                                      NumberNode("45"),
                                      NumberNode("90"),
                                      NumberNode("135"),
                                      NumberNode("180"),
                                      NumberNode("225"),
                                      NumberNode("270"),
                                      NumberNode("315"),
                                  ),
                                  RandomChoiceLink(
                                      NumberNode("1"),
                                      NumberNode("2"),
                                      NumberNode("3"),
                                      NumberNode("4"),
                                  ),
                                  ConceptNode("jump")
                              )
                          )
                          )

            goal_success_rate = 1.0

        elif goal_name == "Look around":
            print "action_gen: look around."

            # Random walk:
            # Choose a random direction and walk 1 block in that direction and
            # either execute a normal walk or a walk + jump in that direction.
            evaluate_atom(self._atomspace,
                          EvaluationLink(
                              GroundedPredicateNode(
                                  "py: action_schemas.set_relative_look"),
                              ListLink(
                                  RandomChoiceLink(
                                      NumberNode("0"),
                                      NumberNode("90"),
                                      NumberNode("180"),
                                      NumberNode("270"),
                                  ),
                                  NumberNode("0")
                              )
                          )
                          )

            goal_success_rate = 0.5

        else:
            # If we got here then there was no handler coded yet for the
            # currently selected goal.  Return a very negative
            # goal_success_rate so that we switch to another goal since
            # standing around doing nothing is not productive.
            goal_success_rate = -20.0

        # Decide whether or not we should change the current goal, or if we
        # should keep doing the same thing in the next time step.
        print "It has been %s time steps since the goal was changed." % self.steps_since_goal_change

        # Make it more and more likely to change the current goal depending on
        # how long we have been on the current goal.
        if random.normalvariate(0.0, 1.0) >= 1.5 - 0.1 * \
                self.steps_since_goal_change + 0.1 * goal_success_rate:
            print "\n\n\n\t\t\tChanging current goal\n\n\n"
            self.steps_since_goal_change = 1

            # Get the full list of all the goals in the atomspace
            goal_atoms = bindlink(self._atomspace,
                                  BindLink(
                                      TypedVariableLink(
                                          VariableNode("$goal"),
                                          TypeNode("ConceptNode")
                                      ),
                                      EvaluationLink(
                                          PredicateNode("be"),
                                          ListLink(
                                              ConceptNode("GOAL"),
                                              VariableNode("$goal")
                                          ),
                                      ),
                                      VariableNode("$goal")
                                  ))

            # print "All goals: ", goal_atoms_list
            goal_atoms_list = goal_atoms.out

            # TODO: This should be done in atomese.
            random_goal = goal_atoms_list[
                random.randint(0, len(goal_atoms_list) - 1)]
            print "Random goal: ", random_goal

            # delete the existing CURRENT_GOAL link and then
            # create a new one pointing to the newly chosen goal.
            self._atomspace.remove(
                Link(
                    ConceptNode("CURRENT_GOAL"),
                    ConceptNode(goal_name)))
            self._atomspace.add_link(
                types.Link, (ConceptNode("CURRENT_GOAL"), random_goal))
        else:
            self.steps_since_goal_change += 1

        print "action_gen end"
示例#33
0
# change the atomspace.
starting_size = atomspace.size()

# Run bindlink.
result = stub_bindlink(atomspace, bindlink_handle)
assert_true(result is not None and result.value() > 0)

# Check the ending atomspace size, it should be the same.
ending_size = atomspace.size()
assert_equals(ending_size, starting_size)

# Remember the starting atomspace size.
starting_size = atomspace.size()

# Run bindlink.
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(
示例#34
0
print(get_cached_value(execute_atom(atomspace, prog1)))

prog2 = net2.execute(inp.execute())
print(get_cached_value(execute_atom(atomspace, prog2)))

bl = BindLink(
    TypedVariableLink(VariableNode("$X"), TypeNode("ConceptNode")),
    #VariableNode("$X"),
    AndLink(
        InheritanceLink(VariableNode("$X"), ConceptNode("color")),
        evaluate(
            VariableNode("$X"),
            inp.execute())  #inp.execution() == execute(ConceptNode("image"))
    ),
    VariableNode("$X"))
print(bindlink(atomspace, bl))

# ----------------


# wrapping torch.tensor tv to make it trainable
# class TensorTVModule(cogModule):
class InheritanceModule(CogModule):
    def __init__(self, atom, init_tv):
        super().__init__(atom)
        self.tv = init_tv

    def forward(self):
        return self.tv