Search in sources :

Example 1 with DistanceUnit

use of uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.DistanceUnit in project GDSC-SMLM by aherbert.

the class PcPalmMolecules method traceMolecules.

/**
 * Trace localisations.
 *
 * @param results The results
 * @param precisions the precisions
 * @param distance The distance threshold (nm)
 * @param time The time threshold (frames)
 * @param singles a list of the singles (not grouped into molecules)
 * @return a list of molecules
 */
private static ArrayList<Molecule> traceMolecules(MemoryPeakResults results, double[] precisions, double distance, int time, ArrayList<Molecule> singles) {
    // These plugins are not really supported so just leave them to throw an exception if
    // the data cannot be handled
    final TypeConverter<IntensityUnit> ic = results.getCalibrationReader().getIntensityConverter(IntensityUnit.PHOTON);
    final TypeConverter<DistanceUnit> dc = results.getCalibrationReader().getDistanceConverter(DistanceUnit.NM);
    // Create a new dataset with the precision
    final MemoryPeakResults results2 = new MemoryPeakResults(results.size());
    for (int i = 0, size = results.size(); i < size; i++) {
        final AttributePeakResult peak2 = new AttributePeakResult(results.get(i));
        peak2.setPrecision(precisions[i]);
        results2.add(peak2);
    }
    final TraceManager tm = new TraceManager(results2);
    final double distanceThreshold = dc.convertBack(distance);
    tm.traceMolecules(distanceThreshold, time);
    final Trace[] traces = tm.getTraces();
    final ArrayList<Molecule> molecules = new ArrayList<>(traces.length);
    for (final Trace t : traces) {
        final double p = t.getLocalisationPrecision(dc);
        final float[] centroid = t.getCentroid();
        final List<Molecule> list = t.size() == 1 ? singles : molecules;
        list.add(new Molecule(dc.convert(centroid[0]), dc.convert(centroid[1]), p, ic.convert(t.getSignal())));
    }
    log("  %d localisations traced to %d molecules (%d singles, %d traces) using d=%.2f nm," + " t=%d frames (%s s)", results.size(), molecules.size() + singles.size(), singles.size(), molecules.size(), distance, time, MathUtils.rounded(time * results.getCalibrationReader().getExposureTime() / 1000.0));
    return molecules;
}
Also used : AttributePeakResult(uk.ac.sussex.gdsc.smlm.results.AttributePeakResult) TDoubleArrayList(gnu.trove.list.array.TDoubleArrayList) ArrayList(java.util.ArrayList) TraceManager(uk.ac.sussex.gdsc.smlm.results.TraceManager) WeightedObservedPoint(org.apache.commons.math3.fitting.WeightedObservedPoint) ClusterPoint(uk.ac.sussex.gdsc.core.clustering.ClusterPoint) Trace(uk.ac.sussex.gdsc.smlm.results.Trace) IntensityUnit(uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.IntensityUnit) MemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults) DistanceUnit(uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.DistanceUnit)

Example 2 with DistanceUnit

use of uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.DistanceUnit in project GDSC-SMLM by aherbert.

the class PeakResultTableModelFrame method doSourceOverlay.

