Search in sources :

Example 36 with FitEngineConfiguration

use of uk.ac.sussex.gdsc.smlm.engine.FitEngineConfiguration in project GDSC-SMLM by aherbert.

the class BenchmarkSpotFit method updateConfiguration.

/**
 * Updates the given configuration using the latest settings used in benchmarking.
 *
 * @param targetConfiguration the configuration
 * @return true, if successful
 */
public static boolean updateConfiguration(FitEngineConfiguration targetConfiguration) {
    final FitConfiguration targetFitConfiguration = targetConfiguration.getFitConfiguration();
    // Q. Why are the settings set to themselves?
    // Removed this for now.
    // targetFitConfiguration.setPsf(targetFitConfiguration.getPsf());
    // targetFitConfiguration.setFitSolverSettings(targetFitConfiguration.getFitSolverSettings());
    // targetFitConfiguration.setFilterSettings(targetFitConfiguration.getFilterSettings());
    final FitEngineConfiguration sourceConfig = Settings.INSTANCE.get().config;
    final FitConfiguration sourceFitConfiguration = sourceConfig.getFitConfiguration();
    // Set the fit engine settings manually to avoid merging all child settings
    // i.e. do not do a global update using:
    // targetConfiguration.setFitEngineSettings(sourceConfig.getFitEngineSettings());
    targetFitConfiguration.setPsf(sourceFitConfiguration.getPsf());
    targetFitConfiguration.setFitSolverSettings(sourceFitConfiguration.getFitSolverSettings());
    targetFitConfiguration.setFilterSettings(sourceFitConfiguration.getFilterSettings());
    targetConfiguration.setFitting(sourceConfig.getFitting());
    targetConfiguration.setIncludeNeighbours(sourceConfig.isIncludeNeighbours());
    targetConfiguration.setNeighbourHeightThreshold(sourceConfig.getNeighbourHeightThreshold());
    targetConfiguration.setDuplicateDistance(sourceConfig.getDuplicateDistance());
    targetConfiguration.setDuplicateDistanceAbsolute(sourceConfig.getDuplicateDistanceAbsolute());
    if (getComputeDoublets()) {
        targetConfiguration.setResidualsThreshold(0);
        targetFitConfiguration.setComputeResiduals(true);
    } else {
        targetConfiguration.setResidualsThreshold(1);
        targetFitConfiguration.setComputeResiduals(false);
    }
    // We used simple filtering.
    targetFitConfiguration.setSmartFilter(false);
    return true;
}
Also used : FitConfiguration(uk.ac.sussex.gdsc.smlm.engine.FitConfiguration) FitEngineConfiguration(uk.ac.sussex.gdsc.smlm.engine.FitEngineConfiguration)

Example 37 with FitEngineConfiguration

use of uk.ac.sussex.gdsc.smlm.engine.FitEngineConfiguration in project GDSC-SMLM by aherbert.

the class PsfCalculator method run.

@Override
public void run(String arg) {
    SmlmUsageTracker.recordPlugin(this.getClass(), arg);
    final PSFCalculatorSettings settings = SettingsManager.readPsfCalculatorSettings(0);
    final double sd = calculate(settings, false);
    if (sd < 0) {
        return;
    }
    SettingsManager.writeSettings(this.settingsBuilder);
    final FitEngineConfiguration config = SettingsManager.readFitEngineConfiguration(0);
    final FitConfiguration fitConfig = config.getFitConfiguration();
    fitConfig.setNmPerPixel(getPixelPitch());
    fitConfig.setPsfType(PSFType.ONE_AXIS_GAUSSIAN_2D);
    fitConfig.setInitialPeakStdDev(sd);
    SettingsManager.writeSettings(config, 0);
}
Also used : PSFCalculatorSettings(uk.ac.sussex.gdsc.smlm.ij.settings.GUIProtos.PSFCalculatorSettings) FitEngineConfiguration(uk.ac.sussex.gdsc.smlm.engine.FitEngineConfiguration) FitConfiguration(uk.ac.sussex.gdsc.smlm.engine.FitConfiguration)

Example 38 with FitEngineConfiguration

use of uk.ac.sussex.gdsc.smlm.engine.FitEngineConfiguration in project GDSC-SMLM by aherbert.

