Search in sources :

Example 31 with MemoryPeakResults

use of gdsc.smlm.results.MemoryPeakResults in project GDSC-SMLM by aherbert.

the class RenameResults method renameResults.

private int renameResults() {
    // Start with the original names for the mapping from old to new
    HashMap<String, String> mappedNames = new HashMap<String, String>();
    for (String name : MemoryPeakResults.getResultNames()) mappedNames.put(name, name);
    // Get the new names
    String[] lines = renameText.split("[;\n]");
    for (String line : lines) {
        String[] fields = line.split("[=]");
        if (fields.length == 2) {
            String oldName = fields[0].trim();
            String newName = fields[1].trim();
            if (!mappedNames.containsKey(oldName)) {
                IJ.error(TITLE, "An unknown original name has been specified: " + oldName);
                return 0;
            }
            if (oldName.equals(newName))
                // No update required
                continue;
            mappedNames.put(oldName, newName);
        }
    }
    // Check the new names are unique
    Set<String> newNames = new HashSet<String>();
    for (String newName : mappedNames.values()) {
        if (newNames.contains(newName)) {
            IJ.error(TITLE, "A duplicate new name has been specified: " + newName);
            return 0;
        }
        newNames.add(newName);
    }
    // Rename
    List<MemoryPeakResults> renamedResults = new LinkedList<MemoryPeakResults>();
    for (Entry<String, String> entry : mappedNames.entrySet()) {
        if (entry.getKey().equals(entry.getValue()))
            continue;
        // Remove from memory and store in a list
        MemoryPeakResults results = MemoryPeakResults.removeResults(entry.getKey());
        if (results != null) {
            results.setName(entry.getValue());
            renamedResults.add(results);
        }
    }
    // Add back to memory
    for (MemoryPeakResults results : renamedResults) MemoryPeakResults.addResults(results);
    return renamedResults.size();
}
Also used : HashMap(java.util.HashMap) MemoryPeakResults(gdsc.smlm.results.MemoryPeakResults) LinkedList(java.util.LinkedList) HashSet(java.util.HashSet)

Example 32 with MemoryPeakResults

use of gdsc.smlm.results.MemoryPeakResults in project GDSC-SMLM by aherbert.

the class PeakFit method addMemoryResults.

private void addMemoryResults(PeakResultsList resultsList, boolean force) {
    if (resultsSettings.resultsInMemory || force) {
        MemoryPeakResults results = new MemoryPeakResults();
        results.setSortAfterEnd(Prefs.getThreads() > 1);
        resultsList.addOutput(results);
        MemoryPeakResults.addResults(results);
    }
}
Also used : MemoryPeakResults(gdsc.smlm.results.MemoryPeakResults)

Example 33 with MemoryPeakResults

use of gdsc.smlm.results.MemoryPeakResults 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 34 with MemoryPeakResults

use of gdsc.smlm.results.MemoryPeakResults in project GDSC-SMLM by aherbert.

the class PulseActivationAnalysis method createOutput.

private PeakResultsList createOutput(int c) {
    PeakResultsList output = new PeakResultsList();
    output.copySettings(results);
    if (channels > 1)
        output.setName(results.getName() + " " + TITLE + " C" + c);
    else
        output.setName(results.getName() + " " + TITLE);
    // Store the set in memory
    MemoryPeakResults memoryResults = new MemoryPeakResults(this.results.size());
    output.addOutput(memoryResults);
    MemoryPeakResults.addResults(memoryResults);
    // Draw the super-resolution image
    Rectangle bounds = results.getBounds(true);
    addImageResults(output, results.getName(), bounds, results.getNmPerPixel(), results.getGain());
    output.begin();
    return output;
}
Also used : PeakResultsList(gdsc.smlm.results.PeakResultsList) Rectangle(java.awt.Rectangle) MemoryPeakResults(gdsc.smlm.results.MemoryPeakResults)

Example 35 with MemoryPeakResults

use of gdsc.smlm.results.MemoryPeakResults in project GDSC-SMLM by aherbert.

the class ResultsManagerTest method writeTSFMatchesRead.

