Search in sources :

Example 56 with GenericDialog

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

the class BenchmarkFilterAnalysis method showIterationDialog.

private boolean showIterationDialog() {
    GenericDialog gd = new GenericDialog(TITLE);
    StringBuilder sb = new StringBuilder();
    sb.append("Iterate ").append(BenchmarkSpotFit.TITLE).append(" & ").append(TITLE).append(".\n");
    sb.append(BenchmarkSpotFit.TITLE).append(" will be run once interactively if results cannot be loaded.\n");
    sb.append(TITLE).append(" will be run once interactively to obtain settings.\n \n");
    sb.append("Configure the convergence criteria for iteration:");
    gd.addMessage(sb.toString());
    gd.addNumericField("Score_Tolerance", iterationScoreTolerance, -1);
    gd.addNumericField("Filter_Tolerance", iterationFilterTolerance, -1);
    gd.addCheckbox("Compare_Results", iterationCompareResults);
    gd.addNumericField("Compare_Distance", iterationCompareDistance, 2);
    gd.addNumericField("Iter_Max_Iterations", iterationMaxIterations, 0);
    gd.addMessage("Configure how the parameter range is updated per iteration:");
    gd.addSlider("Min_range_reduction", 0, 1, iterationMinRangeReduction);
    gd.addSlider("Min_range_reduction_iteration", 1, 10, iterationMinRangeReductionIteration);
    gd.addCheckbox("Converge_before_refit", iterationConvergeBeforeRefit);
    gd.showDialog();
    if (gd.wasCanceled())
        return false;
    iterationScoreTolerance = gd.getNextNumber();
    iterationFilterTolerance = gd.getNextNumber();
    iterationCompareResults = gd.getNextBoolean();
    iterationCompareDistance = Math.abs(gd.getNextNumber());
    iterationMaxIterations = (int) gd.getNextNumber();
    iterationMinRangeReduction = Math.abs(gd.getNextNumber());
    iterationMinRangeReductionIteration = (int) Math.abs(gd.getNextNumber());
    iterationConvergeBeforeRefit = gd.getNextBoolean();
    return true;
}
Also used : GenericDialog(ij.gui.GenericDialog) NonBlockingGenericDialog(ij.gui.NonBlockingGenericDialog)

Example 57 with GenericDialog

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

the class BenchmarkFilterAnalysis method showScoreDialog.

