コード例 #1
0
ファイル: CondensationIsolator.py プロジェクト: hobson/ggpy
 def applyCondensation(cls, condensationSet, rule, sentenceNameSource):
     """ generated source for method applyCondensation """
     varsInCondensationSet = HashSet()
     for literal in condensationSet:
         varsInCondensationSet.addAll(GdlUtils.getVariables(literal))
     varsToKeep = HashSet()
     for literal in condensationSet:
         varsToKeep.addAll(GdlUtils.getVariables(literal))
     varsToKeep2 = HashSet()
     varsToKeep2.addAll(GdlUtils.getVariables(rule.getHead()))
     for literal in rule.getBody():
         if not condensationSet.contains(literal):
             varsToKeep2.addAll(GdlUtils.getVariables(literal))
     varsToKeep.retainAll(varsToKeep2)
     orderedVars = ArrayList(varsToKeep)
     condenserName = sentenceNameSource.getNameWithPrefix(rule.getHead().__name__)
     condenserHead = GdlSentence()
     if orderedVars.isEmpty():
         condenserHead = GdlPool.getProposition(condenserName)
     else:
         condenserHead = GdlPool.getRelation(condenserName, orderedVars)
     condenserBody = ArrayList(condensationSet)
     condenserRule = GdlPool.getRule(condenserHead, condenserBody)
     remainingLiterals = ArrayList()
     for literal in rule.getBody():
         if not condensationSet.contains(literal):
             remainingLiterals.add(literal)
     remainingLiterals.add(condenserHead)
     modifiedRule = GdlPool.getRule(rule.getHead(), remainingLiterals)
     newRules = ArrayList(2)
     newRules.add(condenserRule)
     newRules.add(modifiedRule)
     return newRules
コード例 #2
0
 def getVarsInLiveConjuncts(cls, rule, constantSentenceForms):
     """ generated source for method getVarsInLiveConjuncts """
     result = HashSet()
     for literal in rule.getBody():
         if isinstance(literal, (GdlRelation, )):
             if not SentenceModelUtils.inSentenceFormGroup(literal, constantSentenceForms):
                 result.addAll(GdlUtils.getVariables(literal))
         elif isinstance(literal, (GdlNot, )):
             if not SentenceModelUtils.inSentenceFormGroup(inner, constantSentenceForms):
                 result.addAll(GdlUtils.getVariables(literal))
     return result
コード例 #3
0
 def __init___1(self, parent, i):
     """ generated source for method __init___1 """
     super(IterationOrderCandidate, self).__init__()
     # Shared rules:
     self.varsToAssign = parent.varsToAssign
     self.sourceConjunctCandidates = parent.sourceConjunctCandidates
     self.sourceConjunctSizes = parent.sourceConjunctSizes
     self.functionalSentences = parent.functionalSentences
     self.functionalSentencesInfo = parent.functionalSentencesInfo
     self.varDomainSizes = parent.varDomainSizes
     # Individual rules:
     self.sourceConjunctIndices = ArrayList(parent.sourceConjunctIndices)
     self.varOrdering = ArrayList(parent.varOrdering)
     self.functionalConjunctIndices = ArrayList(parent.functionalConjunctIndices)
     self.varSources = ArrayList(parent.varSources)
     # Add the new source conjunct
     self.sourceConjunctIndices.add(i)
     sourceConjunctCandidate = self.sourceConjunctCandidates.get(i)
     varsFromConjunct = GdlUtils.getVariables(sourceConjunctCandidate)
     # Ignore both previously added vars and duplicates
     # Oh, but we need to be careful here, at some point.
     # i.e., what if there are multiple of the same variable
     # in a single statement?
     # That should probably be handled later.
     for var in varsFromConjunct:
         if not self.varOrdering.contains(var):
             self.varOrdering.add(var)
             self.varSources.add(i)
             self.functionalConjunctIndices.add(-1)
コード例 #4
0
 def getBestVariable(self, functionalSentence, functionInfo):
     """ generated source for method getBestVariable """
     # If all the variables that can be set by the functional sentence are in
     # the varOrdering, we return null. Otherwise, we return one of
     # those with the largest domain.
     # The FunctionInfo is sentence-independent, so we need the context
     # of the sentence (which has variables in it).
     tuple_ = GdlUtils.getTupleFromSentence(functionalSentence)
     dependentSlots = functionInfo.getDependentSlots()
     if len(tuple_) != len(dependentSlots):
         raise RuntimeException("Mismatched sentence " + functionalSentence + " and constant form " + functionInfo)
     candidateVars = HashSet()
     i = 0
     while i < len(tuple_):
         if isinstance(term, (GdlVariable, )) and dependentSlots.get(i) and not self.varOrdering.contains(term) and self.varsToAssign.contains(term):
             candidateVars.add(term)
         i += 1
     # Now we look at the domains, trying to find the largest
     bestVar = None
     bestDomainSize = 0
     for var in candidateVars:
         if domainSize > bestDomainSize:
             bestVar = var
             bestDomainSize = domainSize
     return bestVar
