Search in sources :

Example 1 with CompoundMoleculeModel

use of uk.ac.sussex.gdsc.smlm.model.CompoundMoleculeModel in project GDSC-SMLM by aherbert.

the class CreateData method run.

@Override
public void run(String arg) {
    SmlmUsageTracker.recordPlugin(this.getClass(), arg);
    extraOptions = ImageJUtils.isExtraOptions();
    simpleMode = (arg != null && arg.contains("simple"));
    benchmarkMode = (arg != null && arg.contains("benchmark"));
    spotMode = (arg != null && arg.contains("spot"));
    trackMode = (arg != null && arg.contains("track"));
    if ("load".equals(arg)) {
        loadBenchmarkData();
        return;
    }
    // Each localisation set is a collection of localisations that represent all localisations
    // with the same ID that are on in the same image time frame (Note: the simulation
    // can create many localisations per fluorophore per time frame which is useful when
    // modelling moving particles)
    List<LocalisationModelSet> localisationSets = null;
    // Each fluorophore contains the on and off times when light was emitted
    List<? extends FluorophoreSequenceModel> fluorophores = null;
    if (simpleMode || benchmarkMode || spotMode) {
        if (!showSimpleDialog()) {
            return;
        }
        resetMemory();
        // 1 second frames
        settings.setExposureTime(1000);
        areaInUm = settings.getSize() * settings.getPixelPitch() * settings.getSize() * settings.getPixelPitch() / 1e6;
        // Number of spots per frame
        int count = 0;
        int[] nextN = null;
        SpatialDistribution dist;
        if (benchmarkMode) {
            // --------------------
            // BENCHMARK SIMULATION
            // --------------------
            // Draw the same point on the image repeatedly
            count = 1;
            dist = createFixedDistribution();
            try {
                reportAndSaveFittingLimits(dist);
            } catch (final Exception ex) {
                // This will be from the computation of the CRLB
                IJ.error(TITLE, ex.getMessage());
                return;
            }
        } else if (spotMode) {
            // ---------------
            // SPOT SIMULATION
            // ---------------
            // The spot simulation draws 0 or 1 random point per frame.
            // Ensure we have 50% of the frames with a spot.
            nextN = new int[settings.getParticles() * 2];
            Arrays.fill(nextN, 0, settings.getParticles(), 1);
            RandomUtils.shuffle(nextN, UniformRandomProviders.create());
            // Only put spots in the central part of the image
            final double border = settings.getSize() / 4.0;
            dist = createUniformDistribution(border);
        } else {
            // -----------------
            // SIMPLE SIMULATION
            // -----------------
            // The simple simulation draws n random points per frame to achieve a specified density.
            // No points will appear in multiple frames.
            // Each point has a random number of photons sampled from a range.
            // We can optionally use a mask. Create his first as it updates the areaInUm
            dist = createDistribution();
            // Randomly sample (i.e. not uniform density in all frames)
            if (settings.getSamplePerFrame()) {
                final double mean = areaInUm * settings.getDensity();
                ImageJUtils.log("Mean samples = %f", mean);
                if (mean < 0.5) {
                    final GenericDialog gd = new GenericDialog(TITLE);
                    gd.addMessage("The mean samples per frame is low: " + MathUtils.rounded(mean) + "\n \nContinue?");
                    gd.enableYesNoCancel();
                    gd.hideCancelButton();
                    gd.showDialog();
                    if (!gd.wasOKed()) {
                        return;
                    }
                }
                final PoissonSampler poisson = new PoissonSampler(createRandomGenerator(), mean);
                final StoredDataStatistics samples = new StoredDataStatistics(settings.getParticles());
                while (samples.getSum() < settings.getParticles()) {
                    samples.add(poisson.sample());
                }
                nextN = new int[samples.getN()];
                for (int i = 0; i < nextN.length; i++) {
                    nextN[i] = (int) samples.getValue(i);
                }
            } else {
                // Use the density to get the number per frame
                count = (int) Math.max(1, Math.round(areaInUm * settings.getDensity()));
            }
        }
        UniformRandomProvider rng = null;
        localisationSets = new ArrayList<>(settings.getParticles());
        final int minPhotons = (int) settings.getPhotonsPerSecond();
        final int range = (int) settings.getPhotonsPerSecondMaximum() - minPhotons + 1;
        if (range > 1) {
            rng = createRandomGenerator();
        }
        // Add frames at the specified density until the number of particles has been reached
        int id = 0;
        int time = 0;
        while (id < settings.getParticles()) {
            // Allow the number per frame to be specified
            if (nextN != null) {
                if (time >= nextN.length) {
                    break;
                }
                count = nextN[time];
            }
            // Simulate random positions in the frame for the specified density
            time++;
            for (int j = 0; j < count; j++) {
                final double[] xyz = dist.next();
                // Ignore within border. We do not want to draw things we cannot fit.
                // if (!distBorder.isWithinXy(xyz))
                // continue;
                // Simulate random photons
                final int intensity = minPhotons + ((rng != null) ? rng.nextInt(range) : 0);
                final LocalisationModel m = new LocalisationModel(id, time, xyz, intensity, LocalisationModel.CONTINUOUS);
                // Each localisation can be a separate localisation set
                final LocalisationModelSet set = new LocalisationModelSet(id, time);
                set.add(m);
                localisationSets.add(set);
                id++;
            }
        }
    } else {
        if (!showDialog()) {
            return;
        }
        resetMemory();
        areaInUm = settings.getSize() * settings.getPixelPitch() * settings.getSize() * settings.getPixelPitch() / 1e6;
        int totalSteps;
        double correlation = 0;
        ImageModel imageModel;
        if (trackMode) {
            // ----------------
            // TRACK SIMULATION
            // ----------------
            // In track mode we create fixed lifetime fluorophores that do not overlap in time.
            // This is the simplest simulation to test moving molecules.
            settings.setSeconds((int) Math.ceil(settings.getParticles() * (settings.getExposureTime() + settings.getTOn()) / 1000));
            totalSteps = 0;
            final double simulationStepsPerFrame = (settings.getStepsPerSecond() * settings.getExposureTime()) / 1000.0;
            imageModel = new FixedLifetimeImageModel(settings.getStepsPerSecond() * settings.getTOn() / 1000.0, simulationStepsPerFrame, createRandomGenerator());
        } else {
            // ---------------
            // FULL SIMULATION
            // ---------------
            // The full simulation draws n random points in space.
            // The same molecule may appear in multiple frames, move and blink.
            // 
            // Points are modelled as fluorophores that must be activated and then will
            // blink and photo-bleach. The molecules may diffuse and this can be simulated
            // with many steps per image frame. All steps from a frame are collected
            // into a localisation set which can be drawn on the output image.
            final SpatialIllumination activationIllumination = createIllumination(settings.getPulseRatio(), settings.getPulseInterval());
            // Generate additional frames so that each frame has the set number of simulation steps
            totalSteps = (int) Math.ceil(settings.getSeconds() * settings.getStepsPerSecond());
            // Since we have an exponential decay of activations
            // ensure half of the particles have activated by 30% of the frames.
            final double eAct = totalSteps * 0.3 * activationIllumination.getAveragePhotons();
            // Q. Does tOn/tOff change depending on the illumination strength?
            imageModel = new ActivationEnergyImageModel(eAct, activationIllumination, settings.getStepsPerSecond() * settings.getTOn() / 1000.0, settings.getStepsPerSecond() * settings.getTOffShort() / 1000.0, settings.getStepsPerSecond() * settings.getTOffLong() / 1000.0, settings.getNBlinksShort(), settings.getNBlinksLong(), createRandomGenerator());
            imageModel.setUseGeometricDistribution(settings.getNBlinksGeometricDistribution());
            // Only use the correlation if selected for the distribution
            if (PHOTON_DISTRIBUTION[PHOTON_CORRELATED].equals(settings.getPhotonDistribution())) {
                correlation = settings.getCorrelation();
            }
        }
        imageModel.setPhotonBudgetPerFrame(true);
        imageModel.setDiffusion2D(settings.getDiffuse2D());
        imageModel.setRotation2D(settings.getRotate2D());
        IJ.showStatus("Creating molecules ...");
        final SpatialDistribution distribution = createDistribution();
        final List<CompoundMoleculeModel> compounds = createCompoundMolecules();
        if (compounds == null) {
            return;
        }
        final List<CompoundMoleculeModel> molecules = imageModel.createMolecules(compounds, settings.getParticles(), distribution, settings.getRotateInitialOrientation());
        // Activate fluorophores
        IJ.showStatus("Creating fluorophores ...");
        // Note: molecules list will be converted to compounds containing fluorophores
        fluorophores = imageModel.createFluorophores(molecules, totalSteps);
        if (fluorophores.isEmpty()) {
            IJ.error(TITLE, "No fluorophores created");
            return;
        }
        // Map the fluorophore ID to the compound for mixtures
        if (compounds.size() > 1) {
            idToCompound = new TIntIntHashMap(fluorophores.size());
            for (final FluorophoreSequenceModel l : fluorophores) {
                idToCompound.put(l.getId(), l.getLabel());
            }
        }
        IJ.showStatus("Creating localisations ...");
        // TODO - Output a molecule Id for each fluorophore if using compound molecules. This allows
        // analysis
        // of the ratio of trimers, dimers, monomers, etc that could be detected.
        totalSteps = checkTotalSteps(totalSteps, fluorophores);
        if (totalSteps == 0) {
            return;
        }
        imageModel.setPhotonDistribution(createPhotonDistribution());
        try {
            imageModel.setConfinementDistribution(createConfinementDistribution());
        } catch (final ConfigurationException ex) {
            // We asked the user if it was OK to continue and they said no
            return;
        }
        // This should be optimised
        imageModel.setConfinementAttempts(10);
        final List<LocalisationModel> localisations = imageModel.createImage(molecules, settings.getFixedFraction(), totalSteps, settings.getPhotonsPerSecond() / settings.getStepsPerSecond(), correlation, settings.getRotateDuringSimulation());
        // Re-adjust the fluorophores to the correct time
        if (settings.getStepsPerSecond() != 1) {
            final double scale = 1.0 / settings.getStepsPerSecond();
            for (final FluorophoreSequenceModel f : fluorophores) {
                f.adjustTime(scale);
            }
        }
        // Integrate the frames
        localisationSets = combineSimulationSteps(localisations);
        localisationSets = filterToImageBounds(localisationSets);
    }
    datasetNumber.getAndIncrement();
    final List<LocalisationModel> localisations = drawImage(localisationSets);
    if (localisations == null || localisations.isEmpty()) {
        IJ.error(TITLE, "No localisations created");
        return;
    }
    fluorophores = removeFilteredFluorophores(fluorophores, localisations);
    final double signalPerFrame = showSummary(fluorophores, localisations);
    if (!benchmarkMode) {
        final boolean fullSimulation = (!(simpleMode || spotMode));
        saveSimulationParameters(localisations.size(), fullSimulation, signalPerFrame);
    }
    IJ.showStatus("Saving data ...");
    saveFluorophores(fluorophores);
    saveImageResults(results);
    saveLocalisations(localisations);
    // The settings for the filenames may have changed
    SettingsManager.writeSettings(settings.build());
    IJ.showStatus("Done");
}
Also used : ActivationEnergyImageModel(uk.ac.sussex.gdsc.smlm.model.ActivationEnergyImageModel) CompoundMoleculeModel(uk.ac.sussex.gdsc.smlm.model.CompoundMoleculeModel) ConfigurationException(uk.ac.sussex.gdsc.smlm.data.config.ConfigurationException) GenericDialog(ij.gui.GenericDialog) ExtendedGenericDialog(uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog) SpatialIllumination(uk.ac.sussex.gdsc.smlm.model.SpatialIllumination) PoissonSampler(org.apache.commons.rng.sampling.distribution.PoissonSampler) TIntIntHashMap(gnu.trove.map.hash.TIntIntHashMap) SpatialDistribution(uk.ac.sussex.gdsc.smlm.model.SpatialDistribution) StoredDataStatistics(uk.ac.sussex.gdsc.core.utils.StoredDataStatistics) ReadHint(uk.ac.sussex.gdsc.smlm.results.ImageSource.ReadHint) ConfigurationException(uk.ac.sussex.gdsc.smlm.data.config.ConfigurationException) IOException(java.io.IOException) DataException(uk.ac.sussex.gdsc.core.data.DataException) ConversionException(uk.ac.sussex.gdsc.core.data.utils.ConversionException) NullArgumentException(org.apache.commons.math3.exception.NullArgumentException) LocalisationModel(uk.ac.sussex.gdsc.smlm.model.LocalisationModel) FluorophoreSequenceModel(uk.ac.sussex.gdsc.smlm.model.FluorophoreSequenceModel) FixedLifetimeImageModel(uk.ac.sussex.gdsc.smlm.model.FixedLifetimeImageModel) LocalisationModelSet(uk.ac.sussex.gdsc.smlm.model.LocalisationModelSet) UniformRandomProvider(org.apache.commons.rng.UniformRandomProvider) FixedLifetimeImageModel(uk.ac.sussex.gdsc.smlm.model.FixedLifetimeImageModel) ImageModel(uk.ac.sussex.gdsc.smlm.model.ImageModel) ActivationEnergyImageModel(uk.ac.sussex.gdsc.smlm.model.ActivationEnergyImageModel)

