functional#

Transform Pangolin IR graphs with reusable functional operations.

graph_scan rebuilds IR graphs directly. bind_interface adapts interface-using functions to RVs carrying any interface. The composite, vmap, and scan combinators accept ordinary IR-producing functions and return new IR-producing functions. A Transform packages forward and inverse RV functions; its callable interface provides combinators for distribution-producing functions.

loop, vfor, and sfor build graphs over named integer ranges, with an explicit interface for their internally created coordinates.

The functional layer provides reusable operations and combinators for manipulating pure IR graphs with ordinary Python functions. It does not provide interface coercion, infix operators, or indexing syntax.

IR graph scans#

pangolin.functional.graph_scan(nodes, step, *, boundary=None)#

Scan an IR graph with RV carries and preserve the requested PyTree structure.

This is the IR-specialized form of pangolin.dag.graph_scan. Each node and propagated carry is an ir.RV; step may rebuild or otherwise replace each visited node while emitting arbitrary auxiliary information.

Parameters:
  • nodes (Nodes) – RV or PyTree of RVs whose upstream graph should be scanned.

  • step (Callable[[RV, tuple[RV, ...]], tuple[RV, Emission]]) – Function returning a replacement RV and an emission from one input RV and its replacement parents.

  • boundary (Mapping[RV, RV] | None) – Optional mapping from input RVs to replacement RVs at which traversal stops.

Returns:

  • replacements – Replacement RVs for nodes with the same runtime PyTree structure. The generic return type describes this structure, not preservation of RV subclasses.

  • emissions – Emission from each visited input RV, keyed by that input RV.

Raises:

TypeError – If nodes has a non-RV leaf or step returns a non-RV carry.

Return type:

tuple[Nodes, dict[RV, Emission]]

Function inspection#

pangolin.functional.ir_code(fun, namespace=None)#

Return a function that displays a specialized IR graph as Python-like code.

Every supplied input leaf must be an RV. Each occurrence becomes a fresh abstract input with the same shape and interface before calling fun once. The returned string shows a function building the resulting graph using bare IR names, with no imports or prefixes. Intermediate assignments preserve node sharing, and the return statement preserves the output’s list, tuple, or dictionary structure.

Parameters:
  • fun (Callable[[P], PyTree[RV]]) – Graph-building function with RV-only input and output trees. Bind fixed Python arguments through a closure or functools.partial before inspection.

  • namespace (Mapping[str, object] | None) – Optional mapping such as locals() containing every captured RV. Captures appear as free references, such as scale or parameters['scale'], not function parameters. The first reference whose root name does not conflict with a parameter, the displayed function name, or an IR name is used.

Returns:

code_for – Function returning the displayed code as a string without printing it.

Raises:
  • TypeError – If any supplied input or returned leaf is not an RV.

  • ValueError – If a captured RV has no unambiguous reference in namespace.

  • NotImplementedError – If an input or output uses a custom PyTree rather than built-in lists, tuples, or dicts.

Return type:

Callable[[P], str]

Notes

This describes one traced specialization, not arbitrary Python control flow. Omitted defaults remain fixed during tracing. Captured RVs, including RV defaults, remain free references. Input ancestry is not copied. Interfaces are used during tracing but omitted from the displayed code.

Input names come from the function signature when available; otherwise *args and **kwargs are used. Lambdas use the name model. Ops use their existing repr, which may abbreviate constants. This is an inspection tool, not an executable serialization of the graph.

Examples

Inspect the precise broadcasting behavior of built-in functions:

>>> from pangolin import interface as pi
>>> print(ir_code(pi.normal)(pi.constant(0.0), pi.constant(1.0)))
def normal(mu, sigma):
    a = RV(Normal(), mu, sigma)
    return a
>>> print(ir_code(pi.normal)(pi.constant([0.0, 1.0]), pi.constant(1.0)))
def normal(mu, sigma):
    a = RV(VMap(Normal(), [0, None], 2), mu, sigma)
    return a

Inspect a pairwise squared-distance matrix built with two named vfor indices:

>>> def distances(x):
...     return pi.vfor(
...         lambda i, j: pi.sum((x[i, :] - x[j, :]) ** 2, axis=0),
...         i=x.shape[0],
...         j=x.shape[0],
...     )
>>> print(ir_code(distances)(pi.constant([[0., 0.], [1., 2.], [3., 1.]])))
def distances(x):
    a = RV(VMap(VMap(VMap(Sub(), [0, 0], 2), [None, 0], 3), [0, None], 3), x, x)
    b = RV(Constant(2))
    c = RV(VMap(VMap(VMap(Pow(), [0, None], 2), [0, None], 3), [0, None], 3), a, b)
    d = RV(VMap(VMap(Sum(axis=0), [0], 3), [0], 3), c)
    return d

Input and output PyTree structure remains visible, including repeated references to an RV:

>>> def model(parameters):
...     x = pi.normal(parameters['mean'], parameters['scales'][0])
...     return {'draw': x, 'derived': (pi.exp(x), x)}
>>> print(ir_code(model)({'mean': pi.constant(0.0), 'scales': [pi.constant(1.0)]}))
def model(parameters):
    a = RV(Normal(), parameters['mean'], parameters['scales'][0])
    b = RV(Exp(), a)
    return {'draw': a, 'derived': (b, a)}

Captured RVs are referenced through the supplied namespace:

>>> scale = pi.exponential(1.0)
>>> def model(mean):
...     return pi.normal(mean, scale)
>>> print(ir_code(model, locals())(pi.constant(0.0)))
def model(mean):
    a = RV(Normal(), mean, scale)
    return a

Non-RV inputs are rejected even if the original function accepts them: RV inputs are required so they can be replaced with symbolic inputs during tracing.

>>> pi.normal(0.0, 1.0)
RV(Normal(), RV(Constant(0.)), RV(Constant(1.)))
>>> ir_code(pi.normal)(0.0, 1.0)
Traceback (most recent call last):
    ...
TypeError: ir_code inputs must be a PyTree whose leaves are RV; found float
pangolin.functional.signature(fun, *, in_ops=None, out_ops=None, ops=False)#

Return a function that describes the inputs and output of each call as a string.

Calling signature(fun)(*args, **kwargs) calls fun once with the supplied arguments unchanged and returns the string (inputs) -> output. No coercion, abstract substitution, sampling, or numerical evaluation is added by this combinator. Any such behavior in fun itself still occurs.

RVs are displayed as RV() for scalars, RV(3,) for vectors, and RV(2, 3) for matrices. If enabled, the Op’s str is appended after the dimensions, as in RV(3, vmap(normal, [0, None], 3)). Lists, tuples, and dictionaries are described recursively; dictionary keys and other values use their repr. Positional parameter names are omitted, while supplied keyword names are retained.

Parameters:
  • fun (Callable[[P], object]) – Function whose calls should be summarized.

  • in_ops (bool | None) – Whether to show the Op of each input RV. None uses ops.

  • out_ops (bool | None) – Whether to show the Op of each output RV. None uses ops.

  • ops (bool) – Show both input and output Ops. Default: False. Setting this to True conflicts with an explicit in_ops=False or out_ops=False and raises ValueError.

Returns:

describe_fun – Function with the same accepted arguments as fun. It returns a summary string, rather than fun’s result, without printing it.

Return type:

Callable[[P], str]

Notes

This describes one observed call, not a general static type signature. Ordinary Python values can change the output structure or shape, so their values are shown rather than just their types. Omitted defaults are not listed. Input descriptions are recorded before the call, and Python side effects and exceptions from fun are preserved.

An RV’s displayed Op is only its own Op, not its parents’ graphs. Use ir.print_upstream to inspect the full graph. Interface properties are neither changed nor displayed.

Examples

Inspect how pi.normal coerces Python values into RVs and broadcasts scalar and array inputs. Inputs are shown as supplied, before coercion:

>>> from pangolin import interface as pi
>>> print(signature(pi.normal)(pi.constant(0.0), pi.constant(1.0)))
(RV(), RV()) -> RV()
>>> print(signature(pi.normal)(pi.constant([0.0, 1.0]), pi.constant(1.0)))
(RV(2,), RV()) -> RV(2,)
>>> print(signature(pi.normal)(0.0, 1.0))
(0.0, 1.0) -> RV()
>>> print(signature(pi.normal)([0.0, 1.0], 1.0))
([0.0, 1.0], 1.0) -> RV(2,)

Optionally include Ops alongside shapes, for outputs alone or for both inputs and outputs:

>>> print(signature(pi.normal, out_ops=True)(pi.constant([0.0, 1.0]), pi.constant(1.0)))
(RV(2,), RV()) -> RV(2, vmap(normal, [0, None], 2))
>>> x = pi.normal(0., 1.)
>>> print(signature(pi.exp, in_ops=True)(x))
(RV(normal)) -> RV()
>>> print(signature(pi.exp, ops=True)(x))
(RV(normal)) -> RV(exp)

