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

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

Introduction

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

Prototype

public SimpleBounds(double[] lB, double[] uB) 

Source Link

Usage

From source file:gdsc.smlm.ij.plugins.pcpalm.PCPALMFitting.java

private PointValuePair runBoundedOptimiser(double[][] gr, double[] initialSolution, double[] lB, double[] uB,
        SumOfSquaresModelFunction function) {
    // Create the functions to optimise
    ObjectiveFunction objective = new ObjectiveFunction(new SumOfSquaresMultivariateFunction(function));
    ObjectiveFunctionGradient gradient = new ObjectiveFunctionGradient(
            new SumOfSquaresMultivariateVectorFunction(function));

    final boolean debug = false;

    // Try a BFGS optimiser since this will produce a deterministic solution and can respect bounds.
    PointValuePair optimum = null;/* w ww. j av a2s . c  om*/
    boundedEvaluations = 0;
    final MaxEval maxEvaluations = new MaxEval(2000);
    MultivariateOptimizer opt = null;
    for (int iteration = 0; iteration <= fitRestarts; iteration++) {
        try {
            opt = new BFGSOptimizer();
            final double relativeThreshold = 1e-6;

            // Configure maximum step length for each dimension using the bounds
            double[] stepLength = new double[lB.length];
            for (int i = 0; i < stepLength.length; i++)
                stepLength[i] = (uB[i] - lB[i]) * 0.3333333;

            // The GoalType is always minimise so no need to pass this in
            optimum = opt.optimize(maxEvaluations, gradient, objective,
                    new InitialGuess((optimum == null) ? initialSolution : optimum.getPointRef()),
                    new SimpleBounds(lB, uB), new BFGSOptimizer.GradientTolerance(relativeThreshold),
                    new BFGSOptimizer.StepLength(stepLength));
            if (debug)
                System.out.printf("BFGS Iter %d = %g (%d)\n", iteration, optimum.getValue(),
                        opt.getEvaluations());
        } catch (TooManyEvaluationsException e) {
            break; // No need to restart
        } catch (RuntimeException e) {
            break; // No need to restart
        } finally {
            boundedEvaluations += opt.getEvaluations();
        }
    }

    // Try a CMAES optimiser which is non-deterministic. To overcome this we perform restarts.

    // CMAESOptimiser based on Matlab code:
    // https://www.lri.fr/~hansen/cmaes.m
    // Take the defaults from the Matlab documentation
    double stopFitness = 0; //Double.NEGATIVE_INFINITY;
    boolean isActiveCMA = true;
    int diagonalOnly = 0;
    int checkFeasableCount = 1;
    RandomGenerator random = new Well44497b(); //Well19937c();
    boolean generateStatistics = false;
    ConvergenceChecker<PointValuePair> checker = new SimpleValueChecker(1e-6, 1e-10);
    // The sigma determines the search range for the variables. It should be 1/3 of the initial search region.
    double[] range = new double[lB.length];
    for (int i = 0; i < lB.length; i++)
        range[i] = (uB[i] - lB[i]) / 3;
    OptimizationData sigma = new CMAESOptimizer.Sigma(range);
    OptimizationData popSize = new CMAESOptimizer.PopulationSize(
            (int) (4 + Math.floor(3 * Math.log(initialSolution.length))));
    SimpleBounds bounds = new SimpleBounds(lB, uB);

    opt = new CMAESOptimizer(maxEvaluations.getMaxEval(), stopFitness, isActiveCMA, diagonalOnly,
            checkFeasableCount, random, generateStatistics, checker);
    // Restart the optimiser several times and take the best answer.
    for (int iteration = 0; iteration <= fitRestarts; iteration++) {
        try {
            // Start from the initial solution
            PointValuePair constrainedSolution = opt.optimize(new InitialGuess(initialSolution), objective,
                    GoalType.MINIMIZE, bounds, sigma, popSize, maxEvaluations);
            if (debug)
                System.out.printf("CMAES Iter %d initial = %g (%d)\n", iteration,
                        constrainedSolution.getValue(), opt.getEvaluations());
            boundedEvaluations += opt.getEvaluations();
            if (optimum == null || constrainedSolution.getValue() < optimum.getValue()) {
                optimum = constrainedSolution;
            }
        } catch (TooManyEvaluationsException e) {
        } catch (TooManyIterationsException e) {
        } finally {
            boundedEvaluations += maxEvaluations.getMaxEval();
        }
        if (optimum == null)
            continue;
        try {
            // Also restart from the current optimum
            PointValuePair constrainedSolution = opt.optimize(new InitialGuess(optimum.getPointRef()),
                    objective, GoalType.MINIMIZE, bounds, sigma, popSize, maxEvaluations);
            if (debug)
                System.out.printf("CMAES Iter %d restart = %g (%d)\n", iteration,
                        constrainedSolution.getValue(), opt.getEvaluations());
            if (constrainedSolution.getValue() < optimum.getValue()) {
                optimum = constrainedSolution;
            }
        } catch (TooManyEvaluationsException e) {
        } catch (TooManyIterationsException e) {
        } finally {
            boundedEvaluations += maxEvaluations.getMaxEval();
        }
    }
    return optimum;
}