private void doSourceOverlay() {
    final PeakResultTableModel model = getModel();
    if (model == null) {
        return;
    }
    final PeakResult[] list = table.getSelectedData();
    if (list.length == 0) {
        return;
    }
    final ImageSource source = model.getSource();
    if (source == null) {
        return;
    }
    final String title = source.getOriginal().getName();
    final ImagePlus imp = WindowManager.getImage(title);
    if (imp == null) {
        return;
    }
    // Assumes 3D stack (no channel/time)
    if (imp.getNDimensions() > 3) {
        return;
    }
    try {
        final TypeConverter<DistanceUnit> converter = CalibrationHelper.getDistanceConverter(model.getCalibration(), DistanceUnit.PIXEL);
        final Overlay o = new Overlay();
        if (list.length == 1) {
            final PeakResult p = list[0];
            final PointRoi roi = new OffsetPointRoi(converter.convert(p.getXPosition()), converter.convert(p.getYPosition()));
            roi.setPointType(3);
            roi.setPosition(p.getFrame());
            o.add(roi);
        } else {
            Arrays.sort(list, FramePeakResultComparator.INSTANCE);
            final TFloatArrayList ox = new TFloatArrayList(list.length);
            final TFloatArrayList oy = new TFloatArrayList(list.length);
            int frame = list[0].getFrame() - 1;
            for (int i = 0; i < list.length; i++) {
                if (frame != list[i].getFrame()) {
                    if (ox.size() > 0) {
                        final PointRoi roi = new OffsetPointRoi(ox.toArray(), oy.toArray());
                        roi.setPointType(3);
                        roi.setPosition(frame);
                        ox.resetQuick();
                        oy.resetQuick();
                        o.add(roi);
                    }
                    frame = list[i].getFrame();
                }
                ox.add(converter.convert(list[i].getXPosition()));
                oy.add(converter.convert(list[i].getYPosition()));
            }
            if (ox.size() > 0) {
                final PointRoi roi = new OffsetPointRoi(ox.toArray(), oy.toArray());
                roi.setPointType(3);
                roi.setPosition(frame);
                o.add(roi);
            }
        }
        imp.setOverlay(o);
        final PeakResult p = list[0];
        imp.setSlice(p.getFrame());
        ImageJUtils.adjustSourceRect(imp, 0, (int) converter.convert(p.getXPosition()), (int) converter.convert(p.getYPosition()));
        imp.getWindow().toFront();
    } catch (final ConversionException ex) {
    // Ignore
    }
}
Also used : ConversionException(uk.ac.sussex.gdsc.core.data.utils.ConversionException) OffsetPointRoi(uk.ac.sussex.gdsc.core.ij.gui.OffsetPointRoi) ImagePlus(ij.ImagePlus) PeakResult(uk.ac.sussex.gdsc.smlm.results.PeakResult) ReadHint(uk.ac.sussex.gdsc.smlm.results.ImageSource.ReadHint) TFloatArrayList(gnu.trove.list.array.TFloatArrayList) ImageSource(uk.ac.sussex.gdsc.smlm.results.ImageSource) IJImageSource(uk.ac.sussex.gdsc.smlm.ij.IJImageSource) SeriesImageSource(uk.ac.sussex.gdsc.smlm.ij.SeriesImageSource) Overlay(ij.gui.Overlay) DistanceUnit(uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.DistanceUnit) PointRoi(ij.gui.PointRoi) OffsetPointRoi(uk.ac.sussex.gdsc.core.ij.gui.OffsetPointRoi)

Example 3 with DistanceUnit

use of uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.DistanceUnit in project GDSC-SMLM by aherbert.

the class TraceExporter method export.

