/*
(non-Javadoc)

@see eu.seaclouds.platform.planner.optimizer.heuristics.SearchMethod#
computeOptimalSolution
(eu.seaclouds.platform.planner.optimizer.SuitableOptions, java.util.Map)
329780
@Override
   public Solution[] computeOptimizationProblem(SuitableOptions cloudOffers, QualityInformation requirements,
         Topology topology, int numPlansToGenerate) {

      // To findSolution method, we pass an Empty solution instead of a null
      // value to or create a new method that does not consider the current one.
      // This way may help for replanning, when even the first attempt for
      // solution will be based on the current deployment

      logBlind.debug("Starting the computeOptimizationProblem in BLIND");
      Solution[] bestSols = findInitialRandomSolutions(cloudOffers, numPlansToGenerate, topology);
      logBlind.debug("Initial random solutions found");
      super.setFitnessOfSolutions(bestSols, requirements, topology, cloudOffers);
      super.sortSolutionsByFitnessAndReplaceNaN(bestSols);

      logBlind.debug("Fitness of initial solutions calculated");
      Solution[] currentSol = new Solution[1];
      int numItersNoImprovement = 0;
      while (numItersNoImprovement < super.getMaxIterNoImprove()) {

         currentSol[0] = super.findRandomSolution(cloudOffers, topology);
         currentSol[0].setSolutionFitness(super.fitness(currentSol[0], requirements, topology, cloudOffers));

         if (logBlind.isTraceEnabled()) {
            logBlind.trace(
                  "Start checking the presence of quality attached to solutions after generating a new random solution in BLIND. With sol= "
                        + currentSol[0].toString());
            super.checkQualityAttachedToSolutions(currentSol);
         }
         if (currentSol[0].getSolutionFitness() > super.getMinimumFitnessOfSolutions(bestSols)) {
            logBlind.debug(
                  "Quality of found solution is larger than the best solutions so far {} > {} and can be included: {} ",
                  currentSol[0].getSolutionFitness(), super.getMinimumFitnessOfSolutions(bestSols),
                  currentSol[0].toString());

            if (!currentSol[0].isContainedIn(bestSols)) {
               super.insertOrdered(bestSols, currentSol[0]);

               logBlind.debug(
                     "Better solution found after {} iterations. Adding fitness of {} . Resulting bestsols fitness are: {}",
                     numItersNoImprovement, currentSol[0].getSolutionFitness(), printFitnessArray(bestSols));

               numItersNoImprovement = 0;
            }
         }

         numItersNoImprovement++;
      }

      return bestSols;

   }
99996
protected <E extends SpatialComparable, A> double computeOverlap(A entries, ArrayAdapter<E, A> getter, long[] assign) {
    ModifiableHyperBoundingBox mbr1 = null, mbr2 = null;
    for(int i = 0; i < getter.size(entries); i++) {
      E e = getter.get(entries, i);
      if(BitsUtil.get(assign, i)) {
        if(mbr1 == null) {
          mbr1 = new ModifiableHyperBoundingBox(e);
        }
        else {
          mbr1.extend(e);
        }
      }
      else {
        if(mbr2 == null) {
          mbr2 = new ModifiableHyperBoundingBox(e);
        }
        else {
          mbr2.extend(e);
        }
      }
    }
    if(mbr1 == null || mbr2 == null) {
      throw new AbortException("Invalid state in split: one of the sets is empty.");
    }
    return SpatialUtil.overlap(mbr1, mbr2);
  }
247644
protected Map<Integer, Class<?>> prepareOptionalGenericTypeMap(Method executeMethod) {
        final Parameter[] parameters = executeMethod.getParameters();
        if (parameters.length == 0) {
            return Collections.emptyMap();
        }
        final Map<Integer, Class<?>> optionalGenericTypeMap = new LinkedHashMap<Integer, Class<?>>(4);
        int index = 0;
        for (Parameter parameter : parameters) {
            if (isOptionalParameterType(parameter.getType())) {
                final Type paramedType = parameter.getParameterizedType();
                final Class<?> genericType = DfReflectionUtil.getGenericFirstClass(paramedType);
                checkExecuteMethodOptionalParameter(executeMethod, paramedType, genericType);
                optionalGenericTypeMap.put(index, genericType);
            }
            ++index;
        }
        return Collections.unmodifiableMap(optionalGenericTypeMap);
    }
637957
public OptimizationResult getCalibration() throws SolverException {

		Optimizer.ObjectiveFunction objectiveFunction = new Optimizer.ObjectiveFunction() {
			@Override
			public void setValues(double[] parameters, double[] values) {

				//We change the parameters of the model
				CalibratableProcess newModel = model.getCloneForModifiedParameters(parameters);
				CharacteristicFunctionModel newModelFourier = newModel.getCharacteristicFunctionModel();

				int numberOfMaturities = surface.getMaturities().length;
				double mats[] = surface.getMaturities();

				QuotingConvention targetConvention = surface.getQuotingConvention();

				ArrayList<Double> vals = new ArrayList<Double>();

				for(int t = 0; t<numberOfMaturities; t++) {

					double[] currentStrikes = surface.getSmile(mats[t]).getStrikes();

					EuropeanOptionSmile newPricer = pricer.getCloneWithModifiedParameters(mats[t],currentStrikes);

					try {
						Map<String, Function<Double, Double>> currentModelPrices = newPricer.getValue(0.0, newModelFourier);

						for(int i = 0; i<currentStrikes.length;i++) {

							if(targetConvention.equals(QuotingConvention.VOLATILITYLOGNORMAL)) {
								//we convert prices into lognormal volatilities
								double forward = surface.getEquityForwardCurve().getDiscountFactor(mats[t]);
								double optionMaturity =mats[t];
								double optionStrike = currentStrikes[i];
								double payoffUnit = surface.getDiscountCurve().getDiscountFactor(mats[t]);
								double optionValue = currentModelPrices.get("valuePerStrike").apply(optionStrike);
								vals.add(net.finmath.functions.AnalyticFormulas.blackScholesOptionImpliedVolatility(forward, optionMaturity, optionStrike, payoffUnit, optionValue));


							}else if(targetConvention.equals(QuotingConvention.VOLATILITYNORMAL)) {
								//we convert prices into normal volatilities
								double forward = surface.getEquityForwardCurve().getDiscountFactor(mats[t]);
								double optionMaturity =mats[t];
								double optionStrike = currentStrikes[i];
								double payoffUnit = surface.getDiscountCurve().getDiscountFactor(mats[t]);
								double optionValue = currentModelPrices.get("valuePerStrike").apply(optionStrike);
								vals.add(net.finmath.functions.AnalyticFormulas.bachelierOptionImpliedVolatility(forward, optionMaturity, optionStrike, payoffUnit, optionValue));
							}else {
								//just output the prices
								vals.add(currentModelPrices.get("valuePerStrike").apply(currentStrikes[i]));
							}

						}
					} catch (CalculationException e) {
						e.printStackTrace();
					}

				}
				for(int i = 0; i<values.length; i++) {values[i] = vals.get(i);}
			}
		};

		Optimizer optimizer = optimizerFactory.getOptimizer(
				objectiveFunction,
				initialParameters,
				lowerBound,
				upperBound,
				parameterStep,
				formatTargetValuesForOptimizer() /* targetValues */);


		optimizer.run();

		ArrayList<String> calibrationOutput = outputCalibrationResult(optimizer.getBestFitParameters());

		CalibratableProcess calibratedModel = model.getCloneForModifiedParameters(optimizer.getBestFitParameters());

		return new OptimizationResult(calibratedModel,optimizer.getBestFitParameters(),optimizer.getIterations(),optimizer.getRootMeanSquaredError(),calibrationOutput);
	}
