jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def hypergeometric(x, n, m, N):
    """
    x : number of successes drawn
    n : number of draws
    m : number of successes in total
    N : successes + failures in total.
    """
    if x < max(0, n - (N - m)):
        return 0.
    elif x > min(n, m):
        return 0.
    else:
        return comb(N - m, x) * comb(m, n - x) / comb(N, n)
//  [python]
def hypergeometric(x, n, m, N):
    """
    x : number of successes drawn
    n : number of draws
    m : number of successes in total
    N : successes + failures in total.
    """
    if x < max(0, n - (N - m)):
        return 0.
    elif x > min(n, m):
        return 0.
    else:
        return comb(N - m, x) * comb(m, n - x) / comb(N, n) 

from scipy.special import comb
//  [python]
def binomial_coefficients(n):
    """
        Generates a row in Pascal's triangle (binomial coefficients).

        Args:
            n(int):                 which row of Pascal's triangle to return.

        Returns:
            cs(numpy.ndarray):      a numpy array containing the row of
                                    Pascal's triangle.


        Examples:
            >>> binomial_coefficients(-25)
            array([], dtype=int64)

            >>> binomial_coefficients(-1)
            array([], dtype=int64)

            >>> binomial_coefficients(0)
            array([1])

            >>> binomial_coefficients(1)
            array([1, 1])

            >>> binomial_coefficients(2)
            array([1, 2, 1])

            >>> binomial_coefficients(4)
            array([1, 4, 6, 4, 1])

            >>> binomial_coefficients(4.0)
            array([1, 4, 6, 4, 1])
    """

    # Must be integer
    n = int(n)

    # Below -1 is all the same.
    if n < -1:
        n = -1

    # Get enough repeats of n to get each coefficent
    ns = numpy.repeat(n, n + 1)
    # Get all relevant k's
    ks = numpy.arange(n + 1)

    # Get all the coefficents in order
    cs = scipy.misc.comb(ns, ks)
    cs = numpy.around(cs)
    cs = cs.astype(int)

    return(cs)
//  [python]
def binomial_coefficients(n):
    """
        Generates a row in Pascal's triangle (binomial coefficients).

        Args:
            n(int):                 which row of Pascal's triangle to return.

        Returns:
            cs(numpy.ndarray):      a numpy array containing the row of
                                    Pascal's triangle.


        Examples:
            >>> binomial_coefficients(-25)
            array([], dtype=int64)

            >>> binomial_coefficients(-1)
            array([], dtype=int64)

            >>> binomial_coefficients(0)
            array([1])

            >>> binomial_coefficients(1)
            array([1, 1])

            >>> binomial_coefficients(2)
            array([1, 2, 1])

            >>> binomial_coefficients(4)
            array([1, 4, 6, 4, 1])

            >>> binomial_coefficients(4.0)
            array([1, 4, 6, 4, 1])
    """

    # Must be integer
    n = int(n)

    # Below -1 is all the same.
    if n < -1:
        n = -1

    # Get enough repeats of n to get each coefficent
    ns = numpy.repeat(n, n + 1)
    # Get all relevant k's
    ks = numpy.arange(n + 1)

    # Get all the coefficents in order
    cs = scipy.special.comb(ns, ks)
    cs = numpy.around(cs)
    cs = cs.astype(int)

    return(cs)
//  [python]
def pval(k,n,m,N, adhoc=False):
    #logger.info("%s %s %s %s" % (k,n,m,N))
    pv = 0.0
    for i in range(k,int(min(m,n)+1)):
        #kdrew: use adhoc choose method instead of scipy.misc.comb
        if adhoc:
            pi = ( choose(n,i) * choose((N-n), (m-i)) ) / choose(N,m)
        else:
            pi = ( misc.comb(n,i) * misc.comb((N-n), (m-i)) ) / misc.comb(N,m)
        pv += pi
    return pv
//  [python]
def pval(k,n,m,N, adhoc=False):
    #logger.info("%s %s %s %s" % (k,n,m,N))
    pv = 0.0
    for i in range(k,int(min(m,n)+1)):
        #kdrew: use adhoc choose method instead of scipy.misc.comb
        if adhoc:
            pi = ( choose(n,i) * choose((N-n), (m-i)) ) / choose(N,m)
        else:
            pi = ( special.comb(n,i) * special.comb((N-n), (m-i)) ) / special.comb(N,m)
        pv += pi
    return pv
//  [python]
def __len__(self):
        '''The number of addresses in this address space.

        Returns
        -------
        len: int >= 0
            The number of addresses in this address space.
        '''
        return scipy.misc.comb(2**(self.itr - 1) + self.obj - 1, self.obj - 1, exact=True)
//  [python]
def __len__(self):
        '''The number of addresses in this address space.

        Returns
        -------
        len: int >= 0
            The number of addresses in this address space.
        '''
        return scipy.special.comb(2**(self.itr - 1) + self.obj - 1, self.obj - 1, exact=True)
//  [python]
def _adjusted_rand_index(reference_indices, estimated_indices):
    """Compute the Rand index, adjusted for change.

    Parameters
    ----------
    reference_indices : np.ndarray
        Array of reference indices
    estimated_indices : np.ndarray
        Array of estimated indices

    Returns
    -------
    ari : float
        Adjusted Rand index

    .. note:: Based on sklearn.metrics.cluster.adjusted_rand_score

    """
    n_samples = len(reference_indices)
    ref_classes = np.unique(reference_indices)
    est_classes = np.unique(estimated_indices)
    # Special limit cases: no clustering since the data is not split;
    # or trivial clustering where each document is assigned a unique cluster.
    # These are perfect matches hence return 1.0.
    if (ref_classes.shape[0] == est_classes.shape[0] == 1 or
        ref_classes.shape[0] == est_classes.shape[0] == 0 or
        (ref_classes.shape[0] == est_classes.shape[0] ==
         len(reference_indices))):
        return 1.0

    contingency = _contingency_matrix(reference_indices, estimated_indices)

    # Compute the ARI using the contingency data
    sum_comb_c = sum(scipy.misc.comb(n_c, 2, exact=1) for n_c in
                     contingency.sum(axis=1))
    sum_comb_k = sum(scipy.misc.comb(n_k, 2, exact=1) for n_k in
                     contingency.sum(axis=0))

    sum_comb = sum((scipy.misc.comb(n_ij, 2, exact=1) for n_ij in
                    contingency.flatten()))
    prod_comb = (sum_comb_c * sum_comb_k)/float(scipy.misc.comb(n_samples, 2))
    mean_comb = (sum_comb_k + sum_comb_c)/2.
    return ((sum_comb - prod_comb)/(mean_comb - prod_comb))