private void export(MemoryPeakResults results) {
    // Copy to allow manipulation
    results = results.copy();
    // Strip results with no trace Id
    results.removeIf(result -> result.getId() <= 0);
    // Sort by ID then time
    results.sort(IdFramePeakResultComparator.INSTANCE);
    // Split traces with big jumps and long tracks into smaller tracks
    results = splitTraces(results);
    results = splitLongTraces(results);
    // Count each ID and remove short traces
    int id = 0;
    int count = 0;
    int tracks = 0;
    int maxLength = 0;
    final TIntHashSet remove = new TIntHashSet();
    for (int i = 0, size = results.size(); i < size; i++) {
        final PeakResult result = results.get(i);
        if (result.getId() != id) {
            if (count < settings.minLength) {
                remove.add(id);
            } else {
                tracks++;
                maxLength = Math.max(maxLength, count);
            }
            count = 0;
            id = result.getId();
        }
        count += getLength(result);
    }
    // Final ID
    if (count < settings.minLength) {
        remove.add(id);
    } else {
        tracks++;
        maxLength = Math.max(maxLength, count);
    }
    if (!remove.isEmpty()) {
        results.removeIf(result -> remove.contains(result.getId()));
        results.sort(IdFramePeakResultComparator.INSTANCE);
    }
    if (settings.wobble > 0) {
        // Just leave any exceptions to trickle up and kill the plugin
        final TypeConverter<DistanceUnit> c = results.getDistanceConverter(DistanceUnit.NM);
        final double w = c.convertBack(settings.wobble);
        final UniformRandomProvider rng = UniformRandomProviders.create();
        final NormalizedGaussianSampler gauss = SamplerUtils.createNormalizedGaussianSampler(rng);
        final boolean is3D = results.is3D();
        results.forEach((PeakResultProcedure) peakResult -> {
            peakResult.setXPosition((float) (peakResult.getXPosition() + w * gauss.sample()));
            peakResult.setYPosition((float) (peakResult.getYPosition() + w * gauss.sample()));
            if (is3D) {
                peakResult.setZPosition((float) (peakResult.getZPosition() + w * gauss.sample()));
            }
        });
    }
    if (settings.format == 2) {
        exportVbSpt(results);
    } else if (settings.format == 1) {
        exportAnaDda(results);
    } else {
        exportSpotOn(results);
    }
    ImageJUtils.log("Exported %s: %s in %s", results.getName(), TextUtils.pleural(results.size(), "localisation"), TextUtils.pleural(tracks, "track"));
    if (settings.showTraceLengths) {
        // We store and index (count-1)
        final int[] h = new int[maxLength];
        id = 0;
        for (int i = 0, size = results.size(); i < size; i++) {
            final PeakResult result = results.get(i);
            if (result.getId() != id) {
                h[count - 1]++;
                count = 0;
                id = result.getId();
            }
            count += getLength(result);
        }
        h[count - 1]++;
        final String title = TITLE + ": " + results.getName();
        final Plot plot = new Plot(title, "Length", "Frequency");
        plot.addPoints(SimpleArrayUtils.newArray(h.length, 1, 1.0f), SimpleArrayUtils.toFloat(h), Plot.BAR);
        plot.setLimits(SimpleArrayUtils.findIndex(h, i -> i != 0), maxLength + 1, 0, Double.NaN);
        ImageJUtils.display(title, plot);
    }
}
Also used : MemoryResultsList(uk.ac.sussex.gdsc.smlm.ij.plugins.ResultsManager.MemoryResultsList) Cell(us.hebi.matlab.mat.types.Cell) UnitConverterUtils(uk.ac.sussex.gdsc.smlm.data.config.UnitConverterUtils) IdFramePeakResultComparator(uk.ac.sussex.gdsc.smlm.results.sort.IdFramePeakResultComparator) FrameCounter(uk.ac.sussex.gdsc.smlm.results.count.FrameCounter) PeakResult(uk.ac.sussex.gdsc.smlm.results.PeakResult) MatFile(us.hebi.matlab.mat.types.MatFile) AtomicReference(java.util.concurrent.atomic.AtomicReference) Matrix(us.hebi.matlab.mat.types.Matrix) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) MultiDialog(uk.ac.sussex.gdsc.core.ij.gui.MultiDialog) MemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults) PeakResultProcedure(uk.ac.sussex.gdsc.smlm.results.procedures.PeakResultProcedure) SettingsManager(uk.ac.sussex.gdsc.smlm.ij.settings.SettingsManager) XyrResultProcedure(uk.ac.sussex.gdsc.smlm.results.procedures.XyrResultProcedure) UniformRandomProvider(org.apache.commons.rng.UniformRandomProvider) Files(java.nio.file.Files) BufferedWriter(java.io.BufferedWriter) ExtendedGenericDialog(uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog) IOException(java.io.IOException) NamedObject(uk.ac.sussex.gdsc.smlm.data.NamedObject) DistanceUnit(uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.DistanceUnit) Logger(java.util.logging.Logger) SamplerUtils(uk.ac.sussex.gdsc.core.utils.rng.SamplerUtils) AttributePeakResult(uk.ac.sussex.gdsc.smlm.results.AttributePeakResult) TextUtils(uk.ac.sussex.gdsc.core.utils.TextUtils) Plot(ij.gui.Plot) TIntHashSet(gnu.trove.set.hash.TIntHashSet) TimeUnit(uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.TimeUnit) XyzrResultProcedure(uk.ac.sussex.gdsc.smlm.results.procedures.XyzrResultProcedure) List(java.util.List) Counter(uk.ac.sussex.gdsc.smlm.results.count.Counter) Paths(java.nio.file.Paths) ImageJUtils(uk.ac.sussex.gdsc.core.ij.ImageJUtils) IJ(ij.IJ) SimpleArrayUtils(uk.ac.sussex.gdsc.core.utils.SimpleArrayUtils) Mat5(us.hebi.matlab.mat.format.Mat5) PlugIn(ij.plugin.PlugIn) NormalizedGaussianSampler(org.apache.commons.rng.sampling.distribution.NormalizedGaussianSampler) TypeConverter(uk.ac.sussex.gdsc.core.data.utils.TypeConverter) LocalList(uk.ac.sussex.gdsc.core.utils.LocalList) UniformRandomProviders(uk.ac.sussex.gdsc.core.utils.rng.UniformRandomProviders) Plot(ij.gui.Plot) TIntHashSet(gnu.trove.set.hash.TIntHashSet) PeakResult(uk.ac.sussex.gdsc.smlm.results.PeakResult) AttributePeakResult(uk.ac.sussex.gdsc.smlm.results.AttributePeakResult) UniformRandomProvider(org.apache.commons.rng.UniformRandomProvider) DistanceUnit(uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.DistanceUnit) NormalizedGaussianSampler(org.apache.commons.rng.sampling.distribution.NormalizedGaussianSampler)

