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 setUp(self): self.atomSpaceFileData = AtomSpace() self.atomSpaceInputs = AtomSpace() self.atomSpaceExpected = AtomSpace() self.testFiles = [] self.chainer = None # Works: self.addTestFile("SubsetAS_new.scm") self.addTestFile("AndRule_new.scm") self.addTestFile("BooleanTransformationRule_new.scm") self.addTestFile("DeductionRule_InheritanceLink.scm") self.addTestFile("InheritanceRule.scm") self.addTestFile("InductionRule_InheritanceLink.scm") self.addTestFile( "AbductionRule_InheritanceLink.scm") # Under investigation self.addTestFile("InversionRule_InheritanceLink.scm") self.addTestFile("OrCreationRule.scm") self.addTestFile("OrRule_new.scm") self.addTestFile("NotCreationRule.scm") self.addTestFile("TransitiveSimilarityRule_SimilarityLink.scm") self.addTestFile("AndAs1stArgInsideLinkRule_InheritanceLink.scm") self.addTestFile("AndAs2ndArgInsideLinkRule_InheritanceLink.scm") self.addTestFile("SatisfyingSetToConceptRule.scm") # context rules self.addTestFile("InheritanceToContextRule.scm") self.addTestFile("ContextToInheritanceRule.scm") self.addTestFile("ContextToEvaluationRule.scm") self.addTestFile("ContextToSubsetRule.scm") self.addTestFile("EvaluationToContextRule.scm") self.addTestFile("SubsetToContextRule.scm")
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 main(): # Init loggers log.set_level("fine") log.set_sync(False) agent_log.set_level("fine") agent_log.set_sync(False) ure_logger().set_level("fine") ure_logger().set_sync(False) # Set main atomspace atomspace = AtomSpace() set_default_atomspace(atomspace) # Wrap environment wrapped_env = CartPoleWrapper(env) # Instantiate CartPoleAgent, and tune parameters cpa = CartPoleAgent(wrapped_env) cpa.delta = 1.0e-16 # Run control loop while cpa.step(): time.sleep(0.1) log.info("step_count = {}".format(cpa.step_count)) print(f"The final reward is {cpa.accumulated_reward}.")
def setUp(self): self.atomspace = AtomSpace() scheme.__init__(self.atomspace) for scheme_file in scheme_preload: load_scm(self.atomspace, scheme_file) # Define several animals and something of a different type as well scheme_animals = \ ''' (InheritanceLink (ConceptNode "Frog") (ConceptNode "animal")) (InheritanceLink (ConceptNode "Zebra") (ConceptNode "animal")) (InheritanceLink (ConceptNode "Deer") (ConceptNode "animal")) (InheritanceLink (ConceptNode "Spaceship") (ConceptNode "machine")) ''' scheme_eval_h(self.atomspace, scheme_animals) # Define a graph search query bind_link_query = \ ''' (BindLink ;; The variable to be bound (VariableNode "$var") (ImplicationLink ;; The pattern to be searched for (InheritanceLink (VariableNode "$var") (ConceptNode "animal") ) ;; The value to be returned. (VariableNode "$var") ) ) ''' self.bindlink_handle = scheme_eval_h(self.atomspace, bind_link_query)
def initializeAtomspace(): atomspace = AtomSpace() set_type_ctor_atomspace(atomspace) scheme_eval(atomspace, "(use-modules (opencog))") scheme_eval(atomspace, "(use-modules (opencog exec))") scheme_eval(atomspace, "(use-modules (opencog query))") return atomspace
def main(): # Init loggers log.set_level("fine") log.set_sync(False) agent_log.set_level("fine") agent_log.set_sync(False) ure_logger().set_level("fine") ure_logger().set_sync(False) # Set main atomspace atomspace = AtomSpace() set_default_atomspace(atomspace) # Wrap environment wrapped_env = CartPoleWrapper(env, atomspace) # Instantiate CartPoleAgent, and tune parameters cpa = FixedCartPoleAgent(wrapped_env, atomspace) cpa.delta = 1.0e-16 # Run control loop while not cpa.control_cycle(): wrapped_env.render() time.sleep(0.1) log.info("cycle_count = {}".format(cpa.cycle_count)) log_msg(agent_log, f"The final reward is {cpa.accumulated_reward}.")
def setUp(self): self.atomspace = AtomSpace() __init__(self.atomspace) data = [ "opencog/scm/config.scm", "opencog/atomspace/core_types.scm", "spacetime/spacetime_types.scm", "opencog/nlp/types/nlp_types.scm", "opencog/dynamics/attention/attention_types.scm", "opencog/embodiment/AtomSpaceExtensions/embodiment_types.scm", "opencog/learning/pln/pln_types.scm", "opencog/scm/apply.scm", "opencog/scm/file-utils.scm", "opencog/scm/persistence.scm", #"opencog/scm/repl-shell.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", "opencog/nlp/scm/relex-to-logic.scm", ] for item in data: status = load_scm(self.atomspace, item) self.hobbsAgent = HobbsAgent()
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 __init__(self, atomspace, stimulateAtoms=False, agent=None, learnRuleFrequencies=False): AbstractChainer.__init__(self, atomspace) # It stores a reference to the MindAgent object so it can stimulate atoms. self._stimulateAtoms = stimulateAtoms self._agent = agent self.atomspace = atomspace # For every atom, store the atoms used to produce it (including the atoms used to produce them). # This prevents cycles (very important) as well as repeating the same inference. # Map from Atom -> set(Atom) # Default value is the empty set self.trails = defaultdict(set) #self.produced_from = defaultdict(set) self.history_index = InferenceHistoryIndex() self.history_atomspace = AtomSpace() # TODO actually load and save these. When loading it, rebuild the indexes above. # Record how often each Rule is used. To bias the Rule frequencies. # It will take longer to adapt if you set this higher (this is important so it won't # get a crazy feedback loop). initial_frequency = 100 def constant_factory(): return initial_frequency if learnRuleFrequencies: self.learnRuleFrequencies = True self.rule_count = defaultdict(constant_factory)
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 setUp(self): self.a = AtomSpace() self.x1 = self.a.add(t.ConceptNode, "test1") self.x2 = self.a.add(t.ConceptNode, "test2") self.l1 = self.a.add(t.Link, out=[self.x1, self.x2]) self.l2 = self.a.add(t.Link, out=[self.l1, self.x2]) print 'l1', self.l1
def do_test(test, name, n): """Runs test on n nodes and prints the test name and performance""" a = AtomSpace() start = time.time() ops = test(a, n) finish = time.time() print name print " Items per second: {0:.0f}".format(ops / (finish - start))
def setUp(self): self.space = AtomSpace() tempfd, self.tempfn = tempfile.mkstemp() # close the temp file as Logger will want to manually # open it os.close(tempfd) self.log = opencog.util.create_logger(self.tempfn)
def setUp(self): self.atomspace = AtomSpace() scheme_eval(self.atomspace, "(use-modules (opencog))") scheme_eval(self.atomspace, "(use-modules (opencog nlp))") self.hobbsAgent = HobbsAgent()
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 setUp(self): self.atomSpaceFileData = AtomSpace() self.atomSpaceInputs = AtomSpace() self.atomSpaceExpected = AtomSpace() self.testFiles = [] self.chainer = None # Works: self.addTestFile("AndRule_new.scm") self.addTestFile("BooleanTransformationRule_new.scm") self.addTestFile("DeductionRule_InheritanceLink.scm") self.addTestFile("InversionRule_InheritanceLink.scm") self.addTestFile("OrCreationRule.scm") self.addTestFile("OrRule_new.scm") self.addTestFile("NotCreationRule.scm") self.addTestFile("InductionRule_InheritanceLink.scm") self.addTestFile("AbductionRule_InheritanceLink.scm") self.addTestFile("TransitiveSimilarityRule_SimilarityLink.scm")
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 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 load_atomspace(): """ loads atomspace with knowledge bases and annotation scheme functions found in scm directory. :return: atomspace instance """ atomspace = AtomSpace() scheme_eval(atomspace, '(primitive-load "{}")'.format(config.OPENCOG_DEPS_PATH)) atomspace = load_datasets(atomspace) atomspace = apply_pln(atomspace) return atomspace
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 query))") scheme_eval(self.atomspace, "(use-modules (opencog nlp))") self.hobbsAgent = HobbsAgent()
def setUp(self): self.atomSpaceFileData = AtomSpace() self.atomSpaceInputs = AtomSpace() self.atomSpaceExpected = AtomSpace() self.testFiles = [] self.chainer = None # Works: # self.addTestFile("AbductionRule_InheritanceLink.scm") # Under investigation self.addTestFile("AndRule_new.scm") self.addTestFile("BooleanTransformationRule_new.scm") self.addTestFile("DeductionRule_InheritanceLink.scm") #self.addTestFile("InductionRule_InheritanceLink.scm") # disabled due to result swapping CNodes on buildbot self.addTestFile("InheritanceRule.scm") self.addTestFile("InversionRule_InheritanceLink.scm") self.addTestFile("OrCreationRule.scm") self.addTestFile("OrRule_new.scm") self.addTestFile("NotCreationRule.scm") self.addTestFile("TransitiveSimilarityRule_SimilarityLink.scm")
def set_up_atomspace(): """ Initializes a new atomspace, loads the core types and utitities. :return: an atomspace """ coreTypes = "opencog/atomspace/core_types.scm" utilities = "opencog/scm/utilities.scm" newly_created_atomspace = AtomSpace() __init__(newly_created_atomspace) for item in [coreTypes, utilities]: load_scm(newly_created_atomspace, item) return newly_created_atomspace
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 load_atomspace(): """ loads atomspace with knowledge bases and annotation scheme functions found in scm directory. :return: atomspace instance """ atomspace = AtomSpace() logger.info("Loading Atoms") print("loading atoms") scheme_eval(atomspace, '(primitive-load "{}")'.format(config.OPENCOG_DEPS_PATH)) print("initial atoms:" + scheme_eval(atomspace, "(count-all)").decode("utf-8")) atomspace = load_datasets(atomspace) atomspace = apply_pln(atomspace) print("after datasets:" +scheme_eval(atomspace, "(count-all)").decode("utf-8")) print("done") logger.info("Atoms loaded!") return atomspace
def test_load_scm_file(): # load a scm file a = AtomSpace() load_scm_file(a, "./test/scm/test_load_scm_file.scm") #load_scm_file(a, "./air.scm") # output atomspace to file "diff_log" output_atomspace(a, "py_atomspace.log") # compare output with output of atomspace loaded with cogserver if rough_compare_files( "py_atomspace.log", "./test/log/server_atomspace.log") and rough_compare_files( "./test/log/server_atomspace.log", "py_atomspace.log"): log.info("test passed!") else: log.info("test failed!")
def test_cartpole(): env = gym.make("CartPole-v1") # Set main atomspace atomspace = AtomSpace() set_default_atomspace(atomspace) # Wrap environment wrapped_env = CartPoleWrapper(env, atomspace) # Instantiate CartPoleAgent, and tune parameters cpa = FixedCartPoleAgent(wrapped_env, atomspace) cpa.delta = 1.0e-16 # Run control loop while not cpa.control_cycle(): time.sleep(0.1)
def run(self): atomspace = AtomSpace() scheme_clear=\ """ (clear) """ scheme_code=\ """ (load-scm-from-file "/home/mahlet/webCodes/moses_result.scm") """ scheme_eval(atomspace, scheme_clear) scheme_eval(atomspace, scheme_code) #start the REST API IP_ADDRESS = '0.0.0.0' PORT = 5000 api = RESTAPI(atomspace) api.run(host=IP_ADDRESS, port=PORT)
def do_test(prep, test, description, op_time_adjustment): """Runs tests and prints the test name and performance""" if not args.columns: print description if (test != None): total_time = 0 total_ops = 0 for i in xrange(test_iterations): # Prep the test atomspace = AtomSpace() prep_result = prep(atomspace) # Time the test start = time.time() ops = test(atomspace, prep_result) finish = time.time() # Add the time and ops for this iteration total_time += finish - start total_ops += ops average_time = total_time / test_iterations average_ops = total_ops / test_iterations adjusted_time = average_time - (ops * op_time_adjustment) # Print timing results if args.verbose: time_string = "{0:.03f}".format(adjusted_time) print " Total: {0: >12}s".format(time_string) test_ops = "{0:,d}".format(int(average_ops)) print " Ops: {0: >12}".format(test_ops) op_time = "{0:.03f}".format(adjusted_time * 1000000 / ops) ops_sec = "{0:,d}".format(int(ops / adjusted_time)) if args.columns: print "{0: <40} {1: >12}µs {2: >15}".format( description, op_time, ops_sec) else: print " Op time: {0: >12}µs".format(op_time) print " Ops/sec: {0: >12}".format(ops_sec) print
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)