Ejemplo n.º 1
0
    def put(self, id):
        """
        Updates the AttentionValue (STI, LTI, VLTI) or TruthValue of an atom
        """

        # If the atom is not found in the atomspace.
        if not Atom(id, self.atomspace):
            abort(404, 'Atom not found')

        # Prepare the atom data
        data = reqparse.request.get_json()

        if 'truthvalue' not in data and 'attentionvalue' not in data:
            abort(
                400, 'Invalid request: you must include a truthvalue or '
                'attentionvalue parameter')

        if 'truthvalue' in data:
            tv = ParseTruthValue.parse(data)
            Atom(id, self.atomspace).tv = tv

        if 'attentionvalue' in data:
            (sti, lti, vlti) = ParseAttentionValue.parse(data)
            Atom(id, self.atomspace).av = {
                'sti': sti,
                'lti': lti,
                'vlti': vlti
            }

        atom = self.atomspace.get_atom_with_uuid(id)
        return {'atoms': marshal(atom, atom_fields)}
Ejemplo n.º 2
0
    def put(self, id):
        """
        Updates the AttentionValue (STI, LTI, VLTI) or TruthValue of an atom
        """

        if Atom(id) not in self.atomspace:
            abort(404, 'Atom not found')

        # Prepare the atom data
        data = reqparse.request.get_json()

        if 'truthvalue' not in data and 'attentionvalue' not in data:
            abort(
                400, 'Invalid request: you must include a truthvalue or '
                'attentionvalue parameter')

        if 'truthvalue' in data:
            tv = ParseTruthValue.parse(data)
            self.atomspace.set_tv(h=Atom(id), tv=tv)

        if 'attentionvalue' in data:
            (sti, lti, vlti) = ParseAttentionValue.parse(data)
            self.atomspace.set_av(h=Atom(id), sti=sti, lti=lti, vlti=vlti)

        atom = self.atomspace.get_atom_with_uuid(id)
        return {'atoms': marshal(atom, atom_fields)}
Ejemplo n.º 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_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
Ejemplo n.º 4
0
 def handle_vision_message(self, data):
     print "handle_visiion_message"
     #TODO: In Minecraft the up/down direction is y coord
     # but we should swap y and z in ros node, not here..
     for block in data.blocks:
         swap_y_and_z(block)
     map_handle, cur_map = self._get_map()
     for block in data.blocks:
         old_block_handle = cur_map.get_block((block.x, block.y, block.z))
         updated_eval_links = []
         if old_block_handle.is_undefined():
             blocknode, updated_eval_links = self._build_block_nodes(
                 block, map_handle)
         else:
             old_block_type_node = get_predicate(
                 self._atomspace, "material",
                 Atom(old_block_handle, self._atomspace), 1)
             old_block_type = self._atomspace.get_name(
                 old_block_type_node.h)
             if old_block_type == str(block.blockid):
                 continue
             elif block.blockid == 0:
                 blocknode, updated_eval_links = Atom(
                     Handle(-1), self._atomspace), []
             else:
                 blocknode, updated_eval_links = self._build_block_nodes(
                     block, map_handle)
             #TODO: not sure if we should add disappeared predicate here,
             #It looks reasonable but make the code more messy..
             disappeared_link = add_predicate(
                 self._atomspace, "disappeared",
                 Atom(old_block_handle, self._atomspace))
             updated_eval_links.append(disappeared_link)
         self._space_server.add_map_info(blocknode.h, map_handle, False,
                                         False, block.ROStimestamp, block.x,
                                         block.y, block.z)
         if old_block_handle.is_undefined():
             self._time_server.add_time_info(blocknode.h,
                                             block.ROStimestamp, "ROS")
             self._time_server.add_time_info(blocknode.h, block.MCtimestamp,
                                             "MC")
         for link in updated_eval_links:
             self._time_server.add_time_info(link.h, block.ROStimestamp,
                                             "ROS")
             self._time_server.add_time_info(link.h, block.MCtimestamp,
                                             "MC")
         #print blocknode
         #print updated_eval_links
     print "handle_vision_message end"
    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))