//  [python]
def _adjusted_rand_index(reference_indices, estimated_indices):
    """Compute the Rand index, adjusted for change.

    Parameters
    ----------
    reference_indices : np.ndarray
        Array of reference indices
    estimated_indices : np.ndarray
        Array of estimated indices

    Returns
    -------
    ari : float
        Adjusted Rand index

    .. note:: Based on sklearn.metrics.cluster.adjusted_rand_score

    """
    n_samples = len(reference_indices)
    ref_classes = np.unique(reference_indices)
    est_classes = np.unique(estimated_indices)
    # Special limit cases: no clustering since the data is not split;
    # or trivial clustering where each document is assigned a unique cluster.
    # These are perfect matches hence return 1.0.
    if (ref_classes.shape[0] == est_classes.shape[0] == 1 or
        ref_classes.shape[0] == est_classes.shape[0] == 0 or
        (ref_classes.shape[0] == est_classes.shape[0] ==
         len(reference_indices))):
        return 1.0

    contingency = _contingency_matrix(reference_indices, estimated_indices)

    # Compute the ARI using the contingency data
    sum_comb_c = sum(scipy.special.comb(n_c, 2, exact=1) for n_c in
                     contingency.sum(axis=1))
    sum_comb_k = sum(scipy.special.comb(n_k, 2, exact=1) for n_k in
                     contingency.sum(axis=0))

    sum_comb = sum((scipy.special.comb(n_ij, 2, exact=1) for n_ij in
                    contingency.flatten()))
    prod_comb = (sum_comb_c * sum_comb_k)/float(scipy.special.comb(n_samples, 2))
    mean_comb = (sum_comb_k + sum_comb_c)/2.
    return ((sum_comb - prod_comb)/(mean_comb - prod_comb))
//  [python]
def run_removal(motifs, threshold, cns, norm_factors):
    CN = motifs[0].CN
    for m in motifs:
        assert m.CN == CN
    similarities = get_similarities(motifs, norm_factors, cns)
    assert len(similarities) == scipy.misc.comb(len(motifs), 2)*2
    while any(v > threshold for v in similarities.values()):
        print(f"Running removal on {len(motifs)} motifs... {max(similarities.values())}")
        motifs = remove_one(motifs, similarities=similarities, cns=cns)
        similarities = get_similarities(motifs, norm_factors, cns)
    return motifs
//  [python]
def run_removal(motifs, threshold, cns, norm_factors):
    CN = motifs[0].CN
    for m in motifs:
        assert m.CN == CN
    similarities = get_similarities(motifs, norm_factors, cns)
    assert len(similarities) == scipy.special.comb(len(motifs), 2)*2
    while any(v > threshold for v in similarities.values()):
        print(f"Running removal on {len(motifs)} motifs... {max(similarities.values())}")
        motifs = remove_one(motifs, similarities=similarities, cns=cns)
        similarities = get_similarities(motifs, norm_factors, cns)
    return motifs
//  [python]
def from_power_basis(cls, pp, extrapolate=None):
        """
        Construct a piecewise polynomial in Bernstein basis
        from a power basis polynomial.

        Parameters
        ----------
        pp : PPoly
            A piecewise polynomial in the power basis
        extrapolate : bool, optional
            Whether to extrapolate to ouf-of-bounds points based on first
            and last intervals, or to return NaNs. Default: True.

        """
        dx = np.diff(pp.x)
        k = pp.c.shape[0] - 1   # polynomial order

        rest = (None,)*(pp.c.ndim-2)

        c = np.zeros_like(pp.c)
        for a in range(k+1):
            factor = pp.c[a] / comb(k, k-a) * dx[(slice(None),)+rest]**(k-a)
            for j in range(k-a, k+1):
                c[j] += factor * comb(j, k-a)

        if extrapolate is None:
            extrapolate = pp.extrapolate

        return cls.construct_fast(c, pp.x, extrapolate)
//  [python]
def from_power_basis(cls, pp, extrapolate=None):
        """
        Construct a piecewise polynomial in Bernstein basis
        from a power basis polynomial.

        Parameters
        ----------
        pp : PPoly
            A piecewise polynomial in the power basis
        extrapolate : bool, optional
            Whether to extrapolate to ouf-of-bounds points based on first
            and last intervals, or to return NaNs. Default: True.

        """
        dx = np.diff(pp.x)
        k = pp.c.shape[0] - 1   # polynomial order

        rest = (None,)*(pp.c.ndim-2)

        c = np.zeros_like(pp.c)
        for a in range(k+1):
            factor = pp.c[a] / scipy.special.comb(k, k-a) * dx[(slice(None),)+rest]**(k-a)
            for j in range(k-a, k+1):
                c[j] += factor * scipy.special.comb(j, k-a)

        if extrapolate is None:
            extrapolate = pp.extrapolate

        return cls.construct_fast(c, pp.x, extrapolate)
//  [python]
def from_bernstein_basis(cls, bp, extrapolate=None):
        """
        Construct a piecewise polynomial in the power basis
        from a polynomial in Bernstein basis.

        Parameters
        ----------
        bp : BPoly
            A Bernstein basis polynomial, as created by BPoly
        extrapolate : bool, optional
            Whether to extrapolate to ouf-of-bounds points based on first
            and last intervals, or to return NaNs. Default: True.

        """
        dx = np.diff(bp.x)
        k = bp.c.shape[0] - 1  # polynomial order

        rest = (None,)*(bp.c.ndim-2)

        c = np.zeros_like(bp.c)
        for a in range(k+1):
            factor = (-1)**(a) * comb(k, a) * bp.c[a]
            for s in range(a, k+1):
                val = comb(k-a, s-a) * (-1)**s
                c[k-s] += factor * val / dx[(slice(None),)+rest]**s

        if extrapolate is None:
            extrapolate = bp.extrapolate

        return cls.construct_fast(c, bp.x, extrapolate)
