Search in sources :

Example 6 with IJImageSource

use of uk.ac.sussex.gdsc.smlm.ij.IJImageSource in project GDSC-SMLM by aherbert.

the class PeakFit method setup.

@Override
public int setup(String arg, ImagePlus imp) {
    SmlmUsageTracker.recordPlugin(this.getClass(), arg);
    pluginFlags = FLAGS;
    extraOptions = ImageJUtils.isExtraOptions();
    maximaIdentification = StringUtils.contains(arg, "spot");
    fitMaxima = StringUtils.contains(arg, "maxima");
    simpleFit = StringUtils.contains(arg, "simple");
    final boolean runSeries = StringUtils.contains(arg, "series");
    ImageSource imageSource = null;
    if (fitMaxima) {
        // The image source will be found from the peak results.
        if (!showMaximaDialog()) {
            return DONE;
        }
        final MemoryPeakResults localResults = ResultsManager.loadInputResults(settings.inputOption, false, DistanceUnit.PIXEL);
        if (localResults == null || localResults.size() == 0) {
            IJ.error(TITLE, "No results could be loaded");
            return DONE;
        }
        if (settings.fitAcrossAllFrames) {
            // Allow the user to select a different image. The source will be set as per the
            // main fit routine from the image (imp).
            singleFrame = 0;
        } else {
            // Check for single frame
            singleFrame = getSingleFrame(localResults);
            // Forces the maxima to be used with their original source.
            imp = null;
            imageSource = localResults.getSource();
            pluginFlags |= NO_IMAGE_REQUIRED;
        }
    } else if (runSeries) {
        imp = null;
        // Select input folder
        final String inputDirectory = IJ.getDirectory("Select image series ...");
        if (inputDirectory == null) {
            return DONE;
        }
        // Load input series ...
        SeriesOpener series;
        if (extraOptions) {
            final String helpKey = maximaIdentification ? "spot-finder-series" : "peak-fit-series";
            series = SeriesOpener.create(inputDirectory, true, HelpUrls.getUrl(helpKey));
        } else {
            series = new SeriesOpener(inputDirectory);
        }
        if (series.getNumberOfImages() == 0) {
            IJ.error(TITLE, "No images in the selected directory:\n" + inputDirectory);
            return DONE;
        }
        final SeriesImageSource seriesImageSource = new SeriesImageSource(getName(series.getImageList()), series);
        // TrackProgress logging is very verbose if the series has many images
        // Status is used only when reading TIFF info.
        // seriesImageSource.setTrackProgress(SimpleImageJTrackProgress.getInstance());
        seriesImageSource.setTrackProgress(new TrackProgressAdaptor() {

            @Override
            public void status(String format, Object... args) {
                ImageJUtils.showStatus(() -> String.format(format, args));
            }
        });
        imageSource = seriesImageSource;
        pluginFlags |= NO_IMAGE_REQUIRED;
    }
    // If the image source has not been set then use the input image
    if (imageSource == null) {
        if (imp == null) {
            IJ.noImage();
            return DONE;
        }
        // Check it is not a previous result
        if (imp.getTitle().endsWith(ImageJImagePeakResults.IMAGE_SUFFIX)) {
            IJImageSource ijImageSource = null;
            // Check the image to see if it has an image source XML structure in the info property
            final Object o = imp.getProperty("Info");
            final Pattern pattern = Pattern.compile("Source: (<.*IJImageSource>.*<.*IJImageSource>)", Pattern.DOTALL);
            final Matcher match = pattern.matcher((o == null) ? "" : o.toString());
            if (match.find()) {
                final ImageSource tmpSource = ImageSource.fromXml(match.group(1));
                if (tmpSource instanceof IJImageSource) {
                    ijImageSource = (IJImageSource) tmpSource;
                    if (!ijImageSource.open()) {
                        ijImageSource = null;
                    } else {
                        imp = WindowManager.getImage(ijImageSource.getName());
                    }
                }
            }
            if (ijImageSource == null) {
                // Look for a parent using the title
                final String parentTitle = imp.getTitle().substring(0, imp.getTitle().length() - ImageJImagePeakResults.IMAGE_SUFFIX.length() - 1);
                final ImagePlus parentImp = WindowManager.getImage(parentTitle);
                if (parentImp != null) {
                    ijImageSource = new IJImageSource(parentImp);
                    imp = parentImp;
                }
            }
            String message = "The selected image may be a previous fit result";
            if (ijImageSource != null) {
                if (!TextUtils.isNullOrEmpty(ijImageSource.getName())) {
                    message += " of: \n \n" + ijImageSource.getName();
                }
                message += " \n \nFit the parent?";
            } else {
                message += " \n \nDo you want to continue?";
            }
            final YesNoCancelDialog d = new YesNoCancelDialog(null, TITLE, message);
            if (ijImageSource == null) {
                if (!d.yesPressed()) {
                    return DONE;
                }
            } else {
                if (d.yesPressed()) {
                    imageSource = ijImageSource;
                }
                if (d.cancelPressed()) {
                    return DONE;
                }
            }
        }
        if (imageSource == null) {
            try {
                imageSource = new IJImageSource(imp);
            } catch (final IllegalArgumentException ex) {
                // This can happen if the image has an origin not in integer pixels
                // e.g. the plugin is run on a plot
                IJ.error(TITLE, "Error using image: " + imp.getTitle() + "\n \n" + ex.getMessage());
                return DONE;
            }
        }
    }
    time = -1;
    if (!initialiseImage(imageSource, getBounds(imp), false)) {
        IJ.error(TITLE, "Failed to initialise the source image: " + imageSource.getName());
        return DONE;
    }
    final int flags = showDialog(imp);
    if ((flags & DONE) == 0) {
        initialiseFitting();
    }
    return flags;
}
Also used : Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) SeriesImageSource(uk.ac.sussex.gdsc.smlm.ij.SeriesImageSource) SeriesOpener(uk.ac.sussex.gdsc.core.ij.SeriesOpener) ImagePlus(ij.ImagePlus) TrackProgressAdaptor(uk.ac.sussex.gdsc.core.logging.TrackProgressAdaptor) IJImageSource(uk.ac.sussex.gdsc.smlm.ij.IJImageSource) MemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults) YesNoCancelDialog(ij.gui.YesNoCancelDialog) ImageSource(uk.ac.sussex.gdsc.smlm.results.ImageSource) AggregatedImageSource(uk.ac.sussex.gdsc.smlm.results.AggregatedImageSource) InterlacedImageSource(uk.ac.sussex.gdsc.smlm.results.InterlacedImageSource) SeriesImageSource(uk.ac.sussex.gdsc.smlm.ij.SeriesImageSource) IJImageSource(uk.ac.sussex.gdsc.smlm.ij.IJImageSource)

