Search in sources :

Example 11 with FitEngineConfiguration

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

the class BenchmarkSpotFilter method updateConfiguration.

/**
	 * Updates the given configuration using the latest settings used in benchmarking.
	 *
	 * @param pConfig
	 *            the configuration
	 * @return true, if successful
	 */
public static boolean updateConfiguration(FitEngineConfiguration pConfig) {
    if (filterResult == null)
        return false;
    double scaleSearch = 1;
    double scaleSmooth = 1;
    if (!filterResult.relativeDistances) {
        // Distance were absolute. Convert using the HWHM so they are relative
        // to the configured fitting width.
        scaleSearch = 1 / pConfig.getHWHMMax();
        scaleSmooth = 1 / pConfig.getHWHMMin();
    }
    FitEngineConfiguration config = filterResult.config;
    pConfig.setDataFilterType(config.getDataFilterType());
    final int nFilters = config.getNumberOfFilters();
    for (int n = 0; n < nFilters; n++) {
        pConfig.setDataFilter(config.getDataFilter(n), config.getSmooth(n) * scaleSmooth, n);
    }
    pConfig.setSearch(config.getSearch() * scaleSearch);
    pConfig.setBorder(config.getBorder() * scaleSearch);
    return true;
}
Also used : FitEngineConfiguration(gdsc.smlm.engine.FitEngineConfiguration) PeakResultPoint(gdsc.smlm.ij.plugins.ResultsMatchCalculator.PeakResultPoint) BasePoint(gdsc.core.match.BasePoint)

Example 12 with FitEngineConfiguration

use of 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
	 */
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)

Example 13 with FitEngineConfiguration

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

the class PSFDrift method run.

/*
	 * (non-Javadoc)
	 * 
	 * @see ij.plugin.PlugIn#run(java.lang.String)
	 */
public void run(String arg) {
    SMLMUsageTracker.recordPlugin(this.getClass(), arg);
    // Build a list of suitable images
    List<String> titles = createImageList();
    if (titles.isEmpty()) {
        IJ.error(TITLE, "No suitable PSF images");
        return;
    }
    if ("hwhm".equals(arg)) {
        showHWHM(titles);
        return;
    }
    GenericDialog gd = new GenericDialog(TITLE);
    gd.addMessage("Select the input PSF image");
    gd.addChoice("PSF", titles.toArray(new String[titles.size()]), title);
    gd.addCheckbox("Use_offset", useOffset);
    gd.addNumericField("Scale", scale, 2);
    gd.addNumericField("z_depth", zDepth, 2, 6, "nm");
    gd.addNumericField("Grid_size", gridSize, 0);
    gd.addSlider("Recall_limit", 0.01, 1, recallLimit);
    gd.addSlider("Region_size", 2, 20, regionSize);
    gd.addCheckbox("Background_fitting", backgroundFitting);
    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()]);
    // We need these to set bounds for any bounded fitters
    gd.addSlider("Min_width_factor", 0, 0.99, fitConfig.getMinWidthFactor());
    gd.addSlider("Width_factor", 1.01, 5, fitConfig.getWidthFactor());
    gd.addCheckbox("Offset_fit", offsetFitting);
    gd.addNumericField("Start_offset", startOffset, 3);
    gd.addCheckbox("Include_CoM_fit", comFitting);
    gd.addCheckbox("Use_sampling", useSampling);
    gd.addNumericField("Photons", photons, 0);
    gd.addSlider("Photon_limit", 0, 1, photonLimit);
    gd.addSlider("Smoothing", 0, 0.5, smoothing);
    gd.showDialog();
    if (gd.wasCanceled())
        return;
    title = gd.getNextChoice();
    useOffset = gd.getNextBoolean();
    scale = gd.getNextNumber();
    zDepth = gd.getNextNumber();
    gridSize = (int) gd.getNextNumber();
    recallLimit = gd.getNextNumber();
    regionSize = (int) Math.abs(gd.getNextNumber());
    backgroundFitting = gd.getNextBoolean();
    fitConfig.setFitSolver(gd.getNextChoiceIndex());
    fitConfig.setFitFunction(gd.getNextChoiceIndex());
    fitConfig.setMinWidthFactor(gd.getNextNumber());
    fitConfig.setWidthFactor(gd.getNextNumber());
    offsetFitting = gd.getNextBoolean();
    startOffset = Math.abs(gd.getNextNumber());
    comFitting = gd.getNextBoolean();
    useSampling = gd.getNextBoolean();
    photons = Math.abs(gd.getNextNumber());
    photonLimit = Math.abs(gd.getNextNumber());
    smoothing = Math.abs(gd.getNextNumber());
    if (!comFitting && !offsetFitting) {
        IJ.error(TITLE, "No initial fitting positions");
        return;
    }
    if (regionSize < 1)
        regionSize = 1;
    if (gd.invalidNumber())
        return;
    GlobalSettings settings = new GlobalSettings();
    settings.setFitEngineConfiguration(new FitEngineConfiguration(fitConfig));
    if (!PeakFit.configureFitSolver(settings, null, false, true))
        return;
    imp = WindowManager.getImage(title);
    if (imp == null) {
        IJ.error(TITLE, "No PSF image for image: " + title);
        return;
    }
    psfSettings = getPSFSettings(imp);
    if (psfSettings == null) {
        IJ.error(TITLE, "No PSF settings for image: " + title);
        return;
    }
    computeDrift();
}
Also used : FitEngineConfiguration(gdsc.smlm.engine.FitEngineConfiguration) GenericDialog(ij.gui.GenericDialog) GlobalSettings(gdsc.smlm.ij.settings.GlobalSettings)

Example 14 with FitEngineConfiguration

use of 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
	 */
