Search in sources :

Example 66 with GenericDialog

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

the class CreateData method showLoadDialog.

/**
	 * Show a dialog allowing the parameters for a benchmark simulation to be loaded
	 * 
	 * @return True if the parameters were collected
	 */
private boolean showLoadDialog() {
    GenericDialog gd = new GenericDialog(TITLE);
    String[] images = Utils.getImageList(Utils.GREY_SCALE);
    gd.addChoice("Image", images, benchmarkImage);
    gd.addStringField("Results_file", benchmarkFile);
    gd.addCheckbox("Preprocessed_results", benchmarkAuto);
    if (Utils.isShowGenericDialog()) {
        // Add a listener to allow selection of the file
        @SuppressWarnings("unchecked") Vector<TextField> texts = (Vector<TextField>) gd.getStringFields();
        TextField textFile = texts.get(0);
        textFile.addMouseListener(this);
    }
    gd.showDialog();
    if (gd.wasCanceled())
        return false;
    benchmarkImage = gd.getNextChoice();
    benchmarkFile = gd.getNextString();
    benchmarkAuto = gd.getNextBoolean();
    return true;
}
Also used : GenericDialog(ij.gui.GenericDialog) TextField(java.awt.TextField) Vector(java.util.Vector)

Example 67 with GenericDialog

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

the class BenchmarkFilterAnalysis method iterate.

