Example usage for org.apache.commons.math3.util CombinatoricsUtils binomialCoefficient

List of usage examples for org.apache.commons.math3.util CombinatoricsUtils binomialCoefficient

Introduction

In this page you can find the example usage for org.apache.commons.math3.util CombinatoricsUtils binomialCoefficient.

Prototype

public static long binomialCoefficient(final int n, final int k)
        throws NotPositiveException, NumberIsTooLargeException, MathArithmeticException 

Source Link

Document

Returns an exact representation of the <a href="http://mathworld.wolfram.com/BinomialCoefficient.html"> Binomial Coefficient</a>, " n choose k ", the number of k -element subsets that can be selected from an n -element set.

Usage

From source file:com.cloudera.oryx.app.serving.als.model.LocalitySensitiveHash.java

LocalitySensitiveHash(double sampleRate, int numFeatures, int numCores) {

    // How many hash functions to use? use as few as possible that still achieve the desired sample
    // rate or less, approximately.
    int numHashes = 0;
    int bitsDiffering = 0;
    for (; numHashes < MAX_HASHES; numHashes++) {

        // For a given number of hashes, consider partitions differing from the target hash in how many bits?
        // Choose enough such that number to test is as large as possible while <= the number of cores
        bitsDiffering = 0;/*from  w  w  w  .jav  a2 s.  c o m*/
        // Number of different partitions that are examined when allowing the given number of bits to differ
        long numPartitionsToTry = 1;
        // Make bitsDiffering as large as possible given number of cores
        while (bitsDiffering < numHashes && numPartitionsToTry < numCores) {
            // There are numHashes-choose-bitsDiffering ways for numHashes bits to differ in
            // exactly bitsDiffering bits
            bitsDiffering++;
            numPartitionsToTry += CombinatoricsUtils.binomialCoefficient(numHashes, bitsDiffering);
        }
        // Note that this allows numPartitionsToTry to overshoot numCores by one step

        if (bitsDiffering == numHashes && numPartitionsToTry < numCores) {
            // Can't keep busy enough; keep going
            continue;
        }

        // Consider what fraction of all 2^n partitions is then considered, as a proxy for the
        // sample rate
        // Stop as soon as it's <= target sample rate
        if (numPartitionsToTry <= sampleRate * (1L << numHashes)) {
            break;
        }
    }

    log.info("LSH with {} hashes, querying partitions with up to {} bits differing", numHashes, bitsDiffering);
    this.maxBitsDiffering = bitsDiffering;
    hashVectors = new float[numHashes][];

    RandomGenerator random = RandomManager.getRandom();
    for (int i = 0; i < numHashes; i++) {
        // Pick the most-orthogonal next random vector
        double bestTotalDot = Double.POSITIVE_INFINITY;
        float[] nextBest = null;
        // Try, like, lots of them
        int candidatesSinceBest = 0;
        while (candidatesSinceBest < 1000) {
            float[] candidate = VectorMath.randomVectorF(numFeatures, random);
            // measure by total (absolute) dot product
            double score = totalAbsCos(hashVectors, i, candidate);
            if (score < bestTotalDot) {
                nextBest = candidate;
                // Stop if best possible score
                if (score == 0.0) {
                    break;
                }
                bestTotalDot = score;
                candidatesSinceBest = 0;
            } else {
                candidatesSinceBest++;
            }
        }
        hashVectors[i] = nextBest;
    }
    log.info("Chose {} random hash vectors", hashVectors.length);

    // Contains all 2^numHashes integers from 0. The first element has 0 bits set. The next numHashes elements
    // are all such integers with 1 bit sets. Then 2 bits, and so on. This is used as a "mask" on top of an
    // initial candidate index in order to construct results in getCandidateIndices()
    candidateIndicesPrototype = new int[1 << numHashes];
    int[] offsetPerBitsActive = new int[numHashes + 1];
    for (int i = 1; i <= numHashes; i++) {
        offsetPerBitsActive[i] = offsetPerBitsActive[i - 1]
                + (int) CombinatoricsUtils.binomialCoefficient(numHashes, i - 1);
    }
    for (int i = 0; i < candidateIndicesPrototype.length; i++) {
        candidateIndicesPrototype[offsetPerBitsActive[Integer.bitCount(i)]++] = i;
    }

    // Contains all 2^numHashes integers from 0
    allIndices = new int[1 << numHashes];
    for (int i = 0; i < allIndices.length; i++) {
        allIndices[i] = i;
    }
}

From source file:com.github.rinde.opt.localsearch.Insertions.java

