Example usage for org.apache.commons.math3.analysis.interpolation UnivariateInterpolator interpolate

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

Introduction

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

Prototype

UnivariateFunction interpolate(double xval[], double yval[]);

Source Link

Document

Compute an interpolating function for the dataset.

Usage

From source file:com.bwc.ora.models.Lrp.java

/**
 * Get the local maximums from a collection of Points.
 *
 * @param lrpSeries/*from   ww  w .  j av  a  2s .  co m*/
 * @param seriesTitle
 * @return
 */
public static XYSeries getMaximumsWithHiddenPeaks(XYSeries lrpSeries, String seriesTitle) {
    XYSeries maxPoints = new XYSeries(seriesTitle);

    //convert to x and y coordinate arrays
    double[][] xyline = lrpSeries.toArray();

    //use a spline interpolator to converts points into an equation
    UnivariateInterpolator interpolator = new SplineInterpolator();
    UnivariateFunction function = interpolator.interpolate(xyline[0], xyline[1]);

    // create a differentiator using 5 points and 0.01 step
    FiniteDifferencesDifferentiator differentiator = new FiniteDifferencesDifferentiator(5, 0.01);

    // create a new function that computes both the value and the derivatives
    // using DerivativeStructure
    UnivariateDifferentiableFunction completeF = differentiator.differentiate(function);

    // now we can compute the value and its derivatives
    // here we decided to display up to second order derivatives,
    // because we feed completeF with order 2 DerivativeStructure instances
    //find local minima in second derivative, these indicate the peaks (and hidden peaks)
    //of the input
    for (double x = xyline[0][0] + 1; x < xyline[0][xyline[0].length - 1] - 1; x += 0.5) {
        DerivativeStructure xDSc = new DerivativeStructure(1, 2, 0, x);
        DerivativeStructure xDSl = new DerivativeStructure(1, 2, 0, x - 0.5);
        DerivativeStructure xDSr = new DerivativeStructure(1, 2, 0, x + 0.5);
        DerivativeStructure yDSc = completeF.value(xDSc);
        DerivativeStructure yDSl = completeF.value(xDSl);
        DerivativeStructure yDSr = completeF.value(xDSr);
        double c2d = yDSc.getPartialDerivative(2);
        if (c2d < yDSl.getPartialDerivative(2) && c2d < yDSr.getPartialDerivative(2)) {
            maxPoints.add((int) Math.round(x), yDSc.getValue());
        }
    }

    return maxPoints;
}

From source file:area.math.nm.lib.Interpolation.java

public UnivariateFunction splinePlot(double x[], double y[]) {
    UnivariateInterpolator interpolator = new SplineInterpolator();
    UnivariateFunction function = interpolator.interpolate(x, y);
    return (function);
}

From source file:area.math.nm.lib.Interpolation.java

public String splineInterpolation(double x[], double y[], double input) {
    UnivariateInterpolator interpolator = new SplineInterpolator();
    UnivariateFunction function = interpolator.interpolate(x, y);
    double interpolationX = input;
    double interpolatedY = function.value(input);
    System.out.println("f(" + interpolationX + ") = " + interpolatedY);
    String result = new String(Double.toString(interpolatedY));
    return (result);
}

From source file:eu.crisis_economics.abm.algorithms.statistics.TestFloorInterpolator.java

/**
  * Test whether an instance of {@link FloorInterpolator} interpolates
  * a simple discrete input series as expected. This unit test operates
  * as follows:<br><br>/* w w  w.ja  v a  2s .  c  o  m*/
  * 
  * {@code (a)}
  *    A short discrete subsequence of the function {@code f(T) = T**2}
  *    is generated;<br>
  * {@code (b)}
  *    An instance of {@link FloorInterpolator} is used to create a
  *   {@link UnivariateFunction}, {@code U}, from this sequence;<br>
  * {@code (c)}
  *    {@code U} is sampled repeatedly for a number of points in the domain
  *    of the input sequence. The results of this operation are compared
  *    to correct, expected outputs.
  */
