Search in sources :

Example 16 with Percentile

use of org.apache.commons.math3.stat.descriptive.rank.Percentile in project nd4j by deeplearning4j.

the class Nd4jTestsC method testPercentile3.

@Test
public void testPercentile3() throws Exception {
    INDArray array = Nd4j.linspace(1, 9, 9);
    Percentile percentile = new Percentile(75);
    double exp = percentile.evaluate(array.data().asDouble());
    assertEquals(exp, array.percentileNumber(75));
}
Also used : Percentile(org.apache.commons.math3.stat.descriptive.rank.Percentile) INDArray(org.nd4j.linalg.api.ndarray.INDArray) Test(org.junit.Test)

Example 17 with Percentile

use of org.apache.commons.math3.stat.descriptive.rank.Percentile in project nd4j by deeplearning4j.

the class Nd4jTestsC method testPercentile4.

@Test
public void testPercentile4() throws Exception {
    INDArray array = Nd4j.linspace(1, 10, 10);
    Percentile percentile = new Percentile(75);
    double exp = percentile.evaluate(array.data().asDouble());
    assertEquals(exp, array.percentileNumber(75));
}
Also used : Percentile(org.apache.commons.math3.stat.descriptive.rank.Percentile) INDArray(org.nd4j.linalg.api.ndarray.INDArray) Test(org.junit.Test)

Example 18 with Percentile

use of org.apache.commons.math3.stat.descriptive.rank.Percentile in project jmeter by apache.

the class SamplerMetric method resetForTimeInterval.

/**
 * Reset metric except for percentile related data
 */
public synchronized void resetForTimeInterval() {
    switch(globalWindowMode) {
        case FIXED:
            // http://commons.apache.org/proper/commons-math/userguide/stat.html
            break;
        case TIMED:
            for (DescriptiveStatistics stat : windowedStats) {
                stat.clear();
            }
            break;
        default:
    }
    errors.clear();
    successes = 0;
    failures = 0;
    hits = 0;
    sentBytes = 0;
    receivedBytes = 0;
}
Also used : DescriptiveStatistics(org.apache.commons.math3.stat.descriptive.DescriptiveStatistics)

Example 19 with Percentile

use of org.apache.commons.math3.stat.descriptive.rank.Percentile in project hive by apache.

the class ReplStatsTracker method toString.

@Override
public String toString() {
    StringBuilder sb = new StringBuilder();
    DecimalFormat dFormat = new DecimalFormat("#.##");
    dFormat.setRoundingMode(RoundingMode.HALF_UP);
    sb.append("Replication Stats{");
    for (Map.Entry<String, DescriptiveStatistics> event : descMap.entrySet()) {
        DescriptiveStatistics statistics = event.getValue();
        sb.append("[[Event Name: ").append(event.getKey()).append("; ");
        sb.append("Total Number: ").append(statistics.getN()).append("; ");
        sb.append("Total Time: ").append(dFormat.format(statistics.getSum())).append("; ");
        sb.append("Mean: ").append(formatDouble(dFormat, statistics.getMean())).append("; ");
        sb.append("Median: ").append(formatDouble(dFormat, statistics.getPercentile(50))).append("; ");
        sb.append("Standard Deviation: ").append(formatDouble(dFormat, statistics.getStandardDeviation())).append("; ");
        sb.append("Variance: ").append(formatDouble(dFormat, statistics.getVariance())).append("; ");
        sb.append("Kurtosis: ").append(formatDouble(dFormat, statistics.getKurtosis())).append("; ");
        sb.append("Skewness: ").append(formatDouble(dFormat, statistics.getSkewness())).append("; ");
        sb.append("25th Percentile: ").append(formatDouble(dFormat, statistics.getPercentile(25))).append("; ");
        sb.append("50th Percentile: ").append(formatDouble(dFormat, statistics.getPercentile(50))).append("; ");
        sb.append("75th Percentile: ").append(formatDouble(dFormat, statistics.getPercentile(75))).append("; ");
        sb.append("90th Percentile: ").append(formatDouble(dFormat, statistics.getPercentile(90))).append("; ");
        sb.append("Top ").append(k).append(" EventIds(EventId=Time) ").append(topKEvents.get(event.getKey())).append(";" + "]]");
    }
    sb.append("}");
    return sb.toString();
}
Also used : DescriptiveStatistics(org.apache.commons.math3.stat.descriptive.DescriptiveStatistics) DecimalFormat(java.text.DecimalFormat) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ListOrderedMap(org.apache.commons.collections4.map.ListOrderedMap)

