Example usage for org.apache.commons.math3.analysis.polynomials PolynomialSplineFunction value

List of usage examples for org.apache.commons.math3.analysis.polynomials PolynomialSplineFunction value

Introduction

In this page you can find the example usage for org.apache.commons.math3.analysis.polynomials PolynomialSplineFunction value.

Prototype

public DerivativeStructure value(final DerivativeStructure t) 

Source Link

Usage

From source file:imperial.modaclouds.monitoring.sda.weka.CreateArff.java

/**
 * Create arff file given the data/*from  w  w  w .ja  v  a 2s. c o  m*/
 * 
 * @param timestamps_str   the timestamps data
 * @param data   the values of the metrics
 * @param metricName   the metric name
 * @param fileName   the file name to keep the arff file
 */
public static void create(ArrayList<ArrayList<String>> timestamps_str, ArrayList<ArrayList<String>> data,
        ArrayList<String> metricName, String fileName) {

    System.out.println("data: " + data.get(0));

    long min_timestamp = Long.valueOf(Collections.min(timestamps_str.get(0)));
    long max_timestamp = Long.valueOf(Collections.max(timestamps_str.get(0)));

    for (int i = 1; i < timestamps_str.size(); i++) {
        long min_temp = Long.valueOf(Collections.min(timestamps_str.get(i)));
        long max_temp = Long.valueOf(Collections.max(timestamps_str.get(i)));

        if (max_temp < max_timestamp) {
            max_timestamp = max_temp;
        }

        if (min_temp > min_timestamp) {
            min_timestamp = min_temp;
        }
    }

    for (int i = 0; i < timestamps_str.size(); i++) {
        Iterator<String> iter_time = timestamps_str.get(i).iterator();
        Iterator<String> iter_data = data.get(i).iterator();

        while (iter_time.hasNext()) {
            long temp_timestamps = Long.valueOf(iter_time.next());
            if (temp_timestamps < min_timestamp || temp_timestamps > max_timestamp) {
                iter_time.remove();

                iter_data.next();
                iter_data.remove();
            }
        }
    }

    double[] timestamps = convertDoubles(timestamps_str.get(0));
    double[] targetData = convertDoubles(data.get(0));

    double[][] otherData = new double[data.size() - 1][timestamps.length];
    for (int i = 0; i < data.size() - 1; i++) {
        double[] timestamps_temp = convertDoubles(timestamps_str.get(i));
        double[] targetData_temp = convertDoubles(data.get(i));

        SplineInterpolator spline = new SplineInterpolator();

        Map<Double, Integer> map = new TreeMap<Double, Integer>();
        for (int j = 0; j < timestamps_temp.length; j++) {
            map.put(timestamps_temp[j], j);
        }
        Collection<Integer> indices = map.values();

        int[] indices_int = ArrayUtils.toPrimitive(indices.toArray(new Integer[indices.size()]));
        double[] timestamps_temp_new = new double[indices_int.length];
        double[] targetData_temp_new = new double[indices_int.length];

        for (int j = 0; j < indices_int.length; j++) {
            timestamps_temp_new[j] = timestamps_temp[indices_int[j]];
            targetData_temp_new[j] = targetData_temp[indices_int[j]];
        }

        PolynomialSplineFunction polynomical = spline.interpolate(timestamps_temp_new, targetData_temp_new);

        for (int j = 0; j < timestamps.length; j++) {
            try {
                otherData[i][j] = polynomical.value(timestamps[j]);
            } catch (Exception ex) {
                otherData[i][j] = targetData_temp_new[j];
            }
        }
    }

    ArrayList<Attribute> attributes;
    Instances dataSet;

    attributes = new ArrayList<Attribute>();

    for (String metric : metricName) {
        attributes.add(new Attribute(metric));
    }

    dataSet = new Instances("data", attributes, 0);

    for (int i = 0; i < timestamps.length; i++) {
        double[] instanceValue1 = new double[dataSet.numAttributes()];
        instanceValue1[0] = timestamps[i];
        instanceValue1[1] = targetData[i];

        for (int j = 0; j < data.size() - 1; j++) {
            instanceValue1[2 + j] = otherData[j][i];
        }

        DenseInstance denseInstance1 = new DenseInstance(1.0, instanceValue1);

        dataSet.add(denseInstance1);
    }

    ArffSaver saver = new ArffSaver();
    saver.setInstances(dataSet);
    try {
        String workingDir = System.getProperty("user.dir");
        System.out.println("workingDir: " + workingDir);
        saver.setFile(new File(workingDir + "/" + fileName));
        saver.writeBatch();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:de.mprengemann.intellij.plugin.androidicons.util.ImageUtils.java

private static BufferedImage rescaleBorder(BufferedImage image, int targetWidth, int targetHeight)
        throws IOException {
    if (targetWidth == 0) {
        targetWidth = 1;/*from  w  w w . ja v  a2 s.  c om*/
    }
    if (targetHeight == 0) {
        targetHeight = 1;
    }

    if (targetHeight > 1 && targetWidth > 1) {
        throw new IOException();
    }

    int w = image.getWidth();
    int h = image.getHeight();
    int[] data = image.getRGB(0, 0, w, h, null, 0, w);
    int[] newData = new int[targetWidth * targetHeight];

    for (int x = 0; x < w; x++) {
        for (int y = 0; y < h; y++) {
            newData[y * targetWidth + x] = 0x00;
        }
    }

    List<Integer> startPositions = new ArrayList<Integer>();
    List<Integer> endPositions = new ArrayList<Integer>();

    boolean inBlock = false;
    if (targetHeight == 1) {
        for (int x = 0; x < w; x++) {
            if ((0xff000000 & data[x]) != 0) {
                if (!inBlock) {
                    inBlock = true;
                    startPositions.add(x);
                }
            } else if (inBlock) {
                endPositions.add(x - 1);
                inBlock = false;
            }
        }
        if (inBlock) {
            endPositions.add(w - 1);
        }
    } else {
        for (int y = 0; y < h; y++) {
            if ((0xff000000 & data[y]) != 0) {
                if (!inBlock) {
                    inBlock = true;
                    startPositions.add(y);
                }
            } else if (inBlock) {
                endPositions.add(y - 1);
                inBlock = false;
            }
        }
        if (inBlock) {
            endPositions.add(h - 1);
        }
    }
    try {
        SplineInterpolator interpolator = new SplineInterpolator();
        PolynomialSplineFunction function = interpolator.interpolate(
                new double[] { 0f, 1f, Math.max(w - 1, h - 1) },
                new double[] { 0f, 1f, Math.max(targetHeight - 1, targetWidth - 1) });
        for (int i = 0; i < startPositions.size(); i++) {
            int start = startPositions.get(i);
            int end = endPositions.get(i);
            for (int j = (int) function.value(start); j <= (int) function.value(end); j++) {
                newData[j] = 0xff000000;
            }
        }

        BufferedImage img = UIUtil.createImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_ARGB);
        img.setRGB(0, 0, targetWidth, targetHeight, newData, 0, targetWidth);
        return img;
    } catch (Exception e) {
        Logger.getInstance(ImageUtils.class).error("resizeBorder", e);
    }

    return null;
}

From source file:de.mprengemann.intellij.plugin.androidicons.images.ImageUtils.java

private static BufferedImage rescaleBorder(BufferedImage image, int targetWidth, int targetHeight) {
    if (targetWidth == 0) {
        targetWidth = 1;/*from  w  w w . j  a v  a2 s  .com*/
    }
    if (targetHeight == 0) {
        targetHeight = 1;
    }

    if (targetHeight > 1 && targetWidth > 1) {
        throw new Wrong9PatchException();
    }

    int w = image.getWidth();
    int h = image.getHeight();
    int[] data = image.getRGB(0, 0, w, h, null, 0, w);
    int[] newData = new int[targetWidth * targetHeight];

    for (int x = 0; x < w; x++) {
        for (int y = 0; y < h; y++) {
            newData[y * targetWidth + x] = 0x00;
        }
    }

    List<Integer> startPositions = new ArrayList<Integer>();
    List<Integer> endPositions = new ArrayList<Integer>();

    boolean inBlock = false;
    if (targetHeight == 1) {
        for (int x = 0; x < w; x++) {
            if ((0xff000000 & data[x]) != 0) {
                if (!inBlock) {
                    inBlock = true;
                    startPositions.add(x);
                }
            } else if (inBlock) {
                endPositions.add(x - 1);
                inBlock = false;
            }
        }
        if (inBlock) {
            endPositions.add(w - 1);
        }
    } else {
        for (int y = 0; y < h; y++) {
            if ((0xff000000 & data[y]) != 0) {
                if (!inBlock) {
                    inBlock = true;
                    startPositions.add(y);
                }
            } else if (inBlock) {
                endPositions.add(y - 1);
                inBlock = false;
            }
        }
        if (inBlock) {
            endPositions.add(h - 1);
        }
    }
    try {
        SplineInterpolator interpolator = new SplineInterpolator();
        PolynomialSplineFunction function = interpolator.interpolate(
                new double[] { 0f, 1f, Math.max(w - 1, h - 1) },
                new double[] { 0f, 1f, Math.max(targetHeight - 1, targetWidth - 1) });
        for (int i = 0; i < startPositions.size(); i++) {
            int start = startPositions.get(i);
            int end = endPositions.get(i);
            for (int j = (int) function.value(start); j <= (int) function.value(end); j++) {
                newData[j] = 0xff000000;
            }
        }

        BufferedImage img = UIUtil.createImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_ARGB);
        img.setRGB(0, 0, targetWidth, targetHeight, newData, 0, targetWidth);
        return img;
    } catch (Exception e) {
        Logger.getInstance(ImageUtils.class).error("resizeBorder", e);
    }

    return null;
}

