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

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

Introduction

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

Prototype

public EnumeratedIntegerDistribution(final int[] singletons, final double[] probabilities)
        throws DimensionMismatchException, NotPositiveException, MathArithmeticException,
        NotFiniteNumberException, NotANumberException 

Source Link

Document

Create a discrete distribution using the given probability mass function definition.

Usage

From source file:com.vmware.photon.controller.rootscheduler.simulator.CloudStoreLoader.java

/**
 * Creates host documents in cloudstore.
 *
 * @param cloudstore CloudStore test environment to create documents in.
 * @param numHosts The number of host documents to create.
 * @param hostConfigurations A map from {@link HostConfiguration} to the probability that this
 *                           host configuration is used in the deployment. The sum of all the
 *                           values of this map must be 1.
 * @param numDatastores The number of datastores.
 * @param numDatastoresDistribution Distribution for number of datastores on each host. This
 *                                  distribution is expected to generate samples in the range
 *                                  [0, numDatastores].
 * @throws Throwable/*from   www .  ja v a  2s  .c  om*/
 */
public static void loadHosts(TestEnvironment cloudstore, int numHosts,
        Map<HostConfiguration, Double> hostConfigurations, int numDatastores,
        IntegerDistribution numDatastoresDistribution) throws Throwable {
    int[] indices = new int[hostConfigurations.size()];
    HostConfiguration[] configs = new HostConfiguration[hostConfigurations.size()];
    double[] probabilities = new double[hostConfigurations.size()];
    int i = 0;
    for (Map.Entry<HostConfiguration, Double> entry : hostConfigurations.entrySet()) {
        indices[i] = i;
        configs[i] = entry.getKey();
        probabilities[i] = entry.getValue();
        i++;
    }
    EnumeratedIntegerDistribution configDistribution = new EnumeratedIntegerDistribution(indices,
            probabilities);
    for (i = 0; i < numHosts; i++) {
        HostService.State host = new HostService.State();
        host.hostAddress = "host" + i;
        host.state = HostState.READY;
        host.userName = "username";
        host.password = "password";
        host.reportedDatastores = new HashSet<>();
        int numDatastoresPerHost = numDatastoresDistribution.sample();
        assertThat(numDatastoresPerHost >= 0, is(true));
        assertThat(numDatastoresPerHost <= numDatastores, is(true));
        while (host.reportedDatastores.size() < numDatastoresPerHost) {
            int randomInt = random.nextInt(numDatastores);
            host.reportedDatastores.add(new UUID(0, randomInt).toString());
        }
        host.reportedNetworks = new HashSet<>();
        host.usageTags = new HashSet<>(Arrays.asList(UsageTag.CLOUD.name()));
        int configIndex = configDistribution.sample();
        host.cpuCount = configs[configIndex].numCpus;
        host.memoryMb = configs[configIndex].memoryMb;
        host.documentSelfLink = new UUID(0, i).toString();
        // TODO(mmutsuzaki) Support availability zones.
        Operation result = cloudstore.sendPostAndWait(HostServiceFactory.SELF_LINK, host);
        assertThat(result.getStatusCode(), is(200));
        logger.debug("Created a host document: {}", Utils.toJson(true, false, host));
    }
}

From source file:eu.crisis_economics.utilities.EnumDistribution.java

