Search in sources :

Example 1 with UnivariateInterpolator

use of org.apache.commons.math3.analysis.interpolation.UnivariateInterpolator in project dhis2-core by dhis2.

the class DefaultChartService method getJFreeChartHistory.

@Override
public JFreeChart getJFreeChartHistory(DataElement dataElement, DataElementCategoryOptionCombo categoryOptionCombo, DataElementCategoryOptionCombo attributeOptionCombo, Period lastPeriod, OrganisationUnit organisationUnit, int historyLength, I18nFormat format) {
    lastPeriod = periodService.reloadPeriod(lastPeriod);
    List<Period> periods = periodService.getPeriods(lastPeriod, historyLength);
    MinMaxDataElement minMax = minMaxDataElementService.getMinMaxDataElement(organisationUnit, dataElement, categoryOptionCombo);
    UnivariateInterpolator interpolator = new SplineInterpolator();
    Integer periodCount = 0;
    List<Double> x = new ArrayList<>();
    List<Double> y = new ArrayList<>();
    // ---------------------------------------------------------------------
    // DataValue, MinValue and MaxValue DataSets
    // ---------------------------------------------------------------------
    DefaultCategoryDataset dataValueDataSet = new DefaultCategoryDataset();
    DefaultCategoryDataset metaDataSet = new DefaultCategoryDataset();
    for (Period period : periods) {
        ++periodCount;
        period.setName(format.formatPeriod(period));
        DataValue dataValue = dataValueService.getDataValue(dataElement, period, organisationUnit, categoryOptionCombo, attributeOptionCombo);
        double value = 0;
        if (dataValue != null && dataValue.getValue() != null && MathUtils.isNumeric(dataValue.getValue())) {
            value = Double.parseDouble(dataValue.getValue());
            x.add(periodCount.doubleValue());
            y.add(value);
        }
        dataValueDataSet.addValue(value, dataElement.getShortName(), period.getName());
        if (minMax != null) {
            metaDataSet.addValue(minMax.getMin(), "Min value", period.getName());
            metaDataSet.addValue(minMax.getMax(), "Max value", period.getName());
        }
    }
    if (// minimum 3 points required for interpolation
    x.size() >= 3) {
        periodCount = 0;
        double[] xa = getArray(x);
        int min = MathUtils.getMin(xa).intValue();
        int max = MathUtils.getMax(xa).intValue();
        try {
            UnivariateFunction function = interpolator.interpolate(xa, getArray(y));
            for (Period period : periods) {
                if (++periodCount >= min && periodCount <= max) {
                    metaDataSet.addValue(function.value(periodCount), "Regression value", period.getName());
                }
            }
        } catch (MathRuntimeException ex) {
            throw new RuntimeException("Failed to interpolate", ex);
        }
    }
    // ---------------------------------------------------------------------
    // Plots
    // ---------------------------------------------------------------------
    CategoryPlot plot = getCategoryPlot(dataValueDataSet, getBarRenderer(), PlotOrientation.VERTICAL, CategoryLabelPositions.UP_45);
    plot.setDataset(1, metaDataSet);
    plot.setRenderer(1, getLineRenderer());
    JFreeChart jFreeChart = getBasicJFreeChart(plot);
    return jFreeChart;
}
Also used : MathRuntimeException(org.apache.commons.math3.exception.MathRuntimeException) UnivariateFunction(org.apache.commons.math3.analysis.UnivariateFunction) DataValue(org.hisp.dhis.datavalue.DataValue) Period(org.hisp.dhis.period.Period) JFreeChart(org.jfree.chart.JFreeChart) MathRuntimeException(org.apache.commons.math3.exception.MathRuntimeException) MinMaxDataElement(org.hisp.dhis.minmax.MinMaxDataElement) SplineInterpolator(org.apache.commons.math3.analysis.interpolation.SplineInterpolator) UnivariateInterpolator(org.apache.commons.math3.analysis.interpolation.UnivariateInterpolator) DefaultCategoryDataset(org.jfree.data.category.DefaultCategoryDataset)

