Search in sources :

Example 1 with ModelFunction

use of org.apache.commons.math3.optim.nonlinear.vector.ModelFunction in project dawnsci by DawnScience.

the class EllipseFitter method geometricFit.

@Override
public void geometricFit(IDataset x, IDataset y, double[] init) {
    residual = Double.NaN;
    if (x.getSize() < PARAMETERS || y.getSize() < PARAMETERS) {
        throw new IllegalArgumentException("Need " + PARAMETERS + " or more points");
    }
    if (init == null)
        init = quickfit(x, y);
    else if (init.length < PARAMETERS)
        throw new IllegalArgumentException("Need " + PARAMETERS + " parameters");
    EllipseCoordinatesFunction f = (EllipseCoordinatesFunction) getFitFunction(x, y);
    LevenbergMarquardtOptimizer opt = new LevenbergMarquardtOptimizer();
    try {
        PointVectorValuePair result = opt.optimize(new ModelFunction(f), new ModelFunctionJacobian(f.jacobian()), f.getTarget(), f.getWeight(), f.calcAllInitValues(init), new MaxEval(MAX_EVALUATIONS));
        double[] point = result.getPointRef();
        for (int i = 0; i < PARAMETERS; i++) parameters[i] = point[i];
        residual = opt.getRMS();
        logger.trace("Ellipse fit: rms = {}, x^2 = {}", residual, opt.getChiSquare());
    } catch (DimensionMismatchException e) {
    // cannot happen
    } catch (IllegalArgumentException e) {
    // should not happen!
    } catch (TooManyEvaluationsException e) {
        throw new IllegalArgumentException("Problem with optimizer converging");
    }
}
Also used : DimensionMismatchException(org.apache.commons.math3.exception.DimensionMismatchException) PointVectorValuePair(org.apache.commons.math3.optim.PointVectorValuePair) MaxEval(org.apache.commons.math3.optim.MaxEval) TooManyEvaluationsException(org.apache.commons.math3.exception.TooManyEvaluationsException) LevenbergMarquardtOptimizer(org.apache.commons.math3.optim.nonlinear.vector.jacobian.LevenbergMarquardtOptimizer) ModelFunction(org.apache.commons.math3.optim.nonlinear.vector.ModelFunction) ModelFunctionJacobian(org.apache.commons.math3.optim.nonlinear.vector.ModelFunctionJacobian) MathIllegalArgumentException(org.apache.commons.math3.exception.MathIllegalArgumentException)

Example 2 with ModelFunction

use of org.apache.commons.math3.optim.nonlinear.vector.ModelFunction in project s1tbx by senbox-org.

the class ArcDataIntegration method integrateArcsL2.

/**
 * Integrates arc data to node data using weighted least squares (L2 norm).
 *     This function integrates arc `data` by finding `point_data` (the returned
 *     value), such that `point_data` minimizes:
 *         ||diag(weights) * (A * point_data - data)||_2
 *     where `A` is an incidence matrix of dimensions 'number of arcs' by
 *     'number of nodes'.
 *     Description of the algorithm:
 *         1. Apply weights
 *             A = diag(weights) * A
 *             b = diag(weights) * data
 *         2. Minimize
 *             ||A*x - b||_2
 *
 * @param arcs every row should contain two indices corresponding to the end nodes of a specific arc.
 * @param data data to be integrated.
 * @param weights quality of arc data.
 * @return
 */
