class EvaluationToMemberAgent(MindAgent): def __init__(self): self.chainer = None def create_chainer(self, atomspace): self.chainer = Chainer(atomspace, stimulateAtoms=False, allow_output_with_variables=True, delete_temporary_variables=True) self.chainer.add_rule( GeneralEvaluationToMemberRule(self.chainer, 0, 2)) self.chainer.add_rule(MemberToInheritanceRule(self.chainer)) self.chainer.add_rule( DeductionRule(self.chainer, types.InheritanceLink)) self.chainer.add_rule( InheritanceToMemberRule(self.chainer)) self.chainer.add_rule( MemberToEvaluationRule(self.chainer)) def run(self, atomspace): if self.chainer is None: self.create_chainer(atomspace) return result = self.chainer.forward_step() return result
class InferenceAgent(MindAgent): def __init__(self): self.chainer = None def create_chainer(self, atomspace): self.chainer = Chainer(atomspace, stimulateAtoms=False, allow_output_with_variables=True) # EvaluationToMember, MemberToInheritance self.chainer.add_rule( EvaluationToMemberRule(self.chainer, 0, 1)) self.chainer.add_rule(MemberToEvaluationRule(self.chainer)) self.chainer.add_rule(MemberToInheritanceRule(self.chainer)) self.chainer.add_rule(InheritanceToMemberRule(self.chainer)) # For predicates with 2 arguments, # with the 0th argument made into a variable self.chainer.add_rule( EvaluationToMemberRule(self.chainer, 0, 2)) # ModusPonens: # Implication smokes(x) cancer(X) # smokes(Anna) # |= cancer(Anna) self.chainer.add_rule( ModusPonensRule(self.chainer, types.ImplicationLink)) def run(self, atomspace): if self.chainer is None: self.create_chainer(atomspace) return result = self.chainer.forward_step() return result
class InferenceAgent(MindAgent): def __init__(self): self.chainer = None def create_chainer(self, atomspace, stimulate_atoms=True): self.chainer = Chainer(atomspace, agent=self, stimulateAtoms=stimulate_atoms, allow_output_with_variables=False, preferAttentionalFocus=True, delete_temporary_variables=True) # ModusPonens: # Implication smokes(x) cancer(X) # smokes(Anna) # |= cancer(Anna) self.chainer.add_rule( ModusPonensRule(self.chainer, types.ImplicationLink)) def run(self, atomspace): if self.chainer is None: self.create_chainer(atomspace) return if not check_result(atomspace): result = self.chainer.forward_step() return result
class InferenceAgent(MindAgent): def __init__(self): self.chainer = None def create_chainer(self, atomspace): self.chainer = Chainer(atomspace, stimulateAtoms=False) # Note: # The API for adding Rules and Links to a PLN Chainer is # hard to use. It could be redesigned so that you would # just pass a list of rule types and link types when you # instantiate the Chainer, without having to be aware of # the different sets of rules that require different # argument sets. for rule in RULES_CHAINER_LINKTYPE: for link_type in LINK_TYPES: print rule, link_type self.chainer.add_rule(rule(self.chainer, link_type)) for rule in RULES_CHAINER: self.chainer.add_rule(rule(self.chainer)) def run(self, atomspace): if self.chainer is None: self.create_chainer(atomspace) return result = self.chainer.forward_step() if __VERBOSE__: print result return result
class InferenceAgent(MindAgent): def __init__(self): self.chainer = None print "Initializing InferenceAgent." def create_chainer(self, atomspace, stimulate_atoms=True): self.chainer = Chainer(atomspace, agent=self, stimulateAtoms=stimulate_atoms, allow_output_with_variables=False, preferAttentionalFocus=True, delete_temporary_variables=True) # ModusPonens: # Implication smokes(x) cancer(X) # smokes(Anna) # |= cancer(Anna) self.chainer.add_rule( ModusPonensRule(self.chainer, types.ImplicationLink)) def run(self, atomspace): if self.chainer is None: self.create_chainer(atomspace) print "PLN Chainer created." return print "PLN continuing." target = atomspace[scheme_eval_h(atomspace, "query")] if not check_result(atomspace): result = self.chainer.forward_step() self.chainer._give_stimulus(target, TARGET_STIMULUS) return result
class InferenceAgent(MindAgent): def __init__(self): self.chainer = None print "Initializing InferenceAgent." def create_chainer(self, atomspace, stimulate_atoms=True): self.chainer = Chainer(atomspace, agent=self, stimulateAtoms=stimulate_atoms, allow_output_with_variables=False, preferAttentionalFocus=True, delete_temporary_variables=True) # ModusPonens: # Implication smokes(x) cancer(X) # smokes(Anna) # |= cancer(Anna) self.chainer.add_rule( ModusPonensRule(self.chainer, types.ImplicationLink)) def run(self, atomspace): if self.chainer is None: self.create_chainer(atomspace) print "PLN Chainer created." return print "PLN continuing." target = atomspace[scheme_eval_h(atomspace, "query")] if not check_result(atomspace): result = self.chainer.forward_step() self.chainer._give_stimulus(target, TARGET_STIMULUS) return result
class DeceptionAgent(MindAgent): def __init__(self): self.chainer = None print "Initialized DeceptionAgent." def create_chainer(self, atomspace, stimulate_atoms=False): self.chainer = Chainer(atomspace, agent=self, stimulateAtoms=stimulate_atoms, allow_output_with_variables=False, delete_temporary_variables=True) self.chainer.add_rule( ModusPonensRule(self.chainer, types.ImplicationLink)) def run(self, atomspace): if self.chainer is None: self.create_chainer(atomspace) return result = self.chainer.forward_step() # if __VERBOSE__: # print result return result def get_trails(self): return self.chainer.trails def get_history(self): return self.chainer.history.get_history()
class DeductionAgent(MindAgent): def __init__(self): self.chainer = None def create_chainer(self, atomspace): self.chainer = Chainer(atomspace, stimulateAtoms=False) link_types = [types.InheritanceLink] for link_type in link_types: self.chainer.add_rule(DeductionRule(self.chainer, link_type)) def run(self, atomspace): # Run is invoked on every cogserver cognitive cycle # If it is the first time it has been invoked, then the chainer # needs to be created if self.chainer is None: self.create_chainer(atomspace) return result = self.chainer.forward_step() if __VERBOSE__: print result return result def get_trails(self): return self.chainer.trails def get_history(self): return self.chainer.history.get_history()
class InferenceAgent(MindAgent): def __init__(self): self.chainer = None def create_chainer(self, atomspace, stimulate_atoms=True): self.chainer = Chainer(atomspace, agent=self, stimulateAtoms=stimulate_atoms, allow_output_with_variables=False, preferAttentionalFocus=True, delete_temporary_variables=True) # ModusPonens: # Implication smokes(x) cancer(X) # smokes(Anna) # |= cancer(Anna) self.chainer.add_rule( ModusPonensRule(self.chainer, types.ImplicationLink)) def run(self, atomspace): if self.chainer is None: self.create_chainer(atomspace) return if not check_result(atomspace): result = self.chainer.forward_step() return result
class DeceptionAgent(MindAgent): def __init__(self): self.chainer = None print "Initialized DeceptionAgent." def create_chainer(self, atomspace, stimulate_atoms=False): self.chainer = Chainer(atomspace, agent=self, stimulateAtoms=stimulate_atoms, allow_output_with_variables=False, delete_temporary_variables=True) self.chainer.add_rule( ModusPonensRule(self.chainer, types.ImplicationLink)) def run(self, atomspace): if self.chainer is None: self.create_chainer(atomspace) return result = self.chainer.forward_step() # if __VERBOSE__: # print result return result def get_trails(self): return self.chainer.trails def get_history(self): return self.chainer.history.get_history()
class InferenceAgent(MindAgent): def __init__(self): self.chainer = None self.query = None print "Initializing InferenceAgent." def create_chainer(self, atomspace, stimulate_atoms=True): """ Creates the chainer for the "smokes" example. Optionally, you can define the target query before calling this method, by defining a Scheme expression named "query". For example, you can issue the Scheme expression "(define query hasCancer)" in reference to the predicate defined in smokes.scm before loading this agent. Once defined, the target query will receive stimulus at every time step. Stimulus requires the agent to be running in a CogServer. For a complete example that incorporates this behavior, see example.py here: https://github.com/opencog/external-tools/tree/master/attention """ self.chainer = Chainer(atomspace, agent=self, stimulateAtoms=stimulate_atoms, allow_output_with_variables=False, preferAttentionalFocus=True, delete_temporary_variables=True) # ModusPonens: # Implication smokes(x) cancer(X) # smokes(Anna) # |= cancer(Anna) self.chainer.add_rule( ModusPonensRule(self.chainer, types.ImplicationLink)) # stimulateAtoms is only enabled when the agent is ran inside the # CogServer, since the functionality requires a CogServer and # attention allocation if self.chainer._stimulateAtoms: self.query = scheme_eval_h(atomspace, "query") def run(self, atomspace): if self.chainer is None: self.create_chainer(atomspace) print "PLN Chainer created." return print "PLN continuing." if not check_result(atomspace): result = self.chainer.forward_step() if self.query is not None: self.chainer._give_stimulus(atomspace[self.query], TARGET_STIMULUS) return result
class BackwardInferenceAgent(MindAgent): def __init__(self): self.chainer = None def create_chainer(self, atomspace): self.chainer = Chainer(atomspace, stimulateAtoms=False, agent=self) deduction_link_types = [types.InheritanceLink] # types.SubsetLink, types.IntensionalInheritanceLink] for link_type in deduction_link_types: self.chainer.add_rule(rules.InversionRule(self.chainer, link_type)) self.chainer.add_rule(rules.DeductionRule(self.chainer, link_type)) # self.chainer.add_rule(rules.NotCreationRule(self.chainer)) # self.chainer.add_rule(rules.NotEliminationRule(self.chainer)) # for rule in rules.create_and_or_rules(self.chainer, 1, 5): # self.chainer.add_rule(rule) # self.chainer.add_rule(EvaluationToMemberRule(self.chainer)) # self.chainer.add_rule(MemberToInheritanceRule(self.chainer)) def run(self, atomspace): # incredibly exciting futuristic display! #import os #os.system('cls' if os.name=='nt' else 'clear') # try: if self.chainer is None: self.create_chainer(atomspace) result = self.chainer.backward_step() if result: (outputs, inputs) = result if False: print '==== Inference ====' print show_atoms(outputs), '<=', show_atoms(inputs) print print '==== Attentional Focus ====' for atom in get_attentional_focus(atomspace)[0:30]: print str(atom), atom.av #print '==== Result ====' #print output #print '==== Trail ====' #print_atoms( self.chainer.trails[output] ) if self.chainer._all_nonzero_tvs(inputs): raw_input() else: print 'Invalid inference attempted'
class BackwardInferenceAgent(MindAgent): def __init__(self): self.chainer = None def create_chainer(self, atomspace): self.chainer = Chainer(atomspace, stimulateAtoms = False, agent = self) deduction_link_types = [types.InheritanceLink] # types.SubsetLink, types.IntensionalInheritanceLink] for link_type in deduction_link_types: self.chainer.add_rule(rules.InversionRule(self.chainer, link_type)) self.chainer.add_rule(rules.DeductionRule(self.chainer, link_type)) # self.chainer.add_rule(rules.NotCreationRule(self.chainer)) # self.chainer.add_rule(rules.NotEliminationRule(self.chainer)) # for rule in rules.create_and_or_rules(self.chainer, 1, 5): # self.chainer.add_rule(rule) # self.chainer.add_rule(EvaluationToMemberRule(self.chainer)) # self.chainer.add_rule(MemberToInheritanceRule(self.chainer)) def run(self, atomspace): # incredibly exciting futuristic display! #import os #os.system('cls' if os.name=='nt' else 'clear') # try: if self.chainer is None: self.create_chainer(atomspace) result = self.chainer.backward_step() if result: (outputs, inputs) = result if False: print '==== Inference ====' print show_atoms(outputs), '<=', show_atoms(inputs) print print '==== Attentional Focus ====' for atom in get_attentional_focus(atomspace)[0:30]: print str(atom), atom.av #print '==== Result ====' #print output #print '==== Trail ====' #print_atoms( self.chainer.trails[output] ) if self.chainer._all_nonzero_tvs(inputs): raw_input() else: print 'Invalid inference attempted'
def create_chainer(atomspace, rule_concept_nodes): """ :param atomspace: the atomspace to be used by the chainer :param concept_nodes: list of ConceptNodes where the name is the name of a rule optionally amended by a link_type separated with ":", e.g. [ConceptNode "ModusPonensRule:ImplicationLink"] :return: the chainer that has been created """ chainer = Chainer(atomspace, stimulateAtoms=False, allow_output_with_variables=True, delete_temporary_variables=True) for rule_concept_node in rule_concept_nodes: rule_name, link_type = rule_concept_node.name.split(":") chainer.add_rule(rules[rule_name](chainer, link_types[link_type])) return chainer
def create_chainer(atomspace, rule_concept_nodes): """ :param atomspace: the atomspace to be used by the chainer :param concept_nodes: list of ConceptNodes where the name is the name of a rule optionally amended by a link_type separated with ":", e.g. [ConceptNode "ModusPonensRule:ImplicationLink"] :return: the chainer that has been created """ chainer = Chainer(atomspace, stimulateAtoms=False, allow_output_with_variables=True, delete_temporary_variables=True) for rule_concept_node in rule_concept_nodes: rule_name, link_type = rule_concept_node.name.split(":") chainer.add_rule(rules[rule_name](chainer, link_types[link_type])) return chainer
class InferenceAgent(MindAgent): def __init__(self): self.chainer = None def create_chainer(self, atomspace): self.chainer = Chainer(atomspace, stimulateAtoms=False) self.chainer.add_rule( ModusPonensRule(self.chainer, types.ImplicationLink)) def run(self, atomspace): if self.chainer is None: self.create_chainer(atomspace) return result = self.chainer.forward_step() return result
class InferenceAgent(MindAgent): def __init__(self): self.chainer = None self.antecedents = [] def create_chainer(self, atomspace): self.chainer = Chainer(atomspace, agent=self, stimulateAtoms=True, preferAttentionalFocus=True, delete_temporary_variables=True, allow_output_with_variables=True) self.chainer.add_rule( ModusPonensRule(self.chainer, types.ImplicationLink)) def run(self, atomspace): if self.chainer is None: self.create_chainer(atomspace) implications = atomspace.get_atoms_by_type(types.ImplicationLink) for implication in implications: outgoing = atomspace.get_outgoing(implication.h) and_link = outgoing[0] self.antecedents.append(and_link) return # Run a forward step of the chainer with the ModusPonensRule so as to # perform inference using the "domain rules" defined as # ImplicationLinks self.chainer.forward_step() # Run a backward step of the chainer with the AndCreationRule for each # of the antecedents of the defined "domain rules" so as to # successfully ground the variables. for antecedent in self.antecedents: num_predicates = len(atomspace.get_outgoing(antecedent.h)) self.chainer.backward_step( AndCreationRule(self.chainer, num_predicates), [antecedent]) return
class TemporalAgent(MindAgent): def __init__(self): self.chainer = None def create_chainer(self, atomspace): self.chainer = Chainer(atomspace, stimulateAtoms=False, preferAttentionalFocus=False, allow_output_with_variables=True, delete_temporary_variables=True) for rule in create_temporal_rules(self.chainer): self.chainer.add_rule(rule) def run(self, atomspace): if self.chainer is None: self.create_chainer(atomspace) return result = self.chainer.forward_step() return result
class BackwardAgent(MindAgent): def __init__(self): self.chainer = None def create_chainer(self, atomspace): self.chainer = Chainer(atomspace, stimulateAtoms=False, allow_output_with_variables=True, delete_temporary_variables=True) self.chainer.add_rule( ModusPonensRule(self.chainer, types.ImplicationLink)) def run(self, atomspace): if self.chainer is None: self.create_chainer(atomspace) print "PLN Chainer created." return result = self.chainer.backward_step() return result
class TemporalAgent(MindAgent): def __init__(self): self.chainer = None def create_chainer(self, atomspace): self.chainer = Chainer(atomspace, stimulateAtoms=False, preferAttentionalFocus=False, allow_output_with_variables=True, delete_temporary_variables=True) for rule in create_composition_rules(self.chainer, composition_table): self.chainer.add_rule(rule) print(rule.name) def run(self, atomspace): if self.chainer is None: self.create_chainer(atomspace) return result = self.chainer.forward_step() return result
class ForwardInferenceAgent(MindAgent): def __init__(self): self.chainer = None def run(self, atomspace): if self.chainer is None: self.chainer = Chainer(atomspace, stimulateAtoms = True, agent = self) self.chainer.add_rule(rules.InversionRule(self.chainer)) self.chainer.add_rule(rules.DeductionRule(self.chainer)) # incredibly exciting futuristic display! #import os #os.system('cls' if os.name=='nt' else 'clear') try: result = self.chainer.forward_step() if result: (output, inputs) = result print '==== Inference ====' print output,str(output.av),'<=',' '.join(str(i)+str(output.av) for i in inputs) print print '==== Attentional Focus ====' for atom in get_attentional_focus(atomspace)[0:30]: print str(atom), atom.av #print '==== Result ====' #print output #print '==== Trail ====' #print_atoms( self.chainer.trails[output] ) else: print 'Invalid inference attempted' except Exception, e: print e
class EvaluationToMemberAgent(MindAgent): def __init__(self): self.chainer = None def create_chainer(self, atomspace): self.chainer = Chainer(atomspace, stimulateAtoms=False, allow_output_with_variables=True, delete_temporary_variables=True) self.chainer.add_rule(EvaluationToMemberRule(self.chainer, 0, 2)) self.chainer.add_rule(MemberToInheritanceRule(self.chainer)) self.chainer.add_rule( DeductionRule(self.chainer, types.InheritanceLink)) self.chainer.add_rule(InheritanceToMemberRule(self.chainer)) self.chainer.add_rule(MemberToEvaluationRule(self.chainer)) def run(self, atomspace): if self.chainer is None: self.create_chainer(atomspace) return result = self.chainer.forward_step() return result
class EvaluationToMemberAgent(MindAgent): def __init__(self): self.chainer = None def create_chainer(self, atomspace): self.chainer = Chainer(atomspace, stimulateAtoms=False) # EvaluationToMemberRule only accepts predicates with 1 argument # For predicates with more arguments, GeneralEvaluationToMemberRule # is used. self.chainer.add_rule( GeneralEvaluationToMemberRule(self.chainer, 0, 2)) self.chainer.add_rule(MemberToInheritanceRule(self.chainer)) self.chainer.add_rule( DeductionRule(self.chainer, types.InheritanceLink)) def run(self, atomspace): if self.chainer is None: self.create_chainer(atomspace) return result = self.chainer.forward_step() return result
class EvaluationToMemberAgent(MindAgent): def __init__(self): self.chainer = None def create_chainer(self, atomspace): self.chainer = Chainer(atomspace, stimulateAtoms=False) # EvaluationToMemberRule only accepts predicates with 1 argument # For predicates with more arguments, GeneralEvaluationToMemberRule # is used. self.chainer.add_rule(GeneralEvaluationToMemberRule( self.chainer, 0, 2)) self.chainer.add_rule(MemberToInheritanceRule(self.chainer)) self.chainer.add_rule( DeductionRule(self.chainer, types.InheritanceLink)) def run(self, atomspace): if self.chainer is None: self.create_chainer(atomspace) return result = self.chainer.forward_step() return result
class InferenceAgent(MindAgent): def __init__(self): self.chainer = None self.num_steps_per_cycle = 100 def create_chainer(self, atomspace): # Note: using stimulateAtoms will cause a segfault if you create the Agent from the Python shell (use the agents-start command in the cogserver shell) self.chainer = Chainer(atomspace, stimulateAtoms = False, agent = self, learnRuleFrequencies=True) # ImplicationLink is MixedImplicationLink, you could also have Extensional and Intensional Implication. etc. but that's a bit much. # similarity_types = [types.SimilarityLink, types.ExtensionalSimilarityLink, types.IntensionalSimilarityLink] # types.EquivalenceLink] # conditional_probability_types = [types.InheritanceLink, types.SubsetLink, types.IntensionalInheritanceLink, types.ImplicationLink] # always use the mixed inheritance types, because human inference is normally a mix of intensional and extensional conditional_probability_types = [types.InheritanceLink, types.ImplicationLink, types.PredictiveImplicationLink] similarity_types = [types.SimilarityLink, types.EquivalenceLink] for link_type in conditional_probability_types: self.chainer.add_rule(rules.InversionRule(self.chainer, link_type)) self.chainer.add_rule(rules.DeductionRule(self.chainer, link_type)) self.chainer.add_rule(rules.InductionRule(self.chainer, link_type)) self.chainer.add_rule(rules.AbductionRule(self.chainer, link_type)) # Seems better than Modus Ponens - it doesn't make anything up self.chainer.add_rule(rules.TermProbabilityRule(self.chainer, link_type)) self.chainer.add_rule(rules.ModusPonensRule(self.chainer, link_type)) for link_type in similarity_types: # SimilarityLinks don't require an InversionRule obviously self.chainer.add_rule(rules.TransitiveSimilarityRule(self.chainer, link_type)) self.chainer.add_rule(rules.SymmetricModusPonensRule(self.chainer, link_type)) self.chainer.add_rule(predicate_rules.EvaluationImplicationRule(self.chainer)) # These two Rules create mixed links out of intensional and extensional links self.chainer.add_rule(rules.InheritanceRule(self.chainer)) self.chainer.add_rule(rules.SimilarityRule(self.chainer)) # boolean links for rule in boolean_rules.create_and_or_rules(self.chainer, 2, 8): self.chainer.add_rule(rule) # create probabilistic logical links out of MemberLinks self.chainer.add_rule(rules.AndEvaluationRule(self.chainer)) self.chainer.add_rule(rules.OrEvaluationRule(self.chainer)) # These two "macro rules" make the individual rules redundant self.chainer.add_rule(rules.ExtensionalLinkEvaluationRule(self.chainer)) self.chainer.add_rule(rules.IntensionalLinkEvaluationRule(self.chainer)) #self.chainer.add_rule(rules.SubsetEvaluationRule(self.chainer)) self.chainer.add_rule(rules.NegatedSubsetEvaluationRule(self.chainer)) #self.chainer.add_rule(rules.ExtensionalSimilarityEvaluationRule(self.chainer)) #self.chainer.add_rule(rules.IntensionalInheritanceEvaluationRule(self.chainer)) #self.chainer.add_rule(rules.IntensionalSimilarityEvaluationRule(self.chainer)) self.member_rules = [rules.EvaluationToMemberRule(self.chainer)] self.member_rules += rules.create_general_evaluation_to_member_rules(self.chainer) for rule in self.member_rules: self.chainer.add_rule(rule) # It's important to have both of these self.chainer.add_rule(rules.MemberToInheritanceRule(self.chainer)) # self.chainer.add_rule(rules.InheritanceToMemberRule(self.chainer)) # AttractionLink could be useful for causality self.chainer.add_rule(rules.AttractionRule(self.chainer)) self.chainer.add_rule(quantifier_rules.ScholemRule(self.chainer)) #self.chainer.add_rule(rules.OntologicalInheritanceRule(self.chainer)) # for rule in temporal_rules.create_temporal_rules(self.chainer): # self.chainer.add_rule(rule) # higher_order_rules = [] # for rule in self.chainer.rules: # higher_order_rules.append(quantifier_rules.HigherOrderRule(self.chainer, rule)) # # contextual_rules = [] # for rule in self.chainer.rules: # contextual_rules.append(context_rules.ContextualRule(self.chainer, rule)) # # for rule in higher_order_rules + contextual_rules: # self.chainer.add_rule(rule) # # self.chainer.add_rule(context_rules.AndToContextRule(self.chainer, types.InheritanceLink)) def run(self, atomspace): if self.chainer is None: self.create_chainer(atomspace) # For simplicity, do nothing the first time. Silly APIs mean you have to call run to set the atomspace return # Update all of the node probabilities at each step #self.chainer.update_all_node_probabilities() for i in xrange(0, self.num_steps_per_cycle): self.step() def step(self): result = self.chainer.forward_step() result = self.chainer.backward_step()
class ForwardInferenceAgent(MindAgent): def __init__(self): self.chainer = None def create_chainer(self, atomspace): self.chainer = Chainer(atomspace, stimulateAtoms = False, agent = self, learnRuleFrequencies=False) # ImplicationLink is MixedImplicationLink, you could also have Extensional and Intensional Implication. etc. but that's a bit much. # similarity_types = [types.SimilarityLink, types.ExtensionalSimilarityLink, types.IntensionalSimilarityLink] # types.EquivalenceLink] # conditional_probability_types = [types.InheritanceLink, types.SubsetLink, types.IntensionalInheritanceLink, types.ImplicationLink] # always use the mixed inheritance types, because human inference is normally a mix of intensional and extensional conditional_probability_types = [types.InheritanceLink, types.ImplicationLink] similarity_types = [types.SimilarityLink, types.EquivalenceLink] for link_type in conditional_probability_types: self.chainer.add_rule(rules.InversionRule(self.chainer, link_type)) self.chainer.add_rule(rules.DeductionRule(self.chainer, link_type)) self.chainer.add_rule(rules.InductionRule(self.chainer, link_type)) self.chainer.add_rule(rules.AbductionRule(self.chainer, link_type)) # Seems better than Modus Ponens - it doesn't make anything up self.chainer.add_rule(rules.TermProbabilityRule(self.chainer, link_type)) self.chainer.add_rule(rules.TransitiveSimilarityRule(self.chainer)) # We also want symmetric Modus Ponens. It doesn't need inversion though obviously # These two Rules create mixed links out of intensional and extensional links self.chainer.add_rule(rules.InheritanceRule(self.chainer)) self.chainer.add_rule(rules.SimilarityRule(self.chainer)) # boolean links for rule in boolean_rules.create_and_or_rules(self.chainer, 2, 3): self.chainer.add_rule(rule) # create probabilistic logical links out of MemberLinks self.chainer.add_rule(rules.AndEvaluationRule(self.chainer)) self.chainer.add_rule(rules.OrEvaluationRule(self.chainer)) # These two "macro rules" make the individual rules redundant self.chainer.add_rule(rules.ExtensionalLinkEvaluationRule(self.chainer)) self.chainer.add_rule(rules.IntensionalLinkEvaluationRule(self.chainer)) #self.chainer.add_rule(rules.SubsetEvaluationRule(self.chainer)) self.chainer.add_rule(rules.NegatedSubsetEvaluationRule(self.chainer)) #self.chainer.add_rule(rules.ExtensionalSimilarityEvaluationRule(self.chainer)) #self.chainer.add_rule(rules.IntensionalInheritanceEvaluationRule(self.chainer)) #self.chainer.add_rule(rules.IntensionalSimilarityEvaluationRule(self.chainer)) self.member_rules = [rules.EvaluationToMemberRule(self.chainer)] self.member_rules += rules.create_general_evaluation_to_member_rules(self.chainer) for rule in self.member_rules: self.chainer.add_rule(rule) # It's important to have both of these self.chainer.add_rule(rules.MemberToInheritanceRule(self.chainer)) # self.chainer.add_rule(rules.InheritanceToMemberRule(self.chainer)) # AttractionLink could be useful for causality self.chainer.add_rule(rules.AttractionRule(self.chainer)) self.chainer.add_rule(rules.OntologicalInheritanceRule(self.chainer)) # for rule in temporal_rules.create_temporal_rules(self.chainer): # self.chainer.add_rule(rule) higher_order_rules = [] for rule in self.chainer.rules: higher_order_rules.append(quantifier_rules.HigherOrderRule(self.chainer, rule)) contextual_rules = [] # for rule in self.chainer.rules: # contextual_rules.append(context_rules.ContextualRule(self.chainer, rule)) for rule in higher_order_rules + contextual_rules: self.chainer.add_rule(rule) self.chainer.add_rule(context_rules.AndToContextRule(self.chainer, types.InheritanceLink)) def run(self, atomspace): # incredibly exciting futuristic display! #import os #os.system('cls' if os.name=='nt' else 'clear') def show_atoms(atoms): return ' '.join(str(atom)+str(atom.av) for atom in atoms) if self.chainer is None: self.create_chainer(atomspace) # For simplicity, do nothing the first time. Silly APIs mean you have to call run to set the atomspace return # Update all of the node probabilities at each step #self.chainer.update_all_node_probabilities() result = self.chainer.forward_step() if result: (rule, inputs, outputs) = result print '==== Inference ====' print rule.name, show_atoms(outputs), '<=', show_atoms(inputs) #print #print '==== Attentional Focus ====' #for atom in get_attentional_focus(atomspace)[0:30]: # print str(atom), atom.av #print '==== Result ====' #print output #print '==== Trail ====' #print_atoms( self.chainer.trails[output] ) else: print 'Invalid inference attempted' try: pass except AssertionError: import sys,traceback _,_,tb = sys.exc_info() traceback.print_tb(tb) # Fixed format tbInfo = traceback.extract_tb(tb) filename,line,func,text = tbInfo[-1] print ('An error occurred on line ' + str(line) + ' in statement ' + text) exit(1) except Exception, e: print e print e.args e.print_traceback() import sys,traceback _,_,tb = sys.exc_info() traceback.print_tb(tb) # Fixed format tbInfo = traceback.extract_tb(tb) filename,line,func,text = tbInfo[-1] print ('An error occurred on line ' + str(line) + ' in statement ' + text) exit(1)
class InferenceAgent(MindAgent): def __init__(self): self.chainer = None self.num_steps_per_cycle = 100 def create_chainer(self, atomspace): # Note: using stimulateAtoms will cause a segfault if you # create the Agent from the Python shell (use the agents-start # command in the cogserver shell). It's because giving atoms # stimulus only works if the MindAgent is added to the # CogServer's list of agents. self.chainer = Chainer(atomspace, stimulateAtoms=False, agent=self, learnRuleFrequencies=True) # Todo: Cleanup the following section where rules are added # ImplicationLink is MixedImplicationLink, you could also have # Extensional and Intensional Implication. etc. but that's a bit # much. # similarity_types = # [types.SimilarityLink, # types.ExtensionalSimilarityLink, # types.IntensionalSimilarityLink, # types.EquivalenceLink] # # conditional_probability_types = # [types.InheritanceLink, # types.SubsetLink, # types.IntensionalInheritanceLink, # types.ImplicationLink] # always use the mixed inheritance types, because human inference # is normally a mix of intensional and extensional conditional_probability_types = [types.InheritanceLink, types.ImplicationLink, types.PredictiveImplicationLink] similarity_types = [types.SimilarityLink, types.EquivalenceLink] for link_type in conditional_probability_types: self.chainer.add_rule(InversionRule(self.chainer, link_type)) self.chainer.add_rule(DeductionRule(self.chainer, link_type)) self.chainer.add_rule(InductionRule(self.chainer, link_type)) self.chainer.add_rule(AbductionRule(self.chainer, link_type)) # Seems better than Modus Ponens - it doesn't make anything up self.chainer.add_rule(TermProbabilityRule(self.chainer, link_type)) self.chainer.add_rule(ModusPonensRule(self.chainer, link_type)) for link_type in similarity_types: # SimilarityLinks don't require an InversionRule obviously self.chainer.add_rule(TransitiveSimilarityRule(self.chainer, link_type)) self.chainer.add_rule(SymmetricModusPonensRule(self.chainer, link_type)) self.chainer.add_rule(EvaluationImplicationRule(self.chainer)) # These two Rules create mixed links out of intensional and # extensional links self.chainer.add_rule(InheritanceRule(self.chainer)) self.chainer.add_rule(SimilarityRule(self.chainer)) # boolean links for rule in create_and_or_rules(self.chainer, 2, 8): self.chainer.add_rule(rule) self.chainer.add_rule( boolean_rules.AndBulkEvaluationRule(self.chainer)) # create probabilistic logical links out of MemberLinks self.chainer.add_rule(AndEvaluationRule(self.chainer)) self.chainer.add_rule(OrEvaluationRule(self.chainer)) # These two "macro rules" make the individual rules redundant self.chainer.add_rule(ExtensionalLinkEvaluationRule(self.chainer)) self.chainer.add_rule(IntensionalLinkEvaluationRule(self.chainer)) #self.chainer.add_rule(SubsetEvaluationRule(self.chainer)) self.chainer.add_rule(NegatedSubsetEvaluationRule(self.chainer)) #self.chainer.add_rule( # ExtensionalSimilarityEvaluationRule(self.chainer)) #self.chainer.add_rule( # IntensionalInheritanceEvaluationRule(self.chainer)) #self.chainer.add_rule( # IntensionalSimilarityEvaluationRule(self.chainer)) self.member_rules = [EvaluationToMemberRule(self.chainer), MemberToEvaluationRule(self.chainer)] self.member_rules += \ create_general_evaluation_to_member_rules(self.chainer) for rule in self.member_rules: self.chainer.add_rule(rule) # It's important to have both of these self.chainer.add_rule(MemberToInheritanceRule(self.chainer)) self.chainer.add_rule(InheritanceToMemberRule(self.chainer)) # AttractionLink could be useful for causality self.chainer.add_rule(AttractionRule(self.chainer)) self.chainer.add_rule(ScholemRule(self.chainer)) boolean_transformation_rules = create_boolean_transformation_rules(self.chainer) for rule in boolean_transformation_rules: self.chainer.add_rule(rule) #self.chainer.add_rule(OntologicalInheritanceRule(self.chainer)) #for rule in temporal_create_temporal_rules(self.chainer): #self.chainer.add_rule(rule) #higher_order_rules = [] #for rule in self.chainer.rules: #higher_order_append(HigherOrderRule(self.chainer, rule)) #contextual_rules = [] #for rule in self.chainer.rules: # contextual_append(ContextualRule(self.chainer, rule)) #for rule in higher_order_rules + contextual_rules: # self.chainer.add_rule(rule) #self.chainer.add_rule(AndToContextRule(self.chainer, # types.InheritanceLink)) def run(self, atomspace): if self.chainer is None: self.create_chainer(atomspace) # For simplicity, do nothing the first time. Silly APIs # mean you have to call run to set the atomspace return # Update all of the node probabilities at each step #self.chainer.update_all_node_probabilities() for i in xrange(0, self.num_steps_per_cycle): self.step() # Todo: The variable 'result' is never used def step(self): result = self.chainer.forward_step() result = self.chainer.backward_step()
class SocratesAgent(MindAgent): def __init__(self): self.chainer = None def create_chainer(self, atomspace): self.chainer = Chainer(atomspace, #stimulates atoms (stimulus of 10 at the moment) stimulateAtoms=True, #agent selects atoms with higher stis preferAttentionalFocus=False, allow_output_with_variables=True, delete_temporary_variables=True) self.chainer.add_rule( GeneralEvaluationToMemberRule(self.chainer, 0, 2)) self.chainer.add_rule(MemberToInheritanceRule(self.chainer)) self.chainer.add_rule( DeductionRule(self.chainer, types.InheritanceLink)) self.chainer.add_rule( InheritanceToMemberRule(self.chainer)) self.chainer.add_rule( MemberToEvaluationRule(self.chainer)) self.chainer.add_rule( AbductionRule(self.chainer, types.InheritanceLink)) def run(self, atomspace): if self.chainer is None: self.create_chainer(atomspace) return result = self.chainer.forward_step() return result
class DeceptionAgent(MindAgent): def __init__(self, mode): self.chainer = None self.query = None self.mode = mode # used to switch between inference and behavior outputs print "Initialized DeceptionAgent." def create_chainer(self, atomspace, stimulate_atoms=False): # if mode == 1 it is deception inference mode else it is deception # behavior mode if self.mode == 1: enable_variable_outputs = True else: enable_variable_outputs = False self.chainer = Chainer(atomspace, agent=self, stimulateAtoms=False, preferAttentionalFocus=False, allow_output_with_variables=enable_variable_outputs, delete_temporary_variables=True) # Transformation rules # This rules are invoked randomly and are run in the background because, # they imply the creation of AndLinks between different sets of Links so # as to represent the existance of a state in the world or of state of knowledge # being simulated. In the ure this wouldn't be required as AndLink is used to denote # the existance of the required set of Links without the need of creating # the AndLink. If one wants to match AndLinked set of Links then the QuoteLink # can be used.(This is based on the assumption that ure doesn't make a fundamental # change on how the pattern matcher works presently) if self.mode == 1: self.chainer.add_rule(ImplicationAndRule(self.chainer)) else: self.chainer.add_rule(AndCreationRule(self.chainer, 2)) self.chainer.add_rule(AndCreationRule(self.chainer, 2, types.EvaluationLink)) self.chainer.add_rule(AndCreationRule(self.chainer, 3, types.EvaluationLink)) self.chainer.add_rule(ModusPonensRule(self.chainer, types.ImplicationLink)) def run(self, atomspace): if self.chainer is None: self.create_chainer(atomspace) return # This insures that one of the added rules are invoked in the background # on each step. # self.chainer.forward_step() # Any rule that is used below is assured to be executed on each step # self.chainer.forward_step(AndCreationRule(self.chainer, 2)) # Depending on choice of demo, either the result on deception reasoning # or the behavior that result because of the reasoning can be enabled if self.mode == 1: # * Enable output of reasoning on rules # result = self.chainer.forward_step(ImplicationAndRule(self.chainer)) result = self.chainer.forward_step() else: # * Enable ouput of behavior # result = self.chainer.forward_step(ModusPonensRule(self.chainer, types.ImplicationLink)) result = self.chainer.forward_step() return result def get_trails(self): return self.chainer.trails def get_history(self): return self.chainer.history.get_history()
class PLNUnitTester(TestCase): def setUp(self): self.atomSpaceFileData = AtomSpace() self.atomSpaceInputs = AtomSpace() self.atomSpaceExpected = AtomSpace() self.testFiles = [] # Code below is to get us to the OC (git) root based on predictable test launch locations. self.chainer = Chainer(self.atomSpaceInputs, stimulateAtoms=False, agent=self, learnRuleFrequencies=False, allow_output_with_variables=True, allow_backchaining_with_variables=True) self.addTestFile("DeductionRule_InheritanceLink.scm") self.addTestFile("OrRule_new.scm") def tearDown(self): del self.atomSpaceFileData del self.atomSpaceInputs del self.atomSpaceExpected del self.chainer def test_all(self): for testFile in self.testFiles: print "Testing file: " + testFile self.run_file(testFile) def addTestFile(self, testFile): # Again, default to dev mode ruleFolder = str(os.getcwd()) + "/scm/specific_rules/" if not __DEV_MODE__: ruleFolder = os.getenv("PROJECT_SOURCE_DIR") + "/tests/python/test_pln/scm/specific_rules/" fullTestFile = ruleFolder + testFile self.testFiles.append(fullTestFile) def reset_atom_spaces(self): self.reset_atom_space(self.atomSpaceFileData) self.reset_atom_space(self.atomSpaceInputs) self.reset_atom_space(self.atomSpaceExpected) def load_file_into_atomspace(self, fullPath, atomSpace): load_scm(atomSpace, fullPath) def reset_atom_space(self, atomspaceToReset): atomspaceToReset.clear() # Default to dev mode # Build folder is up, up, up, /build coreTypes = "atomspace/core_types.scm" # Source root is up, up, up utilities = "scm/utilities.scm" if __VERBOSE__: if (os.path.exists(coreTypes)): print "Path '" + coreTypes + "' exists." if (os.path.exists(utilities)): print "Path '" + utilities + "' exists." if not __DEV_MODE__: sourceFolder = os.getenv("PROJECT_SOURCE_DIR") binFolder = os.getenv("PROJECT_BINARY_DIR") coreTypes = binFolder + "/opencog/atomspace/core_types.scm" utilities = sourceFolder + "/opencog/scm/utilities.scm" self.load_file_into_atomspace(coreTypes, atomspaceToReset) self.load_file_into_atomspace(utilities, atomspaceToReset) def fill_atomspace(self, atomspace, atomList): for atom in atomList: self.transfer_atom(atomspace, atom) def load_inputs(self): self.fill_atomspace(self.atomSpaceInputs, self.get_predicate_arguments(self.atomSpaceFileData, "inputs")) if __VERBOSE__: self.print_atomspace(self.atomSpaceInputs) def print_atomspace(self, atomspace): allNodes = atomspace.get_atoms_by_type(types.Node) for node in allNodes: print str(node.type) + " called " + node.name allLinks = atomspace.get_atoms_by_type(types.Link) for link in allLinks: print str(link.type) + " called " + link.name for out in link.out: print " has a node of type " + str(out.type) + " called " + out.name def load_outputs(self): self.fill_atomspace(self.atomSpaceExpected, self.get_predicate_arguments(self.atomSpaceFileData, "outputs")) def load_rules(self): rules = self.get_predicate_arguments(self.atomSpaceFileData, "rules") allRules = AllRules(self.atomSpaceFileData, self.chainer) for rule in rules: #allRules.import_rule(rule, self.chainer) self.chainer.add_rule(allRules.lookup_rule(rule)) def run_chaining_steps(self): if __VERBOSE__: print "Rules that can be applied:" print [" *" + r.name for r in self.chainer.rules] numberOfSteps = 1 try: numberOfStepsNode = self.get_predicate_arguments(self.atomSpaceFileData, "forwardSteps") numberOfSteps = int(numberOfStepsNode[0].name) except: numberOfSteps = 1 while numberOfSteps > 0: result = self.chainer.forward_step() if not result is None: numberOfSteps -= 1 if __VERBOSE__: print result def atomspace_links_to_list(self, atomSpace): result = [] expectedLinks = atomSpace.get_atoms_by_type(types.Link) for link in expectedLinks: atomStringToCheckFor = atomSpace.get_atom_string(link.h) if not "standardize_apart" in atomStringToCheckFor: atomStringToCheckFor = re.sub(r"\[[0-9]+\]", "", atomStringToCheckFor) result.append(atomStringToCheckFor) return result def check_atomspace_contains_atomspace(self, atomSpaceChecklist, atomSpaceToCheck): result = True error = "" expectedList = self.atomspace_links_to_list(atomSpaceChecklist) actualList = self.atomspace_links_to_list(atomSpaceToCheck) for listItem in expectedList: if not (listItem in actualList): if not "VariableNode" in listItem: if not "ListLink" in listItem: result = False error = "Unable to find \n" + listItem print error return result def verify_result(self): allPredictedItemsExist = False allItemsWerePredicted = False print "Checking if all predicted items exist:" if self.check_atomspace_contains_atomspace(self.atomSpaceExpected, self.atomSpaceInputs): print " Yes, all predicted items exist" allPredictedItemsExist = True else: print " No, not all predicted items were created (see above for details)" print "Checking if all items were predicted:" if self.check_atomspace_contains_atomspace(self.atomSpaceInputs, self.atomSpaceExpected): print " Yes, all created items were predicted" allItemsWerePredicted = True else: print " No, not created items were predicted (see above for details)" self.assertTrue(allPredictedItemsExist and allItemsWerePredicted) def run_file(self, filename): print "Running test file: " + filename print os.path.realpath(filename) self.reset_atom_spaces() self.load_file_into_atomspace(filename, self.atomSpaceFileData) self.load_inputs() self.load_outputs() self.load_rules() self.run_chaining_steps() self.verify_result() def transfer_atom(self, new_atomspace, atom): """ transfer (or rather copy) an atom from one atomspace to another. Assumes that both AtomSpaces have the same list of Atom types! returns the equivalent of atom in new_atomspace. creates it if necessary, including the outgoing set of links. """ # The AtomSpace probably clones the TV objects, and it wouldn't # matter much anyway #tv = TruthValue(atom.tv.mean, atom.tv.count) if atom.is_node(): return new_atomspace.add_node(atom.type, atom.name, tv=atom.tv) else: outgoing = [self.transfer_atom(new_atomspace, out) for out in atom.out] return new_atomspace.add_link(atom.type, outgoing, tv=atom.tv) def get_predicate_arguments(self, atomspace, predicate_name): """ Find the EvaluationLink for the predicate, and return the list of arguments (as a python list of Atoms). There must be only one EvaluationLink for it """ var = self.new_variable(atomspace) template = self.link(atomspace, types.EvaluationLink, [self.node(atomspace, types.PredicateNode, predicate_name), var]) queries = self.lookup_atoms(atomspace, template) # It will often find the original template in the results! queries.remove(template) #queries = [query for query in queries if query.tv.count > 0] if len(queries) != 1: raise ValueError("Predicate " + predicate_name + " must have 1 EvaluationLink") return queries[0].out[1].out def lookup_atoms(self, atomspace, template): if len(self.variables(template)) == 0: return [template] if template.type == types.VariableNode: root_type = types.Atom atoms = atomspace.get_atoms_by_type(root_type) else: # If the atom is a link with all variables below it, then # lookup all links of that type. If it has any nodes # (which aren't VariableNodes!), then lookup the incoming # set for that node first_node = self.get_first_node(template) if first_node is None: root_type = template.type atoms = atomspace.get_atoms_by_type(root_type) else: atoms = self.get_incoming_recursive(first_node) return atoms def new_variable(self, atomspace, prefix='$pln_var_'): return atomspace.add_node(types.VariableNode, prefix, prefixed=True) def link(self, atomspace, type, out): return atomspace.add_link(type, out) def node(self, atomspace, type, name): return atomspace.add_node(type, name) def variables(self, atom): """ Find all the variables in an expression (which may be repeated) """ if atom.is_node(): if self.is_variable(atom): return [atom] else: return [] else: result = [] for o in atom.out: result += self.variables(o) return result def get_first_node(self, atom): """ Using a depth first search on the link, return the first Node found. If atom is a Node just return that. """ if atom.is_node() and not self.is_variable(atom): return atom else: for o in atom.out: ret = self.get_first_node(o) if not ret is None: return ret return None def get_incoming_recursive(self, atom): inc = atom.incoming ret = [] ret += inc for link in inc: ret += self.get_incoming_recursive(link) return ret def is_variable(self, atom): return atom.is_a(types.VariableNode)
class InferenceAgent(MindAgent): def __init__(self): self.chainer = None self.query = None print "Initializing InferenceAgent." def create_chainer(self, atomspace, stimulate_atoms=True): """ Creates the chainer for the "smokes" example. Optionally, you can define the target query before calling this method, by defining a Scheme expression named "query". For example, you can issue the Scheme expression "(define query hasCancer)" in reference to the predicate defined in smokes.scm before loading this agent. Once defined, the target query will receive stimulus at every time step. Stimulus requires the agent to be running in a CogServer. For a complete example that incorporates this behavior, see example.py here: https://github.com/opencog/external-tools/tree/master/attention """ self.chainer = Chainer(atomspace, agent=self, stimulateAtoms=stimulate_atoms, allow_output_with_variables=False, preferAttentionalFocus=True, delete_temporary_variables=True) # ModusPonens: # Implication smokes(x) cancer(X) # smokes(Anna) # |= cancer(Anna) self.chainer.add_rule( ModusPonensRule(self.chainer, types.ImplicationLink)) # stimulateAtoms is only enabled when the agent is ran inside the # CogServer, since the functionality requires a CogServer and # attention allocation if self.chainer._stimulateAtoms: self.query = scheme_eval_h(atomspace, "query") def run(self, atomspace): if self.chainer is None: self.create_chainer(atomspace) print "PLN Chainer created." return print "PLN continuing." if not check_result(atomspace): result = self.chainer.forward_step() if self.query is not None: # Allow the stimulus amount to be set dynamically by setting # a configuration atom in the atomspace. stimulus_predicate = atomspace.add_node( types.PredicateNode, 'CONFIG-StimulusAmount') # Only set TARGET_STIMULUS if this atom has been setup with # an appropriate NumberNode with the value. outgoing = stimulus_predicate.out if len(outgoing) > 0: list = outgoing[0].incoming # EvaluationLink list = list[0].out # ListLink list = list[1].out # NumberNode value = list[0].name TARGET_STIMULUS = int(value) print "Target stimulus amount updated to {0}".\ format(TARGET_STIMULUS) self.chainer._give_stimulus(atomspace[self.query], TARGET_STIMULUS) return result
class DeceptionAgent(MindAgent): def __init__(self, mode): self.chainer = None self.query = None self.mode = mode # used to switch between inference and behavior outputs print "Initialized DeceptionAgent." def create_chainer(self, atomspace, stimulate_atoms=False): # if mode == 1 it is deception inference mode else it is deception # behavior mode if self.mode == 1: enable_variable_outputs = True else: enable_variable_outputs = False self.chainer = Chainer( atomspace, agent=self, stimulateAtoms=False, preferAttentionalFocus=False, allow_output_with_variables=enable_variable_outputs, delete_temporary_variables=True) # Transformation rules # This rules are invoked randomly and are run in the background because, # they imply the creation of AndLinks between different sets of Links so # as to represent the existance of a state in the world or of state of knowledge # being simulated. In the ure this wouldn't be required as AndLink is used to denote # the existance of the required set of Links without the need of creating # the AndLink. If one wants to match AndLinked set of Links then the QuoteLink # can be used.(This is based on the assumption that ure doesn't make a fundamental # change on how the pattern matcher works presently) if self.mode == 1: self.chainer.add_rule(ImplicationAndRule(self.chainer)) else: self.chainer.add_rule(AndCreationRule(self.chainer, 2)) self.chainer.add_rule( AndCreationRule(self.chainer, 2, types.EvaluationLink)) self.chainer.add_rule( AndCreationRule(self.chainer, 3, types.EvaluationLink)) self.chainer.add_rule( ModusPonensRule(self.chainer, types.ImplicationLink)) def run(self, atomspace): if self.chainer is None: self.create_chainer(atomspace) return # This insures that one of the added rules are invoked in the background # on each step. # self.chainer.forward_step() # Any rule that is used below is assured to be executed on each step # self.chainer.forward_step(AndCreationRule(self.chainer, 2)) # Depending on choice of demo, either the result on deception reasoning # or the behavior that result because of the reasoning can be enabled if self.mode == 1: # * Enable output of reasoning on rules # result = self.chainer.forward_step(ImplicationAndRule(self.chainer)) result = self.chainer.forward_step() else: # * Enable ouput of behavior # result = self.chainer.forward_step(ModusPonensRule(self.chainer, types.ImplicationLink)) result = self.chainer.forward_step() return result def get_trails(self): return self.chainer.trails def get_history(self): return self.chainer.history.get_history()
class AllRules(object): def __init__(self, atomspace, chainer): from pln.rules import rules, temporal_rules, boolean_rules, quantifier_rules, context_rules, predicate_rules # contains every rule self.chainer = Chainer(atomspace, stimulateAtoms = False, agent = self, learnRuleFrequencies=False) # contains only some rules self.test_chainer = chainer conditional_probability_types = [types.InheritanceLink, types.ImplicationLink, types.PredictiveImplicationLink] similarity_types = [types.SimilarityLink, types.EquivalenceLink] for link_type in conditional_probability_types: self.chainer.add_rule(rules.InversionRule(self.chainer, link_type)) self.chainer.add_rule(rules.DeductionRule(self.chainer, link_type)) self.chainer.add_rule(rules.InductionRule(self.chainer, link_type)) self.chainer.add_rule(rules.AbductionRule(self.chainer, link_type)) # Seems better than Modus Ponens - it doesn't make anything up self.chainer.add_rule(rules.TermProbabilityRule(self.chainer, link_type)) self.chainer.add_rule(rules.ModusPonensRule(self.chainer, link_type)) for link_type in similarity_types: # SimilarityLinks don't require an InversionRule obviously self.chainer.add_rule(rules.TransitiveSimilarityRule(self.chainer, link_type)) self.chainer.add_rule(rules.SymmetricModusPonensRule(self.chainer, link_type)) self.chainer.add_rule(predicate_rules.EvaluationImplicationRule(self.chainer)) # These two Rules create mixed links out of intensional and extensional links self.chainer.add_rule(rules.InheritanceRule(self.chainer)) self.chainer.add_rule(rules.SimilarityRule(self.chainer)) # boolean links for rule in boolean_rules.create_and_or_rules(self.chainer, 2, 8): self.chainer.add_rule(rule) # create probabilistic logical links out of MemberLinks self.chainer.add_rule(rules.AndEvaluationRule(self.chainer)) self.chainer.add_rule(rules.OrEvaluationRule(self.chainer)) self.chainer.add_rule(rules.ExtensionalLinkEvaluationRule(self.chainer)) self.chainer.add_rule(rules.IntensionalLinkEvaluationRule(self.chainer)) self.chainer.add_rule(rules.SubsetEvaluationRule(self.chainer)) self.chainer.add_rule(rules.NegatedSubsetEvaluationRule(self.chainer)) self.chainer.add_rule(rules.ExtensionalSimilarityEvaluationRule(self.chainer)) self.chainer.add_rule(rules.IntensionalInheritanceEvaluationRule(self.chainer)) self.chainer.add_rule(rules.IntensionalSimilarityEvaluationRule(self.chainer)) self.member_rules = [rules.EvaluationToMemberRule(self.chainer), rules.MemberToEvaluationRule(self.chainer)] self.member_rules += rules.create_general_evaluation_to_member_rules(self.chainer) for rule in self.member_rules: self.chainer.add_rule(rule) # It's important to have both of these self.chainer.add_rule(rules.MemberToInheritanceRule(self.chainer)) # self.chainer.add_rule(rules.InheritanceToMemberRule(self.chainer)) # AttractionLink could be useful for causality self.chainer.add_rule(rules.AttractionRule(self.chainer)) self.chainer.add_rule(quantifier_rules.ScholemRule(self.chainer)) for rule in temporal_rules.create_temporal_rules(self.chainer): self.chainer.add_rule(rule) def lookup_rule(self, rule_schema_node): rule = self.chainer.lookup_rule(rule_schema_node.name) rule._chainer = self.test_chainer return rule
class InferenceAgent(MindAgent): def __init__(self): self.chainer = None self.num_steps_per_cycle = 100 def create_chainer(self, atomspace): # Note: using stimulateAtoms will cause a segfault if you # create the Agent from the Python shell (use the agents-start # command in the cogserver shell). It's because giving atoms # stimulus only works if the MindAgent is added to the # CogServer's list of agents. self.chainer = Chainer(atomspace, stimulateAtoms=False, agent=self, learnRuleFrequencies=True) # Todo: Cleanup the following section where rules are added # ImplicationLink is MixedImplicationLink, you could also have # Extensional and Intensional Implication. etc. but that's a bit # much. # similarity_types = # [types.SimilarityLink, # types.ExtensionalSimilarityLink, # types.IntensionalSimilarityLink, # types.EquivalenceLink] # # conditional_probability_types = # [types.InheritanceLink, # types.SubsetLink, # types.IntensionalInheritanceLink, # types.ImplicationLink] # always use the mixed inheritance types, because human inference # is normally a mix of intensional and extensional conditional_probability_types = [ types.InheritanceLink, types.ImplicationLink, types.PredictiveImplicationLink ] similarity_types = [types.SimilarityLink, types.EquivalenceLink] for link_type in conditional_probability_types: self.chainer.add_rule(InversionRule(self.chainer, link_type)) self.chainer.add_rule(DeductionRule(self.chainer, link_type)) self.chainer.add_rule(InductionRule(self.chainer, link_type)) self.chainer.add_rule(AbductionRule(self.chainer, link_type)) # Seems better than Modus Ponens - it doesn't make anything up self.chainer.add_rule(TermProbabilityRule(self.chainer, link_type)) self.chainer.add_rule(ModusPonensRule(self.chainer, link_type)) self.chainer.add_rule( PreciseModusPonensRule(self.chainer, link_type)) for link_type in similarity_types: # SimilarityLinks don't require an InversionRule obviously self.chainer.add_rule( TransitiveSimilarityRule(self.chainer, link_type)) self.chainer.add_rule( SymmetricModusPonensRule(self.chainer, link_type)) self.chainer.add_rule(EvaluationImplicationRule(self.chainer)) # These two Rules create mixed links out of intensional and # extensional links self.chainer.add_rule(InheritanceRule(self.chainer)) self.chainer.add_rule(SimilarityRule(self.chainer)) for link_type in conditional_probability_types: self.chainer.add_rule(AndToSubsetRule1(self.chainer, link_type)) for N in xrange(2, 8): self.chainer.add_rule( AndToSubsetRuleN(self.chainer, link_type, N)) # boolean links for rule in create_and_or_rules(self.chainer, 2, 8): self.chainer.add_rule(rule) for N in xrange(2, 8): self.chainer.add_rule( boolean_rules.AndBulkEvaluationRule(self.chainer, N)) for N in xrange(3, 8): self.chainer.add_rule( boolean_rules.NegatedAndBulkEvaluationRule(self.chainer, N)) # create probabilistic logical links out of MemberLinks self.chainer.add_rule(AndEvaluationRule(self.chainer)) self.chainer.add_rule(OrEvaluationRule(self.chainer)) # These two "macro rules" make the individual rules redundant self.chainer.add_rule(ExtensionalLinkEvaluationRule(self.chainer)) self.chainer.add_rule(IntensionalLinkEvaluationRule(self.chainer)) #self.chainer.add_rule(SubsetEvaluationRule(self.chainer)) self.chainer.add_rule(NegatedSubsetEvaluationRule(self.chainer)) #self.chainer.add_rule( # ExtensionalSimilarityEvaluationRule(self.chainer)) #self.chainer.add_rule( # IntensionalInheritanceEvaluationRule(self.chainer)) #self.chainer.add_rule( # IntensionalSimilarityEvaluationRule(self.chainer)) self.member_rules = [ GeneralEvaluationToMemberRule(self.chainer), MemberToEvaluationRule(self.chainer) ] self.member_rules += \ create_general_evaluation_to_member_rules(self.chainer) for rule in self.member_rules: self.chainer.add_rule(rule) # It's important to have both of these self.chainer.add_rule(MemberToInheritanceRule(self.chainer)) self.chainer.add_rule(InheritanceToMemberRule(self.chainer)) # AttractionLink could be useful for causality self.chainer.add_rule(AttractionRule(self.chainer)) self.chainer.add_rule(ScholemRule(self.chainer)) boolean_transformation_rules = create_boolean_transformation_rules( self.chainer) for rule in boolean_transformation_rules: self.chainer.add_rule(rule) #self.chainer.add_rule(OntologicalInheritanceRule(self.chainer)) #for rule in temporal_create_temporal_rules(self.chainer): #self.chainer.add_rule(rule) #higher_order_rules = [] #for rule in self.chainer.rules: #higher_order_append(HigherOrderRule(self.chainer, rule)) #contextual_rules = [] #for rule in self.chainer.rules: # contextual_append(ContextualRule(self.chainer, rule)) #for rule in higher_order_rules + contextual_rules: # self.chainer.add_rule(rule) #self.chainer.add_rule(AndToContextRule(self.chainer, # types.InheritanceLink)) def run(self, atomspace): if self.chainer is None: self.create_chainer(atomspace) # For simplicity, do nothing the first time. Silly APIs # mean you have to call run to set the atomspace return # Update all of the node probabilities at each step #self.chainer.update_all_node_probabilities() for i in xrange(0, self.num_steps_per_cycle): self.step() # Todo: The variable 'result' is never used def step(self): result = self.chainer.forward_step() result = self.chainer.backward_step()
class SocratesAgent(MindAgent): def __init__(self): self.chainer = None def create_chainer(self, atomspace): self.chainer = Chainer(atomspace, agent=self, stimulateAtoms=True, preferAttentionalFocus=True, allow_output_with_variables=True, delete_temporary_variables=True) self.chainer.add_rule( GeneralEvaluationToMemberRule(self.chainer, 0, 2)) self.chainer.add_rule(MemberToInheritanceRule(self.chainer)) self.chainer.add_rule( DeductionRule(self.chainer, types.InheritanceLink)) self.chainer.add_rule( InheritanceToMemberRule(self.chainer)) self.chainer.add_rule( MemberToEvaluationRule(self.chainer)) self.chainer.add_rule( AbductionRule(self.chainer, types.InheritanceLink)) def run(self, atomspace): if self.chainer is None: self.create_chainer(atomspace) print("PLN Chainer created.") return print("PLN continuing.") # there is no query here, so it doesn't give any stimulus if not check_result(atomspace): result = self.chainer.forward_step() return result
class ContextAgent(MindAgent): def __init__(self): self.chainer = None def create_chainer(self, atomspace): self.chainer = Chainer(atomspace, stimulateAtoms=False, preferAttentionalFocus=False, allow_output_with_variables=True, delete_temporary_variables=True) self.chainer.add_rule(InheritanceToContextRule(self.chainer)) self.chainer.add_rule(EvaluationToContextRule(self.chainer)) self.chainer.add_rule(SubsetToContextRule(self.chainer)) self.chainer.add_rule(ContextToInheritanceRule(self.chainer)) self.chainer.add_rule(ContextToEvaluationRule(self.chainer)) self.chainer.add_rule(ContextToSubsetRule(self.chainer)) self.chainer.add_rule(ContextFreeToSensitiveRule(self.chainer)) def run(self, atomspace): if self.chainer is None: self.create_chainer(atomspace) return result = self.chainer.forward_step() return result
class SocratesAgent(MindAgent): def __init__(self): self.chainer = None def create_chainer(self, atomspace): self.chainer = Chainer( atomspace, #stimulates atoms (stimulus of 10 at the moment) stimulateAtoms=True, #agent selects atoms with higher stis preferAttentionalFocus=False, allow_output_with_variables=True, delete_temporary_variables=True) self.chainer.add_rule(GeneralEvaluationToMemberRule( self.chainer, 0, 2)) self.chainer.add_rule(MemberToInheritanceRule(self.chainer)) self.chainer.add_rule( DeductionRule(self.chainer, types.InheritanceLink)) self.chainer.add_rule(InheritanceToMemberRule(self.chainer)) self.chainer.add_rule(MemberToEvaluationRule(self.chainer)) self.chainer.add_rule( AbductionRule(self.chainer, types.InheritanceLink)) def run(self, atomspace): if self.chainer is None: self.create_chainer(atomspace) return result = self.chainer.forward_step() return result
class AllRules(object): def __init__(self, atomspace, chainer): # contains every rule self.chainer = Chainer(atomspace, stimulateAtoms=False, agent=self, learnRuleFrequencies=False) # contains only some rules self.test_chainer = chainer conditional_probability_types = [ types.InheritanceLink, types.ImplicationLink, types.PredictiveImplicationLink ] similarity_types = [types.SimilarityLink, types.EquivalenceLink] for link_type in conditional_probability_types: self.chainer.add_rule(InversionRule( self.chainer, link_type)) # Rule test exists. self.chainer.add_rule(DeductionRule( self.chainer, link_type)) # Rule test exists. self.chainer.add_rule(InductionRule( self.chainer, link_type)) # Rule test exists. self.chainer.add_rule(AbductionRule( self.chainer, link_type)) # Rule test exists. # Seems better than Modus Ponens - it doesn't make anything up self.chainer.add_rule(TermProbabilityRule(self.chainer, link_type)) self.chainer.add_rule(ModusPonensRule(self.chainer, link_type)) self.chainer.add_rule( PreciseModusPonensRule(self.chainer, link_type)) self.chainer.add_rule( AndAs1stArgInsideLinkRule(self.chainer, link_type)) self.chainer.add_rule( AndAs2ndArgInsideLinkRule(self.chainer, link_type)) for link_type in similarity_types: # SimilarityLinks don't require an InversionRule obviously self.chainer.add_rule( TransitiveSimilarityRule(self.chainer, link_type)) # Rule test exists. self.chainer.add_rule( SymmetricModusPonensRule(self.chainer, link_type)) self.chainer.add_rule(EvaluationImplicationRule( self.chainer)) # No test, appears to produce a TV not new nodes. # These two Rules create mixed links out of intensional and # extensional links self.chainer.add_rule(InheritanceRule( self.chainer)) # Rule test exists. self.chainer.add_rule(SimilarityRule(self.chainer)) for link_type in conditional_probability_types: self.chainer.add_rule(AndToSubsetRule1(self.chainer, link_type)) for N in xrange(2, 8): self.chainer.add_rule( AndToSubsetRuleN(self.chainer, link_type, N)) # boolean links for rule in create_and_or_rules(self.chainer, 2, 8): self.chainer.add_rule(rule) for N in xrange(2, 8): self.chainer.add_rule( boolean_rules.AndBulkEvaluationRule(self.chainer, N)) for N in xrange(3, 8): self.chainer.add_rule( boolean_rules.NegatedAndBulkEvaluationRule(self.chainer, N)) general_evaluation_to_member_rules = create_general_evaluation_to_member_rules( self.chainer) for rule in general_evaluation_to_member_rules: self.chainer.add_rule(rule) # create probabilistic logical links out of MemberLinks self.chainer.add_rule(AndEvaluationRule(self.chainer)) self.chainer.add_rule(OrEvaluationRule(self.chainer)) self.chainer.add_rule(ExtensionalLinkEvaluationRule(self.chainer)) self.chainer.add_rule(IntensionalLinkEvaluationRule(self.chainer)) self.chainer.add_rule(SubsetEvaluationRule(self.chainer)) self.chainer.add_rule(NegatedSubsetEvaluationRule(self.chainer)) self.chainer.add_rule(ExtensionalSimilarityEvaluationRule( self.chainer)) self.chainer.add_rule( IntensionalInheritanceEvaluationRule(self.chainer)) self.chainer.add_rule(IntensionalSimilarityEvaluationRule( self.chainer)) self.chainer.add_rule(SatisfyingSetToConceptRule(self.chainer, 1)) # context rules self.chainer.add_rule(InheritanceToContextRule(self.chainer)) self.chainer.add_rule(EvaluationToContextRule(self.chainer)) self.chainer.add_rule(SubsetToContextRule(self.chainer)) self.chainer.add_rule(ContextToInheritanceRule(self.chainer)) self.chainer.add_rule(ContextToEvaluationRule(self.chainer)) self.chainer.add_rule(ContextToSubsetRule(self.chainer)) # self.member_rules = [GeneralEvaluationToMemberRule(self.chainer), # MemberToEvaluationRule(self.chainer)] # self.member_rules += \ # create_general_evaluation_to_member_rules(self.chainer) # for rule in self.member_rules: # self.chainer.add_rule(rule) # It's important to have both of these self.chainer.add_rule(MemberToInheritanceRule(self.chainer)) # self.chainer.add_rule(InheritanceToMemberRule(self.chainer)) # AttractionLink could be useful for causality self.chainer.add_rule(AttractionRule(self.chainer)) self.chainer.add_rule(ScholemRule(self.chainer)) for rule in create_temporal_rules(self.chainer): self.chainer.add_rule(rule) boolean_transformation_rules = create_boolean_transformation_rules( self.chainer) for rule in boolean_transformation_rules: self.chainer.add_rule(rule) def lookup_rule(self, rule_schema_node): rule = self.chainer.lookup_rule(rule_schema_node.name) rule._chainer = self.test_chainer return rule
class ForwardInferenceAgent(MindAgent): def __init__(self): self.chainer = None def create_chainer(self, atomspace): self.chainer = Chainer(atomspace, stimulateAtoms=False, agent=self, learnRuleFrequencies=False) # ImplicationLink is MixedImplicationLink, you could also have Extensional and Intensional Implication. etc. but that's a bit much. # similarity_types = [types.SimilarityLink, types.ExtensionalSimilarityLink, types.IntensionalSimilarityLink] # types.EquivalenceLink] # conditional_probability_types = [types.InheritanceLink, types.SubsetLink, types.IntensionalInheritanceLink, types.ImplicationLink] # always use the mixed inheritance types, because human inference is normally a mix of intensional and extensional conditional_probability_types = [ types.InheritanceLink, types.ImplicationLink ] similarity_types = [types.SimilarityLink, types.EquivalenceLink] for link_type in conditional_probability_types: self.chainer.add_rule(rules.InversionRule(self.chainer, link_type)) self.chainer.add_rule(rules.DeductionRule(self.chainer, link_type)) self.chainer.add_rule(rules.InductionRule(self.chainer, link_type)) self.chainer.add_rule(rules.AbductionRule(self.chainer, link_type)) #self.chainer.add_rule(rules.ModusPonensRule(self.chainer, link_type)) # As a hack, use the standard DeductionRule for SimilarityLinks. It needs its own formula really. for link_type in similarity_types: self.chainer.add_rule(rules.DeductionRule(self.chainer, link_type)) # These two Rules create mixed links out of intensional and extensional links self.chainer.add_rule(rules.InheritanceRule(self.chainer)) self.chainer.add_rule(rules.SimilarityRule(self.chainer)) # boolean links for rule in boolean_rules.create_and_or_rules(self.chainer, 1, 2): self.chainer.add_rule(rule) # create probabilistic logical links out of MemberLinks self.chainer.add_rule(rules.AndEvaluationRule(self.chainer)) self.chainer.add_rule(rules.OrEvaluationRule(self.chainer)) # These two "macro rules" make the individual rules redundant self.chainer.add_rule(rules.ExtensionalLinkEvaluationRule( self.chainer)) self.chainer.add_rule(rules.IntensionalLinkEvaluationRule( self.chainer)) #self.chainer.add_rule(rules.SubsetEvaluationRule(self.chainer)) self.chainer.add_rule(rules.NegatedSubsetEvaluationRule(self.chainer)) #self.chainer.add_rule(rules.ExtensionalSimilarityEvaluationRule(self.chainer)) #self.chainer.add_rule(rules.IntensionalInheritanceEvaluationRule(self.chainer)) #self.chainer.add_rule(rules.IntensionalSimilarityEvaluationRule(self.chainer)) self.member_rules = [rules.EvaluationToMemberRule(self.chainer)] self.member_rules += rules.create_general_evaluation_to_member_rules( self.chainer) for rule in self.member_rules: self.chainer.add_rule(rule) # It's important to have both of these self.chainer.add_rule(rules.MemberToInheritanceRule(self.chainer)) # self.chainer.add_rule(rules.InheritanceToMemberRule(self.chainer)) # AttractionLink could be useful for causality self.chainer.add_rule(rules.AttractionRule(self.chainer)) # for rule in temporal_rules.create_temporal_rules(self.chainer): # self.chainer.add_rule(rule) def run(self, atomspace): # incredibly exciting futuristic display! #import os #os.system('cls' if os.name=='nt' else 'clear') def show_atoms(atoms): return ' '.join(str(atom) + str(atom.av) for atom in atoms) if self.chainer is None: self.create_chainer(atomspace) # For simplicity, do nothing the first time. Silly APIs mean you have to call run to set the atomspace return # Update all of the node probabilities at each step self.chainer.update_all_node_probabilities() result = self.chainer.forward_step() if result: (rule, inputs, outputs) = result print '==== Inference ====' print rule.name, show_atoms(outputs), '<=', show_atoms(inputs) #print #print '==== Attentional Focus ====' #for atom in get_attentional_focus(atomspace)[0:30]: # print str(atom), atom.av #print '==== Result ====' #print output #print '==== Trail ====' #print_atoms( self.chainer.trails[output] ) else: print 'Invalid inference attempted' try: pass except AssertionError: import sys, traceback _, _, tb = sys.exc_info() traceback.print_tb(tb) # Fixed format tbInfo = traceback.extract_tb(tb) filename, line, func, text = tbInfo[-1] print('An error occurred on line ' + str(line) + ' in statement ' + text) exit(1) except Exception, e: print e print e.args e.print_traceback() import sys, traceback _, _, tb = sys.exc_info() traceback.print_tb(tb) # Fixed format tbInfo = traceback.extract_tb(tb) filename, line, func, text = tbInfo[-1] print('An error occurred on line ' + str(line) + ' in statement ' + text) exit(1)
class AllRules(object): def __init__(self, atomspace, chainer): # contains every rule self.chainer = Chainer(atomspace, stimulateAtoms=False, agent=self, learnRuleFrequencies=False) # contains only some rules self.test_chainer = chainer conditional_probability_types = [types.InheritanceLink, types.ImplicationLink, types.PredictiveImplicationLink] similarity_types = [types.SimilarityLink, types.EquivalenceLink] for link_type in conditional_probability_types: self.chainer.add_rule(InversionRule(self.chainer, link_type)) # Rule test exists. self.chainer.add_rule(DeductionRule(self.chainer, link_type)) # Rule test exists. self.chainer.add_rule(InductionRule(self.chainer, link_type)) # Rule test exists. self.chainer.add_rule(AbductionRule(self.chainer, link_type)) # Rule test exists. # Seems better than Modus Ponens - it doesn't make anything up self.chainer.add_rule(TermProbabilityRule(self.chainer, link_type)) self.chainer.add_rule(ModusPonensRule(self.chainer, link_type)) self.chainer.add_rule(PreciseModusPonensRule(self.chainer, link_type)) for link_type in similarity_types: # SimilarityLinks don't require an InversionRule obviously self.chainer.add_rule( TransitiveSimilarityRule(self.chainer, link_type)) # Rule test exists. self.chainer.add_rule( SymmetricModusPonensRule(self.chainer, link_type)) self.chainer.add_rule(EvaluationImplicationRule(self.chainer)) # No test, appears to produce a TV not new nodes. # These two Rules create mixed links out of intensional and # extensional links self.chainer.add_rule(InheritanceRule(self.chainer)) # Rule test exists. self.chainer.add_rule(SimilarityRule(self.chainer)) for link_type in conditional_probability_types: self.chainer.add_rule(AndToSubsetRule1(self.chainer, link_type)) for N in xrange(2, 8): self.chainer.add_rule(AndToSubsetRuleN(self.chainer, link_type, N)) # boolean links for rule in create_and_or_rules(self.chainer, 2, 8): self.chainer.add_rule(rule) for N in xrange(2, 8): self.chainer.add_rule( boolean_rules.AndBulkEvaluationRule(self.chainer, N)) for N in xrange(3, 8): self.chainer.add_rule( boolean_rules.NegatedAndBulkEvaluationRule(self.chainer, N)) general_evaluation_to_member_rules = create_general_evaluation_to_member_rules(self.chainer) for rule in general_evaluation_to_member_rules: self.chainer.add_rule(rule) # create probabilistic logical links out of MemberLinks self.chainer.add_rule(AndEvaluationRule(self.chainer)) self.chainer.add_rule(OrEvaluationRule(self.chainer)) self.chainer.add_rule(ExtensionalLinkEvaluationRule(self.chainer)) self.chainer.add_rule(IntensionalLinkEvaluationRule(self.chainer)) self.chainer.add_rule(SubsetEvaluationRule(self.chainer)) self.chainer.add_rule(NegatedSubsetEvaluationRule(self.chainer)) self.chainer.add_rule( ExtensionalSimilarityEvaluationRule(self.chainer)) self.chainer.add_rule( IntensionalInheritanceEvaluationRule(self.chainer)) self.chainer.add_rule( IntensionalSimilarityEvaluationRule(self.chainer)) # self.member_rules = [GeneralEvaluationToMemberRule(self.chainer), # MemberToEvaluationRule(self.chainer)] # self.member_rules += \ # create_general_evaluation_to_member_rules(self.chainer) # for rule in self.member_rules: # self.chainer.add_rule(rule) # It's important to have both of these self.chainer.add_rule(MemberToInheritanceRule(self.chainer)) # self.chainer.add_rule(InheritanceToMemberRule(self.chainer)) # AttractionLink could be useful for causality self.chainer.add_rule(AttractionRule(self.chainer)) self.chainer.add_rule(ScholemRule(self.chainer)) for rule in create_temporal_rules(self.chainer): self.chainer.add_rule(rule) boolean_transformation_rules = create_boolean_transformation_rules(self.chainer) for rule in boolean_transformation_rules: self.chainer.add_rule(rule) def lookup_rule(self, rule_schema_node): rule = self.chainer.lookup_rule(rule_schema_node.name) rule._chainer = self.test_chainer return rule
class InferenceAgent(MindAgent): def __init__(self): self.chainer = None self.query = None print "Initializing InferenceAgent." def create_chainer(self, atomspace, stimulate_atoms=True): """ Creates the chainer for the "smokes" example. Optionally, you can define the target query before calling this method, by defining a Scheme expression named "query". For example, you can issue the Scheme expression "(define query hasCancer)" in reference to the predicate defined in smokes.scm before loading this agent. Once defined, the target query will receive stimulus at every time step. Stimulus requires the agent to be running in a CogServer. For a complete example that incorporates this behavior, see example.py here: https://github.com/opencog/external-tools/tree/master/attention """ self.chainer = Chainer(atomspace, agent=self, stimulateAtoms=stimulate_atoms, allow_output_with_variables=False, preferAttentionalFocus=True, delete_temporary_variables=True) # ModusPonens: # Implication smokes(x) cancer(X) # smokes(Anna) # |= cancer(Anna) self.chainer.add_rule( ModusPonensRule(self.chainer, types.ImplicationLink)) # stimulateAtoms is only enabled when the agent is ran inside the # CogServer, since the functionality requires a CogServer and # attention allocation if self.chainer._stimulateAtoms: self.query = scheme_eval_h(atomspace, "query") def run(self, atomspace): if self.chainer is None: self.create_chainer(atomspace) print "PLN Chainer created." return print "PLN continuing." if not check_result(atomspace): result = self.chainer.forward_step() if self.query is not None: # Allow the stimulus amount to be set dynamically by setting # a configuration atom in the atomspace. stimulus_predicate = atomspace.add_node(types.PredicateNode, 'CONFIG-StimulusAmount') # Only set TARGET_STIMULUS if this atom has been setup with # an appropriate NumberNode with the value. outgoing = stimulus_predicate.out if len(outgoing) > 0: list = outgoing[0].incoming # EvaluationLink list = list[0].out # ListLink list = list[1].out # NumberNode value = list[0].name TARGET_STIMULUS = int(value) print "Target stimulus amount updated to {0}".\ format(TARGET_STIMULUS) self.chainer._give_stimulus(atomspace[self.query], TARGET_STIMULUS) return result
class SocratesAgent(MindAgent): def __init__(self): self.chainer = None def create_chainer(self, atomspace): self.chainer = Chainer(atomspace, agent=self, stimulateAtoms=True, preferAttentionalFocus=True, allow_output_with_variables=True, delete_temporary_variables=True) self.chainer.add_rule(GeneralEvaluationToMemberRule( self.chainer, 0, 2)) self.chainer.add_rule(MemberToInheritanceRule(self.chainer)) self.chainer.add_rule( DeductionRule(self.chainer, types.InheritanceLink)) self.chainer.add_rule(InheritanceToMemberRule(self.chainer)) self.chainer.add_rule(MemberToEvaluationRule(self.chainer)) self.chainer.add_rule( AbductionRule(self.chainer, types.InheritanceLink)) def run(self, atomspace): if self.chainer is None: self.create_chainer(atomspace) print("PLN Chainer created.") return print("PLN continuing.") # there is no query here, so it doesn't give any stimulus if not check_result(atomspace): result = self.chainer.forward_step() return result
class ForwardInferenceAgent(MindAgent): def __init__(self): self.chainer = None def create_chainer(self, atomspace): self.chainer = Chainer(atomspace, stimulateAtoms = False, agent = self, learnRuleFrequencies=True) # ImplicationLink is MixedImplicationLink, you could also have Extensional and Intensional Implication. etc. but that's a bit much. # similarity_types = [types.SimilarityLink, types.ExtensionalSimilarityLink, types.IntensionalSimilarityLink] # types.EquivalenceLink] # conditional_probability_types = [types.InheritanceLink, types.SubsetLink, types.IntensionalInheritanceLink, types.ImplicationLink] # always use the mixed inheritance types, because human inference is normally a mix of intensional and extensional conditional_probability_types = [types.InheritanceLink, types.ImplicationLink] similarity_types = [types.SimilarityLink, types.EquivalenceLink] for link_type in conditional_probability_types: self.chainer.add_rule(rules.InversionRule(self.chainer, link_type)) self.chainer.add_rule(rules.DeductionRule(self.chainer, link_type)) self.chainer.add_rule(rules.ModusPonensRule(self.chainer, link_type)) # As a hack, use the standard DeductionRule for SimilarityLinks. It needs its own formula really. for link_type in similarity_types: self.chainer.add_rule(rules.DeductionRule(self.chainer, link_type)) # These two Rules create mixed links out of intensional and extensional links self.chainer.add_rule(rules.InheritanceRule(self.chainer)) self.chainer.add_rule(rules.SimilarityRule(self.chainer)) # and/or/not self.chainer.add_rule(rules.NotCreationRule(self.chainer)) self.chainer.add_rule(rules.NotEliminationRule(self.chainer)) for rule in rules.create_and_or_rules(self.chainer, 1, 2): self.chainer.add_rule(rule) # create probabilistic logical links out of MemberLinks self.chainer.add_rule(rules.SubsetEvaluationRule(self.chainer)) self.chainer.add_rule(rules.IntensionalInheritanceEvaluationRule(self.chainer)) self.chainer.add_rule(rules.ExtensionalSimilarityEvaluationRule(self.chainer)) self.chainer.add_rule(rules.IntensionalSimilarityEvaluationRule(self.chainer)) self.chainer.add_rule(rules.EvaluationToMemberRule(self.chainer)) self.chainer.add_rule(rules.MemberToInheritanceRule(self.chainer)) # AttractionLink could be useful for causality self.chainer.add_rule(rules.AttractionRule(self.chainer)) for rule in temporal_rules.create_temporal_rules(self.chainer): self.chainer.add_rule(rule) def run(self, atomspace): # incredibly exciting futuristic display! #import os #os.system('cls' if os.name=='nt' else 'clear') def show_atoms(atoms): return ' '.join(str(atom)+str(atom.av) for atom in atoms) if self.chainer is None: self.create_chainer(atomspace) import pdb; pdb.set_trace() result = self.chainer.forward_step() if result: (rule, inputs, outputs) = result print '==== Inference ====' print rule.name, show_atoms(outputs), '<=', show_atoms(inputs) print print '==== Attentional Focus ====' for atom in get_attentional_focus(atomspace)[0:30]: print str(atom), atom.av #print '==== Result ====' #print output #print '==== Trail ====' #print_atoms( self.chainer.trails[output] ) else: print 'Invalid inference attempted' try: pass except AssertionError: import sys,traceback _,_,tb = sys.exc_info() traceback.print_tb(tb) # Fixed format tbInfo = traceback.extract_tb(tb) filename,line,func,text = tbInfo[-1] print ('An error occurred on line ' + str(line) + ' in statement ' + text) exit(1) except Exception, e: print e print e.args e.print_traceback() import sys,traceback _,_,tb = sys.exc_info() traceback.print_tb(tb) # Fixed format tbInfo = traceback.extract_tb(tb) filename,line,func,text = tbInfo[-1] print ('An error occurred on line ' + str(line) + ' in statement ' + text) exit(1)
data = "tests/python/test_pln/scm_disabled/temporal/temporalToyExample.scm" # data = "opencog/python/pln_old/examples/temporal/temporal-r2l-input.scm" # initialize atomspace atomspace = AtomSpace() __init__(atomspace) for item in [coreTypes, utilities, timeLinks, data]: load_scm(atomspace, item) # initialize chainer chainer = Chainer(atomspace, stimulateAtoms=False, allow_output_with_variables=True, delete_temporary_variables=True) for rule in create_temporal_rules(chainer): chainer.add_rule(rule) if print_starting_contents: print('AtomSpace starting contents:') atomspace.print_list() outputs_produced = 0 for i in range(0, num_steps): result = chainer.forward_step() output = None input = None rule = None if result is not None: atomspace_string = ""
class AllRules(object): def __init__(self, atomspace, chainer): from pln.rules import rules, temporal_rules, boolean_rules, quantifier_rules, context_rules, predicate_rules # contains every rule self.chainer = Chainer(atomspace, stimulateAtoms=False, agent=self, learnRuleFrequencies=False) # contains only some rules self.test_chainer = chainer conditional_probability_types = [ types.InheritanceLink, types.ImplicationLink, types.PredictiveImplicationLink ] similarity_types = [types.SimilarityLink, types.EquivalenceLink] for link_type in conditional_probability_types: self.chainer.add_rule(rules.InversionRule(self.chainer, link_type)) self.chainer.add_rule(rules.DeductionRule(self.chainer, link_type)) self.chainer.add_rule(rules.InductionRule(self.chainer, link_type)) self.chainer.add_rule(rules.AbductionRule(self.chainer, link_type)) # Seems better than Modus Ponens - it doesn't make anything up self.chainer.add_rule( rules.TermProbabilityRule(self.chainer, link_type)) self.chainer.add_rule( rules.ModusPonensRule(self.chainer, link_type)) for link_type in similarity_types: # SimilarityLinks don't require an InversionRule obviously self.chainer.add_rule( rules.TransitiveSimilarityRule(self.chainer, link_type)) self.chainer.add_rule( rules.SymmetricModusPonensRule(self.chainer, link_type)) self.chainer.add_rule( predicate_rules.EvaluationImplicationRule(self.chainer)) # These two Rules create mixed links out of intensional and extensional links self.chainer.add_rule(rules.InheritanceRule(self.chainer)) self.chainer.add_rule(rules.SimilarityRule(self.chainer)) # boolean links for rule in boolean_rules.create_and_or_rules(self.chainer, 2, 8): self.chainer.add_rule(rule) # create probabilistic logical links out of MemberLinks self.chainer.add_rule(rules.AndEvaluationRule(self.chainer)) self.chainer.add_rule(rules.OrEvaluationRule(self.chainer)) self.chainer.add_rule(rules.ExtensionalLinkEvaluationRule( self.chainer)) self.chainer.add_rule(rules.IntensionalLinkEvaluationRule( self.chainer)) self.chainer.add_rule(rules.SubsetEvaluationRule(self.chainer)) self.chainer.add_rule(rules.NegatedSubsetEvaluationRule(self.chainer)) self.chainer.add_rule( rules.ExtensionalSimilarityEvaluationRule(self.chainer)) self.chainer.add_rule( rules.IntensionalInheritanceEvaluationRule(self.chainer)) self.chainer.add_rule( rules.IntensionalSimilarityEvaluationRule(self.chainer)) self.member_rules = [ rules.EvaluationToMemberRule(self.chainer), rules.MemberToEvaluationRule(self.chainer) ] self.member_rules += rules.create_general_evaluation_to_member_rules( self.chainer) for rule in self.member_rules: self.chainer.add_rule(rule) # It's important to have both of these self.chainer.add_rule(rules.MemberToInheritanceRule(self.chainer)) # self.chainer.add_rule(rules.InheritanceToMemberRule(self.chainer)) # AttractionLink could be useful for causality self.chainer.add_rule(rules.AttractionRule(self.chainer)) self.chainer.add_rule(quantifier_rules.ScholemRule(self.chainer)) for rule in temporal_rules.create_temporal_rules(self.chainer): self.chainer.add_rule(rule) def lookup_rule(self, rule_schema_node): rule = self.chainer.lookup_rule(rule_schema_node.name) rule._chainer = self.test_chainer return rule