private void iterate() {
    // If this is run again immediately then provide options for reporting the results
    if (iterBestFilter != null && iterBestFilter == bestFilter) {
        GenericDialog gd = new GenericDialog(TITLE);
        gd.enableYesNoCancel();
        gd.addMessage("Iteration results are held in memory.\n \nReport these results?");
        gd.showDialog();
        if (gd.wasCanceled())
            return;
        if (gd.wasOKed()) {
            reportIterationResults();
            return;
        }
    }
    // TODO - collect this in the iteration dialog
    if (!showIterationDialog())
        return;
    // Total the time from the interactive plugins
    long time = 0;
    // Run the benchmark fit once interactively, keep the instance
    BenchmarkSpotFit fit = new BenchmarkSpotFit();
    // than has been optimised before)
    if (fit.resetMultiPathFilter() || invalidBenchmarkSpotFitResults(true)) {
        fit.run(null);
        if (!fit.finished)
            // The plugin did not complete
            return;
        resetParametersFromFitting();
    }
    if (invalidBenchmarkSpotFitResults(false))
        return;
    if (BenchmarkSpotFit.stopWatch != null)
        time += BenchmarkSpotFit.stopWatch.getTime();
    // Run filter analysis once interactively
    if (!loadFitResults())
        return;
    // Collect parameters for optimising the parameters
    if (!showDialog(FLAG_OPTIMISE_FILTER | FLAG_OPTIMISE_PARAMS))
        return;
    // Load filters from file
    List<FilterSet> filterSets = readFilterSets();
    if (filterSets == null || filterSets.isEmpty()) {
        IJ.error(TITLE, "No filters specified");
        return;
    }
    ComplexFilterScore current = analyse(filterSets);
    if (current == null)
        return;
    time += filterAnalysisStopWatch.getTime();
    current = analyseParameters(current);
    if (current == null)
        return;
    time += parameterAnalysisStopWatch.getTime();
    // Time the non-interactive plugins as a continuous section
    iterationStopWatch = StopWatch.createStarted();
    // Remove the previous iteration results
    iterBestFilter = null;
    Utils.log(TITLE + " Iterating ...");
    IterationConvergenceChecker checker = new IterationConvergenceChecker(current);
    // Iterate ...
    boolean outerConverged = false;
    int outerIteration = 1;
    double outerRangeReduction = 1;
    while (!outerConverged) {
        if (iterationConvergeBeforeRefit) {
            // Optional inner loop so that the non-filter and filter parameters converge
            // before a refit
            boolean innerConverged = false;
            int innerIteration = 0;
            double innerRangeReduction = 1;
            if (iterationMinRangeReduction < 1) {
                // Linear interpolate down to the min range reduction
                innerRangeReduction = Maths.max(iterationMinRangeReduction, Maths.interpolateY(0, 1, iterationMinRangeReductionIteration, iterationMinRangeReduction, innerIteration++));
            // This would make the range too small...
            //innerRangeReduction *= outerRangeReduction;
            }
            while (!innerConverged) {
                ComplexFilterScore previous = current;
                // Re-use the filters as the user may be loading a custom set.
                current = analyse(filterSets, current, innerRangeReduction);
                if (current == null)
                    break;
                double[] previousParameters = createParameters();
                current = analyseParameters(current, innerRangeReduction);
                if (current == null)
                    return;
                double[] currentParameters = createParameters();
                innerConverged = checker.converged("Filter", previous, current, previousParameters, currentParameters);
            }
            // Check if we can continue (e.g. not max iterations or escape pressed) 
            if (!checker.canContinue)
                break;
        }
        // Do the fit (using the current optimum filter)
        fit.run(current.r.filter, residualsThreshold, failCount, duplicateDistance);
        if (invalidBenchmarkSpotFitResults(false))
            return;
        if (!loadFitResults())
            return;
        // is centred around the current optimum.
        if (iterationMinRangeReduction < 1) {
            // Linear interpolate down to the min range reduction
            outerRangeReduction = Maths.max(iterationMinRangeReduction, Maths.interpolateY(0, 1, iterationMinRangeReductionIteration, iterationMinRangeReduction, outerIteration++));
        }
        // Optimise the filter again.
        ComplexFilterScore previous = current;
        // Re-use the filters as the user may be loading a custom set.
        current = analyse(filterSets, current, outerRangeReduction);
        if (current == null)
            break;
        double[] previousParameters = createParameters();
        current = analyseParameters(current, outerRangeReduction);
        if (current == null)
            return;
        double[] currentParameters = createParameters();
        outerConverged = checker.converged("Fit+Filter", previous, current, previousParameters, currentParameters);
    }
    if (current != null) //if (converged)
    {
        // Set-up the plugin so that it can be run again (in iterative mode) 
        // and the results reported for the top filter.
        // If the user runs the non-iterative mode then the results will be lost.
        iterBestFilter = bestFilter;
    }
    time += iterationStopWatch.getTime();
    IJ.log("Iteration analysis time : " + DurationFormatUtils.formatDurationHMS(time));
    IJ.showStatus("Finished");
}
Also used : FilterSet(gdsc.smlm.results.filter.FilterSet) GenericDialog(ij.gui.GenericDialog) NonBlockingGenericDialog(ij.gui.NonBlockingGenericDialog)

Example 68 with GenericDialog

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

the class BenchmarkFit method showDialog.

