class Test_Atoms_and_Scheme_shell(unittest.TestCase):



  def setUp(self):
    #creating atomspace
    self.atsp = AtomSpace()
    self.TV = TruthValue()
    initialize_opencog(self.atsp)
  def tearDown(self):
    del self.atsp
    

  def test_create_node(self): #params as (self,type) , to test each and every kind of Atoms
    #creating a node 
    self.node_hello = self.atsp.add_node(types.ConceptNode,"HelloWorld")
    #testing if node is created 
    self.test_node_hello =scheme_eval_h(self.atsp, "(ConceptNode \"HelloWorld\")")
    self.assertEqual(self.test_node_hello,self.node_hello)
    self.assertIsInstance(node,Atom)


  def test_create_links(self):
    #creating nodes
    self.fox = self.atsp.add_node(types.ConceptNode,"Fox")
    self.animal = self.atsp.add_node(types.ConceptNode,"Animal")
    #creating link between nodes
    self.inheritance_link = self.atsp.add_link(types.InheritanceLink,[fox,animal])

    #testing if link is created
    self.test_inheritance_link=self.atsp.add_link(types.InheritanceLink,[self.fox,self.animal])

    self.assertEqual(InheritanceLink(self.fox,self.animal),self.test_inheritance_link)

    self.assertIsInstance(inheritance_link,Atom) # In a sense that links are atoms themselves.
Example #2
0
class SimpleAgent():

    def __init__(self):
        self.a = AtomSpace()
        self.nodes = {}
        
        # Initialize Scheme
        scheme_preload = [  
                    "opencog/atomspace/core_types.scm",
                    "opencog/scm/utilities.scm"          ]
        scheme.__init__(self.a)
        for scheme_file in scheme_preload:
            load_scm(self.a, scheme_file)
        initialize_opencog(self.a)
        
        #add 3 nodes with integer values
        self.nodes[0] = self.a.add(types.ConceptNode, "0")
        self.nodes[1] = self.a.add(types.ConceptNode, "1")
        self.nodes[2] = self.a.add(types.ConceptNode, "2")

    def performAction(self):
        #randomly select a link from those available and add the nodes
        fnode = self.a.add_node(types.GroundedSchemaNode, "py: sendValue")
        current_link = self.a.add_link(types.ExecutionOutputLink, [
            fnode,
            self.a.add_link(types.ListLink, [self.nodes[randint(0,2)]])])
        
        scheme_eval(self.a, '(cog-execute! (cog-atom %d))'%(current_link.handle_uuid()))
    
    def remove(self):
        # make sure this is called by the time script exits
        finalize_opencog()
        del self.a
Example #3
0
class UtilitiesTest(TestCase):

    def setUp(self):
        self.atomspace = AtomSpace()
 
    def tearDown(self):
        del self.atomspace

    def test_initialize_finalize(self):
        initialize_opencog(self.atomspace)
        finalize_opencog()

    def test_fast_load(self):
        gen_atoms(self.atomspace)
        with tempfile.TemporaryDirectory() as tmpdirname:
            tmp_file = os.path.join(tmpdirname, 'tmp.scm')
            write_sorted_file(tmp_file, self.atomspace)
            new_space = AtomSpace()
            load_file(tmp_file, new_space)
            self.assertTrue(len(new_space) == len(self.atomspace))
            # files should be binary equal
            new_tmp = os.path.join(tmpdirname, 'tmp1.scm')
            write_sorted_file(new_tmp, new_space)
            self.assertTrue(filecmp.cmp(tmp_file, new_tmp, shallow=False), "files are not equal")
            checklist = """(ListLink(ConceptNode "vfjv\\"jnvfé")
                (ConceptNode "conceptIR~~gF\\",KV")
                (ConceptNode "вверху плыли редкие облачка"))"""
            with open(tmp_file, 'wt') as f:
                f.write(checklist)
            new_space1 = AtomSpace()
            load_file(tmp_file, new_space1)
            self.assertTrue(len(new_space1) == 4)

    def test_is_closed(self):
        A = self.atomspace.add_node(types.ConceptNode, 'A')
        B = self.atomspace.add_node(types.ConceptNode, 'B')
        X = self.atomspace.add_node(types.VariableNode, '$X')
        AB = self.atomspace.add_link(types.InheritanceLink, [A, B])
        AX = self.atomspace.add_link(types.InheritanceLink, [A, X])
        self.assertTrue(is_closed(AB))
        self.assertFalse(is_closed(AX))

    def test_get_free_variables(self):
        A = self.atomspace.add_node(types.ConceptNode, 'A')
        X = self.atomspace.add_node(types.VariableNode, '$X')
        AX = self.atomspace.add_link(types.InheritanceLink, [A, X])
        self.assertEqual(get_free_variables(AX), [X])
Example #4
0
 def query(self, result_atomspace, query):
     res_set = self.intersect(query)
     # add all possible results to tmp atomspace and run query
     # what is called filter step in graph indexing literature
     tmp = AtomSpace()
     atom_str = self._storage.get_atoms(res_set)
     for item in atom_str:
         tmp.add_atom(scheme_eval_h(tmp, item))
     # pack query in BindLink
     q = tmp.add_link(types.BindLink, [query, query])
     results = execute_atom(tmp, q)
     result_atoms = set()
     for atom in results.out:
         result_atoms.add(result_atomspace.add_atom(atom))
     return result_atoms
Example #5
0
class Test_Atoms_and_Scheme_shell(unittest.TestCase):
    def setUp(self):
        self.atsp = AtomSpace()

    def test_create_node(
            self
    ):  #params as (self,type) , to test each and every kind of Atoms
        node = self.atsp.add_node(types.ConceptNode, "HelloWorld")
        self.assertIsInstance(node, Atom)

    def test_create_links(self):
        fox = self.atsp.add_node(types.ConceptNode, "Fox")
        animal = self.atsp.add_node(types.ConceptNode, "Animal")

        inheritance_link = self.atsp.add_link(types.InheritanceLink,
                                              [fox, animal])

        self.assertIsInstance(
            inheritance_link,
            Atom)  # In a sense that links are atoms themselves.
Example #6
0
                        elem = elem.split(')')
                        concepts.append(elem[0])

                    # Construct OpenCog atoms

                    predicate_node = atomspace.add_node(
                        types.PredicateNode, predicate)

                    # ConceptNodes
                    concept_nodes = []
                    for concept in concepts:
                        concept_nodes.append(
                            atomspace.add_node(types.ConceptNode, concept))

                    # ListLink
                    list_link = atomspace.add_link(types.ListLink,
                                                   concept_nodes, crisp_true)

                    # EvaluationLink
                    eval_link = atomspace.add_link(types.EvaluationLink,
                                                   [predicate_node, list_link])
                    new_link = eval_link

                    # Determine whether the predicate is negated, and create
                    # a NotLink if necessary.
                    if negated:
                        # NotLink
                        not_link = atomspace.add_link(types.NotLink,
                                                      [eval_link])

                        # TruthValue
                        atomspace.set_tv(not_link.h, crisp_true)
Example #7
0
class RulesTest(TestCase):
    def setUp(self):
        self.atomspace = AtomSpace()
        self.chainer = Chainer(self.atomspace)

    def tearDown(self):
        del self.atomspace
        del self.chainer

    def _inh_animal_breathe(self):
        '''InheritanceLink animal breathe'''
        default_av = {'sti': 1}
        self.animal = self.atomspace.add_node(types.ConceptNode, "animal")
        self.breathe = self.atomspace.add_node(types.ConceptNode, "breathe")
        self.inh_animal_breathe = self.atomspace.add_link(
            types.InheritanceLink, [self.animal, self.breathe])

        self.animal.tv = TruthValue(0.1, 1)
        self.breathe.tv = TruthValue(0.1, 1)
        self.inh_animal_breathe.tv = TruthValue(1, 1)

        atoms = []
        atoms.append(self.animal)
        atoms.append(self.breathe)
        atoms.append(self.inh_animal_breathe)

        for atom in atoms:
            atom.av = default_av

        return atoms

#    def _apply_rule(self, rule,

    def test_standardize_apart_input_output(self):
        rule = rules.InversionRule(self.chainer, types.InheritanceLink)

        (input, output) = rule.standardize_apart_input_output(self.chainer)

    def test_InversionRule(self):
        rule = rules.InversionRule(self.chainer, types.InheritanceLink)

        self._inh_animal_breathe()

        result = self.chainer._apply_forward(rule)
        print result

    def test_InversionRule_backward(self):
        rule = rules.InversionRule(self.chainer, types.InheritanceLink)

        self._inh_animal_breathe()
        self.inh_breathe_animal = self.atomspace.add_link(
            types.InheritanceLink, [self.breathe, self.animal])
        self.inh_breathe_animal.av = {'sti': 1}

        result = self.chainer._apply_backward(rule)
        print result

    def disabled_test_rules_generically(self):
        '''See what happens if you give a rule the generic inputs. This makes sure that the rule and formula don't have any basic code errors, but doesn't check that they do the right thing.'''
        def apply_rule(rule):
            generic_inputs = rule.inputs
            generic_outpus = rule.outputs

            # Take the generic required input atoms and give them boring TVs
            for atom in generic_inputs:
                atom.av = {'sti': 1}
                atom.tv = TruthValue(1, 1)

            status = self.chainer._apply_forward(rule)

            self.assertNotEquals(status, None)

            return None

        for rule in self.chainer.rules:
            apply_rule(rule)
Example #8
0
from opencog.atomspace import AtomSpace, TruthValue, Atom
from opencog.atomspace import types as t

a = AtomSpace()

TV = TruthValue(1,1)
A = a.add_node(t.ConceptNode, 'A', TV)
B = a.add_node(t.ConceptNode, 'B', TruthValue(0.5,1))
C = a.add_node(t.ConceptNode, 'C', TV)
AB = a.add_link(t.InheritanceLink, [A, B], TV)
BC = a.add_link(t.InheritanceLink, [B, C], TV)
AC = a.add_link(t.InheritanceLink, [A, C])

print AB.incoming


a.print_list()


import logic
from tree import *

target = tree_from_atom(AC)
chainer = logic.Chainer(a)
results = chainer.bc(target)

print '\n---------------------------\n'

print results
print AC.tv
Example #9
0
class TestMap(unittest.TestCase):
    def setUp(self):
        self.atomspace = AtomSpace()
        resolution = 1
        floor_height = -255
        agent_height = 1.6
        self.testmap = Octree3DMapManager.init_new_map(self.atomspace,
                                                       "testmap", resolution,
                                                       floor_height,
                                                       agent_height)

    def tearDown(self):
        del self.testmap
        del self.atomspace

    def test_GetMapName(self):
        self.assertEqual("testmap", self.testmap.get_map_name())

    def test_GetBlock_NoBlockAdded_ReturnUndefinedHandle(self):
        test_pos = (7, 8, 9)

        test_handle = self.testmap.get_block(test_pos)

        self.assertTrue(test_handle.is_undefined())

    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))

    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())

    def testSetBlock_AddBlockWithProbabilityControl_GetFunctionsWorkWithProb(
            self):
        test_pos1 = (7, 8, 9)
        test_handle1 = Handle(100)
        log_odds_threshold = self.testmap.get_log_odds_occupied_threshold()

        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))

        #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_log_odds_occupied_threshold(-0.2)
        log_odds_threshold = self.testmap.get_log_odds_occupied_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))

    def testStandable_NormalBlock_Standable(self):
        #case1: single block
        test_pos = (1, 2, 4)
        block_pos = (1, 2, 3)
        self.assertFalse(self.testmap.check_standable(test_pos))
        test_block = self.atomspace.add_node(types.StructureNode, "block1").h
        material_node = self.atomspace.add_node(types.ConceptNode, "dirt").h
        material_pred_node = self.atomspace.add_node(types.PredicateNode,
                                                     "material").h
        list_link = self.atomspace.add_link(types.ListLink,
                                            [test_block, material_node]).h
        eval_link = self.atomspace.add_link(types.EvaluationLink,
                                            [material_pred_node, list_link]).h
        self.testmap.add_solid_unit_block(test_block, block_pos)

        standable = self.testmap.check_standable(test_pos)

        self.assertTrue(standable)

    def testStandable_WaterBlock_Unstandable(self):
        #case2: single block which is water, cannot stand on water
        test_pos = (1, 2, 4)
        block_pos = (1, 2, 3)
        self.assertFalse(self.testmap.check_standable(test_pos))
        test_block = self.atomspace.add_node(types.StructureNode, "block1").h
        material_node = self.atomspace.add_node(types.ConceptNode, "water").h
        material_pred_node = self.atomspace.add_node(types.PredicateNode,
                                                     "material").h
        list_link = self.atomspace.add_link(types.ListLink,
                                            [test_block, material_node]).h
        eval_link = self.atomspace.add_link(types.EvaluationLink,
                                            [material_pred_node, list_link]).h
        self.testmap.add_solid_unit_block(test_block, block_pos)

        standable = self.testmap.check_standable(test_pos)

        self.assertFalse(standable)

    def testStandable_TwoNearBlock_Unstandable(self):
        # case3: two block which z coord is close ( ditance < agentHeight)
        # so it's not standable
        test_pos = (1, 2, 4)
        block_pos1 = (1, 2, 3)
        self.assertFalse(self.testmap.check_standable(test_pos))
        test_block1 = self.atomspace.add_node(types.StructureNode, "block1").h
        material_node1 = self.atomspace.add_node(types.ConceptNode, "dirt").h
        material_pred_node = self.atomspace.add_node(types.PredicateNode,
                                                     "material").h
        list_link1 = self.atomspace.add_link(types.ListLink,
                                             [test_block1, material_node1]).h
        eval_link1 = self.atomspace.add_link(
            types.EvaluationLink, [material_pred_node, list_link1]).h
        self.testmap.add_solid_unit_block(test_block1, block_pos1)

        blockpos2 = (1, 2, 5)
        testBlock2 = self.atomspace.add_node(types.StructureNode, "block2").h
        material_node2 = self.atomspace.add_node(types.ConceptNode, "stone").h
        material_pred_node = self.atomspace.add_node(types.PredicateNode,
                                                     "material").h
        list_link2 = self.atomspace.add_link(types.ListLink,
                                             [testBlock2, material_node2]).h
        eval_link2 = self.atomspace.add_link(
            types.EvaluationLink, [material_pred_node, list_link2]).h
        self.testmap.add_solid_unit_block(testBlock2, blockpos2)
        self.assertFalse(self.testmap.get_block(blockpos2).is_undefined())
        self.assertFalse(self.testmap.get_block(block_pos1).is_undefined())
        standable = self.testmap.check_standable(test_pos)

        self.assertFalse(standable)

    def testAddandRemoveNoneBlockEntity_NormalEntity_AllGetFunctionsWork(self):
        test_pos = (17, 28, 39)
        timestamp = 12345
        test_handle1 = self.atomspace.add_node(types.EntityNode, "entity").h
        entity_is_self = False
        entity_is_avatar = False

        self.testmap.add_none_block_entity(test_handle1, test_pos,
                                           entity_is_self, entity_is_avatar,
                                           timestamp)

        test_handle2 = self.testmap.get_entity(test_pos)
        self.assertEqual(test_handle1, test_handle2)
        self.assertEqual(test_pos,
                         self.testmap.get_last_appeared_location(test_handle1))
        self.testmap.remove_none_block_entity(test_handle1)

        self.assertTrue(self.testmap.get_entity(test_pos).is_undefined())
        #preserve record
        self.assertEqual(test_pos,
                         self.testmap.get_last_appeared_location(test_handle1))

    def testUpdateEntityLocation_MultipleLocation_LastLocationIsPos2(self):
        test_pos1 = (17, 28, 39)
        timestamp1 = 12345
        test_handle1 = self.atomspace.add_node(types.EntityNode, "entity").h
        entity_is_self = False
        entity_is_avatar = False

        self.testmap.add_none_block_entity(test_handle1, test_pos1,
                                           entity_is_self, entity_is_avatar,
                                           timestamp1)

        test_pos2 = (17, 28, 40)
        timestamp2 = 12346
        self.testmap.update_none_block_entity_location(test_handle1, test_pos2,
                                                       timestamp2)
        last_location = self.testmap.get_last_appeared_location(test_handle1)

        self.assertEqual(test_pos2, last_location)

    def testAddEntity_PressureTest(self):
        count = 10000
        timestamp = 12345
        while count != 0:
            print count
            count -= 1
            test_pos = (count, count, count)
            test_handle1 = self.atomspace.add_node(types.EntityNode,
                                                   "entity" + str(count)).h
            entity_is_self = False
            entity_is_avatar = False

            self.testmap.add_none_block_entity(test_handle1, test_pos,
                                               entity_is_self,
                                               entity_is_avatar, timestamp)
            test_handle2 = self.testmap.get_entity(test_pos)
            self.assertEqual(test_handle1, test_handle2)
            self.assertEqual(
                test_pos,
                self.testmap.get_last_appeared_location(test_handle1))
            self.testmap.remove_none_block_entity(test_handle1)

            self.assertTrue(self.testmap.get_entity(test_pos).is_undefined())
            #preserve record
            self.assertEqual(
                test_pos,
                self.testmap.get_last_appeared_location(test_handle1))
Example #10
0
class BackwardChainerTest(TestCase):

    def setUp(self):
        self.atomspace = AtomSpace()
        self.chainer = Chainer(self.atomspace)

    def tearDown(self):
        del self.atomspace
        del self.chainer        

    def _simple_atoms_1(self):
        atoms = []
        atoms.append( self.atomspace.add_node(types.ConceptNode, "animal") )
        atoms.append( self.atomspace.add_node(types.ConceptNode, "breathe") )
        atoms.append( self.atomspace.add_link(types.InheritanceLink, [atoms[0], atoms[1]]) )

        return atoms 

    def test__selectOne(self):
        atoms = self._simple_atoms_1()
        atoms[0].av = {'sti': 1}

        atom = self.chainer._selectOne(atoms)
        self.assertNotEquals(atom, None)
        self.assertEqual(atom, atoms[0])

        atoms[1].av = {'sti': 1}
        atoms[2].av = {'sti': 1}

        atom = self.chainer._selectOne(atoms)
        self.assertTrue(atom in atoms)

    def test_get_attentional_focus(self):
        atoms = self._simple_atoms_1()
        atoms[2].av = {'sti': 1}

        print atoms[2]

        contents = get_attentional_focus(self.atomspace)
        print contents
        self.assertEqual( len(contents), 1 )

    def test__select_one_matching(self):
        atoms = self._simple_atoms_1()
        atoms[2].av = {'sti': 1}

        template = atoms[2]

        result = self.chainer._select_one_matching(template)
        self.assertEqual( result, atoms[2] )

        

        atoms[0].av = {'sti': 1}

        print get_attentional_focus(self.atomspace)

        template = self.atomspace.add_node(types.VariableNode, "$v1")
        result = self.chainer._select_one_matching(template)
        self.assertNotEqual( result, None )

    def test__find_inputs_recursive(self):
        def apply(generic_inputs, generic_outputs):
            inputs = []
            outputs = []
            empty_substitution = {}
            status = self.chainer._find_inputs_recursive(inputs, outputs, generic_inputs, generic_outputs, empty_substitution)

            return (inputs, outputs)

        atoms = self._simple_atoms_1()
        
        # test it on lots of simple made up rules that include the edge cases
        # [] => []
        generic_inputs = []
        generic_outputs = []
        (inputs, outputs) = apply(generic_inputs, generic_outputs)
        self.assertEquals( inputs, [] )
        self.assertEquals( outputs, [] )

        # [animal] => []
        atoms[0].av = {'sti': 1}

        generic_inputs = [atoms[0]]
        generic_outputs = []
        (inputs, outputs) = apply(generic_inputs, generic_outputs)
        self.assertEquals( inputs, [atoms[0]] )
        self.assertEquals( outputs, [] )

        v1 = self.atomspace.add_node(types.VariableNode, "$v1")
        # [v1] => []
        generic_inputs = [v1]
        generic_outputs = []
        (inputs, outputs) = apply(generic_inputs, generic_outputs)
        self.assertEquals( len(inputs), 1 )
        self.assertEquals( outputs, [] )

        #from nose.tools import set_trace; set_trace()
        # [v1] => [v1]
        generic_inputs = [v1]
        generic_outputs = [v1]
        (inputs, outputs) = apply(generic_inputs, generic_outputs)
        print str(inputs[0])
        print str(outputs[0])
        self.assertEquals( len(inputs), 1 )
        self.assertEquals( len(outputs), 1 )
