Example usage for org.apache.commons.math.optimization GoalType MAXIMIZE

List of usage examples for org.apache.commons.math.optimization GoalType MAXIMIZE

Introduction

In this page you can find the example usage for org.apache.commons.math.optimization GoalType MAXIMIZE.

Prototype

GoalType MAXIMIZE

To view the source code for org.apache.commons.math.optimization GoalType MAXIMIZE.

Click Source Link

Document

Maximization goal.

Usage

From source file:fi.smaa.libror.UTAGMSSolver.java

public void solve(RelationsType rel) throws InfeasibleConstraintsException {
    necessaryRelation = new Array2DRowRealMatrix(model.getNrAlternatives(), model.getNrAlternatives());
    possibleRelation = new Array2DRowRealMatrix(model.getNrAlternatives(), model.getNrAlternatives());
    List<LinearConstraint> baseConstraints = buildRORConstraints();

    // check that the set of constraints is feasible
    try {// w w w  .j  a  v a2  s  .  c  o m
        RealPointValuePair res = solver.optimize(buildObjectiveFunction(), baseConstraints, GoalType.MAXIMIZE,
                true);
        if (res.getValue() <= 0.0) {
            throw new InfeasibleConstraintsException(
                    "Preference information leading to infeasible constraints, epsilon <= 0.0");
        }
    } catch (OptimizationException e) {
        throw new InfeasibleConstraintsException(
                "Preference information leading to infeasible constraints: " + e.getMessage());
    }

    for (int i = 0; i < model.getNrAlternatives(); i++) {
        for (int j = 0; j < model.getNrAlternatives(); j++) {
            boolean necHolds = false;
            if (rel.equals(RelationsType.NECESSARY) || rel.equals(RelationsType.BOTH)) {
                necHolds = solveRelation(i, j, baseConstraints, true);
                necessaryRelation.setEntry(i, j, necHolds ? 1.0 : 0.0);
            }
            if (rel.equals(RelationsType.POSSIBLE) || rel.equals(RelationsType.BOTH)) {
                if (necHolds) {
                    possibleRelation.setEntry(i, j, 1.0);
                } else {
                    possibleRelation.setEntry(i, j, solveRelation(i, j, baseConstraints, false) ? 1.0 : 0.0);
                }
            }
        }
    }
}

From source file:OughtaFocus.java

private double runAutofocusAlgorithm() throws Exception {
    UnivariateRealFunction scoreFun = new UnivariateRealFunction() {
        public double value(double d) throws FunctionEvaluationException {
            try {
                return measureFocusScore(d);
            } catch (Exception e) {
                throw new FunctionEvaluationException(e, d);
            }//from ww w  .  ja  v  a2 s.c o  m
        }
    };
    BrentOptimizer brentOptimizer = new BrentOptimizer();
    brentOptimizer.setAbsoluteAccuracy(tolerance);
    imageCount_ = 0;

    CMMCore core = app_.getMMCore();
    double z = core.getPosition(core.getFocusDevice());
    startZUm_ = z;
    //      getCurrentFocusScore();
    double zResult = brentOptimizer.optimize(scoreFun, GoalType.MAXIMIZE, z - searchRange / 2,
            z + searchRange / 2);
    ReportingUtils.logMessage("OughtaFocus Iterations: " + brentOptimizer.getIterationCount() + ", z="
            + TextUtils.FMT2.format(zResult) + ", dz=" + TextUtils.FMT2.format(zResult - startZUm_) + ", t="
            + (System.currentTimeMillis() - startTimeMs_));
    return zResult;
}

From source file:net.sf.tweety.math.opt.solver.ApacheCommonsSimplex.java

