Search in sources :

Example 11 with FrameCounter

use of uk.ac.sussex.gdsc.smlm.results.count.FrameCounter in project GDSC-SMLM by aherbert.

the class Filter method fractionScore.

/**
 * Filter the results and return the performance score. Allows benchmarking the filter by marking
 * the results as true or false.
 *
 * <p>Input PeakResults must be allocated a score for true positive, false positive, true negative
 * and false negative (accessed via the object property get methods). The filter is run and
 * results that pass accumulate scores for true positive and false positive, otherwise the scores
 * are accumulated for true negative and false negative. The simplest scoring scheme is to mark
 * valid results as tp=fn=1 and fp=tn=0 and invalid results the opposite.
 *
 * <p>The number of consecutive rejections are counted per frame. When the configured number of
 * failures is reached all remaining results for the frame are rejected. This assumes the results
 * are ordered by the frame.
 *
 * @param resultsList a list of results to analyse
 * @param failures the number of failures to allow per frame before all peaks are rejected
 * @return the score
 */
public FractionClassificationResult fractionScore(List<MemoryPeakResults> resultsList, final int failures) {
    final double[] s = new double[4];
    final Counter p = new Counter();
    int negatives = 0;
    for (final MemoryPeakResults peakResults : resultsList) {
        setup(peakResults);
        final FrameCounter counter = new FrameCounter();
        peakResults.forEach((PeakResultProcedure) peak -> {
            counter.advanceAndReset(peak.getFrame());
            final boolean isPositive;
            if (counter.getCount() > failures) {
                isPositive = false;
            } else {
                isPositive = accept(peak);
            }
            if (isPositive) {
                counter.reset();
            } else {
                counter.increment();
            }
            if (isPositive) {
                p.increment();
                s[TP] += peak.getTruePositiveScore();
                s[FP] += peak.getFalsePositiveScore();
            } else {
                s[FN] += peak.getFalseNegativeScore();
                s[TN] += peak.getTrueNegativeScore();
            }
        });
        negatives += peakResults.size();
        end();
    }
    negatives -= p.getCount();
    return new FractionClassificationResult(s[TP], s[FP], s[TN], s[FN], p.getCount(), negatives);
}
Also used : Chromosome(uk.ac.sussex.gdsc.smlm.ga.Chromosome) List(java.util.List) Counter(uk.ac.sussex.gdsc.smlm.results.count.Counter) MemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults) SimpleArrayUtils(uk.ac.sussex.gdsc.core.utils.SimpleArrayUtils) FrameCounter(uk.ac.sussex.gdsc.smlm.results.count.FrameCounter) Nullable(uk.ac.sussex.gdsc.core.annotation.Nullable) ClassificationResult(uk.ac.sussex.gdsc.core.match.ClassificationResult) PeakResult(uk.ac.sussex.gdsc.smlm.results.PeakResult) PeakResultProcedure(uk.ac.sussex.gdsc.smlm.results.procedures.PeakResultProcedure) XStreamOmitField(com.thoughtworks.xstream.annotations.XStreamOmitField) FractionClassificationResult(uk.ac.sussex.gdsc.core.match.FractionClassificationResult) Counter(uk.ac.sussex.gdsc.smlm.results.count.Counter) FrameCounter(uk.ac.sussex.gdsc.smlm.results.count.FrameCounter) FrameCounter(uk.ac.sussex.gdsc.smlm.results.count.FrameCounter) FractionClassificationResult(uk.ac.sussex.gdsc.core.match.FractionClassificationResult) MemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults)

Example 12 with FrameCounter

use of uk.ac.sussex.gdsc.smlm.results.count.FrameCounter in project GDSC-SMLM by aherbert.

the class Filter method filter2.

/**
 * Filter the results.
 *
 * <p>The number of consecutive rejections are counted per frame. When the configured number of
 * failures is reached all remaining results for the frame are rejected. This assumes the results
 * are ordered by the frame.
 *
 * <p>Note that this method is to be used to score a set of results that may have been extracted
 * from a larger set since the number of consecutive failures before each peak are expected to be
 * stored in the origY property. Set this to zero and the results should be identical to
 * {@link #filter(MemoryPeakResults, int)}
 *
 * @param results the results
 * @param failures the number of failures to allow per frame before all peaks are rejected
 * @return the filtered results
 */