the class SpotFinderPreview method showDialog.

@Override
public int showDialog(ImagePlus imp, String command, PlugInFilterRunner pfr) {
    settings = Settings.load();
    this.overlay = imp.getOverlay();
    this.imp = imp;
    // Saved by reference so do it once now
    settings.save();
    // The image is locked by the PlugInFilterRunner so unlock it to allow scroll.
    // This should be OK as the image data is not modified and only the overlay is
    // adjusted. If another plugin changes the image then the preview should update
    // the overlay and it will be obvious to the user to turn this plugin off.
    imp.unlock();
    config = SettingsManager.readFitEngineConfiguration(0);
    fitConfig = config.getFitConfiguration();
    gd = new NonBlockingExtendedGenericDialog(TITLE);
    gd.addHelp(HelpUrls.getUrl("spot-finder-preview"));
    gd.addMessage("Preview candidate maxima");
    final String[] templates = ConfigurationTemplate.getTemplateNames(true);
    gd.addChoice("Template", templates, templates[0]);
    final String[] models = CameraModelManager.listCameraModels(true);
    gd.addChoice("Camera_model_name", models, fitConfig.getCameraModelName());
    PeakFit.addPsfOptions(gd, (FitConfigurationProvider) () -> fitConfig);
    final PeakFit.SimpleFitEngineConfigurationProvider provider = new PeakFit.SimpleFitEngineConfigurationProvider(config);
    PeakFit.addDataFilterOptions(gd, provider);
    gd.addChoice("Spot_filter_2", SettingsManager.getDataFilterMethodNames(), config.getDataFilterMethod(1, settings.defaultDataFilterMethod).ordinal());
    PeakFit.addRelativeParameterOptions(gd, new RelativeParameterProvider(2.5, 4.5, "Smoothing_2", provider) {

        @Override
        void setAbsolute(boolean absolute) {
            final FitEngineConfiguration c = fitEngineConfigurationProvider.getFitEngineConfiguration();
            final DataFilterMethod m = c.getDataFilterMethod(1, settings.defaultDataFilterMethod);
            final double smooth = c.getDataFilterParameterValue(1, settings.defaultSmooth);
            c.setDataFilter(m, smooth, absolute, 1);
        }

        @Override
        boolean isAbsolute() {
            return fitEngineConfigurationProvider.getFitEngineConfiguration().getDataFilterParameterAbsolute(1, false);
        }

        @Override
        double getValue() {
            return fitEngineConfigurationProvider.getFitEngineConfiguration().getDataFilterParameterValue(1, settings.defaultSmooth);
        }
    });
    PeakFit.addSearchOptions(gd, provider);
    PeakFit.addBorderOptions(gd, provider);
    // Find if this image was created with ground truth data
    if (imp.getID() == CreateData.getImageId()) {
        final MemoryPeakResults results = CreateData.getResults();
        if (results != null) {
            gd.addSlider("Match_distance", 0, 2.5, settings.distance);
            gd.addSlider("Lower_match_distance (%)", 0, 100, settings.lowerDistance);
            gd.addCheckbox("Multiple_matches", settings.multipleMatches);
            gd.addCheckbox("Show_TP", settings.showTP);
            gd.addCheckbox("Show_FP", settings.showFP);
            gd.addMessage("");
            label = (Label) gd.getMessage();
            final boolean integerCoords = false;
            actualCoordinates = ResultsMatchCalculator.getCoordinates(results, integerCoords);
        }
    }
    if (label == null) {
        // If no ground truth data add options to show the spots by their rank
        // and number of neighbours
        gd.addSlider("Top_N", 0, 100, settings.topN);
        topNScrollBar = gd.getLastScrollbar();
        gd.addSlider("Select", 0, 100, settings.select);
        selectScrollBar = gd.getLastScrollbar();
        gd.addSlider("Neigbour_radius", 0, 10, settings.neighbourRadius);
    }
    ImageListener imageListener = null;
    if (ImageJUtils.isShowGenericDialog()) {
        // Listen for changes in the dialog options
        gd.addOptionCollectedListener(event -> {
            // Just run on the current processor
            if (preview) {
                run(imp.getProcessor());
            }
        });
        // Listen for changes to an image
        imageListener = new ImageAdapter() {

            @Override
            public void imageUpdated(ImagePlus imp) {
                if (SpotFinderPreview.this.imp.getID() == imp.getID() && preview && imp.getCurrentSlice() != currentSlice && filter != null) {
                    run(imp.getProcessor(), filter);
                }
            }
        };
        ImagePlus.addImageListener(imageListener);
        // Support template settings
        final Vector<TextField> numerics = gd.getNumericFields();
        final Vector<Choice> choices = gd.getChoices();
        final Iterator<TextField> nu = numerics.iterator();
        final Iterator<Choice> ch = choices.iterator();
        final Choice textTemplate = ch.next();
        textTemplate.removeItemListener(gd);
        textTemplate.removeKeyListener(gd);
        textTemplate.addItemListener(this::itemStateChanged);
        textCameraModelName = ch.next();
        textPsf = ch.next();
        textDataFilterType = ch.next();
        textDataFilterMethod = ch.next();
        textSmooth = nu.next();
        textDataFilterMethod2 = ch.next();
        textSmooth2 = nu.next();
        textSearch = nu.next();
        textBorder = nu.next();
    }
    gd.addPreviewCheckbox(pfr);
    gd.addDialogListener(this::dialogItemChanged);
    gd.setOKLabel("Save");
    gd.setCancelLabel("Close");
    gd.showDialog();
    if (imageListener != null) {
        ImagePlus.removeImageListener(imageListener);
    }
    if (!gd.wasCanceled() && !SettingsManager.writeSettings(config, SettingsManager.FLAG_SILENT)) {
        IJ.error(TITLE, "Failed to save settings");
    }
    // Reset
    imp.setOverlay(overlay);
    return DONE;
}
Also used : Choice(java.awt.Choice) ImageListener(ij.ImageListener) FitEngineConfiguration(uk.ac.sussex.gdsc.smlm.engine.FitEngineConfiguration) NonBlockingExtendedGenericDialog(uk.ac.sussex.gdsc.core.ij.gui.NonBlockingExtendedGenericDialog) ImagePlus(ij.ImagePlus) DataFilterMethod(uk.ac.sussex.gdsc.smlm.data.config.FitProtos.DataFilterMethod) RelativeParameterProvider(uk.ac.sussex.gdsc.smlm.ij.plugins.PeakFit.RelativeParameterProvider) ImageAdapter(uk.ac.sussex.gdsc.core.ij.ImageAdapter) TextField(java.awt.TextField) MemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults)

