Search in sources :

Example 1 with IJImageSource

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

the class CreateData method setNoise.

/**
 * Sets the noise in the results if missing.
 *
 * @param results the results
 * @param imp the imp
 */
private static void setNoise(MemoryPeakResults results, ImagePlus imp) {
    // Loaded results do not have noise
    if (results.hasNoise()) {
        return;
    }
    IJ.showStatus("Estimating noise ...");
    // Compute noise per frame
    final ImageStack stack = imp.getImageStack();
    final int width = stack.getWidth();
    final int height = stack.getHeight();
    final IJImageSource source = new IJImageSource(imp);
    final float[] noise = new float[source.getFrames() + 1];
    source.setReadHint(ReadHint.SEQUENTIAL);
    source.open();
    for (int slice = 1; slice < noise.length; slice++) {
        final float[] data = source.next();
        // Use the trimmed method as there may be a lot of spots in the frame
        noise[slice] = FitWorker.estimateNoise(data, width, height, NoiseEstimatorMethod.QUICK_RESIDUALS_LEAST_TRIMMED_OF_SQUARES);
    }
    // Statistics stats = Statistics.create(Arrays.copyOfRange(noise, 1, noise.length));
    // System.out.printf("Noise = %.3f +/- %.3f (%d)\n", stats.getMean(),
    // stats.getStandardDeviation(), stats.getN());
    // Convert noise units from counts to the result format
    final TypeConverter<IntensityUnit> c = results.getIntensityConverter(IntensityUnit.COUNT);
    for (int i = 0; i < noise.length; i++) {
        noise[i] = c.convertBack(noise[i]);
    }
    results.forEach((PeakResultProcedure) result -> {
        if (result.getFrame() < noise.length) {
            result.setNoise(noise[result.getFrame()]);
        }
    });
}
Also used : RandomUtils(uk.ac.sussex.gdsc.core.utils.rng.RandomUtils) LoadLocalisations(uk.ac.sussex.gdsc.smlm.ij.plugins.LoadLocalisations) Arrays(java.util.Arrays) PoissonSamplerUtils(uk.ac.sussex.gdsc.core.utils.rng.PoissonSamplerUtils) Molecule(uk.ac.sussex.gdsc.smlm.data.config.MoleculeProtos.Molecule) IdPeakResult(uk.ac.sussex.gdsc.smlm.results.IdPeakResult) ImageProcessor(ij.process.ImageProcessor) HistogramPlotBuilder(uk.ac.sussex.gdsc.core.ij.HistogramPlot.HistogramPlotBuilder) ConfigurationException(uk.ac.sussex.gdsc.smlm.data.config.ConfigurationException) AiryPsfModel(uk.ac.sussex.gdsc.smlm.model.AiryPsfModel) GaussianPsfModel(uk.ac.sussex.gdsc.smlm.model.GaussianPsfModel) MemoryUtils(uk.ac.sussex.gdsc.core.utils.MemoryUtils) PSFType(uk.ac.sussex.gdsc.smlm.data.config.PSFProtos.PSFType) HelpUrls(uk.ac.sussex.gdsc.smlm.ij.plugins.HelpUrls) ResultsManager(uk.ac.sussex.gdsc.smlm.ij.plugins.ResultsManager) GammaDistribution(org.apache.commons.math3.distribution.GammaDistribution) Future(java.util.concurrent.Future) Vector(java.util.Vector) MemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults) Map(java.util.Map) DensityManager(uk.ac.sussex.gdsc.core.clustering.DensityManager) UnicodeReader(uk.ac.sussex.gdsc.core.utils.UnicodeReader) RadialFalloffIllumination(uk.ac.sussex.gdsc.smlm.model.RadialFalloffIllumination) DistanceUnit(uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.DistanceUnit) RawResultProcedure(uk.ac.sussex.gdsc.smlm.results.procedures.RawResultProcedure) ConcurrencyUtils(uk.ac.sussex.gdsc.core.utils.concurrent.ConcurrencyUtils) TextUtils(uk.ac.sussex.gdsc.core.utils.TextUtils) Gaussian2DFunction(uk.ac.sussex.gdsc.smlm.function.gaussian.Gaussian2DFunction) Executors(java.util.concurrent.Executors) PeakFit(uk.ac.sussex.gdsc.smlm.ij.plugins.PeakFit) TIntHashSet(gnu.trove.set.hash.TIntHashSet) ImagePlus(ij.ImagePlus) LocalisationList(uk.ac.sussex.gdsc.smlm.ij.plugins.LoadLocalisations.LocalisationList) UniformDistribution(uk.ac.sussex.gdsc.smlm.model.UniformDistribution) ShortProcessor(ij.process.ShortProcessor) FileUtils(uk.ac.sussex.gdsc.core.utils.FileUtils) CameraModelFisherInformationAnalysis(uk.ac.sussex.gdsc.smlm.ij.plugins.CameraModelFisherInformationAnalysis) CalibrationProtosHelper(uk.ac.sussex.gdsc.smlm.data.config.CalibrationProtosHelper) PlugIn(ij.plugin.PlugIn) LocalisationModelSet(uk.ac.sussex.gdsc.smlm.model.LocalisationModelSet) AiryPattern(uk.ac.sussex.gdsc.smlm.model.AiryPattern) Prefs(ij.Prefs) FrameCounter(uk.ac.sussex.gdsc.smlm.results.count.FrameCounter) WindowManager(ij.WindowManager) PeakResult(uk.ac.sussex.gdsc.smlm.results.PeakResult) CreateDataSettings(uk.ac.sussex.gdsc.smlm.ij.settings.GUIProtos.CreateDataSettings) GridDistribution(uk.ac.sussex.gdsc.smlm.model.GridDistribution) ArrayList(java.util.ArrayList) Atom(uk.ac.sussex.gdsc.smlm.data.config.MoleculeProtos.Atom) AutoThreshold(uk.ac.sussex.gdsc.core.threshold.AutoThreshold) GenericDialog(ij.gui.GenericDialog) ImagePsfModel(uk.ac.sussex.gdsc.smlm.model.ImagePsfModel) PsfModel(uk.ac.sussex.gdsc.smlm.model.PsfModel) PeakResultProcedure(uk.ac.sussex.gdsc.smlm.results.procedures.PeakResultProcedure) PoissonGaussianFisherInformation(uk.ac.sussex.gdsc.smlm.function.PoissonGaussianFisherInformation) ImagePsfHelper(uk.ac.sussex.gdsc.smlm.ij.settings.ImagePsfHelper) UnivariateLikelihoodFisherInformationCalculator(uk.ac.sussex.gdsc.smlm.fitting.UnivariateLikelihoodFisherInformationCalculator) SpatialIllumination(uk.ac.sussex.gdsc.smlm.model.SpatialIllumination) PeakResultsReader(uk.ac.sussex.gdsc.smlm.results.PeakResultsReader) PsfCombiner(uk.ac.sussex.gdsc.smlm.ij.plugins.PsfCombiner) DiffusionType(uk.ac.sussex.gdsc.smlm.model.DiffusionType) Files(java.nio.file.Files) BufferedWriter(java.io.BufferedWriter) FitWorker(uk.ac.sussex.gdsc.smlm.engine.FitWorker) RandomGeneratorAdapter(uk.ac.sussex.gdsc.core.utils.rng.RandomGeneratorAdapter) AtomOrBuilder(uk.ac.sussex.gdsc.smlm.data.config.MoleculeProtos.AtomOrBuilder) IOException(java.io.IOException) SamplerUtils(uk.ac.sussex.gdsc.core.utils.rng.SamplerUtils) DiscreteUniformSampler(org.apache.commons.rng.sampling.distribution.DiscreteUniformSampler) File(java.io.File) SummaryStatistics(org.apache.commons.math3.stat.descriptive.SummaryStatistics) FloatProcessor(ij.process.FloatProcessor) BasePoissonFisherInformation(uk.ac.sussex.gdsc.smlm.function.BasePoissonFisherInformation) Paths(java.nio.file.Paths) AstigmatismZModel(uk.ac.sussex.gdsc.smlm.function.gaussian.AstigmatismZModel) TextFilePeakResults(uk.ac.sussex.gdsc.smlm.results.TextFilePeakResults) EmCcdCameraModel(uk.ac.sussex.gdsc.smlm.model.camera.EmCcdCameraModel) ImageStack(ij.ImageStack) PoissonSampler(org.apache.commons.rng.sampling.distribution.PoissonSampler) CameraModel(uk.ac.sussex.gdsc.smlm.model.camera.CameraModel) ExtendedPeakResult(uk.ac.sussex.gdsc.smlm.results.ExtendedPeakResult) PsfHelper(uk.ac.sussex.gdsc.smlm.data.config.PsfHelper) BufferedReader(java.io.BufferedReader) ImmutableMemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.ImmutableMemoryPeakResults) DoubleEquality(uk.ac.sussex.gdsc.core.utils.DoubleEquality) StandardResultProcedure(uk.ac.sussex.gdsc.smlm.results.procedures.StandardResultProcedure) SphericalDistribution(uk.ac.sussex.gdsc.smlm.model.SphericalDistribution) TIntArrayList(gnu.trove.list.array.TIntArrayList) GaussianFilter(uk.ac.sussex.gdsc.smlm.filters.GaussianFilter) TextWindow(ij.text.TextWindow) StandardValueProcedure(uk.ac.sussex.gdsc.smlm.function.StandardValueProcedure) ImagePSF(uk.ac.sussex.gdsc.smlm.data.config.PSFProtos.ImagePSF) Formatter(java.util.Formatter) FixedLifetimeImageModel(uk.ac.sussex.gdsc.smlm.model.FixedLifetimeImageModel) StoredDataStatistics(uk.ac.sussex.gdsc.core.utils.StoredDataStatistics) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) PeakResults(uk.ac.sussex.gdsc.smlm.results.PeakResults) DataException(uk.ac.sussex.gdsc.core.data.DataException) PsfCalculator(uk.ac.sussex.gdsc.smlm.ij.plugins.PsfCalculator) EmpiricalDistribution(org.apache.commons.math3.random.EmpiricalDistribution) MathUtils(uk.ac.sussex.gdsc.core.utils.MathUtils) BinomialDiscreteInverseCumulativeProbabilityFunction(uk.ac.sussex.gdsc.core.utils.rng.BinomialDiscreteInverseCumulativeProbabilityFunction) CalibrationWriter(uk.ac.sussex.gdsc.smlm.data.config.CalibrationWriter) Offset(uk.ac.sussex.gdsc.smlm.data.config.PSFProtos.Offset) TextFormat(com.google.protobuf.TextFormat) PsfProtosHelper(uk.ac.sussex.gdsc.smlm.data.config.PsfProtosHelper) SettingsManager(uk.ac.sussex.gdsc.smlm.ij.settings.SettingsManager) ItemEvent(java.awt.event.ItemEvent) CameraType(uk.ac.sussex.gdsc.smlm.data.config.CalibrationProtos.CameraType) SpatialDistribution(uk.ac.sussex.gdsc.smlm.model.SpatialDistribution) ExtendedGenericDialog(uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog) AstigmatismModelManager(uk.ac.sussex.gdsc.smlm.ij.plugins.AstigmatismModelManager) UniformRealDistribution(org.apache.commons.math3.distribution.UniformRealDistribution) MoleculeModel(uk.ac.sussex.gdsc.smlm.model.MoleculeModel) TIntIntHashMap(gnu.trove.map.hash.TIntIntHashMap) MarsagliaTsangGammaSampler(uk.ac.sussex.gdsc.core.utils.rng.MarsagliaTsangGammaSampler) WidthResultProcedure(uk.ac.sussex.gdsc.smlm.results.procedures.WidthResultProcedure) Gaussian2DPeakResultHelper(uk.ac.sussex.gdsc.smlm.results.Gaussian2DPeakResultHelper) List(java.util.List) FluorophoreSequenceModel(uk.ac.sussex.gdsc.smlm.model.FluorophoreSequenceModel) BirResultProcedure(uk.ac.sussex.gdsc.smlm.results.procedures.BirResultProcedure) Entry(java.util.Map.Entry) CompoundMoleculeModel(uk.ac.sussex.gdsc.smlm.model.CompoundMoleculeModel) RealDistribution(org.apache.commons.math3.distribution.RealDistribution) HoltzerAstigmatismZModel(uk.ac.sussex.gdsc.smlm.function.gaussian.HoltzerAstigmatismZModel) ImageModel(uk.ac.sussex.gdsc.smlm.model.ImageModel) MaskDistribution3D(uk.ac.sussex.gdsc.smlm.model.MaskDistribution3D) TypeConverter(uk.ac.sussex.gdsc.core.data.utils.TypeConverter) PrecisionResultProcedure(uk.ac.sussex.gdsc.smlm.results.procedures.PrecisionResultProcedure) Rectangle(java.awt.Rectangle) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) PSF(uk.ac.sussex.gdsc.smlm.data.config.PSFProtos.PSF) WindowOrganiser(uk.ac.sussex.gdsc.core.ij.plugin.WindowOrganiser) IntensityUnit(uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.IntensityUnit) Mixture(uk.ac.sussex.gdsc.smlm.data.config.MoleculeProtos.Mixture) AtomicReference(java.util.concurrent.atomic.AtomicReference) SobolSequenceGenerator(org.apache.commons.math3.random.SobolSequenceGenerator) MaskDistribution(uk.ac.sussex.gdsc.smlm.model.MaskDistribution) OptionListener(uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog.OptionListener) OpenDialog(ij.io.OpenDialog) ParameterUtils(uk.ac.sussex.gdsc.smlm.ij.plugins.ParameterUtils) IJImageSource(uk.ac.sussex.gdsc.smlm.ij.IJImageSource) NoiseEstimatorMethod(uk.ac.sussex.gdsc.smlm.data.config.FitProtos.NoiseEstimatorMethod) ReadHint(uk.ac.sussex.gdsc.smlm.results.ImageSource.ReadHint) ExponentialDistribution(org.apache.commons.math3.distribution.ExponentialDistribution) FisherInformationMatrix(uk.ac.sussex.gdsc.smlm.fitting.FisherInformationMatrix) UnitHelper(uk.ac.sussex.gdsc.smlm.data.config.UnitHelper) LinkedList(java.util.LinkedList) CcdCameraModel(uk.ac.sussex.gdsc.smlm.model.camera.CcdCameraModel) FileSaver(ij.io.FileSaver) Statistics(uk.ac.sussex.gdsc.core.utils.Statistics) ExecutorService(java.util.concurrent.ExecutorService) CreateDataSettingsHelper(uk.ac.sussex.gdsc.smlm.ij.settings.CreateDataSettingsHelper) TFloatArrayList(gnu.trove.list.array.TFloatArrayList) FunctionHelper(uk.ac.sussex.gdsc.smlm.function.FunctionHelper) UniformRandomProvider(org.apache.commons.rng.UniformRandomProvider) PoissonSamplerCache(org.apache.commons.rng.sampling.distribution.PoissonSamplerCache) AstigmatismModel(uk.ac.sussex.gdsc.smlm.data.config.PSFProtos.AstigmatismModel) ConversionException(uk.ac.sussex.gdsc.core.data.utils.ConversionException) SplitMix64(org.apache.commons.rng.core.source64.SplitMix64) Checkbox(java.awt.Checkbox) ActivationEnergyImageModel(uk.ac.sussex.gdsc.smlm.model.ActivationEnergyImageModel) LoadLocalisationsSettings(uk.ac.sussex.gdsc.smlm.ij.settings.GUIProtos.LoadLocalisationsSettings) FileInputStream(java.io.FileInputStream) Ticker(uk.ac.sussex.gdsc.core.logging.Ticker) PsfModelGradient1Function(uk.ac.sussex.gdsc.smlm.model.PsfModelGradient1Function) InterpolatedPoissonFisherInformation(uk.ac.sussex.gdsc.smlm.function.InterpolatedPoissonFisherInformation) Consumer(java.util.function.Consumer) CameraModelManager(uk.ac.sussex.gdsc.smlm.ij.plugins.CameraModelManager) LocalisationModel(uk.ac.sussex.gdsc.smlm.model.LocalisationModel) ImageJUtils(uk.ac.sussex.gdsc.core.ij.ImageJUtils) UniformIllumination(uk.ac.sussex.gdsc.smlm.model.UniformIllumination) SynchronizedPeakResults(uk.ac.sussex.gdsc.smlm.results.SynchronizedPeakResults) IJ(ij.IJ) NullArgumentException(org.apache.commons.math3.exception.NullArgumentException) SmlmUsageTracker(uk.ac.sussex.gdsc.smlm.ij.plugins.SmlmUsageTracker) InverseTransformDiscreteSampler(org.apache.commons.rng.sampling.distribution.InverseTransformDiscreteSampler) Comparator(java.util.Comparator) Collections(java.util.Collections) NormalizedGaussianSampler(org.apache.commons.rng.sampling.distribution.NormalizedGaussianSampler) LocalList(uk.ac.sussex.gdsc.core.utils.LocalList) UniformRandomProviders(uk.ac.sussex.gdsc.core.utils.rng.UniformRandomProviders) IJImageSource(uk.ac.sussex.gdsc.smlm.ij.IJImageSource) ImageStack(ij.ImageStack) IntensityUnit(uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.IntensityUnit) ReadHint(uk.ac.sussex.gdsc.smlm.results.ImageSource.ReadHint)