From source file:eu.tango.energymodeller.energypredictor.CpuOnlySplinePolynomialEnergyPredictor.java

/**
 * This estimates the power used by a host, given its CPU load.
 *
 * @param host The host to get the energy prediction for
 * @param usageCPU The amount of CPU load placed on the host
 * @return The predicted power usage./*from w ww . j a  v  a 2 s. co  m*/
 */
@Override
public double predictPowerUsed(Host host, double usageCPU) {
    PolynomialSplineFunction model = retrieveModel(host).getFunction();
    return model.value(getCpuUsageValue(model, usageCPU));
}

From source file:eu.tango.energymodeller.energypredictor.CpuOnlySplinePolynomialEnergyPredictor.java

/**
 * This predicts the total amount of energy used by a host.
 *
 * @param host The host to get the energy prediction for
 * @param usageCPU The amount of CPU load placed on the host
 * @param timePeriod The time period the prediction is for
 * @return The predicted energy usage./*from   www  . j a  va 2  s.  co  m*/
 */
public EnergyUsagePrediction predictTotalEnergy(Host host, double usageCPU, TimePeriod timePeriod) {
    EnergyUsagePrediction answer = new EnergyUsagePrediction(host);
    PolynomialSplineFunction model = retrieveModel(host).getFunction();
    double powerUsed = model.value(getCpuUsageValue(model, getCpuUsageValue(model, usageCPU)));
    answer.setAvgPowerUsed(powerUsed);
    answer.setTotalEnergyUsed(powerUsed * ((double) TimeUnit.SECONDS.toHours(timePeriod.getDuration())));
    answer.setDuration(timePeriod);
    return answer;
}

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()./*w  ww  .jav a 2 s  .c o  m*/
 * 
 */
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:eu.tango.energymodeller.energypredictor.CpuOnlySplinePolynomialEnergyPredictor.java

