From 2625da1f1ec8ed2ca39cc50b205c723efded50cc Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 1 Nov 2026 17:25:40 -0500 Subject: [PATCH 01/14] Run a researcher's flat file through each state's rules Fixes #732 Co-Authored-By: Claude Opus 5.5 --- changelog.d/732.added.md | 1 + docs/_quarto.yml | 1 + docs/simulated-instruments.md | 61 ++++ .../tax_benefit_models/us/__init__.py | 3 + .../tax_benefit_models/us/flat_file.py | 331 +++++++++++++++++ tests/test_us_flat_file.py | 337 ++++++++++++++++++ 6 files changed, 734 insertions(+) create mode 100644 changelog.d/732.added.md create mode 100644 docs/simulated-instruments.md create mode 100644 src/policyengine/tax_benefit_models/us/flat_file.py create mode 100644 tests/test_us_flat_file.py diff --git a/changelog.d/732.added.md b/changelog.d/732.added.md new file mode 100644 index 000000000..508e3a9d1 --- /dev/null +++ b/changelog.d/732.added.md @@ -0,0 +1 @@ +Add `pe.us.flat_file_microsimulation` and `pe.us.prepare_flat_file`, which run a researcher's own flat file through one state's rules or the file's own states, plus a simulated instruments recipe. diff --git a/docs/_quarto.yml b/docs/_quarto.yml index 5e0472a30..39e12e55b 100644 --- a/docs/_quarto.yml +++ b/docs/_quarto.yml @@ -34,6 +34,7 @@ website: - households.md - reforms.md - microsim.md + - simulated-instruments.md - section: "Analyse" contents: - impact-analysis.md diff --git a/docs/simulated-instruments.md b/docs/simulated-instruments.md new file mode 100644 index 000000000..a3d0552bb --- /dev/null +++ b/docs/simulated-instruments.md @@ -0,0 +1,61 @@ +--- +title: "Simulated instruments" +--- + +A simulated eligibility instrument runs one fixed population through each state's rules. The people stay the same, so differences across states come from the rules alone. `pe.us.flat_file_microsimulation` runs your own microdata this way. + +## The recipe + +```python +import pandas as pd +import policyengine as pe +from policyengine.countries.us.data import US_STATE_FIPS + +people = pd.read_csv("your_survey.csv", dtype={"county_fips": str}) + +snap_eligible = {} +for state in US_STATE_FIPS: + sim = pe.us.flat_file_microsimulation( + people, + year=2024, + state=state, + spm={"geography_kind": "national"}, + ) + snap_eligible[state] = sim.calculate("is_snap_eligible", "2024-01").mean() +``` + +`state` takes a postal code or a FIPS code. `calculate` returns a weighted series, so `mean()` gives the weighted share of SPM units. Pass `reform=` to run a reform in every state, and read the baseline arm from `sim.baseline`. + +To run each household in the state your file records, leave `state` out. The file then needs `state_fips`, and any county or state label it holds has to agree with `state_fips`. + +## What your file needs + +The file holds one row per person. Name a column after a variable, or `variable__period` to date it. A column with no period holds the value for `year`. + +| Column | Needed | Notes | +| --- | --- | --- | +| `household_id`, `tax_unit_id`, `spm_unit_id`, `family_id`, `marital_unit_id` | Yes | Put each on every person's row. Text IDs work. | +| `age` | Yes | Without it, everyone runs as 40. | +| `state_fips` | Unless you pass `state` | Without it, everyone runs as California. | +| `person_id` | No | The helper numbers the rows if you leave it out. | +| `household_weight` | No | Every household weighs 1 without it. | +| Income and other inputs | As your measure needs | Inputs you omit take their defaults, usually zero. | +| `county_fips` | No | Read it as text so that 06037 keeps its leading zero. The helper repairs 6037 either way. | + +`prepare_flat_file` runs these checks and returns the frame the simulation loads, so you can inspect it. It refuses a file that lacks a required column, repeats a `person_id`, puts one household in two states, or holds a county outside its state. It logs columns that name no variable, then ignores them. + +## What a state change clears + +Passing `state` sets `state_fips` in every year your file holds. It also removes stored state labels and all geography finer than a state, such as county, ZIP code, congressional district and tract, because those values mean nothing in the new state. + +With no county, the model applies county-keyed rules using the first county in the state alphabetically, such as Aitkin County in Minnesota. SPM thresholds use county in the default selection, so select `{"geography_kind": "national"}` as the recipe does. The selection applies to every state, which keeps thresholds identical across the loop. To keep real counties, leave `state` out and run each household where the file records it. + +## What to watch for + +- **Years before your file.** A run reads later years from your file's last value, but an earlier year falls back to defaults. A 2024 file read for 2023 runs everyone as California at age 40, with no income. +- **Medicaid dollars.** `medicaid` spreads each state's total spending across the weighted people the file puts in that state, so a small file gets very large amounts per person. Measure eligibility with `is_medicaid_eligible`. The same applies to `healthcare_benefit_value`. +- **Deciles.** Income deciles rank households within your file, not within the US. +- **Minors on their own.** The SPM calculation needs someone aged 18 or over in each SPM unit, or someone aged 15 to 17 with `is_household_head`, `is_household_spouse` or `is_spm_independent_minor_role` set. Those columns hold for all time, so `to_input_dataframe` names them `variable__ETERNITY`. Keep that suffix when you filter an export to one year. +- **Changing state after the build.** `sim.set_input("state_fips", ...)` leaves stored geography in place. Pass `state` so that the helper clears it first. + +`policyengine.py` runs against the country model versions this release pins. Text variables such as `state_code_str` do not map to group entities in these versions, so calculate them at the household level. diff --git a/src/policyengine/tax_benefit_models/us/__init__.py b/src/policyengine/tax_benefit_models/us/__init__.py index bfd62147e..502325353 100644 --- a/src/policyengine/tax_benefit_models/us/__init__.py +++ b/src/policyengine/tax_benefit_models/us/__init__.py @@ -47,6 +47,7 @@ load_managed_long_term_datasets, validate_long_term_dataset_metadata, ) + from .flat_file import flat_file_microsimulation, prepare_flat_file from .household import calculate_household from .model import ( PolicyEngineUS, @@ -81,6 +82,8 @@ "model", "us_latest", "calculate_household", + "flat_file_microsimulation", + "prepare_flat_file", "SPMSelection", "SPMProvenance", "economic_impact_analysis", diff --git a/src/policyengine/tax_benefit_models/us/flat_file.py b/src/policyengine/tax_benefit_models/us/flat_file.py new file mode 100644 index 000000000..5828c072e --- /dev/null +++ b/src/policyengine/tax_benefit_models/us/flat_file.py @@ -0,0 +1,331 @@ +"""Run a researcher's own flat file through the pinned US model. + +A flat file holds one row per person, as a survey extract does. A simulated +instrument runs the same people through each state's rules, so moving the file +to a state has to carry everything that depends on the state: a stored county or +state label from the old state would otherwise contradict the new ``state_fips``. + +``prepare_flat_file`` does that work and checks the file first, because a missing +column does not fail on its own: without ``state_fips`` every household runs as +California. It writes the columns in the one form the pinned loader reads +correctly, ``variable__period``, with each person's groups on their own row. +""" + +import logging +from typing import Optional, Union + +import numpy as np +import pandas as pd + +from policyengine.countries.us.data import US_STATE_FIPS +from policyengine.tax_benefit_models.common.model_version import ( + build_runtime_dataset_provenance, +) + +from .model import us_latest +from .spm import SPMSelection, resolve_spm_selection + +__all__ = ["flat_file_microsimulation", "prepare_flat_file"] + +GROUP_ENTITIES = ("household", "tax_unit", "spm_unit", "family", "marital_unit") +ID_VARIABLES = frozenset( + { + "person_id", + *(f"{group}_id" for group in GROUP_ENTITIES), + *(f"person_{group}_id" for group in GROUP_ENTITIES), + } +) +STATE_LABELS = ("state_code", "state_code_str", "state_name") +# Geography finer than a state, which means nothing in another state. +LOCAL_GEOGRAPHY = ( + "block_geoid", + "cbsa_code", + "congressional_district_geoid", + "county", + "county_fips", + "county_str", + "place_fips", + "puma", + "sldl", + "sldu", + "tract_geoid", + "vtd", + "zcta", + "zip_code", +) +COUNTY_FIPS_LENGTH = 5 +ETERNITY = "ETERNITY" +POSTAL_BY_FIPS = {fips: postal for postal, fips in US_STATE_FIPS.items()} +LISTED_COLUMNS = 10 + + +def _variable_of(column: str) -> str: + """The variable a ``variable__period`` column belongs to.""" + return column.rsplit("__", 1)[0] + + +def _columns_of(frame: pd.DataFrame, name: str) -> list[str]: + return [column for column in frame.columns if _variable_of(column) == name] + + +def _value_at(frame: pd.DataFrame, name: str, year: int) -> Optional[pd.Series]: + """The column of ``name`` that a run in ``year`` reads, carried forward.""" + readable = [] + for column in _columns_of(frame, name): + period = column.rsplit("__", 1)[1] + column_year = year if period == ETERNITY else int(period[:4]) + if column_year <= year: + readable.append((column_year, column)) + return frame[max(readable)[1]] if readable else None + + +def _with_periods(people: pd.DataFrame, year: int) -> pd.DataFrame: + """Name every column ``variable__period``, as the pinned loader expects.""" + frame = people.rename( + columns=lambda column: ( + str(column) if "__" in str(column) else f"{column}__{year}" + ) + ) + repeated = frame.columns[frame.columns.duplicated()].unique().tolist() + if repeated: + raise ValueError( + f"The file gives {', '.join(repeated)} more than once. Keep one column " + "for each variable and period." + ) + return frame + + +def _without_unknown_columns(frame: pd.DataFrame, variables) -> pd.DataFrame: + """Drop columns the model cannot read, and say so.""" + unknown = [ + column for column in frame.columns if _variable_of(column) not in variables + ] + if unknown: + listed = ", ".join(unknown[:LISTED_COLUMNS]) + more = len(unknown) - LISTED_COLUMNS + logging.warning( + f"The run ignores {len(unknown)} column(s) that name no PolicyEngine " + f"variable: {listed}{f' and {more} more' if more > 0 else ''}." + ) + return frame.drop(columns=unknown) + + +def _id_values(values: pd.Series, name: str) -> pd.Series: + """IDs as integers, the only form the model stores.""" + if values.isna().any(): + raise ValueError(f"{name} has blanks. Every row needs one.") + if pd.api.types.is_integer_dtype(values): + return values.astype("int64") + return pd.Series(pd.factorize(values, sort=True)[0], index=values.index) + + +def _with_person_level_ids(frame: pd.DataFrame, year: int) -> pd.DataFrame: + """Put each person's ID and group memberships on their own row.""" + memberships = {} + for group in GROUP_ENTITIES: + columns = _columns_of(frame, f"person_{group}_id") or _columns_of( + frame, f"{group}_id" + ) + if columns: + memberships[group] = _id_values(frame[columns[0]], f"{group}_id") + missing = [group for group in GROUP_ENTITIES if group not in memberships] + if missing: + names = ", ".join(f"{group}_id" for group in missing) + raise ValueError( + f"The file has no {names}. A flat file needs one of these on every " + "person's row to say who belongs together." + ) + + person_columns = _columns_of(frame, "person_id") + if person_columns: + persons = _id_values(frame[person_columns[0]], "person_id") + if persons.duplicated().any(): + raise ValueError("person_id repeats. A flat file holds one row per person.") + else: + persons = pd.Series(np.arange(len(frame)), index=frame.index) + + frame = frame.drop( + columns=[ + column for column in frame.columns if _variable_of(column) in ID_VARIABLES + ] + ) + identifiers = {f"person_id__{year}": persons} + for group, ids in memberships.items(): + identifiers[f"person_{group}_id__{year}"] = ids + return frame.assign(**identifiers) + + +def _county_text(value) -> str: + """A county FIPS code as five-digit text, or blank for no county. + + ``read_csv`` turns 06037 into 6037, or 6037.0 next to a blank. + """ + if pd.isna(value) or value == "": + return "" + if isinstance(value, bytes): + value = value.decode() + if isinstance(value, (float, np.floating)) and float(value).is_integer(): + value = int(value) + text = str(value).strip() + if not text.isdigit() or len(text) > COUNTY_FIPS_LENGTH: + raise ValueError(f"county_fips holds {value!r}, which is no county FIPS code.") + return text.zfill(COUNTY_FIPS_LENGTH) + + +def _with_text_counties(frame: pd.DataFrame) -> pd.DataFrame: + counties = { + column: frame[column].map(_county_text) + for column in _columns_of(frame, "county_fips") + } + return frame.assign(**counties) + + +def _state_fips(state: Union[str, int]) -> int: + """Read a postal code or a FIPS code as a FIPS code.""" + if isinstance(state, str) and state.upper() in US_STATE_FIPS: + return US_STATE_FIPS[state.upper()] + if state in POSTAL_BY_FIPS: + return int(state) + raise ValueError(f"{state!r} is neither a state postal code nor a state FIPS code.") + + +def _in_state(frame: pd.DataFrame, fips: int, year: int) -> pd.DataFrame: + """Move every household to one state, in every year the file holds.""" + frame = frame.drop( + columns=[ + column + for column in frame.columns + if _variable_of(column) in {*STATE_LABELS, *LOCAL_GEOGRAPHY} + ] + ) + state_columns = {f"state_fips__{year}", *_columns_of(frame, "state_fips")} + return frame.assign(**dict.fromkeys(state_columns, fips)) + + +def _require_coherent_geography(frame: pd.DataFrame, year: int) -> None: + """Check a file that keeps its own states, since nothing moves them here.""" + state = _value_at(frame, "state_fips", year) + if state is None: + raise ValueError( + f"The file has no state_fips for {year}, so every household would run " + "as California. Add the column, or pass state= to run them all in one " + "state." + ) + unknown = set(state.unique()) - set(POSTAL_BY_FIPS) + if unknown: + listed = ", ".join(sorted(str(value) for value in unknown)) + raise ValueError(f"state_fips holds {listed}, which name no state.") + + households = frame[f"person_household_id__{year}"] + if state.groupby(households).nunique().gt(1).any(): + raise ValueError("Some households span several values of state_fips.") + + county = _value_at(frame, "county_fips", year) + if county is not None: + known = county != "" + if county[known].str[:2].astype(int).ne(state[known]).any(): + raise ValueError( + "Some rows hold a county_fips outside their state_fips. Correct them, " + "or pass state= to run the file in one state, which clears county." + ) + + postal = state.map(POSTAL_BY_FIPS) + for label in STATE_LABELS: + stored = _value_at(frame, label, year) + if stored is not None and stored.astype(str).ne(postal).any(): + raise ValueError( + f"Some rows hold a {label} that disagrees with state_fips. Correct " + "them, or pass state= to run the file in one state." + ) + + +def prepare_flat_file( + people: pd.DataFrame, + *, + year: int, + state: Optional[Union[str, int]] = None, +) -> pd.DataFrame: + """Check a flat file and write it in the form the pinned loader reads. + + Args: + people: One row per person, with a group ID for each of the household, + tax unit, SPM unit, family and marital unit, plus ``age``. Columns + are named ``variable`` or ``variable__period``. ``person_id`` is + optional. The run ignores columns that name no variable, and logs + them. + year: The year the file describes. A column without a period holds that + year's value. + state: A postal code or FIPS code to run every household in. It applies + to every year the file holds, and clears stored state labels and all + geography finer than a state. Leave it unset to keep the file's own + ``state_fips``, which then has to agree with those columns. + + Returns: + A new frame, leaving ``people`` as it was. + """ + from policyengine_us.system import system + + if people.empty: + raise ValueError("The file has no rows.") + frame = _with_periods(people, year) + frame = _without_unknown_columns(frame, system.variables) + if _value_at(frame, "age", year) is None: + raise ValueError( + f"The file has no age for {year}, so everyone would run as a 40-year-old." + ) + frame = _with_person_level_ids(frame, year) + frame = _with_text_counties(frame) + if state is not None: + return _in_state(frame, _state_fips(state), year) + _require_coherent_geography(frame, year) + return frame + + +def flat_file_microsimulation( + people: pd.DataFrame, + *, + year: int, + state: Optional[Union[str, int]] = None, + spm: Optional[SPMSelection] = None, + **kwargs, +): + """Build a bundled ``Microsimulation`` over a researcher's own flat file. + + A file moved to a ``state`` has no county, so county-keyed rules use the + first county in that state, and SPM thresholds need + ``spm={"geography_kind": "national"}``. + + Args: + people: The flat file, as ``prepare_flat_file`` describes. + year: The year the file describes. + state: The state to run every household in, or ``None`` for the file's + own ``state_fips``. + spm: The SPM selection, which defaults to the bundle's. + **kwargs: Passed on to ``Microsimulation``, for example ``reform``. + + Returns: + A ``Microsimulation`` carrying this release's ``policyengine_bundle``. + """ + from policyengine_core.data import Dataset + from policyengine_us import Microsimulation + + if "dataset" in kwargs: + raise ValueError("flat_file_microsimulation builds its dataset from `people`.") + + prepared = prepare_flat_file(people, year=year, state=state) + microsim = Microsimulation( + dataset=Dataset.from_dataframe(prepared, year), + spm=resolve_spm_selection(spm), + **kwargs, + ) + microsim.policyengine_bundle = dict(us_latest.release_bundle) + microsim.policyengine_bundle.update( + build_runtime_dataset_provenance( + "flat_file", + "flat_file", + None, + logical_name="flat_file", + ) + ) + microsim.policyengine_bundle["spm"] = dict(microsim.spm_config) + return microsim diff --git a/tests/test_us_flat_file.py b/tests/test_us_flat_file.py new file mode 100644 index 000000000..c44bd1bbf --- /dev/null +++ b/tests/test_us_flat_file.py @@ -0,0 +1,337 @@ +"""A researcher's flat file runs through the pinned US model, state by state.""" + +import logging + +import numpy as np +import pandas as pd +import pytest +from hypothesis import HealthCheck, given, settings +from hypothesis import strategies as st + +pytest.importorskip("policyengine_us") + +import policyengine as pe # noqa: E402 +from policyengine.countries.us.data import US_STATE_FIPS # noqa: E402 +from policyengine.tax_benefit_models.us.flat_file import ( # noqa: E402 + LOCAL_GEOGRAPHY, + STATE_LABELS, + prepare_flat_file, +) + +YEAR = 2024 +NATIONAL_SPM = {"geography_kind": "national"} +MISSISSIPPI = 28 +LOS_ANGELES_COUNTY = "06037" +GROUP_COLUMNS = ( + "household_id", + "tax_unit_id", + "spm_unit_id", + "family_id", + "marital_unit_id", +) + + +def survey() -> pd.DataFrame: + return pd.DataFrame( + { + "person_id": [1, 2, 3, 4, 5, 6, 7], + "household_id": [1, 1, 2, 2, 2, 2, 3], + "tax_unit_id": [1, 1, 2, 2, 2, 2, 3], + "spm_unit_id": [1, 1, 2, 2, 2, 2, 3], + "family_id": [1, 1, 2, 2, 2, 2, 3], + "marital_unit_id": [1, 1, 2, 2, 4, 5, 6], + "age": [35, 5, 41, 39, 12, 9, 67], + "employment_income": [20000, 0, 45000, 10000, 0, 0, 12000], + "household_weight": [1000, 1000, 500, 500, 500, 500, 2000], + } + ) + + +def in_state(frame: pd.DataFrame, fips: int = 6) -> pd.DataFrame: + return frame.assign(state_fips=fips) + + +class TestPreparedColumns: + def test_leaves_the_input_alone(self): + people = in_state(survey()) + before = people.copy() + prepare_flat_file(people, year=YEAR, state="MS") + pd.testing.assert_frame_equal(people, before) + + def test_bare_columns_take_the_year(self): + prepared = prepare_flat_file(in_state(survey()), year=YEAR) + assert f"age__{YEAR}" in prepared.columns + assert "age" not in prepared.columns + + def test_a_period_stays_on_its_column(self): + people = in_state(survey()).assign(is_household_head__ETERNITY=False) + prepared = prepare_flat_file(people, year=YEAR) + assert "is_household_head__ETERNITY" in prepared.columns + + def test_group_ids_move_onto_each_persons_row(self): + prepared = prepare_flat_file(in_state(survey()), year=YEAR) + for column in GROUP_COLUMNS: + assert f"{column}__{YEAR}" not in prepared.columns + assert ( + prepared[f"person_{column}__{YEAR}"].tolist() + == survey()[column].tolist() + ) + + def test_an_export_with_many_id_columns_settles_on_one(self): + people = in_state(survey()).rename( + columns={"household_id": "household_id__ETERNITY"} + ) + people[f"person_household_id__{YEAR}"] = people["household_id__ETERNITY"] + prepared = prepare_flat_file(people, year=YEAR) + ids = [column for column in prepared if "household_id" in column] + assert ids == [f"person_household_id__{YEAR}"] + + def test_text_ids_become_integers_that_keep_the_groups(self): + people = in_state(survey()) + people["household_id"] = people["household_id"].map( + {1: "A-17", 2: "B-02", 3: "C-99"} + ) + prepared = prepare_flat_file(people, year=YEAR) + ids = prepared[f"person_household_id__{YEAR}"] + assert pd.api.types.is_integer_dtype(ids) + assert ids.tolist() == [0, 0, 1, 1, 1, 1, 2] + + def test_a_person_id_is_optional(self): + people = in_state(survey()).drop(columns="person_id") + prepared = prepare_flat_file(people, year=YEAR) + assert prepared[f"person_id__{YEAR}"].nunique() == len(people) + + def test_unknown_columns_leave_with_a_log(self, caplog): + people = in_state(survey()).assign(**{"survey_stratum": 3, "foo__bar__2024": 1}) + with caplog.at_level(logging.WARNING): + prepared = prepare_flat_file(people, year=YEAR) + assert "survey_stratum" in caplog.text + assert "foo__bar__2024" in caplog.text + assert not any("foo" in column for column in prepared) + + @pytest.mark.parametrize( + "value, text", + [ + (6037, LOS_ANGELES_COUNTY), + (6037.0, LOS_ANGELES_COUNTY), + ("6037", LOS_ANGELES_COUNTY), + (LOS_ANGELES_COUNTY, LOS_ANGELES_COUNTY), + (np.nan, ""), + ("", ""), + ], + ) + def test_a_county_becomes_five_digit_text(self, value, text): + people = in_state(survey()).assign(county_fips=value) + prepared = prepare_flat_file(people, year=YEAR) + assert set(prepared[f"county_fips__{YEAR}"]) == {text} + + +class TestRefusals: + def test_no_rows(self): + with pytest.raises(ValueError, match="no rows"): + prepare_flat_file(survey().iloc[:0], year=YEAR, state="MS") + + @pytest.mark.parametrize("column", GROUP_COLUMNS) + def test_a_missing_group_names_its_column(self, column): + people = in_state(survey()).drop(columns=column) + with pytest.raises(ValueError, match=column): + prepare_flat_file(people, year=YEAR) + + def test_a_blank_id(self): + people = in_state(survey()).astype({"household_id": float}) + people.loc[0, "household_id"] = np.nan + with pytest.raises(ValueError, match="blanks"): + prepare_flat_file(people, year=YEAR) + + def test_a_person_on_two_rows(self): + people = in_state(survey()).assign(person_id=1) + with pytest.raises(ValueError, match="one row per person"): + prepare_flat_file(people, year=YEAR) + + def test_no_age(self): + with pytest.raises(ValueError, match="age"): + prepare_flat_file(in_state(survey()).drop(columns="age"), year=YEAR) + + def test_an_age_only_from_later_years(self): + people = in_state(survey()).rename(columns={"age": f"age__{YEAR + 1}"}) + with pytest.raises(ValueError, match="age"): + prepare_flat_file(people, year=YEAR) + + def test_a_variable_given_twice(self): + people = in_state(survey()).assign(**{f"age__{YEAR}": 40}) + with pytest.raises(ValueError, match="more than once"): + prepare_flat_file(people, year=YEAR) + + def test_no_state(self): + with pytest.raises(ValueError, match="California"): + prepare_flat_file(survey(), year=YEAR) + + def test_a_state_that_does_not_exist(self): + with pytest.raises(ValueError, match="99"): + prepare_flat_file(in_state(survey(), 99), year=YEAR) + + @pytest.mark.parametrize("state", ["ZZ", 99, ""]) + def test_a_requested_state_that_does_not_exist(self, state): + with pytest.raises(ValueError, match="postal code"): + prepare_flat_file(survey(), year=YEAR, state=state) + + def test_a_household_across_states(self): + people = in_state(survey()) + people.loc[0, "state_fips"] = MISSISSIPPI + with pytest.raises(ValueError, match="span"): + prepare_flat_file(people, year=YEAR) + + def test_a_county_outside_its_state(self): + people = in_state(survey(), MISSISSIPPI).assign(county_fips=LOS_ANGELES_COUNTY) + with pytest.raises(ValueError, match="outside"): + prepare_flat_file(people, year=YEAR) + + def test_a_label_that_disagrees_with_the_state(self): + people = in_state(survey(), MISSISSIPPI).assign(state_code="CA") + with pytest.raises(ValueError, match="state_code"): + prepare_flat_file(people, year=YEAR) + + def test_a_malformed_county(self): + people = in_state(survey()).assign(county_fips="Los Angeles") + with pytest.raises(ValueError, match="county_fips"): + prepare_flat_file(people, year=YEAR) + + +class TestMovingToAState: + def test_a_file_may_start_with_no_state(self): + prepared = prepare_flat_file(survey(), year=YEAR, state="MS") + assert set(prepared[f"state_fips__{YEAR}"]) == {MISSISSIPPI} + + def test_postal_code_and_fips_agree(self): + pd.testing.assert_frame_equal( + prepare_flat_file(survey(), year=YEAR, state="ms"), + prepare_flat_file(survey(), year=YEAR, state=MISSISSIPPI), + ) + + def test_every_year_moves(self): + people = in_state(survey()).assign( + **{f"state_fips__{year}": 6 for year in (YEAR, YEAR + 1, YEAR + 2)} + ) + people = people.drop(columns="state_fips") + prepared = prepare_flat_file(people, year=YEAR, state="MS") + columns = [column for column in prepared if column.startswith("state_fips")] + assert len(columns) == 3 + assert set(prepared[columns].to_numpy().ravel()) == {MISSISSIPPI} + + def test_stale_geography_leaves(self): + stale = {f"{name}__{YEAR}": "x" for name in (*STATE_LABELS, *LOCAL_GEOGRAPHY)} + stale.pop(f"county_fips__{YEAR}") + prepared = prepare_flat_file( + survey().assign(**stale, county_fips=LOS_ANGELES_COUNTY), + year=YEAR, + state="MS", + ) + for name in (*STATE_LABELS, *LOCAL_GEOGRAPHY): + assert not any(column.startswith(f"{name}__") for column in prepared) + + +@settings(max_examples=40, suppress_health_check=[HealthCheck.too_slow]) +@given(st.integers(min_value=1, max_value=99_999)) +def test_any_county_code_reads_the_same_as_text_or_number(code): + """County codes survive whichever form read_csv left them in.""" + from_number = prepare_flat_file( + in_state(survey(), 6).assign(county_fips=code), year=YEAR, state="CA" + ) + from_text = prepare_flat_file( + in_state(survey(), 6).assign(county_fips=f"{code:05d}"), year=YEAR, state="CA" + ) + pd.testing.assert_frame_equal(from_number, from_text) + + +@settings(max_examples=40, suppress_health_check=[HealthCheck.too_slow]) +@given( + st.sampled_from(sorted(US_STATE_FIPS)), + st.sampled_from(sorted(US_STATE_FIPS)), +) +def test_moving_a_file_twice_lands_where_moving_it_once_does(first, second): + """Preparation forgets the old state entirely, and keeps everything else.""" + once = prepare_flat_file(survey(), year=YEAR, state=second) + twice = prepare_flat_file( + prepare_flat_file(survey(), year=YEAR, state=first), + year=YEAR, + state=second, + ) + pd.testing.assert_frame_equal(once[sorted(once)], twice[sorted(twice)]) + + +@settings(max_examples=40, suppress_health_check=[HealthCheck.too_slow]) +@given(st.sampled_from(sorted(US_STATE_FIPS))) +def test_a_prepared_file_prepares_to_itself(state): + """Preparing a file with its own state changes nothing.""" + prepared = prepare_flat_file(survey(), year=YEAR, state=state) + again = prepare_flat_file(prepared, year=YEAR) + pd.testing.assert_frame_equal(prepared[sorted(prepared)], again[sorted(again)]) + + +@pytest.mark.parametrize("state", ["CA", "MS", "MN"]) +def test_the_recipe_runs_a_csv_through_a_state(tmp_path, state): + path = tmp_path / "your_survey.csv" + survey().to_csv(path, index=False) + people = pd.read_csv(path, dtype={"county_fips": str}) + + sim = pe.us.flat_file_microsimulation( + people, year=YEAR, state=state, spm=NATIONAL_SPM + ) + + assert set(sim.calculate("state_code", YEAR).values) == {state} + assert set(sim.calculate("state_code", YEAR + 1).values) == {state} + assert 0 <= sim.calculate("is_snap_eligible", f"{YEAR}-01").mean() <= 1 + assert sim.calculate("spm_unit_spm_threshold", YEAR).sum() > 0 + assert sim.populations["household"].count == 3 + assert sim.populations["marital_unit"].count == 5 + assert sim.policyengine_bundle["runtime_dataset"] == "flat_file" + assert sim.policyengine_bundle["spm"]["geography_kind"] == "national" + + +def test_stale_geography_changes_nothing_after_a_move(): + """A file with stale geography runs as one that never had it.""" + stale = survey().assign( + county_fips=LOS_ANGELES_COUNTY, + zip_code="90001", + state_code="CA", + congressional_district_geoid=634, + ) + arms = [ + pe.us.flat_file_microsimulation(people, year=YEAR, state="MS", spm=NATIONAL_SPM) + for people in (stale, survey()) + ] + for variable, period in [ + ("state_income_tax", YEAR), + ("household_net_income", YEAR), + ("is_snap_eligible", f"{YEAR}-01"), + ]: + first, second = (arm.calculate(variable, period).values for arm in arms) + assert np.array_equal(first, second), variable + + +def test_a_county_keyed_rule_runs_after_a_move(): + people = survey().assign(county_fips=LOS_ANGELES_COUNTY) + sim = pe.us.flat_file_microsimulation(people, year=YEAR, state="MN") + assert set(sim.calculate("county", YEAR).values) == {"AITKIN_COUNTY_MN"} + sim.calculate("mn_ccap_provider_rate", f"{YEAR}-01") + + +def test_a_file_keeps_its_own_states(): + fips = {1: 6, 2: MISSISSIPPI, 3: 36} + people = survey().assign(state_fips=survey()["household_id"].map(fips)) + sim = pe.us.flat_file_microsimulation(people, year=YEAR, spm=NATIONAL_SPM) + assert sim.calculate("state_code", YEAR).values.tolist() == ["CA", "MS", "NY"] + + +def test_keywords_reach_the_simulation(): + reform = {"gov.irs.credits.ctc.amount.base[0].amount": {"2024-01-01": 9000}} + sim = pe.us.flat_file_microsimulation( + survey(), year=YEAR, state="MS", spm=NATIONAL_SPM, reform=reform + ) + reformed = sim.calculate("ctc", YEAR).sum() + assert reformed > sim.baseline.calculate("ctc", YEAR).sum() + + +def test_a_dataset_is_refused(): + with pytest.raises(ValueError, match="people"): + pe.us.flat_file_microsimulation(survey(), year=YEAR, dataset="other.h5") From 236b34214e032cfe8156582ccaa9fed7df3c4ac8 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 1 Nov 2026 17:25:55 -0500 Subject: [PATCH 02/14] Satisfy the repository's isinstance lint rule Co-Authored-By: Claude Opus 5.5 --- src/policyengine/tax_benefit_models/us/flat_file.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/policyengine/tax_benefit_models/us/flat_file.py b/src/policyengine/tax_benefit_models/us/flat_file.py index 5828c072e..b48ae4915 100644 --- a/src/policyengine/tax_benefit_models/us/flat_file.py +++ b/src/policyengine/tax_benefit_models/us/flat_file.py @@ -164,7 +164,7 @@ def _county_text(value) -> str: return "" if isinstance(value, bytes): value = value.decode() - if isinstance(value, (float, np.floating)) and float(value).is_integer(): + if isinstance(value, float | np.floating) and float(value).is_integer(): value = int(value) text = str(value).strip() if not text.isdigit() or len(text) > COUNTY_FIPS_LENGTH: From b2a6b624df3659595733ee949525b7a0d4291544 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 1 Nov 2026 17:37:44 -0500 Subject: [PATCH 03/14] Refuse flat files that would load with silently wrong groups Group IDs numbered within households merge strangers, and rows of one group that disagree lose all but the first person's value. Neither raises at load. Co-Authored-By: Claude Opus 5.5 --- docs/simulated-instruments.md | 4 +- .../tax_benefit_models/us/flat_file.py | 60 +++++++++++++++---- tests/test_us_flat_file.py | 41 ++++++++++++- 3 files changed, 89 insertions(+), 16 deletions(-) diff --git a/docs/simulated-instruments.md b/docs/simulated-instruments.md index a3d0552bb..cdde7bfca 100644 --- a/docs/simulated-instruments.md +++ b/docs/simulated-instruments.md @@ -34,7 +34,7 @@ The file holds one row per person. Name a column after a variable, or `variable_ | Column | Needed | Notes | | --- | --- | --- | -| `household_id`, `tax_unit_id`, `spm_unit_id`, `family_id`, `marital_unit_id` | Yes | Put each on every person's row. Text IDs work. | +| `household_id`, `tax_unit_id`, `spm_unit_id`, `family_id`, `marital_unit_id` | Yes | Put each on every person's row, numbered across the whole file. Text IDs work. | | `age` | Yes | Without it, everyone runs as 40. | | `state_fips` | Unless you pass `state` | Without it, everyone runs as California. | | `person_id` | No | The helper numbers the rows if you leave it out. | @@ -42,7 +42,7 @@ The file holds one row per person. Name a column after a variable, or `variable_ | Income and other inputs | As your measure needs | Inputs you omit take their defaults, usually zero. | | `county_fips` | No | Read it as text so that 06037 keeps its leading zero. The helper repairs 6037 either way. | -`prepare_flat_file` runs these checks and returns the frame the simulation loads, so you can inspect it. It refuses a file that lacks a required column, repeats a `person_id`, puts one household in two states, or holds a county outside its state. It logs columns that name no variable, then ignores them. +`prepare_flat_file` runs these checks and returns the frame the simulation loads, so you can inspect it. It refuses a file that lacks a required column, repeats a `person_id`, numbers groups within each household, gives one group's rows different values for a group-level variable such as `household_weight`, or holds a county outside its state. It logs columns that name no variable, then ignores them. ## What a state change clears diff --git a/src/policyengine/tax_benefit_models/us/flat_file.py b/src/policyengine/tax_benefit_models/us/flat_file.py index b48ae4915..3361a8212 100644 --- a/src/policyengine/tax_benefit_models/us/flat_file.py +++ b/src/policyengine/tax_benefit_models/us/flat_file.py @@ -36,7 +36,8 @@ } ) STATE_LABELS = ("state_code", "state_code_str", "state_name") -# Geography finer than a state, which means nothing in another state. +# Geography finer than a state, and what the model derives from it. Neither means +# anything in another state. LOCAL_GEOGRAPHY = ( "block_geoid", "cbsa_code", @@ -44,10 +45,14 @@ "county", "county_fips", "county_str", + "in_ny_mctd_zone_2", + "in_nyc", + "medicaid_rating_area", "place_fips", "puma", "sldl", "sldu", + "three_digit_zip_code", "tract_geoid", "vtd", "zcta", @@ -73,9 +78,10 @@ def _value_at(frame: pd.DataFrame, name: str, year: int) -> Optional[pd.Series]: readable = [] for column in _columns_of(frame, name): period = column.rsplit("__", 1)[1] - column_year = year if period == ETERNITY else int(period[:4]) - if column_year <= year: - readable.append((column_year, column)) + if period == ETERNITY: + readable.append((year, column)) + elif period[:4].isdigit() and int(period[:4]) <= year: + readable.append((int(period[:4]), column)) return frame[max(readable)[1]] if readable else None @@ -155,6 +161,37 @@ def _with_person_level_ids(frame: pd.DataFrame, year: int) -> pd.DataFrame: return frame.assign(**identifiers) +def _require_groups_within_households(frame: pd.DataFrame, year: int) -> None: + """Refuse IDs numbered within households, which would merge strangers.""" + households = frame[f"person_household_id__{year}"] + for group in GROUP_ENTITIES: + ids = frame[f"person_{group}_id__{year}"] + if households.groupby(ids).nunique().gt(1).any(): + raise ValueError( + f"Some {group}_id values span several households. Number each " + f"{group} across the whole file, not within its household." + ) + + +def _require_group_values_agree(frame: pd.DataFrame, year: int, variables) -> None: + """Refuse a group's rows that disagree, since the first row would win.""" + by_group = {} + for column in frame.columns: + group = variables[_variable_of(column)].entity.key + if group in GROUP_ENTITIES: + by_group.setdefault(group, []).append(column) + for group, columns in by_group.items(): + ids = frame[f"person_{group}_id__{year}"] + spread = frame[columns].groupby(ids, sort=False).nunique().max() + disagreeing = spread[spread > 1].index.tolist() + if disagreeing: + listed = ", ".join(disagreeing[:LISTED_COLUMNS]) + raise ValueError( + f"The rows of one {group} disagree on {listed}, which hold one " + f"value per {group}. Give each person the {group}'s value." + ) + + def _county_text(value) -> str: """A county FIPS code as five-digit text, or blank for no county. @@ -184,7 +221,7 @@ def _state_fips(state: Union[str, int]) -> int: """Read a postal code or a FIPS code as a FIPS code.""" if isinstance(state, str) and state.upper() in US_STATE_FIPS: return US_STATE_FIPS[state.upper()] - if state in POSTAL_BY_FIPS: + if not isinstance(state, bool) and state in POSTAL_BY_FIPS: return int(state) raise ValueError(f"{state!r} is neither a state postal code nor a state FIPS code.") @@ -216,10 +253,6 @@ def _require_coherent_geography(frame: pd.DataFrame, year: int) -> None: listed = ", ".join(sorted(str(value) for value in unknown)) raise ValueError(f"state_fips holds {listed}, which name no state.") - households = frame[f"person_household_id__{year}"] - if state.groupby(households).nunique().gt(1).any(): - raise ValueError("Some households span several values of state_fips.") - county = _value_at(frame, "county_fips", year) if county is not None: known = county != "" @@ -274,10 +307,13 @@ def prepare_flat_file( f"The file has no age for {year}, so everyone would run as a 40-year-old." ) frame = _with_person_level_ids(frame, year) + _require_groups_within_households(frame, year) frame = _with_text_counties(frame) - if state is not None: - return _in_state(frame, _state_fips(state), year) - _require_coherent_geography(frame, year) + if state is None: + _require_coherent_geography(frame, year) + else: + frame = _in_state(frame, _state_fips(state), year) + _require_group_values_agree(frame, year, system.variables) return frame diff --git a/tests/test_us_flat_file.py b/tests/test_us_flat_file.py index c44bd1bbf..d9af999ef 100644 --- a/tests/test_us_flat_file.py +++ b/tests/test_us_flat_file.py @@ -170,7 +170,7 @@ def test_a_state_that_does_not_exist(self): with pytest.raises(ValueError, match="99"): prepare_flat_file(in_state(survey(), 99), year=YEAR) - @pytest.mark.parametrize("state", ["ZZ", 99, ""]) + @pytest.mark.parametrize("state", ["ZZ", 99, "", True]) def test_a_requested_state_that_does_not_exist(self, state): with pytest.raises(ValueError, match="postal code"): prepare_flat_file(survey(), year=YEAR, state=state) @@ -178,7 +178,18 @@ def test_a_requested_state_that_does_not_exist(self, state): def test_a_household_across_states(self): people = in_state(survey()) people.loc[0, "state_fips"] = MISSISSIPPI - with pytest.raises(ValueError, match="span"): + with pytest.raises(ValueError, match="state_fips"): + prepare_flat_file(people, year=YEAR) + + def test_a_group_numbered_within_its_household(self): + people = in_state(survey()).assign(tax_unit_id=1) + with pytest.raises(ValueError, match="tax_unit_id values span"): + prepare_flat_file(people, year=YEAR) + + def test_a_household_value_that_varies_within_the_household(self): + people = in_state(survey()) + people.loc[0, "household_weight"] = 7 + with pytest.raises(ValueError, match="household_weight"): prepare_flat_file(people, year=YEAR) def test_a_county_outside_its_state(self): @@ -218,6 +229,11 @@ def test_every_year_moves(self): assert len(columns) == 3 assert set(prepared[columns].to_numpy().ravel()) == {MISSISSIPPI} + def test_a_moved_file_may_hold_one_stale_county_per_person(self): + people = survey().assign(county_fips=[f"{index:05d}" for index in range(7)]) + prepared = prepare_flat_file(people, year=YEAR, state="MS") + assert not any(column.startswith("county_fips") for column in prepared) + def test_stale_geography_leaves(self): stale = {f"{name}__{YEAR}": "x" for name in (*STATE_LABELS, *LOCAL_GEOGRAPHY)} stale.pop(f"county_fips__{YEAR}") @@ -309,6 +325,27 @@ def test_stale_geography_changes_nothing_after_a_move(): assert np.array_equal(first, second), variable +def test_national_thresholds_do_not_depend_on_the_state(): + thresholds = [ + pe.us.flat_file_microsimulation( + survey(), year=YEAR, state=state, spm=NATIONAL_SPM + ) + .calculate("spm_unit_spm_threshold", YEAR) + .values + for state in ("CA", "MS") + ] + assert np.array_equal(*thresholds) + + +def test_a_year_before_the_file_falls_back_to_defaults(): + sim = pe.us.flat_file_microsimulation( + survey(), year=YEAR, state="MS", spm=NATIONAL_SPM + ) + assert set(sim.calculate("state_code", YEAR - 1).values) == {"CA"} + assert set(sim.calculate("age", YEAR - 1).values) == {40} + assert sim.calculate("employment_income", YEAR - 1).sum() == 0 + + def test_a_county_keyed_rule_runs_after_a_move(): people = survey().assign(county_fips=LOS_ANGELES_COUNTY) sim = pe.us.flat_file_microsimulation(people, year=YEAR, state="MN") From 7d4fde88009b0ec6dec92bb23449d9ff7837f027 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 2 Nov 2026 03:37:26 -0500 Subject: [PATCH 04/14] Keep groups in file order and refuse geography in any year The pinned loader sorts groups by ID but reads a one-row-per-group column in row order, so one-person groups in any other order took each other's values. Number memberships in file order, and keep the file's own IDs in {group}_id so results merge back on them. Check geography across every year the file holds, including county names and tract, block and district columns, and drop stored copies of what the model derives from the state. Record the year, state and a digest with the run, and rewrite the recipe around what the trial found unclear. Co-Authored-By: Claude Opus 5.5 --- docs/simulated-instruments.md | 63 +++++- .../tax_benefit_models/us/flat_file.py | 207 +++++++++++++++--- tests/test_us_flat_file.py | 202 ++++++++++++++++- 3 files changed, 412 insertions(+), 60 deletions(-) diff --git a/docs/simulated-instruments.md b/docs/simulated-instruments.md index cdde7bfca..18faf19e4 100644 --- a/docs/simulated-instruments.md +++ b/docs/simulated-instruments.md @@ -24,25 +24,61 @@ for state in US_STATE_FIPS: snap_eligible[state] = sim.calculate("is_snap_eligible", "2024-01").mean() ``` -`state` takes a postal code or a FIPS code. `calculate` returns a weighted series, so `mean()` gives the weighted share of SPM units. Pass `reform=` to run a reform in every state, and read the baseline arm from `sim.baseline`. +`US_STATE_FIPS` maps postal codes to FIPS codes for the 50 states and DC, so the loop runs 51 times. `state` takes a postal code or a FIPS code. -To run each household in the state your file records, leave `state` out. The file then needs `state_fips`, and any county or state label it holds has to agree with `state_fips`. +`calculate` returns a weighted series, and `mean()` gives a weighted share of the variable's own entity: SPM units for `is_snap_eligible`, people for `is_medicaid_eligible`. A monthly variable such as `is_snap_eligible` takes a month, and an annual one such as `state_income_tax` takes a year. + +Pass `reform=` to run a reform in every state, and read the baseline arm from `sim.baseline`. + +To run each household in the state your file records, leave `state` out. The file then needs `state_fips`. ## What your file needs -The file holds one row per person. Name a column after a variable, or `variable__period` to date it. A column with no period holds the value for `year`. +The file holds one row per person. Name a column after a PolicyEngine variable, or `variable__period` to date it. A column with no period holds the value for `year`. | Column | Needed | Notes | | --- | --- | --- | -| `household_id`, `tax_unit_id`, `spm_unit_id`, `family_id`, `marital_unit_id` | Yes | Put each on every person's row, numbered across the whole file. Text IDs work. | -| `age` | Yes | Without it, everyone runs as 40. | -| `state_fips` | Unless you pass `state` | Without it, everyone runs as California. | +| `household_id`, `tax_unit_id`, `spm_unit_id`, `family_id`, `marital_unit_id` | Yes | Put each on every person's row, numbered across the whole file. | +| `age` | Yes | The helper refuses a file without it, which would otherwise run everyone as 40. | +| `state_fips` | Unless you pass `state` | The helper refuses a file with neither, which would otherwise run everyone as California. | | `person_id` | No | The helper numbers the rows if you leave it out. | | `household_weight` | No | Every household weighs 1 without it. | -| Income and other inputs | As your measure needs | Inputs you omit take their defaults, usually zero. | -| `county_fips` | No | Read it as text so that 06037 keeps its leading zero. The helper repairs 6037 either way. | +| `employment_income` and other inputs | As your measure needs | Give each in its variable's period: `employment_income` holds annual dollars. Inputs you omit take their defaults, usually zero. | +| `county_fips` | No | Read it as text so that 06037 keeps its leading zero. The helper repairs 6037 either way, and reads a blank as no county. | + +A survey that restarts a group's ID in each household needs one number per group first: + +```python +for column in ["tax_unit_id", "spm_unit_id", "family_id", "marital_unit_id"]: + people[column] = people.groupby(["household_id", column]).ngroup() +``` + +To see what the simulation loads, run the checks on their own: + +```python +prepared = pe.us.prepare_flat_file(people, year=2024, state="MS") +``` -`prepare_flat_file` runs these checks and returns the frame the simulation loads, so you can inspect it. It refuses a file that lacks a required column, repeats a `person_id`, numbers groups within each household, gives one group's rows different values for a group-level variable such as `household_weight`, or holds a county outside its state. It logs columns that name no variable, then ignores them. +`prepare_flat_file` refuses a file that: + +- lacks a required column +- repeats a `person_id` +- numbers groups within each household +- gives one group's rows different values for a group-level variable such as `household_weight` + +With `state` left out, it also refuses a county, tract, block, congressional district or state label that contradicts `state_fips` in any year the file holds. With `state` set, those columns leave instead, so they cannot contradict it. + +It logs two things as warnings, which Python prints by default: columns that name no variable, which the run ignores, and county codes that name no county, which fall back to the first county in the state. + +## Reading results back + +Each person-level result follows the rows of your file. Group-level results come back in the order your file first names each group, so pass `map_to="person"` for one value per row: + +```python +people["state_tax"] = sim.calculate("state_income_tax", 2024, map_to="person").values +``` + +`map_to="person"` repeats a group's value on each member's row, so a sum across rows counts it once per member. `sim.calculate("household_id", 2024)` holds your own IDs, which also lets you merge group results back. The helper replaces IDs that are text or exceed 2,147,483,647 with their order in the file, and logs the large ones. ## What a state change clears @@ -50,12 +86,15 @@ Passing `state` sets `state_fips` in every year your file holds. It also removes With no county, the model applies county-keyed rules using the first county in the state alphabetically, such as Aitkin County in Minnesota. SPM thresholds use county in the default selection, so select `{"geography_kind": "national"}` as the recipe does. The selection applies to every state, which keeps thresholds identical across the loop. To keep real counties, leave `state` out and run each household where the file records it. +With or without `state`, the helper removes stored copies of what the model derives from the state, such as `state_group`, so the model's formulas run. + ## What to watch for -- **Years before your file.** A run reads later years from your file's last value, but an earlier year falls back to defaults. A 2024 file read for 2023 runs everyone as California at age 40, with no income. -- **Medicaid dollars.** `medicaid` spreads each state's total spending across the weighted people the file puts in that state, so a small file gets very large amounts per person. Measure eligibility with `is_medicaid_eligible`. The same applies to `healthcare_benefit_value`. +- **Years after your file.** A run carries your file's last value forward, and uprates the inputs that have an uprating rule. $20,000 of 2024 earnings reads as $20,987 in 2025, and a weight of 1,000 reads as 1,009. +- **Years before your file.** An earlier year falls back to defaults. A 2024 file read for 2023 runs everyone as California at age 40, with no income. +- **Medicaid dollars.** `medicaid` spreads each state's total spending across the weighted enrollees the file puts in that state, so a small file gets very large amounts per person. Measure eligibility with `is_medicaid_eligible`. The same applies to `healthcare_benefit_value`. - **Deciles.** Income deciles rank households within your file, not within the US. -- **Minors on their own.** The SPM calculation needs someone aged 18 or over in each SPM unit, or someone aged 15 to 17 with `is_household_head`, `is_household_spouse` or `is_spm_independent_minor_role` set. Those columns hold for all time, so `to_input_dataframe` names them `variable__ETERNITY`. Keep that suffix when you filter an export to one year. +- **Minors on their own.** The SPM calculation needs someone aged 18 or over in each SPM unit, or someone aged 15 to 17 with `is_household_head`, `is_household_spouse` or `is_spm_independent_minor_role` set. Those columns hold for all time, so `sim.to_input_dataframe()`, which writes a simulation's inputs back out as a flat file, names them `variable__ETERNITY`. Keep that suffix when you filter an export to one year. - **Changing state after the build.** `sim.set_input("state_fips", ...)` leaves stored geography in place. Pass `state` so that the helper clears it first. `policyengine.py` runs against the country model versions this release pins. Text variables such as `state_code_str` do not map to group entities in these versions, so calculate them at the household level. diff --git a/src/policyengine/tax_benefit_models/us/flat_file.py b/src/policyengine/tax_benefit_models/us/flat_file.py index 3361a8212..dfa5abb8e 100644 --- a/src/policyengine/tax_benefit_models/us/flat_file.py +++ b/src/policyengine/tax_benefit_models/us/flat_file.py @@ -11,6 +11,7 @@ correctly, ``variable__period``, with each person's groups on their own row. """ +import hashlib import logging from typing import Optional, Union @@ -39,6 +40,7 @@ # Geography finer than a state, and what the model derives from it. Neither means # anything in another state. LOCAL_GEOGRAPHY = ( + "average_home_energy_use_in_state", "block_geoid", "cbsa_code", "congressional_district_geoid", @@ -58,10 +60,34 @@ "zcta", "zip_code", ) +# What the model derives from the state. A stored value hides the formula, so +# these never reach a run. The model names its in-state flags by postal code. +DERIVED_FROM_STATE = frozenset( + { + "spm_unit_state_fips", + "state_group", + "state_group_str", + "tax_unit_state", + *US_STATE_FIPS, + } +) COUNTY_FIPS_LENGTH = 5 +GEOID_LENGTHS = { + "block_geoid": 15, + "county_fips": COUNTY_FIPS_LENGTH, + "tract_geoid": 11, +} +COUNTY_NAMES = ("county", "county_str") +STATE_NAMING_GEOGRAPHY = ( + *GEOID_LENGTHS, + *COUNTY_NAMES, + "congressional_district_geoid", +) ETERNITY = "ETERNITY" +LATEST_YEAR = 9999 POSTAL_BY_FIPS = {fips: postal for postal, fips in US_STATE_FIPS.items()} LISTED_COLUMNS = 10 +LARGEST_STORED_ID = 2**31 - 1 def _variable_of(column: str) -> str: @@ -73,15 +99,21 @@ def _columns_of(frame: pd.DataFrame, name: str) -> list[str]: return [column for column in frame.columns if _variable_of(column) == name] +def _year_of(column: str) -> Optional[int]: + """The year a dated column starts, or ``None`` for one with no year.""" + period = column.rsplit("__", 1)[1] + return int(period[:4]) if period[:4].isdigit() else None + + def _value_at(frame: pd.DataFrame, name: str, year: int) -> Optional[pd.Series]: """The column of ``name`` that a run in ``year`` reads, carried forward.""" readable = [] for column in _columns_of(frame, name): - period = column.rsplit("__", 1)[1] - if period == ETERNITY: + column_year = _year_of(column) + if column.endswith(f"__{ETERNITY}"): readable.append((year, column)) - elif period[:4].isdigit() and int(period[:4]) <= year: - readable.append((int(period[:4]), column)) + elif column_year is not None and column_year <= year: + readable.append((column_year, column)) return frame[max(readable)[1]] if readable else None @@ -117,20 +149,44 @@ def _without_unknown_columns(frame: pd.DataFrame, variables) -> pd.DataFrame: def _id_values(values: pd.Series, name: str) -> pd.Series: - """IDs as integers, the only form the model stores.""" + """IDs as integers, the only form the model stores. + + The model stores them in 32 bits, so anything else takes its place in the + file instead. + """ if values.isna().any(): raise ValueError(f"{name} has blanks. Every row needs one.") + if pd.api.types.is_float_dtype(values) and values.mod(1).eq(0).all(): + values = values.astype("int64") if pd.api.types.is_integer_dtype(values): - return values.astype("int64") - return pd.Series(pd.factorize(values, sort=True)[0], index=values.index) + if values.abs().max() <= LARGEST_STORED_ID: + return values.astype("int64") + logging.warning( + f"{name} holds values too large to store, so the run numbers them in " + "file order." + ) + return pd.Series(pd.factorize(values)[0], index=values.index) + + +def _in_file_order(ids: pd.Series) -> pd.Series: + """Number groups in the order the file first names them. + + The pinned loader sorts groups by ID, but reads a column with one row per + group in row order, so one-person groups in any other order would each take + another's values. In file order the two agree, for every entity at once. + """ + return pd.Series(pd.factorize(ids)[0], index=ids.index) def _with_person_level_ids(frame: pd.DataFrame, year: int) -> pd.DataFrame: - """Put each person's ID and group memberships on their own row.""" + """Put each person's ID and group memberships on their own row. + + ``{group}_id`` keeps the file's own IDs, so results merge back on them. + """ memberships = {} for group in GROUP_ENTITIES: - columns = _columns_of(frame, f"person_{group}_id") or _columns_of( - frame, f"{group}_id" + columns = _columns_of(frame, f"{group}_id") or _columns_of( + frame, f"person_{group}_id" ) if columns: memberships[group] = _id_values(frame[columns[0]], f"{group}_id") @@ -157,7 +213,8 @@ def _with_person_level_ids(frame: pd.DataFrame, year: int) -> pd.DataFrame: ) identifiers = {f"person_id__{year}": persons} for group, ids in memberships.items(): - identifiers[f"person_{group}_id__{year}"] = ids + identifiers[f"{group}_id__{year}"] = ids + identifiers[f"person_{group}_id__{year}"] = _in_file_order(ids) return frame.assign(**identifiers) @@ -217,11 +274,29 @@ def _with_text_counties(frame: pd.DataFrame) -> pd.DataFrame: return frame.assign(**counties) +def _warn_about_unknown_counties(frame: pd.DataFrame) -> None: + """Say when a code names no county, because the model falls back silently.""" + from policyengine_us.tools.geography.county_helpers import ( + load_county_fips_dataset, + ) + + held = set() + for column in _columns_of(frame, "county_fips"): + held |= set(frame[column].unique()) - {""} + unknown = held - set(load_county_fips_dataset()["county_fips"]) if held else held + if unknown: + logging.warning( + f"county_fips holds {len(unknown)} code(s) that name no county, such as " + f"{min(unknown)}. Those households use the first county in their state " + "for county-keyed rules." + ) + + def _state_fips(state: Union[str, int]) -> int: """Read a postal code or a FIPS code as a FIPS code.""" if isinstance(state, str) and state.upper() in US_STATE_FIPS: return US_STATE_FIPS[state.upper()] - if not isinstance(state, bool) and state in POSTAL_BY_FIPS: + if not isinstance(state, bool | np.bool_) and state in POSTAL_BY_FIPS: return int(state) raise ValueError(f"{state!r} is neither a state postal code nor a state FIPS code.") @@ -239,37 +314,80 @@ def _in_state(frame: pd.DataFrame, fips: int, year: int) -> pd.DataFrame: return frame.assign(**dict.fromkeys(state_columns, fips)) +def _named_state(name: str, values: pd.Series) -> pd.Series: + """The state FIPS code each value names, blank where it names none.""" + if name in COUNTY_NAMES: + # "LOS_ANGELES_COUNTY_CA" names California; "UNKNOWN" names nothing. + return values.astype(str).str.rsplit("_", n=1).str[-1].map(US_STATE_FIPS) + if name == "congressional_district_geoid": + states = pd.to_numeric(values, errors="coerce").floordiv(100) + else: + codes = values.astype(str).str.removesuffix(".0").str.zfill(GEOID_LENGTHS[name]) + states = pd.to_numeric(codes.str[:2], errors="coerce") + return states.where(states > 0) + + +def _geography_read(frame: pd.DataFrame, name: str, year: int) -> Optional[pd.Series]: + """The column of ``name`` that a run in ``year`` reads.""" + if name in COUNTY_NAMES and f"{name}__{year}" not in frame: + # The model reads the latest stored county, whichever year that is. + return _value_at(frame, name, LATEST_YEAR) + return _value_at(frame, name, year) + + def _require_coherent_geography(frame: pd.DataFrame, year: int) -> None: """Check a file that keeps its own states, since nothing moves them here.""" - state = _value_at(frame, "state_fips", year) - if state is None: + if _value_at(frame, "state_fips", year) is None: raise ValueError( f"The file has no state_fips for {year}, so every household would run " "as California. Add the column, or pass state= to run them all in one " "state." ) - unknown = set(state.unique()) - set(POSTAL_BY_FIPS) - if unknown: - listed = ", ".join(sorted(str(value) for value in unknown)) - raise ValueError(f"state_fips holds {listed}, which name no state.") - county = _value_at(frame, "county_fips", year) - if county is not None: - known = county != "" - if county[known].str[:2].astype(int).ne(state[known]).any(): - raise ValueError( - "Some rows hold a county_fips outside their state_fips. Correct them, " - "or pass state= to run the file in one state, which clears county." - ) + dated_columns = [ + column + for name in ("state_fips", *STATE_NAMING_GEOGRAPHY) + for column in _columns_of(frame, name) + ] + read_years = {year, *filter(None, map(_year_of, dated_columns))} + for read_year in sorted(read_years): + state = _value_at(frame, "state_fips", read_year) + if state is None: + continue + unknown = set(state.unique()) - set(POSTAL_BY_FIPS) + if unknown: + listed = ", ".join(sorted(str(value) for value in unknown)) + raise ValueError(f"state_fips holds {listed}, which name no state.") + for name in STATE_NAMING_GEOGRAPHY: + stored = _geography_read(frame, name, read_year) + if stored is None: + continue + named = _named_state(name, stored) + if (named.notna() & named.ne(state)).any(): + raise ValueError( + f"Some rows hold a {name} outside their state_fips for " + f"{read_year}. Correct them, or pass state= to run the file in " + "one state, which clears it." + ) - postal = state.map(POSTAL_BY_FIPS) for label in STATE_LABELS: - stored = _value_at(frame, label, year) - if stored is not None and stored.astype(str).ne(postal).any(): - raise ValueError( - f"Some rows hold a {label} that disagrees with state_fips. Correct " - "them, or pass state= to run the file in one state." - ) + for column in _columns_of(frame, label): + state = _value_at(frame, "state_fips", _year_of(column) or year) + if ( + state is not None + and frame[column].astype(str).ne(state.map(POSTAL_BY_FIPS)).any() + ): + raise ValueError( + f"Some rows hold a {label} that disagrees with state_fips. " + "Correct them, or pass state= to run the file in one state." + ) + + +def _digest(frame: pd.DataFrame) -> str: + """A fingerprint of a prepared frame, whatever order its columns take.""" + ordered = frame[sorted(frame.columns)] + rows = pd.util.hash_pandas_object(ordered, index=False).to_numpy().tobytes() + return hashlib.sha256("|".join(ordered.columns).encode() + rows).hexdigest() def prepare_flat_file( @@ -285,7 +403,8 @@ def prepare_flat_file( tax unit, SPM unit, family and marital unit, plus ``age``. Columns are named ``variable`` or ``variable__period``. ``person_id`` is optional. The run ignores columns that name no variable, and logs - them. + them. Stored copies of what the model derives from the state, such + as ``state_group``, leave too, so the formulas run. year: The year the file describes. A column without a period holds that year's value. state: A postal code or FIPS code to run every household in. It applies @@ -294,7 +413,8 @@ def prepare_flat_file( ``state_fips``, which then has to agree with those columns. Returns: - A new frame, leaving ``people`` as it was. + A new frame, leaving ``people`` as it was. Results come back with + groups in the order the file first names them. """ from policyengine_us.system import system @@ -302,6 +422,13 @@ def prepare_flat_file( raise ValueError("The file has no rows.") frame = _with_periods(people, year) frame = _without_unknown_columns(frame, system.variables) + frame = frame.drop( + columns=[ + column + for column in frame.columns + if _variable_of(column) in DERIVED_FROM_STATE + ] + ) if _value_at(frame, "age", year) is None: raise ValueError( f"The file has no age for {year}, so everyone would run as a 40-year-old." @@ -311,6 +438,7 @@ def prepare_flat_file( frame = _with_text_counties(frame) if state is None: _require_coherent_geography(frame, year) + _warn_about_unknown_counties(frame) else: frame = _in_state(frame, _state_fips(state), year) _require_group_values_agree(frame, year, system.variables) @@ -340,7 +468,9 @@ def flat_file_microsimulation( **kwargs: Passed on to ``Microsimulation``, for example ``reform``. Returns: - A ``Microsimulation`` carrying this release's ``policyengine_bundle``. + A ``Microsimulation`` carrying this release's ``policyengine_bundle``, + whose ``flat_file`` entry records the year, the state and a digest of + the prepared file. """ from policyengine_core.data import Dataset from policyengine_us import Microsimulation @@ -363,5 +493,10 @@ def flat_file_microsimulation( logical_name="flat_file", ) ) + microsim.policyengine_bundle["flat_file"] = { + "year": year, + "state": None if state is None else _state_fips(state), + "sha256": _digest(prepared), + } microsim.policyengine_bundle["spm"] = dict(microsim.spm_config) return microsim diff --git a/tests/test_us_flat_file.py b/tests/test_us_flat_file.py index d9af999ef..fee90266a 100644 --- a/tests/test_us_flat_file.py +++ b/tests/test_us_flat_file.py @@ -13,6 +13,7 @@ import policyengine as pe # noqa: E402 from policyengine.countries.us.data import US_STATE_FIPS # noqa: E402 from policyengine.tax_benefit_models.us.flat_file import ( # noqa: E402 + DERIVED_FROM_STATE, LOCAL_GEOGRAPHY, STATE_LABELS, prepare_flat_file, @@ -68,14 +69,40 @@ def test_a_period_stays_on_its_column(self): prepared = prepare_flat_file(people, year=YEAR) assert "is_household_head__ETERNITY" in prepared.columns - def test_group_ids_move_onto_each_persons_row(self): + def test_group_ids_stay_the_files_own(self): prepared = prepare_flat_file(in_state(survey()), year=YEAR) for column in GROUP_COLUMNS: - assert f"{column}__{YEAR}" not in prepared.columns - assert ( - prepared[f"person_{column}__{YEAR}"].tolist() - == survey()[column].tolist() - ) + assert prepared[f"{column}__{YEAR}"].tolist() == survey()[column].tolist() + + def test_memberships_number_groups_in_file_order(self): + people = in_state(survey()).assign(household_id=[9, 9, 3, 3, 3, 3, 7]) + prepared = prepare_flat_file(people, year=YEAR) + assert prepared[f"person_household_id__{YEAR}"].tolist() == [ + 0, + 0, + 1, + 1, + 1, + 1, + 2, + ] + assert prepared[f"household_id__{YEAR}"].tolist() == [9, 9, 3, 3, 3, 3, 7] + + def test_whole_number_float_ids_keep_their_values(self): + people = in_state(survey()).astype({"household_id": float}) + prepared = prepare_flat_file(people, year=YEAR) + assert prepared[f"household_id__{YEAR}"].tolist() == ( + survey()["household_id"].tolist() + ) + + def test_an_id_too_large_to_store_takes_its_place_in_the_file(self, caplog): + people = in_state(survey()).assign( + household_id=survey()["household_id"] + 2**40 + ) + with caplog.at_level(logging.WARNING): + prepared = prepare_flat_file(people, year=YEAR) + assert "too large" in caplog.text + assert prepared[f"household_id__{YEAR}"].tolist() == [0, 0, 1, 1, 1, 1, 2] def test_an_export_with_many_id_columns_settles_on_one(self): people = in_state(survey()).rename( @@ -83,8 +110,8 @@ def test_an_export_with_many_id_columns_settles_on_one(self): ) people[f"person_household_id__{YEAR}"] = people["household_id__ETERNITY"] prepared = prepare_flat_file(people, year=YEAR) - ids = [column for column in prepared if "household_id" in column] - assert ids == [f"person_household_id__{YEAR}"] + ids = {column for column in prepared if "household_id" in column} + assert ids == {f"household_id__{YEAR}", f"person_household_id__{YEAR}"} def test_text_ids_become_integers_that_keep_the_groups(self): people = in_state(survey()) @@ -170,7 +197,7 @@ def test_a_state_that_does_not_exist(self): with pytest.raises(ValueError, match="99"): prepare_flat_file(in_state(survey(), 99), year=YEAR) - @pytest.mark.parametrize("state", ["ZZ", 99, "", True]) + @pytest.mark.parametrize("state", ["ZZ", 99, "", True, np.bool_(True)]) def test_a_requested_state_that_does_not_exist(self, state): with pytest.raises(ValueError, match="postal code"): prepare_flat_file(survey(), year=YEAR, state=state) @@ -192,11 +219,61 @@ def test_a_household_value_that_varies_within_the_household(self): with pytest.raises(ValueError, match="household_weight"): prepare_flat_file(people, year=YEAR) - def test_a_county_outside_its_state(self): - people = in_state(survey(), MISSISSIPPI).assign(county_fips=LOS_ANGELES_COUNTY) - with pytest.raises(ValueError, match="outside"): + @pytest.mark.parametrize( + "column, value", + [ + ("county_fips", LOS_ANGELES_COUNTY), + ("county_fips", 6037), + ("county", "LOS_ANGELES_COUNTY_CA"), + ("county_str", "LOS_ANGELES_COUNTY_CA"), + ("tract_geoid", "06037101110"), + ("tract_geoid", 6037101110), + ("block_geoid", "060371011101000"), + ("congressional_district_geoid", 634), + ], + ) + def test_geography_outside_its_state(self, column, value): + people = in_state(survey(), MISSISSIPPI).assign(**{column: value}) + with pytest.raises(ValueError, match=f"{column} outside"): prepare_flat_file(people, year=YEAR) + @pytest.mark.parametrize("years", [(YEAR + 1,), (YEAR - 1,)]) + def test_a_county_from_another_year_outside_its_state(self, years): + people = in_state(survey(), MISSISSIPPI).assign( + **{f"county_fips__{year}": LOS_ANGELES_COUNTY for year in years} + ) + with pytest.raises(ValueError, match="county_fips outside"): + prepare_flat_file(people, year=YEAR) + + def test_a_county_name_from_a_later_year_outside_its_state(self): + people = in_state(survey(), MISSISSIPPI).assign( + **{f"county__{YEAR + 1}": "LOS_ANGELES_COUNTY_CA"} + ) + with pytest.raises(ValueError, match="county outside"): + prepare_flat_file(people, year=YEAR) + + def test_a_state_that_moves_away_from_its_county(self): + people = survey().assign( + **{ + f"state_fips__{YEAR}": 6, + f"state_fips__{YEAR + 1}": MISSISSIPPI, + "county_fips": LOS_ANGELES_COUNTY, + } + ) + with pytest.raises(ValueError, match=f"for {YEAR + 1}"): + prepare_flat_file(people, year=YEAR) + + def test_a_state_and_county_that_move_together_stay(self): + people = survey().assign( + **{ + f"state_fips__{YEAR}": 6, + f"state_fips__{YEAR + 1}": MISSISSIPPI, + f"county_fips__{YEAR}": LOS_ANGELES_COUNTY, + f"county_fips__{YEAR + 1}": "28001", + } + ) + prepare_flat_file(people, year=YEAR) + def test_a_label_that_disagrees_with_the_state(self): people = in_state(survey(), MISSISSIPPI).assign(state_code="CA") with pytest.raises(ValueError, match="state_code"): @@ -207,6 +284,18 @@ def test_a_malformed_county(self): with pytest.raises(ValueError, match="county_fips"): prepare_flat_file(people, year=YEAR) + def test_a_code_that_names_no_county_gets_a_warning(self, caplog): + people = in_state(survey()).assign(county_fips="06999") + with caplog.at_level(logging.WARNING): + prepare_flat_file(people, year=YEAR) + assert "name no county" in caplog.text + + def test_a_real_county_stays_quiet(self, caplog): + people = in_state(survey()).assign(county_fips=LOS_ANGELES_COUNTY) + with caplog.at_level(logging.WARNING): + prepare_flat_file(people, year=YEAR) + assert "name no county" not in caplog.text + class TestMovingToAState: def test_a_file_may_start_with_no_state(self): @@ -245,6 +334,15 @@ def test_stale_geography_leaves(self): for name in (*STATE_LABELS, *LOCAL_GEOGRAPHY): assert not any(column.startswith(f"{name}__") for column in prepared) + @pytest.mark.parametrize("state", [None, "AK"]) + def test_stored_state_results_leave_whichever_state_runs(self, state): + stale = {f"{name}__{YEAR}": "x" for name in sorted(DERIVED_FROM_STATE)} + prepared = prepare_flat_file( + in_state(survey()).assign(**stale), year=YEAR, state=state + ) + for name in DERIVED_FROM_STATE: + assert f"{name}__{YEAR}" not in prepared.columns + @settings(max_examples=40, suppress_health_check=[HealthCheck.too_slow]) @given(st.integers(min_value=1, max_value=99_999)) @@ -302,6 +400,70 @@ def test_the_recipe_runs_a_csv_through_a_state(tmp_path, state): assert sim.populations["marital_unit"].count == 5 assert sim.policyengine_bundle["runtime_dataset"] == "flat_file" assert sim.policyengine_bundle["spm"]["geography_kind"] == "national" + assert sim.policyengine_bundle["flat_file"]["year"] == YEAR + assert sim.policyengine_bundle["flat_file"]["state"] == US_STATE_FIPS[state] + + +def test_the_provenance_tells_files_apart_and_not_column_orders(): + def digest(people): + sim = pe.us.flat_file_microsimulation( + people, year=YEAR, state="MS", spm=NATIONAL_SPM + ) + return sim.policyengine_bundle["flat_file"]["sha256"] + + people = survey() + reordered = people[list(reversed(people.columns))] + assert digest(people) == digest(reordered) + assert digest(people) != digest(people.assign(age=people["age"] + 1)) + + +def test_one_person_groups_keep_their_own_values_in_any_order(): + people = pd.DataFrame( + { + **{column: [9, 3] for column in GROUP_COLUMNS}, + "age": [30, 40], + "state_fips": [MISSISSIPPI, 6], + "household_weight": [900, 100], + } + ) + sim = pe.us.flat_file_microsimulation(people, year=YEAR, spm=NATIONAL_SPM) + assert sim.calculate("household_id", YEAR).values.tolist() == [9, 3] + assert sim.calculate("state_code", YEAR, map_to="person").values.tolist() == [ + "MS", + "CA", + ] + assert sim.calculate("household_weight", YEAR, map_to="person").values.tolist() == [ + 900, + 100, + ] + + +def test_results_merge_back_on_the_files_own_ids(): + ids = {1: 70, 2: 80, 3: 60} + people = in_state(survey()).assign( + household_id=survey()["household_id"].map(ids), + ) + sim = pe.us.flat_file_microsimulation(people, year=YEAR, spm=NATIONAL_SPM) + weights = pd.DataFrame( + { + "household_id": sim.calculate("household_id", YEAR).values, + "weight": sim.calculate("household_weight", YEAR).values, + } + ) + merged = people.merge(weights, on="household_id") + assert merged["weight"].tolist() == people["household_weight"].tolist() + + +def test_a_stored_state_group_does_not_set_the_poverty_guideline(): + clean = pe.us.flat_file_microsimulation(survey(), year=YEAR, state="AK") + stale = pe.us.flat_file_microsimulation( + survey().assign(state_group="CONTIGUOUS_US"), year=YEAR, state="AK" + ) + period = f"{YEAR}-01" + assert np.array_equal( + clean.calculate("snap_fpg", period).values, + stale.calculate("snap_fpg", period).values, + ) def test_stale_geography_changes_nothing_after_a_move(): @@ -372,3 +534,19 @@ def test_keywords_reach_the_simulation(): def test_a_dataset_is_refused(): with pytest.raises(ValueError, match="people"): pe.us.flat_file_microsimulation(survey(), year=YEAR, dataset="other.h5") + + +@settings(max_examples=30, suppress_health_check=[HealthCheck.too_slow]) +@given(st.permutations(range(7))) +def test_row_order_changes_no_household(order): + """Shuffling a file's rows changes the order of results, not any household.""" + people = in_state(survey()).assign( + state_fips=survey()["household_id"].map({1: 6, 2: 28, 3: 36}) + ) + shuffled = people.iloc[list(order)].reset_index(drop=True) + prepared = prepare_flat_file(shuffled, year=YEAR) + memberships = prepared[f"person_household_id__{YEAR}"] + first_seen = shuffled["household_id"].drop_duplicates().tolist() + assert [first_seen[index] for index in memberships] == ( + shuffled["household_id"].tolist() + ) From 339b533384a9e284c8dc490092b0a54dc6c97a11 Mon Sep 17 00:00:00 2001 From: Max Ghenis <6076111+MaxGhenis@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:26:47 -0500 Subject: [PATCH 05/14] Correct flat-file state overrides and group validation --- docs/simulated-instruments.md | 18 +- .../tax_benefit_models/us/flat_file.py | 225 ++++++++++++------ tests/test_us_flat_file.py | 97 +++++++- 3 files changed, 242 insertions(+), 98 deletions(-) diff --git a/docs/simulated-instruments.md b/docs/simulated-instruments.md index 18faf19e4..63962885c 100644 --- a/docs/simulated-instruments.md +++ b/docs/simulated-instruments.md @@ -2,7 +2,7 @@ title: "Simulated instruments" --- -A simulated eligibility instrument runs one fixed population through each state's rules. The people stay the same, so differences across states come from the rules alone. `pe.us.flat_file_microsimulation` runs your own microdata this way. +A simulated eligibility instrument runs one fixed population under the modeled rules for each state. `pe.us.flat_file_microsimulation` keeps the people fixed and changes their assigned state. The results also reflect the model's geographic defaults, including its choice of county for a moved household. ## The recipe @@ -24,7 +24,7 @@ for state in US_STATE_FIPS: snap_eligible[state] = sim.calculate("is_snap_eligible", "2024-01").mean() ``` -`US_STATE_FIPS` maps postal codes to FIPS codes for the 50 states and DC, so the loop runs 51 times. `state` takes a postal code or a FIPS code. +`US_STATE_FIPS` maps postal codes to FIPS codes for the 50 states and DC, so the loop runs 51 times. `state` takes a postal code or a FIPS code as an integer or numeric string. `calculate` returns a weighted series, and `mean()` gives a weighted share of the variable's own entity: SPM units for `is_snap_eligible`, people for `is_medicaid_eligible`. A monthly variable such as `is_snap_eligible` takes a month, and an annual one such as `state_income_tax` takes a year. @@ -34,13 +34,13 @@ To run each household in the state your file records, leave `state` out. The fil ## What your file needs -The file holds one row per person. Name a column after a PolicyEngine variable, or `variable__period` to date it. A column with no period holds the value for `year`. +The file holds one row per person. Name a column after a PolicyEngine variable, or `variable__period` to date it. A column with no period holds the value for `year`. Use calendar years for age and for the geography fields the helper validates. Group membership stays fixed across periods. | Column | Needed | Notes | | --- | --- | --- | | `household_id`, `tax_unit_id`, `spm_unit_id`, `family_id`, `marital_unit_id` | Yes | Put each on every person's row, numbered across the whole file. | | `age` | Yes | The helper refuses a file without it, which would otherwise run everyone as 40. | -| `state_fips` | Unless you pass `state` | The helper refuses a file with neither, which would otherwise run everyone as California. | +| `state_fips` | Unless you pass `state` | Supply a value for the requested year and for any earlier year with age inputs. Later years can carry the most recent value forward. | | `person_id` | No | The helper numbers the rows if you leave it out. | | `household_weight` | No | Every household weighs 1 without it. | | `employment_income` and other inputs | As your measure needs | Give each in its variable's period: `employment_income` holds annual dollars. Inputs you omit take their defaults, usually zero. | @@ -62,7 +62,7 @@ prepared = pe.us.prepare_flat_file(people, year=2024, state="MS") `prepare_flat_file` refuses a file that: - lacks a required column -- repeats a `person_id` +- has a blank ID, a repeated `person_id` or conflicting group membership columns - numbers groups within each household - gives one group's rows different values for a group-level variable such as `household_weight` @@ -78,11 +78,11 @@ Each person-level result follows the rows of your file. Group-level results come people["state_tax"] = sim.calculate("state_income_tax", 2024, map_to="person").values ``` -`map_to="person"` repeats a group's value on each member's row, so a sum across rows counts it once per member. `sim.calculate("household_id", 2024)` holds your own IDs, which also lets you merge group results back. The helper replaces IDs that are text or exceed 2,147,483,647 with their order in the file, and logs the large ones. +`map_to="person"` repeats a group's value on each member's row, so a sum across rows counts it once per member. `sim.calculate("household_id", 2024)` holds the IDs from your file when they are integers within the signed 32-bit range. The helper numbers other IDs by their first appearance and logs a warning for integers outside that range. ## What a state change clears -Passing `state` sets `state_fips` in every year your file holds. It also removes stored state labels and all geography finer than a state, such as county, ZIP code, congressional district and tract, because those values mean nothing in the new state. +Passing `state` sets `state_fips` in every year your file holds. It removes geography columns such as county, ZIP code, congressional district and tract and clears stored geographic flags such as `is_rural`. Supply source inputs for the outcome you want to measure. A stored outcome such as eligibility or tax can override its formula. With no county, the model applies county-keyed rules using the first county in the state alphabetically, such as Aitkin County in Minnesota. SPM thresholds use county in the default selection, so select `{"geography_kind": "national"}` as the recipe does. The selection applies to every state, which keeps thresholds identical across the loop. To keep real counties, leave `state` out and run each household where the file records it. @@ -91,10 +91,8 @@ With or without `state`, the helper removes stored copies of what the model deri ## What to watch for - **Years after your file.** A run carries your file's last value forward, and uprates the inputs that have an uprating rule. $20,000 of 2024 earnings reads as $20,987 in 2025, and a weight of 1,000 reads as 1,009. -- **Years before your file.** An earlier year falls back to defaults. A 2024 file read for 2023 runs everyone as California at age 40, with no income. +- **Years before your inputs.** The helper prepares the file for the supplied `year`. Calculate outcomes for years the file describes. When a simulation reads a year before the relevant inputs, values can fall back to model defaults, including California and age 40. - **Medicaid dollars.** `medicaid` spreads each state's total spending across the weighted enrollees the file puts in that state, so a small file gets very large amounts per person. Measure eligibility with `is_medicaid_eligible`. The same applies to `healthcare_benefit_value`. - **Deciles.** Income deciles rank households within your file, not within the US. - **Minors on their own.** The SPM calculation needs someone aged 18 or over in each SPM unit, or someone aged 15 to 17 with `is_household_head`, `is_household_spouse` or `is_spm_independent_minor_role` set. Those columns hold for all time, so `sim.to_input_dataframe()`, which writes a simulation's inputs back out as a flat file, names them `variable__ETERNITY`. Keep that suffix when you filter an export to one year. - **Changing state after the build.** `sim.set_input("state_fips", ...)` leaves stored geography in place. Pass `state` so that the helper clears it first. - -`policyengine.py` runs against the country model versions this release pins. Text variables such as `state_code_str` do not map to group entities in these versions, so calculate them at the household level. diff --git a/src/policyengine/tax_benefit_models/us/flat_file.py b/src/policyengine/tax_benefit_models/us/flat_file.py index dfa5abb8e..63786efb3 100644 --- a/src/policyengine/tax_benefit_models/us/flat_file.py +++ b/src/policyengine/tax_benefit_models/us/flat_file.py @@ -1,4 +1,4 @@ -"""Run a researcher's own flat file through the pinned US model. +"""Run a researcher's own flat file through the bundled US model. A flat file holds one row per person, as a survey extract does. A simulated instrument runs the same people through each state's rules, so moving the file @@ -7,8 +7,8 @@ ``prepare_flat_file`` does that work and checks the file first, because a missing column does not fail on its own: without ``state_fips`` every household runs as -California. It writes the columns in the one form the pinned loader reads -correctly, ``variable__period``, with each person's groups on their own row. +California. It names columns ``variable__period`` and puts each person's +groups on their own row. """ import hashlib @@ -17,6 +17,7 @@ import numpy as np import pandas as pd +from policyengine_core import periods from policyengine.countries.us.data import US_STATE_FIPS from policyengine.tax_benefit_models.common.model_version import ( @@ -49,11 +50,16 @@ "county_str", "in_ny_mctd_zone_2", "in_nyc", + "is_on_tribal_land", + "is_rural", "medicaid_rating_area", "place_fips", "puma", + "safmr_used_for_hcv", "sldl", "sldu", + "small_area_fair_market_rent", + "spm_unit_geographic_adjustment", "three_digit_zip_code", "tract_geoid", "vtd", @@ -64,6 +70,7 @@ # these never reach a run. The model names its in-state flags by postal code. DERIVED_FROM_STATE = frozenset( { + "first_county_in_state", "spm_unit_state_fips", "state_group", "state_group_str", @@ -84,46 +91,64 @@ "congressional_district_geoid", ) ETERNITY = "ETERNITY" -LATEST_YEAR = 9999 +ANNUAL_INPUTS = {"age", "state_fips", *STATE_LABELS, *STATE_NAMING_GEOGRAPHY} POSTAL_BY_FIPS = {fips: postal for postal, fips in US_STATE_FIPS.items()} LISTED_COLUMNS = 10 -LARGEST_STORED_ID = 2**31 - 1 +STORED_ID_RANGE = np.iinfo(np.int32) def _variable_of(column: str) -> str: """The variable a ``variable__period`` column belongs to.""" - return column.rsplit("__", 1)[0] + return column.split("__", 1)[0] def _columns_of(frame: pd.DataFrame, name: str) -> list[str]: return [column for column in frame.columns if _variable_of(column) == name] -def _year_of(column: str) -> Optional[int]: - """The year a dated column starts, or ``None`` for one with no year.""" - period = column.rsplit("__", 1)[1] - return int(period[:4]) if period[:4].isdigit() else None +def _id_columns(frame: pd.DataFrame, name: str, year: int) -> list[str]: + """Prefer IDs for the requested year, then undated IDs.""" + preferred = {f"{name}__{year}": 0, f"{name}__{ETERNITY}": 1} + return sorted(_columns_of(frame, name), key=lambda c: (preferred.get(c, 2), c)) + + +def _year_of(column: str) -> int: + """The year of a column validated as an annual input.""" + return int(column.split("__", 1)[1]) def _value_at(frame: pd.DataFrame, name: str, year: int) -> Optional[pd.Series]: """The column of ``name`` that a run in ``year`` reads, carried forward.""" - readable = [] - for column in _columns_of(frame, name): - column_year = _year_of(column) - if column.endswith(f"__{ETERNITY}"): - readable.append((year, column)) - elif column_year is not None and column_year <= year: - readable.append((column_year, column)) - return frame[max(readable)[1]] if readable else None - - -def _with_periods(people: pd.DataFrame, year: int) -> pd.DataFrame: - """Name every column ``variable__period``, as the pinned loader expects.""" - frame = people.rename( - columns=lambda column: ( - str(column) if "__" in str(column) else f"{column}__{year}" - ) - ) + readable = [ + column for column in _columns_of(frame, name) if _year_of(column) <= year + ] + return frame[max(readable, key=_year_of)] if readable else None + + +def _with_periods(people: pd.DataFrame, year: int, variables) -> pd.DataFrame: + """Use the loader's period parser so aliases cannot overwrite an input.""" + + def column_name(column): + name, separator, suffix = str(column).partition("__") + if not separator: + suffix = str(year) + if name not in variables: + return f"{name}__{suffix}" + try: + period = periods.period(suffix) + except ValueError as error: + raise ValueError(f"{column} has an invalid period.") from error + if name in ANNUAL_INPUTS and ( + period.unit != periods.YEAR or period != period.this_year + ): + raise ValueError(f"{column} needs a calendar-year period.") + if variables[name].definition_period == periods.ETERNITY: + suffix = ETERNITY + else: + suffix = str(period) + return f"{name}__{suffix}" + + frame = people.rename(columns=column_name) repeated = frame.columns[frame.columns.duplicated()].unique().tolist() if repeated: raise ValueError( @@ -156,24 +181,26 @@ def _id_values(values: pd.Series, name: str) -> pd.Series: """ if values.isna().any(): raise ValueError(f"{name} has blanks. Every row needs one.") - if pd.api.types.is_float_dtype(values) and values.mod(1).eq(0).all(): - values = values.astype("int64") - if pd.api.types.is_integer_dtype(values): - if values.abs().max() <= LARGEST_STORED_ID: + whole_numbers = pd.api.types.is_integer_dtype(values) or ( + pd.api.types.is_float_dtype(values) and values.mod(1).eq(0).all() + ) + if whole_numbers: + if values.between(STORED_ID_RANGE.min, STORED_ID_RANGE.max).all(): return values.astype("int64") logging.warning( f"{name} holds values too large to store, so the run numbers them in " "file order." ) + elif values.astype("string").str.strip().eq("").any(): + raise ValueError(f"{name} has blanks. Every row needs one.") return pd.Series(pd.factorize(values)[0], index=values.index) def _in_file_order(ids: pd.Series) -> pd.Series: """Number groups in the order the file first names them. - The pinned loader sorts groups by ID, but reads a column with one row per - group in row order, so one-person groups in any other order would each take - another's values. In file order the two agree, for every entity at once. + The loader sorts groups by membership ID. Numbering memberships this way + makes results follow each group's first appearance in the file. """ return pd.Series(pd.factorize(ids)[0], index=ids.index) @@ -185,11 +212,20 @@ def _with_person_level_ids(frame: pd.DataFrame, year: int) -> pd.DataFrame: """ memberships = {} for group in GROUP_ENTITIES: - columns = _columns_of(frame, f"{group}_id") or _columns_of( - frame, f"person_{group}_id" + columns = _id_columns(frame, f"{group}_id", year) + _id_columns( + frame, f"person_{group}_id", year ) if columns: - memberships[group] = _id_values(frame[columns[0]], f"{group}_id") + ids = _id_values(frame[columns[0]], columns[0]) + membership = _in_file_order(ids) + for column in columns[1:]: + if not _in_file_order(_id_values(frame[column], column)).equals( + membership + ): + raise ValueError( + f"{columns[0]} and {column} disagree on group membership." + ) + memberships[group] = (ids, membership) missing = [group for group in GROUP_ENTITIES if group not in memberships] if missing: names = ", ".join(f"{group}_id" for group in missing) @@ -198,11 +234,16 @@ def _with_person_level_ids(frame: pd.DataFrame, year: int) -> pd.DataFrame: "person's row to say who belongs together." ) - person_columns = _columns_of(frame, "person_id") + person_columns = _id_columns(frame, "person_id", year) if person_columns: persons = _id_values(frame[person_columns[0]], "person_id") if persons.duplicated().any(): raise ValueError("person_id repeats. A flat file holds one row per person.") + for column in person_columns[1:]: + if not frame[column].equals(frame[person_columns[0]]): + raise ValueError( + f"person_id must stay the same across periods ({column})." + ) else: persons = pd.Series(np.arange(len(frame)), index=frame.index) @@ -212,16 +253,16 @@ def _with_person_level_ids(frame: pd.DataFrame, year: int) -> pd.DataFrame: ] ) identifiers = {f"person_id__{year}": persons} - for group, ids in memberships.items(): + for group, (ids, membership) in memberships.items(): identifiers[f"{group}_id__{year}"] = ids - identifiers[f"person_{group}_id__{year}"] = _in_file_order(ids) + identifiers[f"person_{group}_id__{year}"] = membership return frame.assign(**identifiers) def _require_groups_within_households(frame: pd.DataFrame, year: int) -> None: """Refuse IDs numbered within households, which would merge strangers.""" households = frame[f"person_household_id__{year}"] - for group in GROUP_ENTITIES: + for group in GROUP_ENTITIES[1:]: ids = frame[f"person_{group}_id__{year}"] if households.groupby(ids).nunique().gt(1).any(): raise ValueError( @@ -232,14 +273,17 @@ def _require_groups_within_households(frame: pd.DataFrame, year: int) -> None: def _require_group_values_agree(frame: pd.DataFrame, year: int, variables) -> None: """Refuse a group's rows that disagree, since the first row would win.""" - by_group = {} + by_group: dict[str, list[str]] = {} for column in frame.columns: - group = variables[_variable_of(column)].entity.key + name = _variable_of(column) + if name in ID_VARIABLES: + continue + group = variables[name].entity.key if group in GROUP_ENTITIES: by_group.setdefault(group, []).append(column) for group, columns in by_group.items(): ids = frame[f"person_{group}_id__{year}"] - spread = frame[columns].groupby(ids, sort=False).nunique().max() + spread = frame[columns].groupby(ids, sort=False).nunique(dropna=False).max() disagreeing = spread[spread > 1].index.tolist() if disagreeing: listed = ", ".join(disagreeing[:LISTED_COLUMNS]) @@ -254,14 +298,16 @@ def _county_text(value) -> str: ``read_csv`` turns 06037 into 6037, or 6037.0 next to a blank. """ - if pd.isna(value) or value == "": + if pd.isna(value): return "" if isinstance(value, bytes): value = value.decode() if isinstance(value, float | np.floating) and float(value).is_integer(): value = int(value) text = str(value).strip() - if not text.isdigit() or len(text) > COUNTY_FIPS_LENGTH: + if not text: + return "" + if not text.isascii() or not text.isdecimal() or len(text) > COUNTY_FIPS_LENGTH: raise ValueError(f"county_fips holds {value!r}, which is no county FIPS code.") return text.zfill(COUNTY_FIPS_LENGTH) @@ -294,8 +340,12 @@ def _warn_about_unknown_counties(frame: pd.DataFrame) -> None: def _state_fips(state: Union[str, int]) -> int: """Read a postal code or a FIPS code as a FIPS code.""" - if isinstance(state, str) and state.upper() in US_STATE_FIPS: - return US_STATE_FIPS[state.upper()] + if isinstance(state, str): + state = state.strip().upper() + if state in US_STATE_FIPS: + return US_STATE_FIPS[state] + if state.isascii() and state.isdecimal() and len(state) <= 2: + state = int(state) if not isinstance(state, bool | np.bool_) and state in POSTAL_BY_FIPS: return int(state) raise ValueError(f"{state!r} is neither a state postal code nor a state FIPS code.") @@ -303,6 +353,11 @@ def _state_fips(state: Union[str, int]) -> int: def _in_state(frame: pd.DataFrame, fips: int, year: int) -> pd.DataFrame: """Move every household to one state, in every year the file holds.""" + years = {year} + for column in frame: + period = periods.period(column.split("__", 1)[1]) + if period.unit != periods.ETERNITY: + years.update(range(period.start.year, period.stop.year + 1)) frame = frame.drop( columns=[ column @@ -310,15 +365,20 @@ def _in_state(frame: pd.DataFrame, fips: int, year: int) -> pd.DataFrame: if _variable_of(column) in {*STATE_LABELS, *LOCAL_GEOGRAPHY} ] ) - state_columns = {f"state_fips__{year}", *_columns_of(frame, "state_fips")} - return frame.assign(**dict.fromkeys(state_columns, fips)) + return frame.assign(**{f"state_fips__{year}": fips for year in sorted(years)}) def _named_state(name: str, values: pd.Series) -> pd.Series: """The state FIPS code each value names, blank where it names none.""" if name in COUNTY_NAMES: # "LOS_ANGELES_COUNTY_CA" names California; "UNKNOWN" names nothing. - return values.astype(str).str.rsplit("_", n=1).str[-1].map(US_STATE_FIPS) + return ( + values.astype(str) + .str.strip() + .str.upper() + .str.extract(r"(?:_|,\s*)([A-Z]{2})$", expand=False) + .map(US_STATE_FIPS) + ) if name == "congressional_district_geoid": states = pd.to_numeric(values, errors="coerce").floordiv(100) else: @@ -329,35 +389,35 @@ def _named_state(name: str, values: pd.Series) -> pd.Series: def _geography_read(frame: pd.DataFrame, name: str, year: int) -> Optional[pd.Series]: """The column of ``name`` that a run in ``year`` reads.""" - if name in COUNTY_NAMES and f"{name}__{year}" not in frame: + if name == "county" and f"{name}__{year}" not in frame: # The model reads the latest stored county, whichever year that is. - return _value_at(frame, name, LATEST_YEAR) + columns = _columns_of(frame, name) + return frame[max(columns, key=_year_of)] if columns else None + if name == "county_str": + # Unlike county, its formula uses the county for the requested year. + return frame.get(f"{name}__{year}") return _value_at(frame, name, year) def _require_coherent_geography(frame: pd.DataFrame, year: int) -> None: """Check a file that keeps its own states, since nothing moves them here.""" - if _value_at(frame, "state_fips", year) is None: - raise ValueError( - f"The file has no state_fips for {year}, so every household would run " - "as California. Add the column, or pass state= to run them all in one " - "state." - ) - + required_years = {year, *map(_year_of, _columns_of(frame, "age"))} dated_columns = [ column - for name in ("state_fips", *STATE_NAMING_GEOGRAPHY) + for name in ("state_fips", *STATE_NAMING_GEOGRAPHY, *STATE_LABELS) for column in _columns_of(frame, name) ] - read_years = {year, *filter(None, map(_year_of, dated_columns))} + read_years = required_years.union(map(_year_of, dated_columns)) for read_year in sorted(read_years): state = _value_at(frame, "state_fips", read_year) if state is None: + if read_year in required_years: + raise ValueError( + f"The file has no state_fips for {read_year}, so every household " + "would run as California. Add the column, or pass state= to run " + "them all in one state." + ) continue - unknown = set(state.unique()) - set(POSTAL_BY_FIPS) - if unknown: - listed = ", ".join(sorted(str(value) for value in unknown)) - raise ValueError(f"state_fips holds {listed}, which name no state.") for name in STATE_NAMING_GEOGRAPHY: stored = _geography_read(frame, name, read_year) if stored is None: @@ -372,7 +432,7 @@ def _require_coherent_geography(frame: pd.DataFrame, year: int) -> None: for label in STATE_LABELS: for column in _columns_of(frame, label): - state = _value_at(frame, "state_fips", _year_of(column) or year) + state = _value_at(frame, "state_fips", _year_of(column)) if ( state is not None and frame[column].astype(str).ne(state.map(POSTAL_BY_FIPS)).any() @@ -396,7 +456,7 @@ def prepare_flat_file( year: int, state: Optional[Union[str, int]] = None, ) -> pd.DataFrame: - """Check a flat file and write it in the form the pinned loader reads. + """Check a flat file and write it in the form the model loader reads. Args: people: One row per person, with a group ID for each of the household, @@ -408,9 +468,9 @@ def prepare_flat_file( year: The year the file describes. A column without a period holds that year's value. state: A postal code or FIPS code to run every household in. It applies - to every year the file holds, and clears stored state labels and all - geography finer than a state. Leave it unset to keep the file's own - ``state_fips``, which then has to agree with those columns. + to every year the file holds and clears stored state labels and + geography such as county, ZIP and tract. Leave it unset to keep the + file's own ``state_fips``, which then has to agree with those columns. Returns: A new frame, leaving ``people`` as it was. Results come back with @@ -420,8 +480,10 @@ def prepare_flat_file( if people.empty: raise ValueError("The file has no rows.") - frame = _with_periods(people, year) + frame = _with_periods(people, year, system.variables) frame = _without_unknown_columns(frame, system.variables) + if state is not None: + frame = _in_state(frame, _state_fips(state), year) frame = frame.drop( columns=[ column @@ -433,14 +495,21 @@ def prepare_flat_file( raise ValueError( f"The file has no age for {year}, so everyone would run as a 40-year-old." ) + for column in _columns_of(frame, "age"): + ages = pd.to_numeric(frame[column], errors="coerce") + if not np.isfinite(ages).fillna(False).all(): + raise ValueError(f"{column} needs a finite age for every person.") frame = _with_person_level_ids(frame, year) _require_groups_within_households(frame, year) - frame = _with_text_counties(frame) if state is None: + for column in _columns_of(frame, "state_fips"): + try: + frame[column] = frame[column].map(_state_fips) + except (TypeError, ValueError) as error: + raise ValueError(f"Invalid state_fips in {column}: {error}") from error + frame = _with_text_counties(frame) _require_coherent_geography(frame, year) _warn_about_unknown_counties(frame) - else: - frame = _in_state(frame, _state_fips(state), year) _require_group_values_agree(frame, year, system.variables) return frame @@ -450,7 +519,7 @@ def flat_file_microsimulation( *, year: int, state: Optional[Union[str, int]] = None, - spm: Optional[SPMSelection] = None, + spm: Optional[Union[SPMSelection, dict[str, object]]] = None, **kwargs, ): """Build a bundled ``Microsimulation`` over a researcher's own flat file. @@ -469,8 +538,8 @@ def flat_file_microsimulation( Returns: A ``Microsimulation`` carrying this release's ``policyengine_bundle``, - whose ``flat_file`` entry records the year, the state and a digest of - the prepared file. + whose ``flat_file`` entry records the year, the state and a SHA-256 + fingerprint of the prepared frame's column names and row hashes. """ from policyengine_core.data import Dataset from policyengine_us import Microsimulation diff --git a/tests/test_us_flat_file.py b/tests/test_us_flat_file.py index fee90266a..35980ad07 100644 --- a/tests/test_us_flat_file.py +++ b/tests/test_us_flat_file.py @@ -16,6 +16,7 @@ DERIVED_FROM_STATE, LOCAL_GEOGRAPHY, STATE_LABELS, + _county_text, prepare_flat_file, ) @@ -69,6 +70,11 @@ def test_a_period_stays_on_its_column(self): prepared = prepare_flat_file(people, year=YEAR) assert "is_household_head__ETERNITY" in prepared.columns + def test_annual_period_aliases_are_canonicalized(self): + people = in_state(survey()).rename(columns={"age": f"age__year:{YEAR}"}) + prepared = prepare_flat_file(people, year=YEAR) + assert f"age__{YEAR}" in prepared.columns + def test_group_ids_stay_the_files_own(self): prepared = prepare_flat_file(in_state(survey()), year=YEAR) for column in GROUP_COLUMNS: @@ -95,9 +101,10 @@ def test_whole_number_float_ids_keep_their_values(self): survey()["household_id"].tolist() ) - def test_an_id_too_large_to_store_takes_its_place_in_the_file(self, caplog): + @pytest.mark.parametrize("offset", [2**40, -(2**63), float(2**64)]) + def test_an_id_too_large_to_store_takes_its_place_in_the_file(self, caplog, offset): people = in_state(survey()).assign( - household_id=survey()["household_id"] + 2**40 + household_id=survey()["household_id"] * 4096 + offset ) with caplog.at_level(logging.WARNING): prepared = prepare_flat_file(people, year=YEAR) @@ -113,6 +120,15 @@ def test_an_export_with_many_id_columns_settles_on_one(self): ids = {column for column in prepared if "household_id" in column} assert ids == {f"household_id__{YEAR}", f"person_household_id__{YEAR}"} + def test_group_ids_use_the_requested_year_regardless_of_column_order(self): + people = in_state(survey()).assign( + **{f"household_id__{YEAR + 1}": survey().household_id + 10} + ) + prepared = prepare_flat_file(people.iloc[:, ::-1], year=YEAR) + assert ( + prepared[f"household_id__{YEAR}"].tolist() == people.household_id.tolist() + ) + def test_text_ids_become_integers_that_keep_the_groups(self): people = in_state(survey()) people["household_id"] = people["household_id"].map( @@ -145,6 +161,7 @@ def test_unknown_columns_leave_with_a_log(self, caplog): (LOS_ANGELES_COUNTY, LOS_ANGELES_COUNTY), (np.nan, ""), ("", ""), + (" ", ""), ], ) def test_a_county_becomes_five_digit_text(self, value, text): @@ -170,6 +187,11 @@ def test_a_blank_id(self): with pytest.raises(ValueError, match="blanks"): prepare_flat_file(people, year=YEAR) + def test_a_blank_text_id(self): + people = in_state(survey()).assign(household_id=" ") + with pytest.raises(ValueError, match="household_id.*blanks"): + prepare_flat_file(people, year=YEAR) + def test_a_person_on_two_rows(self): people = in_state(survey()).assign(person_id=1) with pytest.raises(ValueError, match="one row per person"): @@ -189,10 +211,26 @@ def test_a_variable_given_twice(self): with pytest.raises(ValueError, match="more than once"): prepare_flat_file(people, year=YEAR) + def test_a_variable_given_twice_using_period_aliases(self): + people = in_state(survey()).assign(**{f"age__year:{YEAR}": 40}) + with pytest.raises(ValueError, match="more than once"): + prepare_flat_file(people, year=YEAR) + + def test_a_blank_age_is_refused_before_loading(self): + people = in_state(survey()).astype({"age": "Int64"}) + people.loc[0, "age"] = pd.NA + with pytest.raises(ValueError, match="finite age"): + prepare_flat_file(people, year=YEAR) + def test_no_state(self): with pytest.raises(ValueError, match="California"): prepare_flat_file(survey(), year=YEAR) + def test_historical_age_also_needs_a_state(self): + people = in_state(survey()).rename(columns={"age": f"age__{YEAR - 1}"}) + with pytest.raises(ValueError, match=f"state_fips for {YEAR - 1}"): + prepare_flat_file(people, year=YEAR) + def test_a_state_that_does_not_exist(self): with pytest.raises(ValueError, match="99"): prepare_flat_file(in_state(survey(), 99), year=YEAR) @@ -213,12 +251,23 @@ def test_a_group_numbered_within_its_household(self): with pytest.raises(ValueError, match="tax_unit_id values span"): prepare_flat_file(people, year=YEAR) + def test_conflicting_memberships_are_refused(self): + people = in_state(survey()).assign(person_household_id=survey().person_id) + with pytest.raises(ValueError, match="disagree on group membership"): + prepare_flat_file(people, year=YEAR) + def test_a_household_value_that_varies_within_the_household(self): people = in_state(survey()) people.loc[0, "household_weight"] = 7 with pytest.raises(ValueError, match="household_weight"): prepare_flat_file(people, year=YEAR) + def test_a_blank_group_value_cannot_hide_another_members_value(self): + people = in_state(survey()).astype({"household_weight": float}) + people.loc[0, "household_weight"] = np.nan + with pytest.raises(ValueError, match="disagree on household_weight"): + prepare_flat_file(people, year=YEAR) + @pytest.mark.parametrize( "column, value", [ @@ -226,6 +275,7 @@ def test_a_household_value_that_varies_within_the_household(self): ("county_fips", 6037), ("county", "LOS_ANGELES_COUNTY_CA"), ("county_str", "LOS_ANGELES_COUNTY_CA"), + ("county_str", "Los Angeles County, CA"), ("tract_geoid", "06037101110"), ("tract_geoid", 6037101110), ("block_geoid", "060371011101000"), @@ -252,6 +302,15 @@ def test_a_county_name_from_a_later_year_outside_its_state(self): with pytest.raises(ValueError, match="county outside"): prepare_flat_file(people, year=YEAR) + def test_a_future_county_string_does_not_override_the_current_year(self): + people = in_state(survey()).assign( + **{ + f"state_fips__{YEAR + 1}": MISSISSIPPI, + f"county_str__{YEAR + 1}": "ADAMS_COUNTY_MS", + } + ) + prepare_flat_file(people, year=YEAR) + def test_a_state_that_moves_away_from_its_county(self): people = survey().assign( **{ @@ -308,6 +367,12 @@ def test_postal_code_and_fips_agree(self): prepare_flat_file(survey(), year=YEAR, state=MISSISSIPPI), ) + def test_text_fips_agrees_with_numeric_fips(self): + pd.testing.assert_frame_equal( + prepare_flat_file(in_state(survey(), "06"), year=YEAR), + prepare_flat_file(survey(), year=YEAR, state="06"), + ) + def test_every_year_moves(self): people = in_state(survey()).assign( **{f"state_fips__{year}": 6 for year in (YEAR, YEAR + 1, YEAR + 2)} @@ -323,6 +388,12 @@ def test_a_moved_file_may_hold_one_stale_county_per_person(self): prepared = prepare_flat_file(people, year=YEAR, state="MS") assert not any(column.startswith("county_fips") for column in prepared) + def test_a_moved_file_discards_malformed_counties(self): + prepared = prepare_flat_file( + survey().assign(county_fips="stale"), year=YEAR, state="MS" + ) + assert f"county_fips__{YEAR}" not in prepared + def test_stale_geography_leaves(self): stale = {f"{name}__{YEAR}": "x" for name in (*STATE_LABELS, *LOCAL_GEOGRAPHY)} stale.pop(f"county_fips__{YEAR}") @@ -348,13 +419,9 @@ def test_stored_state_results_leave_whichever_state_runs(self, state): @given(st.integers(min_value=1, max_value=99_999)) def test_any_county_code_reads_the_same_as_text_or_number(code): """County codes survive whichever form read_csv left them in.""" - from_number = prepare_flat_file( - in_state(survey(), 6).assign(county_fips=code), year=YEAR, state="CA" - ) - from_text = prepare_flat_file( - in_state(survey(), 6).assign(county_fips=f"{code:05d}"), year=YEAR, state="CA" - ) - pd.testing.assert_frame_equal(from_number, from_text) + padded = f"{code:05d}" + assert _county_text(code) == _county_text(float(code)) == _county_text(padded) + assert _county_text(padded) == padded @settings(max_examples=40, suppress_health_check=[HealthCheck.too_slow]) @@ -508,8 +575,18 @@ def test_a_year_before_the_file_falls_back_to_defaults(): assert sim.calculate("employment_income", YEAR - 1).sum() == 0 +def test_state_override_applies_to_historical_inputs(): + people = survey().rename(columns={"age": f"age__{YEAR - 1}"}) + sim = pe.us.flat_file_microsimulation( + people, year=YEAR, state="MS", spm=NATIONAL_SPM + ) + assert set(sim.calculate("state_code", YEAR - 1).values) == {"MS"} + + def test_a_county_keyed_rule_runs_after_a_move(): - people = survey().assign(county_fips=LOS_ANGELES_COUNTY) + people = survey().assign( + county_fips=LOS_ANGELES_COUNTY, first_county_in_state="LOS_ANGELES_COUNTY_CA" + ) sim = pe.us.flat_file_microsimulation(people, year=YEAR, state="MN") assert set(sim.calculate("county", YEAR).values) == {"AITKIN_COUNTY_MN"} sim.calculate("mn_ccap_provider_rate", f"{YEAR}-01") From 2059118a0ed031c39016d8f16b288f95e61b195f Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 30 Nov 2026 23:06:40 -0500 Subject: [PATCH 06/14] Validate flat-file geography across input years and preserve whole-number IDs Co-Authored-By: GPT-6.2 Sol Co-Authored-By: Claude Opus 5.5 --- .../tax_benefit_models/us/flat_file.py | 86 +++++++++++-------- tests/test_us_flat_file.py | 79 +++++++++++++++++ 2 files changed, 130 insertions(+), 35 deletions(-) diff --git a/src/policyengine/tax_benefit_models/us/flat_file.py b/src/policyengine/tax_benefit_models/us/flat_file.py index 63786efb3..3a4443de7 100644 --- a/src/policyengine/tax_benefit_models/us/flat_file.py +++ b/src/policyengine/tax_benefit_models/us/flat_file.py @@ -13,6 +13,7 @@ import hashlib import logging +from numbers import Number from typing import Optional, Union import numpy as np @@ -132,8 +133,6 @@ def column_name(column): name, separator, suffix = str(column).partition("__") if not separator: suffix = str(year) - if name not in variables: - return f"{name}__{suffix}" try: period = periods.period(suffix) except ValueError as error: @@ -161,10 +160,10 @@ def column_name(column): def _without_unknown_columns(frame: pd.DataFrame, variables) -> pd.DataFrame: """Drop columns the model cannot read, and say so.""" unknown = [ - column for column in frame.columns if _variable_of(column) not in variables + column for column in frame.columns if _variable_of(str(column)) not in variables ] if unknown: - listed = ", ".join(unknown[:LISTED_COLUMNS]) + listed = ", ".join(map(str, unknown[:LISTED_COLUMNS])) more = len(unknown) - LISTED_COLUMNS logging.warning( f"The run ignores {len(unknown)} column(s) that name no PolicyEngine " @@ -174,25 +173,39 @@ def _without_unknown_columns(frame: pd.DataFrame, variables) -> pd.DataFrame: def _id_values(values: pd.Series, name: str) -> pd.Series: - """IDs as integers, the only form the model stores. + """Keep whole-number IDs that fit the model's signed 32-bit storage. - The model stores them in 32 bits, so anything else takes its place in the - file instead. + Number text labels and out-of-range integers in file order. """ if values.isna().any(): raise ValueError(f"{name} has blanks. Every row needs one.") - whole_numbers = pd.api.types.is_integer_dtype(values) or ( - pd.api.types.is_float_dtype(values) and values.mod(1).eq(0).all() - ) - if whole_numbers: - if values.between(STORED_ID_RANGE.min, STORED_ID_RANGE.max).all(): + + numeric_only = True + fits = True + invalid = f"{name} needs whole numbers for numeric IDs." + for value in values.unique(): + if isinstance(value, str) and not value.strip(): + raise ValueError(f"{name} has blanks. Every row needs one.") + if not isinstance(value, Number) or isinstance(value, bool): + numeric_only = False + continue + if isinstance(value, complex | np.complexfloating): + raise ValueError(invalid) + try: + integer = int(value) + except (ValueError, OverflowError) as error: + raise ValueError(invalid) from error + if integer != value: + raise ValueError(invalid) + fits &= STORED_ID_RANGE.min <= integer <= STORED_ID_RANGE.max + + if numeric_only: + if fits: return values.astype("int64") logging.warning( f"{name} holds values too large to store, so the run numbers them in " "file order." ) - elif values.astype("string").str.strip().eq("").any(): - raise ValueError(f"{name} has blanks. Every row needs one.") return pd.Series(pd.factorize(values)[0], index=values.index) @@ -236,7 +249,7 @@ def _with_person_level_ids(frame: pd.DataFrame, year: int) -> pd.DataFrame: person_columns = _id_columns(frame, "person_id", year) if person_columns: - persons = _id_values(frame[person_columns[0]], "person_id") + persons = _id_values(frame[person_columns[0]], person_columns[0]) if persons.duplicated().any(): raise ValueError("person_id repeats. A flat file holds one row per person.") for column in person_columns[1:]: @@ -351,13 +364,18 @@ def _state_fips(state: Union[str, int]) -> int: raise ValueError(f"{state!r} is neither a state postal code nor a state FIPS code.") -def _in_state(frame: pd.DataFrame, fips: int, year: int) -> pd.DataFrame: - """Move every household to one state, in every year the file holds.""" +def _input_years(frame: pd.DataFrame, year: int) -> set[int]: + """Collect the requested year and every year the dated inputs touch.""" years = {year} for column in frame: period = periods.period(column.split("__", 1)[1]) if period.unit != periods.ETERNITY: years.update(range(period.start.year, period.stop.year + 1)) + return years + + +def _in_state(frame: pd.DataFrame, fips: int, years: set[int]) -> pd.DataFrame: + """Move every household to one state, in every year the file holds.""" frame = frame.drop( columns=[ column @@ -399,16 +417,12 @@ def _geography_read(frame: pd.DataFrame, name: str, year: int) -> Optional[pd.Se return _value_at(frame, name, year) -def _require_coherent_geography(frame: pd.DataFrame, year: int) -> None: +def _require_coherent_geography( + frame: pd.DataFrame, year: int, years: set[int], default_state: int +) -> None: """Check a file that keeps its own states, since nothing moves them here.""" required_years = {year, *map(_year_of, _columns_of(frame, "age"))} - dated_columns = [ - column - for name in ("state_fips", *STATE_NAMING_GEOGRAPHY, *STATE_LABELS) - for column in _columns_of(frame, name) - ] - read_years = required_years.union(map(_year_of, dated_columns)) - for read_year in sorted(read_years): + for read_year in sorted(years): state = _value_at(frame, "state_fips", read_year) if state is None: if read_year in required_years: @@ -417,7 +431,7 @@ def _require_coherent_geography(frame: pd.DataFrame, year: int) -> None: "would run as California. Add the column, or pass state= to run " "them all in one state." ) - continue + state = pd.Series(default_state, index=frame.index) for name in STATE_NAMING_GEOGRAPHY: stored = _geography_read(frame, name, read_year) if stored is None: @@ -430,12 +444,11 @@ def _require_coherent_geography(frame: pd.DataFrame, year: int) -> None: "one state, which clears it." ) - for label in STATE_LABELS: - for column in _columns_of(frame, label): - state = _value_at(frame, "state_fips", _year_of(column)) + for label in STATE_LABELS: + stored = frame.get(f"{label}__{read_year}") if ( - state is not None - and frame[column].astype(str).ne(state.map(POSTAL_BY_FIPS)).any() + stored is not None + and stored.astype(str).ne(state.map(POSTAL_BY_FIPS)).any() ): raise ValueError( f"Some rows hold a {label} that disagrees with state_fips. " @@ -480,10 +493,11 @@ def prepare_flat_file( if people.empty: raise ValueError("The file has no rows.") - frame = _with_periods(people, year, system.variables) - frame = _without_unknown_columns(frame, system.variables) + frame = _without_unknown_columns(people, system.variables) + frame = _with_periods(frame, year, system.variables) + years = _input_years(frame, year) if state is not None: - frame = _in_state(frame, _state_fips(state), year) + frame = _in_state(frame, _state_fips(state), years) frame = frame.drop( columns=[ column @@ -508,7 +522,9 @@ def prepare_flat_file( except (TypeError, ValueError) as error: raise ValueError(f"Invalid state_fips in {column}: {error}") from error frame = _with_text_counties(frame) - _require_coherent_geography(frame, year) + _require_coherent_geography( + frame, year, years, system.variables["state_fips"].default_value + ) _warn_about_unknown_counties(frame) _require_group_values_agree(frame, year, system.variables) return frame diff --git a/tests/test_us_flat_file.py b/tests/test_us_flat_file.py index 35980ad07..da0c69586 100644 --- a/tests/test_us_flat_file.py +++ b/tests/test_us_flat_file.py @@ -101,6 +101,12 @@ def test_whole_number_float_ids_keep_their_values(self): survey()["household_id"].tolist() ) + def test_object_columns_keep_whole_number_ids(self): + ids = pd.Series([1, 1, 0.0, 0.0, 0.0, 0.0, -7], dtype=object) + people = in_state(survey()).assign(household_id=ids) + prepared = prepare_flat_file(people, year=YEAR) + assert prepared[f"household_id__{YEAR}"].tolist() == ids.tolist() + @pytest.mark.parametrize("offset", [2**40, -(2**63), float(2**64)]) def test_an_id_too_large_to_store_takes_its_place_in_the_file(self, caplog, offset): people = in_state(survey()).assign( @@ -152,6 +158,15 @@ def test_unknown_columns_leave_with_a_log(self, caplog): assert "foo__bar__2024" in caplog.text assert not any("foo" in column for column in prepared) + def test_unknown_columns_can_share_a_variable_and_period(self, caplog): + people = in_state(survey()).assign( + survey_stratum=3, **{f"survey_stratum__{YEAR}": 4} + ) + prepared = prepare_flat_file(people, year=YEAR) + assert "ignores 2 column(s)" in caplog.text + assert f"survey_stratum, survey_stratum__{YEAR}" in caplog.text + assert not any(column.startswith("survey_stratum") for column in prepared) + @pytest.mark.parametrize( "value, text", [ @@ -192,6 +207,13 @@ def test_a_blank_text_id(self): with pytest.raises(ValueError, match="household_id.*blanks"): prepare_flat_file(people, year=YEAR) + @pytest.mark.parametrize("dtype", [float, object]) + def test_fractional_ids_name_their_column(self, dtype): + ids = pd.Series([1, 1, 2.5, 2.5, 2.5, 2.5, 3], dtype=dtype) + people = in_state(survey()).assign(household_id=ids) + with pytest.raises(ValueError, match=f"household_id__{YEAR}.*whole numbers"): + prepare_flat_file(people, year=YEAR) + def test_a_person_on_two_rows(self): people = in_state(survey()).assign(person_id=1) with pytest.raises(ValueError, match="one row per person"): @@ -302,6 +324,35 @@ def test_a_county_name_from_a_later_year_outside_its_state(self): with pytest.raises(ValueError, match="county outside"): prepare_flat_file(people, year=YEAR) + @pytest.mark.parametrize( + "input_column", + ["employment_income__2025", "snap__2025-01", "employment_income__year:2024:2"], + ) + def test_a_county_name_outside_its_state_in_a_year_with_only_other_inputs( + self, input_column + ): + people = in_state(survey()).assign( + county="LOS_ANGELES_COUNTY_CA", + **{ + input_column: 100, + "state_fips__2026": MISSISSIPPI, + "county__2026": "ADAMS_COUNTY_MS", + }, + ) + with pytest.raises( + ValueError, match="county outside their state_fips for 2025" + ): + prepare_flat_file(people, year=YEAR) + + def test_a_county_name_outside_the_default_state_in_an_earlier_income_year(self): + people = in_state(survey(), MISSISSIPPI).assign( + county="ADAMS_COUNTY_MS", employment_income__2023=100 + ) + with pytest.raises( + ValueError, match="county outside their state_fips for 2023" + ): + prepare_flat_file(people, year=YEAR) + def test_a_future_county_string_does_not_override_the_current_year(self): people = in_state(survey()).assign( **{ @@ -505,6 +556,34 @@ def test_one_person_groups_keep_their_own_values_in_any_order(): ] +def test_results_map_to_interleaved_people_in_input_order(): + people = ( + survey() + .iloc[[2, 0, 6, 3, 1, 4, 5]] + .assign( + person_id=[90, 4, 16, 2, 43, 7, 6], + state_fips=lambda people: people["household_id"].map({1: 6, 2: 28, 3: 36}), + ) + ) + sim = pe.us.flat_file_microsimulation(people, year=YEAR, spm=NATIONAL_SPM) + + assert ( + sim.calculate("person_id", YEAR).values.tolist() == people["person_id"].tolist() + ) + assert sim.calculate("state_code", YEAR, map_to="person").values.tolist() == [ + "MS", + "CA", + "NY", + "MS", + "CA", + "MS", + "MS", + ] + assert sim.calculate("household_weight", YEAR, map_to="person").values.tolist() == ( + people["household_weight"].tolist() + ) + + def test_results_merge_back_on_the_files_own_ids(): ids = {1: 70, 2: 80, 3: 60} people = in_state(survey()).assign( From 78df2d70d4ef45804745a5cb46b00c7c34bf95b9 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 30 Nov 2026 23:10:19 -0500 Subject: [PATCH 07/14] Explain geography, ID handling and rounded figures in the simulated instruments guide Co-Authored-By: GPT-6.2 Sol Co-Authored-By: Claude Opus 5.5 --- docs/simulated-instruments.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/docs/simulated-instruments.md b/docs/simulated-instruments.md index 63962885c..e15c28c27 100644 --- a/docs/simulated-instruments.md +++ b/docs/simulated-instruments.md @@ -2,7 +2,7 @@ title: "Simulated instruments" --- -A simulated eligibility instrument runs one fixed population under the modeled rules for each state. `pe.us.flat_file_microsimulation` keeps the people fixed and changes their assigned state. The results also reflect the model's geographic defaults, including its choice of county for a moved household. +A simulated eligibility instrument runs one fixed population under the modelled rules for each state. `pe.us.flat_file_microsimulation` keeps the people fixed and changes their assigned state. The results also reflect the model's geographic defaults, including its choice of county for a moved household. ## The recipe @@ -40,7 +40,7 @@ The file holds one row per person. Name a column after a PolicyEngine variable, | --- | --- | --- | | `household_id`, `tax_unit_id`, `spm_unit_id`, `family_id`, `marital_unit_id` | Yes | Put each on every person's row, numbered across the whole file. | | `age` | Yes | The helper refuses a file without it, which would otherwise run everyone as 40. | -| `state_fips` | Unless you pass `state` | Supply a value for the requested year and for any earlier year with age inputs. Later years can carry the most recent value forward. | +| `state_fips` | Unless you pass `state` | Supply a value that covers the requested year and each year with age inputs. The model carries the most recent value forward. | | `person_id` | No | The helper numbers the rows if you leave it out. | | `household_weight` | No | Every household weighs 1 without it. | | `employment_income` and other inputs | As your measure needs | Give each in its variable's period: `employment_income` holds annual dollars. Inputs you omit take their defaults, usually zero. | @@ -62,11 +62,11 @@ prepared = pe.us.prepare_flat_file(people, year=2024, state="MS") `prepare_flat_file` refuses a file that: - lacks a required column -- has a blank ID, a repeated `person_id` or conflicting group membership columns +- has a blank ID, a numeric ID that is not a whole number, a repeated `person_id` or conflicting group membership columns - numbers groups within each household - gives one group's rows different values for a group-level variable such as `household_weight` -With `state` left out, it also refuses a county, tract, block, congressional district or state label that contradicts `state_fips` in any year the file holds. With `state` set, those columns leave instead, so they cannot contradict it. +With `state` left out, it also refuses a county, tract, block, congressional district or state label that contradicts the state in any year the file holds, including years with only inputs such as earnings. For years before the first `state_fips` input, it checks against the model's California default. It logs two things as warnings, which Python prints by default: columns that name no variable, which the run ignores, and county codes that name no county, which fall back to the first county in the state. @@ -78,21 +78,21 @@ Each person-level result follows the rows of your file. Group-level results come people["state_tax"] = sim.calculate("state_income_tax", 2024, map_to="person").values ``` -`map_to="person"` repeats a group's value on each member's row, so a sum across rows counts it once per member. `sim.calculate("household_id", 2024)` holds the IDs from your file when they are integers within the signed 32-bit range. The helper numbers other IDs by their first appearance and logs a warning for integers outside that range. +`map_to="person"` repeats a group's value on each member's row, so a sum across rows counts it once per member. `sim.calculate("household_id", 2024)` holds the IDs from your file when the ID column contains whole numbers within the signed 32-bit range, including whole numbers stored as floats or in an object column. The helper numbers columns with text IDs or out-of-range integers by first appearance. It warns when an all-numeric ID column exceeds the model's range. ## What a state change clears -Passing `state` sets `state_fips` in every year your file holds. It removes geography columns such as county, ZIP code, congressional district and tract and clears stored geographic flags such as `is_rural`. Supply source inputs for the outcome you want to measure. A stored outcome such as eligibility or tax can override its formula. +Passing `state` sets `state_fips` in every year your file holds. It clears county, ZIP code, congressional district, tract and other local geography for every household, including those already in the assigned state. It also clears stored geographic flags such as `is_rural`. Supply source inputs for the outcome you want to measure. A stored outcome such as eligibility or tax can override its formula. -With no county, the model applies county-keyed rules using the first county in the state alphabetically, such as Aitkin County in Minnesota. SPM thresholds use county in the default selection, so select `{"geography_kind": "national"}` as the recipe does. The selection applies to every state, which keeps thresholds identical across the loop. To keep real counties, leave `state` out and run each household where the file records it. +With no county, the model applies county-keyed rules using the first county in the state alphabetically, such as Aitkin County in Minnesota. The bundle defaults to county-based SPM thresholds. The recipe passes `{"geography_kind": "national"}` so every state uses the same national SPM thresholds for the same household inputs. To keep real counties, leave `state` out and run each household where the file records it. With or without `state`, the helper removes stored copies of what the model derives from the state, such as `state_group`, so the model's formulas run. ## What to watch for -- **Years after your file.** A run carries your file's last value forward, and uprates the inputs that have an uprating rule. $20,000 of 2024 earnings reads as $20,987 in 2025, and a weight of 1,000 reads as 1,009. +- **Years after your file.** The model can carry your latest input values forward and uprates inputs with an uprating rule. In this bundle, $20,000 of 2024 earnings reads as $20,987 in 2025, and a 2024 household weight of 1,000 reads as 1,009 in 2025, rounded to the nearest dollar and whole weight. - **Years before your inputs.** The helper prepares the file for the supplied `year`. Calculate outcomes for years the file describes. When a simulation reads a year before the relevant inputs, values can fall back to model defaults, including California and age 40. -- **Medicaid dollars.** `medicaid` spreads each state's total spending across the weighted enrollees the file puts in that state, so a small file gets very large amounts per person. Measure eligibility with `is_medicaid_eligible`. The same applies to `healthcare_benefit_value`. -- **Deciles.** Income deciles rank households within your file, not within the US. +- **Medicaid dollars.** `medicaid` allocates each state's total spending across the people in your file who enrol, using their sample weights and Medicaid cost indices. A small sample can therefore produce very large amounts per person. `healthcare_benefit_value` includes those Medicaid amounts. Use `is_medicaid_eligible` to measure eligibility. +- **Deciles.** Income deciles rank households within your file. - **Minors on their own.** The SPM calculation needs someone aged 18 or over in each SPM unit, or someone aged 15 to 17 with `is_household_head`, `is_household_spouse` or `is_spm_independent_minor_role` set. Those columns hold for all time, so `sim.to_input_dataframe()`, which writes a simulation's inputs back out as a flat file, names them `variable__ETERNITY`. Keep that suffix when you filter an export to one year. - **Changing state after the build.** `sim.set_input("state_fips", ...)` leaves stored geography in place. Pass `state` so that the helper clears it first. From 45ef535fa7341bdb4adce6b06a703d82f805ec1d Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 30 Nov 2026 23:11:14 -0500 Subject: [PATCH 08/14] Show how to carry the source SPM minor role into a new flat file Co-Authored-By: GPT-6.2 Sol Co-Authored-By: Claude Opus 5.5 --- docs/simulated-instruments.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/simulated-instruments.md b/docs/simulated-instruments.md index e15c28c27..9829231e2 100644 --- a/docs/simulated-instruments.md +++ b/docs/simulated-instruments.md @@ -94,5 +94,5 @@ With or without `state`, the helper removes stored copies of what the model deri - **Years before your inputs.** The helper prepares the file for the supplied `year`. Calculate outcomes for years the file describes. When a simulation reads a year before the relevant inputs, values can fall back to model defaults, including California and age 40. - **Medicaid dollars.** `medicaid` allocates each state's total spending across the people in your file who enrol, using their sample weights and Medicaid cost indices. A small sample can therefore produce very large amounts per person. `healthcare_benefit_value` includes those Medicaid amounts. Use `is_medicaid_eligible` to measure eligibility. - **Deciles.** Income deciles rank households within your file. -- **Minors on their own.** The SPM calculation needs someone aged 18 or over in each SPM unit, or someone aged 15 to 17 with `is_household_head`, `is_household_spouse` or `is_spm_independent_minor_role` set. Those columns hold for all time, so `sim.to_input_dataframe()`, which writes a simulation's inputs back out as a flat file, names them `variable__ETERNITY`. Keep that suffix when you filter an export to one year. +- **Minors on their own.** The SPM calculation needs someone aged 18 or over in each SPM unit, or someone aged 15 to 17 with `is_household_head`, `is_household_spouse` or `is_spm_independent_minor_role` set. These inputs use `__ETERNITY`. Keep columns with this suffix when you filter `sim.to_input_dataframe()` to one year. If your file supplies `is_spm_independent_minor_role`, copy it from your source to the new flat file as `is_spm_independent_minor_role__ETERNITY`. The default export omits it. - **Changing state after the build.** `sim.set_input("state_fips", ...)` leaves stored geography in place. Pass `state` so that the helper clears it first. From 7e46459bf396b7fa9acfae5cfb47827281d5ce87 Mon Sep 17 00:00:00 2001 From: "GPT-6.2 Sol" Date: Tue, 1 Dec 2026 08:39:26 -0500 Subject: [PATCH 09/14] Keep US flat-file geography and model inputs faithful to the source Co-Authored-By: GPT-6.2 Sol Co-Authored-By: Claude Opus 5.5 --- changelog.d/732.added.md | 2 +- docs/simulated-instruments.md | 14 +- .../tax_benefit_models/us/flat_file.py | 347 ++++++++++++++---- tests/test_us_flat_file.py | 311 ++++++++++++++++ 4 files changed, 604 insertions(+), 70 deletions(-) diff --git a/changelog.d/732.added.md b/changelog.d/732.added.md index 508e3a9d1..124a010a9 100644 --- a/changelog.d/732.added.md +++ b/changelog.d/732.added.md @@ -1 +1 @@ -Add `pe.us.flat_file_microsimulation` and `pe.us.prepare_flat_file`, which run a researcher's own flat file through one state's rules or the file's own states, plus a simulated instruments recipe. +Add `pe.us.prepare_flat_file` to validate person-level inputs and `pe.us.flat_file_microsimulation` to simulate them in an assigned state or in their recorded states. Include a simulated instruments recipe. diff --git a/docs/simulated-instruments.md b/docs/simulated-instruments.md index 9829231e2..11e23e570 100644 --- a/docs/simulated-instruments.md +++ b/docs/simulated-instruments.md @@ -34,13 +34,13 @@ To run each household in the state your file records, leave `state` out. The fil ## What your file needs -The file holds one row per person. Name a column after a PolicyEngine variable, or `variable__period` to date it. A column with no period holds the value for `year`. Use calendar years for age and for the geography fields the helper validates. Group membership stays fixed across periods. +The file holds one row per person. Name a column after a PolicyEngine variable, or `variable__period` to date it. A column with no period holds the value for `year`. Use calendar years for age and for the geography fields the helper validates. Group membership stays fixed across periods. The loader also reads `person_{group}_role` columns and uses a bare `role` column for groups without their own roles. | Column | Needed | Notes | | --- | --- | --- | | `household_id`, `tax_unit_id`, `spm_unit_id`, `family_id`, `marital_unit_id` | Yes | Put each on every person's row, numbered across the whole file. | | `age` | Yes | The helper refuses a file without it, which would otherwise run everyone as 40. | -| `state_fips` | Unless you pass `state` | Supply a value that covers the requested year and each year with age inputs. The model carries the most recent value forward. | +| `state_fips` | Unless you pass `state` | Supply a value that covers the requested year and each year with age inputs. The model carries the most recent value forward. Supply corresponding local geography when a household moves. | | `person_id` | No | The helper numbers the rows if you leave it out. | | `household_weight` | No | Every household weighs 1 without it. | | `employment_income` and other inputs | As your measure needs | Give each in its variable's period: `employment_income` holds annual dollars. Inputs you omit take their defaults, usually zero. | @@ -62,13 +62,15 @@ prepared = pe.us.prepare_flat_file(people, year=2024, state="MS") `prepare_flat_file` refuses a file that: - lacks a required column -- has a blank ID, a numeric ID that is not a whole number, a repeated `person_id` or conflicting group membership columns +- has a blank ID, a fractional numeric ID, a column that mixes Boolean and numeric IDs, a repeated `person_id` or conflicting group membership columns - numbers groups within each household - gives one group's rows different values for a group-level variable such as `household_weight` With `state` left out, it also refuses a county, tract, block, congressional district or state label that contradicts the state in any year the file holds, including years with only inputs such as earnings. For years before the first `state_fips` input, it checks against the model's California default. -It logs two things as warnings, which Python prints by default: columns that name no variable, which the run ignores, and county codes that name no county, which fall back to the first county in the state. +The helper warns about unused columns and well-formed county FIPS codes absent from the model's lookup. The county formula uses the first county in the state when it resolves an unmatched FIPS. A stored county can take precedence. + +When the file records its own geography, preparation fixes each covered year's county from its state and county FIPS inputs or uses the county values the file supplies. Calculating an earlier or later covered year first leaves that county and its benefits unchanged. ## Reading results back @@ -78,11 +80,11 @@ Each person-level result follows the rows of your file. Group-level results come people["state_tax"] = sim.calculate("state_income_tax", 2024, map_to="person").values ``` -`map_to="person"` repeats a group's value on each member's row, so a sum across rows counts it once per member. `sim.calculate("household_id", 2024)` holds the IDs from your file when the ID column contains whole numbers within the signed 32-bit range, including whole numbers stored as floats or in an object column. The helper numbers columns with text IDs or out-of-range integers by first appearance. It warns when an all-numeric ID column exceeds the model's range. +`map_to="person"` repeats a group's value on each member's row, so a sum across rows counts it once per member. `sim.calculate("household_id", 2024)` holds the IDs from your file when the ID column contains whole numbers within the signed 32-bit range, including whole numbers stored as floats or in an object column. Other group ID columns use their model variables' own types. For example, `family_id` uses 32-bit floating-point storage, which cannot distinguish every integer beyond 16,777,216. The helper numbers text IDs and all-numeric columns that contain an ID the model cannot store exactly by first appearance. It warns with the column name when it recodes an all-numeric column. Use input row order or the prepared IDs to map back after recoding. ## What a state change clears -Passing `state` sets `state_fips` in every year your file holds. It clears county, ZIP code, congressional district, tract and other local geography for every household, including those already in the assigned state. It also clears stored geographic flags such as `is_rural`. Supply source inputs for the outcome you want to measure. A stored outcome such as eligibility or tax can override its formula. +Passing `state` sets `state_fips` in every year your file holds. It clears county, ZIP code, congressional district, tract and other local geography for every household, including those already in the assigned state. It also clears location-based inputs such as `is_rural`, `in_la`, ACA rating areas, SNAP utility regions, child care regions and HUD rent lookups. Supply source inputs for the outcome you want to measure. A stored outcome such as eligibility or tax can override its formula. With no county, the model applies county-keyed rules using the first county in the state alphabetically, such as Aitkin County in Minnesota. The bundle defaults to county-based SPM thresholds. The recipe passes `{"geography_kind": "national"}` so every state uses the same national SPM thresholds for the same household inputs. To keep real counties, leave `state` out and run each household where the file records it. diff --git a/src/policyengine/tax_benefit_models/us/flat_file.py b/src/policyengine/tax_benefit_models/us/flat_file.py index 3a4443de7..4e8cd05b4 100644 --- a/src/policyengine/tax_benefit_models/us/flat_file.py +++ b/src/policyengine/tax_benefit_models/us/flat_file.py @@ -39,43 +39,116 @@ } ) STATE_LABELS = ("state_code", "state_code_str", "state_name") -# Geography finer than a state, and what the model derives from it. Neither means -# anything in another state. +# Local geography, including the model's local flags, programme regions, +# rating areas and location-based lookups. LOCAL_GEOGRAPHY = ( + "ak_ccap_rate_region", + "al_ccsp_region", + "ami", + "ar_sra_zone", "average_home_energy_use_in_state", "block_geoid", + "ca_tanf_region1", "cbsa_code", "congressional_district_geoid", "county", "county_fips", "county_str", + "ct_c4k_region", + "ct_tfa_region", + "ga_caps_zone", + "hud_extremely_low_income_limit", + "hud_fair_market_rent", + "hud_low_income_limit", + "hud_utility_allowance", + "hud_very_low_income_limit", + "id_iccp_county_cluster", + "il_aabd_area", + "il_ccap_county_group", + "il_dhs_csfp_county_eligible", + "il_tanf_county_group", + "in_ala", + "in_cc", + "in_denver", + "in_harris_county_tx", + "in_la", + "in_marin", + "in_multnomah_county_or", "in_ny_mctd_zone_2", "in_nyc", + "in_oc", + "in_riv", + "in_san_francisco", + "in_sbd", + "in_scc", + "in_smc", + "in_wilmington", + "in_yonkers", + "is_in_snap_abawd_waived_area", "is_on_tribal_land", "is_rural", + "ks_ccap_rate_group", + "ks_dcf_csfp_county_eligible", + "ks_tanf_county_group", + "ky_ccap_rate_region", + "lcbp_age_0", + "ma_ccfa_region", + "ma_dese_csfp_county_eligible", + "md_ccs_region", + "me_ccap_region", "medicaid_rating_area", + "mo_ccs_region", + "ms_ccpp_facility_location", + "ne_child_care_subsidy_location", + "nv_ccdp_region", + "ny_ccap_county_group", + "oh_ccap_county_rate_category", + "or_erdc_provider_area", + "pa_ccw_region", + "pa_ccw_stepparent_county_group", + "pa_tanf_county_group", + "pha_payment_standard", "place_fips", "puma", "safmr_used_for_hcv", + "sc_ccap_geography", + "sd_cca_region", + "slcsp_age_0", + "slcsp_rating_area", + "slcsp_rating_area_default", + "slcsp_rating_area_la_county", "sldl", "sldu", "small_area_fair_market_rent", + "snap_utility_region", + "snap_utility_region_str", "spm_unit_geographic_adjustment", "three_digit_zip_code", + "tn_ccap_county_tier", "tract_geoid", + "tx_ccs_workforce_board_region", + "va_ccsp_locality_group", + "va_ccsp_ready_region", + "va_medicaid_lifc_locality_group", "vtd", + "wa_wccc_center_region", + "wa_wccc_region", "zcta", "zip_code", + "zip_code_payment_standard", ) # What the model derives from the state. A stored value hides the formula, so # these never reach a run. The model names its in-state flags by postal code. DERIVED_FROM_STATE = frozenset( { "first_county_in_state", + "snap_region", + "snap_region_str", "spm_unit_state_fips", "state_group", "state_group_str", "tax_unit_state", + "taxsim_state", *US_STATE_FIPS, } ) @@ -95,7 +168,6 @@ ANNUAL_INPUTS = {"age", "state_fips", *STATE_LABELS, *STATE_NAMING_GEOGRAPHY} POSTAL_BY_FIPS = {fips: postal for postal, fips in US_STATE_FIPS.items()} LISTED_COLUMNS = 10 -STORED_ID_RANGE = np.iinfo(np.int32) def _variable_of(column: str) -> str: @@ -126,11 +198,15 @@ def _value_at(frame: pd.DataFrame, name: str, year: int) -> Optional[pd.Series]: return frame[max(readable, key=_year_of)] if readable else None -def _with_periods(people: pd.DataFrame, year: int, variables) -> pd.DataFrame: +def _with_periods( + people: pd.DataFrame, year: int, variables, group_roles: set[str] +) -> pd.DataFrame: """Use the loader's period parser so aliases cannot overwrite an input.""" def column_name(column): name, separator, suffix = str(column).partition("__") + if name == "role" and not separator: + return name if not separator: suffix = str(year) try: @@ -141,7 +217,7 @@ def column_name(column): period.unit != periods.YEAR or period != period.this_year ): raise ValueError(f"{column} needs a calendar-year period.") - if variables[name].definition_period == periods.ETERNITY: + if name in group_roles or variables[name].definition_period == periods.ETERNITY: suffix = ETERNITY else: suffix = str(period) @@ -157,10 +233,16 @@ def column_name(column): return frame -def _without_unknown_columns(frame: pd.DataFrame, variables) -> pd.DataFrame: +def _without_unknown_columns( + frame: pd.DataFrame, variables, group_roles: set[str] +) -> pd.DataFrame: """Drop columns the model cannot read, and say so.""" unknown = [ - column for column in frame.columns if _variable_of(str(column)) not in variables + column + for column in frame.columns + if column != "role" + and _variable_of(str(column)) not in group_roles + and _variable_of(str(column)) not in variables ] if unknown: listed = ", ".join(map(str, unknown[:LISTED_COLUMNS])) @@ -172,41 +254,61 @@ def _without_unknown_columns(frame: pd.DataFrame, variables) -> pd.DataFrame: return frame.drop(columns=unknown) -def _id_values(values: pd.Series, name: str) -> pd.Series: - """Keep whole-number IDs that fit the model's signed 32-bit storage. - - Number text labels and out-of-range integers in file order. - """ +def _id_values(values: pd.Series, name: str, model_dtype) -> pd.Series: + """Keep exact whole-number IDs and number other labels in file order.""" if values.isna().any(): raise ValueError(f"{name} has blanks. Every row needs one.") + dtype = np.dtype(model_dtype) + if dtype.kind == "f": + largest = int(np.finfo(dtype).max) + smallest = -largest + sequential_limit = 1 << (np.finfo(dtype).nmant + 1) + else: + smallest, largest = np.iinfo(dtype).min, np.iinfo(dtype).max + sequential_limit = largest + + storage = dtype if dtype.kind == "f" else "int64" numeric_only = True + has_boolean = False + has_numeric = False fits = True invalid = f"{name} needs whole numbers for numeric IDs." - for value in values.unique(): + # Factorisation and unique() equate True with 1 and False with 0. + for value in values.array: if isinstance(value, str) and not value.strip(): raise ValueError(f"{name} has blanks. Every row needs one.") - if not isinstance(value, Number) or isinstance(value, bool): - numeric_only = False + if isinstance(value, bool | np.bool_): + has_boolean = True + elif isinstance(value, Number): + has_numeric = True + if isinstance(value, complex | np.complexfloating): + raise ValueError(invalid) + try: + integer = int(value) + except (ValueError, OverflowError) as error: + raise ValueError(invalid) from error + if integer != value: + raise ValueError(invalid) + fits &= ( + smallest <= integer <= largest and int(dtype.type(integer)) == integer + ) continue - if isinstance(value, complex | np.complexfloating): - raise ValueError(invalid) - try: - integer = int(value) - except (ValueError, OverflowError) as error: - raise ValueError(invalid) from error - if integer != value: - raise ValueError(invalid) - fits &= STORED_ID_RANGE.min <= integer <= STORED_ID_RANGE.max + numeric_only = False + if has_boolean and has_numeric: + raise ValueError(f"{name} mixes Boolean and numeric IDs. Use one ID type.") if numeric_only: if fits: - return values.astype("int64") + return values.astype(storage) logging.warning( - f"{name} holds values too large to store, so the run numbers them in " - "file order." + f"{name} holds values too large to store exactly, so the run numbers " + "them in file order." ) - return pd.Series(pd.factorize(values)[0], index=values.index) + codes, labels = pd.factorize(values) + if len(labels) - 1 > sequential_limit: + raise ValueError(f"{name} has too many distinct IDs for the model to store.") + return pd.Series(codes, index=values.index, dtype=storage) def _in_file_order(ids: pd.Series) -> pd.Series: @@ -218,10 +320,10 @@ def _in_file_order(ids: pd.Series) -> pd.Series: return pd.Series(pd.factorize(ids)[0], index=ids.index) -def _with_person_level_ids(frame: pd.DataFrame, year: int) -> pd.DataFrame: +def _with_person_level_ids(frame: pd.DataFrame, year: int, variables) -> pd.DataFrame: """Put each person's ID and group memberships on their own row. - ``{group}_id`` keeps the file's own IDs, so results merge back on them. + ``{group}_id`` keeps the file's own numeric IDs when the model can store them. """ memberships = {} for group in GROUP_ENTITIES: @@ -229,10 +331,11 @@ def _with_person_level_ids(frame: pd.DataFrame, year: int) -> pd.DataFrame: frame, f"person_{group}_id", year ) if columns: - ids = _id_values(frame[columns[0]], columns[0]) + dtype = variables[f"{group}_id"].dtype + ids = _id_values(frame[columns[0]], columns[0], dtype) membership = _in_file_order(ids) for column in columns[1:]: - if not _in_file_order(_id_values(frame[column], column)).equals( + if not _in_file_order(_id_values(frame[column], column, dtype)).equals( membership ): raise ValueError( @@ -249,10 +352,12 @@ def _with_person_level_ids(frame: pd.DataFrame, year: int) -> pd.DataFrame: person_columns = _id_columns(frame, "person_id", year) if person_columns: - persons = _id_values(frame[person_columns[0]], person_columns[0]) + dtype = variables["person_id"].dtype + persons = _id_values(frame[person_columns[0]], person_columns[0], dtype) if persons.duplicated().any(): raise ValueError("person_id repeats. A flat file holds one row per person.") for column in person_columns[1:]: + _id_values(frame[column], column, dtype) if not frame[column].equals(frame[person_columns[0]]): raise ValueError( f"person_id must stay the same across periods ({column})." @@ -289,7 +394,7 @@ def _require_group_values_agree(frame: pd.DataFrame, year: int, variables) -> No by_group: dict[str, list[str]] = {} for column in frame.columns: name = _variable_of(column) - if name in ID_VARIABLES: + if name in ID_VARIABLES or name not in variables: continue group = variables[name].entity.key if group in GROUP_ENTITIES: @@ -333,22 +438,95 @@ def _with_text_counties(frame: pd.DataFrame) -> pd.DataFrame: return frame.assign(**counties) -def _warn_about_unknown_counties(frame: pd.DataFrame) -> None: - """Say when a code names no county, because the model falls back silently.""" - from policyengine_us.tools.geography.county_helpers import ( - load_county_fips_dataset, - ) +def _county_lookup(frame: pd.DataFrame) -> Optional[pd.DataFrame]: + """Load the model's county lookup and warn about unmatched FIPS codes.""" + from policyengine_us.tools.geography.county_helpers import load_county_fips_dataset - held = set() - for column in _columns_of(frame, "county_fips"): - held |= set(frame[column].unique()) - {""} - unknown = held - set(load_county_fips_dataset()["county_fips"]) if held else held + columns = _columns_of(frame, "county_fips") + if not columns: + return None + lookup = load_county_fips_dataset() + held = set().union(*(frame[column].unique() for column in columns)) - {""} + unknown = held - set(lookup["county_fips"]) if unknown: logging.warning( f"county_fips holds {len(unknown)} code(s) that name no county, such as " - f"{min(unknown)}. Those households use the first county in their state " - "for county-keyed rules." + f"{min(unknown)}. The county formula uses the first county in the state " + "when it resolves an unmatched FIPS. A stored county can take precedence." ) + return lookup + + +def _with_yearly_counties( + frame: pd.DataFrame, + years: set[int], + default_state: int, + lookup: Optional[pd.DataFrame], +) -> pd.DataFrame: + """Store each input year's county so a calculation cannot change it.""" + from policyengine_us.tools.geography.county_helpers import map_county_string_to_enum + from policyengine_us.variables.household.demographic.geographic.county.county_enum import ( + County, + ) + + # The loader already has a stable county source if the file supplies one. + if _columns_of(frame, "county"): + return frame + + states = {} + for year in sorted(years): + state = _value_at(frame, "state_fips", year) + states[year] = ( + state if state is not None else pd.Series(default_state, index=frame.index) + ) + if lookup is None: + first_year = states[min(years)] + if all(state.equals(first_year) for state in states.values()): + return frame + + members = {member.index: member.name for member in County} + first_counties = {} + for member in sorted(County, key=lambda member: member.value): + if member != County.UNKNOWN: + fips = US_STATE_FIPS.get(member.value.rsplit(", ", 1)[-1]) + first_counties.setdefault(fips, member.name) + if lookup is not None: + county_by_code = map_county_string_to_enum( + lookup["county_name"], lookup["state"] + ).map(members) + county_by_code.index = lookup["county_fips"] + + counties = {} + for year, state in states.items(): + first = state.map(first_counties).fillna(County.UNKNOWN.name) + codes = _value_at(frame, "county_fips", year) + counties[f"county__{year}"] = ( + first if codes is None else codes.map(county_by_code).fillna(first) + ) + return frame.assign(**counties) + + +def _with_enum_names(frame: pd.DataFrame, variables) -> pd.DataFrame: + """Use the loader's enum encoding before comparing places by name.""" + names = {} + for name in ("state_code", "state_name", "county"): + enum = variables[name].possible_values + members = np.array([member.name for member in enum]) + for column in _columns_of(frame, name): + values = np.asarray(frame[column].values) + if ( + values.dtype.kind in "iu" + and ((values < 0) | (values >= len(members))).any() + ): + raise ValueError(f"{column} holds an invalid {enum.__name__} index.") + try: + indices = np.asarray(enum.encode(values)) + except (TypeError, ValueError) as error: + raise ValueError(f"Invalid {column}: {error}") from error + if ((indices < 0) | (indices >= len(members))).any(): + raise ValueError(f"{column} holds an invalid {enum.__name__} index.") + names[column] = members[indices] + return frame.assign(**names) def _state_fips(state: Union[str, int]) -> int: @@ -368,6 +546,8 @@ def _input_years(frame: pd.DataFrame, year: int) -> set[int]: """Collect the requested year and every year the dated inputs touch.""" years = {year} for column in frame: + if column == "role": + continue period = periods.period(column.split("__", 1)[1]) if period.unit != periods.ETERNITY: years.update(range(period.start.year, period.stop.year + 1)) @@ -457,10 +637,30 @@ def _require_coherent_geography( def _digest(frame: pd.DataFrame) -> str: - """A fingerprint of a prepared frame, whatever order its columns take.""" - ordered = frame[sorted(frame.columns)] - rows = pd.util.hash_pandas_object(ordered, index=False).to_numpy().tobytes() - return hashlib.sha256("|".join(ordered.columns).encode() + rows).hexdigest() + """Fingerprint typed values in row order and a canonical column order.""" + digest = hashlib.sha256() + + def add_text(value: str) -> None: + encoded = value.encode("utf-8", errors="surrogatepass") + digest.update(len(encoded).to_bytes(8, "big")) + digest.update(encoded) + + add_text(str(len(frame))) + for column in sorted(frame.columns): + series = frame[column] + add_text(column) + add_text(str(series.dtype)) + if isinstance(series.dtype, np.dtype) and not series.dtype.hasobject: + values = series.to_numpy() + add_text(values.dtype.str) + digest.update(values.tobytes()) + else: + # NumPy reads False and "False" differently in an object column. + for value in series.array: + kind = type(value) + add_text(f"{kind.__module__}.{kind.__qualname__}") + add_text(repr(value)) + return digest.hexdigest() def prepare_flat_file( @@ -475,8 +675,7 @@ def prepare_flat_file( people: One row per person, with a group ID for each of the household, tax unit, SPM unit, family and marital unit, plus ``age``. Columns are named ``variable`` or ``variable__period``. ``person_id`` is - optional. The run ignores columns that name no variable, and logs - them. Stored copies of what the model derives from the state, such + optional. The run keeps group role columns and logs unused columns. Stored copies of what the model derives from the state, such as ``state_group``, leave too, so the formulas run. year: The year the file describes. A column without a period holds that year's value. @@ -491,10 +690,19 @@ def prepare_flat_file( """ from policyengine_us.system import system + return _prepare_flat_file(people, year, state, system) + + +def _prepare_flat_file(people: pd.DataFrame, year: int, state, system) -> pd.DataFrame: + variables = system.variables + group_roles = { + f"{system.person_entity.key}_{entity.key}_role" + for entity in system.group_entities + } if people.empty: raise ValueError("The file has no rows.") - frame = _without_unknown_columns(people, system.variables) - frame = _with_periods(frame, year, system.variables) + frame = _without_unknown_columns(people, variables, group_roles) + frame = _with_periods(frame, year, variables, group_roles) years = _input_years(frame, year) if state is not None: frame = _in_state(frame, _state_fips(state), years) @@ -513,7 +721,7 @@ def prepare_flat_file( ages = pd.to_numeric(frame[column], errors="coerce") if not np.isfinite(ages).fillna(False).all(): raise ValueError(f"{column} needs a finite age for every person.") - frame = _with_person_level_ids(frame, year) + frame = _with_person_level_ids(frame, year, variables) _require_groups_within_households(frame, year) if state is None: for column in _columns_of(frame, "state_fips"): @@ -522,11 +730,13 @@ def prepare_flat_file( except (TypeError, ValueError) as error: raise ValueError(f"Invalid state_fips in {column}: {error}") from error frame = _with_text_counties(frame) - _require_coherent_geography( - frame, year, years, system.variables["state_fips"].default_value + frame = _with_enum_names(frame, variables) + default_state = variables["state_fips"].default_value + _require_coherent_geography(frame, year, years, default_state) + frame = _with_yearly_counties( + frame, years, default_state, _county_lookup(frame) ) - _warn_about_unknown_counties(frame) - _require_group_values_agree(frame, year, system.variables) + _require_group_values_agree(frame, year, variables) return frame @@ -555,7 +765,7 @@ def flat_file_microsimulation( Returns: A ``Microsimulation`` carrying this release's ``policyengine_bundle``, whose ``flat_file`` entry records the year, the state and a SHA-256 - fingerprint of the prepared frame's column names and row hashes. + fingerprint of the prepared frame's typed values. """ from policyengine_core.data import Dataset from policyengine_us import Microsimulation @@ -563,9 +773,20 @@ def flat_file_microsimulation( if "dataset" in kwargs: raise ValueError("flat_file_microsimulation builds its dataset from `people`.") - prepared = prepare_flat_file(people, year=year, state=state) - microsim = Microsimulation( - dataset=Dataset.from_dataframe(prepared, year), + class FlatFileMicrosimulation(Microsimulation): + def build_from_dataset(self): + # The US constructor has registered reform variables by this point. + prepared = _prepare_flat_file( + self.dataset.load(), year, state, self.tax_benefit_system + ) + self.dataset = Dataset.from_dataframe(prepared, year) + super().build_from_dataset() + # The pinned formula treats cached counties as stored inputs. + # Explicit county inputs still use the holder's normal input storage. + self.get_holder("county")._do_not_store = True + + microsim = FlatFileMicrosimulation( + dataset=Dataset.from_dataframe(people, year), spm=resolve_spm_selection(spm), **kwargs, ) @@ -581,7 +802,7 @@ def flat_file_microsimulation( microsim.policyengine_bundle["flat_file"] = { "year": year, "state": None if state is None else _state_fips(state), - "sha256": _digest(prepared), + "sha256": _digest(microsim.dataset.load()), } microsim.policyengine_bundle["spm"] = dict(microsim.spm_config) return microsim diff --git a/tests/test_us_flat_file.py b/tests/test_us_flat_file.py index da0c69586..5f9039209 100644 --- a/tests/test_us_flat_file.py +++ b/tests/test_us_flat_file.py @@ -10,6 +10,20 @@ pytest.importorskip("policyengine_us") +from policyengine_core import periods # noqa: E402 +from policyengine_core.model_api import Variable # noqa: E402 +from policyengine_us import Microsimulation # noqa: E402 +from policyengine_us.entities import Person # noqa: E402 +from policyengine_us.variables.household.demographic.geographic.county.county_enum import ( # noqa: E402 + County, +) +from policyengine_us.variables.household.demographic.geographic.state_code import ( # noqa: E402 + StateCode, +) +from policyengine_us.variables.household.demographic.geographic.state_name import ( # noqa: E402 + StateName, +) + import policyengine as pe # noqa: E402 from policyengine.countries.us.data import US_STATE_FIPS # noqa: E402 from policyengine.tax_benefit_models.us.flat_file import ( # noqa: E402 @@ -49,6 +63,12 @@ def survey() -> pd.DataFrame: ) +def one_person_households(ages): + return pd.DataFrame( + {**{column: range(len(ages)) for column in GROUP_COLUMNS}, "age": ages} + ) + + def in_state(frame: pd.DataFrame, fips: int = 6) -> pd.DataFrame: return frame.assign(state_fips=fips) @@ -214,6 +234,14 @@ def test_fractional_ids_name_their_column(self, dtype): with pytest.raises(ValueError, match=f"household_id__{YEAR}.*whole numbers"): prepare_flat_file(people, year=YEAR) + @pytest.mark.parametrize("column", ["household_id", "person_id"]) + def test_mixed_boolean_and_numeric_ids_name_their_column(self, column): + people = in_state(one_person_households([30, 40, 50])).assign( + **{column: pd.Series([1, True, 9], dtype=object)} + ) + with pytest.raises(ValueError, match=f"{column}__{YEAR}.*Boolean"): + prepare_flat_file(people, year=YEAR) + def test_a_person_on_two_rows(self): people = in_state(survey()).assign(person_id=1) with pytest.raises(ValueError, match="one row per person"): @@ -384,6 +412,22 @@ def test_a_state_and_county_that_move_together_stay(self): ) prepare_flat_file(people, year=YEAR) + @pytest.mark.parametrize( + "county", [County.ADAMS_COUNTY_MS.index, County.ADAMS_COUNTY_MS.name] + ) + def test_county_enum_outside_its_state(self, county): + people = in_state(survey()).assign(county=county) + with pytest.raises(ValueError, match="county outside"): + prepare_flat_file(people, year=YEAR) + + def test_matching_state_enum_members(self): + people = in_state(survey()).assign( + state_code=StateCode.CA, state_name=StateName.CA + ) + sim = pe.us.flat_file_microsimulation(people, year=YEAR, spm=NATIONAL_SPM) + for name in ("state_code", "state_name"): + assert sim.calculate(name, YEAR).tolist() == ["CA"] * 3 + def test_a_label_that_disagrees_with_the_state(self): people = in_state(survey(), MISSISSIPPI).assign(state_code="CA") with pytest.raises(ValueError, match="state_code"): @@ -400,6 +444,16 @@ def test_a_code_that_names_no_county_gets_a_warning(self, caplog): prepare_flat_file(people, year=YEAR) assert "name no county" in caplog.text + def test_a_stored_county_takes_precedence_over_an_unmatched_fips(self, caplog): + people = in_state(survey()).assign( + county_fips="06999", county=County.LOS_ANGELES_COUNTY_CA.name + ) + sim = pe.us.flat_file_microsimulation(people, year=YEAR, spm=NATIONAL_SPM) + assert "name no county" in caplog.text + assert "when it resolves an unmatched FIPS" in caplog.text + assert "A stored county can take precedence" in caplog.text + assert sim.calculate("county", YEAR).tolist() == ["LOS_ANGELES_COUNTY_CA"] * 3 + def test_a_real_county_stays_quiet(self, caplog): people = in_state(survey()).assign(county_fips=LOS_ANGELES_COUNTY) with caplog.at_level(logging.WARNING): @@ -407,6 +461,36 @@ def test_a_real_county_stays_quiet(self, caplog): assert "name no county" not in caplog.text +@pytest.mark.parametrize("order", [(2024, 2025), (2025, 2024)]) +def test_each_year_keeps_its_own_county_regardless_of_calculation_order(order): + people = one_person_households([40]).assign( + state_fips__2024=6, + county_fips__2024="06037", + state_fips__2025=50, + county_fips__2025="50007", + pre_subsidy_rent__2025=12000, + ) + prepared = prepare_flat_file(people, year=2024) + sim = Microsimulation(dataset=prepared, default_input_period=2024) + expected = {2024: "LOS_ANGELES_COUNTY_CA", 2025: "CHITTENDEN_COUNTY_VT"} + counties = {} + for year in order: + counties[year] = sim.calculate("county", year).tolist() + if year == 2025: + allowance = sim.calculate("vt_reach_up_housing_allowance", "2025-01") + assert counties[2025] == [expected[2025]] + assert allowance.tolist() == [450] + assert counties[2024] == [expected[2024]] + + +def test_each_recorded_state_has_its_own_fallback_county(): + people = one_person_households([40]).assign(state_fips=6, state_fips__2025=28) + prepared = prepare_flat_file(people, year=YEAR) + sim = Microsimulation(dataset=prepared, default_input_period=YEAR) + assert sim.calculate("county", 2024).tolist() == ["ALAMEDA_COUNTY_CA"] + assert sim.calculate("county", 2025).tolist() == ["ADAMS_COUNTY_MS"] + + class TestMovingToAState: def test_a_file_may_start_with_no_state(self): prepared = prepare_flat_file(survey(), year=YEAR, state="MS") @@ -434,6 +518,11 @@ def test_every_year_moves(self): assert len(columns) == 3 assert set(prepared[columns].to_numpy().ravel()) == {MISSISSIPPI} + def test_preparing_a_moved_file_with_several_years_again_keeps_its_inputs(self): + people = survey().assign(state_fips__2025=6) + moved = prepare_flat_file(people, year=YEAR, state="MS") + pd.testing.assert_frame_equal(moved, prepare_flat_file(moved, year=YEAR)) + def test_a_moved_file_may_hold_one_stale_county_per_person(self): people = survey().assign(county_fips=[f"{index:05d}" for index in range(7)]) prepared = prepare_flat_file(people, year=YEAR, state="MS") @@ -533,6 +622,33 @@ def digest(people): reordered = people[list(reversed(people.columns))] assert digest(people) == digest(reordered) assert digest(people) != digest(people.assign(age=people["age"] + 1)) + assert digest(people) != digest( + people.assign(household_weight=people.household_weight * 2) + ) + + +def test_the_fingerprint_distinguishes_loader_coercion_of_booleans_and_strings(): + people = in_state( + pd.DataFrame({**{column: [1, 1] for column in GROUP_COLUMNS}, "age": [17, 20]}) + ) + sims = [ + pe.us.flat_file_microsimulation( + people.assign(is_household_head=pd.Series(values, dtype=object)), + year=YEAR, + spm=NATIONAL_SPM, + ) + for values in ([False, "False"], ["False", False]) + ] + assert [sim.calculate("is_household_head", YEAR).tolist() for sim in sims] == [ + [False, True], + [True, False], + ] + thresholds = [sim.calculate("spm_unit_spm_threshold", YEAR).iloc[0] for sim in sims] + assert thresholds == pytest.approx([27_429.15, 25_629.53], abs=0.01) + assert ( + sims[0].policyengine_bundle["flat_file"]["sha256"] + != sims[1].policyengine_bundle["flat_file"]["sha256"] + ) def test_one_person_groups_keep_their_own_values_in_any_order(): @@ -600,6 +716,26 @@ def test_results_merge_back_on_the_files_own_ids(): assert merged["weight"].tolist() == people["household_weight"].tolist() +def test_family_ids_keep_distinct_groups_when_model_storage_loses_precision(caplog): + source_ids = [16777216, 16777217, 2147483647] + families = one_person_households([30, 40, 50]).assign( + family_id=source_ids, household_weight=[100, 200, 300] + ) + people = in_state(families.iloc[[1, 0, 2, 1]].reset_index(drop=True)) + sim = pe.us.flat_file_microsimulation(people, year=YEAR, spm=NATIONAL_SPM) + assert sim.calculate("family_id", YEAR).tolist() == [0, 1, 2] + assert sim.calculate("family_id", YEAR, map_to="person").tolist() == [0, 1, 2, 0] + assert f"family_id__{YEAR}" in caplog.text + + +def test_exact_float_ids_can_exceed_the_signed_integer_range(caplog): + ids = [2**63, 2**64, 2**65] + people = in_state(one_person_households([30, 40, 50])).assign(family_id=ids) + sim = pe.us.flat_file_microsimulation(people, year=YEAR) + assert [int(value) for value in sim.calculate("family_id", YEAR)] == ids + assert f"family_id__{YEAR}" not in caplog.text + + def test_a_stored_state_group_does_not_set_the_poverty_guideline(): clean = pe.us.flat_file_microsimulation(survey(), year=YEAR, state="AK") stale = pe.us.flat_file_microsimulation( @@ -633,6 +769,154 @@ def test_stale_geography_changes_nothing_after_a_move(): assert np.array_equal(first, second), variable +@pytest.mark.parametrize( + "stale_input, value, outcome, period", + [ + ("in_la", True, "la_general_relief_age_eligible", "2024-01"), + ("slcsp_rating_area", 0, "slcsp_age_0", "2024-01"), + ("slcsp_rating_area_default", 0, "slcsp_age_0", "2024-01"), + ], +) +def test_stale_location_inputs_let_the_new_state_calculate( + stale_input, value, outcome, period +): + people = one_person_households([40]) + clean, moved = [ + pe.us.flat_file_microsimulation(arm, year=YEAR, state="MS", spm=NATIONAL_SPM) + for arm in (people, people.assign(**{stale_input: value}, state_fips=6)) + ] + assert ( + moved.calculate(outcome, period).tolist() + == clean.calculate(outcome, period).tolist() + ) + + +LOCATION_INPUTS = ( + "ak_ccap_rate_region", + "al_ccsp_region", + "ami", + "ar_sra_zone", + "ca_tanf_region1", + "ct_c4k_region", + "ct_tfa_region", + "ga_caps_zone", + "hud_extremely_low_income_limit", + "hud_fair_market_rent", + "hud_low_income_limit", + "hud_utility_allowance", + "hud_very_low_income_limit", + "id_iccp_county_cluster", + "il_aabd_area", + "il_ccap_county_group", + "il_dhs_csfp_county_eligible", + "il_tanf_county_group", + "in_ala", + "in_cc", + "in_denver", + "in_harris_county_tx", + "in_la", + "in_marin", + "in_multnomah_county_or", + "in_oc", + "in_riv", + "in_san_francisco", + "in_sbd", + "in_scc", + "in_smc", + "in_wilmington", + "in_yonkers", + "is_in_snap_abawd_waived_area", + "ks_ccap_rate_group", + "ks_dcf_csfp_county_eligible", + "ks_tanf_county_group", + "ky_ccap_rate_region", + "lcbp_age_0", + "ma_ccfa_region", + "ma_dese_csfp_county_eligible", + "md_ccs_region", + "me_ccap_region", + "mo_ccs_region", + "ms_ccpp_facility_location", + "ne_child_care_subsidy_location", + "nv_ccdp_region", + "ny_ccap_county_group", + "oh_ccap_county_rate_category", + "or_erdc_provider_area", + "pa_ccw_region", + "pa_ccw_stepparent_county_group", + "pa_tanf_county_group", + "pha_payment_standard", + "sc_ccap_geography", + "sd_cca_region", + "slcsp_age_0", + "slcsp_rating_area", + "slcsp_rating_area_default", + "slcsp_rating_area_la_county", + "snap_region", + "snap_region_str", + "snap_utility_region", + "snap_utility_region_str", + "taxsim_state", + "tn_ccap_county_tier", + "tx_ccs_workforce_board_region", + "va_ccsp_locality_group", + "va_ccsp_ready_region", + "va_medicaid_lifc_locality_group", + "wa_wccc_center_region", + "wa_wccc_region", + "zip_code_payment_standard", +) + + +@pytest.fixture(scope="module") +def location_input_move(): + people = one_person_households([40]) + clean = pe.us.flat_file_microsimulation(people, year=YEAR, state="MS") + clean_values = {} + stale = {} + for name in LOCATION_INPUTS: + variable = clean.tax_benefit_system.get_variable(name, check_existence=True) + period = "2024-01" if variable.definition_period == periods.MONTH else YEAR + expected = clean.calculate(name, period).tolist() + clean_values[name] = period, expected + first = expected[0] + if variable.value_type is bool: + stale_value = not first + elif variable.value_type is str: + stale_value = "stale geography" + elif variable.value_type in (int, float): + stale_value = 999 if first != 999 else 998 + else: + stale_value = next( + member.name + for member in variable.possible_values + if member.name != first + ) + stale[f"{name}__{period}"] = stale_value + moved = pe.us.flat_file_microsimulation( + people.assign(**stale, state_fips=6), year=YEAR, state="MS" + ) + return moved, clean_values + + +@pytest.mark.parametrize("name", LOCATION_INPUTS) +def test_stored_location_inputs_match_a_clean_run(name, location_input_move): + moved, clean_values = location_input_move + period, expected = clean_values[name] + assert moved.calculate(name, period).tolist() == expected + + +@pytest.mark.parametrize("order", [(2023, 2024), (2024, 2023)]) +def test_a_moved_file_calculates_fallback_counties_independently(order): + sim = pe.us.flat_file_microsimulation( + one_person_households([40]), year=YEAR, state="MS" + ) + assert {year: sim.calculate("county", year).tolist() for year in order} == { + 2023: ["ALAMEDA_COUNTY_CA"], + 2024: ["ADAMS_COUNTY_MS"], + } + + def test_national_thresholds_do_not_depend_on_the_state(): thresholds = [ pe.us.flat_file_microsimulation( @@ -687,6 +971,33 @@ def test_keywords_reach_the_simulation(): assert reformed > sim.baseline.calculate("ctc", YEAR).sum() +@pytest.mark.parametrize("column", ["person_tax_unit_role__2024", "role"]) +def test_the_loader_reads_role_columns(column): + people = one_person_households([30, 40]).assign(**{column: ["member", "invalid"]}) + sim = pe.us.flat_file_microsimulation(people, year=YEAR, state="MS") + roles = sim.populations["tax_unit"].members_role + assert [getattr(role, "key", None) for role in roles] == ["member", None] + + +def test_the_loader_reads_reform_registered_inputs(): + class research_payment(Variable): + label = "Research payment" + value_type = float + entity = Person + definition_period = periods.YEAR + + class ResearchPayment: + @staticmethod + def apply(system): + system.update_variable(research_payment) + + people = one_person_households([40]).assign(research_payment=1250) + sim = pe.us.flat_file_microsimulation( + people, year=YEAR, state="MS", reform=ResearchPayment + ) + assert sim.calculate("research_payment", YEAR).tolist() == [1250] + + def test_a_dataset_is_refused(): with pytest.raises(ValueError, match="people"): pe.us.flat_file_microsimulation(survey(), year=YEAR, dataset="other.h5") From cda0744c60cb76659fa8b9737df0c0198bda7f5d Mon Sep 17 00:00:00 2001 From: "GPT-6.2 Sol" Date: Tue, 1 Dec 2026 08:48:02 -0500 Subject: [PATCH 10/14] Fingerprint the values the US model stores from flat-file inputs Co-Authored-By: GPT-6.2 Sol Co-Authored-By: Claude Opus 5.5 --- .../tax_benefit_models/us/flat_file.py | 41 ++++++++++++------- tests/test_us_flat_file.py | 14 +++++++ 2 files changed, 41 insertions(+), 14 deletions(-) diff --git a/src/policyengine/tax_benefit_models/us/flat_file.py b/src/policyengine/tax_benefit_models/us/flat_file.py index 4e8cd05b4..ca5661d39 100644 --- a/src/policyengine/tax_benefit_models/us/flat_file.py +++ b/src/policyengine/tax_benefit_models/us/flat_file.py @@ -636,8 +636,8 @@ def _require_coherent_geography( ) -def _digest(frame: pd.DataFrame) -> str: - """Fingerprint typed values in row order and a canonical column order.""" +def _digest(frame: pd.DataFrame, simulation) -> str: + """Fingerprint the prepared frame and the model's stored inputs.""" digest = hashlib.sha256() def add_text(value: str) -> None: @@ -645,21 +645,34 @@ def add_text(value: str) -> None: digest.update(len(encoded).to_bytes(8, "big")) digest.update(encoded) - add_text(str(len(frame))) - for column in sorted(frame.columns): - series = frame[column] - add_text(column) - add_text(str(series.dtype)) - if isinstance(series.dtype, np.dtype) and not series.dtype.hasobject: - values = series.to_numpy() - add_text(values.dtype.str) - digest.update(values.tobytes()) + def add_values(values) -> None: + dtype = values.dtype + add_text(str(dtype)) + add_text(str(len(values))) + if isinstance(dtype, np.dtype) and not dtype.hasobject: + add_text(dtype.str) + digest.update(np.asarray(values).tobytes()) else: # NumPy reads False and "False" differently in an object column. - for value in series.array: + for value in values: kind = type(value) add_text(f"{kind.__module__}.{kind.__qualname__}") add_text(repr(value)) + + add_text(str(len(frame.columns))) + for column in sorted(frame.columns): + add_text(column) + add_values(frame[column].array) + + # The core can allocate overlapping input periods in column order. + # Include its stored inputs so either allocation has its own fingerprint. + for name, branch, period in sorted(simulation._user_input_keys): + values = simulation.get_holder(name).get_array(period, branch) + if values is not None: + add_text(name) + add_text(branch) + add_text(str(period)) + add_values(values) return digest.hexdigest() @@ -765,7 +778,7 @@ def flat_file_microsimulation( Returns: A ``Microsimulation`` carrying this release's ``policyengine_bundle``, whose ``flat_file`` entry records the year, the state and a SHA-256 - fingerprint of the prepared frame's typed values. + fingerprint of the prepared frame and the model's stored inputs. """ from policyengine_core.data import Dataset from policyengine_us import Microsimulation @@ -802,7 +815,7 @@ def build_from_dataset(self): microsim.policyengine_bundle["flat_file"] = { "year": year, "state": None if state is None else _state_fips(state), - "sha256": _digest(microsim.dataset.load()), + "sha256": _digest(microsim.dataset.load(), microsim), } microsim.policyengine_bundle["spm"] = dict(microsim.spm_config) return microsim diff --git a/tests/test_us_flat_file.py b/tests/test_us_flat_file.py index 5f9039209..435b7a3af 100644 --- a/tests/test_us_flat_file.py +++ b/tests/test_us_flat_file.py @@ -651,6 +651,20 @@ def test_the_fingerprint_distinguishes_loader_coercion_of_booleans_and_strings() ) +def test_the_fingerprint_distinguishes_overlapping_input_periods(): + people = one_person_households([40]).assign(snap__2024=120, **{"snap__2024-03": 20}) + first, second = [ + pe.us.flat_file_microsimulation(frame, year=YEAR, state="MS") + for frame in (people, people.iloc[:, ::-1]) + ] + assert first.calculate("snap", "2024-04").tolist() == [10] + assert second.calculate("snap", "2024-04").tolist() == pytest.approx([100 / 11]) + assert ( + first.policyengine_bundle["flat_file"]["sha256"] + != second.policyengine_bundle["flat_file"]["sha256"] + ) + + def test_one_person_groups_keep_their_own_values_in_any_order(): people = pd.DataFrame( { From c53060e6a8f1e12ef0439f1828ab03af6a3bd16e Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 2 Dec 2026 16:02:59 -0500 Subject: [PATCH 11/14] Infer counties at calculation time and keep supplied local geography Round 3 found that stored county inputs leaked a future county into earlier years and masked county reforms; that state assignment dropped the Oregon child-care provider area; that a member of the wrong enum passed geography checks; that dated role headers collided; and that stored enum inputs with different members could share a fingerprint. The helper no longer writes county inputs: inferred counties come from the active model formula and stay out of cross-year lookups. State assignment keeps the Oregon provider area and the Mississippi facility location. Geography checks the enum class before encoding. The first role column per entity is kept before periods are added. The fingerprint now includes the enum and its member names. The guide and module text now match the base-registry path, the bare role column, the loader's role warning and the county fallback. Tests cover each case, and the overlapping-period test now runs for SNAP and SSI. Co-Authored-By: Claude Opus 5.5 --- docs/simulated-instruments.md | 12 +- .../tax_benefit_models/us/flat_file.py | 153 +++++++++--------- tests/test_us_flat_file.py | 143 ++++++++++++++-- 3 files changed, 213 insertions(+), 95 deletions(-) diff --git a/docs/simulated-instruments.md b/docs/simulated-instruments.md index 11e23e570..9b32a58f9 100644 --- a/docs/simulated-instruments.md +++ b/docs/simulated-instruments.md @@ -36,6 +36,8 @@ To run each household in the state your file records, leave `state` out. The fil The file holds one row per person. Name a column after a PolicyEngine variable, or `variable__period` to date it. A column with no period holds the value for `year`. Use calendar years for age and for the geography fields the helper validates. Group membership stays fixed across periods. The loader also reads `person_{group}_role` columns and uses a bare `role` column for groups without their own roles. +If several columns give roles for the same group entity, the loader uses the first one in file order. The pinned loader's unused-variable warning can list role columns it has already used to assign roles. + | Column | Needed | Notes | | --- | --- | --- | | `household_id`, `tax_unit_id`, `spm_unit_id`, `family_id`, `marital_unit_id` | Yes | Put each on every person's row, numbered across the whole file. | @@ -53,12 +55,14 @@ for column in ["tax_unit_id", "spm_unit_id", "family_id", "marital_unit_id"]: people[column] = people.groupby(["household_id", column]).ngroup() ``` -To see what the simulation loads, run the checks on their own: +You can inspect how the helper prepares inputs for the base US model. ```python prepared = pe.us.prepare_flat_file(people, year=2024, state="MS") ``` +Standalone preparation uses the base US variable registry. Pass the original frame directly to `pe.us.flat_file_microsimulation` for inputs added by `reform=` on the default system. With an explicit `tax_benefit_system`, register additional input variables on that system before calling the simulation helper. + `prepare_flat_file` refuses a file that: - lacks a required column @@ -70,7 +74,7 @@ With `state` left out, it also refuses a county, tract, block, congressional dis The helper warns about unused columns and well-formed county FIPS codes absent from the model's lookup. The county formula uses the first county in the state when it resolves an unmatched FIPS. A stored county can take precedence. -When the file records its own geography, preparation fixes each covered year's county from its state and county FIPS inputs or uses the county values the file supplies. Calculating an earlier or later covered year first leaves that county and its benefits unchanged. +When the file records its own geography, preparation validates state and county inputs for every covered year. The simulation uses the active county formula to infer counties and keeps inferred values out of county storage. Supplied county inputs retain the loader's precedence. ## Reading results back @@ -84,9 +88,9 @@ people["state_tax"] = sim.calculate("state_income_tax", 2024, map_to="person").v ## What a state change clears -Passing `state` sets `state_fips` in every year your file holds. It clears county, ZIP code, congressional district, tract and other local geography for every household, including those already in the assigned state. It also clears location-based inputs such as `is_rural`, `in_la`, ACA rating areas, SNAP utility regions, child care regions and HUD rent lookups. Supply source inputs for the outcome you want to measure. A stored outcome such as eligibility or tax can override its formula. +Passing `state` sets `state_fips` in every year your file holds. It clears county, ZIP code, congressional district, tract and other local geography for every household, including those already in the assigned state. It also clears location-based inputs such as `is_rural`, `in_la`, ACA rating areas, SNAP utility regions, household-based child care regions and HUD rent lookups. It preserves supplied provider locations such as Oregon's `or_erdc_provider_area` and Mississippi's `ms_ccpp_facility_location`. A stored outcome such as eligibility or tax can override its formula. -With no county, the model applies county-keyed rules using the first county in the state alphabetically, such as Aitkin County in Minnesota. The bundle defaults to county-based SPM thresholds. The recipe passes `{"geography_kind": "national"}` so every state uses the same national SPM thresholds for the same household inputs. To keep real counties, leave `state` out and run each household where the file records it. +Rules that read the county enum use the state's first county alphabetically when a county is missing. In Minnesota that is Aitkin County. The bundle defaults to county-based SPM thresholds. The recipe passes `{"geography_kind": "national"}` so every state uses the same national SPM thresholds for the same household inputs. To keep real counties, leave `state` out and run each household where the file records it. With or without `state`, the helper removes stored copies of what the model derives from the state, such as `state_group`, so the model's formulas run. diff --git a/src/policyengine/tax_benefit_models/us/flat_file.py b/src/policyengine/tax_benefit_models/us/flat_file.py index ca5661d39..dfb513a5c 100644 --- a/src/policyengine/tax_benefit_models/us/flat_file.py +++ b/src/policyengine/tax_benefit_models/us/flat_file.py @@ -7,18 +7,20 @@ ``prepare_flat_file`` does that work and checks the file first, because a missing column does not fail on its own: without ``state_fips`` every household runs as -California. It names columns ``variable__period`` and puts each person's -groups on their own row. +California. It adds periods to variable columns, preserves the bare ``role`` +column, and puts each person's groups on their own row. """ import hashlib import logging +from enum import Enum from numbers import Number from typing import Optional, Union import numpy as np import pandas as pd from policyengine_core import periods +from policyengine_core.enums import EnumArray from policyengine.countries.us.data import US_STATE_FIPS from policyengine.tax_benefit_models.common.model_version import ( @@ -39,8 +41,9 @@ } ) STATE_LABELS = ("state_code", "state_code_str", "state_name") -# Local geography, including the model's local flags, programme regions, -# rating areas and location-based lookups. +# Household geography, including local flags, programme regions, rating areas +# and location-based lookups. Child-care provider and facility locations can +# differ from the household's recorded location. LOCAL_GEOGRAPHY = ( "ak_ccap_rate_region", "al_ccsp_region", @@ -98,12 +101,10 @@ "me_ccap_region", "medicaid_rating_area", "mo_ccs_region", - "ms_ccpp_facility_location", "ne_child_care_subsidy_location", "nv_ccdp_region", "ny_ccap_county_group", "oh_ccap_county_rate_category", - "or_erdc_provider_area", "pa_ccw_region", "pa_ccw_stepparent_county_group", "pa_tanf_county_group", @@ -223,7 +224,10 @@ def column_name(column): suffix = str(period) return f"{name}__{suffix}" - frame = people.rename(columns=column_name) + # The loader uses the first role column for each entity across all periods. + names = people.columns.map(lambda column: _variable_of(str(column))) + later_roles = names.isin(group_roles) & names.duplicated() + frame = people.loc[:, ~later_roles].rename(columns=column_name) repeated = frame.columns[frame.columns.duplicated()].unique().tolist() if repeated: raise ValueError( @@ -438,82 +442,54 @@ def _with_text_counties(frame: pd.DataFrame) -> pd.DataFrame: return frame.assign(**counties) -def _county_lookup(frame: pd.DataFrame) -> Optional[pd.DataFrame]: - """Load the model's county lookup and warn about unmatched FIPS codes.""" +def _warn_unknown_county_fips(frame: pd.DataFrame) -> None: + """Warn about nonblank FIPS codes absent from the model's lookup.""" from policyengine_us.tools.geography.county_helpers import load_county_fips_dataset - columns = _columns_of(frame, "county_fips") - if not columns: - return None - lookup = load_county_fips_dataset() - held = set().union(*(frame[column].unique() for column in columns)) - {""} - unknown = held - set(lookup["county_fips"]) + held = set().union( + *(frame[column].unique() for column in _columns_of(frame, "county_fips")) + ) - {""} + if not held: + return + unknown = held - set(load_county_fips_dataset()["county_fips"]) if unknown: logging.warning( f"county_fips holds {len(unknown)} code(s) that name no county, such as " f"{min(unknown)}. The county formula uses the first county in the state " "when it resolves an unmatched FIPS. A stored county can take precedence." ) - return lookup -def _with_yearly_counties( - frame: pd.DataFrame, - years: set[int], - default_state: int, - lookup: Optional[pd.DataFrame], -) -> pd.DataFrame: - """Store each input year's county so a calculation cannot change it.""" - from policyengine_us.tools.geography.county_helpers import map_county_string_to_enum +def _with_enum_names(frame: pd.DataFrame, variables) -> pd.DataFrame: + """Use the loader's enum encoding before comparing places by name.""" from policyengine_us.variables.household.demographic.geographic.county.county_enum import ( County, ) + from policyengine_us.variables.household.demographic.geographic.state_code import ( + StateCode, + ) + from policyengine_us.variables.household.demographic.geographic.state_name import ( + StateName, + ) - # The loader already has a stable county source if the file supplies one. - if _columns_of(frame, "county"): - return frame - - states = {} - for year in sorted(years): - state = _value_at(frame, "state_fips", year) - states[year] = ( - state if state is not None else pd.Series(default_state, index=frame.index) - ) - if lookup is None: - first_year = states[min(years)] - if all(state.equals(first_year) for state in states.values()): - return frame - - members = {member.index: member.name for member in County} - first_counties = {} - for member in sorted(County, key=lambda member: member.value): - if member != County.UNKNOWN: - fips = US_STATE_FIPS.get(member.value.rsplit(", ", 1)[-1]) - first_counties.setdefault(fips, member.name) - if lookup is not None: - county_by_code = map_county_string_to_enum( - lookup["county_name"], lookup["state"] - ).map(members) - county_by_code.index = lookup["county_fips"] - - counties = {} - for year, state in states.items(): - first = state.map(first_counties).fillna(County.UNKNOWN.name) - codes = _value_at(frame, "county_fips", year) - counties[f"county__{year}"] = ( - first if codes is None else codes.map(county_by_code).fillna(first) - ) - return frame.assign(**counties) - - -def _with_enum_names(frame: pd.DataFrame, variables) -> pd.DataFrame: - """Use the loader's enum encoding before comparing places by name.""" + # Core loads variable files under distinct module names. Accept the model's + # public enums and the active registry's enums, matching members by name. + places = {"state_code": StateCode, "state_name": StateName, "county": County} names = {} - for name in ("state_code", "state_name", "county"): + for name, model_enum in places.items(): enum = variables[name].possible_values members = np.array([member.name for member in enum]) for column in _columns_of(frame, name): values = np.asarray(frame[column].values) + if values.dtype.kind == "O": + values = values.copy() + for index, value in enumerate(values): + if isinstance(value, Enum): + if not isinstance(value, (enum, model_enum)): + raise ValueError( + f"{column} holds a member outside {enum.__name__}." + ) + values[index] = value.name if ( values.dtype.kind in "iu" and ((values < 0) | (values >= len(members))).any() @@ -659,6 +635,22 @@ def add_values(values) -> None: add_text(f"{kind.__module__}.{kind.__qualname__}") add_text(repr(value)) + def add_enum(values: EnumArray, variable) -> None: + enum = values.possible_values + module = enum.__module__ + # Core gives loaded variable modules process-specific names. For an + # enum defined alongside its variable, use the stable source path. + if module == type(variable).__module__ and variable.module_name: + module = variable.module_name + add_text(module) + add_text(enum.__qualname__) + names = {member.index: member.name for member in enum} + # The stored integer array already gives the order and multiplicity. + selected = np.unique(np.asarray(values)) + add_text(str(len(selected))) + for index in selected: + add_text(names.get(index, "")) + add_text(str(len(frame.columns))) for column in sorted(frame.columns): add_text(column) @@ -667,11 +659,17 @@ def add_values(values) -> None: # The core can allocate overlapping input periods in column order. # Include its stored inputs so either allocation has its own fingerprint. for name, branch, period in sorted(simulation._user_input_keys): - values = simulation.get_holder(name).get_array(period, branch) + holder = simulation.get_holder(name) + values = holder.get_array(period, branch) if values is not None: add_text(name) add_text(branch) add_text(str(period)) + if isinstance(values, EnumArray) and values.possible_values is not None: + add_text("enum") + add_enum(values, holder.variable) + else: + add_text("array") add_values(values) return digest.hexdigest() @@ -688,8 +686,9 @@ def prepare_flat_file( people: One row per person, with a group ID for each of the household, tax unit, SPM unit, family and marital unit, plus ``age``. Columns are named ``variable`` or ``variable__period``. ``person_id`` is - optional. The run keeps group role columns and logs unused columns. Stored copies of what the model derives from the state, such - as ``state_group``, leave too, so the formulas run. + optional. Preparation keeps the role columns the loader reads and + logs unused columns against the base US registry. It clears stored + copies of state-derived fields such as ``state_group``. year: The year the file describes. A column without a period holds that year's value. state: A postal code or FIPS code to run every household in. It applies @@ -746,9 +745,7 @@ def _prepare_flat_file(people: pd.DataFrame, year: int, state, system) -> pd.Dat frame = _with_enum_names(frame, variables) default_state = variables["state_fips"].default_value _require_coherent_geography(frame, year, years, default_state) - frame = _with_yearly_counties( - frame, years, default_state, _county_lookup(frame) - ) + _warn_unknown_county_fips(frame) _require_group_values_agree(frame, year, variables) return frame @@ -763,9 +760,13 @@ def flat_file_microsimulation( ): """Build a bundled ``Microsimulation`` over a researcher's own flat file. - A file moved to a ``state`` has no county, so county-keyed rules use the - first county in that state, and SPM thresholds need - ``spm={"geography_kind": "national"}``. + A file moved to a ``state`` loads without county inputs. The county enum + formula uses the state's first county by default. Pass + ``spm={"geography_kind": "national"}`` for national SPM thresholds. + + Pass the original frame for inputs added by ``reform=`` on the default + system. With an explicit tax-benefit system, register those inputs on that + system before calling this helper. Args: people: The flat file, as ``prepare_flat_file`` describes. @@ -788,14 +789,14 @@ def flat_file_microsimulation( class FlatFileMicrosimulation(Microsimulation): def build_from_dataset(self): - # The US constructor has registered reform variables by this point. + # The default US system registers reform variables before loading. prepared = _prepare_flat_file( self.dataset.load(), year, state, self.tax_benefit_system ) self.dataset = Dataset.from_dataframe(prepared, year) super().build_from_dataset() - # The pinned formula treats cached counties as stored inputs. - # Explicit county inputs still use the holder's normal input storage. + # The county formula reuses stored counties across years. Keep its + # results out of the holder so only supplied county inputs are reused. self.get_holder("county")._do_not_store = True microsim = FlatFileMicrosimulation( diff --git a/tests/test_us_flat_file.py b/tests/test_us_flat_file.py index 435b7a3af..ed738259c 100644 --- a/tests/test_us_flat_file.py +++ b/tests/test_us_flat_file.py @@ -11,8 +11,8 @@ pytest.importorskip("policyengine_us") from policyengine_core import periods # noqa: E402 +from policyengine_core.enums import Enum # noqa: E402 from policyengine_core.model_api import Variable # noqa: E402 -from policyengine_us import Microsimulation # noqa: E402 from policyengine_us.entities import Person # noqa: E402 from policyengine_us.variables.household.demographic.geographic.county.county_enum import ( # noqa: E402 County, @@ -420,14 +420,22 @@ def test_county_enum_outside_its_state(self, county): with pytest.raises(ValueError, match="county outside"): prepare_flat_file(people, year=YEAR) - def test_matching_state_enum_members(self): - people = in_state(survey()).assign( - state_code=StateCode.CA, state_name=StateName.CA - ) + @pytest.mark.parametrize( + "state_code, state_name", + [(StateCode.CA, StateName.CA), (StateCode.CA.index, StateName.CA.index)], + ids=["members", "indices"], + ) + def test_matching_state_enums(self, state_code, state_name): + people = in_state(survey()).assign(state_code=state_code, state_name=state_name) sim = pe.us.flat_file_microsimulation(people, year=YEAR, spm=NATIONAL_SPM) for name in ("state_code", "state_name"): assert sim.calculate(name, YEAR).tolist() == ["CA"] * 3 + def test_a_different_enum_with_a_matching_index_is_refused(self): + people = in_state(survey()).assign(state_code=County.BETHEL_CENSUS_AREA_AK) + with pytest.raises(ValueError, match=f"state_code__{YEAR}.*StateCode"): + prepare_flat_file(people, year=YEAR) + def test_a_label_that_disagrees_with_the_state(self): people = in_state(survey(), MISSISSIPPI).assign(state_code="CA") with pytest.raises(ValueError, match="state_code"): @@ -470,8 +478,7 @@ def test_each_year_keeps_its_own_county_regardless_of_calculation_order(order): county_fips__2025="50007", pre_subsidy_rent__2025=12000, ) - prepared = prepare_flat_file(people, year=2024) - sim = Microsimulation(dataset=prepared, default_input_period=2024) + sim = pe.us.flat_file_microsimulation(people, year=2024) expected = {2024: "LOS_ANGELES_COUNTY_CA", 2025: "CHITTENDEN_COUNTY_VT"} counties = {} for year in order: @@ -485,12 +492,46 @@ def test_each_year_keeps_its_own_county_regardless_of_calculation_order(order): def test_each_recorded_state_has_its_own_fallback_county(): people = one_person_households([40]).assign(state_fips=6, state_fips__2025=28) - prepared = prepare_flat_file(people, year=YEAR) - sim = Microsimulation(dataset=prepared, default_input_period=YEAR) + sim = pe.us.flat_file_microsimulation(people, year=YEAR) assert sim.calculate("county", 2024).tolist() == ["ALAMEDA_COUNTY_CA"] assert sim.calculate("county", 2025).tolist() == ["ADAMS_COUNTY_MS"] +@pytest.mark.parametrize("calculate_2026_first", [False, True]) +def test_county_and_benefit_between_recorded_geography_years(calculate_2026_first): + people = one_person_households([40]).assign( + state_fips__2024=50, + county_fips__2024="50007", + pre_subsidy_rent__2024=12000, + state_fips__2026=28, + county_fips__2026="28001", + ) + sim = pe.us.flat_file_microsimulation(people, year=2024) + if calculate_2026_first: + assert sim.calculate("county", 2026).tolist() == [County.ADAMS_COUNTY_MS.name] + assert sim.calculate("vt_reach_up_housing_allowance", "2025-01").tolist() == [450] + assert sim.calculate("county", 2025).tolist() == [County.CHITTENDEN_COUNTY_VT.name] + assert sim.get_holder("county").get_known_periods() == [] + + +def test_a_missing_county_uses_the_reformed_in_state_fallback(): + class first_county_in_state(Variable): + def formula(household, period, parameters): + return np.full(household.count, County.CHITTENDEN_COUNTY_VT.index) + + class ChittendenFallback: + @staticmethod + def apply(system): + system.update_variable(first_county_in_state) + + people = one_person_households([40]).assign( + state_fips=50, county_fips="", pre_subsidy_rent=12000 + ) + sim = pe.us.flat_file_microsimulation(people, year=YEAR, reform=ChittendenFallback) + assert sim.calculate("county", YEAR).tolist() == [County.CHITTENDEN_COUNTY_VT.name] + assert sim.calculate("vt_reach_up_housing_allowance", "2024-01").tolist() == [450] + + class TestMovingToAState: def test_a_file_may_start_with_no_state(self): prepared = prepare_flat_file(survey(), year=YEAR, state="MS") @@ -651,14 +692,53 @@ def test_the_fingerprint_distinguishes_loader_coercion_of_booleans_and_strings() ) -def test_the_fingerprint_distinguishes_overlapping_input_periods(): - people = one_person_households([40]).assign(snap__2024=120, **{"snap__2024-03": 20}) +def test_the_fingerprint_distinguishes_stored_enum_members(): + def category_reform(member_name): + categories = Enum( + "ResearchCategory", {member_name: "Selected", "OTHER": "Default"} + ) + + class research_category(Variable): + label = "Research category" + value_type = Enum + possible_values = categories + default_value = categories.OTHER + entity = Person + definition_period = periods.YEAR + + class ResearchCategory: + @staticmethod + def apply(system): + system.update_variable(research_category) + + return ResearchCategory + + people = one_person_households([40]).assign(research_category=0) + first, second = [ + pe.us.flat_file_microsimulation( + people, year=YEAR, state="MS", reform=category_reform(member_name) + ) + for member_name in ("A", "B") + ] + assert first.calculate("research_category", YEAR).tolist() == ["A"] + assert second.calculate("research_category", YEAR).tolist() == ["B"] + assert ( + first.policyengine_bundle["flat_file"]["sha256"] + != second.policyengine_bundle["flat_file"]["sha256"] + ) + + +@pytest.mark.parametrize("variable", ["snap", "ssi"]) +def test_the_fingerprint_distinguishes_overlapping_input_periods(variable): + people = one_person_households([40]).assign( + **{f"{variable}__2024": 120, f"{variable}__2024-03": 20} + ) first, second = [ pe.us.flat_file_microsimulation(frame, year=YEAR, state="MS") for frame in (people, people.iloc[:, ::-1]) ] - assert first.calculate("snap", "2024-04").tolist() == [10] - assert second.calculate("snap", "2024-04").tolist() == pytest.approx([100 / 11]) + assert first.calculate(variable, "2024-04").tolist() == [10] + assert second.calculate(variable, "2024-04").tolist() == pytest.approx([100 / 11]) assert ( first.policyengine_bundle["flat_file"]["sha256"] != second.policyengine_bundle["flat_file"]["sha256"] @@ -850,12 +930,10 @@ def test_stale_location_inputs_let_the_new_state_calculate( "md_ccs_region", "me_ccap_region", "mo_ccs_region", - "ms_ccpp_facility_location", "ne_child_care_subsidy_location", "nv_ccdp_region", "ny_ccap_county_group", "oh_ccap_county_rate_category", - "or_erdc_provider_area", "pa_ccw_region", "pa_ccw_stepparent_county_group", "pa_tanf_county_group", @@ -920,6 +998,27 @@ def test_stored_location_inputs_match_a_clean_run(name, location_input_move): assert moved.calculate(name, period).tolist() == expected +def test_state_assignment_preserves_oregon_provider_area_for_reimbursement(): + people = one_person_households([0]).assign( + state_fips=US_STATE_FIPS["OR"], + **{ + "or_erdc_provider_area__2024-06": "AREA_A", + "or_erdc_provider_type__2024-06": "STANDARD_FAMILY", + "or_erdc_monthly_care_hours__2024-06": 158, + }, + ) + sim = pe.us.flat_file_microsimulation(people, year=YEAR, state="OR", spm=NATIONAL_SPM) + assert sim.calculate("or_erdc_maximum_monthly_rate", "2024-06").tolist() == [1041] + + +def test_state_assignment_preserves_mississippi_facility_location(): + people = one_person_households([0]).assign( + state_fips=MISSISSIPPI, ms_ccpp_facility_location="METRO" + ) + sim = pe.us.flat_file_microsimulation(people, year=YEAR, state="MS", spm=NATIONAL_SPM) + assert sim.calculate("ms_ccpp_facility_location", YEAR).tolist() == ["METRO"] + + @pytest.mark.parametrize("order", [(2023, 2024), (2024, 2023)]) def test_a_moved_file_calculates_fallback_counties_independently(order): sim = pe.us.flat_file_microsimulation( @@ -993,6 +1092,20 @@ def test_the_loader_reads_role_columns(column): assert [getattr(role, "key", None) for role in roles] == ["member", None] +@pytest.mark.parametrize( + ("role_years", "expected"), + [((2024, 2025), ["member", None]), ((2025, 2024), [None, "member"])], +) +def test_the_loader_uses_the_first_dated_role_column(role_years, expected): + roles_by_year = {2024: ["member", "invalid"], 2025: ["invalid", "member"]} + people = one_person_households([30, 40]).assign( + **{f"person_tax_unit_role__{year}": roles_by_year[year] for year in role_years} + ) + sim = pe.us.flat_file_microsimulation(people, year=YEAR, state="MS") + roles = sim.populations["tax_unit"].members_role + assert [getattr(role, "key", None) for role in roles] == expected + + def test_the_loader_reads_reform_registered_inputs(): class research_payment(Variable): label = "Research payment" From 97a6fee049d1046373dc593edef6f25a507ed2e5 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 2 Dec 2026 16:40:08 -0500 Subject: [PATCH 12/14] Keep New York and Ohio provider-county inputs on state assignment The model uses household county as a proxy for the child care provider's location in four rate inputs: Oregon's provider area and the Mississippi, New York and Ohio county categories. State assignment now keeps all four when a file supplies them, and a parametrized test checks Mississippi, New York and Ohio against a value the clean run would not infer. The prepare_flat_file docstring and the guide now say that loading the prepared frame directly can carry an inferred county across years. Two new test calls are wrapped to the 88-character line limit. Co-Authored-By: Claude Opus 5.5 --- docs/simulated-instruments.md | 4 +-- .../tax_benefit_models/us/flat_file.py | 8 +++-- tests/test_us_flat_file.py | 34 ++++++++++++++----- 3 files changed, 33 insertions(+), 13 deletions(-) diff --git a/docs/simulated-instruments.md b/docs/simulated-instruments.md index 9b32a58f9..e3e5f7db5 100644 --- a/docs/simulated-instruments.md +++ b/docs/simulated-instruments.md @@ -74,7 +74,7 @@ With `state` left out, it also refuses a county, tract, block, congressional dis The helper warns about unused columns and well-formed county FIPS codes absent from the model's lookup. The county formula uses the first county in the state when it resolves an unmatched FIPS. A stored county can take precedence. -When the file records its own geography, preparation validates state and county inputs for every covered year. The simulation uses the active county formula to infer counties and keeps inferred values out of county storage. Supplied county inputs retain the loader's precedence. +When the file records its own geography, preparation validates state and county inputs for every covered year. The simulation uses the active county formula to infer counties and keeps inferred values out of county storage. Supplied county inputs retain the loader's precedence. `prepare_flat_file` writes no county inputs for years without a supplied county, so a simulation that loads its frame directly can carry a county it infers for one year into another. Pass the original frame to `pe.us.flat_file_microsimulation` for results. ## Reading results back @@ -88,7 +88,7 @@ people["state_tax"] = sim.calculate("state_income_tax", 2024, map_to="person").v ## What a state change clears -Passing `state` sets `state_fips` in every year your file holds. It clears county, ZIP code, congressional district, tract and other local geography for every household, including those already in the assigned state. It also clears location-based inputs such as `is_rural`, `in_la`, ACA rating areas, SNAP utility regions, household-based child care regions and HUD rent lookups. It preserves supplied provider locations such as Oregon's `or_erdc_provider_area` and Mississippi's `ms_ccpp_facility_location`. A stored outcome such as eligibility or tax can override its formula. +Passing `state` sets `state_fips` in every year your file holds. It clears county, ZIP code, congressional district, tract and other local geography for every household, including those already in the assigned state. It also clears location-based inputs such as `is_rural`, `in_la`, ACA rating areas, SNAP utility regions, household-based child care regions and HUD rent lookups. It keeps the four inputs the model treats as a child care provider's location: Oregon's `or_erdc_provider_area`, Mississippi's `ms_ccpp_facility_location`, New York's `ny_ccap_county_group` and Ohio's `oh_ccap_county_rate_category`. A stored outcome such as eligibility or tax can override its formula. Rules that read the county enum use the state's first county alphabetically when a county is missing. In Minnesota that is Aitkin County. The bundle defaults to county-based SPM thresholds. The recipe passes `{"geography_kind": "national"}` so every state uses the same national SPM thresholds for the same household inputs. To keep real counties, leave `state` out and run each household where the file records it. diff --git a/src/policyengine/tax_benefit_models/us/flat_file.py b/src/policyengine/tax_benefit_models/us/flat_file.py index dfb513a5c..950fff114 100644 --- a/src/policyengine/tax_benefit_models/us/flat_file.py +++ b/src/policyengine/tax_benefit_models/us/flat_file.py @@ -103,8 +103,6 @@ "mo_ccs_region", "ne_child_care_subsidy_location", "nv_ccdp_region", - "ny_ccap_county_group", - "oh_ccap_county_rate_category", "pa_ccw_region", "pa_ccw_stepparent_county_group", "pa_tanf_county_group", @@ -698,7 +696,11 @@ def prepare_flat_file( Returns: A new frame, leaving ``people`` as it was. Results come back with - groups in the order the file first names them. + groups in the order the file first names them. The frame holds no + county inputs for years without a supplied county, so a simulation + that loads it directly can carry a county it infers for one year into + another. Pass the original frame to ``flat_file_microsimulation`` for + results. """ from policyengine_us.system import system diff --git a/tests/test_us_flat_file.py b/tests/test_us_flat_file.py index ed738259c..8bff40c84 100644 --- a/tests/test_us_flat_file.py +++ b/tests/test_us_flat_file.py @@ -932,8 +932,6 @@ def test_stale_location_inputs_let_the_new_state_calculate( "mo_ccs_region", "ne_child_care_subsidy_location", "nv_ccdp_region", - "ny_ccap_county_group", - "oh_ccap_county_rate_category", "pa_ccw_region", "pa_ccw_stepparent_county_group", "pa_tanf_county_group", @@ -1007,16 +1005,36 @@ def test_state_assignment_preserves_oregon_provider_area_for_reimbursement(): "or_erdc_monthly_care_hours__2024-06": 158, }, ) - sim = pe.us.flat_file_microsimulation(people, year=YEAR, state="OR", spm=NATIONAL_SPM) + sim = pe.us.flat_file_microsimulation( + people, year=YEAR, state="OR", spm=NATIONAL_SPM + ) assert sim.calculate("or_erdc_maximum_monthly_rate", "2024-06").tolist() == [1041] -def test_state_assignment_preserves_mississippi_facility_location(): - people = one_person_households([0]).assign( - state_fips=MISSISSIPPI, ms_ccpp_facility_location="METRO" +@pytest.mark.parametrize( + ("state", "name"), + [ + ("MS", "ms_ccpp_facility_location"), + ("NY", "ny_ccap_county_group"), + ("OH", "oh_ccap_county_rate_category"), + ], +) +def test_state_assignment_preserves_supplied_provider_county_proxies(state, name): + # The model uses household county as a proxy for the provider's location + # for these rate inputs, so a supplied provider location must survive. + people = one_person_households([0]).assign(state_fips=US_STATE_FIPS[state]) + clean = pe.us.flat_file_microsimulation( + people, year=YEAR, state=state, spm=NATIONAL_SPM + ) + variable = clean.tax_benefit_system.get_variable(name, check_existence=True) + inferred = clean.calculate(name, YEAR).tolist()[0] + supplied = next( + member.name for member in variable.possible_values if member.name != inferred + ) + sim = pe.us.flat_file_microsimulation( + people.assign(**{name: supplied}), year=YEAR, state=state, spm=NATIONAL_SPM ) - sim = pe.us.flat_file_microsimulation(people, year=YEAR, state="MS", spm=NATIONAL_SPM) - assert sim.calculate("ms_ccpp_facility_location", YEAR).tolist() == ["METRO"] + assert sim.calculate(name, YEAR).tolist() == [supplied] @pytest.mark.parametrize("order", [(2023, 2024), (2024, 2023)]) From 72af061acb546e54ae31d9bf9c0a4500206b98bf Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 2 Dec 2026 22:54:33 -0500 Subject: [PATCH 13/14] Keep supplied geography through loading and state assignment - Set the county holder's no-store flag before Core loads inputs, and drop values that load-time input handlers computed, so a handler that runs before or after geography never caches a stale county. - Stop state assignment from clearing 23 child-care provider rate selectors; a supplied rate area or county group now survives and sets the rate. - Accept a state_code, state_name or county member from another US system when its enum class has the same qualified name and source file, instead of refusing it. - Describe county inference during loading and the provider selectors that state assignment keeps in docs/simulated-instruments.md. Co-Authored-By: Claude Opus 5.5 --- docs/simulated-instruments.md | 4 +- .../tax_benefit_models/us/flat_file.py | 92 ++-- tests/test_us_flat_file.py | 445 +++++++++++++++++- 3 files changed, 477 insertions(+), 64 deletions(-) diff --git a/docs/simulated-instruments.md b/docs/simulated-instruments.md index e3e5f7db5..cab3c0da9 100644 --- a/docs/simulated-instruments.md +++ b/docs/simulated-instruments.md @@ -74,7 +74,7 @@ With `state` left out, it also refuses a county, tract, block, congressional dis The helper warns about unused columns and well-formed county FIPS codes absent from the model's lookup. The county formula uses the first county in the state when it resolves an unmatched FIPS. A stored county can take precedence. -When the file records its own geography, preparation validates state and county inputs for every covered year. The simulation uses the active county formula to infer counties and keeps inferred values out of county storage. Supplied county inputs retain the loader's precedence. `prepare_flat_file` writes no county inputs for years without a supplied county, so a simulation that loads its frame directly can carry a county it infers for one year into another. Pass the original frame to `pe.us.flat_file_microsimulation` for results. +When the file records its own geography, preparation validates state and county inputs for every covered year. When no supplied county takes precedence, the active model's county formula infers the county. The simulation keeps inferred values out of county storage, including during input loading. A simulation that loads the prepared frame directly can carry a county it infers for one year into another. Pass the original frame to `pe.us.flat_file_microsimulation` for results. ## Reading results back @@ -88,7 +88,7 @@ people["state_tax"] = sim.calculate("state_income_tax", 2024, map_to="person").v ## What a state change clears -Passing `state` sets `state_fips` in every year your file holds. It clears county, ZIP code, congressional district, tract and other local geography for every household, including those already in the assigned state. It also clears location-based inputs such as `is_rural`, `in_la`, ACA rating areas, SNAP utility regions, household-based child care regions and HUD rent lookups. It keeps the four inputs the model treats as a child care provider's location: Oregon's `or_erdc_provider_area`, Mississippi's `ms_ccpp_facility_location`, New York's `ny_ccap_county_group` and Ohio's `oh_ccap_county_rate_category`. A stored outcome such as eligibility or tax can override its formula. +Passing `state` sets `state_fips` in every year your file holds. It clears county, ZIP code, congressional district, tract and other local geography for every household, including those already in the assigned state. It also clears location-based inputs such as `is_rural`, `in_la`, ACA rating areas, SNAP utility regions, child-care eligibility areas based on household residence and HUD rent lookups. State assignment preserves supplied child-care provider rate areas and county groups. A stored outcome such as eligibility or tax can override its formula. Rules that read the county enum use the state's first county alphabetically when a county is missing. In Minnesota that is Aitkin County. The bundle defaults to county-based SPM thresholds. The recipe passes `{"geography_kind": "national"}` so every state uses the same national SPM thresholds for the same household inputs. To keep real counties, leave `state` out and run each household where the file records it. diff --git a/src/policyengine/tax_benefit_models/us/flat_file.py b/src/policyengine/tax_benefit_models/us/flat_file.py index 950fff114..e23dbb3b1 100644 --- a/src/policyengine/tax_benefit_models/us/flat_file.py +++ b/src/policyengine/tax_benefit_models/us/flat_file.py @@ -13,8 +13,10 @@ import hashlib import logging +import sys from enum import Enum from numbers import Number +from pathlib import Path from typing import Optional, Union import numpy as np @@ -41,14 +43,11 @@ } ) STATE_LABELS = ("state_code", "state_code_str", "state_name") -# Household geography, including local flags, programme regions, rating areas -# and location-based lookups. Child-care provider and facility locations can -# differ from the household's recorded location. +# Household geography and residence-based lookups. Child-care provider rate +# areas can describe a different location, even when their formulas use +# household county as the default. LOCAL_GEOGRAPHY = ( - "ak_ccap_rate_region", - "al_ccsp_region", "ami", - "ar_sra_zone", "average_home_energy_use_in_state", "block_geoid", "ca_tanf_region1", @@ -57,17 +56,13 @@ "county", "county_fips", "county_str", - "ct_c4k_region", "ct_tfa_region", - "ga_caps_zone", "hud_extremely_low_income_limit", "hud_fair_market_rent", "hud_low_income_limit", "hud_utility_allowance", "hud_very_low_income_limit", - "id_iccp_county_cluster", "il_aabd_area", - "il_ccap_county_group", "il_dhs_csfp_county_eligible", "il_tanf_county_group", "in_ala", @@ -90,28 +85,17 @@ "is_in_snap_abawd_waived_area", "is_on_tribal_land", "is_rural", - "ks_ccap_rate_group", "ks_dcf_csfp_county_eligible", "ks_tanf_county_group", - "ky_ccap_rate_region", "lcbp_age_0", - "ma_ccfa_region", "ma_dese_csfp_county_eligible", - "md_ccs_region", - "me_ccap_region", "medicaid_rating_area", - "mo_ccs_region", - "ne_child_care_subsidy_location", - "nv_ccdp_region", - "pa_ccw_region", "pa_ccw_stepparent_county_group", "pa_tanf_county_group", "pha_payment_standard", "place_fips", "puma", "safmr_used_for_hcv", - "sc_ccap_geography", - "sd_cca_region", "slcsp_age_0", "slcsp_rating_area", "slcsp_rating_area_default", @@ -123,15 +107,10 @@ "snap_utility_region_str", "spm_unit_geographic_adjustment", "three_digit_zip_code", - "tn_ccap_county_tier", "tract_geoid", - "tx_ccs_workforce_board_region", "va_ccsp_locality_group", - "va_ccsp_ready_region", "va_medicaid_lifc_locality_group", "vtd", - "wa_wccc_center_region", - "wa_wccc_region", "zcta", "zip_code", "zip_code_payment_standard", @@ -458,6 +437,14 @@ def _warn_unknown_county_fips(frame: pd.DataFrame) -> None: ) +def _enum_origin(enum: type[Enum]) -> Optional[tuple[str, Path]]: + module = sys.modules.get(enum.__module__) + source = getattr(module, "__file__", None) + if source is None: + return None + return enum.__qualname__, Path(source).resolve() + + def _with_enum_names(frame: pd.DataFrame, variables) -> pd.DataFrame: """Use the loader's enum encoding before comparing places by name.""" from policyengine_us.variables.household.demographic.geographic.county.county_enum import ( @@ -470,24 +457,33 @@ def _with_enum_names(frame: pd.DataFrame, variables) -> pd.DataFrame: StateName, ) - # Core loads variable files under distinct module names. Accept the model's - # public enums and the active registry's enums, matching members by name. + # Core loads the same variable file under a distinct module name per system. + # Match those enum classes by source and qualified name. places = {"state_code": StateCode, "state_name": StateName, "county": County} names = {} for name, model_enum in places.items(): + columns = _columns_of(frame, name) + if not columns: + continue enum = variables[name].possible_values + allowed_enums = {enum, model_enum} + allowed_origins = {_enum_origin(cls) for cls in allowed_enums} - {None} members = np.array([member.name for member in enum]) - for column in _columns_of(frame, name): + for column in columns: values = np.asarray(frame[column].values) if values.dtype.kind == "O": values = values.copy() for index, value in enumerate(values): - if isinstance(value, Enum): - if not isinstance(value, (enum, model_enum)): + if not isinstance(value, Enum): + continue + cls = type(value) + if cls not in allowed_enums: + if _enum_origin(cls) not in allowed_origins: raise ValueError( f"{column} holds a member outside {enum.__name__}." ) - values[index] = value.name + allowed_enums.add(cls) + values[index] = value.name if ( values.dtype.kind in "iu" and ((values < 0) | (values >= len(members))).any() @@ -691,8 +687,9 @@ def prepare_flat_file( year's value. state: A postal code or FIPS code to run every household in. It applies to every year the file holds and clears stored state labels and - geography such as county, ZIP and tract. Leave it unset to keep the - file's own ``state_fips``, which then has to agree with those columns. + household geography such as county, ZIP and tract. Supplied child-care + provider rate areas are preserved. Leave it unset to keep the file's + own ``state_fips``, which then has to agree with those columns. Returns: A new frame, leaving ``people`` as it was. Results come back with @@ -790,16 +787,35 @@ def flat_file_microsimulation( raise ValueError("flat_file_microsimulation builds its dataset from `people`.") class FlatFileMicrosimulation(Microsimulation): + def build_from_populations(self, populations): + super().build_from_populations(populations) + # The county formula reuses stored counties across years. Set this + # before Core loads inputs, since an input handler can run formulas. + self.get_holder("county")._do_not_store = True + def build_from_dataset(self): # The default US system registers reform variables before loading. prepared = _prepare_flat_file( self.dataset.load(), year, state, self.tax_benefit_system ) self.dataset = Dataset.from_dataframe(prepared, year) - super().build_from_dataset() - # The county formula reuses stored counties across years. Keep its - # results out of the holder so only supplied county inputs are reused. - self.get_holder("county")._do_not_store = True + self._loading_flat_file = True + try: + super().build_from_dataset() + finally: + self._loading_flat_file = False + + def set_input(self, variable_name, period, value): + calculations_started = self._calculations_started + result = super().set_input(variable_name, period, value) + if ( + getattr(self, "_loading_flat_file", False) + and self._calculations_started != calculations_started + ): + # A handler can calculate with only part of the file loaded. + # Clear those results before a later input handler can reuse them. + self.drop_computed_arrays() + return result microsim = FlatFileMicrosimulation( dataset=Dataset.from_dataframe(people, year), diff --git a/tests/test_us_flat_file.py b/tests/test_us_flat_file.py index 8bff40c84..bf66d7cc1 100644 --- a/tests/test_us_flat_file.py +++ b/tests/test_us_flat_file.py @@ -12,8 +12,10 @@ from policyengine_core import periods # noqa: E402 from policyengine_core.enums import Enum # noqa: E402 +from policyengine_core.holders import set_input_dispatch_by_period # noqa: E402 from policyengine_core.model_api import Variable # noqa: E402 -from policyengine_us.entities import Person # noqa: E402 +from policyengine_us.entities import Household, Person # noqa: E402 +from policyengine_us.system import CountryTaxBenefitSystem # noqa: E402 from policyengine_us.variables.household.demographic.geographic.county.county_enum import ( # noqa: E402 County, ) @@ -431,11 +433,27 @@ def test_matching_state_enums(self, state_code, state_name): for name in ("state_code", "state_name"): assert sim.calculate(name, YEAR).tolist() == ["CA"] * 3 + def test_state_enum_members_from_another_system(self): + other_system = CountryTaxBenefitSystem() + people = in_state(survey()).assign( + state_code=other_system.variables["state_code"].possible_values.CA, + state_name=other_system.variables["state_name"].possible_values.CA, + ) + sim = pe.us.flat_file_microsimulation(people, year=YEAR, spm=NATIONAL_SPM) + for name in ("state_code", "state_name"): + assert sim.calculate(name, YEAR).tolist() == ["CA"] * 3 + def test_a_different_enum_with_a_matching_index_is_refused(self): people = in_state(survey()).assign(state_code=County.BETHEL_CENSUS_AREA_AK) with pytest.raises(ValueError, match=f"state_code__{YEAR}.*StateCode"): prepare_flat_file(people, year=YEAR) + def test_a_matching_enum_name_from_another_source_is_refused(self): + other_enum = Enum("StateCode", {"CA": "CA"}, module=__name__) + people = in_state(survey()).assign(state_code=other_enum.CA) + with pytest.raises(ValueError, match=f"state_code__{YEAR}.*StateCode"): + prepare_flat_file(people, year=YEAR) + def test_a_label_that_disagrees_with_the_state(self): people = in_state(survey(), MISSISSIPPI).assign(state_code="CA") with pytest.raises(ValueError, match="state_code"): @@ -514,6 +532,62 @@ def test_county_and_benefit_between_recorded_geography_years(calculate_2026_firs assert sim.get_holder("county").get_known_periods() == [] +@pytest.mark.parametrize("handler_first", [False, True], ids=["after", "before"]) +def test_county_calculated_by_an_input_handler_is_not_reused(handler_first): + seen = [] + + class research_payment(Variable): + label = "Research payment" + value_type = float + entity = Person + definition_period = periods.MONTH + + def set_input(holder, period, array): + county = holder.simulation.household("county", period.this_year) + seen.extend(county.decode_to_str().tolist()) + set_input_dispatch_by_period(holder, period, array) + + class research_county(Variable): + label = "Research county" + value_type = str + entity = Household + definition_period = periods.MONTH + + def set_input(holder, period, _array): + county = holder.simulation.household("county", period.this_year) + set_input_dispatch_by_period(holder, period, county.decode_to_str()) + + system = CountryTaxBenefitSystem() + system.add_variables(research_payment, research_county) + geography = { + "state_fips__2024": 50, + "county_fips__2024": "50007", + "pre_subsidy_rent__2024": 12000, + "state_fips__2026": 28, + "county_fips__2026": "28001", + } + payment = {"research_payment__2026": 1250} + inputs = {**payment, **geography} if handler_first else {**geography, **payment} + people = one_person_households([40]).assign( + **inputs, research_county__2026="record" + ) + sim = pe.us.flat_file_microsimulation(people, year=2024, tax_benefit_system=system) + + expected = County.ALAMEDA_COUNTY_CA if handler_first else County.ADAMS_COUNTY_MS + assert seen == [expected.name] + assert sim.calculate("research_payment", "2026-01").tolist() == [1250] + assert sim.calculate("research_county", "2026-01").tolist() == [ + County.ADAMS_COUNTY_MS.name + ] + assert sim.calculate("vt_reach_up_housing_allowance", "2025-01").tolist() == [450] + assert sim.calculate("county", 2025).tolist() == [County.CHITTENDEN_COUNTY_VT.name] + # Internal population calls use Core's same-period fast path. + assert sim.household("county", 2026).decode_to_str().tolist() == [ + County.ADAMS_COUNTY_MS.name + ] + assert sim.get_holder("county").get_known_periods() == [] + + def test_a_missing_county_uses_the_reformed_in_state_fallback(): class first_county_in_state(Variable): def formula(household, period, parameters): @@ -886,22 +960,15 @@ def test_stale_location_inputs_let_the_new_state_calculate( LOCATION_INPUTS = ( - "ak_ccap_rate_region", - "al_ccsp_region", "ami", - "ar_sra_zone", "ca_tanf_region1", - "ct_c4k_region", "ct_tfa_region", - "ga_caps_zone", "hud_extremely_low_income_limit", "hud_fair_market_rent", "hud_low_income_limit", "hud_utility_allowance", "hud_very_low_income_limit", - "id_iccp_county_cluster", "il_aabd_area", - "il_ccap_county_group", "il_dhs_csfp_county_eligible", "il_tanf_county_group", "in_ala", @@ -920,24 +987,13 @@ def test_stale_location_inputs_let_the_new_state_calculate( "in_wilmington", "in_yonkers", "is_in_snap_abawd_waived_area", - "ks_ccap_rate_group", "ks_dcf_csfp_county_eligible", "ks_tanf_county_group", - "ky_ccap_rate_region", "lcbp_age_0", - "ma_ccfa_region", "ma_dese_csfp_county_eligible", - "md_ccs_region", - "me_ccap_region", - "mo_ccs_region", - "ne_child_care_subsidy_location", - "nv_ccdp_region", - "pa_ccw_region", "pa_ccw_stepparent_county_group", "pa_tanf_county_group", "pha_payment_standard", - "sc_ccap_geography", - "sd_cca_region", "slcsp_age_0", "slcsp_rating_area", "slcsp_rating_area_default", @@ -947,13 +1003,8 @@ def test_stale_location_inputs_let_the_new_state_calculate( "snap_utility_region", "snap_utility_region_str", "taxsim_state", - "tn_ccap_county_tier", - "tx_ccs_workforce_board_region", "va_ccsp_locality_group", - "va_ccsp_ready_region", "va_medicaid_lifc_locality_group", - "wa_wccc_center_region", - "wa_wccc_region", "zip_code_payment_standard", ) @@ -1011,6 +1062,352 @@ def test_state_assignment_preserves_oregon_provider_area_for_reimbursement(): assert sim.calculate("or_erdc_maximum_monthly_rate", "2024-06").tolist() == [1041] +@pytest.mark.parametrize( + "state, month, area, supplied, rate, expected, inputs", + [ + pytest.param( + "AK", + "2022-01", + "ak_ccap_rate_region__2022-01", + "ANCHORAGE_MUNICIPALITY_AK", + "ak_ccap_max_provider_rate_per_child", + 1019, + { + "age": 4, + "ak_ccap_child_eligible__2022-01": True, + "ak_ccap_provider_type__2022-01": "LICENSED_CENTER", + "ak_ccap_care_schedule__2022-01": "FT_MONTH", + }, + id="alaska", + ), + pytest.param( + "AL", + "2024-01", + "al_ccsp_region", + "BIRMINGHAM", + "al_ccsp_maximum_weekly_rate", + 191, + { + "age": 4, + "al_ccsp_eligible_child__2024-01": True, + "childcare_hours_per_week": 35, + "al_ccsp_provider_type__2024-01": "CENTER", + "al_ccsp_quality_tier__2024-01": "STAR_3", + }, + id="alabama", + ), + pytest.param( + "AR", + "2026-01", + "ar_sra_zone__2026-01", + "BENTON_WASHINGTON", + "ar_sra_daily_base_rate", + 38, + {"is_ar_sra_child_eligible__2026-01": True, "childcare_hours_per_day": 8}, + id="arkansas", + ), + pytest.param( + "CT", + "2025-01", + "ct_c4k_region__2025-01", + "EASTERN", + "ct_c4k_payment_rate", + 284, + { + "ct_c4k_eligible_child__2025-01": True, + "ct_c4k_provider_type__2025-01": "CENTER", + "ct_c4k_care_level__2025-01": "FULL_TIME", + "ct_c4k_age_group__2025-01": "INFANT_TODDLER", + }, + id="connecticut", + ), + pytest.param( + "GA", + "2026-04", + "ga_caps_zone__2026-04", + "ZONE_1", + "ga_caps_maximum_weekly_benefit", + 260, + { + "ga_caps_eligible_child__2026-04": True, + "ga_caps_provider_type__2026-04": "CENTER", + "ga_caps_care_type__2026-04": "FULL_TIME", + }, + id="georgia", + ), + pytest.param( + "ID", + "2026-01", + "id_iccp_county_cluster", + "CLUSTER_2", + "id_iccp_maximum_monthly_benefit", + 593, + { + "id_iccp_eligible_child__2026-01": True, + "childcare_hours_per_week": 12, + "id_iccp_provider_type__2026-01": "FAMILY", + "id_iccp_time_category__2026-01": "PART_TIME", + }, + id="idaho", + ), + pytest.param( + "IL", + "2026-01", + "il_ccap_county_group__2026-01", + "GROUP_1A", + "il_ccap_max_daily_rate", + 34, + { + "il_ccap_eligible_child__2026-01": True, + "il_ccap_provider_type__2026-01": "LICENSED_CENTER", + "il_ccap_care_duration__2026-01": "PART_DAY", + }, + id="illinois", + ), + pytest.param( + "KS", + "2025-01", + "ks_ccap_rate_group", + "GROUP_1", + "ks_ccap_hourly_rate", + 7.33, + { + "ks_ccap_eligible_child__2025-01": True, + "ks_ccap_provider_type__2025-01": "CENTER", + }, + id="kansas", + ), + pytest.param( + "KY", + "2025-01", + "ky_ccap_rate_region__2025-01", + "REGION_4", + "ky_ccap_daily_rate", + 47, + { + "ky_ccap_eligible_child__2025-01": True, + "ky_ccap_provider_type__2025-01": "LICENSED_TYPE_I", + "childcare_hours_per_day": 8, + }, + id="kentucky", + ), + pytest.param( + "MA", + "2026-01", + "ma_ccfa_region__2026-01", + "METRO_AND_BOSTON_METRO", + "ma_ccfa_family_child_care_reimbursement", + 88.98, + {"age": 1}, + id="massachusetts", + ), + pytest.param( + "MD", + "2026-01", + "md_ccs_region__2026-01", + "REGION_X", + "md_ccs_payment_rate", + 381, + { + "age": 5, + "md_ccs_eligible_child__2026-01": True, + "md_ccs_provider_type__2026-01": "LICENSED_CENTER", + "childcare_hours_per_day": 8, + }, + id="maryland", + ), + pytest.param( + "ME", + "2024-01", + "me_ccap_region__2024-01", + "CUMBERLAND", + "me_ccap_market_rate", + 303, + { + "me_ccap_eligible_child__2024-01": True, + "me_ccap_time_category__2024-01": "FULL_TIME", + "me_ccap_provider_type__2024-01": "LICENSED_CENTER", + }, + id="maine", + ), + pytest.param( + "MO", + "2025-01", + "mo_ccs_region", + "DENSE_URBAN", + "mo_ccs_maximum_daily_benefit", + 96, + { + "age": 1, + "mo_ccs_eligible_child__2025-01": True, + "mo_ccs_provider_type__2025-01": "LICENSED_CENTER", + "childcare_hours_per_day": 8, + }, + id="missouri", + ), + pytest.param( + "NE", + "2026-01", + "ne_child_care_subsidy_location", + "URBAN", + "ne_child_care_subsidy_maximum_provider_rate", + 132.70, + { + "ne_child_care_subsidy_provider_eligible__2026-01": True, + "ne_child_care_subsidy_provider_type__2026-01": "CENTER", + "ne_child_care_subsidy_quality_tier__2026-01": "BASE", + "ne_child_care_subsidy_rate_unit__2026-01": "FULL_DAY", + "childcare_attending_days_per_month": 2, + }, + id="nebraska", + ), + pytest.param( + "NV", + "2025-01", + "nv_ccdp_region__2025-01", + "MOST_POPULOUS", + "nv_ccdp_provider_rate", + 62.50, + { + "nv_ccdp_eligible_child__2025-01": True, + "nv_ccdp_provider_type__2025-01": "CENTER", + }, + id="nevada", + ), + pytest.param( + "PA", + "2025-01", + "pa_ccw_region", + 1, + "pa_ccw_market_rate", + 51.13, + { + "pa_ccw_eligible_child": True, + "pa_ccw_provider_type__2025-01": "CENTER", + "childcare_hours_per_day": 8, + }, + id="pennsylvania", + ), + pytest.param( + "SC", + "2025-01", + "sc_ccap_geography", + "URBAN", + "sc_ccap_maximum_weekly_benefit", + 140, + { + "sc_ccap_eligible_child__2025-01": True, + "is_enrolled_in_head_start": True, + "childcare_hours_per_week": 30, + "sc_ccap_provider_type__2025-01": "CENTER", + "sc_ccap_quality_level__2025-01": "C", + }, + id="south-carolina", + ), + pytest.param( + "SD", + "2027-01", + "sd_cca_region__2027-01", + "URBAN", + "sd_cca_weekly_rate", + 180, + { + "sd_cca_eligible_child__2027-01": True, + "sd_cca_provider_type__2027-01": "FAMILY_DAY_CARE", + "childcare_hours_per_week": 40, + }, + id="south-dakota", + ), + pytest.param( + "TN", + "2026-01", + "tn_ccap_county_tier__2026-01", + "LOWER_TIER", + "tn_ccap_max_weekly_benefit", + 148, + { + "age": 4, + "tn_ccap_eligible_child__2026-01": True, + "childcare_hours_per_week": 35, + }, + id="tennessee", + ), + pytest.param( + "TX", + "2025-01", + "tx_ccs_workforce_board_region", + "DALLAS_COUNTY", + "tx_ccs_payment_rate", + 472, + { + "tx_ccs_eligible_child__2025-01": True, + "tx_ccs_provider_type__2025-01": "LCCC", + "tx_ccs_provider_rating__2025-01": "REG", + "tx_ccs_care_schedule__2025-01": "FULL_TIME", + "childcare_attending_days_per_month": 10, + }, + id="texas", + ), + pytest.param( + "VA", + "2024-01", + "va_ccsp_ready_region", + "CAPITAL_AREA", + "va_ccsp_daily_mrr", + 94, + {"va_ccsp_provider_type": "CENTER", "va_ccsp_is_full_day": True}, + id="virginia", + ), + pytest.param( + "WA", + "2025-01", + "wa_wccc_center_region__2025-01", + "REGION_4", + "wa_wccc_max_monthly_reimbursement", + 2336.57, + { + "wa_wccc_eligible_child__2025-01": True, + "wa_wccc_provider_type__2025-01": "CENTER", + "wa_wccc_center_age_group__2025-01": "TODDLER", + }, + id="washington-center", + ), + pytest.param( + "WA", + "2025-01", + "wa_wccc_region__2025-01", + "REGION_3", + "wa_wccc_max_monthly_reimbursement", + 1430, + { + "wa_wccc_eligible_child__2025-01": True, + "wa_wccc_provider_type__2025-01": "FAMILY_HOME", + "wa_wccc_family_home_age_group__2025-01": "ENHANCED_TODDLER", + }, + id="washington-family-home", + ), + ], +) +def test_state_assignment_preserves_provider_areas_for_reimbursement( + state, month, area, supplied, rate, expected, inputs +): + # Eligibility and care inputs isolate the pinned model's rate lookup. + year = int(month[:4]) + people = in_state(one_person_households([0]), US_STATE_FIPS[state]).assign(**inputs) + default = pe.us.flat_file_microsimulation( + people, year=year, state=state, spm=NATIONAL_SPM + ) + with_provider_area = pe.us.flat_file_microsimulation( + people.assign(**{area: supplied}), year=year, state=state, spm=NATIONAL_SPM + ) + area_name, _, area_period = area.partition("__") + assert default.calculate(area_name, area_period or year).tolist() != [supplied] + assert default.calculate(rate, month).tolist() != pytest.approx([expected]) + assert with_provider_area.calculate(rate, month).tolist() == pytest.approx( + [expected] + ) + + @pytest.mark.parametrize( ("state", "name"), [ From ee4052d1e1ab2d79018a48782a082c6119ef10ff Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 2 Dec 2026 23:30:49 -0500 Subject: [PATCH 14/14] Clear load-time branches and load geography before other inputs A flat-file load now clears simulation branches, the fast cache and the behavioural-response cache after each load-time input, and restores a registered baseline when loading ends. Branches are snapshots, so a handler's calculation on one could otherwise outlive the partial input set it saw. When a handler starts a calculation, the loader also drops computed arrays, snapshots the SPM forecast provider and re-records county input types. Preparation puts state FIPS and the county fields first, and variables with custom period-conversion handlers load after ordinary inputs, so a handler sees the file's geography rather than California's default. New tests cover the stale-branch case and four state and county cases; docs/simulated-instruments.md describes the load order. Co-Authored-By: GPT-6.2 Sol Co-Authored-By: Claude Opus 5.5 --- docs/simulated-instruments.md | 2 + .../tax_benefit_models/us/flat_file.py | 108 +++++++- tests/test_us_flat_file.py | 250 ++++++++++++++++-- 3 files changed, 331 insertions(+), 29 deletions(-) diff --git a/docs/simulated-instruments.md b/docs/simulated-instruments.md index cab3c0da9..8d2e5986a 100644 --- a/docs/simulated-instruments.md +++ b/docs/simulated-instruments.md @@ -76,6 +76,8 @@ The helper warns about unused columns and well-formed county FIPS codes absent f When the file records its own geography, preparation validates state and county inputs for every covered year. When no supplied county takes precedence, the active model's county formula infers the county. The simulation keeps inferred values out of county storage, including during input loading. A simulation that loads the prepared frame directly can carry a county it infers for one year into another. Pass the original frame to `pe.us.flat_file_microsimulation` for results. +Preparation puts `state_fips`, `county_fips`, `county` and `county_str` first. The simulation then loads ordinary inputs before variables whose custom period-conversion handlers will run. These variables keep their file order, so a handler that reads another handler's output needs the producing column first. The dataset year is the default calculation period during loading. The simulation discards provisional calculation state between inputs and retains values that handlers explicitly store as inputs. Compute results that depend on the completed US simulation, such as behavioral responses, after construction. + ## Reading results back Each person-level result follows the rows of your file. Group-level results come back in the order your file first names each group, so pass `map_to="person"` for one value per row: diff --git a/src/policyengine/tax_benefit_models/us/flat_file.py b/src/policyengine/tax_benefit_models/us/flat_file.py index e23dbb3b1..8a38bcb1f 100644 --- a/src/policyengine/tax_benefit_models/us/flat_file.py +++ b/src/policyengine/tax_benefit_models/us/flat_file.py @@ -23,6 +23,10 @@ import pandas as pd from policyengine_core import periods from policyengine_core.enums import EnumArray +from policyengine_core.holders import ( + set_input_dispatch_by_period, + set_input_divide_by_period, +) from policyengine.countries.us.data import US_STATE_FIPS from policyengine.tax_benefit_models.common.model_version import ( @@ -746,7 +750,47 @@ def _prepare_flat_file(people: pd.DataFrame, year: int, state, system) -> pd.Dat _require_coherent_geography(frame, year, years, default_state) _warn_unknown_county_fips(frame) _require_group_values_agree(frame, year, variables) - return frame + # Core loads in frame order. Input handlers can read these fields as they + # run, so load the prepared geography before the other model inputs. + geography = [ + column + for name in ("state_fips", "county_fips", *COUNTY_NAMES) + for column in _columns_of(frame, name) + ] + geography_columns = set(geography) + columns = geography + [ + column for column in frame if column not in geography_columns + ] + return frame.loc[:, columns] + + +def _has_custom_input_handler(variable) -> bool: + handler = getattr(variable, "set_input", None) + return bool(handler) and handler not in ( + set_input_dispatch_by_period, + set_input_divide_by_period, + ) + + +def _with_custom_inputs_last(frame: pd.DataFrame, variables, year: int) -> pd.DataFrame: + """Load ordinary inputs before variables whose custom handler will run.""" + custom_variables = set() + for column in frame: + name, _, suffix = column.partition("__") + variable = variables.get(name) + if ( + _has_custom_input_handler(variable) + and periods.period(suffix or year).unit != variable.definition_period + ): + custom_variables.add(name) + if not custom_variables: + return frame + # Keep all periods of a variable in order so overlapping inputs are + # allocated as Core would allocate them in the original column order. + columns = sorted( + frame.columns, key=lambda column: _variable_of(column) in custom_variables + ) + return frame.loc[:, columns] def flat_file_microsimulation( @@ -765,7 +809,8 @@ def flat_file_microsimulation( Pass the original frame for inputs added by ``reform=`` on the default system. With an explicit tax-benefit system, register those inputs on that - system before calling this helper. + system before calling this helper. Variables with custom period-conversion + handlers load after ordinary inputs, in file order. Args: people: The flat file, as ``prepare_flat_file`` describes. @@ -798,24 +843,61 @@ def build_from_dataset(self): prepared = _prepare_flat_file( self.dataset.load(), year, state, self.tax_benefit_system ) + prepared = _with_custom_inputs_last( + prepared, self.tax_benefit_system.variables, year + ) self.dataset = Dataset.from_dataframe(prepared, year) - self._loading_flat_file = True + self.default_calculation_period = self.dataset.time_period + # Core's subsample rebuild needs the preexisting baseline's policy. + baseline = self.baseline + registered_baseline = ( + baseline is not None and self.branches.get("baseline") is baseline + ) + self.baseline = None + self.branches.clear() + self._fast_cache.clear() + self._requested_variables = None + self.__dict__.pop("_behavioral_response_measurements", None) + self._flat_file_loader_id = id(self) try: super().build_from_dataset() finally: - self._loading_flat_file = False + self._flat_file_loader_id = None + self.branches.clear() + self.baseline = baseline + if registered_baseline: + self.branches["baseline"] = baseline def set_input(self, variable_name, period, value): - calculations_started = self._calculations_started - result = super().set_input(variable_name, period, value) - if ( - getattr(self, "_loading_flat_file", False) - and self._calculations_started != calculations_started + # Core copies attributes onto clones. Only the loader itself + # should discard state, once the outer input handler has returned. + if getattr(self, "_flat_file_loader_id", None) != id(self) or getattr( + self, "_user_input_contexts", () ): - # A handler can calculate with only part of the file loaded. - # Clear those results before a later input handler can reuse them. - self.drop_computed_arrays() - return result + return super().set_input(variable_name, period, value) + if _has_custom_input_handler( + self.tax_benefit_system.variables.get(variable_name) + ): + # US branch cloning and formulas read this metadata before + # Core would normally populate it at the end of construction. + self.input_variables = sorted( + {name for name, _, _ in self._user_input_keys} + ) + calculations_started = self._calculations_started + try: + return super().set_input(variable_name, period, value) + finally: + # Branches are snapshots and a handler can calculate on one + # without starting any calculation on the loader. + self.branches.clear() + self.__dict__.pop("_behavioral_response_measurements", None) + if self._calculations_started != calculations_started: + self.drop_computed_arrays() + self._requested_variables = None + # SPM receipts live on the provider, outside Core's caches. + provider = self.tax_benefit_system.spm_forecast_provider + self.tax_benefit_system.spm_forecast_provider = provider.snapshot() + self._record_county_input_types() microsim = FlatFileMicrosimulation( dataset=Dataset.from_dataframe(people, year), diff --git a/tests/test_us_flat_file.py b/tests/test_us_flat_file.py index bf66d7cc1..8a40dc457 100644 --- a/tests/test_us_flat_file.py +++ b/tests/test_us_flat_file.py @@ -532,8 +532,27 @@ def test_county_and_benefit_between_recorded_geography_years(calculate_2026_firs assert sim.get_holder("county").get_known_periods() == [] +@pytest.fixture +def county_recording_system(): + class research_county(Variable): + label = "Research county" + value_type = str + entity = Household + definition_period = periods.MONTH + + def set_input(holder, period, _array): + county = holder.simulation.household("county_str", period.this_year) + set_input_dispatch_by_period(holder, period, county) + + system = CountryTaxBenefitSystem() + system.add_variable(research_county) + return system + + @pytest.mark.parametrize("handler_first", [False, True], ids=["after", "before"]) -def test_county_calculated_by_an_input_handler_is_not_reused(handler_first): +def test_county_calculated_by_an_input_handler_is_not_reused( + handler_first, county_recording_system +): seen = [] class research_payment(Variable): @@ -547,18 +566,7 @@ def set_input(holder, period, array): seen.extend(county.decode_to_str().tolist()) set_input_dispatch_by_period(holder, period, array) - class research_county(Variable): - label = "Research county" - value_type = str - entity = Household - definition_period = periods.MONTH - - def set_input(holder, period, _array): - county = holder.simulation.household("county", period.this_year) - set_input_dispatch_by_period(holder, period, county.decode_to_str()) - - system = CountryTaxBenefitSystem() - system.add_variables(research_payment, research_county) + county_recording_system.add_variable(research_payment) geography = { "state_fips__2024": 50, "county_fips__2024": "50007", @@ -571,10 +579,11 @@ def set_input(holder, period, _array): people = one_person_households([40]).assign( **inputs, research_county__2026="record" ) - sim = pe.us.flat_file_microsimulation(people, year=2024, tax_benefit_system=system) + sim = pe.us.flat_file_microsimulation( + people, year=2024, tax_benefit_system=county_recording_system + ) - expected = County.ALAMEDA_COUNTY_CA if handler_first else County.ADAMS_COUNTY_MS - assert seen == [expected.name] + assert seen == [County.ADAMS_COUNTY_MS.name] assert sim.calculate("research_payment", "2026-01").tolist() == [1250] assert sim.calculate("research_county", "2026-01").tolist() == [ County.ADAMS_COUNTY_MS.name @@ -588,6 +597,43 @@ def set_input(holder, period, _array): assert sim.get_holder("county").get_known_periods() == [] +@pytest.mark.parametrize( + "state, geography, expected", + [ + pytest.param("MS", {}, County.ADAMS_COUNTY_MS, id="moved-state"), + pytest.param( + None, + {"state_fips": 6, "county_fips": LOS_ANGELES_COUNTY}, + County.LOS_ANGELES_COUNTY_CA, + id="county-fips", + ), + pytest.param( + None, + {"state_fips": 6, "county": County.LOS_ANGELES_COUNTY_CA.name}, + County.LOS_ANGELES_COUNTY_CA, + id="county", + ), + pytest.param( + None, + {"state_fips": 6, "county_str": County.LOS_ANGELES_COUNTY_CA.name}, + County.LOS_ANGELES_COUNTY_CA, + id="county-str", + ), + ], +) +def test_an_input_handler_records_prepared_geography( + state, geography, expected, county_recording_system +): + people = one_person_households([40]).assign( + research_county__2026="record", **geography + ) + sim = pe.us.flat_file_microsimulation( + people, year=2026, state=state, tax_benefit_system=county_recording_system + ) + + assert sim.calculate("research_county", "2026-01").tolist() == [expected.name] + + def test_a_missing_county_uses_the_reformed_in_state_fallback(): class first_county_in_state(Variable): def formula(household, period, parameters): @@ -606,6 +652,166 @@ def apply(system): assert sim.calculate("vt_reach_up_housing_allowance", "2024-01").tolist() == [450] +@pytest.mark.parametrize("calculate_on_branch", [False, True], ids=["parent", "branch"]) +def test_a_load_time_tax_calculation_leaves_no_branches(calculate_on_branch): + class research_payment(Variable): + label = "Research payment" + value_type = float + entity = Person + definition_period = periods.MONTH + + def set_input(holder, period, array): + simulation = holder.simulation + if calculate_on_branch: + simulation = simulation.get_branch("research") + simulation.tax_unit("income_tax", period.this_year) + assert "itemizing" in simulation.branches + set_input_dispatch_by_period(holder, period, array) + + class research_probe(Variable): + label = "Research probe" + value_type = float + entity = Person + definition_period = periods.MONTH + + def set_input(holder, period, array): + assert holder.simulation.branches == {} + set_input_dispatch_by_period(holder, period, array) + + system = CountryTaxBenefitSystem() + system.add_variables(research_payment, research_probe) + people = one_person_households([40]).assign( + employment_income__2026=100_000, + research_payment__2026=1250, + charitable_cash_donations__2026=40_000, + research_probe__2026=1, + ) + options = dict(year=2026, state="NV", spm=NATIONAL_SPM, tax_benefit_system=system) + sim = pe.us.flat_file_microsimulation(people, **options) + assert sim.branches == {} + clean = pe.us.flat_file_microsimulation( + people.drop(columns=["research_payment__2026", "research_probe__2026"]), + **options, + ) + assert sim.calculate("research_payment", "2026-01").tolist() == [1250] + assert sim.calculate("tax_unit_itemizes", 2026).tolist() == [True] + np.testing.assert_array_equal( + sim.calculate("income_tax", 2026), clean.calculate("income_tax", 2026) + ) + + +@pytest.mark.parametrize("use_default_period", [False, True]) +def test_a_custom_input_handler_reads_the_files_age(use_default_period): + class research_age(Variable): + label = "Recorded research age" + value_type = int + entity = Person + definition_period = periods.MONTH + + def set_input(holder, period, _array): + read_period = None if use_default_period else period.this_year + age = holder.simulation.calculate("age", read_period, use_weights=False) + set_input_dispatch_by_period(holder, period, age) + + system = CountryTaxBenefitSystem() + system.add_variable(research_age) + ages = {"age__2024": 41, "age__2026": 57} + handler = {"research_age__2026": 0} + inputs = {**ages, **handler} if use_default_period else {**handler, **ages} + people = one_person_households([57]).drop(columns="age").assign(**inputs) + sim = pe.us.flat_file_microsimulation( + people, + year=2026, + state="NV", + default_calculation_period=2024, + tax_benefit_system=system, + ) + + assert sim.calculate("research_age", "2026-01").tolist() == [57] + + +def test_load_time_behavioral_measurements_are_discarded(): + from policyengine_us.variables.gov.simulation.behavioral_response_measurements import ( + get_behavioral_response_measurements, + ) + + class research_measure(Variable): + label = "Research measurement" + value_type = float + entity = Person + definition_period = periods.MONTH + + def set_input(holder, period, _array): + person = holder.simulation.person + person("labor_supply_behavioral_response", period.this_year) + measurements = get_behavioral_response_measurements( + person, period.this_year + ) + set_input_dispatch_by_period( + holder, period, measurements["reform_net_income"] + ) + + class research_income(Variable): + label = "Updated research income" + value_type = float + entity = Person + definition_period = periods.MONTH + + def set_input(holder, period, array): + holder.simulation.set_input("household_net_income", period.this_year, array) + set_input_dispatch_by_period(holder, period, array) + + system = CountryTaxBenefitSystem() + system.add_variables(research_measure, research_income) + people = one_person_households([40]).assign( + household_net_income=20_000, + marginal_tax_rate=0.1, + marginal_tax_rate_on_capital_gains=0.2, + research_measure=0, + research_income=50_000, + ) + sim = pe.us.flat_file_microsimulation( + people, year=2026, state="NV", tax_benefit_system=system + ) + + assert sim.calculate("research_measure", "2026-01").tolist() == [20_000] + with pytest.raises(ValueError, match="requires labor_supply_behavioral_response"): + sim.calculate("relative_income_change", 2026) + measurements = get_behavioral_response_measurements( + sim.person, periods.period(2026) + ) + assert measurements["reform_net_income"].tolist() == [50_000] + + +def test_load_time_spm_measurements_are_discarded(): + class research_threshold(Variable): + label = "Research threshold" + value_type = float + entity = Person + definition_period = periods.MONTH + + def set_input(holder, period, _array): + threshold = holder.simulation.spm_unit( + "spm_unit_spm_threshold", period.this_year + ) + set_input_dispatch_by_period(holder, period, threshold) + + system = CountryTaxBenefitSystem() + system.add_variable(research_threshold) + people = one_person_households([40]).assign(research_threshold=0) + sim = pe.us.flat_file_microsimulation( + people, year=YEAR, state="NV", spm=NATIONAL_SPM, tax_benefit_system=system + ) + + assert sim.spm_provenance()["years"] == {} + assert sim.spm_provenance()["geographies"] == [] + np.testing.assert_allclose( + sim.calculate("research_threshold", "2024-01"), + sim.calculate("spm_unit_spm_threshold", YEAR), + ) + assert str(YEAR) in sim.spm_provenance()["years"] + + class TestMovingToAState: def test_a_file_may_start_with_no_state(self): prepared = prepare_flat_file(survey(), year=YEAR, state="MS") @@ -1499,6 +1705,18 @@ def test_keywords_reach_the_simulation(): assert reformed > sim.baseline.calculate("ctc", YEAR).sum() +def test_subsampling_a_flat_file_keeps_its_reform_baseline(): + people = one_person_households([30, 40]) + reform = {"gov.irs.deductions.standard.amount.SINGLE": {"2024-01-01": 1234}} + sim = pe.us.flat_file_microsimulation(people, year=YEAR, state="NV", reform=reform) + + sim.subsample(n=1, seed=1) + + assert sim.get_branch("baseline") is sim.baseline + assert sim.calculate("standard_deduction", YEAR).tolist() == [1234] + assert sim.baseline.calculate("standard_deduction", YEAR).tolist() == [14_600] + + @pytest.mark.parametrize("column", ["person_tax_unit_role__2024", "role"]) def test_the_loader_reads_role_columns(column): people = one_person_households([30, 40]).assign(**{column: ["member", "invalid"]})