From source file:gdsc.smlm.ij.plugins.TraceDiffusion.java

/**
 * Fit the jump distance histogram using a cumulative sum as detailed in
 * <p>/*from   w  w w. java2  s. com*/
 * Update the plot by adding the fit line.
 * 
 * @param jumpDistances
 * @param jdHistogram
 * @param title
 * @param plot
 * @return
 */
private double[][] fitJumpDistance(StoredDataStatistics jumpDistances, double[][] jdHistogram, String title,
        Plot2 plot) {
    final double meanDistance = Math.sqrt(jumpDistances.getMean()) * 1e3;
    final double beta = meanDistance / precision;
    Utils.log(
            "Jump Distance analysis : N = %d, Time = %d frames (%s seconds). Mean Distance = %s nm, Precision = %s nm, Beta = %s",
            jumpDistances.getN(), settings.jumpDistance, Utils.rounded(settings.jumpDistance * exposureTime, 4),
            Utils.rounded(meanDistance, 4), Utils.rounded(precision, 4), Utils.rounded(beta, 4));
    int n = 0;
    int N = 10;
    double[] SS = new double[N];
    Arrays.fill(SS, -1);
    double[] ic = new double[N];
    Arrays.fill(ic, Double.POSITIVE_INFINITY);
    double[][] coefficients = new double[N][];
    double[][] fractions = new double[N][];
    double[][] fitParams = new double[N][];
    double bestIC = Double.POSITIVE_INFINITY;
    int best = -1;

    // Guess the D
    final double estimatedD = jumpDistances.getMean() / 4;
    Utils.log("Estimated D = %s um^2/s", Utils.rounded(estimatedD, 4));

    // Fit using a single population model
    LevenbergMarquardtOptimizer optimizer = new LevenbergMarquardtOptimizer();
    try {
        final JumpDistanceFunction function = new JumpDistanceFunction(jdHistogram[0], jdHistogram[1],
                estimatedD);
        PointVectorValuePair lvmSolution = optimizer.optimize(new MaxIter(3000), new MaxEval(Integer.MAX_VALUE),
                new ModelFunctionJacobian(new MultivariateMatrixFunction() {
                    public double[][] value(double[] point) throws IllegalArgumentException {
                        return function.jacobian(point);
                    }
                }), new ModelFunction(function), new Target(function.getY()), new Weight(function.getWeights()),
                new InitialGuess(function.guess()));

        fitParams[n] = lvmSolution.getPointRef();
        SS[n] = calculateSumOfSquares(function.getY(), lvmSolution.getValueRef());
        ic[n] = Maths.getInformationCriterion(SS[n], function.x.length, 1);
        coefficients[n] = fitParams[n];
        fractions[n] = new double[] { 1 };

        Utils.log("Fit Jump distance (N=%d) : D = %s um^2/s, SS = %f, IC = %s (%d evaluations)", n + 1,
                Utils.rounded(fitParams[n][0], 4), SS[n], Utils.rounded(ic[n], 4), optimizer.getEvaluations());

        bestIC = ic[n];
        best = 0;

        addToPlot(function, fitParams[n], jdHistogram, title, plot, Color.magenta);
    } catch (TooManyIterationsException e) {
        Utils.log("Failed to fit : Too many iterations (%d)", optimizer.getIterations());
    } catch (ConvergenceException e) {
        Utils.log("Failed to fit : %s", e.getMessage());
    }

    n++;

    // Fit using a mixed population model. 
    // Vary n from 2 to N. Stop when the fit fails or the fit is worse.
    int bestMulti = -1;
    double bestMultiIC = Double.POSITIVE_INFINITY;
    while (n < N) {
        // Uses a weighted sum of n exponential functions, each function models a fraction of the particles.
        // An LVM fit cannot restrict the parameters so the fractions do not go below zero.
        // Use the CMEASOptimizer which supports bounded fitting.

        MixedJumpDistanceFunctionMultivariate mixedFunction = new MixedJumpDistanceFunctionMultivariate(
                jdHistogram[0], jdHistogram[1], estimatedD, n + 1);

        double[] lB = mixedFunction.getLowerBounds();
        double[] uB = mixedFunction.getUpperBounds();
        SimpleBounds bounds = new SimpleBounds(lB, uB);

        int maxIterations = 2000;
        double stopFitness = 0; //Double.NEGATIVE_INFINITY;
        boolean isActiveCMA = true;
        int diagonalOnly = 20;
        int checkFeasableCount = 1;
        RandomGenerator random = new Well19937c();
        boolean generateStatistics = false;
        ConvergenceChecker<PointValuePair> checker = new SimpleValueChecker(1e-6, 1e-10);
        // The sigma determines the search range for the variables. It should be 1/3 of the initial search region.
        double[] s = new double[lB.length];
        for (int i = 0; i < s.length; i++)
            s[i] = (uB[i] - lB[i]) / 3;
        OptimizationData sigma = new CMAESOptimizer.Sigma(s);
        OptimizationData popSize = new CMAESOptimizer.PopulationSize(
                (int) (4 + Math.floor(3 * Math.log(mixedFunction.x.length))));

        // Iterate this for stability in the initial guess
        CMAESOptimizer opt = new CMAESOptimizer(maxIterations, stopFitness, isActiveCMA, diagonalOnly,
                checkFeasableCount, random, generateStatistics, checker);

        int evaluations = 0;
        PointValuePair constrainedSolution = null;

        for (int i = 0; i <= settings.fitRestarts; i++) {
            // Try from the initial guess
            try {
                PointValuePair solution = opt.optimize(new InitialGuess(mixedFunction.guess()),
                        new ObjectiveFunction(mixedFunction), GoalType.MINIMIZE, bounds, sigma, popSize,
                        new MaxIter(maxIterations), new MaxEval(maxIterations * 2));
                if (constrainedSolution == null || solution.getValue() < constrainedSolution.getValue()) {
                    evaluations = opt.getEvaluations();
                    constrainedSolution = solution;
                    //Utils.log("[%da] Fit Jump distance (N=%d) : SS = %f (%d evaluations)", i, n + 1,
                    //      solution.getValue(), evaluations);
                }
            } catch (TooManyEvaluationsException e) {
            }

            if (constrainedSolution == null)
                continue;

            // Try from the current optimum
            try {
                PointValuePair solution = opt.optimize(new InitialGuess(constrainedSolution.getPointRef()),
                        new ObjectiveFunction(mixedFunction), GoalType.MINIMIZE, bounds, sigma, popSize,
                        new MaxIter(maxIterations), new MaxEval(maxIterations * 2));
                if (constrainedSolution == null || solution.getValue() < constrainedSolution.getValue()) {
                    evaluations = opt.getEvaluations();
                    constrainedSolution = solution;
                    //Utils.log("[%db] Fit Jump distance (N=%d) : SS = %f (%d evaluations)", i, n + 1,
                    //      solution.getValue(), evaluations);
                }
            } catch (TooManyEvaluationsException e) {
            }
        }

        if (constrainedSolution == null) {
            Utils.log("Failed to fit N=%d", n + 1);
            break;
        }

        fitParams[n] = constrainedSolution.getPointRef();
        SS[n] = constrainedSolution.getValue();

        // TODO - Try a bounded BFGS optimiser

        // Try and improve using a LVM fit
        final MixedJumpDistanceFunctionGradient mixedFunctionGradient = new MixedJumpDistanceFunctionGradient(
                jdHistogram[0], jdHistogram[1], estimatedD, n + 1);

        PointVectorValuePair lvmSolution;
        try {
            lvmSolution = optimizer.optimize(new MaxIter(3000), new MaxEval(Integer.MAX_VALUE),
                    new ModelFunctionJacobian(new MultivariateMatrixFunction() {
                        public double[][] value(double[] point) throws IllegalArgumentException {
                            return mixedFunctionGradient.jacobian(point);
                        }
                    }), new ModelFunction(mixedFunctionGradient), new Target(mixedFunctionGradient.getY()),
                    new Weight(mixedFunctionGradient.getWeights()), new InitialGuess(fitParams[n]));
            double ss = calculateSumOfSquares(mixedFunctionGradient.getY(), lvmSolution.getValue());
            // All fitted parameters must be above zero
            if (ss < SS[n] && Maths.min(lvmSolution.getPoint()) > 0) {
                //Utils.log("  Re-fitting improved the SS from %s to %s (-%s%%)", Utils.rounded(SS[n], 4),
                //      Utils.rounded(ss, 4), Utils.rounded(100 * (SS[n] - ss) / SS[n], 4));
                fitParams[n] = lvmSolution.getPoint();
                SS[n] = ss;
                evaluations += optimizer.getEvaluations();
            }
        } catch (TooManyIterationsException e) {
            //Utils.log("Failed to re-fit : Too many evaluations (%d)", optimizer.getEvaluations());
        } catch (ConvergenceException e) {
            //Utils.log("Failed to re-fit : %s", e.getMessage());
        }

        // Since the fractions must sum to one we subtract 1 degree of freedom from the number of parameters
        ic[n] = Maths.getInformationCriterion(SS[n], mixedFunction.x.length, fitParams[n].length - 1);

        double[] d = new double[n + 1];
        double[] f = new double[n + 1];
        double sum = 0;
        for (int i = 0; i < d.length; i++) {
            f[i] = fitParams[n][i * 2];
            sum += f[i];
            d[i] = fitParams[n][i * 2 + 1];
        }
        for (int i = 0; i < f.length; i++)
            f[i] /= sum;
        // Sort by coefficient size
        sort(d, f);
        coefficients[n] = d;
        fractions[n] = f;

        Utils.log("Fit Jump distance (N=%d) : D = %s um^2/s (%s), SS = %f, IC = %s (%d evaluations)", n + 1,
                format(d), format(f), SS[n], Utils.rounded(ic[n], 4), evaluations);

        boolean valid = true;
        for (int i = 0; i < f.length; i++) {
            // Check the fit has fractions above the minimum fraction
            if (f[i] < minFraction) {
                Utils.log("Fraction is less than the minimum fraction: %s < %s", Utils.rounded(f[i]),
                        Utils.rounded(minFraction));
                valid = false;
                break;
            }
            // Check the coefficients are different
            if (i + 1 < f.length && d[i] / d[i + 1] < minDifference) {
                Utils.log("Coefficients are not different: %s / %s = %s < %s", Utils.rounded(d[i]),
                        Utils.rounded(d[i + 1]), Utils.rounded(d[i] / d[i + 1]), Utils.rounded(minDifference));
                valid = false;
                break;
            }
        }

        if (!valid)
            break;

        // Store the best model
        if (bestIC > ic[n]) {
            bestIC = ic[n];
            best = n;
        }

        // Store the best multi model
        if (bestMultiIC < ic[n]) {
            break;
        }

        bestMultiIC = ic[n];
        bestMulti = n;

        n++;
    }

    // Add the best fit to the plot and return the parameters.
    if (bestMulti > -1) {
        Function function = new MixedJumpDistanceFunctionMultivariate(jdHistogram[0], jdHistogram[1], 0,
                bestMulti + 1);
        addToPlot(function, fitParams[bestMulti], jdHistogram, title, plot, Color.yellow);
    }

    if (best > -1) {
        Utils.log("Best fit achieved using %d population%s: D = %s um^2/s, Fractions = %s", best + 1,
                (best == 0) ? "" : "s", format(coefficients[best]), format(fractions[best]));
    }

    return (best > -1) ? new double[][] { coefficients[best], fractions[best] } : null;
}

