Example usage for org.apache.commons.math3.distribution NormalDistribution sample

List of usage examples for org.apache.commons.math3.distribution NormalDistribution sample

Introduction

In this page you can find the example usage for org.apache.commons.math3.distribution NormalDistribution sample.

Prototype

@Override
public double sample() 

Source Link

Usage

From source file:fr.inria.zenith.randomWalk.RandomWalkTsG.java

public static String[] randomWalk(int length) {
    NormalDistribution n = new NormalDistribution(new JDKRandomGenerator(), 0, 1); //mean 0 std 1 variance 1
    String[] ts = new String[length];
    double[] tstemp = new double[length];
    double[] e = new double[length - 1];

    for (int i = 0; i < e.length; i++) {
        e[i] = n.sample();
    }/* w  w w  . j av a2  s  .  c  o m*/
    ts[0] = "0.0";
    for (int i = 1; i < length; i++) {
        ts[i] = (tstemp[i] = tstemp[i - 1] + e[i - 1]) + "";
    }
    return ts;
}

From source file:com.gs.obevo.schemagen.SchemaGenerator.java

private MinMaxSupplier getMinMaxSupplier(int min, int max, int mean, int sd) {
    final NormalDistribution distribution = new NormalDistribution(mean, sd);
    return new MinMaxSupplier(new DoubleFunction0() {
        @Override/* w w  w .j a  va 2 s  .c  om*/
        public double value() {
            return distribution.sample();
        }
    }, min, max);
}

From source file:com.itemanalysis.psychometrics.factoranalysis.GPArotation.java

private RealMatrix randomStart(int ncol) {
    NormalDistribution norm = new NormalDistribution(0.0, 1.0);
    RealMatrix T = new Array2DRowRealMatrix(ncol, ncol);
    for (int i = 0; i < ncol; i++) {
        for (int j = 0; j < ncol; j++) {
            T.setEntry(i, j, norm.sample());
        }/*www .  j  a  v a  2  s  .  co  m*/
    }
    QRDecomposition qr = new QRDecomposition(T);
    return qr.getQ();
}

From source file:edu.cudenver.bios.matrix.DesignEssenceMatrix.java

/**
 * Fills in a random column in the full design matrix
 *
 * @param randomColumn column index in random submatrix
 * @param fullColumn column index in full design matrix
 * @param fullDesign full design matrix// ww w.  j a va  2s  . c om
 */
private void fillRandomColumn(int randomColumn, int fullColumn, RealMatrix fullDesign) {
    // if the column represents a random predictor, build a normal distribution
    // from which to pull random values
    NormalDistribution dist = null;
    // note, the jsc library takes a standard deviation, not a variance so
    // we take the square root
    dist = new NormalDistribution(randomColMetaData[randomColumn].getMean(),
            Math.sqrt(randomColMetaData[randomColumn].getVariance()));
    dist.reseedRandomGenerator(randomSeed);

    for (int row = 0; row < fullDesign.getRowDimension(); row++) {
        // fill in the data
        fullDesign.setEntry(row, fullColumn, dist.sample());
    }
}

From source file:edu.cmu.tetrad.sem.LargeScaleSimulation.java

/**
 * This simulates data by picking random values for the exogenous terms and
 * percolating this information down through the SEM, assuming it is
 * acyclic. Works, but will hang for cyclic models, and is very slow for
 * large numbers of variables (probably due to the heavyweight lookups of
 * various values--could be improved). The model must be acyclic, or else
 * this will spin./*from   ww w  .ja va  2  s . co m*/
 */
public DataSet simulateDataRecursive(int sampleSize) {
    if (tierIndices == null) {
        List<Node> nodes = graph.getNodes();
        tierIndices = new int[nodes.size()];
        for (int j = 0; j < nodes.size(); j++) {
            tierIndices[j] = j;
        }
    }

    int size = variableNodes.size();
    setupModel(size);

    class SimulateTask extends RecursiveTask<Boolean> {
        private final int from;
        private final int to;
        private double[][] all;
        private int chunk;

        public SimulateTask(int from, int to, double[][] all, int chunk) {
            this.from = from;
            this.to = to;
            this.all = all;
            this.chunk = chunk;
        }

        @Override
        protected Boolean compute() {
            if (from - to > chunk) {
                int mid = from + to / 2;
                SimulateTask left = new SimulateTask(from, mid, all, chunk);
                SimulateTask right = new SimulateTask(mid, to, all, chunk);
                left.fork();
                right.compute();
                left.join();
                return true;
            } else {
                for (int i = from; i < to; i++) {
                    NormalDistribution normal = new NormalDistribution(new Well1024a(++seed), 0, 1);//sqrt(errorVars[col]));
                    normal.sample();

                    if (verbose && (i + 1) % 50 == 0)
                        System.out.println("Simulating " + (i + 1));

                    for (int col : tierIndices) {
                        double value = normal.sample() * sqrt(errorVars[col]);

                        for (int j = 0; j < parents[col].length; j++) {
                            value += all[parents[col][j]][i] * coefs[col][j];
                        }

                        value += means[col];

                        all[col][i] = value;
                    }
                }

                return true;
            }
        }
    }

    if (graph instanceof TimeLagGraph) {
        sampleSize += 200;
    }

    double[][] all = new double[variableNodes.size()][sampleSize];

    int chunk = sampleSize / ForkJoinPoolInstance.getInstance().getPool().getParallelism() + 1;

    ForkJoinPoolInstance.getInstance().getPool().invoke(new SimulateTask(0, sampleSize, all, chunk));

    if (graph instanceof TimeLagGraph) {
        int[] rem = new int[200];
        for (int i = 0; i < 200; ++i) {
            rem[i] = i;
        }
        BoxDataSet dat = new BoxDataSet(new VerticalDoubleDataBox(all), variableNodes);
        dat.removeRows(rem);
        return dat;
    }

    return new BoxDataSet(new VerticalDoubleDataBox(all), variableNodes);
}