コード例 #5
0
ファイル: DistinctAndNotMover.py プロジェクト: hobson/ggpy
 def allVarsInLiteralAlreadySet(cls, literal, setVars):
     """ generated source for method allVarsInLiteralAlreadySet """
     varsInLiteral = GdlUtils.getVariables(literal)
     for varInLiteral in varsInLiteral:
         if not setVars.contains(varInLiteral):
             return False
     return True
コード例 #6
0
 def __init___2(self, parent, functionalSentence, functionalSentenceIndex, functionOutput):
     """ generated source for method __init___2 """
     super(IterationOrderCandidate, self).__init__()
     # Shared rules:
     self.varsToAssign = parent.varsToAssign
     self.sourceConjunctCandidates = parent.sourceConjunctCandidates
     self.sourceConjunctSizes = parent.sourceConjunctSizes
     self.functionalSentences = parent.functionalSentences
     self.functionalSentencesInfo = parent.functionalSentencesInfo
     self.varDomainSizes = parent.varDomainSizes
     # Individual rules:
     self.sourceConjunctIndices = ArrayList(parent.sourceConjunctIndices)
     self.varOrdering = ArrayList(parent.varOrdering)
     self.functionalConjunctIndices = ArrayList(parent.functionalConjunctIndices)
     self.varSources = ArrayList(parent.varSources)
     # And we add the function
     varsInFunction = GdlUtils.getVariables(functionalSentence)
     # First, add the remaining arguments
     for var in varsInFunction:
         if not self.varOrdering.contains(var) and not var == functionOutput and self.varsToAssign.contains(var):
             self.varOrdering.add(var)
             self.functionalConjunctIndices.add(-1)
             self.varSources.add(-1)
     # Then the output
     self.varOrdering.add(functionOutput)
     self.functionalConjunctIndices.add(functionalSentenceIndex)
     self.varSources.add(-1)
コード例 #7
0
ファイル: GameFlow.py プロジェクト: hobson/ggpy
 def getTurnsConjunctsArePossible(self, body):
     """ generated source for method getTurnsConjunctsArePossible """
     # We want to identify the conjuncts that are used by the
     # game flow.
     relevantLiterals = ArrayList()
     for literal in body:
         if isinstance(literal, (GdlSentence, )):
             if SentenceModelUtils.inSentenceFormGroup(sentence, self.formsControlledByFlow):
                 relevantLiterals.add(literal)
         elif isinstance(literal, (GdlNot, )):
             if SentenceModelUtils.inSentenceFormGroup(innerSentence, self.formsControlledByFlow):
                 relevantLiterals.add(literal)
     # If none are related to the game flow, then that's it. It can
     # happen on any turn.
     # if(relevantLiterals.isEmpty())
     # return getCompleteTurnSet();
     turnsPossible = HashSet(getCompleteTurnSet())
     # For each of the relevant literals, we need to see if there are assignments
     # such that
     for literal in relevantLiterals:
         if isinstance(literal, (GdlSentence, )):
             while t < self.getNumTurns():
                 if self.sentencesTrueByTurn.get(t).contains(literal):
                     turns.add(t)
                 else:
                     for s in sentencesTrueByTurn.get(t):
                         # Could be true if there's an assignment
                         if None != GdlUtils.getAssignmentMakingLeftIntoRight(literal, s):
                             turns.add(t)
                             break
                 t += 1
         elif isinstance(literal, (GdlNot, )):
             while t < self.getNumTurns():
                 if not self.sentencesTrueByTurn.get(t).contains(internal):
                     turns.add(t)
                 else:
                     for s in sentencesTrueByTurn.get(t):
                         if None != GdlUtils.getAssignmentMakingLeftIntoRight(internal, s):
                             turns.add(t)
                             break
                 t += 1
         # Accumulate turns
         # Note that all relevant conjuncts must be true, so this
         # is an intersection of when the individual conjuncts
         # could be true.
         turnsPossible.retainAll(turns)
     return turnsPossible
コード例 #8
0
ファイル: VariableConstrainer.py プロジェクト: hobson/ggpy
 def replaceVariablesAndConstants(self, function_):
     """ generated source for method replaceVariablesAndConstants """
     assignment = Maps.newHashMap()
     termsToReplace = Sets.newHashSet()
     GdlVisitors.visitAll(function_, GdlVisitor())
     for var in GdlUtils.getVariables(function_):
         assignment.put(var, getUnusedVariable())
     return CommonTransforms.replaceVariables(function_, assignment)
