Search in sources :

Example 46 with PeakResult

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);
}
Also used : TextFilePeakResults(uk.ac.sussex.gdsc.smlm.results.TextFilePeakResults) LinkedList(java.util.LinkedList) PeakResultPoint(uk.ac.sussex.gdsc.smlm.results.PeakResultPoint) Point(java.awt.Point) PeakResult(uk.ac.sussex.gdsc.smlm.results.PeakResult) TextWindow(ij.text.TextWindow) BufferedTextWindow(uk.ac.sussex.gdsc.core.ij.BufferedTextWindow) Coordinate(uk.ac.sussex.gdsc.core.match.Coordinate) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List) PointPair(uk.ac.sussex.gdsc.core.match.PointPair) PeakResultPoint(uk.ac.sussex.gdsc.smlm.results.PeakResultPoint)

Example 47 with PeakResult

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());
    }
}
Also used : PeakResultPoint(uk.ac.sussex.gdsc.smlm.results.PeakResultPoint) TIntObjectHashMap(gnu.trove.map.hash.TIntObjectHashMap) Arrays(java.util.Arrays) ConfigurationException(uk.ac.sussex.gdsc.smlm.data.config.ConfigurationException) Prefs(ij.Prefs) TextWindow(ij.text.TextWindow) FrameCounter(uk.ac.sussex.gdsc.smlm.results.count.FrameCounter) PeakResult(uk.ac.sussex.gdsc.smlm.results.PeakResult) AtomicReference(java.util.concurrent.atomic.AtomicReference) ConversionException(com.thoughtworks.xstream.converters.ConversionException) TIntProcedure(gnu.trove.procedure.TIntProcedure) MemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults) MathUtils(uk.ac.sussex.gdsc.core.utils.MathUtils) LinkedList(java.util.LinkedList) SettingsManager(uk.ac.sussex.gdsc.smlm.ij.settings.SettingsManager) RandIndex(uk.ac.sussex.gdsc.core.match.RandIndex) Predicate(java.util.function.Predicate) BufferedTextWindow(uk.ac.sussex.gdsc.core.ij.BufferedTextWindow) ExtendedGenericDialog(uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog) InputSource(uk.ac.sussex.gdsc.smlm.ij.plugins.ResultsManager.InputSource) ToIntFunction(java.util.function.ToIntFunction) TIntIntHashMap(gnu.trove.map.hash.TIntIntHashMap) NamedObject(uk.ac.sussex.gdsc.smlm.data.NamedObject) DistanceUnit(uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.DistanceUnit) Coordinate(uk.ac.sussex.gdsc.core.match.Coordinate) TextUtils(uk.ac.sussex.gdsc.core.utils.TextUtils) TIntHashSet(gnu.trove.set.hash.TIntHashSet) XyzrResultProcedure(uk.ac.sussex.gdsc.smlm.results.procedures.XyzrResultProcedure) List(java.util.List) PointPair(uk.ac.sussex.gdsc.core.match.PointPair) Resequencer(uk.ac.sussex.gdsc.core.match.Resequencer) ImageJUtils(uk.ac.sussex.gdsc.core.ij.ImageJUtils) IJ(ij.IJ) MatchCalculator(uk.ac.sussex.gdsc.core.match.MatchCalculator) PlugIn(ij.plugin.PlugIn) LocalList(uk.ac.sussex.gdsc.core.utils.LocalList) BufferedTextWindow(uk.ac.sussex.gdsc.core.ij.BufferedTextWindow) Resequencer(uk.ac.sussex.gdsc.core.match.Resequencer) RandIndex(uk.ac.sussex.gdsc.core.match.RandIndex) LinkedList(java.util.LinkedList) PeakResult(uk.ac.sussex.gdsc.smlm.results.PeakResult) PeakResultPoint(uk.ac.sussex.gdsc.smlm.results.PeakResultPoint) TextWindow(ij.text.TextWindow) BufferedTextWindow(uk.ac.sussex.gdsc.core.ij.BufferedTextWindow) Coordinate(uk.ac.sussex.gdsc.core.match.Coordinate) LinkedList(java.util.LinkedList) List(java.util.List) LocalList(uk.ac.sussex.gdsc.core.utils.LocalList) PointPair(uk.ac.sussex.gdsc.core.match.PointPair) PeakResultPoint(uk.ac.sussex.gdsc.smlm.results.PeakResultPoint)

