Exemplo n.º 1
0
def greedy_some(compiler, cont, item, template=None, result=None):
  if result is None:
    return greedy_some1(item).cps(compiler, cont)  
  else:
    _result  = compiler.new_var(Var('result'))
    return begin(greedy_some2(item, template, _result), 
                     unify(result, _result)).cps(compiler, cont)  
Exemplo n.º 2
0
def lazy_any(compiler, cont, item, template=None, result=None):
    if result is None:
        return lazy_any1(item).cps(compiler, cont)
    else:
        _result = compiler.new_var(Var('result'))
        return begin(lazy_any2(item, template, _result),
                     unify(result, _result)).cps(compiler, cont)
Exemplo n.º 3
0
def lazy_any(compiler, cont, item, template=None, result=None):
  if result is None:
    return lazy_any1(item).cps(compiler, cont)  
  else:
    _result  = compiler.new_var(Var('result'))
    return begin(lazy_any2(item, template, _result), 
                     unify(result, _result)).cps(compiler, cont)  
Exemplo n.º 4
0
    def rightActivate(self, s):
        # AlphaMemory is shared, so this is a bad idea.
#        if self.reachedGoal():
#            # We reached a goal, so this rule should be turned off.
#            print "ALREADY REACHED A GOAL!"
#            return
#
        if s.variables:
            var_bindings = {}
            for var in s.variables:
                newVar = s.context().newSymbol('http://example.com/alphaFilter#var%s' % self.varCounter.next())
                var_bindings[var] = newVar
                newVar.isVariable = True
            try:
                s2 = s.substitution(var_bindings)
            except TypeError:
                raise ValueError(s, type(s))
            s2.variables  = frozenset(var_bindings.values())
        else:
            s2 = s
        for  unWantedBindings, env in unify(s2, self.pattern, vars = self.vars | s2.variables): #
            if s2.variables.intersection(env.asDict().values()):
                print 'we have trouble with %s' % s2.variables.intersection(env.asDict().values())
                # We are in trouble here!
            if fullUnify or not frozenset(unWantedBindings.asDict().values()).difference(self.vars): # bad, but speeds things up
                self.add(TripleWithBinding(s, env))
Exemplo n.º 5
0
def greedy_some(compiler, cont, item, template=None, result=None):
    if result is None:
        return greedy_some1(item).cps(compiler, cont)
    else:
        _result = compiler.new_var(Var('result'))
        return begin(greedy_some2(item, template, _result),
                     unify(result, _result)).cps(compiler, cont)
Exemplo n.º 6
0
def findall(compiler, cont, goal, template=None, bag=None):
  if bag is None: 
    return findall_1(goal).cps(compiler, cont)
  else:
    _bag  = compiler.new_var(Var('bag'))
    return begin(findall_2(goal, template, _bag),unify(bag, _bag)
                 ).cps(compiler, cont)
Exemplo n.º 7
0
    def rightActivate(self, s):
        # Like the original AlphaFilter.rightActivate except that we
        # also handle wildcards.

        # Wildcards /always/ match, but do so without binding
        # pattern variables.

        if s.variables:
            var_bindings = {}
            for var in s.variables:
                newVar = s.context().newSymbol('http://example.com/alphaFilter#var%s' % self.varCounter.next())
                var_bindings[var] = newVar
                newVar.isVariable = True
            try:
                s2 = s.substitution(var_bindings)
            except TypeError:
                raise ValueError(s, type(s))
            s2.variables  = frozenset(var_bindings.values())
        else:
            s2 = s
        for  unWantedBindings, env in unify(s2, self.pattern, vars = self.vars | s2.variables | set(self.goalWildcards.values())): #
            # ONLY FOR WILDCARDS: Filter bindings to wildcards.
            # TODO: Weird bindings here (for compliance)
            # TODO: Excess rdf:types!!
            env = Env(Env(), dict([(item[0], (item[1], Env())) for item in env.asDict().items() if item[1] not in self.goalWildcards.values()]))
            if s2.variables.intersection(env.asDict().values()):
                print 'we have trouble with %s' % s2.variables.intersection(env.asDict().values())
                # We are in trouble here!
            self.add(TripleWithBinding(s, env))
