dit.math

Mathematical tools for dit.

Classes

LinearOperations

The class of operations on linear values.

LogOperations

Functions

approximate_fraction

Return an approxite rational fraction of x.

as_random_state

Coerce rng into a numpy.random.RandomState.

atom_set

Returns the atoms of the sigma-algebra F.

ball

Return random samples within an n-dimensional standard ball of radius 1.

combinations

Returns the binomial coefficient of n choose k.

factorial

Computes n!

get_ops

Returns an Operations instance (linear or log), depending on the base.

is_integer

Tests if x is a integer.

is_number

Tests if x is a number.

is_sigma_algebra

Returns True if F is a sigma algebra on X.

multinomial

Compute the multinomial coefficient, equal to the number of ways of arranging n items into groups of sizes k1, k2, ...

norm

Returns normally distributed mass functions with mean equal to pmf.

perturb_support_pmf

Returns a new distribution with all nonzero probabilities perturbed.

prod

Compute the product of values in vals.

sample

Returns a sample from a discrete distribution.

sample_simplex

Sample uniformly from the simplex.

sigma_algebra

Returns the sigma algebra generated by the subsets in C.

Reference

class LinearOperations[source]

Bases: Operations

The class of operations on linear values.

add(x, y)[source]

Add the arrays element-wise. Neither x nor y will be modified.

Assumption: \(y >= 0\).

Operation: \(z[i] = x[i] + y[i]\)

Parameters:
  • x (NumPy arrays, shape (n,)) – The arrays to add.

  • y (NumPy arrays, shape (n,)) – The arrays to add.

Returns:

z – The resultant array.

Return type:

NumPy array, shape (n,)

add_inplace(x, y)[source]

Adds y to x, in-place. x will be modified, but y will not.

Assumption: \(y >= 0\).

Operation: \(x[i] += y[i]\)

Parameters:
  • x (NumPy arrays, shape (n,)) – The arrays to add.

  • y (NumPy arrays, shape (n,)) – The arrays to add.

Returns:

x – The resultant array.

Return type:

NumPy array, shape (n,)

add_reduce(x, axis=None)[source]

Performs an addition’ reduction on `x.

Assumption: \(y >= 0\).

Operation: \(z = \sum_i x[i]\)

Returns:

z – The summation of the elements in x.

Return type:

float

mult(x, y)[source]

Multiplies the arrays element-wise. Neither x nor y will be modified.

Operation: \(z[i] = x[i] * y[i]\)

Parameters:
  • x (NumPy arrays, shape (n,)) – The arrays to multiply.

  • y (NumPy arrays, shape (n,)) – The arrays to multiply.

Returns:

z – The resultant array.

Return type:

NumPy array, shape (n,)

mult_inplace(x, y)[source]

Multiplies y to x, in-place. x will be modified, but y will not.

Operation: \(x[i] *= y[i]\)

Parameters:
  • x (NumPy arrays, shape (n,)) – The arrays to multiply.

  • y (NumPy arrays, shape (n,)) – The arrays to multiply.

Returns:

x – The resultant array.

Return type:

NumPy array, shape (n,)

mult_reduce(x, axis=None)[source]

Performs an multiplication’ reduction on `x.

Operation: \(z = \prod_i x[i]\)

Returns:

z – The product of the elements in x.

Return type:

float

invert(x)[source]

Returns the element-wise multiplicative inverse of x.

Operation: \(z[i] = 1/x[i]\)

Parameters:

x (NumPy array, shape (n,)) – The array to invert.

Returns:

z – The inverted array.

Return type:

NumPy array, shape (n,)

normalize(x, axis=None)[source]

Returns a normalized version of x.

Operation: \(z[i] = x[i] / sum(x)\)

If x is 2D and axis is None, then normalization is over all elements. Use axis=-1 to normalize each row of x.

Parameters:

x (NumPy array, shape (n,)) – The array to normalize.

Returns:

z – The normalized array.

Return type:

NumPy array, shape (n,)

class LogOperations(base)[source]

Bases: Operations

set_base(base)[source]

Change the base of the logarithm.

Parameters:

base (float) – The base of the logarithm.

mult(x, y)[source]

Multiplies the arrays element-wise. Neither x nor y will be modified.

Parameters:
  • x (NumPy arrays, shape (n,)) – The arrays to multiply.

  • y (NumPy arrays, shape (n,)) – The arrays to multiply.

Returns:

z – The resultant array.

Return type:

NumPy array, shape (n,)

mult_inplace(x, y)[source]

