예제 #1
0
 @Test
 public void optimizeTest() throws IOException {
   List<Map> maps = mapper.readValue(json, new TypeReference<List<Map>>() {});
   Optimizer optimizer = new Optimizer();
   List<Vol> optimize = optimizer.optimize4(Vol.fromMaps(maps));
   System.out.println(optimizer.formatString(optimize));
 }
예제 #2
0
  @Test
  public void optimizeRand() throws IOException {
    Optimizer optimizer = new Optimizer();
    long start;
    List<Vol> optimize;

    for (int i = 0; i < 1; i++) {
      List<Vol> list = randList(100000);

      start = System.currentTimeMillis();
      //            optimize = optimizer.optimize3(null, list);
      //            System.out.println(optimizer.formatString(optimize));
      //            System.out.println(System.currentTimeMillis() - start);
      //            System.out.println(Vol.toString(optimize));

      start = System.currentTimeMillis();
      List<Vol> optimize2 = optimizer.optimize4(list);
      long duration = System.currentTimeMillis() - start;
      System.out.println(optimizer.formatString(optimize2));
      System.out.println(duration);
      //            System.out.println(Vol.toString(optimize2));

      //
      // assertThat(Optimizer.price(optimize)).isLessThanOrEqualTo(Optimizer.price(optimize2));
      Iterator<Vol> iterator = optimize2.iterator();

      Vol vol = iterator.next();
      while (iterator.hasNext()) {
        Vol next = iterator.next();
        assertThat(vol.isNext(next)).isTrue();
        vol = next;
      }
    }
  }
예제 #3
0
    @Override
    protected T compute() {
      Optimizer<T> optimizer =
          optimizerFactory.create(
              new TemperatureFunction() {

                @Override
                public double temperature(int currentStep, int nSteps) {
                  return tempScale * subTempFun.temperature(currentStep, nSteps);
                }
              });
      return optimizer.iterate(subOptimizerSteps, initial);
    }
예제 #4
0
  private double preparePlan() {
    TableFilter[] topArray = topFilters.toArray(new TableFilter[topFilters.size()]);
    for (TableFilter t : topArray) {
      t.setFullCondition(condition);
    }

    Optimizer optimizer = new Optimizer(topArray, condition, session);
    optimizer.optimize();
    topTableFilter = optimizer.getTopFilter();
    double planCost = optimizer.getCost();

    setEvaluatableRecursive(topTableFilter);

    topTableFilter.prepare();
    return planCost;
  }
예제 #5
0
  protected void checkGraph(String fileName, String dirName)
      throws IOException, SyntaxFormatException {
    Parser parser = new Parser(fileName);
    parser.parse();
    Optimizer optimizer = new Optimizer(Optimizer.LEVEL.ALL);
    // optimizer.copyPropagate(parser.getRootBlock());
    // optimizer.commonExpressionChangeToMove(parser.getRootBlock());
    optimizer.optimize(parser.getRootBlock());
    for (Function func : Function.getAllFunction()) {
      // optimizer.copyPropagate(func.getBody().getFirstBlock());
      // optimizer.commonExpressionChangeToMove(func.getBody().getFirstBlock());
      optimizer.optimize(func.getBody().getFirstBlock());
    }

    Block blk = parser.getRootBlock();
    PrintWriter writer =
        new PrintWriter(fileName.replaceAll("testprogs", dirName) + ".vcg", "UTF-8");
    writer.print(GraphPrinter.printCFGBody(blk, "main", true));
    writer.close();
  }
