Search in sources :

Example 16 with WindowOrganiser

use of uk.ac.sussex.gdsc.core.ij.plugin.WindowOrganiser in project GDSC-SMLM by aherbert.

the class CameraModelFisherInformationAnalysis method analyse.

private void analyse() {
    final CameraType type1 = CameraType.forNumber(settings.getCamera1Type());
    final CameraType type2 = CameraType.forNumber(settings.getCamera2Type());
    final FiKey key1 = new FiKey(type1, settings.getCamera1Gain(), settings.getCamera1Noise());
    final FiKey key2 = new FiKey(type2, settings.getCamera2Gain(), settings.getCamera2Noise());
    final BasePoissonFisherInformation f1 = createPoissonFisherInformation(key1);
    if (f1 == null) {
        return;
    }
    final BasePoissonFisherInformation f2 = createPoissonFisherInformation(key2);
    if (f2 == null) {
        return;
    }
    final double[] exp = createExponents();
    if (exp == null) {
        return;
    }
    final double[] photons = new double[exp.length];
    for (int i = 0; i < photons.length; i++) {
        photons[i] = Math.pow(10, exp[i]);
    }
    // Get the alpha.
    // This may be from the cache or computed shutdown the executor if it was created.
    double[] alpha1;
    double[] alpha2;
    try {
        alpha1 = getAlpha(photons, exp, f1, key1);
        alpha2 = getAlpha(photons, exp, f2, key2);
    } finally {
        if (es != null) {
            es.shutdownNow();
        }
    }
    // Compute the Poisson Fisher information
    final double[] fi1 = getFisherInformation(alpha1, photons);
    final double[] fi2 = getFisherInformation(alpha2, photons);
    // ==============
    if (debug && f2 instanceof PoissonGammaGaussianFisherInformation) {
        final PoissonGammaGaussianFisherInformation pgg = (PoissonGammaGaussianFisherInformation) f2;
        final double t = 200;
        final double fi = pgg.getFisherInformation(t);
        final double alpha = fi * t;
        final double[][] data1 = pgg.getFisherInformationFunction(false);
        final double[][] data2 = pgg.getFisherInformationFunction(true);
        final double[] fif = data1[1];
        int max = 0;
        for (int j = 1; j < fif.length; j++) {
            if (fif[max] < fif[j]) {
                max = j;
            }
        }
        ImageJUtils.log("PGG(p=%g) max=%g", t, data1[0][max]);
        final String title = TITLE + " photons=" + MathUtils.rounded(t) + " alpha=" + MathUtils.rounded(alpha);
        final Plot plot = new Plot(title, "Count", "FI function");
        double yMax = MathUtils.max(data1[1]);
        yMax = MathUtils.maxDefault(yMax, data2[1]);
        plot.setLimits(data2[0][0], data2[0][data2[0].length - 1], 0, yMax);
        plot.setColor(Color.red);
        plot.addPoints(data1[0], data1[1], Plot.LINE);
        plot.setColor(Color.blue);
        plot.addPoints(data2[0], data2[1], Plot.LINE);
        ImageJUtils.display(title, plot);
    }
    // ==============
    final Color color1 = Color.BLUE;
    final Color color2 = Color.RED;
    final WindowOrganiser wo = new WindowOrganiser();
    // Test if we can use ImageJ support for a X log scale
    final boolean logScaleX = ((float) photons[0] != 0);
    final double[] x = (logScaleX) ? photons : exp;
    final String xTitle = (logScaleX) ? "photons" : "log10(photons)";
    // Get interpolation for alpha. Convert to base e.
    final double[] logU = exp.clone();
    final double scale = Math.log(10);
    for (int i = 0; i < logU.length; i++) {
        logU[i] *= scale;
    }
    final BasePoissonFisherInformation if1 = getInterpolatedPoissonFisherInformation(type1, logU, alpha1, f1);
    final BasePoissonFisherInformation if2 = getInterpolatedPoissonFisherInformation(type2, logU, alpha2, f2);
    // Interpolate with 5 points per sample for smooth curve
    final int n = 5 * exp.length;
    final double[] iexp = new double[n + 1];
    final double[] iphotons = new double[iexp.length];
    final double h = (exp[exp.length - 1] - exp[0]) / n;
    for (int i = 0; i <= n; i++) {
        iexp[i] = exp[0] + i * h;
        iphotons[i] = Math.pow(10, iexp[i]);
    }
    final double[] ix = (logScaleX) ? iphotons : iexp;
    final double[] ialpha1 = getAlpha(if1, iphotons);
    final double[] ialpha2 = getAlpha(if2, iphotons);
    final int pointShape = getPointShape(settings.getPointOption());
    final String name1 = getName(key1);
    final String name2 = getName(key2);
    final String legend = name1 + "\n" + name2;
    String title = "Relative Fisher Information";
    Plot plot = new Plot(title, xTitle, "Noise coefficient (alpha)");
    plot.setLimits(x[0], x[x.length - 1], -0.05, 1.05);
    if (logScaleX) {
        plot.setLogScaleX();
    }
    plot.setColor(color1);
    plot.addPoints(ix, ialpha1, Plot.LINE);
    plot.setColor(color2);
    plot.addPoints(ix, ialpha2, Plot.LINE);
    plot.setColor(Color.BLACK);
    plot.addLegend(legend);
    // Option to show nodes
    if (pointShape != -1) {
        plot.setColor(color1);
        plot.addPoints(x, alpha1, pointShape);
        plot.setColor(color2);
        plot.addPoints(x, alpha2, pointShape);
        plot.setColor(Color.BLACK);
    }
    ImageJUtils.display(title, plot, 0, wo);
    // The approximation should not produce an infinite computation
    double[] limits = new double[] { fi2[fi2.length - 1], fi2[fi2.length - 1] };
    limits = limits(limits, fi1);
    limits = limits(limits, fi2);
    // Check if we can use ImageJ support for a Y log scale
    final boolean logScaleY = ((float) limits[1] <= Float.MAX_VALUE);
    if (!logScaleY) {
        for (int i = 0; i < fi1.length; i++) {
            fi1[i] = Math.log10(fi1[i]);
            fi2[i] = Math.log10(fi2[i]);
        }
        limits[0] = Math.log10(limits[0]);
        limits[1] = Math.log10(limits[1]);
    }
    final String yTitle = (logScaleY) ? "Fisher Information" : "log10(Fisher Information)";
    title = "Fisher Information";
    plot = new Plot(title, xTitle, yTitle);
    plot.setLimits(x[0], x[x.length - 1], limits[0], limits[1]);
    if (logScaleX) {
        plot.setLogScaleX();
    }
    if (logScaleY) {
        plot.setLogScaleY();
    }
    plot.setColor(color1);
    plot.addPoints(x, fi1, Plot.LINE);
    plot.setColor(color2);
    plot.addPoints(x, fi2, Plot.LINE);
    plot.setColor(Color.BLACK);
    plot.addLegend(legend);
    // // Option to show nodes
    // This gets messy as the lines are straight
    // if (pointShape != -1)
    // {
    // plot.setColor(color1);
    // plot.addPoints(x, pgFI, pointShape);
    // plot.setColor(color3);
    // plot.addPoints(x, pggFI, pointShape);
    // plot.setColor(Color.BLACK);
    // }
    ImageJUtils.display(title, plot, 0, wo);
    wo.tile();
}
Also used : Plot(ij.gui.Plot) Color(java.awt.Color) WindowOrganiser(uk.ac.sussex.gdsc.core.ij.plugin.WindowOrganiser) BasePoissonFisherInformation(uk.ac.sussex.gdsc.smlm.function.BasePoissonFisherInformation) PoissonGammaGaussianFisherInformation(uk.ac.sussex.gdsc.smlm.function.PoissonGammaGaussianFisherInformation)