@Override
public Map<Variable, Term> solve(ConstraintSatisfactionProblem problem) {
    if (!problem.isLinear())
        throw new IllegalArgumentException("Simplex algorithm is for linear problems only.");
    //this.log.info("Wrapping optimization problem for calling the Apache Commons Simplex algorithm.");            
    // 1.) bring all constraints in linear and normalized form
    Set<Statement> constraints = new HashSet<Statement>();
    for (Statement s : problem)
        constraints.add(s.toNormalizedForm().toLinearForm());
    // 2.) for every constraint we need an extra variable
    int numVariables = problem.getVariables().size();
    // 3.) define mappings from variables to indices
    int index = 0;
    Map<Variable, Integer> origVars2Idx = new HashMap<Variable, Integer>();
    for (Variable v : problem.getVariables())
        origVars2Idx.put(v, index++);/*from  ww  w .  j  a va  2s . com*/
    // 4.) Check for target function (for constraint satisfaction problems
    //      its empty
    double[] coefficientsTarget = new double[numVariables];
    int i = 0;
    for (; i < numVariables; i++)
        coefficientsTarget[i] = 0;
    double constTerm = 0;
    if (problem instanceof OptimizationProblem) {
        // bring target function in linear form
        Sum t = ((OptimizationProblem) problem).getTargetFunction().toLinearForm();
        for (Term summand : t.getTerms()) {
            // as t is in linear form every summand is a product
            Product p = (Product) summand;
            if (p.getTerms().size() == 1) {
                // p consists of just a constant term
                Constant c = (Constant) p.getTerms().get(0);
                if (c instanceof FloatConstant)
                    constTerm += ((FloatConstant) c).getValue();
                else
                    constTerm += ((IntegerConstant) c).getValue();
            } else {
                // p consists of a variable and a constant
                Variable v = (Variable) ((p.getTerms().get(0) instanceof Variable) ? (p.getTerms().get(0))
                        : (p.getTerms().get(1)));
                Constant c = (Constant) ((p.getTerms().get(0) instanceof Constant) ? (p.getTerms().get(0))
                        : (p.getTerms().get(1)));
                double coefficient = (c instanceof FloatConstant) ? (((FloatConstant) c).getValue())
                        : (((IntegerConstant) c).getValue());
                coefficientsTarget[origVars2Idx.get(v)] += coefficient;
            }
        }
    }
    LinearObjectiveFunction target = new LinearObjectiveFunction(coefficientsTarget, constTerm);
    // 5.) Represent the constraints
    Set<LinearConstraint> finalConstraints = new HashSet<LinearConstraint>();
    for (Statement s : constraints) {
        double[] coefficientsConstraint = new double[numVariables];
        for (i = 0; i < numVariables; i++)
            coefficientsConstraint[i] = 0;
        // as s is in linear form go through the summands
        Sum leftTerm = (Sum) s.getLeftTerm();
        double rest = 0;
        for (Term summand : leftTerm.getTerms()) {
            // as s is in linear form every summand is a product
            Product p = (Product) summand;
            if (p.getTerms().size() == 1) {
                // p consists of just a constant term
                Constant c = (Constant) p.getTerms().get(0);
                if (c instanceof FloatConstant)
                    rest += ((FloatConstant) c).getValue();
                else
                    rest += ((IntegerConstant) c).getValue();
            } else {
                // p consists of a variable and a constant
                Variable v = (Variable) ((p.getTerms().get(0) instanceof Variable) ? (p.getTerms().get(0))
                        : (p.getTerms().get(1)));
                Constant c = (Constant) ((p.getTerms().get(0) instanceof Constant) ? (p.getTerms().get(0))
                        : (p.getTerms().get(1)));
                double coefficient = (c instanceof FloatConstant) ? (((FloatConstant) c).getValue())
                        : (((IntegerConstant) c).getValue());
                coefficientsConstraint[origVars2Idx.get(v)] += coefficient;
            }
        }
        Relationship r = Relationship.EQ;
        if (s instanceof Inequation)
            r = Relationship.GEQ;
        finalConstraints.add(new LinearConstraint(coefficientsConstraint, r, -rest));
    }
    // 6.) Optimize.
    try {
        //this.log.info("Calling the Apache Commons Simplex algorithm.");
        SimplexSolver solver = new SimplexSolver(0.01);
        solver.setMaxIterations(this.MAXITERATIONS);
        RealPointValuePair r = null;
        if (problem instanceof OptimizationProblem) {
            int type = ((OptimizationProblem) problem).getType();
            r = solver.optimize(target, finalConstraints,
                    (type == OptimizationProblem.MINIMIZE) ? (GoalType.MINIMIZE) : (GoalType.MAXIMIZE),
                    this.onlyPositive);
        } else
            r = solver.optimize(target, finalConstraints, GoalType.MINIMIZE, this.onlyPositive);
        //this.log.info("Parsing output from the Apache Commons Simplex algorithm.");
        Map<Variable, Term> result = new HashMap<Variable, Term>();
        for (Variable v : origVars2Idx.keySet())
            result.put(v, new FloatConstant(r.getPoint()[origVars2Idx.get(v)]));
        return result;
    } catch (OptimizationException e) {
        //log.error(e.getMessage());
        throw new ProblemInconsistentException();
    }
}

