Example usage for org.apache.commons.math3.analysis.interpolation LoessInterpolator LoessInterpolator

List of usage examples for org.apache.commons.math3.analysis.interpolation LoessInterpolator LoessInterpolator

Introduction

In this page you can find the example usage for org.apache.commons.math3.analysis.interpolation LoessInterpolator LoessInterpolator.

Prototype

public LoessInterpolator(double bandwidth, int robustnessIters) 

Source Link

Document

Construct a new LoessInterpolator with given bandwidth and number of robustness iterations.

Usage

From source file:ubic.basecode.math.linearmodels.MeanVarianceEstimator.java

/**
 * First ensures that x values are strictly increasing and performs a loess fit afterwards. The loess fit are
 * determined by <code>BANDWIDTH</code> and <code>ROBUSTNESS_ITERS</code>.
 * /*w  ww . ja v a2  s .c  o  m*/
 * @param xy
 * @return loessFit or null if there are less than 3 data points
 */
private DoubleMatrix2D loessFit(DoubleMatrix2D xy) {
    assert xy != null;

    DoubleMatrix1D sx = xy.viewColumn(0);
    DoubleMatrix1D sy = xy.viewColumn(1);
    Map<Double, Double> map = new TreeMap<>();
    for (int i = 0; i < sx.size(); i++) {
        if (Double.isNaN(sx.get(i)) || Double.isInfinite(sx.get(i)) || Double.isNaN(sy.get(i))
                || Double.isInfinite(sy.get(i))) {
            continue;
        }
        map.put(sx.get(i), sy.get(i));
    }
    DoubleMatrix2D xyChecked = new DenseDoubleMatrix2D(map.size(), 2);
    xyChecked.viewColumn(0).assign(ArrayUtils.toPrimitive(map.keySet().toArray(new Double[0])));
    xyChecked.viewColumn(1).assign(ArrayUtils.toPrimitive(map.values().toArray(new Double[0])));

    // in R:
    // loess(c(1:5),c(1:5)^2,f=0.5,iter=3)
    // Note: we start to loose some precision here in comparison with R's loess FIXME why? does it matter?
    DoubleMatrix2D loessFit = new DenseDoubleMatrix2D(xyChecked.rows(), xyChecked.columns());
    // try {
    // fit a loess curve
    LoessInterpolator loessInterpolator = new LoessInterpolator(MeanVarianceEstimator.BANDWIDTH,
            MeanVarianceEstimator.ROBUSTNESS_ITERS);

    double[] loessY = loessInterpolator.smooth(xyChecked.viewColumn(0).toArray(),
            xyChecked.viewColumn(1).toArray());

    loessFit.viewColumn(0).assign(xyChecked.viewColumn(0));
    loessFit.viewColumn(1).assign(loessY);

    return loessFit;
}