Example usage for org.apache.commons.math3.optim MaxEval MaxEval

List of usage examples for org.apache.commons.math3.optim MaxEval MaxEval

Introduction

In this page you can find the example usage for org.apache.commons.math3.optim MaxEval MaxEval.

Prototype

public MaxEval(int max) 

Source Link

Usage

From source file:org.eclipse.dawnsci.analysis.dataset.roi.fitting.CircleCoordinatesFunction.java

@Override
public void geometricFit(IDataset x, IDataset y, double[] init) {
    residual = Double.NaN;//  w  w  w. j  a  v a  2s .  c  o  m
    if (x.getSize() < PARAMETERS || y.getSize() < PARAMETERS) {
        throw new IllegalArgumentException("Need " + PARAMETERS + " or more points");
    }

    if (x.getSize() == PARAMETERS) {
        init = quickfit(x, y);
        for (int i = 0; i < PARAMETERS; i++)
            parameters[i] = init[i];
        residual = 0;
        return;
    }

    if (init == null)
        init = quickfit(x, y);
    else if (init.length < PARAMETERS)
        throw new IllegalArgumentException("Need " + PARAMETERS + " parameters");

    CircleCoordinatesFunction f = (CircleCoordinatesFunction) getFitFunction(x, y);
    LevenbergMarquardtOptimizer opt = new LevenbergMarquardtOptimizer();

    try {
        PointVectorValuePair result = opt.optimize(new ModelFunction(f),
                new ModelFunctionJacobian(f.jacobian()), f.getTarget(), f.getWeight(),
                f.calcAllInitValues(init), new MaxEval(MAX_EVALUATIONS));

        double[] point = result.getPointRef();
        for (int i = 0; i < PARAMETERS; i++)
            parameters[i] = point[i];

        residual = opt.getRMS();
        logger.trace("Circle fit: rms = {}, x^2 = {}", opt.getRMS(), opt.getChiSquare());
    } catch (DimensionMismatchException e) {
        // cannot happen
    } catch (IllegalArgumentException e) {
        // should not happen!
    } catch (TooManyEvaluationsException e) {
        throw new IllegalArgumentException("Problem with optimizer converging");
    }
}

From source file:org.eclipse.dawnsci.analysis.dataset.roi.fitting.EllipseCoordinatesFunction.java

@Override
public void geometricFit(IDataset x, IDataset y, double[] init) {
    residual = Double.NaN;/*from   w  w  w . j a  v  a2 s  .  c o m*/
    if (x.getSize() < PARAMETERS || y.getSize() < PARAMETERS) {
        throw new IllegalArgumentException("Need " + PARAMETERS + " or more points");
    }

    if (init == null)
        init = quickfit(x, y);
    else if (init.length < PARAMETERS)
        throw new IllegalArgumentException("Need " + PARAMETERS + " parameters");

    EllipseCoordinatesFunction f = (EllipseCoordinatesFunction) getFitFunction(x, y);
    LevenbergMarquardtOptimizer opt = new LevenbergMarquardtOptimizer();

    try {
        PointVectorValuePair result = opt.optimize(new ModelFunction(f),
                new ModelFunctionJacobian(f.jacobian()), f.getTarget(), f.getWeight(),
                f.calcAllInitValues(init), new MaxEval(MAX_EVALUATIONS));

        double[] point = result.getPointRef();
        for (int i = 0; i < PARAMETERS; i++)
            parameters[i] = point[i];

        residual = opt.getRMS();

        logger.trace("Ellipse fit: rms = {}, x^2 = {}", residual, opt.getChiSquare());
    } catch (DimensionMismatchException e) {
        // cannot happen
    } catch (IllegalArgumentException e) {
        // should not happen!
    } catch (TooManyEvaluationsException e) {
        throw new IllegalArgumentException("Problem with optimizer converging");
    }
}

From source file:org.hawkular.datamining.forecast.models.AbstractModelOptimizer.java