public static <T extends Enum<T>> EnumDistribution<T> // Immutable
        create(Class<T> token, String sourceFile) throws IOException {
    if (token == null)
        throw new NullArgumentException();
    if (!token.isEnum())
        throw new IllegalArgumentException("EnumDistribution: " + token.getSimpleName() + " is not an enum.");
    if (token.getEnumConstants().length == 0)
        throw new IllegalArgumentException("EnumDistribution: " + token.getSimpleName() + " is an empty enum.");
    EnumDistribution<T> result = new EnumDistribution<T>();
    result.values = token.getEnumConstants();
    result.probabilities = new EnumMap<T, Double>(token);
    Map<String, T> converter = new HashMap<String, T>();
    final int numberOfValues = result.values.length;
    int[] valueIndices = new int[numberOfValues];
    double[] valueProbabilities = new double[numberOfValues];
    BitSet valueIsComitted = new BitSet(numberOfValues);
    {/*from  w  ww .j av a2s . c  o  m*/
        int counter = 0;
        for (T value : result.values) {
            valueIndices[counter] = counter++;
            result.probabilities.put(value, 0.);
            converter.put(value.name(), value);
        }
    }
    BufferedReader reader = new BufferedReader(new FileReader(sourceFile));
    try {
        String newLine;
        while ((newLine = reader.readLine()) != null) {
            if (newLine.isEmpty())
                continue;
            StringTokenizer tokenizer = new StringTokenizer(newLine);
            final String name = tokenizer.nextToken(" ,:\t"), pStr = tokenizer.nextToken(" ,:\t");
            if (tokenizer.hasMoreTokens())
                throw new ParseException(
                        "EnumDistribution: " + newLine + " is not a valid entry in " + sourceFile + ".", 0);
            final double p = Double.parseDouble(pStr);
            if (p < 0. || p > 1.)
                throw new IOException(pStr + " is not a valid probability for the value " + name);
            result.probabilities.put(converter.get(name), p);
            final int ordinal = converter.get(name).ordinal();
            if (valueIsComitted.get(ordinal))
                throw new ParseException("The value " + name + " appears twice in " + sourceFile, 0);
            valueProbabilities[converter.get(name).ordinal()] = p;
            valueIsComitted.set(ordinal, true);
        }
        { // Check sum of probabilities
            double sum = 0.;
            for (double p : valueProbabilities)
                sum += p;
            if (Math.abs(sum - 1.) > 1e2 * Math.ulp(1.))
                throw new IllegalStateException("EnumDistribution: parser has succeeded, but the resulting "
                        + "probaility sum (value " + sum + ") is not equal to 1.");
        }
    } catch (Exception e) {
        throw new IOException(e.getMessage());
    } finally {
        reader.close();
    }
    result.dice = new EnumeratedIntegerDistribution(valueIndices, valueProbabilities);
    return result;
}

From source file:lda.inference.internal.CollapsedGibbsSampler.java

/**
 * Get the full conditional distribution over topics.
 * docID and vocabID are passed to this distribution for parameters.
 * @param numTopics/*  w  w  w  . ja va 2 s  . c  o  m*/
 * @param docID
 * @param vocabID
 * @return the integer distribution over topics
 */
IntegerDistribution getFullConditionalDistribution(final int numTopics, final int docID, final int vocabID) {
    int[] topics = IntStream.range(0, numTopics).toArray();
    double[] probabilities = Arrays.stream(topics).mapToDouble(t -> getTheta(docID, t) * getPhi(t, vocabID))
            .toArray();
    return new EnumeratedIntegerDistribution(topics, probabilities);
}

From source file:main.java.workload.WorkloadExecutor.java

public void execute(Database db, Cluster cluster, WorkloadBatch wb, Workload wrl) {
    Global.LOGGER.info("=============================================================================");
    Global.LOGGER.info("Warming up the database ...");
    Global.LOGGER.info("Streaming transactional workloads ...");

    trDistribution = new EnumeratedIntegerDistribution(wrl.trTypes, wrl.trProbabilities);
    trDistribution.reseedRandomGenerator(seed[Global.repeatedRuns - 1]);

    wb = new WorkloadBatch(Global.repeatedRuns);

    // RBPTA specific -- will be removed
    if (Global.dataMigrationStrategy.equals("rbpta"))
        RBPTA.init(cluster);// w ww.j  a  v  a 2  s.c  o  m

    // Start simulation
    WorkloadExecutor.simulate(db, cluster, wrl, wb, Global.simulationPeriod);

    // Show batch status in console   
    Global.LOGGER.info("-----------------------------------------------------------------------------");
    Global.LOGGER.info("Total " + Global.total_transactions + " transactions have processed "
            + "by the Transaction Coordinator so far and of them " + Global.global_trSeq + " are unique.");

    Global.LOGGER.info("Total time: " + (Sim.time() / Global.observationWindow) + " hrs");

    // Statistic preparation, calculation, and reporting      
    Metric.collectMetrics(cluster, wb);
    cluster.show();

    perfm.write();
}

From source file:de.tum.bgu.msm.syntheticPopulationGenerator.capeTown.SyntheticPopCT.java

