diff --git a/changelog.d/1720-acs-local-aca-take-up.fixed.md b/changelog.d/1720-acs-local-aca-take-up.fixed.md new file mode 100644 index 0000000000..7e0ca9c081 --- /dev/null +++ b/changelog.d/1720-acs-local-aca-take-up.fixed.md @@ -0,0 +1 @@ +Assign ACA take-up and the Marketplace plan ratio on the ACS tax units of the ACS local-area release instead of shipping the engine defaults, universal take-up of the premium tax credit at the benchmark plan (#1720). Materialize runs one more household-batched engine pre-pass, over the donor households and then the ACS households, after the SSI and Medicaid assignment, and runs the fiscal lane's own `aca_marketplace_inputs` manifest stage on the ACS tax units against what the donor rows leave of each state count: CMS APTC recipients and the IRS SOI premium tax credit returns and amounts, the last two being the 102 state PTC rows of R2's default surface. Where both SOI tables exist the stage's joint step decides the takers, as on the donor; the CMS people are reported (#168). The stage reads the manifest's own anchor column (`reported_has_subsidized_marketplace_health_coverage_at_interview`), which staging writes on ACS persons from the PUMS subsidy item `HIMRKS`. Where a state's anchors weigh more than its residual return count, each stays anchored with probability residual / anchored weight on its own keyed draw: the Medicaid stage's `HINS4` rule, now one shared helper (`microcosm.build.anchor_thinning`) that both stages call, the Medicaid stage's draws unchanged. Without a bronze count the plan ratio is the clipped (premium + credit) / SLCSP of each taker. The feed is compiled once for the SSI, Medicaid and ACA counts. The assignment is recorded in the checkpoint (`acs_local_aca_take_up.npz`), calibrate requires it and the consumer export must reproduce its digest. Both columns join `NEVER_DEFAULT_FILLED` and the pre-check's stage-filled list, and leave the reviewed-fill register; the SSI and Medicaid pre-pass, which runs first, reads them at the engine defaults. The new `acs_local_aca_take_up_signal` grade is report-only: it is recorded in `run_identity.json` and as the diagnostic shadow entry `us_local_aca_take_up_materialize`, and never stops a stage. diff --git a/changelog.d/1720-acs-local-coverage-anchors.fixed.md b/changelog.d/1720-acs-local-coverage-anchors.fixed.md new file mode 100644 index 0000000000..fbc2322620 --- /dev/null +++ b/changelog.d/1720-acs-local-coverage-anchors.fixed.md @@ -0,0 +1,7 @@ +The ACS local lane's staging writes ACS rows' employer coverage and direct-purchase coverage from the ACS items instead of the shared transfer's draws (microcosm#1720, A6; `acs_local_coverage_anchors`, `build_optional_acs_multispine(coverage_anchors=True)`). + +- The loader reads four more optional person items: HINS1 (insurance through a current or former employer or union), HINS2 (insurance purchased directly from an insurance company), HIMRKS (Subsidized Marketplace Coverage: 0 categorically ineligible for a subsidy, 1 direct purchase with a premium subsidy, 2 direct purchase without one) and its allocation flag FHIMRKSP. HIMRKS and FHIMRKSP stay on the staged ACS person rows as raw source items, under the names `ACS_HIMRKS` and `ACS_FHIMRKSP` (as `ACS_MIL`). +- `has_esi` is HINS1 == 1, the counterpart of the donor's ASEC `NOW_GRP`. `has_esi` bars the premium tax credit, CHIP and the self-employed health insurance deduction, so those pools are now measured on ACS rows. +- The two direct-purchase flags follow HINS2. Where it is 2, both are False, whatever HIMRKS says (such conflicts are counted). Where it is 1, HIMRKS code 1 sets the Marketplace flag True and keeps the drawn non-Marketplace flag (ruled 25 Nov 2026); under codes 0 and 2 and a blank, the transfer's draws stand unless both are False, and then one draw, keyed on SERIALNO and SPORDER, picks the type at the donor ASEC role's shares among direct purchasers by age band (under 65, 65 and over). Code 2 cannot tell Marketplace coverage at full price from other direct purchase, and code 0's universe is not documented, so no rule reads either. The choice among direct purchasers is one function, `choose_acs_direct_purchase_types`. +- The step runs on the ACS-only frame after every transfer, so the shared plan, its chain and every other draw are unchanged (a test proves it), and before the self-employed premium attribution, which now reads the native `has_esi`. Its receipt (`acs_local_coverage_anchors` in the staging summary) records the agreement of each native value with the draw it replaces, the donor's type shares, the HIMRKS codes among HINS2 = 1 rows (row counts and weighted shares), the allocated count, the agreement of code 1 with the drawn Marketplace flag, and the HINS2 = 2 conflicts; it grades nothing. No register entry changes: the three columns had none. +- The step also writes the ACA manifest stage's own anchor column, `reported_has_subsidized_marketplace_health_coverage_at_interview` (its name is read from the manifest's `reported_true_anchor`), on ACS rows: True where HINS2 == 1 and HIMRKS == 1, Census-allocated values included; False on every other ACS row (ruled 25 Nov 2026, "Yes, with thinning"; the release's ACA stage does the thinning). Donor rows get no value: the donor reads no subsidized-coverage item (`NOW_MRKS` is unread). After pooling, in the staging H5 and in the release's load, the column is present with donor rows missing (never False); the release's ACA stage reads it on ACS persons only, a missing value as False. It is a source column, not an engine input, so the input-null audit, the reviewed-null register, its pre-check and the release's reviewed-null fill do not read it, and it is not a transfer target, so no draw moves. The receipt's `aca_anchor` gives the anchored rows and their weighted share, the allocated anchored rows and their weighted share of the anchor, and the conflicts (HIMRKS 1 with HINS2 2, rows and weighted share; with HINS2 blank, rows). It thins, draws and grades nothing. diff --git a/changelog.d/1720-acs-local-se-health-premiums.fixed.md b/changelog.d/1720-acs-local-se-health-premiums.fixed.md new file mode 100644 index 0000000000..21b569ddc4 --- /dev/null +++ b/changelog.d/1720-acs-local-se-health-premiums.fixed.md @@ -0,0 +1,6 @@ +The ACS local lane's staging runs the donor's self-employed premium attribution (`attribute_us_se_health_premiums`, unchanged) on ACS rows, so they carry `is_self_employed` and `health_insurance_premiums` instead of the engine defaults, `False` and 0, under which no ACS person got the self-employed health insurance deduction (microcosm#1720; `acs_local_se_health_premiums`, `build_optional_acs_multispine(se_health_premiums=True)`). + +- The flag is the donor's rule, positive Schedule C income (native SEMP plus the transferred SSTB leaf), not ACS COW 6 or 7; the premium is the transferred non-Part-B premium of a flagged person under 65 with no Social Security disability and no employer coverage. SEMP's blank under 15 reads as 0, the reviewed fill's value. +- The stage runs on the ACS-only frame after the shared transfer, whose post-transfer structure settles the self-employment components it reads, and before pooling. It fills only missing cells. Its receipt (`acs_local_se_health_premiums` in the staging summary) records the rule, the flagged rows, the attributed premiums, the premiums the Medicare proxy and employer coverage withheld, and the flag's agreement with COW 6 or 7; it grades nothing. +- The ACS rows' MAGI is then final before the release tool assigns Medicaid take-up; the national build applies the attribution in another order (microcosm#1689). +- The two columns leave the reviewed-fill register and join the release tool's `NEVER_DEFAULT_FILLED`. diff --git a/changelog.d/1720-acs-local-status-inputs.fixed.md b/changelog.d/1720-acs-local-status-inputs.fixed.md new file mode 100644 index 0000000000..87799e92d8 --- /dev/null +++ b/changelog.d/1720-acs-local-status-inputs.fixed.md @@ -0,0 +1,7 @@ +The ACS local lane's staging maps seven person inputs on ACS rows from ACS items instead of leaving the engine default, `False` (microcosm#1720; `acs_local_status_inputs`, `build_optional_acs_multispine(status_inputs=True)`). + +- `is_separated` and `is_surviving_spouse` follow the donor's `relationship_inputs` rule on the ACS rows' `A_MARITL`, which the loader maps from MAR (MAR 4 is code 6, MAR 2 is code 4). The rule is now one shared function, `us_marital_status_inputs`, which the donor stage calls too; donor values are unchanged. +- `is_military` is ACS MIL == 1 (now on active duty); MIL is blank under 17, which reads as False. The donor's rule is a military occupation (`POCCU2` 52); the receipt records how often the two rules, and ESR 4 or 5, agree on ACS rows. +- `has_never_worked`, `is_computer_scientist`, `is_farmer_fisher` and `is_executive_administrative_professional` follow the donor's `org_wages` rule (now the shared `us_flsa_occupation_flags`) on the ACS rows' native `detailed_occupation_recode`. +- The stage runs on the ACS-only frame before any transfer and fills only missing cells. Its receipt (`acs_local_status_inputs` in the staging summary) records each rule, its source columns, the filled and true rows and the weighted shares; it grades nothing. +- The seven columns leave the reviewed-fill register and join the release tool's `NEVER_DEFAULT_FILLED`: a null there now means a staging run from before this change. diff --git a/changelog.d/1720-acs-local-voluntary-filing.fixed.md b/changelog.d/1720-acs-local-voluntary-filing.fixed.md new file mode 100644 index 0000000000..964bd622c3 --- /dev/null +++ b/changelog.d/1720-acs-local-voluntary-filing.fixed.md @@ -0,0 +1,7 @@ +The ACS local lane's staging runs the donor release's SIPP voluntary-filing model on ACS tax units, so they carry `would_file_taxes_voluntarily` instead of the engine default, `False`, under which no ACS unit was a voluntary filer and Medicaid's non-filer rules applied to more of them (microcosm#1720; `acs_local_voluntary_filing`). + +- The model is the donor's own (`voluntary_filing`): the weighted QRF on the pinned full SIPP 2023 file's December filing answers, its five predictors and forest size, and the build seed. It runs through a new table-level entry point, `impute_us_voluntary_filing_from_tables`, which `impute_us_voluntary_filing` now calls too; donor values are unchanged. +- The predictors come from a view of the ACS tax units: tax-unit wages (native WAGP; the blank under 15 reads as no wages), the head's age and sex, `JOINT` filing status and the household's persons under 18. +- Staging reads the SIPP file it already resolves for the SSI disability model, so nothing is downloaded twice; the loader checks the file's length and sha-256 again. +- The stage runs on the pooled frame after the SSI disability stage and before the input-null audit, and fills only missing ACS cells. Its receipt (`acs_local_voluntary_filing` in the staging summary) records the SIPP identity, the fill counts and the ACS and donor weighted true shares; it grades nothing. +- The column leaves the reviewed-fill register, with its EITC and PTC notes, and joins the release tool's `NEVER_DEFAULT_FILLED`. diff --git a/changelog.d/1720-acs-local-weeks-deferrals.fixed.md b/changelog.d/1720-acs-local-weeks-deferrals.fixed.md new file mode 100644 index 0000000000..54c663af2e --- /dev/null +++ b/changelog.d/1720-acs-local-weeks-deferrals.fixed.md @@ -0,0 +1,7 @@ +The ACS local lane's staging draws `weeks_unemployed` and three retirement deferrals (`traditional_401k_contributions_desired`, `roth_401k_contributions_desired`, `roth_ira_contributions_desired`) on ACS rows instead of leaving the engine default, 0 (microcosm#1720; `acs_local_weeks_deferrals`, `build_optional_acs_multispine(weeks_deferrals=True)`). + +- A separate, local-lane-only QRF pass on the donor's ASEC observation role (measured ASEC `LKWEEKS`, and the measured `RETCB_VAL` split by the archived shares), the pattern of the local income pass. The shared declared transfer plan is unchanged; the pass refuses any column the shared plan or the income pass draws (the shared plan keeps `traditional_ira_contributions_desired` and `self_employed_pension_contributions_desired`). +- It runs after the shared transfer, so the weeks family can read the transferred `unemployment_compensation`, through one predictor extension of this call alone. Every earlier fit draws before it and each family seeds from its own name; a test proves that every other column, the earlier provenance and the earlier fits are unchanged with and without the pass. +- The donor's own post-processing, now shared functions its PUF-half stages call too: weeks are clipped to 0-52, rounded and 0 without UC (`postprocess_us_weeks_unemployed_predictions`); deferrals are clipped at 0 and the 401(k) deferrals 0 without wages (`postprocess_us_retirement_contribution_predictions`). Donor values are unchanged. +- Its receipt (`acs_local_weeks_deferrals` in the staging summary) records the donor's ASEC coverage, the predictors, the fill and post-processing counts and the ACS shares; it grades nothing. The four columns leave the reviewed-fill register and join the release tool's `NEVER_DEFAULT_FILLED`. +- Deferrals lower AGI on ACS rows. The pooled file already starts below the AGI targets, so the starting fit can move away from them while the records get closer to the donor's. diff --git a/changelog.d/975-acs-local-group-quarters-housing-take-up.fixed.md b/changelog.d/975-acs-local-group-quarters-housing-take-up.fixed.md new file mode 100644 index 0000000000..482935a80c --- /dev/null +++ b/changelog.d/975-acs-local-group-quarters-housing-take-up.fixed.md @@ -0,0 +1,5 @@ +The ACS local lane's staging sets `takes_up_housing_assistance_if_eligible` False on every ACS SPM unit in group quarters (household TYPEHUGQ 2 or 3), which has no housing unit; the shared transfer had drawn the flag for them from housing-unit donors (microcosm#975, microcosm#1720; `acs_local_group_quarters_housing`, `build_optional_acs_multispine(group_quarters_housing=True)`). + +- A lane-own step on the ACS-only frame after the shared transfer and before pooling, the place of the native receipt anchors. It differs from microcosm#975's proposed design, a structural policy inside the shared transfer, which would move the shared execution contract, the attested `imputation.yaml` entry and the pool lane's pins; the shared plan is unchanged, so housing-unit SPM units keep their draw. +- Its receipt (`acs_local_group_quarters_housing` in the staging summary) counts the group-quarters units by TYPEHUGQ and how many it turned from True to False. It refuses nothing beyond a frame without the columns it reads; an SPM unit without TYPEHUGQ 1, 2 or 3 keeps its draw and is counted. +- The `spm_unit_tenure_type` register entry stays (the RENTER fill stays). Its housing-assistance note is now harmless: the engine pays `hud_hap` times the take-up flag, which is False there. The release tool's and the take-up module's texts that called the flag the open transfer-side fix now describe the step. diff --git a/docs/us-county-files-final-build.md b/docs/us-county-files-final-build.md index 5bf48d09d1..4b067d6206 100644 --- a/docs/us-county-files-final-build.md +++ b/docs/us-county-files-final-build.md @@ -167,6 +167,13 @@ clean && $R2 --stage package $C --out "$RUN/release" minutes. It then computes each household's AGI (minutes) and runs minimum support, SOI support included (`county_support.json`). The engine pass takes about 3 hours. +- Before the AGI, after the SSI and Medicaid take-up, materialize draws the + ACS tax units' ACA take-up and plan ratio after one more engine pre-pass + (time not measured yet) and writes `acs_local_aca_take_up.npz` to the + checkpoint (microcosm#1720). Reported subsidized coverage (HIMRKS) + anchors take-up, thinned by a keyed draw where a state's anchors exceed + its remaining SOI return count. Its grade in `run_identity.json` is + report-only: it never stops the run. - If the register or the donor's lineage entry is not in the checkout yet, commit it after materialize and before calibrate (section 3). The `clean` check before calibrate then holds, and calibrate refuses a donor without diff --git a/docs/us-esi-employer-premiums.md b/docs/us-esi-employer-premiums.md index 8656d1c8e6..6317f09531 100644 --- a/docs/us-esi-employer-premiums.md +++ b/docs/us-esi-employer-premiums.md @@ -637,7 +637,13 @@ file. self-employment income, Social Security, retirement and investment income, household head and tenure where both sources observe them. It does not use ACS's own employer-coverage (`HINS1`), class-of-worker (`COW`) or - employment-status (`ESR`) items. + employment-status (`ESR`) items. Staging does load `HINS1` and writes + `has_esi` from it on ACS rows (microcosm#1720, + `acs_local_coverage_anchors`), but only after every transfer, so the + premium is still drawn without it: an ACS person can carry a premium + without `has_esi`, or `has_esi` without a premium, as with the drawn flag + before. Conditioning the premium on `HINS1` would change the premium pass's + draws. - **A second verdict on the transferred rows' cells.** The gates recompute the MEPS-IC assignment on the rows that carry the raw coverage columns. They compare the transferred rows with those rows and cannot check them against diff --git a/packages/microcosm-build/src/microcosm/build/anchor_thinning.py b/packages/microcosm-build/src/microcosm/build/anchor_thinning.py new file mode 100644 index 0000000000..1caa3e1c33 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/anchor_thinning.py @@ -0,0 +1,149 @@ +"""Keyed thinning of reported take-up anchors to a residual count. + +A take-up stage that preserves reported recipients as anchors can meet a +group, such as a state, where the anchors alone weigh more than the count +left for that group. Thinning holds the anchors to that count in +expectation: every anchor of such a group stays an anchor with one +probability, (residual - fixed mass) / anchored mass, clipped to [0, 1], on +its own keyed uniform. A record's result depends only on the seed, the +stream and its own key, never on the row order. Fixed rows, such as a stored +take-up ``True``, count toward the residual and are never thinned. + +The caller chooses the groups, the mass each row counts toward the residual, +the rows whose mass counts, the fixed rows, the anchors and the stream, so +the rule holds no country's choices. The ACS local lane thins its Medicaid +``HINS4`` anchors (microcosm#1060) and its ACA subsidized-coverage anchors +(microcosm#1720) with it. +""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from dataclasses import dataclass + +import numpy as np +import pandas as pd + +from microcosm.build.stochastic_assignment import stable_identity_uniforms + +__all__ = ["AnchorThinning", "anchor_keep_uniforms", "thin_anchors_to_residuals"] + + +@dataclass(frozen=True) +class AnchorThinning: + """The kept anchors and, per group, the terms of the thinning. + + ``kept`` is aligned with the rows and is ``True`` only on kept anchors. + ``keep_probability`` has one entry per residual group. ``fixed_mass`` and + ``anchor_mass`` hold the counted mass of the fixed rows and of the + anchors in every group the rows carry. + """ + + kept: np.ndarray + keep_probability: dict[str, float] + fixed_mass: dict[str, float] + anchor_mass: dict[str, float] + + @property + def thinned_groups(self) -> list[str]: + """The residual groups whose anchors are kept with probability < 1.""" + + return sorted( + group for group, value in self.keep_probability.items() if value < 1.0 + ) + + +def _group_sums( + groups: np.ndarray, weights: np.ndarray, selected: np.ndarray +) -> dict[str, float]: + """The weight of the selected rows in each group (every group listed).""" + + table = pd.DataFrame({"group": groups, "weight": np.where(selected, weights, 0.0)}) + sums = table.groupby("group", sort=True)["weight"].sum() + return {str(group): float(value) for group, value in sums.items()} + + +def anchor_keep_uniforms( + keys: Sequence[object] | np.ndarray, *, seed: int, stream: str +) -> np.ndarray: + """One seeded blake2b uniform per record key on the keep draw's stream.""" + + return stable_identity_uniforms( + [str(key) for key in keys], seed=int(seed), salt=stream + ) + + +def thin_anchors_to_residuals( + *, + groups: Sequence[object] | np.ndarray, + weights: Sequence[float] | np.ndarray, + counted: Sequence[bool] | np.ndarray, + fixed: Sequence[bool] | np.ndarray, + anchors: Sequence[bool] | np.ndarray, + residuals: Mapping[str, float], + keys: Sequence[object] | np.ndarray, + seed: int, + stream: str, +) -> AnchorThinning: + """Keep each group's anchors with the probability that meets its residual. + + Args: + groups: Each row's group, compared as text with the keys of + ``residuals``. + weights: Each row's mass toward its group's residual. + counted: The rows whose mass counts: those the residual's own + measure can select, such as the eligible ones. + fixed: Rows that take up already and are never thinned. + anchors: Rows that may be thinned. + residuals: The count left to fill in each group. + keys: Each row's record key for the keep draw. + seed: The build seed. + stream: The keep draw's own stream, apart from any take-up draw. + + Returns: + The kept anchors and the terms of the thinning. In a group whose + counted fixed and anchored mass fit its residual, or that has no + residual, every anchor is kept. In any other group each anchor, + counted or not, is kept where its keyed uniform is below + (residual - fixed mass) / anchored mass, clipped to [0, 1]. + + Raises: + ValueError: If the row arrays are not aligned and one-dimensional. + """ + + labels = np.asarray(groups).astype(str) + weights = np.asarray(weights, dtype=np.float64) + counted = np.asarray(counted, dtype=bool) + fixed = np.asarray(fixed, dtype=bool) + anchors = np.asarray(anchors, dtype=bool) + keys = np.asarray(keys, dtype=object) + if labels.ndim != 1 or any( + array.shape != labels.shape + for array in (weights, counted, fixed, anchors, keys) + ): + raise ValueError( + "Anchor thinning needs aligned one-dimensional groups, weights, " + "counted, fixed, anchor and key arrays." + ) + fixed_mass = _group_sums(labels, weights, counted & fixed) + anchor_mass = _group_sums(labels, weights, counted & anchors) + keep: dict[str, float] = {} + for group, target in residuals.items(): + stored = fixed_mass.get(str(group), 0.0) + anchored = anchor_mass.get(str(group), 0.0) + keep[str(group)] = ( + 1.0 + if anchored <= 0.0 or stored + anchored <= target + else float(np.clip((target - stored) / anchored, 0.0, 1.0)) + ) + probability = pd.Series(labels).map(keep).fillna(1.0).to_numpy(dtype=np.float64) + draws = np.zeros(len(labels), dtype=np.float64) + thinning = anchors & (probability < 1.0) + if thinning.any(): + draws[thinning] = anchor_keep_uniforms(keys[thinning], seed=seed, stream=stream) + return AnchorThinning( + kept=anchors & (draws < probability), + keep_probability=keep, + fixed_mass=fixed_mass, + anchor_mass=anchor_mass, + ) diff --git a/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py b/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py index d29ab26d31..02ac9b13f9 100644 --- a/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py +++ b/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py @@ -416,9 +416,13 @@ # the builder's arms by flag; no draw, RNG rule, QRF target or solve changes. # The in-place QRF leaf array in microcosm.fit.qrf (#1682) moves both again # on top of the engine refresh (#1676): the forests' leaf arrays are - # byte-identical, and no draw changes. - "seed_map": "9be0442207d685d3b99508c4ec4e447d1c83cd4d41d2457480bf306ea0491e37", - "seed_protocol": "a6f203aca42c6749ee435b9f2f0b24aa86fc4104492f30b956bae2b79e698c4e", + # byte-identical, and no draw changes. microcosm#1720 moves both again: + # the ACS local lane's weeks and deferrals pass makes the donor's + # weeks-unemployed and retirement-contribution post-processing two shared + # functions, which the PUF-half stages call with the same clip, rounding + # and zero rules; no draw changes. + "seed_map": "42d91aaa12394fdd21b2f89415b318655500183a4cae2c0b9ebca0bead071792", + "seed_protocol": "4fb12bad8c46fcc2457f4ed933bbd55ec655819ca7afc26c11044df16ea4c964", "source_manifest": "777ba41a83bf75ee00937f694a08208e93dcd7c91c9d096d316affd67d424267", "take_up": "ca44532ca9e93e169e07acfd35d57efbacc1297b07006c4e546e05802efc420c", "tail": "f7f8282d48dbf1e01016cd551f5a0de289911140048d20812c920ace0d092936", diff --git a/packages/microcosm-build/src/microcosm/build/us/gates.json b/packages/microcosm-build/src/microcosm/build/us/gates.json index 9c8260ee29..4a4725a050 100644 --- a/packages/microcosm-build/src/microcosm/build/us/gates.json +++ b/packages/microcosm-build/src/microcosm/build/us/gates.json @@ -2263,6 +2263,19 @@ }, "notes": "US ACS local release (tools/build_us_acs_local_release.py): ACS SSI and Medicaid take-up after materialize assigns them; the verdict is recorded in run_identity.json. Exits at once on failure." }, + { + "id": "us_local_aca_take_up_materialize", + "gate": "stage_health", + "phase": "assembled", + "criticality": "diagnostic", + "parameters": { + "check": "aca_take_up_signal", + "residual_relative_tolerance": 1e-09, + "saturated_relative_tolerance": 1e-06, + "acs_local_aca_returns_relative_tolerance": 0.02 + }, + "notes": "US ACS local release (tools/build_us_acs_local_release.py): ACS ACA take-up and plan ratio after materialize assigns them (microcosm#1720); the verdict is recorded in run_identity.json. Report-only: materialize never stops on it." + }, { "id": "us_local_hours_calibrate", "gate": "stage_health", diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_aca_take_up.py b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_aca_take_up.py new file mode 100644 index 0000000000..66e94b72fb --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_aca_take_up.py @@ -0,0 +1,1517 @@ +"""ACA take-up and plan ratio for the ACS tax units of the ACS local lane. + +The ACS transfer leaves both ACA inputs to the runtime, and the local lane +ran no ACA stage, so every ACS tax unit reached the engine pass with +``takes_up_aca_if_eligible`` and ``selected_marketplace_plan_benchmark_ratio`` +missing, and the reviewed-null fill gave them the engine defaults, ``True`` +and ``1.0`` (microcosm#1720). Every eligible ACS unit then received the full +premium tax credit. In the county proof of concept of 17 November 2026 the +pooled file started at 1.85 times the state SOI return count and 1.42 times +the amount, and the release solve removed the excess through the weights of +eligible ACS units instead of choosing takers among them (the microcosm#170 +mechanism). + +This stage assigns both inputs on ACS tax units with the donor's own method, +the fiscal lane's ``aca_marketplace_inputs`` manifest stage, against what +the donor rows leave of the stage's state counts. It fills only missing ACS +cells; donor values and any stored ACS value are kept. + +- **Engine pre-pass.** Like the fiscal lane, the stage reads, for each tax + unit, the weight of its people eligible for the credit, the credit before + take-up, the benchmark (SLCSP) premium and the reported premium: the + fiscal lane's ACA tax-unit table. The caller supplies it as a callable + over a view of whole households (the builder owns the simulations and + their household batching). The stage calls it on the donor households + first, with their stored flags, then on the ACS households, where a + missing take-up cell reads ``True`` and a missing ratio ``1.0``, the + engine defaults. On policyengine-us 2.145.3 ``aca_ptc`` is gated on + filing, and a unit that takes up a positive credit counts as filing for + it (``files_return_for_aca_ptc``), so with the flag ``True`` it is the + credit before take-up, the value the fiscal lane's stage reads. The pass + runs after the SSI and Medicaid assignment: Medicaid eligibility bars the + credit (``gov.aca.ineligible_coverage``) and reads SSI receipt. +- **Residual targets.** The donor H5's flags were drawn against the full + state counts, and pool assembly then scaled every donor weight by + ``1 - acs_share``. Each ACS target is the residual: the state count minus + the donor rows' contribution, floored at zero. The contribution is summed + as the stage sums the ACS rows: on the weight column of the operation that + reads the table (eligible people for the CMS recipients, households for + the SOI returns, credit times household weight for the SOI amounts), over + the units that operation's variable and domain select, at this frame's + pre-calibration weights. Where the ACS capacity is below a residual the + shortfall is recorded; where the donor rows alone exceed a count the + excess is recorded. +- **The stage** runs on the ACS tax units against the residual tables, + through :func:`~microcosm.build.source_runtime.run_source_stage` with the + US handlers: a draw at the CMS residual rate, a calibration to the CMS + residual counts, then, where both SOI tables exist, a joint calibration + that resets each state and fills its residual SOI return count with the + units whose credit per return is closest to the residual average, the + draw only breaking ties. So where SOI rows exist they decide the + selection, as they do on the donor, and the CMS people the takers carry + are reported (microcosm#168). The + ratio is (premium + credit) / SLCSP for takers, clipped to 0.5-1.5, and + 1.0 otherwise; without a bronze table the stage stops after the clip, as + the fiscal lane does. +- **Anchor.** The anchor is the manifest stage's own column, + ``reported_has_subsidized_marketplace_health_coverage_at_interview``, + which staging writes on the ACS persons from the PUMS item that separates + subsidized Marketplace coverage (``HIMRKS``). The fiscal lane reads it as + False where the column is absent, because observed Marketplace coverage + is broader than subsidized coverage (``_aca_source_person_table``), and + so does this stage. Kept anchors take up (the stage's + ``preserve_true_anchors``). A stored ACS take-up cell (staging writes + none) is kept: a stored ``True`` is an anchor that is never thinned, and + a unit stored ``False`` stays out of the stage. +- **Thinning.** Where a state's anchors weigh more than its residual in the + binding table, each reported anchor there stays anchored with probability + (residual - stored-True mass) / anchored mass, on its own keyed draw: the + Medicaid stage's rule for its ``HINS4`` anchors, in the shared + :func:`~microcosm.build.anchor_thinning.thin_anchors_to_residuals`. The + mass is counted as the binding operation counts it, over its domain, + where the credit is positive. A unit not kept is an ordinary non-anchor, + which the joint step can still select where the kept anchors fall short + of the residual. The draw meets the residual in expectation, so a thinned + state's delivery is reported, not graded against the tolerance. The + receipt records each state's anchored mass, keep probability and thinned + rows, and the kept anchors' excess over every table's residual. +- **Draws** come from seeded blake2b uniforms on the donor stage's stream + (``aca:takes_up_aca_if_eligible``), keyed on + ``acs_2024_1yr:SERIALNO:``, so a unit's draw + depends only on the build seed and its own record. The anchor keep draw + has a stream of its own. + +The receipt records, per table and state, the count, the donor rows' +contribution, the residual, the ACS capacity and delivery, the pooled total +and any shortfall or excess, the people per return of each set of rows, and +a digest of the ACS assignment. :func:`acs_local_aca_take_up_signal_gate` +grades the flags and the receipt. The lane reports that verdict and never +stops on it. +""" + +from __future__ import annotations + +import hashlib +from collections.abc import Callable, Mapping +from dataclasses import dataclass +from typing import Any + +import numpy as np +import pandas as pd + +from microcosm.build.anchor_thinning import thin_anchors_to_residuals +from microcosm.build.gates import GateResult +from microcosm.build.source_runtime import SourceRuntimeConfig, run_source_stage +from microcosm.build.stochastic_assignment import stable_identity_uniforms +from microcosm.build.us_runtime.acs_pums import ACS_2024_1YR_SPINE +from microcosm.build.us_runtime.acs_transfer import ASEC_PUF_DONOR_SPINE +from microcosm.build.us_runtime.base_pool import spine_column +from microcosm.frame import Frame +from microcosm.frame.units import US_SCHEMA + +__all__ = [ + "ACS_LOCAL_ACA_PLAN_RATIO_COLUMN", + "ACS_LOCAL_ACA_RETURNS_RELATIVE_TOLERANCE", + "ACS_LOCAL_ACA_STAGE", + "ACS_LOCAL_ACA_TAKE_UP_COLUMN", + "ACS_LOCAL_ACA_TAKE_UP_COLUMNS", + "ACS_LOCAL_ACA_TAKE_UP_GATE_NAME", + "ACS_LOCAL_ACA_TAKE_UP_ISSUE", + "ACS_LOCAL_ACA_TAKE_UP_METHOD", + "AcaTaxUnitTable", + "acs_local_aca_take_up_assignment", + "acs_local_aca_take_up_signal_gate", + "with_acs_local_aca_take_up", + "with_recorded_acs_local_aca_take_up", +] + +ACS_LOCAL_ACA_TAKE_UP_ISSUE = "microcosm#1720" +ACS_LOCAL_ACA_TAKE_UP_GATE_NAME = "acs_local_aca_take_up_signal" +ACS_LOCAL_ACA_TAKE_UP_METHOD = ( + "donor_aca_marketplace_stage_on_acs_tax_units_at_donor_residual_targets" +) +#: The fiscal lane's ACA manifest stage, run here on the ACS tax units. +ACS_LOCAL_ACA_STAGE = "aca_marketplace_inputs" +ACS_LOCAL_ACA_TAKE_UP_COLUMN = "takes_up_aca_if_eligible" +ACS_LOCAL_ACA_PLAN_RATIO_COLUMN = "selected_marketplace_plan_benchmark_ratio" +#: The tax-unit inputs this stage owns on ACS rows: the manifest stage's +#: declared outputs, in its order. +ACS_LOCAL_ACA_TAKE_UP_COLUMNS: tuple[str, ...] = ( + ACS_LOCAL_ACA_TAKE_UP_COLUMN, + ACS_LOCAL_ACA_PLAN_RATIO_COLUMN, +) +#: Grading only: where the ACS capacity exceeds a state's residual in the +#: binding table, the delivered ACS count should be within this share of the +#: residual (or within one unit's weight, the greedy fill's step). The lane +#: reports the verdict and never stops on it. +ACS_LOCAL_ACA_RETURNS_RELATIVE_TOLERANCE = 0.02 + +_TAKE_UP = ACS_LOCAL_ACA_TAKE_UP_COLUMN +_RATIO = ACS_LOCAL_ACA_PLAN_RATIO_COLUMN +#: The engine defaults a missing cell reads in the ACS pre-pass view. +_TAKE_UP_DEFAULT = True +_RATIO_DEFAULT = 1.0 +_STATE = "state_fips" +_ID = "tax_unit_id" +_PERSON_TAX_UNIT = "person_tax_unit_id" +_SPORDER = "SPORDER" +_SERIALNO = "SERIALNO" +#: The deprecated alias the fiscal lane falls back on for observed coverage. +_COVERAGE_ALIAS = "has_marketplace_health_coverage" +_DRAW_KEY_FORMAT = f"{ACS_2024_1YR_SPINE}:SERIALNO:" +_WEIGHTS_BASIS = "acs_rows_pre_calibration_frame_household_weights" +_TARGET_BASIS = ( + "each state count minus the donor rows' contribution (stored flag and " + "ratio x engine eligibility and credit on the donor households x " + "pre-calibration frame weights, summed on the weight column of the stage " + "operation that reads the table), floored at 0" +) +_ANCHOR_RULE = ( + "the manifest stage's own anchor column on the ACS persons, which " + "staging writes from the PUMS subsidy item HIMRKS, read as the fiscal " + "lane reads it (False where the column is absent: observed Marketplace " + "coverage is broader than subsidized coverage, _aca_source_person_table). " + "A stored ACS take-up True is also an anchor and is never thinned, and " + "a stored False stays out of the stage. Kept anchors take up " + "(preserve_true_anchors); their excess over any residual is recorded" +) +#: The anchor keep draw's own blake2b stream, apart from the take-up draw. +_ANCHOR_KEEP_STREAM = "acs_local_aca_subsidized_anchor_keep" +_THINNING_RULE = ( + "where a state's counted stored-True and reported anchor mass in the " + "binding table exceeds its residual, each reported anchor there stays " + "anchored with probability (residual - stored-True mass) / reported " + "anchor mass, on a keyed draw: the Medicaid stage's HINS4 rule " + "(microcosm.build.anchor_thinning). A unit not kept is an ordinary " + "non-anchor, which the stage can still select" +) +#: The columns of the fiscal lane's ACA tax-unit table the stage reads. +_ENGINE_TABLE_COLUMNS = ( + _ID, + _STATE, + "tax_unit_weight", + "household_weight", + "is_aca_ptc_eligible", + "health_insurance_premiums_without_medicare_part_b", + "assigned_aca_ptc", + "weighted_assigned_aca_ptc", + "slcsp", + "aca_take_up_rate", +) +_ELIGIBLE = "is_aca_ptc_eligible" +_CREDIT = "assigned_aca_ptc" +_HOUSEHOLD_WEIGHT = "household_weight" +#: A receipt's residual must be its count minus the donor contribution; the +#: two are written from the same floats, so only a changed formula differs. +_RESIDUAL_RELATIVE_TOLERANCE = 1e-9 +#: A saturated state assigns every unit in the domain: delivery equals +#: capacity up to floating-point summation order. +_SATURATED_RELATIVE_TOLERANCE = 1e-6 +_STATE_NUMBERS = ("target", "donor", "residual", "acs_capacity", "acs_delivered") + +#: The fiscal lane's ACA tax-unit table over a view of whole households, +#: given the target tables its take-up rate and person weights read. +AcaTaxUnitTable = Callable[[Frame, Mapping[str, pd.DataFrame]], pd.DataFrame] + + +@dataclass(frozen=True) +class _TableRole: + """How the manifest stage counts one target table. + + ``variable`` is the operation's boolean (a column or ``column < x``), + ``domain`` the units it may move, and ``weight`` the tax-unit column the + table's counts are summed on. + """ + + operation: str + variable: str + weight: str + domain: str | None + + +@dataclass(frozen=True) +class _StagePlan: + """What the manifest stage reads, as this stage needs it.""" + + stage: Any + roles: Mapping[str, _TableRole] + draw_column: str + draw_stream: str + aggregates: tuple[str, ...] + anchor: str + late_tables: frozenset[str] + + +def _json_ready(value: Any) -> Any: + if isinstance(value, Mapping): + return {str(key): _json_ready(item) for key, item in value.items()} + if isinstance(value, (list, tuple)): + return [_json_ready(item) for item in value] + if isinstance(value, np.generic): + return value.item() + return value + + +def _finite(value: object) -> float: + try: + return float(value) # type: ignore[arg-type] + except (TypeError, ValueError): + return float("nan") + + +def _stage_plan() -> _StagePlan: + """The manifest stage and what its operations read.""" + + from microcosm.build.us_runtime import ( # local: package init owns the manifest + US_SOURCE_MANIFEST, + ) + + stage = US_SOURCE_MANIFEST.stage_map()[ACS_LOCAL_ACA_STAGE] + if tuple(stage.outputs) != ACS_LOCAL_ACA_TAKE_UP_COLUMNS: + raise ValueError( + f"The {ACS_LOCAL_ACA_STAGE} stage declares outputs " + f"{list(stage.outputs)}, not {list(ACS_LOCAL_ACA_TAKE_UP_COLUMNS)}." + ) + roles: dict[str, _TableRole] = {} + draws: set[str] = set() + aggregates: tuple[str, ...] = () + anchor = "" + stream = "" + late: set[str] = set() + clipped = False + for operation in stage.operations: + params = operation.parameters + if "draw" in params: + draws.add(str(params["draw"])) + if operation.kind == "aggregate_person_to_tax_unit": + aggregates = tuple(str(name) for name in params["aggregates"]) + elif operation.kind == "assign_binary_from_rate": + anchor = str(params["reported_true_anchor"]) + # The handler's own stream when the draw column is absent. + stream = f"aca:{params['output']}" + elif operation.kind == "support_clip": + clipped = True + reads: list[tuple[str, object]] = [] + if operation.kind == "calibrate_binary_assignment": + reads = [(str(name), params["weight"]) for name in params["targets"]] + elif operation.kind == "calibrate_binary_assignment_joint_targets": + reads = [ + (str(name), params["count_weight"]) for name in params["count_targets"] + ] + [ + (str(name), params["amount_weight"]) + for name in params["amount_targets"] + ] + for name, weight in reads: + roles.setdefault( + name, + _TableRole( + operation=operation.kind, + variable=str(params["variable"]), + weight=str(weight), + domain=params.get("domain"), + ), + ) + if clipped: + late.add(name) + if len(draws) != 1 or not anchor or not stream or not aggregates: + raise ValueError( + f"The {ACS_LOCAL_ACA_STAGE} stage no longer reads one draw column, a " + "reported anchor and its person aggregates; review this stage." + ) + return _StagePlan( + stage=stage, + roles=roles, + draw_column=next(iter(draws)), + draw_stream=stream, + aggregates=aggregates, + anchor=anchor, + late_tables=frozenset(late), + ) + + +def _checked_tables( + target_tables: Mapping[str, pd.DataFrame], plan: _StagePlan +) -> dict[str, pd.DataFrame]: + """One finite, nonnegative count per zero-padded state in each table.""" + + unread = sorted(set(target_tables) - set(plan.roles)) + if unread: + raise ValueError( + f"No operation of {ACS_LOCAL_ACA_STAGE} reads target table(s) " + f"{unread}; their residuals cannot be summed." + ) + if not target_tables: + raise ValueError("ACS local ACA take-up requires its state target tables.") + checked: dict[str, pd.DataFrame] = {} + for name, table in target_tables.items(): + missing = [column for column in (_STATE, "target") if column not in table] + if missing: + raise ValueError(f"ACA target table {name} lacks column(s) {missing}.") + states = table[_STATE].astype(str).str.zfill(2) + values = pd.to_numeric(table["target"], errors="coerce").to_numpy( + dtype=np.float64 + ) + if states.duplicated().any(): + raise ValueError( + f"ACA target table {name} repeats state(s) " + f"{sorted(states[states.duplicated()])}." + ) + if not np.isfinite(values).all() or (values < 0).any(): + raise ValueError(f"ACA target table {name} must be finite and >= 0.") + checked[name] = pd.DataFrame({_STATE: states.to_numpy(), "target": values}) + return checked + + +def _boolean_cells(values: pd.Series) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """``(flags, present, invalid)`` of a nullable boolean column.""" + + present = values.notna().to_numpy(dtype=bool) + valid = present & values.isin([0, 1]).to_numpy(dtype=bool) + flags = np.zeros(len(values), dtype=bool) + flags[valid] = values[valid].astype(bool).to_numpy(dtype=bool) + return flags, present, present & ~valid + + +def _ratio_cells(values: pd.Series) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """``(ratios, present, invalid)``; a valid ratio is finite and positive.""" + + numbers = pd.to_numeric(values, errors="coerce").to_numpy(dtype=np.float64) + present = values.notna().to_numpy(dtype=bool) + valid = present & np.isfinite(numbers) & (numbers > 0) + return np.where(valid, numbers, np.nan), present, present & ~valid + + +def _engine_table( + function: AcaTaxUnitTable, + view: Frame, + tables: Mapping[str, pd.DataFrame], + *, + label: str, +) -> pd.DataFrame: + """The callable's table, one row per view tax unit, in the view's order.""" + + raw = function(view, tables) + missing = [column for column in _ENGINE_TABLE_COLUMNS if column not in raw] + if missing: + raise ValueError( + f"The {label} ACA engine pre-pass table lacks column(s) {missing}." + ) + ids = view.table("tax_unit")[_ID].to_numpy() + table = raw.loc[:, list(_ENGINE_TABLE_COLUMNS)].set_index(_ID) + if not table.index.is_unique or len(table) != len(ids): + raise ValueError( + f"The {label} ACA engine pre-pass returned {len(table)} rows for " + f"{len(ids)} tax units, or repeated a tax unit." + ) + table = table.reindex(ids) + numbers = table.drop(columns=[_STATE, _ELIGIBLE]).to_numpy(dtype=np.float64) + if table[_STATE].isna().any() or not np.isfinite(numbers).all(): + raise ValueError( + f"The {label} ACA engine pre-pass does not cover every tax unit with " + "a state and finite values." + ) + table = table.reset_index() + table[_STATE] = table[_STATE].astype(str).str.zfill(2) + table[_ELIGIBLE] = table[_ELIGIBLE].fillna(False).astype(bool) + return table + + +def _selected(table: pd.DataFrame, role: _TableRole, *, label: str) -> np.ndarray: + """The units ``role``'s operation counts, as the stage's handlers read it.""" + + from microcosm.build.us_runtime.source_runtime import ( + _binary_calibration_value_state, + _domain_mask, + ) + + values = _binary_calibration_value_state(table, role.variable, label=label) + domain = _domain_mask(table, role.domain, label=label) + return (values.values(table) & domain).to_numpy(dtype=bool) + + +def _domain(table: pd.DataFrame, role: _TableRole, *, label: str) -> np.ndarray: + from microcosm.build.us_runtime.source_runtime import _domain_mask + + return _domain_mask(table, role.domain, label=label).to_numpy(dtype=bool) + + +def _state_sums( + table: pd.DataFrame, selected: np.ndarray, column: str +) -> dict[str, float]: + weights = pd.to_numeric(table[column], errors="coerce").fillna(0.0) + sums = ( + pd.DataFrame( + {_STATE: table[_STATE].to_numpy(), "w": np.where(selected, weights, 0.0)} + ) + .groupby(_STATE, sort=True)["w"] + .sum() + ) + return {str(state): float(value) for state, value in sums.items()} + + +def _state_counts(states: np.ndarray, selected: np.ndarray) -> dict[str, int]: + """The number of selected rows in each state (every state listed).""" + + counts = ( + pd.Series(np.asarray(selected, dtype=bool)) + .groupby(np.asarray(states).astype(str), sort=True) + .sum() + ) + return {str(state): int(value) for state, value in counts.items()} + + +def _state_max( + table: pd.DataFrame, selected: np.ndarray, column: str +) -> dict[str, float]: + weights = pd.to_numeric(table[column], errors="coerce").fillna(0.0) + frame = pd.DataFrame( + {_STATE: table[_STATE].to_numpy(), "w": np.where(selected, weights, 0.0)} + ) + return { + str(state): float(value) + for state, value in frame.groupby(_STATE, sort=True)["w"].max().items() + } + + +def _with_stored( + table: pd.DataFrame, take_up: np.ndarray, ratio: np.ndarray +) -> pd.DataFrame: + result = table.copy() + result[_TAKE_UP] = np.asarray(take_up, dtype=bool) + result[_RATIO] = np.asarray(ratio, dtype=np.float64) + return result + + +def _acs_draw_keys(frame: Frame, tax_unit_ids: np.ndarray) -> np.ndarray: + """``acs_2024_1yr:SERIALNO:`` per ACS tax unit; unique.""" + + person = frame.table("person") + household = frame.table("household") + # Three columns only: never a second copy of the ACS person rows. + members = person.loc[ + person[_PERSON_TAX_UNIT].isin(tax_unit_ids), + [_PERSON_TAX_UNIT, "person_household_id", _SPORDER], + ] + serial = members["person_household_id"].map( + household.set_index("household_id")[_SERIALNO] + ) + order = pd.to_numeric(members[_SPORDER], errors="coerce") + if serial.isna().any() or order.isna().any(): + raise ValueError( + "Every ACS person needs its household SERIALNO and its SPORDER to key " + "the ACA take-up draws." + ) + units = pd.DataFrame( + { + "unit": members[_PERSON_TAX_UNIT].to_numpy(), + "serial": serial.astype(str).to_numpy(), + "order": order.astype(np.int64).to_numpy(), + } + ) + if (units.groupby("unit")["serial"].nunique() > 1).any(): + raise ValueError("An ACS tax unit spans two ACS households.") + first = units.sort_values(["unit", "order"]).groupby("unit", sort=False).first() + keys = ( + f"{ACS_2024_1YR_SPINE}:" + first["serial"] + ":" + first["order"].astype(str) + ).reindex(tax_unit_ids) + if keys.isna().any(): + raise ValueError("An ACS tax unit has no person to key its ACA draw.") + if keys.duplicated().any(): + raise ValueError( + f"{int(keys.duplicated().sum())} ACS tax unit draw key(s) repeat; " + f"{_DRAW_KEY_FORMAT} must identify one unit." + ) + return keys.to_numpy(dtype=object) + + +def _with_tax_unit(frame: Frame, tax_unit: pd.DataFrame) -> Frame: + return Frame( + { + entity: tax_unit if entity == "tax_unit" else frame.table(entity) + for entity in frame.entities + }, + frame.schema, + {entity: frame.weights_for(entity) for entity in frame.weighted_entities}, + frame.strata, + mass_log=frame.mass_log, + metadata=frame.metadata, + ) + + +def _filled_flags( + values: pd.Series, missing: np.ndarray, assigned: np.ndarray +) -> pd.Series: + if not missing.any(): + return values + filled = values.astype(object) + filled.loc[missing] = assigned[missing] + return filled.astype(bool) if filled.notna().all() else filled + + +def _filled_ratios( + values: pd.Series, missing: np.ndarray, assigned: np.ndarray +) -> pd.Series: + if not missing.any(): + return values + filled = pd.to_numeric(values, errors="coerce").astype(np.float64) + filled.loc[missing] = assigned[missing] + return filled + + +def _assignment_sha256( + tax_unit_ids: np.ndarray, take_up: np.ndarray, ratio: np.ndarray +) -> str: + """Digest of the ACS tax units' two inputs, to prove two passes agree.""" + + table = pd.DataFrame( + { + _ID: np.asarray(tax_unit_ids), + _TAKE_UP: np.asarray(take_up, dtype=bool), + _RATIO: np.asarray(ratio, dtype=np.float64), + } + ) + hashed = pd.util.hash_pandas_object(table, index=False).to_numpy() + return hashlib.sha256(hashed.tobytes()).hexdigest() + + +def _acs_masks(frame: Frame) -> tuple[np.ndarray, np.ndarray]: + """ACS persons and ACS tax units, by their origin tags.""" + + person = frame.table("person") + tax_unit = frame.table("tax_unit") + tags = [spine_column(entity) for entity in ("person", "tax_unit")] + for table, tag in zip((person, tax_unit), tags, strict=True): + if tag not in table or table[tag].isna().any(): + raise ValueError( + f"ACS local ACA take-up requires complete origin tags: {tag}." + ) + return ( + person[tags[0]].eq(ACS_2024_1YR_SPINE).to_numpy(dtype=bool), + tax_unit[tags[1]].eq(ACS_2024_1YR_SPINE).to_numpy(dtype=bool), + ) + + +def _rows( + names: tuple[str, ...], + tables: Mapping[str, pd.DataFrame], + sums: Mapping[str, Mapping[str, Mapping[str, float]]], +) -> dict[str, list[dict[str, Any]]]: + """Per table, one accounting row per target state.""" + + result: dict[str, list[dict[str, Any]]] = {} + for name in names: + rows: list[dict[str, Any]] = [] + table = tables[name] + for state, target in zip(table[_STATE], table["target"], strict=True): + target = float(target) + donor = sums["donor"][name].get(state, 0.0) + residual = max(target - donor, 0.0) + capacity = sums["capacity"][name].get(state, 0.0) + delivered = sums["delivered"][name].get(state, 0.0) + anchored = sums["anchored"][name].get(state, 0.0) + pooled = donor + delivered + rows.append( + { + _STATE: str(state), + "target": target, + "donor": donor, + "donor_share_of_target": donor / target if target > 0 else None, + "residual": residual, + "acs_capacity": capacity, + "acs_delivered": delivered, + "acs_max_unit_weight": sums["max_unit"][name].get(state, 0.0), + # Kept anchors take up even above a residual (the stage's + # preserve_true_anchors): the keep draw meets the binding + # table only in expectation and no other table at all. + # Recorded, not graded. + "acs_anchored": anchored, + "anchor_excess": max(anchored - residual, 0.0), + "pooled": pooled, + "pooled_relative_error": ( + (pooled - target) / target if target > 0 else None + ), + "capacity_shortfall": max(residual - capacity, 0.0), + "donor_excess": max(donor - target, 0.0), + } + ) + result[name] = rows + return result + + +def _composition( + plan: _StagePlan, + tables: Mapping[str, pd.DataFrame], + sums: Mapping[str, Mapping[str, Mapping[str, float]]], +) -> dict[str, Any] | None: + """People per return, for each set of rows (microcosm#168).""" + + people = [ + name + for name, role in plan.roles.items() + if name in tables + and role.operation == "calibrate_binary_assignment" + and role.variable == _TAKE_UP + ] + returns = [ + name + for name, role in plan.roles.items() + if name in tables + and role.operation == "calibrate_binary_assignment_joint_targets" + and role.weight == _HOUSEHOLD_WEIGHT + ] + if not people or not returns: + return None + person_table, return_table = people[0], returns[0] + + def ratio(numerator: float, denominator: float) -> float | None: + return numerator / denominator if denominator > 0 else None + + def total(kind: str, name: str) -> float: + return float(sum(sums[kind][name].values())) + + return { + "people_table": person_table, + "returns_table": return_table, + "target": ratio( + float(tables[person_table]["target"].sum()), + float(tables[return_table]["target"].sum()), + ), + "donor": ratio(total("donor", person_table), total("donor", return_table)), + "acs": ratio( + total("delivered", person_table), total("delivered", return_table) + ), + "pooled": ratio( + total("donor", person_table) + total("delivered", person_table), + total("donor", return_table) + total("delivered", return_table), + ), + } + + +def _binding_table(plan: _StagePlan, tables: Mapping[str, pd.DataFrame]) -> str: + """The count table whose residuals the stage's last take-up step meets.""" + + joint = [ + name + for name, role in plan.roles.items() + if role.operation == "calibrate_binary_assignment_joint_targets" + and role.weight == _HOUSEHOLD_WEIGHT + and name in tables + ] + amounts = [ + name + for name, role in plan.roles.items() + if role.operation == "calibrate_binary_assignment_joint_targets" + and role.weight != _HOUSEHOLD_WEIGHT + and name in tables + ] + if joint and amounts: + return joint[0] + first = [ + name + for name, role in plan.roles.items() + if role.operation == "calibrate_binary_assignment" + and role.variable == _TAKE_UP + and name in tables + ] + if not first: + raise ValueError( + f"No target table the {ACS_LOCAL_ACA_STAGE} stage's take-up " + "calibration reads was given." + ) + return first[0] + + +def with_acs_local_aca_take_up( + frame: Frame, + *, + seed: int, + target_tables: Mapping[str, pd.DataFrame], + aca_tax_units: AcaTaxUnitTable, + period: int = 2024, +) -> tuple[Frame, dict[str, Any]]: + """Fill missing ACS-row ACA take-up and plan ratio; keep every other cell. + + Args: + frame: The local lane's multispine US frame, after the SSI and + Medicaid take-up stage. Its person and tax-unit tables must carry + complete origin tags, its tax-unit table both ACA columns, its + person table ``SPORDER`` and observed Marketplace coverage, and + its household table ``SERIALNO`` and ``state_fips``. ACS persons + must fill whole households. + seed: The build seed for the draws. + target_tables: The fiscal lane's ACA state tables + (``state_fips``, ``target``) by name, as the ACS local release + reads them from its compiled registry. + aca_tax_units: Returns the fiscal lane's ACA tax-unit table for + every tax unit of the view it is given, with the target tables + its rate and person weights read: first the donor households + (their stored flags, the full tables), then the ACS households + (missing cells read ``True`` and ``1.0``, the residual tables). + period: The year the stage runs for. + + Returns: + The frame with filled ACS cells and a JSON-ready receipt, including + each table's and state's donor contribution, residual, delivery, + shortfall and excess, and a digest of the ACS assignment. + + Raises: + ValueError: If the frame is not US-schema, origin tags or a required + column are missing, an ACS household holds a non-ACS person, an + ACS row lacks what its draw key reads, the targets are malformed, + or the callable returns a table that does not cover the view. + """ + + if frame.schema != US_SCHEMA: + raise ValueError("ACS local ACA take-up requires the US schema.") + plan = _stage_plan() + tables = _checked_tables(target_tables, plan) + person = frame.table("person") + tax_unit = frame.table("tax_unit") + household = frame.table("household") + absent = [ + f"tax_unit.{column}" for column in (_TAKE_UP, _RATIO) if column not in tax_unit + ] + absent += [ + f"person.{column}" + for column in (_PERSON_TAX_UNIT, _SPORDER) + if column not in person + ] + absent += [ + f"household.{column}" + for column in (_SERIALNO, _STATE) + if column not in household + ] + if absent: + raise ValueError( + f"ACS local ACA take-up requires column(s) {absent}; a missing " + "take-up column would reach the engine as universal take-up." + ) + acs_persons, acs_units = _acs_masks(frame) + if not acs_units.any(): + raise ValueError("ACS local ACA take-up found no ACS tax units.") + household_ids = person["person_household_id"] + acs_households = pd.unique(household_ids[acs_persons]) + mixed = household_ids.isin(acs_households).to_numpy(dtype=bool) & ~acs_persons + if mixed.any(): + raise ValueError( + f"{int(mixed.sum())} non-ACS person(s) share a household with ACS " + "persons; the engine pre-pass evaluates whole ACS households." + ) + unit_ids = tax_unit[_ID].to_numpy() + acs_ids = unit_ids[acs_units] + member_units = person.loc[acs_persons, _PERSON_TAX_UNIT] + if set(member_units) != set(acs_ids): + raise ValueError( + "The ACS-tagged tax units are not exactly the tax units of the ACS persons." + ) + keys = _acs_draw_keys(frame, acs_ids) + + stored_flags, flag_present, flag_invalid = _boolean_cells(tax_unit[_TAKE_UP]) + stored_ratio, ratio_present, ratio_invalid = _ratio_cells(tax_unit[_RATIO]) + if (flag_invalid & acs_units).any() or (ratio_invalid & acs_units).any(): + raise ValueError( + "Stored ACS ACA cells must be a boolean take-up flag and a finite " + f"positive ratio; {int((flag_invalid & acs_units).sum())} flag and " + f"{int((ratio_invalid & acs_units).sum())} ratio cell(s) are not." + ) + + # The donor rows' contribution sets each ACS residual target. A donor + # cell the release did not store reads its engine default, as the + # engine pass would read it; the receipt counts such cells. + donor_units = ~acs_units + donor_counts = { + "tax_units": int(donor_units.sum()), + "missing_take_up_cells": int((donor_units & ~flag_present).sum()), + "invalid_take_up_cells": int((donor_units & flag_invalid).sum()), + "missing_ratio_cells": int((donor_units & ~ratio_present).sum()), + "invalid_ratio_cells": int((donor_units & ratio_invalid).sum()), + } + sums: dict[str, dict[str, dict[str, float]]] = { + kind: {name: {} for name in tables} + for kind in ("donor", "capacity", "delivered", "max_unit", "anchored") + } + if donor_units.any(): + view = frame.select(~acs_persons) + engine = _engine_table(aca_tax_units, view, tables, label="donor") + del view + donor_ids = engine[_ID].to_numpy() + position = pd.Series(np.arange(len(unit_ids)), index=unit_ids) + at = position.reindex(donor_ids).to_numpy() + donor_flags = np.where( + flag_present[at] & ~flag_invalid[at], stored_flags[at], _TAKE_UP_DEFAULT + ) + donor_ratio = np.where( + ratio_present[at] & ~ratio_invalid[at], stored_ratio[at], _RATIO_DEFAULT + ) + evaluated = _with_stored(engine, donor_flags, donor_ratio) + donor_counts["eligible_tax_units"] = int( + (evaluated[_ELIGIBLE] & (evaluated[_CREDIT] > 0)).sum() + ) + for name in tables: + role = plan.roles[name] + chosen = _selected(evaluated, role, label=f"donor {name}") + sums["donor"][name] = _state_sums(evaluated, chosen, role.weight) + del engine, evaluated + residual_tables = { + name: pd.DataFrame( + { + _STATE: table[_STATE].to_numpy(), + "target": np.maximum( + table["target"].to_numpy(dtype=np.float64) + - np.asarray( + [sums["donor"][name].get(state, 0.0) for state in table[_STATE]] + ), + 0.0, + ), + } + ) + for name, table in tables.items() + } + + # Engine pre-pass over the ACS households only. ``select`` copied every + # table, so the view is this stage's own: its missing cells read the + # engine defaults, as the reviewed fill gave them before this stage. + view = frame.select(acs_persons) + view_units = view.table("tax_unit") + at = pd.Series(np.arange(len(unit_ids)), index=unit_ids).reindex( + view_units[_ID].to_numpy() + ) + at = at.to_numpy() + view_units[_TAKE_UP] = np.where( + flag_present[at], stored_flags[at], _TAKE_UP_DEFAULT + ) + view_units[_RATIO] = np.where(ratio_present[at], stored_ratio[at], _RATIO_DEFAULT) + engine = _engine_table(aca_tax_units, view, residual_tables, label="ACS") + del view, view_units + engine = engine.set_index(_ID).reindex(acs_ids).reset_index() + acs_flag_present = flag_present[acs_units] + acs_stored = stored_flags[acs_units] + acs_ratio_present = ratio_present[acs_units] + acs_stored_ratio = stored_ratio[acs_units] + staged = ~acs_flag_present | acs_stored + # The manifest stage's own anchor column, where staging writes it on the + # ACS persons; absent, it reads False, as the fiscal lane's person table + # does. A unit is anchored where a member reports it or its stored cell + # is True; a unit stored False stays out of the stage. + units_of = person.loc[acs_persons, _PERSON_TAX_UNIT] + reported = ( + person.loc[acs_persons, plan.anchor].fillna(False).astype(bool).to_numpy() + if plan.anchor in person + else np.zeros(len(units_of), dtype=bool) + ) + reported_units = np.isin(acs_ids, units_of.to_numpy()[reported]) + stored_true = acs_flag_present & acs_stored + reported_anchor = ~acs_flag_present & reported_units + # Reported anchors above a state's residual in the binding table are + # thinned to it: the Medicaid stage's HINS4 rule, on this stage's own + # keep stream. A stored True is never thinned. + binding = _binding_table(plan, tables) + binding_role = plan.roles[binding] + binding_residuals = residual_tables[binding] + thinning = thin_anchors_to_residuals( + groups=engine[_STATE].to_numpy(), + weights=pd.to_numeric(engine[binding_role.weight], errors="coerce") + .fillna(0.0) + .to_numpy(dtype=np.float64), + counted=_domain(engine, binding_role, label=f"ACS {binding}"), + fixed=stored_true, + anchors=reported_anchor, + residuals=dict( + zip( + binding_residuals[_STATE], + binding_residuals["target"].to_numpy(dtype=np.float64), + strict=True, + ) + ), + keys=keys, + seed=int(seed), + stream=_ANCHOR_KEEP_STREAM, + ) + thinned = reported_anchor & ~thinning.kept + anchored = stored_true | thinning.kept + + stage_units = engine.loc[staged, list(_ENGINE_TABLE_COLUMNS)].reset_index(drop=True) + stage_units[plan.draw_column] = stable_identity_uniforms( + keys[staged], seed=int(seed), salt=plan.draw_stream + ) + # The stage's person table: each ACS person's tax unit, its observed + # Marketplace coverage (the fiscal lane falls back on the deprecated + # alias, as here) and the anchor. Built column by column, so the ACS + # person rows are never copied whole. + coverage: dict[str, np.ndarray] = {} + lacking: list[str] = [] + for column in plan.aggregates: + if column == plan.anchor: + continue + source = column if column in person else _COVERAGE_ALIAS + if source not in person: + lacking.append(column) + continue + coverage[column] = ( + person.loc[acs_persons, source].fillna(False).astype(bool).to_numpy() + ) + if lacking: + raise ValueError( + f"ACS local ACA take-up requires observed coverage {lacking} (or " + f"{_COVERAGE_ALIAS}) on the ACS persons, as the fiscal lane does." + ) + anchored_ids = set(acs_ids[anchored]) + person_table = pd.DataFrame( + { + _ID: units_of.to_numpy(), + **coverage, + plan.anchor: units_of.isin(anchored_ids).to_numpy(), + } + ) + del units_of, coverage + person_table = person_table.loc[ + person_table[_ID].isin(set(stage_units[_ID])) + ].reset_index(drop=True) + stop_after = ( + None if any(name in tables for name in plan.late_tables) else "support_clip" + ) + from microcosm.build.us_runtime import ( # local: package init owns the manifest + us_source_operation_handlers, + ) + + output = run_source_stage( + plan.stage, + tables={ + "cps_person": person_table, + "tax_unit": stage_units, + **residual_tables, + }, + operation_handlers=us_source_operation_handlers(), + config=SourceRuntimeConfig(seed=int(seed), target_year=int(period)), + stop_after=stop_after, + ) + del person_table, stage_units + aligned = output.set_index(_ID).reindex(engine.loc[staged, _ID].to_numpy()) + if aligned[list(ACS_LOCAL_ACA_TAKE_UP_COLUMNS)].isna().any().any(): + raise ValueError( + f"The {ACS_LOCAL_ACA_STAGE} stage output does not cover every staged " + "ACS tax unit." + ) + take_up = np.where(acs_flag_present, acs_stored, False) + ratio = np.where(acs_ratio_present, acs_stored_ratio, _RATIO_DEFAULT) + staged_take_up = aligned[_TAKE_UP].astype(bool).to_numpy() + staged_ratio = aligned[_RATIO].astype(np.float64).to_numpy() + take_up[staged] = np.where( + acs_flag_present[staged], take_up[staged], staged_take_up + ) + ratio[staged] = np.where(acs_ratio_present[staged], ratio[staged], staged_ratio) + del output, aligned + + evaluated = _with_stored(engine, take_up, ratio) + for name in tables: + role = plan.roles[name] + chosen = _selected(evaluated, role, label=f"ACS {name}") + domain = _domain(evaluated, role, label=f"ACS {name}") & staged + sums["delivered"][name] = _state_sums(evaluated, chosen, role.weight) + sums["capacity"][name] = _state_sums(evaluated, domain, role.weight) + sums["max_unit"][name] = _state_max(evaluated, domain, role.weight) + if role.variable == _TAKE_UP: + sums["anchored"][name] = _state_sums( + evaluated, domain & anchored, role.weight + ) + + missing_take_up = np.zeros(len(tax_unit), dtype=bool) + missing_take_up[acs_units] = ~acs_flag_present + missing_ratio = np.zeros(len(tax_unit), dtype=bool) + missing_ratio[acs_units] = ~acs_ratio_present + result = frame + if missing_take_up.any() or missing_ratio.any(): + full_take_up = np.zeros(len(tax_unit), dtype=bool) + full_take_up[acs_units] = take_up + full_ratio = np.full(len(tax_unit), _RATIO_DEFAULT, dtype=np.float64) + full_ratio[acs_units] = ratio + updated = tax_unit.copy() + updated[_TAKE_UP] = _filled_flags( + tax_unit[_TAKE_UP], missing_take_up, full_take_up + ) + updated[_RATIO] = _filled_ratios(tax_unit[_RATIO], missing_ratio, full_ratio) + result = _with_tax_unit(frame, updated) + + final = result.table("tax_unit").loc[acs_units, [_TAKE_UP, _RATIO]] + final_flags, final_flag_present, _ = _boolean_cells(final[_TAKE_UP]) + final_ratio, final_ratio_present, _ = _ratio_cells(final[_RATIO]) + weights = engine[_HOUSEHOLD_WEIGHT].to_numpy(dtype=np.float64) + eligible = engine[_ELIGIBLE].to_numpy(dtype=bool) & ( + engine[_CREDIT].to_numpy(dtype=np.float64) > 0 + ) + takers = take_up & eligible + names = tuple(tables) + clipped = takers & np.isfinite(ratio) + + def weighted_share(selected: np.ndarray, within: np.ndarray) -> float | None: + total = float(weights[within].sum()) + return float(weights[selected & within].sum()) / total if total > 0 else None + + states = engine[_STATE].to_numpy() + anchor_rows = _state_counts(states, reported_anchor) + thinned_rows = _state_counts(states, thinned) + returning_rows = _state_counts(states, thinned & take_up) + thinning_rows = [ + { + _STATE: str(state), + "residual": float(residual), + "stored_true_mass": thinning.fixed_mass.get(str(state), 0.0), + "anchor_mass": thinning.anchor_mass.get(str(state), 0.0), + "keep_probability": thinning.keep_probability.get(str(state), 1.0), + "anchor_rows": anchor_rows.get(str(state), 0), + "thinned_rows": thinned_rows.get(str(state), 0), + "thinned_rows_taking_up": returning_rows.get(str(state), 0), + } + for state, residual in zip( + binding_residuals[_STATE], binding_residuals["target"], strict=True + ) + ] + + receipt: dict[str, Any] = { + "issue": ACS_LOCAL_ACA_TAKE_UP_ISSUE, + "method": ACS_LOCAL_ACA_TAKE_UP_METHOD, + "stage": ACS_LOCAL_ACA_STAGE, + "stop_after": stop_after, + "spine": ACS_2024_1YR_SPINE, + "seed": int(seed), + "draw_key": _DRAW_KEY_FORMAT, + "draw_stream": plan.draw_stream, + "columns": list(ACS_LOCAL_ACA_TAKE_UP_COLUMNS), + "acs_tax_units": int(acs_units.sum()), + "acs_households": int(len(acs_households)), + "weights_basis": _WEIGHTS_BASIS, + "target_basis": _TARGET_BASIS, + "anchor": { + "rule": _ANCHOR_RULE, + "column": plan.anchor, + "column_on_acs_persons": bool(plan.anchor in person), + "reported_acs_persons": int(reported.sum()), + "reported_tax_units": int(reported_units.sum()), + "stored_true_tax_units": int(stored_true.sum()), + "anchored_tax_units": int(anchored.sum()), + "thinning": { + "rule": _THINNING_RULE, + "table": binding, + "weight": binding_role.weight, + "stream": _ANCHOR_KEEP_STREAM, + "draw_key": _DRAW_KEY_FORMAT, + "anchor_tax_units": int(reported_anchor.sum()), + "thinned_tax_units": int(thinned.sum()), + "thinned_tax_units_taking_up": int((thinned & take_up).sum()), + "thinned_states": thinning.thinned_groups, + "states": thinning_rows, + }, + }, + "engine_prepass": { + "rows": "donor_households_then_acs_households", + "donor": donor_counts, + "missing_take_up_cells_read_as": _TAKE_UP_DEFAULT, + "missing_ratio_cells_read_as": _RATIO_DEFAULT, + "potential_credit": ( + "aca_ptc with take-up read True: the credit before the filing " + "gate (files_return_for_aca_ptc counts a unit taking up a " + "positive credit as filing for it)" + ), + "acs_eligible_tax_units": int(eligible.sum()), + }, + "binding_table": binding, + "tables": { + name: { + "operation": plan.roles[name].operation, + "variable": plan.roles[name].variable, + "weight": plan.roles[name].weight, + "domain": plan.roles[name].domain, + "binds": name == binding, + "states": rows, + } + for name, rows in _rows(names, tables, sums).items() + }, + "composition": _composition(plan, tables, sums), + "take_up": { + "column": _TAKE_UP, + "filled_rows": int((~acs_flag_present).sum()), + "preserved_acs_rows": int(acs_flag_present.sum()), + "stored_false_rows_kept": int((acs_flag_present & ~acs_stored).sum()), + "unfilled_acs_rows": int((~final_flag_present).sum()), + "taker_tax_units": int(takers.sum()), + "anchored_taker_tax_units": int((takers & anchored).sum()), + "anchor_share_of_takers": ( + float((takers & anchored).sum()) / float(takers.sum()) + if takers.any() + else None + ), + "weighted_anchor_share_of_takers": weighted_share(anchored, takers), + "weighted_take_up_share_of_eligible": weighted_share(takers, eligible), + "weighted_take_up_share": weighted_share( + take_up, np.ones(len(take_up), dtype=bool) + ), + }, + "plan_ratio": { + "column": _RATIO, + "filled_rows": int((~acs_ratio_present).sum()), + "preserved_acs_rows": int(acs_ratio_present.sum()), + "unfilled_acs_rows": int((~final_ratio_present).sum()), + "taker_share_below_1": weighted_share(clipped & (ratio < 1.0), clipped), + "taker_share_at_lower_clip": weighted_share( + clipped & (ratio <= 0.5), clipped + ), + "taker_share_at_upper_clip": weighted_share( + clipped & (ratio >= 1.5), clipped + ), + }, + "assigned_sha256": _assignment_sha256(acs_ids, final_flags, final_ratio), + } + return result, _json_ready(receipt) + + +def acs_local_aca_take_up_assignment(frame: Frame) -> pd.DataFrame: + """The ACS tax units' ids and complete ACA inputs, in tax-unit order. + + Raises: + ValueError: If origin tags are missing or an ACS cell is missing or + invalid. + """ + + _, acs_units = _acs_masks(frame) + rows = frame.table("tax_unit").loc[acs_units] + for column in ACS_LOCAL_ACA_TAKE_UP_COLUMNS: + if column not in rows: + raise ValueError(f"The frame has no {column}.") + flags, flag_present, flag_invalid = _boolean_cells(rows[_TAKE_UP]) + ratio, ratio_present, ratio_invalid = _ratio_cells(rows[_RATIO]) + if not (flag_present.all() and ratio_present.all()) or ( + flag_invalid.any() or ratio_invalid.any() + ): + raise ValueError( + "The ACS ACA inputs are not complete on the ACS tax units; run the " + "ACS local ACA take-up stage first." + ) + return pd.DataFrame({_ID: rows[_ID].to_numpy(), _TAKE_UP: flags, _RATIO: ratio}) + + +def with_recorded_acs_local_aca_take_up( + frame: Frame, recorded: pd.DataFrame, *, assigned_sha256: str +) -> Frame: + """Apply a recorded ACS assignment and prove it reproduces its digest. + + ``recorded`` is :func:`acs_local_aca_take_up_assignment` of the frame + the stage ran on. It must cover exactly this frame's ACS tax units, in + order; stored ACS cells must agree with it, missing ones take its + values, and the resulting ACS assignment must hash to + ``assigned_sha256``. + + Raises: + ValueError: On any mismatch. + """ + + _, acs_units = _acs_masks(frame) + tax_unit = frame.table("tax_unit") + ids = tax_unit.loc[acs_units, _ID].to_numpy() + required = (_ID, *ACS_LOCAL_ACA_TAKE_UP_COLUMNS) + if ( + any(column not in recorded for column in required) + or len(recorded) != len(ids) + or not np.array_equal(recorded[_ID].to_numpy(), ids) + ): + raise ValueError( + "The recorded ACS ACA take-up does not cover this frame's ACS tax " + "units in order." + ) + for column in ACS_LOCAL_ACA_TAKE_UP_COLUMNS: + if column not in tax_unit: + raise ValueError(f"The frame has no {column}.") + flags = np.asarray(recorded[_TAKE_UP].to_numpy(), dtype=bool) + ratio = np.asarray(recorded[_RATIO].to_numpy(), dtype=np.float64) + stored_flags, flag_present, flag_invalid = _boolean_cells( + tax_unit.loc[acs_units, _TAKE_UP] + ) + stored_ratio, ratio_present, ratio_invalid = _ratio_cells( + tax_unit.loc[acs_units, _RATIO] + ) + if ( + flag_invalid.any() + or ratio_invalid.any() + or (stored_flags[flag_present] != flags[flag_present]).any() + or (stored_ratio[ratio_present] != ratio[ratio_present]).any() + ): + raise ValueError("Stored ACS ACA cells disagree with the recorded assignment.") + if _assignment_sha256(ids, flags, ratio) != assigned_sha256: + raise ValueError("The recorded ACS ACA take-up does not reproduce its digest.") + missing_take_up = np.zeros(len(tax_unit), dtype=bool) + missing_take_up[acs_units] = ~flag_present + missing_ratio = np.zeros(len(tax_unit), dtype=bool) + missing_ratio[acs_units] = ~ratio_present + full_flags = np.zeros(len(tax_unit), dtype=bool) + full_flags[acs_units] = flags + full_ratio = np.full(len(tax_unit), _RATIO_DEFAULT, dtype=np.float64) + full_ratio[acs_units] = ratio + updated = tax_unit.copy() + updated[_TAKE_UP] = _filled_flags(tax_unit[_TAKE_UP], missing_take_up, full_flags) + updated[_RATIO] = _filled_ratios(tax_unit[_RATIO], missing_ratio, full_ratio) + return _with_tax_unit(frame, updated) + + +def _residual_failures(name: str, rows: object) -> list[str]: + """Each state's residual must be its count minus the donor contribution.""" + + if not isinstance(rows, list) or not rows: + return [f"receipt: no state rows for {name}."] + failures: list[str] = [] + for row in rows: + numbers = ( + [_finite(row.get(key)) for key in _STATE_NUMBERS] + if isinstance(row, Mapping) + else [float("nan")] + ) + state = row.get(_STATE) if isinstance(row, Mapping) else "?" + if not all(np.isfinite(numbers)): + failures.append(f"receipt: {name} state {state} has nonfinite values.") + continue + target, donor, residual = numbers[:3] + expected = max(target - donor, 0.0) + if abs(residual - expected) > _RESIDUAL_RELATIVE_TOLERANCE * max(target, 1.0): + failures.append( + f"receipt: {name} state {state} targets {residual:.0f}, not the " + f"donor residual {expected:.0f}." + ) + return failures + + +def _keep_probabilities(receipt: Mapping[str, Any]) -> dict[str, float]: + """Each binding-table state's anchor keep probability in the receipt.""" + + anchor = receipt.get("anchor") + thinning = anchor.get("thinning") if isinstance(anchor, Mapping) else None + rows = thinning.get("states") if isinstance(thinning, Mapping) else None + if not isinstance(rows, list): + return {} + return { + str(row.get(_STATE)): _finite(row.get("keep_probability")) + for row in rows + if isinstance(row, Mapping) + } + + +def _binding_grades( + rows: list, keep: Mapping[str, float] +) -> tuple[list[str], list[dict[str, Any]]]: + """Grade each state of the binding table; return failures and statuses.""" + + tolerance = ACS_LOCAL_ACA_RETURNS_RELATIVE_TOLERANCE + failures: list[str] = [] + graded: list[dict[str, Any]] = [] + for row in rows: + if not isinstance(row, Mapping): + continue + state = row.get(_STATE) + residual = _finite(row.get("residual")) + capacity = _finite(row.get("acs_capacity")) + delivered = _finite(row.get("acs_delivered")) + step = _finite(row.get("acs_max_unit_weight")) + anchored = _finite(row.get("acs_anchored", 0.0)) + probability = keep.get(str(state)) + if not all(np.isfinite([residual, capacity, delivered])): + continue + error = (delivered - residual) / residual if residual > 0 else None + if probability is not None and probability < 1.0: + # The reported anchors above the residual were thinned to it on + # a keyed draw, which meets it in expectation only: reported. + status = "anchors_thinned" + elif residual <= 0: + status = "donor_meets_count" + elif np.isfinite(anchored) and anchored >= residual: + # Anchors that are never thinned (a stored True) take up even + # above the residual: the excess is reported, not failed. + status = "anchor_excess" + elif capacity <= 0: + status = "no_acs_capacity" + elif capacity <= residual: + status = "saturated" + if abs(delivered - capacity) > _SATURATED_RELATIVE_TOLERANCE * capacity: + failures.append( + f"state {state}: ACS capacity {capacity:.0f} cannot reach the " + f"residual {residual:.0f}, so every eligible unit should " + f"take up, but delivery is {delivered:.0f}." + ) + elif abs(delivered - residual) <= max( + tolerance * residual, step if np.isfinite(step) else 0.0 + ): + status = "within_tolerance" + else: + status = "outside_tolerance" + failures.append( + f"state {state}: delivered ACS count {delivered:.0f} misses the " + f"donor residual {residual:.0f} by {error:+.1%}, beyond " + f"{tolerance:.0%} and one unit's weight." + ) + graded.append( + { + _STATE: state, + "status": status, + "relative_error": error, + "capacity_shortfall": max(residual - capacity, 0.0), + "anchor_excess": ( + max(anchored - residual, 0.0) if np.isfinite(anchored) else None + ), + "keep_probability": probability, + } + ) + return failures, graded + + +def _receipt_failures( + receipt: object, acs_units: int, details: dict[str, Any] +) -> list[str]: + if ( + not isinstance(receipt, Mapping) + or receipt.get("issue") != ACS_LOCAL_ACA_TAKE_UP_ISSUE + or receipt.get("method") != ACS_LOCAL_ACA_TAKE_UP_METHOD + ): + details["receipt"] = {"present": False} + return [ + f"No acs_local_aca_take_up receipt ({ACS_LOCAL_ACA_TAKE_UP_ISSUE}); " + "the ACS rows' ACA take-up cannot be shown to be assigned." + ] + failures: list[str] = [] + if type(receipt.get("seed")) is not int: + failures.append("receipt: no integer seed.") + if receipt.get("acs_tax_units") != acs_units: + failures.append( + f"receipt: records {receipt.get('acs_tax_units')!r} ACS tax unit(s) " + f"but the frame has {acs_units}." + ) + digest = receipt.get("assigned_sha256") + if not isinstance(digest, str) or len(digest) != 64: + failures.append("receipt: no assignment digest.") + for key, column in (("take_up", _TAKE_UP), ("plan_ratio", _RATIO)): + entry = receipt.get(key) + if not isinstance(entry, Mapping) or entry.get("column") != column: + failures.append(f"receipt: no {key} entry for {column}.") + elif entry.get("unfilled_acs_rows") != 0: + failures.append( + f"receipt: {column} left {entry.get('unfilled_acs_rows')!r} ACS " + "row(s) unfilled." + ) + tables = receipt.get("tables") + binding = receipt.get("binding_table") + if not isinstance(tables, Mapping) or binding not in tables: + failures.append("receipt: no table accounting with its binding table.") + details["receipt"] = {"present": True, "failures": len(failures)} + return failures + for name, entry in tables.items(): + rows = entry.get("states") if isinstance(entry, Mapping) else None + failures += _residual_failures(str(name), rows) + binding_entry = tables[binding] + rows = binding_entry.get("states") if isinstance(binding_entry, Mapping) else None + keep = _keep_probabilities(receipt) + binding_failures, graded = _binding_grades( + rows if isinstance(rows, list) else [], keep + ) + failures += binding_failures + details["binding_table"] = binding + details["binding_states"] = graded + details["thinned_states"] = sorted( + state for state, probability in keep.items() if probability < 1.0 + ) + # Kept anchors above a table's residual: reported per table, not failed. + details["anchor_excess_states"] = { + str(name): sum( + 1 + for row in entry.get("states") or [] + if isinstance(row, Mapping) and _finite(row.get("anchor_excess")) > 0 + ) + for name, entry in tables.items() + if isinstance(entry, Mapping) + } + details["composition"] = receipt.get("composition") + details["receipt"] = {"present": True, "failures": len(failures)} + return failures + + +def acs_local_aca_take_up_signal_gate( + frame: Frame, *, receipt: Mapping[str, Any] | None +) -> GateResult: + """Grade the ACS rows' ACA take-up and plan ratio. The lane only reports it. + + Fails when either column is absent, an ACS cell is missing or invalid + (a take-up flag that is not boolean, a ratio that is not finite and + positive), the ACS take-up is constant while some state of the binding + table has a residual and ACS capacity, or ``receipt`` does not show the + materialize assignment: no unfilled ACS unit, every table's residual + equal to its count minus the donor contribution, and in the binding + table (the SOI return count where the feed has it) each state's + delivered ACS count within + :data:`ACS_LOCAL_ACA_RETURNS_RELATIVE_TOLERANCE` of its residual, or of + one unit's weight, where the ACS capacity exceeds it, and equal to the + capacity where it does not. States whose reported anchors the receipt + thinned to the residual (the keep draw meets it in expectation only), + states the donor rows already meet, states whose stored anchors alone + meet the residual, states without ACS capacity, shortfalls, excesses, + the kept anchors' excess over any table, the CMS people, the amounts and + the people per return are reported, not failed. + + The ACS local release records this verdict in its receipt and in a + diagnostic shadow entry and never stops on it (microcosm#1720). + """ + + failures: list[str] = [] + details: dict[str, Any] = { + "columns": list(ACS_LOCAL_ACA_TAKE_UP_COLUMNS), + "relative_tolerance": ACS_LOCAL_ACA_RETURNS_RELATIVE_TOLERANCE, + } + try: + _, acs_units = _acs_masks(frame) + except ValueError as exc: + return GateResult( + name=ACS_LOCAL_ACA_TAKE_UP_GATE_NAME, + passed=False, + failures=(str(exc),), + details=details, + ) + tax_unit = frame.table("tax_unit") + tag = spine_column("tax_unit") + if set(tax_unit[tag].unique()) - {ASEC_PUF_DONOR_SPINE, ACS_2024_1YR_SPINE}: + failures.append("ACA take-up origin tags contain an unsupported spine.") + absent = [ + column for column in ACS_LOCAL_ACA_TAKE_UP_COLUMNS if column not in tax_unit + ] + if absent: + failures.append( + f"Missing tax-unit column(s) {absent}; the engine default is " + "universal take-up at the benchmark plan." + ) + else: + flags, flag_present, flag_invalid = _boolean_cells(tax_unit[_TAKE_UP]) + _, ratio_present, ratio_invalid = _ratio_cells(tax_unit[_RATIO]) + acs = { + "missing_take_up_rows": int((acs_units & ~flag_present).sum()), + "invalid_take_up_rows": int((acs_units & flag_invalid).sum()), + "missing_ratio_rows": int((acs_units & ~ratio_present).sum()), + "invalid_ratio_rows": int((acs_units & ratio_invalid).sum()), + "unique_take_up_values": int( + np.unique(flags[acs_units & flag_present & ~flag_invalid]).size + ), + } + details["acs"] = acs + for key, count in acs.items(): + if key != "unique_take_up_values" and count: + failures.append( + f"{ACS_2024_1YR_SPINE}: {count} {key.replace('_', ' ')}." + ) + failures += _receipt_failures(receipt, int(acs_units.sum()), details) + open_states = [ + row + for row in details.get("binding_states", []) + if row["status"] in {"saturated", "within_tolerance", "outside_tolerance"} + ] + if open_states and details.get("acs", {}).get("unique_take_up_values", 2) < 2: + failures.append( + f"{ACS_2024_1YR_SPINE}: ACA take-up is constant although " + f"{len(open_states)} state(s) have a residual the ACS rows can fill." + ) + return GateResult( + name=ACS_LOCAL_ACA_TAKE_UP_GATE_NAME, + passed=not failures, + failures=tuple(failures), + details=_json_ready(details), + ) diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_coverage_anchors.py b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_coverage_anchors.py new file mode 100644 index 0000000000..6f440bb121 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_coverage_anchors.py @@ -0,0 +1,656 @@ +"""Employer and direct-purchase coverage of ACS rows (ACS local lane). + +``has_esi`` and the two direct-purchase flags +(``has_marketplace_health_coverage_at_interview``, +``has_non_marketplace_direct_purchase_health_coverage_at_interview``) reach +ACS rows as draws of the shared transfer, on age, sex, State and income, +although the ACS asks both items (microcosm#1720). ``has_esi`` bars the +premium tax credit and CHIP and the self-employed health insurance deduction, +so the drawn flag made those pools noisy on ACS rows. + +This lane-own step writes the ACS items over the draws, on the ACS-only frame +after every transfer and before pooling, the pattern of the native SNAP +receipt anchor (:mod:`~microcosm.build.us_runtime.acs_local_receipt_anchors`). +Writing them before the transfer would take ``has_esi`` out of its chained +batch and move every other draw of the batch; after it, the shared plan, its +chain and every other draw are unchanged. + +- **has_esi** is ACS ``HINS1 == 1``: insurance through a current or former + employer or union, of the person or another family member, at interview. + The donor reads ASEC ``NOW_GRP``, current employment-based coverage + (:mod:`~microcosm.build.us_runtime.cps_carried`). +- **The two direct-purchase flags** follow ACS ``HINS2`` (insurance purchased + directly from an insurance company), which does not tell Marketplace + coverage from other direct purchase. ``HINS2 == 2``: both False. + ``HINS2 == 1``: ACS ``HIMRKS`` (Subsidized Marketplace Coverage, loaded as + ``ACS_HIMRKS``) code 1, direct purchase with a premium subsidy, which only + the Marketplace pays, sets the Marketplace flag True and keeps the drawn + non-Marketplace flag (ruled 25 Nov 2026). Under codes 0 and 2 and a blank + the transfer's draws stand where one of them is True; where both are False, + one keyed draw picks the type (Marketplace only, non-Marketplace only, or + both) at the donor ASEC role's conditional shares among direct purchasers, + by age band (under 65, 65 and over: at 65+ direct purchase is mostly + Medigap). The draw is keyed on ``acs_2024_1yr:SERIALNO:SPORDER`` and the + build seed. Code 2 cannot tell Marketplace coverage at full price from + other direct purchase, and code 0's universe is not documented, so no rule + reads either. This choice among direct purchasers is one function, + :func:`choose_acs_direct_purchase_types`. +- **Blanks.** The 2024 PUMS dictionary lists no blank code for HINS1, HINS2 + or HIMRKS; a blank that arrives anyway keeps the earlier rule and is + counted. +- **The ACA anchor** (ruled 25 Nov 2026, "Yes, with thinning"). The stage + writes the ACA manifest stage's own anchor column, + ``reported_has_subsidized_marketplace_health_coverage_at_interview`` (read + from the manifest's ``reported_true_anchor``), on the ACS rows: True where + ``HINS2 == 1`` and HIMRKS is 1, allocated values included; False on every + other ACS row. Donor rows are not written: the donor reads no subsidized + item (``NOW_MRKS`` is unread), and the national tool reads the absent + column as False there. The release's ACA stage thins anchors above a + state's residual. ``HIMRKS`` also stays on the staged ACS rows as a raw + source item. + +The step must run before the self-employed premium attribution +(:mod:`~microcosm.build.us_runtime.acs_local_se_health_premiums`), which +reads ``has_esi``. It records a receipt, with the agreement of each native +value with the draw it replaces, and grades nothing. It refuses only a frame +without the columns it reads, and malformed source codes. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from functools import cache +from importlib.resources import files +from typing import Any + +import numpy as np +import pandas as pd + +from microcosm.build.source_manifest import load_source_manifest +from microcosm.build.stochastic_assignment import stable_identity_uniforms +from microcosm.build.us_runtime.acs_inputs import _nullable_source_codes +from microcosm.build.us_runtime.acs_local_ssi_disability import _acs_draw_keys +from microcosm.build.us_runtime.acs_pums import ( + ACS_2024_1YR_SPINE, + ACS_SOURCE_COLUMN_RENAMES, +) +from microcosm.build.us_runtime.acs_transfer import resolve_acs_donor_channel +from microcosm.build.us_runtime.support_provenance import BASE_ASEC_SUPPORT_CHANNEL +from microcosm.frame import Frame +from microcosm.frame.units import US_SCHEMA + +__all__ = [ + "ACS_DIRECT_PURCHASE_CHOICE_SOURCE", + "ACS_DIRECT_PURCHASE_TYPES", + "ACS_LOCAL_COVERAGE_ANCHOR_COLUMNS", + "ACS_LOCAL_COVERAGE_ANCHORS_ISSUE", + "ACS_LOCAL_COVERAGE_ANCHORS_METHOD", + "ACS_LOCAL_COVERAGE_SOURCE_COLUMNS", + "acs_local_aca_reported_true_anchor", + "acs_local_direct_purchase_donor_shares", + "choose_acs_direct_purchase_types", + "with_acs_local_coverage_anchors", +] + +ACS_LOCAL_COVERAGE_ANCHORS_ISSUE = "microcosm#1720" +ACS_LOCAL_COVERAGE_ANCHORS_METHOD = ( + "native_hins1_hins2_after_every_transfer_direct_purchase_type_draw" +) +_ESI = "has_esi" +_MARKETPLACE = "has_marketplace_health_coverage_at_interview" +_OTHER_DIRECT = "has_non_marketplace_direct_purchase_health_coverage_at_interview" +ACS_LOCAL_COVERAGE_ANCHOR_COLUMNS: tuple[str, ...] = (_ESI, _MARKETPLACE, _OTHER_DIRECT) +_EMPLOYER_ITEM = "HINS1" +_DIRECT_ITEM = "HINS2" +#: HIMRKS and its allocation flag, as the loader renames them. +_SUBSIDY_ITEM = ACS_SOURCE_COLUMN_RENAMES["HIMRKS"] +_SUBSIDY_ALLOCATION = ACS_SOURCE_COLUMN_RENAMES["FHIMRKSP"] +#: HIMRKS 1: direct purchase coverage, with premium subsidy. +_SUBSIDIZED_CODE = 1 +#: HIMRKS 1 and 2 are direct purchase codes; a conflict with HINS2 == 2. +_DIRECT_PURCHASE_CODES = (1, 2) +ACS_LOCAL_COVERAGE_SOURCE_COLUMNS: tuple[str, ...] = ( + _EMPLOYER_ITEM, + _DIRECT_ITEM, + _SUBSIDY_ITEM, +) +_AGE = "age" +#: The type of direct purchase as the two donor flags record it. +ACS_DIRECT_PURCHASE_TYPES: Mapping[str, tuple[bool, bool]] = { + "marketplace_only": (True, False), + "non_marketplace_only": (False, True), + "both": (True, True), +} +#: Direct purchase at 65+ is mostly Medigap, so the shares are by age band. +_AGE_BANDS: tuple[tuple[str, float, float], ...] = ( + ("under_65", 0.0, 65.0), + ("65_plus", 65.0, np.inf), +) +_DRAW_KEY_FORMAT = f"{ACS_2024_1YR_SPINE}:SERIALNO:SPORDER" +_DRAW_SALT = "acs_local_direct_purchase_type" +#: Where the Marketplace-versus-other choice comes from (ruled 25 Nov 2026: +#: HIMRKS splits the direct-purchase flags). +ACS_DIRECT_PURCHASE_CHOICE_SOURCE = ( + "himrks_1_marketplace_else_transfer_draws_else_donor_asec_type_shares_by_age_band" +) +_SOURCE_LABELS: Mapping[str, str] = { + _EMPLOYER_ITEM: "Insurance through a current or former employer or union", + _DIRECT_ITEM: "Insurance purchased directly from an insurance company", + _SUBSIDY_ITEM: ( + "HIMRKS, Subsidized Marketplace Coverage: 0 categorically ineligible " + "for subsidy, 1 direct purchase coverage with premium subsidy, 2 " + "direct purchase coverage without a premium subsidy" + ), + _SUBSIDY_ALLOCATION: "FHIMRKSP, Subsidized Marketplace Coverage allocation flag", +} +_NOT_USED: Mapping[str, str] = { + "HIMRKS code 0": "its universe is not documented; no rule reads it", + "HIMRKS code 2": ( + "direct purchase without a subsidy can be on or off the Marketplace; " + "the earlier rule applies" + ), +} +#: The US manifest stage whose own anchor column the stage writes. +_ACA_STAGE = "aca_marketplace_inputs" +_ANCHOR_PARAMETER = "reported_true_anchor" + + +@cache +def acs_local_aca_reported_true_anchor() -> str: + """The ACA manifest stage's own anchor column, from the US manifest. + + Raises: + ValueError: If the manifest has no ACA stage or not exactly one + anchor column. + """ + + stage = ( + load_source_manifest(files("microcosm.build.us").joinpath("source_stages.json")) + .stage_map() + .get(_ACA_STAGE) + ) + if stage is None: + raise ValueError( + f"The US source manifest declares no {_ACA_STAGE!r} stage " + f"({ACS_LOCAL_COVERAGE_ANCHORS_ISSUE})." + ) + anchors = { + str(operation.parameters[_ANCHOR_PARAMETER]) + for operation in stage.operations + if _ANCHOR_PARAMETER in operation.parameters + } + if len(anchors) != 1: + raise ValueError( + f"The {_ACA_STAGE!r} stage must declare one {_ANCHOR_PARAMETER}, " + f"got {sorted(anchors)} ({ACS_LOCAL_COVERAGE_ANCHORS_ISSUE})." + ) + return anchors.pop() + + +def _flags(values: pd.Series, column: str) -> np.ndarray: + """A complete boolean column as an array; refuses anything else.""" + + if values.isna().any() or not values.isin([0, 1]).all(): + raise ValueError( + f"ACS {column} must be a complete boolean after the shared transfer " + f"({ACS_LOCAL_COVERAGE_ANCHORS_ISSUE})." + ) + return values.astype(bool).to_numpy(dtype=bool) + + +def _weighted_share(weights: np.ndarray, flags: np.ndarray) -> float: + total = float(weights.sum()) + return float(weights[flags].sum()) / total if total > 0 else 0.0 + + +def _band_masks(age: np.ndarray) -> dict[str, np.ndarray]: + return {name: (age >= low) & (age < high) for name, low, high in _AGE_BANDS} + + +def _type_shares( + marketplace: np.ndarray, other: np.ndarray, weights: np.ndarray +) -> dict[str, float] | None: + """Weighted type shares among direct purchasers, or None without any.""" + + purchasers = marketplace | other + total = float(weights[purchasers].sum()) + if total <= 0: + return None + return { + name: float(weights[(marketplace == m) & (other == o) & purchasers].sum()) + / total + for name, (m, o) in ACS_DIRECT_PURCHASE_TYPES.items() + } + + +def acs_local_direct_purchase_donor_shares(donor: Frame) -> dict[str, Any]: + """The donor ASEC role's direct-purchase type shares, by age band. + + Measured ``NOW_MRK``/``NOW_NONM`` on the ASEC observation role, weighted + by person weight; the PUF clones are not read. A band without a direct + purchaser falls back to the all-ages shares (recorded). + + Raises: + ValueError: If the donor lacks the ASEC role, an age or a flag. + """ + + try: + asec, channel = resolve_acs_donor_channel(donor, BASE_ASEC_SUPPORT_CHANNEL) + except ValueError as exc: + raise ValueError( + "The ACS direct-purchase draw needs the donor's ASEC observation " + f"role ({ACS_LOCAL_COVERAGE_ANCHORS_ISSUE}): {exc}" + ) from exc + person = asec.table("person") + missing = [ + column for column in (_AGE, _MARKETPLACE, _OTHER_DIRECT) if column not in person + ] + if missing: + raise ValueError( + f"The ASEC donor lacks {missing} ({ACS_LOCAL_COVERAGE_ANCHORS_ISSUE})." + ) + age = pd.to_numeric(person[_AGE], errors="coerce").to_numpy(dtype=np.float64) + marketplace = _flags(person[_MARKETPLACE], f"donor {_MARKETPLACE}") + other = _flags(person[_OTHER_DIRECT], f"donor {_OTHER_DIRECT}") + weights = np.asarray(asec.resolve_weights("person").values, dtype=np.float64) + overall = _type_shares(marketplace, other, weights) + bands: dict[str, Any] = {} + for name, mask in _band_masks(age).items(): + shares = _type_shares(marketplace[mask], other[mask], weights[mask]) + bands[name] = { + "shares": shares if shares is not None else overall, + "fallback_to_all_ages": shares is None, + "purchaser_rows": int((mask & (marketplace | other)).sum()), + } + return { + "channel": channel, + "person_rows": int(len(person)), + "all_ages": overall, + "bands": bands, + } + + +def _draw_types( + uniforms: np.ndarray, shares: Mapping[str, float] +) -> tuple[np.ndarray, np.ndarray, list[str]]: + """Each uniform's type by the cumulative shares, in a fixed order.""" + + names = list(ACS_DIRECT_PURCHASE_TYPES) + edges = np.cumsum([shares[name] for name in names]) + index = np.minimum(np.searchsorted(edges, uniforms, side="right"), len(names) - 1) + chosen = [names[i] for i in index] + marketplace = np.asarray([ACS_DIRECT_PURCHASE_TYPES[c][0] for c in chosen]) + other = np.asarray([ACS_DIRECT_PURCHASE_TYPES[c][1] for c in chosen]) + return marketplace.astype(bool), other.astype(bool), chosen + + +def _agreement(native: np.ndarray, drawn: np.ndarray) -> dict[str, int]: + return { + "both_true_rows": int((native & drawn).sum()), + "native_only_rows": int((native & ~drawn).sum()), + "drawn_only_rows": int((~native & drawn).sum()), + "both_false_rows": int((~native & ~drawn).sum()), + } + + +def _code_rows(codes: pd.Series) -> dict[str, int]: + counts = { + str(int(code)): int(count) + for code, count in codes.value_counts().sort_index().items() + } + counts["blank"] = int(codes.isna().sum()) + return counts + + +def _json_ready(value: Any) -> Any: + if isinstance(value, Mapping): + return {str(key): _json_ready(item) for key, item in value.items()} + if isinstance(value, (list, tuple)): + return [_json_ready(item) for item in value] + if isinstance(value, np.generic): + return value.item() + return value + + +def choose_acs_direct_purchase_types( + rows: pd.DataFrame, + household: pd.DataFrame, + *, + drawn_marketplace: np.ndarray, + drawn_other: np.ndarray, + donor_shares: Mapping[str, Any], + seed: int, + weights: np.ndarray, +) -> tuple[np.ndarray, np.ndarray, dict[str, Any]]: + """The Marketplace-versus-other choice for ACS direct purchasers. + + As ruled on 25 Nov 2026, ``HIMRKS`` (``ACS_HIMRKS``) code 1, direct + purchase coverage with a premium subsidy, sets the Marketplace flag True; + the drawn non-Marketplace flag stands, since HIMRKS says nothing about + another direct plan. Under codes 0 and 2 and a blank the earlier rule + holds: the shared transfer's draws stand where either flag is True; where + both are False, one draw keyed on ``acs_2024_1yr:SERIALNO:SPORDER`` and + ``seed`` picks the type at the donor ASEC role's shares in the person's + age band (``donor_shares``, from + :func:`acs_local_direct_purchase_donor_shares`); a band without shares + leaves both False and counts the row as unresolved. Code 0's universe is + not documented, so no rule reads it. The HINS2 == 2 rule, ``has_esi`` and + the rest of the stage do not depend on this function. + + Args: + rows: The HINS2 == 1 person rows, with ``ACS_HIMRKS``, ``age``, + ``SPORDER`` and ``person_household_id`` (and ``ACS_FHIMRKSP`` if + the source has it). + household: The household table, for ``SERIALNO``. + drawn_marketplace: The transferred Marketplace flag of ``rows``. + drawn_other: The transferred non-Marketplace direct-purchase flag of + ``rows``. + donor_shares: The donor's type shares by age band. + seed: The build seed. + weights: The person weights of ``rows``, for the receipt's shares. + + Returns: + The two flags for ``rows``, in their order, and the receipt of the + choice (row counts and weighted shares only). + + Raises: + ValueError: If a HIMRKS or FHIMRKSP code is malformed, or a row needs + a draw and its key cannot be built. + """ + + subsidy = _nullable_source_codes( + rows[_SUBSIDY_ITEM].rename("HIMRKS"), minimum=0, maximum=2 + ) + subsidized = subsidy.eq(_SUBSIDIZED_CODE).to_numpy(dtype=bool) + allocated: np.ndarray | None = None + if _SUBSIDY_ALLOCATION in rows: + allocated = ( + _nullable_source_codes( + rows[_SUBSIDY_ALLOCATION].rename("FHIMRKSP"), minimum=0, maximum=1 + ) + .eq(1) + .to_numpy(dtype=bool) + ) + weights = np.asarray(weights, dtype=np.float64) + drawn_marketplace = np.asarray(drawn_marketplace, dtype=bool) + drawn_other = np.asarray(drawn_other, dtype=bool) + marketplace = drawn_marketplace | subsidized + other = drawn_other.copy() + to_draw = ~subsidized & ~drawn_marketplace & ~drawn_other + drawn_types: dict[str, int] = dict.fromkeys(ACS_DIRECT_PURCHASE_TYPES, 0) + unresolved = np.zeros(len(rows), dtype=bool) + if to_draw.any(): + positions = np.flatnonzero(to_draw) + try: + keys = _acs_draw_keys(household, rows.iloc[positions]) + except ValueError as exc: + raise ValueError( + f"ACS direct-purchase type draw: {exc} " + f"({ACS_LOCAL_COVERAGE_ANCHORS_ISSUE})" + ) from exc + uniforms = stable_identity_uniforms( + keys.tolist(), seed=int(seed), salt=_DRAW_SALT + ) + age = pd.to_numeric(rows[_AGE], errors="coerce").to_numpy(dtype=np.float64) + for name, mask in _band_masks(age[positions]).items(): + if not mask.any(): + continue + chosen_rows = positions[mask] + shares = donor_shares["bands"][name]["shares"] + if shares is None: + unresolved[chosen_rows] = True + continue + band_marketplace, band_other, chosen = _draw_types(uniforms[mask], shares) + marketplace[chosen_rows] = band_marketplace + other[chosen_rows] = band_other + for choice in chosen: + drawn_types[choice] += 1 + codes = subsidy.to_numpy(dtype=np.float64, na_value=np.nan) + himrks: dict[str, Any] = { + "codes": _code_rows(subsidy), + "weighted_shares": { + **{ + str(code): _weighted_share(weights, codes == code) for code in (0, 1, 2) + }, + "blank": _weighted_share(weights, np.isnan(codes)), + }, + "allocation_flag_loaded": allocated is not None, + "allocated_rows": int(allocated.sum()) if allocated is not None else None, + "allocated_code_1_rows": ( + int((allocated & subsidized).sum()) if allocated is not None else None + ), + "code_1": { + "rows": int(subsidized.sum()), + "drawn_marketplace_true_rows": int((subsidized & drawn_marketplace).sum()), + "drawn_marketplace_false_rows": int( + (subsidized & ~drawn_marketplace).sum() + ), + "drawn_marketplace_weighted_share": _weighted_share( + weights[subsidized], drawn_marketplace[subsidized] + ), + "drawn_non_marketplace_kept_rows": int((subsidized & drawn_other).sum()), + "drawn_non_marketplace_only_became_both_rows": int( + (subsidized & drawn_other & ~drawn_marketplace).sum() + ), + }, + } + receipt: dict[str, Any] = { + "source": ACS_DIRECT_PURCHASE_CHOICE_SOURCE, + "rows": int(len(rows)), + "himrks": himrks, + "set_marketplace_by_code_1_rows": int((subsidized & ~drawn_marketplace).sum()), + "draw_kept_rows": int((~subsidized & ~to_draw).sum()), + "type_drawn_rows": int((to_draw & ~unresolved).sum()), + "type_drawn_by_type": drawn_types, + "unresolved_rows": int(unresolved.sum()), + "donor_shares": dict(donor_shares), + "draw_key": _DRAW_KEY_FORMAT, + "draw_salt": _DRAW_SALT, + "seed": int(seed), + } + return marketplace, other, receipt + + +def with_acs_local_coverage_anchors( + frame: Frame, + donor: Frame, + *, + seed: int, +) -> tuple[Frame, dict[str, Any]]: + """Write ACS HINS1 and HINS2 over the transferred coverage draws. + + Args: + frame: The ACS-only frame after every transfer, before pooling. Its + person table carries HINS1, HINS2, ``age``, ``SPORDER``, + ``person_household_id`` and the three transferred flags; its + household table carries ``SERIALNO``. + donor: The ASEC-by-PUF base, for the direct-purchase type shares. + seed: The build seed for the keyed type draw. + + Returns: + The frame with the native values and a JSON-ready receipt. + + Raises: + ValueError: If the frame is not US-schema, a column is absent, a code + is malformed, a transferred flag is not a complete boolean, or the + donor cannot give the type shares. + """ + + if frame.schema != US_SCHEMA: + raise ValueError("ACS coverage anchors require the US schema.") + person = frame.table("person") + missing = [ + column + for column in ( + *ACS_LOCAL_COVERAGE_SOURCE_COLUMNS, + *ACS_LOCAL_COVERAGE_ANCHOR_COLUMNS, + _AGE, + ) + if column not in person + ] + if missing: + raise ValueError( + f"ACS coverage anchors require person column(s) {missing}: HINS1, " + "HINS2 and HIMRKS (as ACS_HIMRKS) from the pinned ACS PUMS source, " + f"the flags from the shared transfer ({ACS_LOCAL_COVERAGE_ANCHORS_ISSUE})." + ) + employer = _nullable_source_codes(person[_EMPLOYER_ITEM], minimum=1, maximum=2) + direct = _nullable_source_codes(person[_DIRECT_ITEM], minimum=1, maximum=2) + subsidy = _nullable_source_codes( + person[_SUBSIDY_ITEM].rename("HIMRKS"), minimum=0, maximum=2 + ) + allocated: np.ndarray | None = None + if _SUBSIDY_ALLOCATION in person: + allocated = ( + _nullable_source_codes( + person[_SUBSIDY_ALLOCATION].rename("FHIMRKSP"), minimum=0, maximum=1 + ) + .eq(1) + .to_numpy(dtype=bool) + ) + drawn_esi = _flags(person[_ESI], _ESI) + drawn_marketplace = _flags(person[_MARKETPLACE], _MARKETPLACE) + drawn_other = _flags(person[_OTHER_DIRECT], _OTHER_DIRECT) + age = pd.to_numeric(person[_AGE], errors="coerce").to_numpy(dtype=np.float64) + if np.isnan(age).any(): + raise ValueError("ACS coverage anchors require every age.") + + employer_coded = employer.notna().to_numpy(dtype=bool) + esi = np.where(employer_coded, employer.eq(1).to_numpy(dtype=bool), drawn_esi) + + no_direct = direct.eq(2).to_numpy(dtype=bool) + yes_direct = direct.eq(1).to_numpy(dtype=bool) + marketplace = np.where(no_direct, False, drawn_marketplace) + other = np.where(no_direct, False, drawn_other) + # The Marketplace-versus-other choice among direct purchasers is one + # function; HIMRKS code 1 decides it there (ruled 25 Nov 2026). + yes_rows = np.flatnonzero(yes_direct) + chosen_marketplace, chosen_other, choice = choose_acs_direct_purchase_types( + person.iloc[yes_rows], + frame.table("household"), + drawn_marketplace=drawn_marketplace[yes_rows], + drawn_other=drawn_other[yes_rows], + donor_shares=acs_local_direct_purchase_donor_shares(donor), + seed=seed, + weights=np.asarray(frame.resolve_weights("person").values, dtype=np.float64)[ + yes_rows + ], + ) + marketplace[yes_rows] = chosen_marketplace + other[yes_rows] = chosen_other + # The ACA stage's fixed points: direct purchase with a premium subsidy. + anchor_column = acs_local_aca_reported_true_anchor() + subsidized = subsidy.eq(_SUBSIDIZED_CODE).to_numpy(dtype=bool) + anchor = yes_direct & subsidized + + tables = {entity: frame.table(entity) for entity in frame.entities} + tables.update({name: frame.link(name) for name in frame.links}) + updated = person.copy() + updated[_ESI] = esi.astype(bool) + updated[_MARKETPLACE] = marketplace.astype(bool) + updated[_OTHER_DIRECT] = other.astype(bool) + updated[anchor_column] = anchor.astype(bool) + tables["person"] = updated + result = Frame( + tables, + frame.schema, + {entity: frame.weights_for(entity) for entity in frame.weighted_entities}, + frame.strata, + mass_log=frame.mass_log, + metadata=frame.metadata, + ) + + weights = np.asarray(frame.resolve_weights("person").values, dtype=np.float64) + receipt: dict[str, Any] = { + "issue": ACS_LOCAL_COVERAGE_ANCHORS_ISSUE, + "method": ACS_LOCAL_COVERAGE_ANCHORS_METHOD, + "spine": ACS_2024_1YR_SPINE, + "sources": dict(_SOURCE_LABELS), + "acs_persons": int(len(person)), + "hins1_rows": _code_rows(employer), + "hins2_rows": _code_rows(direct), + _ESI: { + "rule": "HINS1 == 1; a blank keeps the transfer's draw", + "agreement_with_draw": _agreement( + esi[employer_coded], drawn_esi[employer_coded] + ), + "changed_rows": int((esi != drawn_esi).sum()), + "native_weighted_share": _weighted_share(weights, esi), + "drawn_weighted_share": _weighted_share(weights, drawn_esi), + }, + "direct_purchase": { + "rule": ( + "HINS2 == 2: both flags False; HINS2 == 1: " + "choose_acs_direct_purchase_types (see choice.source); a " + "blank keeps the draws" + ), + "hins2_no_rows": int(no_direct.sum()), + "set_false_from_draw": { + _MARKETPLACE: int((no_direct & drawn_marketplace).sum()), + _OTHER_DIRECT: int((no_direct & drawn_other).sum()), + }, + "hins2_yes_rows": int(yes_direct.sum()), + # HINS2 == 2 wins over a HIMRKS direct-purchase code: both flags + # stay False. Counted, never resolved the other way. + "himrks_conflicts": { + "hins2_no_himrks_direct_rows": { + str(code): int((no_direct & subsidy.eq(code).to_numpy()).sum()) + for code in _DIRECT_PURCHASE_CODES + }, + "hins2_no_himrks_direct_weighted_share": _weighted_share( + weights, + no_direct & subsidy.isin(_DIRECT_PURCHASE_CODES).to_numpy(), + ), + "hins2_blank_himrks_direct_rows": int( + ( + direct.isna().to_numpy() + & subsidy.isin(_DIRECT_PURCHASE_CODES).to_numpy() + ).sum() + ), + }, + "choice": choice, + "weighted_shares": { + column: { + "native": _weighted_share(weights, final), + "drawn": _weighted_share(weights, drawn), + } + for column, final, drawn in ( + (_MARKETPLACE, marketplace, drawn_marketplace), + (_OTHER_DIRECT, other, drawn_other), + ) + }, + }, + "aca_anchor": { + "column": anchor_column, + "manifest_stage": _ACA_STAGE, + "rule": ( + "HINS2 == 1 and HIMRKS == 1, allocated values included; False " + "on every other ACS row; donor rows are not written" + ), + "replaced_existing_column": anchor_column in person, + "true_rows": int(anchor.sum()), + "weighted_share": _weighted_share(weights, anchor), + # Census-allocated code 1 values are anchors too (not ruled). + "allocation_flag_loaded": allocated is not None, + "allocated_true_rows": ( + int((anchor & allocated).sum()) if allocated is not None else None + ), + "allocated_weighted_share_of_true": ( + _weighted_share(weights[anchor], allocated[anchor]) + if allocated is not None + else None + ), + # HIMRKS 1 where HINS2 is 2 (or blank): no anchor; counted. + "conflicts": { + "himrks_1_hins2_no_rows": int((no_direct & subsidized).sum()), + "himrks_1_hins2_no_weighted_share": _weighted_share( + weights, no_direct & subsidized + ), + "himrks_1_hins2_blank_rows": int( + (direct.isna().to_numpy() & subsidized).sum() + ), + }, + }, + "not_used": dict(_NOT_USED), + } + return result, _json_ready(receipt) diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_group_quarters_housing.py b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_group_quarters_housing.py new file mode 100644 index 0000000000..6300f3f67b --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_group_quarters_housing.py @@ -0,0 +1,163 @@ +"""Housing take-up of ACS group-quarters units (ACS local lane, microcosm#975). + +``takes_up_housing_assistance_if_eligible`` is a target of the shared +declared transfer plan, which has no group-quarters carve-out, so ACS SPM +units in group quarters (household ``TYPEHUGQ`` 2, institutional, and 3, +noninstitutional) drew the flag from housing-unit donors although they have no +housing unit (microcosm#975). The release tool already writes +``receives_housing_assistance`` False there; the take-up flag was the one +housing-receipt signal those units still carried. + +This lane-own step sets the flag False on every ACS group-quarters SPM unit, +on the ACS-only frame after the shared transfer and before pooling, the place +of the native receipt anchors. It differs from microcosm#975's proposed +design, a structural policy inside the shared transfer (``acs_transfer``): +that would move the shared execution contract, the attested +``imputation.yaml`` entry and the pool lane's pins. The shared plan is +unchanged here, so the flag is still drawn (and its draw recorded) before the +step overrides it, and housing-unit SPM units keep their draw. + +The step records a receipt (group-quarters units by ``TYPEHUGQ`` and how many +it turned from True to False) and grades nothing. It refuses only a frame +without the columns it reads; an SPM unit whose household carries no +``TYPEHUGQ`` 1, 2 or 3 keeps its draw and is counted. +""" + +from __future__ import annotations + +from typing import Any + +import numpy as np +import pandas as pd + +from microcosm.build.us_runtime.acs_pums import ACS_2024_1YR_SPINE +from microcosm.frame import Frame +from microcosm.frame.units import US_SCHEMA + +__all__ = [ + "ACS_GROUP_QUARTERS_KINDS", + "ACS_LOCAL_GROUP_QUARTERS_HOUSING_COLUMN", + "ACS_LOCAL_GROUP_QUARTERS_HOUSING_ISSUE", + "ACS_LOCAL_GROUP_QUARTERS_HOUSING_METHOD", + "with_acs_local_group_quarters_housing", +] + +ACS_LOCAL_GROUP_QUARTERS_HOUSING_ISSUE = "microcosm#975" +ACS_LOCAL_GROUP_QUARTERS_HOUSING_COLUMN = "takes_up_housing_assistance_if_eligible" +ACS_LOCAL_GROUP_QUARTERS_HOUSING_METHOD = ( + "lane_own_step_after_shared_transfer_group_quarters_false" +) +#: ACS ``TYPEHUGQ``: 1 housing unit, 2 institutional and 3 noninstitutional +#: group quarters. +ACS_GROUP_QUARTERS_KINDS: tuple[int, ...] = (2, 3) +_HOUSEHOLD_KINDS = (1, *ACS_GROUP_QUARTERS_KINDS) +_KIND = "TYPEHUGQ" +_COLUMN = ACS_LOCAL_GROUP_QUARTERS_HOUSING_COLUMN + + +def _unit_kinds(frame: Frame) -> np.ndarray: + """``TYPEHUGQ`` of each SPM unit's household, aligned to the spm_unit table.""" + + household = frame.table("household") + person = frame.table("person") + spm_unit = frame.table("spm_unit") + missing = [ + f"household.{column}" + for column in ("household_id", _KIND) + if column not in household + ] + [ + f"person.{column}" + for column in ("person_spm_unit_id", "person_household_id") + if column not in person + ] + if "spm_unit_id" not in spm_unit: + missing.append("spm_unit.spm_unit_id") + if missing: + raise ValueError( + f"ACS group-quarters housing take-up requires {missing} " + f"({ACS_LOCAL_GROUP_QUARTERS_HOUSING_ISSUE})." + ) + unit_household = person.drop_duplicates("person_spm_unit_id").set_index( + "person_spm_unit_id" + )["person_household_id"] + kinds = pd.to_numeric(household.set_index("household_id")[_KIND], errors="coerce") + return pd.to_numeric( + spm_unit["spm_unit_id"].map(unit_household).map(kinds), errors="coerce" + ).to_numpy(dtype=np.float64) + + +def with_acs_local_group_quarters_housing( + frame: Frame, +) -> tuple[Frame, dict[str, Any]]: + """Set the housing take-up flag False on ACS group-quarters SPM units. + + Args: + frame: The ACS-only frame after the shared transfer. + + Returns: + The frame (with the flag False in group quarters) and a JSON-ready + receipt. + + Raises: + ValueError: If the frame is not US-schema or a column it reads is + absent. + """ + + if frame.schema != US_SCHEMA: + raise ValueError("ACS group-quarters housing take-up requires the US schema.") + spm_unit = frame.table("spm_unit") + if _COLUMN not in spm_unit: + raise ValueError( + f"ACS group-quarters housing take-up requires spm_unit.{_COLUMN}; the " + "shared transfer draws it " + f"({ACS_LOCAL_GROUP_QUARTERS_HOUSING_ISSUE})." + ) + kinds = _unit_kinds(frame) + unknown = ~np.isin(kinds, _HOUSEHOLD_KINDS) + group_quarters = np.isin(kinds, ACS_GROUP_QUARTERS_KINDS) + before = spm_unit[_COLUMN] + was_true = (before.notna() & before.astype(object).eq(True)).to_numpy(dtype=bool) + was_missing = before.isna().to_numpy(dtype=bool) + updated = spm_unit.copy() + values = before.astype(object).copy() + values.iloc[np.flatnonzero(group_quarters)] = False + updated[_COLUMN] = values.astype(bool) if values.notna().all() else values + tables = { + entity: updated if entity == "spm_unit" else frame.table(entity) + for entity in frame.entities + } + tables.update({name: frame.link(name) for name in frame.links}) + result = Frame( + tables, + frame.schema, + {entity: frame.weights_for(entity) for entity in frame.weighted_entities}, + frame.strata, + mass_log=frame.mass_log, + metadata=frame.metadata, + ) + by_kind = { + str(kind): { + "spm_units": int((kinds == kind).sum()), + "set_false_from_true": int(((kinds == kind) & was_true).sum()), + "set_false_from_missing": int(((kinds == kind) & was_missing).sum()), + } + for kind in ACS_GROUP_QUARTERS_KINDS + } + housing_units = kinds == 1 + receipt: dict[str, Any] = { + "issue": ACS_LOCAL_GROUP_QUARTERS_HOUSING_ISSUE, + "column": _COLUMN, + "method": ACS_LOCAL_GROUP_QUARTERS_HOUSING_METHOD, + "spine": ACS_2024_1YR_SPINE, + "rule": ( + f"{_COLUMN} = False on every SPM unit whose household has TYPEHUGQ 2 " + "or 3; housing units (TYPEHUGQ 1) keep the shared transfer's draw" + ), + "acs_spm_units": int(len(spm_unit)), + "group_quarters_spm_units": int(group_quarters.sum()), + "by_typehugq": by_kind, + "housing_unit_spm_units": int(housing_units.sum()), + "housing_unit_take_up_true": int((housing_units & was_true).sum()), + "unknown_typehugq_spm_units": int(unknown.sum()), + } + return result, receipt diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_reviewed_fill_consumers.yaml b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_reviewed_fill_consumers.yaml index 9348a5495f..dae7c4e9ad 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_reviewed_fill_consumers.yaml +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_reviewed_fill_consumers.yaml @@ -485,88 +485,6 @@ entries: capital_gains_behavioral_response, which read household_net_income, and the labor-supply elasticities they gate), which return 0 before reading anything in an engine pass without a reform; inert. - - entity: person - column: has_never_worked - fill_value: "False" - spines: [acs_2024_1yr] - rows: "every ACS person" - summary: >- - Read only by the FLSA overtime occupation category - (fsla_overtime_occupation_exemption_category), which reaches no means-tested - program. - consumers: [] - notes: [] - - entity: person - column: health_insurance_premiums - fill_value: "0" - spines: [acs_2024_1yr] - rows: "every ACS person" - summary: >- - A direct premium override. The statutory medical-expense aggregate - (medical_expense_health_insurance_premiums) reads 0 as not supplied and uses the - transferred health_insurance_premiums_without_medicare_part_b plus the modeled - Part B premium instead, and so does - medicaid_eligibility_health_insurance_premiums, which Medicaid's spend-down tests - read. The self-employed health insurance deduction, Missouri's child care subsidy, - Orange County general relief and a few state income taxes read it directly. - consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, - housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, - tanf, wic] - notes: - - programs: [eitc, medicaid] - verdict: known_bias - direction: understates - note: >- - Jointly with is_self_employed, also at its default on ACS rows: no ACS person - gets the self-employed health insurance deduction, so AGI and MAGI are - slightly too high for self-employed people who buy their own coverage (the - EITC phase-out reads AGI). - - programs: [aca_ptc, chip] - verdict: known_bias - direction: mixed - via: [medicaid] - note: >- - The same too-high MAGI lowers the PTC and CHIP eligibility directly, but it - also lifts some people above the Medicaid limit, and Medicaid eligibility bars - both the PTC (is_aca_marketplace_enrollee) and CHIP (is_chip_eligible_child), so those - people gain PTC or CHIP eligibility instead. - - programs: [lifeline, wic] - verdict: known_bias - direction: understates - via: [medicaid] - note: >- - Only through Medicaid enrollment (adjunctive eligibility); Lifeline's income - test reads IRS gross income, before the deduction. - - programs: [general_assistance, state_benefits] - verdict: known_bias - direction: understates - note: >- - Missouri's child care subsidy deducts only these premiums from gross income - (mo_ccs_adjusted_income) and Orange County general relief deducts them from - countable income, so at 0 both see slightly too much income. - - programs: [ctc, head_start, housing_assistance, school_meals, snap, tanf] - verdict: harmless - note: >- - SNAP's excess medical deduction and HUD's medical expenses read the - medical-expense aggregate, where 0 means not supplied, and so read the - transferred premiums. The remaining paths are second-order and negligible: - Missouri's smaller child care subsidy leaves slightly larger out-of-pocket - child care for the SNAP, HUD and Missouri TANF child-care deductions and the - CDCC ahead of the CTC; the CTC phases out only above $200,000 of AGI; Head - Start follows SNAP and TANF receipt; school meals also count SSI state - supplements, which this column moves only through a spouse's Medicaid - enrollment (Colorado OAP and AND-CS) and Illinois income tax withholding on - AGI (Illinois AABD). - - programs: [ssi] - verdict: harmless - note: >- - Reached only through the contributed COLA means test - (social_security_cola_means_test_withheld), which is False unless - gov.contrib.ssa.benefit_levers.cola.means_test.enabled, and the behavioral - responses (labor_supply_behavioral_response and - capital_gains_behavioral_response, which read household_net_income, and the - labor-supply elasticities they gate), which return 0 before reading anything - in an engine pass without a reform; inert. - entity: person column: hourly_wage fill_value: "0" @@ -575,17 +493,6 @@ entries: summary: "No policyengine-us 2.145.3 variable reads it." consumers: [] notes: [] - - entity: person - column: is_computer_scientist - fill_value: "False" - spines: [acs_2024_1yr] - rows: "every ACS person" - summary: >- - Read only by the FLSA overtime occupation category - (fsla_overtime_occupation_exemption_category), which reaches no means-tested - program. - consumers: [] - notes: [] - entity: person column: is_enrolled_at_least_half_time_for_american_opportunity_credit fill_value: "False" @@ -647,28 +554,6 @@ entries: capital_gains_behavioral_response, which read household_net_income, and the labor-supply elasticities they gate), which return 0 before reading anything in an engine pass without a reform; inert. - - entity: person - column: is_executive_administrative_professional - fill_value: "False" - spines: [acs_2024_1yr] - rows: "every ACS person" - summary: >- - Read only by the FLSA overtime occupation category - (fsla_overtime_occupation_exemption_category), which reaches no means-tested - program. - consumers: [] - notes: [] - - entity: person - column: is_farmer_fisher - fill_value: "False" - spines: [acs_2024_1yr] - rows: "every ACS person" - summary: >- - Read only by the FLSA overtime occupation category - (fsla_overtime_occupation_exemption_category), which reaches no means-tested - program. - consumers: [] - notes: [] - entity: person column: is_hispanic fill_value: "False" @@ -691,90 +576,6 @@ entries: the reviewed default 0 on the same rows. consumers: [] notes: [] - - entity: person - column: is_military - fill_value: "False" - spines: [acs_2024_1yr] - rows: "every ACS person" - summary: >- - Active-duty status; ACS MIL == 1 could fill it natively. SNAP's five-year bar - exempts a military-connected qualified alien, their spouse and their dependent - children (is_snap_alien_military_connected); Missouri SSP's immigrant waiver, the - 2020-2021 recovery rebate credits' armed-forces exception, the FLSA overtime - occupation category, Indiana EAP and Utah HEAT read it too. - consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, - housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, - tanf, wic] - notes: - - programs: [snap] - verdict: known_bias - direction: mixed - note: >- - ACS active-duty members inside the five-year bar, and their spouses and - dependent children, lose the military-connected exception (8 U.S.C. - 1612(a)(2)(C), is_snap_alien_military_connected), so the bar excludes them. A - unit whose members are all inside the bar loses SNAP; in a unit that keeps an - exempt member, such as a child under 18, the barred adults' income is prorated - (7 CFR 273.11(c)(2)), which can raise or lower its allotment. - - programs: [lifeline] - verdict: known_bias - direction: understates - via: [snap] - note: >- - Only through SNAP receipt, which only a unit whose members are all inside the - bar loses, and only where it is the unit's only route: Lifeline's own income - test is 135% of FPG (150% in Texas). - - programs: [state_benefits] - verdict: harmless - note: >- - California CARE (categorical through CalFresh), Los Angeles EZ-SAVE and - Missouri SSP pay nothing on these files: CARE and EZ-SAVE need an electricity - expense, and Missouri SSP a living arrangement, which no stage writes. Its - other state-benefit routes run only through Medicaid enrollment, which the - Medicaid note below rules nil. - - programs: [head_start, school_meals, wic] - verdict: harmless - note: >- - A unit with a child keeps SNAP receipt through the child, whom the five-year - bar exempts under 18, so Head Start and school-meal categorical eligibility do - not change; WIC's 185% income test passes for any SNAP-income-eligible unit. - Missouri SSP's immigrant waiver needs a living arrangement no stage produces. - - programs: [aca_ptc, chip, medicaid] - verdict: harmless - note: >- - Only through SNAP's community-engagement pass-through, which applies from 2027 - (gov.hhs.medicaid.eligibility.work_requirements.applies), and the 2020-2021 - recovery rebate credits, whose maximums are 0 from 2022. The SNAP change - removes receipt only from a unit whose members are all inside the five-year - bar, and Medicaid's own five-year bar already excludes them (no military - exemption is modeled). CHIP reads Medicaid eligibility only for children and - pregnant people, whom the work requirement exempts; the PTC follows Medicaid. - - programs: [ctc, general_assistance] - verdict: harmless - note: >- - Only through the armed-forces exception of the 2020 and 2021 recovery rebate - credits, whose maximums are 0 from 2022. - - programs: [eitc, housing_assistance, tanf] - verdict: harmless - note: >- - Reached only through the 2020-only charitable deduction for non-itemizers - (charitable_contributions_ald), which is 0 before it reads anything in any - other year, and the behavioral responses (labor_supply_behavioral_response and - capital_gains_behavioral_response, which read household_net_income, and the - labor-supply elasticities they gate), which return 0 before reading anything - in an engine pass without a reform; inert. - - programs: [ssi] - verdict: harmless - note: >- - Reached only through the 2020-only charitable deduction for non-itemizers - (charitable_contributions_ald), which is 0 before it reads anything in any - other year, and/or the contributed COLA means test - (social_security_cola_means_test_withheld), which is False unless - gov.contrib.ssa.benefit_levers.cola.means_test.enabled, and the behavioral - responses (labor_supply_behavioral_response and - capital_gains_behavioral_response, which read household_net_income, and the - labor-supply elasticities they gate), which return 0 before reading anything - in an engine pass without a reform; inert. - entity: person column: is_paid_hourly fill_value: "False" @@ -860,160 +661,6 @@ entries: capital_gains_behavioral_response, which read household_net_income, and the labor-supply elasticities they gate), which return 0 before reading anything in an engine pass without a reform; inert. - - entity: person - column: is_self_employed - fill_value: "False" - spines: [acs_2024_1yr] - rows: "every ACS person" - summary: >- - Read only as the defined_for condition of self_employed_health_insurance_premiums - and self_employed_long_term_care_premiums, the inputs to the self-employed health - insurance deduction. ACS COW 6/7 could fill it natively, but the deduction also - needs health_insurance_premiums, which is 0 on ACS rows, or long-term care - premiums, which no stage produces. - consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, - housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, - tanf, wic] - notes: - - programs: [eitc, medicaid] - verdict: known_bias - direction: understates - note: >- - Jointly with health_insurance_premiums, also at its default on ACS rows: no - ACS person gets the self-employed health insurance deduction, so AGI and MAGI - are slightly too high for self-employed people who buy their own coverage (the - EITC phase-out reads AGI). - - programs: [aca_ptc, chip] - verdict: known_bias - direction: mixed - via: [medicaid] - note: >- - The same too-high MAGI lowers the PTC and CHIP eligibility directly, but it - also lifts some people above the Medicaid limit, and Medicaid eligibility bars - both the PTC (is_aca_marketplace_enrollee) and CHIP (is_chip_eligible_child), so those - people gain PTC or CHIP eligibility instead. - - programs: [lifeline, wic] - verdict: known_bias - direction: understates - via: [medicaid] - note: >- - Only through Medicaid enrollment (adjunctive eligibility); Lifeline's income - test reads IRS gross income, before the deduction. - - programs: [state_benefits] - verdict: known_bias - direction: understates - note: >- - State programs reached through AGI or MAGI see too much income for - self-employed people who buy their own coverage; which of those routes move a - benefit is not reviewed yet (microcosm#1720). - - programs: [ctc, general_assistance, head_start, housing_assistance, - school_meals, snap, tanf] - verdict: harmless - note: >- - They count self-employment income before this deduction and read AGI only - through Medicare IRMAA (AGI two years prior, above $103,000 for a single filer - in 2024, far above their limits), the 2020-only unemployment exclusion - (taxable_uc_agi) and South Carolina TANF's count of taxable Social Security; - the CTC phases out only above $200,000 of AGI. All negligible. School meals - also count SSI state supplements: Illinois AABD deducts Illinois income tax - withholding, which reads AGI, and Colorado OAP and AND-CS read a spouse's - Medicaid enrollment, which the MAGI above moves; DC TANF reads filing status, - which a dependent's gross income can move. All second-order. - - programs: [ssi] - verdict: harmless - note: >- - Reached only through the contributed COLA means test - (social_security_cola_means_test_withheld), which is False unless - gov.contrib.ssa.benefit_levers.cola.means_test.enabled, and the behavioral - responses (labor_supply_behavioral_response and - capital_gains_behavioral_response, which read household_net_income, and the - labor-supply elasticities they gate), which return 0 before reading anything - in an engine pass without a reform; inert. - - entity: person - column: is_separated - fill_value: "False" - spines: [acs_2024_1yr] - rows: "every ACS person" - summary: >- - ACS MAR 4 (separated) is not mapped, so every ACS person reads as not separated. - policyengine-us uses the flag for the separate filing status (a separated head - without a qualifying child files separately), the IRC 7703(b) head-of-household - path, and to stop any member of a separated person's tax unit from being ranked - the tax-unit spouse. A native fill from MAR is a follow-up. - consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, - housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, - tanf, wic] - notes: - - programs: [aca_ptc] - verdict: known_bias - direction: mixed - via: [medicaid] - note: >- - Mostly overstated: separated ACS filers without a qualifying child file single - instead of separately, so the PTC's separate-filer bar (is_aca_ptc_eligible) - never applies to them. The Medicaid changes below move the PTC the other way - for some units, because Medicaid eligibility bars it (is_aca_marketplace_enrollee). - - programs: [chip, ctc, eitc, general_assistance, housing_assistance, medicaid, - snap, ssi, tanf] - verdict: known_bias - direction: mixed - note: >- - Filing status and the tax-unit spouse role change: a separated head's unit - files single or head of household instead of separately, and another adult in - the unit can be ranked the tax-unit spouse (is_tax_unit_spouse), which moves - joint thresholds, SSI spousal deeming, SNAP and TANF dependency rules, HUD - dependents and Los Angeles and Marin general relief marital rules. ACS MAR 4 - persons have no spouse in the household, so this matters only in units that - hold another adult. - - programs: [head_start, lifeline, school_meals, state_benefits, wic] - verdict: known_bias - direction: mixed - via: [medicaid, snap, ssi, tanf] - note: >- - Only through Medicaid, SNAP, SSI and TANF results; the state supplements in - household_state_benefits and in school-meal income also apply SSI's spousal - rules to the same tax-unit roles. - - entity: person - column: is_surviving_spouse - fill_value: "False" - spines: [acs_2024_1yr] - rows: "every ACS person" - summary: >- - Not mapped from ACS MAR 2 (widowed), so no ACS head qualifies for the - surviving-spouse filing status (surviving_spouse_eligible also needs a child - dependent); such heads file as head of household. The status needs a death in the - two prior years, which ACS MARHW (widowed in the past 12 months) only - approximates. - consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, - housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, - tanf, wic] - notes: - - programs: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, - housing_assistance, lifeline, medicaid, school_meals, snap, state_benefits, - tanf, wic] - verdict: harmless - note: >- - These programs read filing status only as joint or separate (the PTC's - separate-filer bar, Medicaid's head-and-spouse count and MAGI, DC TANF's - single-parent exemption, Massachusetts TAFDC), through Medicare IRMAA - thresholds (above $103,000 for a single filer in 2024) or California's CVRP - income caps (above $135,000), and surviving spouse versus head of household - moves none of them. The CTC sees only the tax-liability difference, for the - few recently widowed parents whose liability limits it; negligible. The one - exception is the filing threshold: a surviving spouse's is the joint one, so - as head of household a unit counts as required to file at a lower income, - which moves the filer flag, and Medicaid's non-filer rules, only for a - recently widowed parent with no earnings and no refundable credit; negligible. - - programs: [ssi] - verdict: harmless - note: >- - Reached only through the contributed COLA means test - (social_security_cola_means_test_withheld), which is False unless - gov.contrib.ssa.benefit_levers.cola.means_test.enabled, and the behavioral - responses (labor_supply_behavioral_response and - capital_gains_behavioral_response, which read household_net_income, and the - labor-supply elasticities they gate), which return 0 before reading anything - in an engine pass without a reform; inert. - entity: person column: is_union_member_or_covered fill_value: "False" @@ -1202,88 +849,6 @@ entries: capital_gains_behavioral_response, which read household_net_income, and the labor-supply elasticities they gate), which return 0 before reading anything in an engine pass without a reform; inert. - - entity: person - column: roth_401k_contributions_desired - fill_value: "0" - spines: [acs_2024_1yr] - rows: "every ACS person" - summary: >- - Desired Roth 401(k) deferrals; the ACS has no retirement contribution item. Roth - deferrals do not reduce AGI; they share the 402(g) scale with traditional - deferrals (also 0 on ACS rows) and count for the saver's credit. - consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, - housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, - tanf, wic] - notes: - - programs: [ctc] - verdict: known_bias - direction: overstates - note: >- - No saver's credit for Roth deferrals on ACS rows, so tax liability is too high - and leaves more room for the nonrefundable CTC; weak, for low-income savers. - - programs: [aca_ptc, chip, eitc, general_assistance, head_start, - housing_assistance, lifeline, medicaid, school_meals, snap, state_benefits, - tanf, wic] - verdict: harmless - note: >- - Roth deferrals do not reduce AGI or MAGI, and the 402(g) scale is inert while - traditional deferrals are also 0 on ACS rows. The saver's credit reaches these - programs only through the tax-liability chain, which cannot flip the filer - flag of a unit not already required to file. Roth deferrals to an employer - plan also leave less room for a self-employed person's own plan deduction - (self_employed_pension_contribution_limit), which binds only for self-employed - savers contributing at the limit; negligible. - - programs: [ssi] - verdict: harmless - note: >- - Reached only through the contributed COLA means test - (social_security_cola_means_test_withheld), which is False unless - gov.contrib.ssa.benefit_levers.cola.means_test.enabled, and the behavioral - responses (labor_supply_behavioral_response and - capital_gains_behavioral_response, which read household_net_income, and the - labor-supply elasticities they gate), which return 0 before reading anything - in an engine pass without a reform; inert. - - entity: person - column: roth_ira_contributions_desired - fill_value: "0" - spines: [acs_2024_1yr] - rows: "every ACS person" - summary: >- - Desired Roth IRA contributions; the ACS has no retirement contribution item. Roth - contributions do not reduce AGI; they share the annual IRA limit with the - transferred traditional IRA contributions (ira_contribution_scale) and count for - the saver's credit. - consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, - housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, - tanf, wic] - notes: - - programs: [ctc] - verdict: known_bias - direction: overstates - note: >- - No saver's credit for Roth IRA contributions on ACS rows, so tax liability is - too high and leaves more room for the nonrefundable CTC; weak, for low-income - savers. - - programs: [aca_ptc, chip, eitc, general_assistance, head_start, - housing_assistance, lifeline, medicaid, school_meals, snap, state_benefits, - tanf, wic] - verdict: harmless - note: >- - Roth contributions do not reduce AGI or MAGI. The shared IRA limit scales - traditional contributions down only when desired Roth plus traditional - contributions exceed it ($7,000 in 2024), rare at these programs' incomes; the - saver's credit reaches them only through the tax-liability chain, which cannot - flip the filer flag of a unit not already required to file. - - programs: [ssi] - verdict: harmless - note: >- - Reached only through the contributed COLA means test - (social_security_cola_means_test_withheld), which is False unless - gov.contrib.ssa.benefit_levers.cola.means_test.enabled, and the behavioral - responses (labor_supply_behavioral_response and - capital_gains_behavioral_response, which read household_net_income, and the - labor-supply elasticities they gate), which return 0 before reading anything - in an engine pass without a reform; inert. - entity: person column: s_corp_income fill_value: "0" @@ -1503,72 +1068,6 @@ entries: capital_gains_behavioral_response, which read household_net_income, and the labor-supply elasticities they gate), which return 0 before reading anything in an engine pass without a reform; inert. - - entity: person - column: traditional_401k_contributions_desired - fill_value: "0" - spines: [acs_2024_1yr] - rows: "every ACS person" - summary: >- - Desired traditional 401(k) deferrals; the ACS has no retirement contribution item, - and WAGP is gross of deferrals. At 0, irs_employment_income, AGI and MAGI include - wages that savers defer. - consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, - housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, - tanf, wic] - notes: - - programs: [eitc, lifeline, medicaid, state_benefits] - verdict: known_bias - direction: understates - note: >- - MAGI (Medicaid), AGI (the EITC phase-out) and IRS gross income (Lifeline) are - too high for workers who defer wages, so their eligibility and amounts are - understated. EITC earned income is gross of deferrals, so only the phase-out - moves. State programs reached through those measures see the same; which of - their routes move a benefit is not reviewed yet (microcosm#1720). - - programs: [aca_ptc, chip] - verdict: known_bias - direction: mixed - via: [medicaid] - note: >- - Too-high MAGI lowers the PTC and CHIP eligibility directly, but it also lifts - some workers' households above the Medicaid limit, and Medicaid eligibility - bars both the PTC (is_aca_marketplace_enrollee) and CHIP (is_chip_eligible_child), so - those households gain PTC or CHIP eligibility instead. - - programs: [ctc] - verdict: known_bias - direction: mixed - note: >- - Higher AGI phases the CTC out only above $200,000, while higher tax, and the - missing saver's credit, leave more room for its nonrefundable part. - - programs: [wic] - verdict: known_bias - direction: understates - via: [medicaid] - note: "WIC counts gross income; only adjunctive eligibility through Medicaid." - - programs: [general_assistance, head_start, housing_assistance, school_meals, - snap, tanf] - verdict: harmless - note: >- - They count wages gross of deferrals (employment_income). The AGI paths reach - them only through Medicare IRMAA (above $103,000 of MAGI for a single filer in - 2024), the 2020-only unemployment exclusion and South Carolina TANF's count of - taxable Social Security; Los Angeles General Relief reads - irs_employment_income, but its applicants rarely defer wages. All negligible. - School meals also count SSI state supplements: Illinois AABD deducts Illinois - income tax withholding, which reads AGI, and Colorado OAP and AND-CS read a - spouse's Medicaid enrollment, which Medicaid's filing test on - irs_employment_income moves; DC TANF reads filing status, which a dependent's - gross income can move. All second-order. - - programs: [ssi] - verdict: harmless - note: >- - Reached only through the contributed COLA means test - (social_security_cola_means_test_withheld), which is False unless - gov.contrib.ssa.benefit_levers.cola.means_test.enabled, and the behavioral - responses (labor_supply_behavioral_response and - capital_gains_behavioral_response, which read household_net_income, and the - labor-supply elasticities they gate), which return 0 before reading anything - in an engine pass without a reform; inert. - entity: person column: treasury_tipped_occupation_code fill_value: "0" @@ -1609,76 +1108,6 @@ entries: capital_gains_behavioral_response, which read household_net_income, and the labor-supply elasticities they gate), which return 0 before reading anything in an engine pass without a reform; inert. - - entity: person - column: weeks_unemployed - fill_value: "0" - spines: [acs_2024_1yr] - rows: "every ACS person" - summary: >- - Weeks of unemployment; the ACS asks none. They set the months of UC receipt - (unemployment_compensation_months, 12 when weeks are 0 and UC is positive), which - exempt a recipient from SNAP work registration and so from the ABAWD time limit, - and they feed the Alabama, New York, Oklahoma and Pennsylvania unemployment - benefit calculators, whose claim-wage inputs no stage produces. - consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, - housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, - tanf, wic] - notes: - - programs: [snap] - verdict: known_bias - direction: overstates - note: >- - With weeks 0 a UC recipient is exempt from SNAP work registration, and so from - the ABAWD time limit, in all 12 months; with true weeks only in the months of - receipt. In 2024 that frees ABAWD-age adults (18 to 52, 18 to 54 from October - 2024) with no household member under 18 (under 14 from 2025-07-04), working - under 20 hours a week, outside waived areas. - - programs: [medicaid] - verdict: known_bias - direction: understates - note: >- - No effect for 2024. From 2027 Medicaid's work requirement applies - (gov.hhs.medicaid.eligibility.work_requirements.applies), and its SNAP - community-engagement pass-through needs a SNAP recipient who is subject to a - SNAP work requirement. With weeks 0 a UC recipient is exempt from SNAP work - registration in every month, so loses the pass-through; the fill never adds - one. - - programs: [aca_ptc] - verdict: known_bias - direction: mixed - via: [medicaid] - note: >- - No effect for 2024, and none in practice from 2027: an adult the Medicaid path - above leaves without Medicaid fails only the work requirement, which bars the - Marketplace too (is_medicaid_ineligible_due_to_work_requirement in - gov.aca.ineligible_coverage), and the requirement binds only below its income - test, under the PTC's income floor. Kept known_bias because - REVIEWED_FILL_COUPLINGS requires it wherever Medicaid is. - - programs: [head_start, lifeline, school_meals, state_benefits, wic] - verdict: harmless - note: >- - The ABAWD time limit skips SNAP units with a member under 18 (14 from - 2025-07-04) or a pregnant member, so it never reaches the units Head Start and - WIC serve. Lifeline, California CARE (through CalFresh) and school meals read - SNAP receipt over the year, which the months of receipt keep. From 2027 the - Medicaid change reaches only SNAP recipients, who keep Lifeline through SNAP, - and adults outside WIC's categories; CVRP's increased rebate has its own - income test, and school meals read Medicaid enrollment only second-order, - through state supplements. - - programs: [chip] - verdict: harmless - note: >- - Only through Medicaid eligibility, for children and pregnant people, whom the - Medicaid work requirement exempts, and through the modeled state UI programs, - whose claim-wage inputs no stage produces. - - programs: [ctc, eitc, general_assistance, housing_assistance, ssi, tanf] - verdict: harmless - note: >- - Reached only through the modeled state UI programs - (gov.states.household.modeled_state_unemployment_compensation), whose monetary - eligibility needs base-period and quarterly wage inputs that default to 0 and - no stage produces (test_us_weeks_unemployed.py), so they pay nothing on ACS - rows; total_unemployment_compensation also prefers the reported amount. - entity: person column: weeks_worked fill_value: "0" @@ -2253,134 +1682,6 @@ entries: capital_gains_behavioral_response, which read household_net_income, and the labor-supply elasticities they gate), which return 0 before reading anything in an engine pass without a reform; inert. - - entity: tax_unit - column: selected_marketplace_plan_benchmark_ratio - fill_value: "1.0" - spines: [acs_2024_1yr] - rows: "every ACS tax unit" - summary: >- - Read only by monthly_selected_marketplace_plan_premium_proxy, which - selected_marketplace_plan_premium_proxy sums, a net-premium proxy; the premium tax - credit reads the benchmark (SLCSP) premium, not the selected plan. The proxy - reaches the programs only through household health costs, household_net_income and - the behavioral responses. - consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, - housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, - tanf, wic] - notes: - - programs: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, - housing_assistance, lifeline, medicaid, school_meals, snap, ssi, - state_benefits, tanf, wic] - verdict: harmless - note: >- - Reached only through the behavioral responses - (labor_supply_behavioral_response and capital_gains_behavioral_response, which - read household_net_income, and the labor-supply elasticities they gate), which - return 0 before reading anything in an engine pass without a reform, as every - release pass is; inert. - - entity: tax_unit - column: takes_up_aca_if_eligible - fill_value: "True" - spines: [acs_2024_1yr] - rows: "every ACS tax unit" - summary: >- - Runtime-owned take-up flag, not seeded on ACS rows (reviewed limitation - acs_take_up_engine_defaults). - consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, - housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, - tanf, wic] - notes: - - programs: [aca_ptc] - verdict: known_bias - direction: overstates - note: >- - Universal take-up: assigned_aca_ptc is the full credit for every eligible ACS - unit, while donor rows carry the seeded draw. - - programs: [chip, ctc, eitc, general_assistance, head_start, housing_assistance, - lifeline, medicaid, school_meals, snap, ssi, state_benefits, tanf, wic] - verdict: harmless - note: >- - Reached only through the behavioral responses - (labor_supply_behavioral_response and capital_gains_behavioral_response, which - read household_net_income, and the labor-supply elasticities they gate), which - return 0 before reading anything in an engine pass without a reform, as every - release pass is; inert. - - entity: tax_unit - column: would_file_taxes_voluntarily - fill_value: "False" - spines: [acs_2024_1yr] - rows: "every ACS tax unit" - summary: >- - Voluntary-filing propensity, which donor rows carry (voluntary_filing) and ACS - rows do not. It feeds the filer flag and the EITC's filing condition. - consumers: [aca_ptc, chip, ctc, eitc, general_assistance, head_start, - housing_assistance, lifeline, medicaid, school_meals, snap, ssi, state_benefits, - tanf, wic] - notes: - - programs: [eitc] - verdict: harmless - note: >- - The EITC's own filing test passes for every unit: - would_file_if_eligible_for_refundable_credit is the engine default True on - every row, so voluntary filing never decides the credit. - - programs: [aca_ptc] - verdict: known_bias - direction: mixed - via: [medicaid] - note: >- - No direct effect on ACS rows: files_return_for_aca_ptc counts a unit that - takes up a positive credit as filing for it, and takes_up_aca_if_eligible is - the reviewed default True on every ACS unit. Only through Medicaid's non-filer - rules below, which move the PTC either way because Medicaid eligibility keeps - a person off the Marketplace. - - programs: [chip, medicaid] - verdict: known_bias - direction: mixed - note: >- - Fewer ACS units count as filers, so Medicaid's non-filer household rules apply - to more of them; the direction depends on the household. - - programs: [lifeline, state_benefits, wic] - verdict: known_bias - direction: mixed - via: [medicaid] - note: "Only through Medicaid enrollment." - - programs: [ctc, general_assistance] - verdict: harmless - note: >- - The CTC reads the EITC only in the additional CTC's alternative phase-in for - three or more children; county general assistance reads only income tax - withholding. Negligible. - - programs: [head_start, school_meals, snap] - verdict: harmless - note: >- - Second-order and negligible: only through the Medicaid enrollment of a - Colorado OAP or AND-CS client's spouse (or, for AND-CS, parent), which can lift - the deeming and - so change the grant that SNAP counts as unearned income and school meals count - as income (Head Start follows SNAP receipt); the other state supplements that - read Medicaid enrollment need facility or certification inputs no stage - produces, and the California CARE route into Illinois AABD crosses states. - - programs: [housing_assistance, tanf] - verdict: harmless - note: >- - Reached only through the 2020-only charitable deduction for non-itemizers - (charitable_contributions_ald), which is 0 before it reads anything in any - other year, and the behavioral responses (labor_supply_behavioral_response and - capital_gains_behavioral_response, which read household_net_income, and the - labor-supply elasticities they gate), which return 0 before reading anything - in an engine pass without a reform; inert. - - programs: [ssi] - verdict: harmless - note: >- - Reached only through the 2020-only charitable deduction for non-itemizers - (charitable_contributions_ald), which is 0 before it reads anything in any - other year, and/or the contributed COLA means test - (social_security_cola_means_test_withheld), which is False unless - gov.contrib.ssa.benefit_levers.cola.means_test.enabled, and the behavioral - responses (labor_supply_behavioral_response and - capital_gains_behavioral_response, which read household_net_income, and the - labor-supply elasticities they gate), which return 0 before reading anything - in an engine pass without a reform; inert. - entity: spm_unit column: spm_unit_energy_subsidy fill_value: "0" @@ -2412,15 +1713,16 @@ entries: tanf, wic] notes: - programs: [housing_assistance] - verdict: known_bias - direction: overstates + verdict: harmless note: >- Group-quarters units pass HUD's renter test - (is_eligible_for_housing_assistance). With pre_subsidy_rent 0 their gross rent - is the HUD utility allowance, which policyengine-us encodes only for Los - Angeles County, the Texas TDHCA area and four Kansas PHAs, so a payment arises - only there, and only where the transferred housing take-up flag is True - (microcosm#975). + (is_eligible_for_housing_assistance), but housing_assistance is hud_hap times + takes_up_housing_assistance_if_eligible, and staging sets that flag False on + every group-quarters SPM unit (microcosm#975, acs_local_group_quarters_housing), + so no payment arises. Before that step a payment could arise where the + transferred flag was True and policyengine-us encodes a HUD utility allowance + (Los Angeles County, the Texas TDHCA area and four Kansas PHAs). The verdict + holds while staging writes the flag False there. - programs: [aca_ptc, chip, ctc, general_assistance, head_start, lifeline, medicaid, school_meals, snap, state_benefits, wic] verdict: harmless diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_se_health_premiums.py b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_se_health_premiums.py new file mode 100644 index 0000000000..1c68e83faf --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_se_health_premiums.py @@ -0,0 +1,300 @@ +"""Self-employed health insurance inputs of ACS rows (ACS local lane). + +``is_self_employed`` and ``health_insurance_premiums`` reached the ACS +local-area release missing on every ACS row, and the reviewed-null fill gave +them the engine defaults, ``False`` and 0 (microcosm#1720). No ACS person +could then take the self-employed health insurance deduction, so AGI and MAGI +were too high for self-employed people who buy their own coverage. + +This fresh-build stage runs the donor's own rule, +:func:`~microcosm.build.us_runtime.other_health_insurance.attribute_us_se_health_premiums`, +unchanged, on the ACS-only frame after the shared transfer: + +- **The flag** marks every person with strictly positive combined Schedule C + income (``self_employment_income_before_lsr`` + + ``sstb_self_employment_income_before_lsr``), the donor's rule. It is not ACS + ``COW`` 6 or 7; the receipt records how often the two agree. +- **The premium** copies the transferred + ``health_insurance_premiums_without_medicare_part_b`` for a flagged person + outside the Medicare proxy (age 65+ or any Social Security disability) and + without employer-sponsored coverage (``has_esi``), and is 0 elsewhere. +- **Inputs.** The self-employment total is native ACS ``SEMP``, blank under + 15, which reads as 0 here, the reviewed fill's value. The SSTB component, the + premium and Social Security disability come from the shared transfer, whose + post-transfer structure (``_apply_post_transfer_structure``) has already + zeroed the self-employment components where ``SEMP`` stands, so the stage + must run after it. ``has_esi`` is ACS ``HINS1`` on the local lane: the + coverage step (:mod:`~.acs_local_coverage_anchors`) writes it over the + transferred draw first. +- **Null cells only.** A stored ACS value stands; donor rows are never seen. + +With this stage the ACS rows' MAGI is final before the release tool assigns +Medicaid (and any later ACA) take-up. The national build applies the +attribution in another order (microcosm#1689). The stage records a receipt +and refuses only inputs the rule cannot read. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +import numpy as np +import pandas as pd + +from microcosm.build.source_runtime import SourceRuntimeError +from microcosm.build.us_runtime.acs_pums import ACS_2024_1YR_SPINE +from microcosm.build.us_runtime.other_health_insurance import ( + US_SE_HEALTH_ATTRIBUTION_OUTPUT_COLUMNS, + US_SE_HEALTH_MEDICARE_AGE_THRESHOLD, + US_SE_HEALTH_SELF_EMPLOYMENT_INCOME_SOURCES, + attribute_us_se_health_premiums, +) +from microcosm.frame import Frame +from microcosm.frame.units import US_SCHEMA + +__all__ = [ + "ACS_LOCAL_SE_HEALTH_PREMIUM_COLUMNS", + "ACS_LOCAL_SE_HEALTH_PREMIUMS_ISSUE", + "ACS_LOCAL_SE_HEALTH_PREMIUMS_METHOD", + "ACS_LOCAL_SE_HEALTH_PREMIUMS_SOURCE_COLUMNS", + "with_acs_local_se_health_premiums", +] + +ACS_LOCAL_SE_HEALTH_PREMIUMS_ISSUE = "microcosm#1720" +ACS_LOCAL_SE_HEALTH_PREMIUMS_METHOD = ( + "donor_attribute_us_se_health_premiums_after_shared_transfer_missing_cells_only" +) +#: ``("health_insurance_premiums", "is_self_employed")``. +ACS_LOCAL_SE_HEALTH_PREMIUM_COLUMNS: tuple[str, ...] = ( + US_SE_HEALTH_ATTRIBUTION_OUTPUT_COLUMNS +) +_PREMIUMS, _FLAG = ACS_LOCAL_SE_HEALTH_PREMIUM_COLUMNS +_SELF_EMPLOYMENT, _SSTB = US_SE_HEALTH_SELF_EMPLOYMENT_INCOME_SOURCES +_REPORTED = "health_insurance_premiums_without_medicare_part_b" +_AGE = "age" +_SSDI = "social_security_disability" +_ESI = "has_esi" +#: The person columns the donor's rule reads, in its own names. +ACS_LOCAL_SE_HEALTH_PREMIUMS_SOURCE_COLUMNS: tuple[str, ...] = ( + _REPORTED, + _SELF_EMPLOYMENT, + _SSTB, + _AGE, + _SSDI, + _ESI, +) +#: ACS asks SEMP from age 15; below it the Census blank is the universe. +_SELF_EMPLOYMENT_MINIMUM_AGE = 15 +_CLASS_OF_WORKER = "COW" +#: ACS COW 6 (self-employed, not incorporated) and 7 (incorporated). +_SELF_EMPLOYED_COW_CODES = (6, 7) +_RULE = ( + "is_self_employed: self_employment_income_before_lsr + " + "sstb_self_employment_income_before_lsr > 0; health_insurance_premiums: " + "health_insurance_premiums_without_medicare_part_b where flagged, under " + f"{US_SE_HEALTH_MEDICARE_AGE_THRESHOLD}, with no Social Security disability " + "and no has_esi, else 0 (other_health_insurance." + "attribute_us_se_health_premiums, unchanged)" +) + + +def _weighted_share(weights: np.ndarray, flags: np.ndarray) -> float: + total = float(weights.sum()) + return float(weights[flags].sum()) / total if total > 0 else 0.0 + + +def _boolean_view(values: pd.Series, column: str) -> np.ndarray: + if values.isna().any() or not values.isin([0, 1]).all(): + raise ValueError( + f"ACS {column} must be a complete boolean after the shared transfer " + f"({ACS_LOCAL_SE_HEALTH_PREMIUMS_ISSUE})." + ) + return values.astype(bool).to_numpy(dtype=bool) + + +def _rule_view(person: pd.DataFrame) -> tuple[pd.DataFrame, int]: + """The donor rule's inputs on ACS rows; the SEMP blank under 15 reads 0. + + Returns the view and how many under-15 blanks read as 0. + + Raises: + ValueError: If a column is absent, an age is missing, a blank sits in + SEMP's universe (15+) or in a transferred amount, or ``has_esi`` + is not a complete boolean. + """ + + missing = [ + column + for column in ACS_LOCAL_SE_HEALTH_PREMIUMS_SOURCE_COLUMNS + if column not in person + ] + if missing: + raise ValueError( + f"ACS self-employed health premiums require person column(s) {missing}; " + "they come from the native mapping and the shared transfer " + f"({ACS_LOCAL_SE_HEALTH_PREMIUMS_ISSUE})." + ) + age = pd.to_numeric(person[_AGE], errors="coerce") + if age.isna().any(): + raise ValueError("ACS self-employed health premiums require every age.") + view = pd.DataFrame(index=person.index) + view[_AGE] = age.to_numpy(dtype=np.float64) + self_employment = pd.to_numeric(person[_SELF_EMPLOYMENT], errors="coerce") + universe_blank = self_employment.isna() & age.ge(_SELF_EMPLOYMENT_MINIMUM_AGE) + if universe_blank.any(): + raise ValueError( + f"{int(universe_blank.sum())} ACS person(s) aged " + f"{_SELF_EMPLOYMENT_MINIMUM_AGE}+ have a blank {_SELF_EMPLOYMENT}." + ) + under_age_blanks = int(self_employment.isna().sum()) + view[_SELF_EMPLOYMENT] = self_employment.fillna(0.0).to_numpy(dtype=np.float64) + for column in (_SSTB, _REPORTED, _SSDI): + values = pd.to_numeric(person[column], errors="coerce") + if values.isna().any(): + raise ValueError( + f"{int(values.isna().sum())} ACS person(s) have a blank " + f"transferred {column}; the shared transfer must fill every ACS " + "row before this stage runs." + ) + view[column] = values.to_numpy(dtype=np.float64) + view[_ESI] = _boolean_view(person[_ESI], _ESI) + return view, under_age_blanks + + +def _fill_missing( + person: pd.DataFrame, column: str, values: np.ndarray +) -> tuple[int, int]: + """Write ``values`` into the missing cells of ``column``; keep the rest.""" + + if column not in person: + person[column] = values + return len(values), 0 + present = person[column].notna().to_numpy(dtype=bool) + merged = ( + person[column] + .astype(object) + .where(present, pd.Series(values, index=person.index)) + ) + person[column] = merged.astype(values.dtype) + return int((~present).sum()), int(present.sum()) + + +def _cow_agreement(person: pd.DataFrame, flag: np.ndarray) -> dict[str, Any]: + if _CLASS_OF_WORKER not in person: + return {"loaded": False} + cow = pd.to_numeric(person[_CLASS_OF_WORKER], errors="coerce") + self_employed_cow = cow.isin(_SELF_EMPLOYED_COW_CODES).to_numpy(dtype=bool) + return { + "loaded": True, + "cow_codes": list(_SELF_EMPLOYED_COW_CODES), + "both_rows": int((flag & self_employed_cow).sum()), + "flag_only_rows": int((flag & ~self_employed_cow).sum()), + "cow_only_rows": int((~flag & self_employed_cow).sum()), + "cow_blank_rows": int(cow.isna().sum()), + } + + +def with_acs_local_se_health_premiums( + frame: Frame, +) -> tuple[Frame, dict[str, Any]]: + """Fill missing ACS ``is_self_employed`` and ``health_insurance_premiums``. + + Args: + frame: The ACS-only frame after the shared transfer (and its + post-transfer structure). + + Returns: + The frame with filled cells and a JSON-ready receipt: the rule, its + source columns, filled and preserved rows, flagged rows, attributed + premiums, the rows the Medicare proxy and employer coverage withheld, + and the agreement of the flag with ACS COW 6 or 7. + + Raises: + ValueError: If the frame is not US-schema or the rule cannot read an + input (see :func:`_rule_view`). + """ + + if frame.schema != US_SCHEMA: + raise ValueError("ACS self-employed health premiums require the US schema.") + tables = {entity: frame.table(entity).copy() for entity in frame.entities} + tables.update({name: frame.link(name) for name in frame.links}) + person = tables["person"] + view, under_age_blanks = _rule_view(person) + try: + attributed = attribute_us_se_health_premiums(view) + except SourceRuntimeError as exc: + raise ValueError( + f"ACS self-employed health premiums: {exc} " + f"({ACS_LOCAL_SE_HEALTH_PREMIUMS_ISSUE})" + ) from exc + derived = { + _PREMIUMS: attributed[_PREMIUMS].to_numpy(dtype=np.float64), + _FLAG: attributed[_FLAG].to_numpy(dtype=bool), + } + counts = { + column: _fill_missing(person, column, derived[column]) + for column in ACS_LOCAL_SE_HEALTH_PREMIUM_COLUMNS + } + flag = person[_FLAG].astype(bool).to_numpy(dtype=bool) + premiums = pd.to_numeric(person[_PREMIUMS], errors="coerce").to_numpy( + dtype=np.float64 + ) + positive = premiums > 0 + reported = view[_REPORTED].to_numpy(dtype=np.float64) > 0 + medicare_proxy = (view[_AGE].to_numpy() >= US_SE_HEALTH_MEDICARE_AGE_THRESHOLD) | ( + view[_SSDI].to_numpy() > 0 + ) + esi = view[_ESI].to_numpy(dtype=bool) + weights = np.asarray(frame.resolve_weights("person").values, dtype=np.float64) + positive_weight = float(weights[positive].sum()) + receipt: dict[str, Any] = { + "issue": ACS_LOCAL_SE_HEALTH_PREMIUMS_ISSUE, + "method": ACS_LOCAL_SE_HEALTH_PREMIUMS_METHOD, + "spine": ACS_2024_1YR_SPINE, + "rule": _RULE, + "source_columns": list(ACS_LOCAL_SE_HEALTH_PREMIUMS_SOURCE_COLUMNS), + "acs_persons": len(person), + "self_employment_blank_under_15_read_as_zero_rows": under_age_blanks, + "columns": { + column: {"filled_rows": filled, "preserved_rows": preserved} + for column, (filled, preserved) in counts.items() + }, + "self_employed_rows": int(flag.sum()), + "self_employed_weighted_share": _weighted_share(weights, flag), + "premium_positive_rows": int(positive.sum()), + "premium_positive_weighted_share": _weighted_share(weights, positive), + "premium_weighted_total": float((weights * np.nan_to_num(premiums)).sum()), + "premium_weighted_mean_where_positive": ( + float((weights[positive] * premiums[positive]).sum()) / positive_weight + if positive_weight > 0 + else 0.0 + ), + "withheld": { + "self_employed_with_reported_premium_rows": int((flag & reported).sum()), + "medicare_proxy_rows": int((flag & reported & medicare_proxy).sum()), + "employer_coverage_rows": int( + (flag & reported & ~medicare_proxy & esi).sum() + ), + }, + "cow_agreement": _cow_agreement(person, flag), + } + result = Frame( + tables, + frame.schema, + {entity: frame.weights_for(entity) for entity in frame.weighted_entities}, + frame.strata, + mass_log=frame.mass_log, + metadata=frame.metadata, + ) + return result, _json_ready(receipt) + + +def _json_ready(value: Any) -> Any: + if isinstance(value, Mapping): + return {str(key): _json_ready(item) for key, item in value.items()} + if isinstance(value, (list, tuple)): + return [_json_ready(item) for item in value] + if isinstance(value, np.generic): + return value.item() + return value diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_ssi_medicaid_take_up.py b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_ssi_medicaid_take_up.py index f321d6fee6..c3a36a5daf 100755 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_ssi_medicaid_take_up.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_ssi_medicaid_take_up.py @@ -93,9 +93,9 @@ import numpy as np import pandas as pd +from microcosm.build.anchor_thinning import thin_anchors_to_residuals from microcosm.build.gates import GateResult from microcosm.build.source_runtime import SourceRuntimeConfig, run_source_stage -from microcosm.build.stochastic_assignment import stable_identity_uniforms from microcosm.build.us_runtime.acs_pums import ACS_2024_1YR_SPINE from microcosm.build.us_runtime.acs_transfer import ASEC_PUF_DONOR_SPINE from microcosm.build.us_runtime.base_pool import spine_column @@ -357,12 +357,6 @@ def _group_sums( return {str(group): float(value) for group, value in sums.items()} -def _keyed_uniform(key: str, *, seed: int, stream: str) -> float: - """A seeded blake2b uniform on ``stream`` for one ACS draw key.""" - - return float(stable_identity_uniforms((key,), seed=seed, salt=stream)[0]) - - def _donor_contribution( frame: Frame, donor: np.ndarray, @@ -547,8 +541,9 @@ def _medicaid_assignment( enrollment, floored at zero. A missing cell with ``HINS4 == 1`` anchors, but where the state's anchored eligible weight exceeds that residual each such record stays anchored with probability (residual - stored anchored - weight) / HINS4 anchored eligible weight, on its own keyed draw. The - ``medicaid_take_up`` manifest stage then runs on the ACS rows whose cell + weight) / HINS4 anchored eligible weight, on its own keyed draw (the + shared rule, :func:`~microcosm.build.anchor_thinning.thin_anchors_to_residuals`). + The ``medicaid_take_up`` manifest stage then runs on the ACS rows whose cell is missing or stored ``True`` (a stored ``False`` stays out of the stage), with the kept HINS4 records and stored ``True`` cells as the preserved anchor. @@ -569,26 +564,19 @@ def _medicaid_assignment( stored_true = present & flags hins4 = missing & anchor staged = missing | flags - stored_weight = _group_sums(state, weights, eligible & stored_true) - hins4_weight = _group_sums(state, weights, eligible & hins4) - keep: dict[str, float] = {} - for code, target in zip(codes, residual, strict=True): - stored = stored_weight.get(code, 0.0) - anchored = hins4_weight.get(code, 0.0) - keep[code] = ( - 1.0 - if anchored <= 0.0 or stored + anchored <= target - else float(np.clip((target - stored) / anchored, 0.0, 1.0)) - ) - probability = pd.Series(state).map(keep).fillna(1.0).to_numpy(dtype=np.float64) - keep_draws = np.zeros(len(keys), dtype=np.float64) - thinning = hins4 & (probability < 1.0) - if thinning.any(): - keep_draws[thinning] = [ - _keyed_uniform(str(key), seed=int(seed), stream=_HINS4_KEEP_STREAM) - for key in keys[thinning] - ] - kept = hins4 & (keep_draws < probability) + thinning = thin_anchors_to_residuals( + groups=state, + weights=weights, + counted=eligible, + fixed=stored_true, + anchors=hins4, + residuals=dict(zip(codes, residual, strict=True)), + keys=keys, + seed=int(seed), + stream=_HINS4_KEEP_STREAM, + ) + stored_weight, hins4_weight = thinning.fixed_mass, thinning.anchor_mass + keep, kept = thinning.keep_probability, thinning.kept fixed_true = stored_true | kept table = pd.DataFrame( { diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_status_inputs.py b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_status_inputs.py new file mode 100644 index 0000000000..7d8f79e129 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_status_inputs.py @@ -0,0 +1,321 @@ +"""Marital, military and occupation status of ACS rows (ACS local lane). + +Seven person inputs reached the ACS local-area release missing on every ACS +row, and the reviewed-null fill gave them the engine default, ``False`` +(microcosm#1720), although the ACS asks the items they come from: + +- **is_separated** and **is_surviving_spouse** follow the donor's rule + (:func:`~microcosm.build.us_runtime.relationship_inputs.us_marital_status_inputs`) + on the ACS rows' ``A_MARITL``, which the loader maps from ACS ``MAR`` + (``_ACS_TO_CPS_MARITAL_STATUS``: MAR 4, separated, is code 6; MAR 2, + widowed, is code 4). As on the donor, ``is_surviving_spouse`` is + "widowed", wider than the tax status, which needs a spouse's death in the + two prior years. +- **is_military** is ACS ``MIL`` == 1, "now on active duty" (loaded as + ``ACS_MIL``, microcosm#1020), the item microcosm#1720 names. ``MIL`` is + blank under 17, which reads as not on active duty. The donor's rule is + ``POCCU2`` == 52 (a military occupation on the longest job last year), which + on ACS rows would also mark a veteran whose last job, up to five years ago, + was military. The receipt records how often the two rules, and ACS + ``ESR`` 4 or 5 (Armed Forces), agree on the ACS rows. +- **has_never_worked**, **is_computer_scientist**, **is_farmer_fisher** and + **is_executive_administrative_professional** follow the donor's rule + (:func:`~microcosm.build.us_runtime.org_wages.us_flsa_occupation_flags`) on + the ACS rows' native ``detailed_occupation_recode``, the ``POCCU2`` code of + ``OCCP`` (``ACS_OCCP_TO_POCCU2``); a blank ``OCCP`` from age 16 is code 53, + so ``has_never_worked`` there means no job in the past five years. + +The stage runs on the ACS-only frame after the shared native mapping and +before any transfer; no transfer plan names these columns. It fills only +missing cells, so a stored ACS value stands, and it never sees a donor row. +It records a receipt and refuses nothing beyond malformed source codes. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from dataclasses import dataclass +from typing import Any + +import numpy as np +import pandas as pd + +from microcosm.build.us_runtime.acs_inputs import _nullable_source_codes +from microcosm.build.us_runtime.acs_pums import ( + ACS_2024_1YR_SPINE, + ACS_SOURCE_COLUMN_RENAMES, +) +from microcosm.build.us_runtime.org_wages import ( + FLSA_OVERTIME_OCCUPATION_CODES, + us_flsa_occupation_flags, +) +from microcosm.build.us_runtime.relationship_inputs import ( + US_MARITAL_STATUS_INPUT_A_MARITL_CODES, + us_marital_status_inputs, +) +from microcosm.frame import Frame +from microcosm.frame.units import US_SCHEMA + +__all__ = [ + "ACS_LOCAL_MARITAL_STATUS_COLUMNS", + "ACS_LOCAL_MILITARY_COLUMN", + "ACS_LOCAL_OCCUPATION_FLAG_COLUMNS", + "ACS_LOCAL_STATUS_INPUTS_COLUMNS", + "ACS_LOCAL_STATUS_INPUTS_ISSUE", + "ACS_LOCAL_STATUS_INPUTS_METHOD", + "AcsLocalStatusInputsResult", + "map_acs_local_status_inputs", +] + +ACS_LOCAL_STATUS_INPUTS_ISSUE = "microcosm#1720" +ACS_LOCAL_STATUS_INPUTS_METHOD = "native_acs_items_donor_rules_missing_cells_only" +ACS_LOCAL_MARITAL_STATUS_COLUMNS: tuple[str, ...] = tuple( + US_MARITAL_STATUS_INPUT_A_MARITL_CODES +) +ACS_LOCAL_MILITARY_COLUMN = "is_military" +#: The donor's POCCU2 flags except ``is_military``, which ACS MIL measures. +ACS_LOCAL_OCCUPATION_FLAG_COLUMNS: tuple[str, ...] = ( + *( + column + for column in FLSA_OVERTIME_OCCUPATION_CODES + if column != ACS_LOCAL_MILITARY_COLUMN + ), + "is_executive_administrative_professional", +) +#: Every column this stage writes on ACS rows. +ACS_LOCAL_STATUS_INPUTS_COLUMNS: tuple[str, ...] = ( + *ACS_LOCAL_MARITAL_STATUS_COLUMNS, + ACS_LOCAL_MILITARY_COLUMN, + *ACS_LOCAL_OCCUPATION_FLAG_COLUMNS, +) + +_NATIVE_PROVENANCE = "acs_2024_1yr_native" +_MARITAL_SOURCE = "A_MARITL" +_MILITARY_SOURCE = ACS_SOURCE_COLUMN_RENAMES["MIL"] +_OCCUPATION_SOURCE = "detailed_occupation_recode" +_EMPLOYMENT_STATUS_SOURCE = "ESR" +_AGE_SOURCE = "AGEP" +#: ACS MIL is asked from age 17; below it the Census code is blank. +_MILITARY_MINIMUM_AGE = 17 +_ACTIVE_DUTY_CODE = 1 +#: ACS ESR 4 (Armed Forces, at work) and 5 (with a job but not at work). +_ARMED_FORCES_EMPLOYMENT_CODES = (4, 5) +_DONOR_MILITARY_OCCUPATION_CODE = FLSA_OVERTIME_OCCUPATION_CODES[ + ACS_LOCAL_MILITARY_COLUMN +] +_RULES: Mapping[str, tuple[str, tuple[str, ...], str]] = { + **{ + column: ( + f"A_MARITL == {code} (the donor's relationship_inputs rule; the " + f"loader maps ACS MAR {4 if code == 6 else 2} to it)", + (_MARITAL_SOURCE, "MAR"), + "relationship_inputs: A_MARITL == " + str(code), + ) + for column, code in US_MARITAL_STATUS_INPUT_A_MARITL_CODES.items() + }, + ACS_LOCAL_MILITARY_COLUMN: ( + "ACS MIL == 1 (now on active duty); blank under 17 is False", + (_MILITARY_SOURCE, _AGE_SOURCE), + f"org_wages: POCCU2 == {_DONOR_MILITARY_OCCUPATION_CODE}", + ), + **{ + column: ( + "the donor's org_wages FLSA rule on detailed_occupation_recode " + "(OCCP through ACS_OCCP_TO_POCCU2)", + (_OCCUPATION_SOURCE, "OCCP"), + "org_wages: the same rule on ASEC POCCU2", + ) + for column in ACS_LOCAL_OCCUPATION_FLAG_COLUMNS + }, +} + + +@dataclass(frozen=True) +class AcsLocalStatusInputsResult: + """The mapped ACS frame, its native-input receipts and the stage receipt.""" + + frame: Frame + native_inputs: Mapping[str, Mapping[str, Any]] + receipt: Mapping[str, Any] + + +def _weighted_share(weights: np.ndarray, flags: np.ndarray) -> float: + total = float(weights.sum()) + return float(weights[flags].sum()) / total if total > 0 else 0.0 + + +def _fill_missing( + person: pd.DataFrame, column: str, values: np.ndarray +) -> tuple[np.ndarray, int, int]: + """Write ``values`` into the missing cells of ``column``; keep the rest. + + Returns the final flags, the filled count and the preserved count. + + Raises: + ValueError: If a stored value is not boolean. + """ + + if column not in person: + person[column] = values.astype(bool) + return values.astype(bool), len(values), 0 + stored = person[column] + present = stored.notna().to_numpy(dtype=bool) + if not stored[present].isin([0, 1]).all(): + raise ValueError(f"Stored ACS {column} values must be boolean.") + final = np.where(present, stored.fillna(False).astype(bool), values).astype(bool) + person[column] = final + return final, int((~present).sum()), int(present.sum()) + + +def _military_agreement( + military: np.ndarray, + occupation_military: np.ndarray, + armed_forces: np.ndarray, + weights: np.ndarray, +) -> dict[str, Any]: + def table(other: np.ndarray) -> dict[str, Any]: + return { + "both_rows": int((military & other).sum()), + "mil_only_rows": int((military & ~other).sum()), + "other_only_rows": int((~military & other).sum()), + "other_weighted_true_share": _weighted_share(weights, other), + } + + return { + f"donor_rule_poccu2_{_DONOR_MILITARY_OCCUPATION_CODE}": table( + occupation_military + ), + "esr_armed_forces_4_or_5": table(armed_forces), + } + + +def map_acs_local_status_inputs(frame: Frame) -> AcsLocalStatusInputsResult: + """Write the marital, military and occupation inputs on ACS rows. + + Runs on the ACS-only frame after + :func:`~microcosm.build.us_runtime.acs_inputs.map_acs_native_inputs` + (which writes ``detailed_occupation_recode``) and before any transfer. + + Returns: + The mapped frame, native-input receipts in the ``acs_inputs`` format, + and the stage receipt (rules, source columns, filled and true rows, + weighted true shares and the ``is_military`` agreement tables). + + Raises: + ValueError: If the frame is not US-schema, a source column is absent, + an ``A_MARITL``, ``MIL`` or ``ESR`` code is malformed, or a + stored output value is not boolean. + """ + + if frame.schema != US_SCHEMA: + raise ValueError("ACS local status inputs require the US schema.") + tables = {entity: frame.table(entity).copy() for entity in frame.entities} + tables.update({name: frame.link(name) for name in frame.links}) + person = tables["person"] + required = ( + _MARITAL_SOURCE, + _MILITARY_SOURCE, + _OCCUPATION_SOURCE, + _EMPLOYMENT_STATUS_SOURCE, + _AGE_SOURCE, + ) + missing = [column for column in required if column not in person] + if missing: + raise ValueError( + f"ACS local status inputs require person column(s) {missing}; the " + "pinned ACS PUMS source carries MAR (as A_MARITL), MIL (as " + "ACS_MIL), OCCP, ESR and AGEP " + f"({ACS_LOCAL_STATUS_INPUTS_ISSUE})." + ) + age = pd.to_numeric(person[_AGE_SOURCE], errors="coerce") + if age.isna().any() or age.lt(0).any(): + raise ValueError("ACS local status inputs require a nonnegative AGEP.") + marital = pd.to_numeric(person[_MARITAL_SOURCE], errors="coerce") + derived: dict[str, np.ndarray] = dict( + us_marital_status_inputs(marital.to_numpy(dtype=np.float64)) + ) + military_codes = _nullable_source_codes( + person[_MILITARY_SOURCE].rename("MIL"), minimum=1, maximum=4 + ) + derived[ACS_LOCAL_MILITARY_COLUMN] = military_codes.eq(_ACTIVE_DUTY_CODE).to_numpy( + dtype=bool + ) + occupation = pd.to_numeric(person[_OCCUPATION_SOURCE], errors="coerce").fillna(0) + flags = us_flsa_occupation_flags(occupation) + for column in ACS_LOCAL_OCCUPATION_FLAG_COLUMNS: + derived[column] = flags[column].to_numpy(dtype=bool) + employment = _nullable_source_codes( + person[_EMPLOYMENT_STATUS_SOURCE], minimum=1, maximum=6 + ) + + weights = np.asarray(frame.resolve_weights("person").values, dtype=np.float64) + native: dict[str, Mapping[str, Any]] = {} + columns: dict[str, Any] = {} + final: dict[str, np.ndarray] = {} + for column in ACS_LOCAL_STATUS_INPUTS_COLUMNS: + values, filled, preserved = _fill_missing(person, column, derived[column]) + final[column] = values + rule, source_columns, donor_rule = _RULES[column] + native[column] = { + "entity": "person", + "source_columns": list(source_columns), + "transformation": rule, + "provenance": _NATIVE_PROVENANCE, + "observed_rows": len(values), + "missing_rows": 0, + } + columns[column] = { + "rule": rule, + "donor_rule": donor_rule, + "source_columns": list(source_columns), + "filled_rows": filled, + "preserved_rows": preserved, + "true_rows": int(values.sum()), + "weighted_true_share": _weighted_share(weights, values), + } + + military = final[ACS_LOCAL_MILITARY_COLUMN] + blank_military = military_codes.isna().to_numpy(dtype=bool) + mapped = Frame( + tables, + frame.schema, + {entity: frame.weights_for(entity) for entity in frame.weighted_entities}, + frame.strata, + mass_log=frame.mass_log, + metadata=frame.metadata, + ) + receipt: dict[str, Any] = { + "issue": ACS_LOCAL_STATUS_INPUTS_ISSUE, + "method": ACS_LOCAL_STATUS_INPUTS_METHOD, + "spine": ACS_2024_1YR_SPINE, + "acs_persons": len(person), + "columns": columns, + "a_maritl_rows": { + str(int(code)): int(count) + for code, count in marital.value_counts().sort_index().items() + }, + "military": { + "mil_code_rows": { + **{ + str(int(code)): int(count) + for code, count in military_codes.value_counts() + .sort_index() + .items() + }, + "blank": int(blank_military.sum()), + }, + "blank_rows_age_17_plus": int( + (blank_military & age.ge(_MILITARY_MINIMUM_AGE).to_numpy()).sum() + ), + "coded_rows_under_17": int( + (~blank_military & age.lt(_MILITARY_MINIMUM_AGE).to_numpy()).sum() + ), + "agreement": _military_agreement( + military, + occupation.eq(_DONOR_MILITARY_OCCUPATION_CODE).to_numpy(dtype=bool), + employment.isin(_ARMED_FORCES_EMPLOYMENT_CODES).to_numpy(dtype=bool), + weights, + ), + }, + } + return AcsLocalStatusInputsResult(mapped, native, receipt) diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_take_up.py b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_take_up.py index ec8d0be7a9..7e873cb51c 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_take_up.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_take_up.py @@ -59,8 +59,8 @@ ``SPM_CAPHOUSESUB > 0`` and are equal by construction (:mod:`~microcosm.build.us_runtime.housing_inputs`). Units in an ACS group-quarters household (``TYPEHUGQ`` 2/3) have no housing unit and get - ``False``. Their transferred take-up flag is left alone: forcing it is the - transfer-side fix of microcosm#975. + ``False``. Staging sets their transferred take-up flag False too + (microcosm#975, ``acs_local_group_quarters_housing``). - ``takes_up_medicare_if_eligible`` (person) is native ACS ``HINS3 == 1`` (Medicare coverage at interview), the ACS counterpart of the donor's measured ``MCARE == 1`` @@ -95,8 +95,10 @@ SNAP household targets reweight instead. Other ``takes_up_*`` flags on ACS rows are not this stage's: SSI and Medicaid take-up are assigned after an engine pre-pass by -:mod:`~microcosm.build.us_runtime.acs_local_ssi_medicaid_take_up`, and Early -Head Start, the ACA credit and the rest still ship at the engine default +:mod:`~microcosm.build.us_runtime.acs_local_ssi_medicaid_take_up`, ACA +take-up and the Marketplace plan ratio after one more by +:mod:`~microcosm.build.us_runtime.acs_local_aca_take_up` (microcosm#1720), +and Early Head Start and the rest still ship at the engine default (microcosm#1022); the gate here does not grade them. """ @@ -582,8 +584,9 @@ def _housing_fill( "filled_rows": int(missing.sum()), "preserved_rows": int((acs_units & present).sum()), "group_quarters_filled_false": int((missing & group_quarters).sum()), - # Group-quarters units whose transferred take-up flag is True: the - # transfer-side defect microcosm#975 owns; this receipt stays False. + # Group-quarters units whose take-up flag is True: 0 on a staging + # run that sets it False there (microcosm#975); this receipt stays + # False either way. "group_quarters_take_up_true": int( (acs_units & group_quarters & take_up_present & take_up).sum() ), diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_voluntary_filing.py b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_voluntary_filing.py new file mode 100644 index 0000000000..dc9f797db6 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_voluntary_filing.py @@ -0,0 +1,340 @@ +"""Voluntary filing of ACS tax units (ACS local lane). + +``would_file_taxes_voluntarily`` reached the ACS local-area release missing on +every ACS tax unit, and the reviewed-null fill gave it the engine default, +``False`` (microcosm#1720). Medicaid's non-filer rules then applied to more ACS +units than donor units, and once return counts read the filer flag +(microcosm#1644), ACS units would carry no voluntary filer at all. + +This fresh-build stage runs the donor release's own SIPP model +(:mod:`~microcosm.build.us_runtime.voluntary_filing`), unchanged, on the ACS +tax units and fills only missing cells: + +- **Model.** The weighted QRF on the pinned full SIPP 2023 file's December + filing answers at source-tax-unit grain + (:func:`~microcosm.build.us_runtime.voluntary_filing.load_sipp_2023_voluntary_filing_donor`), + with its five predictors, forest size and the build seed, through + :func:`~microcosm.build.us_runtime.voluntary_filing.impute_us_voluntary_filing_from_tables`. + It reads the same file the staging already verifies for the SSI disability + model; nothing is downloaded twice. +- **Predictors** come from a view of the ACS tax units, built as the donor + builds its own: tax-unit wages (native ``WAGP``; the blank under 15 reads as + no wages), the head's age and sex (native ``AGEP``, ``SEX``), marriage + (``filing_status_input`` is ``JOINT``, from the loader's tax units) and the + household's persons under 18. ACS tax units have no support clones, so each + unit is its own source unit. +- **Draws.** The donor function's QRF draws once per ACS tax unit, in tax-unit + order, from the build seed. +- **Null cells only.** Donor rows and any stored ACS value are unchanged. + +The stage records a receipt (the SIPP identity, the fill counts and the ACS +and donor weighted true shares) and grades nothing. +""" + +from __future__ import annotations + +import hashlib +from collections.abc import Mapping +from pathlib import Path +from typing import Any + +import numpy as np +import pandas as pd + +from microcosm.build.us_runtime.acs_pums import ACS_2024_1YR_SPINE +from microcosm.build.us_runtime.acs_transfer import ASEC_PUF_DONOR_SPINE +from microcosm.build.us_runtime.base_pool import spine_column +from microcosm.build.us_runtime.voluntary_filing import ( + SIPP_2023_VOLUNTARY_FILING_DONOR_REVISION, + SIPP_2023_VOLUNTARY_FILING_DONOR_SHA256, + SIPP_2023_VOLUNTARY_FILING_DONOR_SIZE_BYTES, + SIPP_2023_VOLUNTARY_FILING_DONOR_URL, + SIPP_VOLUNTARY_FILING_MODEL_PREDICTORS, + SIPP_VOLUNTARY_FILING_N_ESTIMATORS, + US_VOLUNTARY_FILING_OUTPUT_COLUMNS, + US_VOLUNTARY_FILING_STAGE_NAME, + VOLUNTARY_FILING_ARCHIVED_DERIVATION_URL, + impute_us_voluntary_filing_from_tables, + load_sipp_2023_voluntary_filing_donor, + us_voluntary_filing_stage_spec, +) +from microcosm.frame import Frame +from microcosm.frame.units import US_SCHEMA + +__all__ = [ + "ACS_LOCAL_VOLUNTARY_FILING_COLUMN", + "ACS_LOCAL_VOLUNTARY_FILING_ISSUE", + "ACS_LOCAL_VOLUNTARY_FILING_METHOD", + "ACS_VOLUNTARY_FILING_SOURCE_COLUMNS", + "load_acs_local_voluntary_filing_donor", + "with_acs_local_voluntary_filing", +] + +ACS_LOCAL_VOLUNTARY_FILING_ISSUE = "microcosm#1720" +ACS_LOCAL_VOLUNTARY_FILING_COLUMN = US_VOLUNTARY_FILING_OUTPUT_COLUMNS[0] +ACS_LOCAL_VOLUNTARY_FILING_METHOD = ( + "donor_sipp_voluntary_filing_qrf_on_acs_tax_units_missing_cells_only" +) +_OUTPUT = ACS_LOCAL_VOLUNTARY_FILING_COLUMN +_WAGES = "employment_income_before_lsr" +_WAGES_MINIMUM_AGE = 15 +#: The ACS person columns the view reads; ``A_LINENO`` (SPORDER) breaks ties +#: among a unit's members as the donor's receiver does. +ACS_VOLUNTARY_FILING_SOURCE_COLUMNS: tuple[str, ...] = ( + "person_id", + "person_tax_unit_id", + "person_household_id", + "age", + "is_female", + _WAGES, + "tax_unit_role_input", +) +_OPTIONAL_PERSON_COLUMNS: tuple[str, ...] = ("A_LINENO",) +_TAX_UNIT_COLUMNS: tuple[str, ...] = ("tax_unit_id", "filing_status_input") + + +def load_acs_local_voluntary_filing_donor( + path: str | Path, +) -> tuple[pd.DataFrame, dict[str, Any]]: + """Load the pinned SIPP filing donor and the identity the receipt pins. + + ``path`` is the file the staging already resolved (and verified) for the + SSI disability model; the byte length and sha-256 are checked again, so + the identity describes the bytes this read. + """ + + source = Path(path) + donor = load_sipp_2023_voluntary_filing_donor( + source, + expected_sha256=SIPP_2023_VOLUNTARY_FILING_DONOR_SHA256, + expected_size_bytes=SIPP_2023_VOLUNTARY_FILING_DONOR_SIZE_BYTES, + ) + return donor, { + "path": str(source.resolve()), + "url": SIPP_2023_VOLUNTARY_FILING_DONOR_URL, + "revision": SIPP_2023_VOLUNTARY_FILING_DONOR_REVISION, + "sha256": SIPP_2023_VOLUNTARY_FILING_DONOR_SHA256, + "size_bytes": SIPP_2023_VOLUNTARY_FILING_DONOR_SIZE_BYTES, + } + + +def _boolean_cells(values: pd.Series) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """``(flags, present, invalid)`` of a nullable boolean column.""" + + present = values.notna().to_numpy(dtype=bool) + valid = present & values.isin([0, 1]).to_numpy(dtype=bool) + flags = np.zeros(len(values), dtype=bool) + flags[valid] = values[valid].astype(bool).to_numpy(dtype=bool) + return flags, present, present & ~valid + + +def _share(weights: np.ndarray, flags: np.ndarray) -> float: + total = float(weights.sum()) + return float(weights[flags].sum()) / total if total > 0 else 0.0 + + +def _acs_view( + person: pd.DataFrame, tax_unit: pd.DataFrame +) -> tuple[pd.DataFrame, pd.DataFrame, int]: + """The ACS rows the donor's receiver reads, and the under-15 wage blanks. + + Raises: + ValueError: If a column is absent, or a wage is blank from age 15. + """ + + missing = [ + column for column in ACS_VOLUNTARY_FILING_SOURCE_COLUMNS if column not in person + ] + [column for column in _TAX_UNIT_COLUMNS if column not in tax_unit] + if missing: + raise ValueError( + f"ACS voluntary filing requires column(s) {missing} on ACS rows " + f"({ACS_LOCAL_VOLUNTARY_FILING_ISSUE})." + ) + columns = [ + *ACS_VOLUNTARY_FILING_SOURCE_COLUMNS, + *(column for column in _OPTIONAL_PERSON_COLUMNS if column in person), + ] + view = person.loc[:, columns].copy() + age = pd.to_numeric(view["age"], errors="coerce") + wages = pd.to_numeric(view[_WAGES], errors="coerce") + blank = wages.isna() & age.ge(_WAGES_MINIMUM_AGE) + if blank.any(): + raise ValueError( + f"{int(blank.sum())} ACS person(s) aged {_WAGES_MINIMUM_AGE}+ have a " + f"blank {_WAGES}." + ) + view[_WAGES] = wages.fillna(0.0).to_numpy(dtype=np.float64) + return ( + view, + tax_unit.loc[:, list(_TAX_UNIT_COLUMNS)].copy(), + int(wages.isna().sum()), + ) + + +def _assignment_sha256(unit_ids: np.ndarray, values: np.ndarray) -> str: + selected = pd.DataFrame( + {"tax_unit_id": np.asarray(unit_ids), "value": np.asarray(values, dtype=bool)} + ) + hashed = pd.util.hash_pandas_object(selected, index=False).to_numpy() + return hashlib.sha256(hashed.tobytes()).hexdigest() + + +def _json_ready(value: Any) -> Any: + if isinstance(value, Mapping): + return {str(key): _json_ready(item) for key, item in value.items()} + if isinstance(value, (list, tuple)): + return [_json_ready(item) for item in value] + if isinstance(value, np.generic): + return value.item() + return value + + +def with_acs_local_voluntary_filing( + frame: Frame, + *, + sipp_donor: pd.DataFrame, + seed: int, + donor_identity: Mapping[str, Any] | None = None, + n_estimators: int | None = None, +) -> tuple[Frame, dict[str, Any]]: + """Fill missing ACS-unit ``would_file_taxes_voluntarily`` from the SIPP model. + + Args: + frame: The local lane's pooled frame. Its person and tax-unit tables + carry complete origin tags, the column (complete on donor units) + and :data:`ACS_VOLUNTARY_FILING_SOURCE_COLUMNS` on ACS rows. + sipp_donor: The training frame from + :func:`load_acs_local_voluntary_filing_donor`. + seed: The build seed for the QRF. + donor_identity: The verified SIPP identity the receipt pins. + n_estimators: Forest size; defaults to the donor stage's own. + + Returns: + The frame with filled cells (the same object if none were missing) + and a JSON-ready receipt with a digest of every ACS unit's value. + + Raises: + ValueError: If the frame is not US-schema, origin tags or a column + are missing, a stored value is not boolean, or a wage is blank + from age 15. + """ + + if frame.schema != US_SCHEMA: + raise ValueError("ACS voluntary filing requires the US schema.") + # The reused model must still be the packaged contract. + us_voluntary_filing_stage_spec() + person = frame.table("person") + tax_unit = frame.table("tax_unit") + masks = [] + for entity in ("person", "tax_unit"): + table = frame.table(entity) + tag = spine_column(entity) + if tag not in table or table[tag].isna().any(): + raise ValueError( + f"ACS voluntary filing requires complete origin tags: {tag}." + ) + if set(table[tag].unique()) - {ASEC_PUF_DONOR_SPINE, ACS_2024_1YR_SPINE}: + raise ValueError("ACS voluntary filing origin tags name an unknown spine.") + masks.append(table[tag].eq(ACS_2024_1YR_SPINE).to_numpy(dtype=bool)) + acs_person, acs_unit = masks + if not acs_unit.any(): + raise ValueError("ACS voluntary filing found no ACS tax units.") + if _OUTPUT not in tax_unit: + raise ValueError( + f"ACS voluntary filing requires tax-unit column {_OUTPUT!r}; the donor " + "release carries it, and without it the donor units would reach the " + "engine default too." + ) + _, present, invalid = _boolean_cells(tax_unit[_OUTPUT]) + if invalid.any(): + raise ValueError( + f"{int(invalid.sum())} stored {_OUTPUT} value(s) are not boolean." + ) + missing = acs_unit & ~present + view_person, view_unit, wage_blanks = _acs_view( + person.loc[acs_person], tax_unit.loc[acs_unit] + ) + fill = missing[acs_unit] + predicted = np.zeros(int(acs_unit.sum()), dtype=bool) + if fill.any(): + kwargs = {} if n_estimators is None else {"n_estimators": int(n_estimators)} + predicted = impute_us_voluntary_filing_from_tables( + view_person, view_unit, sipp_donor, seed=int(seed), **kwargs + ).to_numpy(dtype=bool) + + result = frame + if fill.any(): + updated = tax_unit.copy(deep=False) + filled = tax_unit[_OUTPUT].astype(object).copy() + filled.iloc[np.flatnonzero(missing)] = predicted[fill] + updated[_OUTPUT] = filled.astype(bool) if filled.notna().all() else filled + tables = { + entity: updated if entity == "tax_unit" else frame.table(entity) + for entity in frame.entities + } + tables.update({name: frame.link(name) for name in frame.links}) + result = Frame( + tables, + frame.schema, + {entity: frame.weights_for(entity) for entity in frame.weighted_entities}, + frame.strata, + mass_log=frame.mass_log, + metadata=frame.metadata, + ) + + final, final_present, _ = _boolean_cells(result.table("tax_unit")[_OUTPUT]) + weights = np.asarray(result.resolve_weights("tax_unit").values, dtype=np.float64) + donor_unit = ~acs_unit + receipt: dict[str, Any] = { + "issue": ACS_LOCAL_VOLUNTARY_FILING_ISSUE, + "column": _OUTPUT, + "method": ACS_LOCAL_VOLUNTARY_FILING_METHOD, + "spine": ACS_2024_1YR_SPINE, + "seed": int(seed), + "model": { + "stage": US_VOLUNTARY_FILING_STAGE_NAME, + "archived_source": VOLUNTARY_FILING_ARCHIVED_DERIVATION_URL, + "predictors": list(SIPP_VOLUNTARY_FILING_MODEL_PREDICTORS), + "n_estimators": ( + int(n_estimators) + if n_estimators is not None + else SIPP_VOLUNTARY_FILING_N_ESTIMATORS + ), + "fitted": bool(fill.any()), + "training_units": int(len(sipp_donor)), + }, + "sipp_donor": { + **dict(donor_identity or {}), + "source_audit": _json_ready(sipp_donor.attrs.get("source_audit")), + }, + "predictor_view": { + "employment_income": ( + f"tax-unit sum of native {_WAGES} (ACS WAGP); the blank under " + f"{_WAGES_MINIMUM_AGE} reads as no wages" + ), + "reference_person": ( + "the tax unit's HEAD (tax_unit_role_input), ties by A_LINENO" + ), + "reference_is_married": "filing_status_input == JOINT", + "count_under_18": "persons under 18 in the household", + "wage_blank_under_15_rows": wage_blanks, + }, + "acs_tax_units": int(acs_unit.sum()), + "filled_units": int(missing.sum()), + "preserved_acs_units": int((acs_unit & present).sum()), + "unfilled_acs_units": int((acs_unit & ~final_present).sum()), + "outcome": { + "filled_true_units": int(predicted[fill].sum()), + "acs_true_units": int(final[acs_unit].sum()), + "acs_weighted_true_share": _share(weights[acs_unit], final[acs_unit]), + "donor_weighted_true_share": ( + _share(weights[donor_unit], final[donor_unit]) + if donor_unit.any() + else None + ), + }, + "assigned_sha256": _assignment_sha256( + tax_unit.loc[acs_unit, "tax_unit_id"].to_numpy(), final[acs_unit] + ), + } + return result, _json_ready(receipt) diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_weeks_deferrals.py b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_weeks_deferrals.py new file mode 100644 index 0000000000..d3f38b3eab --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_local_weeks_deferrals.py @@ -0,0 +1,472 @@ +"""Weeks unemployed and retirement deferrals of ACS rows (ACS local lane). + +Four person inputs reached the ACS local-area release missing on every ACS +row, and the reviewed-null fill gave them the engine default, 0 +(microcosm#1720). The ACS asks none of them: + +- ``weeks_unemployed``: a UC recipient with 0 weeks looks like a recipient + for no month, so SNAP's work-registration exemption, and with it the ABAWD + time limit, read wrong. +- ``traditional_401k_contributions_desired``, + ``roth_401k_contributions_desired`` and ``roth_ira_contributions_desired``: + ACS ``WAGP`` is gross of deferrals, so with them at 0, AGI and MAGI include + deferred wages, and no Roth contribution earns the saver's credit. + +This fresh-build stage is a separate, local-lane-only QRF pass on the donor's +ASEC observation role, the pattern of the local income pass +(:mod:`~microcosm.build.us_runtime.acs_local_income`). It never edits the +shared declared transfer plan, which the pool lane shares. + +- **Donor channel.** The ASEC observation role carries the measured values: + ``weeks_unemployed`` is ASEC ``LKWEEKS`` + (:mod:`~microcosm.build.us_runtime.weeks_unemployed`), and the deferrals + are the measured ``RETCB_VAL`` split by the archived shares + (:mod:`~microcosm.build.us_runtime.retirement_contributions`). The PUF + clone role carries QRF predictions of both, so fitting on it would transfer + a model of a model. +- **Place.** It runs after the shared transfer, on the ACS-only frame: the + weeks family reads the transferred ``unemployment_compensation`` as a + predictor, which the ACS rows carry only from then on. Every earlier fit + (hours, income, ESI premium and the shared plan) has drawn before it, and + each family's seed comes from its own name, so their draws are unchanged. +- **Predictors.** The existing transfer predictors (age, sex and state, plus + wages, self-employment, Social Security, retirement, interest, household + head and tenure where both sides observe them). The weeks family adds one + local predictor extension of this call alone: + ``unemployment_compensation``, on the donor the measured ASEC ``UC_VAL`` + and on ACS rows the shared transfer's draw. +- **The donor's post-processing.** Weeks are clipped to 0-52, rounded and set + to 0 wherever ``unemployment_compensation`` is 0, the archived zero rule + (:func:`~microcosm.build.us_runtime.weeks_unemployed.postprocess_us_weeks_unemployed_predictions`). + Deferrals are clipped at 0 and the 401(k) deferrals set to 0 without wages + (:func:`~microcosm.build.us_runtime.retirement_contributions.postprocess_us_retirement_contribution_predictions`). + Both are the rules the donor applies to its own PUF clone half. +- **No double counting.** The shared plan transfers + ``traditional_ira_contributions_desired`` and + ``self_employed_pension_contributions_desired`` (from the PUF role's + deductions), so this pass refuses to draw any column the shared plan or the + local income pass draws. +- **Null cells only.** A stored ACS value stands, and the post-processing + touches only the cells this pass filled. +""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from typing import Any + +import numpy as np +import pandas as pd + +from microcosm.build.gates import FitWeightRecord +from microcosm.build.us_runtime.acs_local_income import ( + ACS_LOCAL_INCOME_TRANSFER_COLUMNS, +) +from microcosm.build.us_runtime.acs_pums import ACS_2024_1YR_SPINE +from microcosm.build.us_runtime.acs_transfer import ( + ASEC_PUF_DONOR_SPINE, + DEFAULT_ACS_TRANSFER_MAX_TARGETS_PER_FIT, + AcsImputedInput, + AcsPersonPredictorExtension, + TargetFamilies, + required_acs_transfer_inputs, + resolve_acs_donor_channel, + transfer_acs_inputs, +) +from microcosm.build.us_runtime.retirement_contributions import ( + postprocess_us_retirement_contribution_predictions, +) +from microcosm.build.us_runtime.support_provenance import BASE_ASEC_SUPPORT_CHANNEL +from microcosm.build.us_runtime.weeks_unemployed import ( + postprocess_us_weeks_unemployed_predictions, +) +from microcosm.frame import US_SCHEMA, Frame + +__all__ = [ + "ACS_LOCAL_RETIREMENT_DEFERRAL_COLUMNS", + "ACS_LOCAL_RETIREMENT_DEFERRAL_FAMILY", + "ACS_LOCAL_UNEMPLOYMENT_COMPENSATION_FEATURE", + "ACS_LOCAL_WEEKS_DEFERRALS_COLUMNS", + "ACS_LOCAL_WEEKS_DEFERRALS_DONOR_CHANNEL", + "ACS_LOCAL_WEEKS_DEFERRALS_FAMILIES", + "ACS_LOCAL_WEEKS_DEFERRALS_ISSUE", + "ACS_LOCAL_WEEKS_DEFERRALS_METHOD", + "ACS_LOCAL_WEEKS_DEFERRALS_PREDICTOR_EXTENSIONS", + "ACS_LOCAL_WEEKS_UNEMPLOYED_COLUMN", + "ACS_LOCAL_WEEKS_UNEMPLOYED_FAMILY", + "AcsLocalWeeksDeferralsResult", + "acs_local_weeks_deferrals_target_families", + "require_acs_local_weeks_deferrals_donor", + "with_acs_local_weeks_deferrals", +] + +ACS_LOCAL_WEEKS_DEFERRALS_ISSUE = "microcosm#1720" +ACS_LOCAL_WEEKS_DEFERRALS_METHOD = ( + "separate_local_qrf_pass_after_shared_transfer_asec_role_missing_cells_only" +) +ACS_LOCAL_WEEKS_DEFERRALS_DONOR_CHANNEL = BASE_ASEC_SUPPORT_CHANNEL +ACS_LOCAL_WEEKS_UNEMPLOYED_FAMILY = "acs_local_weeks_unemployed" +ACS_LOCAL_RETIREMENT_DEFERRAL_FAMILY = "acs_local_retirement_deferrals" +ACS_LOCAL_WEEKS_UNEMPLOYED_COLUMN = "weeks_unemployed" +ACS_LOCAL_RETIREMENT_DEFERRAL_COLUMNS: tuple[str, ...] = ( + "traditional_401k_contributions_desired", + "roth_401k_contributions_desired", + "roth_ira_contributions_desired", +) +#: One chained QRF per family keeps the jointly reported deferrals together. +ACS_LOCAL_WEEKS_DEFERRALS_FAMILIES: Mapping[str, tuple[str, ...]] = { + ACS_LOCAL_WEEKS_UNEMPLOYED_FAMILY: (ACS_LOCAL_WEEKS_UNEMPLOYED_COLUMN,), + ACS_LOCAL_RETIREMENT_DEFERRAL_FAMILY: ACS_LOCAL_RETIREMENT_DEFERRAL_COLUMNS, +} +ACS_LOCAL_WEEKS_DEFERRALS_COLUMNS: tuple[str, ...] = tuple( + column + for columns in ACS_LOCAL_WEEKS_DEFERRALS_FAMILIES.values() + for column in columns +) +_UNEMPLOYMENT_COMPENSATION = "unemployment_compensation" +ACS_LOCAL_UNEMPLOYMENT_COMPENSATION_FEATURE = "__acs_transfer_unemployment_compensation" +#: The weeks family's local predictor: the measured ASEC UC on the donor, the +#: shared transfer's UC on ACS rows. +ACS_LOCAL_WEEKS_DEFERRALS_PREDICTOR_EXTENSIONS: tuple[ + AcsPersonPredictorExtension, ... +] = ( + AcsPersonPredictorExtension( + feature=ACS_LOCAL_UNEMPLOYMENT_COMPENSATION_FEATURE, + donor_components=(_UNEMPLOYMENT_COMPENSATION,), + recipient_source=_UNEMPLOYMENT_COMPENSATION, + families=(ACS_LOCAL_WEEKS_UNEMPLOYED_FAMILY,), + ), +) +_WAGES = "employment_income_before_lsr" +_AGE = "age" +#: ACS asks WAGP from age 15; below it the blank reads as no wages. +_WAGES_MINIMUM_AGE = 15 + + +def acs_local_weeks_deferrals_target_families() -> TargetFamilies: + """The separate ASEC-only pass, disjoint from every other transfer.""" + + overlap = sorted( + set(ACS_LOCAL_WEEKS_DEFERRALS_COLUMNS) + & (required_acs_transfer_inputs() | set(ACS_LOCAL_INCOME_TRANSFER_COLUMNS)) + ) + if overlap: + raise ValueError( + "The ACS local weeks and deferrals pass would transfer column(s) " + f"another transfer already draws {overlap}; double counting " + f"({ACS_LOCAL_WEEKS_DEFERRALS_ISSUE})." + ) + return {"person": dict(ACS_LOCAL_WEEKS_DEFERRALS_FAMILIES)} + + +def _amounts(rows: pd.DataFrame, column: str) -> np.ndarray: + return pd.to_numeric(rows[column], errors="coerce").to_numpy( + dtype=np.float64, na_value=np.nan + ) + + +def _summary(values: np.ndarray, weights: np.ndarray) -> dict[str, Any]: + finite = np.isfinite(values) + positive = finite & (values > 0) + total = float(weights[finite].sum()) + recipients = float(weights[positive].sum()) + amount = float((weights[positive] * values[positive]).sum()) + return { + "rows": int(len(values)), + "missing_rows": int((~finite).sum()), + "negative_rows": int((finite & (values < 0)).sum()), + "positive_rows": int(positive.sum()), + "weighted_positive_share": recipients / total if total > 0 else 0.0, + "weighted_mean_where_positive": amount / recipients if recipients > 0 else 0.0, + } + + +def require_acs_local_weeks_deferrals_donor(frame: Frame) -> dict[str, Any]: + """The donor's ASEC role coverage of the four targets and the predictor. + + Refuses only a donor without the ASEC role or without a column, which the + pass cannot fit; missing and negative cells are recorded, not refused + (the transfer fits on complete donor rows). + """ + + try: + donor, channel = resolve_acs_donor_channel( + frame, ACS_LOCAL_WEEKS_DEFERRALS_DONOR_CHANNEL + ) + except ValueError as exc: + raise ValueError( + "The ACS local weeks and deferrals donor needs the ASEC observation " + f"role ({ACS_LOCAL_WEEKS_DEFERRALS_ISSUE}): {exc}" + ) from exc + person = donor.table("person") + needed = (*ACS_LOCAL_WEEKS_DEFERRALS_COLUMNS, _UNEMPLOYMENT_COMPENSATION) + missing = [column for column in needed if column not in person] + if missing: + raise ValueError( + f"The ASEC donor lacks {missing} ({ACS_LOCAL_WEEKS_DEFERRALS_ISSUE})." + ) + weights = np.asarray(donor.resolve_weights("person").values, dtype=np.float64) + weeks = _amounts(person, ACS_LOCAL_WEEKS_UNEMPLOYED_COLUMN) + uc = _amounts(person, _UNEMPLOYMENT_COMPENSATION) + return { + "channel": channel, + "person_rows": int(len(person)), + "columns": { + column: _summary(_amounts(person, column), weights) for column in needed + }, + # The zero rule is the donor's rule for its PUF half; on its measured + # ASEC role, weeks can be positive without UC (looking for work + # without a claim), which the receipt counts. + "weeks_positive_without_uc_rows": int( + (np.nan_to_num(weeks) > 0)[np.nan_to_num(uc) <= 0].sum() + ), + "weeks_positive_without_uc_weighted_share": float( + weights[(np.nan_to_num(weeks) > 0) & (np.nan_to_num(uc) <= 0)].sum() + ) + / float(weights.sum()) + if float(weights.sum()) > 0 + else 0.0, + } + + +@dataclass(frozen=True) +class AcsLocalWeeksDeferralsResult: + """The ACS frame with filled cells, the pass's fits and its receipt.""" + + frame: Frame + fit_records: tuple[FitWeightRecord, ...] + imputed_inputs: tuple[AcsImputedInput, ...] + receipt: Mapping[str, Any] + + +def _wages(person: pd.DataFrame) -> np.ndarray: + """ACS wages for the 401(k) gate; the blank under 15 reads as none.""" + + if _WAGES not in person or _AGE not in person: + raise ValueError( + f"The ACS deferral gate requires {_WAGES} and {_AGE} on ACS rows " + f"({ACS_LOCAL_WEEKS_DEFERRALS_ISSUE})." + ) + wages = pd.to_numeric(person[_WAGES], errors="coerce") + age = pd.to_numeric(person[_AGE], errors="coerce") + blank = wages.isna() & age.ge(_WAGES_MINIMUM_AGE) + if blank.any(): + raise ValueError( + f"{int(blank.sum())} ACS person(s) aged {_WAGES_MINIMUM_AGE}+ have a " + f"blank {_WAGES}." + ) + return wages.fillna(0.0).to_numpy(dtype=np.float64) + + +def _unemployment_compensation(person: pd.DataFrame) -> np.ndarray: + if _UNEMPLOYMENT_COMPENSATION not in person: + raise ValueError( + f"The ACS weeks zero rule requires {_UNEMPLOYMENT_COMPENSATION} on " + "ACS rows: run the pass after the shared transfer " + f"({ACS_LOCAL_WEEKS_DEFERRALS_ISSUE})." + ) + uc = pd.to_numeric(person[_UNEMPLOYMENT_COMPENSATION], errors="coerce") + if uc.isna().any(): + raise ValueError( + f"{int(uc.isna().sum())} ACS person(s) have a blank transferred " + f"{_UNEMPLOYMENT_COMPENSATION}." + ) + return uc.to_numpy(dtype=np.float64) + + +def _missing_masks(person: pd.DataFrame) -> dict[str, np.ndarray]: + return { + column: ( + person[column].isna().to_numpy(dtype=bool) + if column in person + else np.ones(len(person), dtype=bool) + ) + for column in ACS_LOCAL_WEEKS_DEFERRALS_COLUMNS + } + + +def _postprocessed( + person: pd.DataFrame, filled: Mapping[str, np.ndarray] +) -> tuple[pd.DataFrame, dict[str, int]]: + """Apply the donor's post-processing to the cells this pass filled.""" + + person = person.copy() + changed: dict[str, int] = {} + weeks_rows = filled[ACS_LOCAL_WEEKS_UNEMPLOYED_COLUMN] + if weeks_rows.any(): + column = ACS_LOCAL_WEEKS_UNEMPLOYED_COLUMN + before = _amounts(person, column) + after = before.copy() + after[weeks_rows] = postprocess_us_weeks_unemployed_predictions( + before[weeks_rows], + unemployment_compensation=_unemployment_compensation(person)[weeks_rows], + ) + changed[column] = int((after != before).sum()) + person[column] = after + deferral_rows = np.zeros(len(person), dtype=bool) + for column in ACS_LOCAL_RETIREMENT_DEFERRAL_COLUMNS: + deferral_rows |= filled[column] + if deferral_rows.any(): + wages = _wages(person) + before = person[list(ACS_LOCAL_RETIREMENT_DEFERRAL_COLUMNS)].apply( + pd.to_numeric, errors="coerce" + ) + processed = postprocess_us_retirement_contribution_predictions( + before.loc[deferral_rows].reset_index(drop=True), + employment_income=wages[deferral_rows], + ) + for column in ACS_LOCAL_RETIREMENT_DEFERRAL_COLUMNS: + values = before[column].to_numpy(dtype=np.float64).copy() + rows = filled[column] + new = processed[column].to_numpy(dtype=np.float64) + # ``processed`` is aligned to ``deferral_rows``; keep only this + # column's own filled cells. + values[rows] = new[rows[deferral_rows]] + changed[column] = int( + (values != before[column].to_numpy(dtype=np.float64)).sum() + ) + person[column] = values + return person, changed + + +def _with_person(frame: Frame, person: pd.DataFrame) -> Frame: + tables = {entity: frame.table(entity) for entity in frame.entities} + tables["person"] = person + tables.update({name: frame.link(name) for name in frame.links}) + return Frame( + tables, + frame.schema, + {entity: frame.weights_for(entity) for entity in frame.weighted_entities}, + frame.strata, + mass_log=frame.mass_log, + metadata=frame.metadata, + ) + + +def _column_receipts( + imputed: Sequence[AcsImputedInput], + person: pd.DataFrame, + filled: Mapping[str, np.ndarray], + changed: Mapping[str, int], + weights: np.ndarray, +) -> dict[str, Any]: + columns: dict[str, Any] = {} + for family, targets in ACS_LOCAL_WEEKS_DEFERRALS_FAMILIES.items(): + for column in targets: + entries = [item for item in imputed if item.column == column] + columns[column] = { + "family": family, + "transfer_entries": len(entries), + "donor_channel": sorted({str(item.donor_channel) for item in entries}), + "imputed_rows": int( + sum(item.imputed_recipient_rows for item in entries) + ), + "unmodeled_rows": int( + sum(item.unmodeled_recipient_rows for item in entries) + ), + "predictors": sorted( + {str(p) for item in entries for p in item.predictors} + ), + "filled_rows": int(filled[column].sum()), + "postprocess_changed_rows": int(changed.get(column, 0)), + "acs": _summary(_amounts(person, column), weights), + } + return columns + + +def with_acs_local_weeks_deferrals( + frame: Frame, + donor: Frame, + *, + seed: int, + n_estimators: int, + max_targets_per_fit: int = DEFAULT_ACS_TRANSFER_MAX_TARGETS_PER_FIT, + donor_spine: str = ASEC_PUF_DONOR_SPINE, +) -> AcsLocalWeeksDeferralsResult: + """Fill the ACS rows' weeks unemployed and deferrals from the ASEC role. + + Args: + frame: The ACS-only frame after the shared transfer. + donor: The ASEC-by-PUF base, whose ASEC observation role is the donor. + seed, n_estimators, max_targets_per_fit, donor_spine: As the other + transfers of the lane. + + Returns: + The frame with filled cells, the fit records, the imputed-input + provenance and the receipt (method, donor coverage, predictors, fill + and post-processing counts, ACS shares). The receipt is not graded. + + Raises: + ValueError: If the plan overlaps another transfer, the donor lacks + the ASEC role or a column, or an input the post-processing reads + is blank on an ACS row. + """ + + if frame.schema != US_SCHEMA: + raise ValueError("The ACS local weeks and deferrals pass needs the US schema.") + plan = acs_local_weeks_deferrals_target_families() + donor_summary = require_acs_local_weeks_deferrals_donor(donor) + filled = _missing_masks(frame.table("person")) + transfer = transfer_acs_inputs( + frame, + donor, + target_families=plan, + donor_spine=donor_spine, + donor_channel=ACS_LOCAL_WEEKS_DEFERRALS_DONOR_CHANNEL, + seed=seed, + n_estimators=n_estimators, + max_targets_per_fit=max_targets_per_fit, + person_predictor_extensions=ACS_LOCAL_WEEKS_DEFERRALS_PREDICTOR_EXTENSIONS, + ) + person, changed = _postprocessed(transfer.frame.table("person"), filled) + result = _with_person(transfer.frame, person) + weights = np.asarray(result.resolve_weights("person").values, dtype=np.float64) + uc = _unemployment_compensation(person) + weeks = _amounts(person, ACS_LOCAL_WEEKS_UNEMPLOYED_COLUMN) + receipt: dict[str, Any] = { + "issue": ACS_LOCAL_WEEKS_DEFERRALS_ISSUE, + "method": ACS_LOCAL_WEEKS_DEFERRALS_METHOD, + "spine": ACS_2024_1YR_SPINE, + "donor_channel": ACS_LOCAL_WEEKS_DEFERRALS_DONOR_CHANNEL, + "resolved_donor_channel": transfer.resolved_donor_channel, + "donor": donor_summary, + "families": { + family: list(targets) + for family, targets in ACS_LOCAL_WEEKS_DEFERRALS_FAMILIES.items() + }, + "predictor_extensions": [ + extension.identity() + for extension in ACS_LOCAL_WEEKS_DEFERRALS_PREDICTOR_EXTENSIONS + ], + "postprocessing": { + ACS_LOCAL_WEEKS_UNEMPLOYED_COLUMN: ( + "weeks_unemployed.postprocess_us_weeks_unemployed_predictions: " + "clip to 0-52, round, 0 where unemployment_compensation is 0" + ), + "deferrals": ( + "retirement_contributions." + "postprocess_us_retirement_contribution_predictions: clip at " + "0; 401(k) deferrals 0 where wages are 0 (the WAGP blank under " + "15 reads as no wages)" + ), + }, + "not_transferred_shared_plan_columns": [ + "traditional_ira_contributions_desired", + "self_employed_pension_contributions_desired", + ], + "acs_persons": int(len(person)), + "acs_uc_recipient_rows": int((uc > 0).sum()), + "acs_uc_recipients_with_positive_weeks_rows": int( + ((uc > 0) & (np.nan_to_num(weeks) > 0)).sum() + ), + "columns": _column_receipts( + transfer.imputed_inputs, person, filled, changed, weights + ), + } + return AcsLocalWeeksDeferralsResult( + frame=result, + fit_records=tuple(transfer.fit_records), + imputed_inputs=tuple(transfer.imputed_inputs), + receipt=receipt, + ) diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_multispine.py b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_multispine.py index 6c3cb9059f..9bf2ad694a 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_multispine.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_multispine.py @@ -27,10 +27,16 @@ with_acs_spm_independence_role, without_acs_group_quarters_children, ) +from microcosm.build.us_runtime.acs_local_coverage_anchors import ( + with_acs_local_coverage_anchors, +) from microcosm.build.us_runtime.acs_local_esi_premiums import ( acs_local_esi_premium_transfer_target_families, with_acs_local_esi_premium_anchor, ) +from microcosm.build.us_runtime.acs_local_group_quarters_housing import ( + with_acs_local_group_quarters_housing, +) from microcosm.build.us_runtime.acs_local_hours import ( acs_local_hours_transfer_target_families, complete_acs_local_under15_hours, @@ -49,6 +55,15 @@ require_acs_receipt_anchor_sources, with_acs_local_snap_receipt_anchor, ) +from microcosm.build.us_runtime.acs_local_se_health_premiums import ( + with_acs_local_se_health_premiums, +) +from microcosm.build.us_runtime.acs_local_status_inputs import ( + map_acs_local_status_inputs, +) +from microcosm.build.us_runtime.acs_local_weeks_deferrals import ( + with_acs_local_weeks_deferrals, +) from microcosm.build.us_runtime.acs_local_wic_take_up import ( require_complete_us_wic_take_up, with_acs_local_wic_take_up, @@ -129,7 +144,12 @@ def build_optional_acs_multispine( esi_premium_donor_factory: Callable[[Frame], tuple[Frame, dict[str, object]]] | None = None, work_disability_inputs: bool = False, + status_inputs: bool = False, income_transfer: bool = False, + se_health_premiums: bool = False, + weeks_deferrals: bool = False, + group_quarters_housing: bool = False, + coverage_anchors: bool = False, native_receipt_anchors: bool = False, wic_take_up: bool = False, semp_covers_partnership_income: bool = False, @@ -162,6 +182,12 @@ def build_optional_acs_multispine( native ``is_disabled``/``is_blind``/``weeks_worked`` on every ACS row before any transfer, so the null-only transfer leaves them alone; its receipt is ``provenance["acs_local_work_disability"]``. + ``status_inputs`` (the ACS local lane, microcosm#1720) writes + ``is_separated``/``is_surviving_spouse`` from ``A_MARITL`` and the four + ``POCCU2`` occupation flags from ``detailed_occupation_recode`` under the + donor's own rules, and ``is_military`` from ACS ``MIL`` == 1, on every ACS + row before any transfer; no transfer plan names them. Its receipt is + ``provenance["acs_local_status_inputs"]``. ``income_transfer`` (the ACS local lane, microcosm#1022) runs a separate ASEC-channel QRF pass for the SNAP-relevant income leaves the shared plan does not carry, with its own local-only plan and two opt-in predictor @@ -169,6 +195,32 @@ def build_optional_acs_multispine( ACS-aligned ``RETP`` analog for disability and account distributions); the shared transfer and its execution contract are unchanged. Its receipt is ``provenance["acs_local_income_transfer"]``. + ``weeks_deferrals`` (the ACS local lane, microcosm#1720) runs a separate + ASEC-channel QRF pass for ``weeks_unemployed`` and three retirement + deferrals right after the shared transfer, whose + ``unemployment_compensation`` the weeks family reads through a predictor + extension of that call alone; every earlier fit has drawn by then, so + their draws are unchanged. Its receipt is + ``provenance["acs_local_weeks_deferrals"]``. + ``coverage_anchors`` (the ACS local lane, microcosm#1720) writes ACS + ``HINS1`` over the transferred ``has_esi`` and applies ``HINS2`` to the + two transferred direct-purchase flags, after every transfer (so the + shared plan's chain and every other draw are unchanged) and before the + self-employed premium attribution, which reads ``has_esi``. Its receipt + is ``provenance["acs_local_coverage_anchors"]``. + ``se_health_premiums`` (the ACS local lane, microcosm#1720) runs the + donor's self-employed premium attribution + (:func:`~.other_health_insurance.attribute_us_se_health_premiums`) on the + ACS rows after the shared transfer, whose post-transfer structure has + settled the self-employment components it reads, and before pooling; it + fills only missing ``is_self_employed`` and ``health_insurance_premiums`` + cells. Its receipt is ``provenance["acs_local_se_health_premiums"]``. + ``group_quarters_housing`` (the ACS local lane, microcosm#975 and + microcosm#1720) sets the transferred + ``takes_up_housing_assistance_if_eligible`` False on every ACS SPM unit + in group quarters (``TYPEHUGQ`` 2/3) after the shared transfer, whose + plan is unchanged, and before pooling. Its receipt is + ``provenance["acs_local_group_quarters_housing"]``. ``native_receipt_anchors`` (the ACS local lane, microcosm#1022) replaces the transferred ``receives_snap`` with native household ``FS`` on every ACS SPM unit after the shared transfer, whose plan is unchanged, and @@ -284,6 +336,21 @@ def build_optional_acs_multispine( mapped_frame = local.frame work_disability = local.receipt del local + status_inputs_receipt = None + if status_inputs: + # Local lane only (microcosm#1720): ACS MAR, MIL and OCCP under the + # donor's rules. No transfer plan names these columns, so they land + # before the transfers like the other native mappings. + status = map_acs_local_status_inputs(mapped_frame) + overlap = sorted(set(native_provenance) & set(status.native_inputs)) + if overlap: + raise ValueError( + f"ACS local status inputs would overwrite native {overlap}." + ) + native_provenance.update(_json_ready_mapping(status.native_inputs)) + mapped_frame = status.frame + status_inputs_receipt = _json_ready_mapping(status.receipt) + del status modeled_hours = None if hours_under15_policy is not None: mapped_frame, modeled_hours = complete_acs_local_under15_hours( @@ -436,17 +503,41 @@ def build_optional_acs_multispine( ) del mapped_frame adult_care_gate = _require_recipient_adult_care_structure(transferred.frame) + weeks_deferrals_frame = None + weeks_deferrals_fit_records = () + weeks_deferrals_imputed_inputs = () + weeks_deferrals_receipt = None + if weeks_deferrals: + # Local lane only (microcosm#1720): after the shared transfer, so the + # weeks family reads its unemployment_compensation, and after every + # other fit, whose draws therefore cannot move. ASEC observations, + # a plan disjoint from every other transfer, null cells only. + late = with_acs_local_weeks_deferrals( + transferred.frame, + base, + seed=seed, + n_estimators=n_estimators, + max_targets_per_fit=max_targets_per_fit, + donor_spine=donor_spine, + ) + weeks_deferrals_frame = late.frame + weeks_deferrals_fit_records = late.fit_records + weeks_deferrals_imputed_inputs = late.imputed_inputs + weeks_deferrals_receipt = late.receipt + del late fit_records = ( hours_fit_records + income_fit_records + esi_fit_records + tuple(transferred.fit_records) + + weeks_deferrals_fit_records ) imputed_provenance = _json_ready_sequence( hours_imputed_inputs + income_imputed_inputs + esi_imputed_inputs + tuple(transferred.imputed_inputs) + + weeks_deferrals_imputed_inputs ) deferred_inputs = tuple(transferred.deferred_inputs) if block_location: @@ -466,8 +557,35 @@ def build_optional_acs_multispine( deferred_provenance = _json_ready_sequence(deferred_inputs) resolved_donor_channel = transferred.resolved_donor_channel fit_provenance = _json_ready_sequence(fit_records) - transferred_frame = transferred.frame - del transferred + transferred_frame = ( + transferred.frame if weeks_deferrals_frame is None else weeks_deferrals_frame + ) + del transferred, weeks_deferrals_frame + coverage_receipt = None + if coverage_anchors: + # Local lane only (microcosm#1720): native HINS1/HINS2 over the + # shared transfer's coverage draws. After every transfer, so no other + # draw moves; before the premium attribution, which reads has_esi. + transferred_frame, coverage_receipt = with_acs_local_coverage_anchors( + transferred_frame, base, seed=seed + ) + se_health_receipt = None + if se_health_premiums: + # Local lane only (microcosm#1720): the donor's rule, unchanged, after + # the post-transfer structure has kept the drawn self-employment + # components at zero where SEMP stands; before pooling, so donor rows + # keep their own attribution. + transferred_frame, se_health_receipt = with_acs_local_se_health_premiums( + transferred_frame + ) + group_quarters_housing_receipt = None + if group_quarters_housing: + # Local lane only (microcosm#975): group quarters have no housing + # unit. The shared plan still draws the flag; this lane-own step + # overrides it there, before pooling, so donor rows are never seen. + transferred_frame, group_quarters_housing_receipt = ( + with_acs_local_group_quarters_housing(transferred_frame) + ) receipt_anchors = None if native_receipt_anchors: # Local lane only (microcosm#1022): after the shared transfer, so the @@ -546,6 +664,27 @@ def build_optional_acs_multispine( } if wic_take_up_receipt is not None: provenance["wic_take_up"] = _json_ready(wic_take_up_receipt) + if status_inputs_receipt is not None: + provenance["acs_local_status_inputs"] = status_inputs_receipt + if coverage_receipt is not None: + provenance["acs_local_coverage_anchors"] = _json_ready_mapping( + coverage_receipt + ) + if se_health_receipt is not None: + provenance["acs_local_se_health_premiums"] = _json_ready_mapping( + se_health_receipt + ) + if group_quarters_housing_receipt is not None: + provenance["acs_local_group_quarters_housing"] = _json_ready_mapping( + group_quarters_housing_receipt + ) + if weeks_deferrals_receipt is not None: + provenance["fit_configuration"]["weeks_deferrals_donor_channel"] = ( + weeks_deferrals_receipt["resolved_donor_channel"] + ) + provenance["acs_local_weeks_deferrals"] = _json_ready_mapping( + weeks_deferrals_receipt + ) if hours_donor is not None or hours_donor_factory is not None: provenance["fit_configuration"]["hours_donor_channel"] = hours_donor_channel provenance["local_hours_source"] = hours_source diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_pums.py b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_pums.py index 266670b0fe..be6ee11969 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/acs_pums.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/acs_pums.py @@ -106,7 +106,12 @@ # all other income (OIP), the local income pass's child-support predictor # (microcosm#1022, acs_local_income), and the public assistance income the # local lane's receipt-anchor receipt records (microcosm#1022, -# acs_local_receipt_anchors). The employment status (ESR) the immigration +# acs_local_receipt_anchors), and the employer-coverage and direct-purchase +# items (HINS1, HINS2) the local lane writes has_esi and the two +# direct-purchase flags from, with the subsidized Marketplace coverage recode +# (HIMRKS) and its allocation flag (FHIMRKSP) that split direct purchase +# (microcosm#1720, acs_local_coverage_anchors). +# The employment status (ESR) the immigration # stage reads and the weeks worked (WKWN) the local lane maps natively are # required above, for the work-experience inputs. Older or minimal source # fixtures remain loadable; an absent column stays absent and a Census blank @@ -124,6 +129,10 @@ "CIT", "YOEP", "POBP", + "HINS1", + "HINS2", + "HIMRKS", + "FHIMRKSP", "HINS3", "HINS4", "HINS5", @@ -135,12 +144,18 @@ "OIP", "PAP", ) -# ACS source columns whose Census name is already a different CPS ASEC field in -# the pooled person table. ACS ``MIL`` is military service (veteran status); -# CPS ``MIL`` is military health coverage, which the ASEC immigration stage -# reads. Loading the ACS field under its own name would put two meanings in -# one pooled column, so it is renamed at the read boundary. -ACS_SOURCE_COLUMN_RENAMES: dict[str, str] = {"MIL": "ACS_MIL"} +# ACS source columns renamed at the read boundary. ACS ``MIL`` is military +# service (veteran status); CPS ``MIL`` is military health coverage, which the +# ASEC immigration stage reads. Loading the ACS field under its own name would +# put two meanings in one pooled column. ACS ``HIMRKS`` (Subsidized +# Marketplace Coverage) and its allocation flag ``FHIMRKSP`` have no CPS +# namesake, but they stay on the staged ACS person rows as raw source items +# for later stages (microcosm#1720), so they carry the same ``ACS_`` prefix. +ACS_SOURCE_COLUMN_RENAMES: dict[str, str] = { + "MIL": "ACS_MIL", + "HIMRKS": "ACS_HIMRKS", + "FHIMRKSP": "ACS_FHIMRKSP", +} # Temporary aliases consumed only by microunit's dependent gross-income test. # ACS combined sources stay combined: INTP is placed on one gross-income diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/battery_bindings.py b/packages/microcosm-build/src/microcosm/build/us_runtime/battery_bindings.py index bd687e4f08..4919908c7b 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/battery_bindings.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/battery_bindings.py @@ -1380,6 +1380,21 @@ def _us_local_specs() -> tuple[USGateSpec, ...]: **_pins("medicaid_take_up", "US_MEDICAID_ENROLLMENT_TOLERANCE"), }, ), + # microcosm#1720: report-only, so the entry is diagnostic and the + # tool never stops on its verdict. + USGateSpec( + check="aca_take_up_signal", + legacy_name="acs_local_aca_take_up_signal", + gate="tool:acs_local_aca_take_up_signal_gate", + positional=(FRAME,), + arguments={"receipt": "aca_receipt"}, + pinned=_pins( + "acs_local_aca_take_up", + "_RESIDUAL_RELATIVE_TOLERANCE", + "_SATURATED_RELATIVE_TOLERANCE", + "ACS_LOCAL_ACA_RETURNS_RELATIVE_TOLERANCE", + ), + ), # The calibrated artifact's gates at finalize, and package's re-checks. USGateSpec( check="local_hours_signal", diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/org_wages.py b/packages/microcosm-build/src/microcosm/build/us_runtime/org_wages.py index 66744d5404..9c03ce62ba 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/org_wages.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/org_wages.py @@ -80,6 +80,7 @@ "require_us_occupation_and_work_experience_inputs", "us_org_wages_signal_gate", "us_org_wages_stage_spec", + "us_flsa_occupation_flags", "us_org_wages_summary", "with_us_org_wages_inputs", ] @@ -653,12 +654,31 @@ def derive_us_org_occupation_inputs(person: pd.DataFrame) -> pd.DataFrame: result["detailed_industry_recode"] = detailed_industry.astype(np.int16) result["major_industry_recode"] = major_industry.astype(np.int16) result["worked_last_year"] = worked + flags = us_flsa_occupation_flags(occupation) + for variable in flags.columns: + result[variable] = flags[variable] + return result + + +def us_flsa_occupation_flags(occupation: pd.Series) -> pd.DataFrame: + """The FLSA occupation flags from ``POCCU2`` codes alone. + + One rule for every spine: :func:`derive_us_org_occupation_inputs` calls it + on ASEC ``POCCU2``, and the ACS local lane on the ACS rows' native + ``detailed_occupation_recode`` (``OCCP`` through ``ACS_OCCP_TO_POCCU2``, + microcosm#1720). A missing code reads as 0, as the donor reads it. + Returns the columns of :data:`FLSA_OVERTIME_OCCUPATION_CODES`, then + ``is_executive_administrative_professional``, on ``occupation``'s index. + """ + + codes = pd.to_numeric(occupation, errors="coerce").fillna(0).astype(int) + flags = pd.DataFrame(index=occupation.index) for variable, code in FLSA_OVERTIME_OCCUPATION_CODES.items(): - result[variable] = occupation.eq(code) - result["is_executive_administrative_professional"] = occupation.isin( + flags[variable] = codes.eq(code) + flags["is_executive_administrative_professional"] = codes.isin( FLSA_EXECUTIVE_ADMINISTRATIVE_PROFESSIONAL_OCCUPATION_CODES ) - return result + return flags def _person_state_fips(frame: Frame) -> np.ndarray: diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/relationship_inputs.py b/packages/microcosm-build/src/microcosm/build/us_runtime/relationship_inputs.py index 3695df0023..8292bec51d 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/relationship_inputs.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/relationship_inputs.py @@ -40,7 +40,9 @@ "US_RELATIONSHIP_INPUTS_OUTPUT_COLUMNS", "US_RELATIONSHIP_INPUTS_REQUIRED_SOURCE_COLUMNS", "US_RELATIONSHIP_INPUTS_STAGE_NAME", + "US_MARITAL_STATUS_INPUT_A_MARITL_CODES", "derive_us_relationship_inputs_from_manifest", + "us_marital_status_inputs", "us_relationship_inputs_signal_gate", "us_relationship_inputs_stage_spec", "us_relationship_inputs_summary", @@ -71,6 +73,37 @@ _SURVIVING_SPOUSE_SHARE_BAND = (0.02, 0.08) _VALID_A_MARITL_CODES = frozenset(range(1, 8)) _DERIVE_RELATIONSHIP_INPUTS_PARAMETER_KEYS = frozenset() +#: The CPS ``A_MARITL`` code of each marital-status leaf (the archived eCPS +#: rule, ``datasets/cps/cps.py`` lines 1212-1213): 4 is widowed, 6 separated. +#: The ACS local lane applies the same rule to its ACS rows, whose loader maps +#: ACS ``MAR`` onto these codes (microcosm#1720). +US_MARITAL_STATUS_INPUT_A_MARITL_CODES: dict[str, int] = { + "is_separated": 6, + "is_surviving_spouse": 4, +} + + +def us_marital_status_inputs(marital_status: np.ndarray) -> dict[str, np.ndarray]: + """The marital-status leaves from exact CPS ``A_MARITL`` codes. + + One rule for every spine: the donor stage calls it on ASEC rows, and the + ACS local lane on the ACS rows' loader-mapped ``A_MARITL``. + + Raises: + ValueError: If a code is not an integer in 1-7. + """ + + codes = np.asarray(marital_status, dtype=np.float64) + valid = np.isfinite(codes) & np.isin(codes, sorted(_VALID_A_MARITL_CODES)) + if not valid.all(): + rows = np.flatnonzero(~valid)[:5].tolist() + raise ValueError( + f"Marital-status inputs require A_MARITL codes 1-7; invalid row(s): {rows}." + ) + return { + column: codes == code + for column, code in US_MARITAL_STATUS_INPUT_A_MARITL_CODES.items() + } def us_relationship_inputs_stage_spec() -> SourceStageSpec: @@ -177,8 +210,8 @@ def derive_us_relationship_inputs_from_manifest( result = frame.copy(deep=True) result["is_household_head"] = is_head - result["is_separated"] = marital_status == 6 - result["is_surviving_spouse"] = marital_status == 4 + for column, values in us_marital_status_inputs(marital_status).items(): + result[column] = values return result diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/retirement_contributions.py b/packages/microcosm-build/src/microcosm/build/us_runtime/retirement_contributions.py index 01b116da8a..0aee9354af 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/retirement_contributions.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/retirement_contributions.py @@ -53,6 +53,7 @@ "US_RETIREMENT_CONTRIBUTION_STAGE_NAME", "derive_us_retirement_contributions_from_manifest", "impute_us_retirement_contributions_to_puf_support_from_manifest", + "postprocess_us_retirement_contribution_predictions", "us_retirement_contributions_signal_gate", "us_retirement_contributions_stage_spec", "us_retirement_contributions_summary", @@ -400,20 +401,13 @@ def impute_us_retirement_contributions_to_puf_support_from_manifest( list(US_RETIREMENT_CONTRIBUTION_OUTPUT_COLUMNS), weights=weights.to_numpy(dtype=np.float64), ) - predictions = fitted.predict(test).clip(lower=0.0) - no_wages = test["employment_income"].to_numpy(dtype=np.float64) == 0 - no_self_employment = test["self_employment_income"].to_numpy(dtype=np.float64) == 0 - predictions.loc[ - no_wages, - [ - "traditional_401k_contributions_desired", - "roth_401k_contributions_desired", - ], - ] = 0.0 - predictions.loc[ - no_self_employment, - "self_employed_pension_contributions_desired", - ] = 0.0 + predictions = postprocess_us_retirement_contribution_predictions( + fitted.predict(test), + employment_income=test["employment_income"].to_numpy(dtype=np.float64), + self_employment_income=test["self_employment_income"].to_numpy( + dtype=np.float64 + ), + ) result = frame.copy(deep=True) for column in US_RETIREMENT_CONTRIBUTION_OUTPUT_COLUMNS: @@ -421,6 +415,58 @@ def impute_us_retirement_contributions_to_puf_support_from_manifest( return result +#: The archived split's earnings gates: employer-plan deferrals need wages, +#: and the self-employed pension needs self-employment income. +_WAGE_GATED_CONTRIBUTIONS: tuple[str, ...] = ( + "traditional_401k_contributions_desired", + "roth_401k_contributions_desired", +) +_SELF_EMPLOYMENT_GATED_CONTRIBUTIONS: tuple[str, ...] = ( + "self_employed_pension_contributions_desired", +) + + +def postprocess_us_retirement_contribution_predictions( + predictions: pd.DataFrame, + *, + employment_income: np.ndarray, + self_employment_income: np.ndarray | None = None, +) -> pd.DataFrame: + """The archived post-processing of QRF contributions. + + Every prediction is clipped at 0; the 401(k) deferrals are 0 where + ``employment_income`` is 0, and the self-employed pension where + ``self_employment_income`` is 0. Only the columns ``predictions`` carries + are touched. One rule for every spine: the PUF support half calls it on + all five leaves, and the ACS local lane on the three it draws + (microcosm#1720). + + Raises: + ValueError: If the self-employed pension is predicted without + ``self_employment_income``. + """ + + result = predictions.clip(lower=0.0) + no_wages = np.asarray(employment_income, dtype=np.float64) == 0 + wage_gated = [column for column in _WAGE_GATED_CONTRIBUTIONS if column in result] + if wage_gated: + result.loc[no_wages, wage_gated] = 0.0 + self_employment_gated = [ + column for column in _SELF_EMPLOYMENT_GATED_CONTRIBUTIONS if column in result + ] + if self_employment_gated: + if self_employment_income is None: + raise ValueError( + "The self-employed pension's earnings gate needs " + "self_employment_income." + ) + no_self_employment = ( + np.asarray(self_employment_income, dtype=np.float64) == 0 + ) + result.loc[no_self_employment, self_employment_gated] = 0.0 + return result + + def _person_retirement_predictors(frame: Frame) -> pd.DataFrame: """Build the retired QRF predictors on person rows, failing closed.""" diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/voluntary_filing.py b/packages/microcosm-build/src/microcosm/build/us_runtime/voluntary_filing.py index e15ea5702d..eba5794518 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/voluntary_filing.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/voluntary_filing.py @@ -53,6 +53,7 @@ "SIPP_2023_VOLUNTARY_FILING_DONOR_SIZE_BYTES", "SIPP_2023_VOLUNTARY_FILING_DONOR_URL", "SIPP_VOLUNTARY_FILING_MODEL_PREDICTORS", + "SIPP_VOLUNTARY_FILING_N_ESTIMATORS", "SIPP_VOLUNTARY_FILING_SOURCE_COLUMNS", "US_VOLUNTARY_FILING_NONCONSTANT_TAX_UNIT_COLUMNS", "US_VOLUNTARY_FILING_OUTPUT_COLUMNS", @@ -62,6 +63,7 @@ "VOLUNTARY_FILING_SIPP_DICTIONARY_URL", "fetch_sipp_2023_voluntary_filing_donor", "impute_us_voluntary_filing", + "impute_us_voluntary_filing_from_tables", "load_sipp_2023_voluntary_filing_donor", "us_voluntary_filing_signal_gate", "us_voluntary_filing_stage_spec", @@ -132,6 +134,8 @@ _DONOR_WEIGHT_COLUMN = "tax_unit_weight" _DONOR_SOURCE_KEY_COLUMN = "source_tax_unit_key" _DEFAULT_N_ESTIMATORS = 100 +#: The donor stage's forest size, which the ACS local lane reuses. +SIPP_VOLUNTARY_FILING_N_ESTIMATORS = _DEFAULT_N_ESTIMATORS _TAX_UNIT_SOURCE_ID_COLUMN = "tax_unit_source_id" _TRUE_SHARE_BAND = (0.45, 0.95) _EXPECTED_READ_PARAMETERS: dict[str, object] = { @@ -577,8 +581,16 @@ def _strict_recipient_numeric( def _recipient_tax_unit_predictor_table(frame: Frame) -> pd.DataFrame: """Build the approved five predictors in receiver tax-unit order.""" - person = frame.table("person") - tax_unit = frame.table("tax_unit") + return _recipient_tax_unit_predictor_table_from_tables( + frame.table("person"), frame.table("tax_unit") + ) + + +def _recipient_tax_unit_predictor_table_from_tables( + person: pd.DataFrame, tax_unit: pd.DataFrame +) -> pd.DataFrame: + """The five predictors from a person and a tax-unit table.""" + required = { "person_id", "person_tax_unit_id", @@ -720,6 +732,15 @@ def _recipient_tax_unit_predictor_table(frame: Frame) -> pd.DataFrame: def _source_receiver_rows( frame: Frame, receiver: pd.DataFrame, +) -> tuple[pd.DataFrame, pd.Series]: + """Select one canonical predictor row per source unit and fan-out keys.""" + + return _source_receiver_rows_from_table(frame.table("tax_unit"), receiver) + + +def _source_receiver_rows_from_table( + tax_unit: pd.DataFrame, + receiver: pd.DataFrame, ) -> tuple[pd.DataFrame, pd.Series]: """Select one canonical predictor row per source unit and fan-out keys. @@ -730,7 +751,6 @@ def _source_receiver_rows( one-row-per-source path for tables without support metadata. """ - tax_unit = frame.table("tax_unit") require_assembled_support_provenance(tax_unit, entity="tax_unit") if _TAX_UNIT_SOURCE_ID_COLUMN in tax_unit: source_ids = tax_unit[_TAX_UNIT_SOURCE_ID_COLUMN] @@ -805,6 +825,31 @@ def impute_us_voluntary_filing( ) -> pd.Series: """Fit the weighted SIPP QRF and draw once per source tax unit.""" + return impute_us_voluntary_filing_from_tables( + frame.table("person"), + frame.table("tax_unit"), + donor, + seed=seed, + n_estimators=n_estimators, + ) + + +def impute_us_voluntary_filing_from_tables( + person: pd.DataFrame, + tax_unit: pd.DataFrame, + donor: pd.DataFrame, + *, + seed: int, + n_estimators: int = _DEFAULT_N_ESTIMATORS, +) -> pd.Series: + """:func:`impute_us_voluntary_filing` on a person and a tax-unit table. + + One model for every spine: the donor stage reads its frame's two tables + through it, and the ACS local lane passes a view of its ACS tax units + (microcosm#1720). Returns one boolean per row of ``tax_unit``, on its + index. + """ + required = { *SIPP_VOLUNTARY_FILING_MODEL_PREDICTORS, _OUTPUT, @@ -869,8 +914,10 @@ def impute_us_voluntary_filing( training = training.iloc[order].reset_index(drop=True) weights = weights[order] - receiver = _recipient_tax_unit_predictor_table(frame) - source_receiver, fanout_keys = _source_receiver_rows(frame, receiver) + receiver = _recipient_tax_unit_predictor_table_from_tables(person, tax_unit) + source_receiver, fanout_keys = _source_receiver_rows_from_table( + tax_unit, receiver + ) global QRF if QRF is None: from importlib import import_module @@ -900,7 +947,7 @@ def impute_us_voluntary_filing( raise ValueError("SIPP voluntary-filing source-unit fan-out is incomplete.") return pd.Series( fanout.to_numpy(dtype=bool), - index=frame.table("tax_unit").index, + index=tax_unit.index, name=_OUTPUT, ) diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/weeks_unemployed.py b/packages/microcosm-build/src/microcosm/build/us_runtime/weeks_unemployed.py index dd7e366411..382e6831f6 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/weeks_unemployed.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/weeks_unemployed.py @@ -82,6 +82,7 @@ "fill_asec_2022_weeks_unemployed_source", "impute_us_weeks_unemployed_to_puf_support_from_manifest", "load_asec_2023_weeks_unemployed_source", + "postprocess_us_weeks_unemployed_predictions", "us_weeks_unemployed_signal_gate", "us_weeks_unemployed_stage_spec", "us_weeks_unemployed_summary", @@ -966,11 +967,15 @@ def impute_us_weeks_unemployed_to_puf_support_from_manifest( raise SourceRuntimeError( "US weeks-unemployed QRF produced nonfinite predictions." ) - lower, upper = operation.parameters["clip"] - predicted = np.rint(np.clip(predicted, float(lower), float(upper))) - if _OPTIONAL_UC_PREDICTOR in predictors: - uc = test[_OPTIONAL_UC_PREDICTOR].to_numpy(dtype=np.float64) - predicted = np.where(uc > 0.0, predicted, 0.0) + predicted = postprocess_us_weeks_unemployed_predictions( + predicted, + unemployment_compensation=( + test[_OPTIONAL_UC_PREDICTOR].to_numpy(dtype=np.float64) + if _OPTIONAL_UC_PREDICTOR in predictors + else None + ), + clip=tuple(operation.parameters["clip"]), + ) if not ( np.isfinite(predicted).all() and (predicted == np.floor(predicted)).all() @@ -987,6 +992,34 @@ def impute_us_weeks_unemployed_to_puf_support_from_manifest( return result +def postprocess_us_weeks_unemployed_predictions( + predicted: np.ndarray, + *, + unemployment_compensation: np.ndarray | None, + clip: tuple[float, float] | None = None, +) -> np.ndarray: + """The archived post-processing of QRF weeks: clip, round, zero rule. + + Predictions are clipped to ``clip`` (by default the reviewed contract's + 0--52) and rounded to the nearest integer; + with ``unemployment_compensation`` given, weeks are 0 wherever it is not + positive (the archived zero rule). One rule for every spine: the PUF + support half calls it, and the ACS local lane on its ACS rows + (microcosm#1720). + """ + + lower, upper = ( + clip if clip is not None else WEEKS_UNEMPLOYED_PUF_IMPUTATION_PARAMETERS["clip"] + ) + result = np.rint( + np.clip(np.asarray(predicted, dtype=np.float64), float(lower), float(upper)) + ) + if unemployment_compensation is not None: + uc = np.asarray(unemployment_compensation, dtype=np.float64) + result = np.where(uc > 0.0, result, 0.0) + return result + + def _decoded_strings(values: pd.Series) -> pd.Series: return values.map( lambda value: ( diff --git a/packages/microcosm-build/tests/engine_contract/us/test_us_acs_local_aca_take_up.py b/packages/microcosm-build/tests/engine_contract/us/test_us_acs_local_aca_take_up.py new file mode 100644 index 0000000000..bba553dd2f --- /dev/null +++ b/packages/microcosm-build/tests/engine_contract/us/test_us_acs_local_aca_take_up.py @@ -0,0 +1,177 @@ +"""The ACS local ACA take-up stage with the real engine (microcosm#1720). + +The release tool's pre-pass runs the fiscal lane's batched ACA tax-unit +table under materialize's engine-pass contract, first on the donor +households, then on the ACS households, and the stage runs the fiscal lane's +``aca_marketplace_inputs`` manifest stage on the ACS tax units against what +the donor rows leave of each state count. Engine-free tests cover the +accounting on invented values; this test checks that the real engine's +values flow through it. +""" + +from __future__ import annotations + +import json + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build.us_runtime.base_pool import spine_column +from microcosm.frame import Frame +from test_support.microcosm_build.us_acs_local_esi_premiums import ( + build_lane, + dense_donor, + raw_acs, +) +from test_support.microcosm_build.us_acs_local_release_tool import ( + load_staging_builder_module, + load_tool_module, +) + +TAKE_UP = "takes_up_aca_if_eligible" +RATIO = "selected_marketplace_plan_benchmark_ratio" +CMS = "cms_aca_aptc_recipients_by_state" +RETURNS = "irs_soi_premium_tax_credit_returns_by_state" +AMOUNT = "irs_soi_premium_tax_credit_amount_by_state" +ACS = "acs_2024_1yr" + + +@pytest.fixture(scope="module") +def staged() -> Frame: + """A staged lane frame with the ACA inputs on donor rows only. + + The donor stores both ACA inputs, as a national release does; the ACS + rows carry them missing, with the ``SERIALNO``/``SPORDER`` keys PUMS + gives them, and no person reports Marketplace coverage. + """ + + frame = build_lane(dense_donor(120), raw_acs(100), n_estimators=5).frame + tax_unit = frame.table("tax_unit").copy() + person = frame.table("person").copy() + household = frame.table("household").copy() + acs_units = tax_unit[spine_column("tax_unit")].eq(ACS) + acs_persons = person[spine_column("person")].eq(ACS).to_numpy() + acs_households = household[spine_column("household")].eq(ACS) + rng = np.random.default_rng(0) + tax_unit[TAKE_UP] = pd.Series(rng.random(len(tax_unit)) < 0.5, dtype=object).where( + ~acs_units, np.nan + ) + tax_unit[RATIO] = pd.Series( + np.where(rng.random(len(tax_unit)) < 0.3, 0.8, 1.0) + ).where(~acs_units, np.nan) + person["has_marketplace_health_coverage_at_interview"] = False + # Pinned, so the eligible pool never rests on a drawn has_esi: staging + # writes it from HINS1 (microcosm#1720, A6), which this fixture lacks. + person["has_esi"] = False + person["SPORDER"] = np.where(acs_persons, 1.0, np.nan) + household["SERIALNO"] = pd.Series( + [f"2024HU{value:07d}" for value in household["household_id"]], dtype=object + ).where(acs_households, np.nan) + return Frame( + { + **{entity: frame.table(entity) for entity in frame.entities}, + "tax_unit": tax_unit, + "person": person, + "household": household, + }, + frame.schema, + {"household": frame.weights_for("household")}, + frame.strata, + ) + + +def _summary(tmp_path, frame: Frame): + audit = load_staging_builder_module()._legacy._engine_input_null_audit(frame) + path = tmp_path / "acs_multispine_staging.summary.json" + path.write_text(json.dumps({"reviewed_engine_input_nulls": audit})) + return path + + +def _tables(frame: Frame, values: dict[str, float]) -> dict[str, pd.DataFrame]: + states = sorted({int(code) for code in frame.table("household")["state_fips"]}) + return { + name: pd.DataFrame( + {"state_fips": [f"{code:02d}" for code in states], "target": value} + ) + for name, value in values.items() + } + + +def test_the_stage_runs_on_the_real_engine_and_meets_the_soi_residuals( + tmp_path, staged +) -> None: + tool = load_tool_module() + summary = _summary(tmp_path, staged) + acs = staged.table("tax_unit")[spine_column("tax_unit")].eq(ACS).to_numpy() + + # Counts far above what any set of rows carries: every eligible ACS + # unit takes up, which measures each state's donor contribution and ACS + # capacity with the engine. + huge = _tables(staged, {CMS: 1e9, RETURNS: 1e9, AMOUNT: 1e13}) + _saturated, measured = tool._with_local_aca_take_up( + staged, + seed=3, + targets={"target_tables": huge}, + summary_path=summary, + hh_chunk=60, + ) + assert measured["engine_prepass"]["acs_eligible_tax_units"] > 0 + assert measured["engine_prepass"]["donor"]["eligible_tax_units"] > 0 + rows = { + name: {row["state_fips"]: row for row in entry["states"]} + for name, entry in measured["tables"].items() + } + + # Counts that leave each state's ACS rows half their capacity to fill. + tables = { + name: pd.DataFrame( + { + "state_fips": list(by_state), + "target": [ + row["donor"] + 0.5 * row["acs_capacity"] + for row in by_state.values() + ], + } + ) + for name, by_state in rows.items() + } + # One batch this time: the donor contributions must not depend on it. + result, receipt = tool._with_local_aca_take_up( + staged, + seed=3, + targets={"target_tables": tables}, + summary_path=summary, + hh_chunk=1_000, + ) + + assert receipt["binding_table"] == RETURNS + assert receipt["stop_after"] == "support_clip" + assert receipt["gate"]["passed"], receipt["gate"]["failures"] + assert receipt["gate"]["report_only"] is True + for row in receipt["tables"][RETURNS]["states"]: + if row["acs_capacity"] <= 0: + continue + assert row["donor"] == pytest.approx(rows[RETURNS][row["state_fips"]]["donor"]) + assert row["residual"] <= row["acs_delivered"] + assert row["acs_delivered"] < row["residual"] + row["acs_max_unit_weight"] + units = result.table("tax_unit") + assert units.loc[acs, TAKE_UP].notna().all() + assert units.loc[acs, RATIO].between(0.5, 1.5).all() + flags = units.loc[acs, TAKE_UP].astype(bool) + assert flags.any() and not flags.all() + # Donor cells are the donor's own. + for column in (TAKE_UP, RATIO): + assert ( + units.loc[~acs, column].tolist() + == staged.table("tax_unit").loc[~acs, column].tolist() + ) + # The recorded assignment reproduces the stage on a fresh staging frame. + path = tmp_path / tool.ACS_ACA_TAKE_UP_FILENAME + receipt["assignment_file"] = { + "name": path.name, + "sha256": tool._write_aca_take_up(result, path), + } + applied = tool._with_recorded_aca_take_up(staged, receipt, path) + for column in (TAKE_UP, RATIO): + assert applied.table("tax_unit")[column].tolist() == units[column].tolist() diff --git a/packages/microcosm-build/tests/engine_free/shared/test_anchor_thinning.py b/packages/microcosm-build/tests/engine_free/shared/test_anchor_thinning.py new file mode 100644 index 0000000000..a372a9b211 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/shared/test_anchor_thinning.py @@ -0,0 +1,117 @@ +"""Keyed thinning of reported take-up anchors to a residual count (#1720).""" + +from __future__ import annotations + +import numpy as np +import pytest + +from microcosm.build.anchor_thinning import ( + anchor_keep_uniforms, + thin_anchors_to_residuals, +) +from microcosm.build.stochastic_assignment import stable_identity_uniforms + +STREAM = "test_anchor_keep" + + +def _rows(n: int, *, groups=("06", "36"), seed: int = 0) -> dict[str, np.ndarray]: + rng = np.random.default_rng(seed) + return { + "groups": np.asarray(groups)[np.arange(n) % len(groups)], + "weights": rng.uniform(0.5, 2.0, n), + "counted": rng.random(n) < 0.8, + "fixed": np.zeros(n, dtype=bool), + "anchors": rng.random(n) < 0.5, + "keys": np.asarray([f"2024HU{i:07d}:1" for i in range(n)], dtype=object), + } + + +def _thin(rows, residuals, *, seed: int = 7, stream: str = STREAM): + return thin_anchors_to_residuals( + **rows, residuals=residuals, seed=seed, stream=stream + ) + + +def _mass(rows, selected, group) -> float: + chosen = selected & rows["counted"] & (rows["groups"] == group) + return float(rows["weights"][chosen].sum()) + + +def test_anchors_that_fit_the_residual_are_all_kept() -> None: + rows = _rows(400) + anchored = {group: _mass(rows, rows["anchors"], group) for group in ("06", "36")} + result = _thin(rows, {group: mass + 1.0 for group, mass in anchored.items()}) + assert result.keep_probability == {"06": 1.0, "36": 1.0} + assert result.thinned_groups == [] + assert np.array_equal(result.kept, rows["anchors"]) + assert result.anchor_mass == pytest.approx(anchored) + + +def test_the_keep_probability_meets_the_residual_after_the_fixed_mass() -> None: + rows = _rows(400) + rows["fixed"] = ~rows["anchors"] & (np.arange(400) % 7 == 0) + fixed = {group: _mass(rows, rows["fixed"], group) for group in ("06", "36")} + anchored = {group: _mass(rows, rows["anchors"], group) for group in ("06", "36")} + residuals = {"06": fixed["06"] + 0.25 * anchored["06"], "36": 0.5 * fixed["36"]} + result = _thin(rows, residuals) + assert result.keep_probability["06"] == pytest.approx(0.25) + # Fixed rows alone exceed the residual: no anchor is kept there. + assert result.keep_probability["36"] == 0.0 + assert result.thinned_groups == ["06", "36"] + assert not result.kept[rows["groups"] == "36"].any() + assert result.fixed_mass == pytest.approx(fixed) + # Only anchors are kept; a fixed row is not an anchor. + assert not (result.kept & ~rows["anchors"]).any() + + +def test_uncounted_anchors_are_thinned_with_their_group() -> None: + rows = _rows(4_000) + residual = 0.5 * _mass(rows, rows["anchors"], "06") + result = _thin(rows, {"06": residual}) + uncounted = rows["anchors"] & ~rows["counted"] & (rows["groups"] == "06") + assert 0.4 < result.kept[uncounted].mean() < 0.6 + # A group without a residual keeps every anchor. + other = rows["anchors"] & (rows["groups"] == "36") + assert result.kept[other].all() + assert "36" not in result.keep_probability + + +def test_the_kept_mass_meets_the_residual_in_expectation() -> None: + rows = _rows(200_000, groups=("06",)) + rows["weights"] = np.ones(200_000) + anchored = _mass(rows, rows["anchors"], "06") + result = _thin(rows, {"06": 0.5 * anchored}) + kept = _mass(rows, result.kept, "06") + # Independent keep draws: the relative noise is about 1 / sqrt(n p / (1 - p)), + # here near 0.3%, so the kept mass sits well within 2% of the residual. + assert kept == pytest.approx(0.5 * anchored, rel=0.02) + + +def test_a_record_keeps_its_result_in_any_row_order() -> None: + rows = _rows(2_000) + residuals = { + group: 0.4 * _mass(rows, rows["anchors"], group) for group in ("06", "36") + } + result = _thin(rows, residuals) + order = np.random.default_rng(1).permutation(2_000) + shuffled = _thin({name: values[order] for name, values in rows.items()}, residuals) + assert np.array_equal(shuffled.kept, result.kept[order]) + assert shuffled.keep_probability == pytest.approx(result.keep_probability) + # Another seed or another stream keeps other records. + assert not np.array_equal(_thin(rows, residuals, seed=8).kept, result.kept) + assert not np.array_equal(_thin(rows, residuals, stream="other").kept, result.kept) + + +def test_the_keep_draw_is_the_shared_keyed_uniform() -> None: + keys = ["2024HU0000001:1", "2024HU0000002:3"] + assert np.array_equal( + anchor_keep_uniforms(keys, seed=5, stream=STREAM), + stable_identity_uniforms(keys, seed=5, salt=STREAM), + ) + + +def test_misaligned_rows_are_refused() -> None: + rows = _rows(10) + rows["weights"] = rows["weights"][:9] + with pytest.raises(ValueError, match="aligned"): + _thin(rows, {"06": 1.0}) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_aca_take_up.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_aca_take_up.py new file mode 100644 index 0000000000..ea418fa1c2 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_aca_take_up.py @@ -0,0 +1,838 @@ +"""ACS-row ACA take-up and plan ratio for the retained ACS local lane +(microcosm#1720), with stubbed engine pre-pass values.""" + +from __future__ import annotations + +import copy + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build.us_runtime.acs_local_aca_take_up import ( + ACS_LOCAL_ACA_TAKE_UP_COLUMNS, + ACS_LOCAL_ACA_TAKE_UP_GATE_NAME, + ACS_LOCAL_ACA_TAKE_UP_ISSUE, + acs_local_aca_take_up_assignment, + acs_local_aca_take_up_signal_gate, + with_acs_local_aca_take_up, + with_recorded_acs_local_aca_take_up, +) +from microcosm.build.us_runtime.acs_pums import ACS_2024_1YR_SPINE +from microcosm.build.us_runtime.acs_transfer import ASEC_PUF_DONOR_SPINE +from microcosm.build.us_runtime.base_pool import spine_column +from microcosm.frame import US_SCHEMA, Frame, WeightKind, Weights + +TAKE_UP = "takes_up_aca_if_eligible" +RATIO = "selected_marketplace_plan_benchmark_ratio" +CMS = "cms_aca_aptc_recipients_by_state" +RETURNS = "irs_soi_premium_tax_credit_returns_by_state" +AMOUNT = "irs_soi_premium_tax_credit_amount_by_state" +COVERAGE = "has_marketplace_health_coverage_at_interview" +#: The manifest stage's anchor column; staging writes none today. +ANCHOR = "reported_has_subsidized_marketplace_health_coverage_at_interview" +STATES = (6, 36, 48) +#: Stub engine values ride the tax-unit table, so the pre-pass view carries +#: them: eligibility, the credit before the filing gate, the SLCSP, the +#: reported premium and whether the unit files for another reason. +STUB = ("stub_eligible", "stub_credit", "stub_slcsp", "stub_premium", "stub_filer") + + +def _frame(*, n_donor: int = 300, n_acs: int = 1500, seed: int = 3) -> Frame: + """Donor persons alone in their units; ACS households of two persons. + + Even ACS households file one return for both persons and odd ones two, + so a unit's draw key is its lowest ``SPORDER``. Donor units store both + ACA inputs; ACS units carry them missing. + """ + + rng = np.random.default_rng(seed) + donor_households = np.arange(1, n_donor + 1) + acs_households = np.arange(n_donor + 1, n_donor + n_acs + 1) + households = np.concatenate([donor_households, acs_households]) + person_household = np.concatenate([donor_households, np.repeat(acs_households, 2)]) + n = len(person_household) + acs = np.arange(n) >= n_donor + unit_of = np.empty(n, dtype=np.int64) + unit_of[:n_donor] = np.arange(1, n_donor + 1) + sporder = np.full(n, np.nan) + next_id = n_donor + 1 + for k, household in enumerate(acs_households): + first, second = n_donor + 2 * k, n_donor + 2 * k + 1 + sporder[first], sporder[second] = 1.0, 2.0 + unit_of[first] = next_id + unit_of[second] = next_id if household % 2 == 0 else next_id + 1 + next_id += 1 if household % 2 == 0 else 2 + ids = np.arange(1, n + 1) + person = pd.DataFrame( + { + "person_id": ids, + "person_household_id": person_household, + "person_tax_unit_id": unit_of, + spine_column("person"): np.where( + acs, ACS_2024_1YR_SPINE, ASEC_PUF_DONOR_SPINE + ), + "SPORDER": sporder, + COVERAGE: rng.random(n) < 0.05, + } + ) + tables = {"person": person} + for entity in ("spm_unit", "family", "marital_unit"): + person[f"person_{entity}_id"] = ids + tables[entity] = pd.DataFrame({f"{entity}_id": ids}) + unit_ids = np.arange(1, next_id) + units = len(unit_ids) + donor_unit = unit_ids <= n_donor + eligible = rng.random(units) < 0.4 + stored = eligible & (rng.random(units) < 0.5) + tables["tax_unit"] = pd.DataFrame( + { + "tax_unit_id": unit_ids, + spine_column("tax_unit"): np.where( + donor_unit, ASEC_PUF_DONOR_SPINE, ACS_2024_1YR_SPINE + ), + "stub_eligible": eligible, + "stub_credit": np.where(eligible, rng.uniform(500, 8_000, units), 0.0), + "stub_slcsp": rng.uniform(5_000, 12_000, units), + "stub_premium": rng.uniform(0, 6_000, units), + "stub_filer": rng.random(units) < 0.6, + TAKE_UP: pd.Series(stored, dtype=object).where(donor_unit, np.nan), + RATIO: pd.Series(np.where(stored, rng.uniform(0.6, 1.3, units), 1.0)).where( + donor_unit, np.nan + ), + } + ) + household_acs = households > n_donor + tables["household"] = pd.DataFrame( + { + "household_id": households, + spine_column("household"): np.where( + household_acs, ACS_2024_1YR_SPINE, ASEC_PUF_DONOR_SPINE + ), + "SERIALNO": pd.Series( + [f"2024HU{i:07d}" for i in households], dtype=object + ).where(household_acs, np.nan), + "state_fips": rng.choice(STATES, len(households)), + } + ) + weights = rng.uniform(0.5, 2.0, len(households)) + return Frame( + tables, US_SCHEMA, {"household": Weights(weights, WeightKind.CALIBRATED)} + ) + + +def _with_tax_unit(frame: Frame, tax_unit: pd.DataFrame) -> Frame: + return Frame( + { + entity: tax_unit if entity == "tax_unit" else frame.table(entity) + for entity in frame.entities + }, + frame.schema, + {"household": frame.weights_for("household")}, + ) + + +def _unit_values(frame: Frame, *, flags: np.ndarray, person_counts: bool = True): + """The fiscal lane's tax-unit table, computed from the stub columns. + + The credit is gated on filing as on policyengine-us 2.145.3: a unit + whose flag is ``True`` or that files anyway gets it. + """ + + units = frame.table("tax_unit") + person = frame.table("person") + household = frame.table("household").set_index("household_id") + weight = pd.Series( + np.asarray(frame.weights_for("household").values, dtype=np.float64), + index=household.index, + ) + members = person.groupby("person_tax_unit_id") + home = members["person_household_id"].first().reindex(units["tax_unit_id"]) + size = members.size().reindex(units["tax_unit_id"]).to_numpy() + household_weight = weight.reindex(home.to_numpy()).to_numpy() + eligible = units["stub_eligible"].to_numpy(dtype=bool) + gate = np.asarray(flags, dtype=bool) | units["stub_filer"].to_numpy(dtype=bool) + credit = np.where(eligible, units["stub_credit"].to_numpy(), 0.0) * gate + people = np.where(eligible, household_weight * size, 0.0) + unit_weight = people if person_counts else household_weight + return pd.DataFrame( + { + "tax_unit_id": units["tax_unit_id"].to_numpy(), + "state_fips": household["state_fips"] + .reindex(home.to_numpy()) + .astype(str) + .str.zfill(2) + .to_numpy(), + "tax_unit_weight": unit_weight, + "household_weight": household_weight, + "is_aca_ptc_eligible": (unit_weight > 0) & (credit > 0), + "health_insurance_premiums_without_medicare_part_b": units[ + "stub_premium" + ].to_numpy(), + "assigned_aca_ptc": credit, + "weighted_assigned_aca_ptc": credit * household_weight, + "slcsp": units["stub_slcsp"].to_numpy(), + } + ) + + +def _stub(calls: list | None = None): + """The pre-pass callable: the stub table plus the fiscal lane's rate.""" + + def table(view: Frame, tables) -> pd.DataFrame: + flags = view.table("tax_unit")[TAKE_UP] + if calls is not None: + calls.append( + { + "units": view.table("tax_unit").copy(), + "tables": {name: value.copy() for name, value in tables.items()}, + } + ) + values = _unit_values( + view, flags=flags.astype(bool).to_numpy(), person_counts=CMS in tables + ) + cms = tables.get(CMS) + rate = pd.Series(0.0, index=values.index) + if cms is not None: + eligible = values.loc[values["is_aca_ptc_eligible"]] + weighted = eligible.groupby("state_fips")["tax_unit_weight"].sum() + rates = (cms.set_index("state_fips")["target"] / weighted).fillna(0.0) + rate = values["state_fips"].map(rates).fillna(0.0).clip(0.0, 1.0) + values["aca_take_up_rate"] = rate + return values + + return table + + +def _sums(frame: Frame, *, acs: bool) -> dict[str, dict[str, float]]: + """Per table and state: what one set of rows delivers (ACS: at most).""" + + units = frame.table("tax_unit") + rows = units[spine_column("tax_unit")].eq(ACS_2024_1YR_SPINE).to_numpy() + if not acs: + rows = ~rows + flags = ( + np.ones(len(units), dtype=bool) + if acs + else units[TAKE_UP] + .where(pd.Series(rows, index=units.index), False) + .astype(bool) + .to_numpy() + ) + values = _unit_values(frame, flags=flags | acs) + chosen = rows & flags & values["is_aca_ptc_eligible"].to_numpy() + result: dict[str, dict[str, float]] = {} + for name, column in ( + (CMS, "tax_unit_weight"), + (RETURNS, "household_weight"), + (AMOUNT, "weighted_assigned_aca_ptc"), + ): + summed = ( + pd.Series(np.where(chosen, values[column], 0.0)) + .groupby(values["state_fips"].to_numpy()) + .sum() + ) + result[name] = {str(state): float(value) for state, value in summed.items()} + return result + + +def _targets( + frame: Frame, *, fraction: float = 0.4, excess_state: str | None = None +) -> dict[str, pd.DataFrame]: + """Counts whose donor residual is ``fraction`` of the ACS capacity. + + In ``excess_state`` every count sits below the donor contribution. + """ + + donor, capacity = _sums(frame, acs=False), _sums(frame, acs=True) + tables = {} + for name in (CMS, RETURNS, AMOUNT): + rows = [] + for state in (f"{code:02d}" for code in STATES): + base = donor[name].get(state, 0.0) + target = ( + 0.5 * base + if state == excess_state + else base + fraction * capacity[name].get(state, 0.0) + ) + rows.append({"state_fips": state, "target": target}) + tables[name] = pd.DataFrame(rows) + return tables + + +def _assign(frame: Frame, tables=None, *, seed: int = 7, calls=None, **kwargs): + return with_acs_local_aca_take_up( + frame, + seed=seed, + target_tables=_targets(frame, **kwargs) if tables is None else tables, + aca_tax_units=_stub(calls), + ) + + +@pytest.fixture(scope="module") +def frame() -> Frame: + return _frame() + + +@pytest.fixture(scope="module") +def assigned(frame): + return _assign(frame, excess_state="48") + + +def _acs_units(frame: Frame) -> np.ndarray: + return ( + frame.table("tax_unit")[spine_column("tax_unit")] + .eq(ACS_2024_1YR_SPINE) + .to_numpy() + ) + + +def test_each_residual_is_its_count_minus_the_donor_rows_floored_at_zero( + frame, assigned +) -> None: + _, receipt = assigned + donor = _sums(frame, acs=False) + tables = _targets(frame, excess_state="48") + assert receipt["issue"] == ACS_LOCAL_ACA_TAKE_UP_ISSUE + for name in (CMS, RETURNS, AMOUNT): + rows = {row["state_fips"]: row for row in receipt["tables"][name]["states"]} + for state, target in zip( + tables[name]["state_fips"], tables[name]["target"], strict=True + ): + row = rows[state] + assert row["target"] == pytest.approx(target) + assert row["donor"] == pytest.approx(donor[name][state]) + assert row["residual"] == pytest.approx( + max(target - donor[name][state], 0.0) + ) + # The donor rows alone exceed Texas's counts: no ACS unit takes up. + assert rows["48"]["residual"] == 0.0 + assert rows["48"]["donor_excess"] > 0 + assert rows["48"]["acs_delivered"] == 0.0 + + +def test_the_soi_return_count_binds_and_the_cms_people_are_reported(assigned) -> None: + _, receipt = assigned + assert receipt["binding_table"] == RETURNS + assert receipt["tables"][RETURNS]["binds"] is True + assert receipt["tables"][CMS]["binds"] is False + for row in receipt["tables"][RETURNS]["states"]: + if row["residual"] <= 0: + continue + # The greedy fill stops on the first unit that crosses the residual. + assert row["acs_capacity"] > row["residual"] + assert row["residual"] <= row["acs_delivered"] + assert row["acs_delivered"] < row["residual"] + row["acs_max_unit_weight"] + composition = receipt["composition"] + assert composition["people_table"] == CMS + assert composition["returns_table"] == RETURNS + assert composition["acs"] > 1.0 + assert receipt["stop_after"] == "support_clip" + + +def test_only_missing_acs_cells_are_filled_and_donor_cells_are_kept( + frame, assigned +) -> None: + result, receipt = assigned + acs = _acs_units(frame) + before = frame.table("tax_unit") + after = result.table("tax_unit") + for column in ACS_LOCAL_ACA_TAKE_UP_COLUMNS: + assert after.loc[~acs, column].tolist() == before.loc[~acs, column].tolist() + assert after.loc[acs, column].notna().all() + flags = after.loc[acs, TAKE_UP].astype(bool) + assert flags.any() and not flags.all() + assert receipt["take_up"]["filled_rows"] == int(acs.sum()) + assert receipt["take_up"]["unfilled_acs_rows"] == 0 + assert receipt["plan_ratio"]["unfilled_acs_rows"] == 0 + # Only units eligible with a positive credit take up. + values = _unit_values(result, flags=np.ones(len(after), dtype=bool)) + eligible = values["is_aca_ptc_eligible"].to_numpy() + assert not (flags.to_numpy() & ~eligible[acs]).any() + + +def test_takers_get_the_clipped_premium_ratio_and_others_the_benchmark( + frame, assigned +) -> None: + result, _ = assigned + acs = _acs_units(frame) + units = result.table("tax_unit").loc[acs] + values = _unit_values(result, flags=np.ones(len(_acs_units(result)), dtype=bool)) + values = values.loc[acs] + takers = units[TAKE_UP].astype(bool).to_numpy() + expected = np.clip( + ( + values["health_insurance_premiums_without_medicare_part_b"] + + values["assigned_aca_ptc"] + ) + / values["slcsp"], + 0.5, + 1.5, + ).to_numpy() + ratio = units[RATIO].to_numpy(dtype=float) + np.testing.assert_allclose(ratio[takers], expected[takers]) + assert (ratio[~takers] == 1.0).all() + + +def test_the_prepass_reads_stored_donor_flags_then_acs_defaults(frame) -> None: + calls: list = [] + tables = _targets(frame) + _assign(frame, tables, calls=calls) + donor_call, acs_call = calls + donor_units = donor_call["units"] + assert donor_units[spine_column("tax_unit")].eq(ASEC_PUF_DONOR_SPINE).all() + stored = frame.table("tax_unit").set_index("tax_unit_id")[TAKE_UP] + assert ( + donor_units[TAKE_UP].tolist() + == stored.reindex(donor_units["tax_unit_id"]).tolist() + ) + pd.testing.assert_frame_equal(donor_call["tables"][CMS], tables[CMS]) + acs_units = acs_call["units"] + assert acs_units[spine_column("tax_unit")].eq(ACS_2024_1YR_SPINE).all() + # A missing cell reads the engine default, so the credit is the + # credit before the filing gate. + assert acs_units[TAKE_UP].eq(True).all() + assert acs_units[RATIO].eq(1.0).all() + # And the ACS pass is given the residuals, which its rate reads. + assert acs_call["tables"][RETURNS]["target"].sum() < tables[RETURNS]["target"].sum() + + +def test_a_saturated_state_takes_up_every_eligible_unit(frame) -> None: + tables = _targets(frame, fraction=3.0) + result, receipt = _assign(frame, tables) + for row in receipt["tables"][RETURNS]["states"]: + assert row["capacity_shortfall"] > 0 + assert row["acs_delivered"] == pytest.approx(row["acs_capacity"]) + acs = _acs_units(frame) + values = _unit_values(result, flags=np.ones(len(acs), dtype=bool)) + eligible = values["is_aca_ptc_eligible"].to_numpy()[acs] + assert result.table("tax_unit").loc[acs, TAKE_UP].astype(bool)[eligible].all() + gate = acs_local_aca_take_up_signal_gate(result, receipt=receipt) + assert gate.passed, gate.failures + assert {row["status"] for row in gate.details["binding_states"]} == {"saturated"} + + +def test_stored_acs_cells_are_kept_true_as_an_anchor_false_out_of_the_stage( + frame, +) -> None: + acs = _acs_units(frame) + units = frame.table("tax_unit").copy() + values = _unit_values(frame, flags=np.ones(len(units), dtype=bool)) + eligible = values["is_aca_ptc_eligible"].to_numpy() + acs_eligible = np.flatnonzero(acs & eligible) + anchor, excluded = acs_eligible[:5], acs_eligible[5:10] + flags = units[TAKE_UP].astype(object) + flags.iloc[anchor] = True + flags.iloc[excluded] = False + units[TAKE_UP] = flags + ratio = units[RATIO].astype(float) + ratio.iloc[excluded] = 0.9 + units[RATIO] = ratio + stored = _with_tax_unit(frame, units) + + result, receipt = _assign(stored, _targets(frame, fraction=0.0)) + + after = result.table("tax_unit") + assert after[TAKE_UP].iloc[anchor].astype(bool).all() + assert not after[TAKE_UP].iloc[excluded].astype(bool).any() + assert after[RATIO].iloc[excluded].tolist() == [0.9] * 5 + assert receipt["anchor"]["stored_true_tax_units"] == 5 + assert receipt["take_up"]["preserved_acs_rows"] == 10 + assert receipt["take_up"]["stored_false_rows_kept"] == 5 + # Every residual is 0, so only the anchors take up. + assert int(after.loc[acs, TAKE_UP].astype(bool).sum()) == 5 + + +def test_draws_key_on_the_acs_record_not_on_the_tax_unit_id(frame) -> None: + # The CMS table alone, where the draw decides the takers: with the SOI + # tables the joint step orders units by their credit's distance from the + # residual average and reads the draw only to break ties, as on the donor. + tables = {CMS: _targets(frame)[CMS]} + result, _ = _assign(frame, tables) + acs = _acs_units(frame) + shift = 10_000 + units = frame.table("tax_unit").copy() + units.loc[acs, "tax_unit_id"] += shift + person = frame.table("person").copy() + moved = person[spine_column("person")].eq(ACS_2024_1YR_SPINE) + person.loc[moved, "person_tax_unit_id"] += shift + renumbered = Frame( + { + **{entity: frame.table(entity) for entity in frame.entities}, + "tax_unit": units, + "person": person, + }, + frame.schema, + {"household": frame.weights_for("household")}, + ) + again, _ = _assign(renumbered, tables) + for column in ACS_LOCAL_ACA_TAKE_UP_COLUMNS: + assert ( + again.table("tax_unit").loc[acs, column].tolist() + == result.table("tax_unit").loc[acs, column].tolist() + ) + # Another seed draws other takers. + other, _ = _assign(frame, tables, seed=8) + assert ( + other.table("tax_unit").loc[acs, TAKE_UP].tolist() + != result.table("tax_unit").loc[acs, TAKE_UP].tolist() + ) + + +def test_a_recorded_assignment_reproduces_its_digest_or_is_refused( + frame, assigned +) -> None: + result, receipt = assigned + recorded = acs_local_aca_take_up_assignment(result) + assert recorded.columns.tolist() == ["tax_unit_id", *ACS_LOCAL_ACA_TAKE_UP_COLUMNS] + applied = with_recorded_acs_local_aca_take_up( + frame, recorded, assigned_sha256=receipt["assigned_sha256"] + ) + for column in ACS_LOCAL_ACA_TAKE_UP_COLUMNS: + assert ( + applied.table("tax_unit")[column].tolist() + == result.table("tax_unit")[column].tolist() + ) + with pytest.raises(ValueError, match="digest"): + with_recorded_acs_local_aca_take_up(frame, recorded, assigned_sha256="0" * 64) + changed = recorded.copy() + changed.loc[changed.index[0], RATIO] = changed[RATIO].iloc[0] + 0.01 + with pytest.raises(ValueError, match="digest"): + with_recorded_acs_local_aca_take_up( + frame, changed, assigned_sha256=receipt["assigned_sha256"] + ) + with pytest.raises(ValueError, match="in order"): + with_recorded_acs_local_aca_take_up( + frame, + recorded.iloc[::-1].reset_index(drop=True), + assigned_sha256=receipt["assigned_sha256"], + ) + flipped = result.table("tax_unit").copy() + acs = _acs_units(result) + first = np.flatnonzero(acs)[0] + flipped.loc[first, TAKE_UP] = not bool(flipped.loc[first, TAKE_UP]) + with pytest.raises(ValueError, match="disagree"): + with_recorded_acs_local_aca_take_up( + _with_tax_unit(result, flipped), + recorded, + assigned_sha256=receipt["assigned_sha256"], + ) + with pytest.raises(ValueError, match="not complete"): + acs_local_aca_take_up_assignment(frame) + + +def test_the_gate_passes_the_materialize_assignment_and_reports_its_states( + assigned, +) -> None: + result, receipt = assigned + gate = acs_local_aca_take_up_signal_gate(result, receipt=receipt) + assert gate.name == ACS_LOCAL_ACA_TAKE_UP_GATE_NAME + assert gate.passed, gate.failures + statuses = { + row["state_fips"]: row["status"] for row in gate.details["binding_states"] + } + assert statuses["48"] == "donor_meets_count" + assert {statuses["06"], statuses["36"]} == {"within_tolerance"} + + +def test_the_gate_fails_a_tampered_receipt_and_incomplete_cells( + frame, assigned +) -> None: + result, receipt = assigned + tampered = copy.deepcopy(receipt) + tampered["tables"][AMOUNT]["states"][0]["residual"] += 1_000.0 + gate = acs_local_aca_take_up_signal_gate(result, receipt=tampered) + assert not gate.passed + assert any("not the donor residual" in line for line in gate.failures) + + missed = copy.deepcopy(receipt) + row = next( + row for row in missed["tables"][RETURNS]["states"] if row["residual"] > 0 + ) + row["acs_delivered"] = 0.5 * row["residual"] + gate = acs_local_aca_take_up_signal_gate(result, receipt=missed) + assert any("misses the donor residual" in line for line in gate.failures) + + gate = acs_local_aca_take_up_signal_gate(frame, receipt=receipt) + assert not gate.passed + assert any("missing take up rows" in line for line in gate.failures) + + gate = acs_local_aca_take_up_signal_gate(result, receipt=None) + assert any("No acs_local_aca_take_up receipt" in line for line in gate.failures) + + +def test_without_the_soi_tables_the_cms_residual_binds(frame) -> None: + tables = {CMS: _targets(frame)[CMS]} + result, receipt = _assign(frame, tables) + assert receipt["binding_table"] == CMS + assert receipt["composition"] is None + for row in receipt["tables"][CMS]["states"]: + # The greedy calibration adds or removes drawn units until it + # crosses the residual, so it lands within one unit's weight. + assert abs(row["acs_delivered"] - row["residual"]) < row["acs_max_unit_weight"] + gate = acs_local_aca_take_up_signal_gate(result, receipt=receipt) + assert gate.passed, gate.failures + + +def test_malformed_inputs_are_refused(frame) -> None: + tables = _targets(frame) + with pytest.raises(ValueError, match="reads target table"): + _assign(frame, {**tables, "cms_aca_other": tables[CMS]}) + repeated = pd.concat([tables[CMS], tables[CMS]], ignore_index=True) + with pytest.raises(ValueError, match="repeats state"): + _assign(frame, {**tables, CMS: repeated}) + household = frame.table("household").copy() + household.loc[household["SERIALNO"].notna().idxmax(), "SERIALNO"] = np.nan + unkeyed = Frame( + { + **{entity: frame.table(entity) for entity in frame.entities}, + "household": household, + }, + frame.schema, + {"household": frame.weights_for("household")}, + ) + with pytest.raises(ValueError, match="SERIALNO"): + _assign(unkeyed, tables) + units = frame.table("tax_unit").drop(columns=[TAKE_UP]) + with pytest.raises(ValueError, match="universal take-up"): + _assign(_with_tax_unit(frame, units), tables) + + +def _with_reported_anchor(frame: Frame, units: set) -> Frame: + """The frame with the anchor column True for every member of ``units``.""" + + person = frame.table("person").copy() + person[ANCHOR] = person["person_tax_unit_id"].isin(units).to_numpy() + return Frame( + { + entity: person if entity == "person" else frame.table(entity) + for entity in frame.entities + }, + frame.schema, + {"household": frame.weights_for("household")}, + ) + + +def _eligible_acs_units(frame: Frame) -> np.ndarray: + acs = _acs_units(frame) + values = _unit_values(frame, flags=np.ones(len(acs), dtype=bool)) + eligible = values["is_aca_ptc_eligible"].to_numpy() + return frame.table("tax_unit")["tax_unit_id"].to_numpy()[acs & eligible] + + +def _takers(result: Frame) -> set: + units = result.table("tax_unit") + acs = _acs_units(result) + flags = units.loc[acs, TAKE_UP].astype(bool).to_numpy() + return set(units.loc[acs, "tax_unit_id"].to_numpy()[flags]) + + +def _thinning(receipt: dict) -> dict: + return receipt["anchor"]["thinning"] + + +def _as_tables(receipt: dict, scale: float, *, key: str = "acs_anchored") -> dict: + """Counts of donor + ``scale`` x each state's ``key`` in ``receipt``.""" + + return { + name: pd.DataFrame( + { + "state_fips": [row["state_fips"] for row in entry["states"]], + "target": [row["donor"] + scale * row[key] for row in entry["states"]], + } + ) + for name, entry in receipt["tables"].items() + } + + +def test_the_manifest_anchor_column_anchors_acs_units(frame) -> None: + """The stage reads the manifest's own anchor column on ACS persons (as the + fiscal lane does), so the staged subsidy item needs no rule of its own. + Below every residual no anchor is thinned. A unit stored False stays + out.""" + + candidates = _eligible_acs_units(frame) + anchored = set(candidates[::3]) + excluded = candidates[1] + units = frame.table("tax_unit").copy() + flags = units[TAKE_UP].astype(object) + flags[units["tax_unit_id"].eq(excluded).to_numpy()] = False + units[TAKE_UP] = flags + staged = _with_reported_anchor(_with_tax_unit(frame, units), anchored | {excluded}) + + # Each residual is 0.6 of the ACS capacity, above a third of it. + result, receipt = _assign(staged, _targets(frame, fraction=0.6)) + + takers = _takers(result) + assert anchored <= takers + assert excluded not in takers + assert receipt["anchor"]["column"] == ANCHOR + assert receipt["anchor"]["column_on_acs_persons"] is True + assert receipt["anchor"]["reported_tax_units"] == len(anchored) + 1 + assert receipt["anchor"]["anchored_tax_units"] == len(anchored) + thinning = _thinning(receipt) + assert thinning["table"] == RETURNS + assert thinning["anchor_tax_units"] == len(anchored) + assert thinning["thinned_tax_units"] == 0 + assert thinning["thinned_states"] == [] + for row in thinning["states"]: + assert row["keep_probability"] == 1.0 + assert 0 < row["anchor_mass"] < row["residual"] + shares = receipt["take_up"] + assert shares["anchored_taker_tax_units"] == len(anchored) + assert shares["anchor_share_of_takers"] == pytest.approx( + len(anchored) / shares["taker_tax_units"] + ) + gate = acs_local_aca_take_up_signal_gate(result, receipt=receipt) + assert gate.passed, gate.failures + assert gate.details["thinned_states"] == [] + assert "anchors_thinned" not in { + row["status"] for row in gate.details["binding_states"] + } + + +def test_anchors_above_a_residual_are_thinned_to_it(frame) -> None: + """Where a state's anchors weigh more than its residual return count, each + is kept with probability residual / anchored mass on its own keyed draw; + a unit not kept is an ordinary non-anchor that the joint step can still + fill with. The grade reports such a state and does not fail it.""" + + every = set(_eligible_acs_units(frame)) + staged = _with_reported_anchor(frame, every) + _measured, first = _assign(staged, _targets(frame, fraction=0.0)) + + result, receipt = _assign(staged, _as_tables(first, 0.5, key="acs_capacity")) + + thinning = _thinning(receipt) + assert thinning["stream"] == "acs_local_aca_subsidized_anchor_keep" + assert thinning["thinned_states"] == ["06", "36", "48"] + returns = {row["state_fips"]: row for row in receipt["tables"][RETURNS]["states"]} + for row in thinning["states"]: + assert row["anchor_mass"] == pytest.approx( + returns[row["state_fips"]]["acs_capacity"] + ) + assert row["keep_probability"] == pytest.approx( + row["residual"] / row["anchor_mass"] + ) + assert 0 < row["thinned_rows"] < row["anchor_rows"] + kept = receipt["anchor"]["anchored_tax_units"] + assert kept + thinning["thinned_tax_units"] == len(every) + # Kept anchors take up. The joint step fills a kept mass below the + # residual with non-anchors, here only thinned units; above it the kept + # anchors' excess stays. + takers = _takers(result) + assert takers <= every + assert len(takers) == kept + thinning["thinned_tax_units_taking_up"] + for row in returns.values(): + assert row["acs_delivered"] >= row["residual"] + assert row["acs_delivered"] <= (1 + 1e-9) * max( + row["acs_anchored"], row["residual"] + row["acs_max_unit_weight"] + ) + shares = receipt["take_up"] + assert shares["taker_tax_units"] == len(takers) + assert shares["anchor_share_of_takers"] == pytest.approx(kept / len(takers)) + gate = acs_local_aca_take_up_signal_gate(result, receipt=receipt) + assert gate.passed, gate.failures + assert {row["status"] for row in gate.details["binding_states"]} == { + "anchors_thinned" + } + assert gate.details["thinned_states"] == ["06", "36", "48"] + assert set(gate.details["anchor_excess_states"]) == {CMS, RETURNS, AMOUNT} + + +def test_a_thinned_state_delivers_its_residual_within_the_tolerance() -> None: + """With enough anchors the keep draw's noise is small: each thinned state + delivers its residual return count within the grade's tolerance.""" + + large = _frame(n_acs=12_000, seed=4) + staged = _with_reported_anchor(large, set(_eligible_acs_units(large))) + _measured, first = _assign(staged, _targets(large, fraction=0.0)) + + result, receipt = _assign(staged, _as_tables(first, 0.9, key="acs_capacity")) + + assert _thinning(receipt)["thinned_states"] == ["06", "36", "48"] + for row in receipt["tables"][RETURNS]["states"]: + assert row["residual"] > 0 + assert abs(row["acs_delivered"] - row["residual"]) <= 0.02 * row["residual"] + + +def test_the_anchor_keep_draw_is_keyed_on_the_record(frame) -> None: + """Renumbered tax units keep the same anchors; another seed keeps others. + (A frame's tax units are sorted by id, so the row order of the keep draw + itself is tested on the shared helper.)""" + + every = set(_eligible_acs_units(frame)) + staged = _with_reported_anchor(frame, every) + _measured, first = _assign(staged, _targets(frame, fraction=0.0)) + tables = _as_tables(first, 0.5, key="acs_capacity") + result, receipt = _assign(staged, tables) + acs = _acs_units(frame) + + shift = 10_000 + units = staged.table("tax_unit").copy() + units.loc[acs, "tax_unit_id"] += shift + person = staged.table("person").copy() + moved = person[spine_column("person")].eq(ACS_2024_1YR_SPINE) + person.loc[moved, "person_tax_unit_id"] += shift + renumbered = Frame( + { + **{entity: staged.table(entity) for entity in staged.entities}, + "tax_unit": units, + "person": person, + }, + staged.schema, + {"household": staged.weights_for("household")}, + ) + again, again_receipt = _assign(renumbered, tables) + assert ( + again.table("tax_unit").loc[acs, TAKE_UP].tolist() + == result.table("tax_unit").loc[acs, TAKE_UP].tolist() + ) + assert _thinning(again_receipt)["states"] == _thinning(receipt)["states"] + + other, other_receipt = _assign(staged, tables, seed=8) + assert _takers(other) != _takers(result) + assert [row["keep_probability"] for row in _thinning(other_receipt)["states"]] == ( + pytest.approx([row["keep_probability"] for row in _thinning(receipt)["states"]]) + ) + + +def test_thinning_leaves_donor_rows_and_stored_acs_true_alone(frame) -> None: + """Donor cells keep their stored values, a donor person's anchor cell is + not read, and a stored ACS take-up True stands even where every reported + anchor is released.""" + + candidates = _eligible_acs_units(frame) + stored, reported = candidates[:6], set(candidates[6:]) + units = frame.table("tax_unit").copy() + flags = units[TAKE_UP].astype(object) + flags[units["tax_unit_id"].isin(stored).to_numpy()] = True + units[TAKE_UP] = flags + staged = _with_reported_anchor(_with_tax_unit(frame, units), reported) + person = staged.table("person").copy() + donor_persons = person[spine_column("person")].eq(ASEC_PUF_DONOR_SPINE) + person.loc[donor_persons, ANCHOR] = True + staged = Frame( + { + entity: person if entity == "person" else staged.table(entity) + for entity in staged.entities + }, + staged.schema, + {"household": staged.weights_for("household")}, + ) + + # Every residual is 0: the reported anchors are all released. + result, receipt = _assign(staged, _targets(frame, fraction=0.0)) + + after = result.table("tax_unit") + donor = ~_acs_units(frame) + for column in ACS_LOCAL_ACA_TAKE_UP_COLUMNS: + assert after.loc[donor, column].tolist() == units.loc[donor, column].tolist() + assert _takers(result) == set(stored) + thinning = _thinning(receipt) + assert thinning["thinned_tax_units"] == len(reported) + assert thinning["anchor_tax_units"] == len(reported) + assert {row["keep_probability"] for row in thinning["states"]} == {0.0} + assert sum(row["stored_true_mass"] for row in thinning["states"]) > 0 + assert receipt["anchor"]["stored_true_tax_units"] == len(stored) + assert receipt["anchor"]["anchored_tax_units"] == len(stored) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py index bdb57bae6e..77b2b20e12 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py @@ -970,7 +970,10 @@ def _materialize_county_fixture( # counts from the ledger feed and runs an engine pre-pass this fixture # cannot support; this test checks county hooks only. monkeypatch.setattr( - module, "acs_local_ssi_medicaid_take_up_targets", lambda *_a: {} + module, "_compiled_fiscal_registry", lambda *_a: (SimpleNamespace(specs=[]), []) + ) + monkeypatch.setattr( + module, "acs_local_ssi_medicaid_take_up_targets", lambda *_a, **_k: {} ) monkeypatch.setattr( module, @@ -978,6 +981,14 @@ def _materialize_county_fixture( lambda frame, *, seed, **_k: (frame, {"seed": seed, "assigned_sha256": "stub"}), ) monkeypatch.setattr(module, "_write_ssi_medicaid_take_up", lambda *_a: "stub") + # microcosm#1720: likewise the ACA take-up stage. + monkeypatch.setattr(module, "acs_local_aca_take_up_targets", lambda *_a, **_k: {}) + monkeypatch.setattr( + module, + "_with_local_aca_take_up", + lambda frame, *, seed, **_k: (frame, {"seed": seed, "assigned_sha256": "stub"}), + ) + monkeypatch.setattr(module, "_write_aca_take_up", lambda *_a: "stub") monkeypatch.setattr( module.cd_surface, "sample_staging_frame", @@ -1168,6 +1179,13 @@ def _export_county_fixture(module, monkeypatch, run, out_h5, weights): monkeypatch.setattr( module, "_with_recorded_ssi_medicaid_take_up", lambda frame, *a: frame ) + # microcosm#1720: likewise the recorded ACA take-up. + monkeypatch.setattr( + module, + "_recorded_aca_take_up", + lambda *a, **k: ({"assigned_sha256": "", "assignment_file": ""}, None), + ) + monkeypatch.setattr(module, "_with_recorded_aca_take_up", lambda frame, *a: frame) monkeypatch.setattr( module, "_with_live_stored_inputs", diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_coverage_anchors.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_coverage_anchors.py new file mode 100644 index 0000000000..c787b48d2b --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_coverage_anchors.py @@ -0,0 +1,855 @@ +"""ACS local lane: employer and direct-purchase coverage (microcosm#1720, A6).""" + +from __future__ import annotations + +import json +from types import SimpleNamespace +from typing import Any, cast + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build.us_runtime import acs_multispine +from microcosm.build.us_runtime.acs_local_coverage_anchors import ( + ACS_DIRECT_PURCHASE_CHOICE_SOURCE, + ACS_DIRECT_PURCHASE_TYPES, + ACS_LOCAL_COVERAGE_ANCHOR_COLUMNS, + ACS_LOCAL_COVERAGE_ANCHORS_ISSUE, + ACS_LOCAL_COVERAGE_ANCHORS_METHOD, + acs_local_aca_reported_true_anchor, + acs_local_direct_purchase_donor_shares, + choose_acs_direct_purchase_types, + with_acs_local_coverage_anchors, +) +from microcosm.build.us_runtime.acs_pums import ACS_2024_1YR_SPINE, AcsPumsSource +from microcosm.build.us_runtime.acs_transfer import ( + ASEC_PUF_DONOR_SPINE, + required_acs_transfer_inputs, +) +from microcosm.build.us_runtime.base_pool import spine_column +from microcosm.build.us_runtime.support_provenance import ( + support_channel_column, + support_clone_index_column, + support_source_id_column, +) +from microcosm.frame import ( + US_SCHEMA, + Frame, + WeightKind, + Weights, + put_frame_table, + read_frame_table, +) + +_ESI, _MARKETPLACE, _OTHER = ACS_LOCAL_COVERAGE_ANCHOR_COLUMNS +_ANCHOR = acs_local_aca_reported_true_anchor() +TAG = spine_column("person") + + +def _support_donor( + *, + under_65: tuple[bool, bool] = (True, False), + over_65: tuple[bool, bool] = (False, True), + n_asec: int = 40, +) -> Frame: + """An ASEC-by-PUF donor whose ASEC direct purchasers have one type per + age band; the PUF clones carry the opposite type, which must not count.""" + + rng = np.random.default_rng(720) + n = 2 * n_asec + ids = np.arange(1, n + 1) + roles = np.asarray(["asec"] * n_asec + ["puf_tax_detail"] * n_asec, dtype=object) + age = np.tile(np.where(np.arange(n_asec) % 2 == 0, 40.0, 70.0), 2) + purchaser = np.tile(np.arange(n_asec) % 4 < 2, 2) + young = age < 65 + asec = roles == "asec" + marketplace = np.where(young, under_65[0], over_65[0]) + other = np.where(young, under_65[1], over_65[1]) + marketplace = np.where(asec, marketplace, ~marketplace) & purchaser + other = np.where(asec, other, ~other) & purchaser + person = pd.DataFrame( + { + "person_id": ids, + "age": age, + "is_female": np.tile(rng.integers(0, 2, n_asec).astype(bool), 2), + "employment_income_before_lsr": np.tile( + rng.integers(0, 80_000, n_asec).astype(float), 2 + ), + _ESI: np.tile(rng.random(n_asec) < 0.5, 2), + _MARKETPLACE: marketplace, + _OTHER: other, + } + ) + for entity in US_SCHEMA.entities: + if entity != "person": + person[f"person_{entity}_id"] = ids + tables = {"person": person} + for entity in US_SCHEMA.entities: + if entity != "person": + tables[entity] = pd.DataFrame({f"{entity}_id": ids}) + tables["household"]["state_fips"] = np.resize([6, 36, 48], n) + for entity, table in tables.items(): + table[support_channel_column(entity)] = roles + table[support_source_id_column(entity)] = np.tile(np.arange(1, n_asec + 1), 2) + table[support_clone_index_column(entity)] = (roles == "puf_tax_detail").astype( + int + ) + return Frame( + tables, + US_SCHEMA, + {"household": Weights(np.full(n, 100.0), WeightKind.DESIGN)}, + pd.Series(ASEC_PUF_DONOR_SPINE, index=person.index, dtype=object), + ) + + +#: Eight ACS persons after the transfer, one per household (SERIALNO H1-H8): +#: (age, HINS1, HINS2, drawn ESI, drawn Marketplace, drawn other direct) +_ROWS = [ + (40, 1, 2, False, True, False), # ESI from HINS1; Marketplace off (HINS2 2) + (40, 2, 2, True, False, True), # ESI off; other direct off + (40, 1, 1, True, True, False), # HINS2 1 with a drawn type: kept + (40, 2, 1, False, False, False), # HINS2 1, nothing drawn: under-65 type + (70, 2, 1, False, False, False), # HINS2 1, nothing drawn: 65+ type + (70, 1, 1, False, False, True), # HINS2 1 with a drawn type: kept + (10, np.nan, 2, True, False, False), # HINS1 blank: the draw stands + (30, 2, np.nan, False, True, True), # HINS2 blank: the draws stand +] + + +def _acs_frame(rows=_ROWS, **person_overrides: Any) -> Frame: + ids = np.arange(1, len(rows) + 1) + person = pd.DataFrame( + { + "person_id": ids, + **{ + f"person_{entity}_id": ids + for entity in US_SCHEMA.entities + if entity != "person" + }, + "SPORDER": 1, + "age": [row[0] for row in rows], + "HINS1": [row[1] for row in rows], + "HINS2": [row[2] for row in rows], + _ESI: [row[3] for row in rows], + _MARKETPLACE: [row[4] for row in rows], + _OTHER: [row[5] for row in rows], + # HIMRKS 0 (categorically ineligible for a subsidy): no rule reads + # it, so the earlier rule decides every row. + "ACS_HIMRKS": 0, + **person_overrides, + } + ) + tables = { + "person": person, + **{ + entity: pd.DataFrame({f"{entity}_id": ids}) + for entity in US_SCHEMA.entities + if entity != "person" + }, + } + tables["household"]["SERIALNO"] = [f"2024HU{i:07d}" for i in ids] + return Frame( + tables, + US_SCHEMA, + {"household": Weights(np.full(len(ids), 10.0), WeightKind.DESIGN)}, + pd.Series(ACS_2024_1YR_SPINE, index=person.index, dtype=object), + ) + + +def test_the_three_columns_are_shared_transfer_targets() -> None: + """The step overrides the shared draws; it does not change the plan.""" + + assert set(ACS_LOCAL_COVERAGE_ANCHOR_COLUMNS) <= required_acs_transfer_inputs() + + +def test_the_aca_anchor_is_the_manifest_stages_own_column() -> None: + """The column the national tool reads as False when absent; not a + transfer target, so writing it moves no draw.""" + + assert _ANCHOR == "reported_has_subsidized_marketplace_health_coverage_at_interview" + assert _ANCHOR not in required_acs_transfer_inputs() + + +def test_the_donor_shares_come_from_the_asec_role_by_age_band() -> None: + shares = acs_local_direct_purchase_donor_shares(_support_donor()) + assert shares["channel"] == "asec" + assert shares["bands"]["under_65"]["shares"] == { + "marketplace_only": 1.0, + "non_marketplace_only": 0.0, + "both": 0.0, + } + assert shares["bands"]["65_plus"]["shares"] == { + "marketplace_only": 0.0, + "non_marketplace_only": 1.0, + "both": 0.0, + } + assert shares["all_ages"] == pytest.approx( + {"marketplace_only": 0.5, "non_marketplace_only": 0.5, "both": 0.0} + ) + for band in shares["bands"].values(): + assert band["fallback_to_all_ages"] is False + + +def test_the_acs_items_replace_the_draws() -> None: + frame = _acs_frame() + result, receipt = with_acs_local_coverage_anchors(frame, _support_donor(), seed=7) + person = result.table("person") + + assert person[_ESI].tolist() == [True, False, True, False, False, True, True, False] + assert person[_MARKETPLACE].tolist() == [ + False, + False, + True, + True, + False, + False, + False, + True, + ] + assert person[_OTHER].tolist() == [ + False, + False, + False, + False, + True, + True, + False, + True, + ] + # HIMRKS is 0 on every row: no ACA anchor. + assert person[_ANCHOR].tolist() == [False] * 8 + for column in (*ACS_LOCAL_COVERAGE_ANCHOR_COLUMNS, _ANCHOR): + assert person[column].dtype == bool, column + # Every other column, and the input frame, are untouched. + other_columns = [ + c for c in person if c not in (*ACS_LOCAL_COVERAGE_ANCHOR_COLUMNS, _ANCHOR) + ] + pd.testing.assert_frame_equal( + person[other_columns], frame.table("person")[other_columns] + ) + assert frame.table("person")[_ESI].tolist()[1] is True + + assert receipt["issue"] == ACS_LOCAL_COVERAGE_ANCHORS_ISSUE == "microcosm#1720" + assert receipt["method"] == ACS_LOCAL_COVERAGE_ANCHORS_METHOD + assert receipt["acs_persons"] == 8 + assert receipt["hins1_rows"] == {"1": 3, "2": 4, "blank": 1} + assert receipt["hins2_rows"] == {"1": 4, "2": 3, "blank": 1} + esi = receipt[_ESI] + # Rows with a HINS1 code: 3 yes (one drawn too), 4 no (one drawn yes). + assert esi["agreement_with_draw"] == { + "both_true_rows": 1, + "native_only_rows": 2, + "drawn_only_rows": 1, + "both_false_rows": 3, + } + assert esi["changed_rows"] == 3 + assert esi["native_weighted_share"] == pytest.approx(4 / 8) + assert esi["drawn_weighted_share"] == pytest.approx(3 / 8) + direct = receipt["direct_purchase"] + assert direct["hins2_no_rows"] == 3 + assert direct["set_false_from_draw"] == {_MARKETPLACE: 1, _OTHER: 1} + assert direct["hins2_yes_rows"] == 4 + choice = direct["choice"] + assert choice["source"] == ACS_DIRECT_PURCHASE_CHOICE_SOURCE + assert choice["rows"] == 4 + assert choice["draw_kept_rows"] == 2 + assert choice["type_drawn_rows"] == 2 + assert choice["type_drawn_by_type"] == { + "marketplace_only": 1, + "non_marketplace_only": 1, + "both": 0, + } + assert choice["unresolved_rows"] == 0 + assert choice["draw_key"] == "acs_2024_1yr:SERIALNO:SPORDER" + assert choice["seed"] == 7 + assert choice["himrks"]["codes"] == {"0": 4, "blank": 0} + assert choice["set_marketplace_by_code_1_rows"] == 0 + assert direct["himrks_conflicts"] == { + "hins2_no_himrks_direct_rows": {"1": 0, "2": 0}, + "hins2_no_himrks_direct_weighted_share": 0.0, + "hins2_blank_himrks_direct_rows": 0, + } + assert set(receipt["not_used"]) == {"HIMRKS code 0", "HIMRKS code 2"} + anchor = receipt["aca_anchor"] + assert anchor["column"] == _ANCHOR + assert anchor["manifest_stage"] == "aca_marketplace_inputs" + assert (anchor["true_rows"], anchor["weighted_share"]) == (0, 0.0) + assert anchor["allocation_flag_loaded"] is False + assert anchor["allocated_true_rows"] is None + assert anchor["allocated_weighted_share_of_true"] is None + assert anchor["conflicts"] == { + "himrks_1_hins2_no_rows": 0, + "himrks_1_hins2_no_weighted_share": 0.0, + "himrks_1_hins2_blank_rows": 0, + } + assert anchor["replaced_existing_column"] is False + json.dumps(receipt, allow_nan=False) + + +def test_the_choice_is_one_function_over_the_direct_purchasers() -> None: + """The Marketplace-versus-other choice, alone. Without a HIMRKS code 1, + draws with a type stand; rows with none take the donor's type for their + age band; a band without shares stays unresolved.""" + + rows = pd.DataFrame( + { + "person_household_id": [1, 2, 3, 4, 5], + "SPORDER": [1, 1, 1, 1, 2], + "age": [40.0, 70.0, 30.0, 80.0, 50.0], + # Codes 0 and 2 and a blank: the earlier rule decides every row. + "ACS_HIMRKS": [0, 2, 0, np.nan, 0], + } + ) + household = pd.DataFrame( + {"household_id": [1, 2, 3, 4, 5], "SERIALNO": ["A", "B", "C", "D", "E"]} + ) + shares = { + "bands": { + "under_65": { + "shares": { + "marketplace_only": 0.0, + "non_marketplace_only": 0.0, + "both": 1.0, + } + }, + "65_plus": {"shares": None}, + } + } + marketplace, other, receipt = choose_acs_direct_purchase_types( + rows, + household, + drawn_marketplace=np.asarray([True, False, False, False, False]), + drawn_other=np.asarray([False, True, False, False, False]), + donor_shares=shares, + seed=11, + weights=np.ones(5), + ) + assert marketplace.tolist() == [True, False, True, False, True] + assert other.tolist() == [False, True, True, False, True] + assert receipt == { + "source": ACS_DIRECT_PURCHASE_CHOICE_SOURCE, + "rows": 5, + "himrks": { + "codes": {"0": 3, "2": 1, "blank": 1}, + "weighted_shares": {"0": 0.6, "1": 0.0, "2": 0.2, "blank": 0.2}, + "allocation_flag_loaded": False, + "allocated_rows": None, + "allocated_code_1_rows": None, + "code_1": { + "rows": 0, + "drawn_marketplace_true_rows": 0, + "drawn_marketplace_false_rows": 0, + "drawn_marketplace_weighted_share": 0.0, + "drawn_non_marketplace_kept_rows": 0, + "drawn_non_marketplace_only_became_both_rows": 0, + }, + }, + "set_marketplace_by_code_1_rows": 0, + "draw_kept_rows": 2, + "type_drawn_rows": 2, + "type_drawn_by_type": { + "marketplace_only": 0, + "non_marketplace_only": 0, + "both": 2, + }, + "unresolved_rows": 1, + "donor_shares": shares, + "draw_key": "acs_2024_1yr:SERIALNO:SPORDER", + "draw_salt": "acs_local_direct_purchase_type", + "seed": 11, + } + # No row needs a draw: no key is built, so no household is needed. + kept_marketplace, kept_other, kept = choose_acs_direct_purchase_types( + rows.iloc[:2], + household.iloc[:0], + drawn_marketplace=np.asarray([True, False]), + drawn_other=np.asarray([False, True]), + donor_shares=shares, + seed=11, + weights=np.ones(2), + ) + assert (kept_marketplace.tolist(), kept_other.tolist()) == ( + [True, False], + [False, True], + ) + assert kept["type_drawn_rows"] == 0 + + +def test_himrks_code_1_sets_the_marketplace_flag_and_keeps_the_other_draw() -> None: + """As ruled on 25 Nov 2026: HIMRKS 1 (direct purchase with a premium + subsidy) sets the Marketplace flag; the drawn non-Marketplace flag stands. + Codes 0 and 2 and a blank keep the earlier rule.""" + + rows = pd.DataFrame( + { + "person_household_id": [1, 2, 3, 4, 5, 6], + "SPORDER": 1, + "age": [40.0, 40.0, 40.0, 40.0, 40.0, 70.0], + "ACS_HIMRKS": [1, 1, 1, 2, 0, np.nan], + "ACS_FHIMRKSP": [1, 0, 0, 0, 0, 0], + } + ) + household = pd.DataFrame( + {"household_id": [1, 2, 3, 4, 5, 6], "SERIALNO": list("ABCDEF")} + ) + shares = { + "bands": { + "under_65": { + "shares": { + "marketplace_only": 0.0, + "non_marketplace_only": 0.0, + "both": 1.0, + } + }, + "65_plus": {"shares": None}, + } + } + marketplace, other, receipt = choose_acs_direct_purchase_types( + rows, + household, + # Code 1 rows: nothing drawn; a non-Marketplace draw; a Marketplace draw. + drawn_marketplace=np.asarray([False, False, True, False, False, False]), + drawn_other=np.asarray([False, True, False, False, True, False]), + donor_shares=shares, + seed=11, + weights=np.arange(1.0, 7.0), + ) + assert marketplace.tolist() == [True, True, True, True, False, False] + assert other.tolist() == [False, True, False, True, True, False] + himrks = receipt["himrks"] + assert himrks["codes"] == {"0": 1, "1": 3, "2": 1, "blank": 1} + assert himrks["weighted_shares"] == pytest.approx( + {"0": 5 / 21, "1": 6 / 21, "2": 4 / 21, "blank": 6 / 21} + ) + assert himrks["allocation_flag_loaded"] is True + assert (himrks["allocated_rows"], himrks["allocated_code_1_rows"]) == (1, 1) + assert himrks["code_1"] == { + "rows": 3, + "drawn_marketplace_true_rows": 1, + "drawn_marketplace_false_rows": 2, + "drawn_marketplace_weighted_share": pytest.approx(3 / 6), + "drawn_non_marketplace_kept_rows": 1, + "drawn_non_marketplace_only_became_both_rows": 1, + } + assert receipt["set_marketplace_by_code_1_rows"] == 2 + # Code 0 with a drawn type: kept. Code 2 with nothing drawn: the donor's + # under-65 type. The blank 70-year-old: no 65+ shares, so unresolved. + assert receipt["draw_kept_rows"] == 1 + assert receipt["type_drawn_rows"] == 1 + assert receipt["type_drawn_by_type"]["both"] == 1 + assert receipt["unresolved_rows"] == 1 + json.dumps(receipt, allow_nan=False) + + with pytest.raises(ValueError, match=r"FHIMRKSP requires blank"): + choose_acs_direct_purchase_types( + rows.assign(ACS_FHIMRKSP=[2, 0, 0, 0, 0, 0]), + household, + drawn_marketplace=np.zeros(6, dtype=bool), + drawn_other=np.zeros(6, dtype=bool), + donor_shares=shares, + seed=11, + weights=np.ones(6), + ) + + +def test_hins2_no_wins_over_a_himrks_direct_purchase_code_and_is_counted() -> None: + result, receipt = with_acs_local_coverage_anchors( + _acs_frame( + ACS_HIMRKS=[1, 2, 1, 1, 1, 0, 0, 1], + ACS_FHIMRKSP=[1, 0, 1, 0, 0, 0, 0, 0], + ), + _support_donor(), + seed=7, + ) + person = result.table("person") + # Rows 1 and 2 have HINS2 2: both flags False, whatever HIMRKS says. + assert not person[_MARKETPLACE].iloc[:2].any() + assert not person[_OTHER].iloc[:2].any() + # Rows 4 and 5 have HINS2 1, nothing drawn and code 1: Marketplace only + # (row 5 is 70, where the donor's type would be non-Marketplace). + assert person[_MARKETPLACE].iloc[3:5].tolist() == [True, True] + assert person[_OTHER].iloc[3:5].tolist() == [False, False] + # Row 6 has HINS2 1, a drawn non-Marketplace type and code 0: kept. + assert (person[_MARKETPLACE].iloc[5], person[_OTHER].iloc[5]) == (False, True) + conflicts = receipt["direct_purchase"]["himrks_conflicts"] + assert conflicts["hins2_no_himrks_direct_rows"] == {"1": 1, "2": 1} + assert conflicts["hins2_no_himrks_direct_weighted_share"] == pytest.approx(2 / 8) + # Row 8 has a blank HINS2 and code 1: its draws stand, and it is counted. + assert conflicts["hins2_blank_himrks_direct_rows"] == 1 + assert (person[_MARKETPLACE].iloc[7], person[_OTHER].iloc[7]) == (True, True) + choice = receipt["direct_purchase"]["choice"] + assert choice["himrks"]["codes"] == {"0": 1, "1": 3, "blank": 0} + assert choice["set_marketplace_by_code_1_rows"] == 2 + # The ACA anchor: HINS2 1 and HIMRKS 1 only (rows 3-5), allocated + # values included (row 3); the code 1 rows with HINS2 2 or blank are not. + assert person[_ANCHOR].tolist() == [ + False, + False, + True, + True, + True, + False, + False, + False, + ] + anchor = receipt["aca_anchor"] + assert anchor["true_rows"] == 3 + assert anchor["weighted_share"] == pytest.approx(3 / 8) + assert anchor["allocation_flag_loaded"] is True + assert anchor["allocated_true_rows"] == 1 + assert anchor["allocated_weighted_share_of_true"] == pytest.approx(1 / 3) + # The code 1 rows with HINS2 2 (row 1) or blank (row 8): no anchor. + assert anchor["conflicts"] == { + "himrks_1_hins2_no_rows": 1, + "himrks_1_hins2_no_weighted_share": pytest.approx(1 / 8), + "himrks_1_hins2_blank_rows": 1, + } + + +def _mixed_rows(n: int = 40) -> list[tuple]: + """HINS2 yes and nothing drawn, all under 65.""" + + return [(30 + i % 20, 2, 1, False, False, False) for i in range(n)] + + +def test_the_type_draw_is_keyed_on_the_record_not_the_row_order() -> None: + donor = _support_donor(under_65=(True, True), over_65=(True, False)) + # Make the under-65 types mixed: half Marketplace only, half both. + tables = {entity: donor.table(entity).copy() for entity in donor.entities} + person = tables["person"] + young_buyers = person.index[ + (person["age"] < 65) & (person[_MARKETPLACE] | person[_OTHER]) + ] + person.loc[young_buyers[::2], _OTHER] = False + mixed = Frame( + tables, US_SCHEMA, {"household": donor.weights_for("household")}, donor.strata + ) + frame = _acs_frame(_mixed_rows()) + first, receipt = with_acs_local_coverage_anchors(frame, mixed, seed=3) + again, _ = with_acs_local_coverage_anchors(frame, mixed, seed=3) + types = receipt["direct_purchase"]["choice"]["type_drawn_by_type"] + assert types["marketplace_only"] > 0 and types["both"] > 0 + assert types["non_marketplace_only"] == 0 + pd.testing.assert_frame_equal(first.table("person"), again.table("person")) + + # Half the records removed: each remaining person keeps their type, since + # the draw depends only on the seed and their SERIALNO and SPORDER. + kept = frame.table("household")["household_id"] % 2 == 1 + kept_ids = set(frame.table("household").loc[kept, "household_id"]) + subset_tables = { + entity: frame.table(entity) + .loc[lambda table, entity=entity: table[f"{entity}_id"].isin(kept_ids)] + .reset_index(drop=True) + for entity in frame.entities + } + subset = Frame( + subset_tables, + US_SCHEMA, + { + "household": Weights( + frame.weights_for("household").values[kept.to_numpy()], + WeightKind.DESIGN, + ) + }, + ) + fewer, _ = with_acs_local_coverage_anchors(subset, mixed, seed=3) + by_id = fewer.table("person").set_index("person_id") + original = first.table("person").set_index("person_id").loc[by_id.index] + for column in (_MARKETPLACE, _OTHER): + pd.testing.assert_series_equal(by_id[column], original[column]) + + +def test_a_band_without_donor_purchasers_falls_back_to_all_ages() -> None: + donor = _support_donor(over_65=(False, False)) + shares = acs_local_direct_purchase_donor_shares(donor) + assert shares["bands"]["65_plus"]["fallback_to_all_ages"] is True + assert shares["bands"]["65_plus"]["shares"] == shares["all_ages"] + result, receipt = with_acs_local_coverage_anchors(_acs_frame(), donor, seed=7) + # The 65+ row with nothing drawn takes the all-ages type (Marketplace only). + assert result.table("person")[_MARKETPLACE].iloc[4] == True # noqa: E712 + assert receipt["direct_purchase"]["choice"]["unresolved_rows"] == 0 + + +@pytest.mark.parametrize( + ("overrides", "match"), + [ + ({"HINS1": [1, 2, 1, 2, 2, 1, 3, 2]}, r"HINS1 requires blank"), + ({"HINS2": [2, 2, 1, 1, 1, 1, 2, 0]}, r"HINS2 requires blank"), + ( + {_ESI: [True, None, True, False, False, True, True, False]}, + "complete boolean", + ), + ({"ACS_HIMRKS": [0, 0, 0, 0, 0, 0, 0, 3]}, r"HIMRKS requires blank"), + ], +) +def test_malformed_inputs_are_refused(overrides, match) -> None: + with pytest.raises(ValueError, match=match): + with_acs_local_coverage_anchors( + _acs_frame(**overrides), _support_donor(), seed=7 + ) + + +@pytest.mark.parametrize( + "column", ["HINS1", "HINS2", "ACS_HIMRKS", _MARKETPLACE, "age"] +) +def test_a_missing_column_is_refused(column) -> None: + frame = _acs_frame() + tables = {entity: frame.table(entity) for entity in frame.entities} + tables["person"] = tables["person"].drop(columns=[column]) + with pytest.raises(ValueError, match=column): + with_acs_local_coverage_anchors( + Frame( + tables, + US_SCHEMA, + {"household": frame.weights_for("household")}, + frame.strata, + ), + _support_donor(), + seed=7, + ) + + +def test_a_donor_without_the_asec_role_is_refused() -> None: + donor = _support_donor() + plain = { + entity: donor.table(entity).drop( + columns=[ + support_channel_column(entity), + support_source_id_column(entity), + support_clone_index_column(entity), + ] + ) + for entity in donor.entities + } + with pytest.raises(ValueError, match="ASEC observation role"): + with_acs_local_coverage_anchors( + _acs_frame(), + Frame( + plain, + US_SCHEMA, + {"household": donor.weights_for("household")}, + donor.strata, + ), + seed=7, + ) + + +# --------------------------------------------------------------------------- +# The multispine seam +# --------------------------------------------------------------------------- + + +def test_the_seam_runs_the_step_after_the_transfers_and_before_the_premiums( + monkeypatch, tmp_path +) -> None: + events: list[tuple[Any, ...]] = [] + transferred = SimpleNamespace(table=lambda entity: pd.DataFrame()) + anchored = object() + attributed = object() + base = SimpleNamespace(table=lambda entity: pd.DataFrame()) + + monkeypatch.setattr( + acs_multispine, + "build_acs_pums_unit_frame", + lambda source, *, chunksize: (object(), {"spine": ACS_2024_1YR_SPINE}), + ) + monkeypatch.setattr( + acs_multispine, + "map_acs_native_inputs", + lambda frame: SimpleNamespace(frame=object(), native_inputs={}), + ) + monkeypatch.setattr( + acs_multispine, + "transfer_acs_inputs", + lambda recipient, donor, **kwargs: ( + events.append(("transfer",)) + or SimpleNamespace( + frame=transferred, + imputed_inputs=(), + fit_records=(), + deferred_inputs=(), + resolved_donor_channel="puf_support", + ) + ), + ) + + def fake_anchor(frame, donor, *, seed): + events.append(("coverage", frame, donor, seed)) + return anchored, {"issue": "microcosm#1720", "rows": np.int64(1)} + + def fake_attribute(frame): + events.append(("se_health", frame)) + return attributed, {"issue": "microcosm#1720"} + + monkeypatch.setattr(acs_multispine, "with_acs_local_coverage_anchors", fake_anchor) + monkeypatch.setattr( + acs_multispine, "with_acs_local_se_health_premiums", fake_attribute + ) + monkeypatch.setattr( + acs_multispine, + "with_optional_acs_spine", + lambda actual_base, actual_acs, **kwargs: ( + events.append(("pool", actual_acs)) or object() + ), + ) + source = AcsPumsSource(tmp_path / "csv_hus.zip", tmp_path / "csv_pus.zip") + result = acs_multispine.build_optional_acs_multispine( + cast(Frame, base), + source, + coverage_anchors=True, + se_health_premiums=True, + seed=9, + ) + # The premium attribution reads the frame the coverage step returned. + assert events == [ + ("transfer",), + ("coverage", transferred, base, 9), + ("se_health", anchored), + ("pool", attributed), + ] + assert result.provenance["acs_local_coverage_anchors"] == { + "issue": "microcosm#1720", + "rows": 1, + } + + events.clear() + result = acs_multispine.build_optional_acs_multispine(cast(Frame, base), source) + assert events == [("transfer",), ("pool", transferred)] + assert "acs_local_coverage_anchors" not in result.provenance + + +def _raw_acs(n: int = 20) -> Frame: + """A raw ACS spine of one-person households with HINS1, HINS2 and + HIMRKS (as the loader renames it).""" + + rng = np.random.default_rng(2024) + households = np.arange(600, 600 + n) + person = pd.DataFrame( + { + "person_id": households, + "person_household_id": households, + "person_tax_unit_id": households, + "person_spm_unit_id": households, + "person_family_id": households, + "person_marital_unit_id": households, + "SPORDER": 1, + "AGEP": np.where(np.arange(n) % 3 == 0, 70, 35), + "SEX": rng.integers(1, 3, n), + "RELSHIPP": 20, + "ADJINC": 1_000_000, + "WAGP": rng.integers(0, 90_000, n).astype(float), + "SEMP": 0.0, + "SSP": 0.0, + "SSIP": 0.0, + "RETP": 0.0, + "INTP": 0.0, + "HINS1": np.resize([1, 2, 2], n), + "HINS2": np.resize([2, 1, 2, 1], n), + "ACS_HIMRKS": np.resize([0, 1, 2, 1, 0], n), + "ACS_FHIMRKSP": 0, + } + ) + return Frame( + { + "person": person, + "household": pd.DataFrame( + { + "household_id": households, + "SERIALNO": [f"2024HU{i:07d}" for i in households], + "state_fips": np.resize([6, 36, 48], n), + "puma": "0600100", + "ADJHSG": 1_000_000, + "TEN": 3, + "RNTP": 1_000.0, + "GRNTP": 1_200.0, + "TAXAMT": np.nan, + } + ), + "tax_unit": pd.DataFrame({"tax_unit_id": households}), + "spm_unit": pd.DataFrame({"spm_unit_id": households}), + "family": pd.DataFrame({"family_id": households}), + "marital_unit": pd.DataFrame({"marital_unit_id": households}), + }, + US_SCHEMA, + {"household": Weights(np.full(n, 50.0), WeightKind.DESIGN)}, + pd.Series(ACS_2024_1YR_SPINE, index=person.index, dtype=object), + ) + + +def _real_seam(monkeypatch, tmp_path, *, coverage_anchors: bool): + monkeypatch.setattr( + acs_multispine, "build_acs_pums_unit_frame", lambda *_a, **_k: (_raw_acs(), {}) + ) + return acs_multispine.build_optional_acs_multispine( + _support_donor(), + AcsPumsSource(tmp_path / "csv_hus.zip", tmp_path / "csv_pus.zip"), + target_families={ + "person": {"coverage": tuple(ACS_LOCAL_COVERAGE_ANCHOR_COLUMNS)} + }, + coverage_anchors=coverage_anchors, + seed=5, + n_estimators=5, + ) + + +def test_a_real_transfer_keeps_every_other_draw_and_takes_the_acs_items( + monkeypatch, tmp_path +) -> None: + """The shared transfer's draws (and every other column) are identical + with and without the step; only the three columns follow HINS1/HINS2.""" + + with_step = _real_seam(monkeypatch, tmp_path, coverage_anchors=True) + without_step = _real_seam(monkeypatch, tmp_path, coverage_anchors=False) + + columns = list(ACS_LOCAL_COVERAGE_ANCHOR_COLUMNS) + assert _ANCHOR not in without_step.frame.table("person") + pd.testing.assert_frame_equal( + with_step.frame.table("person").drop(columns=[*columns, _ANCHOR]), + without_step.frame.table("person").drop(columns=columns), + check_like=True, + ) + assert ( + with_step.provenance["imputed_inputs"] + == without_step.provenance["imputed_inputs"] + ) + assert with_step.fit_records == without_step.fit_records + + person = with_step.frame.table("person") + acs = person.loc[person[TAG].eq(ACS_2024_1YR_SPINE)].reset_index(drop=True) + donor = person.loc[person[TAG].eq(ASEC_PUF_DONOR_SPINE)].reset_index(drop=True) + before = without_step.frame.table("person") + donor_before = before.loc[before[TAG].eq(ASEC_PUF_DONOR_SPINE)].reset_index( + drop=True + ) + assert acs[_ESI].tolist() == (acs["HINS1"] == 1).tolist() + no_direct = acs["HINS2"].eq(2) + assert not acs.loc[no_direct, _MARKETPLACE].any() + assert not acs.loc[no_direct, _OTHER].any() + assert (acs.loc[~no_direct, _MARKETPLACE] | acs.loc[~no_direct, _OTHER]).all() + subsidized = ~no_direct & acs["ACS_HIMRKS"].eq(1) + assert subsidized.any() and acs.loc[subsidized, _MARKETPLACE].all() + # The raw item stays on the staged ACS rows, for a later stage. + assert acs["ACS_HIMRKS"].notna().all() + # The ACA anchor is written on ACS rows only; donor rows lack it. + assert acs[_ANCHOR].tolist() == (~no_direct & acs["ACS_HIMRKS"].eq(1)).tolist() + assert donor[_ANCHOR].isna().all() + # Through the staging H5 boundary (R1 writes, R2 reads whole tables), ACS + # rows keep their values and donor rows stay missing, never False. + path = tmp_path / "staging.h5" + with pd.HDFStore(path, mode="w") as store: + put_frame_table(store, "person", person, preferred_format="fixed") + with pd.HDFStore(path, mode="r") as store: + loaded = read_frame_table(store, "person") + loaded_acs = loaded[TAG].eq(ACS_2024_1YR_SPINE) + assert loaded.loc[loaded_acs, _ANCHOR].tolist() == acs[_ANCHOR].tolist() + assert loaded.loc[~loaded_acs, _ANCHOR].isna().all() + # Donor rows keep the donor release's values. + for column in columns: + assert donor[column].tolist() == donor_before[column].tolist(), column + receipt = with_step.provenance["acs_local_coverage_anchors"] + assert receipt["acs_persons"] == 20 + assert set(ACS_DIRECT_PURCHASE_TYPES) == set( + receipt["direct_purchase"]["choice"]["type_drawn_by_type"] + ) + json.dumps(with_step.provenance, allow_nan=False) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_gate_shadow.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_gate_shadow.py index 7c9896b135..4a9dc564c2 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_gate_shadow.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_gate_shadow.py @@ -42,6 +42,7 @@ def _tool_shadows_on(monkeypatch) -> None: "us_local_hours_materialize", "us_local_self_employment_identity_materialize", "us_local_ssi_medicaid_take_up_materialize", + "us_local_aca_take_up_materialize", ), "calibrate": ( "us_local_hours_calibrate", diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_group_quarters_housing.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_group_quarters_housing.py new file mode 100644 index 0000000000..71d5dbda27 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_group_quarters_housing.py @@ -0,0 +1,192 @@ +"""ACS local lane: housing take-up of group-quarters units (microcosm#975).""" + +from __future__ import annotations + +import json +from types import SimpleNamespace +from typing import Any, cast + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build.us_runtime import acs_multispine +from microcosm.build.us_runtime.acs_local_group_quarters_housing import ( + ACS_GROUP_QUARTERS_KINDS, + ACS_LOCAL_GROUP_QUARTERS_HOUSING_COLUMN, + ACS_LOCAL_GROUP_QUARTERS_HOUSING_ISSUE, + ACS_LOCAL_GROUP_QUARTERS_HOUSING_METHOD, + with_acs_local_group_quarters_housing, +) +from microcosm.build.us_runtime.acs_pums import ACS_2024_1YR_SPINE, AcsPumsSource +from microcosm.build.us_runtime.acs_transfer import required_acs_transfer_inputs +from microcosm.frame import US_SCHEMA, Frame, WeightKind, Weights + +_COLUMN = ACS_LOCAL_GROUP_QUARTERS_HOUSING_COLUMN + + +def _acs_frame(kinds: list[float], take_up: list[object], **household: Any) -> Frame: + """One person, SPM unit and household per entry, in that order.""" + + ids = np.arange(1, len(kinds) + 1) + person = pd.DataFrame( + { + "person_id": ids, + **{ + f"person_{entity}_id": ids + for entity in US_SCHEMA.entities + if entity != "person" + }, + } + ) + tables = { + "person": person, + **{ + entity: pd.DataFrame({f"{entity}_id": ids}) + for entity in US_SCHEMA.entities + if entity != "person" + }, + } + tables["household"]["TYPEHUGQ"] = kinds + for column, values in household.items(): + tables["household"][column] = values + tables["spm_unit"][_COLUMN] = pd.Series(take_up, dtype=object) + return Frame( + tables, + US_SCHEMA, + {"household": Weights(np.full(len(ids), 10.0), WeightKind.DESIGN)}, + pd.Series(ACS_2024_1YR_SPINE, index=person.index, dtype=object), + ) + + +def test_the_flag_is_still_a_shared_transfer_target() -> None: + """The step overrides the shared draw; it does not change the plan.""" + + assert _COLUMN in required_acs_transfer_inputs() + assert ACS_GROUP_QUARTERS_KINDS == (2, 3) + + +def test_group_quarters_units_get_false_and_housing_units_keep_their_draw() -> None: + frame = _acs_frame( + kinds=[1, 1, 2, 2, 3, 3, 1], + take_up=[True, False, True, False, True, np.nan, True], + ) + result, receipt = with_acs_local_group_quarters_housing(frame) + assert result.table("spm_unit")[_COLUMN].tolist() == [ + True, + False, + False, + False, + False, + False, + True, + ] + assert result.table("spm_unit")[_COLUMN].dtype == bool + # The input frame is untouched. + assert frame.table("spm_unit")[_COLUMN].iloc[2] is True + + assert receipt["issue"] == ACS_LOCAL_GROUP_QUARTERS_HOUSING_ISSUE == "microcosm#975" + assert receipt["method"] == ACS_LOCAL_GROUP_QUARTERS_HOUSING_METHOD + assert receipt["column"] == _COLUMN + assert receipt["acs_spm_units"] == 7 + assert receipt["group_quarters_spm_units"] == 4 + assert receipt["by_typehugq"] == { + "2": {"spm_units": 2, "set_false_from_true": 1, "set_false_from_missing": 0}, + "3": {"spm_units": 2, "set_false_from_true": 1, "set_false_from_missing": 1}, + } + assert receipt["housing_unit_spm_units"] == 3 + assert receipt["housing_unit_take_up_true"] == 2 + assert receipt["unknown_typehugq_spm_units"] == 0 + json.dumps(receipt, allow_nan=False) + + +def test_an_unknown_kind_keeps_its_draw_and_is_counted() -> None: + frame = _acs_frame(kinds=[1, np.nan, 3], take_up=[True, True, True]) + result, receipt = with_acs_local_group_quarters_housing(frame) + assert result.table("spm_unit")[_COLUMN].tolist() == [True, True, False] + assert receipt["unknown_typehugq_spm_units"] == 1 + + +@pytest.mark.parametrize("missing", ["TYPEHUGQ", _COLUMN]) +def test_a_frame_without_the_columns_it_reads_is_refused(missing) -> None: + frame = _acs_frame(kinds=[1, 2], take_up=[True, True]) + tables = {entity: frame.table(entity).copy() for entity in frame.entities} + for entity in ("household", "spm_unit"): + if missing in tables[entity]: + tables[entity] = tables[entity].drop(columns=[missing]) + with pytest.raises(ValueError, match=missing): + with_acs_local_group_quarters_housing( + Frame( + tables, + US_SCHEMA, + {"household": frame.weights_for("household")}, + frame.strata, + ) + ) + + +def test_the_seam_runs_the_step_after_the_transfer_and_before_pooling( + monkeypatch, tmp_path +) -> None: + events: list[tuple[Any, ...]] = [] + transferred = SimpleNamespace(table=lambda entity: pd.DataFrame()) + stepped = object() + base = SimpleNamespace(table=lambda entity: pd.DataFrame()) + + monkeypatch.setattr( + acs_multispine, + "build_acs_pums_unit_frame", + lambda source, *, chunksize: (object(), {"spine": ACS_2024_1YR_SPINE}), + ) + monkeypatch.setattr( + acs_multispine, + "map_acs_native_inputs", + lambda frame: SimpleNamespace(frame=object(), native_inputs={}), + ) + monkeypatch.setattr( + acs_multispine, + "transfer_acs_inputs", + lambda recipient, donor, **kwargs: ( + events.append(("transfer",)) + or SimpleNamespace( + frame=transferred, + imputed_inputs=(), + fit_records=(), + deferred_inputs=(), + resolved_donor_channel="puf_support", + ) + ), + ) + + def fake_step(frame): + events.append(("group_quarters", frame)) + return stepped, {"issue": "microcosm#975", "units": np.int64(2)} + + monkeypatch.setattr( + acs_multispine, "with_acs_local_group_quarters_housing", fake_step + ) + monkeypatch.setattr( + acs_multispine, + "with_optional_acs_spine", + lambda actual_base, actual_acs, **kwargs: ( + events.append(("pool", actual_acs)) or object() + ), + ) + source = AcsPumsSource(tmp_path / "csv_hus.zip", tmp_path / "csv_pus.zip") + result = acs_multispine.build_optional_acs_multispine( + cast(Frame, base), source, group_quarters_housing=True + ) + assert events == [ + ("transfer",), + ("group_quarters", transferred), + ("pool", stepped), + ] + assert result.provenance["acs_local_group_quarters_housing"] == { + "issue": "microcosm#975", + "units": 2, + } + + events.clear() + result = acs_multispine.build_optional_acs_multispine(cast(Frame, base), source) + assert events == [("transfer",), ("pool", transferred)] + assert "acs_local_group_quarters_housing" not in result.provenance diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_no_county_regression.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_no_county_regression.py index a856627d2e..f3d37fd436 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_no_county_regression.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_no_county_regression.py @@ -304,13 +304,26 @@ def test_no_county_materialization_matches_pre_county_surface( # microcosm#1022: the ACS SSI/Medicaid take-up stage compiles SSA and CMS # counts from the ledger feed and runs an engine pre-pass this fixture # cannot support; this test checks county hooks only. - monkeypatch.setattr(module, "acs_local_ssi_medicaid_take_up_targets", lambda *_: {}) + monkeypatch.setattr( + module, "_compiled_fiscal_registry", lambda *_: (SimpleNamespace(specs=[]), []) + ) + monkeypatch.setattr( + module, "acs_local_ssi_medicaid_take_up_targets", lambda *_, **_k: {} + ) monkeypatch.setattr( module, "_with_local_ssi_medicaid_take_up", lambda frame, *, seed, **_k: (frame, {"seed": seed, "assigned_sha256": "stub"}), ) monkeypatch.setattr(module, "_write_ssi_medicaid_take_up", lambda *_: "stub") + # microcosm#1720: likewise the ACA take-up stage. + monkeypatch.setattr(module, "acs_local_aca_take_up_targets", lambda *_, **_k: {}) + monkeypatch.setattr( + module, + "_with_local_aca_take_up", + lambda frame, *, seed, **_k: (frame, {"seed": seed, "assigned_sha256": "stub"}), + ) + monkeypatch.setattr(module, "_write_aca_take_up", lambda *_: "stub") monkeypatch.setattr(module, "log", lambda *_: None) def materialize(_frame, specs, **_kwargs): diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_tool.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_tool.py index c689873af6..c8223f182f 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_tool.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_tool.py @@ -3,6 +3,7 @@ from __future__ import annotations import ast +import copy import functools import importlib.util import inspect @@ -585,6 +586,46 @@ def test_finalize_reviewed_limitations_carries_staging_and_dedupes() -> None: ): assert fragment in anchor["reason"], fragment assert "acs_snap_receipt_anchor" in (by_id["acs_take_up_engine_defaults"]["reason"]) + # microcosm#1720: the inputs staging writes on ACS rows are a reviewed + # method, recorded and not graded. + staged = by_id["acs_local_staged_inputs"] + assert staged["status"] == "reviewed_modeling_decision" + assert staged["calibration_blocker"] is False + assert set(module.ACS_LOCAL_STATUS_INPUTS_COLUMNS) <= set(staged["columns"]) + assert {"is_self_employed", "health_insurance_premiums"} <= set(staged["columns"]) + assert set(module.ACS_LOCAL_WEEKS_DEFERRALS_COLUMNS) <= set(staged["columns"]) + assert "would_file_taxes_voluntarily" in staged["columns"] + assert "takes_up_housing_assistance_if_eligible" in staged["columns"] + # The housing flag is an override of a draw, not a never-default column. + assert ("spm_unit", "takes_up_housing_assistance_if_eligible") not in ( + module.NEVER_DEFAULT_FILLED + ) + assert "acs_local_group_quarters_housing" in staged["treatment"] + # A6: the coverage flags are overrides of draws, not never-default columns. + assert set(module.ACS_LOCAL_COVERAGE_ANCHOR_COLUMNS) <= set(staged["columns"]) + for column in module.ACS_LOCAL_COVERAGE_ANCHOR_COLUMNS: + assert ("person", column) not in module.NEVER_DEFAULT_FILLED + for fragment in ("HINS1 == 1", "NOW_GRP", "HIMRKS"): + assert fragment in staged["reason"], fragment + assert "acs_local_coverage_anchors" in staged["treatment"] + for fragment in ( + "microcosm#1720", + "A_MARITL", + "surviving_spouse_eligible does not check", + "not as a head of household", + "MIL == 1", + "POCCU2 52", + "attribute_us_se_health_premiums", + "not ACS COW 6 or 7", + "microcosm#1689", + "LKWEEKS", + "RETCB_VAL", + "weeks 0 without UC", + "SIPP 2023", + "microcosm#975", + ): + assert fragment in staged["reason"], fragment + assert "NEVER_DEFAULT_FILLED" in staged["treatment"] # microcosm#1021: native ACS disability is a reviewed method; weeks worked # is staged only, and is_veteran is documented, not exported. work_disability = by_id["acs_work_disability_inputs"] @@ -667,7 +708,47 @@ def test_finalize_reviewed_limitations_carries_staging_and_dedupes() -> None: for fragment in ("PEDIS*", "SERIALNO:SPORDER", "acs_local_ssi_medicaid_take_up"): assert fragment in ssi["reason"] defaults = by_id["acs_take_up_engine_defaults"]["reason"] - assert "(ACA, Early Head Start and the rest)" in defaults + # microcosm#1720: ACA take-up left the engine defaults. + assert "(Early Head Start, CHIP and the rest)" in defaults + assert "(acs_local_aca_take_up, microcosm#1720)" in defaults + assert "ACA, Early Head Start" not in defaults + assert by_id["acs_take_up_engine_defaults"]["treatment"] == ( + "Tracked via microcosm#1720." + ) + aca = by_id["acs_local_aca_take_up"] + assert aca["status"] == "reviewed_modeling_decision" + assert aca["calibration_blocker"] is False + assert aca["columns"] == [ + "takes_up_aca_if_eligible", + "selected_marketplace_plan_benchmark_ratio", + ] + for fragment in ( + "aca_marketplace_inputs", + "floored at zero", + "closest to the residual average", + "microcosm#168", + "too few very large and very small credits", + "reported_has_subsidized_marketplace_health_coverage_at_interview", + "probability residual / anchored weight", + "acs_local_aca_subsidized_anchor_keep", + "microcosm.build.anchor_thinning", + "in expectation only", + "excess over each table is recorded", + "clipped to 0.5-1.5", + "no bronze count", + "HIMRKS", + "from ACS HINS1", + "acs_local_staged_inputs", + ): + assert fragment in aca["reason"], fragment + for fragment in ( + "report-only", + "us_local_aca_take_up_materialize", + "keep probability and thinned rows", + "share of ACS takers", + "digest", + ): + assert fragment in aca["treatment"], fragment assert "EITC take-up is the take-up contract's seeded draw" in defaults assert "WIC take-up the national generator's draw" in defaults assert "Medicare take-up is native ACS HINS3" in defaults @@ -738,7 +819,7 @@ def test_finalize_reviewed_limitations_carries_staging_and_dedupes() -> None: f"{len(register_entries)} entries", f"policyengine-us {_REVIEWED_ENGINE}", "spm_unit.spm_unit_energy_subsidy (liheap)", - "tax_unit.takes_up_aca_if_eligible (aca_ptc)", + "household.household_vehicles_owned (general_assistance)", ): assert fragment in register["reason"], fragment assert "acs_local_reviewed_fill_consumers" in register["treatment"] @@ -2644,6 +2725,104 @@ def test_reviewed_null_fill_refuses_to_default_fill_ssi_medicaid_take_up( assert person[column].isna().sum() == 2 +_ACA = ("takes_up_aca_if_eligible", "selected_marketplace_plan_benchmark_ratio") + + +def test_aca_inputs_are_never_default_filled() -> None: + """microcosm#1720: True is universal take-up, 1.0 the benchmark plan.""" + + module = _load_tool_module() + assert module.ACS_LOCAL_ACA_TAKE_UP_COLUMNS == _ACA + for column in _ACA: + reason = module._NEVER_DEFAULT_FILLED_REASONS[("tax_unit", column)] + assert ("tax_unit", column) in module.NEVER_DEFAULT_FILLED + assert "microcosm#1720" in reason + assert "ACA take-up stage first" in reason + + +@pytest.mark.parametrize("column", _ACA) +def test_reviewed_null_fill_refuses_to_default_fill_aca_inputs( + tmp_path, column +) -> None: + from microcosm.frame import Frame + + module = _load_tool_module() + frame = _plausible_hours_frame() + tax_unit = frame.table("tax_unit") + tax_unit = tax_unit.assign( + **{column: [1.0] * (len(tax_unit) - 2) + [np.nan, np.nan]} + ) + frame = Frame( + { + name: tax_unit if name == "tax_unit" else frame.table(name) + for name in frame.entities + }, + frame.schema, + {"household": frame.weights_for("household")}, + ) + summary = tmp_path / "staging.summary.json" + summary.write_text( + json.dumps( + { + "reviewed_engine_input_nulls": [ + {"entity": "tax_unit", "column": column, "missing_rows": 2} + ] + } + ) + ) + with pytest.raises( + module.DeniedDefaultFillError, match=rf"tax_unit\.{column} \(2 null rows\)" + ): + module.fill_reviewed_nulls(frame, summary) + assert tax_unit[column].isna().sum() == 2 + + +def test_the_prepass_reads_pending_aca_cells_at_the_engine_default( + tmp_path, monkeypatch +) -> None: + """microcosm#1720: the SSI and Medicaid pre-pass runs before the ACA + stage, so its ACS view still carries null ACA cells, which the + never-default rule would refuse. The pre-pass reads them at the engine + defaults, what the reviewed fill gave them before the stage existed.""" + + module = _load_tool_module() + fixtures = _aca_fixtures() + frame = fixtures._frame(n_donor=10, n_acs=20) + view = frame.select(np.ones(frame.n("person"), dtype=bool)) + stored = view.table("tax_unit")[list(_ACA)].copy() + acs = stored[_ACA[0]].isna().to_numpy() + assert acs.any() and not acs.all() + system = SimpleNamespace( + variables={ + _ACA[0]: SimpleNamespace(default_value=True, value_type=bool), + _ACA[1]: SimpleNamespace(default_value=1.0, value_type=float), + } + ) + seen = [] + + def fill(view, summary_path, *, period, system): + seen.append(view.table("tax_unit")[list(_ACA)].copy()) + return [], [] + + monkeypatch.setattr(module, "_formula_owned_columns", lambda view: set()) + monkeypatch.setattr(module, "fill_reviewed_nulls", fill) + + module._prepass_view_contract( + view, summary_path=tmp_path / "s.json", hh_chunk=10_000, system=system + ) + + (filled,) = seen + assert filled[_ACA[0]].dtype == bool + assert filled.loc[acs, _ACA[0]].all() + assert (filled.loc[acs, _ACA[1]] == 1.0).all() + # Stored donor cells are untouched. + assert ( + filled.loc[~acs, _ACA[0]].tolist() + == stored.loc[~acs, _ACA[0]].astype(bool).tolist() + ) + assert filled.loc[~acs, _ACA[1]].tolist() == stored.loc[~acs, _ACA[1]].tolist() + + @pytest.mark.parametrize( "edit", [ @@ -2692,6 +2871,178 @@ def test_ssi_medicaid_consumers_accept_a_current_checkpoint(tmp_path) -> None: assert path == tmp_path / module.ACS_SSI_MEDICAID_TAKE_UP_FILENAME +def _aca_fixtures(): + """The ACA take-up stage's engine-free fixtures (#1720).""" + + spec = importlib.util.spec_from_file_location( + "acs_local_aca_take_up_fixtures", + Path(__file__).with_name("test_us_acs_local_aca_take_up.py"), + ) + fixtures = importlib.util.module_from_spec(spec) + assert spec.loader is not None + spec.loader.exec_module(fixtures) + return fixtures + + +def _aca_receipt(module, checkpoint_dir: Path, **overrides) -> dict: + """A current ACA materialize receipt whose recorded file exists (#1720).""" + + path = checkpoint_dir / module.ACS_ACA_TAKE_UP_FILENAME + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b"recorded ACA assignment") + receipt = { + "issue": "microcosm#1720", + "method": module.ACS_LOCAL_ACA_TAKE_UP_METHOD, + "seed": 0, + "assigned_sha256": "c" * 64, + "gate": {"passed": True, "failures": [], "report_only": True}, + "assignment_file": {"name": path.name, "sha256": module._sha256(path)}, + } + receipt.update(overrides) + return receipt + + +@pytest.mark.parametrize( + "edit", + [ + "absent", + "wrong_issue", + "wrong_method", + "untyped_seed", + "no_file_record", + "missing_file", + "changed_file", + ], +) +def test_aca_consumers_refuse_a_checkpoint_without_the_assignment( + tmp_path, edit +) -> None: + """microcosm#1720: calibrate and the export need the recorded ACS ACA + assignment, the lane's convention for every drawn column.""" + + module = _load_tool_module() + receipt = _aca_receipt(module, tmp_path) + recorded = tmp_path / module.ACS_ACA_TAKE_UP_FILENAME + if edit == "wrong_issue": + receipt["issue"] = "microcosm#1022" + elif edit == "wrong_method": + receipt["method"] = "engine_default" + elif edit == "untyped_seed": + receipt["seed"] = "0" + elif edit == "no_file_record": + del receipt["assignment_file"] + elif edit == "missing_file": + recorded.unlink() + elif edit == "changed_file": + recorded.write_bytes(b"another assignment") + identity = {} if edit == "absent" else {"acs_local_aca_take_up": receipt} + with pytest.raises(SystemExit, match=r"microcosm#1720.*Re-run --stage materialize"): + module._recorded_aca_take_up(identity, tmp_path) + + +def test_aca_consumers_accept_a_checkpoint_whose_report_only_grade_failed( + tmp_path, +) -> None: + """The ACA grade is report-only: a failed verdict does not refuse.""" + + module = _load_tool_module() + receipt = _aca_receipt( + module, + tmp_path, + gate={"passed": False, "failures": ["invented miss"], "report_only": True}, + ) + recorded, path = module._recorded_aca_take_up( + {"acs_local_aca_take_up": receipt}, tmp_path + ) + assert recorded == receipt + assert path == tmp_path / module.ACS_ACA_TAKE_UP_FILENAME + + +def test_the_aca_stage_records_a_failed_grade_and_goes_on(monkeypatch) -> None: + """microcosm#1720: materialize never stops on the ACA grade.""" + + module = _load_tool_module() + receipt = { + "engine_prepass": {}, + "take_up": {"column": "takes_up_aca_if_eligible", "filled_rows": 3}, + "plan_ratio": { + "column": "selected_marketplace_plan_benchmark_ratio", + "filled_rows": 3, + }, + } + receipt["take_up"]["weighted_take_up_share_of_eligible"] = 0.4 + monkeypatch.setattr( + module, + "with_acs_local_aca_take_up", + lambda frame, **_k: (frame, copy.deepcopy(receipt)), + ) + monkeypatch.setattr( + module, + "acs_local_aca_take_up_signal_gate", + lambda frame, *, receipt: GateResult( + name="acs_local_aca_take_up_signal", + passed=False, + failures=("state 06: invented miss.",), + ), + ) + targets = {"target_tables": {}} + frame, recorded = module._with_local_aca_take_up( + "frame", seed=1, targets=targets, summary_path=Path("s"), hh_chunk=10 + ) + assert frame == "frame" + assert recorded["gate"] == { + "name": "acs_local_aca_take_up_signal", + "passed": False, + "failures": ["state 06: invented miss."], + "report_only": True, + } + assert recorded["engine_prepass"]["hh_chunk"] == 10 + + def broken(frame, *, receipt): + raise KeyError("tables") + + monkeypatch.setattr(module, "acs_local_aca_take_up_signal_gate", broken) + _frame, recorded = module._with_local_aca_take_up( + "frame", seed=1, targets=targets, summary_path=Path("s"), hh_chunk=10 + ) + assert recorded["gate"]["passed"] is False + assert "the grade could not run" in recorded["gate"]["failures"][0] + + def unreadable(frame, **_k): + raise ValueError("no SERIALNO") + + monkeypatch.setattr(module, "with_acs_local_aca_take_up", unreadable) + with pytest.raises(SystemExit, match="microcosm#1720.*no SERIALNO"): + module._with_local_aca_take_up( + "frame", seed=1, targets=targets, summary_path=Path("s"), hh_chunk=10 + ) + + +def test_the_recorded_aca_assignment_file_round_trips(tmp_path) -> None: + """The export rebuilds the stage's ACS inputs from the checkpoint file + and refuses a file that no longer matches the receipt's digest.""" + + module = _load_tool_module() + fixtures = _aca_fixtures() + frame = fixtures._frame(n_donor=60, n_acs=240) + assigned, receipt = fixtures._assign(frame) + path = tmp_path / module.ACS_ACA_TAKE_UP_FILENAME + receipt["assignment_file"] = { + "name": path.name, + "sha256": module._write_aca_take_up(assigned, path), + } + applied = module._with_recorded_aca_take_up(frame, receipt, path) + for column in module.ACS_LOCAL_ACA_TAKE_UP_COLUMNS: + assert ( + applied.table("tax_unit")[column].tolist() + == assigned.table("tax_unit")[column].tolist() + ) + with pytest.raises(SystemExit, match="microcosm#1720.*digest"): + module._with_recorded_aca_take_up( + frame, {**receipt, "assigned_sha256": "0" * 64}, path + ) + + def test_materialize_resolves_the_take_up_counts_before_hashing_the_staging_h5( tmp_path, monkeypatch ) -> None: @@ -2727,13 +3078,73 @@ def test_materialize_resolves_the_take_up_counts_before_hashing_the_staging_h5( module, "_load_staging_frame", lambda path: touched.append(path) ) - def unavailable(feed): + # microcosm#1720: one compile serves the SSI/Medicaid and ACA counts. + compiles = [] + monkeypatch.setattr( + module, + "_compiled_fiscal_registry", + lambda feed: compiles.append(feed) or (SimpleNamespace(specs=[]), []), + ) + + def unavailable(feed, *, compiled): + assert compiled[0].specs == [] raise SystemExit(f"no SSA band counts in {Path(feed).name}") monkeypatch.setattr(module, "acs_local_ssi_medicaid_take_up_targets", unavailable) with pytest.raises(SystemExit, match="no SSA band counts in facts.jsonl"): module.do_materialize(args) assert touched == [] + assert len(compiles) == 1 + + +def test_materialize_reads_the_aca_counts_from_the_same_compile( + tmp_path, monkeypatch +) -> None: + """microcosm#1720: a feed without the ACA tables stops materialize + before the staging H5 is hashed, and the feed is compiled once.""" + + module = _load_tool_module() + args = module._parse_args(_materialize_argv(tmp_path)) + (tmp_path / "staging.h5").write_bytes(b"staging") + (tmp_path / "staging.summary.json").write_text( + json.dumps( + { + "reviewed_engine_input_nulls": [{"entity": "person"}], + **_staging_receipt_anchor_summary(), + "engine_versions": { + "policyengine_us": module._installed_engine_version() + }, + } + ) + ) + monkeypatch.setattr( + module, + "state_admin_surface", + lambda *a, **k: SimpleNamespace(registry=[], ri_substitutions=[]), + ) + monkeypatch.setattr(module, "ladder_population", lambda *a, **k: {}) + monkeypatch.setattr(module, "require_one_label_per_geography", lambda *a, **k: None) + touched = [] + monkeypatch.setattr(module, "_sha256", lambda path: touched.append(path)) + monkeypatch.setattr( + module, "_load_staging_frame", lambda path: touched.append(path) + ) + compiled = (SimpleNamespace(specs=[]), []) + compiles = [] + monkeypatch.setattr( + module, + "_compiled_fiscal_registry", + lambda feed: compiles.append(feed) or compiled, + ) + monkeypatch.setattr( + module, + "acs_local_ssi_medicaid_take_up_targets", + lambda feed, *, compiled: {"compiled": compiled}, + ) + with pytest.raises(SystemExit, match="microcosm#1720.*cms_aca_aptc_recipients"): + module.do_materialize(args) + assert touched == [] + assert len(compiles) == 1 def test_calibrate_refuses_a_checkpoint_without_the_ssi_medicaid_assignment( @@ -2758,6 +3169,37 @@ def test_calibrate_refuses_a_checkpoint_without_the_ssi_medicaid_assignment( module.do_calibrate(args) +def test_calibrate_refuses_a_checkpoint_without_the_aca_assignment( + tmp_path, monkeypatch +) -> None: + """microcosm#1720: a checkpoint materialized before the ACA stage is + refused before the solve, as the export would refuse it.""" + + module = _load_tool_module() + args = module._parse_args(_calibrate_argv(tmp_path)) + (tmp_path / "staging.summary.json").write_text( + json.dumps(_staging_receipt_anchor_summary()) + ) + monkeypatch.setattr( + module, + "_verify_run_identity", + lambda a: { + "acs_local_take_up": _TAKE_UP_RECEIPT, + "acs_local_ssi_medicaid_take_up": _ssi_medicaid_receipt( + module, args.checkpoint_dir + ), + }, + ) + monkeypatch.setattr(module, "_require_reviewed_donor_lineage", lambda s: None) + monkeypatch.setattr( + module, + "load_lean_frame", + lambda *a, **k: pytest.fail("calibrate loaded the checkpoint"), + ) + with pytest.raises(SystemExit, match=r"no ACS local ACA take-up assignment"): + module.do_calibrate(args) + + def test_consumer_export_refuses_a_checkpoint_without_the_ssi_medicaid_assignment( tmp_path, monkeypatch ) -> None: @@ -3118,6 +3560,7 @@ def _record_current_materialization(module, args, identity: dict) -> dict: identity["acs_local_ssi_medicaid_take_up"] = _ssi_medicaid_receipt( module, args.checkpoint_dir ) + identity["acs_local_aca_take_up"] = _aca_receipt(module, args.checkpoint_dir) return identity @@ -3876,6 +4319,114 @@ def test_pinned_feed_soi_surfaces_match_their_contracts() -> None: } +def _aca_spec(name, role, state, value, *, level="state", groupby="state"): + return SimpleNamespace( + name=name, + value=value, + metadata={ + "ledger_geography_level": level, + "ledger_layout_groupby_dimension": groupby, + "state_fips": state, + "target_role": role, + }, + ) + + +def test_aca_take_up_targets_read_the_state_tables_of_the_compiled_registry( + monkeypatch, +) -> None: + """microcosm#1720: the ACA tables come from the registry materialize + already compiled for SSI and Medicaid, read as the fiscal lane reads + them; district rows and other roles stay out.""" + + module = _load_tool_module() + monkeypatch.setattr( + module, + "_compiled_fiscal_registry", + lambda feed: pytest.fail("the ACA targets compiled the feed again"), + ) + specs = [ + _aca_spec("cms.aptc.ca", "aca_ptc_recipients", "6", 1_500_000.0), + _aca_spec("cms.aptc.de", "aca_ptc_recipients", "10", 30_000.0), + _aca_spec("soi.returns.ca", "aca_ptc_returns", "6", 600_000.0), + _aca_spec("soi.amount.ca", "aca_spending", "6", 4.0e9), + # The district file's state total and a district row stay out. + _aca_spec( + "soi.cd.ca_total", + "aca_ptc_returns", + "6", + 590_000.0, + groupby="irs_soi.congressional_district", + ), + _aca_spec("soi.cd.ca01", "aca_ptc_returns", "6", 9_000.0, level="cd"), + _aca_spec("cms.enrollment.ca", "aca_enrollment", "6", 1_800_000.0), + ] + compiled = (SimpleNamespace(specs=specs), []) + + targets = module.acs_local_aca_take_up_targets("facts.jsonl", compiled=compiled) + + tables = targets["target_tables"] + assert sorted(tables) == [ + "cms_aca_aptc_recipients_by_state", + "irs_soi_premium_tax_credit_amount_by_state", + "irs_soi_premium_tax_credit_returns_by_state", + ] + aptc = tables["cms_aca_aptc_recipients_by_state"] + assert aptc["state_fips"].tolist() == ["06", "10"] + assert aptc["target"].tolist() == [1_500_000.0, 30_000.0] + returns = tables["irs_soi_premium_tax_credit_returns_by_state"] + assert returns["source_record_id"].tolist() == ["soi.returns.ca"] + + # Without the APTC-recipient table the stage has no rate to draw at. + with pytest.raises(SystemExit, match="microcosm#1720"): + module.acs_local_aca_take_up_targets( + "facts.jsonl", compiled=(SimpleNamespace(specs=specs[2:4]), []) + ) + + +def test_pinned_feed_aca_take_up_targets_bind_the_state_surface_ptc_rows() -> None: + """On the real feed: the ACA stage's SOI tables are exactly the 102 + premium tax credit rows of R2's default ``state`` surface, the CMS table + covers 51 states, and no bronze table exists, so the stage stops after + the ratio's clip as the fiscal lane does (microcosm#1720). + + Feed-gated like the surface contract test above: two registry compiles. + """ + + feed = os.environ.get("MICROCOSM_US_CHRONICLE_FACTS", "") + if not feed or not Path(feed).exists(): + pytest.skip( + "set MICROCOSM_US_CHRONICLE_FACTS to the pinned consumer-facts feed" + ) + + module = _load_tool_module() + tables = module.acs_local_aca_take_up_targets(feed)["target_tables"] + assert sorted(tables) == [ + "cms_aca_aptc_recipients_by_state", + "irs_soi_premium_tax_credit_amount_by_state", + "irs_soi_premium_tax_credit_returns_by_state", + ] + for table in tables.values(): + assert len(table) == 51 + assert table["state_fips"].is_unique + registry, _ = module.state_admin_specs(feed, ["snap", "medicaid", "soi"]) + surface_ptc = { + spec.name + for spec in registry.specs + if spec.metadata.get("target_role") in {"aca_ptc_returns", "aca_spending"} + } + soi = { + name + for table in ( + tables["irs_soi_premium_tax_credit_returns_by_state"], + tables["irs_soi_premium_tax_credit_amount_by_state"], + ) + for name in table["source_record_id"] + } + assert len(surface_ptc) == 102 + assert soi == surface_ptc + + def _staging_frame_with_hours(weekly: list[float], last_week: list[float]): """A minimal US-schema staging frame carrying the two pool hours columns.""" @@ -6631,7 +7182,7 @@ def _reviewed_fill(entity, column, fill_value="0", spine="acs_2024_1yr") -> dict def test_the_register_covers_every_remaining_reviewed_fill() -> None: - """Release 767312d60 default-filled 79 columns; the stack now fills 20 of + """Release 767312d60 default-filled 79 columns; the stack now fills 37 of them (NEVER_DEFAULT_FILLED), and every other one has a register entry, except one the reviewed engine no longer defines, as does each reviewed fill added since.""" @@ -6652,10 +7203,16 @@ def test_the_register_covers_every_remaining_reviewed_fill() -> None: assert len(released) == 79 now_filled = released & set(module.NEVER_DEFAULT_FILLED) registered = {(entry["entity"], entry["column"]) for entry in document["entries"]} - # 20 are filled natively, 1 is retired and 58 are registered. The ACS + # 37 are filled natively, 1 is retired and 41 are registered. The ACS # vehicle count returned to a reviewed fill after the microcosm#1064 review # (VEH counts vehicles available, not owned): it left NEVER_DEFAULT_FILLED - # and gained an entry together, so this still holds. + # and gained an entry together, so this still holds. microcosm#1720: + # staging maps the ACS rows' marital, military and occupation status and + # attributes their self-employed health premiums, and draws their weeks + # unemployed and three retirement deferrals, and their tax units' + # voluntary filing; materialize draws the tax units' ACA take-up and + # plan ratio. + assert len(now_filled) == 37 assert _REVIEWED_FILLS_RETIRED_SINCE_767312D60 <= released - now_filled assert ( registered @@ -6721,7 +7278,7 @@ def test_do_finalize_grades_the_registered_fills_of_both_engine_passes( module = _load_tool_module() args = _finalize_args(module, tmp_path) fills = [ - _reviewed_fill("person", "weeks_unemployed"), + _reviewed_fill("person", "pre_subsidy_rent"), _reviewed_fill("household", "household_vehicles_value"), ] for name in module.REVIEWED_FILL_MANIFESTS: @@ -6748,14 +7305,16 @@ def test_do_finalize_grades_the_registered_fills_of_both_engine_passes( assert detail["known_bias"]["household.household_vehicles_value"]["snap"] == ( "mixed" ) - # policyengine-us 2.145.3 reads the weeks: they set the months of UC receipt, - # which SNAP's ABAWD time limit and, from 2027, Medicaid's SNAP pass-through - # read (microcosm#1675). - assert detail["known_bias"]["person.weeks_unemployed"] == { - "aca_ptc": "mixed", - "medicaid": "understates", - "snap": "overstates", - } + # Group-quarters residents who pay for shelter lose SNAP's shelter + # deduction at 0 rent (microcosm#1071 review); weeks unemployed, the + # earlier example here, left the register when staging began to draw them + # (microcosm#1720). + known = detail["known_bias"]["person.pre_subsidy_rent"] + assert (known["snap"], known["medicaid"], known["aca_ptc"]) == ( + "understates", + "understates", + "mixed", + ) entries = load_reviewed_fill_consumer_register()["entries"] assert len(detail["unused_entries"]) == len(entries) - 2 summary = json.loads(args.out_summary.read_text()) @@ -6867,9 +7426,10 @@ def test_package_regrades_the_packaged_fill_manifests(tmp_path, monkeypatch): def test_package_ships_the_register_and_records_its_digest(tmp_path, monkeypatch): module = _load_tool_module() args = _package_args_with_hours(module, tmp_path, monkeypatch, gate_state="passed") - # microcosm#1675: EITC take-up is drawn on ACS rows and never default-filled; - # ACA take-up still ships at the default with its reviewed known bias. - fills = [_reviewed_fill("tax_unit", "takes_up_aca_if_eligible", "True")] + # microcosm#1675/#1720: EITC and ACA take-up are drawn on ACS rows and + # never default-filled; the owned vehicle count still ships at the + # default with its reviewed known bias. + fills = [_reviewed_fill("household", "household_vehicles_owned", "0")] (args.checkpoint_dir / "consumer_reviewed_null_fills.json").write_text( json.dumps({"columns_filled": 1, "fills": fills}) ) @@ -6889,7 +7449,9 @@ def test_package_ships_the_register_and_records_its_digest(tmp_path, monkeypatch assert record["sha256"] == reviewed_fill_register_sha256(document) assert record["entries"] == len(document["entries"]) assert record["reviewed_against"] == {"policyengine_us": _REVIEWED_ENGINE} - assert record["known_bias"]["tax_unit.takes_up_aca_if_eligible"] == ["aca_ptc"] + assert record["known_bias"]["household.household_vehicles_owned"] == [ + "general_assistance" + ] gate = json.loads((release_dir / "gate_summary.json").read_text())["gates"][ "acs_local_reviewed_fill_consumers" ] @@ -6898,7 +7460,7 @@ def test_package_ships_the_register_and_records_its_digest(tmp_path, monkeypatch assert gate["artifact_sha256"] == result["root_artifact"]["sha256"] assert gate["detail"]["register_sha256"] == record["sha256"] assert gate["detail"]["known_bias"] == { - "tax_unit.takes_up_aca_if_eligible": {"aca_ptc": "overstates"} + "household.household_vehicles_owned": {"general_assistance": "overstates"} } @@ -7125,6 +7687,7 @@ def test_do_calibrate_stamps_and_records_the_penalty_settings( identity["acs_local_ssi_medicaid_take_up"] = _ssi_medicaid_receipt( module, args.checkpoint_dir ) + identity["acs_local_aca_take_up"] = _aca_receipt(module, args.checkpoint_dir) # A checkpoint materialized before #1019 is refused before any solve. monkeypatch.setattr( module, "_verify_run_identity", lambda args: {"staging_sha256": "s"} @@ -7260,6 +7823,7 @@ def recording_solve(*a, **k): lambda f, seed: (f, {"assigned_sha256": _TAKE_UP_RECEIPT["assigned_sha256"]}), ) monkeypatch.setattr(module, "_with_recorded_ssi_medicaid_take_up", lambda f, *a: f) + monkeypatch.setattr(module, "_with_recorded_aca_take_up", lambda f, *a: f) monkeypatch.setattr(module, "project_input_only", lambda f, **k: (f, {})) monkeypatch.setattr(module, "fill_reviewed_nulls", lambda *a, **k: ([], None)) @@ -7299,6 +7863,7 @@ def write_dataset(calibrated, path, **kwargs): identity["acs_local_ssi_medicaid_take_up"] = _ssi_medicaid_receipt( module, args.checkpoint_dir ) + identity["acs_local_aca_take_up"] = _aca_receipt(module, args.checkpoint_dir) return args, events @@ -8005,12 +8570,18 @@ def _write_calibrated( "_recorded_ssi_medicaid_take_up", lambda *a, **k: ({"assigned_sha256": "", "assignment_file": ""}, None), ) + monkeypatch.setattr( + module, + "_recorded_aca_take_up", + lambda *a, **k: ({"assigned_sha256": "", "assignment_file": ""}, None), + ) monkeypatch.setattr( module, "_resample_like_materialize", lambda frame, identity: frame ) monkeypatch.setattr( module, "_with_recorded_ssi_medicaid_take_up", lambda frame, *a: frame ) + monkeypatch.setattr(module, "_with_recorded_aca_take_up", lambda frame, *a: frame) monkeypatch.setattr( module, "_with_live_stored_inputs", diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_reviewed_fill_consumers.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_reviewed_fill_consumers.py index c058d0a8db..da721752ef 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_reviewed_fill_consumers.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_reviewed_fill_consumers.py @@ -624,9 +624,10 @@ def test_the_committed_register_is_sound() -> None: def test_the_committed_register_carries_the_triage_verdicts_for_snap() -> None: """microcosm#1022's triage: these defaults are harmless for SNAP (SNAP is - no consumer, or its note says harmless), and the vehicle value is not. On - policyengine-us 2.145.3 weeks unemployed are not harmless either - (microcosm#1675).""" + no consumer, or its note says harmless), and the vehicle value is not. + Weeks unemployed, not harmless on policyengine-us 2.145.3 (microcosm#1675), + and the self-employed premium left the register when staging began to + write them on ACS rows (microcosm#1720).""" document = load_reviewed_fill_consumer_register() entries = {entry["column"]: entry for entry in document["entries"]} @@ -641,16 +642,14 @@ def snap_verdict(column): for column in ( "spm_unit_energy_subsidy", "net_worth", - "health_insurance_premiums", "real_estate_taxes", "tenure_type", "spm_unit_tenure_type", ): assert snap_verdict(column) in {"harmless", "not a consumer"}, column assert snap_verdict("household_vehicles_value") == "known_bias" - # The weeks set the months of UC receipt, which exempt a recipient from the - # ABAWD time limit only in those months (policyengine-us 2.145.3). - assert snap_verdict("weeks_unemployed") == "known_bias" + for column in ("weeks_unemployed", "health_insurance_premiums"): + assert column not in entries, column # microcosm#1071 review: residents of noninstitutional group quarters who # pay for shelter lose the shelter deduction at 0 rent. assert snap_verdict("pre_subsidy_rent") == "known_bias" diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_se_health_premiums.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_se_health_premiums.py new file mode 100644 index 0000000000..c56cdaacb3 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_se_health_premiums.py @@ -0,0 +1,303 @@ +"""ACS local lane: self-employed health insurance inputs (microcosm#1720).""" + +from __future__ import annotations + +import json +from types import SimpleNamespace +from typing import Any, cast + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build.us_runtime import acs_multispine +from microcosm.build.us_runtime.acs_local_se_health_premiums import ( + ACS_LOCAL_SE_HEALTH_PREMIUM_COLUMNS, + ACS_LOCAL_SE_HEALTH_PREMIUMS_ISSUE, + ACS_LOCAL_SE_HEALTH_PREMIUMS_METHOD, + ACS_LOCAL_SE_HEALTH_PREMIUMS_SOURCE_COLUMNS, + with_acs_local_se_health_premiums, +) +from microcosm.build.us_runtime.acs_pums import ACS_2024_1YR_SPINE, AcsPumsSource +from microcosm.build.us_runtime.other_health_insurance import ( + attribute_us_se_health_premiums, +) +from microcosm.frame import US_SCHEMA, Frame, WeightKind, Weights + +#: Eight ACS persons after the shared transfer, one per household: +#: 0 self-employed, premium, no ESI -> flagged, premium kept +#: 1 self-employed via the SSTB leaf only -> flagged, premium kept +#: 2 self-employed but 70 (Medicare proxy) -> flagged, premium withheld +#: 3 self-employed with SS disability -> flagged, premium withheld +#: 4 self-employed with ESI -> flagged, premium withheld +#: 5 Schedule C loss -> not flagged +#: 6 a wage earner with a premium -> not flagged +#: 7 a child of 10 (SEMP blank) -> not flagged +_PERSONS = { + "age": [40.0, 35.0, 70.0, 50.0, 45.0, 30.0, 28.0, 10.0], + "self_employment_income_before_lsr": [ + 20_000.0, + 0.0, + 9_000.0, + 5_000.0, + 8_000.0, + -3_000.0, + 0.0, + np.nan, + ], + "sstb_self_employment_income_before_lsr": [0.0, 4_000.0, 0, 0, 0, 0, 0, 0], + "health_insurance_premiums_without_medicare_part_b": [ + 6_000.0, + 3_000.0, + 2_000.0, + 1_500.0, + 1_200.0, + 900.0, + 4_000.0, + 0.0, + ], + "social_security_disability": [0.0, 0.0, 0.0, 7_000.0, 0, 0, 0, 0], + "has_esi": [False, False, False, False, True, False, True, False], + "COW": [6.0, 7.0, 6.0, 6.0, 7.0, 6.0, 1.0, np.nan], +} + + +def _acs_frame(**overrides: Any) -> Frame: + ids = np.arange(1, 9) + person = pd.DataFrame( + { + "person_id": ids, + **{ + f"person_{entity}_id": ids + for entity in US_SCHEMA.entities + if entity != "person" + }, + **_PERSONS, + **overrides, + } + ) + return Frame( + { + "person": person, + **{ + entity: pd.DataFrame({f"{entity}_id": ids}) + for entity in US_SCHEMA.entities + if entity != "person" + }, + }, + US_SCHEMA, + {"household": Weights(np.arange(1.0, 9.0) * 10.0, WeightKind.DESIGN)}, + pd.Series(ACS_2024_1YR_SPINE, index=person.index, dtype=object), + ) + + +def test_the_acs_rows_get_the_donors_attribution() -> None: + frame = _acs_frame() + result, receipt = with_acs_local_se_health_premiums(frame) + person = result.table("person") + + assert person["is_self_employed"].tolist() == [1, 1, 1, 1, 1, 0, 0, 0] + assert person["health_insurance_premiums"].tolist() == [ + 6_000.0, + 3_000.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ] + assert person["is_self_employed"].dtype == bool + # The input frame is untouched. + assert "is_self_employed" not in frame.table("person") + + assert receipt["issue"] == ACS_LOCAL_SE_HEALTH_PREMIUMS_ISSUE == "microcosm#1720" + assert receipt["method"] == ACS_LOCAL_SE_HEALTH_PREMIUMS_METHOD + assert receipt["source_columns"] == list( + ACS_LOCAL_SE_HEALTH_PREMIUMS_SOURCE_COLUMNS + ) + assert receipt["acs_persons"] == 8 + assert receipt["self_employment_blank_under_15_read_as_zero_rows"] == 1 + assert receipt["columns"] == { + "health_insurance_premiums": {"filled_rows": 8, "preserved_rows": 0}, + "is_self_employed": {"filled_rows": 8, "preserved_rows": 0}, + } + assert receipt["self_employed_rows"] == 5 + assert receipt["self_employed_weighted_share"] == pytest.approx(150.0 / 360.0) + assert receipt["premium_positive_rows"] == 2 + assert receipt["premium_weighted_total"] == pytest.approx( + 10 * 6_000.0 + 20 * 3_000.0 + ) + assert receipt["withheld"] == { + "self_employed_with_reported_premium_rows": 5, + "medicare_proxy_rows": 2, + "employer_coverage_rows": 1, + } + # COW 6/7 against the Schedule C flag: the loss (COW 6) is cow-only. + assert receipt["cow_agreement"] == { + "loaded": True, + "cow_codes": [6, 7], + "both_rows": 5, + "flag_only_rows": 0, + "cow_only_rows": 1, + "cow_blank_rows": 1, + } + json.dumps(receipt, allow_nan=False) + + +def test_the_stage_is_the_donors_function_on_a_complete_view() -> None: + """One rule for both sets of rows: on complete inputs the stage's values + are exactly the donor function's.""" + + view = pd.DataFrame( + { + column: _PERSONS[column] + for column in ACS_LOCAL_SE_HEALTH_PREMIUMS_SOURCE_COLUMNS + } + ).fillna(0.0) + expected = attribute_us_se_health_premiums(view) + result, _ = with_acs_local_se_health_premiums(_acs_frame()) + person = result.table("person") + for column in ACS_LOCAL_SE_HEALTH_PREMIUM_COLUMNS: + np.testing.assert_array_equal( + person[column].to_numpy(), expected[column].to_numpy() + ) + + +def test_stored_values_stand_and_only_missing_cells_are_filled() -> None: + stored = [np.nan, 111.0, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan] + result, receipt = with_acs_local_se_health_premiums( + _acs_frame(health_insurance_premiums=stored) + ) + person = result.table("person") + assert person["health_insurance_premiums"].tolist()[:2] == [6_000.0, 111.0] + assert receipt["columns"]["health_insurance_premiums"] == { + "filled_rows": 7, + "preserved_rows": 1, + } + + +def test_without_cow_the_agreement_is_marked_unloaded() -> None: + frame = _acs_frame() + tables = {entity: frame.table(entity) for entity in frame.entities} + tables["person"] = tables["person"].drop(columns=["COW"]) + _, receipt = with_acs_local_se_health_premiums( + Frame( + tables, + US_SCHEMA, + {"household": frame.weights_for("household")}, + frame.strata, + ) + ) + assert receipt["cow_agreement"] == {"loaded": False} + + +@pytest.mark.parametrize( + ("overrides", "match"), + [ + ( + {"self_employment_income_before_lsr": [np.nan, 0, 0, 0, 0, 0, 0, 0]}, + r"aged 15\+ have a blank self_employment_income_before_lsr", + ), + ( + {"social_security_disability": [np.nan, 0, 0, 0, 0, 0, 0, 0]}, + "blank transferred social_security_disability", + ), + ({"has_esi": [np.nan, 0, 0, 0, 0, 0, 0, 0]}, "complete boolean"), + ( + { + "health_insurance_premiums_without_medicare_part_b": [ + -1.0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ] + }, + "microcosm#1720", + ), + ], +) +def test_inputs_the_rule_cannot_read_are_refused(overrides, match) -> None: + with pytest.raises(ValueError, match=match): + with_acs_local_se_health_premiums(_acs_frame(**overrides)) + + +def test_a_missing_input_column_is_refused() -> None: + frame = _acs_frame() + tables = {entity: frame.table(entity) for entity in frame.entities} + tables["person"] = tables["person"].drop(columns=["has_esi"]) + with pytest.raises(ValueError, match=r"\['has_esi'\]"): + with_acs_local_se_health_premiums( + Frame( + tables, + US_SCHEMA, + {"household": frame.weights_for("household")}, + frame.strata, + ) + ) + + +def test_the_seam_attributes_after_the_transfer_and_before_pooling( + monkeypatch, tmp_path +) -> None: + events: list[tuple[Any, ...]] = [] + transferred = SimpleNamespace(table=lambda entity: pd.DataFrame()) + attributed = object() + pooled = object() + base = SimpleNamespace(table=lambda entity: pd.DataFrame()) + + monkeypatch.setattr( + acs_multispine, + "build_acs_pums_unit_frame", + lambda source, *, chunksize: (object(), {"spine": ACS_2024_1YR_SPINE}), + ) + monkeypatch.setattr( + acs_multispine, + "map_acs_native_inputs", + lambda frame: SimpleNamespace(frame=object(), native_inputs={}), + ) + + def fake_transfer(recipient, donor, **kwargs): + events.append(("transfer",)) + return SimpleNamespace( + frame=transferred, + imputed_inputs=(), + fit_records=(), + deferred_inputs=(), + resolved_donor_channel="puf_support", + ) + + def fake_attribute(frame): + events.append(("se_health", frame)) + return attributed, {"issue": "microcosm#1720", "share": np.float64(0.1)} + + def fake_pool(actual_base, actual_acs, **kwargs): + events.append(("pool", actual_acs)) + return pooled + + monkeypatch.setattr(acs_multispine, "transfer_acs_inputs", fake_transfer) + monkeypatch.setattr( + acs_multispine, "with_acs_local_se_health_premiums", fake_attribute + ) + monkeypatch.setattr(acs_multispine, "with_optional_acs_spine", fake_pool) + + source = AcsPumsSource(tmp_path / "csv_hus.zip", tmp_path / "csv_pus.zip") + result = acs_multispine.build_optional_acs_multispine( + cast(Frame, base), source, se_health_premiums=True + ) + assert events == [("transfer",), ("se_health", transferred), ("pool", attributed)] + assert result.provenance["acs_local_se_health_premiums"] == { + "issue": "microcosm#1720", + "share": 0.1, + } + json.dumps(result.provenance, allow_nan=False) + + # Without the flag (the pool lane) the stage never runs. + events.clear() + result = acs_multispine.build_optional_acs_multispine(cast(Frame, base), source) + assert events == [("transfer",), ("pool", transferred)] + assert "acs_local_se_health_premiums" not in result.provenance diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_status_inputs.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_status_inputs.py new file mode 100644 index 0000000000..3ddc882866 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_status_inputs.py @@ -0,0 +1,429 @@ +"""ACS local lane: marital, military and occupation status (microcosm#1720).""" + +from __future__ import annotations + +import json + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build.source_manifest import SourceOperationSpec +from microcosm.build.us_runtime import acs_multispine +from microcosm.build.us_runtime.acs_local_status_inputs import ( + ACS_LOCAL_MARITAL_STATUS_COLUMNS, + ACS_LOCAL_OCCUPATION_FLAG_COLUMNS, + ACS_LOCAL_STATUS_INPUTS_COLUMNS, + ACS_LOCAL_STATUS_INPUTS_ISSUE, + ACS_LOCAL_STATUS_INPUTS_METHOD, + map_acs_local_status_inputs, +) +from microcosm.build.us_runtime.acs_pums import ( + _ACS_TO_CPS_MARITAL_STATUS, + ACS_2024_1YR_SPINE, + AcsPumsSource, +) +from microcosm.build.us_runtime.base_pool import spine_column +from microcosm.build.us_runtime.org_wages import ( + FLSA_EXECUTIVE_ADMINISTRATIVE_PROFESSIONAL_OCCUPATION_CODES, + derive_us_org_occupation_inputs, + us_flsa_occupation_flags, +) +from microcosm.build.us_runtime.relationship_inputs import ( + derive_us_relationship_inputs_from_manifest, + us_marital_status_inputs, +) +from microcosm.frame import US_SCHEMA, Frame, WeightKind, Weights + +TAG = spine_column("person") + + +# --------------------------------------------------------------------------- +# The donor's own rules, shared with the ACS rows +# --------------------------------------------------------------------------- + + +def test_the_loader_maps_separated_and_widowed_to_the_donor_codes() -> None: + """The premise of the marital rule: ACS MAR 4 is A_MARITL 6 and MAR 2 is 4.""" + + assert _ACS_TO_CPS_MARITAL_STATUS[4] == 6 + assert _ACS_TO_CPS_MARITAL_STATUS[2] == 4 + + +def test_the_donor_stage_still_derives_its_marital_leaves_from_the_shared_rule(): + codes = np.asarray([1, 2, 3, 4, 5, 6, 7]) + frame = pd.DataFrame({"PH_SEQ": np.arange(1, 8), "P_SEQ": 1, "A_MARITL": codes}) + derived = derive_us_relationship_inputs_from_manifest( + frame, + SourceOperationSpec(kind="derive_relationship_inputs", parameters={}), + None, + ) + shared = us_marital_status_inputs(codes) + assert derived["is_separated"].tolist() == [False] * 5 + [True, False] + assert derived["is_surviving_spouse"].tolist() == [False] * 3 + [True] + [False] * 3 + for column in ACS_LOCAL_MARITAL_STATUS_COLUMNS: + np.testing.assert_array_equal(derived[column].to_numpy(), shared[column]) + + +def test_the_shared_marital_rule_refuses_an_unknown_code() -> None: + with pytest.raises(ValueError, match="A_MARITL codes 1-7"): + us_marital_status_inputs(np.asarray([1.0, 8.0])) + with pytest.raises(ValueError, match="A_MARITL codes 1-7"): + us_marital_status_inputs(np.asarray([np.nan])) + + +def test_the_donor_stage_still_derives_its_occupation_flags_from_the_shared_rule(): + occupation = [0, 8, 41, 52, 53, 1, 50, 20] + person = pd.DataFrame( + { + "PRDTRACE": 1, + "PRDTHSP": 0, + "POCCU2": occupation, + "WEIND": 23, + "WEMIND": 15, + "WKSWORK": 0, + } + ) + derived = derive_us_org_occupation_inputs(person) + shared = us_flsa_occupation_flags(pd.Series(occupation)) + assert list(shared.columns) == [ + "has_never_worked", + "is_military", + "is_computer_scientist", + "is_farmer_fisher", + "is_executive_administrative_professional", + ] + for column in shared.columns: + np.testing.assert_array_equal(derived[column], shared[column]) + assert shared["is_computer_scientist"].tolist() == [0, 1, 0, 0, 0, 0, 0, 0] + assert shared["is_farmer_fisher"].tolist() == [0, 0, 1, 0, 0, 0, 0, 0] + assert shared["is_military"].tolist() == [0, 0, 0, 1, 0, 0, 0, 0] + assert shared["has_never_worked"].tolist() == [0, 0, 0, 0, 1, 0, 0, 0] + assert shared["is_executive_administrative_professional"].tolist() == [ + code in FLSA_EXECUTIVE_ADMINISTRATIVE_PROFESSIONAL_OCCUPATION_CODES + for code in occupation + ] + + +# --------------------------------------------------------------------------- +# The ACS mapping +# --------------------------------------------------------------------------- + + +def _acs_frame(**overrides) -> Frame: + """Eight ACS persons in four households, with the stage's source columns.""" + + person = pd.DataFrame( + { + "person_id": np.arange(1, 9), + "person_household_id": [1, 1, 2, 2, 3, 3, 4, 4], + "person_tax_unit_id": [1, 1, 2, 2, 3, 3, 4, 4], + "person_spm_unit_id": [1, 1, 2, 2, 3, 3, 4, 4], + "person_family_id": [1, 1, 2, 2, 3, 3, 4, 4], + "person_marital_unit_id": [1, 1, 2, 2, 3, 3, 4, 4], + "AGEP": [30, 28, 45, 10, 70, 40, 22, 16], + # A_MARITL: separated, married, widowed, never married (a child), + # widowed, separated, never married, never married. + "A_MARITL": [6, 1, 4, 7, 4, 6, 7, 7], + # MIL: on active duty, never, past duty (a veteran), blank under + # 17, never, active duty, reserves only, blank under 17 (at 16). + "ACS_MIL": [1, 4, 2, np.nan, 4, 1, 3, np.nan], + "ESR": [4, 1, 1, np.nan, 6, 6, 1, 6], + # POCCU2: military, an EAP code, computer, 0 under 16, never + # worked, military (a recent veteran: off duty, no job), farm, 53. + "detailed_occupation_recode": [52, 1, 8, 0, 53, 52, 41, 53], + **overrides, + } + ) + households = [1, 2, 3, 4] + return Frame( + { + "person": person, + "household": pd.DataFrame({"household_id": households}), + "tax_unit": pd.DataFrame({"tax_unit_id": households}), + "spm_unit": pd.DataFrame({"spm_unit_id": households}), + "family": pd.DataFrame({"family_id": households}), + "marital_unit": pd.DataFrame({"marital_unit_id": households}), + }, + US_SCHEMA, + {"household": Weights(np.asarray([10.0, 20.0, 30.0, 40.0]), WeightKind.DESIGN)}, + pd.Series(ACS_2024_1YR_SPINE, index=person.index, dtype=object), + ) + + +def test_the_acs_rows_get_every_status_column_under_its_rule() -> None: + frame = _acs_frame() + result = map_acs_local_status_inputs(frame) + person = result.frame.table("person") + + assert person["is_separated"].tolist() == [1, 0, 0, 0, 0, 1, 0, 0] + assert person["is_surviving_spouse"].tolist() == [0, 0, 1, 0, 1, 0, 0, 0] + # MIL == 1 only; a veteran, a reservist and a blank under 17 are not. + assert person["is_military"].tolist() == [1, 0, 0, 0, 0, 1, 0, 0] + assert person["has_never_worked"].tolist() == [0, 0, 0, 0, 1, 0, 0, 1] + assert person["is_computer_scientist"].tolist() == [0, 0, 1, 0, 0, 0, 0, 0] + assert person["is_farmer_fisher"].tolist() == [0, 0, 0, 0, 0, 0, 1, 0] + assert person["is_executive_administrative_professional"].tolist() == [ + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + ] + for column in ACS_LOCAL_STATUS_INPUTS_COLUMNS: + assert person[column].dtype == bool, column + # The input frame is not modified. + assert "is_military" not in frame.table("person") + + receipt = result.receipt + assert receipt["issue"] == ACS_LOCAL_STATUS_INPUTS_ISSUE == "microcosm#1720" + assert receipt["method"] == ACS_LOCAL_STATUS_INPUTS_METHOD + assert receipt["acs_persons"] == 8 + assert set(receipt["columns"]) == set(ACS_LOCAL_STATUS_INPUTS_COLUMNS) + military = receipt["columns"]["is_military"] + assert military["filled_rows"] == 8 + assert military["preserved_rows"] == 0 + assert military["true_rows"] == 2 + # Household weights 10 and 30 carry the two active-duty persons. + assert military["weighted_true_share"] == pytest.approx(40.0 / 200.0) + assert military["donor_rule"] == "org_wages: POCCU2 == 52" + assert receipt["a_maritl_rows"] == {"1": 1, "4": 2, "6": 2, "7": 3} + assert receipt["military"]["mil_code_rows"] == { + "1": 2, + "2": 1, + "3": 1, + "4": 2, + "blank": 2, + } + assert receipt["military"]["blank_rows_age_17_plus"] == 0 + assert receipt["military"]["coded_rows_under_17"] == 0 + agreement = receipt["military"]["agreement"] + # Both active-duty persons hold a military occupation (POCCU2 52), the + # donor's rule; only one of them is ESR 4 (Armed Forces, at work). + assert agreement["donor_rule_poccu2_52"] == { + "both_rows": 2, + "mil_only_rows": 0, + "other_only_rows": 0, + "other_weighted_true_share": pytest.approx(40.0 / 200.0), + } + assert agreement["esr_armed_forces_4_or_5"] == { + "both_rows": 1, + "mil_only_rows": 1, + "other_only_rows": 0, + "other_weighted_true_share": pytest.approx(10.0 / 200.0), + } + json.dumps(receipt, allow_nan=False) + + assert set(result.native_inputs) == set(ACS_LOCAL_STATUS_INPUTS_COLUMNS) + for entry in result.native_inputs.values(): + assert entry["provenance"] == "acs_2024_1yr_native" + assert entry["missing_rows"] == 0 + assert entry["observed_rows"] == 8 + + +def test_the_recent_veteran_is_military_only_under_the_donor_occupation_rule(): + """Person 6 is off duty with no job (ESR 6) and a military last job.""" + + result = map_acs_local_status_inputs( + _acs_frame(ACS_MIL=[1, 4, 2, np.nan, 4, 2, 3, np.nan]) + ) + agreement = result.receipt["military"]["agreement"]["donor_rule_poccu2_52"] + assert agreement == { + "both_rows": 1, + "mil_only_rows": 0, + "other_only_rows": 1, + "other_weighted_true_share": pytest.approx(40.0 / 200.0), + } + assert result.frame.table("person")["is_military"].tolist() == [1] + [0] * 7 + + +def test_stored_acs_values_stand_and_only_missing_cells_are_filled() -> None: + stored = pd.Series([True, np.nan, np.nan, np.nan, np.nan, False, np.nan, np.nan]) + result = map_acs_local_status_inputs(_acs_frame(is_separated=stored)) + person = result.frame.table("person") + # Row 6's stored False stands against A_MARITL 6; row 1's stored True too. + assert person["is_separated"].tolist() == [1, 0, 0, 0, 0, 0, 0, 0] + entry = result.receipt["columns"]["is_separated"] + assert (entry["filled_rows"], entry["preserved_rows"]) == (6, 2) + + +@pytest.mark.parametrize( + ("overrides", "match"), + [ + ({"ACS_MIL": [1, 4, 2, np.nan, 4, 1, 5, np.nan]}, r"MIL requires blank"), + ({"A_MARITL": [6, 1, 4, 7, 4, 6, 7, 0]}, "A_MARITL codes 1-7"), + ({"ESR": [4, 1, 1, np.nan, 6, 6, 1, 9]}, r"ESR requires blank"), + ({"is_military": [True, 2, 0, 0, 0, 0, 0, 0]}, "must be boolean"), + ], +) +def test_malformed_sources_are_refused(overrides, match) -> None: + with pytest.raises(ValueError, match=match): + map_acs_local_status_inputs(_acs_frame(**overrides)) + + +@pytest.mark.parametrize( + "column", ["A_MARITL", "ACS_MIL", "detailed_occupation_recode", "ESR", "AGEP"] +) +def test_a_missing_source_column_is_refused(column) -> None: + frame = _acs_frame() + tables = {entity: frame.table(entity) for entity in frame.entities} + tables["person"] = tables["person"].drop(columns=[column]) + reduced = Frame( + tables, + US_SCHEMA, + {"household": frame.weights_for("household")}, + frame.strata, + ) + with pytest.raises(ValueError, match=r"microcosm#1720"): + map_acs_local_status_inputs(reduced) + + +# --------------------------------------------------------------------------- +# The multispine seam +# --------------------------------------------------------------------------- + + +def _donor() -> Frame: + person = pd.DataFrame( + { + "person_id": [1, 2, 3, 4], + "person_household_id": [1, 1, 2, 2], + "person_tax_unit_id": [1, 1, 2, 2], + "person_spm_unit_id": [1, 1, 2, 2], + "person_family_id": [1, 1, 2, 2], + "person_marital_unit_id": [1, 1, 2, 2], + "age": [42.0, 38.0, 65.0, 12.0], + "is_female": [False, True, True, False], + "qualified_dividend_income": [100.0, 20.0, 2_000.0, 0.0], + **{ + column: [True, False, False, False] + for column in ACS_LOCAL_STATUS_INPUTS_COLUMNS + }, + } + ) + return Frame( + { + "person": person, + "household": pd.DataFrame({"household_id": [1, 2], "state_fips": [6, 36]}), + "tax_unit": pd.DataFrame({"tax_unit_id": [1, 2]}), + "spm_unit": pd.DataFrame({"spm_unit_id": [1, 2]}), + "family": pd.DataFrame({"family_id": [1, 2]}), + "marital_unit": pd.DataFrame({"marital_unit_id": [1, 2]}), + }, + US_SCHEMA, + {"household": Weights(np.asarray([100.0, 300.0]), WeightKind.DESIGN)}, + pd.Series("asec_puf", index=person.index, dtype=object), + ) + + +def _raw_acs() -> Frame: + person = pd.DataFrame( + { + "person_id": [10, 11], + "person_household_id": [10, 10], + "person_tax_unit_id": [10, 10], + "person_spm_unit_id": [10, 10], + "person_family_id": [10, 10], + "person_marital_unit_id": [10, 10], + "AGEP": [40, 15], + "SEX": [1, 2], + "RELSHIPP": [20, 25], + "ADJINC": [1_100_000, 1_100_000], + "WAGP": [50_000.0, 0.0], + "SEMP": [0.0, np.nan], + "SSP": [0.0, 0.0], + "SSIP": [0.0, 0.0], + "RETP": [0.0, 0.0], + "INTP": [100.0, 0.0], + "A_MARITL": [6, 7], + "ACS_MIL": [1, np.nan], + "ESR": [4, np.nan], + "detailed_occupation_recode": [52, 0], + } + ) + return Frame( + { + "person": person, + "household": pd.DataFrame( + { + "household_id": [10], + "state_fips": [6], + "puma": ["0600100"], + "ADJHSG": [1_000_000], + "TEN": [3], + "RNTP": [1_000.0], + "GRNTP": [1_200.0], + "TAXAMT": [np.nan], + } + ), + "tax_unit": pd.DataFrame({"tax_unit_id": [10]}), + "spm_unit": pd.DataFrame({"spm_unit_id": [10]}), + "family": pd.DataFrame({"family_id": [10]}), + "marital_unit": pd.DataFrame({"marital_unit_id": [10]}), + }, + US_SCHEMA, + {"household": Weights(np.asarray([50.0]), WeightKind.DESIGN)}, + pd.Series(ACS_2024_1YR_SPINE, index=person.index, dtype=object), + ) + + +def _run(monkeypatch, tmp_path, *, status_inputs: bool): + monkeypatch.setattr( + acs_multispine, + "build_acs_pums_unit_frame", + lambda source, *, chunksize: (_raw_acs(), {"spine": ACS_2024_1YR_SPINE}), + ) + return acs_multispine.build_optional_acs_multispine( + _donor(), + AcsPumsSource(tmp_path / "csv_hus.zip", tmp_path / "csv_pus.zip"), + acs_share=0.25, + target_families={"person": {"tax_detail": ("qualified_dividend_income",)}}, + status_inputs=status_inputs, + seed=4, + n_estimators=2, + ) + + +def test_the_seam_maps_the_acs_rows_before_the_transfer_and_keeps_the_donor( + monkeypatch, tmp_path +) -> None: + with_stage = _run(monkeypatch, tmp_path, status_inputs=True) + without_stage = _run(monkeypatch, tmp_path, status_inputs=False) + + person = with_stage.frame.table("person") + acs = person.loc[person[TAG].eq(ACS_2024_1YR_SPINE)].reset_index(drop=True) + donor = person.loc[~person[TAG].eq(ACS_2024_1YR_SPINE)].reset_index(drop=True) + assert acs["is_separated"].tolist() == [True, False] + assert acs["is_military"].tolist() == [True, False] + for column in ACS_LOCAL_STATUS_INPUTS_COLUMNS: + assert acs[column].notna().all(), column + # The donor rows keep the donor's own values. + assert donor[column].tolist() == [True, False, False, False], column + for column in ACS_LOCAL_OCCUPATION_FLAG_COLUMNS: + assert not acs[column].any(), column + receipt = with_stage.provenance["acs_local_status_inputs"] + assert receipt["acs_persons"] == 2 + assert set(ACS_LOCAL_STATUS_INPUTS_COLUMNS) <= set( + with_stage.provenance["native_inputs"] + ) + json.dumps(with_stage.provenance, allow_nan=False) + + # Without the flag (the pool lane) nothing is mapped and nothing else moves. + assert "acs_local_status_inputs" not in without_stage.provenance + other = without_stage.frame.table("person") + other_acs = other.loc[other[TAG].eq(ACS_2024_1YR_SPINE)] + for column in ACS_LOCAL_STATUS_INPUTS_COLUMNS: + assert other_acs[column].isna().all(), column + pd.testing.assert_frame_equal( + person.drop(columns=list(ACS_LOCAL_STATUS_INPUTS_COLUMNS)), + other.drop(columns=list(ACS_LOCAL_STATUS_INPUTS_COLUMNS)), + check_dtype=False, + check_like=True, + ) + assert ( + with_stage.provenance["imputed_inputs"] + == without_stage.provenance["imputed_inputs"] + ) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_voluntary_filing.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_voluntary_filing.py new file mode 100644 index 0000000000..c58f09333f --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_voluntary_filing.py @@ -0,0 +1,244 @@ +"""ACS local lane: voluntary filing of ACS tax units (microcosm#1720).""" + +from __future__ import annotations + +import json +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build.us_runtime import acs_local_voluntary_filing +from microcosm.build.us_runtime.acs_local_voluntary_filing import ( + ACS_LOCAL_VOLUNTARY_FILING_COLUMN, + ACS_LOCAL_VOLUNTARY_FILING_ISSUE, + ACS_LOCAL_VOLUNTARY_FILING_METHOD, + load_acs_local_voluntary_filing_donor, + with_acs_local_voluntary_filing, +) +from microcosm.build.us_runtime.acs_pums import ACS_2024_1YR_SPINE +from microcosm.build.us_runtime.acs_transfer import ASEC_PUF_DONOR_SPINE +from microcosm.build.us_runtime.base_pool import spine_column +from microcosm.build.us_runtime.voluntary_filing import ( + SIPP_2023_VOLUNTARY_FILING_DONOR_SHA256, + SIPP_2023_VOLUNTARY_FILING_DONOR_SIZE_BYTES, + impute_us_voluntary_filing, + impute_us_voluntary_filing_from_tables, +) +from microcosm.frame import US_SCHEMA, Frame +from test_support.microcosm_build.us_voluntary_filing import _donor, _frame + +_OUTPUT = ACS_LOCAL_VOLUNTARY_FILING_COLUMN +_SEED = 31 +_TREES = 8 + + +def test_the_table_entry_point_is_the_donors_imputation() -> None: + """The donor function now reads its two tables through + impute_us_voluntary_filing_from_tables; the donor's values are unchanged.""" + + frame = _frame(14) + donor = _donor(120) + from_frame = impute_us_voluntary_filing( + frame, donor, seed=_SEED, n_estimators=_TREES + ) + from_tables = impute_us_voluntary_filing_from_tables( + frame.table("person"), + frame.table("tax_unit"), + donor, + seed=_SEED, + n_estimators=_TREES, + ) + pd.testing.assert_series_equal(from_frame, from_tables) + + +def _pooled(*, acs_stored: dict[int, object] | None = None) -> Frame: + """Households 1-6 are donor rows with stored values, 7-12 ACS rows.""" + + frame = _frame(12) + tables = {entity: frame.table(entity).copy() for entity in frame.entities} + person = tables["person"] + tax_unit = tables["tax_unit"] + person[spine_column("person")] = np.where( + person["person_household_id"] <= 6, ASEC_PUF_DONOR_SPINE, ACS_2024_1YR_SPINE + ) + acs_unit = tax_unit["tax_unit_id"] > 106 + tax_unit[spine_column("tax_unit")] = np.where( + acs_unit, ACS_2024_1YR_SPINE, ASEC_PUF_DONOR_SPINE + ) + values = pd.Series( + [True, False, True, False, True, False] + [np.nan] * 6, dtype=object + ) + for unit_id, value in (acs_stored or {}).items(): + values.iloc[int(np.flatnonzero(tax_unit["tax_unit_id"] == unit_id)[0])] = value + tax_unit[_OUTPUT] = values + return Frame( + tables, + US_SCHEMA, + {"household": frame.weights_for("household")}, + ) + + +def _acs_only(frame: Frame) -> Frame: + """The ACS rows as their own frame, without origin tags.""" + + tables = {} + for entity in frame.entities: + table = frame.table(entity) + tag = spine_column(entity) + if tag in table: + table = table.loc[table[tag].eq(ACS_2024_1YR_SPINE)].drop(columns=[tag]) + elif entity == "household": + table = table.loc[table["household_id"] > 6] + else: + ids = table[f"{entity}_id"] + table = table.loc[ids % 100 > 6] + tables[entity] = table.reset_index(drop=True) + return Frame( + tables, + US_SCHEMA, + { + "household": frame.weights_for("household").__class__( + frame.weights_for("household").values[6:], + frame.weights_for("household").kind, + ) + }, + ) + + +def test_the_acs_units_get_the_donors_model_and_the_donor_units_stand() -> None: + frame = _pooled() + donor = _donor(120) + result, receipt = with_acs_local_voluntary_filing( + frame, + sipp_donor=donor, + seed=_SEED, + donor_identity={"sha256": "5" * 64}, + n_estimators=_TREES, + ) + after = result.table("tax_unit") + assert after[_OUTPUT].dtype == bool + assert after[_OUTPUT].iloc[:6].tolist() == [True, False, True, False, True, False] + # The ACS fill is exactly the donor function on the ACS rows alone. + expected = impute_us_voluntary_filing( + _acs_only(frame), donor, seed=_SEED, n_estimators=_TREES + ) + assert after[_OUTPUT].iloc[6:].tolist() == expected.tolist() + + assert receipt["issue"] == ACS_LOCAL_VOLUNTARY_FILING_ISSUE == "microcosm#1720" + assert receipt["method"] == ACS_LOCAL_VOLUNTARY_FILING_METHOD + assert receipt["column"] == _OUTPUT + assert receipt["acs_tax_units"] == 6 + assert receipt["filled_units"] == 6 + assert receipt["preserved_acs_units"] == 0 + assert receipt["unfilled_acs_units"] == 0 + assert receipt["model"]["fitted"] is True + assert receipt["model"]["n_estimators"] == _TREES + assert receipt["model"]["training_units"] == 120 + assert receipt["sipp_donor"]["sha256"] == "5" * 64 + assert receipt["outcome"]["acs_true_units"] == int(expected.sum()) + assert 0.0 <= receipt["outcome"]["acs_weighted_true_share"] <= 1.0 + donor_weights = np.linspace(1.0, 2.0, 12)[:6] + assert receipt["outcome"]["donor_weighted_true_share"] == pytest.approx( + donor_weights[[0, 2, 4]].sum() / donor_weights.sum() + ) + json.dumps(receipt, allow_nan=False) + + +def test_stored_acs_values_stand_and_a_complete_column_is_untouched() -> None: + frame = _pooled(acs_stored={107: True}) + result, receipt = with_acs_local_voluntary_filing( + frame, sipp_donor=_donor(120), seed=_SEED, n_estimators=_TREES + ) + assert result.table("tax_unit")[_OUTPUT].iloc[6] == True # noqa: E712 + assert receipt["filled_units"] == 5 + assert receipt["preserved_acs_units"] == 1 + + complete = _pooled(acs_stored={unit: False for unit in range(107, 113)}) + same, receipt = with_acs_local_voluntary_filing( + complete, sipp_donor=_donor(120), seed=_SEED, n_estimators=_TREES + ) + assert same is complete + assert receipt["model"]["fitted"] is False + assert receipt["filled_units"] == 0 + + +def test_a_wage_blank_from_15_and_missing_inputs_are_refused() -> None: + frame = _pooled() + tables = {entity: frame.table(entity).copy() for entity in frame.entities} + person = tables["person"] + acs_adult = person.index[ + person[spine_column("person")].eq(ACS_2024_1YR_SPINE) & person["age"].ge(15) + ][0] + person.loc[acs_adult, "employment_income_before_lsr"] = np.nan + blanked = Frame(tables, US_SCHEMA, {"household": frame.weights_for("household")}) + with pytest.raises(ValueError, match=r"aged 15\+ have a blank"): + with_acs_local_voluntary_filing(blanked, sipp_donor=_donor(), seed=_SEED) + + # A blank under 15 reads as no wages. + tables = {entity: frame.table(entity).copy() for entity in frame.entities} + person = tables["person"] + acs_child = person.index[ + person[spine_column("person")].eq(ACS_2024_1YR_SPINE) & person["age"].lt(15) + ][0] + person.loc[acs_child, "employment_income_before_lsr"] = np.nan + _, receipt = with_acs_local_voluntary_filing( + Frame(tables, US_SCHEMA, {"household": frame.weights_for("household")}), + sipp_donor=_donor(120), + seed=_SEED, + n_estimators=_TREES, + ) + assert receipt["predictor_view"]["wage_blank_under_15_rows"] == 1 + + tables = {entity: frame.table(entity).copy() for entity in frame.entities} + tables["tax_unit"] = tables["tax_unit"].drop(columns=["filing_status_input"]) + with pytest.raises(ValueError, match="filing_status_input"): + with_acs_local_voluntary_filing( + Frame(tables, US_SCHEMA, {"household": frame.weights_for("household")}), + sipp_donor=_donor(), + seed=_SEED, + ) + + +def test_origin_tags_and_the_donor_column_are_required() -> None: + frame = _pooled() + tables = {entity: frame.table(entity).copy() for entity in frame.entities} + tables["tax_unit"] = tables["tax_unit"].drop(columns=[spine_column("tax_unit")]) + with pytest.raises(ValueError, match="origin tags"): + with_acs_local_voluntary_filing( + Frame(tables, US_SCHEMA, {"household": frame.weights_for("household")}), + sipp_donor=_donor(), + seed=_SEED, + ) + tables = {entity: frame.table(entity).copy() for entity in frame.entities} + tables["tax_unit"] = tables["tax_unit"].drop(columns=[_OUTPUT]) + with pytest.raises(ValueError, match="donor release carries it"): + with_acs_local_voluntary_filing( + Frame(tables, US_SCHEMA, {"household": frame.weights_for("household")}), + sipp_donor=_donor(), + seed=_SEED, + ) + + +def test_the_loader_verifies_the_pinned_file_it_is_given(monkeypatch, tmp_path) -> None: + calls: dict[str, object] = {} + + def fake_load(path, **kwargs): + calls["path"] = path + calls.update(kwargs) + return _donor(4) + + monkeypatch.setattr( + acs_local_voluntary_filing, "load_sipp_2023_voluntary_filing_donor", fake_load + ) + source = tmp_path / "pu2023.csv" + donor, identity = load_acs_local_voluntary_filing_donor(source) + assert len(donor) == 4 + assert calls == { + "path": Path(source), + "expected_sha256": SIPP_2023_VOLUNTARY_FILING_DONOR_SHA256, + "expected_size_bytes": SIPP_2023_VOLUNTARY_FILING_DONOR_SIZE_BYTES, + } + assert identity["path"] == str(source.resolve()) + assert identity["sha256"] == SIPP_2023_VOLUNTARY_FILING_DONOR_SHA256 diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_weeks_deferrals.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_weeks_deferrals.py new file mode 100644 index 0000000000..8bafbfe5a3 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_weeks_deferrals.py @@ -0,0 +1,455 @@ +"""ACS local lane: weeks unemployed and retirement deferrals (microcosm#1720).""" + +from __future__ import annotations + +import json +from typing import Any + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build.us_runtime import acs_local_weeks_deferrals, acs_multispine +from microcosm.build.us_runtime.acs_local_income import ( + ACS_LOCAL_INCOME_TRANSFER_COLUMNS, +) +from microcosm.build.us_runtime.acs_local_weeks_deferrals import ( + ACS_LOCAL_RETIREMENT_DEFERRAL_COLUMNS, + ACS_LOCAL_RETIREMENT_DEFERRAL_FAMILY, + ACS_LOCAL_UNEMPLOYMENT_COMPENSATION_FEATURE, + ACS_LOCAL_WEEKS_DEFERRALS_COLUMNS, + ACS_LOCAL_WEEKS_DEFERRALS_DONOR_CHANNEL, + ACS_LOCAL_WEEKS_DEFERRALS_ISSUE, + ACS_LOCAL_WEEKS_DEFERRALS_METHOD, + ACS_LOCAL_WEEKS_UNEMPLOYED_FAMILY, + acs_local_weeks_deferrals_target_families, + require_acs_local_weeks_deferrals_donor, +) +from microcosm.build.us_runtime.acs_pums import ACS_2024_1YR_SPINE, AcsPumsSource +from microcosm.build.us_runtime.acs_transfer import ( + ASEC_PUF_DONOR_SPINE, + required_acs_transfer_inputs, +) +from microcosm.build.us_runtime.base_pool import spine_column +from microcosm.build.us_runtime.retirement_contributions import ( + US_RETIREMENT_CONTRIBUTION_OUTPUT_COLUMNS, + postprocess_us_retirement_contribution_predictions, +) +from microcosm.build.us_runtime.support_provenance import ( + support_channel_column, + support_clone_index_column, + support_source_id_column, +) +from microcosm.build.us_runtime.weeks_unemployed import ( + postprocess_us_weeks_unemployed_predictions, +) +from microcosm.frame import US_SCHEMA, Frame, WeightKind, Weights + +TAG = spine_column("person") +_WEEKS = "weeks_unemployed" +_UC = "unemployment_compensation" +_TRADITIONAL_401K, _ROTH_401K, _ROTH_IRA = ACS_LOCAL_RETIREMENT_DEFERRAL_COLUMNS +#: The PUF clone role's values sit outside the ASEC role's support, so a fit on +#: the wrong role cannot go unnoticed. +_PUF_WEEKS = 52.0 +_PUF_AMOUNT = 5_000_000.0 + + +# --------------------------------------------------------------------------- +# The plan and the donor's own post-processing +# --------------------------------------------------------------------------- + + +def test_the_plan_is_person_only_and_disjoint_from_every_other_transfer() -> None: + plan = acs_local_weeks_deferrals_target_families() + assert plan == { + "person": { + ACS_LOCAL_WEEKS_UNEMPLOYED_FAMILY: (_WEEKS,), + ACS_LOCAL_RETIREMENT_DEFERRAL_FAMILY: ACS_LOCAL_RETIREMENT_DEFERRAL_COLUMNS, + } + } + columns = set(ACS_LOCAL_WEEKS_DEFERRALS_COLUMNS) + assert not columns & required_acs_transfer_inputs() + assert not columns & set(ACS_LOCAL_INCOME_TRANSFER_COLUMNS) + # The shared plan draws the other two contribution leaves. + others = set(US_RETIREMENT_CONTRIBUTION_OUTPUT_COLUMNS) - columns + assert others == { + "traditional_ira_contributions_desired", + "self_employed_pension_contributions_desired", + } + assert others <= required_acs_transfer_inputs() + + +def test_the_plan_refuses_an_overlap_with_the_shared_plan(monkeypatch) -> None: + monkeypatch.setattr( + acs_local_weeks_deferrals, + "ACS_LOCAL_WEEKS_DEFERRALS_COLUMNS", + (*ACS_LOCAL_WEEKS_DEFERRALS_COLUMNS, "traditional_ira_contributions_desired"), + ) + with pytest.raises(ValueError, match="double counting"): + acs_local_weeks_deferrals_target_families() + + +def test_the_weeks_post_processing_is_the_archived_rule() -> None: + predicted = np.asarray([-3.0, 4.4, 4.6, 60.0, 12.0]) + uc = np.asarray([100.0, 100.0, 100.0, 100.0, 0.0]) + assert postprocess_us_weeks_unemployed_predictions( + predicted, unemployment_compensation=uc + ).tolist() == [0.0, 4.0, 5.0, 52.0, 0.0] + assert postprocess_us_weeks_unemployed_predictions( + predicted, unemployment_compensation=None, clip=(0, 10) + ).tolist() == [0.0, 4.0, 5.0, 10.0, 10.0] + + +def test_the_deferral_post_processing_is_the_archived_rule() -> None: + predictions = pd.DataFrame( + { + _TRADITIONAL_401K: [100.0, 200.0, -5.0], + _ROTH_401K: [10.0, 20.0, 30.0], + _ROTH_IRA: [1.0, -2.0, 3.0], + } + ) + result = postprocess_us_retirement_contribution_predictions( + predictions, employment_income=np.asarray([0.0, 5.0, 5.0]) + ) + assert result[_TRADITIONAL_401K].tolist() == [0.0, 200.0, 0.0] + assert result[_ROTH_401K].tolist() == [0.0, 20.0, 30.0] + # The Roth IRA has no earnings gate in the donor's rule; it is clipped. + assert result[_ROTH_IRA].tolist() == [1.0, 0.0, 3.0] + pension = predictions.assign(self_employed_pension_contributions_desired=[5.0] * 3) + with pytest.raises(ValueError, match="self_employment_income"): + postprocess_us_retirement_contribution_predictions( + pension, employment_income=np.ones(3) + ) + gated = postprocess_us_retirement_contribution_predictions( + pension, + employment_income=np.ones(3), + self_employment_income=np.asarray([0.0, 1.0, 0.0]), + ) + assert gated["self_employed_pension_contributions_desired"].tolist() == [ + 0.0, + 5.0, + 0.0, + ] + + +# --------------------------------------------------------------------------- +# A real fit through the multispine seam +# --------------------------------------------------------------------------- + + +def _support_donor(n_asec: int = 60) -> Frame: + """An ASEC-by-PUF donor: an ASEC observation role and its PUF clones. + + Every person is a household. On the ASEC role a third receive UC, weeks + are 1-40 for most of them (and positive for two non-recipients looking + for work), and the deferrals follow the archived split: 401(k) only with + wages. Each PUF clone repeats its source person's demographics, wages and + UC with out-of-support weeks and deferrals. + """ + + rng = np.random.default_rng(1720) + n = 2 * n_asec + ids = np.arange(1, n + 1) + roles = np.asarray(["asec"] * n_asec + ["puf_tax_detail"] * n_asec, dtype=object) + wages = np.where(rng.random(n_asec) < 0.7, rng.integers(5_000, 90_000, n_asec), 0) + uc = np.where(rng.random(n_asec) < 0.35, rng.integers(500, 9_000, n_asec), 0) + weeks = np.where(uc > 0, rng.integers(1, 41, n_asec), 0).astype(float) + weeks[np.flatnonzero(uc == 0)[:2]] = 6.0 + contributing = (wages > 0) & (rng.random(n_asec) < 0.6) + traditional = np.where(contributing, rng.integers(500, 9_000, n_asec), 0) + roth_ira = np.where(rng.random(n_asec) < 0.2, rng.integers(200, 6_000, n_asec), 0) + person = pd.DataFrame( + { + "person_id": ids, + "age": np.tile(rng.integers(18, 80, n_asec), 2).astype(float), + "is_female": np.tile(rng.integers(0, 2, n_asec).astype(bool), 2), + "employment_income_before_lsr": np.tile(wages.astype(float), 2), + _UC: np.tile(uc.astype(float), 2), + _WEEKS: np.concatenate([weeks, np.where(uc > 0, _PUF_WEEKS, 0.0)]), + _TRADITIONAL_401K: np.concatenate( + [traditional.astype(float), np.where(wages > 0, _PUF_AMOUNT, 0.0)] + ), + _ROTH_401K: np.concatenate( + [0.1 * traditional, np.where(wages > 0, _PUF_AMOUNT + 1, 0.0)] + ), + _ROTH_IRA: np.concatenate( + [roth_ira.astype(float), np.full(n_asec, _PUF_AMOUNT + 2)] + ), + } + ) + for entity in US_SCHEMA.entities: + if entity != "person": + person[f"person_{entity}_id"] = ids + tables = {"person": person} + for entity in US_SCHEMA.entities: + if entity != "person": + tables[entity] = pd.DataFrame({f"{entity}_id": ids}) + tables["household"]["state_fips"] = np.resize([6, 36, 48], n) + for entity, table in tables.items(): + table[support_channel_column(entity)] = roles + table[support_source_id_column(entity)] = np.tile(np.arange(1, n_asec + 1), 2) + table[support_clone_index_column(entity)] = (roles == "puf_tax_detail").astype( + int + ) + return Frame( + tables, + US_SCHEMA, + {"household": Weights(np.full(n, 100.0), WeightKind.DESIGN)}, + pd.Series(ASEC_PUF_DONOR_SPINE, index=person.index, dtype=object), + ) + + +def _raw_acs(n: int = 24, children: int = 2) -> Frame: + """A raw ACS PUMS spine of two-person households; the last ``children`` + persons are 10, with WAGP blank.""" + + rng = np.random.default_rng(2024) + households = 500 + np.arange(n) // 2 + person = pd.DataFrame( + { + "person_id": np.arange(500, 500 + n), + "person_household_id": households, + "person_tax_unit_id": households, + "person_spm_unit_id": households, + "person_family_id": households, + "person_marital_unit_id": households, + "AGEP": rng.integers(18, 85, n), + "SEX": rng.integers(1, 3, n), + "RELSHIPP": np.resize([20, 21], n), + "ADJINC": 1_000_000, + "WAGP": np.where( + rng.random(n) < 0.7, rng.integers(5_000, 90_000, n), 0 + ).astype(float), + "SEMP": 0.0, + "SSP": 0.0, + "SSIP": 0.0, + "RETP": 0.0, + "INTP": 0.0, + } + ) + person.loc[n - children :, "AGEP"] = 10 + person.loc[n - children :, ["WAGP", "SEMP"]] = np.nan + unique = np.unique(households) + return Frame( + { + "person": person, + "household": pd.DataFrame( + { + "household_id": unique, + "state_fips": np.resize([6, 36, 48], len(unique)), + "puma": "0600100", + "ADJHSG": 1_000_000, + "TEN": 3, + "RNTP": 1_000.0, + "GRNTP": 1_200.0, + "TAXAMT": np.nan, + } + ), + "tax_unit": pd.DataFrame({"tax_unit_id": unique}), + "spm_unit": pd.DataFrame({"spm_unit_id": unique}), + "family": pd.DataFrame({"family_id": unique}), + "marital_unit": pd.DataFrame({"marital_unit_id": unique}), + }, + US_SCHEMA, + {"household": Weights(np.full(len(unique), 50.0), WeightKind.DESIGN)}, + pd.Series(ACS_2024_1YR_SPINE, index=person.index, dtype=object), + ) + + +def _multispine(monkeypatch, tmp_path, *, weeks_deferrals: bool, calls: list): + """The local lane's seam with the real QRF; only the loader is replaced. + + The shared plan transfers ``unemployment_compensation`` (on the PUF role, + as the declared plan does), which the weeks family then reads. + """ + + real_transfer = acs_local_weeks_deferrals.transfer_acs_inputs + + def recorded(recipient, donor, **kwargs): + calls.append(kwargs) + return real_transfer(recipient, donor, **kwargs) + + monkeypatch.setattr( + acs_multispine, "build_acs_pums_unit_frame", lambda *_a, **_k: (_raw_acs(), {}) + ) + monkeypatch.setattr(acs_local_weeks_deferrals, "transfer_acs_inputs", recorded) + shared_transfer = acs_multispine.transfer_acs_inputs + + def shared_recorded(recipient, donor, **kwargs): + calls.append(kwargs) + return shared_transfer(recipient, donor, **kwargs) + + monkeypatch.setattr(acs_multispine, "transfer_acs_inputs", shared_recorded) + try: + return acs_multispine.build_optional_acs_multispine( + _support_donor(), + AcsPumsSource(tmp_path / "csv_hus.zip", tmp_path / "csv_pus.zip"), + target_families={"person": {"shared_uc": (_UC,)}}, + weeks_deferrals=weeks_deferrals, + seed=5, + n_estimators=5, + ) + finally: + monkeypatch.setattr(acs_multispine, "transfer_acs_inputs", shared_transfer) + monkeypatch.setattr( + acs_local_weeks_deferrals, "transfer_acs_inputs", real_transfer + ) + + +def _rows(result, spine: str) -> pd.DataFrame: + person = result.frame.table("person") + return person.loc[person[TAG].eq(spine)].reset_index(drop=True) + + +def test_a_real_fit_fills_the_acs_rows_from_the_asec_role_only( + monkeypatch, tmp_path +) -> None: + donor_before = _support_donor().table("person") + asec = donor_before[support_channel_column("person")].eq("asec") + calls: list = [] + result = _multispine(monkeypatch, tmp_path, weeks_deferrals=True, calls=calls) + acs = _rows(result, ACS_2024_1YR_SPINE) + donor = _rows(result, ASEC_PUF_DONOR_SPINE) + assert len(acs) == 24 + + # Two fits: the shared plan on the PUF role, then this pass on the ASEC + # role with its UC predictor extension. + assert [call["donor_channel"] for call in calls] == [ + "auto", + ACS_LOCAL_WEEKS_DEFERRALS_DONOR_CHANNEL, + ] + assert calls[1]["target_families"] == acs_local_weeks_deferrals_target_families() + assert "person_predictor_extensions" not in calls[0] + + uc = acs[_UC].to_numpy(dtype=np.float64) + weeks = acs[_WEEKS].to_numpy(dtype=np.float64) + assert np.isfinite(weeks).all() + assert ((weeks >= 0) & (weeks <= 52) & (weeks == np.floor(weeks))).all() + # The archived zero rule, and never the PUF clones' 52. + assert (weeks[uc <= 0] == 0).all() + assert (weeks < _PUF_WEEKS).all() + assert (weeks[uc > 0] > 0).any() + wages = acs["employment_income_before_lsr"].fillna(0.0).to_numpy() + for column in ACS_LOCAL_RETIREMENT_DEFERRAL_COLUMNS: + values = acs[column].to_numpy(dtype=np.float64) + assert np.isfinite(values).all(), column + assert (values >= 0).all(), column + assert values.max() <= donor_before.loc[asec, column].max(), column + # The 401(k) deferrals need wages; the children (WAGP blank) have none. + for column in (_TRADITIONAL_401K, _ROTH_401K): + assert (acs[column].to_numpy()[wages == 0] == 0).all(), column + assert (acs[_TRADITIONAL_401K] > 0).any() + assert acs[_TRADITIONAL_401K].iloc[-2:].tolist() == [0.0, 0.0] + + # Donor rows keep the donor release's values. + for column in (*ACS_LOCAL_WEEKS_DEFERRALS_COLUMNS, _UC): + np.testing.assert_array_equal( + donor[column].to_numpy(dtype=np.float64), + donor_before[column].to_numpy(dtype=np.float64), + ) + + imputed = {item["column"]: item for item in result.provenance["imputed_inputs"]} + for column in ACS_LOCAL_WEEKS_DEFERRALS_COLUMNS: + assert imputed[column]["donor_channel"] == "asec", column + used = set(imputed[column]["predictors"]) + assert (ACS_LOCAL_UNEMPLOYMENT_COMPENSATION_FEATURE in used) is ( + column == _WEEKS + ), column + assert imputed[_UC]["donor_channel"] == "puf_tax_detail" + names = [record.fit_name for record in result.fit_records] + assert any(ACS_LOCAL_WEEKS_UNEMPLOYED_FAMILY in name for name in names) + + receipt = result.provenance["acs_local_weeks_deferrals"] + assert receipt["issue"] == ACS_LOCAL_WEEKS_DEFERRALS_ISSUE == "microcosm#1720" + assert receipt["method"] == ACS_LOCAL_WEEKS_DEFERRALS_METHOD + assert receipt["donor_channel"] == receipt["resolved_donor_channel"] == "asec" + assert receipt["donor"]["person_rows"] == 60 + assert receipt["donor"]["weeks_positive_without_uc_rows"] == 2 + assert receipt["acs_persons"] == 24 + assert receipt["acs_uc_recipient_rows"] == int((uc > 0).sum()) + for column in ACS_LOCAL_WEEKS_DEFERRALS_COLUMNS: + entry = receipt["columns"][column] + assert entry["imputed_rows"] == entry["filled_rows"] == 24, column + assert entry["unmodeled_rows"] == 0, column + assert entry["donor_channel"] == ["asec"], column + assert receipt["columns"][_WEEKS]["acs"]["positive_rows"] == int((weeks > 0).sum()) + json.dumps(result.provenance, allow_nan=False) + + +def test_the_pass_leaves_every_earlier_draw_unchanged(monkeypatch, tmp_path) -> None: + """The proof microcosm#1720 asks for: with and without the pass, every + other column of both spines, the earlier provenance and the earlier fits + are identical, because the pass runs after them and its families draw + with seeds of their own.""" + + with_calls: list = [] + without_calls: list = [] + with_pass = _multispine( + monkeypatch, tmp_path, weeks_deferrals=True, calls=with_calls + ) + without_pass = _multispine( + monkeypatch, tmp_path, weeks_deferrals=False, calls=without_calls + ) + assert len(with_calls) == 2 and len(without_calls) == 1 + assert with_calls[0] == without_calls[0] + + new = list(ACS_LOCAL_WEEKS_DEFERRALS_COLUMNS) + with_person = with_pass.frame.table("person") + without_person = without_pass.frame.table("person") + acs = without_person[TAG].eq(ACS_2024_1YR_SPINE) + # Without the pass the ACS rows have no value for the four columns. + assert without_person.loc[acs, new].isna().all().all() + pd.testing.assert_frame_equal( + with_person.drop(columns=new), + without_person.drop(columns=new), + check_like=True, + ) + earlier = [ + item + for item in with_pass.provenance["imputed_inputs"] + if item["column"] not in new + ] + assert earlier == without_pass.provenance["imputed_inputs"] + assert with_pass.fit_records[: len(without_pass.fit_records)] == ( + without_pass.fit_records + ) + assert "acs_local_weeks_deferrals" not in without_pass.provenance + + +# --------------------------------------------------------------------------- +# The donor +# --------------------------------------------------------------------------- + + +def test_a_donor_without_a_column_or_the_asec_role_is_refused() -> None: + donor = _support_donor() + summary = require_acs_local_weeks_deferrals_donor(donor) + assert summary["channel"] == "asec" + assert summary["columns"][_WEEKS]["positive_rows"] > 0 + tables = {entity: donor.table(entity) for entity in donor.entities} + tables["person"] = tables["person"].drop(columns=[_ROTH_IRA]) + reduced = Frame( + tables, US_SCHEMA, {"household": donor.weights_for("household")}, donor.strata + ) + with pytest.raises(ValueError, match="roth_ira_contributions_desired"): + require_acs_local_weeks_deferrals_donor(reduced) + plain: dict[str, Any] = { + entity: donor.table(entity).drop( + columns=[ + support_channel_column(entity), + support_source_id_column(entity), + support_clone_index_column(entity), + ] + ) + for entity in donor.entities + } + with pytest.raises(ValueError, match="ASEC observation role"): + require_acs_local_weeks_deferrals_donor( + Frame( + plain, + US_SCHEMA, + {"household": donor.weights_for("household")}, + donor.strata, + ) + ) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_multispine_legacy_builder.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_multispine_legacy_builder.py index c479b42107..be8ff80d2e 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_multispine_legacy_builder.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_multispine_legacy_builder.py @@ -288,6 +288,13 @@ def test_main_wires_verified_sources_transfer_audit_export_and_summary( # What build_optional_acs_multispine records for the native FS receipt # anchor (microcosm#1022). anchor_receipt = {"issue": "microcosm#1022", "snap": {"units_anchored": 1}} + # What build_optional_acs_multispine records for the ACS rows' native + # marital, military and occupation status (microcosm#1720). + status_receipt = {"issue": "microcosm#1720", "acs_persons": 1} + se_health_receipt = {"issue": "microcosm#1720", "self_employed_rows": 0} + weeks_deferrals_receipt = {"issue": "microcosm#1720", "acs_persons": 1} + group_quarters_receipt = {"issue": "microcosm#975", "group_quarters_spm_units": 1} + coverage_receipt = {"issue": "microcosm#1720", "acs_persons": 1} # What the ACS local SSI disability-criteria stage returns # (microcosm#1022): the null audit, hours gate and export must see it. ssi_filled = Frame( @@ -302,6 +309,10 @@ def test_main_wires_verified_sources_transfer_audit_export_and_summary( sipp_path = tmp_path / "pu2023.csv" sipp_training = pd.DataFrame({"age": [40.0]}) sipp_identity = {"path": str(sipp_path), "sha256": "5" * 64} + # microcosm#1720: the voluntary-filing model reads the same file. + filing_training = pd.DataFrame({"employment_income": [1.0]}) + filing_identity = {"path": str(sipp_path), "sha256": "5" * 64} + filing_receipt = {"issue": "microcosm#1720", "filled_units": 1} base_h5 = tmp_path / "dense.h5" base_h5.write_bytes(b"dense-base") manifest_path = tmp_path / "acs_sources.json" @@ -412,6 +423,11 @@ def fake_build(actual_base, actual_source, **kwargs): "acs_local_work_disability": work_disability_receipt, "acs_local_income_transfer": income_receipt, "acs_local_receipt_anchors": anchor_receipt, + "acs_local_status_inputs": status_receipt, + "acs_local_se_health_premiums": se_health_receipt, + "acs_local_weeks_deferrals": weeks_deferrals_receipt, + "acs_local_group_quarters_housing": group_quarters_receipt, + "acs_local_coverage_anchors": coverage_receipt, "spm_independence_role": _spm_role_receipt(persons=1), }, ) @@ -466,6 +482,19 @@ def fake_ssi_stage(frame, *, sipp_donor, donor_identity, seed): order.append("ssi_disability") return ssi_filled, ssi_receipt + def fake_filing_load(path): + captured["filing_load"] = path + order.append("filing_load") + return filing_training, filing_identity + + def fake_filing_stage(frame, *, sipp_donor, donor_identity, seed): + assert frame is ssi_filled + assert sipp_donor is filing_training + assert donor_identity is filing_identity + captured["filing_seed"] = seed + order.append("voluntary_filing") + return ssi_filled, filing_receipt + def fake_ssi_gate(frame, *, receipt): assert frame is ssi_filled assert receipt is ssi_receipt @@ -618,6 +647,10 @@ def staging_hours_gate(frame, *, source_null_audit): builder, "with_acs_local_ssi_disability_criteria", fake_ssi_stage ) monkeypatch.setattr(builder, "acs_local_ssi_disability_signal_gate", fake_ssi_gate) + monkeypatch.setattr( + builder, "load_acs_local_voluntary_filing_donor", fake_filing_load + ) + monkeypatch.setattr(builder, "with_acs_local_voluntary_filing", fake_filing_stage) # microcosm#454: the ESI employer premium's donor qualifier and gates. def qualify_esi_premium_donor(frame): @@ -758,7 +791,12 @@ def recorded_coverage(result, donor, *, target_families=None): "target_families": transfer_plan, "hours_under15_policy": None, "work_disability_inputs": True, + "status_inputs": True, "income_transfer": True, + "se_health_premiums": True, + "weeks_deferrals": True, + "group_quarters_housing": True, + "coverage_anchors": True, "native_receipt_anchors": True, "wic_take_up": True, "semp_covers_partnership_income": True, @@ -783,6 +821,7 @@ def recorded_coverage(result, donor, *, target_families=None): assert order == [ "esi_premium_donor", "sipp_load", + "filing_load", "acs_fetch", "receipt_anchor_gate", "immigration", @@ -790,6 +829,7 @@ def recorded_coverage(result, donor, *, target_families=None): "income_gate", "ssi_disability", "ssi_disability_gate", + "voluntary_filing", "null_audit", "esi_premium_gates", "write", @@ -835,6 +875,10 @@ def recorded_coverage(result, donor, *, target_families=None): assert captured["sipp_load"] == (sipp_path, 2024) assert captured["ssi_seed"] == 11 assert summary["acs_local_ssi_disability"] == ssi_receipt + # microcosm#1720: one SIPP path for both models; the build seed draws. + assert captured["filing_load"] == Path(str(sipp_path)) + assert captured["filing_seed"] == 11 + assert summary["acs_local_voluntary_filing"] == filing_receipt assert summary["acs_local_ssi_disability_gate"] == { "name": "acs_local_ssi_disability_signal", "passed": True, @@ -842,6 +886,11 @@ def recorded_coverage(result, donor, *, target_families=None): "details": {"per_spine": {}}, } assert summary["acs_local_receipt_anchors"] == anchor_receipt + assert summary["acs_local_status_inputs"] == status_receipt + assert summary["acs_local_se_health_premiums"] == se_health_receipt + assert summary["acs_local_weeks_deferrals"] == weeks_deferrals_receipt + assert summary["acs_local_group_quarters_housing"] == group_quarters_receipt + assert summary["acs_local_coverage_anchors"] == coverage_receipt assert summary["acs_local_receipt_anchors_gate"] == { "name": "acs_local_receipt_anchor_signal", "passed": True, diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_pums.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_pums.py index 5c7072fe53..0072a99085 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_pums.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_pums.py @@ -162,6 +162,10 @@ def test_acs_loader_preserves_hours_and_allocation_without_filling_blanks(tmp_pa "CIT": 5, "YOEP": 2015, "POBP": 303, + # microcosm#1720: employer and direct-purchase coverage, loaded like the + # other coverage items. + "HINS1": 1, + "HINS2": 2, "HINS3": 2, "HINS4": 1, "HINS5": 2, @@ -228,6 +232,36 @@ def test_acs_loader_keeps_immigration_sources_and_renames_military_service( assert person["CIT"].tolist() == [5, 1] +def test_acs_loader_keeps_the_subsidy_recode_under_acs_source_names( + tmp_path: Path, +) -> None: + """microcosm#1720: HIMRKS (Subsidized Marketplace Coverage) and its + allocation flag stay on the ACS rows as raw source items, under ACS_ + names; absent in the source, they stay absent.""" + + household_zip = tmp_path / "subsidy-hh.zip" + person_zip = tmp_path / "subsidy-person.zip" + _write_csv_zip(household_zip, {"psam_husa.csv": [_household("sub", NP=2)]}) + _write_csv_zip( + person_zip, + { + "psam_pusa.csv": [ + _person("sub", 1, 20, HINS2=1, HIMRKS=1, FHIMRKSP=1), + _person("sub", 2, 21, HINS2=2, HIMRKS=0, FHIMRKSP=0), + ] + }, + ) + tables, _ = load_acs_pums_tables(AcsPumsSource(household_zip, person_zip)) + person = tables["person"] + assert "HIMRKS" not in person and "FHIMRKSP" not in person + assert person["ACS_HIMRKS"].tolist() == [1, 0] + assert person["ACS_FHIMRKSP"].tolist() == [1, 0] + + absent, _ = load_acs_pums_tables(_source(tmp_path)) + for column in ("HIMRKS", "FHIMRKSP", "ACS_HIMRKS", "ACS_FHIMRKSP"): + assert column not in absent["person"] + + def test_acs_loader_leaves_absent_immigration_sources_absent(tmp_path: Path) -> None: tables, _ = load_acs_pums_tables(_source(tmp_path)) # ESR is also a required work-experience column, so it is always loaded. diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py b/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py index 8c76d4622a..27d04475dd 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_battery_bindings.py @@ -97,15 +97,16 @@ "us_local": { # Moved by the entries that pin the thresholds they compare against # (review of #1635, rounds 1 and 2), then by the lane's two ESI - # premium entries (microcosm#454, d2283 PR 0). + # premium entries (microcosm#454, d2283 PR 0), then by the ACA + # take-up stage's diagnostic entry (microcosm#1720). "gates_manifest_sha256": ( - "016410cb9f1b7b6f9ec977ef9cd1edb40abeea2f1877ee3c958d95e7c4c05374" + "910d0c0d7c3ac2ba03fbb1e6fedd2a1b40e0bea7f06f8738b0a37fad33c0c126" ), "policy_sha256": ( - "fb38b4ceb7bc719ecaab8f6e9c013a78f8aef40490d00656bc4cd0c94a51b9cc" + "cb21d4dfa9a779fd680a7dabe97210886fd3b0fe9feb706f8f95f1329b2b8759" ), "spec_fingerprint": ( - "c3774138d171c169b3a61d8dcb5bd15fdf65a65f5da13ecdd0a1792ffcfc5023" + "5fe6a6082d8c58456d8964438593a60cde2a912636a0b7d49851ef317be63bc3" ), }, } diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_keyed_draw_equivalence.py b/packages/microcosm-build/tests/engine_free/us/test_us_keyed_draw_equivalence.py index 71b015f789..f76beff261 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_keyed_draw_equivalence.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_keyed_draw_equivalence.py @@ -15,8 +15,8 @@ import pandas as pd import pytest +import microcosm.build.anchor_thinning as anchor_thinning import microcosm.build.us_runtime.acs_local_ssi_disability as acs_local_ssi_disability -import microcosm.build.us_runtime.acs_local_ssi_medicaid_take_up as acs_local_ssi_medicaid_take_up import microcosm.build.us_runtime.acs_local_vehicles_head_start as acs_local_vehicles_head_start import microcosm.build.us_runtime.immigration as immigration import microcosm.build.us_runtime.medicaid_take_up as medicaid_take_up @@ -130,6 +130,15 @@ def test_shared_helper_is_the_copied_loop(seed, ids) -> None: "acs_local_head_start_take_up", _KEYS, ), + # The shared keep draw of the ACS local lane's anchor thinning, on the + # Medicaid HINS4 stream that the lane's one-key helper used (#1720). + "anchor_thinning": ( + lambda seed: anchor_thinning.anchor_keep_uniforms( + _KEYS, seed=seed, stream="acs_local_medicaid_hins4_anchor_keep" + ), + "acs_local_medicaid_hins4_anchor_keep", + _KEYS, + ), } @@ -144,20 +153,11 @@ def test_module_draws_are_the_copied_loop(seed, module) -> None: @pytest.mark.parametrize("seed", SEEDS) def test_one_key_draws_stay_python_floats(seed) -> None: - for actual, salt in ( - ( - ssi_take_up._stable_source_draw("asec:1", seed=seed), - "takes_up_ssi_if_eligible", - ), - ( - acs_local_ssi_medicaid_take_up._keyed_uniform( - "asec:1", seed=seed, stream="acs_local_medicaid_hins4_anchor_keep" - ), - "acs_local_medicaid_hins4_anchor_keep", - ), - ): - assert type(actual) is float - assert _bits([actual]) == _bits(_main_loop(["asec:1"], seed=seed, salt=salt)) + actual = ssi_take_up._stable_source_draw("asec:1", seed=seed) + assert type(actual) is float + assert _bits([actual]) == _bits( + _main_loop(["asec:1"], seed=seed, salt="takes_up_ssi_if_eligible") + ) @pytest.mark.parametrize("seed", SEEDS) 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 5d76acfe5e..9df80d0998 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 @@ -120,6 +120,13 @@ # re-application and per-origin gate (#1022); exact boundary # functions are pinned below. "acs_local_ssi_medicaid_take_up.py", + # Legacy local-lane ACS-row ACA take-up and plan-ratio assignment, + # recorded re-application and report-only gate (#1720); exact + # boundary functions are pinned below. + "acs_local_aca_take_up.py", + # Local-lane ACS-unit voluntary-filing fill (#1720); the exact + # boundary function is pinned below. + "acs_local_voluntary_filing.py", # Legacy local-lane per-origin native SNAP receipt-anchor gate # (#1022); the exact boundary function is pinned below. "acs_local_receipt_anchors.py", @@ -278,9 +285,39 @@ # Legacy local-lane SSI/Medicaid take-up assignment and release gate # (#1022); outside the registry. "acs_local_ssi_medicaid_take_up.py", + # Legacy local-lane ACA take-up and plan-ratio assignment and its + # report-only gate (#1720); outside the registry. + "acs_local_aca_take_up.py", # Legacy local-lane native FS receipt anchor and release gate (#1022); # outside the registry. "acs_local_receipt_anchors.py", + # Local-lane marital, military and occupation status of ACS rows + # (#1720), mapped on the ACS-only frame before any transfer under the + # donor's rules; tag-free, it runs before origin tags exist. Outside + # the registry. + "acs_local_status_inputs.py", + # Local-lane self-employed health premium inputs of ACS rows (#1720): + # the donor's attribution on the ACS-only frame after the shared + # transfer and before pooling; tag-free. Outside the registry. + "acs_local_se_health_premiums.py", + # Local-lane weeks unemployed and retirement deferrals of ACS rows + # (#1720): a one-pass transfer plan on the donor's ASEC role after the + # shared transfer, on the ACS-only frame before pooling; tag-free (it + # selects the donor role through resolve_acs_donor_channel). Outside + # the registry. + "acs_local_weeks_deferrals.py", + # Local-lane voluntary-filing fill of ACS tax units with the donor's + # SIPP model (#1720); outside the registry. + "acs_local_voluntary_filing.py", + # Local-lane housing take-up of ACS group-quarters SPM units (#975), + # on the ACS-only frame after the shared transfer and before pooling; + # tag-free. Outside the registry. + "acs_local_group_quarters_housing.py", + # Local-lane employer and direct-purchase coverage of ACS rows from + # HINS1/HINS2 (#1720), on the ACS-only frame after every transfer and + # before pooling; tag-free (the donor role through + # resolve_acs_donor_channel). Outside the registry. + "acs_local_coverage_anchors.py", # Legacy local-lane Head Start take-up fill, ACS VEH availability # receipt and grade helpers (#1022); tag-free, the take-up stage # passes the spine masks. Outside the registry. @@ -3739,6 +3776,40 @@ def test_acs_local_ssi_disability_provenance_is_limited_to_reviewed_boundaries() assert not _source_spine_accesses(ast.unparse(remaining)) +def test_acs_local_voluntary_filing_provenance_is_limited_to_reviewed_boundaries() -> ( + None +): + """Pin the ACS-unit voluntary-filing fill (#1720). + + The predictor view, the SIPP loader and the receipt helpers read no origin + tag; only the stage, which selects the ACS rows, does. + """ + + source = (_US_RUNTIME / "acs_local_voluntary_filing.py").read_text() + boundaries = ("with_acs_local_voluntary_filing",) + assert ( + tuple( + sorted( + caller for caller, _line in _function_callers(source, "spine_column") + ) + ) + == boundaries + ) + tree = ast.parse(source) + remaining = ast.Module( + body=[ + node + for node in tree.body + if not ( + isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) + and node.name in boundaries + ) + ], + type_ignores=[], + ) + assert not _source_spine_accesses(ast.unparse(remaining)) + + def test_acs_local_ssi_medicaid_take_up_provenance_is_limited_to_reviewed_boundaries() -> ( None ): @@ -3780,6 +3851,40 @@ def test_acs_local_ssi_medicaid_take_up_provenance_is_limited_to_reviewed_bounda assert not _source_spine_accesses(ast.unparse(remaining)) +def test_acs_local_aca_take_up_provenance_is_limited_to_reviewed_boundaries() -> None: + """Pin the ACS-row ACA take-up boundaries (#1720). + + The residual accounting, draw keys, stage tables, receipt grading and + digest read no origin tag. Only ``_acs_masks``, which the stage, the + recorded re-application, the assignment export and the gate call to pick + the ACS persons and tax units, and the gate's own spine check do. + """ + + source = (_US_RUNTIME / "acs_local_aca_take_up.py").read_text() + boundaries = ("_acs_masks", "acs_local_aca_take_up_signal_gate") + assert ( + tuple( + sorted( + caller for caller, _line in _function_callers(source, "spine_column") + ) + ) + == boundaries + ) + tree = ast.parse(source) + remaining = ast.Module( + body=[ + node + for node in tree.body + if not ( + isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) + and node.name in boundaries + ) + ], + type_ignores=[], + ) + assert not _source_spine_accesses(ast.unparse(remaining)) + + def test_acs_local_receipt_anchors_provenance_is_limited_to_reviewed_boundaries() -> ( None ): diff --git a/tools/_legacy/build_us_acs_multispine_base.py b/tools/_legacy/build_us_acs_multispine_base.py index d0badf2f3a..d1f0270c51 100644 --- a/tools/_legacy/build_us_acs_multispine_base.py +++ b/tools/_legacy/build_us_acs_multispine_base.py @@ -93,6 +93,11 @@ require_acs_local_ssi_disability_donor, with_acs_local_ssi_disability_criteria, ) +from microcosm.build.us_runtime.acs_local_voluntary_filing import ( + ACS_LOCAL_VOLUNTARY_FILING_ISSUE, + load_acs_local_voluntary_filing_donor, + with_acs_local_voluntary_filing, +) from microcosm.build.us_runtime.acs_local_work_disability import ( ACS_DISABILITY_ITEMS, ACS_LOCAL_DISABILITY_COLUMNS, @@ -590,6 +595,11 @@ def _build(args: argparse.Namespace, telemetry: LocalTelemetryEmitter) -> int: ssi_disability_donor, ssi_disability_identity = _load_ssi_disability_donor( args.sipp_donor, period=args.period ) + # microcosm#1720: the voluntary-filing model reads the same verified SIPP + # file, so nothing is downloaded twice. + voluntary_filing_donor, voluntary_filing_identity = _load_voluntary_filing_donor( + ssi_disability_identity + ) base_rows = _row_counts(base) base_mass = float(base.weights_for("household").total) puma_ladder_sha256 = _sha256(args.puma_ladder) @@ -635,7 +645,17 @@ def _build(args: argparse.Namespace, telemetry: LocalTelemetryEmitter) -> int: prepare_acs_local_esi_premium_donor if transfer_esi_premiums else None ), work_disability_inputs=True, + # microcosm#1720: ACS MAR, MIL and OCCP under the donor's rules. + status_inputs=True, income_transfer=True, + # microcosm#1720: the donor's self-employed premium attribution, and + # weeks unemployed and three deferrals from the ASEC observations. + se_health_premiums=True, + weeks_deferrals=True, + # microcosm#975: no housing take-up in group quarters. + group_quarters_housing=True, + # microcosm#1720: has_esi and the direct-purchase flags from HINS1/2. + coverage_anchors=True, native_receipt_anchors=True, # microcosm#1154: the ACS rows' WIC decisions, drawn before pooling. wic_take_up=True, @@ -702,6 +722,16 @@ def _build(args: argparse.Namespace, telemetry: LocalTelemetryEmitter) -> int: ) del ssi_disability_donor gc.collect() + # microcosm#1720: the donor's SIPP voluntary-filing model on the ACS tax + # units, before the input-null audit; recorded, never graded. + result, voluntary_filing = _with_local_voluntary_filing( + result, + sipp_donor=voluntary_filing_donor, + donor_identity=voluntary_filing_identity, + seed=args.seed, + ) + del voluntary_filing_donor + gc.collect() telemetry.transition_stage("audit_inputs") input_null_audit = _engine_input_null_audit(result.frame) gc.collect() @@ -794,10 +824,30 @@ def _build(args: argparse.Namespace, telemetry: LocalTelemetryEmitter) -> int: "details": dict(hours_gate.details), } summary.update(receipt_anchors) + # microcosm#1720: the ACS rows' marital, military and occupation status, + # mapped before the transfer, their self-employed premium inputs, + # attributed after it, and their weeks unemployed and deferrals, drawn + # after it; recorded, never graded. + summary["acs_local_status_inputs"] = result.provenance.get( + "acs_local_status_inputs" + ) + summary["acs_local_se_health_premiums"] = result.provenance.get( + "acs_local_se_health_premiums" + ) + summary["acs_local_weeks_deferrals"] = result.provenance.get( + "acs_local_weeks_deferrals" + ) + summary["acs_local_group_quarters_housing"] = result.provenance.get( + "acs_local_group_quarters_housing" + ) + summary["acs_local_coverage_anchors"] = result.provenance.get( + "acs_local_coverage_anchors" + ) summary.update(immigration) summary.update(work_disability) summary.update(income) summary.update(ssi_disability) + summary.update(voluntary_filing) summary["local_esi_premiums"] = local_esi_premiums summary_path.parent.mkdir(parents=True, exist_ok=True) rendered = json.dumps(summary, indent=2, sort_keys=True, allow_nan=False) + "\n" @@ -1162,6 +1212,53 @@ def _with_local_ssi_disability( } +def _load_voluntary_filing_donor( + ssi_identity: Mapping[str, object], +) -> tuple[pd.DataFrame, dict[str, object]]: + """The SIPP filing donor, from the file the SSI loader resolved. + + The SSI disability loader has resolved (and, on first use, downloaded) + the pinned full SIPP 2023 file; this reads the same path, checking its + length and sha-256 again (microcosm#1720). + """ + + try: + return load_acs_local_voluntary_filing_donor(Path(str(ssi_identity["path"]))) + except (KeyError, OSError, ValueError) as exc: + raise SystemExit( + "The pinned full SIPP 2023 donor for the ACS local voluntary-filing " + f"model ({ACS_LOCAL_VOLUNTARY_FILING_ISSUE}) is unavailable: {exc}" + ) from exc + + +def _with_local_voluntary_filing( + result: AcsMultispineResult, + *, + sipp_donor: pd.DataFrame, + donor_identity: dict[str, object], + seed: int, +) -> tuple[AcsMultispineResult, dict[str, object]]: + """Run the ACS local voluntary-filing stage; return the summary entry. + + It fills only missing ACS-unit ``would_file_taxes_voluntarily`` and + records a receipt (``acs_local_voluntary_filing``); nothing is graded. + """ + + try: + frame, receipt = with_acs_local_voluntary_filing( + result.frame, + sipp_donor=sipp_donor, + donor_identity=donor_identity, + seed=seed, + ) + except ValueError as exc: + raise SystemExit( + "ACS local voluntary-filing stage failed " + f"({ACS_LOCAL_VOLUNTARY_FILING_ISSUE}): {exc}" + ) from exc + return replace(result, frame=frame), {"acs_local_voluntary_filing": receipt} + + def _require_donor_spm_independence_role(base: Frame) -> None: """Fail before any fit unless the donor delivers the source SPM role. diff --git a/tools/build_us_acs_local_release.py b/tools/build_us_acs_local_release.py index 2232417f2b..734dd36401 100644 --- a/tools/build_us_acs_local_release.py +++ b/tools/build_us_acs_local_release.py @@ -137,6 +137,19 @@ from microcosm.build.program_telemetry import program_telemetry from microcosm.build.us_runtime import target_loss_weights as loss_weighting from microcosm.build.us_runtime.acs_inputs import acs_self_employment_identity_gate +from microcosm.build.us_runtime.acs_local_aca_take_up import ( + ACS_LOCAL_ACA_TAKE_UP_COLUMNS, + ACS_LOCAL_ACA_TAKE_UP_GATE_NAME, + ACS_LOCAL_ACA_TAKE_UP_ISSUE, + ACS_LOCAL_ACA_TAKE_UP_METHOD, + acs_local_aca_take_up_assignment, + acs_local_aca_take_up_signal_gate, + with_acs_local_aca_take_up, + with_recorded_acs_local_aca_take_up, +) +from microcosm.build.us_runtime.acs_local_coverage_anchors import ( + ACS_LOCAL_COVERAGE_ANCHOR_COLUMNS, +) from microcosm.build.us_runtime.acs_local_esi_premiums import ( acs_local_esi_premium_anchor_gate, acs_local_esi_premium_gate_payload, @@ -172,6 +185,10 @@ load_reviewed_fill_consumer_register, reviewed_fill_register_summary, ) +from microcosm.build.us_runtime.acs_local_se_health_premiums import ( + ACS_LOCAL_SE_HEALTH_PREMIUM_COLUMNS, + ACS_LOCAL_SE_HEALTH_PREMIUMS_ISSUE, +) from microcosm.build.us_runtime.acs_local_ssi_disability import ( ACS_LOCAL_SSI_DISABILITY_COLUMN, ACS_LOCAL_SSI_DISABILITY_GATE_NAME, @@ -189,6 +206,10 @@ with_acs_local_ssi_medicaid_take_up, with_recorded_acs_local_ssi_medicaid_take_up, ) +from microcosm.build.us_runtime.acs_local_status_inputs import ( + ACS_LOCAL_STATUS_INPUTS_COLUMNS, + ACS_LOCAL_STATUS_INPUTS_ISSUE, +) from microcosm.build.us_runtime.acs_local_take_up import ( ACS_LOCAL_EITC_TAKE_UP_ISSUE, ACS_LOCAL_ENGINE_FREE_FILL_COLUMNS, @@ -204,6 +225,14 @@ US_VEHICLES_OWNED_COLUMN, US_VEHICLES_VALUE_COLUMN, ) +from microcosm.build.us_runtime.acs_local_voluntary_filing import ( + ACS_LOCAL_VOLUNTARY_FILING_COLUMN, + ACS_LOCAL_VOLUNTARY_FILING_ISSUE, +) +from microcosm.build.us_runtime.acs_local_weeks_deferrals import ( + ACS_LOCAL_WEEKS_DEFERRALS_COLUMNS, + ACS_LOCAL_WEEKS_DEFERRALS_ISSUE, +) from microcosm.build.us_runtime.acs_local_wic_take_up import ( ACS_LOCAL_WIC_TAKE_UP_ISSUE, US_WIC_TAKE_UP_COLUMN, @@ -806,19 +835,25 @@ def state_level(spec) -> bool: ) -def acs_local_ssi_medicaid_take_up_targets(feed: str | Path) -> dict[str, object]: +def acs_local_ssi_medicaid_take_up_targets( + feed: str | Path, *, compiled: tuple | None = None +) -> dict[str, object]: """The counts the ACS SSI/Medicaid take-up stage scales (microcosm#1022). Compiled from the same feed and path as :func:`state_admin_specs` (a second compile, run before the staging frame is loaded) and read exactly as the fiscal lane's take-up stages read them: the SSA age-band SSI recipient counts, and the post-substitution CMS state Medicaid enrollment - table with its reviewed substitution records. + table with its reviewed substitution records. ``compiled`` is that + compile, :func:`_compiled_fiscal_registry` of ``feed``, when the caller + already holds it. """ import build_us_fiscal_refresh_release as release_tool - registry, substitutions = _compiled_fiscal_registry(feed) + registry, substitutions = ( + _compiled_fiscal_registry(feed) if compiled is None else compiled + ) try: ssi = release_tool._ssi_take_up_band_targets_from_registry(registry.specs) medicaid = release_tool._medicaid_source_target_table(registry.specs) @@ -834,6 +869,38 @@ def acs_local_ssi_medicaid_take_up_targets(feed: str | Path) -> dict[str, object } +def acs_local_aca_take_up_targets( + feed: str | Path, *, compiled: tuple | None = None +) -> dict[str, object]: + """The state tables the ACS ACA take-up stage scales (microcosm#1720). + + Read from the registry :func:`acs_local_ssi_medicaid_take_up_targets` + compiles (``compiled``; materialize passes it, so the feed is not + compiled a third time) exactly as the fiscal lane's ACA stage reads them + (``_aca_source_target_tables``): each state table by ``target_role``, + CMS APTC recipients, the IRS SOI premium tax credit returns and amounts, + and the CMS bronze consumers where the feed carries them. The SOI tables + are the Historic Table 2 state rows R2's ``state`` surface holds. Like + the fiscal lane, the stage needs the APTC-recipient table: its rate and + first calibration read it. + """ + + import build_us_fiscal_refresh_release as release_tool + + registry, _substitutions = ( + _compiled_fiscal_registry(feed) if compiled is None else compiled + ) + tables = release_tool._aca_source_target_tables(tuple(registry.specs)) + if release_tool.US_ACA_APTC_TARGET_TABLE not in tables: + raise SystemExit( + "The ledger feed cannot supply the ACS local ACA take-up counts " + f"({ACS_LOCAL_ACA_TAKE_UP_ISSUE}): no " + f"{release_tool.US_ACA_APTC_TARGET_TABLE} table. The fiscal lane's " + "ACA stage needs it too." + ) + return {"target_tables": tables} + + # --------------------------------------------------------------------------- # Engine pass under the nullable-artifact contract # --------------------------------------------------------------------------- @@ -959,6 +1026,25 @@ class DeniedDefaultFillError(ValueError): ACS_LOCAL_SSI_MEDICAID_TAKE_UP_COLUMNS, ("SSI", "Medicaid"), strict=True ) }, + # microcosm#1720: the ACA take-up default, True, is universal take-up of + # the premium tax credit, and the plan-ratio default, 1.0, puts every + # taker on the benchmark plan; materialize assigns both on ACS tax units + # after an engine pre-pass and the consumer export applies the recorded + # assignment. + **{ + ("tax_unit", column): ( + f"the engine default is {meaning} ({ACS_LOCAL_ACA_TAKE_UP_ISSUE}); " + "run the ACS local ACA take-up stage first" + ) + for column, meaning in zip( + ACS_LOCAL_ACA_TAKE_UP_COLUMNS, + ( + "universal premium tax credit take-up", + "the benchmark plan for every taker", + ), + strict=True, + ) + }, # microcosm#1154: the WIC take-up default, True, is universal take-up; # staging draws the ACS rows' decisions with the national generator and # the donor release carries its own. @@ -967,12 +1053,63 @@ class DeniedDefaultFillError(ValueError): f"({ACS_LOCAL_WIC_TAKE_UP_ISSUE}); re-run staging with the current " "builder" ), + # microcosm#1720: staging maps the ACS rows' marital, military and + # occupation status from MAR, MIL and OCCP, and the donor release carries + # its own; the default False would ignore the measured item. + **{ + ("person", column): ( + "the engine default False ignores the ACS rows' measured MAR, MIL " + f"or OCCP item ({ACS_LOCAL_STATUS_INPUTS_ISSUE}); re-run staging " + "with the current builder" + ) + for column in ACS_LOCAL_STATUS_INPUTS_COLUMNS + }, + # microcosm#1720: staging runs the donor's self-employed premium + # attribution on the ACS rows; the defaults (False, 0) deny every ACS + # person the self-employed health insurance deduction. + **{ + ("person", column): ( + "the engine default denies every ACS person the self-employed " + f"health insurance deduction ({ACS_LOCAL_SE_HEALTH_PREMIUMS_ISSUE}); " + "re-run staging with the current builder" + ) + for column in ACS_LOCAL_SE_HEALTH_PREMIUM_COLUMNS + }, + # microcosm#1720: staging draws weeks unemployed and three retirement + # deferrals on the ACS rows from the donor's ASEC observations. + **{ + ("person", column): ( + f"the engine default 0 drops {reason} for every ACS person " + f"({ACS_LOCAL_WEEKS_DEFERRALS_ISSUE}); re-run staging with the " + "current builder" + ) + for column, reason in zip( + ACS_LOCAL_WEEKS_DEFERRALS_COLUMNS, + ( + "the months of UC receipt (SNAP's work-registration exemption)", + "traditional 401(k) deferrals, so AGI includes deferred wages", + "Roth 401(k) deferrals and their saver's credit", + "Roth IRA contributions and their saver's credit", + ), + strict=True, + ) + }, + # microcosm#1720: staging runs the donor's SIPP voluntary-filing model on + # the ACS tax units. + ("tax_unit", ACS_LOCAL_VOLUNTARY_FILING_COLUMN): ( + "the engine default False makes no ACS tax unit a voluntary filer, so " + "Medicaid's non-filer rules apply to more of them " + f"({ACS_LOCAL_VOLUNTARY_FILING_ISSUE}); re-run staging with the current " + "builder" + ), } NEVER_DEFAULT_FILLED = frozenset(_NEVER_DEFAULT_FILLED_REASONS) #: The checkpoint file holding the ACS rows' SSI and Medicaid take-up that #: materialize assigned (microcosm#1022); the consumer export applies it. ACS_SSI_MEDICAID_TAKE_UP_FILENAME = "acs_local_ssi_medicaid_take_up.npz" +#: Likewise the ACS tax units' ACA take-up and plan ratio (microcosm#1720). +ACS_ACA_TAKE_UP_FILENAME = "acs_local_aca_take_up.npz" def _formula_owned_columns(base_frame) -> set[str]: @@ -2175,23 +2312,113 @@ def _acs_engine_values( } helper = helpers[variable] started = time.time() + _prepass_view_contract(view, summary_path=summary_path, hh_chunk=hh_chunk) + values = helper(view, maximum_microsim_batch_size=hh_chunk) + gc.collect() + log( + f"Engine pre-pass {variable}: {len(values):,} persons " + f"({time.time() - started:.1f}s, peak RSS {rss():.2f}GB)" + ) + return values + + +#: Never-default columns that a later materialize stage assigns on ACS rows: +#: the ACA take-up stage runs after the SSI and Medicaid pre-pass, so that +#: pass's ACS view still carries them null (microcosm#1720). +_PREPASS_PENDING_COLUMNS: tuple[tuple[str, str], ...] = tuple( + ("tax_unit", column) for column in ACS_LOCAL_ACA_TAKE_UP_COLUMNS +) + + +def _with_prepass_pending_defaults(view, system) -> dict[str, int]: + """Read a pending column's null cells at the engine default, in place. + + Only a pre-pass view gets this: the cells read what the reviewed fill + gave them before their stage existed (for ACA take-up, ``True`` and a + ratio of ``1.0``), and the stage fills them before materialize's engine + pass, whose fill refuses a null there. Returns the cells read so, by + column. + """ + + read: dict[str, int] = {} + for entity, column in _PREPASS_PENDING_COLUMNS: + table = view.table(entity) + if column not in table.columns: + continue + missing = table[column].isna() + if not missing.any(): + continue + value, _kind = _resolve_engine_default(system, column) + filled = table[column].astype(object).where(~missing, value) + value_type = getattr(system.variables[column], "value_type", None) + if value_type is bool: + filled = filled.astype(bool) + elif value_type is float: + filled = filled.astype(np.float64) + table[column] = filled + read[f"{entity}.{column}"] = int(missing.sum()) + return read + + +def _prepass_view_contract( + view, *, summary_path: Path, hh_chunk: int, system=None +) -> None: + """Materialize's engine-pass contract on a pre-pass view, in place. + + The classifier of :func:`project_input_only`, without its copy, then the + reviewed-null fill. The view is the stage's own copy of its households, + so both steps edit it in place: a pre-pass never holds a second copy of + the rows. A column a later materialize stage assigns reads its engine + default where it is still null (:func:`_with_prepass_pending_defaults`). + ``system`` defaults to the policyengine-us tax-benefit system. + """ + + import build_us_fiscal_refresh_release as release_tool + formula_owned = _formula_owned_columns(view) for entity in view.entities: table = view.table(entity) held = sorted(set(table.columns) & formula_owned) if held: table.drop(columns=held, inplace=True) - fill_reviewed_nulls(view, summary_path, period=PERIOD) + if system is None: + from policyengine_us import CountryTaxBenefitSystem + + system = CountryTaxBenefitSystem() + pending = _with_prepass_pending_defaults(view, system) + if pending: + log(f"pre-pass reads pending cells at the engine default: {pending}") + fill_reviewed_nulls(view, summary_path, period=PERIOD, system=system) if view.n("household") > hh_chunk: release_tool._assert_group_entities_nest_in_households(view) release_tool._assert_medicaid_claiming_tax_units_local(view) - values = helper(view, maximum_microsim_batch_size=hh_chunk) + + +def _acs_engine_aca_tax_units( + view, target_tables, *, summary_path: Path, hh_chunk: int +) -> pd.DataFrame: + """The fiscal lane's ACA tax-unit table over a pre-pass view (#1720). + + The ACA stage calls this on the donor households, then on the ACS + households, as :func:`_acs_engine_values` serves the SSI and Medicaid + stage: the same in-place contract, then the fiscal lane's own batched + ``_aca_source_tax_unit_table`` in chunks of ``hh_chunk`` households, one + chunk's simulation at a time. + """ + + import build_us_fiscal_refresh_release as release_tool + + started = time.time() + _prepass_view_contract(view, summary_path=summary_path, hh_chunk=hh_chunk) + table = release_tool._aca_source_tax_unit_table( + view, target_tables, maximum_microsim_batch_size=hh_chunk + ) gc.collect() log( - f"Engine pre-pass {variable}: {len(values):,} persons " + f"Engine pre-pass ACA tax units: {len(table):,} tax units " f"({time.time() - started:.1f}s, peak RSS {rss():.2f}GB)" ) - return values + return table def _with_local_ssi_medicaid_take_up( @@ -2340,6 +2567,163 @@ def _with_recorded_ssi_medicaid_take_up(frame, receipt: dict, path: Path): ) from exc +def _with_local_aca_take_up( + frame, *, seed: int, targets: dict, summary_path: Path, hh_chunk: int +): + """Assign ACS-row ACA take-up and the plan ratio, and grade them (#1720). + + Runs after the SSI and Medicaid assignment and before materialize's + engine pass, so the state SOI premium tax credit rows select takers + among eligible ACS units instead of shrinking their weights. Each ACS + target is what the donor rows leave of the fiscal lane's state counts on + the pooled weights, measured with one more household-batched engine pass + over the donor households, then one over the ACS households. + + The grade is report-only: it goes into the receipt and the diagnostic + shadow entry, a failure is logged, and the stage goes on. Only an input + the stage cannot run on stops it. + """ + + started = time.time() + try: + frame, receipt = with_acs_local_aca_take_up( + frame, + seed=seed, + target_tables=targets["target_tables"], + aca_tax_units=lambda view, tables: _acs_engine_aca_tax_units( + view, tables, summary_path=summary_path, hh_chunk=hh_chunk + ), + period=PERIOD, + ) + except ValueError as exc: + raise SystemExit( + f"ACS local ACA take-up stage failed ({ACS_LOCAL_ACA_TAKE_UP_ISSUE}): {exc}" + ) from exc + receipt["engine_prepass"].update( + stage_wall_s=round(time.time() - started, 1), + hh_chunk=hh_chunk, + peak_rss_gb=round(rss(), 2), + ) + try: + # Report-only: the entry's criticality is diagnostic. + gate = shadow_gate( + "us_local_aca_take_up_materialize", + lambda: acs_local_aca_take_up_signal_gate(frame, receipt=receipt), + lambda: EvidenceContext(frame=frame, artifacts={"aca_receipt": receipt}), + ) + grade = { + "name": gate.name, + "passed": gate.passed, + "failures": list(gate.failures), + } + except Exception as error: # noqa: BLE001 - the grade never stops the stage + grade = { + "name": ACS_LOCAL_ACA_TAKE_UP_GATE_NAME, + "passed": False, + "failures": [f"the grade could not run: {error!r}"], + } + receipt["gate"] = {**grade, "report_only": True} + if not grade["passed"]: + log( + "WARNING ACS local ACA take-up grade (report-only, " + f"{ACS_LOCAL_ACA_TAKE_UP_ISSUE}): " + "; ".join(grade["failures"]) + ) + for key in ("take_up", "plan_ratio"): + entry = receipt[key] + log(f"ACS take-up {entry['column']}: filled {entry['filled_rows']:,} rows") + log( + "ACS ACA take-up: weighted share of eligible units " + f"{receipt['take_up']['weighted_take_up_share_of_eligible']}" + ) + anchor = receipt.get("anchor") or {} + thinning = anchor.get("thinning") or {} + log( + f"ACS ACA anchors: {anchor.get('anchored_tax_units')} kept, " + f"{thinning.get('thinned_tax_units')} thinned in " + f"{len(thinning.get('thinned_states') or [])} state(s); anchor share " + f"of takers {receipt['take_up'].get('anchor_share_of_takers')}" + ) + return frame, receipt + + +def _write_aca_take_up(frame, path: Path) -> str: + """Record the ACS tax units' ACA inputs; return the file sha256.""" + + assignment = acs_local_aca_take_up_assignment(frame) + tax_unit_ids = assignment["tax_unit_id"].to_numpy() + if tax_unit_ids.dtype == object: + tax_unit_ids = tax_unit_ids.astype(str) + take_up, ratio = ACS_LOCAL_ACA_TAKE_UP_COLUMNS + with Path(path).open("wb") as handle: + np.savez( + handle, + tax_unit_id=tax_unit_ids, + **{ + take_up: assignment[take_up].to_numpy(dtype=bool), + ratio: assignment[ratio].to_numpy(dtype=np.float64), + }, + ) + return _sha256(path) + + +def _recorded_aca_take_up(identity: dict, checkpoint_dir: Path): + """The ACS ACA take-up materialize assigned, or refuse. + + Returns the run-identity receipt and the recorded assignment file. A + checkpoint without the receipt, or whose file is missing or changed, was + materialized with every eligible ACS tax unit taking up the premium tax + credit at the benchmark plan (the engine defaults), or cannot prove + what it calibrated against. The receipt's grade is report-only, so its + verdict is not required here. + """ + + receipt = identity.get("acs_local_aca_take_up") + recorded = receipt.get("assignment_file") if isinstance(receipt, dict) else None + if ( + not isinstance(receipt, dict) + or receipt.get("issue") != ACS_LOCAL_ACA_TAKE_UP_ISSUE + or receipt.get("method") != ACS_LOCAL_ACA_TAKE_UP_METHOD + or type(receipt.get("seed")) is not int + or not isinstance(receipt.get("assigned_sha256"), str) + or not isinstance(recorded, dict) + or recorded.get("name") != ACS_ACA_TAKE_UP_FILENAME + or not isinstance(recorded.get("sha256"), str) + ): + raise SystemExit( + "run_identity.json records no ACS local ACA take-up assignment " + f"({ACS_LOCAL_ACA_TAKE_UP_ISSUE}): the checkpoint was materialized " + "with every eligible ACS tax unit taking up the premium tax credit " + "at the benchmark plan (the engine defaults). Re-run --stage " + "materialize." + ) + path = Path(checkpoint_dir) / ACS_ACA_TAKE_UP_FILENAME + if not path.is_file() or _sha256(path) != recorded["sha256"]: + raise SystemExit( + f"The recorded ACS ACA take-up assignment {path} is missing or " + f"changed since materialize ({ACS_LOCAL_ACA_TAKE_UP_ISSUE}). Re-run " + "--stage materialize." + ) + return receipt, path + + +def _with_recorded_aca_take_up(frame, receipt: dict, path: Path): + """Apply the recorded ACS ACA take-up and plan ratio; refuse a mismatch.""" + + columns = ("tax_unit_id", *ACS_LOCAL_ACA_TAKE_UP_COLUMNS) + try: + with np.load(path, allow_pickle=False) as recorded: + table = pd.DataFrame({column: recorded[column] for column in columns}) + return with_recorded_acs_local_aca_take_up( + frame, table, assigned_sha256=receipt["assigned_sha256"] + ) + except (KeyError, OSError, ValueError) as exc: + raise SystemExit( + "The consumer export cannot reproduce the ACS ACA take-up " + f"materialize calibrated against ({ACS_LOCAL_ACA_TAKE_UP_ISSUE}): " + f"{exc} Re-run --stage materialize against this staging file." + ) from exc + + def _cd_holdout_fraction(args) -> float: """The CD holdout fraction this run draws (0 when there is no CD surface).""" @@ -2448,9 +2832,15 @@ def do_materialize(args) -> None: # decides, so it can run while the new donor's evidence is reviewed; # calibrate fixes the commit package accepts, so the entry must be in # the checkout before calibrate starts, and finalize checks it again. - # microcosm#1022: the SSI and Medicaid take-up counts, from the same feed - # and compile path, before the staging frame is loaded. - ssi_medicaid_targets = acs_local_ssi_medicaid_take_up_targets(args.feed) + # microcosm#1022/#1720: the SSI, Medicaid and ACA take-up counts, from + # the same feed and compile path, before the staging frame is loaded. + # One compile serves both stages. + compiled = _compiled_fiscal_registry(args.feed) + ssi_medicaid_targets = acs_local_ssi_medicaid_take_up_targets( + args.feed, compiled=compiled + ) + aca_targets = acs_local_aca_take_up_targets(args.feed, compiled=compiled) + del compiled log("hashing staging inputs for the run identity …") staging_sha = _sha256(args.staging_h5) ladder_sha = _sha256(args.ladder) @@ -2498,6 +2888,24 @@ def do_materialize(args) -> None: ), } gc.collect() + # microcosm#1720: assign the ACS tax units' ACA take-up and plan ratio. + # Medicaid eligibility bars the credit and reads SSI receipt, so this + # follows the SSI assignment. Recorded for calibrate and the export. + frame, aca = _with_local_aca_take_up( + frame, + seed=args.seed, + targets=aca_targets, + summary_path=summary_path, + hh_chunk=args.hh_chunk, + ) + del aca_targets + aca["assignment_file"] = { + "name": ACS_ACA_TAKE_UP_FILENAME, + "sha256": _write_aca_take_up( + frame, args.checkpoint_dir / ACS_ACA_TAKE_UP_FILENAME + ), + } + gc.collect() started = time.time() args.checkpoint_dir.mkdir(parents=True, exist_ok=True) @@ -2637,6 +3045,7 @@ def do_materialize(args) -> None: "sampling": sampling, "acs_local_take_up": take_up, "acs_local_ssi_medicaid_take_up": ssi_medicaid, + "acs_local_aca_take_up": aca, }, indent=2, ) @@ -3194,6 +3603,8 @@ def do_calibrate(args) -> None: # microcosm#1022: and a checkpoint without the recorded ACS SSI/Medicaid # take-up the export must apply. _recorded_ssi_medicaid_take_up(identity, args.checkpoint_dir) + # microcosm#1720: likewise the recorded ACS ACA take-up and plan ratio. + _recorded_aca_take_up(identity, args.checkpoint_dir) _apply_county_solver_profile(args, identity=identity) frame, design_weights, registry, roles, matrix = load_checkpoint_surface( args.checkpoint_dir, identity @@ -3584,6 +3995,7 @@ def _write_calibrated_artifact( ssi_medicaid, ssi_medicaid_path = _recorded_ssi_medicaid_take_up( identity, args.checkpoint_dir ) + aca, aca_path = _recorded_aca_take_up(identity, args.checkpoint_dir) frame = _load_staging_frame(args.staging_h5) _shadow_local_refusal( "us_local_hours_calibrate", @@ -3607,6 +4019,8 @@ def _write_calibrated_artifact( # microcosm#1022: apply the ACS SSI/Medicaid take-up materialize recorded # on the same rung; it must reproduce the recorded digest. frame = _with_recorded_ssi_medicaid_take_up(frame, ssi_medicaid, ssi_medicaid_path) + # microcosm#1720: and the ACS ACA take-up and plan ratio, likewise. + frame = _with_recorded_aca_take_up(frame, aca, aca_path) # microcosm#922: re-apply the county support moves materialize recorded, # so the published file carries the county codes calibration saw. frame = county_surface.apply_recorded_support(frame, identity, args.checkpoint_dir) @@ -3691,6 +4105,10 @@ def _write_calibrated_artifact( "assigned_sha256": ssi_medicaid["assigned_sha256"], "assignment_file": ssi_medicaid["assignment_file"], }, + "acs_local_aca_take_up": { + "assigned_sha256": aca["assigned_sha256"], + "assignment_file": aca["assignment_file"], + }, "live_stored_inputs": live_inputs.provenance, # The code that wrote these bytes, as read when the stage # started. The build's ID names the packaging code, so @@ -4448,23 +4866,25 @@ def finalize_reviewed_limitations( "FS anchor, acs_snap_receipt_anchor), Medicare take-up is " "native ACS HINS3 and Head Start take-up a keyed draw at the " "donor spine's share among ages 3-5 " - "(acs_engine_free_default_fills), and SSI and Medicaid " - "take-up are assigned after an engine pre-pass " - "(acs_local_ssi_medicaid_take_up). EITC take-up is the take-up " - "contract's seeded draw by number of qualifying children " - "(microcosm#1675), and WIC take-up the national generator's " - "draw, made in staging (microcosm#1154). The other " - "runtime-owned takes_up_* flags (ACA, Early Head Start and the " - "rest) are neither transferred nor seeded on ACS rows, so they " - "ship at the engine default, universal take-up; the reviewed-fill " - "consumer register records their known biases " - "(acs_reviewed_default_fill_consumers). The QA " + "(acs_engine_free_default_fills), SSI and Medicaid take-up " + "are assigned after an engine pre-pass " + "(acs_local_ssi_medicaid_take_up), and ACA take-up with the " + "Marketplace plan ratio after one more " + f"(acs_local_aca_take_up, {ACS_LOCAL_ACA_TAKE_UP_ISSUE}). EITC " + "take-up is the take-up contract's seeded draw by number of " + "qualifying children (microcosm#1675), and WIC take-up the " + "national generator's draw, made in staging (microcosm#1154). " + "The other runtime-owned takes_up_* flags (Early Head Start, " + "CHIP and the rest) are neither transferred nor seeded on ACS " + "rows, so they ship at the engine default, universal take-up; " + "the reviewed-fill consumer register records their known " + "biases (acs_reviewed_default_fill_consumers). The QA " "probe's SNAP take-up table is a December-eligible snapshot " "(unit- and person-weighted), informational and never " "graded; it is not the FNS fiscal-year participation rate, " "which is among eligible people over a federal fiscal year." ), - "treatment": "Tracked via microcosm#1022.", + "treatment": f"Tracked via {ACS_LOCAL_ACA_TAKE_UP_ISSUE}.", "calibration_blocker": False, }, { @@ -4487,8 +4907,9 @@ def finalize_reviewed_limitations( "receives_housing_assistance copies the transferred " "takes_up_housing_assistance_if_eligible (equal on the donor by " "construction) and is False in TYPEHUGQ 2/3 group quarters, " - "whose transferred take-up flag is the open transfer-side fix " - "microcosm#975. takes_up_medicare_if_eligible is ACS HINS3 == 1 " + "where staging also sets the transferred take-up flag False " + "(microcosm#975; reviewed limitation acs_local_staged_inputs). " + "takes_up_medicare_if_eligible is ACS HINS3 == 1 " "(coverage at interview), as the donor maps ASEC MCARE == 1; a " "blank or invalid HINS3 reads as not covered. " "takes_up_head_start_if_eligible is True for a person aged 3-5 " @@ -4821,6 +5242,70 @@ def finalize_reviewed_limitations( ), "calibration_blocker": False, }, + { + "id": "acs_local_aca_take_up", + "status": "reviewed_modeling_decision", + "affected_spines": ["acs_2024_1yr"], + "columns": list(ACS_LOCAL_ACA_TAKE_UP_COLUMNS), + "reason": ( + "ACS tax units get takes_up_aca_if_eligible and " + "selected_marketplace_plan_benchmark_ratio from the fiscal " + "lane's own aca_marketplace_inputs manifest stage at " + f"materialize ({ACS_LOCAL_ACA_TAKE_UP_ISSUE}), after one more " + "household-batched engine pre-pass over the donor households " + "and then the ACS households, with the ACS rows' SSI take-up " + "assigned: Medicaid eligibility bars the credit and reads SSI " + "receipt. Each state target is the residual of the stage's " + "count (CMS APTC recipients; the IRS SOI premium tax credit " + "returns and amounts of Historic Table 2) after the donor " + "rows' contribution on the pooled weights, floored at zero. " + "Where both SOI tables exist the stage's joint step decides: " + "it fills each state's residual return count with the units " + "whose credit per return is closest to the residual average, " + "the draw only breaking ties, so the CMS people the takers " + "carry are reported, not met (microcosm#168). Beyond the kept " + "anchors, this selection puts the ACS takers' credits near " + "each state's average credit per return, with too few very " + "large and very small credits, so distributional reads of the " + "credit on ACS rows are biased; the donor's stage selects the " + "same way. The anchor is " + "the manifest stage's own column, " + "reported_has_subsidized_marketplace_health_coverage_at_interview, " + "which staging writes on ACS persons from the PUMS subsidy " + "item HIMRKS; it reads False where absent, the fiscal lane's " + "rule. Where a state's anchors weigh more than its residual " + "return count, each stays anchored with probability residual " + "/ anchored weight on its own keyed draw " + "(acs_local_aca_subsidized_anchor_keep), the Medicaid stage's " + "HINS4 rule in the shared microcosm.build.anchor_thinning; a " + "unit not kept is an ordinary non-anchor. The draw meets the " + "residual in expectation only, and the kept anchors' excess " + "over each table is recorded. " + "The plan ratio is (premium + credit) / SLCSP for takers, " + "clipped to 0.5-1.5, and 1.0 otherwise; the feed carries no " + "bronze count, so the ratio is not calibrated, as on the " + "donor. Draws are keyed on acs_2024_1yr:SERIALNO and the " + "unit's lowest SPORDER, with the build seed. The eligible pool " + "reads the employer coverage staging writes from ACS HINS1 " + "and the direct-purchase flags it bounds with HINS2 (reviewed " + "limitation acs_local_staged_inputs), and the targets bind " + "the pre-calibration frame." + ), + "treatment": ( + "Graded by acs_local_aca_take_up_signal at materialize, " + "report-only: the grade and its diagnostic shadow entry " + "(us_local_aca_take_up_materialize) are recorded and " + "materialize never stops on them. The receipt records each " + "table's state residuals, ACS capacity and delivery, every " + "shortfall and donor excess, each state's anchored weight, " + "keep probability and thinned rows, the share of ACS takers " + "that are anchors, and the people per return of each set of " + "rows. A thinned state is reported, not graded against the " + "tolerance. The consumer export applies the recorded " + "assignment and must reproduce its digest." + ), + "calibration_blocker": False, + }, { "id": "acs_snap_receipt_anchor", "status": "reviewed_modeling_decision", @@ -4889,6 +5374,111 @@ def finalize_reviewed_limitations( ), "calibration_blocker": False, }, + { + "id": "acs_local_staged_inputs", + "status": "reviewed_modeling_decision", + "affected_spines": ["acs_2024_1yr"], + "columns": [ + *ACS_LOCAL_STATUS_INPUTS_COLUMNS, + *ACS_LOCAL_SE_HEALTH_PREMIUM_COLUMNS, + *ACS_LOCAL_WEEKS_DEFERRALS_COLUMNS, + ACS_LOCAL_VOLUNTARY_FILING_COLUMN, + "takes_up_housing_assistance_if_eligible", + *ACS_LOCAL_COVERAGE_ANCHOR_COLUMNS, + ], + "reason": ( + "Staging writes these inputs on ACS rows from ACS items or the " + "donor's own rules instead of leaving the engine default " + f"({ACS_LOCAL_STATUS_INPUTS_ISSUE}). is_separated and " + "is_surviving_spouse follow the donor's relationship_inputs " + "rule on the ACS rows' A_MARITL (ACS MAR 4, separated, and MAR " + "2, widowed; as on the donor, widowed is wider than the " + "surviving-spouse tax status). policyengine-us's " + "surviving_spouse_eligible does not check that the spouse died " + "in one of the two prior tax years (IRC section 2(a)), so on " + "both spines every widowed, unmarried tax unit head with a " + "child dependent files as a surviving spouse, with the joint " + "brackets and standard deduction, not as a head of household. " + "is_military is ACS MIL == 1, now " + "on active duty, and MIL's blank under 17 reads False; the " + "donor reads a military occupation (POCCU2 52), which on ACS " + "rows would also mark a veteran whose last job was military. " + "has_never_worked, is_computer_scientist, is_farmer_fisher and " + "is_executive_administrative_professional follow the donor's " + "org_wages rule on the native detailed_occupation_recode. " + "is_self_employed and health_insurance_premiums come from the " + "donor's own attribution (attribute_us_se_health_premiums), run " + "on the ACS rows after the shared transfer: the flag marks " + "positive Schedule C income (SEMP plus the transferred SSTB " + "leaf), not ACS COW 6 or 7, and the premium is the transferred " + "non-Part-B premium of a flagged person under 65 with no Social " + "Security disability and no employer coverage. The ACS rows' " + "MAGI is then final before materialize assigns Medicaid take-up; " + "the national build applies the attribution in another order " + "(microcosm#1689). weeks_unemployed and the traditional and " + "Roth 401(k) and Roth IRA deferrals come from a separate local " + "QRF pass on the donor's ASEC observation role (measured " + "LKWEEKS, and RETCB_VAL split by the archived shares), run after " + "the shared transfer so the weeks read its " + "unemployment_compensation, with the donor's own " + "post-processing: weeks 0 without UC, 401(k) deferrals 0 " + "without wages. The shared plan keeps the traditional IRA and " + "self-employed pension leaves. The deferrals lower the ACS rows' " + "AGI. would_file_taxes_voluntarily (tax unit) comes from the " + "donor release's own SIPP model (voluntary_filing: the weighted " + "QRF on the pinned full SIPP 2023 file's December filing " + "answers), run on the ACS tax units with tax-unit wages, the " + "head's age and sex, JOINT filing status and the household's " + "persons under 18 as predictors; it reads the file staging " + "already verifies for the SSI disability model. Last, staging " + "sets the transferred takes_up_housing_assistance_if_eligible " + "False on every group-quarters SPM unit (TYPEHUGQ 2/3), which " + "has no housing unit (microcosm#975): a lane-own step after " + "the shared transfer, whose plan is unchanged, rather than the " + "structural policy inside the shared transfer that " + "microcosm#975 proposed. has_esi is ACS HINS1 == 1 (employer " + "or union coverage, current or former, own or a family " + "member's, at interview; the donor reads ASEC NOW_GRP), written " + "over the shared transfer's draw after every transfer, so no " + "other draw moves, and before the self-employed premium " + "attribution reads it. HINS2 (any direct purchase) sets both " + "direct-purchase flags False where it is 2; where it is 1 the " + "draws stand unless both are False, and then one keyed draw " + "picks the type at the donor ASEC role's shares among direct " + "purchasers by age band, except that HIMRKS (Subsidized " + "Marketplace Coverage) code 1, direct purchase with a premium " + "subsidy, sets the Marketplace flag True (ruled 25 Nov 2026). " + "Staging also writes the ACA stage's anchor column, " + "reported_has_subsidized_marketplace_health_coverage_at_" + "interview, on ACS rows: True where HINS2 is 1 and HIMRKS is 1 " + "(ruled 25 Nov 2026), Census-allocated values included. The " + "donor reads no such item, so donor rows carry the column " + "missing; the ACA stage reads it on ACS rows only." + ), + "treatment": ( + "Written at staging only in missing ACS cells, except the " + "group-quarters housing take-up flag and the three coverage " + "flags, which override the shared transfer's draws; donor rows " + "keep the donor release's values. The staging summary's " + "receipts record each rule, its " + "source columns and the filled and true rows " + "(acs_local_status_inputs: also the agreement of is_military " + "with POCCU2 52 and ESR 4 or 5; acs_local_se_health_premiums: " + "also the premiums the Medicare proxy and employer coverage " + "withheld, and the agreement of the flag with COW 6 or 7; " + "acs_local_weeks_deferrals: the donor's ASEC coverage and the " + "post-processing counts; acs_local_voluntary_filing: the SIPP " + "identity and the ACS and donor true shares; " + "acs_local_group_quarters_housing: the units turned False by " + "TYPEHUGQ; acs_local_coverage_anchors: the agreement of each " + "native value with the draw it replaces and the donor's type " + "shares). Recorded, not graded. A null in any column that " + "replaced an engine default stops materialize " + "(NEVER_DEFAULT_FILLED), so a staging run from before them is " + "refused there." + ), + "calibration_blocker": False, + }, { "id": "acs_reviewed_default_fill_consumers", "status": "reviewed_modeling_decision", diff --git a/tools/check_us_acs_local_reviewed_fills.py b/tools/check_us_acs_local_reviewed_fills.py index bdcbca42a0..68f5a639d3 100644 --- a/tools/check_us_acs_local_reviewed_fills.py +++ b/tools/check_us_acs_local_reviewed_fills.py @@ -17,10 +17,12 @@ - A null in a ``NEVER_DEFAULT_FILLED`` column is refused, as materialize refuses it, unless it is on the ACS spine alone and in a column that one of R2's own stages fills on the ACS rows first (``stage_filled_never_default``: - the take-up stage's SPM-unit take-up flags and engine-free fills, and the - SSI and Medicaid take-up flags). R2 expects staging to fill every other - never-default column (immigration, disability, income transfers, SSI - disability criteria); its reason for those says to re-run staging. + the take-up stage's SPM-unit take-up flags and engine-free fills, the SSI + and Medicaid take-up flags, and the tax units' ACA take-up and plan ratio). + R2 expects staging to fill every other never-default column (immigration, + disability, income transfers, SSI disability criteria, and the + microcosm#1720 inputs staging maps or draws on ACS rows); its reason for + those says to re-run staging. - A null in an ESI premium output is refused, as materialize refuses it. - A staging summary whose ``engine_versions`` names another policyengine-us than the installed one, or none, is refused, as materialize refuses it @@ -85,10 +87,13 @@ def stage_filled_never_default(release: Any) -> frozenset[tuple[str, str]]: Materialize's ACS take-up stage fills the SPM-unit take-up flags, EITC take-up and the engine-free fills; its SSI/Medicaid take-up stage fills - those two flags. + those two flags, and its ACA take-up stage the tax units' ACA take-up + and plan ratio (microcosm#1720). R2's reasons for every other never-default column (immigration, - disability, income transfers, SSI disability criteria) say to re-run - staging, and a null there stops materialize on any spine. + disability, income transfers, SSI disability criteria, the + microcosm#1720 staged inputs) say to re-run staging, and a null there + stops materialize on any spine. Staged columns therefore never join this + list. """ filled = frozenset( @@ -100,6 +105,7 @@ def stage_filled_never_default(release: Any) -> frozenset[tuple[str, str]]: ("person", column) for column in release.ACS_LOCAL_SSI_MEDICAID_TAKE_UP_COLUMNS ), + *(("tax_unit", column) for column in release.ACS_LOCAL_ACA_TAKE_UP_COLUMNS), } ) unknown = sorted(filled - set(release.NEVER_DEFAULT_FILLED))