/**
 * Calculates the number of <code>k</code> sized multisubsets that can be
 * formed in a set of size <code>n</code>. See
 * <a href="https://en.wikipedia.org/wiki/Combination#
 * Number_of_combinations_with_repetition">Wikipedia</a> for a description.
 *
 * @param n The size of the set to create subsets from.
 * @param k The size of the multisubsets.
 * @return The number of multisubsets.//from w  w w .  j  ava 2  s .c  o  m
 */
static long multichoose(int n, int k) {
    return CombinatoricsUtils.binomialCoefficient(n + k - 1, k);
}

From source file:iDynoOptimizer.MOEAFramework26.src.org.moeaframework.util.weights.NormalBoundaryIntersectionGenerator.java

@Override
public int size() {
    long size = 0;

    size += CombinatoricsUtils.binomialCoefficient(numberOfObjectives + divisionsOuter - 1, divisionsOuter);

    if (divisionsInner > 0) {
        size += CombinatoricsUtils.binomialCoefficient(numberOfObjectives + divisionsInner - 1, divisionsInner);
    }/*from w w  w.j  a v a2 s  . c o  m*/

    return (int) size;
}

From source file:iDynoOptimizer.MOEAFramework26.src.org.moeaframework.core.indicator.RIndicator.java

/**
 * Generates uniformly-distributed weights.
 * /*from   w w w. j av  a  2s .  co  m*/
 * @param s the number of subdivisions along each objective
 * @param k the number of objectives
 * @return the uniformly-distributed weights
 */
private static double[][] generateUniformWeights(int s, int k) {
    int counter = 0;
    int N = ArithmeticUtils.pow(s + 1, k);

    double[][] weights = new double[(int) CombinatoricsUtils.binomialCoefficient(s + k - 1, k - 1)][k];

    for (int i = 0; i < N; i++) {
        int sum = 0;
        int[] kary = toBaseK(i, s + 1, k);

        for (int j = 0; j < k; j++) {
            sum += kary[j];
        }

        if (sum == s) {
            for (int j = 0; j < k; j++) {
                weights[counter][j] = kary[j] / (double) s;
            }

            counter++;
        }
    }

    return weights;
}

From source file:com.cloudera.oryx.app.serving.als.model.LocalitySensitiveHashTest.java

private static void doTestHashesBits(double sampleRate, int numCores, int numHashes, int maxBitsDiffering) {
    LocalitySensitiveHash lsh = new LocalitySensitiveHash(sampleRate, 10, numCores);
    assertEquals(numHashes, lsh.getNumHashes());
    assertEquals(1L << numHashes, lsh.getNumPartitions());
    assertEquals(maxBitsDiffering, lsh.getMaxBitsDiffering());
    if (sampleRate == 1.0) {
        assertEquals(lsh.getMaxBitsDiffering(), lsh.getNumHashes());
    }// w w  w  . j  ava  2  s.  c  o m
    long partitionsToTry = 0;
    for (int i = 0; i <= maxBitsDiffering; i++) {
        partitionsToTry += CombinatoricsUtils.binomialCoefficient(numHashes, i);
    }
    if (numHashes < LocalitySensitiveHash.MAX_HASHES) {
        assertLessOrEqual((double) partitionsToTry / (1 << numHashes), sampleRate);
    }
}

From source file:com.cloudera.oryx.app.serving.als.model.LocalitySensitiveHash.java

/**
 * @param vector vector whose dot product with hashed vectors is to be maximized
 * @return indices of partitions containing candidates to check
 *//*from w  w w. jav a2  s  .  c o  m*/
int[] getCandidateIndices(float[] vector) {
    int mainIndex = getIndexFor(vector);
    // Simple cases
    int numHashes = getNumHashes();
    if (numHashes == maxBitsDiffering) {
        return allIndices;
    }
    if (maxBitsDiffering == 0) {
        return new int[] { mainIndex };
    }
    // Other cases
    int howMany = 0;
    for (int i = 0; i <= maxBitsDiffering; i++) {
        howMany += (int) CombinatoricsUtils.binomialCoefficient(numHashes, i);
    }
    int[] result = new int[howMany];
    System.arraycopy(candidateIndicesPrototype, 0, result, 0, howMany);
    for (int i = 0; i < howMany; i++) {
        result[i] ^= mainIndex;
    }
    return result;
}

From source file:grakn.core.graql.reasoner.reasoning.VariableRolesIT.java