private boolean showScoreDialog() {
    GenericDialog gd = new GenericDialog(TITLE);
    gd.addHelp(About.HELP_URL);
    addSimulationData(gd);
    // Get the last scored filter or default to the best filter
    getScoreFilter();
    gd.addSlider("Fail_count", 0, 20, scoreFailCount);
    if (BenchmarkSpotFit.computeDoublets)
        gd.addSlider("Residuals_threshold", 0.01, 1, scoreResidualsThreshold);
    gd.addNumericField("Duplicate_distance", scoreDuplicateDistance, 2);
    gd.addTextAreas(XmlUtils.convertQuotes(scoreFilter.toXML()), null, 6, 60);
    gd.addCheckbox("Reset_filter", false);
    //gd.addCheckbox("Show_table", showResultsTable);
    gd.addCheckbox("Show_summary", showSummaryTable);
    gd.addCheckbox("Clear_tables", clearTables);
    //gd.addSlider("Summary_top_n", 0, 20, summaryTopN);
    gd.addCheckbox("Save_best_filter", saveBestFilter);
    gd.addCheckbox("Save_template", saveTemplate);
    gd.addCheckbox("Calculate_sensitivity", calculateSensitivity);
    gd.addSlider("Delta", 0.01, 1, delta);
    if (!simulationParameters.fixedDepth)
        gd.addCheckbox("Depth_recall_analysis", depthRecallAnalysis);
    gd.addCheckbox("Score_analysis", scoreAnalysis);
    gd.addChoice("Component_analysis", COMPONENT_ANALYSIS, COMPONENT_ANALYSIS[componentAnalysis]);
    gd.addStringField("Title", resultsTitle, 20);
    String[] labels = { "Show_TP", "Show_FP", "Show_FN" };
    gd.addCheckboxGroup(1, 3, labels, new boolean[] { showTP, showFP, showFN });
    // Dialog to have a reset checkbox. This reverts back to the default.
    if (Utils.isShowGenericDialog()) {
        final Checkbox cb = (Checkbox) (gd.getCheckboxes().get(0));
        @SuppressWarnings("unchecked") final Vector<TextField> v = gd.getNumericFields();
        final TextArea ta = gd.getTextArea1();
        cb.addItemListener(new ItemListener() {

            public void itemStateChanged(ItemEvent e) {
                if (cb.getState()) {
                    scoreFilter = null;
                    getScoreFilter();
                    int i = 0;
                    v.get(i++).setText(Integer.toString(scoreFailCount));
                    if (BenchmarkSpotFit.computeDoublets)
                        v.get(i++).setText(Double.toString(scoreResidualsThreshold));
                    v.get(i++).setText(Double.toString(scoreDuplicateDistance));
                    ta.setText(XmlUtils.convertQuotes(scoreFilter.toXML()));
                }
            }
        });
    }
    gd.showDialog();
    if (gd.wasCanceled())
        return false;
    scoreFailCount = (int) Math.abs(gd.getNextNumber());
    if (BenchmarkSpotFit.computeDoublets)
        scoreResidualsThreshold = Math.abs(gd.getNextNumber());
    scoreDuplicateDistance = Math.abs(gd.getNextNumber());
    String xml = gd.getNextText();
    try {
        scoreFilter = (DirectFilter) DirectFilter.fromXML(xml);
    } catch (Exception e) {
        scoreFilter = null;
        getScoreFilter();
    }
    boolean reset = gd.getNextBoolean();
    if (reset) {
        scoreFilter = null;
        getScoreFilter();
    }
    //showResultsTable = gd.getNextBoolean();
    showSummaryTable = gd.getNextBoolean();
    clearTables = gd.getNextBoolean();
    //summaryTopN = (int) Math.abs(gd.getNextNumber());
    saveBestFilter = gd.getNextBoolean();
    saveTemplate = gd.getNextBoolean();
    calculateSensitivity = gd.getNextBoolean();
    delta = gd.getNextNumber();
    if (!simulationParameters.fixedDepth)
        depthRecallAnalysis = gd.getNextBoolean();
    scoreAnalysis = gd.getNextBoolean();
    componentAnalysis = gd.getNextChoiceIndex();
    resultsTitle = gd.getNextString();
    showTP = gd.getNextBoolean();
    showFP = gd.getNextBoolean();
    showFN = gd.getNextBoolean();
    if (gd.invalidNumber())
        return false;
    resultsPrefix = BenchmarkSpotFit.resultPrefix + "\t" + resultsTitle + "\t";
    createResultsPrefix2(scoreFailCount, scoreResidualsThreshold, scoreDuplicateDistance);
    // Check there is one output
    if (!showSummaryTable && !calculateSensitivity && !saveBestFilter && !saveTemplate) {
        IJ.error(TITLE, "No output selected");
        return false;
    }
    // Check arguments
    try {
        Parameters.isAboveZero("Delta", delta);
        Parameters.isBelow("Delta", delta, 1);
    } catch (IllegalArgumentException e) {
        IJ.error(TITLE, e.getMessage());
        return false;
    }
    if (!selectTableColumns())
        return false;
    return true;
}
Also used : ItemEvent(java.awt.event.ItemEvent) TextArea(java.awt.TextArea) IOException(java.io.IOException) Checkbox(java.awt.Checkbox) GenericDialog(ij.gui.GenericDialog) NonBlockingGenericDialog(ij.gui.NonBlockingGenericDialog) TextField(java.awt.TextField) ItemListener(java.awt.event.ItemListener)

Example 58 with GenericDialog

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

the class GaussianFit method runFinal.

/**
	 * Perform fitting using the chosen maxima. Update the overlay if successful.
	 * 
	 * @param ip
	 *            The input image
	 */
