diff --git a/changelog.d/temporary-branch.added.md b/changelog.d/temporary-branch.added.md new file mode 100644 index 000000000..6dedd1445 --- /dev/null +++ b/changelog.d/temporary-branch.added.md @@ -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. diff --git a/docs/python_api/simulations.md b/docs/python_api/simulations.md index 0aaf4d8b2..fd1fd8409 100644 --- a/docs/python_api/simulations.md +++ b/docs/python_api/simulations.md @@ -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. diff --git a/docs/usage/branches.md b/docs/usage/branches.md index eec1ae1df..4e7b768a0 100644 --- a/docs/usage/branches.md +++ b/docs/usage/branches.md @@ -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 diff --git a/policyengine_core/simulations/simulation.py b/policyengine_core/simulations/simulation.py index bf1352d6f..cf06ff6b7 100644 --- a/policyengine_core/simulations/simulation.py +++ b/policyengine_core/simulations/simulation.py @@ -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 @@ -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: diff --git a/tests/core/test_temporary_branch.py b/tests/core/test_temporary_branch.py new file mode 100644 index 000000000..caae27161 --- /dev/null +++ b/tests/core/test_temporary_branch.py @@ -0,0 +1,292 @@ +"""``Simulation.temporary_branch``: a branch for one block of code. + +A formula that needs a changed copy of its simulation (raised earnings, a +neutralized variable) creates a branch, calculates in it, and should leave +nothing behind. ``with simulation.temporary_branch(name) as branch:`` gives a +new branch, which a plain simulation keeps in ``branches`` only until the +block ends, whether it ends normally or raises. A read-only simulation (see +``make_read_only``) never keeps it, so there is nothing to remove. + +The branch must be new: a name the simulation already holds, or its own +branch name, would make ``get_branch`` return a branch the block does not own +(or the simulation itself), which the block would then change and remove. So +those names raise ``ValueError`` before anything changes. +""" + +from __future__ import annotations + +import numpy as np +import pytest + +from policyengine_core.country_template import ( + CountryTaxBenefitSystem, + Simulation, +) +from policyengine_core.country_template.entities import Person +from policyengine_core.periods import MONTH +from policyengine_core.variables import Variable + +PERIOD = "2022-01" +SALARY = [4000.0, 2500.0] +RAISED_SALARY = [5000.0, 2500.0] +SITUATION = { + "persons": { + "a": {"salary": {PERIOD: SALARY[0]}, "age": {PERIOD: 40}}, + "b": {"salary": {PERIOD: SALARY[1]}, "age": {PERIOD: 30}}, + }, + "households": {"h": {"parents": ["a", "b"]}}, +} + + +class FailureInsideTheBlock(Exception): + """Raised by a test inside a temporary branch's block.""" + + +@pytest.fixture(scope="module") +def shared_system(): + """A system the tests in this module read but never change.""" + return CountryTaxBenefitSystem() + + +@pytest.fixture +def simulation(shared_system) -> Simulation: + return Simulation(tax_benefit_system=shared_system, situation=SITUATION) + + +def test_a_plain_simulation_keeps_a_temporary_branch_only_inside_its_block( + simulation, +): + registered_before = dict(simulation.branches) + with simulation.temporary_branch("temporary") as branch: + assert simulation.branches["temporary"] is branch + assert branch is not simulation + assert branch.branch_name == "temporary" + assert branch.parent_branch is simulation + assert simulation.branches == registered_before + + +def test_a_temporary_branch_calculates_from_its_own_inputs(simulation): + income_tax = simulation.calculate("income_tax", PERIOD).copy() + with simulation.temporary_branch("raised_salary") as branch: + branch.set_input("salary", PERIOD, np.array(RAISED_SALARY)) + raised_income_tax = branch.calculate("income_tax", PERIOD) + assert raised_income_tax[0] > income_tax[0] + np.testing.assert_array_equal(raised_income_tax[1], income_tax[1]) + np.testing.assert_array_equal( + simulation.calculate("income_tax", PERIOD), income_tax + ) + np.testing.assert_array_equal(simulation.calculate("salary", PERIOD), SALARY) + + +def test_a_temporary_branch_is_removed_when_its_block_raises(simulation): + registered_before = dict(simulation.branches) + with pytest.raises(FailureInsideTheBlock): + with simulation.temporary_branch("temporary") as branch: + branch.set_input("salary", PERIOD, np.array(RAISED_SALARY)) + raise FailureInsideTheBlock() + assert simulation.branches == registered_before + # A later block with the same name starts from the simulation again, + # not from the raised salary the failed block set. + with simulation.temporary_branch("temporary") as branch: + np.testing.assert_array_equal(branch.calculate("salary", PERIOD), SALARY) + + +def test_a_read_only_simulation_never_keeps_a_temporary_branch(simulation): + income_tax = simulation.calculate("income_tax", PERIOD).copy() + registered_before = dict(simulation.branches) + simulation.make_read_only() + with simulation.temporary_branch("raised_salary") as branch: + assert simulation.branches == registered_before + assert branch.parent_branch is simulation + assert not branch.read_only + branch.set_input("salary", PERIOD, np.array(RAISED_SALARY)) + raised_income_tax = branch.calculate("income_tax", PERIOD) + assert raised_income_tax[0] > income_tax[0] + assert simulation.branches == registered_before + np.testing.assert_array_equal( + simulation.calculate("income_tax", PERIOD), income_tax + ) + + +def test_a_read_only_simulation_gives_a_new_temporary_branch_every_time( + simulation, +): + simulation.make_read_only() + with simulation.temporary_branch("temporary") as first: + first.set_input("salary", PERIOD, np.array(RAISED_SALARY)) + with simulation.temporary_branch("temporary") as second: + assert second is not first + np.testing.assert_array_equal(second.calculate("salary", PERIOD), SALARY) + + +def test_a_temporary_branch_of_a_temporary_branch_is_removed_from_its_parent( + simulation, +): + with simulation.temporary_branch("outer") as outer: + with outer.temporary_branch("inner") as inner: + assert outer.branches["inner"] is inner + assert inner.parent_branch is outer + assert "inner" not in outer.branches + assert simulation.branches["outer"] is outer + assert "outer" not in simulation.branches + + +def test_a_temporary_branch_with_its_own_system_leaves_the_parents_system( + simulation, +): + with simulation.temporary_branch("neutralized", clone_system=True) as branch: + assert branch.tax_benefit_system is not simulation.tax_benefit_system + branch.tax_benefit_system.neutralize_variable("income_tax") + np.testing.assert_array_equal(branch.calculate("income_tax", PERIOD), [0, 0]) + assert not simulation.tax_benefit_system.get_variable("income_tax").is_neutralized + assert np.all(simulation.calculate("income_tax", PERIOD) > 0) + + +@pytest.mark.parametrize("read_only", [False, True], ids=["plain", "read-only"]) +def test_a_temporary_branch_refuses_a_name_the_simulation_holds(simulation, read_only): + held = simulation.get_branch("taken") + held.set_input("salary", PERIOD, np.array(RAISED_SALARY)) + if read_only: + simulation.make_read_only() + block_ran = False + with pytest.raises(ValueError, match="taken"): + with simulation.temporary_branch("taken"): + block_ran = True + assert not block_ran + assert simulation.branches["taken"] is held + np.testing.assert_array_equal(held.calculate("salary", PERIOD), RAISED_SALARY) + + +def test_a_temporary_branch_refuses_the_simulations_own_name(simulation): + branch = simulation.get_branch("own_name") + block_ran = False + with pytest.raises(ValueError, match="own_name"): + with branch.temporary_branch("own_name"): + block_ran = True + assert not block_ran + assert simulation.branches["own_name"] is branch + np.testing.assert_array_equal(branch.calculate("salary", PERIOD), SALARY) + + +def test_a_block_that_replaces_its_branch_keeps_the_replacement(simulation): + """The block's end removes only the branch it gave.""" + with simulation.temporary_branch("temporary") as branch: + del simulation.branches["temporary"] + replacement = simulation.get_branch("temporary") + assert replacement is not branch + assert simulation.branches["temporary"] is replacement + + +SALARY_RISE = 1000.0 + + +class income_tax_after_a_salary_rise(Variable): + """Income tax if salary rose by SALARY_RISE, from a temporary branch.""" + + value_type = float + entity = Person + definition_period = MONTH + label = "Income tax after a salary rise" + + def formula(person, period, parameters): + simulation = person.simulation + raised_salary = person("salary", period) + SALARY_RISE + with simulation.temporary_branch("salary_rise") as branch: + branch.set_input("salary", period, raised_salary) + return branch.calculate("income_tax", period) + + +@pytest.fixture(scope="module") +def system_with_a_branching_formula(): + """A system the tests in this module read but never change.""" + system = CountryTaxBenefitSystem() + system.add_variable(income_tax_after_a_salary_rise) + return system + + +@pytest.mark.parametrize("read_only", [False, True], ids=["plain", "read-only"]) +def test_a_formula_calculates_in_a_temporary_branch_and_keeps_its_result( + system_with_a_branching_formula, read_only +): + raised_situation = { + "persons": { + name: {**person, "salary": {PERIOD: salary + SALARY_RISE}} + for (name, person), salary in zip(SITUATION["persons"].items(), SALARY) + }, + "households": SITUATION["households"], + } + expected = Simulation( + tax_benefit_system=system_with_a_branching_formula, + situation=raised_situation, + ).calculate("income_tax", PERIOD) + + simulation = Simulation( + tax_benefit_system=system_with_a_branching_formula, situation=SITUATION + ) + if read_only: + simulation.make_read_only() + registered_before = dict(simulation.branches) + value = simulation.calculate("income_tax_after_a_salary_rise", PERIOD) + + np.testing.assert_array_equal(value, expected) + assert simulation.branches == registered_before + held = simulation.get_holder("income_tax_after_a_salary_rise").get_array(PERIOD) + np.testing.assert_array_equal(held, expected) + np.testing.assert_array_equal(simulation.calculate("salary", PERIOD), SALARY) + + +class SimulationWithABranchOverride(Simulation): + """Marks each branch its own ``get_branch`` returns, with the request.""" + + def get_branch(self, name="branch", clone_system=False): + branch = super().get_branch(name, clone_system) + branch.request_seen_by_the_override = (name, clone_system) + return branch + + +def test_a_temporary_branch_is_made_by_the_simulations_own_get_branch( + shared_system, +): + simulation = SimulationWithABranchOverride( + tax_benefit_system=shared_system, situation=SITUATION + ) + with simulation.temporary_branch("temporary", clone_system=True) as branch: + assert branch.request_seen_by_the_override == ("temporary", True) + assert "temporary" not in simulation.branches + + +class FailureAfterTheBranchIsRegistered(Exception): + """Raised by a ``get_branch`` override after core registered the branch.""" + + +class SimulationWhoseBranchOverrideFails(Simulation): + """Its ``get_branch`` registers a branch through core, then raises.""" + + def get_branch(self, name="branch", clone_system=False): + super().get_branch(name, clone_system) + raise FailureAfterTheBranchIsRegistered() + + +def test_a_branch_whose_creation_fails_after_registering_is_removed(shared_system): + simulation = SimulationWhoseBranchOverrideFails( + tax_benefit_system=shared_system, situation=SITUATION + ) + registered_before = dict(simulation.branches) + block_ran = False + with pytest.raises(FailureAfterTheBranchIsRegistered): + with simulation.temporary_branch("temporary"): + block_ran = True + assert not block_ran + assert simulation.branches == registered_before + + +def test_a_read_only_simulation_keeps_nothing_when_a_block_raises(simulation): + simulation.make_read_only() + registered_before = dict(simulation.branches) + with pytest.raises(FailureInsideTheBlock): + with simulation.temporary_branch("temporary") as branch: + branch.set_input("salary", PERIOD, np.array(RAISED_SALARY)) + raise FailureInsideTheBlock() + assert simulation.branches == registered_before + with simulation.temporary_branch("temporary") as branch: + np.testing.assert_array_equal(branch.calculate("salary", PERIOD), SALARY)