Search in sources :

Example 1 with Calibration

use of uk.ac.sussex.gdsc.smlm.data.config.CalibrationProtos.Calibration in project GDSC-SMLM by aherbert.

the class SettingsManager method readFitEngineConfiguration.

/**
 * Read the FitEngineConfiguration from the settings file in the settings directory. This loads
 * the current Calibration, PSF and FitEngineSettings.
 *
 * @param flags the flags
 * @return the FitEngineConfiguration
 */
public static FitEngineConfiguration readFitEngineConfiguration(int flags) {
    final FitEngineSettings fitEngineSettings = readFitEngineSettings(flags);
    final Calibration calibration = readCalibration(flags);
    final PSF psf = readPsf(flags);
    return new FitEngineConfiguration(fitEngineSettings, calibration, psf);
}
Also used : PSF(uk.ac.sussex.gdsc.smlm.data.config.PSFProtos.PSF) FitEngineConfiguration(uk.ac.sussex.gdsc.smlm.engine.FitEngineConfiguration) Calibration(uk.ac.sussex.gdsc.smlm.data.config.CalibrationProtos.Calibration) FitEngineSettings(uk.ac.sussex.gdsc.smlm.data.config.FitProtos.FitEngineSettings)

Example 2 with Calibration

use of uk.ac.sussex.gdsc.smlm.data.config.CalibrationProtos.Calibration in project GDSC-SMLM by aherbert.

the class PulseActivationAnalysis method runSimulation.

private void runSimulation() {
    title += " Simulation";
    if (!showSimulationDialog()) {
        return;
    }
    final long start = System.currentTimeMillis();
    final UniformRandomProvider rng = getUniformRandomProvider();
    // Draw the molecule positions
    ImageJUtils.showStatus("Simulating molecules ...");
    final float[][][] molecules = new float[3][][];
    final MemoryPeakResults[] channelResults = new MemoryPeakResults[3];
    final Calibration calibration = CalibrationHelper.create(settings.nmPerPixel, 1, 100);
    final Rectangle bounds = new Rectangle(settings.size, settings.size);
    for (int c = 0; c < 3; c++) {
        molecules[c] = simulateMolecules(rng, c);
        // Create a dataset to store the activations
        final MemoryPeakResults r = new MemoryPeakResults();
        r.setCalibration(calibration);
        r.setBounds(bounds);
        r.setName(title + " C" + (c + 1));
        channelResults[c] = r;
    }
    // Simulate activation
    ImageJUtils.showStatus("Simulating activations ...");
    for (int c = 0; c < 3; c++) {
        simulateActivations(rng, molecules, c, channelResults);
    }
    // Combine
    ImageJUtils.showStatus("Producing simulation output ...");
    final MemoryPeakResults r = new MemoryPeakResults();
    r.setCalibration(calibration);
    r.setBounds((Rectangle) bounds.clone());
    r.setName(title);
    final ImageProcessor[] images = new ImageProcessor[3];
    for (int c = 0; c < 3; c++) {
        final PeakResult[] list = channelResults[c].toArray();
        r.addAll(list);
        // Draw the unmixed activations
        final ResultsImageSettings.Builder builder = ResultsImageSettings.newBuilder().setImageType(ResultsImageType.DRAW_LOCALISATIONS).setImageMode(ResultsImageMode.IMAGE_ADD).setWeighted(true).setEqualised(true).setImageSizeMode(ResultsImageSizeMode.IMAGE_SIZE).setImageSize(1024);
        final ImageJImagePeakResults image = ImagePeakResultsFactory.createPeakResultsImage(builder, title, bounds, settings.nmPerPixel);
        image.setCalibration(calibration);
        image.setLiveImage(false);
        image.setDisplayImage(false);
        image.begin();
        image.addAll(list);
        image.end();
        images[c] = image.getImagePlus().getProcessor();
    }
    displayComposite(images, title);
    // Add to memory. Set the composite dataset first.
    MemoryPeakResults.addResults(r);
    for (int c = 0; c < 3; c++) {
        MemoryPeakResults.addResults(channelResults[c]);
    }
    // TODO:
    // Show an image of what it looks like with no unmixing, i.e. colours allocated
    // from the frame
    ImageJUtils.showStatus("Simulation complete: " + TextUtils.millisToString(System.currentTimeMillis() - start));
}
Also used : Rectangle(java.awt.Rectangle) Calibration(uk.ac.sussex.gdsc.smlm.data.config.CalibrationProtos.Calibration) ResultsImageSettings(uk.ac.sussex.gdsc.smlm.data.config.ResultsProtos.ResultsImageSettings) ImageJImagePeakResults(uk.ac.sussex.gdsc.smlm.ij.results.ImageJImagePeakResults) IdPeakResult(uk.ac.sussex.gdsc.smlm.results.IdPeakResult) PeakResult(uk.ac.sussex.gdsc.smlm.results.PeakResult) ImageProcessor(ij.process.ImageProcessor) UniformRandomProvider(org.apache.commons.rng.UniformRandomProvider) SplittableUniformRandomProvider(uk.ac.sussex.gdsc.core.utils.rng.SplittableUniformRandomProvider) MemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults)