Example #11
0
class RulesTest(TestCase):
    def setUp(self):
        self.atomspace = AtomSpace()
        self.chainer = Chainer(self.atomspace)

    def tearDown(self):
        del self.atomspace
        del self.chainer

    def _inh_animal_breathe(self):
        '''InheritanceLink animal breathe'''
        default_av = {'sti':1}
        self.animal = self.atomspace.add_node(types.ConceptNode, "animal")
        self.breathe = self.atomspace.add_node(types.ConceptNode, "breathe")
        self.inh_animal_breathe = self.atomspace.add_link(types.InheritanceLink, [self.animal, self.breathe])

        self.animal.tv = TruthValue(0.1, 1)
        self.breathe.tv = TruthValue(0.1, 1)
        self.inh_animal_breathe.tv = TruthValue(1, 1)

        atoms = []
        atoms.append( self.animal )
        atoms.append( self.breathe )
        atoms.append( self.inh_animal_breathe )

        for atom in atoms:
            atom.av = default_av

        return atoms

#    def _apply_rule(self, rule, 

    def test_standardize_apart_input_output(self):
        rule = rules.InversionRule(self.chainer, types.InheritanceLink)

        (input, output) = rule.standardize_apart_input_output(self.chainer)

    def test_InversionRule(self):
        rule = rules.InversionRule(self.chainer, types.InheritanceLink)
        
        self._inh_animal_breathe()

        result = self.chainer._apply_forward(rule)
        print result

    def test_InversionRule_backward(self):
        rule = rules.InversionRule(self.chainer, types.InheritanceLink)
        
        self._inh_animal_breathe()
        self.inh_breathe_animal = self.atomspace.add_link(types.InheritanceLink, [self.breathe, self.animal])
        self.inh_breathe_animal.av = {'sti':1}

        result = self.chainer._apply_backward(rule)
        print result

    def disabled_test_rules_generically(self):
        '''See what happens if you give a rule the generic inputs. This makes sure that the rule and formula don't have any basic code errors, but doesn't check that they do the right thing.'''
        def apply_rule(rule):
            generic_inputs = rule.inputs
            generic_outpus = rule.outputs

            # Take the generic required input atoms and give them boring TVs
            for atom in generic_inputs:
                atom.av = {'sti':1}
                atom.tv = TruthValue(1, 1)

            status = self.chainer._apply_forward(rule)

            self.assertNotEquals(status, None)

            return None

        for rule in self.chainer.rules:
            apply_rule(rule)
Example #12
0
class AtomSpaceTest(TestCase):
    def setUp(self):
        self.space = AtomSpace()
        initialize_opencog(self.space)

    def tearDown(self):
        finalize_opencog()
        del self.space

    def test_add_node(self):

        # Test long form atomspace node addition.

        # Test node add
        self.space.add_node(types.Node, "node")

        # Test with not a proper truthvalue
        self.assertRaises(TypeError, self.space.add_node, types.Node, "test",
                          0, True)
        # Test with bad type
        self.assertRaises(TypeError, self.space.add_node, "ConceptNode",
                          "test", TruthValue(0.5, 0.8))

        # From here on out we'll use the more compact type constructors
        a1 = Node("test")
        self.assertTrue(a1)
        # duplicates resolve to same atom
        a2 = Node("test")
        self.assertEquals(a1, a2)

        # Should fail when intentionally adding bad type
        caught = False
        try:
            self.space.add_node(types.Link, "test")
        except RuntimeError:
            caught = True
        self.assertEquals(caught, True)

        # Test adding with a truthvalue
        a3 = Node("test_w_tv").truth_value(0.5, 0.8)
        self.assertEquals(self.space.size(), 3)

    def test_add_link(self):
        n1 = Node("test1")
        n2 = Node("test2")
        l1 = Link(n1, n2)
        self.assertTrue(l1 is not None)
        l2 = Link(n1, n2)
        self.assertTrue(l2 is not None)
        self.assertTrue(l2 == l1)

        n3 = Node("test3")
        l3 = Link(n1, n3).truth_value(0.5, 0.8)
        self.assertTrue(l3 is not None)

        # Should fail when adding an intentionally bad type
        caught = False
        try:
            l1 = self.space.add_link(types.Node, [n1, n3])
        except RuntimeError:
            caught = True
        self.assertEquals(caught, True)

    def test_is_valid(self):
        a1 = Node("test1")
        # check with Atom object
        self.assertTrue(self.space.is_valid(a1))
        # check with raw UUID
        self.assertTrue(self.space.is_valid(a1.value()))
        # check with bad UUID
        self.assertFalse(self.space.is_valid(2919))
        # check with bad type
        self.assertRaises(TypeError, self.space.is_valid, "test")

    def test_truth_value(self):
        # check attributes come back as assigned
        tv = TruthValue(0.5, 0.8)
        self.assertEqual(tv.mean, 0.5)
        self.assertAlmostEqual(tv.confidence, 0.8, places=4)
        # test string representation
        self.assertEqual(str(tv), "(stv 0.500000 0.800000)")

        # check equality
        tv2 = TruthValue(0.5, 0.8)
        tv3 = TruthValue(0.6, 0.8)
        self.assertTrue(tv == tv2)
        self.assertFalse(tv == tv3)

        # check truth_value function of atom
        atom = Node("atom with tv")
        default_tv = atom.tv
        atom.truth_value(0.75, 0.9)
        new_tv = atom.tv
        self.assertFalse(new_tv == default_tv)
        self.assertEqual(new_tv.mean, 0.75)
        self.assertAlmostEqual(new_tv.confidence, 0.9, places=4)

    def test_attention_value(self):
        node = Node("test")

        # check values come back as assigned
        node.sti = 1
        node.lti = 2
        node.vlti = 3
        assert node.sti == 1
        assert node.lti == 2
        assert node.vlti == 3

        # Check increment and decrement for vlti
        node.decrement_vlti()
        assert node.vlti == 2
        node.increment_vlti()
        assert node.vlti == 3

        # Check dictionary setting and getting of av property.
        node.av = {"sti": 4, "lti": 5, "vlti": 6}
        assert node.sti == 4
        assert node.lti == 5
        assert node.vlti == 6
        assert node.av == {"sti": 4, "lti": 5, "vlti": 6}

    def test_get_by_type(self):
        a1 = Node("test1")
        a2 = ConceptNode("test2")
        a3 = PredicateNode("test3")

        # test recursive subtypes
        result = self.space.get_atoms_by_type(types.Node)
        self.assertTrue(a1 in result)
        self.assertTrue(a2 in result)
        self.assertTrue(a3 in result)

        # links
        l1 = InheritanceLink(a1, a2)
        result = self.space.get_atoms_by_type(types.Link)
        self.assertTrue(l1 in result)

        # test non-recursive subtype
        result = self.space.get_atoms_by_type(types.Node, subtype=False)
        self.assertTrue(a1 in result)
        self.assertTrue(a2 not in result)
        self.assertTrue(a3 not in result)

        # test empty
        result = self.space.get_atoms_by_type(types.AnchorNode, subtype=False)
        self.assertEqual(len(result), 0)

    def test_get_by_av(self):
        a1 = ConceptNode("test1")
        a2 = ConceptNode("test2")
        a3 = InheritanceLink(a1, a2)
        a4 = ConceptNode("test4")
        a5 = ConceptNode("test5")

        a1.sti = 10
        a2.sti = 5
        a3.sti = 4
        a4.sti = 1

        result = self.space.get_atoms_by_av(4, 10)
        assert len(result) == 3
        assert set(result) == set([a1, a2, a3])
        assert a4 not in result

        result = self.space.get_atoms_in_attentional_focus()
        assert len(result) == 4
        assert set(result) == set([a1, a2, a3, a4])

    def test_incoming_by_type(self):
        a1 = Node("test1")
        a2 = ConceptNode("test2")
        a3 = PredicateNode("test3")

        # test no incoming Node for a1
        result = a1.incoming_by_type(types.Node)
        self.assertTrue(a1 not in result)

        # now check links
        l1 = InheritanceLink(a1, a2)
        result = a1.incoming_by_type(types.Link)
        self.assertTrue(l1 in result)
        result = a2.incoming_by_type(types.Link)
        self.assertTrue(l1 in result)
        result = a3.incoming_by_type(types.Link)
        self.assertTrue(l1 not in result)

    def test_include_incoming_outgoing(self):
        frog = ConceptNode("Frog")
        thing = ConceptNode("Thing")
        animal = ConceptNode("Animal")
        ConceptNode("SeparateThing")
        InheritanceLink(frog, animal)
        InheritanceLink(animal, thing)

        assert len(self.space.include_incoming([ConceptNode("Frog")])) == 2
        assert len(
            self.space.include_outgoing(
                self.space.include_incoming([ConceptNode("Frog")]))) == 3
        assert len(
            self.space.include_incoming(
                self.space.get_atoms_by_type(types.ConceptNode))) == 6
        assert len(
            self.space.include_outgoing(
                self.space.get_atoms_by_type(types.InheritanceLink))) == 5

    def test_remove(self):
        a1 = Node("test1")
        a2 = ConceptNode("test2")
        a3 = PredicateNode("test3")

        self.assertTrue(a1 in self.space)
        self.assertTrue(a2 in self.space)
        self.assertTrue(a3 in self.space)

        self.space.remove(a1)
        self.assertTrue(a1 not in self.space)
        self.assertTrue(a2 in self.space)
        self.assertTrue(a3 in self.space)

        l = SimilarityLink(a2, a3)
        self.space.remove(a2, True)  # won't remove it unless recursive is True
        self.assertTrue(a2 not in self.space)
        self.assertTrue(l not in self.space)

    def test_clear(self):
        a1 = Node("test1")
        a2 = ConceptNode("test2")
        a3 = PredicateNode("test3")
        self.space.clear()
        self.assertEquals(self.space.size(), 0)
        self.assertEquals(len(self.space), 0)

    def test_container_methods(self):
        self.assertEquals(len(self.space), 0)
        a1 = Node("test1")
        a2 = ConceptNode("test2")
        a3 = PredicateNode("test3")

        self.assertTrue(a1 in self.space)
        self.assertTrue(a2 in self.space)
        self.assertTrue(a3 in self.space)

        self.assertEquals(len(self.space), 3)

    def test_get_predicates(self):
        dog = ConceptNode("dog")
        mammal = ConceptNode("mammal")
        canine = ConceptNode("canine")
        animal = ConceptNode("animal")
        dog_mammal = ListLink(dog, mammal)
        dog_canine = ListLink(dog, canine)
        dog_animal = ListLink(dog, animal)
        isA = PredicateNode("IsA")
        dogIsAMammal = EvaluationLink(isA, dog_mammal)
        dogIsACanine = EvaluationLink(isA, dog_canine)
        dogIsAAnimal = EvaluationLink(isA, dog_animal)

        dog_predicates = self.space.get_predicates(dog)
        self.assertEquals(len(dog_predicates), 3)

        count = 0
        for dogIs in self.space.xget_predicates(dog):
            count += 1
        self.assertEquals(count, 3)

    def test_get_predicates_for(self):
        dog = ConceptNode("dog")
        mammal = ConceptNode("mammal")
        canine = ConceptNode("canine")
        animal = ConceptNode("animal")
        dog_mammal = ListLink(dog, mammal)
        dog_canine = ListLink(dog, canine)
        dog_animal = ListLink(dog, animal)
        isA = PredicateNode("IsA")
        dogIsAMammal = EvaluationLink(isA, dog_mammal)
        dogIsACanine = EvaluationLink(isA, dog_canine)
        dogIsAAnimal = EvaluationLink(isA, dog_animal)

        human = ConceptNode("human")
        dog_human = ListLink(dog, human)
        loves = PredicateNode("loves")
        dogLovesHumans = EvaluationLink(loves, dog_human)

        dog_predicates = self.space.get_predicates_for(dog, isA)
        self.assertEquals(len(dog_predicates), 3)

        dog_predicates = self.space.get_predicates_for(dog, loves)
        self.assertEquals(len(dog_predicates), 1)

        count = 0
        for dogIsA in self.space.xget_predicates_for(dog, isA):
            count += 1
        self.assertEquals(count, 3)

        count = 0
        for dogLoves in self.space.xget_predicates_for(dog, loves):
            count += 1
        self.assertEquals(count, 1)
Example #13
0
class Index:
    def __init__(self, storage: Storage):
        self.pattern_space = AtomSpace()
        self.semantic_space = AtomSpace()
        # storage maps index to atom
        self._storage = storage
        # index maps subgraph pattern to matching atom ids
        self._index = dict()

    def add_toplevel_pattern(self, atom):
        args = [
            self.pattern_space.add_node(types.VariableNode, '$X' + str(i))
            for i in range(atom.arity)
        ]
        l = self.pattern_space.add_link(atom.type, args)
        bindlink = self.pattern_space.add_link(types.BindLink, [l, l])
        self.add_pattern(bindlink)

    def add_semantic_pattern(self, atom):
        # find all nodes, that inherit from some atom from semantic atomspace
        # replace such atoms by variable nodes
        result = replace(atom, self.semantic_space, self.pattern_space, dict())
        pattern = self.pattern_space.add_link(types.BindLink, [result, result])
        self.add_pattern(pattern)

    def add_data(self, data):
        idx, new = self._storage.add_atom(data)
        if not new:
            return
        assert data.is_link()
        # self.add_toplevel_pattern(data)
        self.add_semantic_pattern(data)

        tmp = create_child_atomspace(self.pattern_space)
        content = tmp.add_atom(data)
        self.update_index(tmp, content, idx)

    def update_index(self, atomspace, data, idx):
        for pat in self._index.keys():
            match = execute_atom(atomspace, pat)
            # patterns can match patterns, so check:
            for m in match.out:
                if m == data:
                    self._index[pat].add(idx)

    def intersect(self, query):
        """
        Extracts relevant patterns to the query and intersects their indices
        returns set of atoms ids
        """
        # put query in tmp atomspace, check if there are relevant patterns
        tmp = create_child_atomspace(self.pattern_space)
        q = tmp.add_atom(rename(tmp, self.pattern_space, query))
        # check query for exact match:
        exact_match = execute_atom(tmp, tmp.add_link(types.BindLink, [q, q]))
        for m in exact_match.out:
            return self._index[self.pattern_space.add_link(
                types.BindLink, [m, m])]
        # no exact match: search among all patterns
        # todo: search subgraphs
        res_set = None
        for pat, idx in self._index.items():
            # pattern is relevant if it matches query
            match = execute_atom(tmp, pat)
            for m in match.out:
                if hash(m) == hash(q):
                    if res_set is None:
                        res_set = idx
                    else:
                        res_set = res_set.intersection(idx)
        return res_set

    def query(self, result_atomspace, query):
        res_set = self.intersect(query)
        # add all possible results to tmp atomspace and run query
        # what is called filter step in graph indexing literature
        tmp = AtomSpace()
        atom_str = self._storage.get_atoms(res_set)
        for item in atom_str:
            tmp.add_atom(scheme_eval_h(tmp, item))
        # pack query in BindLink
        q = tmp.add_link(types.BindLink, [query, query])
        results = execute_atom(tmp, q)
        result_atoms = set()
        for atom in results.out:
            result_atoms.add(result_atomspace.add_atom(atom))
        return result_atoms

    def update_index_dual_link(self, content):
        # doesn't work
        d = tmp.add_link(types.DualLink, [content])
        # result is a set of conditional parts from pattens(GetLinks)
        pattern_set = execute_atom(tmp, d)
        # todo: create a new pattern

        assert len(pattern_set.out)
        for pattern in pattern_set.out:
            get_link = self.pattern_space.add_link(types.GetLink, pattern)
            self._index[get_link].add(data)

    def add_pattern(self, pat):
        assert pat.type == types.BindLink
        atom = self.pattern_space.add_atom(pat)
        if atom not in self._index:
            self._index[atom] = set()
Example #14
0
# Sample from:
# https://wiki.opencog.org/w/Manipulating_Atoms_in_Python

from opencog.atomspace import AtomSpace, types

a = AtomSpace()
cat = a.add_node(types.ConceptNode, "Cat")
animal = a.add_node(types.ConceptNode, "Animal")
a.add_link(types.InheritanceLink, [cat, animal])

for atom in a:
    print (atom)

from opencog.utilities import initialize_opencog
from opencog.type_constructors import *
from opencog.bindlink import satisfying_set

initialize_opencog(a)

a.clear()

color = ConceptNode("Color")

InheritanceLink(ConceptNode("Red"), color)
InheritanceLink(ConceptNode("Green"), color)
InheritanceLink(ConceptNode("Blue"), color)

# Create a pattern to look for color nodes
varlink = TypedVariableLink(VariableNode("$xcol"), TypeNode("ConceptNode"))
pattern = InheritanceLink(VariableNode("$xcol"), color)
colornodes = GetLink(varlink, pattern)
# create_atoms_by_type.py
#
"""
Simple example of how to create atoms in the AtomSpace.
See also create_atomspace_simple.py for an alternate interface.
"""

from opencog.atomspace import AtomSpace, TruthValue, Atom
from opencog.atomspace import types

a = AtomSpace()

# Create a truth value asserting true and mostly confident.
TV = TruthValue(1, 0.8)

# Add three nodes
concept_type = types.ConceptNode
A = a.add_node(concept_type, 'Apple', TV)
B = a.add_node(concept_type, 'Berry', TruthValue(0.5, 0.75))
C = a.add_node(concept_type, 'Comestible', TV)

# Add three inhertance links, asserting that apples are berries
# and that berries are edible.
inh_type = types.InheritanceLink
AB = a.add_link(inh_type, [A, B], TV)
BC = a.add_link(inh_type, [B, C], TV)
AC = a.add_link(inh_type, [A, C])


print "The atomspace contains:\n\n", a.get_atoms_by_type(types.Atom)
            te = ForestExtractor(atomspace, GephiOutput(atomspace))
            te.output()
        except KeyError,  e:
            KeyError
        except Exception, e:
            import traceback; traceback.print_exc(file=sys.stdout)
        self.cycles+=1

print __name__
if __name__ == "__main__":
    a = AtomSpace()
    t=types
    bob = a.add_node(t.ConceptNode, "Bob")
    alice = a.add_node(t.ConceptNode, "Alice")
    link = a.add_link(t.ListLink, [bob, alice])
    link2 = a.add_link(t.ListLink, [alice, bob])

    link3 = a.add_link(t.EvaluationLink, [a.add_node(t.PredicateNode, "likes"), link2])

    obj1 = a.add_node(t.AccessoryNode, 'ball1')
    obj2 = a.add_node(t.StructureNode, 'tree1')
    next = a.add_link(t.EvaluationLink,
                   [a.add_node(t.PredicateNode, 'next'),
                    a.add_link(t.ListLink, [obj1, obj2])])

    next.tv = TruthValue(1, 1)

    arity3 = a.add_link(t.AndLink, [bob, alice, obj1])

    time = a.add_link(t.AtTimeLink, [a.add_node(t.TimeNode, "t-0"), a.add_node(t.ConceptNode, "blast-off")])