@Test
public void testFloorInterpolatorOutput() {
    final double[] x = new double[] { 2., 3., 4., 5., 6., }, y = new double[] { 4., 9., 16., 25., 36., };
    final double[] expectedResults = { -Double.MAX_VALUE, 4.000000000, Double.MIN_VALUE, 4.000000000,
            1.000000000, 4.000000000, 1.111111111, 4.000000000, 1.222222222, 4.000000000, 1.333333333,
            4.000000000, 1.444444444, 4.000000000, 1.555555556, 4.000000000, 1.666666667, 4.000000000,
            1.777777778, 4.000000000, 1.888888889, 4.000000000, 2.000000000, 4.000000000, 2.111111111,
            4.000000000, 2.222222222, 4.000000000, 2.333333333, 4.000000000, 2.444444444, 4.000000000,
            2.555555556, 4.000000000, 2.666666667, 4.000000000, 2.777777778, 4.000000000, 2.888888889,
            4.000000000, 3.000000000, 9.000000000, 3.111111111, 9.000000000, 3.222222222, 9.000000000,
            3.333333333, 9.000000000, 3.444444444, 9.000000000, 3.555555556, 9.000000000, 3.666666667,
            9.000000000, 3.777777778, 9.000000000, 3.888888889, 9.000000000, 4.000000000, 16.00000000,
            4.111111111, 16.00000000, 4.222222222, 16.00000000, 4.333333333, 16.00000000, 4.444444444,
            16.00000000, 4.555555556, 16.00000000, 4.666666667, 16.00000000, 4.777777778, 16.00000000,
            4.888888889, 16.00000000, 5.000000000, 25.00000000, 5.111111111, 25.00000000, 5.222222222,
            25.00000000, 5.333333333, 25.00000000, 5.444444444, 25.00000000, 5.555555556, 25.00000000,
            5.666666667, 25.00000000, 5.777777778, 25.00000000, 5.888888889, 25.00000000, 6.000000000,
            36.00000000, 6.111111111, 36.00000000, 6.222222222, 36.00000000, 6.333333333, 36.00000000,
            6.444444444, 36.00000000, 6.555555556, 36.00000000, 6.666666667, 36.00000000, 6.777777778,
            36.00000000, 6.888888889, 36.00000000, 7.000000000, 36.00000000, 7.111111111, 36.00000000,
            7.222222222, 36.00000000, 7.333333333, 36.00000000, 7.444444444, 36.00000000, 7.555555556,
            36.00000000, 7.666666667, 36.00000000, 7.777777778, 36.00000000, 7.888888889, 36.00000000,
            8.000000000, 36.00000000, 8.111111111, 36.00000000, 8.222222222, 36.00000000, 8.333333333,
            36.00000000, 8.444444444, 36.00000000, 8.555555556, 36.00000000, 8.666666667, 36.00000000,
            8.777777778, 36.00000000, 8.888888889, 36.00000000, 9.000000000, 36.00000000, 9.111111111,
            36.00000000, 9.222222222, 36.00000000, 9.333333333, 36.00000000, 9.444444444, 36.00000000,
            9.555555556, 36.00000000, 9.666666667, 36.00000000, 9.777777778, 36.00000000, 9.888888889,
            36.00000000, 10.00000000, 36.00000000, 10.11111111, 36.00000000, 10.22222222, 36.00000000,
            10.33333333, 36.00000000, 10.44444444, 36.00000000, 10.55555556, 36.00000000, 10.66666667,
            36.00000000, 10.77777778, 36.00000000, 10.88888889, 36.00000000, 11.00000000, 36.00000000,
            11.11111111, 36.00000000, 11.22222222, 36.00000000, 11.33333333, 36.00000000, 11.44444444,
            36.00000000, 11.55555556, 36.00000000, 11.66666667, 36.00000000, 11.77777778, 36.00000000,
            11.88888889, 36.00000000, 12.00000000, 36.00000000, Double.MAX_VALUE, 36.00000000 };
    final UnivariateInterpolator interpolator = new FloorInterpolator();
    final UnivariateFunction f = interpolator.interpolate(x, y);
    for (int i = 0; i < expectedResults.length; i += 2) {
        final double t = expectedResults[i], f_t_Observed = f.value(t), f_t_Expected = expectedResults[i + 1];
        System.out.printf("t: %16.10g observed: %16.10g expected: %16.10g\n", t, f_t_Observed, f_t_Expected);
        Assert.assertEquals(f_t_Observed, f_t_Expected, 1.e-12);
    }
}

