Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/reform-modify-parameters-copy.breaking.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`Reform.modify_parameters` returns the reform on success and refreshes cached parameter reads after the call.
11 changes: 11 additions & 0 deletions docs/python_api/reforms.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,18 @@ The `policyengine_core.reforms` module contains the definition for `Reform`, a c

## Reform

An instance reform copies parameter values and metadata from its baseline.
A replacement tree returned by a modifier must have its own nodes, as a clone
does. The reform copies the replacement's values and metadata before installing
it, so later modifiers can edit them in place.

When `modify_parameters` exits, it refreshes future dated reads through the
system, the tree passed to the modifier, and the currently installed tree.
This also applies when the modifier raises or returns an invalid value.

```{eval-rst}
.. autoclass:: policyengine_core.reforms.Reform
:members:

.. automethod:: modify_parameters
```
29 changes: 28 additions & 1 deletion policyengine_core/parameters/parameter_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -351,7 +351,11 @@ def clone(self) -> "ParameterNode":
clone.metadata = copy.copy(self.metadata)
clone.children = {key: child.clone() for key, child in self.children.items()}
for child_key, child in clone.children.items():
if _can_expose_child_as_attribute(clone, child_key):
# Older pickles can expose a child whose name is now reserved.
if (
_can_expose_child_as_attribute(clone, child_key)
or self.__dict__.get(child_key) is self.children[child_key]
):
setattr(clone, child_key, child)
child.parent = clone
clone._at_instant_cache = _AtInstantCache()
Expand Down Expand Up @@ -389,6 +393,29 @@ def clear_parent_cache(self):
if self.parent is not None:
self.parent.clear_parent_cache()

def _iter_subtree(self):
"""Yield this node and all parameters, scales and brackets below it."""
pending = [self]
while pending:
item = pending.pop()
yield item
if isinstance(item, ParameterNode):
pending.extend(item.children.values())
elif isinstance(item, parameters.ParameterScale):
pending.extend(item.brackets)

def clear_descendant_caches(self) -> None:
"""Drop the nodes at instant cached by this node and every node below it.

``Parameter.update`` clears the nodes above it, as far as ``parent``
links reach. This reaches the nodes an edit made some other way leaves
behind: a change to ``values_list``, a scale's ``brackets`` or
``children``.
"""
for item in ParameterNode._iter_subtree(self):
if isinstance(item, ParameterNode):
item._at_instant_cache.clear()

def mark_as_modified(self):
self.modified = True
if self.parent is not None:
Expand Down
81 changes: 52 additions & 29 deletions policyengine_core/reforms/reform.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from __future__ import annotations

import copy
from typing import Callable, Union, TYPE_CHECKING
from types import MappingProxyType
from typing import Union, TYPE_CHECKING

from policyengine_core.parameters import ParameterNode, Parameter
from policyengine_core.taxbenefitsystems import TaxBenefitSystem
Expand Down Expand Up @@ -77,6 +78,50 @@ def _update_start_instant(update_kwargs: dict):
return instant_("0001-01-01")


def _copy_payload(value, memo):
"""Copy a payload, preserving read-only mapping views over copied data."""
key = id(value)
if key in memo:
return memo[key]

value_type = type(value)
if value_type in (dict, MappingProxyType):
items = {}
copied = MappingProxyType(items) if value_type is MappingProxyType else items
memo[key] = copied
for name, item in value.items():
items[copy.deepcopy(name, memo)] = _copy_payload(item, memo)
elif value_type is list:
copied = []
memo[key] = copied
copied.extend(_copy_payload(item, memo) for item in value)
elif value_type is tuple:
copied = tuple(_copy_payload(item, memo) for item in value)
# A mutable item may have led back to this tuple during the copy.
if key in memo:
return memo[key]
memo[key] = copied
else:
return copy.deepcopy(value, memo)

# As with deepcopy, keep the source alive while its id is in the memo.
memo.setdefault(id(memo), []).append(value)
return copied