Example #17
0
class Manipulating_atoms_in_python(unittest.TestCase):
    def setUp(self):
        self.atsp = AtomSpace()
        self.TV = TruthValue()

    def test_making_atoms_cPlusPlus_syntax(self):
        cat = self.atsp.add_node(types.ConceptNode, "Cat")
        man = self.atsp.add_node(types.ConceptNode, "Man")
        animal = self.atsp.add_node(types.ConceptNode, "Animal")

        self.assertIsInstance(
            cat, Atom, "Not able to create node"
        )  # checks if the above created nodes are instances of Atom class

        print "Printing individual atoms in the atomspace"
        for atom in self.atsp:
            print atom

    def test_add_links_into_atomspace(self):
        man = self.atsp.add_node(types.ConceptNode, "Man")
        animal = self.atsp.add_node(types.ConceptNode, "Animal")
        inheritance_link = self.atsp.add_link(types.InheritanceLink,
                                              [man, animal])
        self.assertIsInstance(inheritance_link, Atom,
                              "Link not added to atomspace")

    def test_pattern_matching(self):

        #test pattern maching between difetent types of nodes
        initialize_opencog(self.atsp)
        self.scheme_animals = \
        '''
        (InheritanceLink (ConceptNode "Red") (ConceptNode "color"))
        (InheritanceLink (ConceptNode "Green") (ConceptNode "color"))
        (InheritanceLink (ConceptNode "Blue") (ConceptNode "color"))
        (InheritanceLink (ConceptNode "Spaceship") (ConceptNode "machine"))
        '''
        # create amodule or function in scheme
        self.scheme_query = \
        '''
        (define find-colors
        (BindLink
            ;; The variable to be bound
            (VariableNode "$xcol")

            ;; The pattern to be searched for
            (InheritanceLink
            (VariableNode "$xcol")
            (ConceptNode "color")
            )
            ;; The value to be returned.
            (VariableNode "$xcol")
        )
        )
        '''
        #use scheme module
        scheme_eval(self.atsp, "(use-modules (opencog))")
        scheme_eval(self.atsp, "(use-modules (opencog query))")
        scheme_eval_h(self.atsp, self.scheme_animals)
        scheme_eval_h(self.atsp, self.scheme_query)
        self.result = scheme_eval_h(self.atsp, '(cog-bind find-colors)')
        self.varlink = TypedVariableLink(VariableNode("$xcol"),
                                         TypeNode("ConceptNode"))
        self.pattern = InheritanceLink(VariableNode("$xcol"), self.test_color)
        self.colornodes = SatisfactionLink(self.varlink, self.pattern)
        self.assertEqual(self.result, satisfying_set(self.atsp,
                                                     self.colornodes))

    def test_making_atoms_scheme_syntax(self):

        pass
class AtomTest(TestCase):

    def setUp(self):
        self.space = AtomSpace()

    def test_creation(self):
        a = self.space.add_node(types.Node, "test1")
        self.assertEqual(a.name, "test1")
        self.assertEqual(a.tv, TruthValue(1.0, 0.0)) # default is true, no confidence

    def test_w_truthvalue(self):
        tv = TruthValue(0.5, 100)
        a = self.space.add_node(types.Node, "test2", tv)
        self.assertEqual(a.tv, tv)

        # test set tv
        a.tv = TruthValue(0.1, 10)
        self.assertEqual(a.tv, TruthValue(0.1, 10))
        
    def test_w_attention_value(self):
        a = self.space.add_node(types.Node, "test2")

        self.assertEqual(a.av, {'lti': 0, 'sti': 0, 'vlti': False})

        # test set av
        a.av = { "sti": 10, "lti": 1, "vlti": True }
        self.assertEqual(a.av, {'sti': 10, 'lti': 1, 'vlti': True})

    def test_out(self):
        # test get out
        a1 = self.space.add_node(types.Node, "test2")

        self.assertEqual(a1.out, [])

        tv = TruthValue(0.5, 100)
        a2 = self.space.add_node(types.Node, "test3", tv)

        l = self.space.add_link(types.Link, [a1, a2])
        self.assertEqual(l.out, [a1, a2])

        # ensure out is considered immutable
        self.assertRaises(AttributeError, setattr, l, "out", [a1])

    def test_arity(self):
        a1 = self.space.add_node(types.Node, "test2")

        self.assertEqual(a1.arity, 0)

        tv = TruthValue(0.5, 100)
        a2 = self.space.add_node(types.Node, "test3", tv)

        l = self.space.add_link(types.Link, [a1, a2])
        self.assertEqual(l.arity, 2)

        # ensure arity is considered immutable
        self.assertRaises(AttributeError, setattr, l, "arity", 4)

    def test_is_source(self):
        # any out item is a source for unordered links
        # only the fist item is a source of ordered links
        a1 = self.space.add_node(types.Node, "test1")
        a2 = self.space.add_node(types.Node, "test2")

        l_ordered = self.space.add_link(types.OrderedLink, [a1, a2])
        l_unordered = self.space.add_link(types.UnorderedLink, [a1, a2])

        self.assertEqual(l_ordered.is_source(a1), True)
        self.assertEqual(l_ordered.is_source(a2), False)

        self.assertEqual(l_unordered.is_source(a1), True)
        self.assertEqual(l_unordered.is_source(a2), True)

    def test_type(self):
        # test get out
        a = self.space.add_node(types.Node, "test2")

        self.assertEqual(a.type, 1)
        self.assertEqual(a.t, 1)

        a2 = self.space.add_node(types.Node, "test3")
        l = self.space.add_link(types.Link, [a, a2])
        self.assertEqual(l.type, 2)
        self.assertEqual(l.t, 2)

        # ensure type is considered immutable
        self.assertRaises(AttributeError, setattr, l, "type", 5)
        self.assertRaises(AttributeError, setattr, a, "type", 5)

        self.assertEqual(l.type_name, "Link")
        self.assertEqual(a.type_name, "Node")


    def test_strings(self):
        # set up a link and atoms
        tv = TruthValue(0.5, 100)
        a1 = self.space.add_node(types.Node, "test1", tv)

        a2 = self.space.add_node(types.Node, "test2")
        a2.av = {"sti": 10, "lti": 1, "vlti": True}
        a2.tv = TruthValue(0.1, 10)

        l = self.space.add_link(types.Link, [a1, a2])

        # test string representation
        a1_expected = "(Node \"test1\") ; [{0}]\n".format(str(a1.h.value()))
        a1_expected_long = \
            "(Node \"test1\" (av 0 0 0) (stv 0.500000 0.111111)) ; [{0}]\n"\
            .format(str(a1.h.value()))

        a2_expected = "(Node \"test2\") ; [{0}]\n".format(str(a2.h.value()))
        a2_expected_long = \
            "(Node \"test2\" (av 10 1 1) (stv 0.100000 0.012346)) ; [{0}]\n"\
            .format(str(a2.h.value()))

        l_expected = \
            "(Link (stv 1.000000 0.000000)\n  {0}  {1}) ; [{2}]\n"\
            .format(a1_expected, a2_expected, str(l.h.value()))
        l_expected_long = \
            "(Link (av 0 0 0) (stv 1.000000 0.000000)\n  {0}  {1}) ; [{2}]\n"\
            .format(a1_expected_long, a2_expected_long, str(l.h.value()))

        self.assertEqual(str(a2), a2_expected)
        self.assertEqual(a2.long_string(), a2_expected_long)
        self.assertEqual(str(l), l_expected)
        self.assertEqual(l.long_string(), l_expected_long)
Example #19
0
class AtomSpaceTest(TestCase):

    def setUp(self):
        self.space = AtomSpace()
        initialize_opencog(self.space)

    def tearDown(self):
        finalize_opencog()
        del self.space

    def test_add_node(self):

        # Test long form atomspace node addition.

        # Test node add
        self.space.add_node(types.Node, "node" )

        # Test with not a proper truthvalue
        self.assertRaises(TypeError, self.space.add_node, types.Node, "test", 
                0, True)
        # Test with bad type
        self.assertRaises(TypeError, self.space.add_node, "ConceptNode", "test", 
                TruthValue(0.5, 0.8))

        # From here on out we'll use the more compact type constructors
        a1 = Node("test")
        self.assertTrue(a1)
        # duplicates resolve to same atom
        a2 = Node("test")
        self.assertEquals(a1, a2)

        # Should fail when intentionally adding bad type
        caught = False
        try:
            self.space.add_node(types.Link, "test")
        except RuntimeError:
            caught = True
        self.assertEquals(caught, True)

        # Test adding with a truthvalue
        a3 = Node("test_w_tv").truth_value(0.5, 0.8)
        self.assertEquals(self.space.size(), 3)

    def test_add_link(self):
        n1 = Node("test1")
        n2 = Node("test2")
        l1 = Link(n1, n2)
        self.assertTrue(l1 is not None)
        l2 = Link(n1, n2)
        self.assertTrue(l2 is not None)
        self.assertTrue(l2 == l1)

        n3 = Node("test3")
        l3 = Link(n1, n3).truth_value(0.5, 0.8)
        self.assertTrue(l3 is not None)
        
        # Should fail when adding an intentionally bad type
        caught = False
        try:
            l1 = self.space.add_link(types.Node, [n1, n3])
        except RuntimeError:
            caught = True
        self.assertEquals(caught, True)

    def test_is_valid(self):
        a1 = Node("test1")
        # check with Atom object
        self.assertTrue(self.space.is_valid(a1))
        # check with bad type
        self.assertRaises(TypeError, self.space.is_valid, "test")

    def test_truth_value(self):
        # check attributes come back as assigned
        tv = TruthValue(0.5, 0.8)
        self.assertEqual(tv.mean, 0.5)
        self.assertAlmostEqual(tv.confidence, 0.8, places=4)
        # test string representation
        self.assertEqual(str(tv), "(stv 0.500000 0.800000)")

        # check equality
        tv2 = TruthValue(0.5, 0.8)
        tv3 = TruthValue(0.6, 0.8)
        self.assertTrue(tv == tv2)
        self.assertFalse(tv == tv3)

        # check truth_value function of atom
        atom = Node("atom with tv")
        default_tv = atom.tv
        atom.truth_value(0.75, 0.9)
        new_tv = atom.tv
        self.assertFalse(new_tv == default_tv)
        self.assertEqual(new_tv.mean, 0.75)
        self.assertAlmostEqual(new_tv.confidence, 0.9, places=4)

    def test_attention_value(self):
        node = Node("test")

        # check values come back as assigned
        node.sti = 1
        node.lti = 2
        node.vlti = 3
        assert node.sti == 1
        assert node.lti == 2
        assert node.vlti == 3

        # Check increment and decrement for vlti
        node.decrement_vlti()
        assert node.vlti == 2
        node.increment_vlti()
        assert node.vlti == 3

        # Check dictionary setting and getting of av property.
        node.av = {"sti": 4, "lti": 5, "vlti": 6}
        assert node.sti == 4
        assert node.lti == 5
        assert node.vlti == 6
        assert node.av == {"sti": 4, "lti": 5, "vlti": 6}

    def test_get_by_type(self):
        a1 = Node("test1")
        a2 = ConceptNode("test2")
        a3 = PredicateNode("test3")

        # test recursive subtypes
        result = self.space.get_atoms_by_type(types.Node)
        self.assertTrue(a1 in result)
        self.assertTrue(a2 in result)
        self.assertTrue(a3 in result)

        # links
        l1 = InheritanceLink(a1, a2)
        result = self.space.get_atoms_by_type(types.Link)
        self.assertTrue(l1 in result)
        
        # test non-recursive subtype
        result = self.space.get_atoms_by_type(types.Node, subtype=False)
        self.assertTrue(a1 in result)
        self.assertTrue(a2 not in result)
        self.assertTrue(a3 not in result)

        # test empty
        result = self.space.get_atoms_by_type(types.AnchorNode, subtype=False)
        self.assertEqual(len(result), 0)

    def test_get_by_av(self):
        a1 = ConceptNode("test1")
        a2 = ConceptNode("test2")
        a3 = InheritanceLink(a1, a2)
        a4 = ConceptNode("test4")
        a5 = ConceptNode("test5")

        a1.sti = 10
        a2.sti = 5
        a3.sti = 4
        a4.sti = 1

        #ImportanceIndex is Asynchronus give it some time
        sleep(1)

        result = self.space.get_atoms_by_av(4, 10)
        print "The atoms-by-av result is ", result
        assert len(result) == 3
        assert set(result) == set([a1, a2, a3])
        assert a4 not in result

        result = self.space.get_atoms_in_attentional_focus()
        assert len(result) == 4
        assert set(result) == set([a1, a2, a3, a4])

    def test_incoming_by_type(self):
        a1 = Node("test1")
        a2 = ConceptNode("test2")
        a3 = PredicateNode("test3")

        # test no incoming Node for a1
        result = a1.incoming_by_type(types.Node)
        self.assertTrue(a1 not in result)

        # now check links
        l1 = InheritanceLink(a1, a2)
        result = a1.incoming_by_type(types.InheritanceLink)
        self.assertTrue(l1 in result)
        result = a2.incoming_by_type(types.InheritanceLink)
        self.assertTrue(l1 in result)
        result = a3.incoming_by_type(types.InheritanceLink)
        self.assertTrue(l1 not in result)

    def test_include_incoming_outgoing(self):
        frog = ConceptNode("Frog")
        thing = ConceptNode("Thing")
        animal = ConceptNode("Animal")
        ConceptNode("SeparateThing")
        InheritanceLink(frog, animal)
        InheritanceLink(animal, thing)

        assert len(self.space.include_incoming([ConceptNode("Frog")])) == 2
        assert len(self.space.include_outgoing(self.space.include_incoming([ConceptNode("Frog")]))) == 3
        assert len(self.space.include_incoming(self.space.get_atoms_by_type(types.ConceptNode))) == 6
        assert len(self.space.include_outgoing(self.space.get_atoms_by_type(types.InheritanceLink))) == 5

    def test_remove(self):
        a1 = Node("test1")
        a2 = ConceptNode("test2")
        a3 = PredicateNode("test3")

        self.assertTrue(a1 in self.space)
        self.assertTrue(a2 in self.space)
        self.assertTrue(a3 in self.space)

        self.space.remove(a1)
        self.assertTrue(a1 not in self.space)
        self.assertTrue(a2 in self.space)
        self.assertTrue(a3 in self.space)

        l = SimilarityLink(a2, a3)
        self.space.remove(a2, True) # won't remove it unless recursive is True
        self.assertTrue(a2 not in self.space)
        self.assertTrue(l not in self.space)

    def test_clear(self):
        a1 = Node("test1")
        a2 = ConceptNode("test2")
        a3 = PredicateNode("test3")
        self.space.clear()
        self.assertEquals(self.space.size(), 0) 
        self.assertEquals(len(self.space), 0) 

    def test_container_methods(self):
        self.assertEquals(len(self.space), 0) 
        a1 = Node("test1")
        a2 = ConceptNode("test2")
        a3 = PredicateNode("test3")
        
        self.assertTrue(a1 in self.space)
        self.assertTrue(a2 in self.space)
        self.assertTrue(a3 in self.space)

        self.assertEquals(len(self.space), 3)

    def test_get_predicates(self):
        dog = ConceptNode("dog")
        mammal = ConceptNode("mammal")
        canine = ConceptNode("canine")
        animal = ConceptNode("animal")
        dog_mammal = ListLink(dog, mammal)
        dog_canine = ListLink(dog, canine)
        dog_animal = ListLink(dog, animal)
        isA = PredicateNode("IsA")
        dogIsAMammal = EvaluationLink(isA, dog_mammal)
        dogIsACanine = EvaluationLink(isA, dog_canine)
        dogIsAAnimal = EvaluationLink(isA, dog_animal)

        dog_predicates = self.space.get_predicates(dog)
        self.assertEquals(len(dog_predicates), 3)

        count = 0
        for dogIs in self.space.xget_predicates(dog):
            count += 1
        self.assertEquals(count, 3)

    def test_get_predicates_for(self):
        dog = ConceptNode("dog")
        mammal = ConceptNode("mammal")
        canine = ConceptNode("canine")
        animal = ConceptNode("animal")
        dog_mammal = ListLink(dog, mammal)
        dog_canine = ListLink(dog, canine)
        dog_animal = ListLink(dog, animal)
        isA = PredicateNode("IsA")
        dogIsAMammal = EvaluationLink(isA, dog_mammal)
        dogIsACanine = EvaluationLink(isA, dog_canine)
        dogIsAAnimal = EvaluationLink(isA, dog_animal)

        human = ConceptNode("human")
        dog_human = ListLink(dog, human)
        loves = PredicateNode("loves")
        dogLovesHumans = EvaluationLink(loves, dog_human)

        dog_predicates = self.space.get_predicates_for(dog, isA)
        self.assertEquals(len(dog_predicates), 3)

        dog_predicates = self.space.get_predicates_for(dog, loves)
        self.assertEquals(len(dog_predicates), 1)

        count = 0
        for dogIsA in self.space.xget_predicates_for(dog, isA):
            count += 1
        self.assertEquals(count, 3)

        count = 0
        for dogLoves in self.space.xget_predicates_for(dog, loves):
            count += 1
        self.assertEquals(count, 1)
Example #20
0
class AtomTest(TestCase):
    def setUp(self):
        self.space = AtomSpace()

    def test_creation(self):
        a = self.space.add_node(types.Node, "test1")
        self.assertEqual(a.name, "test1")
        self.assertEqual(a.tv, TruthValue(0.0, 0.0))

    def test_w_truthvalue(self):
        tv = TruthValue(0.5, 100)
        a = self.space.add_node(types.Node, "test2", tv)
        self.assertEqual(a.tv, tv)

        # test set tv
        a.tv = TruthValue(0.1, 10)
        self.assertEqual(a.tv, TruthValue(0.1, 10))

    def test_w_attention_value(self):
        a = self.space.add_node(types.Node, "test2")

        self.assertEqual(a.av, {'lti': 0, 'sti': 0, 'vlti': False})

        # test set av
        a.av = {"sti": 10, "lti": 1, "vlti": True}
        self.assertEqual(a.av, {'sti': 10, 'lti': 1, 'vlti': True})

    def test_out(self):
        # test get out
        a1 = self.space.add_node(types.Node, "test2")

        self.assertEqual(a1.out, [])

        tv = TruthValue(0.5, 100)
        a2 = self.space.add_node(types.Node, "test3", tv)

        l = self.space.add_link(types.Link, [a1, a2])
        self.assertEqual(l.out, [a1, a2])

        # ensure out is considered immutable
        self.assertRaises(AttributeError, setattr, l, "out", [a1])

    def test_arity(self):
        a1 = self.space.add_node(types.Node, "test2")

        self.assertEqual(a1.arity, 0)

        tv = TruthValue(0.5, 100)
        a2 = self.space.add_node(types.Node, "test3", tv)

        l = self.space.add_link(types.Link, [a1, a2])
        self.assertEqual(l.arity, 2)

        # ensure arity is considered immutable
        self.assertRaises(AttributeError, setattr, l, "arity", 4)

    def test_is_source(self):
        # any out item is a source for unordered links
        # only the fist item is a source of ordered links
        a1 = self.space.add_node(types.Node, "test1")
        a2 = self.space.add_node(types.Node, "test2")

        l_ordered = self.space.add_link(types.OrderedLink, [a1, a2])
        l_unordered = self.space.add_link(types.UnorderedLink, [a1, a2])

        self.assertEqual(l_ordered.is_source(a1), True)
        self.assertEqual(l_ordered.is_source(a2), False)

        self.assertEqual(l_unordered.is_source(a1), True)
        self.assertEqual(l_unordered.is_source(a2), True)

    def test_type(self):
        # test get out
        a = self.space.add_node(types.Node, "test2")

        self.assertEqual(a.type, 1)
        self.assertEqual(a.t, 1)

        a2 = self.space.add_node(types.Node, "test3")
        l = self.space.add_link(types.Link, [a, a2])
        self.assertEqual(l.type, 2)
        self.assertEqual(l.t, 2)

        # ensure type is considered immutable
        self.assertRaises(AttributeError, setattr, l, "type", 5)
        self.assertRaises(AttributeError, setattr, a, "type", 5)

        self.assertEqual(l.type_name, "Link")
        self.assertEqual(a.type_name, "Node")

    def test_strings(self):
        # set up a link and atoms
        tv = TruthValue(0.5, 100)
        a1 = self.space.add_node(types.Node, "test1", tv)

        a2 = self.space.add_node(types.Node, "test2")
        a2.av = {"sti": 10, "lti": 1, "vlti": True}
        a2.tv = TruthValue(0.1, 10)

        l = self.space.add_link(types.Link, [a1, a2])

        # test string representation
        self.assertEqual(str(a2), "node[Node:test2]")
        self.assertEqual(
            a2.long_string(),
            "node[Node:test2] av:(10,1) tv:([0.100000,10.000000=0.012346])")
        self.assertEqual(str(l), "[Link <test1,test2> 0.0 0.0]")
        self.assertEqual(
            l.long_string(),
            "link[Link sti:(0,0) tv:([0.000000,0.000000=0.000000]) <[Node test1],[Node test2]>]"
        )