public static double[] integrateArcsL2(int[][] arcs, double[] data, double[] weights) {
    // graph size
    int noOfNodes = Arrays.stream(arcs).flatMapToInt(Arrays::stream).max().getAsInt() + 1;
    int noOfArcs = arcs.length;
    SystemUtils.LOG.fine("Number of nodes: " + noOfNodes);
    SystemUtils.LOG.fine("Number of arcs: " + noOfArcs);
    // A: coefficients matrix
    double[][] incidenceMatrix = new double[noOfArcs][noOfNodes];
    // get column and set to zero reference node occurrences
    int[] sourceNodes = getColumnVector(arcs, 0);
    // get column and set to zero reference node occurrences
    int[] targetNodes = getColumnVector(arcs, 1);
    // source nodes
    setValues(incidenceMatrix, repeat(-1.0, noOfArcs), null, sourceNodes);
    // target nodes
    setValues(incidenceMatrix, repeat(1.0, noOfArcs), null, targetNodes);
    // remove reference node column
    if (!referenceNodeIsLast) {
        // remove first column
        shiftColumnsLeft(incidenceMatrix, 1);
    }
    dropLastColumn(incidenceMatrix);
    // problem
    ModelFunction problem = new ModelFunction(new MultivariateVectorFunction() {

        RealMatrix jacobian = new Array2DRowRealMatrix(incidenceMatrix);

        public double[] value(double[] params) {
            double[] values = jacobian.operate(params);
            return values;
        }
    });
    ModelFunctionJacobian problemJacobian = new ModelFunctionJacobian(new MultivariateMatrixFunction() {

        double[][] jacobian = incidenceMatrix;

        public double[][] value(double[] params) {
            return jacobian;
        }
    });
    // optimization
    ConvergenceChecker<PointVectorValuePair> checker = new SimplePointChecker(0.00001, -1.0);
    LevenbergMarquardtOptimizer optimizer = new LevenbergMarquardtOptimizer(checker);
    int maxIterations = 10000;
    PointVectorValuePair solution = optimizer.optimize(new MaxEval(maxIterations), problem, problemJacobian, new Target(data), new Weight(weights), new InitialGuess(new double[noOfNodes - 1]));
    // return solution
    double[] nodeData;
    if (referenceNodeIsLast) {
        nodeData = Arrays.copyOf(solution.getPoint(), noOfNodes);
        // add reference node back (last)
        nodeData[noOfNodes - 1] = 0;
    } else {
        nodeData = new double[noOfNodes];
        // reference node (first) is 0
        System.arraycopy(solution.getPoint(), 0, nodeData, 1, noOfNodes - 1);
    }
    return nodeData;
}
Also used : MaxEval(org.apache.commons.math3.optim.MaxEval) InitialGuess(org.apache.commons.math3.optim.InitialGuess) ModelFunction(org.apache.commons.math3.optim.nonlinear.vector.ModelFunction) MultivariateVectorFunction(org.apache.commons.math3.analysis.MultivariateVectorFunction) LinearConstraint(org.apache.commons.math3.optim.linear.LinearConstraint) Weight(org.apache.commons.math3.optim.nonlinear.vector.Weight) PointVectorValuePair(org.apache.commons.math3.optim.PointVectorValuePair) Target(org.apache.commons.math3.optim.nonlinear.vector.Target) LevenbergMarquardtOptimizer(org.apache.commons.math3.optim.nonlinear.vector.jacobian.LevenbergMarquardtOptimizer) Array2DRowRealMatrix(org.apache.commons.math3.linear.Array2DRowRealMatrix) RealMatrix(org.apache.commons.math3.linear.RealMatrix) Array2DRowRealMatrix(org.apache.commons.math3.linear.Array2DRowRealMatrix) ModelFunctionJacobian(org.apache.commons.math3.optim.nonlinear.vector.ModelFunctionJacobian) MultivariateMatrixFunction(org.apache.commons.math3.analysis.MultivariateMatrixFunction) SimplePointChecker(org.apache.commons.math3.optim.SimplePointChecker)

Example 3 with ModelFunction

use of org.apache.commons.math3.optim.nonlinear.vector.ModelFunction in project dawnsci by DawnScience.

the class CircleFitter method geometricFit.

