Search in sources :

Example 61 with Plot

use of ij.gui.Plot in project GDSC-SMLM by aherbert.

the class CmosAnalysis method showHistogram.

private static void showHistogram(String name, double[] values, int bins, Statistics stats, WindowOrganiser wo) {
    final DoubleData data = DoubleData.wrap(values);
    final double minWidth = 0;
    final int removeOutliers = 0;
    final int shape = Plot.CIRCLE;
    final String label = String.format("Mean = %s +/- %s", MathUtils.rounded(stats.getMean()), MathUtils.rounded(stats.getStandardDeviation()));
    final HistogramPlot histogramPlot = new HistogramPlotBuilder(TITLE, data, name).setMinBinWidth(minWidth).setRemoveOutliersOption(removeOutliers).setNumberOfBins(bins).setPlotShape(shape).setPlotLabel(label).build();
    histogramPlot.show(wo);
    // Redraw using a log scale. This requires a non-zero y-min
    final Plot plot = histogramPlot.getPlot();
    final double[] limits = plot.getLimits();
    plot.setLimits(limits[0], limits[1], 1, limits[3]);
    plot.setAxisYLog(true);
    plot.updateImage();
}
Also used : HistogramPlot(uk.ac.sussex.gdsc.core.ij.HistogramPlot) Plot(ij.gui.Plot) HistogramPlot(uk.ac.sussex.gdsc.core.ij.HistogramPlot) HistogramPlotBuilder(uk.ac.sussex.gdsc.core.ij.HistogramPlot.HistogramPlotBuilder) DoubleData(uk.ac.sussex.gdsc.core.utils.DoubleData)

Example 62 with Plot

use of ij.gui.Plot in project GDSC-SMLM by aherbert.

the class CmosAnalysis method computeError.

private void computeError(int slice, ImageStack simulationStack, WindowOrganiser wo) {
    final String label = simulationStack.getSliceLabel(slice);
    final float[] e = (float[]) simulationStack.getPixels(slice);
    final float[] o = (float[]) measuredStack.getPixels(slice);
    // Get the mean error
    final double[] error = new double[e.length];
    for (int i = e.length; i-- > 0; ) {
        error[i] = (double) o[i] - e[i];
    }
    final Statistics s = new Statistics();
    s.add(error);
    final StringBuilder result = new StringBuilder("Error ").append(label);
    result.append(" = ").append(MathUtils.rounded(s.getMean()));
    result.append(" +/- ").append(MathUtils.rounded(s.getStandardDeviation()));
    // Do statistical tests
    final double[] x = SimpleArrayUtils.toDouble(e);
    final double[] y = SimpleArrayUtils.toDouble(o);
    final PearsonsCorrelation c = new PearsonsCorrelation();
    result.append(" : R=").append(MathUtils.rounded(c.correlation(x, y)));
    // Plot these
    String title = TITLE + " " + label + " Simulation vs Measured";
    final Plot plot = new Plot(title, "simulated", "measured");
    plot.addPoints(e, o, Plot.DOT);
    plot.addLabel(0, 0, result.toString());
    ImageJUtils.display(title, plot, wo);
    // Histogram the error
    new HistogramPlotBuilder(TITLE + " " + label, DoubleData.wrap(error), "Error").setPlotLabel(result.toString()).show(wo);
    // Kolmogorov–Smirnov test that the distributions are the same
    double pvalue = TestUtils.kolmogorovSmirnovTest(x, y);
    result.append(" : Kolmogorov–Smirnov p=").append(MathUtils.rounded(pvalue)).append(' ').append(((pvalue < 0.001) ? REJECT : ACCEPT));
    if (slice == 3) {
        // Paired T-Test compares two related samples to assess whether their
        // population means differ.
        // T-Test is valid when the difference between the means is normally
        // distributed, e.g. gain
        pvalue = TestUtils.pairedTTest(x, y);
        result.append(" : Paired T-Test p=").append(MathUtils.rounded(pvalue)).append(' ').append(((pvalue < 0.001) ? REJECT : ACCEPT));
    } else {
        // Wilcoxon Signed Rank test compares two related samples to assess whether their
        // population mean ranks differ
        final WilcoxonSignedRankTest wsrTest = new WilcoxonSignedRankTest();
        pvalue = wsrTest.wilcoxonSignedRankTest(x, y, false);
        result.append(" : Wilcoxon Signed Rank p=").append(MathUtils.rounded(pvalue)).append(' ').append(((pvalue < 0.001) ? REJECT : ACCEPT));
    }
    ImageJUtils.log(result.toString());
}
Also used : WilcoxonSignedRankTest(org.apache.commons.math3.stat.inference.WilcoxonSignedRankTest) Plot(ij.gui.Plot) HistogramPlot(uk.ac.sussex.gdsc.core.ij.HistogramPlot) HistogramPlotBuilder(uk.ac.sussex.gdsc.core.ij.HistogramPlot.HistogramPlotBuilder) Statistics(uk.ac.sussex.gdsc.core.utils.Statistics) PearsonsCorrelation(org.apache.commons.math3.stat.correlation.PearsonsCorrelation)

