use of uk.ac.sussex.gdsc.smlm.results.PeakResult in project GDSC-SMLM by aherbert.
the class ResultsMatchCalculator method runCompareCoordinates.
@SuppressWarnings("null")
private void runCompareCoordinates(MemoryPeakResults results1, MemoryPeakResults results2) {
final boolean requirePairs = settings.showPairs || settings.isSaveClassifications();
final boolean saveMatched = settings.isSaveMatched();
final boolean saveUnmatched = settings.isSaveUnmatched();
final TextFilePeakResults fileResults = createFilePeakResults(results2);
final List<PointPair> allMatches = new LinkedList<>();
final List<PointPair> pairs = (requirePairs) ? new LinkedList<>() : null;
final double maxDistance = settings.distanceThreshold + settings.increments * settings.delta;
// Divide the results into time points
final TIntObjectHashMap<List<Coordinate>> actualCoordinates = getCoordinates(results1, settings.coordinateMethod1);
final TIntObjectHashMap<List<Coordinate>> predictedCoordinates = getCoordinates(results2, settings.coordinateMethod2);
int n1 = 0;
int n2 = 0;
// Process each time point
for (final int t : getTimepoints(actualCoordinates, predictedCoordinates)) {
final Coordinate[] actual = getCoordinates(actualCoordinates, t);
final Coordinate[] predicted = getCoordinates(predictedCoordinates, t);
final List<Coordinate> tp = null;
List<Coordinate> fp = null;
List<Coordinate> fn = null;
final List<PointPair> matches = new LinkedList<>();
if (requirePairs) {
fp = new LinkedList<>();
fn = new LinkedList<>();
}
MatchCalculator.analyseResults2D(actual, predicted, maxDistance, tp, fp, fn, matches);
// Aggregate
n1 += actual.length;
n2 += predicted.length;
allMatches.addAll(matches);
if (settings.showPairs) {
pairs.addAll(matches);
for (final Coordinate c : fn) {
pairs.add(new PointPair(c, null));
}
for (final Coordinate c : fp) {
pairs.add(new PointPair(null, c));
}
}
if (fileResults != null) {
// Matches are marked in the original value with 1 for true, 0 for false
if (saveMatched) {
for (final PointPair pair : matches) {
PeakResult result = ((PeakResultPoint) pair.getPoint2()).getPeakResult();
result = result.copy();
result.setOrigValue(1);
fileResults.add(result);
}
}
if (saveUnmatched) {
for (final Coordinate c : fp) {
PeakResult result = ((PeakResultPoint) c).getPeakResult();
result = result.copy();
result.setOrigValue(0);
fileResults.add(result);
}
}
}
}
if (fileResults != null) {
fileResults.end();
}
final boolean doIdAnalysis1 = settings.idAnalysis && haveIds(results1);
final boolean doIdAnalysis2 = settings.idAnalysis && haveIds(results2);
// Create output.
// This supports headless mode with just the results table
// or graphical mode with a results table and pairs window.
final boolean headless = java.awt.GraphicsEnvironment.isHeadless();
TextWindow resultsWindow = null;
if (!headless) {
resultsWindow = (settings.showTable) ? createResultsWindow(doIdAnalysis1 || doIdAnalysis2) : null;
showPairs(results1, pairs, resultsWindow);
}
showResults(results1, results2, allMatches, n1, n2, doIdAnalysis1, doIdAnalysis2, resultsWindow);
savePairs(results1, results2, allMatches);
}
use of uk.ac.sussex.gdsc.smlm.results.PeakResult in project GDSC-SMLM by aherbert.
the class ClassificationMatchCalculator method runCompareClassifications.
private void runCompareClassifications(MemoryPeakResults results1, MemoryPeakResults results2) {
final List<PointPair> allMatches = new LinkedList<>();
// Optionally exclude results which do not have an id and/or category
Predicate<PeakResult> test = settings.useId == ClassAnalysis.IGNORE_ZERO ? r -> r.getId() != 0 : null;
if (settings.useCategory == ClassAnalysis.IGNORE_ZERO) {
final Predicate<PeakResult> test2 = r -> r.getCategory() != 0;
test = test == null ? test2 : test.and(test2);
} else if (test == null) {
test = r -> true;
}
// Divide the results into time points
final TIntObjectHashMap<List<PeakResultPoint>> coordinates1 = getCoordinates(results1, test);
final TIntObjectHashMap<List<PeakResultPoint>> coordinates2 = getCoordinates(results2, test);
// Process each time point
int n1 = 0;
int n2 = 0;
for (final int t : getTimepoints(coordinates1, coordinates2)) {
final Coordinate[] c1 = getCoordinates(coordinates1, t);
final Coordinate[] c2 = getCoordinates(coordinates2, t);
n1 += c1.length;
n2 += c2.length;
final List<PointPair> matches = new LinkedList<>();
MatchCalculator.analyseResults3D(c1, c2, settings.matchDistance, null, null, null, matches);
allMatches.addAll(matches);
}
if (allMatches.isEmpty()) {
IJ.error(TITLE, "No localisation matches between the two results sets");
return;
}
// Get the unique Ids and Categories in the matches.
final Mapper ids = getMapper(allMatches, PeakResult::getId, settings.useId);
final Mapper cats = getMapper(allMatches, PeakResult::getCategory, settings.useCategory);
// Map id/category to an index = stride * cat + id
final int stride = ids.size();
// Any integer is allowed as an index
if ((long) stride * cats.size() > 1L << 32) {
IJ.error(TITLE, "Too many combinations of id and category to assigne unique labels");
return;
}
// Extract indices
final int[] set1 = new int[allMatches.size()];
final int[] set2 = new int[allMatches.size()];
int i = 0;
for (final PointPair r : allMatches) {
set1[i] = toIndex(stride, ids, cats, ((PeakResultPoint) r.getPoint1()).getPeakResult());
set2[i] = toIndex(stride, ids, cats, ((PeakResultPoint) r.getPoint2()).getPeakResult());
i++;
}
final Resequencer re = new Resequencer();
re.setCacheMap(true);
re.renumber(set1);
re.renumber(set2);
// Compare
final RandIndex r = new RandIndex().compute(set1, set2);
final TextWindow resultsWindow = ImageJUtils.refresh(resultsWindowRef, () -> new TextWindow(TITLE + " Results", "Results1\tResults2\tID\tCategory\tn1\tc1\tn2\tc2\tMatched\tRand Index\tAdjusted RI", "", 900, 300));
try (BufferedTextWindow bw = new BufferedTextWindow(resultsWindow)) {
final StringBuilder sb = new StringBuilder(2048);
sb.append(results1.getName()).append('\t');
sb.append(results2.getName()).append('\t');
sb.append(ANALYSIS_OPTION[settings.useId.ordinal()]).append('\t');
sb.append(ANALYSIS_OPTION[settings.useCategory.ordinal()]).append('\t');
sb.append(n1).append('\t');
sb.append(MathUtils.max(set1) + 1).append('\t');
sb.append(n2).append('\t');
sb.append(MathUtils.max(set2) + 1).append('\t');
sb.append(set1.length).append('\t');
sb.append(MathUtils.rounded(r.getRandIndex())).append('\t');
sb.append(MathUtils.rounded(r.getAdjustedRandIndex())).append('\t');
bw.append(sb.toString());
}
}
use of uk.ac.sussex.gdsc.smlm.results.PeakResult in project GDSC-SMLM by aherbert.
the class AstigmatismModelManager method plotData.
private boolean plotData() {
if (results.size() <= imp.getStackSize() / 2) {
IJ.error(TITLE, "Not enough fit results " + results.size());
return false;
}
final double umPerSlice = pluginSettings.getNmPerSlice() / 1000.0;
// final double nmPerPixel = results.getNmPerPixel();
z = new double[results.size()];
x = new double[z.length];
y = new double[z.length];
intensity = new double[z.length];
final Counter counter = new Counter();
// We have fit the results so they will be in the preferred units
results.forEach(new PeakResultProcedure() {
@Override
public void execute(PeakResult peak) {
final int i = counter.getAndIncrement();
z[i] = peak.getFrame() * umPerSlice;
x[i] = (peak.getXPosition() - cx);
y[i] = (peak.getYPosition() - cy);
intensity[i] = peak.getIntensity();
}
});
final WidthResultProcedure wp = new WidthResultProcedure(results, DistanceUnit.PIXEL);
wp.getWxWy();
sx = SimpleArrayUtils.toDouble(wp.wx);
sy = SimpleArrayUtils.toDouble(wp.wy);
final WindowOrganiser wo = new WindowOrganiser();
plot(wo, z, "Intensity (photon)", intensity, "Intensity", null, null);
xyPlot = plot(wo, z, "Position (px)", x, "X", y, "Y");
widthPlot = plot(wo, z, "Width (px)", sx, "Sx", sy, "Sy");
wo.tile();
return true;
}
use of uk.ac.sussex.gdsc.smlm.results.PeakResult in project GDSC-SMLM by aherbert.
the class CreateData method saveCompoundMolecules.
@SuppressWarnings("null")
private void saveCompoundMolecules(MemoryPeakResults results) {
if (idToCompound == null) {
return;
}
final MemoryPeakResults[] set = new MemoryPeakResults[compoundNames.size()];
for (int i = 0; i < set.length; i++) {
set[i] = copyMemoryPeakResults("Compound " + (i + 1) + ", " + compoundNames.get(i));
}
final PeakResult[] peakResults = results.toArray();
// Sort using the ID
Arrays.sort(peakResults, new Comparator<PeakResult>() {
@Override
public int compare(PeakResult o1, PeakResult o2) {
return o1.getId() - o2.getId();
}
});
MemoryPeakResults currentResults = null;
final FrameCounter counter = new FrameCounter(-1);
for (final PeakResult p : peakResults) {
if (counter.advance(p.getId())) {
currentResults = set[idToCompound.get(p.getId())];
}
currentResults.add(p);
}
for (int i = 0; i < set.length; i++) {
set[i].end();
}
}
use of uk.ac.sussex.gdsc.smlm.results.PeakResult in project GDSC-SMLM by aherbert.
the class ImageJ3DResultsViewer method createImage3DUniverse.
/**
* Creates the image 3D universe with a unique name.
*
* @param title the title
* @param titleList the title list (of titles to ignore)
* @return the image 3D universe
*/
private Image3DUniverse createImage3DUniverse(String title, List<String> titleList) {
// Get a unique name by appending numbers to the end
String title2 = title;
int counter = 2;
while (titleList.contains(title2)) {
title2 = title + " " + (counter++);
}
final Image3DUniverse universe = new Image3DUniverse();
universe.addUniverseListener(new LocalUniverseListener());
universe.setShowBoundingBoxUponSelection(false);
universe.showAttribute(DefaultUniverse.ATTRIBUTE_SCALEBAR, false);
// Capture a canvas mouse click/region and identify the coordinates.
final ImageCanvas3D canvas = (ImageCanvas3D) universe.getCanvas();
final BranchGroup scene = universe.getScene();
final MouseListener mouseListener = new MouseAdapter() {
@Override
public void mouseClicked(final MouseEvent event) {
if (!consumeEvent(event)) {
return;
}
// Consume the event
event.consume();
// This finds the vertex indices of the rendered object.
final Pair<Content, IntersectionInfo> pair = getPickedContent(canvas, scene, event.getX(), event.getY());
if (pair == null) {
// Do the same as the mouseClicked in Image3DUniverse
universe.select(null);
return;
}
// Only process content added from localisations
final Content c = pair.getKey();
if (!(c.getUserData() instanceof ResultsMetaData)) {
// Do the same as the mouseClicked in Image3DUniverse
universe.select(c);
return;
}
final ResultsMetaData data = (ResultsMetaData) c.getUserData();
final MemoryPeakResults results = data.results;
// Look up the localisation from the clicked vertex
final ContentInstant content = c.getCurrent();
int index = -1;
if (content.getContent() instanceof CustomMeshNode) {
final CustomMeshNode node = (CustomMeshNode) content.getContent();
final CustomMesh mesh = node.getMesh();
int vertexCount;
final GeometryArray ga = (GeometryArray) mesh.getGeometry();
// Default to the number of vertices
vertexCount = ga.getValidVertexCount();
final int countPerLocalisation = vertexCount / results.size();
// Determine the localisation
final int vertexIndex = pair.getValue().getVertexIndices()[0];
index = vertexIndex / countPerLocalisation;
} else if (content.getContent() instanceof ItemGroupNode) {
// All shapes have the index as the user data
final Object o = pair.getValue().getGeometry().getUserData();
if (o instanceof Integer) {
index = (Integer) pair.getValue().getGeometry().getUserData();
}
}
if (index == -1) {
return;
}
final PeakResult result = results.get(index);
if (event.getClickCount() > 1) {
// Centre on the localisation
final Point3d coordinate = new Point3d();
coordinate.set(data.points.get(index));
// Handle the local transform of the content ...
final Transform3D vWorldToLocal = getVworldToLocal(content);
vWorldToLocal.transform(coordinate);
universe.centerAt(coordinate);
} else if (event.isShiftDown()) {
// Ctrl+Shift held down to remove selected
data.removeFromSelectionModel(result);
} else {
// Ctrl held down to set selection
data.addToSelectionModel(result);
}
}
private boolean consumeEvent(final MouseEvent event) {
if (event.isConsumed() || event.getButton() != MouseEvent.BUTTON1 || !(event.isControlDown())) {
return false;
}
if (event.getClickCount() == 1) {
return true;
}
return (event.getClickCount() == 2);
}
};
// 0 = ImageCanvas3D
// 1 = DefaultUniverse
// 2 = Image3DUniverse
final MouseListener[] l = canvas.getMouseListeners();
for (int i = 0; i < l.length; i++) {
if (l[i].getClass().getName().contains("Image3DUniverse")) {
// We want to be before the Image3DUniverse to allow consuming the click event.
// Only allow the click event.
// This disables the right-click pop-up menu.
// It doesn't have anything of use for localisations anyway.
canvas.removeMouseListener(l[i]);
canvas.addMouseListener(mouseListener);
canvas.addMouseListener(new MouseListenerWrapper(l[i], MouseListenerWrapper.MOUSE_CLICKED));
}
}
// 0 = ImageCanvas3D
// 1 = DefaultUniverse
// 2 = Image3DUniverse
// 3 = EventCatcher (from scijava)
final MouseMotionListener[] ml = canvas.getMouseMotionListeners();
for (int i = 0; i < ml.length; i++) {
if (ml[i].getClass().getName().contains("Image3DUniverse")) {
// Ignore this as it just shows the name in the IJ status bar
canvas.removeMouseMotionListener(ml[i]);
}
}
// Finally display the window
universe.show();
final ImageWindow3D window = universe.getWindow();
GUI.center(window);
window.setTitle(title2);
WindowManager.addWindow(window);
window.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent event) {
WindowManager.removeWindow(window);
}
});
// Add a new menu for SMLM functionality
createSmlmMenuBar(universe);
return universe;
}
Aggregations