@Override
public void geometricFit(IDataset x, IDataset y, double[] init) {
    residual = Double.NaN;
    if (x.getSize() < PARAMETERS || y.getSize() < PARAMETERS) {
        throw new IllegalArgumentException("Need " + PARAMETERS + " or more points");
    }
    if (x.getSize() == PARAMETERS) {
        init = quickfit(x, y);
        for (int i = 0; i < PARAMETERS; i++) parameters[i] = init[i];
        residual = 0;
        return;
    }
    if (init == null)
        init = quickfit(x, y);
    else if (init.length < PARAMETERS)
        throw new IllegalArgumentException("Need " + PARAMETERS + " parameters");
    CircleCoordinatesFunction f = (CircleCoordinatesFunction) getFitFunction(x, y);
    LevenbergMarquardtOptimizer opt = new LevenbergMarquardtOptimizer();
    try {
        PointVectorValuePair result = opt.optimize(new ModelFunction(f), new ModelFunctionJacobian(f.jacobian()), f.getTarget(), f.getWeight(), f.calcAllInitValues(init), new MaxEval(MAX_EVALUATIONS));
        double[] point = result.getPointRef();
        for (int i = 0; i < PARAMETERS; i++) parameters[i] = point[i];
        residual = opt.getRMS();
        logger.trace("Circle fit: rms = {}, x^2 = {}", opt.getRMS(), opt.getChiSquare());
    } catch (DimensionMismatchException e) {
    // cannot happen
    } catch (IllegalArgumentException e) {
    // should not happen!
    } catch (TooManyEvaluationsException e) {
        throw new IllegalArgumentException("Problem with optimizer converging");
    }
}
Also used : DimensionMismatchException(org.apache.commons.math3.exception.DimensionMismatchException) PointVectorValuePair(org.apache.commons.math3.optim.PointVectorValuePair) MaxEval(org.apache.commons.math3.optim.MaxEval) TooManyEvaluationsException(org.apache.commons.math3.exception.TooManyEvaluationsException) LevenbergMarquardtOptimizer(org.apache.commons.math3.optim.nonlinear.vector.jacobian.LevenbergMarquardtOptimizer) ModelFunction(org.apache.commons.math3.optim.nonlinear.vector.ModelFunction) ModelFunctionJacobian(org.apache.commons.math3.optim.nonlinear.vector.ModelFunctionJacobian)

Aggregations

MaxEval (org.apache.commons.math3.optim.MaxEval)3 PointVectorValuePair (org.apache.commons.math3.optim.PointVectorValuePair)3 ModelFunction (org.apache.commons.math3.optim.nonlinear.vector.ModelFunction)3 ModelFunctionJacobian (org.apache.commons.math3.optim.nonlinear.vector.ModelFunctionJacobian)3 LevenbergMarquardtOptimizer (org.apache.commons.math3.optim.nonlinear.vector.jacobian.LevenbergMarquardtOptimizer)3 DimensionMismatchException (org.apache.commons.math3.exception.DimensionMismatchException)2 TooManyEvaluationsException (org.apache.commons.math3.exception.TooManyEvaluationsException)2 MultivariateMatrixFunction (org.apache.commons.math3.analysis.MultivariateMatrixFunction)1 MultivariateVectorFunction (org.apache.commons.math3.analysis.MultivariateVectorFunction)1 MathIllegalArgumentException (org.apache.commons.math3.exception.MathIllegalArgumentException)1 Array2DRowRealMatrix (org.apache.commons.math3.linear.Array2DRowRealMatrix)1 RealMatrix (org.apache.commons.math3.linear.RealMatrix)1 InitialGuess (org.apache.commons.math3.optim.InitialGuess)1 SimplePointChecker (org.apache.commons.math3.optim.SimplePointChecker)1 LinearConstraint (org.apache.commons.math3.optim.linear.LinearConstraint)1 Target (org.apache.commons.math3.optim.nonlinear.vector.Target)1 Weight (org.apache.commons.math3.optim.nonlinear.vector.Weight)1