def _copy_parameter_payloads(root: ParameterNode) -> None:
"""Detach the mutable payloads shared by a parameter clone and its baseline."""
memo = {}
for item in ParameterNode._iter_subtree(root):
if item.metadata:
item.metadata = _copy_payload(item.metadata, memo)
if isinstance(item, Parameter):
for entry in item.values_list:
if entry.metadata:
entry.metadata = _copy_payload(entry.metadata, memo)
entry.value = _copy_payload(entry.value, memo)


class Reform(TaxBenefitSystem):
"""A modified TaxBenefitSystem

Expand Down Expand Up @@ -123,13 +168,10 @@ def __init__(self, baseline: TaxBenefitSystem):
"""
super().__init__(baseline.entities)
self.baseline = baseline
# Clone the parameter tree so in-place mutations inside ``apply()``
# (``set_parameter(...)`` or ``self.parameters.path.update(...)``)
# don't leak into the baseline. ``modify_parameters()`` was already
# deep-copying, but plenty of reforms mutate ``self.parameters``
# directly (bug C4).
# Give apply() its own tree and mutable parameter data.
if baseline.parameters is not None:
self.parameters = baseline.parameters.clone()
_copy_parameter_payloads(self.parameters)
else:
self.parameters = None
# Use a fresh at-instant cache so reform mutations aren't shadowed
Expand All @@ -147,6 +189,10 @@ def __init__(self, baseline: TaxBenefitSystem):
def __getattr__(self, attribute):
return getattr(self.baseline, attribute)

def _prepare_parameter_replacement(self, root: ParameterNode) -> ParameterNode:
_copy_parameter_payloads(root)
return root

def preprocess_situation(self, situation: dict, default_period=None) -> dict:
# TaxBenefitSystem defines a no-op hook, so ``__getattr__`` never
# reaches the country's override. Run the country system's hook with
Expand Down Expand Up @@ -174,29 +220,6 @@ def full_key(self) -> str:
key = ".".join([baseline_full_key, key])
return key

def modify_parameters(
self, modifier_function: Callable[[ParameterNode], ParameterNode]
) -> None:
"""Make modifications on the parameters of the legislation.

Call this function in `apply()` if the reform asks for legislation parameter modifications.

Args:
modifier_function: A function that takes a :obj:`.ParameterNode` and should return an object of the same type.
"""
baseline_parameters = self.baseline.parameters
baseline_parameters_copy = copy.deepcopy(baseline_parameters)
reform_parameters = modifier_function(baseline_parameters_copy)
if not isinstance(reform_parameters, ParameterNode):
return ValueError(
"modifier_function {} in module {} must return a ParameterNode".format(
modifier_function.__name__,
modifier_function.__module__,
)
)
self.parameters = reform_parameters
self._parameters_at_instant_cache = {}