예제 #6
0
  /** Run the literal op upgrader */
  private void run() {
    final TranslationAdvice advice = Optimizer.getAdvice();

    ssaMeth.forEachInsn(
        new SsaInsn.Visitor() {
          public void visitMoveInsn(NormalSsaInsn insn) {
            // do nothing
          }

          public void visitPhiInsn(PhiInsn insn) {
            // do nothing
          }

          public void visitNonMoveInsn(NormalSsaInsn insn) {

            Insn originalRopInsn = insn.getOriginalRopInsn();
            Rop opcode = originalRopInsn.getOpcode();
            RegisterSpecList sources = insn.getSources();

            // Replace insns with constant results with const insns
            if (tryReplacingWithConstant(insn)) return;

            if (sources.size() != 2) {
              // We're only dealing with two-source insns here.
              return;
            }

            if (opcode.getBranchingness() == Rop.BRANCH_IF) {
              /*
               * An if instruction can become an if-*z instruction.
               */
              if (isConstIntZeroOrKnownNull(sources.get(0))) {
                replacePlainInsn(
                    insn, sources.withoutFirst(), RegOps.flippedIfOpcode(opcode.getOpcode()), null);
              } else if (isConstIntZeroOrKnownNull(sources.get(1))) {
                replacePlainInsn(insn, sources.withoutLast(), opcode.getOpcode(), null);
              }
            } else if (advice.hasConstantOperation(opcode, sources.get(0), sources.get(1))) {
              insn.upgradeToLiteral();
            } else if (opcode.isCommutative()
                && advice.hasConstantOperation(opcode, sources.get(1), sources.get(0))) {
              /*
               * An instruction can be commuted to a literal operation
               */

              insn.setNewSources(RegisterSpecList.make(sources.get(1), sources.get(0)));

              insn.upgradeToLiteral();
            }
          }
        });
  }
  // --------------------------------------------------------------------
  private int[] allocateBuckets(List<BucketTree.Branch> branches, char nBuckets, int nTrials) {
    double errors[][] = new double[branches.size()][nTrials];
    //        int    parentPaths[] = parentReachPaths(branches);

    BUCKETIZER.setThorough(false);
    for (int branchIndex = 0; branchIndex < branches.size(); branchIndex++) {
      BucketTree.Branch branch = branches.get(branchIndex);

      LOG.debug("allocating branch " + (branchIndex + 1) + " of " + branches.size());
      for (byte nBucketTrial = 0; nBucketTrial < nTrials; nBucketTrial++) {
        errors[branchIndex][nBucketTrial] = BUCKETIZER.bucketize(branch, (byte) (nBucketTrial + 1));
      }
    }

    return Optimizer.optimize(errors, nBuckets);
  }
 // Maakt een random dienstregeling aan
 // || In deze methode zou je je algoritme kunnen plaatsen in plaats van de
 // 'domme'
 // random methode die nu gebruikt wordt
 public Dienstregeling maakDienstregeling() {
   // Dienstregeling d = new Dienstregeling(true);
   // Dienstregeling d = Optimizer.Optimize(10000,1000,2);
   Dienstregeling d = new Dienstregeling();
   int resultaatArray[] = new int[1000];
   int min = 9999999;
   int max = 0;
   double avg = 0;
   for (int i = 0; i < 1000; i++) {
     d = Optimizer.Optimize2(100, 100, 0.1, 0.01);
     int temp = d.telPassagiersKilometers();
     avg += temp / 1000;
     if (temp > max) {
       max = temp;
     }
     if (temp < min) {
       min = temp;
     }
     resultaatArray[i] = temp;
   }
   System.out.println("min: " + min + " max: " + max + " avg: " + avg);
   return d;
 }
 @Override
 public Serializable generate(SharedSessionContractImplementor session, Object object)
     throws HibernateException {
   return optimizer.generate(databaseStructure.buildCallback(session));
 }
