Example usage for org.apache.commons.math3.fitting PolynomialCurveFitter fit

List of usage examples for org.apache.commons.math3.fitting PolynomialCurveFitter fit

Introduction

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

Prototype

public double[] fit(Collection<WeightedObservedPoint> points) 

Source Link

Document

Fits a curve.

Usage

From source file:org.bonej.wrapperPlugins.FractalDimensionWrapper.java

private double[] fitCurve(final Collection<ValuePair<DoubleType, DoubleType>> pairs) {
    if (!allValuesFinite(pairs)) {
        return new double[2];
    }//from  www .  j  a va  2  s.  co  m
    final WeightedObservedPoints points = toWeightedObservedPoints(pairs);
    final PolynomialCurveFitter curveFitter = PolynomialCurveFitter.create(1);
    return curveFitter.fit(points.toList());
}

From source file:org.micromanager.asidispim.fit.Fitter.java

/**
 * Utility to facilitate fitting data plotted in JFreeChart
 * Provide data in JFReeChart format (XYSeries), and retrieve univariate
 * function parameters that best fit (using least squares) the data. All data
 * points will be weighted equally./*  w w w .  ja v  a  2 s .  c o m*/
 * 
 * TODO: investigate whether weighting (possibly automatic weighting) can
 * improve accuracy
 * 
 * @param data xy series in JFReeChart format
 * @param type one of the Fitter.FunctionType predefined functions
 * @param guess initial guess for the fit.  The number and meaning of these
     parameters depends on the FunctionType.  Implemented:
     Gaussian: 0: Normalization, 1: Mean 2: Sigma
        
 * @return array with parameters, whose meaning depends on the FunctionType.
 *          Use the function getXYSeries to retrieve the XYDataset predicted 
 *          by this fit
 */
public static double[] fit(XYSeries data, FunctionType type, double[] guess) {

    if (type == FunctionType.NoFit) {
        return null;
    }
    // create the commons math data object from the JFreeChart data object
    final WeightedObservedPoints obs = new WeightedObservedPoints();
    for (int i = 0; i < data.getItemCount(); i++) {
        obs.add(1.0, data.getX(i).doubleValue(), data.getY(i).doubleValue());
    }

    double[] result = null;
    switch (type) {
    case Pol1:
        final PolynomialCurveFitter fitter1 = PolynomialCurveFitter.create(1);
        result = fitter1.fit(obs.toList());
        break;
    case Pol2:
        final PolynomialCurveFitter fitter2 = PolynomialCurveFitter.create(2);
        result = fitter2.fit(obs.toList());
        break;
    case Pol3:
        final PolynomialCurveFitter fitter3 = PolynomialCurveFitter.create(3);
        result = fitter3.fit(obs.toList());
        break;
    case Gaussian:
        final GaussianWithOffsetCurveFitter gf = GaussianWithOffsetCurveFitter.create();
        if (guess != null) {
            gf.withStartPoint(guess);
        }
        result = gf.fit(obs.toList());
    default:
        break;
    }

    return result;
}

From source file:org.micromanager.saim.fit.Fitter.java

/**
 * Utility to facilitate fitting data plotted in JFreeChart
 * Provide data in JFReeChart format (XYSeries), and retrieve univariate
 * function parameters that best fit (using least squares) the data. All data
 * points will be weighted equally./*from  w  w w .jav a  2  s  .  co  m*/
 * 
 * Various weightmethods are implemented and can be selected using the 
 * weightMethods parameter.
 * 
 * @param data xy series in JFReeChart format
 * @param type one of the Fitter.FunctionType predefined functions
 * @param guess initial guess for the fit.  The number and meaning of these
     parameters depends on the FunctionType.  Implemented:
     Gaussian: 0: Normalization, 1: Mean 2: Sigma
 * @param weightMethod One of the methods in the WeightMethod enum
        
 * @return array with parameters, whose meaning depends on the FunctionType.
 *          Use the function getXYSeries to retrieve the XYDataset predicted 
 *          by this fit
 */