Example 4 with DistanceUnit

use of uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.DistanceUnit in project GDSC-SMLM by aherbert.

the class SpotInspector method mouseClicked.

private void mouseClicked(MouseEvent event) {
    if (id != currentId.get()) {
        return;
    }
    // Show the result that was double clicked in the result table
    if (event.getClickCount() > 1) {
        final int rank = textPanel.getSelectionStart() + 1;
        // Show the spot that was double clicked
        final ImagePlus imp = WindowManager.getImage(TITLE);
        if (imp != null && rank > 0 && rank <= imp.getStackSize()) {
            imp.setSlice(rank);
            if (imp.getWindow() != null) {
                imp.getWindow().toFront();
            }
            final PeakResult r = rankedResults.get(rank - 1).peakResult;
            final TypeConverter<DistanceUnit> dc = results.getDistanceConverter(DistanceUnit.PIXEL);
            final float rx = dc.convert(r.getXPosition());
            final float ry = dc.convert(r.getYPosition());
            final int x = (int) rx;
            final int y = (int) ry;
            // Find bounds
            final int minX = x - settings.radius;
            final int minY = y - settings.radius;
            // Require the Shift key to add all spots
            if (!event.isShiftDown()) {
                // Add the single clicked spot
                imp.setRoi(new OffsetPointRoi(rx - minX, ry - minY));
                return;
            }
            // Add all the spots
            final int maxX = x + settings.radius + 1;
            final int maxY = y + settings.radius + 1;
            // Create ROIs
            final HashSet<Point2D.Float> spots = new HashSet<>();
            results.forEach(DistanceUnit.PIXEL, (XyResultProcedure) (xp, yp) -> {
                if (xp > minX && xp < maxX && yp > minY && yp < maxY) {
                    // Use only unique points
                    spots.add(new Point2D.Float(xp - minX, yp - minY));
                }
            });
            final int points = spots.size();
            final float[] ox = new float[points];
            final float[] oy = new float[points];
            final Counter c = new Counter();
            spots.forEach(p -> {
                ox[c.getCount()] = p.x;
                oy[c.getAndIncrement()] = p.y;
            });
            imp.setRoi(new OffsetPointRoi(ox, oy, points));
        }
    }
}
Also used : PrecisionResultProcedure(uk.ac.sussex.gdsc.smlm.results.procedures.PrecisionResultProcedure) Rectangle(java.awt.Rectangle) Point2D(java.awt.geom.Point2D) ImageProcessor(ij.process.ImageProcessor) HistogramPlotBuilder(uk.ac.sussex.gdsc.core.ij.HistogramPlot.HistogramPlotBuilder) PSF(uk.ac.sussex.gdsc.smlm.data.config.PSFProtos.PSF) WindowManager(ij.WindowManager) PeakResult(uk.ac.sussex.gdsc.smlm.results.PeakResult) IntensityUnit(uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.IntensityUnit) ImageSource(uk.ac.sussex.gdsc.smlm.results.ImageSource) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) PointRoi(ij.gui.PointRoi) HashSet(java.util.HashSet) XyResultProcedure(uk.ac.sussex.gdsc.smlm.results.procedures.XyResultProcedure) StoredDataStatistics(uk.ac.sussex.gdsc.core.utils.StoredDataStatistics) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) MemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults) ReadHint(uk.ac.sussex.gdsc.smlm.results.ImageSource.ReadHint) MouseAdapter(java.awt.event.MouseAdapter) PeakResultProcedure(uk.ac.sussex.gdsc.smlm.results.procedures.PeakResultProcedure) MathUtils(uk.ac.sussex.gdsc.core.utils.MathUtils) FitConfiguration(uk.ac.sussex.gdsc.smlm.engine.FitConfiguration) TextPanel(ij.text.TextPanel) HeightResultProcedure(uk.ac.sussex.gdsc.smlm.results.procedures.HeightResultProcedure) ExtendedGenericDialog(uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog) InputSource(uk.ac.sussex.gdsc.smlm.ij.plugins.ResultsManager.InputSource) OffsetPointRoi(uk.ac.sussex.gdsc.core.ij.gui.OffsetPointRoi) DistanceUnit(uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.DistanceUnit) WidthResultProcedure(uk.ac.sussex.gdsc.smlm.results.procedures.WidthResultProcedure) Plot(ij.gui.Plot) MouseEvent(java.awt.event.MouseEvent) ImageJTablePeakResults(uk.ac.sussex.gdsc.smlm.ij.results.ImageJTablePeakResults) ImagePlus(ij.ImagePlus) FloatProcessor(ij.process.FloatProcessor) List(java.util.List) Counter(uk.ac.sussex.gdsc.smlm.results.count.Counter) ImageJUtils(uk.ac.sussex.gdsc.core.ij.ImageJUtils) IJ(ij.IJ) DescriptiveStatistics(org.apache.commons.math3.stat.descriptive.DescriptiveStatistics) ImageStack(ij.ImageStack) PsfHelper(uk.ac.sussex.gdsc.smlm.data.config.PsfHelper) PlugIn(ij.plugin.PlugIn) Collections(java.util.Collections) TypeConverter(uk.ac.sussex.gdsc.core.data.utils.TypeConverter) StandardResultProcedure(uk.ac.sussex.gdsc.smlm.results.procedures.StandardResultProcedure) OffsetPointRoi(uk.ac.sussex.gdsc.core.ij.gui.OffsetPointRoi) ImagePlus(ij.ImagePlus) ReadHint(uk.ac.sussex.gdsc.smlm.results.ImageSource.ReadHint) PeakResult(uk.ac.sussex.gdsc.smlm.results.PeakResult) Counter(uk.ac.sussex.gdsc.smlm.results.count.Counter) DistanceUnit(uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.DistanceUnit) HashSet(java.util.HashSet)