383664
@Override
  public void evaluate(DoubleSolution solution) {

    int numberOfVariables_ = solution.getNumberOfVariables();
    int numberOfObjectives = solution.getNumberOfObjectives();

    double[] x = new double[numberOfVariables_];
    double[] f = new double[numberOfObjectives];

    for (int i = 0; i < numberOfVariables_; i++) {
      x[i] = solution.getVariableValue(i);
    }

    // check if the point is infeasible
    boolean infeasible = false;
    infeasible = if_infeasible(x);
    while (infeasible) {
      //re-generate a random variable
      for (int i = 0; i < numberOfVariables_; i++) {
        x[i] = generV(getLowerBound(i), getUpperBound(i));
        solution.setVariableValue(i, x[i]);
      }
      infeasible = if_infeasible(x);
    }

    // evaluate f1,...m-1
    for (int i = 0; i < M9 - 1; i++) {
      if (r_polyline9[i][0] == 1) {
        f[i] = Math.abs(x[0] - r_polyline9[i][1]);
      } else {
        f[i] = Math.abs((r_polyline9[i][1] * x[0] - x[1] + r_polyline9[i][2])) / Math
            .sqrt(Math.pow(r_polyline9[i][1], 2) + 1);
      }
    }
    // evaluate fm
    if (r_polyline9[M9 - 1][0] == 1) {
      f[M9 - 1] = Math.abs(x[0] - r_polyline9[M9 - 1][1]);
    } else {
      f[M9 - 1] = Math.abs((r_polyline9[M9 - 1][1] * x[0] - x[1] + r_polyline9[M9 - 1][2])) / Math
          .sqrt(Math.pow(r_polyline9[M9 - 1][1], 2) + 1);
    }

    for (int i = 0; i < numberOfObjectives; i++) {
      solution.setObjective(i, f[i]);
    }

  }
