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.
class TestSpaceServer:

    def setUp(self):
        self._atomspace = AtomSpace()
        self.space_server = SpaceServer(self._atomspace)
        self.time_server = TimeServer(self._atomspace, self.space_server)
        self.space_server.set_time_server(self.time_server)
        
    def tearDown(self):
        del self.space_server
        del self._atomspace

    def test_addMap(self):
        map_atom = self.space_server.add_map(123456, "testmap", 1)
        assert self._atomspace.get_name(map_atom) == "testmap"
    
    def test_getMap(self):
        map_atom = self.space_server.add_map(123456, "testmap", 1)
        mapinstance = self.space_server.get_map(map_atom)
        assert mapinstance.get_map_name() == "testmap"

    def test_addAndRemoveMapInfo(self):
        map_atom = self.space_server.add_map(123456, "testmap", 1)
        object_atom = self._atomspace.add_node(types.StructureNode,"object111")
        assert self.space_server.add_map_info(object_atom, map_atom,
                                             False, False, 123456, 4, 5, 6) == True
        map_instance = self.space_server.get_map(map_atom) 
        assert map_instance.get_block_location(object_atom) == (4, 5, 6)
        self.space_server.remove_map_info(object_atom, map_atom, 234567)
        assert map_instance.get_block_location(object_atom) == None    
class TestSpaceServer:
    def setUp(self):
        self._atomspace = AtomSpace()
        self.space_server = SpaceServer(self._atomspace)
        self.time_server = TimeServer(self._atomspace, self.space_server)
        self.space_server.set_time_server(self.time_server)

    def tearDown(self):
        del self.space_server
        del self._atomspace

    def test_addMap(self):
        map_atom = self.space_server.add_map(123456, "testmap", 1)
        assert map_atom.name == "testmap"

    def test_getMap(self):
        map_atom = self.space_server.add_map(123456, "testmap", 1)
        mapinstance = self.space_server.get_map(map_atom)
        assert mapinstance.get_map_name() == "testmap"

    def test_addAndRemoveMapInfo(self):
        map_atom = self.space_server.add_map(123456, "testmap", 1)
        object_atom = self._atomspace.add_node(types.StructureNode,
                                               "object111")
        assert self.space_server.add_map_info(object_atom, map_atom, False,
                                              False, 123456, 4, 5, 6) == True
        map_instance = self.space_server.get_map(map_atom)
        assert map_instance.get_block_location(object_atom) == (4, 5, 6)
        self.space_server.remove_map_info(object_atom, map_atom, 234567)
        assert map_instance.get_block_location(object_atom) == None
Example #4
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 #5
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 #6
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 #7
0
class TestTimeServer:
    def setUp(self):
        self._atomspace = AtomSpace()
        self._spaceserver = SpaceServer(self._atomspace)
        self._timeserver = TimeServer(self._atomspace, self._spaceserver)
        self._spaceserver.set_time_server(self._timeserver)

    def tearDown(self):
        del self._spaceserver
        del self._atomspace

    def test_addTimeInfo(self):
        objnode = self._atomspace.add_node(types.StructureNode, "object111")
        at_time_link = self._timeserver.add_time_info(objnode, 123456)
        assert objnode in at_time_link.out
class TestTimeServer:
    def setUp(self):
        self._atomspace = AtomSpace()
        self._spaceserver = SpaceServer(self._atomspace)
        self._timeserver = TimeServer(self._atomspace, self._spaceserver)
        self._spaceserver.set_time_server(self._timeserver)

    def tearDown(self):
        del self._spaceserver
        del self._atomspace

    def test_addTimeInfo(self):
        objnode = self._atomspace.add_node(types.StructureNode, "object111")
        at_time_link = self._timeserver.add_time_info(objnode, 123456)
        assert objnode in self._atomspace.get_outgoing(at_time_link)
Example #9
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)
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 #11
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 #12
0
run the example from the CogServer, for which you should use
deduction_agent.py instead.
"""

from __future__ import print_function
from pprint import pprint
from pln.examples.deduction import deduction_agent
from opencog.atomspace import types, AtomSpace, TruthValue

__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))
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()
            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)
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)
deduction_agent.py instead.
"""

from __future__ import print_function
from pprint import pprint
from pln.examples.deduction import deduction_agent
from opencog.atomspace import types, AtomSpace, TruthValue