Example 17 with WindowOrganiser

use of uk.ac.sussex.gdsc.core.ij.plugin.WindowOrganiser 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 18 with WindowOrganiser

use of uk.ac.sussex.gdsc.core.ij.plugin.WindowOrganiser in project GDSC-SMLM by aherbert.

the class AstigmatismModelManager method plotData.

private boolean plotData() {
    if (results.size() <= imp.getStackSize() / 2) {
        IJ.error(TITLE, "Not enough fit results " + results.size());
        return false;
    }
    final double umPerSlice = pluginSettings.getNmPerSlice() / 1000.0;
    // final double nmPerPixel = results.getNmPerPixel();
    z = new double[results.size()];
    x = new double[z.length];
    y = new double[z.length];
    intensity = new double[z.length];
    final Counter counter = new Counter();
    // We have fit the results so they will be in the preferred units
    results.forEach(new PeakResultProcedure() {

        @Override
        public void execute(PeakResult peak) {
            final int i = counter.getAndIncrement();
            z[i] = peak.getFrame() * umPerSlice;
            x[i] = (peak.getXPosition() - cx);
            y[i] = (peak.getYPosition() - cy);
            intensity[i] = peak.getIntensity();
        }
    });
    final WidthResultProcedure wp = new WidthResultProcedure(results, DistanceUnit.PIXEL);
    wp.getWxWy();
    sx = SimpleArrayUtils.toDouble(wp.wx);
    sy = SimpleArrayUtils.toDouble(wp.wy);
    final WindowOrganiser wo = new WindowOrganiser();
    plot(wo, z, "Intensity (photon)", intensity, "Intensity", null, null);
    xyPlot = plot(wo, z, "Position (px)", x, "X", y, "Y");
    widthPlot = plot(wo, z, "Width (px)", sx, "Sx", sy, "Sy");
    wo.tile();
    return true;
}
Also used : Counter(uk.ac.sussex.gdsc.smlm.results.count.Counter) PeakResultProcedure(uk.ac.sussex.gdsc.smlm.results.procedures.PeakResultProcedure) WidthResultProcedure(uk.ac.sussex.gdsc.smlm.results.procedures.WidthResultProcedure) WindowOrganiser(uk.ac.sussex.gdsc.core.ij.plugin.WindowOrganiser) PeakResult(uk.ac.sussex.gdsc.smlm.results.PeakResult)

Example 19 with WindowOrganiser

use of uk.ac.sussex.gdsc.core.ij.plugin.WindowOrganiser in project GDSC-SMLM by aherbert.

the class BenchmarkSpotFit method summariseResults.

