Example #1
0
    def put(self, id):
        """
        Updates the AttentionValue (STI, LTI, VLTI) or TruthValue of an atom
        """

        if Handle(id) not in self.atomspace:
            abort(404, 'Handle 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=Handle(id), tv=tv)

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

        atom = self.atomspace[Handle(id)]
        return {'atoms': marshal(atom, atom_fields)}
Example #2
0
    def delete(self, id):
        """
        Removes an atom from the AtomSpace
        Uri: atoms/[id]

        :param id: Atom handle

        :return result:  Returns a JSON representation of the result, indicating success or failure.
        Example:

        {
          'result':
          {
            'handle': 2,
            'success': 'true'
          }
        }
        """

        if Handle(id) not in self.atomspace:
            abort(404, 'Handle not found')
        else:
            atom = self.atomspace[Handle(id)]

        status = self.atomspace.remove(atom)
        response = DeleteAtomResponse(id, status)
        return {'result': response.format()}
Example #3
0
    def delete(self, id):
        """
        Removes an atom from the AtomSpace
        """

        if Handle(id) not in self.atomspace:
            abort(404, 'Handle not found')
        else:
            atom = self.atomspace[Handle(id)]

        status = self.atomspace.remove(atom)
        response = DeleteAtomResponse(id, status)
        return {'result': response.format()}
Example #4
0
    def __get_atoms_in_sti_range(
            self, focus_atoms, atom_type, least_count, sti_min, sti_max
    ):
        """
        Choose atoms within proper STI range.
        :param Type atom_type: type of atoms to choose.
        :param int least_count: minimum number of atoms to choose.
        :param float sti_min: min value of sti to choose.
        :param float sti_max: max value of sti to choose.
        """
        all_atoms = self.a.get_atoms_by_av(sti_min, sti_max)

        all_atoms_h_set = set(
            map(lambda atom: atom.handle_uuid(), all_atoms)
        )
        focus_atoms_h_set = set(
            map(lambda atom: atom.handle_uuid(), focus_atoms)

        )

        atoms_h_set = all_atoms_h_set & focus_atoms_h_set

        if len(atoms_h_set) < least_count:
            self.last_status = self.Status.NOT_ENOUGH_ATOMS
            raise UserWarning('Size of atom list is too small.')

        self.ret = map(lambda atom_h: self.a[Handle(atom_h)], atoms_h_set)
        self.ret = filter(lambda atom: atom.is_a(atom_type), self.ret)
        if len(self.ret) < least_count:
            self.last_status = self.Status.NOT_ENOUGH_ATOMS
            raise UserWarning('Size of atom list is too small.')
Example #5
0
def test_2(a, n):
    """Add n nodes and create a complete (fully-connected) graph in atomspace
    a and returns the number of items processed
    """
    offset = a.add_node(types.ConceptNode, "Starting handle offset")
    offset = offset.h.value()

    for i in range(1, n + 1):
        a.add_node(types.ConceptNode, str(i), TruthValue(.5, .5))
        for j in range(1, i):
            a.add_link(
                types.HebbianLink,
                [Handle(i + offset), Handle(j + offset)], TruthValue(.2, .3))

    # Number of vertices plus number of edges in a fully connected graph
    return n + (n**2 - n) / 2
Example #6
0
    def testAddSolidUnitBlock__PositionOverBorder__GetBlockFailed(self):
        border = 32768
        test_pos1 = (border, 8, 9)
        test_handle1 = Handle(100)

        self.testmap.add_solid_unit_block(test_handle1, test_pos1)
        test_handle2 = self.testmap.get_block(test_pos1)

        self.assertTrue(test_handle2.is_undefined())
Example #7
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])
Example #8
0
    def get(self, id):
        """
        Returns the atom for the given handle
        Uri: atoms/[id]

        :param id: Atom handle

        :return atoms: Returns a JSON representation of an atom list containing the atom.

        Example:

        {
          'atoms':
          {
            'handle': 6,
            'name': '',
            'type': 'InheritanceLink',
            'outgoing': [2, 1],
            'incoming': [],
            'truthvalue':
              {
                'type': 'simple',
                'details':
                  {
                    'count': '0.4000000059604645',
                    'confidence': '0.0004997501382604241',
                    'strength': '0.5'
                  }
              },
          'attentionvalue':
            {
              'lti': 0,
              'sti': 0,
              'vlti': false
            }
          }
        }
        """

        try:
            atom = self.atomspace[Handle(id)]
        except IndexError:
            abort(404, 'Handle not found')

        json_data = {'atoms': marshal(atom, atom_fields)}

        # if callback function supplied, pad the JSON data (i.e. JSONP):
        args = self.reqparse.parse_args()
        callback = args.get('callback')
        if callback is not None:
            response = str(callback) + '(' + json.dumps(json_data) + ');'
            return current_app.response_class(
                response, mimetype='application/javascript')
        else:
            return current_app.response_class(json.dumps(json_data),
                                              mimetype='application/json')
