ir

Contents

ir#

Intermediate representation for probabilistic models.

Pangolin IR is an immutable, backend-independent DAG of random variables. Each RV is produced from parent random variables by either a deterministic function or a conditional distribution. Constants are constant random variables under the same definition.

The IR represents collections of dependent random variables; execution, sampling, density evaluation, and inference are provided by backends and inference engines. Models may be defined directly with the IR, but most users will construct them through pangolin.interface.

The IR has two core abstractions: Op and RV. An Op describes a deterministic function or conditional distribution and never refers to an RV. An RV is a node in a model DAG, consisting of one Op and an ordered tuple of parent RV objects. Thus, an Op describes what is applied, while an RV records where it is applied and which other RVs it depends on.

IR objects are immutable after construction. Normal attribute assignment and deletion cannot change an Op, Bijector, or RV. Constructors copy or normalize mutable inputs where necessary; for example, sequences are stored as tuples and constant arrays are copied and marked read-only.

Pangolin deliberately provides cooperative rather than “hard” immutability. Hard immutability is too contrary to Python’s object model: Python intentionally provides escape hatches such as object.__setattr__, __dict__, and mutable array flags. Attempting to prohibit every such escape hatch would add substantial machinery while still providing no security boundary. Code that deliberately uses those mechanisms is outside the immutability contract.

That’s the whole IR. Unlike in Pyro / NumPyro / PyMC / Tensorflow Probability, Random variables do not have names, and there is no notion of a “model” class. In Pangolin, you just work with RVs. You can assign those RVs to named variables or put them into tuples or lists or dicts if you want. But that’s up to you.

Other notes:

  • All RV objects have static shapes. The shape of an RV is recursively determined by its Op and the shapes of its parent RV objects.

Core types:

Type

Purpose

Shape

Static shape of an RV

Op

Base class for deterministic functions and distributions

ScalarOp

Base class for operations with scalar inputs and output

RV

Node in a probabilistic model DAG

Bijector

Descriptor for an invertible transformation

VMapStack

Type-hint-only alias for one or more nested VMap operations

Types of Op:

Type

Ops

Constants

Constant

Identity

Identity

Arithmetic

Add, Sub, Mul, Div

Trigonometry

Arccos, Arccosh, Arcsin, Arcsinh, Arctan, Arctanh, Cos, Cosh, Sin, Sinh, Tan, Tanh

Other scalar functions

Pow, Abs, Minimum, Maximum, Exp, InvLogit, Log, Loggamma, Logit, Step

Linear algebra

Matmul, Transpose, Inv, Cholesky

Other multivariate functions

Concatenate, Sum, Softmax, Diag, DiagMatrix

Scalar distributions

Normal, NormalPrec, Lognormal, Cauchy, Bernoulli, BernoulliLogit, Beta, Binomial, Categorical, Uniform, BetaBinomial, Exponential, Gamma, Poisson, StudentT

Multivariate distributions

MultiNormal, Multinomial, Dirichlet, Wishart

Control flow

VMap, Composite, Scan

Indexing

Index

Transformations

Bijected, Truncated

Distribution properties

LogProb, CDF, Quantile

Differentiation

VJP

In addition, this module provides the following utilities:

—

type pangolin.ir.Shape = tuple[int, ...]#

Static shape represented by a tuple of positive integer dimensions.

The empty tuple () represents a scalar.

class pangolin.ir.Op[source]#

Bases: ABC

Abstract base class for operators. An Op represents a deterministic function or distribution. All functionality for sampling or evaluating densities is left to inference backends. An Op is frozen after initialization.

Simple Op objects typically have no parameters. For example, Add() just represents scalar addition. The Op itself does not indicate what variables are being added together. Similarly, Normal() just represents a normal distribution, but it does not itself indicate what the mean and scale of that distribution are. More complex classes have constructors that take any parameters that must be fixed in order to maintain fixed shapes. For example, Sum takes the axis to sum over.

A concrete Op class must provide Op.random, indicating if an op is a conditional distribution (True) or a deterministic function (False). For classes where this is fixed, declare a boolean attribute with a docstring stating its value. For classes where it depends on the particular instance (e.g. VMap), provide a documented property returning a bool. Both are accessed as op.random.

A random Op must similarly provide Op.discrete as a boolean attribute or a property returning a boolean: True for discrete distributions and False for continuous ones. The base property returns None, which deterministic Ops can inherit. Higher-order Ops may derive both properties from a contained Op. As with Op.random, concrete subclasses document their fixed value or derivation rule. Op.__init__ checks that random Ops provide a boolean; subclasses must initialize fields used by these properties before calling super().__init__().

Every concrete Op provides a public Op.get_shape method. It accepts the shapes of the Op’s ordered parents, validates their number and compatibility, and returns the static output Shape. Parent requirements and output rules are part of each concrete Op’s documentation. Because different Ops have different arities, the base class deliberately types Op.get_shape as a weak callable; concrete methods expose their precise signatures wherever the arity is fixed.

An Op must provide structural equality and a compatible hash, as documented by Op.__eq__. The base implementation compares concrete types, which is sufficient for Ops with no constructor state. Ops with constructor state must override both Op.__eq__ and Op.__hash__.

get_shape: Callable[[...], Shape]#

Compute the output shape from the ordered shapes of an Op’s parents.

Each concrete Op implements this as a method taking one Shape argument for each parent, in parent order, and returning the output Shape. Fixed-arity Ops should name those arguments explicitly. Ops whose arity depends on constructor state may accept *parent_shapes, but must validate the number of arguments at runtime.

The implementation must validate that the parent shapes are valid for the operation and raise an exception when they are not. RV calls this method during construction and stores its result unchanged, so this is the operation’s validation boundary for parent shapes.

Examples

A fixed matrix-vector operation could implement get_shape as follows:

>>> class MatrixVectorProduct(Op):
...     random = False
...
...     def get_shape(self, matrix_shape: Shape, vector_shape: Shape) -> Shape:
...         if len(matrix_shape) != 2:
...             raise ValueError("matrix parent must be two-dimensional")
...         if len(vector_shape) != 1:
...             raise ValueError("vector parent must be one-dimensional")
...         if matrix_shape[1] != vector_shape[0]:
...             raise ValueError("matrix and vector dimensions must match")
...         return (matrix_shape[0],)

The arguments correspond to the two parents in order. Valid shapes produce the output shape:

>>> op = MatrixVectorProduct()
>>> op.get_shape((3, 4), (4,))
(3,)

Invalid shapes raise an exception rather than producing an invalid RV:

>>> op.get_shape((3, 4), (5,))
Traceback (most recent call last):
    ...
ValueError: matrix and vector dimensions must match
abstract property random: bool[source]#

Is this class a distribution (True) or a deterministic function (False)?

property discrete: bool | None[source]#

Return whether this distribution is discrete, or None when not applicable.

Returns:

bool | None – True for a discrete distribution and False for a continuous distribution. Deterministic Ops inherit the default None. Random Ops must override this property with a boolean attribute or a property returning a boolean.

__eq__(other)[source]#

Return whether two Ops have the same IR structure.

Ops are equal when they have the same concrete type and equal normalized constructor state. Constructors may normalize equivalent inputs, such as lists and tuples, to the same representation. This is structural equality, not algebraic equivalence. Equal Ops must have equal hashes.

Examples

Stateless Ops of the same type are equal.

>>> Normal() == Normal()
True

Normalized constructor state is compared.

>>> VMap(Normal(), [0, None]) == VMap(Normal(), (0, None))
True

Different constructor state is unequal.

>>> Sum(0) == Sum(1)
False

Equality is structural, not algebraic.

>>> Add() == Composite(2, (Add(),), ((0, 1),))
False
Return type:

bool

property name: str[source]#

Returns the name of the op class as a string

__repr__()[source]#

Return a structural Python representation of the operation.

The representation is constructor-shaped and recursively uses repr for contained IR objects. It is intended for inspecting the structure of the IR, but is not a serialization format and is not guaranteed to be executable Python. In particular, bulk data may be abbreviated.

__str__()[source]#

Return a compact, human-readable representation of the operation.

This representation recursively uses str for contained IR objects and favors readable expressions, such as normal instead of Normal(). It is not a serialization format or stable syntax.

Return type:

str

class pangolin.ir.ScalarOp[source]#

Bases: Op, ABC

Base class for operations whose parents and output are all scalar.

Scalar operations have class-fixed randomness and a class-fixed number of parents. Concrete subclasses declare random and _expected_parents. A parent count generates generic parent names; a mapping supplies names and descriptions for documentation and interface functions.

Random operations may also provide _wikipedia to override the Wikipedia page inferred from the class name, or set it to None to omit the link. Additional documentation can be supplied through _notes.

get_shape(*parents_shapes)[source]#

Return the scalar output shape after validating all parent shapes.

Parameters:

*parents_shapes (Shape) – One shape for each parent declared by the concrete ScalarOp. Every parent must have scalar shape ().

Returns:

Shape – Always ().

Raises:
  • TypeError – If the number of parent shapes is incorrect.

  • ValueError – If any parent is nonscalar.

Return type:

Shape

final class pangolin.ir.RV(op, *parents, interface=NO_INTERFACE)[source]#

Bases: Node

An RV is essentially just an Op and a tuple of parent RV objects.

Each construction creates a distinct graph node. Distinct RV nodes with random Op objects represent separate conditionally independent draws given their parents; reusing an RV object reuses the same draw.

The only purpose of an RV’s interface is to delegate Python syntax. For example, x + y calls x.interface.add(x, y), and x.T calls x.interface.transpose(x). Unsupported standard operations raise NotImplementedError. Additional public attributes call x.interface.get_attribute(x, name), which raises AttributeError unless the interface explicitly supports that name. RV-owned attributes and graph behavior always take precedence; unknown private and dunder attributes are not forwarded. The interface has no effect on the probabilistic interpretation of the DAG, and backend code should never need to inspect it.

Constant RVs can be converted to NumPy arrays with np.asarray(x) or x.to_numpy(). NumPy computations on these values return numerical arrays, not graph nodes. Conversion of other RVs raises TypeError.

Parameters:

Examples