From source file:norbert.mynemo.core.selection.SvdRecommenderSelector.java

/**
 * Evaluates the given recommender type for several configurations. The number of iterations and
 * the number of features for each evaluation is chosen via an optimizer. The number of evaluation
 * performed depends of the number of steps necessary for the evaluation results to converge. The
 * number of evaluations performed is also bounded by an internal maximum.
 *
 * <p>//from w  w w  .  j  a  va  2  s  . c o  m
 * The given recommender type must be part of the SVD based family.
 *
 * @return all evaluations done during the selection process
 */
public Collection<RecommenderEvaluation> select(RecommenderType type, double minimumCoverage) {
    checkArgument(type.getFamily() == RecommenderFamily.SVD_BASED);

    // initialize necessary optimization data
    ConvergenceChecker<PointValuePair> checker = new MaxIterationChecker<PointValuePair>(CMAES_MAX_ITERATIONS);
    SvdRecommenderEvalFunction function = new SvdRecommenderEvalFunction(configuration, type, minimumCoverage);
    ObjectiveFunction objectiveFunction = new ObjectiveFunction(function);
    CMAESOptimizer optimizer = new CMAESOptimizer(CMAES_MAX_ITERATIONS, 1.0, true, 2, 0,
            new JDKRandomGenerator(), false, checker);

    MaxEval maxEval = MaxEval.unlimited();
    GoalType goalType = GoalType.MINIMIZE;
    SimpleBounds bounds = new SimpleBounds(new double[] { MIN_SVD_FEATURES, MIN_SVD_ITERATIONS },
            new double[] { MAX_SVD_FEATURES, MAX_SVD_ITERATIONS });
    InitialGuess initialGuess = new InitialGuess(
            new double[] { INITIAL_GUESS_FEATURES, INITIAL_GUESS_ITERATIONS });
    CMAESOptimizer.PopulationSize populationSize = new CMAESOptimizer.PopulationSize(16);
    CMAESOptimizer.Sigma sigma = new CMAESOptimizer.Sigma(
            new double[] { CMAES_SIGMA_FEATURE, CMAES_SIGMA_ITERATION });

    // run the optimizer
    optimizer.optimize(objectiveFunction, goalType, initialGuess, populationSize, sigma, bounds, maxEval);

    return function.getEvaluations();
}