public int selectJobType(Person person) {
    //given a person, select the job type. It is based on the probabilities

    double[] probabilities = new double[jobStringTypes.length];
    int[] jobTypes = new int[jobStringTypes.length];
    //Person and job type values
    String name = "";
    if (person.getGender() == Gender.MALE) {
        name = "maleEducation";
    } else {// w  ww.ja v a 2  s .c  om
        name = "femaleEducation";
    }
    name = name + educationalLevelByPerson.get(person);

    //if (jobStringTypes.length == probabilitiesJob.getRowCount()) {
    //    probabilities = probabilitiesJob.getColumnAsDouble(name);
    //} else {
    for (int job = 0; job < jobStringTypes.length; job++) {
        jobTypes[job] = jobIntTypes.get(jobStringTypes[job]);
        probabilities[job] = probabilitiesJob.getStringIndexedValueAt(jobStringTypes[job], name);
    }
    //}
    return new EnumeratedIntegerDistribution(jobTypes, probabilities).sample();

}

From source file:Test.ScenarioBail.java

public ScenarioBail(density_tasks DensTask, spatial_concentration SpatConc, degree_of_modularity Mod,
        score_dispersion DispScore, sensors_dispersion DispSens, boolean random, int scenarioWidth) {
    //assignment//from w w w  .  j  a v  a2s  .c om
    this.DensTask = DensTask;
    this.DispScore = DispScore;
    this.DispSens = DispSens;
    this.Mod = Mod;
    this.SpatConc = SpatConc;

    switch (DensTask) {
    case high:
        this.number_of_bails = 30;
        break;
    case low:
        this.number_of_bails = 6;
        break;
    }
    if (SpatConc == spatial_concentration.high) {
        if (random == false) {
            if (number_of_bails == 30) {
                Collections.addAll(this.positions, this.position_30bails_50width1rnd);
            } else {
                Collections.addAll(this.positions, this.position_6bails_50width1rnd);
            }
        } else {

            int v1 = (int) (Math.random() * (scenarioWidth - 16));
            int v2 = (int) (Math.random() * (scenarioWidth - 16));
            v2 = v2 * scenarioWidth;
            ArrayList<Integer> concentrPoints = new ArrayList();
            for (int i = 0; i < 15; i++) {
                int k = v2 + scenarioWidth * i;
                for (int j = k + v1; j < k + v1 + 15; j++) {
                    concentrPoints.add(j);
                }
            }
            ArrayList<Integer> allPoints = new ArrayList();
            ArrayList<Integer> diffPoints = new ArrayList();
            for (int i = 0; i < scenarioWidth * scenarioWidth; i++) {
                allPoints.add(i);
            }
            diffPoints.addAll(allPoints);
            diffPoints.removeAll(concentrPoints);
            EnumeratedIntegerDistribution randomizer;
            Double probDiff = (double) 0 / diffPoints.size();
            Double probConc = (double) 1 / concentrPoints.size();
            double[] probVector = new double[allPoints.size()];
            for (int i = 0; i < allPoints.size(); i++) {
                if (diffPoints.contains(i)) {
                    probVector[i] = probDiff;
                } else {
                    probVector[i] = probConc;
                }
            }
            int[] allPointsarray = allPoints.stream().mapToInt(i -> i).toArray();
            EnumeratedIntegerDistribution randomizerPosition;
            randomizerPosition = new EnumeratedIntegerDistribution(allPointsarray, probVector);
            for (int u = 0; u < this.number_of_bails; u++) {
                this.positions.add(randomizerPosition.sample());

            }
        }
    } else {
        if (random == false) {
            if (number_of_bails == 30) {
                Collections.addAll(this.positions, this.position_30bails_50width1rnd);
            } else {
                Collections.addAll(this.positions, this.position_6bails_50width1rnd);
            }
        } else {
            for (int u = 0; u < this.number_of_bails; u++) {
                int v1 = (int) (Math.random() * (scenarioWidth * scenarioWidth - 1));
                this.positions.add(v1);
            }
        }
    }
    Double high;
    Double low;
    high = 1200.0;
    low = 300.0;
    /*if (Mod == degree_of_modularity.two || Mod == degree_of_modularity.oneComptwo){
        high = 800.0;
        low = 200.0;
    } else {
        high = 1200.0;
        low = 300.0;      
    }*/
    if (DispScore == score_dispersion.high) {

        if (random == false) {

            if (this.number_of_bails == 30) {
                for (int u = 0; u < 6; u++) {
                    this.scores_30bails_50width1rnd[u] = this.scores_30bails_50width1rnd[u] + high;
                }
                Collections.addAll(this.scores, scores_30bails_50width1rnd);
            } else {
                Collections.addAll(this.scores, this.scores_6bails_50widthHDev);
            }
        } else {
            int numHigh = (int) ((int) this.number_of_bails * 0.2);
            int v = (int) (Math.random() * (this.number_of_bails - numHigh));
            ArrayList<Integer> bailsHigh = new ArrayList<>();
            Double sum = 0.0;
            for (int y = 0; y < this.number_of_bails; y++) {
                this.scores.add(Math.random() * low);

            }
            for (int i = v; i < v + numHigh; i++) {
                this.scores.add(i, Math.random() * low + high);

            }

        }
        adjustMean(this.scores, 30000.0);
    } else {
        if (random == false) {
            if (this.number_of_bails == 30) {
                Collections.addAll(this.scores, scores_30bails_50width1rnd);
            } else {
                Collections.addAll(this.scores, this.scores_6bails_50width);
            }
        } else {
            for (int j = 0; j < this.number_of_bails; j++) {
                this.scores.add(Math.random() * (high - low) + high / 2);
            }

        }
        adjustMean(this.scores, 30000.0);
    }
    ArrayList<String> sensors = new ArrayList();
    sensors.add("IR");

    switch (Mod) {
    case three:
        sensors.add("MW");
        sensors.add("AB");
        break;
    case two:
        sensors.add("MW");
        break;
    default:
        break;
    }

    int count = 0;
    if (DispSens == sensors_dispersion.high) {
        for (int j = 1; j <= sensors.size(); j++) {
            List<Set<String>> subset = getSubsets(sensors, j);
            EnumeratedIntegerDistribution randR;
            double[] probVec = new double[subset.size()];
            int[] mapSubset = new int[subset.size()];
            for (int t = 0; t < subset.size(); t++) {
                probVec[t] = (double) 1 / subset.size();
                mapSubset[t] = t;
            }
            randR = new EnumeratedIntegerDistribution(mapSubset, probVec);
            for (int y = 0; y < (int) this.number_of_bails / sensors.size(); y++) {
                Set<String> thisset = subset.get(randR.sample());
                ArrayList<String> thisarray = new ArrayList();
                thisarray.addAll(thisset);
                this.bail_sensor.put(count, thisarray);
                count++;
            }
        }
    } else {
        for (int j = 0; j < this.number_of_bails; j++) {
            this.bail_sensor.put(count, sensors);
            count++;
        }
    }
}

