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

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

Introduction

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

Prototype

int sample();

Source Link

Document

Generate a random value sampled from this distribution.

Usage

From source file:io.coala.math3.Math3ProbabilityDistribution.java

@SafeVarargs
public static <S> Math3ProbabilityDistribution<Long> of(final IntegerDistribution dist, //final PseudoRandom stream,
        final S... args) {
    Objects.requireNonNull(dist);
    final Math3ProbabilityDistribution<Long> result = new Math3ProbabilityDistribution<Long>() {
        @Override//www  .j  a v a  2s.c  om
        public Long draw() {
            return Long.valueOf(dist.sample());
        }
    };
    //      result.stream = stream;
    return result;
}

From source file:net.myrrix.online.som.SelfOrganizingMaps.java

/**
 * @return map of initialized {@link Node}s, where each node is empty and initialized to a randomly chosen
 *  input vector normalized to unit length
 *///from www. j  av  a2  s .c  o m
private static Node[][] buildInitialMap(FastByIDMap<float[]> vectors, int mapSize) {

    double p = ((double) mapSize * mapSize) / vectors.size(); // Choose mapSize^2 out of # vectors
    IntegerDistribution pascalDistribution;
    if (p >= 1.0) {
        // No sampling at all, we can't fill the map with one pass even
        pascalDistribution = null;
    } else {
        // Number of un-selected elements to skip between selections is geometrically distributed with
        // parameter p; this is the same as a negative binomial / Pascal distribution with r=1:
        pascalDistribution = new PascalDistribution(RandomManager.getRandom(), 1, p);
    }

    LongPrimitiveIterator keyIterator = vectors.keySetIterator();
    Node[][] map = new Node[mapSize][mapSize];
    for (Node[] mapRow : map) {
        for (int j = 0; j < mapSize; j++) {
            if (pascalDistribution != null) {
                keyIterator.skip(pascalDistribution.sample());
            }
            while (!keyIterator.hasNext()) {
                keyIterator = vectors.keySetIterator(); // Start over, a little imprecise but affects it not much
                Preconditions.checkState(keyIterator.hasNext());
                if (pascalDistribution != null) {
                    keyIterator.skip(pascalDistribution.sample());
                }
            }
            float[] sampledVector = vectors.get(keyIterator.nextLong());
            mapRow[j] = new Node(sampledVector);
        }
    }
    return map;
}

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   w  w  w  .j  av a  2 s  .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:lda.inference.internal.CollapsedGibbsSampler.java

/**
 * Run collapsed Gibbs sampling [Griffiths and Steyvers 2004].
 *//*from w  ww .  j  av  a  2 s .c o m*/
void runSampling() {
    for (Document d : documents.getDocuments()) {
        for (int w = 0; w < d.getDocLength(); ++w) {
            final Topic oldTopic = topics.get(d.getTopicID(w));
            d.decrementTopicCount(oldTopic.id());

            final Vocabulary v = d.getVocabulary(w);
            oldTopic.decrementVocabCount(v.id());

            IntegerDistribution distribution = getFullConditionalDistribution(lda.getNumTopics(), d.id(),
                    v.id());

            final int newTopicID = distribution.sample();
            d.setTopicID(w, newTopicID);

            d.incrementTopicCount(newTopicID);
            final Topic newTopic = topics.get(newTopicID);
            newTopic.incrementVocabCount(v.id());
        }
    }
}

From source file:fr.inria.atlanmod.dag.instantiator.DagGenerator.java

protected void generateManyContainmentReference(EObject eObject, EReference eReference,
        ListMultimap<EClass, String> indexByKind, ImmutableMultiset<EClass> eAllConcreteSubTypesOrSelf,
        IntegerDistribution distribution) {

    @SuppressWarnings("unchecked")
    List<EObject> values = (List<EObject>) eObject.eGet(eReference);
    verticesSize = distribution.sample();
    LOGGER.fine(MessageFormat.format("Generating {0} values for EReference ''{1}'' in EObject {2}",
            verticesSize, eReference.getName(), eObject.toString()));
    IntegerDistribution distributionId = configuration.getDistributionFor(dagPck.getVertex_Id());
    for (int i = 0; i < verticesSize; i++) {
        final Optional<EObject> nextEObject = generateVertex(vertexClass, indexByKind, distributionId);
        if (nextEObject.isPresent()) {
            values.add(nextEObject.get());
        }/*from www. j  ava2  s.  com*/
    }
}

From source file:fr.obeo.emf.specimen.SpecimenGenerator.java

private boolean booleanInDistribution(IntegerDistribution distribution) {
    int sample = distribution.sample();
    return sample < distribution.getNumericalMean();
}

From source file:fr.inria.atlanmod.dag.instantiator.DagGenerator.java

@SuppressWarnings("unchecked")
protected void generateCrossReferencesForVertex(EObject eObject, ListMultimap<EClass, String> indexByKind) {

    EReference eReference = dagPck.getVertex_Outgoing();

    //EClass eReferenceType = eReference.getEReferenceType();
    IntegerDistribution distribution = configuration.getDistributionFor(eReference);

    //List<Object> values = (List<Object>) eObject.eGet(eReference);
    int sample = distribution.sample();
    LOGGER.fine(MessageFormat.format("Generating {0} values for EReference ''{1}'' in EObject {2}", sample,
            eReference.getName(), eObject.toString()));
    for (int i = 0; i < Math.min(sample, verticesSize - i); i++) {
        // check the edge does not already exist
        IntegerDistribution distId = configuration.getDistributionFor(dagPck.getEdge_Id());
        EObject nextEObject = null;//from ww w . j av  a 2s .  c om
        int count = verticesSize - i;
        while (count-- > 0) {// limiting max iteration to the number of remaining elements 
            nextEObject = ((List<EObject>) rootObject.eGet(dagPck.getDAG_Vertices()))
                    .get(generator.nextInt(verticesSize - i) + i);
            if (!existingEdge((Vertex) eObject, (Vertex) nextEObject))
                break;

        }
        if (nextEObject != null && !nextEObject.equals(eObject)) {
            Optional<Edge> edge = generateEdge(eObject, nextEObject, distId);
            if (edge.isPresent()) {
                //values.add(edge.get());
                ((List<EObject>) rootObject.eGet(dagPck.getDAG_Edges())).add(edge.get());
            }
        }
    }
}

From source file:fr.obeo.emf.specimen.DirectWriteSpecimenGenerator.java

protected boolean booleanInDistribution(IntegerDistribution distribution) {
    int sample = distribution.sample();
    return sample <= distribution.getNumericalMean();
}

From source file:eu.opensourceprojects.mondo.benchmarks.transformationzoo.instantiator.SpecimenGenerator.java

private boolean booleanInDistribution(IntegerDistribution distribution) {
    int sample = distribution.sample();
    //System.out.println(sample < distribution.getNumericalMean());
    return sample < distribution.getNumericalMean();
}

From source file:eu.opensourceprojects.mondo.benchmarks.transformationzoo.instantiator.SpecimenGenerator.java

private void setNextResourceSizeForType(Map<EClass, Integer> resourcesSize, EClass eClass) {
    IntegerDistribution sizeDistribution = c.getResourceSizeDistribution(eClass);
    int desiredSize = sizeDistribution.sample();
    resourcesSize.put(eClass, desiredSize);
}