__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],
class AnaphoraUnitTester(TestCase):
    def setUp(self):

        self.atomspace = AtomSpace()

        scheme_eval(self.atomspace,
                    "(add-to-load-path \"/usr/local/share/opencog/scm\")")
        scheme_eval(self.atomspace, "(use-modules (opencog))")
        scheme_eval(self.atomspace, "(use-modules (opencog atom-types))")
        scheme_eval(self.atomspace, "(use-modules (opencog query))")

        data = [
            "opencog/scm/config.scm",
            "opencog/scm/core_types.scm",
            "opencog/scm/apply.scm",
            "opencog/scm/file-utils.scm",
            "opencog/scm/utilities.scm",
            "opencog/scm/av-tv.scm",
            "opencog/nlp/scm/type-definitions.scm",
            "opencog/nlp/scm/config.scm",
            "opencog/nlp/scm/file-utils.scm",
            "opencog/nlp/scm/nlp-utils.scm",
            "opencog/nlp/scm/disjunct-list.scm",
            "opencog/nlp/scm/processing-utils.scm",
        ]

        for item in data:
            status = load_scm(self.atomspace, item)
            # print "load status=", status, " item=", item

        self.hobbsAgent = HobbsAgent()

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

    def getWord(self, name, type=types.WordInstanceNode):
        word = self.atomspace.add_node(type, name)
        return word

    def compare(self, list_1, list_2):
        if len(list_1) == len(list_2):
            for i in range(len(list_1)):
                if list_1[i] != list_2[i].name:
                    return False
            return True
        else:
            return False

    def test_bfs(self):
        '''
        Testing the bfs function
        '''

        self.hobbsAgent.initilization(self.atomspace)
        self.assertTrue(
            load_scm(self.atomspace, "tests/nlp/anaphora/data/bfs.scm"))

        self.hobbsAgent.run(self.atomspace)
        self.assertTrue(
            self.compare(['a', 'b', 'c', 'd', 'e', 'f', 'g'],
                         self.hobbsAgent.bfs(self.getWord('a'))))
        self.atomspace.clear()

    #@unittest.skip("debugging skipping")
    def test_getWords(self):
        '''
        Testing the getWords function
        '''

        self.assertTrue(
            load_scm(self.atomspace, "tests/nlp/anaphora/data/getWords.scm"))
        self.hobbsAgent.initilization(self.atomspace)
        self.assertTrue(
            self.compare(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j'],
                         self.hobbsAgent.getWords()))
        self.atomspace.clear()

    def test_propose(self):
        '''
        Testing the propose function
        '''
        def filter_1():

            print("Testing filter #1...")
            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#1/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(
                self.getWord('antecedent')))
            self.atomspace.clear()

            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#1/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(
                self.hobbsAgent.propose(self.getWord('antecedent')))
            self.atomspace.clear()

            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#1/data_#3.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(
                self.getWord('antecedent')))
            self.atomspace.clear()

            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#1/data_#4.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(
                self.getWord('antecedent')))
            self.atomspace.clear()

            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#1/data_#5.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(
                self.getWord('antecedent')))
            self.atomspace.clear()

            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#1/data_#6.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(
                self.getWord('antecedent')))
            self.atomspace.clear()

        def filter_2():

            print("Testing filter #2...")
            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#2/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(
                self.hobbsAgent.propose(self.getWord('antecedent')))
            self.atomspace.clear()

            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#2/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(
                self.getWord('antecedent')))
            self.atomspace.clear()

        def filter_3():

            print("Testing filter #3...")
            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#3/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(
                self.hobbsAgent.propose(self.getWord('antecedent'), 3))
            self.atomspace.clear()

            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#3/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(
                self.hobbsAgent.propose(self.getWord('antecedent'), 3))
            self.atomspace.clear()

            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#3/data_#3.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(
                self.hobbsAgent.propose(self.getWord('antecedent'), 3))
            self.atomspace.clear()

        def filter_4():

            print("Testing filter #4...")
            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#4/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(
                self.hobbsAgent.propose(self.getWord('antecedent'), 4))
            self.atomspace.clear()

            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#4/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(
                self.hobbsAgent.propose(self.getWord('antecedent'), 4))
            self.atomspace.clear()

            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#4/data_#3.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(
                self.hobbsAgent.propose(self.getWord('antecedent'), 4))
            self.atomspace.clear()

        def filter_5():

            print("Testing filter #5...")
            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#5/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(
                self.hobbsAgent.propose(self.getWord('antecedent'), 5))
            self.atomspace.clear()

            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#5/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(
                self.hobbsAgent.propose(self.getWord('antecedent'), 5))
            self.atomspace.clear()

            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#5/data_#3.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(
                self.hobbsAgent.propose(self.getWord('antecedent'), 5))
            self.atomspace.clear()

        def filter_6():

            print("Testing filter #6...")
            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#6/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(
                self.hobbsAgent.propose(self.getWord('antecedent'), 6))
            self.atomspace.clear()

            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#6/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(
                self.hobbsAgent.propose(self.getWord('antecedent'), 6))
            self.atomspace.clear()

            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#6/data_#3.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(
                self.hobbsAgent.propose(self.getWord('antecedent'), 6))
            self.atomspace.clear()

        def filter_7():

            print("Testing filter #7...")
            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#7/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(
                self.hobbsAgent.propose(self.getWord('antecedent'), 7))
            self.atomspace.clear()

            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#7/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(
                self.hobbsAgent.propose(self.getWord('antecedent'), 7))
            self.atomspace.clear()

            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#7/data_#3.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(
                self.hobbsAgent.propose(self.getWord('antecedent'), 7))
            self.atomspace.clear()

        def filter_8():

            print("Testing filter #8...")
            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#8/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(
                self.hobbsAgent.propose(self.getWord('antecedent'), 8))
            self.atomspace.clear()

            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#8/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(
                self.hobbsAgent.propose(self.getWord('antecedent'), 8))
            self.atomspace.clear()

            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#8/data_#3.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(
                self.hobbsAgent.propose(self.getWord('antecedent'), 8))
            self.atomspace.clear()

        def filter_9():

            print("Testing filter #9...")
            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#9/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(
                self.hobbsAgent.propose(self.getWord('antecedent'), 9))
            self.atomspace.clear()

            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#9/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(
                self.hobbsAgent.propose(self.getWord('antecedent'), 9))
            self.atomspace.clear()

            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#9/data_#3.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(
                self.hobbsAgent.propose(self.getWord('antecedent'), 9))
            self.atomspace.clear()

        def filter_10():

            print("Testing filter #10...")
            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#10/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(
                self.hobbsAgent.propose(self.getWord('antecedent'), 10))
            self.atomspace.clear()

            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#10/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(
                self.hobbsAgent.propose(self.getWord('antecedent'), 10))
            self.atomspace.clear()

        def filter_11():

            print("Testing filter #11...")
            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#11/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(
                self.hobbsAgent.propose(self.getWord('antecedent'), 11))
            self.atomspace.clear()

            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#11/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(
                self.hobbsAgent.propose(self.getWord('antecedent'), 11))
            self.atomspace.clear()

        def filter_12():

            print("Testing filter #12...")
            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#12/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(
                self.hobbsAgent.propose(
                    self.getWord('antecedent', types.ParseNode), 12))
            self.atomspace.clear()

            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#12/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(
                self.hobbsAgent.propose(self.getWord('antecedent'), 12))
            self.atomspace.clear()

        def filter_13():

            print("Testing filter #13...")
            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#13/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(
                self.hobbsAgent.propose(self.getWord('antecedent'), 13))
            self.atomspace.clear()

            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#13/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(
                self.hobbsAgent.propose(self.getWord('antecedent'), 13))
            self.atomspace.clear()

        def filter_14():

            print("Testing filter #14...")
            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#14/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(
                self.hobbsAgent.propose(self.getWord('antecedent'), 14))
            self.atomspace.clear()

            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#14/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(
                self.hobbsAgent.propose(self.getWord('antecedent'), 14))
            self.atomspace.clear()

        def filter_15():

            print("Testing filter #15...")
            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#15/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(
                self.hobbsAgent.propose(self.getWord('antecedent'), 15))
            self.atomspace.clear()

            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#15/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(
                self.hobbsAgent.propose(self.getWord('antecedent'), 15))
            self.atomspace.clear()

        def filter_16():

            print("Testing filter #16...")
            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#16/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(
                self.hobbsAgent.propose(self.getWord('antecedent'), 16))
            self.atomspace.clear()

            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#16/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(
                self.hobbsAgent.propose(self.getWord('antecedent'), 16))
            self.atomspace.clear()

        def filter_17():

            print("Testing filter #17...")
            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#17/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(
                self.hobbsAgent.propose(self.getWord('antecedent'), 17))
            self.atomspace.clear()

            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#17/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(
                self.hobbsAgent.propose(self.getWord('antecedent'), 17))
            self.atomspace.clear()

        def filter_18():

            print("Testing filter #18...")
            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#18/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(
                self.hobbsAgent.propose(self.getWord('antecedent'), 18))
            self.atomspace.clear()

            self.assertTrue(
                load_scm(
                    self.atomspace,
                    "tests/nlp/anaphora/data/propose/filter-#18/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(
                self.hobbsAgent.propose(self.getWord('antecedent'), 18))
            self.atomspace.clear()

        filter_1()
        filter_2()
        filter_3()
        filter_4()
        filter_5()
        filter_6()
        filter_7()
        filter_8()
        filter_9()
        filter_10()
        filter_11()
        filter_12()
        filter_13()
        filter_14()
        filter_15()
        filter_16()
        filter_17()
        filter_18()

    #@unittest.skip("debugging skipping")
    def test_pleonastic_if(self):

        self.assertTrue(
            load_scm(self.atomspace,
                     "tests/nlp/anaphora/data/pleonastic_it/data_#1.scm"))
        self.hobbsAgent.initilization(self.atomspace)
        self.assertTrue(self.hobbsAgent.pleonastic_it(self.getWord('it')))
        self.atomspace.clear()

        self.assertTrue(
            load_scm(self.atomspace,
                     "tests/nlp/anaphora/data/pleonastic_it/data_#2.scm"))
        self.hobbsAgent.initilization(self.atomspace)
        self.assertTrue(self.hobbsAgent.pleonastic_it(self.getWord('it')))
        self.atomspace.clear()

        self.assertTrue(
            load_scm(self.atomspace,
                     "tests/nlp/anaphora/data/pleonastic_it/data_#3.scm"))
        self.hobbsAgent.initilization(self.atomspace)
        self.assertTrue(self.hobbsAgent.pleonastic_it(self.getWord('it')))
        self.atomspace.clear()

        self.assertTrue(
            load_scm(self.atomspace,
                     "tests/nlp/anaphora/data/pleonastic_it/data_#4.scm"))
        self.hobbsAgent.initilization(self.atomspace)
        self.assertFalse(self.hobbsAgent.pleonastic_it(self.getWord('it')))
        self.atomspace.clear()

        self.assertTrue(
            load_scm(self.atomspace,
                     "tests/nlp/anaphora/data/pleonastic_it/data_#5.scm"))
        self.hobbsAgent.initilization(self.atomspace)
        self.assertFalse(self.hobbsAgent.pleonastic_it(self.getWord('it')))
        self.atomspace.clear()

    #@unittest.skip("debugging skipping")
    def test_conjunctions(self):

        self.assertTrue(
            load_scm(self.atomspace,
                     "tests/nlp/anaphora/data/conjunction.scm"))
        self.hobbsAgent.initilization(self.atomspace)
        self.assertFalse(
            self.hobbsAgent.pleonastic_it(self.getWord('waitresses')))
        self.atomspace.clear()
#
# 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 #19
0
this relationship.

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,
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
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 #22
0
        ps_a  = atom_from_tree(ps, a)
        pal_a = atom_from_tree(pal, a)
        
        print ps
        print pal
        ps_a.tv = TruthValue(1.0, confidence_to_count(1.0))
        
        print ps_a.tv
    
    return result_atoms

if __name__ == '__main__':
    a = AtomSpace()
    log.use_stdout(True)

    atom_from_tree(T('EvaluationLink',a.add_node(t.PredicateNode,'A')), a).tv = TruthValue(1, 1)
    #atom_from_tree(T('EvaluationLink',1), a).tv = TruthValue(1, 1)

    c = Chainer(a)

    #search(T('EvaluationLink',a.add_node(t.PredicateNode,'B')))
    #fc(a)

    #c.bc(T('EvaluationLink',a.add_node(t.PredicateNode,'A')))

#    global rules
#    A = T('EvaluationLink',a.add_node(t.PredicateNode,'A'))
#    B = T('EvaluationLink',a.add_node(t.PredicateNode,'B'))
#    rules.append(Rule(B, 
#                                  [ A ]))
Example #23
0
while (epoch < n_epochs):
    epoch+=1
    for minibatch_index in xrange(n_train_batches):
        mlp_minibatch_avg_cost = train_sup(minibatch_index)
     
        iteration = (epoch - 1) * n_train_batches + minibatch_index
     
        if (iteration + 1) % n_train_batches == 0:
            print 'MLP MODEL'
            test_losses = [test_sup(i) for i in xrange(n_test_batches)]
            test_record[epoch-1] = np.mean(test_losses)
         
            print(('     epoch %i, minibatch %i/%i, test error %f %%') %
                  (epoch, minibatch_index + 1, n_train_batches, test_record[epoch-1] * 100.))

filters=[]     
filters.append(model_sup.layers[0].filters.get_value(borrow=True))
filters.append(model_sup.layers[1].filters.get_value(borrow=True))
filters.append(model_sup.layers[2].filters.get_value(borrow=True))
filters.append(model_sup.layers[3].filters.get_value(borrow=True))

pickle.dump(test_record, open("convae_destin.pkl", "w"))

for i in xrange(n_epochs):
  for j in xrange(4):
    image_adr="convae_destin/layer_%d_filter_%d.eps" % (j,i)
    plt.imshow(filters[j][i, 0, :, :], cmap = plt.get_cmap('gray'), interpolation='nearest')
    plt.axis('off')
    plt.savefig(image_adr , bbox_inches='tight', pad_inches=0)
return atomspace.add_node(types.ArrayNode, str(test_record))
#                SubdueTextOutput(atomspace)))
#            g.output()

            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])
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 #26
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)
Example #27
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)
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',
        )