>>> constant_op = Constant(3)
>>> x = RV(constant_op)
>>> x
RV(Constant(3))
>>> x.op
Constant(3)
>>> x.parents
()
>>> y = RV(constant_op)
>>> y
RV(Constant(3))
>>> normal_op = Normal()
>>> z = RV(normal_op, x, y)
>>> z
RV(Normal(), RV(Constant(3)), RV(Constant(3)))
>>> z.parents[0] == x
True
>>> z.parents[1] == y
True
__getattr__(name)[source]#

Delegate missing public attributes to the interface extension hook.

Parameters:

name (str)

Return type:

Any

property T: RV[source]#

Return the transpose selected by the interface.

to_numpy(dtype=None, *, copy=None)[source]#

Return the stored value of a Constant RV as a NumPy array.

Other Ops raise TypeError, including expressions with constant parents. This method does not evaluate the graph.

Parameters:
  • dtype (DTypeLike) – Optional output dtype.

  • copy (bool | None) – True always copies; None copies only when needed. False forbids copying and raises ValueError if a dtype conversion requires it. Without a copy, the returned array is read-only.

Return type:

ndarray

Examples

>>> x = RV(Constant([1, 2, 3]))
>>> x.to_numpy()
array([1, 2, 3])
>>> np.asarray(x)
array([1, 2, 3])
>>> x.to_numpy().flags.writeable
False
__array__(dtype=None, copy=None)[source]#

Implement NumPy conversion through to_numpy().

Parameters:
  • dtype (DTypeLike)

  • copy (bool | None)

Return type:

ndarray

property shape: Shape[source]#

The shape of the RV. (A tuple of ints.)

property ndim: int[source]#

The number of dimensions of the RV. Equal to the length of RV.shape.

__eq__(other)[source]#

Return whether other is the same RV node.

RV equality and hashing are identity-based, regardless of whether two RV objects have equal Op objects and parents. Use rv_equal to compare the values represented by RV graphs.

Examples

>>> x = RV(Constant(1))
>>> y = RV(Constant(1))
>>> x == y
False
>>> x == x
True
>>> rv_equal(x, y)
True
Parameters:

other (object)

Return type:

bool

__hash__()[source]#

Return the identity-based hash of this RV node.

Return type:

int

__repr__()[source]#

Return a structural Python representation of this RV.

The representation contains the RV’s operation followed by recursive representations of its ordered parents, extending the convention of Op.__repr__ to the graph.

Return type:

str

__str__()[source]#

Return a compact, human-readable expression for this RV.

The expression contains the compact representation of the operation followed by recursive representations of its ordered parents, extending the convention of Op.__str__ to the graph.

Return type:

str

class pangolin.ir.RVInterface[source]#

Bases: object

Provide typed targets for RV syntax, with rejecting defaults.

RVs forward standard syntax directly to these methods: for example, x + y calls x.interface.add(x, y). Subclasses implement whichever operations they support; unsupported operations raise NotImplementedError. Additional public attributes are provided explicitly through get_attribute, which otherwise raises AttributeError.

Notes

x.T calls x.interface.transpose(x). Bracket indexing calls x.interface.getitem(x, *indices); each interface chooses its indexing semantics. For example, pangolin.interface.Interface uses orthogonal indexing.

Additional public attributes call x.interface.get_attribute(x, name). Interface methods do not automatically become RV attributes. Core graph attributes such as parents, op, and shape always belong to RV, as do identity equality and immutability. Unknown private and dunder attributes are never automatically forwarded.

Standard RV operations, including x.T, have return type RV. Additional extensible attributes are statically typed as Any; explicit interface calls retain their method signatures. Implementing only the supported operations is enough to define an interface.

Examples

Pangolin’s standard interface exposes sum and vindex through get_attribute, but does not expose arbitrary interface methods as RV attributes:

>>> from pangolin import interface as pi
>>> x = pi.constant([[1, 2], [3, 4]])
>>> x.sum(axis=0).shape
(2,)
>>> x.T.shape
(2, 2)
>>> hasattr(x, "overload")
False
get_attribute(rv, name, /)[source]#

Provide an additional RV attribute, or raise if it is unsupported.

Parameters:
  • rv (RV)

  • name (str)

Return type:

Any

pangolin.ir.NO_INTERFACE: Final[RVInterface] = NO_INTERFACE#

The default interface, which rejects Python conveniences.

class pangolin.ir.Bijector(forward, inverse, log_det_jac, n_biject_params=0, *, sign=None)[source]#

Bases: object

Describe an invertible transformation using deterministic IR operations.

A Bijector is not an Op and cannot itself be attached to an RV. It is an immutable descriptor containing three deterministic operations. Bijected embeds that descriptor in a random Op so transformed distributions remain explicit in the IR and independent of any backend.

For a transformation y = T(x, *params), forward computes y and inverse computes x. log_det_jac receives both x and y, followed by the same parameters, and computes the scalar forward log absolute Jacobian determinant log |det ∇T(x)|. Supplying both values lets the operation use whichever representation is more convenient.

Optional sign is a deterministic Op returning scalar +1 for increasing or -1 for decreasing transformations. It receives every bijector parameter in order, without the forward input or output. By supplying it, the author guarantees a continuous, strictly monotone scalar bijection for every valid parameter setting.

In general if Y=T(X) then

P_X(x) = P_Y(T(x)) × |det ∇T(x)|

and

P_Y(y) = P_X(T⁻¹(y)) × |det ∇T⁻¹(y)|.

That is, P_Y is the pushforward of P_X and P_X is the pullback of P_Y.

Thus a transformed distribution samples x from its base distribution and applies forward. Its log density applies inverse and subtracts the forward log determinant.

Parameters:
  • forward (Op) – Deterministic operation implementing T(x, *params).

  • inverse (Op) – Deterministic operation implementing T⁻¹(y, *params).

  • log_det_jac (Op) – Deterministic operation implementing log |det ∇T(x)| from (x, y, *params).

  • n_biject_params (int) – Number of parameter RVs accepted by every supplied operation.

  • sign (Op | None) – Optional deterministic Op returning scalar -1 or +1 from all ordered bijector parameters. Describes scalar applications only.

Examples

An implementation of the exp transformation.

>>> forward = Exp()
>>> inverse = Log()
>>> log_jac_det = Composite(
...     2,
...     (Identity(),),
...     [[0]])
>>> bijector = Bijector(forward, inverse, log_jac_det)
>>> isinstance(bijector, Op)
False
>>> print(bijector)
bijector(exp, log, composite(2, [identity], [[0]]))

The exponential bijection is increasing and has no parameters:

>>> increasing = Bijector(Exp(), Log(), log_jac_det, sign=Constant(1))
>>> increasing.sign
Constant(1)
>>> increasing.get_shape(())
()

Scaled logit maps (lo, hi) to the reals, for finite parameters lo < hi. Its forward function is logit((x - lo) / (hi - lo)) and its inverse is lo + (hi - lo) * inv_logit(y):

>>> forward = Composite(
...     3, (Sub(), Sub(), Div(), Logit()),
...     ((0, 1), (2, 1), (3, 4), (5,)))
>>> inverse = Composite(
...     3, (Sub(), InvLogit(), Mul(), Add()),
...     ((2, 1), (0,), (3, 4), (1, 5)))

The forward log-Jacobian is log((hi - lo) / ((x - lo) * (hi - x))). Its inputs are (x, y, lo, hi):

>>> log_jac_det = Composite(
...     4, (Sub(), Sub(), Sub(), Mul(), Div(), Log()),
...     ((3, 2), (0, 2), (3, 0), (5, 6), (4, 7), (8,)))

The sign Op receives (lo, hi), even though the sign is constant:

>>> sign = Composite(2, (Constant(1),), ((),))
>>> scaled_logit = Bijector(forward, inverse, log_jac_det, 2, sign=sign)
>>> scaled_logit.get_shape((), (), ())
()
>>> scaled_logit.sign
Composite(2, [Constant(1)], [[]])
Raises:
  • TypeError – If an operation or parameter count has an invalid type.

  • ValueError – If any operation is random or n_biject_params is negative. Values produced by the sign Op are an author guarantee, not evaluated during construction.

Parameters:
  • forward (Op)

  • inverse (Op)

  • log_det_jac (Op)

  • n_biject_params (int)

  • sign (Op | None)

get_shape(x_shape, *param_shapes)[source]#

Validate operation shapes and return the transformed shape.

Parameters:
Return type:

Shape

__eq__(other)[source]#

Return whether two Bijectors have the same concrete type and structural state.

Parameters:

other (object)

Return type:

bool

__repr__()[source]#

Return a structural Python representation of the bijector.

This follows the same constructor-shaped convention as Op.__repr__ and recursively uses repr for its operations.

__str__()[source]#

Return a compact, human-readable representation of the bijector.

This follows the convention of Op.__str__ and recursively uses str for its operations.

class pangolin.ir.Identity[source]#

Bases: Op

Return one parent unchanged.

random: bool = False#

False

get_shape(par_shape)[source]#

Return the parent shape unchanged.

Parameters:

par_shape (Shape) – Shape of the single parent.

Returns:

Shape – par_shape.

Return type:

Shape

class pangolin.ir.Constant(value)[source]#

Bases: Op

Represent a numeric constant with no parents.

The input is normalized to a C-contiguous NumPy array whose buffer is immutable. The public value remains an ordinary NumPy array, but neither it nor a view sharing its buffer can be made writable.

Constant equality is structural. Two Constant objects are equal when they have the same concrete type, dtype, shape, and C-order data bytes. Consequently, signed zeros are distinct, while NaNs are equal only when their stored bit representations are equal. Hashing uses exactly the same state.

Parameters:

value (ArrayLike) – Numeric value that NumPy can convert to an array.

value#

Immutable NumPy array containing the normalized value.

Raises:

ValueError – If the value is empty or does not have a numeric dtype.

Parameters:

value (ArrayLike)

Examples

>>> constant = Constant([[1.0, 2.0]])
>>> constant.value.tolist()
[[1.0, 2.0]]
>>> constant.value.flags.writeable
False
random: bool = False#

False

get_shape()[source]#

Return the shape of the stored constant.

Constant has no parents, so this method accepts no parent shapes.

Returns:

Shape – Shape of value.

Return type:

Shape

__eq__(other)[source]#

Return whether other has the same stored constant data.

Parameters:

other (object)

Return type:

bool

__hash__()[source]#

Return a hash of the Constant’s concrete type and stored data.

class pangolin.ir.Add[source]#

Bases: ScalarOp

Scalar Add operation.

The constructor takes no arguments. When used in an RV, this operation expects the following scalar parents:

  • a: parent 0

  • b: parent 1

Add expects exactly 2 scalar parents. Its shape behavior is inherited from ScalarOp.get_shape: Every parent must have scalar shape (), and the output shape is ().

Examples

>>> op = Add()
>>> op
Add()
>>> print(op)
add
>>> op.random
False
random: bool = False#

False

class pangolin.ir.Sub[source]#

Bases: ScalarOp

Scalar Sub operation.

The constructor takes no arguments. When used in an RV, this operation expects the following scalar parents:

  • a: parent 0

  • b: parent 1

Sub expects exactly 2 scalar parents. Its shape behavior is inherited from ScalarOp.get_shape: Every parent must have scalar shape (), and the output shape is ().

Examples

>>> op = Sub()
>>> op
Sub()
>>> print(op)
sub
>>> op.random
False
random: bool = False#

False

class pangolin.ir.Mul[source]#

Bases: ScalarOp

Scalar Mul operation.

The constructor takes no arguments. When used in an RV, this operation expects the following scalar parents:

  • a: parent 0

  • b: parent 1

Mul expects exactly 2 scalar parents. Its shape behavior is inherited from ScalarOp.get_shape: Every parent must have scalar shape (), and the output shape is ().

Examples

>>> op = Mul()
>>> op
Mul()
>>> print(op)
mul
>>> op.random
False
random: bool = False#

False

class pangolin.ir.Div[source]#

Bases: ScalarOp

Scalar Div operation.

The constructor takes no arguments. When used in an RV, this operation expects the following scalar parents:

  • a: parent 0

  • b: parent 1

Div expects exactly 2 scalar parents. Its shape behavior is inherited from ScalarOp.get_shape: Every parent must have scalar shape (), and the output shape is ().

Examples

>>> op = Div()
>>> op
Div()
>>> print(op)
div
>>> op.random
False
random: bool = False#

False

class pangolin.ir.Pow[source]#

Bases: ScalarOp

Scalar Pow operation.

The constructor takes no arguments. When used in an RV, this operation expects the following scalar parents:

  • a: parent 0

  • b: parent 1

Pow expects exactly 2 scalar parents. Its shape behavior is inherited from ScalarOp.get_shape: Every parent must have scalar shape (), and the output shape is ().

Examples

>>> op = Pow()
>>> op
Pow()
>>> print(op)
pow
>>> op.random
False
random: bool = False#

False

class pangolin.ir.Arccos[source]#

Bases: ScalarOp

Scalar Arccos operation.

The constructor takes no arguments. When used in an RV, this operation expects the following scalar parents:

  • a: parent 0

Arccos expects exactly 1 scalar parent. Its shape behavior is inherited from ScalarOp.get_shape: Every parent must have scalar shape (), and the output shape is ().

Examples

>>> op = Arccos()
>>> op
Arccos()
>>> print(op)
arccos
>>> op.random
False
random: bool = False#

False

class pangolin.ir.Arccosh[source]#

Bases: ScalarOp

Scalar Arccosh operation.

The constructor takes no arguments. When used in an RV, this operation expects the following scalar parents:

  • a: parent 0

Arccosh expects exactly 1 scalar parent. Its shape behavior is inherited from ScalarOp.get_shape: Every parent must have scalar shape (), and the output shape is ().

Examples

>>> op = Arccosh()
>>> op
Arccosh()
>>> print(op)
arccosh
>>> op.random
False
random: bool = False#

False

class pangolin.ir.Arcsin[source]#

Bases: ScalarOp

Scalar Arcsin operation.

The constructor takes no arguments. When used in an RV, this operation expects the following scalar parents:

  • a: parent 0

Arcsin expects exactly 1 scalar parent. Its shape behavior is inherited from ScalarOp.get_shape: Every parent must have scalar shape (), and the output shape is ().

Examples

>>> op = Arcsin()
>>> op
Arcsin()
>>> print(op)
arcsin
>>> op.random
False
random: bool = False#

False

class pangolin.ir.Arcsinh[source]#

Bases: ScalarOp

Scalar Arcsinh operation.

The constructor takes no arguments. When used in an RV, this operation expects the following scalar parents:

  • a: parent 0

Arcsinh expects exactly 1 scalar parent. Its shape behavior is inherited from ScalarOp.get_shape: Every parent must have scalar shape (), and the output shape is ().

Examples

>>> op = Arcsinh()
>>> op
Arcsinh()
>>> print(op)
arcsinh
>>> op.random
False
random: bool = False#

False

class pangolin.ir.Arctan[source]#

Bases: ScalarOp

Scalar Arctan operation.

The constructor takes no arguments. When used in an RV, this operation expects the following scalar parents:

  • a: parent 0

Arctan expects exactly 1 scalar parent. Its shape behavior is inherited from ScalarOp.get_shape: Every parent must have scalar shape (), and the output shape is ().

Examples

>>> op = Arctan()
>>> op
Arctan()
>>> print(op)
arctan
>>> op.random
False
random: bool = False#

False

class pangolin.ir.Arctanh[source]#

Bases: ScalarOp

Scalar Arctanh operation.

The constructor takes no arguments. When used in an RV, this operation expects the following scalar parents:

  • a: parent 0

Arctanh expects exactly 1 scalar parent. Its shape behavior is inherited from ScalarOp.get_shape: Every parent must have scalar shape (), and the output shape is ().

Examples

>>> op = Arctanh()
>>> op
Arctanh()
>>> print(op)
arctanh
>>> op.random
False
random: bool = False#

False

class pangolin.ir.Cos[source]#

Bases: ScalarOp

Scalar Cos operation.

The constructor takes no arguments. When used in an RV, this operation expects the following scalar parents:

  • a: parent 0

Cos expects exactly 1 scalar parent. Its shape behavior is inherited from ScalarOp.get_shape: Every parent must have scalar shape (), and the output shape is ().

Examples

>>> op = Cos()
>>> op
Cos()
>>> print(op)
cos
>>> op.random
False
random: bool = False#

False

class pangolin.ir.Cosh[source]#

Bases: ScalarOp

Scalar Cosh operation.

The constructor takes no arguments. When used in an RV, this operation expects the following scalar parents:

  • a: parent 0

Cosh expects exactly 1 scalar parent. Its shape behavior is inherited from ScalarOp.get_shape: Every parent must have scalar shape (), and the output shape is ().

Examples

>>> op = Cosh()
>>> op
Cosh()
>>> print(op)
cosh
>>> op.random
False
random: bool = False#

False

class pangolin.ir.Sin[source]#

Bases: ScalarOp

Scalar Sin operation.

The constructor takes no arguments. When used in an RV, this operation expects the following scalar parents:

  • a: parent 0

Sin expects exactly 1 scalar parent. Its shape behavior is inherited from ScalarOp.get_shape: Every parent must have scalar shape (), and the output shape is ().

Examples

>>> op = Sin()
>>> op
Sin()
>>> print(op)
sin
>>> op.random
False
random: bool = False#

False

class pangolin.ir.Sinh[source]#

Bases: ScalarOp

Scalar Sinh operation.

The constructor takes no arguments. When used in an RV, this operation expects the following scalar parents:

  • a: parent 0

Sinh expects exactly 1 scalar parent. Its shape behavior is inherited from ScalarOp.get_shape: Every parent must have scalar shape (), and the output shape is ().

Examples

>>> op = Sinh()
>>> op
Sinh()
>>> print(op)
sinh
>>> op.random
False
random: bool = False#

False

class pangolin.ir.Tan[source]#

Bases: ScalarOp

Scalar Tan operation.

The constructor takes no arguments. When used in an RV, this operation expects the following scalar parents:

  • a: parent 0

Tan expects exactly 1 scalar parent. Its shape behavior is inherited from ScalarOp.get_shape: Every parent must have scalar shape (), and the output shape is ().

Examples

>>> op = Tan()
>>> op
Tan()
>>> print(op)
tan
>>> op.random
False
random: bool = False#

False

class pangolin.ir.Tanh[source]#

Bases: ScalarOp

Scalar Tanh operation.

The constructor takes no arguments. When used in an RV, this operation expects the following scalar parents:

  • a: parent 0

Tanh expects exactly 1 scalar parent. Its shape behavior is inherited from ScalarOp.get_shape: Every parent must have scalar shape (), and the output shape is ().

Examples

>>> op = Tanh()
>>> op
Tanh()
>>> print(op)
tanh
>>> op.random
False
random: bool = False#

False

class pangolin.ir.Abs[source]#

Bases: ScalarOp

Scalar Abs operation.

The constructor takes no arguments. When used in an RV, this operation expects the following scalar parents:

  • a: parent 0

Abs expects exactly 1 scalar parent. Its shape behavior is inherited from ScalarOp.get_shape: Every parent must have scalar shape (), and the output shape is ().

Examples

>>> op = Abs()
>>> op
Abs()
>>> print(op)
abs
>>> op.random
False
random: bool = False#

False

class pangolin.ir.Minimum[source]#

Bases: ScalarOp

Scalar Minimum operation.

The constructor takes no arguments. When used in an RV, this operation expects the following scalar parents:

  • a: first value

  • b: second value

Minimum expects exactly 2 scalar parents. Its shape behavior is inherited from ScalarOp.get_shape: Every parent must have scalar shape (), and the output shape is ().

Examples

>>> op = Minimum()
>>> op
Minimum()
>>> print(op)
minimum
>>> op.random
False

Notes

Returns the smaller of the two values. If either value is NaN, the result is NaN.

random: bool = False#

False

class pangolin.ir.Maximum[source]#

Bases: ScalarOp

Scalar Maximum operation.

The constructor takes no arguments. When used in an RV, this operation expects the following scalar parents:

  • a: first value

  • b: second value

Maximum expects exactly 2 scalar parents. Its shape behavior is inherited from ScalarOp.get_shape: Every parent must have scalar shape (), and the output shape is ().

Examples

>>> op = Maximum()
>>> op
Maximum()
>>> print(op)
maximum
>>> op.random
False

Notes

