Example usage for org.apache.commons.math3.random Well19937c Well19937c

List of usage examples for org.apache.commons.math3.random Well19937c Well19937c

Introduction

In this page you can find the example usage for org.apache.commons.math3.random Well19937c Well19937c.

Prototype

public Well19937c(long seed) 

Source Link

Document

Creates a new random number generator using a single long seed.

Usage

From source file:com.anhth12.lambda.common.random.RandomManager.java

/**
 * @return a new, seeded {@link RandomGenerator}
 *///w ww.j  ava 2s. c  om
public static RandomGenerator getRandom() {
    if (useTestSeed) {
        // No need to track instances anymore
        return new Well19937c(TEST_SEED);
    }
    RandomGenerator random = new Well19937c();
    Collection<RandomGenerator> instances = INSTANCES.get();
    if (instances != null) {
        synchronized (instances) {
            instances.add(random);
        }
    } // else oh well, only matters in tests
    return random;
}

From source file:com.cloudera.oryx.common.random.RandomManager.java

/**
 * @return a new, seeded {@link RandomGenerator}
 *//*from   ww  w . j  av a2s  . c o  m*/
public static RandomGenerator getRandom() {
    if (useTestSeed) {
        // No need to track instances anymore
        return new Well19937c(TEST_SEED);
    }
    RandomGenerator random = new Well19937c();
    synchronized (INSTANCES) {
        INSTANCES.put(random, Boolean.TRUE); // Value does not matter
    }
    return random;
}

From source file:com.milaboratory.core.mutations.generator.SubstitutionModelTest.java

@Test
public void test1() throws Exception {
    SubstitutionModel model = SubstitutionModels.getEmpiricalNucleotideSubstitutionModel();
    RandomGenerator rg = new Well19937c(12312);

    int trials = 100000;

    for (int lF = 0; lF < 4; ++lF) {

        int[] result = new int[4];
        for (int i = 0; i < trials; ++i)
            result[model.sample(rg, lF)]++;

        for (int lT = 0; lT < 4; ++lT)
            Assert.assertEquals(trials * model.getProbability(lF, lT), result[lT],
                    Math.sqrt(trials * model.getProbability(lF, lT)) * 3);
    }/*from   w w  w  .  j  av  a2s  . c o  m*/
}

From source file:com.insightml.models.clusters.GaussianMixtureModelsTest.java

@Test
public void test() {
    final Well19937c rnd = new Well19937c(0);
    final double[] data = Vectors.append(new NormalDistribution(rnd, 10, 5).sample(50),
            new NormalDistribution(rnd, 4000, 100).sample(75));
    final Point[] points = new Point[data.length];
    for (int i = 0; i < points.length; ++i) {
        points[i] = new Point(data[i]);
    }//  w  w w  . ja v a 2  s .  c o  m
    final Triple<IContDistribution[], double[], double[][]> out = new GaussianMixtureModels().run(points, 2,
            10);
    final Components result = new Components(out.getFirst(), out.getSecond());
    System.err.println(result);
    Assert.assertEquals(-685.3993, result.incompleteLogLikelihood(data), 0.0001);
    Assert.assertEquals(-690.2276, result.bic(data), 0.0001);
}

From source file:com.milaboratory.core.mutations.generator.GenericNucleotideMutationModel.java

public GenericNucleotideMutationModel(SubstitutionModel substitutionModel, double deletionProbability,
        double insertionProbability, long seed) {
    this.generator = new Well19937c(seed);
    this.insertionProbability = insertionProbability;

    this.events = new double[4 * 5];
    int i, j;//w  w  w. j a  va  2s  .co m
    double noEventProbability, sum;
    for (i = 0; i < 4; ++i) {
        sum = insertionProbability;
        events[i * 5] = (sum += deletionProbability);

        noEventProbability = 1.0 - sum - substitutionModel.getTotalSubstitutionProbability(i);

        for (j = 0; j < 4; ++j)
            if (i != j)
                events[i * 5 + 1 + j] = (sum += substitutionModel.getProbability(i, j));
            else
                events[i * 5 + 1 + j] = (sum += noEventProbability);

        assert sum <= 1.0001 & sum >= 0.9999;
    }
}