Example #29
0
            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 #30
0
    print len(concept_nodes),'concepts'

    for A in concept_nodes:
        for B in concept_nodes:
            target = T('SubsetLink', A, B)

            print target
            results = chainer.bc(target)
            print results


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'),
Example #31
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 #32
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 #33
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
class TestEntityRecorder(unittest.TestCase):

    def setUp(self):
        self.atomspace = AtomSpace()
        self.test_entity_recorder = EntityRecorder.init_new_entity_recorder()

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

    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.test_entity_recorder.add_none_block_entity(test_handle1,test_pos,
                                                       entity_is_self, entity_is_avatar,
                                                       timestamp)

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

        self.assertTrue(self.test_entity_recorder.get_entity(test_pos).is_undefined())
        #preserve record
        self.assertEqual(test_pos, self.test_entity_recorder.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.test_entity_recorder.add_none_block_entity(test_handle1, test_pos1,
                                                       entity_is_self, entity_is_avatar,
                                                       timestamp1)

        test_pos2 = (17, 28, 40)
        timestamp2 = 12346
        self.test_entity_recorder.update_none_block_entity_location(test_handle1, test_pos2, timestamp2)
        last_location = self.test_entity_recorder.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.test_entity_recorder.add_none_block_entity(test_handle1, test_pos,
                                                           entity_is_self, entity_is_avatar, timestamp)
            test_handle2 = self.test_entity_recorder.get_entity(test_pos)
            self.assertEqual(test_handle1, test_handle2)
            self.assertEqual(test_pos,self.test_entity_recorder.get_last_appeared_location(test_handle1))
            self.test_entity_recorder.remove_none_block_entity(test_handle1)

            self.assertTrue(self.test_entity_recorder.get_entity(test_pos).is_undefined())
            #preserve record
            self.assertEqual(test_pos,self.test_entity_recorder.get_last_appeared_location(test_handle1))
Example #35
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)
InheritanceLink(programmer, fingered, high_tv)
InheritanceLink(programmer, nocturnal, high_tv)