Returns the larger of the two values. If either value is NaN, the result is NaN.

random: bool = False#

False

class pangolin.ir.Exp[source]#

Bases: ScalarOp

Scalar Exp operation.

The constructor takes no arguments. When used in an RV, this operation expects the following scalar parents:

  • a: parent 0

Exp expects exactly 1 scalar parent. Its shape behavior is inherited from ScalarOp.get_shape: Every parent must have scalar shape (), and the output shape is ().

Examples

>>> op = Exp()
>>> op
Exp()
>>> print(op)
exp
>>> op.random
False
random: bool = False#

False

class pangolin.ir.InvLogit[source]#

Bases: ScalarOp

Scalar InvLogit operation.

The constructor takes no arguments. When used in an RV, this operation expects the following scalar parents:

  • a: parent 0

InvLogit expects exactly 1 scalar parent. Its shape behavior is inherited from ScalarOp.get_shape: Every parent must have scalar shape (), and the output shape is ().

Examples

>>> op = InvLogit()
>>> op
InvLogit()
>>> print(op)
inv_logit
>>> op.random
False
random: bool = False#

False

class pangolin.ir.Log[source]#

Bases: ScalarOp

Scalar Log operation.

The constructor takes no arguments. When used in an RV, this operation expects the following scalar parents:

  • a: parent 0

Log expects exactly 1 scalar parent. Its shape behavior is inherited from ScalarOp.get_shape: Every parent must have scalar shape (), and the output shape is ().

Examples

>>> op = Log()
>>> op
Log()
>>> print(op)
log
>>> op.random
False
random: bool = False#

False

class pangolin.ir.Logit[source]#

Bases: ScalarOp

Scalar Logit operation.

The constructor takes no arguments. When used in an RV, this operation expects the following scalar parents:

  • a: parent 0

Logit expects exactly 1 scalar parent. Its shape behavior is inherited from ScalarOp.get_shape: Every parent must have scalar shape (), and the output shape is ().

Examples

>>> op = Logit()
>>> op
Logit()
>>> print(op)
logit
>>> op.random
False
random: bool = False#

False

class pangolin.ir.Step[source]#

Bases: ScalarOp

Scalar Step operation.

The constructor takes no arguments. When used in an RV, this operation expects the following scalar parents:

  • a: parent 0

Step expects exactly 1 scalar parent. Its shape behavior is inherited from ScalarOp.get_shape: Every parent must have scalar shape (), and the output shape is ().

Examples

>>> op = Step()
>>> op
Step()
>>> print(op)
step
>>> op.random
False
random: bool = False#

False

class pangolin.ir.Loggamma[source]#

Bases: ScalarOp

Scalar Loggamma operation.

The constructor takes no arguments. When used in an RV, this operation expects the following scalar parents:

  • a: parent 0

Loggamma expects exactly 1 scalar parent. Its shape behavior is inherited from ScalarOp.get_shape: Every parent must have scalar shape (), and the output shape is ().

Examples

>>> op = Loggamma()
>>> op
Loggamma()
>>> print(op)
loggamma
>>> op.random
False

Notes

Do we want scipy.special.loggamma or scipy.special.gammaln?

random: bool = False#

False

class pangolin.ir.Matmul[source]#

Bases: Op

A class that does matrix multiplication, following the rules of numpy.matmul. Currently only 1d and 2d arrays are supported.

Examples

>>> op = Matmul()
>>> op
Matmul()
>>> print(op)
matmul
>>> op.random
False
random: bool = False#

False

get_shape(a_shape, b_shape)[source]#

Return the shape of a vector or matrix product.

Parameters:
  • a_shape (Shape) – One- or two-dimensional shape of the left parent.

  • b_shape (Shape) – One- or two-dimensional shape of the right parent. Its contracted dimension must match that of a_shape.

Returns:

Shape – Scalar for vector-vector multiplication, a vector for matrix-vector or vector-matrix multiplication, and a matrix for matrix-matrix multiplication.

Raises:

ValueError – If either parent is not one- or two-dimensional or their contracted dimensions do not match.

Return type:

Shape

Examples

>>> op = Matmul()
>>> op.get_shape((4,), (4,)) # inner product
()
>>> op.get_shape((5,4), (4,)) # matrix-vector
(5,)
>>> op.get_shape((5,), (5,4)) # vector-matrix
(4,)
>>> op.get_shape((5,4), (4,3)) # matrix-matrix
(5, 3)
>>> op.get_shape((5,5), (10, 10)) # incoherent shapes, error expected
Traceback (most recent call last):
...
ValueError: Matmul parent shapes do not match ((5, 5) vs. (10, 10))
class pangolin.ir.Inv[source]#

Bases: Op

Take the inverse of a square matrix.

random: bool = False#

False

get_shape(p_shape)[source]#

Return the unchanged shape of a square matrix parent.

Parameters:

p_shape (Shape) – Two-dimensional square shape.

Returns:

Shape – p_shape.

Raises:

ValueError – If the parent is not a square matrix.

Return type:

Shape

class pangolin.ir.Cholesky[source]#

Bases: Op

Compute the Cholesky decomposition of a square matrix.

random: bool = False#

False

get_shape(p_shape)[source]#

Return the unchanged shape of a square matrix parent.

Parameters:

p_shape (Shape) – Two-dimensional square shape.

Returns:

Shape – p_shape.

Raises:

ValueError – If the parent is not a square matrix.

Return type:

Shape

class pangolin.ir.Transpose[source]#

Bases: Op

Take a transpose.

Unlike in many libraries this only works for 2D arrays, rather than reversing all dimensions. The logic is that 99% of the time, calling transpose on a 1D array and getting the original array (like in NumPy / JAX / Pytorch) is a bug. And calling transpose on a 4d array and reversing the dimensions is almost never useful. So, 2D transpose only!

random: bool = False#

False

get_shape(p_shape)[source]#

Reverse the dimensions of a two-dimensional parent shape.

Parameters:

p_shape (Shape) – Two-dimensional parent shape.

Returns:

Shape – (p_shape[1], p_shape[0]).

Raises:

ValueError – If the parent is not two-dimensional.

Return type:

Shape

class pangolin.ir.Diag[source]#

Bases: Op

Extract the diagonal of a square matrix.

random: bool = False#

False

get_shape(p_shape)[source]#

Return the vector shape of a square matrix’s diagonal.

Parameters:

p_shape (Shape) – Two-dimensional square shape.

Returns:

Shape – (p_shape[0],).

Raises:

ValueError – If the parent is not a square matrix.

Return type:

Shape

class pangolin.ir.DiagMatrix[source]#

Bases: Op

Construct a square diagonal matrix from a vector.

random: bool = False#

False

get_shape(p_shape)[source]#

Return the square matrix shape constructed from a vector parent.

Parameters:

p_shape (Shape) – One-dimensional vector shape.

Returns:

Shape – (p_shape[0], p_shape[0]).

Raises:

ValueError – If the parent is not one-dimensional.

Return type:

Shape

class pangolin.ir.Softmax[source]#

Bases: Op

Apply softmax to a one-dimensional array.

The output has the same shape as the input.

Examples

>>> Softmax().get_shape((3,))
(3,)
random: bool = False#

False

get_shape(p_shape)[source]#

Return the unchanged shape of a one-dimensional input.

Parameters:

p_shape (Shape) – One-dimensional parent shape.

Returns:

Shape – p_shape.

Raises:

ValueError – If the input is not one-dimensional.

Return type:

Shape

class pangolin.ir.Sum(axis)[source]#

Bases: Op

Sum an array along one axis.

Parameters:

axis (int) – Axis to sum over. Negative axes count from the end.

random: bool = False#

False

get_shape(x_shape)[source]#

Remove the configured axis from the parent shape.

Parameters:

x_shape (Shape) – Shape of the array to sum. It must contain axis.

Returns:

Shape – x_shape with the configured axis removed.

Raises:

ValueError – If axis is outside x_shape or x_shape is scalar.

Return type:

Shape

class pangolin.ir.Concatenate(axis=0)[source]#

Bases: Op

Concatenate arrays along an existing axis.

Every parent must have the same rank and equal dimensions except along axis. The output retains that rank and has the sum of the parent dimensions along axis. Unlike stacking, concatenation does not introduce a new axis.

Parameters:

axis (int) – Existing axis along which to concatenate. Negative axes count from the end.

Examples

Concatenate matrices by rows using the default axis:

>>> Concatenate().get_shape((2, 3), (4, 3))
(6, 3)

Concatenate them by columns instead:

>>> Concatenate(axis=1).get_shape((2, 3), (2, 4))
(2, 7)
random: bool = False#

False

get_shape(*parent_shapes)[source]#

Join the parent shapes along the configured axis.

Parameters:

*parent_shapes (Shape) – One or more equal-rank shapes. Dimensions other than axis must match.

Returns:

Shape – Common parent shape with the dimensions along axis summed.

Raises:

ValueError – If there are no parents, axis is out of bounds, parent ranks differ, or a non-concatenated dimension differs.

Return type:

Shape

class pangolin.ir.Index[source]#

Bases: Op

Select a scalar entry from an array.

An Index RV has parents array, *indices, with exactly one scalar integer-valued index for each dimension of array. The output shape is always ().

Index itself does not represent slices or array indexing. These can be constructed using VMap around Index. Index parents may be random variables, although a backend need not support inference with random indices.

Examples

>>> op = Index()
>>> op.get_shape((5, 5, 5), (), (), ())
()
random: bool = False#

False

get_shape(var_shape, *indices_shapes)[source]#

Validate scalar indices and return the scalar output shape.

Parameters:
  • var_shape (Shape) – Shape of the array being indexed.

  • *indices_shapes (Shape) – Exactly one scalar shape () for each dimension of var_shape.

Returns:

Shape – Always ().

Raises:

ValueError – If the number of index shapes differs from the rank of var_shape, or any index is nonscalar.

Return type:

Shape

class pangolin.ir.Normal[source]#

Bases: ScalarOp

Scalar Normal distribution.

The constructor takes no arguments. When used in an RV, this operation expects the following scalar parents:

  • mu: location / mean

  • sigma: scale / standard deviation

Normal expects exactly 2 scalar parents. Its shape behavior is inherited from ScalarOp.get_shape: Every parent must have scalar shape (), and the output shape is ().