From source file:com.milaboratory.core.mutations.generator.SubstitutionModelTest.java

@Test
public void test2() throws Exception {
    SubstitutionModel sm = SubstitutionModels.getUniformNucleotideSubstitutionModel(.1);
    RandomGenerator rg = new Well19937c(12313432L);
    int trials = 1000000;

    for (int k = 0; k < TestUtil.its(20, 200); ++k) {
        int mutations = 0;
        for (int i = 0; i < trials; ++i) {
            if (sm.sample(rg, 3) != 3)
                ++mutations;//  w w w  .java  2 s.  c o m
        }

        Assert.assertEquals(100000, mutations, 2000);
    }
}

From source file:com.milaboratory.core.mutations.generator.GenericNucleotideMutationModel.java

GenericNucleotideMutationModel(double[] events, double insertionProbability, long seed) {
    this.generator = new Well19937c(seed);
    this.events = events;
    this.insertionProbability = insertionProbability;
}

From source file:broadwick.rng.RNG.java

/**
 * Create a random number generator from a given generator using the current time as a seed.
 * @param gen the random number generator to use.
 *///  w ww .ja v a  2  s  .co m
public RNG(final Generator gen) {
    if (gen.equals(Generator.MERSENNE)) {
        generator = new RandomDataGenerator(
                new MersenneTwister(System.currentTimeMillis() * Thread.currentThread().getId()));
        name = "Mersenne Twister";
    } else if (gen.equals(Generator.Well19937c)) {
        generator = new RandomDataGenerator(
                new Well19937c(System.currentTimeMillis() * Thread.currentThread().getId()));
        name = "Well19937c";
    } else if (gen.equals(Generator.Well44497b)) {
        generator = new RandomDataGenerator(
                new Well44497b(System.currentTimeMillis() * Thread.currentThread().getId()));
        name = "Well44497b";
    } else {
        // By default, the implementation provided in RandomDataImpl uses
        // the JDK-provided PRNG. Like most other PRNGs, the JDK generator
        // generates sequences of random numbers based on an initial
        // "seed value".
        generator = new RandomDataGenerator();
    }
}

From source file:gdsc.smlm.model.ImageModel.java

/**
 * Construct a new image model/*from   w ww.jav a2 s  . co m*/
 * 
 * @param tOn
 *            Average on-state time
 * @param tOff
 *            Average off-state time for the first dark state
 * @param tOff2
 *            Average off-state time for the second dark state
 * @param nBlinks
 *            Average number of blinks int the first dark state (used for each burst between second dark states)
 * @param nBlinks2
 *            Average number of blinks into the second dark state
 */
public ImageModel(double tOn, double tOff, double tOff2, double nBlinks, double nBlinks2) {
    init(tOn, tOff, tOff2, nBlinks, nBlinks2,
            new Well19937c(System.currentTimeMillis() + System.identityHashCode(this)));
}

From source file:gdsc.smlm.ij.plugins.DiffusionRateTest.java

