Example usage for org.apache.commons.math3.random RandomGenerator nextBoolean

List of usage examples for org.apache.commons.math3.random RandomGenerator nextBoolean

Introduction

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

Prototype

boolean nextBoolean();

Source Link

Document

Returns the next pseudorandom, uniformly distributed boolean value from this random number generator's sequence.

Usage

From source file:edu.oregonstate.eecs.mcplan.domains.firegirl.FireGirlTest.java

/**
 * @param args/*from  ww  w  . ja  va 2  s. com*/
 * @throws IOException
 */
public static void main(final String[] args) throws IOException {
    final int T = 200;
    final double discount = 0.9;
    final RandomGenerator episode_rng = new MersenneTwister(42);
    final RandomGenerator iid_rng = new MersenneTwister(43);
    final FireGirlParameters params = new FireGirlParameters(T, discount,
            new FireGirlLocalFeatureRepresenter());

    double min_suppress_cost = 0;
    final MeanVarianceAccumulator mv_suppress_cost = new MeanVarianceAccumulator();

    final ch.qos.logback.classic.Logger Log = LoggerManager.getLogger("log.domain");
    Log.setLevel(Level.WARN);

    final int Ntrials = 1;
    for (int trial = 0; trial < Ntrials; ++trial) {
        System.out.println("trial: " + trial);
        final FireGirlState s = new FireGirlState(params);
        s.setRandomInitialState(episode_rng);
        for (int t = 0; t < T; ++t) {
            Log.info(" === Year {} === ", t);
            final FireGirlAction a = (iid_rng.nextBoolean() ? FireGirlAction.LetBurn : FireGirlAction.Suppress);
            final FireGirlState.YearResult result = s.doOneYear(episode_rng, a);
            if (a == FireGirlAction.Suppress) {
                mv_suppress_cost.add(result.fire.sup_cost);
            }
            if (result.fire.sup_cost < min_suppress_cost) {
                min_suppress_cost = result.fire.sup_cost;
            }

            //            final File f = new File( "FireGirlTest_" + (t+1) + ".png" );
            //            s.writePng( f );
        }
    }

    System.out.println("min suppress cost: " + min_suppress_cost);
    System.out.println("sup_cost mean: " + mv_suppress_cost.mean());
    System.out.println("sup_cost var: " + mv_suppress_cost.variance());
}

From source file:com.github.rinde.rinsim.core.model.rand.RandomModelTest.java

static void testUnmodifiable(RandomGenerator rng) {
    boolean fail = false;
    try {/* w  ww.  jav  a2  s .co m*/
        rng.setSeed(0);
    } catch (final UnsupportedOperationException e) {
        fail = true;
    }
    assertTrue(fail);
    fail = false;
    try {
        rng.setSeed(new int[] { 0 });
    } catch (final UnsupportedOperationException e) {
        fail = true;
    }
    assertTrue(fail);
    fail = false;
    try {
        rng.setSeed(123L);
    } catch (final UnsupportedOperationException e) {
        fail = true;
    }
    assertTrue(fail);
    fail = false;

    rng.nextBoolean();
    rng.nextBytes(new byte[] {});
    rng.nextDouble();
    rng.nextFloat();
    rng.nextGaussian();
    rng.nextInt();
    rng.nextInt(1);
    rng.nextLong();
}

From source file:com.anhth12.kafka.ulti.DefaultCSVDatumGenerator.java

@Override
public Pair<String, String> generate(int id, RandomGenerator random) {
    return new Pair<>(Integer.toString(id),
            id + "," + random.nextInt(100) + ',' + random.nextBoolean() + ',' + random.nextGaussian());
}

From source file:com.cloudera.oryx.app.batch.mllib.rdf.RandomNumericRDFDataGenerator.java

@Override
public Pair<String, String> generate(int id, RandomGenerator random) {
    List<String> elements = new ArrayList<>(n + 2);
    elements.add(Integer.toString(id));
    int count = 0;
    for (int i = 0; i < n; i++) {
        boolean positive = random.nextBoolean();
        elements.add(positive ? "A" : "B");
        if (positive) {
            count++;//from w w  w. ja  v  a2 s.  c o  m
        }
    }
    elements.add(Integer.toString(count));
    return new Pair<>(Integer.toString(id), TextUtils.joinDelimited(elements, ','));
}

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

@Test
public void test4() throws Exception {
    RandomGenerator rg = new Well19937a();

    int count = 1000;
    long[] values = new long[count];

    for (int n = 0; n < 10; ++n) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        for (int i = 0; i < count; ++i) {
            final int d = rg.nextInt(63) + 1;

            values[i] = (rg.nextLong() >>> d);

            if (rg.nextBoolean())
                values[i] *= -1;//from  w  w  w . j  a v  a 2s. co  m

            final long encoded = IOUtil.encodeZigZag64(values[i]);
            Assert.assertTrue(-1L != encoded);
            IOUtil.writeRawVarint64(bos, encoded);
        }

        byte[] data = bos.toByteArray();

        ByteArrayInputStream bis = new ByteArrayInputStream(data);
        int g;
        for (int i = 0; i < count; ++i) {
            Assert.assertEquals(values[i], IOUtil.decodeZigZag64(IOUtil.readRawVarint64(bis, -1)));
        }
        Assert.assertEquals(-1L, IOUtil.readRawVarint64(bis, -1));
    }
}

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

