Skip to content
Merged
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/uk-engine-read-year-window.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
UK build simulations now hold no year after the one they read. Given a one-year dataset, policyengine-uk (2.177.7) projects it to 2032, and every constructor runs the Universal Credit rebalancing loop over 2026-2032, working out `uc_LCWRA_element` and the arrays behind it for each year; the build reads only 2024 and 2025. Two UK helpers in `microcosm.frame.adapters.policyengine_uk` stop both: `uk_dataset_through` (policyengine-uk's own `extend_single_year_dataset` with `end_year`) and `uk_rebalancing_years_through` (a context manager that narrows `uc_reform.REBALANCING_YEARS` while one simulation is built and restores it after, on success or error). The spine adapter's `materialize` projects its dataset only to the period it reads, on its current-law parameters. The measure resolver in scratch mode, which the dense and national measure steps use, writes its scratch file as a multi-year H5 through its year and builds its main, annual-income and counterfactual simulations inside the loop cut. It projects on one current-law parameter tree per process, not one per resolver. Release scoring (a direct H5) keeps the whole projection, so policyengine-uk still checks every year of a finished file. Values do not change: a new engine test compares every requested output and every array each simulation and its baseline hold up to the year read, for 2024 data read at 2024 and at 2025 and 2025 data read at 2025, through both routes, on a synthetic frame where the health element is paid. Measured on a synthetic 80,000-household simulation of 2024 data read at 2025 (medians of three runs), construction falls from 12.1 to 2.1 seconds and peak memory from 4,981 to 3,152 MiB. Tests pin the source digests of `add_universal_credit_reform` and `_add_inactive_health_element_formula`, and that `REBALANCING_YEARS` is still a range. policyengine-uk now labels a projected year's CGT inputs "supplied" rather than "projected"; nothing in Microcosm reads that label. `uk_dataset_through` runs the one-year dataset's own `validate()` before it projects, because policyengine-uk runs that check only on a year it projects and a stage that reads its data's own year now projects nothing; a NaN in any column still raises policyengine-uk's own error. The check is a little stricter than the projection was: policyengine-uk drops `unused_pension_annual_allowance` from projected years and turns a NaN `student_loan_plan` into the string "nan" there, so a NaN in either now raises too. Microcosm writes the first never and the second with a plan or "NONE" on every row. `uk_dataset_through` refuses an end year before the data's year, so a scratch resolver whose year is before its frame's year now raises `ValueError`; no build does that. Two guards go with the cut. A resolver in scratch mode refuses a measure dated after its year (`cgt_<year>_*`, `company_car_benefit_<year>`): policyengine-uk would answer it from the last year's inputs, with no error and with other values than a release gives. The loop cut holds a lock while its block is open, so a cut on another thread waits and cannot leave the range cut for the rest of the process; a block for another year inside an open block is refused, and so is a range that something else changed inside the block. Release scoring builds its simulations inside `uk_whole_rebalancing_years`, which waits for an open cut and refuses a `REBALANCING_YEARS` that is not the range the engine builds from its own first and last years. `frs_legacy_proxies` is the first UK stage whose implementation hash covers the adapter, and a node key includes its parents' keys, so that stage and every node after it, the dense and national steps included, re-key once; the six FRS stages before it keep their keys.
1 change: 1 addition & 0 deletions changelog.d/us-engine-read-year-window.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
The PolicyEngine-US adapter's `materialize` now hands `Microsimulation` a dataset that holds the read year alone. Given a single-year dataset, policyengine-us 2.2.1 adds an uprated copy of every later year up to its last CPI-U year (2035), stores all twelve years' inputs, and copies all of them again into each branch it opens (federal itemization and some state taxes). `materialize` reads only the dataset's own year, so the adapter now stops the extension there (`extend_single_year_dataset(..., end_year=period)`). Values do not change: no policyengine-us formula reads a later year's data, and a test compares six variables, `household_net_income` among them, with the engine's default window. On the public populace-us 2024 file (57,240 households), process memory after the engine is built falls from 3.66 to 1.78 GiB; on 15,000 of its households, peak memory while computing `income_tax` falls from 10.47 to 8.74 GiB. Calculation time does not change. The adapter's source feeds the implementation hashes of the US post-transfer seed and materialize kernels, and a node key includes its parents' keys, so the seed and every node after it re-key once. The US release builder's in-build simulations, which read only 2024, now stop there too: its six in-build sites (the target frame, reform targets, ACA source inputs, Medicaid and SNAP eligibility, and the December SSI amounts) ask `_dataset_from_frame(..., period_only=True)` for the year alone (`us_dataset_through`). By default `_dataset_from_frame` keeps the engine's projection, as post-export scoring needs (its plans read years after 2025), so a new caller that reads a later year gets the engine's own projected inputs rather than inputs the engine carries forward or a formula-owned column read as zero. Tests pin the policyengine-us formulas that offset a period forward or look up a holder, each reviewed, and the policyengine-core rule that fills a period missing from a dataset, so an engine bump that adds or changes either fails until it is reviewed; the adapter test also compares every array both windows hold through 2024, in every branch.
8 changes: 8 additions & 0 deletions docs/us-release-build-rule.md
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,14 @@ one Microsimulation over the whole file.
2025 state taxes after 2027 keys. It checks for the
`md.msde.ccs.payment.informal.rates` error and warns if that error is absent;
it does not require the upstream bug to persist.
- Each batch engine keeps policyengine-us's projection of the release year to
its last CPI-U year (2035), because the plans request keys in later years
(reform validation reaches past 2025). The build's own simulations hold
`PERIOD` alone instead: the six in-build sites (target frame, JCT reforms,
ACA source inputs, Medicaid, SNAP and December SSI) ask
`_dataset_from_frame(..., period_only=True)`. By default it keeps the
projection, so a new caller that reads a later year gets the engine's own
projected inputs.
- Each reform builds one tax-benefit system and scores its measure batch by
batch. Each batch engine gets that system alone, without `reform=`: given
both, policyengine-us creates a baseline branch, which clones the system.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from __future__ import annotations

import functools
import json
import warnings
from collections.abc import Mapping
Expand Down Expand Up @@ -87,6 +88,9 @@
from microcosm.frame import Frame, MassChangeRecord, Weights
from microcosm.frame.adapters.policyengine_uk import (
frame_isa_income_contract,
uk_dataset_through,
uk_rebalancing_years_through,
uk_whole_rebalancing_years,
validate_uc_claimant_input,
)

Expand Down Expand Up @@ -479,6 +483,15 @@ def _cgt_model_measure(variable: str, default_year: int) -> tuple[str, int] | No
return None


def _dated_measure_year(variable: str) -> int | None:
"""The year a measure dated by its name is computed at, else None."""

match = UK_CGT_DATED_MEASURE.fullmatch(variable)
if match:
return int(match[1])
return company_car_dated_benefit_year(variable)


def _uc_calibration_composition(
frame: Any, simulation: Any, year: int
) -> tuple[np.ndarray, np.ndarray]:
Expand Down Expand Up @@ -1072,7 +1085,10 @@ def __init__(
identifier_universe=engine_identifier_universe,
)
write_uk_national_frame(engine_frame, source_path)
_project_scratch_engine_input(source_path, self.year)
mode = "scratch_frame_export"
# The scratch engine holds no year after the resolver's.
simulation_end_year: int | None = self.year
else:
if self._engine_weight_scale is not None:
raise ValueError(
Expand All @@ -1087,12 +1103,16 @@ def __init__(
dropped = ()
source_path = Path(simulation_source)
mode = "direct_h5"
# A release is scored as users load it: policyengine-uk's whole
# projection and its checks on every year.
simulation_end_year = None
if frame is None:
frame, _provenance = load_uk_national_frame(source_path)
self.frame = frame
self._engine_scratch_dropped_columns = tuple(dropped)
self._factory = factory
self._source_path = source_path
self._simulation_end_year = simulation_end_year
self._counterfactuals: dict[tuple[str, str | None], Any] = {}
self._counterfactual_measures: dict[str, dict[str, Any]] = {}
# The domestic energy measures, computed together on first read.
Expand Down Expand Up @@ -1137,7 +1157,7 @@ def __init__(
"DfE spring-term measures must not be persisted as source inputs: "
f"{persisted_spring_term}"
)
self.simulation = factory(dataset=str(source_path))
self.simulation = self._new_simulation()
validate_uc_claimant_input(self.simulation, frame.table("person"), self.year)
self.contract_targets = _uk_contract_targets()
bound_cgt_periods = {}
Expand Down Expand Up @@ -1340,7 +1360,34 @@ def entity_for(self, variable: str) -> str | None:
return None
return str(definition.entity.key)

def _refuse_dated_measure_after_window(self, variable: str) -> None:
"""Refuse a measure dated after the last year a scratch engine holds.

A scratch engine stops at the resolver's year: its dataset is projected
no further, and policyengine-uk's Universal Credit rebalancing loop
did not run for a later year. policyengine-uk still answers a read
there, from the last year's inputs, with other values than a release
gives. A direct H5 keeps the whole projection and answers every year.
:meth:`knows` still answers for the measure, so the refusal reaches
the operator with its reason, not as an unknown variable.
"""

end_year = getattr(self, "_simulation_end_year", None)
if end_year is None:
return
measure_year = _dated_measure_year(variable)
if measure_year is not None and measure_year > end_year:
raise ValueError(
f"{variable} is measured in {measure_year}, but this resolver's "
f"scratch engine holds no year after {end_year}: the engine's "
"projection and its Universal Credit rebalancing loop stop "
"there, so the values would not be the ones a release gives. "
"Measure it from a direct H5 source, or with a resolver whose "
f"year is {measure_year} or later."
)

def compute(self, entity: str, variable: str) -> tuple[np.ndarray, str]:
self._refuse_dated_measure_after_window(variable)
if variable in UK_ANNUAL_INCOME_MEASURES:
return self._annual_income_measure(entity, variable)
if variable in UK_HOUSEHOLD_ENERGY_MEASURES:
Expand Down Expand Up @@ -1389,6 +1436,7 @@ def counterfactual_delta(
folded = binding.get("folded_into")
folded = None if folded is None else str(folded)
output = str(binding["output_variable"])
self._refuse_dated_measure_after_window(output)
entity = str(binding.get("from_entity") or "person")
direction = str(binding.get("output_delta", "counterfactual_minus_baseline"))
if direction not in (
Expand Down Expand Up @@ -1630,6 +1678,25 @@ def _dataset_year(self) -> int:
return int(period)
return self.year

def _new_simulation(self) -> Any:
"""A new engine simulation of the resolver's source.

In scratch mode the source holds the frame's year through the
resolver's year (:func:`_project_scratch_engine_input`), and
policyengine-uk's Universal Credit rebalancing loop stops at the
resolver's year while the simulation is built: the measures read no
later year, and :meth:`_refuse_dated_measure_after_window` refuses one
that would. A direct H5 keeps the engine's whole projection, and is
built where no cut of that loop is in force
(:func:`~microcosm.frame.adapters.policyengine_uk.uk_whole_rebalancing_years`).
"""

if self._simulation_end_year is None:
with uk_whole_rebalancing_years():
return self._factory(dataset=str(self._source_path))
with uk_rebalancing_years_through(self._simulation_end_year):
return self._factory(dataset=str(self._source_path))

def _annual_income_simulation(self) -> Any:
"""The simulation of each person's year, built once from the same source.

Expand All @@ -1649,7 +1716,7 @@ def _annual_income_simulation(self) -> Any:
if self._annual_income_simulation_cache is not None:
return self._annual_income_simulation_cache
person = self.frame.table("person")
simulation = self._factory(dataset=str(self._source_path))
simulation = self._new_simulation()
annual_inputs: dict[str, np.ndarray] = {}
for name, share_column, other_column in _ANNUAL_INCOME_INPUTS:
current = _values(self.simulation.calculate(name, self.year)).astype(float)
Expand Down Expand Up @@ -1734,7 +1801,7 @@ def _counterfactual_simulation(self, zeroed: str, folded: str | None) -> Any:
key = (zeroed, folded)
if key in self._counterfactuals:
return self._counterfactuals[key]
simulation = self._factory(dataset=str(self._source_path))
simulation = self._new_simulation()
amount = np.asarray(self.simulation.calculate(zeroed, self.year), dtype=float)
if not np.isfinite(amount).all():
raise ValueError(f"{zeroed} must be finite to substitute it.")
Expand Down Expand Up @@ -2056,6 +2123,42 @@ def _policyengine_uk_module() -> Any:
return policyengine_uk


@functools.lru_cache(maxsize=1)
def _current_law_parameters() -> Any:
"""policyengine-uk's current-law parameter tree, built once per process.

The scratch projection only reads it. A ``CountryTaxBenefitSystem`` built
for each resolver cost time, and memory the process never got back, so
one tree serves every resolver.
"""

return _policyengine_uk_module().CountryTaxBenefitSystem().parameters


def _project_scratch_engine_input(path: Path, end_year: int) -> None:
"""Rewrite the one-year scratch H5 at ``path`` through ``end_year``.

policyengine-uk projects a one-year file to its ``PROJECTION_END_YEAR``
(2032) when it loads it. The measure step reads only the frame's year and
the resolver's, so the scratch file becomes a multi-year H5 of those years
alone, projected by policyengine-uk's own uprating on current-law
parameters (:func:`~microcosm.frame.adapters.policyengine_uk.uk_dataset_through`).
policyengine-uk loads a multi-year file as given.
"""

from policyengine_uk.data import UKSingleYearDataset

one_year = UKSingleYearDataset(file_path=str(path))
projected = uk_dataset_through(one_year, end_year, _current_law_parameters())
with warnings.catch_warnings():
# PyTables warns once per table that a year ("2025") is no Python
# identifier; policyengine-uk's multi-year layout names tables so.
warnings.filterwarnings(
"ignore", message="object name is not a valid Python identifier"
)
projected.save(str(path))


def _uk_contract_targets() -> dict[str, Any]:
payload = (
importlib_resources.files("microcosm.build.uk")
Expand Down
Loading
Loading