Example #9
0
    def get_src_list(self, a):
        ret = []

        src_node_h_int_list = self.src_h_list_str.split(', ')
        # Delete end of string
        src_node_h_int_list.pop()

        for src_node_h_int in src_node_h_int_list:
            ret.append(a[Handle(int(src_node_h_int))])

        return ret
Example #10
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 = []
Example #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:
            if len(data['outgoing']) > 0:
                outgoing = [Handle(h) for h 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)}
Example #12
0
    def testBinaryAddandRemove_NormalUnitBlock_AllGetFunctionWork(self):
        test_pos1 = (7, 8, 9)
        test_handle1 = Handle(100)

        self.testmap.add_solid_unit_block(test_handle1, test_pos1)
        test_handle2 = self.testmap.get_block(test_pos1)
        self.assertEqual(test_handle1, test_handle2)
        self.assertEqual(test_pos1,
                         self.testmap.get_block_location(test_handle1))

        self.testmap.remove_solid_unit_block(test_handle1)
        test_handle3 = self.testmap.get_block(test_pos1)
        self.assertTrue(test_handle3.is_undefined())
        self.assertIsNone(self.testmap.get_block_location(test_handle1))
Example #13
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"
Example #14
0
    def test_container_methods(self):
        self.assertEquals(len(self.space), 0)
        h = Handle(100)
        self.assertRaises(KeyError, self.space.__getitem__, "blah")
        self.assertRaises(IndexError, self.space.__getitem__, h)
        a1 = self.space.add_node(types.Node, "test1")
        a2 = self.space.add_node(types.ConceptNode, "test2")
        a3 = self.space.add_node(types.PredicateNode, "test3")
        h1 = a1.h
        h2 = a2.h
        self.assertEquals(a1, self.space[h1])

        self.assertTrue(h1 in self.space)
        self.assertTrue(a1 in self.space)
        self.assertTrue(h2 in self.space)

        self.assertEquals(len(self.space), 3)
Example #15
0
    def get(self, id):
        """
        Returns the atom for the given handle
        Uri: atoms/[id]

        :param id: Atom handle

        :return atoms: Returns a JSON representation of an atom list containing the atom.

        Example:

        {
          'atoms':
          {
            'handle': 6,
            'name': '',
            'type': 'InheritanceLink',
            'outgoing': [2, 1],
            'incoming': [],
            'truthvalue':
              {
                'type': 'simple',
                'details':
                  {
                    'count': '0.4000000059604645',
                    'confidence': '0.0004997501382604241',
                    'strength': '0.5'
                  }
              },
          'attentionvalue':
            {
              'lti': 0,
              'sti': 0,
              'vlti': false
            }
          }
        }
        """

        try:
            atom = self.atomspace[Handle(id)]
        except IndexError:
            abort(404, 'Handle not found')

        return {'atoms': marshal(atom, atom_fields)}
Example #16
0
    def __get_atoms_in_sti_range(self, focus_atoms, atom_type, least_count,
                                 sti_min, sti_max):
        all_atoms = self.a.get_atoms_by_av(sti_min, sti_max)

        all_atoms_h_set = set(map(lambda atom: atom.handle_uuid(), all_atoms))
        focus_atoms_h_set = set(
            map(lambda atom: atom.handle_uuid(), focus_atoms))

        atoms_h_set = all_atoms_h_set & focus_atoms_h_set

        if len(atoms_h_set) < least_count:
            self.last_status = blending_status.NOT_ENOUGH_ATOMS
            return

        self.ret = map(lambda atom_h: self.a[Handle(atom_h)], atoms_h_set)
        self.ret = filter(lambda atom: atom.is_a(atom_type), self.ret)
        if len(self.ret) < least_count:
            self.last_status = blending_status.NOT_ENOUGH_ATOMS
            return
