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 0aaf4d8b2..5189ba9cc 100644 --- a/docs/python_api/simulations.md +++ b/docs/python_api/simulations.md @@ -35,6 +35,40 @@ keeps values it does not hold yet. The method's docstring lists what is not detected. +### Current-law reads + +A simulation built with a reform compares with current law. Formulas read +current law through declared calls, each reported to the simulation's tracer +(`record_current_law_call`, kept as `TraceNode.current_law_calls` by the full +tracer): + +- `population.current_law(variable, period)` returns the variable's value under + current law, for a variable that declares `current_law_read = True` in the + current-law tax-benefit system; any other variable raises + `UndeclaredCurrentLawReadError`. Without a reform it returns the + simulation's own value. +- `simulation.compares_with_current_law` says whether the simulation compares + with current law. +- `simulation.current_law_system` is the current-law tax-benefit system. +- `simulation.current_law_simulation()` is the simulation that calculates + current-law values: the simulation itself without a reform. + +Construction no longer branches a copy under current law. The copy is built the +first time something needs it, by the overridable +`_build_current_law_simulation()`: a branch named `baseline`, under +`default_tax_benefit_system_instance`, holding the inputs the simulation holds +then and none of its calculated values. `compares_with_current_law` and +`current_law_system` never build it. The first declared call that reaches it +makes it read-only (see above). A read-only simulation registers the copy it +builds in `branches`, unlike its other branches. Branches read their parent's +copy; `clone()` and `subsample()` keep a copy only if one was built. + +`simulation.baseline` is deprecated. It returns the copy (built if needed, and +left writable) or `None`, and each read is reported to the tracer. Assigning a +simulation to it makes that simulation the copy, kept as it is given; +assigning `None` stops the comparison. Assigning it on a read-only simulation +raises `ReadOnlySimulationError`. + ## 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..0bbecbb8b 100644 --- a/policyengine_core/populations/population.py +++ b/policyengine_core/populations/population.py @@ -179,6 +179,64 @@ def __call__( # Helpers + @projectors.projectable + def current_law( + self, + variable_name: str, + period: Period = None, + options: Optional[Container[str]] = None, + ): + """Calculate ``variable_name`` under current law, for this entity. + + In a simulation that compares with current law (one built with a + reform, or one of its branches), the value its current-law copy + calculates (see ``Simulation.current_law_simulation``), which this + builds if there is none yet and makes read-only (unless it is a + simulation assigned to ``baseline``, which is kept as it was given). Otherwise the + simulation is current law itself, and this is the same as calling + the population. ``period`` and ``options`` are as for a call. + + The variable must declare ``current_law_read = True`` in the + current-law tax-benefit system; otherwise this raises + ``UndeclaredCurrentLawReadError``. Each call is reported to the + simulation's tracer, with the variable and period. + + Example, for a variable ``income_tax`` declaring + ``current_law_read = True``: + + >>> person.current_law('income_tax', '2017-04') + >>> array([45.]) + + Called through a projection (``person.household.current_law(...)``), + the result is projected as a call's would be. Once the copy is + read-only, the array returned from it is non-writable, as every array + a read-only simulation stores: a formula that writes into what it + read must copy it first. + """ + 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 + ) + 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 bf1352d6f..5af87fd8d 100644 --- a/policyengine_core/simulations/simulation.py +++ b/policyengine_core/simulations/simulation.py @@ -678,6 +678,119 @@ 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_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", + 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 +852,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.""" @@ -991,22 +1101,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 @@ -1052,9 +1150,13 @@ 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 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. @@ -1120,6 +1222,212 @@ 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: + # 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 + + 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 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() + + 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, 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. + """ + 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. 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 + 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 + 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: + # 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, + simulation=simulation, + 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 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. + + 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._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. + 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, 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]): refuse_on_read_only(self, "apply_reform") if isinstance(reform, tuple): @@ -1518,8 +1826,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 @@ -3198,14 +3507,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 @@ -3223,6 +3536,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 @@ -3334,40 +3651,28 @@ 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. ``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 - 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 + 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 + # 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 @@ -3411,6 +3716,14 @@ def get_branch( branch is not read-only. A name registered before ``make_read_only`` gives that branch, as it is. + 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". clone_system (bool, optional): Whether to clone the tax-benefit system. Use this if you're changing policy parameters. Defaults to False. @@ -3420,6 +3733,18 @@ def get_branch( """ if name == self.branch_name: return self + if name == "baseline" and name not in self.branches: + current_law = self._current_law_source() + if ( + current_law.owner is self + and current_law.compares + and current_law.simulation is None + and not current_law.building + ): + # Construction used to register the current-law copy under + # 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] frames = _calculation_frames.get() @@ -3435,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 @@ -3463,6 +3790,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. """ @@ -3472,6 +3804,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) @@ -4076,30 +4413,42 @@ 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: - 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), in a new record, as the other path makes. del self.branches["baseline"] - baseline = self.get_branch("baseline") - # 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. - 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. - baseline.input_variables = list(baseline.input_variables) - baseline.baseline = None - if getattr(self, "baseline", None) is not None: - self.baseline = baseline + 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, 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 + # reform-vs-baseline comparisons after ``subsample`` compared the + # reform against itself. + baseline_tax_benefit_system = replaced.tax_benefit_system + del self.branches["baseline"] + baseline = self._make_current_law_branch(baseline_tax_benefit_system) + 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..2b59e2f94 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,13 @@ 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, + # 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 + ) 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 diff --git a/tests/core/test_clone_reform_baseline.py b/tests/core/test_clone_reform_baseline.py index a23ecb299..c39cbc54c 100644 --- a/tests/core/test_clone_reform_baseline.py +++ b/tests/core/test_clone_reform_baseline.py @@ -1,7 +1,10 @@ """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; +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 new file mode 100644 index 000000000..55ef0e58f --- /dev/null +++ b/tests/core/test_current_law_reads.py @@ -0,0 +1,1004 @@ +"""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 copy as copy_module +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): + 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 declared_yearly_tax(Variable): + label = "Income tax in the year" + 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): + label = "Household income tax in the month" + 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): + 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 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) + + +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. + + +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 + 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): + label = "Whether the baseline alias returns a simulation" + 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, + 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, +) + + +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 _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 = [ + 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) + + _assert_income_tax( + simulation.persons.current_law("declared_monthly_tax", MONTH_PERIOD), + 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. + _assert_income_tax( + simulation.persons.current_law("declared_monthly_tax", MONTH_PERIOD), + 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 + _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() + _assert_income_tax( + simulation.calculate("income_tax", MONTH_PERIOD), MONTHLY_SALARY, REFORM_RATE + ) + simulation.calculate("declared_yearly_tax", YEAR_PERIOD) + + _assert_income_tax( + simulation.persons.current_law("declared_monthly_tax", MONTH_PERIOD), + MONTHLY_SALARY, + BASELINE_RATE, + ) + _assert_income_tax( + simulation.persons.current_law("declared_yearly_tax", YEAR_PERIOD), + YEARLY_SALARY, + BASELINE_RATE, + ) + + +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) + + simulation.set_input("salary", MONTH_PERIOD, OTHER_MONTHLY_SALARY) + + _assert_income_tax( + simulation.baseline.calculate("income_tax", MONTH_PERIOD), + 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() + _assert_income_tax(branch_values, 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 + _assert_income_tax( + simulation.persons.current_law("declared_monthly_tax", MONTH_PERIOD), + 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 + _assert_income_tax( + simulation.persons.current_law("declared_monthly_tax", MONTH_PERIOD), + 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) + + _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 + _assert_income_tax( + simulation.persons.current_law("declared_monthly_tax", MONTH_PERIOD), + 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 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 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 _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_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) + + record = clone._current_law_source() + assert record.owner is clone + assert record.simulation 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: + 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() + + _assert_income_tax( + simulation.calculate("makes_every_declared_call", MONTH_PERIOD), + MONTHLY_SALARY, + BASELINE_RATE, + ) diff --git a/tests/core/test_reform_baseline_system.py b/tests/core/test_reform_baseline_system.py index c1c337280..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,14 +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) - del reform.branches["baseline"] - 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 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")