From dc5f7e82d3ca0c78610475639f2f958719c64ee7 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 18 Oct 2026 14:37:15 -0400 Subject: [PATCH 1/4] Keep loaded roles and IDs through subsample without backing variables subsample rebuilds the simulation from a person-level frame of recorded inputs plus the structural leaves retain_structure adds. retain_structure skipped any leaf the tax-benefit system had no variable for, so a system without person__role rebuilt every member with the default role (silently on master; as a capacity error once #595 lands), and a system without person_id or person__id variables failed to subsample. retain_structure now carries person IDs, memberships and role keys whether or not a variable backs them. An integer role variable cannot hold "no role", so subsample raises before changing anything instead of writing role index 0. The loader records the columns it reads for structure and no longer reports them as ignored. Found in review P3-1 on #595. Co-Authored-By: Claude Opus 5.5 --- changelog.d/subsample-preserve-roles.fixed.md | 1 + policyengine_core/simulations/simulation.py | 58 +++- tests/core/test_subsample_explicit_roles.py | 266 ++++++++++++++++++ tests/fixtures/subsample_roles.py | 159 +++++++++++ 4 files changed, 470 insertions(+), 14 deletions(-) create mode 100644 changelog.d/subsample-preserve-roles.fixed.md create mode 100644 tests/core/test_subsample_explicit_roles.py create mode 100644 tests/fixtures/subsample_roles.py diff --git a/changelog.d/subsample-preserve-roles.fixed.md b/changelog.d/subsample-preserve-roles.fixed.md new file mode 100644 index 000000000..bc846b91b --- /dev/null +++ b/changelog.d/subsample-preserve-roles.fixed.md @@ -0,0 +1 @@ +`Simulation.subsample` now keeps each member's loaded role (and person and membership IDs) when the tax-benefit system has no variable for them, instead of rebuilding everyone with the default role, and the dataset loader no longer reports the structural columns it reads as ignored. diff --git a/policyengine_core/simulations/simulation.py b/policyengine_core/simulations/simulation.py index ddda2ab94..676136b1e 100644 --- a/policyengine_core/simulations/simulation.py +++ b/policyengine_core/simulations/simulation.py @@ -1101,8 +1101,12 @@ def build_from_dataset(self) -> None: person_entity = self.tax_benefit_system.person_entity entity_id_field = f"{person_entity.key}_id" + # Columns read to build the populations are used even when no + # variable has their name, so they are not reported as ignored. + structural_columns = set() def get_eternity_array(name): + structural_columns.add(name) if self.dataset.data_format == Dataset.FLAT_FILE: # Look for any column with variablename__timeperiod for col in data: @@ -1187,7 +1191,7 @@ def get_eternity_array(name): self.set_input( variable, self.dataset.time_period, data[variable] ) - else: + elif variable not in structural_columns: unknown_columns.append(variable) else: for variable in data: @@ -1198,7 +1202,8 @@ def get_eternity_array(name): time_period = self.dataset.time_period or self.default_input_period if variable_name not in self.tax_benefit_system.variables: - unknown_columns.append(variable) + if variable_name not in structural_columns: + unknown_columns.append(variable) continue variable_meta = self.tax_benefit_system.get_variable(variable_name) @@ -3375,6 +3380,11 @@ def subsample( If structural inputs are absent, loaded population IDs, memberships and roles supply the leaves needed to rebuild the same partition. This also supports structural variables whose IDs have formulas. + These leaves are carried whether or not the system defines a variable + for them, and roles are carried by key, so every kept member keeps + the role it was loaded with instead of the default role. An integer + role variable cannot represent a member with no role; subsampling + raises ``ValueError`` before changing anything in that case. Args: n (int, optional): The number of households to sample. Defaults to 10_000. @@ -3404,12 +3414,15 @@ def subsample( df = self._to_person_dataframe(self._get_set_input_periods) def retain_structure(name, values): - variable = self.tax_benefit_system.get_variable(name) - if variable is None or any(column.split("__")[0] == name for column in df): + if any(column.split("__")[0] == name for column in df): return + # The loader reads structural columns by name, so a leaf that no + # variable backs (a role column the system does not define, for + # instance) is still carried. It has no period of its own. + variable = self.tax_benefit_system.get_variable(name) structural_period = ( ETERNITY - if variable.definition_period == ETERNITY + if variable is None or variable.definition_period == ETERNITY else periods.period(self.dataset.time_period).start.period( variable.definition_period ) @@ -3427,18 +3440,35 @@ def retain_structure(name, values): population.ids[population.members_entity_id], ) role_name = f"{person_key}_{entity.key}_role" + if any(column.split("__")[0] == role_name for column in df): + continue + # Carry each member's own role by key; the rebuild otherwise + # gives everyone the default. Members the loader matched to no + # role hold 0, and an empty key reloads them the same way. role_variable = self.tax_benefit_system.get_variable(role_name) - roles = np.broadcast_to(population.members_role, self.persons.count) + roles = np.broadcast_to( + np.asarray(population.members_role, dtype=object), + self.persons.count, + ) + role_keys = [getattr(role, "key", "") for role in roles] if role_variable is not None and role_variable.value_type == int: - role_values = [ - entity.flattened_roles.index(role) - if role in entity.flattened_roles - else 0 - for role in roles - ] + # An integer role column indexes flattened roles, so it has + # no value for "no role". Stop before anything is replaced. + index_of = { + role.key: index for index, role in enumerate(entity.flattened_roles) + } + unindexed = sorted({key for key in role_keys if key not in index_of}) + if unindexed: + raise ValueError( + f"Cannot subsample: {role_name} is an integer role " + f"variable, so it can only hold the {entity.key} roles " + f"{[role.key for role in entity.flattened_roles]}, but " + "some members hold " + f"{[key or '(no role)' for key in unindexed]}." + ) + retain_structure(role_name, [index_of[key] for key in role_keys]) else: - role_values = [getattr(role, "key", "") for role in roles] - retain_structure(role_name, role_values) + retain_structure(role_name, role_keys) # Flat-file loading can infer households from membership IDs even # when the household ID variable has a formula. Use the same leaves diff --git a/tests/core/test_subsample_explicit_roles.py b/tests/core/test_subsample_explicit_roles.py new file mode 100644 index 000000000..a49230b41 --- /dev/null +++ b/tests/core/test_subsample_explicit_roles.py @@ -0,0 +1,266 @@ +"""``subsample`` keeps the roles members were loaded with. + +The rebuild reads each member's role from a ``person__role`` column. +That column used to be carried only when the system defined a variable of +that name, so a system without one rebuilt every member with the default +role: silently on master, and as a capacity error once implicit defaults +are capacity-checked (review P3-1 on PolicyEngine/policyengine-core#595). +Person and membership IDs had the same gap. +""" + +import logging + +import pandas as pd +import pytest + +from policyengine_core.data import Dataset +from policyengine_core.periods import ETERNITY +from tests.fixtures.subsample_roles import ( + DATASET_YEAR, + NO_ROLE, + ROLE, + households_by_members, + load, + load_dataframe, + role_counts, + role_keys, + role_system, + roles_by_person, + source_households, + source_roles, +) + +HOUSEHOLDS = [ + ["first_parent", "second_parent", "child", "child"], + ["first_parent", "child"], + ["first_parent", "lodger"], + ["second_parent", "first_parent", "child", "parent"], + ["child"], +] +# Shuffled so that a household's members are not adjacent rows. +ORDER = [7, 0, 12, 3, 9, 1, 5, 10, 2, 8, 11, 4, 6] +UNKNOWN_COLUMN_WARNING = "do not match any variable" + + +def assert_roles_kept(simulation, households): + """Every kept household is a whole source household with its roles.""" + source = source_households(households) + kept = households_by_members(simulation) + assert kept, "subsample kept no household" + for members, roles in kept.items(): + assert members in source, f"{sorted(members)} is not a source household" + assert roles == source[members] + expected = source_roles(households) + assert roles_by_person(simulation) == { + person: expected[person] for person in simulation.persons.ids.tolist() + } + # The projector counts the same roles the members hold. + household_order = [ + frozenset( + simulation.persons.ids[ + simulation.household.members_entity_id == index + ].tolist() + ) + for index in range(simulation.household.count) + ] + for key, counts in role_counts(simulation).items(): + assert counts == [kept[members][key] for members in household_order] + + +def test_review_reproduction_keeps_explicit_roles(): + """The reviewed case: no role variable and a bounded default role.""" + data = pd.DataFrame( + { + f"person_id__{DATASET_YEAR}": [0, 1, 2, 3], + f"person_household_id__{DATASET_YEAR}": [0, 0, 0, 1], + f"{ROLE}__{DATASET_YEAR}": [ + "first_parent", + "child", + "child", + "first_parent", + ], + f"household_weight__{DATASET_YEAR}": [1.0, 1.0, 1.0, 1.0], + } + ) + simulation = load_dataframe(data, default_role="first_parent") + assert role_counts(simulation) == { + "first_parent": [1, 1], + "second_parent": [0, 0], + "child": [2, 0], + } + + simulation.subsample(n=2, seed=0) + + # Master rebuilt everyone as first_parent: first_parent [3, 1], child [0, 0]. + assert simulation.household.count == 2 + assert role_counts(simulation) == { + "first_parent": [1, 1], + "second_parent": [0, 0], + "child": [2, 0], + } + assert roles_by_person(simulation) == { + 0: "first_parent", + 1: "child", + 2: "child", + 3: "first_parent", + } + + +@pytest.mark.parametrize("role_variable", ["absent", "string"]) +@pytest.mark.parametrize("role_column", [ROLE, "role"]) +@pytest.mark.parametrize("default_role", ["first_parent", "child", "parent", None]) +def test_explicit_roles_survive_subsample(role_variable, role_column, default_role): + simulation = load( + HOUSEHOLDS, + role_variable=role_variable, + role_column=role_column, + default_role=default_role, + order=ORDER, + ) + assert_roles_kept(simulation, HOUSEHOLDS) + assert simulation.household.count == len(HOUSEHOLDS) + + simulation.subsample(n=8, seed="roles", time_period=DATASET_YEAR) + + assert simulation.household.count >= 2 + assert_roles_kept(simulation, HOUSEHOLDS) + + +def test_roles_survive_repeated_subsamples(): + simulation = load(HOUSEHOLDS, order=ORDER, default_role="child") + for n, seed in [(8, "first"), (3, "second"), (2, "third")]: + simulation.subsample(n=n, seed=seed, time_period=DATASET_YEAR) + assert_roles_kept(simulation, HOUSEHOLDS) + + +def test_rebuilt_dataset_carries_role_keys(): + simulation = load(HOUSEHOLDS, order=ORDER) + simulation.subsample(n=8, seed="roles", time_period=DATASET_YEAR) + + data = simulation.dataset.load() + [role_column] = [column for column in data if column.split("__")[0] == ROLE] + [id_column] = [column for column in data if column.split("__")[0] == "person_id"] + assert role_column == f"{ROLE}__{ETERNITY}" + expected = source_roles(HOUSEHOLDS) + people = data[id_column].tolist() + assert dict(zip(people, data[role_column].tolist())) == { + person: expected[person] for person in people + } + + +@pytest.mark.parametrize("missing", ["person_id", "person_household_id"]) +def test_structural_ids_without_variables_survive_subsample(missing): + """Master raised: ``KeyError`` mid-rebuild, or ``IndexError``.""" + system = role_system("absent") + del system.variables[missing] + simulation = load(HOUSEHOLDS, order=ORDER, system=system) + source_ids = sorted(simulation.persons.ids.tolist()) + + simulation.subsample(n=8, seed="roles", time_period=DATASET_YEAR) + + assert set(simulation.persons.ids.tolist()) <= set(source_ids) + assert_roles_kept(simulation, HOUSEHOLDS) + + +@pytest.mark.parametrize("unmatched", ["lodger", "parent"]) +def test_integer_role_variable_rejects_roleless_members_before_changing_anything( + unmatched, +): + """An integer role column cannot say "no role"; master wrote role 0.""" + households = [["first_parent", "child"], ["first_parent", unmatched]] + simulation = load(households, role_variable="integer", role_column="role") + dataset = simulation.dataset + persons = simulation.persons.ids.tolist() + roles = role_keys(simulation).tolist() + weights = simulation.calculate("household_weight", DATASET_YEAR).tolist() + + with pytest.raises(ValueError, match="integer role variable.*no role"): + simulation.subsample(n=2, seed="roles", time_period=DATASET_YEAR) + + assert simulation.dataset is dataset + assert simulation.persons.ids.tolist() == persons + assert role_keys(simulation).tolist() == roles + assert simulation.calculate("household_weight", DATASET_YEAR).tolist() == weights + + +def test_integer_role_variable_carries_flattened_roles(): + households = [["first_parent", "second_parent", "child"], ["child", "first_parent"]] + simulation = load(households, role_variable="integer", role_column="role") + + simulation.subsample(n=4, seed="roles", time_period=DATASET_YEAR) + + assert_roles_kept(simulation, households) + + +def unknown_column_warnings(caplog): + return [ + record.getMessage() + for record in caplog.records + if UNKNOWN_COLUMN_WARNING in record.getMessage() + ] + + +@pytest.mark.parametrize("role_column", [ROLE, "role"]) +def test_structural_columns_are_not_reported_as_ignored(caplog, role_column): + """The loader reads these columns, though no variable has their name.""" + system = role_system("absent") + del system.variables["person_household_id"] + with caplog.at_level(logging.WARNING): + simulation = load(HOUSEHOLDS, role_column=role_column, system=system) + + assert unknown_column_warnings(caplog) == [] + assert_roles_kept(simulation, HOUSEHOLDS) + + +@pytest.mark.parametrize("role_column", [ROLE, "role", None]) +def test_carried_role_columns_are_not_reported_as_ignored(caplog, role_column): + """Like a system with no role variables (policyengine-us, for instance), + whose subsample now carries a role column per group entity.""" + households = HOUSEHOLDS if role_column else [["child"] * 3, ["child"], ["child"]] + simulation = load(households, role_column=role_column, default_role="child") + caplog.clear() + with caplog.at_level(logging.WARNING): + simulation.subsample(n=8, seed="roles", time_period=DATASET_YEAR) + + assert unknown_column_warnings(caplog) == [] + assert_roles_kept(simulation, households) + + +def test_unknown_columns_are_still_reported_beside_structural_ones(caplog): + data = load(HOUSEHOLDS).dataset.load() + data[f"a_removed_input__{DATASET_YEAR}"] = 1.0 + with caplog.at_level(logging.WARNING): + load_dataframe(data) + + [warning] = unknown_column_warnings(caplog) + assert "1 column(s)" in warning + assert f"a_removed_input__{DATASET_YEAR}" in warning + assert ROLE not in warning + + +def test_time_period_array_role_column_is_used_and_not_reported(caplog): + frame = load(HOUSEHOLDS).dataset.load() + data = {column.split("__")[0]: {ETERNITY: frame[column].values} for column in frame} + data["household_id"] = {ETERNITY: [10, 20, 30, 40, 50]} + data["household_weight"] = {DATASET_YEAR: [1.0, 2.0, 3.0, 4.0, 5.0]} + dataset = type( + "RoleArrays", + (Dataset,), + { + "name": "role_arrays", + "label": "Role arrays", + "data_format": Dataset.TIME_PERIOD_ARRAYS, + "file_path": "dataframe", + "time_period": DATASET_YEAR, + "load": lambda self: data, + }, + )() + simulation_class = type(load(HOUSEHOLDS)) + with caplog.at_level(logging.WARNING): + simulation = simulation_class( + tax_benefit_system=role_system("absent"), dataset=dataset + ) + + assert unknown_column_warnings(caplog) == [] + assert_roles_kept(simulation, HOUSEHOLDS) + assert NO_ROLE in role_keys(simulation).tolist() diff --git a/tests/fixtures/subsample_roles.py b/tests/fixtures/subsample_roles.py new file mode 100644 index 000000000..8e6c9471b --- /dev/null +++ b/tests/fixtures/subsample_roles.py @@ -0,0 +1,159 @@ +"""Flat-file households with explicit roles, for testing what ``subsample`` keeps. + +Shared by ``tests/core/test_subsample_explicit_roles.py`` and its Hypothesis +property module, which pytest must be able to skip on its own when +Hypothesis is not installed. + +Households are written as tables of role keys, and the expected role of each +person is read from that table, never from the loader: a key that names a +flattened household role (``first_parent``, ``second_parent``, ``child``) is +that role, and any other key (``parent``, ``lodger``) is no role. +""" + +from collections import Counter + +import numpy as np +import pandas as pd + +from policyengine_core.country_template import CountryTaxBenefitSystem, Simulation +from policyengine_core.country_template.entities import Person +from policyengine_core.data import Dataset +from policyengine_core.periods import ETERNITY +from policyengine_core.variables import Variable + +DATASET_YEAR = "2024" +ROLE = "person_household_role" +FLATTENED_KEYS = ("first_parent", "second_parent", "child") +# How these helpers report a member the loader gave no role. +NO_ROLE = "" + + +class integer_role(Variable): + value_type = int + entity = Person + definition_period = ETERNITY + label = "Integer person household role" + + def formula(person, period): + return person.filled_array(2) + + +integer_role.__name__ = ROLE + + +def role_system(role_variable: str = "absent") -> CountryTaxBenefitSystem: + """The template system with its household role variable ``absent``, + as shipped (``string``), or replaced by an ``integer`` formula.""" + system = CountryTaxBenefitSystem() + if role_variable == "absent": + del system.variables[ROLE] + elif role_variable == "integer": + system.replace_variable(integer_role) + else: + assert role_variable == "string" + return system + + +def expected_role(key: str) -> str: + return key if key in FLATTENED_KEYS else NO_ROLE + + +def dataframe(households, role_column=ROLE, order=None, weights=None): + """One row per person: person ``i`` has ID ``100 + i``, household ``h`` + has membership label ``10 * (h + 1)`` and weight ``weights[h]``.""" + keys = [key for household in households for key in household] + labels = [10 * (h + 1) for h, household in enumerate(households) for _ in household] + weights = weights or [float(h + 1) for h in range(len(households))] + columns = { + f"person_id__{DATASET_YEAR}": [100 + i for i in range(len(keys))], + f"person_household_id__{DATASET_YEAR}": labels, + f"household_weight__{DATASET_YEAR}": [ + float(weights[label // 10 - 1]) for label in labels + ], + } + if role_column == ROLE: + columns[f"{ROLE}__{DATASET_YEAR}"] = keys + elif role_column is not None: + columns[role_column] = keys + data = pd.DataFrame(columns) + if order is not None: + data = data.iloc[list(order)].reset_index(drop=True) + return data + + +def source_roles(households) -> dict: + """``{person ID: expected role key}`` from the household table.""" + keys = [key for household in households for key in household] + return {100 + i: expected_role(key) for i, key in enumerate(keys)} + + +def source_households(households) -> dict: + """``{frozenset of person IDs: Counter of expected role keys}``.""" + result, person = {}, 100 + for household in households: + ids = frozenset(range(person, person + len(household))) + result[ids] = Counter(expected_role(key) for key in household) + person += len(household) + return result + + +def load_dataframe( + data, role_variable="absent", default_role="first_parent", system=None +): + simulation_class = type( + "RoleSimulation", (Simulation,), {"default_role": default_role} + ) + return simulation_class( + tax_benefit_system=system or role_system(role_variable), + dataset=Dataset.from_dataframe(data, DATASET_YEAR), + ) + + +def load( + households, + role_variable="absent", + role_column=ROLE, + default_role="first_parent", + order=None, + weights=None, + system=None, +): + return load_dataframe( + dataframe(households, role_column, order, weights), + role_variable, + default_role, + system, + ) + + +def role_keys(simulation) -> np.ndarray: + household = simulation.populations["household"] + roles = np.broadcast_to( + np.asarray(household.members_role, dtype=object), simulation.persons.count + ) + return np.array([getattr(role, "key", NO_ROLE) for role in roles], dtype=object) + + +def roles_by_person(simulation) -> dict: + return dict(zip(simulation.persons.ids.tolist(), role_keys(simulation).tolist())) + + +def households_by_members(simulation) -> dict: + """``{frozenset of person IDs: Counter of role keys}`` per household.""" + household = simulation.populations["household"] + keys = role_keys(simulation) + result = {} + for index in range(household.count): + members = household.members_entity_id == index + ids = frozenset(simulation.persons.ids[members].tolist()) + result[ids] = Counter(keys[members].tolist()) + return result + + +def role_counts(simulation) -> dict: + """``{role key: nb_persons(role) per household}``, from the projector.""" + household = simulation.populations["household"] + return { + role.key: household.nb_persons(role).tolist() + for role in household.entity.flattened_roles + } From 1b6debb5065f1bf6f961336dd23eba89535a4217 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 18 Oct 2026 14:42:09 -0400 Subject: [PATCH 2/4] Add Hypothesis properties for roles kept through subsample For any households of bounded, unbounded and unmatched role keys, person order, weights, default role, role source and sample, every kept household is a whole source household whose role counts (by key and nb_persons) equal the source's, with or without a role variable, through a second subsample too, and no structural column is reported as ignored. An integer role variable keeps the roles or raises before changing anything. Move the household-table oracle into the shared fixture module. Co-Authored-By: Claude Opus 5.5 --- tests/core/test_subsample_explicit_roles.py | 30 +-- .../test_subsample_explicit_roles_property.py | 183 ++++++++++++++++++ tests/fixtures/subsample_roles.py | 26 +++ 3 files changed, 211 insertions(+), 28 deletions(-) create mode 100644 tests/core/test_subsample_explicit_roles_property.py diff --git a/tests/core/test_subsample_explicit_roles.py b/tests/core/test_subsample_explicit_roles.py index a49230b41..627253f91 100644 --- a/tests/core/test_subsample_explicit_roles.py +++ b/tests/core/test_subsample_explicit_roles.py @@ -19,14 +19,14 @@ DATASET_YEAR, NO_ROLE, ROLE, - households_by_members, + UNKNOWN_COLUMN_WARNING, + assert_roles_kept, load, load_dataframe, role_counts, role_keys, role_system, roles_by_person, - source_households, source_roles, ) @@ -39,32 +39,6 @@ ] # Shuffled so that a household's members are not adjacent rows. ORDER = [7, 0, 12, 3, 9, 1, 5, 10, 2, 8, 11, 4, 6] -UNKNOWN_COLUMN_WARNING = "do not match any variable" - - -def assert_roles_kept(simulation, households): - """Every kept household is a whole source household with its roles.""" - source = source_households(households) - kept = households_by_members(simulation) - assert kept, "subsample kept no household" - for members, roles in kept.items(): - assert members in source, f"{sorted(members)} is not a source household" - assert roles == source[members] - expected = source_roles(households) - assert roles_by_person(simulation) == { - person: expected[person] for person in simulation.persons.ids.tolist() - } - # The projector counts the same roles the members hold. - household_order = [ - frozenset( - simulation.persons.ids[ - simulation.household.members_entity_id == index - ].tolist() - ) - for index in range(simulation.household.count) - ] - for key, counts in role_counts(simulation).items(): - assert counts == [kept[members][key] for members in household_order] def test_review_reproduction_keeps_explicit_roles(): diff --git a/tests/core/test_subsample_explicit_roles_property.py b/tests/core/test_subsample_explicit_roles_property.py new file mode 100644 index 000000000..60728a64d --- /dev/null +++ b/tests/core/test_subsample_explicit_roles_property.py @@ -0,0 +1,183 @@ +"""Property: ``subsample`` keeps every kept member's loaded role. + +For any households of explicit role keys (bounded, unbounded and unmatched), +any person order, weights, default role, role source and sample, every kept +household is a whole source household whose role counts, by key and by +``nb_persons``, equal the source household's, whether or not the system +defines a role variable. An integer role variable either keeps the roles or +rejects members with no role before changing anything. +""" + +import logging +from contextlib import contextmanager + +import pytest + +from tests.fixtures.subsample_roles import ( + DATASET_YEAR, + FLATTENED_KEYS, + ROLE, + UNKNOWN_COLUMN_WARNING, + assert_roles_kept, + load, + role_keys, +) + +hypothesis = pytest.importorskip("hypothesis") +st = hypothesis.strategies + +# ``parent`` is the template's compound key and ``lodger`` no key at all: +# both load as no role. +EXTRA_KEYS = ["child", "lodger", "parent"] + + +def household(first_parent, second_parent): + parents = ["first_parent"] * first_parent + ["second_parent"] * second_parent + return st.lists( + st.sampled_from(EXTRA_KEYS), min_size=0 if parents else 1, max_size=3 + ).map(lambda others: parents + others) + + +HOUSEHOLD = st.tuples(st.booleans(), st.booleans()).flatmap( + lambda parents: household(*parents) +) +HOUSEHOLDS = st.lists(HOUSEHOLD, min_size=1, max_size=6) +DEFAULT_ROLES = st.sampled_from( + ["first_parent", "second_parent", "child", "parent", None] +) +SEEDS = st.sampled_from([0, 1, "a", "b"]) + + +@contextmanager +def unknown_column_warnings(): + class Collect(logging.Handler): + def __init__(self): + super().__init__(logging.WARNING) + self.messages = [] + + def emit(self, record): + if UNKNOWN_COLUMN_WARNING in record.getMessage(): + self.messages.append(record.getMessage()) + + handler = Collect() + root = logging.getLogger() + root.addHandler(handler) + try: + yield handler.messages + finally: + root.removeHandler(handler) + + +def draw_layout(data, households): + people = sum(len(household) for household in households) + order = data.draw(st.permutations(range(people)), label="order") + weights = data.draw( + st.lists(st.integers(1, 9), min_size=len(households), max_size=len(households)), + label="weights", + ) + return order, [float(weight) for weight in weights] + + +@hypothesis.settings(max_examples=200, deadline=None) +@hypothesis.example( + households=[["first_parent", "child", "child"], ["first_parent"]], + role_variable="absent", + role_column=ROLE, + default_role="first_parent", + n=2, + seed=0, + quantize_weights=True, + again=1, + data=None, +).via("review P3-1 on #595") +@hypothesis.given( + households=HOUSEHOLDS, + role_variable=st.sampled_from(["absent", "string"]), + role_column=st.sampled_from([ROLE, "role"]), + default_role=DEFAULT_ROLES, + n=st.integers(1, 8), + seed=SEEDS, + quantize_weights=st.booleans(), + again=st.integers(1, 4), + data=st.data(), +) +def test_subsample_keeps_explicit_roles( + households, + role_variable, + role_column, + default_role, + n, + seed, + quantize_weights, + again, + data, +): + order, weights = (None, None) if data is None else draw_layout(data, households) + with unknown_column_warnings() as warnings: + simulation = load( + households, + role_variable=role_variable, + role_column=role_column, + default_role=default_role, + order=order, + weights=weights, + ) + # The loader itself agrees with the table, so later checks test + # what subsample keeps rather than what was loaded. + assert_roles_kept(simulation, households) + assert simulation.household.count == len(households) + + simulation.subsample( + n=n, seed=seed, time_period=DATASET_YEAR, quantize_weights=quantize_weights + ) + assert 1 <= simulation.household.count <= min(n, len(households)) + assert_roles_kept(simulation, households) + + # The rebuilt simulation carries them on through another subsample. + simulation.subsample(n=again, seed=seed, time_period=DATASET_YEAR) + assert_roles_kept(simulation, households) + + assert warnings == [] + + +@hypothesis.settings(max_examples=100, deadline=None) +@hypothesis.given( + households=HOUSEHOLDS, + default_role=DEFAULT_ROLES, + n=st.integers(1, 8), + seed=SEEDS, + data=st.data(), +) +def test_integer_role_variable_keeps_roles_or_changes_nothing( + households, default_role, n, seed, data +): + order, weights = draw_layout(data, households) + simulation = load( + households, + role_variable="integer", + role_column="role", + default_role=default_role, + order=order, + weights=weights, + ) + roleless = any( + key not in FLATTENED_KEYS for household in households for key in household + ) + dataset = simulation.dataset + persons = simulation.persons.ids.tolist() + roles = role_keys(simulation).tolist() + household_weights = simulation.calculate("household_weight", DATASET_YEAR).tolist() + + if roleless: + with pytest.raises(ValueError, match="integer role variable"): + simulation.subsample(n=n, seed=seed, time_period=DATASET_YEAR) + assert simulation.dataset is dataset + assert simulation.persons.ids.tolist() == persons + assert role_keys(simulation).tolist() == roles + assert ( + simulation.calculate("household_weight", DATASET_YEAR).tolist() + == household_weights + ) + else: + simulation.subsample(n=n, seed=seed, time_period=DATASET_YEAR) + assert_roles_kept(simulation, households) diff --git a/tests/fixtures/subsample_roles.py b/tests/fixtures/subsample_roles.py index 8e6c9471b..142014a4e 100644 --- a/tests/fixtures/subsample_roles.py +++ b/tests/fixtures/subsample_roles.py @@ -26,6 +26,7 @@ FLATTENED_KEYS = ("first_parent", "second_parent", "child") # How these helpers report a member the loader gave no role. NO_ROLE = "" +UNKNOWN_COLUMN_WARNING = "do not match any variable" class integer_role(Variable): @@ -157,3 +158,28 @@ def role_counts(simulation) -> dict: role.key: household.nb_persons(role).tolist() for role in household.entity.flattened_roles } + + +def assert_roles_kept(simulation, households): + """Every kept household is a whole source household with its roles.""" + source = source_households(households) + kept = households_by_members(simulation) + assert kept, "subsample kept no household" + for members, roles in kept.items(): + assert members in source, f"{sorted(members)} is not a source household" + assert roles == source[members] + expected = source_roles(households) + assert roles_by_person(simulation) == { + person: expected[person] for person in simulation.persons.ids.tolist() + } + # The projector counts the same roles the members hold. + household_order = [ + frozenset( + simulation.persons.ids[ + simulation.household.members_entity_id == index + ].tolist() + ) + for index in range(simulation.household.count) + ] + for key, counts in role_counts(simulation).items(): + assert counts == [kept[members][key] for members in household_order] From cd9c72ca4d40979ad11951c02b527debeb8214f2 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 30 Nov 2026 18:04:26 +0000 Subject: [PATCH 3/4] Warn about unused period-suffixed structural columns Clarify structural input precedence during subsampling and cover loaded role keys across dataset formats. Co-Authored-By: GPT-6.2 Sol --- ... => fix-subsample-preserve-roles.fixed.md} | 0 docs/usage/simulation.ipynb | 4 +- policyengine_core/simulations/simulation.py | 22 ++++---- tests/core/test_subsample_explicit_roles.py | 56 +++++++++++++++++-- 4 files changed, 63 insertions(+), 19 deletions(-) rename changelog.d/{subsample-preserve-roles.fixed.md => fix-subsample-preserve-roles.fixed.md} (100%) diff --git a/changelog.d/subsample-preserve-roles.fixed.md b/changelog.d/fix-subsample-preserve-roles.fixed.md similarity index 100% rename from changelog.d/subsample-preserve-roles.fixed.md rename to changelog.d/fix-subsample-preserve-roles.fixed.md diff --git a/docs/usage/simulation.ipynb b/docs/usage/simulation.ipynb index 66979a965..954f6f368 100644 --- a/docs/usage/simulation.ipynb +++ b/docs/usage/simulation.ipynb @@ -1115,7 +1115,9 @@ "source": [ "### Subsampling simulations\n", "\n", - "Often, we're running simulations over very large (100,000+) datasets. This can be slow, so we might want to subsample the dataset to speed up the simulation. This can be done by using `Simulation.subsample` or `Microsimulation.subsample`, which will return a new `Simulation` or `Microsimulation` object with a smaller dataset." + "Use `Simulation.subsample` or `Microsimulation.subsample` to run a simulation on a smaller dataset. The method rebuilds the simulation in place and returns the same object.\n", + "\n", + "Recorded inputs for person IDs, household membership and roles take precedence in the rebuild. For fields without recorded inputs, subsampling uses the loaded IDs, memberships and role keys, even when the system has no variable for the field. When subsampling reconstructs an integer role column, every member needs a recognized flattened role. If any member lacks one, subsampling raises `ValueError` before rebuilding the simulation." ] }, { diff --git a/policyengine_core/simulations/simulation.py b/policyengine_core/simulations/simulation.py index 676136b1e..c9205ed9b 100644 --- a/policyengine_core/simulations/simulation.py +++ b/policyengine_core/simulations/simulation.py @@ -1106,13 +1106,14 @@ def build_from_dataset(self) -> None: structural_columns = set() def get_eternity_array(name): - structural_columns.add(name) if self.dataset.data_format == Dataset.FLAT_FILE: # Look for any column with variablename__timeperiod for col in data: if col.split("__")[0] == name: + structural_columns.add(col) return data[col] - elif self.dataset.data_format == Dataset.TIME_PERIOD_ARRAYS: + structural_columns.add(name) + if self.dataset.data_format == Dataset.TIME_PERIOD_ARRAYS: return data[name][list(data[name].keys())[0]] return data[name] @@ -1202,7 +1203,7 @@ def get_eternity_array(name): time_period = self.dataset.time_period or self.default_input_period if variable_name not in self.tax_benefit_system.variables: - if variable_name not in structural_columns: + if variable not in structural_columns: unknown_columns.append(variable) continue @@ -3377,14 +3378,11 @@ def subsample( Calculated weights and other formula results are recomputed on the sample. Calculation branches are recreated on its populations; baseline policy is kept. - If structural inputs are absent, loaded population IDs, memberships - and roles supply the leaves needed to rebuild the same partition. - This also supports structural variables whose IDs have formulas. - These leaves are carried whether or not the system defines a variable - for them, and roles are carried by key, so every kept member keeps - the role it was loaded with instead of the default role. An integer - role variable cannot represent a member with no role; subsampling - raises ``ValueError`` before changing anything in that case. + Recorded structural inputs take precedence in the rebuild. For each + field without a recorded input, subsampling uses the loaded IDs, + memberships or role keys, including fields without backing variables. + Reconstructing an integer role column raises ``ValueError`` before the + rebuild if any loaded member lacks a recognized flattened role. Args: n (int, optional): The number of households to sample. Defaults to 10_000. @@ -3393,7 +3391,7 @@ def subsample( time_period (str, optional): Sample households based on their weight in this time period. Defaults to the default calculation period. Returns: - Simulation: The quantized simulation. + Simulation: This simulation, rebuilt in place with the sample. """ default_calculation_period = self.default_calculation_period # Set default key if not provided diff --git a/tests/core/test_subsample_explicit_roles.py b/tests/core/test_subsample_explicit_roles.py index 627253f91..cfc14290b 100644 --- a/tests/core/test_subsample_explicit_roles.py +++ b/tests/core/test_subsample_explicit_roles.py @@ -9,6 +9,7 @@ """ import logging +from copy import copy import pandas as pd import pytest @@ -21,6 +22,7 @@ ROLE, UNKNOWN_COLUMN_WARNING, assert_roles_kept, + dataframe, load, load_dataframe, role_counts, @@ -157,15 +159,34 @@ def test_integer_role_variable_rejects_roleless_members_before_changing_anything assert simulation.calculate("household_weight", DATASET_YEAR).tolist() == weights -def test_integer_role_variable_carries_flattened_roles(): +@pytest.mark.parametrize("detach_role", [False, True], ids=["canonical", "detached"]) +def test_integer_role_variable_carries_flattened_roles(detach_role): households = [["first_parent", "second_parent", "child"], ["child", "first_parent"]] simulation = load(households, role_variable="integer", role_column="role") + if detach_role: + roles = simulation.household.members_role + second_parent = roles[1] + roles[1] = copy(second_parent) + assert roles[1] is not second_parent + assert roles[1].key == second_parent.key == "second_parent" simulation.subsample(n=4, seed="roles", time_period=DATASET_YEAR) assert_roles_kept(simulation, households) +def test_recorded_role_input_takes_precedence_over_loaded_roles(): + simulation = load( + [["first_parent", "child"]], role_variable="integer", role_column="role" + ) + assert roles_by_person(simulation) == {100: "first_parent", 101: "child"} + simulation.set_input(ROLE, ETERNITY, [2, 0]) + + assert simulation.subsample(n=1, seed=0) is simulation + + assert roles_by_person(simulation) == {100: "child", 101: "first_parent"} + + def unknown_column_warnings(caplog): return [ record.getMessage() @@ -212,18 +233,41 @@ def test_unknown_columns_are_still_reported_beside_structural_ones(caplog): assert ROLE not in warning -def test_time_period_array_role_column_is_used_and_not_reported(caplog): +def test_unused_period_role_column_is_reported(caplog): + households = [["first_parent", "child"]] + data = dataframe(households) + loaded_column = f"{ROLE}__{DATASET_YEAR}" + unused_column = f"{ROLE}__2025" + data[unused_column] = ["child", "first_parent"] + + with caplog.at_level(logging.WARNING): + simulation = load_dataframe(data) + + [warning] = unknown_column_warnings(caplog) + assert "1 column(s)" in warning + assert unused_column in warning + assert loaded_column not in warning + assert_roles_kept(simulation, households) + + +@pytest.mark.parametrize("data_format", [Dataset.ARRAYS, Dataset.TIME_PERIOD_ARRAYS]) +def test_array_role_column_is_used_and_not_reported(caplog, data_format): frame = load(HOUSEHOLDS).dataset.load() - data = {column.split("__")[0]: {ETERNITY: frame[column].values} for column in frame} - data["household_id"] = {ETERNITY: [10, 20, 30, 40, 50]} - data["household_weight"] = {DATASET_YEAR: [1.0, 2.0, 3.0, 4.0, 5.0]} + data = {column.split("__")[0]: frame[column].values for column in frame} + data["household_id"] = [10, 20, 30, 40, 50] + data["household_weight"] = [1.0, 2.0, 3.0, 4.0, 5.0] + if data_format == Dataset.TIME_PERIOD_ARRAYS: + data = { + name: {DATASET_YEAR if name == "household_weight" else ETERNITY: values} + for name, values in data.items() + } dataset = type( "RoleArrays", (Dataset,), { "name": "role_arrays", "label": "Role arrays", - "data_format": Dataset.TIME_PERIOD_ARRAYS, + "data_format": data_format, "file_path": "dataframe", "time_period": DATASET_YEAR, "load": lambda self: data, From c71bf164cf32e441e9edeccf277d488bd6dbc8bb Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Tue, 1 Dec 2026 05:54:25 +0000 Subject: [PATCH 4/4] Preserve role slots and membership IDs in subsamples Co-Authored-By: GPT-6.2 Sol --- .../fix-subsample-preserve-roles.fixed.md | 2 +- docs/usage/simulation.ipynb | 4 +- policyengine_core/data/dataset.py | 12 +- policyengine_core/simulations/simulation.py | 86 ++++++---- tests/core/test_subsample_explicit_roles.py | 162 +++++++++++++++++- 5 files changed, 225 insertions(+), 41 deletions(-) diff --git a/changelog.d/fix-subsample-preserve-roles.fixed.md b/changelog.d/fix-subsample-preserve-roles.fixed.md index bc846b91b..bc3c8b6cb 100644 --- a/changelog.d/fix-subsample-preserve-roles.fixed.md +++ b/changelog.d/fix-subsample-preserve-roles.fixed.md @@ -1 +1 @@ -`Simulation.subsample` now keeps each member's loaded role (and person and membership IDs) when the tax-benefit system has no variable for them, instead of rebuilding everyone with the default role, and the dataset loader no longer reports the structural columns it reads as ignored. +`Simulation.subsample` carries loaded person IDs, membership IDs and roles for fields without recorded inputs, including distinct integer role slots, and the dataset loader leaves the structural columns it reads out of ignored-column warnings. diff --git a/docs/usage/simulation.ipynb b/docs/usage/simulation.ipynb index 954f6f368..1684ca3fc 100644 --- a/docs/usage/simulation.ipynb +++ b/docs/usage/simulation.ipynb @@ -1117,7 +1117,9 @@ "\n", "Use `Simulation.subsample` or `Microsimulation.subsample` to run a simulation on a smaller dataset. The method rebuilds the simulation in place and returns the same object.\n", "\n", - "Recorded inputs for person IDs, household membership and roles take precedence in the rebuild. For fields without recorded inputs, subsampling uses the loaded IDs, memberships and role keys, even when the system has no variable for the field. When subsampling reconstructs an integer role column, every member needs a recognized flattened role. If any member lacks one, subsampling raises `ValueError` before rebuilding the simulation." + "Recorded structural inputs take precedence and can change household membership or roles. The loader uses the first matching column in dataset order, while subsampling exports recorded periods in sorted order. With multiple recorded periods, the rebuild can use a different period from the original load.\n", + "\n", + "For fields without recorded inputs, subsampling uses the loaded person and membership IDs and carries roles by key or, for integer variables, by flattened role index. This also works for fields without backing variables. If subsampling cannot identify a flattened role for a member when reconstructing an integer role column, it raises `ValueError` before rebuilding the simulation." ] }, { diff --git a/policyengine_core/data/dataset.py b/policyengine_core/data/dataset.py index 1f87103ca..ae604db97 100644 --- a/policyengine_core/data/dataset.py +++ b/policyengine_core/data/dataset.py @@ -73,6 +73,7 @@ class Dataset: FLAT_FILE = "flat_file" _table_cache: Dict[str, pd.DataFrame] = None + _preserve_group_ids: bool = False def __init__(self, require: bool = False): # Setup dataset @@ -481,9 +482,17 @@ def from_file(file_path: str, time_period: str = None): return dataset @staticmethod - def from_dataframe(dataframe: pd.DataFrame, time_period: str = None): + def from_dataframe( + dataframe: pd.DataFrame, + time_period: str = None, + *, + preserve_group_ids: bool = False, + ): """Creates a dataset from a DataFrame. + If ``preserve_group_ids`` is true, the simulation uses the membership + labels as group IDs when loading the dataset. + Returns: Dataset: The dataset. """ @@ -497,6 +506,7 @@ def from_dataframe(dataframe: pd.DataFrame, time_period: str = None): "file_path": "dataframe", "time_period": time_period, "load": lambda self: dataframe, + "_preserve_group_ids": preserve_group_ids, }, )() diff --git a/policyengine_core/simulations/simulation.py b/policyengine_core/simulations/simulation.py index 6b5b4845a..c27e7e0e6 100644 --- a/policyengine_core/simulations/simulation.py +++ b/policyengine_core/simulations/simulation.py @@ -1,5 +1,6 @@ import hashlib import os +from collections import Counter from contextlib import nullcontext import types from contextvars import ContextVar @@ -1120,9 +1121,11 @@ def build_from_dataset(self) -> None: Entity-specific role columns take precedence over a generic ``role`` column, including period-suffixed entity role columns in flat files. - Without either, each person receives the literal ``default_role`` - key. Only flattened-role keys match: unmatched and compound keys remain - unrecognized rather than selecting a first role or subrole. + The loader uses the first matching column in dataset order. + Integer role arrays index flattened role slots. String role arrays + match flattened role keys literally, leaving other keys unmatched. + Without a role column, each person receives the literal + ``default_role`` key. A recognized implicit default with a finite role maximum must fit every group's membership count. Otherwise an explicit role column is required. @@ -1193,8 +1196,7 @@ def get_eternity_array(name): # A flat file has one row per person, so it declares each # group only through its members' rows: their membership # column or, failing that, the group's ID column repeated on - # each member's row. Number the distinct IDs 0, 1, ... and - # give each person their group's number. + # each member's row. membership_field = next( ( field @@ -1211,10 +1213,14 @@ def get_eternity_array(name): f"{int(pd.isna(membership_values).sum())} person(s) " f"have no {membership_field} in the dataset." ) - distinct_ids, person_membership_ids = np.unique( - membership_values, return_inverse=True - ) - entity_ids = np.arange(len(distinct_ids)) + if self.dataset._preserve_group_ids: + entity_ids = np.unique(membership_values) + person_membership_ids = membership_values + else: + distinct_ids, person_membership_ids = np.unique( + membership_values, return_inverse=True + ) + entity_ids = np.arange(len(distinct_ids)) builder.declare_entity(group_entity.key, entity_ids) @@ -3642,11 +3648,15 @@ def subsample( Calculated weights and other formula results are recomputed on the sample. Calculation branches are recreated on its populations; baseline policy is kept. - Recorded structural inputs take precedence in the rebuild. For each - field without a recorded input, subsampling uses the loaded IDs, - memberships or role keys, including fields without backing variables. - Reconstructing an integer role column raises ``ValueError`` before the - rebuild if any loaded member lacks a recognized flattened role. + Recorded structural inputs take precedence in the rebuild and can + change household membership or roles. The dataset loader uses the + first matching column. Subsampling exports recorded periods in sorted + order, so the reload can use a different period from the source. + Fields without recorded inputs use loaded person IDs, membership IDs + and role assignments, including fields without backing variables. + Role columns use keys or, for integer variables, flattened role + indices. Reconstructing an integer column raises ``ValueError`` before + rebuilding if a member's flattened role cannot be identified. Args: n (int, optional): The number of households to sample. Defaults to 10_000. @@ -3704,33 +3714,47 @@ def retain_structure(name, values): role_name = f"{person_key}_{entity.key}_role" if any(column.split("__")[0] == role_name for column in df): continue - # Carry each member's own role by key; the rebuild otherwise - # gives everyone the default. Members the loader matched to no - # role hold 0, and an empty key reloads them the same way. role_variable = self.tax_benefit_system.get_variable(role_name) roles = np.broadcast_to( np.asarray(population.members_role, dtype=object), self.persons.count, ) - role_keys = [getattr(role, "key", "") for role in roles] + flattened_roles = entity.flattened_roles + key_counts = Counter(role.key for role in flattened_roles) if role_variable is not None and role_variable.value_type == int: - # An integer role column indexes flattened roles, so it has - # no value for "no role". Stop before anything is replaced. - index_of = { - role.key: index for index, role in enumerate(entity.flattened_roles) + # Canonical role objects identify their slots even when keys + # repeat. A detached role's key can identify a unique slot. + by_role = {role: index for index, role in enumerate(flattened_roles)} + by_key = { + role.key: index + for role, index in by_role.items() + if key_counts[role.key] == 1 } - unindexed = sorted({key for key in role_keys if key not in index_of}) - if unindexed: + role_values = [ + by_role.get(role, by_key.get(getattr(role, "key", None), -1)) + for role in roles + ] + if -1 in role_values: + unindexed = sorted( + { + getattr(role, "key", "(no role)") + for role, index in zip(roles, role_values) + if index == -1 + } + ) raise ValueError( f"Cannot subsample: {role_name} is an integer role " f"variable, so it can only hold the {entity.key} roles " - f"{[role.key for role in entity.flattened_roles]}, but " - "some members hold " - f"{[key or '(no role)' for key in unindexed]}." + f"{[role.key for role in flattened_roles]}, but " + f"some members hold {unindexed}." ) - retain_structure(role_name, [index_of[key] for key in role_keys]) else: - retain_structure(role_name, role_keys) + # Use a key the loader will leave unmatched. + no_role = "" + while no_role in key_counts: + no_role += "_" + role_values = [getattr(role, "key", no_role) for role in roles] + retain_structure(role_name, role_values) # Flat-file loading can infer households from membership IDs even # when the household ID variable has a formula. Use the same leaves @@ -3843,7 +3867,9 @@ def retain_structure(name, values): df = subset_df # Rebuilding replaces storage, its input record, and store history. - self.dataset = Dataset.from_dataframe(df, self.dataset.time_period) + self.dataset = Dataset.from_dataframe( + df, self.dataset.time_period, preserve_group_ids=True + ) self._store_history = StoreHistory() self._user_input_keys = set() self.build_from_dataset() diff --git a/tests/core/test_subsample_explicit_roles.py b/tests/core/test_subsample_explicit_roles.py index cfc14290b..c617e3e49 100644 --- a/tests/core/test_subsample_explicit_roles.py +++ b/tests/core/test_subsample_explicit_roles.py @@ -11,11 +11,21 @@ import logging from copy import copy +import numpy as np import pandas as pd import pytest +from policyengine_core.country_template.entities import Person +from policyengine_core.country_template.variables.ids import ( + person_household_id, + person_id, +) from policyengine_core.data import Dataset -from policyengine_core.periods import ETERNITY +from policyengine_core.entities import build_entity +from policyengine_core.periods import ETERNITY, YEAR +from policyengine_core.simulations import Simulation +from policyengine_core.taxbenefitsystems import TaxBenefitSystem +from policyengine_core.variables import Variable from tests.fixtures.subsample_roles import ( DATASET_YEAR, NO_ROLE, @@ -23,6 +33,7 @@ UNKNOWN_COLUMN_WARNING, assert_roles_kept, dataframe, + integer_role, load, load_dataframe, role_counts, @@ -175,6 +186,58 @@ def test_integer_role_variable_carries_flattened_roles(detach_role): assert_roles_kept(simulation, households) +def system_with_role_keys(keys): + household = build_entity( + "household", "households", "Household", roles=[{"key": key} for key in keys] + ) + + class household_weight(Variable): + entity = household + value_type = float + definition_period = YEAR + label = "Household weight" + + system = TaxBenefitSystem([Person, household]) + system.add_variables(person_id, person_household_id, household_weight) + return system + + +def test_integer_role_indices_keep_distinct_slots_with_the_same_key(): + system = system_with_role_keys(["adult", "adult", "child"]) + system.add_variable(integer_role) + simulation = load([[0, 1]], role_column="role", system=system) + + def counts_by_slot(): + household = simulation.household + return [ + household.nb_persons(role).tolist() + for role in household.entity.flattened_roles + ] + + assert counts_by_slot() == [[1], [1], [0]] + simulation.subsample(n=1, seed=0) + assert counts_by_slot() == [[1], [1], [0]] + + +def test_unmatched_role_stays_unmatched_when_empty_key_is_a_role(): + simulation = load( + [["unknown", "child"]], + role_column="role", + system=system_with_role_keys(["", "child"]), + ) + assert simulation.household.members_role.tolist() == [ + 0, + simulation.household.entity.CHILD, + ] + + simulation.subsample(n=1, seed=0) + + assert simulation.household.members_role.tolist() == [ + 0, + simulation.household.entity.CHILD, + ] + + def test_recorded_role_input_takes_precedence_over_loaded_roles(): simulation = load( [["first_parent", "child"]], role_variable="integer", role_column="role" @@ -187,6 +250,48 @@ def test_recorded_role_input_takes_precedence_over_loaded_roles(): assert roles_by_person(simulation) == {100: "child", 101: "first_parent"} +def test_recorded_membership_can_change_the_sampled_household_partition(): + simulation = load([["first_parent", "child"]]) + assert simulation.persons.ids.tolist() == [100, 101] + assert simulation.household.members_entity_id.tolist() == [0, 0] + simulation.set_input("person_household_id", ETERNITY, [10, 20]) + + simulation.subsample(n=1, seed=0) + + assert simulation.persons.ids.tolist() == [100] + + +def test_recorded_annual_roles_reload_in_period_order(): + class person_household_role(Variable): + value_type = str + entity = Person + definition_period = YEAR + label = "Annual household role" + + system = role_system("string") + system.replace_variable(person_household_role) + system.load_extension("policyengine_core.extension_template") + data = dataframe([["first_parent", "child"]], role_column=None) + data[f"{ROLE}__2025"] = ["first_parent", "child"] + data[f"{ROLE}__2024"] = ["child", "child"] + data["age__2024"] = [30, 7] + data["salary__2024"] = [0, 0] + simulation = load_dataframe(data, system=system) + assert role_keys(simulation).tolist() == ["first_parent", "child"] + assert simulation.calculate("parenting_allowance", "2024-01").tolist() == [600] + assert simulation.calculate("local_town_child_allowance", "2024-01").tolist() == [ + 100 + ] + + simulation.subsample(n=1, seed=0) + + assert role_keys(simulation).tolist() == ["child", "child"] + assert simulation.calculate("parenting_allowance", "2024-01").tolist() == [0] + assert simulation.calculate("local_town_child_allowance", "2024-01").tolist() == [ + 200 + ] + + def unknown_column_warnings(caplog): return [ record.getMessage() @@ -250,18 +355,13 @@ def test_unused_period_role_column_is_reported(caplog): assert_roles_kept(simulation, households) -@pytest.mark.parametrize("data_format", [Dataset.ARRAYS, Dataset.TIME_PERIOD_ARRAYS]) -def test_array_role_column_is_used_and_not_reported(caplog, data_format): - frame = load(HOUSEHOLDS).dataset.load() - data = {column.split("__")[0]: frame[column].values for column in frame} - data["household_id"] = [10, 20, 30, 40, 50] - data["household_weight"] = [1.0, 2.0, 3.0, 4.0, 5.0] +def role_arrays(data, data_format): if data_format == Dataset.TIME_PERIOD_ARRAYS: data = { name: {DATASET_YEAR if name == "household_weight" else ETERNITY: values} for name, values in data.items() } - dataset = type( + return type( "RoleArrays", (Dataset,), { @@ -273,6 +373,15 @@ def test_array_role_column_is_used_and_not_reported(caplog, data_format): "load": lambda self: data, }, )() + + +@pytest.mark.parametrize("data_format", [Dataset.ARRAYS, Dataset.TIME_PERIOD_ARRAYS]) +def test_array_role_column_is_used_and_not_reported(caplog, data_format): + frame = load(HOUSEHOLDS).dataset.load() + data = {column.split("__")[0]: frame[column].values for column in frame} + data["household_id"] = [10, 20, 30, 40, 50] + data["household_weight"] = [1.0, 2.0, 3.0, 4.0, 5.0] + dataset = role_arrays(data, data_format) simulation_class = type(load(HOUSEHOLDS)) with caplog.at_level(logging.WARNING): simulation = simulation_class( @@ -282,3 +391,40 @@ def test_array_role_column_is_used_and_not_reported(caplog, data_format): assert unknown_column_warnings(caplog) == [] assert_roles_kept(simulation, HOUSEHOLDS) assert NO_ROLE in role_keys(simulation).tolist() + + +@pytest.mark.parametrize("data_format", [Dataset.ARRAYS, Dataset.TIME_PERIOD_ARRAYS]) +def test_repeated_sampling_keeps_unbacked_membership_ids(data_format): + system = role_system("absent") + for name in ("person_id", "person_household_id", "household_id"): + del system.variables[name] + data = { + "person_id": np.array([100, 101, 102]), + "household_id": np.array([10, 20]), + "person_household_id": np.array([10, 10, 20]), + ROLE: np.array(["first_parent", "child", "first_parent"]), + "household_weight": np.array([1.0, 1.0]), + } + simulation = Simulation( + tax_benefit_system=system, dataset=role_arrays(data, data_format) + ) + + def assert_loaded_ids(simulation): + assert simulation.persons.ids.tolist() == [100, 101, 102] + household = simulation.household + assert household.ids[household.members_entity_id].tolist() == [10, 10, 20] + assert role_keys(simulation).tolist() == [ + "first_parent", + "child", + "first_parent", + ] + + assert_loaded_ids(simulation) + for _ in range(2): + simulation.subsample(n=2, seed=0) + assert simulation.dataset.data_format == Dataset.FLAT_FILE + assert_loaded_ids(simulation) + frame = simulation.dataset.load() + assert frame[f"person_household_id__{ETERNITY}"].tolist() == [10, 10, 20] + + assert_loaded_ids(Simulation(tax_benefit_system=system, dataset=simulation.dataset))