Search in sources :

Example 16 with PeakResult

use of uk.ac.sussex.gdsc.smlm.results.PeakResult in project GDSC-SMLM by aherbert.

the class PeakFit method getSingleFrame.

/**
 * Gets the single frame containing all the results (if they are all in a single frame), else 0.
 *
 * @param results the results (must not be empty)
 * @return the single frame (or zero)
 */
private static int getSingleFrame(MemoryPeakResults results) {
    final FrameCounter counter = new FrameCounter(results.getFirstFrame());
    // The counter will return true (stop execution) if a new frame
    results.forEach((PeakResultProcedureX) peakResult -> counter.advance(peakResult.getFrame()));
    if (counter.currentFrame() != counter.previousFrame()) {
        return 0;
    }
    return counter.currentFrame();
}
Also used : Color(java.awt.Color) Choice(java.awt.Choice) Arrays(java.util.Arrays) Calibration(uk.ac.sussex.gdsc.smlm.data.config.CalibrationProtos.Calibration) UnitConverterUtils(uk.ac.sussex.gdsc.smlm.data.config.UnitConverterUtils) ImageProcessor(ij.process.ImageProcessor) ImageSource(uk.ac.sussex.gdsc.smlm.results.ImageSource) Filter(uk.ac.sussex.gdsc.smlm.results.filter.Filter) PSFType(uk.ac.sussex.gdsc.smlm.data.config.PSFProtos.PSFType) StringUtils(org.apache.commons.lang3.StringUtils) ResultsSettings(uk.ac.sussex.gdsc.smlm.data.config.ResultsProtos.ResultsSettings) Panel(java.awt.Panel) Vector(java.util.Vector) Matcher(java.util.regex.Matcher) YesNoCancelDialog(ij.gui.YesNoCancelDialog) MemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults) Map(java.util.Map) FitProtosHelper(uk.ac.sussex.gdsc.smlm.data.config.FitProtosHelper) ImageJImageConverter(uk.ac.sussex.gdsc.smlm.ij.utils.ImageJImageConverter) FilePeakResults(uk.ac.sussex.gdsc.smlm.results.FilePeakResults) EnumSet(java.util.EnumSet) LutHelper(uk.ac.sussex.gdsc.core.ij.process.LutHelper) InputSource(uk.ac.sussex.gdsc.smlm.ij.plugins.ResultsManager.InputSource) DistanceUnit(uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.DistanceUnit) GuiProtosHelper(uk.ac.sussex.gdsc.smlm.ij.settings.GuiProtosHelper) TextUtils(uk.ac.sussex.gdsc.core.utils.TextUtils) Scrollbar(java.awt.Scrollbar) ImagePlus(ij.ImagePlus) CalibrationProtosHelper(uk.ac.sussex.gdsc.smlm.data.config.CalibrationProtosHelper) FitEngineSettings(uk.ac.sussex.gdsc.smlm.data.config.FitProtos.FitEngineSettings) PeakResultProcedureX(uk.ac.sussex.gdsc.smlm.results.procedures.PeakResultProcedureX) Prefs(ij.Prefs) FrameCounter(uk.ac.sussex.gdsc.smlm.results.count.FrameCounter) WindowManager(ij.WindowManager) PeakResult(uk.ac.sussex.gdsc.smlm.results.PeakResult) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) PointRoi(ij.gui.PointRoi) DataFilterMethod(uk.ac.sussex.gdsc.smlm.data.config.FitProtos.DataFilterMethod) GenericDialog(ij.gui.GenericDialog) FitConfiguration(uk.ac.sussex.gdsc.smlm.engine.FitConfiguration) Overlay(ij.gui.Overlay) IntFunction(java.util.function.IntFunction) SeriesOpener(uk.ac.sussex.gdsc.core.ij.SeriesOpener) FitWorker(uk.ac.sussex.gdsc.smlm.engine.FitWorker) FitEngine(uk.ac.sussex.gdsc.smlm.engine.FitEngine) File(java.io.File) AggregatedImageSource(uk.ac.sussex.gdsc.smlm.results.AggregatedImageSource) DirectFilter(uk.ac.sussex.gdsc.smlm.results.filter.DirectFilter) ImageJTablePeakResults(uk.ac.sussex.gdsc.smlm.ij.results.ImageJTablePeakResults) ImageStack(ij.ImageStack) CameraModel(uk.ac.sussex.gdsc.smlm.model.camera.CameraModel) PsfHelper(uk.ac.sussex.gdsc.smlm.data.config.PsfHelper) FitJob(uk.ac.sussex.gdsc.smlm.engine.FitJob) ResultsTableSettings(uk.ac.sussex.gdsc.smlm.data.config.ResultsProtos.ResultsTableSettings) FitTask(uk.ac.sussex.gdsc.smlm.engine.FitParameters.FitTask) ItemListener(java.awt.event.ItemListener) PSFParameter(uk.ac.sussex.gdsc.smlm.data.config.PSFProtos.PSFParameter) FitSolver(uk.ac.sussex.gdsc.smlm.data.config.FitProtos.FitSolver) ResultsImageSettings(uk.ac.sussex.gdsc.smlm.data.config.ResultsProtos.ResultsImageSettings) ImageJPluginLoggerHelper(uk.ac.sussex.gdsc.core.ij.ImageJPluginLoggerHelper) XyResultProcedure(uk.ac.sussex.gdsc.smlm.results.procedures.XyResultProcedure) InterlacedImageSource(uk.ac.sussex.gdsc.smlm.results.InterlacedImageSource) ImageJImagePeakResults(uk.ac.sussex.gdsc.smlm.ij.results.ImageJImagePeakResults) PeakResults(uk.ac.sussex.gdsc.smlm.results.PeakResults) MathUtils(uk.ac.sussex.gdsc.core.utils.MathUtils) CalibrationWriter(uk.ac.sussex.gdsc.smlm.data.config.CalibrationWriter) PlugInFilter(ij.plugin.filter.PlugInFilter) PsfProtosHelper(uk.ac.sussex.gdsc.smlm.data.config.PsfProtosHelper) FitParameters(uk.ac.sussex.gdsc.smlm.engine.FitParameters) SettingsManager(uk.ac.sussex.gdsc.smlm.ij.settings.SettingsManager) ItemEvent(java.awt.event.ItemEvent) CameraType(uk.ac.sussex.gdsc.smlm.data.config.CalibrationProtos.CameraType) ExtendedGenericDialog(uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog) PeakResultsList(uk.ac.sussex.gdsc.smlm.results.PeakResultsList) TrackProgressAdaptor(uk.ac.sussex.gdsc.core.logging.TrackProgressAdaptor) ResultsImageType(uk.ac.sussex.gdsc.smlm.data.config.ResultsProtos.ResultsImageType) FitEngineConfiguration(uk.ac.sussex.gdsc.smlm.engine.FitEngineConfiguration) OffsetPointRoi(uk.ac.sussex.gdsc.core.ij.gui.OffsetPointRoi) GridBagConstraints(java.awt.GridBagConstraints) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) BitFlagUtils(uk.ac.sussex.gdsc.core.utils.BitFlagUtils) List(java.util.List) SpotFilter(uk.ac.sussex.gdsc.smlm.filters.SpotFilter) LUT(ij.process.LUT) Pattern(java.util.regex.Pattern) FitQueue(uk.ac.sussex.gdsc.smlm.engine.FitQueue) SeriesImageSource(uk.ac.sussex.gdsc.smlm.ij.SeriesImageSource) TypeConverter(uk.ac.sussex.gdsc.core.data.utils.TypeConverter) Roi(ij.gui.Roi) ParameterisedFitJob(uk.ac.sussex.gdsc.smlm.engine.ParameterisedFitJob) IntStream(java.util.stream.IntStream) Rectangle(java.awt.Rectangle) Insets(java.awt.Insets) PrecisionMethod(uk.ac.sussex.gdsc.smlm.data.config.FitProtos.PrecisionMethod) PSFCalculatorSettings(uk.ac.sussex.gdsc.smlm.ij.settings.GUIProtos.PSFCalculatorSettings) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) PSF(uk.ac.sussex.gdsc.smlm.data.config.PSFProtos.PSF) ResultsFileSettings(uk.ac.sussex.gdsc.smlm.data.config.ResultsProtos.ResultsFileSettings) AtomicReference(java.util.concurrent.atomic.AtomicReference) TextField(java.awt.TextField) OptionListener(uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog.OptionListener) IJImageSource(uk.ac.sussex.gdsc.smlm.ij.IJImageSource) NoiseEstimatorMethod(uk.ac.sussex.gdsc.smlm.data.config.FitProtos.NoiseEstimatorMethod) ResultsProtosHelper(uk.ac.sussex.gdsc.smlm.data.config.ResultsProtosHelper) TemplateSettings(uk.ac.sussex.gdsc.smlm.data.config.TemplateProtos.TemplateSettings) FastMleSteppingFunctionSolver(uk.ac.sussex.gdsc.smlm.fitting.nonlinear.FastMleSteppingFunctionSolver) SystemColor(java.awt.SystemColor) AstigmatismModel(uk.ac.sussex.gdsc.smlm.data.config.PSFProtos.AstigmatismModel) Iterator(java.util.Iterator) Checkbox(java.awt.Checkbox) Label(java.awt.Label) LutColour(uk.ac.sussex.gdsc.core.ij.process.LutHelper.LutColour) CalibrationReader(uk.ac.sussex.gdsc.smlm.data.config.CalibrationReader) TimeUnit(uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.TimeUnit) Counter(uk.ac.sussex.gdsc.smlm.results.count.Counter) ImageJUtils(uk.ac.sussex.gdsc.core.ij.ImageJUtils) IJ(ij.IJ) PerPixelCameraModel(uk.ac.sussex.gdsc.smlm.model.camera.PerPixelCameraModel) FrameCounter(uk.ac.sussex.gdsc.smlm.results.count.FrameCounter)