@Test
public void test3() throws Exception {
    RandomGenerator rg = new Well19937a();

    int count = 1000;
    int[] values = new int[count];

    for (int n = 0; n < 10; ++n) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        for (int i = 0; i < count; ++i) {
            final int d = rg.nextInt(31) + 1;
            values[i] = (rg.nextInt(Integer.MAX_VALUE) >>> d);
            if (rg.nextBoolean())
                values[i] *= -1;//from w  w w.  j a va2 s. c  o  m
            final int encoded = IOUtil.encodeZigZag32(values[i]);
            Assert.assertTrue(-1 != encoded);
            IOUtil.writeRawVarint32(bos, encoded);
        }

        byte[] data = bos.toByteArray();

        ByteArrayInputStream bis = new ByteArrayInputStream(data);
        int g;
        for (int i = 0; i < count; ++i) {
            Assert.assertEquals(values[i], IOUtil.decodeZigZag32(IOUtil.readRawVarint32(bis, -1)));
        }
        Assert.assertEquals(-1, IOUtil.readRawVarint32(bis, -1));
    }
}

From source file:com.cloudera.oryx.als.common.lsh.LocationSensitiveHash.java

/**
 * @param Y item vectors to hash/*w w w .  j a v  a 2s  .c  o m*/
 */
public LocationSensitiveHash(LongObjectMap<float[]> Y, double lshSampleRatio, int numHashes) {
    Preconditions.checkNotNull(Y);
    Preconditions.checkArgument(!Y.isEmpty(), "Y is empty");

    Preconditions.checkArgument(lshSampleRatio > 0.0 && lshSampleRatio <= 1.0, "Bad LSH ratio: %s",
            lshSampleRatio);
    Preconditions.checkArgument(numHashes >= 1 && numHashes <= 64, "Bad # hashes: %s", numHashes);

    this.Y = Y;

    log.info("Using LSH sampling to sample about {}% of items", lshSampleRatio * 100.0);

    // This follows from the binomial distribution:
    double cumulativeProbability = 0.0;
    double denominator = FastMath.pow(2.0, numHashes);
    int bitsDiffering = -1;
    while (bitsDiffering < numHashes && cumulativeProbability < lshSampleRatio) {
        bitsDiffering++;
        cumulativeProbability += ArithmeticUtils.binomialCoefficientDouble(numHashes, bitsDiffering)
                / denominator;
    }

    maxBitsDiffering = bitsDiffering - 1;
    log.info("Max bits differing: {}", maxBitsDiffering);

    int features = Y.entrySet().iterator().next().getValue().length;

    RandomGenerator random = RandomManager.getRandom();
    randomVectors = new boolean[numHashes][features];
    for (boolean[] randomVector : randomVectors) {
        for (int j = 0; j < features; j++) {
            randomVector[j] = random.nextBoolean();
        }
    }

    meanVector = findMean(Y, features);

    buckets = new LongObjectMap<long[]>();
    int count = 0;
    int maxBucketSize = 0;
    for (LongObjectMap.MapEntry<float[]> entry : Y.entrySet()) {
        long signature = toBitSignature(entry.getValue());
        long[] ids = buckets.get(signature);
        if (ids == null) {
            buckets.put(signature, new long[] { entry.getKey() });
        } else {
            int length = ids.length;
            // Large majority of arrays will be length 1; all are short.
            // This is a reasonable way to store 'sets' of longs
            long[] newIDs = new long[length + 1];
            for (int i = 0; i < length; i++) {
                newIDs[i] = ids[i];
            }
            newIDs[length] = entry.getKey();
            maxBucketSize = FastMath.max(maxBucketSize, newIDs.length);
            buckets.put(signature, newIDs);
        }
        if (++count % 1000000 == 0) {
            log.info("Bucketed {} items", count);
        }
    }

    log.info("Max bucket size {}", maxBucketSize);
    log.info("Put {} items into {} buckets", Y.size(), buckets.size());
    // A separate bucket for new items, which will always be considered
    newItems = new LongSet();
}

From source file:net.myrrix.online.candidate.LocationSensitiveHash.java

/**
 * @param Y item vectors to hash/*from   www.jav  a 2s  .  c o m*/
 */