예제 #10
0
  /* lossesList contains couples (Effect, Losses) */
  public double[][] createLossesList(boolean bMonotonous, boolean bTheoretical) {
    System.out.println("Creating losses list (Security Class -> Losses)... ");

    Hashtable<Double, Double> htLossesList = new Hashtable<Double, Double>();
    Hashtable<Integer, Double> htLossesLookup = new Hashtable<Integer, Double>();
    Hashtable<Integer, Double> htEffectLookup = new Hashtable<Integer, Double>();

    double[][] mdLossesList;
    double dLosses;

    // for every SecClass combination, calculate Losses, ReqLvls and Effectiveness
    for (int i = 0; i < _iNrComb; i++) {
      dLosses = 0;

      int[] viSecClass = intToSecClass(i);

      for (int j = 0; j < _viLvlsNbr.length; j++) {
        dLosses +=
            (Double)
                ee.ioc.cs.vsle.api.ProgramContext.queryTable(
                    _sLossesTableID, Character.toString((_vsGoals[j]).charAt(0)), viSecClass[j]);
      }
      int[] reqLvlList = createReqLvlList(viSecClass, false);
      double dEffect = Optimizer.calcEffect(reqLvlList);

      // in case of duplicates use average value for losses
      if (!htLossesList.containsKey(dEffect)) htLossesList.put(dEffect, dLosses);
      else htLossesList.put(dEffect, (dLosses + htLossesList.get(dEffect)) / 2);

      // create a lookup table for (secClass - losses) couples
      htLossesLookup.put(i, dLosses);

      // create a lookup table for (secClass - effect) couples
      htEffectLookup.put(i, dEffect);
    }
    // if asked to, create a monotonously decreasing version of the losses information do
    if (bMonotonous) {
      mdLossesList = new double[_iNewNbrComb][2];

      int[] viSecClass = new int[_vsGoals.length];
      Arrays.fill(viSecClass, 0);
      double dLossesRef, dMaxDiff, dTmpDiff;
      int iIndex;

      for (int i = 0; i < _iNewNbrComb; i++) {
        mdLossesList[i][0] = htEffectLookup.get(secClassToInt(viSecClass));
        mdLossesList[i][1] = htLossesLookup.get(secClassToInt(viSecClass));

        dLossesRef = htLossesLookup.get(secClassToInt(viSecClass));
        iIndex = 0;
        dMaxDiff = 0;
        dTmpDiff = 0;

        for (int j = 0; j < _vsGoals.length; j++) {
          if ((viSecClass[j] + 1) < _viLvlsNbr[j]) {
            viSecClass[j] += 1;
            dTmpDiff = dLossesRef - htLossesLookup.get(secClassToInt(viSecClass));
            viSecClass[j] -= 1;
          }
          if (dTmpDiff > dMaxDiff) {
            iIndex = j;
            dMaxDiff = dTmpDiff;
          }
        }
        viSecClass[iIndex] += 1;
      }
    }
    // else, sort the Hashtable htLossesList with regard to the effectiveness values
    else {
      Vector<Double> vec = new Vector<Double>(htLossesList.keySet());
      Collections.sort(vec);
      Iterator<Double> it = vec.iterator();

      mdLossesList = new double[htLossesList.size()][2];

      int iI = 0;
      while (it.hasNext()) {
        double dOrdered = it.next();
        mdLossesList[iI][0] = dOrdered;
        mdLossesList[iI][1] = htLossesList.get(dOrdered);
        iI++;
      }
    }
    // if asked to add the theoretical point (Effect=1 - losses=0) do the following
    if (bTheoretical) {
      double[][] mdLossesListTemp = new double[mdLossesList.length + 1][2];
      for (int i = 0; i < mdLossesList.length; i++) {
        mdLossesListTemp[i][0] = mdLossesList[i][0];
        mdLossesListTemp[i][1] = mdLossesList[i][1];
      }
      mdLossesListTemp[mdLossesListTemp.length - 1][0] = 1;
      mdLossesListTemp[mdLossesListTemp.length - 1][1] = 0;

      mdLossesList = new double[mdLossesListTemp.length][2];
      for (int i = 0; i < mdLossesList.length; i++) {
        mdLossesList[i][0] = mdLossesListTemp[i][0];
        mdLossesList[i][1] = mdLossesListTemp[i][1];
      }
    }

    System.out.println(Arrays.deepToString(mdLossesList));
    System.out.println("... done");
    return mdLossesList;
  }