/**
 * This performs a calculation to determine how close the fit is for a given
 * model./*from   w  ww .ja v  a2  s.c o  m*/
 *
 * @param function The PolynomialFunction to assess
 * @param observed The actual set of observed points
 * @return The sum of the square error.
 */
private double getSumOfSquareError(PolynomialSplineFunction function, double[] xObserved, double[] yObserved) {
    double answer = 0;
    for (int i = 0; i < xObserved.length; i++) {
        double error = yObserved[i] - function.value(xObserved[i]);
        answer = answer + (error * error);
    }
    return answer;
}

From source file:jp.ac.tohoku.ecei.sb.metabolomeqc.basiccorrector.LoessIntensityCorrectorTest.java

@Test
public void createSampleLoessFlat() throws Exception {
    DataManager dataManager = new DataManager();
    CSVDataLoader.loadFromCSVData(new File(getClass().getResource("flat-measure-nodrift").getFile()),
            dataManager);// w w  w  .j  a v  a 2  s  .  co  m

    File buildDir = new File(System.getProperty("user.dir"), "build");
    File testOutput = new File(buildDir, "test-data");
    testOutput.mkdirs();

    IntensityMatrixImpl intensityMatrix = new IntensityMatrixImpl(dataManager.getIntensityMatrix());
    List<Sample> globalQC = intensityMatrix.getGlobalQCSamples();
    if (globalQC.size() == 0)
        throw new UnsupportedOperationException("No Global QC");
    Sample selectedGlobalQC = globalQC.get(0);

    LoessInterpolator loessInterpolator = new LoessInterpolator();

    for (HashMap.Entry<Plate, List<Injection>> oneplate : intensityMatrix.getInjectionsByPlate().entrySet()) {
        for (Compound compound : intensityMatrix.getRowKeys()) {
            List<Double> xlist = new ArrayList<>();
            List<Double> ylist = new ArrayList<>();
            for (Injection injection : oneplate.getValue()) {
                if (injection.isIgnored())
                    continue;
                if (!injection.getSample().equals(selectedGlobalQC))
                    continue;
                xlist.add((double) injection.getRunIndex());
                ylist.add(intensityMatrix.get(compound, injection));
            }

            PolynomialSplineFunction fn = loessInterpolator.interpolate(
                    xlist.stream().mapToDouble(x -> x).toArray(), ylist.stream().mapToDouble(x -> x).toArray());
            for (Injection injection : oneplate.getValue()) {
                if (injection.getSample().getSampleType() != Sample.SampleType.NORMAL)
                    continue;
                intensityMatrix.put(compound, injection, fn.value(injection.getRunIndex()));
            }
        }
    }

    dataManager.setIntensityMatrix(intensityMatrix);
    CSVDataLoader.storeToCSVData(new File(testOutput, "loess-flat"), dataManager);
}

