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

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

Introduction

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

Prototype

int nextInt(int n);

Source Link

Document

Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.

Usage

From source file:com.cloudera.oryx.app.traffic.TrafficUtil.java

public static void main(String[] args) throws Exception {
    if (args.length < 3) {
        System.err.println("usage: TrafficUtil [hosts] [requestIntervalMS] [threads] [... other args]");
        return;//from  w ww  . ja v a2  s . c o m
    }

    String[] hostStrings = COMMA.split(args[0]);
    Preconditions.checkArgument(hostStrings.length >= 1);
    int requestIntervalMS = Integer.parseInt(args[1]);
    Preconditions.checkArgument(requestIntervalMS >= 0);
    int numThreads = Integer.parseInt(args[2]);
    Preconditions.checkArgument(numThreads >= 1);

    String[] otherArgs = new String[args.length - 3];
    System.arraycopy(args, 3, otherArgs, 0, otherArgs.length);

    List<URI> hosts = Arrays.stream(hostStrings).map(URI::create).collect(Collectors.toList());

    int perClientRequestIntervalMS = numThreads * requestIntervalMS;

    Endpoints alsEndpoints = new Endpoints(ALSEndpoint.buildALSEndpoints());
    AtomicLong requestCount = new AtomicLong();
    AtomicLong serverErrorCount = new AtomicLong();
    AtomicLong clientErrorCount = new AtomicLong();
    AtomicLong exceptionCount = new AtomicLong();

    long start = System.currentTimeMillis();
    ExecUtils.doInParallel(numThreads, numThreads, true, i -> {
        RandomGenerator random = RandomManager.getRandom(Integer.toString(i).hashCode() ^ System.nanoTime());
        ExponentialDistribution msBetweenRequests;
        if (perClientRequestIntervalMS > 0) {
            msBetweenRequests = new ExponentialDistribution(random, perClientRequestIntervalMS);
        } else {
            msBetweenRequests = null;
        }

        ClientConfig clientConfig = new ClientConfig();
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(numThreads);
        connectionManager.setDefaultMaxPerRoute(numThreads);
        clientConfig.property(ApacheClientProperties.CONNECTION_MANAGER, connectionManager);
        clientConfig.connectorProvider(new ApacheConnectorProvider());
        Client client = ClientBuilder.newClient(clientConfig);

        try {
            while (true) {
                try {
                    WebTarget target = client.target("http://" + hosts.get(random.nextInt(hosts.size())));
                    Endpoint endpoint = alsEndpoints.chooseEndpoint(random);
                    Invocation invocation = endpoint.makeInvocation(target, otherArgs, random);

                    long startTime = System.currentTimeMillis();
                    Response response = invocation.invoke();
                    try {
                        response.readEntity(String.class);
                    } finally {
                        response.close();
                    }
                    long elapsedMS = System.currentTimeMillis() - startTime;

                    int statusCode = response.getStatusInfo().getStatusCode();
                    if (statusCode >= 400) {
                        if (statusCode >= 500) {
                            serverErrorCount.incrementAndGet();
                        } else {
                            clientErrorCount.incrementAndGet();
                        }
                    }

                    endpoint.recordTiming(elapsedMS);

                    if (requestCount.incrementAndGet() % 10000 == 0) {
                        long elapsed = System.currentTimeMillis() - start;
                        log.info("{}ms:\t{} requests\t({} client errors\t{} server errors\t{} exceptions)",
                                elapsed, requestCount.get(), clientErrorCount.get(), serverErrorCount.get(),
                                exceptionCount.get());
                        for (Endpoint e : alsEndpoints.getEndpoints()) {
                            log.info("{}", e);
                        }
                    }

                    if (msBetweenRequests != null) {
                        int desiredElapsedMS = (int) Math.round(msBetweenRequests.sample());
                        if (elapsedMS < desiredElapsedMS) {
                            Thread.sleep(desiredElapsedMS - elapsedMS);
                        }
                    }
                } catch (Exception e) {
                    exceptionCount.incrementAndGet();
                    log.warn("{}", e.getMessage());
                }
            }
        } finally {
            client.close();
        }
    });
}

