diff --git a/changelog.d/732.added.md b/changelog.d/732.added.md new file mode 100644 index 000000000..124a010a9 --- /dev/null +++ b/changelog.d/732.added.md @@ -0,0 +1 @@ +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/_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..8d2e5986a --- /dev/null +++ b/docs/simulated-instruments.md @@ -0,0 +1,106 @@ +--- +title: "Simulated instruments" +--- + +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 + +```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() +``` + +`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. + +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 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. | +| `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. 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. | +| `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() +``` + +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 +- 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. + +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. 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: + +```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 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 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. + +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.** 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` 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. 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. 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..8a38bcb1f --- /dev/null +++ b/src/policyengine/tax_benefit_models/us/flat_file.py @@ -0,0 +1,922 @@ +"""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 +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 adds periods to variable columns, preserves the bare ``role`` +column, and puts each person's groups on their own row. +""" + +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 +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 ( + 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") +# 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 = ( + "ami", + "average_home_energy_use_in_state", + "block_geoid", + "ca_tanf_region1", + "cbsa_code", + "congressional_district_geoid", + "county", + "county_fips", + "county_str", + "ct_tfa_region", + "hud_extremely_low_income_limit", + "hud_fair_market_rent", + "hud_low_income_limit", + "hud_utility_allowance", + "hud_very_low_income_limit", + "il_aabd_area", + "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_dcf_csfp_county_eligible", + "ks_tanf_county_group", + "lcbp_age_0", + "ma_dese_csfp_county_eligible", + "medicaid_rating_area", + "pa_ccw_stepparent_county_group", + "pa_tanf_county_group", + "pha_payment_standard", + "place_fips", + "puma", + "safmr_used_for_hcv", + "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", + "tract_geoid", + "va_ccsp_locality_group", + "va_medicaid_lifc_locality_group", + "vtd", + "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, + } +) +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" +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 + + +def _variable_of(column: str) -> str: + """The variable a ``variable__period`` column belongs to.""" + 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 _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 = [ + 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, 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: + 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 name in group_roles or variables[name].definition_period == periods.ETERNITY: + suffix = ETERNITY + else: + suffix = str(period) + return f"{name}__{suffix}" + + # 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( + 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, group_roles: set[str] +) -> pd.DataFrame: + """Drop columns the model cannot read, and say so.""" + unknown = [ + 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])) + 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, 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." + # 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 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 + 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(storage) + logging.warning( + f"{name} holds values too large to store exactly, so the run numbers " + "them in file order." + ) + 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: + """Number groups in the order the file first names them. + + 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) + + +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 numeric IDs when the model can store them. + """ + memberships = {} + for group in GROUP_ENTITIES: + columns = _id_columns(frame, f"{group}_id", year) + _id_columns( + frame, f"person_{group}_id", year + ) + if columns: + 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, dtype)).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) + 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 = _id_columns(frame, "person_id", year) + if person_columns: + 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})." + ) + 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, membership) in memberships.items(): + identifiers[f"{group}_id__{year}"] = 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[1:]: + 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: dict[str, list[str]] = {} + for column in frame.columns: + name = _variable_of(column) + if name in ID_VARIABLES or name not in 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(dropna=False).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. + + ``read_csv`` turns 06037 into 6037, or 6037.0 next to a blank. + """ + 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: + 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) + + +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 _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 + + 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." + ) + + +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 ( + County, + ) + from policyengine_us.variables.household.demographic.geographic.state_code import ( + StateCode, + ) + from policyengine_us.variables.household.demographic.geographic.state_name import ( + StateName, + ) + + # 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: + values = np.asarray(frame[column].values) + if values.dtype.kind == "O": + values = values.copy() + for index, value in enumerate(values): + 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__}." + ) + allowed_enums.add(cls) + values[index] = value.name + 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: + """Read a postal code or a FIPS code as a FIPS code.""" + 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.") + + +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)) + 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 + for column in frame.columns + if _variable_of(column) in {*STATE_LABELS, *LOCAL_GEOGRAPHY} + ] + ) + 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.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: + 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 == "county" and f"{name}__{year}" not in frame: + # The model reads the latest stored county, whichever year that is. + 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, 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"))} + for read_year in sorted(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." + ) + 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: + 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." + ) + + for label in STATE_LABELS: + stored = frame.get(f"{label}__{read_year}") + if ( + 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. " + "Correct them, or pass state= to run the file in one state." + ) + + +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: + encoded = value.encode("utf-8", errors="surrogatepass") + digest.update(len(encoded).to_bytes(8, "big")) + digest.update(encoded) + + 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 values: + kind = type(value) + 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) + 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): + 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() + + +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 model 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. 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 + to every year the file holds and clears stored state labels and + 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 + 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 + + 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, 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) + 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." + ) + 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, variables) + _require_groups_within_households(frame, year) + 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) + frame = _with_enum_names(frame, variables) + default_state = variables["state_fips"].default_value + _require_coherent_geography(frame, year, years, default_state) + _warn_unknown_county_fips(frame) + _require_group_values_agree(frame, year, variables) + # 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( + people: pd.DataFrame, + *, + year: int, + state: Optional[Union[str, int]] = None, + spm: Optional[Union[SPMSelection, dict[str, object]]] = None, + **kwargs, +): + """Build a bundled ``Microsimulation`` over a researcher's own flat file. + + 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. Variables with custom period-conversion + handlers load after ordinary inputs, in file order. + + 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``, + whose ``flat_file`` entry records the year, the state and a SHA-256 + fingerprint of the prepared frame and the model's stored inputs. + """ + 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`.") + + 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 + ) + prepared = _with_custom_inputs_last( + prepared, self.tax_benefit_system.variables, year + ) + self.dataset = Dataset.from_dataframe(prepared, year) + 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._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): + # 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", () + ): + 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), + 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["flat_file"] = { + "year": year, + "state": None if state is None else _state_fips(state), + "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 new file mode 100644 index 000000000..8a40dc457 --- /dev/null +++ b/tests/test_us_flat_file.py @@ -0,0 +1,1779 @@ +"""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") + +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 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, +) +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 + DERIVED_FROM_STATE, + LOCAL_GEOGRAPHY, + STATE_LABELS, + _county_text, + 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 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) + + +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_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: + 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_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( + household_id=survey()["household_id"] * 4096 + offset + ) + 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( + 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"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( + {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) + + 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", + [ + (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_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) + + @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) + + @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"): + 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_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) + + @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) + + def test_a_household_across_states(self): + people = in_state(survey()) + people.loc[0, "state_fips"] = MISSISSIPPI + 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_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", + [ + ("county_fips", LOS_ANGELES_COUNTY), + ("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"), + ("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) + + @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( + **{ + 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( + **{ + 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) + + @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) + + @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_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"): + 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) + + 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_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): + prepare_flat_file(people, year=YEAR) + 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, + ) + sim = pe.us.flat_file_microsimulation(people, year=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) + 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() == [] + + +@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, county_recording_system +): + 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) + + county_recording_system.add_variable(research_payment) + 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=county_recording_system + ) + + 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 + ] + 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() == [] + + +@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): + 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] + + +@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") + 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_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)} + ) + 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_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") + 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}") + 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) + + @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)) +def test_any_county_code_reads_the_same_as_text_or_number(code): + """County codes survive whichever form read_csv left them in.""" + 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]) +@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" + 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)) + 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_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(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"] + ) + + +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_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( + 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_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( + 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(): + """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 + + +@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 = ( + "ami", + "ca_tanf_region1", + "ct_tfa_region", + "hud_extremely_low_income_limit", + "hud_fair_market_rent", + "hud_low_income_limit", + "hud_utility_allowance", + "hud_very_low_income_limit", + "il_aabd_area", + "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_dcf_csfp_county_eligible", + "ks_tanf_county_group", + "lcbp_age_0", + "ma_dese_csfp_county_eligible", + "pa_ccw_stepparent_county_group", + "pa_tanf_county_group", + "pha_payment_standard", + "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", + "va_ccsp_locality_group", + "va_medicaid_lifc_locality_group", + "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 + + +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] + + +@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"), + [ + ("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 + ) + assert sim.calculate(name, YEAR).tolist() == [supplied] + + +@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( + 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_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, 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") + + +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_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"]}) + 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] + + +@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" + 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") + + +@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() + )