Example 2 with UnivariateInterpolator

use of org.apache.commons.math3.analysis.interpolation.UnivariateInterpolator in project mafscaling by vimsh.

the class BilinearInterpolator method interpolate.

/**
 * Method returns an interpolated/extrapolated value, based on
 * @param x, array of x values
 * @param y, array of y values
 * @param xi, is x value you want to interpolate at
 * @param type, interpolation method type
 * @return interpolated value
 * @throws Exception
 */
public static double interpolate(double[] x, double[] y, double xi, InterpolatorType type) throws Exception {
    UnivariateInterpolator interpolator = null;
    switch(type) {
        case AkimaCubicSpline:
            interpolator = new AkimaSplineInterpolator();
            break;
        case Linear:
            interpolator = new LinearInterpolator();
            break;
        case Regression:
            interpolator = new LoessInterpolator();
            break;
        case CubicSpline:
            interpolator = new SplineInterpolator();
            break;
        default:
            throw new Exception("Invalid interpolator type for this function");
    }
    UnivariateFunction function = interpolator.interpolate(x, y);
    PolynomialFunction[] polynomials = ((PolynomialSplineFunction) function).getPolynomials();
    if (xi > x[x.length - 1])
        return polynomials[polynomials.length - 1].value(xi - x[x.length - 2]);
    if (xi < x[0])
        return polynomials[0].value(xi - x[0]);
    return function.value(xi);
}
Also used : LoessInterpolator(org.apache.commons.math3.analysis.interpolation.LoessInterpolator) UnivariateFunction(org.apache.commons.math3.analysis.UnivariateFunction) LinearInterpolator(org.apache.commons.math3.analysis.interpolation.LinearInterpolator) AkimaSplineInterpolator(org.apache.commons.math3.analysis.interpolation.AkimaSplineInterpolator) SplineInterpolator(org.apache.commons.math3.analysis.interpolation.SplineInterpolator) PiecewiseBicubicSplineInterpolator(org.apache.commons.math3.analysis.interpolation.PiecewiseBicubicSplineInterpolator) AkimaSplineInterpolator(org.apache.commons.math3.analysis.interpolation.AkimaSplineInterpolator) PolynomialFunction(org.apache.commons.math3.analysis.polynomials.PolynomialFunction) UnivariateInterpolator(org.apache.commons.math3.analysis.interpolation.UnivariateInterpolator) PolynomialSplineFunction(org.apache.commons.math3.analysis.polynomials.PolynomialSplineFunction) NumberIsTooSmallException(org.apache.commons.math3.exception.NumberIsTooSmallException) OutOfRangeException(org.apache.commons.math3.exception.OutOfRangeException) NonMonotonicSequenceException(org.apache.commons.math3.exception.NonMonotonicSequenceException) DimensionMismatchException(org.apache.commons.math3.exception.DimensionMismatchException) NoDataException(org.apache.commons.math3.exception.NoDataException)

Example 3 with UnivariateInterpolator

use of org.apache.commons.math3.analysis.interpolation.UnivariateInterpolator in project GDSC-SMLM by aherbert.

the class CameraModelAnalysis method downSampleCdfToPmf.