Ejemplo n.º 6
0
    def outputLinkArgumentEdges(self, a, outgoing=None):
        assert a.is_link()
        # assumes outgoing links/nodes have already been output

        if outgoing == None:
            outgoing = a.out

        try:
            a_id = self.handle2id[a.h.value()]

            output = ''
            for i in xrange(0, len(outgoing)):
                #outi = outgoing[i]
                outi_id = self.handle2id[outgoing[i].h.value()]

                if a.is_a(t.OrderedLink):
                    output += 'd %s %s "%s"\n' % (str(a_id), str(outi_id),
                                                  str(i))
                else:
                    output += 'u %s %s "%s"\n' % (str(a_id), str(outi_id),
                                                  str(i))
        except KeyError, e:
            print "%% Processing", str(
                a
            ), "!!! Error - did not previously output the vertex for this link:", str(
                Atom(Handle(e.args[0]), self._as))
Ejemplo n.º 7
0
    def test_unifier(self):
        h = scheme_eval_h(self.space, "cap-deduce")
        self.assertTrue(h)
        print "\nThe question is:"
        print h
        question = Atom(h, self.space)
        print question

        h = scheme_eval_h(self.space, "(cog-bind cap-deduce)")
        self.assertTrue(h)
        print h
        answer = Atom(h, self.space)
        print "\nThe answer is:"
        print answer
        self.assertEqual(answer.type, types.SetLink)
        self.assertEqual(answer.arity, 2)
Ejemplo n.º 8
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).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
Ejemplo n.º 9
0
def tree_with_real_atoms(tr, a):
    #if isinstance(tr.op, Atom):
    if isinstance(tr.op, FakeAtom):
        return Atom(Handle(tr.op._handle_value), a)
    elif tr.is_leaf():
        return tr
    else:
        return Tree(tr.op,
                    [tree_with_real_atoms(child, a) for child in tr.args])
Ejemplo n.º 10
0
def test_add_connected(atomspace, prep_atom):
    """Add n nodes and create a complete (fully-connected) graph in atomspace
    and returns the number of items processed
    """
    n = 1000
    offset = atomspace.add_node(types.ConceptNode, "Starting handle offset")
    offset = offset.value()

    for i in xrange(1, n + 1):
        atomspace.add_node(types.ConceptNode, str(i), TruthValue(.5, .5))
        for j in xrange(1, i):
            # atomspace.add_link(types.HebbianLink,
            atomspace.add_link(
                types.AssociativeLink,
                [Atom(i + offset, atomspace),
                 Atom(j + offset, atomspace)], TruthValue(.2, .3))

    # Number of vertices plus number of edges in a fully connected graph
    return n + (n**2 - n) / 2
Ejemplo n.º 11
0
    def post(self):
        """
        Creates a new atom. If the atom already exists, it updates the atom.
        """

        # Prepare the atom data and validate it
        data = reqparse.request.get_json()

        if 'type' in data:
            if data['type'] in types.__dict__:
                type = types.__dict__.get(data['type'])
            else:
                abort(
                    400, 'Invalid request: type \'' + type + '\' is not a '
                    'valid type')
        else:
            abort(400, 'Invalid request: required parameter type is missing')

        # TruthValue
        tv = ParseTruthValue.parse(data)

        # Outgoing set
        if 'outgoing' in data:
            print data
            if len(data['outgoing']) > 0:
                outgoing = [
                    Atom(uuid, self.atomspace) for uuid in data['outgoing']
                ]
        else:
            outgoing = None

        # Name
        name = data['name'] if 'name' in data else None

        # Nodes must have names
        if is_a(type, types.Node):
            if name is None:
                abort(
                    400, 'Invalid request: node type specified and required '
                    'parameter name is missing')
        # Links can't have names
        else:
            if name is not None:
                abort(
                    400, 'Invalid request: parameter name is not allowed for '
                    'link types')

        try:
            atom = self.atomspace.add(t=type, name=name, tv=tv, out=outgoing)
        except TypeError:
            abort(
                500, 'Error while processing your request. Check your '
                'parameters.')

        return {'atoms': marshal(atom, atom_fields)}
