pangolin.interface.Interface.loop

Contents

pangolin.interface.Interface.loop#

Interface.loop(fun, /, **sizes)[source]#

Build an RV over named vectorized and sequential axes, in function-parameter order.

Sequential loops support four calling styles:

  1. Decorator with a supplied axis size and initializer:

    >>> from pangolin import interface as pi
    >>> # x[i, 0] ~ normal(0, 1),          0 ≤ i < 3
    >>> # x[i, t] ~ normal(x[i, t-1], 1),  0 ≤ i < 3, 0 < t < 5
    >>> @pi.loop
    ... def x(prev, i=3, t=pi.seq(5, 0.0)):
    ...     return pi.normal(prev[i, t-1], 1)
    
  2. Direct call with a supplied initializer:

    >>> # x[i, 0] ~ normal(0, 1),          0 ≤ i < 3
    >>> # x[i, t] ~ normal(x[i, t-1], 1),  0 ≤ i < 3, 0 < t < 5
    >>> def model(prev, i, t):
    ...     return pi.normal(prev[i, t-1], 1)
    >>> x = pi.loop(model, i=3, t=pi.seq(5, 0.0))
    
  3. Decorator with an initialization branch:

    >>> # a[i] ~ normal(i, 1),             0 ≤ i < 3
    >>> # x[i, 0] ~ normal(a[i], 1),       0 ≤ i < 3
    >>> # x[i, t] ~ normal(x[i, t-1], 1),  0 ≤ i < 3, 0 < t < 5
    >>> @pi.loop
    ... def x(prev, i=3, t=pi.seq(5)):
    ...     if t is None:
    ...         return pi.normal(i, 1)
    ...     return pi.normal(prev[i, t-1], 1)
    
  4. Direct call with an initialization branch:

    >>> # a[i] ~ normal(i, 1),             0 ≤ i < 3
    >>> # x[i, 0] ~ normal(a[i], 1),       0 ≤ i < 3
    >>> # x[i, t] ~ normal(x[i, t-1], 1),  0 ≤ i < 3, 0 < t < 5
    >>> def model(prev, i, t):
    ...     if t is None:
    ...         return pi.normal(i, 1)
    ...     return pi.normal(prev[i, t-1], 1)
    >>> x = pi.loop(model, i=3, t=pi.seq(5))
    

All axis specifications must come from parameter defaults or all from explicit call arguments. For vectorized axes, use an integer size instead of seq(...). Each access to prev must select one sequential axis using coordinate - 1. Preceding indices must be the unchanged coordinates; remaining indices index the previous state normally. (Omit prev when no axis is sequential.)

Return type:

RV

Parameters:
  • fun (callable) – Function taking scalar coordinates, preceded by prev when any axis is sequential. Returns one RV or numeric value.

  • **sizes (int | list | tuple) – Positive integer for a vectorized axis; seq(T, initializer) for a sequential axis. An initializer is an RV or numeric value. seq(T) or seq(T, None) calls fun with that coordinate set to None and the others supplied as RVs for initialization; prev cannot be read in this call. Equivalent lists and tuples are also accepted. Initial states are excluded from the output.

Returns:

output (RV) – The output RV.

Notes

fun is traced once per required initialization branch and once for the body, not per iteration. In prev[...], preceding selectors must be the exact coordinate RVs in function-parameter order; the first differing selector must be coordinate - 1 for a sequential coordinate. Remaining selectors index its previous state normally. Initialization cannot read prev. In a sequential step, no newly created random RV may contribute to the result except the returned RV itself; initialization has no such restriction.

Coordinates and coerced values use this interface. Existing RVs retain their interfaces. Body results and initializer values are coerced to RVs.

Examples

Vectorized axes, using a direct call:

>>> from pangolin import interface as pi
>>> # x[i, j] = 10 * i + j,  0 ≤ i < 2, 0 ≤ j < 3
>>> x = pi.loop(lambda i, j: 10 * i + j, i=2, j=3)
>>> x.shape
(2, 3)
>>> x.op
VMap(VMap(Add(), [None, 0], 3), [0, None], 2)

The same calculation declared with parameter defaults used to indicate axis sizes:

>>> # y[i, j] = 10 * i + j,  0 ≤ i < 2, 0 ≤ j < 3
>>> @pi.loop
... def y(i=2, j=3):
...     return 10 * i + j
>>> y.shape
(2, 3)
>>> ir.rv_equal(x, y)
True

One sequential axis, initialized at zero:

>>> # x[0] ~ normal(0, 1)
>>> # x[t] ~ normal(x[t-1], 1),  0 < t < 3
>>> @pi.loop
... def x(prev, t=pi.seq(3, 0.0)):
...     return pi.normal(prev[t-1], 1)
>>> x.shape
(3,)
>>> x.op
Scan(Composite(1, [Constant(1), Normal()], [[], [0, 1]]), 3, [])

The same model using a None branch for initialization:

>>> # x[0] ~ normal(0, 1)
>>> # x[t] ~ normal(x[t-1], 1),  0 < t < 3
>>> @pi.loop
... def x(prev, t=pi.seq(3)):
...     if t is None:
...         return 0.0
...     return pi.normal(prev[t-1], 1)
>>> x.shape
(3,)

Add a vectorized axis for independent trajectories:

>>> # x[i, 0] ~ normal(0, 1),          0 ≤ i < 2
>>> # x[i, t] ~ normal(x[i, t-1], 1),  0 ≤ i < 2, 0 < t < 3
>>> @pi.loop
... def x(prev, i=2, t=pi.seq(3)):
...     if t is None:
...         return 0.0
...     return pi.normal(prev[i, t-1], 1)
>>> x.shape
(2, 3)

Initialization can depend on the other coordinates inside the function:

>>> # a[i] ~ normal(i, 1),             0 ≤ i < 2
>>> # x[i, 0] ~ normal(a[i], 1),       0 ≤ i < 2
>>> # x[i, t] ~ normal(x[i, t-1], 1),  0 ≤ i < 2, 0 < t < 3
>>> @pi.loop
... def x(prev, i=2, t=pi.seq(3)):
...     if t is None:
...         return pi.normal(i, 1)
...     return pi.normal(prev[i, t-1], 1)
>>> x.shape
(2, 3)
>>> pi.print_upstream(x, {"x": x})
shape  | statement
------ | ---------
(2,)   | a = [0 1]
()     | b = 1
(2,)   | c ~ vmap(normal, [0, None], 2)(a, b)
(2, 3) | x ~ vmap(scan(composite(1, [1, normal], [[], [0, 1]]), 3, []), [0], 2)(c)

Two sequential axes, each with its own initialization branch:

>>> # x[0, 0] ~ normal(1, 1)
>>> # x[0, s] ~ normal(x[0, s-1], 1),              0 < s < 3
>>> # x[t, 0] ~ normal(x[t-1, 0] + 1, 1),          0 < t < 2
>>> # x[t, s] ~ normal(x[t-1, s] + x[t, s-1], 1),  0 < t < 2, 0 < s < 3
>>> @pi.loop
... def x(prev, t=pi.seq(2), s=pi.seq(3)):
...     if t is None:
...         return 0.0
...     elif s is None:
...         return 1.0
...     return pi.normal(prev[t-1, s] + prev[t, s-1], 1)
>>> x.shape
(2, 3)

Nest loops to give each candidate its own drift, volatility, and random walk, with shared population parameters:

>>> N, T = 3, 4
>>> # drift_mean ~ normal(0, 0.2); drift_sd ~ lognormal(-2, 0.5)
>>> # log_volatility_mean ~ normal(-2, 0.5)
>>> drift_mean = pi.normal(0, 0.2)
>>> drift_sd = pi.lognormal(-2, 0.5)
>>> log_volatility_mean = pi.normal(-2, 0.5)
>>> # For 0 ≤ i < N:
>>> # drift[i] ~ normal(drift_mean, drift_sd)
>>> # volatility[i] ~ lognormal(log_volatility_mean, 0.3)
>>> # a[i] ~ normal(0, 1)
>>> # popularity[i, 0] ~ normal(a[i] + drift[i], volatility[i])
>>> # popularity[i, t] ~ normal(popularity[i, t-1] + drift[i], volatility[i]),  0 < t < T
>>> @pi.loop
... def popularity(i=N):
...     drift = pi.normal(drift_mean, drift_sd)
...     volatility = pi.lognormal(log_volatility_mean, 0.3)
...     @pi.loop
...     def trajectory(prev, t=pi.seq(T)):
...         if t is None:
...             return pi.normal(0, 1)
...         return pi.normal(prev[t-1] + drift, volatility)
...     return trajectory
>>> popularity.shape
(3, 4)

Use separate loops to keep drift and volatility directly accessible:

>>> # For 0 ≤ i < N:
>>> # drift[i] ~ normal(drift_mean, drift_sd)
>>> @pi.loop
... def drift(i=N):
...     return pi.normal(drift_mean, drift_sd)
>>> # For 0 ≤ i < N:
>>> # volatility[i] ~ lognormal(log_volatility_mean, 0.3)
>>> @pi.loop
... def volatility(i=N):
...     return pi.lognormal(log_volatility_mean, 0.3)
>>> # For 0 ≤ i < N:
>>> # a[i] ~ normal(0, 1)
>>> # popularity[i, 0] ~ normal(a[i] + drift[i], volatility[i])
>>> # popularity[i, t] ~ normal(popularity[i, t-1] + drift[i], volatility[i]),  0 < t < T
>>> @pi.loop
... def popularity(prev, i=N, t=pi.seq(T)):
...     if t is None:
...         return pi.normal(0, 1)
...     return pi.normal(prev[i, t-1] + drift[i], volatility[i])
>>> drift.shape, volatility.shape, popularity.shape
((3,), (3,), (3, 4))

Put time before candidates to let each update depend on the previous population. A sequential axis carries the complete array of later axes:

>>> # For 0 ≤ i < N:
>>> # a[i] ~ normal(0, 1)
>>> # popularity[0, i] ~ normal(0.9 * a[i] + 0.1 * mean(a), 1)
>>> # m[t] = sum(popularity[t, j] for j in range(N)) / N,                     0 ≤ t < T
>>> # popularity[t, i] ~ normal(0.9 * popularity[t-1, i] + 0.1 * m[t-1], 1),  0 < t < T
>>> @pi.loop
... def popularity(prev, t=pi.seq(T), i=N):
...     if t is None:
...         return pi.normal(0, 1)
...     population_mean = pi.sum(prev[t-1, :], 0) / N
...     return pi.normal(
...         0.9 * prev[t-1, i] + 0.1 * population_mean,
...         1,
...     )
>>> popularity.shape
(4, 3)