Search in sources :

Example 71 with GenericDialog

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

the class PSFCombiner method selectNextImage.

private boolean selectNextImage() {
    // Show a dialog allowing the user to select an input image
    if (titles.isEmpty())
        return false;
    GenericDialog gd = new GenericDialog(TITLE);
    gd.addMessage("Select the next input PSF image.\n(Each PSF must have the nm/pixel scale)");
    int n = (input.size() + 1);
    if (IJ.isMacro())
        gd.addStringField("PSF_" + n, "");
    else
        gd.addChoice("PSF_" + n, titles.toArray(new String[titles.size()]), "");
    gd.addMessage("Cancel to finish");
    gd.showDialog();
    if (gd.wasCanceled())
        return false;
    String title;
    if (IJ.isMacro())
        title = gd.getNextString();
    else
        title = gd.getNextChoice();
    // Check the image exists. If not then exit. This is mainly relevant for Macro mode since
    // the
    // loop will continue otherwise since the titles list is not empty.
    ImagePlus imp = WindowManager.getImage(title);
    if (imp == null)
        return false;
    titles.remove(title);
    input.add(new PSF(title));
    return true;
}
Also used : GenericDialog(ij.gui.GenericDialog) ImagePlus(ij.ImagePlus)

Example 72 with GenericDialog

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

the class MeanVarianceTest method run.

/*
	 * (non-Javadoc)
	 * 
	 * @see ij.plugin.PlugIn#run(java.lang.String)
	 */
