def setUp(self): self.atomspace = AtomSpace() # Get the config file name in a manner not dependent on the # starting working directory. full_path = os.path.realpath(__file__) config_file_name = os.path.dirname(full_path) + "/bindlink_test.conf" # Initialize Python initialize_opencog(self.atomspace, config_file_name) # Define several animals and something of a different type as well InheritanceLink(ConceptNode("Frog"), ConceptNode("animal")) InheritanceLink(ConceptNode("Zebra"), ConceptNode("animal")) InheritanceLink(ConceptNode("Deer"), ConceptNode("animal")) InheritanceLink(ConceptNode("Spaceship"), ConceptNode("machine")) # Define a graph search query self.bindlink_handle = \ BindLink( # The variable node to be grounded. VariableNode("$var"), # The pattern to be grounded. ImplicationLink( InheritanceLink( VariableNode("$var"), ConceptNode("animal") ), # The grounding to be returned. VariableNode("$var") ) # bindlink needs a handle ).h
def setUp(self): print "setUp - atomspace = ", self.atomspace # Get the config file name in a manner not dependent on the # starting working directory. full_path = os.path.realpath(__file__) config_file_name = os.path.dirname(full_path) + "/bindlink_test.conf" # Initialize Python initialize_opencog(self.atomspace, config_file_name) set_type_ctor_atomspace(self.atomspace) # Define several animals and something of a different type as well InheritanceLink( ConceptNode("Frog"), ConceptNode("animal")) InheritanceLink( ConceptNode("Zebra"), ConceptNode("animal")) InheritanceLink( ConceptNode("Deer"), ConceptNode("animal")) InheritanceLink( ConceptNode("Spaceship"), ConceptNode("machine")) # Define a graph search query self.bindlink_handle = \ BindLink( # The variable node to be grounded. VariableNode("$var"), # The pattern to be grounded. InheritanceLink( VariableNode("$var"), ConceptNode("animal") ), # The grounding to be returned. VariableNode("$var") # bindlink needs a handle ).h
def main(): atomspace = AtomSpace() initialize_opencog(atomspace) device = 'cpu' epoch = 20 batch_size = 2 lr = 0.0001 decay_rate = 0.9 decay_steps = 10000 train_loader = torch.utils.data.DataLoader(datasets.MNIST( '/tmp/mnist', train=True, download=True, transform=transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.1307, ), (0.3081, )) ])), batch_size=batch_size, shuffle=True) model = MnistModel(atomspace).to(device) optimizer = optim.Adam(model.parameters(), lr=lr) l = lambda step: exponential_lr( decay_rate, step, decay_steps, staircase=True) scheduler = optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=l) for i in range(epoch): train(model, device, train_loader, optimizer, i + 1, 200, scheduler) torch.save(model.state_dict(), "mnist_cnn.pt")
def tmp_atomspace(atomspace): parent_atomspace = atomspace atomspace = create_child_atomspace(parent_atomspace) initialize_opencog(atomspace) try: yield atomspace finally: atomspace.clear() finalize_opencog() initialize_opencog(parent_atomspace)
def setUp(self): self.atomspace = AtomSpace() initialize_opencog(self.atomspace) scheme_eval(self.atomspace, '(use-modules (opencog))') scheme_eval(self.atomspace, '(use-modules (opencog exec))') scheme_eval(self.atomspace, '(use-modules (opencog query))') scheme_eval(self.atomspace, '(use-modules (opencog logger))') scheme_eval(self.atomspace, '(use-modules (opencog rule-engine))') scm_dir = os.environ["SCM_DIR"] scheme_eval(self.atomspace, '(add-to-load-path "{0}")'.format(scm_dir))
def setUp(self): # self.atsp = scheme_eval_as('(cog-atomspace)') self.atsp = AtomSpace() #creating atomspace self.TV = TruthValue() self.test_dog = self.atsp.add_node(types.ConceptNode, "Dog", self.TV) self.test_cat = self.atsp.add_node(types.ConceptNode, "Cat", self.TV) self.test_animal = self.atsp.add_node(types.ConceptNode, "Animal", self.TV) self.test_color = self.atsp.add_node(types.ConceptNode, "color", self.TV) initialize_opencog(self.atsp)
def main(): torch.set_grad_enabled(False) atomspace = AtomSpace() initialize_opencog(atomspace) tbd_net_checkpoint = '/mnt/fileserver/shared/models/tbd-nets-models/clevr-reg.pt' vocab = load_vocab( Path('/mnt/fileserver/shared/models/tbd-nets-models/data/vocab.json')) tbd_net = load_tbd_net(tbd_net_checkpoint, vocab, feature_dim=(1024, 14, 14)) wrappers = tbd_helpers.generate_wrappers(tbd_net.function_modules, atomspace) tbd_helpers.setup_inheritance(tbd_net.function_modules, atomspace) test(atomspace) BATCH_SIZE = 64 val_loader_kwargs = { 'question_h5': Path( '/mnt/fileserver/shared/datasets/CLEVR_v1/data/val_questions_query_ending.h5' ), 'feature_h5': Path('/mnt/fileserver/shared/datasets/CLEVR_v1/data/val_features.h5'), 'batch_size': BATCH_SIZE, 'num_workers': 0, 'shuffle': False } scheme_eval(atomspace, '(use-modules (opencog logger))') scheme_eval(atomspace, '(cog-logger-set-level! "fine")') loader = ClevrDataLoaderH5(**val_loader_kwargs) model = TBDModel(atomspace) total_acc = 0 for i, batch in enumerate(loader): _, _, feats, expected_answers, programs = batch feats = feats.to(device) programs = programs.to(device) results = model.answer_by_programs(tbd_net, feats, programs) correct = 0 clevr_numeric_actual_answers = [ clevr_answers_map_str_int[x] for x in results ] for (actual, expected) in zip(clevr_numeric_actual_answers, expected_answers): correct += 1 if actual == expected else 0 acc = float(correct) / len(programs) total_acc = total_acc * (i / (i + 1)) + acc / (i + 1) print("Accuracy average: {0}".format(total_acc))
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 setUp(self): print ("setUp - atomspace = ", self.atomspace) # Clear atoms from previous test self.atomspace.clear() # Initialize Python initialize_opencog(self.atomspace) set_type_ctor_atomspace(self.atomspace) # Define several animals and something of a different type as well InheritanceLink( ConceptNode("Frog"), ConceptNode("animal")) InheritanceLink( ConceptNode("Zebra"), ConceptNode("animal")) InheritanceLink( ConceptNode("Deer"), ConceptNode("animal")) InheritanceLink( ConceptNode("Spaceship"), ConceptNode("machine")) # Define a graph search query self.bindlink_atom = \ BindLink( # The variable node to be grounded. VariableNode("$var"), # The pattern to be grounded. InheritanceLink( VariableNode("$var"), ConceptNode("animal") ), # The grounding to be returned. VariableNode("$var") # bindlink needs a handle ) # Define a pattern to be grounded self.getlink_atom = \ GetLink( InheritanceLink( VariableNode("$var"), ConceptNode("animal") ) ) # Remember the starting atomspace size. self.starting_size = self.atomspace.size()
def setUp(self): print "setUp - atomspace = ", self.atomspace # Clear atoms from previous test self.atomspace.clear() # Initialize Python initialize_opencog(self.atomspace, "") set_type_ctor_atomspace(self.atomspace) # Define several animals and something of a different type as well InheritanceLink( ConceptNode("Frog"), ConceptNode("animal")) InheritanceLink( ConceptNode("Zebra"), ConceptNode("animal")) InheritanceLink( ConceptNode("Deer"), ConceptNode("animal")) InheritanceLink( ConceptNode("Spaceship"), ConceptNode("machine")) # Define a graph search query self.bindlink_atom = \ BindLink( # The variable node to be grounded. VariableNode("$var"), # The pattern to be grounded. InheritanceLink( VariableNode("$var"), ConceptNode("animal") ), # The grounding to be returned. VariableNode("$var") # bindlink needs a handle ) # Define a pattern to be grounded self.getlink_atom = \ GetLink( InheritanceLink( VariableNode("$var"), ConceptNode("animal") ) ) # Remember the starting atomspace size. self.starting_size = self.atomspace.size()
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 main(): path_query = 'query.scm' path_data = 'data.scm' atomspace = AtomSpace() initialize_opencog(atomspace) storage = Storage() index = Index(storage) with tmp_atomspace() as tmp: imp = ImplicationLink(VariableNode("C"), VariableNode("B")) # GetLink returns only bindings for variables pat = BindLink(imp, imp) index.add_pattern(pat) with tmp_atomspace() as tmp: base = open(path_data).read() data = scheme_eval_h(tmp, base) index.add_data(data) query = open(path_query).read() q = scheme_eval_h(tmp, query) result = index.query(tmp, q) print(result)
def __init__(self, fname): self.config = configparser.ConfigParser() self.config.read(fname) self.__atomspace = AtomSpace() initialize_opencog(self.atomspace) self.queue_send = Queue() self.queue_recv = Queue() self.hass_thread = start_HassCommunicator_in_thread( self.config['DEFAULT']['uri'], self.config['DEFAULT']['token'], self.queue_send, self.queue_recv) self.home_state = HomeState( self.queue_recv.get(), self.queue_send, safe_load_entity_ids( self.config['DEFAULT']['known_entity_ids_file'])) safe_save_entity_ids(self.home_state.get_all_entity_ids(), self.config['DEFAULT']['known_entity_ids_file']) self.__current_event_gon = GroundedObjectNode("current_event", None)
from opencog.spacetime import SpaceTimeAndAtomSpace from opencog.atomspace import AtomSpace, types from opencog.type_constructors import set_type_ctor_atomspace from opencog.utilities import initialize_opencog, finalize_opencog from perception_module import PerceptionManager from attention_module import AttentionController from action_gen import ActionGenerator from grounded_knowledge import GroundedKnowledge rospy.init_node('OpenCog_Perception') spacetime = SpaceTimeAndAtomSpace() full_path = os.path.realpath(__file__) config_file_name = os.path.dirname(full_path) + "/opencog_python_eval.conf" print config_file_name # import GSN/GPN schema initialize_opencog(spacetime.get_atomspace(), config_file_name) set_type_ctor_atomspace(spacetime.get_atomspace()) pm = PerceptionManager(spacetime.get_atomspace(), spacetime.get_space_server(), spacetime.get_time_server()) ag = ActionGenerator(spacetime.get_atomspace(), spacetime.get_space_server(), spacetime.get_time_server()) ac = AttentionController(spacetime.get_atomspace()) gn = GroundedKnowledge(spacetime.get_atomspace(), spacetime.get_space_server(), spacetime.get_time_server()) time_step = 1 print "\nAtomspace contains %s atoms" % len(spacetime.get_atomspace()) gn.load_block_knowledge(1.0)
def create_child_atomspace(): global child_atomspace child_atomspace = create_temp_atomspace(atomspace) initialize_opencog(child_atomspace) return child_atomspace
from opencog.spacetime import SpaceTimeAndAtomSpace from opencog.atomspace import AtomSpace, types from opencog.type_constructors import set_type_ctor_atomspace from opencog.utilities import initialize_opencog, finalize_opencog from perception_module import PerceptionManager from attention_module import AttentionController from action_gen import ActionGenerator from grounded_knowledge import GroundedKnowledge rospy.init_node('OpenCog_Perception') spacetime = SpaceTimeAndAtomSpace() full_path = os.path.realpath(__file__) config_file_name = os.path.dirname(full_path) + "/opencog_python_eval.conf" print config_file_name # import GSN/GPN schema initialize_opencog(spacetime.get_atomspace(), config_file_name) set_type_ctor_atomspace(spacetime.get_atomspace()) pm = PerceptionManager(spacetime.get_atomspace(), spacetime.get_space_server(), spacetime.get_time_server()) ag = ActionGenerator(spacetime.get_atomspace(), spacetime.get_space_server(), spacetime.get_time_server()) ac = AttentionController(spacetime.get_atomspace()) gn = GroundedKnowledge(spacetime.get_atomspace(), spacetime.get_space_server(), spacetime.get_time_server()) time_step = 1
vehicle=> SimilarityLink (stv 0.100000 0.900000) person=> SimilarityLink (stv 0.800000 0.900000) ----- (ConceptNode "car-man-2") ; [537] vehicle=> SimilarityLink (stv 0.100000 0.900000) person=> SimilarityLink (stv 0.800000 0.900000) ----- (ConceptNode "car-man-3") ; [538] vehicle=> SimilarityLink (stv 0.100000 0.900000) person=> SimilarityLink (stv 0.800000 0.900000) """ print "--------Start third example--------" a = AtomSpace() initialize_opencog(a) # Make custom concept network. """ Make test nodes. """ # Nodes will be blended: car = ConceptNode("car") man = ConceptNode("man") # A. Car is metal. (Not duplicated) metal = ConceptNode("metal") # B. Car moves, man moves. (Duplicated, not conflicted) move = ConceptNode("move")
if (not test): print "assert_true FAILED: test ", test def add_link(atom_one, atom_two): return ListLink(atom_one, atom_two) atomspace = AtomSpace() # Get the config file name in a manner not dependent on the # starting working directory. full_path = os.path.realpath(__file__) config_file_name = os.path.dirname(full_path) + "/bindlink_test.conf" print config_file_name # Initialize Python initialize_opencog(atomspace, config_file_name) # Define several animals and something of a different type as well InheritanceLink( ConceptNode("Frog"), ConceptNode("animal")) InheritanceLink( ConceptNode("Zebra"), ConceptNode("animal")) InheritanceLink( ConceptNode("Deer"), ConceptNode("animal")) InheritanceLink( ConceptNode("Spaceship"), ConceptNode("machine")).truth_value(0.5,0.5) # Define a graph search query bindlink_handle = \ BindLink( # The variable node to be grounded. VariableNode("$var"), # The pattern to be grounded. InheritanceLink(
def delete_child_atomspace(): global child_atomspace child_atomspace.clear() finalize_opencog() initialize_opencog(atomspace)
def assert_equals(object_one, object_two): if (object_one != object_two): print "assert_equals FAILED: one ", object_one, ", two ", object_two def assert_true(test): if (not test): print "assert_true FAILED: test ", test def add_link(atom_one, atom_two): return ListLink(atom_one, atom_two) atomspace = AtomSpace() # Initialize Python initialize_opencog(atomspace, "") # Define several animals and something of a different type as well InheritanceLink( ConceptNode("Frog"), ConceptNode("animal")) InheritanceLink( ConceptNode("Zebra"), ConceptNode("animal")) InheritanceLink( ConceptNode("Deer"), ConceptNode("animal")) InheritanceLink( ConceptNode("Spaceship"), ConceptNode("machine")).truth_value(0.5,0.5) # Define a graph search query bindlink_atom = \ BindLink( # The variable node to be grounded. VariableNode("$var"), # The pattern to be grounded. InheritanceLink(
from opencog.atomspace import AtomSpace, types from opencog.utilities import initialize_opencog, finalize_opencog from opencog.bindlink import execute_atom import opencog.scheme_wrapper as scheme from opencog.scheme_wrapper import load_scm, scheme_eval from opencog.type_constructors import * atomspace = AtomSpace() # Initialize Scheme scheme_preload = ["opencog/scm/core_types.scm", "opencog/scm/utilities.scm"] scheme.__init__(atomspace) for scheme_file in scheme_preload: load_scm(atomspace, scheme_file) initialize_opencog(atomspace, "utilities_test.conf") executed = False def add_link(atom1, atom2): global executed link = ListLink(atom1, atom2) executed = True return link execute_code = \ ''' (cog-execute! (ExecutionOutputLink (GroundedSchemaNode \"py: add_link\")
def create_and_init_atomspace(): atomspace = AtomSpace() initialize_opencog(atomspace) scheme_eval(atomspace, '(use-modules (opencog) (opencog exec))') return atomspace
def setUp(self): self.atomspace = AtomSpace() initialize_opencog(self.atomspace) init_pln()
def setUp(self): #creating atomspace self.atsp = AtomSpace() self.TV = TruthValue() initialize_opencog(self.atsp)
import opencog.scheme_wrapper as scheme from opencog.scheme_wrapper import load_scm, scheme_eval from opencog.type_constructors import * atomspace = AtomSpace() # Initialize Scheme scheme_preload = [ "opencog/atomspace/core_types.scm", "opencog/scm/utilities.scm" ] scheme.__init__(atomspace) for scheme_file in scheme_preload: load_scm(atomspace, scheme_file) initialize_opencog(atomspace, "utilities_test.conf") executed = False def add_link(atom1, atom2): global executed link = ListLink(atom1, atom2) executed = True return link execute_code = \ ''' (cog-execute! (ExecutionOutputLink (GroundedSchemaNode \"py: add_link\") (ListLink
def add_link(atom_one, atom_two): return ListLink(atom_one, atom_two) atomspace = AtomSpace() # Get the config file name in a manner not dependent on the # starting working directory. full_path = os.path.realpath(__file__) config_file_name = os.path.dirname(full_path) + "/bindlink_test.conf" print config_file_name # Initialize Python initialize_opencog(atomspace, config_file_name) # Define several animals and something of a different type as well InheritanceLink(ConceptNode("Frog"), ConceptNode("animal")) InheritanceLink(ConceptNode("Zebra"), ConceptNode("animal")) InheritanceLink(ConceptNode("Deer"), ConceptNode("animal")) InheritanceLink(ConceptNode("Spaceship"), ConceptNode("machine")).truth_value(0.5, 0.5) # Define a graph search query bindlink_handle = \ BindLink( # The variable node to be grounded. VariableNode("$var"), # The pattern to be grounded.
def setUp(self): self.space = AtomSpace() initialize_opencog(self.space)
def test_initialize_finalize(self): initialize_opencog(self.atomspace) finalize_opencog()
def setUpClass(cls): global atomspace atomspace = AtomSpace() initialize_opencog(atomspace)
def create_child_atomspace(self): self.child_atomspace = create_child_atomspace(self.atomspace) initialize_opencog(self.child_atomspace) return self.child_atomspace
from opencog.utilities import initialize_opencog from opencog.atomspace import types, get_refreshed_types from opencog.bindlink import execute_atom from opencog.type_constructors import * from opencog.atomspace import AtomSpace import numpy as np import random types=get_refreshed_types() atomspace = AtomSpace() initialize_opencog(atomspace) def simneu(X,Y): # change input dataset to matrix format print X,Y mat = [] row = [] atom = str(X.name) atom = atom.split(',') mat2 = [] row2 = [] atom2 = str(Y.name) atom2 = atom2.split(',') for i in range(0, len(atom)):
def setUp(self): initialize_opencog() self.atomspace = AtomSpace() set_default_atomspace(self.atomspace)
input = yolo.classes.Input( model='yolov3', img_path= 'https://multimedia.bbycastatic.ca/multimedia/products/500x500/109/10942/10942869.jpg', confidence='0.8') log.info('input: %s' % input) output = yolo.stub.detect(input) #log.info('data received: %s' % output) devices = list( map(lambda x: ConceptNode(x), map(lambda x: map_names[x], json.loads(output.class_ids)))) log.info('list of devices: %s' % devices) return devices def run(): define_knowledge_base() yolo = get_yolo_service() devices = detect_device(yolo) for device in devices: parts = query_parts_for_donation(device) print('You could donate the following parts: %s' % parts) if __name__ == '__main__': log.basicConfig(level=log.INFO) space = AtomSpace() initialize_opencog(space) run()
def delete_child_atomspace(self): self.child_atomspace.clear() finalize_opencog() initialize_opencog(self.atomspace)
from opencog.type_constructors import * from opencog.utilities import initialize_opencog from opencog.bindlink import execute_atom # Initialize AtomSpace atomspace = AtomSpace() initialize_opencog(atomspace) key = PredicateNode("key") atom = ConceptNode("atom") atom.set_value(key, FloatValue(3)) value_of_link = ValueOfLink(atom, key) res = execute_atom(atomspace, value_of_link) print(res)
def setUp(self): self.atomspace = AtomSpace() self.model = CogModel(self.atomspace) initialize_opencog(self.atomspace)