Example #21
0
if __name__ == '__main__':
    atomspace = AtomSpace()

    # jade.ATOMS
    ENTITY = atomspace.add_node('VariableNode', '$ENTITY')
    BLOCK =  atomspace.add_node('VariableNode', '$BLOCK')
    COLOR =  atomspace.add_node('VariableNode', '$COLOR')
    
    atomspace.add_link('ForAllLink',
        [atomspace.add_link('ListLink', [ENTITY, BLOCK, COLOR]),
         atomspace.add_link('ImplicationLink',
             [atomspace.add_link('AndLink',
                 [atomspace.add_link('EvaluationLink',
                    [atomspace.add_node('PredicateNode', 'part-of'),
                     atomspace.add_link('ListLink', [BLOCK, ENTITY])]),
                  atomspace.add_link('EvaluationLink',
                      [atomspace.add_node('PredicateNode', 'color'),
                       atomspace.add_link('ListLink', [BLOCK, COLOR])])]),
              atomspace.add_link('EvaluationLink',
                  [atomspace.add_node('PredicateNode', 'contains-block-of-color'),
                   atomspace.add_link('ListLink', [ENTITY, COLOR])
                  ])
             ])
        ], _default_tv)

    ENTITY1 = atomspace.add_node('VariableNode','$ENTITY1')
    ENTITY2 = atomspace.add_node('VariableNode','$ENTITY2')
    CATEGORY = atomspace.add_node('VariableNode','$CATEGORY')

    atomspace.add_link('ForAllLink',
        [atomspace.add_link('ListLink', [ENTITY1, ENTITY2, CATEGORY]),
         atomspace.add_link('ImplicationLink',
Example #22
0
See:
https://github.com/opencog/opencog/issues/530

Currently, it is represented the same way that Relex2Logic outputs it,
which is not going to work properly.
"""

__author__ = 'Cosmo Harrigan'

from opencog.atomspace import AtomSpace, TruthValue, types

atomspace = AtomSpace()

Socrates = atomspace.add_node(types.ConceptNode, "Socrates")
Man = atomspace.add_node(types.ConceptNode, "man")
Air = atomspace.add_node(types.ConceptNode, "air")
be = atomspace.add_node(types.PredicateNode, "be")
breathe = atomspace.add_node(types.PredicateNode, "breathe")

atomspace.add_link(
    types.EvaluationLink,
    [be, atomspace.add_link(types.ListLink, [Socrates, Man])],
    TruthValue(1,
               TruthValue().confidence_to_count(1)))

atomspace.add_link(
    types.EvaluationLink,
    [breathe, atomspace.add_link(types.ListLink, [Man, Air])],
    TruthValue(1,
               TruthValue().confidence_to_count(1)))
Example #23
0
Python-formatted data definitions for smokes_example.py

The Scheme-formatted definitions are in this file:
  https://github.com/opencog/test-datasets/blob/master/pln/tuffy/smokes/smokes.scm
They are also defined here in Python format for testing.
"""

__author__ = 'Cosmo Harrigan'

from opencog.atomspace import AtomSpace, TruthValue, types

atomspace = AtomSpace()

# Basic variable definitions
X = atomspace.add_node(types.VariableNode, "$X")
lX = atomspace.add_link(types.ListLink, [X])

Y = atomspace.add_node(types.VariableNode, "$Y")
lY = atomspace.add_link(types.ListLink, [Y])

X_Y = atomspace.add_link(types.ListLink, [X, Y])

full_confidence = TruthValue().confidence_to_count(1)
crisp_true = TruthValue(1, full_confidence)

# Anna smokes.
Anna = atomspace.add_node(types.ConceptNode, "Anna")
smokes = atomspace.add_node(types.PredicateNode, "smokes")
atomspace.add_link(types.EvaluationLink,
                   [smokes, atomspace.add_link(types.ListLink, [Anna])],
                   crisp_true)
#
# create_atoms_by_type.py
#
"""
Simple example of how to create atoms in the AtomSpace.
See also create_atomspace_simple.py for an alternate interface.
"""

from opencog.atomspace import AtomSpace, TruthValue, Atom
from opencog.atomspace import types

a = AtomSpace()

# Create a truth value asserting true and mostly confident.
TV = TruthValue(1, 0.8)

# Add three nodes
concept_type = types.ConceptNode
A = a.add_node(concept_type, 'Apple', TV)
B = a.add_node(concept_type, 'Berry', TruthValue(0.5, 0.75))
C = a.add_node(concept_type, 'Comestible', TV)

# Add three inhertance links, asserting that apples are berries
# and that berries are edible.
inh_type = types.InheritanceLink
AB = a.add_link(inh_type, [A, B], TV)
BC = a.add_link(inh_type, [B, C], TV)
AC = a.add_link(inh_type, [A, C])

print "The atomspace contains:\n\n", a.get_atoms_by_type(types.Atom)
Example #25
0
__author__ = 'Cosmo Harrigan'

# Create an AtomSpace with some sample information, equivalent to the information in atomspace_contents.scm
atomspace = AtomSpace()

# Basic concepts
frog = atomspace.add_node(types.ConceptNode, 'Frog', TruthValue(0.01, 100))
intelligent = atomspace.add_node(types.ConceptNode, 'Intelligent', TruthValue(0.05, 100))
slimy = atomspace.add_node(types.ConceptNode, 'Slimy', TruthValue(0.01, 100))
animal = atomspace.add_node(types.ConceptNode, 'Animal', TruthValue(0.1, 100))
being = atomspace.add_node(types.ConceptNode, 'Being', TruthValue(0.1, 100))
moves = atomspace.add_node(types.PredicateNode, 'Moves', TruthValue(0.1, 100))

# Attributes of frogs
atomspace.add_link(types.InheritanceLink, [frog, intelligent], TruthValue(0.2, 100))
atomspace.add_link(types.InheritanceLink, [frog, slimy], TruthValue(0.5, 100))
atomspace.add_link(types.InheritanceLink, [frog, animal], TruthValue(0.9, 100))

# Attributes of animals
atomspace.add_link(types.InheritanceLink, [animal, being], TruthValue(0.9, 100))
atomspace.add_link(types.InheritanceLink, [animal, moves], TruthValue(0.9, 100))

# Peter is a frog
peter = atomspace.add_node(types.ConceptNode, 'Peter', TruthValue(0.001, 100))
atomspace.add_link(types.InheritanceLink, [peter, frog], TruthValue(0.9, 100))

#print('AtomSpace starting contents:')
#atomspace.print_list()

# Test multiple steps of forward inference on the AtomSpace
# Create an AtomSpace with some sample information, equivalent to the
# information in atomspace_contents.scm
atomspace = AtomSpace()

# Basic concepts
frog = atomspace.add_node(types.ConceptNode, 'Frog', TruthValue(0.01, 100))
intelligent = atomspace.add_node(types.ConceptNode, 'Intelligent',
                                 TruthValue(0.05, 100))
slimy = atomspace.add_node(types.ConceptNode, 'Slimy', TruthValue(0.01, 100))
animal = atomspace.add_node(types.ConceptNode, 'Animal', TruthValue(0.1, 100))
being = atomspace.add_node(types.ConceptNode, 'Being', TruthValue(0.1, 100))
moves = atomspace.add_node(types.PredicateNode, 'Moves', TruthValue(0.1, 100))

# Attributes of frogs
atomspace.add_link(types.InheritanceLink, [frog, intelligent],
                   TruthValue(0.2, 100))
atomspace.add_link(types.InheritanceLink, [frog, slimy], TruthValue(0.5, 100))
atomspace.add_link(types.InheritanceLink, [frog, animal], TruthValue(0.9, 100))

# Attributes of animals
atomspace.add_link(types.InheritanceLink, [animal, being],
                   TruthValue(0.9, 100))
atomspace.add_link(types.InheritanceLink, [animal, moves],
                   TruthValue(0.9, 100))

# Peter is a frog
peter = atomspace.add_node(types.ConceptNode, 'Peter', TruthValue(0.001, 100))
atomspace.add_link(types.InheritanceLink, [peter, frog], TruthValue(0.9, 100))

#print('AtomSpace starting contents:')
#atomspace.print_list()
Example #27
0
class AtomSpaceTest(TestCase):
    def setUp(self):
        self.space = AtomSpace()

    def tearDown(self):
        del self.space

    def test_add_node(self):

        a1 = self.space.add_node(types.Node, "test")
        self.assertTrue(a1)
        # duplicates resolve to same handle
        a2 = self.space.add_node(types.Node, "test")
        self.assertEquals(a1, a2)

        # Should fail when intentionally adding bad type
        # self.assertRaises(RuntimeError, self.space.add_node(types.Link, "test"))
        caught = False
        try:
            self.space.add_node(types.Link, "test")
        except RuntimeError:
            caught = True
        self.assertEquals(caught, True)

        # test adding with a truthvalue
        a3 = self.space.add_node(types.Node, "test_w_tv", TruthValue(0.5, 100))
        self.assertEquals(self.space.size(), 2)

        # test adding with prefixed node
        a1 = self.space.add_node(types.Node, "test", prefixed=True)
        a2 = self.space.add_node(types.Node, "test", prefixed=True)
        self.assertNotEqual(a1, a2)
        self.assertEquals(self.space.size(), 4)

        a3 = self.space.add_node(types.Node,
                                 "test",
                                 TruthValue(0.5, 100),
                                 prefixed=True)
        self.assertNotEqual(a1, a3)
        self.assertEquals(self.space.size(), 5)

        # tests with bad parameters
        # test with not a proper truthvalue
        self.assertRaises(TypeError, self.space.add_node, types.Node, "test",
                          0, True)
        # test with bad type
        self.assertRaises(TypeError, self.space.add_node, "ConceptNode",
                          "test", TruthValue(0.5, 100))

    def test_add_link(self):
        n1 = self.space.add_node(types.Node, "test1")
        n2 = self.space.add_node(types.Node, "test2")
        l1 = self.space.add_link(types.Link, [n1, n2])
        self.assertTrue(l1 is not None)
        l2 = self.space.add_link(types.Link, [n1, n2])
        self.assertTrue(l2 is not None)
        self.assertTrue(l2 == l1)

        n3 = self.space.add_node(types.Node, "test3")
        l3 = self.space.add_link(types.Link, [n1, n3], TruthValue(0.5, 100))
        self.assertTrue(l3 is not None)
        # Test with a handle instead of atom
        l4 = self.space.add_link(types.Link, [n2.h, n3], TruthValue(0.5, 100))
        self.assertTrue(l4 is not None)

        # Should fail when adding an intentionally bad type
        caught = False
        try:
            l1 = self.space.add_link(types.Node, [n1, n3])
        except RuntimeError:
            caught = True
        self.assertEquals(caught, True)

    def test_is_valid(self):
        h1 = self.space.add_node(types.Node, "test1")
        # check with Handle object
        self.assertTrue(self.space.is_valid(h1.h))
        # check with raw UUID
        self.assertTrue(self.space.is_valid(h1.h.value()))
        # check with bad UUID
        self.assertFalse(self.space.is_valid(2919))
        # check with bad type
        self.assertRaises(TypeError, self.space.is_valid, "test")

    def test_truth_value(self):
        # check attributes come back as assigned
        tv = TruthValue(0.5, 100)
        self.assertEqual(tv.mean, 0.5)
        self.assertEqual(tv.count, 100)
        # test confidence
        self.assertAlmostEqual(tv.confidence, 0.1111, places=4)
        # test string representation
        self.assertEqual(str(tv), "(stv 0.500000 0.111111)")

        # check equality
        tv2 = TruthValue(0.5, 100)
        tv3 = TruthValue(0.6, 100)
        self.assertTrue(tv == tv2)
        self.assertFalse(tv == tv3)

    def test_get_by_name_and_type(self):
        n1 = self.space.add_node(types.Node, "test")
        n2 = self.space.add_node(types.ConceptNode, "test")
        n3 = self.space.add_node(types.PredicateNode, "test")

        # test recursive subtypes
        result = self.space.get_atoms_by_name(types.Node, "test")
        self.assertTrue(n1 in result)
        self.assertTrue(n2 in result)
        self.assertTrue(n3 in result)

        # test non-recursive subtype
        result = self.space.get_atoms_by_name(types.Node,
                                              "test",
                                              subtype=False)
        self.assertTrue(n1 in result)
        self.assertTrue(n2 not in result)
        self.assertTrue(n3 not in result)

        # test empty
        result = self.space.get_atoms_by_name(types.AnchorNode,
                                              "test",
                                              subtype=False)
        self.assertEqual(len(result), 0)

    def test_get_by_type(self):
        h1 = self.space.add_node(types.Node, "test1")
        h2 = self.space.add_node(types.ConceptNode, "test2")
        h3 = self.space.add_node(types.PredicateNode, "test3")

        # test recursive subtypes
        result = self.space.get_atoms_by_type(types.Node)
        self.assertTrue(h1 in result)
        self.assertTrue(h2 in result)
        self.assertTrue(h3 in result)

        # links
        l1 = self.space.add_link(types.InheritanceLink, [h1, h2])
        result = self.space.get_atoms_by_type(types.Link)
        self.assertTrue(l1 in result)

        # test non-recursive subtype
        result = self.space.get_atoms_by_type(types.Node, subtype=False)
        self.assertTrue(h1 in result)
        self.assertTrue(h2 not in result)
        self.assertTrue(h3 not in result)

        # test empty
        result = self.space.get_atoms_by_type(types.AnchorNode, subtype=False)
        self.assertEqual(len(result), 0)

    def test_get_by_target_type(self):
        h1 = self.space.add_node(types.Node, "test1")
        h2 = self.space.add_node(types.ConceptNode, "test2")
        h3 = self.space.add_node(types.PredicateNode, "test3")

        # test it doesn't apply to Nodes
        result = self.space.get_atoms_by_target_type(types.Node, types.Node)
        self.assertTrue(h1 not in result)

        # links
        l1 = self.space.add_link(types.InheritanceLink, [h1.h, h2.h])
        result = self.space.get_atoms_by_target_type(types.Link,
                                                     types.ConceptNode,
                                                     target_subtype=False)
        self.assertTrue(l1 in result)

        # test recursive target subtype
        result = self.space.get_atoms_by_target_type(types.Link,
                                                     types.Node,
                                                     target_subtype=True)
        self.assertTrue(l1 in result)

    def test_get_by_target_atom(self):
        h1 = self.space.add_node(types.Node, "test1")
        h2 = self.space.add_node(types.ConceptNode, "test2")
        h3 = self.space.add_node(types.PredicateNode, "test3")

        # test it doesn't apply to Nodes
        result = self.space.get_atoms_by_target_atom(types.Node, h1)
        self.assertTrue(h1 not in result)

        # links
        l1 = self.space.add_link(types.InheritanceLink, [h1, h2])
        result = self.space.get_atoms_by_target_atom(types.Link, h1)
        self.assertTrue(l1 in result)
        result = self.space.get_atoms_by_target_atom(types.Link, h3)
        self.assertTrue(l1 not in result)

    def test_remove(self):
        h1 = self.space.add_node(types.Node, "test1")
        h2 = self.space.add_node(types.ConceptNode, "test2")
        h3 = self.space.add_node(types.PredicateNode, "test3")

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

        self.space.remove(h1)
        self.assertTrue(h1 not in self.space)
        self.assertTrue(h2 in self.space)
        self.assertTrue(h3 in self.space)

        l = self.space.add_link(types.SimilarityLink, [h2, h3])
        self.space.remove(h2,
                          False)  # won't remove it unless recursive is True
        self.assertTrue(h2 in self.space)
        self.space.remove(h2, True)  # won't remove it unless recursive is True
        self.assertTrue(h2 not in self.space)
        self.assertTrue(l not in self.space)

    def test_clear(self):
        h1 = self.space.add_node(types.Node, "test1")
        h2 = self.space.add_node(types.ConceptNode, "test2")
        h3 = self.space.add_node(types.PredicateNode, "test3")
        self.space.clear()
        self.assertEquals(self.space.size(), 0)
        self.assertEquals(self.space.size(), 0)
        self.assertEquals(len(self.space), 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.assertTrue(len(self.space), 3)
Example #28
0
class AtomTest(TestCase):
    def setUp(self):
        self.space = AtomSpace()

    def test_creation(self):
        a = self.space.add_node(types.Node, "test1")
        self.assertEqual(a.name, "test1")
        self.assertEqual(a.tv,
                         TruthValue(1.0,
                                    0.0))  # default is true, no confidence

    def test_w_truthvalue(self):
        tv = TruthValue(0.5, 100)
        a = self.space.add_node(types.Node, "test2", tv)
        self.assertEqual(a.tv, tv)

        # test set tv
        a.tv = TruthValue(0.1, 10)
        self.assertEqual(a.tv, TruthValue(0.1, 10))

    def test_w_attention_value(self):
        a = self.space.add_node(types.Node, "test2")

        self.assertEqual(a.av, {'lti': 0, 'sti': 0, 'vlti': False})

        # test set av
        a.av = {"sti": 10, "lti": 1, "vlti": True}
        self.assertEqual(a.av, {'sti': 10, 'lti': 1, 'vlti': True})

    def test_out(self):
        # test get out
        a1 = self.space.add_node(types.Node, "test2")

        self.assertEqual(a1.out, [])

        tv = TruthValue(0.5, 100)
        a2 = self.space.add_node(types.Node, "test3", tv)

        l = self.space.add_link(types.Link, [a1, a2])
        self.assertEqual(l.out, [a1, a2])

        # ensure out is considered immutable
        self.assertRaises(AttributeError, setattr, l, "out", [a1])

    def test_arity(self):
        a1 = self.space.add_node(types.Node, "test2")

        self.assertEqual(a1.arity, 0)

        tv = TruthValue(0.5, 100)
        a2 = self.space.add_node(types.Node, "test3", tv)

        l = self.space.add_link(types.Link, [a1, a2])
        self.assertEqual(l.arity, 2)

        # ensure arity is considered immutable
        self.assertRaises(AttributeError, setattr, l, "arity", 4)

    def test_is_source(self):
        # any out item is a source for unordered links
        # only the fist item is a source of ordered links
        a1 = self.space.add_node(types.Node, "test1")
        a2 = self.space.add_node(types.Node, "test2")

        l_ordered = self.space.add_link(types.OrderedLink, [a1, a2])
        l_unordered = self.space.add_link(types.UnorderedLink, [a1, a2])

        self.assertEqual(l_ordered.is_source(a1), True)
        self.assertEqual(l_ordered.is_source(a2), False)

        self.assertEqual(l_unordered.is_source(a1), True)
        self.assertEqual(l_unordered.is_source(a2), True)

    def test_type(self):
        # test get out
        a = self.space.add_node(types.Node, "test2")

        self.assertEqual(a.type, 1)
        self.assertEqual(a.t, 1)

        a2 = self.space.add_node(types.Node, "test3")
        l = self.space.add_link(types.Link, [a, a2])
        self.assertEqual(l.type, 2)
        self.assertEqual(l.t, 2)

        # ensure type is considered immutable
        self.assertRaises(AttributeError, setattr, l, "type", 5)
        self.assertRaises(AttributeError, setattr, a, "type", 5)

        self.assertEqual(l.type_name, "Link")
        self.assertEqual(a.type_name, "Node")

    def test_strings(self):
        # set up a link and atoms
        tv = TruthValue(0.5, 100)
        a1 = self.space.add_node(types.Node, "test1", tv)

        a2 = self.space.add_node(types.Node, "test2")
        a2.av = {"sti": 10, "lti": 1, "vlti": True}
        a2.tv = TruthValue(0.1, 10)

        l = self.space.add_link(types.Link, [a1, a2])

        # test string representation
        a1_expected = "(Node \"test1\") ; [{0}]\n".format(str(a1.h.value()))
        a1_expected_long = \
            "(Node \"test1\" (av 0 0 0) (stv 0.500000 0.111111)) ; [{0}]\n"\
            .format(str(a1.h.value()))

        a2_expected = "(Node \"test2\") ; [{0}]\n".format(str(a2.h.value()))
        a2_expected_long = \
            "(Node \"test2\" (av 10 1 1) (stv 0.100000 0.012346)) ; [{0}]\n"\
            .format(str(a2.h.value()))

        l_expected = \
            "(Link (stv 1.000000 0.000000)\n  {0}  {1}) ; [{2}]\n"\
            .format(a1_expected, a2_expected, str(l.h.value()))
        l_expected_long = \
            "(Link (av 0 0 0) (stv 1.000000 0.000000)\n  {0}  {1}) ; [{2}]\n"\
            .format(a1_expected_long, a2_expected_long, str(l.h.value()))

        self.assertEqual(str(a2), a2_expected)
        self.assertEqual(a2.long_string(), a2_expected_long)
        self.assertEqual(str(l), l_expected)
        self.assertEqual(l.long_string(), l_expected_long)
class TestMap(unittest.TestCase):

    def setUp(self):
        self.atomspace = AtomSpace()
        resolution = 1
        floor_height = -255
        agent_height = 1.6
        self.testmap = Octree3DMapManager.init_new_map(self.atomspace, "testmap", resolution,
                                                       floor_height, agent_height)

    def tearDown(self):
        del self.testmap
        del self.atomspace

    def test_GetMapName(self):
        self.assertEqual("testmap", self.testmap.get_map_name())

    def test_GetBlock_NoBlockAdded_ReturnUndefinedHandle(self):
        test_pos = (7, 8, 9)

        test_handle = self.testmap.get_block(test_pos)

        self.assertTrue(test_handle.is_undefined())

    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))

    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())

    def testSetBlock_AddBlockWithProbabilityControl_GetFunctionsWorkWithProb(self):
        test_pos1 = (7, 8, 9)
        test_handle1 = Handle(100)
        log_odds_threshold = self.testmap.get_log_odds_occupied_threshold()

        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))

        #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_log_odds_occupied_threshold(-0.2)
        log_odds_threshold = self.testmap.get_log_odds_occupied_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))

    def testStandable_NormalBlock_Standable(self):
        #case1: single block
        test_pos = (1, 2, 4)
        block_pos = (1, 2, 3)
        self.assertFalse(self.testmap.check_standable(test_pos))
        test_block = self.atomspace.add_node(types.StructureNode, "block1").h
        material_node = self.atomspace.add_node(types.ConceptNode, "dirt").h
        material_pred_node = self.atomspace.add_node(types.PredicateNode, "material").h
        list_link = self.atomspace.add_link(types.ListLink, [test_block,material_node]).h
        eval_link = self.atomspace.add_link(types.EvaluationLink,
                                            [material_pred_node,list_link]).h
        self.testmap.add_solid_unit_block(test_block, block_pos)

        standable = self.testmap.check_standable(test_pos)

        self.assertTrue(standable)

    def testStandable_WaterBlock_Unstandable(self):
        #case2: single block which is water, cannot stand on water
        test_pos = (1, 2, 4)
        block_pos = (1, 2, 3)
        self.assertFalse(self.testmap.check_standable(test_pos))
        test_block = self.atomspace.add_node(types.StructureNode, "block1").h
        material_node = self.atomspace.add_node(types.ConceptNode, "water").h
        material_pred_node = self.atomspace.add_node(types.PredicateNode, "material").h
        list_link = self.atomspace.add_link(types.ListLink, [test_block,material_node]).h
        eval_link = self.atomspace.add_link(types.EvaluationLink,
                                          [material_pred_node,list_link]).h
        self.testmap.add_solid_unit_block(test_block, block_pos)

        standable = self.testmap.check_standable(test_pos)

        self.assertFalse(standable)


    def testStandable_TwoNearBlock_Unstandable(self):
        # case3: two block which z coord is close ( ditance < agentHeight)
        # so it's not standable
        test_pos = (1, 2, 4)
        block_pos1 = (1, 2, 3)
        self.assertFalse(self.testmap.check_standable(test_pos))
        test_block1 = self.atomspace.add_node(types.StructureNode, "block1").h
        material_node1 = self.atomspace.add_node(types.ConceptNode, "dirt").h
        material_pred_node = self.atomspace.add_node(types.PredicateNode,"material").h
        list_link1 = self.atomspace.add_link(types.ListLink, [test_block1,material_node1]).h
        eval_link1 = self.atomspace.add_link(types.EvaluationLink,
                                             [material_pred_node,list_link1]).h
        self.testmap.add_solid_unit_block(test_block1, block_pos1)

        blockpos2 = (1, 2, 5)
        testBlock2 = self.atomspace.add_node(types.StructureNode, "block2").h
        material_node2 = self.atomspace.add_node(types.ConceptNode, "stone").h
        material_pred_node = self.atomspace.add_node(types.PredicateNode, "material").h
        list_link2 = self.atomspace.add_link(types.ListLink, [testBlock2, material_node2]).h
        eval_link2 = self.atomspace.add_link(types.EvaluationLink,
                                             [material_pred_node,list_link2]).h
        self.testmap.add_solid_unit_block(testBlock2, blockpos2)
        self.assertFalse(self.testmap.get_block(blockpos2).is_undefined())
        self.assertFalse(self.testmap.get_block(block_pos1).is_undefined())
        standable = self.testmap.check_standable(test_pos)

        self.assertFalse(standable)

    def testAddandRemoveNoneBlockEntity_NormalEntity_AllGetFunctionsWork(self):
        test_pos = (17, 28, 39)
        timestamp = 12345
        test_handle1 = self.atomspace.add_node(types.EntityNode, "entity").h
        entity_is_self = False
        entity_is_avatar = False

        self.testmap.add_none_block_entity(test_handle1,test_pos,
                                           entity_is_self, entity_is_avatar,
                                           timestamp)

        test_handle2 = self.testmap.get_entity(test_pos)
        self.assertEqual(test_handle1, test_handle2)
        self.assertEqual(test_pos, self.testmap.get_last_appeared_location(test_handle1))
        self.testmap.remove_none_block_entity(test_handle1)

        self.assertTrue(self.testmap.get_entity(test_pos).is_undefined())
        #preserve record
        self.assertEqual(test_pos, self.testmap.get_last_appeared_location(test_handle1))

    def testUpdateEntityLocation_MultipleLocation_LastLocationIsPos2(self):
        test_pos1 = (17, 28, 39)
        timestamp1 = 12345
        test_handle1 = self.atomspace.add_node(types.EntityNode, "entity").h
        entity_is_self = False
        entity_is_avatar = False

        self.testmap.add_none_block_entity(test_handle1, test_pos1,
                                           entity_is_self, entity_is_avatar,
                                           timestamp1)

        test_pos2 = (17, 28, 40)
        timestamp2 = 12346
        self.testmap.update_none_block_entity_location(test_handle1, test_pos2, timestamp2)
        last_location = self.testmap.get_last_appeared_location(test_handle1)

        self.assertEqual(test_pos2, last_location)

    def testAddEntity_PressureTest(self):
        count = 10000
        timestamp = 12345
        while count != 0:
            print count
            count -= 1
            test_pos = (count, count, count)
            test_handle1 = self.atomspace.add_node(types.EntityNode, "entity"+str(count)).h
            entity_is_self = False
            entity_is_avatar = False

            self.testmap.add_none_block_entity(test_handle1, test_pos,
                                               entity_is_self, entity_is_avatar, timestamp)
            test_handle2 = self.testmap.get_entity(test_pos)
            self.assertEqual(test_handle1, test_handle2)
            self.assertEqual(test_pos,self.testmap.get_last_appeared_location(test_handle1))
            self.testmap.remove_none_block_entity(test_handle1)

            self.assertTrue(self.testmap.get_entity(test_pos).is_undefined())
            #preserve record
            self.assertEqual(test_pos,self.testmap.get_last_appeared_location(test_handle1))