Example 2 with IJImageSource

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

the class CreateData method loadBenchmarkData.

/**
 * Load benchmark data using an open image and a XYZ text file.
 */
private void loadBenchmarkData() {
    if (!showLoadDialog()) {
        // resetMemory();
        return;
    }
    // Load the image
    final ImagePlus imp = WindowManager.getImage(benchmarkImage);
    if (imp == null) {
        IJ.error(TITLE, "No benchmark image: " + benchmarkImage);
        // resetMemory();
        return;
    }
    // Load the results
    final MemoryPeakResults results = getSimulationResults();
    if (results == null) {
        IJ.error(TITLE, "No benchmark results: " + benchmarkResultsName);
        // resetMemory();
        return;
    }
    results.setName(imp.getTitle() + " (Results)");
    results.setBounds(new Rectangle(0, 0, imp.getWidth(), imp.getHeight()));
    final IJImageSource imageSource = new IJImageSource(imp);
    results.setSource(imageSource);
    // Load the settings as these are used in the dialog
    settings = SettingsManager.readCreateDataSettings(0).toBuilder();
    simulationParameters = showSimulationParametersDialog(imp, results);
    if (simulationParameters != null) {
        // Convert data to allow analysis as if a Gaussian2D PSF
        final boolean isGaussian2D = PsfHelper.isGaussian2D(results.getPsf());
        if (isGaussian2D) {
            Gaussian2DPeakResultHelper.addMeanIntensity(results.getPsf(), results);
        } else if (simulationParameters.sd > 0) {
            final TypeConverter<DistanceUnit> dc = results.getDistanceConverter(DistanceUnit.NM);
            final PSF.Builder psf = PsfProtosHelper.getDefaultPsf(PSFType.ONE_AXIS_GAUSSIAN_2D).toBuilder();
            psf.getParametersBuilder(0).setValue(dc.convertBack(simulationParameters.sd));
            results.setPsf(psf.build());
            // Update all the results. This assumes the results do not have data for a custom PSF,
            // i.e. the parameters only have [t,i,x,y,z]
            final LocalList<PeakResult> newResults = new LocalList<>(results.size());
            final float sd = (float) dc.convertBack(simulationParameters.sd);
            final double meanFactor = Gaussian2DPeakResultHelper.getMeanSignalUsingP05(1, sd, sd);
            results.forEach((PeakResultProcedure) r -> {
                final PeakResult peak = r.resize(PeakResult.STANDARD_PARAMETERS + 1);
                peak.setMeanIntensity((float) (peak.getIntensity() * meanFactor));
                peak.setParameter(PeakResult.STANDARD_PARAMETERS, sd);
                newResults.add(peak);
            });
            results.begin();
            results.addAll(newResults);
            results.end();
        }
        setBackground(results);
        setNoise(results, imp);
        setBenchmarkResults(imp, results);
        IJ.showStatus("Loaded " + TextUtils.pleural(results.size(), "result"));
    } else {
        resetMemory();
    }
}
Also used : TypeConverter(uk.ac.sussex.gdsc.core.data.utils.TypeConverter) IJImageSource(uk.ac.sussex.gdsc.smlm.ij.IJImageSource) LocalList(uk.ac.sussex.gdsc.core.utils.LocalList) PeakResultProcedure(uk.ac.sussex.gdsc.smlm.results.procedures.PeakResultProcedure) HistogramPlotBuilder(uk.ac.sussex.gdsc.core.ij.HistogramPlot.HistogramPlotBuilder) AtomOrBuilder(uk.ac.sussex.gdsc.smlm.data.config.MoleculeProtos.AtomOrBuilder) Rectangle(java.awt.Rectangle) MemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults) ImmutableMemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.ImmutableMemoryPeakResults) ImagePlus(ij.ImagePlus) IdPeakResult(uk.ac.sussex.gdsc.smlm.results.IdPeakResult) PeakResult(uk.ac.sussex.gdsc.smlm.results.PeakResult) ExtendedPeakResult(uk.ac.sussex.gdsc.smlm.results.ExtendedPeakResult)

