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

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

Introduction

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

Prototype

@Override
public double sample() 

Source Link

Document

<p><strong>Algorithm Description</strong>: this implementation uses the <a href="http://www.jesus.ox.ac.uk/~clifford/a5/chap1/node5.html"> Inversion Method</a> to generate exponentially distributed random values from uniform deviates.</p>

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;/*ww w. ja va2s  .  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:controller.DistributionController.java

public static void exponential(double media, double extra, int size) {
    numerosGerados.clear();/*from w  w w  .  ja va2s.  co m*/
    ExponentialDistribution ex = new ExponentialDistribution(media);
    for (int i = 0; i < size; i++) {
        numerosGerados.add(extra + ex.sample());
    }
}

From source file:com.github.rinde.rinsim.scenario.measure.MetricsTest.java

static Times generateTimes(RandomGenerator rng, double intensity) {
    final ExponentialDistribution ed = new ExponentialDistribution(1000d / intensity);
    ed.reseedRandomGenerator(rng.nextLong());
    final List<Long> times = newArrayList();

    long sum = 0;
    while (sum < 1000) {
        sum += DoubleMath.roundToLong(ed.sample(), RoundingMode.HALF_DOWN);
        if (sum < 1000) {
            times.add(sum);//from w w  w  .j av  a  2 s.  c  o m
        }
    }
    return asTimes(1000, times);
}

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  a v  a 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();
    });
}

From source file:org.openmhealth.data.generator.service.TimestampedValueGroupGenerationServiceImpl.java

@Override
public Iterable<TimestampedValueGroup> generateValueGroups(MeasureGenerationRequest request) {

    ExponentialDistribution interPointDurationDistribution = new ExponentialDistribution(
            request.getMeanInterPointDuration().getSeconds());

    long totalDurationInS = Duration.between(request.getStartDateTime(), request.getEndDateTime()).getSeconds();

    OffsetDateTime effectiveDateTime = request.getStartDateTime();
    List<TimestampedValueGroup> timestampedValueGroups = new ArrayList<>();

    do {//from  w  w w .  j ava 2 s.c  o m
        effectiveDateTime = effectiveDateTime.plus((long) interPointDurationDistribution.sample(), SECONDS);

        if (!effectiveDateTime.isBefore(request.getEndDateTime())) {
            break;
        }

        if (request.isSuppressNightTimeMeasures() != null && request.isSuppressNightTimeMeasures()
                && (effectiveDateTime.getHour() >= NIGHT_TIME_START_HOUR
                        || effectiveDateTime.getHour() < NIGHT_TIME_END_HOUR)) {
            continue;
        }

        TimestampedValueGroup valueGroup = new TimestampedValueGroup();
        valueGroup.setTimestamp(effectiveDateTime);

        double trendProgressFraction = (double) Duration.between(request.getStartDateTime(), effectiveDateTime)
                .getSeconds() / totalDurationInS;

        for (Map.Entry<String, BoundedRandomVariableTrend> trendEntry : request.getTrends().entrySet()) {

            String key = trendEntry.getKey();
            BoundedRandomVariableTrend trend = trendEntry.getValue();

            double value = trend.nextValue(trendProgressFraction);
            valueGroup.setValue(key, value);
        }

        timestampedValueGroups.add(valueGroup);
    } while (true);

    return timestampedValueGroups;
}

From source file:SimpleGui.QueryGenerator.java

/**
 * Returns array of values in a given distribution
 * @param distribution//from  ww  w .  j ava 2 s.  com
 * @param numQs
 * @param mean
 * @param variance
 * @param exponentialMean
 * @param u_lower
 * @param u_upper
 * @return
 */
public int[] getDistributionValues(String distribution, int numQs, double mean, double variance,
        double exponentialMean, int u_lower, int u_upper, double slope, int upperBoundary) {

    int[] values = new int[numQs];

    switch (distribution) {
    case "Poisson": {
        RandomEngine engine = new DRand();
        Poisson poisson = new Poisson(mean, engine);
        int poissonObs = poisson.nextInt();
        Normal normal = new Normal(mean, variance, engine);

        for (int i = 0; i < numQs; i++) {
            double normalObs = normal.nextDouble();
            int sample = (int) Math.abs(normalObs);

            while (sample >= upperBoundary) {
                normalObs = normal.nextDouble();
                sample = (int) Math.abs(normalObs);
            }

            values[i] = sample;
            //System.out.println(values[i]+"from poisson");
            //=============================================
            PoissonDistribution p = new PoissonDistribution(mean);
            int randomInt = p.sample();
            // values[i] = randomInt;
        }
        // Arrays.sort(values);

        break;
    }
    case "Random": {

        Random randomGenerator = new Random();
        for (int i = 0; i < numQs; i++) {
            int randomInt = randomGenerator.nextInt(numQs - 1);
            values[i] = randomInt + 1; // to avoid '0'
        }

        break;
    }
    case "Uniform": {
        for (int i = 0; i < numQs; i++) {
            UniformIntegerDistribution u = new UniformIntegerDistribution(u_lower, u_upper);
            int randomInt = u.sample();
            while (randomInt >= upperBoundary) {
                randomInt = u.sample();
            }
            if (randomInt == 0)
                values[i] = randomInt + 1; // to avoid random '0'
            else
                values[i] = randomInt;

        }
        break;
    }

    case "Exponential": {
        for (int i = 0; i < numQs; i++) {
            ExponentialDistribution e = new ExponentialDistribution(exponentialMean);
            double exponential = e.sample();
            while (exponential >= upperBoundary - 1) {
                exponential = e.sample();
            }
            values[i] = new Double(exponential).intValue() + 1; //to avoid random value '0'
        }

        break;
    }

    case "Grading": { // y=mx+c. increment and then decrement for positive slopes.
        int constant = 0;
        for (int i = 0; i < numQs; i++) {
            constant += slope;
            int nextVal = new Double(constant).intValue();
            System.out.println(upperBoundary);
            if (nextVal >= upperBoundary || nextVal < 0) {
                slope = -1 * slope;
                i--;
            } else
                values[i] = nextVal;
        }
        break;
    }
    }
    // Arrays.sort(values);

    return values;
}