EvaluationLink(live_in, ancients, cave, high_tv)
InheritanceLink(ancients, two_legged, high_tv)
InheritanceLink(ancients, fingered, high_tv)

InheritanceLink(vegetarian, two_legged, high_tv)
InheritanceLink(vegetarian, fingered, high_tv)

# 5. Make custom config.
InheritanceLink(ConceptNode("my-config"), ConceptNode("BLEND"))
ExecutionLink(SchemaNode("BLEND:blending-decider"), ConceptNode("my-config"),
              ConceptNode("DecideNull"))
ExecutionLink(SchemaNode("BLEND:link-connector"), ConceptNode("my-config"),
              ConceptNode("ConnectConflictInteractionInformation"))
ExecutionLink(SchemaNode("BLEND:connect-check-type"), ConceptNode("my-config"),
              ConceptNode("Link"))

# Start Conceptual Blending.
result = ConceptualBlending(a).run([
    a.add_node(types.ConceptNode, "bat"),
    a.add_node(types.ConceptNode, "man")
], ConceptNode("my-config"))

print "Newly blended node:"
print str(result[0]) + "\n"

print "Links in new blended node:"
print result[0].incoming
Example #37
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)
Example #38
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
Example #39
0
class AnaphoraUnitTester(TestCase):

    def setUp(self):

        self.atomspace= AtomSpace()

        scheme_eval(self.atomspace, "(add-to-load-path \"/usr/local/share/opencog/scm\")")
        scheme_eval(self.atomspace, "(use-modules (opencog))")
        scheme_eval(self.atomspace, "(use-modules (opencog atom-types))")
        scheme_eval(self.atomspace, "(use-modules (opencog query))")

        data=["opencog/scm/config.scm",
              "opencog/scm/core_types.scm",
              "opencog/scm/apply.scm",
              "opencog/scm/file-utils.scm",
              "opencog/scm/utilities.scm",
              "opencog/scm/av-tv.scm",
              "opencog/nlp/scm/type-definitions.scm",
              "opencog/nlp/scm/config.scm",
              "opencog/nlp/scm/file-utils.scm",
              "opencog/nlp/scm/nlp-utils.scm",
              "opencog/nlp/scm/disjunct-list.scm",
              "opencog/nlp/scm/processing-utils.scm",
              ]


        for item in data:
            status=load_scm(self.atomspace, item)
            # print "load status=", status, " item=", item

        self.hobbsAgent=HobbsAgent()

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

    def getWord(self,name,type=types.WordInstanceNode):
        word = self.atomspace.add_node(type, name)
        return word

    def compare(self,list_1,list_2):
        if len(list_1)==len(list_2):
            for i in range(len(list_1)):
                if list_1[i]!=list_2[i].name:
                    return False
            return True
        else:
            return False

    def test_bfs(self):

        '''
        Testing the bfs function
        '''

        self.hobbsAgent.initilization(self.atomspace)
        self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/bfs.scm"))

        self.hobbsAgent.run(self.atomspace)
        self.assertTrue(self.compare(['a','b','c','d','e','f','g'],self.hobbsAgent.bfs(self.getWord('a'))))
        self.atomspace.clear()

    #@unittest.skip("debugging skipping")
    def test_getWords(self):

        '''
        Testing the getWords function
        '''

        self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/getWords.scm"))
        self.hobbsAgent.initilization(self.atomspace)
        self.assertTrue(self.compare(['a','b','c','d','e','f','g','h','j'],self.hobbsAgent.getWords()))
        self.atomspace.clear()

    def test_propose(self):

        '''
        Testing the propose function
        '''

        def filter_1():

            print("Testing filter #1...")
            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#1/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent')))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#1/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(self.hobbsAgent.propose(self.getWord('antecedent')))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#1/data_#3.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent')))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#1/data_#4.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent')))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#1/data_#5.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent')))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#1/data_#6.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent')))
            self.atomspace.clear()

        def filter_2():

            print("Testing filter #2...")
            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#2/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(self.hobbsAgent.propose(self.getWord('antecedent')))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#2/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent')))
            self.atomspace.clear()

        def filter_3():

            print("Testing filter #3...")
            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#3/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(self.hobbsAgent.propose(self.getWord('antecedent'),3))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#3/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),3))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#3/data_#3.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),3))
            self.atomspace.clear()

        def filter_4():

            print("Testing filter #4...")
            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#4/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(self.hobbsAgent.propose(self.getWord('antecedent'),4))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#4/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),4))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#4/data_#3.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),4))
            self.atomspace.clear()

        def filter_5():

            print("Testing filter #5...")
            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#5/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(self.hobbsAgent.propose(self.getWord('antecedent'),5))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#5/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),5))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#5/data_#3.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),5))
            self.atomspace.clear()

        def filter_6():

            print("Testing filter #6...")
            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#6/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(self.hobbsAgent.propose(self.getWord('antecedent'),6))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#6/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),6))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#6/data_#3.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),6))
            self.atomspace.clear()

        def filter_7():

            print("Testing filter #7...")
            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#7/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(self.hobbsAgent.propose(self.getWord('antecedent'),7))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#7/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),7))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#7/data_#3.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),7))
            self.atomspace.clear()

        def filter_8():

            print("Testing filter #8...")
            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#8/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(self.hobbsAgent.propose(self.getWord('antecedent'),8))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#8/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),8))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#8/data_#3.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),8))
            self.atomspace.clear()

        def filter_9():

            print("Testing filter #9...")
            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#9/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(self.hobbsAgent.propose(self.getWord('antecedent'),9))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#9/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),9))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#9/data_#3.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),9))
            self.atomspace.clear()

        def filter_10():

            print("Testing filter #10...")
            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#10/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(self.hobbsAgent.propose(self.getWord('antecedent'),10))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#10/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),10))
            self.atomspace.clear()

        def filter_11():

            print("Testing filter #11...")
            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#11/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(self.hobbsAgent.propose(self.getWord('antecedent'),11))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#11/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),11))
            self.atomspace.clear()

        def filter_12():

            print("Testing filter #12...")
            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#12/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(self.hobbsAgent.propose(self.getWord('antecedent',types.ParseNode),12))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#12/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),12))
            self.atomspace.clear()

        def filter_13():

            print("Testing filter #13...")
            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#13/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(self.hobbsAgent.propose(self.getWord('antecedent'),13))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#13/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),13))
            self.atomspace.clear()

        def filter_14():

            print("Testing filter #14...")
            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#14/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(self.hobbsAgent.propose(self.getWord('antecedent'),14))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#14/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),14))
            self.atomspace.clear()

        def filter_15():

            print("Testing filter #15...")
            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#15/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(self.hobbsAgent.propose(self.getWord('antecedent'),15))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#15/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),15))
            self.atomspace.clear()

        def filter_16():

            print("Testing filter #16...")
            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#16/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(self.hobbsAgent.propose(self.getWord('antecedent'),16))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#16/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),16))
            self.atomspace.clear()

        def filter_17():

            print("Testing filter #17...")
            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#17/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(self.hobbsAgent.propose(self.getWord('antecedent'),17))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#17/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),17))
            self.atomspace.clear()

        def filter_18():

            print("Testing filter #18...")
            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#18/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(self.hobbsAgent.propose(self.getWord('antecedent'),18))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#18/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),18))
            self.atomspace.clear()

        filter_1()
        filter_2()
        filter_3()
        filter_4()
        filter_5()
        filter_6()
        filter_7()
        filter_8()
        filter_9()
        filter_10()
        filter_11()
        filter_12()
        filter_13()
        filter_14()
        filter_15()
        filter_16()
        filter_17()
        filter_18()

    #@unittest.skip("debugging skipping")
    def test_pleonastic_if(self):

        self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/pleonastic_it/data_#1.scm"))
        self.hobbsAgent.initilization(self.atomspace)
        self.assertTrue(self.hobbsAgent.pleonastic_it(self.getWord('it')))
        self.atomspace.clear()

        self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/pleonastic_it/data_#2.scm"))
        self.hobbsAgent.initilization(self.atomspace)
        self.assertTrue(self.hobbsAgent.pleonastic_it(self.getWord('it')))
        self.atomspace.clear()

        self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/pleonastic_it/data_#3.scm"))
        self.hobbsAgent.initilization(self.atomspace)
        self.assertTrue(self.hobbsAgent.pleonastic_it(self.getWord('it')))
        self.atomspace.clear()

        self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/pleonastic_it/data_#4.scm"))
        self.hobbsAgent.initilization(self.atomspace)
        self.assertFalse(self.hobbsAgent.pleonastic_it(self.getWord('it')))
        self.atomspace.clear()

        self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/pleonastic_it/data_#5.scm"))
        self.hobbsAgent.initilization(self.atomspace)
        self.assertFalse(self.hobbsAgent.pleonastic_it(self.getWord('it')))
        self.atomspace.clear()

    #@unittest.skip("debugging skipping")
    def test_conjunctions(self):

        self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/conjunction.scm"))
        self.hobbsAgent.initilization(self.atomspace)
        self.assertFalse(self.hobbsAgent.pleonastic_it(self.getWord('waitresses')))
        self.atomspace.clear()