Example 2 with CompoundMoleculeModel

use of uk.ac.sussex.gdsc.smlm.model.CompoundMoleculeModel in project GDSC-SMLM by aherbert.

the class CreateData method createCompoundMolecules.

private List<CompoundMoleculeModel> createCompoundMolecules() {
    // Diffusion rate is um^2/sec. Convert to pixels per simulation frame.
    final double diffusionFactor = (1000000.0 / (settings.getPixelPitch() * settings.getPixelPitch())) / settings.getStepsPerSecond();
    List<CompoundMoleculeModel> compounds;
    if (settings.getCompoundMolecules()) {
        // Try and load the compounds from the text specification
        try {
            // Convert from the serialised objects to the compound model
            final String text = settings.getCompoundText();
            final Mixture.Builder builder = Mixture.newBuilder();
            TextFormat.merge(text, builder);
            compounds = new ArrayList<>(builder.getMoleculeCount());
            int id = 1;
            compoundNames = new ArrayList<>(builder.getMoleculeCount());
            for (final Molecule m : builder.getMoleculeList()) {
                final MoleculeModel[] molecules = new MoleculeModel[m.getAtomCount()];
                for (int i = 0; i < molecules.length; i++) {
                    final AtomOrBuilder a = m.getAtomOrBuilder(i);
                    molecules[i] = new MoleculeModel(a.getMass(), a.getX(), a.getY(), a.getZ());
                }
                final CompoundMoleculeModel cm = new CompoundMoleculeModel(id++, 0, 0, 0, Arrays.asList(molecules));
                cm.setFraction(m.getFraction());
                cm.setDiffusionRate(m.getDiffusionRate() * diffusionFactor);
                cm.setDiffusionType(DiffusionType.fromString(m.getDiffusionType()));
                compounds.add(cm);
                compoundNames.add(String.format("Fraction=%s, D=%s um^2/s", MathUtils.rounded(cm.getFraction()), MathUtils.rounded(m.getDiffusionRate())));
            }
            // Convert coordinates from nm to pixels
            final double scaleFactor = 1.0 / settings.getPixelPitch();
            for (final CompoundMoleculeModel c : compounds) {
                c.scale(scaleFactor);
            }
        } catch (final IOException ex) {
            IJ.error(TITLE, "Unable to create compound molecules");
            return null;
        }
    } else {
        // Create a simple compound with one molecule at the origin
        compounds = new ArrayList<>(1);
        final CompoundMoleculeModel m = new CompoundMoleculeModel(1, 0, 0, 0, Arrays.asList(new MoleculeModel(0, 0, 0, 0)));
        m.setDiffusionRate(settings.getDiffusionRate() * diffusionFactor);
        m.setDiffusionType(CreateDataSettingsHelper.getDiffusionType(settings.getDiffusionType()));
        compounds.add(m);
    }
    return compounds;
}
Also used : CompoundMoleculeModel(uk.ac.sussex.gdsc.smlm.model.CompoundMoleculeModel) IOException(java.io.IOException) Mixture(uk.ac.sussex.gdsc.smlm.data.config.MoleculeProtos.Mixture) ReadHint(uk.ac.sussex.gdsc.smlm.results.ImageSource.ReadHint) Molecule(uk.ac.sussex.gdsc.smlm.data.config.MoleculeProtos.Molecule) MoleculeModel(uk.ac.sussex.gdsc.smlm.model.MoleculeModel) CompoundMoleculeModel(uk.ac.sussex.gdsc.smlm.model.CompoundMoleculeModel) AtomOrBuilder(uk.ac.sussex.gdsc.smlm.data.config.MoleculeProtos.AtomOrBuilder)