Ejemplo n.º 12
0
    def test_c_eval(self):
        basic = scheme_eval_h(self.space,
                              "(ConceptNode \"whatever\" (stv 0.5 0.5))")

        a1 = self.space.add_node(types.ConceptNode, "whatever")
        self.assertTrue(a1)

        # Make sure the truth value is what's in the SCM file.
        expected = TruthValue(0.5, 0.5)
        self.assertEquals(a1.tv, expected)

        # Actually, the atoms overall should compare.
        # print "eq", Atom(basic, self.space) == a1
        self.assertEquals(a1, Atom(basic, self.space))

        # Do it again, from a define in the scm file.
        again = scheme_eval_h(self.space, "wobbly")
        a2 = self.space.add_node(types.ConceptNode, "wobbly")
        self.assertTrue(a2)
        self.assertEquals(a2, Atom(again, self.space))
Ejemplo n.º 13
0
    def test_unifier(self):

        status = load_scm(self.space, "opencog/scm/opencog/query.scm")
        self.assertTrue(status)

        scheme_eval(self.space, "(use-modules (opencog query))")
        h = scheme_eval_h(self.space, "find-animals")
        self.assertTrue(h)
        print "\nThe question is:"
        print h
        question = Atom(h, self.space)
        print question

        h = scheme_eval_h(self.space, "(cog-bind find-animals)")
        self.assertTrue(h)
        print h
        answer = Atom(h, self.space)
        print "\nThe answer is:"
        print answer
        self.assertEqual(answer.type, types.SetLink)
        self.assertEqual(answer.arity, 3)
Ejemplo n.º 14
0
def run_pln_example(a, f):
    a.clear()

    testdir = '../tests/reasoning/pln/targets/'
    datadirs = ['../tests/reasoning/pln/scm/', '../opencog/']
    fname = testdir + f
    config = ConfigParser.ConfigParser()
    read_files = config.read(fname)

    if not read_files:
        raise Exception("no such file:", fname)

    def get(field):
        return config.get('PLN_TEST', field)

    def get_list(field):
        return get(field).replace(' ', '').split(',')

    print f

    def load_axioms(fname):
        for d in datadirs:
            kf = d + fname + '.scm'
            try:
                tmp = open(kf, 'r')
                scheme_wrapper.load_scm(a, kf)
                print kf
                return
            except IOError:
                continue
        raise IOError("missing data file: " + kf)

    data_files = get_list('load')
    for fname in data_files:
        load_axioms(fname)
    scm_target = '(cog-handle %s)' % (get('target'), )
    print scm_target
    handle_str = scheme_wrapper.scheme_eval(scm_target)
    try:
        h = int(handle_str)
    except ValueError:
        print handle_str
        raise Exception("Scheme error in target")

    nsteps = int(get('max_steps'))

    target = Atom(Handle(h), a)

    try:
        rule_names = get_list('allowed_rules')
    except ConfigParser.NoOptionError, e:
        rule_names = []
Ejemplo n.º 15
0
    def delete(self, id):
        """
        Removes an atom from the AtomSpace
        """

        if not Atom(id, self.atomspace):
            abort(404, 'Atom not found')
        else:
            atom = self.atomspace.get_atom_with_uuid(id)

        status = self.atomspace.remove(atom)
        response = DeleteAtomResponse(id, status)
        return {'result': response.format()}
Ejemplo n.º 16
0
def get_uniq_atoms(atom: Atom) -> set[Atom]:
    """Return the set of all unique atoms in atom."""

    result = {atom}

    # Recursive cases
    if atom.is_link():
        for o in atom.out:
            result.update(get_uniq_atoms(o))
        return result

    # Base cases (atom is a node)
    return result