public static double[] fit(XYSeries data, FunctionType type, double[] guess, WeightMethod weightMethod) {

    if (type == FunctionType.NoFit) {
        return null;
    }
    // create the commons math data object from the JFreeChart data object
    final WeightedObservedPoints obs = new WeightedObservedPoints();
    // range is used in weigt calculations
    double range = data.getMaxY() - data.getMinY();
    for (int i = 0; i < data.getItemCount(); i++) {
        // add weight based on y intensity and selected weight method
        double weight = 1.0; // used in Equal method
        if (weightMethod != WeightMethod.Equal) {
            double valueMinusMin = data.getY(i).doubleValue() - data.getMinY();
            weight = valueMinusMin / range;
            switch (weightMethod) {
            case Equal:
                break; // weight is already linear
            case Quadratic:
                weight *= weight;
                break;
            case Top50Linear:
                if (valueMinusMin < (0.5 * range))
                    weight = 0.0;
                break;
            case Top80Linear:
                if (valueMinusMin < (0.8 * range))
                    weight = 0.0;
                break;
            }
        }

        obs.add(weight, data.getX(i).doubleValue(), data.getY(i).doubleValue());
    }

    // Carry out the actual fit
    double[] result = null;
    switch (type) {
    case Pol1:
        final PolynomialCurveFitter fitter1 = PolynomialCurveFitter.create(1);
        result = fitter1.fit(obs.toList());
        break;
    case Pol2:
        final PolynomialCurveFitter fitter2 = PolynomialCurveFitter.create(2);
        result = fitter2.fit(obs.toList());
        break;
    case Pol3:
        final PolynomialCurveFitter fitter3 = PolynomialCurveFitter.create(3);
        result = fitter3.fit(obs.toList());
        break;
    case Gaussian:
        GaussianWithOffsetCurveFitter gf = GaussianWithOffsetCurveFitter.create();
        gf = gf.withMaxIterations(50);
        if (guess != null) {
            gf.withStartPoint(guess);
        }
        result = gf.fit(obs.toList());
    }

    return result;
}

From source file:org.specvis.logic.Functions.java

/**
 * Get fitting coefficients for N degree polynomial.
 * @param x//from ww w.j  a va  2 s  .c o m
 * @param y
 * @param degree
 * @param reverseCoefficients
 * @return Fitting coefficients.
 */
public double[] fitPolynomialToData(double[] x, double[] y, int degree, boolean reverseCoefficients) {
    WeightedObservedPoints obs = new WeightedObservedPoints();
    for (int i = 0; i < x.length; i++) {
        obs.add(1, x[i], y[i]);
    }
    PolynomialCurveFitter fitter = PolynomialCurveFitter.create(degree);
    double[] coefficients = fitter.fit(obs.toList());
    if (reverseCoefficients) {
        return reverseDoublePrimitiveArray(coefficients);
    } else {
        return coefficients;
    }
}

From source file:projetoFinal.FuncoesEstatisticas.java

public void setQuadraticRegression(List<Double> x, List<Double> y) {
    obs.clear();//from  ww  w .j  a  v  a  2s .com
    setCoefCQuadraticReg(0);
    setCoefBQuadraticReg(0);
    setCoefAQuadraticReg(0);

    for (int i = 0; i < x.size() && x.size() == y.size(); i++) {
        obs.add(x.get(i), y.get(i));
    }
    if (x.size() > 0 && x.size() == y.size()) {
        final PolynomialCurveFitter fitter = PolynomialCurveFitter.create(2);
        final double[] coeff = fitter.fit(obs.toList());

        setCoefCQuadraticReg(coeff[0]);
        setCoefBQuadraticReg(coeff[1]);
        setCoefAQuadraticReg(coeff[2]);
    }
}

From source file:uk.ac.leeds.ccg.andyt.projects.fluvialglacial.SlopeAreaScatterPlot.java

