def restrictDomainsToUsefulValues(cls, oldModel): """ generated source for method restrictDomainsToUsefulValues """ # Start with everything from the current domain model. neededAndPossibleConstantsByForm = Maps.newHashMap() for form in oldModel.getSentenceForms(): neededAndPossibleConstantsByForm.put(form, HashMultimap.create()) addDomain(neededAndPossibleConstantsByForm.get(form), oldModel.getDomain(form), form) # # * To minimize the contents of the domains, we repeatedly go through two processes to reduce # * the domain: # * # * 1) We remove unneeded constants from the domain. These are constants which (in their # * position) do not contribute to any sentences with a GDL keyword as its name; that # * is, it never matters whether a sentence with that constant in that position is # * true or false. # * 2) We remove impossible constants from the domain. These are constants which cannot # * end up in their position via any rule or sentence in the game description, given # * the current domain. # * # * Constants removed because of one type of pass or the other may cause other constants # * in other sentence forms to become unneeded or impossible, so we make multiple passes # * until everything is stable. # somethingChanged = True while somethingChanged: somethingChanged = removeUnneededConstants(neededAndPossibleConstantsByForm, oldModel) somethingChanged |= removeImpossibleConstants(neededAndPossibleConstantsByForm, oldModel) return toSentenceDomainModel(neededAndPossibleConstantsByForm, oldModel)
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 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 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
def __init__(self, form): """ generated source for method __init__ """ super(MutableFunctionInfo, self).__init__() self.form = form i = 0 while i < form.getTupleSize(): self.dependentSlots.add(True) self.valueMaps.add(Maps.newHashMap()) i += 1
def removeUnneededConstants(cls, curDomains, model): """ generated source for method removeUnneededConstants """ newNeededConstantsByForm = Maps.newHashMap() for form in curDomains.keySet(): newNeededConstantsByForm.put(form, HashMultimap.create()) populateInitialNeededConstants(newNeededConstantsByForm, curDomains, model) somethingChanged = True while somethingChanged: somethingChanged = propagateNeededConstants(newNeededConstantsByForm, curDomains, model) return retainNewDomains(curDomains, newNeededConstantsByForm)
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
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 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 create_0(cls, function_): """ generated source for method create_0 """ name = function_.__name__ arity = function_.arity() tupleSize = 0 functions = Maps.newHashMap() i = 0 while i < arity: if isinstance(term, (GdlFunction, )): functions.put(i, functionForm) tupleSize += functionForm.getTupleSize() else: tupleSize += 1 i += 1 return SimpleSentenceForm(name, arity, ImmutableMap.copyOf(functions), tupleSize)
def create(cls, conjunct, functionInfo, rightmostVar, varOrder, preassignment): """ generated source for method create """ # We have to set up the things mentioned above... internalFunctions = ArrayList() # We can traverse the conjunct for the list of variables/constants... terms = ArrayList() gatherVars(conjunct.getBody(), terms) # Note that we assume here that the var of interest only # appears once in the relation... varIndex = terms.indexOf(rightmostVar) if varIndex == -1: print "conjunct is: " + conjunct print "terms are: " + terms print "righmostVar is: " + rightmostVar terms.remove(rightmostVar) function_ = functionInfo.getValueMap(varIndex) # Set up inputs and such, using terms querySize = len(terms) isInputConstant = ArrayList(len(terms)) queryConstants = Maps.newHashMap() queryInputIndices = ArrayList(len(terms)) i = 0 while i < len(terms): if isinstance(term, (GdlConstant, )): isInputConstant.add(True) queryConstants.put(i, term) queryInputIndices.add(-1) elif isinstance(term, (GdlVariable, )): # Is it in the head assignment? if preassignment.containsKey(term): isInputConstant.add(True) queryConstants.put(i, preassignment.get(term)) queryInputIndices.add(-1) else: isInputConstant.add(False) # queryConstants.add(null); # What value do we put here? # We want to grab some value out of the # input tuple, which uses functional ordering # Index of the relevant variable, by the # assignment's ordering queryInputIndices.add(varOrder.indexOf(term)) i += 1 return AssignmentFunction(ImmutableList.copyOf(internalFunctions), querySize, ImmutableList.copyOf(isInputConstant), ImmutableMap.copyOf(queryConstants), ImmutableList.copyOf(queryInputIndices), ImmutableMap.copyOf(function_))
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 __init__(self): """ generated source for method __init__ """ self.sentences = HashMultimap.create() self.functionInfoMap = Maps.newHashMap()
def combineDomains(cls, varDomainsByVar): """ generated source for method combineDomains """ return ImmutableMap.copyOf(Maps.transformValues(varDomainsByVar.asMap(), Function()))