//  [python]
def from_bernstein_basis(cls, bp, extrapolate=None):
        """
        Construct a piecewise polynomial in the power basis
        from a polynomial in Bernstein basis.

        Parameters
        ----------
        bp : BPoly
            A Bernstein basis polynomial, as created by BPoly
        extrapolate : bool, optional
            Whether to extrapolate to ouf-of-bounds points based on first
            and last intervals, or to return NaNs. Default: True.

        """
        dx = np.diff(bp.x)
        k = bp.c.shape[0] - 1  # polynomial order

        rest = (None,)*(bp.c.ndim-2)

        c = np.zeros_like(bp.c)
        for a in range(k+1):
            factor = (-1)**(a) * scipy.special.comb(k, a) * bp.c[a]
            for s in range(a, k+1):
                val = scipy.special.comb(k-a, s-a) * (-1)**s
                c[k-s] += factor * val / dx[(slice(None),)+rest]**s

        if extrapolate is None:
            extrapolate = bp.extrapolate

        return cls.construct_fast(c, bp.x, extrapolate)
//  [python]
def num_compositions(m, n):
    """
    The total number of m-part compositions of n, which is equal to
    (n+m-1) choose (m-1).

    Parameters
    ----------
    m : scalar(int)
        Number of parts of composition.

    n : scalar(int)
        Integer to decompose.

    Returns
    -------
    scalar(int)
        Total number of m-part compositions of n.

    """
    # docs.scipy.org/doc/scipy/reference/generated/scipy.misc.comb.html
    return scipy.misc.comb(n+m-1, m-1, exact=True)
//  [python]
def num_compositions(m, n):
    """
    The total number of m-part compositions of n, which is equal to
    (n+m-1) choose (m-1).

    Parameters
    ----------
    m : scalar(int)
        Number of parts of composition.

    n : scalar(int)
        Integer to decompose.

    Returns
    -------
    scalar(int)
        Total number of m-part compositions of n.

    """
    # docs.scipy.org/doc/scipy/reference/generated/scipy.misc.comb.html
    return scipy.special.comb(n+m-1, m-1, exact=True)
//  [python]
def binomial_beta(self, alpha, beta, n, k):
        """A function to calculate the binomial beta distribution.

        :param alpha: The alpha parameter.
        :param beta: The beta parameter.
        :param n: The N parameter.
        :param k: The K parameter.
        :return: A vector of binomial-beta transformed results.
        """
        choices = sm.comb(n, k)
        top = sp.betaln(k+alpha, n-k+beta)
        top = top.replace(np.inf, np.nan)
        top.fillna(0, inplace=True)
        bottom = sp.betaln(n, k)
        bottom = bottom.replace(np.inf, np.nan)
        bottom.fillna(0, inplace=True)
        result = np.log(choices) + top - bottom
        result = result.replace([np.inf, -np.inf], np.nan)
        result.fillna(0, inplace=True)
        return result
//  [python]
def binomial_beta(self, alpha, beta, n, k):
        """A function to calculate the binomial beta distribution.

        :param alpha: The alpha parameter.
        :param beta: The beta parameter.
        :param n: The N parameter.
        :param k: The K parameter.
        :return: A vector of binomial-beta transformed results.
        """
        choices = sp.comb(n, k)
        top = sp.betaln(k+alpha, n-k+beta)
        top = top.replace(np.inf, np.nan)
        top.fillna(0, inplace=True)
        bottom = sp.betaln(n, k)
        bottom = bottom.replace(np.inf, np.nan)
        bottom.fillna(0, inplace=True)
        result = np.log(choices) + top - bottom
        result = result.replace([np.inf, -np.inf], np.nan)
        result.fillna(0, inplace=True)
        return result
//  [python]
def __init__(
			self, exchange_recipe, n_PEs, n_particles_per_PE, resampling_algorithm,
			resampling_criterion, prior, state_transition_kernel, sensors, each_PE_required_sensors,
			polynomial_degree):

		super().__init__(
			n_PEs, n_particles_per_PE, resampling_algorithm, resampling_criterion, prior,
			state_transition_kernel, sensors, each_PE_required_sensors)

		# the exchange recipe is kept
		self.exchange_recipe = exchange_recipe

		# for the sake of convenience when following the pseudocode in
		# "Likelihood Consensus and its Application to Distributed Particle Filtering":
		# -------------------

		# the size of the state
		M = 2

		# the chosen degree for the polynomial approximation
		R_p = polynomial_degree

		# a list of tuples, each one representing a combination of possible exponents for a monomial
		r_a_tuples = list(itertools.filterfalse(
			lambda x: sum(x) > R_p, itertools.product(range(R_p+1), repeat=M)))

		# each row contains the exponents for a monomial
		r_a = np.array(r_a_tuples)

		# theoretical number of monomials in the approximation
		R_a = scipy.misc.comb(R_p + M, R_p, exact=True)

		assert(R_a == len(r_a_tuples))

		# exponents for computing d
		self._r_d_tuples = list(itertools.filterfalse(
			lambda x: sum(x) > (2*R_p), itertools.product(range(2*R_p+1), repeat=M)))
		r_d = np.array(self._r_d_tuples)

		# we generate the *two* vectors of exponents (r' and r'' in the paper) jointly,
		# and then drop those combinations that don't satisfy the required constraints
		rs_gamma = [list(itertools.filterfalse(
			lambda x:
			not np.allclose((np.array(x)[:M] + x[M:]), r) or sum(x[:M]) > R_p or sum(x[M:]) > R_p,
			itertools.product(range(R_p+1), repeat=2*M))) for r in r_d]

		# theoretically, this is the number of beta components that should result
		N_c = scipy.misc.comb(2*R_p + M, 2*R_p, exact=True)

		assert(N_c == len(self._r_d_tuples))

		# the particle filters are built (each one associated with a different set of sensors)
		self._PEs = [centralized.TargetTrackingParticleFilterWithConsensusCapabilities(
			n_particles_per_PE, resampling_algorithm, resampling_criterion, prior, state_transition_kernel,
			[sensors[iSensor] for iSensor in connections], M, R_p, r_a_tuples, r_a, self._r_d_tuples, r_d, rs_gamma
		) for connections in each_PE_required_sensors]