Ejemplo n.º 17
0
def do_planning(space, target):
    a = space

    rl = T('ReferenceLink',
           a.add_node(t.ConceptNode, 'plan_selected_demand_goal'), target)
    atom_from_tree(rl, a)

    # hack
    print 'target'
    target_a = atom_from_tree(target, a)
    print target_a
    print target_a.tv
    target_a.tv = TruthValue(0, 0)
    print target_a

    chainer = Chainer(a, planning_mode=True)

    result_atoms = chainer.bc(target, 2000)

    print "planning result: ", result_atoms

    if result_atoms:
        res_Handle = result_atoms[0]
        res = tree_from_atom(Atom(res_Handle, a))

        trail = chainer.trail(res)
        actions = chainer.extract_plan(trail)

        # set plan_success
        ps = T('EvaluationLink', a.add_node(t.PredicateNode, 'plan_success'),
               T('ListLink'))
        # set plan_action_list
        pal = T('ReferenceLink', a.add_node(t.ConceptNode, 'plan_action_list'),
                T('ListLink', actions))

        ps_a = atom_from_tree(ps, a)
        pal_a = atom_from_tree(pal, a)

        print ps
        print pal
        ps_a.tv = TruthValue(1.0, confidence_to_count(1.0))

        print ps_a.tv

    return result_atoms
Ejemplo n.º 18
0
def is_empty_link(atom: Atom) -> bool:
    """Return True iff the atom is a link with empty outgoing set."""

    return atom.is_link() and atom.out == []
Ejemplo n.º 19
0
def atom_to_idstr(atom: Atom) -> str:
    return atom.id_string() if atom else "None"
Ejemplo n.º 20
0
    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"
Ejemplo n.º 21
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")).h)

        goal_name = Atom(goal, self._atomspace).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")).h)
            print "action_gen: result", Atom(result, self._atomspace)

            # 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 self._atomspace.get_outgoing(result) != []:
                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")).h)
            goal_atoms_list = Atom(goal_atoms, self._atomspace).out
            # print "All goals: ", goal_atoms_list

            # 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"
