use of ij.IJ in project GDSC-SMLM by aherbert.
the class TraceMatchCalculator method compareCoordinates.
@SuppressWarnings("null")
private void compareCoordinates(MemoryPeakResults results1, MemoryPeakResults results2, MemoryPeakResults results3, double distanceThreshold) {
final Pulse[] p1 = extractPulses(results1);
final Pulse[] p2 = extractPulses(results2);
final Pulse[] p3 = extractPulses(results3);
final List<Pulse> tp = null;
List<Pulse> fp = null;
List<Pulse> fn = null;
List<PointPair> pairs = null;
final List<Pulse> tp2 = null;
List<Pulse> fp2 = null;
List<Pulse> fn2 = null;
List<PointPair> pairs2 = null;
if (settings.showPairs) {
pairs = new LinkedList<>();
fp = new LinkedList<>();
fn = new LinkedList<>();
pairs2 = new LinkedList<>();
fp2 = new LinkedList<>();
fn2 = new LinkedList<>();
}
final MatchResult result = MatchCalculator.analyseResults2D(p1, p2, distanceThreshold, tp, fp, fn, pairs);
final MatchResult result2 = MatchCalculator.analyseResults2D(p1, p3, distanceThreshold, tp2, fp2, fn2, pairs2);
// Create output
Consumer<String> resultsOutput;
if (!java.awt.GraphicsEnvironment.isHeadless()) {
final TextWindow resultsWindow = ImageJUtils.refresh(resultsWindowRef, () -> new TextWindow(TITLE + " Results", createResultsHeader(), "", 900, 300));
resultsOutput = resultsWindow::append;
if (settings.showPairs) {
if (p3 == null) {
// Produce a pairs output
final WindowAndPainter wap = refresh(pairsWindowRef, true, resultsWindow, results1);
// Add the unmatched points
WindowManager.getIDList();
for (final Coordinate c : fn) {
pairs.add(new PointPair(c, null));
}
for (final Coordinate c : fp) {
pairs.add(new PointPair(null, c));
}
final List<? extends PointPair> sortedPairs = sort(pairs);
for (final PointPair pair : sortedPairs) {
addPairResult(wap.textWindow, pair);
}
} else {
// Produce a triple output
final WindowAndPainter wap = refresh(triplesWindowRef, false, resultsWindow, results1);
final HashMap<Pulse, Triple> map = new HashMap<>();
final ArrayList<Triple> triples = new ArrayList<>(pairs.size());
for (final PointPair pair : pairs) {
final Pulse p = (Pulse) pair.getPoint1();
final Triple t = new Triple(p, (Pulse) pair.getPoint2(), null);
triples.add(t);
map.put(p, t);
}
// Complete the reference set of points
for (final Coordinate c : fn) {
final Pulse p = (Pulse) c;
final Triple t = new Triple(p, null, null);
triples.add(t);
map.put(p, t);
}
// Add the unmatched points
for (final Coordinate c : fp) {
triples.add(new Triple(null, (Pulse) c, null));
}
for (final Coordinate c : fp2) {
triples.add(new Triple(null, null, (Pulse) c));
}
// Add the results from the second match
for (final PointPair pair : pairs2) {
final Pulse p = (Pulse) pair.getPoint1();
final Pulse pp = (Pulse) pair.getPoint2();
final Triple triple = map.get(p);
if (triple != null) {
triple.p3 = pp;
} else {
triples.add(new Triple(null, null, pp));
}
}
final List<? extends Triple> sortedTriples = sort(triples);
for (final Triple t : sortedTriples) {
addTripleResult(wap.textWindow, t);
}
}
}
} else {
if (writeHeader.compareAndSet(true, false)) {
IJ.log(createResultsHeader());
}
resultsOutput = IJ::log;
}
final StringBuilder sb = new StringBuilder();
addResult(resultsOutput, sb, settings.inputOption1, settings.inputOption2, distanceThreshold, result);
if (p3 != null) {
addResult(resultsOutput, sb, settings.inputOption1, settings.inputOption3, distanceThreshold, result2);
}
}
use of ij.IJ in project GDSC-SMLM by aherbert.
the class Fire method createImages.
/**
* Creates the images to use for the FIRE calculation. This must be called after
* {@link #initialise(MemoryPeakResults, MemoryPeakResults)}.
*
* @param fourierImageScale the fourier image scale (set to zero to auto compute)
* @param imageSize the image size
* @param useSignal Use the localisation signal to weight the intensity. The default uses a value
* of 1 per localisation.
* @return the fire images
*/
public FireImages createImages(double fourierImageScale, int imageSize, boolean useSignal) {
if (results == null) {
return null;
}
final SignalProvider signalProvider = (useSignal && (results.hasIntensity())) ? new PeakSignalProvider() : new FixedSignalProvider();
// Draw images using the existing IJ routines.
final Rectangle bounds = new Rectangle((int) Math.ceil(dataBounds.getWidth()), (int) Math.ceil(dataBounds.getHeight()));
final ResultsImageSettings.Builder builder = ResultsImageSettings.newBuilder().setImageType(ResultsImageType.DRAW_NONE).setWeighted(true).setEqualised(false).setImageMode(ResultsImageMode.IMAGE_ADD);
if (fourierImageScale > 0) {
builder.setImageSizeMode(ResultsImageSizeMode.SCALED);
builder.setScale(fourierImageScale);
} else {
builder.setImageSizeMode(ResultsImageSizeMode.IMAGE_SIZE);
builder.setImageSize(imageSize);
}
ImageJImagePeakResults image1 = createPeakResultsImage(bounds, builder, "IP1");
ImageJImagePeakResults image2 = createPeakResultsImage(bounds, builder, "IP2");
final float minx = (float) dataBounds.getX();
final float miny = (float) dataBounds.getY();
if (this.results2 != null) {
// Two image comparison
final ImageJImagePeakResults i1 = image1;
results.forEach((PeakResultProcedure) result -> {
final float x = result.getXPosition() - minx;
final float y = result.getYPosition() - miny;
i1.add(x, y, signalProvider.getSignal(result));
});
final ImageJImagePeakResults i2 = image2;
results2.forEach((PeakResultProcedure) result -> {
final float x = result.getXPosition() - minx;
final float y = result.getYPosition() - miny;
i2.add(x, y, signalProvider.getSignal(result));
});
} else {
// Block sampling.
// Ensure we have at least 2 even sized blocks.
int blockSize = Math.min(results.size() / 2, Math.max(1, settings.blockSize));
int nblocks = (int) Math.ceil((double) results.size() / blockSize);
while (nblocks <= 1 && blockSize > 1) {
blockSize /= 2;
nblocks = (int) Math.ceil((double) results.size() / blockSize);
}
if (nblocks <= 1) {
// This should not happen since the results should contain at least 2 localisations
return null;
}
if (blockSize != settings.blockSize) {
IJ.log(pluginTitle + " Warning: Changed block size to " + blockSize);
}
final Counter i = new Counter();
final Counter block = new Counter();
final int finalBlockSize = blockSize;
final PeakResult[][] blocks = new PeakResult[nblocks][blockSize];
results.forEach((PeakResultProcedure) result -> {
if (i.getCount() == finalBlockSize) {
block.increment();
i.reset();
}
blocks[block.getCount()][i.getAndIncrement()] = result;
});
// Truncate last block
blocks[block.getCount()] = Arrays.copyOf(blocks[block.getCount()], i.getCount());
final int[] indices = SimpleArrayUtils.natural(block.getCount() + 1);
if (settings.randomSplit) {
MathArrays.shuffle(indices);
}
for (final int index : indices) {
// Split alternating so just rotate
final ImageJImagePeakResults image = image1;
image1 = image2;
image2 = image;
for (final PeakResult p : blocks[index]) {
final float x = p.getXPosition() - minx;
final float y = p.getYPosition() - miny;
image.add(x, y, signalProvider.getSignal(p));
}
}
}
image1.end();
final ImageProcessor ip1 = image1.getImagePlus().getProcessor();
image2.end();
final ImageProcessor ip2 = image2.getImagePlus().getProcessor();
if (settings.maxPerBin > 0 && signalProvider instanceof FixedSignalProvider) {
// We can eliminate over-sampled pixels
for (int i = ip1.getPixelCount(); i-- > 0; ) {
if (ip1.getf(i) > settings.maxPerBin) {
ip1.setf(i, settings.maxPerBin);
}
if (ip2.getf(i) > settings.maxPerBin) {
ip2.setf(i, settings.maxPerBin);
}
}
}
return new FireImages(ip1, ip2, nmPerUnit / image1.getScale());
}
use of ij.IJ in project GDSC-SMLM by aherbert.
the class TraceMolecules method runTracing.
/**
* Runs the tracing algorithm using distances and time thresholds between min and max with the
* configured number of steps. Steps are spaced using a logarithmic scale.
*
* <p>Returns a list of [distance,time,N traces]
*
* @param manager the manager
* @param minDistanceThreshold the min distance threshold
* @param maxDistanceThreshold the max distance threshold
* @param minTimeThreshold the min time threshold
* @param maxTimeThreshold the max time threshold
* @param optimiserSteps the optimiser steps
* @return a list of [distance,time,N traces,blinking rate]
*/
public List<double[]> runTracing(TraceManager manager, double minDistanceThreshold, double maxDistanceThreshold, int minTimeThreshold, int maxTimeThreshold, int optimiserSteps) {
ddistanceThresholds = getIntervals(minDistanceThreshold, maxDistanceThreshold, optimiserSteps);
timeThresholds = convert(getIntervals(minTimeThreshold, maxTimeThreshold, optimiserSteps));
final int total = ddistanceThresholds.length * timeThresholds.length;
final ArrayList<double[]> resultsList = new ArrayList<>(total);
IJ.showStatus("Optimising tracing (" + total + " steps) ...");
if (debugMode) {
IJ.log("Optimising tracing ...");
}
int step = 0;
for (final double d : ddistanceThresholds) {
for (final int t : timeThresholds) {
IJ.showProgress(step++, total);
final int n = manager.traceMolecules(d, t);
resultsList.add(new double[] { d, t, n, getBlinkingRate(manager.getTraces()) });
if (debugMode) {
summarise(IJ::log, manager.getTraces(), manager.getTotalFiltered(), d, t);
}
}
}
if (debugMode) {
IJ.log("-=-=-=-");
}
IJ.showStatus("");
IJ.showProgress(1.0);
return resultsList;
}
use of ij.IJ in project GDSC-SMLM by aherbert.
the class ResultsMatchCalculator method showResults.
@SuppressWarnings("null")
private void showResults(MemoryPeakResults results1, MemoryPeakResults results2, final List<PointPair> allMatches, int n1, int n2, final boolean doIdAnalysis1, final boolean doIdAnalysis2, TextWindow resultsWindow) {
if (!settings.showTable) {
return;
}
// Output the results
Consumer<String> output;
if (resultsWindow != null) {
output = resultsWindow::append;
} else {
// Headless mode
output = IJ::log;
if (writeHeader.get()) {
writeHeader.set(false);
IJ.log(createResultsHeader(settings.idAnalysis));
}
}
// We have the results for the largest distance.
// Now reduce the distance threshold and recalculate the results
final double[] distanceThresholds = getDistances(settings.distanceThreshold, settings.increments, settings.delta);
final double[] pairDistances = getPairDistances(allMatches);
// Re-use storage for the ID analysis
TIntHashSet id1 = null;
TIntHashSet id2 = null;
TIntHashSet matchId1 = null;
TIntHashSet matchId2 = null;
final boolean doIdAnalysis = doIdAnalysis1 || doIdAnalysis2;
if (doIdAnalysis) {
if (doIdAnalysis1) {
id1 = getIds(results1);
matchId1 = new TIntHashSet(id1.size());
}
if (doIdAnalysis2) {
id2 = getIds(results2);
matchId2 = new TIntHashSet(id2.size());
}
}
final StringBuilder sb = new StringBuilder();
for (final double distanceThreshold : distanceThresholds) {
double rms = 0;
int tp2 = 0;
final double d2 = distanceThreshold * distanceThreshold;
for (final double d : pairDistances) {
if (d <= d2) {
rms += d;
tp2++;
}
}
// All non-true positives must be added to the false totals.
final int fp2 = n2 - tp2;
final int fn2 = n1 - tp2;
// RMSD to be the root mean square deviation in a single dimension so divide by 2.
// (This assumes 2D Euclidean distances.)
final MatchResult result = new MatchResult(tp2, fp2, fn2, Math.sqrt(MathUtils.div0(rms / 2, tp2)));
MatchResult idResult1 = null;
MatchResult idResult2 = null;
if (doIdAnalysis) {
if (doIdAnalysis1) {
matchId1.clear();
}
if (doIdAnalysis2) {
matchId2.clear();
}
int index = 0;
for (final PointPair pair : allMatches) {
if (pairDistances[index++] <= d2) {
if (doIdAnalysis1) {
matchId1.add(((PeakResultPoint) pair.getPoint1()).getPeakResult().getId());
}
if (doIdAnalysis2) {
matchId2.add(((PeakResultPoint) pair.getPoint2()).getPeakResult().getId());
}
}
}
// => Only the recall will be valid: tp / (tp + fn)
if (doIdAnalysis1) {
idResult1 = new MatchResult(matchId1.size(), 0, id1.size() - matchId1.size(), 0);
}
if (doIdAnalysis2) {
idResult2 = new MatchResult(matchId2.size(), 0, id2.size() - matchId2.size(), 0);
}
}
addResult(sb, settings.inputOption1, settings.inputOption2, distanceThreshold, result, idResult1, idResult2);
output.accept(sb.toString());
}
}
use of ij.IJ in project GDSC-SMLM by aherbert.
the class BenchmarkFilterAnalysis method createGaWindow.
private void createGaWindow() {
if (isHeadless) {
String header = createResultsHeader(false);
header += "\tIteration";
IJ.log(header);
gaWindow = IJ::log;
} else {
final TextWindow window = ImageJUtils.refresh(gaWindowRef, () -> {
String header = createResultsHeader(false);
header += "\tIteration";
return new TextWindow(TITLE + " Evolution", header, "", 900, 300);
});
if (settings.clearTables) {
window.getTextPanel().clear();
}
gaWindow = window::append;
}
}
Aggregations