Search in sources :

Example 1 with LUT

use of ij.process.LUT in project GDSC-SMLM by aherbert.

the class DrawClusters method run.

/*
	 * (non-Javadoc)
	 * 
	 * @see ij.plugin.PlugIn#run(java.lang.String)
	 */
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(inputOption, false);
    if (results == null || results.size() == 0) {
        IJ.error(TITLE, "No results could be loaded");
        return;
    }
    // Get the traces
    Trace[] traces = TraceManager.convert(results);
    if (traces == null || traces.length == 0) {
        IJ.error(TITLE, "No traces could be loaded");
        return;
    }
    // Filter traces to a min size
    int maxFrame = 0;
    int count = 0;
    final int myMaxSize = (maxSize < minSize) ? Integer.MAX_VALUE : maxSize;
    final boolean myDrawLines = (myMaxSize < 2) ? false : drawLines;
    for (int i = 0; i < traces.length; i++) {
        if (expandToSingles)
            traces[i].expandToSingles();
        if (traces[i].size() >= minSize && traces[i].size() <= myMaxSize) {
            traces[count++] = traces[i];
            traces[i].sort();
            if (maxFrame < traces[i].getTail().getFrame())
                maxFrame = traces[i].getTail().getFrame();
        }
    }
    if (count == 0) {
        IJ.error(TITLE, "No traces achieved the size limits");
        return;
    }
    String msg = String.format(TITLE + ": %d / %s (%s)", count, Utils.pleural(traces.length, "trace"), Utils.pleural(results.size(), "localisation"));
    IJ.showStatus(msg);
    //Utils.log(msg);
    Rectangle bounds = results.getBounds(true);
    ImagePlus imp = WindowManager.getImage(title);
    boolean isUseStackPosition = useStackPosition;
    if (imp == null) {
        // Create a default image using 100 pixels as the longest edge
        double maxD = (bounds.width > bounds.height) ? bounds.width : bounds.height;
        int w, h;
        if (maxD == 0) {
            // Note that imageSize can be zero (for auto sizing)
            w = h = (imageSize == 0) ? 20 : imageSize;
        } else {
            // Note that imageSize can be zero (for auto sizing)
            if (imageSize == 0) {
                w = bounds.width;
                h = bounds.height;
            } else {
                w = (int) (imageSize * bounds.width / maxD);
                h = (int) (imageSize * bounds.height / maxD);
            }
        }
        ByteProcessor bp = new ByteProcessor(w, h);
        if (isUseStackPosition) {
            ImageStack stack = new ImageStack(w, h, maxFrame);
            for (int i = 1; i <= maxFrame; i++) // Do not clone as the image is empty
            stack.setPixels(bp.getPixels(), i);
            imp = Utils.display(TITLE, stack);
        } else
            imp = Utils.display(TITLE, bp);
        // Enlarge
        ImageWindow iw = imp.getWindow();
        for (int i = 9; i-- > 0 && iw.getWidth() < 500 && iw.getHeight() < 500; ) {
            iw.getCanvas().zoomIn(imp.getWidth() / 2, imp.getHeight() / 2);
        }
    } else {
        // Check if the image has enough frames for all the traces
        if (maxFrame > imp.getNFrames())
            isUseStackPosition = false;
    }
    final float xScale = (float) (imp.getWidth() / bounds.getWidth());
    final float yScale = (float) (imp.getHeight() / bounds.getHeight());
    // Create ROIs and store data to sort them
    Roi[] rois = new Roi[count];
    int[][] frames = (isUseStackPosition) ? new int[count][] : null;
    int[] indices = Utils.newArray(count, 0, 1);
    double[] values = new double[count];
    for (int i = 0; i < count; i++) {
        Trace trace = traces[i];
        int nPoints = trace.size();
        float[] xPoints = new float[nPoints];
        float[] yPoints = new float[nPoints];
        int j = 0;
        if (isUseStackPosition)
            frames[i] = new int[nPoints];
        for (PeakResult result : trace.getPoints()) {
            xPoints[j] = (result.getXPosition() - bounds.x) * xScale;
            yPoints[j] = (result.getYPosition() - bounds.y) * yScale;
            if (isUseStackPosition)
                frames[i][j] = result.getFrame();
            j++;
        }
        Roi roi;
        if (myDrawLines) {
            roi = new PolygonRoi(xPoints, yPoints, nPoints, Roi.POLYLINE);
            if (splineFit)
                ((PolygonRoi) roi).fitSpline();
        } else {
            roi = new PointRoi(xPoints, yPoints, nPoints);
            ((PointRoi) roi).setShowLabels(false);
        }
        rois[i] = roi;
        switch(sort) {
            case 0:
            default:
                break;
            case // Sort by ID
            1:
                values[i] = traces[i].getId();
                break;
            case // Sort by time
            2:
                values[i] = traces[i].getHead().getFrame();
                break;
            case // Sort by size descending
            3:
                values[i] = -traces[i].size();
                break;
            case // Sort by length descending
            4:
                values[i] = -roi.getLength();
                break;
            case // Mean Square Displacement
            5:
                values[i] = -traces[i].getMSD();
                break;
            case // Mean / Frame
            6:
                values[i] = -traces[i].getMeanPerFrame();
                break;
        }
    }
    if (sort > 0)
        Sort.sort(indices, values);
    // Draw the traces as ROIs on an overlay
    Overlay o = new Overlay();
    LUT lut = LUTHelper.createLUT(DrawClusters.lut);
    final double scale = 256.0 / count;
    if (isUseStackPosition) {
        // Add the tracks on the frames containing the results
        final boolean isHyperStack = imp.isDisplayedHyperStack();
        for (int i = 0; i < count; i++) {
            final int index = indices[i];
            final Color c = LUTHelper.getColour(lut, (int) (i * scale));
            final PolygonRoi roi = (PolygonRoi) rois[index];
            roi.setFillColor(c);
            roi.setStrokeColor(c);
            final FloatPolygon fp = roi.getNonSplineFloatPolygon();
            // For each frame in the track, add the ROI track and a point ROI for the current position
            for (int j = 0; j < frames[index].length; j++) {
                addToOverlay(o, (Roi) roi.clone(), isHyperStack, frames[index][j]);
                //PointRoi pointRoi = new PointRoi(pos.x + fp.xpoints[j], pos.y + fp.ypoints[j]);
                PointRoi pointRoi = new PointRoi(fp.xpoints[j], fp.ypoints[j]);
                pointRoi.setPointType(3);
                pointRoi.setFillColor(c);
                pointRoi.setStrokeColor(Color.black);
                addToOverlay(o, pointRoi, isHyperStack, frames[index][j]);
            }
        }
    } else {
        // Add the tracks as a single overlay
        for (int i = 0; i < count; i++) {
            final Roi roi = rois[indices[i]];
            roi.setStrokeColor(new Color(lut.getRGB((int) (i * scale))));
            o.add(roi);
        }
    }
    imp.setOverlay(o);
    IJ.showStatus(msg);
}
Also used : ByteProcessor(ij.process.ByteProcessor) ImageWindow(ij.gui.ImageWindow) Rectangle(java.awt.Rectangle) PeakResult(gdsc.smlm.results.PeakResult) PolygonRoi(ij.gui.PolygonRoi) MemoryPeakResults(gdsc.smlm.results.MemoryPeakResults) Overlay(ij.gui.Overlay) PointRoi(ij.gui.PointRoi) ImageStack(ij.ImageStack) Color(java.awt.Color) LUT(ij.process.LUT) ImagePlus(ij.ImagePlus) PolygonRoi(ij.gui.PolygonRoi) PointRoi(ij.gui.PointRoi) Roi(ij.gui.Roi) Trace(gdsc.smlm.results.Trace) FloatPolygon(ij.process.FloatPolygon)

