Search in sources :

Example 1 with SeriesImageSource

use of gdsc.smlm.ij.SeriesImageSource in project GDSC-SMLM by aherbert.

the class PeakFit method setup.

/*
	 * (non-Javadoc)
	 * 
	 * @see ij.plugin.filter.PlugInFilter#setup(java.lang.String, ij.ImagePlus)
	 */
public int setup(String arg, ImagePlus imp) {
    SMLMUsageTracker.recordPlugin(this.getClass(), arg);
    plugin_flags = FLAGS;
    extraOptions = Utils.isExtraOptions();
    maximaIdentification = (arg != null && arg.contains("spot"));
    fitMaxima = (arg != null && arg.contains("maxima"));
    simpleFit = (arg != null && arg.contains("simple"));
    boolean runSeries = (arg != null && arg.contains("series"));
    ImageSource imageSource = null;
    if (fitMaxima) {
        imp = null;
        // The image source will be found from the peak results.
        if (!showMaximaDialog())
            return DONE;
        MemoryPeakResults results = ResultsManager.loadInputResults(inputOption, false);
        if (results == null || results.size() == 0) {
            IJ.error(TITLE, "No results could be loaded");
            return DONE;
        }
        // Check for single frame
        singleFrame = results.getHead().getFrame();
        for (PeakResult result : results.getResults()) {
            if (singleFrame != result.getFrame()) {
                singleFrame = 0;
                break;
            }
        }
        imageSource = results.getSource();
        plugin_flags |= NO_IMAGE_REQUIRED;
    } else if (runSeries) {
        imp = null;
        // Select input folder
        String inputDirectory;
        inputDirectory = IJ.getDirectory("Select image series ...");
        //inputDirectory = getInputDirectory("Select image series ...");
        if (inputDirectory == null)
            return DONE;
        // Load input series ...
        SeriesOpener series;
        if (extraOptions)
            series = new SeriesOpener(inputDirectory, true, numberOfThreads);
        else
            series = new SeriesOpener(inputDirectory);
        if (series.getNumberOfImages() == 0) {
            IJ.error(TITLE, "No images in the selected directory:\n" + inputDirectory);
            return DONE;
        }
        SeriesImageSource seriesImageSource = new SeriesImageSource(getName(series.getImageList()), series);
        seriesImageSource.setLogProgress(true);
        if (extraOptions) {
            numberOfThreads = Math.max(1, series.getNumberOfThreads());
            seriesImageSource.setNumberOfThreads(numberOfThreads);
        }
        imageSource = seriesImageSource;
        plugin_flags |= NO_IMAGE_REQUIRED;
    } else {
        if (imp == null) {
            IJ.noImage();
            return DONE;
        }
        // Check it is not a previous result
        if (imp.getTitle().endsWith(IJImagePeakResults.IMAGE_SUFFIX)) {
            IJImageSource tmpImageSource = null;
            // Check the image to see if it has an image source XML structure in the info property
            Object o = imp.getProperty("Info");
            Pattern pattern = Pattern.compile("Source: (<.*IJImageSource>.*<.*IJImageSource>)", Pattern.DOTALL);
            Matcher match = pattern.matcher((o == null) ? "" : o.toString());
            if (match.find()) {
                ImageSource source = ImageSource.fromXML(match.group(1));
                if (source instanceof IJImageSource) {
                    tmpImageSource = (IJImageSource) source;
                    if (!tmpImageSource.open()) {
                        tmpImageSource = null;
                    } else {
                        imp = WindowManager.getImage(tmpImageSource.getName());
                    }
                }
            }
            if (tmpImageSource == null) {
                // Look for a parent using the title
                String parentTitle = imp.getTitle().substring(0, imp.getTitle().length() - IJImagePeakResults.IMAGE_SUFFIX.length() - 1);
                ImagePlus parentImp = WindowManager.getImage(parentTitle);
                if (parentImp != null) {
                    tmpImageSource = new IJImageSource(parentImp);
                    imp = parentImp;
                }
            }
            String message = "The selected image may be a previous fit result";
            if (tmpImageSource != null) {
                // are missing
                if (!Utils.isNullOrEmpty(tmpImageSource.getName()))
                    message += " of: \n \n" + tmpImageSource.getName();
                message += " \n \nFit the parent?";
            } else
                message += " \n \nDo you want to continue?";
            YesNoCancelDialog d = new YesNoCancelDialog(null, TITLE, message);
            if (tmpImageSource == null) {
                if (!d.yesPressed())
                    return DONE;
            } else {
                if (d.yesPressed())
                    imageSource = tmpImageSource;
                if (d.cancelPressed())
                    return DONE;
            }
        }
        if (imageSource == null)
            imageSource = new IJImageSource(imp);
    }
    time = -1;
    if (!initialiseImage(imageSource, getBounds(imp), false)) {
        IJ.error(TITLE, "Failed to initialise the source image: " + imageSource.getName());
        return DONE;
    }
    int flags = showDialog(imp);
    if ((flags & DONE) == 0) {
        // Repeat so that we pass in the selected option for ignoring the bounds.
        // This should not be necessary since it is set within the readDialog method.
        //if (ignoreBoundsForNoise)
        //	initialiseImage(imageSource, bounds, ignoreBoundsForNoise);
        initialiseFitting();
    }
    return flags;
}
Also used : Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) SeriesImageSource(gdsc.smlm.ij.SeriesImageSource) SeriesOpener(gdsc.smlm.ij.utils.SeriesOpener) ImagePlus(ij.ImagePlus) PeakResult(gdsc.smlm.results.PeakResult) ExtendedPeakResult(gdsc.smlm.results.ExtendedPeakResult) IJImageSource(gdsc.smlm.ij.IJImageSource) MemoryPeakResults(gdsc.smlm.results.MemoryPeakResults) YesNoCancelDialog(ij.gui.YesNoCancelDialog) AggregatedImageSource(gdsc.smlm.results.AggregatedImageSource) IJImageSource(gdsc.smlm.ij.IJImageSource) SeriesImageSource(gdsc.smlm.ij.SeriesImageSource) InterlacedImageSource(gdsc.smlm.results.InterlacedImageSource) ImageSource(gdsc.smlm.results.ImageSource)

