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

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

Introduction

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

Prototype

public PolynomialSplineFunction interpolate(double x[], double y[])
        throws DimensionMismatchException, NumberIsTooSmallException, NonMonotonicSequenceException 

Source Link

Document

Computes a linear interpolating function for the data set.

Usage

From source file:com.itemanalysis.psychometrics.scaling.PercentileRank.java

/**
 * Creates a TreeMap<Integer, Double> lookup table of percentile ranks.
 * The key is a score level and the rho is a percentile rank. This
 * method is useful when finding percentile ranks that correspond to an examinee's
 * raw score. After calling this method, individual elements in the
 * TreeMap can be accessed with getPercentileRankAt(int rho) or
 * valueIterator().//from  w  w w.j  ava  2  s .  com
 * 
 */
public void createLookupTable() {
    prankTable = new TreeMap<Integer, Double>();
    Iterator<Comparable<?>> iter = freqTable.valuesIterator();

    int index = 0;
    int length = freqTable.getUniqueCount();
    double[] xval = new double[length + 2];
    double[] yval = new double[length + 2];

    int x = 0;
    int xstar = 0;

    //create boundaries below the minimum possible test score
    //and above teh maximum possible test score.
    //This change allows for the interpolation of percentile
    //ranks at the min and max possible test score.
    xval[0] = min - .5;
    yval[0] = 0;
    xval[length + 1] = (double) max + 0.5;
    yval[length + 1] = 100;

    index = 1;

    //compute percentile ranks fro observed scores
    while (iter.hasNext()) {
        x = ((Long) iter.next()).intValue();
        xstar = Double.valueOf(Math.floor(x + 0.5)).intValue();

        xval[index] = Double.valueOf(xstar);
        yval[index] = Double.valueOf(percentileRank(x, xstar));
        index++;
    }

    //interpolate values
    LinearInterpolator interpolator = new LinearInterpolator();
    PolynomialSplineFunction splineFunction = interpolator.interpolate(xval, yval);

    //create lookup table with interpolated values
    x = min;
    double y = 0.0;
    while (x <= max) {
        y = splineFunction.value(x);
        prankTable.put(x, y);
        x += 1;
    }

}

From source file:malware_classification.Malware_Classification.java

private ArrayList<double[]> interpolate_data(ArrayList<double[]> data_orig, ArrayList<double[]> timestamp_orig,
        int bin_size, int num_bins) {
    ArrayList<double[]> interp_data = new ArrayList<>();
    int num_points_orig = data_orig.size();
    // TODO: change some of the num_points_orig to num_bins
    double[] x = new double[num_points_orig];
    double[] y = new double[num_points_orig];
    int num_cols = data_orig.get(0).length;
    for (int i = 0; i < num_bins; i++) {
        interp_data.add(new double[num_cols]);
    }//from  www . j  a  v a  2 s.c  o  m

    for (int col = 0; col < num_cols; col++) {
        // To use LinearInterpolator, first need arrays
        for (int j = 0; j < num_points_orig; j++) {
            x[j] = timestamp_orig.get(j)[col];
            y[j] = data_orig.get(j)[col];
        }
        LinearInterpolator lin_interp = new LinearInterpolator();
        PolynomialSplineFunction interp_func = lin_interp.interpolate(x, y);
        for (int j = 0; j < num_bins; j++) {
            double curr_bin = bin_size * j;
            double[] knots = interp_func.getKnots();

            //                logger.info()
            if (interp_func.isValidPoint(curr_bin)) {
                interp_data.get(j)[col] = interp_func.value(curr_bin);
            } else if (knots[0] > curr_bin) //bin is too small
            {
                interp_data.get(j)[col] = y[0];
            } else if (knots[knots.length - 1] < curr_bin) // bin is larger than data
            {
                interp_data.get(j)[col] = y[y.length - 1];
            } else {
                logger.warning("Cannot interpolate at bin starting at " + curr_bin);
            }
        }
    }

    return interp_data;

}

From source file:be.ugent.maf.cellmissy.analysis.singlecell.processing.impl.interpolation.TrackLinearInterpolator.java