private boolean showDialog() {
    GenericDialog gd = new GenericDialog(TITLE);
    gd.addHelp(About.HELP_URL);
    final double sa = getSa();
    gd.addMessage(String.format("Fits the benchmark image created by CreateData plugin.\nPSF width = %s, adjusted = %s", Utils.rounded(benchmarkParameters.s / benchmarkParameters.a), Utils.rounded(sa)));
    // For each new benchmark width, reset the PSF width to the square pixel adjustment
    if (lastS != benchmarkParameters.s) {
        lastS = benchmarkParameters.s;
        psfWidth = sa;
    }
    final String filename = SettingsManager.getSettingsFilename();
    GlobalSettings settings = SettingsManager.loadSettings(filename);
    fitConfig = settings.getFitEngineConfiguration().getFitConfiguration();
    fitConfig.setNmPerPixel(benchmarkParameters.a);
    gd.addSlider("Region_size", 2, 20, regionSize);
    gd.addNumericField("PSF_width", psfWidth, 3);
    String[] solverNames = SettingsManager.getNames((Object[]) FitSolver.values());
    gd.addChoice("Fit_solver", solverNames, solverNames[fitConfig.getFitSolver().ordinal()]);
    String[] functionNames = SettingsManager.getNames((Object[]) FitFunction.values());
    gd.addChoice("Fit_function", functionNames, functionNames[fitConfig.getFitFunction().ordinal()]);
    gd.addCheckbox("Offset_fit", offsetFitting);
    gd.addNumericField("Start_offset", startOffset, 3);
    gd.addCheckbox("Include_CoM_fit", comFitting);
    gd.addCheckbox("Background_fitting", backgroundFitting);
    gd.addMessage("Signal fitting can be disabled for " + FitFunction.FIXED.toString() + " function");
    gd.addCheckbox("Signal_fitting", signalFitting);
    gd.addCheckbox("Show_histograms", showHistograms);
    gd.addCheckbox("Save_raw_data", saveRawData);
    gd.showDialog();
    if (gd.wasCanceled())
        return false;
    regionSize = (int) Math.abs(gd.getNextNumber());
    psfWidth = Math.abs(gd.getNextNumber());
    fitConfig.setFitSolver(gd.getNextChoiceIndex());
    fitConfig.setFitFunction(gd.getNextChoiceIndex());
    offsetFitting = gd.getNextBoolean();
    startOffset = Math.abs(gd.getNextNumber());
    comFitting = gd.getNextBoolean();
    backgroundFitting = gd.getNextBoolean();
    signalFitting = gd.getNextBoolean();
    showHistograms = gd.getNextBoolean();
    saveRawData = gd.getNextBoolean();
    if (!comFitting && !offsetFitting) {
        IJ.error(TITLE, "No initial fitting positions");
        return false;
    }
    if (regionSize < 1)
        regionSize = 1;
    if (gd.invalidNumber())
        return false;
    // Initialise the correct calibration
    Calibration calibration = settings.getCalibration();
    calibration.setNmPerPixel(benchmarkParameters.a);
    calibration.setGain(benchmarkParameters.gain);
    calibration.setAmplification(benchmarkParameters.amplification);
    calibration.setBias(benchmarkParameters.bias);
    calibration.setEmCCD(benchmarkParameters.emCCD);
    calibration.setReadNoise(benchmarkParameters.readNoise);
    calibration.setExposureTime(1000);
    if (!PeakFit.configureFitSolver(settings, filename, false))
        return false;
    if (showHistograms) {
        gd = new GenericDialog(TITLE);
        gd.addMessage("Select the histograms to display");
        gd.addNumericField("Histogram_bins", histogramBins, 0);
        double[] convert = getConversionFactors();
        for (int i = 0; i < displayHistograms.length; i++) if (convert[i] != 0)
            gd.addCheckbox(NAMES[i].replace(' ', '_'), displayHistograms[i]);
        gd.showDialog();
        if (gd.wasCanceled())
            return false;
        histogramBins = (int) Math.abs(gd.getNextNumber());
        for (int i = 0; i < displayHistograms.length; i++) if (convert[i] != 0)
            displayHistograms[i] = gd.getNextBoolean();
    }
    return true;
}
Also used : GenericDialog(ij.gui.GenericDialog) GlobalSettings(gdsc.smlm.ij.settings.GlobalSettings) Calibration(gdsc.smlm.results.Calibration)

Example 69 with GenericDialog

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

the class BenchmarkFilterAnalysis method showDialog.

