Search in sources :

Example 81 with MemoryPeakResults

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

the class TraceLengthAnalysis method run.

@Override
public void run(String arg) {
    SmlmUsageTracker.recordPlugin(this.getClass(), arg);
    if (MemoryPeakResults.isMemoryEmpty()) {
        IJ.error(TITLE, "No localisations in memory");
        return;
    }
    if (!showDialog()) {
        return;
    }
    // Load the results
    MemoryPeakResults results = ResultsManager.loadInputResults(settings.inputOption, false, null, null);
    if (MemoryPeakResults.isEmpty(results)) {
        IJ.error(TITLE, "No results could be loaded");
        return;
    }
    try {
        distanceConverter = results.getDistanceConverter(DistanceUnit.UM);
        timeConverter = results.getTimeConverter(TimeUnit.SECOND);
    } catch (final Exception ex) {
        IJ.error(TITLE, "Cannot convert units to um or seconds: " + ex.getMessage());
        return;
    }
    // Get the localisation error (4s^2) in raw units^2
    double precision = 0;
    try {
        final PrecisionResultProcedure p = new PrecisionResultProcedure(results);
        p.getPrecision();
        // Precision in nm using the median
        precision = new Percentile().evaluate(p.precisions, 50);
        // Convert from nm to um to raw units
        final double rawPrecision = distanceConverter.convertBack(precision / 1e3);
        // Get the localisation error (4s^2) in units^2
        error = 4 * rawPrecision * rawPrecision;
    } catch (final Exception ex) {
        ImageJUtils.log(TITLE + " - Unable to compute precision: " + ex.getMessage());
    }
    // Analyse the track lengths
    results = results.copy();
    results.sort(IdFramePeakResultComparator.INSTANCE);
    // Ensure the first result triggers an id change
    lastid = results.getFirst().getId() - 1;
    results.forEach(this::processTrackLength);
    // For the final track
    store();
    msds = msdList.toArray();
    lengths = lengthList.toArray();
    ids = idList.toArray();
    final int[] limits = MathUtils.limits(lengths);
    h1 = new int[limits[1] + 1];
    h2 = new int[h1.length];
    x1 = SimpleArrayUtils.newArray(h1.length, 0, 1f);
    y1 = new float[x1.length];
    y2 = new float[x1.length];
    // Sort by MSD
    final int[] indices = SimpleArrayUtils.natural(msds.length);
    SortUtils.sortIndices(indices, msds, false);
    final double[] msds2 = msds.clone();
    final int[] lengths2 = lengths.clone();
    final int[] ids2 = ids.clone();
    for (int i = 0; i < indices.length; i++) {
        msds[i] = msds2[indices[i]];
        lengths[i] = lengths2[indices[i]];
        ids[i] = ids2[indices[i]];
    }
    // Interactive analysis
    final NonBlockingExtendedGenericDialog gd = new NonBlockingExtendedGenericDialog(TITLE);
    ImageJUtils.addMessage(gd, "Split traces into fixed or moving using the track diffusion coefficient (D).\n" + "Localisation error has been subtracted from jumps (%s nm).", MathUtils.rounded(precision));
    final Statistics s = Statistics.create(msds);
    final double av = s.getMean();
    final String msg = String.format("Average D per track = %s um^2/s", MathUtils.rounded(av));
    gd.addMessage(msg);
    // Histogram the diffusion coefficients
    final WindowOrganiser wo = new WindowOrganiser();
    final HistogramPlot histogramPlot = new HistogramPlotBuilder("Trace diffusion coefficient", StoredData.create(msds), "D (um^2/s)").setRemoveOutliersOption(1).setPlotLabel(msg).build();
    histogramPlot.show(wo);
    final double[] xvalues = histogramPlot.getPlotXValues();
    final double min = xvalues[0];
    final double max = xvalues[xvalues.length - 1];
    // see if we can build a nice slider range from the histogram limits
    if (max - min < 5) {
        // Because sliders are used when the range is <5 and floating point
        gd.addSlider("D_threshold", min, max, settings.msdThreshold);
    } else {
        gd.addNumericField("D_threshold", settings.msdThreshold, 2, 6, "um^2/s");
    }
    gd.addCheckbox("Normalise", settings.normalise);
    gd.addDialogListener((gd1, event) -> {
        settings.msdThreshold = gd1.getNextNumber();
        settings.normalise = gd1.getNextBoolean();
        update();
        return true;
    });
    if (ImageJUtils.isShowGenericDialog()) {
        draw(wo);
        wo.tile();
    }
    gd.setOKLabel("Save datasets");
    gd.setCancelLabel("Close");
    gd.addHelp(HelpUrls.getUrl("trace-length-analysis"));
    gd.showDialog();
    if (gd.wasCanceled()) {
        return;
    }
    // Sort by ID
    final PeakResult[] list = results.toArray();
    Arrays.sort(list, IdFramePeakResultComparator.INSTANCE);
    createResults(results, "Fixed", 0, lastIndex, list);
    createResults(results, "Moving", lastIndex, msds.length, list);
}
Also used : Percentile(org.apache.commons.math3.stat.descriptive.rank.Percentile) NonBlockingExtendedGenericDialog(uk.ac.sussex.gdsc.core.ij.gui.NonBlockingExtendedGenericDialog) HistogramPlotBuilder(uk.ac.sussex.gdsc.core.ij.HistogramPlot.HistogramPlotBuilder) WindowOrganiser(uk.ac.sussex.gdsc.core.ij.plugin.WindowOrganiser) PrecisionResultProcedure(uk.ac.sussex.gdsc.smlm.results.procedures.PrecisionResultProcedure) Statistics(uk.ac.sussex.gdsc.core.utils.Statistics) PeakResult(uk.ac.sussex.gdsc.smlm.results.PeakResult) HistogramPlot(uk.ac.sussex.gdsc.core.ij.HistogramPlot) MemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults)