From source file:com.gordoni.opal.LSInterpolator.java

public LSInterpolator(MapPeriod mp, int what, boolean linear_spline) {
    this.mp = mp;
    this.linear_spline = linear_spline;

    Scenario scenario = mp.scenario;//from ww w  .j a  v  a2  s.c  om
    Config config = scenario.config;

    xval = new double[mp.length[0]];
    for (int i = 0; i < xval.length; i++)
        xval[(xval.length - 1) - i] = scenario.scale[0].bucket_to_pf(mp.bottom[0] + i);
    yval = new double[mp.length[1]];
    for (int i = 0; i < yval.length; i++)
        yval[(yval.length - 1) - i] = scenario.scale[1].bucket_to_pf(mp.bottom[1] + i);

    fval = new double[mp.length[0]][mp.length[1]];
    MapPeriodIterator<MapElement> mpitr = mp.iterator();
    while (mpitr.hasNext()) {
        int[] bucket = mpitr.nextIndex().clone();
        MapElement me = mpitr.next();
        int xindex = (xval.length - 1) - (bucket[0] - mp.bottom[0]);
        int yindex = (yval.length - 1) - (bucket[1] - mp.bottom[1]);
        fval[xindex][yindex] = getWhat(me, what);
    }
    if (!linear_spline) {
        // spline-linear.
        double tmp[] = xval;
        xval = yval;
        yval = tmp;
        fval = Utils.zipDoubleArrayArray(fval);
    }

    this.f = new UnivariateFunction[fval.length];
    for (int i = 0; i < fval.length; i++) {
        UnivariateInterpolator interpolator;
        interpolator = new SplineInterpolator();
        this.f[i] = interpolator.interpolate(yval, fval[i]);
    }
}

From source file:com.itemanalysis.psychometrics.kernel.KernelDensity.java

public UnivariateFunction getInterpolater() {
    UnivariateInterpolator interpolator = new LinearInterpolator();
    UnivariateFunction func = interpolator.interpolate(points, evaluate());
    return func;//  w  w  w . j a va 2s . c om
}

From source file:com.itemanalysis.psychometrics.kernel.KernelDensity.java

/**
 * Returns interpolator for squared evaluate
 *
 * @return//from   ww w .jav a 2  s.  co  m
 */
public UnivariateFunction getInterpolater2() {
    UnivariateInterpolator interpolator = new LinearInterpolator();
    double[] d = evaluate();
    for (int i = 0; i < d.length; i++) {
        d[i] = d[i] * d[i];
    }
    UnivariateFunction func = interpolator.interpolate(points, d);
    return func;
}

From source file:com.gordoni.opal.UniInterpolator.java

public UniInterpolator(MapPeriod mp, int what) {
    this.mp = mp;

    Scenario scenario = mp.scenario;//from w ww  .  jav a  2 s .c o  m
    Config config = scenario.config;

    xval = new double[mp.length[0]];
    for (int i = 0; i < xval.length; i++)
        xval[(xval.length - 1) - i] = scenario.scale[0].bucket_to_pf(mp.bottom[0] + i);

    fval = new double[mp.length[0]];
    MapPeriodIterator<MapElement> mpitr = mp.iterator();
    while (mpitr.hasNext()) {
        int[] bucket = mpitr.nextIndex().clone();
        MapElement me = mpitr.next();
        int xindex = (fval.length - 1) - (bucket[0] - mp.bottom[0]);
        fval[xindex] = getWhat(me, what);
    }

    UnivariateInterpolator interpolator;
    if (config.interpolation1.equals("linear"))
        interpolator = new LinearInterpolator();
    else if (config.interpolation1.equals("spline"))
        interpolator = new SplineInterpolator();
    else {
        assert (false);
        return;
    }

    this.f = interpolator.interpolate(xval, fval);
}