예제 #11
0
  /**
   * Goal-driven recursive (depth-first, exhaustive) search with backtracking
   *
   * @param problem
   * @param algorithm
   * @param subtaskRelsInPath
   * @param depth
   */
  private boolean subtaskPlanningImpl(
      PlanningContext context,
      Set<Rel> relsWithSubtasks,
      EvaluationAlgorithm algorithm,
      LinkedList<Rel> subtaskRelsInPath,
      int depth) {

    Set<Rel> relsWithSubtasksCopy = new LinkedHashSet<Rel>(relsWithSubtasks);

    Set<Rel> relsWithSubtasksToRemove = new LinkedHashSet<Rel>();

    boolean firstMLB = true;

    // start building Maximal Linear Branch (MLB)
    MLB:
    while (!relsWithSubtasksCopy.isEmpty()) {

      if (isSubtaskLoggingOn()) {
        String print = p(depth) + "Starting new MLB with: ";
        for (Rel rel : relsWithSubtasksCopy) {
          print +=
              "\n" + p(depth) + "  " + rel.getParent().getFullName() + " : " + rel.getDeclaration();
        }
        /*
        print += "\n" + p( depth ) + " All remaining rels in problem:";
        for ( Rel rel : problem.getAllRels() ) {
            print += "\n" + p( depth ) + " " + rel.getParentObjectName() + " : " + rel.getDeclaration();
        }
        print += "\n" + p( depth ) + "All found variables: ";
        for ( Var var : problem.getFoundVars() ) {
            print += "\n" + p( depth ) + " " + var.toString();
        }
        */
        logger.debug(print);
      }

      // if this is a first attempt to construct an MLB to solve a subtask(i.e. depth>0),
      // do not invoke linear planning because it has already been done
      if ((depth == 0) || !firstMLB) {

        boolean solvedIntermediately = linearForwardSearch(context, algorithm, true);

        // Having constructed some MLBs the (sub)problem may be solved
        // and there is no need in wasting precious time planning unnecessary branches
        if (solvedIntermediately
            && ( // on the top level optimize only if computing goals
            (depth == 0 && !computeAll)
                // otherwise (inside subtasks) always optimize
                || (depth != 0))) {
          // If the problem is solved, optimize and return
          if (!isOptDisabled) Optimizer.optimize(context, algorithm);
          return true;
        }
      } else {
        firstMLB = false;
      }

      // or children
      OR:
      for (Iterator<Rel> subtaskRelIterator = relsWithSubtasksCopy.iterator();
          subtaskRelIterator.hasNext(); ) {

        Rel subtaskRel = subtaskRelIterator.next();

        if (isSubtaskLoggingOn())
          logger.debug(
              p(depth)
                  + "OR: depth: "
                  + (depth + 1)
                  + " rel - "
                  + subtaskRel.getParent().getFullName()
                  + " : "
                  + subtaskRel.getDeclaration());

        if (subtaskRel.equals(subtaskRelsInPath.peekLast())
            || (!context.isRelReadyToUse(subtaskRel))
            || context.getFoundVars().containsAll(subtaskRel.getOutputs())
            || (!isSubtaskRepetitionAllowed && subtaskRelsInPath.contains(subtaskRel))) {

          if (isSubtaskLoggingOn()) {
            logger.debug(p(depth) + "skipped");
            if (!context.isRelReadyToUse(subtaskRel)) {
              logger.debug(p(depth) + "because it has unknown inputs"); // TODO print unknown
            } else if (context.getFoundVars().containsAll(subtaskRel.getOutputs())) {
              logger.debug(p(depth) + "because all outputs in FoundVars");
            } else if (subtaskRel.equals(subtaskRelsInPath.peekLast())) {
              logger.debug(p(depth) + "because it is nested in itself");
            } else if (!isSubtaskRepetitionAllowed && subtaskRelsInPath.contains(subtaskRel)) {
              logger.debug(
                  p(depth)
                      + "This rel with subtasks is already in use, path: "
                      + subtaskRelsInPath);
            }
          }
          continue OR;
        }

        LinkedList<Rel> newPath = new LinkedList<Rel>(subtaskRelsInPath);
        newPath.add(subtaskRel);

        PlanningResult result = new PlanningResult(subtaskRel, true);

        // this is true if all subtasks are solvable
        boolean allSolved = true;
        // and children
        AND:
        for (SubtaskRel subtask : subtaskRel.getSubtasks()) {
          if (isSubtaskLoggingOn()) logger.debug(p(depth) + "AND: subtask - " + subtask);

          EvaluationAlgorithm sbtAlgorithm = null;

          ////////////////////// INDEPENDENT SUBTASK////////////////////////////////////////
          if (subtask.isIndependent()) {
            if (isSubtaskLoggingOn()) logger.debug("Independent!!!");

            if (subtask.isSolvable() == null) {
              if (isSubtaskLoggingOn())
                logger.debug("Start solving independent subtask " + subtask.getDeclaration());
              // independent subtask is solved only once
              Problem problemContext = subtask.getContext();
              DepthFirstPlanner planner = new DepthFirstPlanner();
              planner.indSubtasks = indSubtasks;
              planner.nested = true;
              sbtAlgorithm = planner.invokePlaning(problemContext, isOptDisabled);
              PlanningContext indCntx = problemContext.getCurrentContext();
              boolean solved = indCntx.getFoundVars().containsAll(indCntx.getAllGoals());
              if (solved) {
                subtask.setSolvable(Boolean.TRUE);
                indSubtasks.put(subtask, sbtAlgorithm);
                if (isSubtaskLoggingOn()) logger.debug("Solved " + subtask.getDeclaration());
              } else {
                subtask.setSolvable(Boolean.FALSE);
                if (RuntimeProperties.isLogInfoEnabled()) {
                  logger.debug("Unable to solve " + subtask.getDeclaration());
                }
              }
              allSolved &= solved;
            } else if (subtask.isSolvable() == Boolean.TRUE) {
              if (isSubtaskLoggingOn()) logger.debug("Already solved");
              allSolved &= true;
              sbtAlgorithm = indSubtasks.get(subtask);
            } else {
              if (isSubtaskLoggingOn()) logger.debug("Not solvable");
              allSolved &= false;
            }
            if (isSubtaskLoggingOn()) logger.debug("End of independent subtask " + subtask);

            if (!allSolved) {
              continue OR;
            }

            assert sbtAlgorithm != null;

            result.addSubtaskAlgorithm(subtask, sbtAlgorithm);
          }
          ////////////////////// DEPENDENT SUBTASK//////////////////////////////////////
          else {
            // lets clone the environment
            PlanningContext newContext = prepareNewContext(context, subtask);

            sbtAlgorithm = new EvaluationAlgorithm();

            // during linear planning, if some goals are found, they are removed from the set
            // "goals"
            boolean solved =
                linearForwardSearch(
                    newContext,
                    sbtAlgorithm,
                    // do not optimize here, because the solution may require additional rels with
                    // subtasks
                    true);

            if (solved) {
              if (isSubtaskLoggingOn()) logger.debug(p(depth) + "SOLVED subtask: " + subtask);

              if (!isOptDisabled) {
                // if a subtask has been solved, optimize its algorithm
                Optimizer.optimize(newContext, sbtAlgorithm);
              }

              result.addSubtaskAlgorithm(subtask, sbtAlgorithm);
              allSolved &= solved;
              continue AND;
            } else if (!solved && (depth == maxDepth)) {
              if (isSubtaskLoggingOn())
                logger.debug(p(depth) + "NOT SOLVED and cannot go any deeper, subtask: " + subtask);
              continue OR;
            }

            if (isSubtaskLoggingOn()) logger.debug(p(depth) + "Recursing deeper");

            solved =
                subtaskPlanningImpl(newContext, relsWithSubtasks, sbtAlgorithm, newPath, depth + 1);

            if (isSubtaskLoggingOn()) logger.debug(p(depth) + "Back to depth " + (depth + 1));

            // the linear planning has been performed at the end of MLB on the depth+1,
            // if the problem was solved, there is no need to run linear planning again
            if ((solved || (solved = linearForwardSearch(newContext, sbtAlgorithm, true)))
                && !isOptDisabled) {
              // if solved, optimize here with full list of goals in order to get rid of
              // unnecessary subtask instances and other relations
              Optimizer.optimize(newContext, sbtAlgorithm);
            }

            if (isSubtaskLoggingOn())
              logger.debug(p(depth) + (solved ? "" : "NOT") + " SOLVED subtask: " + subtask);

            allSolved &= solved;

            // if at least one subtask is not solvable, try another
            // branch
            if (!allSolved) {
              continue OR;
            }

            result.addSubtaskAlgorithm(subtask, sbtAlgorithm);
          }
        } // AND

        if (allSolved) {
          algorithm.add(result);

          Set<Var> newVars = new LinkedHashSet<Var>();

          unfoldVarsToSet(subtaskRel.getOutputs(), newVars);

          context.getKnownVars().addAll(newVars);
          context.getFoundVars().addAll(newVars);

          subtaskRelIterator.remove();

          if (isSubtaskLoggingOn()) {
            logger.debug(
                p(depth)
                    + "SOLVED ALL SUBTASKS for "
                    + subtaskRel.getParent().getFullName()
                    + " : "
                    + subtaskRel.getDeclaration());
            logger.debug(p(depth) + "Updating the problem graph and continuing building new MLB");
          }

          // this is used for incremental dfs
          if (depth == 0) {
            relsWithSubtasksToRemove.add(subtaskRel);
          }

          continue MLB;
        }
        if (isSubtaskLoggingOn())
          logger.debug(
              p(depth)
                  + "NOT SOLVED ALL subtasks, removing from path "
                  + subtaskRel.getParent().getFullName()
                  + " : "
                  + subtaskRel.getDeclaration());
        newPath.remove(subtaskRel);
      } // end OR

      // exit loop because there are no more rels with subtasks to be
      // applied
      // (i.e. no more rels can introduce new variables into the
      // algorithm)
      if (isSubtaskLoggingOn()) logger.debug(p(depth) + "No more MLB can be constructed");
      break MLB;
    }

    // incremental dfs, remove solved subtasks
    if (depth == 0) {
      relsWithSubtasks.removeAll(relsWithSubtasksToRemove);
    }

    return false;
  }