Multiplies y to x, in-place. x will be modified, but y will not.

Parameters:
  • x (NumPy arrays, shape (n,)) – The arrays to multiply.

  • y (NumPy arrays, shape (n,)) – The arrays to multiply.

Returns:

x – The resultant array.

Return type:

NumPy array, shape (n,)

mult_reduce(x, axis=None)[source]

Performs an multiplication’ reduction on `x.

Returns:

z – The product of the elements in x.

Return type:

float

invert(x)[source]

Returns the element-wise multiplicative inverse of x: \(1/x\).

Parameters:

x (NumPy array, shape (n,)) – The array to invert.

Returns:

z – The inverted array.

Return type:

NumPy array, shape (n,)

normalize(x, axis=None)[source]

Returns a normalized version of x.

Non-log equivalent operation: \(z[i] = x[i] / sum(x)\)

If x is 2D and axis is None, then normalization is over all elements. Use axis=-1 to normalize each row of x.

Parameters:

x (NumPy array, shape (n,)) – The array to normalize.

Returns:

z – The normalized array.

Return type:

NumPy array, shape (n,)

approximate_fraction(x, e)[source]

Return an approxite rational fraction of x.

The returned Fraction instance is the fraction with the lowest denominator that differs from x by no more than e.

Examples

>>> x = 1/3
>>> y = approximate_fraction(x, 1e-9)
>>> print y
1/3
as_random_state(rng=None)[source]

Coerce rng into a numpy.random.RandomState.

Parameters:

rng (np.random.Generator, np.random.RandomState, int, None) – The source of randomness. None means the global dit.math.prng; a Generator is wrapped so that both share the same bit generator.

Returns:

rng – A RandomState drawing from rng.

Return type:

np.random.RandomState

atom_set(F, X=None, method=2)[source]

Returns the atoms of the sigma-algebra F.

Parameters:
  • F (set of frozensets) – The candidate sigma algebra.

  • X (frozenset, None) – The universal set. If None, then X is taken to be the union of the sets in F.

Returns:

atoms – A frozenset of frozensets, representing the atoms of the sigma algebra.

Return type:

frozenset

ball(n, size=None, rng=None)[source]

Return random samples within an n-dimensional standard ball of radius 1.

Parameters:
  • size (int) – The number of samples to draw from the unit n-ball.

  • rng (np.random.Generator, np.random.RandomState, int, None) – A random number generator. If None, then dit.math.prng is used.

Returns:

samples – Points within the unit n-ball.

Return type:

NumPy array, shape (size, n)

combinations(n, k)[source]

Returns the binomial coefficient of n choose k.

Parameters:
  • n (int) – The size of the set to draw from.

  • k (int) – The number of elements to draw.

Returns:

nck – n choose k

Return type:

int

Raises:
  • TypeError – If n and k are not numbers.

  • ValueError – If n and k are not positive integers, and n >= k.

factorial(n)[source]

Computes n!

Parameters:

n (int) – A positive integer

Returns:

f – n!

Return type:

int

Raises:
get_ops(base)[source]

Returns an Operations instance (linear or log), depending on the base.

Parameters:

base (float, 'linear', 'e') – The base for the Operations instance.

is_integer(x)[source]

Tests if x is a integer.

Parameters:

x (object) – The object to test the integerness of.

Returns:

b – True if x is an integer, False otherwise.

Return type:

bool

is_number(x)[source]

Tests if x is a number.

Parameters:

x (object) – The object to test the numericalness of.

Returns:

b – True if x is a number, False otherwise.

Return type:

bool

is_sigma_algebra(F, X=None)[source]

Returns True if F is a sigma algebra on X.

Parameters:
  • F (set of frozensets) – The candidate sigma algebra.

  • X (frozenset, None) – The universal set. If None, then X is taken to be the union of the sets in F.

Returns:

issa – True if F is a sigma algebra and False if not.

Return type:

bool

Notes

The time complexity of this algorithm is O ( len(F) * len(X) ).

multinomial(n, ks)[source]

Compute the multinomial coefficient, equal to the number of ways of arranging n items into groups of sizes k1, k2, …

norm(pmf, ilrcov=None, size=None, rng=None)[source]

Returns normally distributed mass functions with mean equal to pmf.

Parameters:
  • pmf (NumPy array, shape (n,)) – The probability mass function about which samples are drawn.

  • ilrcov (float, NumPy array with shape (n-1,) or (n-1,n-1)) – The covariance matrix in isometric log-ratio coordinates. If a float, then a covariance matrix is constructed as a scalar multiple of the identity matrix—e.g. spherical covariance. If ilrcov is a 1D NumPy array, then it specifies the diagonal of the covariance matrix, all non-diagonal elements are set equal to zero. Otherwise, ilrcov should be an (n-1, n-1) 2D symmetric and positive semi-definite matrix. If None, then an identity matrix is used as the covariance matrix.

  • size (int) – The number of samples to draw. Default is to return a single sample.

  • rng (np.random.Generator, np.random.RandomState, int, None) – A random number generator. If None, then dit.math.prng is used.

Returns:

samples – The samples. If size is None, then a single sample is returned.

Return type:

NumPy array, shape (n,) or (size, n)

perturb_support_pmf(pmf, eps=0.1, shape='ball', rng=None)

Returns a new distribution with all nonzero probabilities perturbed.

Probabilities which are zero in the pmf cannot be perturbed by this method. All other probabilities are perturbed via the following process:

  1. Initial pmf p lives on the n-simplex.

  2. Transform p via ilr (isometric logarithmic ratio) transform.

  3. Uniformly draw n random numbers between [0,1].

  4. Construct new transformed pmf: p2_ilr = p1_ilr + eps * rand

  5. Apply inverse ilr transformation.

Practically, a large value of eps means that there is a better chance the perturbation will take the distribution closer to the simplex boundary. Large distributions (with more than 60 elements) fail, due to some underflow issue with the ilr transformation.

Parameters:
  • pmf (NumPy array, shape (n,) or (k,n)) – The distribution to be perturbed. Assumes pmf represents linearly distributed probabilities. One may pass in k such distributions.

  • eps (float) – The scaling factor used for perturbing. Values of 10 correspond to large perturbations for the 1-simplex.

  • shape (str) – The type of neighborhood to draw from. Valid options are ‘square’ or ‘ball’. For ‘square’, a point is chosen uniformly from a unit square centered around pmf in ilr coordinates. For ‘ball’ a point is chosen uniformly from the unit circle centered around the pmf in ilr coordinates. In both cases, the region is then scaled by eps.

  • rng (np.random.Generator, np.random.RandomState, int, None) – A random number generator. If None, then dit.math.prng is used.

Returns:

out – The perturbed distribution.

Return type:

NumPy array

References

For details on the isometric log-ratio transformation see [1].

prod(vals, start=1)[source]

Compute the product of values in vals.

Parameters:
  • vals (iterable) – The values to compute the product of.

  • start (object) – The multiplicative identity to use.

Returns:

p – The product of values in vals.

Return type:

object

sample(dist, size=None, rand=None, rng=None)[source]

Returns a sample from a discrete distribution.

Parameters:
  • dist (Dit distribution) – The distribution from which the sample is drawn.

  • size (int or None) – The number of samples to draw from the distribution. If None, then a single sample is returned. Otherwise, a list of samples if returned.

  • rand (float or NumPy array) – When size is None, rand should be a random number drawn uniformly from the interval [0,1]. When size is not None, then this should be a NumPy array of random numbers. In either situation, if rand is None, then the random number(s) will be drawn from a pseudo random number generator.

  • rng (np.random.Generator, np.random.RandomState, int, None) – A random number generator with a rand’ method that returns a random number between 0 and 1 when called with no arguments. If unspecified, then we use the random number generator on the distribution. Thus, the `dist must have a rng attribute if rng is None.

Returns:

s – The sample drawn from the distribution.

Return type:

sample

sample_simplex(dim, num_samples=1, rng=None)[source]

Sample uniformly from the simplex.

Parameters:
  • dim (int) – The dimension of the simplex to sample from.

  • num_samples (int) – The number of samples to generate.

  • rng (np.random.Generator, None) – An optional random number generator to draw from. If None (default), the global np.random state is used (backwards-compatible).

Returns:

pmf – A matrix of shape (num_samples, dim), where each pmf[i] is a sample from the simplex.

Return type:

np.ndarray

sigma_algebra(C, X=None)[source]

Returns the sigma algebra generated by the subsets in C.

Let X be a set and C be a collection of subsets of X. The sigma algebra generated by the subsets in C is the smallest sigma-algebra which contains every subset in C.

Parameters:
  • C (set of frozensets) – The set of subsets of X.

  • X (frozenset, None) – The underlying set. If None, then X is taken to be the union of the sets in C.

Returns:

sC – The sigma-algebra generated by C.

Return type:

frozenset of frozensets

Notes

The algorithm run time is generally exponential in |X|, the size of X.