From source file:norbert.mynemo.core.selection.UserRecommenderSelector.java

/**
 * Evaluates the given recommender type for several configurations. The number of neighbors for
 * each evaluation is chosen via an optimizer. The number of evaluation performed depends of the
 * number of steps necessary for the evaluation results to converge. The number of evaluations
 * performed is also bounded by an internal maximum.
 *
 * <p>//from  w ww.j a va2s  .  c o  m
 * The given recommender type must be part of the user similarity based family.
 *
 * @return all evaluations done during the selection process
 */
public Collection<RecommenderEvaluation> select(RecommenderType type, double minimumCoverage) {
    checkArgument(type.getFamily() == RecommenderFamily.USER_SIMILARITY_BASED);
    checkArgument(0 <= minimumCoverage && minimumCoverage <= 1,
            "The minimum coverage must be" + "between 0 and 1.");

    final UserBasedRecommenderEvaluationFunction function = new UserBasedRecommenderEvaluationFunction(
            configuration, type, minimumCoverage);

    // find a good initial guess: test 10%, 20% 90% of maximum neighbors
    double secondBestInitialValue = 1;
    double bestInitialValue = 0;
    double bestEvalResult = Integer.MAX_VALUE;
    for (double factor = 0.1; factor <= 0.9; factor += 0.1) {
        double currentNumNeighbors = maxNeighbors * factor;
        double evalResult = function.value(currentNumNeighbors);
        if (evalResult < bestEvalResult) {
            bestEvalResult = evalResult;
            secondBestInitialValue = bestInitialValue;
            bestInitialValue = currentNumNeighbors;
        }
    }

    // initialize the quality parameters of the CMAES optimizer
    final double minNeighbors = 1;
    final double initialGuessNeighbors = bestInitialValue;
    final double sigmaNeighbors = Math.min(Math.abs(bestInitialValue - secondBestInitialValue),
            Math.min(maxNeighbors - bestInitialValue, bestInitialValue - 1));
    // not sure about that
    final int populationSize = (int) (Math.log10(maxNeighbors) / Math.log10(2));
    // inhibit the exception throw if the maximum number of evaluation is reached
    final int maxCmaesEvaluations = Integer.MAX_VALUE;
    // not sure about that
    final int maxCmaesIterations = (int) (Math.log10(maxNeighbors) / Math.log10(2));

    // initialize the other parameters
    final ConvergenceChecker<PointValuePair> checker = new MaxIterationChecker<PointValuePair>(20);
    final ObjectiveFunction objectiveFunction = new ObjectiveFunction(function);
    final CMAESOptimizer optimizer = new CMAESOptimizer(maxCmaesIterations, 1.0, true, 0, 0,
            new JDKRandomGenerator(), false, checker);

    final MaxEval maxEval = new MaxEval(maxCmaesEvaluations);
    final GoalType goalType = GoalType.MINIMIZE;
    final SimpleBounds bounds = new SimpleBounds(new double[] { minNeighbors, minNeighbors },
            new double[] { maxNeighbors, maxNeighbors });
    final InitialGuess initialGuess = new InitialGuess(
            new double[] { initialGuessNeighbors, initialGuessNeighbors });
    final CMAESOptimizer.PopulationSize popSize = new CMAESOptimizer.PopulationSize((populationSize));
    final CMAESOptimizer.Sigma sigma = new CMAESOptimizer.Sigma(
            new double[] { sigmaNeighbors, sigmaNeighbors });

    // run the optimizer
    optimizer.optimize(objectiveFunction, goalType, initialGuess, popSize, sigma, bounds, maxEval);

    return function.getEvaluations();
}