Example 39 with FitEngineConfiguration

use of uk.ac.sussex.gdsc.smlm.engine.FitEngineConfiguration in project GDSC-SMLM by aherbert.

the class DoubletAnalysis method saveTemplate.

/**
 * Save PeakFit configuration template using the current benchmark settings.
 *
 * @param summary the summary
 */
private void saveTemplate(String summary) {
    if (!settings.saveTemplate) {
        return;
    }
    // Start with a clone of the filter settings
    final FitEngineConfiguration config = FitEngineConfiguration.create();
    final FitConfiguration fitConfig = config.getFitConfiguration();
    fitConfig.setFitSettings(filterFitConfig.getFitSettings());
    // Copy settings used during fitting
    updateConfiguration(config);
    // Remove the PSF width to make the template generic
    fitConfig.setInitialPeakStdDev(0);
    fitConfig.setNmPerPixel(0);
    fitConfig.setGain(0);
    fitConfig.setNoise(0);
    // This was done fitting all the results
    config.setFailuresLimit(-1);
    if (settings.useBenchmarkSettings) {
        final FitEngineConfiguration pConfig = FitEngineConfiguration.create();
        // TODO - add option to use latest or the best
        if (BenchmarkFilterAnalysis.updateConfiguration(pConfig, false)) {
            config.setFailuresLimit(pConfig.getFailuresLimit());
        }
    }
    // Set the residuals
    fitConfig.setComputeResiduals(true);
    // TODO - make the choice of the best residuals configurable
    config.setResidualsThreshold(residualsScore.bestResiduals[2]);
    final String filename = BenchmarkFilterAnalysis.getFilename("Template_File", settings.templateFilename);
    if (filename != null) {
        settings.templateFilename = filename;
        final TemplateSettings.Builder settings = TemplateSettings.newBuilder();
        getNotes(settings, summary);
        settings.setFitEngineSettings(config.getFitEngineSettings());
        if (!SettingsManager.toJson(settings.build(), filename, SettingsManager.FLAG_SILENT)) {
            IJ.log("Unable to save the template configuration");
        }
    }
}
Also used : TemplateSettings(uk.ac.sussex.gdsc.smlm.data.config.TemplateProtos.TemplateSettings) FitEngineConfiguration(uk.ac.sussex.gdsc.smlm.engine.FitEngineConfiguration) FitConfiguration(uk.ac.sussex.gdsc.smlm.engine.FitConfiguration)