@staticmethod
def from_dict(
parameter_values: dict,
Expand Down
81 changes: 58 additions & 23 deletions policyengine_core/taxbenefitsystems/tax_benefit_system.py
Original file line number Diff line number Diff line change
Expand Up @@ -816,35 +816,70 @@ def test(self, paths: str, verbose: bool = False) -> None:

run_tests(self, paths, options=dict(verbose=verbose))

def _prepare_parameter_replacement(self, root: ParameterNode) -> ParameterNode:
return root

def modify_parameters(
self, modifier_function: Callable[[ParameterNode], ParameterNode]
) -> None:
"""Make modifications on the parameters of the legislation.
self,
modifier_function: Callable[[ParameterNode], ParameterNode]
| dict[str, dict[str | int | Instant | Period, Any]],
) -> TaxBenefitSystem | ValueError:
"""Modify this system's legislation parameters, including from a reform's ``apply()``.

Call this function in `apply()` if the reform asks for legislation parameter modifications.
A callback receives this system's current tree and may edit it in place
or return a replacement with its own nodes. An instance reform copies
parameter values and metadata when it clones the baseline or accepts
a replacement.

This method clears cached reads for the system, the tree passed to the
callback, and the tree installed when the call exits, including when
it raises. During a callback, reads can still return cached values
after a direct edit. Edits made before an error remain in the tree.

Args:
modifier_function: A function that takes a :obj:`.ParameterNode` and should return an object of the same type.
"""
if isinstance(modifier_function, dict):
for parameter in modifier_function:
for time_period in modifier_function[parameter]:
param: Parameter = self.parameters.get_child(parameter)
param.update(
value=modifier_function[parameter][time_period],
period=periods.period(time_period),
modifier_function: A callable taking and returning a
:class:`.ParameterNode`, or a dict mapping parameter paths
(such as ``tax[1].rate``) to dicts of periods and values.

Returns:
This system on success, or a ``ValueError`` object if a callable
returns something other than a parameter tree.
"""
parameters = self.parameters
try:
if isinstance(modifier_function, dict):
for parameter in modifier_function:
for time_period in modifier_function[parameter]:
param: Parameter = self.parameters.get_child(parameter)
param.update(
value=modifier_function[parameter][time_period],
period=periods.period(time_period),
)
else:
reform_parameters = modifier_function(parameters)
if not isinstance(reform_parameters, ParameterNode):
modifier_type = type(modifier_function)
name = getattr(
modifier_function, "__name__", modifier_type.__name__
)
else:
reform_parameters = modifier_function(self.parameters)
if not isinstance(reform_parameters, ParameterNode):
return ValueError(
"modifier_function {} in module {} must return a ParameterNode".format(
modifier_function.__name__,
modifier_function.__module__,
module = getattr(
modifier_function, "__module__", modifier_type.__module__
)
)
self.parameters = reform_parameters
self._parameters_at_instant_cache = {}
return ValueError(
f"modifier_function {name} in module {module} must return a ParameterNode"
)
if reform_parameters is not parameters:
reform_parameters = self._prepare_parameter_replacement(
reform_parameters
)
self.parameters = reform_parameters
finally:
self._parameters_at_instant_cache = {}
if parameters is not None:
ParameterNode.clear_descendant_caches(parameters)
current = self.parameters
if isinstance(current, ParameterNode) and current is not parameters:
ParameterNode.clear_descendant_caches(current)
return self

def add_modelled_policy_metadata(self):
Expand Down
9 changes: 5 additions & 4 deletions tests/core/parameters/test_vectorial_parameter_node_copy.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
``recarray``.

``ParameterNodeAtInstant`` caches its vectorial node, and
``Reform.modify_parameters`` deep-copies the baseline's parameter tree, so a
``Reform.modify_parameters`` deep-copied the baseline's parameter tree, so a
reform found a ``recarray`` where its cached node should be.
"""

Expand Down Expand Up @@ -200,7 +200,7 @@ def test_copied_parameter_tree_keeps_its_cached_vectorial_node(copier):
assert_near(rate[families][housings].z2, expected)


def test_reform_that_modifies_parameters_keeps_the_cached_vectorial_node(
def test_reform_that_modifies_parameters_reads_the_vectorial_node(
isolated_tax_benefit_system,
):
system = isolated_tax_benefit_system
Expand All @@ -210,10 +210,11 @@ def test_reform_that_modifies_parameters_keeps_the_cached_vectorial_node(

class KeepParameters(Reform):
def apply(self):
# Deep-copies the baseline's tree, cache included.
# Gets the reform's own copy of the tree, not the baseline's, which
# has cached that node.
self.modify_parameters(lambda parameters: parameters)

general = KeepParameters(system).get_parameters_at_instant("2017-01-01").general

assert type(general._vectorial_node) is VectorialParameterNodeAtInstant
assert_near(general[names], expected)
assert type(general._vectorial_node) is VectorialParameterNodeAtInstant
Loading