def graph(cls, srcpath, inclpaths, symOut, refOut, docOut): """ generated source for method graph """ parentDirs = Lists.newArrayList(inclpaths) parentDirs.add(cls.dirname(srcpath)) def compare(a,b): return a - b parentDirs = sorted(parentDirs, compare) idx = cls.newAnalyzer(srcpath, inclpaths) idx.multilineFunType = True jsonFactory = JsonFactory() symJson = jsonFactory.createGenerator(symOut) refJson = jsonFactory.createGenerator(refOut) docJson = jsonFactory.createGenerator(docOut) allJson = [symJson, refJson, docJson] for json in allJson: json.writeStartArray() for b in idx.getAllBindings(): if b.getFile() is not None: if cls.shouldEmit(b.getFile(), srcpath): cls.writeSymJson(b, symJson) cls.writeDocJson(b, idx, docJson) for ref in b.getRefs(): if ref.getFile() is not None: if not cls.seenRef.contains(key) and cls.shouldEmit(ref.getFile(), srcpath): cls.writeRefJson(ref, b, refJson) cls.seenRef.add(key) for json in allJson: json.writeEndArray() json.close()
def main(cls, args): """ generated source for method main """ GamerLogger.setSpilloverLogfile("spilloverLog") GamerLogger.log("Proxy", "Starting the ProxyGamePlayerClient program.") if not (len(args)): GamerLogger.logError("Proxy", "Usage is: \n\tProxyGamePlayerClient gamer port") return port = 9147 gamer = None try: port = Integer.valueOf(args[1]) except Exception as e: GamerLogger.logError("Proxy", args[1] + " is not a valid port.") return gamers = Lists.newArrayList(ProjectSearcher.GAMERS.getConcreteClasses()) gamerNames = ArrayList() if len(gamerNames) != len(gamers): for c in gamers: gamerNames.add(c.__name__.replaceAll("^.*\\.", "")) idx = gamerNames.indexOf(args[0]) if idx == -1: GamerLogger.logError("Proxy", args[0] + " is not a subclass of gamer. Valid options are:") for s in gamerNames: GamerLogger.logError("Proxy", "\t" + s) return try: gamer = (gamers.get(idx).newInstance()) except Exception as ex: GamerLogger.logError("Proxy", "Cannot create instance of " + args[0]) return try: theClient.start() except IOException as e: GamerLogger.logStackTrace("Proxy", e)
def toposortSafe(cls, allElements, dependencyGraph): """ generated source for method toposortSafe """ strataToAdd = createAllStrata(allElements) strataDependencyGraph = createStrataDependencyGraph(dependencyGraph) ordering = Lists.newArrayList() while not strataToAdd.isEmpty(): addOrMergeStratumAndAncestors(curStratum, ordering, strataToAdd, strataDependencyGraph, Lists.newArrayList()) return ordering
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 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 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)
def create_0(cls, form, setMultimap): """ generated source for method create_0 """ Preconditions.checkNotNull(setMultimap) domainsForSlots = Lists.newArrayList() i = 0 while i < form.getTupleSize(): domainsForSlots.add(setMultimap.get(i)) i += 1 return cls.create(form, domainsForSlots)
def getAmbiguities(cls, original, forms): """ generated source for method getAmbiguities """ result = Lists.newArrayList() for form in forms: if form == original: continue if ambiguity.isPresent(): result.add(ambiguity.get()) return result
def applyAmbiguities(cls, originalRule, ambiguitiesByOriginalForm, model): """ generated source for method applyAmbiguities """ rules = Lists.newArrayList(originalRule) # Each literal can potentially multiply the number of rules we have, so # we apply each literal separately to the entire list of rules so far. for literal in Iterables.concat(ImmutableSet.of(originalRule.getHead()), originalRule.getBody()): for rule in rules: Preconditions.checkArgument(originalRule.arity() == rule.arity()) newRules.addAll(applyAmbiguitiesForLiteral(literal, rule, ambiguitiesByOriginalForm, model)) rules = newRules return rules
def readFileToStructure(self, path, structure): header = PdbHeader() header.setTitle(Paths.get(path).getFileName().toString()) structure.setPDBHeader(header) model = ReadFile.getModelFromFile(self, path) structure.setChains(Lists.newArrayList(model)) info = PdbCryst() info.setSpaceGroup(SpaceGroup(0, 1, 1, "P 1", "P 1", BravaisL.CUBIC)) info.setCrystalCell(ReadFile.getBox(self, info.getSpaceGroup().getBravLattice().getExampleUnitCell())) header.setCrystallographicInfo(info) return structure
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)
def getFunctionFromTuple(self, tuple_, curIndex): """ generated source for method getFunctionFromTuple """ functionBody = Lists.newArrayList() i = 0 while i < self.arity: Preconditions.checkArgument(not (isinstance(term, (GdlFunction, )))) if self.functions.containsKey(i): functionBody.add(functionForm.getFunctionFromTuple(tuple_, curIndex)) curIndex += functionForm.getTupleSize() else: functionBody.add(term) curIndex += 1 i += 1 return GdlPool.getFunction(self.name, functionBody)
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 create(cls, form, domain): """ generated source for method create """ domainsForSlotsBuilder = Lists.newArrayList() i = 0 while i < form.getTupleSize(): domainsForSlotsBuilder.add(ImmutableSet.builder()) i += 1 for sentence in domain: assert form.matches(sentence) if len(tuple_) != form.getTupleSize(): raise IllegalArgumentException() while i < len(tuple_): domainsForSlotsBuilder.get(i).add(constant) i += 1 domainsForSlots = ImmutableList.builder() for builder in domainsForSlotsBuilder: domainsForSlots.add(builder.build()) return FullSentenceFormDomain(form, ImmutableList.copyOf(domain), domainsForSlots.build())
def getSentenceFromTuple(self, tuple_): """ generated source for method getSentenceFromTuple """ if len(tuple_) != self.tupleSize: raise IllegalArgumentException("Passed tuple of the wrong size to a sentence form: " + "tuple was " + tuple_ + ", sentence form is " + self) if len(tuple_) < self.arity: raise IllegalStateException("Something is very wrong, probably fixable by the GdlCleaner; name: " + self.name + "; arity: " + self.arity + "; tupleSize: " + self.tupleSize) sentenceBody = Lists.newArrayList() curIndex = 0 i = 0 while i < self.arity: Preconditions.checkArgument(not (isinstance(term, (GdlFunction, )))) if self.functions.containsKey(i): sentenceBody.add(functionForm.getFunctionFromTuple(tuple_, curIndex)) curIndex += functionForm.getTupleSize() else: sentenceBody.add(term) curIndex += 1 i += 1 if self.arity == 0: return GdlPool.getProposition(self.name) else: return GdlPool.getRelation(self.name, sentenceBody)
def reorderRule(cls, oldRule): """ generated source for method reorderRule """ newBody = Lists.newArrayList(oldRule.getBody()) rearrangeDistinctsAndNots(newBody) return GdlPool.getRule(oldRule.getHead(), newBody)
def optimizeAwayTrue(cls, components, negations, pn, trueComponent, falseComponent): """ generated source for method optimizeAwayTrue """ assert ((components != None and negations != None) or pn != None) for output in Lists.newArrayList(trueComponent.getOutputs()): if isEssentialProposition(output) or isinstance(output, (Transition, )): continue if isinstance(output, (Proposition, )): # Move its outputs to be outputs of true for child in output.getOutputs(): # Disconnect child.removeInput(output) # output.removeOutput(child); //do at end # Reconnect; will get children before returning, if nonessential trueComponent.addOutput(child) child.addInput(trueComponent) output.removeAllOutputs() if not isEssentialProposition(output): # Remove the proposition entirely trueComponent.removeOutput(output) output.removeInput(trueComponent) # Update its location to the trueComponent in our map if components != None: components.put(prop.__name__, trueComponent) negations.put(prop.__name__, falseComponent) else: pn.removeComponent(output) elif isinstance(output, (Or, )): # Attach children of or to trueComponent for child in or_.getOutputs(): child.addInput(trueComponent) trueComponent.addOutput(child) child.removeInput(or_) # Disconnect or completely or_.removeAllOutputs() for parent in or_.getInputs(): parent.removeOutput(or_) or_.removeAllInputs() if pn != None: pn.removeComponent(or_) elif isinstance(output, (And, )): # Remove as input from and and_.removeInput(trueComponent) trueComponent.removeOutput(and_) # If and has only one input, remove it if and_.getInputs().size() == 1: and_.removeInput(in_) in_.removeOutput(and_) for out in and_.getOutputs(): # Disconnect from and out.removeInput(and_) # and.removeOutput(out); //do at end # Connect directly to the new input out.addInput(in_) in_.addOutput(out) and_.removeAllOutputs() if pn != None: pn.removeComponent(and_) elif and_.getInputs().size() == 0: if pn != None: pn.removeComponent(and_) elif isinstance(output, (Not, )): # Disconnect from trueComponent not_.removeInput(trueComponent) trueComponent.removeOutput(not_) # Connect all children of the not to falseComponent for child in not_.getOutputs(): # Disconnect child.removeInput(not_) # not.removeOutput(child); //Do at end # Connect to falseComponent child.addInput(falseComponent) falseComponent.addOutput(child) not_.removeAllOutputs() if pn != None: pn.removeComponent(not_) elif isinstance(output, (Transition, )): # ??? System.err.println("Fix optimizeAwayTrue's case for Transitions")
def toSampleTerms(self, bodyModels): """ generated source for method toSampleTerms """ results = Lists.newArrayList() for termModel in bodyModels: results.add(self.toSampleTerms(termModel)) return results
def getDomain(self, form, sentence): """ generated source for method getDomain """ domainContents = Lists.newArrayList() getDomainInternal(sentence.getBody(), self.sentencesModel.get(NameAndArity(sentence)), domainContents) return CartesianSentenceFormDomain.create(form, domainContents)
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 getAllSentencesInBody(cls, body): """ generated source for method getAllSentencesInBody """ sentences = Lists.newArrayList() GdlVisitors.visitAll(body, GdlVisitor()) return sentences