Search in sources :

Example 56 with ExtendedGenericDialog

use of ij.gui.ExtendedGenericDialog in project GDSC-SMLM by aherbert.

the class SpotInspector method showDialog.

private boolean showDialog() {
    ExtendedGenericDialog gd = new ExtendedGenericDialog(TITLE);
    gd.addHelp(About.HELP_URL);
    ResultsManager.addInput(gd, inputOption, InputSource.MEMORY);
    gd.addChoice("Ranking", SORT_ORDER, SORT_ORDER[sortOrderIndex]);
    gd.addSlider("Radius", 1, 15, radius);
    gd.addCheckbox("Calibrated_table", showCalibratedValues);
    gd.addCheckbox("Plot_score", plotScore);
    gd.addCheckbox("Plot_histogram", plotHistogram);
    gd.addNumericField("Histogram_bins", histogramBins, 0);
    gd.addCheckbox("Remove_outliers", removeOutliers);
    gd.showDialog();
    if (gd.wasCanceled())
        return false;
    inputOption = ResultsManager.getInputSource(gd);
    sortOrderIndex = gd.getNextChoiceIndex();
    radius = (int) gd.getNextNumber();
    showCalibratedValues = gd.getNextBoolean();
    plotScore = gd.getNextBoolean();
    plotHistogram = gd.getNextBoolean();
    histogramBins = (int) gd.getNextNumber();
    removeOutliers = gd.getNextBoolean();
    // Check arguments
    try {
        Parameters.isAboveZero("Radius", radius);
        Parameters.isAbove("Histogram bins", histogramBins, 1);
    } catch (IllegalArgumentException ex) {
        IJ.error(TITLE, ex.getMessage());
        return false;
    }
    return true;
}
Also used : ExtendedGenericDialog(ij.gui.ExtendedGenericDialog)

Example 57 with ExtendedGenericDialog

use of ij.gui.ExtendedGenericDialog in project GDSC-SMLM by aherbert.