/**
 *Each role player variable can be mapped to either of the conceptDOF concepts and these can repeat.
 *Each role variable can be mapped to either of RPs roles and only meta roles can repeat.
        /*w w w . j  a va2s.c  o m*/
 *For the case of conceptDOF = 3, roleDOF = 3.
 *We start by considering the number of meta roles we allow.
 *If we consider only non-meta roles, considering each relation player we get:
 *C^3_0 x 3.3 x 3.2 x 3 = 162 combinations
 *
 *If we consider single metarole - C^3_1 = 3 possibilities of assigning them:
 *C^3_1 x 3.3 x 3.2 x 3 = 486 combinations
 *
 *Two metaroles - again C^3_2 = 3 possibilities of assigning them:
 *C^3_2 x 3.3 x 3   x 3 = 243 combinations
 *
 *Three metaroles, C^3_3 = 1 possiblity of assignment:
 *C^3_3 x 3   x 3   x 3 = 81 combinations
 *
 *-> Total = 918 different answers
 *In general, for i allowed meta roles we have:
 *C^{RP}_i PRODUCT_{j = RP-i}{ (conceptDOF)x(roleDOF-j) } x PRODUCT_i{ conceptDOF} } answers.
 *
 *So total number of answers is:
 *SUM_i{ C^{RP}_i PRODUCT_{j = RP-i}{ (conceptDOF)x(roleDOF-j) } x PRODUCT_i{ conceptDOF} }
 *
 * @param RPS number of relation players available
 * @param conceptDOF number of concept degrees of freedom
 * @return number of answer combinations
 */
private int answerCombinations(int RPS, int conceptDOF) {
    int answers = 0;
    //i is the number of meta roles
    for (int i = 0; i <= RPS; i++) {
        int RPProduct = 1;
        //rps with non-meta roles
        for (int j = 0; j < RPS - i; j++)
            RPProduct *= conceptDOF * (RPS - j);
        //rps with meta roles
        for (int k = 0; k < i; k++)
            RPProduct *= conceptDOF;
        answers += CombinatoricsUtils.binomialCoefficient(RPS, i) * RPProduct;
    }
    return answers;
}

From source file:iDynoOptimizer.MOEAFramework26.src.org.moeaframework.algorithm.StandardAlgorithms.java

/**
 * Returns a new {@link NSGAIII} instance.
 * /*from w w w .  j av a2s .c  o  m*/
 * @param properties the properties for customizing the new {@code NSGAIII}
 *        instance
 * @param problem the problem
 * @return a new {@code NSGAIII} instance
 */
private Algorithm newNSGAIII(TypedProperties properties, Problem problem) {
    int divisionsOuter = 4;
    int divisionsInner = 0;

    if (properties.contains("divisionsOuter") && properties.contains("divisionsInner")) {
        divisionsOuter = (int) properties.getDouble("divisionsOuter", 4);
        divisionsInner = (int) properties.getDouble("divisionsInner", 0);
    } else if (properties.contains("divisions")) {
        divisionsOuter = (int) properties.getDouble("divisions", 4);
    } else if (problem.getNumberOfObjectives() == 1) {
        divisionsOuter = 100;
    } else if (problem.getNumberOfObjectives() == 2) {
        divisionsOuter = 20;
    } else if (problem.getNumberOfObjectives() == 3) {
        divisionsOuter = 12;
    } else if (problem.getNumberOfObjectives() == 4) {
        divisionsOuter = 8;
    } else if (problem.getNumberOfObjectives() == 5) {
        divisionsOuter = 6;
    } else if (problem.getNumberOfObjectives() == 6) {
        divisionsOuter = 5;
    } else if (problem.getNumberOfObjectives() == 7) {
        divisionsOuter = 3;
        divisionsInner = 2;
    } else if (problem.getNumberOfObjectives() == 8) {
        divisionsOuter = 3;
        divisionsInner = 2;
    } else if (problem.getNumberOfObjectives() == 9) {
        divisionsOuter = 3;
        divisionsInner = 2;
    } else if (problem.getNumberOfObjectives() == 10) {
        divisionsOuter = 3;
        divisionsInner = 2;
    } else {
        divisionsOuter = 2;
        divisionsInner = 1;
    }

    int populationSize;

    if (properties.contains("populationSize")) {
        populationSize = (int) properties.getDouble("populationSize", 100);
    } else {
        // compute number of reference points
        populationSize = (int) (CombinatoricsUtils
                .binomialCoefficient(problem.getNumberOfObjectives() + divisionsOuter - 1, divisionsOuter)
                + (divisionsInner == 0 ? 0
                        : CombinatoricsUtils.binomialCoefficient(
                                problem.getNumberOfObjectives() + divisionsInner - 1, divisionsInner)));

        // round up to a multiple of 4
        populationSize = (int) Math.ceil(populationSize / 4d) * 4;
    }

    Initialization initialization = new RandomInitialization(problem, populationSize);

    ReferencePointNondominatedSortingPopulation population = new ReferencePointNondominatedSortingPopulation(
            problem.getNumberOfObjectives(), divisionsOuter, divisionsInner);

    Selection selection = null;

    if (problem.getNumberOfConstraints() == 0) {
        selection = new Selection() {

            @Override
            public Solution[] select(int arity, Population population) {
                Solution[] result = new Solution[arity];

                for (int i = 0; i < arity; i++) {
                    result[i] = population.get(PRNG.nextInt(population.size()));
                }

                return result;
            }

        };
    } else {
        selection = new TournamentSelection(2,
                new ChainedComparator(new AggregateConstraintComparator(), new DominanceComparator() {

                    @Override
                    public int compare(Solution solution1, Solution solution2) {
                        return PRNG.nextBoolean() ? -1 : 1;
                    }

                }));
    }

    Variation variation = OperatorFactory.getInstance().getVariation(null, properties, problem);

    return new NSGAII(problem, population, null, selection, variation, initialization);
}