From source file:edu.oregonstate.eecs.mcplan.ml.GaussianMixtureModel.java

/**
 * @param args//w ww  .j a  v a2s . c  o  m
 */
public static void main(final String[] args) {
    final RandomGenerator rng = new MersenneTwister(42);
    final ArrayList<double[]> data = new ArrayList<double[]>();

    // This data displays some problems with singular covariance estimates,
    // perhaps due to "multicollinearity" in the data.
    //      for( int x = -1; x <= 1; ++x ) {
    //         for( int y = -1; y <= 1; ++y ) {
    //            data.add( new double[] { x, y } );
    //            data.add( new double[] { x + 10, y + 10} );
    //            data.add( new double[] { x + 20, y + 20} );
    //            data.add( new double[] { x + 30, y + 30} );
    //         }
    //      }

    final int nsamples = 1000;
    final double[][] mu = new double[][] { new double[] { 0, 0 }, new double[] { 5, 0 }, new double[] { 0, 5 },
            new double[] { 5, 5 } };
    final double[][] Sigma = new double[][] { new double[] { 1, 0 }, new double[] { 0, 1 } };
    final MultivariateNormalDistribution[] p = new MultivariateNormalDistribution[4];
    for (int i = 0; i < 4; ++i) {
        p[i] = new MultivariateNormalDistribution(rng, mu[i], Sigma);
    }
    for (int i = 0; i < nsamples; ++i) {
        final int c = rng.nextInt(4);
        final double[] x = p[c].sample();
        data.add(x);
    }

    // Perturb data
    //      for( final double[] x : data ) {
    //         for( int i = 0; i < x.length; ++i ) {
    //            final double r = rng.nextGaussian() / 1.0;
    //            x[i] += r;
    //         }
    //      }

    double best_bic = Double.MAX_VALUE;
    int best_k = 0;
    for (int k = 1; k <= 6; ++k) {
        System.out.println("*** k = " + k);
        final GaussianMixtureModel gmm = new GaussianMixtureModel(k, data.toArray(new double[data.size()][]),
                10e-5, rng);

        gmm.run();
        for (int i = 0; i < gmm.mu().length; ++i) {
            System.out.println("Center " + i + ": " + gmm.mu()[i]);
        }

        final double bic = ScoreFunctions.bic(data.size(), gmm.nparameters(), gmm.logLikelihood());
        System.out.println("BIC = " + bic);
        System.out.println("ll = " + gmm.logLikelihood());
        gmm.debug();
        if (bic < best_bic) {
            best_bic = bic;
            best_k = k;
        }
    }
    System.out.println("Best model: k = " + best_k);
}

From source file:edu.oregonstate.eecs.mcplan.domains.sailing.SailingVisualization.java

public static void main(final String[] argv) {
    final RandomGenerator rng = new MersenneTwister(41);
    final int V = 1;
    final int T = 30;
    final int dim = 10;
    final int scale = 1;
    final double slip = 0.1;
    final double p = 0.2;

    //      final SailingState.Factory state = new SailingWorlds.EmptyRectangleFactory( V, T, 10, 10 );
    ////      final SailingState state = SailingWorlds.squareIsland( T, 15, 5 );
    ////      final SailingState.Factory state = new SailingWorlds.RandomObstaclesFactory( rng, p, T, 10 );
    //      final SailingFsssModel model = new SailingFsssModel( rng, state );
    //      final int viz_scale = 10;
    //      final SailingVisualization vis = new SailingVisualization( model, viz_scale );

    final RandomGenerator world_rng = new MersenneTwister(43);
    final SailingState.Factory state_factory = new SailingWorlds.RandomObstaclesFactory(p, V, T, dim);
    final SailingFsssModel model = new SailingFsssModel(world_rng, state_factory);
    for (int i = 0; i < 2; ++i) {
        SailingState s = model.initialState();
        System.out.println("Initial state:");
        System.out.println(s);/*from  ww  w  .  j  av a2s. c o m*/
        final SailingFsssModel sim_model = (SailingFsssModel) model.create(rng);
        while (!s.isTerminal()) {
            final SailingAction a = new SailingAction(rng.nextInt(SailingState.Nwind_directions));
            s = sim_model.sampleTransition(s, a);
            System.out.println(s);
        }
    }

}

