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: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:smlm.fitting.FittingClassical.java

@SuppressWarnings("unused")
@Override//w  w w. j  a  v a 2  s .  c  om
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/*ww  w .  j  a v a2  s . c o  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;
}

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

private void internalScalarOptimize() {
    MultivariateOptimizer opt = createOptimizer();
    SimpleBounds bd = createBounds();/*from ww  w  .j  a v  a 2s. c o  m*/
    double offset = 1e12;
    double[] scale = new double[n];
    for (int i = 0; i < n; i++) {
        scale[i] = offset * 0.25;
    }
    MultivariateFunction fn = createFunction();
    if (optimizer == Optimizer.SIMPLEX_MD || optimizer == Optimizer.SIMPLEX_NM) {
        fn = new MultivariateFunctionPenaltyAdapter(fn, bd.getLower(), bd.getUpper(), offset, scale);
    }
    ObjectiveFunction of = new ObjectiveFunction(fn);
    InitialGuess ig = new InitialGuess(getParameterValues());
    MaxEval me = new MaxEval(MAX_EVAL);
    double min = Double.POSITIVE_INFINITY;
    double res = Double.NaN;

    try {
        PointValuePair result;

        switch (optimizer) {
        case CONJUGATE_GRADIENT:
            //            af = new MultivariateFunctionPenaltyAdapter(fn, bd.getLower(), bd.getUpper(), offset, scale);
            result = opt.optimize(ig, GoalType.MINIMIZE, of, me,
                    new ObjectiveFunctionGradient(createGradientFunction()));
            break;
        case BOBYQA:
            result = opt.optimize(ig, GoalType.MINIMIZE, of, me, bd);
            break;
        case CMAES:
            double[] sigma = new double[n];
            for (int i = 0; i < n; i++) {
                IParameter p = params.get(i);
                double v = p.getValue();
                double r = Math.max(p.getUpperLimit() - v, v - p.getLowerLimit());
                sigma[i] = r * 0.05; // 5% of range
            }
            int p = (int) Math.ceil(4 + Math.log(n)) + 1;
            logger.trace("Population size: {}", p);
            result = opt.optimize(ig, GoalType.MINIMIZE, of, me, bd, new CMAESOptimizer.Sigma(sigma),
                    new CMAESOptimizer.PopulationSize(p));
            break;
        case SIMPLEX_MD:
            result = opt.optimize(ig, GoalType.MINIMIZE, of, me, new MultiDirectionalSimplex(n));
            break;
        case SIMPLEX_NM:
            result = opt.optimize(ig, GoalType.MINIMIZE, of, me, new NelderMeadSimplex(n));
            break;
        default:
            throw new IllegalStateException("Should not be called");
        }

        // logger.info("Q-space fit: rms = {}, x^2 = {}", opt.getRMS(), opt.getChiSquare());
        double ires = calculateResidual(opt.getStartPoint());
        logger.trace("Residual: {} from {}", result.getValue(), ires);
        res = result.getValue();
        if (res < min)
            setParameterValues(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());
    }
}