Example #30
0
                        elem = elem.split(')')
                        concepts.append(elem[0])

                    # Construct OpenCog atoms

                    predicate_node = atomspace.add_node(
                        types.PredicateNode, predicate)

                    # ConceptNodes
                    concept_nodes = []
                    for concept in concepts:
                        concept_nodes.append(atomspace.add_node(
                            types.ConceptNode, concept))

                    # ListLink
                    list_link = atomspace.add_link(
                        types.ListLink, concept_nodes, crisp_true)

                    # EvaluationLink
                    eval_link = atomspace.add_link(
                        types.EvaluationLink, [predicate_node, list_link])
                    new_link = eval_link

                    # Determine whether the predicate is negated, and create
                    # a NotLink if necessary.
                    if negated:
                        # NotLink
                        not_link = atomspace.add_link(types.NotLink, [eval_link])

                        # TruthValue
                        atomspace.set_tv(not_link.h, crisp_true)
Example #31
0
class AtomSpaceTest(TestCase):

    def setUp(self):
        self.space = AtomSpace()
        initialize_opencog(self.space)

    def tearDown(self):
        finalize_opencog()
        del self.space

    def test_add_node(self):

        # Test long form atomspace node addition.

        # Test node add
        self.space.add_node(types.Node, "node" )

        # Test with not a proper truthvalue
        self.assertRaises(TypeError, self.space.add_node, types.Node, "test",
                0, True)
        # Test with bad type
        self.assertRaises(TypeError, self.space.add_node, "ConceptNode", "test",
                TruthValue(0.5, 0.8))

        # From here on out we'll use the more compact type constructors
        a1 = Node("test")
        self.assertTrue(a1)
        # duplicates resolve to same atom
        a2 = Node("test")
        self.assertEquals(a1, a2)

        # Should fail when intentionally adding bad type
        caught = False
        try:
            self.space.add_node(types.Link, "test")
        except RuntimeError:
            caught = True
        self.assertEquals(caught, True)

        # Test adding with a truthvalue
        a3 = Node("test_w_tv").truth_value(0.5, 0.8)
        self.assertEquals(self.space.size(), 3)

    def test_add_link(self):
        n1 = Node("test1")
        n2 = Node("test2")
        l1 = Link(n1, n2)
        self.assertTrue(l1 is not None)
        l2 = Link(n1, n2)
        self.assertTrue(l2 is not None)
        self.assertTrue(l2 == l1)

        n3 = Node("test3")
        l3 = Link(n1, n3).truth_value(0.5, 0.8)
        self.assertTrue(l3 is not None)

        # Should fail when adding an intentionally bad type
        caught = False
        try:
            l1 = self.space.add_link(types.Node, [n1, n3])
        except RuntimeError:
            caught = True
        self.assertEquals(caught, True)

    def test_is_valid(self):
        a1 = Node("test1")
        # check with Atom object
        self.assertTrue(self.space.is_valid(a1))
        # check with bad type
        self.assertRaises(TypeError, self.space.is_valid, "test")

    def test_truth_value(self):
        # check attributes come back as assigned
        tv = TruthValue(0.5, 0.8)
        self.assertEqual(tv.mean, 0.5)
        self.assertAlmostEqual(tv.confidence, 0.8, places=4)
        # test string representation
        self.assertEqual(str(tv), "(stv 0.500000 0.800000)")

        # check equality
        tv2 = TruthValue(0.5, 0.8)
        tv3 = TruthValue(0.6, 0.8)
        self.assertTrue(tv == tv2)
        self.assertFalse(tv == tv3)

        # check truth_value function of atom
        atom = Node("atom with tv")
        default_tv = atom.tv
        atom.truth_value(0.75, 0.9)
        new_tv = atom.tv
        self.assertFalse(new_tv == default_tv)
        self.assertEqual(new_tv.mean, 0.75)
        self.assertAlmostEqual(new_tv.confidence, 0.9, places=4)

    def test_get_by_type(self):
        a1 = Node("test1")
        a2 = ConceptNode("test2")
        a3 = PredicateNode("test3")

        # test recursive subtypes
        result = self.space.get_atoms_by_type(types.Node)
        self.assertTrue(a1 in result)
        self.assertTrue(a2 in result)
        self.assertTrue(a3 in result)

        # links
        l1 = InheritanceLink(a1, a2)
        result = self.space.get_atoms_by_type(types.Link)
        self.assertTrue(l1 in result)

        # test non-recursive subtype
        result = self.space.get_atoms_by_type(types.Node, subtype=False)
        self.assertTrue(a1 in result)
        self.assertTrue(a2 not in result)
        self.assertTrue(a3 not in result)

        # test empty
        result = self.space.get_atoms_by_type(types.AnchorNode, subtype=False)
        self.assertEqual(len(result), 0)

    def test_incoming_by_type(self):
        a1 = Node("test1")
        a2 = ConceptNode("test2")
        a3 = PredicateNode("test3")

        # test no incoming Node for a1
        result = a1.incoming_by_type(types.Node)
        self.assertTrue(a1 not in result)

        # now check links
        l1 = InheritanceLink(a1, a2)
        result = a1.incoming_by_type(types.InheritanceLink)
        self.assertTrue(l1 in result)
        result = a2.incoming_by_type(types.InheritanceLink)
        self.assertTrue(l1 in result)
        result = a3.incoming_by_type(types.InheritanceLink)
        self.assertTrue(l1 not in result)

    def test_include_incoming_outgoing(self):
        frog = ConceptNode("Frog")
        thing = ConceptNode("Thing")
        animal = ConceptNode("Animal")
        ConceptNode("SeparateThing")
        InheritanceLink(frog, animal)
        InheritanceLink(animal, thing)

        assert len(self.space.include_incoming([ConceptNode("Frog")])) == 2
        assert len(self.space.include_outgoing(self.space.include_incoming([ConceptNode("Frog")]))) == 3
        assert len(self.space.include_incoming(self.space.get_atoms_by_type(types.ConceptNode))) == 6
        assert len(self.space.include_outgoing(self.space.get_atoms_by_type(types.InheritanceLink))) == 5

    def test_remove(self):
        a1 = Node("test1")
        a2 = ConceptNode("test2")
        a3 = PredicateNode("test3")

        self.assertTrue(a1 in self.space)
        self.assertTrue(a2 in self.space)
        self.assertTrue(a3 in self.space)

        self.space.remove(a1)
        self.assertTrue(a1 not in self.space)
        self.assertTrue(a2 in self.space)
        self.assertTrue(a3 in self.space)

        l = SimilarityLink(a2, a3)
        self.space.remove(a2, True) # won't remove it unless recursive is True
        self.assertTrue(a2 not in self.space)
        self.assertTrue(l not in self.space)

    def test_clear(self):
        a1 = Node("test1")
        a2 = ConceptNode("test2")
        a3 = PredicateNode("test3")
        self.space.clear()
        self.assertEquals(self.space.size(), 0)
        self.assertEquals(len(self.space), 0)

    def test_container_methods(self):
        self.assertEquals(len(self.space), 0)
        a1 = Node("test1")
        a2 = ConceptNode("test2")
        a3 = PredicateNode("test3")

        self.assertTrue(a1 in self.space)
        self.assertTrue(a2 in self.space)
        self.assertTrue(a3 in self.space)

        self.assertEquals(len(self.space), 3)

    def test_context_mgr_tmp(self):
        a = ConceptNode('a')
        with tmp_atomspace() as tmp_as:
             b = ConceptNode('b')
             self.assertTrue(a in self.space)
             # verify that current default atomspace is tmp_as
             self.assertFalse(b in self.space)
        c = ConceptNode('c')
        # verify that current default atomspace is self.space
        self.assertTrue(c in self.space)
Example #32
0
class MyTestCase(unittest.TestCase):
    def setUp(self):
        # self.atsp = scheme_eval_as('(cog-atomspace)')
        self.atsp = AtomSpace()  #creating atomspace
        self.TV = TruthValue()
        self.test_dog = self.atsp.add_node(types.ConceptNode, "Dog", self.TV)
        self.test_cat = self.atsp.add_node(types.ConceptNode, "Cat", self.TV)
        self.test_animal = self.atsp.add_node(types.ConceptNode, "Animal",
                                              self.TV)
        self.test_color = self.atsp.add_node(types.ConceptNode, "color",
                                             self.TV)
        initialize_opencog(self.atsp)

    def TearDown(self):
        del self.atsp

    def test_add_node(self):
        #test whether the node is created or not
        self.test_cat_value = scheme_eval_h(self.atsp, "(ConceptNode \"Cat\")")
        self.assertEqual(self.test_cat_value, self.test_cat)
        self.assertIsInstance(test_cat, Atom)

    def test_add_link(self):
        #test whether the link is created between the node
        self.cat_animal = self.atsp.add_link(types.InheritanceLink,
                                             [self.test_cat, self.test_animal])

        self.assertEqual(InheritanceLink(self.test_cat, self.test_animal),
                         self.cat_animal)
        self.assertIsInstance(self.cat_animal, Atom)

    def test_remove_node(self):
        #test whether the node that is crated is removed or not
        self.assertEqual(True, self.atsp.remove(self.test_cat))

    def test_pattern_match(self):
        #test pattern maching between difetent types of nodes

        self.scheme_animals = \
        '''
        (InheritanceLink (ConceptNode "Red") (ConceptNode "color"))
        (InheritanceLink (ConceptNode "Green") (ConceptNode "color"))
        (InheritanceLink (ConceptNode "Blue") (ConceptNode "color"))
        (InheritanceLink (ConceptNode "Spaceship") (ConceptNode "machine"))
        '''
        # create amodule or function in scheme
        self.scheme_query = \
        '''
        (define find-colors
        (BindLink
            ;; The variable to be bound
            (VariableNode "$xcol")

            ;; The pattern to be searched for
            (InheritanceLink
            (VariableNode "$xcol")
            (ConceptNode "color")
            )
            ;; The value to be returned.
            (VariableNode "$xcol")
        )
        )
        '''
        #use scheme module
        scheme_eval(self.atsp, "(use-modules (opencog))")
        scheme_eval(self.atsp, "(use-modules (opencog query))")
        scheme_eval_h(self.atsp, self.scheme_animals)
        scheme_eval_h(self.atsp, self.scheme_query)
        self.result = scheme_eval_h(self.atsp, '(cog-bind find-colors)')
        self.varlink = TypedVariableLink(VariableNode("$xcol"),
                                         TypeNode("ConceptNode"))
        self.pattern = InheritanceLink(VariableNode("$xcol"), self.test_color)
        self.colornodes = SatisfactionLink(self.varlink, self.pattern)
        self.assertEqual(self.result, satisfying_set(self.atsp,
                                                     self.colornodes))