private boolean showDialog(int optimiseParameters) {
    GenericDialog gd = new GenericDialog(TITLE);
    gd.addHelp(About.HELP_URL);
    boolean showOptimiseFilter = (optimiseParameters & FLAG_OPTIMISE_FILTER) != 0;
    boolean showOptimiseParams = (optimiseParameters & FLAG_OPTIMISE_PARAMS) != 0;
    addSimulationData(gd);
    // TODO - Make minimal filter configurable?
    gd.addSlider("Fail_count", 0, 20, failCount);
    if (showOptimiseParams) {
        gd.addNumericField("Min_fail_count", minFailCount, 0);
        gd.addNumericField("Max_fail_count", maxFailCount, 0);
    }
    if (BenchmarkSpotFit.computeDoublets) {
        gd.addSlider("Residuals_threshold", 0.01, 1, sResidualsThreshold);
        if (showOptimiseParams) {
            gd.addNumericField("Min_residuals_threshold", minResidualsThreshold, 2);
            gd.addNumericField("Max_residuals_threshold", maxResidualsThreshold, 2);
        }
    }
    gd.addNumericField("Duplicate_distance", duplicateDistance, 2);
    if (showOptimiseParams) {
        gd.addNumericField("Min_duplicate_distance", minDuplicateDistance, 2);
        gd.addNumericField("Max_duplicate_distance", maxDuplicateDistance, 2);
    }
    gd.addCheckbox("Reset", reset);
    gd.addCheckbox("Show_table", showResultsTable);
    gd.addCheckbox("Show_summary", showSummaryTable);
    gd.addCheckbox("Clear_tables", clearTables);
    gd.addSlider("Summary_top_n", 0, 20, summaryTopN);
    gd.addNumericField("Summary_depth (nm)", summaryDepth, 0);
    gd.addSlider("Plot_top_n", 0, 20, plotTopN);
    gd.addCheckbox("Save_best_filter", saveBestFilter);
    gd.addCheckbox("Save_template", saveTemplate);
    gd.addCheckbox("Calculate_sensitivity", calculateSensitivity);
    gd.addSlider("Delta", 0.01, 1, delta);
    gd.addMessage("Match scoring");
    Component discardLabel = gd.getMessage();
    gd.addChoice("Criteria", COLUMNS, COLUMNS[criteriaIndex]);
    gd.addNumericField("Criteria_limit", criteriaLimit, 4);
    gd.addChoice("Score", COLUMNS, COLUMNS[scoreIndex]);
    gd.addMessage(String.format("Fitting match distance = %s nm; signal factor = %s", Utils.rounded(BenchmarkSpotFit.distanceInPixels * simulationParameters.a), Utils.rounded(BenchmarkSpotFit.signalFactor)));
    gd.addSlider("Upper_match_distance (%)", 0, 100, upperMatchDistance);
    gd.addSlider("Partial_match_distance (%)", 0, 100, partialMatchDistance);
    gd.addSlider("Upper_signal_factor (%)", 0, 100, upperSignalFactor);
    gd.addSlider("Partial_signal_factor (%)", 0, 100, partialSignalFactor);
    if (!simulationParameters.fixedDepth)
        gd.addCheckbox("Depth_recall_analysis", depthRecallAnalysis);
    gd.addCheckbox("Score_analysis", scoreAnalysis);
    gd.addChoice("Component_analysis", COMPONENT_ANALYSIS, COMPONENT_ANALYSIS[componentAnalysis]);
    if (showOptimiseFilter) {
        gd.addChoice("Evolve", EVOLVE, EVOLVE[evolve]);
        gd.addCheckbox("Repeat_evolve", repeatEvolve);
    }
    if (showOptimiseParams) {
        gd.addChoice("Search", SEARCH, SEARCH[searchParam]);
        gd.addCheckbox("Repeat_search", repeatSearch);
    }
    gd.addStringField("Title", resultsTitle, 20);
    String[] labels = { "Show_TP", "Show_FP", "Show_FN" };
    gd.addCheckboxGroup(1, 3, labels, new boolean[] { showTP, showFP, showFN });
    if (gd.getLayout() != null) {
        GridBagLayout grid = (GridBagLayout) gd.getLayout();
        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 == discardLabel) {
                xOffset += 2;
                yOffset -= rowCount;
            }
            // 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, optimiseParameters))
        return false;
    if (!selectTableColumns())
        return false;
    // We may have to read the results again if the ranking option has changed.
    // Also we must read the results with the maximum duplicate distance we may encounter.
    final double dd = duplicateDistance;
    if (showOptimiseParams)
        duplicateDistance = maxDuplicateDistance;
    readResults();
    duplicateDistance = dd;
    return true;
}
Also used : GridBagConstraints(java.awt.GridBagConstraints) GridBagLayout(java.awt.GridBagLayout) GenericDialog(ij.gui.GenericDialog) NonBlockingGenericDialog(ij.gui.NonBlockingGenericDialog) Color(java.awt.Color) Component(java.awt.Component)

