Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
001f201
Add tests for declared current-law reads and an on-demand copy
anth-volk Dec 1, 2026
e1a2d7d
Label the test variables and compare float32 tax with a tolerance
anth-volk Dec 1, 2026
0548590
Add a test that a copy built later has requested nothing
anth-volk Dec 1, 2026
8f0a378
Declare current-law reads and build the current-law copy on demand
anth-volk Dec 1, 2026
5d591dd
Add tests for review round 1's findings
anth-volk Dec 1, 2026
977323b
Fix review round 1's findings on declared current-law reads
anth-volk Dec 1, 2026
be5b67c
Add tests for review round 2's findings
anth-volk Dec 1, 2026
d0b42e7
Fix review round 2's findings on declared current-law reads
anth-volk Dec 1, 2026
06b7c58
Merge master into declared-current-law-reads
anth-volk Dec 1, 2026
1a90495
Add tests for review round 3's findings
anth-volk Dec 1, 2026
a6bc925
Check the announced clone's record instead of its source's lifetime
anth-volk Dec 1, 2026
13aad57
Fix review round 3's findings on declared current-law reads
anth-volk Dec 1, 2026
0f4feaf
Add tests for stored current-law values
anth-volk Dec 2, 2026
24da644
Count five yearly registered variables in the export test
anth-volk Dec 2, 2026
8ccf920
Add tests that pickled values and deep-copied simulations keep suppli…
anth-volk Dec 2, 2026
87f832d
Add stored current-law values: export, save, load and supply
anth-volk Dec 2, 2026
62f78c7
Add tests for review round 1's findings on stored current-law values
anth-volk Dec 2, 2026
b559d18
Fix review round 1's findings on stored current-law values
anth-volk Dec 2, 2026
d1b537b
Add tests for review round 2's findings on stored current-law values
anth-volk Dec 2, 2026
d3a8038
Fix review round 2's findings on stored current-law values
anth-volk Dec 2, 2026
6920260
Add tests for review round 3's findings on stored current-law values
anth-volk Dec 2, 2026
702bd19
Fix review round 3's findings on stored current-law values
anth-volk Dec 2, 2026
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/current-law-values.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Added stored current-law values: `export_current_law_values` saves a simulation's registered current-law values with each entity's ID array as a `CurrentLawValues` (one versioned HDF5 file through `save` and `load`), and a reform simulation given them through `current_law_values=` or `supply_current_law_values` checks each ID array, raising `CurrentLawValuesMismatchError` naming the entity on a mismatch, then returns them for declared reads, and through `supplied_current_law_value`, without building its current-law copy; `subsample` and `build_from_populations` drop them with a logged warning.
1 change: 1 addition & 0 deletions changelog.d/declared-current-law-reads.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Added declared current-law reads: `Population.current_law` for variables that set `current_law_read = True`, `Simulation.compares_with_current_law`, `Simulation.current_law_system` and `Simulation.current_law_simulation()`, each reported to the tracer through `record_current_law_call`.
1 change: 1 addition & 0 deletions changelog.d/declared-current-law-reads.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
A reform simulation no longer branches its current-law copy while it is constructed: the copy is built from the inputs held when first needed, without calculated values, and the first declared current-law call makes it read-only; `Simulation.baseline` is deprecated and assigning it replaces the copy.
30 changes: 30 additions & 0 deletions docs/python_api/errors.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,24 @@

`policyengine_core.errors` contains error definitions specific to simulations.

## CurrentLawValuesMismatchError

Raised by `Simulation.supply_current_law_values`, and so by
`Simulation(..., current_law_values=...)`, when supplied current-law values do
not fit the simulation. `entity` names the entity whose ID array differs from
the saved one, or that is in one and not the other. `variable` names the
variable whose array length differs from its entity's ID array, whose saved
Enum value names a member, or holds a position, the variable's Enum class in
the current-law system does not have, or that is an Enum in one and not the
other.

```{eval-rst}
.. autoclass:: policyengine_core.errors.current_law_values_mismatch_error.CurrentLawValuesMismatchError
:members:
:undoc-members:
:show-inheritance:
```

## NANCreationError

```{eval-rst}
Expand Down Expand Up @@ -69,6 +87,18 @@ have changed.
:show-inheritance:
```

## UndeclaredCurrentLawReadError

Raised by `Population.current_law` for a variable that does not declare
`current_law_read = True` in the current-law tax-benefit system.

```{eval-rst}
.. autoclass:: policyengine_core.errors.undeclared_current_law_read_error.UndeclaredCurrentLawReadError
:members:
:undoc-members:
:show-inheritance:
```

## VariableNameConflictError