Example #17
0
    def testSetBlock_AddBlockWithProbabilityControl_GetFunctionsWorkWithProb(
            self):
        test_pos1 = (7, 8, 9)
        test_handle1 = Handle(100)
        log_odds_threshold = self.testmap.get_occupancy_thres_log()

        self.testmap.set_unit_block(test_handle1, test_pos1,
                                    log_odds_threshold)

        self.assertEqual(test_handle1, self.testmap.get_block(test_pos1))
        self.assertEqual(test_handle1,
                         self.testmap.get_block(test_pos1, log_odds_threshold))
        self.assertEqual(test_pos1,
                         self.testmap.get_block_location(test_handle1))
        self.assertEqual(
            test_pos1,
            self.testmap.get_block_location(test_handle1, log_odds_threshold))
        self.assertEqual(log_odds_threshold,
                         self.testmap.search(test_pos1).get_log_odds())
        #change the occupancy so it's small enough to make getter find nothing
        self.testmap.set_unit_block(test_handle1, test_pos1, -0.1)

        self.assertTrue(self.testmap.get_block(test_pos1).is_undefined())
        self.assertTrue(
            self.testmap.get_block(test_pos1,
                                   log_odds_threshold).is_undefined())
        self.assertIsNone(self.testmap.get_block_location(test_handle1))
        self.assertIsNone(
            self.testmap.get_block_location(test_handle1, log_odds_threshold))

        #change the threshold, so the occupancy is large enough to find it
        self.testmap.set_occupancy_thres(-0.2)
        log_odds_threshold = self.testmap.get_occupancy_thres_log()
        self.assertEqual(test_handle1, self.testmap.get_block(test_pos1))
        self.assertEqual(test_handle1,
                         self.testmap.get_block(test_pos1, log_odds_threshold))

        self.assertEqual(test_pos1,
                         self.testmap.get_block_location(test_handle1))
        self.assertEqual(
            test_pos1,
            self.testmap.get_block_location(test_handle1, log_odds_threshold))
