Search in sources :

Example 6 with ImageSource

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

the class PeakResultTableModelFrame method doSourceShowInfo.

private void doSourceShowInfo() {
    final PeakResultTableModel model = getModel();
    if (model == null) {
        return;
    }
    final ImageSource source = model.getSource();
    String text = getTitle() + " source";
    if (source == null) {
        text += " = NA";
    } else {
        text += "\n" + XmlUtils.prettyPrintXml(source.toXml());
    }
    // Note:
    // If a raw path is printed to the ImageJ log double-clicking it will open the image.
    // We could separate these onto multiple lines:
    // <path>/path/to/image.tif</path>
    // <string>/path/to/image.tif</string>
    IJ.log(text);
}
Also used : ImageSource(uk.ac.sussex.gdsc.smlm.results.ImageSource) IJImageSource(uk.ac.sussex.gdsc.smlm.ij.IJImageSource) SeriesImageSource(uk.ac.sussex.gdsc.smlm.ij.SeriesImageSource)

Example 7 with ImageSource

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

the class SpotInspector 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
    results = ResultsManager.loadInputResults(settings.inputOption, false, DistanceUnit.PIXEL, null);
    if (MemoryPeakResults.isEmpty(results)) {
        IJ.error(TITLE, "No results could be loaded");
        IJ.showStatus("");
        return;
    }
    // Check if the original image is open
    ImageSource source = results.getSource();
    if (source == null) {
        IJ.error(TITLE, "Unknown original source image");
        return;
    }
    source = source.getOriginal();
    source.setReadHint(ReadHint.NONSEQUENTIAL);
    if (!source.open()) {
        IJ.error(TITLE, "Cannot open original source image: " + source.toString());
        return;
    }
    final float stdDevMax = getStandardDeviation(results);
    if (stdDevMax < 0) {
        // TODO - Add dialog to get the initial peak width
        IJ.error(TITLE, "Fitting configuration (for initial peak width) is not available");
        return;
    }
    // Rank spots
    rankedResults = new ArrayList<>(results.size());
    // Data for the sorting
    final PrecisionResultProcedure pp;
    if (settings.sortOrderIndex == 1) {
        pp = new PrecisionResultProcedure(results);
        pp.getPrecision();
    } else {
        pp = null;
    }
    // Build procedures to get:
    // Shift = position in pixels - originXY
    final StandardResultProcedure sp;
    if (settings.sortOrderIndex == 9) {
        sp = new StandardResultProcedure(results, DistanceUnit.PIXEL);
        sp.getXyr();
    } else {
        sp = null;
    }
    // SD = gaussian widths only for Gaussian PSFs
    final WidthResultProcedure wp;
    if (settings.sortOrderIndex >= 6 && settings.sortOrderIndex <= 8) {
        wp = new WidthResultProcedure(results, DistanceUnit.PIXEL);
        wp.getWxWy();
    } else {
        wp = null;
    }
    // Amplitude for Gaussian PSFs
    final HeightResultProcedure hp;
    if (settings.sortOrderIndex == 2) {
        hp = new HeightResultProcedure(results, IntensityUnit.PHOTON);
        hp.getH();
    } else {
        hp = null;
    }
    final Counter c = new Counter();
    results.forEach((PeakResultProcedure) result -> {
        final float[] score = getScore(result, c.getAndIncrement(), pp, sp, wp, hp, stdDevMax);
        rankedResults.add(new PeakResultRank(result, score[0], score[1]));
    });
    Collections.sort(rankedResults, PeakResultRank::compare);
    // Prepare results table
    final ImageJTablePeakResults table = new ImageJTablePeakResults(false, results.getName(), true);
    table.copySettings(results);
    table.setTableTitle(TITLE);
    table.setAddCounter(true);
    table.setShowZ(results.is3D());
    // TODO - Add to settings
    table.setShowFittingData(true);
    table.setShowNoiseData(true);
    if (settings.showCalibratedValues) {
        table.setDistanceUnit(DistanceUnit.NM);
        table.setIntensityUnit(IntensityUnit.PHOTON);
    } else {
        table.setDistanceUnit(DistanceUnit.PIXEL);
        table.setIntensityUnit(IntensityUnit.COUNT);
    }
    table.begin();
    // Add a mouse listener to jump to the frame for the clicked line
    textPanel = table.getResultsWindow().getTextPanel();
    // We must ignore old instances of this class from the mouse listeners
    id = currentId.incrementAndGet();
    textPanel.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseClicked(MouseEvent event) {
            SpotInspector.this.mouseClicked(event);
        }
    });
    // Add results to the table
    int count = 0;
    for (final PeakResultRank rank : rankedResults) {
        rank.rank = count++;
        table.add(rank.peakResult);
    }
    table.end();
    if (settings.plotScore || settings.plotHistogram) {
        // Get values for the plots
        float[] xValues = null;
        float[] yValues = null;
        double yMin;
        double yMax;
        int spotNumber = 0;
        xValues = new float[rankedResults.size()];
        yValues = new float[xValues.length];
        for (final PeakResultRank rank : rankedResults) {
            xValues[spotNumber] = spotNumber + 1;
            yValues[spotNumber++] = recoverScore(rank.score);
        }
        // Set the min and max y-values using 1.5 x IQR
        final DescriptiveStatistics stats = new DescriptiveStatistics();
        for (final float v : yValues) {
            stats.addValue(v);
        }
        if (settings.removeOutliers) {
            final double lower = stats.getPercentile(25);
            final double upper = stats.getPercentile(75);
            final double iqr = upper - lower;
            yMin = Math.max(lower - iqr, stats.getMin());
            yMax = Math.min(upper + iqr, stats.getMax());
            IJ.log(String.format("Data range: %f - %f. Plotting 1.5x IQR: %f - %f", stats.getMin(), stats.getMax(), yMin, yMax));
        } else {
            yMin = stats.getMin();
            yMax = stats.getMax();
            IJ.log(String.format("Data range: %f - %f", yMin, yMax));
        }
        plotScore(xValues, yValues, yMin, yMax);
        plotHistogram(yValues);
    }
    // Extract spots into a stack
    final int w = source.getWidth();
    final int h = source.getHeight();
    final int size = 2 * settings.radius + 1;
    final ImageStack spots = new ImageStack(size, size, rankedResults.size());
    // To assist the extraction of data from the image source, process them in time order to allow
    // frame caching. Then set the appropriate slice in the result stack
    Collections.sort(rankedResults, (o1, o2) -> Integer.compare(o1.peakResult.getFrame(), o2.peakResult.getFrame()));
    for (final PeakResultRank rank : rankedResults) {
        final PeakResult r = rank.peakResult;
        // Extract image
        // Note that the coordinates are relative to the middle of the pixel (0.5 offset)
        // so do not round but simply convert to int
        final int x = (int) (r.getXPosition());
        final int y = (int) (r.getYPosition());
        // Extract a region but crop to the image bounds
        int minX = x - settings.radius;
        int minY = y - settings.radius;
        final int maxX = Math.min(x + settings.radius + 1, w);
        final int maxY = Math.min(y + settings.radius + 1, h);
        int padX = 0;
        int padY = 0;
        if (minX < 0) {
            padX = -minX;
            minX = 0;
        }
        if (minY < 0) {
            padY = -minY;
            minY = 0;
        }
        final int sizeX = maxX - minX;
        final int sizeY = maxY - minY;
        float[] data = source.get(r.getFrame(), new Rectangle(minX, minY, sizeX, sizeY));
        // Prevent errors with missing data
        if (data == null) {
            data = new float[sizeX * sizeY];
        }
        ImageProcessor spotIp = new FloatProcessor(sizeX, sizeY, data, null);
        // Pad if necessary, i.e. the crop is too small for the stack
        if (padX > 0 || padY > 0 || sizeX < size || sizeY < size) {
            final ImageProcessor spotIp2 = spotIp.createProcessor(size, size);
            spotIp2.insert(spotIp, padX, padY);
            spotIp = spotIp2;
        }
        final int slice = rank.rank + 1;
        spots.setPixels(spotIp.getPixels(), slice);
        spots.setSliceLabel(MathUtils.rounded(rank.originalScore), slice);
    }
    source.close();
    // Reset to the rank order
    Collections.sort(rankedResults, PeakResultRank::compare);
    final ImagePlus imp = ImageJUtils.display(TITLE, spots);
    imp.setRoi((PointRoi) null);
    // Make bigger
    for (int i = 10; i-- > 0; ) {
        imp.getWindow().getCanvas().zoomIn(imp.getWidth() / 2, imp.getHeight() / 2);
    }
}
Also used : HeightResultProcedure(uk.ac.sussex.gdsc.smlm.results.procedures.HeightResultProcedure) 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) DescriptiveStatistics(org.apache.commons.math3.stat.descriptive.DescriptiveStatistics) MouseEvent(java.awt.event.MouseEvent) ImageStack(ij.ImageStack) FloatProcessor(ij.process.FloatProcessor) ImageJTablePeakResults(uk.ac.sussex.gdsc.smlm.ij.results.ImageJTablePeakResults) MouseAdapter(java.awt.event.MouseAdapter) Rectangle(java.awt.Rectangle) WidthResultProcedure(uk.ac.sussex.gdsc.smlm.results.procedures.WidthResultProcedure) PrecisionResultProcedure(uk.ac.sussex.gdsc.smlm.results.procedures.PrecisionResultProcedure) ImagePlus(ij.ImagePlus) ReadHint(uk.ac.sussex.gdsc.smlm.results.ImageSource.ReadHint) PeakResult(uk.ac.sussex.gdsc.smlm.results.PeakResult) ImageProcessor(ij.process.ImageProcessor) Counter(uk.ac.sussex.gdsc.smlm.results.count.Counter) StandardResultProcedure(uk.ac.sussex.gdsc.smlm.results.procedures.StandardResultProcedure) ImageSource(uk.ac.sussex.gdsc.smlm.results.ImageSource)