From source file:fingerprints.helper.RandomNumber.java

/**
 * Mersenne Twister Random Number//  w  w w. ja  v  a 2s  .  co  m
 *
 * @param maximum
 * @return
 */
public static long generateMersenneTwisterRandomNumber(int maximum) {
    RandomGenerator rg = new RandomAdaptor(new MersenneTwister());
    return rg.nextInt(maximum);
}

From source file:fingerprints.helper.RandomNumber.java

/**
 * Mersenne Twister Random Number for a hashcode within a range between 0 to maximum
 *
 * @param maximum//w  ww . j av a  2  s .c  om
 * @param hashCode
 * @return
 */
public static long generateMersenneTwisterRandomNumber(int maximum, long hashCode) {
    RandomGenerator rg = new RandomAdaptor(new MersenneTwister(hashCode));
    return rg.nextInt(maximum);
}

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

public static final <S extends Sequence<S>> int createUniformMutation(S sequence, RandomGenerator generator) {
    return createUniformMutation(sequence, generator, types[generator.nextInt(3)]);
}

From source file:edu.oregonstate.eecs.mcplan.util.ListUtil.java

public static <T> void randomShuffle(final RandomGenerator rng, final T[] v) {
    for (int i = v.length - 1; i >= 0; --i) {
        final int idx = rng.nextInt(i + 1);
        final T t = v[idx];
        v[idx] = v[i];//from w  ww.  j  a v a 2  s  .  c  om
        v[i] = t;
    }
}

From source file:edu.oregonstate.eecs.mcplan.util.ListUtil.java

public static void randomShuffle(final RandomGenerator rng, final int[] v) {
    for (int i = v.length - 1; i >= 0; --i) {
        final int idx = rng.nextInt(i + 1);
        final int t = v[idx];
        v[idx] = v[i];//from   w  w  w .ja v  a  2s  .c  o  m
        v[i] = t;
    }
}

From source file:edu.oregonstate.eecs.mcplan.util.ListUtil.java

public static <T> void randomShuffle(final RandomGenerator rng, final List<T> v) {
    for (int i = v.size() - 1; i >= 0; --i) {
        final int idx = rng.nextInt(i + 1);
        final T t = v.get(idx);
        v.set(idx, v.get(i));//from  w  w  w. j  ava 2s.  c  o m
        v.set(i, t);
    }
}

From source file:com.github.rinde.rinsim.scenario.ScenarioTestUtil.java

public static Scenario create(long seed) {
    final int endTime = 3 * 60 * 60 * 1000;
    Scenario.Builder b = Scenario.builder()
            .addModel(PlaneRoadModel.supplier(new Point(0, 0), new Point(10, 10), SI.KILOMETER,
                    Measure.valueOf(50d, NonSI.KILOMETERS_PER_HOUR)))
            .addModel(DefaultPDPModel.supplier(TimeWindowPolicies.LIBERAL)).addEvents(Collections.nCopies(10,
                    new AddVehicleEvent(-1, VehicleDTO.builder().startPosition(new Point(5, 5)).build())));

    RandomGenerator rng = new MersenneTwister(seed);
    for (int i = 0; i < 20; i++) {
        long announceTime = rng.nextInt(DoubleMath.roundToInt(endTime * .8, RoundingMode.FLOOR));
        b.addEvent(new AddParcelEvent(ParcelDTO
                .builder(new Point(rng.nextDouble() * 10, rng.nextDouble() * 10),
                        new Point(rng.nextDouble() * 10, rng.nextDouble() * 10))
                .orderAnnounceTime(announceTime).pickupTimeWindow(new TimeWindow(announceTime, endTime))
                .deliveryTimeWindow(new TimeWindow(announceTime, endTime)).neededCapacity(0).build()));
    }/*from  w  w w. ja  v a 2 s  .  c  o  m*/

    b.addEvent(new TimedEvent(PDPScenarioEvent.TIME_OUT, endTime)).scenarioLength(endTime)
            .stopCondition(new EndTimeStopCondition(endTime));

    b.addEventType(PDPScenarioEvent.ADD_DEPOT);

    return b.build();
}