List of usage examples for org.apache.commons.math3.optim.nonlinear.scalar GoalType MAXIMIZE
GoalType MAXIMIZE
To view the source code for org.apache.commons.math3.optim.nonlinear.scalar GoalType MAXIMIZE.
Click Source Link
From source file:edu.utexas.cs.tactex.tariffoptimization.OptimizerWrapperApachePowell.java
@Override public TreeMap<Double, TariffSpecification> findOptimum(TariffUtilityEstimate tariffUtilityEstimate, int NUM_RATES, int numEval) { double[] startingVertex = new double[NUM_RATES]; // start from the fixed-rate tariff's offset Arrays.fill(startingVertex, 0.0); PowellOptimizer optimizer = new PowellOptimizer(1e-3, 5); // needed since one optimization found positive // charges (paying customer to consume...) double[][] boundaries = createBoundaries(NUM_RATES); final PointValuePair optimum = optimizer.optimize(new MaxEval(numEval), //new ObjectiveFunction(new MultivariateFunctionMappingAdapter(tariffUtilityEstimate, boundaries[0], boundaries[1])), new ObjectiveFunction(new OptimizerWrapperApacheObjective(tariffUtilityEstimate)), GoalType.MAXIMIZE, new InitialGuess(startingVertex)); TreeMap<Double, TariffSpecification> eval2TOUTariff = new TreeMap<Double, TariffSpecification>(); eval2TOUTariff.put(optimum.getValue(), tariffUtilityEstimate.getCorrespondingSpec(optimum.getKey())); return eval2TOUTariff; }
From source file:edu.utexas.cs.tactex.tariffoptimization.OptimizerWrapperApacheAmoeba.java
@Override public TreeMap<Double, TariffSpecification> findOptimum(TariffUtilityEstimate tariffUtilityEstimate, int NUM_RATES, int numEval) { double[] startingVertex = new double[NUM_RATES]; // start from the fixed-rate tariff's offset //Arrays.fill(startingVertex, -0.5 * SIMPLEX_EDGE); //Arrays.fill(startingVertex, -1 * SIMPLEX_EDGE); // TODO if there are convergence issues, change these guessed thresholds //SimplexOptimizer optimizer = new SimplexOptimizer(1e-10, 1e-30); //SimplexOptimizer optimizer = new SimplexOptimizer(1e-4, 1e-4); //SimplexOptimizer optimizer = new SimplexOptimizer(1e-2, 10); SimplexOptimizer optimizer = new SimplexOptimizer(1e-3, 5); //SimplexOptimizer optimizer = new SimplexOptimizer(1e-2, 5); final PointValuePair optimum = optimizer.optimize(new MaxEval(numEval), new ObjectiveFunction(new OptimizerWrapperApacheObjective(tariffUtilityEstimate)), GoalType.MAXIMIZE, new InitialGuess(startingVertex), //new NelderMeadSimplex(NUM_RATES, -1 * SIMPLEX_EDGE)); new NelderMeadSimplex(NUM_RATES, SIMPLEX_EDGE));// should be positive since this reflects decrease in (negative) charges TreeMap<Double, TariffSpecification> eval2TOUTariff = new TreeMap<Double, TariffSpecification>(); eval2TOUTariff.put(optimum.getValue(), tariffUtilityEstimate.getCorrespondingSpec(optimum.getKey())); return eval2TOUTariff; }
From source file:com.google.cloud.genomics.dataflow.functions.verifybamid.Solver.java
/** * Maximizes a univariate function using a grid search followed by Brent's algorithm. * * @param fn the likelihood function to minimize * @param gridStart the lower bound for the grid search * @param gridEnd the upper bound for the grid search * @param gridStep step size for the grid search * @param relErr relative error tolerance for Brent's algorithm * @param absErr absolute error tolerance for Brent's algorithm * @param maxIter maximum # of iterations to perform in Brent's algorithm * @param maxEval maximum # of Likelihood function evaluations in Brent's algorithm * * @return the value of the parameter that maximizes the function */// w ww . j a v a 2 s . c om public static double maximize(UnivariateFunction fn, double gridStart, double gridEnd, double gridStep, double relErr, double absErr, int maxIter, int maxEval) { Interval interval = gridSearch(fn, gridStart, gridEnd, gridStep); BrentOptimizer bo = new BrentOptimizer(relErr, absErr); UnivariatePointValuePair max = bo.optimize(new MaxIter(maxIter), new MaxEval(maxEval), new SearchInterval(interval.getInf(), interval.getSup()), new UnivariateObjectiveFunction(fn), GoalType.MAXIMIZE); return max.getPoint(); }
From source file:fr.imag.ppplib.calc.opti.ACMLinearProgrammingSolver.java
@Override public void solve(double[] dir) { /* Check the dimension of the vectorspace where lives dir */ if (dir.length != d) throw new LinearProgrammingSolverException(dddirMessage); /* Update the constraints set of the simplex solver if modification */ if (lcListModified) { List<LinearConstraint> lcList = new ArrayList<LinearConstraint>(); int n = dirList.size(); for (int i = 0; i < n; i++) lcList.add(new LinearConstraint(dirList.get(i), Relationship.LEQ, valList.get(i))); lcSet = new LinearConstraintSet(lcList); }/*from ww w . j a va 2 s . c om*/ /* Evaluation */ PointValuePair res = solver.optimize(new LinearObjectiveFunction(dir, 0), lcSet, GoalType.MAXIMIZE); /* Update the results and the flags */ point = res.getPoint(); value = res.getSecond(); evaluated = true; lcListModified = false; }
From source file:edu.utexas.cs.tactex.tariffoptimization.OptimizerWrapperApacheBOBYQA.java
@Override public TreeMap<Double, TariffSpecification> findOptimum(TariffUtilityEstimate tariffUtilityEstimate, int NUM_RATES, int numEval) { double[] startingVertex = new double[NUM_RATES]; // start from the fixed-rate tariff's offset Arrays.fill(startingVertex, 0.0); //Arrays.fill(startingVertex, 0.5 * INITIAL_TRUST_REGION_RADIUS); //Arrays.fill(startingVertex, 1 * INITIAL_TRUST_REGION_RADIUS); final int numIterpolationPoints = 2 * NUM_RATES + 1; // BOBYQA recommends 2n+1 points BOBYQAOptimizer optimizer = new BOBYQAOptimizer(numIterpolationPoints, INITIAL_TRUST_REGION_RADIUS, STOPPING_TRUST_REGION_RADIUS); // needed since one optimization found positive // charges (paying customer to consume...) double[][] boundaries = createBoundaries(NUM_RATES); final PointValuePair optimum = optimizer.optimize(new MaxEval(numEval), new ObjectiveFunction(new OptimizerWrapperApacheObjective(tariffUtilityEstimate)), GoalType.MAXIMIZE, new InitialGuess(startingVertex), //new SimpleBounds(boundaries[0], boundaries[1])); SimpleBounds.unbounded(NUM_RATES)); TreeMap<Double, TariffSpecification> eval2TOUTariff = new TreeMap<Double, TariffSpecification>(); eval2TOUTariff.put(optimum.getValue(), tariffUtilityEstimate.getCorrespondingSpec(optimum.getKey())); return eval2TOUTariff; }
From source file:edu.cmu.tetrad.regression.LogisticRegression2.java
public void regress(int[] target, int numValues, double[][] regressors) { try {/*from ww w .j a v a 2 s . c om*/ int numParams = regressors.length + 1; double[] coefficients = new double[(numValues - 1) * numParams]; // Apparently this needs to be fairly loose. int tolerance = 250; MultivariateOptimizer search = new PowellOptimizer(tolerance, tolerance); PointValuePair pair = search.optimize(new InitialGuess(coefficients), new ObjectiveFunction(new FittingFunction(target, regressors)), GoalType.MAXIMIZE, new MaxEval(1000000)); this.likelihood = pair.getValue(); } catch (TooManyEvaluationsException e) { e.printStackTrace(); this.likelihood = Double.NaN; } }
From source file:com.datumbox.framework.core.mathematics.linearprogramming.LPSolver.java
/** * Solves the LP problem and returns the result. * //from w ww .ja va 2s . c o m * @param linearObjectiveFunction * @param linearConstraintsList * @param nonNegative * @param maximize * @return */ public static LPResult solve(double[] linearObjectiveFunction, List<LPSolver.LPConstraint> linearConstraintsList, boolean nonNegative, boolean maximize) { int m = linearConstraintsList.size(); List<LinearConstraint> constraints = new ArrayList<>(m); for (LPSolver.LPConstraint constraint : linearConstraintsList) { String sign = constraint.getSign(); Relationship relationship = null; if (LPSolver.GEQ.equals(sign)) { relationship = Relationship.GEQ; } else if (LPSolver.LEQ.equals(sign)) { relationship = Relationship.LEQ; } else if (LPSolver.EQ.equals(sign)) { relationship = Relationship.EQ; } constraints .add(new LinearConstraint(constraint.getContraintBody(), relationship, constraint.getValue())); } SimplexSolver solver = new SimplexSolver(); PointValuePair solution = solver.optimize(new LinearObjectiveFunction(linearObjectiveFunction, 0.0), new LinearConstraintSet(constraints), maximize ? GoalType.MAXIMIZE : GoalType.MINIMIZE, new NonNegativeConstraint(nonNegative), PivotSelectionRule.BLAND); LPResult result = new LPResult(); result.setObjectiveValue(solution.getValue()); result.setVariableValues(solution.getPoint()); return result; }
From source file:net.sf.tweety.math.opt.solver.ApacheCommonsNonLinearConjugateGradientOptimizer.java
@Override public Map<Variable, Term> solve(ConstraintSatisfactionProblem problem) throws GeneralMathException { // only optimization problems if (!(problem instanceof OptimizationProblem)) throw new IllegalArgumentException("Only optimization problems allowed for this solver."); OptimizationProblem p = (OptimizationProblem) problem; // no constraints allowed if (!p.isEmpty()) throw new IllegalArgumentException( "Only optimization problems without constraints allowed for this solver."); final Term target = p.getTargetFunction(); final List<Variable> vars = new ArrayList<Variable>(target.getVariables()); MultivariateFunction acTarget = new MultivariateFunction() { @Override/*from w ww . jav a 2 s. com*/ public double value(double[] arg0) { return target.replaceAllTerms(arg0, vars).doubleValue(); } }; final Term[] targetGradient = new Term[vars.size()]; for (int i = 0; i < vars.size(); i++) targetGradient[i] = target.derive(vars.get(i)); MultivariateVectorFunction acTargetGradient = new MultivariateVectorFunction() { @Override public double[] value(double[] arg0) throws IllegalArgumentException { double[] result = new double[arg0.length]; for (int i = 0; i < arg0.length; i++) result[i] = targetGradient[i].replaceAllTerms(arg0, vars).doubleValue(); return result; } }; // create solver NonLinearConjugateGradientOptimizer optimizer = new NonLinearConjugateGradientOptimizer( NonLinearConjugateGradientOptimizer.Formula.FLETCHER_REEVES, new SimplePointChecker<PointValuePair>(this.precision, this.precision)); double[] s = new double[vars.size()]; for (int i = 0; i < vars.size(); i++) s[i] = 0.5; PointValuePair val = optimizer.optimize(new ObjectiveFunction(acTarget), new ObjectiveFunctionGradient(acTargetGradient), new InitialGuess(s), p.getType() == OptimizationProblem.MAXIMIZE ? GoalType.MAXIMIZE : GoalType.MINIMIZE, new MaxEval(this.maxEval)); Map<Variable, Term> result = new HashMap<Variable, Term>(); for (int i = 0; i < vars.size(); i++) result.put(vars.get(i), new FloatConstant(val.getPoint()[i])); return result; }
From source file:de.bund.bfr.math.MultivariateOptimization.java
@Override public Result optimize(int nParameterSpace, int nOptimizations, boolean stopWhenSuccessful, Map<String, Double> minStartValues, Map<String, Double> maxStartValues, int maxIterations, DoubleConsumer progessListener, ExecutionContext exec) throws CanceledExecutionException { if (exec != null) { exec.checkCanceled();//from ww w .ja va2 s . com } progessListener.accept(0.0); List<ParamRange> ranges = MathUtils.getParamRanges(parameters, minStartValues, maxStartValues, nParameterSpace); ranges.set(parameters.indexOf(sdParam), new ParamRange(1.0, 1, 1.0)); List<StartValues> startValuesList = MathUtils.createStartValuesList(ranges, nOptimizations, values -> optimizerFunction.value(Doubles.toArray(values)), progress -> progessListener.accept(0.5 * progress), exec); Result result = new Result(); AtomicInteger currentIteration = new AtomicInteger(); SimplexOptimizer optimizer = new SimplexOptimizer(new SimpleValueChecker(1e-10, 1e-10) { @Override public boolean converged(int iteration, PointValuePair previous, PointValuePair current) { if (super.converged(iteration, previous, current)) { return true; } return currentIteration.incrementAndGet() >= maxIterations; } }); int count = 0; for (StartValues startValues : startValuesList) { if (exec != null) { exec.checkCanceled(); } progessListener.accept(0.5 * count++ / startValuesList.size() + 0.5); try { PointValuePair optimizerResults = optimizer.optimize(new MaxEval(Integer.MAX_VALUE), new MaxIter(maxIterations), new InitialGuess(Doubles.toArray(startValues.getValues())), new ObjectiveFunction(optimizerFunction), GoalType.MAXIMIZE, new NelderMeadSimplex(parameters.size())); double logLikelihood = optimizerResults.getValue() != null ? optimizerResults.getValue() : Double.NaN; if (result.logLikelihood == null || logLikelihood > result.logLikelihood) { result = getResults(optimizerResults); if (result.logLikelihood == 0.0 || stopWhenSuccessful) { break; } } } catch (TooManyEvaluationsException | TooManyIterationsException | ConvergenceException e) { } } return result; }
From source file:net.sf.tweety.math.opt.solver.ApacheCommonsCMAESOptimizer.java
@Override public Map<Variable, Term> solve(ConstraintSatisfactionProblem problem) throws GeneralMathException { // only optimization problems if (!(problem instanceof OptimizationProblem)) throw new IllegalArgumentException("Only optimization problems allowed for this solver."); OptimizationProblem p = (OptimizationProblem) problem; // only box constraints allowed (so far) if (!p.isEmpty()) throw new IllegalArgumentException( "Only optimization problems with box constraints on variables allowed for this solver (no other constraints."); final List<Variable> vars = new ArrayList<Variable>(p.getTargetFunction().getVariables()); double[] lb = new double[vars.size()]; double[] ub = new double[vars.size()]; double[] s = new double[vars.size()]; double[] sigma = new double[vars.size()]; for (int i = 0; i < vars.size(); i++) { lb[i] = vars.get(i).getLowerBound(); ub[i] = vars.get(i).getUpperBound(); s[i] = (lb[i] + ub[i]) / 2;/*from w w w.j a va 2 s.co m*/ sigma[i] = ub[i] - lb[i]; } final Term targetFunction = p.getTargetFunction(); MultivariateFunction target = new MultivariateFunction() { @Override public double value(double[] arg0) { return targetFunction.replaceAllTerms(arg0, vars).doubleValue(); } }; // construct solver CMAESOptimizer optimizer = new CMAESOptimizer(this.maxIterations, this.stopFitness, this.isActiveCMA, this.diagonalOnly, this.checkFeasableCount, new JDKRandomGenerator(), false, new SimplePointChecker<PointValuePair>(this.precision, this.precision)); PointValuePair val = optimizer.optimize(new CMAESOptimizer.Sigma(sigma), new ObjectiveFunction(target), new InitialGuess(s), p.getType() == OptimizationProblem.MAXIMIZE ? GoalType.MAXIMIZE : GoalType.MINIMIZE, new MaxEval(this.maxIterations), new SimpleBounds(lb, ub), new CMAESOptimizer.PopulationSize(this.populationSize)); Map<Variable, Term> result = new HashMap<Variable, Term>(); for (int i = 0; i < vars.size(); i++) result.put(vars.get(i), new FloatConstant(val.getPoint()[i])); return result; }