Пример #1
0
def PopulateTokenFromANode(aNode,bindings):
    #print aNode, bindings
    termList = [isinstance(term,Variable) and bindings[term] or term
                    for term in aNode.triplePattern]
    token = ReteToken(tuple(termList))
    token.bindVariables(aNode)
    return token
Пример #2
0
def PopulateTokenFromANode(aNode,bindings):
    #print aNode, bindings
    termList = [isinstance(term,Variable) and bindings[term] or term
                    for term in aNode.triplePattern]
    token = ReteToken(tuple(termList))
    token.bindVariables(aNode)
    return token
Пример #3
0
    def handleInferredTriple(self,
                             inferredTriple,
                             tokens,
                             termNode,
                             binding,
                             debug=False,
                             executeFn=None):
        inferredToken=ReteToken(inferredTriple)
        self.proofTracers.setdefault(inferredTriple,[]).append(binding)
        self.justifications.setdefault(inferredTriple,set()).add(termNode)
        if termNode.filter and inferredTriple not in self.filteredFacts:
            self.filteredFacts.add(inferredTriple)
        if inferredTriple not in self.inferredFacts and inferredToken not in self.workingMemory:
            if debug:
                lit = BuildUnitermFromTuple(inferredTriple,
                    newNss=self.nsMap)
                print "Inferred triple: ", lit, " from ",termNode.clauseRepresentation()
                inferredToken.debug = True
            if executeFn:
                #The indicated execute action is supposed to be triggered
                #when the indicates RHS triple is inferred for the
                #first time
                executeFn(termNode,inferredTriple,tokens,binding,debug)
            if self.goal is not None and self.goal == inferredTriple:#in self.inferredFacts:
                for binding in tokens.bindings:
                    rt=None#self.bfp.extractProof(binding,termNode.ruleNo,inferredTriple,applyBindings=True)
                    def depth(l):
                        assert isinstance(l,(tuple))
                        if isinstance(l,tuple):
                            depths = [depth(item) for item in l[2]]
                            return 1 + max(depths) if depths else 1
                            #self.bfp.proof = -1,rt#depth(rt),rt
                if debug:
                    "Proved goal " + repr(self.goal)
                raise InferredGoal("Proved goal " + repr(self.goal))
            self.inferredFacts.add(inferredTriple)
            self.addWME(inferredToken)
            currIdx = self.instanciations.get(termNode,0)
            currIdx+=1
            self.instanciations[termNode] = currIdx

        else:
            if debug:
                lit = BuildUnitermFromTuple(inferredTriple,
                    newNss=self.nsMap)
                print "Inferred triple skipped: ", lit
            if executeFn:
                #The indicated execute action is supposed to be triggered
                #when the indicates RHS triple is inferred for the
                #first time
                executeFn(termNode,inferredTriple,tokens,binding,debug)
Пример #4
0
    def fireConsequent(self,tokens,termNode,debug=False):
        """

        "In general, a p-node also contains a specifcation of what production it corresponds to | the
        name of the production, its right-hand-side actions, etc. A p-node may also contain information
        about the names of the variables that occur in the production. Note that variable names
        are not mentioned in any of the Rete node data structures we describe in this chapter. This is
        intentional |it enables nodes to be shared when two productions have conditions with the same
        basic form, but with different variable names."


        Takes a set of tokens and the terminal Beta node they came from
        and fires the inferred statements using the patterns associated
        with the terminal node.  Statements that have been previously inferred
        or already exist in the working memory are not asserted
        """
        if debug:
            print "%s from %s"%(tokens,termNode)

        # newTokens = []
        termNode.instanciatingTokens.add(tokens)
        def iterCondition(condition):
            if isinstance(condition,Exists):
                return condition.formula
            return isinstance(condition,SetOperator) and condition or iter([condition])
        def extractVariables(term,existential=True):
            if isinstance(term,existential and BNode or Variable):
                yield term
            elif isinstance(term,Uniterm):
                for t in term.toRDFTuple():
                    if isinstance(t,existential and BNode or Variable):
                        yield t

        #replace existentials in the head with new BNodes!
        BNodeReplacement = {}
        for rule in termNode.rules:
            if isinstance(rule.formula.head,Exists):
                for bN in rule.formula.head.declare:
                    if not isinstance(rule.formula.body,Exists) or \
                       bN not in rule.formula.body.declare:
                       BNodeReplacement[bN] = BNode()
        for rhsTriple in termNode.consequent:
            if BNodeReplacement:
                rhsTriple = tuple([BNodeReplacement.get(term,term) for term in rhsTriple])
            if debug:
                if not tokens.bindings:
                    tokens._generateBindings()
            key = tuple(map(lambda item: None if isinstance(item,BNode) else item,rhsTriple))
            override,executeFn = termNode.executeActions.get(key,(None,None))

            if override:
                #There is an execute action associated with this production
                #that is attaced to the given consequent triple and
                #is meant to perform all of the production duties
                #(bypassing the inference of triples, etc.)
                executeFn(termNode,None,tokens,None,debug)
            else:
                for inferredTriple,binding in _mulPatternWithSubstitutions(tokens,rhsTriple,termNode):
                    if [term for term in inferredTriple if isinstance(term,Variable)]:
                        #Unfullfilled bindings (skip non-ground head literals)
                        if executeFn:
                            #The indicated execute action is supposed to be triggered
                            #when the indicates RHS triple is inferred for the
                            #(even if it is not ground)
                            executeFn(termNode,inferredTriple,tokens,binding,debug)
                        continue
                    # if rhsTriple[1].find('subClassOf_derived')+1:import pdb;pdb.set_trace()
                    inferredToken=ReteToken(inferredTriple)
                    self.proofTracers.setdefault(inferredTriple,[]).append(binding)
                    self.justifications.setdefault(inferredTriple,set()).add(termNode)
                    if termNode.filter and inferredTriple not in self.filteredFacts:
                        self.filteredFacts.add(inferredTriple)
                    if inferredTriple not in self.inferredFacts and inferredToken not in self.workingMemory:
                        # if (rhsTriple == (Variable('A'), RDFS.RDFSNS['subClassOf_derived'], Variable('B'))):
                        #     import pdb;pdb.set_trace()
                        if debug:
                            print "Inferred triple: ", inferredTriple, " from ",termNode.clauseRepresentation()
                            inferredToken.debug = True
                        self.inferredFacts.add(inferredTriple)
                        self.addWME(inferredToken)
                        currIdx = self.instantiations.get(termNode,0)
                        currIdx+=1
                        self.instantiations[termNode] = currIdx
                        if executeFn:
                            #The indicated execute action is supposed to be triggered
                            #when the indicates RHS triple is inferred for the
                            #first time
                            executeFn(termNode,inferredTriple,tokens,binding,debug)
                        if self.goal is not None and self.goal in self.inferredFacts:
                            raise InferredGoal("Proved goal " + repr(self.goal))
                    else:
                        if debug:
                            print "Inferred triple skipped: ", inferredTriple
                        if executeFn:
                            #The indicated execute action is supposed to be triggered
                            #when the indicates RHS triple is inferred for the
                            #first time
                            executeFn(termNode,inferredTriple,tokens,binding,debug)