Inspect a pairwise squared-distance matrix built with two named vfor indices:

>>> def distances(x):
...     return pi.vfor(
...         lambda i, j: pi.sum((x[i, :] - x[j, :]) ** 2, axis=0),
...         i=x.shape[0],
...         j=x.shape[0],
...     )
>>> print(signature(distances)(pi.constant([[0., 0.], [1., 2.], [3., 1.]])))
(RV(3, 2)) -> RV(3, 3)

Input and output PyTree structure remains visible:

>>> def model(parameters):
...     x = pi.normal(parameters['mean'], parameters['scales'][0])
...     return {'draw': x, 'derived': (pi.exp(x), x)}
>>> print(signature(model)({'mean': pi.constant(0.0), 'scales': [pi.constant(1.0)]}))
({'mean': RV(), 'scales': [RV()]}) -> {'draw': RV(), 'derived': (RV(), RV())}

Captured RVs are not call arguments and do not appear in the signature:

>>> scale = pi.exponential(1.0)
>>> def model(mean):
...     return pi.normal(mean, scale)
>>> print(signature(model)(pi.constant(0.0)))
(RV()) -> RV()

PyTree structure and keyword names remain visible, even when the output structure depends on a Python argument:

>>> def model(parameters, *, squared=False):
...     x = pi.normal(parameters['mean'], parameters['scale'])
...     if squared:
...         return {'x': x, 'squared': x * x}
...     else:
...         return x
>>> print(signature(model)({'mean': 0.0, 'scale': 1.0}, squared=True))
({'mean': 0.0, 'scale': 1.0}, squared=True) -> {'x': RV(), 'squared': RV()}
>>> print(signature(model)({'mean': 0.0, 'scale': 1.0}, squared=False))
({'mean': 0.0, 'scale': 1.0}, squared=False) -> RV()

Interface binding#

pangolin.functional.bind_interface(interface, fun, /)#

Bind the RV inputs seen by fun to an interface while preserving its signature.

The returned function accepts RVs carrying any interfaces. On each call, fun is traced with abstract replacements carrying interface for every RV input. Non-RV inputs are passed through unchanged. The traced graph is then replayed with the exact original RVs replacing the abstract inputs.

Captured RVs remain unchanged, while every generated RV carries the interface selected by its corresponding traced RV. Repeated input and output RV identities are preserved, and returning an input directly returns that exact input object.

Parameters:
  • interface (RVInterface) – Interface attached to the abstract RV inputs supplied to fun.

  • fun (Callable[[P], Output]) – RV-producing function to bind. Its output must be a PyTree of RVs.

Returns:

bound_fun – Function with the same signature and output PyTree type as fun.

Raises:

TypeError – If an output leaf is not an ir.RV.

Return type:

Callable[[P], Output]

Examples

Bind infix addition to a small interface without changing the actual input RV:

>>> class AddInterface(ir.RVInterface):
...     def add(self, x, y):
...         if not isinstance(y, ir.RV):
...             y = ir.RV(ir.Constant(y), interface=self)
...         return ir.RV(ir.Add(), x, y, interface=self)
>>> interface = AddInterface()
>>> add_one = bind_interface(interface, lambda x: x + 1)
>>> x = ir.RV(ir.Constant(2))
>>> result = add_one(x)
>>> result.parents[0] is x
True
>>> result.interface is interface
True

Indexing#

pangolin.functional.index_orthogonal(x, *indices, interface=NO_INTERFACE)#

Index an RV with independent indices for each axis.

Supply exactly one integer-valued index RV per dimension of x. Each index contributes all of its dimensions independently, so the output shape is the concatenation of the index shapes. This constructs scalar ir.Index wrapped in one ir.VMap per index dimension.

Parameters:
  • x (RV) – RV to index.

  • *indices (RV) – Index RVs in axis order. Scalars select a single entry along an axis. No coercion, slices, or ellipses are supported.

  • interface (RVInterface) – Interface attached to the result. Defaults to ir.NO_INTERFACE, regardless of the interfaces of x and indices. Existing parents are left unchanged.

Returns:

indexed – RV containing the selected entries.

Return type:

RV

Examples

>>> from pangolin import ir
>>> x = ir.RV(ir.Constant([[10, 20, 30], [40, 50, 60]]))
>>> rows = ir.RV(ir.Constant([1, 0]))
>>> column = ir.RV(ir.Constant(2))
>>> y = index_orthogonal(x, rows, column)
>>> y.op
VMap(Index(), [None, 0, None], 2)
>>> y.shape
(2,)

Array indices are independent, not paired:

>>> columns = ir.RV(ir.Constant([2, 0, 1]))
>>> y = index_orthogonal(x, rows, columns)
>>> y.op
VMap(VMap(Index(), [None, None, 0], 3), [None, 0, None], 2)
>>> y.shape
(2, 3)

Graph combinators#

pangolin.functional.composite(fun, *, simplify=True)#

A combinator that returns a function compressing fun’s graph into one RV.

Each call invokes fun normally, traces the newly created IR graph contributing to its output, and compresses that graph into one ir.Composite Op. Pre-existing RVs become parents of the resulting RV. New RVs that do not contribute to the output are omitted.

Every contributing RV other than the output must have a deterministic Op. The output may be deterministic or random. Arguments need not be RVs: they are passed to fun unchanged and may control ordinary Python execution or be used by fun to construct RVs. composite performs no argument coercion. The result is a plain ir.RV carrying the traced output’s interface.

Parameters:
  • fun (Callable[[P], RV]) – Function that creates and returns exactly one new ir.RV. Its arguments may have any Python or PyTree structure accepted by the function itself.

  • simplify (bool) – If true, replace a Composite containing a single Op with that Op when they are equivalent (the default). Otherwise, retain the Composite.

Returns:

composite_fun – Function accepting the same runtime arguments as fun and returning an RV containing the compressed Op, which is an ir.Composite unless simplified.

Raises:
  • TypeError – If fun does not return exactly one ir.RV.

  • ValueError – If fun returns an RV that existed before the call, or a contributing intermediate RV has a random Op.

Return type:

Callable[[P], RV]

Examples

The combinator first returns a function. Calling that function constructs a Composite RV whose parents are the existing arguments:

>>> def normal_with_sum(a, b):
...     total = ir.RV(ir.Add(), a, b)
...     return ir.RV(ir.Normal(), total, b)
>>> composite_normal_with_sum = composite(normal_with_sum)
>>> composite_normal_with_sum
<function composite_normal_with_sum at 0x...>
>>> x = ir.RV(ir.Constant(1))
>>> y = ir.RV(ir.Constant(2))
>>> result = composite_normal_with_sum(x, y)
>>> result.op
Composite(2, [Add(), Normal()], [[0, 1], [2, 1]])
>>> result.parents == (x, y)
True

RVs captured by fun follow contributing argument RVs in the parent list:

>>> offset = ir.RV(ir.Constant(3))
>>> add_offset = composite(lambda value: ir.RV(ir.Add(), offset, value))
>>> result = add_offset(x)
>>> result.parents == (x, offset)
True

Non-RV arguments are passed through and do not themselves become parents:

>>> def choose(value, take_log):
...     op = ir.Log() if take_log else ir.Exp()
...     return ir.RV(op, value)
>>> choose_composite = composite(choose, simplify=False)
>>> result = choose_composite(x, True)
>>> result.op
Composite(1, [Log()], [[0]])
>>> result.parents == (x,)
True

By default, the single-Op Composite is simplified:

>>> composite(choose)(x, True).op
Log()

The Composite RV carries the interface selected by fun:

>>> interface = ir.RVInterface()
>>> value = ir.RV(ir.Constant(1))
>>> special_exp = composite(
...     lambda value: ir.RV(ir.Exp(), value, interface=interface)
... )
>>> result = special_exp(value)
>>> result.interface is interface
True
pangolin.functional.log_prob(fun)#

A combinator that returns a function building a distribution’s log probability.

Calling log_prob(fun)(value, *args, **kwargs) calls fun(*args, **kwargs) once, retains its contributing deterministic graph, and creates an ir.LogProb RV using the output’s Op and parents. It does not introduce a Composite or retain the random output as a parent. The result is a deterministic scalar RV carrying that output’s interface.

The function must return exactly one newly created random RV. Every other contributing newly created RV must be deterministic. Existing random inputs and captures are allowed. The resulting LogProb node evaluates the output distribution at the evaluation value and its parent values. It does not compute a marginal density by integrating over random parents. Newly created nodes that do not contribute to the output are ignored. Discrete and continuous distributions are both allowed.

Parameters:

fun (Callable[[P], RV]) – Function creating one random RV. Arguments may have any Python or PyTree structure accepted by the function itself and are supplied unchanged, without coercion.

