interface#

This module defines a friendly interface for creating models in the Pangolin IR.

Working with RVs#

An RV represents a scalar or array-shaped value in a probabilistic model. Calling a distribution function creates an RV; it does not draw a sample. Arithmetic expressions create additional RVs:

>>> from pangolin import interface as pi
>>> slope = pi.normal(0, 1)
>>> mean = 2 * slope + 1
>>> observation = pi.normal(mean, 0.5)
>>> pi.print_upstream(observation, locals())
shape | statement
----- | ---------
()    | a = 2
()    | b = 0
()    | c = 1
()    | slope ~ normal(b, c)
()    | d = mul(a, slope)
()    | e = 1
()    | mean = add(d, e)
()    | f = 0.5
()    | observation ~ normal(mean, f)

Most graph-building functions accept RVLike inputs: RVs, numbers, or numeric arrays. Numbers and arrays become constant RVs automatically.

Every RV has a fixed shape, available as x.shape. Scalars have shape ():

>>> x = pi.normal(0, 1)
>>> x.shape
()
>>> y = pi.constant([1, 2, 3])
>>> y.shape
(3,)

You can use familiar Python notation instead of calling the corresponding functions:

Notation

Equivalent function call

x + y

pi.add(x, y)

x - y

pi.sub(x, y)

x * y

pi.mul(x, y)

x / y

pi.div(x, y)

x ** y

pi.pow(x, y)

abs(x)

pi.abs(x)

x @ y

pi.matmul(x, y)

x.T

pi.transpose(x)

x[i, j]

pi.oindex(x, i, j)

For RVs created using the default interface, these are shorthand for the corresponding function calls and follow the same rules.

Broadcasting is configurable. The default interface uses simple broadcasting: scalar arguments can be combined with arrays, while all non-scalar arguments must have the same shape. This applies to scalar distribution functions and scalar arithmetic:

>>> x = pi.normal([0, 1, 2], 1)
>>> x.shape
(3,)
>>> y = 2 * x + 1
>>> y.shape
(3,)

You can disable broadcasting, allow rank promotion, or use NumPy-style broadcasting. Use pi.overload(...) for a temporary change or create a separately configured Interface. See Broadcasting for the rules and examples.

Combinators take ordinary Python graph-building functions and return new graph-building functions. For example, vmap turns a function into one that operates across an array:

>>> def shifted_normal(mean):
...     return pi.normal(mean, 1) + 2
>>> mapped_normal = pi.vmap(shifted_normal)
>>> means = pi.constant([0, 1, 2])
>>> x = mapped_normal(means)
>>> x.shape
(3,)

Combinators can be combined: for example, vmap can map a function built using scan to create multiple time series. See Combinators for the available operations.

  • See Examples for examples using arrays, time series, and nested combinators.

  • See Broadcasting for broadcasting rules and configuration options.

  • See Indexing for indexing rules and examples.

Reference card#

The entire interface is based on methods that create pangolin.ir.RV objects (or that create functions that create pangolin.ir.RV objects).

Here are the main public tools:

Constants#

constant(value, /)

Create an interface RV representing a fixed numeric value.

Scalar arithmetic and mathematics#

add(a, b)

Create an RV by applying pangolin.ir.Add to its parents.

sub(a, b)

Create an RV by applying pangolin.ir.Sub to its parents.

mul(a, b)

Create an RV by applying pangolin.ir.Mul to its parents.

div(a, b)

Create an RV by applying pangolin.ir.Div to its parents.

pow(a, b)

Create an RV by applying pangolin.ir.Pow to its parents.

sqrt(x)

Take a square root.

abs(a)

Create an RV by applying pangolin.ir.Abs to its parents.

minimum(a, b)

Create an RV by applying pangolin.ir.Minimum to its parents.

maximum(a, b)

Create an RV by applying pangolin.ir.Maximum to its parents.

arccos(a)

Create an RV by applying pangolin.ir.Arccos to its parents.

arccosh(a)

Create an RV by applying pangolin.ir.Arccosh to its parents.

arcsin(a)

Create an RV by applying pangolin.ir.Arcsin to its parents.

arcsinh(a)

Create an RV by applying pangolin.ir.Arcsinh to its parents.

arctan(a)

Create an RV by applying pangolin.ir.Arctan to its parents.

arctanh(a)

Create an RV by applying pangolin.ir.Arctanh to its parents.

cos(a)

Create an RV by applying pangolin.ir.Cos to its parents.

cosh(a)

Create an RV by applying pangolin.ir.Cosh to its parents.

exp(a)

Create an RV by applying pangolin.ir.Exp to its parents.

inv_logit(a)

Create an RV by applying pangolin.ir.InvLogit to its parents.

expit(a)

An alias for pangolin.interface.inv_logit().

sigmoid(a)