public void run(String arg) {
    SMLMUsageTracker.recordPlugin(this.getClass(), arg);
    if (Utils.isExtraOptions()) {
        ImagePlus imp = WindowManager.getCurrentImage();
        if (imp.getStackSize() > 1) {
            GenericDialog gd = new GenericDialog(TITLE);
            gd.addMessage("Perform single image analysis on the current image?");
            gd.addNumericField("Bias", _bias, 0);
            gd.showDialog();
            if (gd.wasCanceled())
                return;
            singleImage = true;
            _bias = Math.abs(gd.getNextNumber());
        } else {
            IJ.error(TITLE, "Single-image mode requires a stack");
            return;
        }
    }
    List<ImageSample> images;
    String inputDirectory = "";
    if (singleImage) {
        IJ.showStatus("Loading images...");
        images = getImages();
        if (images.size() == 0) {
            IJ.error(TITLE, "Not enough images for analysis");
            return;
        }
    } else {
        inputDirectory = IJ.getDirectory("Select image series ...");
        if (inputDirectory == null)
            return;
        SeriesOpener series = new SeriesOpener(inputDirectory, false, 0);
        series.setVariableSize(true);
        if (series.getNumberOfImages() < 3) {
            IJ.error(TITLE, "Not enough images in the selected directory");
            return;
        }
        if (!IJ.showMessageWithCancel(TITLE, String.format("Analyse %d images, first image:\n%s", series.getNumberOfImages(), series.getImageList()[0]))) {
            return;
        }
        IJ.showStatus("Loading images");
        images = getImages(series);
        if (images.size() < 3) {
            IJ.error(TITLE, "Not enough images for analysis");
            return;
        }
        if (images.get(0).exposure != 0) {
            IJ.error(TITLE, "First image in series must have exposure 0 (Bias image)");
            return;
        }
    }
    boolean emMode = (arg != null && arg.contains("em"));
    GenericDialog gd = new GenericDialog(TITLE);
    gd.addMessage("Set the output options:");
    gd.addCheckbox("Show_table", showTable);
    gd.addCheckbox("Show_charts", showCharts);
    if (emMode) {
        // Ask the user for the camera gain ...
        gd.addMessage("Estimating the EM-gain requires the camera gain without EM readout enabled");
        gd.addNumericField("Camera_gain (ADU/e-)", cameraGain, 4);
    }
    gd.showDialog();
    if (gd.wasCanceled())
        return;
    showTable = gd.getNextBoolean();
    showCharts = gd.getNextBoolean();
    if (emMode) {
        cameraGain = gd.getNextNumber();
    }
    IJ.showStatus("Computing mean & variance");
    final double nImages = images.size();
    for (int i = 0; i < images.size(); i++) {
        IJ.showStatus(String.format("Computing mean & variance %d/%d", i + 1, images.size()));
        images.get(i).compute(singleImage, i / nImages, (i + 1) / nImages);
    }
    IJ.showProgress(1);
    IJ.showStatus("Computing results");
    // Allow user to input multiple bias images
    int start = 0;
    Statistics biasStats = new Statistics();
    Statistics noiseStats = new Statistics();
    final double bias;
    if (singleImage) {
        bias = _bias;
    } else {
        while (start < images.size()) {
            ImageSample sample = images.get(start);
            if (sample.exposure == 0) {
                biasStats.add(sample.means);
                for (PairSample pair : sample.samples) {
                    noiseStats.add(pair.variance);
                }
                start++;
            } else
                break;
        }
        bias = biasStats.getMean();
    }
    // Get the mean-variance data
    int total = 0;
    for (int i = start; i < images.size(); i++) total += images.get(i).samples.size();
    if (showTable && total > 2000) {
        gd = new GenericDialog(TITLE);
        gd.addMessage("Table output requires " + total + " entries.\n \nYou may want to disable the table.");
        gd.addCheckbox("Show_table", showTable);
        gd.showDialog();
        if (gd.wasCanceled())
            return;
        showTable = gd.getNextBoolean();
    }
    TextWindow results = (showTable) ? createResultsWindow() : null;
    double[] mean = new double[total];
    double[] variance = new double[mean.length];
    Statistics gainStats = (singleImage) ? new StoredDataStatistics(total) : new Statistics();
    final WeightedObservedPoints obs = new WeightedObservedPoints();
    for (int i = (singleImage) ? 0 : start, j = 0; i < images.size(); i++) {
        StringBuilder sb = (showTable) ? new StringBuilder() : null;
        ImageSample sample = images.get(i);
        for (PairSample pair : sample.samples) {
            if (j % 16 == 0)
                IJ.showProgress(j, total);
            mean[j] = pair.getMean();
            variance[j] = pair.variance;
            // Gain is in ADU / e
            double gain = variance[j] / (mean[j] - bias);
            gainStats.add(gain);
            obs.add(mean[j], variance[j]);
            if (emMode) {
                gain /= (2 * cameraGain);
            }
            if (showTable) {
                sb.append(sample.title).append("\t");
                sb.append(sample.exposure).append("\t");
                sb.append(pair.slice1).append("\t");
                sb.append(pair.slice2).append("\t");
                sb.append(IJ.d2s(pair.mean1, 2)).append("\t");
                sb.append(IJ.d2s(pair.mean2, 2)).append("\t");
                sb.append(IJ.d2s(mean[j], 2)).append("\t");
                sb.append(IJ.d2s(variance[j], 2)).append("\t");
                sb.append(Utils.rounded(gain, 4)).append("\n");
            }
            j++;
        }
        if (showTable)
            results.append(sb.toString());
    }
    IJ.showProgress(1);
    if (singleImage) {
        StoredDataStatistics stats = (StoredDataStatistics) gainStats;
        Utils.log(TITLE);
        if (emMode) {
            double[] values = stats.getValues();
            MathArrays.scaleInPlace(0.5, values);
            stats = new StoredDataStatistics(values);
        }
        if (showCharts) {
            // Plot the gain over time
            String title = TITLE + " Gain vs Frame";
            Plot2 plot = new Plot2(title, "Slice", "Gain", Utils.newArray(gainStats.getN(), 1, 1.0), stats.getValues());
            PlotWindow pw = Utils.display(title, plot);
            // Show a histogram
            String label = String.format("Mean = %s, Median = %s", Utils.rounded(stats.getMean()), Utils.rounded(stats.getMedian()));
            int id = Utils.showHistogram(TITLE, stats, "Gain", 0, 1, 100, true, label);
            if (Utils.isNewWindow()) {
                Point point = pw.getLocation();
                point.x = pw.getLocation().x;
                point.y += pw.getHeight();
                WindowManager.getImage(id).getWindow().setLocation(point);
            }
        }
        Utils.log("Single-image mode: %s camera", (emMode) ? "EM-CCD" : "Standard");
        final double gain = stats.getMedian();
        if (emMode) {
            final double totalGain = gain;
            final double emGain = totalGain / cameraGain;
            Utils.log("  Gain = 1 / %s (ADU/e-)", Utils.rounded(cameraGain, 4));
            Utils.log("  EM-Gain = %s", Utils.rounded(emGain, 4));
            Utils.log("  Total Gain = %s (ADU/e-)", Utils.rounded(totalGain, 4));
        } else {
            cameraGain = gain;
            Utils.log("  Gain = 1 / %s (ADU/e-)", Utils.rounded(cameraGain, 4));
        }
    } else {
        IJ.showStatus("Computing fit");
        // Sort
        int[] indices = rank(mean);
        mean = reorder(mean, indices);
        variance = reorder(variance, indices);
        // Compute optimal coefficients.
        // a - b x
        final double[] init = { 0, 1 / gainStats.getMean() };
        final PolynomialCurveFitter fitter = PolynomialCurveFitter.create(2).withStartPoint(init);
        final double[] best = fitter.fit(obs.toList());
        // Construct the polynomial that best fits the data.
        final PolynomialFunction fitted = new PolynomialFunction(best);
        if (showCharts) {
            // Plot mean verses variance. Gradient is gain in ADU/e.
            String title = TITLE + " results";
            Plot2 plot = new Plot2(title, "Mean", "Variance");
            double[] xlimits = Maths.limits(mean);
            double[] ylimits = Maths.limits(variance);
            double xrange = (xlimits[1] - xlimits[0]) * 0.05;
            if (xrange == 0)
                xrange = 0.05;
            double yrange = (ylimits[1] - ylimits[0]) * 0.05;
            if (yrange == 0)
                yrange = 0.05;
            plot.setLimits(xlimits[0] - xrange, xlimits[1] + xrange, ylimits[0] - yrange, ylimits[1] + yrange);
            plot.setColor(Color.blue);
            plot.addPoints(mean, variance, Plot2.CROSS);
            plot.setColor(Color.red);
            plot.addPoints(new double[] { mean[0], mean[mean.length - 1] }, new double[] { fitted.value(mean[0]), fitted.value(mean[mean.length - 1]) }, Plot2.LINE);
            Utils.display(title, plot);
        }
        final double avBiasNoise = Math.sqrt(noiseStats.getMean());
        Utils.log(TITLE);
        Utils.log("  Directory = %s", inputDirectory);
        Utils.log("  Bias = %s +/- %s (ADU)", Utils.rounded(bias, 4), Utils.rounded(avBiasNoise, 4));
        Utils.log("  Variance = %s + %s * mean", Utils.rounded(best[0], 4), Utils.rounded(best[1], 4));
        if (emMode) {
            final double emGain = best[1] / (2 * cameraGain);
            // Noise is standard deviation of the bias image divided by the total gain (in ADU/e-)
            final double totalGain = emGain * cameraGain;
            Utils.log("  Read Noise = %s (e-) [%s (ADU)]", Utils.rounded(avBiasNoise / totalGain, 4), Utils.rounded(avBiasNoise, 4));
            Utils.log("  Gain = 1 / %s (ADU/e-)", Utils.rounded(1 / cameraGain, 4));
            Utils.log("  EM-Gain = %s", Utils.rounded(emGain, 4));
            Utils.log("  Total Gain = %s (ADU/e-)", Utils.rounded(totalGain, 4));
        } else {
            // Noise is standard deviation of the bias image divided by the gain (in ADU/e-)
            cameraGain = best[1];
            final double readNoise = avBiasNoise / cameraGain;
            Utils.log("  Read Noise = %s (e-) [%s (ADU)]", Utils.rounded(readNoise, 4), Utils.rounded(readNoise * cameraGain, 4));
            Utils.log("  Gain = 1 / %s (ADU/e-)", Utils.rounded(1 / cameraGain, 4));
        }
    }
    IJ.showStatus("");
}
Also used : StoredDataStatistics(gdsc.core.utils.StoredDataStatistics) PlotWindow(ij.gui.PlotWindow) PolynomialFunction(org.apache.commons.math3.analysis.polynomials.PolynomialFunction) SeriesOpener(gdsc.smlm.ij.utils.SeriesOpener) Plot2(ij.gui.Plot2) Point(java.awt.Point) ImagePlus(ij.ImagePlus) StoredDataStatistics(gdsc.core.utils.StoredDataStatistics) Statistics(gdsc.core.utils.Statistics) Point(java.awt.Point) PolynomialCurveFitter(org.apache.commons.math3.fitting.PolynomialCurveFitter) WeightedObservedPoints(org.apache.commons.math3.fitting.WeightedObservedPoints) TextWindow(ij.text.TextWindow) GenericDialog(ij.gui.GenericDialog)