Example 3 with Calibration

use of uk.ac.sussex.gdsc.smlm.data.config.CalibrationProtos.Calibration in project GDSC-SMLM by aherbert.

the class PsfEstimator method setup.

@Override
public int setup(String arg, ImagePlus imp) {
    SmlmUsageTracker.recordPlugin(this.getClass(), arg);
    extraOptions = ImageJUtils.isExtraOptions();
    if (imp == null) {
        IJ.noImage();
        return DONE;
    }
    settings = SettingsManager.readPsfEstimatorSettings(0).toBuilder();
    // Reset
    if (IJ.controlKeyDown()) {
        config = new FitEngineConfiguration();
        final Calibration calibration = SettingsManager.readCalibration(0);
        config.getFitConfiguration().setCalibration(calibration);
        config.getFitConfiguration().setPsfType(PSFType.TWO_AXIS_AND_THETA_GAUSSIAN_2D);
    } else {
        config = SettingsManager.readFitEngineConfiguration(0);
    }
    final Roi roi = imp.getRoi();
    if (roi != null && roi.getType() != Roi.RECTANGLE) {
        IJ.error("Rectangular ROI required");
        return DONE;
    }
    return showDialog(imp);
}
Also used : FitEngineConfiguration(uk.ac.sussex.gdsc.smlm.engine.FitEngineConfiguration) Calibration(uk.ac.sussex.gdsc.smlm.data.config.CalibrationProtos.Calibration) Roi(ij.gui.Roi)

Example 4 with Calibration

use of uk.ac.sussex.gdsc.smlm.data.config.CalibrationProtos.Calibration in project GDSC-SMLM by aherbert.

the class LoadLocalisations method getFields.