public SlopeAreaScatterPlot(int degree, Object[] data, ExecutorService executorService, File file,
        String format, String title, int dataWidth, int dataHeight, String xAxisLabel, String yAxisLabel,
        boolean drawOriginLinesOnPlot, int decimalPlacePrecisionForCalculations,
        int decimalPlacePrecisionForDisplay, RoundingMode aRoundingMode) {
    init(executorService, file, format, title, dataWidth, dataHeight, xAxisLabel, yAxisLabel,
            drawOriginLinesOnPlot, decimalPlacePrecisionForCalculations, decimalPlacePrecisionForDisplay,
            aRoundingMode);/*from  ww  w . ja  v  a2  s.c o m*/
    setStartAgeOfEndYearInterval(0);
    setData(data);
    PolynomialCurveFitter pcf;
    pcf = PolynomialCurveFitter.create(degree);
    final WeightedObservedPoints obs = new WeightedObservedPoints();
    ArrayList<Generic_XYNumericalData> theGeneric_XYNumericalData;
    theGeneric_XYNumericalData = (ArrayList<Generic_XYNumericalData>) data[0];
    Iterator<Generic_XYNumericalData> ite;
    ite = theGeneric_XYNumericalData.iterator();
    Generic_XYNumericalData generic_XYNumericalData;
    while (ite.hasNext()) {
        generic_XYNumericalData = ite.next();
        obs.add(generic_XYNumericalData.x.doubleValue(), generic_XYNumericalData.y.doubleValue());
    }
    double[] coeffs = pcf.fit(obs.toList());
    title += ", y = ";
    BigDecimal coeffBD;
    String coeffS;

    double a = 0.0d;
    double b = 0.0d;
    double c = 0.0d;
    for (int i = coeffs.length - 1; i > -1; i--) {
        System.out.println(coeffs[i]);
        coeffBD = Generic_BigDecimal.roundToAndSetDecimalPlaces(BigDecimal.valueOf(coeffs[i]),
                decimalPlacePrecisionForDisplay, aRoundingMode);
        coeffS = coeffBD.toPlainString();
        String s;
        s = getCoeff(coeffBD, coeffS);
        if (i > 1) {
            if (!s.isEmpty()) {
                title += "(" + s + "*x^" + i + ")+";
            }

            if (i == 2) {
                a = Double.valueOf(s);
            }

        } else if (i == 1) {
            if (!s.isEmpty()) {
                title += "(" + s + "*x)";
                b = Double.valueOf(s);
            } else {
                b = 0.0d;
            }
        } else if (!s.isEmpty()) {
            title += s;
            c = Double.valueOf(s);
        } else {
            c = 0.0d;
        }
        //title += "" + coeffs[i] + ",";
    }
    //title = title.substring(0, (title.length() - 3));
    //title += ")";

    PolynomialFunction pf;
    pf = new PolynomialFunction(coeffs);
    double minx = getMinX().doubleValue();
    double maxx = getMaxX().doubleValue();
    double range = maxx - minx;
    int intervals = 100;
    double interval = range / (double) intervals;

    maxy = Double.NEGATIVE_INFINITY;

    double x;
    double y;
    bestfit = new ArrayList<Generic_XYNumericalData>();
    for (int i = 0; i < 100; i++) {
        x = minx + interval * i;
        y = pf.value(x);
        if (y > maxy) {
            maxy = y;
            xAtMaxy = x;
        }
        generic_XYNumericalData = new Generic_XYNumericalData(BigDecimal.valueOf(x), BigDecimal.valueOf(y));
        bestfit.add(generic_XYNumericalData);
    }

    maxy2 = Double.NEGATIVE_INFINITY;
    if (a < 0) {
        maxy2 = c - ((b * b) / (4.0d * a));
        xAtMaxy2 = (-1.0d * b) / (2.0d * a);
        isHump = true;
    } else {
        isHump = false;
    }

    double SRMSE = 0.0d;
    double deltay;
    ite = theGeneric_XYNumericalData.iterator();
    while (ite.hasNext()) {
        generic_XYNumericalData = ite.next();
        x = generic_XYNumericalData.x.doubleValue();
        y = generic_XYNumericalData.y.doubleValue();
        deltay = Math.sqrt(Math.pow(y - pf.value(x), 2));
        SRMSE += deltay;
    }
    double MRMSE = SRMSE / (double) theGeneric_XYNumericalData.size();
    title += ", MRMSE = " + (Generic_BigDecimal.roundToAndSetDecimalPlaces(BigDecimal.valueOf(MRMSE),
            decimalPlacePrecisionForDisplay, aRoundingMode)).toPlainString();
    setTitle(title);
}