Example 2 with LUT

use of ij.process.LUT in project GDSC-SMLM by aherbert.

the class FIRE method run.

/*
	 * (non-Javadoc)
	 * 
	 * @see ij.plugin.PlugIn#run(java.lang.String)
	 */
public void run(String arg) {
    extraOptions = Utils.isExtraOptions();
    SMLMUsageTracker.recordPlugin(this.getClass(), arg);
    // Require some fit results and selected regions
    int size = MemoryPeakResults.countMemorySize();
    if (size == 0) {
        IJ.error(TITLE, "There are no fitting results in memory");
        return;
    }
    if ("q".equals(arg)) {
        TITLE += " Q estimation";
        runQEstimation();
        return;
    }
    IJ.showStatus(TITLE + " ...");
    if (!showInputDialog())
        return;
    MemoryPeakResults results = ResultsManager.loadInputResults(inputOption, false);
    if (results == null || results.size() == 0) {
        IJ.error(TITLE, "No results could be loaded");
        return;
    }
    MemoryPeakResults results2 = ResultsManager.loadInputResults(inputOption2, false);
    results = cropToRoi(results);
    if (results.size() < 2) {
        IJ.error(TITLE, "No results within the crop region");
        return;
    }
    if (results2 != null) {
        results2 = cropToRoi(results2);
        if (results2.size() < 2) {
            IJ.error(TITLE, "No results2 within the crop region");
            return;
        }
    }
    initialise(results, results2);
    if (!showDialog())
        return;
    long start = System.currentTimeMillis();
    // Compute FIRE
    String name = results.getName();
    double fourierImageScale = SCALE_VALUES[imageScaleIndex];
    int imageSize = IMAGE_SIZE_VALUES[imageSizeIndex];
    if (this.results2 != null) {
        name += " vs " + results2.getName();
        FireResult result = calculateFireNumber(fourierMethod, samplingMethod, thresholdMethod, fourierImageScale, imageSize);
        if (result != null) {
            logResult(name, result);
            if (showFRCCurve)
                showFrcCurve(name, result, thresholdMethod);
        }
    } else {
        FireResult result = null;
        int repeats = (randomSplit) ? Math.max(1, FIRE.repeats) : 1;
        if (repeats == 1) {
            result = calculateFireNumber(fourierMethod, samplingMethod, thresholdMethod, fourierImageScale, imageSize);
            if (result != null) {
                logResult(name, result);
                if (showFRCCurve)
                    showFrcCurve(name, result, thresholdMethod);
            }
        } else {
            // Multi-thread this ... 			
            int nThreads = Maths.min(repeats, getThreads());
            ExecutorService executor = Executors.newFixedThreadPool(nThreads);
            TurboList<Future<?>> futures = new TurboList<Future<?>>(repeats);
            TurboList<FIREWorker> workers = new TurboList<FIREWorker>(repeats);
            setProgress(repeats);
            IJ.showProgress(0);
            IJ.showStatus(TITLE + " computing ...");
            for (int i = 1; i <= repeats; i++) {
                FIREWorker w = new FIREWorker(i, fourierImageScale, imageSize);
                workers.add(w);
                futures.add(executor.submit(w));
            }
            // Wait for all to finish
            for (int t = futures.size(); t-- > 0; ) {
                try {
                    // The future .get() method will block until completed
                    futures.get(t).get();
                } catch (Exception e) {
                    // This should not happen. 
                    // Ignore it and allow processing to continue (the number of neighbour samples will just be smaller).  
                    e.printStackTrace();
                }
            }
            IJ.showProgress(1);
            executor.shutdown();
            // Show a combined FRC curve plot of all the smoothed curves if we have multiples.
            LUT valuesLUT = LUTHelper.createLUT(LutColour.FIRE_GLOW);
            @SuppressWarnings("unused") LUT // Black at max value
            noSmoothLUT = LUTHelper.createLUT(LutColour.GRAYS).createInvertedLut();
            LUTHelper.DefaultLUTMapper mapper = new LUTHelper.DefaultLUTMapper(0, repeats);
            FrcCurve curve = new FrcCurve();
            Statistics stats = new Statistics();
            WindowOrganiser wo = new WindowOrganiser();
            boolean oom = false;
            for (int i = 0; i < repeats; i++) {
                FIREWorker w = workers.get(i);
                if (w.oom)
                    oom = true;
                if (w.result == null)
                    continue;
                result = w.result;
                if (!Double.isNaN(result.fireNumber))
                    stats.add(result.fireNumber);
                if (showFRCCurveRepeats) {
                    // Output each FRC curve using a suffix.
                    logResult(w.name, result);
                    wo.add(Utils.display(w.plot.getTitle(), w.plot));
                }
                if (showFRCCurve) {
                    int index = mapper.map(i + 1);
                    //@formatter:off
                    curve.add(name, result, thresholdMethod, LUTHelper.getColour(valuesLUT, index), Color.blue, //LUTHelper.getColour(noSmoothLUT, index)
                    null);
                //@formatter:on
                }
            }
            if (result != null) {
                wo.cascade();
                double mean = stats.getMean();
                logResult(name, result, mean, stats);
                if (showFRCCurve) {
                    curve.addResolution(mean);
                    Plot2 plot = curve.getPlot();
                    Utils.display(plot.getTitle(), plot);
                }
            }
            if (oom) {
                //@formatter:off
                IJ.error(TITLE, "ERROR - Parallel computation out-of-memory.\n \n" + TextUtils.wrap("The number of results will be reduced. " + "Please reduce the size of the Fourier image " + "or change the number of threads " + "using the extra options (hold down the 'Shift' " + "key when running the plugin).", 80));
            //@formatter:on
            }
        }
        // Only do this once
        if (showFRCTimeEvolution && result != null && !Double.isNaN(result.fireNumber))
            showFrcTimeEvolution(name, result.fireNumber, thresholdMethod, nmPerPixel / result.getNmPerPixel(), imageSize);
    }
    IJ.showStatus(TITLE + " complete : " + Utils.timeToString(System.currentTimeMillis() - start));
}
Also used : TurboList(gdsc.core.utils.TurboList) LUTHelper(ij.process.LUTHelper) LUT(ij.process.LUT) WindowOrganiser(ij.plugin.WindowOrganiser) Plot2(ij.gui.Plot2) Statistics(gdsc.core.utils.Statistics) StoredDataStatistics(gdsc.core.utils.StoredDataStatistics) DescriptiveStatistics(org.apache.commons.math3.stat.descriptive.DescriptiveStatistics) WeightedObservedPoint(org.apache.commons.math3.fitting.WeightedObservedPoint) TooManyEvaluationsException(org.apache.commons.math3.exception.TooManyEvaluationsException) ExecutorService(java.util.concurrent.ExecutorService) Future(java.util.concurrent.Future) MemoryPeakResults(gdsc.smlm.results.MemoryPeakResults)