Example 3 with IJImageSource

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

the class CreateData method showSimulationParametersDialog.

private SimulationParameters showSimulationParametersDialog(ImagePlus imp, MemoryPeakResults results) {
    final int molecules = results.size();
    // Get the missing parameters from the user
    boolean fullSimulation = false;
    double sd = -1;
    if (!results.convertToPreferredUnits()) {
        IJ.error(TITLE, String.format("Results should be in the preferred units (%s,%s)", UnitHelper.getName(MemoryPeakResults.PREFERRED_DISTANCE_UNIT), UnitHelper.getName(MemoryPeakResults.PREFERRED_INTENSITY_UNIT)));
        return null;
    }
    // Get these from the data
    final RawResultProcedure sp = new RawResultProcedure(results);
    sp.getBixyz();
    final float[] signal = sp.intensity;
    float[] limits = MathUtils.limits(signal);
    final double minSignal = limits[0];
    final double maxSignal = limits[1];
    final double signalPerFrame = MathUtils.sum(signal) / molecules;
    final float[] depths = sp.z;
    limits = MathUtils.limits(depths);
    float depth = Math.max(Math.abs(limits[0]), Math.abs(limits[1]));
    final boolean fixedDepth = Double.compare(limits[0], limits[1]) == 0;
    final CalibrationWriter cal = results.getCalibrationWriter();
    final String iUnits = " " + UnitHelper.getName(cal.getIntensityUnit());
    final String zUnits = " " + UnitHelper.getName(cal.getDistanceUnit());
    // Get this from the user
    double background = -1;
    // Use last simulation parameters for missing settings.
    // This is good if we are re-running the plugin to load data.
    Rectangle lastCameraBounds = null;
    if (simulationParameters != null && simulationParameters.isLoaded()) {
        fullSimulation = simulationParameters.fullSimulation;
        sd = simulationParameters.sd;
        background = simulationParameters.background;
        if (!cal.hasBias()) {
            cal.setBias(simulationParameters.bias);
        }
        if (!cal.hasCountPerPhoton()) {
            cal.setCountPerPhoton(simulationParameters.gain);
        }
        if (!cal.hasQuantumEfficiency()) {
            cal.setQuantumEfficiency(simulationParameters.qe);
        }
        if (!cal.hasReadNoise()) {
            cal.setReadNoise(simulationParameters.readNoise);
        }
        if (!cal.hasCameraType()) {
            cal.setCameraType(simulationParameters.cameraType);
        }
        if (!cal.hasNmPerPixel()) {
            cal.setNmPerPixel(simulationParameters.pixelPitch);
        }
        if (!cal.hasCameraModelName()) {
            cal.setCameraModelName(simulationParameters.cameraModelName);
        }
        lastCameraBounds = simulationParameters.cameraBounds;
    }
    // Show a dialog to confirm settings
    final ExtendedGenericDialog gd = new ExtendedGenericDialog(TITLE);
    final StringBuilder sb = new StringBuilder();
    sb.append("Results contain ").append(TextUtils.pleural(molecules, "molecule")).append('\n');
    sb.append("Min signal = ").append(MathUtils.rounded(minSignal)).append(iUnits).append('\n');
    sb.append("Max signal = ").append(MathUtils.rounded(maxSignal)).append(iUnits).append('\n');
    sb.append("Av signal = ").append(MathUtils.rounded(signalPerFrame)).append(iUnits).append('\n');
    if (fixedDepth) {
        sb.append("Fixed depth = ").append(MathUtils.rounded(depth)).append(zUnits).append('\n');
    }
    gd.addMessage(sb.toString());
    gd.addCheckbox("Flourophore_simulation", fullSimulation);
    gd.addNumericField("Gaussian_SD", sd, 3, 8, "nm");
    gd.addNumericField("Pixel_pitch", cal.getNmPerPixel(), 3, 8, "nm");
    gd.addNumericField("Background", background, 3, 8, "photon");
    // Camera type does not need the full simulation settings. Plus the units are different
    // so just re-implement.
    gd.addChoice("Camera_type", SettingsManager.getCameraTypeNames(), CalibrationProtosHelper.getName(cal.getCameraType()), new OptionListener<Integer>() {

        @Override
        public boolean collectOptions(Integer field) {
            cal.setCameraType(SettingsManager.getCameraTypeValues()[field]);
            return collectOptions(false);
        }

        @Override
        public boolean collectOptions() {
            return collectOptions(true);
        }

        private boolean collectOptions(boolean silent) {
            final CameraType cameraType = cal.getCameraType();
            final boolean isCcd = CalibrationProtosHelper.isCcdCameraType(cameraType);
            final ExtendedGenericDialog egd = new ExtendedGenericDialog(TITLE, null);
            if (isCcd) {
                egd.addNumericField("Total_gain", cal.getCountPerPhoton(), 3, 8, "count/photon");
                egd.addNumericField("Quantum_efficiency", cal.getQuantumEfficiency(), 3, 8, "e-/photon");
                egd.addNumericField("Read_noise", cal.getReadNoise(), 3, 8, "count");
                egd.addNumericField("Bias", cal.getBias(), 3, 8, "count");
            } else if (cameraType == CameraType.SCMOS) {
                final String[] models = CameraModelManager.listCameraModels(true);
                egd.addChoice("Camera_model_name", models, cal.getCameraModelName());
                egd.addNumericField("Quantum_efficiency", cal.getQuantumEfficiency(), 2, 6, "electron/photon");
            } else {
                IJ.error("Unsupported camera type " + CalibrationProtosHelper.getName(cameraType));
                return false;
            }
            egd.setSilent(silent);
            egd.showDialog(true, gd);
            if (egd.wasCanceled()) {
                return false;
            }
            if (isCcd) {
                cal.setCountPerPhoton(egd.getNextNumber());
                cal.setQuantumEfficiency(egd.getNextNumber());
                cal.setReadNoise(egd.getNextNumber());
                cal.setBias(egd.getNextNumber());
            } else if (cameraType == CameraType.SCMOS) {
                cal.setCameraModelName(egd.getNextChoice());
                cal.setQuantumEfficiency(Math.abs(egd.getNextNumber()));
            }
            return true;
        }
    });
    if (!fixedDepth) {
        gd.addNumericField("Depth", depth, 3, 8, "pixel");
    }
    gd.addHelp(HelpUrls.getUrl("load-benchmark-data"));
    gd.showDialog();
    if (gd.wasCanceled()) {
        return null;
    }
    fullSimulation = gd.getNextBoolean();
    sd = gd.getNextNumber();
    cal.setNmPerPixel(gd.getNextNumber());
    background = gd.getNextNumber();
    cal.setCameraType(SettingsManager.getCameraTypeValues()[gd.getNextChoiceIndex()]);
    float myDepth = depth;
    if (!fixedDepth) {
        myDepth = (float) gd.getNextNumber();
        if (myDepth < depth) {
            IJ.error(TITLE, String.format("Input depth is smaller than the depth guessed from the data: %f < %f", myDepth, depth));
            return null;
        }
        depth = myDepth;
    }
    gd.collectOptions();
    // Validate settings
    Rectangle modelBounds = null;
    try {
        ParameterUtils.isAboveZero("Gaussian SD", sd);
        ParameterUtils.isAboveZero("Pixel pitch", cal.getNmPerPixel());
        ParameterUtils.isPositive("Background", background);
        ParameterUtils.isAboveZero("Quantum efficiency", cal.getQuantumEfficiency());
        ParameterUtils.isEqualOrBelow("Quantum efficiency", cal.getQuantumEfficiency(), 1);
        if (cal.isCcdCamera()) {
            ParameterUtils.isAboveZero("Total gain", cal.getCountPerPhoton());
            ParameterUtils.isPositive("Read noise", cal.getReadNoise());
            ParameterUtils.isPositive("Bias", cal.getBias());
        } else if (cal.isScmos()) {
            // Load the model
            cameraModel = CameraModelManager.load(cal.getCameraModelName());
            if (cameraModel == null) {
                IJ.error(TITLE, "Unknown camera model for name: " + cal.getCameraModelName());
                return null;
            }
            int ox = 0;
            int oy = 0;
            if (lastCameraBounds != null) {
                ox = lastCameraBounds.x;
                oy = lastCameraBounds.y;
            }
            cameraModel = PeakFit.cropCameraModel(cameraModel, new Rectangle(ox, oy, imp.getWidth(), imp.getHeight()), null, false);
            modelBounds = cameraModel.getBounds();
            final IJImageSource imageSource = (IJImageSource) results.getSource();
            imageSource.setOrigin(modelBounds.x, modelBounds.y);
            cal.clearGlobalCameraSettings();
        } else {
            IJ.error(TITLE, "Unknown camera type: " + cal.getCameraType());
            return null;
        }
    } catch (final IllegalArgumentException ex) {
        IJ.error(TITLE, ex.getMessage());
        return null;
    }
    // Store calibration
    results.setCalibration(cal.getCalibration());
    final double a = cal.getNmPerPixel();
    final double bias = cal.getBias();
    final double gain = cal.getCountPerPhoton();
    final double readNoise = cal.getReadNoise();
    final double qe = cal.getQuantumEfficiency();
    // Note: The calibration will throw an exception if the converter cannot be created.
    // This is OK as the data will be invalid.
    // Convert +/- depth to total depth in nm
    depth = cal.getDistanceConverter(DistanceUnit.NM).convert(depth * 2);
    // Compute total background variance in photons
    final double backgroundVariance = background;
    // Do not add EM-CCD noise factor. The Mortensen formula also includes this factor
    // so this is "double-counting" the EM-CCD.
    // if (emCCD)
    // backgroundVariance *= 2;
    // Read noise is in ADUs. Convert to Photons to get contribution to background variance
    final double readNoiseInPhotons = readNoise / gain;
    // Get the expected value at each pixel in photons. Assuming a Poisson distribution this
    // is equal to the total variance at the pixel.
    final double b2 = backgroundVariance + readNoiseInPhotons * readNoiseInPhotons;
    // Convert values to photons
    final TypeConverter<IntensityUnit> ic = cal.getIntensityConverter(IntensityUnit.PHOTON);
    final SimulationParameters p = new SimulationParameters(molecules, fullSimulation, sd, a, ic.convert(minSignal), ic.convert(maxSignal), ic.convert(signalPerFrame), depth, fixedDepth, bias, gain, qe, readNoise, cal.getCameraType(), cal.getCameraModelName(), modelBounds, background, b2, createPsf(sd / a));
    p.loaded = true;
    return p;
}
Also used : RawResultProcedure(uk.ac.sussex.gdsc.smlm.results.procedures.RawResultProcedure) Rectangle(java.awt.Rectangle) ExtendedGenericDialog(uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog) ReadHint(uk.ac.sussex.gdsc.smlm.results.ImageSource.ReadHint) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) IJImageSource(uk.ac.sussex.gdsc.smlm.ij.IJImageSource) CalibrationWriter(uk.ac.sussex.gdsc.smlm.data.config.CalibrationWriter) IntensityUnit(uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.IntensityUnit) CameraType(uk.ac.sussex.gdsc.smlm.data.config.CalibrationProtos.CameraType)