```{eval-rst}
Expand Down
89 changes: 89 additions & 0 deletions docs/python_api/simulations.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,95 @@ keeps values it does not hold yet.

The method's docstring lists what is not detected.

### Current-law reads

A simulation built with a reform compares with current law. Formulas read
current law through declared calls, each reported to the simulation's tracer
(`record_current_law_call`, kept as `TraceNode.current_law_calls` by the full
tracer):

- `population.current_law(variable, period)` returns the variable's value under
current law, for a variable that declares `current_law_read = True` in the
current-law tax-benefit system; any other variable raises
`UndeclaredCurrentLawReadError`. Without a reform it returns the
simulation's own value.
- `simulation.compares_with_current_law` says whether the simulation compares
with current law.
- `simulation.current_law_system` is the current-law tax-benefit system.
- `simulation.current_law_simulation()` is the simulation that calculates
current-law values: the simulation itself without a reform.

Construction no longer branches a copy under current law. The copy is built the
first time something needs it, by the overridable
`_build_current_law_simulation()`: a branch named `baseline`, under
`default_tax_benefit_system_instance`, holding the inputs the simulation holds
then and none of its calculated values. `compares_with_current_law` and
`current_law_system` never build it. The first declared call that reaches it
makes it read-only (see above). A read-only simulation registers the copy it
builds in `branches`, unlike its other branches. Branches read their parent's
copy; `clone()` and `subsample()` keep a copy only if one was built.

`simulation.baseline` is deprecated. It returns the copy (built if needed, and
left writable) or `None`, and each read is reported to the tracer. Assigning a
simulation to it makes that simulation the copy, kept as it is given;
assigning `None` stops the comparison. Assigning it on a read-only simulation
raises `ReadOnlySimulationError`.

### Stored current-law values

A simulation without a reform can save the current-law values a reform
simulation over the same population would otherwise calculate again
(`policyengine_core.simulations.current_law_values`):

- `export_current_law_values(simulation, period, source_run_id=None)`
calculates every variable that declares `current_law_read = True`: a yearly
variable for the calculation year `period` (by default the simulation's
`default_calculation_period`), a monthly variable for each of
its twelve months, an eternal variable once. It returns a `CurrentLawValues`
holding those arrays, keyed by variable and `PeriodKey` (unit, first day,
size), each entity's ID array, and `source_run_id`. Numbers, booleans,
dates, strings and Enum values are kept; an Enum value as positions with its
member names. It refuses a simulation that compares with current law.
- `values.save(path)` writes one HDF5 file. Its root attribute `manifest` is a
JSON manifest naming the format (`FORMAT_NAME`) and its version
(`FORMAT_VERSION`), the core version that wrote it, `source_run_id`, and
each dataset with its variable, period and dtype. `CurrentLawValues.load(path)`
reads it back, refusing another format or a newer version, and ignoring
groups the manifest does not list.

A simulation takes them with `Simulation(..., current_law_values=values)`, or
with `simulation.supply_current_law_values(values)` once its population is in
place (for a caller that builds the population after construction, or a
simulation that does not run core's constructor). Core checks only that each
entity's ID array equals the saved one, element by element. To build arrays it
can read, it also maps each Enum value to the variable's Enum class in the
current-law system by member name and checks each array's length against its
variable's entity. Any of these failing raises `CurrentLawValuesMismatchError`,
naming the entity or the variable. Every other check on where the values came
from belongs to the caller.

While the simulation compares with current law, `population.current_law(...)`
without options returns a supplied value, not writable, without building the
current-law copy, and `simulation.supplied_current_law_value(variable, period)`
returns it or `None` (a declared call); neither uses a supplied value where the
simulation held an input for that variable and period when the values were
supplied. A copy core builds
starts from the supplied values as calculated values; a simulation assigned to
`baseline` is kept as given. Supplied values are never inputs, so no uprating or
carry-over starts from them.

The values describe current law for the inputs the simulation holds when they
are supplied. Branches made with `get_branch` read them. A clone made before the
copy is built does not keep them and builds its own copy from its own inputs; a
clone made once the copy exists keeps a copy of it and the values; a deep copy
or pickle keeps them with its inputs. Inputs set later on the simulation, or on
its copy through `baseline`, are not reflected in them. `subsample` and
`build_from_populations` drop them and log a warning on the
`policyengine_core.simulations.current_law_values` logger, as does a read or a
copy built after the population changed some other way. Supplying values to a
branch (or a clone of one), or once the copy core builds exists, raises
`ValueError`.

## Microsimulation

```{eval-rst}
Expand Down
2 changes: 2 additions & 0 deletions policyengine_core/errors/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from .current_law_values_mismatch_error import CurrentLawValuesMismatchError
from .cycle_error import CycleError
from .empty_argument_error import EmptyArgumentError
from .nan_creation_error import NaNCreationError
Expand All @@ -8,5 +9,6 @@
from .read_only_simulation_error import ReadOnlySimulationError
from .situation_parsing_error import SituationParsingError
from .spiral_error import SpiralError
from .undeclared_current_law_read_error import UndeclaredCurrentLawReadError
from .variable_name_conflict_error import VariableNameConflictError
from .variable_not_found_error import VariableNotFoundError
26 changes: 26 additions & 0 deletions policyengine_core/errors/current_law_values_mismatch_error.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from typing import Optional