Example 7 with IJImageSource

use of uk.ac.sussex.gdsc.smlm.ij.IJImageSource in project GDSC-SMLM by aherbert.

the class FailCountManager method createData.

/**
 * Creates the fail count data by running fitting on the current image.
 */
private void createData() {
    final ImagePlus imp = WindowManager.getCurrentImage();
    if (imp == null) {
        IJ.error(TITLE, "No image for fitting");
        return;
    }
    if (!showCreateDataDialog(imp)) {
        return;
    }
    // Get the current fit configuration
    final Configuration c = new Configuration();
    if (!c.showDialog(false)) {
        return;
    }
    final FitEngineConfiguration fitConfig = c.getFitEngineConfiguration();
    // Update stopping criteria.
    fitConfig.resetFailCounter();
    fitConfig.setFailuresLimit(settings.getFailCountLimit());
    final ImageSource source = new IJImageSource(imp);
    final PeakFit peakFit = new PeakFit(fitConfig, ResultsSettings.getDefaultInstance());
    peakFit.setResultsSuffix("(FailCountAnalysis)");
    if (!peakFit.initialise(source, null, false)) {
        IJ.error(TITLE, "Failed to initialise the fit engine");
        return;
    }
    final FitEngine engine = peakFit.createFitEngine();
    final Rectangle bounds = new Rectangle(source.getWidth(), source.getHeight());
    // Run
    final int totalFrames = Math.min(source.getFrames(), settings.getMaxFrames());
    final int step = ImageJUtils.getProgressInterval(totalFrames);
    IJ.showProgress(0);
    boolean shutdown = false;
    int slice = 0;
    final LocalList<ParameterisedFitJob> jobs = new LocalList<>(totalFrames);
    while (!shutdown && slice < totalFrames) {
        final float[] data = source.next();
        if (data == null) {
            break;
        }
        if (slice++ % step == 0) {
            final int frames = slice;
            if (ImageJUtils.showStatus(() -> "Fitting slice: " + frames + " / " + totalFrames)) {
                IJ.showProgress(slice, totalFrames);
            }
        }
        final ParameterisedFitJob job = createJob(source.getStartFrameNumber(), data, bounds);
        jobs.push(job);
        engine.run(job);
        shutdown = escapePressed();
    }
    ImageJUtils.showStatus("Extracting fail count data");
    engine.end(shutdown);
    IJ.showProgress(1);
    source.close();
    // Extract the fail count data
    final LocalList<FailCountData> failCountData = new LocalList<>(jobs.size());
    for (int i = 0; i < jobs.size(); i++) {
        final ParameterisedFitJob job = jobs.unsafeGet(i);
        if (job.getStatus() == Status.FINISHED) {
            final FitParameters fitParams = job.getFitParameters();
            // Find the last success
            boolean[] results = fitParams.pass;
            int end = results.length - 1;
            while (end > 0 && !results[end]) {
                end--;
            }
            // Add on the configured fail count limit
            end = Math.min(end + 1 + settings.getFailCountLimit(), results.length);
            results = Arrays.copyOf(results, end);
            failCountData.add(new FailCountData(job.getSlice(), results));
        }
    }
    failCountDataRef.set(failCountData);
    ImageJUtils.showStatus("");
    // Save for the future
    if (settings.getSaveAfterFitting()) {
        saveData();
    }
}
Also used : FitParameters(uk.ac.sussex.gdsc.smlm.engine.FitParameters) ParameterisedFitJob(uk.ac.sussex.gdsc.smlm.engine.ParameterisedFitJob) FitEngineConfiguration(uk.ac.sussex.gdsc.smlm.engine.FitEngineConfiguration) FitEngineConfiguration(uk.ac.sussex.gdsc.smlm.engine.FitEngineConfiguration) Rectangle(java.awt.Rectangle) ImagePlus(ij.ImagePlus) IJImageSource(uk.ac.sussex.gdsc.smlm.ij.IJImageSource) LocalList(uk.ac.sussex.gdsc.core.utils.LocalList) FitEngine(uk.ac.sussex.gdsc.smlm.engine.FitEngine) ImageSource(uk.ac.sussex.gdsc.smlm.results.ImageSource) IJImageSource(uk.ac.sussex.gdsc.smlm.ij.IJImageSource)