Examples

>>> op = Normal()
>>> op
Normal()
>>> print(op)
normal
>>> op.random
True
random: bool = True#

True

discrete: bool = False#

False

class pangolin.ir.NormalPrec[source]#

Bases: ScalarOp

Scalar NormalPrec distribution.

The constructor takes no arguments. When used in an RV, this operation expects the following scalar parents:

  • mu: location / mean

  • tau: precision / inverse variance

NormalPrec expects exactly 2 scalar parents. Its shape behavior is inherited from ScalarOp.get_shape: Every parent must have scalar shape (), and the output shape is ().

Examples

>>> op = NormalPrec()
>>> op
NormalPrec()
>>> print(op)
normal_prec
>>> op.random
True
random: bool = True#

True

discrete: bool = False#

False

class pangolin.ir.Lognormal[source]#

Bases: ScalarOp

Scalar Lognormal distribution.

The constructor takes no arguments. When used in an RV, this operation expects the following scalar parents:

  • mu: logarithm of location

  • sigma: logarithm of scale (not sigma squared!)

Lognormal expects exactly 2 scalar parents. Its shape behavior is inherited from ScalarOp.get_shape: Every parent must have scalar shape (), and the output shape is ().

Examples

>>> op = Lognormal()
>>> op
Lognormal()
>>> print(op)
lognormal
>>> op.random
True
random: bool = True#

True

discrete: bool = False#

False

class pangolin.ir.Bernoulli[source]#

Bases: ScalarOp

Scalar Bernoulli distribution.

The constructor takes no arguments. When used in an RV, this operation expects the following scalar parents:

  • theta: probability (between 0 and 1)

Bernoulli expects exactly 1 scalar parent. Its shape behavior is inherited from ScalarOp.get_shape: Every parent must have scalar shape (), and the output shape is ().

Examples

>>> op = Bernoulli()
>>> op
Bernoulli()
>>> print(op)
bernoulli
>>> op.random
True
random: bool = True#

True

discrete: bool = True#

True

class pangolin.ir.BernoulliLogit[source]#

Bases: ScalarOp

Scalar BernoulliLogit distribution.

The constructor takes no arguments. When used in an RV, this operation expects the following scalar parents:

  • theta: logit of probability (unbounded)

BernoulliLogit expects exactly 1 scalar parent. Its shape behavior is inherited from ScalarOp.get_shape: Every parent must have scalar shape (), and the output shape is ().

Examples

>>> op = BernoulliLogit()
>>> op
BernoulliLogit()
>>> print(op)
bernoulli_logit
>>> op.random
True
random: bool = True#

True

discrete: bool = True#

True

class pangolin.ir.Binomial[source]#

Bases: ScalarOp

Scalar Binomial distribution.

The constructor takes no arguments. When used in an RV, this operation expects the following scalar parents:

  • N: number of trials

  • theta: probability of success for each trial

Binomial expects exactly 2 scalar parents. Its shape behavior is inherited from ScalarOp.get_shape: Every parent must have scalar shape (), and the output shape is ().

Examples

>>> op = Binomial()
>>> op
Binomial()
>>> print(op)
binomial
>>> op.random
True
random: bool = True#

True

discrete: bool = True#

True

class pangolin.ir.Cauchy[source]#

Bases: ScalarOp

Scalar Cauchy distribution.

The constructor takes no arguments. When used in an RV, this operation expects the following scalar parents:

  • mu: location

  • sigma: scale

Cauchy expects exactly 2 scalar parents. Its shape behavior is inherited from ScalarOp.get_shape: Every parent must have scalar shape (), and the output shape is ().

Examples

>>> op = Cauchy()
>>> op
Cauchy()
>>> print(op)
cauchy
>>> op.random
True
random: bool = True#

True

discrete: bool = False#

False

class pangolin.ir.Uniform[source]#

Bases: ScalarOp

Scalar Uniform distribution.

The constructor takes no arguments. When used in an RV, this operation expects the following scalar parents:

  • alpha: lower bound

  • beta: upper bound

Uniform expects exactly 2 scalar parents. Its shape behavior is inherited from ScalarOp.get_shape: Every parent must have scalar shape (), and the output shape is ().

Examples

>>> op = Uniform()
>>> op
Uniform()
>>> print(op)
uniform
>>> op.random
True
random: bool = True#

True

discrete: bool = False#

False

class pangolin.ir.Beta[source]#

Bases: ScalarOp

Scalar Beta distribution.

The constructor takes no arguments. When used in an RV, this operation expects the following scalar parents:

  • alpha: shape

  • beta: shape

Beta expects exactly 2 scalar parents. Its shape behavior is inherited from ScalarOp.get_shape: Every parent must have scalar shape (), and the output shape is ().

Examples

>>> op = Beta()
>>> op
Beta()
>>> print(op)
beta
>>> op.random
True
random: bool = True#

True

discrete: bool = False#

False

class pangolin.ir.Exponential[source]#

Bases: ScalarOp

Scalar Exponential distribution.

The constructor takes no arguments. When used in an RV, this operation expects the following scalar parents:

  • beta: rate / inverse scale

Exponential expects exactly 1 scalar parent. Its shape behavior is inherited from ScalarOp.get_shape: Every parent must have scalar shape (), and the output shape is ().

Examples

>>> op = Exponential()
>>> op
Exponential()
>>> print(op)
exponential
>>> op.random
True
random: bool = True#

True

discrete: bool = False#

False

class pangolin.ir.Gamma[source]#

Bases: ScalarOp

Scalar Gamma distribution.

The constructor takes no arguments. When used in an RV, this operation expects the following scalar parents:

  • alpha: shape

  • beta: rate / inverse scale

Gamma expects exactly 2 scalar parents. Its shape behavior is inherited from ScalarOp.get_shape: Every parent must have scalar shape (), and the output shape is ().

Examples

>>> op = Gamma()
>>> op
Gamma()
>>> print(op)
gamma
>>> op.random
True

Notes

This follows Stan in using the “shape/rate” parameterization, not the “shape/scale” parameterization.

random: bool = True#

True

discrete: bool = False#

False

class pangolin.ir.Poisson[source]#

Bases: ScalarOp

Scalar Poisson distribution.

The constructor takes no arguments. When used in an RV, this operation expects the following scalar parents:

  • lambd: lambda

Poisson expects exactly 1 scalar parent. Its shape behavior is inherited from ScalarOp.get_shape: Every parent must have scalar shape (), and the output shape is ().

Examples

>>> op = Poisson()
>>> op
Poisson()
>>> print(op)
poisson
>>> op.random
True
random: bool = True#

True

discrete: bool = True#

True

class pangolin.ir.BetaBinomial[source]#

Bases: ScalarOp

Scalar BetaBinomial distribution.

The constructor takes no arguments. When used in an RV, this operation expects the following scalar parents:

  • N: as in binomial dist

  • alpha: as in beta dist

  • beta: as in beta dist

BetaBinomial expects exactly 3 scalar parents. Its shape behavior is inherited from ScalarOp.get_shape: Every parent must have scalar shape (), and the output shape is ().

Examples

>>> op = BetaBinomial()
>>> op
BetaBinomial()
>>> print(op)
beta_binomial
>>> op.random
True

Notes

This follows the (N,alpha,beta) convention of Stan (and Wikipedia). Some other systems (e.g. Numpyro) use alternate variable orderings. This is no problem for you as a user, since pangolin does the re-ordering for you based on the backend. But keep it in mind if translating a model from one system to another.

random: bool = True#

True

discrete: bool = True#

True

class pangolin.ir.StudentT[source]#

Bases: ScalarOp

Scalar StudentT distribution.

The constructor takes no arguments. When used in an RV, this operation expects the following scalar parents:

  • nu: degress of freedom

  • mu: location (often 0)

  • sigma: scale (often 1)

StudentT expects exactly 3 scalar parents. Its shape behavior is inherited from ScalarOp.get_shape: Every parent must have scalar shape (), and the output shape is ().

Examples

>>> op = StudentT()
>>> op
StudentT()
>>> print(op)
student_t
>>> op.random
True
random: bool = True#

True

discrete: bool = False#

False

class pangolin.ir.MultiNormal[source]#

Bases: Op

Represent a multivariate normal distribution.

When used in an RV, the parents are a mean vector followed by a covariance matrix.

random: bool = True#

True

discrete: bool = False#

False

get_shape(mean_shape, covariance_shape)[source]#

Return the event-vector shape after validating mean and covariance.

Parameters:
  • mean_shape (Shape) – One-dimensional mean-vector shape (n,).

  • covariance_shape (Shape) – Square covariance-matrix shape (n, n).

Returns:

Shape – mean_shape.

Raises:

ValueError – If the mean is not a vector or the covariance is not a square matrix matching its length.

Return type:

Shape

class pangolin.ir.Categorical[source]#

Bases: Op

Represent a categorical distribution.

A Categorical RV has one parent: a one-dimensional vector of weights. Its output is scalar.

Examples

>>> Categorical().get_shape((3,))
()
random: bool = True#

True

discrete: bool = True#

True

get_shape(weights_shape)[source]#

Return the scalar output shape for a vector of weights.

Parameters:

weights_shape (Shape) – One-dimensional shape of the categorical weights.

Returns:

Shape – ().

Raises:

ValueError – If the weights are not one-dimensional.

Return type:

Shape

class pangolin.ir.Multinomial[source]#

Bases: Op

Create a Multinomial Op. Takes no parameters.

When used in an RV, a multinomial op expects a first parent n (a scalar) indicating the number of observations and a second parent p indicating a vector of probabilities (a 1D array). Note that this is different from Stan (which doesn’t need n to be passed).

random: bool = True#

True

discrete: bool = True#

True

get_shape(n_shape, p_shape)[source]#

Return the count-vector shape after validating both parents.

Parameters:
  • n_shape (Shape) – Scalar shape () for the number of trials.

  • p_shape (Shape) – One-dimensional probability-vector shape.

Returns:

Shape – p_shape.

Raises:

ValueError – If the number of trials is nonscalar or the probabilities are not one-dimensional.

Return type:

Shape

class pangolin.ir.Dirichlet[source]#

Bases: Op

Create a Dirichlet Op. Takes no parameters.