Exemplo n.º 8
0
 def unifySecondary(self, other, env1, env2, vars, universals, existentials,
                    n1Source, n2Source):
     MyStatements = ImmutableSet(self.statements)
     OtherStatements = ImmutableSet(other.statements)
     for x in unify(
             MyStatements, OtherStatements, env1, env2, vars,
             universals | self.universals() | other.universals(),
             existentials | self.existentials() | other.existentials(),
             n1Source, n2Source):
         yield x
Exemplo n.º 9
0
 def unifySecondary(self, other, env1, env2, vars,
                    universals, existentials,
                    n1Source, n2Source):
     MyStatements = ImmutableSet(self.statements)
     OtherStatements = ImmutableSet(other.statements)
     for x in unify(MyStatements, OtherStatements, env1, env2, vars,
                    universals | self.universals() | other.universals(),
                    existentials | self.existentials() | other.existentials(),
                    n1Source, n2Source):
         yield x
Exemplo n.º 10
0
 def unify(self,
           other,
           env1,
           env2,
           vars,
           universals,
           existentials,
           n1Source=32,
           n2Source=32):
     return unify(self, other, env1, env2, vars, universals, existentials,
                  n1Source, n2Source)
Exemplo n.º 11
0
def times(compiler, cont, item, expect_times, template=None, result=None):
    if result is None:
        expect_times1 = compiler.new_var(Const('expect_times'))
        return begin(assign(expect_times1, getvalue(expect_times)),
                     times1(item, expect_times1)).cps(compiler, cont)
    else:
        expect_times1 = compiler.new_var(Const('expect_times'))
        result1 = compiler.new_var(il.ConstLocalVar('result'))
        result2 = compiler.new_var(Var('result'))
        result2_2 = result2.interlang()
        template1 = template.interlang()
        return begin(assign(expect_times1, getvalue(expect_times)),
                     times2(item, expect_times1, template, result2),
                     unify(result, result2)).cps(compiler, cont)
Exemplo n.º 12
0
def times(compiler, cont, item, expect_times, template=None, result=None):
  if result is None:
    expect_times1 = compiler.new_var(Const('expect_times'))
    return begin(assign(expect_times1, getvalue(expect_times)), 
                    times1(item, expect_times1)).cps(compiler, cont)
  else:
    expect_times1 = compiler.new_var(Const('expect_times'))
    result1  = compiler.new_var(il.ConstLocalVar('result'))
    result2  = compiler.new_var(Var('result'))
    result2_2  = result2.interlang()
    template1 = template.interlang()
    return begin(assign(expect_times1, getvalue(expect_times)), 
                 times2(item, expect_times1, template, result2),
                 unify(result, result2)
                 ).cps(compiler, cont)  
 def solve(self, *query_goals):
     for query_goal in query_goals:
         if not term.is_syntactically_valid(
                 query_goal) or not query_goal[0].islower():
             raise LogicProgram.QueryError(
                 f'{str(query_goal)} is syntactically invalid.')
     query_variables = {
         var
         for atom in query_goals for var in term.variables(atom)
     }
     # A list of pairs consisting of:
     # - a list of goals to be solved, and
     # - the substitution to apply to the variables that occur in the query
     #   as determined by the unifications computed so far.
     goals_solution_list = deque([(deque(query_goals),
                                   {var: var
                                    for var in query_variables})])
     while goals_solution_list:
         goals, solution = goals_solution_list.popleft()
         if not goals:
             yield solution
             continue
         reserved_variables = (
             query_variables
             | {var
                for atom in goals for var in term.variables(atom)})
         goal = goals.popleft()
         next_goals_solution_list = deque()
         for clause in self.program:
             variable_renaming = term.fresh_variables(
                 clause.variables, reserved_variables)
             head = term.substitute(clause.head, variable_renaming)
             mgu = term.unify(goal, head)
             if mgu is not None:
                 new_goals = deque(
                     term.substitute(
                         term.substitute(atom, variable_renaming), mgu)
                     for atom in clause.body)
                 new_goals.extend(
                     term.substitute(goal, mgu) for goal in goals)
                 new_solution = {
                     var: term.substitute(solution[var], mgu)
                     for var in solution
                 }
                 next_goals_solution_list.appendleft(
                     (new_goals, new_solution))
         goals_solution_list.extendleft(next_goals_solution_list)