From source file:com.winterwell.maths.stats.algorithms.KalmanFilterTest.java

@Test
public void testCannonball() {
    // simulates the flight of a cannonball (only taking gravity and initial thrust into account)

    // number of iterations
    final int iterations = 144;
    // discrete time interval
    final double dt = 0.1d;
    // position measurement noise (meter)
    final double measurementNoise = 30d;
    // the initial velocity of the cannonball
    final double initialVelocity = 100;
    // shooting angle
    final double angle = 45;

    final Cannonball cannonball = new Cannonball(dt, angle, initialVelocity);

    final double speedX = cannonball.getXVelocity();
    final double speedY = cannonball.getYVelocity();

    // A = [ 1, dt, 0,  0 ]  =>  x(n+1) = x(n) + vx(n)
    //     [ 0,  1, 0,  0 ]  => vx(n+1) =        vx(n)
    //     [ 0,  0, 1, dt ]  =>  y(n+1) =              y(n) + vy(n)
    //     [ 0,  0, 0,  1 ]  => vy(n+1) =                     vy(n)
    final Matrix A = new DenseMatrix(
            new double[][] { { 1, dt, 0, 0 }, { 0, 1, 0, 0 }, { 0, 0, 1, dt }, { 0, 0, 0, 1 } });

    // The control vector, which adds acceleration to the kinematic equations.
    // 0          =>  x(n+1) =  x(n+1)
    // 0          => vx(n+1) = vx(n+1)
    // -9.81*dt^2 =>  y(n+1) =  y(n+1) - 1/2 * 9.81 * dt^2
    // -9.81*dt   => vy(n+1) = vy(n+1) - 9.81 * dt
    final Vector controlVector = new DenseVector(new double[] { 0, 0, 0.5 * -9.81 * dt * dt, -9.81 * dt });

    //        // The control matrix B only expects y and vy, see control vector
    //        final Matrix B = MatrixUtils.createRealMatrix(new double[][] {
    //                { 0, 0, 0, 0 },
    //                { 0, 0, 0, 0 },
    //                { 0, 0, 1, 0 },
    //                { 0, 0, 0, 1 }
    //        });

    // We only observe the x/y position of the cannonball
    final Matrix H = new DenseMatrix(
            new double[][] { { 1, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 1, 0 }, { 0, 0, 0, 0 } });

    // our guess of the initial state.
    final Vector initialState = new DenseVector(new double[] { 0, speedX, 0, speedY });

    // the initial error covariance matrix, the variance = noise^2
    final double var = measurementNoise * measurementNoise;
    final Matrix initialErrorCovariance = new DenseMatrix(
            new double[][] { { var, 0, 0, 0 }, { 0, 1e-3, 0, 0 }, { 0, 0, var, 0 }, { 0, 0, 0, 1e-3 } });

    // we assume no process noise -> zero matrix
    final Matrix Q = new DenseMatrix(4, 4);

    // the measurement covariance matrix
    final Matrix R = new DenseMatrix(
            new double[][] { { var, 0, 0, 0 }, { 0, 1e-3, 0, 0 }, { 0, 0, var, 0 }, { 0, 0, 0, 1e-3 } });

    //        final ProcessModel pm = new DefaultProcessModel(A, B, Q, initialState, initialErrorCovariance);
    //        final MeasurementModel mm = new DefaultMeasurementModel(H, R);
    final KalmanFilter filter = new KalmanFilter(4, 4);
    filter.setTransitionMatrix(A);/*from   ww  w .j a  v a2s. co m*/
    filter.setTransitionNoise(Q);
    filter.setEmissionMatrix(H);
    filter.setEmissionNoise(R);

    Gaussian state = new Gaussian(initialState, initialErrorCovariance);

    final RandomGenerator rng = new Well19937c(1000);
    final NormalDistribution dist = new NormalDistribution(rng, 0, measurementNoise);

    for (int i = 0; i < iterations; i++) {
        // get the "real" cannonball position
        double x = cannonball.getX();
        double y = cannonball.getY();

        // apply measurement noise to current cannonball position
        double nx = x + dist.sample();
        double ny = y + dist.sample();

        cannonball.step();

        state = filter.predict(state, controlVector);
        // correct the filter with our measurements
        state = filter.correct(state, new DenseVector(new double[] { nx, 0, ny, 0 }));

        // state estimate shouldn't be larger than the measurement noise
        double diff = FastMath.abs(cannonball.getY() - state.getMean().get(2));
        Assert.assertTrue(Precision.compareTo(diff, measurementNoise, 1e-6) < 0);
    }

    // error covariance of the x/y-position should be already very low (< 3m std dev = 9 variance)

    Assert.assertTrue(Precision.compareTo(state.getCovar().get(0, 0), 9, 1e-6) < 0);

    Assert.assertTrue(Precision.compareTo(state.getCovar().get(2, 2), 9, 1e-6) < 0);
}

