use of gdsc.smlm.results.PeakResult in project GDSC-SMLM by aherbert.
the class DrawClusters method run.
/*
* (non-Javadoc)
*
* @see ij.plugin.PlugIn#run(java.lang.String)
*/
public void run(String arg) {
SMLMUsageTracker.recordPlugin(this.getClass(), arg);
if (MemoryPeakResults.isMemoryEmpty()) {
IJ.error(TITLE, "No localisations in memory");
return;
}
if (!showDialog())
return;
// Load the results
MemoryPeakResults results = ResultsManager.loadInputResults(inputOption, false);
if (results == null || results.size() == 0) {
IJ.error(TITLE, "No results could be loaded");
return;
}
// Get the traces
Trace[] traces = TraceManager.convert(results);
if (traces == null || traces.length == 0) {
IJ.error(TITLE, "No traces could be loaded");
return;
}
// Filter traces to a min size
int maxFrame = 0;
int count = 0;
final int myMaxSize = (maxSize < minSize) ? Integer.MAX_VALUE : maxSize;
final boolean myDrawLines = (myMaxSize < 2) ? false : drawLines;
for (int i = 0; i < traces.length; i++) {
if (expandToSingles)
traces[i].expandToSingles();
if (traces[i].size() >= minSize && traces[i].size() <= myMaxSize) {
traces[count++] = traces[i];
traces[i].sort();
if (maxFrame < traces[i].getTail().getFrame())
maxFrame = traces[i].getTail().getFrame();
}
}
if (count == 0) {
IJ.error(TITLE, "No traces achieved the size limits");
return;
}
String msg = String.format(TITLE + ": %d / %s (%s)", count, Utils.pleural(traces.length, "trace"), Utils.pleural(results.size(), "localisation"));
IJ.showStatus(msg);
//Utils.log(msg);
Rectangle bounds = results.getBounds(true);
ImagePlus imp = WindowManager.getImage(title);
boolean isUseStackPosition = useStackPosition;
if (imp == null) {
// Create a default image using 100 pixels as the longest edge
double maxD = (bounds.width > bounds.height) ? bounds.width : bounds.height;
int w, h;
if (maxD == 0) {
// Note that imageSize can be zero (for auto sizing)
w = h = (imageSize == 0) ? 20 : imageSize;
} else {
// Note that imageSize can be zero (for auto sizing)
if (imageSize == 0) {
w = bounds.width;
h = bounds.height;
} else {
w = (int) (imageSize * bounds.width / maxD);
h = (int) (imageSize * bounds.height / maxD);
}
}
ByteProcessor bp = new ByteProcessor(w, h);
if (isUseStackPosition) {
ImageStack stack = new ImageStack(w, h, maxFrame);
for (int i = 1; i <= maxFrame; i++) // Do not clone as the image is empty
stack.setPixels(bp.getPixels(), i);
imp = Utils.display(TITLE, stack);
} else
imp = Utils.display(TITLE, bp);
// Enlarge
ImageWindow iw = imp.getWindow();
for (int i = 9; i-- > 0 && iw.getWidth() < 500 && iw.getHeight() < 500; ) {
iw.getCanvas().zoomIn(imp.getWidth() / 2, imp.getHeight() / 2);
}
} else {
// Check if the image has enough frames for all the traces
if (maxFrame > imp.getNFrames())
isUseStackPosition = false;
}
final float xScale = (float) (imp.getWidth() / bounds.getWidth());
final float yScale = (float) (imp.getHeight() / bounds.getHeight());
// Create ROIs and store data to sort them
Roi[] rois = new Roi[count];
int[][] frames = (isUseStackPosition) ? new int[count][] : null;
int[] indices = Utils.newArray(count, 0, 1);
double[] values = new double[count];
for (int i = 0; i < count; i++) {
Trace trace = traces[i];
int nPoints = trace.size();
float[] xPoints = new float[nPoints];
float[] yPoints = new float[nPoints];
int j = 0;
if (isUseStackPosition)
frames[i] = new int[nPoints];
for (PeakResult result : trace.getPoints()) {
xPoints[j] = (result.getXPosition() - bounds.x) * xScale;
yPoints[j] = (result.getYPosition() - bounds.y) * yScale;
if (isUseStackPosition)
frames[i][j] = result.getFrame();
j++;
}
Roi roi;
if (myDrawLines) {
roi = new PolygonRoi(xPoints, yPoints, nPoints, Roi.POLYLINE);
if (splineFit)
((PolygonRoi) roi).fitSpline();
} else {
roi = new PointRoi(xPoints, yPoints, nPoints);
((PointRoi) roi).setShowLabels(false);
}
rois[i] = roi;
switch(sort) {
case 0:
default:
break;
case // Sort by ID
1:
values[i] = traces[i].getId();
break;
case // Sort by time
2:
values[i] = traces[i].getHead().getFrame();
break;
case // Sort by size descending
3:
values[i] = -traces[i].size();
break;
case // Sort by length descending
4:
values[i] = -roi.getLength();
break;
case // Mean Square Displacement
5:
values[i] = -traces[i].getMSD();
break;
case // Mean / Frame
6:
values[i] = -traces[i].getMeanPerFrame();
break;
}
}
if (sort > 0)
Sort.sort(indices, values);
// Draw the traces as ROIs on an overlay
Overlay o = new Overlay();
LUT lut = LUTHelper.createLUT(DrawClusters.lut);
final double scale = 256.0 / count;
if (isUseStackPosition) {
// Add the tracks on the frames containing the results
final boolean isHyperStack = imp.isDisplayedHyperStack();
for (int i = 0; i < count; i++) {
final int index = indices[i];
final Color c = LUTHelper.getColour(lut, (int) (i * scale));
final PolygonRoi roi = (PolygonRoi) rois[index];
roi.setFillColor(c);
roi.setStrokeColor(c);
final FloatPolygon fp = roi.getNonSplineFloatPolygon();
// For each frame in the track, add the ROI track and a point ROI for the current position
for (int j = 0; j < frames[index].length; j++) {
addToOverlay(o, (Roi) roi.clone(), isHyperStack, frames[index][j]);
//PointRoi pointRoi = new PointRoi(pos.x + fp.xpoints[j], pos.y + fp.ypoints[j]);
PointRoi pointRoi = new PointRoi(fp.xpoints[j], fp.ypoints[j]);
pointRoi.setPointType(3);
pointRoi.setFillColor(c);
pointRoi.setStrokeColor(Color.black);
addToOverlay(o, pointRoi, isHyperStack, frames[index][j]);
}
}
} else {
// Add the tracks as a single overlay
for (int i = 0; i < count; i++) {
final Roi roi = rois[indices[i]];
roi.setStrokeColor(new Color(lut.getRGB((int) (i * scale))));
o.add(roi);
}
}
imp.setOverlay(o);
IJ.showStatus(msg);
}
use of gdsc.smlm.results.PeakResult in project GDSC-SMLM by aherbert.
the class DriftCalculator method findTimeLimits.
private int[] findTimeLimits(MemoryPeakResults results) {
int min = Integer.MAX_VALUE;
int max = 0;
for (PeakResult r : results) {
if (min > r.getFrame())
min = r.getFrame();
if (max < r.getFrame())
max = r.getFrame();
}
return new int[] { min, max };
}
use of gdsc.smlm.results.PeakResult in project GDSC-SMLM by aherbert.
the class DriftCalculator method applyDriftCorrection.
private void applyDriftCorrection(MemoryPeakResults results, double[][] drift) {
ExtendedGenericDialog gd = new ExtendedGenericDialog(TITLE);
gd.addMessage("Apply drift correction to in-memory results?");
gd.addChoice("Update_method", UPDATE_METHODS, UPDATE_METHODS[updateMethod]);
// Option to save the drift unless it was loaded from file
if (method != DRIFT_FILE)
gd.addCheckbox("Save_drift", saveDrift);
gd.showDialog();
if (gd.wasCanceled())
return;
updateMethod = gd.getNextChoiceIndex();
if (method != DRIFT_FILE) {
saveDrift = gd.getNextBoolean();
saveDrift(calculatedTimepoints, lastdx, lastdy);
}
if (updateMethod == 0)
return;
final double[] dx = drift[0];
final double[] dy = drift[1];
if (updateMethod == 1) {
// Update the results in memory
Utils.log("Applying drift correction to the results set: " + results.getName());
for (PeakResult r : results) {
r.params[Gaussian2DFunction.X_POSITION] += dx[r.getFrame()];
r.params[Gaussian2DFunction.Y_POSITION] += dy[r.getFrame()];
}
} else {
// Create a new set of results
MemoryPeakResults newResults = new MemoryPeakResults(results.size());
newResults.copySettings(results);
newResults.setName(results.getName() + " (Corrected)");
MemoryPeakResults.addResults(newResults);
final boolean truncate = updateMethod == 3;
Utils.log("Creating %sdrift corrected results set: " + newResults.getName(), (truncate) ? "truncated " : "");
for (PeakResult r : results) {
if (truncate) {
if (r.getFrame() < interpolationStart || r.getFrame() > interpolationEnd)
continue;
}
float[] params = Arrays.copyOf(r.params, r.params.length);
params[Gaussian2DFunction.X_POSITION] += dx[r.getFrame()];
params[Gaussian2DFunction.Y_POSITION] += dy[r.getFrame()];
newResults.addf(r.getFrame(), r.origX, r.origY, r.origValue, r.error, r.noise, params, r.paramsStdDev);
}
}
}
use of gdsc.smlm.results.PeakResult in project GDSC-SMLM by aherbert.
the class FitWorker method estimateBackground.
/**
* Get an estimate of the background level using the fitted peaks. If no fits available then estimate background
* using mean of image.
*
* @param peakResults
* @param width
* @param height
* @return
*/
@SuppressWarnings("unused")
private float estimateBackground(LinkedList<PeakResult> peakResults, int width, int height) {
if (peakResults.size() > 0) {
// Compute average background of the fitted peaks
double sum = 0;
for (PeakResult result : peakResults) sum += result.params[Gaussian2DFunction.BACKGROUND];
float av = (float) sum / peakResults.size();
if (logger != null)
logger.info("Average background %f", av);
return av;
} else {
// Compute average of the entire image
double sum = 0;
for (int i = width * height; i-- > 0; ) sum += data[i];
float av = (float) sum / (width * height);
if (logger != null)
logger.info("Image background %f", av);
return av;
}
}
use of gdsc.smlm.results.PeakResult in project GDSC-SMLM by aherbert.
the class DistanceResultFilter method filter.
/* (non-Javadoc)
* @see gdsc.smlm.engine.filter.ResultFilter#filter(gdsc.smlm.fitting.FitResult, int, gdsc.smlm.results.PeakResult[])
*/
@Override
public void filter(FitResult fitResult, int maxIndex, PeakResult... results) {
boolean found = false;
for (PeakResult r : results) {
if (r == null)
continue;
for (float[] coord : filter) {
final float dx = r.getXPosition() - coord[0];
final float dy = r.getYPosition() - coord[1];
if (dx * dx + dy * dy < d2) {
found = true;
peakResults.add(r);
break;
}
}
}
if (found) {
// Add the result and the fitted index to the filtered results
filteredFitResults[filteredCount] = fitResult;
filteredIndices[filteredCount] = maxIndex;
filteredCount++;
}
}
Aggregations