private static double downSampleCdfToPmf(CameraModelAnalysisSettings settings, TDoubleArrayList list, double step, double zero, double[] pg, double sum) {
    // Down-sample to 1.0 pixel step interval.
    // Build cumulative distribution.
    double lowerSum = 0;
    for (int i = 0; i < pg.length; i++) {
        lowerSum += pg[i];
        pg[i] = lowerSum;
    }
    SimpleArrayUtils.multiply(pg, sum / lowerSum);
    pg[pg.length - 1] = sum;
    final double offset = (settings.getRoundDown()) ? 0 : -0.5;
    // Note the interpolation of the CDF is good when the step is much smaller than 1.
    // When the step is above 1 then the gain is likely to be very low and thus
    // unrealistic for modelling. This case is ignored.
    // Subtract the CDF to the upper bounds from the CDF of the lower bound
    // to get the discrete PMF
    // // Pad the CDF to avoid index-out-of bounds during interpolation
    final int padSize = 0;
    // padSize = (int) Math.ceil(1 / step) + 2;
    // list.resetQuick();
    // list.add(new double[padSize]);
    // list.add(g);
    // for (int i = padSize; i-- > 0;)
    // list.add(1);
    // double[] pd = list.toArray();
    final double[] pd = pg;
    list.resetQuick();
    final double[] x = SimpleArrayUtils.newArray(pd.length, zero - padSize * step, step);
    // Q. If the EM-CCD the distribution may have a Dirac delta at c=0 which
    // could break interpolation using a spline?
    final UnivariateInterpolator in = // (settings.getMode() == MODE_EM_CCD) ? new LinearInterpolator() :
    new SplineInterpolator();
    final UnivariateFunction f = in.interpolate(x, pd);
    int bound = (int) Math.floor(zero);
    list.add(0);
    zero--;
    double upperSum = 0;
    final double min = x[0];
    final double max = x[x.length - 1];
    while (upperSum < sum) {
        bound++;
        // Find the point at which the CDF should be computed
        lowerSum = upperSum;
        final double point = bound + offset;
        if (point < min) {
            upperSum = 0;
        } else if (point > max) {
            upperSum = sum;
        } else {
            upperSum = f.value(point);
        }
        list.add(upperSum - lowerSum);
    }
    list.add(0);
    return zero;
}
Also used : UnivariateFunction(org.apache.commons.math3.analysis.UnivariateFunction) SplineInterpolator(org.apache.commons.math3.analysis.interpolation.SplineInterpolator) UnivariateInterpolator(org.apache.commons.math3.analysis.interpolation.UnivariateInterpolator)

Example 4 with UnivariateInterpolator

use of org.apache.commons.math3.analysis.interpolation.UnivariateInterpolator in project dhis2-core by dhis2.

the class DefaultChartService method getJFreeChartHistory.