Example 82 with MemoryPeakResults

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

the class TraceLengthAnalysis method createResults.

private void createResults(MemoryPeakResults results, String suffix, int from, int to, PeakResult[] list) {
    final MemoryPeakResults out = new MemoryPeakResults();
    out.copySettings(results);
    out.setName(results.getName() + " " + suffix);
    // Sort target ids
    Arrays.sort(ids, from, to);
    for (int i = 0; i < list.length && from < to; ) {
        final int nextId = ids[from++];
        // Move forward
        while (i < list.length && list[i].getId() < nextId) {
            i++;
        }
        // Write out
        while (i < list.length && list[i].getId() == nextId) {
            out.add(list[i++]);
        }
    }
    MemoryPeakResults.addResults(out);
}
Also used : MemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults)

Example 83 with MemoryPeakResults

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

the class TraceMolecules method saveCentroidResults.

private static MemoryPeakResults saveCentroidResults(MemoryPeakResults sourceResults, Trace[] traces, String name) {
    final MemoryPeakResults tracedResults = TraceManager.convertToCentroidPeakResults(sourceResults, traces);
    tracedResults.setName(sourceResults.getName() + " " + name);
    MemoryPeakResults.addResults(tracedResults);
    return tracedResults;
}
Also used : MemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults)

Example 84 with MemoryPeakResults

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

the class TraceMolecules method run.