From source file:objenome.goal.numeric.OptimizeMultivariate.java

@Override
public synchronized void solve(Objenome o, List<SetNumericValue> variables) {

    this.variables = variables;
    objenome = o;/*from   www .  j  av  a 2s  . c  om*/

    if (numStarts == -1)
        numStarts = variables.size() * 2;

    double[] lower = new double[variables.size()];
    double[] upper = new double[variables.size()];
    double[] mid = new double[variables.size()];
    int j = 0;
    for (SetNumericValue n : variables) {
        lower[j] = n.getMin().doubleValue();
        upper[j] = n.getMax().doubleValue();
        mid[j] = (lower[j] + upper[j]) * 0.5f;
        j++;
    }

    //TODO add MultiStart

    MultivariateOptimizer optimize = new BOBYQAOptimizer(variables.size() * 2);
    //new PowellOptimizer(0.01, 0.05);

    RandomGenerator rng = getRandomGenerator();

    MultiStartMultivariateOptimizer multiOptimize = new MultiStartMultivariateOptimizer(optimize, numStarts,
            new UncorrelatedRandomVectorGenerator(variables.size(), new UniformRandomGenerator(rng)));

    PointValuePair result = multiOptimize.optimize(new MaxEval(evaluations), new SimpleBounds(lower, upper),
            goal, new InitialGuess(mid), new ObjectiveFunction(this));

    apply(result.getPointRef());

    bestValue = result.getValue();
}