private void writeTSFMatchesRead(int channels, int slices, int positions, int types) {
    String filename = createFile();
    FileOutputStream out = null;
    try {
        out = new FileOutputStream(filename);
    } catch (Exception e) {
        closeOutput(out);
        e.printStackTrace();
        Assert.fail(e.getMessage());
    }
    // Write the offsets used in the TSF format
    try {
        DataOutputStream dos = new DataOutputStream(out);
        dos.writeInt(0);
        dos.writeLong(0);
    } catch (IOException e) {
        closeOutput(out);
        e.printStackTrace();
        Assert.fail(e.getMessage());
    }
    // Generate random spots
    int size = 1000;
    Spot[] spots = new Spot[size];
    for (int i = 1; i <= size; i++) {
        Spot.Builder builder = Spot.newBuilder();
        builder.setChannel(1 + rand.nextInt(channels));
        builder.setSlice(1 + rand.nextInt(slices));
        builder.setPos(1 + rand.nextInt(positions));
        builder.setFluorophoreType(rand.nextInt(1, types));
        // This is a required field but is ignored when reading
        builder.setMolecule(i);
        builder.setCluster(rand.nextInt(10));
        builder.setFrame(rand.nextInt(1, 100));
        builder.setXPosition(rand.nextInt(50));
        builder.setYPosition(rand.nextInt(50));
        builder.setBackground(rand.next());
        builder.setIntensity(rand.next());
        builder.setX(rand.next());
        builder.setY(rand.next());
        builder.setWidth(TSFPeakResultsWriter.SD_TO_FWHM_FACTOR * rand.next());
        Spot spot = builder.build();
        spots[i - 1] = spot;
        try {
            spot.writeDelimitedTo(out);
        } catch (IOException e) {
            closeOutput(out);
            e.printStackTrace();
            Assert.fail(e.getMessage());
        }
    }
    // Write the header
    // Get the offset to the SpotList message
    long offset = 0;
    try {
        // The offset is the amount to skip forward after reading the int 
        // magic number (4 bytes) and long offset (8 bytes)
        //out.flush();
        offset = out.getChannel().position() - 12;
    } catch (IOException e) {
        closeOutput(out);
        e.printStackTrace();
        Assert.fail(e.getMessage());
    }
    // Record the SpotList message
    SpotList.Builder builder = SpotList.newBuilder();
    builder.setApplicationId(1);
    builder.setNrSpots(size);
    builder.setLocationUnits(LocationUnits.PIXELS);
    builder.setIntensityUnits(IntensityUnits.COUNTS);
    builder.setFitMode(FitMode.ONEAXIS);
    builder.setNrChannels(channels);
    builder.setNrSlices(slices);
    builder.setNrPos(positions);
    for (int type = 1; type <= types; type++) {
        FluorophoreType.Builder typeBuilder = FluorophoreType.newBuilder();
        typeBuilder.setId(type);
        typeBuilder.setDescription("Type " + type);
        typeBuilder.setIsFiducial(rand.next() < 0.5f);
        builder.addFluorophoreTypes(typeBuilder.build());
    }
    SpotList spotList = builder.build();
    try {
        spotList.writeDelimitedTo(out);
    } catch (IOException e) {
        e.printStackTrace();
        Assert.fail(e.getMessage());
    } finally {
        closeOutput(out);
    }
    // Write the offset to the SpotList message into the offset position
    RandomAccessFile f = null;
    try {
        f = new RandomAccessFile(new File(filename), "rw");
        f.seek(4);
        f.writeLong(offset);
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail(e.getMessage());
    } finally {
        if (f != null) {
            try {
                f.close();
            } catch (IOException e) {
            }
        }
    }
    // Read each combination 
    for (int channel = 1; channel <= channels; channel++) for (int slice = 1; slice <= slices; slice++) for (int position = 1; position <= positions; position++) for (int type = 1; type <= types; type++) {
        StringBuilder sb = new StringBuilder();
        sb.append(" channel=").append(channel);
        sb.append(" slice=").append(slice);
        sb.append(" position=").append(position);
        sb.append(" fluorophore_type=[").append(type).append(":Type ").append(type).append(":fiducial=").append(builder.getFluorophoreTypes(type - 1).getIsFiducial()).append(']');
        // This is needed to trick the Macro class into returning the options 
        // for the thread to the GenericDialog used in the ResultsManager
        Thread.currentThread().setName("Run$_");
        Macro.setOptions(sb.toString());
        ResultsManager.setInputFilename(filename);
        MemoryPeakResults in = ResultsManager.loadInputResults(ResultsManager.INPUT_FILE, false);
        checkEqual(spots, channel, slice, position, type, in);
    }
}
Also used : FluorophoreType(gdsc.smlm.tsf.TaggedSpotFile.FluorophoreType) Spot(gdsc.smlm.tsf.TaggedSpotFile.Spot) DataOutputStream(java.io.DataOutputStream) IOException(java.io.IOException) SpotList(gdsc.smlm.tsf.TaggedSpotFile.SpotList) IOException(java.io.IOException) RandomAccessFile(java.io.RandomAccessFile) FileOutputStream(java.io.FileOutputStream) MemoryPeakResults(gdsc.smlm.results.MemoryPeakResults) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File)

Aggregations

MemoryPeakResults (gdsc.smlm.results.MemoryPeakResults)86 PeakResult (gdsc.smlm.results.PeakResult)40 Rectangle (java.awt.Rectangle)16 ArrayList (java.util.ArrayList)13 ExtendedPeakResult (gdsc.smlm.results.ExtendedPeakResult)10 ImagePlus (ij.ImagePlus)10 StoredDataStatistics (gdsc.core.utils.StoredDataStatistics)8 Statistics (gdsc.core.utils.Statistics)7 IJImageSource (gdsc.smlm.ij.IJImageSource)7 Calibration (gdsc.smlm.results.Calibration)7 ExtendedGenericDialog (ij.gui.ExtendedGenericDialog)7 FractionClassificationResult (gdsc.core.match.FractionClassificationResult)6 IJImagePeakResults (gdsc.smlm.ij.results.IJImagePeakResults)6 Trace (gdsc.smlm.results.Trace)6 LinkedList (java.util.LinkedList)6 BasePoint (gdsc.core.match.BasePoint)5 ImageStack (ij.ImageStack)5 Plot2 (ij.gui.Plot2)5 Point (java.awt.Point)5 ClusterPoint (gdsc.core.clustering.ClusterPoint)4