Example usage for org.apache.commons.math3.fitting.leastsquares LeastSquaresBuilder weight

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

Introduction

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

Prototype

RealMatrix weight

To view the source code for org.apache.commons.math3.fitting.leastsquares LeastSquaresBuilder weight.

Click Source Link

Document

weight matrix

Usage

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

/**
 * create a multivariateJacobianFunction from MVF and MMF (using builder?)
 * //  w w  w.j  a v a  2 s. c  o  m
 */
private void internalLeastSquaresOptimize() {
    LeastSquaresOptimizer opt = createLeastSquaresOptimizer();

    try {

        LeastSquaresBuilder builder = new LeastSquaresBuilder().model(createJacobianFunction())
                .target(data.getData()).start(getParameterValues()).lazyEvaluation(false)
                .maxEvaluations(MAX_EVAL).maxIterations(MAX_ITER);

        builder.checker(new EvaluationRmsChecker(REL_TOL, ABS_TOL));

        if (weight != null) {
            builder.weight(MatrixUtils.createRealDiagonalMatrix(weight.getData()));
        }

        // TODO add checker, validator
        LeastSquaresProblem problem = builder.build();

        Optimum result = opt.optimize(problem);

        RealVector res = result.getPoint();
        setParameterValues(
                res instanceof ArrayRealVector ? ((ArrayRealVector) res).getDataRef() : res.toArray());
        try {
            RealVector err = result.getSigma(1e-14);

            //            sqrt(S / (n - m) * C[i][i]);
            double c = result.getCost();
            int n = data.getSize();
            int m = getParameterValues().length;

            double[] s = err instanceof ArrayRealVector ? ((ArrayRealVector) err).getDataRef() : err.toArray();

            errors = new double[s.length];

            for (int i = 0; i < errors.length; i++)
                errors[i] = Math.sqrt(((c * c) / ((n - m)) * (s[i] * s[i])));

        } catch (SingularMatrixException e) {
            logger.warn("Could not find errors as covariance matrix was singular");
        }

        logger.trace("Residual: {} from {}", result.getRMS(), Math.sqrt(calculateResidual()));
    } catch (Exception e) {
        logger.error("Problem with least squares optimizer", e);
        throw new IllegalArgumentException("Problem with least squares optimizer");
    }
}