コード例 #9
0
ファイル: VariableConstrainer.py プロジェクト: hobson/ggpy
 def getReplacementAssignment(self, sentence, varGen):
     """ generated source for method getReplacementAssignment """
     Preconditions.checkArgument(self.applies(sentence))
     assignment = Maps.newHashMap()
     tuple_ = GdlUtils.getTupleFromSentence(sentence)
     for varIndex in replacementsByOriginalTupleIndex.keySet():
         assignment.put(tuple_.get(varIndex), replacementFunction)
     return assignment
コード例 #10
0
ファイル: GameFlow.py プロジェクト: hobson/ggpy
 def addSentenceForms(self, ordering, trueFlowSentences, model, functionInfoMap):
     """ generated source for method addSentenceForms """
     for curForm in ordering:
         # Check against trueFlowSentences, add to trueFlowSentences
         # or check against constantForms if necessary
         # Use basic Assignments class, of course
         for alwaysTrueSentences in model.getSentencesListedAsTrue(curForm):
             trueFlowSentences.add(alwaysTrueSentences)
         for rule in model.getRules(curForm):
             while asnItr.hasNext():
                 if trueFlowSentences.contains(transformedHead):
                     asnItr.changeOneInNext(varsInHead, assignment)
                 # Go through the conjuncts
                 for literal in rule.getBody():
                     if isinstance(literal, (GdlSentence, )):
                         if curForm.matches(literal):
                             raise RuntimeException("Haven't implemented recursion in the game flow")
                         if self.constantForms.contains(conjForm):
                             if not self.constantChecker.isTrueConstant(transformed):
                                 isGoodAssignment = False
                                 asnItr.changeOneInNext(GdlUtils.getVariables(literal), assignment)
                         else:
                             if not trueFlowSentences.contains(transformed):
                                 # False sentence
                                 isGoodAssignment = False
                                 asnItr.changeOneInNext(GdlUtils.getVariables(literal), assignment)
                     elif isinstance(literal, (GdlNot, )):
                         if self.constantForms.contains(conjForm):
                             if self.constantChecker.isTrueConstant(transformed):
                                 isGoodAssignment = False
                                 asnItr.changeOneInNext(GdlUtils.getVariables(literal), assignment)
                         else:
                             if trueFlowSentences.contains(transformed):
                                 # False sentence
                                 isGoodAssignment = False
                                 asnItr.changeOneInNext(GdlUtils.getVariables(literal), assignment)
                     # Nothing else needs attention, really
                 # We've gone through all the conjuncts and are at the
                 # end of the rule
                 if isGoodAssignment:
                     trueFlowSentences.add(transformedHead)
                     if varsInHead.isEmpty():
                         break
                     else:
                         asnItr.changeOneInNext(varsInHead, assignment)
コード例 #11
0
 def getVarDomainInRuleBody(cls, varInHead, rule, newPossibleConstantsByForm, curDomain, model):
     """ generated source for method getVarDomainInRuleBody """
     try:
         for conjunct in getPositiveConjuncts(rule.getBody()):
             if GdlUtils.getVariables(conjunct).contains(varInHead):
                 domains.add(getVarDomainInSentence(varInHead, conjunct, newPossibleConstantsByForm, curDomain, model))
         return getIntersection(domains)
     except RuntimeException as e:
         raise RuntimeException("Error in rule " + rule + " for variable " + varInHead, e)
コード例 #12
0
ファイル: VariableConstrainer.py プロジェクト: hobson/ggpy
 def applies(self, sentence):
     """ generated source for method applies """
     if not self.original.matches(sentence):
         return False
     tuple_ = GdlUtils.getTupleFromSentence(sentence)
     for varIndex in replacementsByOriginalTupleIndex.keySet():
         if not (isinstance(, (GdlVariable, ))):
             return False
     return True
コード例 #13
0
ファイル: CondensationIsolator.py プロジェクト: hobson/ggpy
 def getNewFormDomain(cls, condensingRule, oldModel, newForm):
     """ generated source for method getNewFormDomain """
     varDomains = SentenceDomainModels.getVarDomains(condensingRule, oldModel, VarDomainOpts.BODY_ONLY)
     domainsForSlots = Lists.newArrayList()
     for term in GdlUtils.getTupleFromSentence(condensingRule.getHead()):
         if not (isinstance(term, (GdlVariable, ))):
             raise RuntimeException("Expected all slots in the head of a condensing rule to be variables, but the rule was: " + condensingRule)
         domainsForSlots.add(varDomains.get(term))
     return CartesianSentenceFormDomain.create(newForm, domainsForSlots)