private void summariseResults(BenchmarkSpotFitResult spotFitResults, long runTime, final PreprocessedPeakResult[] preprocessedPeakResults, int uniqueIdCount, CandidateData candidateData, TIntObjectHashMap<List<Coordinate>> actualCoordinates) {
    // Summarise the fitting results. N fits, N failures.
    // Optimal match statistics if filtering is perfect (since fitting is not perfect).
    final StoredDataStatistics distanceStats = new StoredDataStatistics();
    final StoredDataStatistics depthStats = new StoredDataStatistics();
    // Get stats for all fitted results and those that match
    // Signal, SNR, Width, xShift, yShift, Precision
    createFilterCriteria();
    final StoredDataStatistics[][] stats = new StoredDataStatistics[3][filterCriteria.length];
    for (int i = 0; i < stats.length; i++) {
        for (int j = 0; j < stats[i].length; j++) {
            stats[i][j] = new StoredDataStatistics();
        }
    }
    final double nmPerPixel = simulationParameters.pixelPitch;
    double tp = 0;
    double fp = 0;
    int failCtp = 0;
    int failCfp = 0;
    int ctp = 0;
    int cfp = 0;
    final int[] singleStatus = new int[FitStatus.values().length];
    final int[] multiStatus = new int[singleStatus.length];
    final int[] doubletStatus = new int[singleStatus.length];
    final int[] multiDoubletStatus = new int[singleStatus.length];
    // Easier to materialise the values since we have a lot of non final variables to manipulate
    final TIntObjectHashMap<FilterCandidates> fitResults = spotFitResults.fitResults;
    final int[] frames = new int[fitResults.size()];
    final FilterCandidates[] candidates = new FilterCandidates[fitResults.size()];
    final int[] counter = new int[1];
    fitResults.forEachEntry((frame, candidate) -> {
        frames[counter[0]] = frame;
        candidates[counter[0]] = candidate;
        counter[0]++;
        return true;
    });
    for (final FilterCandidates result : candidates) {
        // Count the number of fit results that matched (tp) and did not match (fp)
        tp += result.tp;
        fp += result.fp;
        for (int i = 0; i < result.fitResult.length; i++) {
            if (result.spots[i].match) {
                ctp++;
            } else {
                cfp++;
            }
            final MultiPathFitResult fitResult = result.fitResult[i];
            if (singleStatus != null && result.spots[i].match) {
                // Debugging reasons for fit failure
                addStatus(singleStatus, fitResult.getSingleFitResult());
                addStatus(multiStatus, fitResult.getMultiFitResult());
                addStatus(doubletStatus, fitResult.getDoubletFitResult());
                addStatus(multiDoubletStatus, fitResult.getMultiDoubletFitResult());
            }
            if (noMatch(fitResult)) {
                if (result.spots[i].match) {
                    failCtp++;
                } else {
                    failCfp++;
                }
            }
            // We have multi-path results.
            // We want statistics for:
            // [0] all fitted spots
            // [1] fitted spots that match a result
            // [2] fitted spots that do not match a result
            addToStats(fitResult.getSingleFitResult(), stats);
            addToStats(fitResult.getMultiFitResult(), stats);
            addToStats(fitResult.getDoubletFitResult(), stats);
            addToStats(fitResult.getMultiDoubletFitResult(), stats);
        }
        // Statistics on spots that fit an actual result
        for (int i = 0; i < result.match.length; i++) {
            if (!result.match[i].isFitResult()) {
                // For now just ignore the candidates that matched
                continue;
            }
            final FitMatch fitMatch = (FitMatch) result.match[i];
            distanceStats.add(fitMatch.distance * nmPerPixel);
            depthStats.add(fitMatch.zdepth * nmPerPixel);
        }
    }
    if (tp == 0) {
        IJ.error(TITLE, "No fit results matched the simulation actual results");
        return;
    }
    // Store data for computing correlation
    final double[] i1 = new double[depthStats.getN()];
    final double[] i2 = new double[i1.length];
    final double[] is = new double[i1.length];
    int ci = 0;
    for (final FilterCandidates result : candidates) {
        for (int i = 0; i < result.match.length; i++) {
            if (!result.match[i].isFitResult()) {
                // For now just ignore the candidates that matched
                continue;
            }
            final FitMatch fitMatch = (FitMatch) result.match[i];
            final ScoredSpot spot = result.spots[fitMatch.index];
            i1[ci] = fitMatch.predictedSignal;
            i2[ci] = fitMatch.actualSignal;
            is[ci] = spot.spot.intensity;
            ci++;
        }
    }
    // We want to compute the Jaccard against the spot metric
    // Filter the results using the multi-path filter
    final ArrayList<MultiPathFitResults> multiPathResults = new ArrayList<>(fitResults.size());
    for (int i = 0; i < frames.length; i++) {
        final int frame = frames[i];
        final MultiPathFitResult[] multiPathFitResults = candidates[i].fitResult;
        final int totalCandidates = candidates[i].spots.length;
        final List<Coordinate> list = actualCoordinates.get(frame);
        final int nActual = (list == null) ? 0 : list.size();
        multiPathResults.add(new MultiPathFitResults(frame, multiPathFitResults, totalCandidates, nActual));
    }
    // Score the results and count the number returned
    final List<FractionalAssignment[]> assignments = new ArrayList<>();
    final TIntHashSet set = new TIntHashSet(uniqueIdCount);
    final FractionScoreStore scoreStore = set::add;
    final MultiPathFitResults[] multiResults = multiPathResults.toArray(new MultiPathFitResults[0]);
    // Filter with no filter
    final MultiPathFilter mpf = new MultiPathFilter(new SignalFilter(0), null, multiFilter.residualsThreshold);
    mpf.fractionScoreSubset(multiResults, NullFailCounter.INSTANCE, this.results.size(), assignments, scoreStore, CoordinateStoreFactory.create(0, 0, imp.getWidth(), imp.getHeight(), config.convertUsingHwhMax(config.getDuplicateDistanceParameter())));
    final double[][] matchScores = new double[set.size()][];
    int count = 0;
    for (int i = 0; i < assignments.size(); i++) {
        final FractionalAssignment[] a = assignments.get(i);
        if (a == null) {
            continue;
        }
        for (int j = 0; j < a.length; j++) {
            final PreprocessedPeakResult r = ((PeakFractionalAssignment) a[j]).peakResult;
            set.remove(r.getUniqueId());
            final double precision = Math.sqrt(r.getLocationVariance());
            final double signal = r.getSignal();
            final double snr = r.getSnr();
            final double width = r.getXSdFactor();
            final double xShift = r.getXRelativeShift2();
            final double yShift = r.getYRelativeShift2();
            // Since these two are combined for filtering and the max is what matters.
            final double shift = (xShift > yShift) ? Math.sqrt(xShift) : Math.sqrt(yShift);
            final double eshift = Math.sqrt(xShift + yShift);
            final double[] score = new double[8];
            score[FILTER_SIGNAL] = signal;
            score[FILTER_SNR] = snr;
            score[FILTER_MIN_WIDTH] = width;
            score[FILTER_MAX_WIDTH] = width;
            score[FILTER_SHIFT] = shift;
            score[FILTER_ESHIFT] = eshift;
            score[FILTER_PRECISION] = precision;
            score[FILTER_PRECISION + 1] = a[j].getScore();
            matchScores[count++] = score;
        }
    }
    // Add the rest
    set.forEach(new CustomTIntProcedure(count) {

        @Override
        public boolean execute(int uniqueId) {
            // This should not be null or something has gone wrong
            final PreprocessedPeakResult r = preprocessedPeakResults[uniqueId];
            if (r == null) {
                throw new IllegalArgumentException("Missing result: " + uniqueId);
            }
            final double precision = Math.sqrt(r.getLocationVariance());
            final double signal = r.getSignal();
            final double snr = r.getSnr();
            final double width = r.getXSdFactor();
            final double xShift = r.getXRelativeShift2();
            final double yShift = r.getYRelativeShift2();
            // Since these two are combined for filtering and the max is what matters.
            final double shift = (xShift > yShift) ? Math.sqrt(xShift) : Math.sqrt(yShift);
            final double eshift = Math.sqrt(xShift + yShift);
            final double[] score = new double[8];
            score[FILTER_SIGNAL] = signal;
            score[FILTER_SNR] = snr;
            score[FILTER_MIN_WIDTH] = width;
            score[FILTER_MAX_WIDTH] = width;
            score[FILTER_SHIFT] = shift;
            score[FILTER_ESHIFT] = eshift;
            score[FILTER_PRECISION] = precision;
            matchScores[count++] = score;
            return true;
        }
    });
    final FitConfiguration fitConfig = config.getFitConfiguration();
    // Debug the reasons the fit failed
    if (singleStatus != null) {
        String name = PeakFit.getSolverName(fitConfig);
        if (fitConfig.getFitSolver() == FitSolver.MLE && fitConfig.isModelCamera()) {
            name += " Camera";
        }
        IJ.log("Failure counts: " + name);
        printFailures("Single", singleStatus);
        printFailures("Multi", multiStatus);
        printFailures("Doublet", doubletStatus);
        printFailures("Multi doublet", multiDoubletStatus);
    }
    final StringBuilder sb = new StringBuilder(300);
    // Add information about the simulation
    final double signal = simulationParameters.averageSignal;
    final int n = results.size();
    sb.append(imp.getStackSize()).append('\t');
    final int w = imp.getWidth();
    final int h = imp.getHeight();
    sb.append(w).append('\t');
    sb.append(h).append('\t');
    sb.append(n).append('\t');
    final double density = ((double) n / imp.getStackSize()) / (w * h) / (simulationParameters.pixelPitch * simulationParameters.pixelPitch / 1e6);
    sb.append(MathUtils.rounded(density)).append('\t');
    sb.append(MathUtils.rounded(signal)).append('\t');
    sb.append(MathUtils.rounded(simulationParameters.sd)).append('\t');
    sb.append(MathUtils.rounded(simulationParameters.pixelPitch)).append('\t');
    sb.append(MathUtils.rounded(simulationParameters.depth)).append('\t');
    sb.append(simulationParameters.fixedDepth).append('\t');
    sb.append(MathUtils.rounded(simulationParameters.gain)).append('\t');
    sb.append(MathUtils.rounded(simulationParameters.readNoise)).append('\t');
    sb.append(MathUtils.rounded(simulationParameters.background)).append('\t');
    sb.append(MathUtils.rounded(simulationParameters.noise)).append('\t');
    if (simulationParameters.fullSimulation) {
    // The total signal is spread over frames
    }
    sb.append(MathUtils.rounded(signal / simulationParameters.noise)).append('\t');
    sb.append(MathUtils.rounded(simulationParameters.sd / simulationParameters.pixelPitch)).append('\t');
    sb.append(spotFilter.getDescription());
    // nP and nN is the fractional score of the spot candidates
    addCount(sb, (double) candidateData.countPositive + candidateData.countNegative);
    addCount(sb, candidateData.countPositive);
    addCount(sb, candidateData.countNegative);
    addCount(sb, candidateData.fractionPositive);
    addCount(sb, candidateData.fractionNegative);
    String name = PeakFit.getSolverName(fitConfig);
    if (fitConfig.getFitSolver() == FitSolver.MLE && fitConfig.isModelCamera()) {
        name += " Camera";
    }
    add(sb, name);
    add(sb, config.getFitting());
    spotFitResults.resultPrefix = sb.toString();
    // Q. Should I add other fit configuration here?
    // The fraction of positive and negative candidates that were included
    add(sb, (100.0 * ctp) / candidateData.countPositive);
    add(sb, (100.0 * cfp) / candidateData.countNegative);
    // Score the fitting results compared to the original simulation.
    // Score the candidate selection:
    add(sb, ctp + cfp);
    add(sb, ctp);
    add(sb, cfp);
    // TP are all candidates that can be matched to a spot
    // FP are all candidates that cannot be matched to a spot
    // FN = The number of missed spots
    FractionClassificationResult match = new FractionClassificationResult(ctp, cfp, 0, simulationParameters.molecules - ctp);
    add(sb, match.getRecall());
    add(sb, match.getPrecision());
    add(sb, match.getF1Score());
    add(sb, match.getJaccard());
    // Score the fitting results:
    add(sb, failCtp);
    add(sb, failCfp);
    // TP are all fit results that can be matched to a spot
    // FP are all fit results that cannot be matched to a spot
    // FN = The number of missed spots
    add(sb, tp);
    add(sb, fp);
    match = new FractionClassificationResult(tp, fp, 0, simulationParameters.molecules - tp);
    add(sb, match.getRecall());
    add(sb, match.getPrecision());
    add(sb, match.getF1Score());
    add(sb, match.getJaccard());
    // Do it again but pretend we can perfectly filter all the false positives
    // add(sb, tp);
    match = new FractionClassificationResult(tp, 0, 0, simulationParameters.molecules - tp);
    // Recall is unchanged
    // Precision will be 100%
    add(sb, match.getF1Score());
    add(sb, match.getJaccard());
    // The mean may be subject to extreme outliers so use the median
    double median = distanceStats.getMedian();
    add(sb, median);
    final WindowOrganiser wo = new WindowOrganiser();
    String label = String.format("Recall = %s. n = %d. Median = %s nm. SD = %s nm", MathUtils.rounded(match.getRecall()), distanceStats.getN(), MathUtils.rounded(median), MathUtils.rounded(distanceStats.getStandardDeviation()));
    new HistogramPlotBuilder(TITLE, distanceStats, "Match Distance (nm)").setPlotLabel(label).show(wo);
    median = depthStats.getMedian();
    add(sb, median);
    // Sort by spot intensity and produce correlation
    double[] correlation = null;
    double[] rankCorrelation = null;
    double[] rank = null;
    final FastCorrelator fastCorrelator = new FastCorrelator();
    final ArrayList<Ranking> pc1 = new ArrayList<>();
    final ArrayList<Ranking> pc2 = new ArrayList<>();
    ci = 0;
    if (settings.showCorrelation) {
        final int[] indices = SimpleArrayUtils.natural(i1.length);
        SortUtils.sortData(indices, is, settings.rankByIntensity, true);
        correlation = new double[i1.length];
        rankCorrelation = new double[i1.length];
        rank = new double[i1.length];
        for (final int ci2 : indices) {
            fastCorrelator.add(Math.round(i1[ci2]), Math.round(i2[ci2]));
            pc1.add(new Ranking(i1[ci2], ci));
            pc2.add(new Ranking(i2[ci2], ci));
            correlation[ci] = fastCorrelator.getCorrelation();
            rankCorrelation[ci] = Correlator.correlation(rank(pc1), rank(pc2));
            if (settings.rankByIntensity) {
                rank[ci] = is[0] - is[ci];
            } else {
                rank[ci] = ci;
            }
            ci++;
        }
    } else {
        for (int i = 0; i < i1.length; i++) {
            fastCorrelator.add(Math.round(i1[i]), Math.round(i2[i]));
            pc1.add(new Ranking(i1[i], i));
            pc2.add(new Ranking(i2[i], i));
        }
    }
    final double pearsonCorr = fastCorrelator.getCorrelation();
    final double rankedCorr = Correlator.correlation(rank(pc1), rank(pc2));
    // Get the regression
    final SimpleRegression regression = new SimpleRegression(false);
    for (int i = 0; i < pc1.size(); i++) {
        regression.addData(pc1.get(i).value, pc2.get(i).value);
    }
    // final double intercept = regression.getIntercept();
    final double slope = regression.getSlope();
    if (settings.showCorrelation) {
        String title = TITLE + " Intensity";
        Plot plot = new Plot(title, "Candidate", "Spot");
        final double[] limits1 = MathUtils.limits(i1);
        final double[] limits2 = MathUtils.limits(i2);
        plot.setLimits(limits1[0], limits1[1], limits2[0], limits2[1]);
        label = String.format("Correlation=%s; Ranked=%s; Slope=%s", MathUtils.rounded(pearsonCorr), MathUtils.rounded(rankedCorr), MathUtils.rounded(slope));
        plot.addLabel(0, 0, label);
        plot.setColor(Color.red);
        plot.addPoints(i1, i2, Plot.DOT);
        if (slope > 1) {
            plot.drawLine(limits1[0], limits1[0] * slope, limits1[1], limits1[1] * slope);
        } else {
            plot.drawLine(limits2[0] / slope, limits2[0], limits2[1] / slope, limits2[1]);
        }
        ImageJUtils.display(title, plot, wo);
        title = TITLE + " Correlation";
        plot = new Plot(title, "Spot Rank", "Correlation");
        final double[] xlimits = MathUtils.limits(rank);
        double[] ylimits = MathUtils.limits(correlation);
        ylimits = MathUtils.limits(ylimits, rankCorrelation);
        plot.setLimits(xlimits[0], xlimits[1], ylimits[0], ylimits[1]);
        plot.setColor(Color.red);
        plot.addPoints(rank, correlation, Plot.LINE);
        plot.setColor(Color.blue);
        plot.addPoints(rank, rankCorrelation, Plot.LINE);
        plot.setColor(Color.black);
        plot.addLabel(0, 0, label);
        ImageJUtils.display(title, plot, wo);
    }
    add(sb, pearsonCorr);
    add(sb, rankedCorr);
    add(sb, slope);
    label = String.format("n = %d. Median = %s nm", depthStats.getN(), MathUtils.rounded(median));
    new HistogramPlotBuilder(TITLE, depthStats, "Match Depth (nm)").setRemoveOutliersOption(1).setPlotLabel(label).show(wo);
    // Plot histograms of the stats on the same window
    final double[] lower = new double[filterCriteria.length];
    final double[] upper = new double[lower.length];
    final double[] min = new double[lower.length];
    final double[] max = new double[lower.length];
    for (int i = 0; i < stats[0].length; i++) {
        final double[] limits = showDoubleHistogram(stats, i, wo, matchScores);
        lower[i] = limits[0];
        upper[i] = limits[1];
        min[i] = limits[2];
        max[i] = limits[3];
    }
    // Reconfigure some of the range limits
    // Make this a bit bigger
    upper[FILTER_SIGNAL] *= 2;
    // Make this a bit bigger
    upper[FILTER_SNR] *= 2;
    final double factor = 0.25;
    if (lower[FILTER_MIN_WIDTH] != 0) {
        // (assuming lower is less than 1)
        upper[FILTER_MIN_WIDTH] = 1 - Math.max(0, factor * (1 - lower[FILTER_MIN_WIDTH]));
    }
    if (upper[FILTER_MIN_WIDTH] != 0) {
        // (assuming upper is more than 1)
        lower[FILTER_MAX_WIDTH] = 1 + Math.max(0, factor * (upper[FILTER_MAX_WIDTH] - 1));
    }
    // Round the ranges
    final double[] interval = new double[stats[0].length];
    interval[FILTER_SIGNAL] = SignalFilter.DEFAULT_INCREMENT;
    interval[FILTER_SNR] = SnrFilter.DEFAULT_INCREMENT;
    interval[FILTER_MIN_WIDTH] = WidthFilter2.DEFAULT_MIN_INCREMENT;
    interval[FILTER_MAX_WIDTH] = WidthFilter.DEFAULT_INCREMENT;
    interval[FILTER_SHIFT] = ShiftFilter.DEFAULT_INCREMENT;
    interval[FILTER_ESHIFT] = EShiftFilter.DEFAULT_INCREMENT;
    interval[FILTER_PRECISION] = PrecisionFilter.DEFAULT_INCREMENT;
    interval[FILTER_ITERATIONS] = 0.1;
    interval[FILTER_EVALUATIONS] = 0.1;
    // Create a range increment
    final double[] increment = new double[lower.length];
    for (int i = 0; i < increment.length; i++) {
        lower[i] = MathUtils.floor(lower[i], interval[i]);
        upper[i] = MathUtils.ceil(upper[i], interval[i]);
        final double range = upper[i] - lower[i];
        // Allow clipping if the range is small compared to the min increment
        double multiples = range / interval[i];
        // Use 8 multiples for the equivalent of +/- 4 steps around the centre
        if (multiples < 8) {
            multiples = Math.ceil(multiples);
        } else {
            multiples = 8;
        }
        increment[i] = MathUtils.ceil(range / multiples, interval[i]);
        if (i == FILTER_MIN_WIDTH) {
            // Requires clipping based on the upper limit
            lower[i] = upper[i] - increment[i] * multiples;
        } else {
            upper[i] = lower[i] + increment[i] * multiples;
        }
    }
    for (int i = 0; i < stats[0].length; i++) {
        lower[i] = MathUtils.round(lower[i]);
        upper[i] = MathUtils.round(upper[i]);
        min[i] = MathUtils.round(min[i]);
        max[i] = MathUtils.round(max[i]);
        increment[i] = MathUtils.round(increment[i]);
        sb.append('\t').append(min[i]).append(':').append(lower[i]).append('-').append(upper[i]).append(':').append(max[i]);
    }
    // Disable some filters
    increment[FILTER_SIGNAL] = Double.POSITIVE_INFINITY;
    // increment[FILTER_SHIFT] = Double.POSITIVE_INFINITY;
    increment[FILTER_ESHIFT] = Double.POSITIVE_INFINITY;
    wo.tile();
    sb.append('\t').append(TextUtils.nanosToString(runTime));
    createTable().append(sb.toString());
    if (settings.saveFilterRange) {
        GUIFilterSettings filterSettings = SettingsManager.readGuiFilterSettings(0);
        String filename = (silent) ? filterSettings.getFilterSetFilename() : ImageJUtils.getFilename("Filter_range_file", filterSettings.getFilterSetFilename());
        if (filename == null) {
            return;
        }
        // Remove extension to store the filename
        filename = FileUtils.replaceExtension(filename, ".xml");
        filterSettings = filterSettings.toBuilder().setFilterSetFilename(filename).build();
        // Create a filter set using the ranges
        final ArrayList<Filter> filters = new ArrayList<>(4);
        // Create the multi-filter using the same precision type as that used during fitting.
        // Currently no support for z-filter as 3D astigmatism fitting is experimental.
        final PrecisionMethod precisionMethod = getPrecisionMethod((DirectFilter) multiFilter.getFilter());
        Function<double[], Filter> generator;
        if (precisionMethod == PrecisionMethod.POISSON_CRLB) {
            generator = parameters -> new MultiFilterCrlb(parameters[FILTER_SIGNAL], (float) parameters[FILTER_SNR], parameters[FILTER_MIN_WIDTH], parameters[FILTER_MAX_WIDTH], parameters[FILTER_SHIFT], parameters[FILTER_ESHIFT], parameters[FILTER_PRECISION], 0f, 0f);
        } else if (precisionMethod == PrecisionMethod.MORTENSEN) {
            generator = parameters -> new MultiFilter(parameters[FILTER_SIGNAL], (float) parameters[FILTER_SNR], parameters[FILTER_MIN_WIDTH], parameters[FILTER_MAX_WIDTH], parameters[FILTER_SHIFT], parameters[FILTER_ESHIFT], parameters[FILTER_PRECISION], 0f, 0f);
        } else {
            // Default
            generator = parameters -> new MultiFilter2(parameters[FILTER_SIGNAL], (float) parameters[FILTER_SNR], parameters[FILTER_MIN_WIDTH], parameters[FILTER_MAX_WIDTH], parameters[FILTER_SHIFT], parameters[FILTER_ESHIFT], parameters[FILTER_PRECISION], 0f, 0f);
        }
        filters.add(generator.apply(lower));
        filters.add(generator.apply(upper));
        filters.add(generator.apply(increment));
        if (saveFilters(filename, filters)) {
            SettingsManager.writeSettings(filterSettings);
        }
        // Create a filter set using the min/max and the initial bounds.
        // Set sensible limits
        min[FILTER_SIGNAL] = Math.max(min[FILTER_SIGNAL], 30);
        max[FILTER_SNR] = Math.min(max[FILTER_SNR], 10000);
        max[FILTER_PRECISION] = Math.min(max[FILTER_PRECISION], 100);
        // Make the 4-set filters the same as the 3-set filters.
        filters.clear();
        filters.add(generator.apply(min));
        filters.add(generator.apply(lower));
        filters.add(generator.apply(upper));
        filters.add(generator.apply(max));
        saveFilters(FileUtils.replaceExtension(filename, ".4.xml"), filters);
    }
    spotFitResults.min = min;
    spotFitResults.max = max;
}
Also used : Color(java.awt.Color) PeakResultPoint(uk.ac.sussex.gdsc.smlm.results.PeakResultPoint) Arrays(java.util.Arrays) CoordinateStoreFactory(uk.ac.sussex.gdsc.smlm.results.filter.CoordinateStoreFactory) HistogramPlotBuilder(uk.ac.sussex.gdsc.core.ij.HistogramPlot.HistogramPlotBuilder) BasePreprocessedPeakResult(uk.ac.sussex.gdsc.smlm.results.filter.BasePreprocessedPeakResult) MultiPathFitResults(uk.ac.sussex.gdsc.smlm.results.filter.MultiPathFitResults) Filter(uk.ac.sussex.gdsc.smlm.results.filter.Filter) HelpUrls(uk.ac.sussex.gdsc.smlm.ij.plugins.HelpUrls) Pair(org.apache.commons.lang3.tuple.Pair) MemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults) FilterValidationFlag(uk.ac.sussex.gdsc.smlm.results.filter.FilterValidationFlag) FitProtosHelper(uk.ac.sussex.gdsc.smlm.data.config.FitProtosHelper) ImageJImageConverter(uk.ac.sussex.gdsc.smlm.ij.utils.ImageJImageConverter) PrecisionFilter(uk.ac.sussex.gdsc.smlm.results.filter.PrecisionFilter) WidthFilter2(uk.ac.sussex.gdsc.smlm.results.filter.WidthFilter2) LinearInterpolator(org.apache.commons.math3.analysis.interpolation.LinearInterpolator) BlockingQueue(java.util.concurrent.BlockingQueue) StopWatch(org.apache.commons.lang3.time.StopWatch) ConcurrencyUtils(uk.ac.sussex.gdsc.core.utils.concurrent.ConcurrencyUtils) MultiPathFitResult(uk.ac.sussex.gdsc.smlm.results.filter.MultiPathFitResult) TextUtils(uk.ac.sussex.gdsc.core.utils.TextUtils) Plot(ij.gui.Plot) PeakFit(uk.ac.sussex.gdsc.smlm.ij.plugins.PeakFit) TIntHashSet(gnu.trove.set.hash.TIntHashSet) ImagePlus(ij.ImagePlus) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) TextArea(java.awt.TextArea) PeakFractionalAssignment(uk.ac.sussex.gdsc.smlm.results.filter.PeakFractionalAssignment) XmlUtils(uk.ac.sussex.gdsc.core.utils.XmlUtils) ShiftFilter(uk.ac.sussex.gdsc.smlm.results.filter.ShiftFilter) FileUtils(uk.ac.sussex.gdsc.core.utils.FileUtils) PlugIn(ij.plugin.PlugIn) MultiPathFilter(uk.ac.sussex.gdsc.smlm.results.filter.MultiPathFilter) PolynomialSplineFunction(org.apache.commons.math3.analysis.polynomials.PolynomialSplineFunction) Prefs(ij.Prefs) TIntProcedure(gnu.trove.procedure.TIntProcedure) ArrayList(java.util.ArrayList) SortUtils(uk.ac.sussex.gdsc.core.utils.SortUtils) SignalFilter(uk.ac.sussex.gdsc.smlm.results.filter.SignalFilter) FitConfiguration(uk.ac.sussex.gdsc.smlm.engine.FitConfiguration) BenchmarkSpotFilterResult(uk.ac.sussex.gdsc.smlm.ij.plugins.benchmark.BenchmarkSpotFilter.BenchmarkSpotFilterResult) FitEngineConfigurationProvider(uk.ac.sussex.gdsc.smlm.ij.plugins.PeakFit.FitEngineConfigurationProvider) Assignment(uk.ac.sussex.gdsc.core.match.Assignment) FitWorker(uk.ac.sussex.gdsc.smlm.engine.FitWorker) MultiFilterCrlb(uk.ac.sussex.gdsc.smlm.results.filter.MultiFilterCrlb) FileOutputStream(java.io.FileOutputStream) FilterResult(uk.ac.sussex.gdsc.smlm.ij.plugins.benchmark.BenchmarkSpotFilter.FilterResult) FractionClassificationResult(uk.ac.sussex.gdsc.core.match.FractionClassificationResult) DirectFilter(uk.ac.sussex.gdsc.smlm.results.filter.DirectFilter) ResultsMatchCalculator(uk.ac.sussex.gdsc.smlm.ij.plugins.ResultsMatchCalculator) PreprocessedPeakResult(uk.ac.sussex.gdsc.smlm.results.filter.PreprocessedPeakResult) Percentile(org.apache.commons.math3.stat.descriptive.rank.Percentile) EShiftFilter(uk.ac.sussex.gdsc.smlm.results.filter.EShiftFilter) DescriptiveStatistics(org.apache.commons.math3.stat.descriptive.DescriptiveStatistics) ImageStack(ij.ImageStack) MaximaSpotFilter(uk.ac.sussex.gdsc.smlm.filters.MaximaSpotFilter) FitTask(uk.ac.sussex.gdsc.smlm.engine.FitParameters.FitTask) NullFailCounter(uk.ac.sussex.gdsc.smlm.results.count.NullFailCounter) FractionScoreStore(uk.ac.sussex.gdsc.smlm.results.filter.MultiPathFilter.FractionScoreStore) TIntObjectHashMap(gnu.trove.map.hash.TIntObjectHashMap) TextWindow(ij.text.TextWindow) Spot(uk.ac.sussex.gdsc.smlm.filters.Spot) ItemListener(java.awt.event.ItemListener) FitSolver(uk.ac.sussex.gdsc.smlm.data.config.FitProtos.FitSolver) ParameterType(uk.ac.sussex.gdsc.smlm.results.filter.ParameterType) StoredDataStatistics(uk.ac.sussex.gdsc.core.utils.StoredDataStatistics) OutOfRangeException(org.apache.commons.math3.exception.OutOfRangeException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AssignmentComparator(uk.ac.sussex.gdsc.core.match.AssignmentComparator) PeakResults(uk.ac.sussex.gdsc.smlm.results.PeakResults) ResultAssignment(uk.ac.sussex.gdsc.smlm.results.filter.ResultAssignment) PsfCalculator(uk.ac.sussex.gdsc.smlm.ij.plugins.PsfCalculator) PlotWindow(ij.gui.PlotWindow) MathUtils(uk.ac.sussex.gdsc.core.utils.MathUtils) FitParameters(uk.ac.sussex.gdsc.smlm.engine.FitParameters) SettingsManager(uk.ac.sussex.gdsc.smlm.ij.settings.SettingsManager) ItemEvent(java.awt.event.ItemEvent) BasePoint(uk.ac.sussex.gdsc.core.match.BasePoint) ExtendedGenericDialog(uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog) FitEngineConfiguration(uk.ac.sussex.gdsc.smlm.engine.FitEngineConfiguration) Coordinate(uk.ac.sussex.gdsc.core.match.Coordinate) FractionalAssignment(uk.ac.sussex.gdsc.core.match.FractionalAssignment) FilterXStreamUtils(uk.ac.sussex.gdsc.smlm.results.filter.FilterXStreamUtils) FitStatus(uk.ac.sussex.gdsc.smlm.fitting.FitStatus) List(java.util.List) PointPair(uk.ac.sussex.gdsc.core.match.PointPair) SimpleArrayUtils(uk.ac.sussex.gdsc.core.utils.SimpleArrayUtils) ParameterisedFitJob(uk.ac.sussex.gdsc.smlm.engine.ParameterisedFitJob) Rectangle(java.awt.Rectangle) FastCorrelator(uk.ac.sussex.gdsc.core.utils.FastCorrelator) PrecisionMethod(uk.ac.sussex.gdsc.smlm.data.config.FitProtos.PrecisionMethod) ImmutableFractionalAssignment(uk.ac.sussex.gdsc.core.match.ImmutableFractionalAssignment) MultiFilter(uk.ac.sussex.gdsc.smlm.results.filter.MultiFilter) WindowOrganiser(uk.ac.sussex.gdsc.core.ij.plugin.WindowOrganiser) ScoredSpot(uk.ac.sussex.gdsc.smlm.ij.plugins.benchmark.BenchmarkSpotFilter.ScoredSpot) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) TextField(java.awt.TextField) IJImageSource(uk.ac.sussex.gdsc.smlm.ij.IJImageSource) Correlator(uk.ac.sussex.gdsc.core.utils.Correlator) NoiseEstimatorMethod(uk.ac.sussex.gdsc.smlm.data.config.FitProtos.NoiseEstimatorMethod) LinkedList(java.util.LinkedList) ConcurrentRuntimeException(org.apache.commons.lang3.concurrent.ConcurrentRuntimeException) WidthFilter(uk.ac.sussex.gdsc.smlm.results.filter.WidthFilter) GUIFilterSettings(uk.ac.sussex.gdsc.smlm.ij.settings.GUIProtos.GUIFilterSettings) RampedScore(uk.ac.sussex.gdsc.core.utils.RampedScore) FitResult(uk.ac.sussex.gdsc.smlm.fitting.FitResult) Checkbox(java.awt.Checkbox) FilterSet(uk.ac.sussex.gdsc.smlm.results.filter.FilterSet) Ticker(uk.ac.sussex.gdsc.core.logging.Ticker) SnrFilter(uk.ac.sussex.gdsc.smlm.results.filter.SnrFilter) MultiFilter2(uk.ac.sussex.gdsc.smlm.results.filter.MultiFilter2) SimpleRegression(org.apache.commons.math3.stat.regression.SimpleRegression) HistogramPlot(uk.ac.sussex.gdsc.core.ij.HistogramPlot) ImageJUtils(uk.ac.sussex.gdsc.core.ij.ImageJUtils) SynchronizedPeakResults(uk.ac.sussex.gdsc.smlm.results.SynchronizedPeakResults) IJ(ij.IJ) SmlmUsageTracker(uk.ac.sussex.gdsc.smlm.ij.plugins.SmlmUsageTracker) Collections(java.util.Collections) ArrayList(java.util.ArrayList) HistogramPlotBuilder(uk.ac.sussex.gdsc.core.ij.HistogramPlot.HistogramPlotBuilder) PrecisionMethod(uk.ac.sussex.gdsc.smlm.data.config.FitProtos.PrecisionMethod) MultiPathFitResult(uk.ac.sussex.gdsc.smlm.results.filter.MultiPathFitResult) MultiFilterCrlb(uk.ac.sussex.gdsc.smlm.results.filter.MultiFilterCrlb) PeakFractionalAssignment(uk.ac.sussex.gdsc.smlm.results.filter.PeakFractionalAssignment) FractionalAssignment(uk.ac.sussex.gdsc.core.match.FractionalAssignment) ImmutableFractionalAssignment(uk.ac.sussex.gdsc.core.match.ImmutableFractionalAssignment) FractionClassificationResult(uk.ac.sussex.gdsc.core.match.FractionClassificationResult) BasePreprocessedPeakResult(uk.ac.sussex.gdsc.smlm.results.filter.BasePreprocessedPeakResult) PreprocessedPeakResult(uk.ac.sussex.gdsc.smlm.results.filter.PreprocessedPeakResult) ScoredSpot(uk.ac.sussex.gdsc.smlm.ij.plugins.benchmark.BenchmarkSpotFilter.ScoredSpot) FastCorrelator(uk.ac.sussex.gdsc.core.utils.FastCorrelator) Plot(ij.gui.Plot) HistogramPlot(uk.ac.sussex.gdsc.core.ij.HistogramPlot) StoredDataStatistics(uk.ac.sussex.gdsc.core.utils.StoredDataStatistics) Coordinate(uk.ac.sussex.gdsc.core.match.Coordinate) FitConfiguration(uk.ac.sussex.gdsc.smlm.engine.FitConfiguration) MultiPathFilter(uk.ac.sussex.gdsc.smlm.results.filter.MultiPathFilter) TIntHashSet(gnu.trove.set.hash.TIntHashSet) GUIFilterSettings(uk.ac.sussex.gdsc.smlm.ij.settings.GUIProtos.GUIFilterSettings) SignalFilter(uk.ac.sussex.gdsc.smlm.results.filter.SignalFilter) WindowOrganiser(uk.ac.sussex.gdsc.core.ij.plugin.WindowOrganiser) MultiFilter(uk.ac.sussex.gdsc.smlm.results.filter.MultiFilter) PeakResultPoint(uk.ac.sussex.gdsc.smlm.results.PeakResultPoint) BasePoint(uk.ac.sussex.gdsc.core.match.BasePoint) PeakFractionalAssignment(uk.ac.sussex.gdsc.smlm.results.filter.PeakFractionalAssignment) FractionScoreStore(uk.ac.sussex.gdsc.smlm.results.filter.MultiPathFilter.FractionScoreStore) SimpleRegression(org.apache.commons.math3.stat.regression.SimpleRegression) Filter(uk.ac.sussex.gdsc.smlm.results.filter.Filter) PrecisionFilter(uk.ac.sussex.gdsc.smlm.results.filter.PrecisionFilter) ShiftFilter(uk.ac.sussex.gdsc.smlm.results.filter.ShiftFilter) MultiPathFilter(uk.ac.sussex.gdsc.smlm.results.filter.MultiPathFilter) SignalFilter(uk.ac.sussex.gdsc.smlm.results.filter.SignalFilter) DirectFilter(uk.ac.sussex.gdsc.smlm.results.filter.DirectFilter) EShiftFilter(uk.ac.sussex.gdsc.smlm.results.filter.EShiftFilter) MaximaSpotFilter(uk.ac.sussex.gdsc.smlm.filters.MaximaSpotFilter) MultiFilter(uk.ac.sussex.gdsc.smlm.results.filter.MultiFilter) WidthFilter(uk.ac.sussex.gdsc.smlm.results.filter.WidthFilter) SnrFilter(uk.ac.sussex.gdsc.smlm.results.filter.SnrFilter) MultiFilter2(uk.ac.sussex.gdsc.smlm.results.filter.MultiFilter2) MultiPathFitResults(uk.ac.sussex.gdsc.smlm.results.filter.MultiPathFitResults)

