diff --git a/README.md b/README.md index ea1d0d5..04edfc8 100644 --- a/README.md +++ b/README.md @@ -174,6 +174,32 @@ If a version bump takes the function past 225 MiB, the install comes back, and t An install that stops partway leaves its temporary files in `/tmp`. If a complete install no longer fits beside them, every request on that instance fails with "No space left on device" until the platform replaces it. `tests/test_deploy_footprint.py` fails when the function passes 225 MiB, and when a complete install stops fitting on top of a stopped one. If the first fails after a version bump, trim another package, or accept the install and update this section. If the second fails, trim another package or give one a URL source. `main` requires no checks, so a failing run warns the author of a bump and doesn't block its merge. +## County from ZIP + +The form asks for a ZIP and no county. The API resolves the county, so the form, share links, direct API calls and the Modal fallback all follow one rule: + +1. An explicit `county`, such as a share link's `county=MIDDLESEX_COUNTY_MA`, always wins. +2. Otherwise the household gets the ZIP's first county in its state. A ZIP that spans counties lists the county with the most 2020 Census residents first, and a tie goes to the lower county code. +3. A ZIP code tabulation area (ZCTA) with no residents ranks its counties by land area. +4. A ZIP with no ZCTA of its own, such as a post-office-box ZIP, uses GeoNames' county, or else the first county in its state of the ZCTA the crosswalk gives it. +5. A ZIP with no county in the household's state resolves to nothing. policyengine-us then uses the state's first county alphabetically, and the results page says so. + +A series response carries a `location` block saying which county the calculation used and why (`source` is `explicit`, `zip` or `none`). When a ZIP spans counties, the results page shows each county's share of the ZIP's residents and lets the user pick another. The choice goes in the share link, and editing the ZIP clears it. The API also sends the ZIP to policyengine-us, because Los Angeles County's rating area reads it. + +The small-area rent variables read the ZIP too, but no household takes up housing assistance. CliffWatch has no input for whether a household holds a voucher (#30), and its rent field also takes mortgage payments, so wherever the ZIP carries a payment standard the engine would otherwise pay a voucher's subsidy to renters and homeowners alike. + +policyengine-us finds a county's ACA rating area by joining the county's code to its `aca_rating_areas.csv`, and it gives rating area 1 to any county the join misses. That file spells 31 counties differently from their codes: `BAYLOR_TX` for `BAYLOR_COUNTY_TX`, `DONA_ANA_NM` for `DOÑA_ANA_COUNTY_NM`, and the former Valdez-Cordova and Wade Hampton rows for the census areas that replaced them. `RATING_AREA_OVERRIDES` in `cliff_watch/zip_county.py` sends those counties' rating areas with the county. Oglala Lakota County, South Dakota, has no row under any name and keeps rating area 1. `tests/test_zip_county_engine.py` fails when an engine update changes those rows or fixes the names, so the list goes when the gap does. + +policyengine-us has no benchmark premium for three counties: Calhoun and Edgefield in South Carolina, and Gulf in Florida. A household there reads no premium tax credit, so `location.has_benchmark_premium` turns false and the results page says so. `tests/test_zip_county_engine.py` compares that list with the engine and fails when an engine update adds those rating areas, so the note goes when the gap does. + +`scripts/build_zip_county.py` builds `cliff_watch/data/zip_county.json.gz`. It reads the [Census 2020 ZCTA-county relationship file](https://www.census.gov/geographies/reference-files/time-series/geo/relationship-files.html), [2020 DHC table P1](https://api.census.gov/data/2020/dec/dhc) at summary level 881, [GeoNames US postal codes](https://www.geonames.org/) ([CC BY 4.0](https://creativecommons.org/licenses/by/4.0/); the table keeps each ZIP's county and drops the rest) and the UDS Mapper ZIP-to-ZCTA crosswalk as `policyengine-us-data` stored it. The script's docstring lists the sources, and the table's `meta` block records each downloaded file's hash. + +Rebuild the table when `policyengine-us` renames a county; `tests/test_zip_county.py` fails if a code stops being an engine county. + +```bash +CENSUS_API_KEY=... uv run python scripts/build_zip_county.py --cache-dir /tmp/zip-county +``` + ## Quick CLI Smoke Test You can also run the calculator without the frontend: @@ -189,7 +215,7 @@ python3 -m cliff_watch.calculator examples/sample_household.json --mode series - Household inputs are person-based in v1, with each family member entered individually by type and age. - Earnings are assigned to the first adult and held constant over the year. - A second adult is treated as a spouse, and later adults are modeled as additional household members in the same household unit. -- County-specific refinements are not exposed in the UI yet. +- The form has no county field. The API resolves the county from the ZIP, as [County from ZIP](#county-from-zip) describes. - The modeled bundle is intentionally narrower than every possible administrative program. ## License diff --git a/api/_shared.py b/api/_shared.py index c3b3ecf..e922f56 100644 --- a/api/_shared.py +++ b/api/_shared.py @@ -15,6 +15,7 @@ calculate_household_types, calculate_income_series, household_input_from_dict, + household_location, ) from cliff_watch.config import ( CCDF_MODELED_STATES, @@ -141,6 +142,7 @@ def compute_series( (item["net_resources"] for item in data), default=0, ), + "location": household_location(payload), } diff --git a/changelog.d/zip-to-county.fixed.md b/changelog.d/zip-to-county.fixed.md new file mode 100644 index 0000000..66e9011 --- /dev/null +++ b/changelog.d/zip-to-county.fixed.md @@ -0,0 +1 @@ +Read each household's county from its ZIP, so premium tax credits and the other county rules use the household's own county instead of its state's first county alphabetically. An explicit `county` in a share link still wins. A ZIP that spans counties takes the county with the most 2020 Census residents, and the results page names that county, quotes its share of the ZIP's residents and offers the others. The page also says when policyengine-us holds no benchmark premium for a county. CliffWatch now sends the ACA rating area for the 31 counties that the engine's rating-area file spells differently from their codes, which its name join had priced as rating area 1. Links that named Los Angeles County no longer show a housing voucher subsidy: CliffWatch has no input for whether a household holds a voucher (#30), and its rent field also takes mortgage payments, so no household takes one up. diff --git a/cliff_watch/calculator.py b/cliff_watch/calculator.py index 5f84ea8..d1939a2 100644 --- a/cliff_watch/calculator.py +++ b/cliff_watch/calculator.py @@ -34,6 +34,12 @@ STATE_PROGRAM_OVERRIDES, STATE_TANF_VARIABLES, ) +from cliff_watch.zip_county import ( + county_for_zip, + describe_location, + normalize_zip, + rating_area_override, +) class CalculatorDependencyError(RuntimeError): @@ -60,6 +66,7 @@ class HouseholdInput: earned_income: float year: int = DEFAULT_YEAR county: str | None = None + zip: str | None = None people: tuple[HouseholdMemberInput, ...] = () household_type: str | None = None filing_status: str | None = None @@ -285,7 +292,7 @@ def _filtered_program_value( def _normalize_county(county: str | None, state: str) -> str | None: - if county is None: + if county is None or not county.strip(): return None normalized = ( @@ -301,6 +308,22 @@ def _normalize_county(county: str | None, state: str) -> str | None: return f"{normalized}_{state}" +def resolved_county(payload: HouseholdInput) -> str | None: + """The county the engine gets: the explicit one, or else the ZIP's.""" + return _normalize_county(payload.county, payload.state) or county_for_zip( + payload.zip, payload.state + ) + + +def household_location(payload: HouseholdInput) -> dict[str, Any]: + """The county a calculation uses and where it came from, for the page to show.""" + return describe_location( + payload.zip, + payload.state, + _normalize_county(payload.county, payload.state), + ) + + def _compat_people_from_template( household_type: str, ) -> tuple[HouseholdMemberInput, ...]: @@ -633,9 +656,17 @@ def _base_household_groups( "state_name": {year: payload.state}, } - county = _normalize_county(payload.county, payload.state) + county = resolved_county(payload) if county: household["county"] = {year: county} + # The engine's rating-area file names these counties differently from + # its county codes, so its join misses them (see RATING_AREA_OVERRIDES). + rating_area = rating_area_override(county) + if rating_area is not None: + household["slcsp_rating_area"] = {year: rating_area} + zip_code = normalize_zip(payload.zip) + if zip_code: + household["zip_code"] = {year: zip_code} tax_unit = { "members": member_ids, @@ -661,6 +692,13 @@ def _base_household_groups( "receives_housing_assistance": { year: _program_included(payload, "housing_assistance") }, + # CliffWatch has no input for whether a household holds a housing + # voucher (#30), and its rent field also takes mortgage payments. With + # housing assistance among its programs, receives_housing_assistance + # makes a household eligible, so wherever the ZIP or county carries a + # payment standard the engine would pay a voucher's subsidy to renters + # and homeowners alike. No household takes it up until that input exists. + "takes_up_housing_assistance_if_eligible": {year: False}, } if childcare_expenses > 0: spm_unit["childcare_expenses"] = {year: childcare_expenses} @@ -1246,7 +1284,8 @@ def _simulate_core(payload: HouseholdInput) -> dict[str, Any]: "state": payload.state, "earned_income": payload.earned_income, "year": payload.year, - "county": payload.county, + "county": resolved_county(payload), + "zip": normalize_zip(payload.zip), "household_type": payload.household_type, "filing_status": _effective_filing_status(payload), "people": [ @@ -2071,6 +2110,7 @@ def numeric(field: str) -> float: earned_income=numeric("earned_income"), year=int(data.get("year", DEFAULT_YEAR)), county=data.get("county"), + zip=normalize_zip(data.get("zip")), people=people, household_type=data.get("household_type"), filing_status=data.get("filing_status"), diff --git a/cliff_watch/data/zip_county.json.gz b/cliff_watch/data/zip_county.json.gz new file mode 100644 index 0000000..06e5648 Binary files /dev/null and b/cliff_watch/data/zip_county.json.gz differ diff --git a/cliff_watch/variable_graph.py b/cliff_watch/variable_graph.py index ea5bac5..ecc25a4 100644 --- a/cliff_watch/variable_graph.py +++ b/cliff_watch/variable_graph.py @@ -60,7 +60,11 @@ "when a subsidy pays part of it. Kept as before; a follow-up weighs " "dropping it." ), - "county": "The household's county as entered.", + "county": ( + "The household's county as entered, or else the county its ZIP resolves " + "to (cliff_watch/zip_county.py). The formula would give the state's " + "first county alphabetically. The JS builder sends only an entered county." + ), "filing_status": ( "The household's filing status as entered, or as derived from the " "household when none is entered." @@ -77,6 +81,13 @@ "is_full_time_student": ( "Entered for each person; the formula infers it from school enrollment." ), + "slcsp_rating_area": ( + "Set only for the 31 counties in RATING_AREA_OVERRIDES, to the rating " + "area the engine's aca_rating_areas.csv holds for them under another " + "name. The formula joins the county's code to that file, misses these " + "names and gives rating area 1. Python only: the JS builder doesn't " + "carry this map." + ), "ssi": "An SSI amount the household reports receiving replaces the computed one.", "state_name": "The household's state as entered.", } diff --git a/cliff_watch/zip_county.py b/cliff_watch/zip_county.py new file mode 100644 index 0000000..8f7294c --- /dev/null +++ b/cliff_watch/zip_county.py @@ -0,0 +1,201 @@ +"""Map a household's ZIP code to its county. + +The form asks for a ZIP and no county, and policyengine-us gives a household with +no county its state's first county. This module closes that gap. It reads +`data/zip_county.json.gz`, which `scripts/build_zip_county.py` builds from Census +and GeoNames data, and resolves a county by this rule: + +1. An explicit county, such as a share link's `county=`, always wins. +2. Otherwise the household gets the ZIP's first county in the household's state. + A ZIP with several counties lists the one with the most 2020 Census residents + first, ties going to the lower county code. +3. A ZIP with no county in that state resolves to nothing, and the engine then + uses the state's first county. `describe_location` reports this as "none", so + the page can say so. + +It also lists two engine gaps by county: the counties whose benchmark premium the +engine lacks, and the counties whose ACA rating area its name join misses. + +This module imports no engine code, so a request pays only for reading the table. +""" + +from __future__ import annotations + +import gzip +import json +import re +from dataclasses import dataclass +from functools import lru_cache +from pathlib import Path +from typing import Any + +DATA_PATH = Path(__file__).resolve().parent / "data" / "zip_county.json.gz" + +# policyengine-us's `gov.aca.state_rating_area_cost` has no row for these counties' +# rating areas (South Carolina 9 and 19, Florida 22), so a household there reads a +# $0 benchmark premium and no premium tax credit. The page says so. A test compares +# this set with the engine, so an engine update that adds the rows fails until the +# set shrinks. +COUNTIES_WITHOUT_BENCHMARK = frozenset( + {"CALHOUN_COUNTY_SC", "EDGEFIELD_COUNTY_SC", "GULF_COUNTY_FL"} +) + +# policyengine-us finds a county's ACA rating area by joining the county's name to +# `gov/hhs/medicaid/geography/aca_rating_areas.csv`, and gives rating area 1 to any +# county the join misses. That file names these counties differently from the +# engine's `County` codes, so the calculator sends each one's rating area as an +# input. Each entry gives the file's row and the rating area that row holds. Most +# rows drop a word or a letter (`BAYLOR_TX`, `DONA_ANA_NM`). Chugach and Copper +# River read the row of Valdez-Cordova, the census area the Census Bureau split +# into them in 2019, and Kusilvak reads Wade Hampton's, its name until 2015. The +# file has no row for Oglala Lakota County, South Dakota, under that name or under +# Shannon County, its name until 2015, so it keeps the engine's rating area 1. +# Tests compare this map with the engine, so an engine update that renames a row +# fails until the entry goes. +RATING_AREA_OVERRIDES = { + "ADAMS_COUNTY_MS": ("ADAMS_MS", 6), + "BAYLOR_COUNTY_TX": ("BAYLOR_TX", 24), + "BEN_HILL_COUNTY_GA": ("BEN_HILL_GA", 15), + "BRYAN_COUNTY_GA": ("BRYAN_GA", 14), + "CHOCTAW_COUNTY_MS": ("CHOCTAW_MS", 6), + "CHUGACH_CENSUS_AREA_AK": ("VALDEZCORDOVA_AK", 1), + "CHURCHILL_COUNTY_NV": ("CHURCHILL_NV", 4), + "CLARK_COUNTY_KY": ("CLARK_KY", 5), + "COPPER_RIVER_CENSUS_AREA_AK": ("VALDEZCORDOVA_AK", 1), + "CUMBERLAND_COUNTY_KY": ("CUMBERLAND_KY", 4), + "DAWSON_COUNTY_GA": ("DAWSON_GA", 10), + "DEUEL_COUNTY_NE": ("DEUEL_NE", 4), + "DOÑA_ANA_COUNTY_NM": ("DONA_ANA_NM", 3), + "HAINES_BOROUGH_AK": ("HAINES_AK", 3), + "HARDEMAN_COUNTY_TX": ("HARDEMAN_TX", 24), + "HEMPHILL_COUNTY_TX": ("HEMPHILL_TX", 2), + "JIM_HOGG_COUNTY_TX": ("JIM_HOGG_TX", 12), + "JOHNSON_COUNTY_GA": ("JOHNSON_GA", 11), + "KIMBLE_COUNTY_TX": ("KIMBLE_TX", 17), + "KUSILVAK_CENSUS_AREA_AK": ("WADE_HAMPTON_AK", 2), + "LASALLE_PARISH_LA": ("LA_SALLE_LA", 6), + "LOGAN_COUNTY_NE": ("LOGAN_NE", 4), + "LOS_ALAMOS_COUNTY_NM": ("LOS_ALAMOS_NM", 5), + "MITCHELL_COUNTY_NC": ("MITCHELL_NC", 1), + "NESHOBA_COUNTY_MS": ("NESHOBA_MS", 6), + "PASQUOTANK_COUNTY_NC": ("PASQUOTANK_NC", 12), + "PETERSBURG_BOROUGH_AK": ("PETERSBURG_AK", 3), + "PRINCE_OF_WALES_HYDER_CENSUS_AREA_AK": ("PRINCE_OF_WALESHYDER_AK", 3), + "REAGAN_COUNTY_TX": ("REAGAN_TX", 17), + "TOOMBS_COUNTY_GA": ("TOOMBS_GA", 11), + "WALTHALL_COUNTY_MS": ("WALTHALL_MS", 6), +} +COUNTIES_WITHOUT_RATING_AREA_ROW = frozenset({"OGLALA_LAKOTA_COUNTY_SD"}) + + +def rating_area_override(county: str | None) -> int | None: + """The ACA rating area to send for a county the engine's join misses, if any.""" + entry = RATING_AREA_OVERRIDES.get(county) if county else None + return entry[1] if entry else None + + +_NON_DIGITS = re.compile(r"[^0-9]") + + +@dataclass(frozen=True) +class CountyOption: + code: str + name: str + residents: int | None + resident_share: float | None + + +@dataclass(frozen=True) +class _Table: + names_by_code: dict[str, str] + codes: tuple[str, ...] + zips: dict[str, list[list[int | None]]] + + +@lru_cache(maxsize=1) +def _table() -> _Table: + with gzip.open(DATA_PATH, "rt", encoding="utf-8") as file: + document = json.load(file) + counties = document["counties"] + return _Table( + names_by_code={code: name for code, name in counties}, + codes=tuple(code for code, _ in counties), + zips=document["zips"], + ) + + +def normalize_zip(value: Any) -> str | None: + """Return the first five digits, as the form does, or None if there are fewer.""" + digits = _NON_DIGITS.sub("", "" if value is None else str(value))[:5] + return digits if len(digits) == 5 else None + + +def counties_for_zip(zip_code: Any, state: str | None) -> tuple[CountyOption, ...]: + """The ZIP's counties in `state`, in resolution order. + + `resident_share` is the county's share of everyone in the ZIP, across state + lines. It is None where the table records no residents. + """ + normalized = normalize_zip(zip_code) + if normalized is None or not state: + return () + table = _table() + rows = table.zips.get(normalized) + if not rows: + return () + total_residents = sum(residents or 0 for _, residents in rows) + suffix = f"_{state}" + options = [] + for index, residents in rows: + code = table.codes[index] + if code.endswith(suffix): + options.append( + CountyOption( + code=code, + name=table.names_by_code[code], + residents=residents, + resident_share=( + residents / total_residents + if residents is not None and total_residents + else None + ), + ) + ) + return tuple(options) + + +def county_for_zip(zip_code: Any, state: str | None) -> str | None: + """The county code a household in this ZIP and state resolves to, if any.""" + options = counties_for_zip(zip_code, state) + return options[0].code if options else None + + +def describe_location( + zip_code: Any, + state: str | None, + explicit_county: str | None = None, +) -> dict[str, Any]: + """Say which county a calculation uses and why, for the page to show.""" + options = counties_for_zip(zip_code, state) + if explicit_county: + county, source = explicit_county, "explicit" + elif options: + county, source = options[0].code, "zip" + else: + county, source = None, "none" + return { + "zip": normalize_zip(zip_code), + "county": county, + "county_name": _table().names_by_code.get(county) if county else None, + "source": source, + "has_benchmark_premium": county not in COUNTIES_WITHOUT_BENCHMARK, + "counties": [ + { + "code": option.code, + "name": option.name, + "residents": option.residents, + "resident_share": option.resident_share, + } + for option in options + ], + } diff --git a/frontend/src/App.css b/frontend/src/App.css index 209200a..6bf88f6 100644 --- a/frontend/src/App.css +++ b/frontend/src/App.css @@ -1218,6 +1218,16 @@ body { color: #b45309; } +.county-note .chart-note { + margin-bottom: 0.5rem; + color: var(--color-text); +} + +.county-picker { + max-width: 24rem; + margin-bottom: 1rem; +} + .charts-grid { display: grid; grid-template-columns: 1fr 1fr; diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index 96834e5..02a306e 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -236,6 +236,14 @@ function App() { } } + // The county picker in the results reruns the chart at once. Editing the ZIP + // clears the choice, since a county belongs to the ZIP it was chosen under. + const handleCountyChange = (county) => { + const nextDraft = { ...draft, county } + setDraft(nextDraft) + handleCalculate(combineDraftAndScenarioToInputs(nextDraft, scenario, metadata)) + } + useEffect(() => { handleCalculateRef.current = handleCalculate }) @@ -299,6 +307,7 @@ function App() { hasCalculated={hasCalculated} error={error} seriesError={seriesError} + onCountyChange={handleCountyChange} /> diff --git a/frontend/src/__fixtures__/policyengine-us-variable-graph.json b/frontend/src/__fixtures__/policyengine-us-variable-graph.json index 6a7e638..13ec066 100644 --- a/frontend/src/__fixtures__/policyengine-us-variable-graph.json +++ b/frontend/src/__fixtures__/policyengine-us-variable-graph.json @@ -2515,6 +2515,11 @@ "adds": [], "subtracts": [] }, + "slcsp_rating_area": { + "entity": "household", + "adds": [], + "subtracts": [] + }, "snap": { "entity": "spm_unit", "adds": [], @@ -2676,6 +2681,11 @@ "adds": [], "subtracts": [] }, + "takes_up_housing_assistance_if_eligible": { + "entity": "spm_unit", + "adds": [], + "subtracts": [] + }, "takes_up_medicaid_if_eligible": { "entity": "person", "adds": [], @@ -3076,6 +3086,11 @@ "entity": "spm_unit", "adds": [], "subtracts": [] + }, + "zip_code": { + "entity": "household", + "adds": [], + "subtracts": [] } } } diff --git a/frontend/src/components/ResultsPanel.jsx b/frontend/src/components/ResultsPanel.jsx index 2346b90..545a095 100644 --- a/frontend/src/components/ResultsPanel.jsx +++ b/frontend/src/components/ResultsPanel.jsx @@ -2,7 +2,8 @@ import { useState } from 'react' import BenefitChart from './BenefitChart' import CliffInsights from './CliffInsights' import { formatCurrency } from '../dataLookup' -import { householdSummary } from '../utils/householdSummary' +import { countyContext, countyDraftValue } from '../utils/countyContext' +import { householdStateName, householdSummary } from '../utils/householdSummary' import { buildShareUrl } from '../utils/urlState' function copyTextFallback(text) { @@ -80,6 +81,30 @@ function ShareButton({ inputs }) { ) } +function CountyNote({ context, location, onCountyChange }) { + if (!context.note) return null + + return ( +
+

{context.note}

+ {context.options.length > 1 && ( +
+ + +
+ )} +
+ ) +} + function ResultsPanel({ metadata, inputs, @@ -89,6 +114,7 @@ function ResultsPanel({ hasCalculated, error, seriesError, + onCountyChange, }) { if (error) { return ( @@ -110,6 +136,9 @@ function ResultsPanel({ ) } + const location = seriesData?.location + const county = countyContext(location, householdStateName(inputs, metadata)) + return (
@@ -119,10 +148,15 @@ function ResultsPanel({

- {householdSummary(inputs, metadata)} + {householdSummary(inputs, metadata, county.countyName)}

{seriesData ? ( <> +

Calculated through {formatCurrency(seriesData?.max_earned_income || 0)}/year in {formatCurrency(seriesData?.step_annual || 0)}/year wage and salary steps {seriesData?.refined_zone_count diff --git a/frontend/src/policyengineApi.js b/frontend/src/policyengineApi.js index 06c9f87..a17c00b 100644 --- a/frontend/src/policyengineApi.js +++ b/frontend/src/policyengineApi.js @@ -685,6 +685,9 @@ export function buildSituation(payload, options = {}) { takes_up_snap_if_eligible: { [year]: programIncluded(payload, 'snap', options.metadata) }, takes_up_tanf_if_eligible: { [year]: programIncluded(payload, 'tanf', options.metadata) }, receives_housing_assistance: { [year]: programIncluded(payload, 'housing_assistance', options.metadata) }, + // No input says whether a household holds a voucher (#30), so none takes + // one up, as in cliff_watch/calculator.py. + takes_up_housing_assistance_if_eligible: { [year]: false }, } if (ccdfModeled) { spmUnitEntity.child_care_subsidies = { [year]: null } diff --git a/frontend/src/utils/countyContext.js b/frontend/src/utils/countyContext.js new file mode 100644 index 0000000..233c1db --- /dev/null +++ b/frontend/src/utils/countyContext.js @@ -0,0 +1,112 @@ +// What the results panel says about the county a calculation used, from the +// `location` block the API returns with a series. A pure function, so the wording +// and the choices stay testable without rendering React. + +function formatShare(share) { + if (share === null || share === undefined) return null + const percent = Math.round(share * 100) + if (percent < 1) return 'under 1%' + if (percent >= 100) return share < 1 ? 'over 99%' : '100%' + return `${percent}%` +} + +function optionLabel(county) { + const share = formatShare(county.resident_share) + return share ? `${county.name} (${share} of residents)` : county.name +} + +function usedCountyClause(county, isFirst) { + const share = formatShare(county.resident_share) + if (share) return `This chart uses ${county.name}, home to ${share} of its residents.` + // A ZIP with no residents ranks its counties by land area. + return isFirst + ? `This chart uses ${county.name}, which has the largest share of its land.` + : `This chart uses ${county.name}.` +} + +// What a link naming a county outside the ZIP says about the ZIP's own county. +// The ZIP's first county can hold well under half its residents, so the line +// quotes its share rather than calling the ZIP mostly that county's. +function zipCountyLine(zip, counties) { + if (!counties.length) return '' + const [first] = counties + if (counties.length === 1) return ` ZIP ${zip} lies in ${first.name}.` + const share = formatShare(first.resident_share) + const reason = share + ? `home to ${share} of its residents` + : 'which has the largest share of its land' + return ` ZIP ${zip} covers more than one county, and the chart would otherwise use ${first.name}, ${reason}.` +} + +const EMPTY_CONTEXT = Object.freeze({ + countyName: null, + note: null, + options: [], + selected: null, +}) + +export function countyContext(location, stateName = '') { + if (!location) return EMPTY_CONTEXT + + const context = countyChoices(location, stateName) + if (location.has_benchmark_premium !== false) return context + + const gap = `CliffWatch has no benchmark premium for ${context.countyName}, so this chart shows no premium tax credit.` + return { ...context, note: context.note ? `${context.note} ${gap}` : gap } +} + +function countyChoices(location, stateName) { + const { county, source, zip } = location + const countyName = location.county_name || county || null + const counties = location.counties || [] + + if (source === 'none' || !county) { + const place = stateName === 'District of Columbia' ? `the ${stateName}` : stateName + return { + ...EMPTY_CONTEXT, + note: zip + ? `CliffWatch can't place ZIP ${zip} in a county in ${place}, so rules that vary by county use the first county alphabetically there.` + : `This household has no ZIP code, so rules that vary by county use the first county alphabetically in ${place}.`, + } + } + + const used = counties.find((option) => option.code === county) + + if (!used) { + // A share link named a county the ZIP doesn't cover. + return { + countyName, + note: `This link names ${countyName}, so this chart uses it.${zipCountyLine(zip, counties)}`, + options: counties.length + ? [ + { code: county, label: countyName }, + ...counties.map((option) => ({ + code: option.code, + label: optionLabel(option), + })), + ] + : [], + selected: county, + } + } + + if (counties.length === 1) { + return { ...EMPTY_CONTEXT, countyName, selected: county } + } + + return { + countyName, + note: `ZIP ${zip} covers more than one county. ${usedCountyClause(used, used === counties[0])}`, + options: counties.map((option) => ({ + code: option.code, + label: optionLabel(option), + })), + selected: county, + } +} + +// What a county choice stores in the draft: the ZIP's own county goes back to +// null, so a share link names a county only when it overrides the ZIP. +export function countyDraftValue(code, location) { + return code === location?.counties?.[0]?.code ? null : code +} diff --git a/frontend/src/utils/countyContext.test.js b/frontend/src/utils/countyContext.test.js new file mode 100644 index 0000000..5e28e5a --- /dev/null +++ b/frontend/src/utils/countyContext.test.js @@ -0,0 +1,317 @@ +import assert from 'node:assert/strict' +import fc from 'fast-check' +import { test } from 'vitest' + +import { countyContext, countyDraftValue } from './countyContext.js' + +const MIDDLESEX = { + code: 'MIDDLESEX_COUNTY_MA', + name: 'Middlesex County', + residents: 9116, + resident_share: 0.4, +} +const NORFOLK = { + code: 'NORFOLK_COUNTY_MA', + name: 'Norfolk County', + residents: 9024, + resident_share: 0.396, +} +const SUFFOLK = { + code: 'SUFFOLK_COUNTY_MA', + name: 'Suffolk County', + residents: 4486, + resident_share: 0.197, +} + +const location = (overrides) => ({ + zip: '02467', + county: 'MIDDLESEX_COUNTY_MA', + county_name: 'Middlesex County', + source: 'zip', + counties: [MIDDLESEX, NORFOLK, SUFFOLK], + ...overrides, +}) + +test('countyContext says nothing before a series arrives', () => { + assert.deepEqual(countyContext(undefined), { + countyName: null, + note: null, + options: [], + selected: null, + }) +}) + +test('a ZIP in one county names it and offers no choice', () => { + const context = countyContext(location({ + zip: '02139', + counties: [{ ...MIDDLESEX, resident_share: 1 }], + })) + + assert.equal(context.countyName, 'Middlesex County') + assert.equal(context.note, null) + assert.deepEqual(context.options, []) +}) + +test('a ZIP across counties states the rule and offers each county', () => { + const context = countyContext(location()) + + assert.equal( + context.note, + 'ZIP 02467 covers more than one county. This chart uses Middlesex County, home to 40% of its residents.', + ) + assert.deepEqual(context.options, [ + { code: 'MIDDLESEX_COUNTY_MA', label: 'Middlesex County (40% of residents)' }, + { code: 'NORFOLK_COUNTY_MA', label: 'Norfolk County (40% of residents)' }, + { code: 'SUFFOLK_COUNTY_MA', label: 'Suffolk County (20% of residents)' }, + ]) + assert.equal(context.selected, 'MIDDLESEX_COUNTY_MA') +}) + +test('a county chosen from the ZIP’s list reads like the default', () => { + const context = countyContext(location({ + county: 'NORFOLK_COUNTY_MA', + county_name: 'Norfolk County', + source: 'explicit', + })) + + assert.equal( + context.note, + 'ZIP 02467 covers more than one county. This chart uses Norfolk County, home to 40% of its residents.', + ) + assert.equal(context.selected, 'NORFOLK_COUNTY_MA') +}) + +test('a link naming a county outside the ZIP says so and offers the ZIP’s county', () => { + const context = countyContext(location({ + zip: '02139', + county: 'BARNSTABLE_COUNTY_MA', + county_name: 'Barnstable County', + source: 'explicit', + counties: [{ ...MIDDLESEX, resident_share: 1 }], + })) + + assert.equal( + context.note, + 'This link names Barnstable County, so this chart uses it. ZIP 02139 lies in Middlesex County.', + ) + assert.deepEqual(context.options.map((option) => option.code), [ + 'BARNSTABLE_COUNTY_MA', + 'MIDDLESEX_COUNTY_MA', + ]) +}) + +test('a link naming a county outside a ZIP across counties quotes the ZIP county’s share', () => { + // Middlesex holds 40% of ZIP 02467's residents, so "mostly" would overstate it. + const context = countyContext(location({ + county: 'BARNSTABLE_COUNTY_MA', + county_name: 'Barnstable County', + source: 'explicit', + })) + + assert.equal( + context.note, + 'This link names Barnstable County, so this chart uses it. ZIP 02467 covers more than one county, and the chart would otherwise use Middlesex County, home to 40% of its residents.', + ) + assert.deepEqual(context.options.map((option) => option.label), [ + 'Barnstable County', + 'Middlesex County (40% of residents)', + 'Norfolk County (40% of residents)', + 'Suffolk County (20% of residents)', + ]) +}) + +test('a link naming a county outside a ZIP with no residents names the county with most land', () => { + const context = countyContext(location({ + county: 'BARNSTABLE_COUNTY_MA', + county_name: 'Barnstable County', + source: 'explicit', + counties: [ + { ...MIDDLESEX, residents: null, resident_share: null }, + { ...NORFOLK, residents: null, resident_share: null }, + ], + })) + + assert.equal( + context.note, + 'This link names Barnstable County, so this chart uses it. ZIP 02467 covers more than one county, and the chart would otherwise use Middlesex County, which has the largest share of its land.', + ) +}) + +// A ZIP's counties as the API sends them: residents descending. +const zipCountiesArb = fc + .array(fc.integer({ min: 1, max: 50_000 }), { minLength: 1, maxLength: 5 }) + .map((counts) => { + const sorted = [...counts].sort((a, b) => b - a) + const total = sorted.reduce((sum, count) => sum + count, 0) + return sorted.map((residents, index) => ({ + code: `COUNTY_${index}_MA`, + name: `County ${index}`, + residents, + resident_share: residents / total, + })) + }) + +test('every share a note quotes matches that county’s option, and no note says mostly', () => { + fc.assert( + fc.property(zipCountiesArb, fc.boolean(), fc.nat(), (counties, outside, pick) => { + const index = pick % counties.length + const chosen = outside + ? { code: 'OUTSIDE_COUNTY_MA', name: 'Outside County' } + : counties[index] + const { note, options } = countyContext({ + zip: '02467', + county: chosen.code, + county_name: chosen.name, + source: !outside && index === 0 ? 'zip' : 'explicit', + counties, + }) + if (note === null) return + assert.doesNotMatch(note, /\bmostly\b|\bmost of\b/) + const quoted = [...note.matchAll(/(County \d+), home to (under 1%|over 99%|\d+%) of its residents/g)] + for (const [, name, share] of quoted) { + assert.ok( + options.some((option) => option.label === `${name} (${share} of residents)`), + `${note} quotes ${name} at ${share}`, + ) + } + }), + ) +}) + +test('a link naming a county for an unplaced ZIP offers nothing else', () => { + const context = countyContext(location({ + zip: '99999', + county: 'BARNSTABLE_COUNTY_MA', + county_name: 'Barnstable County', + source: 'explicit', + counties: [], + })) + + assert.equal(context.note, 'This link names Barnstable County, so this chart uses it.') + assert.deepEqual(context.options, []) +}) + +test('a ZIP with no county in the state says the default applies', () => { + const context = countyContext( + location({ zip: '20147', county: null, county_name: null, source: 'none', counties: [] }), + 'District of Columbia', + ) + + assert.equal(context.countyName, null) + assert.equal( + context.note, + "CliffWatch can't place ZIP 20147 in a county in the District of Columbia, so rules that vary by county use the first county alphabetically there.", + ) + + assert.equal( + countyContext( + location({ zip: '02139', county: null, county_name: null, source: 'none', counties: [] }), + 'California', + ).note, + "CliffWatch can't place ZIP 02139 in a county in California, so rules that vary by county use the first county alphabetically there.", + ) +}) + +test('a household with no ZIP says the same without naming one', () => { + const context = countyContext( + location({ zip: null, county: null, county_name: null, source: 'none', counties: [] }), + 'Massachusetts', + ) + + assert.equal( + context.note, + 'This household has no ZIP code, so rules that vary by county use the first county alphabetically in Massachusetts.', + ) +}) + +test('a ZIP with no residents falls back to land in its wording', () => { + const context = countyContext(location({ + counties: [ + { ...MIDDLESEX, residents: null, resident_share: null }, + { ...NORFOLK, residents: null, resident_share: null }, + ], + })) + + assert.equal( + context.note, + 'ZIP 02467 covers more than one county. This chart uses Middlesex County, which has the largest share of its land.', + ) + assert.deepEqual(context.options.map((option) => option.label), [ + 'Middlesex County', + 'Norfolk County', + ]) +}) + +test('a picked county in a ZIP with no residents claims nothing about land', () => { + const context = countyContext(location({ + county: 'NORFOLK_COUNTY_MA', + county_name: 'Norfolk County', + source: 'explicit', + counties: [ + { ...MIDDLESEX, residents: null, resident_share: null }, + { ...NORFOLK, residents: null, resident_share: null }, + ], + })) + + assert.equal( + context.note, + 'ZIP 02467 covers more than one county. This chart uses Norfolk County.', + ) +}) + +test('shares never round to a misleading 0% or 100%', () => { + const context = countyContext(location({ + counties: [ + { ...MIDDLESEX, resident_share: 0.998 }, + { ...NORFOLK, resident_share: 0.002 }, + ], + })) + + assert.deepEqual(context.options.map((option) => option.label), [ + 'Middlesex County (over 99% of residents)', + 'Norfolk County (under 1% of residents)', + ]) +}) + +test('a county with no benchmark premium says the chart shows no credit', () => { + const context = countyContext(location({ + zip: '29824', + county: 'EDGEFIELD_COUNTY_SC', + county_name: 'Edgefield County', + has_benchmark_premium: false, + counties: [{ + code: 'EDGEFIELD_COUNTY_SC', + name: 'Edgefield County', + residents: 11000, + resident_share: 1, + }], + })) + + assert.equal(context.countyName, 'Edgefield County') + assert.equal( + context.note, + 'CliffWatch has no benchmark premium for Edgefield County, so this chart shows no premium tax credit.', + ) + assert.deepEqual(context.options, []) +}) + +test('a ZIP across counties keeps its note when its county has no benchmark premium', () => { + const context = countyContext(location({ has_benchmark_premium: false })) + + assert.equal( + context.note, + 'ZIP 02467 covers more than one county. This chart uses Middlesex County, home to 40% of its residents. CliffWatch has no benchmark premium for Middlesex County, so this chart shows no premium tax credit.', + ) + assert.equal(context.options.length, 3) +}) + +test('a county with a benchmark premium adds nothing', () => { + const context = countyContext(location({ has_benchmark_premium: true })) + + assert.doesNotMatch(context.note, /benchmark premium/) +}) + +test('choosing the ZIP’s own county clears the override', () => { + assert.equal(countyDraftValue('MIDDLESEX_COUNTY_MA', location()), null) + assert.equal(countyDraftValue('NORFOLK_COUNTY_MA', location()), 'NORFOLK_COUNTY_MA') +}) diff --git a/frontend/src/utils/householdSummary.js b/frontend/src/utils/householdSummary.js index 3170213..9a625a6 100644 --- a/frontend/src/utils/householdSummary.js +++ b/frontend/src/utils/householdSummary.js @@ -30,14 +30,22 @@ function formatPeopleGroup(people, kind, singular, plural) { ].filter(Boolean).join(' ') } -export function householdSummary(inputs, metadata) { - const people = inputs?.people || [] - const stateName = metadata?.states?.find((state) => state.code === inputs?.state)?.name +export function householdStateName(inputs, metadata) { + return metadata?.states?.find((state) => state.code === inputs?.state)?.name || inputs?.state || '' +} + +function placeName(stateName, countyName) { + if (!countyName || countyName === stateName) return stateName + return stateName ? `${countyName}, ${stateName}` : countyName +} + +export function householdSummary(inputs, metadata, countyName = null) { + const people = inputs?.people || [] return [ - stateName, + placeName(householdStateName(inputs, metadata), countyName), formatPeopleGroup(people, 'adult', 'adult', 'adults'), formatPeopleGroup(people, 'child', 'dependent', 'dependents'), ].filter(Boolean).join(' · ') diff --git a/frontend/src/utils/householdSummary.test.js b/frontend/src/utils/householdSummary.test.js index 1b2923a..2186838 100644 --- a/frontend/src/utils/householdSummary.test.js +++ b/frontend/src/utils/householdSummary.test.js @@ -24,6 +24,26 @@ test('householdSummary preserves the compact count summary without modifiers', ( ) }) +test('householdSummary leads with the county when the API names one', () => { + const people = [{ kind: 'adult', age: 33 }, { kind: 'child', age: 6 }, { kind: 'child', age: 10 }] + + assert.equal( + householdSummary({ state: 'MN', people }, metadata, 'Hennepin County'), + 'Hennepin County, Minnesota · 1 adult · 2 dependents', + ) +}) + +test('householdSummary names the District of Columbia once', () => { + assert.equal( + householdSummary( + { state: 'DC', people: [{ kind: 'adult', age: 33 }] }, + { states: [{ code: 'DC', name: 'District of Columbia' }] }, + 'District of Columbia', + ), + 'District of Columbia · 1 adult · 0 dependents', + ) +}) + test('householdSummary includes selected household member modifiers', () => { assert.equal( householdSummary({ diff --git a/frontend/src/utils/zipCounty.test.js b/frontend/src/utils/zipCounty.test.js new file mode 100644 index 0000000..41b8ed7 --- /dev/null +++ b/frontend/src/utils/zipCounty.test.js @@ -0,0 +1,110 @@ +// Share links and the form's ZIP rule, against the table the API reads. + +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import { gunzipSync } from 'node:zlib' +import { test } from 'vitest' + +import { buildHouseholdPayload, getZipState, hasValidZip } from '../dataLookup.js' +import { + combineDraftAndScenarioToInputs, + createInitialScenario, + inputsToDraft, + inputsToScenario, +} from '../wizard/cliffWatchDraft.js' +import { decodeInputs, encodeInputs } from './urlState.js' + +const metadata = { + year: 2026, + defaults: { chart_max_earned_income: 100000, series_step: 500 }, + states: [{ code: 'MA', name: 'Massachusetts' }], +} + +const ZIP_LINK = '?s=MA&zip=02139&ms=unmarried&p=33:a::0,6:c::0,10:c::0' +const COUNTY = 'MIDDLESEX_COUNTY_MA' + +function linkToInputs(search) { + const decoded = decodeInputs(search) + return combineDraftAndScenarioToInputs( + inputsToDraft(decoded), + { ...createInitialScenario(metadata), ...inputsToScenario(decoded, metadata) }, + metadata, + ) +} + +test('a link with only a ZIP sends the ZIP and no county', () => { + const payload = buildHouseholdPayload(linkToInputs(ZIP_LINK), metadata) + + assert.equal(payload.zip, '02139') + assert.equal(payload.county, null) +}) + +test('a link naming a county sends it and keeps it when re-encoded', () => { + const inputs = linkToInputs(`${ZIP_LINK}&county=${COUNTY}`) + const payload = buildHouseholdPayload(inputs, metadata) + + assert.equal(payload.county, COUNTY) + assert.equal(payload.zip, '02139') + assert.equal(new URLSearchParams(encodeInputs(inputs)).get('county'), COUNTY) +}) + +test('a link with only a ZIP gains no county when re-encoded', () => { + const params = new URLSearchParams(encodeInputs(linkToInputs(ZIP_LINK))) + + assert.equal(params.has('county'), false) + assert.equal(params.get('zip'), '02139') +}) + +test('the two links differ only in the county they send', () => { + const zipOnly = buildHouseholdPayload(linkToInputs(ZIP_LINK), metadata) + const named = buildHouseholdPayload(linkToInputs(`${ZIP_LINK}&county=${COUNTY}`), metadata) + + assert.deepEqual({ ...zipOnly, county: COUNTY }, named) +}) + +// The form takes a household's state from the ZIP. These ZIPs get a state that the +// table can't place them in, so the API answers `source: "none"` and the page says +// so. Two prefixes in the wizard's ZIP table cover most of them: it sends Northern +// Virginia's 201xx ZIPs to DC and DC's 569xx government ZIPs to Minnesota. A ZIP +// in those ranges passes only with that exact disagreement. Any other ZIP joining +// this list is a new disagreement to look at; the wizard fixing some of these +// fails nothing. +const KNOWN_FORM_STATE_MISMATCHES = new Set([ + '05501', '05544', '06390', '20588', '20598', '72643', '73301', '73344', '73960', '83414', +]) +const KNOWN_PREFIX_MISMATCHES = [ + { prefix: '201', formState: 'DC', tableState: 'VA' }, + { prefix: '569', formState: 'MN', tableState: 'DC' }, +] +const isKnownPrefixMismatch = (zip, formState, tableStates) => KNOWN_PREFIX_MISMATCHES.some( + (known) => zip.startsWith(known.prefix) + && formState === known.formState + && tableStates.has(known.tableState), +) + +test('the form picks a state the table agrees with, apart from the known ZIPs', () => { + const tablePath = new URL('../../../cliff_watch/data/zip_county.json.gz', import.meta.url) + const table = JSON.parse(gunzipSync(readFileSync(tablePath)).toString('utf8')) + const stateOf = (index) => table.counties[index][0].slice(-2) + + const unexpected = [] + let checked = 0 + for (const [zip, rows] of Object.entries(table.zips)) { + const formState = getZipState(zip) + if (!formState) continue + checked += 1 + assert.equal(hasValidZip(zip, formState), true) + + const tableStates = new Set(rows.map(([index]) => stateOf(index))) + if ( + !tableStates.has(formState) + && !KNOWN_FORM_STATE_MISMATCHES.has(zip) + && !isKnownPrefixMismatch(zip, formState, tableStates) + ) { + unexpected.push(`${zip}: form ${formState}, table ${[...tableStates].join('/')}`) + } + } + + assert.ok(checked > 40_000, `checked ${checked} ZIPs`) + assert.deepEqual(unexpected, []) +}) diff --git a/scripts/build_zip_county.py b/scripts/build_zip_county.py new file mode 100644 index 0000000..432f143 --- /dev/null +++ b/scripts/build_zip_county.py @@ -0,0 +1,390 @@ +"""Build cliff_watch/data/zip_county.json.gz, which maps a ZIP to its counties. + +Sources, all public: + +- Census 2020 ZCTA-to-county relationship file: which counties each ZIP Code + Tabulation Area (ZCTA) touches, and how much land it has in each. +- Census 2020 Demographic and Housing Characteristics (DHC), table P1, summary + level 881: residents of each ZCTA-county part. +- GeoNames US postal codes (CC BY 4.0): the county of each ZIP that has no ZCTA + of its own, such as a post-office-box or single-organization ZIP. +- The UDS Mapper ZIP-to-ZCTA crosswalk, as policyengine-us-data stored it: the + ZCTA of a ZIP that GeoNames can't place in a county the engine knows. GeoNames + gives Connecticut's planning regions, and the engine still has its 8 counties. + This build reads only that file's ZIP, ZCTA and state columns. Its county column + holds a random county for a ZCTA that spans several. +- policyengine-us's county_fips_2020.csv.gz and County enum: the code the engine + reads for each county FIPS. + +The rule the table encodes, which `cliff_watch.zip_county` applies: + +- Each ZIP lists its counties in resolution order. +- A ZIP with its own ZCTA lists counties by 2020 residents, most first, with ties + broken by county code. +- A ZCTA with no residents lists counties by land area and records no population. +- A ZIP with no ZCTA lists the single county GeoNames gives it, or else the first + county of its crosswalk ZCTA in its own state, and records no population. + +Run it from the repository root: + + CENSUS_API_KEY=... uv run python scripts/build_zip_county.py --cache-dir /tmp/zc + +The cache directory keeps each download, so a rerun repeats no request and gives +a byte-identical file. +""" + +from __future__ import annotations + +import argparse +import csv +import gzip +import hashlib +import io +import json +import os +import sys +import time +import urllib.error +import urllib.parse +import urllib.request +import zipfile +from collections import defaultdict +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path + +RELATIONSHIP_URL = ( + "https://www2.census.gov/geo/docs/maps-data/data/rel2020/zcta520/" + "tab20_zcta520_county20_natl.txt" +) +DHC_URL = "https://api.census.gov/data/2020/dec/dhc" +GEONAMES_URL = "https://download.geonames.org/export/zip/US.zip" +UDS_CROSSWALK_URL = ( + "https://raw.githubusercontent.com/PolicyEngine/policyengine-us-data/" + "76c61544d7e7db37bed768784a8cd2411e48d6c2/" + "policyengine_us_data/geography/zip_codes.csv.gz" +) + +OUTPUT_PATH = ( + Path(__file__).resolve().parents[1] / "cliff_watch" / "data" / "zip_county.json.gz" +) + +# The 50 states and DC, the places the form accepts. +STATE_FIPS = { + "AL": "01", "AK": "02", "AZ": "04", "AR": "05", "CA": "06", "CO": "08", + "CT": "09", "DE": "10", "DC": "11", "FL": "12", "GA": "13", "HI": "15", + "ID": "16", "IL": "17", "IN": "18", "IA": "19", "KS": "20", "KY": "21", + "LA": "22", "ME": "23", "MD": "24", "MA": "25", "MI": "26", "MN": "27", + "MS": "28", "MO": "29", "MT": "30", "NE": "31", "NV": "32", "NH": "33", + "NJ": "34", "NM": "35", "NY": "36", "NC": "37", "ND": "38", "OH": "39", + "OK": "40", "OR": "41", "PA": "42", "RI": "44", "SC": "45", "SD": "46", + "TN": "47", "TX": "48", "UT": "49", "VT": "50", "VA": "51", "WA": "53", + "WV": "54", "WI": "55", "WY": "56", +} # fmt: skip +STATE_BY_FIPS = {fips: state for state, fips in STATE_FIPS.items()} + +ZCTAS_PER_REQUEST = 200 +USER_AGENT = "cliff-watch-build-zip-county" + + +def _download(url: str, attempts: int = 6) -> bytes: + request = urllib.request.Request(url, headers={"User-Agent": USER_AGENT}) + for attempt in range(attempts): + try: + with urllib.request.urlopen(request, timeout=120) as response: + return response.read() + except (urllib.error.URLError, TimeoutError) as exc: + if attempt == attempts - 1: + raise + print(f"retrying after {exc}", file=sys.stderr) + time.sleep(2**attempt) + raise AssertionError("unreachable") + + +def _cached(cache_dir: Path, name: str, url: str) -> bytes: + path = cache_dir / name + if path.exists(): + return path.read_bytes() + body = _download(url) + path.write_bytes(body) + return body + + +def read_relationship_file(body: bytes) -> dict[str, dict[str, int]]: + """Land area in square meters by ZCTA and county FIPS.""" + land_by_zcta: dict[str, dict[str, int]] = defaultdict(dict) + reader = csv.DictReader(io.StringIO(body.decode("utf-8-sig")), delimiter="|") + for row in reader: + zcta = row["GEOID_ZCTA5_20"] + county_fips = row["GEOID_COUNTY_20"] + if not zcta or not county_fips: + continue + land_by_zcta[zcta][county_fips] = int(row["AREALAND_PART"] or 0) + return dict(land_by_zcta) + + +def read_population( + land_by_zcta: dict[str, dict[str, int]], + cache_dir: Path, + api_key: str | None, +) -> tuple[dict[str, dict[str, int]], list[str]]: + """2020 residents by ZCTA and county FIPS, from DHC summary level 881.""" + zctas_by_state: dict[str, set[str]] = defaultdict(set) + for zcta, counties in land_by_zcta.items(): + for county_fips in counties: + if county_fips[:2] in STATE_BY_FIPS: + zctas_by_state[county_fips[:2]].add(zcta) + + jobs: list[tuple[str, int, list[str]]] = [] + for state_fips, zctas in sorted(zctas_by_state.items()): + ordered = sorted(zctas) + for start in range(0, len(ordered), ZCTAS_PER_REQUEST): + batch = ordered[start : start + ZCTAS_PER_REQUEST] + jobs.append((state_fips, start, batch)) + + def fetch(job: tuple[str, int, list[str]]) -> tuple[str, list[list[str]]]: + state_fips, start, batch = job + name = f"dhc-{state_fips}-{start:05d}-{len(batch)}.json" + path = cache_dir / name + if path.exists(): + return name, json.loads(path.read_text()) + query = { + "get": "P1_001N", + "for": "county (or part):*", + "in": ( + f"state:{state_fips} " + f"zip code tabulation area (or part):{','.join(batch)}" + ), + } + if api_key: + query["key"] = api_key + url = f"{DHC_URL}?{urllib.parse.urlencode(query)}" + body = _download(url) + rows = json.loads(body) + path.write_text(json.dumps(rows)) + return name, rows + + population: dict[str, dict[str, int]] = defaultdict(dict) + with ThreadPoolExecutor(max_workers=6) as pool: + results = sorted(pool.map(fetch, jobs), key=lambda result: result[0]) + + for _, rows in results: + header = rows[0] + count_index = header.index("P1_001N") + state_index = header.index("state") + zcta_index = header.index("zip code tabulation area (or part)") + county_index = header.index("county (or part)") + for row in rows[1:]: + county_fips = row[state_index] + row[county_index] + population[row[zcta_index]][county_fips] = int(row[count_index]) + return dict(population), [name for name, _ in results] + + +def read_geonames(body: bytes) -> dict[str, tuple[str, str]]: + """State and county FIPS by ZIP, for rows that name a county.""" + with zipfile.ZipFile(io.BytesIO(body)) as archive: + text = archive.read("US.txt").decode("utf-8") + counties = {} + for line in text.splitlines(): + fields = line.split("\t") + zip_code, state, county_suffix = fields[1], fields[4], fields[6] + if state in STATE_FIPS and county_suffix.isdigit(): + counties[zip_code] = ( + state, + STATE_FIPS[state] + county_suffix.zfill(3), + ) + return counties + + +def read_uds_crosswalk(body: bytes) -> dict[str, tuple[str, str]]: + """State and ZCTA by ZIP. The file's county column is random, so this skips it.""" + text = gzip.decompress(body).decode("utf-8") + crosswalk = {} + for row in csv.DictReader(io.StringIO(text)): + if row["state"] in STATE_FIPS: + crosswalk[row["zip_code"].zfill(5)] = ( + row["state"], + row["zcta"].zfill(5), + ) + return crosswalk + + +def read_engine_counties() -> tuple[dict[str, tuple[str, str]], str]: + """Engine county code and display name by county FIPS, and the engine version.""" + from importlib.metadata import version + + from policyengine_us.tools.geography.county_helpers import ( + load_county_fips_dataset, + map_county_string_to_enum, + ) + from policyengine_us.variables.household.demographic.geographic.county.county_enum import ( + County, + ) + + dataset = load_county_fips_dataset() + dataset = dataset[dataset["state"].isin(STATE_FIPS)].reset_index(drop=True) + enum_indices = map_county_string_to_enum(dataset["county_name"], dataset["state"]) + names = County._member_names_ + counties = {} + for fips, name, index in zip( + dataset["county_fips"], dataset["county_name"], enum_indices + ): + code = names[int(index)] + if code == "UNKNOWN": + raise ValueError(f"The County enum has no member for {fips} {name}") + counties[fips] = (code, name) + return counties, version("policyengine-us") + + +def build_table( + land_by_zcta: dict[str, dict[str, int]], + population: dict[str, dict[str, int]], + geonames: dict[str, tuple[str, str]], + uds_crosswalk: dict[str, tuple[str, str]], + engine_counties: dict[str, tuple[str, str]], +) -> tuple[dict[str, list[tuple[str, int | None]]], dict[str, int]]: + """Each ZIP's counties in resolution order, with the build's own counts.""" + zips: dict[str, list[tuple[str, int | None]]] = {} + counts = { + "zcta_with_residents": 0, + "zcta_without_residents": 0, + "zip_without_zcta_from_geonames": 0, + "zip_without_zcta_from_crosswalk": 0, + "zcta_outside_engine_counties": 0, + } + + for zcta, land in sorted(land_by_zcta.items()): + known = {fips: area for fips, area in land.items() if fips in engine_counties} + if not known: + # Territories' ZCTAs: the form accepts no ZIP in these places. + counts["zcta_outside_engine_counties"] += 1 + continue + residents = {fips: population.get(zcta, {}).get(fips, 0) for fips in known} + if sum(residents.values()) > 0: + ranked = sorted( + ( + (engine_counties[fips][0], count) + for fips, count in residents.items() + if count > 0 + ), + key=lambda item: (-item[1], item[0]), + ) + zips[zcta] = [(code, count) for code, count in ranked] + counts["zcta_with_residents"] += 1 + else: + ranked_land = sorted( + ((engine_counties[fips][0], area) for fips, area in known.items()), + key=lambda item: (-item[1], item[0]), + ) + zips[zcta] = [(code, None) for code, _ in ranked_land] + counts["zcta_without_residents"] += 1 + + zcta_rows = dict(zips) + for zip_code, (_, county_fips) in sorted(geonames.items()): + if zip_code in land_by_zcta or county_fips not in engine_counties: + continue + zips[zip_code] = [(engine_counties[county_fips][0], None)] + counts["zip_without_zcta_from_geonames"] += 1 + + for zip_code, (state, zcta) in sorted(uds_crosswalk.items()): + if zip_code in zips or zip_code in land_by_zcta: + continue + in_state = [ + code for code, _ in zcta_rows.get(zcta, []) if code.endswith(f"_{state}") + ] + if in_state: + zips[zip_code] = [(in_state[0], None)] + counts["zip_without_zcta_from_crosswalk"] += 1 + + return zips, counts + + +def _sha256(body: bytes) -> str: + return hashlib.sha256(body).hexdigest() + + +def write_table( + path: Path, + zips: dict[str, list[tuple[str, int | None]]], + engine_counties: dict[str, tuple[str, str]], + meta: dict, +) -> bytes: + counties = sorted(engine_counties.values()) + index_by_code = {code: index for index, (code, _) in enumerate(counties)} + document = { + "meta": meta, + "counties": [[code, name] for code, name in counties], + "zips": { + zip_code: [[index_by_code[code], count] for code, count in rows] + for zip_code, rows in sorted(zips.items()) + }, + } + raw = json.dumps(document, ensure_ascii=False, separators=(",", ":")).encode( + "utf-8" + ) + buffer = io.BytesIO() + with gzip.GzipFile( + filename="", mode="wb", compresslevel=9, fileobj=buffer, mtime=0 + ) as archive: + archive.write(raw) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(buffer.getvalue()) + return buffer.getvalue() + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--output", type=Path, default=OUTPUT_PATH) + args = parser.parse_args() + args.cache_dir.mkdir(parents=True, exist_ok=True) + + relationship = _cached(args.cache_dir, "relationship.txt", RELATIONSHIP_URL) + geonames_body = _cached(args.cache_dir, "geonames-US.zip", GEONAMES_URL) + crosswalk_body = _cached(args.cache_dir, "uds-zip-codes.csv.gz", UDS_CROSSWALK_URL) + land_by_zcta = read_relationship_file(relationship) + population, _ = read_population( + land_by_zcta, + args.cache_dir, + os.environ.get("CENSUS_API_KEY"), + ) + geonames = read_geonames(geonames_body) + engine_counties, engine_version = read_engine_counties() + zips, counts = build_table( + land_by_zcta, + population, + geonames, + read_uds_crosswalk(crosswalk_body), + engine_counties, + ) + + meta = { + "built_by": "scripts/build_zip_county.py", + "engine": f"policyengine-us {engine_version}", + "sources": { + "relationship_file": { + "url": RELATIONSHIP_URL, + "sha256": _sha256(relationship), + }, + "residents": { + "url": DHC_URL, + "table": "P1_001N", + "summary_level": 881, + }, + "geonames": { + "url": GEONAMES_URL, + "sha256": _sha256(geonames_body), + "license": "CC BY 4.0", + }, + "uds_crosswalk": { + "url": UDS_CROSSWALK_URL, + "sha256": _sha256(crosswalk_body), + }, + }, + "counts": counts, + } + written = write_table(args.output, zips, engine_counties, meta) + print(json.dumps({"zips": len(zips), "bytes": len(written), **counts}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/scripts/generate_variable_graph.py b/scripts/generate_variable_graph.py index 1b0eb4f..4b2f441 100644 --- a/scripts/generate_variable_graph.py +++ b/scripts/generate_variable_graph.py @@ -35,6 +35,7 @@ build_variable_graph, situation_variables, ) +from cliff_watch.zip_county import RATING_AREA_OVERRIDES, _table SNAPSHOT = ( REPO / "frontend" / "src" / "__fixtures__" / "policyengine-us-variable-graph.json" @@ -68,15 +69,38 @@ def _person(kind: str, age: int) -> dict: } +def _locations(state: str) -> list[dict]: + """A county by name, the state's first ZIP alone, and a county whose ACA rating + area the builder sends (cliff_watch/zip_county.py), where the state has one.""" + table = _table() + first_zip = min( + zip_code + for zip_code, rows in table.zips.items() + if any(table.codes[index].endswith(f"_{state}") for index, _ in rows) + ) + overrides = sorted( + code for code in RATING_AREA_OVERRIDES if code.endswith(f"_{state}") + ) + return [ + {"county": "Some County"}, + {"zip": first_zip}, + *([{"county": overrides[0]}] if overrides else []), + ] + + def python_emitted_variables() -> set[tuple[str, str]]: """``(group, variable)`` pairs the Python builder emits over a full grid.""" names: set[tuple[str, str]] = set() for state in STATE_NAME_BY_CODE: - for filing_status in ("JOINT", "HEAD_OF_HOUSEHOLD"): + for filing_status, location in ( + (status, location) + for status in ("JOINT", "HEAD_OF_HOUSEHOLD") + for location in _locations(state) + ): payload = household_input_from_dict( { "state": state, - "county": "Some County", + **location, "earned_income": 20000, "filing_status": filing_status, "people": [ diff --git a/tests/test_payload_invariants.py b/tests/test_payload_invariants.py index f88917d..0100a97 100644 --- a/tests/test_payload_invariants.py +++ b/tests/test_payload_invariants.py @@ -27,9 +27,11 @@ from cliff_watch.calculator import ( HEAD_INCOME_INPUTS, HouseholdInput, + _normalize_county, build_household_situation, build_household_variation_situation, household_input_from_dict, + resolved_county, ) from cliff_watch.config import PUBLIC_ASSISTANCE_PROGRAM_OPTIONS, STATE_NAME_BY_CODE from cliff_watch.variable_graph import ( @@ -42,6 +44,7 @@ situation_inputs, situation_variables, ) +from cliff_watch.zip_county import RATING_AREA_OVERRIDES, _table, rating_area_override REPO = Path(__file__).resolve().parents[1] SNAPSHOT = ( @@ -109,6 +112,54 @@ def _person(kind): ) +def _places(): + """Each state's ZIPs, its counties, and the names that normalize to them.""" + table = _table() + zips: dict[str, list[str]] = {} + for zip_code, rows in sorted(table.zips.items()): + for state in sorted({table.codes[index][-2:] for index, _ in rows}): + zips.setdefault(state, []).append(zip_code) + counties: dict[str, list[str]] = {} + for code in table.codes: + counties.setdefault(code[-2:], []).append(code) + names = { + state: [ + table.names_by_code[code] + for code in codes + if _normalize_county(table.names_by_code[code], state) == code + ] + for state, codes in counties.items() + } + return sorted(table.zips), zips, counties, names + + +ALL_ZIPS, ZIPS_BY_STATE, COUNTIES_BY_STATE, COUNTY_NAMES_BY_STATE = _places() + + +def _location(state): + """No place, a ZIP in the state or anywhere, a county by code or by name, or both. + + Counties whose rating area the engine misses come up as often as any other. + """ + counties = [ + st.sampled_from(COUNTIES_BY_STATE[state]), + st.sampled_from(COUNTY_NAMES_BY_STATE[state]), + ] + overrides = sorted(c for c in RATING_AREA_OVERRIDES if c.endswith(f"_{state}")) + if overrides: + counties.append(st.sampled_from(overrides)) + county = st.one_of(*counties) + zip_code = st.one_of( + st.sampled_from(ZIPS_BY_STATE[state]), st.sampled_from(ALL_ZIPS) + ) + return st.one_of( + st.just({}), + st.fixed_dictionaries({"zip": zip_code}), + st.fixed_dictionaries({"county": county}), + st.fixed_dictionaries({"zip": zip_code, "county": county}), + ) + + @st.composite def raw_payloads(draw, income_fields=tuple(HEAD_INCOME_INPUTS)): filing_status = draw( @@ -117,8 +168,10 @@ def raw_payloads(draw, income_fields=tuple(HEAD_INCOME_INPUTS)): married = filing_status in {"JOINT", "SEPARATE"} adults = draw(st.lists(_person("adult"), min_size=2 if married else 1, max_size=4)) children = draw(st.lists(_person("child"), max_size=4)) + state = draw(st.sampled_from(sorted(STATE_NAME_BY_CODE))) return { - "state": draw(st.sampled_from(sorted(STATE_NAME_BY_CODE))), + "state": state, + **draw(_location(state)), "year": YEAR, "earned_income": draw(st.integers(0, 300_000)), "filing_status": filing_status, @@ -205,6 +258,30 @@ def test_never_sets_a_total_with_one_of_its_components(system, raw): ) +@PROPERTY_SETTINGS +@given(raw=raw_payloads()) +def test_location_inputs_follow_the_county_rule(raw): + """The county is the entered one or else the ZIP's; the ZIP goes as entered; a + rating area goes only for a county the engine's join misses; and no household + takes up housing assistance, whatever the place.""" + payload = household_input_from_dict(raw) + county = resolved_county(payload) + rating_area = rating_area_override(county) + for path, situation in _situations(payload): + for record in situation["households"].values(): + assert record.get("county") == ({YEAR: county} if county else None), path + assert record.get("zip_code") == ( + {YEAR: payload.zip} if payload.zip else None + ), path + assert record.get("slcsp_rating_area") == ( + None if rating_area is None else {YEAR: rating_area} + ), path + for record in situation["spm_units"].values(): + assert record["takes_up_housing_assistance_if_eligible"] == {YEAR: False}, ( + path + ) + + def test_head_income_fields_map_to_distinct_person_components(system): targets = list(HEAD_INCOME_INPUTS.values()) assert len(set(targets)) == len(targets) @@ -371,6 +448,20 @@ def head(variable): # ignores marital_status, which the UI sends instead of filing_status; JS # doesn't lowercase programs_mode; and JS's fallback program list, used when # metadata is missing, leaves out ssdi. +# +# Python also resolves a county from the ZIP, sends the ZIP, and sends a rating +# area for the counties in RATING_AREA_OVERRIDES. The JS builder, which no +# production page calls, does none of these and carries no ZIP table, so the +# comparison leaves out the ZIP and those counties and keeps any other county. + + +def _shared_location(raw): + shared = {key: value for key, value in raw.items() if key != "zip"} + county = resolved_county(household_input_from_dict(shared)) + if rating_area_override(county) is not None: + shared.pop("county") + return shared + NODE = shutil.which("node") JS_BUILDER = REPO / "frontend" / "src" / "policyengineApi.js" @@ -410,6 +501,7 @@ def normalize(value): @settings(max_examples=60, deadline=None, suppress_health_check=[HealthCheck.too_slow]) @given(raw=raw_payloads()) def test_js_builder_sends_the_same_inputs(raw): + raw = _shared_location(raw) payload = household_input_from_dict(raw) cases = [{"payload": raw, "series": False}, {"payload": raw, "series": True}] output = subprocess.run( diff --git a/tests/test_zip_county.py b/tests/test_zip_county.py new file mode 100644 index 0000000..6f01b7c --- /dev/null +++ b/tests/test_zip_county.py @@ -0,0 +1,789 @@ +"""The ZIP-to-county table and the rule that reads it, with no engine run. + +`tests/test_zip_county_engine.py` runs the same rule through policyengine-us. +""" + +from __future__ import annotations + +import gzip +import importlib.util +import json +import random +import re +import sys +from dataclasses import asdict +from functools import lru_cache +from pathlib import Path + +import pytest +from hypothesis import HealthCheck, given, settings +from hypothesis import strategies as st + +from cliff_watch.calculator import ( + _normalize_county, + build_household_situation, + household_input_from_dict, + household_location, + resolved_county, +) +from cliff_watch.zip_county import ( + COUNTIES_WITHOUT_BENCHMARK, + COUNTIES_WITHOUT_RATING_AREA_ROW, + DATA_PATH, + RATING_AREA_OVERRIDES, + _table, + counties_for_zip, + county_for_zip, + describe_location, + normalize_zip, + rating_area_override, +) + +ROOT = Path(__file__).resolve().parents[1] + +# These tests run on busy machines, where a timing limit measures the machine. +PROPERTY = settings(deadline=None, suppress_health_check=[HealthCheck.too_slow]) + +STATES = frozenset( + [ + "AL", + "AK", + "AZ", + "AR", + "CA", + "CO", + "CT", + "DE", + "DC", + "FL", + "GA", + "HI", + "ID", + "IL", + "IN", + "IA", + "KS", + "KY", + "LA", + "ME", + "MD", + "MA", + "MI", + "MN", + "MS", + "MO", + "MT", + "NE", + "NV", + "NH", + "NJ", + "NM", + "NY", + "NC", + "ND", + "OH", + "OK", + "OR", + "PA", + "RI", + "SC", + "SD", + "TN", + "TX", + "UT", + "VT", + "VA", + "WA", + "WV", + "WI", + "WY", + ] +) + + +def _state_of(code: str) -> str: + return code.rsplit("_", 1)[1] + + +def _payload(**overrides): + return household_input_from_dict( + { + "state": "MA", + "earned_income": 30_000, + "year": 2026, + "marital_status": "UNMARRIED", + "people": [ + {"kind": "adult", "age": 33}, + {"kind": "child", "age": 6}, + {"kind": "child", "age": 10}, + ], + **overrides, + } + ) + + +@lru_cache(maxsize=1) +def _load_builder(): + name = "build_zip_county" + spec = importlib.util.spec_from_file_location( + name, ROOT / "scripts" / "build_zip_county.py" + ) + module = importlib.util.module_from_spec(spec) + sys.modules[name] = module + spec.loader.exec_module(module) + return module + + +# A fixed sample keeps Hypothesis's database stable across table rebuilds. +_ALL_ZIPS = sorted(_table().zips) +_ZIP_SAMPLE = random.Random(20261105).sample(_ALL_ZIPS, 2_000) +_COUNTY_CODES = st.sampled_from(_table().codes) + + +def _zips_by_state() -> dict[str, list[str]]: + """Every (ZIP, state) pair the table holds, grouped by state. A ZIP that + crosses a state line appears under each of its states.""" + table = _table() + by_state: dict[str, list[str]] = {} + for zip_code in _ALL_ZIPS: + for state in sorted( + {_state_of(table.codes[i]) for i, _ in table.zips[zip_code]} + ): + by_state.setdefault(state, []).append(zip_code) + return by_state + + +def _override_county_zips(zips_by_state: dict[str, list[str]]) -> dict[str, str]: + """Per override county, the first ZIP that resolves to it.""" + override: dict[str, str] = {} + for state, zips in sorted(zips_by_state.items()): + for zip_code in zips: + county = county_for_zip(zip_code, state) + if county in RATING_AREA_OVERRIDES: + override.setdefault(county, zip_code) + return override + + +_ZIPS_BY_STATE = _zips_by_state() +_OVERRIDE_COUNTY_ZIPS = _override_county_zips(_ZIPS_BY_STATE) +_ZIP_LIKE_TEXT = st.one_of( + st.none(), + st.text(max_size=12), + st.sampled_from(_ZIP_SAMPLE), + st.integers(min_value=0, max_value=99_999_999).map(str), + st.from_regex(r"\A[0-9]{5}-[0-9]{4}\Z"), +) + + +# The table, for every row. + + +def test_every_zip_is_five_ascii_digits() -> None: + pattern = re.compile(r"[0-9]{5}") + assert all(pattern.fullmatch(zip_code) for zip_code in _table().zips) + + +def test_every_county_belongs_to_a_state_the_form_accepts() -> None: + assert {_state_of(code) for code in _table().codes} == STATES + + +def test_every_county_serves_some_zip() -> None: + used = {index for rows in _table().zips.values() for index, _ in rows} + assert used == set(range(len(_table().codes))) + + +def test_every_county_code_is_an_engine_county() -> None: + pytest.importorskip("policyengine_us") + from policyengine_us.variables.household.demographic.geographic.county.county_enum import ( + County, + ) + + members = set(County._member_names_) + assert [code for code in _table().codes if code not in members] == [] + + +def test_every_county_code_survives_the_explicit_county_path() -> None: + """A picked county must reach the engine as the code the table gave it.""" + for code in _table().codes: + assert _normalize_county(code, _state_of(code)) == code + + +def test_each_zip_lists_counties_in_resolution_order() -> None: + table = _table() + for zip_code, rows in table.zips.items(): + assert rows, zip_code + counted = [residents is not None for _, residents in rows] + # Either the Census counted every county in the row or none of them. + assert all(counted) or not any(counted), zip_code + if all(counted): + keys = [(-residents, table.codes[index]) for index, residents in rows] + assert keys == sorted(keys), zip_code + assert all(residents > 0 for _, residents in rows), zip_code + codes = [table.codes[index] for index, _ in rows] + assert len(codes) == len(set(codes)), zip_code + + +def test_resident_shares_sum_to_one_across_state_lines() -> None: + table = _table() + for zip_code, rows in table.zips.items(): + states = {_state_of(table.codes[index]) for index, _ in rows} + options = [ + option for state in states for option in counties_for_zip(zip_code, state) + ] + assert len(options) == len(rows), zip_code + if rows[0][1] is None: + assert all(option.resident_share is None for option in options), zip_code + else: + total = sum(option.resident_share for option in options) + assert total == pytest.approx(1.0), zip_code + + +def test_county_for_zip_returns_the_first_row_in_each_state() -> None: + table = _table() + for zip_code, rows in table.zips.items(): + first_by_state: dict[str, str] = {} + for index, _ in rows: + code = table.codes[index] + first_by_state.setdefault(_state_of(code), code) + for state, code in first_by_state.items(): + assert county_for_zip(zip_code, state) == code, zip_code + + +def test_table_records_its_sources_and_builder() -> None: + with gzip.open(DATA_PATH, "rt", encoding="utf-8") as file: + meta = json.load(file)["meta"] + assert meta["built_by"] == "scripts/build_zip_county.py" + assert meta["sources"]["geonames"]["license"] == "CC BY 4.0" + assert set(meta["sources"]) == { + "relationship_file", + "residents", + "geonames", + "uds_crosswalk", + } + + +# Pinned places, checked by hand against the Census files. + + +@pytest.mark.parametrize( + ("zip_code", "state", "expected"), + [ + ("02139", "MA", [("MIDDLESEX_COUNTY_MA", 39_525)]), + ("02138", "MA", [("MIDDLESEX_COUNTY_MA", 37_982)]), + ( + "02467", + "MA", + [ + ("MIDDLESEX_COUNTY_MA", 9_116), + ("NORFOLK_COUNTY_MA", 9_024), + ("SUFFOLK_COUNTY_MA", 4_486), + ], + ), + ("02163", "MA", [("SUFFOLK_COUNTY_MA", 1_391)]), + ("10463", "NY", [("BRONX_COUNTY_NY", 62_707), ("NEW_YORK_COUNTY_NY", 8_594)]), + ("42223", "KY", [("CHRISTIAN_COUNTY_KY", 12_828)]), + ("42223", "TN", [("MONTGOMERY_COUNTY_TN", 7_307)]), + ("96742", "HI", [("KALAWAO_COUNTY_HI", 82)]), + ], +) +def test_pinned_resident_counts(zip_code, state, expected) -> None: + options = counties_for_zip(zip_code, state) + assert [(option.code, option.residents) for option in options] == expected + + +@pytest.mark.parametrize( + ("zip_code", "state", "expected"), + [ + ("10001", "NY", "NEW_YORK_COUNTY_NY"), + ("90210", "CA", "LOS_ANGELES_COUNTY_CA"), + ("90001", "CA", "LOS_ANGELES_COUNTY_CA"), + ("60601", "IL", "COOK_COUNTY_IL"), + ("30303", "GA", "FULTON_COUNTY_GA"), + ("77002", "TX", "HARRIS_COUNTY_TX"), + ("20001", "DC", "DISTRICT_OF_COLUMBIA_DC"), + ("22314", "VA", "ALEXANDRIA_CITY_VA"), + ("70112", "LA", "ORLEANS_PARISH_LA"), + ("99501", "AK", "ANCHORAGE_MUNICIPALITY_AK"), + ("21201", "MD", "BALTIMORE_CITY_MD"), + ("63101", "MO", "ST_LOUIS_CITY_MO"), + ("88001", "NM", "DOÑA_ANA_COUNTY_NM"), + ("06010", "CT", "HARTFORD_COUNTY_CT"), + ("89439", "NV", "WASHOE_COUNTY_NV"), + ("89439", "CA", "SIERRA_COUNTY_CA"), + # A ZIP with no ZCTA of its own: a county, and no resident count to show. + ("02238", "MA", "MIDDLESEX_COUNTY_MA"), + ], +) +def test_pinned_counties(zip_code, state, expected) -> None: + assert county_for_zip(zip_code, state) == expected + + +def test_zip_with_no_zcta_records_no_residents() -> None: + [option] = counties_for_zip("02238", "MA") + assert option.residents is None + assert option.resident_share is None + + +def test_puerto_rico_zip_is_outside_the_table() -> None: + assert describe_location("00601", "MA") == { + "zip": "00601", + "county": None, + "county_name": None, + "source": "none", + "has_benchmark_premium": True, + "counties": [], + } + + +@pytest.mark.parametrize( + ("zip_code", "state", "county"), + [ + ("29135", "SC", "CALHOUN_COUNTY_SC"), + ("29824", "SC", "EDGEFIELD_COUNTY_SC"), + ("32456", "FL", "GULF_COUNTY_FL"), + ], +) +def test_location_flags_a_county_with_no_benchmark_premium( + zip_code, state, county +) -> None: + location = describe_location(zip_code, state) + assert location["county"] == county + assert location["has_benchmark_premium"] is False + + +def test_the_benchmark_flag_follows_the_county_a_link_names() -> None: + edgefield = describe_location("29201", "SC", "EDGEFIELD_COUNTY_SC") + richland = describe_location("29824", "SC", "RICHLAND_COUNTY_SC") + assert edgefield["has_benchmark_premium"] is False + assert richland["has_benchmark_premium"] is True + + +def test_no_state_default_county_lacks_a_benchmark_premium() -> None: + """A location with no county reads true, because the engine then uses the default.""" + assert COUNTIES_WITHOUT_BENCHMARK <= set(_table().codes) + for state in {_state_of(code) for code in COUNTIES_WITHOUT_BENCHMARK}: + counties = [code for code in _table().codes if _state_of(code) == state] + assert min(counties) not in COUNTIES_WITHOUT_BENCHMARK + + +# The rating areas the engine's name join misses. `tests/test_zip_county_engine.py` +# checks each entry against the engine's own file. + + +def test_rating_area_overrides_name_table_counties_and_their_own_state() -> None: + codes = set(_table().codes) + assert set(RATING_AREA_OVERRIDES) <= codes + assert COUNTIES_WITHOUT_RATING_AREA_ROW <= codes + assert not set(RATING_AREA_OVERRIDES) & COUNTIES_WITHOUT_RATING_AREA_ROW + for code, (row, area) in RATING_AREA_OVERRIDES.items(): + # The file's spelling differs from the code but names the same state. + assert row != code + assert _state_of(row) == _state_of(code), code + assert isinstance(area, int) and area >= 1, code + assert rating_area_override(code) == area + + +@pytest.mark.parametrize( + "county", [None, "", "MIDDLESEX_COUNTY_MA", "OGLALA_LAKOTA_COUNTY_SD", "X_MA"] +) +def test_other_counties_get_no_rating_area_override(county) -> None: + assert rating_area_override(county) is None + + +@pytest.mark.parametrize("county", sorted(RATING_AREA_OVERRIDES)) +def test_an_override_county_sends_its_rating_area_by_name_or_by_zip(county) -> None: + state = _state_of(county) + zip_code = _OVERRIDE_COUNTY_ZIPS[county] + area = RATING_AREA_OVERRIDES[county][1] + named = build_household_situation(_payload(state=state, county=county)) + from_zip = build_household_situation(_payload(state=state, zip=zip_code)) + + assert named["households"]["household"]["slcsp_rating_area"] == {2026: area} + assert from_zip["households"]["household"]["county"] == {2026: county} + assert from_zip["households"]["household"]["slcsp_rating_area"] == {2026: area} + + +# The rule, through the calculator's input type. + + +def test_zip_alone_resolves_to_its_county() -> None: + payload = _payload(zip="02139") + assert resolved_county(payload) == "MIDDLESEX_COUNTY_MA" + location = household_location(payload) + assert location["source"] == "zip" + assert location["county"] == "MIDDLESEX_COUNTY_MA" + assert location["county_name"] == "Middlesex County" + + household = build_household_situation(payload)["households"]["household"] + assert household["county"][2026] == "MIDDLESEX_COUNTY_MA" + assert household["zip_code"][2026] == "02139" + + +def test_explicit_county_overrides_the_zip() -> None: + payload = _payload(zip="02139", county="SUFFOLK_COUNTY_MA") + assert resolved_county(payload) == "SUFFOLK_COUNTY_MA" + location = household_location(payload) + assert location["source"] == "explicit" + assert location["county"] == "SUFFOLK_COUNTY_MA" + assert [county["code"] for county in location["counties"]] == [ + "MIDDLESEX_COUNTY_MA" + ] + + household = build_household_situation(payload)["households"]["household"] + assert household["county"][2026] == "SUFFOLK_COUNTY_MA" + assert household["zip_code"][2026] == "02139" + + +@pytest.mark.parametrize("blank", [None, "", " "]) +def test_blank_county_falls_through_to_the_zip(blank) -> None: + payload = _payload(zip="02139", county=blank) + assert resolved_county(payload) == "MIDDLESEX_COUNTY_MA" + assert household_location(payload)["source"] == "zip" + + +def test_cross_state_zip_resolves_by_the_household_state() -> None: + kentucky = _payload(state="KY", zip="42223") + tennessee = _payload(state="TN", zip="42223") + assert resolved_county(kentucky) == "CHRISTIAN_COUNTY_KY" + assert resolved_county(tennessee) == "MONTGOMERY_COUNTY_TN" + assert household_location(kentucky)["counties"][0][ + "resident_share" + ] == pytest.approx(12_828 / (12_828 + 7_307)) + + +def test_zip_outside_the_state_leaves_the_engine_its_default() -> None: + payload = _payload(state="CA", zip="02139") + assert resolved_county(payload) is None + assert household_location(payload)["source"] == "none" + assert "county" not in build_household_situation(payload)["households"]["household"] + + +def test_no_zip_and_no_county_stay_as_they_were() -> None: + payload = _payload() + assert payload.zip is None + household = build_household_situation(payload)["households"]["household"] + assert "county" not in household + assert "zip_code" not in household + assert household_location(payload) == { + "zip": None, + "county": None, + "county_name": None, + "source": "none", + "has_benchmark_premium": True, + "counties": [], + } + + +@pytest.mark.parametrize( + "written", ["02139", " 02139 ", "02139-1234", "021391234", "ZIP 02139"] +) +def test_payload_normalizes_zip_like_the_form(written) -> None: + assert _payload(zip=written).zip == "02139" + + +@pytest.mark.parametrize("written", ["", "2139", "abcde", None, "02139"]) +def test_payload_drops_a_zip_with_too_few_ascii_digits(written) -> None: + assert _payload(zip=written).zip is None + + +# Properties for every input. + + +@PROPERTY +@given(_ZIP_LIKE_TEXT) +def test_normalize_zip_gives_five_ascii_digits_or_none_and_is_idempotent(value) -> None: + normalized = normalize_zip(value) + assert normalized is None or re.fullmatch(r"[0-9]{5}", normalized) + assert normalize_zip(normalized) == normalized + + +@PROPERTY +@given(_ZIP_LIKE_TEXT, st.sampled_from(sorted(STATES))) +def test_lookup_never_raises_and_stays_in_the_state(value, state) -> None: + county = county_for_zip(value, state) + assert county is None or _state_of(county) == state + location = describe_location(value, state) + assert location["county"] == county + assert location["source"] == ("zip" if county else "none") + assert location["has_benchmark_premium"] == ( + county not in COUNTIES_WITHOUT_BENCHMARK + ) + assert all(_state_of(option["code"]) == state for option in location["counties"]) + # The page reads this block as JSON. + assert json.loads(json.dumps(location)) == location + + +@PROPERTY +@given(_ZIP_LIKE_TEXT, _COUNTY_CODES) +def test_explicit_county_always_wins(value, county) -> None: + state = _state_of(county) + payload = _payload(state=state, zip=value, county=county) + assert resolved_county(payload) == county + location = household_location(payload) + assert location["county"] == county + assert location["source"] == "explicit" + assert location["county_name"] + + +@pytest.mark.parametrize("state", sorted(STATES)) +def test_zip_alone_builds_the_same_situation_as_its_county_named(state) -> None: + """Every ZIP the table holds for the state, so across the states every + (ZIP, state) pair.""" + for zip_code in _ZIPS_BY_STATE[state]: + county = county_for_zip(zip_code, state) + assert county is not None and _state_of(county) == state, zip_code + zip_only = build_household_situation(_payload(state=state, zip=zip_code)) + explicit = build_household_situation( + _payload(state=state, zip=zip_code, county=county) + ) + assert zip_only == explicit, zip_code + assert zip_only["households"]["household"]["county"] == {2026: county} + + +def test_the_per_state_loops_cover_every_zip_and_state() -> None: + """The loops above walk `_ZIPS_BY_STATE`, so it must list each (ZIP, state) + pair the table holds exactly once, including the pairs of ZIPs that cross a + state line.""" + table = _table() + pairs = { + (zip_code, _state_of(table.codes[index])) + for zip_code, rows in table.zips.items() + for index, _ in rows + } + listed = [ + (zip_code, state) for state, zips in _ZIPS_BY_STATE.items() for zip_code in zips + ] + assert len(listed) == len(set(listed)) + assert set(listed) == pairs + assert set(_ZIPS_BY_STATE) == {state for _, state in pairs} == STATES + assert len(pairs) > len(table.zips) # some ZIPs cross a state line + + +@PROPERTY +@given(_ZIP_LIKE_TEXT, _COUNTY_CODES) +def test_only_an_override_county_gets_a_rating_area_input(value, county) -> None: + household = build_household_situation( + _payload(state=_state_of(county), zip=value, county=county) + )["households"]["household"] + if county in RATING_AREA_OVERRIDES: + assert household["slcsp_rating_area"] == { + 2026: RATING_AREA_OVERRIDES[county][1] + } + else: + assert "slcsp_rating_area" not in household + + +@PROPERTY +@given(_ZIP_LIKE_TEXT, st.sampled_from(sorted(STATES))) +def test_no_household_takes_up_housing_assistance(value, state) -> None: + """CliffWatch has no voucher input (#30), so no ZIP or county turns one on.""" + situation = build_household_situation(_payload(state=state, zip=value)) + for record in situation["spm_units"].values(): + assert record["takes_up_housing_assistance_if_eligible"] == {2026: False} + + +@pytest.mark.parametrize("state", sorted(STATES)) +def test_counties_for_a_zip_lead_with_the_county_it_resolves_to(state) -> None: + for zip_code in _ZIPS_BY_STATE[state]: + options = counties_for_zip(zip_code, state) + assert options[0].code == county_for_zip(zip_code, state), zip_code + for option in options: + assert _state_of(option.code) == state, zip_code + assert option.name, zip_code + if option.resident_share is not None: + assert 0 < option.resident_share <= 1, zip_code + + +@PROPERTY +@given(_ZIP_LIKE_TEXT) +def test_payload_survives_the_cache_key_serialization(value) -> None: + payload = _payload(zip=value) + round_tripped = json.loads(json.dumps(asdict(payload), sort_keys=True)) + assert household_input_from_dict(round_tripped).zip == payload.zip + + +# The builder's rule, on toy inputs. + +ENGINE = { + "25017": ("MIDDLESEX_COUNTY_MA", "Middlesex County"), + "25021": ("NORFOLK_COUNTY_MA", "Norfolk County"), + "25025": ("SUFFOLK_COUNTY_MA", "Suffolk County"), + "09003": ("HARTFORD_COUNTY_CT", "Hartford County"), + "21047": ("CHRISTIAN_COUNTY_KY", "Christian County"), + "47125": ("MONTGOMERY_COUNTY_TN", "Montgomery County"), +} + + +def _build(land=None, population=None, geonames=None, crosswalk=None): + return _load_builder().build_table( + land or {}, + population or {}, + geonames or {}, + crosswalk or {}, + ENGINE, + ) + + +def test_builder_ranks_counties_by_residents() -> None: + zips, counts = _build( + land={"02467": {"25017": 1, "25021": 2, "25025": 3}}, + population={"02467": {"25017": 9, "25021": 8, "25025": 7}}, + ) + assert zips["02467"] == [ + ("MIDDLESEX_COUNTY_MA", 9), + ("NORFOLK_COUNTY_MA", 8), + ("SUFFOLK_COUNTY_MA", 7), + ] + assert counts["zcta_with_residents"] == 1 + + +def test_builder_breaks_a_resident_tie_by_code() -> None: + zips, _ = _build( + land={"02467": {"25025": 1, "25017": 2}}, + population={"02467": {"25025": 5, "25017": 5}}, + ) + assert [code for code, _ in zips["02467"]] == [ + "MIDDLESEX_COUNTY_MA", + "SUFFOLK_COUNTY_MA", + ] + + +def test_builder_leaves_out_a_county_with_land_and_no_residents() -> None: + zips, _ = _build( + land={"02467": {"25017": 1, "25021": 99}}, + population={"02467": {"25017": 5, "25021": 0}}, + ) + assert zips["02467"] == [("MIDDLESEX_COUNTY_MA", 5)] + + +def test_builder_ranks_a_zcta_with_no_residents_by_land_and_records_no_count() -> None: + zips, counts = _build(land={"02238": {"25017": 1, "25021": 5}}) + assert zips["02238"] == [("NORFOLK_COUNTY_MA", None), ("MIDDLESEX_COUNTY_MA", None)] + assert counts["zcta_without_residents"] == 1 + + +def test_builder_gives_a_zip_with_no_zcta_its_geonames_county() -> None: + zips, counts = _build( + land={"02139": {"25017": 1}}, + population={"02139": {"25017": 5}}, + geonames={"02238": ("MA", "25021"), "02139": ("MA", "25025")}, + ) + assert zips["02238"] == [("NORFOLK_COUNTY_MA", None)] + # A ZIP with its own ZCTA keeps the Census answer over GeoNames. + assert zips["02139"] == [("MIDDLESEX_COUNTY_MA", 5)] + assert counts["zip_without_zcta_from_geonames"] == 1 + + +def test_builder_falls_back_to_the_crosswalk_zctas_county_in_the_same_state() -> None: + zips, counts = _build( + land={"42223": {"21047": 1, "47125": 1}, "06010": {"09003": 1}}, + population={"42223": {"21047": 9, "47125": 7}, "06010": {"09003": 5}}, + # GeoNames gives a planning region the engine lacks, so the row moves on. + geonames={"06011": ("CT", "09110")}, + crosswalk={ + "06011": ("CT", "06010"), + "42221": ("TN", "42223"), + "99999": ("MA", "42223"), + }, + ) + assert zips["06011"] == [("HARTFORD_COUNTY_CT", None)] + # In its own state, though the ZCTA's largest county lies across the line. + assert zips["42221"] == [("MONTGOMERY_COUNTY_TN", None)] + # No county of that ZCTA in that state, so no row at all. + assert "99999" not in zips + assert counts["zip_without_zcta_from_crosswalk"] == 2 + + +def test_builder_skips_a_zcta_outside_the_engine_counties() -> None: + zips, counts = _build(land={"00601": {"72001": 1}}) + assert zips == {} + assert counts["zcta_outside_engine_counties"] == 1 + + +_FIPS = sorted(ENGINE) +_LAND_AND_POPULATION = st.dictionaries( + st.sampled_from(["02138", "02139", "02140", "02141"]), + st.dictionaries( + st.sampled_from(_FIPS), + st.tuples( + st.integers(min_value=0, max_value=1_000), + st.integers(min_value=0, max_value=1_000), + ), + min_size=1, + ), + max_size=4, +) + + +@PROPERTY +@given(_LAND_AND_POPULATION) +def test_builder_invariants_for_any_inputs(cells) -> None: + land = {z: {f: a for f, (a, _) in row.items()} for z, row in cells.items()} + population = {z: {f: p for f, (_, p) in row.items()} for z, row in cells.items()} + + zips, counts = _build(land=land, population=population) + fips_by_code = {code: fips for fips, (code, _) in ENGINE.items()} + + def in_order(rows, measure_by_fips): + """Most first by each county's measure, ties broken by county code.""" + keys = [(-measure_by_fips[fips_by_code[code]], code) for code, _ in rows] + return keys == sorted(keys) and len(set(keys)) == len(keys) + + assert set(zips) == set(land) + for zcta, rows in zips.items(): + residents = population[zcta] + if sum(residents.values()) > 0: + top = max(residents.values()) + # The first county holds the most residents, and only counties with + # residents appear. + assert rows[0][1] == top + assert all(count and count > 0 for _, count in rows) + assert len(rows) == sum(1 for value in residents.values() if value > 0) + assert sum(count for _, count in rows) == sum(residents.values()) + assert in_order(rows, residents) + else: + # With no residents, every county with land appears, most land first. + assert all(count is None for _, count in rows) + assert len(rows) == len(land[zcta]) + assert {fips_by_code[code] for code, _ in rows} == set(land[zcta]) + assert in_order(rows, land[zcta]) + assert (counts["zcta_with_residents"] + counts["zcta_without_residents"]) == len( + zips + ) + + # The order of the input files changes nothing. + rng = random.Random(0) + + def shuffled(mapping): + items = list(mapping.items()) + rng.shuffle(items) + return { + key: dict(rng.sample(list(value.items()), len(value))) + for key, value in items + } + + assert _build(land=shuffled(land), population=shuffled(population))[0] == zips + + +def test_builder_writes_the_same_bytes_for_the_same_table(tmp_path) -> None: + builder = _load_builder() + zips = { + "02467": [("MIDDLESEX_COUNTY_MA", 9), ("NORFOLK_COUNTY_MA", 8)], + "02238": [("MIDDLESEX_COUNTY_MA", None)], + } + first = builder.write_table(tmp_path / "a.json.gz", zips, ENGINE, {"note": "toy"}) + second = builder.write_table( + tmp_path / "b.json.gz", + dict(reversed(list(zips.items()))), + ENGINE, + {"note": "toy"}, + ) + assert first == second + + with gzip.open(tmp_path / "a.json.gz", "rt", encoding="utf-8") as file: + document = json.load(file) + codes = [code for code, _ in document["counties"]] + assert document["zips"]["02467"] == [ + [codes.index("MIDDLESEX_COUNTY_MA"), 9], + [codes.index("NORFOLK_COUNTY_MA"), 8], + ] diff --git a/tests/test_zip_county_engine.py b/tests/test_zip_county_engine.py new file mode 100644 index 0000000..576ddf1 --- /dev/null +++ b/tests/test_zip_county_engine.py @@ -0,0 +1,407 @@ +"""The ZIP's county through policyengine-us. + +The household is the single parent in Cambridge, Massachusetts, whose chart showed +Barnstable County's benchmark premiums before the API read the ZIP. +""" + +from __future__ import annotations + +import pytest + +pytest.importorskip("policyengine_us") + +from api._shared import _series_cached, compute_series +from cliff_watch.calculator import ( + _load_simulation, + build_household_situation, + calculate_household, + calculate_income_series, + household_input_from_dict, +) +from cliff_watch.zip_county import ( + COUNTIES_WITHOUT_BENCHMARK, + COUNTIES_WITHOUT_RATING_AREA_ROW, + RATING_AREA_OVERRIDES, + _table, + rating_area_override, +) + +YEAR = 2026 +MAX_EARNINGS = 60_000 +STEP = 2_500 + + +def _payload(**overrides): + return household_input_from_dict( + { + "state": "MA", + "earned_income": 0, + "year": YEAR, + "marital_status": "UNMARRIED", + "people": [ + {"kind": "adult", "age": 33}, + {"kind": "child", "age": 6}, + {"kind": "child", "age": 10}, + ], + **overrides, + } + ) + + +def _series(payload): + return calculate_income_series(payload, max_earned_income=MAX_EARNINGS, step=STEP) + + +def _engine_values(payload, *variables): + simulation = _load_simulation()(situation=build_household_situation(payload)) + return { + variable: simulation.calculate(variable, YEAR).tolist()[0] + for variable in variables + } + + +@pytest.fixture(scope="module") +def zip_only_series(): + return _series(_payload(zip="02139")) + + +def test_middlesex_zip_gives_the_same_series_as_the_explicit_county( + zip_only_series, +) -> None: + explicit = _series(_payload(zip="02139", county="MIDDLESEX_COUNTY_MA")) + + assert zip_only_series["data"] == explicit["data"] + + +def test_a_single_calculation_reports_the_county_and_zip_it_used() -> None: + from_zip = calculate_household(_payload(earned_income=30_000, zip="02139")) + named = calculate_household( + _payload(earned_income=30_000, zip="02139", county="MIDDLESEX_COUNTY_MA") + ) + no_zip = calculate_household(_payload(earned_income=30_000)) + + assert from_zip == named + assert from_zip["input"]["county"] == "MIDDLESEX_COUNTY_MA" + assert from_zip["input"]["zip"] == "02139" + assert no_zip["input"]["county"] is None + assert no_zip["input"]["zip"] is None + + +def test_the_series_differs_from_the_state_default_county(zip_only_series) -> None: + """The negative control: this household's chart does depend on its county.""" + no_county = _series(_payload()) + + assert zip_only_series["data"] != no_county["data"] + assert any( + with_zip["aca_ptc"] != without["aca_ptc"] + for with_zip, without in zip( + zip_only_series["data"], no_county["data"], strict=True + ) + ) + + +def test_naming_the_default_county_reproduces_the_old_series() -> None: + """A ZIP changes this series only through the county it resolves to.""" + old_behaviour = _series(_payload()) + named = _series(_payload(zip="02139", county="BARNSTABLE_COUNTY_MA")) + + assert named["data"] == old_behaviour["data"] + + +def test_engine_reads_the_zips_county_and_rating_area() -> None: + no_county = _engine_values(_payload(), "county_str", "slcsp_rating_area") + from_zip = _engine_values(_payload(zip="02139"), "county_str", "slcsp_rating_area") + + assert no_county["county_str"] == "BARNSTABLE_COUNTY_MA" + assert from_zip["county_str"] == "MIDDLESEX_COUNTY_MA" + assert no_county["slcsp_rating_area"] == 7 + assert from_zip["slcsp_rating_area"] == 3 + + +@pytest.mark.parametrize( + ("zip_code", "rating_area"), + [("90802", 15), ("91001", 15), ("93534", 15), ("90001", 16), ("90210", 16)], +) +def test_los_angeles_county_rating_area_reads_the_zip(zip_code, rating_area) -> None: + values = _engine_values( + _payload(state="CA", zip=zip_code), "county_str", "slcsp_rating_area" + ) + assert values["county_str"] == "LOS_ANGELES_COUNTY_CA" + assert values["slcsp_rating_area"] == rating_area + + +def test_api_series_reports_the_location_it_used() -> None: + response = compute_series( + _payload(zip="02467"), max_earned_income=20_000, step=5_000 + ) + location = response["location"] + + assert location["zip"] == "02467" + assert location["county"] == "MIDDLESEX_COUNTY_MA" + assert location["county_name"] == "Middlesex County" + assert location["source"] == "zip" + assert [county["code"] for county in location["counties"]] == [ + "MIDDLESEX_COUNTY_MA", + "NORFOLK_COUNTY_MA", + "SUFFOLK_COUNTY_MA", + ] + + +def test_api_series_cache_keeps_zips_apart(zip_only_series) -> None: + """Payloads that differ only in the ZIP must not share a cached series. + + Cambridge (Middlesex) and Hyannis (Barnstable) give this household different + series, so a cache key without the ZIP would hand the second call the first's. + """ + _series_cached.cache_clear() + cambridge = compute_series( + _payload(zip="02139"), max_earned_income=MAX_EARNINGS, step=STEP + ) + hyannis = compute_series( + _payload(zip="02601"), max_earned_income=MAX_EARNINGS, step=STEP + ) + + assert cambridge["location"]["county"] == "MIDDLESEX_COUNTY_MA" + assert hyannis["location"]["county"] == "BARNSTABLE_COUNTY_MA" + assert cambridge["data"] == zip_only_series["data"] + assert hyannis["data"] == _series(_payload(zip="02601"))["data"] + assert cambridge["data"] != hyannis["data"] + + +# Housing assistance: CliffWatch has no input for whether a household holds a +# voucher (#30), and its rent field also takes mortgage payments, so no household +# takes one up. The engine still computes the subsidy, which is the control. + + +@pytest.mark.parametrize( + ("state", "zip_code", "county"), + [ + ("CA", "90802", None), + ("TX", "75201", None), + ("TX", "77002", None), + ("KS", "67202", None), + ("CA", None, "LOS_ANGELES_COUNTY_CA"), + ], +) +def test_no_household_takes_up_the_voucher_the_engine_computes( + state, zip_code, county +) -> None: + values = _engine_values( + _payload( + state=state, + zip=zip_code, + county=county, + earned_income=30_000, + rent_annual=24_000, + ), + "hud_hap", + "housing_assistance", + ) + assert values["hud_hap"] > 0 + assert values["housing_assistance"] == 0 + + +# ACA rating areas: policyengine-us joins the county's code to this file by exact +# name and gives rating area 1 to a county the join misses. + + +@pytest.fixture(scope="module") +def rating_area_file(): + from policyengine_us.parameters.gov.hhs.medicaid.geography import ( + aca_rating_areas, + ) + + return { + county: int(area) + for county, area in zip( + aca_rating_areas["county"], aca_rating_areas["rating_area"], strict=True + ) + } + + +def test_every_county_has_a_rating_area_row_or_an_override(rating_area_file) -> None: + missed = {code for code in _table().codes if code not in rating_area_file} + assert missed == set(RATING_AREA_OVERRIDES) | COUNTIES_WITHOUT_RATING_AREA_ROW + + +# Each county without a row, with the names a row for it could start with. +# Oglala Lakota County was Shannon County until 2015. +_NAMES_OF_COUNTIES_WITHOUT_A_ROW = {"OGLALA_LAKOTA_COUNTY_SD": ("OGLALA_", "SHANNON_")} + + +def test_a_county_without_a_row_has_none_under_any_name(rating_area_file) -> None: + """The test above sees only the exact code. A row under another spelling, such + as `OGLALA_LAKOTA_SD`, would leave the county at rating area 1 where an + override should send the row's area.""" + assert set(_NAMES_OF_COUNTIES_WITHOUT_A_ROW) == COUNTIES_WITHOUT_RATING_AREA_ROW + for code, names in _NAMES_OF_COUNTIES_WITHOUT_A_ROW.items(): + state = code.rsplit("_", 1)[1] + rows = sorted( + row + for row in rating_area_file + if row.startswith(names) and row.endswith(f"_{state}") + ) + assert rows == [], (code, rows) + + +def test_each_override_holds_its_rows_rating_area(rating_area_file) -> None: + for code, (row, area) in RATING_AREA_OVERRIDES.items(): + assert code not in rating_area_file, code + assert rating_area_file[row] == area, code + + +def _twin(code, rating_area_file): + """A county in the same state whose exact name the file holds, in the same area.""" + area = RATING_AREA_OVERRIDES[code][1] + state = code.rsplit("_", 1)[1] + return next( + ( + other + for other in _table().codes + if other.endswith(f"_{state}") and rating_area_file.get(other) == area + ), + None, + ) + + +def _rating_areas_and_benchmarks(counties, rating_areas=None): + """Rating area and January age-0 benchmark for one household per county. + + Once any household in a simulation sets an input, policyengine-core gives the + others its default (0 for a rating area) rather than the formula's value, so + this sets the rating area on every household or on none. CliffWatch's own + simulations hold one household each. + """ + groups = ("tax_units", "families", "spm_units", "marital_units") + situation = {"people": {}, "households": {}, **{group: {} for group in groups}} + for index, code in enumerate(counties): + person = f"person_{index}" + situation["people"][person] = {"age": {YEAR: 40}} + household = { + "members": [person], + "state_name": {YEAR: code.rsplit("_", 1)[1]}, + "county": {YEAR: code}, + } + if rating_areas is not None: + household["slcsp_rating_area"] = {YEAR: rating_areas[index]} + situation["households"][f"household_{index}"] = household + for group in groups: + situation[group][f"{group}_{index}"] = {"members": [person]} + + simulation = _load_simulation()(situation=situation) + return dict( + zip( + counties, + zip( + simulation.calculate("slcsp_rating_area", YEAR).tolist(), + simulation.calculate("slcsp_age_0", f"{YEAR}-01").tolist(), + strict=True, + ), + strict=True, + ) + ) + + +def test_an_override_county_gets_the_benchmark_of_its_rating_area( + rating_area_file, +) -> None: + """Each override county against a twin whose name the join matches. + + Doña Ana County is the only county in New Mexico's rating area 3, so it has no + twin; it checks against the rating area 1 the join gives it without the input. + """ + counties = sorted(RATING_AREA_OVERRIDES) + twins = {code: _twin(code, rating_area_file) for code in counties} + assert [code for code, twin in twins.items() if twin is None] == [ + "DOÑA_ANA_COUNTY_NM" + ] + sent = _rating_areas_and_benchmarks( + counties, [rating_area_override(code) for code in counties] + ) + joined = _rating_areas_and_benchmarks( + sorted({twin for twin in twins.values() if twin}) + ["DOÑA_ANA_COUNTY_NM"] + ) + + for code in counties: + area, cost = sent[code] + assert area == RATING_AREA_OVERRIDES[code][1], code + assert cost > 0, code + if twins[code]: + assert joined[twins[code]] == (area, cost), code + # Without the input the join misses Doña Ana and prices it as rating area 1. + assert joined["DOÑA_ANA_COUNTY_NM"][0] == 1 + assert joined["DOÑA_ANA_COUNTY_NM"][1] != sent["DOÑA_ANA_COUNTY_NM"][1] + + +def test_an_override_reaches_every_point_of_the_series(monkeypatch) -> None: + """Baylor County by ZIP prices tax credits like Archer County, its rating area 24 + twin, at every earnings level, and unlike the rating area 1 it got before.""" + baylor = _series(_payload(state="TX", zip="76380"))["data"] + archer = _series(_payload(state="TX", county="ARCHER_COUNTY_TX"))["data"] + monkeypatch.setattr("cliff_watch.calculator.rating_area_override", lambda _: None) + before = _series(_payload(state="TX", zip="76380"))["data"] + + credits = [point["aca_ptc"] for point in baylor] + assert any(credit > 0 for credit in credits) + assert credits == [point["aca_ptc"] for point in archer] + assert credits != [point["aca_ptc"] for point in before] + + +def test_the_first_reviews_baylor_household_reads_rating_area_24() -> None: + values = _engine_values( + _payload(state="TX", zip="76380", earned_income=30_000), + "county_str", + "slcsp_rating_area", + ) + assert values == {"county_str": "BAYLOR_COUNTY_TX", "slcsp_rating_area": 24} + + +def test_the_counties_without_a_benchmark_match_the_engine() -> None: + """Fails when an engine update adds their rating areas, so the page note goes too. + + A single adult at $60,000 reads a benchmark in every other county, so a zero here + means the engine holds no premium for the county. + """ + codes = _table().codes + groups = ("tax_units", "families", "spm_units", "marital_units") + situation = {"people": {}, "households": {}, **{group: {} for group in groups}} + for index, code in enumerate(codes): + person = f"person_{index}" + situation["people"][person] = { + "age": {YEAR: 40}, + "employment_income": {YEAR: 60_000}, + } + situation["households"][f"household_{index}"] = { + "members": [person], + "state_name": {YEAR: code.rsplit("_", 1)[1]}, + "county": {YEAR: code}, + } + for group in groups: + situation[group][f"{group}_{index}"] = {"members": [person]} + + simulation = _load_simulation()(situation=situation) + benchmark = simulation.calculate("slcsp", YEAR, map_to="household") + + assert len(benchmark) == len(codes) + assert { + code for code, premium in zip(codes, benchmark, strict=True) if premium == 0 + } == COUNTIES_WITHOUT_BENCHMARK + + +@pytest.mark.parametrize( + ("zip_code", "state"), [("29135", "SC"), ("29824", "SC"), ("32456", "FL")] +) +def test_a_county_without_a_benchmark_shows_no_premium_tax_credit( + zip_code, state +) -> None: + """What the page's note says, with the state default county as the control.""" + response = compute_series( + _payload(state=state, zip=zip_code), max_earned_income=60_000, step=10_000 + ) + state_default = compute_series( + _payload(state=state), max_earned_income=60_000, step=10_000 + ) + + assert response["location"]["has_benchmark_premium"] is False + assert all(point["aca_ptc"] == 0 for point in response["data"]) + assert any(point["aca_ptc"] > 0 for point in state_default["data"])