Example 8 with ImageSource

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

the class PsfEstimator method calculateStatistics.

private boolean calculateStatistics(PeakFit fitter, double[] params, double[] paramsDev) {
    debug("  Fitting PSF");
    swapStatistics();
    // Create the fit engine using the PeakFit plugin
    final FitConfiguration fitConfig = config.getFitConfiguration();
    fitConfig.setInitialPeakStdDev0((float) params[1]);
    try {
        fitConfig.setInitialPeakStdDev1((float) params[2]);
        fitConfig.setInitialAngle((float) Math.toRadians(params[0]));
    } catch (IllegalStateException ex) {
    // Ignore this as the current PSF is not a 2 axis and theta Gaussian PSF
    }
    final ImageStack stack = imp.getImageStack();
    final Rectangle roi = stack.getProcessor(1).getRoi();
    ImageSource source = new IJImageSource(imp);
    // Allow interlaced data by wrapping the image source
    if (interlacedData) {
        source = new InterlacedImageSource(source, dataStart, dataBlock, dataSkip);
    }
    // Allow frame aggregation by wrapping the image source
    if (integrateFrames > 1) {
        source = new AggregatedImageSource(source, integrateFrames);
    }
    fitter.initialiseImage(source, roi, true);
    fitter.addPeakResults(this);
    fitter.initialiseFitting();
    final FitEngine engine = fitter.createFitEngine();
    // Use random slices
    final int[] slices = new int[stack.getSize()];
    for (int i = 0; i < slices.length; i++) {
        slices[i] = i + 1;
    }
    RandomUtils.shuffle(slices, UniformRandomProviders.create());
    IJ.showStatus("Fitting ...");
    // Use multi-threaded code for speed
    int sliceIndex;
    for (sliceIndex = 0; sliceIndex < slices.length; sliceIndex++) {
        final int slice = slices[sliceIndex];
        IJ.showProgress(size(), settings.getNumberOfPeaks());
        final ImageProcessor ip = stack.getProcessor(slice);
        // stack processor does not set the bounds required by ImageConverter
        ip.setRoi(roi);
        final FitJob job = new FitJob(slice, ImageJImageConverter.getData(ip), roi);
        engine.run(job);
        if (sampleSizeReached() || ImageJUtils.isInterrupted()) {
            break;
        }
    }
    if (ImageJUtils.isInterrupted()) {
        IJ.showProgress(1);
        engine.end(true);
        return false;
    }
    // Wait until we have enough results
    while (!sampleSizeReached() && !engine.isQueueEmpty()) {
        IJ.showProgress(size(), settings.getNumberOfPeaks());
        try {
            Thread.sleep(50);
        } catch (final InterruptedException ex) {
            Thread.currentThread().interrupt();
            throw new ConcurrentRuntimeException("Unexpected interruption", ex);
        }
    }
    // End now if we have enough samples
    engine.end(sampleSizeReached());
    ImageJUtils.finished();
    // This count will be an over-estimate given that the provider is ahead of the consumer
    // in this multi-threaded system
    debug("  Processed %d/%d slices (%d peaks)", sliceIndex, slices.length, size());
    setParams(ANGLE, params, paramsDev, sampleNew[ANGLE]);
    setParams(X, params, paramsDev, sampleNew[X]);
    setParams(Y, params, paramsDev, sampleNew[Y]);
    if (settings.getShowHistograms()) {
        final HistogramPlotBuilder builder = new HistogramPlotBuilder(TITLE).setNumberOfBins(settings.getHistogramBins());
        final WindowOrganiser wo = new WindowOrganiser();
        for (int ii = 0; ii < 3; ii++) {
            if (sampleNew[ii].getN() == 0) {
                continue;
            }
            final StoredDataStatistics stats = StoredDataStatistics.create(sampleNew[ii].getValues());
            builder.setData(stats).setName(NAMES[ii]).setPlotLabel("Mean = " + MathUtils.rounded(stats.getMean()) + ". Median = " + MathUtils.rounded(sampleNew[ii].getPercentile(50))).show(wo);
        }
        wo.tile();
    }
    if (size() < 2) {
        log("ERROR: Insufficient number of fitted peaks, terminating ...");
        return false;
    }
    return true;
}
Also used : InterlacedImageSource(uk.ac.sussex.gdsc.smlm.results.InterlacedImageSource) AggregatedImageSource(uk.ac.sussex.gdsc.smlm.results.AggregatedImageSource) ImageStack(ij.ImageStack) Rectangle(java.awt.Rectangle) StoredDataStatistics(uk.ac.sussex.gdsc.core.utils.StoredDataStatistics) HistogramPlotBuilder(uk.ac.sussex.gdsc.core.ij.HistogramPlot.HistogramPlotBuilder) WindowOrganiser(uk.ac.sussex.gdsc.core.ij.plugin.WindowOrganiser) IJImageSource(uk.ac.sussex.gdsc.smlm.ij.IJImageSource) ImageProcessor(ij.process.ImageProcessor) FitEngine(uk.ac.sussex.gdsc.smlm.engine.FitEngine) ConcurrentRuntimeException(org.apache.commons.lang3.concurrent.ConcurrentRuntimeException) FitConfiguration(uk.ac.sussex.gdsc.smlm.engine.FitConfiguration) ImageSource(uk.ac.sussex.gdsc.smlm.results.ImageSource) IJImageSource(uk.ac.sussex.gdsc.smlm.ij.IJImageSource) InterlacedImageSource(uk.ac.sussex.gdsc.smlm.results.InterlacedImageSource) AggregatedImageSource(uk.ac.sussex.gdsc.smlm.results.AggregatedImageSource) FitJob(uk.ac.sussex.gdsc.smlm.engine.FitJob)