When used in an RV, a Dirichlet op expects one parent, namely the concentration

random: bool = True#

True

discrete: bool = False#

False

get_shape(concentration_shape)[source]#

Return the concentration-vector shape unchanged.

Parameters:

concentration_shape (Shape) – One-dimensional concentration-vector shape.

Returns:

Shape – concentration_shape.

Raises:

ValueError – If the concentration is not one-dimensional.

Return type:

Shape

class pangolin.ir.Wishart[source]#

Bases: Op

Create a Wishart Op. Takes no parameters.

When used in an RV, expects two parameters: nu (degrees of freedom, scalar) and S (symmetric positive-definite scale matrix).

random: bool = True#

True

discrete: bool = False#

False

get_shape(nu_shape, scale_shape)[source]#

Return the scale-matrix shape after validating both parents.

Parameters:
  • nu_shape (Shape) – Scalar shape () for the degrees of freedom.

  • scale_shape (Shape) – Two-dimensional square scale-matrix shape.

Returns:

Shape – scale_shape.

Raises:

ValueError – If the degrees of freedom are nonscalar or the scale is not a square matrix.

Return type:

Shape

class pangolin.ir.VMap(base_op, in_axes, axis_size=None)[source]#

Bases: Op, Generic

Vectorize one operation over axes of its inputs.

All arguments here are heavily inspired by jax.lax.vmap although note that VMap only maps a single Op. (The vmap function in the interface elsewhere takes an arbitrary function and transforms it into a graph of RV objects with VMap operations.)

Parameters:
  • base_op (BaseOp) – Operation to vectorize.

  • in_axes (Sequence[int | None]) – Axis to map for each input, or None for an unmapped input. Negative axes count from the end.

  • axis_size (int | None) – Positive size of the mapped axis. It is inferred from mapped inputs when omitted and required when every input is unmapped.

Raises:
  • TypeError – If the constructor arguments have invalid types.

  • ValueError – If axis_size is not positive or cannot be inferred from in_axes.

Examples

>>> # diagonal normal
>>> op = VMap(Normal(), in_axes=[0, 0])
>>> op.get_shape((5,), (5,))
(5,)
>>> # diagonal normal with shared scale
>>> op = VMap(Normal(), in_axes=[0, None])
>>> op.get_shape((5,), ())
(5,)
>>> # 2D diagonal normal with shared scale
>>> op = VMap(VMap(Normal(), in_axes=[0, None]), in_axes=[0, None])
>>> op.get_shape((6,4), ())
(6, 4)
>>> # 2D diagonal normal with "outer product" of location and scale
>>> op = VMap(VMap(Normal(), in_axes=[None, 0]), in_axes=[0, None])
>>> op.get_shape((6,), (4,))
(6, 4)
>>> # 2D diagonal normal with "outer product" in the other order
>>> op = VMap(VMap(Normal(), in_axes=[0, None]), in_axes=[None, 0])
>>> op.get_shape((6,), (4,))
(4, 6)
property random: bool[source]#

Equal to base_op.random

property discrete: bool | None[source]#

Equal to base_op.discrete

get_shape(*parents_shapes)[source]#

Remove mapped axes, apply the base shape rule, and prepend the mapped size.

Parameters:

*parents_shapes (Shape) – One shape for each entry of in_axes. An entry of None passes its shape unchanged to base_op. An integer entry removes that axis before calling base_op.get_shape. All removed axes must have the same size, equal to axis_size when it was provided.

Returns:

Shape – The mapped axis size prepended to the output shape of base_op.

Raises:

ValueError – If the number of shapes differs from in_axes, a mapped axis is invalid, mapped sizes disagree, or the remaining shapes are invalid for base_op.

Return type:

Shape

__str__()[source]#

Return a string representation of the VMap operation.

Just like VMap.__repr__ except uses str for calling the recursive distribution.

type pangolin.ir.VMapStack = VMap | VMap[VMapStack]#

Type-hint-only alias for one or more nested VMap operations around BaseOp.

This alias has no runtime behavior.

For example, VMapStack[Normal] includes VMap[Normal], VMap[VMap[Normal]], and any deeper nesting, but not Normal itself.

class pangolin.ir.Composite(num_inputs: int, ops: tuple[*tuple[Op, ...], LastOp], par_nums: Sequence[Sequence[int]])[source]#
class pangolin.ir.Composite(num_inputs: int, ops: Sequence[Op], par_nums: Sequence[Sequence[int]])

Bases: Op, Generic

Compose a sequence of operations into one operation.

Values are numbered in sequential order. The first num_inputs values are the inputs to the composite. Each operation appends one value, so operation i may refer only to values numbered from 0 through num_inputs + i - 1. Repeated and reordered references are allowed.

Parameters:
  • num_inputs (int) – Number of inputs to the composite.

  • ops (Sequence[Op]) – Nonempty sequence of operations to apply. Every operation except the last must be deterministic.

  • par_nums (Sequence[Sequence[int]]) – One sequence of parent value numbers for each operation.

Raises:
  • TypeError – If an argument has an invalid type.

  • ValueError – If the structure is empty or inconsistent, an intermediate operation is random, or a parent refers to a value that is not yet available.

Examples

Add two inputs and exponentiate the result.

>>> op = Composite(2, (Add(), Exp()), ((0, 1), (2,)))
>>> op.get_shape((), ())
()
property random: bool[source]#

Equal to ops[-1].random

property discrete: bool | None[source]#

Equal to ops[-1].discrete

get_shape(*parents_shapes)[source]#

Apply the component shape rules and return the final output shape.

Parameters:

*parents_shapes (Shape) – Exactly num_inputs shapes. Component Ops receive these input shapes or earlier intermediate shapes according to par_nums.

Returns:

Shape – Output shape produced by the final component Op.

Raises:

ValueError – If the number of supplied shapes differs from num_inputs or a component Op rejects its selected parent shapes.

Return type:

Shape

class pangolin.ir.Scan(base_op, length, in_axes)[source]#

Bases: Op, Generic

Repeat an operation while feeding each output into the next iteration.

An RV using Scan has parents ordered as start, *inputs. Conceptually, it represents the following recurrence:

carry = start
outputs = []
for t in range(length):
    args = []
    for x, axis in zip(inputs, in_axes):
        if axis is None:
            args.append(x)
        else:
            args.append(take(x, t, axis))
    carry = base_op(carry, *args)
    outputs.append(carry)
result = stack(outputs)

Here, take(x, t, axis) selects the t-th slice of x along the specified axis, analogous to numpy.take. Thus, in_axes describes only inputs, not start. A mapped input supplies one slice per iteration, while an unmapped input is reused at every iteration. The carry is always the first argument to base_op.

If base_op is random, each iteration is a conditional draw; otherwise, the scan is a deterministic recurrence. The result contains every newly produced carry, but not the initial carry. Because each output becomes the next input carry, base_op must return start_shape. The result shape is therefore (length,) + start_shape.

Parameters:
  • base_op (O) – Operation to repeat.

  • length (int) – Positive number of repetitions.

  • in_axes (Sequence[int | None]) – Axis to scan for each non-carry input, or None for an unmapped input. Every mapped axis must have size length.

Raises:
  • TypeError – If the constructor arguments have invalid types.

  • ValueError – If length is not positive, or mapped input shapes disagree with length or in_axes.

Examples

Compute a scalar cumulative sum. The carry is the first argument to Add, and the mapped input contributes one scalar per iteration.

>>> op = Scan(Add(), length=3, in_axes=(0,))
>>> op.get_shape((), (3,))
(3,)

Repeatedly multiply a vector carry by the same matrix. The carry is the first argument to Matmul, and the unmapped matrix is the second.

>>> op = Scan(Matmul(), length=4, in_axes=(None,))
>>> op.get_shape((3,), (3, 3))
(4, 3)
property random: bool[source]#

Equal to self.base_op.random

property discrete: bool | None[source]#

Equal to self.base_op.discrete

get_shape(start_shape, *other_shapes)[source]#

Return the stacked shapes produced by repeatedly applying base_op.

Parameters:
  • start_shape (Shape) – Shape of the initial carried value. It is the first base_op input, and the output of base_op must have this same shape.

  • *other_shapes (Shape) – One shape for each entry of in_axes. Unmapped shapes are passed unchanged to base_op; each mapped shape loses its selected axis, whose size must equal length.

Returns:

Shape – (length,) followed by the output shape of base_op for one iteration.

Raises:

ValueError – If the number of other shapes differs from in_axes, a mapped axis is invalid or has the wrong length, base_op rejects the per-iteration shapes, or its output shape differs from the carry shape.

Return type:

Shape

class pangolin.ir.Bijected(base_op, bijector)[source]#

Bases: Op, Generic

A continuous distribution obtained by applying a bijector to another distribution.

Bijected is restricted to continuous base distributions because its density uses the Jacobian change-of-variables formula. A transformation of a discrete distribution instead preserves probability masses and must not apply a Jacobian correction.

The parent order is part of the IR contract. The first bijector.n_biject_params parents are parameters of the bijection; all remaining parents are parameters of base_op.

Given an ordered parent sequence parents, the transformed random variable is equal in distribution to:

n = op.bijector.n_biject_params
x = RV(op.base_op, *parents[n:])
y = RV(op.bijector.forward, x, *parents[:n])

In the actual IR, RV(op, *parents) represents this distribution with a single random node rather than explicitly constructing x and the deterministic y.

Examples

Create a new op that’s equivalent to Lognormal:

>>> exp_bijector = Bijector(
...     Exp(),
...     Log(),
...     Composite(2, (Identity(),), [[0]]),
... )
>>> op = Bijected(Normal(), exp_bijector)
>>> print(op)
bijected(normal, bijector(exp, log, composite(2, [identity], [[0]])))
>>> op.get_shape((),())
()

Use that new op to create a random variable:

>>> y = RV(op, RV(Constant(0)), RV(Constant(1)))
>>> y.shape
()

A parameterized bijection receives its parameters before those of the base distribution. This example describes Y = X + offset.

>>> shift = Bijector(
...     Add(),
...     Sub(),
...     Composite(3, (Constant(0),), [[]]),
...     n_biject_params=1,
... )
>>> shifted_normal = Bijected(Normal(), shift)
>>> shifted_normal.get_shape((), (), ())
()
Parameters:
  • base_op (O) – Random, continuous Op describing the base distribution.

  • bijector (B) – Bijection applied to samples from the base distribution.