From source file:fi.smaa.libror.UTAGMSSolver.java

/**
 * Check whether relation holds.//from   ww  w . j  ava2s.c o m
 * 
 * @param i index of first alternative, PRECOND: >= 0
 * @param j index of the second alternative, PRECOND: >= 0
 * @param rorConstraints base constraints E_{ROR}^{A^R}
 * @param necessary true if the relation solved is the necessary one, false otherwise
 * @return
 */
private boolean solveRelation(int i, int j, List<LinearConstraint> rorConstraints, boolean necessary) {
    if (i < 0 && j < 0) {
        throw new IllegalArgumentException("PRECOND violation");
    }

    if (i == j) {
        return true;
    }

    List<LinearConstraint> constraints = new ArrayList<LinearConstraint>(rorConstraints);
    addNecOrPrefConstraint(i, j, necessary, constraints);
    LinearObjectiveFunction goalFunction = buildObjectiveFunction();

    try {
        RealPointValuePair res = solver.optimize(goalFunction, constraints, GoalType.MAXIMIZE, true);
        if (necessary) {
            return res.getValue() <= 0.0;
        } else { // possible
            return res.getValue() > 0.0;
        }

    } catch (NoFeasibleSolutionException e) {
        if (necessary) {
            return true;
        } else { // possible
            return false;
        }
    } catch (OptimizationException e) {
        throw new IllegalStateException("Invalid OptimizationException: " + e.getMessage());
    }
}

From source file:Align_Projections.java

public void run() {

    detectorAngle = Double.valueOf(detectorAngleText.getText()).doubleValue();
    centerPixel = Double.valueOf(centerPixelText.getText()).doubleValue();
    horizontalBorder = Integer.valueOf(horizontalBorderText.getText()).intValue();
    topBorder = Integer.valueOf(topBorderText.getText()).intValue();
    bottomBorder = Integer.valueOf(bottomBorderText.getText()).intValue();

    // IJ.log("Starting worker thread");
    int count = 0;
    double[] x = new double[2];
    x[0] = centerPixel * tuningWeights[0];
    x[1] = detectorAngle * tuningWeights[1];
    PowellOptimizer maximizer = new PowellOptimizer(1E-4);
    maximizer.setConvergenceChecker(new ConvergenceCheckerWithManualCancel(this, 1E-4, 1E-4));
    maximizer.setMaxEvaluations(1000000);
    maximizer.setMaxIterations(1000000);
    try {/*  w  w  w  .  java  2  s . c  om*/
        // IJ.log("Starting optimization first round");
        RealPointValuePair result = maximizer.optimize(this, GoalType.MAXIMIZE, x);
        centerPixel = result.getPoint()[0] / tuningWeights[0];
        detectorAngle = result.getPoint()[1] / tuningWeights[1];
        centerPixelText.setText(IJ.d2s(centerPixel, 6));
        detectorAngleText.setText(IJ.d2s(detectorAngle, 6));
        crossCorrelation = result.getValue();
        updateCrossCorrelation();
    } catch (GetMeOuttaHereException e) {
    } catch (Exception e) {
        IJ.log("Exception occurred in optimizer.");
        stopTuning = true;
    }
    // Now do the whole thing again, but with narrower tolerances (the defaults, which are roughly machine precision)
    if (!stopTuning) {
        maximizer = new PowellOptimizer();
        maximizer.setConvergenceChecker(new ConvergenceCheckerWithManualCancel(this));
        maximizer.setMaxEvaluations(1000000);
        maximizer.setMaxIterations(1000000);
        try {
            // IJ.log("Starting optimization second round");
            RealPointValuePair result = maximizer.optimize(this, GoalType.MAXIMIZE, x);
            centerPixel = result.getPoint()[0] / tuningWeights[0];
            detectorAngle = result.getPoint()[1] / tuningWeights[1];
            centerPixelText.setText(IJ.d2s(centerPixel, 6));
            detectorAngleText.setText(IJ.d2s(detectorAngle, 6));
            crossCorrelation = result.getValue();
            updateCrossCorrelation();
        } catch (GetMeOuttaHereException e) {
        } catch (Exception e) {
            IJ.log("Exception occurred in optimizer.");
        }
    }

    UpdateOverlayAndControls();
    optimizeButton.setLabel("Optimize");
    optimizeButton.setEnabled(true);
    updateButton.setEnabled(true);
    applyButton.setEnabled(true);
    resetButton.setEnabled(true);
    detectorAngleText.setEnabled(true);
    centerPixelText.setEnabled(true);
    horizontalBorderText.setEnabled(true);
    topBorderText.setEnabled(true);
    bottomBorderText.setEnabled(true);
    // IJ.log("Exiting worker thread");
}