From source file:uk.ac.diamond.scisoft.ncd.calibration.rcp.views.MultivariateFunctionWithMonitor.java

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 MultivariateFunctionWithMonitor function = this;
    Job job = new Job(jobName) {
        @Override/*from  w  w w .  j ava2  s .co m*/
        protected IStatus run(IProgressMonitor monitor) {

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

            CMAESOptimizer beamPosOptimizer = new CMAESOptimizer(cmaesMaxIterations, 0.0, true, 0,
                    cmaesCheckFeasableCount, new Well19937a(), false, cmaesChecker);
            final PointValuePair res = beamPosOptimizer.optimize(new MaxEval(cmaesMaxIterations),
                    new ObjectiveFunction(function), GoalType.MAXIMIZE,
                    new CMAESOptimizer.PopulationSize(cmaesLambda), new CMAESOptimizer.Sigma(cmaesInputSigma),
                    SimpleBounds.unbounded(2), new InitialGuess(startPosition));
            final double[] newBeamPos = res.getPoint();
            logger.info("Optimiser terminated at beam position ({}, {}) with the value {}",
                    new Object[] { newBeamPos[0], newBeamPos[1], res.getValue() });
            // Run calculation with optimised beam center to update UI 
            function.value(newBeamPos);

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

From source file:uk.ac.diamond.scisoft.ncd.core.data.plots.GuinierPlotData.java

public Object[] getGuinierPlotParameters(IDataset data, IDataset axis) {
    Dataset guinierData = getSaxsPlotDataset(data, axis);
    Dataset guinierAxis = getSaxsPlotAxis(axis);
    /*      int sliceSize = data.getSize() / 10;
          int[] step = new int[] {sliceSize};
          IndexIterator dataSliceIter = guinierData.getSliceIterator(null, null, null);
          IndexIterator axisSliceIter = guinierAxis.getSliceIterator(null, null, null);
          // Iterate over data slices// ww w  .j a  v  a2s .co  m
          int[] minPosition = new int[] {-1};
          double minError = Double.MAX_VALUE;
          double slope = Double.NaN;
          double intercept = Double.NaN;
          Map<DoublePoint, Double> clusterInputMap = new HashMap<DoublePoint, Double>();
          while (dataSliceIter.hasNext() && axisSliceIter.hasNext()) {
             SimpleRegression regression = new SimpleRegression();
             int[] pos = dataSliceIter.getPos();
             // Iterate over data values for linear regression
             IndexIterator dataIter = new SliceIterator(
       guinierData.getShape(),
       guinierData.getSize(),
       pos, step);
             pos = axisSliceIter.getPos();
             IndexIterator axisIter = new SliceIterator(
       guinierAxis.getShape(),
       guinierAxis.getSize(),
       pos, step);
             int points = 0;
             while (dataIter.hasNext() && axisIter.hasNext()) {
    double dataVal = guinierData.getDouble(dataIter.getPos());
    double axisVal = guinierAxis.getDouble(axisIter.getPos());
    regression.addData(axisVal, dataVal);
    points++;
             }
             if (points == sliceSize) {
    regression.regress();
    double err = regression.getMeanSquareError();
    if (err < minError) {
       minError = err;
       minPosition = Arrays.copyOf(pos, pos.length);
       slope = regression.getSlope();
       intercept = regression.getIntercept();
       double I0 = Math.exp(intercept);
       double Rg = Math.sqrt(-3.0*slope);
       System.out.println("    Min Pos : " + Arrays.toString(minPosition));
       System.out.println("   Min Error : " + Double.toString(minError));
       System.out.println("   Slope : " + Double.toString(slope) + "   Intercept : " + Double.toString(intercept));
       System.out.println("   I(0) : " + Double.toString(I0) + "   Rg : " + Double.toString(Rg));
       clusterInputMap.put(new DoublePoint(minPosition), minError);
    }
             } else {
    break;
             }
          }
                  
          DBSCANClusterer<DoublePoint> clusterer = new DBSCANClusterer<DoublePoint>(5, 5);
          List<Cluster<DoublePoint>> clusterResults = clusterer.cluster(clusterInputMap.keySet());
            
          // output the clusters
          for (int i = 0; i < clusterResults.size(); i++) {
              System.out.println("Cluster " + i);
             double[] minPoint = null;
             double minVal = Double.MAX_VALUE;
              for (DoublePoint point : clusterResults.get(i).getPoints()) {
      System.out.println(Arrays.toString(point.getPoint()));
      Double val = clusterInputMap.get(point);
      if (val < minVal) {
         minVal = val;
         minPoint = Arrays.copyOf(point.getPoint(), point.getPoint().length);
      }
      minVal = (val < minVal ? val : minVal);
              }
               System.out.println("Min cluster point : " + Arrays.toString(minPoint));
               System.out.println("Min cluster value : " + Double.toString(minVal));
              System.out.println();
          }
                  
    */ ConvergenceChecker<PointValuePair> cmaesChecker = new SimplePointChecker<PointValuePair>(1e-6, 1e-8);
    RandomDataGenerator rnd = new RandomDataGenerator();
    CMAESOptimizer optimizer = new CMAESOptimizer(cmaesMaxIterations, 0.0, true, 0, cmaesCheckFeasableCount,
            rnd.getRandomGenerator(), false, cmaesChecker);
    GuinierLineFitFunction function = new GuinierLineFitFunction(guinierData, guinierAxis);

    Amount<Dimensionless> I0 = Amount.valueOf(Double.NaN, Double.NaN, Dimensionless.UNIT);
    Amount<Dimensionless> Rg = Amount.valueOf(Double.NaN, Double.NaN, Dimensionless.UNIT);
    double[] qvals = new double[] { Double.NaN, Double.NaN };

    double q0 = guinierAxis.getDouble(0);
    double qMin = guinierAxis.getDouble(1);
    double qMax = guinierAxis.getDouble(guinierAxis.getSize() - 1);
    double[] startPosition = new double[] { guinierAxis.getDouble(0),
            guinierAxis.getDouble(GuinierLineFitFunction.MIN_POINTS) };
    double[] cmaesInputSigma = new double[] { (qMin - q0) * 0.1, qMax * 0.1 };
    try {
        final PointValuePair res = optimizer.optimize(new MaxEval(cmaesMaxIterations),
                new ObjectiveFunction(function), GoalType.MAXIMIZE,
                new CMAESOptimizer.PopulationSize(cmaesLambda), new CMAESOptimizer.Sigma(cmaesInputSigma),
                new SimpleBounds(new double[] { q0, q0 }, new double[] { qMin, qMax }),
                new InitialGuess(startPosition));

        qvals = res.getPoint();
        function.value(qvals);
        I0 = getI0(function.regression);
        Rg = getRg(function.regression);

        System.out.println("Final Result");
        String msg = StringUtils.join(new String[] { "   I(0) ", I0.toString(), "   Rg ", Rg.toString() },
                " : ");
        System.out.println(msg);
        msg = StringUtils.join(new String[] { "Slice", ArrayUtils.toString(res.getPoint()), "R",
                Double.toString(function.regression.getR()) }, " : ");
        System.out.println(msg);

        /*         // Run Monte-Carlo simulation to generate error estimates Rg values 
                 //double finalR = function.regression.getR();
                 int maxSample = 10000;
                 int minSample = 10;
                 int totalSample = 100000;
                 int counter = 0;
                 int totalCounter = 0;
                 GuinierLineFitFunction mcFunction = new GuinierLineFitFunction(guinierData, guinierAxis);
                 DescriptiveStatistics statsR = new DescriptiveStatistics();
                 List<Pair<Double, Amount<Dimensionless>>> listI0 = new ArrayList<Pair<Double,Amount<Dimensionless>>>();
                 List<Pair<Double, Amount<Dimensionless>>> listRg = new ArrayList<Pair<Double,Amount<Dimensionless>>>();
                 while ((counter < maxSample && totalCounter < totalSample)
                       || (counter < minSample && totalCounter >= totalSample)) {
                    double q1 = rnd.nextUniform(q0, qMin);
                    double q2 = rnd.nextUniform(q0, qMax);
                    if (!(q2 > q1)) {
                       continue;
                    }
                    totalCounter++;
                     mcFunction.value(new double[] {q1, q2});
                     double tmpR = Math.abs(mcFunction.regression.getR());
                     //boolean equalsR = Precision.equalsWithRelativeTolerance(tmpR, finalR, 0.1); 
                     if (!(Double.isNaN(tmpR) || Double.isInfinite(tmpR))) {
        statsR.addValue(tmpR);
        Amount<Dimensionless> tmpI0 = getI0(mcFunction.regression);
        Amount<Dimensionless> tmpRg = getRg(mcFunction.regression);
         if (Double.isNaN(tmpI0.getEstimatedValue()) || Double.isInfinite(tmpI0.getEstimatedValue()) ||
               Double.isNaN(tmpRg.getEstimatedValue()) || Double.isInfinite(tmpRg.getEstimatedValue())) {
            continue;
         }
        listI0.add(new Pair<Double, Amount<Dimensionless>>(tmpR, tmpI0));
        listRg.add(new Pair<Double, Amount<Dimensionless>>(tmpR, tmpRg));
        counter++;
                     }
                 }
                         
                 double threshold = statsR.getPercentile(90);
                 //double threshold = 0.95*statsR.getMax();
                 SummaryStatistics statsI0 = new SummaryStatistics();
                 SummaryStatistics statsRg = new SummaryStatistics();
                 for (Pair<Double, Amount<Dimensionless>> tmpVal : listRg) {
                    if (tmpVal.getFirst() > threshold) {
        statsRg.addValue(tmpVal.getSecond().getEstimatedValue());
                    }
                 }
                 for (Pair<Double, Amount<Dimensionless>> tmpVal : listI0) {
                    if (tmpVal.getFirst() > threshold) {
        statsI0.addValue(tmpVal.getSecond().getEstimatedValue());
                    }
                 }
                         
                 double meanI0 = statsI0.getMean();
                 double stdI0 = statsI0.getStandardDeviation();
                 I0 = Amount.valueOf(meanI0, stdI0, Dimensionless.UNIT);
                         
                 double meanRg = statsRg.getMean();
                 double stdRg = statsRg.getStandardDeviation();
                 Rg = Amount.valueOf(meanRg, stdRg, Dimensionless.UNIT);
                         
                 String msg = StringUtils.join(new String[] {
                       "Monte-Carlo Rg", Rg.toString()
                       },
                       " : ");
                 System.out.println(msg);
        */
    } catch (MaxCountExceededException e) {
        System.out.println("Maximum counts exceeded");
        return null;
    }
    return new Object[] { I0, Rg, qvals[0], qvals[1] };
}

From source file:uk.ac.diamond.scisoft.ncd.core.data.plots.LogLogPlotData.java

public double[] getPorodPlotParameters(IDataset data, IDataset axis) {
    Dataset loglogData = getSaxsPlotDataset(data, axis);
    Dataset loglogAxis = getSaxsPlotAxis(axis);
    CMAESOptimizer optimizer = new CMAESOptimizer(cmaesMaxIterations, 0.0, true, 0, cmaesCheckFeasableCount,
            new Well19937a(), false, cmaesChecker);
    PorodLineFitFunction function = new PorodLineFitFunction(loglogData, loglogAxis);

    int dataSize = loglogAxis.getSize();
    double qMax = Math.pow(10.0, loglogAxis.getDouble(dataSize - 1));
    double i0 = Math.pow(10.0, loglogData.getDouble(0));
    double[] startPosition = new double[] { i0, 1.0 / qMax, 4.0 };
    double[] cmaesInputSigma = new double[] { 0.1 * i0, 0.1 / qMax, 0.1 };
    double[] lb = new double[] { 0.0, 0.0, 0.0 };
    double[] ub = new double[] { Double.MAX_VALUE, Double.MAX_VALUE, Double.MAX_VALUE };
    double[] params = new double[] { Double.NaN, Double.NaN, Double.NaN };
    try {/* w w  w. ja va2s. c om*/
        final PointValuePair res = optimizer.optimize(new MaxEval(cmaesMaxIterations),
                new ObjectiveFunction(function), GoalType.MAXIMIZE,
                new CMAESOptimizer.PopulationSize(cmaesLambda), new CMAESOptimizer.Sigma(cmaesInputSigma),
                new SimpleBounds(lb, ub), new InitialGuess(startPosition));

        params = res.getPoint();
        double solvation = params[0];
        double correlation = params[1];
        double exponent = params[2];

        double rms = Math.exp(-function.value(params));

        System.out.println();
        System.out.println("Final Result");
        String msg = StringUtils.join(new String[] { "   solvation ", Double.toString(solvation),
                "   correlation ", Double.toString(correlation), "   exponent ", Double.toString(exponent) },
                " : ");
        System.out.println(msg);
        msg = StringUtils.join(new String[] { "RMS", Double.toString(rms) }, " : ");
        System.out.println(msg);
        System.out.println();

    } catch (MaxCountExceededException e) {
        params = new double[] { Double.NaN, Double.NaN, Double.NaN };
    }
    return params;
}

From source file:uk.ac.diamond.scisoft.ncd.core.data.plots.PorodPlotData.java

public SimpleRegression getPorodPlotParameters(IDataset data, IDataset axis) {
    Dataset porodData = getSaxsPlotDataset(data, axis);
    Dataset porodAxis = getSaxsPlotAxis(axis);
    CMAESOptimizer optimizer = new CMAESOptimizer(cmaesMaxIterations, 0.0, true, 0, cmaesCheckFeasableCount,
            new Well19937a(), false, cmaesChecker);
    PorodLineFitFunction function = new PorodLineFitFunction(porodData, porodAxis);

    int dataSize = porodAxis.getSize();
    double q0 = porodAxis.getDouble(0);
    double qMax = porodAxis.getDouble(dataSize - 1);
    double[] startPosition = new double[] { porodAxis.getDouble(dataSize - PorodLineFitFunction.MIN_POINTS - 1),
            porodAxis.getDouble(dataSize - 1) };
    double[] cmaesInputSigma = new double[] { qMax * 0.1, qMax * 0.1 };
    try {/*from   w  ww .jav  a  2s . c  o m*/
        final PointValuePair res = optimizer.optimize(new MaxEval(cmaesMaxIterations),
                new ObjectiveFunction(function), GoalType.MAXIMIZE,
                new CMAESOptimizer.PopulationSize(cmaesLambda), new CMAESOptimizer.Sigma(cmaesInputSigma),
                new SimpleBounds(new double[] { q0, q0 }, new double[] { qMax, qMax }),
                new InitialGuess(startPosition));

        function.value(res.getPoint());
        double slope = function.regression.getSlope();
        Amount<Dimensionless> c4 = getC4(function.regression);

        System.out.println("Final Result");
        String msg = StringUtils
                .join(new String[] { "   c4 ", c4.toString(), "   slope ", Double.toString(slope) }, " : ");
        System.out.println(msg);
        msg = StringUtils.join(new String[] { "Slice", ArrayUtils.toString(res.getPoint()), "R",
                Double.toString(function.regression.getR()) }, " : ");
        System.out.println(msg);
    } catch (MaxCountExceededException e) {
        return null;
    }
    return function.regression;
}