Search in sources :

Example 81 with GenericDialog

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

the class PSFCreator method showDialog.

private int showDialog() {
    GenericDialog gd = new GenericDialog(TITLE);
    gd.addHelp(About.HELP_URL);
    gd.addMessage("Produces an average PSF using selected diffraction limited spots.\nUses the current fit configuration to fit spots.");
    gd.addCheckbox("Update_Fit_Configuration", false);
    gd.addNumericField("nm_per_slice", nmPerSlice, 0);
    gd.addSlider("Radius", 3, 20, radius);
    gd.addSlider("Amplitude_fraction", 0.01, 0.5, amplitudeFraction);
    gd.addSlider("Start_background_frames", 1, 20, startBackgroundFrames);
    gd.addSlider("End_background_frames", 1, 20, endBackgroundFrames);
    gd.addSlider("Magnification", 5, 15, magnification);
    gd.addSlider("Smoothing", 0.25, 0.5, smoothing);
    gd.addCheckbox("Centre_each_slice", centreEachSlice);
    gd.addNumericField("CoM_cut_off", comCutOff, -2);
    gd.addCheckbox("Interactive_mode", interactiveMode);
    String[] methods = ImageProcessor.getInterpolationMethods();
    gd.addChoice("Interpolation", methods, methods[interpolationMethod]);
    ((Checkbox) gd.getCheckboxes().get(0)).addItemListener(this);
    gd.showDialog();
    if (gd.wasCanceled())
        return DONE;
    gd.getNextBoolean();
    nmPerSlice = gd.getNextNumber();
    radius = gd.getNextNumber();
    amplitudeFraction = gd.getNextNumber();
    startBackgroundFrames = (int) gd.getNextNumber();
    endBackgroundFrames = (int) gd.getNextNumber();
    magnification = (int) gd.getNextNumber();
    smoothing = gd.getNextNumber();
    centreEachSlice = gd.getNextBoolean();
    comCutOff = Maths.max(0, gd.getNextNumber());
    interactiveMode = gd.getNextBoolean();
    interpolationMethod = gd.getNextChoiceIndex();
    // Check arguments
    try {
        Parameters.isPositive("nm/slice", nmPerSlice);
        Parameters.isAbove("Radius", radius, 2);
        Parameters.isAbove("Amplitude fraction", amplitudeFraction, 0.01);
        Parameters.isBelow("Amplitude fraction", amplitudeFraction, 0.9);
        Parameters.isPositive("Start background frames", startBackgroundFrames);
        Parameters.isPositive("End background frames", endBackgroundFrames);
        Parameters.isAbove("Total background frames", startBackgroundFrames + endBackgroundFrames, 1);
        Parameters.isAbove("Magnification", magnification, 1);
        Parameters.isAbove("Smoothing", smoothing, 0);
        Parameters.isBelow("Smoothing", smoothing, 1);
    } catch (IllegalArgumentException e) {
        IJ.error(TITLE, e.getMessage());
        return DONE;
    }
    return flags;
}
Also used : Checkbox(java.awt.Checkbox) GenericDialog(ij.gui.GenericDialog)

Example 82 with GenericDialog

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

the class Noise method showDialog.

public int showDialog(ImagePlus imp, String command, PlugInFilterRunner pfr) {
    // If using a stack, provide a preview graph of the noise for two methods
    if (imp.getStackSize() > 1) {
        this.pfr = pfr;
        drawPlot();
        gd = new GenericDialog(TITLE);
        gd.addHelp(About.HELP_URL);
        String[] methodNames = SettingsManager.getNames((Object[]) NoiseEstimator.Method.values());
        gd.addChoice("Method1 (blue)", methodNames, methodNames[algorithm]);
        gd.addChoice("Method2 (red)", methodNames, methodNames[algorithm2]);
        gd.addSlider("Lowest_radius", 1, 15, lowestPixelsRange);
        //gd.addPreviewCheckbox(pfr);
        gd.addDialogListener(this);
        gd.addMessage("Click OK to compute noise table using all methods");
        gd.showDialog();
        if (gd.wasCanceled() || !dialogItemChanged(gd, null))
            return DONE;
    }
    return IJ.setupDialog(imp, FLAGS);
}
Also used : GenericDialog(ij.gui.GenericDialog)

Example 83 with GenericDialog

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

the class PSFCalculator method calculate.