//  [python]
def __init__(
			self, exchange_recipe, n_PEs, n_particles_per_PE, resampling_algorithm,
			resampling_criterion, prior, state_transition_kernel, sensors, each_PE_required_sensors,
			polynomial_degree):

		super().__init__(
			n_PEs, n_particles_per_PE, resampling_algorithm, resampling_criterion, prior,
			state_transition_kernel, sensors, each_PE_required_sensors)

		# the exchange recipe is kept
		self.exchange_recipe = exchange_recipe

		# for the sake of convenience when following the pseudocode in
		# "Likelihood Consensus and its Application to Distributed Particle Filtering":
		# -------------------

		# the size of the state
		M = 2

		# the chosen degree for the polynomial approximation
		R_p = polynomial_degree

		# a list of tuples, each one representing a combination of possible exponents for a monomial
		r_a_tuples = list(itertools.filterfalse(
			lambda x: sum(x) > R_p, itertools.product(range(R_p+1), repeat=M)))

		# each row contains the exponents for a monomial
		r_a = np.array(r_a_tuples)

		# theoretical number of monomials in the approximation
		R_a = scipy.special.comb(R_p + M, R_p, exact=True)

		assert(R_a == len(r_a_tuples))

		# exponents for computing d
		self._r_d_tuples = list(itertools.filterfalse(
			lambda x: sum(x) > (2*R_p), itertools.product(range(2*R_p+1), repeat=M)))
		r_d = np.array(self._r_d_tuples)

		# we generate the *two* vectors of exponents (r' and r'' in the paper) jointly,
		# and then drop those combinations that don't satisfy the required constraints
		rs_gamma = [list(itertools.filterfalse(
			lambda x:
			not np.allclose((np.array(x)[:M] + x[M:]), r) or sum(x[:M]) > R_p or sum(x[M:]) > R_p,
			itertools.product(range(R_p+1), repeat=2*M))) for r in r_d]

		# theoretically, this is the number of beta components that should result
		N_c = scipy.special.comb(2*R_p + M, 2*R_p, exact=True)

		assert(N_c == len(self._r_d_tuples))

		# the particle filters are built (each one associated with a different set of sensors)
		self._PEs = [centralized.TargetTrackingParticleFilterWithConsensusCapabilities(
			n_particles_per_PE, resampling_algorithm, resampling_criterion, prior, state_transition_kernel,
			[sensors[iSensor] for iSensor in connections], M, R_p, r_a_tuples, r_a, self._r_d_tuples, r_d, rs_gamma
		) for connections in each_PE_required_sensors]
//  [python]
def _raise_degree(c, d):
        """Raise a degree of a polynomial in the Bernstein basis.

        Given the coefficients of a polynomial degree `k`, return (the
        coefficients of) the equivalent polynomial of degree `k+d`.

        Parameters
        ----------
        c : array_like
            coefficient array, 1D
        d : integer

        Returns
        -------
        array
            coefficient array, 1D array of length `c.shape[0] + d`

        Notes
        -----
        This uses the fact that a Berstein polynomial `b_{a, k}` can be
        identically represented as a linear combination of polynomials of
        a higher degree `k+d`:

            .. math:: b_{a, k} = comb(k, a) \sum_{j=0}^{d} b_{a+j, k+d} \
                                comb(d, j) / comb(k+d, a+j)

        """
        if d == 0:
            return c

        k = c.shape[0] - 1
        out = np.zeros((c.shape[0] + d,) + c.shape[1:], dtype=c.dtype)

        for a in range(c.shape[0]):
            f = c[a] * comb(k, a)
            for j in range(d+1):
                out[a+j] += f * comb(d, j) / comb(k+d, a+j)
        return out
//  [python]
def combinatorial_factors(self, node):
        n_node = self.G.n_lineages_subtended_by[node]
        return scipy.misc.comb(n_node, np.arange(n_node + 1))
//  [python]
def combinatorial_factors(self, node):
        n_node = self.G.n_lineages_subtended_by[node]
        return scipy.special.comb(n_node, np.arange(n_node + 1))
//  [python]
def __mul__(self, other):
        """
        Gene IDs should be ordered alphabetically.
        And only works for databases with all gene IDs loaded into memory.
        """
        assert self.gene_count == other.gene_count
        assert numpy.all(numpy.in1d(self.gene_ids, other.gene_ids))
        assert self.total_gene_count == other.total_gene_count
        assert self.gene_count == self.total_gene_count

        db_name = "(" + self.name + "*" + other.name + ")"

        feature_count = self.feature_count + other.feature_count
        # TODO: scipy.misc appears to be unavailable in version 0.10 ...
        combination_count = scipy.misc.comb(feature_count, 2, exact=1)
        # Fill rankings array with zeros, but do not use numpy.zeros as it does not preallocate the whole array.
        rankings = numpy.full(shape=(self.gene_count, combination_count), fill_value=0, dtype=self.dtype)
        feature_ids = []
        idx = 0
        rankings_pair = numpy.full(shape=(self.gene_count, 2), fill_value=0, dtype=numpy.float)

        for feature_idx1 in range(0, self.feature_count):
            for feature_idx2 in range(0, other.feature_count):
                feature_name = self.feature_ids[feature_idx1] + "*" + other.feature_ids[feature_idx2]
                feature_ids.append(feature_name)
                logging.info("combining {0:s} via orderstatistics".format(feature_name))

                # The relative rankings have to be created from 1-based absolute rankings,
                # to avoid zeros in the relative rankings (annihilator in multiplication).
                rankings_pair[:, 0] = (self.rankings[:, feature_idx1] + 1.0) / float(self.gene_count)
                rankings_pair[:, 1] = (other.rankings[:, feature_idx2] + 1.0) / float(self.gene_count)

                # This only works because gene_ids are ordered alphabetically.
                combined_gene_ids = self.gene_ids[numpy.argsort(combine_via_order_statistics(rankings_pair))]
                rankings[:, idx] = numpy.argsort(combined_gene_ids)
                idx += 1

        return RankingsDatabase(db_name,
                                numpy.array(feature_ids, dtype='|S255'),
                                self.gene_ids,
                                rankings,
                                numpy.zeros(shape=combination_count, dtype=numpy.int_),
                                {0: db_name},
                                self.total_gene_count)