Example 3 with CompoundMoleculeModel

use of uk.ac.sussex.gdsc.smlm.model.CompoundMoleculeModel in project GDSC-SMLM by aherbert.

the class CreateData method convertRelativeToAbsolute.

/**
 * Update the fluorophores relative coordinates to absolute.
 *
 * @param molecules the molecules
 */
@SuppressWarnings("unused")
private static void convertRelativeToAbsolute(List<CompoundMoleculeModel> molecules) {
    for (final CompoundMoleculeModel c : molecules) {
        final double[] xyz = c.getCoordinates();
        for (int n = c.getSize(); n-- > 0; ) {
            final MoleculeModel m = c.getMolecule(n);
            final double[] xyz2 = m.getCoordinates();
            for (int i = 0; i < 3; i++) {
                xyz2[i] += xyz[i];
            }
        }
    }
}
Also used : MoleculeModel(uk.ac.sussex.gdsc.smlm.model.MoleculeModel) CompoundMoleculeModel(uk.ac.sussex.gdsc.smlm.model.CompoundMoleculeModel) CompoundMoleculeModel(uk.ac.sussex.gdsc.smlm.model.CompoundMoleculeModel) ReadHint(uk.ac.sussex.gdsc.smlm.results.ImageSource.ReadHint)

Example 4 with CompoundMoleculeModel

