From d3e4bc6bae37f4e657f6255b13621aab8e16609b Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 14 Nov 2026 20:36:56 -0500 Subject: [PATCH 01/20] Make the county rung a production county calibration (#922) Extend tools/us_acs_local_county_surface.py and its hooks in tools/build_us_acs_local_release.py so `--geographies state,cd,county --soi-mode state_county` calibrates every county: ACS county households (B11001) as trained levels under new state parents, the IRS SOI county split with Kalawao in a declared {15005, 15009} cell, held-out ACS validation families scored after calibration, minimum support, and a reliability grade and CSV for every county. Adds the production county test file. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_acs_local_county_production.py | 1262 +++++++++++ tools/build_us_acs_local_release.py | 38 +- tools/us_acs_local_county_surface.py | 1933 ++++++++++++++++- 3 files changed, 3145 insertions(+), 88 deletions(-) create mode 100644 packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py new file mode 100644 index 0000000000..bf5f222f72 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py @@ -0,0 +1,1262 @@ +"""The production county rung: ACS families, Kalawao, support and grades. + +microcosm#922. Fixtures follow the pinned county facts' projected row shape: +ACS rows carry ``dimensions.statistic`` (estimate or margin_of_error, ids +ending E or M), B01003 splits its counties across two record sets, B19013 +lacks a county, and IRS SOI county rows are tax-year all-return totals. +""" + +from __future__ import annotations + +import copy +import hashlib +import importlib.util +import json +import math +from functools import lru_cache +from types import SimpleNamespace + +import numpy as np +import pandas as pd +import pytest +from scipy import sparse + +from microcosm.calibrate import TargetRegistry +from test_support.paths import paths_for + +hypothesis = pytest.importorskip("hypothesis") +from hypothesis import given, settings # noqa: E402 +from hypothesis import strategies as st # noqa: E402 + +_SETTINGS = settings(max_examples=40, deadline=None) + + +@lru_cache +def _fixtures(): + path = ( + paths_for("microcosm-build").tests + / "engine_free" + / "us" + / "test_us_acs_local_county_surface.py" + ) + spec = importlib.util.spec_from_file_location( + "county_production_fixtures", path + ) + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + spec.loader.exec_module(module) + return module + + +def _county(): + return _fixtures()._county() + + +def _release(): + return _fixtures()._release() + + +_TABLE_DIMENSIONS = { + "B11001_001": {"household_type": "all"}, + "B11001_002": {"household_type": "family"}, + "B11001_007": {"household_type": "nonfamily"}, + "B19051_001": {"earnings_status": "all"}, + "B19051_002": {"earnings_status": "with_earnings"}, + "B19051_003": {"earnings_status": "without_earnings"}, + "B19001_001": {"income_range": "all"}, +} + + +def _dimensions(measure): + stem = measure[:-1] + if stem in _TABLE_DIMENSIONS: + return dict(_TABLE_DIMENSIONS[stem]) + for bracket, label, _lower, _upper in _county().B19001_BRACKETS: + if bracket[:-1] == stem: + return {"income_range": label} + return {} + + +def _acs_fact(county, measure, value, *, group=0, name=None): + """One projected ACS county row, in the pinned file's shape.""" + table = measure.split("_")[0].lower() + statistic = "estimate" if measure.endswith("E") else "margin_of_error" + return { + "aggregate_fact_key": f"ledger.aggregate_fact.v2:{county}{measure}", + "schema_version": "chronicle.consumer_fact.v5", + "geography": { + "id": f"0500000US{county}", + "level": "county", + "name": name or f"Fixture County {county}, Fixture State", + "vintage": "2024", + }, + "observed_measure": { + "source_concept": f"{measure} ({statistic})", + "source_measure_id": measure, + "source_name": "census_acs", + "source_table": f"ACS 2020-2024 5-year {table.upper()}", + "unit": "USD" if table in {"b19013", "b19025", "b19061"} else "count", + }, + "dimensions": {**_dimensions(measure), "statistic": statistic}, + "period": {"type": "calendar_year", "value": 2024}, + "value": value, + "value_type": "integer", + "layout": { + "groupby_dimension": "census_acs.county", + "groupby_value_id": county, + "measure_id": measure, + "record_set_id": f"census_acs.acs5_2020_2024.{table}.county.group_{group}", + "record_set_spec_id": f"census_acs.acs5.{table}.county.v1", + "source_column_id": measure, + "source_row_id": county, + "table_record_kind": "total", + }, + } + + +def _county_values(code, seed=0): + rng = np.random.default_rng(int(code) + 7919 * seed) + households = int(rng.integers(50, 5_000)) + brackets = rng.multinomial(households, np.full(16, 1 / 16)) + return { + "households": households, + "earning_households": int(households * rng.uniform(0.5, 0.9)), + "earnings": int(households * rng.uniform(20_000, 90_000)), + "income": int(households * rng.uniform(30_000, 120_000)), + "brackets": [int(value) for value in brackets], + "median": int(rng.uniform(30_000, 120_000)), + "population": int(households * rng.uniform(2.0, 3.0)), + } + + +def _acs_rows(counties, *, values=None, without_median=(), b01003_group_1=()): + """All seven ACS county tables for ``counties`` (five-digit strings). + + Margins of error ride beside most estimates; B01003 estimates sit in + record set group_0 without margins, except ``b01003_group_1`` counties, + which carry both in group_1. ``without_median`` counties have no B19013. + """ + values = values or {} + rows = [] + for county in counties: + data = values.get(county) or _county_values(county) + cells = { + "B11001_001": data["households"], + "B11001_002": int(data["households"] * 0.6), + "B11001_007": data["households"] - int(data["households"] * 0.6), + "B19051_001": data["households"], + "B19051_002": data["earning_households"], + "B19051_003": data["households"] - data["earning_households"], + "B19061_001": data["earnings"], + "B19025_001": data["income"], + "B19001_001": sum(data["brackets"]), + } + for (bracket, *_rest), value in zip( + _county().B19001_BRACKETS, data["brackets"], strict=True + ): + cells[bracket[:-1]] = value + for stem, value in cells.items(): + rows.append(_acs_fact(county, f"{stem}E", value)) + rows.append(_acs_fact(county, f"{stem}M", max(1, int(value * 0.05)))) + if county not in without_median: + rows.append(_acs_fact(county, "B19013_001E", data["median"], group=1)) + rows.append(_acs_fact(county, "B19013_001M", 900, group=1)) + if county in b01003_group_1: + rows.append(_acs_fact(county, "B01003_001E", data["population"], group=1)) + rows.append(_acs_fact(county, "B01003_001M", 40, group=1)) + else: + rows.append(_acs_fact(county, "B01003_001E", data["population"], group=0)) + return rows + + +def _soi_rows(values): + """IRS SOI county rows, ``{county: (returns, agi)}``.""" + fixture = _fixtures() + rows = [] + for county, (returns, agi) in values.items(): + for measure, value in ( + ("return_count", returns), + ("adjusted_gross_income", agi), + ): + row = fixture._fact(county, measure, value) + row["layout"]["groupby_value_id"] = f"county_{county}" + rows.append(row) + return rows + + +def _codes(counties): + return [f"{int(code):05d}" for code in counties] + + +# --- ACS fact parsing --------------------------------------------------------- + + +def test_acs_values_train_on_estimates_and_carry_optional_margins() -> None: + county = _county() + rows = _acs_rows(["01001", "01003"], b01003_group_1=["01003"]) + # Drop one margin: an estimate never needs its MOE row. + rows = [ + row + for row in rows + if not ( + row["observed_measure"]["source_measure_id"] == "B11001_001M" + and row["geography"]["id"].endswith("01001") + ) + ] + values = county.acs_county_values( + rows, ["B11001_001E", "B01003_001E"], required={1001: 1.0, 1003: 1.0} + ) + households = values["B11001_001E"] + assert households[1001][1] is None + assert households[1003][1] is not None + assert households[1003][0] != households[1003][1] + # B01003 reaches every county only across its two record sets. + assert set(values["B01003_001E"]) == {1001, 1003} + assert values["B01003_001E"][1001][1] is None + assert values["B01003_001E"][1003][1] == 40 + + +@pytest.mark.parametrize( + "case", + ["missing", "unexpected", "duplicate", "negative", "statistic", "layout", "pr"], +) +def test_acs_county_inventory_refusals(case) -> None: + county = _county() + rows = _acs_rows(["01001", "01003"]) + estimate = next( + row + for row in rows + if row["observed_measure"]["source_measure_id"] == "B11001_001E" + ) + required = {1001: 1.0, 1003: 1.0} + if case == "missing": + rows.remove(estimate) + match = "missing=\\['01001'\\]" + elif case == "unexpected": + rows += _acs_rows(["01005"]) + match = "unexpected=\\['01005'\\]" + elif case == "duplicate": + rows.append(copy.deepcopy(estimate)) + match = "Duplicate" + elif case == "negative": + estimate["value"] = -1 + match = "nonnegative" + elif case == "statistic": + estimate["dimensions"]["statistic"] = "margin_of_error" + match = "statistic" + elif case == "layout": + estimate["layout"]["groupby_value_id"] = "01003" + match = "disagree" + else: + rows += _acs_rows(["72001"]) + match = "Puerto Rico" + with pytest.raises(ValueError, match=match): + county.acs_county_values(rows, ["B11001_001E"], required=required) + + +def test_a_puerto_rico_soi_row_reaching_the_rung_is_refused() -> None: + fixture = _fixtures() + county = _county() + rows = _soi_rows({"01001": (10, 100), "72001": (5, 50)}) + with pytest.raises(ValueError, match="Puerto Rico"): + county.state_county_soi_surface( + [fixture._state_spec(), fixture._state_spec("adjusted_gross_income")], + rows, + {1001: 10.0}, + ) + + +def test_median_income_is_a_diagnostic_and_a_missing_county_is_listed() -> None: + county = _county() + counties = ["35001", "35011"] + design = county.county_validation_design( + _acs_rows(counties, without_median=["35011"]), {35001: 10.0, 35011: 5.0} + ) + assert design["median_income_diagnostic"]["missing"] == ["35011"] + measures = { + measure + for family in design["families"].values() + for measure in family["source_measure_ids"] + } + assert "B19013_001E" not in measures + + +def test_validation_design_refuses_a_zero_state_denominator_and_bad_brackets() -> ( + None +): + county = _county() + values = {code: _county_values(code) for code in ["01001", "01003"]} + for data in values.values(): + data["earnings"] = 0 + with pytest.raises(ValueError, match="share denominator"): + county.county_validation_design( + _acs_rows(list(values), values=values), {1001: 1.0, 1003: 1.0} + ) + rows = _acs_rows(["01001"]) + for row in rows: + if row["observed_measure"]["source_measure_id"] == "B19001_003E": + row["dimensions"]["income_range"] = "10000_to_19999" + with pytest.raises(ValueError, match="bracket"): + county.county_validation_design(rows, {1001: 1.0}) + + +# --- ACS households (trained) ------------------------------------------------- + + +@st.composite +def _acs_layouts(draw): + states = draw( + st.lists(st.sampled_from([1, 6, 12, 15, 36]), min_size=1, max_size=3, unique=True) + ) + counties = {} + for state in states: + for index in range(draw(st.integers(1, 5))): + code = state * 1000 + 2 * index + 1 + counties[code] = float(draw(st.integers(1, 10_000_000))) + values = { + f"{code:05d}": { + **_county_values(f"{code:05d}"), + "households": draw(st.integers(0, 2_000_000)), + } + for code in counties + } + for state in states: + codes = [f"{code:05d}" for code in counties if code // 1000 == state] + if not any(values[code]["households"] for code in codes): + values[codes[0]]["households"] = 1 + return counties, values + + +@_SETTINGS +@given(_acs_layouts()) +def test_acs_household_children_sum_to_their_new_state_parent(layout) -> None: + county = _county() + populations, values = layout + surface = county.acs_household_surface( + _acs_rows(list(values), values=values), populations + ) + parents = { + spec.metadata["state_fips"]: spec + for spec in surface.specs + if spec.metadata["geography_level"] == "state" + } + for state, parent in parents.items(): + public = math.fsum( + data["households"] + for code, data in values.items() + if code[:2] == state + ) + assert parent.value == pytest.approx(public, rel=1e-12) + assert parent.family == "acs_households" + children = [ + spec + for spec in surface.specs + if spec.metadata.get("state_county_parent_target_name") == parent.name + ] + assert {child.metadata["county_fips"] for child in children} == { + code for code in values if code[:2] == state + } + assert math.fsum(child.value for child in children) == pytest.approx( + parent.value, rel=1e-12, abs=1e-9 + ) + assert surface.receipt["new_state_targets"] == len(parents) + + +def test_acs_household_specs_share_one_label_per_geography_with_other_targets() -> ( + None +): + fixture = _fixtures() + county = _county() + module = _release() + populations = {1001: 80.0, 1003: 120.0} + acs = county.acs_household_surface(_acs_rows(["01001", "01003"]), populations) + population_specs = module.population_target_specs( + ["pop_state_01", "pop_county_01001", "pop_county_01003"], [200.0, 80.0, 120.0] + ) + TargetRegistry( + (*population_specs, *acs.specs, fixture._state_spec()), country="us" + ) + + +def _households(rows): + frame = pd.DataFrame(rows) + frame["household_id"] = np.arange(1, len(frame) + 1) + return frame + + +def test_household_universe_excludes_acs_group_quarters_only() -> None: + county = _county() + households = pd.DataFrame( + { + "household_spine": ["acs_2024_1yr"] * 3 + ["asec_puf"], + "TYPEHUGQ": [1, 2, 3, np.nan], + } + ) + np.testing.assert_array_equal(county.household_universe(households), [1, 0, 0, 1]) + for bad in ( + households.assign(TYPEHUGQ=[1, 2, np.nan, np.nan]), + households.assign(TYPEHUGQ=[1, 2, 4, np.nan]), + households.assign(TYPEHUGQ=[1, 2, 3, 1]), + households.drop(columns="TYPEHUGQ"), + ): + with pytest.raises(ValueError): + county.household_universe(bad) + + +@_SETTINGS +@given( + st.lists( + st.tuples( + st.sampled_from([1001, 1003, 6001, 6003, 6005]), + st.sampled_from(["acs_2024_1yr", "asec_puf"]), + st.sampled_from([1, 2, 3]), + ), + min_size=1, + max_size=40, + ) +) +def test_acs_household_rows_partition_each_state_row(draws) -> None: + county = _county() + households = _households( + { + "county_fips": code, + "state_fips": code // 1000, + "household_spine": spine, + "TYPEHUGQ": kind if spine == "acs_2024_1yr" else np.nan, + } + for code, spine, kind in draws + ) + populations = {code: 10.0 for code in (1001, 1003, 6001, 6003, 6005)} + specs = county.acs_household_surface( + _acs_rows(_codes(populations)), populations + ).specs + rows = county.acs_household_rows(households, specs) + universe = county.household_universe(households) + for index, spec in enumerate(specs): + if spec.metadata["geography_level"] != "state": + continue + children = [ + child + for child, other in enumerate(specs) + if other.metadata.get("state_county_parent_target_name") == spec.name + ] + parent = rows[[index]].toarray()[0] + np.testing.assert_array_equal(rows[children].toarray().sum(axis=0), parent) + # Each household counts in at most one county row, and only if it is + # a household (not group quarters). + assert (rows[children].toarray() > 0).sum(axis=0).max(initial=0) <= 1 + in_state = households["state_fips"].to_numpy() == int(spec.metadata["state_fips"]) + np.testing.assert_array_equal(parent, universe * in_state) + + +# --- Kalawao and declared combined SOI cells --------------------------------- + +_HAWAII = {15001: 200.0, 15003: 1000.0, 15005: 80.0, 15007: 70.0, 15009: 160.0} + + +def _hawaii_parents(): + fixture = _fixtures() + return [ + fixture._state_spec(state="15", value=500.0), + fixture._state_spec("adjusted_gross_income", 50_000.0, state="15"), + ] + + +def _hawaii_soi(without=(15005,)): + return _soi_rows( + { + f"{code:05d}": (int(population), int(population * 100)) + for code, population in _HAWAII.items() + if code not in without + } + ) + + +def test_kalawao_shares_a_declared_soi_cell_with_maui() -> None: + county = _county() + surface = county.state_county_soi_surface( + _hawaii_parents(), _hawaii_soi(), _HAWAII + ) + maui = [spec for spec in surface.specs if spec.metadata["county_fips"] == "15009"] + assert len(maui) == 2 + for spec in maui: + assert spec.metadata["state_county_cell_members"] == "15005,15009" + assert "fewer than 20 returns" in spec.metadata["state_county_cell_basis"] + published = sum( + population for code, population in _HAWAII.items() if code != 15005 + ) + assert float(spec.metadata["state_county_share"]) == pytest.approx( + 160.0 / published + ) + assert float(spec.metadata["county_population"]) == 80.0 + 160.0 + assert not [ + spec for spec in surface.specs if spec.metadata["county_fips"] == "15005" + ] + (merge,) = surface.receipt["combined_cells"] + assert merge["members"] == ["15005", "15009"] + assert merge["absent_from_soi"] == "15005" + assert set(merge["concepts"]) == { + "return_count|2022", + "adjusted_gross_income|2022", + } + assert "22incydocguide" in merge["source"] + + +def test_an_undeclared_absent_county_is_still_refused() -> None: + county = _county() + with pytest.raises(ValueError, match="missing=\\['15007'\\]"): + county.state_county_soi_surface( + _hawaii_parents(), _hawaii_soi(without=(15005, 15007)), _HAWAII + ) + with pytest.raises(ValueError, match="missing=\\['15005'\\]"): + county.state_county_soi_surface( + _hawaii_parents(), _hawaii_soi(), _HAWAII, combined_cells={} + ) + # A host that is itself absent cannot carry the absent county. + with pytest.raises(ValueError, match="missing"): + county.state_county_soi_surface( + _hawaii_parents(), _hawaii_soi(without=(15005, 15009)), _HAWAII + ) + + +@pytest.mark.parametrize( + ("cells", "match"), + [({15005: 6001}, "one state"), ({15005: 15005}, "distinct"), ({15005: 15009, 15009: 15001}, "itself merged")], +) +def test_declared_combined_cells_must_be_well_formed(cells, match) -> None: + with pytest.raises(ValueError, match=match): + _county().state_county_soi_surface( + _hawaii_parents(), _hawaii_soi(), _HAWAII, combined_cells=cells + ) + + +def test_a_present_declared_county_keeps_its_own_soi_row() -> None: + surface = _county().state_county_soi_surface( + _hawaii_parents(), _hawaii_soi(without=()), _HAWAII + ) + assert surface.receipt["combined_cells"] == [] + assert {spec.metadata["county_fips"] for spec in surface.specs} == _codes( + _HAWAII + ).__class__(_codes(_HAWAII)) | set() + + +@_SETTINGS +@given( + st.lists(st.sampled_from(sorted(_HAWAII)), min_size=1, max_size=30), + st.lists(st.integers(-1000, 1000), min_size=30, max_size=30), +) +def test_combined_cells_partition_the_parent_row_exactly(codes, values) -> None: + county = _county() + surface = county.state_county_soi_surface( + _hawaii_parents(), _hawaii_soi(), _HAWAII + ) + households = _households( + {"county_fips": code, "state_fips": 15} for code in codes + ) + parents = _hawaii_parents() + data = np.asarray(values[: len(codes)], dtype=np.float32) + parent_matrix = sparse.csr_array(np.vstack([np.ones(len(codes)), data])) + children = county.split_state_rows( + parents, parent_matrix, surface.specs, households + ) + for index, parent in enumerate(parents): + rows = [ + row + for row, spec in enumerate(surface.specs) + if spec.metadata["state_county_parent_target_name"] == parent.name + ] + dense = children[rows].toarray() + np.testing.assert_array_equal( + dense.sum(axis=0), parent_matrix[[index]].toarray()[0] + ) + # Every household is in exactly one SOI cell of each concept. + np.testing.assert_array_equal( + (children[rows].toarray() != 0).sum(axis=0) <= 1, True + ) + kalawao = households["county_fips"].to_numpy() == 15005 + maui_row = next( + position + for position, row in enumerate(rows) + if surface.specs[row].metadata["county_fips"] == "15009" + ) + np.testing.assert_array_equal( + dense[maui_row][kalawao], parent_matrix[[index]].toarray()[0][kalawao] + ) + assert math.fsum( + spec.value + for spec in surface.specs + if spec.metadata["state_county_parent_target_name"] == parents[0].name + ) == pytest.approx(parents[0].value) + + +def test_split_rows_refuse_overlapping_member_sets() -> None: + county = _county() + surface = county.state_county_soi_surface( + _hawaii_parents(), _hawaii_soi(), _HAWAII + ) + specs = list(surface.specs) + tampered = [ + spec + if spec.metadata["county_fips"] != "15001" + else type(spec)( + **{ + **{field: getattr(spec, field) for field in spec.__dataclass_fields__}, + "metadata": { + **spec.metadata, + "state_county_cell_members": "15001,15005", + }, + } + ) + for spec in specs + ] + households = _households({"county_fips": 15001, "state_fips": 15} for _ in range(2)) + with pytest.raises(ValueError, match="overlap"): + county.split_state_rows( + _hawaii_parents(), + sparse.csr_array(np.ones((2, 2), np.float32)), + tampered, + households, + ) + + +def test_any_all_return_soi_concept_with_a_broad_parent_gets_county_rows() -> None: + fixture = _fixtures() + county = _county() + parents = [ + fixture._state_spec(), + fixture._state_spec("adjusted_gross_income", 1000.0), + fixture._state_spec( + "wages_and_salaries_amount", + 600.0, + ledger_measure_unit="usd", + ), + ] + facts = _soi_rows({"01001": (10, 100), "01003": (30, 300)}) + for code, value in (("01001", 40.0), ("01003", 120.0)): + row = fixture._fact(code, "wages_and_salaries_amount", value) + row["observed_measure"]["unit"] = "usd" + facts.append(row) + surface = county.state_county_soi_surface( + parents, facts, {1001: 1.0, 1003: 1.0} + ) + wages = { + spec.metadata["county_fips"]: spec.value + for spec in surface.specs + if spec.metadata["source_measure_id"] == "wages_and_salaries_amount" + } + assert wages == pytest.approx({"01001": 150.0, "01003": 450.0}) + assert "wages_and_salaries_amount" in surface.receipt["concepts"] + + +# --- minimum support ---------------------------------------------------------- + + +def _support_households(cells, *, tract=(), gq=(), disagree=()): + """Households from ``[(puma, county), ...]``; flags index into ``cells``.""" + rows = [] + for index, (puma, code) in enumerate(cells): + acs = index % 2 == 0 + rows.append( + { + "household_id": 1000 + index, + "state_fips": code // 1000, + "county_fips": f"{code:05d}", + "county_fips_2023": f"{code + 2 if index in disagree else code:05d}", + "puma": f"{puma:07d}", + "household_spine": "acs_2024_1yr" if acs else "asec_puf", + "household_source_id": index, + "TYPEHUGQ": (2.0 if index in gq else 1.0) if acs else np.nan, + "tract_geoid": f"{code:05d}000100" if index in tract else None, + "size_marker": index, + } + ) + return pd.DataFrame(rows) + + +def test_minimum_support_moves_exactly_k_same_puma_households() -> None: + county = _county() + cells = [(100001, 1001)] * 8 + [(100001, 1003)] * 4 + [(100002, 1007)] * 5 + households = _support_households(cells, tract=(0,), gq=(2,), disagree=(4,)) + populations = {1001: 100.0, 1003: 50.0, 1005: 12.0, 1007: 60.0} + overlaps = county.puma_overlaps( + [100001, 100001, 100001, 100002, 100002], + [1001, 1003, 1005, 1005, 1007], + [90.0, 50.0, 10.0, 2.0, 58.0], + ) + moves, receipt = county.plan_minimum_support( + households, populations, overlaps, per_county=3 + ) + assert receipt["unsupported_before"] == ["01005"] + assert len(moves) == 3 + assert {move["to_county"] for move in moves} == {"01005"} + assert {move["puma"] for move in moves} == {"0100001"} + moved = set(move["household_id"] for move in moves) + # Ineligible households (tract, group quarters, disagreeing columns) stay. + assert moved.isdisjoint({1000, 1002, 1004}) + # The donor county keeps at least k households. + remaining = households.loc[ + ~households["household_id"].isin(moved), "county_fips" + ].value_counts() + assert remaining.min() >= 3 + applied = county.apply_support_moves(households, moves) + changed = applied["household_id"].isin(moved) + assert (applied.loc[changed, "county_fips"] == "01005").all() + assert (applied.loc[changed, "county_fips_2023"] == "01005").all() + untouched = [ + column + for column in households.columns + if column not in {"county_fips", "county_fips_2023"} + ] + pd.testing.assert_frame_equal(applied[untouched], households[untouched]) + pd.testing.assert_frame_equal(applied[~changed], households[~changed]) + + +def test_minimum_support_is_all_or_nothing_and_names_the_county() -> None: + county = _county() + cells = [(100001, 1001)] * 4 + households = _support_households(cells) + overlaps = county.puma_overlaps([100001, 100001], [1001, 1003], [90.0, 10.0]) + moves, receipt = county.plan_minimum_support( + households, {1001: 90.0, 1003: 10.0}, overlaps, per_county=3 + ) + assert moves == [] + assert receipt["counties"]["01003"]["status"] == "insufficient_eligible_donors" + assert receipt["counties"]["01003"]["moved"] == 0 + + +def test_a_fully_supported_frame_is_returned_unchanged() -> None: + county = _county() + households = _support_households([(100001, 1001)] * 3 + [(100001, 1003)] * 3) + moves, receipt = county.plan_minimum_support( + households, {1001: 1.0, 1003: 1.0}, {}, per_county=3 + ) + assert moves == [] and receipt["unsupported_before"] == [] + assert county.apply_support_moves(households, moves) is households + + +@st.composite +def _support_layouts(draw): + states = draw(st.lists(st.sampled_from([1, 6]), min_size=1, max_size=2, unique=True)) + overlaps_rows, cells, populations = [], [], {} + for state in states: + pumas = [state * 100_000 + index + 1 for index in range(draw(st.integers(1, 2)))] + counties = [state * 1000 + 2 * index + 1 for index in range(draw(st.integers(2, 5)))] + for code in counties: + populations[code] = float(draw(st.integers(0, 1000))) + for puma in draw(st.lists(st.sampled_from(pumas), min_size=1, max_size=2, unique=True)): + overlaps_rows.append((puma, code, float(draw(st.integers(1, 500))))) + cells += [(puma, code)] * draw(st.integers(0, 7)) + if not cells: + cells = [(overlaps_rows[0][0], overlaps_rows[0][1])] + flags = draw( + st.lists(st.sampled_from(["", "tract", "gq", "disagree"]), min_size=len(cells), max_size=len(cells)) + ) + per_county = draw(st.integers(1, 4)) + order = draw(st.permutations(range(len(cells)))) + return overlaps_rows, cells, populations, flags, per_county, order + + +@_SETTINGS +@given(_support_layouts()) +def test_minimum_support_invariants(layout) -> None: + county = _county() + overlap_rows, cells, populations, flags, per_county, order = layout + households = _support_households( + cells, + tract={i for i, flag in enumerate(flags) if flag == "tract"}, + gq={i for i, flag in enumerate(flags) if flag == "gq"}, + disagree={i for i, flag in enumerate(flags) if flag == "disagree"}, + ) + overlaps = county.puma_overlaps(*zip(*overlap_rows, strict=True)) + moves, receipt = county.plan_minimum_support( + households, populations, overlaps, per_county=per_county + ) + before = households.set_index("household_id") + supported = set(before["county_fips"].astype(int)) + destinations = {} + for move in moves: + destination = int(move["to_county"]) + destinations[destination] = destinations.get(destination, 0) + 1 + source = before.loc[move["household_id"]] + # Never into a county with support; state and PUMA unchanged. + assert destination not in supported + assert populations[destination] > 0 + assert int(move["puma"]) == int(source["puma"]) + assert destination // 1000 == int(source["state_fips"]) + assert int(move["puma"]) in {puma for puma, _ in overlaps[destination]} + # Only eligible households move. + assert pd.isna(source["tract_geoid"]) + assert source["county_fips"] == source["county_fips_2023"] + assert source["TYPEHUGQ"] != 2.0 + # The count moved into a county is exact. + assert set(destinations.values()) <= {per_county} + after = county.apply_support_moves(households, moves) + counts = after["county_fips"].astype(int).value_counts() + for code in supported: + if code in {int(move["from_county"]) for move in moves}: + assert counts[code] >= per_county + for column in households.columns: + if column not in {"county_fips", "county_fips_2023"}: + pd.testing.assert_series_equal(after[column], households[column]) + # Deterministic, and independent of row order. + shuffled = households.iloc[list(order)].reset_index(drop=True) + again, _receipt = county.plan_minimum_support( + shuffled, populations, overlaps, per_county=per_county + ) + assert sorted(again, key=json.dumps) == sorted(moves, key=json.dumps) + assert receipt["moves_sha256"] == county._moves_digest(moves) + + +def test_recorded_moves_reapply_to_a_fresh_frame_and_refuse_a_changed_plan( + tmp_path, +) -> None: + from microcosm.frame import US_SCHEMA, Frame, WeightKind, Weights + + county = _county() + cells = [(100001, 1001)] * 8 + households = _support_households(cells) + overlaps = county.puma_overlaps([100001, 100001], [1001, 1003], [90.0, 10.0]) + moves, receipt = county.plan_minimum_support( + households, {1001: 90.0, 1003: 10.0}, overlaps, per_county=3 + ) + ids = households["household_id"].to_numpy() + tables = { + "household": households, + "person": pd.DataFrame( + { + "person_id": ids, + "person_household_id": ids, + **{f"person_{group}_id": ids for group in US_SCHEMA.group_entities}, + } + ), + } + for group in US_SCHEMA.group_entities: + tables[group] = pd.DataFrame({f"{group}_id": ids}) + frame = Frame( + tables, + US_SCHEMA, + {"household": Weights(np.ones(len(ids)), WeightKind.DESIGN)}, + ) + (tmp_path / county.SUPPORT_FILENAME).write_text( + json.dumps({"minimum_support": receipt}) + ) + identity = { + "county_column": "county_fips", + "county_support": { + "moves": len(moves), + "moves_sha256": receipt["moves_sha256"], + "rewritten_columns": receipt["rewritten_columns"], + }, + } + moved = county.apply_recorded_support(frame, identity, tmp_path) + expected = county.apply_support_moves(households, moves) + pd.testing.assert_frame_equal( + moved.table("household").reset_index(drop=True), + expected.reset_index(drop=True), + check_dtype=False, + ) + assert county.apply_recorded_support(frame, {}, tmp_path) is frame + tampered = copy.deepcopy(receipt) + tampered["moves"][0]["to_county"] = "01001" + (tmp_path / county.SUPPORT_FILENAME).write_text( + json.dumps({"minimum_support": tampered}) + ) + with pytest.raises(SystemExit, match="no longer holds"): + county.apply_recorded_support(frame, identity, tmp_path) + stale = county.apply_support_moves(households, moves) + with pytest.raises(ValueError, match="no longer matches"): + county.apply_support_moves(stale, moves) + + +def test_check_support_applies_minimum_support_before_refusing( + monkeypatch, tmp_path +) -> None: + from microcosm.frame import US_SCHEMA, Frame, WeightKind, Weights + + county = _county() + households = _support_households([(100001, 1001)] * 8) + ids = households["household_id"].to_numpy() + tables = { + "household": households, + "person": pd.DataFrame( + { + "person_id": ids, + "person_household_id": ids, + **{f"person_{group}_id": ids for group in US_SCHEMA.group_entities}, + } + ), + } + for group in US_SCHEMA.group_entities: + tables[group] = pd.DataFrame({f"{group}_id": ids}) + frame = Frame( + tables, US_SCHEMA, {"household": Weights(np.ones(8), WeightKind.DESIGN)} + ) + monkeypatch.setattr( + county, + "county_puma_overlaps", + lambda _path: county.puma_overlaps( + [100001, 100001], [1001, 1003], [90.0, 10.0] + ), + ) + populations = {"county": {1001: 90.0, 1003: 10.0}} + args = SimpleNamespace( + county_column="county_fips", + county_min_support=3, + ladder=tmp_path / "ladder.npz", + checkpoint_dir=tmp_path, + allow_partial_geography=False, + sample_fraction=1.0, + ) + result = county.check_support(frame, populations, args) + report = json.loads((tmp_path / county.SUPPORT_FILENAME).read_text()) + assert report["unsupported_counties"] == [] + assert report["counties"]["01003"]["supporting_households"] == 3 + assert len(report["minimum_support"]["moves"]) == 3 + assert args.county_support_receipt["moved_counties"] == ["01003"] + assert (result.table("household")["county_fips"] == "01003").sum() == 3 + # Without the step the same frame is refused. + with pytest.raises(SystemExit, match="no supporting household"): + county.check_support( + frame, populations, SimpleNamespace(**{**vars(args), "county_min_support": 0}) + ) + + +# --- validation scoring and the reliability grade ---------------------------- + + +def _validation_inputs(counties, households_per_county, *, seed=0): + county = _county() + populations = {int(code): 100.0 + int(code) % 97 for code in counties} + design = county.county_validation_design(_acs_rows(counties), populations) + rng = np.random.default_rng(seed) + codes = np.repeat( + np.asarray([int(code) for code in counties]), households_per_county + ) + n = len(codes) + households = pd.DataFrame( + { + "household_id": np.arange(1, n + 1), + "county_fips": codes, + "state_fips": codes // 1000, + "household_spine": np.where(np.arange(n) % 2 == 0, "acs_2024_1yr", "asec_puf"), + "household_source_id": np.arange(n), + } + ) + earnings = rng.uniform(0, 100_000, n) * (rng.uniform(size=n) > 0.2) + measures = { + "household_id": households["household_id"].to_numpy(), + "in_household_universe": (rng.uniform(size=n) > 0.05).astype(float), + "earnings": earnings, + "household_income_approx": earnings + rng.uniform(-5_000, 60_000, n), + } + return design, measures, households, rng.uniform(0.5, 3.0, n) + + +def test_validation_targets_redistribute_each_state_total_by_public_shares() -> None: + county = _county() + counties = ["01001", "01003", "01005", "06001", "06003"] + design, measures, households, weights = _validation_inputs(counties, [5, 3, 4, 6, 2]) + result = county.score_county_validation( + design, + measures, + households, + final_weights=weights, + design_weights=np.ones(len(weights)), + cap=10.0, + ) + assert result["never_in_loss"] is True + for family in county.VALIDATION_FAMILIES: + if family.household_measure == "income_bracket": + continue + for state in ("01", "06"): + cells = [ + result["counties"][code][family.name] + for code in counties + if code.startswith(state) + ] + assert math.fsum(cell["target"] for cell in cells) == pytest.approx( + math.fsum(cell["estimate"] for cell in cells), rel=1e-9 + ) + assert math.fsum(cell["pro_rata"] for cell in cells) == pytest.approx( + math.fsum(cell["estimate"] for cell in cells), rel=1e-9 + ) + # Scaling every weight leaves every error unchanged (M_s scales too). + scaled = county.score_county_validation( + design, + measures, + households, + final_weights=weights * 7.5, + design_weights=np.ones(len(weights)), + cap=10.0, + ) + for code in counties: + for family in county.GRADED_VALIDATION_FAMILIES: + assert scaled["counties"][code][family]["abs_rel_error"] == pytest.approx( + result["counties"][code][family]["abs_rel_error"], rel=1e-9, abs=1e-12 + ) + + +def test_validation_scores_zero_when_estimates_match_public_shares() -> None: + county = _county() + counties = ["01001", "01003"] + design, measures, households, _weights = _validation_inputs(counties, [1, 1]) + public = design["families"]["acs_earnings"]["public"]["B19061_001E"] + measures = { + **measures, + "in_household_universe": np.ones(2), + "earnings": np.asarray([public["01001"][0], public["01003"][0]]), + } + result = county.score_county_validation( + design, + measures, + households, + final_weights=np.ones(2), + design_weights=np.ones(2), + cap=1.0, + ) + for code in counties: + assert result["counties"][code]["acs_earnings"]["abs_rel_error"] == ( + pytest.approx(0.0, abs=1e-12) + ) + + +def test_every_one_of_3144_counties_gets_a_cell_and_only_unsupported_are_u() -> None: + county = _county() + states = [state for state in range(1, 57) if state not in {3, 7, 14, 43, 52}] + counties = [] + for index in range(3_144): + state = states[index % len(states)] + counties.append(f"{state * 1000 + 1 + 2 * (index // len(states)):05d}") + assert len(set(counties)) == 3_144 + per_county = [0 if index % 997 == 0 else 2 for index in range(len(counties))] + supported = [ + code for code, count in zip(counties, per_county, strict=True) if count + ] + design, measures, households, weights = _validation_inputs(counties, per_county) + validation = county.score_county_validation( + design, + measures, + households, + final_weights=weights, + design_weights=np.ones(len(weights)), + cap=10.0, + ) + report = county.reliability_report( + households, + [], + sparse.csr_array((0, len(households))), + final_weights=weights, + validation=validation, + county_populations=design["county_populations"], + county_names=design["county_names"], + ) + assert set(report["counties"]) == set(counties) + grades = {code: cell["grade"] for code, cell in report["counties"].items()} + assert {code for code, grade in grades.items() if grade == "U"} == ( + set(counties) - set(supported) + ) + for code in supported: + cell = report["counties"][code] + assert cell["validation"]["n_families"] == len( + county.GRADED_VALIDATION_FAMILIES + ) + assert cell["grade_driver"].startswith("validation:") + assert cell["county_name"] + csv_text = county.reliability_csv(report) + lines = csv_text.splitlines() + assert lines[0].split(",")[:5] == [ + "county_fips", + "state_fips", + "county_name", + "status", + "grade", + ] + assert len(lines) == 1 + 3_144 + + +def test_minimum_support_counties_are_graded_and_marked() -> None: + county = _county() + counties = ["01001", "01003"] + design, measures, households, weights = _validation_inputs(counties, [5, 3]) + validation = county.score_county_validation( + design, + measures, + households, + final_weights=weights, + design_weights=np.ones(len(weights)), + cap=10.0, + ) + report = county.reliability_report( + households, + [], + sparse.csr_array((0, len(households))), + final_weights=weights, + validation=validation, + minimum_support_counties=["01003"], + ) + assert report["counties"]["01003"]["status"] == "minimum_support" + assert report["counties"]["01003"]["grade"] in {"A", "B", "C", "D"} + assert report["counties"]["01001"]["status"] == "supported" + + +def test_combined_soi_cell_errors_count_toward_both_member_counties() -> None: + county = _county() + households = pd.DataFrame( + { + "county_fips": [15005, 15009], + "state_fips": [15, 15], + "household_spine": ["asec_puf", "asec_puf"], + "household_source_id": [1, 2], + } + ) + records = [ + { + "name": "county_15009__returns", + "geography_level": "county", + "county_fips": "15009", + "state_county_cell_members": "15005,15009", + "value": 10.0, + "role": "holdout", + } + ] + report = county.reliability_report( + households, + records, + sparse.csr_array(np.asarray([[1.0, 1.0]])), + final_weights=np.asarray([4.0, 4.0]), + ) + for code in ("15005", "15009"): + assert report["counties"][code]["holdout"]["n_targets"] == 1 + assert report["counties"][code]["holdout"]["max_abs_rel_error"] == ( + pytest.approx(0.2) + ) + + +@_SETTINGS +@given(st.floats(0.0, 1.0), st.floats(1.0, 2_000.0), st.floats(1.0, 2_000.0)) +def test_grades_stay_monotone_in_ess_at_fixed_validation_error(error, low, high) -> None: + county = _county() + order = "UABCD" + low, high = sorted((low, high)) + grade_low = county.reliability_grade(low, error) + grade_high = county.reliability_grade(high, error) + assert "ABCD".index(grade_high) <= "ABCD".index(grade_low) + assert grade_low in order + + +def test_household_validation_measures_count_semp_once_and_exclude_gq() -> None: + from microcosm.frame import US_SCHEMA, Frame, WeightKind, Weights + + county = _county() + ids = np.asarray([1, 2, 3]) + households = pd.DataFrame( + { + "household_id": ids, + "household_spine": ["acs_2024_1yr", "acs_2024_1yr", "asec_puf"], + "TYPEHUGQ": [1.0, 3.0, np.nan], + } + ) + person = pd.DataFrame( + { + "person_id": [1, 2, 3, 4], + "person_household_id": [1, 1, 2, 3], + **{ + f"person_{group}_id": [1, 1, 2, 3] + for group in US_SCHEMA.group_entities + }, + "employment_income_before_lsr": [100.0, 50.0, 10.0, 1000.0], + # ACS SEMP routed wholly to the SSTB leaf after QBI reconciliation. + "self_employment_income_before_lsr": [0.0, 0.0, 0.0, 20.0], + "sstb_self_employment_income_before_lsr": [30.0, np.nan, 0.0, 5.0], + "farm_operations_income": [0.0, 0.0, 0.0, 7.0], + "taxable_interest_income": [1.0, 0.0, 0.0, 2.0], + "partnership_income": [99.0, 0.0, 0.0, 11.0], + } + ) + tables = {"household": households, "person": person} + for group in US_SCHEMA.group_entities: + tables[group] = pd.DataFrame({f"{group}_id": ids}) + frame = Frame( + tables, US_SCHEMA, {"household": Weights(np.ones(3), WeightKind.DESIGN)} + ) + arrays, report = county.household_validation_measures(frame) + np.testing.assert_array_equal(arrays["earnings"], [180.0, 10.0, 1032.0]) + # Partnership income is donor-only in the income approximation. + np.testing.assert_array_equal( + arrays["household_income_approx"], [181.0, 10.0, 1045.0] + ) + np.testing.assert_array_equal(arrays["in_household_universe"], [1.0, 0.0, 1.0]) + assert report["group_quarters_households"] == 1 + with pytest.raises(ValueError, match="earnings inputs"): + county.household_validation_measures( + Frame( + {**tables, "person": person.drop(columns="farm_operations_income")}, + US_SCHEMA, + {"household": Weights(np.ones(3), WeightKind.DESIGN)}, + ) + ) + + +def test_packaged_csv_must_be_the_flattening_of_the_bound_report(tmp_path) -> None: + county = _county() + counties = ["01001", "01003"] + design, measures, households, weights = _validation_inputs(counties, [3, 2]) + validation = county.score_county_validation( + design, + measures, + households, + final_weights=weights, + design_weights=np.ones(len(weights)), + cap=10.0, + ) + identity = {"geographies": "state,county", "county_column": "county_fips"} + stamp = hashlib.sha256( + json.dumps(identity, sort_keys=True, separators=(",", ":")).encode() + ).hexdigest() + summary = { + "run_identity_sha256": stamp, + "weights_sha256": "w", + "county_reliability": county.reliability_report( + households, + [], + sparse.csr_array((0, len(households))), + final_weights=weights, + validation=validation, + ), + } + (tmp_path / "calibration_summary.json").write_text(json.dumps(summary)) + county.write_reports(tmp_path, summary, identity=identity) + files = {} + extra = county.package_reports(files, tmp_path, identity) + assert set(files) == {county.RELIABILITY_FILENAME} + assert extra == { + county.RELIABILITY_CSV_FILENAME: ( + tmp_path / county.RELIABILITY_CSV_FILENAME + ).read_text() + } + csv_path = tmp_path / county.RELIABILITY_CSV_FILENAME + csv_path.write_text(csv_path.read_text().replace(",D,", ",A,", 1) + "\n") + with pytest.raises(SystemExit, match="flattening"): + county.package_reports({}, tmp_path, identity) + + +def test_acs_household_rows_have_their_own_state_budgets_in_the_loss() -> None: + county = _county() + populations = {1001: 80.0, 1003: 120.0, 6001: 50.0} + specs = county.acs_household_surface( + _acs_rows(_codes(populations)), populations + ).specs + mapping = county.loss_row_mapping(specs) + assert mapping.mapping_id == "us_acs_local_county.v2" + keys = [mapping.concept_budget_key(spec) for spec in specs] + states = [key for key, spec in zip(keys, specs, strict=True) if spec.metadata["geography_level"] == "state"] + assert len(set(states)) == 2 + counties = { + spec.metadata["state_fips"]: key + for key, spec in zip(keys, specs, strict=True) + if spec.metadata["geography_level"] == "county" + } + assert len(set(counties.values())) == 2 + assert all(mapping.value_basis(spec) == "count" for spec in specs) + weights = county.target_loss_weights(specs, {}) + assert np.isfinite(weights).all() and (weights > 0).all() diff --git a/tools/build_us_acs_local_release.py b/tools/build_us_acs_local_release.py index f819b2c7b2..bee0c7a9b5 100644 --- a/tools/build_us_acs_local_release.py +++ b/tools/build_us_acs_local_release.py @@ -2312,7 +2312,10 @@ def do_materialize(args) -> None: (args.checkpoint_dir / name).unlink(missing_ok=True) if getattr(args, "gate_report", None) is not None: Path(args.gate_report).unlink(missing_ok=True) - county_surface.check_support(frame, populations, args) + # microcosm#922: a county with ladder population but no household gets a + # fixed number of same-PUMA households before any measure is built; the + # frame returned carries their rewritten county columns. + frame = county_surface.check_support(frame, populations, args) materialized = materialize_chunked( frame, registry.specs, @@ -2485,6 +2488,7 @@ def _verify_run_identity(args, *, require: bool = True) -> dict: "calibration_summary.json", "calibration_diagnostics.json", "county_reliability.json", + "county_reliability.csv", "consumer_export.json", "consumer_reviewed_null_fills.json", "spine_qa.json", @@ -2878,12 +2882,16 @@ def calibration_evidence( design_weights: np.ndarray, weights: np.ndarray, target_loss_cap: float, + checkpoint_dir: Path | None = None, + identity: dict | None = None, ) -> dict: """The sparse-surface evidence the calibration summary adds. The CD holdout scored against the pro-rata baseline, and ESS over rows and distinct households with household-weight share by spine, at the - design and the calibrated weights. + design and the calibrated weights. With the checkpoint directory and run + identity, a county run also scores its held-out ACS validation families + (microcosm#922), which never reach the loss. """ origin = _origin_columns(frame) @@ -2907,7 +2915,14 @@ def calibration_evidence( cap=target_loss_cap, ), **county_surface.calibration_evidence( - frame, roles, matrix, design_weights, weights, target_loss_cap + frame, + roles, + matrix, + design_weights, + weights, + target_loss_cap, + checkpoint_dir=checkpoint_dir, + identity=identity, ), } @@ -3116,6 +3131,8 @@ def save(weights: np.ndarray, epochs_done: int) -> None: design_weights=design_weights, weights=np.asarray(result.weights, dtype=np.float64), target_loss_cap=args.target_loss_cap, + checkpoint_dir=args.checkpoint_dir, + identity=identity, ), "total_wall_seconds": round(time.time() - started, 1), "peak_rss_gb": round(rss(), 3), @@ -3305,6 +3322,9 @@ def _write_calibrated_artifact( # microcosm#1022: apply the ACS SSI/Medicaid take-up materialize recorded # on the same rung; it must reproduce the recorded digest. frame = _with_recorded_ssi_medicaid_take_up(frame, ssi_medicaid, ssi_medicaid_path) + # microcosm#922: re-apply the county support moves materialize recorded, + # so the published file carries the county codes calibration saw. + frame = county_surface.apply_recorded_support(frame, identity, args.checkpoint_dir) staging_ids = frame.table("household")["household_id"].to_numpy() with pd.HDFStore(args.checkpoint_dir / "target_frame_lean.h5", mode="r") as store: lean_ids = store["household"]["household_id"].to_numpy() @@ -6538,7 +6558,10 @@ def _version(package: str) -> str: "run_identity.json": identity, } contract_files["spine_qa.json"] = spine_qa - county_surface.package_reports(contract_files, args.checkpoint_dir, identity) + # The county reliability CSV ships beside its JSON (microcosm#922). + county_files = county_surface.package_reports( + contract_files, args.checkpoint_dir, identity + ) contract_files["consumer_export.json"] = consumer_export contract_files["consumer_reviewed_null_fills.json"] = consumer_fills # microcosm#1022: the notes the fills were graded against ship beside them. @@ -6548,6 +6571,8 @@ def _version(package: str) -> str: release_dir.mkdir(parents=True, exist_ok=True) for name, payload in contract_files.items(): (release_dir / name).write_text(json.dumps(payload, indent=1)) + for name, text in county_files.items(): + (release_dir / name).write_text(text) if diagnostics_status["status"] == "available": source_diagnostics = args.checkpoint_dir / "calibration_diagnostics.json" if not source_diagnostics.is_file(): @@ -6600,8 +6625,10 @@ def _artifact(path_name: str, kind: str, local: Path) -> dict: # declared artifacts only (microcosm#1570), so every other file written # above, the evidence JSON included, is declared, as the UK dense # assembler declares its evidence. - for name in contract_files: + for name in [*contract_files, *county_files]: key = Path(name).stem + if name in county_files: + key = Path(name).name.replace(".", "_") if name != "build_manifest.json" and key not in artifacts: artifacts[key] = _artifact(name, "diagnostics", release_dir / name) @@ -6638,6 +6665,7 @@ def _artifact(path_name: str, kind: str, local: Path) -> dict: ) sums = {path.name: _sha256(path) for path in sorted(release_dir.glob("*.json"))} + sums.update({name: _sha256(release_dir / name) for name in county_files}) sums[ARTIFACT_FILENAME] = h5_sha (release_dir / "sha256sums.txt").write_text( "".join(f"{digest} {name}\n" for name, digest in sorted(sums.items())) diff --git a/tools/us_acs_local_county_surface.py b/tools/us_acs_local_county_surface.py index 73dd2de0d4..f6ba2908d6 100644 --- a/tools/us_acs_local_county_surface.py +++ b/tools/us_acs_local_county_surface.py @@ -30,12 +30,43 @@ COUNTY_HOLDOUT_SALT = "acs-local-county-v1" DEFAULT_COUNTY_HOLDOUT_FRACTION = 0.1 RELIABILITY_FILENAME = "county_reliability.json" +RELIABILITY_CSV_FILENAME = "county_reliability.csv" +SUPPORT_FILENAME = "county_support.json" +SURFACE_FILENAME = "county_surface.json" +#: Materialize-time validation inputs (microcosm#922): the public county +#: design and the household measures it is scored on. Neither is a target: +#: they never enter the registry, roles, matrix or loss. +VALIDATION_DESIGN_FILENAME = "county_validation.json" +VALIDATION_MEASURES_FILENAME = "county_validation_measures.npz" SOI_MODE = "state_county" COUNTY_PREFIX = "0500000US" # The LWI release contract covers the 50 states and DC on planning-region # county boundaries. A self-consistent but incomplete ladder is not complete. REQUIRED_COUNTY_COUNT = 3_144 COUNTY_SOI_REQUIRED_MEASURES = ("return_count", "adjusted_gross_income") +#: Puerto Rico (state 72) is outside the County Files. The county facts loader +#: drops its municipios with a count; a row that still reaches this module is +#: a defect, never a county to fit. +PUERTO_RICO_STATE = 72 + +#: Counties absent from an IRS SOI county file, each merged into one declared +#: host county of the same state for the SOI families only. The IRS 2022 +#: county users guide (https://www.irs.gov/pub/irs-soi/22incydocguide.docx) +#: says items with fewer than 20 returns for a county were excluded, and +#: 22incyallnoagi.csv has no row for Kalawao County, HI (15005). Its SOI value +#: is therefore missing, not zero; the guide does not say whether its returns +#: are counted in another county's row. Kalawao is merged into Maui (15009), +#: which surrounds it: the combined cell's share is Maui's published value +#: over the state's published county sum, and its households are those in +#: either county. Kalawao keeps its own ladder population, ACS household and +#: validation rows. Any other absent county is refused unless declared here. +DECLARED_SOI_COMBINED_CELLS = {15005: 15009} +SOI_COMBINED_CELL_BASIS = ( + "IRS SOI 2022 county users guide (22incydocguide.docx): items with fewer " + "than 20 returns for a county were excluded; 22incyallnoagi.csv has no row " + "for this county, so its SOI value is missing, not zero, and it is " + "merged into its declared host county for the SOI families only." +) def _concatenate(parts, dtype): @@ -235,27 +266,80 @@ class CountySurface: receipt: dict -def state_county_soi_surface(state_specs, facts, county_populations): +def county_code_of(fact, *, source): + """The five-digit county code of a county fact, refusing bad geography. + + The row geography is authoritative. A layout group value, when present, + must name the same county (a FIPS/state mismatch is refused), and a + Puerto Rico row reaching the rung is refused explicitly. + """ + geography = fact.get("geography", {}) + if geography.get("level") != "county": + raise ValueError(f"{source} county facts must be county rows: {geography!r}.") + geoid = str(geography.get("id", "")) + digits = geoid[len(COUNTY_PREFIX) :] + if ( + not geoid.startswith(COUNTY_PREFIX) + or len(digits) != 5 + or not (digits.isascii() and digits.isdigit()) + ): + raise ValueError(f"Invalid county {source} geography {geoid!r}.") + code = int(digits) + if code // 1000 == PUERTO_RICO_STATE: + raise ValueError( + f"Puerto Rico {source} county fact {geoid} reached the county rung; " + "state 72 is outside the 3,144 County Files county-equivalents and " + "the county facts loader must drop it." + ) + if not 1 <= code // 1000 <= 56 or code % 1000 == 0: + raise ValueError(f"Invalid county {source} geography {geoid!r}.") + group = (fact.get("layout") or {}).get("groupby_value_id") + if group is not None and str(group)[-5:] != digits: + raise ValueError( + f"{source} county fact {geoid} names layout county {group!r}; " + "geography and layout disagree on the county FIPS." + ) + return code + + +def _validated_combined_cells(combined_cells): + cells = {int(absent): int(host) for absent, host in dict(combined_cells).items()} + for absent, host in cells.items(): + if absent == host or absent // 1000 != host // 1000: + raise ValueError( + f"Declared SOI combined cell {absent:05d}->{host:05d} must join two " + "distinct counties of one state." + ) + if host in cells: + raise ValueError( + f"Declared SOI combined cell host {host:05d} is itself merged." + ) + return cells + + +def state_county_soi_surface( + state_specs, + facts, + county_populations, + *, + combined_cells=DECLARED_SOI_COMBINED_CELLS, +): """Rebase complete county fact blocks onto existing broad state totals. Every state must carry county return count and AGI with unsliced state parents. Other measures require both county facts and a state parent. - New ACS families can produce the same child metadata and use split_state_rows - without extending the engine materializer. + A county absent from a block is refused unless ``combined_cells`` declares + it, with its host present: then one child row covers both counties, its + share is the host's published value over the state's published sum, and + ``state_county_cell_members`` lists the member counties. """ + combined = _validated_combined_cells(combined_cells) blocks = defaultdict(dict) for fact in facts: - geography = fact.get("geography", {}) observed = fact.get("observed_measure", {}) - if ( - geography.get("level") != "county" - or observed.get("source_name") != "irs_soi" - ): + if observed.get("source_name") != "irs_soi": continue - geoid = str(geography.get("id", "")) - if not geoid.startswith(COUNTY_PREFIX) or len(geoid) != len(COUNTY_PREFIX) + 5: - raise ValueError(f"Invalid county SOI geography {geoid!r}.") - code = int(geoid[-5:]) + code = county_code_of(fact, source="SOI") dimensions = fact.get("dimensions", {}) if any( str(dimensions.get(key, "all")).lower() != "all" @@ -311,35 +395,48 @@ def state_county_soi_surface(state_specs, facts, county_populations): f"Missing broad state SOI parent state={state:02d}, concept={measure}; " "state_county requires return count and AGI in every state." ) - specs, receipts = [], [] + specs, receipts, merges = [], [], defaultdict(list) for key, parent in sorted(parents.items()): state, measure, period = key expected = { int(code) for code in county_populations if int(code) // 1000 == state } block = blocks.get(key, {}) + absent = expected - block.keys() + merged = { + code: combined[code] + for code in absent + if code in combined + and combined[code] in block + and combined[code] in expected + } missing, extra = ( - sorted(expected - block.keys()), + sorted(absent - merged.keys()), sorted(block.keys() - expected), ) if not expected or missing or extra: raise ValueError( f"Incomplete county SOI block state={state:02d}, concept={measure}, period={period}; " f"missing={[f'{code:05d}' for code in missing]}, unexpected={[f'{code:05d}' for code in extra]}. " - "County facts, ladder and county column must use matching boundaries." + "County facts, ladder and county column must use matching boundaries; " + "only a declared combined SOI cell may cover an absent county." ) + members = {code: [code] for code in sorted(block)} + for code, host in sorted(merged.items()): + members[host].append(code) + merges[(host, code)].append(f"{measure}|{period}") total = math.fsum(value for value, _fact in block.values()) if total <= 0: raise ValueError( f"County SOI block {key} has no positive share denominator." ) - codes = sorted(expected) + codes = sorted(block) shares = [block[code][0] / total for code in codes] largest = max(range(len(codes)), key=lambda index: shares[index]) shares[largest] += 1.0 - math.fsum(shares) targets = [parent.value * share for share in shares] targets[largest] += parent.value - math.fsum(targets) - state_population = math.fsum(county_populations[code] for code in codes) + state_population = math.fsum(county_populations[code] for code in expected) for code, share, target in zip(codes, shares, targets, strict=True): raw, fact = block[code] unit = fact.get("observed_measure", {}).get("unit") @@ -351,6 +448,7 @@ def state_county_soi_surface(state_specs, facts, county_populations): f"County SOI units differ from state parent {parent.name}: {unit!r}." ) county = f"{code:05d}" + cell = sorted(members[code]) name = f"county_{county}__{parent.name}" metadata = { **parent.metadata, @@ -367,9 +465,16 @@ def state_county_soi_surface(state_specs, facts, county_populations): "state_county_parent_target_name": parent.name, "state_county_share": str(share), "state_county_source_value": str(raw), - "county_population": str(county_populations[code]), + "county_population": str( + math.fsum(county_populations[member] for member in cell) + ), "state_population": str(state_population), } + if len(cell) > 1: + metadata["state_county_cell_members"] = ",".join( + f"{member:05d}" for member in cell + ) + metadata["state_county_cell_basis"] = SOI_COMBINED_CELL_BASIS specs.append( dataclasses.replace( parent, @@ -387,13 +492,14 @@ def state_county_soi_surface(state_specs, facts, county_populations): "state_fips": f"{state:02d}", "concept": measure, "parent": parent.name, - "counties": len(codes), + "counties": len(expected), + "cells": len(codes), "share_sum": math.fsum(shares), "target_sum": math.fsum(targets), } ) # Counties without a state parent cannot silently disappear. - covered = {int(spec.metadata["county_fips"]) for spec in specs} + covered = {int(member) for spec in specs for member in cell_members(spec.metadata)} missing = sorted(set(county_populations) - covered) if missing: raise ValueError(f"Counties have no materialized SOI state parent: {missing}.") @@ -404,16 +510,43 @@ def state_county_soi_surface(state_specs, facts, county_populations): "county_targets": len(specs), "concepts": sorted({key[1] for key in parents}), "blocks": receipts, + "combined_cells": [ + { + "members": sorted((f"{host:05d}", f"{absent:05d}")), + "host": f"{host:05d}", + "absent_from_soi": f"{absent:05d}", + "concepts": sorted(concepts), + "basis": SOI_COMBINED_CELL_BASIS, + "source": "https://www.irs.gov/pub/irs-soi/22incydocguide.docx", + "own_rows_kept": "ladder population, ACS households and " + "ACS validation rows stay per county", + } + for (host, absent), concepts in sorted(merges.items()) + ], "new_engine_columns": 0, "basis": "state target x county fact / state sum of county facts", }, ) +def cell_members(metadata): + """The county codes one county child row covers (one unless combined).""" + members = metadata.get("state_county_cell_members") + if members: + return [int(member) for member in str(members).split(",")] + return [int(metadata["county_fips"])] + + def split_state_rows( state_specs, state_matrix, county_specs, households, *, county_column=COUNTY_COLUMN ): - """Partition stored parent rows exactly; never materialize new columns.""" + """Partition stored parent rows exactly; never materialize new columns. + + A child row covers its member set (``cell_members``): one county, or a + declared combined SOI cell. Member sets of one parent never overlap and + cover every household of the parent's state, so each household falls in + exactly one child row of each parent. + """ codes = county_codes(households, county_column=county_column) matrix = sparse.csr_array(state_matrix) if matrix.shape != (len(state_specs), len(households)): @@ -428,14 +561,17 @@ def split_state_rows( for parent_name, indices in blocks.items(): parent_index = by_name[parent_name] parent = state_specs[parent_index] - child_codes = [ - int(county_specs[index].metadata["county_fips"]) for index in indices + child_members = [ + cell_members(county_specs[index].metadata) for index in indices ] - if len(set(child_codes)) != len(child_codes): + flat = [code for members in child_members for code in members] + if len(set(flat)) != len(flat): raise ValueError(f"County rows of {parent_name} overlap.") state = int(parent.metadata["state_fips"]) + if any(code // 1000 != state for code in flat): + raise ValueError(f"County rows of {parent_name} leave its state.") present = codes // 1000 == state - if not np.isin(codes[present], child_codes).all(): + if not np.isin(codes[present], flat).all(): raise ValueError(f"Households of {parent_name} fall in no county row.") start, end = matrix.indptr[parent_index : parent_index + 2] positions, values = matrix.indices[start:end], matrix.data[start:end] @@ -443,8 +579,8 @@ def split_state_rows( raise ValueError( f"State row {parent_name} contains households outside its state." ) - for index, code in zip(indices, child_codes, strict=True): - selected = codes[positions] == code + for index, members in zip(indices, child_members, strict=True): + selected = np.isin(codes[positions], members) rows.append(np.full(int(selected.sum()), index, np.int32)) cols.append(positions[selected].astype(np.int32)) data.append(values[selected]) @@ -457,6 +593,880 @@ def split_state_rows( ) +# --------------------------------------------------------------------------- +# ACS county families (microcosm#922) +# --------------------------------------------------------------------------- + +ACS_SOURCE_NAME = "census_acs" +ACS_TABLES = "ACS 2020-2024 5-year" +ACS_HOUSEHOLDS_FAMILY = "acs_households" +ACS_HOUSEHOLDS_MEASURE = "B11001_001E" +#: Spine tags of the staging household table (``household_spine``). +ACS_SPINE = "acs_2024_1yr" +DONOR_SPINE = "asec_puf" +#: ACS PUMS household record type: 1 housing unit, 2 institutional and 3 +#: noninstitutional group quarters. ACS household tables (B11001, B19001, +#: B19025, B19051, B19061) exclude group quarters, so the household measures +#: do too, as the county pilot did +#: (experiments/us-county-pilot-20261024/county_targets.py, +#: ``household_measures`` and ``GROUP_QUARTERS_TYPES``). Donor (ASEC by PUF) +#: households are all in the household universe there too. +HOUSEHOLD_KIND_COLUMN = "TYPEHUGQ" +ACS_HOUSING_UNIT_KIND = 1 +GROUP_QUARTERS_KINDS = (2, 3) +#: Earnings: wages plus all self-employment, ACS B19061's concept. These are +#: the pilot's EARNINGS_COLUMNS plus DONOR_ONLY_EARNINGS_COLUMNS, summed over +#: a household's people. The pilot zeroed the last two on ACS records because +#: staging then stacked donor draws on SEMP (microcosm#1380). Materialize now +#: refuses such staging (``acs_self_employment_identity_gate``, run by +#: ``_require_acs_self_employment_identity`` before this point), and that gate +#: lets an ACS row's SEMP sit wholly on the SSTB leaf after QBI reconciliation +#: with farm income zero, so summing all four on every record counts SEMP +#: exactly once; zeroing the SSTB leaf would drop it. +EARNINGS_COLUMNS = ( + "employment_income_before_lsr", + "self_employment_income_before_lsr", + "sstb_self_employment_income_before_lsr", + "farm_operations_income", +) +#: The pilot's other person-level income inputs, carried when staging stores +#: them, so the household-income concept of ACS B19025/B19001 can be +#: approximated. Absent ones are listed in the receipt. +OTHER_INCOME_COLUMNS = ( + "taxable_interest_income", + "tax_exempt_interest_income", + "qualified_dividend_income", + "non_qualified_dividend_income", + "rental_income", + "estate_income", + "social_security_retirement", + "social_security_disability", + "social_security_survivors", + "social_security_dependents", + "ssi_reported", + "tanf_reported", + "public_assistance_income", + "taxable_private_pension_income", + "tax_exempt_private_pension_income", + "taxable_ira_distributions", + "unemployment_compensation", + "veterans_benefits", + "workers_compensation", + "alimony_income", + "child_support_received", + "miscellaneous_income", +) +#: Partnership and S-corporation income from donor tax detail. ACS SEMP +#: already counts partnership income, so on ACS records these donor leaves +#: are zeroed in the income approximation (the pilot's rule). +DONOR_ONLY_OTHER_INCOME_COLUMNS = ("partnership_income", "s_corp_income") +#: ACS B19001 household income brackets: estimate id, its income_range +#: dimension value in the county facts, and [lower, upper) dollar bounds. +#: Income below zero falls in the first bracket, as in ACS. +B19001_BRACKETS = ( + ("B19001_002E", "under_10000", -math.inf, 10_000.0), + ("B19001_003E", "10000_to_14999", 10_000.0, 15_000.0), + ("B19001_004E", "15000_to_19999", 15_000.0, 20_000.0), + ("B19001_005E", "20000_to_24999", 20_000.0, 25_000.0), + ("B19001_006E", "25000_to_29999", 25_000.0, 30_000.0), + ("B19001_007E", "30000_to_34999", 30_000.0, 35_000.0), + ("B19001_008E", "35000_to_39999", 35_000.0, 40_000.0), + ("B19001_009E", "40000_to_44999", 40_000.0, 45_000.0), + ("B19001_010E", "45000_to_49999", 45_000.0, 50_000.0), + ("B19001_011E", "50000_to_59999", 50_000.0, 60_000.0), + ("B19001_012E", "60000_to_74999", 60_000.0, 75_000.0), + ("B19001_013E", "75000_to_99999", 75_000.0, 100_000.0), + ("B19001_014E", "100000_to_124999", 100_000.0, 125_000.0), + ("B19001_015E", "125000_to_149999", 125_000.0, 150_000.0), + ("B19001_016E", "150000_to_199999", 150_000.0, 200_000.0), + ("B19001_017E", "200000_plus", 200_000.0, math.inf), +) + + +@dataclasses.dataclass(frozen=True) +class ValidationFamily: + """A held-out ACS county family: scored for every county, never trained.""" + + name: str + measure_ids: tuple + household_measure: str + approximate: bool + unit: str + description: str + + +#: Validation families: within-state shares of each ACS county table, scored +#: after calibration against the final weights' state totals. They never +#: enter the loss, the target registry or the roles. +VALIDATION_FAMILIES = ( + ValidationFamily( + "acs_earnings", + ("B19061_001E",), + "earnings", + False, + "usd", + "aggregate household earnings: wages plus all self-employment", + ), + ValidationFamily( + "acs_earning_households", + ("B19051_002E",), + "earning_households", + False, + "count", + "households with earnings (household earnings not zero)", + ), + ValidationFamily( + "acs_household_income", + ("B19025_001E",), + "income", + True, + "usd", + "aggregate household income, approximated by earnings plus the stored " + "income inputs (approximate)", + ), + ValidationFamily( + "acs_household_income_distribution", + tuple(bracket[0] for bracket in B19001_BRACKETS), + "income_bracket", + True, + "count", + "households by household income bracket, on the approximate income " + "(approximate); scored per bracket and as the bracket L1 error over " + "the county's households", + ), +) +#: B19013 is a median: a diagnostic only, never a linear target or a share. +MEDIAN_INCOME_MEASURE = "B19013_001E" + + +def _moe_id(measure_id): + return measure_id[:-1] + "M" + + +def acs_county_values(facts, measure_ids, *, required=None): + """``{measure: {county: (estimate, moe or None, name)}}`` from ACS rows. + + Reads every record set (B01003 splits its counties across two). Trains + and scores on estimates only: a row is an estimate exactly when its + ``statistic`` is ``estimate`` and its id ends in ``E``; its margin of + error (id ending ``M``) is carried when present and never required. + Duplicate, negative or nonfinite estimates are refused. With + ``required`` (county codes), every measure must cover exactly those + counties. + """ + wanted = set(measure_ids) + moe_ids = {_moe_id(measure): measure for measure in wanted} + estimates = {measure: {} for measure in wanted} + margins = {measure: {} for measure in wanted} + for fact in facts: + observed = fact.get("observed_measure", {}) + if observed.get("source_name") != ACS_SOURCE_NAME: + continue + measure = observed.get("source_measure_id") + if measure not in wanted and measure not in moe_ids: + continue + statistic = (fact.get("dimensions") or {}).get("statistic") + is_estimate = measure in wanted + if statistic != ("estimate" if is_estimate else "margin_of_error"): + raise ValueError( + f"ACS county fact {measure} carries statistic {statistic!r}; " + "an id ending E is an estimate and one ending M its margin of error." + ) + code = county_code_of(fact, source="ACS") + value = float(fact["value"]) + target = estimates[measure] if is_estimate else margins[moe_ids[measure]] + if code in target: + raise ValueError(f"Duplicate ACS county fact {measure} for {code:05d}.") + if not math.isfinite(value) or value < 0: + raise ValueError( + f"ACS county fact {measure} for {code:05d} must be finite and " + f"nonnegative, got {value!r}." + ) + target[code] = (value, str((fact.get("geography") or {}).get("name", ""))) + result = {} + for measure in sorted(wanted): + values = estimates[measure] + if required is not None: + expected = {int(code) for code in required} + missing = sorted(expected - values.keys()) + extra = sorted(values.keys() - expected) + if missing or extra: + raise ValueError( + f"Incomplete ACS county inventory for {measure}: " + f"missing={[f'{code:05d}' for code in missing][:20]} " + f"({len(missing)}), unexpected=" + f"{[f'{code:05d}' for code in extra][:20]} ({len(extra)}). " + "County facts, ladder and county column must use matching " + "boundaries." + ) + result[measure] = { + code: ( + value, + margins[measure][code][0] if code in margins[measure] else None, + name, + ) + for code, (value, name) in sorted(values.items()) + } + return result + + +def _state_label(state): + from microcosm.calibrate.geography_constants import US_STATE_FIPS_TO_NAME + + label = US_STATE_FIPS_TO_NAME.get(f"{int(state):02d}") + if label is None: + raise ValueError(f"State {int(state):02d} has no Census state name.") + return label + + +def _acs_hierarchy(name, *, state=None, county=None): + from microcosm.calibrate import ( + CalibrationHierarchy, + HierarchyCategory, + HierarchyGeography, + HierarchyNode, + ) + from microcosm.calibrate.provider_labels import calibration_provider_label + + provider = HierarchyNode( + ACS_SOURCE_NAME, calibration_provider_label("us", ACS_SOURCE_NAME) + ) + if county is not None: + # The same label every county family gives this county (_hierarchy). + geography = HierarchyGeography( + f"{COUNTY_PREFIX}{county}", f"County {county}", "county" + ) + label = f"County {county} households (ACS)" + else: + state_label = _state_label(state) + geography = HierarchyGeography( + f"0400000US{int(state):02d}", state_label, "state" + ) + label = f"{state_label} households (ACS)" + return CalibrationHierarchy( + provider=provider, + category=HierarchyCategory("census_acs.households", "Households", provider.id), + geography=geography, + dimensions=(), + target=HierarchyNode(name, label), + ) + + +def acs_households_parent_name(state): + return f"acs_households_state_{int(state):02d}" + + +def acs_household_surface(facts, county_populations, *, period=2024): + """State households parents and their county children (trained, levels). + + Each state parent is the sum of its counties' ACS B11001_001E values, a + new state target that moves state household counts to ACS 5-year levels; + its county children split it by county share, so they sum to it. The + measure counts households outside ACS group quarters + (:func:`household_universe`). ACS margins of error ride in metadata. + """ + from microcosm.calibrate import TargetSpec + + values = acs_county_values( + facts, [ACS_HOUSEHOLDS_MEASURE], required=county_populations + )[ACS_HOUSEHOLDS_MEASURE] + source = ( + f"US Census Bureau {ACS_TABLES} B11001_001E (households), county; " + "state = sum of its counties" + ) + specs, receipts = [], [] + for state in sorted({int(code) // 1000 for code in county_populations}): + codes = sorted(code for code in values if code // 1000 == state) + public = [values[code][0] for code in codes] + total = math.fsum(public) + if not codes or total <= 0: + raise ValueError( + f"ACS county households for state {state:02d} have no positive " + "share denominator." + ) + parent_name = acs_households_parent_name(state) + state_population = math.fsum(county_populations[code] for code in codes) + specs.append( + TargetSpec( + name=parent_name, + entity="household", + measure=parent_name, + value=total, + period=period, + source=source, + family=ACS_HOUSEHOLDS_FAMILY, + metadata={ + "geography_level": "state", + "state_fips": f"{state:02d}", + "source_measure_id": ACS_HOUSEHOLDS_MEASURE, + "acs_state_parent_basis": "sum of county estimates", + "household_universe": "excludes ACS group quarters (TYPEHUGQ 2, 3)", + "new_state_target": "true", + }, + hierarchy=_acs_hierarchy(parent_name, state=state), + ) + ) + shares = [value / total for value in public] + largest = max(range(len(codes)), key=lambda index: shares[index]) + shares[largest] += 1.0 - math.fsum(shares) + targets = [total * share for share in shares] + targets[largest] += total - math.fsum(targets) + for code, share, target in zip(codes, shares, targets, strict=True): + county = f"{code:05d}" + name = f"county_{county}__{parent_name}" + estimate, moe, label = values[code] + metadata = { + "geography_level": "county", + "county_fips": county, + "state_fips": f"{state:02d}", + "source_measure_id": ACS_HOUSEHOLDS_MEASURE, + "state_county_parent_target_name": parent_name, + "state_county_share": str(share), + "state_county_source_value": str(estimate), + "county_population": str(county_populations[code]), + "state_population": str(state_population), + "household_universe": "excludes ACS group quarters (TYPEHUGQ 2, 3)", + } + if label: + metadata["county_label"] = label + if moe is not None: + metadata["acs_margin_of_error"] = str(moe) + specs.append( + TargetSpec( + name=name, + entity="household", + measure=name, + value=target, + period=period, + source=f"US Census Bureau {ACS_TABLES} B11001_001E " + "(households), county share of the state sum", + family=ACS_HOUSEHOLDS_FAMILY, + metadata=metadata, + hierarchy=_acs_hierarchy(name, county=county), + ) + ) + receipts.append( + { + "state_fips": f"{state:02d}", + "state_target": parent_name, + "state_households": total, + "counties": len(codes), + "share_sum": math.fsum(shares), + "target_sum": math.fsum(targets), + "counties_with_moe": sum(values[code][1] is not None for code in codes), + } + ) + return CountySurface( + tuple(specs), + { + "family": ACS_HOUSEHOLDS_FAMILY, + "source_measure_id": ACS_HOUSEHOLDS_MEASURE, + "source": f"{ACS_TABLES} county B11001", + "new_state_targets": len(receipts), + "county_targets": len(specs) - len(receipts), + "note": ( + "New state targets: each state's households target is the sum " + "of its counties' ACS 5-year B11001_001E estimates, which moves " + "state household counts to ACS 5-year levels (the county pilot " + "found the release about 6% under ACS households). County rows " + "split those state targets; group-quarters records count as " + "no household." + ), + "blocks": receipts, + "new_engine_columns": 0, + }, + ) + + +def _spines(households): + if "household_spine" not in households.columns: + raise ValueError( + "ACS county household measures need household_spine to find ACS rows." + ) + spine = households["household_spine"].astype(str).to_numpy() + unknown = sorted(set(spine) - {ACS_SPINE, DONOR_SPINE}) + if unknown: + raise ValueError(f"Unexpected household spines {unknown[:5]}.") + return spine + + +def household_universe(households): + """1.0 for households in ACS's household universe, 0.0 for group quarters. + + An ACS household must carry ``TYPEHUGQ`` 1, 2 or 3 (missing or other + codes are refused); a donor household carries none and is a household. + """ + spine = _spines(households) + acs = spine == ACS_SPINE + if HOUSEHOLD_KIND_COLUMN in households.columns: + kind = pd.to_numeric( + households[HOUSEHOLD_KIND_COLUMN], errors="coerce" + ).to_numpy(float) + elif acs.any(): + raise ValueError( + f"ACS households lack {HOUSEHOLD_KIND_COLUMN}; the household measures " + "cannot exclude group quarters." + ) + else: + kind = np.full(len(households), np.nan) + allowed = (ACS_HOUSING_UNIT_KIND, *GROUP_QUARTERS_KINDS) + bad = acs & ~np.isin(kind, allowed) + if bad.any(): + raise ValueError( + f"{int(bad.sum())} ACS household(s) carry {HOUSEHOLD_KIND_COLUMN} " + f"outside {list(allowed)} (missing counts as outside)." + ) + off_arm = ~acs & ~np.isnan(kind) + if off_arm.any(): + raise ValueError( + f"{int(off_arm.sum())} donor household(s) carry an ACS " + f"{HOUSEHOLD_KIND_COLUMN}; it does not describe them." + ) + return (~(acs & np.isin(kind, GROUP_QUARTERS_KINDS))).astype(np.float64) + + +def acs_household_rows(households, specs, *, county_column=COUNTY_COLUMN): + """Rows of the ACS households family: state or county x household universe.""" + codes = county_codes(households, county_column=county_column) + universe = household_universe(households).astype(np.float32) + rows, cols, data = [], [], [] + for index, spec in enumerate(specs): + state = int(spec.metadata["state_fips"]) + if spec.metadata["geography_level"] == "state": + selected = codes // 1000 == state + else: + selected = codes == int(spec.metadata["county_fips"]) + positions = np.flatnonzero(selected & (universe > 0)) + rows.append(np.full(len(positions), index, np.int32)) + cols.append(positions.astype(np.int32)) + data.append(universe[positions]) + return sparse.csr_array( + ( + _concatenate(data, np.float32), + (_concatenate(rows, np.int32), _concatenate(cols, np.int32)), + ), + shape=(len(specs), len(households)), + ) + + +def _bracket_bounds(label): + if label.startswith("under_"): + return -math.inf, float(label.removeprefix("under_")) + if label.endswith("_plus"): + return float(label.removesuffix("_plus")), math.inf + lower, _separator, upper = label.partition("_to_") + return float(lower), float(upper) + 1.0 + + +def county_validation_design(facts, county_populations): + """The public side of every validation family, refused if incomplete. + + Estimates must cover every ladder county, each state's county sum must + be positive (a zero share denominator is refused), and the B19001 + brackets must be the income ranges the facts label. B19013 medians are a + diagnostic, so a county without one (De Baca, 35011) is listed, not + refused. + """ + counties = sorted(int(code) for code in county_populations) + measure_ids = [ + measure for family in VALIDATION_FAMILIES for measure in family.measure_ids + ] + values = acs_county_values(facts, measure_ids, required=counties) + labels = {} + for fact in facts: + observed = fact.get("observed_measure", {}) + if observed.get("source_name") == ACS_SOURCE_NAME and str( + observed.get("source_measure_id", "") + ).startswith("B19001_0"): + labels.setdefault( + observed["source_measure_id"], + (fact.get("dimensions") or {}).get("income_range"), + ) + for measure, label, lower, upper in B19001_BRACKETS: + if labels.get(measure) != label or _bracket_bounds(label) != (lower, upper): + raise ValueError( + f"ACS {measure} is labelled {labels.get(measure)!r}; the bracket " + f"table expects {label!r} = [{lower}, {upper})." + ) + states = sorted({code // 1000 for code in counties}) + for measure, public in values.items(): + for state in states: + total = math.fsum( + value + for code, (value, _m, _n) in public.items() + if code // 1000 == state + ) + if total <= 0: + raise ValueError( + f"ACS {measure} has no positive share denominator in state " + f"{state:02d}." + ) + median = acs_county_values(facts, [MEDIAN_INCOME_MEASURE])[MEDIAN_INCOME_MEASURE] + names = {} + for measure in measure_ids: + for code, (_value, _moe, name) in values[measure].items(): + if name: + names.setdefault(code, name) + return { + "schema_version": 1, + "source": f"US Census Bureau {ACS_TABLES} county tables", + "counties": [f"{code:05d}" for code in counties], + "county_populations": { + f"{code:05d}": float(county_populations[code]) for code in counties + }, + "county_names": {f"{code:05d}": names.get(code, "") for code in counties}, + "families": { + family.name: { + "approximate": family.approximate, + "unit": family.unit, + "description": family.description, + "household_measure": family.household_measure, + "source_measure_ids": list(family.measure_ids), + "public": { + measure: { + f"{code:05d}": [value, moe] + for code, (value, moe, _name) in values[measure].items() + } + for measure in family.measure_ids + }, + } + for family in VALIDATION_FAMILIES + }, + "brackets": [ + {"measure": measure, "income_range": label, "lower": lower, "upper": upper} + for measure, label, lower, upper in B19001_BRACKETS + ], + "median_income_diagnostic": { + "source_measure_id": MEDIAN_INCOME_MEASURE, + "role": "diagnostic only; never a linear target or a share", + "public": { + f"{code:05d}": [value, moe] + for code, (value, moe, _name) in median.items() + if code in set(counties) + }, + "missing": [f"{code:05d}" for code in counties if code not in median], + }, + "score": ( + "target(c) = M_s x public(c) / sum of public over the state's " + "counties, M_s the state total under the final weights; pro-rata " + "baseline M_s x ladder county population / state population" + ), + } + + +def household_validation_measures(frame): + """Household-aligned measures the validation families are scored on. + + Returns ``(arrays, report)``: ``household_id``, ``in_household_universe``, + ``earnings`` (:data:`EARNINGS_COLUMNS` summed over the household's + people) and ``household_income_approx`` (earnings plus the carried + :data:`OTHER_INCOME_COLUMNS`, plus :data:`DONOR_ONLY_OTHER_INCOME_COLUMNS` + on donor records). Missing person values count as zero, as in the pilot. + """ + households = frame.table("household") + person = frame.table("person") + index = pd.Index(households["household_id"].to_numpy()) + position = index.get_indexer(person["person_household_id"].to_numpy()) + if (position < 0).any(): + raise ValueError("Persons reference households missing from the table.") + missing = [column for column in EARNINGS_COLUMNS if column not in person.columns] + if missing: + raise ValueError( + f"County validation needs person earnings inputs {missing}; refusing " + "to treat them as zero." + ) + n = len(households) + spine = _spines(households) + donor_person = spine[position] == DONOR_SPINE + universe = household_universe(households) + weights = np.asarray(frame.weights_for("household").values, dtype=np.float64) + + def summed(column, *, donor_only=False): + values = pd.to_numeric(person[column], errors="coerce").to_numpy( + np.float64, na_value=np.nan + ) + if np.isinf(values).any(): + raise ValueError(f"Person {column} carries an infinite value.") + values = np.nan_to_num(values, nan=0.0) + if donor_only: + values = np.where(donor_person, values, 0.0) + return np.bincount(position, weights=values, minlength=n) + + earnings = np.zeros(n) + components = {} + for column in EARNINGS_COLUMNS: + part = summed(column) + earnings += part + components[column] = float((weights * part).sum()) + income = earnings.copy() + carried = [column for column in OTHER_INCOME_COLUMNS if column in person.columns] + donor_carried = [ + column for column in DONOR_ONLY_OTHER_INCOME_COLUMNS if column in person.columns + ] + for column in carried: + part = summed(column) + income += part + components[column] = float((weights * part).sum()) + for column in donor_carried: + part = summed(column, donor_only=True) + income += part + components[column] = float((weights * part).sum()) + group_quarters = universe == 0 + report = { + "earnings_columns": list(EARNINGS_COLUMNS), + "earnings_rule": "all four leaves on every record; the ACS " + "self-employment identity gate guarantees SEMP once (microcosm#1380)", + "other_income_columns_carried": carried, + "donor_only_income_columns_carried": donor_carried, + "income_columns_absent": [ + column + for column in (*OTHER_INCOME_COLUMNS, *DONOR_ONLY_OTHER_INCOME_COLUMNS) + if column not in person.columns + ], + "design_weighted_component_totals": components, + "group_quarters_households": int(group_quarters.sum()), + "group_quarters_design_weight": float(weights[group_quarters].sum()), + "households": int(n), + } + arrays = { + "household_id": households["household_id"].to_numpy(), + "in_household_universe": universe, + "earnings": earnings, + "household_income_approx": income, + } + return arrays, report + + +def _family_vectors(family, measures): + universe = np.asarray(measures["in_household_universe"], dtype=np.float64) + earnings = np.asarray(measures["earnings"], dtype=np.float64) + income = np.asarray(measures["household_income_approx"], dtype=np.float64) + if family.household_measure == "earnings": + return {family.measure_ids[0]: earnings * universe} + if family.household_measure == "earning_households": + return {family.measure_ids[0]: (earnings != 0) * universe} + if family.household_measure == "income": + return {family.measure_ids[0]: income * universe} + return { + measure: ((income >= lower) & (income < upper)) * universe + for measure, _label, lower, upper in B19001_BRACKETS + } + + +def _abs_rel(estimate, target): + return np.abs(estimate - target) / np.maximum(np.abs(target), 1.0) + + +def _weighted_medians(group, values, weights, n_groups): + order = np.lexsort((values, group)) + group, values, weights = group[order], values[order], weights[order] + result = np.full(n_groups, np.nan) + starts = np.searchsorted(group, np.arange(n_groups), side="left") + ends = np.searchsorted(group, np.arange(n_groups), side="right") + for index in range(n_groups): + start, end = starts[index], ends[index] + cumulative = np.cumsum(weights[start:end]) + if end == start or cumulative[-1] <= 0: + continue + result[index] = values[ + start + int(np.searchsorted(cumulative, cumulative[-1] / 2)) + ] + return result + + +def score_county_validation( + design, + measures, + households, + *, + final_weights, + design_weights, + cap, + county_column=COUNTY_COLUMN, +): + """Score every validation family for every county, report only. + + For each ACS measure, ``target(c) = M_s * public(c) / sum_s public`` with + ``M_s`` the state total of the household measure under the final + weights, so a uniform concept gap between the measure and the ACS table + cancels; the pro-rata baseline is ``M_s * pop(c) / pop(s)`` from the + ladder. Nothing here can reach the loss: it reads final weights only. + """ + counties = [int(code) for code in design["counties"]] + position = {code: index for index, code in enumerate(counties)} + codes = county_codes(households, county_column=county_column) + ids = households["household_id"].to_numpy() + if not np.array_equal(np.asarray(measures["household_id"]), ids): + raise ValueError( + "County validation measures are not aligned with the checkpoint households." + ) + unknown = sorted(set(codes) - set(position)) + if unknown: + raise ValueError(f"Households name counties outside the design: {unknown[:5]}.") + county_index = np.asarray([position[int(code)] for code in codes], dtype=np.int64) + n = len(counties) + states = np.asarray([code // 1000 for code in counties]) + state_codes = np.unique(states) + state_of = np.searchsorted(state_codes, states) + population = np.asarray( + [design["county_populations"][f"{code:05d}"] for code in counties], float + ) + state_population = np.bincount(state_of, weights=population)[state_of] + weight_sets = { + "calibrated": np.asarray(final_weights, dtype=np.float64), + "design": np.asarray(design_weights, dtype=np.float64), + } + per_county = {f"{code:05d}": {} for code in counties} + families = {} + for family in VALIDATION_FAMILIES: + published = design["families"][family.name]["public"] + vectors = _family_vectors(family, measures) + family_rows = {} + for measure, vector in vectors.items(): + public = np.asarray( + [published[measure][f"{code:05d}"][0] for code in counties], float + ) + share = public / np.bincount(state_of, weights=public)[state_of] + row = {"public": public} + for label, weights in weight_sets.items(): + estimate = np.bincount( + county_index, weights=weights * vector, minlength=n + ) + state_total = np.bincount(state_of, weights=estimate)[state_of] + row[label] = estimate + row[f"{label}_target"] = state_total * share + if label == "calibrated": + row["pro_rata"] = state_total * population / state_population + family_rows[measure] = row + summary = { + "approximate": family.approximate, + "unit": family.unit, + "description": family.description, + "source_measure_ids": list(family.measure_ids), + } + if family.household_measure == "income_bracket": + l1 = {} + for label, target_key in ( + ("calibrated", "calibrated_target"), + ("design", "design_target"), + ("pro_rata", "calibrated_target"), + ): + difference = sum( + np.abs(row[label] - row[target_key]) for row in family_rows.values() + ) + total = sum(row[target_key] for row in family_rows.values()) + l1[label] = difference / np.maximum(total, 1.0) + for label, key in ( + ("calibrated", "calibrated"), + ("design", "design_weights"), + ("pro_rata", "pro_rata_baseline"), + ): + values = l1[label] + summary[key] = { + "mean_bracket_l1_error": float(values.mean()), + "median_bracket_l1_error": float(np.median(values)), + "p90_bracket_l1_error": float(np.quantile(values, 0.9)), + "max_bracket_l1_error": float(values.max()), + } + summary["calibrated_beats_pro_rata_share"] = float( + (l1["calibrated"] < l1["pro_rata"]).mean() + ) + summary["error"] = ( + "sum over brackets |estimate - target| / max(sum of targets, 1)" + ) + for index, code in enumerate(counties): + key = f"{code:05d}" + per_county[key][family.name] = { + "approximate": True, + "abs_rel_error": float(l1["calibrated"][index]), + "pro_rata_abs_rel_error": float(l1["pro_rata"][index]), + "design_abs_rel_error": float(l1["design"][index]), + "brackets": { + measure: { + "public_value": float(row["public"][index]), + "public_moe": published[measure][key][1], + "target": float(row["calibrated_target"][index]), + "estimate": float(row["calibrated"][index]), + } + for measure, row in family_rows.items() + }, + } + else: + measure = family.measure_ids[0] + row = family_rows[measure] + errors = _abs_rel(row["calibrated"], row["calibrated_target"]) + design_errors = _abs_rel(row["design"], row["design_target"]) + baseline = _abs_rel(row["pro_rata"], row["calibrated_target"]) + summary["calibrated"] = cd_surface._error_summary( + row["calibrated"], row["calibrated_target"], cap=cap + ) + summary["design_weights"] = cd_surface._error_summary( + row["design"], row["design_target"], cap=cap + ) + summary["pro_rata_baseline"] = cd_surface._error_summary( + row["pro_rata"], row["calibrated_target"], cap=cap + ) + summary["calibrated_beats_pro_rata_share"] = float( + (errors < baseline).mean() + ) + for index, code in enumerate(counties): + key = f"{code:05d}" + per_county[key][family.name] = { + "approximate": family.approximate, + "public_value": float(row["public"][index]), + "public_moe": published[measure][key][1], + "target": float(row["calibrated_target"][index]), + "estimate": float(row["calibrated"][index]), + "abs_rel_error": float(errors[index]), + "pro_rata": float(row["pro_rata"][index]), + "pro_rata_abs_rel_error": float(baseline[index]), + "design_abs_rel_error": float(design_errors[index]), + } + families[family.name] = summary + universe = np.asarray(measures["in_household_universe"], dtype=np.float64) > 0 + medians = _weighted_medians( + county_index[universe], + np.asarray(measures["household_income_approx"], dtype=np.float64)[universe], + weight_sets["calibrated"][universe], + n, + ) + median_public = design["median_income_diagnostic"]["public"] + for index, code in enumerate(counties): + key = f"{code:05d}" + public = median_public.get(key) + estimate = None if math.isnan(medians[index]) else float(medians[index]) + per_county[key]["median_household_income"] = { + "diagnostic_only": True, + "approximate": True, + "public_value": None if public is None else public[0], + "public_moe": None if public is None else public[1], + "estimate": estimate, + "ratio": ( + estimate / public[0] + if public is not None and estimate is not None and public[0] > 0 + else None + ), + "status": "scored" if public is not None else "no_public_value", + } + return { + "report_only": True, + "never_in_loss": True, + "families": families, + "median_income_diagnostic": { + "source_measure_id": MEDIAN_INCOME_MEASURE, + "role": "diagnostic only; never a linear target or a share", + "missing_public": design["median_income_diagnostic"]["missing"], + }, + "score": design["score"], + "counties": per_county, + } + + +#: The validation errors a county's grade reads: one per family (the income +#: distribution as its bracket L1 error). Medians never enter a grade. +GRADED_VALIDATION_FAMILIES = tuple(family.name for family in VALIDATION_FAMILIES) + + def target_record(spec): record = cd_surface.target_record(spec) record["geography_level"] = record["geography_level"] or spec.metadata.get( @@ -468,6 +1478,7 @@ def target_record(spec): "state_county_share", "county_population", "state_population", + "state_county_cell_members", ): if key in spec.metadata: value = spec.metadata[key] @@ -593,8 +1604,9 @@ def score_county_holdout( def reliability_grade(ess, error): """Provisional A/B/C: source ESS >=400/100/30, error <=10/20/50%; else D. - U means no holdout or source-identity evidence. ESS is a precision - diagnostic, not a standard error or a guarantee of unbiased county estimates. + U means no holdout, validation or source-identity evidence. ESS is a + precision diagnostic, not a standard error or a guarantee of unbiased + county estimates. """ if ess is None or error is None or not math.isfinite(error): return "U" @@ -604,6 +1616,25 @@ def reliability_grade(ess, error): return "D" +def record_counties(record): + """The counties a county record's error counts toward (combined cells: all).""" + members = record.get("state_county_cell_members") + if members: + return [int(member) for member in str(members).split(",")] + return [int(record["county_fips"])] + + +def _county_groups(codes): + order = np.argsort(codes, kind="stable") + sorted_codes = codes[order] + unique, starts = np.unique(sorted_codes, return_index=True) + ends = np.append(starts[1:], len(sorted_codes)) + return { + int(code): order[start:end] + for code, start, end in zip(unique, starts, ends, strict=True) + } + + def reliability_report( households, records, @@ -612,7 +1643,19 @@ def reliability_report( final_weights, county_populations=None, county_column=COUNTY_COLUMN, + validation=None, + minimum_support_counties=(), + county_names=None, ): + """One reliability cell per county: support, ESS, errors and a grade. + + ``validation`` (from :func:`score_county_validation`) supplies each + county's held-out ACS family errors, which count as holdout evidence, so + a supported county with source identity always gets A/B/C/D. A county is + U only without any held-out evidence (no household support) or without + source identity. ``minimum_support_counties`` mark counties whose only + households came from the minimum-support step. + """ codes = county_codes(households, county_column=county_column) weights = np.asarray(final_weights, float) if ( @@ -627,30 +1670,45 @@ def reliability_report( by_county = defaultdict(list) for index, record in enumerate(records): if record.get("geography_level") == "county": - by_county[int(record["county_fips"])].append(index) - counties = sorted(set(codes) | set(by_county) | set(county_populations or {})) + for code in record_counties(record): + by_county[code].append(index) + validated = (validation or {}).get("counties", {}) + counties = sorted( + set(int(code) for code in codes) + | set(by_county) + | {int(code) for code in (county_populations or {})} + | {int(code) for code in validated} + ) + groups = _county_groups(codes) + minimum = {int(code) for code in minimum_support_counties} + names = county_names or {} result = {} provenance = {"household_spine", "household_source_id"}.issubset(households.columns) for code in counties: - mask = codes == code + rows = groups.get(code, np.empty(0, dtype=np.int64)) source = ( - households.loc[mask, ["household_spine", "household_source_id"]] + households.iloc[rows][["household_spine", "household_source_id"]] if provenance else None ) if source is not None and not source.isna().any().any(): source_weights = cd_surface.distinct_household_weights( - weights[mask], + weights[rows], source["household_spine"].to_numpy(), source["household_source_id"].to_numpy(), ) - elif not mask.any(): + elif not len(rows): source_weights = np.empty(0) else: source_weights = None + key = f"{int(code):05d}" + status = "no_support" + if len(rows): + status = "minimum_support" if code in minimum else "supported" cell = { "state_fips": f"{int(code) // 1000:02d}", - "supporting_households": int(mask.sum()), + "county_name": names.get(key) or None, + "supporting_households": len(rows), "distinct_source_households": ( len(source_weights) if source_weights is not None else None ), @@ -659,9 +1717,10 @@ def reliability_report( if source_weights is not None else None ), - "kish_ess_rows": cd_surface.kish_ess(weights[mask]), - "status": "supported" if mask.any() else "no_support", + "kish_ess_rows": cd_surface.kish_ess(weights[rows]), + "status": status, } + candidates = [] for role, label in ( (cd_surface.ROLE_TRAIN, "training"), (cd_surface.ROLE_HOLDOUT, "holdout"), @@ -679,34 +1738,484 @@ def reliability_report( "mean_abs_rel_error": float(np.mean(errors)) if errors else None, "max_abs_rel_error": float(max(errors)) if errors else None, } - errors = [ - cell[key]["max_abs_rel_error"] - for key in ("training", "holdout") - if cell[key]["max_abs_rel_error"] is not None + candidates += [ + (float(error), f"{label}:{records[index]['name']}") + for error, index in zip(errors, indices, strict=True) + ] + families = validated.get(key) or {} + # A county without household support has no held-out estimate to + # judge: its validation estimates are zero by construction. + graded = ( + { + name: families[name] + for name in GRADED_VALIDATION_FAMILIES + if name in families + } + if len(rows) + else {} + ) + cell["validation"] = { + "n_families": len(graded), + "families": families, + } + candidates += [ + (float(entry["abs_rel_error"]), f"validation:{name}") + for name, entry in graded.items() ] - error = max(errors) if errors and cell["holdout"]["n_targets"] else None + evidence = cell["holdout"]["n_targets"] > 0 or bool(graded) + if evidence and candidates: + error, driver = max(candidates, key=lambda item: (item[0], item[1])) + else: + error, driver = None, None + cell["grade_error"] = error + cell["grade_driver"] = driver cell["grade"] = reliability_grade(cell["kish_ess"], error) - result[f"{int(code):05d}"] = cell + result[key] = cell return { - "schema_version": 2, + "schema_version": 3, "county_column": county_column, "ess_basis": { "kish_ess": "final weights summed within county by (household_spine, household_source_id)", "kish_ess_rows": "final weights over physical household rows, including clones", }, "counties": result, + "validation_families": { + name: { + key: value + for key, value in summary.items() + if key in {"approximate", "unit", "description", "source_measure_ids"} + } + for name, summary in (validation or {}).get("families", {}).items() + }, "grade_rule": { "provisional": True, "A": "source ESS >=400 and max error <=0.10", "B": "source ESS >=100 and max error <=0.20", "C": "source ESS >=30 and max error <=0.50", - "D": "otherwise with holdout evidence", - "U": "no county holdout evidence or source household identity unavailable", - "error": "maximum training/holdout absolute relative error; denominator max(abs(target),1)", + "D": "otherwise with holdout or validation evidence", + "U": "no county holdout or validation evidence (no household " + "support) or source household identity unavailable", + "error": "maximum absolute relative error over the county's training " + "and holdout targets and its validation families (the income " + "distribution as its bracket L1 error); denominator max(abs(target),1)", + "validation_families": list(GRADED_VALIDATION_FAMILIES), }, } +#: Columns of the flat per-county reliability CSV, in order. +def reliability_csv_columns(): + columns = [ + "county_fips", + "state_fips", + "county_name", + "status", + "grade", + "grade_provisional", + "grade_error", + "grade_driver", + "supporting_households", + "distinct_source_households", + "kish_ess", + "kish_ess_rows", + "training_targets", + "training_max_abs_rel_error", + "training_mean_abs_rel_error", + "holdout_targets", + "holdout_max_abs_rel_error", + ] + for name in GRADED_VALIDATION_FAMILIES: + columns += [f"{name}_abs_rel_error", f"{name}_pro_rata_abs_rel_error"] + columns += [ + "median_household_income_public", + "median_household_income_estimate", + ] + return columns + + +def reliability_csv(report): + """The flat CSV of a reliability report: one row per county, sorted by FIPS.""" + import csv + import io + + provisional = bool(report.get("grade_rule", {}).get("provisional", True)) + stream = io.StringIO() + writer = csv.DictWriter( + stream, fieldnames=reliability_csv_columns(), lineterminator="\n" + ) + writer.writeheader() + + def cell_value(value): + if value is None: + return "" + if isinstance(value, float): + return repr(value) + return value + + for code, cell in sorted(report["counties"].items()): + families = (cell.get("validation") or {}).get("families", {}) + median = families.get("median_household_income") or {} + row = { + "county_fips": code, + "state_fips": cell.get("state_fips"), + "county_name": cell.get("county_name"), + "status": cell.get("status"), + "grade": cell.get("grade"), + "grade_provisional": "true" if provisional else "false", + "grade_error": cell.get("grade_error"), + "grade_driver": cell.get("grade_driver"), + "supporting_households": cell.get("supporting_households"), + "distinct_source_households": cell.get("distinct_source_households"), + "kish_ess": cell.get("kish_ess"), + "kish_ess_rows": cell.get("kish_ess_rows"), + "training_targets": (cell.get("training") or {}).get("n_targets"), + "training_max_abs_rel_error": (cell.get("training") or {}).get( + "max_abs_rel_error" + ), + "training_mean_abs_rel_error": (cell.get("training") or {}).get( + "mean_abs_rel_error" + ), + "holdout_targets": (cell.get("holdout") or {}).get("n_targets"), + "holdout_max_abs_rel_error": (cell.get("holdout") or {}).get( + "max_abs_rel_error" + ), + "median_household_income_public": median.get("public_value"), + "median_household_income_estimate": median.get("estimate"), + } + for name in GRADED_VALIDATION_FAMILIES: + entry = families.get(name) or {} + row[f"{name}_abs_rel_error"] = entry.get("abs_rel_error") + row[f"{name}_pro_rata_abs_rel_error"] = entry.get("pro_rata_abs_rel_error") + writer.writerow({key: cell_value(value) for key, value in row.items()}) + return stream.getvalue() + + +# --------------------------------------------------------------------------- +# Minimum support for counties without households (microcosm#922) +# --------------------------------------------------------------------------- + +DEFAULT_COUNTY_MIN_SUPPORT = 3 +MAX_COUNTY_MIN_SUPPORT = 50 +COUNTY_MIN_SUPPORT_KEY = "acs-local-county-support-v1" +#: The household county columns a move rewrites (each only if present, plus +#: the configured county column); nothing else changes. +COUNTY_FIPS_COLUMNS = ("county_fips", "county_fips_2023") +#: Location columns that fix a household's county. A household carrying one +#: is never moved: finalize's ladder and block gates check the stored county +#: against it, and a move rewrites county columns only. +COUNTY_DETERMINING_LOCATION_COLUMNS = ("tract_geoid", "block_geoid") + + +def county_puma_overlaps(ladder_path): + """``{county: [(puma, population), ...]}``, largest overlap first.""" + from microcosm.build.us_runtime.puma_ladder import load_us_puma_ladder + + ladder = load_us_puma_ladder(ladder_path) + return puma_overlaps( + ladder.county_overlap_puma, + ladder.county_overlap_county, + ladder.county_overlap_population, + ) + + +def puma_overlaps(pumas, counties, populations): + cells = defaultdict(lambda: defaultdict(float)) + for puma, county, population in zip( + np.asarray(pumas), np.asarray(counties), np.asarray(populations), strict=True + ): + cells[int(county)][int(puma)] += float(population) + return { + county: sorted( + ( + (puma, population) + for puma, population in by_puma.items() + if population > 0 + ), + key=lambda item: (-item[1], item[0]), + ) + for county, by_puma in cells.items() + } + + +def support_rank(key, county, household_id): + """The keyed hash that orders a destination county's candidate donors.""" + return hashlib.sha256( + f"{key}\x1f{int(county):05d}\x1f{household_id}".encode() + ).hexdigest() + + +def _household_pumas(households): + if "puma" not in households.columns: + raise ValueError("Minimum county support needs the household puma column.") + return _codes(households["puma"], column="puma") + + +def _blank(values): + series = pd.Series(values) + return ( + series.isna() | series.astype(str).str.strip().isin(["", "nan", "None"]) + ).to_numpy() + + +def _moves_digest(moves): + return hashlib.sha256( + json.dumps(moves, sort_keys=True, separators=(",", ":")).encode() + ).hexdigest() + + +def plan_minimum_support( + households, + county_populations, + overlaps, + *, + county_column=COUNTY_COLUMN, + per_county=DEFAULT_COUNTY_MIN_SUPPORT, + key=COUNTY_MIN_SUPPORT_KEY, +): + """Choose ``per_county`` donor households for each unsupported county. + + A county is unsupported when its ladder population is positive and no + household names it. Its donors come from the PUMA that overlaps it most + (then the next, by ladder population), ordered by + :func:`support_rank` of ``(key, county, household_id)``. A donor must be + in the household universe (not ACS group quarters), carry no tract or + block geoid, have agreeing county columns, and leave its own county with + at least ``per_county`` households. Exactly ``per_county`` households + move or none do (the county is then still unsupported and named). + Counties with support are never chosen; state and PUMA never change. + Returns ``(moves, receipt)``. + """ + if per_county < 0: + raise ValueError("Minimum county support must be nonnegative.") + codes = county_codes(households, county_column=county_column) + ids = households["household_id"].to_numpy() + if len(pd.unique(ids)) != len(ids): + raise ValueError("Minimum county support needs unique household ids.") + present = {int(code) for code in np.unique(codes)} + unsupported = sorted( + int(code) + for code, population in county_populations.items() + if float(population) > 0 and int(code) not in present + ) + receipt = { + "households_per_county": int(per_county), + "key": key, + "rank": "sha256(key + 0x1f + five-digit county + 0x1f + household_id)", + "unsupported_before": [f"{code:05d}" for code in unsupported], + "rewritten_columns": [], + "eligibility": ( + "same PUMA as the county (largest ladder overlap first); not ACS " + "group quarters; no tract_geoid or block_geoid; county columns " + "agree; the donor county keeps at least households_per_county " + "households" + ), + "counties": {}, + "moves": [], + } + if per_county == 0 or not unsupported: + receipt["moves_sha256"] = _moves_digest([]) + return [], receipt + pumas = _household_pumas(households) + if np.any(pumas // 100_000 != codes // 1000): + raise ValueError("Household PUMA and county disagree on the state.") + eligible = np.ones(len(households), dtype=bool) + if "household_spine" in households.columns and ( + HOUSEHOLD_KIND_COLUMN in households.columns + or not (households["household_spine"].astype(str) == ACS_SPINE).any() + ): + eligible &= household_universe(households) > 0 + for column in COUNTY_DETERMINING_LOCATION_COLUMNS: + if column in households.columns: + eligible &= _blank(households[column]) + rewritten = [county_column] + [ + column + for column in COUNTY_FIPS_COLUMNS + if column in households.columns and column != county_column + ] + for column in rewritten[1:]: + eligible &= _codes(households[column], column=column) == codes + receipt["rewritten_columns"] = rewritten + receipt["location_columns_present"] = [ + column + for column in COUNTY_DETERMINING_LOCATION_COLUMNS + if column in households.columns + ] + by_puma = _county_groups(pumas) + counts = defaultdict(int) + for code in codes: + counts[int(code)] += 1 + moved = np.zeros(len(households), dtype=bool) + moves = [] + for county in unsupported: + order = overlaps.get(county, []) + tried, taken = [], [] + for puma, _population in order: + if puma // 100_000 != county // 1000: + raise ValueError( + f"Ladder overlap puts county {county:05d} in PUMA {puma:07d} " + "of another state." + ) + tried.append(f"{puma:07d}") + positions = by_puma.get(puma, np.empty(0, dtype=np.int64)) + candidates = sorted( + ( + position + for position in positions.tolist() + if eligible[position] and not moved[position] + ), + key=lambda position: ( + support_rank(key, county, ids[position]), + position, + ), + ) + for position in candidates: + if len(taken) == per_county: + break + donor = int(codes[position]) + pending = sum( + 1 for _p, from_county, _r in taken if from_county == donor + ) + if counts[donor] - pending - 1 < per_county: + continue + taken.append((position, donor, puma)) + if len(taken) == per_county: + break + status = "moved" if len(taken) == per_county else "insufficient_eligible_donors" + if status == "moved": + for position, donor, puma in taken: + counts[donor] -= 1 + counts[county] += 1 + moved[position] = True + household_id = ids[position] + moves.append( + { + "household_id": ( + int(household_id) + if isinstance(household_id, (int, np.integer)) + else str(household_id) + ), + "from_county": f"{donor:05d}", + "to_county": f"{county:05d}", + "puma": f"{puma:07d}", + "rank": support_rank(key, county, household_id), + } + ) + receipt["counties"][f"{county:05d}"] = { + "ladder_population": float(county_populations[county]), + "pumas_by_overlap": [f"{puma:07d}" for puma, _population in order], + "pumas_tried": tried, + "moved": per_county if status == "moved" else 0, + "status": status, + } + receipt["moves"] = moves + receipt["moves_sha256"] = _moves_digest(moves) + receipt["moved_counties"] = sorted({move["to_county"] for move in moves}) + return moves, receipt + + +def _county_value(template, code): + if pd.api.types.is_numeric_dtype(template.dtype): + return int(code) + return f"{int(code):05d}" + + +def apply_support_moves( + households, moves, *, county_column=COUNTY_COLUMN, columns=None +): + """Rewrite the county columns of each moved household, nothing else. + + Each move must still find its household in ``from_county`` and its PUMA, + so a recorded plan cannot land on another frame silently. + """ + if not moves: + return households + result = households.copy() + columns = ( + list(columns) + if columns is not None + else [county_column] + + [ + column + for column in COUNTY_FIPS_COLUMNS + if column in households.columns and column != county_column + ] + ) + ids = pd.Index(result["household_id"].to_numpy()) + if not ids.is_unique: + raise ValueError("Minimum county support needs unique household ids.") + codes = county_codes(result, county_column=county_column) + pumas = _household_pumas(result) + keys = [move["household_id"] for move in moves] + positions = ids.get_indexer(keys) + if (positions < 0).any(): + raise ValueError("A recorded county support move names an absent household.") + if len(set(positions.tolist())) != len(positions): + raise ValueError("A household is moved twice by the county support plan.") + for position, move in zip(positions.tolist(), moves, strict=True): + if codes[position] != int(move["from_county"]) or pumas[position] != int( + move["puma"] + ): + raise ValueError( + f"County support move of household {move['household_id']} no longer " + f"matches its county {codes[position]:05d} or PUMA " + f"{pumas[position]:07d}." + ) + if int(move["to_county"]) // 1000 != codes[position] // 1000: + raise ValueError("A county support move would change the state.") + for column in columns: + location = result.columns.get_loc(column) + for position, move in zip(positions.tolist(), moves, strict=True): + result.iat[position, location] = _county_value( + result[column], move["to_county"] + ) + return result + + +def with_household_table(frame, households): + """The same frame with its household table replaced.""" + from microcosm.frame import Frame + + tables = {entity: frame.table(entity) for entity in frame.entities} + tables["household"] = households + tables.update({name: frame.link(name) for name in frame.links}) + return Frame( + tables, + frame.schema, + {entity: frame.weights_for(entity) for entity in frame.weighted_entities}, + frame.strata, + mass_log=frame.mass_log, + metadata=frame.metadata, + ) + + +def apply_recorded_support(frame, identity, checkpoint_dir): + """Re-apply the materialize-time county support moves to a staging frame. + + The consumer export reloads staging, so without this the published file + would lose the moves calibration saw. The recorded moves must match the + digest the run identity binds. + """ + receipt = (identity or {}).get("county_support") or {} + if not receipt.get("moves"): + return frame + report = json.loads((Path(checkpoint_dir) / SUPPORT_FILENAME).read_text()) + moves = (report.get("minimum_support") or {}).get("moves", []) + if _moves_digest(moves) != receipt.get("moves_sha256") or len(moves) != receipt.get( + "moves" + ): + raise SystemExit( + f"{SUPPORT_FILENAME} no longer holds the county support moves the run " + "identity binds; re-run --stage materialize." + ) + households = apply_support_moves( + frame.table("household"), + moves, + county_column=identity.get("county_column", COUNTY_COLUMN), + columns=receipt.get("rewritten_columns"), + ) + return with_household_table(frame, households) + + def require_support(dropped, *, capped_smoke=False): if dropped and not capped_smoke: raise SystemExit( @@ -732,6 +2241,17 @@ def add_arguments(parser): "--county-facts-sha256", help="SHA-256 of --county-facts; must be the county pin's facts_sha256.", ) + parser.add_argument( + "--county-min-support", + type=int, + default=DEFAULT_COUNTY_MIN_SUPPORT, + help=( + "Households moved, within the same PUMA, into each county whose " + "ladder population is positive but which has no household " + f"(default {DEFAULT_COUNTY_MIN_SUPPORT}; 0 disables the step). " + "Every move is recorded in county_support.json." + ), + ) def _validate_county_facts(args, parser, geographies): @@ -801,10 +2321,15 @@ def validate_arguments(args, parser): parser.error("--county-column must be a household column name.") if not args.county_holdout_salt: parser.error("--county-holdout-salt must be a non-empty string.") + if not 0 <= args.county_min_support <= MAX_COUNTY_MIN_SUPPORT: + parser.error(f"--county-min-support must be in [0, {MAX_COUNTY_MIN_SUPPORT}].") _validate_county_facts(args, parser, geographies) def prepare_run(args, geographies, populations, *, surface=None): + # Validation inputs describe one materialization; a new one replaces them. + for name in (VALIDATION_DESIGN_FILENAME, VALIDATION_MEASURES_FILENAME): + (Path(args.checkpoint_dir) / name).unlink(missing_ok=True) if ( "county" in geographies and args.sample_fraction == 1.0 @@ -833,6 +2358,14 @@ def prepare_run(args, geographies, populations, *, surface=None): surface.county_facts.rows, populations["county"], ) + # Refuse incomplete ACS inventories, duplicates, negatives and + # zero denominators here, before the engine pass. + surface.acs_households = acs_household_surface( + surface.county_facts.rows, populations["county"] + ) + surface.county_validation_design = county_validation_design( + surface.county_facts.rows, populations["county"] + ) except (ValueError, OSError) as error: (args.checkpoint_dir / "county_surface.json").write_text( json.dumps({"status": "refused", "error": str(error)}) @@ -841,62 +2374,181 @@ def prepare_run(args, geographies, populations, *, surface=None): def check_support(frame, populations, args): + """Apply minimum support, write county_support.json, refuse what remains. + + Returns the frame, with county columns rewritten for any moved household. + """ if "county" not in populations: - return + return frame + column = getattr(args, "county_column", COUNTY_COLUMN) + per_county = int(getattr(args, "county_min_support", 0) or 0) households = frame.table("household") - codes = county_codes( - households, county_column=getattr(args, "county_column", COUNTY_COLUMN) - ) + codes = county_codes(households, county_column=column) unknown = sorted(set(codes) - set(populations["county"])) + support = None + needed = any( + float(population) > 0 and int(code) not in set(codes.tolist()) + for code, population in populations["county"].items() + ) + if per_county > 0 and not unknown: + overlaps = county_puma_overlaps(args.ladder) if needed else {} + moves, support = plan_minimum_support( + households, + populations["county"], + overlaps, + county_column=column, + per_county=per_county, + ) + if moves: + frame = with_household_table( + frame, + apply_support_moves( + households, + moves, + county_column=column, + columns=support["rewritten_columns"], + ), + ) + households = frame.table("household") + codes = county_codes(households, county_column=column) + args.county_support_receipt = { + "file": SUPPORT_FILENAME, + "households_per_county": per_county, + "key": COUNTY_MIN_SUPPORT_KEY, + "moves": len(moves), + "moves_sha256": support["moves_sha256"], + "moved_counties": support.get("moved_counties", []), + "rewritten_columns": support["rewritten_columns"], + } missing = sorted(set(populations["county"]) - set(codes)) + counts = defaultdict(int) + for code in codes: + counts[int(code)] += 1 report = { - "county_column": getattr(args, "county_column", COUNTY_COLUMN), + "county_column": column, "counties": { - f"{int(code):05d}": {"supporting_households": int((codes == code).sum())} + f"{int(code):05d}": {"supporting_households": counts.get(int(code), 0)} for code in sorted(populations["county"]) }, "unsupported_counties": [f"{int(code):05d}" for code in missing], "unknown_counties": [f"{int(code):05d}" for code in unknown], } - (args.checkpoint_dir / "county_support.json").write_text( - json.dumps(report, indent=2) - ) + if support is not None: + report["minimum_support"] = support + (args.checkpoint_dir / SUPPORT_FILENAME).write_text(json.dumps(report, indent=2)) if unknown: raise SystemExit(f"Households name counties outside the ladder: {unknown}.") smoke = bool(args.allow_partial_geography and args.sample_fraction < 1) require_support(report["unsupported_counties"], capped_smoke=smoke) + return frame + + +def _write_validation_inputs(checkpoint_dir, design, arrays, report): + checkpoint_dir = Path(checkpoint_dir) + design_path = checkpoint_dir / VALIDATION_DESIGN_FILENAME + measures_path = checkpoint_dir / VALIDATION_MEASURES_FILENAME + design_path.write_text( + json.dumps({**design, "household_measures": report}, indent=1, allow_nan=False) + ) + np.savez( + measures_path, + household_id=np.asarray(arrays["household_id"]), + in_household_universe=np.asarray(arrays["in_household_universe"], np.float64), + earnings=np.asarray(arrays["earnings"], np.float64), + household_income_approx=np.asarray( + arrays["household_income_approx"], np.float64 + ), + ) + + def digest(path): + return hashlib.sha256(path.read_bytes()).hexdigest() + + return { + "design_file": VALIDATION_DESIGN_FILENAME, + "design_sha256": digest(design_path), + "measures_file": VALIDATION_MEASURES_FILENAME, + "measures_sha256": digest(measures_path), + "families": [family.name for family in VALIDATION_FAMILIES], + "role": "held out: scored after calibration, never in the loss, the " + "target registry, the roles or the matrix", + } + + +def load_validation_inputs(checkpoint_dir, receipt): + """The validation design and household measures, refused if they changed.""" + checkpoint_dir = Path(checkpoint_dir) + design_path = checkpoint_dir / receipt["design_file"] + measures_path = checkpoint_dir / receipt["measures_file"] + for path, recorded in ( + (design_path, receipt.get("design_sha256")), + (measures_path, receipt.get("measures_sha256")), + ): + if ( + not path.is_file() + or hashlib.sha256(path.read_bytes()).hexdigest() != recorded + ): + raise SystemExit( + f"{path.name} changed since materialize (or is missing); the " + "county validation inputs no longer match the run identity. " + "Re-run --stage materialize." + ) + design = json.loads(design_path.read_text()) + with np.load(measures_path, allow_pickle=False) as stored: + measures = {key: stored[key] for key in stored.files} + return design, measures def attach_surface(surface, materialized, frame, populations, args): if args.soi_mode != SOI_MODE: return materialized.compiled_specs, materialized.matrix + column = getattr(args, "county_column", COUNTY_COLUMN) + facts = getattr(surface, "county_facts", None) county = getattr(surface, "county_surface", None) if county is None: - facts = getattr(surface, "county_facts", None) or _load_county_facts(args) + facts = facts or _load_county_facts(args) county = state_county_soi_surface( materialized.compiled_specs, facts.rows, populations["county"] ) + acs = getattr(surface, "acs_households", None) + if acs is None: + facts = facts or _load_county_facts(args) + acs = acs_household_surface(facts.rows, populations["county"]) + design = getattr(surface, "county_validation_design", None) + if design is None: + facts = facts or _load_county_facts(args) + design = county_validation_design(facts.rows, populations["county"]) + households = frame.table("household") matrix = split_state_rows( materialized.compiled_specs, materialized.matrix, county.specs, - frame.table("household"), - county_column=getattr(args, "county_column", COUNTY_COLUMN), + households, + county_column=column, ) + acs_matrix = acs_household_rows(households, acs.specs, county_column=column) # A positive target with only zero household measures is unsupported too. empty = [ spec.name - for index, spec in enumerate(county.specs) - if spec.value != 0 and matrix.indptr[index] == matrix.indptr[index + 1] + for rows, specs in ((matrix, county.specs), (acs_matrix, acs.specs)) + for index, spec in enumerate(specs) + if spec.value != 0 and rows.indptr[index] == rows.indptr[index + 1] ] - (args.checkpoint_dir / "county_surface.json").write_text( - json.dumps({**county.receipt, "unsupported_targets": empty}, indent=2) + (args.checkpoint_dir / SURFACE_FILENAME).write_text( + json.dumps( + { + **county.receipt, + "acs_households": acs.receipt, + "unsupported_targets": empty, + }, + indent=2, + ) ) require_support( empty, capped_smoke=bool(args.allow_partial_geography and args.sample_fraction < 1), ) - county_specs = list(county.specs) + county_specs = [*county.specs, *acs.specs] + matrix = sparse.vstack([matrix, acs_matrix], format="csr") if empty: unsupported = set(empty) keep = [ @@ -907,6 +2559,21 @@ def attach_surface(surface, materialized, frame, populations, args): matrix = sparse.csr_array(matrix[keep]) county_specs = [county_specs[index] for index in keep] args.county_targets_dropped = empty + args.county_acs_households_receipt = { + key: acs.receipt[key] + for key in ( + "family", + "source_measure_id", + "new_state_targets", + "county_targets", + ) + } + # The validation families' household measures, from the full frame: the + # calibrate stage only has the lean checkpoint. + arrays, measure_report = household_validation_measures(frame) + args.county_validation_receipt = _write_validation_inputs( + args.checkpoint_dir, design, arrays, measure_report + ) surface.soi_receipt.update(county.receipt) return [*materialized.compiled_specs, *county_specs], sparse.vstack( [materialized.matrix, matrix], format="csr" @@ -935,11 +2602,17 @@ def run_metadata(args, county_holdout): "county_holdout": county_holdout, "county_targets_dropped": getattr(args, "county_targets_dropped", []), } - # Only a run that read county facts records them, so a no-county run - # identity keeps its pre-county bytes. - receipt = getattr(args, "county_facts_receipt", None) - if receipt is not None: - metadata["county_facts"] = receipt + # Only a run that read county facts (or ran the county support step) + # records them, so a no-county run identity keeps its pre-county bytes. + for key, attribute in ( + ("county_facts", "county_facts_receipt"), + ("county_support", "county_support_receipt"), + ("county_acs_households", "county_acs_households_receipt"), + ("county_validation", "county_validation_receipt"), + ): + receipt = getattr(args, attribute, None) + if receipt is not None: + metadata[key] = receipt return metadata @@ -954,8 +2627,23 @@ def struct_columns(households, existing_columns, *, county_column=COUNTY_COLUMN) def calibration_evidence( - frame, roles, matrix, design_weights, weights, target_loss_cap + frame, + roles, + matrix, + design_weights, + weights, + target_loss_cap, + *, + checkpoint_dir=None, + identity=None, ): + """County holdout, validation and reliability evidence (report only). + + Reads the final weights; nothing here feeds back into the solve. With a + run identity that records county validation inputs, every validation + family is scored for every county and the reliability report grades on + it. + """ county_roles = [ record for record in roles if record.get("geography_level") == "county" ] @@ -971,7 +2659,27 @@ def calibration_evidence( ), COUNTY_COLUMN, ) - return { + households = frame.table("household") + receipt = (identity or {}).get("county_validation") + validation = design = None + if receipt: + if checkpoint_dir is None: + raise SystemExit( + "The run identity records county validation inputs; scoring " + "them needs the checkpoint directory." + ) + design, measures = load_validation_inputs(checkpoint_dir, receipt) + validation = score_county_validation( + design, + measures, + households, + final_weights=weights, + design_weights=design_weights, + cap=target_loss_cap, + county_column=column, + ) + support = (identity or {}).get("county_support") or {} + evidence = { "county_holdout": score_county_holdout( roles, matrix, @@ -980,13 +2688,22 @@ def calibration_evidence( cap=target_loss_cap, ), "county_reliability": reliability_report( - frame.table("household"), + households, roles, matrix, final_weights=weights, county_column=column, + validation=validation, + county_populations=None if design is None else design["county_populations"], + minimum_support_counties=support.get("moved_counties", []), + county_names=None if design is None else design["county_names"], ), } + if validation is not None: + evidence["county_validation"] = { + key: value for key, value in validation.items() if key != "counties" + } + return evidence def _bound_report(summary, identity): @@ -998,14 +2715,27 @@ def _bound_report(summary, identity): report["counties"].setdefault( code, { + "state_fips": code[:2], + "county_name": None, "supporting_households": 0, "distinct_source_households": 0, "kish_ess": 0.0, "kish_ess_rows": 0.0, - "training": {"n_targets": 0, "mean_abs_rel_error": None}, - "holdout": {"n_targets": 0, "mean_abs_rel_error": None}, - "grade": "U", "status": "no_support", + "training": { + "n_targets": 0, + "mean_abs_rel_error": None, + "max_abs_rel_error": None, + }, + "holdout": { + "n_targets": 0, + "mean_abs_rel_error": None, + "max_abs_rel_error": None, + }, + "validation": {"n_families": 0, "families": {}}, + "grade_error": None, + "grade_driver": None, + "grade": "U", }, ) report.update( @@ -1013,6 +2743,8 @@ def _bound_report(summary, identity): ) report["county_column"] = identity.get("county_column", COUNTY_COLUMN) report["unsupported_targets"] = identity.get("county_targets_dropped", []) + if identity.get("county_support"): + report["minimum_support"] = identity["county_support"] return report @@ -1023,18 +2755,28 @@ def feed_path(feed): def write_reports(checkpoint_dir, summary, *, identity): + """Write county_reliability.json and its flat CSV into the checkpoint.""" if "county_reliability" not in summary: return + report = _bound_report(summary, identity) (Path(checkpoint_dir) / RELIABILITY_FILENAME).write_text( - json.dumps(_bound_report(summary, identity), indent=2, allow_nan=False) + json.dumps(report, indent=2, allow_nan=False) + ) + (Path(checkpoint_dir) / RELIABILITY_CSV_FILENAME).write_text( + reliability_csv(report) ) def package_reports(contract_files, checkpoint_dir, identity): + """Add the bound reliability JSON; return the CSV files to package beside it. + + Both must match the current calibration identity, weights and evidence: + the CSV must be exactly the flattening of the bound report. + """ if "county" not in { item.strip() for item in identity.get("geographies", "").split(",") }: - return + return {} report = json.loads((Path(checkpoint_dir) / RELIABILITY_FILENAME).read_text()) summary = json.loads( (Path(checkpoint_dir) / "calibration_summary.json").read_text() @@ -1050,7 +2792,15 @@ def package_reports(contract_files, checkpoint_dir, identity): raise SystemExit( "County reliability report does not match the current calibration identity, weights or evidence." ) + csv_path = Path(checkpoint_dir) / RELIABILITY_CSV_FILENAME + expected = reliability_csv(report) + if not csv_path.is_file() or csv_path.read_text() != expected: + raise SystemExit( + f"{RELIABILITY_CSV_FILENAME} is missing or is not the flattening of " + f"the bound {RELIABILITY_FILENAME}; re-run --stage calibrate." + ) contract_files[RELIABILITY_FILENAME] = report + return {RELIABILITY_CSV_FILENAME: expected} def refresh_recipe(command, materialize_rss): @@ -1073,6 +2823,9 @@ def refresh_recipe(command, materialize_rss): " --county-facts " f" --county-facts-sha256 {facts['facts_sha256']}" ) + support = materialize_rss.get("county_support") + if support: + command += f" --county-min-support {int(support['households_per_county'])}" return command @@ -1085,24 +2838,34 @@ def _is_county(spec): ) +def _is_acs_family(spec): + return spec.family == ACS_HOUSEHOLDS_FAMILY + + def loss_row_mapping(specs): """Extend the existing loss formula with county count/amount budgets. Each county concept shares one budget across its state's counties, so - adding thousands of counties does not multiply its loss budget. + adding thousands of counties does not multiply its loss budget. ACS + household rows are counts; each state households parent has its own + budget, as each state population row does. """ from microcosm.build.us_runtime import target_loss_weights as weighting base = weighting.US_ACS_LOCAL_TARGET_LOSS_ROW_MAPPING - if not any(_is_county(spec) for spec in specs): + if not any(_is_county(spec) or _is_acs_family(spec) for spec in specs): return base def basis(spec): - if _is_county(spec) and spec.family == "census_population": + if _is_acs_family(spec) or ( + _is_county(spec) and spec.family == "census_population" + ): return weighting.COUNT_BASIS return base.value_basis(spec) def key(spec): + if _is_acs_family(spec) and not _is_county(spec): + return (basis(spec), spec.entity, spec.period, spec.family, spec.name) if not _is_county(spec): return base.concept_budget_key(spec) code = spec.metadata["county_fips"] @@ -1120,7 +2883,11 @@ def key(spec): ) def validate(rows, bases, keys): - indices = [index for index, spec in enumerate(rows) if not _is_county(spec)] + indices = [ + index + for index, spec in enumerate(rows) + if not (_is_county(spec) or _is_acs_family(spec)) + ] if base.validate is not None: base.validate( [rows[index] for index in indices], @@ -1129,7 +2896,7 @@ def validate(rows, bases, keys): ) return weighting.TargetLossRowMapping( - "us_acs_local_county.v1", basis, key, validate + "us_acs_local_county.v2", basis, key, validate ) From a31efcb2e74eb2d070adc03f2e46ead26b8dba4c Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 14 Nov 2026 22:28:11 -0500 Subject: [PATCH 02/20] Test the production county rung and update the county smoke test (#922) The new engine-free file covers ACS fact parsing and refusals, the trained acs_households family, the declared Kalawao/Maui SOI cell, minimum county support, validation scoring and grades for 3,144 counties, the reliability CSV and its packaging check. It copies the SOI fixture helpers instead of importing the older test module, whose imports pull in policyengine_us. The county smoke test now feeds ACS rows in the pinned shape and person earnings, expects the 12-row matrix and scores validation end to end. The refresh recipe now replays --county-min-support 0 for a run that recorded no support receipt, instead of falling back to the default of 3. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_acs_local_county_production.py | 238 +++++++++++------- .../us/test_us_acs_local_county_surface.py | 91 ++++++- tools/us_acs_local_county_surface.py | 7 +- 3 files changed, 240 insertions(+), 96 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py index bf5f222f72..8a1f167678 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py @@ -13,6 +13,7 @@ import importlib.util import json import math +import sys from functools import lru_cache from types import SimpleNamespace @@ -21,7 +22,7 @@ import pytest from scipy import sparse -from microcosm.calibrate import TargetRegistry +from microcosm.calibrate import TargetRegistry, TargetSpec from test_support.paths import paths_for hypothesis = pytest.importorskip("hypothesis") @@ -31,29 +32,81 @@ _SETTINGS = settings(max_examples=40, deadline=None) -@lru_cache -def _fixtures(): - path = ( - paths_for("microcosm-build").tests - / "engine_free" - / "us" - / "test_us_acs_local_county_surface.py" - ) - spec = importlib.util.spec_from_file_location( - "county_production_fixtures", path +# The SOI fixtures of test_us_acs_local_county_surface.py, copied rather than +# imported: that module imports microcosm.build.us_runtime, whose package +# imports policyengine_us, and these tests need no engine. +def _state_spec(measure="return_count", value=100.0, *, state="01", **metadata): + variable = "count" if measure == "return_count" else measure + name = f"state.{state}.{measure}" + return TargetSpec( + name=name, + entity="household", + measure=name, + value=value, + period=2024, + source="fixture state SOI", + family="irs_soi", + signed=value < 0, + metadata={ + "ledger_geography_level": "state", + "ledger_layout_record_set_spec_id": "irs_soi.historic_table_2.state_broad_totals.v1", + "state_fips": state, + "source_measure_id": measure, + "source_period": "2022", + "ledger_measure_unit": "count" if measure == "return_count" else "usd", + "variable": variable, + "source_variable": variable, + "soi_variable": variable, + "measure_mode": "sum", + "agi_lower_bound": "-inf", + "agi_upper_bound": "inf", + "filing_status": "All", + **metadata, + }, ) - module = importlib.util.module_from_spec(spec) - assert spec.loader is not None - spec.loader.exec_module(module) - return module -def _county(): - return _fixtures()._county() +def _fact(county, measure, value): + return { + "geography": { + "id": f"0500000US{county}", + "level": "county", + "name": f"County {county}", + "vintage": "2022", + }, + "period": {"type": "tax_year", "value": 2022}, + "observed_measure": { + "source_measure_id": measure, + "source_concept": ( + "irs_soi.individual_income_tax_returns" + if measure == "return_count" + else "irs_soi.adjusted_gross_income" + ), + "source_name": "irs_soi", + "unit": "count" if measure == "return_count" else "usd", + }, + "layout": { + "record_set_id": "irs_soi.ty2022.county_totals", + "record_set_spec_id": "irs_soi.county_totals.v1", + "measure_id": measure, + }, + "dimensions": {"filing_status": "all", "income_range": "all"}, + "value": value, + } -def _release(): - return _fixtures()._release() +@lru_cache +def _county(): + """The county surface module alone. + + Loading it through the release tool imports policyengine_us, which these + engine-free tests never need. The release imports the same module by the + same name, so either route gives one module object. + """ + tools = str(paths_for("microcosm-build").repository / "tools") + if tools not in sys.path: + sys.path.insert(0, tools) + return importlib.import_module("us_acs_local_county_surface") _TABLE_DIMENSIONS = { @@ -171,14 +224,13 @@ def _acs_rows(counties, *, values=None, without_median=(), b01003_group_1=()): def _soi_rows(values): """IRS SOI county rows, ``{county: (returns, agi)}``.""" - fixture = _fixtures() rows = [] for county, (returns, agi) in values.items(): for measure, value in ( ("return_count", returns), ("adjusted_gross_income", agi), ): - row = fixture._fact(county, measure, value) + row = _fact(county, measure, value) row["layout"]["groupby_value_id"] = f"county_{county}" rows.append(row) return rows @@ -255,12 +307,11 @@ def test_acs_county_inventory_refusals(case) -> None: def test_a_puerto_rico_soi_row_reaching_the_rung_is_refused() -> None: - fixture = _fixtures() county = _county() rows = _soi_rows({"01001": (10, 100), "72001": (5, 50)}) with pytest.raises(ValueError, match="Puerto Rico"): county.state_county_soi_surface( - [fixture._state_spec(), fixture._state_spec("adjusted_gross_income")], + [_state_spec(), _state_spec("adjusted_gross_income")], rows, {1001: 10.0}, ) @@ -281,9 +332,7 @@ def test_median_income_is_a_diagnostic_and_a_missing_county_is_listed() -> None: assert "B19013_001E" not in measures -def test_validation_design_refuses_a_zero_state_denominator_and_bad_brackets() -> ( - None -): +def test_validation_design_refuses_a_zero_state_denominator_and_bad_brackets() -> None: county = _county() values = {code: _county_values(code) for code in ["01001", "01003"]} for data in values.values(): @@ -306,7 +355,9 @@ def test_validation_design_refuses_a_zero_state_denominator_and_bad_brackets() - @st.composite def _acs_layouts(draw): states = draw( - st.lists(st.sampled_from([1, 6, 12, 15, 36]), min_size=1, max_size=3, unique=True) + st.lists( + st.sampled_from([1, 6, 12, 15, 36]), min_size=1, max_size=3, unique=True + ) ) counties = {} for state in states: @@ -342,9 +393,7 @@ def test_acs_household_children_sum_to_their_new_state_parent(layout) -> None: } for state, parent in parents.items(): public = math.fsum( - data["households"] - for code, data in values.items() - if code[:2] == state + data["households"] for code, data in values.items() if code[:2] == state ) assert parent.value == pytest.approx(public, rel=1e-12) assert parent.family == "acs_households" @@ -362,20 +411,23 @@ def test_acs_household_children_sum_to_their_new_state_parent(layout) -> None: assert surface.receipt["new_state_targets"] == len(parents) -def test_acs_household_specs_share_one_label_per_geography_with_other_targets() -> ( - None -): - fixture = _fixtures() +def test_acs_household_specs_share_one_label_per_geography_with_other_targets() -> None: + from microcosm.calibrate.geography_constants import US_STATE_FIPS_TO_NAME + county = _county() - module = _release() populations = {1001: 80.0, 1003: 120.0} acs = county.acs_household_surface(_acs_rows(["01001", "01003"]), populations) - population_specs = module.population_target_specs( - ["pop_state_01", "pop_county_01001", "pop_county_01003"], [200.0, 80.0, 120.0] - ) - TargetRegistry( - (*population_specs, *acs.specs, fixture._state_spec()), country="us" - ) + for spec in acs.specs: + geography = spec.hierarchy.geography + if spec.metadata["geography_level"] == "state": + assert geography.id == "0400000US01" + # The label the release's state population targets carry. + assert geography.label == US_STATE_FIPS_TO_NAME["01"] + county_population = [ + county.population_spec(f"pop_county_{code:05d}", value) + for code, value in populations.items() + ] + TargetRegistry((*county_population, *acs.specs, _state_spec()), country="us") def _households(rows): @@ -445,7 +497,9 @@ def test_acs_household_rows_partition_each_state_row(draws) -> None: # Each household counts in at most one county row, and only if it is # a household (not group quarters). assert (rows[children].toarray() > 0).sum(axis=0).max(initial=0) <= 1 - in_state = households["state_fips"].to_numpy() == int(spec.metadata["state_fips"]) + in_state = households["state_fips"].to_numpy() == int( + spec.metadata["state_fips"] + ) np.testing.assert_array_equal(parent, universe * in_state) @@ -455,10 +509,9 @@ def test_acs_household_rows_partition_each_state_row(draws) -> None: def _hawaii_parents(): - fixture = _fixtures() return [ - fixture._state_spec(state="15", value=500.0), - fixture._state_spec("adjusted_gross_income", 50_000.0, state="15"), + _state_spec(state="15", value=500.0), + _state_spec("adjusted_gross_income", 50_000.0, state="15"), ] @@ -474,9 +527,7 @@ def _hawaii_soi(without=(15005,)): def test_kalawao_shares_a_declared_soi_cell_with_maui() -> None: county = _county() - surface = county.state_county_soi_surface( - _hawaii_parents(), _hawaii_soi(), _HAWAII - ) + surface = county.state_county_soi_surface(_hawaii_parents(), _hawaii_soi(), _HAWAII) maui = [spec for spec in surface.specs if spec.metadata["county_fips"] == "15009"] assert len(maui) == 2 for spec in maui: @@ -521,7 +572,11 @@ def test_an_undeclared_absent_county_is_still_refused() -> None: @pytest.mark.parametrize( ("cells", "match"), - [({15005: 6001}, "one state"), ({15005: 15005}, "distinct"), ({15005: 15009, 15009: 15001}, "itself merged")], + [ + ({15005: 6001}, "one state"), + ({15005: 15005}, "distinct"), + ({15005: 15009, 15009: 15001}, "itself merged"), + ], ) def test_declared_combined_cells_must_be_well_formed(cells, match) -> None: with pytest.raises(ValueError, match=match): @@ -535,9 +590,10 @@ def test_a_present_declared_county_keeps_its_own_soi_row() -> None: _hawaii_parents(), _hawaii_soi(without=()), _HAWAII ) assert surface.receipt["combined_cells"] == [] - assert {spec.metadata["county_fips"] for spec in surface.specs} == _codes( - _HAWAII - ).__class__(_codes(_HAWAII)) | set() + assert {spec.metadata["county_fips"] for spec in surface.specs} == set( + _codes(_HAWAII) + ) + assert "state_county_cell_members" not in surface.specs[0].metadata @_SETTINGS @@ -547,12 +603,8 @@ def test_a_present_declared_county_keeps_its_own_soi_row() -> None: ) def test_combined_cells_partition_the_parent_row_exactly(codes, values) -> None: county = _county() - surface = county.state_county_soi_surface( - _hawaii_parents(), _hawaii_soi(), _HAWAII - ) - households = _households( - {"county_fips": code, "state_fips": 15} for code in codes - ) + surface = county.state_county_soi_surface(_hawaii_parents(), _hawaii_soi(), _HAWAII) + households = _households({"county_fips": code, "state_fips": 15} for code in codes) parents = _hawaii_parents() data = np.asarray(values[: len(codes)], dtype=np.float32) parent_matrix = sparse.csr_array(np.vstack([np.ones(len(codes)), data])) @@ -591,9 +643,7 @@ def test_combined_cells_partition_the_parent_row_exactly(codes, values) -> None: def test_split_rows_refuse_overlapping_member_sets() -> None: county = _county() - surface = county.state_county_soi_surface( - _hawaii_parents(), _hawaii_soi(), _HAWAII - ) + surface = county.state_county_soi_surface(_hawaii_parents(), _hawaii_soi(), _HAWAII) specs = list(surface.specs) tampered = [ spec @@ -620,12 +670,11 @@ def test_split_rows_refuse_overlapping_member_sets() -> None: def test_any_all_return_soi_concept_with_a_broad_parent_gets_county_rows() -> None: - fixture = _fixtures() county = _county() parents = [ - fixture._state_spec(), - fixture._state_spec("adjusted_gross_income", 1000.0), - fixture._state_spec( + _state_spec(), + _state_spec("adjusted_gross_income", 1000.0), + _state_spec( "wages_and_salaries_amount", 600.0, ledger_measure_unit="usd", @@ -633,12 +682,10 @@ def test_any_all_return_soi_concept_with_a_broad_parent_gets_county_rows() -> No ] facts = _soi_rows({"01001": (10, 100), "01003": (30, 300)}) for code, value in (("01001", 40.0), ("01003", 120.0)): - row = fixture._fact(code, "wages_and_salaries_amount", value) + row = _fact(code, "wages_and_salaries_amount", value) row["observed_measure"]["unit"] = "usd" facts.append(row) - surface = county.state_county_soi_surface( - parents, facts, {1001: 1.0, 1003: 1.0} - ) + surface = county.state_county_soi_surface(parents, facts, {1001: 1.0, 1003: 1.0}) wages = { spec.metadata["county_fips"]: spec.value for spec in surface.specs @@ -736,20 +783,32 @@ def test_a_fully_supported_frame_is_returned_unchanged() -> None: @st.composite def _support_layouts(draw): - states = draw(st.lists(st.sampled_from([1, 6]), min_size=1, max_size=2, unique=True)) + states = draw( + st.lists(st.sampled_from([1, 6]), min_size=1, max_size=2, unique=True) + ) overlaps_rows, cells, populations = [], [], {} for state in states: - pumas = [state * 100_000 + index + 1 for index in range(draw(st.integers(1, 2)))] - counties = [state * 1000 + 2 * index + 1 for index in range(draw(st.integers(2, 5)))] + pumas = [ + state * 100_000 + index + 1 for index in range(draw(st.integers(1, 2))) + ] + counties = [ + state * 1000 + 2 * index + 1 for index in range(draw(st.integers(2, 5))) + ] for code in counties: populations[code] = float(draw(st.integers(0, 1000))) - for puma in draw(st.lists(st.sampled_from(pumas), min_size=1, max_size=2, unique=True)): + for puma in draw( + st.lists(st.sampled_from(pumas), min_size=1, max_size=2, unique=True) + ): overlaps_rows.append((puma, code, float(draw(st.integers(1, 500))))) cells += [(puma, code)] * draw(st.integers(0, 7)) if not cells: cells = [(overlaps_rows[0][0], overlaps_rows[0][1])] flags = draw( - st.lists(st.sampled_from(["", "tract", "gq", "disagree"]), min_size=len(cells), max_size=len(cells)) + st.lists( + st.sampled_from(["", "tract", "gq", "disagree"]), + min_size=len(cells), + max_size=len(cells), + ) ) per_county = draw(st.integers(1, 4)) order = draw(st.permutations(range(len(cells)))) @@ -831,7 +890,7 @@ def test_recorded_moves_reapply_to_a_fresh_frame_and_refuse_a_changed_plan( ), } for group in US_SCHEMA.group_entities: - tables[group] = pd.DataFrame({f"{group}_id": ids}) + tables.setdefault(group, pd.DataFrame({f"{group}_id": ids})) frame = Frame( tables, US_SCHEMA, @@ -887,7 +946,7 @@ def test_check_support_applies_minimum_support_before_refusing( ), } for group in US_SCHEMA.group_entities: - tables[group] = pd.DataFrame({f"{group}_id": ids}) + tables.setdefault(group, pd.DataFrame({f"{group}_id": ids})) frame = Frame( tables, US_SCHEMA, {"household": Weights(np.ones(8), WeightKind.DESIGN)} ) @@ -917,7 +976,9 @@ def test_check_support_applies_minimum_support_before_refusing( # Without the step the same frame is refused. with pytest.raises(SystemExit, match="no supporting household"): county.check_support( - frame, populations, SimpleNamespace(**{**vars(args), "county_min_support": 0}) + frame, + populations, + SimpleNamespace(**{**vars(args), "county_min_support": 0}), ) @@ -938,7 +999,9 @@ def _validation_inputs(counties, households_per_county, *, seed=0): "household_id": np.arange(1, n + 1), "county_fips": codes, "state_fips": codes // 1000, - "household_spine": np.where(np.arange(n) % 2 == 0, "acs_2024_1yr", "asec_puf"), + "household_spine": np.where( + np.arange(n) % 2 == 0, "acs_2024_1yr", "asec_puf" + ), "household_source_id": np.arange(n), } ) @@ -955,7 +1018,9 @@ def _validation_inputs(counties, households_per_county, *, seed=0): def test_validation_targets_redistribute_each_state_total_by_public_shares() -> None: county = _county() counties = ["01001", "01003", "01005", "06001", "06003"] - design, measures, households, weights = _validation_inputs(counties, [5, 3, 4, 6, 2]) + design, measures, households, weights = _validation_inputs( + counties, [5, 3, 4, 6, 2] + ) result = county.score_county_validation( design, measures, @@ -1134,7 +1199,9 @@ def test_combined_soi_cell_errors_count_toward_both_member_counties() -> None: @_SETTINGS @given(st.floats(0.0, 1.0), st.floats(1.0, 2_000.0), st.floats(1.0, 2_000.0)) -def test_grades_stay_monotone_in_ess_at_fixed_validation_error(error, low, high) -> None: +def test_grades_stay_monotone_in_ess_at_fixed_validation_error( + error, low, high +) -> None: county = _county() order = "UABCD" low, high = sorted((low, high)) @@ -1161,8 +1228,7 @@ def test_household_validation_measures_count_semp_once_and_exclude_gq() -> None: "person_id": [1, 2, 3, 4], "person_household_id": [1, 1, 2, 3], **{ - f"person_{group}_id": [1, 1, 2, 3] - for group in US_SCHEMA.group_entities + f"person_{group}_id": [1, 1, 2, 3] for group in US_SCHEMA.group_entities }, "employment_income_before_lsr": [100.0, 50.0, 10.0, 1000.0], # ACS SEMP routed wholly to the SSTB leaf after QBI reconciliation. @@ -1175,7 +1241,7 @@ def test_household_validation_measures_count_semp_once_and_exclude_gq() -> None: ) tables = {"household": households, "person": person} for group in US_SCHEMA.group_entities: - tables[group] = pd.DataFrame({f"{group}_id": ids}) + tables.setdefault(group, pd.DataFrame({f"{group}_id": ids})) frame = Frame( tables, US_SCHEMA, {"household": Weights(np.ones(3), WeightKind.DESIGN)} ) @@ -1249,7 +1315,11 @@ def test_acs_household_rows_have_their_own_state_budgets_in_the_loss() -> None: mapping = county.loss_row_mapping(specs) assert mapping.mapping_id == "us_acs_local_county.v2" keys = [mapping.concept_budget_key(spec) for spec in specs] - states = [key for key, spec in zip(keys, specs, strict=True) if spec.metadata["geography_level"] == "state"] + states = [ + key + for key, spec in zip(keys, specs, strict=True) + if spec.metadata["geography_level"] == "state" + ] assert len(set(states)) == 2 counties = { spec.metadata["state_fips"]: key diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py index af6c9ae3e4..b89f8b3b3f 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py @@ -41,6 +41,22 @@ def _county(): return _release().county_surface +@lru_cache +def _production(): + """The production county tests, for their ACS fact builders.""" + path = ( + paths_for("microcosm-build").tests + / "engine_free" + / "us" + / "test_us_acs_local_county_production.py" + ) + spec = importlib.util.spec_from_file_location("county_production_rows", path) + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + spec.loader.exec_module(module) + return module + + def _state_spec(measure="return_count", value=100.0, *, state="01", **metadata): variable = "count" if measure == "return_count" else measure name = f"state.{state}.{measure}" @@ -283,7 +299,11 @@ def test_state_county_requires_both_concepts_and_parents_in_every_state( ) -def test_kalawao_gap_still_refuses_the_county_surface_with_the_missing_code() -> None: +def test_kalawao_without_its_declared_host_still_refuses_with_the_missing_code() -> ( + None +): + # Kalawao's SOI cell is declared combined with Maui (15009); with Maui + # absent too there is no published cell to carry it. with pytest.raises(ValueError, match="15005"): _county().state_county_soi_surface( [ @@ -499,8 +519,10 @@ def test_reliability_report_counts_source_households_and_absent_counties() -> No assert cells["01005"]["distinct_source_households"] == 0 assert cells["01005"]["kish_ess"] == 0.0 assert cells["01005"]["kish_ess_rows"] == 0.0 - assert report["schema_version"] == 2 + assert report["schema_version"] == 3 assert report["grade_rule"]["provisional"] is True + assert cells["01001"]["status"] == "supported" + assert cells["01005"]["status"] == "no_support" assert "household_source_id" in report["ess_basis"]["kish_ess"] @@ -593,6 +615,11 @@ def test_county_hooks_materialize_a_fixture_and_preserve_configured_geography( "person_id": ids, "person_household_id": ids, **{f"person_{group}_id": ids for group in US_SCHEMA.group_entities}, + # The held-out ACS validation families read household earnings. + "employment_income_before_lsr": [30_000.0, 50_000.0, 0.0], + "self_employment_income_before_lsr": [0.0, 5_000.0, 0.0], + "sstb_self_employment_income_before_lsr": [0.0, 0.0, 0.0], + "farm_operations_income": [0.0, 0.0, 0.0], } ) tables = {"person": person} @@ -722,18 +749,28 @@ def fake_materialize(current, specs, **_kwargs): monkeypatch.setattr(module, "materialize_chunked", fake_materialize) county_reads = [] + # The SOI rows plus every ACS county table, in the pinned row shape; + # B01003 spans its two record sets and 01003 has no B19013 median. + acs_rows = _production()._acs_rows( + ["01001", "01003"], without_median=["01003"], b01003_group_1=["01003"] + ) + def fake_county_facts(path, **_kwargs): county_reads.append(path) - return SimpleNamespace( - rows=tuple( + rows = ( + *( _fact(code, measure, value) for measure in ("return_count", "adjusted_gross_income") for code, value in (("01001", 1.0), ("01003", 3.0)) ), + *acs_rows, + ) + return SimpleNamespace( + rows=rows, receipt=lambda: { "path": str(path), "facts_sha256": county_pin.facts_sha256, - "row_count": 4, + "row_count": len(rows), }, ) @@ -759,8 +796,27 @@ def feed_is_not_county_facts(*_args, **_kwargs): np.testing.assert_array_equal( loaded.table("household")["planning_region"], [1001, 1003, 1001] ) - assert matrix.shape == (9, 3) - assert len(registry) == 9 + # 2 SOI parents, 4 SOI county rows, 1 ACS households state parent and + # its 2 county rows, and 3 population rows; validation adds no row. + assert matrix.shape == (12, 3) + assert len(registry) == 12 + households_rows = [ + index + for index, record in enumerate(records) + if record.get("family") == "acs_households" + ] + assert len(households_rows) == 3 + np.testing.assert_array_equal( + matrix[households_rows].toarray().sum(axis=0), [2.0, 2.0, 2.0] + ) + assert identity["county_acs_households"]["new_state_targets"] == 1 + assert ( + identity["county_validation"]["design_sha256"] + == hashlib.sha256( + (args.checkpoint_dir / "county_validation.json").read_bytes() + ).hexdigest() + ) + assert identity["county_support"]["moves"] == 0 assert { record["county_column"] for record in records @@ -782,14 +838,24 @@ def feed_is_not_county_facts(*_args, **_kwargs): design_weights=design, weights=np.asarray([10.0, 75.0, 15.0]), target_loss_cap=1.0, + checkpoint_dir=args.checkpoint_dir, + identity=identity, ) - assert evidence["county_holdout"]["n_targets"] == 4 + # Four SOI and two ACS households county rows. + assert evidence["county_holdout"]["n_targets"] == 6 assert evidence["county_reliability"]["county_column"] == "planning_region" assert set(evidence["county_reliability"]["counties"]) == {"01001", "01003"} + assert evidence["county_validation"]["never_in_loss"] is True + for cell in evidence["county_reliability"]["counties"].values(): + assert cell["validation"]["n_families"] == 4 + assert cell["grade"] in {"A", "B", "C", "D"} county.write_reports(args.checkpoint_dir, evidence, identity=identity) written = json.loads((args.checkpoint_dir / "county_reliability.json").read_text()) assert written["county_column"] == "planning_region" assert written["counties"]["01001"]["distinct_source_households"] == 1 + assert (args.checkpoint_dir / "county_reliability.csv").read_text() == ( + county.reliability_csv(written) + ) def test_county_loss_weights_share_a_state_concept_budget_without_changing_other_rows() -> ( @@ -821,7 +887,7 @@ def test_county_loss_weights_share_a_state_concept_budget_without_changing_other ] mapping = county.loss_row_mapping(specs) weights = county.target_loss_weights(specs, {}) - assert mapping.mapping_id == "us_acs_local_county.v1" + assert mapping.mapping_id == "us_acs_local_county.v2" assert np.isfinite(weights).all() assert np.all(weights > 0) for parent in parents: @@ -937,6 +1003,13 @@ def test_county_refresh_recipe_round_trips_custom_geography_and_salt() -> None: assert metadata["county_facts"]["path"] not in recipe assert str(parsed.county_facts) == "" assert parsed.county_facts_sha256 == metadata["county_facts"]["facts_sha256"] + # No support receipt: the run moved no household, and its replay moves none. + assert parsed.county_min_support == 0 + supported = _county().refresh_recipe( + module.release_refresh_recipe("state_county"), + {**metadata, "county_support": {"households_per_county": 5}}, + ) + assert module._parse_args(shlex.split(supported)[3:]).county_min_support == 5 def test_county_run_metadata_adds_only_the_county_facts_receipt() -> None: diff --git a/tools/us_acs_local_county_surface.py b/tools/us_acs_local_county_surface.py index f6ba2908d6..276b16c21d 100644 --- a/tools/us_acs_local_county_surface.py +++ b/tools/us_acs_local_county_surface.py @@ -2823,9 +2823,10 @@ def refresh_recipe(command, materialize_rss): " --county-facts " f" --county-facts-sha256 {facts['facts_sha256']}" ) - support = materialize_rss.get("county_support") - if support: - command += f" --county-min-support {int(support['households_per_county'])}" + # A run without a support receipt moved no household (the step was off, + # or the run predates it), so its replay must turn the step off too. + support = materialize_rss.get("county_support") or {} + command += f" --county-min-support {int(support.get('households_per_county', 0))}" return command From 73275fc9dc2fac4317dc63820b8ef347a81cbb6b Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 14 Nov 2026 22:32:06 -0500 Subject: [PATCH 03/20] Document the production county rung (#922) The county rung doc now describes the trained ACS households family and its new state targets, the four held-out ACS validation families and their within-state share scoring, minimum county support, the declared Kalawao/Maui SOI cell, schema-3 reliability grades with the packaged CSV, the updated row and nnz estimates, and --county-min-support in the full-run command. Co-Authored-By: Claude Opus 5.5 --- .../922-us-county-rung-production.added.md | 1 + docs/us-acs-local-county-rung.md | 183 +++++++++++++++--- 2 files changed, 155 insertions(+), 29 deletions(-) create mode 100644 changelog.d/922-us-county-rung-production.added.md diff --git a/changelog.d/922-us-county-rung-production.added.md b/changelog.d/922-us-county-rung-production.added.md new file mode 100644 index 0000000000..8b9b404e18 --- /dev/null +++ b/changelog.d/922-us-county-rung-production.added.md @@ -0,0 +1 @@ +Make the ACS-local county rung (`--geographies state,cd,county --soi-mode state_county`) a full production calibration. It trains new ACS county household targets under new ACS state household targets, and scores four held-out ACS county families (earnings, households with earnings, approximate household income and its brackets) against a pro-rata baseline without changing the loss or the weights. It gives every supported county an A–D reliability grade in `county_reliability.json` and a packaged `county_reliability.csv`. `--county-min-support` (default 3) fills empty counties with same-PUMA households and records each move in `county_support.json`. Kalawao shares a declared SOI cell with Maui. diff --git a/docs/us-acs-local-county-rung.md b/docs/us-acs-local-county-rung.md index 5f82a51767..23e6df1f78 100644 --- a/docs/us-acs-local-county-rung.md +++ b/docs/us-acs-local-county-rung.md @@ -3,9 +3,11 @@ This implements microcosm#922 item 1: an optional county rung on the US ACS local release line. County logic lives in `tools/us_acs_local_county_surface.py`; the release driver and district helper -only call its hooks. The initial surface uses ladder population and public IRS -county shares. Future ACS county families can use the same county row, -holdout, and reliability interfaces. +only call its hooks. The production surface (`--geographies state,cd,county +--soi-mode state_county`) trains on ladder population, public IRS SOI county +shares and ACS county households, scores four held-out ACS county families, +gives every county a reliability grade, and moves a few same-PUMA households +into any county the staging frame leaves empty. ## Plan and invariants @@ -21,6 +23,15 @@ holdout, and reliability interfaces. Only an explicitly capped smoke may continue with missing support. - Holdout roles are deterministic given their salt. Scoring compares held-out county targets with state target times county population share. +- ACS household county rows sum to new ACS state household targets. The four + ACS validation families never enter the loss, the target registry, the + matrix or the weights. +- Minimum support never moves a household into a county that already has + one, never changes a household's state or PUMA, rewrites only the county + columns, moves exactly the configured number of households into each + county it fills (or none), and is deterministic. +- Kalawao (`15005`) shares one declared SOI cell with Maui (`15009`) for the + SOI families only; any other county missing from SOI is refused. - Reliability reports show supporting rows, distinct source households, Kish ESS, training and holdout error. At fixed error, increasing ESS cannot worsen the grade. Missing holdout evidence is explicit. @@ -94,8 +105,10 @@ are also reported and refused outside that smoke exception. The exception does not excuse missing source facts or mismatched county boundaries, and development samples cannot be packaged as releases. -Calibration writes schema-2 `county_reliability.json` next to its calibration -outputs and includes it in the packaged evidence. Each county reports its +Calibration writes schema-3 `county_reliability.json` and a flat +`county_reliability.csv` next to its calibration outputs, and packaging +publishes both (the CSV is refused unless it is the flattening of the bound +JSON report). Each county reports its supporting household rows, distinct `(household_spine, household_source_id)` pairs when available, and training/holdout target counts and mean/maximum absolute relative errors. `kish_ess` aggregates final weights by those source pairs within each @@ -109,8 +122,14 @@ remain explicit with zero support and grade `U`. For each target, relative error is `abs(estimate - target) / max(abs(target), 1)`. The grade uses the maximum error -across all of the county's training and holdout targets. The A/B/C/D thresholds -are **provisional** and recorded as such in the report. +across all of the county's training and holdout targets and, in a +`state_county` run, its four ACS validation errors (see below), so every +county with households has holdout evidence. Each cell records the +validation errors beside the pro-rata baseline errors, the error that set the +grade (`grade_error`, `grade_driver`) and a `status`: `supported`, +`minimum_support` (a county filled by the support step, graded normally) or +`no_support`. The A/B/C/D thresholds are **provisional** and recorded as such +in the report. | Grade | Minimum source Kish ESS | Maximum error | |---|---:|---:| @@ -122,11 +141,103 @@ are **provisional** and recorded as such in the report. Rules are evaluated from A through C, then D; a county without holdout evidence receives U even if its training fit is good, as does a county without source -identity. Thus a 10% block holdout can leave many counties ungraded when only -two concepts are available. At fixed error, raising ESS cannot worsen a grade. +identity. Without `--soi-mode state_county` there are no validation families, +so a 10% block holdout can leave many counties ungraded. With it, only a +county with no supporting household can be U. At fixed error, raising ESS cannot worsen a grade. These are report-only evidence grades; Kish ESS is not a county standard error or a guarantee of unbiased estimates. +## ACS county families (microcosm#922) + +A `state_county` run reads the ACS 2020-2024 5-year county tables from the +county facts rows already loaded for SOI (`surface.county_facts.rows`); it +never reopens `--feed` or the county facts file. Every family trains or scores +on estimates (`..._E`, `dimensions.statistic = "estimate"`) only. A margin of +error row (`..._M`) is carried beside its estimate in receipts when it exists +and is never required: B01003 has 3,014 counties with estimates only in record +set `group_0` and 130 counties with estimates and margins in `group_1`. Each +table must name every county exactly once; duplicates, negative or nonfinite +estimates, a statistic that does not match the measure ID, a layout county +that differs from the row geography, a Puerto Rico row (state `72`) and +incomplete or unexpected county inventories are refused by name. + +**Trained: `acs_households`.** Each state gets a new households target equal +to the sum of its counties' B11001_001E estimates, and each county a child +target that splits it by its public share, with largest-residual rounding so +the children sum exactly to the parent. These state rows are new state +targets: they move state household counts to ACS 5-year levels (the county +pilot, microcosm#1377, found the release 6.0% under ACS B11001 nationally). +The receipt records this as `new_state_targets`. The measure is 1 per +household in ACS's household universe, so ACS group-quarters records +(`TYPEHUGQ` 2 or 3) count as no household, as in the pilot +(`experiments/us-county-pilot-20261024/county_targets.py`, +`GROUP_QUARTERS_TYPES`). An ACS household without `TYPEHUGQ` 1, 2 or 3 is +refused, and so is a donor household that carries one. State rows each have +their own loss budget; county rows share one budget per state, as the SOI +county rows do (loss mapping `us_acs_local_county.v2`). + +**Held out: four validation families.** These are scored after calibration +and never enter the loss, the target registry, its digest, the matrix or the +weights: + +| Family | ACS estimates | Household measure | +|---|---|---| +| `acs_earnings` | B19061_001E | wages plus all self-employment, summed over the household's people | +| `acs_earning_households` | B19051_002E | households with nonzero earnings | +| `acs_household_income` (approximate) | B19025_001E | earnings plus the stored income inputs | +| `acs_household_income_distribution` (approximate) | B19001_002E-017E | households by approximate income bracket | + +Earnings sum `employment_income_before_lsr`, +`self_employment_income_before_lsr`, `sstb_self_employment_income_before_lsr` +and `farm_operations_income` on every record. The pilot zeroed the last two +on ACS records because staging then stacked donor draws on SEMP +(microcosm#1380); materialize now refuses such staging, and the gate it runs +lets an ACS row's SEMP sit wholly on the SSTB leaf, so summing all four counts +SEMP once. The income approximation adds the pilot's 22 other income inputs +that staging stores, plus `partnership_income` and `s_corp_income` on donor +records only; the receipt lists any input staging lacks. B19013 (median +household income) is a diagnostic only, never a target or a share; De Baca +County (`35011`) has no B19013 row and is listed as missing. + +Each county is scored as a within-state share: + +```text +target(c) = M_s * public(c) / sum of public over the state's counties +pro_rata(c) = M_s * ladder population(c) / state population +``` + +where `M_s` is the state's total of the household measure under the final +weights. The report gives each county's calibrated, design-weight and +pro-rata errors per family; the bracket family's graded error is the L1 +error over its 16 brackets divided by the county's bracket target total (at +least 1). Materialize +writes the public values (`county_validation.json`) and the household +measures (`county_validation_measures.npz`), and the run identity binds their +SHA256 under `county_validation`, so calibration scores exactly what +materialize saw. + +## Minimum county support (microcosm#922) + +A sampled staging frame can leave a small county with no household. Before +calibration, `--county-min-support K` (default 3, 0 turns it off, at most 50) +fills each such county with exactly K households from the same PUMA, or with +none if K eligible households are not available (status +`insufficient_eligible_donors`, which the support check then refuses as +before). PUMAs are tried in order of their population overlap with the county. +Within a PUMA, households are ranked by the SHA256 of the key +`acs-local-county-support-v1`, the county and the household ID, so the +choice does not depend on row order. An eligible household is in the household +universe, carries no `tract_geoid` or `block_geoid` (finalize gates compare +those with the county), has agreeing `county_fips` and `county_fips_2023` +values, and comes from a county that keeps at least K households after the +move. The step rewrites `county_fips` and `county_fips_2023` (whichever are +present) and nothing else: state, PUMA, congressional district, weights and +every other column stay as they were. Every move is recorded in +`county_support.json` under `minimum_support`, and the run identity binds the +moves' SHA256; the export stage re-applies the recorded moves to the reloaded +staging frame and refuses moves that no longer match. Filled counties are +graded normally with status `minimum_support`. + ## County facts input (microcosm#922) County facts do not come from `--feed`. They have their own pin, @@ -162,8 +273,9 @@ is loaded or any target row is materialized (the state administrative targets are compiled from `--feed` earlier). On the build machine the loader reads the pinned file in about 5 s and holds about 0.9 GB of rows, measured apart from importing the US runtime. The rows stay on the surface for the rest of the materialize stage; today only the -SOI county split reads them, in `prepare_run`. No county step reads `--feed`, -and nothing reopens the county facts file after `prepare_run`. The +SOI county split, the ACS households family and the validation design read +them, all in `prepare_run`. No county step reads `--feed`, and nothing reopens +the county facts file after `prepare_run`. The run identity and `materialize_rss.json` record the county facts receipt under `county_facts`. The refresh recipe carries both flags. It names placeholder files (``, like `--feed`'s) and never the build machine's path; @@ -171,17 +283,23 @@ the county digest it carries is the pinned one, while `--feed-sha256` stays a `` placeholder. A run without county facts records nothing new, so its run identity keeps its pre-county bytes. -The inspected Chronicle publisher inputs have two concrete blockers: +The inspected Chronicle publisher inputs have two concrete issues: - **Kalawao:** the SOI CSV has 3,143 counties and omits `15005` Kalawao County. PEP and five ACS tables carry all 3,144. B19013 has 3,143 (it has no De Baca County, `35011`), and B01003 reaches 3,144 only across its two record sets. - The IRS 2022 county users guide (`22incydocguide.docx`) says items with fewer - than 20 returns for a county were excluded, so Kalawao's SOI value is - missing, not zero. The guide does not say whether Kalawao's returns are - counted in another county's row. Until the rung declares a reviewed treatment (a - combined SOI cell {15005, 15009}, planned in the production county rung's own change), - a complete county SOI block still fails with that county named. + The [IRS 2022 county users guide](https://www.irs.gov/pub/irs-soi/22incydocguide.docx) + says items with fewer than 20 returns for a county were excluded, so + Kalawao's SOI value is missing, not zero. The guide does not say whether + Kalawao's returns are counted in another county's row. The rung therefore + declares one combined SOI cell, {15005, 15009} with Maui as host + (`DECLARED_SOI_COMBINED_CELLS`), for the SOI families only. The cell's + share is Maui's published value over the state's published county sum, and + its households are those in either county. Kalawao keeps its own PEP + population and ACS rows. The SOI receipt records the merge under + `combined_cells`, and each Maui row carries `state_county_cell_members` + `15005,15009`. Any other county missing from SOI, a declared cell whose + host is missing too, or a declaration across states is refused. - **Connecticut:** both packages use the nine planning-region codes `09110` through `09190`. The household county column and ladder must use those same boundaries. Select `--county-column county_fips_2023` when the parallel @@ -202,24 +320,28 @@ for `co-est2024-alldata.csv`. A full run needs the pinned main feed and its SHA256, the pinned county facts file and its SHA256, -a staging H5 and summary with household support in every county, a matching -county-boundary PUMA ladder, and resolution of the Kalawao SOI gap. The +a staging H5 and summary with household support in every county (after the +minimum support step), and a matching county-boundary PUMA ladder. The historical staging file was approximately 10.7 GB. The historical ladder was 446,791 bytes with SHA256 `39a2ab2abeab07a88362af7ab2940e0e1d50a297c919e4bbc6fb65bab51147d8`; that old digest is reference evidence, not an approved planning-region ladder. -At 3,144 counties and the current two SOI concepts, the county increment is -`3,144 × (population + returns + AGI) = 9,432` rows. With the pinned 4,380 state -administrative rows, 51 state population rows and 436 district population -rows, this is approximately **14,299 rows** including holdouts. The exact +At 3,144 counties, the county increment is 3,144 population rows, 3,143 rows +for each of the two SOI concepts (Kalawao shares Maui's cell), 3,144 ACS +household rows and 51 new ACS state household rows: **12,625 rows**. With the +pinned 4,380 state administrative rows, 51 state population rows and 436 +district population rows, this is approximately **17,492 rows** including +holdouts. The validation families add no row. The exact count depends on the pinned county facts and the ladder; an incomplete SOI county block is refused rather than reducing that count silently. For the historical 1,588,854-household staging population, each household can -contribute to at most three added county rows. That gives at most **4,766,562 -added nnz**, approximately **38.2 MB** of raw float32/int32 CSR data and indices, -plus about 38 KB of row pointers. Zero measures reduce nnz. Temporary matrix +contribute to at most four added county rows and one added state households +row. That gives at most **7,944,270 added nnz**, approximately **63.6 MB** of +raw float32/int32 CSR data and indices, plus about 50 KB of row pointers. The +validation measures file holds four float64 arrays per household, about +51 MB. Zero measures reduce nnz. Temporary matrix copies and Python overhead add memory, and existing state rows and the engine/frame dominate the total. Historical full materialization peaked at 75.6–93.9 GB; calibration was about 67.6 GB. Allocate **128 GiB** and start with @@ -233,7 +355,8 @@ check (`check_stage`) refuses a `state_county` materialize before any compute. A `--run` that skips that check stages its inputs first and is then refused by the release tool's own argument check. -Once the input blockers are resolved, set these paths and the two pinned +Once a staging frame and ladder on the county facts' boundaries (see +Connecticut above) are available, set these paths and the two pinned digests in the execution environment. This example uses the planning-region column; use `county_fips` only with a ladder matching that column. The following is documentation only and has not been executed: @@ -279,6 +402,7 @@ uv run python tools/build_us_acs_local_release.py \ --families snap,medicaid,soi --geographies state,cd,county \ --soi-mode state_county --county-column "$COUNTY_COLUMN" \ --county-holdout-fraction 0.1 --county-holdout-salt acs-local-county-v1 \ + --county-min-support 3 \ --county-target-loss-cap 10 --county-max-weight-ratio 5 \ --sample-fraction 1.0 --hh-chunk 20000 \ --checkpoint-dir "$COUNTY_RUN/checkpoints" \ @@ -290,7 +414,8 @@ uv run python tools/build_us_acs_local_release.py \ It does not publish. The command deliberately omits the partial-geography escape hatch. Run setup first with `uv sync --all-packages --extra us` in the intended numerical environment. The recorded refresh recipe preserves the -geographies, county column, holdout fraction and salt. +geographies, county column, holdout fraction and salt, and the minimum +support count (0 for a run that recorded no support receipt). The driver fixes `PERIOD = 2024` and has no `--year` switch. The command builds a **2024 base candidate**, not the contracted 2026/2027 files. Those years need From 8472d3cae7fdfdc76551ecd98b76b6dc340139b9 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 14 Nov 2026 22:35:42 -0500 Subject: [PATCH 04/20] Test that validation values change no loss input or weight (#922) The county smoke test's materialization becomes a fixture helper, and a new test materializes it twice with different public values for the four held-out ACS validation tables. The target registry, roles and matrix are byte-identical, only the validation design digest differs, and the solved weights are equal. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_acs_local_county_surface.py | 96 ++++++++++++++++++- 1 file changed, 91 insertions(+), 5 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py index b89f8b3b3f..a277ea4fc1 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py @@ -598,10 +598,8 @@ def test_missing_source_identity_cannot_produce_a_row_based_reliability_grade( @pytest.mark.skipif( importlib.util.find_spec("tables") is None, reason="requires pytables" ) -def test_county_hooks_materialize_a_fixture_and_preserve_configured_geography( - monkeypatch, tmp_path -) -> None: - """A three-household smoke exercises real sparse checkpoints, without an engine.""" +def _materialize_county_fixture(monkeypatch, tmp_path, *, acs_values=None): + """Materialize a three-household state_county fixture, with a fake engine.""" from microcosm.build import ledger_artifact from microcosm.build.us_runtime import county_facts as county_facts_module from microcosm.calibrate import TargetRegistry @@ -752,7 +750,10 @@ def fake_materialize(current, specs, **_kwargs): # The SOI rows plus every ACS county table, in the pinned row shape; # B01003 spans its two record sets and 01003 has no B19013 median. acs_rows = _production()._acs_rows( - ["01001", "01003"], without_median=["01003"], b01003_group_1=["01003"] + ["01001", "01003"], + values=acs_values, + without_median=["01003"], + b01003_group_1=["01003"], ) def fake_county_facts(path, **_kwargs): @@ -782,6 +783,27 @@ def feed_is_not_county_facts(*_args, **_kwargs): ledger_artifact, "load_ledger_consumer_artifact", feed_is_not_county_facts ) module.do_materialize(args) + return SimpleNamespace( + module=module, + county=county, + args=args, + frame=frame, + parents=parents, + seen=seen, + county_reads=county_reads, + county_facts_file=county_facts_file, + county_pin=county_pin, + ) + + +def test_county_hooks_materialize_a_fixture_and_preserve_configured_geography( + monkeypatch, tmp_path +) -> None: + """A three-household smoke exercises real sparse checkpoints, without an engine.""" + run = _materialize_county_fixture(monkeypatch, tmp_path) + module, county, args = run.module, run.county, run.args + parents, seen, county_reads = run.parents, run.seen, run.county_reads + county_facts_file, county_pin = run.county_facts_file, run.county_pin assert seen == parents # Read exactly once, from the resolved --county-facts path; attach_surface # reuses what prepare_run loaded. @@ -858,6 +880,70 @@ def feed_is_not_county_facts(*_args, **_kwargs): ) +def test_validation_values_change_no_loss_input_and_no_weight( + monkeypatch, tmp_path +) -> None: + """The held-out ACS families never reach the registry, roles, matrix or solve. + + Two materializations differ only in the four validation tables' public + values (earnings, households with earnings, household income and its + brackets). Every loss input is byte-identical and the solved weights are + equal; only the validation design file differs. + """ + production = _production() + runs = [] + for scale in (1, 7): + values = {} + for code in ("01001", "01003"): + data = production._county_values(code) + values[code] = { + **data, + "earning_households": data["earning_households"] // scale, + "earnings": data["earnings"] * scale, + "income": data["income"] * scale + scale, + "brackets": data["brackets"][::-1] if scale > 1 else data["brackets"], + } + run = _materialize_county_fixture( + monkeypatch, tmp_path / f"scale_{scale}", acs_values=values + ) + identity = json.loads( + (run.args.checkpoint_dir / "run_identity.json").read_text() + ) + runs.append((run, identity)) + (first, first_identity), (second, second_identity) = runs + module = first.module + for name in ("target_registry.json", module.TARGET_ROLES_FILENAME): + assert (first.args.checkpoint_dir / name).read_bytes() == ( + second.args.checkpoint_dir / name + ).read_bytes() + for key in ("target_registry_sha256", "target_roles_sha256", "target_matrix"): + assert first_identity[key] == second_identity[key] + assert ( + first_identity["county_validation"]["design_sha256"] + != second_identity["county_validation"]["design_sha256"] + ) + weights = [] + for run, identity in runs: + frame, design, registry, roles, matrix = module.load_checkpoint_surface( + run.args.checkpoint_dir, identity + ) + targets = module.cd_surface.calibration_target_set( + roles, matrix, frame.n("household"), specs=registry.specs + ) + result, _done = module.calibrate_surface( + frame, + targets, + epochs=20, + epoch_batch=10, + max_weight_ratio=5.0, + target_loss_cap=10.0, + l2_lambda=0.0, + seed=0, + ) + weights.append(np.asarray(result.weights)) + np.testing.assert_array_equal(weights[0], weights[1]) + + def test_county_loss_weights_share_a_state_concept_budget_without_changing_other_rows() -> ( None ): From a5d54747122995514714c92cdbffad56ae3c6d92 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 14 Nov 2026 22:40:31 -0500 Subject: [PATCH 05/20] Test Connecticut planning regions as county equivalents (#922) The ACS households family gives the nine planning regions 09110-09190 one state 09 parent and nine rows that partition it, and a legacy Connecticut county code outside the planning-region inventory is refused by name. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_acs_local_county_production.py | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py index 8a1f167678..cbb79b2342 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py @@ -430,6 +430,35 @@ def test_acs_household_specs_share_one_label_per_geography_with_other_targets() TargetRegistry((*county_population, *acs.specs, _state_spec()), country="us") +def test_connecticut_planning_regions_are_county_equivalents() -> None: + county = _county() + regions = [f"091{index}0" for index in range(1, 10)] + populations = {int(code): 100.0 + index for index, code in enumerate(regions)} + surface = county.acs_household_surface(_acs_rows(regions), populations) + (parent,) = [ + spec for spec in surface.specs if spec.metadata["geography_level"] == "state" + ] + assert parent.metadata["state_fips"] == "09" + children = [spec for spec in surface.specs if spec is not parent] + assert [child.metadata["county_fips"] for child in children] == regions + households = _households( + {"county_fips": code, "state_fips": 9, "household_spine": "asec_puf"} + for code in regions + ) + rows = county.acs_household_rows(households, surface.specs).toarray() + at = surface.specs.index(parent) + child_rows = rows[[index for index in range(len(rows)) if index != at]] + np.testing.assert_array_equal(child_rows.sum(axis=0), rows[at]) + np.testing.assert_array_equal(child_rows, np.eye(9)) + # A legacy Connecticut county code is not in the planning-region inventory. + with pytest.raises(ValueError, match="09001"): + county.acs_county_values( + _acs_rows([*regions, "09001"]), + ["B11001_001E"], + required=populations, + ) + + def _households(rows): frame = pd.DataFrame(rows) frame["household_id"] = np.arange(1, len(frame) + 1) From c288341fe9374a26d6396581b89fe77655112a26 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 14 Nov 2026 22:41:39 -0500 Subject: [PATCH 06/20] Grade a county with no household U even when a combined cell covers it (#922) Review finding: in a capped smoke with Kalawao left empty and Hawaii's SOI block held out, Kalawao took grade D from Maui's error through their combined SOI cell. A county without household support now always grades U; its training and holdout counts stay in the cell for information. The doc now says Kalawao keeps its own ladder population row (not PEP) and ACS rows. Co-Authored-By: Claude Opus 5.5 --- docs/us-acs-local-county-rung.md | 4 ++-- .../us/test_us_acs_local_county_production.py | 14 ++++++++++++++ tools/us_acs_local_county_surface.py | 4 +++- 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/docs/us-acs-local-county-rung.md b/docs/us-acs-local-county-rung.md index 23e6df1f78..db911c6040 100644 --- a/docs/us-acs-local-county-rung.md +++ b/docs/us-acs-local-county-rung.md @@ -295,8 +295,8 @@ The inspected Chronicle publisher inputs have two concrete issues: declares one combined SOI cell, {15005, 15009} with Maui as host (`DECLARED_SOI_COMBINED_CELLS`), for the SOI families only. The cell's share is Maui's published value over the state's published county sum, and - its households are those in either county. Kalawao keeps its own PEP - population and ACS rows. The SOI receipt records the merge under + its households are those in either county. Kalawao keeps its own + population row (from the ladder, like every county's) and ACS rows. The SOI receipt records the merge under `combined_cells`, and each Maui row carries `state_county_cell_members` `15005,15009`. Any other county missing from SOI, a declared cell whose host is missing too, or a declaration across states is refused. diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py index cbb79b2342..e590fa0912 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py @@ -1224,6 +1224,20 @@ def test_combined_soi_cell_errors_count_toward_both_member_counties() -> None: assert report["counties"][code]["holdout"]["max_abs_rel_error"] == ( pytest.approx(0.2) ) + assert report["counties"][code]["grade"] == "D" + # With no Kalawao household, Kalawao is U: Maui's error is not its own. + only_maui = county.reliability_report( + households.iloc[[1]], + records, + sparse.csr_array(np.asarray([[1.0]])), + final_weights=np.asarray([8.0]), + county_populations={15005: 80.0, 15009: 160.0}, + ) + kalawao = only_maui["counties"]["15005"] + assert kalawao["status"] == "no_support" + assert kalawao["holdout"]["n_targets"] == 1 + assert (kalawao["grade"], kalawao["grade_error"]) == ("U", None) + assert only_maui["counties"]["15009"]["grade"] == "D" @_SETTINGS diff --git a/tools/us_acs_local_county_surface.py b/tools/us_acs_local_county_surface.py index 276b16c21d..48876f35c2 100644 --- a/tools/us_acs_local_county_surface.py +++ b/tools/us_acs_local_county_surface.py @@ -1762,7 +1762,9 @@ def reliability_report( (float(entry["abs_rel_error"]), f"validation:{name}") for name, entry in graded.items() ] - evidence = cell["holdout"]["n_targets"] > 0 or bool(graded) + # A county without household support is U: a combined SOI cell's + # rows (Kalawao's in Maui's) carry another county's error. + evidence = len(rows) and (cell["holdout"]["n_targets"] > 0 or bool(graded)) if evidence and candidates: error, driver = max(candidates, key=lambda item: (item[0], item[1])) else: From dc472fd9d724fa804d4dcd5ef2d81ccb8b1cd974 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 14 Nov 2026 22:50:23 -0500 Subject: [PATCH 07/20] Count only household-universe records as county support (#922) Review findings on minimum county support: - check_support rebuilt a set of every household's county once per county (3,144 times over about 1.6M codes in a full build). It now asks unsupported_counties once. - The donor floor counted ACS group-quarters records, so a move could take a county's only housing unit and leave its acs_households row empty, turning a build that passed into a refusal. Support and the donor floor now count only households in the household universe, so a county with group-quarters records alone is filled like an empty one. The support invariants property now defines support the same way and checks each county's receipt; a new example covers both cases. Co-Authored-By: Claude Opus 5.5 --- docs/us-acs-local-county-rung.md | 8 ++- .../us/test_us_acs_local_county_production.py | 65 +++++++++++++++++-- tools/us_acs_local_county_surface.py | 56 +++++++++++----- 3 files changed, 102 insertions(+), 27 deletions(-) diff --git a/docs/us-acs-local-county-rung.md b/docs/us-acs-local-county-rung.md index db911c6040..d98e734274 100644 --- a/docs/us-acs-local-county-rung.md +++ b/docs/us-acs-local-county-rung.md @@ -218,7 +218,9 @@ materialize saw. ## Minimum county support (microcosm#922) -A sampled staging frame can leave a small county with no household. Before +A sampled staging frame can leave a small county with no household, or with +ACS group-quarters records only, which support no households-family target. +Only households in the household universe count as support. Before calibration, `--county-min-support K` (default 3, 0 turns it off, at most 50) fills each such county with exactly K households from the same PUMA, or with none if K eligible households are not available (status @@ -229,8 +231,8 @@ Within a PUMA, households are ranked by the SHA256 of the key choice does not depend on row order. An eligible household is in the household universe, carries no `tract_geoid` or `block_geoid` (finalize gates compare those with the county), has agreeing `county_fips` and `county_fips_2023` -values, and comes from a county that keeps at least K households after the -move. The step rewrites `county_fips` and `county_fips_2023` (whichever are +values, and comes from a county that keeps at least K households in the +household universe after the move. The step rewrites `county_fips` and `county_fips_2023` (whichever are present) and nothing else: state, PUMA, congressional district, weights and every other column stay as they were. Every move is recorded in `county_support.json` under `minimum_support`, and the run identity binds the diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py index e590fa0912..f67725fc83 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py @@ -800,6 +800,46 @@ def test_minimum_support_is_all_or_nothing_and_names_the_county() -> None: assert receipt["counties"]["01003"]["moved"] == 0 +def test_group_quarters_records_are_not_county_support() -> None: + county = _county() + counties = [1001, 1003, 1003, 1003, 1003, 1007, 1007] + kinds = [1.0, 2.0, 1.0, 2.0, 2.0, 3.0, 2.0] + households = _support_households([(100001, code) for code in counties]) + households["household_spine"] = "acs_2024_1yr" + households["TYPEHUGQ"] = kinds + # 01003 has one housing unit beside three group-quarters records; 01007 + # has group quarters only; 01005 has nothing. + populations = {1001: 10.0, 1003: 40.0, 1005: 5.0, 1007: 8.0, 1009: 30.0} + overlaps = county.puma_overlaps( + [100001] * 5, sorted(populations), [10.0, 40.0, 5.0, 8.0, 30.0] + ) + moves, receipt = county.plan_minimum_support( + households, populations, overlaps, per_county=1 + ) + assert receipt["unsupported_before"] == ["01005", "01007"] + # 01003's lone housing unit would leave it with group quarters only. + assert moves == [] + assert {entry["status"] for entry in receipt["counties"].values()} == { + "insufficient_eligible_donors" + } + richer = pd.concat( + [ + households, + _support_households([(100001, 1009)] * 3).assign( + household_id=[2001, 2002, 2003], + household_spine="acs_2024_1yr", + TYPEHUGQ=1.0, + ), + ], + ignore_index=True, + ) + moves, receipt = county.plan_minimum_support( + richer, populations, overlaps, per_county=1 + ) + assert {move["to_county"] for move in moves} == {"01005", "01007"} + assert {move["from_county"] for move in moves} == {"01009"} + + def test_a_fully_supported_frame_is_returned_unchanged() -> None: county = _county() households = _support_households([(100001, 1001)] * 3 + [(100001, 1003)] * 3) @@ -860,7 +900,10 @@ def test_minimum_support_invariants(layout) -> None: households, populations, overlaps, per_county=per_county ) before = households.set_index("household_id") - supported = set(before["county_fips"].astype(int)) + # Support is a household in the household universe: ACS group quarters + # (TYPEHUGQ 2 here) support no households-family target. + in_universe = households["TYPEHUGQ"].ne(2.0) + supported = set(households.loc[in_universe, "county_fips"].astype(int)) destinations = {} for move in moves: destination = int(move["to_county"]) @@ -876,13 +919,23 @@ def test_minimum_support_invariants(layout) -> None: assert pd.isna(source["tract_geoid"]) assert source["county_fips"] == source["county_fips_2023"] assert source["TYPEHUGQ"] != 2.0 - # The count moved into a county is exact. + # The count moved into a county is exact, and the receipt says so. assert set(destinations.values()) <= {per_county} + for code, entry in receipt["counties"].items(): + assert entry["moved"] == destinations.get(int(code), 0) + assert entry["status"] == ( + "moved" if entry["moved"] else "insufficient_eligible_donors" + ) + assert {int(code) for code in receipt["unsupported_before"]} == { + code + for code, population in populations.items() + if population > 0 and code not in supported + } after = county.apply_support_moves(households, moves) - counts = after["county_fips"].astype(int).value_counts() - for code in supported: - if code in {int(move["from_county"]) for move in moves}: - assert counts[code] >= per_county + # Donor counties keep at least per_county supporting households. + counts = after.loc[in_universe, "county_fips"].astype(int).value_counts() + for code in {int(move["from_county"]) for move in moves}: + assert counts[code] >= per_county for column in households.columns: if column not in {"county_fips", "county_fips_2023"}: pd.testing.assert_series_equal(after[column], households[column]) diff --git a/tools/us_acs_local_county_surface.py b/tools/us_acs_local_county_surface.py index 48876f35c2..82f488610e 100644 --- a/tools/us_acs_local_county_surface.py +++ b/tools/us_acs_local_county_surface.py @@ -1965,6 +1965,32 @@ def _moves_digest(moves): ).hexdigest() +def support_universe(households): + """Households that count as county support: those in the household universe. + + An ACS group-quarters record supports no households-family target, so it + neither makes a county supported nor counts toward a donor county's floor. + Without the columns that identify group quarters every household counts. + """ + if "household_spine" in households.columns and ( + HOUSEHOLD_KIND_COLUMN in households.columns + or not (households["household_spine"].astype(str) == ACS_SPINE).any() + ): + return household_universe(households) > 0 + return np.ones(len(households), dtype=bool) + + +def unsupported_counties(households, county_populations, *, county_column): + """Counties with positive ladder population and no supporting household.""" + codes = county_codes(households, county_column=county_column) + present = {int(code) for code in np.unique(codes[support_universe(households)])} + return sorted( + int(code) + for code, population in county_populations.items() + if float(population) > 0 and int(code) not in present + ) + + def plan_minimum_support( households, county_populations, @@ -1977,7 +2003,7 @@ def plan_minimum_support( """Choose ``per_county`` donor households for each unsupported county. A county is unsupported when its ladder population is positive and no - household names it. Its donors come from the PUMA that overlaps it most + household in the household universe names it (:func:`support_universe`). Its donors come from the PUMA that overlaps it most (then the next, by ladder population), ordered by :func:`support_rank` of ``(key, county, household_id)``. A donor must be in the household universe (not ACS group quarters), carry no tract or @@ -1993,11 +2019,9 @@ def plan_minimum_support( ids = households["household_id"].to_numpy() if len(pd.unique(ids)) != len(ids): raise ValueError("Minimum county support needs unique household ids.") - present = {int(code) for code in np.unique(codes)} - unsupported = sorted( - int(code) - for code, population in county_populations.items() - if float(population) > 0 and int(code) not in present + universe = support_universe(households) + unsupported = unsupported_counties( + households, county_populations, county_column=county_column ) receipt = { "households_per_county": int(per_county), @@ -2009,7 +2033,7 @@ def plan_minimum_support( "same PUMA as the county (largest ladder overlap first); not ACS " "group quarters; no tract_geoid or block_geoid; county columns " "agree; the donor county keeps at least households_per_county " - "households" + "households in the household universe" ), "counties": {}, "moves": [], @@ -2020,12 +2044,7 @@ def plan_minimum_support( pumas = _household_pumas(households) if np.any(pumas // 100_000 != codes // 1000): raise ValueError("Household PUMA and county disagree on the state.") - eligible = np.ones(len(households), dtype=bool) - if "household_spine" in households.columns and ( - HOUSEHOLD_KIND_COLUMN in households.columns - or not (households["household_spine"].astype(str) == ACS_SPINE).any() - ): - eligible &= household_universe(households) > 0 + eligible = universe.copy() for column in COUNTY_DETERMINING_LOCATION_COLUMNS: if column in households.columns: eligible &= _blank(households[column]) @@ -2043,8 +2062,10 @@ def plan_minimum_support( if column in households.columns ] by_puma = _county_groups(pumas) + # The donor floor counts supporting households only, so a move never + # leaves a donor county with group-quarters records alone. counts = defaultdict(int) - for code in codes: + for code in codes[universe]: counts[int(code)] += 1 moved = np.zeros(len(households), dtype=bool) moves = [] @@ -2388,11 +2409,10 @@ def check_support(frame, populations, args): codes = county_codes(households, county_column=column) unknown = sorted(set(codes) - set(populations["county"])) support = None - needed = any( - float(population) > 0 and int(code) not in set(codes.tolist()) - for code, population in populations["county"].items() - ) if per_county > 0 and not unknown: + needed = unsupported_counties( + households, populations["county"], county_column=column + ) overlaps = county_puma_overlaps(args.ladder) if needed else {} moves, support = plan_minimum_support( households, From 25175640c25ea1ff1187c04de645a436d356954f Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 14 Nov 2026 22:51:37 -0500 Subject: [PATCH 08/20] Refuse group-quarters-only counties before the engine pass; document block_v1 (#922) Review findings: in a state_county run a county whose staged households are all ACS group quarters has an empty acs_households row, which attach_surface refused only after the engine pass. check_support now counts household-universe records as support in a state_county run, so that county is filled by minimum support or refused before any measure is built. Other runs keep counting every household. The doc now says minimum support fills nothing on block_v1 staging, where every household carries block and tract geoids; filling counties there needs a block redrawn inside the PUMA and county, which is not implemented. Co-Authored-By: Claude Opus 5.5 --- docs/us-acs-local-county-rung.md | 11 ++++++ .../us/test_us_acs_local_county_production.py | 35 +++++++++++++++++++ tools/us_acs_local_county_surface.py | 14 ++++++-- 3 files changed, 58 insertions(+), 2 deletions(-) diff --git a/docs/us-acs-local-county-rung.md b/docs/us-acs-local-county-rung.md index d98e734274..6b9cb8d04e 100644 --- a/docs/us-acs-local-county-rung.md +++ b/docs/us-acs-local-county-rung.md @@ -240,6 +240,17 @@ moves' SHA256; the export stage re-applies the recorded moves to the reloaded staging frame and refuses moves that no longer match. Filled counties are graded normally with status `minimum_support`. +The step is for legacy-location staging. Under `--location-rule block_v1` +([US household location](us-location-v1.md)) every household carries a +`block_geoid` and `tract_geoid`, so no household is eligible: an empty county +stays unsupported (status `insufficient_eligible_donors`) and a full build +refuses as before. Filling counties there needs a block redrawn inside the +PUMA and county, with every block-derived geography (tract, both county +columns, place, legislative districts, CBSA and congressional districts) +looked up again; that is not implemented. The receipt's +`location_columns_present` names the columns that made households +ineligible. + ## County facts input (microcosm#922) County facts do not come from `--feed`. They have their own pin, diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py index f67725fc83..d524266d3c 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py @@ -840,6 +840,41 @@ def test_group_quarters_records_are_not_county_support() -> None: assert {move["from_county"] for move in moves} == {"01009"} +@pytest.mark.parametrize("soi_mode", ["state_county", "state"]) +def test_a_state_county_run_refuses_group_quarters_only_counties_before_the_engine( + tmp_path, soi_mode +) -> None: + county = _county() + households = pd.DataFrame( + { + "household_id": [1, 2], + "county_fips": ["01001", "01003"], + "state_fips": [1, 1], + "household_spine": ["acs_2024_1yr", "acs_2024_1yr"], + "TYPEHUGQ": [1.0, 3.0], + } + ) + frame = SimpleNamespace(table=lambda _entity: households) + args = SimpleNamespace( + checkpoint_dir=tmp_path, + county_column="county_fips", + county_min_support=0, + soi_mode=soi_mode, + allow_partial_geography=False, + sample_fraction=1.0, + ) + populations = {"county": {1001: 10.0, 1003: 20.0}} + if soi_mode == "state_county": + with pytest.raises(SystemExit, match="01003"): + county.check_support(frame, populations, args) + else: + assert county.check_support(frame, populations, args) is frame + report = json.loads((tmp_path / county.SUPPORT_FILENAME).read_text()) + strict = soi_mode == "state_county" + assert report["unsupported_counties"] == (["01003"] if strict else []) + assert report["counties"]["01003"]["supporting_households"] == (0 if strict else 1) + + def test_a_fully_supported_frame_is_returned_unchanged() -> None: county = _county() households = _support_households([(100001, 1001)] * 3 + [(100001, 1003)] * 3) diff --git a/tools/us_acs_local_county_surface.py b/tools/us_acs_local_county_surface.py index 82f488610e..adaa88722e 100644 --- a/tools/us_acs_local_county_surface.py +++ b/tools/us_acs_local_county_surface.py @@ -2442,9 +2442,14 @@ def check_support(frame, populations, args): "moved_counties": support.get("moved_counties", []), "rewritten_columns": support["rewritten_columns"], } - missing = sorted(set(populations["county"]) - set(codes)) + # A state_county run trains an ACS households row for every county, which + # only household-universe records support; refuse a county with group + # quarters alone here, before the engine pass, not after it. + strict = getattr(args, "soi_mode", None) == SOI_MODE + supporting = codes[support_universe(households)] if strict else codes + missing = sorted(set(populations["county"]) - set(supporting)) counts = defaultdict(int) - for code in codes: + for code in supporting: counts[int(code)] += 1 report = { "county_column": column, @@ -2455,6 +2460,11 @@ def check_support(frame, populations, args): "unsupported_counties": [f"{int(code):05d}" for code in missing], "unknown_counties": [f"{int(code):05d}" for code in unknown], } + if strict: + report["support_basis"] = ( + "households in the household universe (ACS group-quarters records " + "support no acs_households target)" + ) if support is not None: report["minimum_support"] = support (args.checkpoint_dir / SUPPORT_FILENAME).write_text(json.dumps(report, indent=2)) From 02855f77a6cc0f60c2646535fb5bf8365eaac7a9 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 14 Nov 2026 22:52:27 -0500 Subject: [PATCH 09/20] Write open B19001 bracket ends as null in the validation design (#922) Materialize writes county_validation.json with allow_nan=False, and the first and last B19001 brackets have infinite bounds, so every state_county materialize refused. The county smoke test caught it; the design's bracket list now writes an open end as null, and the production tests check that the design and the validation scores are strict JSON. Co-Authored-By: Claude Opus 5.5 --- .../engine_free/us/test_us_acs_local_county_production.py | 5 +++++ tools/us_acs_local_county_surface.py | 8 +++++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py index d524266d3c..dd3c4cc1a3 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py @@ -324,6 +324,10 @@ def test_median_income_is_a_diagnostic_and_a_missing_county_is_listed() -> None: _acs_rows(counties, without_median=["35011"]), {35001: 10.0, 35011: 5.0} ) assert design["median_income_diagnostic"]["missing"] == ["35011"] + # Materialize writes the design as strict JSON (open bracket ends: null). + assert ( + json.loads(json.dumps(design, allow_nan=False))["brackets"][0]["lower"] is None + ) measures = { measure for family in design["families"].values() @@ -1147,6 +1151,7 @@ def test_validation_targets_redistribute_each_state_total_by_public_shares() -> cap=10.0, ) assert result["never_in_loss"] is True + json.dumps(result, allow_nan=False) for family in county.VALIDATION_FAMILIES: if family.household_measure == "income_bracket": continue diff --git a/tools/us_acs_local_county_surface.py b/tools/us_acs_local_county_surface.py index adaa88722e..28fb92fd01 100644 --- a/tools/us_acs_local_county_surface.py +++ b/tools/us_acs_local_county_surface.py @@ -1132,8 +1132,14 @@ def county_validation_design(facts, county_populations): } for family in VALIDATION_FAMILIES }, + # [lower, upper) dollars; JSON has no infinity, so an open end is null. "brackets": [ - {"measure": measure, "income_range": label, "lower": lower, "upper": upper} + { + "measure": measure, + "income_range": label, + "lower": None if math.isinf(lower) else lower, + "upper": None if math.isinf(upper) else upper, + } for measure, label, lower, upper in B19001_BRACKETS ], "median_income_diagnostic": { From f76393660cc7c39a9ab34604b4bab2dccfe37e4c Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 14 Nov 2026 23:00:46 -0500 Subject: [PATCH 10/20] Count donor partnership SE earnings in the validation earnings (#922) Review finding: the earnings and households-with-earnings families omitted partnership_self_employment_net_earnings on donor records, though ACS SEMP (B19061, B19051) counts partnership self-employment income. The pilot left it out because it built income as earnings plus partnership_income, which already holds most of it. Earnings now add it on donor records, and the income approximation starts from the four base leaves, so neither measure counts it twice. The receipt lists the donor earnings column when staging stores it. Co-Authored-By: Claude Opus 5.5 --- docs/us-acs-local-county-rung.md | 10 ++++--- .../us/test_us_acs_local_county_production.py | 12 +++++++-- tools/us_acs_local_county_surface.py | 26 ++++++++++++++++++- 3 files changed, 42 insertions(+), 6 deletions(-) diff --git a/docs/us-acs-local-county-rung.md b/docs/us-acs-local-county-rung.md index 6b9cb8d04e..19a35df892 100644 --- a/docs/us-acs-local-county-rung.md +++ b/docs/us-acs-local-county-rung.md @@ -193,9 +193,13 @@ and `farm_operations_income` on every record. The pilot zeroed the last two on ACS records because staging then stacked donor draws on SEMP (microcosm#1380); materialize now refuses such staging, and the gate it runs lets an ACS row's SEMP sit wholly on the SSTB leaf, so summing all four counts -SEMP once. The income approximation adds the pilot's 22 other income inputs -that staging stores, plus `partnership_income` and `s_corp_income` on donor -records only; the receipt lists any input staging lacks. B19013 (median +SEMP once. Donor records also add `partnership_self_employment_net_earnings`, +which ACS SEMP counts (the gate keeps it zero on ACS rows). The income +approximation starts from the four leaves, not from earnings, and adds the +pilot's 22 other income inputs that staging stores plus `partnership_income` +and `s_corp_income` on donor records only, so donor partnership earnings, +mostly inside `partnership_income`, are not counted twice. The receipt lists +any input staging lacks. B19013 (median household income) is a diagnostic only, never a target or a share; De Baca County (`35011`) has no B19013 row and is listed as missing. diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py index dd3c4cc1a3..faefa3044d 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py @@ -1373,6 +1373,9 @@ def test_household_validation_measures_count_semp_once_and_exclude_gq() -> None: "farm_operations_income": [0.0, 0.0, 0.0, 7.0], "taxable_interest_income": [1.0, 0.0, 0.0, 2.0], "partnership_income": [99.0, 0.0, 0.0, 11.0], + # Donor-only earnings; zero on ACS rows after the identity gate, + # and ignored there even when not. + "partnership_self_employment_net_earnings": [40.0, 0.0, 0.0, 9.0], } ) tables = {"household": households, "person": person} @@ -1382,11 +1385,16 @@ def test_household_validation_measures_count_semp_once_and_exclude_gq() -> None: tables, US_SCHEMA, {"household": Weights(np.ones(3), WeightKind.DESIGN)} ) arrays, report = county.household_validation_measures(frame) - np.testing.assert_array_equal(arrays["earnings"], [180.0, 10.0, 1032.0]) - # Partnership income is donor-only in the income approximation. + # The donor household adds its partnership SE earnings (9) to earnings. + np.testing.assert_array_equal(arrays["earnings"], [180.0, 10.0, 1041.0]) + # Income starts from the four leaves, then adds the carried inputs and + # donor-only partnership income, which holds the partnership earnings. np.testing.assert_array_equal( arrays["household_income_approx"], [181.0, 10.0, 1045.0] ) + assert report["donor_only_earnings_columns_carried"] == [ + "partnership_self_employment_net_earnings" + ] np.testing.assert_array_equal(arrays["in_household_universe"], [1.0, 0.0, 1.0]) assert report["group_quarters_households"] == 1 with pytest.raises(ValueError, match="earnings inputs"): diff --git a/tools/us_acs_local_county_surface.py b/tools/us_acs_local_county_surface.py index 28fb92fd01..f0af7af6fe 100644 --- a/tools/us_acs_local_county_surface.py +++ b/tools/us_acs_local_county_surface.py @@ -629,6 +629,14 @@ def split_state_rows( "sstb_self_employment_income_before_lsr", "farm_operations_income", ) +#: Partnership self-employment earnings, imputed on donor records from PUF +#: partnership SE income; ACS SEMP counts them, and the identity gate keeps +#: them zero on ACS rows. They count toward earnings on donor records when +#: staging stores them. The pilot left them out because it built income as +#: earnings plus ``partnership_income``, which already holds most of them; +#: here income is built from :data:`EARNINGS_COLUMNS` instead, so neither +#: measure counts them twice. +DONOR_PARTNERSHIP_EARNINGS_COLUMNS = ("partnership_self_employment_net_earnings",) #: The pilot's other person-level income inputs, carried when staging stores #: them, so the household-income concept of ACS B19025/B19001 can be #: approximated. Absent ones are listed in the receipt. @@ -1204,7 +1212,18 @@ def summed(column, *, donor_only=False): part = summed(column) earnings += part components[column] = float((weights * part).sum()) + # Income starts from the base leaves: donor partnership SE earnings are + # mostly inside partnership_income, which the income approximation adds. income = earnings.copy() + donor_earnings = [ + column + for column in DONOR_PARTNERSHIP_EARNINGS_COLUMNS + if column in person.columns + ] + for column in donor_earnings: + part = summed(column, donor_only=True) + earnings += part + components[column] = float((weights * part).sum()) carried = [column for column in OTHER_INCOME_COLUMNS if column in person.columns] donor_carried = [ column for column in DONOR_ONLY_OTHER_INCOME_COLUMNS if column in person.columns @@ -1221,7 +1240,12 @@ def summed(column, *, donor_only=False): report = { "earnings_columns": list(EARNINGS_COLUMNS), "earnings_rule": "all four leaves on every record; the ACS " - "self-employment identity gate guarantees SEMP once (microcosm#1380)", + "self-employment identity gate guarantees SEMP once (microcosm#1380); " + "partnership SE earnings on donor records", + "donor_only_earnings_columns_carried": donor_earnings, + "income_rule": "the four earnings leaves plus the carried income " + "columns; donor partnership SE earnings enter through " + "partnership_income, not twice", "other_income_columns_carried": carried, "donor_only_income_columns_carried": donor_carried, "income_columns_absent": [ From d05559c165c0d2e90d3040286269b24910aef435 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 15 Nov 2026 14:42:05 -0500 Subject: [PATCH 11/20] Fix the county support fixture inventory (#922) Co-Authored-By: OpenAI Codex --- .../engine_free/us/test_us_acs_local_county_production.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py index faefa3044d..4b58c9bbda 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py @@ -812,7 +812,7 @@ def test_group_quarters_records_are_not_county_support() -> None: households["household_spine"] = "acs_2024_1yr" households["TYPEHUGQ"] = kinds # 01003 has one housing unit beside three group-quarters records; 01007 - # has group quarters only; 01005 has nothing. + # has group quarters only; 01005 and 01009 have nothing initially. populations = {1001: 10.0, 1003: 40.0, 1005: 5.0, 1007: 8.0, 1009: 30.0} overlaps = county.puma_overlaps( [100001] * 5, sorted(populations), [10.0, 40.0, 5.0, 8.0, 30.0] @@ -820,7 +820,7 @@ def test_group_quarters_records_are_not_county_support() -> None: moves, receipt = county.plan_minimum_support( households, populations, overlaps, per_county=1 ) - assert receipt["unsupported_before"] == ["01005", "01007"] + assert receipt["unsupported_before"] == ["01005", "01007", "01009"] # 01003's lone housing unit would leave it with group quarters only. assert moves == [] assert {entry["status"] for entry in receipt["counties"].values()} == { From 5c5515b089784c549c14018af997fb4e7a33df85 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 15 Nov 2026 14:42:51 -0500 Subject: [PATCH 12/20] Refuse unprepared county facts without reopening the file (#922) Co-Authored-By: OpenAI Codex --- docs/us-acs-local-county-rung.md | 4 ++- .../us/test_us_acs_local_county_production.py | 28 +++++++++++++++++++ tools/us_acs_local_county_surface.py | 13 +++++++-- 3 files changed, 41 insertions(+), 4 deletions(-) diff --git a/docs/us-acs-local-county-rung.md b/docs/us-acs-local-county-rung.md index 19a35df892..a8d98088e0 100644 --- a/docs/us-acs-local-county-rung.md +++ b/docs/us-acs-local-county-rung.md @@ -292,7 +292,9 @@ holds about 0.9 GB of rows, measured apart from importing the US runtime. The rows stay on the surface for the rest of the materialize stage; today only the SOI county split, the ACS households family and the validation design read them, all in `prepare_run`. No county step reads `--feed`, and nothing reopens -the county facts file after `prepare_run`. The +the county facts file after `prepare_run`. If the prepared facts are missing, +`attach_surface` records a refusal in `county_surface.json` and stops, even +when derived surfaces are cached. The run identity and `materialize_rss.json` record the county facts receipt under `county_facts`. The refresh recipe carries both flags. It names placeholder files (``, like `--feed`'s) and never the build machine's path; diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py index 4b58c9bbda..57454c6cf2 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py @@ -353,6 +353,34 @@ def test_validation_design_refuses_a_zero_state_denominator_and_bad_brackets() - county.county_validation_design(rows, {1001: 1.0}) +@pytest.mark.parametrize("cached_parts", range(8)) +@pytest.mark.parametrize("facts_attribute", ["absent", "none"]) +def test_attach_surface_refuses_unprepared_facts_without_reopening( + monkeypatch, tmp_path, cached_parts, facts_attribute +) -> None: + """P3-4: no combination of cached derived surfaces may reopen the file.""" + county = _county() + surface = SimpleNamespace() + if facts_attribute == "none": + surface.county_facts = None + for bit, name in enumerate( + ("county_surface", "acs_households", "county_validation_design") + ): + if cached_parts & (1 << bit): + setattr(surface, name, SimpleNamespace()) + + def unexpected_load(_args): + pytest.fail("attach_surface reopened the county facts file") + + monkeypatch.setattr(county, "_load_county_facts", unexpected_load) + args = SimpleNamespace(soi_mode="state_county", checkpoint_dir=tmp_path / "run") + with pytest.raises(SystemExit, match="prepare_run did not load the county facts"): + county.attach_surface(surface, None, None, None, args) + report = json.loads((args.checkpoint_dir / county.SURFACE_FILENAME).read_text()) + assert report["status"] == "refused" + assert "prepare_run did not load the county facts" in report["error"] + + # --- ACS households (trained) ------------------------------------------------- diff --git a/tools/us_acs_local_county_surface.py b/tools/us_acs_local_county_surface.py index f0af7af6fe..3f8376f856 100644 --- a/tools/us_acs_local_county_surface.py +++ b/tools/us_acs_local_county_surface.py @@ -2565,19 +2565,26 @@ def attach_surface(surface, materialized, frame, populations, args): return materialized.compiled_specs, materialized.matrix column = getattr(args, "county_column", COUNTY_COLUMN) facts = getattr(surface, "county_facts", None) + if facts is None: + message = ( + "prepare_run did not load the county facts; refusing to reopen " + "the county facts file during attach_surface. Re-run --stage materialize." + ) + args.checkpoint_dir.mkdir(parents=True, exist_ok=True) + (args.checkpoint_dir / SURFACE_FILENAME).write_text( + json.dumps({"status": "refused", "error": message}) + ) + raise SystemExit(message) county = getattr(surface, "county_surface", None) if county is None: - facts = facts or _load_county_facts(args) county = state_county_soi_surface( materialized.compiled_specs, facts.rows, populations["county"] ) acs = getattr(surface, "acs_households", None) if acs is None: - facts = facts or _load_county_facts(args) acs = acs_household_surface(facts.rows, populations["county"]) design = getattr(surface, "county_validation_design", None) if design is None: - facts = facts or _load_county_facts(args) design = county_validation_design(facts.rows, populations["county"]) households = frame.table("household") matrix = split_state_rows( From 88ab158b5d417b0157873261730440ee7ac977e4 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 15 Nov 2026 14:43:18 -0500 Subject: [PATCH 13/20] Exclude ACS group quarters from county household reliability (#922) Co-Authored-By: OpenAI Codex --- docs/us-acs-local-county-rung.md | 9 +- .../us/test_us_acs_local_county_production.py | 97 +++++++++++++++++++ tools/us_acs_local_county_surface.py | 12 ++- 3 files changed, 112 insertions(+), 6 deletions(-) diff --git a/docs/us-acs-local-county-rung.md b/docs/us-acs-local-county-rung.md index a8d98088e0..2a73411ea5 100644 --- a/docs/us-acs-local-county-rung.md +++ b/docs/us-acs-local-county-rung.md @@ -118,7 +118,9 @@ donors each split into two clones have source ESS 200 (grade B at adequate fit) and row ESS 400; cloning cannot earn grade A. Missing or null source provenance makes source ESS unavailable and the grade U. The report binds the run identity, calibrated weights, and configured county column. Unsupported smoke counties -remain explicit with zero support and grade `U`. +remain explicit with zero support and grade `U`. ACS group-quarters records +count toward neither household support nor household ESS; a county with only +those records remains `no_support` and grade `U` in a smoke run. For each target, relative error is `abs(estimate - target) / max(abs(target), 1)`. The grade uses the maximum error @@ -142,8 +144,9 @@ in the report. Rules are evaluated from A through C, then D; a county without holdout evidence receives U even if its training fit is good, as does a county without source identity. Without `--soi-mode state_county` there are no validation families, -so a 10% block holdout can leave many counties ungraded. With it, only a -county with no supporting household can be U. At fixed error, raising ESS cannot worsen a grade. +so a 10% block holdout can leave many counties ungraded. With it and complete +source identity, only a county with no supporting household can be U. At +fixed error, raising ESS cannot worsen a grade. These are report-only evidence grades; Kish ESS is not a county standard error or a guarantee of unbiased estimates. diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py index 57454c6cf2..6c3835aa86 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py @@ -1502,3 +1502,100 @@ def test_acs_household_rows_have_their_own_state_budgets_in_the_loss() -> None: assert all(mapping.value_basis(spec) == "count" for spec in specs) weights = county.target_loss_weights(specs, {}) assert np.isfinite(weights).all() and (weights > 0).all() + + +@pytest.mark.parametrize("target_supported", [False, True]) +@_SETTINGS +@given( + support_weights=st.lists( + st.floats(min_value=1.0, max_value=1_000.0), min_size=1, max_size=500 + ), + group_quarters=st.lists( + st.tuples( + st.sampled_from([1001, 1003]), + st.sampled_from([2.0, 3.0]), + st.floats(min_value=1_000_000.0, max_value=1_000_000_000_000.0), + ), + min_size=1, + max_size=30, + ), + errors=st.tuples(*(st.floats(0.0, 1.0) for _ in range(4))), + minimum_support=st.booleans(), +) +def test_group_quarters_cannot_change_county_reliability( + target_supported, support_weights, group_quarters, errors, minimum_support +) -> None: + county = _county() + # Keep another county supported even when the target county has no housing + # units. Every ACS baseline row is a housing unit with known provenance. + target_weights = support_weights if target_supported else [] + weights = np.asarray([1.0, *target_weights]) + baseline = pd.DataFrame( + { + "household_id": np.arange(len(weights)), + "county_fips": [1003, *([1001] * len(target_weights))], + "state_fips": 1, + "household_spine": "acs_2024_1yr", + "household_source_id": np.arange(len(weights)), + "TYPEHUGQ": 1.0, + } + ) + gq_counties, gq_kinds, gq_weights = zip(*group_quarters, strict=True) + additions = pd.DataFrame( + { + "household_id": np.arange(len(weights), len(weights) + len(group_quarters)), + "county_fips": gq_counties, + "state_fips": 1, + "household_spine": "acs_2024_1yr", + # Missing identities on excluded rows must not invalidate a + # supported county's distinct-source ESS or reliability grade. + "household_source_id": np.nan, + "TYPEHUGQ": gq_kinds, + } + ) + assert len(county.GRADED_VALIDATION_FAMILIES) == len(errors) == 4 + validation = { + "counties": { + code: { + family: {"abs_rel_error": error} + for family, error in zip( + county.GRADED_VALIDATION_FAMILIES, errors, strict=True + ) + } + for code in ("01001", "01003") + } + } + options = { + "county_populations": {1001: 10.0, 1003: 10.0}, + "validation": validation, + "minimum_support_counties": ["01001"] if minimum_support else [], + } + before = county.reliability_report( + baseline, + [], + sparse.csr_array((0, len(baseline))), + final_weights=weights, + **options, + ) + with_gq = pd.concat([baseline, additions], ignore_index=True) + after = county.reliability_report( + with_gq, + [], + sparse.csr_array((0, len(with_gq))), + final_weights=np.concatenate([weights, np.asarray(gq_weights)]), + **options, + ) + target = before["counties"]["01001"] + if target_supported: + assert target["grade"] in ("A", "B", "C", "D") + else: + assert target["grade"] == "U" + assert target["supporting_households"] == len(target_weights) + assert target["status"] == ( + ("minimum_support" if minimum_support else "supported") + if target_supported + else "no_support" + ) + # This compares support counts, distinct-source and physical-row ESS, + # grade and status for both the target and the fixed supported county. + assert after["counties"] == before["counties"] diff --git a/tools/us_acs_local_county_surface.py b/tools/us_acs_local_county_surface.py index 3f8376f856..def65ae88d 100644 --- a/tools/us_acs_local_county_surface.py +++ b/tools/us_acs_local_county_surface.py @@ -1709,7 +1709,13 @@ def reliability_report( | {int(code) for code in (county_populations or {})} | {int(code) for code in validated} ) - groups = _county_groups(codes) + # Precision and support must use the same household universe as the + # trained ACS households rows. Group-quarters records cannot supply + # household evidence or increase household ESS, even in a capped smoke. + universe = support_universe(households) + groups = { + code: rows[universe[rows]] for code, rows in _county_groups(codes).items() + } minimum = {int(code) for code in minimum_support_counties} names = county_names or {} result = {} @@ -1807,8 +1813,8 @@ def reliability_report( "schema_version": 3, "county_column": county_column, "ess_basis": { - "kish_ess": "final weights summed within county by (household_spine, household_source_id)", - "kish_ess_rows": "final weights over physical household rows, including clones", + "kish_ess": "final weights summed within county by (household_spine, household_source_id), excluding ACS group quarters", + "kish_ess_rows": "final weights over physical household rows, including clones, excluding ACS group quarters", }, "counties": result, "validation_families": { From a770ba7f755434ef367128dbc5e9f935723fc961 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 15 Nov 2026 14:43:31 -0500 Subject: [PATCH 14/20] Validate every county income bracket label and clarify receipts (#922) Co-Authored-By: OpenAI Codex --- docs/us-acs-local-county-rung.md | 16 +++++--- .../us/test_us_acs_local_county_production.py | 18 +++++++++ tools/us_acs_local_county_surface.py | 40 +++++++++++-------- 3 files changed, 52 insertions(+), 22 deletions(-) diff --git a/docs/us-acs-local-county-rung.md b/docs/us-acs-local-county-rung.md index 2a73411ea5..4c6e711445 100644 --- a/docs/us-acs-local-county-rung.md +++ b/docs/us-acs-local-county-rung.md @@ -162,7 +162,9 @@ set `group_0` and 130 counties with estimates and margins in `group_1`. Each table must name every county exactly once; duplicates, negative or nonfinite estimates, a statistic that does not match the measure ID, a layout county that differs from the row geography, a Puerto Rico row (state `72`) and -incomplete or unexpected county inventories are refused by name. +incomplete or unexpected county inventories are refused by name. Every +B19001 estimate and margin row must carry the expected income-bracket label, +including rows after the first county. **Trained: `acs_households`.** Each state gets a new households target equal to the sum of its counties' B11001_001E estimates, and each county a child @@ -214,9 +216,10 @@ pro_rata(c) = M_s * ladder population(c) / state population ``` where `M_s` is the state's total of the household measure under the final -weights. The report gives each county's calibrated, design-weight and -pro-rata errors per family; the bracket family's graded error is the L1 -error over its 16 brackets divided by the county's bracket target total (at +weights. The design-weight diagnostic uses its own state total, so it also +measures within-state shares. The report gives each county's calibrated, +design-weight and pro-rata errors per family; the bracket family's graded +error is the L1 error over its 16 brackets divided by the county's bracket target total (at least 1). Materialize writes the public values (`county_validation.json`) and the household measures (`county_validation_measures.npz`), and the run identity binds their @@ -362,8 +365,9 @@ For the historical 1,588,854-household staging population, each household can contribute to at most four added county rows and one added state households row. That gives at most **7,944,270 added nnz**, approximately **63.6 MB** of raw float32/int32 CSR data and indices, plus about 50 KB of row pointers. The -validation measures file holds four float64 arrays per household, about -51 MB. Zero measures reduce nnz. Temporary matrix +validation measures file holds four 64-bit arrays per household (the +household ID and three float64 measures), about 51 MB. Zero measures reduce +nnz. Temporary matrix copies and Python overhead add memory, and existing state rows and the engine/frame dominate the total. Historical full materialization peaked at 75.6–93.9 GB; calibration was about 67.6 GB. Allocate **128 GiB** and start with diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py index 6c3835aa86..c394dc340f 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py @@ -381,6 +381,24 @@ def unexpected_load(_args): assert "prepare_run did not load the county facts" in report["error"] +@pytest.mark.parametrize("bracket_index", range(16)) +@pytest.mark.parametrize("county_code", ["01001", "01003"]) +@pytest.mark.parametrize("suffix", ["E", "M"]) +def test_every_countys_income_bracket_label_is_checked( + bracket_index, county_code, suffix +) -> None: + county = _county() + measure = county.B19001_BRACKETS[bracket_index][0][:-1] + suffix + rows = _acs_rows(["01001", "01003"]) + for row in rows: + if row["observed_measure"]["source_measure_id"] == measure and row["geography"][ + "id" + ].endswith(county_code): + row["dimensions"]["income_range"] = "wrong_bracket" + with pytest.raises(ValueError, match=f"{measure}.*labelled.*bracket"): + county.county_validation_design(rows, {1001: 1.0, 1003: 1.0}) + + # --- ACS households (trained) ------------------------------------------------- diff --git a/tools/us_acs_local_county_surface.py b/tools/us_acs_local_county_surface.py index def65ae88d..6783a89f22 100644 --- a/tools/us_acs_local_county_surface.py +++ b/tools/us_acs_local_county_surface.py @@ -1080,21 +1080,27 @@ def county_validation_design(facts, county_populations): measure for family in VALIDATION_FAMILIES for measure in family.measure_ids ] values = acs_county_values(facts, measure_ids, required=counties) - labels = {} + brackets = { + measure: (label, lower, upper) + for measure, label, lower, upper in B19001_BRACKETS + } for fact in facts: observed = fact.get("observed_measure", {}) - if observed.get("source_name") == ACS_SOURCE_NAME and str( - observed.get("source_measure_id", "") - ).startswith("B19001_0"): - labels.setdefault( - observed["source_measure_id"], - (fact.get("dimensions") or {}).get("income_range"), - ) - for measure, label, lower, upper in B19001_BRACKETS: - if labels.get(measure) != label or _bracket_bounds(label) != (lower, upper): + measure = str(observed.get("source_measure_id", "")) + estimate_id = measure[:-1] + "E" + if ( + observed.get("source_name") != ACS_SOURCE_NAME + or measure[-1:] not in {"E", "M"} + or estimate_id not in brackets + ): + continue + expected, lower, upper = brackets[estimate_id] + label = (fact.get("dimensions") or {}).get("income_range") + if label != expected or _bracket_bounds(label) != (lower, upper): raise ValueError( - f"ACS {measure} is labelled {labels.get(measure)!r}; the bracket " - f"table expects {label!r} = [{lower}, {upper})." + f"ACS {measure} for {fact.get('geography', {}).get('id')} is " + f"labelled {label!r}; the bracket table expects {expected!r} " + f"= [{lower}, {upper})." ) states = sorted({code // 1000 for code in counties}) for measure, public in values.items(): @@ -1172,10 +1178,12 @@ def household_validation_measures(frame): """Household-aligned measures the validation families are scored on. Returns ``(arrays, report)``: ``household_id``, ``in_household_universe``, - ``earnings`` (:data:`EARNINGS_COLUMNS` summed over the household's - people) and ``household_income_approx`` (earnings plus the carried - :data:`OTHER_INCOME_COLUMNS`, plus :data:`DONOR_ONLY_OTHER_INCOME_COLUMNS` - on donor records). Missing person values count as zero, as in the pilot. + ``earnings`` (the four :data:`EARNINGS_COLUMNS` leaves, plus donor + partnership self-employment earnings, summed over the household's people) + and ``household_income_approx`` (the four leaves plus carried + :data:`OTHER_INCOME_COLUMNS` on all records, and + :data:`DONOR_ONLY_OTHER_INCOME_COLUMNS` on donor records). Income includes donor partnership earnings through + partnership income, once. Missing person values count as zero, as in the pilot. """ households = frame.table("household") person = frame.table("person") From 44ddec5a850f7cc571f435866e52b894e67d42b7 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 15 Nov 2026 15:16:20 -0500 Subject: [PATCH 15/20] Fix two county rung tests that could not pass (#922) - test_validation_values_change_no_loss_input_and_no_weight wrote its fixtures into tmp_path/scale_, which it never created, so it failed with FileNotFoundError before reaching any assertion. It now creates each scale folder. The test then passes: registry, roles and matrix digests and the solved weights are equal across the two validation value sets, and only the validation design digest differs. - test_calibration_outputs_are_bound_to_the_materialization pins the calibration outputs a rematerialization clears. This branch added county_reliability.csv to CALIBRATION_OUTPUT_FILENAMES without updating the pin. County suites (six files, -n 4): 277 passed, 1 failed before this fix; release-tool suites (four files, -n 4): 676 passed, 2 skipped, 1 failed. Both failing tests pass after it. Co-Authored-By: Claude Opus 5.5 --- .../engine_free/us/test_us_acs_local_county_surface.py | 6 +++--- .../tests/engine_free/us/test_us_acs_local_sparse_cd.py | 1 + 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py index a277ea4fc1..b433cf5554 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py @@ -903,9 +903,9 @@ def test_validation_values_change_no_loss_input_and_no_weight( "income": data["income"] * scale + scale, "brackets": data["brackets"][::-1] if scale > 1 else data["brackets"], } - run = _materialize_county_fixture( - monkeypatch, tmp_path / f"scale_{scale}", acs_values=values - ) + scale_dir = tmp_path / f"scale_{scale}" + scale_dir.mkdir() + run = _materialize_county_fixture(monkeypatch, scale_dir, acs_values=values) identity = json.loads( (run.args.checkpoint_dir / "run_identity.json").read_text() ) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_sparse_cd.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_sparse_cd.py index 137f145f43..29e0549485 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_sparse_cd.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_sparse_cd.py @@ -1137,6 +1137,7 @@ def test_calibration_outputs_are_bound_to_the_materialization(tmp_path) -> None: "calibration_summary.json", "calibration_diagnostics.json", "county_reliability.json", + "county_reliability.csv", "consumer_export.json", "consumer_reviewed_null_fills.json", "spine_qa.json", From ddc49578b2547ec901730db6f33f3b6227217a32 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 15 Nov 2026 23:11:25 -0500 Subject: [PATCH 16/20] Keep group quarters out of county reliability after a checkpoint reload (#922) Round-1 review of #1630 found that the lean checkpoint drops TYPEHUGQ, so after a reload support_universe() counted every ACS record as a household: 40 households and 360 group-quarters records went from ESS 40 and grade C to ESS 400 and grade A, and a county of group quarters alone from U to A. A run with county targets now keeps TYPEHUGQ in its lean checkpoint; a run without them writes the same columns as before. calibration_evidence grades with reliability_universe(), which refuses a frame whose ACS records lack TYPEHUGQ (such as a checkpoint written before this change) instead of counting it whole, and checks the mask against the run's identity-bound validation measures. The regression test round-trips the checkpoint. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_acs_local_county_surface.py | 105 ++++++++++++++++++ tools/build_us_acs_local_release.py | 14 ++- tools/us_acs_local_county_surface.py | 69 +++++++++++- 3 files changed, 180 insertions(+), 8 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py index b433cf5554..d42897ab27 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py @@ -595,6 +595,111 @@ def test_missing_source_identity_cannot_produce_a_row_based_reliability_grade( assert cell["grade"] == "U" +_RELIABILITY_KEYS = ("supporting_households", "kish_ess", "grade", "status") + + +@pytest.mark.skipif( + importlib.util.find_spec("tables") is None, reason="requires pytables" +) +@pytest.mark.parametrize("real_households", [40, 0]) +def test_group_quarters_stay_out_of_reliability_after_a_checkpoint_reload( + tmp_path, real_households +) -> None: + """A county of 40 households and 360 group-quarters records grades C on + the full frame. Its lean checkpoint once dropped TYPEHUGQ, so the reload + counted all 400 records and graded A; a county of group quarters alone + went from U to A (review of #1630). A county run now keeps TYPEHUGQ and + grades the same after the reload; a run without county targets writes the + columns it always did, and a checkpoint without TYPEHUGQ is refused.""" + module, county = _release(), _county() + from microcosm.frame import US_SCHEMA, Frame, WeightKind, Weights + + n = 400 + ids = np.arange(1, n + 1) + households = pd.DataFrame( + { + "household_id": ids, + "county_fips": np.full(n, 1001), + "state_fips": np.ones(n, dtype=int), + "household_spine": [county.ACS_SPINE] * n, + "household_source_id": ids, + "TYPEHUGQ": [1.0] * real_households + [3.0] * (n - real_households), + } + ) + tables = { + "household": households, + "person": pd.DataFrame( + { + "person_id": ids, + "person_household_id": ids, + **{f"person_{group}_id": ids for group in US_SCHEMA.group_entities}, + } + ), + **{ + group: pd.DataFrame({f"{group}_id": ids}) + for group in US_SCHEMA.group_entities + }, + } + frame = Frame( + tables, US_SCHEMA, {"household": Weights(np.ones(n), WeightKind.DESIGN)} + ) + matrix = sparse.csr_array(np.ones((1, n), dtype=np.float32)) + specs = [county.population_spec("pop_county_01001", 400.0)] + records = [ + { + "name": "pop_county_01001", + "value": 400.0, + "role": "train", + "geography_level": "county", + "county_fips": "01001", + } + ] + validation = { + "counties": { + "01001": { + name: {"abs_rel_error": 0.0} + for name in county.GRADED_VALIDATION_FAMILIES + } + } + } + + def graded(table): + cell = county.reliability_report( + table, + records, + matrix, + final_weights=np.ones(n), + validation=validation, + household_universe_mask=county.reliability_universe(table), + )["counties"]["01001"] + return {key: cell[key] for key in _RELIABILITY_KEYS} + + full = graded(households) + assert full["supporting_households"] == real_households + assert full["grade"] == ("C" if real_households else "U") + + plain = module.extract_struct_tables(frame) + assert list(plain["household_struct"].columns) == [ + "household_id", + "state_fips", + "county_fips", + "household_spine", + "household_source_id", + ] + struct = module.extract_struct_tables(frame, county_run=True) + assert "TYPEHUGQ" in struct["household_struct"].columns + module.write_lean_checkpoint(struct, matrix, specs, records, tmp_path / "county") + lean, weights = module.load_lean_frame(tmp_path / "county" / "target_frame_lean.h5") + assert graded(lean.table("household")) == full + + module.write_lean_checkpoint(plain, matrix, specs, records, tmp_path / "old") + old, _ = module.load_lean_frame(tmp_path / "old" / "target_frame_lean.h5") + with pytest.raises(ValueError, match="TYPEHUGQ"): + county.reliability_universe(old.table("household")) + with pytest.raises(SystemExit, match="materialize again"): + county.calibration_evidence(old, records, matrix, weights, np.ones(n), 1.0) + + @pytest.mark.skipif( importlib.util.find_spec("tables") is None, reason="requires pytables" ) diff --git a/tools/build_us_acs_local_release.py b/tools/build_us_acs_local_release.py index 9babbdec51..07fa32d417 100644 --- a/tools/build_us_acs_local_release.py +++ b/tools/build_us_acs_local_release.py @@ -1739,15 +1739,19 @@ def require_one_label_per_geography(admin_registry, ladder_populations, geograph TARGET_ROLES_FILENAME = "target_roles.json" -def extract_struct_tables(frame, *, county_column="county_fips"): - """Small structural/geography copies so the big frame can be freed early.""" +def extract_struct_tables(frame, *, county_column="county_fips", county_run=False): + """Small structural/geography copies so the big frame can be freed early. + + ``county_run`` keeps what county reliability needs after a reload + (:func:`us_acs_local_county_surface.struct_columns`). + """ households = frame.table("household") struct_columns = [ column for column in LEAN_HOUSEHOLD_COLUMNS if column in households.columns ] struct_columns += county_surface.struct_columns( - households, struct_columns, county_column=county_column + households, struct_columns, county_column=county_column, county_run=county_run ) person_columns = [ column for column in PERSON_STRUCT if column in frame.table("person").columns @@ -2381,7 +2385,9 @@ def do_materialize(args) -> None: matrix = sparse.vstack([admin_matrix, pop_matrix], format="csr") del admin_matrix, pop_matrix struct = extract_struct_tables( - frame, county_column=getattr(args, "county_column", "county_fips") + frame, + county_column=getattr(args, "county_column", "county_fips"), + county_run=any(role.get("geography_level") == "county" for role in roles), ) n_households = frame.n("household") del frame diff --git a/tools/us_acs_local_county_surface.py b/tools/us_acs_local_county_surface.py index 6783a89f22..05b5a33a53 100644 --- a/tools/us_acs_local_county_surface.py +++ b/tools/us_acs_local_county_surface.py @@ -1684,6 +1684,7 @@ def reliability_report( validation=None, minimum_support_counties=(), county_names=None, + household_universe_mask=None, ): """One reliability cell per county: support, ESS, errors and a grade. @@ -1693,6 +1694,11 @@ def reliability_report( U only without any held-out evidence (no household support) or without source identity. ``minimum_support_counties`` mark counties whose only households came from the minimum-support step. + + ``household_universe_mask`` is the households that count toward support + and ESS; without it, :func:`support_universe` decides. The build passes + :func:`reliability_universe`, which refuses a frame that cannot tell group + quarters apart instead of counting every record. """ codes = county_codes(households, county_column=county_column) weights = np.asarray(final_weights, float) @@ -1720,7 +1726,15 @@ def reliability_report( # Precision and support must use the same household universe as the # trained ACS households rows. Group-quarters records cannot supply # household evidence or increase household ESS, even in a capped smoke. - universe = support_universe(households) + if household_universe_mask is None: + universe = support_universe(households) + else: + universe = np.asarray(household_universe_mask) + if universe.dtype != bool or universe.shape != (len(households),): + raise ValueError( + "The county reliability household universe must be one boolean " + "per household." + ) groups = { code: rows[universe[rows]] for code, rows in _county_groups(codes).items() } @@ -2024,6 +2038,20 @@ def support_universe(households): return np.ones(len(households), dtype=bool) +def reliability_universe(households): + """The households county reliability counts, refusing to guess. + + Unlike :func:`support_universe`, a frame that names its spines but whose + ACS records lack ``TYPEHUGQ`` is refused rather than counted whole. A lean + checkpoint written before county runs kept ``TYPEHUGQ`` is such a frame: + every group-quarters record would otherwise count toward a county's + support, distinct sources and ESS. + """ + if "household_spine" in households.columns: + return household_universe(households) > 0 + return support_universe(households) + + def unsupported_counties(households, county_populations, *, county_column): """Counties with positive ladder population and no supporting household.""" codes = county_codes(households, county_column=county_column) @@ -2699,14 +2727,29 @@ def run_metadata(args, county_holdout): return metadata -def struct_columns(households, existing_columns, *, county_column=COUNTY_COLUMN): - # Preserve configured county columns through the structure-only checkpoint. - return [ +def struct_columns( + households, existing_columns, *, county_column=COUNTY_COLUMN, county_run=False +): + """The household columns the structure-only checkpoint adds for counties. + + Every configured county column survives. A run with county targets also + keeps ``TYPEHUGQ``, so reliability after a reload can still exclude group + quarters. A run without county targets keeps exactly the columns it kept + before, and so writes the same checkpoint bytes. + """ + columns = [ column for column in households.columns if (column.startswith("county_fips") or column == county_column) and column not in existing_columns ] + if ( + county_run + and HOUSEHOLD_KIND_COLUMN in households.columns + and HOUSEHOLD_KIND_COLUMN not in existing_columns + ): + columns.append(HOUSEHOLD_KIND_COLUMN) + return columns def calibration_evidence( @@ -2743,6 +2786,14 @@ def calibration_evidence( COUNTY_COLUMN, ) households = frame.table("household") + try: + universe = reliability_universe(households) + except ValueError as error: + raise SystemExit( + "County reliability cannot exclude group quarters from these " + f"households: {error} A lean checkpoint written before county runs " + "kept TYPEHUGQ needs --stage materialize again." + ) from error receipt = (identity or {}).get("county_validation") validation = design = None if receipt: @@ -2761,6 +2812,15 @@ def calibration_evidence( cap=target_loss_cap, county_column=column, ) + # The validation measures are bound to the run identity and aligned + # with these households (score_county_validation checked the ids). + bound = np.asarray(measures["in_household_universe"], dtype=np.float64) > 0 + if not np.array_equal(bound, universe): + raise SystemExit( + f"{int((bound != universe).sum())} checkpoint household(s) " + "disagree with the run's validation measures about the " + "household universe; refusing to grade county reliability." + ) support = (identity or {}).get("county_support") or {} evidence = { "county_holdout": score_county_holdout( @@ -2780,6 +2840,7 @@ def calibration_evidence( county_populations=None if design is None else design["county_populations"], minimum_support_counties=support.get("moved_counties", []), county_names=None if design is None else design["county_names"], + household_universe_mask=universe, ), } if validation is not None: From edc871ab8f2174338616809854d717545fe20a1b Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 16 Nov 2026 09:26:01 -0500 Subject: [PATCH 17/20] Test county support moves through the driver, and fix the reload test's frame (#922) Round-1 review of #1630, P2: the driver fixture recorded no support move, so a driver that dropped check_support's moved frame or skipped the export's replay still passed. The new test puts eight eligible households and one group-quarters record in 01001 and none in 01003, with K=3, and checks the moved counties in the frame the engine pass sees, the support receipt and run identity, the lean checkpoint after a reload, reliability after the reload, and the consumer export, which reloads unmoved staging. _materialize_county_fixture takes a household table and the county-PUMA overlaps for it. The checkpoint-reload test from ddc49578b built its frame with the ids-only group tables after the household table, so the frame kept household_id alone. It now adds the household table last and checks the frame keeps its columns. Mutation check: dropping the moved frame, skipping the export replay, dropping TYPEHUGQ from the lean checkpoint, and counting every record in calibration_evidence each fail these tests. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_acs_local_county_surface.py | 232 ++++++++++++++++-- 1 file changed, 210 insertions(+), 22 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py index d42897ab27..501c75842e 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py @@ -627,7 +627,6 @@ def test_group_quarters_stay_out_of_reliability_after_a_checkpoint_reload( } ) tables = { - "household": households, "person": pd.DataFrame( { "person_id": ids, @@ -639,10 +638,13 @@ def test_group_quarters_stay_out_of_reliability_after_a_checkpoint_reload( group: pd.DataFrame({f"{group}_id": ids}) for group in US_SCHEMA.group_entities }, + # After the group tables, which include an ids-only household table. + "household": households, } frame = Frame( tables, US_SCHEMA, {"household": Weights(np.ones(n), WeightKind.DESIGN)} ) + assert list(frame.table("household").columns) == list(households.columns) matrix = sparse.csr_array(np.ones((1, n), dtype=np.float32)) specs = [county.population_spec("pop_county_01001", 400.0)] records = [ @@ -703,8 +705,22 @@ def graded(table): @pytest.mark.skipif( importlib.util.find_spec("tables") is None, reason="requires pytables" ) -def _materialize_county_fixture(monkeypatch, tmp_path, *, acs_values=None): - """Materialize a three-household state_county fixture, with a fake engine.""" +def _materialize_county_fixture( + monkeypatch, + tmp_path, + *, + acs_values=None, + households=None, + county_column="planning_region", + overlaps=None, +): + """Materialize a state_county fixture, with a fake engine. + + By default three households and no county support move. ``households`` + replaces the household table (one person each, design weight 10), and + ``overlaps`` stands in for the ladder's county-PUMA overlaps that minimum + support reads. + """ from microcosm.build import ledger_artifact from microcosm.build.us_runtime import county_facts as county_facts_module from microcosm.calibrate import TargetRegistry @@ -712,37 +728,54 @@ def _materialize_county_fixture(monkeypatch, tmp_path, *, acs_values=None): module = _release() county = _county() - ids = np.arange(1, 4) + if households is None: + ids = np.arange(1, 4) + incomes = { + "employment_income_before_lsr": [30_000.0, 50_000.0, 0.0], + "self_employment_income_before_lsr": [0.0, 5_000.0, 0.0], + } + household_table = pd.DataFrame( + { + "household_id": ids, + "state_fips": [1, 1, 1], + "county_fips": [99999, 99999, 99999], + "planning_region": [1001, 1003, 1001], + "household_spine": ["asec_puf"] * 3, + "household_source_id": [7, 8, 7], + } + ) + design = np.asarray([10.0, 20.0, 30.0]) + else: + ids = households["household_id"].to_numpy() + incomes = { + "employment_income_before_lsr": 10_000.0 * (np.arange(len(ids)) + 1), + "self_employment_income_before_lsr": np.zeros(len(ids)), + } + household_table = households + design = np.full(len(ids), 10.0) + zeros = np.zeros(len(ids)) person = pd.DataFrame( { "person_id": ids, "person_household_id": ids, **{f"person_{group}_id": ids for group in US_SCHEMA.group_entities}, # The held-out ACS validation families read household earnings. - "employment_income_before_lsr": [30_000.0, 50_000.0, 0.0], - "self_employment_income_before_lsr": [0.0, 5_000.0, 0.0], - "sstb_self_employment_income_before_lsr": [0.0, 0.0, 0.0], - "farm_operations_income": [0.0, 0.0, 0.0], + **incomes, + "sstb_self_employment_income_before_lsr": zeros, + "farm_operations_income": zeros, } ) tables = {"person": person} for group in US_SCHEMA.group_entities: tables[group] = pd.DataFrame({f"{group}_id": ids}) - tables["household"] = pd.DataFrame( - { - "household_id": ids, - "state_fips": [1, 1, 1], - "county_fips": [99999, 99999, 99999], - "planning_region": [1001, 1003, 1001], - "household_spine": ["asec_puf"] * 3, - "household_source_id": [7, 8, 7], - } - ) + tables["household"] = household_table frame = Frame( tables, US_SCHEMA, - {"household": Weights(np.asarray([10.0, 20.0, 30.0]), WeightKind.DESIGN)}, + {"household": Weights(design, WeightKind.DESIGN)}, ) + if overlaps is not None: + monkeypatch.setattr(county, "county_puma_overlaps", lambda _path: overlaps) staging, feed, ladder, county_facts_file = ( tmp_path / name for name in ("staging.h5", "feed.json", "ladder.npz", "county_facts.jsonl") @@ -776,7 +809,9 @@ def _materialize_county_fixture(monkeypatch, tmp_path, *, acs_values=None): "--geographies", "state,county", "--county-column", - "planning_region", + county_column, + "--county-min-support", + "3", "--sample-fraction", "0.01", "--county-holdout-fraction", @@ -838,14 +873,19 @@ def _materialize_county_fixture(monkeypatch, tmp_path, *, acs_values=None): ) materialized = SimpleNamespace( compiled_specs=parents, - matrix=sparse.csr_array(np.asarray([[1, 1, 1], [10, 10, 10]], np.float32)), + matrix=sparse.csr_array( + np.asarray([[1] * len(ids), [10] * len(ids)], np.float32) + ), chunk_stats=[], carrier_check={}, ) seen = [] + materialized_frames = [] def fake_materialize(current, specs, **_kwargs): - assert current is frame + if households is None: + assert current is frame + materialized_frames.append(current) seen.extend(specs) return materialized @@ -893,6 +933,7 @@ def feed_is_not_county_facts(*_args, **_kwargs): county=county, args=args, frame=frame, + materialized_frames=materialized_frames, parents=parents, seen=seen, county_reads=county_reads, @@ -985,6 +1026,153 @@ def test_county_hooks_materialize_a_fixture_and_preserve_configured_geography( ) +def _export_county_fixture(module, monkeypatch, run, out_h5, weights): + """Run the consumer export on a materialized fixture, its heavy steps stubbed. + + Staging reloads as the fixture's original frame, so the export sees the + counties staging stores, not the ones materialize moved. + """ + monkeypatch.setattr( + module, "project_input_only", lambda base, period=None: (base, {}) + ) + monkeypatch.setattr(module, "fill_reviewed_nulls", lambda *a, **k: ([], None)) + # The fixture's take-up stub records the digest "stub" for every seed. + monkeypatch.setattr( + module, + "_recorded_take_up", + lambda identity: {"seed": 0, "assigned_sha256": "stub"}, + ) + monkeypatch.setattr( + module, + "_recorded_ssi_medicaid_take_up", + lambda *a, **k: ({"assigned_sha256": "", "assignment_file": ""}, None), + ) + monkeypatch.setattr( + module, "_resample_like_materialize", lambda frame, identity: frame + ) + monkeypatch.setattr( + module, "_with_recorded_ssi_medicaid_take_up", lambda frame, *a: frame + ) + monkeypatch.setattr( + module, + "_with_live_stored_inputs", + lambda frame: SimpleNamespace(frame=frame, provenance={}), + ) + identity = json.loads((run.args.checkpoint_dir / "run_identity.json").read_text()) + run.args.out_h5 = out_h5 + module._write_calibrated_artifact( + run.args, + weights, + identity, + {}, + code=module._repo_code_identity(allow_dirty=True), + ) + return pd.read_hdf(out_h5, "household") + + +@pytest.mark.skipif( + importlib.util.find_spec("tables") is None, reason="requires pytables" +) +def test_support_moves_reach_materialize_the_checkpoint_and_the_export( + monkeypatch, tmp_path +) -> None: + """Minimum support through the driver (microcosm#922 review). + + Eight eligible households and one group-quarters record sit in 01001 and + none in 01003, which overlaps the same PUMA. With K=3, exactly three + households move. The engine pass must see the moved frame, the lean + checkpoint must carry the moved counties, reliability after the reload + must count them in 01003, and the export, which reloads unmoved staging, + must publish them there too. + """ + county = _county() + ids = np.arange(1, 10) + acs = ids % 2 == 1 + households = pd.DataFrame( + { + "household_id": ids, + "state_fips": 1, + "county_fips": 1001, + "county_fips_2023": 1001, + "puma": 100100, + "household_spine": np.where(acs, "acs_2024_1yr", "asec_puf"), + "household_source_id": ids + 100, + # Household 9 is an ACS group-quarters record: it supports no + # county and never moves. + "TYPEHUGQ": np.where(acs, np.where(ids == 9, 3.0, 1.0), np.nan), + } + ) + staged = households.copy() + populations = {1001: 80.0, 1003: 120.0} + overlaps = county.puma_overlaps([100100, 100100], [1001, 1003], [80.0, 120.0]) + moves, receipt = county.plan_minimum_support( + staged, populations, overlaps, county_column="county_fips", per_county=3 + ) + moved_ids = sorted(move["household_id"] for move in moves) + assert len(moved_ids) == 3 and 9 not in moved_ids + expected = np.where(np.isin(ids, moved_ids), 1003, 1001) + + run = _materialize_county_fixture( + monkeypatch, + tmp_path, + households=households, + county_column="county_fips", + overlaps=overlaps, + ) + module, args = run.module, run.args + # Staging is untouched; the engine pass saw the moved frame. + pd.testing.assert_frame_equal(run.frame.table("household"), staged) + (seen_frame,) = run.materialized_frames + for column in ("county_fips", "county_fips_2023"): + np.testing.assert_array_equal( + seen_frame.table("household")[column].to_numpy(), expected + ) + np.testing.assert_array_equal(seen_frame.table("household")["puma"], 100100) + np.testing.assert_array_equal(seen_frame.table("household")["state_fips"], 1) + + support = json.loads((args.checkpoint_dir / county.SUPPORT_FILENAME).read_text()) + assert support["unsupported_counties"] == [] + assert support["counties"]["01003"]["supporting_households"] == 3 + assert support["counties"]["01001"]["supporting_households"] == 5 + assert support["minimum_support"]["moves"] == receipt["moves"] + identity = json.loads((args.checkpoint_dir / "run_identity.json").read_text()) + assert identity["county_support"]["moves"] == 3 + assert identity["county_support"]["moves_sha256"] == receipt["moves_sha256"] + assert identity["county_support"]["moved_counties"] == ["01003"] + + loaded, design, _registry, records, matrix = module.load_checkpoint_surface( + args.checkpoint_dir, identity + ) + lean = loaded.table("household") + np.testing.assert_array_equal(lean["household_id"], ids) + np.testing.assert_array_equal(lean["county_fips"].to_numpy(), expected) + for record in records: + if record.get("state_county_parent_target_name"): + record["role"] = "holdout" + weights = np.full(len(ids), 10.0) + evidence = module.calibration_evidence( + frame=loaded, + roles=records, + matrix=matrix, + design_weights=design, + weights=weights, + target_loss_cap=1.0, + checkpoint_dir=args.checkpoint_dir, + identity=identity, + ) + graded = evidence["county_reliability"]["counties"] + assert graded["01003"]["supporting_households"] == 3 + assert graded["01001"]["supporting_households"] == 5 + + exported = _export_county_fixture( + module, monkeypatch, run, tmp_path / "calibrated.h5", weights + ) + np.testing.assert_array_equal(exported["household_id"], ids) + for column in ("county_fips", "county_fips_2023"): + np.testing.assert_array_equal(exported[column].to_numpy(), expected) + np.testing.assert_array_equal(exported["puma"], 100100) + + def test_validation_values_change_no_loss_input_and_no_weight( monkeypatch, tmp_path ) -> None: From 118f96f931dc5f890c478fa2a2ad8a7b20150eeb Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 16 Nov 2026 12:33:53 -0500 Subject: [PATCH 18/20] Recompute the evidence when a completed run resumes (#922) An earlier round-2 review run of #1630 found that the completed-resume shortcut in do_calibrate reused the old calibration_summary.json and called write_reports without calibration_evidence or reliability_universe. A checkpoint from before TYPEHUGQ was kept, with a matching old summary, therefore kept its inflated county grades: 40 households and 360 group-quarters records stayed at A instead of C. The shortcut now recomputes calibration_evidence from the checkpoint and the saved weights before it writes anything, and refuses if any key differs from the summary's (compared as canonical JSON). A checkpoint the current code refuses, such as one without TYPEHUGQ, is refused there as it is by a fresh solve. test_a_completed_resume_ships_only_evidence_this_code_computes covers regraded evidence and a refused checkpoint, and checks that nothing is written. Comparing nothing fails the first case; skipping the recomputation fails both. Release tool, county surface and sparse CD suites: 409 passed, 2 skipped. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_acs_local_release_tool.py | 58 +++++++++++++++++++ tools/build_us_acs_local_release.py | 30 ++++++++++ 2 files changed, 88 insertions(+) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_tool.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_tool.py index f1362125a7..8fd5cf4585 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_tool.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_tool.py @@ -7086,6 +7086,64 @@ def test_calibrate_records_the_code_it_read_when_it_started( assert events == ["git", "prepare", "git", "write"] +@pytest.mark.parametrize("now", ["regraded", "refused"]) +def test_a_completed_resume_ships_only_evidence_this_code_computes( + tmp_path: Path, monkeypatch, now +) -> None: + """A resumed run with nothing left to solve recomputes the summary's + evidence from the checkpoint and the saved weights. Evidence an older build + wrote (county grades that counted group quarters as support), or a + checkpoint the current code refuses (one without TYPEHUGQ), stops the + stage before it writes anything, as a fresh solve would (review of + #1630).""" + + module = _load_tool_module() + args, events = _calibrate_through_the_write( + module, tmp_path, monkeypatch, [_STARTED_CODE] * 5 + ) + older = { + "cd_holdout": {"n_targets": 0}, + "n_holdout_targets": 0, + "county_reliability": {"counties": {"01001": {"grade": "A"}}}, + } + monkeypatch.setattr(module, "calibration_evidence", lambda **kwargs: older) + module.do_calibrate(args) + outputs = [ + args.out_h5, + args.checkpoint_dir / "calibration_summary.json", + args.checkpoint_dir / "consumer_export.json", + args.checkpoint_dir / "weights_latest.npz", + ] + written = [path.read_bytes() for path in outputs] + + events.clear() + args.resume = True + if now == "regraded": + current = { + **older, + "county_reliability": {"counties": {"01001": {"grade": "C"}}}, + } + monkeypatch.setattr(module, "calibration_evidence", lambda **kwargs: current) + refusal = r"\['county_reliability'\] evidence .* another build wrote it" + else: + + def refuse(**kwargs): + raise SystemExit("the checkpoint has no TYPEHUGQ; materialize again") + + monkeypatch.setattr(module, "calibration_evidence", refuse) + refusal = "materialize again" + with pytest.raises(SystemExit, match=refusal): + module.do_calibrate(args) + assert events == ["git"] + assert [path.read_bytes() for path in outputs] == written + + # The evidence this code computes, unchanged, still takes the shortcut. + events.clear() + monkeypatch.setattr(module, "calibration_evidence", lambda **kwargs: older) + module.do_calibrate(args) + assert events == ["git", "prepare", "git", "write"] + + @pytest.mark.parametrize( ("started", "at_write", "refusal"), [ diff --git a/tools/build_us_acs_local_release.py b/tools/build_us_acs_local_release.py index 07fa32d417..e3538528e0 100644 --- a/tools/build_us_acs_local_release.py +++ b/tools/build_us_acs_local_release.py @@ -3062,6 +3062,36 @@ def do_calibrate(args) -> None: and _stamped_settings(previous.get("solver_settings")) == settings and previous.get("weights_sha256") == _weights_digest(warm) ): + # The summary's evidence must be what this code computes from the + # checkpoint and these weights. Otherwise the shortcut ships what + # an older build wrote, such as county reliability grades that + # counted group quarters as support from a checkpoint without + # TYPEHUGQ. Recomputing it refuses that checkpoint exactly as a + # fresh solve does (review of #1630). + evidence = calibration_evidence( + frame=frame, + roles=roles, + matrix=matrix, + design_weights=design_weights, + weights=np.asarray(warm, dtype=np.float64), + target_loss_cap=args.target_loss_cap, + checkpoint_dir=args.checkpoint_dir, + identity=identity, + ) + stale = sorted( + key + for key, value in evidence.items() + if json.dumps(previous.get(key), sort_keys=True) + != json.dumps(value, sort_keys=True) + ) + if stale: + raise SystemExit( + f"calibration_summary.json records {stale} evidence that " + "this code does not compute from the checkpoint and the " + "weights_latest.npz weights, so another build wrote it. " + "Delete weights_latest.npz or run without --resume to " + "recalibrate." + ) log( f"calibration already complete at {done} epochs and " "the calibration summary exists; nothing to do (delete " From c5c7b46972fac99d934ea3714be208c0d564e081 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 16 Nov 2026 15:56:57 -0500 Subject: [PATCH 19/20] Take 2023 county populations from the ladder's tract overlaps (#922) A full county run with --county-column county_fips_2023 refused at prepare_run: the PUMA ladder's county overlaps are 2020 counties, so a national ladder declares 3,143 county-equivalents (Connecticut's eight legacy counties) against the 3,144 the County Files need, and the planning-region facts would not match its Connecticut codes. Under county_fips_2023 the rung now regroups the ladder's (PUMA, tract) overlaps by each tract's 2023 county-equivalent (county_fips_2023_from_tracts) for both the county populations and the minimum support step's PUMA overlaps. Every PUMA's population is conserved and every county outside Connecticut keeps its 2020 overlaps. Any other county column is unchanged. A national ladder built today gives 3,144 county-equivalents, the nine regions and the same total; an opt-in test reruns that check against MICROCOSM_US_PUMA_LADDER_ARTIFACT. Co-Authored-By: Claude Opus 5.5 --- .../922-us-county-rung-production.added.md | 2 +- docs/us-acs-local-county-rung.md | 25 +++- .../us/test_us_acs_local_county_production.py | 2 +- .../us/test_us_acs_local_county_surface.py | 107 +++++++++++++++++- tools/build_us_acs_local_release.py | 14 ++- tools/us_acs_local_county_surface.py | 78 +++++++++++-- 6 files changed, 205 insertions(+), 23 deletions(-) diff --git a/changelog.d/922-us-county-rung-production.added.md b/changelog.d/922-us-county-rung-production.added.md index 8b9b404e18..28fa9c242a 100644 --- a/changelog.d/922-us-county-rung-production.added.md +++ b/changelog.d/922-us-county-rung-production.added.md @@ -1 +1 @@ -Make the ACS-local county rung (`--geographies state,cd,county --soi-mode state_county`) a full production calibration. It trains new ACS county household targets under new ACS state household targets, and scores four held-out ACS county families (earnings, households with earnings, approximate household income and its brackets) against a pro-rata baseline without changing the loss or the weights. It gives every supported county an A–D reliability grade in `county_reliability.json` and a packaged `county_reliability.csv`. `--county-min-support` (default 3) fills empty counties with same-PUMA households and records each move in `county_support.json`. Kalawao shares a declared SOI cell with Maui. +Make the ACS-local county rung (`--geographies state,cd,county --soi-mode state_county`) a full production calibration. It trains new ACS county household targets under new ACS state household targets, and scores four held-out ACS county families (earnings, households with earnings, approximate household income and its brackets) against a pro-rata baseline without changing the loss or the weights. It gives every supported county an A–D reliability grade in `county_reliability.json` and a packaged `county_reliability.csv`. `--county-min-support` (default 3) fills empty counties with same-PUMA households and records each move in `county_support.json`. Kalawao shares a declared SOI cell with Maui. Under `--county-column county_fips_2023` the rung takes its county populations and county-PUMA overlaps from the ladder's tract overlaps on 2023 boundaries, so Connecticut's nine planning regions and all 3,144 county-equivalents come from the existing PUMA ladder. diff --git a/docs/us-acs-local-county-rung.md b/docs/us-acs-local-county-rung.md index 4c6e711445..99c0dcd94f 100644 --- a/docs/us-acs-local-county-rung.md +++ b/docs/us-acs-local-county-rung.md @@ -326,10 +326,22 @@ The inspected Chronicle publisher inputs have two concrete issues: `15005,15009`. Any other county missing from SOI, a declared cell whose host is missing too, or a declaration across states is refused. - **Connecticut:** both packages use the nine planning-region codes `09110` - through `09190`. The household county column and ladder must use those same - boundaries. Select `--county-column county_fips_2023` when the parallel - planning-region work supplies that column, and use its matching ladder. - Changing the column name alone cannot translate legacy county targets. + through `09190`. The household county column and the ladder's county + populations must use those same boundaries, so a full run selects + `--county-column county_fips_2023`. The PUMA ladder's own county overlaps are + 2020 counties (Connecticut's eight legacy counties, 3,143 in all). Under + `county_fips_2023` the rung therefore takes its county populations, and the + PUMA overlaps the minimum support step draws from, from the ladder's tract + overlaps instead: each tract's 2023 county-equivalent + (`county_fips_2023_from_tracts`) is its planning region in Connecticut and + its own county elsewhere, so every PUMA's population is conserved and every + county outside Connecticut keeps its 2020 overlaps + (`ladder_county_overlaps`). A ladder without tract overlaps is refused under + that column. Read against a national ladder that + `tools/build_us_puma_ladder_artifact.py` built on 2026-11-16, this gives 3,144 + county-equivalents with the nine regions and the same national total; set + `MICROCOSM_US_PUMA_LADDER_ARTIFACT` to rerun that check. Any other county + column reads the 2020 overlaps unchanged. SOI facts carry `geography.level = "county"` and Census-style IDs such as `0500000US01001`; the row geography is authoritative even though the record @@ -346,11 +358,12 @@ for `co-est2024-alldata.csv`. A full run needs the pinned main feed and its SHA256, the pinned county facts file and its SHA256, a staging H5 and summary with household support in every county (after the -minimum support step), and a matching county-boundary PUMA ladder. The +minimum support step), and the PUMA ladder the staging was built with (its +tract overlaps supply the 2023 county populations; see Connecticut above). The historical staging file was approximately 10.7 GB. The historical ladder was 446,791 bytes with SHA256 `39a2ab2abeab07a88362af7ab2940e0e1d50a297c919e4bbc6fb65bab51147d8`; -that old digest is reference evidence, not an approved planning-region ladder. +that old digest is reference evidence only. At 3,144 counties, the county increment is 3,144 population rows, 3,143 rows for each of the two SOI concepts (Kalawao shares Maui's cell), 3,144 ACS diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py index c394dc340f..fae1b8362f 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_production.py @@ -1120,7 +1120,7 @@ def test_check_support_applies_minimum_support_before_refusing( monkeypatch.setattr( county, "county_puma_overlaps", - lambda _path: county.puma_overlaps( + lambda _path, _column="county_fips": county.puma_overlaps( [100001, 100001], [1001, 1003], [90.0, 10.0] ), ) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py index 501c75842e..f1d6f553ad 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_surface.py @@ -135,6 +135,107 @@ def test_ladder_county_population_is_scaled_to_each_state() -> None: assert sum(v for k, v in only_counties["county"].items() if k // 1000 == 1) == 100.0 +def _split_connecticut_tracts(): + """Two real tracts of one legacy Connecticut county in different regions.""" + from microcosm.build.us_runtime.county_vintage import ( + load_ct_planning_region_by_tract, + ) + + by_county: dict[int, dict[int, int]] = {} + for tract, region in sorted(load_ct_planning_region_by_tract().items()): + regions = by_county.setdefault(int(str(tract)[:5]), {}) + regions.setdefault(int(region), int(tract)) + legacy, regions = next( + (legacy, regions) + for legacy, regions in sorted(by_county.items()) + if len(regions) >= 2 + ) + (first_region, first_tract), (second_region, second_tract) = sorted( + regions.items() + )[:2] + return legacy, (first_tract, first_region), (second_tract, second_region) + + +def _vintage_ladder(): + legacy, (tract_a, _), (tract_b, _) = _split_connecticut_tracts() + return SimpleNamespace( + puma=np.asarray([100001, 900101]), + puma_population=np.asarray([50.0, 50.0]), + county_overlap_puma=np.asarray([100001, 900101]), + county_overlap_county=np.asarray([1001, legacy]), + county_overlap_population=np.asarray([50.0, 50.0]), + tract_overlap_puma=np.asarray([100001, 900101, 900101]), + tract_overlap_tract=np.asarray([1001020100, tract_a, tract_b]), + tract_overlap_population=np.asarray([50.0, 30.0, 20.0]), + ) + + +def test_county_fips_2023_takes_planning_regions_from_tract_overlaps() -> None: + county = _county() + legacy, (_, region_a), (_, region_b) = _split_connecticut_tracts() + ladder = _vintage_ladder() + legacy_populations = county.with_county_populations(ladder, {}, ["county"]) + assert legacy_populations["county"] == {1001: 50.0, legacy: 50.0} + populations = county.with_county_populations( + ladder, {}, ["county"], county_column="county_fips_2023" + ) + assert populations["county"] == {1001: 50.0, region_a: 30.0, region_b: 20.0} + assert populations["state"] == legacy_populations["state"] + pumas, counties, values = county.ladder_county_overlaps(ladder, "county_fips_2023") + # Every PUMA keeps its population; Alabama keeps its 2020 overlap. + for puma, total in zip(ladder.puma, ladder.puma_population, strict=True): + assert values[pumas == puma].sum() == total + assert counties[pumas == 100001].tolist() == [1001] + overlaps = county.puma_overlaps(pumas, counties, values) + assert overlaps[region_a] == [(900101, 30.0)] + assert overlaps[region_b] == [(900101, 20.0)] + # Any other column reads the 2020 overlaps unchanged. + same = county.ladder_county_overlaps(ladder, "county_fips") + assert same[1].tolist() == [1001, legacy] + + +def test_county_fips_2023_refuses_a_ladder_without_tract_overlaps() -> None: + county = _county() + ladder = _vintage_ladder() + ladder.tract_overlap_tract = np.asarray([], dtype=np.int64) + ladder.tract_overlap_puma = np.asarray([], dtype=np.int64) + ladder.tract_overlap_population = np.asarray([], dtype=float) + with pytest.raises(ValueError, match="tract overlaps"): + county.with_county_populations( + ladder, {}, ["county"], county_column="county_fips_2023" + ) + + +def test_an_existing_national_ladder_declares_3144_county_equivalents_in_2023() -> None: + """Read-only check of a built national PUMA ladder (skipped without one). + + Set ``MICROCOSM_US_PUMA_LADDER_ARTIFACT`` to the NPZ that + ``tools/build_us_puma_ladder_artifact.py`` writes. + """ + import os + from pathlib import Path + + artifact = os.environ.get("MICROCOSM_US_PUMA_LADDER_ARTIFACT") + if not artifact: + pytest.skip("MICROCOSM_US_PUMA_LADDER_ARTIFACT is not set") + release = _release() + geographies = ["state", "cd", "county"] + legacy = release.ladder_population(Path(artifact), geographies) + current = release.ladder_population( + Path(artifact), geographies, county_column="county_fips_2023" + ) + assert len(current["county"]) == _county().REQUIRED_COUNTY_COUNT + assert sorted(code for code in current["county"] if code // 1000 == 9) == list( + range(9110, 9200, 10) + ) + assert math.isclose( + math.fsum(current["county"].values()), math.fsum(legacy["county"].values()) + ) + for code, value in legacy["county"].items(): + if code // 1000 != 9: + assert math.isclose(current["county"][code], value) + + def test_population_rows_partition_households_and_accept_an_alternate_county_column() -> ( None ): @@ -775,7 +876,11 @@ def _materialize_county_fixture( {"household": Weights(design, WeightKind.DESIGN)}, ) if overlaps is not None: - monkeypatch.setattr(county, "county_puma_overlaps", lambda _path: overlaps) + monkeypatch.setattr( + county, + "county_puma_overlaps", + lambda _path, _column="county_fips": overlaps, + ) staging, feed, ladder, county_facts_file = ( tmp_path / name for name in ("staging.h5", "feed.json", "ladder.npz", "county_facts.jsonl") diff --git a/tools/build_us_acs_local_release.py b/tools/build_us_acs_local_release.py index e3538528e0..b477458791 100644 --- a/tools/build_us_acs_local_release.py +++ b/tools/build_us_acs_local_release.py @@ -1557,7 +1557,9 @@ def sparse_rows(matrix, rows): ] -def ladder_population(ladder_path: Path, geographies: list[str]): +def ladder_population( + ladder_path: Path, geographies: list[str], *, county_column: str = "county_fips" +): from microcosm.build.us_runtime.puma_ladder import load_us_puma_ladder ladder = load_us_puma_ladder(ladder_path) @@ -1575,7 +1577,9 @@ def ladder_population(ladder_path: Path, geographies: list[str]): ) for cd in np.unique(ladder.cd_overlap_cd) } - return county_surface.with_county_populations(ladder, populations, geographies) + return county_surface.with_county_populations( + ladder, populations, geographies, county_column=county_column + ) def household_sizes(frame) -> np.ndarray: @@ -2248,7 +2252,11 @@ def do_materialize(args) -> None: f"admin specs: {len(registry)} ({families}, soi_mode={args.soi_mode}); " f"RI substitution records={len(surface.ri_substitutions)}" ) - populations = ladder_population(args.ladder, sorted(set(geographies) | {"cd"})) + populations = ladder_population( + args.ladder, + sorted(set(geographies) | {"cd"}), + county_column=getattr(args, "county_column", "county_fips"), + ) county_surface.prepare_run(args, geographies, populations, surface=surface) require_one_label_per_geography(registry, populations, geographies) summary_path = _staging_summary_path(args) diff --git a/tools/us_acs_local_county_surface.py b/tools/us_acs_local_county_surface.py index 05b5a33a53..35d128d1e9 100644 --- a/tools/us_acs_local_county_surface.py +++ b/tools/us_acs_local_county_surface.py @@ -92,7 +92,57 @@ def county_codes(households, *, county_column=COUNTY_COLUMN) -> np.ndarray: return counties -def with_county_populations(ladder, populations, geographies): +#: The household column whose county-equivalents are the 2023 boundaries +#: (Connecticut's nine planning regions). The PUMA ladder's county overlaps +#: are 2020 counties, so this column takes its overlaps from the ladder's +#: tract overlaps instead (:func:`ladder_county_overlaps`). +COUNTY_COLUMN_2023 = "county_fips_2023" + + +def ladder_county_overlaps(ladder, county_column=COUNTY_COLUMN): + """``(pumas, counties, populations)`` on the boundaries of ``county_column``. + + The PUMA ladder records ``(PUMA, county)`` overlaps on 2020 counties, which + name Connecticut's eight legacy counties. For ``county_fips_2023`` the + overlaps are the ladder's ``(PUMA, tract)`` overlaps regrouped by each + tract's 2023 county-equivalent + (:func:`microcosm.build.us_runtime.county_vintage.county_fips_2023_from_tracts`): + a Connecticut tract takes its planning region and every other tract keeps + its county, so each PUMA's population is conserved and every county + outside Connecticut keeps its 2020 overlaps. Any other column reads the + 2020 overlaps unchanged. + """ + if county_column != COUNTY_COLUMN_2023: + return ( + np.asarray(ladder.county_overlap_puma), + np.asarray(ladder.county_overlap_county), + np.asarray(ladder.county_overlap_population, dtype=float), + ) + from microcosm.build.us_runtime.county_vintage import ( + county_fips_2023_from_tracts, + ) + + tracts = np.asarray(ladder.tract_overlap_tract) + pumas = _codes(ladder.tract_overlap_puma, column="tract_overlap_puma") + values = np.asarray(ladder.tract_overlap_population, dtype=float) + if not len(tracts) or len(tracts) != len(pumas) or len(tracts) != len(values): + raise ValueError( + f"{COUNTY_COLUMN_2023} needs the ladder's tract overlaps, and this " + "ladder has none or misaligned ones." + ) + counties = _codes(county_fips_2023_from_tracts(tracts), column=COUNTY_COLUMN_2023) + cells = pd.DataFrame({"puma": pumas, "county": counties, "population": values}) + grouped = cells.groupby(["puma", "county"], sort=True)["population"].sum() + return ( + grouped.index.get_level_values("puma").to_numpy(np.int64), + grouped.index.get_level_values("county").to_numpy(np.int64), + grouped.to_numpy(float), + ) + + +def with_county_populations( + ladder, populations, geographies, *, county_column=COUNTY_COLUMN +): """Aggregate ladder overlaps, then reconcile counties to state levels.""" if "county" not in geographies: return populations @@ -103,8 +153,15 @@ def with_county_populations(ladder, populations, geographies): int(state): float(np.asarray(ladder.puma_population)[states == state].sum()) for state in np.unique(states) } - counties = _codes(ladder.county_overlap_county, column="county_overlap_county") - values = np.asarray(ladder.county_overlap_population, dtype=float) + if county_column == COUNTY_COLUMN_2023: + _pumas, overlap_counties, overlap_values = ladder_county_overlaps( + ladder, county_column + ) + else: + overlap_counties = ladder.county_overlap_county + overlap_values = ladder.county_overlap_population + counties = _codes(overlap_counties, column="county_overlap_county") + values = np.asarray(overlap_values, dtype=float) if ( len(counties) != len(values) or not np.isfinite(values).all() @@ -1966,16 +2023,15 @@ def cell_value(value): COUNTY_DETERMINING_LOCATION_COLUMNS = ("tract_geoid", "block_geoid") -def county_puma_overlaps(ladder_path): - """``{county: [(puma, population), ...]}``, largest overlap first.""" +def county_puma_overlaps(ladder_path, county_column=COUNTY_COLUMN): + """``{county: [(puma, population), ...]}``, largest overlap first. + + Counties are on ``county_column``'s boundaries (:func:`ladder_county_overlaps`). + """ from microcosm.build.us_runtime.puma_ladder import load_us_puma_ladder ladder = load_us_puma_ladder(ladder_path) - return puma_overlaps( - ladder.county_overlap_puma, - ladder.county_overlap_county, - ladder.county_overlap_population, - ) + return puma_overlaps(*ladder_county_overlaps(ladder, county_column)) def puma_overlaps(pumas, counties, populations): @@ -2485,7 +2541,7 @@ def check_support(frame, populations, args): needed = unsupported_counties( households, populations["county"], county_column=column ) - overlaps = county_puma_overlaps(args.ladder) if needed else {} + overlaps = county_puma_overlaps(args.ladder, column) if needed else {} moves, support = plan_minimum_support( households, populations["county"], From 5186faa250efd7df09918047e14c6849d31cbe2d Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 16 Nov 2026 19:13:01 -0500 Subject: [PATCH 20/20] Let the geography-label test's ladder stub take county_column (#922) c5c7b4697 passes county_column to ladder_population from do_materialize. The stub in test_materialize_refuses_a_geography_label_conflict_before_the_engine_pass took only the ladder path and geographies, so engine-free CI failed with a TypeError (1 failed, 29,850 passed). The stub now accepts the column with the default value. Co-Authored-By: Claude Opus 5.5 --- .../tests/engine_free/us/test_us_acs_local_geography_labels.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_geography_labels.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_geography_labels.py index d914871777..e0de4f8cd8 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_geography_labels.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_geography_labels.py @@ -215,7 +215,7 @@ def test_materialize_refuses_a_geography_label_conflict_before_the_engine_pass( monkeypatch.setattr( module, "ladder_population", - lambda ladder_path, geographies: { + lambda ladder_path, geographies, county_column="county_fips": { "state": {23: 1_400_000.0}, "cd": {2301: 700_000.0, 2302: 700_000.0}, },