@Override
@Transactional(readOnly = true)
public JFreeChart getJFreeChartHistory(DataElement dataElement, CategoryOptionCombo categoryOptionCombo, CategoryOptionCombo attributeOptionCombo, Period lastPeriod, OrganisationUnit organisationUnit, int historyLength, I18nFormat format) {
    lastPeriod = periodService.reloadPeriod(lastPeriod);
    List<Period> periods = periodService.getPeriods(lastPeriod, historyLength);
    MinMaxDataElement minMax = minMaxDataElementService.getMinMaxDataElement(organisationUnit, dataElement, categoryOptionCombo);
    UnivariateInterpolator interpolator = new SplineInterpolator();
    int periodCount = 0;
    List<Double> x = new ArrayList<>();
    List<Double> y = new ArrayList<>();
    // ---------------------------------------------------------------------
    // DataValue, MinValue and MaxValue DataSets
    // ---------------------------------------------------------------------
    DefaultCategoryDataset dataValueDataSet = new DefaultCategoryDataset();
    DefaultCategoryDataset metaDataSet = new DefaultCategoryDataset();
    for (Period period : periods) {
        ++periodCount;
        period.setName(format.formatPeriod(period));
        DataValue dataValue = dataValueService.getDataValue(dataElement, period, organisationUnit, categoryOptionCombo, attributeOptionCombo);
        double value = 0;
        if (dataValue != null && dataValue.getValue() != null && MathUtils.isNumeric(dataValue.getValue())) {
            value = Double.parseDouble(dataValue.getValue());
            x.add((double) periodCount);
            y.add(value);
        }
        dataValueDataSet.addValue(value, dataElement.getShortName(), period.getName());
        if (minMax != null) {
            metaDataSet.addValue(minMax.getMin(), "Min value", period.getName());
            metaDataSet.addValue(minMax.getMax(), "Max value", period.getName());
        }
    }
    if (// minimum 3 points required for interpolation
    x.size() >= 3) {
        periodCount = 0;
        double[] xa = getArray(x);
        int min = MathUtils.getMin(xa).intValue();
        int max = MathUtils.getMax(xa).intValue();
        try {
            UnivariateFunction function = interpolator.interpolate(xa, getArray(y));
            for (Period period : periods) {
                if (++periodCount >= min && periodCount <= max) {
                    metaDataSet.addValue(function.value(periodCount), "Regression value", period.getName());
                }
            }
        } catch (MathRuntimeException ex) {
            throw new RuntimeException("Failed to interpolate", ex);
        }
    }
    // ---------------------------------------------------------------------
    // Plots
    // ---------------------------------------------------------------------
    CategoryPlot plot = getCategoryPlot(dataValueDataSet, getBarRenderer(), PlotOrientation.VERTICAL, CategoryLabelPositions.UP_45);
    plot.setDataset(1, metaDataSet);
    plot.setRenderer(1, getLineRenderer());
    return getBasicJFreeChart(plot);
}
Also used : MathRuntimeException(org.apache.commons.math3.exception.MathRuntimeException) UnivariateFunction(org.apache.commons.math3.analysis.UnivariateFunction) DataValue(org.hisp.dhis.datavalue.DataValue) ArrayList(java.util.ArrayList) Period(org.hisp.dhis.period.Period) CategoryPlot(org.jfree.chart.plot.CategoryPlot) MathRuntimeException(org.apache.commons.math3.exception.MathRuntimeException) MinMaxDataElement(org.hisp.dhis.minmax.MinMaxDataElement) SplineInterpolator(org.apache.commons.math3.analysis.interpolation.SplineInterpolator) UnivariateInterpolator(org.apache.commons.math3.analysis.interpolation.UnivariateInterpolator) DefaultCategoryDataset(org.jfree.data.category.DefaultCategoryDataset) Transactional(org.springframework.transaction.annotation.Transactional)

Aggregations

UnivariateFunction (org.apache.commons.math3.analysis.UnivariateFunction)4 SplineInterpolator (org.apache.commons.math3.analysis.interpolation.SplineInterpolator)4 UnivariateInterpolator (org.apache.commons.math3.analysis.interpolation.UnivariateInterpolator)4 MathRuntimeException (org.apache.commons.math3.exception.MathRuntimeException)2 DataValue (org.hisp.dhis.datavalue.DataValue)2 MinMaxDataElement (org.hisp.dhis.minmax.MinMaxDataElement)2 Period (org.hisp.dhis.period.Period)2 DefaultCategoryDataset (org.jfree.data.category.DefaultCategoryDataset)2 ArrayList (java.util.ArrayList)1 AkimaSplineInterpolator (org.apache.commons.math3.analysis.interpolation.AkimaSplineInterpolator)1 LinearInterpolator (org.apache.commons.math3.analysis.interpolation.LinearInterpolator)1 LoessInterpolator (org.apache.commons.math3.analysis.interpolation.LoessInterpolator)1 PiecewiseBicubicSplineInterpolator (org.apache.commons.math3.analysis.interpolation.PiecewiseBicubicSplineInterpolator)1 PolynomialFunction (org.apache.commons.math3.analysis.polynomials.PolynomialFunction)1 PolynomialSplineFunction (org.apache.commons.math3.analysis.polynomials.PolynomialSplineFunction)1 DimensionMismatchException (org.apache.commons.math3.exception.DimensionMismatchException)1 NoDataException (org.apache.commons.math3.exception.NoDataException)1 NonMonotonicSequenceException (org.apache.commons.math3.exception.NonMonotonicSequenceException)1 NumberIsTooSmallException (org.apache.commons.math3.exception.NumberIsTooSmallException)1 OutOfRangeException (org.apache.commons.math3.exception.OutOfRangeException)1