Example 8 with IJImageSource

use of uk.ac.sussex.gdsc.smlm.ij.IJImageSource in project GDSC-SMLM by aherbert.

the class OverlayResults method run.

@Override
public void run(String arg) {
    SmlmUsageTracker.recordPlugin(this.getClass(), arg);
    if (MemoryPeakResults.isMemoryEmpty()) {
        IJ.error(TITLE, "There are no fitting results in memory");
        return;
    }
    names = new String[MemoryPeakResults.getResultNames().size() + 1];
    ids = new int[names.length];
    int count = 0;
    names[count++] = "(None)";
    for (final MemoryPeakResults results : MemoryPeakResults.getAllResults()) {
        if (results.getSource() != null && results.getSource().getOriginal() instanceof IJImageSource) {
            final IJImageSource source = (IJImageSource) (results.getSource().getOriginal());
            final ImagePlus imp = WindowManager.getImage(source.getName());
            if (imp != null) {
                ids[count] = imp.getID();
                names[count++] = results.getName();
            }
        }
    }
    if (count == 1) {
        IJ.error(TITLE, "There are no result images available");
        return;
    }
    names = Arrays.copyOf(names, count);
    Thread thread = null;
    Worker worker = null;
    final NonBlockingGenericDialog gd = new NonBlockingGenericDialog(TITLE);
    settings = Settings.load();
    settings.save();
    gd.addMessage("Overlay results on current image frame");
    gd.addChoice("Results", names, (settings.name == null) ? "" : settings.name);
    gd.addCheckbox("Show_table", settings.showTable);
    gd.addMessage("");
    gd.addHelp(HelpUrls.getUrl("overlay-results"));
    gd.hideCancelButton();
    gd.setOKLabel("Close");
    if (!(IJ.isMacro() || java.awt.GraphicsEnvironment.isHeadless())) {
        worker = new Worker();
        choice = (Choice) gd.getChoices().get(0);
        choice.addItemListener(worker);
        checkbox = (Checkbox) gd.getCheckboxes().get(0);
        checkbox.addItemListener(worker);
        label = (Label) gd.getMessage();
        // Initialise
        worker.refresh();
        // Listen for changes to an image
        ImagePlus.addImageListener(worker);
        thread = new Thread(worker);
        thread.setDaemon(true);
        thread.start();
    }
    gd.showDialog();
    if (worker != null) {
        ImagePlus.removeImageListener(worker);
    }
    if (!gd.wasCanceled()) {
        settings.name = gd.getNextChoice();
        settings.showTable = gd.getNextBoolean();
    }
    if (thread != null && worker != null) {
        worker.running = false;
        inbox.close(true);
        try {
            thread.join(0);
        } catch (final InterruptedException ex) {
            Logger.getLogger(getClass().getName()).log(Level.WARNING, "Unexpected interruption", ex);
            Thread.currentThread().interrupt();
        }
    }
}
Also used : IJImageSource(uk.ac.sussex.gdsc.smlm.ij.IJImageSource) MemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults) NonBlockingGenericDialog(ij.gui.NonBlockingGenericDialog) ImagePlus(ij.ImagePlus) Point(java.awt.Point)