コード例 #14
0
ファイル: DistinctAndNotMover.py プロジェクト: hobson/ggpy
 def reinsertLiteralInRightPlace(cls, ruleBody, literalToReinsert):
     """ generated source for method reinsertLiteralInRightPlace """
     setVars = Sets.newHashSet()
     i = 0
     while i < len(ruleBody):
         if isinstance(literal, (GdlSentence, )):
             setVars.addAll(GdlUtils.getVariables(literal))
             if allVarsInLiteralAlreadySet(literalToReinsert, setVars):
                 ruleBody.add(i + 1, literalToReinsert)
                 return
         i += 1
コード例 #15
0
ファイル: AssignmentsImpl.py プロジェクト: hobson/ggpy
 def getBestIterationOrderCandidate(cls, rule, varDomains, functionInfoMap, completedSentenceFormSizes, preassignment, analyticFunctionOrdering):
     """ generated source for method getBestIterationOrderCandidate """
     # SentenceModel model,
     # Here are the things we need to pass into the first IOC constructor
     sourceConjunctCandidates = ArrayList()
     # What is a source conjunct candidate?
     # - It is a positive conjunct in the rule (i.e. a GdlSentence in the body).
     # - It has already been fully defined; i.e. it is not recursively defined in terms of the current form.
     # Furthermore, we know the number of potentially true tuples in it.
     varsToAssign = GdlUtils.getVariables(rule)
     newVarsToAssign = ArrayList()
     for var in varsToAssign:
         if not newVarsToAssign.contains(var):
             newVarsToAssign.add(var)
     varsToAssign = newVarsToAssign
     if preassignment != None:
         varsToAssign.removeAll(preassignment.keySet())
     # Calculate var domain sizes
     varDomainSizes = getVarDomainSizes(varDomains)# rule, model
     sourceConjunctSizes = ArrayList()
     for conjunct in rule.getBody():
         if isinstance(conjunct, (GdlRelation, )):
             if completedSentenceFormSizes != None and completedSentenceFormSizes.containsKey(form):
                 # New: Don't add if it will be useless as a source
                 # For now, we take a strict definition of that
                 # Compare its size with the product of the domains
                 # of the variables it defines
                 # In the future, we could require a certain ratio
                 # to decide that this is worthwhile
                 for var in vars:
                     maxSize *= domainSize
                 if size >= maxSize:
                     continue 
                 sourceConjunctCandidates.add(relation)
                 sourceConjunctSizes.add(size)
     functionalSentences = ArrayList()
     functionalSentencesInfo = ArrayList()
     for conjunct in rule.getBody():
         if isinstance(conjunct, (GdlSentence, )):
             if functionInfoMap != None and functionInfoMap.containsKey(form):
                 functionalSentences.add(conjunct)
                 functionalSentencesInfo.add(functionInfoMap.get(form))
     # TODO: If we have a head assignment, treat everything as already replaced
     # Maybe just translate the rule? Or should we keep the pool clean?
     emptyCandidate = IterationOrderCandidate(varsToAssign, sourceConjunctCandidates, sourceConjunctSizes, functionalSentences, functionalSentencesInfo, varDomainSizes)
     searchQueue = PriorityQueue()
     searchQueue.add(emptyCandidate)
     while not searchQueue.isEmpty():
         # 			print "Node being checked out: " + curNode;
         if curNode.isComplete():
             # This is the complete ordering with the lowest heuristic value
             return curNode
         searchQueue.addAll(curNode.getChildren(analyticFunctionOrdering))
     raise RuntimeException("Found no complete iteration orderings")
コード例 #16
0
 def applyRuleBodyOnlyPropagation(cls, neededConstantsByForm, curDomains, model):
     """ generated source for method applyRuleBodyOnlyPropagation """
     somethingChanged = False
     for rule in getRules(model.getDescription()):
         for var in ImmutableSet.copyOf(GdlUtils.getVariables(rule)):
             if not varsInHead.contains(var):
                 if neededConstants == None:
                     raise IllegalStateException("var is " + var + ";\nvarDomains key set is " + varDomains.keySet() + ";\nvarsInHead is " + varsInHead + ";\nrule is " + rule)
                 for conjunct in rule.getBody():
                     somethingChanged |= addPossibleValuesToConjunct(neededConstants, conjunct, var, neededConstantsByForm, model)
     return somethingChanged