434064
public static <S extends Solution<?>> S getBestSolution(S solution1, S solution2, Comparator<S> comparator, BinaryOperator<S> equalityPolicy) {
    S result;
    int flag = comparator.compare(solution1, solution2);
    if (flag == -1) {
      result = solution1;
    } else if (flag == 1) {
      result = solution2;
    } else {
      result = equalityPolicy.apply(solution1, solution2);
    }

    return result;
  }
309565
@Override
    public double compute(double a, double b) {
        if (Op.isEq(Op.min(a, b), 0.0)) {
            return Op.max(a, b);
        }
        return 1.0;
    }
430885
@Override
    public void evaluate(BinarySolution solution) {
    int counterOnes;
    int counterZeroes;

    counterOnes = 0;
    counterZeroes = 0;

    BitSet bitset = solution.getVariableValue(0) ;

    for (int i = 0; i < bitset.length(); i++) {
      if (bitset.get(i)) {
        counterOnes++;
      } else {
        counterZeroes++;
      }
    }

    // OneZeroMax is a maximization problem: multiply by -1 to minimize
    solution.setObjective(0, -1.0 * counterOnes);
    solution.setObjective(1, -1.0 * counterZeroes);
  }
1302789
@Override
  protected Object getOptionValue(Queue<String> argq) {
    return Double.parseDouble(argq.remove());
  }
1196225
public boolean handleOptions(Map<Option, String> map) {
        boolean ok = true;
        for (Map.Entry<Option, String> e: map.entrySet()) {
            try {
                ok = ok & handleOption(e.getKey(), e.getValue());
            } catch (IllegalArgumentException ex) {
                log.error(Errors.IllegalArgumentForOption(e.getKey().getPrimaryName(), ex.getMessage()));
                ok = false;
            }
        }
        return ok;
    }
654691
@Override
  protected double computeCost(
      final DataSegment proposalSegment,
      final ServerHolder server,
      final boolean includeCurrentServer
  )
  {
    double cost = super.computeCost(proposalSegment, server, includeCurrentServer);

    if (cost == Double.POSITIVE_INFINITY) {
      return cost;
    }

    int nSegments = 1;
    if (server.getServer().getLazyAllSegments().size() > 0) {
      nSegments = server.getServer().getLazyAllSegments().size();
    }

    double normalizedCost = cost / nSegments;
    double usageRatio = (double) server.getSizeUsed() / (double) server.getServer().getMaxSize();

    return normalizedCost * usageRatio;
  }
652700
@SuppressWarnings("unchecked")
  public S execute(S solution) {
    int best;
    evaluations = 0;
    numberOfNonComparableSolutions = 0;

    int rounds = improvementRounds;

    int i = 0;
    while (i < rounds) {
      S mutatedSolution = mutationOperator.execute((S) solution.copy());

      problem.evaluate(mutatedSolution);
      evaluations++;
      if (problem.getNumberOfConstraints() > 0) {
        best = constraintComparator.compare(mutatedSolution, solution);
        if (best == 0) {
          best = comparator.compare(mutatedSolution, solution);
        }
      } else {
        best = comparator.compare(mutatedSolution, solution);
      }

      if (best == -1) {
        solution = mutatedSolution;
        numberOfImprovements++;
      } else if (best == 1) {
        // Current solution is best
      } else {
        numberOfNonComparableSolutions++;

        if (randomGenerator.getRandomValue() < 0.5) {
          solution = mutatedSolution;
        }
      }
      i++;
    }
    return (S) solution.copy();
  }
1255331
public void computeSolutions( FastQueue<DMatrixRMaj> solutions )
	{
		if( !rootFinder.process(poly))
			return;

		List<Complex_F64> zeros = rootFinder.getRoots();

		for( Complex_F64 c : zeros ) {
			if( !c.isReal() && Math.abs(c.imaginary) > 1e-10 )
				continue;

			DMatrixRMaj F = solutions.grow();

			double a = c.real;
			double b = 1-c.real;

			for( int i = 0; i < 9; i++ ) {
				F.data[i] = a*F1.data[i] + b*F2.data[i];
			}

			// det(F) = 0 is already enforced, but for essential matrices it needs to enforce
			// that the first two singular values are zero and the last one is zero
			if( !computeFundamental && !projectOntoEssential(F) ) {
					solutions.removeTail();
			}
		}
	}