Example 9 with IJImageSource

use of uk.ac.sussex.gdsc.smlm.ij.IJImageSource in project GDSC-SMLM by aherbert.

the class SpotAnalysis method extractSpotProfile.

private double[][] extractSpotProfile(ImagePlus imp, Rectangle bounds, ImageStack rawSpot) {
    final int nSlices = imp.getStackSize();
    final IJImageSource rawSource = new IJImageSource(imp);
    final double[][] profile = new double[2][nSlices];
    for (int n = 0; n < nSlices; n++) {
        IJ.showProgress(n, nSlices);
        final float[] data = rawSource.next(bounds);
        rawSpot.setPixels(data, n + 1);
        final Statistics stats = Statistics.create(data);
        profile[0][n] = stats.getMean() / gain;
        profile[1][n] = stats.getStandardDeviation() / gain;
    }
    return profile;
}
Also used : IJImageSource(uk.ac.sussex.gdsc.smlm.ij.IJImageSource) Statistics(uk.ac.sussex.gdsc.core.utils.Statistics) Point(java.awt.Point)

Example 10 with IJImageSource

use of uk.ac.sussex.gdsc.smlm.ij.IJImageSource in project GDSC-SMLM by aherbert.

the class SpotAnalysis method addCandidateFrames.

private void addCandidateFrames(String title) {
    for (final MemoryPeakResults r : MemoryPeakResults.getAllResults()) {
        if (r.getSource() instanceof IJImageSource && r.getSource().getName().equals(title)) {
            final float minx = areaBounds.x;
            final float maxx = minx + areaBounds.width;
            final float miny = areaBounds.y;
            final float maxy = miny + areaBounds.height;
            r.forEach(DistanceUnit.PIXEL, (XyrResultProcedure) (x, y, result) -> {
                if (result.getXPosition() >= minx && result.getXPosition() <= maxx && result.getYPosition() >= miny && result.getYPosition() <= maxy) {
                    candidateFrames.add(result.getFrame());
                }
            });
        }
    }
}
Also used : Color(java.awt.Color) Choice(java.awt.Choice) TIntObjectHashMap(gnu.trove.map.hash.TIntObjectHashMap) Arrays(java.util.Arrays) GaussianBlur(ij.plugin.filter.GaussianBlur) TIntArrayList(gnu.trove.list.array.TIntArrayList) ImageProcessor(ij.process.ImageProcessor) TextWindow(ij.text.TextWindow) Scanner(java.util.Scanner) GUI(ij.gui.GUI) Point(java.awt.Point) ZProjector(ij.plugin.ZProjector) ItemListener(java.awt.event.ItemListener) ImageRoiPainter(uk.ac.sussex.gdsc.smlm.ij.utils.ImageRoiPainter) Button(java.awt.Button) Panel(java.awt.Panel) Future(java.util.concurrent.Future) MemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults) Gaussian2DFitter(uk.ac.sussex.gdsc.smlm.fitting.Gaussian2DFitter) MathUtils(uk.ac.sussex.gdsc.core.utils.MathUtils) BorderLayout(java.awt.BorderLayout) ListSelectionEvent(javax.swing.event.ListSelectionEvent) PsfProtosHelper(uk.ac.sussex.gdsc.smlm.data.config.PsfProtosHelper) ItemEvent(java.awt.event.ItemEvent) XyrResultProcedure(uk.ac.sussex.gdsc.smlm.results.procedures.XyrResultProcedure) Frame(java.awt.Frame) LoessInterpolator(org.apache.commons.math3.analysis.interpolation.LoessInterpolator) OffsetPointRoi(uk.ac.sussex.gdsc.core.ij.gui.OffsetPointRoi) DistanceUnit(uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.DistanceUnit) Gaussian2DPeakResultHelper(uk.ac.sussex.gdsc.smlm.results.Gaussian2DPeakResultHelper) GridBagConstraints(java.awt.GridBagConstraints) KeyEvent(java.awt.event.KeyEvent) Logger(java.util.logging.Logger) ConcurrencyUtils(uk.ac.sussex.gdsc.core.utils.concurrent.ConcurrencyUtils) Component(java.awt.Component) Gaussian2DFunction(uk.ac.sussex.gdsc.smlm.function.gaussian.Gaussian2DFunction) Plot(ij.gui.Plot) WindowEvent(java.awt.event.WindowEvent) Executors(java.util.concurrent.Executors) ImagePlus(ij.ImagePlus) FitStatus(uk.ac.sussex.gdsc.smlm.fitting.FitStatus) List(java.util.List) SimpleArrayUtils(uk.ac.sussex.gdsc.core.utils.SimpleArrayUtils) GridBagLayout(java.awt.GridBagLayout) Roi(ij.gui.Roi) JPanel(javax.swing.JPanel) Rectangle(java.awt.Rectangle) Insets(java.awt.Insets) ActionListener(java.awt.event.ActionListener) PolynomialSplineFunction(org.apache.commons.math3.analysis.polynomials.PolynomialSplineFunction) Prefs(ij.Prefs) WindowManager(ij.WindowManager) WindowOrganiser(uk.ac.sussex.gdsc.core.ij.plugin.WindowOrganiser) PeakResult(uk.ac.sussex.gdsc.smlm.results.PeakResult) KeyAdapter(java.awt.event.KeyAdapter) AtomicReference(java.util.concurrent.atomic.AtomicReference) TextField(java.awt.TextField) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) IJImageSource(uk.ac.sussex.gdsc.smlm.ij.IJImageSource) Trace(uk.ac.sussex.gdsc.smlm.results.Trace) ImageJTrackProgress(uk.ac.sussex.gdsc.core.ij.ImageJTrackProgress) GenericDialog(ij.gui.GenericDialog) Menus(ij.Menus) LinkedList(java.util.LinkedList) NoSuchElementException(java.util.NoSuchElementException) FitConfiguration(uk.ac.sussex.gdsc.smlm.engine.FitConfiguration) Statistics(uk.ac.sussex.gdsc.core.utils.Statistics) ExecutorService(java.util.concurrent.ExecutorService) FlowLayout(java.awt.FlowLayout) FitResult(uk.ac.sussex.gdsc.smlm.fitting.FitResult) Files(java.nio.file.Files) PlugInFrame(ij.plugin.frame.PlugInFrame) BufferedWriter(java.io.BufferedWriter) Label(java.awt.Label) JList(javax.swing.JList) ImageAdapter(uk.ac.sussex.gdsc.core.ij.ImageAdapter) IOException(java.io.IOException) Ticker(uk.ac.sussex.gdsc.core.logging.Ticker) ActionEvent(java.awt.event.ActionEvent) JScrollPane(javax.swing.JScrollPane) DefaultListModel(javax.swing.DefaultListModel) Paths(java.nio.file.Paths) ImageJUtils(uk.ac.sussex.gdsc.core.ij.ImageJUtils) IJ(ij.IJ) ImageStack(ij.ImageStack) ListSelectionListener(javax.swing.event.ListSelectionListener) IJImageSource(uk.ac.sussex.gdsc.smlm.ij.IJImageSource) MemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults)

Aggregations

IJImageSource (uk.ac.sussex.gdsc.smlm.ij.IJImageSource)16 ImagePlus (ij.ImagePlus)10 Rectangle (java.awt.Rectangle)10 MemoryPeakResults (uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults)9 ImageStack (ij.ImageStack)6 ImageSource (uk.ac.sussex.gdsc.smlm.results.ImageSource)6 ExtendedGenericDialog (uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog)5 GenericDialog (ij.gui.GenericDialog)4 ImageProcessor (ij.process.ImageProcessor)4 Ticker (uk.ac.sussex.gdsc.core.logging.Ticker)4 CalibrationWriter (uk.ac.sussex.gdsc.smlm.data.config.CalibrationWriter)4 FitEngine (uk.ac.sussex.gdsc.smlm.engine.FitEngine)4 PeakResult (uk.ac.sussex.gdsc.smlm.results.PeakResult)4 IJ (ij.IJ)3 Prefs (ij.Prefs)3 WindowManager (ij.WindowManager)3 Point (java.awt.Point)3 ItemEvent (java.awt.event.ItemEvent)3 File (java.io.File)3 ArrayList (java.util.ArrayList)3