Returns:

log_prob_fun – Function taking a positional-only evaluation RV followed by fun’s arguments. The evaluation RV must have exactly the distribution output’s shape; no coercion or broadcasting is performed. For array-valued distributions the result is the joint log density or mass of the whole array.

Raises:
  • TypeError – If the evaluation value or the function output is not a single RV.

  • ValueError – If the output is pre-existing or deterministic, a contributing intermediate RV is random, or the evaluation value has the wrong shape.

Return type:

Callable[[Concatenate[RV, P]], RV]

Examples

Deterministic parameter calculations remain ordinary graph nodes:

>>> def normal_with_log_scale(mean, log_scale):
...     scale = ir.RV(ir.Exp(), log_scale)
...     return ir.RV(ir.Normal(), mean, scale)
>>> normal_log_prob = log_prob(normal_with_log_scale)
>>> mean = ir.RV(ir.Constant(0.0))
>>> log_scale = ir.RV(ir.Constant(0.0))
>>> value = ir.RV(ir.Constant(2.0))
>>> result = normal_log_prob(value, mean, log_scale)
>>> result.op
LogProb(Normal())
>>> result.parents[2].op
Exp()
>>> result.parents[0] is value
True
>>> result.shape, result.op.random
((), False)
pangolin.functional.cdf(fun)#

A combinator that returns a function building a distribution’s CDF.

Calling cdf(fun)(value, *args, **kwargs) calls fun(*args, **kwargs) once, retains its contributing deterministic graph, and creates an ir.CDF RV using the output’s Op and parents. It does not introduce a Composite or retain the random output as a parent. The result is a deterministic scalar RV carrying that output’s interface.

The function must return exactly one newly created random RV. Every other contributing newly created RV must be deterministic. Existing random inputs and captures are allowed. The resulting CDF node evaluates the output distribution at the evaluation value and its parent values. It does not compute a marginal CDF by integrating over random parents. Newly created nodes that do not contribute to the output are ignored. Discrete and continuous distributions are both allowed.

Parameters:

fun (Callable[[P], RV]) – Function creating one random RV. Arguments may have any Python or PyTree structure accepted by the function itself and are supplied unchanged, without coercion.

Returns:

cdf_fun – Function taking a positional-only evaluation RV followed by fun’s arguments. The evaluation RV must have exactly the distribution output’s shape; no coercion or broadcasting is performed. The result is the probability that the output is less than or equal to the evaluation value. For array-valued distributions this means every component satisfies the inequality simultaneously, not an array of componentwise CDFs.

Raises:
  • TypeError – If the evaluation value or the function output is not a single RV.

  • ValueError – If the output is pre-existing or deterministic, a contributing intermediate RV is random, or the evaluation value has the wrong shape.

Return type:

Callable[[Concatenate[RV, P]], RV]

Examples

Deterministic parameter calculations remain ordinary graph nodes:

>>> def normal_with_log_scale(mean, log_scale):
...     scale = ir.RV(ir.Exp(), log_scale)
...     return ir.RV(ir.Normal(), mean, scale)
>>> normal_cdf = cdf(normal_with_log_scale)
>>> mean = ir.RV(ir.Constant(0.0))
>>> log_scale = ir.RV(ir.Constant(0.0))
>>> value = ir.RV(ir.Constant(2.0))
>>> result = normal_cdf(value, mean, log_scale)
>>> result.op
CDF(Normal())
>>> result.parents[2].op
Exp()
>>> result.parents[0] is value
True
>>> result.shape, result.op.random
((), False)
pangolin.functional.quantile(fun)#

A combinator that returns a function building a scalar distribution’s quantile.

Calling quantile(fun)(probability, *args, **kwargs) calls fun(*args, **kwargs) once, retains its contributing deterministic graph, and creates an ir.Quantile RV using the output’s Op and parents. It does not introduce a Composite or retain the random output as a parent. The result is a deterministic scalar RV.

The function must return exactly one newly created scalar random RV. Every other contributing newly created RV must be deterministic. Existing random inputs and captures are allowed. The quantile evaluates the output distribution using its parent values; it does not integrate over their upstream distributions. Newly created nodes that do not contribute to the output are ignored. Discrete and continuous distributions are allowed by the IR, but numerical support depends on the backend.

Parameters:

fun (Callable[[P], RV]) – Function creating one scalar random RV. Its arguments may have any Python or PyTree structure accepted by the function itself.

Returns:

quantile_fun – Function taking a positional-only scalar probability RV followed by fun’s arguments. For a probability strictly between zero and one, the result is the smallest value at which the CDF reaches that probability. At zero and one, it uses the corresponding one-sided limits, which may be infinite. Probability values and numerical support are checked by the backend, not when constructing the graph.

Raises:
  • TypeError – If the probability or the function output is not a single RV.

  • ValueError – If the probability or distribution output is not scalar, the output is pre-existing or deterministic, or a contributing intermediate RV is random.

Return type:

Callable[[Concatenate[RV, P]], RV]

Notes

Arguments are supplied to fun unchanged. This combinator performs no coercion or broadcasting. Any coercion performed by fun is preserved, but its output must still be scalar. Use vmap around the quantile function for independent evaluations; there is no joint quantile for an array-valued distribution. The result carries the interface of fun’s output, regardless of the probability RV’s interface.

Examples

Deterministic parameter calculations remain ordinary graph nodes:

>>> def normal_with_log_scale(mean, log_scale):
...     scale = ir.RV(ir.Exp(), log_scale)
...     return ir.RV(ir.Normal(), mean, scale)
>>> probability = ir.RV(ir.Constant(0.5))
>>> zero = ir.RV(ir.Constant(0.0))
>>> result = quantile(normal_with_log_scale)(probability, zero, zero)
>>> result.op
Quantile(Normal())
>>> result.parents[0] is probability
True
>>> result.parents[2].op
Exp()
>>> result.shape, result.op.random
((), False)

Vectorize the quantile function, rather than the distribution inside it:

>>> from pangolin.functional import vmap
>>> probabilities = ir.RV(ir.Constant([0.1, 0.5, 0.9]))
>>> result = vmap(quantile(normal_with_log_scale), (0, None, None))(probabilities, zero, zero)
>>> result.op
VMap(Quantile(Normal()), [0, None, None], 3)
>>> result.shape
(3,)
pangolin.functional.truncated(fun, lo=None, hi=None)#

A combinator that restricts scalar distributions to a shared interval.

Calling truncated(fun, lo, hi)(*args, **kwargs) calls fun once and constructs a new random RV representing its output distribution restricted to the supplied bounds, with the appropriate normalization. Each bound must be a scalar RV or None to omit that bound. Supplied bounds may be random or deterministic; their realized values must be finite and strictly inside the base distribution’s support, with lo < hi when both are supplied. Backends enforce these value-dependent requirements during evaluation, not when the graph is constructed.

The function must return exactly one newly created continuous random RV. As with composite, no other random RVs created by the function may contribute to the output. Multivariate distributions are unsupported, except when formed by vectorizing scalar distributions.

The result preserves the output shape, applying the same bounds to every vectorized draw. With both bounds omitted, the original output RV is returned, subject to the same requirements.

Parameters:
  • fun (Callable[[P], RV]) – Function creating one continuous random RV, scalar or an independent array of scalar draws expressed through VMap and Composite. Its arguments may have any Python or PyTree structure accepted by the function itself.

  • lo (RV | None) – Scalar RV supplying the lower bound, or None (the default) to omit it.

  • hi (RV | None) – Scalar RV supplying the upper bound, or None (the default) to omit it.

Returns:

truncated_fun – Function accepting the same arguments as fun and constructing its truncated output.

Raises:
  • TypeError – If either bound is neither an RV nor None, or fun does not return exactly one RV.

  • ValueError – If a bound is not scalar, the output is pre-existing, deterministic, or discrete, a contributing intermediate RV is random, or a remaining base distribution is not scalar.

Return type:

Callable[[P], RV]

Notes

Arguments are supplied to fun unchanged. This combinator performs no coercion or broadcasting. Any coercion or broadcasting performed by fun is preserved. Bounds are checked when the combinator is constructed and are never broadcast. The result carries the interface of fun’s output, regardless of the interfaces of its bounds or parameters.

Examples

Truncate a Normal using scalar RV bounds. The result’s parents are the bounds followed by the original distribution parameters:

>>> def normal(mean, scale):
...     return ir.RV(ir.Normal(), mean, scale)
>>> zero = ir.RV(ir.Constant(0.0))
>>> one = ir.RV(ir.Constant(1.0))
>>> mean = ir.RV(ir.Constant(1.1))
>>> scale = ir.RV(ir.Constant(2.2))
>>> positive_normal = truncated(normal, lo=zero)
>>> result = positive_normal(mean, scale)
>>> result.op
Truncated(Normal(), upper=False)
>>> result.parents == (zero, mean, scale)
True
>>> result.shape, result.op.random
((), True)