//  [python]
def __mul__(self, other):
        """
        Gene IDs should be ordered alphabetically.
        And only works for databases with all gene IDs loaded into memory.
        """
        assert self.gene_count == other.gene_count
        assert numpy.all(numpy.in1d(self.gene_ids, other.gene_ids))
        assert self.total_gene_count == other.total_gene_count
        assert self.gene_count == self.total_gene_count

        db_name = "(" + self.name + "*" + other.name + ")"

        feature_count = self.feature_count + other.feature_count
        combination_count = scipy.special.comb(feature_count, 2, exact=1)
        rankings = numpy.full(shape=(self.gene_count, combination_count), fill_value=0, dtype=self.dtype)
        feature_ids = []
        idx = 0
        rankings_pair = numpy.full(shape=(self.gene_count, 2), fill_value=0, dtype=numpy.float)

        for feature_idx1 in range(0, self.feature_count):
            for feature_idx2 in range(0, other.feature_count):
                feature_name = self.feature_ids[feature_idx1] + "*" + other.feature_ids[feature_idx2]
                feature_ids.append(feature_name)
                logging.info("combining {0:s} via orderstatistics".format(feature_name))

                rankings_pair[:, 0] = (self.rankings[:, feature_idx1] + 1.0) / float(self.gene_count)
                rankings_pair[:, 1] = (other.rankings[:, feature_idx2] + 1.0) / float(self.gene_count)

                combined_gene_ids = self.gene_ids[numpy.argsort(combine_via_order_statistics(rankings_pair))]
                rankings[:, idx] = numpy.argsort(combined_gene_ids)
                idx += 1

        return RankingsDatabase(db_name,
                                numpy.array(feature_ids, dtype='|S255'),
                                self.gene_ids,
                                rankings,
                                numpy.zeros(shape=combination_count, dtype=numpy.int_),
                                {0: db_name},
                                self.total_gene_count)
//  [python]
def __pow__(self, power, modulo=None):
        if power != 2:
            raise ValueError('Only power of 2 supported.')

        db_name = self.name + "**2"
        combination_count = scipy.misc.comb(self.feature_count, 2, exact=1)
        # Fill rankings array with zeros, but do not use numpy.zeros as it does not preallocate the whole array.
        rankings = numpy.full(shape=(self.gene_count, combination_count), fill_value=0, dtype=self.dtype)
        feature_ids = []
        idx = 0
        rankings_pair = numpy.empty(shape=(self.gene_count, 2), dtype=numpy.float)

        for feature_idx1 in range(0, self.feature_count):
            for feature_idx2 in range(feature_idx1 + 1, self.feature_count):
                feature_name = self.feature_ids[feature_idx1] + "*" + self.feature_ids[feature_idx2]
                feature_ids.append(feature_name)
                logging.info("combining {0:s} via orderstatistics".format(feature_name))

                # The relative rankings have to be created from 1-based absolute rankings,
                # to avoid zeros in the relative rankings (annihilator in multiplication).
                rankings_pair[:, 0] = (self.rankings[:, feature_idx1] + 1.0) / float(self.gene_count)
                rankings_pair[:, 1] = (self.rankings[:, feature_idx2] + 1.0) / float(self.gene_count)

                # This only works because gene_ids are ordered alphabetically.
                combined_gene_ids = self.gene_ids[numpy.argsort(combine_via_order_statistics(rankings_pair))]
                rankings[:, idx] = numpy.argsort(combined_gene_ids)
                idx += 1

        return RankingsDatabase(db_name,
                                numpy.array(feature_ids, dtype='|S255'),
                                self.gene_ids, rankings,
                                numpy.zeros(shape=combination_count, dtype=numpy.int_),
                                {0: db_name},
                                self.total_gene_count)
//  [python]
def __pow__(self, power, modulo=None):
        if power != 2:
            raise ValueError('Only power of 2 supported.')

        db_name = self.name + "**2"
        combination_count = scipy.special.comb(self.feature_count, 2, exact=1)
        # Fill rankings array with zeros, but do not use numpy.zeros as it does not preallocate the whole array.
        rankings = numpy.full(shape=(self.gene_count, combination_count), fill_value=0, dtype=self.dtype)
        feature_ids = []
        idx = 0
        rankings_pair = numpy.empty(shape=(self.gene_count, 2), dtype=numpy.float)

        for feature_idx1 in range(0, self.feature_count):
            for feature_idx2 in range(feature_idx1 + 1, self.feature_count):
                feature_name = self.feature_ids[feature_idx1] + "*" + self.feature_ids[feature_idx2]
                feature_ids.append(feature_name)
                logging.info("combining {0:s} via orderstatistics".format(feature_name))

                # The relative rankings have to be created from 1-based absolute rankings,
                # to avoid zeros in the relative rankings (annihilator in multiplication).
                rankings_pair[:, 0] = (self.rankings[:, feature_idx1] + 1.0) / float(self.gene_count)
                rankings_pair[:, 1] = (self.rankings[:, feature_idx2] + 1.0) / float(self.gene_count)

                # This only works because gene_ids are ordered alphabetically.
                combined_gene_ids = self.gene_ids[numpy.argsort(combine_via_order_statistics(rankings_pair))]
                rankings[:, idx] = numpy.argsort(combined_gene_ids)
                idx += 1

        return RankingsDatabase(db_name,
                                numpy.array(feature_ids, dtype='|S255'),
                                self.gene_ids, rankings,
                                numpy.zeros(shape=combination_count, dtype=numpy.int_),
                                {0: db_name},
                                self.total_gene_count)
//  [python]
def generate_data():
        d = 7
        D = 3
        K = 2
        p = scipy.misc.comb(D, K)
        m = 5

        V_mat = np.asarray(np.random.rand(D, d), dtype=config.floatX)
        U_mat = np.eye(d, dtype=config.floatX)
        UinvT_mat = np.eye(d, dtype=config.floatX)
        Q_mat = np.dot( V_mat.T, V_mat )

        H_mat = np.asarray(np.random.rand(m, d), dtype=config.floatX)
        all_perm=np.array((list(itertools.permutations(list(range(D))))))
        a = np.zeros((m, D))
        a[:] = np.arange(D)
        b = all_perm[np.random.randint(0,p,size=m)]
        tmp_Y_i = (a.flatten()[(b+D*np.arange(m)[...,np.newaxis]).flatten()]).reshape(a.shape)
        Y_indexes_mat = np.asarray(tmp_Y_i[:,:K], dtype=np.int32)
        Y_values_mat = np.asarray(np.ones((m, K)), dtype=config.floatX)
        Y = np.zeros((m, D))
        for i in range(K):
            Y[np.arange(m), Y_indexes_mat[:,i].flatten()] = 1.
        return V_mat, U_mat, UinvT_mat, Q_mat, H_mat, Y_indexes_mat, Y_values_mat, Y