Example 63 with Plot

use of ij.gui.Plot in project GDSC-SMLM by aherbert.

the class DensityEstimator method run.

@Override
public void run(String arg) {
    SmlmUsageTracker.recordPlugin(this.getClass(), arg);
    // Require some fit results and selected regions
    if (MemoryPeakResults.countMemorySize() == 0) {
        IJ.error(TITLE, "There are no fitting results in memory");
        return;
    }
    if (!showDialog()) {
        return;
    }
    // Currently this only supports pixel distance units
    final MemoryPeakResults results = ResultsManager.loadInputResults(settings.inputOption, false, DistanceUnit.PIXEL, null);
    if (MemoryPeakResults.isEmpty(results)) {
        IJ.error(TITLE, "No results could be loaded");
        IJ.showStatus("");
        return;
    }
    final long start = System.currentTimeMillis();
    IJ.showStatus("Calculating density ...");
    // Scale to um^2 from px^2
    final double scale = Math.pow(results.getDistanceConverter(DistanceUnit.UM).convertBack(1), 2);
    results.sort();
    final FrameCounter counter = results.newFrameCounter();
    final double localisationsPerFrame = (double) results.size() / (results.getLastFrame() - counter.currentFrame() + 1);
    final Rectangle bounds = results.getBounds(true);
    final double globalDensity = localisationsPerFrame / bounds.width / bounds.height;
    final int border = settings.border;
    final boolean includeSingles = settings.includeSingles;
    final int size = 2 * border + 1;
    final double minDensity = Math.pow(size, -2);
    ImageJUtils.log("%s : %s : Global density %s. Minimum density in %dx%d px = %s um^-2", TITLE, results.getName(), MathUtils.rounded(globalDensity * scale), size, size, MathUtils.rounded(minDensity * scale));
    final TIntArrayList x = new TIntArrayList();
    final TIntArrayList y = new TIntArrayList();
    final ExecutorService es = Executors.newFixedThreadPool(Prefs.getThreads());
    final LocalList<FrameDensity> densities = new LocalList<>();
    final LocalList<Future<?>> futures = new LocalList<>();
    results.forEach((PeakResultProcedure) (peak) -> {
        if (counter.advance(peak.getFrame())) {
            final FrameDensity fd = new FrameDensity(peak.getFrame(), x.toArray(), y.toArray(), border, includeSingles);
            densities.add(fd);
            futures.add(es.submit(fd));
            x.resetQuick();
            y.resetQuick();
        }
        x.add((int) peak.getXPosition());
        y.add((int) peak.getYPosition());
    });
    densities.add(new FrameDensity(counter.currentFrame(), x.toArray(), y.toArray(), border, includeSingles));
    futures.add(es.submit(densities.get(densities.size() - 1)));
    es.shutdown();
    // Wait
    ConcurrencyUtils.waitForCompletionUnchecked(futures);
    densities.sort((o1, o2) -> Integer.compare(o1.frame, o2.frame));
    final int total = densities.stream().mapToInt(fd -> fd.counts.length).sum();
    // Plot density
    final Statistics stats = new Statistics();
    final float[] frame = new float[total];
    final float[] density = new float[total];
    densities.stream().forEach(fd -> {
        for (int i = 0; i < fd.counts.length; i++) {
            final double d = (fd.counts[i] / fd.values[i]) * scale;
            frame[stats.getN()] = fd.frame;
            density[stats.getN()] = (float) d;
            stats.add(d);
        }
    });
    final double mean = stats.getMean();
    final double sd = stats.getStandardDeviation();
    final String label = String.format("Density = %s +/- %s um^-2", MathUtils.rounded(mean), MathUtils.rounded(sd));
    final Plot plot = new Plot("Frame vs Density", "Frame", "Density (um^-2)");
    plot.addPoints(frame, density, Plot.CIRCLE);
    plot.addLabel(0, 0, label);
    final WindowOrganiser wo = new WindowOrganiser();
    ImageJUtils.display(plot.getTitle(), plot, wo);
    // Histogram density
    new HistogramPlotBuilder("Local", StoredData.create(density), "Density (um^-2)").setPlotLabel(label).show(wo);
    wo.tile();
    // Log the number of singles
    final int singles = densities.stream().mapToInt(fd -> fd.singles).sum();
    ImageJUtils.log("Singles %d / %d (%s%%)", singles, results.size(), MathUtils.rounded(100.0 * singles / results.size()));
    IJ.showStatus(TITLE + " complete : " + TextUtils.millisToString(System.currentTimeMillis() - start));
}
Also used : Rectangle(java.awt.Rectangle) Arrays(java.util.Arrays) TIntArrayList(gnu.trove.list.array.TIntArrayList) HistogramPlotBuilder(uk.ac.sussex.gdsc.core.ij.HistogramPlot.HistogramPlotBuilder) Prefs(ij.Prefs) StoredData(uk.ac.sussex.gdsc.core.utils.StoredData) FrameCounter(uk.ac.sussex.gdsc.smlm.results.count.FrameCounter) WindowOrganiser(uk.ac.sussex.gdsc.core.ij.plugin.WindowOrganiser) IntDoubleConsumer(uk.ac.sussex.gdsc.core.utils.function.IntDoubleConsumer) AtomicReference(java.util.concurrent.atomic.AtomicReference) Future(java.util.concurrent.Future) MemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults) PeakResultProcedure(uk.ac.sussex.gdsc.smlm.results.procedures.PeakResultProcedure) MathUtils(uk.ac.sussex.gdsc.core.utils.MathUtils) Statistics(uk.ac.sussex.gdsc.core.utils.Statistics) ExecutorService(java.util.concurrent.ExecutorService) LocalDensity(uk.ac.sussex.gdsc.smlm.results.LocalDensity) ExtendedGenericDialog(uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog) InputSource(uk.ac.sussex.gdsc.smlm.ij.plugins.ResultsManager.InputSource) DistanceUnit(uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.DistanceUnit) ConcurrencyUtils(uk.ac.sussex.gdsc.core.utils.concurrent.ConcurrencyUtils) TextUtils(uk.ac.sussex.gdsc.core.utils.TextUtils) Plot(ij.gui.Plot) Executors(java.util.concurrent.Executors) ImageJUtils(uk.ac.sussex.gdsc.core.ij.ImageJUtils) IJ(ij.IJ) PlugIn(ij.plugin.PlugIn) LocalList(uk.ac.sussex.gdsc.core.utils.LocalList) FrameCounter(uk.ac.sussex.gdsc.smlm.results.count.FrameCounter) Plot(ij.gui.Plot) Rectangle(java.awt.Rectangle) HistogramPlotBuilder(uk.ac.sussex.gdsc.core.ij.HistogramPlot.HistogramPlotBuilder) WindowOrganiser(uk.ac.sussex.gdsc.core.ij.plugin.WindowOrganiser) Statistics(uk.ac.sussex.gdsc.core.utils.Statistics) TIntArrayList(gnu.trove.list.array.TIntArrayList) LocalList(uk.ac.sussex.gdsc.core.utils.LocalList) ExecutorService(java.util.concurrent.ExecutorService) Future(java.util.concurrent.Future) MemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults)