760211
@SuppressWarnings("unchecked")
    protected final <K extends AbstractOption<?>, V extends AbstractOptionValue<K, ?>> Map<K, V> asMap0() {
        return Collections.unmodifiableMap((Map<? extends K, ? extends V>) valueMap);
    }
242612
public static <K, V> ConfigurationOptionBuilder<Map<K, V>> mapOption(ValueConverter<K> keyConverter, ValueConverter<V> valueConverter) {
		return new ConfigurationOptionBuilder<Map<K, V>>(new MapValueConverter<K, V>(keyConverter, valueConverter), Map.class)
				.defaultValue(Collections.<K, V>emptyMap());
	}
390904
@Override public Double evaluate(List<S> solutionList) {
    if (solutionList == null) {
      throw new JMetalException("The pareto front approximation is null") ;
    }

    return invertedGenerationalDistancePlus(new ArrayFront(solutionList), referenceParetoFront);
  }
481330
private static QrMode[] applyOptimisation(int version, QrMode[] inputMode) {

        int inputLength = inputMode.length;
        int blockCount = 0;
        int i, j;
        QrMode currentMode = QrMode.NULL;

        for (i = 0; i < inputLength; i++) {
            if (inputMode[i] != currentMode) {
                currentMode = inputMode[i];
                blockCount++;
            }
        }

        int[] blockLength = new int[blockCount];
        QrMode[] blockMode = new QrMode[blockCount];

        j = -1;
        currentMode = QrMode.NULL;
        for (i = 0; i < inputLength; i++) {
            if (inputMode[i] != currentMode) {
                j++;
                blockLength[j] = 1;
                blockMode[j] = inputMode[i];
                currentMode = inputMode[i];
            } else {
                blockLength[j]++;
            }
        }

        if (blockCount > 1) {
            // Search forward
            for (i = 0; i <= (blockCount - 2); i++) {
                if (blockMode[i] == QrMode.BINARY) {
                    switch (blockMode[i + 1]) {
                        case KANJI:
                            if (blockLength[i + 1] < tribus(version, 4, 5, 6)) {
                                blockMode[i + 1] = QrMode.BINARY;
                            }
                            break;
                        case ALPHANUM:
                            if (blockLength[i + 1] < tribus(version, 7, 8, 9)) {
                                blockMode[i + 1] = QrMode.BINARY;
                            }
                            break;
                        case NUMERIC:
                            if (blockLength[i + 1] < tribus(version, 3, 4, 5)) {
                                blockMode[i + 1] = QrMode.BINARY;
                            }
                            break;
                    }
                }

                if ((blockMode[i] == QrMode.ALPHANUM)
                        && (blockMode[i + 1] == QrMode.NUMERIC)) {
                    if (blockLength[i + 1] < tribus(version, 6, 8, 10)) {
                        blockMode[i + 1] = QrMode.ALPHANUM;
                    }
                }
            }

            // Search backward
            for (i = blockCount - 1; i > 0; i--) {
                if (blockMode[i] == QrMode.BINARY) {
                    switch (blockMode[i - 1]) {
                        case KANJI:
                            if (blockLength[i - 1] < tribus(version, 4, 5, 6)) {
                                blockMode[i - 1] = QrMode.BINARY;
                            }
                            break;
                        case ALPHANUM:
                            if (blockLength[i - 1] < tribus(version, 7, 8, 9)) {
                                blockMode[i - 1] = QrMode.BINARY;
                            }
                            break;
                        case NUMERIC:
                            if (blockLength[i - 1] < tribus(version, 3, 4, 5)) {
                                blockMode[i - 1] = QrMode.BINARY;
                            }
                            break;
                    }
                }

                if ((blockMode[i] == QrMode.ALPHANUM)
                        && (blockMode[i - 1] == QrMode.NUMERIC)) {
                    if (blockLength[i - 1] < tribus(version, 6, 8, 10)) {
                        blockMode[i - 1] = QrMode.ALPHANUM;
                    }
                }
            }
        }

        // ZINT NOTE: this method is different from the original Zint code in that it creates a
        // new array to hold the optimized values and returns it, rather than modifying the
        // original array; this allows this method to be called as many times as we want without
        // worrying about side effects

        QrMode[] optimized = new QrMode[inputMode.length];

        j = 0;
        for (int block = 0; block < blockCount; block++) {
            currentMode = blockMode[block];
            for (i = 0; i < blockLength[block]; i++) {
                optimized[j] = currentMode;
                j++;
            }
        }

        return optimized;
    }