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

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

Introduction

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

Prototype

public InitialGuess(double[] startPoint) 

Source Link

Usage

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

/**
 * Run optimisation of sector region position in a separate job. 
 * /*  w  ww .  java  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:org.dawnsci.plotting.tools.powdercheck.PowderCheckJob.java

private List<PowderCheckResult> fitPeaksToTrace(final Dataset xIn, final Dataset yIn, Dataset baselineIn) {

    resultList.clear();//from  www.  j a  v a 2  s . co  m

    List<HKL> spacings = CalibrationFactory.getCalibrationStandards().getCalibrant().getHKLs();
    final double[] qVals = new double[spacings.size()];

    for (int i = 0; i < spacings.size(); i++) {
        if (xAxis == XAxis.ANGLE)
            qVals[i] = 2 * Math.toDegrees(Math.asin((metadata.getDiffractionCrystalEnvironment().getWavelength()
                    / (2 * spacings.get(i).getDNano() * 10))));
        else
            qVals[i] = (Math.PI * 2) / (spacings.get(i).getDNano() * 10);
    }

    double qMax = xIn.max().doubleValue();
    double qMin = xIn.min().doubleValue();

    List<Double> qList = new ArrayList<Double>();

    int count = 0;

    for (double q : qVals) {
        if (q > qMax || q < qMin)
            continue;
        count++;
        qList.add(q);
    }

    double minPeak = Collections.min(qList);
    double maxPeak = Collections.max(qList);

    int minXidx = ROISliceUtils.findPositionOfClosestValueInAxis(xIn, minPeak) - EDGE_PIXEL_NUMBER;
    int maxXidx = ROISliceUtils.findPositionOfClosestValueInAxis(xIn, maxPeak) + EDGE_PIXEL_NUMBER;

    int maxSize = xIn.getSize();

    minXidx = minXidx < 0 ? 0 : minXidx;
    maxXidx = maxXidx > maxSize - 1 ? maxSize - 1 : maxXidx;

    final Dataset x = xIn.getSlice(new int[] { minXidx }, new int[] { maxXidx }, null);
    final Dataset y = yIn.getSlice(new int[] { minXidx }, new int[] { maxXidx }, null);
    y.setName("Fit");
    Dataset baseline = baselineIn.getSlice(new int[] { minXidx }, new int[] { maxXidx }, null);

    List<APeak> peaks = Generic1DFitter.fitPeaks(x, y, Gaussian.class, count + 10);

    List<PowderCheckResult> initResults = new ArrayList<PowderCheckResult>();

    CompositeFunction cf = new CompositeFunction();

    for (APeak peak : peaks)
        cf.addFunction(peak);

    double limit = findMatchLimit(qList, cf);

    while (cf.getNoOfFunctions() != 0 && !qList.isEmpty())
        findMatches(initResults, qList, cf, limit);

    final CompositeFunction cfFinal = compositeFunctionFromResults(initResults);

    double[] initParam = new double[cfFinal.getFunctions().length * 3];

    {
        int i = 0;
        for (IFunction func : cfFinal.getFunctions()) {
            initParam[i++] = func.getParameter(0).getValue();
            initParam[i++] = func.getParameter(1).getValue();
            initParam[i++] = func.getParameter(2).getValue();
        }
    }

    final Dataset yfit = DatasetFactory.zeros(x, Dataset.FLOAT64);

    MultivariateOptimizer opt = new SimplexOptimizer(REL_TOL, ABS_TOL);

    MultivariateFunction fun = new MultivariateFunction() {

        @Override
        public double value(double[] arg0) {

            int j = 0;
            for (IFunction func : cfFinal.getFunctions()) {

                double[] p = func.getParameterValues();
                p[0] = arg0[j++];
                p[1] = arg0[j++];
                p[2] = arg0[j++];
                func.setParameterValues(p);
            }

            for (int i = 0; i < yfit.getSize(); i++) {
                yfit.set(cfFinal.val(x.getDouble(i)), i);
            }

            return y.residual(yfit);
        }
    };

    opt.optimize(new InitialGuess(initParam), GoalType.MINIMIZE, new ObjectiveFunction(fun),
            new MaxEval(MAX_EVAL), new NelderMeadSimplex(initParam.length));

    Dataset fit = Maths.add(yfit, baseline);
    fit.setName("Fit");
    Dataset residual = Maths.subtract(y, yfit);
    residual.setName("Residual");

    system.updatePlot1D(x, Arrays.asList(new IDataset[] { fit, residual }), null);
    setPlottingSystemAxes();
    for (int i = 0; i < cfFinal.getNoOfFunctions(); i++) {
        resultList.add(new PowderCheckResult(cfFinal.getFunction(i), initResults.get(i).getCalibrantQValue()));
    }

    return resultList;

}

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

/**
 * Calculate angles of closest points on circle to targets
 * @param initParameters geometric parameters
 * @return array of all initial parameters
 *//*from w ww .  j  a va  2  s .c o m*/
InitialGuess calcAllInitValues(double[] initParameters) {
    double[] init = new double[n + PARAMETERS];
    for (int i = 0; i < initParameters.length; i++) {
        init[i] = initParameters[i];
    }
    final double x = initParameters[1];
    final double y = initParameters[2];

    // work out the angle values for the closest points on circle
    final IndexIterator itx = X.getIterator();
    final IndexIterator ity = Y.getIterator();
    int i = PARAMETERS;
    while (itx.hasNext() && ity.hasNext()) {
        final double Xc = X.getElementDoubleAbs(itx.index) - x;
        final double Yc = Y.getElementDoubleAbs(ity.index) - y;

        init[i++] = Math.atan2(Yc, Xc);
    }
    return new InitialGuess(init);
}

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

/**
 * Calculate angles of closest points on ellipse to targets
 * @param initParameters geometric parameters
 * @return array of all initial parameters
 *///from   ww w  . j a  va 2s. c om
InitialGuess calcAllInitValues(double[] initParameters) {
    double[] init = new double[n + PARAMETERS];
    for (int i = 0; i < initParameters.length; i++) {
        init[i] = initParameters[i];
    }
    final double a = initParameters[0];
    final double b = initParameters[1];
    final double alpha = initParameters[2];
    final double x = initParameters[3];
    final double y = initParameters[4];
    final double twopi = 2 * Math.PI;
    angleDerivative.setRadii(a, b);
    angleDerivative.setAngle(alpha);

    // work out the angle values for the closest points on ellipse
    final IndexIterator itx = X.getIterator();
    final IndexIterator ity = Y.getIterator();
    int i = PARAMETERS;
    while (itx.hasNext() && ity.hasNext()) {
        final double Xc = X.getElementDoubleAbs(itx.index) - x;
        final double Yc = Y.getElementDoubleAbs(ity.index) - y;

        angleDerivative.setCoordinate(Xc, Yc);
        try {
            // find quadrant to use
            double pa = Math.atan2(Yc, Xc);
            if (pa < 0)
                pa += twopi;
            pa -= alpha;
            final double end;
            final double halfpi = 0.5 * Math.PI;
            pa /= halfpi;
            end = Math.ceil(pa) * halfpi;
            final double angle = solver.solve(100, angleDerivative, end - halfpi, end);
            init[i++] = angle;
        } catch (TooManyEvaluationsException e) {
            throw new IllegalArgumentException("Problem with solver converging as iterations exceed limit");
        } catch (MathIllegalArgumentException e) {
            // cannot happen
        }
    }
    return new InitialGuess(init);
}

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));/*  w  ww.  jav  a2  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
    );/*  w  w w. ja  v a 2 s  .c o  m*/

    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;
}