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
RVobjects have static shapes. The shape of anRVis recursively determined by itsOpand the shapes of its parentRVobjects.
Core types:
Type |
Purpose |
|---|---|
Static shape of an |
|
Base class for deterministic functions and distributions |
|
Base class for operations with scalar inputs and output |
|
Node in a probabilistic model DAG |
|
Descriptor for an invertible transformation |
|
Type-hint-only alias for one or more nested |
Types of Op:
Type |
Ops |
|---|---|
Constants |
|
Identity |
|
Arithmetic |
|
Trigonometry |
|
Other scalar functions |
|
Linear algebra |
|
Other multivariate functions |
|
Scalar distributions |
|
Multivariate distributions |
|
Control flow |
|
Indexing |
|
Transformations |
|
Distribution properties |
|
Differentiation |
In addition, this module provides the following utilities:
split_shape: Remove one axis from a shape.rv_equal: Test whether two random variables are mathematically equal.print_upstream: Print a readable table describing an entire graph.graph_upstream: Print a graph as a Unicode DAG.
—
- 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:
ABCAbstract base class for operators. An
Oprepresents a deterministic function or distribution. All functionality for sampling or evaluating densities is left to inference backends. AnOpis frozen after initialization.Simple
Opobjects typically have no parameters. For example,Add()just represents scalar addition. TheOpitself 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,Sumtakes the axis to sum over.A concrete
Opclass must provideOp.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 abool. Both are accessed asop.random.A random
Opmust similarly provideOp.discreteas a boolean attribute or a property returning a boolean:Truefor discrete distributions andFalsefor continuous ones. The base property returnsNone, which deterministic Ops can inherit. Higher-order Ops may derive both properties from a containedOp. As withOp.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 callingsuper().__init__().Every concrete
Opprovides a publicOp.get_shapemethod. It accepts the shapes of theOp’s ordered parents, validates their number and compatibility, and returns the static outputShape. Parent requirements and output rules are part of each concreteOp’s documentation. Because different Ops have different arities, the base class deliberately typesOp.get_shapeas a weak callable; concrete methods expose their precise signatures wherever the arity is fixed.An
Opmust provide structural equality and a compatible hash, as documented byOp.__eq__. The base implementation compares concrete types, which is sufficient for Ops with no constructor state. Ops with constructor state must override bothOp.__eq__andOp.__hash__.- get_shape: Callable[[...], Shape]#
Compute the output shape from the ordered shapes of an
Op’s parents.Each concrete
Opimplements this as a method taking oneShapeargument for each parent, in parent order, and returning the outputShape. 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.
RVcalls 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_shapeas 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 –
Truefor a discrete distribution andFalsefor a continuous distribution. Deterministic Ops inherit the defaultNone. 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
- __repr__()[source]#
Return a structural Python representation of the operation.
The representation is constructor-shaped and recursively uses
reprfor 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.
- class pangolin.ir.ScalarOp[source]#
Bases:
Op,ABCBase 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
randomand_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
_wikipediato override the Wikipedia page inferred from the class name, or set it toNoneto omit the link. Additional documentation can be supplied through_notes.
- final class pangolin.ir.RV(op, *parents, interface=NO_INTERFACE)[source]#
Bases:
NodeAn
RVis essentially just anOpand a tuple of parentRVobjects.Each construction creates a distinct graph node. Distinct
RVnodes with randomOpobjects represent separate conditionally independent draws given their parents; reusing anRVobject reuses the same draw.The only purpose of an RV’s
interfaceis to delegate Python syntax. For example,x + ycallsx.interface.add(x, y), andx.Tcallsx.interface.transpose(x). Unsupported standard operations raiseNotImplementedError. Additional public attributes callx.interface.get_attribute(x, name), which raisesAttributeErrorunless 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)orx.to_numpy(). NumPy computations on these values return numerical arrays, not graph nodes. Conversion of other RVs raises TypeError.- Parameters:
op (pangolin.ir.Op) – The
Opdefining theRV.interface (pangolin.ir.RVInterface) – Immutable target for Python-syntax delegation. The default
NO_INTERFACErejects all such syntax.
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
- 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
- __eq__(other)[source]#
Return whether
otheris the sameRVnode.RVequality and hashing are identity-based, regardless of whether twoRVobjects have equalOpobjects and parents. Userv_equalto compare the values represented byRVgraphs.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
- __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 ofOp.__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:
objectProvide typed targets for RV syntax, with rejecting defaults.
RVs forward standard syntax directly to these methods: for example,
x + ycallsx.interface.add(x, y). Subclasses implement whichever operations they support; unsupported operations raiseNotImplementedError. Additional public attributes are provided explicitly throughget_attribute, which otherwise raisesAttributeError.Notes
x.Tcallsx.interface.transpose(x). Bracket indexing callsx.interface.getitem(x, *indices); each interface chooses its indexing semantics. For example,pangolin.interface.Interfaceuses orthogonal indexing.Additional public attributes call
x.interface.get_attribute(x, name). Interface methods do not automatically become RV attributes. Core graph attributes such asparents,op, andshapealways 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 typeRV. Additional extensible attributes are statically typed asAny; explicit interface calls retain their method signatures. Implementing only the supported operations is enough to define an interface.Examples
Pangolin’s standard interface exposes
sumandvindexthroughget_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
- 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:
objectDescribe an invertible transformation using deterministic IR operations.
A
Bijectoris not anOpand cannot itself be attached to anRV. It is an immutable descriptor containing three deterministic operations.Bijectedembeds that descriptor in a randomOpso transformed distributions remain explicit in the IR and independent of any backend.For a transformation
y = T(x, *params),forwardcomputesyandinversecomputesx.log_det_jacreceives bothxandy, followed by the same parameters, and computes the scalar forward log absolute Jacobian determinantlog |det ∇T(x)|. Supplying both values lets the operation use whichever representation is more convenient.Optional
signis a deterministic Op returning scalar+1for increasing or-1for 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)thenP_X(x) = P_Y(T(x)) × |det ∇T(x)|and
P_Y(y) = P_X(T⁻¹(y)) × |det ∇T⁻¹(y)|.That is,
P_Yis the pushforward ofP_XandP_Xis the pullback ofP_Y.Thus a transformed distribution samples
xfrom its base distribution and appliesforward. Its log density appliesinverseand 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
-1or+1from all ordered bijector parameters. Describes scalar applications only.
Examples
An implementation of the
exptransformation.>>> 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 parameterslo < hi. Its forward function islogit((x - lo) / (hi - lo))and its inverse islo + (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_paramsis negative. Values produced by the sign Op are an author guarantee, not evaluated during construction.
- Parameters:
- get_shape(x_shape, *param_shapes)[source]#
Validate operation shapes and return the transformed 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 usesreprfor its operations.
- __str__()[source]#
Return a compact, human-readable representation of the bijector.
This follows the convention of
Op.__str__and recursively usesstrfor its operations.
- class pangolin.ir.Identity[source]#
Bases:
OpReturn one parent unchanged.
- random: bool = False#
False
- class pangolin.ir.Constant(value)[source]#
Bases:
OpRepresent a numeric constant with no parents.
The input is normalized to a C-contiguous NumPy array whose buffer is immutable. The public
valueremains an ordinary NumPy array, but neither it nor a view sharing its buffer can be made writable.Constantequality is structural. TwoConstantobjects 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.
Constanthas no parents, so this method accepts no parent shapes.- Returns:
Shape – Shape of
value.- Return type:
- class pangolin.ir.Add[source]#
Bases:
ScalarOpScalar
Addoperation.The constructor takes no arguments. When used in an
RV, this operation expects the following scalar parents:a: parent 0b: parent 1
Addexpects exactly 2 scalar parents. Its shape behavior is inherited fromScalarOp.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:
ScalarOpScalar
Suboperation.The constructor takes no arguments. When used in an
RV, this operation expects the following scalar parents:a: parent 0b: parent 1
Subexpects exactly 2 scalar parents. Its shape behavior is inherited fromScalarOp.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:
ScalarOpScalar
Muloperation.The constructor takes no arguments. When used in an
RV, this operation expects the following scalar parents:a: parent 0b: parent 1
Mulexpects exactly 2 scalar parents. Its shape behavior is inherited fromScalarOp.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:
ScalarOpScalar
Divoperation.The constructor takes no arguments. When used in an
RV, this operation expects the following scalar parents:a: parent 0b: parent 1
Divexpects exactly 2 scalar parents. Its shape behavior is inherited fromScalarOp.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:
ScalarOpScalar
Powoperation.The constructor takes no arguments. When used in an
RV, this operation expects the following scalar parents:a: parent 0b: parent 1
Powexpects exactly 2 scalar parents. Its shape behavior is inherited fromScalarOp.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:
ScalarOpScalar
Arccosoperation.The constructor takes no arguments. When used in an
RV, this operation expects the following scalar parents:a: parent 0
Arccosexpects exactly 1 scalar parent. Its shape behavior is inherited fromScalarOp.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:
ScalarOpScalar
Arccoshoperation.The constructor takes no arguments. When used in an
RV, this operation expects the following scalar parents:a: parent 0
Arccoshexpects exactly 1 scalar parent. Its shape behavior is inherited fromScalarOp.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:
ScalarOpScalar
Arcsinoperation.The constructor takes no arguments. When used in an
RV, this operation expects the following scalar parents:a: parent 0
Arcsinexpects exactly 1 scalar parent. Its shape behavior is inherited fromScalarOp.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:
ScalarOpScalar
Arcsinhoperation.The constructor takes no arguments. When used in an
RV, this operation expects the following scalar parents:a: parent 0
Arcsinhexpects exactly 1 scalar parent. Its shape behavior is inherited fromScalarOp.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:
ScalarOpScalar
Arctanoperation.The constructor takes no arguments. When used in an
RV, this operation expects the following scalar parents:a: parent 0
Arctanexpects exactly 1 scalar parent. Its shape behavior is inherited fromScalarOp.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:
ScalarOpScalar
Arctanhoperation.The constructor takes no arguments. When used in an
RV, this operation expects the following scalar parents:a: parent 0
Arctanhexpects exactly 1 scalar parent. Its shape behavior is inherited fromScalarOp.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:
ScalarOpScalar
Cosoperation.The constructor takes no arguments. When used in an
RV, this operation expects the following scalar parents:a: parent 0
Cosexpects exactly 1 scalar parent. Its shape behavior is inherited fromScalarOp.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:
ScalarOpScalar
Coshoperation.The constructor takes no arguments. When used in an
RV, this operation expects the following scalar parents:a: parent 0
Coshexpects exactly 1 scalar parent. Its shape behavior is inherited fromScalarOp.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:
ScalarOpScalar
Sinoperation.The constructor takes no arguments. When used in an
RV, this operation expects the following scalar parents:a: parent 0
Sinexpects exactly 1 scalar parent. Its shape behavior is inherited fromScalarOp.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:
ScalarOpScalar
Sinhoperation.The constructor takes no arguments. When used in an
RV, this operation expects the following scalar parents:a: parent 0
Sinhexpects exactly 1 scalar parent. Its shape behavior is inherited fromScalarOp.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:
ScalarOpScalar
Tanoperation.The constructor takes no arguments. When used in an
RV, this operation expects the following scalar parents:a: parent 0
Tanexpects exactly 1 scalar parent. Its shape behavior is inherited fromScalarOp.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:
ScalarOpScalar
Tanhoperation.The constructor takes no arguments. When used in an
RV, this operation expects the following scalar parents:a: parent 0
Tanhexpects exactly 1 scalar parent. Its shape behavior is inherited fromScalarOp.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:
ScalarOpScalar
Absoperation.The constructor takes no arguments. When used in an
RV, this operation expects the following scalar parents:a: parent 0
Absexpects exactly 1 scalar parent. Its shape behavior is inherited fromScalarOp.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:
ScalarOpScalar
Minimumoperation.The constructor takes no arguments. When used in an
RV, this operation expects the following scalar parents:a: first valueb: second value
Minimumexpects exactly 2 scalar parents. Its shape behavior is inherited fromScalarOp.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:
ScalarOpScalar
Maximumoperation.The constructor takes no arguments. When used in an
RV, this operation expects the following scalar parents:a: first valueb: second value
Maximumexpects exactly 2 scalar parents. Its shape behavior is inherited fromScalarOp.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:
ScalarOpScalar
Expoperation.The constructor takes no arguments. When used in an
RV, this operation expects the following scalar parents:a: parent 0
Expexpects exactly 1 scalar parent. Its shape behavior is inherited fromScalarOp.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:
ScalarOpScalar
InvLogitoperation.The constructor takes no arguments. When used in an
RV, this operation expects the following scalar parents:a: parent 0
InvLogitexpects exactly 1 scalar parent. Its shape behavior is inherited fromScalarOp.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:
ScalarOpScalar
Logoperation.The constructor takes no arguments. When used in an
RV, this operation expects the following scalar parents:a: parent 0
Logexpects exactly 1 scalar parent. Its shape behavior is inherited fromScalarOp.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:
ScalarOpScalar
Logitoperation.The constructor takes no arguments. When used in an
RV, this operation expects the following scalar parents:a: parent 0
Logitexpects exactly 1 scalar parent. Its shape behavior is inherited fromScalarOp.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:
ScalarOpScalar
Stepoperation.The constructor takes no arguments. When used in an
RV, this operation expects the following scalar parents:a: parent 0
Stepexpects exactly 1 scalar parent. Its shape behavior is inherited fromScalarOp.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:
ScalarOpScalar
Loggammaoperation.The constructor takes no arguments. When used in an
RV, this operation expects the following scalar parents:a: parent 0
Loggammaexpects exactly 1 scalar parent. Its shape behavior is inherited fromScalarOp.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.loggammaorscipy.special.gammaln?- random: bool = False#
False
- class pangolin.ir.Matmul[source]#
Bases:
OpA 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:
- 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:
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:
OpTake the inverse of a square matrix.
- random: bool = False#
False
- class pangolin.ir.Cholesky[source]#
Bases:
OpCompute the Cholesky decomposition of a square matrix.
- random: bool = False#
False
- class pangolin.ir.Transpose[source]#
Bases:
OpTake 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
- class pangolin.ir.Diag[source]#
Bases:
OpExtract the diagonal of a square matrix.
- random: bool = False#
False
- class pangolin.ir.DiagMatrix[source]#
Bases:
OpConstruct a square diagonal matrix from a vector.
- random: bool = False#
False
- class pangolin.ir.Softmax[source]#
Bases:
OpApply 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
- class pangolin.ir.Sum(axis)[source]#
Bases:
OpSum an array along one axis.
- Parameters:
axis (int) – Axis to sum over. Negative axes count from the end.
- random: bool = False#
False
- class pangolin.ir.Concatenate(axis=0)[source]#
Bases:
OpConcatenate 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 alongaxis. 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
axismust match.- Returns:
Shape – Common parent shape with the dimensions along
axissummed.- Raises:
ValueError – If there are no parents,
axisis out of bounds, parent ranks differ, or a non-concatenated dimension differs.- Return type:
- class pangolin.ir.Index[source]#
Bases:
OpSelect a scalar entry from an array.
An
IndexRVhas parentsarray, *indices, with exactly one scalar integer-valued index for each dimension ofarray. The output shape is always().Indexitself does not represent slices or array indexing. These can be constructed usingVMaparoundIndex. 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
- class pangolin.ir.Normal[source]#
Bases:
ScalarOpScalar Normal distribution.
The constructor takes no arguments. When used in an
RV, this operation expects the following scalar parents:mu: location / meansigma: scale / standard deviation
Normalexpects exactly 2 scalar parents. Its shape behavior is inherited fromScalarOp.get_shape: Every parent must have scalar shape(), and the output shape is().Examples
>>> op = Normal() >>> op Normal() >>> print(op) normal >>> op.random True
See also
- random: bool = True#
True
- discrete: bool = False#
False
- class pangolin.ir.NormalPrec[source]#
Bases:
ScalarOpScalar NormalPrec distribution.
The constructor takes no arguments. When used in an
RV, this operation expects the following scalar parents:mu: location / meantau: precision / inverse variance
NormalPrecexpects exactly 2 scalar parents. Its shape behavior is inherited fromScalarOp.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
See also
- random: bool = True#
True
- discrete: bool = False#
False
- class pangolin.ir.Lognormal[source]#
Bases:
ScalarOpScalar Lognormal distribution.
The constructor takes no arguments. When used in an
RV, this operation expects the following scalar parents:mu: logarithm of locationsigma: logarithm of scale (not sigma squared!)
Lognormalexpects exactly 2 scalar parents. Its shape behavior is inherited fromScalarOp.get_shape: Every parent must have scalar shape(), and the output shape is().Examples
>>> op = Lognormal() >>> op Lognormal() >>> print(op) lognormal >>> op.random True
See also
- random: bool = True#
True
- discrete: bool = False#
False
- class pangolin.ir.Bernoulli[source]#
Bases:
ScalarOpScalar 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)
Bernoulliexpects exactly 1 scalar parent. Its shape behavior is inherited fromScalarOp.get_shape: Every parent must have scalar shape(), and the output shape is().Examples
>>> op = Bernoulli() >>> op Bernoulli() >>> print(op) bernoulli >>> op.random True
See also
- random: bool = True#
True
- discrete: bool = True#
True
- class pangolin.ir.BernoulliLogit[source]#
Bases:
ScalarOpScalar BernoulliLogit distribution.
The constructor takes no arguments. When used in an
RV, this operation expects the following scalar parents:theta: logit of probability (unbounded)
BernoulliLogitexpects exactly 1 scalar parent. Its shape behavior is inherited fromScalarOp.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:
ScalarOpScalar Binomial distribution.
The constructor takes no arguments. When used in an
RV, this operation expects the following scalar parents:N: number of trialstheta: probability of success for each trial
Binomialexpects exactly 2 scalar parents. Its shape behavior is inherited fromScalarOp.get_shape: Every parent must have scalar shape(), and the output shape is().Examples
>>> op = Binomial() >>> op Binomial() >>> print(op) binomial >>> op.random True
See also
- random: bool = True#
True
- discrete: bool = True#
True
- class pangolin.ir.Cauchy[source]#
Bases:
ScalarOpScalar Cauchy distribution.
The constructor takes no arguments. When used in an
RV, this operation expects the following scalar parents:mu: locationsigma: scale
Cauchyexpects exactly 2 scalar parents. Its shape behavior is inherited fromScalarOp.get_shape: Every parent must have scalar shape(), and the output shape is().Examples
>>> op = Cauchy() >>> op Cauchy() >>> print(op) cauchy >>> op.random True
See also
- random: bool = True#
True
- discrete: bool = False#
False
- class pangolin.ir.Uniform[source]#
Bases:
ScalarOpScalar Uniform distribution.
The constructor takes no arguments. When used in an
RV, this operation expects the following scalar parents:alpha: lower boundbeta: upper bound
Uniformexpects exactly 2 scalar parents. Its shape behavior is inherited fromScalarOp.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:
ScalarOpScalar Beta distribution.
The constructor takes no arguments. When used in an
RV, this operation expects the following scalar parents:alpha: shapebeta: shape
Betaexpects exactly 2 scalar parents. Its shape behavior is inherited fromScalarOp.get_shape: Every parent must have scalar shape(), and the output shape is().Examples
>>> op = Beta() >>> op Beta() >>> print(op) beta >>> op.random True
See also
- random: bool = True#
True
- discrete: bool = False#
False
- class pangolin.ir.Exponential[source]#
Bases:
ScalarOpScalar Exponential distribution.
The constructor takes no arguments. When used in an
RV, this operation expects the following scalar parents:beta: rate / inverse scale
Exponentialexpects exactly 1 scalar parent. Its shape behavior is inherited fromScalarOp.get_shape: Every parent must have scalar shape(), and the output shape is().Examples
>>> op = Exponential() >>> op Exponential() >>> print(op) exponential >>> op.random True
See also
- random: bool = True#
True
- discrete: bool = False#
False
- class pangolin.ir.Gamma[source]#
Bases:
ScalarOpScalar Gamma distribution.
The constructor takes no arguments. When used in an
RV, this operation expects the following scalar parents:alpha: shapebeta: rate / inverse scale
Gammaexpects exactly 2 scalar parents. Its shape behavior is inherited fromScalarOp.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.
See also
- random: bool = True#
True
- discrete: bool = False#
False
- class pangolin.ir.Poisson[source]#
Bases:
ScalarOpScalar Poisson distribution.
The constructor takes no arguments. When used in an
RV, this operation expects the following scalar parents:lambd: lambda
Poissonexpects exactly 1 scalar parent. Its shape behavior is inherited fromScalarOp.get_shape: Every parent must have scalar shape(), and the output shape is().Examples
>>> op = Poisson() >>> op Poisson() >>> print(op) poisson >>> op.random True
See also
- random: bool = True#
True
- discrete: bool = True#
True
- class pangolin.ir.BetaBinomial[source]#
Bases:
ScalarOpScalar BetaBinomial distribution.
The constructor takes no arguments. When used in an
RV, this operation expects the following scalar parents:N: as in binomial distalpha: as in beta distbeta: as in beta dist
BetaBinomialexpects exactly 3 scalar parents. Its shape behavior is inherited fromScalarOp.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:
ScalarOpScalar StudentT distribution.
The constructor takes no arguments. When used in an
RV, this operation expects the following scalar parents:nu: degress of freedommu: location (often 0)sigma: scale (often 1)
StudentTexpects exactly 3 scalar parents. Its shape behavior is inherited fromScalarOp.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
See also
- random: bool = True#
True
- discrete: bool = False#
False
- class pangolin.ir.MultiNormal[source]#
Bases:
OpRepresent 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
- class pangolin.ir.Categorical[source]#
Bases:
OpRepresent a categorical distribution.
A
CategoricalRVhas 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
- class pangolin.ir.Multinomial[source]#
Bases:
OpCreate a
MultinomialOp. Takes no parameters.When used in an
RV, a multinomial op expects a first parentn(a scalar) indicating the number of observations and a second parentpindicating a vector of probabilities (a 1D array). Note that this is different from Stan (which doesn’t neednto be passed).- random: bool = True#
True
- discrete: bool = True#
True
- class pangolin.ir.Dirichlet[source]#
Bases:
OpCreate a
DirichletOp. 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
- class pangolin.ir.Wishart[source]#
Bases:
OpCreate a
WishartOp. Takes no parameters.When used in an
RV, expects two parameters:nu(degrees of freedom, scalar) andS(symmetric positive-definite scale matrix).- random: bool = True#
True
- discrete: bool = False#
False
- class pangolin.ir.VMap(base_op, in_axes, axis_size=None)[source]#
Bases:
Op,GenericVectorize one operation over axes of its inputs.
All arguments here are heavily inspired by jax.lax.vmap although note that
VMaponly maps a singleOp. (Thevmapfunction in the interface elsewhere takes an arbitrary function and transforms it into a graph ofRVobjects withVMapoperations.)- Parameters:
base_op (BaseOp) – Operation to vectorize.
in_axes (Sequence[int | None]) – Axis to map for each input, or
Nonefor 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_sizeis not positive or cannot be inferred fromin_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)
- 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 ofNonepasses its shape unchanged tobase_op. An integer entry removes that axis before callingbase_op.get_shape. All removed axes must have the same size, equal toaxis_sizewhen 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 forbase_op.- Return type:
- type pangolin.ir.VMapStack = VMap | VMap[VMapStack]#
Type-hint-only alias for one or more nested
VMapoperations aroundBaseOp.This alias has no runtime behavior.
For example,
VMapStack[Normal]includesVMap[Normal],VMap[VMap[Normal]], and any deeper nesting, but notNormalitself.
- 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,GenericCompose a sequence of operations into one operation.
Values are numbered in sequential order. The first
num_inputsvalues are the inputs to the composite. Each operation appends one value, so operationimay refer only to values numbered from0throughnum_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((), ()) ()
- get_shape(*parents_shapes)[source]#
Apply the component shape rules and return the final output shape.
- Parameters:
*parents_shapes (Shape) – Exactly
num_inputsshapes. Component Ops receive these input shapes or earlier intermediate shapes according topar_nums.- Returns:
Shape – Output shape produced by the final component
Op.- Raises:
ValueError – If the number of supplied shapes differs from
num_inputsor a componentOprejects its selected parent shapes.- Return type:
- class pangolin.ir.Scan(base_op, length, in_axes)[source]#
Bases:
Op,GenericRepeat an operation while feeding each output into the next iteration.
An
RVusingScanhas parents ordered asstart, *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 thet-th slice ofxalong the specified axis, analogous to numpy.take. Thus,in_axesdescribes onlyinputs, notstart. A mapped input supplies one slice per iteration, while an unmapped input is reused at every iteration. The carry is always the first argument tobase_op.If
base_opis 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_opmust returnstart_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
Nonefor an unmapped input. Every mapped axis must have sizelength.
- Raises:
TypeError – If the constructor arguments have invalid types.
ValueError – If
lengthis not positive, or mapped input shapes disagree withlengthorin_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)
- 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_opinput, and the output ofbase_opmust have this same shape.*other_shapes (Shape) – One shape for each entry of
in_axes. Unmapped shapes are passed unchanged tobase_op; each mapped shape loses its selected axis, whose size must equallength.
- Returns:
Shape –
(length,)followed by the output shape ofbase_opfor 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_oprejects the per-iteration shapes, or its output shape differs from the carry shape.- Return type:
- class pangolin.ir.Bijected(base_op, bijector)[source]#
Bases:
Op,GenericA continuous distribution obtained by applying a bijector to another distribution.
Bijectedis 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_paramsparents are parameters of the bijection; all remaining parents are parameters ofbase_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 constructingxand the deterministicy.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
Opdescribing the base distribution.bijector (B) – Bijection applied to samples from the base distribution.
- Raises:
- 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_paramsshapes for the bijector parameters; then the parent shapes expected bybase_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_opor the bijector rejects the supplied shapes.
- Return type:
- class pangolin.ir.Truncated(base_op, *, lower=True, upper=True)[source]#
Bases:
Op,GenericRestrict a continuous scalar distribution to an interval.
Parents are the lower bound if
lower, then the upper bound ifupper, then the parameters ofbase_opin 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
Opwhose 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_opis not anOpor either bound flag is not a boolean.ValueError – If
base_opis 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 ifupper; each must be(). Remaining shapes are passed tobase_op.get_shapein 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:
- class pangolin.ir.LogProb(base_op)[source]#
Bases:
Op,GenericEvaluate 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 bybase_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
Opdescribing a discrete or continuous distribution.- Raises:
TypeError – If
base_opis not anOp.ValueError – If
base_opis 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:
- 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:
- class pangolin.ir.CDF(base_op)[source]#
Bases:
Op,GenericEvaluate 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 bybase_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
Opdescribing a discrete or continuous distribution.- Raises:
TypeError – If
base_opis not anOp.ValueError – If
base_opis 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:
- 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:
- class pangolin.ir.Quantile(base_op)[source]#
Bases:
Op,GenericEvaluate 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
Opdescribing a discrete or continuous scalar distribution.- Raises:
TypeError – If
base_opis not anOp.ValueError – If
base_opis deterministic. Scalar applicability is checked byget_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:
- 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:
- class pangolin.ir.VJP(base_op, argnum)[source]#
Bases:
Op,GenericApply 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 inputargnum. 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
Opto 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_opis not anOp, orargnumis not an integer (excluding booleans).ValueError – If
base_opis random orargnumis 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:
- Raises:
TypeError – If the cotangent is missing or the base Op rejects the number of input shapes.
ValueError – If
argnumis out of range, the base Op rejects its input shapes, or the cotangent shape differs from the base Op’s output shape.
- Return type:
- 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
Noneto leave the shape unchanged.
- Returns:
remaining_shape – Shape with the selected axis removed.
axis_size – Size of the removed axis, or
NonewhenaxisisNone.
- Raises:
TypeError – If
axisis not an integer orNone.ValueError – If
axisis 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
AandBequal in a mathematical sense?That is, are they guaranteed to always have the same value? This is defined by the following rules:
If
A.opis random, thenAis isrv_equaltoBif and only if they refer to the same object in memory.If
A.opis non-random, thenAisrv_equaltoBif and only if they have the sameOpand their parents arerv_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
RVandOpobjects are immutable.- Parameters:
- 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
Opobjects 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 namesa,b, … in topological order, skipping all discovered names, including unused aliases. Seepangolin.util.node_namesfor 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_upstreamPrint 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 bypangolin.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. Seepangolin.util.node_namesfor 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_parentsis 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 ◀──┘ │ │ │ ↓ └───▶vgraph_upstreamdraws 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_upstreamPrint upstream RVs as a table.
pangolin.util.render_dagGeneric renderer with a complete glyph reference.