# 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 #41
0
                    # Parse: Predicate
                    concepts = []
                    line = line.split('(')
                    predicate = line[0]

                    # Parse: Concepts
                    done = False
                    line = line[1].split(',')
                    for elem in line:
                        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
Example #42
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
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 #44
0
        pal_a = atom_from_tree(pal, a)

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

        print ps_a.tv

    return result_atoms


if __name__ == '__main__':
    a = AtomSpace()
    log.use_stdout(True)

    atom_from_tree(T('EvaluationLink', a.add_node(t.PredicateNode, 'A')),
                   a).tv = TruthValue(1, 1)
    #atom_from_tree(T('EvaluationLink',1), a).tv = TruthValue(1, 1)

    c = Chainer(a)

    #search(T('EvaluationLink',a.add_node(t.PredicateNode,'B')))
    #fc(a)

    #c.bc(T('EvaluationLink',a.add_node(t.PredicateNode,'A')))

    #    global rules
    #    A = T('EvaluationLink',a.add_node(t.PredicateNode,'A'))
    #    B = T('EvaluationLink',a.add_node(t.PredicateNode,'B'))
    #    rules.append(Rule(B,
    #                                  [ A ]))
Example #45
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)
class TestEntityRecorder(unittest.TestCase):
    def setUp(self):
        self.atomspace = AtomSpace()
        self.test_entity_recorder = EntityRecorder.init_new_entity_recorder()

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

    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.test_entity_recorder.add_none_block_entity(
            test_handle1, test_pos, entity_is_self, entity_is_avatar,
            timestamp)

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

        self.assertTrue(
            self.test_entity_recorder.get_entity(test_pos).is_undefined())
        #preserve record
        self.assertEqual(
            test_pos,
            self.test_entity_recorder.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.test_entity_recorder.add_none_block_entity(
            test_handle1, test_pos1, entity_is_self, entity_is_avatar,
            timestamp1)

        test_pos2 = (17, 28, 40)
        timestamp2 = 12346
        self.test_entity_recorder.update_none_block_entity_location(
            test_handle1, test_pos2, timestamp2)
        last_location = self.test_entity_recorder.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.test_entity_recorder.add_none_block_entity(
                test_handle1, test_pos, entity_is_self, entity_is_avatar,
                timestamp)
            test_handle2 = self.test_entity_recorder.get_entity(test_pos)
            self.assertEqual(test_handle1, test_handle2)
            self.assertEqual(
                test_pos,
                self.test_entity_recorder.get_last_appeared_location(
                    test_handle1))
            self.test_entity_recorder.remove_none_block_entity(test_handle1)

            self.assertTrue(
                self.test_entity_recorder.get_entity(test_pos).is_undefined())
            #preserve record
            self.assertEqual(
                test_pos,
                self.test_entity_recorder.get_last_appeared_location(
                    test_handle1))
Example #47
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 #48
0
class AnaphoraUnitTester(TestCase):

    def setUp(self):

        self.atomspace= AtomSpace()

        scheme_eval(self.atomspace, "(use-modules (opencog))")
        scheme_eval(self.atomspace, "(use-modules (opencog nlp))")
        scheme_eval(self.atomspace, "(use-modules (opencog nlp oc))")

        self.hobbsAgent=HobbsAgent()

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

    def getWord(self,name,type=types.WordInstanceNode):
        word = self.atomspace.add_node(type, name)
        return word

    def compare(self,list_1,list_2):
        if len(list_1)==len(list_2):
            for i in range(len(list_1)):
                if list_1[i]!=list_2[i].name:
                    return False
            return True
        else:
            return False

    def test_bfs(self):

        '''
        Testing the bfs function
        '''

        self.hobbsAgent.initilization(self.atomspace)
        self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/bfs.scm"))

        self.hobbsAgent.run(self.atomspace)
        self.assertTrue(self.compare(['a','b','c','d','e','f','g'],self.hobbsAgent.bfs(self.getWord('a'))))
        self.atomspace.clear()

    def test_getWords(self):

        '''
        Testing the getWords function
        '''

        self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/getWords.scm"))
        self.hobbsAgent.initilization(self.atomspace)
        self.assertTrue(self.compare(['a','b','c','d','e','f','g','h','j'],self.hobbsAgent.getWords()))
        self.atomspace.clear()

    def test_propose(self):

        '''
        Testing the propose function
        '''

        def filter_1():

            print("Testing filter #1...")
            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#1/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent')))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#1/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(self.hobbsAgent.propose(self.getWord('antecedent')))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#1/data_#3.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent')))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#1/data_#4.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent')))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#1/data_#5.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent')))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#1/data_#6.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent')))
            self.atomspace.clear()

        def filter_2():

            print("Testing filter #2...")
            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#2/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(self.hobbsAgent.propose(self.getWord('antecedent')))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#2/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent')))
            self.atomspace.clear()

        def filter_3():

            print("Testing filter #3...")
            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#3/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(self.hobbsAgent.propose(self.getWord('antecedent'),3))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#3/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),3))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#3/data_#3.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),3))
            self.atomspace.clear()

        def filter_4():

            print("Testing filter #4...")
            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#4/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(self.hobbsAgent.propose(self.getWord('antecedent'),4))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#4/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),4))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#4/data_#3.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),4))
            self.atomspace.clear()

        def filter_5():

            print("Testing filter #5...")
            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#5/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(self.hobbsAgent.propose(self.getWord('antecedent'),5))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#5/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),5))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#5/data_#3.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),5))
            self.atomspace.clear()

        def filter_6():

            print("Testing filter #6...")
            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#6/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(self.hobbsAgent.propose(self.getWord('antecedent'),6))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#6/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),6))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#6/data_#3.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),6))
            self.atomspace.clear()

        def filter_7():

            print("Testing filter #7...")
            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#7/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(self.hobbsAgent.propose(self.getWord('antecedent'),7))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#7/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),7))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#7/data_#3.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),7))
            self.atomspace.clear()

        def filter_8():

            print("Testing filter #8...")
            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#8/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(self.hobbsAgent.propose(self.getWord('antecedent'),8))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#8/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),8))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#8/data_#3.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),8))
            self.atomspace.clear()

        def filter_9():

            print("Testing filter #9...")
            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#9/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(self.hobbsAgent.propose(self.getWord('antecedent'),9))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#9/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),9))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#9/data_#3.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),9))
            self.atomspace.clear()

        def filter_10():

            print("Testing filter #10...")
            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#10/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(self.hobbsAgent.propose(self.getWord('antecedent'),10))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#10/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),10))
            self.atomspace.clear()

        def filter_11():

            print("Testing filter #11...")
            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#11/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(self.hobbsAgent.propose(self.getWord('antecedent'),11))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#11/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),11))
            self.atomspace.clear()

        def filter_12():

            print("Testing filter #12...")
            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#12/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(self.hobbsAgent.propose(self.getWord('antecedent',types.ParseNode),12))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#12/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),12))
            self.atomspace.clear()

        def filter_13():

            print("Testing filter #13...")
            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#13/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(self.hobbsAgent.propose(self.getWord('antecedent'),13))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#13/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),13))
            self.atomspace.clear()

        def filter_14():

            print("Testing filter #14...")
            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#14/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(self.hobbsAgent.propose(self.getWord('antecedent'),14))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#14/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),14))
            self.atomspace.clear()

        def filter_15():

            print("Testing filter #15...")
            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#15/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(self.hobbsAgent.propose(self.getWord('antecedent'),15))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#15/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),15))
            self.atomspace.clear()

        def filter_16():

            print("Testing filter #16...")
            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#16/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(self.hobbsAgent.propose(self.getWord('antecedent'),16))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#16/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),16))
            self.atomspace.clear()

        def filter_17():

            print("Testing filter #17...")
            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#17/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(self.hobbsAgent.propose(self.getWord('antecedent'),17))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#17/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),17))
            self.atomspace.clear()

        def filter_18():

            print("Testing filter #18...")
            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#18/data_#1.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertFalse(self.hobbsAgent.propose(self.getWord('antecedent'),18))
            self.atomspace.clear()

            self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/propose/filter-#18/data_#2.scm"))
            self.hobbsAgent.initilization(self.atomspace)
            self.assertTrue(self.hobbsAgent.propose(self.getWord('antecedent'),18))
            self.atomspace.clear()

        filter_1()
        filter_2()
        filter_3()
        filter_4()
        filter_5()
        filter_6()
        filter_7()
        filter_8()
        filter_9()
        filter_10()
        filter_11()
        filter_12()
        filter_13()
        filter_14()
        filter_15()
        filter_16()
        filter_17()
        filter_18()

    def test_pleonastic_if(self):

        self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/pleonastic_it/data_#1.scm"))
        self.hobbsAgent.initilization(self.atomspace)
        self.assertTrue(self.hobbsAgent.pleonastic_it(self.getWord('it')))
        self.atomspace.clear()

        self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/pleonastic_it/data_#2.scm"))
        self.hobbsAgent.initilization(self.atomspace)
        self.assertTrue(self.hobbsAgent.pleonastic_it(self.getWord('it')))
        self.atomspace.clear()

        self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/pleonastic_it/data_#3.scm"))
        self.hobbsAgent.initilization(self.atomspace)
        self.assertTrue(self.hobbsAgent.pleonastic_it(self.getWord('it')))
        self.atomspace.clear()

        self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/pleonastic_it/data_#4.scm"))
        self.hobbsAgent.initilization(self.atomspace)
        self.assertFalse(self.hobbsAgent.pleonastic_it(self.getWord('it')))
        self.atomspace.clear()

        self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/pleonastic_it/data_#5.scm"))
        self.hobbsAgent.initilization(self.atomspace)
        self.assertFalse(self.hobbsAgent.pleonastic_it(self.getWord('it')))
        self.atomspace.clear()

    def test_conjunctions(self):
        self.assertTrue(load_scm(self.atomspace, "tests/nlp/anaphora/data/conjunction.scm"))
        self.hobbsAgent.initilization(self.atomspace)
        self.assertFalse(self.hobbsAgent.pleonastic_it(self.getWord('waitresses')))
        self.atomspace.clear()
Example #49
0
    print len(concept_nodes),'concepts'

    for A in concept_nodes:
        for B in concept_nodes:
            target = T('SubsetLink', A, B)

            print target
            results = chainer.bc(target)
            print results


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'),
Example #50
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)
ExecutionLink(
    SchemaNode("BLEND:blending-decider"),
    ConceptNode("my-config"),
    ConceptNode("DecideNull")
)
ExecutionLink(
    SchemaNode("BLEND:link-connector"),
    ConceptNode("my-config"),
    ConceptNode("ConnectConflictInteractionInformation")
)
ExecutionLink(
    SchemaNode("BLEND:connect-check-type"),
    ConceptNode("my-config"),
    ConceptNode("Link")
)