@Override
public InterpolatedTrack interpolateTrack(double[] time, double[] x, double[] y) {
    // create a new linear interpolator
    LinearInterpolator linearInterpolator = new LinearInterpolator();
    int interpolationPoints = PropertiesConfigurationHolder.getInstance().getInt("numberOfInterpolationPoints");

    // create arrays to hold the interpolant time, the interpolated X and the interpolated Y
    double[] interpolantTime = new double[interpolationPoints];
    double[] interpolatedX = new double[interpolationPoints];
    double[] interpolatedY = new double[interpolationPoints];
    // the step used for the interpolation in both direction
    double interpolationStep = (time[time.length - 1] - time[0]) / interpolationPoints;

    // check for monotonicity
    boolean monotonic = MathArrays.isMonotonic(time, MathArrays.OrderDirection.INCREASING, false);
    // in case time is not monotonic, sort in place time, x and y coordinates
    if (!monotonic) {
        MathArrays.sortInPlace(time, x, y);
    }//from w w  w .ja v  a2 s . co m

    // call the interpolator, and actually do the interpolation
    try {
        PolynomialSplineFunction functionX = linearInterpolator.interpolate(time, x);
        PolynomialSplineFunction functionY = linearInterpolator.interpolate(time, y);

        // get the polynomial functions in both directions
        PolynomialFunction polynomialFunctionX = functionX.getPolynomials()[0];
        PolynomialFunction polynomialFunctionY = functionY.getPolynomials()[0];

        for (int i = 0; i < interpolationPoints; i++) {
            interpolantTime[i] = time[0] + (i * interpolationStep);
            interpolatedX[i] = functionX.value(interpolantTime[i]);
            interpolatedY[i] = functionY.value(interpolantTime[i]);
        }
        for (int k = 0; k < interpolationPoints; k++) {
            if (Double.isNaN(interpolatedX[k]) | Double.isNaN(interpolatedY[k])) {
                return null;
            }
        }

        return new InterpolatedTrack(interpolantTime, interpolatedX, interpolatedY, polynomialFunctionX,
                polynomialFunctionY);
    } catch (NumberIsTooSmallException e) {
        LOG.error(e.getMessage());
        return null;
    }
}

From source file:org.apache.solr.client.solrj.io.eval.LerpEvaluator.java

@Override
public Object doWork(Object... objects) throws IOException {

    Object first = objects[0];/*w  ww.java2 s . co  m*/

    double[] x = null;
    double[] y = null;

    if (objects.length == 1) {
        //Only the y values passed
        y = ((List) first).stream().mapToDouble(value -> ((Number) value).doubleValue()).toArray();
        x = new double[y.length];
        for (int i = 0; i < y.length; i++) {
            x[i] = i;
        }
    } else if (objects.length == 2) {
        Object second = objects[1];
        x = ((List) first).stream().mapToDouble(value -> ((Number) value).doubleValue()).toArray();
        y = ((List) second).stream().mapToDouble(value -> ((Number) value).doubleValue()).toArray();
    }

    LinearInterpolator interpolator = new LinearInterpolator();
    PolynomialSplineFunction spline = interpolator.interpolate(x, y);

    List<Number> list = new ArrayList();
    for (double xvalue : x) {
        list.add(spline.value(xvalue));
    }

    VectorFunction vec = new VectorFunction(spline, list);
    vec.addToContext("x", x);
    vec.addToContext("y", y);

    return vec;
}

From source file:org.meteoinfo.math.interpolate.InterpUtil.java

/**
 * Make linear interpolation function - PolynomialSplineFunction
 * @param x X data// w  w w . j a  va2s  . c  o  m
 * @param y Y data
 * @return Linear interpolation function
 */
public static PolynomialSplineFunction linearInterpFunc(Array x, Array y) {
    double[] xd = (double[]) ArrayUtil.copyToNDJavaArray(x);
    double[] yd = (double[]) ArrayUtil.copyToNDJavaArray(y);
    LinearInterpolator li = new LinearInterpolator();
    PolynomialSplineFunction psf = li.interpolate(xd, yd);

    return psf;
}

From source file:org.micromanager.plugins.magellan.acq.AcqDurationEstimator.java