Example 73 with GenericDialog

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

the class MedianFilter method showDialog.

private int showDialog() {
    GenericDialog gd = new GenericDialog(TITLE);
    gd.addHelp(About.HELP_URL);
    gd.addMessage("Compute the median using a rolling window at set intervals.\nBlocks of pixels are processed on separate threads.");
    gd.addSlider("Radius", 10, 100, radius);
    gd.addSlider("Interval", 10, 30, interval);
    gd.addSlider("Block_size", 1, 32, blockSize);
    gd.addCheckbox("Subtract", subtract);
    gd.addSlider("Bias", 0, 1000, bias);
    gd.showDialog();
    if (gd.wasCanceled())
        return DONE;
    radius = (int) Math.abs(gd.getNextNumber());
    interval = (int) Math.abs(gd.getNextNumber());
    blockSize = (int) Math.abs(gd.getNextNumber());
    if (blockSize < 1)
        blockSize = 1;
    subtract = gd.getNextBoolean();
    bias = (float) Math.abs(gd.getNextNumber());
    if (gd.invalidNumber() || interval < 1 || radius < 1)
        return DONE;
    // Check the window size is smaller than the stack size
    if (imp.getStackSize() < 2 * radius + 1) {
        IJ.error(TITLE, "The window size is larger than the stack size.\nThis is equal to a z-stack median projection.");
        return DONE;
    }
    return FLAGS;
}
Also used : GenericDialog(ij.gui.GenericDialog)