public LocationSensitiveHash(FastByIDMap<float[]> Y) {
    Preconditions.checkNotNull(Y);
    Preconditions.checkArgument(!Y.isEmpty(), "Y is empty");
    Preconditions.checkState(LSH_SAMPLE_RATIO < 1.0);

    this.Y = Y;

    log.info("Using LSH sampling to sample about {}% of items", LSH_SAMPLE_RATIO * 100.0);

    // This follows from the binomial distribution:
    double cumulativeProbability = 0.0;
    double denominator = FastMath.pow(2.0, NUM_HASHES);
    int bitsDiffering = -1;
    while (bitsDiffering < NUM_HASHES && cumulativeProbability < LSH_SAMPLE_RATIO) {
        bitsDiffering++;
        cumulativeProbability += ArithmeticUtils.binomialCoefficientDouble(NUM_HASHES, bitsDiffering)
                / denominator;
    }

    maxBitsDiffering = bitsDiffering - 1;
    log.info("Max bits differing: {}", maxBitsDiffering);

    int features = Y.entrySet().iterator().next().getValue().length;

    RandomGenerator random = RandomManager.getRandom();
    randomVectors = new boolean[NUM_HASHES][features];
    for (boolean[] randomVector : randomVectors) {
        for (int j = 0; j < features; j++) {
            randomVector[j] = random.nextBoolean();
        }
    }

    meanVector = findMean(Y, features);

    buckets = new FastByIDMap<long[]>(1000);
    int count = 0;
    int maxBucketSize = 0;
    for (FastByIDMap.MapEntry<float[]> entry : Y.entrySet()) {
        long signature = toBitSignature(entry.getValue());
        long[] ids = buckets.get(signature);
        if (ids == null) {
            buckets.put(signature, new long[] { entry.getKey() });
        } else {
            int length = ids.length;
            // Large majority of arrays will be length 1; all are short.
            // This is a reasonable way to store 'sets' of longs
            long[] newIDs = new long[length + 1];
            for (int i = 0; i < length; i++) {
                newIDs[i] = ids[i];
            }
            newIDs[length] = entry.getKey();
            maxBucketSize = FastMath.max(maxBucketSize, newIDs.length);
            buckets.put(signature, newIDs);
        }
        if (++count % 1000000 == 0) {
            log.info("Bucketed {} items", count);
        }
    }

    log.info("Max bucket size {}", maxBucketSize);
    log.info("Put {} items into {} buckets", Y.size(), buckets.size());
    // A separate bucket for new items, which will always be considered
    newItems = new FastIDSet();
}

From source file:edu.oregonstate.eecs.mcplan.domains.tamarisk.TamariskState.java

public TamariskState(final RandomGenerator rng, final TamariskParameters params,
        final DirectedGraph<Integer, DefaultEdge> graph) {
    this.rng = rng;
    this.params = params;
    habitats = new Species[params.Nreaches][params.Nhabitats];
    this.graph = graph; //params.createRandomGraph( rng.nextInt(), true );

    // Lower-variance initialization
    final boolean[] invaded = new boolean[params.Nreaches];
    final int Ninvaded = 1 + params.Nreaches / 2;
    for (int i = 0; i < Ninvaded; ++i) {
        invaded[i] = true;/* w w  w .jav a  2 s  .c o  m*/
    }
    Fn.shuffle(rng, invaded);
    final boolean[] tamarisk = new boolean[params.Nhabitats];
    final int Ntamarisk = 1 + params.Nhabitats / 2; //rng.nextInt( params.Nhabitats );
    for (int j = 0; j < Ntamarisk; ++j) {
        tamarisk[j] = true;
    }
    for (int i = 0; i < params.Nreaches; ++i) {
        if (invaded[i]) {
            Fn.shuffle(rng, tamarisk);
            for (int j = 0; j < params.Nhabitats; ++j) {
                if (tamarisk[j]) {
                    habitats[i][j] = Species.Tamarisk;
                } else {
                    habitats[i][j] = rng.nextBoolean() ? Species.Native : Species.None;
                }
            }
        } else {
            for (int j = 0; j < params.Nhabitats; ++j) {
                habitats[i][j] = rng.nextBoolean() ? Species.Native : Species.None;
            }
        }
    }

    // Seed habitats with species chosen uniformly at random
    //      for( int i = 0; i < params.Nreaches; ++i ) {
    //         for( int j = 0; j < params.Nhabitats; ++j ) {
    //            final int si = rng.nextInt( Species.values().length );
    //            habitats[i][j] = Species.values()[si];
    //         }
    //      }
}

From source file:org.asoem.greyfish.utils.collect.UnrolledListAT.java

protected static void executeRandomized(final int runs, final RandomGenerator rng, final Runnable runnable1,
        final Runnable runnable2) {
    for (int i = 0; i < runs; i++) {
        if (rng.nextBoolean()) {
            runnable1.run();/* w  w w.  j  a v a  2s  .c  om*/
            runnable2.run();
        } else {
            runnable2.run();
            runnable1.run();
        }
    }
}