protected void optimize(double[] initialGuess, MultivariateFunctionMappingAdapter costFunction) {

    // Nelder-Mead Simplex
    SimplexOptimizer optimizer = new SimplexOptimizer(0.0001, 0.0001);
    PointValuePair unBoundedResult = optimizer.optimize(GoalType.MINIMIZE, new MaxIter(MAX_ITER),
            new MaxEval(MAX_EVAL), new InitialGuess(initialGuess), new ObjectiveFunction(costFunction),
            new NelderMeadSimplex(initialGuess.length));

    result = costFunction.unboundedToBounded(unBoundedResult.getPoint());
}

From source file:org.hawkular.datamining.forecast.models.performance.OptimizationAlgorithmsTests.java

private long executeSimplex(ModelData modelData) {
    long start = System.nanoTime();
    SimplexOptimizer optimizer = new SimplexOptimizer(0.00001, 0.00001);
    PointValuePair unbounded = optimizer.optimize(GoalType.MINIMIZE, new MaxIter(MAX_ITER),
            new MaxEval(MAX_EVAL), new InitialGuess(INITIAL_GUESS), new ObjectiveFunction(objectiveFunction),
            new NelderMeadSimplex(2));
    long executionTime = System.nanoTime() - start;

    printOptimizationResult(objectiveFunction, unbounded.getPoint(), modelData);

    return executionTime;
}

From source file:org.hawkular.datamining.forecast.models.performance.OptimizationAlgorithmsTests.java

private long executeMultidirectionalSimplex(ModelData modelData) {
    long start = System.nanoTime();
    SimplexOptimizer optimizer = new SimplexOptimizer(0.00001, 0.00001);
    PointValuePair unbounded = optimizer.optimize(GoalType.MINIMIZE, new MaxIter(MAX_ITER),
            new MaxEval(MAX_EVAL), new InitialGuess(INITIAL_GUESS), new ObjectiveFunction(objectiveFunction),
            new MultiDirectionalSimplex(2));
    long executionTime = System.nanoTime() - start;

    printOptimizationResult(objectiveFunction, unbounded.getPoint(), modelData);

    return executionTime;
}

From source file:org.hawkular.datamining.forecast.models.performance.OptimizationAlgorithmsTests.java

private long executeBobyQA(ModelData modelData) {
    long start = System.nanoTime();
    BOBYQAOptimizer optimizer = new BOBYQAOptimizer(6);
    PointValuePair bobyQAResult = optimizer.optimize(GoalType.MINIMIZE, new MaxEval(MAX_EVAL),
            new MaxIter(MAX_ITER), new InitialGuess(INITIAL_GUESS), new ObjectiveFunction(objectiveFunction),
            SimpleBounds.unbounded(2));//from w w  w  .  j ava2 s . c om
    long executionTime = System.nanoTime() - start;

    printOptimizationResult(objectiveFunction, bobyQAResult.getPoint(), modelData);

    return executionTime;
}

From source file:org.hawkular.datamining.forecast.models.performance.OptimizationAlgorithmsTests.java

private long executePowell(ModelData modelData) {
    long start = System.nanoTime();
    PowellOptimizer optimizer = new PowellOptimizer(0.00001, 0.00001);
    PointValuePair unbounded = optimizer.optimize(GoalType.MINIMIZE, new MaxIter(MAX_ITER),
            new MaxEval(MAX_EVAL), new InitialGuess(INITIAL_GUESS), new ObjectiveFunction(objectiveFunction));
    long executionTime = System.nanoTime() - start;

    printOptimizationResult(objectiveFunction, unbounded.getPoint(), modelData);

    return executionTime;
}

From source file:playground.thibautd.initialdemandgeneration.socnetgensimulated.framework.ModelIterator.java