@Override
public void run(String arg) {
    SmlmUsageTracker.recordPlugin(this.getClass(), arg);
    if (MemoryPeakResults.isMemoryEmpty()) {
        IJ.error(pluginTitle, "No localisations in memory");
        return;
    }
    altKeyDown = ImageJUtils.isExtraOptions();
    Trace[] traces = null;
    int totalFiltered = 0;
    if ("dynamic".equals(arg)) {
        // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
        // Dynamic Mutliple Target Tracing
        // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
        outputName = "Dynamic Trace";
        if (!showDynamicTraceDialog()) {
            return;
        }
        final DmttConfiguration config = createDmttConfiguration();
        traces = new DynamicMultipleTargetTracing(results).traceMolecules(config).toArray(new Trace[0]);
    } else if ("cluster".equals(arg)) {
        // -=-=-=-=-=
        // Clustering
        // -=-=-=-=-=
        outputName = "Cluster";
        if (!showClusterDialog()) {
            return;
        }
        final ClusteringEngine engine = new ClusteringEngine(Prefs.getThreads(), getClusteringAlgorithm(settings.getClusteringAlgorithm()), SimpleImageJTrackProgress.getInstance());
        if (settings.getSplitPulses()) {
            engine.setPulseInterval(settings.getPulseInterval());
            limitTimeThreshold(settings.getPulseInterval());
        }
        final List<Cluster> clusters = engine.findClusters(convertToClusterPoints(), getDistance(settings.getDistanceThreshold(), results.getCalibration()), timeThresholdInFrames());
        if (clusters == null) {
            ImageJUtils.log("Aborted");
            return;
        }
        traces = convertToTraces(clusters);
    } else {
        // -=-=-=-
        // Tracing
        // -=-=-=-
        outputName = "Trace";
        if (!showDialog()) {
            return;
        }
        final TraceManager manager = new TraceManager(results);
        manager.setTraceMode(getTraceMode(settings.getTraceMode()));
        manager.setActivationFrameInterval(settings.getPulseInterval());
        manager.setActivationFrameWindow(settings.getPulseWindow());
        manager.setDistanceExclusion(getDistance(settings.getDistanceExclusion(), results.getCalibration()));
        if (settings.getOptimise()) {
            // Optimise before configuring for a pulse interval
            runOptimiser(manager);
        }
        if (settings.getSplitPulses()) {
            manager.setPulseInterval(settings.getPulseInterval());
            limitTimeThreshold(settings.getPulseInterval());
        }
        manager.setTracker(SimpleImageJTrackProgress.getInstance());
        manager.traceMolecules(getDistance(settings.getDistanceThreshold(), results.getCalibration()), timeThresholdInFrames());
        traces = manager.getTraces();
        totalFiltered = manager.getTotalFiltered();
    }
    // --=-=-=-=-=-
    // Results processing
    // --=-=-=-=-=-
    outputName += (outputName.endsWith("e") ? "" : "e") + "d";
    saveResults(results, traces, outputName);
    // Save singles + single localisations in a trace
    saveCentroidResults(results, getSingles(traces), outputName + " Singles");
    final Trace[] multiTraces = getTraces(traces);
    saveResults(results, multiTraces, outputName + " Multi");
    // Save centroids
    outputName += " Centroids";
    final MemoryPeakResults tracedResults = saveCentroidResults(results, traces, outputName);
    // Save traces separately
    saveCentroidResults(results, multiTraces, outputName + " Multi");
    // Sort traces by time to assist the results source in extracting frames sequentially.
    // Do this before saving to assist in debugging using the saved traces file.
    sortByTime(traces);
    if (settings.getSaveTraces()) {
        saveTraces(traces);
    }
    summarise(createSummaryTable(), traces, totalFiltered, settings.getDistanceThreshold(), timeThresholdInSeconds());
    IJ.showStatus(String.format("%d localisations => %d traces (%d filtered)", results.size(), tracedResults.size(), totalFiltered));
}
Also used : Trace(uk.ac.sussex.gdsc.smlm.results.Trace) DmttConfiguration(uk.ac.sussex.gdsc.smlm.results.DynamicMultipleTargetTracing.DmttConfiguration) DynamicMultipleTargetTracing(uk.ac.sussex.gdsc.smlm.results.DynamicMultipleTargetTracing) List(java.util.List) ArrayList(java.util.ArrayList) MemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults) ClusteringEngine(uk.ac.sussex.gdsc.core.clustering.ClusteringEngine) TraceManager(uk.ac.sussex.gdsc.smlm.results.TraceManager) ClusterPoint(uk.ac.sussex.gdsc.core.clustering.ClusterPoint)

Example 85 with MemoryPeakResults

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

the class SummariseResults method showSummary.

private static void showSummary(Collection<MemoryPeakResults> results, int[] removeNullResults) {
    final TextWindow summary = createSummaryTable();
    final StringBuilder sb = new StringBuilder();
    try (BufferedTextWindow tw = new BufferedTextWindow(summary)) {
        for (final MemoryPeakResults result : results) {
            tw.append(createSummary(sb, result, removeNullResults));
        }
        tw.append("");
    }
    summary.toFront();
}
Also used : TextWindow(ij.text.TextWindow) BufferedTextWindow(uk.ac.sussex.gdsc.core.ij.BufferedTextWindow) BufferedTextWindow(uk.ac.sussex.gdsc.core.ij.BufferedTextWindow) MemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults)

Aggregations

MemoryPeakResults (uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults)138 PeakResult (uk.ac.sussex.gdsc.smlm.results.PeakResult)61 List (java.util.List)47 ExtendedGenericDialog (uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog)46 IJ (ij.IJ)39 DistanceUnit (uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.DistanceUnit)39 ImageJUtils (uk.ac.sussex.gdsc.core.ij.ImageJUtils)38 PeakResultProcedure (uk.ac.sussex.gdsc.smlm.results.procedures.PeakResultProcedure)38 ArrayList (java.util.ArrayList)36 AtomicReference (java.util.concurrent.atomic.AtomicReference)36 PlugIn (ij.plugin.PlugIn)34 MathUtils (uk.ac.sussex.gdsc.core.utils.MathUtils)33 Counter (uk.ac.sussex.gdsc.smlm.results.count.Counter)33 ImagePlus (ij.ImagePlus)31 Rectangle (java.awt.Rectangle)31 SimpleArrayUtils (uk.ac.sussex.gdsc.core.utils.SimpleArrayUtils)31 LocalList (uk.ac.sussex.gdsc.core.utils.LocalList)28 TextUtils (uk.ac.sussex.gdsc.core.utils.TextUtils)28 SettingsManager (uk.ac.sussex.gdsc.smlm.ij.settings.SettingsManager)28 FrameCounter (uk.ac.sussex.gdsc.smlm.results.count.FrameCounter)28