the class SpotInspector 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
    results = ResultsManager.loadInputResults(inputOption, false);
    if (results == null || results.size() == 0) {
        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();
    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<PeakResultRank>(results.size());
    final double a = results.getNmPerPixel();
    final double gain = results.getGain();
    final boolean emCCD = results.isEMCCD();
    for (PeakResult r : results.getResults()) {
        float[] score = getScore(r, a, gain, emCCD, stdDevMax);
        rankedResults.add(new PeakResultRank(r, score[0], score[1]));
    }
    Collections.sort(rankedResults);
    // Prepare results table. Get bias if necessary
    if (showCalibratedValues) {
        // Get a bias if required
        Calibration calibration = results.getCalibration();
        if (calibration.getBias() == 0) {
            ExtendedGenericDialog gd = new ExtendedGenericDialog(TITLE);
            gd.addMessage("Calibrated results requires a camera bias");
            gd.addNumericField("Camera_bias (ADUs)", calibration.getBias(), 2);
            gd.showDialog();
            if (!gd.wasCanceled()) {
                calibration.setBias(Math.abs(gd.getNextNumber()));
            }
        }
    }
    IJTablePeakResults table = new IJTablePeakResults(false, results.getName(), true);
    table.copySettings(results);
    table.setTableTitle(TITLE);
    table.setAddCounter(true);
    table.setShowCalibratedValues(showCalibratedValues);
    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;
    textPanel.addMouseListener(this);
    // Add results to the table
    int n = 0;
    for (PeakResultRank rank : rankedResults) {
        rank.rank = n++;
        PeakResult r = rank.peakResult;
        table.add(r.getFrame(), r.origX, r.origY, r.origValue, r.error, r.noise, r.params, r.paramsStdDev);
    }
    table.end();
    if (plotScore || plotHistogram) {
        // Get values for the plots
        float[] xValues = null, yValues = null;
        double yMin, yMax;
        int spotNumber = 0;
        xValues = new float[rankedResults.size()];
        yValues = new float[xValues.length];
        for (PeakResultRank rank : rankedResults) {
            xValues[spotNumber] = spotNumber + 1;
            yValues[spotNumber++] = recoverScore(rank.score);
        }
        // Set the min and max y-values using 1.5 x IQR 
        DescriptiveStatistics stats = new DescriptiveStatistics();
        for (float v : yValues) stats.addValue(v);
        if (removeOutliers) {
            double lower = stats.getPercentile(25);
            double upper = stats.getPercentile(75);
            double iqr = upper - lower;
            yMin = FastMath.max(lower - iqr, stats.getMin());
            yMax = FastMath.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, yMin, yMax);
    }
    // Extract spots into a stack
    final int w = source.getWidth();
    final int h = source.getHeight();
    final int size = 2 * radius + 1;
    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, new Comparator<PeakResultRank>() {

        public int compare(PeakResultRank o1, PeakResultRank o2) {
            if (o1.peakResult.getFrame() < o2.peakResult.getFrame())
                return -1;
            if (o1.peakResult.getFrame() > o2.peakResult.getFrame())
                return 1;
            return 0;
        }
    });
    for (PeakResultRank rank : rankedResults) {
        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.params[Gaussian2DFunction.X_POSITION]);
        final int y = (int) (r.params[Gaussian2DFunction.Y_POSITION]);
        // Extract a region but crop to the image bounds
        int minX = x - radius;
        int minY = y - radius;
        int maxX = FastMath.min(x + radius + 1, w);
        int maxY = FastMath.min(y + radius + 1, h);
        int padX = 0, padY = 0;
        if (minX < 0) {
            padX = -minX;
            minX = 0;
        }
        if (minY < 0) {
            padY = -minY;
            minY = 0;
        }
        int sizeX = maxX - minX;
        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) {
            ImageProcessor spotIp2 = spotIp.createProcessor(size, size);
            spotIp2.insert(spotIp, padX, padY);
            spotIp = spotIp2;
        }
        int slice = rank.rank + 1;
        spots.setPixels(spotIp.getPixels(), slice);
        spots.setSliceLabel(Utils.rounded(rank.originalScore), slice);
    }
    source.close();
    ImagePlus imp = Utils.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 : DescriptiveStatistics(org.apache.commons.math3.stat.descriptive.DescriptiveStatistics) ImageStack(ij.ImageStack) FloatProcessor(ij.process.FloatProcessor) Rectangle(java.awt.Rectangle) Calibration(gdsc.smlm.results.Calibration) ExtendedGenericDialog(ij.gui.ExtendedGenericDialog) ImagePlus(ij.ImagePlus) PeakResult(gdsc.smlm.results.PeakResult) ImageProcessor(ij.process.ImageProcessor) IJTablePeakResults(gdsc.smlm.ij.results.IJTablePeakResults) ImageSource(gdsc.smlm.results.ImageSource)

Example 58 with ExtendedGenericDialog

use of ij.gui.ExtendedGenericDialog in project GDSC-SMLM by aherbert.

the class TraceMolecules method showClusterDialog.

private boolean showClusterDialog() {
    TITLE = outputName + " Molecules";
    ExtendedGenericDialog gd = new ExtendedGenericDialog(TITLE);
    gd.addHelp(About.HELP_URL);
    ResultsManager.addInput(gd, inputOption, InputSource.MEMORY);
    globalSettings = SettingsManager.loadSettings();
    settings = globalSettings.getClusteringSettings();
    gd.addNumericField("Distance_Threshold (nm)", settings.distanceThreshold, 2);
    gd.addNumericField("Time_Threshold", settings.getTimeThreshold(), 2);
    String[] timeUnits = SettingsManager.getNames((Object[]) ClusteringSettings.TimeUnit.values());
    gd.addChoice("Time_unit", timeUnits, timeUnits[settings.getTimeUnit().ordinal()]);
    String[] algorithm = SettingsManager.getNames((Object[]) ClusteringAlgorithm.values());
    gd.addChoice("Clustering_algorithm", algorithm, algorithm[settings.getClusteringAlgorithm().ordinal()]);
    gd.addNumericField("Pulse_interval (frames)", settings.pulseInterval, 0);
    gd.addCheckbox("Split_pulses", settings.splitPulses);
    gd.addCheckbox("Save_clusters", settings.saveTraces);
    gd.addCheckbox("Show_histograms", settings.showHistograms);
    gd.addCheckbox("Save_cluster_data", settings.saveTraceData);
    gd.addCheckbox("Refit_option", settings.refitOption);
    if (altKeyDown) {
        gd.addCheckbox("Debug", inputDebugMode);
    }
    gd.showDialog();
    if (gd.wasCanceled() || !readClusterDialog(gd))
        return false;
    // Update the settings
    SettingsManager.saveSettings(globalSettings);
    // Load the results
    results = ResultsManager.loadInputResults(inputOption, true);
    if (results == null || results.size() == 0) {
        IJ.error(TITLE, "No results could be loaded");
        IJ.showStatus("");
        return false;
    }
    // Store exposure time in seconds
    exposureTime = results.getCalibration().getExposureTime() / 1000;
    return true;
}
Also used : ExtendedGenericDialog(ij.gui.ExtendedGenericDialog)

