Search in sources :

Example 1 with ExponentialDataFunction

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

the class TrackPopulationAnalysisTest method canComputeExponentialLogLikelihood.

@Test
void canComputeExponentialLogLikelihood() {
    final RandomGenerator rng = new RandomGeneratorAdapter(RngUtils.createWithFixedSeed());
    final double delta = 1e-6;
    for (final double mean : new double[] { 2, 10 }) {
        // Create exponential data
        ExponentialDistribution ed = new ExponentialDistribution(rng, mean);
        final double[] values = ed.sample(1000);
        // Discretise
        final double factor = mean / 10;
        for (int i = 0; i < values.length; i++) {
            values[i] = Math.round(values[i] / factor) * factor;
        }
        // Histogram these
        final double[][] h = MathUtils.cumulativeHistogram(values, false);
        final ExponentialDataFunction ef = ExponentialDataFunction.fromCdf(h);
        // Test with different means
        for (final double du : new double[] { -0.1, 0, 0.1 }) {
            final double mu = mean + du;
            ed = new ExponentialDistribution(rng, mu);
            double ll = 0;
            for (final double x : values) {
                ll += ed.logDensity(x);
            }
            final double ll2 = ef.value(mu);
            Assertions.assertEquals(ll, ll2, 1e-10, "Log likelihood");
            // Check for gradient
            final double ll2a = ef.value(mu + delta);
            final double ll2b = ef.value(mu - delta);
            final double gradient = (ll2a - ll2b) / (2 * delta);
            Assertions.assertEquals(gradient, ef.gradient(mu), Math.abs(gradient) * 1e-4, "Gradient");
        }
    }
}
Also used : RandomGeneratorAdapter(uk.ac.sussex.gdsc.core.utils.rng.RandomGeneratorAdapter) ExponentialDataFunction(uk.ac.sussex.gdsc.smlm.ij.plugins.TrackPopulationAnalysis.ExponentialDataFunction) ExponentialDistribution(org.apache.commons.math3.distribution.ExponentialDistribution) RandomGenerator(org.apache.commons.math3.random.RandomGenerator) Test(org.junit.jupiter.api.Test)

Aggregations

ExponentialDistribution (org.apache.commons.math3.distribution.ExponentialDistribution)1 RandomGenerator (org.apache.commons.math3.random.RandomGenerator)1 Test (org.junit.jupiter.api.Test)1 RandomGeneratorAdapter (uk.ac.sussex.gdsc.core.utils.rng.RandomGeneratorAdapter)1 ExponentialDataFunction (uk.ac.sussex.gdsc.smlm.ij.plugins.TrackPopulationAnalysis.ExponentialDataFunction)1