Example 20 with WindowOrganiser

use of uk.ac.sussex.gdsc.core.ij.plugin.WindowOrganiser in project GDSC-SMLM by aherbert.

the class BenchmarkFilterAnalysis method saveTemplate.

/**
 * Save PeakFit configuration template using the current benchmark settings.
 *
 * @param topFilterSummary the top filter summary
 */
private void saveTemplate(String topFilterSummary) {
    final FitEngineConfiguration config = new FitEngineConfiguration();
    if (!updateAllConfiguration(config, true)) {
        IJ.log("Unable to create the template configuration");
        return;
    }
    // Remove the PSF width to make the template generic
    config.getFitConfiguration().setInitialPeakStdDev(0);
    // Only get this once when doing iterative analysis
    String filename;
    final boolean localSaveTemplateIsSet = saveTemplateIsSet;
    if (localSaveTemplateIsSet) {
        filename = settings.templateFilename;
    } else {
        filename = getFilename("Template_File", settings.templateFilename);
        saveTemplateIsSet = true;
    }
    if (filename != null) {
        settings.templateFilename = filename;
        Prefs.set(Settings.KEY_TEMPLATE_FILENAME, filename);
        final TemplateSettings.Builder templateSettings = TemplateSettings.newBuilder();
        getNotes(templateSettings, topFilterSummary);
        templateSettings.setFitEngineSettings(config.getFitEngineSettings());
        if (!SettingsManager.toJson(templateSettings.build(), filename, SettingsManager.FLAG_SILENT | SettingsManager.FLAG_JSON_WHITESPACE)) {
            IJ.log("Unable to save the template configuration");
            return;
        }
        // This need only be performed once as the sample image is the same for all iterations.
        if (localSaveTemplateIsSet) {
            return;
        }
        // Save some random frames from the test image data
        final ImagePlus imp = CreateData.getImage();
        if (imp == null) {
            return;
        }
        // Get the number of frames
        final ResultsImageSampler sampler = getSampler(results, imp);
        if (!sampler.isValid()) {
            return;
        }
        // Iteratively show the example until the user is happy.
        // Yes = OK, No = Repeat, Cancel = Do not save
        final String keyNo = "nNo";
        final String keyLow = "nLower";
        final String keyHigh = "nHigher";
        if (ImageJUtils.isMacro()) {
            // Collect the options if running in a macro
            final String options = Macro.getOptions();
            settings.countNo = Integer.parseInt(Macro.getValue(options, keyNo, Integer.toString(settings.countNo)));
            settings.countLow = Integer.parseInt(Macro.getValue(options, keyLow, Integer.toString(settings.countLow)));
            settings.countHigh = Integer.parseInt(Macro.getValue(options, keyHigh, Integer.toString(settings.countHigh)));
        } else if (settings.countLow + settings.countHigh == 0) {
            settings.countLow = settings.countHigh = 1;
        }
        final ImagePlus[] out = new ImagePlus[1];
        out[0] = sampler.getSample(settings.countNo, settings.countLow, settings.countHigh);
        if (!ImageJUtils.isMacro()) {
            // Show the template results
            final ConfigurationTemplate configTemplate = new ConfigurationTemplate();
            // Interactively show the sample image data
            final boolean[] close = new boolean[1];
            final ImagePlus[] outImp = new ImagePlus[1];
            if (out[0] != null) {
                final WindowOrganiser windowOrganiser = new WindowOrganiser();
                outImp[0] = display(out[0], windowOrganiser);
                if (windowOrganiser.isNotEmpty()) {
                    close[0] = true;
                    // Zoom a bit
                    final ImageWindow iw = outImp[0].getWindow();
                    for (int i = 7; i-- > 0 && Math.max(iw.getWidth(), iw.getHeight()) < 512; ) {
                        iw.getCanvas().zoomIn(0, 0);
                    }
                }
                configTemplate.createResults(outImp[0]);
            }
            // TODO - fix this when a second sample is made as the results are not updated.
            final ImageListener listener = new ImageListener() {

                @Override
                public void imageOpened(ImagePlus imp) {
                // Do nothing
                }

                @Override
                public void imageClosed(ImagePlus imp) {
                // Do nothing
                }

                @Override
                public void imageUpdated(ImagePlus imp) {
                    if (imp != null && imp == outImp[0]) {
                        configTemplate.updateResults(imp.getCurrentSlice());
                    }
                }
            };
            ImagePlus.addImageListener(listener);
            // Turn off the recorder when the dialog is showing
            final boolean record = Recorder.record;
            Recorder.record = false;
            final NonBlockingGenericDialog gd = new NonBlockingGenericDialog(TITLE);
            ImageJUtils.addMessage(gd, "Showing image data for the template example.\n \nSample Frames:\nEmpty = %d\n" + "Lower density = %d\nHigher density = %d\n", sampler.getNumberOfEmptySamples(), sampler.getNumberOfLowDensitySamples(), sampler.getNumberOfHighDensitySamples());
            gd.addSlider(keyNo, 0, 10, settings.countNo);
            gd.addSlider(keyLow, 0, 10, settings.countLow);
            gd.addSlider(keyHigh, 0, 10, settings.countHigh);
            gd.addDialogListener((genDialog, event) -> {
                // image the user has not seen.
                if (event == null) {
                    return true;
                }
                settings.countNo = (int) genDialog.getNextNumber();
                settings.countLow = (int) genDialog.getNextNumber();
                settings.countHigh = (int) genDialog.getNextNumber();
                out[0] = sampler.getSample(settings.countNo, settings.countLow, settings.countHigh);
                if (out[0] != null) {
                    final WindowOrganiser windowOrganiser = new WindowOrganiser();
                    outImp[0] = display(out[0], windowOrganiser);
                    if (windowOrganiser.isNotEmpty()) {
                        close[0] = true;
                        // Zoom a bit
                        final ImageWindow iw = outImp[0].getWindow();
                        for (int i = 7; i-- > 0 && Math.max(iw.getWidth(), iw.getHeight()) < 512; ) {
                            iw.getCanvas().zoomIn(0, 0);
                        }
                    }
                    configTemplate.createResults(outImp[0]);
                }
                return true;
            });
            gd.showDialog();
            if (gd.wasCanceled()) {
                out[0] = null;
                // For the recorder
                settings.countNo = settings.countLow = settings.countHigh = 0;
            }
            if (close[0]) {
                // Because closing the image sets the stack pixels array to null
                if (out[0] != null) {
                    out[0] = out[0].duplicate();
                }
                outImp[0].close();
            }
            configTemplate.closeResults();
            ImagePlus.removeImageListener(listener);
            if (record) {
                Recorder.record = true;
                Recorder.recordOption(keyNo, Integer.toString(settings.countNo));
                Recorder.recordOption(keyLow, Integer.toString(settings.countLow));
                Recorder.recordOption(keyHigh, Integer.toString(settings.countHigh));
            }
        }
        if (out[0] == null) {
            return;
        }
        final ImagePlus example = out[0];
        filename = FileUtils.replaceExtension(filename, ".tif");
        IJ.save(example, filename);
    }
}
Also used : ResultsImageSampler(uk.ac.sussex.gdsc.smlm.ij.results.ResultsImageSampler) ImageWindow(ij.gui.ImageWindow) ImageListener(ij.ImageListener) FitEngineConfiguration(uk.ac.sussex.gdsc.smlm.engine.FitEngineConfiguration) ConfigurationTemplate(uk.ac.sussex.gdsc.smlm.ij.plugins.ConfigurationTemplate) WindowOrganiser(uk.ac.sussex.gdsc.core.ij.plugin.WindowOrganiser) NonBlockingGenericDialog(ij.gui.NonBlockingGenericDialog) ImagePlus(ij.ImagePlus) TemplateSettings(uk.ac.sussex.gdsc.smlm.data.config.TemplateProtos.TemplateSettings)

Aggregations

WindowOrganiser (uk.ac.sussex.gdsc.core.ij.plugin.WindowOrganiser)25 Plot (ij.gui.Plot)12 HistogramPlotBuilder (uk.ac.sussex.gdsc.core.ij.HistogramPlot.HistogramPlotBuilder)10 ImagePlus (ij.ImagePlus)8 Rectangle (java.awt.Rectangle)8 Statistics (uk.ac.sussex.gdsc.core.utils.Statistics)8 ImageStack (ij.ImageStack)7 Point (java.awt.Point)7 LocalList (uk.ac.sussex.gdsc.core.utils.LocalList)7 PlotWindow (ij.gui.PlotWindow)6 ExtendedGenericDialog (uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog)6 StoredDataStatistics (uk.ac.sussex.gdsc.core.utils.StoredDataStatistics)6 MemoryPeakResults (uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults)6 Color (java.awt.Color)5 ExecutorService (java.util.concurrent.ExecutorService)5 IJ (ij.IJ)4 PlugIn (ij.plugin.PlugIn)4 LUT (ij.process.LUT)4 Future (java.util.concurrent.Future)4 HistogramPlot (uk.ac.sussex.gdsc.core.ij.HistogramPlot)4