# Start Conceptual Blending.
result = ConceptualBlending(a).run(
    [
        a.add_node(types.ConceptNode, "bat"),
        a.add_node(types.ConceptNode, "man")
    ],
    ConceptNode("my-config")
)

print "Newly blended node:"
print str(result[0]) + "\n"

print "Links in new blended node:"
print result[0].incoming
Example #52
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 #53
0
        ps_a  = atom_from_tree(ps, a)
        pal_a = atom_from_tree(pal, a)
        
        print ps
        print pal
        ps_a.tv = TruthValue(1.0, confidence_to_count(1.0))
        
        print ps_a.tv
    
    return result_atoms

if __name__ == '__main__':
    a = AtomSpace()
    log.use_stdout(True)

    atom_from_tree(T('EvaluationLink',a.add_node(t.PredicateNode,'A')), a).tv = TruthValue(1, 1)
    #atom_from_tree(T('EvaluationLink',1), a).tv = TruthValue(1, 1)

    c = Chainer(a)

    #search(T('EvaluationLink',a.add_node(t.PredicateNode,'B')))
    #fc(a)

    #c.bc(T('EvaluationLink',a.add_node(t.PredicateNode,'A')))

#    global rules
#    A = T('EvaluationLink',a.add_node(t.PredicateNode,'A'))
#    B = T('EvaluationLink',a.add_node(t.PredicateNode,'B'))
#    rules.append(Rule(B, 
#                                  [ A ]))
Example #54
0
this relationship.

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,
Example #55
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 #56
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 #57
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])],
Example #58
0
deduction_agent.py instead.
"""

from __future__ import print_function
from pprint import pprint
from pln.examples.deduction import deduction_agent
from opencog.atomspace import types, AtomSpace, TruthValue

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