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

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

Introduction

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

Prototype

public Well1024a(long seed) 

Source Link

Document

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

Usage

From source file:com.milaboratory.core.io.sequence.fasta.FastaWriterTest.java

private static SingleRead randomRead(long id) {
    Well1024a random = new Well1024a(id);
    Bit2Array seq = new Bit2Array(50 + random.nextInt(150));
    for (int i = 0; i < seq.size(); ++i)
        seq.set(i, (byte) random.nextInt(NucleotideSequence.ALPHABET.size()));
    byte[] quality = new byte[seq.size()];
    Arrays.fill(quality, SequenceQuality.GOOD_QUALITY_VALUE);
    return new SingleReadImpl(id,
            new NSequenceWithQuality(new NucleotideSequence(seq), new SequenceQuality(quality)), "id" + id);
}

From source file:com.milaboratory.core.io.util.TestUtil.java

public static File createRandomFile(long seed, int avLinesCount) throws IOException {
    File temp = File.createTempFile("temp" + seed, "tmp");
    temp.deleteOnExit();//from  w ww  . j  a  v a 2  s. c o m
    FileOutputStream output = new FileOutputStream(temp);
    Well1024a random = new Well1024a(seed);

    int numberOfLines = avLinesCount + random.nextInt(10);
    for (int i = 0; i < numberOfLines; ++i) {
        StringBuilder sb = new StringBuilder();
        for (int j = (1 + random.nextInt(100)); j >= 0; --j)
            sb.append(random.nextInt(100));
        String string = sb.toString();
        byte[] bytes = string.getBytes();
        output.write(bytes);
        output.write('\n');
    }
    output.close();
    return temp;
}

From source file:com.milaboratory.core.io.sequence.fasta.FastaReaderTest.java

private static TestItem createTestData(long seed, int readsCount, boolean withWildcards) throws IOException {
    Well1024a rnd = new Well1024a(seed);

    File tempFile = File.createTempFile("temp" + seed, ".fasta");
    tempFile.deleteOnExit();//from   w w w. j av a 2s. c om
    FileOutputStream output = new FileOutputStream(tempFile);

    SingleRead[] reads = new SingleRead[readsCount];

    WildcardSymbol[] wildcards = NucleotideSequence.ALPHABET.getAllWildcards().toArray(new WildcardSymbol[0]);
    long id = 0;
    for (int i = 0; i < readsCount; ++i) {
        char[] seq = new char[50 + rnd.nextInt(100)];
        char[] seqExp = new char[seq.length];

        int qPointer = 0;
        byte[] qualityData = new byte[seq.length];
        Arrays.fill(qualityData, SequenceQuality.GOOD_QUALITY_VALUE);
        for (int j = 0; j < seq.length; ++j) {
            seq[j] = seqExp[j] = NucleotideSequence.ALPHABET.symbolFromCode((byte) rnd.nextInt(4));
            if (j != 0 && j != seq.length - 1 && ((4 * j) % seq.length == 0) && rnd.nextBoolean()) {
                //next line for sequence
                seq[j] = seqExp[j] = '\n';
                --qPointer;
            } else if (withWildcards && j % 5 == 0) {//wildcard
                WildcardSymbol wildcard = wildcards[rnd.nextInt(wildcards.length)];
                if (NucleotideSequence.ALPHABET.codeFromSymbol(wildcard.getSymbol()) == -1) {
                    seq[j] = wildcard.getSymbol();
                    seqExp[j] = NucleotideSequence.ALPHABET
                            .symbolFromCode(wildcard.getUniformlyDistributedSymbol(id ^ (j + qPointer)));//as used in FastaReader#getSequenceWithQuality(..)
                    qualityData[j + qPointer] = SequenceQuality.BAD_QUALITY_VALUE;
                }
            }
        }
        String description = ">seq" + i;
        String sequenceString = new String(seq);
        output.write(description.getBytes());
        output.write('\n');
        output.write(sequenceString.getBytes());
        output.write('\n');

        reads[i] = new SingleReadImpl(id,
                new NSequenceWithQuality(new NucleotideSequence(new String(seqExp).replace("\n", "")),
                        new SequenceQuality(Arrays.copyOfRange(qualityData, 0, seq.length + qPointer))),
                description.substring(1));
        ++id;
    }
    output.close();

    return new TestItem(tempFile, reads);
}

From source file:cc.redberry.groovy.feyncalc.pairedchi.ParallelExpandTest.java