Example 59 with ExtendedGenericDialog

use of ij.gui.ExtendedGenericDialog in project GDSC-SMLM by aherbert.

the class TraceMolecules method readClusterDialog.

private boolean readClusterDialog(ExtendedGenericDialog gd) {
    inputOption = ResultsManager.getInputSource(gd);
    settings.distanceThreshold = gd.getNextNumber();
    settings.setTimeThreshold(gd.getNextNumber());
    settings.setTimeUnit(gd.getNextChoiceIndex());
    settings.setClusteringAlgorithm(gd.getNextChoiceIndex());
    settings.pulseInterval = (int) gd.getNextNumber();
    settings.splitPulses = gd.getNextBoolean();
    settings.saveTraces = gd.getNextBoolean();
    settings.showHistograms = gd.getNextBoolean();
    settings.saveTraceData = gd.getNextBoolean();
    settings.refitOption = gd.getNextBoolean();
    if (altKeyDown) {
        debugMode = inputDebugMode = gd.getNextBoolean();
    }
    if (gd.invalidNumber())
        return false;
    if (settings.showHistograms) {
        gd = new ExtendedGenericDialog(TITLE);
        gd.addMessage("Select the histograms to display");
        gd.addCheckbox("Remove_outliers", settings.removeOutliers);
        gd.addNumericField("Histogram_bins", settings.histogramBins, 0);
        for (int i = 0; i < displayHistograms.length; i++) gd.addCheckbox(NAMES[i].replace(' ', '_'), displayHistograms[i]);
        gd.showDialog();
        if (gd.wasCanceled())
            return false;
        settings.removeOutliers = gd.getNextBoolean();
        settings.histogramBins = (int) Math.abs(gd.getNextNumber());
        for (int i = 0; i < displayHistograms.length; i++) displayHistograms[i] = gd.getNextBoolean();
    }
    // Check arguments
    try {
        Parameters.isAboveZero("Distance threshold", settings.distanceThreshold);
        if (settings.getClusteringAlgorithm() == ClusteringAlgorithm.CENTROID_LINKAGE_DISTANCE_PRIORITY || settings.getClusteringAlgorithm() == ClusteringAlgorithm.CENTROID_LINKAGE_TIME_PRIORITY) {
            Parameters.isAboveZero("Time threshold", settings.getTimeThreshold());
            Parameters.isPositive("Pulse interval", settings.pulseInterval);
        }
        Parameters.isAboveZero("Histogram bins", settings.histogramBins);
    } catch (IllegalArgumentException e) {
        IJ.error(TITLE, e.getMessage());
        return false;
    }
    return true;
}
Also used : ExtendedGenericDialog(ij.gui.ExtendedGenericDialog) ClusterPoint(gdsc.core.clustering.ClusterPoint)

Example 60 with ExtendedGenericDialog

use of ij.gui.ExtendedGenericDialog in project GDSC-SMLM by aherbert.

the class TraceMolecules method getParameters.