private static boolean getFields(LoadLocalisationsSettings.Builder settings) {
    settings.getLocalisationsFilename();
    final ExtendedGenericDialog gd = new ExtendedGenericDialog(TITLE);
    gd.addMessage("Load delimited localisations");
    // Show a preview of the file in a text area
    final List<String> preview = loadLines(settings, 100);
    if (!preview.isEmpty()) {
        // Add a TextArea. This cannot add scroll bars after the constructor so we put up
        // with this. But we can use a monospaced font and size the text area nicely.
        gd.addTextAreas(preview.stream().collect(Collectors.joining("\n")), null, Math.min(10, preview.size()), Math.min(80, preview.stream().mapToInt(String::length).max().getAsInt()));
        final TextArea ta = gd.getTextArea1();
        final Font font = new Font(Font.MONOSPACED, Font.PLAIN, (int) (10 * Prefs.getGuiScale()));
        ta.setFont(font);
        ta.setEditable(false);
    }
    if (!settings.getHideFieldDatasetName()) {
        gd.addStringField("Dataset_name", settings.getName(), 30);
    }
    gd.addMessage("Calibration:");
    // Allow the full camera type top be captured
    final Calibration.Builder calibrationBuilder = settings.getCalibrationBuilder();
    final CalibrationWriter cw = new CalibrationWriter(calibrationBuilder);
    PeakFit.addCameraOptions(gd, 0, cw);
    // Only primitive support for other calibration
    gd.addNumericField("Pixel_size", cw.getNmPerPixel(), 3, 8, "nm");
    gd.addNumericField("Exposure_time", cw.getExposureTime(), 3, 8, "");
    // This is the unit for the exposure time (used to convert the exposure time to milliseconds).
    // Use the name as the list is a truncated list of the full enum.
    final TimeUnit t = calibrationBuilder.getTimeCalibration().getTimeUnit();
    gd.addChoice("Time_unit", TimeUnitLoader.getTimeUnits(), SettingsManager.getName(UnitHelper.getName(t), UnitHelper.getShortName(t)));
    gd.addMessage("Records:");
    gd.addNumericField("Header_lines", settings.getHeaderLines(), 0);
    gd.addStringField("Comment", settings.getComment());
    gd.addStringField("Delimiter", settings.getDelimiter());
    gd.addChoice("Distance_unit", SettingsManager.getDistanceUnitNames(), cw.getDistanceUnitValue());
    gd.addChoice("Intensity_unit", SettingsManager.getIntensityUnitNames(), cw.getIntensityUnitValue());
    gd.addMessage("Define the fields:");
    gd.addNumericField("Frame", settings.getFieldT(), 0);
    gd.addNumericField("ID", settings.getFieldId(), 0);
    gd.addNumericField("Category", settings.getFieldCategory(), 0);
    gd.addNumericField("X", settings.getFieldX(), 0);
    gd.addNumericField("Y", settings.getFieldY(), 0);
    gd.addNumericField("Z", settings.getFieldZ(), 0);
    gd.addNumericField("Intensity", settings.getFieldI(), 0);
    gd.addNumericField("Sx", settings.getFieldSx(), 0);
    gd.addNumericField("Sy", settings.getFieldSy(), 0);
    gd.addNumericField("Precision", settings.getFieldPrecision(), 0);
    gd.addChoice("Precision_method", SettingsManager.getPrecisionMethodNames(), cw.getPrecisionMethodValue());
    gd.addHelp(HelpUrls.getUrl("load-localisations"));
    gd.showDialog();
    if (gd.wasCanceled()) {
        return false;
    }
    if (!settings.getHideFieldDatasetName()) {
        settings.setName(getNextString(gd, settings.getName()));
    }
    cw.setCameraType(SettingsManager.getCameraTypeValues()[gd.getNextChoiceIndex()]);
    cw.setNmPerPixel(gd.getNextNumber());
    cw.setExposureTime(gd.getNextNumber());
    // The time units used a truncated list so look-up the value from the index
    calibrationBuilder.getTimeCalibrationBuilder().setTimeUnit(TimeUnitLoader.getTimeUnitValues()[gd.getNextChoiceIndex()]);
    settings.setHeaderLines((int) gd.getNextNumber());
    settings.setComment(gd.getNextString());
    settings.setDelimiter(getNextString(gd, settings.getDelimiter()));
    cw.setDistanceUnit(DistanceUnit.forNumber(gd.getNextChoiceIndex()));
    cw.setIntensityUnit(IntensityUnit.forNumber(gd.getNextChoiceIndex()));
    final int[] columns = new int[10];
    for (int i = 0; i < columns.length; i++) {
        columns[i] = (int) gd.getNextNumber();
    }
    int index = 0;
    settings.setFieldT(columns[index++]);
    settings.setFieldId(columns[index++]);
    settings.setFieldCategory(columns[index++]);
    settings.setFieldX(columns[index++]);
    settings.setFieldY(columns[index++]);
    settings.setFieldZ(columns[index++]);
    settings.setFieldI(columns[index++]);
    settings.setFieldSx(columns[index++]);
    settings.setFieldSy(columns[index++]);
    settings.setFieldPrecision(columns[index]);
    cw.setPrecisionMethod(PrecisionMethod.forNumber(gd.getNextChoiceIndex()));
    // Collect the camera calibration
    gd.collectOptions();
    // Validate after reading the dialog (so we store the last entered values)
    if (gd.invalidNumber()) {
        IJ.error(TITLE, "Invalid number in input fields");
        return false;
    }
    for (int i = 0; i < columns.length; i++) {
        if (columns[i] < 0) {
            continue;
        }
        for (int j = i + 1; j < columns.length; j++) {
            if (columns[j] < 0) {
                continue;
            }
            if (columns[i] == columns[j]) {
                IJ.error(TITLE, "Duplicate indicies: " + columns[i]);
                return false;
            }
        }
    }
    if (cw.getNmPerPixel() <= 0) {
        IJ.error(TITLE, "Require positive pixel pitch");
        return false;
    }
    if (cw.isCcdCamera()) {
        if (!cw.hasCountPerPhoton()) {
            IJ.error(TITLE, "Require positive count/photon for CCD camera type");
            return false;
        }
    } else {
    // Q.Validate other camera types?
    }
    if (settings.getFieldX() < 0 || settings.getFieldY() < 0) {
        IJ.error(TITLE, "Require valid X and Y indices");
        return false;
    }
    return true;
}
Also used : TextArea(java.awt.TextArea) CalibrationWriter(uk.ac.sussex.gdsc.smlm.data.config.CalibrationWriter) TimeUnit(uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.TimeUnit) ExtendedGenericDialog(uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog) Calibration(uk.ac.sussex.gdsc.smlm.data.config.CalibrationProtos.Calibration) Font(java.awt.Font)