コード例 #17
0
ファイル: GdlChainingReasoner.py プロジェクト: hobson/ggpy
 def getRuleResults(self, rule, domainModel, sentencesSoFar):
     """ generated source for method getRuleResults """
     ConcurrencyUtils.checkForInterruption()
     headForm = self.model.getSentenceForm(rule.getHead())
     varDomains = SentenceDomainModels.getVarDomains(rule, domainModel, VarDomainOpts.INCLUDE_HEAD)
     functionInfoMap = sentencesSoFar.getFunctionInfo()
     completedSentenceFormValues = sentencesSoFar.getSentences().asMap()
     assignments = AssignmentsImpl(rule, varDomains, functionInfoMap, completedSentenceFormValues)
     asnItr = assignments.getIterator()
     sentencesToAdd = GdlSentenceSet.create()
     while asnItr.hasNext():
         for literal in rule.getBody():
             ConcurrencyUtils.checkForInterruption()
             if not satisfies(assignment, literal, sentencesSoFar.getSentences()):
                 asnItr.changeOneInNext(GdlUtils.getVariables(literal), assignment)
                 allSatisfied = False
                 break
         if allSatisfied:
             sentencesToAdd.put(headForm, CommonTransforms.replaceVariables(head, assignment))
             asnItr.changeOneInNext(GdlUtils.getVariables(head), assignment)
     return sentencesToAdd
コード例 #18
0
 def getVarDomainInSentence(cls, var, conjunct, newPossibleConstantsByForm, curDomain, model):
     """ generated source for method getVarDomainInSentence """
     form = model.getSentenceForm(conjunct)
     tuple_ = GdlUtils.getTupleFromSentence(conjunct)
     domains = Lists.newArrayList()
     i = 0
     while i < len(tuple_):
         if tuple_.get(i) == var:
             domains.add(newPossibleConstantsByForm.get(form).get(i))
             domains.add(curDomain.get(form).get(i))
         i += 1
     return getIntersection(domains)
コード例 #19
0
ファイル: GdlChainingReasoner.py プロジェクト: hobson/ggpy
 def addRuleResultsForChosenLiteral(self, rule, chosenLiteral, chosenNewSentences, domainModel, allSentences, sentencesToAdd):
     """ generated source for method addRuleResultsForChosenLiteral """
     headForm = self.model.getSentenceForm(rule.getHead())
     varDomains = SentenceDomainModels.getVarDomains(rule, domainModel, VarDomainOpts.INCLUDE_HEAD)
     functionInfoMap = allSentences.getFunctionInfo()
     completedSentenceFormValues = allSentences.getSentences().asMap()
     for chosenNewSentence in chosenNewSentences:
         if preassignments != None:
             while asnItr.hasNext():
                 for literal in rule.getBody():
                     if literal == chosenLiteral:
                         # Already satisfied
                         continue 
                     if not self.satisfies(assignment, literal, allSentences.getSentences()):
                         asnItr.changeOneInNext(GdlUtils.getVariables(literal), assignment)
                         allSatisfied = False
                         break
                 if allSatisfied:
                     if not allSentences.containsSentence(headForm, newHead):
                         sentencesToAdd.put(headForm, newHead)
                     asnItr.changeOneInNext(GdlUtils.getVariables(head), assignment)
コード例 #20
0
ファイル: DistinctAndNotMover.py プロジェクト: hobson/ggpy
 def findDistinctOrNotToMoveIndex(cls, ruleBody):
     """ generated source for method findDistinctOrNotToMoveIndex """
     setVars = Sets.newHashSet()
     i = 0
     while i < len(ruleBody):
         if isinstance(literal, (GdlSentence, )):
             setVars.addAll(GdlUtils.getVariables(literal))
         elif isinstance(literal, (GdlDistinct, )) or isinstance(literal, (GdlNot, )):
             if not allVarsInLiteralAlreadySet(literal, setVars):
                 return i
         i += 1
     return None
コード例 #21
0
ファイル: SentenceFormsFinder.py プロジェクト: hobson/ggpy
 def getVarsToModelsMap(self, rule):
     """ generated source for method getVarsToModelsMap """
     varsToUse = Sets.newHashSet(GdlUtils.getVariables(rule.getHead()))
     varsToModelsMap = Maps.newHashMap()
     for var in varsToUse:
         varsToModelsMap.put(var, TermModel())
     for literal in rule.getBody():
         if isinstance(literal, (GdlRelation, )):
             if not self.sentencesModel.containsKey(nameAndArity):
                 self.sentencesModel.put(nameAndArity, getNTermModels(nameAndArity.getArity()))
             addVariablesToMap(literalBody, literalModel, varsToModelsMap)
     return varsToModelsMap