Example #18
0
    def get_src_list(self, a):
        """Get a source node list in EqualLinkKey.

        It converts source node string to list of Atom.

        Args:
            a: An instance of AtomSpace to find Atom.
            :param a: AtomSpace
        Returns:
            The atoms that saved in EqualLink.
            :rtype : list[Atom]
        """
        ret = []

        src_node_h_int_list = self.src_h_list_str.split(', ')
        # Delete end of string
        src_node_h_int_list.pop()

        for src_node_h_int in src_node_h_int_list:
            ret.append(a[Handle(int(src_node_h_int))])

        return ret
    def get(self, id=""):
        """
        Returns a list of atoms matching the specified criteria
        Uri:

        atoms/[id]
        (or)
        atoms?type=[type]&name=[name]&filterby=[filterby]
            &tvStrengthMin=[tvStrengthMin]&tvConfidenceMin=[tvConfidenceMin]
            &tvCountMin=[tvCountMin]&includeIncoming=[includeIncoming]
            &includeOutgoing=[includeOutgoing]&callback=[callback]

        :param id: (optional, int, to specifically request an atom by handle,
            can be combined with includeIncoming or includeOutgoing only; if
            specified, other query parameters will have no effect) Atom handle

        :param type: (optional) Atom type, see
            http://wiki.opencog.org/w/OpenCog_Atom_types
        :param name: (optional, string, not allowed for Link types) Atom name
        If neither type or name are provided, all atoms will be retrieved
        :param filterby: (optional, can't be combined with type or name)
            Allows certain predefined filters
          - The filter 'stirange' allows the additional parameters 'stimin'
            (required, int) and 'stimax' (optional, int) and returns the atoms
            in a given STI range
          - The filter 'attentionalfocus' (boolean) returns the atoms in the
            AttentionalFocus
        :param tvStrengthMin: (optional, float) Only return atoms with
            TruthValue strength greater than this amount
        :param tvConfidenceMin: (optional, float) Only return atoms with
            TruthValue confidence greater than this amount
        :param tvCountMin: (optional, float) Only return atoms with TruthValue
            count greater than this amount
        :param includeIncoming: (optional, boolean) Returns the conjunction of
            the set of atoms and their incoming sets
        :param includeOutgoing: (optional, boolean) Returns the conjunction of
            the set of atoms and their outgoing sets. Useful in combination
            with includeIncoming.

        :param dot: (optional, boolean) Returns the atom set represented in
            the DOT graph description language
            (See opencog/python/graph_description/README.md for details)

        :param callback: (optional) JavaScript callback function for JSONP
            support

        :return result: Returns a JSON representation of an atom list.
        Example:

        {
          'result':
          {
            'complete': 'true',
            'skipped': 'false',
            'total': 10,
            'atoms':
              [
                { 'handle': 6,
                  'name': '',
                  'type': 'InheritanceLink',
                  'outgoing': [2, 1],
                  'incoming': [],
                  'truthvalue':
                    {
                      'type': 'simple',
                      'details':
                        {
                          'count': '0.4000000059604645',
                          'confidence': '0.0004997501382604241',
                          'strength': '0.5'
                        }
                    }
                  'attentionvalue':
                    {
                      'lti': 0,
                      'sti': 0,
                      'vlti': false
                    }
                },
                     ...
              ]
          }
        }
        """

        args = self.reqparse.parse_args()
        type = args.get('type')
        name = args.get('name')
        callback = args.get('callback')

        filter_by = args.get('filterby')
        sti_min = args.get('stimin')
        sti_max = args.get('stimax')

        tv_strength_min = args.get('tvStrengthMin')
        tv_confidence_min = args.get('tvConfidenceMin')
        tv_count_min = args.get('tvCountMin')

        include_incoming = args.get('includeIncoming')
        include_outgoing = args.get('includeOutgoing')

        dot_format = args.get('dot')

        if id != "":
            try:
                atom = self.atomspace[Handle(id)]
                atoms = [atom]
            except IndexError:
                atoms = []
                # abort(404, 'Handle not found')
        else:
            # First, check if there is a valid filter type, and give it
            # precedence if it exists
            valid_filter = False
            if filter_by is not None:
                if filter_by == 'stirange':
                    if sti_min is not None:
                        valid_filter = True
                        atoms = self.atomspace.get_atoms_by_av(
                            sti_min, sti_max)
                    else:
                        abort(
                            400, 'Invalid request: stirange filter requires '
                            'stimin parameter')
                elif filter_by == 'attentionalfocus':
                    valid_filter = True
                    atoms = self.atomspace.get_atoms_in_attentional_focus()

            # If there is not a valid filter type, proceed to select by type
            # or name
            if not valid_filter:
                if type is None and name is None:
                    atoms = self.atomspace.get_atoms_by_type(types.Atom)
                elif name is None:
                    atoms = self.atomspace.get_atoms_by_type(
                        types.__dict__.get(type))
                else:
                    if type is None:
                        type = 'Node'
                    atoms = self.atomspace.get_atoms_by_name(
                        t=types.__dict__.get(type), name=name)

            # Optionally, filter by TruthValue
            if tv_strength_min is not None:
                atoms = [
                    atom for atom in atoms if atom.tv.mean >= tv_strength_min
                ]

            if tv_confidence_min is not None:
                atoms = [
                    atom for atom in atoms
                    if atom.tv.confidence >= tv_confidence_min
                ]

            if tv_count_min is not None:
                atoms = [
                    atom for atom in atoms if atom.tv.count >= tv_count_min
                ]

        # Optionally, include the incoming set
        if include_incoming in ['True', 'true', '1']:
            atoms = self.atomspace.include_incoming(atoms)

        # Optionally, include the outgoing set
        if include_outgoing in ['True', 'true', '1']:
            atoms = self.atomspace.include_outgoing(atoms)

        # The default is to return the atom set as JSON atoms. Optionally, a
        # DOT return format is also supported
        if dot_format not in ['True', 'true', '1']:
            atom_list = AtomListResponse(atoms)
            json_data = {'result': atom_list.format()}

            # if callback function supplied, pad the JSON data (i.e. JSONP):
            if callback is not None:
                response = str(callback) + '(' + json.dumps(json_data) + ');'
                return current_app.response_class(
                    response, mimetype='application/javascript')
            else:
                return current_app.response_class(json.dumps(json_data),
                                                  mimetype='application/json')
        else:
            dot_output = dot.get_dot_representation(atoms)
            return jsonify({'result': dot_output})
    def post(self):
        """
        Creates a new atom. If the atom already exists, it updates the atom.
        Uri: atoms

        Include data with the POST request providing a JSON representation of
        the atom.
        Valid data elements:

        type (required) Atom type, see
            http://wiki.opencog.org/w/OpenCog_Atom_types
        name (required for Node types, not allowed for Link types) Atom name
        truthvalue (required) TruthValue, formatted as follows:
            type (required) TruthValue type (only 'simple' is currently
                available), see http://wiki.opencog.org/w/TruthValue
            details (required) TruthValue parameters, formatted as follows:
                strength (required)
                count (required)
        outgoing (optional) The set of arguments of the relation, formatted as
            a list of Atom handles (only valid for Links, not nodes), see
            http://wiki.opencog.org/w/Link#Incoming_and_Outgoing_Sets

        Examples:

        Node: {
                'type': 'ConceptNode',
                'name': 'Frog',
                'truthvalue':
                  {
                    'type': 'simple',
                    'details':
                      {
                        'strength': 0.8,
                        'count': 0.2
                      }
                  }
              }

        Link: {
                'type': 'InheritanceLink',
                'outgoing': [1, 2],
                'truthvalue':
                  {
                    'type': 'simple',
                    'details':
                      {
                        'strength': 0.5,
                        'count': 0.4
                      }
                  }
              }

        :return atoms: Returns a JSON representation of an atom list containing
        the atom. Example:
        {
          'atoms':
          {
            'handle': 6,
            'name': '',
            'type': 'InheritanceLink',
            'outgoing': [2, 1],
            'incoming': [],
            'truthvalue':
              {
                'type': 'simple',
                'details':
                  {
                    'count': '0.4000000059604645',
                    'confidence': '0.0004997501382604241',
                    'strength': '0.5'
                  }
              },
            'attentionvalue':
              {
                'lti': 0,
                'sti': 0,
                'vlti': false
              }
          }
        }
        """

        # 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:
            if len(data['outgoing']) > 0:
                outgoing = [Handle(h) for h 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)}