Example #33
0
class AtomSpaceTest(TestCase):
    def setUp(self):
        self.space = AtomSpace()

    def tearDown(self):
        del self.space

    def test_add_node(self):

        a1 = self.space.add_node(types.Node, "test")
        self.assertTrue(a1)
        # duplicates resolve to same handle
        a2 = self.space.add_node(types.Node, "test")
        self.assertEquals(a1, a2)

        # Should fail when intentionally adding bad type
        # self.assertRaises(RuntimeError, self.space.add_node(types.Link, "test"))
        caught = False
        try:
            self.space.add_node(types.Link, "test")
        except RuntimeError:
            caught = True
        self.assertEquals(caught, True)

        # test adding with a truthvalue
        a3 = self.space.add_node(types.Node, "test_w_tv", TruthValue(0.5, 100))
        self.assertEquals(self.space.size(), 2)

        ### FIXME TODO -- re-enable this test after the prefixing code is
        ###
        ### # test adding with prefixed node
        ### a1 = self.space.add_node(types.Node, "test", prefixed=True)
        ### a2 = self.space.add_node(types.Node, "test", prefixed=True)
        ### self.assertNotEqual(a1, a2)
        ### self.assertEquals(self.space.size(), 4)
        ###
        ### a3 = self.space.add_node(types.Node, "test", TruthValue(0.5, 100), prefixed=True)
        ### self.assertNotEqual(a1, a3)
        ### self.assertEquals(self.space.size(), 5)

        # tests with bad parameters
        # test with not a proper truthvalue
        self.assertRaises(TypeError, self.space.add_node, types.Node, "test",
                          0, True)
        # test with bad type
        self.assertRaises(TypeError, self.space.add_node, "ConceptNode",
                          "test", TruthValue(0.5, 100))

    def test_add_link(self):
        n1 = self.space.add_node(types.Node, "test1")
        n2 = self.space.add_node(types.Node, "test2")
        l1 = self.space.add_link(types.Link, [n1, n2])
        self.assertTrue(l1 is not None)
        l2 = self.space.add_link(types.Link, [n1, n2])
        self.assertTrue(l2 is not None)
        self.assertTrue(l2 == l1)

        n3 = self.space.add_node(types.Node, "test3")
        l3 = self.space.add_link(types.Link, [n1, n3], TruthValue(0.5, 100))
        self.assertTrue(l3 is not None)
        # Test with a handle instead of atom
        l4 = self.space.add_link(types.Link, [n2.h, n3], TruthValue(0.5, 100))
        self.assertTrue(l4 is not None)

        # Should fail when adding an intentionally bad type
        caught = False
        try:
            l1 = self.space.add_link(types.Node, [n1, n3])
        except RuntimeError:
            caught = True
        self.assertEquals(caught, True)

    def test_is_valid(self):
        h1 = self.space.add_node(types.Node, "test1")
        # check with Handle object
        self.assertTrue(self.space.is_valid(h1.h))
        # check with raw UUID
        self.assertTrue(self.space.is_valid(h1.h.value()))
        # check with bad UUID
        self.assertFalse(self.space.is_valid(2919))
        # check with bad type
        self.assertRaises(TypeError, self.space.is_valid, "test")

    def test_truth_value(self):
        # check attributes come back as assigned
        tv = TruthValue(0.5, 100)
        self.assertEqual(tv.mean, 0.5)
        self.assertEqual(tv.count, 100)
        # test confidence
        self.assertAlmostEqual(tv.confidence, 0.1111, places=4)
        # test string representation
        self.assertEqual(str(tv), "(stv 0.500000 0.111111)")

        # check equality
        tv2 = TruthValue(0.5, 100)
        tv3 = TruthValue(0.6, 100)
        self.assertTrue(tv == tv2)
        self.assertFalse(tv == tv3)

    def test_get_by_name_and_type(self):
        n1 = self.space.add_node(types.Node, "test")
        n2 = self.space.add_node(types.ConceptNode, "test")
        n3 = self.space.add_node(types.PredicateNode, "test")

        # test recursive subtypes
        result = self.space.get_atoms_by_name(types.Node, "test")
        self.assertTrue(n1 in result)
        self.assertTrue(n2 in result)
        self.assertTrue(n3 in result)

        # test non-recursive subtype
        result = self.space.get_atoms_by_name(types.Node,
                                              "test",
                                              subtype=False)
        self.assertTrue(n1 in result)
        self.assertTrue(n2 not in result)
        self.assertTrue(n3 not in result)

        # test empty
        result = self.space.get_atoms_by_name(types.AnchorNode,
                                              "test",
                                              subtype=False)
        self.assertEqual(len(result), 0)

    def test_get_by_type(self):
        h1 = self.space.add_node(types.Node, "test1")
        h2 = self.space.add_node(types.ConceptNode, "test2")
        h3 = self.space.add_node(types.PredicateNode, "test3")

        # test recursive subtypes
        result = self.space.get_atoms_by_type(types.Node)
        self.assertTrue(h1 in result)
        self.assertTrue(h2 in result)
        self.assertTrue(h3 in result)

        # links
        l1 = self.space.add_link(types.InheritanceLink, [h1, h2])
        result = self.space.get_atoms_by_type(types.Link)
        self.assertTrue(l1 in result)

        # test non-recursive subtype
        result = self.space.get_atoms_by_type(types.Node, subtype=False)
        self.assertTrue(h1 in result)
        self.assertTrue(h2 not in result)
        self.assertTrue(h3 not in result)

        # test empty
        result = self.space.get_atoms_by_type(types.AnchorNode, subtype=False)
        self.assertEqual(len(result), 0)

    def test_get_by_av(self):
        h1 = self.space.add_node(types.ConceptNode, "test1")
        h2 = self.space.add_node(types.ConceptNode, "test2")
        h3 = self.space.add_link(types.InheritanceLink, [h1, h2])
        h4 = self.space.add_node(types.ConceptNode, "test4")
        h5 = self.space.add_node(types.ConceptNode, "test5")

        self.space.set_av(h=h1.h, sti=10)
        self.space.set_av(h=h2.h, sti=5)
        self.space.set_av(h=h3.h, sti=4)
        self.space.set_av(h=h4.h, sti=1)

        result = self.space.get_atoms_by_av(4, 10)
        assert len(result) == 3
        assert set(result) == set([h1, h2, h3])
        assert h4 not in result

        result = self.space.get_atoms_in_attentional_focus()
        assert len(result) == 4
        assert set(result) == set([h1, h2, h3, h4])

    def test_get_by_target_atom(self):
        h1 = self.space.add_node(types.Node, "test1")
        h2 = self.space.add_node(types.ConceptNode, "test2")
        h3 = self.space.add_node(types.PredicateNode, "test3")

        # test it doesn't apply to Nodes
        result = self.space.get_atoms_by_target_atom(types.Node, h1)
        self.assertTrue(h1 not in result)

        # links
        l1 = self.space.add_link(types.InheritanceLink, [h1, h2])
        result = self.space.get_atoms_by_target_atom(types.Link, h1)
        self.assertTrue(l1 in result)
        result = self.space.get_atoms_by_target_atom(types.Link, h3)
        self.assertTrue(l1 not in result)

    def test_include_incoming_outgoing(self):
        frog = self.space.add_node(types.ConceptNode, "Frog")
        thing = self.space.add_node(types.ConceptNode, "Thing")
        animal = self.space.add_node(types.ConceptNode, "Animal")
        self.space.add_node(types.ConceptNode, "SeparateThing")
        self.space.add_link(types.InheritanceLink, [frog, animal])
        self.space.add_link(types.InheritanceLink, [animal, thing])

        assert len(
            self.space.include_incoming(
                self.space.get_atoms_by_name(types.ConceptNode, "Frog"))) == 2
        assert len(
            self.space.include_incoming(
                self.space.get_atoms_by_type(types.ConceptNode))) == 6
        assert len(
            self.space.include_outgoing(
                self.space.get_atoms_by_type(types.InheritanceLink))) == 5
        assert len(
            self.space.include_outgoing(
                self.space.include_incoming(
                    self.space.get_atoms_by_name(types.ConceptNode,
                                                 "Frog")))) == 3

    def test_remove(self):
        h1 = self.space.add_node(types.Node, "test1")
        h2 = self.space.add_node(types.ConceptNode, "test2")
        h3 = self.space.add_node(types.PredicateNode, "test3")

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

        self.space.remove(h1)
        self.assertTrue(h1 not in self.space)
        self.assertTrue(h2 in self.space)
        self.assertTrue(h3 in self.space)

        l = self.space.add_link(types.SimilarityLink, [h2, h3])
        self.space.remove(h2, True)  # won't remove it unless recursive is True
        self.assertTrue(h2 not in self.space)
        self.assertTrue(l not in self.space)

    def test_clear(self):
        h1 = self.space.add_node(types.Node, "test1")
        h2 = self.space.add_node(types.ConceptNode, "test2")
        h3 = self.space.add_node(types.PredicateNode, "test3")
        self.space.clear()
        self.assertEquals(self.space.size(), 0)
        self.assertEquals(self.space.size(), 0)
        self.assertEquals(len(self.space), 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)

    def test_get_predicates(self):
        dog = self.space.add_node(types.ConceptNode, "dog")
        mammal = self.space.add_node(types.ConceptNode, "mammal")
        canine = self.space.add_node(types.ConceptNode, "canine")
        animal = self.space.add_node(types.ConceptNode, "animal")
        dog_mammal = self.space.add_link(types.ListLink, [dog, mammal])
        dog_canine = self.space.add_link(types.ListLink, [dog, canine])
        dog_animal = self.space.add_link(types.ListLink, [dog, animal])
        isA = self.space.add_node(types.PredicateNode, "IsA")
        dogIsAMammal = self.space.add_link(types.EvaluationLink,
                                           [isA, dog_mammal])
        dogIsACanine = self.space.add_link(types.EvaluationLink,
                                           [isA, dog_canine])
        dogIsAAnimal = self.space.add_link(types.EvaluationLink,
                                           [isA, dog_animal])

        dog_predicates = self.space.get_predicates(dog)
        self.assertEquals(len(dog_predicates), 3)

        count = 0
        for dogIs in self.space.xget_predicates(dog):
            count += 1
        self.assertEquals(count, 3)

    def test_get_predicates_for(self):
        dog = self.space.add_node(types.ConceptNode, "dog")
        mammal = self.space.add_node(types.ConceptNode, "mammal")
        canine = self.space.add_node(types.ConceptNode, "canine")
        animal = self.space.add_node(types.ConceptNode, "animal")
        dog_mammal = self.space.add_link(types.ListLink, [dog, mammal])
        dog_canine = self.space.add_link(types.ListLink, [dog, canine])
        dog_animal = self.space.add_link(types.ListLink, [dog, animal])
        isA = self.space.add_node(types.PredicateNode, "IsA")
        dogIsAMammal = self.space.add_link(types.EvaluationLink,
                                           [isA, dog_mammal])
        dogIsACanine = self.space.add_link(types.EvaluationLink,
                                           [isA, dog_canine])
        dogIsAAnimal = self.space.add_link(types.EvaluationLink,
                                           [isA, dog_animal])

        human = self.space.add_node(types.ConceptNode, "human")
        dog_human = self.space.add_link(types.ListLink, [dog, human])
        loves = self.space.add_node(types.PredicateNode, "loves")
        dogLovesHumans = self.space.add_link(types.EvaluationLink,
                                             [loves, dog_human])

        dog_predicates = self.space.get_predicates_for(dog, isA)
        self.assertEquals(len(dog_predicates), 3)

        dog_predicates = self.space.get_predicates_for(dog, loves)
        self.assertEquals(len(dog_predicates), 1)

        count = 0
        for dogIsA in self.space.xget_predicates_for(dog, isA):
            count += 1
        self.assertEquals(count, 3)

        count = 0
        for dogLoves in self.space.xget_predicates_for(dog, loves):
            count += 1
        self.assertEquals(count, 1)
Example #34
0
class AtomSpaceTest(TestCase):

    def setUp(self):
        self.space = AtomSpace()

    def tearDown(self):
        del self.space

    def test_add_node(self):

        a1 = self.space.add_node(types.Node,"test")
        self.assertTrue(a1)
        # duplicates resolve to same handle
        a2 = self.space.add_node(types.Node,"test")
        self.assertEquals(a1,a2)

        # fails when adding with a link type
        a1 = self.space.add_node(types.Link,"test")
        self.assertEquals(a1,None)

        # test adding with a truthvalue
        a3 = self.space.add_node(types.Node,"test_w_tv",TruthValue(0.5,100))
        self.assertEquals(self.space.size(),2)

        # test adding with prefixed node
        a1 = self.space.add_node(types.Node,"test",prefixed=True)
        a2 = self.space.add_node(types.Node,"test",prefixed=True)
        self.assertNotEqual(a1,a2)
        self.assertEquals(self.space.size(),4)

        a3 = self.space.add_node(types.Node,"test",TruthValue(0.5,100),prefixed=True)
        self.assertNotEqual(a1,a3)
        self.assertEquals(self.space.size(),5)

        # tests with bad parameters
        # test with not a proper truthvalue
        self.assertRaises(TypeError,self.space.add_node,types.Node,"test",0,True)
        # test with bad type
        self.assertRaises(TypeError,self.space.add_node,"ConceptNode","test",TruthValue(0.5,100))

    def test_add_link(self):
        n1 = self.space.add_node(types.Node,"test1")
        n2 = self.space.add_node(types.Node,"test2")
        l1 = self.space.add_link(types.Link,[n1,n2])
        self.assertTrue(l1 is not None)
        l2 = self.space.add_link(types.Link,[n1,n2])
        self.assertTrue(l2 is not None)
        self.assertTrue(l2 == l1)

        n3 = self.space.add_node(types.Node,"test3")
        l3 = self.space.add_link(types.Link,[n1,n3],TruthValue(0.5,100))
        self.assertTrue(l3 is not None)
        # test with a handle instead of atom
        l4 = self.space.add_link(types.Link,[n2.h,n3],TruthValue(0.5,100))
        self.assertTrue(l4 is not None)

        # fails when adding with a node type
        l1 = self.space.add_link(1,[n1,n3])
        self.assertEquals(l1,None)

    def test_is_valid(self):
        h1 = self.space.add_node(types.Node,"test1")
        # check with Handle object
        self.assertTrue(self.space.is_valid(h1.h))
        # check with raw UUID
        self.assertTrue(self.space.is_valid(h1.h.value()))
        # check with bad UUID
        self.assertFalse(self.space.is_valid(2919))
        # check with bad type
        self.assertRaises(TypeError,self.space.is_valid,"test")

    def test_truth_value(self):
        # check attributes come back as assigned
        tv = TruthValue(0.5, 100)
        self.assertEqual(tv.mean,0.5)
        self.assertEqual(tv.count,100)
        # test confidence
        self.assertAlmostEqual(tv.confidence,0.1111,places=4)
        # test string representation
        self.assertEqual(str(tv),"[0.500000,100.000000=0.111111]")

        # check equality
        tv2 = TruthValue(0.5, 100)
        tv3 = TruthValue(0.6, 100)
        self.assertTrue(tv == tv2)
        self.assertFalse(tv == tv3)

    def test_get_by_name_and_type(self):
        n1 = self.space.add_node(types.Node,"test")
        n2 = self.space.add_node(types.ConceptNode,"test")
        n3 = self.space.add_node(types.PredicateNode,"test")

        # test recursive subtypes
        result = self.space.get_atoms_by_name(types.Node,"test")
        self.assertTrue(n1 in result)
        self.assertTrue(n2 in result)
        self.assertTrue(n3 in result)

        # test non-recursive subtype
        result = self.space.get_atoms_by_name(types.Node,"test",subtype=False)
        self.assertTrue(n1 in result)
        self.assertTrue(n2 not in result)
        self.assertTrue(n3 not in result)

        # test empty
        result = self.space.get_atoms_by_name(types.SemeNode,"test",subtype=False)
        self.assertEqual(len(result),0)

    def test_get_by_type(self):
        h1 = self.space.add_node(types.Node,"test1")
        h2 = self.space.add_node(types.ConceptNode,"test2")
        h3 = self.space.add_node(types.PredicateNode,"test3")

        # test recursive subtypes
        result = self.space.get_atoms_by_type(types.Node)
        self.assertTrue(h1 in result)
        self.assertTrue(h2 in result)
        self.assertTrue(h3 in result)

        # links
        l1 = self.space.add_link(types.InheritanceLink,[h1,h2])
        result = self.space.get_atoms_by_type(types.Link)
        self.assertTrue(l1 in result)
        
        # test non-recursive subtype
        result = self.space.get_atoms_by_type(types.Node,subtype=False)
        self.assertTrue(h1 in result)
        self.assertTrue(h2 not in result)
        self.assertTrue(h3 not in result)

        # test empty
        result = self.space.get_atoms_by_type(types.SemeNode,subtype=False)
        self.assertEqual(len(result),0)

    def test_get_by_target_type(self):
        h1 = self.space.add_node(types.Node,"test1")
        h2 = self.space.add_node(types.ConceptNode,"test2")
        h3 = self.space.add_node(types.PredicateNode,"test3")

        # test it doesn't apply to Nodes
        result = self.space.get_atoms_by_target_type(types.Node,types.Node)
        self.assertTrue(h1 not in result)

        # links
        l1 = self.space.add_link(types.InheritanceLink,[h1.h,h2.h])
        result = self.space.get_atoms_by_target_type(types.Link,types.ConceptNode,target_subtype=False)
        self.assertTrue(l1 in result)
        
        # test recursive target subtype
        result = self.space.get_atoms_by_target_type(types.Link,types.Node,target_subtype=True)
        self.assertTrue(l1 in result)

    def test_get_by_target_atom(self):
        h1 = self.space.add_node(types.Node,"test1")
        h2 = self.space.add_node(types.ConceptNode,"test2")
        h3 = self.space.add_node(types.PredicateNode,"test3")

        # test it doesn't apply to Nodes
        result = self.space.get_atoms_by_target_atom(types.Node,h1)
        self.assertTrue(h1 not in result)

        # links
        l1 = self.space.add_link(types.InheritanceLink,[h1,h2])
        result = self.space.get_atoms_by_target_atom(types.Link,h1)
        self.assertTrue(l1 in result)
        result = self.space.get_atoms_by_target_atom(types.Link,h3)
        self.assertTrue(l1 not in result)

    def test_remove(self):
        h1 = self.space.add_node(types.Node,"test1")
        h2 = self.space.add_node(types.ConceptNode,"test2")
        h3 = self.space.add_node(types.PredicateNode,"test3")

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

        self.space.remove(h1)
        self.assertTrue(h1 not in self.space)
        self.assertTrue(h2 in self.space)
        self.assertTrue(h3 in self.space)

        l = self.space.add_link(types.SimilarityLink,[h2,h3])
        self.space.remove(h2) # won't remove it unless recursive is True
        self.assertTrue(h2 in self.space)
        self.space.remove(h2,True) # won't remove it unless recursive is True
        self.assertTrue(h2 not in self.space)
        self.assertTrue(l not in self.space)

    def test_clear(self):
        h1 = self.space.add_node(types.Node,"test1")
        h2 = self.space.add_node(types.ConceptNode,"test2")
        h3 = self.space.add_node(types.PredicateNode,"test3")
        self.space.clear()
        self.assertEquals(self.space.size(),0) 
        self.assertEquals(self.space.size(),0) 
        self.assertEquals(len(self.space),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.assertTrue(len(self.space), 3)
class TestMap(unittest.TestCase):

    def setUp(self):
        self.atomspace = AtomSpace()
        resolution = 1
        self.testmap = OctomapOcTree.init_new_map("testmap", resolution)

    def tearDown(self):
        del self.testmap
        del self.atomspace

    def test_GetMapName(self):
        self.assertEqual("testmap", self.testmap.get_map_name())

    def test_GetBlock_NoBlockAdded_ReturnUndefinedHandle(self):
        test_pos = (7, 8, 9)

        test_handle = self.testmap.get_block(test_pos)

        self.assertTrue(test_handle.is_undefined())

    def testBinaryAddandRemove_NormalUnitBlock_AllGetFunctionWork(self):
        test_pos1 = (7.0, 8.0, 9.0)
        test_handle1 = self.atomspace.add_node(types.Node,"bogus").h

        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))

    def testAddSolidUnitBlock__PositionOverBorder__GetBlockFailed(self):
        border = 32768
        test_pos1 = (border, 8, 9)
        test_handle1 = self.atomspace.add_node(types.Node,"bogus").h

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

        self.assertTrue(test_handle2.is_undefined())

    def testSetBlock_AddBlockWithProbabilityControl_GetFunctionsWorkWithProb(self):
        test_pos1 = (7.0, 8.0, 9.0)
        test_handle1 = self.atomspace.add_node(types.Node,"bogus").h
        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))

    def testStandable_NormalBlock_Standable(self):
        #case1: single block
        test_pos = (1, 2, 4)
        block_pos = (1, 2, 3)
        self.testmap.set_agent_height(1)
        self.assertFalse(check_standable(self.atomspace, self.testmap, test_pos))
        test_block = self.atomspace.add_node(types.StructureNode, "block1").h
        material_node = self.atomspace.add_node(types.ConceptNode, "dirt").h
        material_pred_node = self.atomspace.add_node(types.PredicateNode, "material").h
        list_link = self.atomspace.add_link(types.ListLink, [test_block,material_node]).h
        eval_link = self.atomspace.add_link(types.EvaluationLink,
                                            [material_pred_node,list_link]).h
        self.testmap.add_solid_unit_block(test_block, block_pos)

        standable = check_standable(self.atomspace, self.testmap, test_pos)

        self.assertTrue(standable)

    def testStandable_WaterBlock_Unstandable(self):
        #case2: single block which is water, cannot stand on water
        test_pos = (1, 2, 4)
        block_pos = (1, 2, 3)
        self.testmap.set_agent_height(1)
        self.assertFalse(check_standable(self.atomspace, self.testmap, test_pos))
        test_block = self.atomspace.add_node(types.StructureNode, "block1").h
        material_node = self.atomspace.add_node(types.ConceptNode, "water").h
        material_pred_node = self.atomspace.add_node(types.PredicateNode, "material").h
        list_link = self.atomspace.add_link(types.ListLink, [test_block,material_node]).h
        eval_link = self.atomspace.add_link(types.EvaluationLink,
                                          [material_pred_node,list_link]).h
        self.testmap.add_solid_unit_block(test_block, block_pos)

        standable = check_standable(self.atomspace, self.testmap, test_pos)

        self.assertFalse(standable)


    def testStandable_TwoNearBlock_Unstandable(self):
        # case3: two block which z coord is close ( ditance < agentHeight)
        # so it's not standable
        test_pos = (1, 2, 4)
        block_pos1 = (1, 2, 3)
        # higher agent hieght
        self.testmap.set_agent_height(2)
        self.assertFalse(check_standable(self.atomspace, self.testmap, test_pos))
        test_block1 = self.atomspace.add_node(types.StructureNode, "block1").h
        material_node1 = self.atomspace.add_node(types.ConceptNode, "dirt").h
        material_pred_node = self.atomspace.add_node(types.PredicateNode,"material").h
        list_link1 = self.atomspace.add_link(types.ListLink, [test_block1,material_node1]).h
        eval_link1 = self.atomspace.add_link(types.EvaluationLink,
                                             [material_pred_node,list_link1]).h
        self.testmap.add_solid_unit_block(test_block1, block_pos1)

        blockpos2 = (1, 2, 5)
        testBlock2 = self.atomspace.add_node(types.StructureNode, "block2").h
        material_node2 = self.atomspace.add_node(types.ConceptNode, "stone").h
        material_pred_node = self.atomspace.add_node(types.PredicateNode, "material").h
        list_link2 = self.atomspace.add_link(types.ListLink, [testBlock2, material_node2]).h
        eval_link2 = self.atomspace.add_link(types.EvaluationLink,
                                             [material_pred_node,list_link2]).h
        self.testmap.add_solid_unit_block(testBlock2, blockpos2)
        self.assertFalse(self.testmap.get_block(blockpos2).is_undefined())
        self.assertFalse(self.testmap.get_block(block_pos1).is_undefined())
        standable = check_standable(self.atomspace, self.testmap, test_pos)

        self.assertFalse(standable)