Example 4 with IJImageSource

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

the class PeakResultTableModelFrame method doSourceShowImage.

private void doSourceShowImage() {
    final PeakResultTableModel model = getModel();
    if (model == null) {
        return;
    }
    final ImageSource source = model.getSource();
    if (source == null) {
        return;
    }
    // Check if already open
    final ImagePlus imp = WindowManager.getImage(source.getName());
    if (imp != null) {
        imp.getWindow().toFront();
        return;
    }
    // Check if an ImageJ image source
    if (source instanceof IJImageSource) {
        final IJImageSource imageSource = (IJImageSource) source;
        final String path = imageSource.getPath();
        if (path != null && new File(path).exists()) {
            IJ.showStatus("Opening image ...");
            IJ.open(path);
            IJ.showStatus("");
        } else {
            IJ.log("Cannot find the image source: " + path);
        }
        return;
    }
    // Open a SeriesImageSource.
    if (source instanceof SeriesImageSource) {
        final SeriesImageSource imageSource = (SeriesImageSource) source;
        // No memory buffer
        imageSource.setBufferLimit(0);
        imageSource.setReadHint(ReadHint.NONSEQUENTIAL);
        if (!source.open()) {
            IJ.log("Cannot open the series image source");
            return;
        }
        new TiffSeriesVirtualStack(imageSource).show();
    }
}
Also used : IJImageSource(uk.ac.sussex.gdsc.smlm.ij.IJImageSource) SeriesImageSource(uk.ac.sussex.gdsc.smlm.ij.SeriesImageSource) ImageSource(uk.ac.sussex.gdsc.smlm.results.ImageSource) IJImageSource(uk.ac.sussex.gdsc.smlm.ij.IJImageSource) SeriesImageSource(uk.ac.sussex.gdsc.smlm.ij.SeriesImageSource) ImagePlus(ij.ImagePlus) File(java.io.File) TiffSeriesVirtualStack(uk.ac.sussex.gdsc.smlm.ij.plugins.TiffSeriesViewer.TiffSeriesVirtualStack)