Example 3 with LUT

use of ij.process.LUT in project GDSC-SMLM by aherbert.

the class PeakFit method addSingleFrameOverlay.

private void addSingleFrameOverlay() {
    // If a single frame was processed add the peaks as an overlay if they are in memory
    ImagePlus imp = this.imp;
    if (fitMaxima && singleFrame > 0) {
        if (source instanceof IJImageSource) {
            String title = source.getName();
            imp = WindowManager.getImage(title);
        }
    }
    if (singleFrame > 0 && imp != null) {
        MemoryPeakResults results = null;
        for (PeakResults r : this.results.toArray()) if (r instanceof MemoryPeakResults) {
            results = (MemoryPeakResults) r;
            break;
        }
        if (results == null || results.size() == 0)
            return;
        ExtendedGenericDialog gd = new ExtendedGenericDialog(TITLE);
        gd.enableYesNoCancel();
        gd.hideCancelButton();
        gd.addMessage("Add the fitted localisations as an overlay?");
        gd.showDialog();
        if (!gd.wasOKed())
            return;
        LUT lut = LUTHelper.createLUT(LutColour.ICE);
        Overlay o = new Overlay();
        ArrayList<PeakResult> list = (ArrayList<PeakResult>) results.getResults();
        for (int i = 0, j = results.size() - 1; i < results.size(); i++, j--) {
            PeakResult r = list.get(i);
            PointRoi roi = new PointRoi(r.getXPosition(), r.getYPosition());
            Color c = LUTHelper.getColour(lut, j, results.size());
            roi.setStrokeColor(c);
            roi.setFillColor(c);
            if (imp.getStackSize() > 1)
                roi.setPosition(singleFrame);
            o.add(roi);
        }
        imp.setOverlay(o);
        imp.getWindow().toFront();
    }
}
Also used : Color(java.awt.Color) SystemColor(java.awt.SystemColor) ArrayList(java.util.ArrayList) LUT(ij.process.LUT) ExtendedGenericDialog(ij.gui.ExtendedGenericDialog) ImagePlus(ij.ImagePlus) PeakResult(gdsc.smlm.results.PeakResult) ExtendedPeakResult(gdsc.smlm.results.ExtendedPeakResult) IJImageSource(gdsc.smlm.ij.IJImageSource) PeakResults(gdsc.smlm.results.PeakResults) IJTablePeakResults(gdsc.smlm.ij.results.IJTablePeakResults) MemoryPeakResults(gdsc.smlm.results.MemoryPeakResults) IJImagePeakResults(gdsc.smlm.ij.results.IJImagePeakResults) BinaryFilePeakResults(gdsc.smlm.results.BinaryFilePeakResults) MALKFilePeakResults(gdsc.smlm.results.MALKFilePeakResults) FilePeakResults(gdsc.smlm.results.FilePeakResults) MemoryPeakResults(gdsc.smlm.results.MemoryPeakResults) Overlay(ij.gui.Overlay) PointRoi(ij.gui.PointRoi)