/**
	 * Present an interactive dialog that allows the user to calculate the Gaussian PSF standard deviation using the
	 * provided settings.
	 * 
	 * @param settings
	 * @param simpleMode
	 *            Only present a wavelength, NA and proportionality factor fields.
	 * @return the PSF standard deviation
	 */
public double calculate(PSFCalculatorSettings settings, boolean simpleMode) {
    gd = new GenericDialog(TITLE);
    gd.addHelp(About.HELP_URL);
    this.settings = settings;
    if (!simpleMode) {
        gd.addNumericField("Pixel_pitch (um)", settings.pixelPitch, 2);
        gd.addNumericField("Magnification", settings.magnification, 0);
        gd.addNumericField("Beam_Expander", settings.beamExpander, 2);
        gd.addMessage(getPixelPitchLabel());
        pixelPitchLabel = (Label) gd.getMessage();
    //pixelPitchLabel.setText(getPixelPitchLabel());
    }
    gd.addSlider("Wavelength (nm)", 400, 750, settings.wavelength);
    gd.addSlider("Numerical_Aperture (NA)", 1, 1.5, settings.numericalAperture);
    gd.addMessage(getAbbeLimitLabel());
    abbeLimitLabel = (Label) gd.getMessage();
    //abbe.setText(getAbbeLimitLabel());
    gd.addMessage("*** Account for optical aberations and focus error ***");
    gd.addSlider("Proportionality_factor", 1, 2.5, settings.proportionalityFactor);
    gd.addCheckbox("Adjust_for_square_pixels", settings.adjustForSquarePixels);
    if (!simpleMode) {
        gd.addNumericField("Airy Width (nm)", calculateAiryWidth(settings.wavelength, settings.numericalAperture), 3);
        gd.addNumericField("Airy Width (pixels)", calculateAiryWidth(settings.pixelPitch, settings.magnification * settings.beamExpander, settings.wavelength, settings.numericalAperture), 3);
    }
    gd.addNumericField("StdDev (nm)", calculateStdDev(settings.wavelength, settings.numericalAperture, settings.proportionalityFactor), 3);
    double sd = calculateStdDev(settings.pixelPitch, settings.magnification * settings.beamExpander, settings.wavelength, settings.numericalAperture, settings.proportionalityFactor, settings.adjustForSquarePixels);
    gd.addNumericField("StdDev (pixels)", sd, 3);
    gd.addNumericField("HWHM (pixels)", sd * Gaussian2DFunction.SD_TO_HWHM_FACTOR, 3);
    if (!simpleMode) {
        widthNmText = (TextField) gd.getNumericFields().get(gd.getNumericFields().size() - 5);
        widthPixelsText = (TextField) gd.getNumericFields().get(gd.getNumericFields().size() - 4);
    }
    sdNmText = (TextField) gd.getNumericFields().get(gd.getNumericFields().size() - 3);
    sdPixelsText = (TextField) gd.getNumericFields().get(gd.getNumericFields().size() - 2);
    fwhmPixelsText = (TextField) gd.getNumericFields().get(gd.getNumericFields().size() - 1);
    //widthNmText
    if (!simpleMode) {
        disableEditing(widthNmText);
        disableEditing(widthPixelsText);
    }
    disableEditing(sdNmText);
    disableEditing(sdPixelsText);
    disableEditing(fwhmPixelsText);
    if (!simpleMode)
        gd.addMessage("Save StdDev pixel width to the fitting properties");
    gd.addDialogListener(this);
    double s = calculateStdDev(settings.pixelPitch, settings.magnification * settings.beamExpander, settings.wavelength, settings.numericalAperture, 1, false);
    plotProfile(calculateAiryWidth(settings.pixelPitch, settings.magnification * settings.beamExpander, settings.wavelength, settings.numericalAperture), sd / s);
    gd.showDialog();
    if (gd.wasCanceled()) {
        return -1;
    }
    return calculateStdDev(settings.pixelPitch, settings.magnification * settings.beamExpander, settings.wavelength, settings.numericalAperture, settings.proportionalityFactor, settings.adjustForSquarePixels);
}
Also used : GenericDialog(ij.gui.GenericDialog)

Example 84 with GenericDialog

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

the class BenchmarkFilterAnalysis method parameterAnalysis.

