Example usage for org.apache.commons.math3.distribution ExponentialDistribution ExponentialDistribution

List of usage examples for org.apache.commons.math3.distribution ExponentialDistribution ExponentialDistribution

Introduction

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

Prototype

public ExponentialDistribution(double mean, double inverseCumAccuracy) 

Source Link

Document

Create an exponential distribution with the given mean.

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;// w  ww  .  j a v a  2 s. com
    }

    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:adams.data.distribution.Exponential.java

/**
 * Returns the configured distribution./*from w  ww  . j  av  a 2  s  . c  o  m*/
 *
 * @return      the distribution
 */
@Override
public RealDistribution getRealDistribution() {
    return new ExponentialDistribution(m_Mean, m_InverseCumAccuracy);
}

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

private double drawWindSpeed(final RandomGenerator rng, final int date) {
    final RealDistribution wind_pdf = new ExponentialDistribution(rng, params.wind_mean);
    return wind_pdf.sample();
}

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

private double drawEndOfFire(final RandomGenerator rng) {
    final RealDistribution end_pdf = new ExponentialDistribution(rng, params.fire_average_end_day);
    return 1 + end_pdf.sample();
}

From source file:edu.cmu.tetrad.util.RandomUtil.java

/**
 * Returns the next random number drawn from the Exponential distribution with the given lambda.
 *
 * @param lambda The rate parameter. See Wikipedia.
 * @return Ibid.//from ww w .j a v  a2  s .  c  o  m
 */
public double nextExponential(double lambda) {
    return new ExponentialDistribution(randomGenerator, lambda).sample();
}

From source file:io.coala.random.impl.RandomDistributionFactoryImpl.java

@Override
public RandomNumberDistribution<Double> getExponential(final RandomNumberStream rng, final Number mean) {
    final RealDistribution dist = new ExponentialDistribution(
            RandomNumberStream.Util.asCommonsRandomGenerator(rng), mean.doubleValue());
    return new RandomNumberDistribution<Double>() {
        @Override//ww  w. ja  v  a  2  s  .c  o  m
        public Double draw() {
            return dist.sample();
        }
    };
}

From source file:nl.rivm.cib.episim.model.disease.infection.MSEIRSTest.java

public static Observable<Entry<Double, long[]>> stochasticGillespie(final SIRConfig config,
        final double maxDt) {
    return Observable.create(sub -> {
        final double gamma = 1. / config.recovery();
        final double beta = gamma * config.reproduction();
        final long[] y = config.population();
        final double[] T = config.t();
        final double dt = Double.isFinite(maxDt) && maxDt > 0 ? maxDt : T[1];

        final Long seed = config.seed();
        final RandomGenerator rng = new MersenneTwister(seed == null ? System.currentTimeMillis() : seed);

        for (double t = T[0]; t < T[1];) {
            publishCopy(sub, t, y);/*from   www. ja v a2s .  com*/

            // SIR terms (flow rates)
            final double n = y[0] + y[1] + y[2], flow_si = beta * y[0] * y[1] / n, flow_ir = gamma * y[1],
                    flow_sum = flow_si + flow_ir;

            final double t2 = t + new ExponentialDistribution(rng, 1d / flow_sum).sample();

            // publish intermediate values
            for (double t1 = Math.min(t2, t + dt), tMax = Math.min(T[1], t2); t1 < tMax; t1 += dt)
                publishCopy(sub, t1, y);

            // advance time to next event
            t = t2;

            // determine event (s->i, i->r, ...)
            if (rng.nextDouble() < flow_si / flow_sum) {
                y[0]--; // from S
                y[1]++; // to I
            } else {
                y[1]--; // from I
                y[2]++; // to R
                if (y[0] != 0 && y[1] == 0) {
                    y[0]--; // from S
                    y[1]++; // to I
                }
            }
        }
        sub.onComplete();
    });
}

From source file:nl.rivm.cib.episim.model.disease.infection.MSEIRSTest.java

public static Observable<Entry<Double, long[]>> stochasticSellke(final SIRConfig config, final double maxDt) {
    return Observable.create(sub -> {
        final double beta = config.reproduction() / config.recovery();
        final long[] y = config.population();
        final double[] T = config.t();
        final double dt = Double.isFinite(maxDt) && maxDt > 0 ? maxDt : T[1];

        final Long seed = config.seed();
        final RandomGenerator rng = new MersenneTwister(seed == null ? System.currentTimeMillis() : seed);

        final ExponentialDistribution resistanceDist = new ExponentialDistribution(rng, 1),
                recoverDist = new ExponentialDistribution(rng, config.recovery());

        // pending infections (mapping resistance -> amount)
        final TreeMap<Double, Integer> tInfect = IntStream.range(0, (int) y[0])
                .mapToObj(i -> resistanceDist.sample())
                .collect(Collectors.toMap(r -> r, r -> 1, Integer::sum, TreeMap::new));
        // pending recoveries (mapping time -> amount)
        final TreeMap<Double, Integer> tRecover = new TreeMap<>();

        double cumPres = 0;
        // Re-initialize infectives as susceptibles with zero resistance
        tInfect.put(cumPres, (int) y[1]);
        y[0] += y[1]; // I -> S
        y[1] -= y[1]; // I -> 0
        for (double t = T[0]; t < T[1];) {
            publishCopy(sub, t, y);/*from w w  w  . j  ava 2 s  . c  om*/
            final long localPopSize = y[0] + y[1] + y[2];
            final Double ri = tInfect.isEmpty() ? null : tInfect.firstKey(), ti = ri == null ? null :
            // now + remaining resistance per relative pressure
            t + (ri - cumPres) / (beta * Math.max(y[1], 1) / localPopSize),
                    tr = tRecover.isEmpty() ? null : tRecover.firstKey();

            // time of next infection is earliest
            if (ti != null && (tr == null || ti < tr)) {
                final int ni = tInfect.remove(ri);
                cumPres = ri;

                // publish intermediate values
                for (double t1 = Math.min(ti, t + dt), tMax = Math.min(T[1], ti); t1 < tMax; t1 += dt)
                    publishCopy(sub, t1, y);

                // infect
                t = ti;
                y[0] -= ni; // from S
                y[1] += ni; // to I

                // schedule S_t recoveries at t+Exp(1/gamma)
                for (int i = 0; i < ni; i++)
                    tRecover.compute(t + recoverDist.sample(), (k, v) -> v == null ? 1 : v + 1);
            }
            // time of next recovery is earliest
            else if (tr != null) {
                final int nr = tRecover.remove(tr);
                if (ri != null)
                    // advance cumulative pressure by dt * relative pressure
                    cumPres += (tr - t) * beta * y[1] / localPopSize;

                // publish intermediate values
                for (double t1 = Math.min(tr, t + dt), tMax = Math.min(T[1], tr); t1 < tMax; t1 += dt)
                    publishCopy(sub, t1, y);

                // recover
                t = tr;
                y[1] -= nr; // from I
                y[2] += nr; // to R
            }
            // no events remaining
            else {
                // publish intermediate values
                for (double t1 = t + dt; t1 < T[1]; t1 += dt)
                    publishCopy(sub, t1, y);

                // time ends
                break;
            }
        }
        sub.onComplete();
    });
}