private void runFinal(ImageProcessor ip) {
    ip.reset();
    Rectangle bounds = ip.getRoi();
    // Crop to the ROI
    float[] data = ImageConverter.getData(ip);
    int width = bounds.width;
    int height = bounds.height;
    // Sort the maxima
    float[] smoothData = data;
    if (getSmooth() > 0) {
        // Smoothing destructively modifies the data so create a copy
        smoothData = Arrays.copyOf(data, width * height);
        AverageFilter filter = new AverageFilter();
        //filter.blockAverage(smoothData, width, height, smooth);
        if (smooth <= border)
            filter.stripedBlockAverageInternal(smoothData, width, height, (float) smooth);
        else
            filter.stripedBlockAverage(smoothData, width, height, (float) smooth);
    }
    Sort.sort(maxIndices, smoothData);
    // Show the candidate peaks
    if (maxIndices.length > 0) {
        String message = String.format("Identified %d peaks", maxIndices.length);
        if (isLogProgress()) {
            IJ.log(message);
            for (int index : maxIndices) {
                IJ.log(String.format("  %.2f @ [%d,%d]", data[index], bounds.x + index % width, bounds.y + index / width));
            }
        }
        // Check whether to run if the number of peaks is large
        if (maxIndices.length > 10) {
            GenericDialog gd = new GenericDialog("Warning");
            gd.addMessage(message + "\nDo you want to fit?");
            gd.showDialog();
            if (gd.wasCanceled())
                return;
        }
    } else {
        IJ.log("No maxima identified");
        return;
    }
    results = new IJTablePeakResults(showDeviations, imp.getTitle() + " [" + imp.getCurrentSlice() + "]");
    results.begin();
    // Perform the Gaussian fit
    long ellapsed = 0;
    if (!singleFit) {
        if (isLogProgress())
            IJ.log("Combined fit");
        // Estimate height from smoothed data
        double[] estimatedHeights = new double[maxIndices.length];
        for (int i = 0; i < estimatedHeights.length; i++) estimatedHeights[i] = smoothData[maxIndices[i]];
        FitConfiguration config = new FitConfiguration();
        setupPeakFiltering(config);
        long time = System.nanoTime();
        double[] params = fitMultiple(data, width, height, maxIndices, estimatedHeights);
        ellapsed = System.nanoTime() - time;
        if (params != null) {
            // Copy all the valid parameters into a new array
            double[] validParams = new double[params.length];
            int c = 0;
            int validPeaks = 0;
            validParams[c++] = params[0];
            double[] initialParams = convertParameters(fitResult.getInitialParameters());
            double[] paramsDev = convertParameters(fitResult.getParameterStdDev());
            Rectangle regionBounds = new Rectangle();
            int[] xpoints = new int[maxIndices.length];
            int[] ypoints = new int[maxIndices.length];
            int nMaxima = 0;
            for (int i = 1, n = 0; i < params.length; i += 6, n++) {
                int y = maxIndices[n] / width;
                int x = maxIndices[n] % width;
                // Check the peak is a good fit
                if (filterResults && config.validatePeak(n, initialParams, params) != FitStatus.OK)
                    continue;
                if (showFit) {
                    // Copy the valid parameters
                    validPeaks++;
                    for (int ii = i, j = 0; j < 6; ii++, j++) validParams[c++] = params[ii];
                }
                double[] peakParams = extractParams(params, i);
                double[] peakParamsDev = extractParams(paramsDev, i);
                addResult(bounds, regionBounds, data, peakParams, peakParamsDev, nMaxima, x, y, data[maxIndices[n]]);
                // Add fit result to the overlay - Coords are updated with the region offsets in addResult
                double xf = peakParams[3];
                double yf = peakParams[4];
                xpoints[nMaxima] = (int) (xf + 0.5);
                ypoints[nMaxima] = (int) (yf + 0.5);
                nMaxima++;
            }
            setOverlay(nMaxima, xpoints, ypoints);
            // Draw the fit
            if (showFit && validPeaks != 0) {
                double[] pixels = new double[data.length];
                EllipticalGaussian2DFunction f = new EllipticalGaussian2DFunction(validPeaks, width, height);
                invertParameters(validParams);
                f.initialise(validParams);
                for (int x = 0; x < pixels.length; x++) pixels[x] = f.eval(x);
                FloatProcessor fp = new FloatProcessor(width, height, pixels);
                // Insert into a full size image
                FloatProcessor fp2 = new FloatProcessor(ip.getWidth(), ip.getHeight());
                fp2.insert(fp, bounds.x, bounds.y);
                Utils.display(TITLE, fp2);
            }
        } else {
            if (isLogProgress()) {
                IJ.log("Failed to fit " + Utils.pleural(maxIndices.length, "peak") + getReason(fitResult));
            }
            imp.setOverlay(null);
        }
    } else {
        if (isLogProgress())
            IJ.log("Individual fit");
        int nMaxima = 0;
        int[] xpoints = new int[maxIndices.length];
        int[] ypoints = new int[maxIndices.length];
        // Extract each peak and fit individually
        ImageExtractor ie = new ImageExtractor(data, width, height);
        float[] region = null;
        Gaussian2DFitter gf = createGaussianFitter(filterResults);
        for (int n = 0; n < maxIndices.length; n++) {
            int y = maxIndices[n] / width;
            int x = maxIndices[n] % width;
            long time = System.nanoTime();
            Rectangle regionBounds = ie.getBoxRegionBounds(x, y, singleRegionSize);
            region = ie.crop(regionBounds, region);
            int newIndex = (y - regionBounds.y) * regionBounds.width + x - regionBounds.x;
            if (isLogProgress()) {
                IJ.log("Fitting peak " + (n + 1));
            }
            double[] peakParams = fitSingle(gf, region, regionBounds.width, regionBounds.height, newIndex, smoothData[maxIndices[n]]);
            ellapsed += System.nanoTime() - time;
            // Output fit result
            if (peakParams != null) {
                double[] peakParamsDev = null;
                if (showDeviations) {
                    peakParamsDev = convertParameters(fitResult.getParameterStdDev());
                }
                addResult(bounds, regionBounds, data, peakParams, peakParamsDev, n, x, y, data[maxIndices[n]]);
                // Add fit result to the overlay - Coords are updated with the region offsets in addResult
                double xf = peakParams[3];
                double yf = peakParams[4];
                xpoints[nMaxima] = (int) (xf + 0.5);
                ypoints[nMaxima] = (int) (yf + 0.5);
                nMaxima++;
            } else {
                if (isLogProgress()) {
                    IJ.log("Failed to fit peak " + (n + 1) + getReason(fitResult));
                }
            }
        }
        // Update the overlay
        if (nMaxima > 0)
            setOverlay(nMaxima, xpoints, ypoints);
        else
            imp.setOverlay(null);
    }
    results.end();
    if (isLogProgress())
        IJ.log("Time = " + (ellapsed / 1000000.0) + "ms");
}
Also used : FloatProcessor(ij.process.FloatProcessor) EllipticalGaussian2DFunction(gdsc.smlm.function.gaussian.EllipticalGaussian2DFunction) Gaussian2DFitter(gdsc.smlm.fitting.Gaussian2DFitter) Rectangle(java.awt.Rectangle) AverageFilter(gdsc.smlm.filters.AverageFilter) IJTablePeakResults(gdsc.smlm.ij.results.IJTablePeakResults) FitConfiguration(gdsc.smlm.fitting.FitConfiguration) GenericDialog(ij.gui.GenericDialog) ImageExtractor(gdsc.core.utils.ImageExtractor)

