AI-generated. An AI assistant drafted this page, and no maintainer has reviewed it yet. Please report errors on the issue tracker.
Functions on values and distributions¶
A ProbPipe-native function is a Python function decorated with @function.
We write it for one value of each input, and ProbPipe applies it to distributions and to batches of inputs as well.
This chapter shows what each kind of call returns, how to set the number of draws a call uses, and the operations pushforward and expectation.
Read it when you want to push uncertainty through a computation of your own, such as a forecast or a decision rule.
# On Google Colab, install ProbPipe; elsewhere this cell does nothing.
try:
import google.colab # noqa: F401
IN_COLAB = True
except ImportError:
IN_COLAB = False
if IN_COLAB:
# Colab's preinstalled PyMC 5 does not work with ArviZ 1.x, so the install upgrades PyMC.
%pip install --quiet "probpipe-core[pymc] @ git+https://github.com/TARPS-group/prob-pipe.git@main"
import jax
import jax.numpy as jnp
from probpipe import (
EmpiricalDistribution,
Normal,
NumericArrayBatch,
expectation,
function,
mean,
pushforward,
config,
quantile,
variance,
workflow_run,
)
A function of values¶
Our running example is a savings account.
future_value computes the balance after years years of a deposit of principal that grows at the annual rate.
The @function decorator makes it a ProbPipe-native function, which is an instance of Function:
@function
def future_value(principal: float, rate: jax.Array, years: float) -> jax.Array:
return principal * (1.0 + rate) ** years
balance = future_value(1000.0, 0.05, 10.0)
print("the function:", future_value)
print("balance of 1000 after 10 years at 5%:", balance.raw)
the function: future_value(principal, rate, years) balance of 1000 after 10 years at 5%: 1628.8947
print shows the function's notation, which is its label followed by its parameters.
Called with numbers, the function evaluates its body once.
It returns the balance as a NumericArray, and its .raw is the underlying JAX array.
The type hints state what each parameter accepts and what the body returns, and ProbPipe reads them when it decides how to apply the function.
Calling a function on a distribution¶
The rate of return is uncertain. Suppose it follows a normal distribution with mean 5% and standard deviation 2%. We pass that distribution in place of the number:
rate = Normal("rate", 0.05, 0.02)
with workflow_run(seed=0):
balance = future_value(1000.0, rate, 10.0)
print("result:", balance)
print("mean balance after 10 years:", mean(balance).raw)
print("90% interval of the balance:", quantile(balance, jnp.array([0.05, 0.95])).raw)
print("route:", balance.provenance.metadata["route"])
result: future_value(1000.0, rate ~ Normal, 10.0) mean balance after 10 years: 1637.634 90% interval of the balance: [1158.4106 2165.6436] route: sampling_lift
The result is the distribution of the balance.
It displays as future_value(1000.0, rate ~ Normal, 10.0), which is the function applied to a draw of rate from the distribution labeled Normal.
ProbPipe lifts the function to the distribution: it draws 256 rates, evaluates the body at each draw, and returns an EmpiricalDistribution over the 256 balances.
The result is a distribution like any other, so mean and quantile apply to it.
Its provenance records the route sampling_lift and that the result is approximate.
The workflow_run block seeds the draws, so running the cell again reproduces the result.
More draws give a more accurate result.
using(max_evaluations=...) returns a copy of the function that uses another number of draws, and config.sampling.max_evaluations sets the number for every function and operation that sets none of its own:
with workflow_run(seed=0):
balance_4000 = future_value.using(max_evaluations=4000)(1000.0, rate, 10.0)
print("draws set by using:", balance_4000.num_atoms)
config.sampling.max_evaluations = 1000
with workflow_run(seed=0):
balance_1000 = future_value(1000.0, rate, 10.0)
print("draws with the default set to 1000:", balance_1000.num_atoms)
config.sampling.reset()
draws set by using: 4000 draws with the default set to 1000: 1000
An EmpiricalDistribution is a distribution over a finite set of atoms, so a function can be evaluated at every atom instead of at random draws.
Here the rate takes one of three values with equal probability:
three_rates = EmpiricalDistribution(jnp.array([0.02, 0.05, 0.08]), output_name="rate")
balance_3 = future_value(1000.0, three_rates, 10.0)
print("balance at each rate:", balance_3.atoms.raw)
print("route:", balance_3.provenance.metadata["route"])
print("exact:", balance_3.provenance.metadata["exact"])
balance at each rate: [1218.9941 1628.8938 2158.9258] route: empirical_enumeration exact: True
The route empirical_enumeration evaluates the body once per atom and keeps each atom's weight, so the result is the exact distribution of the balance.
It needs no seed, since it draws nothing.
ProbPipe enumerates the atoms when their number is at most max_evaluations, 256 by default, and it samples from them otherwise.
Values and distributions together¶
A call can pass a value to some parameters and a distribution to others, as the calls above did.
Each distribution argument is lifted, and each value is passed to every evaluation unchanged.
When two arguments are distributions, their draws are dependent if the arguments come from one distribution and independent otherwise.
gap makes the difference visible:
@function
def gap(a: jax.Array, b: jax.Array) -> jax.Array:
return a - b
other_rate = Normal("other_rate", 0.05, 0.02)
with workflow_run(seed=0):
same = gap(rate, rate)
independent = gap(rate, other_rate)
print("variance of rate - rate:", variance(same).raw)
print("variance of rate - other_rate:", variance(independent).raw)
variance of rate - rate: 0.0 variance of rate - other_rate: 0.00078610674
Both arguments of gap(rate, rate) come from one distribution, so each evaluation reads them from the same draw, and the difference is always 0.
The arguments of gap(rate, other_rate) come from two distributions, which are drawn independently, so the variance of the difference is near $2 \times 0.02^2 = 0.0008$.
The same rule keeps the dependence between two fields of one joint distribution, such as a posterior, and Joint models and conditional distributions describes those fields.
A copy that with_label returns is the same distribution under a new label, so gap(rate, rate.with_label("r")) also reads both arguments from one draw.
To draw two independent values, we construct the distribution twice, as other_rate does.
ProbPipe passes the distribution itself to a parameter whose type hint is Distribution, so the body can call operations on it.
horizons = NumericArrayBatch(jnp.array([5.0, 10.0, 20.0]), "horizon", label="years")
print("levels of the batch:", dict(zip(horizons.level_names, horizons.batch_shape)))
print("the horizons:", horizons.raw)
print("the second horizon:", horizons[1].raw)
levels of the batch: {'horizon': 3}
the horizons: [ 5. 10. 20.]
the second horizon: 10.0
A function called on a batch evaluates its body at each element and returns a batch of the results on the same level:
balances = future_value(1000.0, 0.05, horizons)
print("result:", type(balances).__name__)
print("balance at 5%, by horizon:", balances.raw)
result: NumericArrayBatch balance at 5%, by horizon: [1276.2812 1628.8938 2653.2952]
Two batches on different levels form a grid of every combination, whereas two batches on the same level are paired element by element.
Within one level, sizes follow NumPy's broadcasting rule, so a batch of size one on a level is paired with every element of the other batch.
A batch of two rates on the level scenario therefore gives a 2 × 3 grid of balances:
rates = NumericArrayBatch(jnp.array([0.03, 0.05]), "scenario", label="rate")
grid = future_value(1000.0, rates, horizons)
print("levels of the grid:", dict(zip(grid.level_names, grid.batch_shape)))
print("balance by scenario (rows) and horizon (columns):")
print(grid.raw)
levels of the grid: {'scenario': 2, 'horizon': 3}
balance by scenario (rows) and horizon (columns):
[[1159.2738 1343.916 1806.1102]
[1276.2812 1628.8938 2653.2952]]
A batch and a distribution can be passed in one call. The result is a batch of distributions, one per horizon, and the operations applied to it return a batch of results:
with workflow_run(seed=1):
balance_by_horizon = future_value(1000.0, rate, horizons)
print("result:", type(balance_by_horizon).__name__)
print("mean balance by horizon:", mean(balance_by_horizon).raw)
print("distribution at the first horizon:", balance_by_horizon[0].label)
result: DistributionBatch mean balance by horizon: [1286.059 1678.1405 2964.3757] distribution at the first horizon: future_value[horizon=0]
Indexing the batch by position returns the distribution of one element, labeled by its position on the level. Each element is computed from its own draws of the rate.
A function can also return a batch, such as the balance at the end of each of ten years.
Called on the distribution of the rate, it returns the distribution of the whole path of balances, and each draw is one batch on the level year:
@function
def balance_path(principal: float, rate: jax.Array) -> NumericArrayBatch:
years = jnp.arange(1.0, 11.0)
return NumericArrayBatch(principal * (1.0 + rate) ** years, "year", label="balance")
with workflow_run(seed=0):
paths = balance_path(1000.0, rate)
path_means = mean(paths)
print("levels of the atoms:", dict(zip(paths.atoms.level_names, paths.atoms.batch_shape)))
print("levels of the mean:", dict(zip(path_means.level_names, path_means.batch_shape)))
print("mean balance after years 1, 5, and 10:", path_means.raw[jnp.array([0, 4, 9])])
levels of the atoms: {'balance_path': 256, 'year': 10}
levels of the mean: {'year': 10}
mean balance after years 1, 5, and 10: [1048.9791 1274.3679 1637.634 ]
The atoms are 256 paths of 10 balances, and their first level is named balance_path after the function's output.
The mean of a distribution of batches is taken element by element, so it is a batch on the level year.
A later function called on paths receives each path as its raw array, unless its parameter is annotated with a batch class, such as NumericArrayBatch:
@function
def last_year_gain(path: jax.Array) -> jax.Array:
return path[-1] - path[-2]
with workflow_run(seed=1):
gains = last_year_gain(paths)
print("mean gain in the tenth year:", mean(gains).raw)
mean gain in the tenth year: 81.15051
The body of last_year_gain indexes the raw array of each path, so it is plain JAX code.
Several outputs as a record¶
A function that computes several quantities returns them as a dictionary, with the return type dict[str, jax.Array].
ProbPipe returns the dictionary as a record whose fields are the dictionary's keys:
@function
def growth(principal: float, rate: jax.Array, years: float) -> dict[str, jax.Array]:
balance = principal * (1.0 + rate) ** years
return {"balance": balance, "gain": balance - principal}
at_5_percent = growth(1000.0, 0.05, 10.0)
print("result:", repr(at_5_percent))
print("gain at 5%:", at_5_percent["gain"].raw)
result: NumericRecord('growth(1000.0, 0.05, 10.0)')
balance 1628.8947
gain 628.89465
gain at 5%: 628.89465
Lifted to the distribution of the rate, the function returns a joint distribution of the two fields, and indexing it by a field name gives that field's distribution:
with workflow_run(seed=0):
outcome = growth(1000.0, rate, 10.0)
print("result:", outcome)
print("mean gain after 10 years:", mean(outcome["gain"]).raw)
result: growth(1000.0, rate ~ Normal, 10.0) mean gain after 10 years: 637.6341
Both fields of each atom come from the same draw of the rate, so their dependence is kept.
A function's result is labeled by the function's name by default.
The output_label argument of @function sets another label, which the result of every call takes, so the result carries the name of the quantity it holds:
@function(output_label="savings")
def savings_after(principal: float, rate: jax.Array, years: float) -> jax.Array:
return principal * (1.0 + rate) ** years
with workflow_run(seed=0):
savings = savings_after(1000.0, rate, 10.0)
print("the function:", repr(savings_after))
print("label of the result:", savings.label)
the function: Function('savings_after', parameters=('principal', 'rate', 'years'), output_label='savings')
label of the result: savings
pushforward, expectation, and check¶
The operation pushforward(d, f) returns the distribution of f(X) for X drawn from the distribution d.
It takes the distribution first, and the function receives one draw of d at a time, even at a parameter annotated Distribution, to which the direct call f(d) passes the whole distribution.
A function of several parameters takes the others by name in fixed_args, so that each draw binds the one parameter left open:
with workflow_run(seed=0):
balance = pushforward(rate, future_value, fixed_args={"principal": 1000.0, "years": 10.0})
prov_meta = balance.provenance.metadata
print("mean balance after 10 years:", mean(balance).raw)
print(f"provenance: route={prov_meta['route']}, method={prov_meta['method']}")
mean balance after 10 years: 1647.6038 provenance: route=evaluation_rules, method=sampling_lift
pushforward selects an evaluation rule as the direct call does, here the sampling lift.
Each fixed argument is a constant, and pushforward refuses a distribution or a batch in fixed_args.
Its mean differs a little from the first section's, since a workflow derives each call's draws from the seed and the call, and the two calls differ.
The operation expectation(d, f) computes the expectation of f(X) for X drawn from d, which is mean(pushforward(d, f)).
The integrand f receives one event of d at a time.
The probability of an event is the expectation of its indicator, so the probability that the balance doubles in 10 years is:
def doubles(balance: jax.Array) -> jax.Array:
return (balance >= 2000.0).astype(jnp.float32)
with workflow_run(seed=2):
balance = future_value.using(max_evaluations=4000)(1000.0, rate, 10.0)
probability = expectation(balance, doubles)
print("probability that the balance doubles in 10 years:", probability.raw)
print("route:", probability.provenance.metadata["route"])
probability that the balance doubles in 10 years: 0.13125001 route: closed_form
The balance is an empirical distribution, so expectation computes the exact expectation over its 4,000 atoms, and the route closed_form records that.
The balance doubles when the rate is at least $2^{1/10} - 1 \approx 7.2\%$, which has probability 0.14 under the normal distribution of the rate.
expectation also accepts a distribution with no closed-form expectation, such as rate itself, and it then takes the route pushforward_mean, which builds the pushforward from draws and takes its mean.
Every ProbPipe-native function has a check method, which reports how a call would be computed without running it:
report = future_value.check(1000.0, rate, 10.0)
print("selected rule:", report.selected.method_name)
print("exact:", report.selected.exact)
print("lifted parameters:", report.lifted)
report = future_value.check(1000.0, three_rates, 10.0)
print("selected rule for three rates:", report.selected.method_name)
selected rule: sampling_lift
exact: False
lifted parameters: ('rate',)
selected rule for three rates: empirical_enumeration
The call on rate would take the sampling lift over the parameter rate, which is approximate, and the call on the three rates would enumerate their atoms.
How a result was computed explains routes, options, and provenance for every operation.
See also¶
- Functions:
Function,function, andCallReport. - Operations:
pushforward,expectation, and the moments such asmean. - Values and records:
NumericArrayBatchand the other batches. - Workflows and reproducibility:
workflow_runandconfig.sampling. - The chapters Terms, Values and records, Distributions, Joint models and conditional distributions, and How a result was computed.
- Tutorial 2 applies a function to a prior and a posterior, and tutorial 4 forecasts with a lifted function and compares harvest scenarios as a batch.