public SocialNetwork iterateModelToTarget(final ModelRunner runner, final Thresholds initialThresholds) {
    final MultivariateOptimizer optimizer = new CMAESOptimizer(maxIterations, 1E-9, true, 3, 50,
            new MersenneTwister(42), false, new Convergence());

    final double x = initialThresholds.getPrimaryThreshold();
    final double y = initialThresholds.getSecondaryReduction();

    final PointValuePair result = optimizer.optimize(GoalType.MINIMIZE, new MaxEval(maxIterations),
            new InitialGuess(new double[] { x, y }), new ObjectiveFunction(new Function(runner)),
            new CMAESOptimizer.Sigma(new double[] { 5, 500 }), new CMAESOptimizer.PopulationSize(7),
            new SimpleBounds(new double[] { Double.NEGATIVE_INFINITY, 0 }, // lower bounds: constrain secondary reduction to be positive
                    new double[] { Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY }) // upper bounds
    );/*from   ww  w.  j  a v a  2s . c  om*/

    final Thresholds bestThresholds = new Thresholds(result.getPoint()[0], result.getPoint()[1]);
    final SocialNetwork bestSn = generate(runner, bestThresholds);

    log.info("best social network found for thresholds: " + bestThresholds);

    return bestSn;
}

From source file:smlm.fitting.FittingClassical.java

@SuppressWarnings("unused")
@Override/* ww w  .j a  v  a 2 s. c o  m*/
public boolean FitThis() {

    // Initial estimates (your initial x)
    // Calculating the centroid
    ImageStatistics stat = roi.getStatistics();
    double x0 = stat.xCenterOfMass;
    double y0 = stat.yCenterOfMass;
    double[] start = { x0, y0, param.psfSigma, param.psfSigma, i0Max, backgroundLevel };

    PointValuePair solutionMult = null;
    MultivariateFunctionMappingAdapter fitFunc = null;

    if (param.fitting != Params.Fitting.CentroidFit) {
        // initial step sizes (take a good guess)
        double[] step = { 1, 1, 0.1, 0.1, stdBackground, stdBackground };
        // convergence tolerance
        double ftol = 0.0001;// 0.000001;
        pixelPrecision = 3;// 5;

        if (param.fitting == Params.Fitting.FastGaussianFit) {
            ftol = 0.1;
            pixelPrecision = 3;
        }

        SimplexOptimizer Fit = new SimplexOptimizer(ftol, ftol * ftol);
        double[] low = new double[] { 0, 0, 0, 0, 0, 0 };
        double[] up = new double[] { roi.getWidth(), roi.getHeight(), Double.POSITIVE_INFINITY,
                Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY };
        fitFunc = new MultivariateFunctionMappingAdapter(new LLH(), low, up);

        // maximal number of iterations
        int maxIter = 5000;
        // Nelder and Mead maximisation procedure
        // x0 e [0, xmax]
        // Fit.addConstraint(0, -1, 0);
        // Fit.addConstraint(0, 1, roi.getWidth());
        // y0 e [0, ymax]
        // Fit.addConstraint(1, -1, 0);
        // Fit.addConstraint(1, 1, roi.getHeight());
        /*
         * // sigmax e [PSFSigma/3, 3*PSFSigma] Fit.addConstraint(2, -1,
         * PSFSigmaInt-PSFSigmaInt/2); Fit.addConstraint(2, 1,
         * 2*PSFSigmaInt); // sigmay e [PSFSigma/3, 3*PSFSigma]
         * Fit.addConstraint(3, -1, PSFSigmaInt-PSFSigmaInt/2);
         * Fit.addConstraint(3, 1, 2*PSFSigmaInt); // I0 e [StdBackground,
         * 50*Intensities[i]] Fit.addConstraint(4, -1, StdBackground);
         * Fit.addConstraint(4, 1, 50*XY[3][i]); // PoissonNoise e
         * [BackgroundLevel/3, 3*BackgroundLevel] Fit.addConstraint(5, -1,
         * BackgroundLevel/3); Fit.addConstraint(5, 1, 3*BackgroundLevel);
         */

        solutionMult = Fit.optimize(new MaxEval(maxIter), new ObjectiveFunction(fitFunc), GoalType.MAXIMIZE,
                new InitialGuess(fitFunc.boundedToUnbounded(start)), new MultiDirectionalSimplex(step));
    }

    // Result of minimisation
    // Save the fit results
    this.fit.incrementCounter();
    if (param.fitting == Params.Fitting.CentroidFit) {
        results = start;
    } else {
        results = fitFunc.unboundedToBounded(solutionMult.getPoint());
    }
    for (int i = 0; i < isArgumentFixed.length; i++) {
        if (isArgumentFixed[i]) {
            results[i] = fixedArguments[i];
        }
    }

    if (cycle != -1)
        this.fit.addValue(ResultsTableMt.CYCLE, cycle);
    this.fit.addValue(ResultsTableMt.FRAME, realFrame);
    this.fit.addValue(ResultsTableMt.X0, results[0] + xMax - ((double) roiWidth * param.psfSigmaInt));
    this.fit.addValue(ResultsTableMt.Y0, results[1] + yMax - ((double) roiWidth * param.psfSigmaInt));
    this.fit.addValue(ResultsTableMt.SIGMAX, results[2]);
    this.fit.addValue(ResultsTableMt.SIGMAY, results[3]);
    this.fit.addValue(ResultsTableMt.I0, results[4]);
    this.fit.addValue(ResultsTableMt.NOISE, results[5]);

    if (param.fitting == Params.Fitting.CentroidFit || true) {
        this.fit.addValue(ResultsTableMt.IS_FITTED, 1);
        if (param.fitting != Params.Fitting.CentroidFit) {
            this.fit.addValue("MinFit", solutionMult.getValue());
        }
    } else
        this.fit.addValue(ResultsTableMt.IS_FITTED, 0);

    // Save results
    if (param.debug) {
        DrawInitialRoi(true);
        DrawFit(true);
    }
    return true;
}