Raises:
  • TypeError – If base_op is not an Op or bijector is not a Bijector.

  • ValueError – If base_op is deterministic or discrete.

random: bool = True#

True

discrete: bool = False#

False

get_shape(*args)[source]#

Apply the base-distribution and bijector shape rules in parent order.

Parameters:

*args (Shape) – First, exactly bijector.n_biject_params shapes for the bijector parameters; then the parent shapes expected by base_op.

Returns:

Shape – Shape returned by the bijector for a value having the output shape of base_op.

Raises:
  • TypeError – If the total number of shapes is incompatible with base_op.

  • ValueError – If base_op or the bijector rejects the supplied shapes.

Return type:

Shape

__str__()[source]#

Return a compact representation of the transformed distribution.

class pangolin.ir.Truncated(base_op, *, lower=True, upper=True)[source]#

Bases: Op, Generic

Restrict a continuous scalar distribution to an interval.

Parents are the lower bound if lower, then the upper bound if upper, then the parameters of base_op in their original order. Bounds and the base output must be scalar. The result is the normalized distribution restricted to the supplied bounds. With neither bound, it is the base distribution unchanged.

Each supplied bound must be finite and strictly inside the base distribution’s support; when both are supplied, the lower bound must be less than the upper bound. Backends must enforce these value-dependent requirements whenever the distribution is evaluated, including sampling, density, CDF, and quantile calculations. The IR checks only structural requirements and does not require CDF or inverse-CDF capability at construction.

Parameters:
  • base_op (BaseOp) – Random, continuous Op whose output must be scalar for the supplied parameter shapes.

  • lower (bool) – Whether a lower-bound parent is supplied. Default True.

  • upper (bool) – Whether an upper-bound parent is supplied. Default True.

Raises:
  • TypeError – If base_op is not an Op or either bound flag is not a boolean.

  • ValueError – If base_op is deterministic or discrete.

Examples

A truncated Normal takes lower bound, upper bound, location, and scale:

>>> op = Truncated(Normal())
>>> op.get_shape((), (), (), ())
()
>>> op.random, op.discrete
(True, False)

One-sided truncations take just one bound before the base parameters:

>>> Truncated(Normal(), upper=False).get_shape((), (), ())
()
>>> Truncated(Normal(), lower=False).get_shape((), (), ())
()

With neither bound, only the base parameters are supplied:

>>> Truncated(Normal(), lower=False, upper=False).get_shape((), ())
()

Truncation can be nested. Each level supplies its own bounds:

>>> Truncated(op).get_shape((), (), (), (), (), ())
()

Vectorize outside truncation to produce independent draws with shared bounds and scale:

>>> VMap(op, (None, None, 0, None)).get_shape((), (), (3,), ())
(3,)
random: bool = True#

True

discrete: bool = False#

False

get_shape(*parent_shapes)[source]#

Validate scalar bounds and base output, and return scalar shape.

Parameters:

*parent_shapes (Shape) – Lower-bound shape if lower, then upper-bound shape if upper; each must be (). Remaining shapes are passed to base_op.get_shape in their original order.

Raises:
  • TypeError – If required shapes are missing or the base Op rejects the number of parameters.

  • ValueError – If the bounds or base output are not scalar, or the base Op rejects its parameters.

Return type:

Shape

class pangolin.ir.LogProb(base_op)[source]#

Bases: Op, Generic

Evaluate a distribution’s log density or log probability mass.

The first parent is the evaluation value; all remaining parents are the parameters of base_op, in its original parent order. The evaluation value must have exactly the shape produced by base_op. The output is always scalar: for an array-valued distribution it is the joint log density or mass of the whole array, not an array of componentwise values.

This is a deterministic operation, even when its parents are random RVs. It evaluates the local distribution with the supplied parameter values fixed; it does not integrate over their upstream distributions. Constructing this Op neither samples nor evaluates anything. Numerical evaluation and support for particular base Ops are left to backends.

Parameters:

base_op (BaseOp) – Random Op describing a discrete or continuous distribution.

Raises:
  • TypeError – If base_op is not an Op.

  • ValueError – If base_op is deterministic.

Examples

A Normal log density takes a scalar value, location, and scale:

>>> op = LogProb(Normal())
>>> op.get_shape((), (), ())
()
>>> op.random
False

Discrete distributions are supported as well:

>>> LogProb(Bernoulli()).get_shape((), ())
()

A vector-valued distribution still has a scalar log density:

>>> LogProb(VMap(Normal(), (0, None))).get_shape((3,), (3,), ())
()
random: bool = False#

False

get_shape(value_shape, *parent_shapes)[source]#

Validate the evaluation value and distribution parameters, and return scalar shape.

Parameters:
  • value_shape (Shape) – Shape of the value at which to evaluate the log density or mass.

  • *parent_shapes (Shape) – Parameter shapes passed to base_op.get_shape in their original order.

Raises:
  • TypeError – If a required shape is missing or the base Op rejects the number of parameter shapes.

  • ValueError – If the base Op rejects the parameter shapes or its output shape differs from value_shape.

Return type:

Shape

class pangolin.ir.CDF(base_op)[source]#

Bases: Op, Generic

Evaluate a distribution’s cumulative distribution function.

The first parent is the evaluation value; all remaining parents are the parameters of base_op, in its original parent order. The value must have exactly the shape produced by base_op. The output is always scalar: the probability that every component of a draw is less than or equal to the corresponding component of the value. This is a joint CDF, not an array of marginal CDFs. For discrete distributions, equality includes the mass at the value; the evaluation value itself need not be an integer.

This is a deterministic operation, even when its parents are random RVs. It evaluates the local distribution with the supplied parameter values fixed; it does not integrate over their upstream distributions. Constructing this Op neither samples nor evaluates anything. Numerical evaluation and support for particular base Ops are left to backends.

Parameters:

base_op (BaseOp) – Random Op describing a discrete or continuous distribution.

Raises:
  • TypeError – If base_op is not an Op.

  • ValueError – If base_op is deterministic.

Examples

A Normal CDF takes a scalar value, location, and scale:

>>> op = CDF(Normal())
>>> op.get_shape((), (), ())
()
>>> op.random
False

Discrete distributions have CDFs as well:

>>> CDF(Poisson()).get_shape((), ())
()

The joint CDF of independent draws is scalar, whereas mapping a scalar CDF gives a vector:

>>> CDF(VMap(Normal(), (0, None))).get_shape((3,), (3,), ())
()
>>> VMap(CDF(Normal()), (0, 0, None)).get_shape((3,), (3,), ())
(3,)
random: bool = False#

False

get_shape(value_shape, *parent_shapes)[source]#

Validate the evaluation value and distribution parameters, and return scalar shape.

Parameters:
  • value_shape (Shape) – Shape of the value at which to evaluate the CDF.

  • *parent_shapes (Shape) – Parameter shapes passed to base_op.get_shape in their original order.

Raises:
  • TypeError – If a required shape is missing or the base Op rejects the number of parameter shapes.

  • ValueError – If the base Op rejects the parameter shapes or its output shape differs from value_shape.

Return type:

Shape

class pangolin.ir.Quantile(base_op)[source]#

Bases: Op, Generic

Evaluate a scalar distribution’s quantile function (inverse CDF).

The first parent is a scalar probability; all remaining parents are the parameters of base_op, in its original parent order. The base distribution and the result must both be scalar. For a probability strictly between zero and one, the quantile is the smallest value at which the CDF reaches that probability. This definition also applies to discrete distributions. At zero and one, use the corresponding one-sided limits of the quantile function, which may be infinite.

This is a deterministic operation, even when its parents are random RVs. It evaluates the local distribution with the supplied parameter values fixed; it does not integrate over their upstream distributions. Constructing this Op neither samples nor evaluates anything. Numerical evaluation, validation that the probability lies in [0, 1], and support for particular base Ops are left to backends.

Parameters:

base_op (BaseOp) – Random Op describing a discrete or continuous scalar distribution.

Raises:
  • TypeError – If base_op is not an Op.

  • ValueError – If base_op is deterministic. Scalar applicability is checked by get_shape.

Examples

A Normal quantile takes a scalar probability, location, and scale:

>>> op = Quantile(Normal())
>>> op.get_shape((), (), ())
()
>>> op.random
False

Discrete distributions have quantiles as well:

>>> Quantile(Poisson()).get_shape((), ())
()

The distribution may itself be wrapped, as long as its output is scalar:

>>> Quantile(Truncated(Normal())).get_shape((), (), (), (), ())
()

Map a scalar quantile to evaluate several probabilities or parameter settings:

>>> VMap(Quantile(Normal()), (0, 0, None)).get_shape((3,), (3,), ())
(3,)

There is no joint quantile for an array-valued distribution:

>>> Quantile(VMap(Normal(), (0, None))).get_shape((), (3,), ())
Traceback (most recent call last):
    ...
ValueError: base_op must have scalar output
random: bool = False#

False

get_shape(probability_shape, *parent_shapes)[source]#

Validate the scalar probability and distribution output, and return scalar shape.

Parameters:
  • probability_shape (Shape) – Shape of the probability at which to evaluate the quantile.

  • *parent_shapes (Shape) – Parameter shapes passed to base_op.get_shape in their original order.

Raises:
  • TypeError – If a required shape is missing or the base Op rejects the number of parameter shapes.

  • ValueError – If the probability or base output is not scalar, or the base Op rejects its parameter shapes.

Return type:

Shape

class pangolin.ir.VJP(base_op, argnum)[source]#

Bases: Op, Generic

Apply a vector-Jacobian product to one input of a deterministic Op.

The first parent is a cotangent with exactly the shape of the output of base_op; all remaining parents are its inputs in their original order. The result has the shape of base input argnum. For real-valued inputs and output, this is the gradient of the sum of the elementwise product of the output and cotangent, with respect to that input. All other inputs and the cotangent are held fixed for this differentiation.

This is a deterministic operation, even when its parents are random RVs. It differentiates the local function described by base_op, not its parents’ upstream computations. Constructing this Op neither evaluates nor differentiates anything. Numerical evaluation, supported dtypes, and differentiability of particular base Ops are left to backends.