Example 70 with GenericDialog

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

the class BenchmarkFilterAnalysis method saveTemplate.

/**
	 * Save PeakFit configuration template using the current benchmark settings.
	 * 
	 * @param topFilterSummary
	 */
private void saveTemplate(String topFilterSummary) {
    FitEngineConfiguration config = new FitEngineConfiguration(new FitConfiguration());
    if (!updateAllConfiguration(config, true)) {
        IJ.log("Unable to create the template configuration");
        return;
    }
    // Remove the PSF width to make the template generic
    config.getFitConfiguration().setInitialPeakStdDev(0);
    String filename = getFilename("Template_File", templateFilename);
    if (filename != null) {
        templateFilename = filename;
        Prefs.set(KEY_TEMPLATE_FILENAME, filename);
        GlobalSettings settings = new GlobalSettings();
        settings.setNotes(getNotes(topFilterSummary));
        settings.setFitEngineConfiguration(config);
        if (!SettingsManager.saveSettings(settings, filename, true)) {
            IJ.log("Unable to save the template configuration");
            return;
        }
        // Save some random frames from the test image data
        ImagePlus imp = CreateData.getImage();
        if (imp == null)
            return;
        // Get the number of frames
        final ImageStack stack = imp.getImageStack();
        if (sampler == null || sampler.getResults() != results) {
            sampler = new ResultsImageSampler(results, stack, 32);
            sampler.analyse();
        }
        if (!sampler.isValid())
            return;
        // Iteratively show the example until the user is happy.
        // Yes = OK, No = Repeat, Cancel = Do not save
        String keyNo = "nNo";
        String keyLow = "nLower";
        String keyHigh = "nHigher";
        if (Utils.isMacro()) {
            // Collect the options if running in a macro
            String options = Macro.getOptions();
            nNo = Integer.parseInt(Macro.getValue(options, keyNo, Integer.toString(nNo)));
            nLow = Integer.parseInt(Macro.getValue(options, keyLow, Integer.toString(nLow)));
            nHigh = Integer.parseInt(Macro.getValue(options, keyHigh, Integer.toString(nHigh)));
        } else {
            if (nLow + nHigh == 0)
                nLow = nHigh = 1;
        }
        final ImagePlus[] out = new ImagePlus[1];
        out[0] = sampler.getSample(nNo, nLow, nHigh);
        if (!Utils.isMacro()) {
            // Show the template results
            final ConfigurationTemplate configTemplate = new ConfigurationTemplate();
            // Interactively show the sample image data
            final boolean[] close = new boolean[1];
            final ImagePlus[] outImp = new ImagePlus[1];
            if (out[0] != null) {
                outImp[0] = display(out[0]);
                if (Utils.isNewWindow()) {
                    close[0] = true;
                    // Zoom a bit
                    ImageWindow iw = outImp[0].getWindow();
                    for (int i = 7; i-- > 0 && Math.max(iw.getWidth(), iw.getHeight()) < 512; ) {
                        iw.getCanvas().zoomIn(0, 0);
                    }
                }
                configTemplate.createResults(outImp[0]);
            }
            // TODO - fix this when a second sample is made as the results are not updated.
            ImageListener listener = new ImageListener() {

                public void imageOpened(ImagePlus imp) {
                }

                public void imageClosed(ImagePlus imp) {
                }

                public void imageUpdated(ImagePlus imp) {
                    if (imp != null && imp == outImp[0]) {
                        configTemplate.updateResults(imp.getCurrentSlice());
                    }
                }
            };
            ImagePlus.addImageListener(listener);
            // For the dialog
            String msg = String.format("Showing image data for the template example.\n \nSample Frames:\nEmpty = %d\nLower density = %d\nHigher density = %d\n", sampler.getNumberOfEmptySamples(), sampler.getNumberOfLowDensitySamples(), sampler.getNumberOfHighDensitySamples());
            // Turn off the recorder when the dialog is showing
            boolean record = Recorder.record;
            Recorder.record = false;
            NonBlockingGenericDialog gd = new NonBlockingGenericDialog(TITLE);
            gd.addMessage(msg);
            //gd.enableYesNoCancel(" Save ", " Resample ");
            gd.addSlider(keyNo, 0, 10, nNo);
            gd.addSlider(keyLow, 0, 10, nLow);
            gd.addSlider(keyHigh, 0, 10, nHigh);
            gd.addDialogListener(new DialogListener() {

                public boolean dialogItemChanged(GenericDialog gd, AWTEvent e) {
                    // image the user has not seen.
                    if (e == null)
                        return true;
                    nNo = (int) gd.getNextNumber();
                    nLow = (int) gd.getNextNumber();
                    nHigh = (int) gd.getNextNumber();
                    out[0] = sampler.getSample(nNo, nLow, nHigh);
                    if (out[0] != null) {
                        outImp[0] = display(out[0]);
                        if (Utils.isNewWindow()) {
                            close[0] = true;
                            // Zoom a bit
                            ImageWindow iw = outImp[0].getWindow();
                            for (int i = 7; i-- > 0 && Math.max(iw.getWidth(), iw.getHeight()) < 512; ) {
                                iw.getCanvas().zoomIn(0, 0);
                            }
                        }
                        configTemplate.createResults(outImp[0]);
                    }
                    return true;
                }
            });
            gd.showDialog();
            if (gd.wasCanceled()) {
                out[0] = null;
                // For the recorder
                nNo = nLow = nHigh = 0;
            }
            if (close[0]) {
                // Because closing the image sets the stack pixels array to null
                if (out[0] != null)
                    out[0] = out[0].duplicate();
                outImp[0].close();
            }
            configTemplate.closeResults();
            ImagePlus.removeImageListener(listener);
            if (record) {
                Recorder.record = true;
                Recorder.recordOption(keyNo, Integer.toString(nNo));
                Recorder.recordOption(keyLow, Integer.toString(nLow));
                Recorder.recordOption(keyHigh, Integer.toString(nHigh));
            }
        }
        if (out[0] == null)
            return;
        ImagePlus example = out[0];
        filename = Utils.replaceExtension(filename, ".tif");
        IJ.save(example, filename);
    }
}
Also used : ResultsImageSampler(gdsc.smlm.ij.results.ResultsImageSampler) ImageWindow(ij.gui.ImageWindow) ImageStack(ij.ImageStack) ImageListener(ij.ImageListener) FitEngineConfiguration(gdsc.smlm.engine.FitEngineConfiguration) GlobalSettings(gdsc.smlm.ij.settings.GlobalSettings) NonBlockingGenericDialog(ij.gui.NonBlockingGenericDialog) ImagePlus(ij.ImagePlus) FitConfiguration(gdsc.smlm.fitting.FitConfiguration) DialogListener(ij.gui.DialogListener) GenericDialog(ij.gui.GenericDialog) NonBlockingGenericDialog(ij.gui.NonBlockingGenericDialog) AWTEvent(java.awt.AWTEvent)

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