コード例 #22
0
ファイル: CondensationIsolator.py プロジェクト: hobson/ggpy
 def getCondensationSet(cls, rule, model, checker, sentenceNameSource):
     """ generated source for method getCondensationSet """
     varsInRule = GdlUtils.getVariables(rule)
     varsInHead = GdlUtils.getVariables(rule.getHead())
     varsNotInHead = ArrayList(varsInRule)
     varsNotInHead.removeAll(varsInHead)
     for var in varsNotInHead:
         ConcurrencyUtils.checkForInterruption()
         for literal in rule.getBody():
             if GdlUtils.getVariables(literal).contains(var):
                 minSet.add(literal)
         for literal in minSet:
             if isinstance(literal, (GdlRelation, )):
                 varsSupplied.addAll(GdlUtils.getVariables(literal))
             elif isinstance(literal, (GdlDistinct, )) or isinstance(literal, (GdlNot, )):
                 varsNeeded.addAll(GdlUtils.getVariables(literal))
         varsNeeded.removeAll(varsSupplied)
         if not varsNeeded.isEmpty():
             continue 
         for varNeeded in varsNeeded:
             for literal in rule.getBody():
                 if isinstance(literal, (GdlRelation, )):
                     if GdlUtils.getVariables(literal).contains(varNeeded):
                         suppliers.add(literal)
             candidateSuppliersList.add(suppliers)
         for suppliers in candidateSuppliersList:
             if Collections.disjoint(suppliers, literalsToAdd):
                 literalsToAdd.add(suppliers.iterator().next())
         minSet.addAll(literalsToAdd)
         if goodCondensationSetByHeuristic(minSet, rule, model, checker, sentenceNameSource):
             return minSet
     return None
コード例 #23
0
 def addConstantsFromSentenceIfInOldDomain(cls, newConstantsByForm, oldDomain, model, sentence):
     """ generated source for method addConstantsFromSentenceIfInOldDomain """
     form = model.getSentenceForm(sentence)
     tuple_ = GdlUtils.getTupleFromSentence(sentence)
     if len(tuple_) != form.getTupleSize():
         raise IllegalStateException()
     i = 0
     while i < form.getTupleSize():
         ConcurrencyUtils.checkForInterruption()
         if isinstance(term, (GdlConstant, )):
             if oldDomainForTerm.contains(term):
                 newConstantsByForm.get(form).put(i, term)
         i += 1
コード例 #24
0
 def propagatePossibleConstants(cls, newPossibleConstantsByForm, curDomain, model):
     """ generated source for method propagatePossibleConstants """
     # Injection: Go from the intersections of variable values in rules to the
     # values in their heads
     somethingChanged = False
     for rule in getRules(model.getDescription()):
         for varInHead in ImmutableSet.copyOf(GdlUtils.getVariables(rule.getHead())):
             domainsOfHeadVars.put(varInHead, domain)
             somethingChanged |= addPossibleValuesToSentence(domain, head, varInHead, newPossibleConstantsByForm, model)
     # Language-based injections
     somethingChanged |= applyLanguageBasedInjections(GdlPool.INIT, GdlPool.TRUE, newPossibleConstantsByForm)
     somethingChanged |= applyLanguageBasedInjections(GdlPool.NEXT, GdlPool.TRUE, newPossibleConstantsByForm)
     somethingChanged |= applyLanguageBasedInjections(GdlPool.LEGAL, GdlPool.DOES, newPossibleConstantsByForm)
     return somethingChanged
コード例 #25
0
 def addPossibleValuesToSentence(cls, neededAndPossibleConstants, sentence, curVar, neededConstantsByForm, model):
     """ generated source for method addPossibleValuesToSentence """
     ConcurrencyUtils.checkForInterruption()
     somethingChanged = False
     form = model.getSentenceForm(sentence)
     tuple_ = GdlUtils.getTupleFromSentence(sentence)
     Preconditions.checkArgument(form.getTupleSize() == len(tuple_))
     i = 0
     while i < len(tuple_):
         if tuple_.get(i) == curVar:
             Preconditions.checkNotNull(neededConstantsByForm.get(form))
             Preconditions.checkNotNull(neededAndPossibleConstants)
             somethingChanged |= neededConstantsByForm.get(form).putAll(i, neededAndPossibleConstants)
         i += 1
     return somethingChanged
コード例 #26
0
ファイル: FunctionInfoImpl.py プロジェクト: hobson/ggpy
 def getProducibleVars(self, sentence):
     """ generated source for method getProducibleVars """
     if not self.form.matches(sentence):
         raise RuntimeException("Sentence " + sentence + " does not match constant form")
     tuple_ = GdlUtils.getTupleFromSentence(sentence)
     candidateVars = HashSet()
     # Variables that appear multiple times go into multipleVars
     multipleVars = HashSet()
     # ...which, of course, means we have to spot non-candidate vars
     nonCandidateVars = HashSet()
     i = 0
     while i < len(tuple_):
         if isinstance(term, (GdlVariable,)) and not multipleVars.contains(term):
             if candidateVars.contains(var) or nonCandidateVars.contains(var):
                 multipleVars.add(var)
                 candidateVars.remove(var)
             elif self.dependentSlots.get(i):
                 candidateVars.add(var)
             else:
                 nonCandidateVars.add(var)
         i += 1
     return candidateVars