Example 2 with SeriesImageSource

use of gdsc.smlm.ij.SeriesImageSource in project GDSC-SMLM by aherbert.

the class CMOSAnalysis method run.

private void run() {
    long start = System.currentTimeMillis();
    // Avoid all the file saves from updating the progress bar and status line
    Utils.setShowProgress(false);
    Utils.setShowStatus(false);
    JLabel statusLine = Utils.getStatusLine();
    progressBar = Utils.getProgressBar();
    // Create thread pool and workers
    ExecutorService executor = Executors.newFixedThreadPool(getThreads());
    TurboList<Future<?>> futures = new TurboList<Future<?>>(nThreads);
    TurboList<ImageWorker> workers = new TurboList<ImageWorker>(nThreads);
    double[][][] data = new double[subDirs.size()][2][];
    double[] pixelOffset = null, pixelVariance = null;
    Statistics statsOffset = null, statsVariance = null;
    // For each sub-directory compute the mean and variance
    final int nSubDirs = subDirs.size();
    boolean error = false;
    for (int n = 0; n < nSubDirs; n++) {
        SubDir sd = subDirs.getf(n);
        statusLine.setText("Analysing " + sd.name);
        // Open the series
        SeriesImageSource source = new SeriesImageSource(sd.name, sd.path.getPath());
        //source.setLogProgress(true);
        if (!source.open()) {
            error = true;
            IJ.error(TITLE, "Failed to open image series: " + sd.path.getPath());
            break;
        }
        // So the bar remains at 99% when workers have finished
        totalProgress = source.getFrames() + 1;
        stepProgress = Utils.getProgressInterval(totalProgress);
        progress = 0;
        progressBar.show(0);
        ArrayMoment moment = (rollingAlgorithm) ? new RollingArrayMoment() : new SimpleArrayMoment();
        final BlockingQueue<ImageJob> jobs = new ArrayBlockingQueue<ImageJob>(nThreads * 2);
        for (int i = 0; i < nThreads; i++) {
            final ImageWorker worker = new ImageWorker(jobs, moment);
            workers.add(worker);
            futures.add(executor.submit(worker));
        }
        // Process the data
        for (float[] pixels = source.next(); pixels != null; pixels = source.next()) {
            put(jobs, new ImageJob(pixels));
        }
        // Finish all the worker threads by passing in a null job
        for (int i = 0; i < nThreads; i++) {
            put(jobs, new ImageJob(null));
        }
        // Wait for all to finish
        for (int t = futures.size(); t-- > 0; ) {
            try {
                // The future .get() method will block until completed
                futures.get(t).get();
            } catch (Exception e) {
                // This should not happen. 
                e.printStackTrace();
            }
        }
        // Create the final aggregate statistics
        for (ImageWorker w : workers) moment.add(w.moment);
        data[n][0] = moment.getFirstMoment();
        data[n][1] = moment.getVariance();
        // Reset
        futures.clear();
        workers.clear();
        Statistics s = new Statistics(data[n][0]);
        if (n != 0) {
            // Compute mean ADU
            Statistics signal = new Statistics();
            double[] mean = data[n][0];
            for (int i = 0; i < pixelOffset.length; i++) signal.add(mean[i] - pixelOffset[i]);
            Utils.log("%s Mean = %s +/- %s. Signal = %s +/- %s ADU", sd.name, Utils.rounded(s.getMean()), Utils.rounded(s.getStandardDeviation()), Utils.rounded(signal.getMean()), Utils.rounded(signal.getStandardDeviation()));
            // TODO - optionally save
            ImageStack stack = new ImageStack(source.getWidth(), source.getHeight());
            stack.addSlice("Mean", Utils.toFloat(data[n][0]));
            stack.addSlice("Variance", Utils.toFloat(data[n][1]));
            IJ.save(new ImagePlus("PerPixel", stack), new File(directory, "perPixel" + sd.name + ".tif").getPath());
        } else {
            pixelOffset = data[0][0];
            pixelVariance = data[0][1];
            statsOffset = s;
            statsVariance = new Statistics(pixelVariance);
            Utils.log("%s Offset = %s +/- %s. Variance = %s +/- %s", sd.name, Utils.rounded(s.getMean()), Utils.rounded(s.getStandardDeviation()), Utils.rounded(statsVariance.getMean()), Utils.rounded(statsVariance.getStandardDeviation()));
        }
    }
    Utils.setShowStatus(true);
    Utils.setShowProgress(true);
    IJ.showProgress(1);
    executor.shutdown();
    if (error)
        return;
    // Compute the gain
    statusLine.setText("Computing gain");
    double[] pixelGain = new double[pixelOffset.length];
    // Ignore first as this is the 0 exposure image
    for (int i = 0; i < pixelGain.length; i++) {
        // Use equation 2.5 from the Huang et al paper.
        double bibiT = 0;
        double biaiT = 0;
        for (int n = 1; n < nSubDirs; n++) {
            double bi = data[n][0][i] - pixelOffset[i];
            double ai = data[n][1][i] - pixelVariance[i];
            bibiT += bi * bi;
            biaiT += bi * ai;
        }
        pixelGain[i] = biaiT / bibiT;
    }
    Statistics statsGain = new Statistics(pixelGain);
    Utils.log("Gain Mean = %s +/- %s", Utils.rounded(statsGain.getMean()), Utils.rounded(statsGain.getStandardDeviation()));
    // Histogram of offset, variance and gain
    int bins = Utils.getBinsSturges(pixelGain.length);
    WindowOrganiser wo = new WindowOrganiser();
    showHistogram("Offset", pixelOffset, bins, statsOffset, wo);
    showHistogram("Variance", pixelVariance, bins, statsVariance, wo);
    showHistogram("Gain", pixelGain, bins, statsGain, wo);
    wo.tile();
    // Save
    measuredStack = new ImageStack(size, size);
    measuredStack.addSlice("Offset", Utils.toFloat(pixelOffset));
    measuredStack.addSlice("Variance", Utils.toFloat(pixelVariance));
    measuredStack.addSlice("Gain", Utils.toFloat(pixelGain));
    IJ.save(new ImagePlus("PerPixel", measuredStack), new File(directory, "perPixel.tif").getPath());
    // Remove the status from the ij.io.ImageWriter class
    IJ.showStatus("");
    Utils.log("Analysis time = " + Utils.timeToString(System.currentTimeMillis() - start));
}
Also used : RollingArrayMoment(gdsc.core.math.RollingArrayMoment) ArrayMoment(gdsc.core.math.ArrayMoment) RollingArrayMoment(gdsc.core.math.RollingArrayMoment) SimpleArrayMoment(gdsc.core.math.SimpleArrayMoment) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) SimpleArrayMoment(gdsc.core.math.SimpleArrayMoment) TurboList(gdsc.core.utils.TurboList) ImageStack(ij.ImageStack) SeriesImageSource(gdsc.smlm.ij.SeriesImageSource) JLabel(javax.swing.JLabel) WindowOrganiser(ij.plugin.WindowOrganiser) Statistics(gdsc.core.utils.Statistics) ImagePlus(ij.ImagePlus) ExecutorService(java.util.concurrent.ExecutorService) Future(java.util.concurrent.Future) File(java.io.File)