/**
	 * Run the optimum filter on a set of labelled peak results using various parameter settings outputting performance
	 * statistics on the success of the filter to an ImageJ table.
	 * <p>
	 * If a new optimum is found the class level static parameters are updated.
	 *
	 * @param nonInteractive
	 *            True if non interactive
	 * @param currentOptimum
	 *            the optimum
	 * @param rangeReduction
	 *            the range reduction
	 * @return the best filter
	 */
private ComplexFilterScore parameterAnalysis(boolean nonInteractive, ComplexFilterScore currentOptimum, double rangeReduction) {
    this.ga_resultsList = resultsList;
    String algorithm = "";
    // All the search algorithms use search dimensions.
    ss_filter = currentOptimum.r.filter;
    FixedDimension[] originalDimensions = new FixedDimension[3];
    double[] point = createParameters();
    String[] names = { "Fail count", "Residuals threshold", "Duplicate distance" };
    {
        // Local scope for i
        int i = 0;
        try {
            originalDimensions[i++] = new FixedDimension(minFailCount, maxFailCount, 1);
            // TODO - let the min intervals be configured, maybe via extra options
            if (BenchmarkSpotFit.computeDoublets)
                originalDimensions[i++] = new FixedDimension(minResidualsThreshold, maxResidualsThreshold, 0.05);
            else
                originalDimensions[i++] = new FixedDimension(1, 1, 0.05);
            originalDimensions[i++] = new FixedDimension(minDuplicateDistance, maxDuplicateDistance, 0.5);
        } catch (IllegalArgumentException e) {
            Utils.log(TITLE + " : Unable to configure dimension [%d] %s: " + e.getMessage(), i, names[i]);
            return null;
        }
    }
    // Check for a search
    boolean active = false;
    for (int i = 0; i < originalDimensions.length; i++) {
        if (originalDimensions[i].isActive()) {
            active = true;
            break;
        }
    }
    if (!active) {
        Utils.log(TITLE + " : No search range");
        return currentOptimum;
    }
    // Optionally use a reduced range (this is used for iteration)
    if (rangeReduction > 0 && rangeReduction < 1) {
        // Suppress dialogs and use the current settings
        nonInteractive = true;
        for (int i = 0; i < originalDimensions.length; i++) {
            double centre = point[i];
            double r = 0;
            if (originalDimensions[i].isActive()) {
                r = (originalDimensions[i].max - originalDimensions[i].min) * rangeReduction;
            }
            double lower = centre - r * 0.5;
            double upper = centre + r * 0.5;
            originalDimensions[i] = originalDimensions[i].create(lower, upper);
        }
    }
    analysisStopWatch = StopWatch.createStarted();
    // Store this for later debugging
    SearchResult<FilterScore> optimum = null;
    if (searchParam == 0 || searchParam == 2) {
        // Collect parameters for the range search algorithm
        pauseParameterTimer();
        boolean isStepSearch = searchParam == 2;
        // The step search should use a multi-dimension refinement and no range reduction
        SearchSpace.RefinementMode myRefinementMode = SearchSpace.RefinementMode.MULTI_DIMENSION;
        GenericDialog gd = null;
        boolean runAlgorithm = nonInteractive;
        if (!nonInteractive) {
            // Ask the user for the search parameters.
            gd = new GenericDialog(TITLE);
            gd.addMessage("Configure the " + SEARCH[searchParam] + " algorithm for " + ss_filter.getType());
            gd.addSlider("Width", 1, 5, pRangeSearchWidth);
            if (!isStepSearch) {
                gd.addNumericField("Max_iterations", pMaxIterations, 0);
                String[] modes = SettingsManager.getNames((Object[]) SearchSpace.RefinementMode.values());
                gd.addSlider("Reduce", 0.01, 0.99, pRangeSearchReduce);
                gd.addChoice("Refinement", modes, modes[pRefinementMode]);
            }
            gd.addNumericField("Seed_size", pSeedSize, 0);
            gd.showDialog();
            runAlgorithm = !gd.wasCanceled();
        }
        if (runAlgorithm) {
            SearchDimension[] dimensions = new SearchDimension[originalDimensions.length];
            if (!nonInteractive) {
                pRangeSearchWidth = (int) gd.getNextNumber();
                if (!isStepSearch) {
                    pMaxIterations = (int) gd.getNextNumber();
                    pRangeSearchReduce = gd.getNextNumber();
                    pRefinementMode = gd.getNextChoiceIndex();
                }
                pSeedSize = (int) gd.getNextNumber();
            }
            if (!isStepSearch)
                myRefinementMode = SearchSpace.RefinementMode.values()[pRefinementMode];
            for (int i = 0; i < dimensions.length; i++) {
                if (originalDimensions[i].isActive()) {
                    try {
                        dimensions[i] = originalDimensions[i].create(pRangeSearchWidth);
                        dimensions[i].setPad(true);
                        // Prevent range reduction so that the step search just does a single refinement step
                        dimensions[i].setReduceFactor((isStepSearch) ? 1 : pRangeSearchReduce);
                        // Centre on current optimum
                        dimensions[i].setCentre(point[i]);
                    } catch (IllegalArgumentException e) {
                        IJ.error(TITLE, String.format("Unable to configure dimension [%d] %s: " + e.getMessage(), i, names[i]));
                        return null;
                    }
                } else {
                    dimensions[i] = new SearchDimension(point[i]);
                }
            }
            // Check the number of combinations is OK
            long combinations = SearchSpace.countCombinations(dimensions);
            if (!nonInteractive && combinations > 10000) {
                gd = new GenericDialog(TITLE);
                gd.addMessage(String.format("%d combinations for the configured dimensions.\n \nClick 'Yes' to optimise.", combinations));
                gd.enableYesNoCancel();
                gd.hideCancelButton();
                gd.showDialog();
                if (!gd.wasOKed()) {
                    combinations = 0;
                }
            }
            if (combinations == 0) {
                resumeParameterTimer();
            } else {
                algorithm = SEARCH[searchParam] + " " + pRangeSearchWidth;
                ga_statusPrefix = algorithm + " " + ss_filter.getName() + " ... ";
                ga_iteration = 0;
                p_optimum = null;
                SearchSpace ss = new SearchSpace();
                ss.setTracker(this);
                if (pSeedSize > 0) {
                    // Add current optimum to seed
                    // Note: If we have an optimum and we are not seeding this should not matter as the dimensions 
                    // have been centred on the current optimum					
                    double[][] seed = new double[1][];
                    seed[0] = point;
                    // Sample without rounding as the seed will be rounded
                    double[][] sample = SearchSpace.sampleWithoutRounding(dimensions, pSeedSize - 1, null);
                    ss.seed(merge(sample, seed));
                }
                ConvergenceChecker<FilterScore> checker = new InterruptConvergenceChecker(0, 0, pMaxIterations);
                createGAWindow();
                resumeParameterTimer();
                optimum = ss.search(dimensions, new ParameterScoreFunction(), checker, myRefinementMode);
                if (optimum != null) {
                    // In case optimisation was stopped
                    IJ.resetEscape();
                    // Now update the parameters for final assessment
                    point = optimum.point;
                // Not required as the seed in now rounded
                //if (pSeedSize > 0)
                //{
                //	// The optimum may be off grid if it was from the seed
                //	point = enumerateMinInterval(point, names, originalDimensions);
                //}
                }
            }
        } else
            resumeParameterTimer();
    }
    if (searchParam == 1) {
        // Collect parameters for the enrichment search algorithm
        pauseParameterTimer();
        GenericDialog gd = null;
        boolean runAlgorithm = nonInteractive;
        if (!nonInteractive) {
            // Ask the user for the search parameters.
            gd = new GenericDialog(TITLE);
            gd.addMessage("Configure the " + SEARCH[searchParam] + " algorithm for " + ss_filter.getType());
            gd.addNumericField("Max_iterations", pMaxIterations, 0);
            gd.addNumericField("Converged_count", pConvergedCount, 0);
            gd.addNumericField("Samples", pEnrichmentSamples, 0);
            gd.addSlider("Fraction", 0.01, 0.99, pEnrichmentFraction);
            gd.addSlider("Padding", 0, 0.99, pEnrichmentPadding);
            gd.showDialog();
            runAlgorithm = !gd.wasCanceled();
        }
        if (runAlgorithm) {
            FixedDimension[] dimensions = Arrays.copyOf(originalDimensions, originalDimensions.length);
            if (!nonInteractive) {
                pMaxIterations = (int) gd.getNextNumber();
                pConvergedCount = (int) gd.getNextNumber();
                pEnrichmentSamples = (int) gd.getNextNumber();
                pEnrichmentFraction = gd.getNextNumber();
                pEnrichmentPadding = gd.getNextNumber();
            }
            algorithm = SEARCH[searchParam];
            ga_statusPrefix = algorithm + " " + ss_filter.getName() + " ... ";
            ga_iteration = 0;
            p_optimum = null;
            SearchSpace ss = new SearchSpace();
            ss.setTracker(this);
            // Add current optimum to seed
            double[][] seed = new double[1][];
            seed[0] = point;
            ss.seed(seed);
            ConvergenceChecker<FilterScore> checker = new InterruptConvergenceChecker(0, 0, pMaxIterations, pConvergedCount);
            createGAWindow();
            resumeParameterTimer();
            optimum = ss.enrichmentSearch(dimensions, new ParameterScoreFunction(), checker, pEnrichmentSamples, pEnrichmentFraction, pEnrichmentPadding);
            if (optimum != null) {
                // In case optimisation was stopped
                IJ.resetEscape();
                point = optimum.point;
            // Not required as the search now respects the min interval
            // Enumerate on the min interval to produce the final filter
            //point = enumerateMinInterval(point, names, originalDimensions);
            }
        } else
            resumeParameterTimer();
    }
    if (searchParam == 3) {
        // Collect parameters for the enumeration search algorithm
        pauseParameterTimer();
        SearchDimension[] dimensions = new SearchDimension[originalDimensions.length];
        for (int i = 0; i < dimensions.length; i++) {
            if (originalDimensions[i].isActive()) {
                try {
                    dimensions[i] = originalDimensions[i].create(0);
                } catch (IllegalArgumentException e) {
                    IJ.error(TITLE, String.format("Unable to configure dimension [%d] %s: " + e.getMessage(), i, names[i]));
                    return null;
                }
            } else {
                dimensions[i] = new SearchDimension(point[i]);
            }
        }
        GenericDialog gd = null;
        long combinations = SearchSpace.countCombinations(dimensions);
        if (!nonInteractive && combinations > 2000) {
            gd = new GenericDialog(TITLE);
            gd.addMessage(String.format("%d combinations for the configured dimensions.\n \nClick 'Yes' to optimise.", combinations));
            gd.enableYesNoCancel();
            gd.hideCancelButton();
            gd.showDialog();
            if (!gd.wasOKed()) {
                combinations = 0;
            }
        }
        if (combinations == 0) {
            resumeParameterTimer();
        } else {
            algorithm = SEARCH[searchParam];
            ga_statusPrefix = algorithm + " " + ss_filter.getName() + " ... ";
            ga_iteration = 0;
            p_optimum = null;
            SearchSpace ss = new SearchSpace();
            ss.setTracker(this);
            createGAWindow();
            resumeParameterTimer();
            optimum = ss.findOptimum(dimensions, new ParameterScoreFunction());
            if (optimum != null) {
                // In case optimisation was stopped
                IJ.resetEscape();
                // Now update the parameters for final assessment
                point = optimum.point;
            }
        }
    }
    IJ.showStatus("Analysing " + ss_filter.getName() + " ...");
    // Update the parameters using the optimum
    failCount = (int) Math.round(point[0]);
    residualsThreshold = sResidualsThreshold = point[1];
    duplicateDistance = point[2];
    // Refresh the coordinate store
    if (coordinateStore == null || duplicateDistance != coordinateStore.getResolution()) {
        coordinateStore = createCoordinateStore();
    }
    createResultsPrefix2();
    // (Re) Score the filter.
    // TODO - check this is now OK. Maybe remove the enumeration on the min interval grid
    // If scoring of filter here is different to scoring in the optimisation routine it is probably an ss_filter.clone() issue,
    // i.e. multi-threading use of the filter clone is not working.
    // Or it could be that the optimisation produced params off the min-interval grid
    FilterScoreResult scoreResult = scoreFilter(ss_filter);
    if (optimum != null) {
        if (scoreResult.score != optimum.score.score && scoreResult.criteria != optimum.score.criteria) {
            ParameterScoreResult r = scoreFilter((DirectFilter) ss_filter.clone(), minimalFilter, failCount, residualsThreshold, duplicateDistance, createCoordinateStore(duplicateDistance), false);
            System.out.printf("Weird re- score of the filter: %f!=%f or %f!=%f (%f:%f)\n", scoreResult.score, optimum.score.score, scoreResult.criteria, optimum.score.criteria, r.score, r.criteria);
        }
    }
    SimpleFilterScore max = new SimpleFilterScore(scoreResult, true, scoreResult.criteria >= minCriteria);
    analysisStopWatch.stop();
    if (showResultsTable) {
        BufferedTextWindow tw = null;
        if (resultsWindow != null)
            tw = new BufferedTextWindow(resultsWindow);
        addToResultsWindow(tw, scoreResult.text);
        if (resultsWindow != null)
            resultsWindow.getTextPanel().updateDisplay();
    }
    // Check the top result against the limits of the original dimensions
    StringBuilder sb = new StringBuilder(200);
    for (int j = 0; j < originalDimensions.length; j++) {
        if (!originalDimensions[j].isActive())
            continue;
        final double value = point[j];
        double lowerLimit = originalDimensions[j].getLower();
        double upperLimit = originalDimensions[j].getUpper();
        int c1 = Double.compare(value, lowerLimit);
        if (c1 <= 0) {
            sb.append(" : ").append(names[j]).append(' ').append(ComplexFilterScore.FLOOR).append('[').append(Utils.rounded(value));
            if (c1 == -1) {
                sb.append("<").append(Utils.rounded(lowerLimit));
            }
            sb.append("]");
        } else {
            int c2 = Double.compare(value, upperLimit);
            if (c2 >= 0) {
                sb.append(" : ").append(names[j]).append(' ').append(ComplexFilterScore.CEIL).append('[').append(Utils.rounded(value));
                if (c2 == 1) {
                    sb.append(">").append(Utils.rounded(upperLimit));
                }
                sb.append("]");
            }
        }
    }
    if (sb.length() > 0) {
        if (max.criteriaPassed) {
            Utils.log("Warning: Top filter (%s @ %s|%s) [%s] at the limit of the expanded range%s", ss_filter.getName(), Utils.rounded((invertScore) ? -max.score : max.score), Utils.rounded((invertCriteria) ? -minCriteria : minCriteria), limitFailCount + limitRange, sb.toString());
        } else {
            Utils.log("Warning: Top filter (%s @ -|%s) [%s] at the limit of the expanded range%s", ss_filter.getName(), Utils.rounded((invertCriteria) ? -max.criteria : max.criteria), limitFailCount + limitRange, sb.toString());
        }
    }
    // We may have no filters that pass the criteria
    String type = max.r.filter.getType();
    if (!max.criteriaPassed) {
        Utils.log("Warning: Filter does not pass the criteria: %s : Best = %s using %s", type, Utils.rounded((invertCriteria) ? -max.criteria : max.criteria), max.r.filter.getName());
        return null;
    }
    // Update without duplicates
    boolean allowDuplicates = false;
    // Re-use the atLimit and algorithm for the input optimum
    ComplexFilterScore newFilterScore = new ComplexFilterScore(max.r, currentOptimum.atLimit, currentOptimum.algorithm, currentOptimum.time, algorithm, analysisStopWatch.getTime());
    addBestFilter(type, allowDuplicates, newFilterScore);
    // Add spacer at end of each result set
    if (isHeadless) {
        if (showResultsTable)
            IJ.log("");
    } else {
        if (showResultsTable)
            resultsWindow.append("");
    }
    if (newFilterScore.compareTo(currentOptimum) <= 0)
        return newFilterScore;
    else {
        // Update the algorithm and time
        currentOptimum.paramAlgorithm = algorithm;
        currentOptimum.paramTime = analysisStopWatch.getTime();
    }
    return currentOptimum;
}
Also used : SearchSpace(gdsc.smlm.search.SearchSpace) GenericDialog(ij.gui.GenericDialog) NonBlockingGenericDialog(ij.gui.NonBlockingGenericDialog) BufferedTextWindow(gdsc.core.ij.BufferedTextWindow) SearchDimension(gdsc.smlm.search.SearchDimension) FixedDimension(gdsc.smlm.search.FixedDimension) FilterScore(gdsc.smlm.results.filter.FilterScore)

