use of gdsc.smlm.filters.MaximaSpotFilter in project GDSC-SMLM by aherbert.
the class FitEngineConfiguration method createSpotFilter.
/**
* Create the spot filter for identifying candidate maxima. The actual border, search width and smoothing parameters
* can be configured relative to the configured standard deviations or left absolute. The standard deviation is used
* to determine the Half-Width at Half-Maximum (HWHM) for each dimension and the parameters set as follows.
*
* <pre>
*
* int search = (int) Math.ceil(getSearch() * hwhmMax);
* int border = (int) Math.floor(getBorder() * hwhmMax);
* // For each filter
* double smooth = getSmooth(i) * hwhmMin;
*
* </pre>
*
* @param relative
* True if the parameters should be made relative to the configured standard deviations
* @return
*/
public MaximaSpotFilter createSpotFilter(boolean relative) {
final double hwhmMin, hwhmMax;
if (relative) {
// Get the half-width at half maximim
hwhmMin = getHWHMMin();
hwhmMax = getHWHMMax();
} else {
hwhmMin = hwhmMax = 1;
}
// Region for maxima finding
int search = (int) Math.ceil(Maths.round(getSearch() * hwhmMax, 0.01));
if (search < 1)
search = 1;
// Border where peaks are ignored
int border = (int) Math.floor(Maths.round(getBorder() * hwhmMax, 0.01));
if (border < 0)
border = 0;
DataProcessor processor0 = createDataProcessor(border, 0, hwhmMin);
final int nFilters = Math.min(dataFilter.length, smooth.length);
final MaximaSpotFilter spotFilter;
switch(dataFilterType) {
case JURY:
if (nFilters > 1) {
DataProcessor[] processors = new DataProcessor[nFilters];
processors[0] = processor0;
for (int i = 1; i < nFilters; i++) processors[i] = createDataProcessor(border, i, hwhmMin);
spotFilter = new JurySpotFilter(search, border, processors);
break;
}
case DIFFERENCE:
if (nFilters > 1) {
DataProcessor processor1 = createDataProcessor(border, 1, hwhmMin);
spotFilter = new DifferenceSpotFilter(search, border, processor0, processor1);
break;
}
case SINGLE:
default:
spotFilter = new SingleSpotFilter(search, border, processor0);
}
return spotFilter;
}
use of gdsc.smlm.filters.MaximaSpotFilter in project GDSC-SMLM by aherbert.
the class SpotFinderPreview method run.
/*
* (non-Javadoc)
*
* @see ij.plugin.filter.PlugInFilter#run(ij.process.ImageProcessor)
*/
public void run(ImageProcessor ip) {
Rectangle bounds = ip.getRoi();
MaximaSpotFilter filter = config.createSpotFilter(true);
// Crop to the ROI
FloatProcessor fp = ip.crop().toFloat(0, null);
float[] data = (float[]) fp.getPixels();
int width = fp.getWidth();
int height = fp.getHeight();
Spot[] spots = filter.rank(data, width, height);
data = filter.getPreprocessedData();
fp = new FloatProcessor(width, height, data);
ip = ip.duplicate();
ip.insert(fp, bounds.x, bounds.y);
//ip.resetMinAndMax();
ip.setMinAndMax(fp.getMin(), fp.getMax());
Overlay o = new Overlay();
o.add(new ImageRoi(0, 0, ip));
if (label != null) {
// Get results for frame
Coordinate[] actual = ResultsMatchCalculator.getCoordinates(actualCoordinates, imp.getCurrentSlice());
Coordinate[] predicted = new Coordinate[spots.length];
for (int i = 0; i < spots.length; i++) {
predicted[i] = new BasePoint(spots[i].x + bounds.x, spots[i].y + bounds.y);
}
// Q. Should this use partial scoring with multi-matches allowed.
// If so then this needs to be refactored out of the BenchmarkSpotFilter class.
// TODO - compute AUC and max jaccard and plot
// Compute matches
List<PointPair> matches = new ArrayList<PointPair>(Math.min(actual.length, predicted.length));
List<Coordinate> FP = new ArrayList<Coordinate>(predicted.length);
MatchResult result = MatchCalculator.analyseResults2D(actual, predicted, distance * fitConfig.getInitialPeakStdDev0(), null, FP, null, matches);
// Show scores
setLabel(String.format("P=%s, R=%s, J=%s", Utils.rounded(result.getPrecision()), Utils.rounded(result.getRecall()), Utils.rounded(result.getJaccard())));
// Create Rois for TP and FP
if (showTP) {
float[] x = new float[matches.size()];
float[] y = new float[x.length];
int n = 0;
for (PointPair pair : matches) {
BasePoint p = (BasePoint) pair.getPoint2();
x[n] = p.getX() + 0.5f;
y[n] = p.getY() + 0.5f;
n++;
}
addRoi(0, o, x, y, n, Color.green);
}
if (showFP) {
float[] x = new float[predicted.length - matches.size()];
float[] y = new float[x.length];
int n = 0;
for (Coordinate c : FP) {
BasePoint p = (BasePoint) c;
x[n] = p.getX() + 0.5f;
y[n] = p.getY() + 0.5f;
n++;
}
addRoi(0, o, x, y, n, Color.red);
}
} else {
float[] x = new float[spots.length];
float[] y = new float[x.length];
for (int i = 0; i < spots.length; i++) {
x[i] = spots[i].x + bounds.x + 0.5f;
y[i] = spots[i].y + bounds.y + 0.5f;
}
PointRoi roi = new PointRoi(x, y);
// Add options to configure colour and labels
o.add(roi);
}
imp.setOverlay(o);
}
use of gdsc.smlm.filters.MaximaSpotFilter in project GDSC-SMLM by aherbert.
the class BenchmarkFilterAnalysis method createResults.
/**
* Create peak results.
*
* @param filterResults
* The results from running the filter (or null)
* @param filter
* the filter
*/
private MemoryPeakResults createResults(PreprocessedPeakResult[] filterResults, DirectFilter filter, boolean withBorder) {
if (filterResults == null) {
final MultiPathFilter multiPathFilter = createMPF(filter, minimalFilter);
//multiPathFilter.setDebugFile("/tmp/filter.txt");
filterResults = filterResults(multiPathFilter);
}
MemoryPeakResults results = new MemoryPeakResults();
results.copySettings(this.results);
results.setName(TITLE);
if (withBorder) {
// To produce the same results as the PeakFit plugin we must implement the border
// functionality used in the FitWorker. This respects the border of the spot filter.
FitEngineConfiguration config = new FitEngineConfiguration(new FitConfiguration());
updateAllConfiguration(config);
MaximaSpotFilter spotFilter = config.createSpotFilter(true);
final int border = spotFilter.getBorder();
int[] bounds = getBounds();
final int borderLimitX = bounds[0] - border;
final int borderLimitY = bounds[1] - border;
for (PreprocessedPeakResult spot : filterResults) {
if (spot.getX() > border && spot.getX() < borderLimitX && spot.getY() > border && spot.getY() < borderLimitY) {
double[] p = spot.toGaussian2DParameters();
float[] params = new float[p.length];
for (int j = 0; j < p.length; j++) params[j] = (float) p[j];
int frame = spot.getFrame();
int origX = (int) p[Gaussian2DFunction.X_POSITION];
int origY = (int) p[Gaussian2DFunction.Y_POSITION];
results.addf(frame, origX, origY, 0, 0, spot.getNoise(), params, null);
}
}
} else {
for (PreprocessedPeakResult spot : filterResults) {
double[] p = spot.toGaussian2DParameters();
float[] params = new float[p.length];
for (int j = 0; j < p.length; j++) params[j] = (float) p[j];
int frame = spot.getFrame();
int origX = (int) p[Gaussian2DFunction.X_POSITION];
int origY = (int) p[Gaussian2DFunction.Y_POSITION];
results.addf(frame, origX, origY, 0, 0, spot.getNoise(), params, null);
}
}
return results;
}
use of gdsc.smlm.filters.MaximaSpotFilter in project GDSC-SMLM by aherbert.
the class BenchmarkSpotFilter method run.
private BenchmarkFilterResult run(FitEngineConfiguration config, boolean relativeDistances, boolean batchSummary) {
if (Utils.isInterrupted())
return null;
MaximaSpotFilter spotFilter = config.createSpotFilter(relativeDistances);
// Extract all the results in memory into a list per frame. This can be cached
if (// || lastRelativeDistances != relativeDistances)
lastId != simulationParameters.id) {
// Always use float coordinates.
// The Worker adds a pixel offset for the spot coordinates.
TIntObjectHashMap<ArrayList<Coordinate>> coordinates = ResultsMatchCalculator.getCoordinates(results.getResults(), false);
actualCoordinates = new TIntObjectHashMap<PSFSpot[]>();
lastId = simulationParameters.id;
//lastRelativeDistances = relativeDistances;
// Store these so we can reset them
final int total = totalProgress;
final String prefix = progressPrefix;
// Spot PSFs may overlap so we must determine the amount of signal overlap and amplitude effect
// for each spot...
IJ.showStatus("Computing PSF overlap ...");
final int nThreads = Prefs.getThreads();
final BlockingQueue<Integer> jobs = new ArrayBlockingQueue<Integer>(nThreads * 2);
List<OverlapWorker> workers = new LinkedList<OverlapWorker>();
List<Thread> threads = new LinkedList<Thread>();
for (int i = 0; i < nThreads; i++) {
OverlapWorker worker = new OverlapWorker(jobs, coordinates);
Thread t = new Thread(worker);
workers.add(worker);
threads.add(t);
t.start();
}
// Process the frames
totalProgress = coordinates.size();
stepProgress = Utils.getProgressInterval(totalProgress);
progress = 0;
coordinates.forEachKey(new TIntProcedure() {
public boolean execute(int value) {
put(jobs, value);
return true;
}
});
// Finish all the worker threads by passing in a null job
for (int i = 0; i < threads.size(); i++) {
put(jobs, -1);
}
// Wait for all to finish
for (int i = 0; i < threads.size(); i++) {
try {
threads.get(i).join();
} catch (InterruptedException e) {
e.printStackTrace();
}
actualCoordinates.putAll(workers.get(i).coordinates);
}
threads.clear();
IJ.showProgress(-1);
IJ.showStatus("");
setupProgress(total, prefix);
}
if (!batchMode)
IJ.showStatus("Computing results ...");
final ImageStack stack = imp.getImageStack();
float background = 0;
if (spotFilter.isAbsoluteIntensity()) {
// To allow the signal factor to be computed we need to lower the image by the background so
// that the intensities correspond to the results amplitude.
// Just assume the background is uniform.
double sum = 0;
for (PeakResult r : results) sum += r.getBackground();
background = (float) (sum / results.size());
}
// Create a pool of workers
final int nThreads = Prefs.getThreads();
BlockingQueue<Integer> jobs = new ArrayBlockingQueue<Integer>(nThreads * 2);
List<Worker> workers = new LinkedList<Worker>();
List<Thread> threads = new LinkedList<Thread>();
for (int i = 0; i < nThreads; i++) {
Worker worker = new Worker(jobs, stack, spotFilter, background);
Thread t = new Thread(worker);
workers.add(worker);
threads.add(t);
t.start();
}
// Fit the frames
for (int i = 1; i <= stack.getSize(); i++) {
put(jobs, i);
}
// Finish all the worker threads by passing in a null job
for (int i = 0; i < threads.size(); i++) {
put(jobs, -1);
}
// Wait for all to finish
for (int i = 0; i < threads.size(); i++) {
try {
threads.get(i).join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
threads.clear();
if (Utils.isInterrupted())
return null;
if (!batchMode) {
IJ.showProgress(-1);
IJ.showStatus("Collecting results ...");
}
TIntObjectHashMap<FilterResult> filterResults = new TIntObjectHashMap<FilterResult>();
time = 0;
for (Worker w : workers) {
time += w.time;
filterResults.putAll(w.results);
}
// Show a table of the results
BenchmarkFilterResult filterResult = summariseResults(filterResults, config, spotFilter, relativeDistances, batchSummary);
if (!batchMode)
IJ.showStatus("");
return filterResult;
}
use of gdsc.smlm.filters.MaximaSpotFilter in project GDSC-SMLM by aherbert.
the class SmoothImage method run.
/*
* (non-Javadoc)
*
* @see ij.plugin.filter.PlugInFilter#run(ij.process.ImageProcessor)
*/
public void run(ImageProcessor ip) {
Rectangle bounds = ip.getRoi();
// Crop to the ROI
FloatProcessor fp = ip.crop().toFloat(0, null);
float[] data = (float[]) fp.getPixels();
MaximaSpotFilter filter = createSpotFilter();
int width = fp.getWidth();
int height = fp.getHeight();
data = filter.preprocessData(data, width, height);
//System.out.println(filter.getDescription());
fp = new FloatProcessor(width, height, data);
ip.insert(fp, bounds.x, bounds.y);
//ip.resetMinAndMax();
ip.setMinAndMax(fp.getMin(), fp.getMax());
}
Aggregations