From source file:org.compevol.ssgd.MaximumLikelihood.java

@Override
public void run() {
    final Bounds<Double> bounds = variables.getBounds();
    final double[] lower = new double[bounds.getBoundsDimension()];
    final double[] upper = new double[bounds.getBoundsDimension()];
    final double[] sigma = new double[variables.getDimension()];
    Arrays.fill(sigma, 1.0);/*  w  w w .j  a  v  a2 s .  c  o  m*/
    for (int i = 0; i < variables.getDimension(); ++i) {
        lower[i] = bounds.getLowerLimit(i) / variables.getParameterValue(i);
        upper[i] = bounds.getUpperLimit(i) / variables.getParameterValue(i);
    }
    final PointValuePair result = optimizer.optimize(
            new CMAESOptimizer.PopulationSize(4 + 3 * (int) Math.log(variables.getDimension())),
            new CMAESOptimizer.Sigma(sigma), GoalType.MAXIMIZE, new ObjectiveFunction(likelihood),
            new InitialGuess(initial), new SimpleBounds(lower, upper), new MaxEval(Integer.MAX_VALUE));
    System.out.println(variables);
    System.out.println(result.getValue());
}

From source file:org.dawnsci.plotting.tools.diffraction.BeamCenterRefinement.java

/**
 * Run optimisation of sector region position in a separate job. 
 * //from   w  ww. j a v a  2s . c  om
 * @param startPosition Initial position of sector region
 */