Example 74 with GenericDialog

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

the class PSFCreator method ignoreSpot.

private boolean ignoreSpot(int n, final double[] z, final double[] a, final double[] smoothA, final double[] xCoord, final double[] yCoord, final double[] sd, final double[] newZ, final double[] smoothX, final double[] smoothY, double[] smoothSd, final double cx, final double cy, final int cz, double csd) {
    this.slice = cz;
    // the addition of the data
    if (interactiveMode) {
        zCentre = cz;
        psfWidth = csd * nmPerPixel;
        // Store the data for replotting
        this.z = z;
        this.a = a;
        this.smoothAz = z;
        this.smoothA = smoothA;
        this.xCoord = xCoord;
        this.yCoord = yCoord;
        this.sd = sd;
        this.newZ = newZ;
        this.smoothX = smoothX;
        this.smoothY = smoothY;
        this.smoothSd = smoothSd;
        showPlots(z, a, z, smoothA, xCoord, yCoord, sd, newZ, smoothX, smoothY, smoothSd, cz);
        // Draw the region on the input image as an overlay
        imp.setSlice(cz);
        imp.setOverlay(new Roi((int) (cx - boxRadius), (int) (cy - boxRadius), 2 * boxRadius + 1, 2 * boxRadius + 1), Color.GREEN, 1, null);
        // Ask if the spot should be included
        GenericDialog gd = new GenericDialog(TITLE);
        gd.enableYesNoCancel();
        gd.hideCancelButton();
        gd.addMessage(String.format("Add spot %d to the PSF?\n \nEstimated centre using min PSF width:\n \nx = %.2f\ny = %.2f\nz = %d\nsd = %.2f\n", n, cx, cy, cz, csd));
        gd.addSlider("Slice", z[0], z[z.length - 1], slice);
        if (yesNoPosition != null) {
            gd.centerDialog(false);
            gd.setLocation(yesNoPosition);
        }
        gd.addDialogListener(new SimpleInteractivePlotListener());
        gd.showDialog();
        yesNoPosition = gd.getLocation();
        return !gd.wasOKed();
    }
    return false;
}
Also used : GenericDialog(ij.gui.GenericDialog) Roi(ij.gui.Roi) PolygonRoi(ij.gui.PolygonRoi)

Example 75 with GenericDialog

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

the class PSFCreator method createInteractivePlots.

private void createInteractivePlots(ImageStack psf, int zCentre, double nmPerPixel, double psfWidth) {
    this.psf = psf;
    this.zCentre = zCentre;
    this.psfNmPerPixel = nmPerPixel;
    this.psfWidth = psfWidth;
    this.slice = zCentre;
    this.distanceThreshold = psfWidth * 3;
    GenericDialog gd = new GenericDialog(TITLE);
    gd.addMessage("Plot the cumulative signal verses distance from the PSF centre.\n \nZ-centre = " + zCentre + "\nPSF width = " + Utils.rounded(psfWidth) + " nm");
    gd.addSlider("Slice", 1, psf.getSize(), slice);
    final double maxDistance = (psf.getWidth() / 1.414213562) * nmPerPixel;
    gd.addSlider("Distance", 0, maxDistance, distanceThreshold);
    gd.addCheckbox("Normalise", normalise);
    gd.addDialogListener(new InteractivePlotListener());
    if (!IJ.isMacro())
        drawPlots(true);
    gd.showDialog();
    if (gd.wasCanceled())
        return;
    drawPlots(true);
}
Also used : GenericDialog(ij.gui.GenericDialog)

Aggregations

GenericDialog (ij.gui.GenericDialog)87 NonBlockingGenericDialog (ij.gui.NonBlockingGenericDialog)12 ExtendedGenericDialog (ij.gui.ExtendedGenericDialog)10 GlobalSettings (gdsc.smlm.ij.settings.GlobalSettings)9 Checkbox (java.awt.Checkbox)9 Color (java.awt.Color)8 Component (java.awt.Component)8 GridBagConstraints (java.awt.GridBagConstraints)8 GridBagLayout (java.awt.GridBagLayout)8 Rectangle (java.awt.Rectangle)7 BasePoint (gdsc.core.match.BasePoint)6 FitConfiguration (gdsc.smlm.fitting.FitConfiguration)6 PeakResultPoint (gdsc.smlm.ij.plugins.ResultsMatchCalculator.PeakResultPoint)6 Calibration (gdsc.smlm.results.Calibration)6 ArrayList (java.util.ArrayList)6 PeakResult (gdsc.smlm.results.PeakResult)5 TextField (java.awt.TextField)5 File (java.io.File)5 Vector (java.util.Vector)5 FitEngineConfiguration (gdsc.smlm.engine.FitEngineConfiguration)4