Example 85 with GenericDialog

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

the class About method installResource.

/**
	 * @param resource
	 * @param ijDirectory
	 * @param destinationName
	 * @param resourceTitle
	 * @param notes
	 * @param options
	 * @return -1 on error, 0 if installed, 1 if removed
	 */
private static int installResource(String resource, String ijDirectory, String destinationName, String resourceTitle, String notes, ConfigureOption... options) {
    Class<About> resourceClass = About.class;
    InputStream toolsetStream = resourceClass.getResourceAsStream(resource);
    if (toolsetStream == null)
        return -1;
    String dir = IJ.getDirectory(ijDirectory);
    if (dir == null) {
        IJ.error("Unable to locate " + ijDirectory + " directory");
        return -1;
    }
    EnumSet<ConfigureOption> opt = EnumSet.of(options[0], options);
    GenericDialog gd = new GenericDialog(TITLE);
    String filename = dir + destinationName;
    boolean fileExists = new File(filename).exists();
    StringBuilder sb = new StringBuilder();
    sb.append("Configure resource '").append(resourceTitle).append("' at:\n \n").append(filename);
    if (notes != null)
        sb.append("\n \n").append(XmlUtils.lineWrap(notes, 80, 0, null));
    gd.addMessage(sb.toString());
    // Configure the options
    String[] choices = new String[3];
    ConfigureOption[] optChoices = new ConfigureOption[choices.length];
    int count = 0;
    if (opt.contains(ConfigureOption.INSTALL)) {
        choices[count] = ConfigureOption.INSTALL.toString();
        if (fileExists)
            choices[count] += " (overwrite)";
        optChoices[count] = ConfigureOption.INSTALL;
        count++;
    }
    if (opt.contains(ConfigureOption.EDIT)) {
        choices[count] = ConfigureOption.EDIT.toString();
        if (fileExists)
            choices[count] += " (overwrite)";
        optChoices[count] = ConfigureOption.EDIT;
        count++;
    }
    if (opt.contains(ConfigureOption.REMOVE) && fileExists) {
        choices[count] = ConfigureOption.REMOVE.toString();
        optChoices[count] = ConfigureOption.REMOVE;
        count++;
    }
    if (count == 0)
        return -1;
    choices = Arrays.copyOf(choices, count);
    gd.addChoice("Option", choices, choices[0]);
    gd.showDialog();
    if (gd.wasCanceled())
        return -1;
    ConfigureOption choice = optChoices[gd.getNextChoiceIndex()];
    if (choice == ConfigureOption.REMOVE) {
        try {
            new File(filename).delete();
            return 1;
        } catch (SecurityException e) {
            IJ.error("Unable to remove existing file");
        }
        return -1;
    }
    // Read the file
    LinkedList<String> contents = new LinkedList<String>();
    BufferedReader input = null;
    try {
        // Read
        input = new BufferedReader(new UnicodeReader(toolsetStream, null));
        String line;
        while ((line = input.readLine()) != null) {
            contents.add(line);
        }
    } catch (IOException e) {
        IJ.error("Unable to install " + resourceTitle + ".\n \n" + e.getMessage());
        return -1;
    } finally {
        close(input);
    }
    if (choice == ConfigureOption.EDIT) {
        // Allow the user to edit the file contents
        gd = new GenericDialog(TITLE);
        gd.addMessage("Edit the file contents before install:");
        sb.setLength(0);
        for (String line : contents) sb.append(line).append("\n");
        gd.addTextAreas(sb.toString(), null, 20, 80);
        gd.showDialog();
        if (gd.wasOKed()) {
            contents.clear();
            String text = gd.getNextText();
            for (String line : text.split("\n")) contents.add(line);
        }
    }
    // Install the file
    BufferedWriter output = null;
    try {
        // Write
        FileOutputStream fos = new FileOutputStream(filename);
        output = new BufferedWriter(new OutputStreamWriter(fos, "UTF-8"));
        for (String content : contents) {
            output.write(content);
            output.newLine();
        }
    } catch (IOException e) {
        IJ.error("Unable to install " + resourceTitle + ".\n \n" + e.getMessage());
    } finally {
        close(output);
    }
    return 0;
}
Also used : InputStream(java.io.InputStream) UnicodeReader(gdsc.core.utils.UnicodeReader) IOException(java.io.IOException) LinkedList(java.util.LinkedList) BufferedWriter(java.io.BufferedWriter) GenericDialog(ij.gui.GenericDialog) FileOutputStream(java.io.FileOutputStream) BufferedReader(java.io.BufferedReader) OutputStreamWriter(java.io.OutputStreamWriter) File(java.io.File)

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