From source file:com.github.lindenb.jvarkit.tools.redon.CopyNumber01.java

private void normalizeCoverage() {
    final Median medianOp = new Median();
    final Mean meanOp = new Mean();

    if (medianOp.evaluate(new double[] { 20, 1000, 19 }) != 20) {
        throw new RuntimeException("boum");
    }/*from   w w  w. ja  v a2 s .c om*/

    int autosome_count = 0;
    Collections.sort(this.interval2row, CopyNumber01.sortOnXY);

    for (int j = 0; j < this.interval2row.size(); ++j) {
        GCAndDepth r = this.interval2row.get(j);
        if (isSexualChrom(r.getChrom()))
            continue;
        autosome_count++;
    }

    double x[] = new double[autosome_count];
    double y[] = new double[autosome_count];

    int i = 0;
    for (int j = 0; j < this.interval2row.size(); ++j) {
        GCAndDepth r = this.interval2row.get(j);
        if (isSexualChrom(r.getChrom()))
            continue;
        x[i] = r.getX();
        y[i] = r.getY();
        ++i;
    }

    final double min_x = x[0];
    final double max_x = x[x.length - 1];

    /* merge adjacent x having same values */
    i = 0;
    int k = 0;
    while (i < x.length) {
        int j = i + 1;

        while (j < x.length && Double.compare(x[i], x[j]) == 0) {
            ++j;
        }
        x[k] = x[i];
        y[k] = meanOp.evaluate(y, i, j - i);
        ++k;
        i = j;
    }

    /* reduce size of x et y */
    if (k != x.length) {
        info("Compacting X from " + x.length + " to " + k);
        x = Arrays.copyOf(x, k);
        y = Arrays.copyOf(y, k);
    }

    //min depth cal
    double min_depth = Double.MAX_VALUE;

    UnivariateInterpolator interpolator = createInterpolator();
    UnivariateFunction spline = interpolator.interpolate(x, y);
    int points_removed = 0;
    i = 0;
    while (i < this.interval2row.size()) {
        GCAndDepth r = this.interval2row.get(i);
        if (r.getX() < min_x || r.getX() > max_x) {
            this.interval2row.remove(i);
            ++points_removed;
        } else {
            double norm = spline.value(r.getX());
            if (Double.isNaN(norm) || Double.isInfinite(norm)) {
                info("NAN " + r);
                this.interval2row.remove(i);
                ++points_removed;
                continue;
            }
            r.depth -= norm;
            min_depth = Math.min(min_depth, r.depth);
            ++i;
        }
    }
    info("Removed " + points_removed + " because GC% is too small (Sexual chrom)");
    spline = null;

    //fit to min, fill new y for median calculation
    info("min:" + min_depth);

    y = new double[this.interval2row.size()];
    for (i = 0; i < this.interval2row.size(); ++i) {
        GCAndDepth gc = this.interval2row.get(i);
        gc.depth -= min_depth;
        y[i] = gc.depth;
    }

    //normalize on median
    double median_depth = medianOp.evaluate(y, 0, y.length);
    info("median:" + median_depth);
    for (i = 0; i < this.interval2row.size(); ++i) {
        GCAndDepth gc = this.interval2row.get(i);
        gc.depth /= median_depth;
    }

    //restore genomic order
    Collections.sort(this.interval2row, CopyNumber01.sortOnPosition);

    /**  smoothing values with neighbours */
    final int SMOOTH_WINDOW = 5;
    y = new double[this.interval2row.size()];
    for (i = 0; i < this.interval2row.size(); ++i) {
        y[i] = this.interval2row.get(i).getY();
    }
    for (i = 0; i < this.interval2row.size(); ++i) {
        GCAndDepth gc = this.interval2row.get(i);
        int left = i;
        int right = i;
        while (left > 0 && i - left < SMOOTH_WINDOW && this.interval2row.get(left - 1).tid == gc.tid) {
            left--;
        }
        while (right + 1 < this.interval2row.size() && right - i < SMOOTH_WINDOW
                && this.interval2row.get(right + 1).tid == gc.tid) {
            right++;
        }
        gc.depth = medianOp.evaluate(y, left, (right - left) + 1);
    }

}