Example 40 with FitEngineConfiguration

use of uk.ac.sussex.gdsc.smlm.engine.FitEngineConfiguration in project GDSC-SMLM by aherbert.

the class BenchmarkFilterAnalysis method saveTemplate.

/**
 * Save PeakFit configuration template using the current benchmark settings.
 *
 * @param topFilterSummary the top filter summary
 */
private void saveTemplate(String topFilterSummary) {
    final FitEngineConfiguration config = FitEngineConfiguration.create();
    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);
    // Only get this once when doing iterative analysis
    String filename;
    final boolean localSaveTemplateIsSet = saveTemplateIsSet;
    if (localSaveTemplateIsSet) {
        filename = settings.templateFilename;
    } else {
        filename = getFilename("Template_File", settings.templateFilename);
        saveTemplateIsSet = true;
    }
    if (filename != null) {
        settings.templateFilename = filename;
        Prefs.set(Settings.KEY_TEMPLATE_FILENAME, filename);
        final TemplateSettings.Builder templateSettings = TemplateSettings.newBuilder();
        getNotes(templateSettings, topFilterSummary);
        templateSettings.setFitEngineSettings(config.getFitEngineSettings());
        if (!SettingsManager.toJson(templateSettings.build(), filename, SettingsManager.FLAG_SILENT | SettingsManager.FLAG_JSON_WHITESPACE)) {
            IJ.log("Unable to save the template configuration");
            return;
        }
        // This need only be performed once as the sample image is the same for all iterations.
        if (localSaveTemplateIsSet) {
            return;
        }
        // Save some random frames from the test image data
        final ImagePlus imp = CreateData.getImage();
        if (imp == null) {
            return;
        }
        // Get the number of frames
        final ResultsImageSampler sampler = getSampler(results, imp);
        if (!sampler.isValid()) {
            return;
        }
        // Iteratively show the example until the user is happy.
        // Yes = OK, No = Repeat, Cancel = Do not save
        final String keyNo = "nNo";
        final String keyLow = "nLower";
        final String keyHigh = "nHigher";
        if (ImageJUtils.isMacro()) {
            // Collect the options if running in a macro
            final String options = Macro.getOptions();
            settings.countNo = Integer.parseInt(Macro.getValue(options, keyNo, Integer.toString(settings.countNo)));
            settings.countLow = Integer.parseInt(Macro.getValue(options, keyLow, Integer.toString(settings.countLow)));
            settings.countHigh = Integer.parseInt(Macro.getValue(options, keyHigh, Integer.toString(settings.countHigh)));
        } else if (settings.countLow + settings.countHigh == 0) {
            settings.countLow = settings.countHigh = 1;
        }
        final ImagePlus[] out = new ImagePlus[1];
        out[0] = sampler.getSample(settings.countNo, settings.countLow, settings.countHigh);
        if (!ImageJUtils.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) {
                final WindowOrganiser windowOrganiser = new WindowOrganiser();
                outImp[0] = display(out[0], windowOrganiser);
                if (windowOrganiser.isNotEmpty()) {
                    close[0] = true;
                    // Zoom a bit
                    final 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.
            final ImageListener listener = new ImageListener() {

                @Override
                public void imageOpened(ImagePlus imp) {
                // Do nothing
                }

                @Override
                public void imageClosed(ImagePlus imp) {
                // Do nothing
                }

                @Override
                public void imageUpdated(ImagePlus imp) {
                    if (imp != null && imp == outImp[0]) {
                        configTemplate.updateResults(imp.getCurrentSlice());
                    }
                }
            };
            ImagePlus.addImageListener(listener);
            // Turn off the recorder when the dialog is showing
            final boolean record = Recorder.record;
            Recorder.record = false;
            final NonBlockingGenericDialog gd = new NonBlockingGenericDialog(TITLE);
            ImageJUtils.addMessage(gd, "Showing image data for the template example.\n \nSample Frames:\nEmpty = %d\n" + "Lower density = %d\nHigher density = %d\n", sampler.getNumberOfEmptySamples(), sampler.getNumberOfLowDensitySamples(), sampler.getNumberOfHighDensitySamples());
            gd.addSlider(keyNo, 0, 10, settings.countNo);
            gd.addSlider(keyLow, 0, 10, settings.countLow);
            gd.addSlider(keyHigh, 0, 10, settings.countHigh);
            gd.addDialogListener((genDialog, event) -> {
                // image the user has not seen.
                if (event == null) {
                    return true;
                }
                settings.countNo = (int) genDialog.getNextNumber();
                settings.countLow = (int) genDialog.getNextNumber();
                settings.countHigh = (int) genDialog.getNextNumber();
                out[0] = sampler.getSample(settings.countNo, settings.countLow, settings.countHigh);
                if (out[0] != null) {
                    final WindowOrganiser windowOrganiser = new WindowOrganiser();
                    outImp[0] = display(out[0], windowOrganiser);
                    if (windowOrganiser.isNotEmpty()) {
                        close[0] = true;
                        // Zoom a bit
                        final 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
                settings.countNo = settings.countLow = settings.countHigh = 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(settings.countNo));
                Recorder.recordOption(keyLow, Integer.toString(settings.countLow));
                Recorder.recordOption(keyHigh, Integer.toString(settings.countHigh));
            }
        }
        if (out[0] == null) {
            return;
        }
        final ImagePlus example = out[0];
        filename = FileUtils.replaceExtension(filename, ".tif");
        IJ.save(example, filename);
    }
}
Also used : ResultsImageSampler(uk.ac.sussex.gdsc.smlm.ij.results.ResultsImageSampler) ImageWindow(ij.gui.ImageWindow) ImageListener(ij.ImageListener) FitEngineConfiguration(uk.ac.sussex.gdsc.smlm.engine.FitEngineConfiguration) ConfigurationTemplate(uk.ac.sussex.gdsc.smlm.ij.plugins.ConfigurationTemplate) WindowOrganiser(uk.ac.sussex.gdsc.core.ij.plugin.WindowOrganiser) NonBlockingGenericDialog(ij.gui.NonBlockingGenericDialog) ImagePlus(ij.ImagePlus) TemplateSettings(uk.ac.sussex.gdsc.smlm.data.config.TemplateProtos.TemplateSettings)

Aggregations

FitEngineConfiguration (uk.ac.sussex.gdsc.smlm.engine.FitEngineConfiguration)43 FitConfiguration (uk.ac.sussex.gdsc.smlm.engine.FitConfiguration)16 ExtendedGenericDialog (uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog)10 TemplateSettings (uk.ac.sussex.gdsc.smlm.data.config.TemplateProtos.TemplateSettings)8 ImagePlus (ij.ImagePlus)6 Checkbox (java.awt.Checkbox)6 BasePoint (uk.ac.sussex.gdsc.core.match.BasePoint)6 DataFilterMethod (uk.ac.sussex.gdsc.smlm.data.config.FitProtos.DataFilterMethod)6 PeakResultPoint (uk.ac.sussex.gdsc.smlm.results.PeakResultPoint)6 MultiPathFilter (uk.ac.sussex.gdsc.smlm.results.filter.MultiPathFilter)6 ImageListener (ij.ImageListener)4 Choice (java.awt.Choice)4 Rectangle (java.awt.Rectangle)4 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)4 NonBlockingExtendedGenericDialog (uk.ac.sussex.gdsc.core.ij.gui.NonBlockingExtendedGenericDialog)4 MemoryPeakResults (uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults)4 DirectFilter (uk.ac.sussex.gdsc.smlm.results.filter.DirectFilter)4 ImageWindow (ij.gui.ImageWindow)2 NonBlockingGenericDialog (ij.gui.NonBlockingGenericDialog)2 TextField (java.awt.TextField)2