Example usage for org.apache.commons.math3.fitting.leastsquares LevenbergMarquardtOptimizer LevenbergMarquardtOptimizer

List of usage examples for org.apache.commons.math3.fitting.leastsquares LevenbergMarquardtOptimizer LevenbergMarquardtOptimizer

Introduction

In this page you can find the example usage for org.apache.commons.math3.fitting.leastsquares LevenbergMarquardtOptimizer LevenbergMarquardtOptimizer.

Prototype

public LevenbergMarquardtOptimizer() 

Source Link

Document

Default constructor.

Usage

From source file:eu.crisis_economics.abm.markets.clearing.heterogeneous.LevenbergMarquardtClearingAlgorithm.java

@Override
public double applyToNetwork(final MixedClearingNetwork network) {
    Preconditions.checkNotNull(network);

    final VectorCostFunction function = super.getVectorCostFunction(network);
    final MultivariateJacobianFunction model = LeastSquaresFactory.model(function,
            super.getJacobianMatrixFunction(network));
    final RealVector observed = new ArrayRealVector(super.calculateTarget(network)),
            start = new ArrayRealVector(network.getNumberOfEdges());
    for (int i = 0; i < network.getNumberOfEdges(); ++i)
        start.setEntry(i, network.getEdges().get(i).getMaximumRateAdmissibleByBothParties());
    start.set(1.0);/* ww w .j a  v a  2 s. c  o m*/

    final ConvergenceChecker<LeastSquaresProblem.Evaluation> evaluationChecker = LeastSquaresFactory
            .evaluationChecker(new SimpleVectorValueChecker(relErrorTarget, absErrorTarget));
    final LeastSquaresProblem problem = LeastSquaresFactory.create(model, observed, start, evaluationChecker,
            maximumEvaluations, maximumIterations);

    final LevenbergMarquardtOptimizer optimizer = new LevenbergMarquardtOptimizer();
    final Optimum result = optimizer.optimize(problem);

    final double residualCost = result.getRMS();
    System.out.println("Network cleared: residual cost: " + residualCost + ".");

    return residualCost;
}

From source file:iocomms.subpos.ArrayLocations.java

private Position trilaterate(ArrayLocations locations) {
    //Trilateration nonlinear weighted least squares

    //https://github.com/lemmingapex/Trilateration - MIT Licence
    //http://commons.apache.org/proper/commons-math/download_math.cgi

    double[][] positions = new double[locations.size()][3];
    double[] distances = new double[locations.size()];
    int i = 0;// w w  w  .j  a  v a2s  .  c o m
    while (i < locations.size()) {

        //Map projection is treated as Mercator for calcs
        //Convert lat,lng to meters and then back again
        //Altitude is in cm

        positions[i] = new double[] { WebMercator.latitudeToY(locations.get(i).lat),
                WebMercator.longitudeToX(locations.get(i).lng), locations.get(i).altitude };

        distances[i] = locations.get(i).distance;
        i++;
    }
    TrilaterationFunction trilaterationFunction = new TrilaterationFunction(positions, distances);
    NonLinearLeastSquaresSolver solver = new NonLinearLeastSquaresSolver(trilaterationFunction,
            new LevenbergMarquardtOptimizer());

    LeastSquaresOptimizer.Optimum optimum = solver.solve();
    double[] centroid = optimum.getPoint().toArray();

    double errorRadius = 0;
    boolean errorCalc = false;

    // Error and geometry information
    try {
        //Create new array without the altitude. Including altitude causes a
        //SingularMatrixException as it cannot invert the matrix.
        double[][] err_positions = new double[locations.size()][2];
        i = 0;
        while (i < locations.size()) {

            err_positions[i] = new double[] { positions[i][0], positions[i][1] };
            i++;
        }
        trilaterationFunction = new TrilaterationFunction(err_positions, distances);
        solver = new NonLinearLeastSquaresSolver(trilaterationFunction, new LevenbergMarquardtOptimizer());

        optimum = solver.solve();
        RealVector standardDeviation = optimum.getSigma(0);
        //RealMatrix covarianceMatrix = optimum.getCovariances(0);

        errorRadius = ((standardDeviation.getEntry(0) + standardDeviation.getEntry(1)) / 2) * 100;
        errorCalc = true;

    } catch (Exception ex) {
        errorRadius = 0;
        errorCalc = false;
    }

    return new Position(WebMercator.yToLatitude(optimum.getPoint().toArray()[0]),
            WebMercator.xToLongitude(centroid[1]), centroid[2], errorRadius, errorCalc);

}

From source file:de.bund.bfr.math.LeastSquaresOptimization.java