Example #21
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)
    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",
                    Atom(old_block_handle, self._atomspace), 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(
                        Handle(-1), self._atomspace), []
                    disappeared_link = add_predicate(
                        self._atomspace, "disappeared",
                        Atom(old_block_handle, self._atomspace))
                    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",
                    Atom(old_block_handle, self._atomspace))
                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)
        """
Example #23
0
    def put(self, id):
        """
        Updates the AttentionValue (STI, LTI, VLTI) or TruthValue of an atom
        Uri: atoms/[id]

        :param id: Atom handle
        Include data with the PUT request providing a JSON representation of the updated attributes.
        Valid data elements:

        truthvalue (optional) TruthValue, formatted as follows:
            type (required) TruthValue type (only 'simple' is currently available)
                            see http://wiki.opencog.org/w/TruthValue
            details (required) TruthValue parameters, formatted as follows:
                strength (required)
                count (required)
        attentionvalue (optional) AttentionValue, formatted as follows:
            sti (optional) Short-Term Importance
            lti (optional) Long-Term Importance
            vlti (optional) Very-Long Term Importance

        Example:

        {
          'truthvalue':
          {
            'type': 'simple',
            'details':
              {
                'strength': 0.005,
                'count': 0.8
              }
          },
        'attentionvalue':
          {
            'sti': 9,
            'lti': 2,
            'vlti': True
          }
        }

        :return atoms: Returns a JSON representation of an atom list containing the atom.
        Example:

        { 'atoms':
          {
            'handle': 6,
            'name': '',
            'type': 'InheritanceLink',
            'outgoing': [2, 1],
            'incoming': [],
            'truthvalue':
              {
                'type': 'simple',
                'details':
                  {
                    'count': '0.4000000059604645',
                    'confidence': '0.0004997501382604241',
                    'strength': '0.5'
                  }
              },
            'attentionvalue':
              {
                'lti': 0,
                'sti': 0,
                'vlti': false
              }
            }
          }
        }
        """

        if Handle(id) not in self.atomspace:
            abort(404, 'Handle 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=Handle(id), tv=tv)

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

        atom = self.atomspace[Handle(id)]
        return {'atoms': marshal(atom, atom_fields)}
Example #24
0
    def _get(self, id=""):
        """
        Returns a list of atoms matching the specified criteria
        """

        args = self.reqparse.parse_args()
        type = args.get('type')
        name = args.get('name')
        callback = args.get('callback')

        filter_by = args.get('filterby')
        sti_min = args.get('stimin')
        sti_max = args.get('stimax')

        tv_strength_min = args.get('tvStrengthMin')
        tv_confidence_min = args.get('tvConfidenceMin')
        tv_count_min = args.get('tvCountMin')

        include_incoming = args.get('includeIncoming')
        include_outgoing = args.get('includeOutgoing')

        dot_format = args.get('dot')

        limit = args.get('limit')

        if id != "":
            try:
                atom = self.atomspace[Handle(id)]
                atoms = [atom]
            except IndexError:
                atoms = []
                # abort(404, 'Handle not found')
        else:
            # First, check if there is a valid filter type, and give it
            # precedence if it exists
            valid_filter = False
            if filter_by is not None:
                if filter_by == 'stirange':
                    if sti_min is not None:
                        valid_filter = True
                        atoms = self.atomspace.get_atoms_by_av(
                            sti_min, sti_max)
                    else:
                        abort(
                            400, 'Invalid request: stirange filter requires '
                            'stimin parameter')
                elif filter_by == 'attentionalfocus':
                    valid_filter = True
                    atoms = self.atomspace.get_atoms_in_attentional_focus()

            # If there is not a valid filter type, proceed to select by type
            # or name
            if not valid_filter:
                if type is None and name is None:
                    atoms = self.atomspace.get_atoms_by_type(types.Atom)
                elif name is None:
                    atoms = self.atomspace.get_atoms_by_type(
                        types.__dict__.get(type))
                else:
                    if type is None:
                        type = 'Node'
                    atoms = self.atomspace.get_atoms_by_name(
                        t=types.__dict__.get(type), name=name)

            # Optionally, filter by TruthValue
            if tv_strength_min is not None:
                atoms = [
                    atom for atom in atoms if atom.tv.mean >= tv_strength_min
                ]

            if tv_confidence_min is not None:
                atoms = [
                    atom for atom in atoms
                    if atom.tv.confidence >= tv_confidence_min
                ]

            if tv_count_min is not None:
                atoms = [
                    atom for atom in atoms if atom.tv.count >= tv_count_min
                ]

        # Optionally, include the incoming set
        if include_incoming in ['True', 'true', '1']:
            atoms = self.atomspace.include_incoming(atoms)

        # Optionally, include the outgoing set
        if include_outgoing in ['True', 'true', '1']:
            atoms = self.atomspace.include_outgoing(atoms)

        # Optionally, limit number of atoms returned
        if limit is not None:
            if len(atoms) > limit:
                atoms = atoms[0:limit]

        # The default is to return the atom set as JSON atoms. Optionally, a
        # DOT return format is also supported
        if dot_format not in ['True', 'true', '1']:
            atom_list = AtomListResponse(atoms)
            json_data = {'result': atom_list.format()}

            # if callback function supplied, pad the JSON data (i.e. JSONP):
            if callback is not None:
                response = str(callback) + '(' + json.dumps(json_data) + ');'
                return current_app.response_class(
                    response, mimetype='application/javascript')
            else:
                return current_app.response_class(json.dumps(json_data),
                                                  mimetype='application/json')
        else:
            dot_output = dot.get_dot_representation(atoms)
            return jsonify({'result': dot_output})