public MemoryPeakResults filter2(MemoryPeakResults results, final int failures) {
    final MemoryPeakResults newResults = new MemoryPeakResults();
    final FrameCounter counter = new FrameCounter();
    newResults.copySettings(results);
    setup(results);
    results.forEach((PeakResultProcedure) peak -> {
        counter.advanceAndReset(peak.getFrame());
        counter.increment(peak.getOrigY());
        final boolean isPositive;
        if (counter.getCount() > failures) {
            isPositive = false;
        } else {
            isPositive = accept(peak);
        }
        if (isPositive) {
            counter.reset();
            newResults.add(peak);
        } else {
            counter.increment();
        }
    });
    end();
    return newResults;
}
Also used : Chromosome(uk.ac.sussex.gdsc.smlm.ga.Chromosome) List(java.util.List) Counter(uk.ac.sussex.gdsc.smlm.results.count.Counter) MemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults) SimpleArrayUtils(uk.ac.sussex.gdsc.core.utils.SimpleArrayUtils) FrameCounter(uk.ac.sussex.gdsc.smlm.results.count.FrameCounter) Nullable(uk.ac.sussex.gdsc.core.annotation.Nullable) ClassificationResult(uk.ac.sussex.gdsc.core.match.ClassificationResult) PeakResult(uk.ac.sussex.gdsc.smlm.results.PeakResult) PeakResultProcedure(uk.ac.sussex.gdsc.smlm.results.procedures.PeakResultProcedure) XStreamOmitField(com.thoughtworks.xstream.annotations.XStreamOmitField) FractionClassificationResult(uk.ac.sussex.gdsc.core.match.FractionClassificationResult) FrameCounter(uk.ac.sussex.gdsc.smlm.results.count.FrameCounter) MemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults)

Example 13 with FrameCounter

use of uk.ac.sussex.gdsc.smlm.results.count.FrameCounter in project GDSC-SMLM by aherbert.

the class Filter method scoreSubset.

/**
 * Filter the results and return the performance score. Allows benchmarking the filter by marking
 * the results as true or false.
 *
 * <p>Any input PeakResult with an original value that is not zero will be treated as a true
 * result, all other results are false. The filter is run and the results are marked as true
 * positive, false negative and false positive.
 *
 * <p>The number of consecutive rejections are counted per frame. When the configured number of
 * failures is reached all remaining results for the frame are rejected. This assumes the results
 * are ordered by the frame.
 *
 * <p>Note that this method is to be used to score a subset that was generated using
 * {@link #filterSubset(MemoryPeakResults, int, double[])} since the number of consecutive
 * failures before each peak are expected to be stored in the origX property.
 *
 * @param resultsList a list of results to analyse
 * @param failures the number of failures to allow per frame before all peaks are rejected
 * @param tn The initial true negatives (used when the results have been pre-filtered)
 * @param fn The initial false negatives (used when the results have been pre-filtered)
 * @return the score
 */
public ClassificationResult scoreSubset(List<MemoryPeakResults> resultsList, final int failures, int tn, int fn) {
    final int[] s = new int[4];
    s[TN] = tn;
    s[FN] = fn;
    for (final MemoryPeakResults peakResults : resultsList) {
        setup(peakResults);
        final FrameCounter counter = new FrameCounter();
        peakResults.forEach((PeakResultProcedure) peak -> {
            counter.advanceAndReset(peak.getFrame());
            final boolean isTrue = peak.getOrigValue() != 0;
            counter.increment(peak.getOrigX());
            final boolean isPositive;
            if (counter.getCount() > failures) {
                isPositive = false;
            } else {
                isPositive = accept(peak);
            }
            if (isPositive) {
                counter.reset();
            } else {
                counter.increment();
            }
            if (isTrue) {
                if (isPositive) {
                    s[TP]++;
                } else {
                    s[FN]++;
                }
            } else if (isPositive) {
                s[FP]++;
            } else {
                s[TN]++;
            }
        });
        end();
    }
    return new ClassificationResult(s[TP], s[FP], s[TN], s[FN]);
}
Also used : Chromosome(uk.ac.sussex.gdsc.smlm.ga.Chromosome) List(java.util.List) Counter(uk.ac.sussex.gdsc.smlm.results.count.Counter) MemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults) SimpleArrayUtils(uk.ac.sussex.gdsc.core.utils.SimpleArrayUtils) FrameCounter(uk.ac.sussex.gdsc.smlm.results.count.FrameCounter) Nullable(uk.ac.sussex.gdsc.core.annotation.Nullable) ClassificationResult(uk.ac.sussex.gdsc.core.match.ClassificationResult) PeakResult(uk.ac.sussex.gdsc.smlm.results.PeakResult) PeakResultProcedure(uk.ac.sussex.gdsc.smlm.results.procedures.PeakResultProcedure) XStreamOmitField(com.thoughtworks.xstream.annotations.XStreamOmitField) FractionClassificationResult(uk.ac.sussex.gdsc.core.match.FractionClassificationResult) FrameCounter(uk.ac.sussex.gdsc.smlm.results.count.FrameCounter) MemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults) ClassificationResult(uk.ac.sussex.gdsc.core.match.ClassificationResult) FractionClassificationResult(uk.ac.sussex.gdsc.core.match.FractionClassificationResult)