Parameters:
  • base_op (BaseOp) – Deterministic Op to differentiate, including deterministic container or wrapper Ops.

  • argnum (int) – Zero-based, nonnegative index of the input to differentiate with respect to. The cotangent is not counted as an input of base_op.

Raises:
  • TypeError – If base_op is not an Op, or argnum is not an integer (excluding booleans).

  • ValueError – If base_op is random or argnum is negative.

Examples

A scalar multiplication takes a scalar cotangent followed by two inputs:

>>> op = VJP(Mul(), 0)
>>> op.get_shape((), (), ())
()
>>> op.random
False

A matrix product returns a gradient shaped like the selected matrix:

>>> VJP(Matmul(), 0).get_shape((2, 4), (2, 3), (3, 4))
(2, 3)
>>> VJP(Matmul(), 1).get_shape((2, 4), (2, 3), (3, 4))
(3, 4)

A log density is deterministic, so it can be differentiated as well:

>>> VJP(LogProb(Normal()), 1).get_shape((), (), (), ())
()
random: bool = False#

False

get_shape(cotangent_shape, *input_shapes)[source]#

Validate the base inputs and cotangent, and return the selected input’s shape.

Parameters:
  • cotangent_shape (Shape) – Shape of the cotangent, which must match the base Op’s output shape.

  • *input_shapes (Shape) – Input shapes passed to base_op.get_shape in their original order.

Raises:
  • TypeError – If the cotangent is missing or the base Op rejects the number of input shapes.

  • ValueError – If argnum is out of range, the base Op rejects its input shapes, or the cotangent shape differs from the base Op’s output shape.

Return type:

Shape

pangolin.ir.split_shape(shape, axis)[source]#

Remove one axis from a shape.

Parameters:
  • shape (Shape) – Shape from which to remove an axis.

  • axis (int | None) – Axis to remove, including negative axes, or None to leave the shape unchanged.

Returns:

  • remaining_shape – Shape with the selected axis removed.

  • axis_size – Size of the removed axis, or None when axis is None.

Raises:
  • TypeError – If axis is not an integer or None.

  • ValueError – If axis is outside the shape.

Return type:

tuple[Shape, int | None]

Examples

>>> split_shape((2, 3, 4), -1)
((2, 3), 4)
>>> split_shape((2, 3, 4), None)
((2, 3, 4), None)
pangolin.ir.rv_equal(A, B)[source]#

Are A and B equal in a mathematical sense?

That is, are they guaranteed to always have the same value? This is defined by the following rules:

  1. If A.op is random, then A is is rv_equal to B if and only if they refer to the same object in memory.

  2. If A.op is non-random, then A is rv_equal to B if and only if they have the same Op and their parents are rv_equal (defined recursively using this function).

This function is implemented using caching to make it efficient even with large graphs. This doesn’t change the results since RV and Op objects are immutable.

Parameters:
  • A (RV) – the first RV to be compared

  • B (RV) – the second RV to be compared

Return type:

bool

Examples

Constants behave as you’d expect.

>>> a = RV(Constant(0.5))
>>> b = RV(Constant(0.5))
>>> c = RV(Constant(0.7))
>>> # same object always equal
>>> rv_equal(a, a)
True
>>> # equivalent non-random ops, all (nonexistent) parents equal
>>> rv_equal(a, b)
True
>>> # non-equivalent ops always non-equal
>>> rv_equal(a, c)
False

Random Op objects are always non-equal unless they are the same object.

>>> rv_equal(RV(Bernoulli(), a), RV(Bernoulli(), a))
False
>>> rv_equal(RV(Bernoulli(), a), RV(Bernoulli(), b))
False
>>> rv_equal(RV(Bernoulli(), a), RV(Bernoulli(), c))
False

Non-random op are if ops are equal and parents are recursively equal.

>>> rv_equal(RV(Exp(), a), RV(Exp(), a))
True
>>> rv_equal(RV(Exp(), a), RV(Exp(), b))
True
>>> rv_equal(RV(Exp(), a), RV(Exp(), c))
False
pangolin.ir.print_upstream(vars, namespace=None)[source]#

Print all upstream RVs as a readable table.

Parameters:
  • vars (PyTree[RV]) – An RV or a PyTree of RVs whose upstream graph is printed. Each distinct RV appears once.

  • namespace (Mapping[str, object] | None) – Optional mapping supplying names, such as locals(). Lists, tuples, and dictionary values are searched recursively; the first name found for each upstream RV is used. The namespace supplies labels only and does not add roots to the printed graph. Unnamed RVs receive names a, b, … in topological order, skipping all discovered names, including unused aliases. See pangolin.util.node_names for path naming rules.

Raises:
  • TypeError – If an input leaf is not an RV.

  • ValueError – If namespace traversal encounters a cyclic container or a name shared by distinct upstream RVs.

Return type:

None

Examples

>>> r = RV(Constant(0.5))
>>> s = RV(Bernoulli(), r)
>>> t = RV(Constant(2))
>>> u = RV(Normal(), s, t)
>>> v = RV(Constant([75, 50, 99]))
>>> print_upstream([u, v]) # use autogenerated names
shape | statement
----- | ---------
()    | a = 0.5
()    | b ~ bernoulli(a)
()    | c = 2
()    | d ~ normal(b, c)
(3,)  | e = [75 50 99]
>>> print_upstream({'dog':[u], 'kitty':(v,)}) # any pytree is OK
shape | statement
----- | ---------
()    | a = 0.5
()    | b ~ bernoulli(a)
()    | c = 2
()    | d ~ normal(b, c)
(3,)  | e = [75 50 99]
>>> print_upstream([u, v], locals())
shape | statement
----- | ---------
()    | r = 0.5
()    | s ~ bernoulli(r)
()    | t = 2
()    | u ~ normal(s, t)
(3,)  | v = [75 50 99]
>>> print_upstream([u, v], {"cool_r": r, "dog": u, "kitty": v})
shape | statement
----- | ---------
()    | cool_r = 0.5
()    | a ~ bernoulli(cool_r)
()    | b = 2
()    | dog ~ normal(a, b)
(3,)  | kitty = [75 50 99]

RVs stored in nested containers receive names using dictionary keys and sequence indices. Shared parents appear only once:

>>> from pangolin import interface as pi
>>> params = {
...     "location": pi.normal(0, 1),
...     "scale": pi.exponential(1),
... }
>>> observations = [
...     pi.normal(params["location"], params["scale"])
...     for _ in range(2)
... ]
>>> print_upstream(observations, locals())
shape | statement
----- | ---------
()    | a = 0
()    | b = 1
()    | params['location'] ~ normal(a, b)
()    | c = 1
()    | params['scale'] ~ exponential(c)
()    | observations[0] ~ normal(params['location'], params['scale'])
()    | observations[1] ~ normal(params['location'], params['scale'])

See also

graph_upstream

Print upstream RVs as a Unicode DAG.

pangolin.ir.graph_upstream(vars, namespace=None, *, number_parents='auto')[source]#

Print all upstream RVs and shapes as a Unicode DAG.

Circles are RVs. Edges always travel from top to bottom and from left to right; they never travel upward or leftward.

┼ is always a pure crossing: the horizontal and vertical lines do not connect there.

A node’s distinct parents are read from left to right by default. When that visual order differs from the operation’s parent order, automatic subscripts (₀, ₁, ₂, …) record the position of each parent. When the same parent appears in more than one position, ⁎ is used.

This gives a compact overview of chains and simple branches; for dense graphs or an explicit statement of every parent relationship, use print_upstream. Detailed rendering conventions are documented by pangolin.util.render_dag.

Parameters:
  • vars (PyTree[RV]) – An RV or a PyTree of RVs whose upstream graph is printed. Each distinct RV appears once.

  • namespace (Mapping[str, object] | None) – Optional mapping supplying names, such as locals(). Lists, tuples, and dictionary values are searched recursively; the first name found for each upstream RV is appended to its label. The namespace supplies labels only and does not add roots to the graph. Unnamed RVs have no name annotation. See pangolin.util.node_names for path naming rules.

  • number_parents (Literal['off', 'on', 'auto']) – Whether to number no edges, all edges, or only edges whose parent order or multiplicity would otherwise be ambiguous. A repeated parent is marked with ⁎ when annotations are enabled.

Raises:
  • TypeError – If an input leaf is not an RV.

  • ValueError – If number_parents is not "off", "on", or "auto"; or if parent annotations would be printed for a node with more than ten parent positions. Also raised if namespace traversal encounters a cyclic container or a name shared by distinct upstream RVs.

Return type:

None

Examples

A simple example:

>>> from pangolin import interface as pi
>>> x = pi.constant(3.3)
>>> y = pi.exp(x)
>>> z = pi.normal(x, y)
>>> graph_upstream(z, {"z": z})
○   () 3.3
│
├─○ () exp
│ │
└─○ () normal ← z

A more complex example:

>>> x = pi.constant(2)
>>> y = pi.exp(x)
>>> z = pi.log(x)
>>> u = pi.beta_binomial(x, y, z)
>>> v = y + u

These RVs form a small DAG that can be drawn spaciously as follows:

x
│
├─────────┬────┐
│         │    │
└───▶y    │    │
     │    ↓    │
     │    z    │
     │    │    │
     │    ↓    │
     ├───▶u ◀──┘
     │    │
     │    ↓
     └───▶v

graph_upstream draws the same DAG compactly, assigning each node its own row:

>>> graph_upstream(v, locals())
○     () 2 ← x
│
├─○   () exp ← y
│ │
├─┼─○ () log ← z
│ ├┐│
└─┼┴○ () beta_binomial ← u
  │ │
  └─○ () add ← v
>>> x = pi.constant([-3.0, 0.0, 2.5])
>>> y = pi.constant(3.1)
>>> z = pi.vfor(lambda i: pi.normal(pi.exp(x[i]), y), i=3)
>>> graph_upstream(z, {"z": z})
○   (3,) [-3.  0.  2.5]
│
○   (3,) vmap(exp, [0], 3)
│
│ ○ ()   3.1
│ │
└─○ (3,) vmap(normal, [0, None], 3) ← z

See also

print_upstream

Print upstream RVs as a table.

pangolin.util.render_dag

Generic renderer with a complete glyph reference.