public void run(String arg) {
    if (!showDialog())
        return;//from ww  w . j av  a2  s  . co  m

    int totalSteps = settings.seconds * settings.stepsPerSecond;

    final double conversionFactor = 1000000.0 / (settings.pixelPitch * settings.pixelPitch);

    // Diffusion rate is um^2/sec. Convert to pixels per simulation frame.
    final double diffusionRateInPixelsPerSecond = settings.diffusionRate * conversionFactor;
    final double diffusionRateInPixelsPerStep = diffusionRateInPixelsPerSecond / settings.stepsPerSecond;

    Utils.log(TITLE + " : D = %s um^2/sec", Utils.rounded(settings.diffusionRate, 4));
    Utils.log("Mean-displacement per dimension = %s nm/sec",
            Utils.rounded(1e3 * ImageModel.getRandomMoveDistance(settings.diffusionRate), 4));

    // Convert diffusion co-efficient into the standard deviation for the random walk
    final double diffusionSigma = ImageModel.getRandomMoveDistance(diffusionRateInPixelsPerStep);
    Utils.log("Simulation step-size = %s nm", Utils.rounded(settings.pixelPitch * diffusionSigma, 4));

    // Move the molecules and get the diffusion rate
    IJ.showStatus("Simulating ...");
    final long start = System.nanoTime();
    RandomGenerator random = new Well19937c(System.currentTimeMillis() + System.identityHashCode(this));
    Statistics[] stats2D = new Statistics[totalSteps];
    Statistics[] stats3D = new Statistics[totalSteps];
    for (int j = 0; j < totalSteps; j++) {
        stats2D[j] = new Statistics();
        stats3D[j] = new Statistics();
    }
    SphericalDistribution dist = new SphericalDistribution(settings.confinementRadius / settings.pixelPitch);
    Statistics asymptote = new Statistics();
    for (int i = 0; i < settings.particles; i++) {
        if (i % 16 == 0)
            IJ.showProgress(i, settings.particles);

        MoleculeModel m = new MoleculeModel(i, new double[3]);
        if (useConfinement) {
            // Note: When using confinement the average displacement should asymptote
            // at the average distance of a point from the centre of a ball. This is 3r/4.
            // See: http://answers.yahoo.com/question/index?qid=20090131162630AAMTUfM
            // The equivalent in 2D is 2r/3. However although we are plotting 2D distance
            // this is a projection of the 3D position onto the plane and so the particles
            // will not be evenly spread (there will be clustering at centre caused by the
            // poles)
            for (int j = 0; j < totalSteps; j++) {
                double[] xyz = m.getCoordinates();
                double[] originalXyz = Arrays.copyOf(xyz, 3);
                for (int n = confinementAttempts; n-- > 0;) {
                    if (settings.useGridWalk)
                        m.walk(diffusionSigma, random);
                    else
                        m.move(diffusionSigma, random);
                    if (!dist.isWithin(m.getCoordinates())) {
                        // Reset position
                        for (int k = 0; k < 3; k++)
                            xyz[k] = originalXyz[k];
                    } else {
                        // The move was allowed
                        break;
                    }
                }

                stats2D[j].add(squared(m.getCoordinates()));
                stats3D[j].add(distance2(m.getCoordinates()));
            }
            asymptote.add(distance(m.getCoordinates()));
        } else {
            if (settings.useGridWalk) {
                for (int j = 0; j < totalSteps; j++) {
                    m.walk(diffusionSigma, random);
                    stats2D[j].add(squared(m.getCoordinates()));
                    stats3D[j].add(distance2(m.getCoordinates()));
                }
            } else {
                for (int j = 0; j < totalSteps; j++) {
                    m.move(diffusionSigma, random);
                    stats2D[j].add(squared(m.getCoordinates()));
                    stats3D[j].add(distance2(m.getCoordinates()));
                }
            }
        }

        // Debug: record all the particles so they can be analysed
        // System.out.printf("%f %f %f\n", m.getX(), m.getY(), m.getZ());
    }
    final double time = (System.nanoTime() - start) / 1000000.0;

    IJ.showStatus("Analysing results ...");
    IJ.showProgress(1);

    if (showDiffusionExample) {
        showExample(totalSteps, diffusionSigma, random);
    }

    // Plot a graph of mean squared distance
    double[] xValues = new double[stats2D.length];
    double[] yValues2D = new double[stats2D.length];
    double[] yValues3D = new double[stats3D.length];
    double[] upper = new double[stats2D.length];
    double[] lower = new double[stats2D.length];
    final CurveFitter<Parametric> fitter2D = new CurveFitter<Parametric>(new LevenbergMarquardtOptimizer());
    final CurveFitter<Parametric> fitter3D = new CurveFitter<Parametric>(new LevenbergMarquardtOptimizer());
    Statistics gradient2D = new Statistics();
    Statistics gradient3D = new Statistics();
    final int firstN = (useConfinement) ? fitN : totalSteps;
    for (int j = 0; j < totalSteps; j++) {
        // Convert steps to seconds
        xValues[j] = (double) (j + 1) / settings.stepsPerSecond;

        // Convert values in pixels^2 to um^2
        final double mean = stats2D[j].getMean() / conversionFactor;
        final double sd = stats2D[j].getStandardDeviation() / conversionFactor;
        yValues2D[j] = mean;
        yValues3D[j] = stats3D[j].getMean() / conversionFactor;
        upper[j] = mean + sd;
        lower[j] = mean - sd;

        if (j < firstN) {
            fitter2D.addObservedPoint(xValues[j], yValues2D[j]);
            gradient2D.add(yValues2D[j] / xValues[j]);
            fitter3D.addObservedPoint(xValues[j], yValues3D[j]);
            gradient3D.add(yValues3D[j] / xValues[j]);
        }
    }

    // TODO - Fit using the equation for 2D confined diffusion:
    // MSD = 4s^2 + R^2 (1 - 0.99e^(-1.84^2 Dt / R^2)
    // s = localisation precision
    // R = confinement radius
    // D = 2D diffusion coefficient
    // t = time

    // Do linear regression to get diffusion rate
    final double[] init2D = { 0, 1 / gradient2D.getMean() }; // a - b x
    final double[] best2D = fitter2D.fit(new PolynomialFunction.Parametric(), init2D);
    final PolynomialFunction fitted2D = new PolynomialFunction(best2D);

    final double[] init3D = { 0, 1 / gradient3D.getMean() }; // a - b x
    final double[] best3D = fitter3D.fit(new PolynomialFunction.Parametric(), init3D);
    final PolynomialFunction fitted3D = new PolynomialFunction(best3D);

    // Create plot
    String title = TITLE;
    Plot2 plot = new Plot2(title, "Time (seconds)", "Mean-squared Distance (um^2)", xValues, yValues2D);
    double[] limits = Maths.limits(upper);
    limits = Maths.limits(limits, lower);
    limits = Maths.limits(limits, yValues3D);
    plot.setLimits(0, totalSteps / settings.stepsPerSecond, limits[0], limits[1]);
    plot.setColor(Color.blue);
    plot.addPoints(xValues, lower, Plot2.LINE);
    plot.addPoints(xValues, upper, Plot2.LINE);
    plot.setColor(Color.magenta);
    plot.addPoints(xValues, yValues3D, Plot2.LINE);
    plot.setColor(Color.red);
    plot.addPoints(new double[] { xValues[0], xValues[xValues.length - 1] },
            new double[] { fitted2D.value(xValues[0]), fitted2D.value(xValues[xValues.length - 1]) },
            Plot2.LINE);
    plot.setColor(Color.green);
    plot.addPoints(new double[] { xValues[0], xValues[xValues.length - 1] },
            new double[] { fitted3D.value(xValues[0]), fitted3D.value(xValues[xValues.length - 1]) },
            Plot2.LINE);
    plot.setColor(Color.black);

    Utils.display(title, plot);

    // For 2D diffusion: d^2 = 4D
    // where: d^2 = mean-square displacement

    double D = best2D[1] / 4.0;
    String msg = "2D Diffusion rate = " + Utils.rounded(D, 4) + " um^2 / sec (" + Utils.timeToString(time)
            + ")";
    IJ.showStatus(msg);
    Utils.log(msg);

    D = best3D[1] / 6.0;
    Utils.log("3D Diffusion rate = " + Utils.rounded(D, 4) + " um^2 / sec (" + Utils.timeToString(time) + ")");

    if (useConfinement)
        Utils.log("3D asymptote distance = %s nm (expected %.2f)",
                Utils.rounded(asymptote.getMean() * settings.pixelPitch, 4),
                3 * settings.confinementRadius / 4);
}