From source file:jp.ac.tohoku.ecei.sb.metabolomeqc.basiccorrector.LoessIntensityCorrector.java

@Override
public IntensityMatrix doCorrection(IntensityMatrix original) {
    updateBadInjections(original);/*from   w w  w  . ja v  a2s.  co m*/
    List<Injection> normalSamples = original.getNormalInjections();

    List<Sample> globalQCSamples = original.getGlobalQCSamples();
    if (globalQCSamples.size() == 0)
        throw new UnsupportedOperationException("No global QC");
    Sample selectedGlobalQC = globalQCSamples.get(0);

    // Calculate SQC median
    Map<Compound, Double> compoundIntensityBase = GlobalQCMedianCalculator.calcGlobalQCMedian(original,
            badInjections);

    // Main Correction
    IntensityMatrix corrected = new IntensityMatrixImpl(original.getSize()[0], normalSamples.size());
    corrected.setRowKeys(original.getRowKeys());
    corrected.setColumnKeys(normalSamples);
    //corrected.getAttributes().putAll(original.getAttributes());

    LoessInterpolator loessInterpolator = new LoessInterpolator(bandwidth, robustnessIters, accuracy);

    for (Compound oneCompound : corrected.getRowKeys()) {
        double base = compoundIntensityBase.get(oneCompound);
        for (Map.Entry<Plate, List<Injection>> plateInjection : original.getInjectionsByPlate().entrySet()) {
            List<Double> xlist = new ArrayList<>();
            List<Double> ylist = new ArrayList<>();
            for (Injection injection : plateInjection.getValue()) {
                //log.info("injection: {}", injection);
                if (!injection.getSample().equals(selectedGlobalQC))
                    continue;
                if (injection.isIgnored())
                    continue;
                if (badInjections != null && badInjections.contains(injection))
                    continue;

                xlist.add((double) injection.getRunIndex());
                ylist.add(original.get(oneCompound, injection));
            }

            //log.info("X : {}", xlist.size());

            PolynomialSplineFunction fn = loessInterpolator.interpolate(
                    xlist.stream().mapToDouble(x -> x).toArray(), ylist.stream().mapToDouble(x -> x).toArray());

            for (Injection injection : plateInjection.getValue()) {
                if (!normalSamples.contains(injection))
                    continue;
                corrected.put(oneCompound, injection,
                        original.get(oneCompound, injection) - base + fn.value(injection.getRunIndex()));
            }
        }
    }

    return corrected;
}

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  ww. j a va2 s .  c  o 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;
    }
}