@Test
public void tes2() throws Exception {

    RandomGenerator rw = new Well1024a(new SecureRandom().nextInt());
    for (int i = 0; i < 100; ++i) {
        int seed = rw.nextInt();
        System.out.println(i + "  " + seed);
        CC.resetTensorNames(seed);/*from ww  w  . j  a  va  2  s .c o  m*/

        setAntiSymmetric("e_abcd");
        //            setAntiSymmetric("D_ac");
        //            setAntiSymmetric("B_abc");
        //            setAntiSymmetric("A_abc");

        RandomTensor rnd = new RandomTensor(false);
        rnd.reset(seed);

        rnd.addToNamespace(parse("F_a"));
        rnd.addToNamespace(parse("A_ab"));
        rnd.addToNamespace(parse("B_abc"));
        rnd.addToNamespace(parse("D_ac"));
        rnd.addToNamespace(parse("g_ac"));
        rnd.addToNamespace(parse("e_abcd"));

        Sum t1 = (Sum) rnd.nextSum(100, 8, IndicesFactory.EMPTY_INDICES);
        Sum t2 = (Sum) rnd.nextSum(100, 8, IndicesFactory.EMPTY_INDICES);
        t1 = (Sum) parseExpression("e_abcd*e_pqrs = 0").transform(t1);
        t2 = (Sum) parseExpression("e_abcd*e_pqrs = 0").transform(t2);
        System.out.println(t1.size() + "  " + t2.size());
        Transformation tr = new TransformationCollection(EliminateMetricsTransformation.ELIMINATE_METRICS,
                Tensors.parseExpression("A_ab*B^bac = T^c"), Tensors.parseExpression("A_ab*A^ba = xx"),
                Tensors.parseExpression("D_ab*D^ba = yy"),
                EliminateDueSymmetriesTransformation.ELIMINATE_DUE_SYMMETRIES,
                new LeviCivitaSimplifyTransformation(parseSimple("e_abcd"), true),
                ExpandAndEliminateTransformation.EXPAND_AND_ELIMINATE,
                Tensors.parseExpression("A_ab*B^bac = T^c"), Tensors.parseExpression("A_ab*A^ba = xx"),
                Tensors.parseExpression("D_ab*D^ba = yy"), Tensors.parseExpression("d^a_a = 4"));
        t2 = (Sum) ApplyIndexMapping.renameDummy(t2, TensorUtils.getAllIndicesNamesT(t1).toArray());

        Tensor r1 = new ExpandTransformation(tr).transform(multiplyAndRenameConflictingDummies(t1, t2));
        Tensor r3 = new ParallelExpand(t1, t2, 4, tr, null).expand();

        Assert.assertTrue(TensorUtils.isZero(tr.transform(subtract(r1, r3))));
    }
}

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   w  w w.ja  v a  2 s .c o  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: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  ww.j  a v  a  2 s .com
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: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);/*  w  w w.j  a  v a2 s  .c  o  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:org.briljantframework.data.dataframe.transform.TransformationTests.java

@Before
public void setUp() throws Exception {
    NormalDistribution distribution = new NormalDistribution(new Well1024a(100), 10, 2,
            NormalDistribution.DEFAULT_INVERSE_ABSOLUTE_ACCURACY);
    train = getBuilder().set("a", Vector.fromSupplier(distribution::sample, 100))
            .set("b", Vector.fromSupplier(distribution::sample, 100))
            .set("c", Vector.fromSupplier(distribution::sample, 100)).build();

    test = getBuilder().set("a", Vector.fromSupplier(distribution::sample, 100))
            .set("c", Vector.fromSupplier(distribution::sample, 100))
            .set("b", Vector.fromSupplier(distribution::sample, 80)).build();

}

From source file:org.orekit.data.NutationCodecTest.java

@Test
public void testKeySymmetry() {

    RandomGenerator random = new Well1024a(0x8fef7f6f99ad5d56l);
    int[] multipliers = new int[15];
    for (int i = 0; i < 100000; ++i) {
        Arrays.fill(multipliers, 0);
        int nb = 1 + random.nextInt(7);
        for (int k = 0; k < nb; ++k) {
            int index = random.nextInt(15);
            while (multipliers[index] == 0) {
                multipliers[index] = random.nextInt(128) - 64;
            }//from w  w w .  ja  va 2  s.  c om
        }
        long key = NutationCodec.encode(multipliers);
        int[] rebuilt = NutationCodec.decode(key);
        for (int k = 0; k < multipliers.length; ++k) {
            Assert.assertEquals(multipliers[k], rebuilt[k]);
        }
    }

}

From source file:org.orekit.frames.TopocentricFrameTest.java

@Test
public void testPointAtDistance() throws OrekitException {

    RandomGenerator random = new Well1024a(0xa1e6bd5cd0578779l);
    final OneAxisEllipsoid earth = new OneAxisEllipsoid(Constants.WGS84_EARTH_EQUATORIAL_RADIUS,
            Constants.WGS84_EARTH_FLATTENING, itrf);
    final AbsoluteDate date = AbsoluteDate.J2000_EPOCH;

    for (int i = 0; i < 20; ++i) {
        // we don't need uniform point on the sphere, just a few different test configurations
        double latitude = FastMath.PI * (0.5 - random.nextDouble());
        double longitude = 2 * FastMath.PI * random.nextDouble();
        TopocentricFrame topo = new TopocentricFrame(earth, new GeodeticPoint(latitude, longitude, 0.0),
                "topo");
        Transform transform = earth.getBodyFrame().getTransformTo(topo, date);
        for (int j = 0; j < 20; ++j) {
            double elevation = FastMath.PI * (0.5 - random.nextDouble());
            double azimuth = 2 * FastMath.PI * random.nextDouble();
            double range = 500000.0 * (1.0 + random.nextDouble());
            Vector3D absolutePoint = earth.transform(topo.pointAtDistance(azimuth, elevation, range));
            Vector3D relativePoint = transform.transformPosition(absolutePoint);
            double rebuiltElevation = topo.getElevation(relativePoint, topo, AbsoluteDate.J2000_EPOCH);
            double rebuiltAzimuth = topo.getAzimuth(relativePoint, topo, AbsoluteDate.J2000_EPOCH);
            double rebuiltRange = topo.getRange(relativePoint, topo, AbsoluteDate.J2000_EPOCH);
            Assert.assertEquals(elevation, rebuiltElevation, 1.0e-12);
            Assert.assertEquals(azimuth, MathUtils.normalizeAngle(rebuiltAzimuth, azimuth), 1.0e-12);
            Assert.assertEquals(range, rebuiltRange, 1.0e-12 * range);
        }/*www .  j  av a  2 s. co  m*/
    }
}