@Override
public Result optimize(int nParameterSpace, int nOptimizations, boolean stopWhenSuccessful,
        Map<String, Double> minStartValues, Map<String, Double> maxStartValues, int maxIterations,
        DoubleConsumer progressListener, ExecutionContext exec) throws CanceledExecutionException {
    if (exec != null) {
        exec.checkCanceled();/*w  w  w. j av a 2s.  c o  m*/
    }

    progressListener.accept(0.0);

    List<ParamRange> ranges = MathUtils.getParamRanges(parameters, minStartValues, maxStartValues,
            nParameterSpace);
    RealVector targetVector = new ArrayRealVector(Doubles.toArray(targetValues));
    List<StartValues> startValuesList = MathUtils.createStartValuesList(ranges, nOptimizations,
            values -> targetVector
                    .getDistance(new ArrayRealVector(optimizerFunction.value(Doubles.toArray(values)))),
            progress -> progressListener.accept(0.5 * progress), exec);
    LevenbergMarquardtOptimizer optimizer = new LevenbergMarquardtOptimizer();
    Result result = new Result();
    AtomicInteger count = new AtomicInteger(0);

    for (StartValues startValues : startValuesList) {
        if (exec != null) {
            exec.checkCanceled();
        }

        progressListener.accept(0.5 * count.get() / startValuesList.size() + 0.5);

        try {
            LeastSquaresBuilder builder = createLeastSquaresBuilder(startValues.getValues(), maxIterations);

            builder.checker((iteration, previous, current) -> {
                double currentProgress = (double) iteration / (double) maxIterations;

                if (exec != null) {
                    try {
                        exec.checkCanceled();
                    } catch (CanceledExecutionException e) {
                        return true;
                    }
                }

                progressListener.accept(0.5 * (count.get() + currentProgress) / startValuesList.size() + 0.5);
                return iteration == maxIterations;
            });

            LeastSquaresOptimizer.Optimum optimizerResults = optimizer.optimize(builder.build());

            if (exec != null) {
                exec.checkCanceled();
            }

            double cost = optimizerResults.getCost();

            if (result.sse == null || cost * cost < result.sse) {
                result = getResults(optimizerResults);

                if (result.sse == 0.0) {
                    break;
                }

                if (result.r2 != null && result.r2 > 0.0 && stopWhenSuccessful) {
                    break;
                }
            }
        } catch (TooManyEvaluationsException | TooManyIterationsException | ConvergenceException e) {
        }

        count.incrementAndGet();
    }

    return result;
}

From source file:de.bund.bfr.knime.pmm.common.math.ParameterOptimizer.java

private void optimize(List<Double> startValues) throws Exception {
    double[] targets = new double[targetValues.size()];
    double[] startValueArray = new double[startValues.size()];

    for (int i = 0; i < targetValues.size(); i++) {
        targets[i] = targetValues.get(i);
    }//from  w  w w. j a v a 2 s  .  c om

    for (int i = 0; i < startValues.size(); i++) {
        startValueArray[i] = startValues.get(i);
    }

    OptimizerFunction optimizerFunction = new OptimizerFunction(parser, function, parameters, arguments,
            argumentValues, targetValues);
    OptimizerFunctionJacobian optimizerFunctionJacobian = new OptimizerFunctionJacobian(parser, function,
            parameters, derivatives, arguments, argumentValues, targetValues);

    LeastSquaresBuilder builder = new LeastSquaresBuilder().model(optimizerFunction, optimizerFunctionJacobian)
            .maxEvaluations(MAX_EVAL).maxIterations(MAX_EVAL).target(targets).start(startValueArray);

    optimizerValues = new LevenbergMarquardtOptimizer().optimize(builder.build());
}

From source file:org.orekit.propagation.conversion.AbstractPropagatorConverter.java

/** Build a new instance.
 * @param builder propagator builder//from  ww w  .  ja va  2  s  . c  o m
 * @param threshold absolute convergence threshold for optimization algorithm
 * @param maxIterations maximum number of iterations for fitting
 */
protected AbstractPropagatorConverter(final PropagatorBuilder builder, final double threshold,
        final int maxIterations) {
    this.builder = builder;
    this.frame = builder.getFrame();
    this.availableParameters = builder.getSupportedParameters();
    this.optimizer = new LevenbergMarquardtOptimizer();
    this.maxIterations = maxIterations;
    this.sample = new ArrayList<SpacecraftState>();

    final SimpleVectorValueChecker svvc = new SimpleVectorValueChecker(-1.0, threshold);
    this.checker = LeastSquaresFactory.evaluationChecker(svvc);

}

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

private LeastSquaresOptimizer createLeastSquaresOptimizer() {
    switch (optimizer) {
    case GAUSS_NEWTON:
        return new GaussNewtonOptimizer();
    case LEVENBERG_MARQUARDT:
        return new LevenbergMarquardtOptimizer();
    default:/*from w  w  w . ja v a2  s. c  om*/
        throw new IllegalStateException("Should not be called");
    }
}