Exemplo n.º 14
0
 def rightActivate(self, s):
     if s.variables:
         var_bindings = {}
         for var in s.variables:
             newVar = s.context().newSymbol("http://example.com/alphaFilter#var%s" % self.varCounter.next())
             var_bindings[var] = newVar
             newVar.isVariable = True
         try:
             s2 = s.substitution(var_bindings)
         except TypeError:
             raise ValueError(s, type(s))
         s2.variables = frozenset(var_bindings.values())
     else:
         s2 = s
     for unWantedBindings, env in unify(s2, self.pattern, vars=self.vars | s2.variables):  #
         if s2.variables.intersection(env.asDict().values()):
             print "we have trouble with %s" % s2.variables.intersection(env.asDict().values())
             # We are in trouble here!
         if fullUnify or not frozenset(unWantedBindings.asDict().values()).difference(
             self.vars
         ):  # bad, but speeds things up
             self.add(TripleWithBinding(s, env))
Exemplo n.º 15
0
 def triplesMatching(self, successor, env, includeMissing=False): # This is fast enough
     retVal = self   # No reason to do additional work here
     assert self.initialized
     builtInMade = []
     if isinstance(self.pattern.predicate(), BuiltIn) and self.pattern.predicate() != self.pattern.predicate().store.sameAs:
         # TODO: log:conclusion, air:conclusion
         if self.pattern.predicate() is self.pattern.context().store.supports:
             # We also need to support the air:supports predicate
             # as well, but that's handled differently, as we need
             # to instantiate another AIR reasoner rather than an
             # N3Logic reasoner.
             subject = self.pattern.substitution(env).subject()
             
             knowledgeBase = self.pattern.context().store.newFormula()
             knowledgeBase.loadFormulaWithSubstitution(subject, env)
             # Think over a new formula, not the old one, so that the output is not modified.
             cwmThink(knowledgeBase)
             knowledgeBase.close()
             node = compilePattern(knowledgeBase._index, self.pattern.object().statements, self.vars, self.context)
             def onSuccess((triples, environment, penalty)):
                 newAssumption = self.pattern.substitution(environment.asDict()).substitution(env)
                 #somebodyPleaseAssertFromBuiltin(self.pattern.predicate(), newAssumption)
                 
                 builtInMade.append(TripleWithBinding(newAssumption, environment))
                 self.supportBuiltin(builtInMade[-1].triple)
             def onFailure():
                 # Do nothing.
                 pass
             prod = ProductionNode(node, onSuccess, onFailure)
         elif self.pattern.predicate() is self.pattern.context().store.owlEntails:
             # We also need to support the air:supports predicate
             # as well, but that's handled differently, as we need
             # to instantiate another AIR reasoner rather than an
             # N3Logic reasoner.
             subject = self.pattern.substitution(env).subject()
             
             knowledgeBase = self.pattern.context().store.newFormula()
             knowledgeBase.loadFormulaWithSubstitution(subject, env)
             # Also load the OWL rules formula.
             owlFormula = self.pattern.context().store.load(OWL_RULES)
             knowledgeBase.loadFormulaWithSubstitution(owlFormula, env)
             # Think over a new formula, not the old one, so that the output is not modified.
             cwmThink(knowledgeBase)
             knowledgeBase.close()
             node = compilePattern(knowledgeBase._index, self.pattern.object().statements, self.vars, self.context)
             def onSuccess((triples, environment, penalty)):
                 newAssumption = self.pattern.substitution(environment.asDict()).substitution(env)
                 #somebodyPleaseAssertFromBuiltin(self.pattern.predicate(), newAssumption)
                 
                 builtInMade.append(TripleWithBinding(newAssumption, environment))
                 self.supportBuiltin(builtInMade[-1].triple)
             def onFailure():
                 # Do nothing.
                 pass
             prod = ProductionNode(node, onSuccess, onFailure)
         elif self.pattern.predicate() is self.pattern.context().store.airJustifies:
             from policyrunner import runPolicy as airThink
             subject = self.pattern.substitution(env).subject()
             # HACK! I don't know what base URI these really are!
             logs = subject[0]
             rules = subject[1]
             if len(subject) == 3:
                 filterProperties = list(subject[2])
             else:
                 filterProperties = ['http://dig.csail.mit.edu/TAMI/2007/amord/air#compliant-with', 'http://dig.csail.mit.edu/TAMI/2007/amord/air#non-compliant-with']
             f, workingContext = airThink([], [], logFormulaObjs=logs, ruleFormulaObjs=rules, filterProperties=filterProperties, store=self.pattern.context().store)
             node = compilePattern(workingContext._index, self.pattern.object().statements, self.vars, self.context)
             def onSuccess((triples, environment, penalty)):
                 newAssumption = self.pattern.substitution(environment.asDict()).substitution(env)
                 #somebodyPleaseAssertFromBuiltin(self.pattern.predicate(), newAssumption)
                 
                 builtInMade.append(TripleWithBinding(newAssumption, environment))
                 self.supportBuiltin(builtInMade[-1].triple)
             def onFailure():
                 # Do nothing.
                 pass
             prod = ProductionNode(node, onSuccess, onFailure)
         elif self.pattern.predicate() is self.pattern.context().store.includes:
             # log:includes references the (Indexed)Formula in the
             # subject and checks it for a pattern match.
             if not isinstance(self.pattern.substitution(env).subject(), Formula):
                 # This match... isn't.
                 if includeMissing:
                     return retVal + [TripleWithBinding(BogusTriple(self.pattern), Env())] + builtInMade
                 return retVal + builtInMade
             newIndex = self.pattern.substitution(env).subject()._index
             node = compilePattern(newIndex, self.pattern.object().statements, self.vars, self.context, ignoreBuiltins=True)
             def onSuccess((triples, environment, penalty)):
                 newAssumption = self.pattern.substitution(environment.asDict()).substitution(env)
                 #somebodyPleaseAssertFromBuiltin(self.pattern.predicate(), newAssumption)
                 
                 builtInMade.append(TripleWithBinding(newAssumption, environment))
                 self.supportBuiltin(builtInMade[-1].triple)
             def onFailure():
                 # Do nothing.
                 pass
             prod = ProductionNode(node, onSuccess, onFailure)
         elif self.pattern.predicate() is self.pattern.context().store.notIncludes:
             # log:notIncludes references the (Indexed)Formula in the
             # subject and checks it for a pattern match.
             newIndex = self.pattern.substitution(env).subject()._index
             node = compilePattern(newIndex, self.pattern.object().statements, self.vars, ignoreBuiltins=True)
             def onSuccess((triples, environment, penalty)):
                 # Do nothing.
                 pass
             def onFailure():
                 newAssumption = self.pattern.substitution(env.asDict()).substitution(env)
                 #somebodyPleaseAssertFromBuiltin(self.pattern.predicate(), newAssumption)
                 
                 builtInMade.append(TripleWithBinding(newAssumption, env))
                 self.supportBuiltin(builtInMade[-1].triple)
             prod = ProductionNode(node, onSuccess, onFailure)
         # Alright, if we are ACTING as a function, we need to bind
         # the object.
         elif self.pattern.predicateActsAs(self.pattern.freeVariables(),
                                           set(env.keys())) == Function:
             matchedPat = self.pattern.substitution(env)
             # Need to listify anything that is a term that
             # resolves to a list for list builtins to work (since
             # they don't execute with context)
             if isinstance(self.pattern.predicate(), ListBuiltIn) and isNonEmptyListTerm(matchedPat.subject(), self.context):
                 subject = listify(matchedPat.subject(), self.context)
             else:
                 subject = matchedPat.subject()
             object = self.pattern.predicate().evalObj(subject, None, None, None, None)
             if object is not None:
                 for binds, environment in unify(self.pattern.object(), object, vars = self.vars):
                     builtInMade.append(TripleWithBinding(matchedPat.substitution(binds), environment.flatten(binds)))
                     self.supportBuiltin(builtInMade[-1].triple)
         elif self.pattern.predicateActsAs(self.pattern.freeVariables(),
                                           set(env.keys())) == MultipleFunction:
             # Each item of the possible objects needs to be
             # returned as a separate triple matching.
             matchedPat = self.pattern.substitution(env)
             if isinstance(self.pattern.predicate(), ListBuiltIn) and isNonEmptyListTerm(matchedPat.subject(), self.context):
                 subject = listify(matchedPat.subject(), self.context)
             else:
                 subject = matchedPat.subject()
             for object in self.pattern.predicate().evalObj(subject, None, None, None, None):
                 for binds, environment in unify(self.pattern.object(), object, vars = self.vars):
                     builtInMade.append(TripleWithBinding(matchedPat.substitution(binds), environment.flatten(binds)))
                     self.supportBuiltin(builtInMade[-1].triple)
         elif self.pattern.predicateActsAs(self.pattern.freeVariables(),
                                           set(env.keys())) == ReverseFunction:
             # If we're acting as a ReverseFunction, bind the
             # result of the reverse function to the subject.
             matchedPat = self.pattern.substitution(env)
             if isinstance(self.pattern.predicate(), ListBuiltIn) and isNonEmptyListTerm(matchedPat.object(), self.context):
                 object = listify(matchedPat.object(), self.context)
             else:
                 object = matchedPat.object()
             subject = self.pattern.predicate().evalSubj(object, None, None, None, None)
             if subject is not None:
                 for binds, environment in unify(self.pattern.subject(), subject, vars = self.vars):
                     builtInMade.append(TripleWithBinding(matchedPat.substitution(binds), environment.flatten(binds)))
                     self.supportBuiltin(builtInMade[-1].triple)
         elif self.pattern.predicateActsAs(self.pattern.freeVariables(),
                                           set(env.keys())) == MultipleReverseFunction:
             # Each item of the possible subjects needs to be
             # returned as a separate triple matching.
             matchedPat = self.pattern.substitution(env)
             if isinstance(self.pattern.predicate(), ListBuiltIn) and isNonEmptyListTerm(matchedPat.object(), self.context):
                 object = listify(matchedPat.object(), self.context)
             else:
                 object = matchedPat.object()
             for subject in self.pattern.predicate().evalSubj(object, None, None, None, None):
                 for binds, environment in unify(self.pattern.subject(), subject, vars = self.vars):
                     builtInMade.append(TripleWithBinding(matchedPat.substitution(binds), environment.flatten(binds)))
                     self.supportBuiltin(builtInMade[-1].triple)
         elif self.pattern.predicateActsAs(self.pattern.freeVariables(),
                                           set(env.keys())) == BuiltIn:
             # If we're acting as a ReverseFunction, bind the
             # result of the reverse function to the subject.
             matchedPat = self.pattern.substitution(env)
             if isinstance(self.pattern.predicate(), ListBuiltIn) and isNonEmptyListTerm(matchedPat.subject(), self.context):
                 subject = listify(matchedPat.subject(), self.context)
             else:
                 subject = matchedPat.subject()
             if isinstance(self.pattern.predicate(), ListBuiltIn) and isNonEmptyListTerm(matchedPat.object(), self.context):
                 object = listify(matchedPat.object(), self.context)
             else:
                 object = matchedPat.object()
             if matchedPat.predicate().eval(subject, object,
                                            None, None, None, None):
                 builtInMade.append(TripleWithBinding(matchedPat, env))
                 self.supportBuiltin(builtInMade[-1].triple)
     if includeMissing:
         return retVal + [TripleWithBinding(BogusTriple(self.pattern), Env())] + builtInMade
     return retVal + builtInMade