private void saveTemplate(String summary) {
    if (!saveTemplate)
        return;
    // Start with a clone of the filter settings
    FitConfiguration fitConfig = filterFitConfig.clone();
    FitEngineConfiguration config = new FitEngineConfiguration(fitConfig);
    // 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 (useBenchmarkSettings) {
        FitEngineConfiguration pConfig = new FitEngineConfiguration(new FitConfiguration());
        // 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]);
    String filename = BenchmarkFilterAnalysis.getFilename("Template_File", templateFilename);
    if (filename != null) {
        templateFilename = filename;
        GlobalSettings settings = new GlobalSettings();
        settings.setNotes(getNotes(summary));
        settings.setFitEngineConfiguration(config);
        if (!SettingsManager.saveSettings(settings, filename, true))
            IJ.log("Unable to save the template configuration");
    }
}
Also used : FitConfiguration(gdsc.smlm.fitting.FitConfiguration) FitEngineConfiguration(gdsc.smlm.engine.FitEngineConfiguration) GlobalSettings(gdsc.smlm.ij.settings.GlobalSettings)

Example 15 with FitEngineConfiguration

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

the class Configuration method refreshSettings.

private void refreshSettings(String newFilename) {
    if (newFilename != null && new File(newFilename).exists()) {
        YesNoCancelDialog d = new YesNoCancelDialog(IJ.getInstance(), TITLE, "Reload settings from file");
        d.setVisible(true);
        if (d.yesPressed()) {
            // Reload the settings and update the GUI
            // XXX : This does not deal with loading settings into fields that are not displayed,
            // e.g. for configuring the Fit Solvers. This could be done by writing into
            // a class scope settings instance (loaded in showDialog()). However the user would not 
            // see all the changes that have been written, since the later dialogs are shown depending 
            // on what options are initially configured. 
            GlobalSettings settings = SettingsManager.unsafeLoadSettings(newFilename, false);
            if (settings == null)
                return;
            FitEngineConfiguration config = settings.getFitEngineConfiguration();
            FitConfiguration fitConfig = config.getFitConfiguration();
            Calibration calibration = settings.getCalibration();
            textNmPerPixel.setText("" + calibration.getNmPerPixel());
            textGain.setText("" + calibration.getGain());
            textEMCCD.setState(calibration.isEmCCD());
            textExposure.setText("" + calibration.getExposureTime());
            textInitialPeakStdDev0.setText("" + fitConfig.getInitialPeakStdDev0());
            textInitialPeakStdDev1.setText("" + fitConfig.getInitialPeakStdDev1());
            textInitialAngleD.setText("" + fitConfig.getInitialAngle());
            textDataFilterType.select(config.getDataFilterType().ordinal());
            textDataFilter.select(config.getDataFilter(0).ordinal());
            textSmooth.setText("" + config.getSmooth(0));
            textSearch.setText("" + config.getSearch());
            textBorder.setText("" + config.getBorder());
            textFitting.setText("" + config.getFitting());
            textFitSolver.select(fitConfig.getFitSolver().ordinal());
            textFitFunction.select(fitConfig.getFitFunction().ordinal());
            textFailuresLimit.setText("" + config.getFailuresLimit());
            textIncludeNeighbours.setState(config.isIncludeNeighbours());
            textNeighbourHeightThreshold.setText("" + config.getNeighbourHeightThreshold());
            textResidualsThreshold.setText("" + config.getResidualsThreshold());
            textDuplicateDistance.setText("" + fitConfig.getDuplicateDistance());
            textCoordinateShiftFactor.setText("" + fitConfig.getCoordinateShiftFactor());
            textSignalStrength.setText("" + fitConfig.getSignalStrength());
            textMinPhotons.setText("" + fitConfig.getMinPhotons());
            textMinWidthFactor.setText("" + fitConfig.getMinWidthFactor());
            textWidthFactor.setText("" + fitConfig.getWidthFactor());
            textPrecisionThreshold.setText("" + fitConfig.getPrecisionThreshold());
        }
    }
}
Also used : FitEngineConfiguration(gdsc.smlm.engine.FitEngineConfiguration) FitConfiguration(gdsc.smlm.fitting.FitConfiguration) YesNoCancelDialog(ij.gui.YesNoCancelDialog) GlobalSettings(gdsc.smlm.ij.settings.GlobalSettings) Calibration(gdsc.smlm.results.Calibration) File(java.io.File)

Aggregations

FitEngineConfiguration (gdsc.smlm.engine.FitEngineConfiguration)22 FitConfiguration (gdsc.smlm.fitting.FitConfiguration)16 GlobalSettings (gdsc.smlm.ij.settings.GlobalSettings)9 ExtendedGenericDialog (ij.gui.ExtendedGenericDialog)6 Calibration (gdsc.smlm.results.Calibration)5 GenericDialog (ij.gui.GenericDialog)4 Checkbox (java.awt.Checkbox)4 XStreamException (com.thoughtworks.xstream.XStreamException)3 BasePoint (gdsc.core.match.BasePoint)3 PeakResultPoint (gdsc.smlm.ij.plugins.ResultsMatchCalculator.PeakResultPoint)3 ResultsSettings (gdsc.smlm.ij.settings.ResultsSettings)3 DirectFilter (gdsc.smlm.results.filter.DirectFilter)3 MultiPathFilter (gdsc.smlm.results.filter.MultiPathFilter)3 MemoryPeakResults (gdsc.smlm.results.MemoryPeakResults)2 Choice (java.awt.Choice)2 TextField (java.awt.TextField)2 File (java.io.File)2 FileNotFoundException (java.io.FileNotFoundException)2 IOException (java.io.IOException)2 Vector (java.util.Vector)2