예제 #12
0
  /**
   * Linear forward search algorithm
   *
   * @param p
   * @param algorithm
   * @param targetVars
   * @param _computeAll
   * @return
   */
  private boolean linearForwardSearch(
      PlanningContext context, EvaluationAlgorithm algorithm, boolean _computeAll) {

    /*
     * while iterating through hashset, items cant be removed from/added to
     * that set. Theyre collected into these sets and added/removedall
     * together after iteration is finished
     */
    Set<Var> newVars = new LinkedHashSet<Var>();
    Set<Var> relOutputs = new LinkedHashSet<Var>();
    Set<Var> removableVars = new LinkedHashSet<Var>();

    boolean changed = true;

    if (isLinearLoggingOn())
      logger.debug(
          "------Starting linear planning with (sub)goals: "
              + context.getRemainingGoals()
              + "--------");

    if (isLinearLoggingOn()) logger.debug("Algorithm " + algorithm);

    int counter = 1;

    while ((!_computeAll && changed && !context.getRemainingGoals().isEmpty())
        || (changed && _computeAll)) {

      if (isLinearLoggingOn()) logger.debug("----Iteration " + counter + " ----");

      counter++;
      changed = false;

      // iterate through all knownvars
      if (isLinearLoggingOn()) logger.debug("Known:" + context.getKnownVars());

      for (Var var : context.getKnownVars()) {

        if (isLinearLoggingOn()) logger.debug("Current Known: " + var);

        // Check the relations of all components
        for (Rel rel : var.getRels()) {
          if (isLinearLoggingOn()) logger.debug("And its rel: " + rel);
          if (context.isAvailableRel(rel)) {
            context.removeUnknownInput(rel, var);

            if (isLinearLoggingOn()) logger.debug("problem contains it " + rel);

            removableVars.add(var);

            if (context.isRelReadyToUse(rel) && rel.getType() != RelType.TYPE_METHOD_WITH_SUBTASK) {

              if (isLinearLoggingOn()) logger.debug("rel is ready to be used " + rel);

              boolean relIsNeeded = false;

              if (isLinearLoggingOn()) logger.debug("its outputs " + rel.getOutputs());

              for (Var relVar : rel.getOutputs()) {

                if (!context.getFoundVars().contains(relVar)) {
                  relIsNeeded = true;
                }
              }

              if (rel.getOutputs().isEmpty()) {
                relIsNeeded = true;
              }
              if (isLinearLoggingOn()) logger.debug("relIsNeeded " + relIsNeeded);

              if (relIsNeeded) {

                if (isLinearLoggingOn()) logger.debug("needed rel:  " + rel);

                if (!rel.getOutputs().isEmpty()) {
                  relOutputs.clear();
                  unfoldVarsToSet(rel.getOutputs(), relOutputs);
                  newVars.addAll(relOutputs);
                  context.getFoundVars().addAll(relOutputs);
                }
                algorithm.addRel(rel);
                if (isLinearLoggingOn()) logger.debug("algorithm " + algorithm);
              }

              context.removeRel(rel);
              changed = true;
            }
          }
        }
      }

      // remove targets if they have already been found
      for (Iterator<Var> targetIter = context.getRemainingGoals().iterator();
          targetIter.hasNext(); ) {
        Var targetVar = targetIter.next();
        if (context.getFoundVars().contains(targetVar)) {
          targetIter.remove();
        }
      }

      if (isLinearLoggingOn()) logger.debug("foundvars " + context.getFoundVars());

      context.getKnownVars().addAll(newVars);
      context.getKnownVars().removeAll(removableVars);
      newVars.clear();
    }
    if (isLinearLoggingOn()) logger.debug("algorithm " + algorithm);

    if (!_computeAll) {
      Optimizer.optimize(context, algorithm);

      if (isLinearLoggingOn()) logger.debug("optimized algorithm " + algorithm);
    }

    if (isLinearLoggingOn()) logger.debug("\n---!!!Finished linear planning!!!---\n");

    return context.getRemainingGoals().isEmpty()
        || context.getFoundVars().containsAll(context.getAllGoals());
  }