use of uk.ac.sussex.gdsc.smlm.model.CompoundMoleculeModel in project GDSC-SMLM by aherbert.

the class BlinkEstimatorTest method estimateBlinking.

private TIntHashSet estimateBlinking(UniformRandomProvider rg, double blinkingRate, double ton, double toff, int particles, double fixedFraction, boolean timeAtLowerBound, boolean doAssert) {
    Assumptions.assumeTrue(TestSettings.allow(TestComplexity.MAXIMUM));
    final SpatialIllumination activationIllumination = new UniformIllumination(100);
    int totalSteps = 100;
    final double eAct = totalSteps * 0.3 * activationIllumination.getAveragePhotons();
    final ImageModel imageModel = new ActivationEnergyImageModel(eAct, activationIllumination, ton, 0, toff, 0, blinkingRate, rg);
    final double[] max = new double[] { 256, 256, 32 };
    final double[] min = new double[3];
    final SpatialDistribution distribution = new UniformDistribution(min, max, rg.nextInt());
    final List<CompoundMoleculeModel> compounds = new ArrayList<>(1);
    final CompoundMoleculeModel c = new CompoundMoleculeModel(1, 0, 0, 0, Arrays.asList(new MoleculeModel(0, 0, 0, 0)));
    c.setDiffusionRate(diffusionRate);
    c.setDiffusionType(DiffusionType.RANDOM_WALK);
    compounds.add(c);
    final List<CompoundMoleculeModel> molecules = imageModel.createMolecules(compounds, particles, distribution, false);
    // Activate fluorophores
    final List<? extends FluorophoreSequenceModel> fluorophores = imageModel.createFluorophores(molecules, totalSteps);
    totalSteps = checkTotalSteps(totalSteps, fluorophores);
    final List<LocalisationModel> localisations = imageModel.createImage(molecules, fixedFraction, totalSteps, photons, 0.5, false);
    // // Remove localisations to simulate missed counts.
    // List<LocalisationModel> newLocalisations = new
    // ArrayList<LocalisationModel>(localisations.size());
    // boolean[] id = new boolean[fluorophores.size() + 1];
    // Statistics photonStats = new Statistics();
    // for (LocalisationModel l : localisations)
    // {
    // photonStats.add(l.getIntensity());
    // // Remove by intensity threshold and optionally at random.
    // if (l.getIntensity() < minPhotons || rand.nextDouble() < pDelete)
    // continue;
    // newLocalisations.add(l);
    // id[l.getId()] = true;
    // }
    // localisations = newLocalisations;
    // logger.info("Photons = %f", photonStats.getMean());
    // 
    // List<FluorophoreSequenceModel> newFluorophores = new
    // ArrayList<FluorophoreSequenceModel>(fluorophores.size());
    // for (FluorophoreSequenceModel f : fluorophores)
    // {
    // if (id[f.getId()])
    // newFluorophores.add(f);
    // }
    // fluorophores = newFluorophores;
    final MemoryPeakResults results = new MemoryPeakResults();
    final CalibrationWriter calibration = new CalibrationWriter();
    calibration.setNmPerPixel(pixelPitch);
    calibration.setExposureTime(msPerFrame);
    calibration.setCountPerPhoton(1);
    results.setCalibration(calibration.getCalibration());
    results.setPsf(PsfHelper.create(PSFType.ONE_AXIS_GAUSSIAN_2D));
    final float b = 0;
    float intensity;
    final float z = 0;
    for (final LocalisationModel l : localisations) {
        // Remove by intensity threshold and optionally at random.
        if (l.getIntensity() < minPhotons || rg.nextDouble() < probabilityDelete) {
            continue;
        }
        final int frame = l.getTime();
        intensity = (float) l.getIntensity();
        final float x = (float) l.getX();
        final float y = (float) l.getY();
        final float[] params = Gaussian2DPeakResultHelper.createParams(b, intensity, x, y, z, psfWidth);
        results.add(frame, 0, 0, 0, 0, 0, 0, params, null);
    }
    // Add random localisations
    // Intensity doesn't matter at the moment for tracing
    intensity = (float) photons;
    for (int i = (int) (localisations.size() * probabilityAdd); i-- > 0; ) {
        final int frame = 1 + rg.nextInt(totalSteps);
        final float x = (float) (rg.nextDouble() * max[0]);
        final float y = (float) (rg.nextDouble() * max[1]);
        final float[] params = Gaussian2DPeakResultHelper.createParams(b, intensity, x, y, z, psfWidth);
        results.add(frame, 0, 0, 0, 0, 0, 0, params, null);
    }
    // Get actual simulated stats ...
    final Statistics statsNBlinks = new Statistics();
    final Statistics statsTOn = new Statistics();
    final Statistics statsTOff = new Statistics();
    final Statistics statsSampledNBlinks = new Statistics();
    final Statistics statsSampledTOn = new Statistics();
    final StoredDataStatistics statsSampledTOff = new StoredDataStatistics();
    for (final FluorophoreSequenceModel f : fluorophores) {
        statsNBlinks.add(f.getNumberOfBlinks());
        statsTOn.add(f.getOnTimes());
        statsTOff.add(f.getOffTimes());
        final int[] on = f.getSampledOnTimes();
        statsSampledNBlinks.add(on.length);
        statsSampledTOn.add(on);
        statsSampledTOff.add(f.getSampledOffTimes());
    }
    logger.info(FunctionUtils.getSupplier("N = %d (%d), N-blinks = %f, tOn = %f, tOff = %f, Fixed = %f", fluorophores.size(), localisations.size(), blinkingRate, ton, toff, fixedFraction));
    logger.info(FunctionUtils.getSupplier("Actual N-blinks = %f (%f), tOn = %f (%f), tOff = %f (%f), 95%% = %f, max = %f", statsNBlinks.getMean(), statsSampledNBlinks.getMean(), statsTOn.getMean(), statsSampledTOn.getMean(), statsTOff.getMean(), statsSampledTOff.getMean(), statsSampledTOff.getStatistics().getPercentile(95), statsSampledTOff.getStatistics().getMax()));
    logger.info("-=-=--=-");
    final BlinkEstimator be = new BlinkEstimator();
    be.setMaxDarkTime((int) (toff * 10));
    be.setMsPerFrame(msPerFrame);
    be.setRelativeDistance(false);
    final double d = ImageModel.getRandomMoveDistance(diffusionRate);
    be.setSearchDistance((fixedFraction < 1) ? Math.sqrt(2 * d * d) * 3 : 0);
    be.setTimeAtLowerBound(timeAtLowerBound);
    // Assertions.assertTrue("Max dark time must exceed the dark time of the data (otherwise no
    // plateau)",
    // be.maxDarkTime > statsSampledTOff.getStatistics().getMax());
    final int nMolecules = fluorophores.size();
    if (usePopulationStatistics) {
        blinkingRate = statsNBlinks.getMean();
        toff = statsTOff.getMean();
    } else {
        blinkingRate = statsSampledNBlinks.getMean();
        toff = statsSampledTOff.getMean();
    }
    // See if any fitting regime gets a correct answer
    final TIntHashSet ok = new TIntHashSet();
    for (int numberOfFittedPoints = MIN_FITTED_POINTS; numberOfFittedPoints <= MAX_FITTED_POINTS; numberOfFittedPoints++) {
        be.setNumberOfFittedPoints(numberOfFittedPoints);
        be.computeBlinkingRate(results, true);
        final double moleculesError = DoubleEquality.relativeError(nMolecules, be.getNMolecules());
        final double blinksError = DoubleEquality.relativeError(blinkingRate, be.getNBlinks());
        final double offError = DoubleEquality.relativeError(toff * msPerFrame, be.getTOff());
        logger.info(FunctionUtils.getSupplier("Error %d: N = %f, blinks = %f, tOff = %f : %f", numberOfFittedPoints, moleculesError, blinksError, offError, (moleculesError + blinksError + offError) / 3));
        if (moleculesError < relativeError && blinksError < relativeError && offError < relativeError) {
            ok.add(numberOfFittedPoints);
            logger.info("-=-=--=-");
            logger.info(FunctionUtils.getSupplier("*** Correct at %d fitted points ***", numberOfFittedPoints));
            if (doAssert) {
                break;
            }
        }
    // if (!be.isIncreaseNFittedPoints())
    // break;
    }
    logger.info("-=-=--=-");
    if (doAssert) {
        Assertions.assertFalse(ok.isEmpty());
    }
    // relativeError);
    return ok;
}
Also used : ActivationEnergyImageModel(uk.ac.sussex.gdsc.smlm.model.ActivationEnergyImageModel) CompoundMoleculeModel(uk.ac.sussex.gdsc.smlm.model.CompoundMoleculeModel) ArrayList(java.util.ArrayList) TIntHashSet(gnu.trove.set.hash.TIntHashSet) MoleculeModel(uk.ac.sussex.gdsc.smlm.model.MoleculeModel) CompoundMoleculeModel(uk.ac.sussex.gdsc.smlm.model.CompoundMoleculeModel) SpatialIllumination(uk.ac.sussex.gdsc.smlm.model.SpatialIllumination) CalibrationWriter(uk.ac.sussex.gdsc.smlm.data.config.CalibrationWriter) MemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults) SpatialDistribution(uk.ac.sussex.gdsc.smlm.model.SpatialDistribution) UniformDistribution(uk.ac.sussex.gdsc.smlm.model.UniformDistribution) StoredDataStatistics(uk.ac.sussex.gdsc.core.utils.StoredDataStatistics) StoredDataStatistics(uk.ac.sussex.gdsc.core.utils.StoredDataStatistics) Statistics(uk.ac.sussex.gdsc.core.utils.Statistics) UniformIllumination(uk.ac.sussex.gdsc.smlm.model.UniformIllumination) LocalisationModel(uk.ac.sussex.gdsc.smlm.model.LocalisationModel) FluorophoreSequenceModel(uk.ac.sussex.gdsc.smlm.model.FluorophoreSequenceModel) ActivationEnergyImageModel(uk.ac.sussex.gdsc.smlm.model.ActivationEnergyImageModel) ImageModel(uk.ac.sussex.gdsc.smlm.model.ImageModel)