private double interpolateOrExtrapolate(double[] x, double[] y, double xVal) {
    if (x.length == 1) {
        return y[0];
    }/*w w w  . j a  v a2  s . c o  m*/
    LinearInterpolator interpolator = new LinearInterpolator();
    PolynomialSplineFunction interpolant = interpolator.interpolate(x, y);
    if (xVal < interpolant.getKnots()[0]) {
        return interpolant.getKnots()[0];
    } else if (xVal > interpolant.getKnots()[interpolant.getN() - 1]) {
        return interpolant.getKnots()[interpolant.getN() - 1];
    } else {
        return interpolant.value(xVal);
    }
}

From source file:org.roi.itlab.cassandra.random_attributes.AgeRandomGenerator.java

@Override
public void buildGenerator() {
    double[] x = { 18.0, 25.0, 30.0, 60.0, 90.0 };
    double[] y = { 1.0, 2.0, 3.0, 1.0, 0.1 };
    LinearInterpolator li = new LinearInterpolator();
    randomGenerator = new RandomGenerator();
    randomGenerator.setMin(LICENSE_AGE);
    randomGenerator.setMax(MAX_AGE);//w ww  .ja v  a  2 s.c  o m
    randomGenerator.setProportionalWeight(4);
    randomGenerator.setPsf(li.interpolate(x, y));

}

From source file:org.roi.itlab.cassandra.random_attributes.ExperienceRandomGenerator.java

@Override
public void buildGenerator() {

    int max_exp = age - LICENSE_AGE;

    double[] x = { 0.0, 5.0, 30.0, 60.0 };
    double[] y = { 1.0, 2.0, 4.0, 2.0 };
    LinearInterpolator li = new LinearInterpolator();
    randomGenerator = new RandomGenerator();
    randomGenerator.setMin(MIN_EXP);/*www  .  j  a v a 2  s.com*/
    randomGenerator.setMax(max_exp);
    randomGenerator.setProportionalWeight(4);
    randomGenerator.setPsf(li.interpolate(x, y));
}

From source file:Richards1DSolver.Richards1DSolver.java

private double[] linearInterp(double[] x, double[] y, double[] xi) {
    LinearInterpolator li = new LinearInterpolator(); // or other interpolator
    PolynomialSplineFunction psf = li.interpolate(x, y);

    double[] yi = new double[xi.length];
    for (int i = 0; i < xi.length; i++) {
        yi[i] = psf.value(xi[i]);//from   w w  w.ja  va 2 s  .  co  m
    }
    return yi;
}

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

/**
 * Similar implementation of R's stats.approxfun(..., rule = 2) where values outside the interval ['min(x)',
 * 'max(x)'] gets the value at the closest data extreme. Also performs sorting based on xTrain.
 * // w  w  w .j  av a2  s.  c  o  m
 * @param x the training set of x values
 * @param y the training set of y values
 * @param xInterpolate the set of x values to interpolate
 * @return yInterpolate the interpolated set of y values
 */
protected static double[] approx(double[] x, double[] y, double[] xInterpolate) {

    assert x != null;
    assert y != null;
    assert xInterpolate != null;
    assert x.length == y.length;

    double[] yInterpolate = new double[xInterpolate.length];
    LinearInterpolator linearInterpolator = new LinearInterpolator();

    // make sure that x is strictly increasing
    DoubleMatrix2D matrix = new DenseDoubleMatrix2D(x.length, 2);
    matrix.viewColumn(0).assign(x);
    matrix.viewColumn(1).assign(y);
    matrix = matrix.viewSorted(0);
    double[] sortedX = matrix.viewColumn(0).toArray();
    double[] sortedY = matrix.viewColumn(1).toArray();

    // make sure x is within the domain
    DoubleArrayList xList = new DoubleArrayList(sortedX);
    double x3ListMin = Descriptive.min(xList);
    double x3ListMax = Descriptive.max(xList);
    PolynomialSplineFunction fun = linearInterpolator.interpolate(sortedX, sortedY);
    for (int i = 0; i < xInterpolate.length; i++) {
        try {
            // approx(...,rule=2)
            if (xInterpolate[i] > x3ListMax) {
                yInterpolate[i] = fun.value(x3ListMax);
            } else if (xInterpolate[i] < x3ListMin) {
                yInterpolate[i] = fun.value(x3ListMin);
            } else {
                yInterpolate[i] = fun.value(xInterpolate[i]);
            }
        } catch (OutOfRangeException e) {
            // this shouldn't happen anymore
            yInterpolate[i] = Double.NaN;
        }
    }

    return yInterpolate;
}