Example 64 with Plot

use of ij.gui.Plot in project GDSC-SMLM by aherbert.

the class DiffusionRateTest method plotMsd.

/**
 * Plot the MSD.
 *
 * @param totalSteps the total steps
 * @param xValues the x values (the time)
 * @param yValues the y values (MSD)
 * @param lower the lower bounds (mean-SD)
 * @param upper the upper bounds (mean+SD)
 * @param fitted the fitted line
 * @param dimensions the number of dimensions for the jumps
 */
private void plotMsd(int totalSteps, double[] xValues, double[] yValues, double[] lower, double[] upper, PolynomialFunction fitted, int dimensions) {
    final String title = TITLE + " " + dimensions + "D";
    final Plot plot = new Plot(title, "Time (seconds)", "Mean-squared Distance (um^2)");
    plot.addPoints(xValues, yValues, Plot.LINE);
    double[] limits = MathUtils.limits(upper);
    limits = MathUtils.limits(limits, lower);
    plot.setLimits(0, totalSteps / settings.getStepsPerSecond(), limits[0], limits[1]);
    plot.setColor(Color.blue);
    plot.addPoints(xValues, lower, Plot.LINE);
    plot.addPoints(xValues, upper, Plot.LINE);
    if (fitted != null) {
        plot.setColor(Color.red);
        plot.addPoints(new double[] { xValues[0], xValues[xValues.length - 1] }, new double[] { fitted.value(xValues[0]), fitted.value(xValues[xValues.length - 1]) }, Plot.LINE);
    }
    plot.setColor(Color.black);
    ImageJUtils.display(title, plot, 0, windowOrganiser);
}
Also used : Plot(ij.gui.Plot) HistogramPlot(uk.ac.sussex.gdsc.core.ij.HistogramPlot)

