Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/temporary-branch.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Added `Simulation.temporary_branch`, a context manager that gives a new branch for one `with` block and removes it from `branches` when the block ends or raises; a read-only simulation never keeps it.
4 changes: 4 additions & 0 deletions docs/python_api/simulations.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ keeps values it does not hold yet.
calculation raises `ReadOnlySimulationError` instead.
- `get_branch` with a new name returns a branch that is not kept in `branches`
and is not read-only itself.
- `temporary_branch` gives a new branch for each `with` block and never keeps
it in `branches`. As on any simulation, it refuses the simulation's own branch
name and the name of a branch it holds (one registered before
`make_read_only`).

The method's docstring lists what is not detected.

Expand Down
28 changes: 28 additions & 0 deletions docs/usage/branches.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,34 @@ the branch is created does not reach the branch, and what the branch stores
does not reach the parent. A branch of a branch reads its own values first,
then its parent's, then those of the simulation at the root.

## Temporary branches

A formula that needs a branch only while it calculates, and should leave
nothing behind, uses `temporary_branch`:

```python
with simulation.temporary_branch("raised_earnings") as branch:
branch.set_input("employment_income", 2026, raised_earnings)
raised_net_income = branch.calculate("household_net_income", 2026)
```

The branch is made by `get_branch`, so it starts with everything described
above. The simulation holds it in `branches` only while the block runs: when
the block ends, normally or by raising, the branch is removed, unless the block
already removed it or put another branch under its name. A read-only
simulation (see `make_read_only`) never keeps it, so each block gets a new
branch and there is nothing to remove.

Without `clone_system=True` the branch shares the simulation's tax-benefit
system, so a change to the system or its parameters made through the branch
also changes the simulation, and stays after the block. Use
`clone_system=True` for such changes, as described under "Dropping calculated
values" below.

A name the simulation already holds, or its own branch name, raises
`ValueError` before the block runs, because `get_branch` would return that
branch or the simulation itself.

## Inputs set on a branch

`set_input` on a branch stores the new value and drops every value the branch
Expand Down
93 changes: 91 additions & 2 deletions policyengine_core/simulations/simulation.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,21 @@
import hashlib
import os
from contextlib import nullcontext
from contextlib import contextmanager, nullcontext
import types
from contextvars import ContextVar
from dataclasses import dataclass
from threading import Lock
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Type, Union
from typing import (
TYPE_CHECKING,
Any,
Dict,
Iterator,
List,
Optional,
Tuple,
Type,
Union,
)

import numpy as np
import pandas as pd
Expand Down Expand Up @@ -3451,6 +3461,85 @@ def get_branch(
branch.tracer = self.tracer
return branch

@contextmanager
def temporary_branch(
self, name: str = "branch", clone_system: bool = False
) -> Iterator["Simulation"]:
"""Give a new branch for the length of a ``with`` block.

For a formula that needs a changed copy of this simulation (raised
inputs, for example) and should leave nothing behind::

with simulation.temporary_branch("raised_earnings") as branch:
branch.set_input("earnings", period, raised_earnings)
raised = branch.calculate("net_income", period)

The branch is made by :meth:`get_branch`, so it is part of this
simulation as any other branch is. A simulation that keeps its
branches holds it in ``branches`` only while the block runs: when the
block ends, normally or by raising, the branch is removed, unless
the block already removed it or put another branch under its name,
which then stays. If making the branch fails, nothing is left under
its name. A read-only simulation (see :meth:`make_read_only`)
never keeps it, so there is nothing to remove, and each block gets a
new branch.

Without ``clone_system`` the branch shares this simulation's
tax-benefit system, so a change to the system or its parameters made
through the branch (``neutralize_variable``, a parameter update)
changes this simulation too, and stays after the block. Pass
``clone_system=True`` for such changes, and call
:meth:`drop_computed_arrays` on the branch before calculating, as
with :meth:`get_branch`.

A name this simulation already holds in ``branches``, or its own
``branch_name``, raises ``ValueError`` before anything changes:
:meth:`get_branch` would return that branch, or this simulation
itself, which the block would then change and remove. Other names
are accepted, as by :meth:`get_branch`, including the branch name of
a simulation this one was branched from.

Args:
name (str, optional): Name of the branch. Defaults to "branch".
clone_system (bool, optional): Whether the branch gets its own
copy of the tax-benefit system, as in :meth:`get_branch`.
Defaults to False.

Yields:
Simulation: The new branch.

Raises:
ValueError: ``name`` is this simulation's branch name, or the
name of a branch this simulation holds.
"""
if name == self.branch_name:
raise ValueError(
f"A temporary branch can't be named {name!r}: that is this "
"simulation's own branch name, so get_branch would return "
"the simulation itself."
)
if name in self.branches:
raise ValueError(
f"A temporary branch can't be named {name!r}: this simulation "
"already holds a branch with that name, which the block would "
"change and remove."
)
try:
branch = self.get_branch(name, clone_system=clone_system)
except BaseException:
# The name was free before this call, so a branch now under it
# was registered by this call (by core, before an override of
# get_branch raised).
self.branches.pop(name, None)
raise
try:
yield branch
finally:
# Remove only the branch this block was given: the block may have
# replaced it, and a read-only simulation never kept it.
if self.branches.get(name) is branch:
del self.branches[name]

def derivative(
self, variable: str, wrt: str, period: Period = None, delta: float = 1
) -> ArrayLike:
Expand Down
Loading