Aggregations

SeriesImageSource (gdsc.smlm.ij.SeriesImageSource)2 ImagePlus (ij.ImagePlus)2 ArrayMoment (gdsc.core.math.ArrayMoment)1 RollingArrayMoment (gdsc.core.math.RollingArrayMoment)1 SimpleArrayMoment (gdsc.core.math.SimpleArrayMoment)1 Statistics (gdsc.core.utils.Statistics)1 TurboList (gdsc.core.utils.TurboList)1 IJImageSource (gdsc.smlm.ij.IJImageSource)1 SeriesOpener (gdsc.smlm.ij.utils.SeriesOpener)1 AggregatedImageSource (gdsc.smlm.results.AggregatedImageSource)1 ExtendedPeakResult (gdsc.smlm.results.ExtendedPeakResult)1 ImageSource (gdsc.smlm.results.ImageSource)1 InterlacedImageSource (gdsc.smlm.results.InterlacedImageSource)1 MemoryPeakResults (gdsc.smlm.results.MemoryPeakResults)1 PeakResult (gdsc.smlm.results.PeakResult)1 ImageStack (ij.ImageStack)1 YesNoCancelDialog (ij.gui.YesNoCancelDialog)1 WindowOrganiser (ij.plugin.WindowOrganiser)1 File (java.io.File)1 ArrayBlockingQueue (java.util.concurrent.ArrayBlockingQueue)1