예제 #13
0
  public static void main(final String[] args) throws Exception {
    new RPClassGenerator().createRPClasses();
    final CreatureGroupsXMLLoader loader = new CreatureGroupsXMLLoader("/data/conf/creatures.xml");
    final List<DefaultCreature> creatures = loader.load();

    Collections.sort(
        creatures,
        new Comparator<DefaultCreature>() {
          @Override
          public int compare(final DefaultCreature o1, final DefaultCreature o2) {
            return o1.getLevel() - o2.getLevel();
          }
        });

    final int[] atkLevels = new int[HIGHEST_LEVEL + 1];
    final int[] defLevels = new int[HIGHEST_LEVEL + 1];

    for (int level = 0; level < atkLevels.length; level++) {
      // help newbies a bit, so don't start at real stats, but a bit lower
      atkLevels[level] = (int) Math.round(Math.log(level + 4) * 9 - 10);
      defLevels[level] = (int) Math.round(Math.log(level + 4) * 20 + level - 26);
    }

    final EntityManager em = SingletonRepository.getEntityManager();

    final Item shield = em.getItem("wooden shield");
    final Item armor = em.getItem("dress");
    final Item helmet = em.getItem("leather helmet");
    final Item legs = em.getItem("leather legs");
    final Item boots = em.getItem("leather boots");

    player = (Player) new PlayerTransformer().transform(new RPObject());
    player.equip("lhand", shield);
    player.equip("rhand", em.getItem("club"));
    player.equip("armor", armor);
    player.equip("head", helmet);
    player.equip("legs", legs);
    player.equip("feet", boots);

    // Setup the list of creatures to balance
    Collection<DefaultCreature> creaturesToBalance;
    if (args.length > 0) {
      Collection<String> names = Arrays.asList(args);
      creaturesToBalance = new ArrayList<DefaultCreature>();

      for (DefaultCreature creature : creatures) {
        if (names.contains(creature.getCreatureName())) {
          creaturesToBalance.add(creature);
        }
      }
    } else {
      // default to all of them
      creaturesToBalance = creatures;
    }

    for (final DefaultCreature creature : creaturesToBalance) {
      final int level = creature.getLevel();

      if (creature.getLevel() > HIGHEST_LEVEL) {
        continue;
      }

      final Creature target = creature.getCreature();
      final Optimizer optimizer = new Optimizer(target);

      player.setLevel(level);
      player.setBaseHP(100 + 10 * level);
      player.setAtk(atkLevels[level]);
      player.setDef(defLevels[level]);

      equip(player, level);

      System.out.println("Player(" + level + ") vs " + creature.getCreatureName());

      durationThreshold = DEFAULT_DURATION_THRESHOLD;

      boolean balanced = false;
      int tries = 0;
      while (!balanced) {
        final Pair<Integer, Integer> results = combat(player, target, ROUNDS);
        final int meanTurns = results.first();
        final int meanLeftHP = results.second();

        final int proposedXPValue = (int) ((2 * creature.getLevel() + 1) * (meanTurns / 2.0));
        creature.setLevel(creature.getLevel(), proposedXPValue);

        System.out.println(
            "Target ATK: "
                + target.getAtk()
                + "/DEF: "
                + target.getDef()
                + "/HP: "
                + target.getBaseHP()
                + "\t Turns: "
                + meanTurns
                + "\tLeft HP:"
                + meanLeftHP);

        if (isCorrectResult(level, meanTurns, meanLeftHP / (double) player.getBaseHP())) {
          balanced = true;
        } else {
          optimizer.step(meanLeftHP, meanTurns);

          System.out.println(
              "New ATK: "
                  + target.getAtk()
                  + "/DEF: "
                  + target.getDef()
                  + "/HP: "
                  + target.getBaseHP());
        }

        // relax convergence criteria for pathological cases
        tries++;
        if (tries % 200 == 0) {
          durationThreshold *= 1.1;
          System.out.println(target.getName() + ": changed threshold to " + durationThreshold);
        }
      }

      boolean changed = false;

      if (creature.getAtk() != target.getAtk()) {
        changed = true;
      }

      if (creature.getDef() != target.getDef()) {
        changed = true;
      }

      if (creature.getHP() != target.getBaseHP()) {
        changed = true;
      }

      System.out.print("BALANCED: ");
      final StringBuilder stringBuilder = new StringBuilder();
      stringBuilder.append(creature.getCreatureName());
      stringBuilder.append("(");
      stringBuilder.append(creature.getLevel());
      stringBuilder.append(")\t");
      if (changed) {
        stringBuilder.append("*\t");
      } else {
        stringBuilder.append(" \t");
      }
      stringBuilder.append("ATK: ");
      stringBuilder.append(target.getAtk());
      stringBuilder.append("\t\tDEF: ");
      stringBuilder.append(target.getDef());
      stringBuilder.append("\t\tHP: ");
      stringBuilder.append(target.getBaseHP());
      System.out.println(stringBuilder.toString());
    }
  }