Vectorization remains outside the scalar truncation. The bounds are shared, not mapped:

>>> from pangolin.functional import composite, vmap
>>> means = ir.RV(ir.Constant([1.1, 1.2, 1.3]))
>>> vector_normal = vmap(normal, (0, None))
>>> result = truncated(vector_normal, lo=zero)(means, scale)
>>> result.op
VMap(Truncated(Normal(), upper=False), [None, 0, None], 3)
>>> result.shape
(3,)

Deterministic parameter calculations inside a Composite are retained:

>>> def normal_with_log_scale(mean, log_scale):
...     scale = ir.RV(ir.Exp(), log_scale)
...     return normal(mean, scale)
>>> log_scale = ir.RV(ir.Constant(3.3))
>>> result = truncated(composite(normal_with_log_scale), zero, one)(mean, log_scale)
>>> result.op
Composite(4, [Exp(), Truncated(Normal())], [[3], [0, 1, 2, 4]])

Scalar bijections are truncated in their output coordinates, not underneath the bijection:

>>> from pangolin.functional import tforms
>>> result = truncated(tforms.exp(normal), lo=one)(mean, scale)
>>> result.op
Truncated(Bijected(Normal(), Bijector(Exp(), Log(), Composite(2, [Log()], [[1]]), sign=Constant(1))), upper=False)

Even a length-one array is not a scalar bound:

>>> truncated(normal, ir.RV(ir.Constant([0.0])))
Traceback (most recent call last):
    ...
ValueError: truncation bounds must be scalar
pangolin.functional.grad(fun, argnum=0)#

A combinator that returns a function building a scalar output’s gradient.

The selected positional argument must be an RV or a PyTree whose leaves are RVs. The function is traced once and must return one scalar RV. A single reverse traversal builds gradients for all selected leaves, without introducing a Composite.

Each leaf occurrence is an independent differentiation input, even when the same RV appears in multiple positions. Reusing a leaf within the function accumulates its contributions. Other arguments and captures are independent of every selected leaf for differentiation, even when they refer to the same RV or depend on it in the existing graph.

Parameters:
  • fun (Callable[[P], RV]) – Function returning one scalar RV, with no contributing newly created random nodes. Existing random inputs and captures are allowed; their upstream graphs are not differentiated.

  • argnum (int) – Nonnegative index of the positional RV or RV-only PyTree argument to differentiate. Other arguments may have any Python or PyTree structure accepted by fun; no inputs are coerced.

Returns:

grad_fun – Function accepting fun’s arguments and returning the selected argument’s PyTree structure, with one gradient RV of matching shape per leaf. An unused leaf gives zeros; returning a selected scalar leaf gives one for that leaf and zeros for the others. Empty trees return empty trees, but fun is still called and its output validated. A single RV argument still returns a single RV. Container types follow JAX’s PyTree registration; dictionary keys and custom-node metadata are not differentiated.

Raises:
  • TypeError – If argnum is not an integer, any selected leaf is not an RV (including None), or the output is not a single RV.

  • ValueError – If argnum is negative or missing from the positional arguments, the output is not scalar, or the contributing computation contains newly created random RVs.

Return type:

Callable[[P], Any]

Notes

Each selected leaf’s interface is preserved during tracing. New derivative nodes and every returned gradient RV use the function output’s interface. Existing inputs and captures retain their interfaces. The scalar seed uses the default interface; an Identity node adapts it when necessary. Numeric leaves are not coerced into RVs.

Static typing preserves fun’s parameter signature but uses Any for the gradient’s return type to avoid rejecting valid lambdas and compositions. The selected argument’s RV-only restriction and the returned tree structure are enforced at runtime.

Examples

>>> def square(x):
...     return ir.RV(ir.Mul(), x, x)
>>> derivative = grad(square)
>>> result = derivative(ir.RV(ir.Constant(3.0)))
>>> result.op
Add()
>>> [parent.op for parent in result.parents]
[VJP(Mul(), 0), VJP(Mul(), 1)]

The gradient has the same tree structure as the selected argument:

>>> def product(pair):
...     return ir.RV(ir.Mul(), pair['x'], pair['y'][0])
>>> x = ir.RV(ir.Constant(2.0))
>>> y = ir.RV(ir.Constant(3.0))
>>> result = grad(product)({'x': x, 'y': [y]})
>>> result['x'].op, result['y'][0].op
(VJP(Mul(), 0), VJP(Mul(), 1))
>>> result['x'].parents[1:] == (x, y)
True
pangolin.functional.vjp(fun, argnum=0)#

A combinator that returns a function building a vector-Jacobian product.

vjp(fun, argnum)(cotangent, *args, **kwargs) differentiates with respect to one positional argument of fun, which must be an RV. For real-valued inputs and outputs, the result is the gradient of the sum of the elementwise product of fun’s output and cotangent. The cotangent’s own dependencies do not contribute to this differentiation. The function must return one RV and must not create contributing random nodes. Arguments and captures may themselves be random RVs: their upstream graphs are not differentiated. Other arguments and captures are independent of the selected argument for differentiation, even when they refer to the same RV.

The function is traced once. Reverse traversal builds per-Op ir.VJP nodes and adds contributions where paths meet, without introducing a Composite. The resulting graph is connected back to the original arguments. Newly created nodes that do not contribute to the output are ignored.

Parameters:
  • fun (Callable[[P], RV]) – Function returning one RV. Contributing newly created nodes must be deterministic. Returning the selected argument or another existing RV is allowed.

  • argnum (int) – Nonnegative index of the positional RV argument to differentiate. Other arguments may have any Python or PyTree structure accepted by fun; no inputs are coerced.

Returns:

vjp_fun – Function taking a positional-only cotangent RV followed by fun’s arguments. The cotangent must have exactly the output’s shape, without coercion or broadcasting. Returns one RV with the selected argument’s shape. An unused argument gives zeros; an identity function gives the cotangent’s value.

Raises:
  • TypeError – If argnum is not an integer, the cotangent or selected argument is not an RV, or the output is not a single RV.

  • ValueError – If argnum is negative or missing from fun’s positional arguments, the cotangent has the wrong shape, or the contributing computation contains newly created random RVs.

Return type:

Callable[[Concatenate[RV, P]], RV]

Notes

RVs representing calculations in fun retain their interfaces. New VJP, accumulation, and zero nodes use the function output’s interface. Existing inputs, captures, and the supplied cotangent retain their interfaces. The returned RV always has the function output’s interface; an Identity node adapts it when necessary.

Examples

>>> def square(x):
...     return ir.RV(ir.Mul(), x, x)
>>> derivative = vjp(square)
>>> x = ir.RV(ir.Constant(3.0))
>>> cotangent = ir.RV(ir.Constant(2.0))
>>> result = derivative(cotangent, x)
>>> result.op
Add()
>>> [parent.op for parent in result.parents]
[VJP(Mul(), 0), VJP(Mul(), 1)]
>>> result.parents[0].parents[1:] == (x, x)
True
pangolin.functional.vmap(fun, in_axes=0, axis_size=None, *, simplify=True)#

A combinator that returns a vectorized version of an IR-producing function.

Pangolin calls fun once with abstract RVs and lifts the resulting scalar graph. Each abstract input carries the actual input’s interface, and each lifted node carries the interface selected by the corresponding traced node.

An input leaf assigned an integer axis must be an RV. A leaf assigned None may be either an RV or any Python value; non-RV values are passed to fun unchanged and never become VMap parents. Outputs must be a PyTree of newly created RVs.

Parameters:
  • fun (Callable[[*Args], Output]) – Function whose output is a PyTree of newly created ir.RV objects.

  • in_axes (PyTree[int | None]) – Integer, None, or PyTree selecting an axis for each RV input. The specification may be a prefix of the positional argument PyTree. None leaves an RV unmapped or passes a non-RV value unchanged.

  • axis_size (int | None) – Explicit mapped-axis size. It is inferred from the first mapped RV when omitted and is required when no RV input is mapped.

  • simplify (bool) – Whether to eliminate recognized indexing and axis-permutation patterns.

Returns:

vectorized_fun – Function accepting the original positional argument structures and returning the original output PyTree structure with a leading mapped axis on each RV.

Raises:
  • TypeError – If an integer axis is assigned to a non-RV argument or an output leaf is not an ir.RV.

  • ValueError – If mapped sizes disagree, no axis size is available, or an output RV was not created by fun.

Return type:

Callable[[*Args], Output]

Examples

The combinator returns a function that maps a scalar exponential over an RV vector:

>>> def scalar_exp(x):
...     return ir.RV(ir.Exp(), x)
>>> mapped_exp = vmap(scalar_exp)
>>> mapped_exp
<function vmap_scalar_exp at 0x...>
>>> values = ir.RV(ir.Constant([1.0, 2.0, 3.0]))
>>> result = mapped_exp(values)
>>> result.op
VMap(Exp(), [0], 3)
>>> result.parents == (values,)
True

An unmapped Python value is passed through without becoming a parent:

>>> def choose(x, operation):
...     op = ir.Log() if operation == "log" else ir.Exp()
...     return ir.RV(op, x)
>>> mapped_choose = vmap(choose, in_axes=(0, None))
>>> result = mapped_choose(values, "log")
>>> result.op
VMap(Log(), [0], 3)
>>> result.parents == (values,)
True

Each lifted output carries the interface selected by the mapped function:

>>> interface = ir.RVInterface()
>>> special_exp = vmap(lambda x: ir.RV(ir.Exp(), x, interface=interface))
>>> special_result = special_exp(values)
>>> special_result.interface is interface
True
pangolin.functional.scan(fun, length, in_axes=0, *, simplify=True)#

A combinator that returns a function constructing a Scan RV from a step function.

The step function has the conceptual signature fun(carry, *step_args) -> next_carry. It must create and return exactly one RV that depends on carry and has the same shape. Calling the returned function constructs one RV representing all length successive carries.

Pangolin calls fun once; it does not execute a Python loop. Each RV argument is replaced by an abstract RV carrying the same interface. A non-RV argument is permitted when its axis is None and is passed to fun unchanged. Non-RV values never become Scan parents. The traced step output must have the initial carry’s interface, which the resulting Scan RV also carries.

Parameters:
  • fun (Callable[[Carry, *Args], ir.RV]) – Step function with the conceptual signature fun(carry, *step_args) -> next_carry.

  • length (int) – Positive number of scan steps.

  • in_axes (PyTree[int | None]) – Axis specification for the arguments after the carry. An integer selects an axis of an RV; None reuses an RV or passes a non-RV value unchanged at every step. A PyTree may match or be a prefix of the additional argument structure. The carry is not included.

  • simplify (bool) – If true, replace full-range indexing in the step with direct scanned inputs and remove unused coordinates (the default).

Returns:

scan_fun – Function accepting an initial carry followed by additional RV PyTrees and returning one RV containing an ir.Scan Op.

Raises:
  • TypeError – If the initial carry is not an ir.RV, an integer axis is assigned to a non-RV argument, or fun does not return exactly one RV.

  • ValueError – If length is invalid, a scanned axis has the wrong length, the output does not depend on the carry, the output existed before the call, its shape or interface differs from the carry, or a contributing intermediate RV has a random Op.

Return type:

Callable[[Carry, *Args], ir.RV]

Examples

The combinator returns a function that repeatedly exponentiates a scalar carry:

>>> start = ir.RV(ir.Constant(1.0))
>>> def exp_step(carry):
...     return ir.RV(ir.Exp(), carry)
>>> repeated_exp = scan(exp_step, length=3)
>>> repeated_exp
<function scan_exp_step at 0x...>
>>> result = repeated_exp(start)
>>> result.op
Scan(Exp(), 3, [])
>>> result.parents == (start,)
True

Scan an additional argument along axis zero:

>>> increments = ir.RV(ir.Constant([1.0, 2.0, 3.0]))
>>> add_steps = scan(lambda carry, x: ir.RV(ir.Add(), carry, x), length=3)
>>> result = add_steps(start, increments)
>>> result.op
Scan(Add(), 3, [0])
>>> result.parents == (start, increments)
True

A non-RV configuration argument can be passed unchanged with in_axes=None:

>>> def configured_step(carry, config):
...     op = ir.Exp() if config["exponential"] else ir.Identity()
...     return ir.RV(op, carry)
>>> configured = scan(configured_step, length=2, in_axes=None)
>>> result = configured(start, {"exponential": True})
>>> result.op
Scan(Exp(), 2, [])
>>> result.parents == (start,)
True

The Scan RV carries the initial carry’s interface:

>>> interface = ir.RVInterface()
>>> special_start = ir.RV(ir.Constant(1.0), interface=interface)
>>> special_scan = scan(lambda carry: ir.RV(ir.Exp(), carry, interface=interface), length=3)
>>> special_result = special_scan(special_start)
>>> special_result.interface is interface
True
pangolin.functional.vfor(fun: Callable[[], Output], /, *, interface: RVInterface, **sizes: int) → Output#
pangolin.functional.vfor(fun: Callable[[ir.RV], Output], /, *, interface: RVInterface, **sizes: int) → Output
pangolin.functional.vfor(fun: Callable[[ir.RV, ir.RV], Output], /, *, interface: RVInterface, **sizes: int) → Output
pangolin.functional.vfor(fun: Callable[[ir.RV, ir.RV, ir.RV], Output], /, *, interface: RVInterface, **sizes: int) → Output
pangolin.functional.vfor(fun: Callable[[ir.RV, ir.RV, ir.RV, ir.RV], Output], /, *, interface: RVInterface, **sizes: int) → Output
pangolin.functional.vfor(fun: Callable[[ir.RV, ir.RV, ir.RV, ir.RV, ir.RV], Output], /, *, interface: RVInterface, **sizes: int) → Output
pangolin.functional.vfor(fun: Callable[[ir.RV, ir.RV, ir.RV, ir.RV, ir.RV, ir.RV, *Rest], Output], /, *, interface: RVInterface, **sizes: int) → Output
pangolin.functional.vfor(fun: None = None, /, *, interface: RVInterface, **sizes: int) → VForDecorator

Vectorize a function over named integer ranges.

fun must have a fixed positional signature. Each parameter receives a scalar ir.RV representing an integer coordinate from zero through one less than its named size. fun must return a PyTree of newly created ir.RV objects; it cannot return a coordinate or an existing RV captured through a closure. With no coordinate parameters, fun is called directly and its RV outputs need not be newly created.

Axis sizes are matched to function parameters by name. Output axes occur in function-parameter order, regardless of the order in which keyword arguments are supplied.

This combinator supports direct calls, decorator factories, and multiline decorator syntax.

Parameters:
  • fun (Callable[..., PyTree[ir.RV]] | None) – Function to vectorize, or None when creating a decorator. It must have a fixed positional signature, accept one scalar ir.RV coordinate per parameter, and return a PyTree of newly created ir.RV objects. No parameter may be named interface.

  • interface (ir.RVInterface) – Required keyword-only interface attached to the generated coordinate RVs. Output RVs retain the interfaces chosen by fun.

  • **sizes (int) – Positive integer size for every parameter of fun, supplied under the corresponding parameter name.

Returns:

output_or_decorator (PyTree[ir.RV] | decorator) – The vectorized output PyTree when fun is supplied, otherwise a decorator that accepts fun and produces that output.

Raises:
  • TypeError – If fun is not callable, has no fixed positional signature, a size is not an integer, or the output is not a PyTree of ir.RV objects.

  • ValueError – If an axis size is missing, an unknown axis name is supplied, a size is not positive, a parameter is named interface, or an output RV was not created by fun.

Return type:

Output | VForDecorator

Notes

Static type checking preserves the number of coordinate arguments and exact PyTree structure of the output, and requires the first six arguments to be ir.RV objects. Runtime validation still applies to every argument.

Examples

Direct call:

>>> from pangolin import interface as pi
>>> interface = pi.default
>>> x = vfor(lambda i, j: 10 * i + j, interface=interface, i=2, j=3)
>>> x.shape
(2, 3)

Keyword order does not affect axis order:

>>> y = vfor(lambda i, j: 10 * i + j, interface=interface, j=3, i=2)
>>> y.shape
(2, 3)
>>> ir.rv_equal(x, y)
True

Decorator factory:

>>> make_x = vfor(interface=interface, i=2, j=3)
>>> x = make_x(lambda i, j: 10 * i + j)
>>> x.shape
(2, 3)

Multiline decorator form:

>>> @vfor(interface=interface, i=2, j=3)
... def x(i, j):
...     return 10 * i + j
>>> x.shape
(2, 3)

Every function parameter must have a named size:

>>> vfor(lambda i, j: i + j, interface=interface, i=2)
Traceback (most recent call last):
...
ValueError: vfor missing size for axis 'j'

Unknown axis names are rejected:

>>> vfor(lambda i, j: i + j, interface=interface, i=2, j=3, k=4)
Traceback (most recent call last):
...
ValueError: vfor got size for unknown axis 'k'; expected ('i', 'j')

Python defaults are not interpreted as axis sizes:

>>> vfor(lambda i=3: i + 1, interface=interface)
Traceback (most recent call last):
...
TypeError: <lambda> has no fixed positional signature: 'i' has a default
pangolin.functional.sfor(fun: Callable[[RV, RV], RV], /, *, init: RV, interface: RVInterface, **sizes: int) → RV#
pangolin.functional.sfor(fun: Callable[[RV, RV, RV], RV], /, *, init: RV, interface: RVInterface, **sizes: int) → RV
pangolin.functional.sfor(fun: Callable[[RV, RV, RV, RV], RV], /, *, init: RV, interface: RVInterface, **sizes: int) → RV
pangolin.functional.sfor(fun: Callable[[RV, RV, RV, RV, RV], RV], /, *, init: RV, interface: RVInterface, **sizes: int) → RV
pangolin.functional.sfor(fun: Callable[[ir.RV, ir.RV, ir.RV, ir.RV, ir.RV, ir.RV, *Rest], ir.RV], /, *, init: RV, interface: RVInterface, **sizes: int) → RV
pangolin.functional.sfor(fun: None = None, /, *, init: RV, interface: RVInterface, **sizes: int) → SForDecorator

Build a state sequence with named sequential and parallel coordinates.

This combinator constructs the result directly. A scalar call of the form:

x = sfor(fun, init=init, interface=interface, t=T)

has these semantics:

previous = init
states = []
for t in range(T):
    t_rv = ir.RV(ir.Constant(t), interface=interface)
    next_state = fun(previous, t_rv)
    states.append(next_state)
    previous = next_state
x = stack(states)

For example, if:

fun = lambda previous, t: normal(previous, 1)

then:

x[0] ~ normal(init, 1)
x[t] ~ normal(x[t-1], 1), t > 0

A call with parallel coordinates:

x = sfor(fun, init=init, interface=interface, t=T, i=I, j=J)

has these semantics:

previous = init
states = []
for t in range(T):
    t_rv = ir.RV(ir.Constant(t), interface=interface)
    next_state = empty((I, J))
    for i in range(I):
        i_rv = ir.RV(ir.Constant(i), interface=interface)
        for j in range(J):
            j_rv = ir.RV(ir.Constant(j), interface=interface)
            next_state[i, j] = fun(previous, t_rv, i_rv, j_rv)
    states.append(next_state)
    previous = next_state
x = stack(states)

This pseudocode describes the meaning of the loops, not the graph constructed internally. Internally, each coordinate range is a constant RV array with the supplied interface, and the combinators trace fun with abstract scalar coordinates carrying that same interface. The loops are represented by one Scan containing nested VMap operations; they are not executed in Python. Function-parameter order determines the nesting, while keyword order has no effect.

For example, if:

fun = lambda previous, t, i, j: normal(a[i, j] * previous[i, j] + b[t, i, j], c[i, j])

then:

x[0, i, j] ~ normal(a[i, j] * init[i, j] + b[0, i, j], c[i, j])
x[t, i, j] ~ normal(a[i, j] * x[t-1, i, j] + b[t, i, j], c[i, j]), t > 0

Finally, decorator form:

@sfor(init=init, interface=interface, t=T)
def x(previous, t):
    return normal(previous, 1)

is equivalent to:

def fun(previous, t):
    return normal(previous, 1)

x = sfor(fun, init=init, interface=interface, t=T)

In both forms, init and interface must be supplied as keyword arguments.

Each call to fun must return exactly one ir.RV created during that call. The result must depend on previous. Any other RVs created during the call that contribute to the result must have deterministic Ops. The assembled state must have the same interface as init.

The shape of init must match one complete state assembled from fun. For fun(previous, t, i, j), let S be the shape returned by one call to fun. With t=T, i=I, and j=J, init must have shape (I, J, *S), and the result has shape (T, I, J, *S). Equivalently, result.shape == (T,) + init.shape. Note that the output axes appear in function-parameter order; keyword order is ignored.

Each parallel call receives the complete previous state; sfor does not slice it along the parallel axes.

Parameters:
  • fun (Callable[..., ir.RV] | None) – Step function, or None in decorator form. It must have a fixed positional signature with at least two parameters and no defaults, variadic parameters, or keyword-only parameters. The first parameter receives the complete previous state; the second receives the scalar sequential coordinate; any later parameters receive scalar parallel coordinates. No parameter may be named init or interface. The function must satisfy the return, carry-dependence, determinism, shape, and interface requirements above.

  • init (ir.RV) – Keyword-only complete state before the first step. It must already be an RV; it is not coerced. Its shape and interface must match the state assembled by mapping fun over every parallel coordinate.

  • interface (ir.RVInterface) – Required keyword-only interface attached to the generated sequential and parallel coordinate RVs. It need not match init.interface; the operations used by fun determine whether those interfaces can be used together.

  • **sizes (int) – Exactly one positive integer for every coordinate parameter: the sequential parameter and all parallel parameters. Names must match the function parameters. Values determine axis lengths; function-parameter order, not keyword order, determines axis order.

Returns:

result_or_decorator (ir.RV | decorator) – When fun is supplied, an ir.RV containing every state produced by the scan, not including init. If the sequential size is T, result[t] is the state produced at coordinate t and result.shape == (T,) + init.shape. When fun is omitted, a decorator that accepts it and returns such an ir.RV. The result has init.interface.

Raises:
  • TypeError – If fun is not callable or lacks the required signature, init is not an RV, a size is not an integer, or fun does not return exactly one ir.RV.

  • ValueError – If a parameter is named init or interface, the function has no sequential coordinate, sizes are missing, unknown, or nonpositive, the result does not depend on previous, an intermediate Op is random, or the mapped state does not match the shape or interface of init.

Return type:

RV | SForDecorator

Broadcasting combinators#

pangolin.functional.broadcast_off(scalar_fun: Callable[[], RV]) → Callable[[], RV]#
pangolin.functional.broadcast_off(scalar_fun: Callable[[RV], RV]) → Callable[[RV], RV]
pangolin.functional.broadcast_off(scalar_fun: Callable[[RV, RV], RV]) → Callable[[RV, RV], RV]
pangolin.functional.broadcast_off(scalar_fun: Callable[[RV, RV, RV], RV]) → Callable[[RV, RV, RV], RV]
pangolin.functional.broadcast_off(scalar_fun: Callable[[RV, RV, RV, RV], RV]) → Callable[[RV, RV, RV, RV], RV]
pangolin.functional.broadcast_off(scalar_fun: Callable[[RV, RV, RV, RV, RV], RV]) → Callable[[RV, RV, RV, RV, RV], RV]
pangolin.functional.broadcast_off(scalar_fun: Callable[[ir.RV, ir.RV, ir.RV, ir.RV, ir.RV, ir.RV, *Rest], ir.RV]) → Callable[[ir.RV, ir.RV, ir.RV, ir.RV, ir.RV, ir.RV, *Rest], ir.RV]

Require scalar RV inputs when calling a scalar function.

This combinator returns a function that calls scalar_fun with the supplied arguments. RV interfaces are preserved without interpreting them.

Parameters:

scalar_fun (Callable[[...], RV]) – Function accepting scalar RV arguments and returning one scalar RV.

Raises:
  • TypeError – If a supplied argument is not an RV or the underlying function rejects the call.

  • ValueError – If any input RV is not scalar.

Return type:

Callable[[…], RV]

Notes

Only explicitly supplied arguments participate in broadcasting. Each must be an RV; the combinator performs no coercion. Positional and keyword arguments follow identical shape rules, including values supplied to keyword-only parameters or collected by **kwargs.

The combinator does not inspect the function signature or insert default arguments. Omitted defaults are handled normally by Python when scalar_fun is called, just like values captured inside the function. Their shapes do not determine the broadcast shape. Supplying a default value explicitly makes it a broadcast input, like any other supplied argument.

Keyword calls are supported at runtime, but the static overloads describe positional calls only.

Examples

>>> def exp(x):
...     return ir.RV(ir.Exp(), x)
>>> scalar_exp = broadcast_off(exp)
>>> scalar_exp(ir.RV(ir.Constant(2))).shape
()
pangolin.functional.broadcast_simple(scalar_fun: Callable[[], RV]) → Callable[[], RV]#
pangolin.functional.broadcast_simple(scalar_fun: Callable[[RV], RV]) → Callable[[RV], RV]
pangolin.functional.broadcast_simple(scalar_fun: Callable[[RV, RV], RV]) → Callable[[RV, RV], RV]
pangolin.functional.broadcast_simple(scalar_fun: Callable[[RV, RV, RV], RV]) → Callable[[RV, RV, RV], RV]
pangolin.functional.broadcast_simple(scalar_fun: Callable[[RV, RV, RV, RV], RV]) → Callable[[RV, RV, RV, RV], RV]
pangolin.functional.broadcast_simple(scalar_fun: Callable[[RV, RV, RV, RV, RV], RV]) → Callable[[RV, RV, RV, RV, RV], RV]
pangolin.functional.broadcast_simple(scalar_fun: Callable[[ir.RV, ir.RV, ir.RV, ir.RV, ir.RV, ir.RV, *Rest], ir.RV]) → Callable[[ir.RV, ir.RV, ir.RV, ir.RV, ir.RV, ir.RV, *Rest], ir.RV]