Example 17 with PeakResult

use of uk.ac.sussex.gdsc.smlm.results.PeakResult in project GDSC-SMLM by aherbert.

the class PeakFit method runMaximaFitting.

/**
 * Load the selected results from memory. All multiple frame results are added directly to the
 * results. All single frame results are added to a list of candidate maxima per frame and fitted
 * using the configured parameters.
 */
private void runMaximaFitting() {
    final MemoryPeakResults memoryResults = ResultsManager.loadInputResults(settings.inputOption, false, DistanceUnit.PIXEL);
    if (memoryResults == null || memoryResults.size() == 0) {
        log("No results for maxima fitting");
        return;
    }
    // The total frames (for progress reporting)
    int totalFrames;
    // A function that can convert a frame into a set of candidate indices
    final IntFunction<int[]> frameToMaxIndices;
    // The frames to process (should be sorted ascending)
    Supplier<IntStream> frames;
    // Support fitting all time frames with the same results.
    if (settings.fitAcrossAllFrames) {
        // Check if the input spans multiple frames
        if (getSingleFrame(memoryResults) == 0) {
            final int min = memoryResults.getMinFrame();
            final int max = memoryResults.getMaxFrame();
            final GenericDialog gd = new GenericDialog(TITLE);
            gd.enableYesNoCancel();
            gd.hideCancelButton();
            ImageJUtils.addMessage(gd, "Candidate maxima for fitting span multiple frames (%d-%d).\n \n" + "Please confirm the %s are correct.", min, max, TextUtils.pleural(memoryResults.size(), "candidate"));
            gd.showDialog();
            if (!gd.wasOKed()) {
                return;
            }
        }
        final int[] maxIndices = getMaxIndices(Arrays.asList(memoryResults.toArray()));
        // This may not work correctly if using for example a series image source that
        // incorrectly estimates the number of frames
        totalFrames = source.getFrames();
        frameToMaxIndices = frame -> maxIndices;
        frames = () -> IntStream.rangeClosed(1, totalFrames);
    } else {
        // Build a map between the time-frame and the results in that frame.
        final Map<Integer, List<PeakResult>> map = Arrays.stream(memoryResults.toArray()).parallel().filter(peakResult -> peakResult.getFrame() == peakResult.getEndFrame()).collect(Collectors.groupingBy(PeakResult::getFrame));
        totalFrames = map.size();
        // Build a function that can convert a frame into a set of candidate indices
        frameToMaxIndices = frame -> getMaxIndices(map.get(frame));
        frames = () -> map.keySet().stream().mapToInt(Integer::intValue).sorted();
    }
    final ImageStack stack = (extraSettings.showProcessedFrames) ? new ImageStack(bounds.width, bounds.height) : null;
    // Use the FitEngine to allow multi-threading.
    final FitEngine engine = createFitEngine(getNumberOfThreads(totalFrames));
    if (engine == null) {
        return;
    }
    final int step = ImageJUtils.getProgressInterval(totalFrames);
    // No crop bounds are supported.
    // To pre-process data for noise estimation
    final boolean isFitCameraCounts = fitConfig.isFitCameraCounts();
    final CameraModel cameraModel = fitConfig.getCameraModel();
    runTime = System.nanoTime();
    final AtomicBoolean shutdown = new AtomicBoolean();
    final String format = String.format("Slice: %%d / %d (Results=%%d)", totalFrames);
    frames.get().forEachOrdered(slice -> {
        if (shutdown.get() || escapePressed()) {
            shutdown.set(true);
            return;
        }
        final float[] data = source.get(slice);
        if (data == null) {
            shutdown.set(true);
            return;
        }
        if (slice % step == 0) {
            if (ImageJUtils.showStatus(() -> String.format(format, slice, results.size()))) {
                IJ.showProgress(slice, totalFrames);
            }
        }
        // We must pre-process the data before noise estimation
        final float[] data2 = data.clone();
        if (isFitCameraCounts) {
            cameraModel.removeBias(data2);
        } else {
            cameraModel.removeBiasAndGain(data2);
        }
        final float noise = FitWorker.estimateNoise(data2, source.getWidth(), source.getHeight(), config.getNoiseMethod());
        if (stack != null) {
            stack.addSlice(String.format("Frame %d - %d", source.getStartFrameNumber(), source.getEndFrameNumber()), data);
        }
        // Get the frame number from the source to allow for interlaced and aggregated data
        engine.run(createMaximaFitJob(frameToMaxIndices.apply(slice), source.getStartFrameNumber(), source.getEndFrameNumber(), data, bounds, noise));
    });
    engine.end(shutdown.get());
    time = engine.getTime();
    runTime = System.nanoTime() - runTime;
    if (stack != null) {
        ImageJUtils.display("Processed frames", stack);
    }
    showResults();
    source.close();
}
Also used : Color(java.awt.Color) Choice(java.awt.Choice) Arrays(java.util.Arrays) Calibration(uk.ac.sussex.gdsc.smlm.data.config.CalibrationProtos.Calibration) UnitConverterUtils(uk.ac.sussex.gdsc.smlm.data.config.UnitConverterUtils) ImageProcessor(ij.process.ImageProcessor) ImageSource(uk.ac.sussex.gdsc.smlm.results.ImageSource) Filter(uk.ac.sussex.gdsc.smlm.results.filter.Filter) PSFType(uk.ac.sussex.gdsc.smlm.data.config.PSFProtos.PSFType) StringUtils(org.apache.commons.lang3.StringUtils) ResultsSettings(uk.ac.sussex.gdsc.smlm.data.config.ResultsProtos.ResultsSettings) Panel(java.awt.Panel) Vector(java.util.Vector) Matcher(java.util.regex.Matcher) YesNoCancelDialog(ij.gui.YesNoCancelDialog) MemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults) Map(java.util.Map) FitProtosHelper(uk.ac.sussex.gdsc.smlm.data.config.FitProtosHelper) ImageJImageConverter(uk.ac.sussex.gdsc.smlm.ij.utils.ImageJImageConverter) FilePeakResults(uk.ac.sussex.gdsc.smlm.results.FilePeakResults) EnumSet(java.util.EnumSet) LutHelper(uk.ac.sussex.gdsc.core.ij.process.LutHelper) InputSource(uk.ac.sussex.gdsc.smlm.ij.plugins.ResultsManager.InputSource) DistanceUnit(uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.DistanceUnit) GuiProtosHelper(uk.ac.sussex.gdsc.smlm.ij.settings.GuiProtosHelper) TextUtils(uk.ac.sussex.gdsc.core.utils.TextUtils) Scrollbar(java.awt.Scrollbar) ImagePlus(ij.ImagePlus) CalibrationProtosHelper(uk.ac.sussex.gdsc.smlm.data.config.CalibrationProtosHelper) FitEngineSettings(uk.ac.sussex.gdsc.smlm.data.config.FitProtos.FitEngineSettings) PeakResultProcedureX(uk.ac.sussex.gdsc.smlm.results.procedures.PeakResultProcedureX) Prefs(ij.Prefs) FrameCounter(uk.ac.sussex.gdsc.smlm.results.count.FrameCounter) WindowManager(ij.WindowManager) PeakResult(uk.ac.sussex.gdsc.smlm.results.PeakResult) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) PointRoi(ij.gui.PointRoi) DataFilterMethod(uk.ac.sussex.gdsc.smlm.data.config.FitProtos.DataFilterMethod) GenericDialog(ij.gui.GenericDialog) FitConfiguration(uk.ac.sussex.gdsc.smlm.engine.FitConfiguration) Overlay(ij.gui.Overlay) IntFunction(java.util.function.IntFunction) SeriesOpener(uk.ac.sussex.gdsc.core.ij.SeriesOpener) FitWorker(uk.ac.sussex.gdsc.smlm.engine.FitWorker) FitEngine(uk.ac.sussex.gdsc.smlm.engine.FitEngine) File(java.io.File) AggregatedImageSource(uk.ac.sussex.gdsc.smlm.results.AggregatedImageSource) DirectFilter(uk.ac.sussex.gdsc.smlm.results.filter.DirectFilter) ImageJTablePeakResults(uk.ac.sussex.gdsc.smlm.ij.results.ImageJTablePeakResults) ImageStack(ij.ImageStack) CameraModel(uk.ac.sussex.gdsc.smlm.model.camera.CameraModel) PsfHelper(uk.ac.sussex.gdsc.smlm.data.config.PsfHelper) FitJob(uk.ac.sussex.gdsc.smlm.engine.FitJob) ResultsTableSettings(uk.ac.sussex.gdsc.smlm.data.config.ResultsProtos.ResultsTableSettings) FitTask(uk.ac.sussex.gdsc.smlm.engine.FitParameters.FitTask) ItemListener(java.awt.event.ItemListener) PSFParameter(uk.ac.sussex.gdsc.smlm.data.config.PSFProtos.PSFParameter) FitSolver(uk.ac.sussex.gdsc.smlm.data.config.FitProtos.FitSolver) ResultsImageSettings(uk.ac.sussex.gdsc.smlm.data.config.ResultsProtos.ResultsImageSettings) ImageJPluginLoggerHelper(uk.ac.sussex.gdsc.core.ij.ImageJPluginLoggerHelper) XyResultProcedure(uk.ac.sussex.gdsc.smlm.results.procedures.XyResultProcedure) InterlacedImageSource(uk.ac.sussex.gdsc.smlm.results.InterlacedImageSource) ImageJImagePeakResults(uk.ac.sussex.gdsc.smlm.ij.results.ImageJImagePeakResults) PeakResults(uk.ac.sussex.gdsc.smlm.results.PeakResults) MathUtils(uk.ac.sussex.gdsc.core.utils.MathUtils) CalibrationWriter(uk.ac.sussex.gdsc.smlm.data.config.CalibrationWriter) PlugInFilter(ij.plugin.filter.PlugInFilter) PsfProtosHelper(uk.ac.sussex.gdsc.smlm.data.config.PsfProtosHelper) FitParameters(uk.ac.sussex.gdsc.smlm.engine.FitParameters) SettingsManager(uk.ac.sussex.gdsc.smlm.ij.settings.SettingsManager) ItemEvent(java.awt.event.ItemEvent) CameraType(uk.ac.sussex.gdsc.smlm.data.config.CalibrationProtos.CameraType) ExtendedGenericDialog(uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog) PeakResultsList(uk.ac.sussex.gdsc.smlm.results.PeakResultsList) TrackProgressAdaptor(uk.ac.sussex.gdsc.core.logging.TrackProgressAdaptor) ResultsImageType(uk.ac.sussex.gdsc.smlm.data.config.ResultsProtos.ResultsImageType) FitEngineConfiguration(uk.ac.sussex.gdsc.smlm.engine.FitEngineConfiguration) OffsetPointRoi(uk.ac.sussex.gdsc.core.ij.gui.OffsetPointRoi) GridBagConstraints(java.awt.GridBagConstraints) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) BitFlagUtils(uk.ac.sussex.gdsc.core.utils.BitFlagUtils) List(java.util.List) SpotFilter(uk.ac.sussex.gdsc.smlm.filters.SpotFilter) LUT(ij.process.LUT) Pattern(java.util.regex.Pattern) FitQueue(uk.ac.sussex.gdsc.smlm.engine.FitQueue) SeriesImageSource(uk.ac.sussex.gdsc.smlm.ij.SeriesImageSource) TypeConverter(uk.ac.sussex.gdsc.core.data.utils.TypeConverter) Roi(ij.gui.Roi) ParameterisedFitJob(uk.ac.sussex.gdsc.smlm.engine.ParameterisedFitJob) IntStream(java.util.stream.IntStream) Rectangle(java.awt.Rectangle) Insets(java.awt.Insets) PrecisionMethod(uk.ac.sussex.gdsc.smlm.data.config.FitProtos.PrecisionMethod) PSFCalculatorSettings(uk.ac.sussex.gdsc.smlm.ij.settings.GUIProtos.PSFCalculatorSettings) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) PSF(uk.ac.sussex.gdsc.smlm.data.config.PSFProtos.PSF) ResultsFileSettings(uk.ac.sussex.gdsc.smlm.data.config.ResultsProtos.ResultsFileSettings) AtomicReference(java.util.concurrent.atomic.AtomicReference) TextField(java.awt.TextField) OptionListener(uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog.OptionListener) IJImageSource(uk.ac.sussex.gdsc.smlm.ij.IJImageSource) NoiseEstimatorMethod(uk.ac.sussex.gdsc.smlm.data.config.FitProtos.NoiseEstimatorMethod) ResultsProtosHelper(uk.ac.sussex.gdsc.smlm.data.config.ResultsProtosHelper) TemplateSettings(uk.ac.sussex.gdsc.smlm.data.config.TemplateProtos.TemplateSettings) FastMleSteppingFunctionSolver(uk.ac.sussex.gdsc.smlm.fitting.nonlinear.FastMleSteppingFunctionSolver) SystemColor(java.awt.SystemColor) AstigmatismModel(uk.ac.sussex.gdsc.smlm.data.config.PSFProtos.AstigmatismModel) Iterator(java.util.Iterator) Checkbox(java.awt.Checkbox) Label(java.awt.Label) LutColour(uk.ac.sussex.gdsc.core.ij.process.LutHelper.LutColour) CalibrationReader(uk.ac.sussex.gdsc.smlm.data.config.CalibrationReader) TimeUnit(uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.TimeUnit) Counter(uk.ac.sussex.gdsc.smlm.results.count.Counter) ImageJUtils(uk.ac.sussex.gdsc.core.ij.ImageJUtils) IJ(ij.IJ) PerPixelCameraModel(uk.ac.sussex.gdsc.smlm.model.camera.PerPixelCameraModel) CameraModel(uk.ac.sussex.gdsc.smlm.model.camera.CameraModel) PerPixelCameraModel(uk.ac.sussex.gdsc.smlm.model.camera.PerPixelCameraModel) ImageStack(ij.ImageStack) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) FitEngine(uk.ac.sussex.gdsc.smlm.engine.FitEngine) GenericDialog(ij.gui.GenericDialog) ExtendedGenericDialog(uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog) MemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults) ArrayList(java.util.ArrayList) PeakResultsList(uk.ac.sussex.gdsc.smlm.results.PeakResultsList) List(java.util.List) IntStream(java.util.stream.IntStream)