Example 65 with Plot

use of ij.gui.Plot in project GDSC-SMLM by aherbert.

the class AstigmatismModelManager method plotFit.

private void plotFit(final double[] parameters) {
    final double gamma = parameters[P_GAMMA];
    final double d = parameters[P_D];
    final double s0x = parameters[P_S0X];
    final double Ax = parameters[P_AX];
    final double Bx = parameters[P_BX];
    final double s0y = parameters[P_S0Y];
    final double Ay = parameters[P_AY];
    final double By = parameters[P_BY];
    final double z0 = parameters[P_Z0];
    // Draw across the entire data range
    final double one_d2 = 1.0 / MathUtils.pow2(d);
    // Update plot
    final double[] sx1 = new double[z.length];
    final double[] sy1 = new double[z.length];
    for (int i = 0; i < z.length; i++) {
        sx1[i] = getS(s0x, z[i] - z0 - gamma, one_d2, Ax, Bx);
        sy1[i] = getS(s0y, z[i] - z0 + gamma, one_d2, Ay, By);
    }
    // Just redraw the plot
    widthPlot = plot(null, z, "Width (px)", sx, "Sx", sy, "Sy");
    final Plot plot = widthPlot.getPlot();
    plot.setColor(Color.RED);
    plot.addPoints(z, sx1, Plot.LINE);
    plot.setColor(Color.BLUE);
    plot.addPoints(z, sy1, Plot.LINE);
    plot.setColor(Color.BLACK);
    plot.updateImage();
}
Also used : Plot(ij.gui.Plot)

Aggregations

Plot (ij.gui.Plot)89 HistogramPlot (uk.ac.sussex.gdsc.core.ij.HistogramPlot)20 Point (java.awt.Point)19 PlotWindow (ij.gui.PlotWindow)17 Color (java.awt.Color)13 WindowOrganiser (uk.ac.sussex.gdsc.core.ij.plugin.WindowOrganiser)13 HistogramPlotBuilder (uk.ac.sussex.gdsc.core.ij.HistogramPlot.HistogramPlotBuilder)12 BasePoint (uk.ac.sussex.gdsc.core.match.BasePoint)12 ExtendedGenericDialog (uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog)11 MemoryPeakResults (uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults)11 Rectangle (java.awt.Rectangle)9 ArrayList (java.util.ArrayList)9 GenericDialog (ij.gui.GenericDialog)8 NonBlockingExtendedGenericDialog (uk.ac.sussex.gdsc.core.ij.gui.NonBlockingExtendedGenericDialog)7 LocalList (uk.ac.sussex.gdsc.core.utils.LocalList)7 Statistics (uk.ac.sussex.gdsc.core.utils.Statistics)7 StoredData (uk.ac.sussex.gdsc.core.utils.StoredData)7 StoredDataStatistics (uk.ac.sussex.gdsc.core.utils.StoredDataStatistics)7 ImagePlus (ij.ImagePlus)6 TDoubleArrayList (gnu.trove.list.array.TDoubleArrayList)5