def renameVars(self): if self._renameVarsMaps: if self in self._renameVarsMaps[-1]: return self._renameVarsMaps[-1][self] # progress('Running renameVars of self=%s' % self.debugString()) m2 = {} for triple in self: for node in triple.spo(): if isinstance(node, Formula): if node not in m2: m2[node] = node.renameVars() m = {} n = {} F1 = self.newFormula() F1.loadFormulaWithSubstitution( self, m2, why=Because("Vars in subexpressions must be renamed")) for v in sorted(list(F1.existentials()), Term.compareAnyTerm): m[v] = F1.newBlankNode() for v in sorted(list(F1.universals()), Term.compareAnyTerm): n[v] = F1.newUniversal(v) e = F1.existentials() u = F1.universals() for var in m: e.remove(var) for var in n: u.remove(var) m.update(n) #progress('F1 is %s' % F1.debugString()) #progress('bindings are %s' % m) retVal = F1.substitution(m, why=Because("Vars must be renamed"), cannon=False, keepOpen=True) self._renameVarsMaps.append(0) retVal = retVal.canonicalize() self._renameVarsMaps.pop() if self._renameVarsMaps: self._renameVarsMaps[-1][self] = retVal self._renameVarsMaps[-1][retVal] = retVal assert retVal.canonical is retVal, retVal #progress('...got %s' % retVal.debugString()) return retVal
def renameVars(self): if self._renameVarsMaps: if self in self._renameVarsMaps[-1]: return self._renameVarsMaps[-1][self] #progress('Running renameVars of self=%s' % self.debugString()) m2 = {} for triple in self: for node in triple.spo(): if isinstance(node, Formula): if node not in m2: m2[node] = node.renameVars() m = {} n = {} F1 = self.newFormula() F1.loadFormulaWithSubstitution(self, m2, why=Because("Vars in subexpressions must be renamed")) for v in sorted(list(F1.existentials()), Term.compareAnyTerm): m[v] = F1.newBlankNode() for v in sorted(list(F1.universals()), Term.compareAnyTerm): n[v] = F1.newUniversal(v) e = F1.existentials() u = F1.universals() for var in m: e.remove(var) for var in n: u.remove(var) m.update(n) #progress('F1 is %s' % F1.debugString()) #progress('bindings are %s' % m) retVal = F1.substitution(m, why=Because("Vars must be renamed"), cannon=False, keepOpen=True) self._renameVarsMaps.append(0) retVal = retVal.canonicalize() self._renameVarsMaps.pop() if self._renameVarsMaps: self._renameVarsMaps[-1][self] = retVal self._renameVarsMaps[-1][retVal] = retVal assert retVal.canonical is retVal, retVal #progress('...got %s' % retVal.debugString()) return retVal
def explain(self, ko, flags): me = self.me.get(ko, None) if me != None: return me # Only do this once me = self.meIn(ko) g = self.formula e = g.existentials() if g.occurringIn(e) != e: raise RuntimeError(g.debugString()) qed = ko.newBlankNode(why=dontAsk) standIn = formulaStandIn(ko, self.formula, flags) ko.add(subj=me, pred=reason.gives, obj=standIn, why=dontAsk) statementsForReason = {} # reverse index: group by reason for s, rea in sorted(self.reasonForStatement.items()): x = statementsForReason.get(rea, None) if x is None: statementsForReason[rea] = [s] else: x.append(s) if diag.chatty_flag > 29: progress( "Collector %s (->%s), explaining %i reasons for total of %i statements:-" % (self, me, len(statementsForReason), len(self.reasonForStatement))) progress("reasonForStatement", self.reasonForStatement) progress("statementsForReason", statementsForReason) # @@ Should special case (no conjunction) if only one r if len(statementsForReason) != 1: ko.add(subj=me, pred=rdf.type, obj=reason.Conjunction, why=dontAsk) for r, ss in statementsForReason.items(): assert r is not self, ("Loop in reasons!", self, id(self), s) try: r1 = r.explain(ko, flags=flags) except: print ss raise if diag.chatty_flag > 29: progress("\tExplaining reason %s (->%s) for %i statements" % (r, r1, len(ss))) for s in ss: progress("\t Statement %s" % (s)) if len(statementsForReason) == 1: ## No need for conjunction ko.substituteEqualsInPlace({r1: me}, why=dontAsk) else: ko.add(me, reason.component, r1, why=dontAsk) return me
def explain(self, ko, flags): me = self.me.get(ko, None) if me != None: return me # Only do this once me = self.meIn(ko) g = self.formula e = g.existentials() if g.occurringIn(e) != e: raise RuntimeError(g.debugString()) qed = ko.newBlankNode(why= dontAsk) standIn = formulaStandIn(ko,self.formula, flags) ko.add(subj=me, pred=reason.gives, obj=standIn, why=dontAsk) statementsForReason = {} # reverse index: group by reason for s, rea in sorted(self.reasonForStatement.items()): x = statementsForReason.get(rea, None) if x is None: statementsForReason[rea] = [s] else: x.append(s) if diag.chatty_flag > 29: progress( "Collector %s (->%s), explaining %i reasons for total of %i statements:-" % (self, me, len(statementsForReason), len(self.reasonForStatement))) progress("reasonForStatement", self.reasonForStatement) progress("statementsForReason", statementsForReason) # @@ Should special case (no conjunction) if only one r if len(statementsForReason) != 1: ko.add(subj=me, pred=rdf.type, obj=reason.Conjunction, why=dontAsk) for r, ss in statementsForReason.items(): assert r is not self, ("Loop in reasons!", self, id(self), s) try: r1 = r.explain(ko, flags=flags) except: print ss raise if diag.chatty_flag > 29: progress( "\tExplaining reason %s (->%s) for %i statements" % (r, r1, len(ss))) for s in ss: progress("\t Statement %s" % (s)) if len(statementsForReason) == 1: ## No need for conjunction ko.substituteEqualsInPlace({r1: me}, why=dontAsk) else: ko.add(me, reason.component, r1, why=dontAsk) return me
def patch(workingContext, patchFormula): """A task of running a set of updates on a knowledge base This is simpler than an Inference task, in that a patch is only done once, patches cannot lead to new patches, etc. """ if diag.chatty_flag >20: progress("New Update task, patches from %s applied to %s" % (patchFormula, workingContext)) store = workingContext.store true = store.newFormula().close() # {} universals = Set() lhs_done = [] agenda = {} for pred in store.insertion, store.deletion: for s in patchFormula.statementsMatching(pred=pred): dict = agenda.get(s.subject(), None) if dict == None: dict = {store.insertion: [], store.deletion: []} agenda[s.subject()] = dict dict[pred].append(s.object()) for lhs, dict in sorted(agenda.items()): if diag.chatty_flag > 19: progress("Patches lhs= %s: %s" %(lhs, dict)) if isinstance(lhs, Formula): if lhs.universals() != Set(): raise RuntimeError("""Cannot query for universally quantified things. As of 2003/07/28 forAll x ...x cannot be on left hand side of rule. This/these were: %s\n""" % lhs.universals()) addenda, minuenda = dict[store.insertion], dict[store.deletion] while addenda or minuenda: if addenda: conclusion = addenda.pop() else: conclusion = true if minuenda: retraction = minuenda.pop() else: retraction = true unmatched = lhs.statements[:] templateExistentials = lhs.existentials().copy() _substitute({lhs: workingContext}, unmatched) # Change context column variablesMentioned = lhs.occurringIn(patchFormula.universals()) variablesUsed = conclusion.occurringIn(variablesMentioned) | \ retraction.occurringIn(variablesMentioned) for x in sorted(variablesMentioned): if x not in variablesUsed: templateExistentials.add(x) if diag.chatty_flag >20: progress("New Patch =========== applied to %s" %(workingContext) ) for s in lhs.statements: progress(" ", `s`) progress("+=>") for s in conclusion.statements: progress(" ", `s`) progress("-=>") for s in retraction.statements: progress(" ", `s`) progress("Universals declared in outer " + seqToString(patchFormula.universals())) progress(" mentioned in template " + seqToString(variablesMentioned)) progress(" also used in conclusion " + seqToString(variablesUsed)) progress("Existentials in template " + seqToString(templateExistentials)) q = UpdateQuery(store, unmatched = unmatched, template = lhs, variables = patchFormula.universals(), existentials =templateExistentials, workingContext = workingContext, conclusion = conclusion, retraction = retraction, rule = None) q.resolve()
def patch(workingContext, patchFormula): """A task of running a set of updates on a knowledge base This is simpler than an Inference task, in that a patch is only done once, patches cannot lead to new patches, etc. """ if diag.chatty_flag > 20: progress("New Update task, patches from %s applied to %s" % (patchFormula, workingContext)) store = workingContext.store true = store.newFormula().close() # {} universals = Set() lhs_done = [] agenda = {} for pred in store.insertion, store.deletion: for s in patchFormula.statementsMatching(pred=pred): dict = agenda.get(s.subject(), None) if dict == None: dict = {store.insertion: [], store.deletion: []} agenda[s.subject()] = dict dict[pred].append(s.object()) for lhs, dict in sorted(agenda.items()): if diag.chatty_flag > 19: progress("Patches lhs= %s: %s" % (lhs, dict)) if isinstance(lhs, Formula): if lhs.universals() != Set(): raise RuntimeError( """Cannot query for universally quantified things. As of 2003/07/28 forAll x ...x cannot be on left hand side of rule. This/these were: %s\n""" % lhs.universals()) addenda, minuenda = dict[store.insertion], dict[store.deletion] while addenda or minuenda: if addenda: conclusion = addenda.pop() else: conclusion = true if minuenda: retraction = minuenda.pop() else: retraction = true unmatched = lhs.statements[:] templateExistentials = lhs.existentials().copy() _substitute({lhs: workingContext}, unmatched) # Change context column variablesMentioned = lhs.occurringIn(patchFormula.universals()) variablesUsed = conclusion.occurringIn(variablesMentioned) | \ retraction.occurringIn(variablesMentioned) for x in sorted(variablesMentioned): if x not in variablesUsed: templateExistentials.add(x) if diag.chatty_flag > 20: progress("New Patch =========== applied to %s" % (workingContext)) for s in lhs.statements: progress(" ", ` s `) progress("+=>") for s in conclusion.statements: progress(" ", ` s `) progress("-=>") for s in retraction.statements: progress(" ", ` s `) progress("Universals declared in outer " + seqToString(patchFormula.universals())) progress(" mentioned in template " + seqToString(variablesMentioned)) progress(" also used in conclusion " + seqToString(variablesUsed)) progress("Existentials in template " + seqToString(templateExistentials)) q = UpdateQuery(store, unmatched=unmatched, template=lhs, variables=patchFormula.universals(), existentials=templateExistentials, workingContext=workingContext, conclusion=conclusion, retraction=retraction, rule=None) q.resolve()