Example 5 with DistanceUnit

use of uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.DistanceUnit in project GDSC-SMLM by aherbert.

the class PeakFit method configureZFilter.

/**
 * Show a dialog to configure the results z filter. The updated settings are saved to the settings
 * file.
 *
 * <p>If the fit configuration PSF is not 3D or the simple filter is disabled then this method
 * returns true. If it is enabled then a dialog is shown to input the configuration for the z
 * filter.
 *
 * <p>Note: The PSF and any z-model must be correctly configured for fitting in pixel units.
 *
 * @param config the config
 * @param flags the flags
 * @return true, if successful
 */
public static boolean configureZFilter(FitEngineConfiguration config, int flags) {
    final FitConfiguration fitConfig = config.getFitConfiguration();
    if (fitConfig.isDisableSimpleFilter() || !fitConfig.is3D()) {
        return true;
    }
    // Create a converter to map the model units in pixels to nm for the dialog.
    // Note the output units of pixels may not yet be set in the calibration so we assume it is
    // pixels.
    final TypeConverter<DistanceUnit> c = UnitConverterUtils.createConverter(DistanceUnit.PIXEL, DistanceUnit.NM, fitConfig.getCalibrationReader().getNmPerPixel());
    final ExtendedGenericDialog gd = new ExtendedGenericDialog(TITLE);
    gd.addMessage("3D filter");
    gd.addNumericField("Min_z", c.convert(fitConfig.getMinZ()), 0, 6, "nm");
    gd.addNumericField("Max_z", c.convert(fitConfig.getMaxZ()), 0, 6, "nm");
    gd.showDialog();
    if (gd.wasCanceled()) {
        return false;
    }
    final double minZ = gd.getNextNumber();
    final double maxZ = gd.getNextNumber();
    if (gd.invalidNumber() || minZ > maxZ) {
        IJ.error(TITLE, "Min Z must be equal or below the max Z");
        return false;
    }
    // Map back
    fitConfig.setMinZ(c.convertBack(minZ));
    fitConfig.setMaxZ(c.convertBack(maxZ));
    if (BitFlagUtils.anyNotSet(flags, FLAG_NO_SAVE)) {
        SettingsManager.writeSettings(config, 0);
    }
    return true;
}
Also used : FitConfiguration(uk.ac.sussex.gdsc.smlm.engine.FitConfiguration) ExtendedGenericDialog(uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog) DistanceUnit(uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.DistanceUnit)

Aggregations

DistanceUnit (uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.DistanceUnit)21 MemoryPeakResults (uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults)7 ExtendedGenericDialog (uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog)6 IntensityUnit (uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.IntensityUnit)6 CalibrationReader (uk.ac.sussex.gdsc.smlm.data.config.CalibrationReader)5 PeakResult (uk.ac.sussex.gdsc.smlm.results.PeakResult)5 IJ (ij.IJ)3 Plot (ij.gui.Plot)3 PlugIn (ij.plugin.PlugIn)3 ArrayList (java.util.ArrayList)3 ConversionException (uk.ac.sussex.gdsc.core.data.utils.ConversionException)3 TypeConverter (uk.ac.sussex.gdsc.core.data.utils.TypeConverter)3 MultiDialog (uk.ac.sussex.gdsc.core.ij.gui.MultiDialog)3 PeakResultProcedure (uk.ac.sussex.gdsc.smlm.results.procedures.PeakResultProcedure)3 ImagePlus (ij.ImagePlus)2 PointRoi (ij.gui.PointRoi)2 Rectangle (java.awt.Rectangle)2 List (java.util.List)2 AtomicReference (java.util.concurrent.atomic.AtomicReference)2 Test (org.junit.jupiter.api.Test)2