From source file:uk.ac.diamond.scisoft.analysis.diffraction.FittingUtils.java

/**
 * Optimize given function//  www . j a v  a2  s. co  m
 * @param f
 * @param opt
 * @param min
 * @return residual
 */
public static double optimize(FitFunction f, MultivariateOptimizer opt, double min) {
    double res = Double.NaN;
    try {
        PointValuePair result;

        if (opt instanceof BOBYQAOptimizer) {
            result = opt.optimize(new InitialGuess(f.getInitial()), GoalType.MINIMIZE, new ObjectiveFunction(f),
                    new MaxEval(MAX_EVAL), f.getBounds());
        } else if (opt instanceof CMAESOptimizer) {
            int p = (int) Math.ceil(4 + Math.log(f.getN())) + 1;
            logger.trace("Population size: {}", p);
            result = opt.optimize(new InitialGuess(f.getInitial()), GoalType.MINIMIZE, new ObjectiveFunction(f),
                    new CMAESOptimizer.Sigma(f.getSigma()), new CMAESOptimizer.PopulationSize(p),
                    new MaxEval(MAX_EVAL), f.getBounds());
        } else {
            int n = f.getN();
            double offset = 1e12;
            double[] scale = new double[n];
            for (int i = 0; i < n; i++) {
                scale[i] = offset * 0.25;
            }
            SimpleBounds bnds = f.getBounds();
            MultivariateFunctionPenaltyAdapter of = new MultivariateFunctionPenaltyAdapter(f, bnds.getLower(),
                    bnds.getUpper(), offset, scale);
            result = opt.optimize(new InitialGuess(f.getInitial()), GoalType.MINIMIZE,
                    new ObjectiveFunction(of), new MaxEval(MAX_EVAL), new MultiDirectionalSimplex(n));
            //            new NelderMeadSimplex(n));
        }

        // logger.info("Q-space fit: rms = {}, x^2 = {}", opt.getRMS(), opt.getChiSquare());
        double ires = f.value(opt.getStartPoint());
        logger.trace("Residual: {} from {}", result.getValue(), ires);
        res = result.getValue();
        if (res < min)
            f.setParameters(result.getPoint());
        logger.trace("Used {} evals and {} iters", opt.getEvaluations(), opt.getIterations());
        //         System.err.printf("Used %d evals and %d iters\n", opt.getEvaluations(), opt.getIterations());
        // logger.info("Q-space fit: rms = {}, x^2 = {}", opt.getRMS(), opt.getChiSquare());
    } catch (IllegalArgumentException e) {
        logger.error("Start point has wrong dimension", e);
        // should not happen!
    } catch (TooManyEvaluationsException e) {
        throw new IllegalArgumentException("Could not fit as optimizer did not converge");
        //            logger.error("Convergence problem: max iterations ({}) exceeded", opt.getMaxIterations());
    }

    return res;
}