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 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 initializeInstantiations(self, description): """ generated source for method initializeInstantiations """ trues = ArrayList() for gdl in description: if isinstance(gdl, (GdlSentence, )): if sentence.__name__.getValue() == "base": if sentence.arity() == 1: trues.add(GdlPool.getRule(GdlPool.getRelation(GdlPool.getConstant("true"), [None]*))) else: self.expandTrue(sentence, 1, LinkedList(), results) trues.addAll(results) instantiations = HashMap() instantiations.put(GdlPool.getConstant("true"), trues) return instantiations
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 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 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 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 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 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 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 selectPuzzleMove(self, finishBy): """ generated source for method selectPuzzleMove """ if getStateMachine().getRoles().size() > 1: return Move(GdlPool.getConstant("OOPS")) moves = getStateMachine().getLegalMoves(getCurrentState(), getRole()) bestScoreSoFar = -1 bestMoveSoFar = None for move in moves: self.statesExpanded.increment(1) if bestScoreAfterMove > bestScoreSoFar: bestScoreSoFar = bestScoreAfterMove bestMoveSoFar = move if bestScoreSoFar == 100: break self.expectedScore.set(bestScoreSoFar) return bestMoveSoFar
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
def run(self): """ generated source for method run """ try: if self.strategy == "Noop": self.selection = Move(GdlPool.getConstant("Noop")) elif self.strategy == "Legal": self.selection = moves.get(0) elif self.strategy == "Random": self.selection = moves.get(self.theRandom.nextInt(len(moves))) elif self.strategy == "Puzzle": self.selection = selectPuzzleMove(self.finishBy) elif self.strategy == "Minimax": self.selection = selectMinimaxMove(self.finishBy) elif self.strategy == "Heuristic": self.selection = selectHeuristicMove(self.finishBy) elif self.strategy == "Monte Carlo": self.selection = selectMonteCarloMove(self.finishBy) except MoveDefinitionException as e: raise RuntimeException(e) except TransitionDefinitionException as e: raise RuntimeException(e) except GoalDefinitionException as e: raise RuntimeException(e)
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()
def stateMachineSelectMove(self, timeout): """ generated source for method stateMachineSelectMove """ return Move(GdlPool.getConstant("NOOP"))