From source file:ch.algotrader.simulation.SimulationExecutorImpl.java

/**
 * {@inheritDoc}/*  ww w  . jav  a2 s.  c  o m*/
 */
@Override
public OptimizationResultVO optimizeSingleParam(final StrategyGroup strategyGroup, final String parameter,
        final double min, final double max, final double accuracy) {

    Validate.notEmpty(parameter, "Parameter is empty");

    try {
        UnivariateRealFunction function = new UnivariateFunction(this, strategyGroup, parameter);
        UnivariateRealOptimizer optimizer = new BrentOptimizer();
        optimizer.setAbsoluteAccuracy(accuracy);
        optimizer.optimize(function, GoalType.MAXIMIZE, min, max);
        OptimizationResultVO optimizationResult = new OptimizationResultVO();
        optimizationResult.setParameter(parameter);
        optimizationResult.setResult(optimizer.getResult());
        optimizationResult.setFunctionValue(optimizer.getFunctionValue());
        optimizationResult.setIterations(optimizer.getIterationCount());

        return optimizationResult;
    } catch (MathException ex) {
        throw new SimulationExecutorException(ex);
    }
}

From source file:ch.algotrader.simulation.SimulationExecutorImpl.java

/**
 * {@inheritDoc}//from   w  w w  .  java  2 s  .c om
 */
@Override
public void optimizeMultiParam(final StrategyGroup strategyGroup, final String[] parameters,
        final double[] starts) {

    Validate.notNull(parameters, "Parameter is null");
    Validate.notNull(starts, "Starts is null");

    RealPointValuePair result;
    try {
        MultivariateRealFunction function = new MultivariateFunction(this, strategyGroup, parameters);
        MultivariateRealOptimizer optimizer = new MultiDirectional();
        optimizer.setConvergenceChecker(new SimpleScalarValueChecker(0.0, 0.01));
        result = optimizer.optimize(function, GoalType.MAXIMIZE, starts);
        if (RESULT_LOGGER.isInfoEnabled()) {
            for (int i = 0; i < result.getPoint().length; i++) {
                RESULT_LOGGER.info("optimal value for {}={}", parameters[i],
                        format.format(result.getPoint()[i]));
            }
            RESULT_LOGGER.info("functionValue: {} needed iterations: {})", format.format(result.getValue()),
                    optimizer.getEvaluations());
        }
    } catch (MathException ex) {
        throw new SimulationExecutorException(ex);
    }
}

From source file:org.rascalmpl.library.analysis.linearprogramming.LinearProgramming.java

public IValue llOptimize(IBool minimize, IBool nonNegative, ISet constraints, IConstructor f) {
    SimplexSolver solver = new SimplexSolver();
    ArrayList<LinearConstraint> constraintsJ = new ArrayList<LinearConstraint>(constraints.size());
    for (IValue v : constraints) {
        constraintsJ.add(convertConstraint((IConstructor) v));
    }//  w  w w.  jav a  2s. c  om
    LinearObjectiveFunction fJ = convertLinObjFun(f);
    GoalType goal = minimize.getValue() ? GoalType.MINIMIZE : GoalType.MAXIMIZE;
    IValueFactory vf = values;
    boolean nonNegativeJ = nonNegative.getValue();
    try {
        RealPointValuePair res = solver.optimize(fJ, constraintsJ, goal, nonNegativeJ);
        return vf.constructor(Maybe.Maybe_just, vf.constructor(LLSolution_llSolution,
                convertToRealList(res.getPoint(), vf), vf.real(res.getValue())));
    } catch (Exception e) {
        return vf.constructor(Maybe.Maybe_nothing);
    }

}