Example 48 with PeakResult

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;
}
Also used : Counter(uk.ac.sussex.gdsc.smlm.results.count.Counter) PeakResultProcedure(uk.ac.sussex.gdsc.smlm.results.procedures.PeakResultProcedure) WidthResultProcedure(uk.ac.sussex.gdsc.smlm.results.procedures.WidthResultProcedure) WindowOrganiser(uk.ac.sussex.gdsc.core.ij.plugin.WindowOrganiser) PeakResult(uk.ac.sussex.gdsc.smlm.results.PeakResult)

Example 49 with PeakResult

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();
    }
}
Also used : FrameCounter(uk.ac.sussex.gdsc.smlm.results.count.FrameCounter) MemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults) ImmutableMemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.ImmutableMemoryPeakResults) ReadHint(uk.ac.sussex.gdsc.smlm.results.ImageSource.ReadHint) IdPeakResult(uk.ac.sussex.gdsc.smlm.results.IdPeakResult) PeakResult(uk.ac.sussex.gdsc.smlm.results.PeakResult) ExtendedPeakResult(uk.ac.sussex.gdsc.smlm.results.ExtendedPeakResult)

Example 50 with PeakResult

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;
}
Also used : CustomMeshNode(customnode.CustomMeshNode) Transform3D(org.scijava.java3d.Transform3D) ItemGroupNode(uk.ac.sussex.gdsc.smlm.ij.ij3d.ItemGroupNode) IndexedGeometryArray(org.scijava.java3d.IndexedGeometryArray) GeometryArray(org.scijava.java3d.GeometryArray) WindowAdapter(java.awt.event.WindowAdapter) MouseMotionListener(java.awt.event.MouseMotionListener) PeakResult(uk.ac.sussex.gdsc.smlm.results.PeakResult) MouseListener(java.awt.event.MouseListener) Point3d(org.scijava.vecmath.Point3d) CustomMesh(customnode.CustomMesh) MemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults) IntersectionInfo(org.scijava.java3d.PickInfo.IntersectionInfo) MouseEvent(java.awt.event.MouseEvent) Image3DUniverse(ij3d.Image3DUniverse) ImageCanvas3D(ij3d.ImageCanvas3D) BranchGroup(org.scijava.java3d.BranchGroup) MouseAdapter(java.awt.event.MouseAdapter) ContentInstant(ij3d.ContentInstant) CustomContentInstant(uk.ac.sussex.gdsc.smlm.ij.ij3d.CustomContentInstant) ImageWindow3D(ij3d.ImageWindow3D) Content(ij3d.Content) CustomContent(uk.ac.sussex.gdsc.smlm.ij.ij3d.CustomContent) WindowEvent(java.awt.event.WindowEvent) NamedObject(uk.ac.sussex.gdsc.smlm.data.NamedObject)

Aggregations

PeakResult (uk.ac.sussex.gdsc.smlm.results.PeakResult)64 MemoryPeakResults (uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults)37 List (java.util.List)18 LocalList (uk.ac.sussex.gdsc.core.utils.LocalList)18 Rectangle (java.awt.Rectangle)17 Counter (uk.ac.sussex.gdsc.smlm.results.count.Counter)17 FrameCounter (uk.ac.sussex.gdsc.smlm.results.count.FrameCounter)17 PeakResultProcedure (uk.ac.sussex.gdsc.smlm.results.procedures.PeakResultProcedure)17 ImagePlus (ij.ImagePlus)14 ExtendedGenericDialog (uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog)14 DistanceUnit (uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.DistanceUnit)14 IJ (ij.IJ)13 ImageJUtils (uk.ac.sussex.gdsc.core.ij.ImageJUtils)12 PlugIn (ij.plugin.PlugIn)11 AtomicReference (java.util.concurrent.atomic.AtomicReference)10 SimpleArrayUtils (uk.ac.sussex.gdsc.core.utils.SimpleArrayUtils)10 SettingsManager (uk.ac.sussex.gdsc.smlm.ij.settings.SettingsManager)10 PointRoi (ij.gui.PointRoi)9 ArrayList (java.util.ArrayList)9 TypeConverter (uk.ac.sussex.gdsc.core.data.utils.TypeConverter)9