From 001f201dfb2aa2da0b5f2c118b3d8b9715f1b983 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:31:43 +0400 Subject: [PATCH 01/21] Add tests for declared current-law reads and an on-demand copy Tests that fail before the change: Population.current_law reads a variable declared with current_law_read, an undeclared read raises, each declared call is reported to the tracer, a reform simulation builds no current-law copy while it is constructed, the copy is built from the inputs held when it is first needed and made read-only by the first declared call, and assigning baseline replaces the copy. Two existing tests read the baseline branch before anything built it; they now build it through simulation.baseline, or drop it only if it exists. Co-Authored-By: Claude Opus 5.5 --- tests/core/test_current_law_reads.py | 592 +++++++++++++++++++ tests/core/test_reform_baseline_system.py | 3 +- tests/core/test_subsample_baseline_branch.py | 3 +- 3 files changed, 596 insertions(+), 2 deletions(-) create mode 100644 tests/core/test_current_law_reads.py diff --git a/tests/core/test_current_law_reads.py b/tests/core/test_current_law_reads.py new file mode 100644 index 000000000..0592acdf2 --- /dev/null +++ b/tests/core/test_current_law_reads.py @@ -0,0 +1,592 @@ +"""Declared current-law reads, and the current-law copy built when one needs it. + +A reform simulation compares with current law. Formulas read current law +through declared calls: ``Population.current_law`` for a variable whose +``current_law_read`` attribute is true, ``Simulation.compares_with_current_law``, +``Simulation.current_law_system`` and ``Simulation.current_law_simulation``. +Each call is reported to the simulation's tracer. + +The simulation no longer branches a copy under current law while it is +constructed: the copy is built the first time something needs it, from the +inputs the simulation holds then, without the values it has calculated. The +first declared call that reaches the copy makes it read-only. A copy reached +only through the deprecated ``baseline`` alias stays writable, and so does a +simulation assigned to ``baseline``. +""" + +from __future__ import annotations + +import functools + +import numpy as np +import pytest + +from policyengine_core import errors, tracers +from policyengine_core.country_template import ( + CountryTaxBenefitSystem, + Microsimulation, + Simulation, +) +from policyengine_core.country_template.entities import Household, Person +from policyengine_core.periods import MONTH, YEAR +from policyengine_core.populations import Population +from policyengine_core.variables import Variable + +MONTH_PERIOD = "2022-01" +YEAR_PERIOD = "2022" +INSTANT = "2022-01-01" +BASELINE_RATE = 0.15 +REFORM_RATE = 0.42 +REFORM = {"taxes.income_tax_rate": {INSTANT: REFORM_RATE}} +YEARLY_SALARY = [48000.0, 30000.0] +MONTHLY_SALARY = [salary / 12 for salary in YEARLY_SALARY] +OTHER_MONTHLY_SALARY = [1000.0, 3000.0] +SITUATION = { + "persons": { + "a": {"salary": {YEAR_PERIOD: YEARLY_SALARY[0]}}, + "b": {"salary": {YEAR_PERIOD: YEARLY_SALARY[1]}}, + }, + "households": {"h": {"parents": ["a", "b"]}}, +} + + +# Variables whose current-law values formulas may read. + + +class declared_monthly_tax(Variable): + value_type = float + entity = Person + definition_period = MONTH + current_law_read = True + + def formula(person, period, parameters): + return person("income_tax", period) + + +class declared_yearly_tax(Variable): + value_type = float + entity = Person + definition_period = YEAR + current_law_read = True + + def formula(person, period, parameters): + return person("income_tax", period, options=["add"]) + + +class declared_household_monthly_tax(Variable): + value_type = float + entity = Household + definition_period = MONTH + current_law_read = True + + def formula(household, period, parameters): + return household.sum(household.members("income_tax", period)) + + +class declared_household_yearly_tax(Variable): + value_type = float + entity = Household + definition_period = YEAR + current_law_read = True + + def formula(household, period, parameters): + return household.sum(household.members("income_tax", period, options=["add"])) + + +# Variables whose formulas make declared calls. + + +class makes_every_declared_call(Variable): + value_type = float + entity = Person + definition_period = MONTH + + def formula(person, period, parameters): + simulation = person.simulation + compares = simulation.compares_with_current_law + rate = simulation.current_law_system.parameters(period).taxes.income_tax_rate + current_law_tax = person.current_law("declared_monthly_tax", period) + simulation.current_law_simulation() + return current_law_tax + 0 * rate + 0 * compares + + +class reads_the_baseline_alias(Variable): + value_type = float + entity = Person + definition_period = MONTH + + def formula(person, period, parameters): + baseline = person.simulation.baseline + return person.filled_array(0.0 if baseline is None else 1.0) + + +TEST_VARIABLES = ( + declared_monthly_tax, + declared_yearly_tax, + declared_household_monthly_tax, + declared_household_yearly_tax, + makes_every_declared_call, + reads_the_baseline_alias, +) + + +class DeclaredSystem(CountryTaxBenefitSystem): + def __init__(self, reform=None): + super().__init__(reform=reform) + for variable in TEST_VARIABLES: + self.add_variable(variable) + + +def _require_declared_current_law_reads() -> None: + """Fail on an assertion, not an error, where the declared calls are missing.""" + assert "current_law_read" in Variable.__dict__, "Variable.current_law_read" + assert hasattr(Population, "current_law"), "Population.current_law" + assert hasattr(Simulation, "current_law_simulation"), "current_law_simulation" + assert hasattr(Simulation, "compares_with_current_law") + assert hasattr(Simulation, "current_law_system") + assert hasattr(errors, "UndeclaredCurrentLawReadError") + assert hasattr(tracers.SimpleTracer, "record_current_law_call") + assert hasattr(tracers.FullTracer, "record_current_law_call") + + +@functools.lru_cache(maxsize=None) +def _simulation_classes(): + _require_declared_current_law_reads() + current_law_system = DeclaredSystem() + + class DeclaredSimulation(Simulation): + default_tax_benefit_system = DeclaredSystem + default_tax_benefit_system_instance = current_law_system + + class DeclaredMicrosimulation(Microsimulation): + default_tax_benefit_system = DeclaredSystem + default_tax_benefit_system_instance = current_law_system + + return DeclaredSimulation, DeclaredMicrosimulation + + +def _declared_simulation(reform=REFORM, **options): + simulation_class, _ = _simulation_classes() + return simulation_class(situation=SITUATION, reform=reform, **options) + + +def _current_law_values(entity_key, variable, period): + """What a simulation without a reform calculates.""" + plain = _declared_simulation(reform=None) + return plain.populations[entity_key](variable, period) + + +def _income_tax(salary, rate): + return np.array(salary) * rate + + +DECLARED_READS = [ + pytest.param("person", "declared_monthly_tax", MONTH_PERIOD, id="person-month"), + pytest.param("person", "declared_yearly_tax", YEAR_PERIOD, id="person-year"), + pytest.param( + "household", + "declared_household_monthly_tax", + MONTH_PERIOD, + id="household-month", + ), + pytest.param( + "household", + "declared_household_yearly_tax", + YEAR_PERIOD, + id="household-year", + ), +] + + +@pytest.mark.parametrize("entity_key, variable, period", DECLARED_READS) +def test_a_declared_read_returns_the_value_the_baseline_alias_returns( + entity_key, variable, period +): + simulation = _declared_simulation() + population = simulation.populations[entity_key] + + current_law_values = population.current_law(variable, period) + + np.testing.assert_array_equal( + current_law_values, _current_law_values(entity_key, variable, period) + ) + alias_values = _declared_simulation().baseline.populations[entity_key]( + variable, period + ) + np.testing.assert_array_equal(current_law_values, alias_values) + # The reform's own values differ, so the read did not return them. + assert not np.array_equal(population(variable, period), current_law_values) + + +@pytest.mark.parametrize( + "entity_key, variable", + [("person", "disposable_income"), ("household", "total_taxes")], +) +def test_an_undeclared_read_raises(entity_key, variable): + simulation = _declared_simulation() + + with pytest.raises(errors.UndeclaredCurrentLawReadError, match=variable): + simulation.populations[entity_key].current_law(variable, MONTH_PERIOD) + # Without a reform the check is the same. + with pytest.raises(errors.UndeclaredCurrentLawReadError, match=variable): + _declared_simulation(reform=None).populations[entity_key].current_law( + variable, MONTH_PERIOD + ) + + +def test_current_law_read_is_false_unless_a_variable_declares_it(): + _require_declared_current_law_reads() + system = CountryTaxBenefitSystem() + assert system.variables["income_tax"].current_law_read is False + assert DeclaredSystem().variables["declared_monthly_tax"].current_law_read is True + + +def test_a_reform_simulation_has_no_copy_after_construction(): + simulation = Simulation(situation=SITUATION, reform=REFORM) + + assert "baseline" not in simulation.branches + + +def test_the_first_declared_read_builds_the_copy_once(): + simulation = _declared_simulation() + assert "baseline" not in simulation.branches + + simulation.persons.current_law("declared_monthly_tax", MONTH_PERIOD) + + copy = simulation.branches["baseline"] + assert simulation.current_law_simulation() is copy + simulation.household.current_law("declared_household_yearly_tax", YEAR_PERIOD) + assert simulation.branches["baseline"] is copy + assert copy.parent_branch is simulation + assert copy.branch_name == "baseline" + assert ( + copy.tax_benefit_system + is _simulation_classes()[0].default_tax_benefit_system_instance + ) + # The copy is current law itself: it compares with nothing. + assert copy.compares_with_current_law is False + assert copy.current_law_simulation() is copy + assert copy.baseline is None + + +def test_compares_with_current_law_never_builds_a_copy(): + simulation = _declared_simulation() + + assert simulation.compares_with_current_law is True + assert "baseline" not in simulation.branches + assert _declared_simulation(reform=None).compares_with_current_law is False + + +def test_current_law_system_never_builds_a_copy(): + simulation = _declared_simulation() + current_law_system = _simulation_classes()[0].default_tax_benefit_system_instance + + assert simulation.current_law_system is current_law_system + assert "baseline" not in simulation.branches + assert ( + simulation.current_law_system.parameters(INSTANT).taxes.income_tax_rate + == BASELINE_RATE + ) + plain = _declared_simulation(reform=None) + assert plain.current_law_system is plain.tax_benefit_system + + +def test_without_a_reform_a_declared_read_returns_the_simulations_own_values(): + simulation = _declared_simulation(reform=None) + + np.testing.assert_array_equal( + simulation.persons.current_law("declared_monthly_tax", MONTH_PERIOD), + _income_tax(MONTHLY_SALARY, BASELINE_RATE), + ) + assert simulation.current_law_simulation() is simulation + assert simulation.baseline is None + assert simulation.branches == {} + assert not simulation.read_only + + +def test_the_copy_refuses_set_input_after_a_declared_call(): + simulation = _declared_simulation() + + simulation.persons.current_law("declared_monthly_tax", MONTH_PERIOD) + + copy = simulation.current_law_simulation() + assert copy.read_only + with pytest.raises(errors.ReadOnlySimulationError): + copy.set_input("salary", MONTH_PERIOD, OTHER_MONTHLY_SALARY) + # The simulation itself still takes inputs. + simulation.set_input("salary", MONTH_PERIOD, OTHER_MONTHLY_SALARY) + + +def test_current_law_simulation_makes_the_copy_read_only(): + simulation = _declared_simulation() + + copy = simulation.current_law_simulation() + + assert copy is simulation.branches["baseline"] + assert copy.read_only + + +def test_a_copy_reached_only_through_the_alias_stays_writable_until_a_declared_call(): + simulation = _declared_simulation() + + copy = simulation.baseline + assert not copy.read_only + copy.set_input("salary", MONTH_PERIOD, OTHER_MONTHLY_SALARY) + + # The declared call reads the copy as it was given its input. + np.testing.assert_array_equal( + simulation.persons.current_law("declared_monthly_tax", MONTH_PERIOD), + _income_tax(OTHER_MONTHLY_SALARY, BASELINE_RATE), + ) + assert simulation.baseline is copy + assert copy.read_only + + +def test_get_branch_baseline_returns_the_copy(): + simulation = Simulation(situation=SITUATION, reform=REFORM) + + copy = simulation.get_branch("baseline") + + assert simulation.baseline is copy + np.testing.assert_array_equal( + copy.calculate("income_tax", MONTH_PERIOD), + _income_tax(MONTHLY_SALARY, BASELINE_RATE), + ) + + +def test_a_copy_built_after_reform_calculations_holds_no_reform_values(): + simulation = _declared_simulation() + np.testing.assert_array_equal( + simulation.calculate("income_tax", MONTH_PERIOD), + _income_tax(MONTHLY_SALARY, REFORM_RATE), + ) + simulation.calculate("declared_yearly_tax", YEAR_PERIOD) + + np.testing.assert_array_equal( + simulation.persons.current_law("declared_monthly_tax", MONTH_PERIOD), + _income_tax(MONTHLY_SALARY, BASELINE_RATE), + ) + np.testing.assert_array_equal( + simulation.persons.current_law("declared_yearly_tax", YEAR_PERIOD), + _income_tax(YEARLY_SALARY, BASELINE_RATE), + ) + + +def test_an_input_set_after_construction_reaches_a_copy_built_later(): + simulation = Simulation(situation=SITUATION, reform=REFORM) + + simulation.set_input("salary", MONTH_PERIOD, OTHER_MONTHLY_SALARY) + + np.testing.assert_array_equal( + simulation.baseline.calculate("income_tax", MONTH_PERIOD), + _income_tax(OTHER_MONTHLY_SALARY, BASELINE_RATE), + ) + + +def test_an_input_set_after_the_copy_is_built_does_not_reach_it(): + simulation = _declared_simulation() + simulation.persons.current_law("declared_monthly_tax", MONTH_PERIOD) + + simulation.set_input("salary", MONTH_PERIOD, OTHER_MONTHLY_SALARY) + + copy = simulation.current_law_simulation() + np.testing.assert_array_equal( + copy.calculate("salary", MONTH_PERIOD), MONTHLY_SALARY + ) + np.testing.assert_array_equal( + simulation.calculate("salary", MONTH_PERIOD), OTHER_MONTHLY_SALARY + ) + + +def test_a_branch_made_before_the_copy_reads_its_parents_copy(): + simulation = _declared_simulation() + branch = simulation.get_branch("temporary") + branch.set_input("salary", MONTH_PERIOD, OTHER_MONTHLY_SALARY) + + branch_values = branch.persons.current_law("declared_monthly_tax", MONTH_PERIOD) + + # As the branch's ``baseline`` was its parent's, the branch reads the copy + # built from its parent's inputs. + assert branch.current_law_simulation() is simulation.current_law_simulation() + np.testing.assert_array_equal( + branch_values, _income_tax(MONTHLY_SALARY, BASELINE_RATE) + ) + assert branch.compares_with_current_law is True + assert "baseline" not in branch.branches + + +def test_assigning_a_simulation_to_baseline_makes_it_the_copy(): + simulation = _declared_simulation() + separate = _declared_simulation(reform=None) + separate.set_input("salary", MONTH_PERIOD, OTHER_MONTHLY_SALARY) + + simulation.baseline = separate + + assert simulation.baseline is separate + assert simulation.current_law_simulation() is separate + assert simulation.compares_with_current_law is True + np.testing.assert_array_equal( + simulation.persons.current_law("declared_monthly_tax", MONTH_PERIOD), + _income_tax(OTHER_MONTHLY_SALARY, BASELINE_RATE), + ) + # Kept as it was given: core does not make it read-only. + assert not separate.read_only + assert simulation.current_law_system is separate.tax_benefit_system + + +def test_assigning_none_to_baseline_stops_comparing_with_current_law(): + simulation = _declared_simulation() + + simulation.baseline = None + + assert simulation.baseline is None + assert simulation.compares_with_current_law is False + assert simulation.current_law_simulation() is simulation + np.testing.assert_array_equal( + simulation.persons.current_law("declared_monthly_tax", MONTH_PERIOD), + _income_tax(MONTHLY_SALARY, REFORM_RATE), + ) + assert "baseline" not in simulation.branches + + +def test_assigning_none_on_a_branch_leaves_its_parent_comparing(): + simulation = _declared_simulation() + branch = simulation.get_branch("measurement") + + branch.baseline = None + + assert branch.compares_with_current_law is False + assert simulation.compares_with_current_law is True + assert simulation.baseline is not None + + +def test_a_simulation_not_built_by_cores_constructor_compares_once_assigned(): + """A country package's simulation may skip core's ``__init__``.""" + simulation_class, _ = _simulation_classes() + simulation = simulation_class.__new__(simulation_class) + + assert simulation.baseline is None + assert simulation.compares_with_current_law is False + + separate = _declared_simulation(reform=None) + simulation.baseline = separate + + assert simulation.compares_with_current_law is True + assert simulation.current_law_simulation() is separate + + +def test_a_clone_of_a_simulation_without_a_copy_builds_its_own_from_its_inputs(): + simulation = _declared_simulation() + clone = simulation.clone() + + clone.set_input("salary", MONTH_PERIOD, OTHER_MONTHLY_SALARY) + + np.testing.assert_array_equal( + clone.persons.current_law("declared_monthly_tax", MONTH_PERIOD), + _income_tax(OTHER_MONTHLY_SALARY, BASELINE_RATE), + ) + assert clone.current_law_simulation().parent_branch is clone + assert "baseline" not in simulation.branches + np.testing.assert_array_equal( + simulation.persons.current_law("declared_monthly_tax", MONTH_PERIOD), + _income_tax(MONTHLY_SALARY, BASELINE_RATE), + ) + + +def test_subsample_keeps_no_copy_when_none_was_built(): + _, microsimulation_class = _simulation_classes() + simulation = microsimulation_class(reform=REFORM) + + simulation.subsample(n=3, seed="current-law", time_period="2022") + + assert "baseline" not in simulation.branches + values = simulation.persons.current_law("declared_monthly_tax", MONTH_PERIOD) + assert len(values) == simulation.persons.count + assert simulation.current_law_simulation().persons.count == simulation.persons.count + + +def _node_named(nodes, name): + for node in nodes: + if node.name == name: + return node + found = _node_named(node.children, name) + if found is not None: + return found + return None + + +def _reported_calls(node): + return [ + ( + call.call, + call.variable, + None if call.period is None else str(call.period), + call.branch_name, + ) + for call in node.current_law_calls + ] + + +@pytest.mark.parametrize("reform", [REFORM, None], ids=["reform", "current-law"]) +def test_each_declared_call_is_reported_to_the_tracer(reform): + simulation = _declared_simulation(reform=reform, trace=True) + + simulation.calculate("makes_every_declared_call", MONTH_PERIOD) + + node = _node_named(simulation.tracer.trees, "makes_every_declared_call") + assert _reported_calls(node) == [ + ("compares_with_current_law", None, None, "default"), + ("current_law_system", None, None, "default"), + ("current_law", "declared_monthly_tax", MONTH_PERIOD, "default"), + ("current_law_simulation", None, None, "default"), + ] + # The value read is calculated as before: on the copy under a reform, in + # the simulation itself without one. + read = _node_named(node.children, "declared_monthly_tax") + assert read.branch_name == ("baseline" if reform else "default") + + +def test_reading_the_baseline_alias_is_reported_to_the_tracer(): + simulation = _declared_simulation(trace=True) + + simulation.calculate("reads_the_baseline_alias", MONTH_PERIOD) + + node = _node_named(simulation.tracer.trees, "reads_the_baseline_alias") + assert _reported_calls(node) == [("baseline", None, None, "default")] + + +def test_a_tracer_without_the_new_method_still_calculates(): + class TracerWithoutCurrentLawCalls: + """A tracer written before core reported current-law calls.""" + + def __init__(self): + self._stack = [] + + def record_calculation_start(self, variable, period, branch_name="default"): + self._stack.append( + {"name": variable, "period": period, "branch_name": branch_name} + ) + + def record_calculation_result(self, value): + pass + + def record_parameter_access(self, parameter, period, branch_name, value): + pass + + def record_formula_run(self): + pass + + def record_calculation_end(self): + self._stack.pop() + + @property + def stack(self): + return self._stack + + simulation = _declared_simulation() + simulation.tracer = TracerWithoutCurrentLawCalls() + + np.testing.assert_array_equal( + simulation.calculate("makes_every_declared_call", MONTH_PERIOD), + _income_tax(MONTHLY_SALARY, BASELINE_RATE), + ) diff --git a/tests/core/test_reform_baseline_system.py b/tests/core/test_reform_baseline_system.py index c1c337280..f093a3108 100644 --- a/tests/core/test_reform_baseline_system.py +++ b/tests/core/test_reform_baseline_system.py @@ -196,7 +196,8 @@ def test_the_baseline_drops_a_holder_built_for_another_entity(): # Create the reform's household holder before cloning the baseline branch so # ``_bind_to_tax_benefit_system`` must drop the cross-entity holder. reform.calculate("salary", PERIOD) - del reform.branches["baseline"] + # Construction no longer builds the baseline branch; drop one if built. + reform.branches.pop("baseline", None) baseline = reform.get_branch("baseline") baseline.tax_benefit_system = reform.default_tax_benefit_system_instance baseline._bind_to_tax_benefit_system() diff --git a/tests/core/test_subsample_baseline_branch.py b/tests/core/test_subsample_baseline_branch.py index bcc3d59e1..634688071 100644 --- a/tests/core/test_subsample_baseline_branch.py +++ b/tests/core/test_subsample_baseline_branch.py @@ -16,7 +16,8 @@ def test_subsample_restores_baseline_system_and_branch_wiring(): simulation = Microsimulation( reform={"taxes.income_tax_rate": {INSTANT: REFORM_RATE}} ) - baseline_system_before = simulation.branches["baseline"].tax_benefit_system + # The baseline branch is built when first needed; reading it builds it. + baseline_system_before = simulation.baseline.tax_benefit_system simulation.subsample(n=3, seed="fix-522", time_period="2022") From e1a2d7dd063cd5023a11f0fc6acf0ea42761aa8c Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:35:55 +0400 Subject: [PATCH 02/21] Label the test variables and compare float32 tax with a tolerance Core requires a label on every variable, and income tax is calculated in float32, so the tests compare it with the expected amounts to one part in a million. Co-Authored-By: Claude Opus 5.5 --- tests/core/test_current_law_reads.py | 75 ++++++++++++++++------------ 1 file changed, 44 insertions(+), 31 deletions(-) diff --git a/tests/core/test_current_law_reads.py b/tests/core/test_current_law_reads.py index 0592acdf2..92bd1b926 100644 --- a/tests/core/test_current_law_reads.py +++ b/tests/core/test_current_law_reads.py @@ -54,6 +54,7 @@ class declared_monthly_tax(Variable): + label = "Income tax in the month" value_type = float entity = Person definition_period = MONTH @@ -64,6 +65,7 @@ def formula(person, period, parameters): class declared_yearly_tax(Variable): + label = "Income tax in the year" value_type = float entity = Person definition_period = YEAR @@ -74,6 +76,7 @@ def formula(person, period, parameters): class declared_household_monthly_tax(Variable): + label = "Household income tax in the month" value_type = float entity = Household definition_period = MONTH @@ -84,6 +87,7 @@ def formula(household, period, parameters): class declared_household_yearly_tax(Variable): + label = "Household income tax in the year" value_type = float entity = Household definition_period = YEAR @@ -97,6 +101,7 @@ def formula(household, period, parameters): class makes_every_declared_call(Variable): + label = "Current-law income tax, read with every declared call" value_type = float entity = Person definition_period = MONTH @@ -111,6 +116,7 @@ def formula(person, period, parameters): class reads_the_baseline_alias(Variable): + label = "Whether the baseline alias returns a simulation" value_type = float entity = Person definition_period = MONTH @@ -176,8 +182,9 @@ def _current_law_values(entity_key, variable, period): return plain.populations[entity_key](variable, period) -def _income_tax(salary, rate): - return np.array(salary) * rate +def _assert_income_tax(values, salary, rate): + """Income tax is calculated in float32, so compare to one part in a million.""" + np.testing.assert_allclose(values, np.array(salary) * rate, rtol=1e-6) DECLARED_READS = [ @@ -294,9 +301,10 @@ def test_current_law_system_never_builds_a_copy(): def test_without_a_reform_a_declared_read_returns_the_simulations_own_values(): simulation = _declared_simulation(reform=None) - np.testing.assert_array_equal( + _assert_income_tax( simulation.persons.current_law("declared_monthly_tax", MONTH_PERIOD), - _income_tax(MONTHLY_SALARY, BASELINE_RATE), + MONTHLY_SALARY, + BASELINE_RATE, ) assert simulation.current_law_simulation() is simulation assert simulation.baseline is None @@ -334,9 +342,10 @@ def test_a_copy_reached_only_through_the_alias_stays_writable_until_a_declared_c copy.set_input("salary", MONTH_PERIOD, OTHER_MONTHLY_SALARY) # The declared call reads the copy as it was given its input. - np.testing.assert_array_equal( + _assert_income_tax( simulation.persons.current_law("declared_monthly_tax", MONTH_PERIOD), - _income_tax(OTHER_MONTHLY_SALARY, BASELINE_RATE), + OTHER_MONTHLY_SALARY, + BASELINE_RATE, ) assert simulation.baseline is copy assert copy.read_only @@ -348,27 +357,27 @@ def test_get_branch_baseline_returns_the_copy(): copy = simulation.get_branch("baseline") assert simulation.baseline is copy - np.testing.assert_array_equal( - copy.calculate("income_tax", MONTH_PERIOD), - _income_tax(MONTHLY_SALARY, BASELINE_RATE), + _assert_income_tax( + copy.calculate("income_tax", MONTH_PERIOD), MONTHLY_SALARY, BASELINE_RATE ) def test_a_copy_built_after_reform_calculations_holds_no_reform_values(): simulation = _declared_simulation() - np.testing.assert_array_equal( - simulation.calculate("income_tax", MONTH_PERIOD), - _income_tax(MONTHLY_SALARY, REFORM_RATE), + _assert_income_tax( + simulation.calculate("income_tax", MONTH_PERIOD), MONTHLY_SALARY, REFORM_RATE ) simulation.calculate("declared_yearly_tax", YEAR_PERIOD) - np.testing.assert_array_equal( + _assert_income_tax( simulation.persons.current_law("declared_monthly_tax", MONTH_PERIOD), - _income_tax(MONTHLY_SALARY, BASELINE_RATE), + MONTHLY_SALARY, + BASELINE_RATE, ) - np.testing.assert_array_equal( + _assert_income_tax( simulation.persons.current_law("declared_yearly_tax", YEAR_PERIOD), - _income_tax(YEARLY_SALARY, BASELINE_RATE), + YEARLY_SALARY, + BASELINE_RATE, ) @@ -377,9 +386,10 @@ def test_an_input_set_after_construction_reaches_a_copy_built_later(): simulation.set_input("salary", MONTH_PERIOD, OTHER_MONTHLY_SALARY) - np.testing.assert_array_equal( + _assert_income_tax( simulation.baseline.calculate("income_tax", MONTH_PERIOD), - _income_tax(OTHER_MONTHLY_SALARY, BASELINE_RATE), + OTHER_MONTHLY_SALARY, + BASELINE_RATE, ) @@ -408,9 +418,7 @@ def test_a_branch_made_before_the_copy_reads_its_parents_copy(): # As the branch's ``baseline`` was its parent's, the branch reads the copy # built from its parent's inputs. assert branch.current_law_simulation() is simulation.current_law_simulation() - np.testing.assert_array_equal( - branch_values, _income_tax(MONTHLY_SALARY, BASELINE_RATE) - ) + _assert_income_tax(branch_values, MONTHLY_SALARY, BASELINE_RATE) assert branch.compares_with_current_law is True assert "baseline" not in branch.branches @@ -425,9 +433,10 @@ def test_assigning_a_simulation_to_baseline_makes_it_the_copy(): assert simulation.baseline is separate assert simulation.current_law_simulation() is separate assert simulation.compares_with_current_law is True - np.testing.assert_array_equal( + _assert_income_tax( simulation.persons.current_law("declared_monthly_tax", MONTH_PERIOD), - _income_tax(OTHER_MONTHLY_SALARY, BASELINE_RATE), + OTHER_MONTHLY_SALARY, + BASELINE_RATE, ) # Kept as it was given: core does not make it read-only. assert not separate.read_only @@ -442,9 +451,10 @@ def test_assigning_none_to_baseline_stops_comparing_with_current_law(): assert simulation.baseline is None assert simulation.compares_with_current_law is False assert simulation.current_law_simulation() is simulation - np.testing.assert_array_equal( + _assert_income_tax( simulation.persons.current_law("declared_monthly_tax", MONTH_PERIOD), - _income_tax(MONTHLY_SALARY, REFORM_RATE), + MONTHLY_SALARY, + REFORM_RATE, ) assert "baseline" not in simulation.branches @@ -481,15 +491,17 @@ def test_a_clone_of_a_simulation_without_a_copy_builds_its_own_from_its_inputs() clone.set_input("salary", MONTH_PERIOD, OTHER_MONTHLY_SALARY) - np.testing.assert_array_equal( + _assert_income_tax( clone.persons.current_law("declared_monthly_tax", MONTH_PERIOD), - _income_tax(OTHER_MONTHLY_SALARY, BASELINE_RATE), + OTHER_MONTHLY_SALARY, + BASELINE_RATE, ) assert clone.current_law_simulation().parent_branch is clone assert "baseline" not in simulation.branches - np.testing.assert_array_equal( + _assert_income_tax( simulation.persons.current_law("declared_monthly_tax", MONTH_PERIOD), - _income_tax(MONTHLY_SALARY, BASELINE_RATE), + MONTHLY_SALARY, + BASELINE_RATE, ) @@ -586,7 +598,8 @@ def stack(self): simulation = _declared_simulation() simulation.tracer = TracerWithoutCurrentLawCalls() - np.testing.assert_array_equal( + _assert_income_tax( simulation.calculate("makes_every_declared_call", MONTH_PERIOD), - _income_tax(MONTHLY_SALARY, BASELINE_RATE), + MONTHLY_SALARY, + BASELINE_RATE, ) From 05485906e64c8fdbc98e21d5b081981c144f4e50 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:39:56 +0400 Subject: [PATCH 03/21] Add a test that a copy built later has requested nothing A variable that must be calculated after another raises in the current-law copy when the copy has not requested that other variable, as it did when construction built the copy, even if the reform simulation requested it. Co-Authored-By: Claude Opus 5.5 --- tests/core/test_current_law_reads.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/tests/core/test_current_law_reads.py b/tests/core/test_current_law_reads.py index 92bd1b926..e5075d317 100644 --- a/tests/core/test_current_law_reads.py +++ b/tests/core/test_current_law_reads.py @@ -97,6 +97,18 @@ def formula(household, period, parameters): return household.sum(household.members("income_tax", period, options=["add"])) +class declared_tax_after_income_tax(Variable): + label = "Income tax, calculated only once income tax was requested" + value_type = float + entity = Person + definition_period = MONTH + current_law_read = True + requires_computation_after = "income_tax" + + def formula(person, period, parameters): + return person("income_tax", period) + + # Variables whose formulas make declared calls. @@ -131,6 +143,7 @@ def formula(person, period, parameters): declared_yearly_tax, declared_household_monthly_tax, declared_household_yearly_tax, + declared_tax_after_income_tax, makes_every_declared_call, reads_the_baseline_alias, ) @@ -381,6 +394,21 @@ def test_a_copy_built_after_reform_calculations_holds_no_reform_values(): ) +def test_a_copy_built_later_has_requested_nothing_its_simulation_requested(): + """``requires_computation_after`` holds in the copy as in one built at once. + + The reform simulation requested income tax; the copy has not, so a + variable that must be calculated after income tax raises there, as it did + when construction built the copy. + """ + simulation = _declared_simulation() + simulation.calculate("income_tax", MONTH_PERIOD) + simulation.calculate("declared_tax_after_income_tax", MONTH_PERIOD) + + with pytest.raises(ValueError, match="requires income_tax to be requested first"): + simulation.persons.current_law("declared_tax_after_income_tax", MONTH_PERIOD) + + def test_an_input_set_after_construction_reaches_a_copy_built_later(): simulation = Simulation(situation=SITUATION, reform=REFORM) From 8f0a3781f0fe26ec2a099b8c19c052f8bde772bd Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:40:08 +0400 Subject: [PATCH 04/21] Declare current-law reads and build the current-law copy on demand Formulas read current law through declared calls, each reported to the simulation's tracer (record_current_law_call; the full tracer keeps them on TraceNode.current_law_calls): - Population.current_law(variable, period) reads a variable declaring current_law_read = True, and raises UndeclaredCurrentLawReadError for any other; without a reform it returns the simulation's own value. - Simulation.compares_with_current_law and Simulation.current_law_system, which never build a copy. - Simulation.current_law_simulation(), the simulation that calculates current-law values. A reform simulation no longer branches its current-law copy while it is constructed. The overridable _build_current_law_simulation() builds it the first time it is needed: a branch named baseline under the default system instance, keeping the inputs held then and dropping calculated values. The first declared call that reaches it makes it read-only. Branches read their parent's copy, and clone() and subsample() keep a copy only if one was built. Simulation.baseline is now a deprecated property: reading it returns the copy, left writable, and is reported to the tracer; assigning a simulation makes it the copy, kept as given, and assigning None stops the comparison. get_branch("baseline") still returns the copy. Co-Authored-By: Claude Opus 5.5 --- .../declared-current-law-reads.added.md | 1 + .../declared-current-law-reads.changed.md | 1 + docs/python_api/errors.md | 12 + docs/python_api/simulations.md | 32 ++ policyengine_core/errors/__init__.py | 1 + .../undeclared_current_law_read_error.py | 8 + policyengine_core/populations/population.py | 47 +++ policyengine_core/simulations/simulation.py | 362 +++++++++++++++--- policyengine_core/tracers/__init__.py | 2 +- policyengine_core/tracers/full_tracer.py | 20 + policyengine_core/tracers/simple_tracer.py | 11 +- policyengine_core/tracers/trace_node.py | 22 ++ policyengine_core/variables/variable.py | 6 + 13 files changed, 468 insertions(+), 57 deletions(-) create mode 100644 changelog.d/declared-current-law-reads.added.md create mode 100644 changelog.d/declared-current-law-reads.changed.md create mode 100644 policyengine_core/errors/undeclared_current_law_read_error.py diff --git a/changelog.d/declared-current-law-reads.added.md b/changelog.d/declared-current-law-reads.added.md new file mode 100644 index 000000000..996b5cac5 --- /dev/null +++ b/changelog.d/declared-current-law-reads.added.md @@ -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`. diff --git a/changelog.d/declared-current-law-reads.changed.md b/changelog.d/declared-current-law-reads.changed.md new file mode 100644 index 000000000..7de4cccfa --- /dev/null +++ b/changelog.d/declared-current-law-reads.changed.md @@ -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. diff --git a/docs/python_api/errors.md b/docs/python_api/errors.md index 34c73c594..8b9963358 100644 --- a/docs/python_api/errors.md +++ b/docs/python_api/errors.md @@ -69,6 +69,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} diff --git a/docs/python_api/simulations.md b/docs/python_api/simulations.md index ade143bd8..e138b3428 100644 --- a/docs/python_api/simulations.md +++ b/docs/python_api/simulations.md @@ -26,6 +26,38 @@ parameter change after `make_read_only()` makes its next calculation raise not kept in `branches` and is not read-only itself. 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). 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. + ## Microsimulation ```{eval-rst} diff --git a/policyengine_core/errors/__init__.py b/policyengine_core/errors/__init__.py index 4c80bc797..74e5370c7 100644 --- a/policyengine_core/errors/__init__.py +++ b/policyengine_core/errors/__init__.py @@ -8,5 +8,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 diff --git a/policyengine_core/errors/undeclared_current_law_read_error.py b/policyengine_core/errors/undeclared_current_law_read_error.py new file mode 100644 index 000000000..ab2580386 --- /dev/null +++ b/policyengine_core/errors/undeclared_current_law_read_error.py @@ -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. + """ diff --git a/policyengine_core/populations/population.py b/policyengine_core/populations/population.py index 4e459117b..8a70907ed 100644 --- a/policyengine_core/populations/population.py +++ b/policyengine_core/populations/population.py @@ -179,6 +179,53 @@ def __call__( # Helpers + 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. 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. + + Example: + + >>> person.current_law('income_tax', '2017-04') + >>> array([45.]) + """ + from policyengine_core.errors import UndeclaredCurrentLawReadError + + simulation = self.simulation + variable = simulation._current_law_system().get_variable( + variable_name, check_existence=True + ) + if not variable.current_law_read: + raise UndeclaredCurrentLawReadError( + f'The variable "{variable_name}" does not declare ' + "current_law_read = True, so formulas may not read its " + "current-law value with current_law(). Declare it on the " + "variable." + ) + 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) + 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) diff --git a/policyengine_core/simulations/simulation.py b/policyengine_core/simulations/simulation.py index ac5dcaffd..48d584d20 100644 --- a/policyengine_core/simulations/simulation.py +++ b/policyengine_core/simulations/simulation.py @@ -678,6 +678,95 @@ def _taint_waiting_frames(simulation: "Simulation") -> None: simulation = getattr(simulation, "parent_branch", None) +class _CurrentLawSource: + """Where a simulation's current-law values come from. + + ``compares`` says whether the simulation compares with current law (it + was built with a reform, or a simulation was assigned to its + ``baseline``). ``simulation`` is the simulation that calculates + current-law values for it, once built or assigned, and ``owner`` the one + it is built from. A simulation shares this record with the branches + ``get_branch`` makes of it, as it shared its ``baseline`` before: a + branch reads its parent's copy, built once from the parent's inputs. + Assigning ``baseline`` gives the simulation a new record, so branches + made before keep the old one. ``assigned`` marks a simulation assigned to + ``baseline``, which core keeps as it was given and never makes read-only. + """ + + def __init__( + self, + owner: "Simulation", + compares: bool, + simulation: Optional["Simulation"] = None, + assigned: bool = False, + ): + self.owner = owner + self.compares = compares + self.simulation = simulation + self.assigned = assigned + self.building = False + + def get(self, make_read_only: bool) -> "Simulation": + """The current-law copy, built first if there is none yet. + + With ``make_read_only``, as for a declared call, a copy core built is + made read-only (see ``Simulation.make_read_only``). + """ + copy = self.simulation + if copy is None: + if self.building: + raise RuntimeError( + "The current-law copy of this simulation was requested while " + "it was being built. _build_current_law_simulation must not " + "read current-law values or the baseline alias." + ) + self.building = True + try: + copy = self.owner._build_current_law_simulation() + finally: + self.building = False + # The copy is current law: it compares with nothing. + copy.__dict__["_current_law"] = _CurrentLawSource(copy, compares=False) + self.simulation = copy + if make_read_only and not self.assigned: + copy.make_read_only() + return copy + + def for_clone( + self, + source: "Simulation", + clone: "Simulation", + debug: bool, + trace: bool, + ) -> "_CurrentLawSource": + """The record for a clone of ``source``, whose record this is. + + A copy not built yet is not shared: the clone builds its own from its + own inputs when it needs one. A built copy that is a branch of + ``source`` is copied for the clone, as a branch of the clone; any + other (a simulation a country package built and assigned) is shared. + """ + copy = self.simulation + if copy is None or getattr(copy, "parent_branch", None) is not source: + return _CurrentLawSource( + clone, self.compares, simulation=copy, assigned=self.assigned + ) + # A copy of the copy, not a new branch of the clone: the clone's + # cached arrays include values calculated under ``source``'s policy, + # which a new branch would read as its own. + new_copy = copy.clone(debug=debug, trace=trace, clone_tax_benefit_system=False) + new_copy.parent_branch = clone + # A copy traced in its simulation (as the builder makes it) is traced + # in the clone. + if copy.tracer is source.tracer: + new_copy.tracer = clone.tracer + if source.branches.get(copy.branch_name) is copy: + clone.branches[copy.branch_name] = new_copy + return _CurrentLawSource( + clone, self.compares, simulation=new_copy, assigned=self.assigned + ) + + @dataclass(frozen=True) class PreservedUserInput: variable_name: str @@ -739,9 +828,6 @@ class Simulation: datasets: List[Dataset] = [] """The list of datasets available for this simulation.""" - baseline: "Simulation" = None - """The baseline simulation, if this simulation is a reform.""" - is_over_dataset: bool = False """Whether this simulation is built over a dataset.""" @@ -983,22 +1069,10 @@ def __init__( ) np.random.seed(hashed_input) - if reform is not None: - self.baseline = self.get_branch("baseline") - self.baseline.trace = self.trace - self.baseline.tracer = self.tracer - self.baseline.tax_benefit_system = self.default_tax_benefit_system_instance - # The branch was built under the reform's system: its populations - # looked variables up there, and its holders kept the reform's - # variables, so a variable the reform neutralized read as the - # default in the baseline too. - self.baseline._bind_to_tax_benefit_system() - # The branch shares this simulation's list of input variables, - # and the binding keeps a list it drops nothing from. The - # baseline runs under another system, so it keeps its own list. - self.baseline.input_variables = list(self.baseline.input_variables) - else: - self.baseline = None + # A reform simulation compares with current law. The simulation that + # calculates its current-law values is built when first needed (see + # ``current_law_simulation``), from the inputs held then. + self._current_law = _CurrentLawSource(self, compares=reform is not None) self.parent_branch = None @@ -1112,6 +1186,165 @@ def _refuse_if_parameters_changed(self) -> None: "no longer match its parameters." ) + def _current_law_source(self) -> _CurrentLawSource: + """This simulation's record of where its current-law values come from. + + A simulation that core's ``__init__`` did not build (a country + package may build its own) gets one when first asked: it compares + with current law only once a simulation is assigned to ``baseline``. + """ + source = self.__dict__.get("_current_law") + if source is None: + source = _CurrentLawSource(self, compares=False) + self.__dict__["_current_law"] = source + return source + + def _report_current_law_call( + self, + call: str, + variable: Optional[str] = None, + period: Optional[Period] = None, + ) -> None: + """Report a declared current-law call to this simulation's tracer. + + A tracer without ``record_current_law_call`` (one written before core + reported these calls) is not told. + """ + record = getattr(getattr(self, "tracer", None), "record_current_law_call", None) + if record is None: + return + if period is not None and not isinstance(period, Period): + period = periods.period(period) + record(call, variable, period, getattr(self, "branch_name", "default")) + + @property + def compares_with_current_law(self) -> bool: + """Whether this simulation compares with current law. + + True for a simulation built with a reform, and for its branches; + False without a reform, and for the current-law copy itself. + Assigning ``baseline`` changes it: a simulation makes it true, and + ``None`` false. A declared call: it is reported to the simulation's + tracer, and it never builds the current-law copy. + """ + self._report_current_law_call("compares_with_current_law") + return self._current_law_source().compares + + @property + def current_law_system(self) -> "TaxBenefitSystem": + """The tax-benefit system of current law, without building a copy. + + For a simulation that compares with current law, the system its + current-law copy calculates with (the class's + ``default_tax_benefit_system_instance`` unless a simulation was + assigned to ``baseline``); otherwise this simulation's own system. A + declared call, reported to the simulation's tracer. + """ + self._report_current_law_call("current_law_system") + return self._current_law_system() + + def _current_law_system(self) -> "TaxBenefitSystem": + source = self._current_law_source() + if not source.compares: + return self.tax_benefit_system + if source.simulation is not None: + return source.simulation.tax_benefit_system + return source.owner.default_tax_benefit_system_instance + + def current_law_simulation(self) -> "Simulation": + """The simulation that calculates this simulation's current-law values. + + For a simulation that compares with current law, the current-law + copy, built on the first call (by :meth:`_build_current_law_simulation`) + from the inputs the simulation holds then. A branch gets its parent's. + A copy core built is made read-only (see :meth:`make_read_only`); a + simulation assigned to ``baseline`` is returned as it was given. + Without a comparison, this simulation itself. A declared call, + reported to the simulation's tracer. + """ + self._report_current_law_call("current_law_simulation") + source = self._current_law_source() + if not source.compares: + return self + return source.get(make_read_only=True) + + @property + def baseline(self) -> Optional["Simulation"]: + """Deprecated alias: use the declared current-law calls instead. + + The current-law copy for a simulation that compares with current law + (see :meth:`current_law_simulation`), otherwise ``None``. Reading it + builds the copy if there is none, and does not make it read-only, so + code that sets inputs on the baseline keeps working; the first + declared call makes it read-only. Assigning a simulation makes it the + copy, kept as it is given, and the simulation then compares with + current law; assigning ``None`` stops the comparison. Each read is + reported to the tracer as a ``baseline`` call. Formulas should use + ``Population.current_law``, ``compares_with_current_law``, + ``current_law_system`` and ``current_law_simulation``; the alias is + due to be removed once country packages read current law only through + them. + """ + self._report_current_law_call("baseline") + source = self._current_law_source() + if not source.compares: + return None + return source.get(make_read_only=False) + + @baseline.setter + def baseline(self, simulation: Optional["Simulation"]) -> None: + self.__dict__["_current_law"] = _CurrentLawSource( + self, + compares=simulation is not None, + simulation=simulation, + assigned=simulation is not None, + ) + + def _build_current_law_simulation(self) -> "Simulation": + """Build the simulation that calculates this one's current-law values. + + Called once, the first time a simulation that compares with current + law needs current-law values (see :meth:`current_law_simulation`), + which may be in the middle of a calculation. Country packages may + override it to give the copy their own state; an override must not + read current-law values or ``baseline`` itself. + + The copy is a branch of this simulation named ``baseline``, traced in + this simulation, under the class's + ``default_tax_benefit_system_instance``. It keeps the inputs this + simulation holds now and none of the values it has calculated, which + were calculated under the reform: so an input set on this simulation + before the copy is built reaches the copy, and one set afterwards + does not. + """ + # A branch registered under the name, by code that ran before the copy + # was needed, may hold the reform's values; the copy replaces it. + self.branches.pop("baseline", None) + copy = self.get_branch("baseline") + copy.__dict__["_current_law"] = _CurrentLawSource(copy, compares=False) + copy.trace = self.trace + copy.tracer = self.tracer + copy.tax_benefit_system = self.default_tax_benefit_system_instance + # The branch was built under the reform's system: its populations + # looked variables up there, and its holders kept the reform's + # variables, so a variable the reform neutralized read as the + # default in the copy too. + copy._bind_to_tax_benefit_system() + # The branch shares this simulation's list of input variables, and + # the binding keeps a list it drops nothing from. The copy runs under + # another system, so it keeps its own list. + copy.input_variables = list(copy.input_variables) + # The branch started from everything this simulation holds, including + # what it calculated under the reform. Keep only the inputs, and read + # macro-cache files as this simulation does. + macro_cache_read = self.macro_cache_read + copy.drop_computed_arrays() + copy.macro_cache_read = macro_cache_read + # Nor has the copy requested what this simulation requested, which + # ``requires_computation_after`` reads. + copy._requested_variables = set() + return copy + def apply_reform(self, reform: Union[tuple, Reform]): refuse_on_read_only(self, "apply_reform") if isinstance(reform, tuple): @@ -3323,40 +3556,24 @@ def clone( # A ``set_input`` running on this simulation is not running on the copy. new._user_input_contexts = [] - # A branch shares its parent's baseline: formulas that run in a - # branch read the parent's baseline values through it. That holds for - # every clone of this simulation made while ``get_branch`` is making - # a branch of it, not only the one that shares its arrays (a subclass - # ``clone`` may clone it directly first; see ``_BranchClone``). + # A branch shares its parent's record of where its current-law + # values come from: formulas that run in a branch read the parent's + # current-law copy. That holds for every clone of this simulation + # made while ``get_branch`` is making a branch of it, not only the + # one that shares its arrays (a subclass ``clone`` may clone it + # directly first; see ``_BranchClone``). branching = request is not None and request.simulation is self - baseline = getattr(self, "baseline", None) - if ( - not branching - and baseline is not None - and getattr(baseline, "parent_branch", None) is self - ): - # This simulation's own baseline branch (``__init__`` makes one - # for a reform). A shared one filled this simulation's caches - # with the copy's baseline calculations and took inputs set - # through either, ``get_branch("baseline")`` on the copy made a - # branch under the copy's (reform) policy, ``subsample`` of the - # copy left its baseline at the old size, and the copy kept this - # simulation alive through the branch's ``parent_branch``. The - # copy gets a copy of the branch, not a new branch of itself as in - # ``__init__``: its cached arrays include values calculated under - # this simulation's policy, which a new branch would read as its - # own. - new_baseline = baseline.clone( - debug=debug, trace=trace, clone_tax_benefit_system=False + current_law = self.__dict__.get("_current_law") + if not branching and current_law is not None and current_law.owner is self: + # This simulation's own record. A shared copy filled this + # simulation's caches with the clone's current-law calculations + # and took inputs set through either, ``subsample`` of the clone + # left the copy at the old size, and the clone kept this + # simulation alive through the copy's ``parent_branch``. A record + # this simulation shares with its parent stays shared. + new.__dict__["_current_law"] = current_law.for_clone( + self, new, debug, trace ) - new_baseline.parent_branch = new - # A baseline traced in its simulation (as ``__init__`` makes it) - # is traced in the copy. - if baseline.tracer is self.tracer: - new_baseline.tracer = new.tracer - if self.branches.get(baseline.branch_name) is baseline: - new.branches[baseline.branch_name] = new_baseline - new.baseline = new_baseline return new @@ -3409,6 +3626,23 @@ def get_branch( """ if name == self.branch_name: return self + if name == "baseline" and name not in self.branches: + current_law = self.__dict__.get("_current_law") + if ( + current_law is not None + and current_law.owner is self + and current_law.compares + and not current_law.building + and ( + current_law.simulation is None + or getattr(current_law.simulation, "parent_branch", None) is self + ) + ): + # Construction used to register the current-law copy under + # this name, and code reached it here. A copy built after + # ``make_read_only`` is not registered (see ``get_branch`` on a + # read-only simulation), so it is returned from the record. + return current_law.get(make_read_only=False) if name in self.branches: branch = self.branches[name] frames = _calculation_frames.get() @@ -4073,9 +4307,19 @@ def retain_structure(name, values): # rebuilt baseline branch kept the reform system and reform-vs-baseline # comparisons after ``subsample`` compared the reform against itself. if "baseline" in self.branches: + # A current-law copy that was built (or a baseline branch that was + # assigned). One not built yet is built from the new sample when + # needed. baseline_tax_benefit_system = self.branches["baseline"].tax_benefit_system del self.branches["baseline"] - baseline = self.get_branch("baseline") + # A new branch, not the copy this replaces (see ``get_branch``). + current_law = self._current_law_source() + building = current_law.building + current_law.building = True + try: + baseline = self.get_branch("baseline") + finally: + current_law.building = building # As in ``__init__``, the branch is traced in this simulation, # uses the baseline system's entities and variables, and has no # baseline of its own: ``get_branch`` gave it this simulation's, @@ -4086,9 +4330,17 @@ def retain_structure(name, values): baseline._bind_to_tax_benefit_system() # As in ``__init__``, the baseline keeps its own list. baseline.input_variables = list(baseline.input_variables) - baseline.baseline = None - if getattr(self, "baseline", None) is not None: - self.baseline = baseline + baseline.__dict__["_current_law"] = _CurrentLawSource( + baseline, compares=False + ) + current_law = self._current_law_source() + if current_law.compares: + self.__dict__["_current_law"] = _CurrentLawSource( + self, + compares=True, + simulation=baseline, + assigned=current_law.assigned, + ) self.default_calculation_period = default_calculation_period return self diff --git a/policyengine_core/tracers/__init__.py b/policyengine_core/tracers/__init__.py index f23c0bbcd..d4198c923 100644 --- a/policyengine_core/tracers/__init__.py +++ b/policyengine_core/tracers/__init__.py @@ -4,7 +4,7 @@ from .performance_log import PerformanceLog from .variable_graph import VariableGraph from .simple_tracer import SimpleTracer -from .trace_node import TraceNode +from .trace_node import CurrentLawCall, TraceNode from .tracing_parameter_node_at_instant import ( TracingChildren, TracingParameterNode, diff --git a/policyengine_core/tracers/full_tracer.py b/policyengine_core/tracers/full_tracer.py index f2d93e7f4..7df194eba 100644 --- a/policyengine_core/tracers/full_tracer.py +++ b/policyengine_core/tracers/full_tracer.py @@ -76,6 +76,26 @@ def record_formula_run(self) -> None: if self._current_node is not None: self._current_node.formula_ran = True + def record_current_law_call( + self, + call: str, + variable: Optional[str], + period: Optional[Period], + branch_name: str, + ) -> None: + """Note on the calculation running now a declared current-law call + its formula made (see ``tracers.CurrentLawCall``). A call made outside + any calculation is not recorded.""" + if self._current_node is not None: + self._current_node.current_law_calls.append( + tracers.CurrentLawCall( + call=call, + variable=variable, + period=period, + branch_name=branch_name, + ) + ) + def _record_start_time( self, time_in_s: Optional[float] = None, diff --git a/policyengine_core/tracers/simple_tracer.py b/policyengine_core/tracers/simple_tracer.py index 9838491be..babcc2b4f 100644 --- a/policyengine_core/tracers/simple_tracer.py +++ b/policyengine_core/tracers/simple_tracer.py @@ -1,7 +1,7 @@ from __future__ import annotations import typing -from typing import Dict, List, Union +from typing import Dict, List, Optional, Union if typing.TYPE_CHECKING: from numpy.typing import ArrayLike @@ -33,6 +33,15 @@ def record_parameter_access(self, parameter: str, period, branch_name: str, valu def record_formula_run(self) -> None: pass + def record_current_law_call( + self, + call: str, + variable: Optional[str], + period: Optional[Period], + branch_name: str, + ) -> None: + pass # ignore declared current-law calls + def record_calculation_end(self) -> None: self.stack.pop() diff --git a/policyengine_core/tracers/trace_node.py b/policyengine_core/tracers/trace_node.py index 53679efab..8e991d0d3 100644 --- a/policyengine_core/tracers/trace_node.py +++ b/policyengine_core/tracers/trace_node.py @@ -13,6 +13,23 @@ Time = typing.Union[float, int] +@dataclasses.dataclass(frozen=True) +class CurrentLawCall: + """A declared current-law call a formula made while it was calculated. + + ``call`` names it: ``current_law``, ``compares_with_current_law``, + ``current_law_system`` or ``current_law_simulation``, or ``baseline`` for + a read of the deprecated alias. ``variable`` and ``period`` are the value + a ``current_law`` call read, and ``None`` for the other calls. + ``branch_name`` is the branch of the simulation that made the call. + """ + + call: str + variable: typing.Optional[str] = None + period: typing.Optional[Period] = None + branch_name: str = "default" + + @dataclasses.dataclass class TraceNode: name: str @@ -28,6 +45,11 @@ class TraceNode: # ``subtracts``. It stays False for a value that was stored, cached or # defaulted, including one masked by ``defined_for``. formula_ran: bool = False + # The declared current-law calls the formula made (``CurrentLawCall``), + # in order. The values those calls read are children, as other reads are. + current_law_calls: typing.List[CurrentLawCall] = dataclasses.field( + default_factory=list + ) def calculation_time(self, round_: bool = True) -> Time: result = self.end - self.start diff --git a/policyengine_core/variables/variable.py b/policyengine_core/variables/variable.py index de9415c42..8071419a7 100644 --- a/policyengine_core/variables/variable.py +++ b/policyengine_core/variables/variable.py @@ -143,6 +143,9 @@ class Variable: hidden_input: bool = False """Whether the variable is hidden from the input screen entirely on PolicyEngine.""" + current_law_read: bool = False + """Whether formulas may read the variable's current-law value with ``Population.current_law``. In a simulation with a reform, that call returns the value calculated under current law; without a reform, the simulation's own value. Reading the current-law value of a variable that does not declare this raises ``UndeclaredCurrentLawReadError``. A reform's ``update_variable`` keeps it unless the new class sets it.""" + requires_computation_after: str = None """Name of a variable that must be computed before this variable.""" @@ -309,6 +312,9 @@ def __init__(self, baseline_variable=None): self.hidden_input = self.set( attr, "hidden_input", allowed_type=bool, default=False ) + self.current_law_read = self.set( + attr, "current_law_read", allowed_type=bool, default=False + ) self.requires_computation_after = self.set( attr, "requires_computation_after", allowed_type=str From 5d591dd6a002f845ef6c3ac2e787938434450a0c Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:14:44 +0400 Subject: [PATCH 05/21] Add tests for review round 1's findings Tests that fail before the fixes: current_law is projected through entity projections like a population call; current_law without a period raises before building the copy and names the calling code; a derivative does not depend on whether the copy was built before it; removing the registered copy lets get_branch("baseline") make a new branch; a simulation saved with baseline in its instance dictionary keeps it; an AttributeError while building the copy is not read as "no baseline". Tests for behaviour that already holds: options pass through current_law; a copy built inside a calculation ignores that calculation's reform values; a clone of a simulation with a read-only copy gets its own copy; a branch of a branch reads the first simulation's copy; a deep copy keeps its own copy; the declaration check reads an assigned simulation's system. One edited test now builds the baseline by reading it, and two test modules no longer say construction builds the branch. Co-Authored-By: Claude Opus 5.5 --- tests/core/test_clone_reform_baseline.py | 6 +- tests/core/test_current_law_reads.py | 184 ++++++++++++++++++++++ tests/core/test_reform_baseline_system.py | 18 +-- 3 files changed, 196 insertions(+), 12 deletions(-) diff --git a/tests/core/test_clone_reform_baseline.py b/tests/core/test_clone_reform_baseline.py index a23ecb299..88d7eceab 100644 --- a/tests/core/test_clone_reform_baseline.py +++ b/tests/core/test_clone_reform_baseline.py @@ -1,7 +1,9 @@ """A clone of a reform simulation has a baseline of its own. -``Simulation.__init__`` gives a reform simulation a baseline branch, -``baseline``, under the baseline policy. ``Simulation.clone`` copies the +A reform simulation has a baseline branch, ``baseline``, under the baseline +policy (the current-law copy: ``Simulation.__init__`` built it, and +``_build_current_law_simulation`` now builds it when it is first needed, so +these tests read ``baseline`` to build it). ``Simulation.clone`` copies the instance dictionary, so a clone shared that branch with its source: calculations on the clone's baseline filled the source's, an input set on either one's baseline reached the other, ``clone.get_branch("baseline")`` diff --git a/tests/core/test_current_law_reads.py b/tests/core/test_current_law_reads.py index e5075d317..96ebf80e5 100644 --- a/tests/core/test_current_law_reads.py +++ b/tests/core/test_current_law_reads.py @@ -16,6 +16,7 @@ from __future__ import annotations +import copy as copy_module import functools import numpy as np @@ -112,6 +113,32 @@ def formula(person, period, parameters): # Variables whose formulas make declared calls. +class reform_then_current_law_tax(Variable): + label = "Current-law income tax, read after the reform's" + value_type = float + entity = Person + definition_period = MONTH + + def formula(person, period, parameters): + # The reform simulation calculates these first, in this calculation. + reform_tax = person("income_tax", period) + reform_declared_tax = person("declared_monthly_tax", period) + current_law_tax = person.current_law("declared_monthly_tax", period) + return current_law_tax + 0 * reform_tax + 0 * reform_declared_tax + + +class income_tax_change(Variable): + label = "Income tax change from current law" + value_type = float + entity = Person + definition_period = MONTH + + def formula(person, period, parameters): + return person("income_tax", period) - person.current_law( + "declared_monthly_tax", period + ) + + class makes_every_declared_call(Variable): label = "Current-law income tax, read with every declared call" value_type = float @@ -144,6 +171,8 @@ def formula(person, period, parameters): declared_household_monthly_tax, declared_household_yearly_tax, declared_tax_after_income_tax, + reform_then_current_law_tax, + income_tax_change, makes_every_declared_call, reads_the_baseline_alias, ) @@ -545,6 +574,161 @@ def test_subsample_keeps_no_copy_when_none_was_built(): assert simulation.current_law_simulation().persons.count == simulation.persons.count +def test_current_law_is_projected_like_a_population_call(): + simulation = _declared_simulation() + + per_person = simulation.persons.household.current_law( + "declared_household_monthly_tax", MONTH_PERIOD + ) + + household_total = sum(MONTHLY_SALARY) * BASELINE_RATE + _assert_income_tax(per_person, [household_total, household_total], 1.0) + first_person = simulation.household.first_person.current_law( + "declared_monthly_tax", MONTH_PERIOD + ) + _assert_income_tax(first_person, [MONTHLY_SALARY[0]], BASELINE_RATE) + + +def test_current_law_passes_options_on(): + simulation = _declared_simulation() + + yearly = simulation.persons.current_law( + "declared_monthly_tax", YEAR_PERIOD, options=["add"] + ) + + _assert_income_tax(yearly, YEARLY_SALARY, BASELINE_RATE) + + +def test_current_law_without_a_period_raises_before_building_the_copy(): + simulation = _declared_simulation() + + with pytest.raises(ValueError, match="did not specify on which period") as error: + simulation.persons.current_law("declared_monthly_tax") + + assert "baseline" not in simulation.branches + # The message points at the code that left the period out. + assert "test_current_law_reads.py" in str(error.value) + + +def test_a_copy_built_in_a_calculation_ignores_what_that_calculation_calculated(): + simulation = _declared_simulation() + + values = simulation.calculate("reform_then_current_law_tax", MONTH_PERIOD) + + _assert_income_tax(values, MONTHLY_SALARY, BASELINE_RATE) + _assert_income_tax( + simulation.calculate("declared_monthly_tax", MONTH_PERIOD), + MONTHLY_SALARY, + REFORM_RATE, + ) + + +def test_a_derivative_does_not_depend_on_whether_the_copy_was_built(): + """``derivative`` changes an input on a clone; its current law does not.""" + fresh = _declared_simulation() + built = _declared_simulation() + built.current_law_simulation() + + fresh_derivative = fresh.derivative("income_tax_change", "salary", MONTH_PERIOD) + built_derivative = built.derivative("income_tax_change", "salary", MONTH_PERIOD) + + np.testing.assert_allclose(fresh_derivative, built_derivative, rtol=1e-3) + np.testing.assert_allclose(fresh_derivative, [REFORM_RATE] * 2, rtol=1e-3) + + +def test_removing_the_registered_copy_lets_get_branch_make_a_new_branch(): + """As before: code that rebuilds the baseline branch itself gets a new one.""" + simulation = _declared_simulation() + copy = simulation.baseline + + simulation.branches.pop("baseline") + new_branch = simulation.get_branch("baseline") + + assert new_branch is not copy + assert simulation.branches["baseline"] is new_branch + + +def test_a_clone_of_a_simulation_with_a_read_only_copy_gets_its_own_copy(): + simulation = _declared_simulation() + copy = simulation.current_law_simulation() + copy_values = copy.calculate("declared_monthly_tax", MONTH_PERIOD) + + clone = simulation.clone() + + clone_copy = clone.branches["baseline"] + assert clone_copy is not copy + assert clone_copy.parent_branch is clone + assert not clone_copy.read_only + assert clone.current_law_simulation() is clone_copy + assert clone_copy.read_only + np.testing.assert_array_equal( + clone_copy.calculate("declared_monthly_tax", MONTH_PERIOD), copy_values + ) + assert copy.read_only + assert simulation.current_law_simulation() is copy + + +def test_a_branch_of_a_branch_reads_the_first_simulations_copy(): + simulation = _declared_simulation() + inner = simulation.get_branch("outer").get_branch("inner") + + values = inner.persons.current_law("declared_monthly_tax", MONTH_PERIOD) + + assert inner.current_law_simulation() is simulation.current_law_simulation() + _assert_income_tax(values, MONTHLY_SALARY, BASELINE_RATE) + + +def test_a_deep_copy_keeps_its_own_copy(): + simulation = Simulation(situation=SITUATION, reform=REFORM) + copy = simulation.baseline + + duplicate = copy_module.deepcopy(simulation) + + assert duplicate.compares_with_current_law is True + assert duplicate.baseline is duplicate.branches["baseline"] + assert duplicate.baseline is not copy + assert duplicate.baseline.parent_branch is duplicate + _assert_income_tax( + duplicate.baseline.calculate("income_tax", MONTH_PERIOD), + MONTHLY_SALARY, + BASELINE_RATE, + ) + + +def test_a_simulation_saved_by_an_earlier_core_keeps_its_baseline(): + """An earlier core kept ``baseline`` in the instance dictionary.""" + simulation = Simulation(situation=SITUATION) + separate = Simulation(situation=SITUATION) + del simulation.__dict__["_current_law"] + simulation.__dict__["baseline"] = separate + + assert simulation.compares_with_current_law is True + assert simulation.current_law_simulation() is separate + assert simulation.baseline is separate + + +def test_the_declaration_check_reads_an_assigned_simulations_system(): + simulation = _declared_simulation() + # The template's own system has no ``declared_monthly_tax``. + simulation.baseline = Simulation(situation=SITUATION) + + with pytest.raises(errors.VariableNotFoundError): + simulation.persons.current_law("declared_monthly_tax", MONTH_PERIOD) + + +def test_an_attribute_error_while_building_is_not_read_as_no_baseline(): + simulation_class, _ = _simulation_classes() + + class FailingSimulation(simulation_class): + def _build_current_law_simulation(self): + raise AttributeError("a country package's builder failed") + + simulation = FailingSimulation(situation=SITUATION, reform=REFORM) + + with pytest.raises(RuntimeError, match="builder failed"): + getattr(simulation, "baseline", None) + + def _node_named(nodes, name): for node in nodes: if node.name == name: diff --git a/tests/core/test_reform_baseline_system.py b/tests/core/test_reform_baseline_system.py index f093a3108..1c1225e1d 100644 --- a/tests/core/test_reform_baseline_system.py +++ b/tests/core/test_reform_baseline_system.py @@ -1,7 +1,9 @@ """A reform simulation's baseline branch uses the baseline system throughout. -``Simulation.__init__`` builds the baseline branch with ``get_branch``, under -the reform's system, and then gives it the baseline's. The branch's +The baseline branch (the current-law copy, which ``Simulation.__init__`` +built and ``_build_current_law_simulation`` now builds when it is first +needed) is made with ``get_branch``, under the reform's system, and then given +the baseline's. The branch's populations kept the reform system's entities, so they looked variables up in the reform's system, and its holders kept the reform's ``Variable`` objects: a variable the reform neutralized read as its default in the baseline too, @@ -193,15 +195,11 @@ def test_the_baseline_drops_a_holder_built_for_another_entity(): "households": {"h": {"parents": ["a", "b"]}}, } reform = Simulation(situation=situation, reform=move_salary_to_households) - # Create the reform's household holder before cloning the baseline branch so - # ``_bind_to_tax_benefit_system`` must drop the cross-entity holder. + # Create the reform's household holder before the baseline branch is + # built, so ``_bind_to_tax_benefit_system`` must drop the cross-entity + # holder. Reading ``baseline`` builds the branch. reform.calculate("salary", PERIOD) - # Construction no longer builds the baseline branch; drop one if built. - reform.branches.pop("baseline", None) - baseline = reform.get_branch("baseline") - baseline.tax_benefit_system = reform.default_tax_benefit_system_instance - baseline._bind_to_tax_benefit_system() - baseline.input_variables = list(baseline.input_variables) + baseline = reform.baseline assert "salary" in reform.household._holders assert "salary" not in baseline.household._holders From 977323b6fdc9a8c4b649b719349859b645cab3fe Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:16:25 +0400 Subject: [PATCH 06/21] Fix review round 1's findings on declared current-law reads - current_law is projectable, so person.household.current_law(...) returns one value per person, as person.household(...) does. - current_law checks the period before building the copy, so a missing period builds nothing and the error names the calling code. - derivative builds the current-law copy before cloning, so its result does not depend on whether an earlier call built the copy: the changed clone compares with the current law of the simulation's own inputs, as before. - get_branch("baseline") returns a built copy missing from branches only on a read-only simulation; elsewhere, code that removed the registered copy gets a new branch, as before. - subsample builds a copy core built again with _build_current_law_simulation, so an override applies and the copy starts with nothing requested; other baseline branches are rebuilt as before. - The builder also clears pending cache invalidations. - A simulation that kept baseline in its instance dictionary (saved by an earlier core) keeps it as its current-law copy. - An AttributeError while building the copy through the baseline property is raised as a RuntimeError, so getattr(simulation, "baseline", None) does not read it as "no baseline". - Docstrings no longer say construction builds the copy. Co-Authored-By: Claude Opus 5.5 --- policyengine_core/populations/population.py | 9 +- policyengine_core/simulations/simulation.py | 138 ++++++++++++++------ 2 files changed, 107 insertions(+), 40 deletions(-) diff --git a/policyengine_core/populations/population.py b/policyengine_core/populations/population.py index 8a70907ed..946808ec7 100644 --- a/policyengine_core/populations/population.py +++ b/policyengine_core/populations/population.py @@ -179,6 +179,7 @@ def __call__( # Helpers + @projectors.projectable def current_law( self, variable_name: str, @@ -199,13 +200,19 @@ def current_law( ``UndeclaredCurrentLawReadError``. Each call is reported to the simulation's tracer, with the variable and period. - Example: + 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. """ from policyengine_core.errors import UndeclaredCurrentLawReadError + # Before anything is built, so a missing period names the caller. + self.check_period_validity(variable_name, period) simulation = self.simulation variable = simulation._current_law_system().get_variable( variable_name, check_existence=True diff --git a/policyengine_core/simulations/simulation.py b/policyengine_core/simulations/simulation.py index 48d584d20..3a908eb6c 100644 --- a/policyengine_core/simulations/simulation.py +++ b/policyengine_core/simulations/simulation.py @@ -1118,9 +1118,11 @@ def make_read_only(self) -> None: Calling it again changes nothing, and keeps the first record of the parameters. Nothing else is made read-only: not a clone, and not a - branch registered before this call (a reform simulation's - ``baseline``, or one a formula made in an earlier calculation), which - ``get_branch`` still returns as it is. A pickled or deep-copied + branch registered before this call (a reform simulation's current-law + copy built before it, or one a formula made in an earlier + calculation), which ``get_branch`` still returns as it is. A + current-law copy built after this call is not registered, and + ``get_branch("baseline")`` returns it. A pickled or deep-copied read-only simulation stays read-only, but a value it keeps only in its fast cache (a variable its memory configuration does not store) comes back writable. @@ -1195,7 +1197,15 @@ def _current_law_source(self) -> _CurrentLawSource: """ source = self.__dict__.get("_current_law") if source is None: - source = _CurrentLawSource(self, compares=False) + # A simulation saved by a core that kept ``baseline`` as an + # instance attribute, which the ``baseline`` property now hides. + saved_baseline = self.__dict__.pop("baseline", None) + source = _CurrentLawSource( + self, + compares=saved_baseline is not None, + simulation=saved_baseline, + assigned=saved_baseline is not None, + ) self.__dict__["_current_law"] = source return source @@ -1289,7 +1299,14 @@ def baseline(self) -> Optional["Simulation"]: source = self._current_law_source() if not source.compares: return None - return source.get(make_read_only=False) + try: + return source.get(make_read_only=False) + except AttributeError as error: + # Raised from a property, it would make ``getattr(simulation, + # "baseline", None)`` return ``None`` as if there were no copy. + raise RuntimeError( + f"Building the current-law copy of this simulation failed: {error}" + ) from error @baseline.setter def baseline(self, simulation: Optional["Simulation"]) -> None: @@ -1341,8 +1358,10 @@ def _build_current_law_simulation(self) -> "Simulation": copy.drop_computed_arrays() copy.macro_cache_read = macro_cache_read # Nor has the copy requested what this simulation requested, which - # ``requires_computation_after`` reads. + # ``requires_computation_after`` reads, or anything to delete once a + # calculation ends, as a spiral in this simulation queues. copy._requested_variables = set() + copy.invalidated_caches = set() return copy def apply_reform(self, reform: Union[tuple, Reform]): @@ -1743,8 +1762,9 @@ def _bind_to_tax_benefit_system(self) -> None: """Make this simulation's populations and holders use its own system. For a simulation given another system after its populations were - built: a reform simulation's baseline branch is a branch under the - reform's system that is then given the baseline's. Each population + built: a reform simulation's current-law copy is a branch under the + reform's system that is then given the baseline's + (see ``_build_current_law_simulation``). Each population takes that system's entity, so it looks variables up there, and each holder takes that system's variable, so a variable the reform neutralized or redefined is the baseline's again. Holders, recorded @@ -3420,14 +3440,18 @@ def clone( Copy the simulation just enough to be able to run the copy without modifying the original simulation. The copy records its own cache invalidations (``invalidated_caches``, - starting from this simulation's pending ones). If ``baseline`` is a - branch of this simulation, as a reform simulation's is, the copy gets - a copy of that branch as its own: a branch of the copy, under the same - name, with this baseline's tax-benefit system, traced in the copy if - this baseline is traced in this simulation. Any other ``baseline`` is - shared: a branch's is its parent's, and a country package that builds - a separate baseline simulation copies it, if it needs to, in its own - ``clone``. + starting from this simulation's pending ones). A simulation that + compares with current law gives the copy its own current-law copy + only if it has built one (see :meth:`current_law_simulation`): if + that is a branch of this simulation, the copy gets a copy of that + branch as its own, a branch of the copy under the same name, with the + same tax-benefit system, traced in the copy if it is traced in this + simulation, and not read-only until a declared call reaches it. A + copy not built yet is built by the copy from its own inputs when it + needs one, so an input set on the copy reaches it. Any other + current-law simulation is shared: a branch's is its parent's, and a + simulation a country package built and assigned to ``baseline`` is + shared unless the package copies it in its own ``clone``. Every cached array is copied, except in the first ``clone`` of this simulation made while ``get_branch`` is creating a branch of it: that @@ -3617,6 +3641,13 @@ def get_branch( branch is not read-only. A name registered before ``make_read_only`` gives that branch, as it is. + On a simulation that compares with current law, ``"baseline"`` gives + its current-law copy while that copy is not built yet (building it, + see :meth:`current_law_simulation`) and, on a read-only simulation, + while the copy is not registered. Once a built copy is registered, + the name gives it as any registered branch; code that removed it from + ``branches`` gets a new branch. + Args: name (str, optional): Name of the branch. Defaults to "branch". clone_system (bool, optional): Whether to clone the tax-benefit system. Use this if you're changing policy parameters. Defaults to False. @@ -3635,13 +3666,19 @@ def get_branch( and not current_law.building and ( current_law.simulation is None - or getattr(current_law.simulation, "parent_branch", None) is self + or ( + self.read_only + and getattr(current_law.simulation, "parent_branch", None) + is self + ) ) ): # Construction used to register the current-law copy under - # this name, and code reached it here. A copy built after - # ``make_read_only`` is not registered (see ``get_branch`` on a - # read-only simulation), so it is returned from the record. + # this name, and code reached it here. A read-only simulation + # does not register the copy it builds (see below), so it is + # returned from the record. On any other simulation, code + # that removed the registered copy gets a new branch, as + # before. return current_law.get(make_read_only=False) if name in self.branches: branch = self.branches[name] @@ -3686,6 +3723,11 @@ def derivative( period (Period): The period for which to compute the derivative. delta (float): The infinitesimal to use for the derivative. + A simulation that compares with current law compares the changed + copy with the current law of its own inputs: the current-law copy is + built first if there is none, so the copy of this simulation gets a + copy of it, without the change. + Returns: ArrayLike: The derivative. """ @@ -3695,6 +3737,11 @@ def derivative( elif period is None and self.default_calculation_period is not None: period = periods.period(self.default_calculation_period) + current_law = self._current_law_source() + if current_law.compares and current_law.owner is self: + # Otherwise the clone, which builds its own copy when it needs + # one, would build it from the changed input. + current_law.get(make_read_only=False) alt_sim = self.clone() alt_sim.drop_computed_arrays() alt_sim.set_input(wrt, period, self.calculate(wrt, period) + delta) @@ -4299,41 +4346,54 @@ def retain_structure(name, values): name: branch for name, branch in self.branches.items() if name == "baseline" } - # Ensure the baseline branch has the new data: rebuild it from the - # subsampled simulation through ``get_branch`` (the same wiring - # ``__init__`` uses), then restore the saved baseline tax-benefit - # system. Previously the saved system was assigned to - # ``self.branches["tax_benefit_system"]`` — a stray dict key — so the - # rebuilt baseline branch kept the reform system and reform-vs-baseline - # comparisons after ``subsample`` compared the reform against itself. - if "baseline" in self.branches: - # A current-law copy that was built (or a baseline branch that was - # assigned). One not built yet is built from the new sample when - # needed. - baseline_tax_benefit_system = self.branches["baseline"].tax_benefit_system + # Ensure a baseline branch that was built has the new data. A + # current-law copy not built yet is built from the new sample when it + # is first needed. + current_law = self._current_law_source() + replaced = self.branches.get("baseline") + if ( + replaced is not None + and current_law.owner is self + and current_law.simulation is replaced + and not current_law.assigned + ): + # The current-law copy core built: build it again from the new + # sample, with ``_build_current_law_simulation`` (which a country + # package may override). + del self.branches["baseline"] + current_law.simulation = None + current_law.get(make_read_only=False) + elif replaced is not None: + # A baseline branch assigned to ``baseline``, or registered under + # the name: rebuild it from the subsampled simulation through + # ``get_branch``, as the builder does, then restore its saved + # tax-benefit system. Previously the saved system was assigned to + # ``self.branches["tax_benefit_system"]`` (a stray dict key), so the + # rebuilt baseline branch kept the reform system and + # reform-vs-baseline comparisons after ``subsample`` compared the + # reform against itself. + baseline_tax_benefit_system = replaced.tax_benefit_system del self.branches["baseline"] # A new branch, not the copy this replaces (see ``get_branch``). - current_law = self._current_law_source() building = current_law.building current_law.building = True try: baseline = self.get_branch("baseline") finally: current_law.building = building - # As in ``__init__``, the branch is traced in this simulation, - # uses the baseline system's entities and variables, and has no - # baseline of its own: ``get_branch`` gave it this simulation's, - # the branch it replaces, which kept the old population alive. + # As the builder does, the branch is traced in this simulation, + # uses the baseline system's entities and variables, and compares + # with no current law of its own: ``get_branch`` gave it this + # simulation's record, whose copy kept the old population alive. baseline.trace = self.trace baseline.tracer = self.tracer baseline.tax_benefit_system = baseline_tax_benefit_system baseline._bind_to_tax_benefit_system() - # As in ``__init__``, the baseline keeps its own list. + # As the builder does, the baseline keeps its own list. baseline.input_variables = list(baseline.input_variables) baseline.__dict__["_current_law"] = _CurrentLawSource( baseline, compares=False ) - current_law = self._current_law_source() if current_law.compares: self.__dict__["_current_law"] = _CurrentLawSource( self, From be5b67cffa8f6ee075220eba522e7a5c81fefa28 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:39:02 +0400 Subject: [PATCH 07/21] Add tests for review round 2's findings Tests that fail before the fixes: a read-only simulation registers the current-law copy it builds, so a clone of it keeps its copy registered and get_branch("baseline") and subsample see it; a saved simulation's own baseline branch, kept in its instance dictionary by an earlier core, is copied by clone rather than shared; assigning baseline on a read-only simulation raises. Tests for behaviour that already holds: subsample builds a read-only copy again as a writable one, and does so with an overridden builder; a copy built in a calculation that runs again after an input change reads the new input. Co-Authored-By: Claude Opus 5.5 --- tests/core/test_current_law_reads.py | 115 +++++++++++++++++++++++++++ 1 file changed, 115 insertions(+) diff --git a/tests/core/test_current_law_reads.py b/tests/core/test_current_law_reads.py index 96ebf80e5..6c9c480b2 100644 --- a/tests/core/test_current_law_reads.py +++ b/tests/core/test_current_law_reads.py @@ -110,6 +110,19 @@ def formula(person, period, parameters): return person("income_tax", period) +class sets_salary_then_reads_current_law(Variable): + label = "Current-law income tax, read after the formula changes salary" + value_type = float + entity = Person + definition_period = MONTH + + def formula(person, period, parameters): + # An input set on the simulation while it calculates makes core run + # the calculation again. + person.simulation.set_input("salary", period, OTHER_MONTHLY_SALARY) + return person.current_law("declared_monthly_tax", period) + + # Variables whose formulas make declared calls. @@ -173,6 +186,7 @@ def formula(person, period, parameters): declared_tax_after_income_tax, reform_then_current_law_tax, income_tax_change, + sets_salary_then_reads_current_law, makes_every_declared_call, reads_the_baseline_alias, ) @@ -729,6 +743,107 @@ def _build_current_law_simulation(self): getattr(simulation, "baseline", None) +def test_a_read_only_simulation_registers_the_copy_it_builds(): + simulation = _declared_simulation() + simulation.make_read_only() + + copy = simulation.current_law_simulation() + + assert simulation.branches.get("baseline") is copy + assert simulation.get_branch("baseline") is copy + # Other branches of a read-only simulation stay unregistered. + assert "temporary" not in simulation.get_branch("temporary").branches + assert "temporary" not in simulation.branches + + +def test_a_clone_of_a_read_only_simulation_with_a_copy_keeps_it_registered(): + _, microsimulation_class = _simulation_classes() + simulation = microsimulation_class(reform=REFORM) + simulation.make_read_only() + simulation.current_law_simulation() + + clone = simulation.clone() + + clone_copy = clone.branches.get("baseline") + assert clone_copy is not None + assert clone.get_branch("baseline") is clone_copy + assert clone.current_law_simulation() is clone_copy + clone.subsample(n=3, seed="current-law", time_period="2022") + rebuilt = clone.current_law_simulation() + assert rebuilt is not clone_copy + assert rebuilt.persons.count == clone.persons.count + assert rebuilt.tax_benefit_system is clone_copy.tax_benefit_system + + +def test_subsample_builds_a_read_only_copy_again_as_a_writable_one(): + _, microsimulation_class = _simulation_classes() + simulation = microsimulation_class(reform=REFORM) + old_copy = simulation.current_law_simulation() + assert old_copy.read_only + + simulation.subsample(n=3, seed="current-law", time_period="2022") + + new_copy = simulation.branches["baseline"] + assert new_copy is not old_copy + assert not new_copy.read_only + assert old_copy.read_only + values = simulation.persons.current_law("declared_monthly_tax", MONTH_PERIOD) + assert len(values) == simulation.persons.count + assert simulation.current_law_simulation() is new_copy + assert new_copy.read_only + + +def test_subsample_builds_the_copy_again_with_an_overridden_builder(): + _, microsimulation_class = _simulation_classes() + + class MarkingMicrosimulation(microsimulation_class): + def _build_current_law_simulation(self): + copy = super()._build_current_law_simulation() + copy.built_by_override = True + return copy + + simulation = MarkingMicrosimulation(reform=REFORM) + simulation.current_law_simulation() + + simulation.subsample(n=3, seed="current-law", time_period="2022") + + assert simulation.current_law_simulation().built_by_override is True + + +def test_a_copy_built_in_a_calculation_that_runs_again_reads_the_new_input(): + simulation = _declared_simulation() + + values = simulation.calculate("sets_salary_then_reads_current_law", MONTH_PERIOD) + + # The formula set the input before the copy was built. + _assert_income_tax(values, OTHER_MONTHLY_SALARY, BASELINE_RATE) + + +def test_a_saved_simulations_own_baseline_branch_is_copied_by_clone(): + """An earlier core kept ``baseline``, a branch, in the instance dictionary.""" + simulation = Simulation(situation=SITUATION, reform=REFORM) + branch = simulation.baseline + del simulation.__dict__["_current_law"] + simulation.__dict__["baseline"] = branch + + clone = simulation.clone() + + assert clone.baseline is not branch + assert clone.baseline.parent_branch is clone + assert clone.branches.get("baseline") is clone.baseline + assert simulation.baseline is branch + + +def test_assigning_baseline_on_a_read_only_simulation_raises(): + simulation = _declared_simulation() + simulation.make_read_only() + + with pytest.raises(errors.ReadOnlySimulationError): + simulation.baseline = None + + assert simulation.compares_with_current_law is True + + def _node_named(nodes, name): for node in nodes: if node.name == name: From d0b42e78b9366a89ff89e0927961f8a008d23fe8 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:40:35 +0400 Subject: [PATCH 08/21] Fix review round 2's findings on declared current-law reads - A read-only simulation registers the current-law copy it builds, so a clone of it keeps its copy registered and get_branch("baseline") and subsample see it. get_branch("baseline") now returns the record's copy only while it is not built. - clone() and get_branch() turn a baseline kept in the instance dictionary by an earlier core into a record before deciding, so a clone copies a saved simulation's own baseline branch rather than sharing it. - Assigning baseline on a read-only simulation raises ReadOnlySimulationError, as assigning tax_benefit_system does. - The builder and subsample set up the baseline branch with one helper, _make_current_law_branch, and subsample gives the simulation a new record in both of its paths. - Docstrings: the builder is also called by subsample; get_branch's "baseline" case applies to a reform simulation, not its branches; a current_law result from a read-only copy is non-writable. Co-Authored-By: Claude Opus 5.5 --- docs/python_api/simulations.md | 8 +- policyengine_core/populations/population.py | 5 +- policyengine_core/simulations/simulation.py | 137 ++++++++++---------- 3 files changed, 78 insertions(+), 72 deletions(-) diff --git a/docs/python_api/simulations.md b/docs/python_api/simulations.md index e138b3428..7691a9037 100644 --- a/docs/python_api/simulations.md +++ b/docs/python_api/simulations.md @@ -50,13 +50,15 @@ first time something needs it, by the overridable `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). Branches read their parent's copy; `clone()` -and `subsample()` keep a copy only if one was built. +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 `None` stops the comparison. Assigning it on a read-only simulation +raises `ReadOnlySimulationError`. ## Microsimulation diff --git a/policyengine_core/populations/population.py b/policyengine_core/populations/population.py index 946808ec7..5d5ef4567 100644 --- a/policyengine_core/populations/population.py +++ b/policyengine_core/populations/population.py @@ -207,7 +207,10 @@ def current_law( >>> array([45.]) Called through a projection (``person.household.current_law(...)``), - the result is projected as a call's would be. + 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. """ from policyengine_core.errors import UndeclaredCurrentLawReadError diff --git a/policyengine_core/simulations/simulation.py b/policyengine_core/simulations/simulation.py index 3a908eb6c..4c637cd5c 100644 --- a/policyengine_core/simulations/simulation.py +++ b/policyengine_core/simulations/simulation.py @@ -1121,8 +1121,10 @@ def make_read_only(self) -> None: branch registered before this call (a reform simulation's current-law copy built before it, or one a formula made in an earlier calculation), which ``get_branch`` still returns as it is. A - current-law copy built after this call is not registered, and - ``get_branch("baseline")`` returns it. A pickled or deep-copied + current-law copy built after this call is registered as + ``baseline``, unlike the other branches it makes (see + :meth:`current_law_simulation`). Assigning ``baseline`` raises + ``ReadOnlySimulationError``. A pickled or deep-copied read-only simulation stays read-only, but a value it keeps only in its fast cache (a variable its memory configuration does not store) comes back writable. @@ -1288,7 +1290,8 @@ def baseline(self) -> Optional["Simulation"]: code that sets inputs on the baseline keeps working; the first declared call makes it read-only. Assigning a simulation makes it the copy, kept as it is given, and the simulation then compares with - current law; assigning ``None`` stops the comparison. Each read is + current law; assigning ``None`` stops the comparison. Assigning it on + a read-only simulation raises ``ReadOnlySimulationError``. Each read is reported to the tracer as a ``baseline`` call. Formulas should use ``Population.current_law``, ``compares_with_current_law``, ``current_law_system`` and ``current_law_simulation``; the alias is @@ -1310,6 +1313,8 @@ def baseline(self) -> Optional["Simulation"]: @baseline.setter def baseline(self, simulation: Optional["Simulation"]) -> None: + # It would change the values a read-only simulation's formulas read. + refuse_on_read_only(self, "Assigning baseline") self.__dict__["_current_law"] = _CurrentLawSource( self, compares=simulation is not None, @@ -1317,12 +1322,47 @@ def baseline(self, simulation: Optional["Simulation"]) -> None: assigned=simulation is not None, ) + def _make_current_law_branch(self, system: "TaxBenefitSystem") -> "Simulation": + """A new branch named ``baseline`` that calculates under ``system``. + + Registered in ``branches`` under the name, also on a read-only + simulation, whose other branches are not (see :meth:`make_read_only`): + the current-law copy is part of the simulation. Traced in this + simulation, with holders bound to ``system``, its own list of input + variables, and no comparison with current law of its own. + """ + current_law = self._current_law_source() + # A new branch, not the copy the record may hold (see ``get_branch``). + building = current_law.building + current_law.building = True + try: + branch = self.get_branch("baseline") + finally: + current_law.building = building + if self.read_only: + self.branches["baseline"] = branch + branch.__dict__["_current_law"] = _CurrentLawSource(branch, compares=False) + branch.trace = self.trace + branch.tracer = self.tracer + branch.tax_benefit_system = system + # The branch was built under this simulation's (reform) system: its + # populations looked variables up there, and its holders kept the + # reform's variables, so a variable the reform neutralized read as + # the default in the branch too. + branch._bind_to_tax_benefit_system() + # The branch shares this simulation's list of input variables, and + # the binding keeps a list it drops nothing from. The branch runs + # under another system, so it keeps its own list. + branch.input_variables = list(branch.input_variables) + return branch + def _build_current_law_simulation(self) -> "Simulation": """Build the simulation that calculates this one's current-law values. - Called once, the first time a simulation that compares with current - law needs current-law values (see :meth:`current_law_simulation`), - which may be in the middle of a calculation. Country packages may + Called the first time a simulation that compares with current law + needs current-law values (see :meth:`current_law_simulation`), which + may be in the middle of a calculation, and by :meth:`subsample` to + build a copy it built again from the new sample. Country packages may override it to give the copy their own state; an override must not read current-law values or ``baseline`` itself. @@ -1337,20 +1377,7 @@ def _build_current_law_simulation(self) -> "Simulation": # A branch registered under the name, by code that ran before the copy # was needed, may hold the reform's values; the copy replaces it. self.branches.pop("baseline", None) - copy = self.get_branch("baseline") - copy.__dict__["_current_law"] = _CurrentLawSource(copy, compares=False) - copy.trace = self.trace - copy.tracer = self.tracer - copy.tax_benefit_system = self.default_tax_benefit_system_instance - # The branch was built under the reform's system: its populations - # looked variables up there, and its holders kept the reform's - # variables, so a variable the reform neutralized read as the - # default in the copy too. - copy._bind_to_tax_benefit_system() - # The branch shares this simulation's list of input variables, and - # the binding keeps a list it drops nothing from. The copy runs under - # another system, so it keeps its own list. - copy.input_variables = list(copy.input_variables) + copy = self._make_current_law_branch(self.default_tax_benefit_system_instance) # The branch started from everything this simulation holds, including # what it calculated under the reform. Keep only the inputs, and read # macro-cache files as this simulation does. @@ -3469,6 +3496,10 @@ def clone( through them. Without it, the copy shares this simulation's system, which still names this simulation. """ + # A simulation saved by an earlier core keeps ``baseline`` in its + # instance dictionary; turn it into this simulation's record first, so + # the copy below does not carry the bare attribute. + current_law = self._current_law_source() request = _branch_clone.get() share_arrays = ( request is not None and request.pending and request.simulation is self @@ -3587,8 +3618,7 @@ def clone( # one that shares its arrays (a subclass ``clone`` may clone it # directly first; see ``_BranchClone``). branching = request is not None and request.simulation is self - current_law = self.__dict__.get("_current_law") - if not branching and current_law is not None and current_law.owner is self: + if not branching and current_law.owner is self: # This simulation's own record. A shared copy filled this # simulation's caches with the clone's current-law calculations # and took inputs set through either, ``subsample`` of the clone @@ -3641,12 +3671,13 @@ def get_branch( branch is not read-only. A name registered before ``make_read_only`` gives that branch, as it is. - On a simulation that compares with current law, ``"baseline"`` gives - its current-law copy while that copy is not built yet (building it, - see :meth:`current_law_simulation`) and, on a read-only simulation, - while the copy is not registered. Once a built copy is registered, - the name gives it as any registered branch; code that removed it from - ``branches`` gets a new branch. + On a simulation built with a reform (not on its branches, which get a + new branch under the name), ``"baseline"`` gives its current-law copy + while that copy is not built yet, building it (see + :meth:`current_law_simulation`). A built copy is registered under the + name, on a read-only simulation too, so the name gives it as any + registered branch; code that removed it from ``branches`` gets a new + branch. Args: name (str, optional): Name of the branch. Defaults to "branch". @@ -3658,27 +3689,16 @@ def get_branch( if name == self.branch_name: return self if name == "baseline" and name not in self.branches: - current_law = self.__dict__.get("_current_law") + current_law = self._current_law_source() if ( - current_law is not None - and current_law.owner is self + current_law.owner is self and current_law.compares + and current_law.simulation is None and not current_law.building - and ( - current_law.simulation is None - or ( - self.read_only - and getattr(current_law.simulation, "parent_branch", None) - is self - ) - ) ): # Construction used to register the current-law copy under - # this name, and code reached it here. A read-only simulation - # does not register the copy it builds (see below), so it is - # returned from the record. On any other simulation, code - # that removed the registered copy gets a new branch, as - # before. + # this name, and code reached it here. Code that removed a + # registered copy gets a new branch, as before. return current_law.get(make_read_only=False) if name in self.branches: branch = self.branches[name] @@ -4359,14 +4379,14 @@ def retain_structure(name, values): ): # The current-law copy core built: build it again from the new # sample, with ``_build_current_law_simulation`` (which a country - # package may override). + # package may override), in a new record, as the other path makes. del self.branches["baseline"] - current_law.simulation = None + current_law = _CurrentLawSource(self, compares=True) + self.__dict__["_current_law"] = current_law current_law.get(make_read_only=False) elif replaced is not None: # A baseline branch assigned to ``baseline``, or registered under - # the name: rebuild it from the subsampled simulation through - # ``get_branch``, as the builder does, then restore its saved + # the name: rebuild it from the subsampled simulation, keeping its # tax-benefit system. Previously the saved system was assigned to # ``self.branches["tax_benefit_system"]`` (a stray dict key), so the # rebuilt baseline branch kept the reform system and @@ -4374,26 +4394,7 @@ def retain_structure(name, values): # reform against itself. baseline_tax_benefit_system = replaced.tax_benefit_system del self.branches["baseline"] - # A new branch, not the copy this replaces (see ``get_branch``). - building = current_law.building - current_law.building = True - try: - baseline = self.get_branch("baseline") - finally: - current_law.building = building - # As the builder does, the branch is traced in this simulation, - # uses the baseline system's entities and variables, and compares - # with no current law of its own: ``get_branch`` gave it this - # simulation's record, whose copy kept the old population alive. - baseline.trace = self.trace - baseline.tracer = self.tracer - baseline.tax_benefit_system = baseline_tax_benefit_system - baseline._bind_to_tax_benefit_system() - # As the builder does, the baseline keeps its own list. - baseline.input_variables = list(baseline.input_variables) - baseline.__dict__["_current_law"] = _CurrentLawSource( - baseline, compares=False - ) + baseline = self._make_current_law_branch(baseline_tax_benefit_system) if current_law.compares: self.__dict__["_current_law"] = _CurrentLawSource( self, From 1a90495fe45ec133b8328a39658353263b7bedda Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 2 Dec 2026 00:11:41 +0400 Subject: [PATCH 09/21] Add tests for review round 3's findings Tests that fail before the fixes: a clone announced as a branch outside get_branch (as policyengine-uk's subsample makes one, to share arrays) builds its own current-law copy from its own inputs and does not keep its source alive through the current-law record; assigning baseline on a simulation saved by an earlier core drops the saved attribute, so its clones do not carry it. Test for behaviour that already holds: a traced clone of a simulation whose copy is built traces the clone's copy in the clone. The clone test module's docstring now says when a test's clone builds a copy of its own. Co-Authored-By: Claude Opus 5.5 --- tests/core/test_clone_reform_baseline.py | 5 +- tests/core/test_current_law_reads.py | 70 ++++++++++++++++++++++++ 2 files changed, 73 insertions(+), 2 deletions(-) diff --git a/tests/core/test_clone_reform_baseline.py b/tests/core/test_clone_reform_baseline.py index 88d7eceab..c39cbc54c 100644 --- a/tests/core/test_clone_reform_baseline.py +++ b/tests/core/test_clone_reform_baseline.py @@ -2,8 +2,9 @@ A reform simulation has a baseline branch, ``baseline``, under the baseline policy (the current-law copy: ``Simulation.__init__`` built it, and -``_build_current_law_simulation`` now builds it when it is first needed, so -these tests read ``baseline`` to build it). ``Simulation.clone`` copies the +``_build_current_law_simulation`` now builds it when it is first needed; +reading ``baseline`` builds it, so a test that clones before reading it gives +the clone a copy of its own built from the clone's inputs). ``Simulation.clone`` copies the instance dictionary, so a clone shared that branch with its source: calculations on the clone's baseline filled the source's, an input set on either one's baseline reached the other, ``clone.get_branch("baseline")`` diff --git a/tests/core/test_current_law_reads.py b/tests/core/test_current_law_reads.py index 6c9c480b2..c7ae40a7d 100644 --- a/tests/core/test_current_law_reads.py +++ b/tests/core/test_current_law_reads.py @@ -18,6 +18,8 @@ import copy as copy_module import functools +import gc +import weakref import numpy as np import pytest @@ -844,6 +846,74 @@ def test_assigning_baseline_on_a_read_only_simulation_raises(): assert simulation.compares_with_current_law is True +def _clone_announced_as_a_branch(simulation): + """Clone as policyengine-uk's subsample does, sharing arrays like a branch.""" + from policyengine_core.simulations.simulation import _BranchClone, _branch_clone + + request = _BranchClone(simulation) + token = _branch_clone.set(request) + try: + return simulation.clone() + finally: + request.pending = False + _branch_clone.reset(token) + + +def test_a_clone_announced_as_a_branch_builds_its_own_copy(): + simulation = _declared_simulation() + clone = _clone_announced_as_a_branch(simulation) + + clone.set_input("salary", MONTH_PERIOD, OTHER_MONTHLY_SALARY) + + _assert_income_tax( + clone.persons.current_law("declared_monthly_tax", MONTH_PERIOD), + OTHER_MONTHLY_SALARY, + BASELINE_RATE, + ) + assert clone.current_law_simulation().parent_branch is clone + assert "baseline" not in simulation.branches + + +def test_a_clone_announced_as_a_branch_does_not_keep_its_source_alive(): + simulation = _declared_simulation(reform=None) + clone = _clone_announced_as_a_branch(simulation) + source = weakref.ref(simulation) + + del simulation + gc.collect() + + assert source() is None + assert clone.compares_with_current_law is False + + +def test_assigning_baseline_on_a_saved_simulation_drops_the_saved_attribute(): + simulation = Simulation(situation=SITUATION, reform=REFORM) + branch = simulation.baseline + del simulation.__dict__["_current_law"] + simulation.__dict__["baseline"] = branch + separate = Simulation(situation=SITUATION) + + simulation.baseline = separate + + assert "baseline" not in simulation.__dict__ + clone = simulation.clone() + assert "baseline" not in clone.__dict__ + assert clone.baseline is separate + + +def test_a_traced_clone_of_a_built_copy_traces_its_copy_in_the_clone(): + simulation = _declared_simulation(trace=True) + copy = simulation.current_law_simulation() + assert copy.tracer is simulation.tracer + + clone = simulation.clone(trace=True) + + clone_copy = clone.branches["baseline"] + assert clone_copy is not copy + assert clone_copy.tracer is clone.tracer + assert clone_copy.trace + + def _node_named(nodes, name): for node in nodes: if node.name == name: From a6bc9250905e5592e8951a82101c52c7d4724423 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 2 Dec 2026 00:12:33 +0400 Subject: [PATCH 10/21] Check the announced clone's record instead of its source's lifetime The template's module-level system names the last simulation built from it, which keeps that simulation alive whatever the clone holds, so the test now checks that the clone's current-law record refers to the clone and not to its source. It fails before the fix. Co-Authored-By: Claude Opus 5.5 --- tests/core/test_current_law_reads.py | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/tests/core/test_current_law_reads.py b/tests/core/test_current_law_reads.py index c7ae40a7d..55ef0e58f 100644 --- a/tests/core/test_current_law_reads.py +++ b/tests/core/test_current_law_reads.py @@ -18,8 +18,6 @@ import copy as copy_module import functools -import gc -import weakref import numpy as np import pytest @@ -874,15 +872,19 @@ def test_a_clone_announced_as_a_branch_builds_its_own_copy(): assert "baseline" not in simulation.branches -def test_a_clone_announced_as_a_branch_does_not_keep_its_source_alive(): +def test_a_clone_announced_as_a_branch_does_not_refer_to_its_source(): + """Its current-law record must not keep the source alive. + + (A weak reference cannot show this: the template's module-level system + names the last simulation built from it, which keeps it alive anyway.) + """ simulation = _declared_simulation(reform=None) - clone = _clone_announced_as_a_branch(simulation) - source = weakref.ref(simulation) - del simulation - gc.collect() + clone = _clone_announced_as_a_branch(simulation) - assert source() is None + record = clone._current_law_source() + assert record.owner is clone + assert record.simulation is None assert clone.compares_with_current_law is False From 13aad57219df1f24c4cfa157ec7fb00b61f15a62 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 2 Dec 2026 00:12:33 +0400 Subject: [PATCH 11/21] Fix review round 3's findings on declared current-law reads - A clone announced as a branch outside get_branch (policyengine-uk's subsample announces one to share arrays) gets a current-law record of its own that does not refer to its source, so it no longer keeps the source alive, and builds its own copy from its own inputs. get_branch gives the branch its parent's record once the clone is made. - Assigning baseline drops a baseline kept in the instance dictionary by an earlier core, so clones and pickles no longer carry it. - Docstrings: current_law_system names the default system of the simulation the copy is built from; current_law_simulation states that the copy is registered, also on a read-only simulation; current_law states the exception for an assigned simulation; TraceNode.current_law_calls says the values read are children only when the calculating simulation shares the tracer. Co-Authored-By: Claude Opus 5.5 --- policyengine_core/populations/population.py | 3 +- policyengine_core/simulations/simulation.py | 60 ++++++++++++++++----- policyengine_core/tracers/trace_node.py | 4 +- 3 files changed, 53 insertions(+), 14 deletions(-) diff --git a/policyengine_core/populations/population.py b/policyengine_core/populations/population.py index 5d5ef4567..0bbecbb8b 100644 --- a/policyengine_core/populations/population.py +++ b/policyengine_core/populations/population.py @@ -191,7 +191,8 @@ def current_law( 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. Otherwise the + 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. diff --git a/policyengine_core/simulations/simulation.py b/policyengine_core/simulations/simulation.py index fd8f6bcdd..5af87fd8d 100644 --- a/policyengine_core/simulations/simulation.py +++ b/policyengine_core/simulations/simulation.py @@ -732,6 +732,30 @@ def get(self, make_read_only: bool) -> "Simulation": copy.make_read_only() return copy + def for_announced_branch( + self, source: "Simulation", clone: "Simulation" + ) -> "_CurrentLawSource": + """The record for a clone of ``source`` announced as a branch. + + ``get_branch`` replaces it with ``source``'s own record once the + clone is made, so its branches read ``source``'s copy. A caller that + announces a clone as a branch only to share arrays (as + policyengine-uk's subsample does) keeps this one: it does not refer to + ``source``, and a copy that is a branch of ``source`` is not kept, so + the clone builds its own from its own inputs when it needs one. A + simulation assigned to ``baseline`` that is not a branch of + ``source`` is shared, as ``clone`` shares it. + """ + copy = self.simulation + if copy is not None and getattr(copy, "parent_branch", None) is source: + copy = None + return _CurrentLawSource( + clone, + self.compares, + simulation=copy, + assigned=self.assigned and copy is not None, + ) + def for_clone( self, source: "Simulation", @@ -1255,10 +1279,10 @@ def current_law_system(self) -> "TaxBenefitSystem": """The tax-benefit system of current law, without building a copy. For a simulation that compares with current law, the system its - current-law copy calculates with (the class's - ``default_tax_benefit_system_instance`` unless a simulation was - assigned to ``baseline``); otherwise this simulation's own system. A - declared call, reported to the simulation's tracer. + current-law copy calculates with: the copy's, once built or assigned, + and before that the ``default_tax_benefit_system_instance`` of the + simulation it will be built from. Otherwise this simulation's own + system. A declared call, reported to the simulation's tracer. """ self._report_current_law_call("current_law_system") return self._current_law_system() @@ -1276,9 +1300,11 @@ def current_law_simulation(self) -> "Simulation": For a simulation that compares with current law, the current-law copy, built on the first call (by :meth:`_build_current_law_simulation`) - from the inputs the simulation holds then. A branch gets its parent's. - A copy core built is made read-only (see :meth:`make_read_only`); a - simulation assigned to ``baseline`` is returned as it was given. + from the inputs the simulation holds then, and registered in + ``branches`` as ``baseline``, on a read-only simulation too (unlike + its other branches). A branch gets its parent's. A copy core built is + made read-only (see :meth:`make_read_only`); a simulation assigned to + ``baseline`` is returned as it was given. Without a comparison, this simulation itself. A declared call, reported to the simulation's tracer. """ @@ -1323,6 +1349,9 @@ def baseline(self) -> Optional["Simulation"]: def baseline(self, simulation: Optional["Simulation"]) -> None: # It would change the values a read-only simulation's formulas read. refuse_on_read_only(self, "Assigning baseline") + # A simulation saved by an earlier core keeps ``baseline`` in its + # instance dictionary, which clones and pickles would still carry. + self.__dict__.pop("baseline", None) self.__dict__["_current_law"] = _CurrentLawSource( self, compares=simulation is not None, @@ -3624,12 +3653,17 @@ def clone( # A branch shares its parent's record of where its current-law # values come from: formulas that run in a branch read the parent's - # current-law copy. That holds for every clone of this simulation - # made while ``get_branch`` is making a branch of it, not only the - # one that shares its arrays (a subclass ``clone`` may clone it - # directly first; see ``_BranchClone``). + # current-law copy. ``get_branch`` gives the branch that record once + # the clone is made. Until then, every clone of this simulation made + # while it is announced as a branch's (not only the one that shares + # its arrays; a subclass ``clone`` may clone it directly first, and a + # country package may announce a clone only to share arrays; see + # ``_BranchClone``) gets a record of its own that does not refer to + # this simulation. branching = request is not None and request.simulation is self - if not branching and current_law.owner is self: + if branching: + new.__dict__["_current_law"] = current_law.for_announced_branch(self, new) + elif current_law.owner is self: # This simulation's own record. A shared copy filled this # simulation's caches with the clone's current-law calculations # and took inputs set through either, ``subsample`` of the clone @@ -3726,6 +3760,8 @@ def get_branch( finally: request.pending = False _branch_clone.reset(token) + # The branch reads this simulation's current-law copy (see ``clone``). + branch.__dict__["_current_law"] = self._current_law_source() if not self.read_only: self.branches[name] = branch branch.branch_name = name diff --git a/policyengine_core/tracers/trace_node.py b/policyengine_core/tracers/trace_node.py index 8e991d0d3..2b59e2f94 100644 --- a/policyengine_core/tracers/trace_node.py +++ b/policyengine_core/tracers/trace_node.py @@ -46,7 +46,9 @@ class TraceNode: # defaulted, including one masked by ``defined_for``. formula_ran: bool = False # The declared current-law calls the formula made (``CurrentLawCall``), - # in order. The values those calls read are children, as other reads are. + # in order. The values those calls read are children, as other reads are, + # when the simulation that calculates them shares this tracer (core's + # current-law copy does; a simulation assigned to ``baseline`` may not). current_law_calls: typing.List[CurrentLawCall] = dataclasses.field( default_factory=list ) From 0f4feafcd3bd2e08070ded41211d423cfae7186b Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 2 Dec 2026 18:51:39 +0400 Subject: [PATCH 12/21] Add tests for stored current-law values Tests that fail before the change: export, save, load and supply give the current-law copy's values for every registered variable and value type; ID arrays that differ are refused naming the entity; Enum values are supplied by member name; supplied values are calculated values, never inputs or uprating bases; a run with every read supplied builds no copy; a subsample drops the values and logs it; the file is one versioned HDF5 file. Co-Authored-By: Claude Opus 5.5 --- tests/core/test_current_law_values.py | 696 ++++++++++++++++++++++++++ 1 file changed, 696 insertions(+) create mode 100644 tests/core/test_current_law_values.py diff --git a/tests/core/test_current_law_values.py b/tests/core/test_current_law_values.py new file mode 100644 index 000000000..b978c37d5 --- /dev/null +++ b/tests/core/test_current_law_values.py @@ -0,0 +1,696 @@ +"""Stored current-law values: export, save, load and supply. + +A simulation without a reform exports the values of every variable that +declares ``current_law_read = True``, for the calculation year (and its months +for monthly variables), with each entity's ID array. The values are saved to +one HDF5 file, whose JSON manifest names the format and its version, and +loaded back. A reform simulation given them (``current_law_values=`` or +``supply_current_law_values``) checks each entity's ID array against them and +returns them for declared reads before building a current-law copy. A copy +that is built starts from them as calculated values, never as inputs. +""" + +from __future__ import annotations + +import datetime +import functools +import importlib +import inspect +import json +import logging + +import h5py +import numpy as np +import pytest + +from policyengine_core import errors +from policyengine_core.country_template import ( + CountryTaxBenefitSystem, + Microsimulation, + Simulation, +) +from policyengine_core.country_template.entities import Household, Person +from policyengine_core.enums import Enum, EnumArray +from policyengine_core.periods import ETERNITY, MONTH, YEAR, period +from policyengine_core.variables import Variable + +YEAR_PERIOD = "2022" +MONTH_PERIOD = "2022-01" +MONTHS = [f"2022-{month:02d}" for month in range(1, 13)] +INSTANT = "2022-01-01" +REFORM = {"taxes.income_tax_rate": {INSTANT: 0.42}} +SOURCE_RUN_ID = "current-law-run-1" +VALUES_LOGGER = "policyengine_core.simulations.current_law_values" + + +def _situation(person_names=("a", "b"), households=None): + salaries = {"a": 48000.0, "b": 30000.0} + if households is None: + households = {"h": list(person_names)} + return { + "persons": { + name: {"salary": {YEAR_PERIOD: salaries[name]}} for name in person_names + }, + "households": { + household: {"parents": members} for household, members in households.items() + }, + } + + +SITUATION = _situation() + + +class TaxBand(Enum): + LOW = "Low" + MEDIUM = "Medium" + HIGH = "High" + + +class ReorderedTaxBand(Enum): + HIGH = "High" + LOW = "Low" + MEDIUM = "Medium" + + +class TaxBandWithoutMedium(Enum): + LOW = "Low" + HIGH = "High" + + +def _tax_band_variable(band_class): + medium = getattr(band_class, "MEDIUM", band_class.HIGH) + + class stored_tax_band(Variable): + label = "Band of the month's income tax" + value_type = Enum + possible_values = band_class + default_value = band_class.LOW + entity = Person + definition_period = MONTH + current_law_read = True + + def formula(person, period, parameters): + tax = person("income_tax", period) + return np.where( + tax >= 1000, + band_class.HIGH, + np.where(tax >= 500, medium, band_class.LOW), + ) + + return stored_tax_band + + +# Registered variables of every value type core stores. + + +class stored_monthly_tax(Variable): + label = "Income tax in the month" + value_type = float + entity = Person + definition_period = MONTH + current_law_read = True + + def formula(person, period, parameters): + return person("income_tax", period) + + +class stored_household_yearly_tax(Variable): + label = "Household income tax in the year" + value_type = float + entity = Household + definition_period = YEAR + current_law_read = True + + def formula(household, period, parameters): + return household.sum(household.members("income_tax", period, options=["add"])) + + +class stored_pays_over_500(Variable): + label = "Whether the month's income tax is over 500" + value_type = bool + entity = Person + definition_period = MONTH + current_law_read = True + + def formula(person, period, parameters): + return person("income_tax", period) > 500 + + +class stored_tax_thousands(Variable): + label = "Whole thousands of the year's income tax" + value_type = int + entity = Person + definition_period = YEAR + current_law_read = True + + def formula(person, period, parameters): + return person("income_tax", period, options=["add"]) // 1000 + + +class stored_tax_label(Variable): + label = "A label naming the year's income tax in thousands" + value_type = str + entity = Person + definition_period = YEAR + current_law_read = True + + def formula(person, period, parameters): + thousands = person("stored_tax_thousands", period) + return np.array([f"thousands-{number}" for number in thousands], dtype=object) + + +class stored_tax_due_date(Variable): + label = "The day the year's income tax is due" + value_type = datetime.date + entity = Person + definition_period = YEAR + current_law_read = True + + def formula(person, period, parameters): + thousands = person("stored_tax_thousands", period) + return np.datetime64("2023-01-31") + thousands.astype("timedelta64[D]") + + +class stored_person_position(Variable): + label = "Each person's position, for all time" + value_type = int + entity = Person + definition_period = ETERNITY + current_law_read = True + + def formula(person, period, parameters): + return np.arange(person.count) + + +class stored_uprated_amount(Variable): + label = "An amount uprated by the income tax rate, with no formula" + value_type = float + entity = Person + definition_period = YEAR + current_law_read = True + uprating = "taxes.income_tax_rate" + + +class reads_a_supplied_value(Variable): + label = "The supplied current-law tax, or zero" + value_type = float + entity = Person + definition_period = MONTH + + def formula(person, period, parameters): + supplied = person.simulation.supplied_current_law_value( + "stored_monthly_tax", period + ) + return person.filled_array(0.0) if supplied is None else supplied + + +REGISTERED_VARIABLES = ( + stored_monthly_tax, + stored_household_yearly_tax, + stored_pays_over_500, + stored_tax_thousands, + stored_tax_label, + stored_tax_due_date, + stored_person_position, + stored_uprated_amount, +) + + +def _system_class(band_class): + class ValuesSystem(CountryTaxBenefitSystem): + def __init__(self, reform=None): + super().__init__(reform=reform) + for variable in REGISTERED_VARIABLES + ( + _tax_band_variable(band_class), + reads_a_supplied_value, + ): + self.add_variable(variable) + + return ValuesSystem + + +def _values_module(): + """The new module; fail on an assertion, not an error, while it is missing.""" + try: + module = importlib.import_module( + "policyengine_core.simulations.current_law_values" + ) + except ModuleNotFoundError: + module = None + assert module is not None, "policyengine_core.simulations.current_law_values" + assert hasattr(errors, "CurrentLawValuesMismatchError") + assert hasattr(Simulation, "supply_current_law_values") + assert hasattr(Simulation, "supplied_current_law_value") + assert "current_law_values" in inspect.signature(Simulation.__init__).parameters + return module + + +@functools.lru_cache(maxsize=None) +def _simulation_classes(band_class=TaxBand): + system_class = _system_class(band_class) + current_law_system = system_class() + + class ValuesSimulation(Simulation): + default_tax_benefit_system = system_class + default_tax_benefit_system_instance = current_law_system + + class ValuesMicrosimulation(Microsimulation): + default_tax_benefit_system = system_class + default_tax_benefit_system_instance = current_law_system + + return ValuesSimulation, ValuesMicrosimulation + + +def _simulation(reform=REFORM, situation=SITUATION, band_class=TaxBand, **options): + simulation_class, _ = _simulation_classes(band_class) + return simulation_class(situation=situation, reform=reform, **options) + + +def _microsimulation(reform=REFORM, **options): + _, microsimulation_class = _simulation_classes() + return microsimulation_class(reform=reform, **options) + + +def _exported(simulation=None, source_run_id=SOURCE_RUN_ID): + module = _values_module() + if simulation is None: + simulation = _simulation(reform=None) + return module.export_current_law_values( + simulation, YEAR_PERIOD, source_run_id=source_run_id + ) + + +def _registered_reads(): + """Each registered variable's entity, name and every period export saves.""" + system = _simulation_classes()[0].default_tax_benefit_system_instance + reads = [] + for variable in system.variables.values(): + if not variable.current_law_read: + continue + if variable.definition_period == MONTH: + variable_periods = MONTHS + elif variable.definition_period == YEAR: + variable_periods = [YEAR_PERIOD] + else: + variable_periods = [ETERNITY] + for variable_period in variable_periods: + reads.append((variable.entity.key, variable.name, variable_period)) + return reads + + +def _assert_same_values(actual, expected): + if isinstance(expected, EnumArray): + assert isinstance(actual, EnumArray) + np.testing.assert_array_equal(np.asarray(actual), np.asarray(expected)) + assert actual.possible_values is expected.possible_values + return + assert actual.dtype == expected.dtype + np.testing.assert_array_equal(actual, expected) + + +def _names(enum_array): + return [item.name for item in enum_array.decode()] + + +def test_export_save_load_and_supply_give_the_copys_values_for_every_registered_variable( + tmp_path, +): + module = _values_module() + exported = _exported() + path = tmp_path / "current_law_values.h5" + exported.save(path) + loaded = module.CurrentLawValues.load(path) + assert loaded.source_run_id == SOURCE_RUN_ID + + supplied = _simulation(current_law_values=loaded) + calculated = _simulation() + reads = _registered_reads() + assert len(reads) == 12 * 3 + 5 # three monthly, four yearly, one eternal + + for entity_key, variable, variable_period in reads: + expected = calculated.populations[entity_key].current_law( + variable, variable_period + ) + actual = supplied.populations[entity_key].current_law(variable, variable_period) + _assert_same_values(actual, expected) + # The reform changes these, so the reads above did not return its values. + assert not np.array_equal( + supplied.persons("stored_monthly_tax", MONTH_PERIOD), + supplied.persons.current_law("stored_monthly_tax", MONTH_PERIOD), + ) + assert _names(supplied.persons.current_law("stored_tax_band", MONTH_PERIOD)) == [ + "MEDIUM", + "LOW", + ] + assert list(supplied.persons.current_law("stored_tax_label", YEAR_PERIOD)) == [ + "thousands-7", + "thousands-4", + ] + + +def test_a_run_with_every_read_supplied_builds_no_copy(): + simulation = _simulation(current_law_values=_exported()) + + for entity_key, variable, variable_period in _registered_reads(): + simulation.populations[entity_key].current_law(variable, variable_period) + + assert "baseline" not in simulation.branches + # A run without the values builds the copy for the same reads. + without = _simulation() + without.persons.current_law("stored_monthly_tax", MONTH_PERIOD) + assert "baseline" in without.branches + + +def test_a_period_that_was_not_supplied_is_calculated_by_the_copy(): + simulation = _simulation(current_law_values=_exported()) + calculated = _simulation() + + for variable, variable_period in [ + ("stored_monthly_tax", "2023-01"), + ("stored_tax_thousands", "2023"), + ]: + _assert_same_values( + simulation.persons.current_law(variable, variable_period), + calculated.persons.current_law(variable, variable_period), + ) + assert "baseline" in simulation.branches + + +@pytest.mark.parametrize("supplied_through", ["constructor", "method"]) +@pytest.mark.parametrize( + "situation, entity", + [ + pytest.param( + _situation(households={"h1": ["a"], "h2": ["b"]}), + "household", + id="a-household-dropped", + ), + pytest.param( + _situation(person_names=("b", "a")), "person", id="two-people-swapped" + ), + ], +) +def test_an_id_array_that_differs_is_refused_naming_the_entity( + situation, entity, supplied_through +): + _values_module() + # The values come from a run with one household of two people, a then b. + exported = _exported() + + with pytest.raises(errors.CurrentLawValuesMismatchError) as raised: + if supplied_through == "constructor": + _simulation(situation=situation, current_law_values=exported) + else: + _simulation(situation=situation).supply_current_law_values(exported) + + assert raised.value.entity == entity + assert entity in str(raised.value) + assert isinstance(raised.value, ValueError) + + +def test_values_supplied_after_construction_are_checked_and_read(): + simulation = _simulation() + exported = _exported() + + simulation.supply_current_law_values(exported) + + expected = _simulation().persons.current_law("stored_monthly_tax", MONTH_PERIOD) + np.testing.assert_array_equal( + simulation.persons.current_law("stored_monthly_tax", MONTH_PERIOD), expected + ) + assert "baseline" not in simulation.branches + + +def test_a_supplied_value_is_not_an_input_and_never_an_uprating_base(): + module = _values_module() + current_law = _simulation(reform=None) + supplied_amount = np.array([100.0, 200.0], dtype=np.float32) + values = module.CurrentLawValues( + arrays={ + ( + "stored_uprated_amount", + module.PeriodKey.from_period(period(YEAR_PERIOD)), + ): supplied_amount + }, + entity_ids={ + key: np.asarray(population.ids) + for key, population in current_law.populations.items() + }, + ) + simulation = _simulation(current_law_values=values) + + np.testing.assert_array_equal( + simulation.persons.current_law("stored_uprated_amount", YEAR_PERIOD), + supplied_amount, + ) + copy = simulation.current_law_simulation() + # The copy starts from the supplied value, as a calculated value. + np.testing.assert_array_equal( + copy.calculate("stored_uprated_amount", YEAR_PERIOD), supplied_amount + ) + assert "stored_uprated_amount" not in simulation.input_variables + assert "stored_uprated_amount" not in copy.input_variables + assert "stored_uprated_amount" not in copy.get_input_variables( + include_computed_variables=False + ) + # An input would be uprated into the next year; a calculated value is not. + np.testing.assert_array_equal( + simulation.persons.current_law("stored_uprated_amount", "2023"), [0.0, 0.0] + ) + + +def test_a_copy_built_with_supplied_values_starts_from_them(): + module = _values_module() + exported = _exported() + # Values that differ from what current law calculates, so a copy that + # recalculated them would show it. + month_key = ( + "stored_monthly_tax", + module.PeriodKey.from_period(period(MONTH_PERIOD)), + ) + altered_arrays = dict(exported.arrays) + altered_arrays[month_key] = np.array([1.0, 2.0], dtype=np.float32) + altered = module.CurrentLawValues( + arrays=altered_arrays, + entity_ids=exported.entity_ids, + source_run_id=exported.source_run_id, + enum_members=exported.enum_members, + ) + simulation = _simulation(current_law_values=altered) + + copy = simulation.current_law_simulation() + + np.testing.assert_array_equal( + copy.calculate("stored_monthly_tax", MONTH_PERIOD), [1.0, 2.0] + ) + # A branch of the copy starts from them too. + branch = copy.get_branch("scratch") + np.testing.assert_array_equal( + branch.calculate("stored_monthly_tax", MONTH_PERIOD), [1.0, 2.0] + ) + + +def test_a_supplied_read_returns_a_read_only_array(): + simulation = _simulation(current_law_values=_exported()) + + values = simulation.persons.current_law("stored_monthly_tax", MONTH_PERIOD) + + assert not values.flags.writeable + with pytest.raises(ValueError): + values[0] = 0.0 + + +def test_supplied_current_law_value_returns_the_supplied_array_or_none(): + exported = _exported() + simulation = _simulation(current_law_values=exported) + expected = _simulation().persons.current_law("stored_monthly_tax", MONTH_PERIOD) + + np.testing.assert_array_equal( + simulation.supplied_current_law_value("stored_monthly_tax", MONTH_PERIOD), + expected, + ) + assert ( + simulation.supplied_current_law_value("stored_monthly_tax", "2023-01") is None + ) + assert "baseline" not in simulation.branches + # Without supplied values, and without a reform, there is nothing supplied. + assert ( + _simulation().supplied_current_law_value("stored_monthly_tax", MONTH_PERIOD) + is None + ) + no_reform = _simulation(reform=None, current_law_values=exported) + assert ( + no_reform.supplied_current_law_value("stored_monthly_tax", MONTH_PERIOD) is None + ) + # It is a declared call: an undeclared variable raises. + with pytest.raises(errors.UndeclaredCurrentLawReadError, match="income_tax"): + simulation.supplied_current_law_value("income_tax", MONTH_PERIOD) + + +def test_supplied_current_law_value_is_reported_to_the_tracer(): + simulation = _simulation(current_law_values=_exported(), trace=True) + + simulation.calculate("reads_a_supplied_value", MONTH_PERIOD) + + node = next( + node + for node in simulation.tracer.trees + if node.name == "reads_a_supplied_value" + ) + assert [ + (call.call, call.variable, str(call.period)) for call in node.current_law_calls + ] == [("supplied_current_law_value", "stored_monthly_tax", MONTH_PERIOD)] + + +def test_enum_values_are_supplied_by_member_name(): + _values_module() + exported = _exported() + + simulation = _simulation(band_class=ReorderedTaxBand, current_law_values=exported) + bands = simulation.persons.current_law("stored_tax_band", MONTH_PERIOD) + + assert bands.possible_values is ReorderedTaxBand + assert _names(bands) == ["MEDIUM", "LOW"] + assert "baseline" not in simulation.branches + + +def test_an_enum_member_the_current_class_lacks_is_refused_naming_the_variable(): + _values_module() + exported = _exported() + + with pytest.raises(errors.CurrentLawValuesMismatchError) as raised: + _simulation(band_class=TaxBandWithoutMedium, current_law_values=exported) + + assert raised.value.variable == "stored_tax_band" + assert "stored_tax_band" in str(raised.value) + assert "MEDIUM" in str(raised.value) + + +def test_clones_and_branches_keep_the_supplied_values(): + simulation = _simulation(current_law_values=_exported()) + expected = _simulation().persons.current_law("stored_monthly_tax", MONTH_PERIOD) + + clone = simulation.clone() + branch = simulation.get_branch("scratch") + + for reader in (clone, branch): + np.testing.assert_array_equal( + reader.persons.current_law("stored_monthly_tax", MONTH_PERIOD), expected + ) + assert "baseline" not in simulation.branches + assert "baseline" not in clone.branches + + +def test_supplying_is_refused_once_the_copy_is_built(): + exported = _exported() + simulation = _simulation() + simulation.current_law_simulation() + + with pytest.raises(ValueError, match="current-law copy"): + simulation.supply_current_law_values(exported) + + +def test_supplying_is_refused_on_a_read_only_simulation(): + exported = _exported() + simulation = _simulation() + simulation.make_read_only() + + with pytest.raises(errors.ReadOnlySimulationError): + simulation.supply_current_law_values(exported) + + +def test_export_refuses_a_simulation_that_compares_with_current_law(): + module = _values_module() + + with pytest.raises(ValueError, match="compares with current law"): + module.export_current_law_values(_simulation(), YEAR_PERIOD) + + +def test_the_file_is_one_hdf5_file_with_a_versioned_manifest(tmp_path): + module = _values_module() + path = tmp_path / "values.h5" + + _exported().save(path) + + assert [item.name for item in tmp_path.iterdir()] == ["values.h5"] + with h5py.File(path, "r") as file: + manifest = json.loads(file.attrs["manifest"]) + assert manifest["format"] == module.FORMAT_NAME + assert manifest["format_version"] == module.FORMAT_VERSION == 1 + assert manifest["source_run_id"] == SOURCE_RUN_ID + assert manifest["calculated_values"] is True + listed = { + (entry["variable"], entry["period"]["unit"], entry["period"]["start"]) + for entry in manifest["arrays"] + } + assert ("stored_monthly_tax", "month", "2022-03-01") in listed + assert ("stored_person_position", "eternity", "0001-01-01") in listed + band = next( + entry for entry in manifest["arrays"] if entry["variable"] == "stored_tax_band" + ) + assert band["enum_members"] == ["LOW", "MEDIUM", "HIGH"] + assert {entity["key"] for entity in manifest["entities"]} == {"person", "household"} + + +def test_load_refuses_another_format_or_a_newer_version(tmp_path): + module = _values_module() + path = tmp_path / "values.h5" + _exported().save(path) + with h5py.File(path, "r") as file: + manifest = json.loads(file.attrs["manifest"]) + + for changes, message in [ + ({"format": "something else"}, "format"), + ({"format_version": module.FORMAT_VERSION + 1}, "version"), + ]: + with h5py.File(path, "a") as file: + file.attrs["manifest"] = json.dumps({**manifest, **changes}) + with pytest.raises(ValueError, match=message): + module.CurrentLawValues.load(path) + + +def test_load_ignores_groups_it_does_not_know(tmp_path): + module = _values_module() + path = tmp_path / "values.h5" + exported = _exported() + exported.save(path) + with h5py.File(path, "a") as file: + file.create_group("seeds").create_dataset("extra", data=np.arange(3)) + + loaded = module.CurrentLawValues.load(path) + + assert set(loaded.arrays) == set(exported.arrays) + for key, array in exported.arrays.items(): + np.testing.assert_array_equal(loaded.arrays[key], array) + + +def test_a_subsampled_reform_simulation_drops_its_supplied_values_and_logs_it( + tmp_path, caplog +): + module = _values_module() + path = tmp_path / "values.h5" + module.export_current_law_values( + _microsimulation(reform=None), YEAR_PERIOD, source_run_id=SOURCE_RUN_ID + ).save(path) + supplied = _microsimulation(current_law_values=module.CurrentLawValues.load(path)) + without = _microsimulation() + + with caplog.at_level(logging.WARNING, logger=VALUES_LOGGER): + supplied.subsample(n=3, seed="current-law-values", time_period=YEAR_PERIOD) + without.subsample(n=3, seed="current-law-values", time_period=YEAR_PERIOD) + + records = [record for record in caplog.records if record.name == VALUES_LOGGER] + assert len(records) == 1 + assert records[0].levelno == logging.WARNING + assert SOURCE_RUN_ID in records[0].getMessage() + assert ( + supplied.supplied_current_law_value("stored_monthly_tax", MONTH_PERIOD) is None + ) + for variable, variable_period in [ + ("stored_monthly_tax", MONTH_PERIOD), + ("stored_tax_thousands", YEAR_PERIOD), + ]: + np.testing.assert_array_equal( + supplied.persons.current_law(variable, variable_period), + without.persons.current_law(variable, variable_period), + ) From 24da6442ec7f24c7e490bdf2da5eeadc1addd9b8 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 2 Dec 2026 18:56:09 +0400 Subject: [PATCH 13/21] Count five yearly registered variables in the export test Co-Authored-By: Claude Opus 5.5 --- tests/core/test_current_law_values.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/core/test_current_law_values.py b/tests/core/test_current_law_values.py index b978c37d5..fecd6b7b6 100644 --- a/tests/core/test_current_law_values.py +++ b/tests/core/test_current_law_values.py @@ -325,7 +325,7 @@ def test_export_save_load_and_supply_give_the_copys_values_for_every_registered_ supplied = _simulation(current_law_values=loaded) calculated = _simulation() reads = _registered_reads() - assert len(reads) == 12 * 3 + 5 # three monthly, four yearly, one eternal + assert len(reads) == 12 * 3 + 6 # three monthly, five yearly, one eternal for entity_key, variable, variable_period in reads: expected = calculated.populations[entity_key].current_law( From 8ccf920ef97a89ac0e65c1b3efbf700c6e9530f0 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 2 Dec 2026 18:57:27 +0400 Subject: [PATCH 14/21] Add tests that pickled values and deep-copied simulations keep supplied values Co-Authored-By: Claude Opus 5.5 --- tests/core/test_current_law_values.py | 39 +++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/tests/core/test_current_law_values.py b/tests/core/test_current_law_values.py index fecd6b7b6..fcb7c352a 100644 --- a/tests/core/test_current_law_values.py +++ b/tests/core/test_current_law_values.py @@ -12,12 +12,14 @@ from __future__ import annotations +import copy import datetime import functools import importlib import inspect import json import logging +import pickle import h5py import numpy as np @@ -694,3 +696,40 @@ def test_a_subsampled_reform_simulation_drops_its_supplied_values_and_logs_it( supplied.persons.current_law(variable, variable_period), without.persons.current_law(variable, variable_period), ) + + +def _result_or_error(action): + try: + return action(), None + except Exception as error: # reported by the assertion that follows + return None, error + + +def test_pickled_values_stay_equal_and_read_only(): + exported = _exported() + + restored, error = _result_or_error(lambda: pickle.loads(pickle.dumps(exported))) + + assert error is None, f"pickling CurrentLawValues raised {error!r}" + assert restored.source_run_id == exported.source_run_id + assert dict(restored.enum_members) == dict(exported.enum_members) + assert set(restored.arrays) == set(exported.arrays) + for key, array in exported.arrays.items(): + np.testing.assert_array_equal(restored.arrays[key], array) + assert not restored.arrays[key].flags.writeable + for entity_key, ids in exported.entity_ids.items(): + np.testing.assert_array_equal(restored.entity_ids[entity_key], ids) + assert not restored.entity_ids[entity_key].flags.writeable + + +def test_a_deep_copied_simulation_keeps_its_supplied_values(): + simulation = _simulation(current_law_values=_exported()) + expected = _simulation().persons.current_law("stored_tax_band", MONTH_PERIOD) + + restored, error = _result_or_error(lambda: copy.deepcopy(simulation)) + + assert error is None, f"deep-copying the simulation raised {error!r}" + bands = restored.persons.current_law("stored_tax_band", MONTH_PERIOD) + _assert_same_values(bands, expected) + assert not bands.flags.writeable + assert "baseline" not in restored.branches From 87f832dcb58f71fdf29ebb9bc5cb03706519ecb8 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 2 Dec 2026 18:59:23 +0400 Subject: [PATCH 15/21] Add stored current-law values: export, save, load and supply export_current_law_values calculates every variable that declares current_law_read = True on a simulation without a reform (the calculation year, its months for monthly variables, eternity for eternal ones) and returns a CurrentLawValues with each entity's ID array and the source run id. save and load write one HDF5 file whose JSON manifest names the format and its version; load refuses another format or a newer version and ignores groups it does not list. Numbers, booleans, dates, strings and Enum values are kept, Enum values as positions with their member names. A simulation takes them with current_law_values= or supply_current_law_values, which checks each entity's ID array element by element and maps Enum values to the current-law system's Enum classes by member name, raising CurrentLawValuesMismatchError naming the entity or variable. Declared reads and supplied_current_law_value return supplied values, not writable, without building the current-law copy; a copy core builds starts from them as calculated values, never inputs. Clones and branches keep them; subsample drops them and logs a warning. Co-Authored-By: Claude Opus 5.5 --- changelog.d/current-law-values.added.md | 1 + docs/python_api/errors.md | 15 + docs/python_api/simulations.md | 41 ++ policyengine_core/errors/__init__.py | 1 + .../current_law_values_mismatch_error.py | 25 + policyengine_core/populations/population.py | 23 +- policyengine_core/simulations/__init__.py | 5 + .../simulations/current_law_values.py | 579 ++++++++++++++++++ policyengine_core/simulations/simulation.py | 149 +++++ 9 files changed, 828 insertions(+), 11 deletions(-) create mode 100644 changelog.d/current-law-values.added.md create mode 100644 policyengine_core/errors/current_law_values_mismatch_error.py create mode 100644 policyengine_core/simulations/current_law_values.py diff --git a/changelog.d/current-law-values.added.md b/changelog.d/current-law-values.added.md new file mode 100644 index 000000000..2ef9cd4de --- /dev/null +++ b/changelog.d/current-law-values.added.md @@ -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, then returns them for declared reads, and through `supplied_current_law_value`, without building its current-law copy. diff --git a/docs/python_api/errors.md b/docs/python_api/errors.md index 8b9963358..a035c027b 100644 --- a/docs/python_api/errors.md +++ b/docs/python_api/errors.md @@ -2,6 +2,21 @@ `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: an entity's ID array differs from the saved one +(`entity` names it), or a saved Enum value names a member the variable's Enum +class lacks (`variable` names it). + +```{eval-rst} +.. autoclass:: policyengine_core.errors.current_law_values_mismatch_error.CurrentLawValuesMismatchError + :members: + :undoc-members: + :show-inheritance: +``` + ## NANCreationError ```{eval-rst} diff --git a/docs/python_api/simulations.md b/docs/python_api/simulations.md index 5189ba9cc..5b3df4b40 100644 --- a/docs/python_api/simulations.md +++ b/docs/python_api/simulations.md @@ -69,6 +69,47 @@ 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`, 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, and maps each +Enum value to the variable's Enum class in the current-law system by member +name; either 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). 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. Clones and branches keep them; `subsample` drops them and +logs a warning on the `policyengine_core.simulations.current_law_values` +logger. Supplying values once the copy core builds exists raises `ValueError`. + ## Microsimulation ```{eval-rst} diff --git a/policyengine_core/errors/__init__.py b/policyengine_core/errors/__init__.py index 74e5370c7..3d4651d47 100644 --- a/policyengine_core/errors/__init__.py +++ b/policyengine_core/errors/__init__.py @@ -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 diff --git a/policyengine_core/errors/current_law_values_mismatch_error.py b/policyengine_core/errors/current_law_values_mismatch_error.py new file mode 100644 index 000000000..586d7279f --- /dev/null +++ b/policyengine_core/errors/current_law_values_mismatch_error.py @@ -0,0 +1,25 @@ +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 a saved + Enum value names a member 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 diff --git a/policyengine_core/populations/population.py b/policyengine_core/populations/population.py index 0bbecbb8b..6e6b3b101 100644 --- a/policyengine_core/populations/population.py +++ b/policyengine_core/populations/population.py @@ -201,6 +201,11 @@ def current_law( ``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. + Example, for a variable ``income_tax`` declaring ``current_law_read = True``: @@ -213,25 +218,21 @@ def current_law( a read-only simulation stores: a formula that writes into what it read must copy it first. """ - from policyengine_core.errors import UndeclaredCurrentLawReadError - # Before anything is built, so a missing period names the caller. self.check_period_validity(variable_name, period) simulation = self.simulation - variable = simulation._current_law_system().get_variable( - variable_name, check_existence=True + variable = simulation._declared_current_law_variable( + variable_name, "current_law" ) - if not variable.current_law_read: - raise UndeclaredCurrentLawReadError( - f'The variable "{variable_name}" does not declare ' - "current_law_read = True, so formulas may not read its " - "current-law value with current_law(). Declare it on the " - "variable." - ) 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 diff --git a/policyengine_core/simulations/__init__.py b/policyengine_core/simulations/__init__.py index c992f3a2b..20f77e18b 100644 --- a/policyengine_core/simulations/__init__.py +++ b/policyengine_core/simulations/__init__.py @@ -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 diff --git a/policyengine_core/simulations/current_law_values.py b/policyengine_core/simulations/current_law_values.py new file mode 100644 index 000000000..d40b7271c --- /dev/null +++ b/policyengine_core/simulations/current_law_values.py @@ -0,0 +1,579 @@ +"""Stored current-law values: export, save, load and the stored form. + +A simulation without a reform calculates the current-law values that a reform +simulation over the same population would otherwise calculate again on its +current-law copy. :func:`export_current_law_values` calculates the value of +every variable that declares ``current_law_read = True``, for the calculation +year, its twelve months for monthly variables, or eternity for eternal ones, +and returns them with each entity's ID array as a :class:`CurrentLawValues`. +:meth:`CurrentLawValues.save` writes them to one HDF5 file whose JSON manifest +names the format and its version; :meth:`CurrentLawValues.load` reads it back. + +A reform simulation takes them with ``Simulation(..., current_law_values=...)`` +or ``Simulation.supply_current_law_values``. It checks only that each entity's +ID array equals the supplied one (and maps Enum values to its own Enum +classes by member name); every other check on where the values came from +belongs to the caller. Every supplied array is a calculated value: never an +input, so uprating and carry-over never start from one. +""" + +from __future__ import annotations + +import dataclasses +import json +import logging +import os +from importlib import metadata +from pathlib import Path +from types import MappingProxyType +from typing import TYPE_CHECKING, Dict, Mapping, Optional, Tuple, Union + +import h5py +import numpy as np + +from policyengine_core import periods +from policyengine_core.enums import ENUM_ARRAY_DTYPE, Enum, EnumArray +from policyengine_core.periods import Period + +if TYPE_CHECKING: + from policyengine_core.simulations.simulation import Simulation + +LOGGER = logging.getLogger(__name__) +"""Logs what happens to supplied values, such as a subsample dropping them.""" + +FORMAT_NAME = "policyengine-core current-law values" +"""The ``format`` a saved file's manifest names.""" + +FORMAT_VERSION = 1 +"""The version of the format this core writes, and the newest it reads. + +A later format that extends this one (a seeds file, for instance) adds groups +and raises the version; this core ignores groups its manifest does not list, +and refuses a version newer than its own. +""" + +MANIFEST_ATTRIBUTE = "manifest" +"""The root attribute of a saved file that holds its JSON manifest.""" + +STRING_DTYPE_LABEL = "str" +"""The dtype a manifest names for strings, saved as UTF-8.""" + + +@dataclasses.dataclass(frozen=True) +class PeriodKey: + """A period as stored values are keyed by: unit, first day, and size. + + Not ``str(period)``, which does not always give back the period it came + from. ``size`` is ``None`` for eternity. + """ + + unit: str + start: str + size: Optional[int] + + @classmethod + def from_period(cls, period: Union[Period, str]) -> "PeriodKey": + period = periods.period(period) + if period.unit == periods.ETERNITY: + return cls(periods.ETERNITY, str(period.start), None) + return cls(period.unit, str(period.start), int(period.size)) + + def to_period(self) -> Period: + if self.unit == periods.ETERNITY: + return periods.period(periods.ETERNITY) + return Period((self.unit, periods.instant(self.start), self.size)) + + def to_json(self) -> dict: + return {"unit": self.unit, "start": self.start, "size": self.size} + + @classmethod + def from_json(cls, data: Mapping) -> "PeriodKey": + size = data["size"] + return cls( + str(data["unit"]), str(data["start"]), None if size is None else int(size) + ) + + +ValueKey = Tuple[str, PeriodKey] +"""A stored value's key: the variable's name and its period.""" + + +def _read_only(array: np.ndarray) -> np.ndarray: + array.flags.writeable = False + return array + + +def _sort_key(item) -> tuple: + (variable, key), _array = item + return (variable, key.unit, key.start, -1 if key.size is None else key.size) + + +class CurrentLawValues: + """Current-law values calculated by a simulation run without a reform. + + ``arrays`` maps ``(variable name, PeriodKey)`` to the value, one element + per member of the variable's entity, in the order of that entity's ID + array in ``entity_ids`` (entity key to ID array). Enum values are kept as + positions, with the member names in position order in ``enum_members`` + (variable name to names); an ``EnumArray`` given without them gives its + own class's names. ``source_run_id`` names the simulation run they came + from, for the caller's logs and checks; core does not read it. + + Every array is copied when the object is made and is not writable. Every + array is a calculated value (``calculated_values``), never an input. + """ + + calculated_values = True + + def __init__( + self, + arrays: Mapping[ValueKey, np.ndarray], + entity_ids: Mapping[str, np.ndarray], + source_run_id: Optional[str] = None, + enum_members: Optional[Mapping[str, Tuple[str, ...]]] = None, + ): + members = {name: tuple(names) for name, names in (enum_members or {}).items()} + stored = {} + for key, array in arrays.items(): + variable, period_key = key + if not isinstance(variable, str) or not isinstance(period_key, PeriodKey): + raise TypeError( + "CurrentLawValues keys are (variable name, PeriodKey) pairs; " + f"got {key!r}." + ) + if isinstance(array, EnumArray) and variable not in members: + if array.possible_values is None: + raise ValueError( + f'The Enum value of "{variable}" has no Enum class, so its ' + "member names are unknown; give them in enum_members." + ) + members[variable] = tuple(item.name for item in array.possible_values) + if variable in members: + array = np.asarray(array).astype(ENUM_ARRAY_DTYPE, copy=True) + else: + array = np.array(array, copy=True) + if array.ndim != 1: + raise ValueError( + f'The value of "{variable}" for {period_key} is not a ' + "one-dimensional array." + ) + stored[(variable, period_key)] = _read_only(array) + unused = set(members) - {variable for variable, _ in stored} + if unused: + raise ValueError( + f"enum_members names variables with no value: {sorted(unused)}." + ) + # Plain dictionaries, so the object pickles and deep-copies; the + # properties hand out read-only views of them. + self._arrays = stored + self._entity_ids = { + key: _read_only(np.array(ids, copy=True)) for key, ids in entity_ids.items() + } + self._enum_members = members + self.source_run_id = source_run_id + + def __setstate__(self, state: dict) -> None: + # Unpickled and deep-copied arrays come back writable. + self.__dict__.update(state) + for array in list(self._arrays.values()) + list(self._entity_ids.values()): + _read_only(array) + + @property + def arrays(self) -> Mapping[ValueKey, np.ndarray]: + return MappingProxyType(self._arrays) + + @property + def entity_ids(self) -> Mapping[str, np.ndarray]: + return MappingProxyType(self._entity_ids) + + @property + def enum_members(self) -> Mapping[str, Tuple[str, ...]]: + return MappingProxyType(self._enum_members) + + def get(self, variable: str, period: Union[Period, str]) -> Optional[np.ndarray]: + """The stored array for ``variable`` and ``period``, or ``None``. + + An Enum value is given as positions (see ``enum_members``). + """ + return self._arrays.get((variable, PeriodKey.from_period(period))) + + def __repr__(self) -> str: + return ( + f"CurrentLawValues({len(self._arrays)} arrays, entities " + f"{sorted(self._entity_ids)}, source_run_id={self.source_run_id!r})" + ) + + def save(self, path: Union[str, os.PathLike]) -> None: + """Write the values to one HDF5 file at ``path``. + + The file holds each entity's ID array under ``entity_ids/``, + each value under ``arrays/``, and, in its root attribute + ``manifest``, a JSON manifest: the format and its version, the + policyengine-core version that wrote it, ``source_run_id``, + ``calculated_values``, and for each array its dataset, dtype, + variable, period and (for an Enum value) member names. The file is + written beside ``path`` first and then moved into place, so a reader + never sees a part-written file. + """ + path = Path(path) + temporary_path = path.with_name(f"{path.name}.partial") + try: + with h5py.File(temporary_path, "w") as file: + entities = [] + for entity_key, ids in sorted(self._entity_ids.items()): + dataset = f"entity_ids/{entity_key}" + entities.append( + { + "key": entity_key, + "dataset": dataset, + "dtype": _write_array(file, dataset, ids, entity_key), + } + ) + entries = [] + for index, ((variable, key), array) in enumerate( + sorted(self._arrays.items(), key=_sort_key) + ): + dataset = f"arrays/{index}" + entry = { + "variable": variable, + "period": key.to_json(), + "dataset": dataset, + "dtype": _write_array(file, dataset, array, variable), + } + if variable in self._enum_members: + entry["enum_members"] = list(self._enum_members[variable]) + entries.append(entry) + manifest = { + "format": FORMAT_NAME, + "format_version": FORMAT_VERSION, + "policyengine_core_version": _core_version(), + "source_run_id": self.source_run_id, + "calculated_values": self.calculated_values, + "entities": entities, + "arrays": entries, + } + file.attrs[MANIFEST_ATTRIBUTE] = json.dumps(manifest, sort_keys=True) + os.replace(temporary_path, path) + finally: + if temporary_path.exists(): + temporary_path.unlink() + + @classmethod + def load(cls, path: Union[str, os.PathLike]) -> "CurrentLawValues": + """Read values :meth:`save` wrote. + + Refuses a file whose manifest names another format, or a version of + this format newer than this core's (``FORMAT_VERSION``). Groups and + datasets the manifest does not list are ignored. + """ + with h5py.File(path, "r") as file: + raw_manifest = file.attrs.get(MANIFEST_ATTRIBUTE) + if raw_manifest is None: + raise ValueError( + f"{path} has no '{MANIFEST_ATTRIBUTE}' attribute, so it is not a " + f"file of the format '{FORMAT_NAME}'." + ) + manifest = json.loads(raw_manifest) + if manifest.get("format") != FORMAT_NAME: + raise ValueError( + f"{path} is a file of the format {manifest.get('format')!r}, " + f"not '{FORMAT_NAME}'." + ) + version = manifest.get("format_version") + if ( + not isinstance(version, int) + or isinstance(version, bool) + or not 1 <= version <= FORMAT_VERSION + ): + raise ValueError( + f"{path} has format version {version!r}; this policyengine-core " + f"reads versions 1 to {FORMAT_VERSION}." + ) + entity_ids = { + entity["key"]: _read_array(file, entity["dataset"], entity["dtype"]) + for entity in manifest["entities"] + } + arrays = {} + enum_members: Dict[str, Tuple[str, ...]] = {} + for entry in manifest["arrays"]: + variable = entry["variable"] + key = (variable, PeriodKey.from_json(entry["period"])) + arrays[key] = _read_array(file, entry["dataset"], entry["dtype"]) + if "enum_members" in entry: + names = tuple(entry["enum_members"]) + if enum_members.setdefault(variable, names) != names: + raise ValueError( + f'{path} lists different Enum members for "{variable}" ' + "in different periods." + ) + return cls( + arrays, + entity_ids, + source_run_id=manifest.get("source_run_id"), + enum_members=enum_members, + ) + + +def _write_array(file: h5py.File, dataset: str, array: np.ndarray, name: str) -> str: + """Write ``array`` and return the dtype label the manifest records.""" + kind = array.dtype.kind + if kind in "biuf": + file.create_dataset(dataset, data=array) + return str(array.dtype) + if kind == "M": + file.create_dataset(dataset, data=array.view(np.int64)) + return str(array.dtype) + if kind in "USO": + strings = [] + for value in array: + if isinstance(value, bytes): + value = value.decode("utf-8") + if not isinstance(value, str): + raise TypeError( + f'The array for "{name}" holds {type(value).__name__} ' + "values; stored current-law values hold numbers, booleans, " + "dates, strings and Enum values." + ) + strings.append(value) + file.create_dataset( + dataset, + data=np.array(strings, dtype=object), + dtype=h5py.string_dtype("utf-8"), + ) + return STRING_DTYPE_LABEL + raise TypeError( + f'The array for "{name}" has dtype {array.dtype}; stored current-law ' + "values hold numbers, booleans, dates, strings and Enum values." + ) + + +def _read_array(file: h5py.File, dataset: str, dtype_label: str) -> np.ndarray: + data = file[dataset] + if dtype_label == STRING_DTYPE_LABEL: + return np.array(data.asstr()[()], dtype=object) + if dtype_label.startswith("datetime64"): + return np.asarray(data[()], dtype=np.int64).view(dtype_label) + return np.asarray(data[()], dtype=np.dtype(dtype_label)) + + +def _core_version() -> Optional[str]: + try: + return metadata.version("policyengine-core") + except metadata.PackageNotFoundError: + return None + + +def export_current_law_values( + simulation: "Simulation", + period: Union[Period, str, None] = None, + source_run_id: Optional[str] = None, +) -> CurrentLawValues: + """Calculate and return a simulation's registered current-law values. + + For every variable of the simulation's tax-benefit system that declares + ``current_law_read = True``: a yearly variable's value for ``period``, a + monthly variable's for each of its twelve months, and an eternal + variable's once. A variable defined for another unit (days) is left out, + with a warning on this module's logger, and a reform simulation reading + it calculates it. Each entity's ID array is saved with them. + + ``period`` is the calculation year, by default the simulation's + ``default_calculation_period``. The simulation must not compare with + current law (built with a reform, or given a ``baseline``): its own values + are what is exported. ``source_run_id`` is kept with the values. + """ + if simulation._current_law_source().compares: + raise ValueError( + "export_current_law_values needs a simulation without a reform: this " + "one compares with current law, so its own values are not current " + "law's." + ) + if period is None: + period = simulation.default_calculation_period + if period is None: + raise ValueError( + "export_current_law_values needs the calculation year: pass period, " + "or give the simulation a default_calculation_period." + ) + year = periods.period(period) + if year.unit != periods.YEAR or year.size != 1: + raise ValueError( + f"export_current_law_values saves one calculation year; got {year}." + ) + arrays: Dict[ValueKey, np.ndarray] = {} + enum_members: Dict[str, Tuple[str, ...]] = {} + variables = simulation.tax_benefit_system.variables + for name in sorted(variables): + variable = variables[name] + if not variable.current_law_read: + continue + if variable.definition_period == periods.YEAR: + variable_periods = [year] + elif variable.definition_period == periods.MONTH: + variable_periods = year.get_subperiods(periods.MONTH) + elif variable.definition_period == periods.ETERNITY: + variable_periods = [periods.period(periods.ETERNITY)] + else: + LOGGER.warning( + 'Current-law values leave out "%s": values defined for each %s ' + "are not saved, so a reform simulation calculates them.", + name, + variable.definition_period, + ) + continue + is_enum = variable.value_type == Enum + population = simulation.populations[variable.entity.key] + for variable_period in variable_periods: + values = population(name, variable_period) + if is_enum and not isinstance(values, EnumArray): + values = variable.possible_values.encode(np.asarray(values)) + arrays[(name, PeriodKey.from_period(variable_period))] = values + if is_enum: + enum_members[name] = tuple(item.name for item in variable.possible_values) + entity_ids = { + key: np.asarray(population.ids) + for key, population in simulation.populations.items() + } + return CurrentLawValues( + arrays, + entity_ids, + source_run_id=source_run_id, + enum_members=enum_members, + ) + + +class SuppliedCurrentLawValues: + """Values supplied to a simulation, ready for its reads. + + ``values`` is the ``CurrentLawValues`` given; ``arrays`` holds its arrays + keyed the same way, with each Enum value mapped to the variable's Enum + class in the simulation's current-law system by member name (see + :func:`prepare_supplied_values`). + """ + + def __init__(self, values: CurrentLawValues, arrays: Mapping[ValueKey, np.ndarray]): + self.values = values + # A plain dictionary, so a simulation holding it pickles and + # deep-copies. + self.arrays = dict(arrays) + + def __setstate__(self, state: dict) -> None: + # Unpickled and deep-copied arrays come back writable. + self.__dict__.update(state) + for array in self.arrays.values(): + _read_only(array) + + def get(self, variable, period: Union[Period, str, None]) -> Optional[np.ndarray]: + """The supplied array for ``variable`` (a ``Variable``) and ``period``.""" + if variable.definition_period == periods.ETERNITY: + key = PeriodKey.from_period(periods.ETERNITY) + else: + key = PeriodKey.from_period(period) + return self.arrays.get((variable.name, key)) + + +def _arrays_equal(first: np.ndarray, second: np.ndarray) -> bool: + try: + return bool(np.array_equal(first, second)) + except (TypeError, ValueError): + return False + + +def check_population(simulation: "Simulation", values: CurrentLawValues) -> None: + """Raise unless each entity's ID array equals the one in ``values``. + + The same entities must be on both sides, and each pair of ID arrays must + be equal element by element. Raises ``CurrentLawValuesMismatchError`` + naming the first entity that differs. + """ + from policyengine_core.errors import CurrentLawValuesMismatchError + + populations = simulation.populations + supplied_ids = values.entity_ids + entity_keys = list(populations) + [ + key for key in supplied_ids if key not in populations + ] + for entity_key in entity_keys: + if entity_key not in supplied_ids: + raise CurrentLawValuesMismatchError( + "The supplied current-law values have no ID array for the entity " + f'"{entity_key}", which this simulation has.', + entity=entity_key, + ) + if entity_key not in populations: + raise CurrentLawValuesMismatchError( + "The supplied current-law values have an ID array for the entity " + f'"{entity_key}", which this simulation does not have.', + entity=entity_key, + ) + ids = np.asarray(populations[entity_key].ids) + expected = supplied_ids[entity_key] + if ids.shape == expected.shape and _arrays_equal(ids, expected): + continue + if ids.shape == expected.shape: + different = np.flatnonzero( + np.array([left != right for left, right in zip(ids, expected)]) + ) + detail = ( + f"the {len(ids)} IDs differ, first at position {int(different[0])} " + f"({ids[different[0]]!r} here, {expected[different[0]]!r} in the values)" + ) + else: + detail = f"it has {len(ids)} IDs here and {len(expected)} in the values" + raise CurrentLawValuesMismatchError( + "The supplied current-law values were calculated for another " + f'population: the entity "{entity_key}" does not match ({detail}).', + entity=entity_key, + ) + + +def prepare_supplied_values( + values: CurrentLawValues, system +) -> SuppliedCurrentLawValues: + """Ready ``values`` for a simulation whose current-law system is ``system``. + + Each Enum value becomes an ``EnumArray`` of the variable's Enum class in + ``system``, mapped by member name, not writable. Raises + ``CurrentLawValuesMismatchError`` naming the variable when a saved member + name is not in that class, or when the variable is an Enum in one and not + the other. A variable ``system`` does not have is kept as it is: no + declared read can reach it. + """ + from policyengine_core.errors import CurrentLawValuesMismatchError + + lookups = {} + arrays = {} + for (variable_name, key), array in values.arrays.items(): + variable = system.variables.get(variable_name) + saved_members = values.enum_members.get(variable_name) + if variable is None: + arrays[(variable_name, key)] = array + continue + is_enum = variable.value_type == Enum + if is_enum != (saved_members is not None): + raise CurrentLawValuesMismatchError( + f'"{variable_name}" is {"an" if is_enum else "not an"} Enum ' + "variable in the current-law system, but its supplied value is " + f"{'not an' if is_enum else 'an'} Enum value.", + variable=variable_name, + ) + if is_enum: + if variable_name not in lookups: + enum_class = variable.possible_values + positions = {item.name: item.index for item in enum_class} + missing = [name for name in saved_members if name not in positions] + if missing: + raise CurrentLawValuesMismatchError( + f'The supplied values of "{variable_name}" name Enum ' + f"members {missing} that its Enum class in the current-law " + "system does not have.", + variable=variable_name, + ) + lookup = np.array( + [positions[name] for name in saved_members], dtype=ENUM_ARRAY_DTYPE + ) + lookups[variable_name] = (lookup, enum_class) + lookup, enum_class = lookups[variable_name] + array = _read_only(EnumArray(lookup[array], enum_class)) + arrays[(variable_name, key)] = array + return SuppliedCurrentLawValues(values, arrays) diff --git a/policyengine_core/simulations/simulation.py b/policyengine_core/simulations/simulation.py index 5af87fd8d..762b561cd 100644 --- a/policyengine_core/simulations/simulation.py +++ b/policyengine_core/simulations/simulation.py @@ -32,6 +32,13 @@ from policyengine_core.periods import Instant, Period from policyengine_core.periods.config import ETERNITY, MONTH, YEAR from policyengine_core.periods.helpers import period +from policyengine_core.simulations.current_law_values import ( + LOGGER as current_law_values_logger, + CurrentLawValues, + SuppliedCurrentLawValues, + check_population, + prepare_supplied_values, +) from policyengine_core.tracers import ( FullTracer, SimpleTracer, @@ -727,6 +734,9 @@ def get(self, make_read_only: bool) -> "Simulation": self.building = False # The copy is current law: it compares with nothing. copy.__dict__["_current_law"] = _CurrentLawSource(copy, compares=False) + # It starts from the values supplied to the simulation it is + # built from, as calculated values. + self.owner._seed_current_law_copy(copy) self.simulation = copy if make_read_only and not self.assigned: copy.make_read_only() @@ -852,6 +862,10 @@ class Simulation: datasets: List[Dataset] = [] """The list of datasets available for this simulation.""" + _supplied_current_law: Optional[SuppliedCurrentLawValues] = None + """Stored current-law values supplied to this simulation, ready for its + reads (see :meth:`supply_current_law_values`).""" + is_over_dataset: bool = False """Whether this simulation is built over a dataset.""" @@ -955,6 +969,7 @@ def __init__( trace: bool = False, default_input_period: str = None, default_calculation_period: str = None, + current_law_values: Optional[CurrentLawValues] = None, ): self.default_input_period = default_input_period or self.default_input_period self.default_calculation_period = ( @@ -1108,6 +1123,11 @@ def __init__( self.parent_branch = None + # Stored current-law values, checked against the population just + # built (see ``supply_current_law_values``). + if current_law_values is not None: + self.supply_current_law_values(current_law_values) + def make_read_only(self) -> None: """Make this simulation refuse every change to its inputs, stored values and tax-benefit system. @@ -1314,6 +1334,122 @@ def current_law_simulation(self) -> "Simulation": return self return source.get(make_read_only=True) + def supply_current_law_values(self, values: CurrentLawValues) -> None: + """Use stored current-law values for this simulation's declared reads. + + ``values`` (a ``CurrentLawValues``; see + ``policyengine_core.simulations.current_law_values``) are what a + simulation run without a reform calculated over the same population. + ``Simulation(..., current_law_values=values)`` calls this once its + population is built. A caller that builds the population after + construction, or a simulation that does not run core's constructor, + calls it once the population is in place. + + Core checks one thing: each entity's ID array must equal the one saved + with the values, element by element, with the same entities on both + sides. It also maps each Enum value to the variable's Enum class in + the current-law system by member name. Either failing raises + ``CurrentLawValuesMismatchError``, naming the entity or the variable, + and leaves the simulation as it was. Every other check on where the + values came from (current law, dataset, year, model version and + settings) belongs to the caller. + + While the simulation compares with current law, + ``Population.current_law`` (called without options) and + :meth:`supplied_current_law_value` return a supplied value, not + writable, without building the current-law copy. A copy core builds + starts from the supplied values as calculated values, so its branches + do too; a simulation assigned to ``baseline`` is kept as it was given. + A period or option not supplied is calculated by the copy. Supplied + values are never inputs, so no uprating or carry-over starts from + them. Clones and branches keep them; :meth:`subsample` drops them and + logs that it did. + + Supplying values again replaces them. Raises ``ValueError`` once the + copy core builds exists, since it has calculated without them, and + ``ReadOnlySimulationError`` on a read-only simulation. + """ + refuse_on_read_only(self, "supply_current_law_values") + current_law = self._current_law_source() + if current_law.simulation is not None and not current_law.assigned: + raise ValueError( + "Current-law values must be supplied before the simulation's " + "current-law copy is built, and this simulation has built it." + ) + check_population(self, values) + self.__dict__["_supplied_current_law"] = prepare_supplied_values( + values, self._current_law_system() + ) + + def supplied_current_law_value( + self, variable_name: str, period: Period = None + ) -> Optional[ArrayLike]: + """The supplied current-law value of ``variable_name``, or ``None``. + + For helpers that have a cheaper way to proceed than calculating + current law: it never builds the current-law copy. ``None`` when the + simulation does not compare with current law, when no values were + supplied (see :meth:`supply_current_law_values`), or when they hold + nothing for that period. The array is not writable. The variable must + declare ``current_law_read = True``, as for ``Population.current_law``. + A declared call, reported to the simulation's tracer. + """ + variable = self._declared_current_law_variable( + variable_name, "supplied_current_law_value" + ) + self.populations[variable.entity.key].check_period_validity( + variable_name, period + ) + self._report_current_law_call( + "supplied_current_law_value", variable_name, period + ) + if not self._current_law_source().compares: + return None + return self._supplied_current_law_array(variable, period) + + def _supplied_current_law_array( + self, variable: Variable, period: Period + ) -> Optional[ArrayLike]: + supplied = self._supplied_current_law + if supplied is None: + return None + return supplied.get(variable, period) + + def _declared_current_law_variable(self, variable_name: str, call: str) -> Variable: + """``variable_name`` in the current-law system, if it declares reads. + + Raises ``UndeclaredCurrentLawReadError`` naming ``call`` otherwise. + """ + from policyengine_core.errors import UndeclaredCurrentLawReadError + + variable = self._current_law_system().get_variable( + variable_name, check_existence=True + ) + if not variable.current_law_read: + raise UndeclaredCurrentLawReadError( + f'The variable "{variable_name}" does not declare ' + "current_law_read = True, so formulas may not read its " + f"current-law value with {call}(). Declare it on the variable." + ) + return variable + + def _seed_current_law_copy(self, copy: "Simulation") -> None: + """Store the supplied values in a current-law copy just built. + + Each is stored as a calculated value (as a formula's result is), so it + is never an input, and uprating and carry-over never start from it. + """ + supplied = self._supplied_current_law + if supplied is None: + return + variables = copy.tax_benefit_system.variables + for (variable_name, key), array in supplied.arrays.items(): + if variable_name not in variables: + continue + copy.get_holder(variable_name).put_in_cache( + array, key.to_period(), copy.branch_name, derived=True + ) + @property def baseline(self) -> Optional["Simulation"]: """Deprecated alias: use the declared current-law calls instead. @@ -1379,6 +1515,8 @@ def _make_current_law_branch(self, system: "TaxBenefitSystem") -> "Simulation": if self.read_only: self.branches["baseline"] = branch branch.__dict__["_current_law"] = _CurrentLawSource(branch, compares=False) + # The copy is current law: values supplied for its reads are not its. + branch.__dict__["_supplied_current_law"] = None branch.trace = self.trace branch.tracer = self.tracer branch.tax_benefit_system = system @@ -4224,6 +4362,17 @@ def subsample( Simulation: The quantized simulation. """ refuse_on_read_only(self, "subsample") + supplied = self._supplied_current_law + if supplied is not None: + # Saved for the whole population, they no longer match its IDs. + self.__dict__["_supplied_current_law"] = None + source_run_id = supplied.values.source_run_id + current_law_values_logger.warning( + "Subsampling dropped the current-law values supplied from " + "simulation run %s; the current-law copy calculates them on the " + "subsample when a read needs them.", + "(no id given)" if source_run_id is None else source_run_id, + ) default_calculation_period = self.default_calculation_period # Set default key if not provided if seed is None: From 62f78c7185f20eb638c2c3d0df37e3349c5054f1 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 2 Dec 2026 20:10:33 +0400 Subject: [PATCH 16/21] Add tests for review round 1's findings on stored current-law values Clones made before the copy is built read current law of their own inputs; a declared read of a variable holding an input reads the input; a rebuilt population drops supplied values and logs it; Enum positions outside the saved members and arrays of the wrong length are refused naming the variable; byte-string IDs are accepted after save and load; a copy built through the baseline alias hands out writable values; supplying to a branch is refused; a failed subsample keeps the values. Two tests cover behaviour that already holds: an assigned baseline is not filled, and ADD reads go to the copy. Co-Authored-By: Claude Opus 5.5 --- tests/core/test_current_law_values.py | 202 +++++++++++++++++++++++++- 1 file changed, 194 insertions(+), 8 deletions(-) diff --git a/tests/core/test_current_law_values.py b/tests/core/test_current_law_values.py index fcb7c352a..c3b380f23 100644 --- a/tests/core/test_current_law_values.py +++ b/tests/core/test_current_law_values.py @@ -568,19 +568,22 @@ def test_an_enum_member_the_current_class_lacks_is_refused_naming_the_variable() assert "MEDIUM" in str(raised.value) -def test_clones_and_branches_keep_the_supplied_values(): +def test_branches_and_clones_made_with_the_copy_keep_the_supplied_values(): simulation = _simulation(current_law_values=_exported()) expected = _simulation().persons.current_law("stored_monthly_tax", MONTH_PERIOD) - clone = simulation.clone() branch = simulation.get_branch("scratch") - - for reader in (clone, branch): - np.testing.assert_array_equal( - reader.persons.current_law("stored_monthly_tax", MONTH_PERIOD), expected - ) + np.testing.assert_array_equal( + branch.persons.current_law("stored_monthly_tax", MONTH_PERIOD), expected + ) assert "baseline" not in simulation.branches - assert "baseline" not in clone.branches + # A clone made once the copy exists keeps a copy of that copy, and the + # values it started from. + simulation.current_law_simulation() + clone = simulation.clone() + np.testing.assert_array_equal( + clone.supplied_current_law_value("stored_monthly_tax", MONTH_PERIOD), expected + ) def test_supplying_is_refused_once_the_copy_is_built(): @@ -733,3 +736,186 @@ def test_a_deep_copied_simulation_keeps_its_supplied_values(): _assert_same_values(bands, expected) assert not bands.flags.writeable assert "baseline" not in restored.branches + + +NEW_SALARIES = [100000.0, 10000.0] + + +def test_a_clone_made_before_the_copy_is_built_reads_current_law_of_its_own_inputs(): + simulation = _simulation(current_law_values=_exported()) + + clone = simulation.clone() + clone.delete_arrays("salary") + clone.set_input("salary", YEAR_PERIOD, NEW_SALARIES) + + without_values = _simulation() + without_values.delete_arrays("salary") + without_values.set_input("salary", YEAR_PERIOD, NEW_SALARIES) + expected = without_values.persons.current_law("stored_tax_thousands", YEAR_PERIOD) + np.testing.assert_array_equal(expected, [15, 1]) + np.testing.assert_array_equal( + clone.persons.current_law("stored_tax_thousands", YEAR_PERIOD), expected + ) + assert clone.supplied_current_law_value("stored_tax_thousands", YEAR_PERIOD) is None + # The simulation cloned keeps its values. + np.testing.assert_array_equal( + simulation.persons.current_law("stored_tax_thousands", YEAR_PERIOD), [7, 4] + ) + assert "baseline" not in simulation.branches + + +def test_a_declared_read_of_a_variable_holding_an_input_reads_the_input(): + simulation = _simulation(current_law_values=_exported()) + + simulation.set_input("stored_tax_thousands", YEAR_PERIOD, [99, 98]) + + np.testing.assert_array_equal( + simulation.persons.current_law("stored_tax_thousands", YEAR_PERIOD), [99, 98] + ) + assert ( + simulation.supplied_current_law_value("stored_tax_thousands", YEAR_PERIOD) + is None + ) + # Other supplied values still answer without building the copy. + copies_before = "baseline" in simulation.branches + simulation.persons.current_law("stored_monthly_tax", MONTH_PERIOD) + assert ("baseline" in simulation.branches) == copies_before + + +def test_a_rebuilt_population_drops_the_supplied_values_and_logs_it(caplog): + simulation = _simulation(current_law_values=_exported()) + one_person = _simulation(reform=None, situation=_situation(person_names=("a",))) + + with caplog.at_level(logging.WARNING, logger=VALUES_LOGGER): + simulation.build_from_populations(one_person.populations) + + assert simulation.persons.count == 1 + assert ( + simulation.supplied_current_law_value("stored_monthly_tax", MONTH_PERIOD) + is None + ) + records = [record for record in caplog.records if record.name == VALUES_LOGGER] + assert len(records) == 1 + assert SOURCE_RUN_ID in records[0].getMessage() + + +@pytest.mark.parametrize("positions", [[0, 5], [0, -1]], ids=["too-high", "negative"]) +def test_an_enum_position_outside_the_saved_members_is_refused(positions): + module = _values_module() + exported = _exported() + band_key = ("stored_tax_band", module.PeriodKey.from_period(period(MONTH_PERIOD))) + arrays = dict(exported.arrays) + arrays[band_key] = np.array(positions, dtype=np.int16) + damaged = module.CurrentLawValues( + arrays=arrays, + entity_ids=exported.entity_ids, + source_run_id=exported.source_run_id, + enum_members=exported.enum_members, + ) + + _, error = _result_or_error(lambda: _simulation(current_law_values=damaged)) + + assert isinstance(error, errors.CurrentLawValuesMismatchError), repr(error) + assert error.variable == "stored_tax_band" + + +def test_an_array_whose_length_differs_from_its_entity_is_refused(): + module = _values_module() + exported = _exported() + month_key = ( + "stored_monthly_tax", + module.PeriodKey.from_period(period(MONTH_PERIOD)), + ) + arrays = dict(exported.arrays) + arrays[month_key] = np.array([1.0, 2.0, 3.0], dtype=np.float32) + damaged = module.CurrentLawValues( + arrays=arrays, + entity_ids=exported.entity_ids, + source_run_id=exported.source_run_id, + enum_members=exported.enum_members, + ) + + _, error = _result_or_error(lambda: _simulation(current_law_values=damaged)) + + assert isinstance(error, errors.CurrentLawValuesMismatchError), repr(error) + assert error.variable == "stored_monthly_tax" + + +def _with_byte_string_ids(simulation): + for population in simulation.populations.values(): + population.ids = np.char.encode(np.asarray(population.ids).astype(str), "utf-8") + return simulation + + +def test_byte_string_ids_are_accepted_after_save_and_load(tmp_path): + module = _values_module() + path = tmp_path / "values.h5" + current_law = _with_byte_string_ids(_simulation(reform=None)) + module.export_current_law_values(current_law, YEAR_PERIOD).save(path) + loaded = module.CurrentLawValues.load(path) + simulation = _with_byte_string_ids(_simulation()) + + _, error = _result_or_error(lambda: simulation.supply_current_law_values(loaded)) + + assert error is None, repr(error) + + +def test_a_copy_built_through_the_baseline_alias_hands_out_writable_values(): + simulation = _simulation(current_law_values=_exported()) + expected = _simulation().persons.current_law("stored_monthly_tax", MONTH_PERIOD) + + values = simulation.baseline.calculate("stored_monthly_tax", MONTH_PERIOD) + + np.testing.assert_array_equal(values, expected) + assert values.flags.writeable + + +def test_supplying_values_to_a_branch_is_refused(): + exported = _exported() + branch = _simulation().get_branch("scratch") + + with pytest.raises(ValueError, match="branch"): + branch.supply_current_law_values(exported) + + +def test_a_failed_subsample_keeps_the_supplied_values(caplog): + simulation = _simulation(current_law_values=_exported()) + + with caplog.at_level(logging.WARNING, logger=VALUES_LOGGER): + # A simulation built from a situation has no dataset to subsample. + with pytest.raises(AttributeError): + simulation.subsample(n=1) + + assert ( + simulation.supplied_current_law_value("stored_monthly_tax", MONTH_PERIOD) + is not None + ) + assert not [record for record in caplog.records if record.name == VALUES_LOGGER] + + +def test_a_simulation_assigned_to_baseline_is_not_filled(): + simulation = _simulation(current_law_values=_exported()) + assigned = _simulation(reform=None) + simulation.baseline = assigned + expected = _simulation().persons.current_law("stored_monthly_tax", MONTH_PERIOD) + + np.testing.assert_array_equal( + simulation.persons.current_law("stored_monthly_tax", MONTH_PERIOD), expected + ) + holder = assigned.get_holder("stored_monthly_tax") + assert holder.get_array(period(MONTH_PERIOD)) is None + + +def test_add_and_divide_reads_go_to_the_copy_which_starts_from_the_supplied_months(): + simulation = _simulation(current_law_values=_exported()) + calculated = _simulation() + + np.testing.assert_array_equal( + simulation.persons.current_law( + "stored_monthly_tax", YEAR_PERIOD, options=["add"] + ), + calculated.persons.current_law( + "stored_monthly_tax", YEAR_PERIOD, options=["add"] + ), + ) + assert "baseline" in simulation.branches From b559d18ca646be0313e07254f1a41db64c11bd50 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 2 Dec 2026 20:12:36 +0400 Subject: [PATCH 17/21] Fix review round 1's findings on stored current-law values A clone made before the current-law copy is built no longer keeps supplied values, so it calculates current law from its own inputs, as a clone does without them; get_branch gives branches the simulation's values. Declared reads and supplied_current_law_value skip a supplied value where the simulation holds an input for that variable and period. build_from_populations drops supplied values with the same logged warning as subsample, and a read whose array no longer fits the population drops them too; subsample drops them only once its own checks have passed. Supplying refuses Enum positions outside the saved member names, arrays whose length differs from their entity's IDs, and a branch. Byte-string IDs compare as text. A copy is filled with writable copies of the arrays. save writes through a temporary file of its own. Docs describe which inputs the values reflect. Co-Authored-By: Claude Opus 5.5 --- docs/python_api/errors.md | 9 +- docs/python_api/simulations.md | 31 +++-- .../current_law_values_mismatch_error.py | 11 +- .../simulations/current_law_values.py | 79 +++++++++-- policyengine_core/simulations/simulation.py | 131 ++++++++++++++---- 5 files changed, 201 insertions(+), 60 deletions(-) diff --git a/docs/python_api/errors.md b/docs/python_api/errors.md index a035c027b..c58b040ea 100644 --- a/docs/python_api/errors.md +++ b/docs/python_api/errors.md @@ -6,9 +6,12 @@ Raised by `Simulation.supply_current_law_values`, and so by `Simulation(..., current_law_values=...)`, when supplied current-law values do -not fit the simulation: an entity's ID array differs from the saved one -(`entity` names it), or a saved Enum value names a member the variable's Enum -class lacks (`variable` names it). +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 diff --git a/docs/python_api/simulations.md b/docs/python_api/simulations.md index 5b3df4b40..35ae718e7 100644 --- a/docs/python_api/simulations.md +++ b/docs/python_api/simulations.md @@ -94,21 +94,30 @@ 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, and maps each -Enum value to the variable's Enum class in the current-law system by member -name; either failing raises `CurrentLawValuesMismatchError`, naming the entity -or the variable. Every other check on where the values came from belongs to -the caller. +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). 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. Clones and branches keep them; `subsample` drops them and -logs a warning on the `policyengine_core.simulations.current_law_values` -logger. Supplying values once the copy core builds exists raises `ValueError`. +returns it or `None` (a declared call); neither uses a supplied value where the +simulation holds an input for that variable and period. 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. 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. Supplying values +to a branch, or once the copy core builds exists, raises `ValueError`. ## Microsimulation diff --git a/policyengine_core/errors/current_law_values_mismatch_error.py b/policyengine_core/errors/current_law_values_mismatch_error.py index 586d7279f..abd757a88 100644 --- a/policyengine_core/errors/current_law_values_mismatch_error.py +++ b/policyengine_core/errors/current_law_values_mismatch_error.py @@ -7,11 +7,12 @@ class CurrentLawValuesMismatchError(ValueError): 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 a saved - Enum value names a member 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. + 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__( diff --git a/policyengine_core/simulations/current_law_values.py b/policyengine_core/simulations/current_law_values.py index d40b7271c..7bb3852f1 100644 --- a/policyengine_core/simulations/current_law_values.py +++ b/policyengine_core/simulations/current_law_values.py @@ -23,6 +23,7 @@ import json import logging import os +import tempfile from importlib import metadata from pathlib import Path from types import MappingProxyType @@ -37,6 +38,8 @@ if TYPE_CHECKING: from policyengine_core.simulations.simulation import Simulation + from policyengine_core.taxbenefitsystems import TaxBenefitSystem + from policyengine_core.variables import Variable LOGGER = logging.getLogger(__name__) """Logs what happens to supplied values, such as a subsample dropping them.""" @@ -98,6 +101,11 @@ def from_json(cls, data: Mapping) -> "PeriodKey": """A stored value's key: the variable's name and its period.""" +def _enum_member_names(enum_class) -> Tuple[str, ...]: + """An Enum class's member names, in position order.""" + return tuple(item.name for item in enum_class) + + def _read_only(array: np.ndarray) -> np.ndarray: array.flags.writeable = False return array @@ -147,7 +155,7 @@ def __init__( f'The Enum value of "{variable}" has no Enum class, so its ' "member names are unknown; give them in enum_members." ) - members[variable] = tuple(item.name for item in array.possible_values) + members[variable] = _enum_member_names(array.possible_values) if variable in members: array = np.asarray(array).astype(ENUM_ARRAY_DTYPE, copy=True) else: @@ -216,7 +224,13 @@ def save(self, path: Union[str, os.PathLike]) -> None: never sees a part-written file. """ path = Path(path) - temporary_path = path.with_name(f"{path.name}.partial") + # A file of its own beside ``path``, so writers to one path do not + # collide, and the move into place stays on one file system. + descriptor, temporary_name = tempfile.mkstemp( + dir=path.parent, prefix=f"{path.name}.", suffix=".partial" + ) + os.close(descriptor) + temporary_path = Path(temporary_name) try: with h5py.File(temporary_path, "w") as file: entities = [] @@ -429,7 +443,7 @@ def export_current_law_values( values = variable.possible_values.encode(np.asarray(values)) arrays[(name, PeriodKey.from_period(variable_period))] = values if is_enum: - enum_members[name] = tuple(item.name for item in variable.possible_values) + enum_members[name] = _enum_member_names(variable.possible_values) entity_ids = { key: np.asarray(population.ids) for key, population in simulation.populations.items() @@ -463,8 +477,10 @@ def __setstate__(self, state: dict) -> None: for array in self.arrays.values(): _read_only(array) - def get(self, variable, period: Union[Period, str, None]) -> Optional[np.ndarray]: - """The supplied array for ``variable`` (a ``Variable``) and ``period``.""" + def get( + self, variable: "Variable", period: Union[Period, str, None] + ) -> Optional[np.ndarray]: + """The supplied array for ``variable`` and ``period``, or ``None``.""" if variable.definition_period == periods.ETERNITY: key = PeriodKey.from_period(periods.ETERNITY) else: @@ -472,6 +488,25 @@ def get(self, variable, period: Union[Period, str, None]) -> Optional[np.ndarray return self.arrays.get((variable.name, key)) +def _comparable_ids(ids: np.ndarray) -> np.ndarray: + """``ids`` with byte strings decoded, so they compare with text. + + A saved file holds string IDs as UTF-8 text, and loads them as ``str``; + a population may hold them as bytes (as h5py reads fixed-length strings). + """ + if ids.dtype.kind == "S": + return np.char.decode(ids, "utf-8") + if ids.dtype.kind == "O" and any(isinstance(value, bytes) for value in ids): + return np.array( + [ + value.decode("utf-8") if isinstance(value, bytes) else value + for value in ids + ], + dtype=object, + ) + return ids + + def _arrays_equal(first: np.ndarray, second: np.ndarray) -> bool: try: return bool(np.array_equal(first, second)) @@ -506,8 +541,8 @@ def check_population(simulation: "Simulation", values: CurrentLawValues) -> None f'"{entity_key}", which this simulation does not have.', entity=entity_key, ) - ids = np.asarray(populations[entity_key].ids) - expected = supplied_ids[entity_key] + ids = _comparable_ids(np.asarray(populations[entity_key].ids)) + expected = _comparable_ids(supplied_ids[entity_key]) if ids.shape == expected.shape and _arrays_equal(ids, expected): continue if ids.shape == expected.shape: @@ -528,16 +563,19 @@ def check_population(simulation: "Simulation", values: CurrentLawValues) -> None def prepare_supplied_values( - values: CurrentLawValues, system + values: CurrentLawValues, system: "TaxBenefitSystem" ) -> SuppliedCurrentLawValues: """Ready ``values`` for a simulation whose current-law system is ``system``. Each Enum value becomes an ``EnumArray`` of the variable's Enum class in ``system``, mapped by member name, not writable. Raises - ``CurrentLawValuesMismatchError`` naming the variable when a saved member - name is not in that class, or when the variable is an Enum in one and not - the other. A variable ``system`` does not have is kept as it is: no - declared read can reach it. + ``CurrentLawValuesMismatchError`` naming the variable when an array's + length differs from its variable's entity's ID array (the variable moved + to another entity, for instance), when a saved member name is not in the + Enum class or a saved position is outside the saved names, or when the + variable is an Enum in one and not the other. A variable ``system`` does + not have is kept as it is: no declared read can reach it. Call it after + :func:`check_population`. """ from policyengine_core.errors import CurrentLawValuesMismatchError @@ -549,6 +587,16 @@ def prepare_supplied_values( if variable is None: arrays[(variable_name, key)] = array continue + entity_ids = values.entity_ids.get(variable.entity.key) + if entity_ids is None or len(array) != len(entity_ids): + raise CurrentLawValuesMismatchError( + f'The supplied value of "{variable_name}" for {key.unit} ' + f"{key.start} has {len(array)} elements, but its entity " + f'"{variable.entity.key}" has ' + f"{'no ID array' if entity_ids is None else f'{len(entity_ids)} IDs'} " + "in the values.", + variable=variable_name, + ) is_enum = variable.value_type == Enum if is_enum != (saved_members is not None): raise CurrentLawValuesMismatchError( @@ -574,6 +622,13 @@ def prepare_supplied_values( ) lookups[variable_name] = (lookup, enum_class) lookup, enum_class = lookups[variable_name] + if array.size and (array.min() < 0 or array.max() >= len(lookup)): + raise CurrentLawValuesMismatchError( + f'The supplied values of "{variable_name}" hold Enum positions ' + f"from {int(array.min())} to {int(array.max())}, outside the " + f"{len(lookup)} member names saved with them.", + variable=variable_name, + ) array = _read_only(EnumArray(lookup[array], enum_class)) arrays[(variable_name, key)] = array return SuppliedCurrentLawValues(values, arrays) diff --git a/policyengine_core/simulations/simulation.py b/policyengine_core/simulations/simulation.py index 762b561cd..a98ac0e30 100644 --- a/policyengine_core/simulations/simulation.py +++ b/policyengine_core/simulations/simulation.py @@ -1347,30 +1347,52 @@ def supply_current_law_values(self, values: CurrentLawValues) -> None: Core checks one thing: each entity's ID array must equal the one saved with the values, element by element, with the same entities on both - sides. It also maps each Enum value to the variable's Enum class in - the current-law system by member name. Either failing raises - ``CurrentLawValuesMismatchError``, naming the entity or the variable, - and leaves the simulation as it was. Every other check on where the - values came from (current law, dataset, year, model version and - settings) belongs to the caller. + sides. 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, and leaves the simulation as it was. Every + other check on where the values came from (current law, dataset, + year, model version and settings) belongs to the caller. While the simulation compares with current law, ``Population.current_law`` (called without options) and :meth:`supplied_current_law_value` return a supplied value, not - writable, without building the current-law copy. A copy core builds + writable, without building the current-law copy, except where the + simulation holds an input for that variable and period (current law + then starts from the input, which the copy reads). A copy core builds starts from the supplied values as calculated values, so its branches do too; a simulation assigned to ``baseline`` is kept as it was given. A period or option not supplied is calculated by the copy. Supplied values are never inputs, so no uprating or carry-over starts from - them. Clones and branches keep them; :meth:`subsample` drops them and - logs that it did. + them. - Supplying values again replaces them. Raises ``ValueError`` once the - copy core builds exists, since it has calculated without them, and + They describe current law for the inputs the simulation holds when + they are supplied. Branches made with ``get_branch`` read them, as + they read the simulation's copy. A clone made before the copy is built + does not keep them: it builds its own copy from its own inputs, as a + clone does without them. A clone made once the copy exists keeps a + copy of that copy and the values. An input set afterwards on the + simulation (other than for a supplied variable and period), or on its + copy through the deprecated ``baseline`` alias, is not reflected in + them. :meth:`subsample` and :meth:`build_from_populations` drop them + and log a warning on the + ``policyengine_core.simulations.current_law_values`` logger. + + Supplying values again replaces them for this simulation and the + branches made afterwards. Raises ``ValueError`` on a branch (supply + them to the simulation it was made from) and once the copy core + builds exists, since it has calculated without them, and ``ReadOnlySimulationError`` on a read-only simulation. """ refuse_on_read_only(self, "supply_current_law_values") current_law = self._current_law_source() + if current_law.owner is not self: + raise ValueError( + "Current-law values are supplied to the simulation a branch was " + "made from, whose current-law copy the branch reads; this " + "simulation is a branch." + ) if current_law.simulation is not None and not current_law.assigned: raise ValueError( "Current-law values must be supplied before the simulation's " @@ -1382,15 +1404,16 @@ def supply_current_law_values(self, values: CurrentLawValues) -> None: ) def supplied_current_law_value( - self, variable_name: str, period: Period = None + self, variable_name: str, period: Union[Period, str, None] = None ) -> Optional[ArrayLike]: """The supplied current-law value of ``variable_name``, or ``None``. For helpers that have a cheaper way to proceed than calculating current law: it never builds the current-law copy. ``None`` when the simulation does not compare with current law, when no values were - supplied (see :meth:`supply_current_law_values`), or when they hold - nothing for that period. The array is not writable. The variable must + supplied (see :meth:`supply_current_law_values`), when they hold + nothing for that period, or when the simulation holds an input for + the variable and period. The array is not writable. The variable must declare ``current_law_read = True``, as for ``Population.current_law``. A declared call, reported to the simulation's tracer. """ @@ -1408,12 +1431,56 @@ def supplied_current_law_value( return self._supplied_current_law_array(variable, period) def _supplied_current_law_array( - self, variable: Variable, period: Period + self, variable: Variable, period: Union[Period, str, None] ) -> Optional[ArrayLike]: + """The supplied value for a declared read, or ``None`` to calculate it. + + ``None`` also where this simulation holds an input for the variable + and period: current law starts from that input, as the copy does. + """ supplied = self._supplied_current_law if supplied is None: return None - return supplied.get(variable, period) + array = supplied.get(variable, period) + if array is None: + return None + population = self.populations.get(variable.entity.key) + if population is None or population.count != len(array): + # The population changed some way that did not drop them. + self._drop_supplied_current_law( + "the simulation's population no longer matches them" + ) + return None + if self._holds_input_for(variable, period): + return None + return array + + def _holds_input_for( + self, variable: Variable, period: Union[Period, str, None] + ) -> bool: + if variable.name not in self.tax_benefit_system.variables: + return False + if variable.definition_period == ETERNITY: + period = periods.period(ETERNITY) + else: + period = periods.period(period) + holder = self.get_holder(variable.name) + return period in holder.get_input_periods(self.branch_name) + + def _drop_supplied_current_law(self, reason: str) -> None: + """Stop using supplied current-law values, and log why.""" + supplied = self._supplied_current_law + if supplied is None: + return + self.__dict__["_supplied_current_law"] = None + source_run_id = supplied.values.source_run_id + current_law_values_logger.warning( + "Dropped the current-law values supplied from simulation run %s, " + "because %s; the current-law copy calculates them when a read needs " + "them.", + "(no id given)" if source_run_id is None else source_run_id, + reason, + ) def _declared_current_law_variable(self, variable_name: str, call: str) -> Variable: """``variable_name`` in the current-law system, if it declares reads. @@ -1446,8 +1513,10 @@ def _seed_current_law_copy(self, copy: "Simulation") -> None: for (variable_name, key), array in supplied.arrays.items(): if variable_name not in variables: continue + # A copy of the array: the copy is writable until a declared call + # makes it read-only (see ``baseline``), and its values with it. copy.get_holder(variable_name).put_in_cache( - array, key.to_period(), copy.branch_name, derived=True + array.copy(), key.to_period(), copy.branch_name, derived=True ) @property @@ -1721,6 +1790,9 @@ def build_from_populations(self, populations: Dict[str, Population]) -> None: populations (Dict[str, Population]): A dictionary of populations, indexed by entity key. """ refuse_on_read_only(self, "build_from_populations") + # Values supplied for the population being replaced do not describe + # the new one. + self._drop_supplied_current_law("the simulation's population was rebuilt") self.populations = populations self.link_to_entities_instances() self.create_shortcuts() @@ -3811,6 +3883,13 @@ def clone( new.__dict__["_current_law"] = current_law.for_clone( self, new, debug, trace ) + new_current_law = new.__dict__["_current_law"] + if new_current_law is not current_law and new_current_law.simulation is None: + # The clone builds its own copy from its own inputs when it needs + # one, so an input set on the clone reaches it; values supplied for + # this simulation's inputs would not. ``get_branch`` gives a branch + # this simulation's values back. + new.__dict__["_supplied_current_law"] = None return new @@ -3898,8 +3977,10 @@ def get_branch( finally: request.pending = False _branch_clone.reset(token) - # The branch reads this simulation's current-law copy (see ``clone``). + # The branch reads this simulation's current-law copy (see ``clone``), + # and the values supplied for it. branch.__dict__["_current_law"] = self._current_law_source() + branch.__dict__["_supplied_current_law"] = self._supplied_current_law if not self.read_only: self.branches[name] = branch branch.branch_name = name @@ -4362,17 +4443,6 @@ def subsample( Simulation: The quantized simulation. """ refuse_on_read_only(self, "subsample") - supplied = self._supplied_current_law - if supplied is not None: - # Saved for the whole population, they no longer match its IDs. - self.__dict__["_supplied_current_law"] = None - source_run_id = supplied.values.source_run_id - current_law_values_logger.warning( - "Subsampling dropped the current-law values supplied from " - "simulation run %s; the current-law copy calculates them on the " - "subsample when a read needs them.", - "(no id given)" if source_run_id is None else source_run_id, - ) default_calculation_period = self.default_calculation_period # Set default key if not provided if seed is None: @@ -4538,6 +4608,9 @@ def retain_structure(name, values): df = subset_df + # Supplied current-law values were saved for the whole population and + # no longer match its IDs. + self._drop_supplied_current_law("the simulation was subsampled") # Rebuilding replaces storage, its input record, and store history. self.dataset = Dataset.from_dataframe(df, self.dataset.time_period) self._store_history = StoreHistory() From d1b537b90b848bd1f397f1f5618c5f020e4955bd Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 2 Dec 2026 20:31:55 +0400 Subject: [PATCH 18/21] Add tests for review round 2's findings on stored current-law values The saved file gets the mode a new file gets, and a population replaced without build_from_populations drops the supplied values before a copy is filled from them. Co-Authored-By: Claude Opus 5.5 --- tests/core/test_current_law_values.py | 39 +++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/tests/core/test_current_law_values.py b/tests/core/test_current_law_values.py index c3b380f23..dabb7e894 100644 --- a/tests/core/test_current_law_values.py +++ b/tests/core/test_current_law_values.py @@ -19,7 +19,9 @@ import inspect import json import logging +import os import pickle +import stat import h5py import numpy as np @@ -919,3 +921,40 @@ def test_add_and_divide_reads_go_to_the_copy_which_starts_from_the_supplied_mont ), ) assert "baseline" in simulation.branches + + +def _current_umask(): + umask = os.umask(0) + os.umask(umask) + return umask + + +def test_the_saved_file_has_the_mode_a_new_file_gets(tmp_path): + path = tmp_path / "values.h5" + + _exported().save(path) + + assert stat.S_IMODE(os.stat(path).st_mode) == 0o666 & ~_current_umask() + assert [item.name for item in tmp_path.iterdir()] == ["values.h5"] + + +def test_a_population_replaced_directly_drops_the_values_before_filling_a_copy(caplog): + simulation = _simulation(current_law_values=_exported()) + one_person = _simulation(reform=None, situation=_situation(person_names=("a",))) + # Replace the population the way build_from_populations does, without it. + simulation.populations = one_person.populations + simulation.link_to_entities_instances() + simulation.create_shortcuts() + simulation.persons = simulation.populations["person"] + + with caplog.at_level(logging.WARNING, logger=VALUES_LOGGER): + copy, error = _result_or_error(simulation.current_law_simulation) + + assert error is None, repr(error) + assert copy.persons.count == 1 + assert ( + simulation.supplied_current_law_value("stored_monthly_tax", MONTH_PERIOD) + is None + ) + records = [record for record in caplog.records if record.name == VALUES_LOGGER] + assert len(records) == 1 From d3a803807e0f242c33637462e3ae95c8f8268728 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 2 Dec 2026 20:32:44 +0400 Subject: [PATCH 19/21] Fix review round 2's findings on stored current-law values save gives the file the mode a newly created file gets, not the owner-only mode of its temporary file. Filling a copy checks each supplied array's length against the copy's population first, and drops the values with the logged warning when the population changed some way that did not drop them. The refusal on a branch names clones of branches too; docs describe deep copies and the input exception. Co-Authored-By: Claude Opus 5.5 --- docs/python_api/simulations.md | 13 +++--- policyengine_core/populations/population.py | 3 +- .../simulations/current_law_values.py | 9 +++++ policyengine_core/simulations/simulation.py | 40 ++++++++++++++----- tests/core/test_current_law_values.py | 2 +- 5 files changed, 49 insertions(+), 18 deletions(-) diff --git a/docs/python_api/simulations.md b/docs/python_api/simulations.md index 35ae718e7..74cbde730 100644 --- a/docs/python_api/simulations.md +++ b/docs/python_api/simulations.md @@ -113,11 +113,14 @@ 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. 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. Supplying values -to a branch, or once the copy core builds exists, raises `ValueError`. +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 diff --git a/policyengine_core/populations/population.py b/policyengine_core/populations/population.py index 6e6b3b101..6d827092b 100644 --- a/policyengine_core/populations/population.py +++ b/policyengine_core/populations/population.py @@ -204,7 +204,8 @@ def current_law( 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. + ``options`` are given and the simulation holds no input for that + variable and period. Example, for a variable ``income_tax`` declaring ``current_law_read = True``: diff --git a/policyengine_core/simulations/current_law_values.py b/policyengine_core/simulations/current_law_values.py index 7bb3852f1..541a15834 100644 --- a/policyengine_core/simulations/current_law_values.py +++ b/policyengine_core/simulations/current_law_values.py @@ -267,6 +267,9 @@ def save(self, path: Union[str, os.PathLike]) -> None: "arrays": entries, } file.attrs[MANIFEST_ATTRIBUTE] = json.dumps(manifest, sort_keys=True) + # ``mkstemp`` makes the file readable by its owner only; give it + # the mode a newly created file gets. + os.chmod(temporary_path, 0o666 & ~_current_umask()) os.replace(temporary_path, path) finally: if temporary_path.exists(): @@ -328,6 +331,12 @@ def load(cls, path: Union[str, os.PathLike]) -> "CurrentLawValues": ) +def _current_umask() -> int: + umask = os.umask(0) + os.umask(umask) + return umask + + def _write_array(file: h5py.File, dataset: str, array: np.ndarray, name: str) -> str: """Write ``array`` and return the dtype label the manifest records.""" kind = array.dtype.kind diff --git a/policyengine_core/simulations/simulation.py b/policyengine_core/simulations/simulation.py index a98ac0e30..1192b241b 100644 --- a/policyengine_core/simulations/simulation.py +++ b/policyengine_core/simulations/simulation.py @@ -1360,7 +1360,8 @@ def supply_current_law_values(self, values: CurrentLawValues) -> None: :meth:`supplied_current_law_value` return a supplied value, not writable, without building the current-law copy, except where the simulation holds an input for that variable and period (current law - then starts from the input, which the copy reads). A copy core builds + then starts from that input, as a copy built from those inputs does). + A copy core builds starts from the supplied values as calculated values, so its branches do too; a simulation assigned to ``baseline`` is kept as it was given. A period or option not supplied is calculated by the copy. Supplied @@ -1375,13 +1376,17 @@ def supply_current_law_values(self, values: CurrentLawValues) -> None: copy of that copy and the values. An input set afterwards on the simulation (other than for a supplied variable and period), or on its copy through the deprecated ``baseline`` alias, is not reflected in - them. :meth:`subsample` and :meth:`build_from_populations` drop them + them. A deep copy or pickle of the simulation keeps them, with its + inputs. :meth:`subsample` and :meth:`build_from_populations` drop them and log a warning on the - ``policyengine_core.simulations.current_law_values`` logger. + ``policyengine_core.simulations.current_law_values`` logger, as does a + read or a copy built after the population changed some other way. Supplying values again replaces them for this simulation and the - branches made afterwards. Raises ``ValueError`` on a branch (supply - them to the simulation it was made from) and once the copy core + branches made afterwards. Raises ``ValueError`` on a simulation that + reads another simulation's current-law copy (a branch, or a clone of + one: supply them to the simulation the branch was made from) and once + the copy core builds exists, since it has calculated without them, and ``ReadOnlySimulationError`` on a read-only simulation. """ @@ -1389,9 +1394,9 @@ def supply_current_law_values(self, values: CurrentLawValues) -> None: current_law = self._current_law_source() if current_law.owner is not self: raise ValueError( - "Current-law values are supplied to the simulation a branch was " - "made from, whose current-law copy the branch reads; this " - "simulation is a branch." + "This simulation reads the current-law copy of the simulation " + "it was branched from (it is a branch, or a clone of one); " + "supply current-law values to that simulation." ) if current_law.simulation is not None and not current_law.assigned: raise ValueError( @@ -1510,9 +1515,22 @@ def _seed_current_law_copy(self, copy: "Simulation") -> None: if supplied is None: return variables = copy.tax_benefit_system.variables - for (variable_name, key), array in supplied.arrays.items(): - if variable_name not in variables: - continue + seeds = [ + (variables[variable_name], key, array) + for (variable_name, key), array in supplied.arrays.items() + if variable_name in variables + ] + if any( + len(array) != copy.populations[variable.entity.key].count + for variable, key, array in seeds + ): + # The population changed some way that did not drop them. + self._drop_supplied_current_law( + "the simulation's population no longer matches them" + ) + return + for variable, key, array in seeds: + variable_name = variable.name # A copy of the array: the copy is writable until a declared call # makes it read-only (see ``baseline``), and its values with it. copy.get_holder(variable_name).put_in_cache( diff --git a/tests/core/test_current_law_values.py b/tests/core/test_current_law_values.py index dabb7e894..da78556d7 100644 --- a/tests/core/test_current_law_values.py +++ b/tests/core/test_current_law_values.py @@ -876,7 +876,7 @@ def test_supplying_values_to_a_branch_is_refused(): exported = _exported() branch = _simulation().get_branch("scratch") - with pytest.raises(ValueError, match="branch"): + with pytest.raises(ValueError, match="branched from"): branch.supply_current_law_values(exported) From 692026045e2766d0d412a64f377d86ce475f5ac5 Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 2 Dec 2026 20:53:10 +0400 Subject: [PATCH 20/21] Add tests for review round 3's findings on stored current-law values An input set after a supplied read does not change later reads, as it does not without supplied values; saving never changes the process umask. The input exception's test now sets the input before the values are supplied. Co-Authored-By: Claude Opus 5.5 --- tests/core/test_current_law_values.py | 39 +++++++++++++++++++++++++-- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/tests/core/test_current_law_values.py b/tests/core/test_current_law_values.py index da78556d7..77f3aa6ce 100644 --- a/tests/core/test_current_law_values.py +++ b/tests/core/test_current_law_values.py @@ -767,10 +767,11 @@ def test_a_clone_made_before_the_copy_is_built_reads_current_law_of_its_own_inpu def test_a_declared_read_of_a_variable_holding_an_input_reads_the_input(): - simulation = _simulation(current_law_values=_exported()) - + simulation = _simulation() simulation.set_input("stored_tax_thousands", YEAR_PERIOD, [99, 98]) + simulation.supply_current_law_values(_exported()) + np.testing.assert_array_equal( simulation.persons.current_law("stored_tax_thousands", YEAR_PERIOD), [99, 98] ) @@ -958,3 +959,37 @@ def test_a_population_replaced_directly_drops_the_values_before_filling_a_copy(c ) records = [record for record in caplog.records if record.name == VALUES_LOGGER] assert len(records) == 1 + + +def test_an_input_set_after_a_supplied_read_does_not_change_later_reads(): + def read_set_and_read_again(simulation): + first = simulation.persons.current_law("stored_tax_thousands", YEAR_PERIOD) + first = np.array(first, copy=True) + simulation.set_input("stored_tax_thousands", YEAR_PERIOD, [99, 98]) + second = simulation.persons.current_law("stored_tax_thousands", YEAR_PERIOD) + return first, second + + first, second = read_set_and_read_again(_simulation(current_law_values=_exported())) + _, second_without_values = read_set_and_read_again(_simulation()) + + # Without supplied values the first read built the copy, which the later + # input does not reach; one run gives one current-law value. + np.testing.assert_array_equal(second_without_values, [7, 4]) + np.testing.assert_array_equal(second, first) + np.testing.assert_array_equal(second, second_without_values) + + +def test_saving_never_changes_the_process_umask(tmp_path, monkeypatch): + path = tmp_path / "values.h5" + exported = _exported() + expected_mode = 0o666 & ~_current_umask() + + def refuse_umask(mask): + raise AssertionError("save changed the process umask") + + monkeypatch.setattr(os, "umask", refuse_umask) + _, error = _result_or_error(lambda: exported.save(path)) + monkeypatch.undo() + + assert error is None, repr(error) + assert stat.S_IMODE(os.stat(path).st_mode) == expected_mode From 702bd1991294c6b08a215ffd34e9af101638b88e Mon Sep 17 00:00:00 2001 From: Anthony Volk <14987227+anth-volk@users.noreply.github.com> Date: Wed, 2 Dec 2026 20:53:58 +0400 Subject: [PATCH 21/21] Fix review round 3's findings on stored current-law values save creates its temporary file with os.open and mode 0o666, so the process umask gives it a new file's mode, instead of changing the umask and the file's mode. Whether a supplied value is skipped for an input the simulation holds is decided once, when the values are supplied, so an input set later cannot make one run give two current-law values for the same variable and period. Docs and the changelog fragment name the error class, the logged drops, export's default period and the eternity key. Co-Authored-By: Claude Opus 5.5 --- changelog.d/current-law-values.added.md | 2 +- docs/python_api/simulations.md | 6 ++-- policyengine_core/populations/population.py | 4 +-- .../simulations/current_law_values.py | 26 +++++--------- policyengine_core/simulations/simulation.py | 34 +++++++++++-------- 5 files changed, 36 insertions(+), 36 deletions(-) diff --git a/changelog.d/current-law-values.added.md b/changelog.d/current-law-values.added.md index 2ef9cd4de..2d21205e6 100644 --- a/changelog.d/current-law-values.added.md +++ b/changelog.d/current-law-values.added.md @@ -1 +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, then returns them for declared reads, and through `supplied_current_law_value`, without building its current-law copy. +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. diff --git a/docs/python_api/simulations.md b/docs/python_api/simulations.md index 74cbde730..b87fcbd8d 100644 --- a/docs/python_api/simulations.md +++ b/docs/python_api/simulations.md @@ -77,7 +77,8 @@ simulation over the same population would otherwise calculate again - `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`, a monthly variable for each of + 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, @@ -105,7 +106,8 @@ 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 holds an input for that variable and period. A copy core builds +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. diff --git a/policyengine_core/populations/population.py b/policyengine_core/populations/population.py index 6d827092b..3005f77ea 100644 --- a/policyengine_core/populations/population.py +++ b/policyengine_core/populations/population.py @@ -204,8 +204,8 @@ def current_law( 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 holds no input for that - variable and period. + ``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``: diff --git a/policyengine_core/simulations/current_law_values.py b/policyengine_core/simulations/current_law_values.py index 541a15834..0a6ef092d 100644 --- a/policyengine_core/simulations/current_law_values.py +++ b/policyengine_core/simulations/current_law_values.py @@ -23,7 +23,7 @@ import json import logging import os -import tempfile +import uuid from importlib import metadata from pathlib import Path from types import MappingProxyType @@ -201,7 +201,9 @@ def enum_members(self) -> Mapping[str, Tuple[str, ...]]: def get(self, variable: str, period: Union[Period, str]) -> Optional[np.ndarray]: """The stored array for ``variable`` and ``period``, or ``None``. - An Enum value is given as positions (see ``enum_members``). + An Enum value is given as positions (see ``enum_members``). An eternal + variable's value is stored under the eternity period, so ask for it + with ``"eternity"``. """ return self._arrays.get((variable, PeriodKey.from_period(period))) @@ -225,12 +227,11 @@ def save(self, path: Union[str, os.PathLike]) -> None: """ path = Path(path) # A file of its own beside ``path``, so writers to one path do not - # collide, and the move into place stays on one file system. - descriptor, temporary_name = tempfile.mkstemp( - dir=path.parent, prefix=f"{path.name}.", suffix=".partial" - ) - os.close(descriptor) - temporary_path = Path(temporary_name) + # collide, and the move into place stays on one file system. Created + # with mode 0o666, so the process umask gives it the mode any new file + # gets; HDF5 keeps that mode when it writes the file. + temporary_path = path.with_name(f"{path.name}.{uuid.uuid4().hex}.partial") + os.close(os.open(temporary_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o666)) try: with h5py.File(temporary_path, "w") as file: entities = [] @@ -267,9 +268,6 @@ def save(self, path: Union[str, os.PathLike]) -> None: "arrays": entries, } file.attrs[MANIFEST_ATTRIBUTE] = json.dumps(manifest, sort_keys=True) - # ``mkstemp`` makes the file readable by its owner only; give it - # the mode a newly created file gets. - os.chmod(temporary_path, 0o666 & ~_current_umask()) os.replace(temporary_path, path) finally: if temporary_path.exists(): @@ -331,12 +329,6 @@ def load(cls, path: Union[str, os.PathLike]) -> "CurrentLawValues": ) -def _current_umask() -> int: - umask = os.umask(0) - os.umask(umask) - return umask - - def _write_array(file: h5py.File, dataset: str, array: np.ndarray, name: str) -> str: """Write ``array`` and return the dtype label the manifest records.""" kind = array.dtype.kind diff --git a/policyengine_core/simulations/simulation.py b/policyengine_core/simulations/simulation.py index 1192b241b..11edc2b8a 100644 --- a/policyengine_core/simulations/simulation.py +++ b/policyengine_core/simulations/simulation.py @@ -1359,8 +1359,9 @@ def supply_current_law_values(self, values: CurrentLawValues) -> None: ``Population.current_law`` (called without options) and :meth:`supplied_current_law_value` return a supplied value, not writable, without building the current-law copy, except where the - simulation holds an input for that variable and period (current law - then starts from that input, as a copy built from those inputs does). + simulation holds an input for that variable and period when the + values are supplied (current law then starts from that input, as a + copy built from those inputs does). A copy core builds starts from the supplied values as calculated values, so its branches do too; a simulation assigned to ``baseline`` is kept as it was given. @@ -1404,9 +1405,19 @@ def supply_current_law_values(self, values: CurrentLawValues) -> None: "current-law copy is built, and this simulation has built it." ) check_population(self, values) - self.__dict__["_supplied_current_law"] = prepare_supplied_values( - values, self._current_law_system() - ) + system = self._current_law_system() + supplied = prepare_supplied_values(values, system) + # Where this simulation holds an input, current law starts from it, as + # a copy built from these inputs does: such a value is not used. + # Decided here, once, so every read in the run agrees, as they do + # without supplied values, whatever inputs are set later. + for variable_name, key in list(supplied.arrays): + variable = system.variables.get(variable_name) + if variable is not None and self._holds_input_for( + variable, key.to_period() + ): + del supplied.arrays[(variable_name, key)] + self.__dict__["_supplied_current_law"] = supplied def supplied_current_law_value( self, variable_name: str, period: Union[Period, str, None] = None @@ -1417,8 +1428,9 @@ def supplied_current_law_value( current law: it never builds the current-law copy. ``None`` when the simulation does not compare with current law, when no values were supplied (see :meth:`supply_current_law_values`), when they hold - nothing for that period, or when the simulation holds an input for - the variable and period. The array is not writable. The variable must + nothing for that period, or when the simulation held an input for the + variable and period when they were supplied. The array is not + writable. The variable must declare ``current_law_read = True``, as for ``Population.current_law``. A declared call, reported to the simulation's tracer. """ @@ -1438,11 +1450,7 @@ def supplied_current_law_value( def _supplied_current_law_array( self, variable: Variable, period: Union[Period, str, None] ) -> Optional[ArrayLike]: - """The supplied value for a declared read, or ``None`` to calculate it. - - ``None`` also where this simulation holds an input for the variable - and period: current law starts from that input, as the copy does. - """ + """The supplied value for a declared read, or ``None`` to calculate it.""" supplied = self._supplied_current_law if supplied is None: return None @@ -1456,8 +1464,6 @@ def _supplied_current_law_array( "the simulation's population no longer matches them" ) return None - if self._holds_input_for(variable, period): - return None return array def _holds_input_for(