From source file:eu.crisis_economics.abm.model.parameters.FromFileTimeseriesParameter.java

/**
  * Create a {@link FromFileTimeseriesParameter} object using the specified
  * file.<br><br>//w ww. j a va 2  s .  co m
  * 
  * See also {@link FromFileTimeseriesParameter} and {@link Parameter}.
  * 
  * @param filename
  *        The name of the file from which to read timeseries data.
  * @param parameterName
  *        The name of the resulting {@link Parameter}. It is acceptable
  *        for this argument to be the empty string.
  * @param interpolator
  *        An instance of a {@link UnivariateInterpolator}. This interpolator
  *        is used to convert timeseries keypoints into a queryable function
  *        {@code f(T)} for all {@code T} in the domain of the interpolation
  *        keys. Possible examples, among others, include the {@link SplineInterpolator}
  *        and the {@link LinearInterpolator}.
  * 
  * @throws IOException
  *         This method raises {@link IOException} if, for any reason, the stated
  *         file cannot be processed. Reasons for such failure include: (a) the
  *         file does not exist; (b) the file is inaccessible to the read stream;
  *         (c) the file does not contain any data or contains fewer than two 
  *         records; (d) the file exists and can be accessed but does not have
  *         the required format. See {@link FromFileTimeseriesParameter}.
  */
@Inject
public FromFileTimeseriesParameter(@Named("FROM_FILE_TIMESERIES_PARAMETER_FILENAME") final String filename,
        @Named("FROM_FILE_TIMESERIES_PARAMETER_NAME") final String parameterName,
        @Named("FROM_FILE_TIMESERIES_PARAMETER_INTERPOLATOR") final UnivariateInterpolator interpolator)
        throws IOException {
    super(parameterName);
    Preconditions.checkNotNull(filename);
    final BufferedReader reader = new BufferedReader(new FileReader(filename));
    String line = null;
    final List<Double> x = new ArrayList<Double>(), y = new ArrayList<Double>();
    int numInterpolationPoints = 0;
    try {
        while ((line = reader.readLine()) != null) {
            if (line.isEmpty())
                continue;
            final String[] entries = line.split("[\\s:;,\t]+");
            if (entries.length != 2)
                throw new IOException(getClass().getSimpleName() + ": serialized timeseries are expected to "
                        + "consist of exactly two data columns. The input data: " + entries + " does "
                        + "not conform to this template. The data in file " + filename + " could not "
                        + "be parsed.");
            x.add(Double.parseDouble(entries[0]));
            y.add(Double.parseDouble(entries[1]));
            ++numInterpolationPoints;
        }
    } catch (final NumberFormatException e) {
        throw new IOException(e.getMessage());
    } finally {
        reader.close();
    }

    if (numInterpolationPoints <= 1)
        throw new IllegalArgumentException(getClass().getSimpleName() + ": file " + filename
                + " exists and has valid format,"
                + " but contains fewer than 2 records. At least two interpolation points are required.");
    final UnivariateFunction function = interpolator.interpolate(ArrayUtil.toPrimitive(x),
            ArrayUtil.toPrimitive(y));
    this.interpolation = function;
    this.bounds = new SimpleDomainBounds(x.get(0), x.get(x.size() - 1));
    this.outOfRangeEvaluation = new SimpleDomainBounds(y.get(0), y.get(y.size() - 1));
}