Aggregations

MemoryPeakResults (gdsc.smlm.results.MemoryPeakResults)3 LUT (ij.process.LUT)3 PeakResult (gdsc.smlm.results.PeakResult)2 ImagePlus (ij.ImagePlus)2 Overlay (ij.gui.Overlay)2 PointRoi (ij.gui.PointRoi)2 Color (java.awt.Color)2 Statistics (gdsc.core.utils.Statistics)1 StoredDataStatistics (gdsc.core.utils.StoredDataStatistics)1 TurboList (gdsc.core.utils.TurboList)1 IJImageSource (gdsc.smlm.ij.IJImageSource)1 IJImagePeakResults (gdsc.smlm.ij.results.IJImagePeakResults)1 IJTablePeakResults (gdsc.smlm.ij.results.IJTablePeakResults)1 BinaryFilePeakResults (gdsc.smlm.results.BinaryFilePeakResults)1 ExtendedPeakResult (gdsc.smlm.results.ExtendedPeakResult)1 FilePeakResults (gdsc.smlm.results.FilePeakResults)1 MALKFilePeakResults (gdsc.smlm.results.MALKFilePeakResults)1 PeakResults (gdsc.smlm.results.PeakResults)1 Trace (gdsc.smlm.results.Trace)1 ImageStack (ij.ImageStack)1