Exemplo n.º 16
0
 def unify(self, other, env1, env2, vars,
                    universals, existentials,
                    n1Source=32, n2Source=32):
     return unify(self, other, env1, env2, vars,
                    universals, existentials,
                    n1Source, n2Source)
Exemplo n.º 17
0
    def triplesMatching(self, successor, env, includeMissing=False):  # This is fast enough
        retVal = self  # No reason to do additional work here
        assert self.initialized
        builtInMade = []
        if (
            isinstance(self.pattern.predicate(), BuiltIn)
            and self.pattern.predicate() != self.pattern.predicate().store.sameAs
        ):
            if self.pattern.predicate() is self.pattern.context().store.includes:
                # log:includes references the (Indexed)Formula in the
                # subject and checks it for a pattern match.
                newIndex = self.pattern.substitution(env).subject()._index
                node = compilePattern(newIndex, self.pattern.object().statements, self.vars)

                def onSuccess((triples, environment, penalty)):
                    newAssumption = self.pattern.substitution(environment.asDict())
                    # somebodyPleaseAssertFromBuiltin(self.pattern.predicate(), newAssumption)

                    builtInMade.append(TripleWithBinding(newAssumption, environment))
                    self.supportBuiltin(builtInMade[-1].triple)

                def onFailure():
                    # Do nothing.
                    pass

                prod = ProductionNode(node, onSuccess, onFailure)
            elif self.pattern.predicate() is self.pattern.context().store.notIncludes:
                # log:notIncludes references the (Indexed)Formula in the
                # subject and checks it for a pattern match.
                newIndex = self.pattern.substitution(env).subject()._index
                node = compilePattern(newIndex, self.pattern.object().statements, self.vars)

                def onSuccess((triples, environment, penalty)):
                    # Do nothing.
                    pass

                def onFailure():
                    newAssumption = self.pattern.substitution(env.asDict())
                    # somebodyPleaseAssertFromBuiltin(self.pattern.predicate(), newAssumption)

                    builtInMade.append(TripleWithBinding(newAssumption, env))
                    self.supportBuiltin(builtInMade[-1].triple)

                prod = ProductionNode(node, onSuccess, onFailure)
            # Alright, if we are ACTING as a function, we need to bind
            # the object.
            elif self.pattern.predicateActsAs(self.pattern.freeVariables(), set(env.keys())) == Function:
                matchedPat = self.pattern.substitution(env)
                object = self.pattern.predicate().evalObj(matchedPat.subject(), None, None, None, None)
                if object is not None:
                    for binds, environment in unify(self.pattern.object(), object, vars=self.vars):
                        builtInMade.append(
                            TripleWithBinding(matchedPat.substitution(binds), environment.flatten(binds))
                        )
                        self.supportBuiltin(builtInMade[-1].triple)
            elif self.pattern.predicateActsAs(self.pattern.freeVariables(), set(env.keys())) == MultipleFunction:
                # Each item of the possible objects needs to be
                # returned as a separate triple matching.
                matchedPat = self.pattern.substitution(env)
                for object in self.pattern.predicate().evalObj(matchedPat.subject(), None, None, None, None):
                    for binds, environment in unify(self.pattern.object(), object, vars=self.vars):
                        builtInMade.append(
                            TripleWithBinding(matchedPat.substitution(binds), environment.flatten(binds))
                        )
                        self.supportBuiltin(builtInMade[-1].triple)
            elif self.pattern.predicateActsAs(self.pattern.freeVariables(), set(env.keys())) == ReverseFunction:
                # If we're acting as a ReverseFunction, bind the
                # result of the reverse function to the subject.
                matchedPat = self.pattern.substitution(env)
                subject = self.pattern.predicate().evalSubj(matchedPat.object(), None, None, None, None)
                if subject is not None:
                    for binds, environment in unify(self.pattern.subject(), subject, vars=self.vars):
                        builtInMade.append(
                            TripleWithBinding(matchedPat.substitution(binds), environment.flatten(binds))
                        )
                        self.supportBuiltin(builtInMade[-1].triple)
            elif self.pattern.predicateActsAs(self.pattern.freeVariables(), set(env.keys())) == MultipleReverseFunction:
                # Each item of the possible subjects needs to be
                # returned as a separate triple matching.
                matchedPat = self.pattern.substitution(env)
                for subject in self.pattern.predicate().evalSubj(matchedPat.object(), None, None, None, None):
                    for binds, environment in unify(self.pattern.subject(), subject, vars=self.vars):
                        builtInMade.append(
                            TripleWithBinding(matchedPat.substitution(binds), environment.flatten(binds))
                        )
                        self.supportBuiltin(builtInMade[-1].triple)
            elif self.pattern.predicateActsAs(self.pattern.freeVariables(), set(env.keys())) == BuiltIn:
                # If we're acting as a ReverseFunction, bind the
                # result of the reverse function to the subject.
                matchedPat = self.pattern.substitution(env)
                if matchedPat.predicate().eval(matchedPat.subject(), matchedPat.object(), None, None, None, None):
                    builtInMade.append(TripleWithBinding(matchedPat, env))
                    self.supportBuiltin(builtInMade[-1].triple)
        if includeMissing:
            return retVal + [TripleWithBinding(BogusTriple(self.pattern), Env())] + builtInMade
        return retVal + builtInMade