From source file:edu.cmu.tetrad.sem.LargeScaleSimulation.java

public double[][] getUncorrelatedGaussianShocks(int sampleSize) {
    NormalDistribution normal = new NormalDistribution(new Well1024a(++seed), 0, 1);

    int numVars = variableNodes.size();
    setupModel(numVars);/*from  w  w w .ja v  a2  s  .  co m*/

    double[][] shocks = new double[sampleSize][numVars];

    for (int i = 0; i < sampleSize; i++) {
        for (int j = 0; j < numVars; j++) {
            shocks[i][j] = normal.sample() * sqrt(errorVars[j]);
        }
    }

    return shocks;
}

From source file:edu.cmu.tetrad.sem.LargeScaleSimulation.java

/**
 * Simulates data using the model X = (I - B)Y^-1 * e. Errors are uncorrelated.
 *
 * @param sampleSize The nubmer of samples to draw.
 *//* w w w  .ja v a  2  s  . co m*/
public DataSet simulateDataReducedForm(int sampleSize) {
    if (sampleSize < 1)
        throw new IllegalArgumentException("Sample size must be >= 1: " + sampleSize);

    int size = variableNodes.size();
    setupModel(size);

    NormalDistribution normal = new NormalDistribution(new Well1024a(++seed), 0, 1);

    TetradMatrix B = new TetradMatrix(getCoefficientMatrix());
    TetradMatrix iMinusBInv = TetradAlgebra.identity(B.rows()).minus(B).inverse();

    double[][] all = new double[variableNodes.size()][sampleSize];

    for (int row = 0; row < sampleSize; row++) {
        TetradVector e = new TetradVector(B.rows());

        for (int j = 0; j < e.size(); j++) {
            e.set(j, normal.sample() * sqrt(errorVars[j]));
        }

        TetradVector x = iMinusBInv.times(e);

        for (int j = 0; j < x.size(); j++) {
            all[j][row] = x.get(j);
        }
    }

    List<Node> continuousVars = new ArrayList<>();

    for (Node node : getVariableNodes()) {
        final ContinuousVariable var = new ContinuousVariable(node.getName());
        var.setNodeType(node.getNodeType());
        continuousVars.add(var);
    }

    BoxDataSet boxDataSet = new BoxDataSet(new VerticalDoubleDataBox(all), continuousVars);
    return DataUtils.restrictToMeasured(boxDataSet);
}

From source file:org.apache.accumulo.core.file.rfile.RolllingStatsTest.java

@Test
public void testNormal() {
    NormalDistribution nd = new NormalDistribution(new Well19937c(42), 200, 20);
    testDistribrution(() -> (int) nd.sample());
}

From source file:org.asoem.greyfish.utils.math.RandomGenerators.java

/**
 * Generates a random value for the normal distribution with the mean equal to {@code mu} and standard deviation
 * equal to {@code sigma}./*from www.j  a  v  a 2  s  . c  o m*/
 *
 * @param mu    the mean of the distribution
 * @param sigma the standard deviation of the distribution
 * @return a random value for the given normal distribution
 */
public static double nextNormal(final RandomGenerator rng, final double mu, final double sigma) {
    final NormalDistribution normalDistribution = new NormalDistribution(rng, mu, sigma,
            NormalDistribution.DEFAULT_INVERSE_ABSOLUTE_ACCURACY);
    while (true) {
        final double sample = normalDistribution.sample();
        if (!Doubles.isFinite(sample)) {
            logger.warn("Discarding non finite sample from normal distribution (mu={}, sigma={}): {}", mu,
                    sigma, sample);
            continue;
        }
        return sample;
    }
}