class AtomTest(TestCase):
    def setUp(self):
        self.space = AtomSpace()

    def test_creation(self):
        a = self.space.add_node(types.Node, "test1")
        self.assertEqual(a.name, "test1")
        self.assertEqual(a.tv, TruthValue(0.0, 0.0))

    def test_w_truthvalue(self):
        tv = TruthValue(0.5, 100)
        a = self.space.add_node(types.Node, "test2", tv)
        self.assertEqual(a.tv, tv)

        # test set tv
        a.tv = TruthValue(0.1, 10)
        self.assertEqual(a.tv, TruthValue(0.1, 10))

    def test_w_attention_value(self):
        a = self.space.add_node(types.Node, "test2")

        self.assertEqual(a.av, {"lti": 0, "sti": 0, "vlti": False})

        # test set av
        a.av = {"sti": 10, "lti": 1, "vlti": True}
        self.assertEqual(a.av, {"sti": 10, "lti": 1, "vlti": True})

    def test_out(self):
        # test get out
        a1 = self.space.add_node(types.Node, "test2")

        self.assertEqual(a1.out, [])

        tv = TruthValue(0.5, 100)
        a2 = self.space.add_node(types.Node, "test3", tv)

        l = self.space.add_link(types.Link, [a1, a2])
        self.assertEqual(l.out, [a1, a2])

        # ensure out is considered immutable
        self.assertRaises(AttributeError, setattr, l, "out", [a1])

    def test_arity(self):
        a1 = self.space.add_node(types.Node, "test2")

        self.assertEqual(a1.arity, 0)

        tv = TruthValue(0.5, 100)
        a2 = self.space.add_node(types.Node, "test3", tv)

        l = self.space.add_link(types.Link, [a1, a2])
        self.assertEqual(l.arity, 2)

        # ensure arity is considered immutable
        self.assertRaises(AttributeError, setattr, l, "arity", 4)

    def test_is_source(self):
        # any out item is a source for unordered links
        # only the fist item is a source of ordered links
        a1 = self.space.add_node(types.Node, "test1")
        a2 = self.space.add_node(types.Node, "test2")

        l_ordered = self.space.add_link(types.OrderedLink, [a1, a2])
        l_unordered = self.space.add_link(types.UnorderedLink, [a1, a2])

        self.assertEqual(l_ordered.is_source(a1), True)
        self.assertEqual(l_ordered.is_source(a2), False)

        self.assertEqual(l_unordered.is_source(a1), True)
        self.assertEqual(l_unordered.is_source(a2), True)

    def test_type(self):
        # test get out
        a = self.space.add_node(types.Node, "test2")

        self.assertEqual(a.type, 1)
        self.assertEqual(a.t, 1)

        a2 = self.space.add_node(types.Node, "test3")
        l = self.space.add_link(types.Link, [a, a2])
        self.assertEqual(l.type, 2)
        self.assertEqual(l.t, 2)

        # ensure type is considered immutable
        self.assertRaises(AttributeError, setattr, l, "type", 5)
        self.assertRaises(AttributeError, setattr, a, "type", 5)

        self.assertEqual(l.type_name, "Link")
        self.assertEqual(a.type_name, "Node")

    def test_strings(self):
        # set up a link and atoms
        tv = TruthValue(0.5, 100)
        a1 = self.space.add_node(types.Node, "test1", tv)

        a2 = self.space.add_node(types.Node, "test2")
        a2.av = {"sti": 10, "lti": 1, "vlti": True}
        a2.tv = TruthValue(0.1, 10)

        l = self.space.add_link(types.Link, [a1, a2])

        # test string representation
        self.assertEqual(str(a2), '(Node "test2")\n')
        self.assertEqual(a2.long_string(), '(Node "test2" (av 10 1 1) (stv 0.100000 0.012346))\n')
        self.assertEqual(str(l), '(Link (stv 0.000000 0.000000)\n  (Node "test1")\n  (Node "test2")\n)\n')
        self.assertEqual(
            l.long_string(),
            "(Link (av 0 0 0) (stv 0.000000 0.000000)\n"
            + '  (Node "test1" (av 0 0 0) (stv 0.500000 0.111111))\n'
            + '  (Node "test2" (av 10 1 1) (stv 0.100000 0.012346))\n)\n',
        )