Ejemplo n.º 22
0
    def handle_vision_message(self, data):
        # print "handle_visiion_message"
        # TODO: In Minecraft the up/down direction is y coord
        # but we should swap y and z in ros node, not here..
        for block in data.blocks:
            swap_y_and_z(block)
        material_dict = {}
        map_handle, cur_map = self._get_map()
        for block in data.blocks:
            old_block_handle = cur_map.get_block((block.x, block.y, block.z))
            updated_eval_links = []

            # Count how many of each block type we have seen during this vision frame.
            # Also store the new block material in case it differs from the existing material.
            # TODO: Use this dict for something or it can be removed, currently
            # it is created and filled up but not used by anything else.
            block_material = blocks.get_block(block.blockid,
                                              block.metadata).display_name

            if block_material in material_dict:
                material_dict[block_material] += 1
            else:
                material_dict[block_material] = 1

            # If this is the first time this block has been seen
            if old_block_handle.is_undefined():
                # Create the block in atomspace and set its initial attention
                # value.
                blocknode, updated_eval_links = self._build_block_nodes(
                    block, map_handle)
                # TODO: Make the 200 a constant, this occurs one other place.
                self._atomspace.set_av(blocknode.h, 200)
            else:
                # Block already exists, check to see if it is still the same
                # type.
                old_block_type_node = get_predicate(self._atomspace,
                                                    "material",
                                                    old_block_handle, 1)
                old_block_type = self._atomspace.get_name(
                    old_block_type_node.h)
                if old_block_type == block_material:
                    # Add short term importance to this block since it is in
                    # the field of view.
                    cur_sti = self._atomspace.get_av(old_block_handle)['sti']
                    # TODO: Make these numbers constants.
                    # TODO: Make the amount added be dependendant on the
                    # distance to the block.
                    cur_sti = min(cur_sti + 20, 500)
                    self._atomspace.set_av(old_block_handle, cur_sti)
                    continue
                elif block.blockid == 0:
                    # Block used to be solid and is now an air block, remove it
                    # from the atomspace and mark the old block as being
                    # disappeared for attention allocation routine to look at.

                    blocknode, updated_eval_links = Atom(-1), []
                    disappeared_link = add_predicate(self._atomspace,
                                                     "disappeared",
                                                     old_block_handle)
                    updated_eval_links.append(disappeared_link)
                else:
                    # NOTE: There is a bit of a bug here since the attention
                    # value does not increase here, but that is ok because this
                    # is rare anyway so skipping an increase is no big deal.
                    blocknode, updated_eval_links = self._build_block_nodes(
                        block, map_handle)

                disappeared_link = add_predicate(self._atomspace,
                                                 "disappeared",
                                                 old_block_handle)
                updated_eval_links.append(disappeared_link)

            # Add the block to the spaceserver and the timeserver.
            self._space_server.add_map_info(blocknode.h, map_handle, False,
                                            False, block.ROStimestamp, block.x,
                                            block.y, block.z)
            if old_block_handle.is_undefined():
                self._time_server.add_time_info(blocknode.h,
                                                block.ROStimestamp, "ROS")
                self._time_server.add_time_info(blocknode.h, block.MCtimestamp,
                                                "MC")
            for link in updated_eval_links:
                self._time_server.add_time_info(link.h, block.ROStimestamp,
                                                "ROS")
                self._time_server.add_time_info(link.h, block.MCtimestamp,
                                                "MC")
                # print blocknode
                # print updated_eval_links

        # TODO: The code below stores the number of blocks of each type seen in
        # the current field of view into the atomspace.  It is commented out as
        # it should probably not store this until the code to erase old values
        # is also added otherwise this data just piles up as new links from the
        # same root node and it becomes a jumbled mess.

        # print "\nBlock material summary:  saw %s kinds of blocks" %
        # len(material_dict)
        """
Ejemplo n.º 23
0
def run_pln_example(a, f):
    a.clear()

    testdir = '../tests/reasoning/pln/targets/'
    datadirs = ['../tests/reasoning/pln/scm/', '../opencog/']
    fname = testdir + f
    config = ConfigParser.ConfigParser()
    read_files = config.read(fname)

    if not read_files:
        raise Exception("no such file:", fname)

    def get(field):
        return config.get('PLN_TEST', field)

    print f

    def load_axioms(fname):
        for d in datadirs:
            kf = d + fname + '.scm'
            try:
                tmp = open(kf, 'r')
                scheme_wrapper.load_scm(a, kf)
                print kf
                return
            except IOError:
                continue
        raise IOError("missing data file: " + kf)

    data_files = get('load').replace(' ', '').split(',')
    for fname in data_files:
        load_axioms(fname)
    scm_target = '(cog-handle %s)' % (get('target'), )
    print scm_target
    handle_str = scheme_wrapper.scheme_eval(scm_target)
    try:
        h = int(handle_str)
    except ValueError:
        print handle_str
        raise Exception("Scheme error in target")

    nsteps = int(get('max_steps'))

    target = Atom(Handle(h), a)

    print target

    import logic
    import tree
    # hack - won't work if the Scheme target is some variable that doesn't contain "Demand"
    if "Demand" in scm_target:
        # superhack - doesn't care which target you say
        target_tr = tree.tree_from_atom(target)
        res = logic.do_planning(a, target_tr)
    else:
        c = logic.Chainer(a)
        target_tr = tree.tree_from_atom(target)
        res = c.bc(target_tr, nsteps)

    if len(res):
        print 'PASSED'
        passed.append(f)
    else:
        print 'FAILED'
        failed.append(f)