An alias for pangolin.interface.inv_logit().

log(a)

Create an RV by applying pangolin.ir.Log to its parents.

loggamma(a)

Create an RV by applying pangolin.ir.Loggamma to its parents.

logit(a)

Create an RV by applying pangolin.ir.Logit to its parents.

sin(a)

Create an RV by applying pangolin.ir.Sin to its parents.

sinh(a)

Create an RV by applying pangolin.ir.Sinh to its parents.

step(a)

Create an RV by applying pangolin.ir.Step to its parents.

tan(a)

Create an RV by applying pangolin.ir.Tan to its parents.

tanh(a)

Create an RV by applying pangolin.ir.Tanh to its parents.

Array operations and linear algebra#

matmul(a, b)

Multiply two vectors or matrices.

transpose(a)

Transpose a matrix.

inv(a)

Invert a square matrix.

cholesky(a)

Compute the lower-triangular Cholesky factor of a square matrix.

diag(a)

Extract the diagonal of a square matrix as a vector.

diag_matrix(a)

Construct a square diagonal matrix from a vector.

softmax(a)

Apply the softmax function to a vector.

concatenate(*arrays[, axis])

Concatenate arrays along an existing axis without broadcasting.

sum(x, axis)

Sum an array along one axis, removing that axis from the result.

fill_tril(params)

Fill a lower-triangular matrix row by row from a vector.

extract_tril(L)

Extract the lower-triangular entries of a square matrix row by row.

Indexing#

See Indexing for indexing rules and examples.

oindex(x, *indices)

Index an RV using fully orthogonal indexing.

vindex(var, *indices)

Index an RV using fully vectorized indexing.

Scalar distributions#

normal(mu, sigma)

Create a Normal distributed RV (Wikipedia).

normal_prec(mu, tau)

Create a NormalPrec distributed RV (Wikipedia).

lognormal(mu, sigma)

Create a Lognormal distributed RV (Wikipedia).

cauchy(mu, sigma)

Create a Cauchy distributed RV (Wikipedia).

bernoulli(theta)

Create a Bernoulli distributed RV (Wikipedia).

bernoulli_logit(theta)

Create a BernoulliLogit distributed RV.

binomial(N, theta)

Create a Binomial distributed RV (Wikipedia).

uniform(alpha, beta)

Create a Uniform distributed RV (Wikipedia).

beta(alpha, beta)

Create a Beta distributed RV (Wikipedia).

beta_binomial(N, alpha, beta)

Create a BetaBinomial distributed RV (Wikipedia).

exponential(beta)

Create a Exponential distributed RV (Wikipedia).

gamma(alpha, beta)

Create a Gamma distributed RV (Wikipedia).

poisson(lambd)

Create a Poisson distributed RV (Wikipedia).

student_t(nu, mu, sigma)

Create a StudentT distributed RV (Wikipedia).

Multivariate distributions#

multi_normal(mean, cov)

Create a multivariate normal RV.

categorical(theta)

Create a scalar categorical RV (Wikipedia).

multinomial(n, p)

Create a multinomial RV (Wikipedia).

dirichlet(alpha)

Create a simplex-valued Dirichlet RV (Wikipedia).

wishart(nu, scale)

Create a matrix-valued Wishart RV (Wikipedia).

Bijected distributions#

Transform

Construct transformed distributions using an invertible transformation.

compose_transforms()

Compose Transforms in left-to-right application order.

tforms

Standard transform library.

Combinators#

The combinators and Transform machinery are also available in pangolin.functional. For their IR-level contracts, see functional.

broadcast()

Broadcast a scalar function.

vmap()

Map a function over argument axes.

loop()

Build a loop with vectorized and sequential axes.

seq()

Specify a sequential loop axis.

vfor()

Build a vectorized indexed loop.

sfor()

Build a sequential indexed loop.

log_prob()

Construct a log-probability graph.

cdf()

Construct a cumulative-probability graph.

quantile()

Construct a scalar quantile graph.

truncated()

Restrict scalar distributions to a shared interval.

grad()

Differentiate a scalar-valued function.

vjp()

Construct a vector-Jacobian product.

composite()

Build a Composite operation.

scan()

Build a recurrence.

Graph inspection#

upstream_nodes()

Find upstream graph nodes.

print_upstream()

Print upstream RVs as a table.

graph_upstream()

Print upstream RVs as a Unicode DAG.

ir_code()

Inspect a graph-building function as IR code.

signature()

Describe the inputs and output of a function call.

Configuration#

The default interface uses simple broadcasting. Use with pi.overload(broadcasting="rank") for a temporary change. To create a separate configured interface, see Interface.

Interface

Create a separately configured interface.

overload()

Temporarily change the default interface’s configuration.

See Broadcasting for the rules and examples for each mode.