Aggregations

ImageSource (uk.ac.sussex.gdsc.smlm.results.ImageSource)8 IJImageSource (uk.ac.sussex.gdsc.smlm.ij.IJImageSource)7 ImagePlus (ij.ImagePlus)6 Rectangle (java.awt.Rectangle)4 SeriesImageSource (uk.ac.sussex.gdsc.smlm.ij.SeriesImageSource)4 ImageStack (ij.ImageStack)3 PointRoi (ij.gui.PointRoi)2 ImageProcessor (ij.process.ImageProcessor)2 HistogramPlotBuilder (uk.ac.sussex.gdsc.core.ij.HistogramPlot.HistogramPlotBuilder)2 ExtendedGenericDialog (uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog)2 OffsetPointRoi (uk.ac.sussex.gdsc.core.ij.gui.OffsetPointRoi)2 StoredDataStatistics (uk.ac.sussex.gdsc.core.utils.StoredDataStatistics)2 DistanceUnit (uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.DistanceUnit)2 FitConfiguration (uk.ac.sussex.gdsc.smlm.engine.FitConfiguration)2 FitEngine (uk.ac.sussex.gdsc.smlm.engine.FitEngine)2 TFloatArrayList (gnu.trove.list.array.TFloatArrayList)1 IJ (ij.IJ)1 WindowManager (ij.WindowManager)1 GenericDialog (ij.gui.GenericDialog)1 Overlay (ij.gui.Overlay)1