Example 18 with PeakResult

use of uk.ac.sussex.gdsc.smlm.results.PeakResult in project GDSC-SMLM by aherbert.

the class PeakFit method getMaxIndices.

private int[] getMaxIndices(List<PeakResult> sliceCandidates) {
    final int[] maxIndices = new int[sliceCandidates.size()];
    int count = 0;
    for (final PeakResult result : sliceCandidates) {
        maxIndices[count++] = result.getOrigX() + bounds.width * result.getOrigY();
    }
    return maxIndices;
}
Also used : PeakResult(uk.ac.sussex.gdsc.smlm.results.PeakResult)

Example 19 with PeakResult

use of uk.ac.sussex.gdsc.smlm.results.PeakResult 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());
}
Also used : Color(java.awt.Color) RandomUtils(uk.ac.sussex.gdsc.core.utils.rng.RandomUtils) Arrays(java.util.Arrays) Macro(ij.Macro) ImageProcessor(ij.process.ImageProcessor) Rectangle2D(java.awt.geom.Rectangle2D) Future(java.util.concurrent.Future) Pair(org.apache.commons.lang3.tuple.Pair) MemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults) GoalType(org.apache.commons.math3.optim.nonlinear.scalar.GoalType) UnivariateObjectiveFunction(org.apache.commons.math3.optim.univariate.UnivariateObjectiveFunction) LutHelper(uk.ac.sussex.gdsc.core.ij.process.LutHelper) WeightedObservedPoint(org.apache.commons.math3.fitting.WeightedObservedPoint) ThresholdMethod(uk.ac.sussex.gdsc.smlm.ij.frc.Frc.ThresholdMethod) XyrResultProcedure(uk.ac.sussex.gdsc.smlm.results.procedures.XyrResultProcedure) LoessInterpolator(org.apache.commons.math3.analysis.interpolation.LoessInterpolator) InputSource(uk.ac.sussex.gdsc.smlm.ij.plugins.ResultsManager.InputSource) DistanceUnit(uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.DistanceUnit) SimpleCurveFitter(org.apache.commons.math3.fitting.SimpleCurveFitter) PointValuePair(org.apache.commons.math3.optim.PointValuePair) NelderMeadSimplex(org.apache.commons.math3.optim.nonlinear.scalar.noderiv.NelderMeadSimplex) ConcurrencyUtils(uk.ac.sussex.gdsc.core.utils.concurrent.ConcurrencyUtils) TextUtils(uk.ac.sussex.gdsc.core.utils.TextUtils) Plot(ij.gui.Plot) Scrollbar(java.awt.Scrollbar) Executors(java.util.concurrent.Executors) ImagePlus(ij.ImagePlus) TDoubleArrayList(gnu.trove.list.array.TDoubleArrayList) FrcCurveResult(uk.ac.sussex.gdsc.smlm.ij.frc.Frc.FrcCurveResult) MaxEval(org.apache.commons.math3.optim.MaxEval) PlugIn(ij.plugin.PlugIn) AtomicDouble(com.google.common.util.concurrent.AtomicDouble) MathArrays(org.apache.commons.math3.util.MathArrays) Prefs(ij.Prefs) WindowManager(ij.WindowManager) PeakResult(uk.ac.sussex.gdsc.smlm.results.PeakResult) UnivariateOptimizer(org.apache.commons.math3.optim.univariate.UnivariateOptimizer) GenericDialog(ij.gui.GenericDialog) PeakResultProcedure(uk.ac.sussex.gdsc.smlm.results.procedures.PeakResultProcedure) GaussianCurveFitter(org.apache.commons.math3.fitting.GaussianCurveFitter) ResultsImageSizeMode(uk.ac.sussex.gdsc.smlm.data.config.ResultsProtos.ResultsImageSizeMode) FourierMethod(uk.ac.sussex.gdsc.smlm.ij.frc.Frc.FourierMethod) MouseEvent(java.awt.event.MouseEvent) DescriptiveStatistics(org.apache.commons.math3.stat.descriptive.DescriptiveStatistics) Erf(uk.ac.sussex.gdsc.smlm.function.Erf) UnivariatePointValuePair(org.apache.commons.math3.optim.univariate.UnivariatePointValuePair) SamplingMethod(uk.ac.sussex.gdsc.smlm.ij.frc.Frc.SamplingMethod) Frc(uk.ac.sussex.gdsc.smlm.ij.frc.Frc) DoubleMedianWindow(uk.ac.sussex.gdsc.core.utils.DoubleMedianWindow) FrcFireResult(uk.ac.sussex.gdsc.smlm.ij.frc.Frc.FrcFireResult) ResultsImageSettings(uk.ac.sussex.gdsc.smlm.data.config.ResultsProtos.ResultsImageSettings) StoredDataStatistics(uk.ac.sussex.gdsc.core.utils.StoredDataStatistics) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ImageJImagePeakResults(uk.ac.sussex.gdsc.smlm.ij.results.ImageJImagePeakResults) MouseAdapter(java.awt.event.MouseAdapter) DataException(uk.ac.sussex.gdsc.core.data.DataException) NonBlockingExtendedGenericDialog(uk.ac.sussex.gdsc.core.ij.gui.NonBlockingExtendedGenericDialog) PlotWindow(ij.gui.PlotWindow) MathUtils(uk.ac.sussex.gdsc.core.utils.MathUtils) SettingsManager(uk.ac.sussex.gdsc.smlm.ij.settings.SettingsManager) Collection(java.util.Collection) ExtendedGenericDialog(uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog) TrackProgressAdaptor(uk.ac.sussex.gdsc.core.logging.TrackProgressAdaptor) ResultsImageType(uk.ac.sussex.gdsc.smlm.data.config.ResultsProtos.ResultsImageType) ParametricUnivariateFunction(org.apache.commons.math3.analysis.ParametricUnivariateFunction) ObjectiveFunction(org.apache.commons.math3.optim.nonlinear.scalar.ObjectiveFunction) SimplexOptimizer(org.apache.commons.math3.optim.nonlinear.scalar.noderiv.SimplexOptimizer) BracketFinder(org.apache.commons.math3.optim.univariate.BracketFinder) List(java.util.List) Gaussian(org.apache.commons.math3.analysis.function.Gaussian) SimpleArrayUtils(uk.ac.sussex.gdsc.core.utils.SimpleArrayUtils) UnivariateFunction(org.apache.commons.math3.analysis.UnivariateFunction) MultivariateFunction(org.apache.commons.math3.analysis.MultivariateFunction) LUT(ij.process.LUT) FrcCurve(uk.ac.sussex.gdsc.smlm.ij.frc.Frc.FrcCurve) PrecisionResultProcedure(uk.ac.sussex.gdsc.smlm.results.procedures.PrecisionResultProcedure) Rectangle(java.awt.Rectangle) SearchInterval(org.apache.commons.math3.optim.univariate.SearchInterval) WindowOrganiser(uk.ac.sussex.gdsc.core.ij.plugin.WindowOrganiser) AtomicReference(java.util.concurrent.atomic.AtomicReference) TrackProgress(uk.ac.sussex.gdsc.core.logging.TrackProgress) TextField(java.awt.TextField) AWTEvent(java.awt.AWTEvent) ImagePeakResultsFactory(uk.ac.sussex.gdsc.smlm.ij.results.ImagePeakResultsFactory) InitialGuess(org.apache.commons.math3.optim.InitialGuess) UnitHelper(uk.ac.sussex.gdsc.smlm.data.config.UnitHelper) LinkedList(java.util.LinkedList) Statistics(uk.ac.sussex.gdsc.core.utils.Statistics) ExecutorService(java.util.concurrent.ExecutorService) DialogListener(ij.gui.DialogListener) ConversionException(uk.ac.sussex.gdsc.core.data.utils.ConversionException) Checkbox(java.awt.Checkbox) StdMath(uk.ac.sussex.gdsc.smlm.utils.StdMath) ResultsImageMode(uk.ac.sussex.gdsc.smlm.data.config.ResultsProtos.ResultsImageMode) LutColour(uk.ac.sussex.gdsc.core.ij.process.LutHelper.LutColour) Recorder(ij.plugin.frame.Recorder) WeightedObservedPoints(org.apache.commons.math3.fitting.WeightedObservedPoints) BrentOptimizer(org.apache.commons.math3.optim.univariate.BrentOptimizer) CalibrationReader(uk.ac.sussex.gdsc.smlm.data.config.CalibrationReader) Counter(uk.ac.sussex.gdsc.smlm.results.count.Counter) HistogramPlot(uk.ac.sussex.gdsc.core.ij.HistogramPlot) ImageJUtils(uk.ac.sussex.gdsc.core.ij.ImageJUtils) IJ(ij.IJ) LocalList(uk.ac.sussex.gdsc.core.utils.LocalList) UniformRandomProviders(uk.ac.sussex.gdsc.core.utils.rng.UniformRandomProviders) Rectangle(java.awt.Rectangle) ResultsImageSettings(uk.ac.sussex.gdsc.smlm.data.config.ResultsProtos.ResultsImageSettings) ImageJImagePeakResults(uk.ac.sussex.gdsc.smlm.ij.results.ImageJImagePeakResults) WeightedObservedPoint(org.apache.commons.math3.fitting.WeightedObservedPoint) PeakResult(uk.ac.sussex.gdsc.smlm.results.PeakResult) ImageProcessor(ij.process.ImageProcessor) Counter(uk.ac.sussex.gdsc.smlm.results.count.Counter)