class CurrentLawValuesMismatchError(ValueError):
"""Supplied current-law values do not fit the simulation given them.

Raised by ``Simulation.supply_current_law_values`` (and so by
``Simulation(..., current_law_values=...)``) when an entity's ID array
differs from the one saved with the values, element by element, or an
entity is in one and not the other (``entity`` names it); or when an
array's length differs from its variable's entity's ID array, a saved
Enum value names a member, or holds a position, the variable's Enum class
in the current-law system does not have, or the variable is an Enum in
one and not the other (``variable`` names it). Callers that pair
simulation runs catch it and run without the values.
"""

def __init__(
self,
message: str,
entity: Optional[str] = None,
variable: Optional[str] = None,
):
super().__init__(message)
self.entity = entity
self.variable = variable
8 changes: 8 additions & 0 deletions policyengine_core/errors/undeclared_current_law_read_error.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
class UndeclaredCurrentLawReadError(ValueError):
"""A formula read the current-law value of a variable not declared for it.

Raised by ``Population.current_law`` when the variable's
``current_law_read`` attribute, in the current-law tax-benefit system, is
not true. Declaring the reads lets core know in advance which current-law
values a simulation may need.
"""
60 changes: 60 additions & 0 deletions policyengine_core/populations/population.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,66 @@ def __call__(

# Helpers

@projectors.projectable
def current_law(
self,
variable_name: str,
period: Period = None,
options: Optional[Container[str]] = None,
):
"""Calculate ``variable_name`` under current law, for this entity.

In a simulation that compares with current law (one built with a
reform, or one of its branches), the value its current-law copy
calculates (see ``Simulation.current_law_simulation``), which this
builds if there is none yet and makes read-only (unless it is a
simulation assigned to ``baseline``, which is kept as it was given). Otherwise the
simulation is current law itself, and this is the same as calling
the population. ``period`` and ``options`` are as for a call.

The variable must declare ``current_law_read = True`` in the
current-law tax-benefit system; otherwise this raises
``UndeclaredCurrentLawReadError``. Each call is reported to the
simulation's tracer, with the variable and period.

A value supplied to the simulation (see
``Simulation.supply_current_law_values``) for that variable and period
is returned, not writable, without building the copy, when no
``options`` are given and the simulation held no input for that
variable and period when the values were supplied.

Example, for a variable ``income_tax`` declaring
``current_law_read = True``:

>>> person.current_law('income_tax', '2017-04')
>>> array([45.])

Called through a projection (``person.household.current_law(...)``),
the result is projected as a call's would be. Once the copy is
read-only, the array returned from it is non-writable, as every array
a read-only simulation stores: a formula that writes into what it
read must copy it first.
"""
# Before anything is built, so a missing period names the caller.
self.check_period_validity(variable_name, period)
simulation = self.simulation
variable = simulation._declared_current_law_variable(
variable_name, "current_law"
)
simulation._report_current_law_call("current_law", variable_name, period)
source = simulation._current_law_source()
if not source.compares:
return self(variable_name, period, options)
if not options and variable.entity.key == self.entity.key:
# A supplied value, without building the copy.
supplied = simulation._supplied_current_law_array(variable, period)
if supplied is not None:
return supplied
current_law_simulation = source.get(make_read_only=True)
return current_law_simulation.populations[self.entity.key](
variable_name, period, options
)

def get_holder(self, variable_name: str) -> Holder:
self.entity.check_variable_defined_for_entity(variable_name)
variable = self.entity.get_variable(variable_name)
Expand Down
5 changes: 5 additions & 0 deletions policyengine_core/simulations/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@
check_type,
transform_to_strict_syntax,
)
from .current_law_values import (
CurrentLawValues,
PeriodKey,
export_current_law_values,
)
from .microsimulation import Microsimulation
from .simulation import Simulation
from .simulation_builder import SimulationBuilder
Expand Down
Loading
Loading