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
def toSentenceDomainModel(cls, neededAndPossibleConstantsByForm, formModel): """ generated source for method toSentenceDomainModel """ domains = Maps.newHashMap() for form in formModel.getSentenceForms(): ConcurrencyUtils.checkForInterruption() domains.put(form, CartesianSentenceFormDomain.create(form, neededAndPossibleConstantsByForm.get(form))) return ImmutableSentenceDomainModel.create(formModel, domains)
def __init__(self, form, trueSentences): """ generated source for method __init__ """ super(FunctionInfoImpl, self).__init__() self.form = form numSlots = form.getTupleSize() i = 0 while i < numSlots: # We want to establish whether or not this is a constant... for sentence in trueSentences: ConcurrencyUtils.checkForInterruption() tuplePart.addAll(tuple_.subList(0, i)) tuplePart.addAll(tuple_.subList(i + 1, len(tuple_))) if functionMap.containsKey(tuplePart): # We have two tuples with different values in just this slot functional = False break # Otherwise, we record it functionMap.put(ImmutableList.copyOf(tuplePart), tuple_.get(i)) if functional: # Record the function self.dependentSlots.add(True) self.valueMaps.add(functionMap) else: # Forget it self.dependentSlots.add(False) self.valueMaps.add(None) i += 1
def applyLanguageBasedInjections(cls, curName, resultingName, newPossibleConstantsByForm): """ generated source for method applyLanguageBasedInjections """ somethingChanged = False for form in newPossibleConstantsByForm.keySet(): ConcurrencyUtils.checkForInterruption() if form.__name__ == curName: somethingChanged |= resultingFormDomain.putAll(curFormDomain) return somethingChanged
def populateInitialNeededConstants(cls, newNeededConstantsByForm, curDomains, model): """ generated source for method populateInitialNeededConstants """ for form in model.getSentenceForms(): ConcurrencyUtils.checkForInterruption() if cls.ALWAYS_NEEDED_SENTENCE_NAMES.contains(name): newNeededConstantsByForm.get(form).putAll(curDomains.get(form)) for rule in getRules(model.getDescription()): for sentence in getAllSentencesInBody(rule.getBody()): addConstantsFromSentenceIfInOldDomain(newNeededConstantsByForm, curDomains, model, sentence)
def addSentenceToModel(self, sentence, varsToModelsMap): """ generated source for method addSentenceToModel """ ConcurrencyUtils.checkForInterruption() changesMade = False sentenceName = NameAndArity(sentence) if not self.sentencesModel.containsKey(sentenceName): changesMade = True self.sentencesModel.put(sentenceName, getNTermModels(sentence.arity())) changesMade |= addBodyToModel(self.sentencesModel.get(sentenceName), sentence.getBody(), varsToModelsMap) return changesMade
def addSentencesTrueByRules(cls, sentencesByForm, model): """ generated source for method addSentencesTrueByRules """ prover = AimaProver(model.getDescription()) for form in model.getConstantSentenceForms(): for result in prover.askAll(query, ImmutableSet.of()): ConcurrencyUtils.checkForInterruption() # Variables may end up being replaced with functions, which is not # what we want here, so we have to double-check that the form is correct. if form.matches(result): sentencesByForm.put(form, result)
def getRuleResultsForNewSentences(self, rule, domainModel, allSentences, newSentences): """ generated source for method getRuleResultsForNewSentences """ results = GdlSentenceSet.create() for literal in rule.getBody(): ConcurrencyUtils.checkForInterruption() if isinstance(literal, (GdlSentence, )): addRuleResultsForChosenLiteral(rule, literal, newSentences.getSentences().get(literalForm), domainModel, allSentences, results) elif isinstance(literal, (GdlOr, )): raise IllegalArgumentException("Need more implementation work for this to work with ORs here") return results
def applyRuleHeadPropagation(cls, neededConstantsByForm, curDomains, model): """ generated source for method applyRuleHeadPropagation """ somethingChanged = False for rule in getRules(model.getDescription()): while i < len(headTuple): ConcurrencyUtils.checkForInterruption() if isinstance(, (GdlVariable, )): neededAndPossibleConstants.retainAll(varDomains.get(curVar)) for conjunct in rule.getBody(): somethingChanged |= addPossibleValuesToConjunct(neededAndPossibleConstants, conjunct, curVar, neededConstantsByForm, model) i += 1 return somethingChanged
def addFormToCompletedValues_0(cls, form, completedSentenceFormValues, components): """ generated source for method addFormToCompletedValues_0 """ # Kind of inefficient. Could do better by collecting these as we go, # then adding them back into the CSFV map once the sentence forms are complete. # completedSentenceFormValues.put(form, new ArrayList<GdlSentence>()); sentences = ArrayList() for sentence in components.keySet(): ConcurrencyUtils.checkForInterruption() if form.matches(sentence): # The sentence has a node associated with it sentences.add(sentence) completedSentenceFormValues.put(form, sentences)
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
def findAmbiguity(cls, original, replacement): """ generated source for method findAmbiguity """ Preconditions.checkArgument(original.__name__ == replacement.__name__) Preconditions.checkArgument(not original == replacement) ConcurrencyUtils.checkForInterruption() replacementsByOriginalTupleIndex = Maps.newHashMap() # Make the arguments ?v0, ?v1, ?v2, ... so we can find the tuple indices easily originalSentence = original.getSentenceFromTuple(getNumberedTuple(original.getTupleSize())) replacementSentence = replacement.getSentenceFromTuple(getNumberedTuple(replacement.getTupleSize())) success = cls.findAmbiguity(originalSentence.getBody(), replacementSentence.getBody(), replacementsByOriginalTupleIndex) if success: return Optional.of(cls.Ambiguity.create(original, replacementsByOriginalTupleIndex, replacement)) else: return Optional.absent()
def getCartesianDomainsFromModel(self): """ generated source for method getCartesianDomainsFromModel """ results = Maps.newHashMap() for sentenceEntry in sentencesModel.entrySet(): ConcurrencyUtils.checkForInterruption() # We'll end up taking the Cartesian product of the different # types of terms we have available if nameAndArity.getArity() == 0: results.put(form, CartesianSentenceFormDomain.create(form, ImmutableList.of())) else: for terms in Sets.cartesianProduct(sampleTerms): ConcurrencyUtils.checkForInterruption() results.put(form, domain) return results
def applyAmbiguitiesForLiteral(cls, literal, rule, ambiguitiesByOriginalForm, model): """ generated source for method applyAmbiguitiesForLiteral """ ConcurrencyUtils.checkForInterruption() results = Lists.newArrayList(rule) varGen = getVariableGenerator(rule) if isinstance(literal, (GdlSentence, )): for ambiguity in ambiguitiesByOriginalForm.get(form): ConcurrencyUtils.checkForInterruption() if ambiguity.applies(sentence): results.add(newRule) elif isinstance(literal, (GdlNot, )): # Do nothing. Variables must appear in a positive literal in the # rule, and will be handled there. elif isinstance(literal, (GdlOr, )): raise RuntimeException("ORs should have been removed") elif isinstance(literal, (GdlDistinct, )): # Do nothing return results class UnusedVariableGenerator(object): """ generated source for class UnusedVariableGenerator """ 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) def getUnusedVariable(self): """ generated source for method getUnusedVariable """ @classmethod def getVariableGenerator(cls, rule): """ generated source for method getVariableGenerator """ # Not thread-safe return cls.UnusedVariableGenerator() # # * Removes rules with sentences with empty domains. These simply won't have # * sentence forms in the generated sentence model, so this is fairly easy. # * @throws InterruptedException # @classmethod def cleanUpIrrelevantRules(cls, expandedRules): """ generated source for method cleanUpIrrelevantRules """ model = SentenceFormModelFactory.create(expandedRules) return ImmutableList.copyOf(Collections2.filter(expandedRules, Predicate()))
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
def applyInjection(self, oldName, newName): """ generated source for method applyInjection """ ConcurrencyUtils.checkForInterruption() Preconditions.checkArgument(oldName.getArity() == newName.getArity()) changesMade = False if self.sentencesModel.containsKey(oldName): if not self.sentencesModel.containsKey(newName): changesMade = True self.sentencesModel.put(newName, getNTermModels(newName.arity)) if len(oldModel) != len(newModel): raise IllegalStateException() while i < len(oldModel): ConcurrencyUtils.checkForInterruption() changesMade |= newModel.get(i).mergeIn(oldModel.get(i)) i += 1 return changesMade
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
def getTopologicalOrdering(cls, forms, dependencyGraph, usingBase, usingInput): """ generated source for method getTopologicalOrdering """ queue = LinkedList(forms) ordering = ArrayList(len(forms)) alreadyOrdered = HashSet() while not queue.isEmpty(): for dependency in dependencyGraph.get(curForm): if not dependency == curForm and not alreadyOrdered.contains(dependency): readyToAdd = False break if usingBase and (curForm.__name__ == cls.TRUE or curForm.__name__ == cls.NEXT or curForm.__name__ == cls.INIT): if not alreadyOrdered.contains(baseForm): readyToAdd = False if usingInput and (curForm.__name__ == cls.DOES or curForm.__name__ == cls.LEGAL): if not alreadyOrdered.contains(inputForm): readyToAdd = False if readyToAdd: ordering.add(curForm) alreadyOrdered.add(curForm) else: queue.add(curForm) ConcurrencyUtils.checkForInterruption() return ordering
def findAmbiguity_0(cls, originalBody, replacementBody, replacementsByOriginalTupleIndex): """ generated source for method findAmbiguity_0 """ if len(originalBody) != len(replacementBody): return False i = 0 while i < len(originalBody): ConcurrencyUtils.checkForInterruption() if isinstance(replacementTerm, (GdlVariable, )): if not (isinstance(originalTerm, (GdlVariable, ))): return False elif isinstance(replacementTerm, (GdlFunction, )): if isinstance(originalTerm, (GdlVariable, )): replacementsByOriginalTupleIndex.put(varIndex, replacementTerm) elif isinstance(originalTerm, (GdlFunction, )): if originalFunction.__name__ != replacementFunction.__name__: return False if not successSoFar: return False else: raise RuntimeException() else: raise RuntimeException() i += 1 return True
def removeUnreachableBasesAndInputs(cls, pn, basesTrueByInit): """ generated source for method removeUnreachableBasesAndInputs """ reachability = Maps.newHashMap() numTrueInputs = HashMultiset.create() numFalseInputs = HashMultiset.create() toAdd = Stack() legalsToInputs = Maps.newHashMap() for legalProp in Iterables.concat(pn.getLegalPropositions().values()): if inputProp != None: legalsToInputs.put(legalProp, inputProp) for c in pn.getComponents(): ConcurrencyUtils.checkForInterruption() if isinstance(c, (Constant, )): if c.getValue(): toAdd.add(Pair.of(c, cls.Type.TRUE)) else: toAdd.add(Pair.of(c, cls.Type.FALSE)) for p in pn.getInputPropositions().values(): toAdd.add(Pair.of(p, cls.Type.FALSE)) for baseProp in pn.getBasePropositions().values(): if basesTrueByInit.contains(baseProp): toAdd.add(Pair.of(baseProp, cls.Type.TRUE)) else: toAdd.add(Pair.of(baseProp, cls.Type.FALSE)) initProposition = pn.getInitProposition() toAdd.add(Pair.of(initProposition, cls.Type.BOTH)) while not toAdd.isEmpty(): ConcurrencyUtils.checkForInterruption() if oldType == None: oldType = cls.Type.NEITHER if isinstance(curComp, (Proposition, )): typeToAdd = newInputType elif isinstance(curComp, (Transition, )): typeToAdd = newInputType elif isinstance(curComp, (Constant, )): typeToAdd = newInputType elif isinstance(curComp, (Not, )): typeToAdd = newInputType.opposite() elif isinstance(curComp, (And, )): if newInputType.hasTrue: numTrueInputs.add(curComp) if numTrueInputs.count(curComp) == curComp.getInputs().size(): typeToAdd = cls.Type.TRUE if newInputType.hasFalse: typeToAdd = typeToAdd.with_(cls.Type.FALSE) elif isinstance(curComp, (Or, )): if newInputType.hasFalse: numFalseInputs.add(curComp) if numFalseInputs.count(curComp) == curComp.getInputs().size(): typeToAdd = cls.Type.FALSE if newInputType.hasTrue: typeToAdd = typeToAdd.with_(cls.Type.TRUE) else: raise RuntimeException("Unhandled component type " + curComp.__class__) if oldType.includes(typeToAdd): continue reachability.put(curComp, typeToAdd.with_(oldType)) typeToAdd = typeToAdd.minus(oldType) if typeToAdd == cls.Type.NEITHER: raise RuntimeException("Something's messed up here") for output in curComp.getOutputs(): toAdd.add(Pair.of(output, typeToAdd)) if legalsToInputs.containsKey(curComp): if inputProp == None: raise IllegalStateException() toAdd.add(Pair.of(inputProp, typeToAdd)) trueConst = Constant(True) falseConst = Constant(False) pn.addComponent(trueConst) pn.addComponent(falseConst) for entry in reachability.entrySet(): if type_ == cls.Type.TRUE or type_ == cls.Type.FALSE: if isinstance(c, (Constant, )): continue for input in c.getInputs(): input.removeOutput(c) c.removeAllInputs() if type_ == cls.Type.TRUE ^ (isinstance(c, (Not, ))): c.addInput(trueConst) trueConst.addOutput(c) else: c.addInput(falseConst) falseConst.addOutput(c) cls.optimizeAwayTrueAndFalse(pn, trueConst, falseConst)
def addSentenceForm(cls, form, model, components, negations, trueComponent, falseComponent, usingBase, usingInput, recursionForms, temporaryComponents, temporaryNegations, functionInfoMap, constantChecker, completedSentenceFormValues): """ generated source for method addSentenceForm """ alwaysTrueSentences = model.getSentencesListedAsTrue(form) rules = model.getRules(form) for alwaysTrueSentence in alwaysTrueSentences: if alwaysTrueSentence.__name__ == cls.LEGAL or alwaysTrueSentence.__name__ == cls.NEXT or alwaysTrueSentence.__name__ == cls.GOAL: trueComponent.addOutput(prop) prop.addInput(trueComponent) components.put(alwaysTrueSentence, trueComponent) negations.put(alwaysTrueSentence, falseComponent) continue if usingInput and form.__name__ == cls.DOES: for inputSentence in constantChecker.getTrueSentences(inputForm): components.put(doesSentence, prop) return if usingBase and form.__name__ == cls.TRUE: for baseSentence in constantChecker.getTrueSentences(baseForm): components.put(trueSentence, prop) return inputsToOr = HashMap() for rule in rules: varsInLiveConjuncts.addAll(GdlUtils.getVariables(rule.getHead())) while asnItr.hasNext(): if assignment == None: continue ConcurrencyUtils.checkForInterruption() for literal in rule.getBody(): if isinstance(literal, (GdlSentence, )): if constantChecker.isConstantForm(conjunctForm): if not constantChecker.isTrueConstant(transformed): asnItr.changeOneInNext(varsToChange, assignment) componentsToConnect.add(None) continue if conj == None: conj = temporaryComponents.get(transformed) if conj == None and SentenceModelUtils.inSentenceFormGroup(transformed, recursionForms): temporaryComponents.put(transformed, tempProp) conj = tempProp if conj == None or isThisConstant(conj, falseComponent): asnItr.changeOneInNext(varsInConjunct, assignment) componentsToConnect.add(None) continue componentsToConnect.add(conj) elif isinstance(literal, (GdlNot, )): if constantChecker.isConstantForm(conjunctForm): if constantChecker.isTrueConstant(transformed): asnItr.changeOneInNext(varsToChange, assignment) componentsToConnect.add(None) continue if isThisConstant(conj, falseComponent): asnItr.changeOneInNext(varsInConjunct, assignment) componentsToConnect.add(None) continue if conj == None: conj = temporaryNegations.get(transformed) if conj == None and SentenceModelUtils.inSentenceFormGroup(transformed, recursionForms): if positive == None: positive = temporaryComponents.get(transformed) if positive == None: temporaryComponents.put(transformed, tempProp) positive = tempProp not_.addInput(positive) positive.addOutput(not_) temporaryNegations.put(transformed, not_) conj = not_ if conj == None: if positive == None: continue if existingNotOutput != None: componentsToConnect.add(existingNotOutput) negations.put(transformed, existingNotOutput) continue not_.addInput(positive) positive.addOutput(not_) negations.put(transformed, not_) conj = not_ componentsToConnect.add(conj) elif isinstance(literal, (GdlDistinct, )): else: raise RuntimeException("Unwanted GdlLiteral type") if not componentsToConnect.contains(None): andify(componentsToConnect, andComponent, trueComponent) if not isThisConstant(andComponent, falseComponent): if not inputsToOr.containsKey(sentence): inputsToOr.put(sentence, HashSet()) inputsToOr.get(sentence).add(andComponent) if preventDuplicatesFromConstants: asnItr.changeOneInNext(varsInLiveConjuncts, assignment) for entry in inputsToOr.entrySet(): ConcurrencyUtils.checkForInterruption() for input in inputs: if isinstance(input, (Constant, )) or input.getInputs().size() == 0: realInputs.add(input) else: realInputs.add(input.getSingleInput()) input.getSingleInput().removeOutput(input) input.removeAllInputs() cls.orify(realInputs, prop, falseComponent) components.put(sentence, prop) if form.__name__ == cls.TRUE or form.__name__ == cls.DOES: for sentence in model.getDomain(form): ConcurrencyUtils.checkForInterruption() components.put(sentence, prop)
def optimizeAwayTrueAndFalse(cls, components, negations, trueComponent, falseComponent): """ generated source for method optimizeAwayTrueAndFalse """ while hasNonessentialChildren(trueComponent) or hasNonessentialChildren(falseComponent): ConcurrencyUtils.checkForInterruption() optimizeAwayTrue(components, negations, None, trueComponent, falseComponent) optimizeAwayFalse(components, negations, None, trueComponent, falseComponent)
def create_0(cls, description, verbose): """ generated source for method create_0 """ print "Building propnet..." startTime = System.currentTimeMillis() description = GdlCleaner.run(description) description = DeORer.run(description) description = VariableConstrainer.replaceFunctionValuedVariables(description) description = Relationizer.run(description) description = CondensationIsolator.run(description) if verbose: for gdl in description: print gdl # We want to start with a rule graph and follow the rule graph. # Start by finding general information about the game model = SentenceDomainModelFactory.createWithCartesianDomains(description) # Restrict domains to values that could actually come up in rules. # See chinesecheckers4's "count" relation for an example of why this # could be useful. model = SentenceDomainModelOptimizer.restrictDomainsToUsefulValues(model) if verbose: print "Setting constants..." constantChecker = ConstantCheckerFactory.createWithForwardChaining(model) if verbose: print "Done setting constants" sentenceFormNames = SentenceForms.getNames(model.getSentenceForms()) usingBase = sentenceFormNames.contains("base") usingInput = sentenceFormNames.contains("input") # For now, we're going to build this to work on those with a # particular restriction on the dependency graph: # Recursive loops may only contain one sentence form. # This describes most games, but not all legal games. dependencyGraph = model.getDependencyGraph() if verbose: print "Computing topological ordering... ", System.out.flush() ConcurrencyUtils.checkForInterruption() topologicalOrdering = getTopologicalOrdering(model.getSentenceForms(), dependencyGraph, usingBase, usingInput) if verbose: print "done" roles = Role.computeRoles(description) components = HashMap() negations = HashMap() trueComponent = Constant(True) falseComponent = Constant(False) functionInfoMap = HashMap() completedSentenceFormValues = HashMap() for form in topologicalOrdering: ConcurrencyUtils.checkForInterruption() if verbose: print "Adding sentence form " + form, System.out.flush() if constantChecker.isConstantForm(form): if verbose: print " (constant)" # Only add it if it's important if form.__name__ == cls.LEGAL or form.__name__ == cls.GOAL or form.__name__ == cls.INIT: # Add it for trueSentence in constantChecker.getTrueSentences(form): trueProp.addInput(trueComponent) trueComponent.addOutput(trueProp) components.put(trueSentence, trueComponent) if verbose: print "Checking whether " + form + " is a functional constant..." addConstantsToFunctionInfo(form, constantChecker, functionInfoMap) addFormToCompletedValues(form, completedSentenceFormValues, constantChecker) continue if verbose: print # TODO: Adjust "recursive forms" appropriately # Add a temporary sentence form thingy? ... addSentenceForm(form, model, components, negations, trueComponent, falseComponent, usingBase, usingInput, Collections.singleton(form), temporaryComponents, temporaryNegations, functionInfoMap, constantChecker, completedSentenceFormValues) # TODO: Pass these over groups of multiple sentence forms if verbose and not temporaryComponents.isEmpty(): print "Processing temporary components..." processTemporaryComponents(temporaryComponents, temporaryNegations, components, negations, trueComponent, falseComponent) addFormToCompletedValues(form, completedSentenceFormValues, components) # if(verbose) # TODO: Add this, but with the correct total number of components (not just Propositions) # print " "+completedSentenceFormValues.get(form).size() + " components added"; # Connect "next" to "true" if verbose: print "Adding transitions..." addTransitions(components) # Set up "init" proposition if verbose: print "Setting up 'init' proposition..." setUpInit(components, trueComponent, falseComponent) # Now we can safely... removeUselessBasePropositions(components, negations, trueComponent, falseComponent) if verbose: print "Creating component set..." componentSet = HashSet(components.values()) # Try saving some memory here... components = None negations = None completeComponentSet(componentSet) ConcurrencyUtils.checkForInterruption() if verbose: print "Initializing propnet object..." # Make it look the same as the PropNetFactory results, until we decide # how we want it to look normalizePropositions(componentSet) propnet = PropNet(roles, componentSet) if verbose: print "Done setting up propnet; took " + (System.currentTimeMillis() - startTime) + "ms, has " + len(componentSet) + " components and " + propnet.getNumLinks() + " links" print "Propnet has " + propnet.getNumAnds() + " ands; " + propnet.getNumOrs() + " ors; " + propnet.getNumNots() + " nots" # print propnet; return propnet
def run(cls, description): """ generated source for method run """ # This class is not put together in any "optimal" way, so it's left in # an unpolished state for now. A better version would use estimates of # the impact of breaking apart rules. (It also needs to stop itself from # making multiple new relations with the same meaning.) # This version will be rather advanced. # In particular, it will try to incorporate # 1) More thorough scanning for condensations; # 2) Condensations that are only safe to perform because of mutexes. # TODO: Don't perform condensations on stuff like (add _ _ _)... # In general, don't perform condensations where the headroom is huge? # Better yet... DON'T perform condensations on recursive functions! # As for headroom... maybe make sure that # of vars eliminated > # "kept" # Or make sure none are kept? Use directional connected components? description = GdlCleaner.run(description) description = DeORer.run(description) description = VariableConstrainer.replaceFunctionValuedVariables(description) # How do we define a condensation, and what needs to be true in it? # Definition: A condensation set is a set of conjuncts of a # sentence. # Restrictions: # 1) There must be some variable not in the head of the sentence that # appears exclusively in the condensation set. (This means we can # easily find sets one of which must be a condensation set.) # 2) For any variable appearing in a distinct or not conjunct in the set, # there must be a positive conjunct in the set also containing that # variable. This does apply to variables found in the head. # 3) There must be at least one non-distinct literal outside the # condensation set. # How mutexes work: # Say we have a rule # (<= (r1 ?b) # (r2 ?a ?b ?c) # (r3 ?b ?c) # (r4 ?a) # (r5 ?c)) # If we wanted to factor out ?a, we'd normally have to do # (<= (r6 ?b ?c) # * (r2 ?a ?b ?c) # * (r4 ?a)) # * (<= (r1 ?b) # * (r6 ?b ?c) # * (r3 ?b ?c) # * (r5 ?c)) # * But if we know r2 is a mutex, instead we can do (notice r2 splitting): # * (<= (r6 ?b) # * (r2 ?a ?b ?c) # * (r4 ?a)) # * (<= (r1 ?b) # * (r2 ?a ?b ?c) # * (r6 ?b) # * (r3 ?b ?c) # * (r5 ?c)) # * Which in turn becomes: # * (<= (r6 ?b) # * (r2 ?a ?b ?c) # * (r4 ?a)) # * (<= (r7 ?b) # * (r2 ?a ?b ?c) # * (r3 ?b ?c) # * (r5 ?c)) # * (<= (r1 ?b) # * (r6 ?b) # * (r7 ?b)) # * Both r6 and r7 can be further condensed to ignore ?c and ?a, # * respectively. What just happened? # * 1) The condensation set for ?a included the mutex r2. # * 2) r2 (by itself) would have required ?c to be included as an # * argument passed back to the original rule, which is undesirable. # * Instead, as it's a mutex, we leave a copy in the original rule # * and don't include the ?c. # * # * So, what kind of algorithm can we find to solve this task? # newDescription = ArrayList() rulesToAdd = LinkedList() for gdl in description: if isinstance(gdl, (GdlRule, )): rulesToAdd.add(gdl) else: newDescription.add(gdl) # Don't use the model indiscriminately; it reflects the old description, # not necessarily the new one model = SentenceDomainModelFactory.createWithCartesianDomains(description) model = SentenceDomainModelOptimizer.restrictDomainsToUsefulValues(model) sentenceNameSource = UnusedSentenceNameSource.create(model) constantChecker = ConstantCheckerFactory.createWithForwardChaining(model) constantForms = model.getConstantSentenceForms() ConcurrencyUtils.checkForInterruption() curDescription = Lists.newArrayList(description) while not rulesToAdd.isEmpty(): if isRecursive(curRule): # Don't mess with it! newDescription.add(curRule) continue if SentenceModelUtils.inSentenceFormGroup(curRuleHead, constantForms): newDescription.add(curRule) continue ConcurrencyUtils.checkForInterruption() if condensationSet != None: rulesToAdd.addAll(newRules) # Since we're making only small changes, we can readjust # the model as we go, instead of recomputing it replacementDescription.removeAll(oldRules) replacementDescription.addAll(newRules) curDescription = replacementDescription model = augmentModelWithNewForm(model, newRules) else: newDescription.add(curRule) return newDescription
def addTrueSentencesToModel(self): """ generated source for method addTrueSentencesToModel """ for gdl in description: ConcurrencyUtils.checkForInterruption() if isinstance(gdl, (GdlSentence, )): addSentenceToModel(gdl, ImmutableMap.of())