Example 5 with Calibration

use of uk.ac.sussex.gdsc.smlm.data.config.CalibrationProtos.Calibration in project GDSC-SMLM by aherbert.

the class PeakResultsReader method getCalibration.

/**
 * Gets the calibration specified in the results header.
 *
 * @return The calibration specified in the results header.
 */
@SuppressWarnings("deprecation")
public Calibration getCalibration() {
    if (calibration == null) {
        getHeader();
        if (header != null && header.length() > 0) {
            if (format == FileFormat.RAPID_STORM) {
                calibration.setDistanceUnit(DistanceUnit.NM);
                // RapidSTORM has a resolution attribute in the header in units of px m^-1
                final Pattern pattern = Pattern.compile("resolution=\"([^ ]+) px m");
                final Matcher match = pattern.matcher(header);
                if (match.find()) {
                    try {
                        final float resolution = Float.parseFloat(match.group(1));
                        if (Double.isFinite(resolution) && resolution > 0) {
                            final double nmPerPixel = (float) (1e9 / resolution);
                            calibration = new CalibrationWriter();
                            calibration.setNmPerPixel(nmPerPixel);
                        }
                    } catch (final NumberFormatException ex) {
                    // Ignore
                    }
                }
            } else {
                final String calibrationString = getField("Calibration");
                if (calibrationString != null && calibrationString.length() > 0) {
                    // Older formats used XML
                    if (calibrationString.startsWith("<")) {
                        // Convert the XML back
                        try {
                            // Support package gdsc.smlm renamed to uk.ac.sussex.gdsc.smlm
                            final uk.ac.sussex.gdsc.smlm.results.Calibration cal = (uk.ac.sussex.gdsc.smlm.results.Calibration) XStreamUtils.fromXml(XStreamUtils.updateGdscPackageName(calibrationString));
                            cal.validate();
                            // Convert to a calibration helper
                            calibration = new CalibrationWriter();
                            if (cal.hasNmPerPixel()) {
                                calibration.setNmPerPixel(cal.getNmPerPixel());
                            }
                            if (cal.hasGain()) {
                                calibration.setCountPerPhoton(cal.getGain());
                            }
                            if (cal.hasExposureTime()) {
                                calibration.setExposureTime(cal.getExposureTime());
                            }
                            if (cal.hasReadNoise()) {
                                calibration.setReadNoise(cal.getReadNoise());
                            }
                            if (cal.hasBias()) {
                                calibration.setBias(cal.getBias());
                            }
                            if (cal.emCCD) {
                                calibration.setCameraType(CameraType.EMCCD);
                            }
                            if (cal.hasAmplification() && cal.hasGain()) {
                                calibration.setQuantumEfficiency(cal.getGain() / cal.getAmplification());
                            }
                            // Previous version were always in fixed units
                            calibration.setDistanceUnit(DistanceUnit.PIXEL);
                            calibration.setIntensityUnit(IntensityUnit.COUNT);
                            calibration.setAngleUnit(AngleUnit.DEGREE);
                            calibration.setTimeUnit(TimeUnit.FRAME);
                        } catch (final Exception ex) {
                            logger.log(Level.WARNING, "Unable to deserialise the Calibration settings", ex);
                        }
                    } else {
                        // Assume JSON format
                        try {
                            final Calibration.Builder calibrationBuilder = Calibration.newBuilder();
                            JsonFormat.parser().merge(calibrationString, calibrationBuilder);
                            calibration = new CalibrationWriter(calibrationBuilder);
                            // Old results did not save the time unit
                            if (calibration.getTimeUnitValue() == TimeUnit.TIME_UNIT_NA_VALUE) {
                                calibration.setTimeUnit(TimeUnit.FRAME);
                            }
                        } catch (final InvalidProtocolBufferException ex) {
                            logger.log(Level.WARNING, "Unable to deserialise the Calibration settings", ex);
                        }
                    }
                }
                if (format == FileFormat.MALK) {
                    if (calibration == null) {
                        calibration = new CalibrationWriter();
                    }
                    calibration.setDistanceUnit(DistanceUnit.NM);
                    calibration.setIntensityUnit(IntensityUnit.PHOTON);
                    calibration.setTimeUnit(TimeUnit.FRAME);
                }
            }
        }
        // Calibration is a smart object so we can create an empty one
        if (calibration == null) {
            calibration = new CalibrationWriter();
        }
    }
    return calibration.getCalibration();
}
Also used : Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) Calibration(uk.ac.sussex.gdsc.smlm.data.config.CalibrationProtos.Calibration) NoSuchElementException(java.util.NoSuchElementException) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) IOException(java.io.IOException) EOFException(java.io.EOFException) CalibrationWriter(uk.ac.sussex.gdsc.smlm.data.config.CalibrationWriter)

Aggregations

Calibration (uk.ac.sussex.gdsc.smlm.data.config.CalibrationProtos.Calibration)17 CalibrationWriter (uk.ac.sussex.gdsc.smlm.data.config.CalibrationWriter)7 Rectangle (java.awt.Rectangle)5 ExtendedGenericDialog (uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog)5 DistanceUnit (uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.DistanceUnit)5 CalibrationReader (uk.ac.sussex.gdsc.smlm.data.config.CalibrationReader)4 PSF (uk.ac.sussex.gdsc.smlm.data.config.PSFProtos.PSF)4 MemoryPeakResults (uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults)3 InvalidProtocolBufferException (com.google.protobuf.InvalidProtocolBufferException)2 Plot (ij.gui.Plot)2 Roi (ij.gui.Roi)2 LUT (ij.process.LUT)2 Color (java.awt.Color)2 EOFException (java.io.EOFException)2 IOException (java.io.IOException)2 NoSuchElementException (java.util.NoSuchElementException)2 Matcher (java.util.regex.Matcher)2 Pattern (java.util.regex.Pattern)2 Test (org.junit.jupiter.api.Test)2 WindowOrganiser (uk.ac.sussex.gdsc.core.ij.plugin.WindowOrganiser)2