public void optimize(final double[] startPosition) {
    final int cmaesLambda = this.cmaesLambda;
    final double[] cmaesInputSigma = this.cmaesInputSigma;
    final int cmaesMaxIterations = this.cmaesMaxIterations;
    final int cmaesCheckFeasableCount = this.cmaesCheckFeasableCount;
    final ConvergenceChecker<PointValuePair> cmaesChecker = this.cmaesChecker;
    final BeamCenterRefinement function = this;
    Job job = new Job("Beam Position Refinement") {
        @Override
        protected IStatus run(IProgressMonitor monitor) {

            function.setInitPeaks(initPeaks);
            function.setMonitor(monitor);

            final double[] lB = new double[] { startPosition[0] - 20, startPosition[1] - 20 };
            final double[] uB = new double[] { startPosition[0] + 20, startPosition[1] + 20 };
            CMAESOptimizer beamPosOptimizer = new CMAESOptimizer(cmaesMaxIterations, 0.0, true, 0,
                    cmaesCheckFeasableCount, new Well19937a(), false, cmaesChecker);
            final PointValuePair result = beamPosOptimizer.optimize(new MaxEval(cmaesMaxIterations),
                    new ObjectiveFunction(function), GoalType.MAXIMIZE,
                    new CMAESOptimizer.PopulationSize(cmaesLambda), new CMAESOptimizer.Sigma(cmaesInputSigma),
                    new SimpleBounds(lB, uB), new InitialGuess(startPosition));

            final double[] newBeamPosition = result.getPoint();
            logger.info("Optimiser terminated at beam position ({}, {}) with the value {}",
                    new Object[] { newBeamPosition[0], newBeamPosition[1], result.getValue() });
            Display.getDefault().syncExec(new Runnable() {
                @Override
                public void run() {
                    ((IDiffractionMetadata) dataset.getMetadata()).getDetector2DProperties()
                            .setBeamCentreCoords(newBeamPosition);
                }
            });

            return Status.OK_STATUS;
        }
    };
    job.schedule();
}

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:put.ci.cevo.framework.algorithms.ApacheCMAES.java

public void optimize(EvolutionTarget target, int populationSize, double sigma, double[] guess,
        PopulationEvaluator<double[]> populationEvaluator) {
    this.maxIterations = ((GenerationsTarget) target).getGenerations();
    this.populationEvaluator = populationEvaluator;
    optimize(new MaxIter(maxIterations), new PopulationSize(populationSize),
            new Sigma(DoubleArrays.vector(sigma, guess.length)), new InitialGuess(guess), GoalType.MAXIMIZE,
            new SimpleBounds(DoubleArrays.vector(Double.NEGATIVE_INFINITY, guess.length),
                    DoubleArrays.vector(Double.POSITIVE_INFINITY, guess.length)));
}

From source file:uk.ac.diamond.scisoft.analysis.optimize.ApacheOptimizer.java

private SimpleBounds createBounds() {
    double[] lb = new double[n];
    double[] ub = new double[n];
    for (int i = 0; i < n; i++) {
        IParameter p = params.get(i);/*  ww w  .j  a va  2s . co m*/
        lb[i] = p.getLowerLimit();
        ub[i] = p.getUpperLimit();
    }

    return new SimpleBounds(lb, ub);
}