Example 20 with Percentile

use of org.apache.commons.math3.stat.descriptive.rank.Percentile in project GDSC-SMLM by aherbert.

the class BenchmarkSpotFit method showDoubleHistogram.

private double[] showDoubleHistogram(StoredDataStatistics[][] stats, final int index, WindowOrganiser wo, double[][] matchScores) {
    final String xLabel = filterCriteria[index].name;
    LowerLimit lower = filterCriteria[index].lower;
    UpperLimit upper = filterCriteria[index].upper;
    double[] jaccard = null;
    double[] metric = null;
    double maxJaccard = 0;
    if (index <= FILTER_PRECISION && (settings.showFilterScoreHistograms || upper.requiresJaccard || lower.requiresJaccard)) {
        // Jaccard score verses the range of the metric
        for (final double[] d : matchScores) {
            if (!Double.isFinite(d[index])) {
                System.out.printf("Error in fit data [%d]: %s%n", index, d[index]);
            }
        }
        // Do not use Double.compare(double, double) so we get exceptions in the sort for inf/nan
        Arrays.sort(matchScores, (o1, o2) -> {
            if (o1[index] < o2[index]) {
                return -1;
            }
            if (o1[index] > o2[index]) {
                return 1;
            }
            return 0;
        });
        final int scoreIndex = FILTER_PRECISION + 1;
        final int n = results.size();
        double tp = 0;
        double fp = 0;
        jaccard = new double[matchScores.length + 1];
        metric = new double[jaccard.length];
        for (int k = 0; k < matchScores.length; k++) {
            final double score = matchScores[k][scoreIndex];
            tp += score;
            fp += (1 - score);
            jaccard[k + 1] = tp / (fp + n);
            metric[k + 1] = matchScores[k][index];
        }
        metric[0] = metric[1];
        maxJaccard = MathUtils.max(jaccard);
        if (settings.showFilterScoreHistograms) {
            final String title = TITLE + " Jaccard " + xLabel;
            final Plot plot = new Plot(title, xLabel, "Jaccard");
            plot.addPoints(metric, jaccard, Plot.LINE);
            // Remove outliers
            final double[] limitsx = MathUtils.limits(metric);
            final Percentile p = new Percentile();
            final double l = p.evaluate(metric, 25);
            final double u = p.evaluate(metric, 75);
            final double iqr = 1.5 * (u - l);
            limitsx[1] = Math.min(limitsx[1], u + iqr);
            plot.setLimits(limitsx[0], limitsx[1], 0, MathUtils.max(jaccard));
            ImageJUtils.display(title, plot, wo);
        }
    }
    // [0] is all
    // [1] is matches
    // [2] is no match
    final StoredDataStatistics s1 = stats[0][index];
    final StoredDataStatistics s2 = stats[1][index];
    final StoredDataStatistics s3 = stats[2][index];
    if (s1.getN() == 0) {
        return new double[4];
    }
    final DescriptiveStatistics d = s1.getStatistics();
    double median = 0;
    Plot plot = null;
    String title = null;
    if (settings.showFilterScoreHistograms) {
        median = d.getPercentile(50);
        final String label = String.format("n = %d. Median = %s nm", s1.getN(), MathUtils.rounded(median));
        final HistogramPlot histogramPlot = new HistogramPlotBuilder(TITLE, s1, xLabel).setMinBinWidth(filterCriteria[index].minBinWidth).setRemoveOutliersOption((filterCriteria[index].restrictRange) ? 1 : 0).setPlotLabel(label).build();
        final PlotWindow plotWindow = histogramPlot.show(wo);
        if (plotWindow == null) {
            IJ.log("Failed to show the histogram: " + xLabel);
            return new double[4];
        }
        title = plotWindow.getTitle();
        // Reverse engineer the histogram settings
        plot = histogramPlot.getPlot();
        final double[] xvalues = histogramPlot.getPlotXValues();
        final int bins = xvalues.length;
        final double yMin = xvalues[0];
        final double binSize = xvalues[1] - xvalues[0];
        final double yMax = xvalues[0] + (bins - 1) * binSize;
        if (s2.getN() > 0) {
            final double[] values = s2.getValues();
            final double[][] hist = HistogramPlot.calcHistogram(values, yMin, yMax, bins);
            if (hist[0].length > 0) {
                plot.setColor(Color.red);
                plot.addPoints(hist[0], hist[1], Plot.BAR);
                ImageJUtils.display(title, plot);
            }
        }
        if (s3.getN() > 0) {
            final double[] values = s3.getValues();
            final double[][] hist = HistogramPlot.calcHistogram(values, yMin, yMax, bins);
            if (hist[0].length > 0) {
                plot.setColor(Color.blue);
                plot.addPoints(hist[0], hist[1], Plot.BAR);
                ImageJUtils.display(title, plot);
            }
        }
    }
    // Do cumulative histogram
    final double[][] h1 = MathUtils.cumulativeHistogram(s1.getValues(), true);
    final double[][] h2 = MathUtils.cumulativeHistogram(s2.getValues(), true);
    final double[][] h3 = MathUtils.cumulativeHistogram(s3.getValues(), true);
    if (settings.showFilterScoreHistograms) {
        title = TITLE + " Cumul " + xLabel;
        plot = new Plot(title, xLabel, "Frequency");
        // Find limits
        double[] xlimit = MathUtils.limits(h1[0]);
        xlimit = MathUtils.limits(xlimit, h2[0]);
        xlimit = MathUtils.limits(xlimit, h3[0]);
        // Restrict using the inter-quartile range
        if (filterCriteria[index].restrictRange) {
            final double q1 = d.getPercentile(25);
            final double q2 = d.getPercentile(75);
            final double iqr = (q2 - q1) * 2.5;
            xlimit[0] = MathUtils.max(xlimit[0], median - iqr);
            xlimit[1] = MathUtils.min(xlimit[1], median + iqr);
        }
        plot.setLimits(xlimit[0], xlimit[1], 0, 1.05);
        plot.addPoints(h1[0], h1[1], Plot.LINE);
        plot.setColor(Color.red);
        plot.addPoints(h2[0], h2[1], Plot.LINE);
        plot.setColor(Color.blue);
        plot.addPoints(h3[0], h3[1], Plot.LINE);
    }
    // Determine the maximum difference between the TP and FP
    double maxx1 = 0;
    double maxx2 = 0;
    double max1 = 0;
    double max2 = 0;
    // We cannot compute the delta histogram, or use percentiles
    if (s2.getN() == 0) {
        upper = UpperLimit.ZERO;
        lower = LowerLimit.ZERO;
    }
    final boolean requireLabel = (settings.showFilterScoreHistograms && filterCriteria[index].requireLabel);
    if (requireLabel || upper.requiresDeltaHistogram() || lower.requiresDeltaHistogram()) {
        if (s2.getN() != 0 && s3.getN() != 0) {
            final LinearInterpolator li = new LinearInterpolator();
            final PolynomialSplineFunction f1 = li.interpolate(h2[0], h2[1]);
            final PolynomialSplineFunction f2 = li.interpolate(h3[0], h3[1]);
            for (final double x : h1[0]) {
                if (x < h2[0][0] || x < h3[0][0]) {
                    continue;
                }
                try {
                    final double v1 = f1.value(x);
                    final double v2 = f2.value(x);
                    final double diff = v2 - v1;
                    if (diff > 0) {
                        if (max1 < diff) {
                            max1 = diff;
                            maxx1 = x;
                        }
                    } else if (max2 > diff) {
                        max2 = diff;
                        maxx2 = x;
                    }
                } catch (final OutOfRangeException ex) {
                    // Because we reached the end
                    break;
                }
            }
        }
    }
    if (plot != null) {
        // We use bins=1 on charts where we do not need a label
        if (requireLabel) {
            final String label = String.format("Max+ %s @ %s, Max- %s @ %s", MathUtils.rounded(max1), MathUtils.rounded(maxx1), MathUtils.rounded(max2), MathUtils.rounded(maxx2));
            plot.setColor(Color.black);
            plot.addLabel(0, 0, label);
        }
        ImageJUtils.display(title, plot, wo);
    }
    // Now compute the bounds using the desired limit
    double lowerBound;
    double upperBound;
    switch(lower) {
        case MAX_NEGATIVE_CUMUL_DELTA:
            // Switch to percentiles if we have no delta histogram
            if (maxx2 < 0) {
                lowerBound = maxx2;
                break;
            }
        // fall-through
        case ONE_PERCENT:
            lowerBound = getPercentile(h2, 0.01);
            break;
        case MIN:
            lowerBound = getPercentile(h2, 0.0);
            break;
        case ZERO:
            lowerBound = 0;
            break;
        case HALF_MAX_JACCARD_VALUE:
            lowerBound = getXValue(metric, jaccard, maxJaccard * 0.5);
            break;
        default:
            throw new IllegalStateException("Missing lower limit method");
    }
    switch(upper) {
        case MAX_POSITIVE_CUMUL_DELTA:
            // Switch to percentiles if we have no delta histogram
            if (maxx1 > 0) {
                upperBound = maxx1;
                break;
            }
        // fall-through
        case NINETY_NINE_PERCENT:
            upperBound = getPercentile(h2, 0.99);
            break;
        case NINETY_NINE_NINE_PERCENT:
            upperBound = getPercentile(h2, 0.999);
            break;
        case ZERO:
            upperBound = 0;
            break;
        case MAX_JACCARD2:
            upperBound = getXValue(metric, jaccard, maxJaccard) * 2;
            // System.out.printf("MaxJ = %.4f @ %.3f\n", maxJ, u / 2);
            break;
        default:
            throw new IllegalStateException("Missing upper limit method");
    }
    final double min = getPercentile(h1, 0);
    final double max = getPercentile(h1, 1);
    return new double[] { lowerBound, upperBound, min, max };
}
Also used : DescriptiveStatistics(org.apache.commons.math3.stat.descriptive.DescriptiveStatistics) Percentile(org.apache.commons.math3.stat.descriptive.rank.Percentile) Plot(ij.gui.Plot) HistogramPlot(uk.ac.sussex.gdsc.core.ij.HistogramPlot) StoredDataStatistics(uk.ac.sussex.gdsc.core.utils.StoredDataStatistics) HistogramPlotBuilder(uk.ac.sussex.gdsc.core.ij.HistogramPlot.HistogramPlotBuilder) PlotWindow(ij.gui.PlotWindow) PolynomialSplineFunction(org.apache.commons.math3.analysis.polynomials.PolynomialSplineFunction) PeakResultPoint(uk.ac.sussex.gdsc.smlm.results.PeakResultPoint) BasePoint(uk.ac.sussex.gdsc.core.match.BasePoint) HistogramPlot(uk.ac.sussex.gdsc.core.ij.HistogramPlot) LinearInterpolator(org.apache.commons.math3.analysis.interpolation.LinearInterpolator) OutOfRangeException(org.apache.commons.math3.exception.OutOfRangeException)

Aggregations

Percentile (org.apache.commons.math3.stat.descriptive.rank.Percentile)31 ArrayList (java.util.ArrayList)16 RealMatrix (org.apache.commons.math3.linear.RealMatrix)16 Array2DRowRealMatrix (org.apache.commons.math3.linear.Array2DRowRealMatrix)14 List (java.util.List)11 Collectors (java.util.stream.Collectors)11 IntStream (java.util.stream.IntStream)11 File (java.io.File)10 DoubleStream (java.util.stream.DoubleStream)10 Median (org.apache.commons.math3.stat.descriptive.rank.Median)10 Logger (org.apache.logging.log4j.Logger)10 Test (org.testng.annotations.Test)10 Random (java.util.Random)9 Stream (java.util.stream.Stream)9 DescriptiveStatistics (org.apache.commons.math3.stat.descriptive.DescriptiveStatistics)9 Level (org.apache.logging.log4j.Level)8 Marker (org.apache.logging.log4j.Marker)8 Message (org.apache.logging.log4j.message.Message)8 AbstractLogger (org.apache.logging.log4j.spi.AbstractLogger)8 SimpleInterval (org.broadinstitute.hellbender.utils.SimpleInterval)8