Aggregations

CompoundMoleculeModel (uk.ac.sussex.gdsc.smlm.model.CompoundMoleculeModel)4 MoleculeModel (uk.ac.sussex.gdsc.smlm.model.MoleculeModel)3 ReadHint (uk.ac.sussex.gdsc.smlm.results.ImageSource.ReadHint)3 IOException (java.io.IOException)2 StoredDataStatistics (uk.ac.sussex.gdsc.core.utils.StoredDataStatistics)2 ActivationEnergyImageModel (uk.ac.sussex.gdsc.smlm.model.ActivationEnergyImageModel)2 FluorophoreSequenceModel (uk.ac.sussex.gdsc.smlm.model.FluorophoreSequenceModel)2 ImageModel (uk.ac.sussex.gdsc.smlm.model.ImageModel)2 LocalisationModel (uk.ac.sussex.gdsc.smlm.model.LocalisationModel)2 SpatialDistribution (uk.ac.sussex.gdsc.smlm.model.SpatialDistribution)2 SpatialIllumination (uk.ac.sussex.gdsc.smlm.model.SpatialIllumination)2 TIntIntHashMap (gnu.trove.map.hash.TIntIntHashMap)1 TIntHashSet (gnu.trove.set.hash.TIntHashSet)1 GenericDialog (ij.gui.GenericDialog)1 ArrayList (java.util.ArrayList)1 NullArgumentException (org.apache.commons.math3.exception.NullArgumentException)1 UniformRandomProvider (org.apache.commons.rng.UniformRandomProvider)1 PoissonSampler (org.apache.commons.rng.sampling.distribution.PoissonSampler)1 DataException (uk.ac.sussex.gdsc.core.data.DataException)1 ConversionException (uk.ac.sussex.gdsc.core.data.utils.ConversionException)1