From source file:iDynoOptimizer.MOEAFramework26.src.org.moeaframework.algorithm.StandardAlgorithms.java

/**
 * Returns a new {@link DBEA} instance./*from  w  w  w.j av a2 s .  c  om*/
 * 
 * @param properties the properties for customizing the new {@code DBEA}
 *        instance
 * @param problem the problem
 * @return a new {@code DBEA} instance
 */
private Algorithm newDBEA(TypedProperties properties, Problem problem) {
    int divisionsOuter = 4;
    int divisionsInner = 0;

    if (properties.contains("divisionsOuter") && properties.contains("divisionsInner")) {
        divisionsOuter = (int) properties.getDouble("divisionsOuter", 4);
        divisionsInner = (int) properties.getDouble("divisionsInner", 0);
    } else if (properties.contains("divisions")) {
        divisionsOuter = (int) properties.getDouble("divisions", 4);
    } else if (problem.getNumberOfObjectives() == 1) {
        divisionsOuter = 100;
    } else if (problem.getNumberOfObjectives() == 2) {
        divisionsOuter = 20;
    } else if (problem.getNumberOfObjectives() == 3) {
        divisionsOuter = 12;
    } else if (problem.getNumberOfObjectives() == 4) {
        divisionsOuter = 8;
    } else if (problem.getNumberOfObjectives() == 5) {
        divisionsOuter = 6;
    } else if (problem.getNumberOfObjectives() == 6) {
        divisionsOuter = 5;
    } else if (problem.getNumberOfObjectives() == 7) {
        divisionsOuter = 3;
        divisionsInner = 2;
    } else if (problem.getNumberOfObjectives() == 8) {
        divisionsOuter = 3;
        divisionsInner = 2;
    } else if (problem.getNumberOfObjectives() == 9) {
        divisionsOuter = 3;
        divisionsInner = 2;
    } else if (problem.getNumberOfObjectives() == 10) {
        divisionsOuter = 3;
        divisionsInner = 2;
    } else {
        divisionsOuter = 2;
        divisionsInner = 1;
    }

    int populationSize;

    if (properties.contains("populationSize")) {
        populationSize = (int) properties.getDouble("populationSize", 100);
    } else {
        // compute number of reference points
        populationSize = (int) (CombinatoricsUtils
                .binomialCoefficient(problem.getNumberOfObjectives() + divisionsOuter - 1, divisionsOuter)
                + (divisionsInner == 0 ? 0
                        : CombinatoricsUtils.binomialCoefficient(
                                problem.getNumberOfObjectives() + divisionsInner - 1, divisionsInner)));
    }

    Initialization initialization = new RandomInitialization(problem, populationSize);

    Variation variation = OperatorFactory.getInstance().getVariation(null, properties, problem);

    return new DBEA(problem, initialization, variation, divisionsOuter, divisionsInner);
}

From source file:org.apache.flink.graph.library.clustering.directed.GlobalClusteringCoefficientTest.java

@Test
public void testWithCompleteGraph() throws Exception {
    long expectedDegree = completeGraphVertexCount - 1;
    long expectedCount = completeGraphVertexCount
            * CombinatoricsUtils.binomialCoefficient((int) expectedDegree, 2);

    Result expectedResult = new Result(expectedCount, expectedCount);

    Result globalClusteringCoefficient = new GlobalClusteringCoefficient<LongValue, NullValue, NullValue>()
            .run(completeGraph).execute();

    assertEquals(expectedResult, globalClusteringCoefficient);
}