Example 59 with GenericDialog

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

the class FilterAnalysis method showDialog.

private boolean showDialog(List<MemoryPeakResults> resultsList, boolean fileInput) {
    GenericDialog gd = new GenericDialog(TITLE);
    gd.addHelp(About.HELP_URL);
    int total = 0;
    int tp = 0;
    for (MemoryPeakResults r : resultsList) {
        total += r.size();
        for (PeakResult p : r.getResults()) if (p.origValue != 0)
            tp++;
    }
    gd.addMessage(String.format("%d files, %d results, %d True-Positives", resultsList.size(), total, tp));
    if (!fileInput) {
        gd.addCheckbox("SNR_filter", snrFilter);
        gd.addNumericField("Min_SNR", minSnr, 0);
        gd.addNumericField("Max_SNR", maxSnr, 0);
        gd.addNumericField("Min_Width", minWidth, 2);
        gd.addNumericField("Max_Width", maxWidth, 2);
        gd.addNumericField("Increment_Width", incWidth, 2);
        gd.addCheckbox("Precision_filter", precisionFilter);
        gd.addNumericField("Min_Precision", minPrecision, 0);
        gd.addNumericField("Max_Precision", maxPrecision, 0);
        gd.addCheckbox("Trace_filter", traceFilter);
        gd.addNumericField("Min_distance", minDistance, 2);
        gd.addNumericField("Max_distance", maxDistance, 2);
        gd.addNumericField("Increment_distance", incDistance, 2);
        gd.addNumericField("Min_time", minTime, 0);
        gd.addNumericField("Max_time", maxTime, 0);
        gd.addNumericField("Increment_time", incTime, 0);
        gd.addCheckbox("Hysteresis_SNR_filter", hysteresisSnrFilter);
        gd.addNumericField("Min_SNR_gap", minSnrGap, 0);
        gd.addNumericField("Max_SNR_gap", maxSnrGap, 0);
        gd.addNumericField("Increment_SNR_gap", incSnrGap, 0);
        gd.addCheckbox("Hysteresis_Precision_filter", hysteresisPrecisionFilter);
        gd.addNumericField("Min_Precision_gap", minPrecisionGap, 0);
        gd.addNumericField("Max_Precision_gap", maxPrecisionGap, 0);
        gd.addNumericField("Increment_Precision_gap", incPrecisionGap, 0);
        gd.addCheckbox("Save_filters", saveFilterSets);
    }
    gd.addCheckbox("Show_table", showResultsTable);
    gd.addSlider("Plot_top_n", 0, 20, plotTopN);
    gd.addCheckbox("Calculate_sensitivity", calculateSensitivity);
    gd.addSlider("Delta", 0.01, 1, delta);
    if (!fileInput) {
        // Re-arrange to 2 columns
        if (gd.getLayout() != null) {
            GridBagLayout grid = (GridBagLayout) gd.getLayout();
            Component splitLabel = (Component) gd.getCheckboxes().get(3);
            int xOffset = 0, yOffset = 0;
            int lastY = -1, rowCount = 0;
            for (Component comp : gd.getComponents()) {
                // Check if this should be the second major column
                if (comp == splitLabel) {
                    xOffset += 2;
                    yOffset -= rowCount;
                    rowCount = 0;
                }
                // Reposition the field
                GridBagConstraints c = grid.getConstraints(comp);
                if (lastY != c.gridy)
                    rowCount++;
                lastY = c.gridy;
                c.gridx = c.gridx + xOffset;
                c.gridy = c.gridy + yOffset;
                c.insets.left = c.insets.left + 10 * xOffset;
                c.insets.top = 0;
                c.insets.bottom = 0;
                grid.setConstraints(comp, c);
            }
            if (IJ.isLinux())
                gd.setBackground(new Color(238, 238, 238));
        }
    }
    gd.showDialog();
    if (gd.wasCanceled() || !readDialog(gd, fileInput))
        return false;
    return true;
}
Also used : GridBagConstraints(java.awt.GridBagConstraints) GridBagLayout(java.awt.GridBagLayout) GenericDialog(ij.gui.GenericDialog) Color(java.awt.Color) MemoryPeakResults(gdsc.smlm.results.MemoryPeakResults) Component(java.awt.Component) PeakResult(gdsc.smlm.results.PeakResult)