Example 20 with PeakResult

use of uk.ac.sussex.gdsc.smlm.results.PeakResult in project GDSC-SMLM by aherbert.

the class Fire method showFrcTimeEvolution.

private void showFrcTimeEvolution(String name, double fireNumber, ThresholdMethod thresholdMethod, double fourierImageScale, int imageSize) {
    IJ.showStatus("Calculating FRC time evolution curve...");
    // Sort by time
    results.sort();
    final int nSteps = 10;
    int maxT = results.getLastFrame();
    if (maxT == 0) {
        maxT = results.size();
    }
    final int step = maxT / nSteps;
    final TDoubleArrayList x = new TDoubleArrayList();
    final TDoubleArrayList y = new TDoubleArrayList();
    double yMin = fireNumber;
    double yMax = fireNumber;
    final MemoryPeakResults newResults = new MemoryPeakResults();
    newResults.copySettings(results);
    int index = 0;
    final PeakResult[] list = results.toArray();
    for (int t = step; t <= maxT - step; t += step) {
        while (index < list.length) {
            final PeakResult r = list[index];
            if (r.getFrame() <= t) {
                newResults.add(r);
                index++;
            } else {
                break;
            }
        }
        x.add(t);
        final Fire f = this.copy();
        final FireResult result = f.calculateFireNumber(fourierMethod, samplingMethod, thresholdMethod, fourierImageScale, imageSize);
        final double fire = (result == null) ? 0 : result.fireNumber;
        y.add(fire);
        yMin = Math.min(yMin, fire);
        yMax = Math.max(yMax, fire);
    }
    // Add the final fire number
    x.add(maxT);
    y.add(fireNumber);
    final double[] xValues = x.toArray();
    final double[] yValues = y.toArray();
    String units = "px";
    if (results.getCalibration() != null) {
        nmPerUnit = results.getNmPerPixel();
        units = "nm";
    }
    final String title = name + " FRC Time Evolution";
    final Plot plot = new Plot(title, "Frames", "Resolution (" + units + ")");
    final double range = Math.max(1, yMax - yMin) * 0.05;
    plot.setLimits(xValues[0], xValues[xValues.length - 1], yMin - range, yMax + range);
    plot.setColor(Color.red);
    plot.addPoints(xValues, yValues, Plot.CONNECTED_CIRCLES);
    ImageJUtils.display(title, plot);
}
Also used : TDoubleArrayList(gnu.trove.list.array.TDoubleArrayList) FrcFireResult(uk.ac.sussex.gdsc.smlm.ij.frc.Frc.FrcFireResult) Plot(ij.gui.Plot) HistogramPlot(uk.ac.sussex.gdsc.core.ij.HistogramPlot) MemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults) WeightedObservedPoint(org.apache.commons.math3.fitting.WeightedObservedPoint) PeakResult(uk.ac.sussex.gdsc.smlm.results.PeakResult)

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