def test_conjunction_fuzzy_with_virtual_evaluation(self): """Test for correct vardecl parameter initialization in BackwardChainer vardecl = VariableList() would cause empty set as backward chaining result vardecl = UNDEFINED should produce two results: (Item0, large), (Item1, small) """ self.init() scheme_eval(self.atomspace, '(load-from-path "fuzzy-conjunction-introduction-config.scm")') rbs = ConceptNode("conjunction-rule-base") item0 = ConceptNode("Item0") item1 = ConceptNode("Item1") size = ConceptNode("Size") small = ConceptNode("small") large = ConceptNode("large") InheritanceLink(item0, ConceptNode("Items")).tv = TruthValue(0.9, 0.9) InheritanceLink(item1, ConceptNode("Items")).tv = TruthValue(0.9, 0.9) InheritanceLink(small, size).tv = TruthValue(1.0, 1.0) InheritanceLink(large, size).tv = TruthValue(1.0, 1.0) P = GroundedPredicateNode("py:run_predicate") X = VariableNode("$X") Y = VariableNode("$Y") P_A = EvaluationLink(P, ListLink(X, Y)) target = AndLink(InheritanceLink(Y, size), InheritanceLink(X, ConceptNode("Items")), P_A) bc = BackwardChainer(self.atomspace, rbs, target) bc.do_chain() results = bc.get_results() self.assertTrue(len(results.get_out()) == 2) del bc
def test_fc_deduction(self): self.init() scheme_eval(self.atomspace, '(load-from-path "fc-deduction-config.scm")') A = ConceptNode("A") B = ConceptNode("B") C = ConceptNode("C") InheritanceLink(A, B).tv = TruthValue(0.8, 0.9) InheritanceLink(B, C).tv = TruthValue(0.98, 0.94) chainer = ForwardChainer(self.atomspace, ConceptNode("fc-deduction-rule-base"), InheritanceLink(VariableNode("$who"), C), TypedVariableLink(VariableNode("$who"), TypeNode("ConceptNode"))) chainer.do_chain() results = chainer.get_results() resultLink = results.out[0] self.assertEquals(types.InheritanceLink, resultLink.type) resultA = resultLink.out[0] resultC = resultLink.out[1] self.assertEquals(A, resultA) self.assertEquals(C, resultC) resultTV = resultLink.tv self.assertAlmostEqual(1.0, resultTV.mean, places=5) self.assertAlmostEqual(1.0, resultTV.confidence, places=5)
def setUp(self): global shared_space self.space = shared_space scheme_eval(self.space, '(add-to-load-path "' + os.environ['PROJECT_SOURCE_DIR'] + '")') scheme_eval(self.space, '(add-to-load-path "' + os.environ['PROJECT_SOURCE_DIR'] + '/opencog/scm")')
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 __init__(self): # Get the atomspace that the scheme is using at just this moment. self.atomspace = scheme_eval_as('(cog-atomspace)') # Needed for the public define of chat-state, chat-start, etc. # XXX Except that this doesn't actually make chat-state visible? # WTF? But use-modules in btree.scm does work... strange. scheme_eval(self.atomspace, "(use-modules (opencog exec))") scheme_eval(self.atomspace, "(use-modules (opencog eva-model))")
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))") scheme_eval(self.atomspace, "(use-modules (opencog nlp))") self.hobbsAgent=HobbsAgent()
def test_unifier(self): scheme_eval(self.space, "(use-modules (opencog exec))") question = scheme_eval_h(self.space, "find-animals") self.assertTrue(question) print ("\nThe question is:", question) answer = scheme_eval_h(self.space, "(cog-execute! find-animals)") self.assertTrue(answer) print ("\nThe answer is:", answer) self.assertEqual(answer.type, types.SetLink) self.assertEqual(answer.arity, 3)
def load_datasets(atomspace): """ loads datasets from scm/datasets directory to atomspace :param atomspace: atomspace instance that will be loaded with datasets. :return: a loaded atomspace instance """ logger.info("Loading datasets") logger.info("In Production Mode") for dataset in config.DATASET_PATHs: scheme_eval(atomspace, '(load-file "{}")'.format(dataset)) return atomspace
def __init__(self, atomspace, anchorNode, target, command, resultNode, atomType): ''' Stores necessary information ''' self.atomspace = atomspace self.anchorNode = anchorNode self.target = target self.command = command self.resultNode = resultNode self.atomType = atomType scheme_eval(self.atomspace, "(use-modules (opencog) (opencog exec))")
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 test_unifier(self): scheme_eval(self.space, "(use-modules (opencog exec))") question = scheme_eval_h(self.space, "find-animals") self.assertTrue(question) print "\nThe question is:" print question answer = scheme_eval_h(self.space, "(cog-execute! find-animals)") self.assertTrue(answer) print "\nThe answer is:" print answer self.assertEqual(answer.type, types.SetLink) self.assertEqual(answer.arity, 3)
def __init__(self,atomspace,anchorNode, target, command,resultNode,atomType): ''' Stores necessary information ''' self.atomspace=atomspace self.anchorNode=anchorNode self.target=target self.command=command self.resultNode=resultNode self.atomType=atomType scheme_eval(self.atomspace, "(use-modules (opencog) (opencog exec))") scheme_eval(self.atomspace, "(use-modules (opencog nlp))")
def test_unifier(self): scheme_eval(self.space, "(use-modules (opencog query))") question = scheme_eval_h(self.space, "find-animals") self.assertTrue(question) print "\nThe question is:" print question answer = scheme_eval_h(self.space, "(cog-bind find-animals)") self.assertTrue(answer) print "\nThe answer is:" print answer self.assertEqual(answer.type, types.SetLink) self.assertEqual(answer.arity, 3)
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 run_message_passing_ure(): fc_message_sending_rule_name = DefinedSchemaNode("fc-message-sending-rule") DefineLink(fc_message_sending_rule_name, create_messages_rule) fc_message_sending_rbs = ConceptNode("fc-message-sending-rule") InheritanceLink(fc_message_sending_rbs, ConceptNode("URE")) MemberLink(fc_message_sending_rule_name, fc_message_sending_rbs) # Set URE maximum-iterations from opencog.scheme_wrapper import scheme_eval execute_code = \ ''' (use-modules (opencog rule-engine)) (ure-set-num-parameter (ConceptNode "fc-message-sending-rbs") "URE:maximum-iterations" 30) ''' scheme_eval(atomspace, execute_code) # chainer = ForwardChainer(atomspace, # ConceptNode("fc-message-sending-rule"), # SetLink()) # log.set_level('FINE') # chainer = ForwardChainer(atomspace, # ConceptNode("fc-message-sending-rule"), # get_message(VariableNode("$V1"), VariableNode("$V2")), # VariableList( # TypedVariableLink(VariableNode("$V1"), TypeNode("ConceptNode")), # TypedVariableLink(VariableNode("$V2"), TypeNode("ConceptNode"))) # ) # chainer = BackwardChainer(atomspace, # ConceptNode("fc-message-sending-rule"), # get_message(VariableNode("$V1"), VariableNode("$V2"))) chainer = BackwardChainer( atomspace, ConceptNode("fc-message-sending-rule"), get_message(VariableNode("$V1"), VariableNode("$V2")), VariableList( TypedVariableLink(VariableNode("$V1"), TypeNode("ConceptNode")), TypedVariableLink(VariableNode("$V2"), TypeNode("ConceptNode")))) chainer.do_chain() results = chainer.get_results()
def prep_bind(atomspace): for scheme_file in scheme_preload: load_scm(atomspace, scheme_file) scheme_eval(atomspace, "(use-modules (opencog))") scheme_eval(atomspace, "(use-modules (opencog query))") # 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(atomspace, scheme_animals)
def post(self): data = reqparse.request.get_json() print(data) if 'query' in data: query = data['query'] print(query) action = "(test-ghost \"{}\")".format(query) scheme_eval(self.atomspace, action) response = scheme_eval(self.atomspace, '(get-result)') print(response) else: abort(400, 'Invalid request: required parameter command is missing') return jsonify({'response': response})
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 start_annotation(**kwargs): logger = logging.getLogger("annotation-service") try: mnemonic = kwargs["mnemonic"] path = os.path.join(RESULT_DIR, mnemonic) if not os.path.exists(path): os.makedirs(path) annotate(atomspace, kwargs["payload"]["annotations"], kwargs["payload"]["genes"], mnemonic) logger.info("when executing atoms:" + scheme_eval(atomspace, "(count-all)").decode("utf-8")) json_file = os.path.join(path, mnemonic + ".json") logger.info("Applying Multi-level Layout") out_dict = multi_level_layout(json_file) with open(json_file, "w") as fp: json.dump({"elements": out_dict}, fp) csv_file = to_csv(mnemonic) logger.info(csv_file) return True except Exception as ex: msg = "Error: " + ex.__str__() logger.error(msg) print(traceback._cause_message) return False
def test_unifier(self): status = load_scm(self.space, "opencog/scm/opencog/query.scm") self.assertTrue(status) scheme_eval(self.space, "(use-modules (opencog query))") question = scheme_eval_h(self.space, "find-animals") self.assertTrue(question) print "\nThe question is:" print question answer = scheme_eval_h(self.space, "(cog-bind find-animals)") self.assertTrue(answer) print "\nThe answer is:" print answer self.assertEqual(answer.type, types.SetLink) self.assertEqual(answer.arity, 3)
def predicate_to_scheme(self, predicate): for prop in predicate.properties: if predicate.properties[prop]: print( scheme_eval( atomspace, '(variable_' + prop + ' "' + predicate.obo_name + '" 1)').decode("utf-8").strip()) '''
def run_message_passing_ure(): fc_message_sending_rule_name = DefinedSchemaNode("fc-message-sending-rule") DefineLink( fc_message_sending_rule_name, create_messages_rule) fc_message_sending_rbs = ConceptNode("fc-message-sending-rule") MemberLink( fc_message_sending_rule_name, fc_message_sending_rbs ) EvaluationLink( PredicateNode("URE:FC:retry-exhausted-sources"), fc_message_sending_rbs ).tv = TruthValue(1, 1) # Set URE maximum-iterations from opencog.scheme_wrapper import scheme_eval execute_code = \ ''' (use-modules (opencog) (opencog rule-engine)) (ure-set-num-parameter (ConceptNode "fc-message-sending-rbs") "URE:maximum-iterations" 10) ''' scheme_eval(atomspace, execute_code) # log.info("=== Dump AtomSpace Begin ===") # for atom in atomspace: # if not atom.incoming: # log.info(str(atom)) # log.info("=== Dump AtomSpace End ===") print("run forward chainer") chainer = ForwardChainer(atomspace, ConceptNode("fc-message-sending-rule"), get_directed_edge(VariableNode("$V1"), VariableNode("$V2")), VariableList( TypedVariableLink(VariableNode("$V1"), TypeNode("ConceptNode")), TypedVariableLink(VariableNode("$V2"), TypeNode("ConceptNode")))) chainer.do_chain()
def load_datasets(atomspace): """ loads datasets from scm/datasets directory to atomspace :param atomspace: atomspace instance that will be loaded with datasets. :return: a loaded atomspace instance """ logger.info("Loading datasets") if config.PRODUCTION_MODE: logger.info("In Production Mode") for dataset in config.DATASET_PATHs: scheme_eval(atomspace, '(primitive-load "{}")'.format(dataset)) return atomspace else: logger.info("In Dev Mode") scheme_eval(atomspace, '(primitive-load "{}")'.format(config.TEST_DATASET)) return atomspace
def echo(bot, update): """Echo the user message.""" print ("Ok, we got message {}".format(update.message.text)) reply = scheme_eval(atomspace, '(process-query "{}" "{}")'.format(update.message.from_user.first_name, update.message.text)) print ("And now we have a reply {}".format(reply)) reply_decoded = reply.decode("utf-8") print ("Decoding the reply: {}".format(reply_decoded)) bot.send_message(chat_id=update.message.chat_id, text=reply_decoded)
def check_gene_availability(atomspace, genes): logger = logging.getLogger("annotation-service") genes = generate_gene_function(genes) logger.info("checking genes : " + genes) logger.info(genes) genes_fn = "(find-genes {gene_list})".format(gene_list=genes) gene_result = scheme_eval(atomspace, genes_fn).decode('utf-8') gene_dict = json.loads(gene_result) return gene_result, len(gene_dict) == 0
def annotate(atomspace, annotations, genes, mnemonic): """ Performs annotation according to a list of annotations given on a list of genes :param atomspace: the atomspace that contains the loaded knowledge bases where the annotations will be performed from :param annotations: a list of annotations :param genes: a list of genes. :return: a string response directly from the scheme_eval response decoded in utf-8 """ logger = logging.getLogger("annotation-service") logger.info(annotations) genes_list = generate_gene_function(genes) parse_function = "(annotate-genes {genes} \"{session}\" \"{request}\")".format( genes=genes_list, request=json.dumps(annotations).replace('"', '\\"'), session=mnemonic) logger.info(parse_function) scheme_eval(atomspace, parse_function).decode("utf-8") logger.info("Finished annotation")
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 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 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 test_c_gc(self): print("Enter garbage-collection-test\n") status = scheme_eval(self.space, '(define n 0)') self.assertTrue(status) status = scheme_eval(self.space, """ (for-each (lambda (y) (let* ((bigstr (list->string (map (lambda (x) (integer->char (+ 48 (modulo (+ x y) 79)))) (iota 900)))) (biglst (string->list bigstr)) (revstr (reverse-list->string biglst))) (set! n (+ 1 n)))) (iota 2000))""") self.assertTrue(status) status = scheme_eval(self.space, '(gc-stats)') self.assertTrue(status) print("Finish garbage-coolection-test\n")
def test_b_load_file(self): status = scheme_eval(self.space, '(load-from-path "tests/cython/guile/basic_unify.scm")') self.assertTrue(status) a1 = self.space.add_node(types.ConceptNode, "hello") self.assertTrue(a1) # Make sure the truth value is what's in the SCM file. expected = TruthValue(0.5, 0.5) self.assertEquals(a1.tv, expected)
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 execution(self): ''' First binds the "anchorNode" with the "target" if "anchorNode" exists, then executes scheme command "command" ''' if self.anchorNode != None and self.target != None: self.tmpLink=self.atomspace.add_link(types.ListLink, [self.anchorNode, self.target], TruthValue(1.0, 100)) else: self.tmpLink=None response = scheme_eval(self.atomspace, self.command) d=3;
def test_unifier(self): status = load_scm(self.space, "opencog/scm/opencog/query.scm") self.assertTrue(status) scheme_eval(self.space, "(use-modules (opencog query))") h = scheme_eval_h(self.space, "find-animals") self.assertTrue(h) print "\nThe question is:" print h question = Atom(h, self.space) print question h = scheme_eval_h(self.space, "(cog-bind find-animals)") self.assertTrue(h) print h answer = Atom(h, self.space) print "\nThe answer is:" print answer self.assertEqual(answer.type, types.SetLink) self.assertEqual(answer.arity, 3)
def run_forward_chainer(internal_atomspace): send_messages_rbs = ConceptNode("send-messages-rule-base") send_message_variable_factor = DefinedSchemaNode( "send-message-variable-factor-rule") send_message_factor_variable = DefinedSchemaNode( "send-message-factor-variable-rule") DefineLink(send_message_variable_factor, send_message_variable_factor_rule()) DefineLink(send_message_factor_variable, send_message_factor_variable_rule()) MemberLink(send_message_variable_factor, send_messages_rbs) MemberLink(send_message_factor_variable, send_messages_rbs) # Set URE maximum-iterations from opencog.scheme_wrapper import scheme_eval execute_code = \ ''' (use-modules (opencog rule-engine)) (ure-set-num-parameter (ConceptNode "{}") "URE:maximum-iterations" 50) '''.format(send_messages_rbs.name) scheme_eval(internal_atomspace, execute_code) EvaluationLink(PredicateNode("URE:FC:retry-exhausted-sources"), send_messages_rbs).tv = TruthValue(1, 1) chainer = ForwardChainer( internal_atomspace, send_messages_rbs, get_edge_predicate(VariableNode("$F"), VariableNode("$V")), VariableList( TypedVariableLink(VariableNode("$F"), TypeNode("ConceptNode")), TypedVariableLink(VariableNode("$V"), TypeNode("ConceptNode")))) chainer.do_chain()
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 init(self): project_source_dir = os.environ["PROJECT_SOURCE_DIR"] scheme_eval(self.atomspace, '(add-to-load-path "{0}")'.format(project_source_dir)) scheme_eval(self.atomspace, '(add-to-load-path "{0}/{1}")'.format(project_source_dir, "tests/rule-engine/forwardchainer/scm")) scheme_eval(self.atomspace, '(add-to-load-path "{0}/{1}")'.format(project_source_dir, "opencog/scm/opencog/rule-engine"))
def test_crisp(self): """port of crisp.scm from examples/rule-engine/simple""" scheme_eval(self.atomspace, '(load-from-path "crisp-config.scm")') A = PredicateNode("A", TruthValue(1, 1)) B = PredicateNode("B") C = PredicateNode("C") AB = ImplicationLink(A, B) AB.tv = TruthValue(1, 1) BC = ImplicationLink(B, C) BC.tv = TruthValue(1, 1) crisprbs = ConceptNode("crisp-rule-base") InheritanceLink(crisprbs, ConceptNode("URE")) trace_as = AtomSpace() scheme_eval( self.atomspace, '(crisp-fc (ImplicationLink (stv 1 1) (PredicateNode "A") (PredicateNode "B")))' ) chainer = BackwardChainer(self.atomspace, crisprbs, C) chainer.do_chain() results = chainer.get_results() self.assertTrue(results.get_out()[0].name == "C") self.assertTrue(results.get_out()[0].tv == AB.tv)
def post(self): """ Send a command to the Scheme interpreter """ # Validate, parse and send the command data = reqparse.request.get_json() if 'command' in data: response = scheme_eval(self.atomspace, data['command']) else: abort(400, 'Invalid request: required parameter command is missing') return jsonify({'response': response})
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 test_b_load_file(self): print("Enter load-file test\n") status = scheme_eval(self.space, '(load-from-path "tests/cython/guile/basic_unify.scm")') self.assertTrue(status) print("Loaded file\n") a1 = self.space.add_node(types.ConceptNode, "hello") self.assertTrue(a1) print("Added atom\n") # Make sure the truth value is what's in the SCM file. expected = TruthValue(0.5, 0.5) self.assertEquals(a1.tv, expected) print("Got=" + str(a1.tv) + " expected=" + str(expected))
def _relation_properties(self, relation, thing1, things2, indicators): if relation == 'is_a': return [ scheme_eval( atomspace, '(' + relation + ' "' + thing1 + '" "' + thing2 + '" 1)') for thing2 in things2 ] for label in indicators: if indicators[label]: [ self._predicate_scheme_eval(label, relation, thing1, thing2) for thing2 in things2 ]
def post(self): """ Send a command to the Scheme interpreter Uri: scheme Include a JSON object with the POST request containing the command in a field named "command" Example command: {'command': '(cog-set-af-boundary! 100)'} Returns: A JSON object containing the Scheme-formatted result of the command in a field named "response". Example response: {'response': '100\n'} Note that in this API, the request is processed synchronously. It blocks until the request has finished. This functionality is implemented as a POST method because it can cause side-effects. """ # Validate, parse and send the command data = reqparse.request.get_json() if 'command' in data: response = scheme_eval(self.atomspace, data['command']) else: abort(400, 'Invalid request: required parameter command is missing') return jsonify({'response': response})
def btree_stop(self): scheme_eval(self.atomspace, "(behavior-tree-halt)")
from __future__ import print_function from pprint import pprint # from pln.examples.deduction import deduction_agent from opencog.atomspace import types, AtomSpace, TruthValue from opencog.cogserver_type_constructors import * from agents.hobbs import HobbsAgent from agents.dumpAgent import dumpAgent from opencog.scheme_wrapper import load_scm,scheme_eval_h, scheme_eval, __init__ __author__ = 'Hujie Wang' ''' This agent is purely for testing purposes, which can be used to test hobbsAgent in a standalone atomspace environment. ''' atomspace = AtomSpace() # __init__(atomspace) scheme_eval(atomspace, "(use-modules (opencog) (opencog exec))") scheme_eval(atomspace, "(use-modules (opencog nlp))") #status2 = load_scm(atomspace, "opencog/nlp/anaphora/tests/atomspace.scm") #init=initAgent() #init.run(atomspace) dump=dumpAgent() dump.run(atomspace) hobbsAgent = HobbsAgent() hobbsAgent.run(atomspace) scheme_eval(atomspace, 'getWords')
# """ Example of how to use the pattern matcher. Based on the following example in the wiki: http://wiki.opencog.org/w/Pattern_matching#The_Simplified_API """ __author__ = 'Cosmo Harrigan' from opencog.atomspace import AtomSpace from opencog.scheme_wrapper import scheme_eval, scheme_eval_h atomspace = AtomSpace() # Add to scheme's %load-path directory to serach for opencog guile modules scheme_eval(atomspace, "(add-to-load-path \"/usr/local/share/opencog/scm\")") # Import opencog modules required for using `cog-execute!` in scheme_eval scheme_eval(atomspace, "(use-modules (opencog))") scheme_eval(atomspace, "(use-modules (opencog exec))") # 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(atomspace, scheme_animals) # Define a graph search query
def test_a_load_core_types(self): scheme_eval(self.space, "(use-modules (opencog))")
executed = True return link execute_code = \ ''' (cog-execute! (ExecutionOutputLink (GroundedSchemaNode \"py: add_link\") (ListLink (ConceptNode \"one\") (ConceptNode \"two\") ) ) ) ''' scheme_eval(atomspace, execute_code) print "execute: cog-execute" if (executed): print "add_link - executed successfully" else: print "add_link - did NOT execute" executed = False execute_atom( atomspace, ExecutionOutputLink( GroundedSchemaNode("py: add_link"), ListLink( ConceptNode("one"), ConceptNode("two") )
def test_operation(): for i in range(NUMBER_OF_ITERATIONS): scheme_eval(atomspace, '(+ 2 2)')
def btree_run(self): scheme_eval(self.atomspace, "(behavior-tree-run)")
# """ Example of how to use the pattern matcher. Based on the following example in the wiki: http://wiki.opencog.org/w/Pattern_matching#The_Simplified_API """ __author__ = 'Cosmo Harrigan' from opencog.atomspace import AtomSpace from opencog.scheme_wrapper import scheme_eval, scheme_eval_h atomspace = AtomSpace() # Import opencog modules required for using `cog-execute!` in scheme_eval scheme_eval(atomspace, "(use-modules (opencog))") scheme_eval(atomspace, "(use-modules (opencog exec))") # 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(atomspace, scheme_animals) # Define a graph search query scheme_query = \ ''' (define find-animals
def perceived_text(self, text): scheme_eval(self.atomspace, '(cog-evaluate! (PutLink (DefinedPredicate "heard text")' + ' (SentenceNode "' + text + '")))')