diff --git a/changelog.d/parameter-clone-without-parent.changed.md b/changelog.d/parameter-clone-without-parent.changed.md new file mode 100644 index 000000000..825fe3b1f --- /dev/null +++ b/changelog.d/parameter-clone-without-parent.changed.md @@ -0,0 +1 @@ +`clone()` of a parameter node, scale or parameter now returns a copy with no parent, so changes made in a cloned part of a parameter tree no longer mark the tree it was cloned from as modified or clear that tree's caches. diff --git a/changelog.d/read-only-simulations.added.md b/changelog.d/read-only-simulations.added.md new file mode 100644 index 000000000..5bdbeec36 --- /dev/null +++ b/changelog.d/read-only-simulations.added.md @@ -0,0 +1 @@ +Added `Simulation.make_read_only()`: a read-only simulation still calculates and keeps new values, refuses changes to its inputs, stored arrays and tax-benefit system with `ReadOnlySimulationError`, raises on its next calculation after a parameter change, stores only non-writable arrays, and makes private branches that are never kept in its `branches`. diff --git a/docs/python_api/errors.md b/docs/python_api/errors.md index a0bdcfe7a..34c73c594 100644 --- a/docs/python_api/errors.md +++ b/docs/python_api/errors.md @@ -38,6 +38,19 @@ :show-inheritance: ``` +## ReadOnlySimulationError + +Raised when an operation would change a simulation made read-only with +`Simulation.make_read_only()`, and by its next calculation once its parameters +have changed. + +```{eval-rst} +.. autoclass:: policyengine_core.errors.read_only_simulation_error.ReadOnlySimulationError + :members: + :undoc-members: + :show-inheritance: +``` + ## SituationParsingError ```{eval-rst} diff --git a/docs/python_api/simulations.md b/docs/python_api/simulations.md index 176c4be80..0aaf4d8b2 100644 --- a/docs/python_api/simulations.md +++ b/docs/python_api/simulations.md @@ -12,6 +12,29 @@ The `policyengine_core.simulations` module contains the definition of `Simulatio :show-inheritance: ``` +### Read-only simulations + +`Simulation.make_read_only()` makes a simulation refuse every change to its +inputs, stored values and tax-benefit system, while it still calculates and +keeps values it does not hold yet. + +- `set_input` and `delete_arrays` (on the simulation or a holder), + `drop_computed_arrays`, `invalidate_cache_entry`, `apply_reform`, + `subsample`, `build_from_dataset`, `build_from_populations`, + `SimulationBuilder` building into it, the `set_input_dispatch_by_period` and + `set_input_divide_by_period` helpers, and assigning or deleting + `tax_benefit_system` raise `ReadOnlySimulationError`. +- Every array it stores, reads back from disk storage or reads from the macro + cache is non-writable, so a formula that writes in place into an array it + read raises numpy's `ValueError`. +- A parameter change after `make_read_only()` is not refused, since other + simulations may share the parameter tree; the read-only simulation's next + calculation raises `ReadOnlySimulationError` instead. +- `get_branch` with a new name returns a branch that is not kept in `branches` + and is not read-only itself. + +The method's docstring lists what is not detected. + ## Microsimulation ```{eval-rst} diff --git a/policyengine_core/data_storage/in_memory_storage.py b/policyengine_core/data_storage/in_memory_storage.py index bc60c8fe3..73f842326 100644 --- a/policyengine_core/data_storage/in_memory_storage.py +++ b/policyengine_core/data_storage/in_memory_storage.py @@ -4,6 +4,7 @@ from numpy.typing import ArrayLike from policyengine_core import periods +from policyengine_core.data_storage.non_writable import make_non_writable from policyengine_core.data_storage.storage_keys import check_storable from policyengine_core.data_storage.store_history import ( _period_from_storage_key, @@ -85,6 +86,10 @@ class InMemoryStorage: # every holder, so copying at each clone would cost a set per input # holder per branch for inputs most branches never change. _inputs: Union[Set[str], FrozenSet[str]] = _NO_INPUTS + # Whether every array this storage holds is non-writable: set by + # ``make_read_only`` for a read-only simulation's holders (see + # ``Simulation.make_read_only``). A clone is not read-only. + read_only: bool = False is_eternal: bool def __init__(self, is_eternal: bool): @@ -117,6 +122,26 @@ def __setstate__(self, state: dict) -> None: # those of stores made after unpickling it. if self._sequence_numbers: advance_sequence_past(max(self._sequence_numbers.values())) + # Unpickled arrays are writable again. + if self.read_only: + self.make_read_only() + + def make_read_only(self) -> None: + """Mark every array this storage holds non-writable, and every array + it stores or copies from here on (see ``put`` and ``get``). + + An array still shared with the storage this one was cloned from (see + ``clone``) is copied first: the other storage can write into its own + array in place, which would change what this one reads. + """ + self.read_only = True + shared = self._shared + for key, array in list(self._arrays.items()): + if key in shared: + array = self._arrays[key] = array.copy() + make_non_writable(array) + # Nothing is shared any more (see ``_release_if_empty``). + self.__dict__.pop("_shared", None) def clone(self, share_arrays: bool = False) -> "InMemoryStorage": """Copy this storage. @@ -130,6 +155,10 @@ def clone(self, share_arrays: bool = False) -> "InMemoryStorage": it in place does not change this storage. (Masked arrays are copied straight away: a view would share their mask.) + The clone is not read-only, even when this storage is (see + ``make_read_only``): what it copies is writable, and what it shares + is copied on first read, as usual. + The clone has its own index in both cases: ``put`` and ``delete`` on either storage replace or drop index entries without touching the arrays, so neither storage sees what the other stores, replaces or @@ -183,6 +212,11 @@ def get(self, period: Period, branch_name: str = "default") -> ArrayLike: # First read of an array shared by ``clone``: from here on the # caller may write into it, so it needs to be this storage's own. values = values.copy() + # Not reached today, since ``make_read_only`` copies every shared + # array and only ``clone`` shares them, in a storage that is not + # read-only; kept so the rule holds if that changes. + if self.read_only: + make_non_writable(values) self._arrays[key] = values self._stop_sharing(key) return values @@ -284,6 +318,10 @@ def put( ``derived`` marks a value the simulation calculated rather than took as input (see ``_inputs``), and ``sequence_number`` records when the value was stored (a new number by default); see :meth:`drop_computed`. + + In a read-only storage (see ``make_read_only``) ``value`` itself is + marked non-writable, so a caller still holding it cannot write into + the stored value either. """ if self.is_eternal: period = periods.period(periods.ETERNITY) @@ -293,6 +331,8 @@ def put( # would be ambiguous to parse back, as ``OnDiskStorage.put`` does. check_storable(branch_name, period) key = f"{branch_name}:{period}" + if self.read_only: + make_non_writable(value) self._arrays[key] = value self._stop_sharing(key) if derived: diff --git a/policyengine_core/data_storage/non_writable.py b/policyengine_core/data_storage/non_writable.py new file mode 100644 index 000000000..ccf3ad106 --- /dev/null +++ b/policyengine_core/data_storage/non_writable.py @@ -0,0 +1,20 @@ +import numpy + + +def make_non_writable(value) -> None: + """Mark ``value``'s data non-writable, if it is a numpy array. + + The flag is set on the array object itself, so it holds for every holder + of that object: a later in-place write through it raises ``ValueError``. + A masked array's mask is a separate array, so it is marked too, after + giving an array with no mask an all-false one of its own: otherwise + masking an entry in place would make a new, writable mask. Values that + are not numpy arrays are left as they are. + """ + if not isinstance(value, numpy.ndarray): + return + value.flags.writeable = False + if isinstance(value, numpy.ma.MaskedArray): + if value._mask is numpy.ma.nomask: + value.mask = numpy.ma.make_mask_none(value.shape, value.dtype) + value._mask.flags.writeable = False diff --git a/policyengine_core/data_storage/on_disk_storage.py b/policyengine_core/data_storage/on_disk_storage.py index 13c899f91..e7705dee1 100644 --- a/policyengine_core/data_storage/on_disk_storage.py +++ b/policyengine_core/data_storage/on_disk_storage.py @@ -9,6 +9,7 @@ from numpy.typing import ArrayLike from policyengine_core import periods +from policyengine_core.data_storage.non_writable import make_non_writable from policyengine_core.data_storage.store_history import ( _period_from_storage_key, advance_sequence_past, @@ -112,6 +113,10 @@ class OnDiskStorage: # Whether this storage writes only new files (see ``_path_to_write``). _detached = False _own_epoch = None + # Whether ``get`` returns, and ``put`` leaves, only non-writable arrays: + # set by ``make_read_only`` for a read-only simulation's holders (see + # ``Simulation.make_read_only``). A clone is not read-only. + read_only = False def __init__( self, @@ -290,6 +295,17 @@ def clone(self) -> "OnDiskStorage": self._own_paths = {} return clone + def make_read_only(self) -> None: + """Make ``get`` return non-writable arrays from here on, and ``put`` + mark the arrays it stores non-writable. + + Each ``get`` reads its file into a new array, so writing into one in + place never changed the stored value; the flag makes that write raise + all the same, as it does for a read-only ``InMemoryStorage``. The + files themselves are left as they are. + """ + self.read_only = True + def _decode_file(self, file: str) -> ArrayLike: enum = self._enums.get(file) if enum is not None: @@ -305,7 +321,10 @@ def get(self, period: Period, branch_name: str = "default") -> ArrayLike: values = self._files.get(f"{branch_name}_{period}") if values is None: return None - return self._decode_file(values) + array = self._decode_file(values) + if self.read_only: + make_non_writable(array) + return array def has(self, period: Period, branch_name: str = "default") -> bool: """Whether a value is stored for ``period`` under ``branch_name``. @@ -335,7 +354,8 @@ def put( """Store ``value`` for ``period`` on ``branch_name``. ``derived`` and ``sequence_number`` are as in - :meth:`InMemoryStorage.put`. + :meth:`InMemoryStorage.put`. In a read-only storage ``value`` is + marked non-writable, as there. """ if self.is_eternal: period = periods.period(periods.ETERNITY) @@ -345,6 +365,8 @@ def put( # ``InMemoryStorage.put`` rejects. A month anchored mid-month, say, # would be stored under the key of the calendar month. check_storable(branch_name, period) + if self.read_only: + make_non_writable(value) filename = f"{branch_name}_{period}" path = self._path_to_write(filename) diff --git a/policyengine_core/errors/__init__.py b/policyengine_core/errors/__init__.py index cd7cb6a09..4c80bc797 100644 --- a/policyengine_core/errors/__init__.py +++ b/policyengine_core/errors/__init__.py @@ -5,6 +5,7 @@ from .parameter_not_found_error import ParameterNotFoundError from .parameter_parsing_error import ParameterParsingError from .period_mismatch_error import PeriodMismatchError +from .read_only_simulation_error import ReadOnlySimulationError from .situation_parsing_error import SituationParsingError from .spiral_error import SpiralError from .variable_name_conflict_error import VariableNameConflictError diff --git a/policyengine_core/errors/read_only_simulation_error.py b/policyengine_core/errors/read_only_simulation_error.py new file mode 100644 index 000000000..433bd9946 --- /dev/null +++ b/policyengine_core/errors/read_only_simulation_error.py @@ -0,0 +1,23 @@ +class ReadOnlySimulationError(RuntimeError): + """An operation would change a simulation made read-only. + + Raised by an operation that would change the inputs, stored values or + tax-benefit system of a simulation after ``Simulation.make_read_only()``, + and by its next calculation once its parameters have changed (see + ``Simulation.make_read_only``). + """ + + +def refuse_on_read_only(simulation, operation: str) -> None: + """Raise :class:`ReadOnlySimulationError` if ``simulation`` is read-only. + + ``operation`` names what was refused, for the message. ``simulation`` may + be ``None``, or a stand-in object without the flag: neither is read-only. + """ + if getattr(simulation, "read_only", False): + raise ReadOnlySimulationError( + f"{operation} would change a read-only simulation. " + "make_read_only() was called on it, so it refuses changes to its " + "inputs, stored values and tax-benefit system. Make the change on " + "a branch (get_branch) or a clone instead." + ) diff --git a/policyengine_core/holders/helpers.py b/policyengine_core/holders/helpers.py index 1eba51fff..f6a860985 100644 --- a/policyengine_core/holders/helpers.py +++ b/policyengine_core/holders/helpers.py @@ -6,6 +6,7 @@ from policyengine_core import periods from policyengine_core.data_storage.store_history import _period_from_storage_key +from policyengine_core.errors.read_only_simulation_error import refuse_on_read_only from policyengine_core.holders.holder import Holder from policyengine_core.periods import Period @@ -76,8 +77,10 @@ def _store_input( The value is added to the simulation's record of inputs even when the helper is called directly instead of through ``Holder.set_input``, and ``calculate``'s fast cache drops the value it held for the period. + Raises ``ReadOnlySimulationError`` for a read-only simulation's holder. """ simulation = getattr(holder, "simulation", None) + refuse_on_read_only(simulation, "set_input") input_keys = getattr(simulation, "_user_input_keys", None) # Let the holder normalize and record the supplied-input tier, including # direct helper calls. Keep a legacy holder without an input record in @@ -261,6 +264,8 @@ def set_input_dispatch_by_period(holder: Holder, period: Period, array: ArrayLik To read more about ``set_input`` attributes, check the `documentation `_. """ + # Before anything is dropped or stored (see ``Simulation.make_read_only``). + refuse_on_read_only(getattr(holder, "simulation", None), "set_input") array = holder._to_array(array, validate_nan=True) period_size = period.size @@ -307,6 +312,8 @@ def set_input_divide_by_period(holder: Holder, period: Period, array: ArrayLike) To read more about ``set_input`` attributes, check the `documentation `_. """ + # Before anything is dropped or stored (see ``Simulation.make_read_only``). + refuse_on_read_only(getattr(holder, "simulation", None), "set_input") if not isinstance(array, numpy.ndarray): array = numpy.array(array) array = holder._to_array(array, validate_nan=True) diff --git a/policyengine_core/holders/holder.py b/policyengine_core/holders/holder.py index e695126e8..28e16e149 100644 --- a/policyengine_core/holders/holder.py +++ b/policyengine_core/holders/holder.py @@ -12,6 +12,7 @@ from policyengine_core.data_storage.store_history import next_sequence_number from policyengine_core.enums import Enum from policyengine_core.errors import PeriodMismatchError +from policyengine_core.errors.read_only_simulation_error import refuse_on_read_only from policyengine_core.periods import Period if TYPE_CHECKING: @@ -47,6 +48,15 @@ def __init__(self, variable: "Variable", population: "Population"): self._on_disk_storable = True if self.variable.name in self.simulation.memory_config.variables_to_drop: self._do_not_store = True + if getattr(self.simulation, "read_only", False): + self._make_read_only() + + def _make_read_only(self) -> None: + """Make every array this holder stores non-writable, now and from + here on (see ``Simulation.make_read_only``).""" + self._memory_storage.make_read_only() + if self._disk_storage is not None: + self._disk_storage.make_read_only() def _follow_definition(self, variable: "Variable") -> None: """Take ``variable`` as this holder's definition when its storage fits. @@ -147,6 +157,21 @@ def delete_arrays( A deleted value set with ``set_input`` stops counting as an input, so a value calculated later for the same period is not taken for one. + + Raises ``ReadOnlySimulationError`` for a read-only simulation's + holder (see ``Simulation.make_read_only``). + """ + refuse_on_read_only(getattr(self, "simulation", None), "delete_arrays") + self._delete_arrays(period, branch_name) + + def _delete_arrays( + self, period: Period = None, branch_name: str = "default" + ) -> None: + """:meth:`delete_arrays`, for a read-only simulation too. + + Core calls this when the deletion is part of a calculation: after a + spiral, it deletes the values calculated from the default the spiral + returned (``Simulation.purge_cache_of_invalid_values``). """ simulation = getattr(self, "simulation", None) user_input_keys = getattr(simulation, "_user_input_keys", None) @@ -616,7 +641,11 @@ def set_input( Custom handlers store replayable inputs with ``holder._set`` or ``holder.set_input``. Values written through ``put_in_cache`` are excluded from input export and reform replay. + + Raises ``ReadOnlySimulationError`` for a read-only simulation's + holder (see ``Simulation.make_read_only``). """ + refuse_on_read_only(getattr(self, "simulation", None), "set_input") period = periods.period(period) if ( diff --git a/policyengine_core/parameters/parameter.py b/policyengine_core/parameters/parameter.py index 171665c19..38bc642d0 100644 --- a/policyengine_core/parameters/parameter.py +++ b/policyengine_core/parameters/parameter.py @@ -127,8 +127,11 @@ def __eq__(self, other): return (self.name == other.name) and (self.values_list == other.values_list) def clone(self): + """Copy this parameter and its values, with no parent (see + ``ParameterNode.clone``).""" clone = empty_clone(self) clone.__dict__ = self.__dict__.copy() + clone.parent = None # Own dict, shared values: see ParameterAtInstant.clone. clone.metadata = copy.copy(self.metadata) @@ -214,7 +217,9 @@ def update( self.values_list = new_values - self.parent.clear_parent_cache() + # A parameter cloned on its own has no parent (see ``clone``). + if getattr(self, "parent", None) is not None: + self.parent.clear_parent_cache() self.mark_as_modified() @@ -222,7 +227,8 @@ def update( def mark_as_modified(self): self.modified = True - self.parent.mark_as_modified() + if getattr(self, "parent", None) is not None: + self.parent.mark_as_modified() def get_descendants(self): return iter(()) diff --git a/policyengine_core/parameters/parameter_node.py b/policyengine_core/parameters/parameter_node.py index f1c2f84ed..ea4b3f13c 100644 --- a/policyengine_core/parameters/parameter_node.py +++ b/policyengine_core/parameters/parameter_node.py @@ -93,6 +93,36 @@ def _clear_at_instant_caches_upward(node) -> None: node = getattr(node, "parent", None) +def change_counting_nodes(parameters) -> tuple: + """The nodes whose ``_change_count`` count the changes made in the tree + under ``parameters``. + + ``mark_as_modified`` adds one to the count of every node it passes on its + way up the ``parent`` links, so the node at the top of those links counts + every change made below it. For each child of ``parameters`` this follows + its ``parent`` links to the top, and returns each node reached once, in + the order of the children. That is normally just ``parameters``. But a + shallow copy of a tree's top node (policyengine-us makes one for each + traced simulation) shares the original's children, whose ``parent`` is + still the original, while a child added through the copy has the copy as + its parent. Empty when ``parameters`` has no children (or is not a + parameter node): such a tree holds no parameter values. + """ + children = getattr(parameters, "children", None) + if not children: + return () + counting_nodes = [] + for child in children.values(): + node = child + visited = set() + while getattr(node, "parent", None) is not None and id(node) not in visited: + visited.add(id(node)) + node = node.parent + if not any(node is counting_node for counting_node in counting_nodes): + counting_nodes.append(node) + return tuple(counting_nodes) + + class _AtInstantCache(dict): """A parameter node's nodes at instant, by instant. @@ -130,6 +160,16 @@ class ParameterNode(AtInstantLike): parent: "ParameterNode" = None """The parent of the node, or None if the node is the root of the tree.""" + _change_count: int = 0 + """How many times a change below this node was recorded: each + ``mark_as_modified`` that reaches the node (``Parameter.update`` calls it, + and so do the scale and node equivalents) adds one, as does + ``TaxBenefitSystem.modify_parameters`` for the tree it passes on. A + read-only simulation compares the counts on the nodes + ``change_counting_nodes`` finds with the ones it recorded (see + ``Simulation.make_read_only``). An edit that bypasses those, such as + assigning ``values_list`` or calling ``add_child`` directly, adds nothing.""" + def __init__( self, name: str = "", @@ -344,8 +384,16 @@ def get_descendants(self) -> Iterable[Union["ParameterNode", Parameter]]: yield from child.get_descendants() def clone(self) -> "ParameterNode": + """Copy this node and everything below it. + + The copy has no parent: it is the top node of a tree of its own, so + changes made in it do not mark the tree this node is in modified, nor + clear its caches. Cloning the node holding this one sets the parent + of the copy it makes. + """ clone = commons.empty_clone(self) clone.__dict__ = self.__dict__.copy() + clone.parent = None # Own dict, shared values: see ParameterAtInstant.clone. clone.metadata = copy.copy(self.metadata) @@ -391,6 +439,7 @@ def clear_parent_cache(self): def mark_as_modified(self): self.modified = True + self._change_count += 1 if self.parent is not None: self.parent.mark_as_modified() diff --git a/policyengine_core/parameters/parameter_scale.py b/policyengine_core/parameters/parameter_scale.py index 507d01511..b838013ab 100644 --- a/policyengine_core/parameters/parameter_scale.py +++ b/policyengine_core/parameters/parameter_scale.py @@ -117,8 +117,11 @@ def mark_as_modified(self): self.parent.mark_as_modified() def clone(self) -> "ParameterScale": + """Copy this scale and its brackets, with no parent (see + ``ParameterNode.clone``).""" clone = commons.empty_clone(self) clone.__dict__ = self.__dict__.copy() + clone.parent = None clone.brackets = [bracket.clone() for bracket in self.brackets] for bracket in clone.brackets: diff --git a/policyengine_core/simulations/simulation.py b/policyengine_core/simulations/simulation.py index 55c4a2f52..bf1352d6f 100644 --- a/policyengine_core/simulations/simulation.py +++ b/policyengine_core/simulations/simulation.py @@ -15,6 +15,7 @@ from policyengine_core import commons, periods from policyengine_core.data.dataset import Dataset +from policyengine_core.data_storage.non_writable import make_non_writable from policyengine_core.data_storage.store_history import ( StoreHistory, next_sequence_number, @@ -25,7 +26,8 @@ ) from policyengine_core.entities.entity import Entity from policyengine_core.enums import Enum, EnumArray -from policyengine_core.errors import CycleError, SpiralError +from policyengine_core.errors import CycleError, ReadOnlySimulationError, SpiralError +from policyengine_core.errors.read_only_simulation_error import refuse_on_read_only from policyengine_core.holders.holder import Holder from policyengine_core.periods import Instant, Period from policyengine_core.periods.config import ETERNITY, MONTH, YEAR @@ -178,6 +180,7 @@ def _latest_input_key(period: Period, definition_period: str) -> tuple: from policyengine_core.variables import Variable, QuantityType from policyengine_core.reforms.reform import Reform from policyengine_core.parameters import get_parameter +from policyengine_core.parameters.parameter_node import change_counting_nodes from policyengine_core.simulations.simulation_macro_cache import ( SimulationMacroCache, ) @@ -751,6 +754,24 @@ class Simulation: start_instant: str = None """The earliest data input instant of the simulation.""" + # Set by ``make_read_only``; see ``read_only``. + _read_only: bool = False + + # The parameter tree's top node's ``children`` mapping, and the nodes + # counting changes to the tree (see ``change_counting_nodes``) with their + # counts, when ``make_read_only`` ran. + _read_only_parameters: Optional[ + Tuple[Optional[Dict[str, Any]], Tuple[Tuple[Any, int], ...]] + ] = None + + @property + def read_only(self) -> bool: + """Whether the simulation refuses changes to its inputs, stored values + and tax-benefit system. Only :meth:`make_read_only` sets it, and it is + copied to nothing else: a clone or branch of a read-only simulation is + not read-only.""" + return self._read_only + # The temporary folder this simulation made for the values it stores on # disk, if it made one (see ``data_storage_dir``). _storage_directory: TemporaryStorageDirectory = None @@ -785,6 +806,35 @@ def _data_storage_dir(self, path: Optional[str]) -> None: None if path is None else directory_containing(os.fspath(path)) ) + @property + def tax_benefit_system(self) -> "TaxBenefitSystem": + """The tax-benefit system the simulation calculates with. + + Kept in the instance's ``__dict__`` under the same name, which this + property takes precedence over, so ``clone`` copies it with the rest + of the instance. Assigning it on a read-only simulation raises + ``ReadOnlySimulationError`` (see :meth:`make_read_only`). + """ + try: + return self.__dict__["tax_benefit_system"] + except KeyError: + raise AttributeError( + f"{type(self).__name__!r} object has no attribute 'tax_benefit_system'" + ) from None + + @tax_benefit_system.setter + def tax_benefit_system(self, system: "TaxBenefitSystem") -> None: + refuse_on_read_only(self, "Assigning tax_benefit_system") + self.__dict__["tax_benefit_system"] = system + + @tax_benefit_system.deleter + def tax_benefit_system(self) -> None: + refuse_on_read_only(self, "Deleting tax_benefit_system") + try: + del self.__dict__["tax_benefit_system"] + except KeyError: + raise AttributeError("tax_benefit_system") from None + def __init__( self, tax_benefit_system: "TaxBenefitSystem" = None, @@ -960,7 +1010,118 @@ def __init__( self.parent_branch = None + def make_read_only(self) -> None: + """Make this simulation refuse every change to its inputs, stored + values and tax-benefit system. + + It still calculates a value it does not hold yet, and keeps it. From + here on: + + - ``set_input`` and ``delete_arrays`` (on the simulation or one of its + holders), ``drop_computed_arrays``, ``invalidate_cache_entry``, + ``apply_reform``, ``subsample``, ``build_from_dataset``, + ``build_from_populations`` and assigning or deleting + ``tax_benefit_system`` raise ``ReadOnlySimulationError`` and change + nothing. As a registered branch, it keeps what it holds when its + parent applies a reform; its own branches are cleared as usual. + - Every array it stores is non-writable: those it holds now, those it + calculates, and those its disk storage reads back. Writing into one + in place, as a formula that modifies an array it read would, raises + numpy's ``ValueError``. The flag is set on the array object itself, + so it holds for anything else holding the same object: an array + given to ``set_input`` that was stored as it was given, or another + simulation's array that a formula returned as it was. An array it + still shares with the simulation it was branched from is copied + first. + - Its parameter tree's change counts are recorded, on the nodes + that count the tree's changes (see ``change_counting_nodes``: + normally the tree's top node, or the original a shallow copy of it + shares children with). Its next calculation, including one answered + from what it holds, raises ``ReadOnlySimulationError`` once a count + has moved (an update anywhere in the tree, made through any + simulation or system that shares it) or its system has another + tree. A clone of part of the tree is a tree of its own. + - ``get_branch`` with a name it has not registered returns a new + branch every time and keeps it out of ``branches``, so nothing done + through the branch stays in this simulation. The branch is part of + the simulation, reads its values, and is not read-only: it takes + inputs and keeps branches of its own. A second ``get_branch`` with + the same name, including one made when core runs a calculation + again after an input change, gets another new branch, without what + was set on the first. + + 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 + 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. + + Not detected: + + - formula changes made in place on its tax-benefit system object + (``neutralize_variable``, ``update_variable``, ``add_variable``), by + a branch that shares the system (``get_branch`` without + ``clone_system``) or anything else holding it; + - parameter edits that record no change: assigning ``values_list`` or + a ``ParameterAtInstant``'s value, or ``add_child``, outside + ``TaxBenefitSystem.modify_parameters``; + - writes made through a holder's low-level ``_set`` or + ``put_in_cache``, or straight into its storage, which still store + (non-writable) values, replacing what is stored; + - the populations' structure arrays (IDs, memberships and roles), + which stay writable: clones and branches share them; + - writes through a view of a stored array taken before this call, or + into an array object a formula returned as a view of another + simulation's writable array. + """ + if self.read_only: + return + parameters = self.tax_benefit_system.parameters + self._read_only_parameters = ( + getattr(parameters, "children", None), + tuple( + (counting_node, getattr(counting_node, "_change_count", 0)) + for counting_node in change_counting_nodes(parameters) + ), + ) + self._read_only = True + for population in getattr(self, "populations", {}).values(): + for holder in population._holders.values(): + holder._make_read_only() + for array in (getattr(self, "_fast_cache", None) or {}).values(): + make_non_writable(array) + + def _refuse_if_parameters_changed(self) -> None: + """Raise ``ReadOnlySimulationError`` if the parameters a read-only + simulation recorded have changed since (see :meth:`make_read_only`). + + The tree is the same while its top node holds the same ``children`` + mapping: a shallow copy of the top node (policyengine-us makes one + for each traced simulation) holds the original's, while a clone or + another tree holds its own. + """ + recorded_children, recorded_change_counts = self._read_only_parameters + parameters = self.tax_benefit_system.parameters + if getattr(parameters, "children", None) is not recorded_children: + raise ReadOnlySimulationError( + "The tax-benefit system of this read-only simulation has a " + "different parameter tree from the one it had when " + "make_read_only() was called, so the values it holds may no " + "longer match its parameters." + ) + for counting_node, recorded_change_count in recorded_change_counts: + if getattr(counting_node, "_change_count", 0) != recorded_change_count: + raise ReadOnlySimulationError( + "A parameter of this read-only simulation changed after " + "make_read_only() was called, so the values it holds may " + "no longer match its parameters." + ) + def apply_reform(self, reform: Union[tuple, Reform]): + refuse_on_read_only(self, "apply_reform") if isinstance(reform, tuple): for subreform in reform: self.apply_reform(subreform) @@ -990,7 +1151,16 @@ def _invalidate_all_caches(self) -> None: else (formula outputs, cached short-path results, on-disk caches) is wiped so the next ``calculate`` recomputes under the new tax-benefit system. + + A read-only simulation (see ``make_read_only``) keeps what it holds, + and only its branches are cleared: it is reached here only as a + branch of a simulation applying a reform, and if the reform changed + its parameters, its next calculation raises instead. """ + if self.read_only: + for branch in self.branches.values(): + branch._invalidate_all_caches() + return self.invalidated_caches = set() # Snapshot user-provided inputs before wiping so they can be # replayed into the fresh storage. Use the storage API instead of @@ -1104,6 +1274,7 @@ def build_from_populations(self, populations: Dict[str, Population]) -> None: Args: populations (Dict[str, Population]): A dictionary of populations, indexed by entity key. """ + refuse_on_read_only(self, "build_from_populations") self.populations = populations self.link_to_entities_instances() self.create_shortcuts() @@ -1129,6 +1300,7 @@ def build_from_dataset(self) -> None: Explicit dataset role columns do not validate role capacity. ``default_role=None`` requires a role column. """ + refuse_on_read_only(self, "build_from_dataset") self.build_from_populations(self.tax_benefit_system.instantiate_entities()) from policyengine_core.simulations.simulation_builder import ( SimulationBuilder, @@ -1366,6 +1538,13 @@ def _bind_to_tax_benefit_system(self) -> None: gives it a list of its own. Between reforms, ``Population.get_holder`` keeps compatible holders on the current definitions. """ + if self.read_only: + # Binding can drop holders, and with them what a read-only + # simulation holds (see ``make_read_only``). Its branches are + # bound as usual. + for branch in self.branches.values(): + branch._bind_to_tax_benefit_system() + return system = self.tax_benefit_system if system is None: # A reform simulation of a class with no default system instance @@ -1498,6 +1677,9 @@ def calculate( ArrayLike: The calculated variable. """ + if self.read_only: + self._refuse_if_parameters_changed() + if period is not None and not isinstance(period, Period): period = periods.period(period) elif period is None and self.default_calculation_period is not None: @@ -1777,6 +1959,9 @@ def _calculate(self, variable_name: str, period: Period = None) -> ArrayLike: sequence_number = next_sequence_number() holder._record_store(period, sequence_number) self._get_store_history().record_unknown_sources(sequence_number) + if self.read_only: + # As a value read back from disk storage is. + make_non_writable(value) return value if variable.requires_computation_after is not None: @@ -2078,6 +2263,9 @@ def _calculate(self, variable_name: str, period: Period = None) -> ArrayLike: smc.set_cache_value(cache_path, array) if hasattr(self, "_fast_cache") and unchanged: + if self.read_only: + # The default a spiral returns is kept here, not stored. + make_non_writable(array) self._fast_cache[(variable_name, period)] = array return array @@ -2158,7 +2346,13 @@ def _cache_result( first. A calculation that was running when an input set on this simulation dropped values may have read the replaced value, so its result is returned but not kept (see ``_drop_computed``). + + In a read-only simulation the value returned is non-writable, as what + is stored is: the caller, and the fast cache, may hold this array + rather than the stored one (storing can convert it). """ + if self.read_only: + make_non_writable(array) epoch, inputs_set, started_at = input_state if inputs_set != self._inputs_set: stored_input = self._input_set_meanwhile(holder, period, started_at) @@ -2190,7 +2384,14 @@ def purge_cache_of_invalid_values(self) -> None: return for _name, _period in invalidated_caches: holder = self.get_holder(_name) - holder.delete_arrays(_period) + # Part of a calculation, so a read-only simulation runs it too, + # through the holder's method that does not refuse. A holder that + # is not core's (a test's stand-in, say) may only have the public + # one. + delete_arrays = getattr(holder, "_delete_arrays", None) + if delete_arrays is None: + delete_arrays = holder.delete_arrays + delete_arrays(_period) if _fast_cache is not None: _fast_cache.pop((_name, _period), None) self.invalidated_caches = set() @@ -2636,6 +2837,17 @@ def _check_for_cycle(self, variable: str, period: Period) -> None: raise SpiralError(message, variable) def invalidate_cache_entry(self, variable: str, period: Period) -> None: + """Delete the value of ``variable`` for ``period`` once the running + calculation ends (see :meth:`purge_cache_of_invalid_values`). + + Raises ``ReadOnlySimulationError`` on a read-only simulation (see + :meth:`make_read_only`). Core's own handling of a spiral, which is + part of a calculation, still invalidates values there. + """ + refuse_on_read_only(self, "invalidate_cache_entry") + self._invalidate_cache_entry(variable, period) + + def _invalidate_cache_entry(self, variable: str, period: Period) -> None: invalidated_caches = getattr(self, "invalidated_caches", None) if invalidated_caches is None: self.invalidated_caches = {(variable, period)} @@ -2649,7 +2861,7 @@ def invalidate_spiral_variables(self, variable: str) -> None: # for deletion from the cache once the calculation ends. count = 0 for frame in reversed(self.tracer.stack): - self.invalidate_cache_entry(frame["name"], frame["period"]) + self._invalidate_cache_entry(frame["name"], frame["period"]) if frame["name"] == variable: count += 1 if count > self.max_spiral_loops: @@ -2719,7 +2931,11 @@ def delete_arrays(self, variable: str, period: Period = None) -> None: True >>> simulation.get_array('age', '2018-05') is None True + + Raises ``ReadOnlySimulationError`` on a read-only simulation (see + :meth:`make_read_only`). """ + refuse_on_read_only(self, "delete_arrays") holder = self.get_holder(variable) for branch_name in self._get_visible_branch_names(): holder.delete_arrays(period, branch_name) @@ -2750,9 +2966,13 @@ def drop_computed_arrays(self) -> int: ``set_input`` on a branch drops what depends on the input by itself. Branches already created from this simulation keep their values. + Raises ``ReadOnlySimulationError`` on a read-only simulation (see + :meth:`make_read_only`). + Returns: int: The number of arrays deleted. """ + refuse_on_read_only(self, "drop_computed_arrays") # Recalculate rather than read macro-cache files written before. self.macro_cache_read = False for frame in _calculation_frames.get(): @@ -2841,7 +3061,11 @@ def set_input(self, variable_name: str, period: Period, value: ArrayLike) -> Non their values; and a value another simulation calculated from the branch and kept stays when the branch's input changes after that calculation ended. + + Raises ``ReadOnlySimulationError`` on a read-only simulation (see + :meth:`make_read_only`); a branch of it takes inputs. """ + refuse_on_read_only(self, "set_input") period = periods.period(period) if self.start_instant is None or self.start_instant > period.start: self.start_instant = period.start @@ -3015,6 +3239,9 @@ def clone( "tracer", "branches", "_fast_cache", + # A copy of a read-only simulation is not read-only. + "_read_only", + "_read_only_parameters", ): new_dict[key] = value # Aliases of this simulation's methods (``calc`` and ``df``, and any a @@ -3178,6 +3405,12 @@ def get_branch( tax-benefit system or parameters are changed should call :meth:`drop_computed_arrays` before calculating. + On a read-only simulation (see :meth:`make_read_only`), a name it has + not registered gives a new branch every time, which is not kept in + ``branches``: nothing done through it stays in this simulation. The + branch is not read-only. A name registered before ``make_read_only`` + gives that branch, as it is. + 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. @@ -3202,7 +3435,8 @@ def get_branch( finally: request.pending = False _branch_clone.reset(token) - self.branches[name] = branch + if not self.read_only: + self.branches[name] = branch branch.branch_name = name branch.parent_branch = self branch._fixed_point_branch = True @@ -3646,9 +3880,13 @@ def subsample( seed (int, optional): The key used to seed the random number generator. Defaults to the dataset name. time_period (str, optional): Sample households based on their weight in this time period. Defaults to the default calculation period. + Raises ``ReadOnlySimulationError`` on a read-only simulation (see + :meth:`make_read_only`). + Returns: Simulation: The quantized simulation. """ + refuse_on_read_only(self, "subsample") default_calculation_period = self.default_calculation_period # Set default key if not provided if seed is None: diff --git a/policyengine_core/simulations/simulation_builder.py b/policyengine_core/simulations/simulation_builder.py index 6b65cfe9b..5f9f9db1d 100644 --- a/policyengine_core/simulations/simulation_builder.py +++ b/policyengine_core/simulations/simulation_builder.py @@ -16,6 +16,7 @@ ) from policyengine_core.periods import Period from policyengine_core.populations import GroupPopulation, Population +from policyengine_core.errors.read_only_simulation_error import refuse_on_read_only from policyengine_core.simulations.simulation import Simulation from policyengine_core.simulations.helpers import ( check_type, @@ -173,6 +174,7 @@ def build_from_dict( This method uses :any:`build_from_entities` if entities are fully specified, or :any:`build_from_variables` if not. """ + refuse_on_read_only(simulation, "SimulationBuilder.build_from_dict") input_dict = self.explicit_singular_entities(tax_benefit_system, input_dict) if any( @@ -218,6 +220,7 @@ def build_from_entities( 'households': {'household': {'parents': ['Javier']}} }) """ + refuse_on_read_only(simulation, "SimulationBuilder.build_from_entities") input_dict = copy.deepcopy(input_dict) if simulation is None: @@ -323,6 +326,7 @@ def build_from_variables( {'salary': {'2016-10': 12000}} ) """ + refuse_on_read_only(simulation, "SimulationBuilder.build_from_variables") count = _get_person_count(input_dict) simulation = self.build_default_simulation( tax_benefit_system, count, simulation @@ -356,6 +360,7 @@ def build_default_simulation( TypeError: if ``count`` is not an integer, as ``range(count)`` would. """ + refuse_on_read_only(simulation, "SimulationBuilder.build_default_simulation") # ``np.arange`` accepts 2.5 or 2.0, and the simulation then fails in # ``sum`` or ``calculate``; ``operator.index`` refuses what ``range`` @@ -709,6 +714,12 @@ def add_variable_value( def finalize_variables_init(self, population): # Due to set_input mechanism, we must bufferize all inputs, then actually set them, # so that the months are set first and the years last. + # A read-only simulation's population is refused before anything in it + # changes (see ``Simulation.make_read_only``). + refuse_on_read_only( + getattr(population, "simulation", None), + "SimulationBuilder.finalize_variables_init", + ) plural_key = population.entity.plural if plural_key in self.entity_counts: population.count = self.get_count(plural_key) diff --git a/policyengine_core/taxbenefitsystems/tax_benefit_system.py b/policyengine_core/taxbenefitsystems/tax_benefit_system.py index 6137efe28..ba1980a7d 100644 --- a/policyengine_core/taxbenefitsystems/tax_benefit_system.py +++ b/policyengine_core/taxbenefitsystems/tax_benefit_system.py @@ -40,6 +40,7 @@ ParameterNodeAtInstant, Parameter, ) +from policyengine_core.parameters.parameter_node import change_counting_nodes from policyengine_core.parameters.operations.homogenize_parameters import ( homogenize_parameter_structures, ) @@ -835,7 +836,18 @@ def modify_parameters( period=periods.period(time_period), ) else: - reform_parameters = modifier_function(self.parameters) + parameters = self.parameters + try: + reform_parameters = modifier_function(parameters) + finally: + # The modifier may have changed the tree in place without + # ``update`` (assigning ``values_list``, say), so count a + # change where ``mark_as_modified`` would (see + # ``ParameterNode._change_count``). + for counting_node in change_counting_nodes(parameters): + counting_node._change_count = ( + getattr(counting_node, "_change_count", 0) + 1 + ) if not isinstance(reform_parameters, ParameterNode): return ValueError( "modifier_function {} in module {} must return a ParameterNode".format( diff --git a/tests/core/test_read_only_simulation.py b/tests/core/test_read_only_simulation.py new file mode 100644 index 000000000..677824953 --- /dev/null +++ b/tests/core/test_read_only_simulation.py @@ -0,0 +1,998 @@ +"""A simulation made read-only with ``make_read_only()``. + +A read-only simulation still calculates values it does not hold yet, and +keeps them. It refuses everything that would change its inputs, its stored +values or its tax-benefit system: + +- ``set_input`` and ``delete_arrays`` (on the simulation or a holder), + ``drop_computed_arrays``, ``invalidate_cache_entry``, ``apply_reform``, + ``subsample``, ``build_from_dataset``, ``build_from_populations``, + ``SimulationBuilder`` building into it, the ``set_input`` helpers, and + assigning or deleting ``tax_benefit_system`` raise + ``ReadOnlySimulationError`` and change nothing; +- every array it stores is non-writable, in memory or on disk, and so is a + value it reads from the macro cache, so writing into one in place raises + numpy's ``ValueError``; +- a parameter change after ``make_read_only()`` (an update anywhere in its + parameter tree, or a new tree) makes its next calculation raise. + +A branch it makes with ``get_branch`` is part of it, but private: the branch +is not kept in its ``branches``, so nothing done through the branch stays in +the read-only simulation. The branch is not read-only itself. +""" + +from __future__ import annotations + +import copy +import pickle +import types +import warnings + +import numpy as np +import pytest + +from policyengine_core import errors, periods +from policyengine_core.country_template import ( + CountryTaxBenefitSystem, + Microsimulation, + Simulation, +) +from policyengine_core.country_template.entities import Person +from policyengine_core.country_template.reforms.removal_basic_income import ( + removal_basic_income, +) +from policyengine_core.experimental import MemoryConfig +from policyengine_core.holders import ( + set_input_dispatch_by_period, + set_input_divide_by_period, +) +from policyengine_core.parameters import ParameterNode +from policyengine_core.simulations import SimulationBuilder +from policyengine_core.simulations.simulation_macro_cache import ( + SimulationMacroCache, +) +from policyengine_core.variables import Variable + +PERIOD = "2022-01" +INSTANT = periods.instant("2022-01-01") +BASELINE_INCOME_TAX_RATE = 0.15 +REFORM_INCOME_TAX_RATE = 0.42 +SALARY = [4000.0, 2500.0] +OTHER_SALARY = [1000.0, 3000.0] +SITUATION = { + "persons": { + "a": {"salary": {PERIOD: SALARY[0]}, "age": {PERIOD: 40}}, + "b": {"salary": {PERIOD: SALARY[1]}, "age": {PERIOD: 30}}, + }, + "households": {"h": {"parents": ["a", "b"]}}, +} +OUTPUTS = ["income_tax", "disposable_income", "total_taxes", "household_income"] + + +@pytest.fixture(scope="module") +def shared_system(): + """A system the tests in this module read but never change.""" + return CountryTaxBenefitSystem() + + +def build_simulation(tax_benefit_system) -> Simulation: + return Simulation(tax_benefit_system=tax_benefit_system, situation=SITUATION) + + +def stored_values(simulation) -> dict: + """Copies of every array the simulation's holders store, memory and disk.""" + values = {} + for population in simulation.populations.values(): + for variable_name, holder in population._holders.items(): + for branch_name, period in holder.get_known_branch_periods(): + array = holder._get_array_from_storage(period, branch_name) + values[(variable_name, branch_name, str(period))] = np.array( + array, copy=True + ) + return values + + +def stored_arrays(simulation) -> dict: + """The array objects the simulation's in-memory storages hold.""" + return { + (variable_name, key): array + for population in simulation.populations.values() + for variable_name, holder in population._holders.items() + for key, array in holder._memory_storage._arrays.items() + } + + +def assert_same_values(before: dict, after: dict) -> None: + assert before.keys() == after.keys() + for key, array in after.items(): + assert np.array_equal(array, before[key]), key + + +# ----- The flag ----- # + + +def test_a_simulation_is_read_only_only_once_made_read_only(shared_system): + simulation = build_simulation(shared_system) + assert simulation.read_only is False + + simulation.make_read_only() + + assert simulation.read_only is True + + +def test_a_clone_of_a_read_only_simulation_is_not_read_only(shared_system): + simulation = build_simulation(shared_system) + simulation.make_read_only() + + clone = simulation.clone() + clone.set_input("salary", PERIOD, OTHER_SALARY) + + assert clone.read_only is False + assert clone.calculate("salary", PERIOD).tolist() == OTHER_SALARY + assert clone.calculate("salary", PERIOD).flags.writeable + assert simulation.calculate("salary", PERIOD).tolist() == SALARY + + +# ----- Refused operations ----- # + +REFUSED_OPERATIONS = [ + pytest.param( + lambda simulation: simulation.set_input("salary", PERIOD, OTHER_SALARY), + id="set_input", + ), + pytest.param( + lambda simulation: simulation.get_holder("salary").set_input( + periods.period(PERIOD), OTHER_SALARY + ), + id="holder-set_input", + ), + pytest.param( + lambda simulation: simulation.delete_arrays("salary", PERIOD), + id="delete_arrays-one-period", + ), + pytest.param( + lambda simulation: simulation.delete_arrays("income_tax"), + id="delete_arrays-every-period", + ), + pytest.param( + lambda simulation: simulation.get_holder("income_tax").delete_arrays(), + id="holder-delete_arrays", + ), + pytest.param( + lambda simulation: simulation.drop_computed_arrays(), + id="drop_computed_arrays", + ), + pytest.param( + lambda simulation: simulation.apply_reform(removal_basic_income), + id="apply_reform", + ), + pytest.param( + lambda simulation: simulation.subsample(n=1), + id="subsample", + ), + pytest.param( + lambda simulation: simulation.build_from_dataset(), + id="build_from_dataset", + ), + pytest.param( + lambda simulation: simulation.build_from_populations( + simulation.tax_benefit_system.instantiate_entities() + ), + id="build_from_populations", + ), + pytest.param( + lambda simulation: setattr( + simulation, + "tax_benefit_system", + simulation.tax_benefit_system.clone(), + ), + id="assign-tax_benefit_system", + ), + pytest.param( + lambda simulation: delattr(simulation, "tax_benefit_system"), + id="delete-tax_benefit_system", + ), + pytest.param( + # The next calculation would delete the value (see + # ``purge_cache_of_invalid_values``). + lambda simulation: simulation.invalidate_cache_entry( + "salary", periods.period(PERIOD) + ), + id="invalidate_cache_entry", + ), + pytest.param( + lambda simulation: SimulationBuilder().build_from_dict( + simulation.tax_benefit_system, + { + "persons": {"x": {}, "y": {}, "z": {}}, + "households": {"h": {"parents": ["x", "y"], "children": ["z"]}}, + }, + simulation, + ), + id="builder-entities-into-it", + ), + pytest.param( + lambda simulation: SimulationBuilder().build_from_dict( + simulation.tax_benefit_system, + {"salary": {PERIOD: [1.0, 2.0, 3.0, 4.0, 5.0]}}, + simulation, + ), + id="builder-variables-into-it", + ), + pytest.param( + lambda simulation: set_input_divide_by_period( + simulation.get_holder("salary"), + periods.period("2022"), + np.array([12000.0, 24000.0]), + ), + id="set_input_divide_by_period", + ), + pytest.param( + lambda simulation: set_input_dispatch_by_period( + simulation.get_holder("salary"), + periods.period("2022"), + np.array([1000.0, 2000.0]), + ), + id="set_input_dispatch_by_period", + ), + pytest.param( + lambda simulation: _finalize_builder_persons_into(simulation), + id="builder-finalize_variables_init", + ), +] + + +def _finalize_builder_persons_into(simulation) -> None: + builder = SimulationBuilder() + builder.add_person_entity(simulation.persons.entity, {"x": {}, "y": {}, "z": {}}) + builder.finalize_variables_init(simulation.persons) + + +def population_structure(simulation) -> dict: + """Each population's size, IDs and memberships.""" + return { + key: ( + population.count, + list(population.ids), + None if population.entity.is_person else list(population.members_entity_id), + ) + for key, population in simulation.populations.items() + } + + +@pytest.mark.parametrize("refused_operation", REFUSED_OPERATIONS) +def test_a_read_only_simulation_refuses_the_operation_and_changes_nothing( + refused_operation, +): + simulation = build_simulation(CountryTaxBenefitSystem()) + for output in OUTPUTS: + simulation.calculate(output, PERIOD) + simulation.make_read_only() + values_before = stored_values(simulation) + system_before = simulation.tax_benefit_system + parameters_before = system_before.parameters + populations_before = dict(simulation.populations) + variables_before = dict(system_before.variables) + branches_before = dict(simulation.branches) + start_instant_before = simulation.start_instant + structure_before = population_structure(simulation) + + with pytest.raises(errors.ReadOnlySimulationError): + refused_operation(simulation) + + assert population_structure(simulation) == structure_before + + assert_same_values(values_before, stored_values(simulation)) + assert simulation.tax_benefit_system is system_before + assert simulation.tax_benefit_system.parameters is parameters_before + assert simulation.tax_benefit_system.variables == variables_before + assert simulation.populations == populations_before + assert simulation.branches == branches_before + assert simulation.start_instant == start_instant_before + # It still calculates, and gives what it gave before. + for output in OUTPUTS: + assert np.array_equal( + simulation.calculate(output, PERIOD), + values_before[(output, "default", PERIOD)], + ) + + +# ----- Non-writable arrays ----- # + + +def test_inputs_stored_before_make_read_only_become_non_writable(shared_system): + simulation = build_simulation(shared_system) + salary = simulation.get_array("salary", PERIOD) + + simulation.make_read_only() + + assert not salary.flags.writeable + with pytest.raises(ValueError, match="read-only"): + salary[0] = 0.0 + assert simulation.calculate("salary", PERIOD).tolist() == SALARY + + +def test_values_calculated_before_make_read_only_become_non_writable(shared_system): + simulation = build_simulation(shared_system) + income_tax = simulation.calculate("income_tax", PERIOD) + expected = np.array(income_tax, copy=True) + + simulation.make_read_only() + + assert not simulation.get_array("income_tax", PERIOD).flags.writeable + # A repeated calculation is answered from the simulation's fast cache. + repeated = simulation.calculate("income_tax", PERIOD) + assert not repeated.flags.writeable + with pytest.raises(ValueError, match="read-only"): + repeated += 1 + assert np.array_equal(simulation.calculate("income_tax", PERIOD), expected) + + +def test_every_array_a_read_only_simulation_stores_is_non_writable(shared_system): + simulation = build_simulation(shared_system) + simulation.make_read_only() + + disposable_income = simulation.calculate("disposable_income", PERIOD) + simulation.calculate("household_income", PERIOD) + + assert not disposable_income.flags.writeable + arrays = stored_arrays(simulation) + assert ("disposable_income", f"default:{PERIOD}") in arrays + for key, array in arrays.items(): + assert not array.flags.writeable, key + + +class salary_doubled_in_place(Variable): + value_type = float + entity = Person + definition_period = periods.MONTH + label = "Salary doubled by writing into the salary array it read" + + def formula(person, period, parameters): + salary = person("salary", period) + salary *= 2 + return salary + + +def test_a_formula_writing_into_an_array_it_read_raises(): + system = CountryTaxBenefitSystem() + system.add_variable(salary_doubled_in_place) + simulation = build_simulation(system) + simulation.make_read_only() + + with pytest.raises(ValueError, match="read-only"): + simulation.calculate("salary_doubled_in_place", PERIOD) + + assert simulation.calculate("salary", PERIOD).tolist() == SALARY + + +class salary_as_masked_array(Variable): + value_type = float + entity = Person + definition_period = periods.MONTH + label = "Salary, returned as a masked array" + + def formula(person, period, parameters): + return np.ma.masked_array(person("salary", period)) + + +def _assert_mask_refuses_changes(stored) -> None: + assert isinstance(stored, np.ma.MaskedArray) + with pytest.raises(ValueError, match="read-only"): + stored[0] = np.ma.masked + with pytest.raises(ValueError, match="read-only"): + stored.mask = [True, False] + assert not np.ma.getmaskarray(stored).any() + + +@pytest.mark.parametrize( + "masked_salary", + [ + pytest.param(np.ma.masked_array(SALARY), id="no-mask"), + pytest.param(np.ma.masked_array(SALARY, mask=[False, False]), id="mask"), + ], +) +def test_a_masked_array_stored_before_make_read_only_refuses_masking( + shared_system, masked_salary +): + simulation = build_simulation(shared_system) + simulation.set_input("salary", PERIOD, masked_salary) + simulation.make_read_only() + + _assert_mask_refuses_changes(simulation.get_array("salary", PERIOD)) + + +def test_a_masked_array_a_read_only_simulation_calculates_refuses_masking(): + system = CountryTaxBenefitSystem() + system.add_variable(salary_as_masked_array) + simulation = build_simulation(system) + simulation.make_read_only() + + simulation.calculate("salary_as_masked_array", PERIOD) + + _assert_mask_refuses_changes(simulation.get_array("salary_as_masked_array", PERIOD)) + + +def _simulation_storing_on_disk(tax_benefit_system) -> Simulation: + simulation = build_simulation(tax_benefit_system) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + # Every holder made from here on stores its values on disk. + simulation.memory_config = MemoryConfig(max_memory_occupation=0) + return simulation + + +def test_values_stored_on_disk_before_make_read_only_read_back_non_writable( + shared_system, +): + simulation = _simulation_storing_on_disk(shared_system) + simulation.calculate("income_tax", PERIOD) + assert simulation.get_holder("income_tax")._disk_storage.has(periods.period(PERIOD)) + + simulation.make_read_only() + + stored = simulation.get_array("income_tax", PERIOD) + assert not stored.flags.writeable + with pytest.raises(ValueError, match="read-only"): + stored[0] = 0.0 + + +def test_values_a_read_only_simulation_stores_on_disk_are_non_writable( + shared_system, +): + simulation = _simulation_storing_on_disk(shared_system) + simulation.make_read_only() + + income_tax = simulation.calculate("income_tax", PERIOD) + + assert simulation.get_holder("income_tax")._disk_storage.has(periods.period(PERIOD)) + assert not income_tax.flags.writeable + assert not simulation.get_array("income_tax", PERIOD).flags.writeable + + +def test_the_first_read_of_an_array_shared_with_another_simulation_is_non_writable( + shared_system, +): + simulation = build_simulation(shared_system) + simulation.calculate("income_tax", PERIOD) + # A branch starts by sharing its parent's arrays, and copies each one the + # first time it reads it. + branch = simulation.get_branch("made_read_only_later") + branch.make_read_only() + + income_tax = branch.get_array("income_tax", PERIOD) + + assert not income_tax.flags.writeable + assert not branch.calculate("salary", PERIOD).flags.writeable + + +def test_a_read_only_branch_keeps_its_values_when_its_parent_writes_in_place( + shared_system, +): + parent = build_simulation(shared_system) + income_tax = np.array(parent.calculate("income_tax", PERIOD), copy=True) + branch = parent.get_branch("made_read_only_later") + branch.make_read_only() + + # The parent is not read-only: a formula there could write into a value + # it stores, which the branch shared until it first read it. + parent.get_array("income_tax", PERIOD)[0] = -1.0 + + assert np.array_equal(branch.get_array("income_tax", PERIOD), income_tax) + assert np.array_equal(branch.calculate("income_tax", PERIOD), income_tax) + + +# ----- Simulations that are not read-only ----- # + + +def test_updating_a_clone_of_a_subtree_leaves_the_original_tree_unmarked(): + system = CountryTaxBenefitSystem() + assert not system.parameters.modified + taxes_copy = system.parameters.taxes.clone() + + taxes_copy.income_tax_rate.update(start=INSTANT, value=0.5) + + assert taxes_copy.parent is None + assert not system.parameters.modified + assert not system.parameters.taxes.modified + assert system.parameters.taxes.income_tax_rate(INSTANT) == BASELINE_INCOME_TAX_RATE + + +def test_deleting_the_system_of_a_simulation_that_is_not_read_only_still_works( + shared_system, +): + simulation = build_simulation(shared_system) + + del simulation.tax_benefit_system + + assert not hasattr(simulation, "tax_benefit_system") + + +def test_a_parents_reform_leaves_a_read_only_branch_unchanged(): + parent = build_simulation(CountryTaxBenefitSystem()) + branch = parent.get_branch("own_system", clone_system=True) + for output in OUTPUTS: + branch.calculate(output, PERIOD) + branch.make_read_only() + branch_system = branch.tax_benefit_system + values_before = stored_values(branch) + + parent.apply_reform(removal_basic_income) + + assert branch.tax_benefit_system is branch_system + assert_same_values(values_before, stored_values(branch)) + for output in OUTPUTS: + assert np.array_equal( + branch.calculate(output, PERIOD), + values_before[(output, "own_system", PERIOD)], + ) + + +def test_a_parents_reform_still_clears_the_branches_of_a_read_only_branch(): + parent = build_simulation(CountryTaxBenefitSystem()) + # Both branches share the parent's system, so the reform reaches them. + read_only_branch = parent.get_branch("read_only_branch") + nested_branch = read_only_branch.get_branch("nested_branch") + nested_branch.calculate("income_tax", PERIOD) + read_only_branch.make_read_only() + + parent.apply_reform( + {"taxes.income_tax_rate": {"2022-01-01": REFORM_INCOME_TAX_RATE}} + ) + + # The nested branch is not read-only: it recalculates under the reform. + assert np.allclose( + nested_branch.calculate("income_tax", PERIOD), + np.array(SALARY) * REFORM_INCOME_TAX_RATE, + ) + # The read-only branch keeps its values, and refuses to calculate with + # parameters that changed under it. + with pytest.raises(errors.ReadOnlySimulationError): + read_only_branch.calculate("income_tax", PERIOD) + + +def test_a_value_read_from_the_macro_cache_is_non_writable(tmp_path, monkeypatch): + system = CountryTaxBenefitSystem() + simulation = build_simulation(system) + simulation.make_read_only() + # Serve income_tax from a macro-cache file, as a simulation built over a + # dataset would. + cache_file_path = tmp_path / "income_tax.h5" + cache_file_path.touch() + simulation.macro_cache_read = True + simulation.dataset = types.SimpleNamespace( + file_path=tmp_path / "dataset.h5", name="dataset" + ) + monkeypatch.setattr(Simulation, "check_macro_cache", lambda *arguments: True) + monkeypatch.setattr(SimulationMacroCache, "set_cache_path", lambda *arguments: None) + monkeypatch.setattr( + SimulationMacroCache, "get_cache_path", lambda self: cache_file_path + ) + monkeypatch.setattr( + SimulationMacroCache, + "get_cache_value", + lambda self, path: np.array([600.0, 375.0], dtype=np.float32), + ) + + income_tax = simulation.calculate("income_tax", PERIOD) + + assert income_tax.tolist() == [600.0, 375.0] + assert not income_tax.flags.writeable + + +def test_assigning_read_only_directly_is_refused(shared_system): + simulation = build_simulation(shared_system) + + with pytest.raises(AttributeError): + simulation.read_only = True + + assert simulation.read_only is False + assert simulation.calculate("salary", PERIOD).tolist() == SALARY + + +# ----- Parameter changes ----- # + + +def _update_income_tax_rate(system): + system.parameters.taxes.income_tax_rate.update(start=INSTANT, value=0.5) + + +def _update_a_scale_bracket_rate(system): + system.parameters.taxes.social_security_contribution.brackets[0].rate.update( + start=INSTANT, value=0.5 + ) + + +def _mark_a_node_modified(system): + system.parameters.benefits.mark_as_modified() + + +def _mark_a_scale_modified(system): + system.parameters.taxes.social_security_contribution.mark_as_modified() + + +def _modify_parameters_with_a_dictionary(system): + system.modify_parameters({"taxes.income_tax_rate": {"2022-01-01": 0.5}}) + + +def _edit_values_in_place_through_modify_parameters(system): + def replace_income_tax_rate_values(parameters): + income_tax_rate = parameters.taxes.income_tax_rate + income_tax_rate.values_list = income_tax_rate.values_list[-1:] + return parameters + + system.modify_parameters(replace_income_tax_rate_values) + + +def _replace_the_parameter_tree(system): + system.parameters = system.parameters.clone() + + +PARAMETER_CHANGES = [ + pytest.param(_update_income_tax_rate, id="parameter-update"), + pytest.param(_update_a_scale_bracket_rate, id="scale-bracket-update"), + pytest.param(_mark_a_node_modified, id="node-marked-modified"), + pytest.param(_mark_a_scale_modified, id="scale-marked-modified"), + pytest.param(_modify_parameters_with_a_dictionary, id="modify_parameters-dict"), + pytest.param( + _edit_values_in_place_through_modify_parameters, + id="modify_parameters-in-place-edit", + ), + pytest.param(_replace_the_parameter_tree, id="new-parameter-tree"), +] + + +@pytest.mark.parametrize("change_parameters", PARAMETER_CHANGES) +def test_a_parameter_change_after_make_read_only_makes_the_next_calculation_raise( + change_parameters, +): + system = CountryTaxBenefitSystem() + simulation = build_simulation(system) + simulation.calculate("income_tax", PERIOD) + simulation.make_read_only() + + change_parameters(system) + + # A value it holds (answered from the fast cache) and a new one. + with pytest.raises(errors.ReadOnlySimulationError): + simulation.calculate("income_tax", PERIOD) + with pytest.raises(errors.ReadOnlySimulationError): + simulation.calculate("disposable_income", PERIOD) + + +@pytest.mark.parametrize("change_parameters", PARAMETER_CHANGES) +def test_a_parameter_change_before_make_read_only_is_accepted(change_parameters): + system = CountryTaxBenefitSystem() + simulation = build_simulation(system) + change_parameters(system) + + simulation.make_read_only() + + simulation.calculate("disposable_income", PERIOD) + + +def test_a_parameter_change_on_a_branch_with_its_own_system_is_accepted( + shared_system, +): + simulation = build_simulation(shared_system) + simulation.make_read_only() + branch = simulation.get_branch("own_system", clone_system=True) + + _update_income_tax_rate(branch.tax_benefit_system) + + income_tax = simulation.calculate("income_tax", PERIOD) + assert np.allclose(income_tax, np.array(SALARY) * BASELINE_INCOME_TAX_RATE) + + +def _give_the_system_a_shallow_copy_of_its_top_node(system): + """Replace the system's parameter tree's top node with a shallow copy, as + policyengine-us does for each traced simulation (``isolate_parameter_tracing``). + The copy shares the original's children, whose ``parent`` is still the + original top node.""" + private_top_node = copy.copy(system.parameters) + private_top_node._at_instant_cache = {} + system.parameters = private_top_node + system._parameters_at_instant_cache = {} + + +@pytest.mark.parametrize("change_parameters", PARAMETER_CHANGES) +def test_a_parameter_change_is_caught_when_the_top_node_is_a_shallow_copy( + change_parameters, +): + system = CountryTaxBenefitSystem() + _give_the_system_a_shallow_copy_of_its_top_node(system) + simulation = build_simulation(system) + simulation.calculate("income_tax", PERIOD) + simulation.make_read_only() + + change_parameters(system) + + with pytest.raises(errors.ReadOnlySimulationError): + simulation.calculate("income_tax", PERIOD) + + +def test_a_shallow_copy_of_the_top_node_made_later_is_not_a_parameter_change(): + system = CountryTaxBenefitSystem() + simulation = build_simulation(system) + expected = {output: simulation.calculate(output, PERIOD) for output in OUTPUTS} + simulation.make_read_only() + + _give_the_system_a_shallow_copy_of_its_top_node(system) + + for output in OUTPUTS: + assert np.array_equal(simulation.calculate(output, PERIOD), expected[output]) + + +def test_a_shallow_copy_of_a_top_node_without_children_is_not_a_parameter_change(): + system = CountryTaxBenefitSystem() + system.parameters = ParameterNode("", data={}) + system._parameters_at_instant_cache = {} + simulation = build_simulation(system) + simulation.make_read_only() + + _give_the_system_a_shallow_copy_of_its_top_node(system) + + assert simulation.calculate("salary", PERIOD).tolist() == SALARY + + +def _update_a_clone_of_a_node(system): + taxes_copy = system.parameters.taxes.clone() + taxes_copy.income_tax_rate.update(start=INSTANT, value=0.5) + + +def _update_a_clone_of_a_scale(system): + scale_copy = system.parameters.taxes.social_security_contribution.clone() + scale_copy.brackets[0].rate.update(start=INSTANT, value=0.5) + + +def _update_a_clone_of_a_parameter(system): + rate_copy = system.parameters.taxes.income_tax_rate.clone() + rate_copy.update(start=INSTANT, value=0.5) + + +@pytest.mark.parametrize( + "update_a_clone", + [ + pytest.param(_update_a_clone_of_a_node, id="node"), + pytest.param(_update_a_clone_of_a_scale, id="scale"), + pytest.param(_update_a_clone_of_a_parameter, id="parameter"), + ], +) +def test_updating_a_clone_of_a_subtree_is_not_a_change_to_the_tree(update_a_clone): + system = CountryTaxBenefitSystem() + simulation = build_simulation(system) + simulation.make_read_only() + + update_a_clone(system) + + assert np.allclose( + simulation.calculate("income_tax", PERIOD), + np.array(SALARY) * BASELINE_INCOME_TAX_RATE, + ) + + +def test_a_change_to_a_child_added_through_a_shallow_copied_top_node_is_caught(): + system = CountryTaxBenefitSystem() + _give_the_system_a_shallow_copy_of_its_top_node(system) + added_node = ParameterNode( + "added_node", data={"rate": {"values": {"2000-01-01": 0.1}}} + ) + system.parameters.add_child("added_node", added_node) + simulation = build_simulation(system) + simulation.make_read_only() + + system.parameters.added_node.rate.update(start=INSTANT, value=0.5) + + with pytest.raises(errors.ReadOnlySimulationError): + simulation.calculate("income_tax", PERIOD) + + +def test_making_a_simulation_read_only_again_keeps_the_first_parameter_record(): + system = CountryTaxBenefitSystem() + simulation = build_simulation(system) + simulation.make_read_only() + _update_income_tax_rate(system) + + simulation.make_read_only() + + with pytest.raises(errors.ReadOnlySimulationError): + simulation.calculate("income_tax", PERIOD) + + +# ----- Branches ----- # + + +def test_a_branch_of_a_read_only_simulation_is_not_kept_in_its_branches( + shared_system, +): + simulation = build_simulation(shared_system) + simulation.make_read_only() + + branch = simulation.get_branch("what_if") + + assert "what_if" not in simulation.branches + assert simulation.get_branch("what_if") is not branch + assert branch.read_only is False + assert branch.parent_branch is simulation + + +def test_a_branch_of_a_read_only_simulation_takes_inputs_and_calculates_from_them( + shared_system, +): + simulation = build_simulation(shared_system) + simulation.calculate("income_tax", PERIOD) + simulation.make_read_only() + values_before = stored_values(simulation) + + branch = simulation.get_branch("what_if") + branch.set_input("salary", PERIOD, OTHER_SALARY) + branch_income_tax = branch.calculate("income_tax", PERIOD) + branch_disposable_income = branch.calculate("disposable_income", PERIOD) + + assert np.allclose( + branch_income_tax, np.array(OTHER_SALARY) * BASELINE_INCOME_TAX_RATE + ) + assert branch_disposable_income.flags.writeable + assert_same_values(values_before, stored_values(simulation)) + assert np.allclose( + simulation.calculate("income_tax", PERIOD), + np.array(SALARY) * BASELINE_INCOME_TAX_RATE, + ) + + +def test_a_branch_of_a_read_only_simulation_reads_its_values(shared_system): + simulation = build_simulation(shared_system) + simulation.make_read_only() + + branch = simulation.get_branch("what_if") + + assert branch.calculate("salary", PERIOD).tolist() == SALARY + assert np.array_equal( + branch.calculate("disposable_income", PERIOD), + simulation.calculate("disposable_income", PERIOD), + ) + + +def test_a_branch_of_a_read_only_simulation_keeps_branches_of_its_own( + shared_system, +): + simulation = build_simulation(shared_system) + simulation.make_read_only() + branch = simulation.get_branch("what_if") + + nested = branch.get_branch("nested") + + assert branch.branches["nested"] is nested + + +def test_a_branch_registered_before_make_read_only_is_returned_as_it_is( + shared_system, +): + simulation = build_simulation(shared_system) + earlier_branch = simulation.get_branch("earlier") + + simulation.make_read_only() + + assert simulation.get_branch("earlier") is earlier_branch + assert simulation.branches == {"earlier": earlier_branch} + + +def test_a_read_only_reform_simulation_still_calculates_against_its_baseline(): + reform = {"taxes.income_tax_rate": {"2022-01-01": REFORM_INCOME_TAX_RATE}} + simulation = Simulation(situation=SITUATION, reform=reform) + simulation.make_read_only() + + reform_income_tax = simulation.calculate("income_tax", PERIOD) + baseline_income_tax = simulation.baseline.calculate("income_tax", PERIOD) + + assert np.allclose(reform_income_tax, np.array(SALARY) * REFORM_INCOME_TAX_RATE) + assert np.allclose(baseline_income_tax, np.array(SALARY) * BASELINE_INCOME_TAX_RATE) + assert simulation.get_branch("baseline") is simulation.baseline + + +# ----- What a read-only simulation still does ----- # + + +def test_a_read_only_simulation_calculates_new_values_and_keeps_them(shared_system): + plain_simulation = build_simulation(shared_system) + simulation = build_simulation(shared_system) + simulation.make_read_only() + + for output in OUTPUTS: + result = simulation.calculate(output, PERIOD) + assert np.array_equal(result, plain_simulation.calculate(output, PERIOD)) + assert np.array_equal(simulation.get_array(output, PERIOD), result) + + +def test_values_calculate_add_and_calculate_divide_keep_are_non_writable( + shared_system, +): + plain_simulation = build_simulation(shared_system) + simulation = build_simulation(shared_system) + simulation.make_read_only() + + results = { + "salary over the year": simulation.calculate("salary", "2022"), + "salary summed": simulation.calculate_add("salary", "2022"), + "housing_tax over a month": simulation.calculate_divide("housing_tax", PERIOD), + } + + assert np.array_equal( + results["salary over the year"], plain_simulation.calculate("salary", "2022") + ) + assert np.array_equal( + results["salary summed"], plain_simulation.calculate_add("salary", "2022") + ) + assert np.array_equal( + results["housing_tax over a month"], + plain_simulation.calculate_divide("housing_tax", PERIOD), + ) + for description, result in results.items(): + assert not result.flags.writeable, description + for key, array in stored_arrays(simulation).items(): + assert not array.flags.writeable, key + + +def test_a_read_only_microsimulation_gives_the_same_weighted_results(): + plain_microsimulation = Microsimulation() + read_only_microsimulation = Microsimulation() + read_only_microsimulation.make_read_only() + + for variable_name in ("disposable_income", "income_tax", "housing_tax"): + period = "2022" if variable_name == "housing_tax" else PERIOD + assert ( + read_only_microsimulation.calculate(variable_name, period).sum() + == plain_microsimulation.calculate(variable_name, period).sum() + ) + for key, array in stored_arrays(read_only_microsimulation).items(): + assert not array.flags.writeable, key + + +def test_a_pickled_read_only_simulation_stays_read_only(shared_system): + simulation = build_simulation(shared_system) + expected = simulation.calculate("disposable_income", PERIOD).copy() + simulation.make_read_only() + + restored = pickle.loads(pickle.dumps(simulation)) + + assert restored.read_only is True + for key, array in stored_arrays(restored).items(): + assert not array.flags.writeable, key + with pytest.raises(errors.ReadOnlySimulationError): + restored.set_input("salary", PERIOD, OTHER_SALARY) + assert np.array_equal(restored.calculate("disposable_income", PERIOD), expected) + + +class spiral_this_month(Variable): + value_type = int + entity = Person + definition_period = periods.MONTH + label = "Reads spiral_last_month for the previous month" + + def formula(person, period): + return person("spiral_last_month", period.last_month) + 1 + + +class spiral_last_month(Variable): + value_type = int + entity = Person + definition_period = periods.MONTH + label = "Reads spiral_this_month for the same month" + + def formula(person, period): + return person("spiral_this_month", period) + 1 + + +def test_a_read_only_simulation_still_drops_the_values_a_spiral_invalidates(): + system = CountryTaxBenefitSystem() + system.add_variables(spiral_this_month, spiral_last_month) + plain_simulation = build_simulation(system) + simulation = build_simulation(system) + simulation.make_read_only() + + result = simulation.calculate("spiral_this_month", PERIOD) + + assert np.array_equal( + result, plain_simulation.calculate("spiral_this_month", PERIOD) + ) + assert stored_values(simulation).keys() == stored_values(plain_simulation).keys()