Broadcast a scalar function over scalars and equal-shaped arrays.

This combinator returns a function applying scalar_fun elementwise using nested vmap calls. Scalars are broadcast to the common array shape. Tracing preserves input interfaces and the output interface selected by scalar_fun.

Parameters:

scalar_fun (Callable[[...], RV]) – Function accepting scalar RV arguments and returning one scalar RV.

Raises:
  • TypeError – If a supplied argument is not an RV or the underlying function rejects the call.

  • ValueError – If the non-scalar input shapes differ.

Return type:

Callable[[…], RV]

Notes

Only explicitly supplied arguments participate in broadcasting. Each must be an RV; the combinator performs no coercion. Positional and keyword arguments follow identical shape rules, including values supplied to keyword-only parameters or collected by **kwargs.

The combinator does not inspect the function signature or insert default arguments. Omitted defaults are handled normally by Python when scalar_fun is called, just like values captured inside the function. Their shapes do not determine the broadcast shape. Supplying a default value explicitly makes it a broadcast input, like any other supplied argument.

Keyword calls are supported at runtime, but the static overloads describe positional calls only.

Examples

>>> def normal(mu, sigma):
...     return ir.RV(ir.Normal(), mu, sigma)
>>> broadcasted_normal = broadcast_simple(normal)
>>> mu = ir.RV(ir.Constant([0, 1, 2]))
>>> sigma = ir.RV(ir.Constant(1))
>>> broadcasted_normal(mu, sigma).shape
(3,)
pangolin.functional.broadcast_rank(scalar_fun: Callable[[], RV]) → Callable[[], RV]#
pangolin.functional.broadcast_rank(scalar_fun: Callable[[RV], RV]) → Callable[[RV], RV]
pangolin.functional.broadcast_rank(scalar_fun: Callable[[RV, RV], RV]) → Callable[[RV, RV], RV]
pangolin.functional.broadcast_rank(scalar_fun: Callable[[RV, RV, RV], RV]) → Callable[[RV, RV, RV], RV]
pangolin.functional.broadcast_rank(scalar_fun: Callable[[RV, RV, RV, RV], RV]) → Callable[[RV, RV, RV, RV], RV]
pangolin.functional.broadcast_rank(scalar_fun: Callable[[RV, RV, RV, RV, RV], RV]) → Callable[[RV, RV, RV, RV, RV], RV]
pangolin.functional.broadcast_rank(scalar_fun: Callable[[ir.RV, ir.RV, ir.RV, ir.RV, ir.RV, ir.RV, *Rest], ir.RV]) → Callable[[ir.RV, ir.RV, ir.RV, ir.RV, ir.RV, ir.RV, *Rest], ir.RV]

Broadcast a scalar function using leading-rank promotion.

Each input shape must be a suffix of the longest shape. This combinator returns a function applying scalar_fun elementwise using nested vmap calls, broadcasting missing leading axes. Existing singleton axes are not expanded. Tracing preserves input interfaces and the output interface selected by scalar_fun.

Parameters:

scalar_fun (Callable[[...], RV]) – Function accepting scalar RV arguments and returning one scalar RV.

Raises:
  • TypeError – If a supplied argument is not an RV or the underlying function rejects the call.

  • ValueError – If an input shape is not a suffix of the longest shape.

Return type:

Callable[[…], RV]

Notes

Only explicitly supplied arguments participate in broadcasting. Each must be an RV; the combinator performs no coercion. Positional and keyword arguments follow identical shape rules, including values supplied to keyword-only parameters or collected by **kwargs.

The combinator does not inspect the function signature or insert default arguments. Omitted defaults are handled normally by Python when scalar_fun is called, just like values captured inside the function. Their shapes do not determine the broadcast shape. Supplying a default value explicitly makes it a broadcast input, like any other supplied argument.

Keyword calls are supported at runtime, but the static overloads describe positional calls only.

Examples

>>> def add(x, y):
...     return ir.RV(ir.Add(), x, y)
>>> broadcasted_add = broadcast_rank(add)
>>> x = ir.RV(ir.Constant([1, 2, 3]))
>>> y = ir.RV(ir.Constant([[4, 5, 6], [7, 8, 9]]))
>>> broadcasted_add(x, y).shape
(2, 3)
pangolin.functional.broadcast_numpy(scalar_fun: Callable[[], RV]) → Callable[[], RV]#
pangolin.functional.broadcast_numpy(scalar_fun: Callable[[RV], RV]) → Callable[[RV], RV]
pangolin.functional.broadcast_numpy(scalar_fun: Callable[[RV, RV], RV]) → Callable[[RV, RV], RV]
pangolin.functional.broadcast_numpy(scalar_fun: Callable[[RV, RV, RV], RV]) → Callable[[RV, RV, RV], RV]
pangolin.functional.broadcast_numpy(scalar_fun: Callable[[RV, RV, RV, RV], RV]) → Callable[[RV, RV, RV, RV], RV]
pangolin.functional.broadcast_numpy(scalar_fun: Callable[[RV, RV, RV, RV, RV], RV]) → Callable[[RV, RV, RV, RV, RV], RV]
pangolin.functional.broadcast_numpy(scalar_fun: Callable[[ir.RV, ir.RV, ir.RV, ir.RV, ir.RV, ir.RV, *Rest], ir.RV]) → Callable[[ir.RV, ir.RV, ir.RV, ir.RV, ir.RV, ir.RV, *Rest], ir.RV]

Broadcast a scalar function using NumPy’s broadcasting rules.

Input shapes are aligned on the right; missing leading axes and singleton axes may be expanded. This combinator returns a function applying scalar_fun elementwise using nested vmap calls. Tracing preserves input interfaces and the output interface selected by scalar_fun.

Parameters:

scalar_fun (Callable[[...], RV]) – Function accepting scalar RV arguments and returning one scalar RV.

Raises:
  • TypeError – If a supplied argument is not an RV or the underlying function rejects the call.

  • ValueError – If the input shapes cannot be broadcast together.

Return type:

Callable[[…], RV]

Notes

Only explicitly supplied arguments participate in broadcasting. Each must be an RV; the combinator performs no coercion. Positional and keyword arguments follow identical shape rules, including values supplied to keyword-only parameters or collected by **kwargs.

The combinator does not inspect the function signature or insert default arguments. Omitted defaults are handled normally by Python when scalar_fun is called, just like values captured inside the function. Their shapes do not determine the broadcast shape. Supplying a default value explicitly makes it a broadcast input, like any other supplied argument.

Keyword calls are supported at runtime, but the static overloads describe positional calls only.

Examples

>>> def add(x, y):
...     return ir.RV(ir.Add(), x, y)
>>> broadcasted_add = broadcast_numpy(add)
>>> x = ir.RV(ir.Constant([[1], [2]]))
>>> y = ir.RV(ir.Constant([3, 4, 5]))
>>> broadcasted_add(x, y).shape
(2, 3)

Bijected distributions#

class pangolin.functional.Transform(forward, inverse, log_det_jac, *, sign=None)#

Package an invertible pair of RV functions with distribution combinators.

forward(x) computes y, inverse(y) reconstructs x, and log_det_jac(x, y) computes the scalar forward log absolute Jacobian determinant. Thus, a Transform contains two inverse value functions plus the density correction that relates them. Transform.__call__ and Transform.apply_and_invert are combinators that accept a function constructing x and return functions based on one random RV with an ir.Bijected Op.

The three functions are traced when the transformed function is called. Their deterministic graphs are compiled into an ir.Bijector; RVs they capture become bijector parameters. The forward and inverse functions must capture the same RV identities, while log_det_jac may use any subset of them.

Optional sign() declares a continuous, strictly monotone scalar bijection, returning +1 for increasing or -1 for decreasing. It is traced at application time and may capture any subset of the forward parameters; its Op accepts all parameters in the same order. It may not depend on the value being transformed or introduce additional captured RVs.

Parameters:
  • forward (Callable[[ir.RV], ir.RV]) – Unary function mapping a base RV to its transformed value.

  • inverse (Callable[[ir.RV], ir.RV]) – Unary function mapping the transformed value back to the base value.

  • log_det_jac (Callable[[ir.RV, ir.RV], ir.RV]) – Binary function computing log(abs(det(J_forward(x)))) from x and y.

  • sign (Callable[[], ir.RV] | None) – Optional zero-argument function returning a deterministic scalar RV, +1 for an increasing scalar bijection or -1 for a decreasing one.

Examples

Construct an exponential Transform and apply it to a normal distribution function:

>>> exp_transform = Transform(
...     lambda x: ir.RV(ir.Exp(), x),
...     lambda y: ir.RV(ir.Log(), y),
...     lambda x, y: ir.RV(ir.Log(), y),
... )
>>> def normal(mean, scale):
...     return ir.RV(ir.Normal(), mean, scale)
>>> mean = ir.RV(ir.Constant(0))
>>> scale = ir.RV(ir.Constant(1))
>>> result = exp_transform(normal)(mean, scale)
>>> result.op
Bijected(Normal(), Bijector(Exp(), Log(), Composite(2, [Log()], [[1]])))
>>> result.parents == (mean, scale)
True

The forward and inverse functions determine the transformed and reconstructed interfaces:

>>> forward_interface = ir.RVInterface()
>>> inverse_interface = ir.RVInterface()
>>> special_exp = Transform(
...     lambda x: ir.RV(ir.Exp(), x, interface=forward_interface),
...     lambda y: ir.RV(ir.Log(), y, interface=inverse_interface),
...     lambda x, y: ir.RV(ir.Log(), y),
... )
>>> def special_normal(mean, scale):
...     return ir.RV(ir.Normal(), mean, scale)
>>> special_mean = ir.RV(ir.Constant(0))
>>> special_scale = ir.RV(ir.Constant(1))
>>> transformed, reconstructed = special_exp.apply_and_invert(special_normal)(
...     special_mean, special_scale
... )
>>> transformed.interface is forward_interface
True
>>> reconstructed.interface is inverse_interface
True

The sign is supplied by a graph-building callback too:

>>> increasing_exp = Transform(
...     exp_transform.forward, exp_transform.inverse, exp_transform.log_det_jac,
...     sign=lambda: ir.RV(ir.Constant(1)),
... )
>>> increasing_exp(normal)(mean, scale).op.bijector.sign
Constant(1)
__call__(fun, /)#

Apply this Transform combinator to a continuous distribution function.

The returned function preserves fun’s complete call signature and passes all arguments through unchanged. The result carries the interface selected by Transform.forward.

Parameters:

fun (Callable[[P], RV]) – Function that creates one continuous random RV accepted by forward.

Returns:

transformed_fun – Function with the same signature as fun that creates the transformed RV.

Return type:

Callable[[P], RV]

apply_and_invert(fun, /)#

Apply this Transform combinator and also reconstruct the base value.

Like Transform.__call__, this method is a combinator: it accepts a distribution-producing function and returns another function.

The reconstructed base is deterministic and uses the compiled inverse operation; it is not a second draw from fun.

Parameters:

fun (Callable[[P], RV]) – Function that creates one continuous random RV accepted by forward.

Returns:

transformed_and_base_fun – Function with the same signature as fun that returns (y, x).

Return type:

Callable[[P], tuple[RV, RV]]

property reverse: Transform#

Reverse the value functions, negate the LDJ, and preserve the sign.

__repr__()#

Return a constructor-shaped representation of the Transform.

Return type:

str

pangolin.functional.compose_transforms(transforms, log_det_direction='forward')#

Compose Transform combinators in left-to-right application order.

Monotonic signs are multiplied if every Transform supplies one; otherwise the result’s sign is absent. The empty composition has sign +1.

Parameters:
  • transforms (Sequence[Transform]) – Transforms to apply in sequence; the first item is applied first.

  • log_det_direction (Literal['forward', 'inverse']) – Whether to reconstruct intermediate values from x or from y while computing the combined log determinant.

Returns:

transform – One Transform equivalent to applying every input Transform in order.

Raises:
  • TypeError – If an item is not a Transform.

  • ValueError – If log_det_direction is not "forward" or "inverse".

Return type:

Transform

The standard transform combinators are documented in pangolin.functional.tforms.

Backend-independent unconstraining#

pangolin.functional.unconstrain(vars, given, *, transform_for=<function transform_for>)#

Rewrite an inference problem with unconstrained latent RVs.

The inference problem is the joint ancestor graph of vars and given. The graph is rebuilt parent-first without modifying the input graph. Deterministic nodes and random nodes appearing as leaves of given retain their Ops. For each other random node, transform_for(op, parents) selects a constrained-to-unconstrained Transform using its rewritten parents. None leaves the node unchanged; otherwise apply_transform creates unconstrained randomness and a deterministic reconstruction of the original value. Shared nodes remain shared, and the two input PyTree structures are preserved.

Parameters:
  • vars (PyTree[RV]) – PyTree of RVs whose joint distribution is of interest.

  • given (PyTree[RV]) – PyTree of observed RVs; these exact nodes are not passed to the selector.

  • transform_for (Callable[[Op, tuple[RV, ...]], Transform | None]) – Function accepting an Op and its parent RVs and returning a Transform or None. The default is pangolin.functional.transform_for. A custom selector may delegate an Op to the default selector or implement its own handling of composed Ops. Delegating a composed Op uses the default choices throughout that Op.

Returns:

  • new_vars – Rewritten vars with the same PyTree structure and conditional distribution.

  • new_given – Rewritten given with the same PyTree structure. Observed random nodes retain their original Ops while receiving reconstructed latent parents.

Raises:
  • TypeError – If either input has a non-RV leaf or the selector returns something other than a Transform or None.

  • NotImplementedError – If the default selector encounters a discrete or unsupported continuous Op.

  • Exception – Exceptions from the selector or transform construction are propagated.

Return type:

tuple[PyTree[RV], PyTree[RV]]

Notes

A supplied Transform must be a valid bijection from the distribution’s domain onto unconstrained coordinates, with the correct log-Jacobian. It may change the coordinate shape, but its inverse must reconstruct the original shape. None preserves the distribution without asserting that its domain is unconstrained.

Examples

Consider a model with a positive latent scale and an observed Normal value:

>>> from pangolin import functional, ir
>>> rate = ir.RV(ir.Constant(1.0))
>>> location = ir.RV(ir.Constant(0.0))
>>> scale = ir.RV(ir.Exponential(), rate)
>>> observation = ir.RV(ir.Normal(), location, scale)
>>> ir.print_upstream(observation, {"scale": scale, "observation": observation})
shape | statement
----- | ---------
()    | a = 0.
()    | b = 1.
()    | scale ~ exponential(b)
()    | observation ~ normal(a, scale)

Rewrite scale with observation given, then display both returned values:

>>> new_scale, new_observation = functional.unconstrain(scale, observation)
>>> ir.print_upstream(new_observation, {"scale": new_scale, "observation": new_observation})
shape | statement
----- | ---------
()    | a = 0.
()    | b = 1.
()    | c ~ bijected(exponential, bijector(log, exp, composite(2, [log, -1, mul], [[0], [], [3, 2]]), sign=1))(b)
()    | scale = exp(c)
()    | observation ~ normal(a, scale)

The rewritten scale and observation occupy the same constrained spaces as before. The random scale node has become a deterministic reconstruction from the unconstrained random node c, while the given observation retains its original Normal Op.

pangolin.functional.transform_for(op, parents, /)#

Return Pangolin’s default constrained-to-unconstrained Transform.

The primitive Op policy is:

  • Normal, NormalPrec, Cauchy, StudentT, and MultiNormal are unchanged.

  • Exponential, Gamma, and Lognormal use tforms.log.

  • Beta uses tforms.logit.

  • Uniform uses tforms.scaled_logit with its lower and upper parents.

  • Dirichlet uses tforms.softmax_centered_ilr.

  • Wishart uses tforms.unconstrain_spd.

  • Bernoulli, BernoulliLogit, Binomial, Poisson, BetaBinomial, Categorical, and Multinomial raise NotImplementedError because they are discrete.

Container Ops recursively use the same policy:

  • Composite uses the policy for its final Op.

  • VMap applies the base transform independently at each mapped position.

  • Scan applies the base transform at each step using the previous constrained carry. If inversion depends on that carry, a deterministic Scan reconstructs the trajectory in order.

  • For Bijected, its stored bijection T maps a base value x to the represented value y. Unconstraining first recovers x = T.inverse(y), then unconstrains x using the policy for the base Op. If the base Op is already unconstrained, the transform is simply T.inverse.

  • Truncated with two bounds uses a scaled logit. With one bound, it unconstrains the base and takes the log of the positive distance from the transformed bound, using the base transform’s sign. With neither bound, it uses the base transform unchanged.

These rules recurse through arbitrary nested combinations of Composite, VMap, Scan, Bijected, and Truncated.

An unsupported continuous Op raises NotImplementedError, and a deterministic Op raises ValueError.

Parameters:
  • op (Op) – Random Op whose distribution is to be unconstrained.

  • parents (tuple[RV, ...]) – RVs supplying the Op’s parameters, in their usual order.

Returns:

Transform or None – A Transform mapping the distribution to unconstrained coordinates, or None if it is already unconstrained. The transform may capture parent RVs.

Return type:

Transform | None

Notes

The helpers recursively call this default selector. Passing a custom selector to unconstrain does not change their recursive choices.