diff --git a/.github/test_outcome_allowlist.toml b/.github/test_outcome_allowlist.toml index e3b947e134..9975be0ea4 100644 --- a/.github/test_outcome_allowlist.toml +++ b/.github/test_outcome_allowlist.toml @@ -19,6 +19,18 @@ # Keep entries narrow. An entry that matches nothing in a run is reported as a # warning; remove it once its bug is fixed. Failures can never be accepted. +[[allow]] +nodeid = "policyengine_uk/tests/test_subsample.py::test_neutralized_inputs_and_model_values_survive_subsampling[[]*]" +outcome = "xfailed" +reason = "^needs policyengine-core holder resync$" +why = "Issue #2254 / PR #2265 waits for core to resync restored holders after subsampling. Both ownership variants retain every assertion under strict xfail." + +[[allow]] +nodeid = "policyengine_uk/tests/test_input_records.py::test_restoring_reform_can_replace_a_neutralized_input[[]subsampled-*]" +outcome = "xfailed" +reason = "^needs policyengine-core holder resync$" +why = "Issue #2254 / PR #2265 waits for core to accept writes immediately after restoring a subsampled holder. Direct supplied/model controls remain unmarked." + [[allow]] nodeid = "policyengine_uk/tests/test_uc_state_pension_properties.py::test_state_pension_does_not_change_partners_marriage_allowance" outcome = "xfailed" diff --git a/changelog.d/2254.fixed.md b/changelog.d/2254.fixed.md new file mode 100644 index 0000000000..eab64a3be3 --- /dev/null +++ b/changelog.d/2254.fixed.md @@ -0,0 +1 @@ +`Simulation.subsample()` no longer raises `TypeError` about a missing `dataset` argument: it keeps a weighted sample of households with every supplied weight total unchanged, and replaces the baseline and `dataset` with copies holding the same households. It keeps the stored inputs and model values of neutralised variables for the sampled records. diff --git a/changelog.d/2307.fixed.md b/changelog.d/2307.fixed.md new file mode 100644 index 0000000000..b05817f4f9 --- /dev/null +++ b/changelog.d/2307.fixed.md @@ -0,0 +1 @@ +`supplied_input` and `supplied_input_periods` no longer count a value cached over a supplied input as supplied, and read an input stored on disk from disk when a value is cached over it in memory (#2307). diff --git a/docs/book/usage/simulations.md b/docs/book/usage/simulations.md index d60c196479..ac11a0337a 100644 --- a/docs/book/usage/simulations.md +++ b/docs/book/usage/simulations.md @@ -545,6 +545,21 @@ weighted_total = (unweighted_values * modified_weights).sum() print(f"Total with 10% higher weights: £{weighted_total / 1e9:.1f}bn") ``` +### Subsampling a microsimulation + +`subsample` cuts a simulation built from a dataset down to a weighted random sample of its households: + +```python +sim = Microsimulation( + dataset="hf://policyengine/policyengine-uk-data/enhanced_frs_2022_23.h5" +) +sim.subsample(n=10_000, seed=0, time_period=2026) +``` + +It draws `n` households with replacement, each with probability proportional to its weight in `time_period` (with the default `quantize_weights=True`), and keeps every household drawn at least once, with its benefit units and people. So the sample holds at most `n` households. A household's new weight is proportional to the number of times it was drawn, and the total household weight of every year is unchanged. The values the simulation was given are kept for the sampled records; results are calculated again on the sample, so population estimates then carry sampling error. + +The simulation's `baseline` and `dataset` are replaced with copies cut down to the same households; the objects they held before are left as they were. The `dataset` holds the rows of the dataset the simulation was built from, so it holds whole years only and does not include values set with `set_input` after the simulation was built. The same `seed` always draws the same households. + ## Debugging simulations When simulations don't behave as expected: diff --git a/policyengine_uk/simulation.py b/policyengine_uk/simulation.py index e000f0f9a3..f32010b536 100644 --- a/policyengine_uk/simulation.py +++ b/policyengine_uk/simulation.py @@ -89,6 +89,7 @@ drop_calculated_years, retained_input_variables, ) +from policyengine_uk.utils.subsample import subsample_simulation from policyengine_uk.utils.supplied_inputs import ( SUPPLIED_INPUT_VARIABLES, copy_model_values, @@ -1652,6 +1653,75 @@ def build_from_ids( self.build_from_populations(builder.populations) + def subsample( + self, + n: Optional[int] = None, + frac: Optional[float] = None, + seed=None, + time_period=None, + quantize_weights: bool = True, + ) -> "Simulation": + """Cut the simulation down to a weighted random sample of households. + + Draws ``n`` households with replacement and keeps each household + drawn at least once, with its benefit units and people. So the sample + holds at most ``n`` households. Only households with a positive + weight in ``time_period`` can be drawn: with ``quantize_weights`` + (the default), each with probability proportional to that weight; + without it, each with equal probability. A period before the first + one the simulation was given household weights for has none, so the + first given weights are used instead. + + Every value the simulation was given (from its dataset or through + ``set_input``) is kept for the sampled records, for every period, and + so is every value the model stored as its own (``set_model_value``), + which stays the model's. So does the record of where each capital + gains input came from, and what the dataset declared about how its + amounts grow (its ISA income contracts and savings income series). Calculated values are dropped and recalculated + on the sample, and the tracer starts again. + + Each supplied weight is replaced so that its total is unchanged in + every period: a household's new weight is proportional to the number + of times it was drawn, and also to its old weight without + ``quantize_weights``. A zero weight stays zero. With + ``quantize_weights``, a household's new weight in ``time_period``, + averaged over draws, is its old one; in another period that holds + only if the household's share of the total weight is the same there. + + ``baseline`` is replaced with a copy subsampled to the same + households, which keeps its own policy and inputs. The baseline the + simulation held before is left as it was, since another simulation + (a clone of this one) can hold it too. ``dataset`` is replaced with + the rows of the dataset the simulation was built from for the + sampled records, with its weights rescaled in the same way. Like the + dataset before, it holds whole years only, and not values set with + ``set_input`` after the simulation was built. + + Args: + n: The number of households to draw. + frac: The number to draw as a share of all households, used when + ``n`` is not given. + seed: A number or text that fixes the draw. The same seed always + draws the same households; without one, a fixed seed is used. + time_period: Draw households by their weight in this period. + Defaults to the default calculation period. + quantize_weights: If false, draw households with a positive + weight with equal probability, and make a household's new + weight proportional to its old weight times the number of + times it was drawn. + + Returns: + This simulation, subsampled. + """ + return subsample_simulation( + self, + n=n, + frac=frac, + seed=seed, + time_period=time_period, + quantize_weights=quantize_weights, + ) + def move_values(self, variable_donor: str, variable_target: str) -> None: """Move values from one variable to another across all branches. diff --git a/policyengine_uk/tests/test_input_records.py b/policyengine_uk/tests/test_input_records.py index a29f1d61fb..24b795e4fd 100644 --- a/policyengine_uk/tests/test_input_records.py +++ b/policyengine_uk/tests/test_input_records.py @@ -12,12 +12,20 @@ """ import numpy as np +import pandas as pd import pytest from policyengine_core.experimental.memory_config import MemoryConfig from policyengine_core.periods import period +from policyengine_core.reforms import Reform -from policyengine_uk import Simulation -from policyengine_uk.utils.supplied_inputs import set_model_value, supplied_input +from policyengine_uk import Microsimulation, Simulation +from policyengine_uk.data import UKSingleYearDataset +from policyengine_uk.utils.supplied_inputs import ( + is_model_value, + set_model_value, + stored_supplied_value, + supplied_input, +) pytestmark = pytest.mark.usefixtures("cloned_uk_tax_benefit_system") @@ -176,3 +184,99 @@ def test_rebuilt_populations_forget_the_inputs_they_replace(): holder.put_in_cache(np.array([123.0]), period(2026)) person = sim.populations["person"] assert supplied_input(person, "adjusted_net_income", period(2026)) is None + + +@pytest.mark.parametrize("model", [False, True], ids=["supplied", "model"]) +@pytest.mark.parametrize( + "subsampled", + [ + pytest.param(False, id="direct"), + pytest.param( + True, + id="subsampled", + marks=pytest.mark.xfail( + strict=True, + raises=AssertionError, + reason="needs policyengine-core holder resync", + ), + ), + ], +) +def test_restoring_reform_can_replace_a_neutralized_input(model, subsampled): + """A write after restoration replaces the hidden value and its ownership.""" + if subsampled: + dataset = UKSingleYearDataset( + person=pd.DataFrame( + { + "person_id": [1], + "person_benunit_id": [1], + "person_household_id": [1], + "age": [40], + "employment_income": [30_000.0], + } + ), + benunit=pd.DataFrame({"benunit_id": [1]}), + household=pd.DataFrame( + { + "household_id": [1], + "household_weight": [1.0], + "region": ["LONDON"], + "tenure_type": ["OWNED_OUTRIGHT"], + "rent": [0.0], + "council_tax": [0.0], + } + ), + fiscal_year=2025, + ) + simulation = Microsimulation(dataset=dataset) + else: + simulation = Simulation(situation={"age": 40, "employment_income": 30_000}) + name = "adjusted_net_income" + input_period = period(2025) + original_variable = simulation.tax_benefit_system.get_variable(name).__class__ + if model: + set_model_value(simulation, name, input_period, [10_000]) + else: + simulation.set_input(name, input_period, [10_000]) + + class NeutralizeIncome(Reform): + def apply(self): + self.neutralize_variable(name) + + class RestoreAndReplaceIncome(Reform): + def apply(self): + self.replace_variable(original_variable) + assert not self.get_variable(name).is_neutralized + assert self.get_variable(name).__class__ is original_variable + self.simulation.set_input(name, input_period, [20_000]) + stored = stored_supplied_value( + self.simulation.get_holder(name), + input_period, + self.simulation.branch_name, + ) + np.testing.assert_array_equal(stored, [20_000]) + np.testing.assert_array_equal( + self.simulation.calculate(name, input_period), [20_000] + ) + assert not is_model_value(self.simulation, name, input_period, stored) + np.testing.assert_array_equal( + supplied_input( + self.simulation.populations["person"], name, input_period + ), + [20_000], + ) + + simulation.apply_reform(NeutralizeIncome) + if subsampled: + simulation.subsample(n=1, seed=0, time_period=2025) + simulation.apply_reform(RestoreAndReplaceIncome) + + stored = stored_supplied_value( + simulation.get_holder(name), input_period, simulation.branch_name + ) + np.testing.assert_array_equal(stored, [20_000]) + np.testing.assert_array_equal(simulation.calculate(name, input_period), [20_000]) + assert not is_model_value(simulation, name, input_period, stored) + np.testing.assert_array_equal( + supplied_input(simulation.populations["person"], name, input_period), [20_000] + ) diff --git a/policyengine_uk/tests/test_subsample.py b/policyengine_uk/tests/test_subsample.py new file mode 100644 index 0000000000..2417c08aed --- /dev/null +++ b/policyengine_uk/tests/test_subsample.py @@ -0,0 +1,1443 @@ +"""``Simulation.subsample`` keeps a weighted sample of a dataset's households. + +Before, the method was inherited from policyengine-core and raised +``TypeError``: it rebuilds through ``build_from_dataset()`` with no arguments, +and the UK builder needs the dataset. The UK method subsamples the +simulation's populations, its baseline and its dataset together. + +Invariants, for every dataset, sample size ``n``, seed, sampling period and +``quantize_weights``: + +1. Size: between 1 and ``n`` households are kept, each with a positive weight + in the sampling period. +2. Weight totals: the total household weight of every year is unchanged, to + float32 precision, and so is the total of every other supplied weight over + its own entity. +3. Quantized weights: with ``quantize_weights`` (the default), a household's + weight is its number of draws times the year's total over the draws of + households with a positive weight that year: a whole multiple of + total / ``n`` in the sampling year, and in any year where every drawn + household has a positive weight, with the multiples summing to ``n``. + Without it, a household's weight is proportional to its old weight times a + whole number of draws. Either way a zero weight stays zero, in every year. +4. Links: a kept household or benefit unit has exactly the people it had, a + kept person keeps their household and benefit unit, and no other record is + kept. This holds for identifiers that 32-bit floats cannot tell apart, and + whatever the stored ``person_household_id`` and ``person_benunit_id`` + inputs hold. +5. Inputs: every supplied value other than a weight is unchanged for the kept + records, in every period, and the subsample supplies the same variables + and periods as before. Calculated values are not kept. +6. Determinism: the same seed keeps the same households with the same weights. +7. Baseline: the baseline is replaced with a copy that holds the same + households and weights and keeps its own policy. The baseline held before + is unchanged, so subsampling a clone leaves the source simulation and its + baseline as they were. +8. Dataset (differential): ``dataset`` holds the same records as the + populations, from the rows of the dataset the simulation was built from, + with weights rescaled in the same way. For a simulation whose inputs are + all in its dataset, a simulation built from that dataset gives the same + results as the subsampled simulation. Intended: an input the dataset does + not hold stays out of it, as it was out of the dataset before + subsampling. That is an input set with ``set_input`` after the build, or + one for a part of a year, which a DataFrame can give and a dataset of + whole years cannot hold. +9. Unbiasedness: over many seeds, a household's mean quantized weight in the + sampling period is its old weight. Intended exceptions: in another period, + the mean is the household's share of the sampling period's total times + that period's total, which is its old weight only if its share is the same + in both periods; and unquantized weights keep the total exactly, so they + are a ratio estimate, whose mean is off by a few per cent in a small + sample and closes on the old weight as the sample grows. +10. Trace and inputs: the tracer starts again, and a supplied input stored on + disk is kept, not a value calculated later and cached over it in memory. +11. Model values and origins: a value the model stored as its own + (``set_model_value``, as the Universal Credit health element reform does + for every simulation) stays the model's, not supplied, and the record of + where each capital gains input came from is unchanged. + +The properties are generated for datasets of one year, which the model +projects, and of several years whose weights change differently from +household to household. + +Intended exceptions: a simulation built from a situation, one given no +household weights or a negative one, a branch, and a baseline holding other +households raise ``ValueError`` and are left unchanged. +""" + +from types import SimpleNamespace + +import numpy as np +import pandas as pd +import pytest +from hypothesis import HealthCheck, example, given, settings +from hypothesis import strategies as st +from policyengine_core.data_storage import OnDiskStorage +from policyengine_core.periods import period as period_ +from policyengine_core.reforms import Reform +from policyengine_core.tracers import FullTracer + +from policyengine_uk import CountryTaxBenefitSystem, Microsimulation, Simulation +from policyengine_uk.data import UKMultiYearDataset, UKSingleYearDataset +from policyengine_uk.data.isa_income import LEGACY_CONTRACT, simulation_contract +from policyengine_uk.data.savings_income_projection import ( + OBR_SAVINGS_INCOME_2022_2025, +) +from policyengine_uk.utils.subsample import ( + WEIGHT_VARIABLES, + draw_household_counts, + rescale_weights, + subsample_dataset, +) +from policyengine_uk.utils.supplied_inputs import ( + is_model_value, + set_model_value, + stored_supplied_value, + supplied_input, + supplied_input_arrays, +) + +pytestmark = pytest.mark.usefixtures("cloned_uk_tax_benefit_system") + +YEARS = range(2025, 2031) +# Neighbouring identifiers of the size the UK datasets use. As 32-bit floats, +# identifiers this large are exact only at multiples of 64. +FIRST_HOUSEHOLD_ID = 900_000_001 +FIRST_BENUNIT_ID = 906_000_001 +FIRST_PERSON_ID = 967_000_001 +PERSONAL_ALLOWANCE = "gov.hmrc.income_tax.allowances.personal_allowance.amount" +REGIONS = ["LONDON", "WALES", "SCOTLAND", "NORTH_EAST"] + +# Six households: (weight, people in each benefit unit). +HOUSEHOLDS = [ + (100.0, [1, 1]), + (200.0, [1]), + (300.0, [2, 2]), + (400.0, [1]), + (500.0, [1, 1]), + (600.0, [2]), +] + + +def dataset(households=HOUSEHOLDS, year=2025, weights=True) -> UKSingleYearDataset: + """A dataset of ``households``, each a weight and the number of people in + each of its benefit units.""" + people, benunits, rows = [], [], [] + for index, (weight, units) in enumerate(households): + household_id = FIRST_HOUSEHOLD_ID + index + rows.append( + { + "household_id": household_id, + "household_weight": weight, + "region": REGIONS[index % len(REGIONS)], + "rent": 0.0, + "tenure_type": "OWNED_OUTRIGHT", + "council_tax": 1_000.0 + index, + } + ) + for size in units: + benunit_id = FIRST_BENUNIT_ID + len(benunits) + benunits.append({"benunit_id": benunit_id}) + for _ in range(size): + people.append( + { + "person_id": FIRST_PERSON_ID + len(people), + "person_benunit_id": benunit_id, + "person_household_id": household_id, + "age": 25 + 3 * len(people), + "employment_income": 9_000.0 * (1 + len(people) % 7), + } + ) + household = pd.DataFrame(rows) + if not weights: + household = household.drop(columns="household_weight") + return UKSingleYearDataset( + person=pd.DataFrame(people), + benunit=pd.DataFrame(benunits), + household=household, + fiscal_year=year, + ) + + +def values(simulation, variable, period) -> np.ndarray: + return np.asarray(simulation.calculate(variable, period)) + + +def ids(simulation, entity) -> list: + return np.asarray(simulation.populations[entity].ids).tolist() + + +def members(simulation, entity) -> dict: + """The people in each ``entity``, by its identifier, from the populations.""" + population = simulation.populations[entity] + groups = np.asarray(population.ids)[population.members_entity_id] + members_by_group = {group: set() for group in ids(simulation, entity)} + for person, group in zip(ids(simulation, "person"), groups.tolist()): + members_by_group[group].add(person) + return members_by_group + + +def by_id(simulation, variable, period) -> dict: + entity = simulation.tax_benefit_system.get_variable(variable).entity.key + return dict(zip(ids(simulation, entity), values(simulation, variable, period))) + + +def weights_by_id(simulation, period) -> dict: + return by_id(simulation, "household_weight", period) + + +def supplied(simulation) -> set: + """The variables and periods the simulation holds supplied values for.""" + return { + (name, str(period)) for name, period, _ in supplied_input_arrays(simulation) + } + + +# The reported failure. + + +def test_subsample_runs_on_a_dataset_simulation(): + simulation = Microsimulation(dataset=dataset()) + total = values(simulation, "household_weight", 2026).sum() + + result = simulation.subsample(n=4, seed=0, time_period=2026) + + assert result is simulation + assert 1 <= len(ids(simulation, "household")) <= 4 + assert values(simulation, "household_weight", 2026).sum() == pytest.approx( + total, rel=1e-5 + ) + assert np.isfinite(values(simulation, "household_net_income", 2026)).all() + + +def test_subsample_is_the_uk_method_not_policyengine_cores(): + """policyengine-core's method ends in ``build_from_dataset()``, which the + UK builder cannot answer, so the UK classes must not inherit it.""" + assert "subsample" in vars(Simulation) + assert Microsimulation.subsample is Simulation.subsample + + +# Links. + + +def test_identifiers_beyond_float32_precision_keep_their_households(): + simulation = Microsimulation(dataset=dataset()) + households = members(simulation, "household") + benunits = members(simulation, "benunit") + + simulation.subsample(n=5, seed=3, time_period=2025) + + kept = ids(simulation, "household") + assert 1 < len(kept) <= 5 + assert members(simulation, "household") == { + household: households[household] for household in kept + } + kept_people = set(ids(simulation, "person")) + assert members(simulation, "benunit") == { + benunit: people for benunit, people in benunits.items() if people <= kept_people + } + assert kept_people == set().union(*(households[household] for household in kept)) + assert values(simulation, "household_id", 2025).tolist() == kept + + +def test_memberships_come_from_the_populations_not_the_stored_identifiers(): + simulation = Microsimulation(dataset=dataset()) + households = members(simulation, "household") + benunits = members(simulation, "benunit") + people = len(ids(simulation, "person")) + for variable in ("person_household_id", "person_benunit_id"): + simulation.set_input(variable, 2025, np.zeros(people)) + + simulation.subsample(n=5, seed=3) + + for entity, before in (("household", households), ("benunit", benunits)): + assert members(simulation, entity) == { + group: before[group] for group in ids(simulation, entity) + } + # Intended: the stored values are supplied inputs, so they are kept. + assert set(values(simulation, "person_household_id", 2025).tolist()) == {0} + + +def test_zero_weight_households_are_never_kept(): + households = [(0.0, [1]), (50.0, [2]), (0.0, [1, 1]), (70.0, [1])] + for seed in range(5): + simulation = Microsimulation(dataset=dataset(households)) + simulation.subsample(n=6, seed=seed) + assert set(ids(simulation, "household")) <= { + FIRST_HOUSEHOLD_ID + 1, + FIRST_HOUSEHOLD_ID + 3, + } + + +# Weights. + + +def test_quantized_weights_count_draws_and_keep_every_years_total(): + simulation = Microsimulation(dataset=dataset()) + totals = { + year: values(simulation, "household_weight", year).sum() for year in YEARS + } + + simulation.subsample(n=7, seed=1, time_period=2027) + + draws = None + for year in YEARS: + weights = values(simulation, "household_weight", year) + assert weights.sum() == pytest.approx(totals[year], rel=1e-5) + multiples = weights * 7 / totals[year] + assert np.abs(multiples - multiples.round()).max() < 1e-3 + assert multiples.round().sum() == 7 + # The same draws set the weights of every year. + assert draws is None or multiples.round().tolist() == draws + draws = multiples.round().tolist() + + +def test_unquantized_weights_scale_the_old_weights_by_draws(): + simulation = Microsimulation(dataset=dataset()) + before = weights_by_id(simulation, 2025) + total = sum(before.values()) + + simulation.subsample(n=5, seed=2, quantize_weights=False) + + after = weights_by_id(simulation, 2025) + assert sum(after.values()) == pytest.approx(total, rel=1e-5) + ratios = np.array([after[household] / before[household] for household in after]) + draws = ratios * 5 / ratios.sum() + assert np.abs(draws - draws.round()).max() < 1e-3 + assert draws.round().sum() == 5 + + +def test_other_supplied_weights_keep_their_totals_over_their_own_entity(): + data = dataset() + data.household["original_weight"] = [7.0, 5.0, 3.0, 2.0, 1.0, 9.0] + data.person["raw_person_weight"] = np.arange(1.0, len(data.person) + 1) + simulation = Microsimulation(dataset=data) + benunit_weight = values(simulation, "benunit_weight", 2025) + simulation.set_input("benunit_weight", 2025, benunit_weight * 2) + totals = { + (name, year): values(simulation, name, year).sum() + for name in ("original_weight", "raw_person_weight") + for year in YEARS + } + totals["benunit_weight", 2025] = benunit_weight.sum() * 2 + + simulation.subsample(n=4, seed=5) + + for (name, year), total in totals.items(): + assert values(simulation, name, year).sum() == pytest.approx(total, rel=1e-5) + table = getattr( + simulation.dataset[year], + simulation.tax_benefit_system.get_variable(name).entity.key, + ) + if name in table: + assert table[name].sum() == pytest.approx(total, rel=1e-5) + + +def test_every_weight_variable_is_listed(): + """A new sampling weight must be rescaled by a subsample, so it has to be + listed. A variable that only ends in "weight" must be left out on purpose: + household_bus_fare_age_weight shares out bus fare spending by age.""" + named = { + name for name in CountryTaxBenefitSystem().variables if name.endswith("weight") + } + assert named == WEIGHT_VARIABLES | {"household_bus_fare_age_weight"} + + +# Inputs. + + +def test_supplied_values_are_kept_and_calculated_values_are_not(): + simulation = Microsimulation(dataset=dataset()) + hours = np.arange(1.0, len(ids(simulation, "person")) + 1) + simulation.set_input("hours_worked", 2027, hours) + energy = np.arange(10.0, 10.0 + len(ids(simulation, "household"))) + simulation.set_input("monthly_domestic_energy_consumption", "2026-03", energy) + hours_by_person = dict(zip(ids(simulation, "person"), hours)) + energy_by_household = dict(zip(ids(simulation, "household"), energy)) + ages = {year: by_id(simulation, "age", year) for year in YEARS} + regions = by_id(simulation, "region", 2025) + inputs = supplied(simulation) + # Calculate results before subsampling; they must not become inputs. + for variable in ("income_tax", "household_net_income", "universal_credit"): + simulation.calculate(variable, 2026) + simulation.calculate("age", 2035) + income_tax = by_id(simulation, "income_tax", 2026) + + simulation.subsample(n=4, seed=4) + + assert supplied(simulation) == inputs + for variable in ("income_tax", "household_net_income", "universal_credit"): + assert simulation.get_holder(variable).get_known_periods() == [] + assert period_(2035) not in simulation.get_holder("age").get_known_periods() + people = ids(simulation, "person") + households = ids(simulation, "household") + # A result calculated before is calculated again, on the sample. + assert by_id(simulation, "income_tax", 2026) == { + person: income_tax[person] for person in people + } + assert by_id(simulation, "hours_worked", 2027) == { + person: hours_by_person[person] for person in people + } + assert by_id(simulation, "monthly_domestic_energy_consumption", "2026-03") == { + household: energy_by_household[household] for household in households + } + for year in YEARS: + assert by_id(simulation, "age", year) == { + person: ages[year][person] for person in people + } + assert by_id(simulation, "region", 2025) == { + household: regions[household] for household in households + } + + +def test_a_calculated_value_that_replaced_an_input_is_not_kept(): + """The record of an input outlives a calculated value stored over it. + The subsample must not keep the record: the next calculation would fill + the period again, and the record would pass the result off as supplied.""" + simulation = Microsimulation(dataset=dataset()) + people = len(ids(simulation, "person")) + simulation.set_input("hours_worked", 2027, np.full(people, 1_000.0)) + simulation.get_holder("hours_worked").put_in_cache( + np.full(people, 500.0), period_(2027) + ) + assert ("hours_worked", "2027") not in supplied(simulation) + + simulation.subsample(n=4, seed=4) + simulation.calculate("hours_worked", 2027) + + assert ("hours_worked", "2027") not in supplied(simulation) + assert "2027" not in simulation.to_input_dict().get("hours_worked", {}) + assert not any( + name == "hours_worked" and str(period) == "2027" + for name, _, period in simulation._user_input_keys + ) + + +def input_on_disk_under_a_cached_value(simulation, folder): + """Store household_net_income for 2025 as an input on disk, then cache a + calculated value over it in memory. Returns the input.""" + period = period_(2025) + holder = simulation.get_holder("household_net_income") + holder._disk_storage = OnDiskStorage(str(folder), preserve_storage_dir=True) + holder._on_disk_storable = True + # A memory limit no simulation can stay under sends the input to disk. + simulation.memory_config = SimpleNamespace(max_memory_occupation_pc=-1) + supplied_value = np.full(len(HOUSEHOLDS), 111.0) + simulation.set_input("household_net_income", period, supplied_value) + holder._on_disk_storable = False + simulation.memory_config = None + holder.put_in_cache(np.full(len(HOUSEHOLDS), 999.0), period) + return supplied_value + + +def test_an_input_on_disk_is_kept_not_a_value_cached_over_it(tmp_path): + simulation = Microsimulation(dataset=dataset()) + supplied_value = input_on_disk_under_a_cached_value(simulation, tmp_path) + holder = simulation.get_holder("household_net_income") + assert holder._memory_storage.get(period_(2025)).tolist() == [999.0] * 6 + + assert stored_supplied_value(holder, period_(2025), "default").tolist() == ( + supplied_value.tolist() + ) + simulation.subsample(n=2, seed=1) + assert set(values(simulation, "household_net_income", 2025).tolist()) == {111.0} + + +def test_supplied_values_match_policyengine_cores_recorded_inputs(tmp_path): + """Differential: policyengine-core 3.33 reads a recorded input from its + tier in ``Simulation._get_recorded_input_array``; earlier versions have + no such method, and ``stored_supplied_value`` follows the same rule.""" + simulation = Microsimulation(dataset=dataset()) + if not hasattr(simulation, "_get_recorded_input_array"): + pytest.skip("policyengine-core reads recorded inputs from 3.33") + input_on_disk_under_a_cached_value(simulation, tmp_path) + people = len(ids(simulation, "person")) + simulation.set_input("hours_worked", 2027, np.full(people, 1_000.0)) + simulation.get_holder("hours_worked").put_in_cache( + np.full(people, 500.0), period_(2027) + ) + simulation.calculate("income_tax", 2026) + + keys = sorted(simulation._user_input_keys, key=lambda key: (key[0], str(key[2]))) + assert keys + for variable, branch, period in keys: + ours = stored_supplied_value(simulation.get_holder(variable), period, branch) + cores = simulation._get_recorded_input_array(variable, period) + if cores is None: + assert ours is None, (variable, period) + else: + assert np.asarray(ours).tolist() == np.asarray(cores).tolist(), ( + variable, + period, + ) + + +def test_a_trace_starts_again_on_the_sample(): + simulation = Microsimulation(dataset=dataset(), trace=True) + simulation.calculate("household_net_income", 2025) + # A baseline traced in its simulation stays traced in it. + simulation.baseline.tracer = simulation.tracer + + simulation.subsample(n=1, seed=1) + simulation.calculate("household_net_income", 2025) + + assert isinstance(simulation.tracer, FullTracer) + assert simulation.baseline.tracer is simulation.tracer + flat = simulation.tracer.get_serialized_flat_trace() + assert len(flat["household_net_income<2025, (default)>"]["value"]) == 1 + + +def test_a_model_value_stays_the_models(): + """Formulas ask whether a value was supplied (``supplied_input``). A value + the model stored as its own must not read as supplied after the rebuild, + while a supplied one still does.""" + simulation = Microsimulation(dataset=dataset()) + benunits = ids(simulation, "benunit") + model = np.arange(1.0, len(benunits) + 1) * 100 + set_model_value(simulation, "uc_LCWRA_element", 2026, model) + simulation.set_input("uc_carer_element", 2026, np.full(len(benunits), 7.0)) + model_by_benunit = dict(zip(benunits, model)) + # The Universal Credit health element reform stores the model's own + # values for other years in every simulation. + model_periods = { + str(period) + for name, period, values in supplied_input_arrays(simulation) + if is_model_value(simulation, name, period, values) + } + assert {"2026", "2027"} <= model_periods + + simulation.subsample(n=3, seed=1) + + benunit = simulation.populations["benunit"] + kept = ids(simulation, "benunit") + assert supplied_input(benunit, "uc_LCWRA_element", period_(2026)) is None + assert by_id(simulation, "uc_LCWRA_element", 2026) == { + unit: model_by_benunit[unit] for unit in kept + } + assert supplied_input(benunit, "uc_carer_element", period_(2026)).tolist() == ( + [7.0] * len(kept) + ) + for held in (simulation, simulation.baseline): + assert { + str(period) + for name, period, values in supplied_input_arrays(held) + if is_model_value(held, name, period, values) + } >= model_periods - {"2026"} + + +@pytest.mark.parametrize("model", [False, True], ids=["supplied", "model"]) +@pytest.mark.xfail( + strict=True, + raises=AssertionError, + reason="needs policyengine-core holder resync", +) +def test_neutralized_inputs_and_model_values_survive_subsampling(model): + """Neutralisation hides stored inputs without discarding them or their owner.""" + data = dataset([(100.0, [1]), (100.0, [1])]) + data.person["employment_income"] = 30_000.0 + simulation = Microsimulation(dataset=data) + name = "adjusted_net_income" + period = period_(2025) + original_variable = simulation.tax_benefit_system.get_variable(name).__class__ + original_values = np.array([10_000.0, 11_000.0]) + if model: + set_model_value(simulation, name, period, original_values) + else: + simulation.set_input(name, period, original_values) + original_by_person = dict(zip(ids(simulation, "person"), original_values)) + + class NeutralizeIncome(Reform): + def apply(self): + self.neutralize_variable(name) + + class RestoreIncome(Reform): + def apply(self): + self.replace_variable(original_variable) + + simulation.apply_reform(NeutralizeIncome) + expected_results = { + variable: by_id(simulation, variable, period) + for variable in ("net_income", "income_tax") + } + if not model: + assert all( + value == 0 + for result in expected_results.values() + for value in result.values() + ) + + simulation.subsample(n=1, seed=0, time_period=2025) + + kept = ids(simulation, "person") + expected_input = [original_by_person[person] for person in kept] + assert (name, str(period)) in supplied(simulation) + stored = stored_supplied_value( + simulation.get_holder(name), period, simulation.branch_name + ) + np.testing.assert_array_equal(stored, expected_input) + assert is_model_value(simulation, name, period, stored) is model + assert simulation.tax_benefit_system.get_variable(name).is_neutralized + np.testing.assert_array_equal(values(simulation, name, period), np.zeros(len(kept))) + person = simulation.populations["person"] + if model: + assert supplied_input(person, name, period) is None + else: + np.testing.assert_array_equal( + supplied_input(person, name, period), np.zeros(len(kept)) + ) + for variable, expected in expected_results.items(): + assert by_id(simulation, variable, period) == { + person: expected[person] for person in kept + } + + simulation.apply_reform(RestoreIncome) + + np.testing.assert_array_equal(values(simulation, name, period), expected_input) + assert is_model_value(simulation, name, period, np.asarray(expected_input)) is model + if model: + assert supplied_input(person, name, period) is None + else: + np.testing.assert_array_equal( + supplied_input(person, name, period), expected_input + ) + + +def test_where_capital_gains_inputs_came_from_is_kept(): + data = dataset() + data.person["capital_gains"] = np.arange(len(data.person)) * 1_000.0 + simulation = Microsimulation(dataset=data) + full = simulation.dataset + before = simulation.capital_gains_projection_metadata["application"] + statuses = {record["status"] for record in before["by_period"].values()} + assert statuses == {"supplied", "projected"} + + simulation.subsample(n=3, seed=1) + + assert simulation.capital_gains_projection_metadata["application"] == before + assert ( + simulation.dataset._cgt_extension_provenance == full._cgt_extension_provenance + ) + # Differential: a simulation built from the subsampled dataset reports + # the same origins as one built from the full dataset. + rebuilt = Microsimulation(dataset=simulation.dataset) + assert ( + rebuilt.capital_gains_projection_metadata["application"] + == Microsimulation(dataset=full).capital_gains_projection_metadata[ + "application" + ] + ) + + +def test_a_neutralised_capital_gains_input_still_reads_as_its_default(): + data = dataset() + data.person["capital_gains"] = np.arange(len(data.person)) * 1_000.0 + simulation = Microsimulation(dataset=data) + + class NeutraliseGains(Reform): + def apply(self): + self.neutralize_variable("capital_gains_before_response") + + simulation.apply_reform(NeutraliseGains) + simulation.calculate("capital_gains_before_response", 2026) + before = simulation.capital_gains_projection_metadata["application"] + by_variable = before["by_variable"]["capital_gains_before_response"] + assert by_variable["2026"]["status"] == "default" + + simulation.subsample(n=3, seed=1) + + assert simulation.capital_gains_projection_metadata["application"] == before + + +def test_how_the_dataset_says_its_amounts_grow_is_kept(): + """The dataset's ISA income contract, savings income series and energy + price basis describe every household, so the sample keeps them.""" + data = dataset() + data = UKSingleYearDataset( + person=data.person.assign( + savings_interest_income=np.arange(len(data.person)) * 500.0, + individual_savings_account_interest_income=100.0, + ), + benunit=data.benunit, + household=data.household, + fiscal_year=2025, + isa_income_contract=dict(LEGACY_CONTRACT), + savings_income_projection=OBR_SAVINGS_INCOME_2022_2025, + energy_price_basis={"period_type": "fiscal_year", "period_value": 2025}, + ) + full = Microsimulation(dataset=data) + simulation = Microsimulation(dataset=data) + full_dataset = simulation.dataset + years = full_dataset.years + contracts = {year: simulation_contract(simulation, year) for year in years} + + simulation.subsample(n=4, seed=0, time_period=2026) + + for each in (simulation, simulation.baseline): + assert {year: simulation_contract(each, year) for year in years} == contracts + assert each._savings_income_projection == OBR_SAVINGS_INCOME_2022_2025 + sample = simulation.dataset + for year in years: + for name in ( + "isa_income_contract", + "savings_income_projection", + "energy_price_basis", + ): + assert getattr(sample[year], name) == getattr(full_dataset[year], name) + # Under the legacy contract the model projects savings interest past the + # dataset's last year from gross interest. + expected = by_id(full, "savings_interest_income", 2035) + for record, value in by_id(simulation, "savings_interest_income", 2035).items(): + assert value == pytest.approx(expected[record]) + + +def test_results_match_the_same_households_in_the_full_simulation(): + """Subsampling changes which households are held and their weights, + not what the model calculates for a household.""" + full = Microsimulation(dataset=dataset()) + sample = Microsimulation(dataset=dataset()) + sample.subsample(n=4, seed=6, time_period=2026) + + for variable in ("income_tax", "household_net_income", "council_tax"): + expected = by_id(full, variable, 2026) + for record, value in by_id(sample, variable, 2026).items(): + assert value == pytest.approx(expected[record]) + + +# Determinism. + + +def test_the_same_seed_keeps_the_same_households(): + samples = [] + for seed in (0, 0, "text seed", "text seed", None, None): + simulation = Microsimulation(dataset=dataset()) + simulation.subsample(n=3, seed=seed, time_period=2026) + samples.append(weights_by_id(simulation, 2026)) + + assert samples[0] == samples[1] + assert samples[2] == samples[3] + assert samples[4] == samples[5] + + +def test_different_seeds_keep_different_households(): + weights = np.array([weight for weight, _ in HOUSEHOLDS]) + draws = {tuple(draw_household_counts(weights, 2, seed)) for seed in range(12)} + assert len(draws) > 1 + + +def test_frac_sets_the_number_of_draws(): + by_frac = Microsimulation(dataset=dataset()) + by_frac.subsample(frac=0.5, seed=8) + by_n = Microsimulation(dataset=dataset()) + by_n.subsample(n=3, seed=8) + + assert weights_by_id(by_frac, 2025) == weights_by_id(by_n, 2025) + + +def test_a_period_before_the_data_samples_by_the_first_weights(): + """The model has no weights before the data's first year: it would give + every household the default weight of one.""" + early = Microsimulation(dataset=dataset()) + assert set(values(early, "household_weight", 2020).tolist()) == {1.0} + early.subsample(n=3, seed=9, time_period=2020) + first = Microsimulation(dataset=dataset()) + first.subsample(n=3, seed=9, time_period=2025) + + assert weights_by_id(early, 2025) == weights_by_id(first, 2025) + + +# Baseline. + + +def test_a_reform_and_its_baseline_keep_the_same_households(): + reform = {PERSONAL_ALLOWANCE: 0} + simulation = Microsimulation(dataset=dataset(), reform=reform) + + simulation.subsample(n=4, seed=0, time_period=2026) + + baseline = simulation.baseline + assert 1 <= len(ids(simulation, "household")) <= 4 + for held in (baseline, baseline.baseline): + assert ids(held, "household") == ids(simulation, "household") + assert ids(held, "person") == ids(simulation, "person") + assert weights_by_id(held, 2026) == weights_by_id(simulation, 2026) + # Each simulation keeps its own policy, on the sample. + sample = simulation.dataset + reformed = Microsimulation(dataset=sample, reform=reform) + unreformed = Microsimulation(dataset=sample) + for held, expected in ((simulation, reformed), (baseline, unreformed)): + assert values(held, "income_tax", 2026).tolist() == pytest.approx( + values(expected, "income_tax", 2026).tolist() + ) + assert ( + values(simulation, "income_tax", 2026).sum() + > values(baseline, "income_tax", 2026).sum() + ) + + +@pytest.mark.parametrize("reform", [None, {PERSONAL_ALLOWANCE: 0}]) +def test_subsampling_a_clone_leaves_the_source_and_its_baseline_alone(reform): + """policyengine-core's ``clone`` shares a separate baseline between the + source and the clone, so the clone must not subsample it in place.""" + source = Microsimulation(dataset=dataset(), reform=reform) + baselines = [] + held = source + while getattr(held, "baseline", None) is not None: + held = held.baseline + baselines.append((held, held.dataset, weights_by_id(held, 2026))) + clone = source.clone() + assert clone.baseline is source.baseline + + clone.subsample(n=2, seed=1) + + assert len(ids(clone, "household")) <= 2 + assert ids(clone.baseline, "household") == ids(clone, "household") + assert len(ids(source, "household")) == len(HOUSEHOLDS) + held = source + for baseline, data, weights in baselines: + assert held.baseline is baseline + assert len(ids(baseline, "household")) == len(HOUSEHOLDS) + assert baseline.dataset is data + assert weights_by_id(baseline, 2026) == weights + held = baseline + # The source can still be subsampled on its own. + source.subsample(n=3, seed=2) + assert ids(source.baseline, "household") == ids(source, "household") + + +def test_the_baseline_held_before_is_left_as_it_was(): + simulation = Microsimulation(dataset=dataset()) + before = simulation.baseline + + simulation.subsample(n=2, seed=1) + + assert simulation.baseline is not before + assert len(ids(before, "household")) == len(HOUSEHOLDS) + assert ids(simulation.baseline, "household") == ids(simulation, "household") + + +def test_a_baseline_copy_does_not_copy_the_baselines_arrays(monkeypatch): + """The copy of a baseline rebuilds its arrays at once, so copying the + baseline's cached arrays first would only double its memory.""" + from policyengine_core.data_storage import InMemoryStorage + + from policyengine_uk.utils import subsample as module + + if module._branch_clone is None: + pytest.skip("this policyengine-core cannot share a clone's arrays") + simulation = Microsimulation(dataset=dataset(), reform={PERSONAL_ALLOWANCE: 0}) + simulation.baseline.calculate("household_net_income", 2026) + calls = [] + clone = InMemoryStorage.clone + + def recording_clone(self, share_arrays=False): + calls.append(share_arrays) + return clone(self, share_arrays=share_arrays) + + monkeypatch.setattr(InMemoryStorage, "clone", recording_clone) + + simulation.subsample(n=3, seed=1) + + assert calls + assert all(calls) + + +def test_a_baseline_holding_other_households_is_refused_and_nothing_changes(): + simulation = Microsimulation(dataset=dataset()) + simulation.baseline.subsample(n=2, seed=1) + households = ids(simulation, "household") + data = simulation.dataset + + with pytest.raises(ValueError, match="same households"): + simulation.subsample(n=3, seed=0) + + assert ids(simulation, "household") == households + assert simulation.dataset is data + + +# Dataset. + + +def test_the_dataset_holds_the_sample(): + simulation = Microsimulation(dataset=dataset()) + full = simulation.dataset + full_households = len(full[2025].household) + + simulation.subsample(n=4, seed=0, time_period=2026) + + sample = simulation.dataset + assert isinstance(sample, UKMultiYearDataset) + assert sample is not full + assert sample.years == full.years + assert simulation.baseline.dataset is sample + # The dataset the simulation was built from is not changed. + assert len(full[2025].household) == full_households + for year in sample.years: + tables = sample[year] + assert tables.household.household_id.tolist() == ids(simulation, "household") + assert tables.benunit.benunit_id.tolist() == ids(simulation, "benunit") + assert tables.person.person_id.tolist() == ids(simulation, "person") + assert tables.household.household_weight.tolist() == pytest.approx( + values(simulation, "household_weight", year).tolist(), rel=1e-5 + ) + assert tables.household.region.tolist() == list( + values(simulation, "region", year) + ) + + +def test_inputs_set_after_the_build_stay_out_of_the_dataset(): + """Intended: ``dataset`` is the subsample of the dataset the simulation + was built from, which held no values set afterwards either. So a later + input stays in the simulation only, and a weight set on the simulation + alone is rescaled to its own total there, while the baseline and the + dataset keep the dataset's weights.""" + simulation = Microsimulation(dataset=dataset()) + people = len(ids(simulation, "person")) + simulation.set_input("hours_worked", 2025, np.full(people, 1_234.0)) + simulation.set_input("household_weight", 2025, np.ones(len(HOUSEHOLDS))) + hours_in_data = Microsimulation(dataset=simulation.dataset).calculate( + "hours_worked", 2025 + ) + + simulation.subsample(n=2, seed=1) + + rebuilt = Microsimulation(dataset=simulation.dataset) + assert set(values(simulation, "hours_worked", 2025).tolist()) == {1_234.0} + assert set(values(rebuilt, "hours_worked", 2025).tolist()) <= set( + np.asarray(hours_in_data).tolist() + ) + assert values(simulation, "household_weight", 2025).sum() == pytest.approx( + len(HOUSEHOLDS) + ) + total = sum(weight for weight, _ in HOUSEHOLDS) + for held in (simulation.baseline, rebuilt): + assert values(held, "household_weight", 2025).sum() == pytest.approx(total) + + +def test_an_input_for_part_of_a_year_stays_out_of_the_dataset(): + """Intended: a DataFrame can give a monthly input, which the simulation + keeps and a dataset of whole years cannot hold, so a simulation built + from the subsampled dataset does not have it.""" + frame = pd.DataFrame( + { + "person_id__2025": [1, 2], + "household_id__2025": [1, 2], + "household_weight__2025": [1.0, 1.0], + "ebr_energy_bills_credit_eligible__2025-01": [False, False], + } + ) + simulation = Microsimulation(dataset=frame) + + simulation.subsample(n=1, seed=1) + + monthly = ("ebr_energy_bills_credit_eligible", "2025-01") + assert monthly in supplied(simulation) + assert values(simulation, *monthly).tolist() == [False] + assert monthly not in supplied(Microsimulation(dataset=simulation.dataset)) + + +def test_subsampling_a_single_year_dataset_keeps_its_type(): + data = dataset() + counts = np.array([0, 2, 0, 1, 0, 0]) + household_ids = data.household.household_id.values + + sample = subsample_dataset(data, household_ids, counts) + + assert isinstance(sample, UKSingleYearDataset) + assert sample.time_period == data.time_period + assert sample.household.household_id.tolist() == household_ids[counts > 0].tolist() + assert sample.household.household_weight.tolist() == pytest.approx([1_400.0, 700.0]) + assert len(data.household) == 6 + + +def test_a_simulation_built_from_a_dataframe_subsamples_its_dataset(): + households = np.arange(4) + frame = pd.DataFrame( + { + "person_id__2025": FIRST_PERSON_ID + households, + "person_benunit_id__2025": FIRST_BENUNIT_ID + households, + "person_household_id__2025": FIRST_HOUSEHOLD_ID + households, + "benunit_id__2025": FIRST_BENUNIT_ID + households, + "household_id__2025": FIRST_HOUSEHOLD_ID + households, + "household_weight__2025": [10.0, 20.0, 30.0, 40.0], + "age__2025": [30, 40, 50, 60], + } + ) + simulation = Microsimulation(dataset=frame) + ages = by_id(simulation, "age", 2025) + + simulation.subsample(n=3, seed=1) + + kept = ids(simulation, "household") + assert 1 <= len(kept) <= 3 + assert ids(simulation.baseline, "household") == kept + assert sum(weights_by_id(simulation, 2025).values()) == pytest.approx(100.0) + assert by_id(simulation, "age", 2025) == { + person: ages[person] for person in ids(simulation, "person") + } + assert isinstance(simulation.dataset, UKMultiYearDataset) + tables = simulation.dataset[2025] + assert tables.household.household_id.tolist() == kept + assert tables.household.household_weight.sum() == pytest.approx(100.0) + + +# Refusals. + + +def test_subsample_needs_n_or_frac(): + simulation = Microsimulation(dataset=dataset()) + with pytest.raises(ValueError, match="n or frac"): + simulation.subsample(seed=0) + + +@pytest.mark.parametrize("n", [0, -3]) +def test_subsample_needs_at_least_one_draw(n): + simulation = Microsimulation(dataset=dataset()) + with pytest.raises(ValueError, match="at least one household"): + simulation.subsample(n=n) + assert len(ids(simulation, "household")) == len(HOUSEHOLDS) + + +def test_a_simulation_without_weights_is_refused(): + simulation = Microsimulation(dataset=dataset(weights=False)) + with pytest.raises(ValueError, match="household_weight"): + simulation.subsample(n=2) + + +def test_a_negative_household_weight_is_refused_and_nothing_changes(): + simulation = Microsimulation(dataset=dataset([(1.0, [1]), (-2.0, [1])])) + weights = weights_by_id(simulation, 2025) + + with pytest.raises(ValueError, match="negative"): + simulation.subsample(n=1, seed=0) + + assert weights_by_id(simulation, 2025) == weights + + +def test_another_negative_weight_is_refused(): + data = dataset() + data.household["original_weight"] = [1.0, 2.0, 3.0, -4.0, 5.0, 6.0] + simulation = Microsimulation(dataset=data) + households = ids(simulation, "household") + + with pytest.raises(ValueError, match="original_weight for 2025.*negative"): + simulation.subsample(n=3) + + assert ids(simulation, "household") == households + + +def test_a_simulation_with_no_positive_weight_is_refused(): + households = [(0.0, [1]), (0.0, [2])] + simulation = Microsimulation(dataset=dataset(households)) + with pytest.raises(ValueError, match="positive weight"): + simulation.subsample(n=2) + + +def test_a_situation_is_refused(): + simulation = Simulation(situation={"age": 30}) + with pytest.raises(ValueError, match="built from a dataset"): + simulation.subsample(n=1) + + +def test_a_branch_is_refused(): + simulation = Microsimulation(dataset=dataset()) + branch = simulation.get_branch("other") + with pytest.raises(ValueError, match="branches"): + branch.subsample(n=2) + + +def test_branches_are_made_again_on_the_sample(): + simulation = Microsimulation(dataset=dataset()) + simulation.get_branch("other").calculate("income_tax", 2026) + + simulation.subsample(n=3, seed=0) + + assert simulation.branches == {} + branch = simulation.get_branch("other") + assert ids(branch, "household") == ids(simulation, "household") + assert len(branch.calculate("income_tax", 2026)) == len(ids(simulation, "person")) + + +def test_a_benefit_unit_across_households_is_refused(): + data = dataset() + # Move the second person of the third household's first benefit unit to + # the fourth household. + data.person.loc[3, "person_household_id"] = FIRST_HOUSEHOLD_ID + 3 + simulation = Microsimulation(dataset=data) + with pytest.raises(ValueError, match="more than one household"): + simulation.subsample(n=3) + + +def test_a_total_that_cannot_be_kept_names_the_weight(): + simulation = Microsimulation(dataset=dataset()) + simulation.set_input("original_weight", 2026, [np.inf, 1.0, 1.0, 1.0, 1.0, 1.0]) + households = ids(simulation, "household") + + with pytest.raises(ValueError, match="original_weight for 2026.*finite total"): + simulation.subsample(n=3) + + assert ids(simulation, "household") == households + + +@pytest.mark.parametrize("quantize", [True, False]) +def test_a_weight_held_only_by_records_not_drawn_is_refused(quantize): + """The third household holds all of the original weight and is never + drawn, and the drawn ones stand for no one, so no sample keeps that + total.""" + data = dataset([(100.0, [1]), (200.0, [2]), (0.0, [1])]) + data.household["original_weight"] = [0.0, 0.0, 9.0] + simulation = Microsimulation(dataset=data) + + with pytest.raises(ValueError, match="original_weight for 2025.*no weight"): + simulation.subsample(n=2, quantize_weights=quantize) + + +def test_a_zero_weight_stays_zero_in_every_year(): + """A household drawn by its positive weight in one year keeps a zero + weight in a year where it has one, and the year's total goes to the + drawn households that stand for someone that year.""" + years = [] + for year, weights in ((2025, [100.0, 200.0, 300.0]), (2026, [0.0, 200.0, 300.0])): + years.append(dataset([(weight, [1]) for weight in weights], year=year)) + simulation = Microsimulation(dataset=UKMultiYearDataset(datasets=years)) + + simulation.subsample(n=6, seed=0, time_period=2025) + + first = FIRST_HOUSEHOLD_ID + kept = ids(simulation, "household") + assert first in kept + weights_2026 = weights_by_id(simulation, 2026) + assert weights_2026[first] == 0 + assert sum(weights_2026.values()) == pytest.approx(500.0) + assert sum(weights_by_id(simulation, 2025).values()) == pytest.approx(600.0) + assert rescale_weights(np.array([0.0, 100, 100]), np.array([1, 1, 0])).tolist() == ( + [0.0, 200.0, 0.0] + ) + + +# Properties of the draw and the weights. + +DRAW_SETTINGS = settings(max_examples=200, deadline=None, derandomize=True) +weight = st.one_of( + st.just(0.0), + st.floats(min_value=1e-3, max_value=1e6, allow_nan=False, allow_infinity=False), +) +weight_lists = st.lists(weight, min_size=1, max_size=40).filter( + lambda weights: max(weights) > 0 +) +seeds = st.one_of(st.integers(), st.text(max_size=8)) + + +@DRAW_SETTINGS +@given( + weights=weight_lists, + n=st.integers(1, 60), + seed=seeds, + quantize=st.booleans(), +) +def test_draws_sum_to_n_and_skip_weightless_households(weights, n, seed, quantize): + weights = np.array(weights) + + counts = draw_household_counts(weights, n, seed, quantize) + + assert counts.shape == weights.shape + assert counts.sum() == n + assert (counts >= 0).all() + assert (counts[weights <= 0] == 0).all() + assert 1 <= (counts > 0).sum() <= n + assert counts.tolist() == draw_household_counts(weights, n, seed, quantize).tolist() + + +@DRAW_SETTINGS +@given( + weights=weight_lists, + n=st.integers(1, 60), + seed=seeds, + quantize=st.booleans(), +) +def test_rescaled_weights_keep_the_total(weights, n, seed, quantize): + weights = np.array(weights) + counts = draw_household_counts(weights, n, seed, quantize) + + rescaled = rescale_weights(weights, counts, quantize) + + assert rescaled.sum() == pytest.approx(weights.sum(), rel=1e-9) + assert (rescaled[counts == 0] == 0).all() + assert (rescaled[counts > 0] > 0).all() + drawn = counts > 0 + shares = rescaled[drawn] / ( + counts[drawn] if quantize else weights[drawn] * counts[drawn] + ) + assert shares == pytest.approx(np.full(drawn.sum(), shares[0]), rel=1e-9) + + +@DRAW_SETTINGS +@given( + weights=weight_lists, + counts=st.data(), + quantize=st.booleans(), +) +def test_a_second_weight_keeps_its_own_total(weights, counts, quantize): + """A weight is rescaled by draws made from another weight, as when a + year's weights are rescaled by a sample drawn in another year.""" + weights = np.array(weights) + counts = np.array( + counts.draw( + st.lists(st.integers(0, 5), min_size=len(weights), max_size=len(weights)) + ) + ) + drawn_weight = (counts * (weights > 0) if quantize else weights * counts).sum() + if weights.sum() > 0 and drawn_weight == 0: + with pytest.raises(ValueError, match="no weight"): + rescale_weights(weights, counts, quantize) + return + + rescaled = rescale_weights(weights, counts, quantize) + + assert rescaled.sum() == pytest.approx(weights.sum(), rel=1e-9) + assert (rescaled[counts == 0] == 0).all() + + +def test_negative_sampling_weights_are_refused_before_drawing(): + """A negative weight would otherwise just never be drawn, and the total + it lowers would be shared out among the drawn households.""" + with pytest.raises(ValueError, match="must not be negative to sample"): + draw_household_counts(np.array([1.0, -2.0, 3.0]), 2, 0) + + +def test_weights_without_a_total_are_refused_or_stay_zero(): + counts = np.array([1, 2]) + assert rescale_weights(np.zeros(2), counts).tolist() == [0.0, 0.0] + for weights in ([np.nan, 1.0], [np.inf, 1.0]): + with pytest.raises(ValueError, match="finite total"): + rescale_weights(np.array(weights), counts) + with pytest.raises(ValueError, match="finite"): + draw_household_counts(np.array([np.inf, 1.0]), 2, 0) + + +def mean_new_weights(weights, n, seeds, quantize): + return np.mean( + [ + rescale_weights( + weights, draw_household_counts(weights, n, seed, quantize), quantize + ) + for seed in range(seeds) + ], + axis=0, + ) + + +def test_a_households_mean_quantized_weight_is_its_old_weight(): + weights = np.array([1.0, 2.0, 3.0, 4.0, 0.0, 10.0, 30.0]) + + mean = mean_new_weights(weights, n=40, seeds=3_000, quantize=True) + + assert mean == pytest.approx(weights, rel=0.03) + + +def test_unquantized_weights_are_a_ratio_estimate(): + """Intended: keeping the total exactly makes the unquantized weights a + ratio estimate, so a household's mean new weight is off by a few per cent + in a small sample and closes on its old weight as the sample grows.""" + weights = np.array([1.0, 2.0, 3.0, 4.0, 0.0, 10.0, 30.0]) + positive = weights > 0 + + def error(n): + mean = mean_new_weights(weights, n=n, seeds=1_500, quantize=False) + return np.abs(mean[positive] / weights[positive] - 1).max() + + assert 0.04 < error(40) < 0.10 + assert error(400) < 0.02 + + +def test_another_periods_mean_weight_follows_the_sampling_periods_shares(): + """Intended: households are drawn by their weights in the sampling period + only, so in another period a household's mean new weight is its share of + the sampling period's total times that period's total. That is its old + weight there only if its share is the same in both periods.""" + sampling = np.array([1.0, 2.0, 3.0, 4.0, 10.0]) + other = np.array([5.0, 1.0, 3.0, 4.0, 2.0]) + expected = sampling / sampling.sum() * other.sum() + mean = np.mean( + [ + rescale_weights(other, draw_household_counts(sampling, 40, seed)) + for seed in range(3_000) + ], + axis=0, + ) + assert mean == pytest.approx(expected, rel=0.03) + assert not np.allclose(mean, other, rtol=0.2) + + +# Properties of a subsampled simulation. + +MAX_HOUSEHOLDS = 7 +SIMULATION_SETTINGS = settings( + max_examples=10, + deadline=None, + derandomize=True, + suppress_health_check=[HealthCheck.too_slow, HealthCheck.data_too_large], +) +household_specs = st.lists( + st.tuples( + st.one_of(st.just(0.0), st.floats(min_value=0.5, max_value=5_000.0)), + st.lists(st.integers(1, 3), min_size=1, max_size=2), + ), + min_size=2, + max_size=MAX_HOUSEHOLDS, +).filter(lambda households: any(weight > 0 for weight, _ in households)) + + +MULTI_YEARS = (2025, 2026, 2027) + + +def multi_year_dataset(households, factors) -> UKMultiYearDataset: + """A dataset of ``households`` for each of MULTI_YEARS, with each + household's weight multiplied by its own factor in each year.""" + return UKMultiYearDataset( + datasets=[ + dataset( + [ + (weight * factor, units) + for (weight, units), factor in zip(households, year_factors) + ], + year=year, + ) + for year, year_factors in zip(MULTI_YEARS, factors) + ] + ) + + +FACTORS = st.lists( + st.lists( + st.sampled_from([0.5, 0.8, 1.0, 1.25, 2.0]), + min_size=MAX_HOUSEHOLDS, + max_size=MAX_HOUSEHOLDS, + ), + min_size=len(MULTI_YEARS), + max_size=len(MULTI_YEARS), +) +# Households whose shares of the total weight change from year to year. +CHANGING_SHARES = dict( + households=[(100.0, [1]), (300.0, [2]), (0.0, [1]), (50.0, [1, 2])], + n=6, + seed=11, + multi_year=True, + factors=[[1.0] * MAX_HOUSEHOLDS, [2.0, 0.5, 1.0, 1.25, 1, 1, 1], [0.5] + [2.0] * 6], + year_index=1, +) + + +@SIMULATION_SETTINGS +@given( + households=household_specs, + n=st.integers(1, 10), + seed=st.integers(0, 10_000), + quantize=st.booleans(), + multi_year=st.booleans(), + factors=FACTORS, + year_index=st.integers(0, len(YEARS) - 1), +) +@example(quantize=True, **CHANGING_SHARES) +@example(quantize=False, **CHANGING_SHARES) +def test_subsample_properties( + households, n, seed, quantize, multi_year, factors, year_index +): + if multi_year: + factors = [year_factors[: len(households)] for year_factors in factors] + years = list(MULTI_YEARS) + else: + years = list(YEARS) + year = years[year_index % len(years)] + + def build(): + if multi_year: + return Microsimulation(dataset=multi_year_dataset(households, factors)) + return Microsimulation(dataset=dataset(households)) + + def subsample(): + return build().subsample( + n=n, seed=seed, time_period=year, quantize_weights=quantize + ) + + full = build() + sample = subsample() + kept = ids(sample, "household") + people = ids(sample, "person") + + # 1. Size. + assert 1 <= len(kept) <= n + full_weights = {period: weights_by_id(full, period) for period in years} + assert all(full_weights[year][household] > 0 for household in kept) + + draws_by_period = {} + for period in years: + weights = weights_by_id(sample, period) + total = sum(full_weights[period].values()) + # 2. Weight totals. + assert sum(weights.values()) == pytest.approx(total, rel=1e-5) + # 3. Quantized weights: whole numbers of draws, of the old weight + # when the weights are not quantized. + shares = np.array( + [ + weights[household] + / (1 if quantize else full_weights[period][household]) + for household in kept + ] + ) + draws = shares * n / shares.sum() + assert np.abs(draws - draws.round()).max() < 1e-2 + assert draws.round().sum() == n + draws_by_period[period] = draws.round().tolist() + # The same draws set the weights of every period. + assert len({tuple(draws) for draws in draws_by_period.values()}) == 1 + + # 4. Links. + for entity in ("household", "benunit"): + full_members = members(full, entity) + sample_members = members(sample, entity) + assert all(sample_members.values()) + assert sample_members == { + group: full_members[group] for group in sample_members + } + assert set(people) == set().union(*members(sample, "household").values()) + assert set(people) == set().union(*members(sample, "benunit").values()) + assert len(set(people)) == len(people) + + # 5. Inputs. + assert supplied(sample) == supplied(full) + for period in years: + for variable in ("age", "employment_income", "region", "council_tax"): + expected = by_id(full, variable, period) + assert by_id(sample, variable, period) == { + record: expected[record] + for record in ids( + sample, sample.tax_benefit_system.get_variable(variable).entity.key + ) + } + + # 6. Determinism. + again = subsample() + assert ids(again, "person") == people + for period in years: + assert weights_by_id(again, period) == weights_by_id(sample, period) + + # 7. Baseline. + assert ids(sample.baseline, "household") == kept + assert ids(sample.baseline, "person") == people + assert weights_by_id(sample.baseline, year) == weights_by_id(sample, year) + + # 8. Dataset, and a simulation built from it. + rebuilt = Microsimulation(dataset=sample.dataset) + for entity in ("person", "benunit", "household"): + assert ids(rebuilt, entity) == ids(sample, entity) + assert getattr(sample.dataset[year], entity)[f"{entity}_id"].tolist() == ids( + sample, entity + ) + for period in years: + assert list(weights_by_id(rebuilt, period).values()) == pytest.approx( + list(weights_by_id(sample, period).values()), rel=1e-5 + ) + for variable in ("household_net_income", "income_tax", "universal_credit"): + assert values(rebuilt, variable, year).tolist() == pytest.approx( + values(sample, variable, year).tolist() + ) diff --git a/policyengine_uk/tests/test_supplied_inputs.py b/policyengine_uk/tests/test_supplied_inputs.py new file mode 100644 index 0000000000..d06f4b8201 --- /dev/null +++ b/policyengine_uk/tests/test_supplied_inputs.py @@ -0,0 +1,471 @@ +"""Only a supplied value that is still stored counts as a supplied input. + +``supplied_input`` and ``supplied_input_periods`` tell formulas whether a value +was given to the simulation as an input (``set_input``) rather than filled in +by the engine. policyengine-core keeps its record of an input +(``Simulation._user_input_keys``) after a value is cached over the input, so +the helpers read a supplied value only from a storage tier (memory or disk) +that still holds it (#2307). Before, they counted a value cached over an input +as supplied, and read an input stored on disk from memory when a value was +cached over it there. + +Invariants, for every sequence of inputs set, values cached (calculated or +not), arrays deleted and calculations run, on a branch, on the branch it was +made from and on the default branch, in memory or on disk: + +1. Survival (model): ``supplied_input`` returns the input on the nearest of + those branches that still stores one for the period, reading memory before + disk; otherwise None. An input stays stored until it is deleted, or + another input or a value is cached over it in the same tier. A value + cached in memory over an input on disk leaves the input. A value the + engine calculates never replaces an input. +2. Agreement: ``supplied_input`` returns a value for a period exactly when + ``supplied_input_periods`` lists the period, and the list is sorted + earliest first. +3. Differential: for every recorded input, the helpers count it as supplied + exactly when policyengine-core's ``Holder._stores_user_input`` does. On + policyengine-core 3.33.1 and later, ``supplied_input`` returns what + ``Simulation._get_recorded_input_array`` returns, and from 3.33.2 + ``supplied_input_periods`` lists the periods + ``Simulation._get_set_input_periods`` does. +4. Calculation: calculating, on the default branch and on a branch, leaves + every supplied value of every variable in ``SUPPLIED_INPUT_VARIABLES`` + supplied and unchanged. No calculation caches a value over a supplied + input, so in normal use the helpers gave the right answer before the fix + too. + +Intended: a neutralised variable whose input is still stored reads as its +default, as it does through the engine. +""" + +from contextlib import contextmanager, nullcontext +from types import SimpleNamespace + +import numpy as np +import pytest +from hypothesis import HealthCheck, example, given, settings +from hypothesis import strategies as st +from policyengine_core.data_storage import OnDiskStorage +from policyengine_core.enums import Enum +from policyengine_core.periods import period as period_ +from policyengine_core.reforms import Reform + +from policyengine_uk import Simulation +from policyengine_uk.utils.supplied_inputs import ( + SUPPLIED_INPUT_VARIABLES, + stored_supplied_value, + supplied_input, + supplied_input_periods, +) + +pytestmark = pytest.mark.usefixtures("cloned_uk_tax_benefit_system") + + +def single_person(person=None): + return Simulation( + situation={ + "people": {"person": {"age": {2025: 40}, **(person or {})}}, + "benunits": {"benunit": {"members": ["person"]}}, + "households": {"household": {"members": ["person"]}}, + } + ) + + +@contextmanager +def under_memory_pressure(holder, folder): + """Store what ``holder`` stores next on disk, unless it already holds a + value for that period in memory, as a simulation over its memory limit + does.""" + if holder._disk_storage is None: + holder._disk_storage = OnDiskStorage(str(folder), preserve_storage_dir=True) + holder._on_disk_storable = True + # A memory limit no simulation can stay under. + holder.simulation.memory_config = SimpleNamespace(max_memory_occupation_pc=-1) + try: + yield + finally: + holder._on_disk_storable = False + holder.simulation.memory_config = None + + +def read(population, variable, year): + value = supplied_input(population, variable, period_(year)) + return None if value is None else value.tolist() + + +def recorded_input_array(simulation, variable, year): + """policyengine-core's own reading of the supplied value, from 3.33.1.""" + value = simulation._get_recorded_input_array(variable, period_(year)) + return None if value is None else np.asarray(value).tolist() + + +def stored_period(sim, variable, year): + """The period a test stores ``variable`` for: ``year``, or its first month + for a monthly variable.""" + definition = sim.tax_benefit_system.get_variable(variable) + return period_(f"{year}-01" if definition.definition_period == "month" else year) + + +def value_of_type(sim, variable, number): + """A one-person value of ``variable``'s type, built from ``number``: the + number itself, True for a boolean, or one of an enum's values.""" + definition = sim.tax_benefit_system.get_variable(variable) + if definition.value_type is Enum: + names = [item.name for item in definition.possible_values] + return definition.possible_values.encode( + np.array([names[int(number) % len(names)]]) + ) + if definition.value_type is bool: + return np.array([bool(number)]) + return np.array([number], dtype=definition.dtype) + + +@pytest.mark.parametrize("variable", sorted(SUPPLIED_INPUT_VARIABLES)) +def test_a_value_cached_over_an_input_is_not_supplied(variable): + sim = single_person() + holder = sim.get_holder(variable) + population = holder.population + period = stored_period(sim, variable, 2025) + supplied = value_of_type(sim, variable, 1) + cached = value_of_type(sim, variable, 0) + sim.set_input(variable, period, supplied) + assert supplied_input(population, variable, period).tolist() == supplied.tolist() + + holder.put_in_cache(cached, period) + + assert holder.get_array(period).tolist() == cached.tolist() + assert supplied_input(population, variable, period) is None + assert supplied_input_periods(population, variable) == [] + assert not holder._stores_user_input(period, "default") + if hasattr(sim, "_get_recorded_input_array"): + assert sim._get_recorded_input_array(variable, period) is None + + +def test_other_years_inputs_are_still_supplied(): + sim = single_person({"trading_loss": {2024: 100.0, 2025: 200.0, 2026: 300.0}}) + holder = sim.get_holder("trading_loss") + holder.put_in_cache(np.array([999.0]), period_(2025)) + population = holder.population + assert [read(population, "trading_loss", year) for year in (2024, 2025, 2026)] == [ + [100.0], + None, + [300.0], + ] + assert supplied_input_periods(population, "trading_loss") == [ + period_(2024), + period_(2026), + ] + + +def test_an_input_on_disk_under_a_value_cached_in_memory_is_supplied(tmp_path): + sim = single_person() + holder = sim.get_holder("trading_loss") + with under_memory_pressure(holder, tmp_path): + sim.set_input("trading_loss", 2025, [100.0]) + assert holder._disk_storage.has(period_(2025), "default") + assert not holder._memory_storage.has(period_(2025), "default") + + holder.put_in_cache(np.array([999.0]), period_(2025)) + + # The engine reads the cached value, but the input is still stored. + assert holder.get_array(period_(2025)).tolist() == [999.0] + population = holder.population + assert read(population, "trading_loss", 2025) == [100.0] + assert supplied_input_periods(population, "trading_loss") == [period_(2025)] + assert holder._stores_user_input(period_(2025), "default") + if hasattr(sim, "_get_recorded_input_array"): + assert recorded_input_array(sim, "trading_loss", 2025) == [100.0] + + +def test_a_value_cached_over_an_input_on_disk_is_not_supplied(tmp_path): + sim = single_person() + holder = sim.get_holder("trading_loss") + with under_memory_pressure(holder, tmp_path): + sim.set_input("trading_loss", 2025, [100.0]) + holder.put_in_cache(np.array([999.0]), period_(2025)) + assert holder._disk_storage.get(period_(2025)).tolist() == [999.0] + assert not holder._memory_storage.has(period_(2025), "default") + + population = holder.population + assert read(population, "trading_loss", 2025) is None + assert supplied_input_periods(population, "trading_loss") == [] + assert not holder._stores_user_input(period_(2025), "default") + + +def test_a_calculated_value_is_never_stored_over_an_input(tmp_path): + """policyengine-core stores a calculated (derived) value over nothing the + engine reads as an input, in memory or on disk.""" + sim = single_person() + holder = sim.get_holder("trading_loss") + sim.set_input("trading_loss", 2025, [100.0]) + with under_memory_pressure(holder, tmp_path): + sim.set_input("trading_loss", 2026, [200.0]) + holder.put_in_cache(np.array([999.0]), period_(2026), derived=True) + holder.put_in_cache(np.array([999.0]), period_(2025), derived=True) + holder.put_in_cache(np.array([999.0]), period_(2026), derived=True) + assert holder.get_array(period_(2025)).tolist() == [100.0] + assert holder.get_array(period_(2026)).tolist() == [200.0] + population = holder.population + assert read(population, "trading_loss", 2025) == [100.0] + assert read(population, "trading_loss", 2026) == [200.0] + + +def test_the_nearest_branch_still_storing_an_input_is_read(): + sim = single_person({"trading_loss": {2025: 100.0}}) + branch = sim.get_branch("reform") + population = branch.get_variable_population("trading_loss") + # The branch reads the input of the simulation it was made from. + assert read(population, "trading_loss", 2025) == [100.0] + + branch.set_input("trading_loss", 2025, [200.0]) + assert read(population, "trading_loss", 2025) == [200.0] + # The simulation the branch was made from does not see the branch's input. + assert read(sim.get_variable_population("trading_loss"), "trading_loss", 2025) == [ + 100.0 + ] + + holder = branch.get_holder("trading_loss") + holder.put_in_cache(np.array([999.0]), period_(2025), "reform") + # The branch's input is gone, so the input it was made from is read, as + # policyengine-core reads it. + assert read(population, "trading_loss", 2025) == [100.0] + assert supplied_input_periods(population, "trading_loss") == [period_(2025)] + if hasattr(branch, "_get_recorded_input_array"): + assert recorded_input_array(branch, "trading_loss", 2025) == [100.0] + + holder.put_in_cache(np.array([998.0]), period_(2025), "default") + assert read(population, "trading_loss", 2025) is None + assert supplied_input_periods(population, "trading_loss") == [] + + +class neutralize_trading_loss(Reform): + def apply(self): + self.neutralize_variable("trading_loss") + + +def test_a_neutralised_input_reads_as_its_default_only_while_it_is_stored(): + sim = single_person({"trading_loss": {2025: 100.0, 2026: 200.0}}) + sim.apply_reform(neutralize_trading_loss) + holder = sim.get_holder("trading_loss") + holder.put_in_cache(np.array([999.0]), period_(2026)) + population = holder.population + assert read(population, "trading_loss", 2025) == [0.0] + assert read(population, "trading_loss", 2026) is None + assert supplied_input_periods(population, "trading_loss") == [period_(2025)] + + +CALCULATED = [ + "household_net_income", + "income_tax", + "ni_class_4", + "ni_class_4_losses_carried_forward", + "ni_class_4_trading_loss", + "ni_class_4_losses_brought_forward", + "trading_loss", + "person_bus_fare_spending", + "bus_fare_spending", + "local_bus_trips", +] + + +def assert_supplied(sim, expected): + for variable in SUPPLIED_INPUT_VARIABLES: + population = sim.get_variable_population(variable) + stored = sorted( + (period for name, period in expected if name == variable), + key=lambda period: period.start, + ) + assert supplied_input_periods(population, variable) == stored, variable + for period in stored: + assert ( + supplied_input(population, variable, period).tolist() + == expected[variable, period] + ), (variable, period) + for variable, branch_name, period in sim._user_input_keys: + assert sim.get_holder(variable)._stores_user_input(period, branch_name) + + +def test_calculating_leaves_every_supplied_value_supplied(): + situation = { + "self_employment_income": {year: 30_000 for year in range(2024, 2028)}, + "employment_income": {year: 10_000 for year in range(2024, 2028)}, + } + sim = single_person(situation) + # The situation's registered inputs, then a value of every other + # registered variable for 2025 and 2026. + expected = { + (variable, period_(year)): [float(value)] + for variable, values in situation.items() + if variable in SUPPLIED_INPUT_VARIABLES + for year, value in values.items() + } + for year in (2025, 2026): + for number, variable in enumerate(sorted(SUPPLIED_INPUT_VARIABLES), 1): + if variable in situation: + continue + period = stored_period(sim, variable, year) + value = value_of_type(sim, variable, number + year) + sim.set_input(variable, period, value) + expected[variable, period] = value.tolist() + branch = sim.get_branch("reform") + branch.set_input("trading_loss", 2027, [123.0]) + branch_expected = {**expected, ("trading_loss", period_(2027)): [123.0]} + + for simulation in (sim, branch): + for year in (2024, 2025, 2026, 2027, 2028): + for variable in CALCULATED: + simulation.calculate(variable, year) + + assert_supplied(sim, expected) + assert_supplied(branch, branch_expected) + + +BRANCHES = ("child", "parent", "default") # nearest first +YEARS = (2024, 2025, 2026) +step = st.one_of( + # Set an input, on disk if under memory pressure. + st.tuples( + st.just("set"), st.sampled_from(BRANCHES), st.sampled_from(YEARS), st.booleans() + ), + # Cache a value, calculated (derived) or not, on disk if under pressure. + st.tuples( + st.just("cache"), + st.sampled_from(BRANCHES), + st.sampled_from(YEARS), + st.booleans(), + st.booleans(), + ), + st.tuples(st.just("delete"), st.sampled_from(BRANCHES), st.sampled_from(YEARS)), + st.tuples( + st.just("calculate"), + st.sampled_from(["trading_loss", "ni_class_4_losses_brought_forward"]), + st.sampled_from(YEARS + (2027,)), + ), +) + +_templates = [] + + +def branch_chain(): + """A branch ("child") of a branch ("parent") of a simulation.""" + if not _templates: + _templates.append(single_person()) + root = _templates[0].clone(clone_tax_benefit_system=False) + return root.get_branch("parent").get_branch("child") + + +def tier_holding(holder, period, branch_name, value): + """The tier that holds ``value`` for ``period`` on ``branch_name``.""" + for tier, storage in ( + ("memory", holder._memory_storage), + ("disk", holder._disk_storage), + ): + if ( + storage is not None + and storage.has(period, branch_name) + and storage.get(period, branch_name).tolist() == [value] + ): + return tier + return None + + +def expected_supplied(stored, year): + """Invariant 1: the input on the nearest branch, memory before disk.""" + for branch_name in BRANCHES: + for tier in ("memory", "disk"): + if (branch_name, year, tier) in stored: + return [stored[branch_name, year, tier]] + return None + + +@settings( + max_examples=100, + deadline=None, + derandomize=True, + suppress_health_check=[HealthCheck.too_slow], +) +@given(steps=st.lists(step, max_size=10)) +# A value cached over the input in the same tier (#2307). +@example(steps=[("set", "child", 2025, False), ("cache", "child", 2025, False, False)]) +# An input on disk under a value cached in memory. +@example(steps=[("set", "child", 2025, True), ("cache", "child", 2025, False, False)]) +# A value cached over the child's input leaves the parent's. +@example( + steps=[ + ("set", "parent", 2025, False), + ("set", "child", 2025, True), + ("cache", "child", 2025, False, True), + ] +) +# An input in memory over an earlier input on disk is read, as the engine +# reads it. +@example(steps=[("set", "child", 2025, True), ("set", "child", 2025, False)]) +# From policyengine-core 3.33, the first input drops the cached value, so it +# and the second input go to disk (found by Hypothesis). +@example( + steps=[ + ("cache", "child", 2024, False, False), + ("set", "child", 2024, True), + ("set", "child", 2024, True), + ] +) +def test_only_inputs_still_stored_are_supplied(tmp_path_factory, steps): + child = branch_chain() + holder = child.get_holder("trading_loss") + population = holder.population + folder = tmp_path_factory.mktemp("disk") + # The surviving inputs, by (branch, year, tier). + stored = {} + for index, (kind, *args) in enumerate(steps): + if kind in ("set", "cache"): + branch_name, year, *flags = args + pressure = flags[-1] + period = period_(year) + # Every value written is new, so the tier holding it shows where + # core stored it. (Under pressure, core stores on disk unless + # memory holds a value for the period; from 3.33, setting an input + # first drops cached values that may depend on it.) + value = (1.0 if kind == "set" else 10_000.0) + index + with under_memory_pressure(holder, folder) if pressure else nullcontext(): + if kind == "set": + holder.set_input(period, np.array([value]), branch_name) + else: + derived = flags[0] + holder.put_in_cache(np.array([value]), period, branch_name, derived) + tier = tier_holding(holder, period, branch_name, value) + if kind == "set": + assert tier is not None + stored[branch_name, year, tier] = value + elif tier is not None: + # A calculated value never replaces an input. + assert not (derived and (branch_name, year, tier) in stored) + stored.pop((branch_name, year, tier), None) + elif kind == "delete": + branch_name, year = args + holder.delete_arrays(period_(year), branch_name) + for tier in ("memory", "disk"): + stored.pop((branch_name, year, tier), None) + else: + variable, year = args + child.calculate(variable, year) + + supplied_years = [] + for year in YEARS: + expected = expected_supplied(stored, year) + assert read(population, "trading_loss", year) == expected, (year, stored) + if expected is not None: + supplied_years.append(year) + if hasattr(child, "_get_recorded_input_array"): + assert recorded_input_array(child, "trading_loss", year) == expected + # Invariant 2. + periods = supplied_input_periods(population, "trading_loss") + assert periods == [period_(year) for year in supplied_years] + if hasattr(child, "_get_set_input_periods"): + assert set(child._get_set_input_periods("trading_loss")) == set(periods) + # Invariant 3, for every recorded input of the variable. + for variable, branch_name, period in child._user_input_keys: + if variable == "trading_loss": + ours = stored_supplied_value(holder, period, branch_name) + assert (ours is not None) == holder._stores_user_input( + period, branch_name + ), (branch_name, period) diff --git a/policyengine_uk/utils/subsample.py b/policyengine_uk/utils/subsample.py new file mode 100644 index 0000000000..5e6afb49fa --- /dev/null +++ b/policyengine_uk/utils/subsample.py @@ -0,0 +1,547 @@ +"""Subsample a simulation built from a dataset. + +``Simulation.subsample`` keeps a weighted random sample of households and +gives the sample weights with the same totals as before. policyengine-core's +``subsample`` cannot do this for a UK simulation: + +- it rebuilds through ``Simulation.build_from_dataset()`` with no arguments, + and the UK builder takes the dataset to load; +- given that dataset, the UK builder still cannot load what core rebuilds + from: core's flat-file ``Dataset``, which ``Dataset.load_dataset`` does not + read. The UK builder would also rebuild every year from the first one, + projected forward, rather than keep each year's inputs; +- it reads each person's household and benefit unit back from the stored + ``person_household_id`` and ``person_benunit_id`` inputs, which need not + match the populations: ``set_input`` can store any value there, and the + model stores them as 32-bit integers, which change identifiers outside + that range; +- it rebuilds a ``baseline`` branch, while a UK simulation's baseline is a + simulation of its own. + +So the functions here take the households, benefit units and people from the +simulation's populations, whose identifiers and memberships are exact, and +subsample the baseline and the dataset with the same draw. +""" + +import copy +import hashlib +import operator +from dataclasses import dataclass +from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union + +import numpy as np +import pandas as pd +from policyengine_core.periods import Period, period as period_ +from policyengine_core.tracers import SimpleTracer + +try: + # How ``get_branch`` makes a clone that shares the cached arrays instead + # of copying them (policyengine-core 3.32.27 and later). See + # ``_copy_sharing_arrays``. + from policyengine_core.simulations.simulation import ( + _BranchClone, + _branch_clone, + ) +except ImportError: # pragma: no cover - a core without shared clones + _BranchClone = _branch_clone = None + +from policyengine_uk.data.dataset_schema import ( + UKMultiYearDataset, + UKSingleYearDataset, +) +from policyengine_uk.utils.supplied_inputs import ( + is_model_value, + set_model_value, + supplied_input_arrays, +) + +if TYPE_CHECKING: + from policyengine_uk.simulation import Simulation + +# Variables that count how many units of the population a record stands for. +# A subsample rescales each one that is supplied as an input, so that its +# total over its own entity is unchanged. Each is rescaled on its own, so a +# person weight supplied alongside household weights need not equal the new +# weight of the person's household, as the model's person_weight formula +# makes it; the datasets supply neither person_weight nor benunit_weight. +WEIGHT_VARIABLES = frozenset( + { + "household_weight", + "benunit_weight", + "person_weight", + "original_weight", + "raw_person_weight", + } +) + +# policyengine-core seeds a subsample with the dataset's name by default. UK +# datasets have no name, so every UK subsample without a seed uses this one. +DEFAULT_SEED = "policyengine-uk" + +UKDataset = Union[UKSingleYearDataset, UKMultiYearDataset] + +# What a simulation records about the data it was built from, which a rebuild +# of its populations resets and a subsample keeps. Each is about variables, +# periods or the dataset as a whole, not about records, so it holds for the +# sample: +# - where each capital gains input came from, by variable and period, and the +# periods a neutralised capital gains input read as its default; +# - the dataset's ISA income contract for each year, which sets how savings +# interest is represented and projected; +# - the series the dataset's savings income grows by. +DATASET_RECORDS = ( + "_cgt_input_provenance", + "_cgt_defaulted_periods", + "_isa_income_contracts", + "_savings_income_projection", +) + + +def _random_state(seed) -> np.random.RandomState: + """A generator for ``seed``, which may be a number or text. + + NumPy's compatibility guarantee keeps ``RandomState``'s results for a + fixed seed and calls the same, up to roundoff, so a seed chooses the same + households wherever it runs. The digest gives the same number in every + process, which the built-in ``hash`` does not. + """ + digest = hashlib.sha256(str(seed).encode("utf-8")).digest() + return np.random.RandomState(int.from_bytes(digest[:4], "big")) + + +def draw_household_counts( + weights: np.ndarray, n: int, seed, quantize_weights: bool = True +) -> np.ndarray: + """Draw ``n`` households with replacement and count each one's draws. + + Only households with a positive weight can be drawn. Each draw picks a + household with probability proportional to its weight, or with equal + probability when ``quantize_weights`` is false. + + Returns: + The number of times each household was drawn; the counts sum to ``n``. + """ + n = operator.index(n) + if n < 1: + raise ValueError(f"A subsample needs at least one household, not {n}.") + weights = np.asarray(weights, dtype=float) + if (weights < 0).any(): + raise ValueError("Household weights must not be negative to sample by them.") + eligible = np.flatnonzero(weights > 0) + if eligible.size == 0: + raise ValueError("No household has a positive weight to sample by.") + if not np.isfinite(weights[eligible]).all(): + raise ValueError("Household weights must be finite to sample by them.") + probabilities = ( + weights[eligible] / weights[eligible].sum() if quantize_weights else None + ) + draws = _random_state(seed).choice( + eligible.size, size=n, replace=True, p=probabilities + ) + counts = np.zeros(weights.size, dtype=np.int64) + counts[eligible] = np.bincount(draws, minlength=eligible.size) + return counts + + +def rescale_weights( + weights: np.ndarray, counts: np.ndarray, quantize_weights: bool = True +) -> np.ndarray: + """Weights for the drawn records that keep the total of ``weights``. + + A drawn record's new weight is proportional to the number of times its + household was drawn (``counts``), and also to its old weight when + ``quantize_weights`` is false. A record that was not drawn gets zero, and + so does a record whose weight is zero: it stands for no one, which a + subsample keeps. (A household drawn by its weight in one year can have a + zero weight in another, and a person or benefit unit weight can be zero.) + """ + weights = np.asarray(weights, dtype=float) + total = weights.sum() + if not np.isfinite(total): + raise ValueError("the weights do not have a finite total") + if (weights < 0).any(): + raise ValueError("the weights include negative values") + if total == 0: + return np.zeros_like(weights) + drawn = ( + (counts * (weights > 0)).astype(float) if quantize_weights else weights * counts + ) + drawn_total = drawn.sum() + if drawn_total == 0: + raise ValueError( + "the sampled records have no weight. Draw a different sample, or " + "sample by this period's weights" + ) + return drawn * (total / drawn_total) + + +def _rescaled(name: str, period, weights, counts, quantize_weights) -> np.ndarray: + try: + return rescale_weights(weights, counts, quantize_weights) + except ValueError as error: + raise ValueError( + f"Cannot preserve the total of {name} for {period}: {error}." + ) from error + + +def _subsample_table( + table: pd.DataFrame, counts: np.ndarray, period, quantize_weights: bool +) -> pd.DataFrame: + """The rows of ``table`` drawn at least once, with their new weights.""" + kept = counts > 0 + subsample = table.loc[kept].reset_index(drop=True) + for column in table.columns: + if column in WEIGHT_VARIABLES: + weights = _rescaled( + column, period, table[column].values, counts, quantize_weights + ) + subsample[column] = weights[kept] + return subsample + + +def _subsample_single_year_dataset( + dataset: UKSingleYearDataset, + household_ids: np.ndarray, + counts: np.ndarray, + quantize_weights: bool, +) -> UKSingleYearDataset: + # Read the stored tables, in which enum columns stay encoded; the public + # properties decode every enum column of the whole table. + person, benunit, household = dataset.tables + draws = pd.Series(counts, index=household_ids) + + def draws_of(households) -> np.ndarray: + return draws.reindex(np.asarray(households)).fillna(0).values + + # A benefit unit belongs to the household of its members. + benunit_household = person.groupby("person_benunit_id")[ + "person_household_id" + ].first() + tables = [ + _subsample_table(table, table_counts, dataset.time_period, quantize_weights) + for table, table_counts in ( + (person, draws_of(person["person_household_id"])), + ( + benunit, + draws_of(benunit_household.reindex(benunit["benunit_id"].values)), + ), + (household, draws_of(household["household_id"])), + ) + ] + # The year's declarations of how its amounts were measured and grow + # describe every row, so they hold for the sample. + subsample = UKSingleYearDataset( + person=tables[0], + benunit=tables[1], + household=tables[2], + fiscal_year=dataset.time_period, + energy_price_basis=dataset.energy_price_basis, + isa_income_contract=copy.deepcopy(dataset.isa_income_contract), + savings_income_projection=dataset.savings_income_projection, + ) + subsample._enum_columns = dict(dataset._enum_columns) + return subsample + + +def subsample_dataset( + dataset: UKDataset, + household_ids: np.ndarray, + counts: np.ndarray, + quantize_weights: bool = True, +) -> UKDataset: + """A copy of ``dataset`` holding the drawn households, for every year. + + Args: + dataset: The dataset to subsample. It is not changed. + household_ids: The identifier of each household that could be drawn. + counts: The number of times each of those households was drawn. + quantize_weights: As for ``Simulation.subsample``. + """ + if isinstance(dataset, UKMultiYearDataset): + subsample = UKMultiYearDataset( + datasets=[ + _subsample_single_year_dataset( + dataset[year], household_ids, counts, quantize_weights + ) + for year in dataset.years + ] + ) + # Which capital gains inputs the loader projected, by variable and + # year, which a simulation built from the dataset reports. + if hasattr(dataset, "_cgt_extension_provenance"): + subsample._cgt_extension_provenance = copy.deepcopy( + dataset._cgt_extension_provenance + ) + return subsample + return _subsample_single_year_dataset( + dataset, household_ids, counts, quantize_weights + ) + + +@dataclass +class _Subsample: + """What one simulation holds once it is subsampled.""" + + simulation: "Simulation" + # The arguments of Simulation.build_from_ids. + ids: Tuple[np.ndarray, ...] + # Each supplied input, cut down to the sample, and whether it is the + # model's own value (set_model_value) rather than a supplied one. + inputs: List[Tuple[str, Period, np.ndarray, bool]] + dataset: Optional[UKDataset] + # The values of DATASET_RECORDS the simulation holds. + records: Dict[str, object] + + +def _sorted_positions(kept: np.ndarray, ids: np.ndarray) -> np.ndarray: + """Positions of the kept members of a group population, ordered by + identifier, which is the order ``Simulation.build_from_ids`` gives them.""" + positions = np.flatnonzero(kept) + return positions[np.argsort(ids[positions], kind="stable")] + + +def _plan( + simulation: "Simulation", + household_ids: np.ndarray, + counts: np.ndarray, + quantize_weights: bool, + datasets: Dict[int, UKDataset], +) -> _Subsample: + """Work out the subsample of ``simulation`` without changing it.""" + person = simulation.populations["person"] + benunit = simulation.populations["benunit"] + household = simulation.populations["household"] + if not np.array_equal(np.asarray(household.ids), household_ids): + raise ValueError( + "A simulation and its baseline must hold the same households to " + "be subsampled together." + ) + person_household = np.asarray(household.members_entity_id) + person_benunit = np.asarray(benunit.members_entity_id) + + # A benefit unit is kept with its household, so it must sit within one. + benunit_household = np.full(benunit.count, -1) + benunit_household[person_benunit] = person_household + if not np.array_equal(benunit_household[person_benunit], person_household): + raise ValueError( + "Cannot subsample: a benefit unit has members in more than one household." + ) + members = np.bincount(person_household, minlength=household.count) + if (members[counts > 0] == 0).any(): + raise ValueError("Cannot subsample: a sampled household has no members.") + + entity_counts = { + "person": counts[person_household], + "benunit": np.where(benunit_household >= 0, counts[benunit_household], 0), + "household": counts, + } + positions = { + "person": np.flatnonzero(entity_counts["person"] > 0), + "benunit": _sorted_positions( + entity_counts["benunit"] > 0, np.asarray(benunit.ids) + ), + "household": _sorted_positions(counts > 0, household_ids), + } + + inputs = [] + for name, period, values in supplied_input_arrays(simulation): + entity_key = simulation.tax_benefit_system.get_variable(name).entity.key + model = is_model_value(simulation, name, period, values) + if name in WEIGHT_VARIABLES: + values = _rescaled( + name, period, values, entity_counts[entity_key], quantize_weights + ) + inputs.append((name, period, values[positions[entity_key]], model)) + + # A simulation and its baseline usually share one dataset object, so + # subsample each dataset once and share the result in the same way. + dataset = simulation.dataset + if dataset is not None: + if id(dataset) not in datasets: + datasets[id(dataset)] = subsample_dataset( + dataset, household_ids, counts, quantize_weights + ) + dataset = datasets[id(dataset)] + + kept_people = positions["person"] + return _Subsample( + simulation=simulation, + ids=( + np.asarray(person.ids)[kept_people], + np.asarray(benunit.ids)[person_benunit[kept_people]], + household_ids[person_household[kept_people]], + np.asarray(benunit.ids)[positions["benunit"]], + household_ids[positions["household"]], + ), + inputs=inputs, + dataset=dataset, + records={ + name: copy.deepcopy(getattr(simulation, name)) + for name in DATASET_RECORDS + if hasattr(simulation, name) + }, + ) + + +def _apply( + subsample: _Subsample, simulation: "Simulation", tracer: SimpleTracer +) -> None: + """Rebuild ``simulation`` on ``subsample``, which was worked out for it + or for the simulation it is a copy of.""" + start_instant = simulation.start_instant + # Branches hold the populations the subsample replaces; formulas make + # them again when they next ask for them. + simulation.branches = {} + # The rebuild replaces every stored value, so the record of inputs, and + # of what was calculated from them, starts again with the inputs it sets. + simulation._user_input_keys = set() + simulation._store_history = None + # A trace of calculations on the replaced populations would otherwise be + # reported for the sample: a flat trace keeps a variable's first value. + simulation.tracer = tracer + simulation.build_from_ids(*subsample.ids) + for name, period, values, model in subsample.inputs: + holder = simulation.get_holder(name) + if holder.variable.is_neutralized: + # These are canonical stored inputs, not new inputs. set_input + # rejects them while neutralised, but they must survive so the + # input record and a later restoration still see them. + holder._set(period, values, simulation.branch_name, is_input=True) + if model: + simulation._model_values[(name, simulation.branch_name, period)] = ( + np.array(values) + ) + elif model: + # Keep it the model's: formulas that ask whether a value was + # supplied would otherwise read it as the user's. + set_model_value(simulation, name, period, values) + else: + simulation.set_input(name, period, values) + # The rebuild reset what the simulation recorded about its data, and + # recorded each capital gains input as supplied; restore them. + for name, value in subsample.records.items(): + setattr(simulation, name, copy.deepcopy(value)) + simulation.start_instant = start_instant + # Drop results calculated on the populations the subsample replaced. + simulation._invalidate_all_caches() + simulation.dataset = subsample.dataset + + +def _copy_sharing_arrays(simulation: "Simulation") -> "Simulation": + """A clone of ``simulation`` that shares its cached arrays. + + ``clone`` copies every cached array, and the subsample discards them all + at once, so for a full-size baseline that doubles its memory for nothing. + Announce the clone as ``get_branch`` does: the copy then reads views of + the arrays and copies one only if it reads it, which it never does. The + simulation is not changed; with a core that cannot share, the arrays are + copied. + """ + if _branch_clone is None: # pragma: no cover - a core without shared clones + return simulation.clone(debug=simulation.debug, trace=simulation.trace) + request = _BranchClone(simulation) + token = _branch_clone.set(request) + try: + return simulation.clone(debug=simulation.debug, trace=simulation.trace) + finally: + request.pending = False + _branch_clone.reset(token) + + +def _sampling_weights(simulation: "Simulation", time_period) -> np.ndarray: + """Household weights for ``time_period``, to draw the sample by. + + A period before the first supplied weights has none: the model would + return the default weight of one for every household. Use the first + supplied weights for such a period. + """ + periods = sorted( + ( + period + for name, period, _ in supplied_input_arrays(simulation) + if name == "household_weight" + ), + key=lambda period: period.start, + ) + if not periods: + raise ValueError( + "Cannot subsample a simulation that was given no household_weight values." + ) + requested = period_(time_period) + if requested.start < periods[0].start: + requested = periods[0] + return np.asarray(simulation.calculate("household_weight", requested)) + + +def subsample_simulation( + simulation: "Simulation", + n: Optional[int] = None, + frac: Optional[float] = None, + seed=None, + time_period=None, + quantize_weights: bool = True, +) -> "Simulation": + """Subsample ``simulation`` in place; see ``Simulation.subsample``.""" + if not simulation.built_from_dataset: + raise ValueError("Only a simulation built from a dataset can be subsampled.") + if simulation.branch_name != "default": + raise ValueError("Subsample a simulation, not one of its branches.") + if n is None and frac is None: + raise ValueError("Either n or frac must be provided.") + if time_period is None: + time_period = simulation.default_calculation_period + + weights = _sampling_weights(simulation, time_period) + if n is None: + n = int(len(weights) * frac) + counts = draw_household_counts( + weights, n, DEFAULT_SEED if seed is None else seed, quantize_weights + ) + + # The baseline is a simulation of its own, with a baseline of its own + # when this one has a scenario. Give each of them the same households. + simulations = [] + while simulation is not None and simulation not in simulations: + simulations.append(simulation) + simulation = getattr(simulation, "baseline", None) + + # Work out every subsample before changing anything, so that a + # simulation that cannot be subsampled leaves them all as they were. + household_ids = np.asarray(simulations[0].populations["household"].ids) + datasets: Dict[int, UKDataset] = {} + subsamples = [ + _plan(each, household_ids, counts, quantize_weights, datasets) + for each in simulations + ] + + # Each simulation gets a new tracer of the same kind. Simulations that + # shared a tracer share the new one. The old tracer is kept with its + # replacement so that its id is not reused while this runs. + tracers: Dict[int, Tuple[SimpleTracer, SimpleTracer]] = {} + + def new_tracer(old: SimpleTracer) -> SimpleTracer: + if id(old) not in tracers: + tracers[id(old)] = (old, type(old)()) + return tracers[id(old)][1] + + first = simulations[0] + _apply(subsamples[0], first, new_tracer(first.tracer)) + + # Replace each baseline with a subsampled copy rather than subsample it + # in place: policyengine-core's ``clone`` shares a separate baseline, so + # another simulation can hold this one and still hold every household. + # The copy shares the baseline's arrays rather than copying them, so it + # costs little memory; the old baselines stay in memory until nothing + # holds them. + copies = {id(first): first} + for subsample in subsamples[1:]: + baseline = subsample.simulation + copy = _copy_sharing_arrays(baseline) + _apply(subsample, copy, new_tracer(baseline.tracer)) + copies[id(baseline)] = copy + for each in simulations: + holder = copies[id(each)] + baseline = getattr(holder, "baseline", None) + if baseline is not None and id(baseline) in copies: + holder.baseline = copies[id(baseline)] + return first diff --git a/policyengine_uk/utils/supplied_inputs.py b/policyengine_uk/utils/supplied_inputs.py index d8a01bb8c8..8b96946f60 100644 --- a/policyengine_uk/utils/supplied_inputs.py +++ b/policyengine_uk/utils/supplied_inputs.py @@ -7,8 +7,17 @@ (variable, branch, period) that ``set_input`` stores in ``Simulation._user_input_keys``. From 3.32.27 (policyengine-core#561), core forgets the record of an input that ``Holder.delete_arrays`` deletes, and each -clone gets its own copy of the record. The helpers also require a stored -value, so missing arrays do not count as supplied inputs. +clone gets its own copy of the record. + +The record can still outlive the value it names. A value cached over an input +takes that storage tier (memory or disk) off the holder's record of where the +input is (``Holder._user_input_storage``), but leaves the entry in +``_user_input_keys``. So every helper here reads a supplied value only if it is +still stored, and only from a tier in which ``Holder._stores_user_input`` +finds the input: one that the holder records the input in and that holds a +value the engine did not calculate (see ``stored_supplied_value``). A missing +value, or one carried over, calculated or cached into the same tier, is not +supplied; an input stored on disk under a value cached in memory still is. ``Simulation.build_from_populations`` installs new populations, and so new holders, but core keeps the record of the values they replace @@ -31,9 +40,12 @@ it), when ``delete_arrays`` removes it, and when a rebuild installs populations that do not hold it, and a clone or branch gets its own copy of the record. + +``supplied_input_arrays`` answers for every variable. It includes values +``set_model_value`` stored, which ``is_model_value`` tells apart. """ -from typing import List, Optional +from typing import List, Optional, Tuple import numpy as np from policyengine_core import periods @@ -136,7 +148,9 @@ def drop_missing_supplied_inputs(simulation, variable_name: str) -> None: def supplied_input_periods(population, variable_name: str) -> List[Period]: """Periods for which ``variable_name`` was supplied as an input, on this - branch or one it was made from, earliest first.""" + branch or one it was made from, and the supplied value is still stored, + earliest first. A period whose input a value carried over, calculated or + cached in its place has replaced is left out.""" _check_registered(variable_name) simulation = population.simulation branch_names = set(_visible_branch_names(simulation)) @@ -148,11 +162,10 @@ def supplied_input_periods(population, variable_name: str) -> List[Period]: for name, branch_name, period in input_keys if name == variable_name and branch_name in branch_names - and holder._get_array_from_storage(period, branch_name) is not None - and not _is_model_value( - simulation, - (name, branch_name, period), - holder._get_array_from_storage(period, branch_name), + # Checked without reading the value, which may be on disk, unless + # the model stored a value for the period (set_model_value). + and _supplied_without_reading( + simulation, holder, (name, branch_name, period) ) }, key=lambda period: period.start, @@ -208,9 +221,10 @@ def supplied_input( population, variable_name: str, period: Period ) -> Optional[np.ndarray]: """The value of ``variable_name`` for ``period`` if it was supplied as an - input, on this branch or the nearest one it was made from; otherwise - None. A value the engine carried over from an earlier period, or cached - after a calculation, is not an input.""" + input, on this branch or the nearest one it was made from, and is still + stored; otherwise None. A value the engine carried over from an earlier + period, or cached after a calculation, is not an input, including one + cached over the input.""" _check_registered(variable_name) simulation = population.simulation input_keys = getattr(simulation, "_user_input_keys", None) or () @@ -218,10 +232,12 @@ def supplied_input( for branch_name in _visible_branch_names(simulation): if (variable_name, branch_name, period) in input_keys: # Read the stored input itself: Holder.get_array would fall back - # to other branches' values, including cached calculations. - # A record can outlive its stored array (see above); a missing - # stored array must be ignored even if its key remains. - value = holder._get_array_from_storage(period, branch_name) + # to other branches' values, including cached calculations, and + # reads memory before disk whatever each holds. A record can + # outlive its input (see above); then look on the branch this one + # was made from, as policyengine-core's + # Simulation._get_recorded_input_array does. + value = stored_supplied_value(holder, period, branch_name) if value is not None: # A value the model stored itself (set_model_value) is not # supplied, though the engine keeps it like an input. @@ -240,12 +256,84 @@ def supplied_input( return None +def supplied_input_arrays(simulation) -> List[Tuple[str, Period, np.ndarray]]: + """Every value ``simulation`` was given as an input and still stores, on + its own branch, with its variable and the period it is stored for. + + Ordered by variable and period, so that the same simulation always gives + the same list. + """ + input_keys = getattr(simulation, "_user_input_keys", None) or () + arrays = [] + for variable_name, branch_name, period in input_keys: + if branch_name != simulation.branch_name: + continue + value = stored_supplied_value( + simulation.get_holder(variable_name), period, branch_name + ) + if value is not None: + arrays.append((variable_name, period, value)) + return sorted(arrays, key=lambda item: (item[0], item[1].start, str(item[1]))) + + +def stored_supplied_value(holder, period: Period, branch_name: str): + """The supplied value ``holder`` still stores for ``period``, or None. + + A record can outlive its stored value (see above), and a value calculated + later can take its place in one tier while the input survives in the + other. So read only a tier in which ``Holder._stores_user_input`` finds + the input: one that the holder records the input in (either tier when it + records none) and that holds a value it did not calculate, memory first. + Reading memory before disk regardless could return a value cached over an + input stored on disk. + """ + storage = _supplied_value_storage(holder, period, branch_name) + return None if storage is None else storage.get(period, branch_name) + + +def _supplied_value_storage(holder, period: Period, branch_name: str): + """The storage (memory or disk) from which ``stored_supplied_value`` + reads, or None if the supplied value is gone.""" + for location, storage in ( + ("memory", holder._memory_storage), + ("disk", holder._disk_storage), + ): + if storage is not None and holder._stores_user_input( + period, branch_name, location + ): + return storage + return None + + +def _supplied_without_reading(simulation, holder, key) -> bool: + """Whether ``supplied_input`` finds a supplied value for ``key`` on its + own branch. Reads the value only if the model stored one for the period + (``set_model_value``), to tell the two apart.""" + _, branch_name, period = key + storage = _supplied_value_storage(holder, period, branch_name) + if storage is None: + return False + model_values = getattr(simulation, "_model_values", None) or {} + if key not in model_values: + return True + return not _is_model_value(simulation, key, storage.get(period, branch_name)) + + def _is_model_value(simulation, key, value) -> bool: model_values = getattr(simulation, "_model_values", None) or {} written = model_values.get(key) return written is not None and np.array_equal(written, value) +def is_model_value(simulation, variable_name: str, period: Period, value) -> bool: + """Whether ``value``, stored for ``variable_name`` and ``period`` on this + simulation's branch, is the model's own value (``set_model_value``) + rather than a supplied one.""" + return _is_model_value( + simulation, (variable_name, simulation.branch_name, period), value + ) + + def set_model_value(simulation, variable_name: str, period, value) -> None: """Store ``value`` for ``variable_name`` and ``period`` with ``set_input``, as the model's own value rather than a supplied one, unless the period's