Example 14 with FrameCounter

use of uk.ac.sussex.gdsc.smlm.results.count.FrameCounter in project GDSC-SMLM by aherbert.

the class Filter method score.

/**
 * Filter the results and return the performance score. Allows benchmarking the filter by marking
 * the results as true or false.
 *
 * <p>Any input PeakResult with an original value that is not zero will be treated as a true
 * result, all other results are false. The filter is run and the results are marked as true
 * positive, false negative and false positive.
 *
 * <p>The number of consecutive rejections are counted per frame. When the configured number of
 * failures is reached all remaining results for the frame are rejected. This assumes the results
 * are ordered by the frame.
 *
 * @param resultsList a list of results to analyse
 * @param failures the number of failures to allow per frame before all peaks are rejected
 * @return the score
 */
public ClassificationResult score(List<MemoryPeakResults> resultsList, final int failures) {
    final int[] s = new int[4];
    for (final MemoryPeakResults peakResults : resultsList) {
        setup(peakResults);
        final FrameCounter counter = new FrameCounter();
        peakResults.forEach((PeakResultProcedure) peak -> {
            counter.advanceAndReset(peak.getFrame());
            final boolean isTrue = peak.getOrigValue() != 0;
            final boolean isPositive;
            if (counter.getCount() > failures) {
                isPositive = false;
            } else {
                isPositive = accept(peak);
            }
            if (isPositive) {
                counter.reset();
            } else {
                counter.increment();
            }
            if (isTrue) {
                if (isPositive) {
                    s[TP]++;
                } else {
                    s[FN]++;
                }
            } else if (isPositive) {
                s[FP]++;
            } else {
                s[TN]++;
            }
        });
        end();
    }
    return new ClassificationResult(s[TP], s[FP], s[TN], s[FN]);
}
Also used : Chromosome(uk.ac.sussex.gdsc.smlm.ga.Chromosome) List(java.util.List) Counter(uk.ac.sussex.gdsc.smlm.results.count.Counter) MemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults) SimpleArrayUtils(uk.ac.sussex.gdsc.core.utils.SimpleArrayUtils) FrameCounter(uk.ac.sussex.gdsc.smlm.results.count.FrameCounter) Nullable(uk.ac.sussex.gdsc.core.annotation.Nullable) ClassificationResult(uk.ac.sussex.gdsc.core.match.ClassificationResult) PeakResult(uk.ac.sussex.gdsc.smlm.results.PeakResult) PeakResultProcedure(uk.ac.sussex.gdsc.smlm.results.procedures.PeakResultProcedure) XStreamOmitField(com.thoughtworks.xstream.annotations.XStreamOmitField) FractionClassificationResult(uk.ac.sussex.gdsc.core.match.FractionClassificationResult) FrameCounter(uk.ac.sussex.gdsc.smlm.results.count.FrameCounter) MemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults) ClassificationResult(uk.ac.sussex.gdsc.core.match.ClassificationResult) FractionClassificationResult(uk.ac.sussex.gdsc.core.match.FractionClassificationResult)

Example 15 with FrameCounter

use of uk.ac.sussex.gdsc.smlm.results.count.FrameCounter 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)

Aggregations

FrameCounter (uk.ac.sussex.gdsc.smlm.results.count.FrameCounter)20 MemoryPeakResults (uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults)19 PeakResult (uk.ac.sussex.gdsc.smlm.results.PeakResult)19 List (java.util.List)16 PeakResultProcedure (uk.ac.sussex.gdsc.smlm.results.procedures.PeakResultProcedure)15 Counter (uk.ac.sussex.gdsc.smlm.results.count.Counter)14 Nullable (uk.ac.sussex.gdsc.core.annotation.Nullable)12 ClassificationResult (uk.ac.sussex.gdsc.core.match.ClassificationResult)12 FractionClassificationResult (uk.ac.sussex.gdsc.core.match.FractionClassificationResult)12 SimpleArrayUtils (uk.ac.sussex.gdsc.core.utils.SimpleArrayUtils)12 Chromosome (uk.ac.sussex.gdsc.smlm.ga.Chromosome)12 XStreamOmitField (com.thoughtworks.xstream.annotations.XStreamOmitField)11 IJ (ij.IJ)6 AtomicReference (java.util.concurrent.atomic.AtomicReference)6 ImageJUtils (uk.ac.sussex.gdsc.core.ij.ImageJUtils)6 ExtendedGenericDialog (uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog)6 LocalList (uk.ac.sussex.gdsc.core.utils.LocalList)6 TextUtils (uk.ac.sussex.gdsc.core.utils.TextUtils)6 Prefs (ij.Prefs)5 PlugIn (ij.plugin.PlugIn)5