예제 #14
0
  public void optimize(Declaration declaration) throws XPathException {
    Expression exp = compiledFunction.getBody();
    ExpressionVisitor visitor = makeExpressionVisitor();
    Expression exp2 = exp;
    Optimizer opt = getConfiguration().obtainOptimizer();
    try {
      if (opt.getOptimizationLevel() != Optimizer.NO_OPTIMIZATION) {
        exp2 = exp.optimize(visitor, null);
      }

    } catch (XPathException err) {
      err.maybeSetLocation(this);
      compileError(err);
    }

    // Try to extract new global variables from the body of the function
    if (opt.getOptimizationLevel() != Optimizer.NO_OPTIMIZATION) {
      Expression exp3 = opt.promoteExpressionsToGlobal(exp2, visitor);
      if (exp3 != null) {
        exp2 = visitor.optimize(exp3, null);
      }
    }

    // Add trace wrapper code if required
    exp2 = makeTraceInstruction(this, exp2);

    allocateSlots(exp2);
    if (exp2 != exp) {
      compiledFunction.setBody(exp2);
    }

    int tailCalls =
        ExpressionTool.markTailFunctionCalls(exp2, getObjectName(), getNumberOfArguments());
    if (tailCalls != 0) {
      compiledFunction.setTailRecursive(tailCalls > 0, tailCalls > 1);
      compiledFunction.setBody(new TailCallLoop(compiledFunction));
    }

    // Generate byte code if appropriate

    if (getConfiguration().isGenerateByteCode(Configuration.XSLT)) {
      try {
        Expression cbody =
            opt.compileToByteCode(
                compiledFunction.getBody(),
                nameAtt,
                Expression.PROCESS_METHOD | Expression.ITERATE_METHOD);
        if (cbody != null) {
          compiledFunction.setBody(cbody);
        }
      } catch (Exception e) {
        System.err.println("Failed while compiling function " + nameAtt);
        e.printStackTrace();
        throw new XPathException(e);
      }
    }

    compiledFunction.computeEvaluationMode();

    if (isExplaining()) {
      exp2.explain(getConfiguration().getStandardErrorOutput());
    }
  }