Ejemplo n.º 1
0
 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)
Ejemplo n.º 2
0
 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()
Ejemplo n.º 3
0
 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
Ejemplo n.º 4
0
 def getNTermModels(cls, arity):
     """ generated source for method getNTermModels """
     result = Lists.newArrayListWithCapacity(arity)
     i = 0
     while i < arity:
         result.add(TermModel())
         i += 1
     return result
Ejemplo n.º 5
0
 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
Ejemplo n.º 6
0
 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
Ejemplo n.º 7
0
 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)
Ejemplo n.º 8
0
 def getNUnderscores(cls, numTerms):
     """ generated source for method getNUnderscores """
     underscore = GdlPool.UNDERSCORE
     terms = Lists.newArrayListWithCapacity(numTerms)
     i = 0
     while i < numTerms:
         terms.add(underscore)
         i += 1
     return terms
Ejemplo n.º 9
0
 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
Ejemplo n.º 10
0
 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)
Ejemplo n.º 11
0
 def run(cls, oldRules):
     """ generated source for method run """
     oldRules = DeORer.run(oldRules)
     newRules = Lists.newArrayListWithCapacity(len(oldRules))
     for gdl in oldRules:
         if isinstance(gdl, (GdlRule, )):
             newRules.add(reorderRule(rule))
         else:
             newRules.add(gdl)
     return newRules
Ejemplo n.º 12
0
 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
Ejemplo n.º 13
0
 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
Ejemplo n.º 14
0
 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)
Ejemplo n.º 15
0
 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)
Ejemplo n.º 16
0
    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()))
Ejemplo n.º 17
0
 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())
Ejemplo n.º 18
0
 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)
Ejemplo n.º 19
0
 def reorderRule(cls, oldRule):
     """ generated source for method reorderRule """
     newBody = Lists.newArrayList(oldRule.getBody())
     rearrangeDistinctsAndNots(newBody)
     return GdlPool.getRule(oldRule.getHead(), newBody)
Ejemplo n.º 20
0
 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
Ejemplo n.º 21
0
 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()
Ejemplo n.º 22
0
 def getAllSentencesInBody(cls, body):
     """ generated source for method getAllSentencesInBody """
     sentences = Lists.newArrayList()
     GdlVisitors.visitAll(body, GdlVisitor())
     return sentences
Ejemplo n.º 23
0
 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")
Ejemplo n.º 24
0
 def deepCopyOf(cls, original):
     """ generated source for method deepCopyOf """
     copy = Lists.newArrayListWithCapacity(len(original))
     for originalTermModel in original:
         copy.add(cls.TermModel.copyOf(originalTermModel))
     return copy
Ejemplo n.º 25
0
 def create(cls, form, domainsForSlots):
     """ generated source for method create """
     return CartesianSentenceFormDomain(form, ImmutableList.copyOf(Lists.transform(domainsForSlots, Function())))
Ejemplo n.º 26
0
 def toSampleTerms(self, bodyModels):
     """ generated source for method toSampleTerms """
     results = Lists.newArrayList()
     for termModel in bodyModels:
         results.add(self.toSampleTerms(termModel))
     return results
Ejemplo n.º 27
0
 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)