private boolean getParameters(int n, double d) {
    ExtendedGenericDialog gd = new ExtendedGenericDialog(TITLE + " Optimiser");
    String msg = String.format("Estimate %d molecules at d=%f, t=1", n, d);
    IJ.log(msg);
    gd.addMessage(msg);
    gd.addNumericField("Min_Distance_Threshold (px)", settings.minDistanceThreshold, 2);
    gd.addNumericField("Max_Distance_Threshold (px)", settings.maxDistanceThreshold, 2);
    gd.addNumericField("Min_Time_Threshold (frames)", settings.minTimeThreshold, 0);
    gd.addNumericField("Max_Time_Threshold (frames)", settings.maxTimeThreshold, 0);
    gd.addSlider("Steps", 1, 20, settings.optimiserSteps);
    gd.addNumericField("Blinking_rate", settings.blinkingRate, 2);
    String[] plotNames = SettingsManager.getNames((Object[]) ClusteringSettings.OptimiserPlot.values());
    gd.addChoice("Plot", plotNames, plotNames[settings.getOptimiserPlot().ordinal()]);
    if (altKeyDown)
        gd.addCheckbox("Optimise_blinking", inputOptimiseBlinkingRate);
    gd.showDialog();
    if (gd.wasCanceled())
        return false;
    settings.minDistanceThreshold = gd.getNextNumber();
    settings.maxDistanceThreshold = gd.getNextNumber();
    settings.minTimeThreshold = (int) gd.getNextNumber();
    settings.maxTimeThreshold = (int) gd.getNextNumber();
    settings.optimiserSteps = (int) gd.getNextNumber();
    settings.blinkingRate = gd.getNextNumber();
    settings.setOptimiserPlot(gd.getNextChoiceIndex());
    if (altKeyDown) {
        optimiseBlinkingRate = inputOptimiseBlinkingRate = gd.getNextBoolean();
    }
    if (gd.invalidNumber())
        return false;
    if (settings.minDistanceThreshold < 0)
        settings.minDistanceThreshold = 0;
    if (settings.maxDistanceThreshold < settings.minDistanceThreshold)
        settings.maxDistanceThreshold = settings.minDistanceThreshold;
    if (settings.minTimeThreshold < 0)
        settings.minTimeThreshold = 0;
    if (settings.maxTimeThreshold < settings.minTimeThreshold)
        settings.maxTimeThreshold = settings.minTimeThreshold;
    if (settings.optimiserSteps < 0)
        settings.optimiserSteps = 1;
    if (settings.blinkingRate < MIN_BLINKING_RATE) {
        IJ.error(gd.getTitle(), "Blinking rate must be above " + MIN_BLINKING_RATE);
        return false;
    }
    if (settings.minDistanceThreshold == settings.maxDistanceThreshold && settings.minTimeThreshold == settings.maxTimeThreshold) {
        IJ.error(gd.getTitle(), "Nothing to optimise");
        return false;
    }
    SettingsManager.saveSettings(globalSettings);
    return true;
}
Also used : ExtendedGenericDialog(ij.gui.ExtendedGenericDialog)

Aggregations

ExtendedGenericDialog (ij.gui.ExtendedGenericDialog)60 ImagePlus (ij.ImagePlus)11 NonBlockingExtendedGenericDialog (ij.gui.NonBlockingExtendedGenericDialog)8 FitEngineConfiguration (gdsc.smlm.engine.FitEngineConfiguration)6 GlobalSettings (gdsc.smlm.ij.settings.GlobalSettings)6 MemoryPeakResults (gdsc.smlm.results.MemoryPeakResults)6 Calibration (gdsc.smlm.results.Calibration)5 ClusterPoint (gdsc.core.clustering.ClusterPoint)4 FitConfiguration (gdsc.smlm.fitting.FitConfiguration)4 PeakResult (gdsc.smlm.results.PeakResult)4 Rectangle (java.awt.Rectangle)4 LinkedList (java.util.LinkedList)4 ArrayList (java.util.ArrayList)3 WeightedObservedPoint (org.apache.commons.math3.fitting.WeightedObservedPoint)3 IJImageSource (gdsc.smlm.ij.IJImageSource)2 IJTablePeakResults (gdsc.smlm.ij.results.IJTablePeakResults)2 ResultsSettings (gdsc.smlm.ij.settings.ResultsSettings)2 ImageSource (gdsc.smlm.results.ImageSource)2 Trace (gdsc.smlm.results.Trace)2 Filter (gdsc.smlm.results.filter.Filter)2