class AtomSpaceTest(TestCase):

    def setUp(self):
        self.space = AtomSpace()

    def tearDown(self):
        del self.space

    def test_add_node(self):

        a1 = self.space.add_node(types.Node, "test")
        self.assertTrue(a1)
        # duplicates resolve to same handle
        a2 = self.space.add_node(types.Node, "test")
        self.assertEquals(a1, a2)

        # Should fail when intentionally adding bad type
        # self.assertRaises(RuntimeError, self.space.add_node(types.Link, "test"))
        caught = False
        try:
            self.space.add_node(types.Link, "test")
        except RuntimeError:
            caught = True
        self.assertEquals(caught, True)

        # test adding with a truthvalue
        a3 = self.space.add_node(types.Node, "test_w_tv", TruthValue(0.5, 100))
        self.assertEquals(self.space.size(), 2)

        # test adding with prefixed node
        a1 = self.space.add_node(types.Node, "test", prefixed=True)
        a2 = self.space.add_node(types.Node, "test", prefixed=True)
        self.assertNotEqual(a1, a2)
        self.assertEquals(self.space.size(), 4)

        a3 = self.space.add_node(types.Node, "test", TruthValue(0.5, 100), prefixed=True)
        self.assertNotEqual(a1, a3)
        self.assertEquals(self.space.size(), 5)

        # tests with bad parameters
        # test with not a proper truthvalue
        self.assertRaises(TypeError, self.space.add_node, types.Node, "test", 0, True)
        # test with bad type
        self.assertRaises(TypeError, self.space.add_node, "ConceptNode", "test", TruthValue(0.5, 100))

    def test_add_link(self):
        n1 = self.space.add_node(types.Node, "test1")
        n2 = self.space.add_node(types.Node, "test2")
        l1 = self.space.add_link(types.Link, [n1, n2])
        self.assertTrue(l1 is not None)
        l2 = self.space.add_link(types.Link, [n1, n2])
        self.assertTrue(l2 is not None)
        self.assertTrue(l2 == l1)

        n3 = self.space.add_node(types.Node, "test3")
        l3 = self.space.add_link(types.Link, [n1, n3], TruthValue(0.5, 100))
        self.assertTrue(l3 is not None)
        # Test with a handle instead of atom
        l4 = self.space.add_link(types.Link, [n2.h, n3], TruthValue(0.5, 100))
        self.assertTrue(l4 is not None)

        # Should fail when adding an intentionally bad type
        caught = False
        try:
            l1 = self.space.add_link(types.Node, [n1, n3])
        except RuntimeError:
            caught = True
        self.assertEquals(caught, True)

    def test_is_valid(self):
        h1 = self.space.add_node(types.Node, "test1")
        # check with Handle object
        self.assertTrue(self.space.is_valid(h1.h))
        # check with raw UUID
        self.assertTrue(self.space.is_valid(h1.h.value()))
        # check with bad UUID
        self.assertFalse(self.space.is_valid(2919))
        # check with bad type
        self.assertRaises(TypeError, self.space.is_valid, "test")

    def test_truth_value(self):
        # check attributes come back as assigned
        tv = TruthValue(0.5, 100)
        self.assertEqual(tv.mean, 0.5)
        self.assertEqual(tv.count, 100)
        # test confidence
        self.assertAlmostEqual(tv.confidence, 0.1111, places=4)
        # test string representation
        self.assertEqual(str(tv), "(stv 0.500000 0.111111)")

        # check equality
        tv2 = TruthValue(0.5, 100)
        tv3 = TruthValue(0.6, 100)
        self.assertTrue(tv == tv2)
        self.assertFalse(tv == tv3)

    def test_get_by_name_and_type(self):
        n1 = self.space.add_node(types.Node, "test")
        n2 = self.space.add_node(types.ConceptNode, "test")
        n3 = self.space.add_node(types.PredicateNode, "test")

        # test recursive subtypes
        result = self.space.get_atoms_by_name(types.Node, "test")
        self.assertTrue(n1 in result)
        self.assertTrue(n2 in result)
        self.assertTrue(n3 in result)

        # test non-recursive subtype
        result = self.space.get_atoms_by_name(types.Node, "test", subtype=False)
        self.assertTrue(n1 in result)
        self.assertTrue(n2 not in result)
        self.assertTrue(n3 not in result)

        # test empty
        result = self.space.get_atoms_by_name(types.AnchorNode, "test", subtype=False)
        self.assertEqual(len(result), 0)

    def test_get_by_type(self):
        h1 = self.space.add_node(types.Node, "test1")
        h2 = self.space.add_node(types.ConceptNode, "test2")
        h3 = self.space.add_node(types.PredicateNode, "test3")

        # test recursive subtypes
        result = self.space.get_atoms_by_type(types.Node)
        self.assertTrue(h1 in result)
        self.assertTrue(h2 in result)
        self.assertTrue(h3 in result)

        # links
        l1 = self.space.add_link(types.InheritanceLink, [h1, h2])
        result = self.space.get_atoms_by_type(types.Link)
        self.assertTrue(l1 in result)
        
        # test non-recursive subtype
        result = self.space.get_atoms_by_type(types.Node, subtype=False)
        self.assertTrue(h1 in result)
        self.assertTrue(h2 not in result)
        self.assertTrue(h3 not in result)

        # test empty
        result = self.space.get_atoms_by_type(types.AnchorNode, subtype=False)
        self.assertEqual(len(result), 0)

    def test_get_by_av(self):
        h1 = self.space.add_node(types.ConceptNode, "test1")
        h2 = self.space.add_node(types.ConceptNode, "test2")
        h3 = self.space.add_link(types.InheritanceLink, [h1, h2])
        h4 = self.space.add_node(types.ConceptNode, "test4")
        h5 = self.space.add_node(types.ConceptNode, "test5")

        self.space.set_av(h=h1.h, sti=10)
        self.space.set_av(h=h2.h, sti=5)
        self.space.set_av(h=h3.h, sti=4)
        self.space.set_av(h=h4.h, sti=1)

        result = self.space.get_atoms_by_av(4, 10)
        assert len(result) == 3
        assert set(result) == set([h1, h2, h3])
        assert h4 not in result

        result = self.space.get_atoms_in_attentional_focus()
        assert len(result) == 4
        assert set(result) == set([h1, h2, h3, h4])

    def test_get_by_target_type(self):
        h1 = self.space.add_node(types.Node, "test1")
        h2 = self.space.add_node(types.ConceptNode, "test2")
        h3 = self.space.add_node(types.PredicateNode, "test3")

        # test it doesn't apply to Nodes
        result = self.space.get_atoms_by_target_type(types.Node, types.Node)
        self.assertTrue(h1 not in result)

        # links
        l1 = self.space.add_link(types.InheritanceLink, [h1.h, h2.h])
        result = self.space.get_atoms_by_target_type(types.Link, types.ConceptNode, target_subtype=False)
        self.assertTrue(l1 in result)
        
        # test recursive target subtype
        result = self.space.get_atoms_by_target_type(types.Link, types.Node, target_subtype=True)
        self.assertTrue(l1 in result)

    def test_get_by_target_atom(self):
        h1 = self.space.add_node(types.Node, "test1")
        h2 = self.space.add_node(types.ConceptNode, "test2")
        h3 = self.space.add_node(types.PredicateNode, "test3")

        # test it doesn't apply to Nodes
        result = self.space.get_atoms_by_target_atom(types.Node, h1)
        self.assertTrue(h1 not in result)

        # links
        l1 = self.space.add_link(types.InheritanceLink, [h1, h2])
        result = self.space.get_atoms_by_target_atom(types.Link, h1)
        self.assertTrue(l1 in result)
        result = self.space.get_atoms_by_target_atom(types.Link, h3)
        self.assertTrue(l1 not in result)

    def test_include_incoming_outgoing(self):
        frog = self.space.add_node(types.ConceptNode, "Frog")
        thing = self.space.add_node(types.ConceptNode, "Thing")
        animal = self.space.add_node(types.ConceptNode, "Animal")
        self.space.add_node(types.ConceptNode, "SeparateThing")
        self.space.add_link(types.InheritanceLink, [frog, animal])
        self.space.add_link(types.InheritanceLink, [animal, thing])

        assert len(self.space.include_incoming(self.space.get_atoms_by_name(types.ConceptNode, "Frog"))) == 2
        assert len(self.space.include_incoming(self.space.get_atoms_by_type(types.ConceptNode))) == 6
        assert len(self.space.include_outgoing(self.space.get_atoms_by_type(types.InheritanceLink))) == 5
        assert len(self.space.include_outgoing(
            self.space.include_incoming(self.space.get_atoms_by_name(types.ConceptNode, "Frog")))) == 3

    def test_remove(self):
        h1 = self.space.add_node(types.Node, "test1")
        h2 = self.space.add_node(types.ConceptNode, "test2")
        h3 = self.space.add_node(types.PredicateNode, "test3")

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

        self.space.remove(h1)
        self.assertTrue(h1 not in self.space)
        self.assertTrue(h2 in self.space)
        self.assertTrue(h3 in self.space)

        l = self.space.add_link(types.SimilarityLink, [h2, h3])
        self.space.remove(h2, True) # won't remove it unless recursive is True
        self.assertTrue(h2 not in self.space)
        self.assertTrue(l not in self.space)

    def test_clear(self):
        h1 = self.space.add_node(types.Node, "test1")
        h2 = self.space.add_node(types.ConceptNode, "test2")
        h3 = self.space.add_node(types.PredicateNode, "test3")
        self.space.clear()
        self.assertEquals(self.space.size(), 0) 
        self.assertEquals(self.space.size(), 0) 
        self.assertEquals(len(self.space), 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.assertTrue(len(self.space), 3)
Example #38
0
if __name__ == '__main__':
    atomspace = AtomSpace()

    # jade.ATOMS
    ENTITY = atomspace.add_node('VariableNode', '$ENTITY')
    BLOCK =  atomspace.add_node('VariableNode', '$BLOCK')
    COLOR =  atomspace.add_node('VariableNode', '$COLOR')
    
    atomspace.add_link('ForAllLink',
        [atomspace.add_link('ListLink', [ENTITY, BLOCK, COLOR]),
         atomspace.add_link('ImplicationLink',
             [atomspace.add_link('AndLink',
                 [atomspace.add_link('EvaluationLink',
                    [atomspace.add_node('PredicateNode', 'part-of'),
                     atomspace.add_link('ListLink', [BLOCK, ENTITY])]),
                  atomspace.add_link('EvaluationLink',
                      [atomspace.add_node('PredicateNode', 'color'),
                       atomspace.add_link('ListLink', [BLOCK, COLOR])])]),
              atomspace.add_link('EvaluationLink',
                  [atomspace.add_node('PredicateNode', 'contains-block-of-color'),
                   atomspace.add_link('ListLink', [ENTITY, COLOR])
                  ])
             ])
        ], _default_tv)

    ENTITY1 = atomspace.add_node('VariableNode','$ENTITY1')
    ENTITY2 = atomspace.add_node('VariableNode','$ENTITY2')
    CATEGORY = atomspace.add_node('VariableNode','$CATEGORY')

    atomspace.add_link('ForAllLink',
        [atomspace.add_link('ListLink', [ENTITY1, ENTITY2, CATEGORY]),
         atomspace.add_link('ImplicationLink',
            te.output()
        except KeyError, e:
            KeyError
        except Exception, e:
            import traceback
            traceback.print_exc(file=sys.stdout)
        self.cycles += 1


print __name__
if __name__ == "__main__":
    a = AtomSpace()
    t = types
    bob = a.add_node(t.ConceptNode, "Bob")
    alice = a.add_node(t.ConceptNode, "Alice")
    link = a.add_link(t.ListLink, [bob, alice])
    link2 = a.add_link(t.ListLink, [alice, bob])

    link3 = a.add_link(t.EvaluationLink,
                       [a.add_node(t.PredicateNode, "likes"), link2])

    obj1 = a.add_node(t.AccessoryNode, 'ball1')
    obj2 = a.add_node(t.StructureNode, 'tree1')
    next = a.add_link(t.EvaluationLink, [
        a.add_node(t.PredicateNode, 'next'),
        a.add_link(t.ListLink, [obj1, obj2])
    ])

    next.tv = TruthValue(1, 1)

    arity3 = a.add_link(t.AndLink, [bob, alice, obj1])
Example #40
0
class LogicTest(TestCase):
    def setUp(self):
        self.atomspace = AtomSpace()
        self.logic = Logic(self.atomspace)

    def tearDown(self):
        del self.atomspace
        del self.logic

    def _simple_atoms(self):
        '''InheritanceLink animal breathe'''
        self.animal = self.atomspace.add_node(types.ConceptNode, "animal")
        self.breathe = self.atomspace.add_node(types.ConceptNode, "breathe")
        self.inh_animal_breathe = self.atomspace.add_link(types.InheritanceLink, [self.animal, self.breathe])

        atoms = []
        atoms.append( self.animal )
        atoms.append( self.breathe )
        atoms.append( self.inh_animal_breathe )

        return atoms

    def _what_breathes(self):
        '''InheritanceLink $v1 breathe'''
        self.v1 = self.atomspace.add_node(types.VariableNode, "$v1")
        template = self.atomspace.add_link(types.InheritanceLink, 
                        [self.v1,
                         self.breathe])
        return template

    def test_variable_stuff(self):
        var1 = self.logic.new_variable()
        self.assertTrue( var1.is_a(types.VariableNode) )
        var2 = self.logic.new_variable()
        self.assertNotEqual( var1, var2 )

        self.assertTrue(self.logic.is_variable(var1))

    def test_find(self):
        atoms = self._simple_atoms()

        template = self.inh_animal_breathe

        result = self.logic.find(template, self.atomspace.get_atoms_by_type(types.Atom))
        self.assertEquals( type(result), list )
        self.assertEquals( result, [self.inh_animal_breathe] )

        
        template = self._what_breathes()

        result = self.logic.find(template, self.atomspace.get_atoms_by_type(types.Atom))
        # it should give you the inheritancelink and the template link itself!
        self.assertEquals( result, [self.inh_animal_breathe, template] )

    def test_substitute(self):
        atoms = self._simple_atoms()

        template = self._what_breathes()

        cat = self.atomspace.add_node(types.ConceptNode, "cat")
        substitution = {self.v1: cat}

        # substitute $v1->cat in (InheritanceLink $v1 breathe)
        # producing (InheritanceLink cat breathe)
        intended_result = self.atomspace.add_link(types.InheritanceLink, [cat, self.breathe])

        result = self.logic.substitute(substitution, template)
        self.assertEqual( result, intended_result)
Example #41
0
class ForwardChainerTest(TestCase):
    def setUp(self):
        self.atomspace = AtomSpace()
        self.chainer = Chainer(self.atomspace)

    def tearDown(self):
        del self.atomspace
        del self.chainer

    def _simple_atoms_1(self):
        atoms = []
        atoms.append(self.atomspace.add_node(types.ConceptNode, "animal"))
        atoms.append(self.atomspace.add_node(types.ConceptNode, "breathe"))
        atoms.append(
            self.atomspace.add_link(types.InheritanceLink,
                                    [atoms[0], atoms[1]]))

        return atoms

    def test__selectOne(self):
        atoms = self._simple_atoms_1()

        atom = self.chainer._selectOne(atoms)
        self.assertNotEquals(atom, None)
        self.assertEqual(atom, atoms[0])

        atom = self.chainer._selectOne(atoms)
        self.assertTrue(atom in atoms)

    def test_get_attentional_focus(self):
        atoms = self._simple_atoms_1()

        print atoms[2]

        contents = get_attentional_focus(self.atomspace)
        print contents
        self.assertEqual(len(contents), 1)

    def test__select_one_matching(self):
        atoms = self._simple_atoms_1()

        template = atoms[2]

        result = self.chainer._select_one_matching(template)
        self.assertEqual(result, atoms[2])

        print get_attentional_focus(self.atomspace)

        template = self.atomspace.add_node(types.VariableNode, "$v1")
        result = self.chainer._select_one_matching(template)
        self.assertNotEqual(result, None)

    def test__find_inputs_recursive(self):
        def apply(generic_inputs, generic_outputs):
            inputs = []
            outputs = []
            empty_substitution = {}
            status = self.chainer._find_inputs_recursive(
                inputs, outputs, generic_inputs, generic_outputs,
                empty_substitution)

            return (inputs, outputs)

        atoms = self._simple_atoms_1()

        # test it on lots of simple made up rules that include the edge cases
        # [] => []
        generic_inputs = []
        generic_outputs = []
        (inputs, outputs) = apply(generic_inputs, generic_outputs)
        self.assertEquals(inputs, [])
        self.assertEquals(outputs, [])

        # [animal] => []

        generic_inputs = [atoms[0]]
        generic_outputs = []
        (inputs, outputs) = apply(generic_inputs, generic_outputs)
        self.assertEquals(inputs, [atoms[0]])
        self.assertEquals(outputs, [])

        v1 = self.atomspace.add_node(types.VariableNode, "$v1")
        # [v1] => []
        generic_inputs = [v1]
        generic_outputs = []
        (inputs, outputs) = apply(generic_inputs, generic_outputs)
        self.assertEquals(len(inputs), 1)
        self.assertEquals(outputs, [])

        #from nose.tools import set_trace; set_trace()
        # [v1] => [v1]
        generic_inputs = [v1]
        generic_outputs = [v1]
        (inputs, outputs) = apply(generic_inputs, generic_outputs)
        print str(inputs[0])
        print str(outputs[0])
        self.assertEquals(len(inputs), 1)
        self.assertEquals(len(outputs), 1)
Example #42
0
class AtomSpaceTest(TestCase):
    def setUp(self):
        self.space = AtomSpace()
        initialize_opencog(self.space)

    def tearDown(self):
        finalize_opencog()
        del self.space

    def test_add_node(self):

        # Test long form atomspace node addition.

        # Test node add
        self.space.add_node(types.Node, "node")

        # Test with not a proper truthvalue
        self.assertRaises(TypeError, self.space.add_node, types.Node, "test",
                          0, True)
        # Test with bad type
        self.assertRaises(TypeError, self.space.add_node, "ConceptNode",
                          "test", TruthValue(0.5, 0.8))

        # From here on out we'll use the more compact type constructors
        a1 = Node("test")
        self.assertTrue(a1)
        # duplicates resolve to same atom
        a2 = Node("test")
        self.assertEquals(a1, a2)

        # Should fail when intentionally adding bad type
        caught = False
        try:
            self.space.add_node(types.Link, "test")
        except RuntimeError:
            caught = True
        self.assertEquals(caught, True)

        # Test adding with a truthvalue
        a3 = Node("test_w_tv").truth_value(0.5, 0.8)
        self.assertEquals(self.space.size(), 3)

    def test_add_link(self):
        n1 = Node("test1")
        n2 = Node("test2")
        l1 = Link(n1, n2)
        self.assertTrue(l1 is not None)
        l2 = Link(n1, n2)
        self.assertTrue(l2 is not None)
        self.assertTrue(l2 == l1)

        n3 = Node("test3")
        l3 = Link(n1, n3).truth_value(0.5, 0.8)
        self.assertTrue(l3 is not None)

        # Should fail when adding an intentionally bad type
        caught = False
        try:
            l1 = self.space.add_link(types.Node, [n1, n3])
        except RuntimeError:
            caught = True
        self.assertEquals(caught, True)

    def test_is_valid(self):
        a1 = Node("test1")
        # check with Atom object
        self.assertTrue(self.space.is_valid(a1))
        # check with bad type
        self.assertRaises(TypeError, self.space.is_valid, "test")

    def test_truth_value(self):
        # check attributes come back as assigned
        tv = TruthValue(0.5, 0.8)
        self.assertEqual(tv.mean, 0.5)
        self.assertAlmostEqual(tv.confidence, 0.8, places=4)
        # test string representation
        self.assertEqual(str(tv), "(stv 0.500000 0.800000)")

        # check equality
        tv2 = TruthValue(0.5, 0.8)
        tv3 = TruthValue(0.6, 0.8)
        self.assertTrue(tv == tv2)
        self.assertFalse(tv == tv3)

        # check truth_value function of atom
        atom = Node("atom with tv")
        default_tv = atom.tv
        atom.truth_value(0.75, 0.9)
        new_tv = atom.tv
        self.assertFalse(new_tv == default_tv)
        self.assertEqual(new_tv.mean, 0.75)
        self.assertAlmostEqual(new_tv.confidence, 0.9, places=4)

    def test_get_by_type(self):
        a1 = Node("test1")
        a2 = ConceptNode("test2")
        a3 = PredicateNode("test3")

        # test recursive subtypes
        result = self.space.get_atoms_by_type(types.Node)
        self.assertTrue(a1 in result)
        self.assertTrue(a2 in result)
        self.assertTrue(a3 in result)

        # links
        l1 = InheritanceLink(a1, a2)
        result = self.space.get_atoms_by_type(types.Link)
        self.assertTrue(l1 in result)

        # test non-recursive subtype
        result = self.space.get_atoms_by_type(types.Node, subtype=False)
        self.assertTrue(a1 in result)
        self.assertTrue(a2 not in result)
        self.assertTrue(a3 not in result)

        # test empty
        result = self.space.get_atoms_by_type(types.AnchorNode, subtype=False)
        self.assertEqual(len(result), 0)

    def test_incoming_by_type(self):
        a1 = Node("test1")
        a2 = ConceptNode("test2")
        a3 = PredicateNode("test3")

        # test no incoming Node for a1
        result = a1.incoming_by_type(types.Node)
        self.assertTrue(a1 not in result)

        # now check links
        l1 = InheritanceLink(a1, a2)
        result = a1.incoming_by_type(types.InheritanceLink)
        self.assertTrue(l1 in result)
        result = a2.incoming_by_type(types.InheritanceLink)
        self.assertTrue(l1 in result)
        result = a3.incoming_by_type(types.InheritanceLink)
        self.assertTrue(l1 not in result)

    def test_include_incoming_outgoing(self):
        frog = ConceptNode("Frog")
        thing = ConceptNode("Thing")
        animal = ConceptNode("Animal")
        ConceptNode("SeparateThing")
        InheritanceLink(frog, animal)
        InheritanceLink(animal, thing)

        assert len(self.space.include_incoming([ConceptNode("Frog")])) == 2
        assert len(
            self.space.include_outgoing(
                self.space.include_incoming([ConceptNode("Frog")]))) == 3
        assert len(
            self.space.include_incoming(
                self.space.get_atoms_by_type(types.ConceptNode))) == 6
        assert len(
            self.space.include_outgoing(
                self.space.get_atoms_by_type(types.InheritanceLink))) == 5

    def test_remove(self):
        a1 = Node("test1")
        a2 = ConceptNode("test2")
        a3 = PredicateNode("test3")

        self.assertTrue(a1 in self.space)
        self.assertTrue(a2 in self.space)
        self.assertTrue(a3 in self.space)

        self.space.remove(a1)
        self.assertTrue(a1 not in self.space)
        self.assertTrue(a2 in self.space)
        self.assertTrue(a3 in self.space)

        l = SimilarityLink(a2, a3)
        self.space.remove(a2, True)  # won't remove it unless recursive is True
        self.assertTrue(a2 not in self.space)
        self.assertTrue(l not in self.space)

    def test_clear(self):
        a1 = Node("test1")
        a2 = ConceptNode("test2")
        a3 = PredicateNode("test3")
        self.space.clear()
        self.assertEquals(self.space.size(), 0)
        self.assertEquals(len(self.space), 0)

    def test_container_methods(self):
        self.assertEquals(len(self.space), 0)
        a1 = Node("test1")
        a2 = ConceptNode("test2")
        a3 = PredicateNode("test3")

        self.assertTrue(a1 in self.space)
        self.assertTrue(a2 in self.space)
        self.assertTrue(a3 in self.space)

        self.assertEquals(len(self.space), 3)

    def test_context_mgr_tmp(self):
        a = ConceptNode('a')
        with tmp_atomspace() as tmp_as:
            b = ConceptNode('b')
            self.assertTrue(a in self.space)
            # verify that current default atomspace is tmp_as
            self.assertFalse(b in self.space)
        c = ConceptNode('c')
        # verify that current default atomspace is self.space
        self.assertTrue(c in self.space)
Example #43
0
from opencog.atomspace import AtomSpace, TruthValue, Atom
from opencog.atomspace import types as t

a = AtomSpace()

TV = TruthValue(1, 1)
A = a.add_node(t.ConceptNode, 'A', TV)
B = a.add_node(t.ConceptNode, 'B', TruthValue(0.5, 1))
C = a.add_node(t.ConceptNode, 'C', TV)
AB = a.add_link(t.InheritanceLink, [A, B], TV)
BC = a.add_link(t.InheritanceLink, [B, C], TV)
AC = a.add_link(t.InheritanceLink, [A, C])

a.print_list()

import logic
from tree import *

target = tree_from_atom(AC)
chainer = logic.Chainer(a)
results = chainer.bc(target)

print '\n---------------------------\n'

print results
print AC
Example #44
0
Currently, it is represented the same way that Relex2Logic outputs it,
which is not going to work properly.
"""

__author__ = 'Cosmo Harrigan'

from opencog.atomspace import AtomSpace, TruthValue, types

atomspace = AtomSpace()

Socrates = atomspace.add_node(types.ConceptNode, "Socrates")
Man = atomspace.add_node(types.ConceptNode, "man")
Air = atomspace.add_node(types.ConceptNode, "air")
be = atomspace.add_node(types.PredicateNode, "be")
breathe = atomspace.add_node(types.PredicateNode, "breathe")

atomspace.add_link(
    types.EvaluationLink,
    [be,
     atomspace.add_link(
         types.ListLink,
         [Socrates, Man])],
    TruthValue(1, TruthValue().confidence_to_count(1)))

atomspace.add_link(
    types.EvaluationLink,
    [breathe,
     atomspace.add_link(
         types.ListLink, [Man, Air])],
    TruthValue(1, TruthValue().confidence_to_count(1)))
Example #45
0
The full definitions are in this Scheme file:
  https://github.com/opencog/test-datasets/blob/master/pln/tuffy/smokes/smokes.scm
They are redefined in Python format here for testing, due to this bug that
prevents importing Scheme files without a running cogserver:
  https://github.com/opencog/opencog/issues/530
"""

__author__ = 'Cosmo Harrigan'

from opencog.atomspace import AtomSpace, TruthValue, types

atomspace = AtomSpace()

# Basic variable definitions
X = atomspace.add_node(types.VariableNode, "$X")
lX = atomspace.add_link(types.ListLink, [X])

Y = atomspace.add_node(types.VariableNode, "$Y")
lY = atomspace.add_link(types.ListLink, [Y])

X_Y = atomspace.add_link(types.ListLink, [X, Y])

full_confidence = TruthValue().confidence_to_count(1)
crisp_true = TruthValue(1, full_confidence)

# Anna smokes.
Anna = atomspace.add_node(types.ConceptNode, "Anna")
smokes = atomspace.add_node(types.PredicateNode, "smokes")
atomspace.add_link(types.EvaluationLink,
                   [smokes, atomspace.add_link(types.ListLink, [Anna])],
                   crisp_true)
class TestMap(unittest.TestCase):

    def setUp(self):
        self.atomspace = AtomSpace()
        resolution = 1
        self.testmap = OctomapOcTree.init_new_map(self.atomspace, "testmap", resolution)

    def tearDown(self):
        del self.testmap
        del self.atomspace

    def test_GetMapName(self):
        self.assertEqual("testmap", self.testmap.get_map_name())

    def test_GetBlock_NoBlockAdded_ReturnUndefinedHandle(self):
        test_pos = (7, 8, 9)
        test_atom = self.testmap.get_block(test_pos)
        self.assertIsNone(test_atom)

    def testBinaryAddandRemove_NormalUnitBlock_AllGetFunctionWork(self):
        test_pos1 = (7.0, 8.0, 9.0)
        test_atom1 = self.atomspace.add_node(types.Node,"bogus")

        self.testmap.add_solid_unit_block(test_atom1, test_pos1)
        test_atom2 = self.testmap.get_block(test_pos1)
        self.assertEqual(test_atom1, test_atom2)
        self.assertEqual(test_pos1, self.testmap.get_block_location(test_atom1))

        self.testmap.remove_solid_unit_block(test_atom1)
        test_atom3 = self.testmap.get_block(test_pos1)
        self.assertIsNone(test_atom3)
        self.assertIsNone(self.testmap.get_block_location(test_atom1))

    def testAddSolidUnitBlock__PositionOverBorder__GetBlockFailed(self):
        border = 32768
        test_pos1 = (border, 8, 9)
        test_atom1 = self.atomspace.add_node(types.Node,"bogus")

        self.testmap.add_solid_unit_block(test_atom1, test_pos1)
        test_atom2 = self.testmap.get_block(test_pos1)

        self.assertIsNone(test_atom2)

    def testSetBlock_AddBlockWithProbabilityControl_GetFunctionsWorkWithProb(self):
        test_pos1 = (7.0, 8.0, 9.0)
        test_atom1 = self.atomspace.add_node(types.Node,"bogus")
        log_odds_threshold = self.testmap.get_occupancy_thres_log()

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

        self.assertEqual(test_atom1, self.testmap.get_block(test_pos1))
        self.assertEqual(test_atom1, self.testmap.get_block(test_pos1, log_odds_threshold))
        self.assertEqual(test_pos1, self.testmap.get_block_location(test_atom1))
        self.assertEqual(test_pos1, self.testmap.get_block_location(test_atom1,
                                                                    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_atom1, test_pos1, -0.1)

        self.assertIsNone(self.testmap.get_block(test_pos1))
        self.assertIsNone(self.testmap.get_block(test_pos1, log_odds_threshold))
        self.assertIsNone(self.testmap.get_block_location(test_atom1))
        self.assertIsNone(self.testmap.get_block_location(test_atom1,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_atom1, self.testmap.get_block(test_pos1))
        self.assertEqual(test_atom1, self.testmap.get_block(test_pos1, log_odds_threshold))

        self.assertEqual(test_pos1, self.testmap.get_block_location(test_atom1))
        self.assertEqual(test_pos1, self.testmap.get_block_location(test_atom1,
                                                                    log_odds_threshold))

    def testStandable_NormalBlock_Standable(self):
        #case1: single block
        test_pos = (1, 2, 4)
        block_pos = (1, 2, 3)
        self.testmap.set_agent_height(1)
        self.assertFalse(check_standable(self.atomspace, self.testmap, test_pos))
        test_block = self.atomspace.add_node(types.StructureNode, "block1")
        material_node = self.atomspace.add_node(types.ConceptNode, "dirt")
        material_pred_node = self.atomspace.add_node(types.PredicateNode, "material")
        list_link = self.atomspace.add_link(types.ListLink, [test_block,material_node])
        eval_link = self.atomspace.add_link(types.EvaluationLink,
                                            [material_pred_node,list_link])
        self.testmap.add_solid_unit_block(test_block, block_pos)

        standable = check_standable(self.atomspace, self.testmap, test_pos)

        self.assertTrue(standable)

    def testStandable_WaterBlock_Unstandable(self):
        #case2: single block which is water, cannot stand on water
        test_pos = (1, 2, 4)
        block_pos = (1, 2, 3)
        self.testmap.set_agent_height(1)
        self.assertFalse(check_standable(self.atomspace, self.testmap, test_pos))
        test_block = self.atomspace.add_node(types.StructureNode, "block1")
        material_node = self.atomspace.add_node(types.ConceptNode, "water")
        material_pred_node = self.atomspace.add_node(types.PredicateNode, "material")
        list_link = self.atomspace.add_link(types.ListLink, [test_block,material_node])
        eval_link = self.atomspace.add_link(types.EvaluationLink,
                                          [material_pred_node,list_link])
        self.testmap.add_solid_unit_block(test_block, block_pos)

        standable = check_standable(self.atomspace, self.testmap, test_pos)

        self.assertFalse(standable)


    def testStandable_TwoNearBlock_Unstandable(self):
        # case3: two block which z coord is close ( ditance < agentHeight)
        # so it's not standable
        test_pos = (1, 2, 4)
        block_pos1 = (1, 2, 3)
        # higher agent hieght
        self.testmap.set_agent_height(2)
        self.assertFalse(check_standable(self.atomspace, self.testmap, test_pos))
        test_block1 = self.atomspace.add_node(types.StructureNode, "block1")
        material_node1 = self.atomspace.add_node(types.ConceptNode, "dirt")
        material_pred_node = self.atomspace.add_node(types.PredicateNode,"material")
        list_link1 = self.atomspace.add_link(types.ListLink, [test_block1,material_node1])
        eval_link1 = self.atomspace.add_link(types.EvaluationLink,
                                             [material_pred_node,list_link1])
        self.testmap.add_solid_unit_block(test_block1, block_pos1)

        block_pos2 = (1, 2, 5)
        testBlock2 = self.atomspace.add_node(types.StructureNode, "block2")
        material_node2 = self.atomspace.add_node(types.ConceptNode, "stone")
        material_pred_node = self.atomspace.add_node(types.PredicateNode, "material")
        list_link2 = self.atomspace.add_link(types.ListLink, [testBlock2, material_node2])
        eval_link2 = self.atomspace.add_link(types.EvaluationLink,
                                             [material_pred_node,list_link2])
        self.testmap.add_solid_unit_block(testBlock2, block_pos2)
        self.assertTrue(self.testmap.get_block(block_pos2) != None)
        self.assertTrue(self.testmap.get_block(block_pos1) != None)
        standable = check_standable(self.atomspace, self.testmap, test_pos)

        self.assertFalse(standable)