use of gdsc.smlm.ij.settings.GlobalSettings in project GDSC-SMLM by aherbert.
the class ResultsManager method showDialog.
private boolean showDialog() {
ExtendedGenericDialog gd = new ExtendedGenericDialog(TITLE);
gd.addHelp(About.HELP_URL);
// Build a list of all images with a region ROI
List<String> titles = new LinkedList<String>();
if (WindowManager.getWindowCount() > 0) {
for (int imageID : WindowManager.getIDList()) {
ImagePlus imp = WindowManager.getImage(imageID);
if (imp != null && imp.getRoi() != null && imp.getRoi().isArea())
titles.add(imp.getTitle());
}
}
GlobalSettings settings = SettingsManager.loadSettings();
resultsSettings = settings.getResultsSettings();
gd.addMessage("Read the Peak Results and output to a new format");
gd.addMessage("Select the Peak Results");
addInput(gd, inputOption, InputSource.MEMORY, InputSource.FILE);
if (!titles.isEmpty())
gd.addCheckbox((titles.size() == 1) ? "Use_ROI" : "Choose_ROI", chooseRoi);
gd.addMessage("--- Table output ---");
String[] tableNames = SettingsManager.getNames((Object[]) ResultsTable.values());
gd.addChoice("Results_table", tableNames, tableNames[resultsSettings.getResultsTable().ordinal()], new OptionListener<Choice>() {
@Override
public void collectOptions(Choice field) {
ExtendedGenericDialog egd = new ExtendedGenericDialog(TITLE, null);
egd.addCheckbox("Show_deviations", resultsSettings.showDeviations);
egd.showDialog(true);
if (egd.wasCanceled())
return;
resultsSettings.showDeviations = egd.getNextBoolean();
}
@Override
public void collectOptions() {
collectOptions(null);
}
});
gd.addMessage("--- Image output ---");
String[] imageNames = SettingsManager.getNames((Object[]) ResultsImage.values());
gd.addChoice("Image", imageNames, imageNames[resultsSettings.getResultsImage().ordinal()]);
// TODO - move these to an options pop-uo
gd.addCheckbox("Weighted", resultsSettings.weightedImage);
gd.addCheckbox("Equalised", resultsSettings.equalisedImage);
gd.addSlider("Image_Precision (nm)", 5, 30, resultsSettings.precision);
gd.addSlider("Image_Scale", 1, 15, resultsSettings.imageScale);
gd.addNumericField("Image_Window", resultsSettings.imageRollingWindow, 0);
gd.addMessage("--- File output ---");
// Do not add a results file to prevent constant overwrite messages
gd.addFilenameField("Results_file", "");
// TODO - move these to an options pop-uo
String[] formatNames = SettingsManager.getNames((Object[]) ResultsFileFormat.values());
gd.addChoice("Results_format", formatNames, formatNames[resultsSettings.getResultsFileFormat().ordinal()]);
gd.addMessage(" ");
gd.addCheckbox("Results_in_memory (file input only)", resultsSettings.resultsInMemory);
gd.showDialog();
if (gd.wasCanceled())
return false;
inputOption = ResultsManager.getInputSource(gd);
inputFilename = gd.getNextString();
if (!titles.isEmpty())
chooseRoi = gd.getNextBoolean();
resultsSettings.setResultsTable(gd.getNextChoiceIndex());
resultsSettings.showDeviations = gd.getNextBoolean();
resultsSettings.setResultsImage(gd.getNextChoiceIndex());
resultsSettings.weightedImage = gd.getNextBoolean();
resultsSettings.equalisedImage = gd.getNextBoolean();
resultsSettings.precision = gd.getNextNumber();
resultsSettings.imageScale = gd.getNextNumber();
resultsSettings.imageRollingWindow = (int) gd.getNextNumber();
resultsSettings.resultsFilename = gd.getNextString();
resultsSettings.setResultsFileFormat(gd.getNextChoiceIndex());
resultsSettings.resultsInMemory = gd.getNextBoolean();
// Check arguments
try {
if (resultsSettings.getResultsImage() == ResultsImage.SIGNAL_AV_PRECISION || resultsSettings.getResultsImage() == ResultsImage.LOCALISATIONS_AV_PRECISION) {
Parameters.isAboveZero("Image precision", resultsSettings.precision);
}
Parameters.isAboveZero("Image scale", resultsSettings.imageScale);
Parameters.isPositive("Image rolling window", resultsSettings.imageRollingWindow);
} catch (IllegalArgumentException e) {
IJ.error(TITLE, e.getMessage());
return false;
}
Prefs.set(Constants.inputFilename, inputFilename);
if (!titles.isEmpty() && chooseRoi) {
if (titles.size() == 1) {
roiImage = titles.get(0);
Recorder.recordOption("Image", roiImage);
} else {
String[] items = titles.toArray(new String[titles.size()]);
gd = new ExtendedGenericDialog(TITLE);
gd.addMessage("Select the source image for the ROI");
gd.addChoice("Image", items, roiImage);
gd.showDialog();
if (gd.wasCanceled())
return false;
roiImage = gd.getNextChoice();
}
ImagePlus imp = WindowManager.getImage(roiImage);
roiBounds = imp.getRoi().getBounds();
roiImageWidth = imp.getWidth();
roiImageHeight = imp.getHeight();
} else {
roiBounds = null;
}
SettingsManager.saveSettings(settings);
return true;
}
use of gdsc.smlm.ij.settings.GlobalSettings in project GDSC-SMLM by aherbert.
the class PeakFit method showDialog.
@SuppressWarnings("unchecked")
private int showDialog(ImagePlus imp) {
// Executing as an ImageJ plugin.
// Override the defaults with those in the configuration file
final String filename = SettingsManager.getSettingsFilename();
if (simpleFit) {
return showSimpleDialog(filename);
}
GlobalSettings settings = SettingsManager.loadSettings(filename);
calibration = settings.getCalibration();
config = settings.getFitEngineConfiguration();
fitConfig = config.getFitConfiguration();
resultsSettings = settings.getResultsSettings();
boolean isCrop = (bounds != null && imp != null && (bounds.width < imp.getWidth() || bounds.height < imp.getHeight()));
if (!extraOptions) {
integrateFrames = 1;
resultsSettings.imageRollingWindow = 0;
fitConfig.setBackgroundFitting(true);
fitConfig.setMinIterations(0);
fitConfig.setNoise(0);
config.setNoiseMethod(Method.QUICK_RESIDUALS_LEAST_MEAN_OF_SQUARES);
showProcessedFrames = false;
}
ExtendedGenericDialog gd = new ExtendedGenericDialog(TITLE);
gd.addHelp(About.HELP_URL);
gd.addMessage((maximaIdentification) ? "Identify candidate maxima" : "Fit 2D Gaussian to identified maxima");
String[] templates = ConfigurationTemplate.getTemplateNames(true);
gd.addChoice("Template", templates, templates[0]);
gd.addStringField("Config_file", filename, 40);
gd.addNumericField("Calibration (nm/px)", calibration.getNmPerPixel(), 2);
gd.addNumericField("Gain (ADU/photon)", calibration.getGain(), 2);
gd.addCheckbox("EM-CCD", calibration.isEmCCD());
gd.addNumericField("Exposure_time (ms)", calibration.getExposureTime(), 2);
if (isCrop)
gd.addCheckbox("Ignore_bounds_for_noise", optionIgnoreBoundsForNoise);
// This is already set to false before the dialog is displayed
//else
// ignoreBoundsForNoise = false;
gd.addNumericField("Initial_StdDev0", fitConfig.getInitialPeakStdDev0(), 3);
if (!maximaIdentification) {
gd.addNumericField("Initial_StdDev1", fitConfig.getInitialPeakStdDev1(), 3);
gd.addNumericField("Initial_Angle", fitConfig.getInitialAngle(), 3);
}
String[] filterTypes = SettingsManager.getNames((Object[]) DataFilterType.values());
gd.addChoice("Spot_filter_type", filterTypes, filterTypes[config.getDataFilterType().ordinal()]);
String[] filterNames = SettingsManager.getNames((Object[]) DataFilter.values());
gd.addChoice("Spot_filter", filterNames, filterNames[config.getDataFilter(0).ordinal()]);
gd.addSlider("Smoothing", 0, 2.5, config.getSmooth(0));
gd.addSlider("Search_width", 0.5, 2.5, config.getSearch());
gd.addSlider("Border", 0.5, 2.5, config.getBorder());
gd.addSlider("Fitting_width", 2, 4.5, config.getFitting());
if (extraOptions && !fitMaxima) {
gd.addCheckbox("Interlaced_data", optionInterlacedData);
gd.addSlider("Integrate_frames", 1, 5, optionIntegrateFrames);
}
Component discardLabel = null;
if (!maximaIdentification) {
gd.addMessage("--- Gaussian fitting ---");
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()]);
if (extraOptions)
gd.addCheckbox("Fit_background", fitConfig.isBackgroundFitting());
// Parameters specific to each Fit solver are collected in a second dialog
gd.addNumericField("Fail_limit", config.getFailuresLimit(), 0);
gd.addCheckbox("Include_neighbours", config.isIncludeNeighbours());
gd.addSlider("Neighbour_height", 0.01, 1, config.getNeighbourHeightThreshold());
gd.addSlider("Residuals_threshold", 0.01, 1, config.getResidualsThreshold());
gd.addSlider("Duplicate_distance", 0, 1.5, fitConfig.getDuplicateDistance());
gd.addMessage("--- Peak filtering ---\nDiscard fits that shift; are too low; or expand/contract");
discardLabel = gd.getMessage();
gd.addCheckbox("Smart_filter", fitConfig.isSmartFilter());
gd.addCheckbox("Disable_simple_filter", fitConfig.isDisableSimpleFilter());
gd.addSlider("Shift_factor", 0.01, 2, fitConfig.getCoordinateShiftFactor());
gd.addNumericField("Signal_strength", fitConfig.getSignalStrength(), 2);
gd.addNumericField("Min_photons", fitConfig.getMinPhotons(), 0);
if (extraOptions) {
gd.addNumericField("Noise", fitConfig.getNoise(), 2);
String[] noiseMethodNames = SettingsManager.getNames((Object[]) Method.values());
gd.addChoice("Noise_method", noiseMethodNames, noiseMethodNames[config.getNoiseMethod().ordinal()]);
}
gd.addSlider("Min_width_factor", 0, 0.99, fitConfig.getMinWidthFactor());
gd.addSlider("Width_factor", 1.01, 5, fitConfig.getWidthFactor());
gd.addNumericField("Precision", fitConfig.getPrecisionThreshold(), 2);
}
gd.addMessage("--- Results ---");
gd.addCheckbox("Log_progress", resultsSettings.logProgress);
if (!maximaIdentification) {
gd.addCheckbox("Show_deviations", resultsSettings.showDeviations);
}
String[] tableNames = SettingsManager.getNames((Object[]) ResultsTable.values());
gd.addChoice("Results_table", tableNames, tableNames[resultsSettings.getResultsTable().ordinal()]);
String[] imageNames = SettingsManager.getNames((Object[]) ResultsImage.values());
gd.addMessage("--- Image output ---");
gd.addChoice("Image", imageNames, imageNames[resultsSettings.getResultsImage().ordinal()]);
gd.addCheckbox("Weighted", resultsSettings.weightedImage);
gd.addCheckbox("Equalised", resultsSettings.equalisedImage);
gd.addSlider("Image_Precision (nm)", 5, 30, resultsSettings.precision);
gd.addSlider("Image_Scale", 1, 15, resultsSettings.imageScale);
if (extraOptions) {
gd.addNumericField("Image_window", resultsSettings.imageRollingWindow, 0);
gd.addCheckbox("Show_processed_frames", optionShowProcessedFrames);
}
gd.addMessage("--- File output ---");
gd.addStringField("Results_dir", resultsSettings.resultsDirectory);
String[] formatNames = SettingsManager.getNames((Object[]) ResultsFileFormat.values());
gd.addChoice("Results_format", formatNames, formatNames[resultsSettings.getResultsFileFormat().ordinal()]);
gd.addMessage(" ");
gd.addCheckbox("Results_in_memory", resultsSettings.resultsInMemory);
if (extraOptions) {
gd.addMessage("--- Misc ---");
gd.addSlider("Fraction_of_threads", 0.1, 1, fractionOfThreads);
}
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));
}
// Add a mouse listener to the config file field
if (Utils.isShowGenericDialog()) {
Vector<TextField> texts = (Vector<TextField>) gd.getStringFields();
Vector<TextField> numerics = (Vector<TextField>) gd.getNumericFields();
Vector<Checkbox> checkboxes = (Vector<Checkbox>) gd.getCheckboxes();
Vector<Choice> choices = (Vector<Choice>) gd.getChoices();
int n = 0;
int t = 0;
int b = 0;
int ch = 0;
Choice textTemplate = choices.get(ch++);
textTemplate.addItemListener(this);
textConfigFile = texts.get(t++);
textConfigFile.addMouseListener(this);
textConfigFile.addTextListener(this);
// TODO: add a value changed listener to detect when typing a new file
textNmPerPixel = numerics.get(n++);
textGain = numerics.get(n++);
textEMCCD = checkboxes.get(b++);
textExposure = numerics.get(n++);
textInitialPeakStdDev0 = numerics.get(n++);
if (!maximaIdentification) {
textInitialPeakStdDev1 = numerics.get(n++);
textInitialAngleD = numerics.get(n++);
}
textDataFilterType = choices.get(ch++);
textDataFilter = choices.get(ch++);
textSmooth = numerics.get(n++);
textSearch = numerics.get(n++);
textBorder = numerics.get(n++);
textFitting = numerics.get(n++);
if (extraOptions && !fitMaxima) {
// Skip over the interlaced data option
b++;
// Skip over the integrate frames option
n++;
}
if (!maximaIdentification) {
textFitSolver = choices.get(ch++);
textFitFunction = choices.get(ch++);
if (extraOptions)
textFitBackground = checkboxes.get(b++);
textFailuresLimit = numerics.get(n++);
textIncludeNeighbours = checkboxes.get(b++);
textNeighbourHeightThreshold = numerics.get(n++);
textResidualsThreshold = numerics.get(n++);
textDuplicateDistance = numerics.get(n++);
textSmartFilter = checkboxes.get(b++);
textDisableSimpleFilter = checkboxes.get(b++);
textCoordinateShiftFactor = numerics.get(n++);
textSignalStrength = numerics.get(n++);
textMinPhotons = numerics.get(n++);
if (extraOptions) {
textNoise = numerics.get(n++);
textNoiseMethod = choices.get(ch++);
}
textMinWidthFactor = numerics.get(n++);
textWidthFactor = numerics.get(n++);
textPrecisionThreshold = numerics.get(n++);
updateFilterInput();
textSmartFilter.addItemListener(this);
textDisableSimpleFilter.addItemListener(this);
}
textLogProgress = checkboxes.get(b++);
if (!maximaIdentification)
textShowDeviations = checkboxes.get(b++);
textResultsTable = choices.get(ch++);
textResultsImage = choices.get(ch++);
textWeightedImage = checkboxes.get(b++);
textEqualisedImage = checkboxes.get(b++);
textPrecision = numerics.get(n++);
textImageScale = numerics.get(n++);
if (extraOptions) {
textImageRollingWindow = numerics.get(n++);
// Skip over show processed frames option
b++;
}
textResultsDirectory = texts.get(t++);
textResultsDirectory.addMouseListener(this);
textBinaryResults = choices.get(ch++);
textResultsInMemory = checkboxes.get(b++);
}
gd.showDialog();
// The refreshSettings method can be called by the dialog listener.
// This updates the Calibration, FitEngineConfiguration, and ResultsSettings so set these
// back in the GlobalSettings object.
settings.setCalibration(this.calibration);
settings.setFitEngineConfiguration(this.config);
settings.setResultsSettings(this.resultsSettings);
if (gd.wasCanceled() || !readDialog(settings, gd, isCrop))
return DONE;
if (imp != null) {
// Store whether the user selected to process all the images.
int flags = IJ.setupDialog(imp, plugin_flags);
// Check if cancelled
if ((flags & DONE) != 0)
return DONE;
if ((flags & DOES_STACKS) == 0) {
// Save the slice number for the overlay
singleFrame = imp.getCurrentSlice();
// Account for interlaced data
if (interlacedData) {
int start = singleFrame;
// Calculate the first frame that is not skipped
while (ignoreFrame(start) && start > dataStart) start--;
if (start < dataStart) {
log("The current frame (%d) is before the start of the interlaced data", singleFrame);
return DONE;
}
if (start != singleFrame)
log("Updated the current frame (%d) to a valid interlaced data frame (%d)", singleFrame, start);
singleFrame = start;
}
// Account for integrated frames
int endFrame = singleFrame;
if (integrateFrames > 1) {
int totalFrames = 1;
while (totalFrames < integrateFrames) {
endFrame++;
if (!ignoreFrame(endFrame))
totalFrames++;
}
log("Updated the image end frame (%d) to %d allow %d integrated frames", singleFrame, endFrame, integrateFrames);
}
// Create a new image source with the correct frames
setSource(new IJImageSource(imp, singleFrame, endFrame - singleFrame));
// Store the image so the results can be added as an overlay
this.imp = imp;
this.imp.setOverlay(null);
}
}
// Allow interlaced data by wrapping the image source
if (interlacedData) {
setSource(new InterlacedImageSource(this.source, dataStart, dataBlock, dataSkip));
}
// Allow frame aggregation by wrapping the image source
if (integrateFrames > 1) {
setSource(new AggregatedImageSource(this.source, integrateFrames));
}
// Ask if the user wants to log progress on multiple frame images
if (resultsSettings.logProgress && source.getFrames() > 1) {
gd = new ExtendedGenericDialog(TITLE);
gd.addMessage("Warning: Log progress on multiple-frame image will be slow");
gd.addCheckbox("Log_progress", resultsSettings.logProgress);
gd.showDialog();
if (gd.wasCanceled())
return DONE;
resultsSettings.logProgress = gd.getNextBoolean();
if (!resultsSettings.logProgress)
SettingsManager.saveSettings(settings, filename);
}
// Get a bias if required
if (resultsSettings.getResultsTable() == ResultsTable.CALIBRATED && calibration.getBias() == 0) {
gd = new ExtendedGenericDialog(TITLE);
gd.addMessage("Calibrated results requires a camera bias");
gd.addNumericField("Camera_bias (ADUs)", calibration.getBias(), 2);
gd.showDialog();
if (!gd.wasCanceled()) {
calibration.setBias(Math.abs(gd.getNextNumber()));
if (calibration.getBias() > 0)
SettingsManager.saveSettings(settings, filename);
}
}
// single call to be made.
return plugin_flags;
}
use of gdsc.smlm.ij.settings.GlobalSettings in project GDSC-SMLM by aherbert.
the class PeakFit method itemStateChanged.
public void itemStateChanged(ItemEvent e) {
if (e.getSource() instanceof Choice) {
// Update the settings from the template
Choice choice = (Choice) e.getSource();
String templateName = choice.getSelectedItem();
//System.out.println("Update to " + templateName);
// Get the configuration template
GlobalSettings template = ConfigurationTemplate.getTemplate(templateName);
if (template != null) {
String notes = template.getNotes();
IJ.log("Applying template: " + templateName);
if (!Utils.isNullOrEmpty(notes))
IJ.log(notes);
boolean custom = ConfigurationTemplate.isCustomTemplate(templateName);
if (template.isFitEngineConfiguration()) {
refreshSettings(template.getFitEngineConfiguration().clone(), custom);
}
if (template.isCalibration()) {
refreshSettings(template.getCalibration().clone());
}
if (template.isResultsSettings()) {
refreshSettings(template.getResultsSettings().clone());
}
}
} else if (e.getSource() instanceof Checkbox) {
if (e.getSource() == textSmartFilter) {
// Prevent both filters being enabled
textDisableSimpleFilter.setState(textSmartFilter.getState());
updateFilterInput();
} else if (e.getSource() == textDisableSimpleFilter) {
updateFilterInput();
} else {
// Run the PSF Calculator
Checkbox cb = (Checkbox) e.getSource();
if (cb.getState()) {
cb.setState(false);
PSFCalculator calculator = new PSFCalculator();
calculatorSettings.pixelPitch = calibration.getNmPerPixel() / 1000.0;
calculatorSettings.magnification = 1;
calculatorSettings.beamExpander = 1;
double sd = calculator.calculate(calculatorSettings, true);
if (sd > 0)
textInitialPeakStdDev0.setText(Double.toString(sd));
}
}
}
}
use of gdsc.smlm.ij.settings.GlobalSettings in project GDSC-SMLM by aherbert.
the class BenchmarkSpotFit method showDialog.
@SuppressWarnings("unchecked")
private boolean showDialog() {
GenericDialog gd = new GenericDialog(TITLE);
gd.addHelp(About.HELP_URL);
gd.addMessage(String.format("Fit candidate spots in the benchmark image created by " + CreateData.TITLE + " plugin\nand identified by the " + BenchmarkSpotFilter.TITLE + " plugin.\nPSF width = %s nm (Square pixel adjustment = %s nm)\n \nConfigure the fitting:", Utils.rounded(simulationParameters.s), Utils.rounded(getSa())));
gd.addSlider("Fraction_positives", 50, 100, fractionPositives);
gd.addSlider("Fraction_negatives_after_positives", 0, 100, fractionNegativesAfterAllPositives);
gd.addSlider("Min_negatives_after_positives", 0, 10, negativesAfterAllPositives);
gd.addSlider("Match_distance", 0.5, 3.5, distance);
gd.addSlider("Lower_distance", 0, 3.5, lowerDistance);
gd.addSlider("Match_signal", 0, 3.5, signalFactor);
gd.addSlider("Lower_signal", 0, 3.5, lowerSignalFactor);
// Collect options for fitting
final double sa = getSa();
gd.addNumericField("Initial_StdDev", Maths.round(sa / simulationParameters.a), 3);
gd.addSlider("Fitting_width", 2, 4.5, config.getFitting());
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.addMessage("Multi-path filter (used to pick optimum results during fitting)");
// Allow loading the best filter fot these results
boolean benchmarkSettingsCheckbox = fitResultsId == BenchmarkFilterAnalysis.lastId;
// This should always be an opt-in decision. Otherwise the user cannot use the previous settings
useBenchmarkSettings = false;
if (benchmarkSettingsCheckbox)
gd.addCheckbox("Benchmark_settings", useBenchmarkSettings);
gd.addTextAreas(XmlUtils.convertQuotes(multiFilter.toXML()), null, 6, 60);
gd.addNumericField("Fail_limit", config.getFailuresLimit(), 0);
gd.addCheckbox("Include_neighbours", config.isIncludeNeighbours());
gd.addSlider("Neighbour_height", 0.01, 1, config.getNeighbourHeightThreshold());
//gd.addSlider("Residuals_threshold", 0.01, 1, config.getResidualsThreshold());
gd.addCheckbox("Compute_doublets", computeDoublets);
gd.addNumericField("Duplicate_distance", fitConfig.getDuplicateDistance(), 2);
gd.addCheckbox("Show_score_histograms", showFilterScoreHistograms);
gd.addCheckbox("Show_correlation", showCorrelation);
gd.addCheckbox("Plot_rank_by_intensity", rankByIntensity);
gd.addCheckbox("Save_filter_range", saveFilterRange);
if (extraOptions) {
}
// Add a mouse listener to the config file field
if (benchmarkSettingsCheckbox && Utils.isShowGenericDialog()) {
Vector<TextField> numerics = (Vector<TextField>) gd.getNumericFields();
Vector<Checkbox> checkboxes = (Vector<Checkbox>) gd.getCheckboxes();
taFilterXml = gd.getTextArea1();
Checkbox b = checkboxes.get(0);
b.addItemListener(this);
textFailLimit = numerics.get(9);
cbIncludeNeighbours = checkboxes.get(1);
textNeighbourHeight = numerics.get(10);
cbComputeDoublets = checkboxes.get(2);
if (useBenchmarkSettings) {
FitConfiguration tmpFitConfig = new FitConfiguration();
FitEngineConfiguration tmp = new FitEngineConfiguration(tmpFitConfig);
// Collect the residuals threshold
tmpFitConfig.setComputeResiduals(true);
if (BenchmarkFilterAnalysis.updateConfiguration(tmp, false)) {
textFailLimit.setText("" + tmp.getFailuresLimit());
cbIncludeNeighbours.setState(tmp.isIncludeNeighbours());
textNeighbourHeight.setText(Utils.rounded(tmp.getNeighbourHeightThreshold()));
cbComputeDoublets.setState(tmp.getResidualsThreshold() < 1);
final DirectFilter primaryFilter = tmpFitConfig.getSmartFilter();
final double residualsThreshold = tmp.getResidualsThreshold();
taFilterXml.setText(new MultiPathFilter(primaryFilter, minimalFilter, residualsThreshold).toXML());
}
}
}
gd.showDialog();
if (gd.wasCanceled())
return false;
fractionPositives = Math.abs(gd.getNextNumber());
fractionNegativesAfterAllPositives = Math.abs(gd.getNextNumber());
negativesAfterAllPositives = (int) Math.abs(gd.getNextNumber());
distance = Math.abs(gd.getNextNumber());
lowerDistance = Math.abs(gd.getNextNumber());
signalFactor = Math.abs(gd.getNextNumber());
lowerSignalFactor = Math.abs(gd.getNextNumber());
fitConfig.setInitialPeakStdDev(gd.getNextNumber());
config.setFitting(gd.getNextNumber());
fitConfig.setFitSolver(gd.getNextChoiceIndex());
fitConfig.setFitFunction(gd.getNextChoiceIndex());
boolean myUseBenchmarkSettings = false;
if (benchmarkSettingsCheckbox)
//useBenchmarkSettings =
myUseBenchmarkSettings = gd.getNextBoolean();
// Read dialog settings
String xml = gd.getNextText();
int failLimit = (int) gd.getNextNumber();
boolean includeNeighbours = gd.getNextBoolean();
double neighbourHeightThreshold = gd.getNextNumber();
boolean myComputeDoublets = gd.getNextBoolean();
double myDuplicateDistance = gd.getNextNumber();
MultiPathFilter myMultiFilter = null;
if (myUseBenchmarkSettings && !Utils.isShowGenericDialog()) {
// Only copy the benchmark settings if not interactive
FitConfiguration tmpFitConfig = new FitConfiguration();
FitEngineConfiguration tmp = new FitEngineConfiguration(tmpFitConfig);
// Collect the residuals threshold
tmpFitConfig.setComputeResiduals(true);
if (BenchmarkFilterAnalysis.updateConfiguration(tmp, false)) {
config.setFailuresLimit(tmp.getFailuresLimit());
config.setIncludeNeighbours(tmp.isIncludeNeighbours());
config.setNeighbourHeightThreshold(tmp.getNeighbourHeightThreshold());
computeDoublets = (tmp.getResidualsThreshold() < 1);
fitConfig.setDuplicateDistance(tmpFitConfig.getDuplicateDistance());
final DirectFilter primaryFilter = tmpFitConfig.getSmartFilter();
final double residualsThreshold = tmp.getResidualsThreshold();
myMultiFilter = new MultiPathFilter(primaryFilter, minimalFilter, residualsThreshold);
}
} else {
myMultiFilter = MultiPathFilter.fromXML(xml);
config.setFailuresLimit(failLimit);
config.setIncludeNeighbours(includeNeighbours);
config.setNeighbourHeightThreshold(neighbourHeightThreshold);
computeDoublets = myComputeDoublets;
fitConfig.setDuplicateDistance(myDuplicateDistance);
}
if (myMultiFilter == null) {
gd = new GenericDialog(TITLE);
gd.addMessage("The multi-path filter was invalid.\n \nContinue with a default filter?");
gd.enableYesNoCancel();
gd.hideCancelButton();
gd.showDialog();
if (!gd.wasOKed())
return false;
} else {
multiFilter = myMultiFilter;
}
if (computeDoublets) {
//config.setComputeResiduals(true);
config.setResidualsThreshold(0);
fitConfig.setComputeResiduals(true);
} else {
config.setResidualsThreshold(1);
fitConfig.setComputeResiduals(false);
}
showFilterScoreHistograms = gd.getNextBoolean();
showCorrelation = gd.getNextBoolean();
rankByIntensity = gd.getNextBoolean();
saveFilterRange = gd.getNextBoolean();
// Avoid stupidness, i.e. things that move outside the fit window and are bad widths
// TODO - Fix this for simple or smart filter...
fitConfig.setDisableSimpleFilter(false);
// Realistically we cannot fit lower than this
fitConfig.setMinPhotons(15);
// Disable shift as candidates may be re-mapped to alternative candidates so the initial position is wrong.
fitConfig.setCoordinateShiftFactor(0);
fitConfig.setMinWidthFactor(1.0 / 5);
fitConfig.setWidthFactor(5);
// Disable the direct filter
fitConfig.setDirectFilter(null);
if (extraOptions) {
}
if (gd.invalidNumber())
return false;
if (lowerDistance > distance)
lowerDistance = distance;
if (lowerSignalFactor > signalFactor)
lowerSignalFactor = signalFactor;
// Distances relative to sa (not s) as this is the same as the BenchmarkSpotFilter plugin
distanceInPixels = distance * sa / simulationParameters.a;
lowerDistanceInPixels = lowerDistance * sa / simulationParameters.a;
GlobalSettings settings = new GlobalSettings();
settings.setFitEngineConfiguration(config);
settings.setCalibration(cal);
// Copy simulation defaults if a new simulation
if (lastId != simulationParameters.id) {
cal.setNmPerPixel(simulationParameters.a);
cal.setGain(simulationParameters.gain);
cal.setAmplification(simulationParameters.amplification);
cal.setExposureTime(100);
cal.setReadNoise(simulationParameters.readNoise);
cal.setBias(simulationParameters.bias);
cal.setEmCCD(simulationParameters.emCCD);
// This is needed to configure the fit solver
fitConfig.setNmPerPixel(Maths.round(cal.getNmPerPixel()));
fitConfig.setGain(Maths.round(cal.getGain()));
fitConfig.setBias(Maths.round(cal.getBias()));
fitConfig.setReadNoise(Maths.round(cal.getReadNoise()));
fitConfig.setAmplification(Maths.round(cal.getAmplification()));
fitConfig.setEmCCD(cal.isEmCCD());
}
if (!PeakFit.configureFitSolver(settings, null, extraOptions))
return false;
return true;
}
use of gdsc.smlm.ij.settings.GlobalSettings in project GDSC-SMLM by aherbert.
the class BenchmarkSpotFilter method showDialog.
private boolean showDialog() {
GenericDialog gd = new GenericDialog(TITLE);
gd.addHelp(About.HELP_URL);
StringBuilder sb = new StringBuilder();
sb.append("Finds spots in the benchmark image created by CreateData plugin.\n");
final double sa = getSa() / simulationParameters.a;
sb.append("PSF width = ").append(Utils.rounded(simulationParameters.s / simulationParameters.a)).append(" px (sa = ").append(Utils.rounded(sa)).append(" px). HWHM = ").append(Utils.rounded(sa * Gaussian2DFunction.SD_TO_HWHM_FACTOR)).append(" px\n");
sb.append("Simulation depth = ").append(Utils.rounded(simulationParameters.depth)).append(" nm");
if (simulationParameters.fixedDepth)
sb.append(" (fixed)");
sb.append("\n \nConfigure the spot filter:");
gd.addMessage(sb.toString());
if (batchMode) {
// Support enumeration of single spot filters
gd.addCheckbox("Mean", batchMean);
gd.addCheckbox("Gaussian", batchGaussian);
gd.addCheckbox("Circular", batchCircular);
gd.addCheckbox("Median", batchMedian);
gd.addSlider("Min_search_width", 1, 4, minSearch);
gd.addSlider("Max_search_width", 1, 4, maxSearch);
gd.addCheckbox("Filter_relative_distances (to HWHM)", filterRelativeDistances);
} else {
String[] filterTypes = SettingsManager.getNames((Object[]) DataFilterType.values());
gd.addChoice("Spot_filter_type", filterTypes, filterTypes[config.getDataFilterType().ordinal()]);
String[] filterNames = SettingsManager.getNames((Object[]) DataFilter.values());
gd.addChoice("Spot_filter", filterNames, filterNames[config.getDataFilter(0).ordinal()]);
gd.addCheckbox("Filter_relative_distances (to HWHM)", filterRelativeDistances);
gd.addSlider("Smoothing", 0, 2.5, config.getSmooth(0));
gd.addSlider("Search_width", 1, 4, search);
}
gd.addSlider("Border", 0, 5, border);
gd.addCheckbox("Hard_border", hardBorder);
gd.addMessage("Scoring options:");
gd.addCheckbox("Score_relative_distances (to HWHM)", scoreRelativeDistances);
gd.addSlider("Analysis_border", 0, 5, sAnalysisBorder);
gd.addChoice("Matching_method", MATCHING_METHOD, MATCHING_METHOD[matchingMethod]);
gd.addSlider("Match_distance", 0.5, 3.5, upperDistance);
gd.addSlider("Lower_distance", 0, 3.5, lowerDistance);
gd.addSlider("Signal_factor", 0, 3.5, upperSignalFactor);
gd.addSlider("Lower_factor", 0, 3.5, lowerSignalFactor);
gd.addSlider("Recall_fraction", 50, 100, recallFraction);
if (!batchMode) {
gd.addCheckbox("Show_plots", showPlot);
gd.addCheckbox("Plot_rank_by_intensity", rankByIntensity);
gd.addCheckbox("Show_failures_plots", showFailuresPlot);
gd.addCheckbox("Show_TP", showTP);
gd.addCheckbox("Show_FP", showFP);
gd.addCheckbox("Show_FN", showFN);
}
if (extraOptions)
gd.addCheckbox("Debug", sDebug);
gd.showDialog();
if (gd.wasCanceled())
return false;
fitConfig.setInitialPeakStdDev(Maths.round(sa));
if (batchMode) {
batchMean = gd.getNextBoolean();
batchGaussian = gd.getNextBoolean();
batchCircular = gd.getNextBoolean();
batchMedian = gd.getNextBoolean();
if (!(batchMean || batchGaussian || batchCircular || batchMedian))
return false;
minSearch = gd.getNextNumber();
maxSearch = gd.getNextNumber();
filterRelativeDistances = gd.getNextBoolean();
} else {
config.setDataFilterType(gd.getNextChoiceIndex());
config.setDataFilter(gd.getNextChoiceIndex(), Maths.round(Math.abs(gd.getNextNumber()), 0.001), 0);
filterRelativeDistances = gd.getNextBoolean();
search = gd.getNextNumber();
}
border = gd.getNextNumber();
hardBorder = gd.getNextBoolean();
scoreRelativeDistances = gd.getNextBoolean();
sAnalysisBorder = Math.abs(gd.getNextNumber());
matchingMethod = gd.getNextChoiceIndex();
upperDistance = Math.abs(gd.getNextNumber());
lowerDistance = Math.abs(gd.getNextNumber());
upperSignalFactor = Math.abs(gd.getNextNumber());
lowerSignalFactor = Math.abs(gd.getNextNumber());
recallFraction = Math.abs(gd.getNextNumber());
if (!batchMode) {
showPlot = gd.getNextBoolean();
rankByIntensity = gd.getNextBoolean();
showFailuresPlot = gd.getNextBoolean();
showTP = gd.getNextBoolean();
showFP = gd.getNextBoolean();
showFN = gd.getNextBoolean();
}
if (extraOptions)
debug = sDebug = gd.getNextBoolean();
if (gd.invalidNumber())
return false;
if (lowerDistance > upperDistance)
lowerDistance = upperDistance;
if (lowerSignalFactor > upperSignalFactor)
lowerSignalFactor = upperSignalFactor;
if (batchMode) {
// Clear the cached results if the setting changed
Settings settings = new Settings(simulationParameters.id, filterRelativeDistances, //search, maxSearch, // Ignore search distance for smart caching
border, scoreRelativeDistances, sAnalysisBorder, hardBorder, matchingMethod, upperDistance, lowerDistance, upperSignalFactor, lowerSignalFactor, recallFraction);
if (!settings.equals(batchSettings)) {
cachedBatchResults.clear();
}
batchSettings = settings;
// relative (if requested) so that the results are consistent with single-filter mode.
if (filterRelativeDistances) {
final double hwhmMax = config.getHWHMMax();
config.setBorder(Maths.round(border * hwhmMax, 0.001));
} else {
config.setBorder(Maths.round(border, 0.001));
}
} else {
config.setSearch(Maths.round(search, 0.001));
config.setBorder(Maths.round(border, 0.001));
// Single filter ...
// Allow more complicated filters to be configured
GlobalSettings settings = new GlobalSettings();
settings.setFitEngineConfiguration(config);
if (!PeakFit.configureDataFilter(settings, null, false))
return false;
}
int analysisBorder;
if (scoreRelativeDistances) {
// Convert distance to PSF standard deviation units
final double hwhmMax = config.getHWHMMax();
matchDistance = upperDistance * hwhmMax;
lowerMatchDistance = lowerDistance * hwhmMax;
analysisBorder = (int) (sAnalysisBorder * hwhmMax);
} else {
matchDistance = upperDistance;
lowerMatchDistance = lowerDistance;
analysisBorder = (int) (sAnalysisBorder);
}
if (analysisBorder > 0) {
lastAnalysisBorder = new Rectangle(analysisBorder, analysisBorder, imp.getWidth() - 2 * analysisBorder, imp.getHeight() - 2 * analysisBorder);
} else {
lastAnalysisBorder = new Rectangle(imp.getWidth(), imp.getHeight());
}
return true;
}
Aggregations