コード例 #27
0
ファイル: AssignmentsImpl.py プロジェクト: hobson/ggpy
 def __init__(self, headAssignment, rule, varDomains, functionInfoMap, completedSentenceFormValues):
     """ generated source for method __init__ """
     super(AssignmentsImpl, self).__init__()
     self.empty = False
     self.headAssignment = headAssignment
     # We first have to find the remaining variables in the body
     self.varsToAssign = GdlUtils.getVariables(rule)
     # Remove all the duplicates; we do, however, want to keep the ordering
     newVarsToAssign = ArrayList()
     for v in varsToAssign:
         if not newVarsToAssign.contains(v):
             newVarsToAssign.add(v)
     self.varsToAssign = newVarsToAssign
     self.varsToAssign.removeAll(headAssignment.keySet())
     # varsToAssign is set at this point
     # We see if iterating over entire tuples will give us a
     # better result, and we look for the best way of doing that.
     # Let's get the domains of the variables
     # Map<GdlVariable, Set<GdlConstant>> varDomains = model.getVarDomains(rule);
     # Since we're looking at a particular rule, we can do this one step better
     # by looking at the domain of the head, which may be more restrictive
     # and taking the intersections of the two domains where applicable
     # Map<GdlVariable, Set<GdlConstant>> headVarDomains = model.getVarDomainsInSentence(rule.getHead());
     # We can run the A* search for a good set of source conjuncts
     # at this point, then use the result to build the rest.
     completedSentenceFormSizes = HashMap()
     if completedSentenceFormValues != None:
         for form in completedSentenceFormValues.keySet():
             completedSentenceFormSizes.put(form, completedSentenceFormValues.get(form).size())
     varDomainSizes = HashMap()
     for var in varDomains.keySet():
         varDomainSizes.put(var, varDomains.get(var).size())
     bestOrdering = IterationOrderCandidate()
     bestOrdering = getBestIterationOrderCandidate(rule, varDomains, functionInfoMap, completedSentenceFormSizes, headAssignment, False)# model,
     # TODO: True here?
     # Want to replace next few things with order
     # Need a few extra things to handle the use of iteration over existing tuples
     self.varsToAssign = bestOrdering.getVariableOrdering()
     # For each of these vars, we have to find one or the other.
     # Let's start by finding all the domains, a task already done.
     self.valuesToIterate = Lists.newArrayListWithCapacity(len(self.varsToAssign))
     for var in varsToAssign:
         if varDomains.containsKey(var):
             if not varDomains.get(var).isEmpty():
                 self.valuesToIterate.add(ImmutableList.copyOf(varDomains.get(var)))
             else:
                 self.valuesToIterate.add(ImmutableList.of(GdlPool.getConstant("0")))
         else:
             self.valuesToIterate.add(ImmutableList.of(GdlPool.getConstant("0")))
     # Okay, the iteration-over-domain is done.
     # Now let's look at sourced iteration.
     self.sourceDefiningSlot = ArrayList(len(self.varsToAssign))
     i = 0
     while i < len(self.varsToAssign):
         self.sourceDefiningSlot.add(-1)
         i += 1
     # We also need to convert values into tuples
     # We should do so while constraining to any constants in the conjunct
     # Let's convert the conjuncts
     sourceConjuncts = bestOrdering.getSourceConjuncts()
     self.tuplesBySource = Lists.newArrayListWithCapacity(len(sourceConjuncts))
     # new ArrayList<List<List<GdlConstant>>>(len(sourceConjuncts));
     self.varsChosenBySource = Lists.newArrayListWithCapacity(len(sourceConjuncts))
     # new ArrayList<List<Integer>>(len(sourceConjuncts));
     self.putDontCheckBySource = Lists.newArrayListWithCapacity(len(sourceConjuncts))
     # new ArrayList<List<Boolean>>(len(sourceConjuncts));
     j = 0
     while j < len(sourceConjuncts):
         # flatten into a tuple
         # Go through the vars/constants in the tuple
         while i < len(conjunctTuple):
             if isinstance(term, (GdlConstant, )):
                 constraintSlots.add(i)
                 constraintValues.add(term)
                 # TODO: What if tuple size ends up being 0?
                 # Need to keep that in mind
             elif isinstance(term, (GdlVariable, )):
                 varsChosen.add(varIndex)
                 if self.sourceDefiningSlot.get(varIndex) == -1:
                     # We define it
                     self.sourceDefiningSlot.set(varIndex, j)
                     putDontCheck.add(True)
                 else:
                     # It's an overlap; we just check for consistency
                     putDontCheck.add(False)
             else:
                 raise RuntimeException("Function returned in tuple")
             i += 1
         self.varsChosenBySource.add(ImmutableList.copyOf(varsChosen))
         self.putDontCheckBySource.add(ImmutableList.copyOf(putDontCheck))
         # Now we put the tuples together
         # We use constraintSlots and constraintValues to check that the
         # tuples have compatible values
         for sentence in sentences:
             # Check that it doesn't conflict with our headAssignment
             if not headAssignment.isEmpty():
                 for var in headAssignment.keySet():
                     if tupleAssignment.containsKey(var) and tupleAssignment.get(var) != headAssignment.get(var):
                         continue 
             while c < len(constraintSlots):
                 if not longTuple.get(slot) == value:
                     continue 
                 c += 1
             while s < len(longTuple):
                 # constraintSlots is sorted in ascending order
                 if c < len(constraintSlots) and constraintSlots.get(c) == s:
                     c += 1
                 else:
                     shortTuple.add(longTuple.get(s))
                 s += 1
             # The tuple fits the source conjunct
             tuples.add(ImmutableList.copyOf(shortTuple))
         # sortTuples(tuples); //Needed? Useful? Not sure. Probably not?
         self.tuplesBySource.add(ImmutableList.copyOf(tuples))
         j += 1
     # We now want to see which we can give assignment functions to
     self.valuesToCompute = ArrayList(len(self.varsToAssign))
     for var in varsToAssign:
         self.valuesToCompute.add(None)
     self.indicesToChangeWhenNull = ArrayList(len(self.varsToAssign))
     i = 0
     while i < len(self.varsToAssign):
         # Change itself, why not?
         # Actually, instead let's try -1, to catch bugs better
         self.indicesToChangeWhenNull.add(-1)
         i += 1
     # Now we have our functions already selected by the ordering
     # bestOrdering.functionalConjunctIndices;
     # Make AssignmentFunctions out of the ordering
     functionalConjuncts = bestOrdering.getFunctionalConjuncts()
     # 		print "functionalConjuncts: " + functionalConjuncts;
     i = 0
     while i < len(functionalConjuncts):
         if functionalConjunct != None:
             # These are the only ones that could be constant functions
             if functionInfoMap != None:
                 functionInfo = functionInfoMap.get(conjForm)
             if functionInfo != None:
                 # Now we need to figure out which variables are involved
                 # and which are suitable as functional outputs.
                 # 1) Which vars are in this conjunct?
                 # 2) Of these vars, which is "rightmost"?
                 # 3) Is it only used once in the relation?
                 if Collections.frequency(varsInSentence, rightmostVar) != 1:
                     continue 
                 # Can't use it
                 # 4) Which slot is it used in in the relation?
                 # 5) Build an AssignmentFunction if appropriate.
                 #    This should be able to translate from values of
                 #    the other variables to the value of the wanted
                 #    variable.
                 # We don't guarantee that this works until we check
                 if not function_.functional():
                     continue 
                 self.valuesToCompute.set(index, function_)
                 remainingVarsInSentence.remove(rightmostVar)
                 self.indicesToChangeWhenNull.set(index, self.varsToAssign.indexOf(nextRightmostVar))
         i += 1
     # We now have the remainingVars also assigned their domains
     # We also cover the distincts here
     # Assume these are just variables and constants
     self.distincts = ArrayList()
     for literal in rule.getBody():
         if isinstance(literal, (GdlDistinct, )):
             self.distincts.add(literal)
     computeVarsToChangePerDistinct()
     # Need to add "distinct" restrictions to head assignment, too...
     checkDistinctsAgainstHead()
コード例 #28
0
ファイル: MutableFunctionInfo.py プロジェクト: hobson/ggpy
 def create_0(cls, form, initialSentences):
     """ generated source for method create_0 """
     functionInfo = MutableFunctionInfo(form)
     for sentence in initialSentences:
         functionInfo.addTuple(GdlUtils.getTupleFromGroundSentence(sentence))
     return functionInfo
コード例 #29
0
ファイル: MutableFunctionInfo.py プロジェクト: hobson/ggpy
 def addSentence(self, sentence):
     """ generated source for method addSentence """
     self.addTuple(GdlUtils.getTupleFromGroundSentence(sentence))
コード例 #30
0
 def getVarsInConjunct(cls, literal):
     """ generated source for method getVarsInConjunct """
     return GdlUtils.getVariables(literal)