From cc50a0cd664ede5c93bd44630cb6398c6b7c1a67 Mon Sep 17 00:00:00 2001 From: David Trimmer Date: Wed, 18 Nov 2026 14:22:56 -0500 Subject: [PATCH] Report held-out SNAP caseload composition and take-up (#647) Adds us_snap_caseload_composition_holdout.json beside the other held-out reports certification writes: on the written release H5, the SPM units receiving SNAP split by whether they pass the federal gross and net income tests and the federal resource test, and take-up among eligible units, nationally and by state at the release's weights. Validation only: it never enters the calibration registry or a take-up stage and never refuses a release; an unavailable measurement is reported as such. A unit is eligible on its December is_snap_eligible and receives when its annual snap is also positive: policyengine-core reports a monthly true-or-false variable for a year as its December value. A unit failing an income test and the resource test counts under income. The report lists the states where the share of eligible units carrying the take-up flag, or receiving, reaches 0.999; the take-up stage's own diagnostic measures saturation at pre-calibration weights. The national shares sit beside USDA's estimates in its proposed rule on categorical eligibility (91 FR 72454, at 72457 and 72459): 5.4% of participating households above an income limit and 11.5% above the resource limit alone. The post-export scoring plan gains one consumer of ten SPM-unit keys, so a build made at this commit records it and its certification scores one more baseline pass. The build itself runs no new engine pass. Tests: hand-computed composition, take-up and state rows; Hypothesis invariants (inputs never written, totals linear in the weights, order invariant and additive over batches, groups partition the receiving units); batch-size invariance through the household-batched scorer; no ledger mapping or pinned Chronicle record set carries a federal-test measure; an engine-scenario test pins the December rule and the groups on policyengine-us 2.145.3. Co-Authored-By: Claude Fable 5.2 --- ...-caseload-composition-holdout-647.added.md | 1 + docs/agent-guide.md | 23 + docs/us-release-build-rule.md | 2 +- .../snap_caseload_composition_holdout.py | 602 +++++++++++++ .../us/test_us_fiscal_refresh_builder.py | 144 ++- .../us/test_us_post_export_scoring.py | 108 +++ ...st_us_snap_caseload_composition_holdout.py | 819 ++++++++++++++++++ .../engine_free/us/test_us_spine_blindness.py | 3 + ...st_us_snap_caseload_composition_holdout.py | 230 +++++ ...st_us_snap_caseload_composition_holdout.py | 130 +++ .../microcosm_build/us_post_export_scoring.py | 68 +- tools/build_us_fiscal_refresh_release.py | 81 ++ 12 files changed, 2208 insertions(+), 3 deletions(-) create mode 100644 changelog.d/us-snap-caseload-composition-holdout-647.added.md create mode 100644 packages/microcosm-build/src/microcosm/build/us_runtime/snap_caseload_composition_holdout.py create mode 100644 packages/microcosm-build/tests/engine_free/us/test_us_snap_caseload_composition_holdout.py create mode 100644 packages/microcosm-build/tests/engine_scenario/us/test_us_snap_caseload_composition_holdout.py create mode 100644 packages/microcosm-build/tests/engine_workflow/us/test_us_snap_caseload_composition_holdout.py diff --git a/changelog.d/us-snap-caseload-composition-holdout-647.added.md b/changelog.d/us-snap-caseload-composition-holdout-647.added.md new file mode 100644 index 0000000000..599745f14c --- /dev/null +++ b/changelog.d/us-snap-caseload-composition-holdout-647.added.md @@ -0,0 +1 @@ +Report held-out SNAP caseload composition against the federal income and resource tests, and take-up among eligible units, at the release's weights in `us_snap_caseload_composition_holdout.json`, beside USDA's estimates in 91 FR 72454; validation only, never a calibration target, take-up input or release gate (#647). diff --git a/docs/agent-guide.md b/docs/agent-guide.md index 40216f3617..b3f709b591 100644 --- a/docs/agent-guide.md +++ b/docs/agent-guide.md @@ -458,6 +458,29 @@ includes PolicyEngine/policyengine-us#10106, which falls back to the earliest input year, so the holdout now reports payers. A Part with no weighted payer never reports a Trustees comparison. It is held out the same way: no calibration row, no release refusal. +It also writes `us_snap_caseload_composition_holdout.json`: the SPM units +receiving SNAP, split by whether they pass the federal gross and net income +tests and the federal resource test, and take-up among eligible units, +nationally and by state at the release's weights (microcosm#647). A unit is +eligible on its December `is_snap_eligible` and receives when its annual +`snap` is also positive: policyengine-core reports a monthly true-or-false +variable for a year as its December value. A unit failing an income test and +the resource test counts under income, as in USDA's shares. Persons are the +unit's `snap_unit_size`, which leaves out the members SNAP excludes. Each +unit's state and weight are the engine's own for the unit +(`spm_unit_state_fips` and the weights on the result), never a household +value mapped to its units, which shares the value out by head count. Units +with `receives_snap`, the survey report the take-up stage anchors on, are +split into those receiving, those eligible with no benefit and those the +engine finds not eligible. The report lists +the states where the share of eligible units carrying +`takes_up_snap_if_eligible`, or receiving, reaches 0.999; the take-up stage's +own diagnostic measures saturation at pre-calibration weights. The national +shares sit beside USDA's estimates in its 2026 proposed rule on categorical +eligibility (91 FR 72454, at 72457 and 72459): 5.4% of participating +households above an income limit and 11.5% above the resource limit alone. It +is held out the same way: no calibration row, no take-up input, no release +refusal. It also writes `us_population_structure_holdout.json` from the written H5 alone (no engine): marital status of people 65+ by sex (ACS 2024 B12002), people 65+ living alone (ACS 2024 B09021), people receiving Social Security in diff --git a/docs/us-release-build-rule.md b/docs/us-release-build-rule.md index e9f94df6ec..d1b7a9577a 100644 --- a/docs/us-release-build-rule.md +++ b/docs/us-release-build-rule.md @@ -42,7 +42,7 @@ county SOI targets out of the local-area solve, then score those blocks against a pro-rata baseline; the scores are marked report-only and refuse nothing. `us_runtime/support_mix.py` uses them to split targets and to order ACS households for the support-mix bake-off. The national builder imports neither -helper. Its three +helper. Its four `*_holdout.json` reports compare one build with outside benchmarks and never refuse a release. So a US national release says it beats the incumbent on the frozen register, and says it beats it on held-out cells only once a national diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/snap_caseload_composition_holdout.py b/packages/microcosm-build/src/microcosm/build/us_runtime/snap_caseload_composition_holdout.py new file mode 100644 index 0000000000..85e2976dff --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/snap_caseload_composition_holdout.py @@ -0,0 +1,602 @@ +"""Held-out SNAP caseload composition and take-up, never a calibration target. + +The US release reports this diagnostic beside its other held-out reports. +Calibration fits state SNAP household counts and benefit dollars, which say +nothing about who the modeled recipients are: how many sit outside the federal +income and resource limits, and whether every eligible unit ends up receiving. +The shares of participating households USDA estimates above those limits, in +its 2026 proposed rule on categorical eligibility, are comparators here, not +fitted rows or a release gate (microcosm#647). +""" + +from __future__ import annotations + +import json +from dataclasses import dataclass +from pathlib import Path +from types import MappingProxyType +from typing import Any + +import numpy as np +import pandas as pd + +from microcosm.calibrate.geography_constants import US_STATE_NUMERIC_FIPS_TO_POSTAL + +__all__ = [ + "SNAP_CASELOAD_ASSET_THRESHOLD", + "SNAP_CASELOAD_COMPOSITION_HOLDOUT_VARIABLES", + "SNAP_SATURATION_THRESHOLD", + "USDA_CATEGORICAL_ELIGIBILITY_PROPOSED_RULE_2026", + "USDA_CATEGORICAL_ELIGIBILITY_PROPOSED_RULE_CITATION", + "USDA_CATEGORICAL_ELIGIBILITY_PROPOSED_RULE_TITLE", + "USDA_CATEGORICAL_ELIGIBILITY_PROPOSED_RULE_URL", + "SnapFederalLimitBenchmark", + "snap_caseload_composition_holdout_from_sim", + "snap_caseload_composition_holdout_payload", + "snap_caseload_composition_holdout_unavailable", + "write_snap_caseload_composition_holdout", +] + +_BENEFIT = "snap" +_ELIGIBLE = "is_snap_eligible" +_GROSS_TEST = "meets_snap_gross_income_test" +_NET_TEST = "meets_snap_net_income_test" +_ASSET_TEST = "meets_snap_asset_test" +_ASSETS = "snap_assets" +_TAKE_UP_FLAG = "takes_up_snap_if_eligible" +_REPORTED_RECEIPT = "receives_snap" +_SIZE = "snap_unit_size" +_STATE = "spm_unit_state_fips" +_WEIGHT = "weight" +#: The SPM-unit variables the release scorer computes, in request order. +SNAP_CASELOAD_COMPOSITION_HOLDOUT_VARIABLES: tuple[str, ...] = ( + _BENEFIT, + _ELIGIBLE, + _GROSS_TEST, + _NET_TEST, + _ASSET_TEST, + _ASSETS, + _TAKE_UP_FLAG, + _REPORTED_RECEIPT, + _SIZE, + _STATE, +) +_BOOLEAN_VARIABLES = ( + _ELIGIBLE, + _GROSS_TEST, + _NET_TEST, + _ASSET_TEST, + _TAKE_UP_FLAG, + _REPORTED_RECEIPT, +) + +#: Reporting threshold for liquid assets among receiving units, in dollars. +SNAP_CASELOAD_ASSET_THRESHOLD = 3_000.0 +#: A state is listed once one of its take-up shares reaches this value. +SNAP_SATURATION_THRESHOLD = 0.999 + +_INCOME_FAILING = "income_failing" +_ASSET_ONLY = "asset_only" +_WITHIN_LIMITS = "within_federal_limits" +_OUTSIDE_LIMITS = "outside_federal_limits" +_MODELED_RECIPIENT = "modeled_recipient" +_ELIGIBLE_NON_RECIPIENT = "eligible_non_recipient" +_NOT_ELIGIBLE = "not_eligible" +_TAKE_UP_SHARES = ( + "flagged_share_of_eligible_units", + "receiving_share_of_eligible_units", + "receiving_share_of_eligible_persons", +) +_DEFINITIONS = MappingProxyType( + { + "eligible": f"SPM units with {_ELIGIBLE} in December", + "flagged": f"eligible units with {_TAKE_UP_FLAG}", + "receiving": f"eligible units with a positive annual {_BENEFIT}", + "persons": ( + f"units weighted by {_SIZE} in December: the unit's members SNAP " + "does not exclude" + ), + "records": "units with a positive weight", + "average_monthly_benefit": f"annual {_BENEFIT} divided by twelve", + _INCOME_FAILING: ( + "receiving units that fail the federal gross or net income test, " + "whatever their resource test result" + ), + _ASSET_ONLY: ( + "receiving units that pass both federal income tests and fail the " + "federal resource test" + ), + _WITHIN_LIMITS: "receiving units that pass all three federal tests", + "reported_receipt": ( + f"receiving units with {_REPORTED_RECEIPT} in December; a file that " + f"stores no {_REPORTED_RECEIPT} reads every receiving unit as " + "take_up_fill" + ), + "take_up_fill": "every other receiving unit", + "reported_recipients": ( + f"units with {_REPORTED_RECEIPT} in December, whatever the engine " + "makes of them" + ), + _MODELED_RECIPIENT: "reported units that are receiving units", + _ELIGIBLE_NON_RECIPIENT: ( + "reported units eligible in December with no annual benefit" + ), + _NOT_ELIGIBLE: ( + "reported units not eligible in December, whatever their annual benefit" + ), + "benefit_outside_december_eligibility": ( + f"units with a positive annual {_BENEFIT} that are not eligible in " + "December; counted in no share" + ), + } +) + + +@dataclass(frozen=True) +class SnapFederalLimitBenchmark: + """One USDA estimate of participating households above a federal limit.""" + + group: str + label: str + printed_page: int + household_share: float + participant_share: float | None = None + fiscal_year: int | None = None + households: int | None = None + individuals: int | None = None + + +USDA_CATEGORICAL_ELIGIBILITY_PROPOSED_RULE_TITLE = ( + "Supplemental Nutrition Assistance Program: Reforming Categorical Eligibility" +) +USDA_CATEGORICAL_ELIGIBILITY_PROPOSED_RULE_CITATION = "91 FR 72454" +USDA_CATEGORICAL_ELIGIBILITY_PROPOSED_RULE_URL = ( + "https://www.federalregister.gov/documents/2026/11/10/2026-22936/" + "supplemental-nutrition-assistance-program-reforming-categorical-eligibility" +) + +#: USDA's estimates in the proposed rule's preamble (November 10, 2026). Fixed +#: held-out observations, never passed to the calibration target registry or to +#: a take-up stage. Page 72457 gives the fiscal year 2024 households with +#: incomes above the federal gross or net limits and with resources above the +#: federal limit; its note 25 counts a household failing both under income. +#: Page 72459 gives the combined shares of households and participants above +#: the limits, without a year. +USDA_CATEGORICAL_ELIGIBILITY_PROPOSED_RULE_2026 = MappingProxyType( + { + _INCOME_FAILING: SnapFederalLimitBenchmark( + group=_INCOME_FAILING, + label="Incomes above the federal gross or net income limits", + printed_page=72457, + household_share=0.054, + fiscal_year=2024, + households=1_200_000, + individuals=2_000_000, + ), + _ASSET_ONLY: SnapFederalLimitBenchmark( + group=_ASSET_ONLY, + label="Resources above the federal limit, incomes within the limits", + printed_page=72457, + household_share=0.115, + fiscal_year=2024, + households=2_500_000, + individuals=5_400_000, + ), + _OUTSIDE_LIMITS: SnapFederalLimitBenchmark( + group=_OUTSIDE_LIMITS, + label="Income or resources above the federal limits", + printed_page=72459, + household_share=0.169, + participant_share=0.176, + ), + } +) + + +def snap_caseload_composition_holdout_unavailable( + error: Exception, *, period: int, release_id: str | None = None +) -> dict[str, Any]: + """An observational receipt when plan discovery or scoring is unavailable.""" + payload: dict[str, Any] = { + "schema_version": 1, + "status": "unavailable", + "period": int(period), + "target_role": "validation", + "enforced": False, + "used_for_calibration": False, + "source_url": USDA_CATEGORICAL_ELIGIBILITY_PROPOSED_RULE_URL, + "error": f"{type(error).__name__}: {error}", + } + if release_id is not None: + payload["release_id"] = release_id + return payload + + +def _ratio(numerator: float, denominator: float) -> float | None: + return numerator / denominator if denominator > 0 else None + + +def _kish_effective_sample_size(weights: np.ndarray) -> float | None: + """Kish effective sample size, ``(sum w)^2 / sum w^2``.""" + squared = float(np.square(weights).sum()) + return float(weights.sum()) ** 2 / squared if squared > 0 else None + + +def _boolean(values: np.ndarray, name: str) -> np.ndarray: + if values.dtype == np.bool_: + return values + try: + numeric = values.astype(np.float64) + except (TypeError, ValueError) as error: + raise ValueError(f"{name} must be boolean.") from error + if not np.isin(numeric, (0.0, 1.0)).all(): + # A count of months is not a December value: refuse it instead of + # reading every positive count as true. + raise ValueError(f"{name} must be boolean.") + return numeric == 1.0 + + +def _numeric(values: np.ndarray, name: str, *, nonnegative: bool = True) -> np.ndarray: + try: + numeric = values.astype(np.float64) + except (TypeError, ValueError) as error: + raise ValueError(f"{name} must be numeric.") from error + if not np.isfinite(numeric).all(): + raise ValueError(f"{name} must be finite.") + if nonnegative and np.any(numeric < 0): + raise ValueError(f"{name} must be nonnegative.") + return numeric + + +_STATE_FIPS_CODES = np.fromiter(US_STATE_NUMERIC_FIPS_TO_POSTAL, dtype=np.float64) + + +def _state_codes(values: np.ndarray) -> np.ndarray: + numeric = _numeric(values, _STATE) + # A household's code shared out among its units by head count is a + # fraction of the state's code. A code that belongs to no state is refused + # here. One that lands on another state's code cannot be told apart, so + # the scorer must be asked for the unit's own state, as from_sim does. + if not np.isin(numeric, _STATE_FIPS_CODES).all(): + raise ValueError(f"{_STATE} must be a state FIPS code.") + return np.array([f"{int(code):02d}" for code in numeric], dtype="U2") + + +@dataclass(frozen=True) +class _Units: + """Validated SPM-unit columns; a selection copies and writes no input.""" + + weight: np.ndarray + benefit: np.ndarray + eligible: np.ndarray + passes_income: np.ndarray + passes_assets: np.ndarray + assets: np.ndarray + flagged: np.ndarray + reported: np.ndarray + size: np.ndarray + state: np.ndarray + + def select(self, mask: np.ndarray) -> _Units: + return _Units( + **{name: getattr(self, name)[mask] for name in self.__dataclass_fields__} + ) + + +def _validated_units(units: pd.DataFrame) -> _Units: + required = (_WEIGHT, *SNAP_CASELOAD_COMPOSITION_HOLDOUT_VARIABLES) + missing = [column for column in required if column not in units.columns] + if missing: + raise ValueError(f"SNAP caseload composition needs column(s): {missing}.") + columns = {name: units[name].to_numpy() for name in required} + booleans = {name: _boolean(columns[name], name) for name in _BOOLEAN_VARIABLES} + return _Units( + weight=_numeric(columns[_WEIGHT], _WEIGHT), + benefit=_numeric(columns[_BENEFIT], _BENEFIT), + eligible=booleans[_ELIGIBLE], + passes_income=booleans[_GROSS_TEST] & booleans[_NET_TEST], + passes_assets=booleans[_ASSET_TEST], + assets=_numeric(columns[_ASSETS], _ASSETS, nonnegative=False), + flagged=booleans[_TAKE_UP_FLAG], + reported=booleans[_REPORTED_RECEIPT], + size=_numeric(columns[_SIZE], _SIZE), + state=_state_codes(columns[_STATE]), + ) + + +def _records(weights: np.ndarray) -> int: + return int(np.count_nonzero(weights > 0)) + + +def _group_row( + units: _Units, + mask: np.ndarray, + *, + receiving_units: float, + receiving_persons: float, +) -> dict[str, Any]: + weights = units.weight[mask] + weighted_units = float(weights.sum()) + weighted_persons = float((weights * units.size[mask]).sum()) + annual_benefits = float((weights * units.benefit[mask]).sum()) + return { + "records": _records(weights), + "weighted_units": weighted_units, + "weighted_persons": weighted_persons, + "share_of_receiving_units": _ratio(weighted_units, receiving_units), + "share_of_receiving_persons": _ratio(weighted_persons, receiving_persons), + "average_monthly_benefit": _ratio(annual_benefits / 12, weighted_units), + "kish_effective_sample_size": _kish_effective_sample_size(weights), + } + + +def _scope_row(units: _Units) -> dict[str, Any]: + weights = units.weight + persons = weights * units.size + positive = units.benefit > 0 + receiving = units.eligible & positive + outside = ~units.eligible & positive + eligible_units = float(weights[units.eligible].sum()) + eligible_persons = float(persons[units.eligible].sum()) + flagged_units = float(weights[units.eligible & units.flagged].sum()) + receiving_weights = weights[receiving] + receiving_units = float(receiving_weights.sum()) + receiving_persons = float(persons[receiving].sum()) + + def group(mask: np.ndarray) -> dict[str, Any]: + return _group_row( + units, + receiving & mask, + receiving_units=receiving_units, + receiving_persons=receiving_persons, + ) + + reported_units = float(weights[units.reported].sum()) + + def reported(mask: np.ndarray) -> dict[str, Any]: + selected = weights[units.reported & mask] + weighted_units = float(selected.sum()) + return { + "records": _records(selected), + "weighted_units": weighted_units, + "share_of_reported_units": _ratio(weighted_units, reported_units), + } + + over_threshold = receiving & (units.assets > SNAP_CASELOAD_ASSET_THRESHOLD) + return { + "take_up": { + "eligible_records": _records(weights[units.eligible]), + "eligible_weighted_units": eligible_units, + "eligible_weighted_persons": eligible_persons, + "flagged_weighted_units": flagged_units, + "receiving_weighted_units": receiving_units, + "receiving_weighted_persons": receiving_persons, + "flagged_share_of_eligible_units": _ratio(flagged_units, eligible_units), + "receiving_share_of_eligible_units": _ratio( + receiving_units, eligible_units + ), + "receiving_share_of_eligible_persons": _ratio( + receiving_persons, eligible_persons + ), + }, + "receiving": { + "records": _records(receiving_weights), + "weighted_units": receiving_units, + "weighted_persons": receiving_persons, + "annual_benefits": float((weights * units.benefit)[receiving].sum()), + "kish_effective_sample_size": _kish_effective_sample_size( + receiving_weights + ), + "persons_per_unit": _ratio(receiving_persons, receiving_units), + "single_person_unit_share": _ratio( + float(weights[receiving & (units.size == 1)].sum()), receiving_units + ), + "share_with_snap_assets_over_threshold": _ratio( + float(weights[over_threshold].sum()), receiving_units + ), + }, + "composition": { + _INCOME_FAILING: group(~units.passes_income), + _ASSET_ONLY: group(units.passes_income & ~units.passes_assets), + _WITHIN_LIMITS: group(units.passes_income & units.passes_assets), + }, + "caseload_source": { + "reported_receipt": group(units.reported), + "take_up_fill": group(~units.reported), + }, + "reported_recipients": { + "records": _records(weights[units.reported]), + "weighted_units": reported_units, + _MODELED_RECIPIENT: reported(receiving), + _ELIGIBLE_NON_RECIPIENT: reported(units.eligible & ~positive), + _NOT_ELIGIBLE: reported(~units.eligible), + }, + "benefit_outside_december_eligibility": { + "records": _records(weights[outside]), + "weighted_units": float(weights[outside].sum()), + "annual_benefits": float((weights * units.benefit)[outside].sum()), + }, + } + + +def _percentage_points(share: float | None, benchmark: float | None) -> float | None: + if share is None or benchmark is None: + return None + return 100 * (share - benchmark) + + +def _comparisons(national: dict[str, Any]) -> list[dict[str, Any]]: + """The national composition beside USDA's shares; nothing is compared by state.""" + composition = national["composition"] + receiving = national["receiving"] + outside = (_INCOME_FAILING, _ASSET_ONLY) + shares = { + group: ( + composition[group]["share_of_receiving_units"], + composition[group]["share_of_receiving_persons"], + ) + for group in outside + } + shares[_OUTSIDE_LIMITS] = ( + _ratio( + sum(composition[group]["weighted_units"] for group in outside), + receiving["weighted_units"], + ), + _ratio( + sum(composition[group]["weighted_persons"] for group in outside), + receiving["weighted_persons"], + ), + ) + rows = [] + for group, benchmark in USDA_CATEGORICAL_ELIGIBILITY_PROPOSED_RULE_2026.items(): + unit_share, person_share = shares[group] + rows.append( + { + "group": group, + "label": benchmark.label, + "share_of_receiving_units": unit_share, + "share_of_receiving_persons": person_share, + "benchmark_household_share": benchmark.household_share, + "benchmark_participant_share": benchmark.participant_share, + "benchmark_households": benchmark.households, + "benchmark_individuals": benchmark.individuals, + "benchmark_fiscal_year": benchmark.fiscal_year, + "benchmark_printed_page": benchmark.printed_page, + "difference_percentage_points": _percentage_points( + unit_share, benchmark.household_share + ), + "person_difference_percentage_points": _percentage_points( + person_share, benchmark.participant_share + ), + } + ) + return rows + + +def _states_at_or_above_threshold(states: list[dict[str, Any]]) -> dict[str, list[str]]: + return { + share: [ + row["state_fips"] + for row in states + if row["take_up"][share] is not None + and row["take_up"][share] >= SNAP_SATURATION_THRESHOLD + ] + for share in _TAKE_UP_SHARES + } + + +def snap_caseload_composition_holdout_payload( + units: pd.DataFrame, *, period: int, release_id: str | None = None +) -> dict[str, Any]: + """SNAP recipients by federal test result, and take-up among the eligible. + + ``units`` holds one row per SPM unit: its calibrated ``weight`` and the + ``SNAP_CASELOAD_COMPOSITION_HOLDOUT_VARIABLES`` as the written-H5 scorer + returns them for the period. The engine reports a monthly true-or-false + variable for a year as its December value, so eligibility, the income + tests and reported receipt are December's; the benefit is the year's + total. A unit receives when it is eligible in December and its annual + benefit is positive. A benefit paid to a unit not eligible in December is + reported apart and counted in no share. + + Persons are each unit's SNAP unit size, which leaves out the members SNAP + excludes. A unit's state and weight are the engine's own values for the + unit, never a household value shared out among its units by head count; a + code that belongs to no state is refused. Units that report receipt are + also split by what the engine makes of them: receiving, eligible with no + benefit, or not eligible. + + Each receiving unit falls in exactly one composition group. A unit failing + both an income test and the resource test counts as income-failing, the + convention of the USDA shares. A share or average with no weight behind it + is null, not zero. The function reads its inputs and never writes them. + """ + validated = _validated_units(units) + national = _scope_row(validated) + states = [ + { + "state_fips": str(state), + **_scope_row(validated.select(validated.state == state)), + } + for state in np.unique(validated.state) + ] + payload: dict[str, Any] = { + "schema_version": 1, + "status": "available", + "period": int(period), + "target_role": "validation", + "enforced": False, + "used_for_calibration": False, + "measure": ( + "SNAP recipients by federal income and resource test result, and " + "take-up among eligible units" + ), + "weight_basis": "SPM unit's calibrated household_weight", + "monthly_values_read_in": "December", + "definitions": dict(_DEFINITIONS), + "asset_threshold": SNAP_CASELOAD_ASSET_THRESHOLD, + "saturation_threshold": SNAP_SATURATION_THRESHOLD, + "reported_receipt_present": bool(validated.reported.any()), + "benchmark": { + "source": USDA_CATEGORICAL_ELIGIBILITY_PROPOSED_RULE_TITLE, + "citation": USDA_CATEGORICAL_ELIGIBILITY_PROPOSED_RULE_CITATION, + "source_url": USDA_CATEGORICAL_ELIGIBILITY_PROPOSED_RULE_URL, + "published": "2026-11-10", + "population": "participating SNAP households", + "double_counting": ( + "A household failing both the income and resource tests is " + "counted under income (note 25)." + ), + "resource_data": ( + "Survey of Income and Program Participation, December 2019 (note 14)" + ), + }, + "comparability": ( + "USDA estimates shares of participating SNAP households, by limit " + "for fiscal year 2024, with resources estimated from the December " + "2019 Survey of Income and Program Participation. The model counts " + f"SPM units in {int(period)} that are eligible in December and " + "carry a positive annual benefit, and reads each monthly test in " + "December. The model's SNAP household is the SPM unit less the " + "members SNAP excludes, which need not be the household a State " + "agency forms, and the model spreads annual income evenly over the " + "months. This is a held-out diagnostic, not an exact population or " + "period match, a calibration target, or a release gate." + ), + "national": national, + "states": states, + "states_at_or_above_saturation_threshold": _states_at_or_above_threshold( + states + ), + "comparisons": _comparisons(national), + } + if release_id is not None: + payload["release_id"] = release_id + return payload + + +def snap_caseload_composition_holdout_from_sim( + simulation: Any, *, period: int, release_id: str | None = None +) -> dict[str, Any]: + """Measure aligned SPM-unit results from the household-batched H5 scorer.""" + results = { + variable: simulation.calculate(variable, period) + for variable in SNAP_CASELOAD_COMPOSITION_HOLDOUT_VARIABLES + } + units = pd.DataFrame( + {variable: np.asarray(result) for variable, result in results.items()} + ) + units[_WEIGHT] = np.asarray(results[_BENEFIT].weights) + return snap_caseload_composition_holdout_payload( + units, period=period, release_id=release_id + ) + + +def write_snap_caseload_composition_holdout( + payload: dict[str, Any], path: Path | str +) -> Path: + path = Path(path) + path.write_text( + json.dumps(payload, indent=2, sort_keys=True, allow_nan=False) + "\n" + ) + return path diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py index 22c7309323..a2c2d2e49f 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py @@ -7249,6 +7249,40 @@ def calculate(variable, period): def simulate(reform): return SimpleNamespace(calculate=calculate) + if name == "snap_caseload_composition_holdout": + captured["snap_holdout_scored"] = self.dataset_path + record.update( + baseline_passes=1, + reform_passes=0, + reform_systems=0, + n_batches=1, + max_batch_households=2, + ) + + def calculate(variable, period): + assert period == builder.PERIOD + # Two eligible, receiving units: a one-person California + # unit over the resource limit and a three-person Texas + # unit within every federal limit. + values = { + "snap": [1_200.0, 2_400.0], + "is_snap_eligible": [True, True], + "meets_snap_gross_income_test": [True, True], + "meets_snap_net_income_test": [True, True], + "meets_snap_asset_test": [False, True], + "snap_assets": [9_000.0, 0.0], + "takes_up_snap_if_eligible": [True, True], + "receives_snap": [False, True], + "snap_unit_size": [1, 3], + "spm_unit_state_fips": [6.0, 48.0], + } + return builder._PostExportValues( + np.array(values[variable]), np.array([2.0, 3.0]) + ) + + def simulate(reform): + return SimpleNamespace(calculate=calculate) + return SimpleNamespace(name=name, simulate=simulate, record=lambda: record) def finish_consumer(self, scoring): @@ -7385,6 +7419,9 @@ def record_certified_contract(directory, *, artifact_root=None): assert captured["planned_reform_passes"]["reform_coverage_smoke"] == 0 # The holdouts score no reform, so _main gives them no count. assert captured["planned_reform_passes"]["ssi_social_security_holdout"] is None + assert ( + captured["planned_reform_passes"]["snap_caseload_composition_holdout"] is None + ) assert captured["scorer_opened_on"] == captured["written_dataset"] assert captured["holdout_scored"] == captured["written_dataset"] assert captured["scorer_closed"] is True @@ -7414,6 +7451,25 @@ def record_certified_contract(directory, *, artifact_root=None): assert part_b["weighted_aggregate_premiums"] == pytest.approx(2 * 12 * 69.90) assert part_d["weighted_payers"] == 2 assert part_d["weighted_aggregate_premiums"] == pytest.approx(2 * 12 * 12.90) + assert captured["snap_holdout_scored"] == captured["written_dataset"] + snap_holdout_path = release_dir / "us_snap_caseload_composition_holdout.json" + snap_holdout = json.loads(snap_holdout_path.read_text()) + assert snap_holdout["status"] == "available" + assert snap_holdout["release_id"] == release_id + assert snap_holdout["enforced"] is False + assert snap_holdout["used_for_calibration"] is False + assert snap_holdout["benchmark"]["citation"] == "91 FR 72454" + snap_national = snap_holdout["national"] + assert snap_national["take_up"]["receiving_share_of_eligible_units"] == 1 + snap_composition = snap_national["composition"] + assert snap_composition["income_failing"]["weighted_units"] == 0 + assert snap_composition["asset_only"]["share_of_receiving_units"] == ( + pytest.approx(0.4) + ) + assert snap_composition["within_federal_limits"][ + "share_of_receiving_units" + ] == pytest.approx(0.6) + assert [row["state_fips"] for row in snap_holdout["states"]] == ["06", "48"] # The population-structure holdout reads the written H5 only after the # scorer closes. The harness H5 holds placeholder bytes, so the step # records the report as unavailable and the release still publishes it. @@ -7500,12 +7556,17 @@ def record_certified_contract(directory, *, artifact_root=None): assert block["post_export_scoring"] == { "dataset_sha256": build_manifest["dataset"]["sha256"], "consumers": ( - ["ssi_social_security_holdout", "medicare_irmaa_holdout"] + [ + "ssi_social_security_holdout", + "medicare_irmaa_holdout", + "snap_caseload_composition_holdout", + ] if skipped_smoke else [ "reform_coverage_smoke", "ssi_social_security_holdout", "medicare_irmaa_holdout", + "snap_caseload_composition_holdout", ] ), } @@ -7531,6 +7592,13 @@ def record_certified_contract(directory, *, artifact_root=None): "sha256": hashlib.sha256(population_path.read_bytes()).hexdigest(), "role": "us_population_structure_holdout", } + assert artifacts["us_snap_caseload_composition_holdout"] == { + "kind": "diagnostics", + "path": snap_holdout_path.name, + "repo_id": builder.REPO_ID, + "sha256": hashlib.sha256(snap_holdout_path.read_bytes()).hexdigest(), + "role": "us_snap_caseload_composition_holdout", + } if not skipped_smoke: smoke = json.loads((release_dir / "reform_coverage_smoke.json").read_text()) assert smoke["reform_coverage_smoke"]["passed"] is True @@ -10320,6 +10388,7 @@ def fake_release_gate_failures(*args, **kwargs): "demographics", "ssi_social_security_holdout", "medicare_irmaa_holdout", + "snap_caseload_composition_holdout", ] assert captured["diagnostics"]["default_dataset"] == { "method": "l0_refit", @@ -14027,6 +14096,79 @@ def score_holdout(name, consumer, **kwargs): assert failures == [] +@pytest.mark.parametrize( + "scoring_available", (True, False), ids=("available", "unavailable") +) +def test_build_manifests_selects_snap_caseload_composition_holdout_for_publication( + monkeypatch, tmp_path, scoring_available +) -> None: + from microcosm.build.us_runtime.snap_caseload_composition_holdout import ( + SNAP_CASELOAD_COMPOSITION_HOLDOUT_VARIABLES, + snap_caseload_composition_holdout_payload, + ) + from microcosm.data.contract import ( + _check_local_artifact_hashes, + _check_release_manifest, + ) + from microcosm.data.release import _release_manifest_release_artifacts + + builder = _load_builder_module() + release_id, release_dir, artifact_root = _gate_evidence_release_dir( + builder, monkeypatch, tmp_path, coverage={} + ) + + def score_holdout(name, consumer, **kwargs): + assert name == "snap_caseload_composition_holdout" + if not scoring_available: + raise RuntimeError("holdout scoring is unavailable") + values = ( + [1_200.0, 0.0], + [True, True], + [False, True], + [True, True], + [True, True], + [0.0, 0.0], + [True, False], + [False, False], + [2, 1], + [6, 6], + ) + units = pd.DataFrame( + dict(zip(SNAP_CASELOAD_COMPOSITION_HOLDOUT_VARIABLES, values, strict=True)) + ) + units["weight"] = [1.0, 2.0] + return snap_caseload_composition_holdout_payload(units, period=builder.PERIOD) + + monkeypatch.setattr(builder, "_score_post_export_consumer", score_holdout) + builder._write_snap_caseload_composition_holdout( + release_dir=release_dir, + dataset_path=artifact_root / builder.DATASET_FILENAME, + release_id=release_id, + ) + builder._build_manifests( + **_minimal_manifest_kwargs(builder, release_id, release_dir, artifact_root) + ) + + filename = "us_snap_caseload_composition_holdout.json" + holdout_path = release_dir / filename + holdout = json.loads(holdout_path.read_text()) + assert holdout["status"] == ("available" if scoring_available else "unavailable") + assert holdout["release_id"] == release_id + manifest = json.loads((release_dir / "release_manifest.json").read_text()) + assert manifest["artifacts"]["us_snap_caseload_composition_holdout"] == { + "kind": "diagnostics", + "path": filename, + "repo_id": builder.REPO_ID, + "revision": release_id, + "sha256": hashlib.sha256(holdout_path.read_bytes()).hexdigest(), + } + assert filename in _release_manifest_release_artifacts(release_dir) + failures: list[str] = [] + _check_release_manifest(manifest, release_id, failures) + _check_local_artifact_hashes(release_dir, manifest, failures) + assert failures == [] + + def _write_scf_education_debt_fits(builder, monkeypatch, release_dir, filenames): monkeypatch.setattr( builder, diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_scoring.py b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_scoring.py index d355f085bc..5ae21f1a4e 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_post_export_scoring.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_post_export_scoring.py @@ -465,6 +465,7 @@ def default_tax_benefit_system(*args, **kwargs): "demographics", "ssi_social_security_holdout", "medicare_irmaa_holdout", + "snap_caseload_composition_holdout", ] smoke_keys = { (probe.budget_measure, int(probe.period or builder.PERIOD), None) @@ -484,6 +485,18 @@ def default_tax_benefit_system(*args, **kwargs): ("base_part_b_premium", builder.PERIOD, None), ("income_adjusted_part_d_premium_surcharge", builder.PERIOD, None), ) + assert plan.baseline_plan("snap_caseload_composition_holdout") == ( + ("snap", builder.PERIOD, None), + ("is_snap_eligible", builder.PERIOD, None), + ("meets_snap_gross_income_test", builder.PERIOD, None), + ("meets_snap_net_income_test", builder.PERIOD, None), + ("meets_snap_asset_test", builder.PERIOD, None), + ("snap_assets", builder.PERIOD, None), + ("takes_up_snap_if_eligible", builder.PERIOD, None), + ("receives_snap", builder.PERIOD, None), + ("snap_unit_size", builder.PERIOD, None), + ("spm_unit_state_fips", builder.PERIOD, None), + ) validation = plan.baseline_plan("reform_validation") assert ("income_tax", builder.PERIOD, None) in validation assert ("state_code_str", builder.PERIOD, None) in validation @@ -506,6 +519,7 @@ def default_tax_benefit_system(*args, **kwargs): "demographics", "ssi_social_security_holdout", "medicare_irmaa_holdout", + "snap_caseload_composition_holdout", ] @@ -580,6 +594,98 @@ def unavailable(*args, **kwargs): assert builder._medicare_irmaa_holdout_consumer(None)["status"] == "unavailable" +def test_snap_caseload_composition_holdout_is_invariant_to_household_batch_size( + builder, tmp_path +) -> None: + frame = _nested_frame() + consumer = builder._snap_caseload_composition_holdout_consumer + reference = consumer(_unbatched_simulate(frame, _EngineLog())) + assert reference["status"] == "available" + national = reference["national"] + # The fixture's unit of household 4 is not eligible; every other unit + # receives: 300 + 500 + 700 + 1,300 + 1,700 + 1,900. + assert national["receiving"]["weighted_units"] == 6_400 + assert national["benefit_outside_december_eligibility"]["weighted_units"] == 1_100 + composition = national["composition"] + # Households 3 and 6 fail the gross test and household 5 the net test. + assert composition["income_failing"]["weighted_units"] == 3_700 + # Household 2 passes both and fails the resource test. + assert composition["asset_only"]["weighted_units"] == 500 + assert composition["within_federal_limits"]["weighted_units"] == 2_200 + # Household 7 is eligible without the take-up flag. + assert national["take_up"]["flagged_weighted_units"] == 4_500 + assert [row["state_fips"] for row in reference["states"]] == [ + "06", + "24", + "36", + "48", + ] + for batch_size in (1, 2, None): + log = _EngineLog() + scorer = _scorer(builder, frame, log, batch_size, tmp_path / str(batch_size)) + plan = builder._record_post_export_baseline_plan(consumer) + scoring = scorer.open_consumer("snap_caseload_composition_holdout", plan) + payload = consumer(scoring.simulate) + assert payload == reference + record = scorer.finish_consumer(scoring) + assert record["baseline_passes"] == 1 + assert record["reform_passes"] == record["reform_systems"] == 0 + assert len(log.constructions) == scorer.n_batches + scorer.close() + + +def test_snap_caseload_composition_holdout_measurement_error_is_report_only( + builder, monkeypatch, tmp_path +) -> None: + def unavailable(*args, **kwargs): + raise ValueError("fixture unavailable") + + monkeypatch.setattr(builder, "_score_post_export_consumer", unavailable) + builder._write_snap_caseload_composition_holdout( + release_dir=tmp_path, + dataset_path=tmp_path / "fixture.h5", + release_id="fixture", + ) + payload = json.loads( + (tmp_path / "us_snap_caseload_composition_holdout.json").read_text() + ) + assert payload["status"] == "unavailable" + assert payload["error"] == "ValueError: fixture unavailable" + assert payload["enforced"] is False + assert payload["used_for_calibration"] is False + + +def test_snap_caseload_composition_holdout_discovery_error_does_not_fail_the_plan( + builder, monkeypatch +) -> None: + def unavailable(*args, **kwargs): + raise KeyError("snap_assets") + + monkeypatch.setattr( + builder, "snap_caseload_composition_holdout_from_sim", unavailable + ) + args = SimpleNamespace( + skip_reform_coverage_smoke=True, + skip_reform_validation=True, + skip_out_of_sample_reforms=True, + skip_demographics=True, + maximum_microsim_batch_size=3, + ) + plan = builder._record_post_export_scoring_plan( + args, + n_households=7, + result=_empty_calibration_result(), + release_id="fixture", + ) + assert plan.error is None + assert plan.terminal_failures() == [] + assert plan.baseline_plan("snap_caseload_composition_holdout") == () + assert ( + builder._snap_caseload_composition_holdout_consumer(None)["status"] + == "unavailable" + ) + + def test_ssi_social_security_holdout_is_invariant_to_household_batch_size( builder, tmp_path ) -> None: @@ -739,6 +845,7 @@ def test_an_unbuildable_plan_is_recorded_and_refused_not_raised( "demographics", "ssi_social_security_holdout", "medicare_irmaa_holdout", + "snap_caseload_composition_holdout", ] empty = builder._PostExportScoringPlan( n_households=7, maximum_batch_size=3, baseline_plans={} @@ -820,6 +927,7 @@ def test_main_and_writers_never_build_a_whole_pool_simulation(builder) -> None: "_write_demographics", "_write_ssi_social_security_holdout", "_write_medicare_irmaa_holdout", + "_write_snap_caseload_composition_holdout", ): _, tree = _function_source(builder, name) called = _called_names(tree) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_snap_caseload_composition_holdout.py b/packages/microcosm-build/tests/engine_free/us/test_us_snap_caseload_composition_holdout.py new file mode 100644 index 0000000000..b3b69b8963 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_snap_caseload_composition_holdout.py @@ -0,0 +1,819 @@ +"""Held-out SNAP caseload composition without a country engine (microcosm#647). + +Invariants: + +* The holdout never changes weights or any other input: it reads read-only + arrays and returns a new payload. +* Weighted units, persons and benefits are linear in the weights, invariant to + unit order, and additive over any split of the units (household batches). +* The three composition groups partition the receiving units, and receiving + units never outweigh eligible units. +* A benefit paid to a unit not eligible in December reaches no share. +* Units reporting receipt fall in exactly one of three groups: receiving, + eligible with no benefit, or not eligible. +* A state code that belongs to no state is refused, never filed under one. +* A share with no weight behind it is null, never zero or a failed gate. +* The USDA shares are validation only: no ledger mapping binds a federal test, + the pinned Chronicle feed carries no caseload-composition record set, and + only the release tool imports the holdout. +""" + +import json +import math +import re +from importlib.resources import files + +import numpy as np +import pandas as pd +import pytest +from hypothesis import given, settings +from hypothesis import strategies as st + +from microcosm.build.us_runtime import fiscal_targets +from microcosm.build.us_runtime.snap_caseload_composition_holdout import ( + SNAP_CASELOAD_ASSET_THRESHOLD, + SNAP_CASELOAD_COMPOSITION_HOLDOUT_VARIABLES, + SNAP_SATURATION_THRESHOLD, + USDA_CATEGORICAL_ELIGIBILITY_PROPOSED_RULE_2026, + USDA_CATEGORICAL_ELIGIBILITY_PROPOSED_RULE_URL, + snap_caseload_composition_holdout_from_sim, + snap_caseload_composition_holdout_payload, + snap_caseload_composition_holdout_unavailable, + write_snap_caseload_composition_holdout, +) +from test_support.paths import paths_for + +_COLUMNS = ( + "unit", + "weight", + "snap", + "is_snap_eligible", + "meets_snap_gross_income_test", + "meets_snap_net_income_test", + "meets_snap_asset_test", + "snap_assets", + "takes_up_snap_if_eligible", + "receives_snap", + "snap_unit_size", + "spm_unit_state_fips", +) +# Annual benefits. F is eligible without the take-up flag; I carries the flag +# and a zero benefit; H has a benefit but is not eligible in December; G's +# assets sit exactly at the reporting threshold; D fails an income test and the +# resource test. A, D, F, G and H report receipt: F and H without receiving. +_ROWS = ( + ("A", 10.0, 1_200.0, True, True, True, True, 0.0, True, True, 1, 1), + ("B", 30.0, 2_400.0, True, True, True, True, 500.0, True, False, 3, 1), + ("C", 20.0, 600.0, True, False, True, True, 4_000.0, True, False, 2, 1), + ("D", 10.0, 240.0, True, True, False, False, 5_000.0, True, True, 1, 6), + ("E", 20.0, 4_800.0, True, True, True, False, 9_000.0, True, False, 4, 6), + ("F", 40.0, 0.0, True, True, True, True, 0.0, False, True, 2, 6), + ("G", 10.0, 3_600.0, True, True, True, True, 3_000.0, True, True, 1, 6), + ("H", 5.0, 900.0, False, True, True, True, 0.0, True, True, 2, 6), + ("I", 25.0, 0.0, True, True, True, True, 0.0, True, False, 2, 1), +) + + +_REPORTED_GROUPS = ("modeled_recipient", "eligible_non_recipient", "not_eligible") + + +def _units(rows=_ROWS) -> pd.DataFrame: + return pd.DataFrame(list(rows), columns=_COLUMNS).drop(columns="unit") + + +def _payload(units=None, *, period=2024, **kwargs) -> dict: + return snap_caseload_composition_holdout_payload( + _units() if units is None else units, period=period, **kwargs + ) + + +def test_usda_shares_match_the_proposed_rule_preamble(): + """91 FR 72457 (shares by limit, note 25) and 72459 (combined shares).""" + rows = USDA_CATEGORICAL_ELIGIBILITY_PROPOSED_RULE_2026 + income, assets, outside = ( + rows["income_failing"], + rows["asset_only"], + rows["outside_federal_limits"], + ) + assert (income.household_share, income.printed_page) == (0.054, 72457) + assert (income.households, income.individuals) == (1_200_000, 2_000_000) + assert (assets.household_share, assets.printed_page) == (0.115, 72457) + assert (assets.households, assets.individuals) == (2_500_000, 5_400_000) + assert income.fiscal_year == assets.fiscal_year == 2024 + assert (outside.household_share, outside.participant_share) == (0.169, 0.176) + assert outside.printed_page == 72459 + assert outside.household_share == pytest.approx( + income.household_share + assets.household_share + ) + assert list(rows) == ["income_failing", "asset_only", "outside_federal_limits"] + with pytest.raises(TypeError): + rows["within_federal_limits"] = income + + +def test_holdout_variables_are_the_engine_measures_in_request_order(): + assert SNAP_CASELOAD_COMPOSITION_HOLDOUT_VARIABLES == ( + "snap", + "is_snap_eligible", + "meets_snap_gross_income_test", + "meets_snap_net_income_test", + "meets_snap_asset_test", + "snap_assets", + "takes_up_snap_if_eligible", + "receives_snap", + "snap_unit_size", + "spm_unit_state_fips", + ) + + +def test_take_up_counts_eligible_flagged_and_receiving_units_and_persons(): + take_up = _payload()["national"]["take_up"] + + # Eligible: every unit but H. 10 + 30 + 20 + 10 + 20 + 40 + 10 + 25 = 165. + assert take_up["eligible_records"] == 8 + assert take_up["eligible_weighted_units"] == 165 + # 10*1 + 30*3 + 20*2 + 10*1 + 20*4 + 40*2 + 10*1 + 25*2 = 370. + assert take_up["eligible_weighted_persons"] == 370 + # F is eligible without the flag: 165 - 40. + assert take_up["flagged_weighted_units"] == 125 + assert take_up["flagged_share_of_eligible_units"] == pytest.approx(125 / 165) + # Receiving: A, B, C, D, E and G. F and I are eligible with no benefit. + assert take_up["receiving_weighted_units"] == 100 + assert take_up["receiving_weighted_persons"] == 240 + assert take_up["receiving_share_of_eligible_units"] == pytest.approx(100 / 165) + assert take_up["receiving_share_of_eligible_persons"] == pytest.approx(240 / 370) + + +def test_composition_groups_partition_the_receiving_units(): + national = _payload()["national"] + groups = national["composition"] + + assert national["receiving"]["records"] == 6 + assert national["receiving"]["weighted_units"] == 100 + # C fails the gross test and D the net test: 20 + 10. + assert groups["income_failing"]["records"] == 2 + assert groups["income_failing"]["weighted_units"] == 30 + assert groups["income_failing"]["share_of_receiving_units"] == pytest.approx(0.30) + # E passes both income tests and fails the resource test. + assert groups["asset_only"]["records"] == 1 + assert groups["asset_only"]["share_of_receiving_units"] == pytest.approx(0.20) + # A, B and G: 10 + 30 + 10. + assert groups["within_federal_limits"]["records"] == 3 + assert groups["within_federal_limits"]["share_of_receiving_units"] == ( + pytest.approx(0.50) + ) + assert sum(row["weighted_units"] for row in groups.values()) == 100 + + +def test_a_unit_failing_income_and_resources_counts_as_income_failing(): + groups = _payload()["national"]["composition"] + + # D fails the net test and the resource test; only E is asset-only. + assert groups["income_failing"]["weighted_units"] == 30 + assert groups["asset_only"]["weighted_units"] == 20 + + +def test_person_shares_weight_each_unit_by_its_size(): + groups = _payload()["national"]["composition"] + + # Receiving persons: 10 + 90 + 40 + 10 + 80 + 10 = 240. + assert groups["income_failing"]["weighted_persons"] == 50 + assert groups["income_failing"]["share_of_receiving_persons"] == pytest.approx( + 50 / 240 + ) + assert groups["asset_only"]["share_of_receiving_persons"] == pytest.approx(80 / 240) + assert groups["within_federal_limits"]["share_of_receiving_persons"] == ( + pytest.approx(110 / 240) + ) + + +def test_benefits_are_annual_totals_and_monthly_averages_divide_by_twelve(): + national = _payload()["national"] + groups = national["composition"] + + # 12,000 + 72,000 + 12,000 + 2,400 + 96,000 + 36,000. + assert national["receiving"]["annual_benefits"] == 230_400 + # (20*600 + 10*240) / 12 / 30. + assert groups["income_failing"]["average_monthly_benefit"] == pytest.approx(40.0) + assert groups["asset_only"]["average_monthly_benefit"] == pytest.approx(400.0) + # (10*1,200 + 30*2,400 + 10*3,600) / 12 / 50. + assert groups["within_federal_limits"]["average_monthly_benefit"] == ( + pytest.approx(200.0) + ) + + +def test_receiving_unit_shape(): + receiving = _payload()["national"]["receiving"] + + assert receiving["persons_per_unit"] == pytest.approx(2.4) + # A, D and G are one-person units: 30 of 100. + assert receiving["single_person_unit_share"] == pytest.approx(0.30) + # C, D and E hold more than $3,000; G holds exactly $3,000. + assert SNAP_CASELOAD_ASSET_THRESHOLD == 3_000 + assert receiving["share_with_snap_assets_over_threshold"] == pytest.approx(0.50) + + +def test_kish_effective_sample_sizes(): + national = _payload()["national"] + + # 100^2 / (100 + 900 + 400 + 100 + 400 + 100). + assert national["receiving"]["kish_effective_sample_size"] == pytest.approx(5.0) + # 30^2 / (400 + 100). + assert national["composition"]["income_failing"][ + "kish_effective_sample_size" + ] == pytest.approx(1.8) + # 50^2 / (100 + 900 + 100). + assert national["composition"]["within_federal_limits"][ + "kish_effective_sample_size" + ] == pytest.approx(2_500 / 1_100) + + +def test_reported_receipt_and_the_take_up_fill_split_the_caseload(): + payload = _payload() + source = payload["national"]["caseload_source"] + + assert payload["reported_receipt_present"] is True + + # A, D and G report receipt. + assert source["reported_receipt"]["records"] == 3 + assert source["reported_receipt"]["share_of_receiving_units"] == pytest.approx(0.30) + # B, C and E come from the fill: 70^2 / (900 + 400 + 400). + assert source["take_up_fill"]["share_of_receiving_units"] == pytest.approx(0.70) + assert source["take_up_fill"]["kish_effective_sample_size"] == pytest.approx( + 4_900 / 1_700 + ) + + +def test_a_file_without_reported_receipt_says_so(): + """A release that stores no receives_snap reads as all take-up fill.""" + units = _units() + units["receives_snap"] = False + payload = _payload(units) + source = payload["national"]["caseload_source"] + + assert payload["reported_receipt_present"] is False + assert source["reported_receipt"]["weighted_units"] == 0 + assert source["take_up_fill"]["share_of_receiving_units"] == 1 + assert "stores no receives_snap" in payload["definitions"]["reported_receipt"] + + +def test_reported_recipients_split_by_what_the_engine_makes_of_them(): + reported = _payload()["national"]["reported_recipients"] + + # A, D, F, G and H report receipt: 10 + 10 + 40 + 10 + 5. + assert reported["records"] == 5 + assert reported["weighted_units"] == 75 + # A, D and G receive. + assert reported["modeled_recipient"] == { + "records": 3, + "weighted_units": 30, + "share_of_reported_units": pytest.approx(30 / 75), + } + # F is eligible with no benefit. + assert reported["eligible_non_recipient"] == { + "records": 1, + "weighted_units": 40, + "share_of_reported_units": pytest.approx(40 / 75), + } + # H is not eligible in December, whatever its benefit. + assert reported["not_eligible"] == { + "records": 1, + "weighted_units": 5, + "share_of_reported_units": pytest.approx(5 / 75), + } + + +def test_reported_recipients_by_state_and_with_no_reporter(): + payload = _payload() + states = {row["state_fips"]: row for row in payload["states"]} + + # Alabama's only reporter, A, receives. + alabama = states["01"]["reported_recipients"] + assert alabama["weighted_units"] == 10 + assert alabama["modeled_recipient"]["share_of_reported_units"] == 1 + assert alabama["eligible_non_recipient"]["share_of_reported_units"] == 0 + # California: D and G receive (20), F does not (40), H is not eligible (5). + california = states["06"]["reported_recipients"] + assert california["weighted_units"] == 65 + assert california["modeled_recipient"]["weighted_units"] == 20 + assert california["eligible_non_recipient"]["weighted_units"] == 40 + assert california["not_eligible"]["weighted_units"] == 5 + + units = _units() + units["receives_snap"] = False + silent = _payload(units)["national"]["reported_recipients"] + assert silent["records"] == 0 + assert silent["weighted_units"] == 0 + for group in _REPORTED_GROUPS: + assert silent[group]["share_of_reported_units"] is None + + +def test_a_household_code_shared_out_among_its_units_is_refused(): + """A unit's state is its own, never its household's code split by head count. + + A household value mapped to its units by head count gives each unit the + household's value times the unit's share of the household's members. For a + California household (06) of four holding units of one and three people + that is 1.5 and 4.5; for two units of two it is 3 and 3. None is a state. + """ + units = _units() + for shared_out in ((1.5, 4.5), (3.0, 3.0)): + units["spm_unit_state_fips"] = [*shared_out, *([6.0] * (len(units) - 2))] + with pytest.raises(ValueError, match="state FIPS code"): + _payload(units) + units["spm_unit_state_fips"] = 6.0 + assert [row["state_fips"] for row in _payload(units)["states"]] == ["06"] + + +def test_a_benefit_outside_december_eligibility_reaches_no_share(): + national = _payload()["national"] + without = _payload(_units([row for row in _ROWS if row[0] != "H"]))["national"] + + assert national["benefit_outside_december_eligibility"] == { + "records": 1, + "weighted_units": 5, + "annual_benefits": 4_500, + } + for block in ("take_up", "receiving", "composition", "caseload_source"): + assert national[block] == without[block] + + +def test_each_state_uses_its_own_units(): + payload = _payload() + states = {row["state_fips"]: row for row in payload["states"]} + + assert list(states) == ["01", "06"] + alabama, california = states["01"], states["06"] + # A, B, C and I are eligible (85) and flagged; A, B and C receive (60). + assert alabama["take_up"]["eligible_weighted_units"] == 85 + assert alabama["take_up"]["flagged_share_of_eligible_units"] == 1 + assert alabama["take_up"]["receiving_share_of_eligible_units"] == pytest.approx( + 60 / 85 + ) + assert alabama["composition"]["income_failing"]["share_of_receiving_units"] == ( + pytest.approx(20 / 60) + ) + assert alabama["composition"]["asset_only"]["share_of_receiving_units"] == 0 + assert alabama["composition"]["asset_only"]["average_monthly_benefit"] is None + # D, E, F and G are eligible (80); D, E and G receive (40), one per group. + assert california["take_up"]["receiving_share_of_eligible_units"] == 0.5 + assert california["composition"]["income_failing"]["share_of_receiving_units"] == ( + 0.25 + ) + assert california["composition"]["asset_only"]["share_of_receiving_units"] == 0.5 + assert california["benefit_outside_december_eligibility"]["weighted_units"] == 5 + assert payload["states_at_or_above_saturation_threshold"] == { + "flagged_share_of_eligible_units": ["01"], + "receiving_share_of_eligible_units": [], + "receiving_share_of_eligible_persons": [], + } + + +def test_states_are_listed_once_a_take_up_share_reaches_the_threshold(): + def unit(weight, benefit, state, *, size=1): + return ( + "x", + weight, + benefit, + True, + True, + True, + True, + 0.0, + True, + False, + size, + state, + ) + + # State 2: every eligible unit receives. State 4: 999 of 1,000 eligible + # units receive, exactly the threshold. State 5: 998 of 1,000. State 6: + # 999 of 1,000 units, but the unit without a benefit holds four people. + rows = ( + unit(7.0, 100.0, 2), + unit(999.0, 100.0, 4), + unit(1.0, 0.0, 4), + unit(998.0, 100.0, 5), + unit(2.0, 0.0, 5), + unit(999.0, 100.0, 6), + unit(1.0, 0.0, 6, size=4), + ) + payload = _payload(_units(rows)) + + assert SNAP_SATURATION_THRESHOLD == 0.999 + assert payload["saturation_threshold"] == 0.999 + listed = payload["states_at_or_above_saturation_threshold"] + assert listed["flagged_share_of_eligible_units"] == ["02", "04", "05", "06"] + assert listed["receiving_share_of_eligible_units"] == ["02", "04", "06"] + # State 6: 999 of 1,003 persons. + assert listed["receiving_share_of_eligible_persons"] == ["02", "04"] + + +def test_usda_shares_are_labelled_held_out_comparisons(): + payload = _payload(release_id="fixture") + income, assets, outside = payload["comparisons"] + + assert income["group"] == "income_failing" + assert income["benchmark_household_share"] == 0.054 + assert income["benchmark_printed_page"] == 72457 + assert income["benchmark_fiscal_year"] == 2024 + assert income["difference_percentage_points"] == pytest.approx(24.6) + assert income["person_difference_percentage_points"] is None + assert assets["group"] == "asset_only" + assert assets["benchmark_household_share"] == 0.115 + assert assets["difference_percentage_points"] == pytest.approx(8.5) + assert outside["group"] == "outside_federal_limits" + assert outside["share_of_receiving_units"] == pytest.approx(0.50) + assert outside["difference_percentage_points"] == pytest.approx(33.1) + # (50 + 80) / 240 persons against 17.6% of participants. + assert outside["share_of_receiving_persons"] == pytest.approx(130 / 240) + assert outside["person_difference_percentage_points"] == pytest.approx( + 100 * (130 / 240 - 0.176) + ) + assert outside["benchmark_printed_page"] == 72459 + assert payload["release_id"] == "fixture" + assert payload["status"] == "available" + assert payload["target_role"] == "validation" + assert payload["enforced"] is False + assert payload["used_for_calibration"] is False + assert "gate" not in payload + assert payload["benchmark"]["citation"] == "91 FR 72454" + assert payload["benchmark"]["source_url"] == ( + USDA_CATEGORICAL_ELIGIBILITY_PROPOSED_RULE_URL + ) + assert "note 25" in payload["benchmark"]["double_counting"] + assert payload["monthly_values_read_in"] == "December" + assert "December" in payload["comparability"] + assert "calibration target" in payload["comparability"] + + +def test_numeric_flags_are_accepted_and_month_counts_refused(): + booleans = _payload() + flags = _units() + for column in ( + "is_snap_eligible", + "meets_snap_gross_income_test", + "meets_snap_net_income_test", + "meets_snap_asset_test", + "takes_up_snap_if_eligible", + "receives_snap", + ): + flags[column] = flags[column].astype(np.float64) + assert _payload(flags) == booleans + + # An engine that summed twelve monthly results would report counts. + counts = _units() + counts["is_snap_eligible"] = np.where(counts["is_snap_eligible"], 12, 0) + with pytest.raises(ValueError, match="is_snap_eligible must be boolean"): + _payload(counts) + + +def test_no_receiving_unit_reports_null_shares(tmp_path): + units = _units() + units["snap"] = 0.0 + payload = _payload(units) + national = payload["national"] + + assert national["take_up"]["eligible_weighted_units"] == 165 + assert national["take_up"]["receiving_share_of_eligible_units"] == 0 + assert national["receiving"]["weighted_units"] == 0 + assert national["receiving"]["persons_per_unit"] is None + assert national["receiving"]["kish_effective_sample_size"] is None + for row in national["composition"].values(): + assert row["weighted_units"] == 0 + assert row["share_of_receiving_units"] is None + assert row["average_monthly_benefit"] is None + for row in payload["comparisons"]: + assert row["share_of_receiving_units"] is None + assert row["difference_percentage_points"] is None + path = write_snap_caseload_composition_holdout(payload, tmp_path / "holdout.json") + assert json.loads(path.read_text()) == payload + + +def test_no_unit_at_all_is_reported_not_refused(): + """The scoring plan's dry run hands the consumer empty results.""" + payload = _payload(_units(())) + + assert payload["status"] == "available" + assert payload["states"] == [] + assert payload["national"]["take_up"]["eligible_weighted_units"] == 0 + assert payload["national"]["take_up"]["flagged_share_of_eligible_units"] is None + json.dumps(payload, allow_nan=False) + + +def test_records_count_units_with_a_positive_weight(): + rows = list(_ROWS) + rows.append(("Z", 0.0, 1_200.0, True, True, True, True, 0.0, True, False, 1, 1)) + national = _payload(_units(rows))["national"] + + assert national["receiving"]["records"] == 6 + assert national["take_up"]["eligible_records"] == 8 + assert national["composition"]["within_federal_limits"]["records"] == 3 + + +def test_unavailable_payload_is_observational(): + payload = snap_caseload_composition_holdout_unavailable( + KeyError("snap_assets"), period=2024, release_id="fixture" + ) + + assert payload["status"] == "unavailable" + assert payload["enforced"] is False + assert payload["used_for_calibration"] is False + assert payload["target_role"] == "validation" + assert payload["error"] == "KeyError: 'snap_assets'" + assert payload["release_id"] == "fixture" + assert payload["source_url"] == USDA_CATEGORICAL_ELIGIBILITY_PROPOSED_RULE_URL + + +def _with(column, value): + units = _units() + units[column] = units[column].astype(object) + units.loc[0, column] = value + return units + + +@pytest.mark.parametrize( + "units, message", + [ + (_units().drop(columns="snap_assets"), "snap_assets"), + (_with("weight", math.nan), "weight must be finite"), + (_with("weight", -1.0), "weight must be nonnegative"), + (_with("snap", -1.0), "snap must be nonnegative"), + (_with("snap", math.inf), "snap must be finite"), + (_with("snap_assets", math.nan), "snap_assets must be finite"), + (_with("snap_unit_size", -1), "snap_unit_size must be nonnegative"), + (_with("meets_snap_asset_test", None), "meets_snap_asset_test must be boolean"), + (_with("receives_snap", 0.5), "receives_snap must be boolean"), + (_with("spm_unit_state_fips", 6.5), "state FIPS code"), + (_with("spm_unit_state_fips", 3), "state FIPS code"), + (_with("spm_unit_state_fips", 0), "state FIPS code"), + (_with("spm_unit_state_fips", 100), "state FIPS code"), + ], +) +def test_malformed_inputs_are_refused_not_silently_reported(units, message): + with pytest.raises(ValueError, match=message): + _payload(units) + + +class _Result: + def __init__(self, values, weights) -> None: + self._values = np.asarray(values) + self.weights = np.asarray(weights, dtype=np.float64) + + def __array__(self, dtype=None, copy=None): + return np.asarray(self._values, dtype=dtype) + + +class _Simulation: + """Serves the fixture columns and records what it was asked for.""" + + def __init__(self, units: pd.DataFrame) -> None: + self._units = units + self.requests: list[tuple] = [] + + def calculate(self, variable, period=None, map_to=None): + self.requests.append((variable, period, map_to)) + return _Result(self._units[variable], self._units["weight"]) + + +def test_from_sim_asks_the_scorer_for_each_variable_once_at_the_period(): + simulation = _Simulation(_units()) + payload = snap_caseload_composition_holdout_from_sim( + simulation, period=2024, release_id="fixture" + ) + + assert simulation.requests == [ + (variable, 2024, None) + for variable in SNAP_CASELOAD_COMPOSITION_HOLDOUT_VARIABLES + ] + assert payload == _payload(release_id="fixture") + + +# --------------------------------------------------------------------------- +# Property-based invariants +# --------------------------------------------------------------------------- + + +@st.composite +def _unit_rows(draw, min_size=0, max_size=30): + n = draw(st.integers(min_value=min_size, max_value=max_size)) + + def booleans(): + return draw(st.lists(st.booleans(), min_size=n, max_size=n)) + + weights = draw( + st.lists( + st.floats(0, 1e4, allow_nan=False, allow_infinity=False), + min_size=n, + max_size=n, + ) + ) + benefits = draw( + st.lists(st.sampled_from((0.0, 276.0, 3_504.0)), min_size=n, max_size=n) + ) + return pd.DataFrame( + { + "weight": np.asarray(weights, dtype=np.float64), + "snap": np.asarray(benefits, dtype=np.float64), + "is_snap_eligible": np.asarray(booleans(), dtype=bool), + "meets_snap_gross_income_test": np.asarray(booleans(), dtype=bool), + "meets_snap_net_income_test": np.asarray(booleans(), dtype=bool), + "meets_snap_asset_test": np.asarray(booleans(), dtype=bool), + "snap_assets": np.asarray( + draw( + st.lists( + st.sampled_from((0.0, 3_000.0, 8_000.0)), min_size=n, max_size=n + ) + ), + dtype=np.float64, + ), + "takes_up_snap_if_eligible": np.asarray(booleans(), dtype=bool), + "receives_snap": np.asarray(booleans(), dtype=bool), + "snap_unit_size": np.asarray( + draw(st.lists(st.integers(1, 6), min_size=n, max_size=n)), + dtype=np.int64, + ), + "spm_unit_state_fips": np.asarray( + draw(st.lists(st.sampled_from((1, 6, 48)), min_size=n, max_size=n)), + dtype=np.int64, + ), + } + ) + + +def _totals(payload) -> list[float]: + national = payload["national"] + totals = [ + national["take_up"]["eligible_weighted_units"], + national["take_up"]["eligible_weighted_persons"], + national["take_up"]["flagged_weighted_units"], + national["receiving"]["weighted_units"], + national["receiving"]["weighted_persons"], + national["receiving"]["annual_benefits"], + national["benefit_outside_december_eligibility"]["weighted_units"], + ] + for block in ("composition", "caseload_source"): + for row in national[block].values(): + totals.extend((row["weighted_units"], row["weighted_persons"])) + reported = national["reported_recipients"] + totals.append(reported["weighted_units"]) + totals.extend(reported[group]["weighted_units"] for group in _REPORTED_GROUPS) + return totals + + +@settings(max_examples=200, deadline=None) +@given(_unit_rows()) +def test_holdout_never_writes_its_inputs(units): + before = units.copy(deep=True) + payload = _payload(units) + pd.testing.assert_frame_equal(units, before) + json.dumps(payload, allow_nan=False) + + +@settings(max_examples=200, deadline=None) +@given(_unit_rows(), st.floats(0.5, 4.0, allow_nan=False)) +def test_totals_scale_with_the_weights(units, scale): + reference = _totals(_payload(units)) + scaled_units = units.assign(weight=units["weight"] * scale) + for total, scaled in zip(reference, _totals(_payload(scaled_units)), strict=True): + assert scaled == pytest.approx(total * scale, rel=1e-9, abs=1e-3) + + +@settings(max_examples=200, deadline=None) +@given(_unit_rows(min_size=1), st.randoms(use_true_random=False), st.data()) +def test_totals_are_order_invariant_and_additive_over_batches(units, rng, data): + n = len(units) + reference = _totals(_payload(units)) + order = list(range(n)) + rng.shuffle(order) + shuffled = _totals(_payload(units.iloc[order].reset_index(drop=True))) + split = data.draw(st.integers(0, n)) + first = _totals(_payload(units.iloc[:split].reset_index(drop=True))) + second = _totals(_payload(units.iloc[split:].reset_index(drop=True))) + for whole, permuted, left, right in zip( + reference, shuffled, first, second, strict=True + ): + assert permuted == pytest.approx(whole, rel=1e-9, abs=1e-3) + assert left + right == pytest.approx(whole, rel=1e-9, abs=1e-3) + + +@settings(max_examples=200, deadline=None) +@given(_unit_rows()) +def test_groups_partition_receiving_units_within_the_eligible(units): + payload = _payload(units) + for scope in (payload["national"], *payload["states"]): + take_up, receiving = scope["take_up"], scope["receiving"] + assert receiving["weighted_units"] <= take_up["eligible_weighted_units"] + 1e-6 + for block in ("composition", "caseload_source"): + assert sum( + row["weighted_units"] for row in scope[block].values() + ) == pytest.approx(receiving["weighted_units"], rel=1e-9, abs=1e-6) + reported = scope["reported_recipients"] + assert sum( + reported[group]["weighted_units"] for group in _REPORTED_GROUPS + ) == pytest.approx(reported["weighted_units"], rel=1e-9, abs=1e-6) + assert ( + sum(reported[group]["records"] for group in _REPORTED_GROUPS) + == (reported["records"]) + ) + share = take_up["receiving_share_of_eligible_units"] + assert share is None or 0 <= share <= 1 + 1e-9 + if receiving["weighted_units"] > 0: + assert sum( + row["share_of_receiving_units"] for row in scope["composition"].values() + ) == pytest.approx(1.0) + assert sum( + row["receiving"]["weighted_units"] for row in payload["states"] + ) == pytest.approx(payload["national"]["receiving"]["weighted_units"], abs=1e-6) + + +@settings(max_examples=200, deadline=None) +@given(_unit_rows(min_size=1), st.data()) +def test_units_not_eligible_in_december_never_reach_a_share(units, data): + """Whatever benefit, flag or test result an ineligible unit carries leaves + every take-up, composition and source figure unchanged.""" + eligible = units["is_snap_eligible"].to_numpy() + reference = _payload(units) + + def noise(values): + return np.asarray( + data.draw( + st.lists( + st.sampled_from(values), min_size=len(units), max_size=len(units) + ) + ) + ) + + perturbed_units = units.copy() + perturbed_units["snap"] = np.where(eligible, units["snap"], noise((0.0, 99.0))) + for column in ( + "meets_snap_gross_income_test", + "meets_snap_net_income_test", + "meets_snap_asset_test", + "takes_up_snap_if_eligible", + "receives_snap", + ): + perturbed_units[column] = np.where( + eligible, units[column], noise((False, True)) + ) + perturbed = _payload(perturbed_units) + for block in ("take_up", "receiving", "composition", "caseload_source"): + assert perturbed["national"][block] == reference["national"][block] + assert perturbed["comparisons"] == reference["comparisons"] + + +# --------------------------------------------------------------------------- +# Validation only: the USDA shares cannot reach calibration or take-up +# --------------------------------------------------------------------------- + + +def test_no_ledger_mapping_binds_a_federal_test_measure(): + """Calibration fits SNAP households and benefits, never who passes a test.""" + held_out = set(SNAP_CASELOAD_COMPOSITION_HOLDOUT_VARIABLES) - {"snap"} + mapped = [] + for mapping in ( + fiscal_targets.DIRECT_LEDGER_TARGETS, + fiscal_targets.INDICATOR_LEDGER_TARGETS, + ): + for key, (base_variable, _, metadata) in mapping.items(): + variables = ( + (base_variable,) if isinstance(base_variable, str) else base_variable + ) + mapped.append((key, set(variables), dict(metadata))) + assert any("snap" in variables for _, variables, _ in mapped) + for key, variables, metadata in mapped: + assert not variables & held_out, key + text = json.dumps([key, metadata]).lower() + assert "categorical" not in text, key + assert "federal_limit" not in text and "resource_limit" not in text, key + + +def test_pinned_chronicle_feed_carries_no_caseload_composition_rows(): + """Only a feed re-pin could bring a USDA composition share to calibration.""" + scope = json.loads( + files("microcosm.build.us").joinpath("chronicle_feed_scope.json").read_text() + ) + assert scope["pairs"] + assert any("usda_snap" in json.dumps(pair) for pair in scope["pairs"]) + for pair in scope["pairs"]: + text = json.dumps(pair).lower() + assert "categorical" not in text and "quality_control" not in text, pair + assert "federal_limit" not in text and "resource" not in text, pair + + +def test_only_the_release_tool_imports_the_holdout(): + """No calibration, take-up, registry or gate module can read the shares.""" + root = paths_for("microcosm-build").repository + pattern = re.compile( + r"snap_caseload_composition_holdout" + r"|USDA_CATEGORICAL_ELIGIBILITY_PROPOSED_RULE" + ) + module = "snap_caseload_composition_holdout.py" + readers = sorted( + path.relative_to(root).as_posix() + for directory in ("packages", "tools") + for path in (root / directory).rglob("*.py") + if "tests" not in path.relative_to(root).parts + and path.name != module + and pattern.search(path.read_text(encoding="utf-8")) + ) + assert readers == ["tools/build_us_fiscal_refresh_release.py"] diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py b/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py index 44664623b6..b0b0705f43 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py @@ -421,6 +421,9 @@ "sipp_financial_assets.py", "sipp_tips.py", "sipp_vehicles.py", + # Reviewed held-out SNAP caseload composition diagnostic; no population + # treatment. + "snap_caseload_composition_holdout.py", "snap_discretionary_exemption.py", "snap_state_take_up.py", "snap_take_up.py", diff --git a/packages/microcosm-build/tests/engine_scenario/us/test_us_snap_caseload_composition_holdout.py b/packages/microcosm-build/tests/engine_scenario/us/test_us_snap_caseload_composition_holdout.py new file mode 100644 index 0000000000..fc1134dedc --- /dev/null +++ b/packages/microcosm-build/tests/engine_scenario/us/test_us_snap_caseload_composition_holdout.py @@ -0,0 +1,230 @@ +"""The SNAP caseload composition holdout's measures on the locked policyengine-us. + +The release scorer asks the engine for each measure at the release year. These +tests pin what the engine returns for that request, on households whose SNAP +position is known, and what the holdout makes of it (microcosm#647). +""" + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build.us_runtime.snap_caseload_composition_holdout import ( + SNAP_CASELOAD_COMPOSITION_HOLDOUT_VARIABLES, + snap_caseload_composition_holdout_payload, +) + +PERIOD = 2024 +MONTHS = [f"{PERIOD}-{month:02d}" for month in range(1, 13)] +JANUARY, DECEMBER = MONTHS[0], MONTHS[-1] +# 7 CFR 273.10(e)(2)(ii)(C): the minimum monthly allotment for a one- or +# two-person household, $23 in fiscal years 2024 and 2025. +_MINIMUM_MONTHLY_ALLOTMENT = 23 +_NAMES = ( + "within", + "asset_only", + "income_failing", + "no_take_up", + "not_eligible", + "october", +) + + +def _household( + name, + *, + state_fips, + earnings, + assets=0.0, + takes_up=True, + reported=(), + undocumented_adult=False, +) -> dict: + """A parent of 35 and a child of 6 in their own household and SPM unit. + + The state is given as ``state_fips`` and reported receipt month by month, + as a release H5 stores them. ``undocumented_adult`` adds a second adult, + whom SNAP excludes from the unit. + """ + adult, child = f"{name}_adult", f"{name}_child" + people = { + adult: { + "age": {PERIOD: 35}, + "employment_income": {PERIOD: earnings}, + "bank_account_assets": {PERIOD: assets}, + }, + child: {"age": {PERIOD: 6}}, + } + if undocumented_adult: + people[f"{name}_other_adult"] = { + "age": {PERIOD: 40}, + "immigration_status": {PERIOD: "UNDOCUMENTED"}, + } + members = list(people) + return { + "people": people, + "tax_units": {f"{name}_tax_unit": {"members": members}}, + "families": {f"{name}_family": {"members": members}}, + "marital_units": { + f"{member}_marital_unit": {"members": [member]} for member in members + }, + "spm_units": { + f"{name}_spm_unit": { + "members": members, + "takes_up_snap_if_eligible": {PERIOD: takes_up}, + "receives_snap": {month: month in reported for month in MONTHS}, + } + }, + "households": { + f"{name}_household": { + "members": members, + "state_fips": {PERIOD: state_fips}, + } + }, + } + + +@pytest.fixture(scope="module") +def simulation(): + """Six households, in ``_NAMES`` order. + + In the locked engine's rules, California (06) and Washington (53) confer + categorical eligibility with no resource test, and Washington's reaches a + household over both federal income limits. Texas (48) keeps a resource + test. Missouri (29) applies the federal limits alone, which rise each + October. The unit without the take-up flag holds a third member, an + undocumented adult, whom SNAP excludes. + """ + from policyengine_us import Simulation + + households = ( + _household("within", state_fips=6, earnings=12_000), + _household( + "asset_only", + state_fips=6, + earnings=12_000, + assets=10_000.0, + reported=MONTHS, + ), + _household("income_failing", state_fips=53, earnings=32_000), + _household( + "no_take_up", + state_fips=6, + earnings=12_000, + takes_up=False, + undocumented_adult=True, + ), + _household("not_eligible", state_fips=48, earnings=12_000, assets=10_000.0), + # Gross income sits between the limits of fiscal years 2024 and 2025. + _household("october", state_fips=29, earnings=26_200, reported=[JANUARY]), + ) + situation: dict = {} + for household in households: + for entity, members in household.items(): + situation.setdefault(entity, {}).update(members) + return Simulation(situation=situation) + + +def _units(simulation) -> pd.DataFrame: + units = pd.DataFrame( + { + variable: np.asarray(simulation.calculate(variable, PERIOD)) + for variable in SNAP_CASELOAD_COMPOSITION_HOLDOUT_VARIABLES + }, + index=list(_NAMES), + ) + units["weight"] = 1.0 + return units + + +def test_a_year_request_reads_monthly_tests_in_december(simulation) -> None: + """Pin the engine rule the holdout's wording rests on (microcosm#647). + + policyengine-core reports a monthly true-or-false variable for a year as + its December value, and a monthly amount as the year's total. If an engine + bump changes either, this test fails and the holdout's definitions, which + say "in December", must change with it. + """ + units = _units(simulation) + position = _NAMES.index("october") + + def month(variable: str, period: str): + return np.asarray(simulation.calculate(variable, period))[position] + + # Eligible from October only, so the year reads eligible. + assert not month("is_snap_eligible", JANUARY) + assert month("is_snap_eligible", DECEMBER) + assert units.loc["october", "is_snap_eligible"] + assert units.loc["october", "meets_snap_gross_income_test"] + # Reported receipt in January only, so the year reads no receipt. + assert month("receives_snap", JANUARY) + assert not month("receives_snap", DECEMBER) + assert not units.loc["october", "receives_snap"] + # The benefit is the three eligible months' total. + assert month("snap", JANUARY) == 0 + assert month("snap", DECEMBER) > 0 + assert units.loc["october", "snap"] == pytest.approx(3 * month("snap", DECEMBER)) + for variable in ( + "is_snap_eligible", + "meets_snap_gross_income_test", + "meets_snap_net_income_test", + "meets_snap_asset_test", + "takes_up_snap_if_eligible", + "receives_snap", + ): + assert units[variable].dtype == np.bool_, variable + + +def test_holdout_groups_follow_the_engine_on_households(simulation) -> None: + units = _units(simulation) + + # Categorical eligibility carries the unit over the resource limit and the + # unit over both income limits; the second gets the minimum allotment. + assert units.loc["asset_only", "is_snap_eligible"] + assert not units.loc["asset_only", "meets_snap_asset_test"] + assert units.loc["income_failing", "is_snap_eligible"] + assert not units.loc["income_failing", "meets_snap_gross_income_test"] + assert not units.loc["income_failing", "meets_snap_net_income_test"] + assert units.loc["income_failing", "snap"] == pytest.approx( + 12 * _MINIMUM_MONTHLY_ALLOTMENT + ) + # Texas tests resources, so the same unit is not eligible there. + assert not units.loc["not_eligible", "is_snap_eligible"] + assert units.loc["not_eligible", "snap"] == 0 + # An eligible unit without the take-up flag receives nothing. + assert units.loc["no_take_up", "is_snap_eligible"] + assert units.loc["no_take_up", "snap"] == 0 + # Persons are the members SNAP does not exclude: the unit of three with + # an undocumented adult counts two. + np.testing.assert_array_equal( + np.asarray(simulation.calculate("spm_unit_size", PERIOD)), [2, 2, 2, 3, 2, 2] + ) + np.testing.assert_array_equal(units["snap_unit_size"], [2] * 6) + assert units["snap_unit_size"].dtype.kind == "i" + np.testing.assert_array_equal(units["spm_unit_state_fips"], [6, 6, 53, 6, 48, 29]) + + payload = snap_caseload_composition_holdout_payload(units, period=PERIOD) + national = payload["national"] + assert payload["status"] == "available" + take_up = national["take_up"] + assert take_up["eligible_weighted_units"] == 5 + assert take_up["flagged_weighted_units"] == 4 + assert take_up["receiving_weighted_units"] == 4 + assert take_up["eligible_weighted_persons"] == 10 + assert take_up["receiving_share_of_eligible_persons"] == pytest.approx(0.8) + composition = national["composition"] + assert composition["income_failing"]["weighted_units"] == 1 + assert composition["income_failing"]["average_monthly_benefit"] == pytest.approx( + _MINIMUM_MONTHLY_ALLOTMENT + ) + assert composition["asset_only"]["weighted_units"] == 1 + assert composition["within_federal_limits"]["weighted_units"] == 2 + assert national["caseload_source"]["reported_receipt"]["weighted_units"] == 1 + assert national["caseload_source"]["take_up_fill"]["weighted_units"] == 3 + assert national["benefit_outside_december_eligibility"]["weighted_units"] == 0 + assert [row["state_fips"] for row in payload["states"]] == ["06", "29", "48", "53"] + assert payload["states_at_or_above_saturation_threshold"] == { + "flagged_share_of_eligible_units": ["29", "53"], + "receiving_share_of_eligible_units": ["29", "53"], + "receiving_share_of_eligible_persons": ["29", "53"], + } diff --git a/packages/microcosm-build/tests/engine_workflow/us/test_us_snap_caseload_composition_holdout.py b/packages/microcosm-build/tests/engine_workflow/us/test_us_snap_caseload_composition_holdout.py new file mode 100644 index 0000000000..f67cde495c --- /dev/null +++ b/packages/microcosm-build/tests/engine_workflow/us/test_us_snap_caseload_composition_holdout.py @@ -0,0 +1,130 @@ +"""The SNAP caseload composition holdout through the release scorer (microcosm#647). + +The report takes each SPM unit's state and weight from the engine: the unit's +own ``spm_unit_state_fips`` and the weights on each scored result. This test +writes a release H5 whose first household holds two SPM units of different +sizes and reads the report the release tool writes from it, on the locked +policyengine-us. +""" + +# ruff: noqa: F403, F405 +from test_support.microcosm_build.us_post_export_scoring import * + +# (person, household, tax unit, SPM unit, family, age, wages, weekly hours). +# Household 1, in Texas (48), holds a one-person unit and a three-person unit. +# Household 2, in California (06), is one person far above the income limits. +_PEOPLE = ( + (1, 1, 10, 100, 1000, 70, 0.0, 0.0), + (2, 1, 11, 101, 1001, 35, 12_000.0, 25.0), + (3, 1, 11, 101, 1001, 8, 0.0, 0.0), + (4, 1, 11, 101, 1001, 5, 0.0, 0.0), + (5, 2, 20, 200, 2000, 40, 150_000.0, 40.0), +) +_HOUSEHOLD_WEIGHTS = (1_000.0, 2_000.0) + + +def _write_two_unit_household_h5(builder, directory: Path) -> Path: + from microcosm.frame.adapters.policyengine_us import PolicyEngineUSEngine + + person = pd.DataFrame( + [ + { + "person_id": person_id, + "person_household_id": household_id, + "person_tax_unit_id": tax_unit_id, + "person_spm_unit_id": spm_unit_id, + "person_family_id": family_id, + "person_marital_unit_id": person_id * 10_000, + "age": age, + "employment_income_before_lsr": wages, + "weekly_hours_worked_before_lsr": hours, + } + for ( + person_id, + household_id, + tax_unit_id, + spm_unit_id, + family_id, + age, + wages, + hours, + ) in _PEOPLE + ] + ) + frame = Frame( + { + "person": person, + "household": pd.DataFrame( + { + "household_id": [1, 2], + "state_fips": [48, 6], + "county_fips": ["48201", "06037"], + } + ), + "tax_unit": pd.DataFrame({"tax_unit_id": [10, 11, 20]}), + "spm_unit": pd.DataFrame({"spm_unit_id": [100, 101, 200]}), + "family": pd.DataFrame({"family_id": [1000, 1001, 2000]}), + "marital_unit": pd.DataFrame( + {"marital_unit_id": person["person_marital_unit_id"].to_numpy()} + ), + }, + US_SCHEMA, + {"household": Weights(np.asarray(_HOUSEHOLD_WEIGHTS), WeightKind.CALIBRATED)}, + ) + path = directory / "populace_us_2024.h5" + PolicyEngineUSEngine().write_dataset(frame, path, period=builder.PERIOD) + return path + + +def test_each_unit_of_a_shared_household_carries_its_state_and_weight( + builder, tmp_path +) -> None: + """Both Texas units read Texas at the household's weight (microcosm#647). + + policyengine-core maps a household value to SPM units by sharing it out by + head count: asked for ``state_fips`` or ``household_weight`` that way, it + gives the one-person unit a quarter of the Texas household's value and the + three-person unit three quarters, so codes 12 and 36 and weights 250 and + 750. The report would then show no Texas row, 1,000 eligible units and + 2,500 eligible persons. It asks for the unit's own state and reads the + weights on the result instead, which this test pins on the locked engine. + """ + path = _write_two_unit_household_h5(builder, tmp_path) + scorer = builder._HouseholdBatchedPostExportScorer( + path, maximum_microsim_batch_size=1 + ) + try: + plan = builder._record_post_export_baseline_plan( + builder._snap_caseload_composition_holdout_consumer + ) + simulation = scorer.open_consumer( + "snap_caseload_composition_holdout", plan + ).simulate(None) + state = simulation.calculate("spm_unit_state_fips", builder.PERIOD) + size = simulation.calculate("snap_unit_size", builder.PERIOD) + np.testing.assert_array_equal(np.asarray(state), [48, 48, 6]) + np.testing.assert_array_equal(np.asarray(size), [1, 3, 1]) + for result in (state, size): + np.testing.assert_array_equal(result.weights, [1_000, 1_000, 2_000]) + finally: + scorer.close() + + builder._write_snap_caseload_composition_holdout( + release_dir=tmp_path, + dataset_path=path, + release_id="fixture", + maximum_microsim_batch_size=1, + ) + payload = json.loads( + (tmp_path / "us_snap_caseload_composition_holdout.json").read_text() + ) + + assert payload["status"] == "available", payload.get("error") + states = {row["state_fips"]: row for row in payload["states"]} + assert list(states) == ["06", "48"] + texas = states["48"]["take_up"] + assert texas["eligible_records"] == 2 + assert texas["eligible_weighted_units"] == 2_000 + assert texas["eligible_weighted_persons"] == 4_000 + assert states["06"]["take_up"]["eligible_weighted_units"] == 0 + assert payload["national"]["take_up"]["eligible_weighted_units"] == 2_000 diff --git a/test_support/microcosm_build/us_post_export_scoring.py b/test_support/microcosm_build/us_post_export_scoring.py index ae4f7bbbee..ccce0d478b 100644 --- a/test_support/microcosm_build/us_post_export_scoring.py +++ b/test_support/microcosm_build/us_post_export_scoring.py @@ -227,7 +227,21 @@ def sum(self) -> float: "income_adjusted_part_d_premium_surcharge", } ) -_SPM_UNIT_VARIABLES = frozenset({"snap", "housing_assistance", "spm_unit_benefits"}) +_SPM_UNIT_VARIABLES = frozenset( + { + "snap", + "housing_assistance", + "spm_unit_benefits", + "is_snap_eligible", + "meets_snap_gross_income_test", + "meets_snap_net_income_test", + "meets_snap_asset_test", + "snap_assets", + "takes_up_snap_if_eligible", + "receives_snap", + "snap_unit_size", + } +) def _native_entity(variable: str) -> str: @@ -292,6 +306,56 @@ def _medicare_holdout_fixture_values(person: pd.DataFrame, variable: str): return np.where(enrolled, 156.0 * tier, 0.0) +_SNAP_HOLDOUT_FIXTURE_VARIABLES = frozenset( + { + "is_snap_eligible", + "meets_snap_gross_income_test", + "meets_snap_net_income_test", + "meets_snap_asset_test", + "snap_assets", + "takes_up_snap_if_eligible", + "receives_snap", + "snap_unit_size", + "spm_unit_state_fips", + } +) + + +def _snap_holdout_fixture_values(frame: Frame, variable: str): + """Fixture SNAP semantics spread over several households and states. + + Not the law: each rule keys on the household number ``h`` of the unit + (``spm_unit_id // 100``), so every composition group and several states + hold weight. The unit is eligible unless ``h`` is a multiple of four, + fails the gross income test when ``h`` is a multiple of three and the net + test when ``h`` is five, passes the resource test when ``h`` is odd, + carries the take-up flag unless ``h`` is seven and reports receipt when + ``h`` is at most two. Size and state come from the frame. The annual + ``snap`` keeps the fake engine's generic positive value. + """ + unit_ids = frame.table("spm_unit")["spm_unit_id"].to_numpy() + household = unit_ids // 100 + if variable == "is_snap_eligible": + return household % 4 != 0 + if variable == "meets_snap_gross_income_test": + return household % 3 != 0 + if variable == "meets_snap_net_income_test": + return household != 5 + if variable == "meets_snap_asset_test": + return household % 2 == 1 + if variable == "snap_assets": + return 1_000.0 * household + if variable == "takes_up_snap_if_eligible": + return household != 7 + if variable == "receives_snap": + return household <= 2 + if variable == "snap_unit_size": + sizes = frame.table("person").groupby("person_spm_unit_id").size() + return sizes.reindex(unit_ids).to_numpy() + state_fips = frame.table("household")["state_fips"].to_numpy() + return state_fips[_household_positions(frame, "spm_unit")].astype(np.float64) + + def _native_values(frame: Frame, variable: str, period: int, delta: float): person = frame.table("person") state_fips = frame.table("household")["state_fips"].to_numpy() @@ -310,6 +374,8 @@ def _native_values(frame: Frame, variable: str, period: int, delta: float): return person["person_id"].to_numpy() % 3 == 0 if variable in _MEDICARE_HOLDOUT_FIXTURE_VARIABLES: return _medicare_holdout_fixture_values(person, variable) + if variable in _SNAP_HOLDOUT_FIXTURE_VARIABLES: + return _snap_holdout_fixture_values(frame, variable) entity = _native_entity(variable) ids = frame.table(entity)[f"{entity}_id"].to_numpy() base = zlib.crc32(f"{variable}@{period}".encode()) % 89 diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index 85705e3032..15b2d29770 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -409,6 +409,11 @@ project_ecps_parity_known_gap_names, us_release_input_coverage_signal_counts, ) +from microcosm.build.us_runtime.snap_caseload_composition_holdout import ( + snap_caseload_composition_holdout_from_sim, + snap_caseload_composition_holdout_unavailable, + write_snap_caseload_composition_holdout, +) from microcosm.build.us_runtime.ssi_social_security_holdout import ( ssi_social_security_holdout_from_sim, ssi_social_security_holdout_unavailable, @@ -5801,6 +5806,15 @@ def _medicare_irmaa_holdout_consumer(simulate) -> dict[str, Any]: return medicare_irmaa_holdout_unavailable(error, period=PERIOD) +def _snap_caseload_composition_holdout_consumer(simulate) -> dict[str, Any]: + try: + return snap_caseload_composition_holdout_from_sim(simulate(None), period=PERIOD) + except Exception as error: + # As for the SSI holdout: an optional diagnostic adds no failure to + # plan discovery when its inputs are unavailable (microcosm#647). + return snap_caseload_composition_holdout_unavailable(error, period=PERIOD) + + def _reform_validation_consumer( *, result, release_id: str ) -> Callable[[Callable[[Any], Any] | None], dict[str, Any]]: @@ -5839,6 +5853,9 @@ def _post_export_consumers( consumers["demographics"] = _demographics_consumer consumers["ssi_social_security_holdout"] = _ssi_social_security_holdout_consumer consumers["medicare_irmaa_holdout"] = _medicare_irmaa_holdout_consumer + consumers["snap_caseload_composition_holdout"] = ( + _snap_caseload_composition_holdout_consumer + ) return consumers @@ -11656,6 +11673,37 @@ def _write_medicare_irmaa_holdout( ) +def _write_snap_caseload_composition_holdout( + *, + release_dir: Path, + dataset_path: Path, + release_id: str, + post_export_scorer: _HouseholdBatchedPostExportScorer | None = None, + baseline_plan: Sequence[PostExportKey] | None = None, + maximum_microsim_batch_size: int | None = DEFAULT_MAXIMUM_MICROSIM_BATCH_SIZE, +) -> None: + """Report held-out SNAP composition and take-up; never refuses a release.""" + try: + payload = _score_post_export_consumer( + "snap_caseload_composition_holdout", + _snap_caseload_composition_holdout_consumer, + dataset_path=dataset_path, + post_export_scorer=post_export_scorer, + baseline_plan=baseline_plan, + maximum_microsim_batch_size=maximum_microsim_batch_size, + ) + payload["release_id"] = release_id + except Exception as error: + # Reporting is observational, including an unavailable measurement. + # It must not introduce a new release refusal or calibration target. + payload = snap_caseload_composition_holdout_unavailable( + error, period=PERIOD, release_id=release_id + ) + write_snap_caseload_composition_holdout( + payload, release_dir / "us_snap_caseload_composition_holdout.json" + ) + + def _write_population_structure_holdout( *, release_dir: Path, dataset_path: Path, release_id: str ) -> None: @@ -12340,6 +12388,20 @@ def _build_manifests( if (release_dir / "us_medicare_irmaa_holdout.json").exists() else {} ), + **( + { + "us_snap_caseload_composition_holdout": _artifact_entry( + "us_snap_caseload_composition_holdout.json", + _sha256( + release_dir / "us_snap_caseload_composition_holdout.json" + ), + kind="diagnostics", + revision=release_id, + ) + } + if (release_dir / "us_snap_caseload_composition_holdout.json").exists() + else {} + ), **( { "us_population_structure_holdout": _artifact_entry( @@ -14555,6 +14617,7 @@ def _read_us_build_record(path: Path) -> _USBuildRecord: "demographics.json", "us_ssi_social_security_holdout.json", "us_medicare_irmaa_holdout.json", + "us_snap_caseload_composition_holdout.json", "us_population_structure_holdout.json", "us_source_coverage.json", "us_take_up_participation.json", @@ -19947,6 +20010,24 @@ def _certify_us_build( "us_medicare_irmaa_holdout", release_dir / "us_medicare_irmaa_holdout.json", ) + telemetry.stage( + "snap_caseload_composition_holdout", + message="Writing held-out SNAP caseload composition and take-up.", + ) + _write_snap_caseload_composition_holdout( + release_dir=release_dir, + dataset_path=dataset_path, + release_id=release_id, + post_export_scorer=post_export_scorer, + baseline_plan=post_export_scoring_plan.baseline_plan( + "snap_caseload_composition_holdout" + ), + ) + if telemetry is not None: + telemetry.attach_artifact( + "us_snap_caseload_composition_holdout", + release_dir / "us_snap_caseload_composition_holdout.json", + ) # Every post-export engine stage has run; free the scorer's batch frames. # The manifest must pin the bytes those stages scored, and both manifests # carry how they were scored (Route A remediation PR-3).