def updateDomains(self): """ generated source for method updateDomains """ changedSomething = True while changedSomething: changedSomething = False for d in domains.values(): for intSet in d.functionRefs: for d2 in intSet: if d2 != None: if domain == None: domain = HashSet(d2.values) else: domain.retainAll(d2.values) if domain != None: d.values.addAll(domain) if d.loc != None: if name == "does": newLoc.name = GdlPool.getConstant("legal") newLoc.idx = d.loc.idx if otherDom == None: raise RuntimeException("Uh oh, missed a legal") d.values.addAll(otherDom.values) elif name == "true": newLoc.name = GdlPool.getConstant("next") newLoc.idx = d.loc.idx if otherDom == None: raise RuntimeException("Uh oh, missed a next") d.values.addAll(otherDom.values) if len(d.values) != before: changedSomething = True
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
def removeComponent(self, c): """ generated source for method removeComponent """ if isinstance(c, (Proposition, )): if self.basePropositions.containsKey(name): self.basePropositions.remove(name) elif self.inputPropositions.containsKey(name): self.inputPropositions.remove(name) if partner != None: self.legalInputMap.remove(partner) self.legalInputMap.remove(p) elif name == GdlPool.getProposition(GdlPool.getConstant("INIT")): raise RuntimeException("The INIT component cannot be removed. Consider leaving it and ignoring it.") elif name == GdlPool.getProposition(GdlPool.getConstant("terminal")): raise RuntimeException("The terminal component cannot be removed.") else: for propositions in legalPropositions.values(): if self.propositions.contains(p): self.propositions.remove(p) if partner != None: self.legalInputMap.remove(partner) self.legalInputMap.remove(p) for propositions in goalPropositions.values(): self.propositions.remove(p) self.propositions.remove(p) self.components.remove(c) for parent in c.getInputs(): parent.removeOutput(c) for child in c.getOutputs(): child.removeInput(c)
def normalizePropositions(cls, componentSet): """ generated source for method normalizePropositions """ for component in componentSet: if isinstance(component, (Proposition, )): if isinstance(sentence, (GdlRelation, )): if relation.__name__ == cls.NEXT: p.setName(GdlPool.getProposition(GdlPool.getConstant("anon")))
def addMissingInputs(self): """ generated source for method addMissingInputs """ addList = ArrayList() for proposition in propositions.values(): if isinstance(, (GdlRelation, )): if relation.__name__.getValue() == "legal": addList.add(proposition) for addItem in addList: self.components.add(getProposition(GdlPool.getRelation(GdlPool.getConstant("does"), relation.getBody())))
def expandTrue(self, base, index, workingSet, results): """ generated source for method expandTrue """ if base.arity() == index: results.add(GdlPool.getRule(GdlPool.getRelation(GdlPool.getConstant("true"), [None]*))) else: for term in (base.get(index)).getBody(): workingSet.addLast(term) self.expandTrue(base, index + 1, workingSet, results) workingSet.removeLast()
def cleanParentheses_1(cls, sentence): """ generated source for method cleanParentheses_1 """ if isinstance(sentence, (GdlProposition, )): return sentence cleanedBody = ArrayList() for term in sentence.getBody(): cleanedBody.add(cls.cleanParentheses(term)) if len(cleanedBody) == 0: return GdlPool.getProposition(sentence.__name__) else: return GdlPool.getRelation(sentence.__name__, cleanedBody)
def cleanParentheses_0(cls, literal): """ generated source for method cleanParentheses_0 """ if isinstance(literal, (GdlSentence, )): return cls.cleanParentheses(literal) elif isinstance(literal, (GdlDistinct, )): return GdlPool.getDistinct(term1, term2) elif isinstance(literal, (GdlNot, )): return GdlPool.getNot(cls.cleanParentheses(body)) elif isinstance(literal, (GdlOr, )): while i < or_.arity(): pass i += 1 return GdlPool.getOr(disjuncts) raise RuntimeException("Unexpected literal type in GdlCleaner")
def mergeBaseRelations(self, rels): """ generated source for method mergeBaseRelations """ merges = HashMap() for rel in rels: if not merges.containsKey(name): merges.put(name, ArrayList()) addRelToMerge(rel, merge) rval = HashSet() valConst = GdlPool.getConstant("val") for c in merges.keySet(): body.add(c) for mergeSet in merge: Collections.sort(ms2, SortTerms()) body.add(GdlPool.getFunction(valConst, ms2)) rval.add(toAdd) return rval
def findAndInstantiateBaseProps(self, gdl): """ generated source for method findAndInstantiateBaseProps """ if isinstance(gdl, (GdlRelation, )): if name == "init": if relation.arity() != 1: raise RuntimeException("Can't init more than one thing as far as I know.") if isinstance(template, (GdlConstant, )): body.add(template) self.baseRelations.add(toAdd) System.err.println("Weird init of constant") elif isinstance(template, (GdlVariable, )): System.err.println("Weird init of constant") body.add(self.universalDom) self.baseRelations.add(toAdd) System.err.println("Weird init of variable") elif isinstance(template, (GdlFunction, )): instantiateBaseProps(func.toSentence()) elif isinstance(gdl, (GdlRule, )): if name == "next": if head.arity() != 1: raise RuntimeException("Can't next more than one thing as far as I know.") if isinstance(, (GdlVariable, )): # weird case where you have rule like (next ?q) l.idx = 0 l.name = head.__name__ for c in dom.values: body.add(c) self.baseRelations.add(GdlPool.getRelation(self.baseConstant, body)) else: instantiateBasePropsWithRHS(head.get(0).toSentence(), rule.getBody())
def getAllInstantiations(self): """ generated source for method getAllInstantiations """ rval = ArrayList() for gdl in description: if isinstance(gdl, (GdlRelation, )): if name == "base": continue rval.add(GdlPool.getRule(relation)) for d in domains.values(): for r in d.ruleRefs: for varInstantiation in varInstantiations: if varInstantiation.containsValue(None): raise RuntimeException("Shouldn't instantiate anything to null.") rval.add(getInstantiation(r.originalRule, varInstantiation)) if rval.get(len(rval) - 1).__str__().contains("null"): raise RuntimeException("Shouldn't instantiate anything to null: " + rval.get(len(rval) - 1).__str__()) for ruleRef in extraRefs: for c in ruleRef.conditions: if c.dom == None: c.updateDom() if c.dom != None: newConditions.add(c) if len(newConditions) != len(ruleRef.conditions): ruleRef.conditions = newConditions for r in extraRefs: for varInstantiation in varInstantiations: if varInstantiation.containsValue(None): raise RuntimeException("Shouldn't instantiate anything to null.") rval.add(getInstantiation(r.originalRule, varInstantiation)) if rval.get(len(rval) - 1).__str__().contains("null"): raise RuntimeException("Shouldn't instantiate anything to null.") if len(varInstantiations) == 0: rval.add(getInstantiation(r.originalRule, HashMap())) return rval
def substituteRule(cls, rule, theta): """ generated source for method substituteRule """ head = cls.substitute(rule.getHead(), theta) body = ArrayList() for literal in rule.getBody(): body.add(cls.substituteLiteral(literal, theta)) return GdlPool.getRule(head, body)
def cleanParentheses(cls, rule): """ generated source for method cleanParentheses """ cleanedHead = cls.cleanParentheses(rule.getHead()) cleanedBody = ArrayList() for literal in rule.getBody(): cleanedBody.add(cls.cleanParentheses(literal)) return GdlPool.getRule(cleanedHead, cleanedBody)
def removeNotDistinctLiteral(cls, rule, notDistinctLiteral): """ generated source for method removeNotDistinctLiteral """ # Figure out the substitution we want... # If we have two constants: Either remove one or # maybe get rid of the ___? # One is a variable: Replace the variable with the other thing # throughout the rule distinct = notDistinctLiteral.getBody() arg1 = distinct.getArg1() arg2 = distinct.getArg2() if arg1 == arg2: # Just remove that literal newBody.addAll(rule.getBody()) newBody.remove(notDistinctLiteral) return GdlPool.getRule(rule.getHead(), newBody) if isinstance(arg1, (GdlVariable, )): # What we return will still have the not-distinct literal, # but it will get replaced in the next pass. # (Even if we have two variables, they will be equal next time through.) return CommonTransforms.replaceVariable(rule, arg1, arg2) if isinstance(arg2, (GdlVariable, )): return CommonTransforms.replaceVariable(rule, arg2, arg1) if isinstance(arg1, (GdlConstant, )) or isinstance(arg2, (GdlConstant, )): # We have two non-equal constants, or a constant and a function. # The rule should have no effect. return None # We have two functions. Complicated! (Have to replace them with unified version.) # We pass on this case for now. # TODO: Implement correctly. raise UnsupportedOperationException("We can't currently handle (not (distinct <function> <function>)).")
def getNameWithPrefix(self, prefix): """ generated source for method getNameWithPrefix """ i = 0 while True: if not self.allNamesSoFar.contains(candidateName): self.allNamesSoFar.add(candidateName) return GdlPool.getConstant(candidateName) i += 1
def getNumberedTuple(cls, tupleSize): """ generated source for method getNumberedTuple """ result = Lists.newArrayList() i = 0 while i < tupleSize: result.add(GdlPool.getVariable("?v" + Integer.toString(i))) i += 1 return result
def getVariablesTuple(cls, tupleSize): """ generated source for method getVariablesTuple """ varsTuple = Lists.newArrayList() i = 0 while i < tupleSize: varsTuple.add(GdlPool.getVariable("?" + i)) i += 1 return varsTuple
def substituteOr(cls, or_, theta): """ generated source for method substituteOr """ if or_.isGround(): return or_ else: while i < or_.arity(): disjuncts.add(cls.substituteLiteral(or_.get(i), theta)) i += 1 return GdlPool.getOr(disjuncts)
def substituteRelation(cls, relation, theta): """ generated source for method substituteRelation """ if relation.isGround(): return relation else: while i < relation.arity(): body.add(substituteTerm(relation.get(i), theta)) i += 1 return GdlPool.getRelation(name, body)
def substituteFunction(cls, function_, theta): """ generated source for method substituteFunction """ if function_.isGround(): return function_ else: while i < function_.arity(): body.add(substituteTerm(function_.get(i), theta)) i += 1 return GdlPool.getFunction(name, body)
def testClojureGamer(self): """ generated source for method testClojureGamer """ try: assertEquals("SampleClojureGamer", g.__name__) g.setMatch(m) g.setRoleName(GdlPool.getConstant("xplayer")) g.metaGame(1000) assertTrue(g.selectMove(1000) != None) except Exception as e: e.printStackTrace()
def checkValidity(self, theGame): """ generated source for method checkValidity """ try: sm.initialize(theGame.getRules()) if len(bases) == 0: raise ValidatorException("Could not find base propositions.") elif len(inputs) == 0: raise ValidatorException("Could not find input propositions.") for base in bases: truesFromBases.add(GdlPool.getRelation(self.TRUE, base.getBody())) for input in inputs: legalsFromInputs.add(GdlPool.getRelation(self.LEGAL, input.getBody())) if truesFromBases.isEmpty() and legalsFromInputs.isEmpty(): return ImmutableList.of() while System.currentTimeMillis() < startTime + self.millisecondsToTest: # Check state against bases, inputs if not truesFromBases.isEmpty(): if not truesFromBases.containsAll(state.getContents()): missingBases.addAll(state.getContents()) missingBases.removeAll(truesFromBases) raise ValidatorException("Found missing bases: " + missingBases) if not legalsFromInputs.isEmpty(): for role in sm.getRoles(): for move in legalMoves: legalSentences.add(GdlPool.getRelation(self.LEGAL, [None]*)) if not legalsFromInputs.containsAll(legalSentences): missingInputs.addAll(legalSentences) missingInputs.removeAll(legalsFromInputs) raise ValidatorException("Found missing inputs: " + missingInputs) state = sm.getRandomNextState(state) if sm.isTerminal(state): state = initialState except MoveDefinitionException as mde: raise ValidatorException("Could not find legal moves while simulating: " + mde) except TransitionDefinitionException as tde: raise ValidatorException("Could not find transition definition while simulating: " + tde) except RuntimeException as e: raise ValidatorException("Ran into a runtime exception while simulating: " + e) except StackOverflowError as e: raise ValidatorException("Ran into a stack overflow while simulating: " + e) except OutOfMemoryError as e: raise ValidatorException("Ran out of memory while simulating: " + e) return ImmutableList.of()
def run(cls, description): """ generated source for method run """ newDesc = ArrayList() for gdl in description: if isinstance(gdl, (GdlRule, )): for body in newBodies: newDesc.add(GdlPool.getRule(rule.getHead(), body)) else: newDesc.add(gdl) return newDesc
def fixDisjunctions(self): """ generated source for method fixDisjunctions """ fixList = ArrayList() for proposition in propositions.values(): if proposition.getInputs().size() > 1: fixList.add(proposition) for fixItem in fixList: for input in fixItem.getInputs(): i += 1 if isinstance(, (GdlProposition, )): disjunct = Proposition(GdlPool.getProposition(GdlPool.getConstant(proposition.__name__.getValue() + "-" + i))) else: disjunct = Proposition(GdlPool.getRelation(GdlPool.getConstant(relation.__name__.getValue() + "-" + i), relation.getBody())) input.getOutputs().clear() link(input, disjunct) link(disjunct, or_) self.components.add(disjunct) fixItem.getInputs().clear() link(or_, fixItem) self.components.add(or_)
def cleanParentheses_2(cls, term): """ generated source for method cleanParentheses_2 """ if isinstance(term, (GdlConstant, )) or isinstance(term, (GdlVariable, )): return term if isinstance(term, (GdlFunction, )): # The whole point of the function if function_.arity() == 0: return function_.__name__ for functionTerm in function_.getBody(): cleanedBody.add(cls.cleanParentheses(functionTerm)) return GdlPool.getFunction(function_.__name__, cleanedBody) raise RuntimeException("Unexpected term type in GdlCleaner")
def getInstantiations(self, constant): """ generated source for method getInstantiations """ if not self.instantiations.containsKey(constant): self.instantiations.put(constant, ArrayList()) if constant.getValue() == "does": for rule in getInstantiations(GdlPool.getConstant("legal")): self.instantiations.get(constant).add(equivalentDoesRule) else: for template in templates.get(constant): instantiate(template, 0, Substitution(), results) self.instantiations.get(constant).addAll(results) return self.instantiations.get(constant)
def getInstantiationAux(self, gdl, varInstantiation): """ generated source for method getInstantiationAux """ if isinstance(gdl, (GdlRelation, )): while i < relation.arity(): body.add(self.getInstantiationAux(relation.get(i), varInstantiation)) i += 1 return GdlPool.getRelation(relation.__name__, body) elif isinstance(gdl, (GdlRule, )): while i < rule.arity(): body.add(self.getInstantiationAux(rule.get(i), varInstantiation)) i += 1 return GdlPool.getRule(head, body) elif isinstance(gdl, (GdlDistinct, )): return GdlPool.getDistinct(arg1, arg2) elif isinstance(gdl, (GdlNot, )): return GdlPool.getNot(body) elif isinstance(gdl, (GdlOr, )): while i < or_.arity(): body.add(self.getInstantiationAux(or_.get(i), varInstantiation)) i += 1 return GdlPool.getOr(body) elif isinstance(gdl, (GdlProposition, )): return gdl elif isinstance(gdl, (GdlConstant, )): return gdl elif isinstance(gdl, (GdlFunction, )): while i < func.arity(): body.add(self.getInstantiationAux(func.get(i), varInstantiation)) i += 1 return GdlPool.getFunction(func.__name__, body) elif isinstance(gdl, (GdlVariable, )): return varInstantiation.get(variable) else: raise RuntimeException("Someone went and extended the GDL hierarchy without updating this code.")
def replaceVariablesInternal(cls, gdl, assignment): """ generated source for method replaceVariablesInternal """ if isinstance(gdl, (GdlProposition, )): return gdl elif isinstance(gdl, (GdlRelation, )): for term in relation.getBody(): newBody.add(cls.replaceVariables(term, assignment)) return GdlPool.getRelation(name, newBody) elif isinstance(gdl, (GdlConstant, )): return gdl elif isinstance(gdl, (GdlVariable, )): if assignment.containsKey(gdl): return assignment.get(gdl) else: return gdl elif isinstance(gdl, (GdlFunction, )): for term in function_.getBody(): newBody.add(cls.replaceVariables(term, assignment)) return GdlPool.getFunction(name, newBody) elif isinstance(gdl, (GdlDistinct, )): return GdlPool.getDistinct(arg1, arg2) elif isinstance(gdl, (GdlNot, )): return GdlPool.getNot(cls.replaceVariables(internal, assignment)) elif isinstance(gdl, (GdlOr, )): while i < or_.arity(): newInternals.add(cls.replaceVariables(or_.get(i), assignment)) i += 1 return GdlPool.getOr(newInternals) elif isinstance(gdl, (GdlRule, )): for conjunct in rule.getBody(): newBody.add(cls.replaceVariables(conjunct, assignment)) return GdlPool.getRule(newHead, newBody) else: raise RuntimeException("Unforeseen Gdl subtype " + gdl.__class__.getSimpleName())
def expandFirstOr(cls, gdl): """ generated source for method expandFirstOr """ rval = List() expandedChild = List() if isinstance(gdl, (GdlDistinct, )): # Can safely be ignored, won't contain 'or' rval = ArrayList() rval.add(gdl) return rval elif isinstance(gdl, (GdlNot, )): expandedChild = cls.expandFirstOr(not_.getBody()) rval = ArrayList() for g in expandedChild: if not (isinstance(g, (GdlLiteral, ))): raise RuntimeException("Not must have literal child.") rval.add(GdlPool.getNot(lit)) return rval elif isinstance(gdl, (GdlOr, )): rval = ArrayList() while i < or_.arity(): rval.add(or_.get(i)) i += 1 return rval elif isinstance(gdl, (GdlProposition, )): # Can safely be ignored, won't contain 'or' rval = ArrayList() rval.add(gdl) return rval elif isinstance(gdl, (GdlRelation, )): # Can safely be ignored, won't contain 'or' rval = ArrayList() rval.add(gdl) return rval elif isinstance(gdl, (GdlRule, )): raise RuntimeException("This should be used to remove 'or's from the body of a rule, and rules can't be nested") elif isinstance(gdl, (GdlConstant, )): # Can safely be ignored, won't contain 'or' rval = ArrayList() rval.add(gdl) return rval elif isinstance(gdl, (GdlFunction, )): # Can safely be ignored, won't contain 'or' rval = ArrayList() rval.add(gdl) return rval elif isinstance(gdl, (GdlVariable, )): # Can safely be ignored, won't contain 'or' rval = ArrayList() rval.add(gdl) return rval else: raise RuntimeException("Uh oh, gdl hierarchy must have been extended without updating this code.")
def getAnnotations(self): """ generated source for method getAnnotations """ # Find universe and initial domains for gdl in description: processGdl(gdl, None) processDomain(gdl) # Compute the actual domains of everything updateDomains() # printDomains(); # printDomainRefs(); # Compute function corresponding to universal set for insertion in baseprops body = ArrayList() body.addAll(self.universe) self.universalDom = GdlPool.getFunction(GdlPool.getConstant("thing"), body) # Find next/init things and use them to instantiate base props for gdl in description: findAndInstantiateBaseProps(gdl) self.baseRelations = mergeBaseRelations(self.baseRelations) # Return the results rval = ArrayList() rval.addAll(self.baseRelations) return rval