From source file:Test.ScenarioBug.java

private void modifyVector(ArrayList<Double> cost_photo, boolean b) {
    ArrayList<Double> factors = new ArrayList();

    if (b == true) {

        factors.add(0.50);/*from w ww.  j a  v  a  2  s  .c o  m*/
        factors.add(1.0);
        factors.add(2.0);
    } else {
        factors.add(1.0);
        factors.add(1.0);
        factors.add(1.0);
    }
    double[] probVector = new double[3];
    probVector[0] = 0.4;
    probVector[1] = 0.2;
    probVector[2] = 0.4;
    int[] map = new int[3];
    map[0] = 0;
    map[1] = 1;
    map[2] = 2;
    Double sum = 0.0;
    for (int i = 0; i < this.number_of_bugs; i++) {
        sum = sum + cost_photo.get(i);
    }
    Double sum_2 = 0.0;
    for (int i = 0; i < this.number_of_bugs; i++) {
        EnumeratedIntegerDistribution randomizerPosition;
        randomizerPosition = new EnumeratedIntegerDistribution(map, probVector);
        int solution = randomizerPosition.sample();
        cost_photo.add(i, cost_photo.get(i) * factors.get(solution));
        sum_2 = sum_2 + cost_photo.get(i);
    }
    for (int i = 0; i < this.number_of_bugs; i++) {
        cost_photo.add(i, cost_photo.get(i) * sum / sum_2);
    }
}

From source file:Test.utile_functions.java

public ArrayList<String> assignRandomSensors(int[] amount_of_sensors, double[] probabilities,
        ArrayList<String> types_of_sensors) {

    ArrayList<String> result = new ArrayList<String>();

    EnumeratedIntegerDistribution randomizer;
    Random random_number = new Random();
    randomizer = new EnumeratedIntegerDistribution(amount_of_sensors, probabilities);
    int quantity;
    quantity = randomizer.sample();// ww  w .  j  a v  a2s .  co  m
    Collections.shuffle(types_of_sensors, new Random());
    for (int i = 0; i < quantity; i++) {
        result.add(types_of_sensors.get(i));
    }

    return result;
}