Example 5 with IJImageSource

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

the class PeakFit method addSingleFrameOverlay.

private void addSingleFrameOverlay() {
    // If a single frame was processed add the peaks as an overlay if they are in memory
    ImagePlus localImp = this.imp;
    if (fitMaxima && singleFrame > 0 && source instanceof IJImageSource) {
        final String title = source.getName();
        localImp = WindowManager.getImage(title);
    }
    if (singleFrame > 0 && localImp != null) {
        MemoryPeakResults memoryResults = null;
        for (final PeakResults r : this.results.toArray()) {
            if (r instanceof MemoryPeakResults) {
                memoryResults = (MemoryPeakResults) r;
                break;
            }
        }
        if (memoryResults == null || memoryResults.size() == 0) {
            return;
        }
        final ExtendedGenericDialog gd = new ExtendedGenericDialog(TITLE);
        gd.enableYesNoCancel();
        gd.hideCancelButton();
        gd.addMessage("Add the fitted localisations as an overlay?");
        gd.showDialog();
        if (!gd.wasOKed()) {
            return;
        }
        final LUT lut = LutHelper.createLut(LutColour.ICE);
        final Overlay o = new Overlay();
        final int size = memoryResults.size();
        final Counter j = new Counter(size);
        final ImagePlus finalImp = localImp;
        memoryResults.forEach(DistanceUnit.PIXEL, (XyResultProcedure) (x, y) -> {
            final PointRoi roi = new OffsetPointRoi(x, y);
            final Color c = LutHelper.getColour(lut, j.decrementAndGet(), size);
            roi.setStrokeColor(c);
            roi.setFillColor(c);
            if (finalImp.getStackSize() > 1) {
                roi.setPosition(singleFrame);
            }
            o.add(roi);
        });
        localImp.setOverlay(o);
        localImp.getWindow().toFront();
    }
}
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) OffsetPointRoi(uk.ac.sussex.gdsc.core.ij.gui.OffsetPointRoi) Color(java.awt.Color) SystemColor(java.awt.SystemColor) LUT(ij.process.LUT) ExtendedGenericDialog(uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog) ImagePlus(ij.ImagePlus) IJImageSource(uk.ac.sussex.gdsc.smlm.ij.IJImageSource) FrameCounter(uk.ac.sussex.gdsc.smlm.results.count.FrameCounter) Counter(uk.ac.sussex.gdsc.smlm.results.count.Counter) MemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults) FilePeakResults(uk.ac.sussex.gdsc.smlm.results.FilePeakResults) ImageJTablePeakResults(uk.ac.sussex.gdsc.smlm.ij.results.ImageJTablePeakResults) ImageJImagePeakResults(uk.ac.sussex.gdsc.smlm.ij.results.ImageJImagePeakResults) PeakResults(uk.ac.sussex.gdsc.smlm.results.PeakResults) MemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults) Overlay(ij.gui.Overlay) PointRoi(ij.gui.PointRoi) OffsetPointRoi(uk.ac.sussex.gdsc.core.ij.gui.OffsetPointRoi)

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