//  [python]
def generate_data():
        d = 7
        D = 3
        K = 2
        p = scipy.special.comb(D, K)
        m = 5

        V_mat = np.asarray(np.random.rand(D, d), dtype=config.floatX)
        U_mat = np.eye(d, dtype=config.floatX)
        UinvT_mat = np.eye(d, dtype=config.floatX)
        Q_mat = np.dot( V_mat.T, V_mat )

        H_mat = np.asarray(np.random.rand(m, d), dtype=config.floatX)
        all_perm=np.array((list(itertools.permutations(list(range(D))))))
        a = np.zeros((m, D))
        a[:] = np.arange(D)
        b = all_perm[np.random.randint(0,p,size=m)]
        tmp_Y_i = (a.flatten()[(b+D*np.arange(m)[...,np.newaxis]).flatten()]).reshape(a.shape)
        Y_indexes_mat = np.asarray(tmp_Y_i[:,:K], dtype=np.int32)
        Y_values_mat = np.asarray(np.ones((m, K)), dtype=config.floatX)
        Y = np.zeros((m, D))
        for i in range(K):
            Y[np.arange(m), Y_indexes_mat[:,i].flatten()] = 1.
        return V_mat, U_mat, UinvT_mat, Q_mat, H_mat, Y_indexes_mat, Y_values_mat, Y
//  [python]
def _ell(A, m):
    """
    A helper function for expm_2009.

    Parameters
    ----------
    A : linear operator
        A linear operator whose norm of power we care about.
    m : int
        The power of the linear operator

    Returns
    -------
    value : int
        A value related to a bound.

    """
    if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
        raise ValueError('expected A to be like a square matrix')

    p = 2*m + 1

    # The c_i are explained in (2.2) and (2.6) of the 2005 expm paper.
    # They are coefficients of terms of a generating function series expansion.
    abs_c_recip = scipy.misc.comb(2*p, p, exact=True) * math.factorial(2*p + 1)

    # This is explained after Eq. (1.2) of the 2009 expm paper.
    # It is the "unit roundoff" of IEEE double precision arithmetic.
    u = 2**-53

    # Compute the one-norm of matrix power p of abs(A).
    A_abs_onenorm = _onenorm_matrix_power_nnm(abs(A), p)

    # Treat zero norm as a special case.
    if not A_abs_onenorm:
        return 0

    alpha = A_abs_onenorm / (_onenorm(A) * abs_c_recip)
    log2_alpha_div_u = np.log2(alpha/u)
    value = int(np.ceil(log2_alpha_div_u / (2 * m)))
    return max(value, 0)
//  [python]
def _ell(A, m):
    """
    A helper function for expm_2009.

    Parameters
    ----------
    A : linear operator
        A linear operator whose norm of power we care about.
    m : int
        The power of the linear operator

    Returns
    -------
    value : int
        A value related to a bound.

    """
    if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
        raise ValueError('expected A to be like a square matrix')

    p = 2*m + 1

    # The c_i are explained in (2.2) and (2.6) of the 2005 expm paper.
    # They are coefficients of terms of a generating function series expansion.
    abs_c_recip = scipy.special.comb(2*p, p, exact=True) * math.factorial(2*p + 1)

    # This is explained after Eq. (1.2) of the 2009 expm paper.
    # It is the "unit roundoff" of IEEE double precision arithmetic.
    u = 2**-53

    # Compute the one-norm of matrix power p of abs(A).
    A_abs_onenorm = _onenorm_matrix_power_nnm(abs(A), p)

    # Treat zero norm as a special case.
    if not A_abs_onenorm:
        return 0

    alpha = A_abs_onenorm / (_onenorm(A) * abs_c_recip)
    log2_alpha_div_u = np.log2(alpha/u)
    value = int(np.ceil(log2_alpha_div_u / (2 * m)))
    return max(value, 0)
//  [python]
x = np.arange(0, N + 1)

theta = np.array([0.3, 0.5, 0.8])
colors = ['b', 'r', 'g']

i = 0
for th in theta:
	p = scipy.misc.comb(N, x)*th**x*(1. - th)**(N - x)
	p /= p.sum()
	plt.plot(x, p, 'o-', color=colors[i], markersize=10,
		label='$\\theta = {val}$'.format(val=th))
	i += 1
//  [python]
x = np.arange(0, N + 1)

theta = np.array([0.3, 0.5, 0.8])
colors = ['b', 'r', 'g']

i = 0
for th in theta:
	p = scipy.special.comb(N, x)*th**x*(1. - th)**(N - x)
	p /= p.sum()
	plt.plot(x, p, 'o-', color=colors[i], markersize=10,
		label='$\\theta = {val}$'.format(val=th))
	i += 1
//  [python]
def ER_figure_N(Ns, m, beta=1, labels=None):
    """Varying population size."""

    ss = []
    plot_data = [[] for _ in range(3)]
    n = len(m[0])

    for N in Ns:
        print(N)
        mu = 1 / N
        norm = float(scipy.misc.comb(N+n, n))
        e, s = compute_entropy_rate(
            N=N, m=m, n=3, beta=beta, exact=False, mu=mu, lim=1e-10)
        ss.append(s)
        iss_states = [(N, 0, 0), (N / 2, N / 2, 0), (N / 3, N / 3, N / 3)]
        for i, iss_state in enumerate(iss_states):
            s_max = s[iss_state]
            plot_data[i].append((e, s_max, e / (s_max * norm)))
    # Plot data
    gs = gridspec.GridSpec(3, 1)
    ax1, ax2, ax3 = plot_data_sub(Ns, plot_data, gs, labels, use_log=True, sci=False)
    ax2.legend(loc="upper right")
    ax3.set_xlabel("Population Size $N$")
//  [python]
def ER_figure_N(Ns, m, beta=1, labels=None):
    """Varying population size."""

    ss = []
    plot_data = [[] for _ in range(3)]
    n = len(m[0])

    for N in Ns:
        print(N)
        mu = 1 / N
        norm = float(scipy.special.comb(N+n, n))
        e, s = compute_entropy_rate(
            N=N, m=m, n=3, beta=beta, exact=False, mu=mu, lim=1e-10)
        ss.append(s)
        iss_states = [(N, 0, 0), (N / 2, N / 2, 0), (N / 3, N / 3, N / 3)]
        for i, iss_state in enumerate(iss_states):
            s_max = s[iss_state]
            plot_data[i].append((e, s_max, e / (s_max * norm)))
    # Plot data
    gs = gridspec.GridSpec(3, 1)
    ax1, ax2, ax3 = plot_data_sub(Ns, plot_data, gs, labels, use_log=True, sci=False)
    ax2.legend(loc="upper right")
    ax3.set_xlabel("Population Size $N$")