Example 60 with GenericDialog

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

the class FilterAnalysis method readResults.

private List<MemoryPeakResults> readResults() {
    if (resultsList != null && inputDirectory.equals(lastInputDirectory)) {
        GenericDialog gd = new GenericDialog(TITLE);
        gd.addMessage("Re-use results from the same directory (no to refresh)?");
        gd.enableYesNoCancel();
        gd.hideCancelButton();
        gd.showDialog();
        if (gd.wasOKed())
            return resultsList;
    }
    List<MemoryPeakResults> resultsList = new LinkedList<MemoryPeakResults>();
    File[] fileList = (new File(inputDirectory)).listFiles(new FilenameFilter() {

        public boolean accept(File dir, String name) {
            return (name.endsWith(".xls") || name.endsWith(".csv") || name.endsWith(".bin"));
        }
    });
    if (fileList != null) {
        // Exclude directories
        for (int i = 0; i < fileList.length; i++) {
            if (fileList[i].isFile()) {
                IJ.showStatus(String.format("Reading results ... %d/%d", i + 1, fileList.length));
                IJ.showProgress(i, fileList.length);
                PeakResultsReader reader = new PeakResultsReader(fileList[i].getPath());
                MemoryPeakResults results = reader.getResults();
                if (results != null && results.size() > 0) {
                    resultsList.add(results);
                }
            }
        }
    }
    IJ.showStatus("");
    IJ.showProgress(1);
    lastInputDirectory = inputDirectory;
    return resultsList;
}
Also used : FilenameFilter(java.io.FilenameFilter) GenericDialog(ij.gui.GenericDialog) MemoryPeakResults(gdsc.smlm.results.MemoryPeakResults) PeakResultsReader(gdsc.smlm.results.PeakResultsReader) File(java.io.File) LinkedList(java.util.LinkedList)

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