//  [python]
def getSize(self):
    if self.n <= 0:
      return (1 if self.d == 0 else 0)
    elif self.d == 0:
      return 1
    elif self.d < 0:
      return 0
    else:
      return sum([2**q * scipy.misc.comb(self.d - 1 + q, self.d - 1, exact=True)
                  for q in range(self.n - self.d + 1)])
//  [python]
def getSize(self):
    if self.n <= 0:
      return (1 if self.d == 0 else 0)
    elif self.d == 0:
      return 1
    elif self.d < 0:
      return 0
    else:
      return sum([2**q * scipy.special.comb(self.d - 1 + q, self.d - 1, exact=True)
                  for q in range(self.n - self.d + 1)])
//  [python]
def getSize(self):
    if self.b == 0:
      return sum([2**q * scipy.misc.comb(self.d, q, exact=True) *
                  RegularSparse(self.n, self.d - q).getSize()
                  for q in range(self.d + 1)])
    elif self.b >= 1:
      return (RegularSparse(self.n, self.d).getSize() +
              sum([2**q * scipy.misc.comb(self.d, q, exact=True) *
                   RegularSparse(self.n - q - self.b + 1, self.d - q).getSize()
                   for q in range(1, self.d + 1)]))
    else:
      raise ValueError("Invalid value for b.")
//  [python]
def getSize(self):
    if self.b == 0:
      return sum([2**q * scipy.special.comb(self.d, q, exact=True) *
                  RegularSparse(self.n, self.d - q).getSize()
                  for q in range(self.d + 1)])
    elif self.b >= 1:
      return (RegularSparse(self.n, self.d).getSize() +
              sum([2**q * scipy.special.comb(self.d, q, exact=True) *
                   RegularSparse(self.n - q - self.b + 1, self.d - q).getSize()
                   for q in range(1, self.d + 1)]))
    else:
      raise ValueError("Invalid value for b.")
//  [python]
def messages(self):

		# the length of subset of the state on which the likelihood depends
		M = 2

		# theoretically, this is the number of beta components that should result
		n_consensus_algorithms = scipy.misc.comb(2*self.polynomial_degree + M, 2*self.polynomial_degree, exact=True) - 1

		# overall number of neighbours: #neighbours of the 1st PE + #neighbours of the 2nd PE +...
		n_neighbours = sum([len(neighbours) for neighbours in self._neighborhoods])

		# each PE sends "n_consensus_algorithms" values to each one of its neighbours, once per iteration...
		n_messages = n_neighbours*n_consensus_algorithms*self._max_iterations

		# ...additionally it needs to send each neighbour the number of neighbours it has itself (Metropolis weights)
		n_messages += n_neighbours

		return n_messages
//  [python]
def messages(self):

		# the length of subset of the state on which the likelihood depends
		M = 2

		# theoretically, this is the number of beta components that should result
		n_consensus_algorithms = scipy.special.comb(2*self.polynomial_degree + M, 2*self.polynomial_degree, exact=True) - 1

		# overall number of neighbours: #neighbours of the 1st PE + #neighbours of the 2nd PE +...
		n_neighbours = sum([len(neighbours) for neighbours in self._neighborhoods])

		# each PE sends "n_consensus_algorithms" values to each one of its neighbours, once per iteration...
		n_messages = n_neighbours*n_consensus_algorithms*self._max_iterations

		# ...additionally it needs to send each neighbour the number of neighbours it has itself (Metropolis weights)
		n_messages += n_neighbours

		return n_messages
//  [python]
def pval_old(k,n,m,N, adhoc=False, denm=False, logchoose=False):
    #logger.info("%s %s %s %s" % (k,n,m,N))
    pv = 0.0
    for i in range(k,int(min(m,n)+1)):
        #kdrew: use adhoc choose method instead of scipy.misc.comb
        if adhoc:
            pi = ( choose(n,i) * choose((N-n), (m-i)) ) / choose(N,m)
        elif denm:
            pi = ( misc.comb(n,i) * misc.comb((N-n), (m-i)) ) / m
        elif logchoose:
            r1 = logchoose_func(n, i)
            try:
                r2 = logchoose_func(N-n, m-i)
            except ValueError as ve:
                print(str(ve))
                return np.nan
            r3 = logchoose_func(N,m)

            pi = scipy.exp(r1 + r2 - r3)
        else:
            pi = ( misc.comb(n,i) * misc.comb((N-n), (m-i)) ) / misc.comb(N,m)
        pv += pi
    return pv
//  [python]
def pval_old(k,n,m,N, adhoc=False, denm=False, logchoose=False):
    #logger.info("%s %s %s %s" % (k,n,m,N))
    pv = 0.0
    for i in range(k,int(min(m,n)+1)):
        #kdrew: use adhoc choose method instead of scipy.misc.comb
        if adhoc:
            pi = ( choose(n,i) * choose((N-n), (m-i)) ) / choose(N,m)
        elif denm:
            pi = ( scipy.special.comb(n,i) * scipy.special.comb((N-n), (m-i)) ) / m
        elif logchoose:
            r1 = logchoose_func(n, i)
            try:
                r2 = logchoose_func(N-n, m-i)
            except ValueError as ve:
                print(str(ve))
                return np.nan
            r3 = logchoose_func(N,m)

            pi = scipy.exp(r1 + r2 - r3)
        else:
            pi = ( scipy.special.comb(n,i) * scipy.special.comb((N-n), (m-i)) ) / scipy.special.comb(N,m)
        pv += pi
    return pv
//  [python]
def create_graph(reviews_file, graph_file):

    print('%s: start' % time.strftime("%Y/%d/%m-%H:%M:%S"))

    with open(reviews_file, 'rb') as read_file:
        reviews = pickle.load(read_file)
    reviews = reviews[:13]

    print('num reviews: %d' % len(reviews))
    print('%s: loaded reviews' % time.strftime("%Y/%d/%m-%H:%M:%S"))

    all_nouns = list(get_all_nouns(reviews))
    print('num nouns: %d' % len(all_nouns))
    print('%s: obtained nouns' % time.strftime("%Y/%d/%m-%H:%M:%S"))

    all_senses = generate_all_senses(reviews)
    total_possible_vertices = scipy.misc.comb(len(all_senses), 2, exact=True)
    print('num senses: %d' % len(all_senses))
    print('total possible senses: %d' % total_possible_vertices)
    print('%s: obtained senses' % time.strftime("%Y/%d/%m-%H:%M:%S"))

    graph = networkx.Graph()

    for sense in all_senses:
        graph.add_node(sense.name())
    print('%s: created graph' % time.strftime("%Y/%d/%m-%H:%M:%S"))
    print('num nodes: %d' % len(graph.nodes()))

    cycle = 0
    for synset1, synset2 in itertools.combinations(all_senses, 2):
        cycle += 1
        if not cycle % 100000:
            print('sense cycle: %d/%d\r' % (cycle, total_possible_vertices)),
        if synset1.wup_similarity(synset2) >= 0.7:
            graph.add_edge(synset1.name(), synset2.name())
    print('%s: added vertices' % time.strftime("%Y/%d/%m-%H:%M:%S"))
    print('num edges: %d' % len(graph.edges()))

    with open(graph_file, 'wb') as write_file:
        pickle.dump(graph, write_file, pickle.HIGHEST_PROTOCOL)

    with open(graph_file, 'rb') as read_file:
        graph = pickle.load(read_file)

    print('num nodes: %d' % len(graph.nodes()))
    print('num edges: %d' % len(graph.edges()))

    my_dominating_set = dominating_set.min_weighted_dominating_set(graph)
    print('%s found dominating set' % time.strftime("%Y/%d/%m-%H:%M:%S"))
    print('dominating set length: %d' % len(my_dominating_set))
    my_vertex_cover = vertex_cover.min_weighted_vertex_cover(graph)
    print('%s found vertex cover' % time.strftime("%Y/%d/%m-%H:%M:%S"))
    print('vertex cover length: %d' % len(my_vertex_cover))
//  [python]
def create_graph(reviews_file, graph_file):

    print('%s: start' % time.strftime("%Y/%d/%m-%H:%M:%S"))

    with open(reviews_file, 'rb') as read_file:
        reviews = pickle.load(read_file)
    reviews = reviews[:13]

    print('num reviews: %d' % len(reviews))
    print('%s: loaded reviews' % time.strftime("%Y/%d/%m-%H:%M:%S"))

    all_nouns = list(get_all_nouns(reviews))
    print('num nouns: %d' % len(all_nouns))
    print('%s: obtained nouns' % time.strftime("%Y/%d/%m-%H:%M:%S"))

    all_senses = generate_all_senses(reviews)
    total_possible_vertices = scipy.special.comb(len(all_senses), 2, exact=True)
    print('num senses: %d' % len(all_senses))
    print('total possible senses: %d' % total_possible_vertices)
    print('%s: obtained senses' % time.strftime("%Y/%d/%m-%H:%M:%S"))

    graph = networkx.Graph()

    for sense in all_senses:
        graph.add_node(sense.name())
    print('%s: created graph' % time.strftime("%Y/%d/%m-%H:%M:%S"))
    print('num nodes: %d' % len(graph.nodes()))

    cycle = 0
    for synset1, synset2 in itertools.combinations(all_senses, 2):
        cycle += 1
        if not cycle % 100000:
            print('sense cycle: %d/%d\r' % (cycle, total_possible_vertices)),
        if synset1.wup_similarity(synset2) >= 0.7:
            graph.add_edge(synset1.name(), synset2.name())
    print('%s: added vertices' % time.strftime("%Y/%d/%m-%H:%M:%S"))
    print('num edges: %d' % len(graph.edges()))

    with open(graph_file, 'wb') as write_file:
        pickle.dump(graph, write_file, pickle.HIGHEST_PROTOCOL)

    with open(graph_file, 'rb') as read_file:
        graph = pickle.load(read_file)

    print('num nodes: %d' % len(graph.nodes()))
    print('num edges: %d' % len(graph.edges()))

    my_dominating_set = dominating_set.min_weighted_dominating_set(graph)
    print('%s found dominating set' % time.strftime("%Y/%d/%m-%H:%M:%S"))
    print('dominating set length: %d' % len(my_dominating_set))
    my_vertex_cover = vertex_cover.min_weighted_vertex_cover(graph)
    print('%s found vertex cover' % time.strftime("%Y/%d/%m-%H:%M:%S"))
    print('vertex cover length: %d' % len(my_vertex_cover))
//  [python]
def get_num_hole_card_combinations(game):
    num_players = game.get_num_players()
    num_hole_cards = game.get_num_hole_cards()
    num_cards = game.get_num_suits() * game.get_num_ranks()
    num_total_hole_cards = num_players * num_hole_cards
    return scipy.misc.comb(num_cards, num_total_hole_cards, exact=True) \
        * scipy.special.perm(num_total_hole_cards, num_total_hole_cards, exact=True)
//  [python]
def get_num_hole_card_combinations(game):
    num_players = game.get_num_players()
    num_hole_cards = game.get_num_hole_cards()
    num_cards = game.get_num_suits() * game.get_num_ranks()
    num_total_hole_cards = num_players * num_hole_cards
    return scipy.special.comb(num_cards, num_total_hole_cards, exact=True) \
        * scipy.special.perm(num_total_hole_cards, num_total_hole_cards, exact=True)
//  [python]
def printMetricQuantity(self):
        denominator = scipy.misc.comb(self.numberOfNeuronsToTrack, self.kValue)* math.pow(2,  self.kValue)
        numerator = 0
        for key in self.k_Activation_record:
            numerator = numerator + len(self.k_Activation_record[key])
        print(str(self.kValue)+"-projection neuron on-off activation coverage:"+str(numerator) + "/"+str(int(denominator))+"="+str(numerator/denominator))
//  [python]
def printMetricQuantity(self):
        denominator = scipy.special.comb(self.numberOfNeuronsToTrack, self.kValue)* math.pow(2,  self.kValue)
        numerator = 0
        for key in self.k_Activation_record:
            numerator = numerator + len(self.k_Activation_record[key])
        print(str(self.kValue)+"-projection neuron on-off activation coverage:"+str(numerator) + "/"+str(int(denominator))+"="+str(numerator/denominator))
//  [python]
def _munp(self, n, c):
        k = arange(0, n+1)
        vals = 1.0/c**n * sum(
            s.comb(n, k) * (-1)**k * special.gamma(c*k + 1),
            axis=0)
        return where(c*n > -1, vals, inf)
//  [python]
def _munp(self, n, c):
        k = arange(0, n+1)
        vals = 1.0/c**n * sum(
            comb(n, k) * (-1)**k * special.gamma(c*k + 1),
            axis=0)
        return where(c*n > -1, vals, inf)