From 288b2e3ca8fc2a74cef707877eadae8d1edaa09b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:17:36 +0000 Subject: [PATCH 01/23] Pin the bytes of the ACS local target surface on the pinned feed and ladder microcosm#1728 moves the code that builds the local target surface out of the tools. Each move must leave every target, role and receipt as it was. TargetRegistry.version sorts metadata keys, so it does not see a change of key order. Materialize writes target_registry.json and target_roles.json with the keys in insertion order, and their sha256 is in the run identity. test_us_acs_local_surface_bytes.py follows the target part of do_materialize for each non-county --soi-mode: the admin surface, the ladder populations, the role records, the district pro-rata populations, the ladder population rows, and the district and county hold-outs. It pins the sha256 of target_registry.json, of target_roles.json, of the target receipts, and of the population rows' matrix on a household table that supports every ladder cell (a release run refuses a cell with no household). Measured at 3316038cc and run twice: state 4,867 targets, totals 742, full 30,464, state_cd 26,912. The tests run only when MICROCOSM_US_CHRONICLE_FACTS and MICROCOSM_US_PUMA_LADDER_ARTIFACT name the pinned inputs. state_county is not pinned: it needs the pinned county facts, which are not on this machine, and a household frame for its support moves. Co-Authored-By: Claude Opus 5.5 --- .../us/test_us_acs_local_surface_bytes.py | 271 ++++++++++++++++++ 1 file changed, 271 insertions(+) create mode 100644 packages/microcosm-build/tests/engine_free/us/test_us_acs_local_surface_bytes.py diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_surface_bytes.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_surface_bytes.py new file mode 100644 index 0000000000..79576aac9a --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_surface_bytes.py @@ -0,0 +1,271 @@ +"""The bytes the ACS local materialize stage writes for its targets (microcosm#1728). + +The shared-code work of microcosm#1728 moves the code that builds the local +target surface out of the tools. Each move must leave every target, role and +receipt as it was. ``TargetRegistry.version`` sorts metadata keys, so it does +not see a change of key order; the stage writes ``target_registry.json`` and +``target_roles.json`` with the keys in insertion order, and their sha256 is in +the run identity. These tests pin those bytes. + +For each non-county ``--soi-mode``, the test follows the target part of +``do_materialize``: the admin surface, the ladder populations, the role +records, the district pro-rata populations (``state_cd``), the ladder +population rows, and the district and county hold-outs. The household frame +and the engine pass are not needed for that: a release keeps every compiled +target (a lost one stops the run) and every ladder cell (a cell with no +household stops the run without ``--allow-partial-geography``). So the test +gives the population rows a small household table that supports every ladder +cell, and pins the rows' matrix on that table too. + +The pins were measured at ``3316038cc``, before any code moved. They run only +when ``MICROCOSM_US_CHRONICLE_FACTS`` names the pinned feed and +``MICROCOSM_US_PUMA_LADDER_ARTIFACT`` names the pinned PUMA ladder. The +county mode (``state_county``) needs the pinned county facts and a household +frame for its support moves; it is not pinned here. +""" + +from __future__ import annotations + +import hashlib +import importlib.util +import json +import os +from pathlib import Path +from types import SimpleNamespace + +import numpy as np +import pandas as pd +import pytest + +from microcosm.calibrate import TargetRegistry +from test_support.paths import paths_for + +_TEST_PATHS = paths_for("microcosm-build") + +#: The pinned PUMA ladder (as in ``test_us_target_sets.py``). +PINNED_LADDER_SHA256 = ( + "39a2ab2abeab07a88362af7ab2940e0e1d50a297c919e4bbc6fb65bab51147d8" +) + +#: The tool's defaults: ``--families`` and ``--geographies``. +FAMILIES = ("snap", "medicaid", "soi") +GEOGRAPHIES = ("state", "cd") + +#: For each mode on the pinned feed and ladder: the number of targets, and the +#: sha256 of ``target_registry.json``, of ``target_roles.json``, of the target +#: receipts (SOI surface, district hold-out, county hold-out) and of the +#: population rows' matrix on the supporting household table. +PINNED_BYTES: dict[str, dict[str, object]] = { + "full": { + "targets": 30_464, + "target_registry_sha256": ( + "d568f29827f8c24a07021628c747c4437b212984be9e82ff93cbebc1ec4ecb69" + ), + "target_roles_sha256": ( + "a55d88c7c2b747e7321de6cdae4671dfcb29b3ee5c97587d7983ac888652743a" + ), + "receipts_sha256": ( + "f102782cd2fcfdd896a91bbb163ab1a5120cf06e008aade657cb2b54b4b1eddb" + ), + "population_matrix_sha256": ( + "ae7785b655538f802e9ef7203c3ae6160ad250ed9e22c06c39475ae4614994f4" + ), + }, + "state": { + "targets": 4_867, + "target_registry_sha256": ( + "0157f2b653e51147b8e1b1fc364b0616d1198665718426384349c37cea8a0e4c" + ), + "target_roles_sha256": ( + "929b1b27b62f57c492829b51dd9c0e72a21b470b32345f0475a545f7d76de28d" + ), + "receipts_sha256": ( + "c5f148b6b2f72745dd1c3d470b88743f5acf9c5cc07c10fedeef6c6831f31afc" + ), + "population_matrix_sha256": ( + "ae7785b655538f802e9ef7203c3ae6160ad250ed9e22c06c39475ae4614994f4" + ), + }, + "state_cd": { + "targets": 26_912, + "target_registry_sha256": ( + "fad3ddf61915407fe187d9c739bd379d17c804347dc446e85f3e0303e8518bf3" + ), + "target_roles_sha256": ( + "ffa9c4c964ea84385f0bfe5ef3c1053937897bfcecff941315d0a61f0ab0cca4" + ), + "receipts_sha256": ( + "9c67654cd7c8ab53b68969bf7ea30134871a1407af37d87ae3b2067294efed7f" + ), + "population_matrix_sha256": ( + "ae7785b655538f802e9ef7203c3ae6160ad250ed9e22c06c39475ae4614994f4" + ), + }, + "totals": { + "targets": 742, + "target_registry_sha256": ( + "07a69bf412892b2e5e73868a6d49886c0077c875b07cce293bc742745d858d16" + ), + "target_roles_sha256": ( + "c1d5eca2710f97a073c111273b78d2d9e0f58777314b1bd74eb8dd95410a686e" + ), + "receipts_sha256": ( + "7195a0a24ce81a4f63d680781d9fbdc2b3f4a50c9d2b3fe1e16e9f4eff66e3e9" + ), + "population_matrix_sha256": ( + "ae7785b655538f802e9ef7203c3ae6160ad250ed9e22c06c39475ae4614994f4" + ), + }, +} + + +def _load_tool(name: str): + path = _TEST_PATHS.repository / "tools" / f"{name}.py" + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + spec.loader.exec_module(module) + return module + + +def _pinned_inputs() -> tuple[str, Path]: + feed = os.environ.get("MICROCOSM_US_CHRONICLE_FACTS", "") + if not feed or not Path(feed).exists(): + pytest.skip("set MICROCOSM_US_CHRONICLE_FACTS to the pinned 41b2fb2 feed") + ladder = os.environ.get("MICROCOSM_US_PUMA_LADDER_ARTIFACT", "") + if not ladder or not Path(ladder).exists(): + pytest.skip("set MICROCOSM_US_PUMA_LADDER_ARTIFACT to the PUMA ladder") + assert hashlib.sha256(Path(ladder).read_bytes()).hexdigest() == PINNED_LADDER_SHA256 + return feed, Path(ladder) + + +def _sha256(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def _supporting_households(populations) -> tuple[pd.DataFrame, np.ndarray]: + """One household in each ladder district, and in each state with none.""" + + districts = sorted(int(code) for code in populations["cd"]) + states = {code // 100 for code in districts} + rows = [ + {"state_fips": code // 100, "congressional_district_geoid": code} + for code in districts + ] + rows += [ + {"state_fips": int(code), "congressional_district_geoid": 0} + for code in sorted(populations["state"]) + if int(code) not in states + ] + households = pd.DataFrame(rows) + return households, np.ones(len(households), dtype=np.float32) + + +def materialize_target_part(local_tool, feed: str, ladder: Path, soi_mode: str): + """The target part of ``do_materialize`` for one mode, without a frame. + + Returns ``(specs, roles, receipts, population_matrix)`` in the order the + stage writes them. + """ + + cd_surface = local_tool.cd_surface + county_surface = local_tool.county_surface + args = SimpleNamespace( + soi_mode=soi_mode, + cd_holdout_fraction=None, + county_column="county_fips", + county_holdout_fraction=county_surface.DEFAULT_COUNTY_HOLDOUT_FRACTION, + county_holdout_salt=county_surface.COUNTY_HOLDOUT_SALT, + ) + holdout_fraction = local_tool._cd_holdout_fraction(args) + surface = local_tool.state_admin_surface(feed, list(FAMILIES), soi_mode=soi_mode) + registry = surface.registry + populations = local_tool.ladder_population( + ladder, + sorted(set(GEOGRAPHIES) | {"cd"}), + county_column="county_fips", + ) + local_tool.require_one_label_per_geography(registry, populations, list(GEOGRAPHIES)) + compiled_specs = list(registry.specs) + admin_roles = [county_surface.target_record(spec) for spec in compiled_specs] + if soi_mode == local_tool.SOI_MODE_STATE_CD: + local_tool._attach_pro_rata_populations(admin_roles, populations["cd"]) + local_tool._require_pro_rata_populations(admin_roles) + households, sizes = _supporting_households(populations) + pop_roles, pop_matrix, pop_dropped = cd_surface.population_rows( + households, + sizes, + populations, + list(GEOGRAPHIES), + county_column="county_fips", + ) + assert pop_dropped == [] + pop_specs = local_tool.population_target_specs( + [record["name"] for record in pop_roles], + [record["value"] for record in pop_roles], + ) + roles = admin_roles + pop_roles + holdout = cd_surface.assign_target_roles(roles, fraction=holdout_fraction) + county_holdout = county_surface.assign_roles(roles, args) + receipts = { + "soi_surface": surface.soi_receipt, + "cd_holdout": holdout, + "county_holdout": county_holdout, + } + return (*compiled_specs, *pop_specs), roles, receipts, pop_matrix + + +def surface_bytes(local_tool, feed: str, ladder: Path, soi_mode: str, tmp_path: Path): + """The pinned measurements of one mode (see ``PINNED_BYTES``).""" + + specs, roles, receipts, pop_matrix = materialize_target_part( + local_tool, feed, ladder, soi_mode + ) + registry_path = tmp_path / f"target_registry_{soi_mode}.json" + TargetRegistry(specs, country="us").to_json(registry_path) + matrix = ( + str(pop_matrix.shape).encode() + + pop_matrix.indptr.astype(np.int64).tobytes() + + pop_matrix.indices.astype(np.int64).tobytes() + + pop_matrix.data.astype(np.float32).tobytes() + ) + return { + "targets": len(specs), + "target_registry_sha256": _sha256(registry_path.read_bytes()), + "target_roles_sha256": _sha256(json.dumps(roles, indent=1).encode()), + "receipts_sha256": _sha256(json.dumps(receipts, indent=1).encode()), + "population_matrix_sha256": _sha256(matrix), + } + + +@pytest.fixture(scope="module") +def local_tool(): + return _load_tool("build_us_acs_local_release") + + +@pytest.mark.parametrize("soi_mode", sorted(PINNED_BYTES)) +def test_pinned_feed_local_surface_bytes_are_unchanged( + local_tool, soi_mode: str, tmp_path: Path +) -> None: + feed, ladder = _pinned_inputs() + assert ( + surface_bytes(local_tool, feed, ladder, soi_mode, tmp_path) + == (PINNED_BYTES[soi_mode]) + ) + + +def test_every_non_county_mode_is_pinned(local_tool) -> None: + assert set(PINNED_BYTES) == set(local_tool.SOI_MODES) - { + local_tool.county_surface.SOI_MODE + } + + +def test_the_supporting_households_cover_every_cell() -> None: + populations = {"state": {6: 1.0, 11: 1.0, 72: 1.0}, "cd": {601: 1.0, 1198: 1.0}} + households, sizes = _supporting_households(populations) + assert households.to_dict("records") == [ + {"state_fips": 6, "congressional_district_geoid": 601}, + {"state_fips": 11, "congressional_district_geoid": 1198}, + {"state_fips": 72, "congressional_district_geoid": 0}, + ] + assert sizes.tolist() == [1.0, 1.0, 1.0] From e3e483dbd39d68d4700301fe1929d4a278fd8dd7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:42:26 +0000 Subject: [PATCH 02/23] Let a cross-grain rule declare how a control is divided (allocator hook) microcosm#1760 moves the US share mechanisms to the shared cross-grain operator with the same bytes. The operator divides a control among its lower rows as row x control / numpy sum. The US rows sum with math.fsum and, for the county rows, use a residual rule. On the pinned US feed the numpy sum changes the last bit of 5,533 of 21,743 district values. CrossGrainRule gains one field, allocator, default None. With None the operator runs the standing rule: no float operation is added or removed. With an allocator, the operator calls it for each control and takes (values, factor, raw_sum) from it; the refusals and the closure check apply unchanged, and the leg receipt names the allocator. The file gains no import. The UK declares no allocator. The UK graph hashes this file, so the UK target nodes and the nodes after them compute again on the next UK run, with the same outputs. Proof: - test_support/microcosm_build/cross_grain_reference.py is the file at e29843dc7, pinned by sha256. test_cross_grain_allocator.py runs 400 seeded surfaces (with and without factor bounds) through both modules and compares the value bytes, the receipts and the refusal texts. It also checks that only CrossGrainRule and the reconcile function differ from the reference, and that the imports are the same. - The operator tests and the UK tests that use the operator pass unchanged. Co-Authored-By: Claude Fable 5.2 --- .../src/microcosm/build/cross_grain.py | 61 +- .../shared/test_cross_grain_allocator.py | 360 ++++ .../microcosm_build/cross_grain_reference.py | 1478 +++++++++++++++++ 3 files changed, 1896 insertions(+), 3 deletions(-) create mode 100644 packages/microcosm-build/tests/engine_free/shared/test_cross_grain_allocator.py create mode 100644 test_support/microcosm_build/cross_grain_reference.py diff --git a/packages/microcosm-build/src/microcosm/build/cross_grain.py b/packages/microcosm-build/src/microcosm/build/cross_grain.py index 301f1e955f..674887d59c 100644 --- a/packages/microcosm-build/src/microcosm/build/cross_grain.py +++ b/packages/microcosm-build/src/microcosm/build/cross_grain.py @@ -78,6 +78,17 @@ class CrossGrainRule: #: constituencies and authorities while a country row controls the legs no #: region row covers. control_grains: tuple[str, ...] = () + #: How one control's value is divided among its lower rows. ``None`` is + #: the standing rule: each row times the control over the rows' numpy + #: sum. An allocator takes the rows' values, in surface order, and the + #: control's value, and returns ``(values, factor, raw_sum)``: the + #: reconciled rows in the same order, and the factor and the lower-row + #: total that the leg receipt records. A country whose sources need + #: another summation or a residual rule declares one (microcosm#1760); + #: the refusals and the closure check below apply to it unchanged. + allocator: Callable[[np.ndarray, float], tuple[np.ndarray, float, float]] | None = ( + None + ) @dataclass(frozen=True) @@ -546,8 +557,15 @@ def _reconcile_cross_grain_surface_with_control_receipts( raw_values = reconciled.iloc[positions][columns["value"]].to_numpy( dtype=np.float64 ) - raw_sum = float(raw_values.sum()) parent_value = float(control["value"]) + if rule.allocator is None: + allocation = None + raw_sum = float(raw_values.sum()) + else: + allocation = _allocation( + rule.allocator, raw_values, parent_value, group.inconsistency_id + ) + raw_sum = allocation[2] if not np.isfinite(raw_sum) or not np.isfinite(parent_value): raise ValueError( f"cross-grain inconsistency {group.inconsistency_id!r} " @@ -565,7 +583,10 @@ def _reconcile_cross_grain_surface_with_control_receipts( # Live only when the control is itself zero (the floor above is # vacuous there): a zero-summing leg against a zero control is a # no-op, where `parent_value / raw_sum` would be 0/0. - factor = 1.0 if raw_sum == 0.0 else parent_value / raw_sum + if allocation is None: + factor = 1.0 if raw_sum == 0.0 else parent_value / raw_sum + else: + factor = allocation[1] if not np.isfinite(factor): raise ValueError( f"cross-grain inconsistency {group.inconsistency_id!r} " @@ -603,7 +624,7 @@ def _reconcile_cross_grain_surface_with_control_receipts( "longer measure one quantity." ) reconciled.iloc[positions, reconciled.columns.get_loc(columns["value"])] = ( - raw_values * factor + raw_values * factor if allocation is None else allocation[0] ) already.update(positions) new_total = float( @@ -639,6 +660,11 @@ def _reconcile_cross_grain_surface_with_control_receipts( 0.0 if raw_sum == 0.0 else (new_total - raw_sum) / raw_sum ), "declared_factor": factor, + **( + {} + if rule.allocator is None + else {"allocator": _allocator_name(rule.allocator)} + ), **( {} if bound is None @@ -1321,6 +1347,35 @@ def _control_positions( return positions +def _allocation( + allocator: Callable[[np.ndarray, float], tuple[np.ndarray, float, float]], + raw_values: np.ndarray, + parent_value: float, + inconsistency_id: str, +) -> tuple[np.ndarray, float, float]: + """One control's lower rows as the rule's declared allocator divides them. + + Returns ``(values, factor, raw_sum)``. A result that is not one value for + each row is refused here; the caller's refusals (a non-finite or vanishing + total, a negative factor, a total off its control) then read ``factor`` + and ``raw_sum`` as they read the standing rule's own. + """ + + values, factor, raw_sum = allocator(raw_values, parent_value) + values = np.asarray(values, dtype=np.float64) + if values.shape != raw_values.shape: + raise ValueError( + f"cross-grain inconsistency {inconsistency_id!r}: allocator " + f"{_allocator_name(allocator)!r} returned {values.shape} value(s) " + f"for {raw_values.shape} lower row(s)." + ) + return values, float(factor), float(raw_sum) + + +def _allocator_name(allocator: Callable[..., Any]) -> str: + return str(getattr(allocator, "__name__", type(allocator).__name__)) + + def _controls_agree(left: float, right: float) -> bool: return bool( np.isclose(float(left), float(right), rtol=_CONTROL_AGREEMENT_RTOL, atol=0.0) diff --git a/packages/microcosm-build/tests/engine_free/shared/test_cross_grain_allocator.py b/packages/microcosm-build/tests/engine_free/shared/test_cross_grain_allocator.py new file mode 100644 index 0000000000..ea6e4da683 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/shared/test_cross_grain_allocator.py @@ -0,0 +1,360 @@ +"""The allocator hook of the cross-grain operator (microcosm#1760). + +``CrossGrainRule.allocator`` lets a country declare how one control's value is +divided among its lower rows. The UK declares none, and the UK graph hashes +``cross_grain.py``, so the hook must leave the standing rule as it was: the +same values bit for bit, the same receipts and the same refusals. + +``test_support/microcosm_build/cross_grain_reference.py`` is the module as it +stood at ``e29843dc7``, before the hook; its sha256 is pinned here. The +differential test runs seeded random surfaces through both modules. When the +standing rule changes on purpose, delete the reference copy and the tests that +read it: they prove only that the hook changed nothing. +""" + +from __future__ import annotations + +import ast +import hashlib +import inspect +import json +import math + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build import cross_grain +from microcosm.build.cross_grain import ( + CrossGrainBridge, + CrossGrainRule, + apply_cross_grain_reconciliation, +) +from test_support.microcosm_build import cross_grain_reference +from test_support.paths import paths_for + +_TEST_PATHS = paths_for("microcosm-build") + +#: sha256 of ``cross_grain.py`` at ``e29843dc7``. +REFERENCE_SHA256 = "f61f83dd4577f322cfbc5a1276c4454c36877b56b2d480480ac74155623cd7f3" + +#: What the hook changed or added in the module; everything else is the +#: reference, source line for source line. +CHANGED = {"CrossGrainRule", "_reconcile_cross_grain_surface_with_control_receipts"} +ADDED = {"_allocation", "_allocator_name"} + +_LEGS = ("E", "W", "S", "N") + + +def test_the_reference_copy_is_the_operator_before_the_hook() -> None: + path = ( + _TEST_PATHS.repository + / "test_support" + / "microcosm_build" + / "cross_grain_reference.py" + ) + assert hashlib.sha256(path.read_bytes()).hexdigest() == REFERENCE_SHA256 + + +def _definitions(module) -> dict[str, str]: + tree = ast.parse(inspect.getsource(module)) + source = inspect.getsource(module) + return { + node.name: ast.get_source_segment(source, node) + for node in tree.body + if isinstance(node, ast.FunctionDef | ast.ClassDef) + } + + +def test_the_hook_touches_one_rule_field_and_one_function() -> None: + new, old = _definitions(cross_grain), _definitions(cross_grain_reference) + assert set(new) - set(old) == ADDED + assert set(old) - set(new) == set() + assert {name for name in old if new[name] != old[name]} == CHANGED + + +def _imports(module) -> list[str]: + return [ + ast.unparse(node) + for node in ast.parse(inspect.getsource(module)).body + if isinstance(node, ast.Import | ast.ImportFrom) + ] + + +def test_the_hook_adds_no_import() -> None: + """The UK graph hashes the modules a target module imports by name.""" + + assert _imports(cross_grain) == _imports(cross_grain_reference) + + +def _signature(concept: str) -> dict[str, object]: + return { + "measurement": { + "concept": concept, + "entity": "household", + "map_to": None, + "filters": [], + } + } + + +def _random_case(seed: int): + """A surface, its bound targets, signatures, rule arguments and licences. + + Three tiers (a country, regions as a middle control tier, two leaf + grains), several exact-signature concepts and one bounded bridge. Values + are sometimes signed, zero or missing on a leg, so the draws reach the + refusals as well as the rescaling. + """ + + rng = np.random.default_rng(seed) + legs = tuple(leg for leg in _LEGS if rng.random() < 0.85) or ("E",) + # A middle tier on every leg, on none, or (now and then) on some: the + # last is refused, since a partial tier would take the whole control. + tier = rng.random() + regions = ( + () + if tier < 0.45 + else legs + if tier < 0.9 + else tuple(leg for leg in legs if rng.random() < 0.6) + ) + rows: list[tuple[str, str, str, float]] = [] + signatures: dict[str, dict[str, object]] = {} + bound: list[str] = [] + licences: dict[str, frozenset[str]] = {} + + def value(scale: float) -> float: + draw = float(rng.lognormal(mean=math.log(scale), sigma=1.0)) + roll = rng.random() + if roll < 0.02: + return 0.0 + if roll < 0.06: + return -draw + return draw + + for index in range(int(rng.integers(1, 4))): + concept = f"concept_{index}" + national, local = f"national_{index}", f"local_{index}" + signatures[national] = _signature(concept) + signatures[local] = _signature(concept) + bound.append(national) + rows.append(("country", "UK", national, abs(value(1e6)) + 1.0)) + for region in regions: + if rng.random() < 0.97: + rows.append(("region", region, national, abs(value(2e5)) + 1.0)) + empty: set[str] = set() + for leg in legs: + if rng.random() < 0.05: + empty.add(leg) + continue + for grain in ("constituency", "la"): + for area in range(int(rng.integers(1, 5))): + rows.append((grain, f"{leg}{grain[0]}{area}", local, value(5e4))) + if rng.random() < 0.85: + licences[local] = frozenset(empty) + bridges: tuple[CrossGrainBridge, ...] = () + if rng.random() < 0.6: + shift = float(rng.choice([0.05, 0.5, 0.9])) + bridges = ( + CrossGrainBridge( + "bridged", + concept="bridged_concept", + higher_target_ids=("part_a", "part_b"), + lower_side="contract:bridged_local", + max_factor_shift=None if rng.random() < 0.3 else shift, + ), + ) + signatures["part_a"] = _signature("bridged_concept") + signatures["part_b"] = _signature("bridged_concept") + signatures["bridged_local"] = _signature("bridged_local_concept") + bound += ["part_a", "part_b"] + total = abs(value(1e6)) + 1.0 + split = float(rng.uniform(0.1, 0.9)) + rows.append(("country", "UK", "part_a", total * split)) + rows.append(("country", "UK", "part_b", total * (1.0 - split))) + target = total * float(rng.uniform(0.7, 1.3)) + areas = [f"{leg}c{index}" for leg in legs for index in range(3)] + shares = rng.dirichlet(np.ones(len(areas))) + rows += [ + ("constituency", area, "bridged_local", float(target * share)) + for area, share in zip(areas, shares, strict=True) + ] + order = rng.permutation(len(rows)) + surface = pd.DataFrame( + [rows[index] for index in order], + columns=["grain", "geography_id", "target_id", "value"], + ) + rule_arguments = { + "grain_precedence": ("country", "region", "constituency", "la"), + "signature_fields": ("concept", "entity", "map_to", "filters"), + "bridges": bridges, + "leg_of_area": lambda area: area[0], + "parent_geography_legs": {"UK": legs, **{leg: (leg,) for leg in regions}}, + "control_grains": ("country", "region") if regions else (), + } + return surface, tuple(bound), signatures, rule_arguments, licences + + +def _outcome(module, case, *, check_factor_bounds: bool): + surface, bound, signatures, rule_arguments, licences = case + bridges = tuple( + module.CrossGrainBridge( + bridge.bridge_id, + concept=bridge.concept, + higher_target_ids=bridge.higher_target_ids, + lower_side=bridge.lower_side, + max_factor_shift=bridge.max_factor_shift, + ) + for bridge in rule_arguments["bridges"] + ) + rule = module.CrossGrainRule(**{**rule_arguments, "bridges": bridges}) + try: + reconciled, receipt = module.apply_cross_grain_reconciliation( + surface, + bound, + signatures, + rule, + licensed_empty_legs=licences, + check_factor_bounds=check_factor_bounds, + ) + except ValueError as error: + return ("refused", str(error)) + return ( + "reconciled", + reconciled["value"].to_numpy(dtype=np.float64).tobytes(), + json.dumps(receipt, sort_keys=False), + ) + + +def test_the_default_path_is_the_operator_before_the_hook_bit_for_bit() -> None: + outcomes = {"reconciled": 0, "refused": 0} + rescaled_legs = 0 + for seed in range(400): + case = _random_case(seed) + for check_factor_bounds in (True, False): + new = _outcome(cross_grain, case, check_factor_bounds=check_factor_bounds) + old = _outcome( + cross_grain_reference, case, check_factor_bounds=check_factor_bounds + ) + assert new == old, seed + outcomes[new[0]] += 1 + if new[0] == "reconciled": + rescaled_legs += sum( + len(group["legs"]) for group in json.loads(new[2])["groups"] + ) + # The draws reach both the rescaling and the refusals. + assert outcomes["reconciled"] >= 200 + assert outcomes["refused"] >= 100 + assert rescaled_legs >= 1_000 + + +def _fsum_allocator(raw_values, parent_value): + raw_sum = math.fsum(raw_values.tolist()) + factor = 1.0 if raw_sum == 0.0 else parent_value / raw_sum + return raw_values * factor, factor, raw_sum + + +def _rule(allocator=None) -> CrossGrainRule: + return CrossGrainRule( + grain_precedence=("country", "constituency"), + signature_fields=("concept", "entity", "map_to", "filters"), + bridges=(), + leg_of_area=lambda area: area[0], + parent_geography_legs={"UK": ("E", "W")}, + allocator=allocator, + ) + + +def _surface(values) -> pd.DataFrame: + return pd.DataFrame( + [("country", "UK", "national", 120.0)] + + [ + ("constituency", f"E{index}", "local", value) + for index, value in enumerate(values) + ], + columns=["grain", "geography_id", "target_id", "value"], + ) + + +_SIGNATURES = {"national": _signature("households"), "local": _signature("households")} + + +def test_an_allocator_divides_the_control_and_the_receipt_names_it() -> None: + seen = [] + + def allocator(raw_values, parent_value): + seen.append((raw_values.tolist(), parent_value)) + return _fsum_allocator(raw_values, parent_value) + + surface = _surface([40.0, 20.0]) + reconciled, receipt = apply_cross_grain_reconciliation( + surface, ("national",), _SIGNATURES, _rule(allocator) + ) + + # The rows arrive in surface order with the control's value. + assert seen == [([40.0, 20.0], 120.0)] + assert reconciled["value"].tolist() == [120.0, 80.0, 40.0] + (leg,) = receipt["groups"][0]["legs"] + assert leg["old_total"] == 60.0 + assert leg["declared_factor"] == 2.0 + assert leg["new_total"] == 120.0 + assert leg["allocator"] == "allocator" + + +def test_the_standing_rule_writes_no_allocator_key() -> None: + _reconciled, receipt = apply_cross_grain_reconciliation( + _surface([40.0, 20.0]), ("national",), _SIGNATURES, _rule() + ) + (leg,) = receipt["groups"][0]["legs"] + assert "allocator" not in leg + + +def test_an_allocator_can_differ_from_the_numpy_sum_in_the_last_bit() -> None: + """Why the hook exists: an exactly rounded sum is another factor.""" + + rng = np.random.default_rng(1760) + for _attempt in range(200): + values = rng.lognormal(mean=10.0, sigma=2.0, size=37) + if math.fsum(values.tolist()) != float(values.sum()): + break + else: + pytest.fail("no draw separated fsum from the numpy sum") + surface = _surface(values.tolist()) + standing, _ = apply_cross_grain_reconciliation( + surface, ("national",), _SIGNATURES, _rule() + ) + allocated, receipt = apply_cross_grain_reconciliation( + surface, ("national",), _SIGNATURES, _rule(_fsum_allocator) + ) + assert ( + standing["value"].to_numpy().tobytes() + != allocated["value"].to_numpy().tobytes() + ) + (leg,) = receipt["groups"][0]["legs"] + assert leg["old_total"] == math.fsum(values.tolist()) + np.testing.assert_array_equal( + allocated["value"].to_numpy()[1:], + values * (120.0 / math.fsum(values.tolist())), + ) + + +@pytest.mark.parametrize( + ("allocator", "message"), + [ + (lambda raw, parent: (raw * 0.0, 1.0, 0.0), "vanishing lower-leg total"), + (lambda raw, parent: (-raw, -1.0, float(raw.sum())), "opposite-signed"), + (lambda raw, parent: (raw, 1.0, float(raw.sum())), "off its control"), + (lambda raw, parent: (raw[:1], 2.0, float(raw.sum())), "returned"), + ( + lambda raw, parent: (raw * math.nan, 2.0, float(raw.sum())), + "non-finite reconciled total", + ), + (lambda raw, parent: (raw * 2.0, math.inf, float(raw.sum())), "non-finite"), + ], +) +def test_the_operators_refusals_apply_to_an_allocator(allocator, message) -> None: + with pytest.raises(ValueError, match=message): + apply_cross_grain_reconciliation( + _surface([40.0, 20.0]), ("national",), _SIGNATURES, _rule(allocator) + ) diff --git a/test_support/microcosm_build/cross_grain_reference.py b/test_support/microcosm_build/cross_grain_reference.py new file mode 100644 index 0000000000..301f1e955f --- /dev/null +++ b/test_support/microcosm_build/cross_grain_reference.py @@ -0,0 +1,1478 @@ +"""Country-agnostic reconciliation of targets bound at multiple grains. + +The operator in this module changes target values, never loss weights. A +country supplies the measurement signature, explicit bridges for known +partition relationships, grain precedence, and geography-to-leg mappings. +""" + +from __future__ import annotations + +import hashlib +import json +from collections.abc import Callable, Iterable, Mapping +from dataclasses import dataclass +from typing import Any + +import numpy as np +import pandas as pd + +# Closure of a rescaled leg onto its control is the property this pass exists +# to establish, so it is asserted rather than assumed. The tolerance matches +# the frame kernel's mass-conservation bound (``_MASS_CONSERVE_RTOL``). +_CLOSURE_RTOL = 1e-9 +# A leg whose members cancel to near-nothing would yield an arbitrarily large +# factor, so the vanishing-total refusal is relative to the control rather than +# an exact-zero test. +_MIN_LEG_SUM_RTOL = 1e-9 +# Two controls over the same legs agree when they differ by summation order +# only: a control summed from member rows (a partition parent) and the same +# total read from one row can differ in the last bits. +_CONTROL_AGREEMENT_RTOL = 1e-12 +# Absent, null, and empty signature values are one canonical "unspecified", so +# two spellings of the same measurement cannot land in different groups. +_UNSPECIFIED = ("",) + + +@dataclass(frozen=True) +class CrossGrainBridge: + """Declare one higher-control partition as the identity of a lower side. + + By default the higher targets partition one control at each geography + (the UK household composition), so every one must be valued there. + ``per_geography`` declares instead that each higher target is the control + of the geography it sits at (each nation's household estimate over its + own legs, microcosm#1123): a geography then carries some of them only. + ``max_factor_shift``, when set, bounds each lower grain's total under a + control: the control over that grain's rows in all the legs it covers, as + given, before any group rescales them (under the GB Universal Credit + caseload, each grain's GB total). A factor further than that from one is + refused: the two sides would no longer measure one quantity. A grain + another group rescales first is still bounded, but the legs inside the + total are not bounded one by one: a group with no bound (an exact + signature group putting one leg's authorities on its constituencies) + rescales them by whatever factor it needs. The bound must lie in (0, 1): + at one or more it would accept every factor below one. + """ + + bridge_id: str + concept: str + higher_target_ids: tuple[str, ...] + lower_side: str + per_geography: bool = False + max_factor_shift: float | None = None + + +@dataclass(frozen=True) +class CrossGrainRule: + """All country-owned declarations needed by the shared operator.""" + + grain_precedence: tuple[str, ...] + signature_fields: tuple[str, ...] + bridges: tuple[CrossGrainBridge, ...] + leg_of_area: Callable[[str], str] + parent_geography_legs: Mapping[str, tuple[str, ...]] + #: Grains whose rows parent the grains below them. Empty means the top + #: grain alone (the standing single-winner rule). Declaring a middle tier + #: (a region between country and constituency) lets each lower leg take + #: its nearest covering control, so a region row controls its own + #: constituencies and authorities while a country row controls the legs no + #: region row covers. + control_grains: tuple[str, ...] = () + + +@dataclass(frozen=True) +class CrossGrainInconsistency: + """Detected rows for one winning-grain/lower-grain reconciliation.""" + + inconsistency_id: str + bridge_id: str | None + signature: tuple[tuple[str, Any], ...] + winning_grain: str + lower_grain: str + winning_positions: tuple[int, ...] + lower_positions: tuple[int, ...] + higher_target_ids: tuple[str, ...] + + +def detect_cross_grain_inconsistencies( + local_frame: pd.DataFrame, + bound_higher_targets: Iterable[str], + contract_signatures: Mapping[str, Mapping[str, Any]], + rule: CrossGrainRule, + *, + reviewed_unbound_higher_targets: Mapping[str, Mapping[str, object]] | None = None, + licensed_empty_legs: Mapping[str, frozenset[str]] | None = None, +) -> tuple[CrossGrainInconsistency, ...]: + """Detect exact-signature and explicitly bridged cross-grain groups. + + ``local_frame`` is a long target surface. It must expose ``value`` and + ``target_id`` plus either the canonical ``grain``/``geography_id`` columns + or the rowwise aliases ``area_type``/``area_code``. Contract sides may be + written as either ```` or ``contract:``. External + target sides are forbidden: every reconciled row belongs to the contract. + + A partially bound declared bridge is ignored only when every missing + higher member has a record in ``reviewed_unbound_higher_targets``. + """ + + columns = _surface_columns(local_frame) + _validate_rule(rule) + _validate_licensed_empty_legs(licensed_empty_legs) + bound = tuple(str(target_id) for target_id in bound_higher_targets) + _require_unique_nonblank(bound, label="bound_higher_targets") + unknown = sorted(set(bound) - set(contract_signatures)) + if unknown: + raise ValueError( + "cross-grain bound higher target(s) are absent from the contract: " + f"{unknown}." + ) + + bridge_by_side = _bridge_by_side(rule) + bound_set = set(bound) + unbound_bridge_ids = { + record["bridge_id"] + for record in _reviewed_unbound_bridges( + bound_set, + rule, + reviewed_unbound_higher_targets, + ) + } + + grouped: dict[ + tuple[str, str, tuple[tuple[str, Any], ...]], + list[tuple[int, str, str, str, float]], + ] = {} + seen_bound: set[str] = set() + values = local_frame[columns["value"]].to_numpy(dtype=np.float64) + if not np.isfinite(values).all(): + raise ValueError("cross-grain target values must all be finite.") + + for position, row in enumerate(local_frame.to_dict(orient="records")): + grain = str(row[columns["grain"]]) + geography_id = str(row[columns["geography_id"]]) + side = str(row[columns["target_id"]]) + if grain not in rule.grain_precedence: + raise ValueError( + f"cross-grain surface row {position} uses unknown grain " + f"{grain!r}; expected one of {rule.grain_precedence}." + ) + if not geography_id: + raise ValueError( + f"cross-grain surface row {position} has a blank geography id." + ) + bridge = bridge_by_side.get(side) + contract_id = _contract_target_id(side) + if bridge is None and contract_id is not None: + bridge = bridge_by_side.get(contract_id) + if bridge is None: + bridge = bridge_by_side.get(f"contract:{contract_id}") + if bridge is not None and bridge.bridge_id in unbound_bridge_ids: + bridge = None + + is_bound_higher = contract_id in bound_set + if grain in _control_grains(rule) and not is_bound_higher: + continue + if is_bound_higher: + seen_bound.add(contract_id) + + keys: list[tuple[str, str, tuple[tuple[str, Any], ...]]] = [] + if bridge is not None: + keys.append( + ( + "bridge", + bridge.bridge_id, + (("concept", _freeze(bridge.concept)),), + ) + ) + # A declared bridge is additive to exact-signature detection. This + # matters when one lower side has both a bridged control and a second, + # exact-signature partition (the UK UC case): both controls must be + # seen so incompatible same-grain values fail closed. + if contract_id is not None and contract_id in contract_signatures: + keys.append( + ( + "signature", + "", + _measurement_signature( + contract_signatures[contract_id], rule.signature_fields + ), + ) + ) + for key in dict.fromkeys(keys): + grouped.setdefault(key, []).append( + (position, grain, geography_id, side, float(values[position])) + ) + + missing_rows = sorted(bound_set - seen_bound) + if missing_rows: + raise ValueError( + "cross-grain bound higher target(s) have no value rows in the " + f"surface: {missing_rows}." + ) + + inconsistencies: list[CrossGrainInconsistency] = [] + precedence = {grain: index for index, grain in enumerate(rule.grain_precedence)} + control_grains = _control_grains(rule) + for (kind, bridge_id, signature), rows in grouped.items(): + grains = sorted({row[1] for row in rows}, key=precedence.__getitem__) + if len(grains) < 2: + continue + identity = _inconsistency_identity(kind, bridge_id, signature) + controls_present = [grain for grain in grains if grain in control_grains] + # A group with no control-tier row keeps the standing single-winner + # rule: its top grain parents the rest. With control rows present, + # every control grain parents each grain below it, and reconciliation + # assigns each lower leg to its nearest covering control. + pairs = ( + [(grains[0], lower) for lower in grains[1:]] + if not controls_present + else [ + (higher, lower) + for lower in grains + for higher in controls_present + if precedence[higher] < precedence[lower] + ] + ) + for winning_grain, lower_grain in pairs: + winning = tuple(row[0] for row in rows if row[1] == winning_grain) + higher_ids = tuple( + sorted( + { + target_id + for position in winning + if ( + target_id := _contract_target_id( + str(local_frame.iloc[position][columns["target_id"]]) + ) + ) + is not None + } + ) + ) + lower = tuple(row[0] for row in rows if row[1] == lower_grain) + inconsistencies.append( + CrossGrainInconsistency( + inconsistency_id=(f"{identity}:{winning_grain}_over_{lower_grain}"), + bridge_id=bridge_id or None, + signature=signature, + winning_grain=winning_grain, + lower_grain=lower_grain, + winning_positions=winning, + lower_positions=lower, + higher_target_ids=higher_ids, + ) + ) + # Lower grains reconcile top-down (a region row is rescaled to its country + # before it controls its authorities), and within one lower grain the + # nearest control grain claims first. + return tuple( + sorted( + inconsistencies, + key=lambda group: ( + precedence[group.lower_grain], + -precedence[group.winning_grain], + group.inconsistency_id, + ), + ) + ) + + +def _reconcile_cross_grain_surface_with_control_receipts( + local_frame: pd.DataFrame, + groups: Iterable[CrossGrainInconsistency], + rule: CrossGrainRule, + *, + licensed_empty_legs: Mapping[str, frozenset[str]] | None = None, + check_factor_bounds: bool = True, + frame_only_positions: frozenset[int] = frozenset(), +) -> tuple[ + pd.DataFrame, + list[dict[str, Any]], + list[dict[str, Any]], + list[dict[str, Any]], +]: + """Return a copied surface with every detected lower grain rescaled. + + ``frame_only_positions`` are rows that join the frame to take a share of + a control and bind nothing (a small-cell rule's deferred cells): a leg + holding only those, for targets licensed empty on it, needs no control. + """ + + columns = _surface_columns(local_frame) + _validate_rule(rule) + _validate_licensed_empty_legs(licensed_empty_legs) + materialized_groups = tuple(groups) + _assert_compatible_overlapping_groups( + local_frame, materialized_groups, columns, rule + ) + reconciled = local_frame.copy(deep=True) + receipts: list[dict[str, Any]] = [] + empty_legs_licensed: list[dict[str, Any]] = [] + controls_without_lower_rows: list[dict[str, Any]] = [] + delegated_legs: list[dict[str, Any]] = [] + control_grains = _control_grains(rule) + bridges_by_id = {bridge.bridge_id: bridge for bridge in rule.bridges} + # Rows already rescaled by a nearer control, per group identity and lower + # grain, so a farther control never rescales them again; and the rows no + # control has covered yet, checked once every pair has had its turn. + claimed: dict[tuple[str, str], set[int]] = {} + unparented_rows: dict[tuple[str, str], dict[int, str]] = {} + first_pair_id: dict[tuple[str, str], str] = {} + absent_middle_tier_legs: list[dict[str, Any]] = [] + deferred_legs_without_control: list[dict[str, Any]] = [] + pairs_per_key: dict[tuple[str, str], int] = {} + for group in materialized_groups: + key = (group.inconsistency_id.rsplit(":", 1)[0], group.lower_grain) + pairs_per_key[key] = pairs_per_key.get(key, 0) + 1 + pairs_seen: dict[tuple[str, str], int] = {} + # Per group identity, the targets on its leaf grains: a leg a middle tier + # leaves empty is genuinely empty only when every leaf target is licensed + # empty there too. + leaf_targets: dict[str, set[str]] = {} + for group in materialized_groups: + identity = group.inconsistency_id.rsplit(":", 1)[0] + bucket = leaf_targets.setdefault(identity, set()) + if group.lower_grain not in control_grains: + bucket.update( + str(reconciled.iloc[position][columns["target_id"]]) + for position in group.lower_positions + ) + for group in materialized_groups: + controls = _winning_controls(reconciled, group, columns, rule) + claim_key = (group.inconsistency_id.rsplit(":", 1)[0], group.lower_grain) + first_pair_id.setdefault(claim_key, group.inconsistency_id) + pairs_seen[claim_key] = pairs_seen.get(claim_key, 0) + 1 + last_pair_for_key = pairs_seen[claim_key] == pairs_per_key[claim_key] + already = claimed.setdefault(claim_key, set()) + lower_by_leg_all: dict[str, list[int]] = {} + lower_by_leg: dict[str, list[int]] = {} + row_legs: dict[int, tuple[str, ...]] = {} + for position in group.lower_positions: + area = str(reconciled.iloc[position][columns["geography_id"]]) + legs = _row_legs(area, rule) + if not legs: + raise ValueError( + f"cross-grain inconsistency {group.inconsistency_id!r} " + f"maps area {area!r} to a blank leg." + ) + row_legs[position] = legs + for leg in legs: + lower_by_leg_all.setdefault(leg, []).append(position) + if position not in already: + lower_by_leg.setdefault(leg, []).append(position) + + lower_target_ids = tuple( + sorted( + { + str(reconciled.iloc[position][columns["target_id"]]) + for position in group.lower_positions + } + ) + ) + assigned_controls: dict[str, dict[str, Any]] = {} + for control in controls: + for leg in control["covered_legs"]: + existing = assigned_controls.get(leg) + if existing is not None: + if existing["covered_legs"] != control[ + "covered_legs" + ] or not _controls_agree(existing["value"], control["value"]): + raise ValueError( + "cross-grain inconsistency " + f"{group.inconsistency_id!r} has two different " + f"control values at grain {group.winning_grain!r} " + f"for leg {leg!r}." + ) + continue + assigned_controls[leg] = control + + pending = unparented_rows.setdefault(claim_key, {}) + for leg in set(lower_by_leg) - set(assigned_controls): + for position in lower_by_leg[leg]: + pending[position] = leg + if last_pair_for_key and group.lower_grain not in control_grains: + # No farther control can still claim these leaf rows: refuse now, + # ahead of the empty-leg licence check, as the standing rule does. + # A leg only licensed-empty targets hold carries deferred cells + # alone and needs no control (_wholly_deferred_legs). + open_rows = { + position: leg + for position, leg in pending.items() + if position not in already and leg not in assigned_controls + } + unparented = sorted( + set(open_rows.values()) + - set( + _wholly_deferred_legs( + open_rows, + reconciled, + columns, + licensed_empty_legs, + frame_only_positions, + ) + ) + ) + if unparented: + raise ValueError( + f"cross-grain inconsistency {group.inconsistency_id!r} has " + f"unparented lower-grain leg(s) {unparented}." + ) + + populated_controls: list[dict[str, Any]] = [] + for control in controls: + positions = _control_positions( + control, lower_by_leg, row_legs, group.inconsistency_id + ) + delegated = [ + leg + for leg in control["covered_legs"] + if leg not in lower_by_leg and leg in lower_by_leg_all + ] + empty = [ + leg for leg in control["covered_legs"] if leg not in lower_by_leg_all + ] + if positions and delegated: + raise ValueError( + f"cross-grain inconsistency {group.inconsistency_id!r} " + f"control {control['parent_geography_id']!r} covers leg(s) " + f"{delegated} that a nearer control already reconciled " + "alongside legs it must still reconcile; a control cannot " + "be split across tiers." + ) + if positions and empty and group.lower_grain in control_grains: + # A middle tier present on some of the control's legs and on no + # row at all on the others would take the whole control onto + # the legs it covers. Only legs licensed empty for every leaf + # target (no data at any grain) may be left out. + identity = group.inconsistency_id.rsplit(":", 1)[0] + required = sorted(leaf_targets.get(identity) or lower_target_ids) + unlicensed_legs = sorted( + leg + for leg in empty + if any( + leg + not in _licensed_legs_for_target(target_id, licensed_empty_legs) + for target_id in required + ) + ) + if unlicensed_legs: + raise ValueError( + f"cross-grain inconsistency {group.inconsistency_id!r} " + f"control {control['parent_geography_id']!r} has rows at " + f"grain {group.lower_grain!r} on some legs and no row at " + f"that grain on {unlicensed_legs}, which are not licensed " + "empty; a partial tier would take the whole control onto " + "the legs it covers." + ) + if positions: + populated_controls.append(control) + continue + if delegated: + delegated_legs.append( + { + "inconsistency_id": group.inconsistency_id, + "parent_geography_id": str(control["parent_geography_id"]), + "legs": delegated, + "reason": ( + "every lower row on these legs was reconciled by a " + "nearer control grain" + ), + } + ) + if group.lower_grain in control_grains: + # A middle tier need not exist under every control: a country + # row with no region rows on its legs parents the leaf rows + # there directly. Not a licence matter. + if empty: + absent_middle_tier_legs.append( + { + "inconsistency_id": group.inconsistency_id, + "parent_geography_id": str(control["parent_geography_id"]), + "legs": empty, + } + ) + continue + if not empty: + continue + for leg in empty: + unlicensed = [ + target_id + for target_id in lower_target_ids + if leg + not in _licensed_legs_for_target( + target_id, + licensed_empty_legs, + ) + ] + if unlicensed: + raise ValueError( + f"cross-grain inconsistency {group.inconsistency_id!r} " + f"has an empty leg {leg!r} for parent geography " + f"{control['parent_geography_id']!r}; the leg lacks a " + f"licence for lower target(s) {unlicensed}." + ) + empty_legs_licensed.append( + { + "inconsistency_id": group.inconsistency_id, + "parent_geography_id": str(control["parent_geography_id"]), + "leg": leg, + "lower_target_ids": list(lower_target_ids), + } + ) + controls_without_lower_rows.append( + { + "inconsistency_id": group.inconsistency_id, + "parent_geography_id": str(control["parent_geography_id"]), + "covered_legs": list(control["covered_legs"]), + "higher_target_ids": list(control["higher_target_ids"]), + "lower_target_ids": list(lower_target_ids), + } + ) + controls = populated_controls + + leg_receipts: list[dict[str, Any]] = [] + used_controls: set[tuple[str, tuple[str, ...]]] = set() + for control in controls: + control_key = ( + str(control["parent_geography_id"]), + tuple(control["covered_legs"]), + ) + if control_key in used_controls: + continue + used_controls.add(control_key) + positions = _control_positions( + control, lower_by_leg, row_legs, group.inconsistency_id + ) + raw_values = reconciled.iloc[positions][columns["value"]].to_numpy( + dtype=np.float64 + ) + raw_sum = float(raw_values.sum()) + parent_value = float(control["value"]) + if not np.isfinite(raw_sum) or not np.isfinite(parent_value): + raise ValueError( + f"cross-grain inconsistency {group.inconsistency_id!r} " + "contains a non-finite leg total." + ) + # Offsetting members are legitimate for a net-valued concept, so + # only the conditioning matters: a leg that cancels to nothing + # against a nonzero control would rescale by an arbitrary factor. + if abs(raw_sum) < _MIN_LEG_SUM_RTOL * abs(parent_value): + raise ValueError( + f"cross-grain inconsistency {group.inconsistency_id!r} " + f"cannot scale a vanishing lower-leg total {raw_sum!r} to " + f"control {parent_value!r}." + ) + # Live only when the control is itself zero (the floor above is + # vacuous there): a zero-summing leg against a zero control is a + # no-op, where `parent_value / raw_sum` would be 0/0. + factor = 1.0 if raw_sum == 0.0 else parent_value / raw_sum + if not np.isfinite(factor): + raise ValueError( + f"cross-grain inconsistency {group.inconsistency_id!r} " + "produced a non-finite reconciliation factor." + ) + if factor < 0.0: + raise ValueError( + f"cross-grain inconsistency {group.inconsistency_id!r} " + "cannot reconcile opposite-signed lower and control targets." + ) + bridge = bridges_by_id.get(group.bridge_id or "") + bound = None if bridge is None else bridge.max_factor_shift + input_factor = None + if bound is not None: + # The bound reads the lower rows as given, not as an earlier + # group left them: an exact-signature group that rescales this + # grain onto a nearer tier first would leave a factor of one + # here whatever the input (microcosm#1302 review). + input_sum = float( + local_frame.iloc[positions][columns["value"]] + .to_numpy(dtype=np.float64) + .sum() + ) + if input_sum != 0.0: + input_factor = parent_value / input_sum + else: + input_factor = 1.0 if parent_value == 0.0 else float("inf") + if check_factor_bounds and not abs(input_factor - 1.0) <= bound: + raise ValueError( + f"cross-grain bridge {bridge.bridge_id!r} would scale the " + f"{group.lower_grain} rows of leg " + f"{'+'.join(control['covered_legs'])!r} by {input_factor!r} " + f"on their input totals, further than its declared " + f"max_factor_shift {bound} from one: the two sides no " + "longer measure one quantity." + ) + reconciled.iloc[positions, reconciled.columns.get_loc(columns["value"])] = ( + raw_values * factor + ) + already.update(positions) + new_total = float( + reconciled.iloc[positions][columns["value"]] + .to_numpy(dtype=np.float64) + .sum() + ) + if not np.isfinite(new_total): + raise ValueError( + f"cross-grain inconsistency {group.inconsistency_id!r} " + "produced a non-finite reconciled total." + ) + if not np.isclose(new_total, parent_value, rtol=_CLOSURE_RTOL, atol=0.0): + raise ValueError( + f"cross-grain inconsistency {group.inconsistency_id!r} " + f"left leg {'+'.join(control['covered_legs'])!r} off its " + f"control: reconciled total {new_total!r} against control " + f"{parent_value!r}." + ) + areas = { + str(reconciled.iloc[position][columns["geography_id"]]) + for position in positions + } + leg_receipts.append( + { + "leg": "+".join(control["covered_legs"]), + "parent_geography_id": str(control["parent_geography_id"]), + "higher_target_ids": list(control["higher_target_ids"]), + "n_areas": len(areas), + "old_total": raw_sum, + "new_total": new_total, + "relative_shift": ( + 0.0 if raw_sum == 0.0 else (new_total - raw_sum) / raw_sum + ), + "declared_factor": factor, + **( + {} + if bound is None + else { + "max_factor_shift": bound, + "factor_on_input_totals": input_factor, + "factor_bound_checked": check_factor_bounds, + } + ), + "reason": ( + "standing cross-grain rule: " + f"{group.winning_grain} controls {group.lower_grain}" + ), + } + ) + receipts.append( + { + "inconsistency_id": group.inconsistency_id, + "bridge_id": group.bridge_id, + "winning_grain": group.winning_grain, + "lower_grain": group.lower_grain, + "legs": leg_receipts, + } + ) + for (identity, lower_grain), pending in unparented_rows.items(): + if lower_grain in control_grains: + # A control-tier row with no control above it is the top of its + # own leg, not an orphan. + continue + open_rows = { + position: leg + for position, leg in pending.items() + if position not in claimed[(identity, lower_grain)] + } + deferred = _wholly_deferred_legs( + open_rows, reconciled, columns, licensed_empty_legs, frame_only_positions + ) + still = set(open_rows.values()) - set(deferred) + if still: + raise ValueError( + f"cross-grain inconsistency " + f"{first_pair_id[(identity, lower_grain)]!r} has " + f"unparented lower-grain leg(s) {sorted(still)}." + ) + deferred_legs_without_control.extend( + { + "inconsistency_id": first_pair_id[(identity, lower_grain)], + "lower_grain": lower_grain, + "leg": leg, + "lower_target_ids": list(target_ids), + } + for leg, target_ids in sorted(deferred.items()) + ) + return ( + reconciled, + receipts, + empty_legs_licensed, + controls_without_lower_rows, + delegated_legs, + absent_middle_tier_legs, + deferred_legs_without_control, + ) + + +def _wholly_deferred_legs( + rows: Mapping[int, str], + frame: pd.DataFrame, + columns: Mapping[str, str], + licensed_empty_legs: Mapping[str, frozenset[str]] | None, + frame_only_positions: frozenset[int], +) -> dict[str, tuple[str, ...]]: + """The legs of ``rows`` that hold deferred cells alone. + + A leg qualifies when every row on it is frame-only (it binds nothing and + joins the frame only to take its share of a control) and every target on + it is licensed empty there, so no cell of it binds on the leg. With no + control above them such rows have nothing to reconcile, and the leg is + no orphan (microcosm#1301: a region row signed out below the small-cell + floor leaves its wholly deferred authorities without one). A bound row, + or a row of a target the leg is not licensed for, keeps it an orphan. + """ + + targets_by_leg: dict[str, set[str]] = {} + bound_legs: set[str] = set() + for position, leg in rows.items(): + targets_by_leg.setdefault(leg, set()).add( + str(frame.iloc[position][columns["target_id"]]) + ) + if position not in frame_only_positions: + bound_legs.add(leg) + return { + leg: tuple(sorted(target_ids)) + for leg, target_ids in targets_by_leg.items() + if leg not in bound_legs + and all( + leg in _licensed_legs_for_target(target_id, licensed_empty_legs) + for target_id in target_ids + ) + } + + +def reconcile_cross_grain_surface( + local_frame: pd.DataFrame, + groups: Iterable[CrossGrainInconsistency], + rule: CrossGrainRule, + *, + licensed_empty_legs: Mapping[str, frozenset[str]] | None = None, + check_factor_bounds: bool = True, +) -> tuple[pd.DataFrame, list[dict[str, Any]]]: + """Return a copied surface with every detected lower grain rescaled.""" + + reconciled, receipts, *_ = _reconcile_cross_grain_surface_with_control_receipts( + local_frame, + groups, + rule, + licensed_empty_legs=licensed_empty_legs, + check_factor_bounds=check_factor_bounds, + ) + return reconciled, receipts + + +def apply_cross_grain_reconciliation( + local_frame: pd.DataFrame, + bound_higher_targets: Iterable[str], + contract_signatures: Mapping[str, Mapping[str, Any]], + rule: CrossGrainRule, + *, + reviewed_unbound_higher_targets: Mapping[str, Mapping[str, object]] | None = None, + licensed_empty_legs: Mapping[str, frozenset[str]] | None = None, + check_factor_bounds: bool = True, + frame_only_positions: Iterable[int] = (), +) -> tuple[pd.DataFrame, dict[str, Any]]: + """Detect, reconcile, and return the always-present pass receipt. + + ``check_factor_bounds=False`` records each bounded bridge's factor without + refusing it, for a pass that is not the caller's last (a surface whose + off-surface cells join a second pass is bounded on that one). + ``frame_only_positions`` names the rows that bind nothing (deferred + cells); a leg holding only those needs no control + (``deferred_legs_without_control``). + """ + + bound = tuple(str(target_id) for target_id in bound_higher_targets) + groups = detect_cross_grain_inconsistencies( + local_frame, + bound, + contract_signatures, + rule, + reviewed_unbound_higher_targets=reviewed_unbound_higher_targets, + licensed_empty_legs=licensed_empty_legs, + ) + unbound_bridges = _reviewed_unbound_bridges( + set(bound), + rule, + reviewed_unbound_higher_targets, + ) + ( + reconciled, + group_receipts, + empty_legs_licensed, + controls_without_lower_rows, + delegated_legs, + absent_middle_tier_legs, + deferred_legs_without_control, + ) = _reconcile_cross_grain_surface_with_control_receipts( + local_frame, + groups, + rule, + licensed_empty_legs=licensed_empty_legs, + check_factor_bounds=check_factor_bounds, + frame_only_positions=frozenset(int(p) for p in frame_only_positions), + ) + receipt = { + "bound_higher_targets": list(bound), + "factor_bounds_checked": check_factor_bounds, + "inconsistencies_in_force": [group.inconsistency_id for group in groups], + "groups": group_receipts, + "unbound_bridges": unbound_bridges, + "empty_legs_licensed": empty_legs_licensed, + "controls_without_lower_rows": controls_without_lower_rows, + "delegated_legs": delegated_legs, + "absent_middle_tier_legs": absent_middle_tier_legs, + "deferred_legs_without_control": deferred_legs_without_control, + "absence": ( + None + if groups + else "No cross-grain inconsistencies are in force on this surface." + ), + } + return reconciled, receipt + + +PARTITION_KINDS = ("exhaustive", "share_of_parent") + + +@dataclass(frozen=True) +class CrossGrainPartition: + """Member targets that divide one parent target at the same geography. + + ``exhaustive``: the members sum to the parent, so they are rescaled jointly + onto it (council-tax bands onto the authority's total). ``share_of_parent``: + the members cover part of the parent (tenure categories the census also + splits into shared ownership and rent-free), so they move by the parent's + own reconciliation factor and keep their shares. + """ + + partition_id: str + parent_target_id: str + member_target_ids: tuple[str, ...] + kind: str = "exhaustive" + + +def apply_cross_grain_partitions( + raw_frame: pd.DataFrame, + reconciled_frame: pd.DataFrame, + partitions: Iterable[CrossGrainPartition], +) -> tuple[pd.DataFrame, dict[str, Any]]: + """Rescale each partition's members onto their reconciled parent. + + Runs after :func:`apply_cross_grain_reconciliation`: ``raw_frame`` is its + input and ``reconciled_frame`` its output, row for row, so a + ``share_of_parent`` partition reads the parent's own factor. A geography + with the parent and no members is recorded; one with some members but not + all is refused, since rescaling a partial set onto the whole parent would + move the missing members' mass onto the present ones. + """ + + columns = _surface_columns(reconciled_frame) + if len(raw_frame) != len(reconciled_frame): + raise ValueError("cross-grain partitions need the raw and reconciled surface.") + partitions = tuple(partitions) + _validate_partitions(partitions) + out = reconciled_frame.copy(deep=True) + value_column = out.columns.get_loc(columns["value"]) + raw_values = raw_frame[columns["value"]].to_numpy(dtype=np.float64) + target_ids = [ + _contract_target_id(str(value)) for value in out[columns["target_id"]] + ] + cells: dict[tuple[str, str], dict[str, list[int]]] = {} + for position, (grain, geography_id, target_id) in enumerate( + zip( + out[columns["grain"]], out[columns["geography_id"]], target_ids, strict=True + ) + ): + cells.setdefault((str(grain), str(geography_id)), {}).setdefault( + target_id, [] + ).append(position) + receipts: list[dict[str, Any]] = [] + parents_without_members: list[dict[str, Any]] = [] + for partition in partitions: + legs: list[dict[str, Any]] = [] + for (grain, geography_id), by_target in sorted(cells.items()): + parent_rows = by_target.get(partition.parent_target_id, []) + if not parent_rows: + continue + if len(parent_rows) != 1: + raise ValueError( + f"cross-grain partition {partition.partition_id!r} has " + f"{len(parent_rows)} parent rows at {geography_id!r}." + ) + present = [ + member for member in partition.member_target_ids if member in by_target + ] + if not present: + parents_without_members.append( + { + "partition_id": partition.partition_id, + "grain": grain, + "geography_id": geography_id, + } + ) + continue + if len(present) != len(partition.member_target_ids): + missing = sorted(set(partition.member_target_ids) - set(present)) + raise ValueError( + f"cross-grain partition {partition.partition_id!r} at " + f"{geography_id!r} lacks member(s) {missing}." + ) + positions = [ + position for member in present for position in by_target[member] + ] + parent = parent_rows[0] + parent_value = float(out.iloc[parent][columns["value"]]) + member_values = out.iloc[positions][columns["value"]].to_numpy( + dtype=np.float64 + ) + old_total = float(member_values.sum()) + if partition.kind == "exhaustive": + if abs(old_total) < _MIN_LEG_SUM_RTOL * abs(parent_value): + raise ValueError( + f"cross-grain partition {partition.partition_id!r} at " + f"{geography_id!r} cannot scale a vanishing member total." + ) + factor = 1.0 if old_total == 0.0 else parent_value / old_total + expected_total = parent_value + else: + raw_parent = float(raw_values[parent]) + if raw_parent == 0.0: + factor = 1.0 + else: + factor = parent_value / raw_parent + expected_total = old_total * factor + if not np.isfinite(factor) or factor < 0.0: + raise ValueError( + f"cross-grain partition {partition.partition_id!r} at " + f"{geography_id!r} produced factor {factor!r}." + ) + out.iloc[positions, value_column] = member_values * factor + new_total = float( + out.iloc[positions][columns["value"]].to_numpy(dtype=np.float64).sum() + ) + if not np.isclose(new_total, expected_total, rtol=_CLOSURE_RTOL, atol=0.0): + raise ValueError( + f"cross-grain partition {partition.partition_id!r} left " + f"{geography_id!r} at {new_total!r} against {expected_total!r}." + ) + legs.append( + { + "grain": grain, + "geography_id": geography_id, + "parent_value": parent_value, + "old_total": old_total, + "new_total": new_total, + "declared_factor": factor, + } + ) + receipts.append( + { + "partition_id": partition.partition_id, + "kind": partition.kind, + "parent_target_id": partition.parent_target_id, + "member_target_ids": list(partition.member_target_ids), + "cells": legs, + } + ) + return out, { + "partitions": receipts, + "parents_without_members": parents_without_members, + } + + +def _validate_partitions(partitions: tuple[CrossGrainPartition, ...]) -> None: + _require_unique_nonblank( + tuple(partition.partition_id for partition in partitions), + label="partition ids", + ) + for partition in partitions: + if partition.kind not in PARTITION_KINDS: + raise ValueError( + f"cross-grain partition {partition.partition_id!r} has unknown " + f"kind {partition.kind!r}; expected one of {PARTITION_KINDS}." + ) + if not partition.parent_target_id or not partition.member_target_ids: + raise ValueError( + f"cross-grain partition {partition.partition_id!r} has a blank " + "parent or no members." + ) + _require_unique_nonblank( + partition.member_target_ids, + label=f"partition {partition.partition_id!r} members", + ) + if partition.parent_target_id in partition.member_target_ids: + raise ValueError( + f"cross-grain partition {partition.partition_id!r} lists its " + "parent as a member." + ) + + +def _reviewed_unbound_bridges( + bound_higher_targets: set[str], + rule: CrossGrainRule, + reviewed_unbound_higher_targets: Mapping[str, Mapping[str, object]] | None, +) -> list[dict[str, Any]]: + reviewed = reviewed_unbound_higher_targets or {} + unbound: list[dict[str, Any]] = [] + for bridge in rule.bridges: + higher = set(bridge.higher_target_ids) + selected = bound_higher_targets & higher + if not selected or selected == higher: + continue + missing = sorted(higher - selected) + unreviewed = [target_id for target_id in missing if target_id not in reviewed] + if unreviewed: + raise ValueError( + f"cross-grain bridge {bridge.bridge_id!r} is partially bound; " + f"missing higher target(s) {missing}; missing target(s) that " + f"lack a reviewed exclusion: {unreviewed}." + ) + unbound.append( + { + "bridge_id": bridge.bridge_id, + "missing": missing, + "basis": "reviewed_exclusion", + "records": { + target_id: dict(reviewed[target_id]) for target_id in missing + }, + } + ) + return unbound + + +def _surface_columns(frame: pd.DataFrame) -> dict[str, str]: + aliases = { + "grain": ("grain", "area_type"), + "geography_id": ("geography_id", "area_code"), + "target_id": ("target_id",), + "value": ("value",), + } + resolved: dict[str, str] = {} + for canonical, candidates in aliases.items(): + present = [candidate for candidate in candidates if candidate in frame.columns] + if not present: + raise ValueError( + f"cross-grain surface must expose {canonical!r}; accepted " + f"column name(s): {list(candidates)}." + ) + resolved[canonical] = present[0] + return resolved + + +def _control_grains(rule: CrossGrainRule) -> tuple[str, ...]: + return tuple(rule.control_grains) or (rule.grain_precedence[0],) + + +def _validate_rule(rule: CrossGrainRule) -> None: + _require_unique_nonblank(rule.grain_precedence, label="grain_precedence") + if rule.control_grains: + _require_unique_nonblank(rule.control_grains, label="control_grains") + unknown = [g for g in rule.control_grains if g not in rule.grain_precedence] + if unknown: + raise ValueError( + f"cross-grain control_grains {unknown} are not in grain_precedence." + ) + if rule.grain_precedence[0] not in rule.control_grains: + raise ValueError( + "cross-grain control_grains must include the top grain " + f"{rule.grain_precedence[0]!r}." + ) + _require_unique_nonblank(rule.signature_fields, label="signature_fields") + if not rule.grain_precedence: + raise ValueError("cross-grain grain_precedence must not be empty.") + bridge_ids = tuple(bridge.bridge_id for bridge in rule.bridges) + _require_unique_nonblank(bridge_ids, label="bridge ids") + _bridge_by_side(rule) + for bridge in rule.bridges: + if not bridge.concept or not bridge.lower_side: + raise ValueError( + f"cross-grain bridge {bridge.bridge_id!r} has a blank declaration." + ) + _require_unique_nonblank( + bridge.higher_target_ids, + label=f"bridge {bridge.bridge_id!r} higher_target_ids", + ) + if not bridge.higher_target_ids: + raise ValueError( + f"cross-grain bridge {bridge.bridge_id!r} has no higher targets." + ) + external_sides = [ + side + for side in (*bridge.higher_target_ids, bridge.lower_side) + if side.startswith("external:") + ] + if external_sides: + raise ValueError( + f"cross-grain bridge {bridge.bridge_id!r} uses forbidden " + f"external side(s) {external_sides}; all sides must be contract targets." + ) + bound = bridge.max_factor_shift + if bound is not None and ( + isinstance(bound, bool) + or not isinstance(bound, int | float) + or not 0.0 < bound < 1.0 + ): + raise ValueError( + f"cross-grain bridge {bridge.bridge_id!r} declares max_factor_shift " + f"{bound!r}; a bound must be a number in (0, 1): at one or more " + "it would accept every factor below one." + ) + for geography_id, legs in rule.parent_geography_legs.items(): + if not str(geography_id) or not legs or any(not str(leg) for leg in legs): + raise ValueError( + "cross-grain parent_geography_legs must map nonblank geography " + "ids to nonempty, nonblank leg tuples." + ) + if len(set(legs)) != len(legs): + raise ValueError( + f"cross-grain parent geography {geography_id!r} repeats a leg." + ) + + +def _bridge_by_side(rule: CrossGrainRule) -> dict[str, CrossGrainBridge]: + result: dict[str, CrossGrainBridge] = {} + for bridge in rule.bridges: + sides = (*bridge.higher_target_ids, bridge.lower_side) + for side in sides: + canonical = side.removeprefix("contract:") + aliases = {canonical, f"contract:{canonical}"} + for alias in aliases: + existing = result.get(alias) + if existing is not None and existing.bridge_id != bridge.bridge_id: + raise ValueError( + f"cross-grain target side {side!r} is matched by two " + f"bridges: {existing.bridge_id!r} and {bridge.bridge_id!r}." + ) + result[alias] = bridge + return result + + +def _measurement_signature( + contract: Mapping[str, Any], fields: tuple[str, ...] +) -> tuple[tuple[str, Any], ...]: + """Canonicalize one contract entry's measurement into a grouping key. + + A signature field that is absent, null, or an empty container collapses to + one canonical "unspecified" value: two spellings of the same measurement + must never land in different groups, because a silent split lets the joint + solve reconcile the pair implicitly. Sequence-valued fields are compared + as unordered collections, since a filter list is a conjunction. + """ + + measurement = contract.get("measurement") + if measurement is None: + raise ValueError( + "cross-grain contract entry must carry a 'measurement' mapping; " + "a top-level fallback would let two contract spellings of the same " + f"measurement split silently. Got keys {sorted(contract)}." + ) + if not isinstance(measurement, Mapping): + raise ValueError("cross-grain contract measurement must be a mapping.") + return tuple( + (field, _canonical_signature_value(measurement.get(field))) for field in fields + ) + + +def _canonical_signature_value(value: Any) -> Any: + frozen = _freeze(value) + if frozen is None or frozen == () or frozen == "": + return _UNSPECIFIED + if isinstance(value, (list, tuple, set, frozenset)): + # Order-insensitive at this level only: a signature field holding a + # sequence is a conjunction (the filter list), so its members are the + # same measurement however the contract orders them. Ordering *inside* + # a member stays significant — a `between` payload's bounds are data, + # not a conjunction — so `_freeze` below is order-preserving. + return tuple(sorted(frozen, key=_sort_key)) + return frozen + + +def _sort_key(member: Any) -> str: + return json.dumps(_json_safe(member), sort_keys=True, separators=(",", ":")) + + +def _freeze(value: Any) -> Any: + if isinstance(value, Mapping): + return tuple( + sorted((str(key), _freeze(member)) for key, member in value.items()) + ) + if isinstance(value, (set, frozenset)): + # A set has no order to preserve; sort for a deterministic signature. + return tuple(sorted((_freeze(member) for member in value), key=_sort_key)) + if isinstance(value, (list, tuple)): + return tuple(_freeze(member) for member in value) + if isinstance(value, np.generic): + value = value.item() + if isinstance(value, bool): + return value + if isinstance(value, (int, float)): + # 0 and 0.0 are the same signature value; keep one numeric spelling. + return float(value) + return value + + +def _contract_target_id(side: str) -> str: + if side.startswith("external:"): + raise ValueError( + f"cross-grain target side {side!r} is external; every side must " + "name a contract target." + ) + return side.removeprefix("contract:") + + +def _validate_licensed_empty_legs( + licensed_empty_legs: Mapping[str, frozenset[str]] | None, +) -> None: + if licensed_empty_legs is None: + return + if not isinstance(licensed_empty_legs, Mapping): + raise TypeError("licensed_empty_legs must be a mapping.") + for target_id, legs in licensed_empty_legs.items(): + if not isinstance(target_id, str) or not target_id.strip(): + raise ValueError("licensed_empty_legs target ids must be nonblank strings.") + if not isinstance(legs, frozenset): + raise TypeError(f"licensed_empty_legs[{target_id!r}] must be a frozenset.") + if any(not isinstance(leg, str) or not leg.strip() for leg in legs): + raise ValueError( + f"licensed_empty_legs[{target_id!r}] must contain nonblank strings." + ) + + +def _licensed_legs_for_target( + target_id: str, + licensed_empty_legs: Mapping[str, frozenset[str]] | None, +) -> frozenset[str]: + if licensed_empty_legs is None: + return frozenset() + canonical = _contract_target_id(target_id) + aliases = {target_id} + if canonical is not None: + aliases.update((canonical, f"contract:{canonical}")) + return frozenset( + leg for alias in aliases for leg in licensed_empty_legs.get(alias, frozenset()) + ) + + +def _inconsistency_identity( + kind: str, + bridge_id: str, + signature: tuple[tuple[str, Any], ...], +) -> str: + if kind == "bridge": + return bridge_id + payload = json.dumps(_json_safe(signature), sort_keys=True, separators=(",", ":")) + digest = hashlib.sha256(payload.encode()).hexdigest()[:12] + concept = next( + (str(value) for field, value in signature if field == "concept"), "target" + ) + return f"exact:{concept}:{digest}" + + +def _json_safe(value: Any) -> Any: + if isinstance(value, tuple): + return [_json_safe(member) for member in value] + if isinstance(value, Mapping): + return {str(key): _json_safe(member) for key, member in value.items()} + return value + + +def _row_legs(geography_id: str, rule: CrossGrainRule) -> tuple[str, ...]: + """The legs one lower row covers. + + A row on a declared parent geography covers that geography's legs, so a + nation row (England) sits under a country control across all of its + regions; any other row covers the one leg its area maps to. + """ + + declared = rule.parent_geography_legs.get(geography_id) + if declared is not None: + return tuple(str(leg) for leg in declared) + leg = str(rule.leg_of_area(geography_id)) + return (leg,) if leg else () + + +def _control_positions( + control: Mapping[str, Any], + lower_by_leg: Mapping[str, list[int]], + row_legs: Mapping[int, tuple[str, ...]], + inconsistency_id: str, +) -> list[int]: + """The unclaimed lower rows on a control's legs, each once. + + A row whose legs are not all inside the control's would be rescaled by a + factor computed for a different total, so it is refused. + """ + + covered = tuple(control["covered_legs"]) + positions = list( + dict.fromkeys( + position for leg in covered for position in lower_by_leg.get(leg, ()) + ) + ) + for position in positions: + outside = sorted(set(row_legs[position]) - set(covered)) + if outside: + raise ValueError( + f"cross-grain inconsistency {inconsistency_id!r}: a lower row " + f"spans leg(s) {outside} outside control " + f"{control['parent_geography_id']!r}; a row must sit inside one " + "control." + ) + return positions + + +def _controls_agree(left: float, right: float) -> bool: + return bool( + np.isclose(float(left), float(right), rtol=_CONTROL_AGREEMENT_RTOL, atol=0.0) + ) + + +def _winning_controls( + frame: pd.DataFrame, + group: CrossGrainInconsistency, + columns: Mapping[str, str], + rule: CrossGrainRule, +) -> list[dict[str, Any]]: + rows = [ + { + "position": position, + "geography_id": str(frame.iloc[position][columns["geography_id"]]), + "target_id": str(frame.iloc[position][columns["target_id"]]), + "value": float(frame.iloc[position][columns["value"]]), + } + for position in group.winning_positions + ] + # A winning row whose geography declares its legs is a parent control in + # its own right, whatever grain it sits at: the top grain always is, and a + # middle tier (a region between country and constituency) is when the + # country declares a leg map for every one of its codes. Rows with no + # declared legs stay on the area-derived path below. + declared_parents = group.winning_grain == rule.grain_precedence[0] or all( + row["geography_id"] in rule.parent_geography_legs for row in rows + ) + if declared_parents: + by_geography: dict[str, list[dict[str, Any]]] = {} + for row in rows: + by_geography.setdefault(row["geography_id"], []).append(row) + controls = [] + for geography_id, members in sorted(by_geography.items()): + deduplicated: dict[str, float] = {} + for member in members: + target_id = _contract_target_id(member["target_id"]) + if target_id is None: + raise ValueError( + f"cross-grain winning row {member['target_id']!r} is not " + "a contract target." + ) + existing = deduplicated.get(target_id) + if existing is not None and existing != member["value"]: + raise ValueError( + f"cross-grain target {target_id!r} has two different " + f"control values at {geography_id!r}." + ) + deduplicated[target_id] = member["value"] + if group.bridge_id is not None: + bridge = next( + bridge + for bridge in rule.bridges + if bridge.bridge_id == group.bridge_id + ) + missing = sorted(set(bridge.higher_target_ids) - set(deduplicated)) + if missing and not bridge.per_geography: + raise ValueError( + f"cross-grain bridge {bridge.bridge_id!r} is partially " + f"valued at {geography_id!r}; missing {missing}." + ) + covered_legs = rule.parent_geography_legs.get(geography_id) + if covered_legs is None: + raise ValueError( + f"cross-grain parent geography {geography_id!r} declares no legs." + ) + controls.append( + { + "parent_geography_id": geography_id, + "covered_legs": tuple(covered_legs), + "higher_target_ids": tuple(sorted(deduplicated)), + "value": float(sum(deduplicated.values())), + } + ) + return controls + + by_leg: dict[str, list[dict[str, Any]]] = {} + for row in rows: + leg = str(rule.leg_of_area(row["geography_id"])) + if not leg: + raise ValueError( + f"cross-grain winning area {row['geography_id']!r} maps to a blank leg." + ) + by_leg.setdefault(leg, []).append(row) + return [ + { + "parent_geography_id": f"area-derived:{leg}", + "covered_legs": (leg,), + "higher_target_ids": tuple( + sorted( + { + target_id + for member in members + if (target_id := _contract_target_id(member["target_id"])) + is not None + } + ) + ), + "value": float(sum(member["value"] for member in members)), + } + for leg, members in sorted(by_leg.items()) + ] + + +def _assert_compatible_overlapping_groups( + frame: pd.DataFrame, + groups: tuple[CrossGrainInconsistency, ...], + columns: Mapping[str, str], + rule: CrossGrainRule, +) -> None: + """Refuse competing same-grain controls over any shared lower row.""" + + for index, left in enumerate(groups): + left_positions = set(left.lower_positions) + left_controls = _winning_controls(frame, left, columns, rule) + for right in groups[index + 1 :]: + if left.winning_grain != right.winning_grain: + continue + if not (left_positions & set(right.lower_positions)): + continue + right_controls = _winning_controls(frame, right, columns, rule) + left_by_coverage = { + tuple(control["covered_legs"]): float(control["value"]) + for control in left_controls + } + right_by_coverage = { + tuple(control["covered_legs"]): float(control["value"]) + for control in right_controls + } + for coverage in set(left_by_coverage) & set(right_by_coverage): + if not _controls_agree( + left_by_coverage[coverage], right_by_coverage[coverage] + ): + raise ValueError( + "cross-grain groups " + f"{left.inconsistency_id!r} and " + f"{right.inconsistency_id!r} have two different " + f"control values at grain {left.winning_grain!r} " + f"for legs {coverage}." + ) + + +def _require_unique_nonblank(values: Iterable[str], *, label: str) -> None: + materialized = tuple(str(value) for value in values) + blanks = [value for value in materialized if not value] + if blanks: + raise ValueError(f"cross-grain {label} must not contain blank values.") + duplicates = sorted( + {value for value in materialized if materialized.count(value) > 1} + ) + if duplicates: + raise ValueError( + f"cross-grain {label} must be unique; duplicate(s) {duplicates}." + ) From bc8aa6ae1dbbe5d1c330916b158e451ca3427f06 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:45:00 +0000 Subject: [PATCH 03/23] Add the shared controls module beside the cross-grain operator microcosm.build.cross_grain_controls holds what a country's sources can need around the operator (microcosm#1760). It is plain arithmetic on values and keys, with no country in it: - allocators for CrossGrainRule.allocator: proportional_fsum (the standing rule with an exactly rounded sum), and share_residual_to_largest and scale_residual_to_largest, which reproduce rows first made outside the operator and are marked for replacement in Stage B; - derived controls: sum_of_lower_rows and scaled_by_sibling_ratio; - the factor band: control_ratio, level_ratio, median_by_group, band_verdict; - completeness: leg_completeness, with declared combined cells; - self-consistency: sum_gap. The operator does not import the module, so the UK graph does not hash it. No caller uses it yet. Proof: test_cross_grain_controls.py holds each allocator, bit for bit, to the arithmetic it replaces on 200 seeded blocks, runs each one through the operator, and checks the helpers and that the module names no country. Co-Authored-By: Claude Fable 5.2 --- .../microcosm/build/cross_grain_controls.py | 337 ++++++++++++++++++ .../shared/test_cross_grain_controls.py | 320 +++++++++++++++++ 2 files changed, 657 insertions(+) create mode 100644 packages/microcosm-build/src/microcosm/build/cross_grain_controls.py create mode 100644 packages/microcosm-build/tests/engine_free/shared/test_cross_grain_controls.py diff --git a/packages/microcosm-build/src/microcosm/build/cross_grain_controls.py b/packages/microcosm-build/src/microcosm/build/cross_grain_controls.py new file mode 100644 index 0000000000..7edec120dd --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/cross_grain_controls.py @@ -0,0 +1,337 @@ +"""Controls, allocators and checks that sit beside the cross-grain operator. + +:mod:`microcosm.build.cross_grain` groups the rows of one quantity, finds the +control of each lower leg, divides the control among the leg's rows, checks +the sum and writes the receipt. A country's sources can need more than that +around the same job (microcosm#1760): + +- **allocators**: another way to divide a control among its rows than the + operator's standing rule. A country names one in its declarations and passes + it as ``CrossGrainRule.allocator``; +- **derived controls**: a control that no source publishes as one row, computed + before the operator runs and placed on the surface as the control row; +- **the factor band**: how far one control's ratio to its lower rows may sit + from the median ratio across the controls of the same quantity; +- **completeness**: whether a leg holds exactly the members it must, with + declared combined cells; +- **self-consistency**: a source's own total against the sum of its own lower + rows. + +Every function here is plain arithmetic on values and keys. None knows a +country, a source or a geography: the caller's declarations supply them. The +operator does not import this module, so the graphs that hash the operator do +not hash it. +""" + +from __future__ import annotations + +import math +from collections.abc import Callable, Hashable, Iterable, Mapping +from dataclasses import dataclass + +import numpy as np + +#: ``(values, factor, raw_sum)``, as ``CrossGrainRule.allocator`` returns it. +Allocation = tuple[np.ndarray, float, float] +Allocator = Callable[[np.ndarray, float], Allocation] + + +# --------------------------------------------------------------------------- +# Allocators +# --------------------------------------------------------------------------- + + +def proportional_fsum(raw_values: np.ndarray, parent_value: float) -> Allocation: + """Each row times the control over the rows' exactly rounded sum. + + The operator's standing rule with ``math.fsum`` in place of the numpy + sum, so the factor does not depend on the order of the rows. A zero total + keeps the rows (factor one), as the standing rule does. + """ + + raw_sum = math.fsum(raw_values.tolist()) + factor = 1.0 if raw_sum == 0.0 else parent_value / raw_sum + return raw_values * factor, factor, raw_sum + + +def residual_shares(raw_values: Iterable[float]) -> tuple[list[float], float, int]: + """Each value's share of the exactly rounded total, summing to one. + + Returns ``(shares, total, largest)``. The shares' rounding residual goes + to the largest share (the first of equal largest shares), never to a small + row. The total must not be zero. + """ + + values = [float(value) for value in raw_values] + total = math.fsum(values) + shares = [value / total for value in values] + largest = max(range(len(values)), key=lambda index: shares[index]) + shares[largest] += 1.0 - math.fsum(shares) + return shares, total, largest + + +def share_residual_to_largest( + raw_values: np.ndarray, parent_value: float +) -> Allocation: + """The control times each row's share, with two residual steps. + + The shares come from :func:`residual_shares`; the products' rounding + residual goes to the same largest row, so the rows sum to the control + exactly under ``math.fsum``. The recorded factor is the control over the + rows' total; no single factor reproduces the rows. + + This allocator and :func:`scale_residual_to_largest` reproduce, bit for + bit, rows that were first made outside the operator. Stage B of + microcosm#1760 replaces the two with one allocator. + """ + + if math.fsum(raw_values.tolist()) == 0.0: + return raw_values.copy(), 1.0, 0.0 + shares, total, largest = residual_shares(raw_values.tolist()) + values = [parent_value * share for share in shares] + values[largest] += parent_value - math.fsum(values) + return np.asarray(values, dtype=np.float64), parent_value / total, total + + +def scale_residual_to_largest( + raw_values: np.ndarray, parent_value: float +) -> Allocation: + """The control times each row over the rows' total, with one residual step. + + Multiply first, then divide; the rounding residual goes to the largest + scaled row (the first of equal largest rows). The recorded factor is the + control over the rows' total. + + See :func:`share_residual_to_largest` for why this allocator exists. + """ + + raw = raw_values.tolist() + total = math.fsum(raw) + if total == 0.0: + return raw_values.copy(), 1.0, 0.0 + values = [parent_value * value / total for value in raw] + largest = max(range(len(values)), key=lambda index: values[index]) + values[largest] += parent_value - math.fsum(values) + return np.asarray(values, dtype=np.float64), parent_value / total, total + + +#: The allocators a declaration can name. +ALLOCATORS: Mapping[str, Allocator] = { + allocator.__name__: allocator + for allocator in ( + proportional_fsum, + share_residual_to_largest, + scale_residual_to_largest, + ) +} + + +def allocator_named(name: str) -> Allocator: + """The allocator a declaration names; an unknown name is refused.""" + + try: + return ALLOCATORS[name] + except KeyError: + raise ValueError( + f"Unknown cross-grain allocator {name!r}; expected one of " + f"{sorted(ALLOCATORS)}." + ) from None + + +# --------------------------------------------------------------------------- +# Derived controls +# --------------------------------------------------------------------------- + + +def sum_of_lower_rows(values: Iterable[float]) -> float: + """A total that is the exactly rounded sum of its own lower rows.""" + + return math.fsum(float(value) for value in values) + + +def sibling_ratio(sibling_higher: float, sibling_lower: float) -> float: + """A sibling quantity's level in the higher source over the lower one's.""" + + return float(sibling_higher) / float(sibling_lower) + + +def scaled_by_sibling_ratio( + value: float, sibling_higher: float, sibling_lower: float +) -> tuple[float, float]: + """A lower-source level lifted onto the higher source's basis. + + Only the lower source publishes this quantity. A sibling quantity that + both sources publish at the same geography estimates the gap between + them. Returns ``(value * factor, factor)`` with the sibling's ratio as + the factor. The caller refuses a missing or zero sibling first. + """ + + factor = sibling_ratio(sibling_higher, sibling_lower) + return float(value) * factor, factor + + +# --------------------------------------------------------------------------- +# The factor band +# --------------------------------------------------------------------------- + + +def level_ratio(higher: float, lower: float) -> float: + """Two levels of one quantity as a ratio; ``NaN`` where none is defined. + + No ratio is defined against a zero lower level, or when the two levels + disagree on being positive. + """ + + higher, lower = float(higher), float(lower) + if lower != 0.0 and (higher > 0) == (lower > 0): + return higher / lower + return math.nan + + +def control_ratio( + control_value: float, lower_values: Iterable[float] +) -> tuple[float | None, float]: + """``(control / lower sum, lower sum)``, with the sum exactly rounded. + + The ratio is the factor :func:`proportional_fsum` gives the same rows. It + is ``None`` when the rows sum to zero. + """ + + lower_sum = sum_of_lower_rows(lower_values) + if lower_sum == 0.0: + return None, lower_sum + return float(control_value) / lower_sum, lower_sum + + +def median_by_group[Key: Hashable, Group: Hashable]( + ratios: Mapping[Key, float], + group_of: Callable[[Key], Group], + *, + positive_only: bool = False, +) -> dict[Group, float]: + """The median finite ratio of each group of keys. + + ``positive_only`` also leaves out ratios that are zero or negative. + """ + + grouped: dict[Group, list[float]] = {} + for key, ratio in ratios.items(): + if math.isfinite(ratio) and (ratio > 0 or not positive_only): + grouped.setdefault(group_of(key), []).append(ratio) + return {group: float(np.median(values)) for group, values in grouped.items()} + + +@dataclass(frozen=True) +class BandVerdict: + """One ratio judged against its group's median.""" + + ok: bool + ratio: float + median: float + relative: float + + +def band_verdict(ratio: float, median: float, band: float) -> BandVerdict: + """Whether ``ratio`` sits within ``band`` of ``median``, either way. + + ``relative`` is the ratio over the median. It is ``NaN``, and the verdict + fails, when the ratio is not finite or the median is zero or unknown. + """ + + relative = ratio / median if math.isfinite(ratio) and median else math.nan + ok = math.isfinite(relative) and 1 / band <= relative <= band + return BandVerdict(ok=ok, ratio=ratio, median=median, relative=relative) + + +# --------------------------------------------------------------------------- +# Completeness +# --------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class LegCompleteness: + """A leg's present members against the members it must hold.""" + + missing: tuple + unexpected: tuple + duplicated: tuple + #: Absent member -> the present host whose row covers it. + merged: Mapping + + @property + def complete(self) -> bool: + return not (self.missing or self.unexpected or self.duplicated) + + +def leg_completeness[Member: Hashable]( + present: Iterable[Member], + expected: Iterable[Member], + *, + combined_cells: Mapping[Member, Member] | None = None, +) -> LegCompleteness: + """Compare the members a leg holds with the members it must hold. + + ``combined_cells`` maps a member that may be absent to its declared host. + An absent member is covered, not missing, when its host is present and + expected: the host's row then stands for both. + """ + + held = list(present) + held_set, expected_set = set(held), set(expected) + combined = dict(combined_cells or {}) + absent = expected_set - held_set + merged = { + member: combined[member] + for member in sorted(absent) + if member in combined + and combined[member] in held_set + and combined[member] in expected_set + } + seen: set = set() + duplicated = sorted( + {member for member in held if member in seen or seen.add(member)} + ) + return LegCompleteness( + missing=tuple(sorted(absent - merged.keys())), + unexpected=tuple(sorted(held_set - expected_set)), + duplicated=tuple(duplicated), + merged=merged, + ) + + +# --------------------------------------------------------------------------- +# Self-consistency +# --------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class SumGap: + """The distance between a total and the sum of its lower rows.""" + + gap: float + scale: float + + @property + def relative(self) -> float: + return self.gap / self.scale + + def within(self, rtol: float) -> bool: + """The gap is at most ``rtol`` of the scale.""" + + return self.gap <= rtol * self.scale + + def exceeds(self, rtol: float) -> bool: + """The gap is more than ``rtol`` of the scale.""" + + return self.gap > rtol * self.scale + + +def sum_gap(total: float, lower_sum: float, *, floor: float = 1.0) -> SumGap: + """A total against the sum of its lower rows. + + The scale is the total's size, and at least ``floor``, so a total near + zero is judged on an absolute gap. + """ + + total = float(total) + return SumGap(gap=abs(total - lower_sum), scale=max(abs(total), floor)) diff --git a/packages/microcosm-build/tests/engine_free/shared/test_cross_grain_controls.py b/packages/microcosm-build/tests/engine_free/shared/test_cross_grain_controls.py new file mode 100644 index 0000000000..e06e705a50 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/shared/test_cross_grain_controls.py @@ -0,0 +1,320 @@ +"""The controls, allocators and checks beside the cross-grain operator. + +``microcosm.build.cross_grain_controls`` holds what a country's sources can +need around the operator (microcosm#1760). The allocators must give, bit for +bit, the arithmetic they replace; the ``_old_*`` functions here state that +arithmetic as it was written before the operator ran it. +""" + +from __future__ import annotations + +import ast +import inspect +import math +import re +import struct + +import numpy as np +import pandas as pd +import pytest + +from microcosm.build import cross_grain_controls as controls +from microcosm.build.cross_grain import ( + CrossGrainRule, + apply_cross_grain_reconciliation, +) + +SEEDS = range(200) + + +def _bits(values) -> bytes: + return b"".join(struct.pack(" tuple[np.ndarray, float]: + """One leg's rows and its control, sometimes with equal or zero rows.""" + + rng = np.random.default_rng(seed) + size = int(rng.integers(1, 60)) + values = rng.lognormal(mean=rng.uniform(0.0, 14.0), sigma=2.0, size=size) + if rng.random() < 0.3: + values = np.round(values) + if size > 2 and rng.random() < 0.3: + values[int(rng.integers(size))] = values.max() # equal largest rows + if size > 1 and rng.random() < 0.3: + values[int(rng.integers(size))] = 0.0 + if signed and rng.random() < 0.5: + values[int(rng.integers(size))] *= -0.25 + if not values.any(): + values[0] = 1.0 + parent = float(values.sum() * rng.uniform(0.5, 2.0)) + if rng.random() < 0.2: + parent = float(round(parent)) + return values, parent + + +def _old_proportional(values: list[float], parent: float): + child_sum = math.fsum(float(value) for value in values) + factor = 1.0 if child_sum == 0.0 else parent / child_sum + return [float(value) * factor for value in values], factor, child_sum + + +def _old_share_rows(values: list[float], parent: float): + total = math.fsum(values) + shares = [value / total for value in values] + largest = max(range(len(values)), key=lambda index: shares[index]) + shares[largest] += 1.0 - math.fsum(shares) + targets = [parent * share for share in shares] + targets[largest] += parent - math.fsum(targets) + return shares, targets, total + + +def _old_scaled_rows(values: list[float], parent: float): + total = math.fsum(values) + scaled = [float(parent) * value / total for value in values] + largest = max(range(len(values)), key=lambda index: scaled[index]) + scaled[largest] += float(parent) - math.fsum(scaled) + return scaled, total + + +def test_proportional_fsum_is_the_old_rebase_bit_for_bit() -> None: + for seed in SEEDS: + values, parent = _block(seed, signed=True) + new_values, factor, raw_sum = controls.proportional_fsum(values, parent) + old_values, old_factor, old_sum = _old_proportional(values.tolist(), parent) + assert _bits(new_values) == _bits(old_values), seed + assert _bits([factor, raw_sum]) == _bits([old_factor, old_sum]), seed + # The factor does not depend on the order of the rows. + shuffled = np.random.default_rng(seed).permutation(values) + assert controls.proportional_fsum(shuffled, parent)[1:] == (factor, raw_sum) + + +def test_share_residual_to_largest_is_the_old_share_rows_bit_for_bit() -> None: + for seed in SEEDS: + values, parent = _block(seed) + new_values, factor, raw_sum = controls.share_residual_to_largest(values, parent) + shares, targets, total = _old_share_rows(values.tolist(), parent) + assert _bits(new_values) == _bits(targets), seed + assert raw_sum == total and factor == parent / total, seed + new_shares, new_total, _largest = controls.residual_shares(values.tolist()) + assert _bits(new_shares) == _bits(shares) and new_total == total, seed + assert math.isclose(math.fsum(new_shares), 1.0, rel_tol=0.0, abs_tol=1e-15) + assert math.isclose(math.fsum(new_values), parent, rel_tol=1e-15), seed + + +def test_scale_residual_to_largest_is_the_old_scaled_rows_bit_for_bit() -> None: + for seed in SEEDS: + values, parent = _block(seed) + new_values, factor, raw_sum = controls.scale_residual_to_largest(values, parent) + scaled, total = _old_scaled_rows(values.tolist(), parent) + assert _bits(new_values) == _bits(scaled), seed + assert raw_sum == total and factor == parent / total, seed + assert math.isclose(math.fsum(new_values), parent, rel_tol=1e-15), seed + + +def test_the_residual_goes_to_the_first_of_equal_largest_rows() -> None: + values = np.array([1.0, 3.0, 3.0, 0.1]) + shares, total, largest = controls.residual_shares(values.tolist()) + assert (total, largest) == (7.1, 1) + untouched = [value / total for value in values.tolist()] + assert [shares[0], shares[2], shares[3]] == [ + untouched[0], + untouched[2], + untouched[3], + ] + assert math.fsum(shares) == 1.0 + + +@pytest.mark.parametrize("name", sorted(controls.ALLOCATORS)) +def test_an_allocator_keeps_rows_that_sum_to_zero(name: str) -> None: + values = np.array([0.0, 0.0, 0.0]) + new_values, factor, raw_sum = controls.ALLOCATORS[name](values, 5.0) + assert new_values.tolist() == [0.0, 0.0, 0.0] + assert (factor, raw_sum) == (1.0, 0.0) + # The operator then refuses the vanishing leg under a nonzero control. + surface = pd.DataFrame( + [("higher", "P", "control", 5.0)] + + [("lower", f"P{index}", "rows", 0.0) for index in range(3)], + columns=["grain", "geography_id", "target_id", "value"], + ) + with pytest.raises(ValueError, match="vanishing lower-leg total"): + apply_cross_grain_reconciliation( + surface, ("control",), _SIGNATURES, _rule(controls.ALLOCATORS[name]) + ) + + +def test_a_declaration_names_an_allocator() -> None: + assert sorted(controls.ALLOCATORS) == [ + "proportional_fsum", + "scale_residual_to_largest", + "share_residual_to_largest", + ] + assert controls.allocator_named("proportional_fsum") is controls.proportional_fsum + with pytest.raises(ValueError, match="Unknown cross-grain allocator 'numpy_sum'"): + controls.allocator_named("numpy_sum") + + +_SIGNATURES = { + "control": {"measurement": {"concept": "quantity"}}, + "rows": {"measurement": {"concept": "quantity"}}, +} + + +def _rule(allocator) -> CrossGrainRule: + return CrossGrainRule( + grain_precedence=("higher", "lower"), + signature_fields=("concept",), + bridges=(), + leg_of_area=lambda area: area[0], + parent_geography_legs={"P": ("P",)}, + allocator=allocator, + ) + + +@pytest.mark.parametrize("name", sorted(controls.ALLOCATORS)) +def test_the_operator_runs_each_allocator(name: str) -> None: + allocator = controls.ALLOCATORS[name] + for seed in range(40): + values, parent = _block(seed) + surface = pd.DataFrame( + [("higher", "P", "control", parent)] + + [ + ("lower", f"P{index}", "rows", value) + for index, value in enumerate(values.tolist()) + ], + columns=["grain", "geography_id", "target_id", "value"], + ) + reconciled, receipt = apply_cross_grain_reconciliation( + surface, ("control",), _SIGNATURES, _rule(allocator) + ) + direct, factor, raw_sum = allocator(values, parent) + assert _bits(reconciled["value"].to_numpy()[1:]) == _bits(direct), seed + (leg,) = receipt["groups"][0]["legs"] + assert (leg["allocator"], leg["declared_factor"], leg["old_total"]) == ( + name, + factor, + raw_sum, + ) + + +def test_derived_controls() -> None: + # Exactly rounded: a running float total would lose the 1.0. + assert controls.sum_of_lower_rows([1e16, 1.0, -1e16]) == 1.0 + assert controls.sum_of_lower_rows([0.1] * 10) == 1.0 + assert controls.sibling_ratio(110.0, 100.0) == 110.0 / 100.0 + scaled, factor = controls.scaled_by_sibling_ratio(40.0, 110.0, 100.0) + assert (scaled, factor) == (40.0 * (110.0 / 100.0), 110.0 / 100.0) + + +def test_level_ratio_is_undefined_at_zero_or_across_signs() -> None: + assert controls.level_ratio(6.0, 4.0) == 1.5 + assert controls.level_ratio(-6.0, -4.0) == 1.5 + assert controls.level_ratio(0.0, 0.0) != controls.level_ratio(0.0, 0.0) # NaN + for higher, lower in ((6.0, 0.0), (6.0, -4.0), (-6.0, 4.0), (0.0, 4.0)): + assert math.isnan(controls.level_ratio(higher, lower)), (higher, lower) + # Zero over a negative level: neither is positive, so a ratio is defined. + assert controls.level_ratio(0.0, -4.0) == 0.0 + + +def test_control_ratio_is_the_proportional_factor() -> None: + for seed in range(40): + values, parent = _block(seed, signed=True) + ratio, lower_sum = controls.control_ratio(parent, values.tolist()) + _values, factor, raw_sum = controls.proportional_fsum(values, parent) + if raw_sum == 0.0: + assert ratio is None + else: + assert (ratio, lower_sum) == (factor, raw_sum) + assert controls.control_ratio(5.0, [1.0, -1.0]) == (None, 0.0) + + +def test_median_by_group_reads_finite_ratios_only() -> None: + ratios = { + ("a", "x"): 1.0, + ("b", "x"): 3.0, + ("c", "x"): math.nan, + ("d", "x"): math.inf, + ("a", "y"): -2.0, + ("b", "y"): 0.0, + ("c", "y"): 4.0, + ("a", "z"): math.nan, + } + assert controls.median_by_group(ratios, lambda key: key[1]) == { + "x": 2.0, + "y": 0.0, + } + assert controls.median_by_group(ratios, lambda key: key[1], positive_only=True) == { + "x": 2.0, + "y": 4.0, + } + + +def test_band_verdict() -> None: + inside = controls.band_verdict(1.2, 1.0, 1.25) + assert inside == controls.BandVerdict(True, 1.2, 1.0, 1.2) + assert controls.band_verdict(1.25, 1.0, 1.25).ok + assert controls.band_verdict(0.8, 1.0, 1.25).ok + assert not controls.band_verdict(1.26, 1.0, 1.25).ok + assert not controls.band_verdict(0.79, 1.0, 1.25).ok + # No median, a zero median or a ratio that is not finite: no verdict. + for ratio, median in ((1.0, math.nan), (1.0, 0.0), (math.nan, 1.0), (math.inf, 1)): + verdict = controls.band_verdict(ratio, median, 1.25) + assert not verdict.ok and math.isnan(verdict.relative), (ratio, median) + # An unbounded band still refuses a ratio on the other side of zero. + assert controls.band_verdict(1e9, 1.0, math.inf).ok + assert not controls.band_verdict(-1.0, 1.0, math.inf).ok + + +def test_leg_completeness() -> None: + complete = controls.leg_completeness(["a", "b"], {"a", "b"}) + assert complete.complete and complete.merged == {} + report = controls.leg_completeness(["a", "a", "x"], ["a", "b", "c"]) + assert not report.complete + assert (report.missing, report.unexpected, report.duplicated) == ( + ("b", "c"), + ("x",), + ("a",), + ) + # A declared combined cell covers an absent member through its host. + merged = controls.leg_completeness( + ["a", "b"], ["a", "b", "c"], combined_cells={"c": "b", "z": "a"} + ) + assert merged.complete and merged.merged == {"c": "b"} + # The host must be present and expected. + for present, expected in ((["a"], ["a", "b", "c"]), (["a", "b"], ["a", "c"])): + report = controls.leg_completeness(present, expected, combined_cells={"c": "b"}) + assert "c" in report.missing and report.merged == {} + + +def test_sum_gap() -> None: + gap = controls.sum_gap(100.0, 99.0) + assert (gap.gap, gap.scale, gap.relative) == (1.0, 100.0, 0.01) + assert gap.within(0.01) and not gap.exceeds(0.01) + assert gap.exceeds(0.001) and not gap.within(0.001) + # A total near zero is judged on the absolute gap. + small = controls.sum_gap(0.0, 0.5) + assert (small.gap, small.scale) == (0.5, 1.0) + assert controls.sum_gap(0.0, 0.5, floor=0.25).scale == 0.25 + # A gap that is not a number is neither within nor beyond a tolerance. + undefined = controls.sum_gap(math.nan, 1.0) + assert not undefined.within(1.0) and not undefined.exceeds(1.0) + + +def test_the_module_holds_no_country_and_the_operator_does_not_import_it() -> None: + from microcosm.build import cross_grain + + source = inspect.getsource(controls) + imported = { + (node.module if isinstance(node, ast.ImportFrom) else alias.name).split(".")[0] + for node in ast.walk(ast.parse(source)) + if isinstance(node, ast.Import | ast.ImportFrom) + for alias in node.names + } + assert imported <= {"__future__", "collections", "dataclasses", "math", "numpy"} | { + "typing" + } + named = re.findall( + r"\b(us|uk|us_runtime|uk_runtime|irs|soi|census|hmrc)\b", source.lower() + ) + assert named == [] + assert "cross_grain_controls" not in inspect.getsource(cross_grain) From d1f62f9dd8c8c9fc9e9e8bc4d5a1d787a09a1ea9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:05:01 +0000 Subject: [PATCH 04/23] Declare the US nesting mechanisms and add the adapter to the operator us/cross_grain_declarations.json is the US file of the shared cross-grain operator (microcosm#1760). It names the geography levels and the levels that hold controls with the key names of uk/cross_grain_declarations.json, and it declares the four mechanisms that make lower-level rows from a higher-level control in the local tools (rows 5 to 8 of the issue): the allocator, the rule for the control, the bounds, the source of the member lists, the old metadata keys, and the reviewed registers with their reasons. The registers were Python literals in the tools: the defective, unparented and excluded district measures, the six level bridges, the factor band, the two tolerances, the reviewed crosswalk digest, the required county measures and the combined cell with its basis. The tools now read them from the declaration under their old names. No function uses the operator yet. us_runtime/cross_grain_declarations.py reads the file. us_runtime/target_nesting.py is the adapter: it builds one surface from blocks (a control and its lower rows), runs the operator with the declared allocator, and returns each block's rows. A stage can record the operator's own receipts and write them to target_nesting.json. The new resource row moves the US F0 pins, as each new legacy resource does: 42,407 configuration fields (32,621 authored), the country_manifest claim at 116 pointers, and the US bundle's semantic spec_sha256 (9141b9bf). No target changes. Both pin tools ran twice and their --check modes pass. Proof: test_us_cross_grain_declarations.py holds each register to the literal it replaces (value, type and order), read from test_support/microcosm_build/us_target_nesting_reference.py, which is the tool code at e29843dc7. It also checks the declaration's shape and the adapter's block interface. Co-Authored-By: Claude Fable 5.2 --- docs/evidence/spec-engine/us-f0-coverage.json | 20 +- .../build/spec_engine/field_usage.py | 8 +- .../microcosm/build/us/country_package.json | 5 + .../build/us/cross_grain_declarations.json | 198 +++ .../us_runtime/cross_grain_declarations.py | 160 ++ .../build/us_runtime/target_nesting.py | 278 ++++ .../us/test_spec_engine_coverage_tool.py | 10 +- .../shared/test_spec_engine_field_usage.py | 10 +- .../us/test_us_cross_grain_declarations.py | 271 ++++ .../engine_free/us/test_us_spine_blindness.py | 7 + .../us/test_us_multispine_pool_tool.py | 2 +- .../us_target_nesting_reference.py | 1383 +++++++++++++++++ tools/generate_us_bundle_from_constants.py | 3 + tools/spec_engine_coverage.py | 2 +- tools/us_acs_local_cd_surface.py | 118 +- tools/us_acs_local_county_surface.py | 42 +- 16 files changed, 2397 insertions(+), 120 deletions(-) create mode 100644 packages/microcosm-build/src/microcosm/build/us/cross_grain_declarations.json create mode 100644 packages/microcosm-build/src/microcosm/build/us_runtime/cross_grain_declarations.py create mode 100644 packages/microcosm-build/src/microcosm/build/us_runtime/target_nesting.py create mode 100644 packages/microcosm-build/tests/engine_free/us/test_us_cross_grain_declarations.py create mode 100644 test_support/microcosm_build/us_target_nesting_reference.py diff --git a/docs/evidence/spec-engine/us-f0-coverage.json b/docs/evidence/spec-engine/us-f0-coverage.json index b613307197..be99c8d1b1 100644 --- a/docs/evidence/spec-engine/us-f0-coverage.json +++ b/docs/evidence/spec-engine/us-f0-coverage.json @@ -6,7 +6,7 @@ "country": "us", "documentation_sha256": "fda6ec0dd925077f4d84d30a1c206dd81d82c5e16bd94506e81fe1b9f7e2f466", "field_usage": { - "authored_normative_field_count": 32618, + "authored_normative_field_count": 32621, "claim_count": 48, "claims": [ { @@ -16,8 +16,8 @@ "legacy_sinks": [], "mode": "front_end_validation", "pointer_class": "all", - "pointer_count": 113, - "pointer_sha256": "11b70807bf06832e71367643c7d0e09891c1d4923fe574b471d6632562129897", + "pointer_count": 116, + "pointer_sha256": "3a77833a2aee67d0f58a3dd972f947a79a24afc7c0ebc1821a0e8dd3cbf5771a", "rationale": null, "relative_sink_prefix": null, "source_prefix": "/authored/country_package.json", @@ -758,20 +758,20 @@ "verifier": "vintages" } ], - "configuration_field_count": 42404, - "consumed_field_count": 42404, + "configuration_field_count": 42407, + "consumed_field_count": 42407, "generation0_effect_counts": { "legacy_behavior": 38780, - "no_generation0_effect": 3624 + "no_generation0_effect": 3627 }, "mode_counts": { "compiler_semantic": 27674, - "front_end_validation": 358, + "front_end_validation": 361, "identity_only": 103, "legacy_behavior": 14269 }, "multiple_primary_use_field_count": 0, - "pointer_inventory_sha256": "38fc67ba13d62a5c0eaff36abb8f04d4d2974e21baaed6d2966d76480e643608", + "pointer_inventory_sha256": "b7565bf43ff7139460a8345d3858a6950c4fdcf4cb61afe6b056550040b1c710", "resolved_binding_field_count": 9786, "unused_field_count": 0 }, @@ -2585,7 +2585,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "b94bfc6a5742de010443938a676d4d34e70df80dd405f89e2ff7a70f747c8107" + "spec_sha256": "9141b9bf0fa71678c7b7f0c55bc96e040cdfab378f09b54540659910560b0424" } }, "report_schema_version": 3, @@ -2595,7 +2595,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "b94bfc6a5742de010443938a676d4d34e70df80dd405f89e2ff7a70f747c8107" + "spec_sha256": "9141b9bf0fa71678c7b7f0c55bc96e040cdfab378f09b54540659910560b0424" }, "status": "pass" } diff --git a/packages/microcosm-build/src/microcosm/build/spec_engine/field_usage.py b/packages/microcosm-build/src/microcosm/build/spec_engine/field_usage.py index d6a9e8751e..4089a583be 100644 --- a/packages/microcosm-build/src/microcosm/build/spec_engine/field_usage.py +++ b/packages/microcosm-build/src/microcosm/build/spec_engine/field_usage.py @@ -26,9 +26,9 @@ ) from .schemas import load_schema_registry -EXPECTED_AUTHORED_FIELD_COUNT = 32618 +EXPECTED_AUTHORED_FIELD_COUNT = 32621 EXPECTED_RESOLVED_BINDING_FIELD_COUNT = 9786 -EXPECTED_CONFIGURATION_FIELD_COUNT = 42404 +EXPECTED_CONFIGURATION_FIELD_COUNT = 42407 class FieldUsageError(AssertionError): @@ -369,8 +369,8 @@ def _path_inventory(rows: Sequence[tuple[str, object]]) -> tuple[int, str]: "bdd9e79157590fade42d28cc2b5d5c8b58e13903af75375a0e3235c94d2a8339", ), "country_manifest": ( - 113, - "11b70807bf06832e71367643c7d0e09891c1d4923fe574b471d6632562129897", + 116, + "3a77833a2aee67d0f58a3dd972f947a79a24afc7c0ebc1821a0e8dd3cbf5771a", ), "generated_authorities": ( 8_614, diff --git a/packages/microcosm-build/src/microcosm/build/us/country_package.json b/packages/microcosm-build/src/microcosm/build/us/country_package.json index 855a488fe9..0cce9b5401 100644 --- a/packages/microcosm-build/src/microcosm/build/us/country_package.json +++ b/packages/microcosm-build/src/microcosm/build/us/country_package.json @@ -82,6 +82,11 @@ "kind": "legacy_json", "schema_id": "legacy_json" }, + { + "path": "cross_grain_declarations.json", + "kind": "legacy_json", + "schema_id": "legacy_json" + }, { "path": "ecps_parity_known_gaps.json", "kind": "legacy_json", diff --git a/packages/microcosm-build/src/microcosm/build/us/cross_grain_declarations.json b/packages/microcosm-build/src/microcosm/build/us/cross_grain_declarations.json new file mode 100644 index 0000000000..d0253a90fa --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/us/cross_grain_declarations.json @@ -0,0 +1,198 @@ +{ + "schema_version": 1, + "description": "US cross-grain nesting declarations (microcosm#1760). Each mechanism makes the rows of a lower geography level from a control at a higher level, on the shared operator microcosm.build.cross_grain, with the helpers of microcosm.build.cross_grain_controls. This file holds the US choices: the order of the levels, which levels hold controls, the allocator of each mechanism, the rule for its control, its bounds, the source of its member lists, and its reviewed registers with their reasons. Tools and tests read it through microcosm.build.us_runtime.cross_grain_declarations; the adapter is microcosm.build.us_runtime.target_nesting. Stage A changes no target value. docs/us-target-nesting.md describes each mechanism.", + "grain_precedence": [ + "country", + "state", + "congressional_district", + "county" + ], + "control_grains": [ + "country", + "state" + ], + "signature_fields": [ + "concept", + "filters" + ], + "bridges": [], + "partitions": [], + "mechanisms": { + "state_congressional_district_soi": { + "issue_row": 5, + "title": "State to congressional district, IRS SOI (--soi-mode state_cd)", + "tool_function": "tools/us_acs_local_cd_surface.py:state_cd_soi_surface", + "family": "irs_soi", + "higher_grain": "state", + "lower_grain": "congressional_district", + "allocator": "proportional_fsum", + "vintage_rule": "state_cd.historic_table_2_level_cd_file_shares.v1", + "control": { + "kind": "bound_row_or_scaled_by_sibling_ratio", + "description": "Historic Table 2 (TY2022) is the single vintage of every state concept it carries, and its state row is the control. A concept only the district file carries keeps the district file's own state row as its control, lifted onto the Historic Table 2 basis by a sibling concept's ratio of the two files' state totals in the same state.", + "level_bridges": { + "description": "District-file-only concepts (Historic Table 2 lacks them) and the sibling concept whose two state levels bridge theirs onto the Historic Table 2 basis. The district file's own state levels sit below Historic Table 2's for two reasons: it covers only the returns processed in its window (about 1.7% fewer), and the feed stamps it one tax year late, so its amounts are aged one year less. A sibling both files carry, in the same state, estimates that gap, on the assumption that the measure shares the sibling's ratio: counts bridge by return_count (counts are not aged), amounts by the closest amount Historic Table 2 carries. The factor band applies to the sibling. The bridge is stamp-invariant: if the stamp is corrected (#1030) both levels move together.", + "siblings": { + "charitable_amount": "itemized_deductions_amount", + "charitable_returns": "return_count", + "interest_paid_deduction_amount": "itemized_deductions_amount", + "interest_paid_deduction_returns": "return_count", + "qualified_business_income_deduction_amount": "adjusted_gross_income", + "qualified_business_income_deduction_returns": "return_count" + } + } + }, + "factor_band": { + "tolerance": 1.25, + "on_out_of_band": "drop_block", + "description": "How far a state's Historic Table 2 / district-file ratio may sit from its measure's median across states before the district file's data for that (state, concept) is refused. The ratio mixes a common part (the file's coverage and aging gap, or a measure-wide rebase such as taxable interest's x2.47 onto Table 4.3), which the median absorbs, with a state-specific part. A state-specific part beyond 25% means the two publications disagree about that state (Hawaii's dividends differ 2.4x from the typical gap on the pinned feed), so the district file's shares, or a bridge built on that sibling, are not trusted: the block's district rows and any bridged state row are dropped and recorded; the Historic Table 2 state row stays." + }, + "self_consistency": { + "rtol": 1e-06, + "description": "The district file's own state row must equal the sum of its district rows to this relative tolerance wherever both are present (the receipt records the largest gap; the feed-gated contract test pins it on the pinned feed). A gap means a column or crosswalk defect inside the file (#1038 class), which no median absorbs." + }, + "closure": { + "rtol": 1e-09, + "description": "Relative tolerance for 'district rows sum to their state parent'. The rebase makes it exact up to float64 rounding." + }, + "members": { + "source": "congressional_district_vintage_crosswalk", + "reviewed_crosswalk_sha256": "a347303fff3fea145f758488c43cb94355df5a8cb5e512552b2ee3791d2aa233", + "single_member_legs": "dropped", + "description": "The 117th->119th congressional-district crosswalk the compiler used names each state's source-plan and current-plan districts. A district block must cover exactly the current plan's districts of its state. A state with one source-plan district is at-large there: the district file has no sub-state rows for it, so its district rows are dropped (at_large_on_source_plan). reviewed_crosswalk_sha256 is the packaged crosswalk the registers below were reviewed against; a test pins it, so regenerating the crosswalk forces a second look at them." + }, + "registers": { + "defective_lower_measures": { + "description": "District-file measures that read the wrong IRS column (microcosm#1038). The compiler's US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS drops these facts by (measure id, IRS column) before this surface sees them; this register stays as a second fence on the state_cd surface, at both geographies, and records the reason in the receipt.", + "entries": { + "limited_state_local_taxes_amount": "22incd.csv column A18425 is state and local income taxes (Schedule A line 5a), not the limited SALT deduction (A18460); the district file sums to 1.98x Historic Table 2 (microcosm#1038).", + "limited_state_local_taxes_returns": "22incd.csv column N18425 counts state and local income-tax deductions, not the limited SALT deduction (microcosm#1038).", + "premium_tax_credit_returns": "22incd.csv column N85530 is the additional Medicare tax (Form 8959 line 24), not the premium tax credit (N85770) (microcosm#1038)." + } + }, + "unparented_lower_measures": { + "description": "District-file measures with no state parent in either vintage, so their district rows could not nest in a bound state target.", + "entries": { + "tax_filer_individual_count": "The compiler drops this measure at state and national geography (fiscal_targets._soi_reference_from_fact), so no state target exists for its district rows to reconcile to." + } + }, + "excluded_legs": { + "description": "States whose district SOI rows stay off the surface, with the evidence. Empty since #1043 rebuilt the 117th->119th crosswalk from the block plan registry: the packaged crosswalk before it (sha256 c7cb040b...) carried North Carolina's 2016 plan instead of the 2019 plan the 117th Congress used, and 37.0% of NC's population mapped to a different 119th district, so NC's district rows were held off until then.", + "entries": {} + } + }, + "metadata_keys": { + "lower_rows": [ + "state_cd_vintage_rule", + "state_cd_parent_target_name", + "state_cd_parent_basis", + "state_cd_parent_value", + "state_cd_cd_file_value", + "state_cd_cd_file_state_sum", + "state_cd_rebase_factor" + ], + "derived_controls": [ + "state_cd_vintage_rule", + "state_cd_cd_file_value", + "state_cd_level_bridge_sibling", + "state_cd_level_bridge_cd_file_sibling", + "state_cd_level_bridge_factor" + ] + }, + "receipt": "materialize_rss.json: soi_surface" + }, + "state_county_population": { + "issue_row": 8, + "title": "State to county, resident population (PUMA ladder)", + "tool_function": "tools/us_acs_local_county_surface.py:with_county_populations", + "family": "census_population", + "higher_grain": "state", + "lower_grain": "county", + "allocator": "scale_residual_to_largest", + "control": { + "kind": "bound_row", + "description": "The state total from the 2020 PUMA ladder. The county rows are the ladder's (PUMA, county) population overlaps, summed by county and scaled to the state total; the rounding residual goes to the largest county, never a small one." + }, + "members": { + "source": "us_puma_ladder_county_overlaps", + "description": "Every county of the ladder's overlaps, on the boundaries of the county column (county_fips: 2020 counties; county_fips_2023: Connecticut's planning regions, from the tract overlaps). A state with no positive county or state population is refused, and so is a county with no state." + }, + "metadata_keys": { + "lower_rows": [] + }, + "receipt": "none before microcosm#1760" + }, + "state_county_soi": { + "issue_row": 6, + "title": "State to county, IRS SOI (--soi-mode state_county)", + "tool_function": "tools/us_acs_local_county_surface.py:state_county_soi_surface", + "family": "irs_soi", + "higher_grain": "state", + "lower_grain": "county", + "allocator": "share_residual_to_largest", + "control": { + "kind": "bound_row", + "description": "The broad state row that already exists on the state surface: all returns, no AGI class, no filing status. County SOI facts supply shares, never a second state level." + }, + "required_measures": [ + "return_count", + "adjusted_gross_income" + ], + "members": { + "source": "us_puma_ladder_county_populations", + "description": "Every county of the state in the ladder's county populations. A county absent from a block is refused unless combined_cells declares it with its host present: then one child row covers both counties.", + "combined_cells": [ + { + "absent": "15005", + "host": "15009" + } + ], + "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.", + "combined_cell_description": "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." + }, + "metadata_keys": { + "lower_rows": [ + "state_county_parent_target_name", + "state_county_share", + "state_county_source_value", + "county_population", + "state_population", + "state_county_cell_members", + "state_county_cell_basis" + ] + }, + "receipt": "county_surface.json" + }, + "county_state_acs_households": { + "issue_row": 7, + "title": "County to state, ACS households (--soi-mode state_county)", + "tool_function": "tools/us_acs_local_county_surface.py:acs_household_surface", + "family": "acs_households", + "higher_grain": "state", + "lower_grain": "county", + "allocator": "share_residual_to_largest", + "control": { + "kind": "sum_of_lower_rows", + "description": "The children make the parent: each state's households target is the sum of its counties' ACS 5-year B11001_001E estimates, a new state target. The county rows then divide it by county share, so they sum to it." + }, + "members": { + "source": "us_puma_ladder_county_populations", + "description": "Every county of the ladder's county populations must carry an estimate; a missing or unexpected county is refused." + }, + "metadata_keys": { + "lower_rows": [ + "state_county_parent_target_name", + "state_county_share", + "state_county_source_value", + "county_population", + "state_population" + ], + "derived_controls": [ + "acs_state_parent_basis", + "new_state_target" + ] + }, + "receipt": "county_surface.json: acs_households" + } + } +} diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/cross_grain_declarations.py b/packages/microcosm-build/src/microcosm/build/us_runtime/cross_grain_declarations.py new file mode 100644 index 0000000000..95f585a6ff --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/cross_grain_declarations.py @@ -0,0 +1,160 @@ +"""US cross-grain nesting declarations (microcosm#1760). + +``us/cross_grain_declarations.json`` holds every US choice the shared +cross-grain operator (:mod:`microcosm.build.cross_grain`) and its helpers +(:mod:`microcosm.build.cross_grain_controls`) need: the order of the geography +levels, the levels that hold controls, and, for each mechanism that makes the +rows of a lower level from a control at a higher one, its allocator, the rule +for its control, its bounds, the source of its member lists and its reviewed +registers with their reasons. The key names follow +``uk/cross_grain_declarations.json`` wherever the meaning is the same. + +This module reads the file and hands out typed views of it. It does no +arithmetic and reads no target; the adapter that runs the operator is +:mod:`microcosm.build.us_runtime.target_nesting`. +""" + +from __future__ import annotations + +import functools +import json +from collections.abc import Mapping +from dataclasses import dataclass +from importlib import resources as importlib_resources +from typing import Any + +from microcosm.build.cross_grain_controls import ALLOCATORS + +US_CROSS_GRAIN_DECLARATIONS_RESOURCE = "cross_grain_declarations.json" + +#: The mechanisms of the issue's rows 5 to 8, by their declared id. +DISTRICT_SOI = "state_congressional_district_soi" +COUNTY_POPULATION = "state_county_population" +COUNTY_SOI = "state_county_soi" +COUNTY_ACS_HOUSEHOLDS = "county_state_acs_households" + +_CONTROL_KINDS = ( + "bound_row", + "bound_row_or_scaled_by_sibling_ratio", + "sum_of_lower_rows", +) + + +@functools.lru_cache(maxsize=1) +def load_us_cross_grain_declarations() -> Mapping[str, Any]: + """The declarations file, checked for the fields every reader relies on.""" + + payload = json.loads( + importlib_resources.files("microcosm.build.us") + .joinpath(US_CROSS_GRAIN_DECLARATIONS_RESOURCE) + .read_text(encoding="utf-8") + ) + if payload.get("schema_version") != 1: + raise ValueError( + "US cross-grain declarations schema_version must be 1, got " + f"{payload.get('schema_version')!r}." + ) + grains = tuple(payload["grain_precedence"]) + unknown_controls = [g for g in payload["control_grains"] if g not in grains] + if unknown_controls: + raise ValueError( + f"US cross-grain control_grains {unknown_controls} are not in " + "grain_precedence." + ) + for mechanism_id, mechanism in payload["mechanisms"].items(): + higher, lower = mechanism["higher_grain"], mechanism["lower_grain"] + if ( + higher not in payload["control_grains"] + or lower not in grains + or grains.index(higher) >= grains.index(lower) + ): + raise ValueError( + f"US cross-grain mechanism {mechanism_id!r} must name a control " + f"grain above its lower grain, got {higher!r} over {lower!r}." + ) + if mechanism["allocator"] not in ALLOCATORS: + raise ValueError( + f"US cross-grain mechanism {mechanism_id!r} names unknown " + f"allocator {mechanism['allocator']!r}; expected one of " + f"{sorted(ALLOCATORS)}." + ) + if mechanism["control"]["kind"] not in _CONTROL_KINDS: + raise ValueError( + f"US cross-grain mechanism {mechanism_id!r} names unknown " + f"control kind {mechanism['control']['kind']!r}; expected one " + f"of {_CONTROL_KINDS}." + ) + return payload + + +def us_cross_grain_mechanism(mechanism_id: str) -> Mapping[str, Any]: + """One declared mechanism; an unknown id is refused.""" + + mechanisms = load_us_cross_grain_declarations()["mechanisms"] + if mechanism_id not in mechanisms: + raise ValueError( + f"Unknown US cross-grain mechanism {mechanism_id!r}; declared: " + f"{sorted(mechanisms)}." + ) + return mechanisms[mechanism_id] + + +@dataclass(frozen=True) +class DistrictSoiNesting: + """The declared choices of the state-to-district SOI mechanism.""" + + vintage_rule: str + allocator: str + level_bridges: Mapping[str, str] + factor_band: float + internal_rtol: float + closure_rtol: float + reviewed_crosswalk_sha256: str + defective_lower_measures: Mapping[str, str] + unparented_lower_measures: Mapping[str, str] + excluded_legs: Mapping[str, str] + + +@functools.lru_cache(maxsize=1) +def us_district_soi_nesting() -> DistrictSoiNesting: + declared = us_cross_grain_mechanism(DISTRICT_SOI) + registers = declared["registers"] + return DistrictSoiNesting( + vintage_rule=str(declared["vintage_rule"]), + allocator=str(declared["allocator"]), + level_bridges=dict(declared["control"]["level_bridges"]["siblings"]), + factor_band=declared["factor_band"]["tolerance"], + internal_rtol=declared["self_consistency"]["rtol"], + closure_rtol=declared["closure"]["rtol"], + reviewed_crosswalk_sha256=str(declared["members"]["reviewed_crosswalk_sha256"]), + defective_lower_measures=dict(registers["defective_lower_measures"]["entries"]), + unparented_lower_measures=dict( + registers["unparented_lower_measures"]["entries"] + ), + excluded_legs=dict(registers["excluded_legs"]["entries"]), + ) + + +@dataclass(frozen=True) +class CountySoiNesting: + """The declared choices of the state-to-county SOI mechanism.""" + + allocator: str + required_measures: tuple[str, ...] + #: Absent county -> host county, as five-digit integer codes. + combined_cells: Mapping[int, int] + combined_cell_basis: str + + +@functools.lru_cache(maxsize=1) +def us_county_soi_nesting() -> CountySoiNesting: + declared = us_cross_grain_mechanism(COUNTY_SOI) + members = declared["members"] + return CountySoiNesting( + allocator=str(declared["allocator"]), + required_measures=tuple(str(m) for m in declared["required_measures"]), + combined_cells={ + int(cell["absent"]): int(cell["host"]) for cell in members["combined_cells"] + }, + combined_cell_basis=str(members["combined_cell_basis"]), + ) diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/target_nesting.py b/packages/microcosm-build/src/microcosm/build/us_runtime/target_nesting.py new file mode 100644 index 0000000000..a07cfa6ce8 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/target_nesting.py @@ -0,0 +1,278 @@ +"""US target nesting on the shared cross-grain operator (microcosm#1760). + +A target for a small area must agree with the target of the area that +contains it. This module makes the rows of a lower geography level from a +control at a higher level, for each mechanism that +``us/cross_grain_declarations.json`` declares. The arithmetic is not here: + +- :func:`microcosm.build.cross_grain.apply_cross_grain_reconciliation` groups + the rows of one quantity, finds the control of each lower leg, divides it + among the leg's rows with the mechanism's declared allocator, checks the sum + and writes its receipt; +- :mod:`microcosm.build.cross_grain_controls` supplies the allocators, the + derived controls, the factor band, the completeness check and the + self-consistency check. + +What is here is the US side of each mechanism: which specs or facts are the +control and the lower rows, the refusals with their US wording, and the +metadata keys and receipts the local tools wrote before the operator made the +rows. Stage A changes no value: every surface has the bytes it had. + +The module reads specs and facts only. It reads no frame and no household. +""" + +from __future__ import annotations + +import json +from collections.abc import Mapping, Sequence +from contextvars import ContextVar +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import numpy as np +import pandas as pd + +from microcosm.build.cross_grain import ( + CrossGrainRule, + apply_cross_grain_reconciliation, +) +from microcosm.build.cross_grain_controls import allocator_named +from microcosm.build.us_runtime.cross_grain_declarations import ( + load_us_cross_grain_declarations, + us_cross_grain_mechanism, +) + +#: The file a materialize stage writes the operator's own receipts to. +NESTING_RECEIPTS_FILENAME = "target_nesting.json" + +# --------------------------------------------------------------------------- +# Blocks through the operator +# --------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class NestingBlock: + """One control and the lower rows it is divided among. + + ``concept`` and ``filters`` are the measurement signature that ties the + control to its rows. ``lower_values`` are in the order the allocator must + see them: a residual rule gives its residual to the first of equal + largest rows. + """ + + concept: str + filters: tuple[tuple[str, str], ...] + control_geography_id: str + control_value: float + lower_geography_ids: tuple[str, ...] + lower_values: tuple[float, ...] + + +@dataclass(frozen=True) +class NestedRows: + """A block's rows as the operator left them, with its leg receipt.""" + + values: tuple[float, ...] + #: The factor and the lower-row total the allocator reported. + factor: float + lower_sum: float + + +def geography_id(grain: str, code: str) -> str: + """A surface geography id that cannot collide across grains.""" + + return f"{grain}:{code}" + + +def _signature_key(block: NestingBlock) -> str: + return "|".join( + [block.concept, *(f"{name}={value}" for name, value in block.filters)] + ) + + +def reconcile_blocks( + mechanism_id: str, blocks: Sequence[NestingBlock] +) -> tuple[list[NestedRows], dict[str, Any]]: + """Divide each block's control among its rows on the shared operator. + + Builds one surface for the mechanism (a control row and the lower rows of + every block), runs :func:`apply_cross_grain_reconciliation` with the + mechanism's declared allocator, and returns each block's rows, in block + order, with the operator's receipt. A block is one leg: its control row + parents exactly its own lower rows. + + Raises: + ValueError: If two blocks share a signature and a control geography, + if a lower row sits under two controls, if a block has no lower + row, or if the operator refuses a block (a vanishing or + non-finite total, a negative factor, or rows off their control). + """ + + declarations = load_us_cross_grain_declarations() + mechanism = us_cross_grain_mechanism(mechanism_id) + higher, lower = str(mechanism["higher_grain"]), str(mechanism["lower_grain"]) + rows: list[tuple[str, str, str, float]] = [] + signatures: dict[str, dict[str, Any]] = {} + bound: list[str] = [] + area_legs: dict[str, str] = {} + spans: list[tuple[str, int, int]] = [] + controls_seen: set[tuple[str, str]] = set() + for block in blocks: + key = _signature_key(block) + control_id = f"{mechanism_id}:{higher}:{key}" + lower_id = f"{mechanism_id}:{lower}:{key}" + if (control_id, block.control_geography_id) in controls_seen: + raise ValueError( + f"Nesting mechanism {mechanism_id!r} has two blocks for {key!r} " + f"at {block.control_geography_id!r}." + ) + controls_seen.add((control_id, block.control_geography_id)) + if not block.lower_geography_ids or len(block.lower_geography_ids) != len( + block.lower_values + ): + raise ValueError( + f"Nesting mechanism {mechanism_id!r} block {key!r} at " + f"{block.control_geography_id!r} needs one value for each of " + "its lower rows, and at least one row." + ) + if control_id not in signatures: + measurement = { + "concept": block.concept, + "filters": [{name: value} for name, value in block.filters], + } + signatures[control_id] = {"measurement": measurement} + signatures[lower_id] = {"measurement": measurement} + bound.append(control_id) + rows.append( + (higher, block.control_geography_id, control_id, block.control_value) + ) + start = len(rows) + for area, value in zip( + block.lower_geography_ids, block.lower_values, strict=True + ): + if area_legs.setdefault(area, block.control_geography_id) != ( + block.control_geography_id + ): + raise ValueError( + f"Nesting mechanism {mechanism_id!r}: lower geography " + f"{area!r} sits under two controls." + ) + rows.append((lower, area, lower_id, float(value))) + spans.append((control_id, start, len(rows))) + if not blocks: + receipt: dict[str, Any] = { + "absence": f"Mechanism {mechanism_id} had no block to reconcile." + } + _record(mechanism_id, 0, receipt) + return [], receipt + surface = pd.DataFrame( + rows, columns=["grain", "geography_id", "target_id", "value"] + ) + rule = CrossGrainRule( + grain_precedence=tuple(declarations["grain_precedence"]), + signature_fields=tuple(declarations["signature_fields"]), + bridges=(), + leg_of_area=area_legs.__getitem__, + parent_geography_legs={ + control_geography: (control_geography,) + for _control_id, control_geography in sorted(controls_seen) + }, + control_grains=tuple(declarations["control_grains"]), + allocator=allocator_named(str(mechanism["allocator"])), + ) + reconciled, receipt = apply_cross_grain_reconciliation( + surface, bound, signatures, rule + ) + values = reconciled["value"].to_numpy(dtype=np.float64) + legs = { + (leg["higher_target_ids"][0], leg["parent_geography_id"]): leg + for group in receipt["groups"] + for leg in group["legs"] + } + nested: list[NestedRows] = [] + for block, (control_id, start, stop) in zip(blocks, spans, strict=True): + leg = legs.get((control_id, block.control_geography_id)) + if leg is None: + raise ValueError( + f"Nesting mechanism {mechanism_id!r}: the operator did not " + f"reconcile the block at {block.control_geography_id!r}." + ) + nested.append( + NestedRows( + values=tuple(values[start:stop].tolist()), + factor=leg["declared_factor"], + lower_sum=leg["old_total"], + ) + ) + _record(mechanism_id, len(blocks), receipt) + return nested, receipt + + +# --------------------------------------------------------------------------- +# The operator's own receipts +# --------------------------------------------------------------------------- + +_RECEIPTS: ContextVar[list[dict[str, Any]] | None] = ContextVar( + "us_target_nesting_receipts", default=None +) + + +def start_nesting_receipts() -> list[dict[str, Any]]: + """Start a fresh record of the nesting passes that run from here on. + + The four tool functions keep the signatures and the receipts they had, so + the operator's own receipt cannot travel in their results. A stage that + wants it calls this first and writes the list with + :func:`write_nesting_receipts` when its targets are made. Without a call, + nothing is recorded. + """ + + receipts: list[dict[str, Any]] = [] + _RECEIPTS.set(receipts) + return receipts + + +def stop_nesting_receipts() -> None: + """End the record that :func:`start_nesting_receipts` started.""" + + _RECEIPTS.set(None) + + +def _record(mechanism_id: str, blocks: int, receipt: Mapping[str, Any]) -> None: + receipts = _RECEIPTS.get() + if receipts is not None: + mechanism = us_cross_grain_mechanism(mechanism_id) + receipts.append( + { + "mechanism": mechanism_id, + "issue_row": mechanism["issue_row"], + "allocator": mechanism["allocator"], + "blocks": blocks, + "operator_receipt": dict(receipt), + } + ) + + +def write_nesting_receipts( + checkpoint_dir: Path, receipts: Sequence[Mapping[str, Any]] +) -> Path: + """Write the recorded operator receipts beside the stage's other files. + + The file is a receipt only. No stage reads it, and it is not part of the + run identity. + """ + + path = Path(checkpoint_dir) / NESTING_RECEIPTS_FILENAME + path.write_text( + json.dumps( + { + "schema_version": 1, + "operator": "microcosm.build.cross_grain", + "declarations": "us/cross_grain_declarations.json", + "passes": list(receipts), + }, + indent=2, + ) + ) + return path diff --git a/packages/microcosm-build/tests/engine_contract/us/test_spec_engine_coverage_tool.py b/packages/microcosm-build/tests/engine_contract/us/test_spec_engine_coverage_tool.py index 3a8ec0d1df..726dfa5037 100644 --- a/packages/microcosm-build/tests/engine_contract/us/test_spec_engine_coverage_tool.py +++ b/packages/microcosm-build/tests/engine_contract/us/test_spec_engine_coverage_tool.py @@ -82,22 +82,22 @@ def test_us_coverage_is_exact_complete_and_honest( assert_coverage_complete(coverage_report) assert coverage_report["status"] == "pass" fields = coverage_report["field_usage"] - assert fields["configuration_field_count"] == 42404 - assert fields["authored_normative_field_count"] == 32618 + assert fields["configuration_field_count"] == 42407 + assert fields["authored_normative_field_count"] == 32621 assert fields["resolved_binding_field_count"] == 9786 - assert fields["consumed_field_count"] == 42404 + assert fields["consumed_field_count"] == 42407 assert fields["unused_field_count"] == 0 assert fields["multiple_primary_use_field_count"] == 0 assert fields["claim_count"] == 48 assert fields["mode_counts"] == { "legacy_behavior": 14_269, "compiler_semantic": 27674, - "front_end_validation": 358, + "front_end_validation": 361, "identity_only": 103, } assert fields["generation0_effect_counts"] == { "legacy_behavior": 38_780, - "no_generation0_effect": 3624, + "no_generation0_effect": 3627, } inventory = coverage_report["inventory_coverage"] diff --git a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_field_usage.py b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_field_usage.py index 6db563c643..dbfbae1de4 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_field_usage.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_field_usage.py @@ -95,22 +95,22 @@ def _mutated_bundle( def test_exact_complete_ledger_has_one_primary_mode_per_pointer(field_ledger) -> None: - assert len(field_ledger.fields) == EXPECTED_CONFIGURATION_FIELD_COUNT == 42404 + assert len(field_ledger.fields) == EXPECTED_CONFIGURATION_FIELD_COUNT == 42407 assert field_ledger.source_counts == { - "authored": 32618, + "authored": 32621, "resolved_bindings": 9786, } assert field_ledger.mode_counts == { "legacy_behavior": 14_269, "compiler_semantic": 27674, - "front_end_validation": 358, + "front_end_validation": 361, "identity_only": 103, } assert field_ledger.generation0_effect_counts == { "legacy_behavior": 38_780, - "no_generation0_effect": 3624, + "no_generation0_effect": 3627, } - assert len({field.pointer for field in field_ledger.fields}) == 42404 + assert len({field.pointer for field in field_ledger.fields}) == 42407 def test_eligibility_concepts_are_validation_not_generation0_behavior( diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_cross_grain_declarations.py b/packages/microcosm-build/tests/engine_free/us/test_us_cross_grain_declarations.py new file mode 100644 index 0000000000..cc54f2d8ac --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_cross_grain_declarations.py @@ -0,0 +1,271 @@ +"""The US nesting declarations and the adapter's path to the operator. + +``us/cross_grain_declarations.json`` holds the US choices of the shared +cross-grain operator (microcosm#1760). The registers in it were Python +literals in the local tools; the tools read them from the declaration under +their old names. These tests hold each one to the literal it replaces +(``test_support/microcosm_build/us_target_nesting_reference.py`` is the tool +code before the move), and check the declaration's shape and the adapter's +block interface. +""" + +from __future__ import annotations + +import importlib +import json +import sys +from importlib import resources as importlib_resources + +import pytest + +from microcosm.build import cross_grain_controls +from microcosm.build.us_runtime import cross_grain_declarations as declarations +from microcosm.build.us_runtime import target_nesting +from microcosm.build.us_runtime.target_nesting import NestingBlock +from test_support.microcosm_build import us_target_nesting_reference as reference +from test_support.paths import paths_for + +_TEST_PATHS = paths_for("microcosm-build") + +DISTRICT_REGISTERS = ( + "STATE_CD_VINTAGE_RULE", + "STATE_CD_DEFECTIVE_CD_FILE_MEASURES", + "STATE_CD_UNPARENTED_CD_MEASURES", + "STATE_CD_LEVEL_BRIDGES", + "STATE_CD_EXCLUDED_CD_STATES", + "STATE_CD_FACTOR_BAND", + "STATE_CD_INTERNAL_RTOL", + "RECONCILIATION_RTOL", +) +COUNTY_REGISTERS = ( + "COUNTY_SOI_REQUIRED_MEASURES", + "DECLARED_SOI_COMBINED_CELLS", + "SOI_COMBINED_CELL_BASIS", +) + + +def _load_tool(name: str): + """A tool module by its own name, as the local release tool imports it.""" + + tools = _TEST_PATHS.repository / "tools" + if str(tools) not in sys.path: + sys.path.insert(0, str(tools)) + return importlib.import_module(name) + + +@pytest.fixture(scope="module") +def district_tool(): + return _load_tool("us_acs_local_cd_surface") + + +@pytest.fixture(scope="module") +def county_tool(): + return _load_tool("us_acs_local_county_surface") + + +def _same(new, old) -> bool: + """Equal in value, type and, for a mapping, order of entries.""" + + if type(new) is not type(old) or new != old: + return False + if isinstance(old, dict): + return list(new.items()) == list(old.items()) and all( + type(new[key]) is type(old[key]) for key in old + ) + return True + + +@pytest.mark.parametrize("name", DISTRICT_REGISTERS) +def test_a_district_register_is_the_literal_it_replaces(district_tool, name) -> None: + assert _same(getattr(district_tool, name), getattr(reference, name)) + + +@pytest.mark.parametrize("name", COUNTY_REGISTERS) +def test_a_county_register_is_the_literal_it_replaces(county_tool, name) -> None: + assert _same(getattr(county_tool, name), getattr(reference, name)) + + +def test_the_tools_hold_copies_not_the_cached_declaration(district_tool) -> None: + declared = declarations.us_district_soi_nesting() + assert district_tool.STATE_CD_LEVEL_BRIDGES == declared.level_bridges + assert district_tool.STATE_CD_LEVEL_BRIDGES is not declared.level_bridges + + +def test_the_declaration_names_the_operators_keys_as_the_uk_file_does() -> None: + declared = declarations.load_us_cross_grain_declarations() + uk = json.loads( + importlib_resources.files("microcosm.build.uk") + .joinpath("cross_grain_declarations.json") + .read_text(encoding="utf-8") + ) + # Every US key but the US-only sections is a key of the UK file. + us_only = {"mechanisms", "inventory"} + assert set(declared) - us_only <= set(uk) + assert declared["schema_version"] == uk["schema_version"] == 1 + # The US levels are the feed's own geography levels, widest first. + assert declared["grain_precedence"] == [ + "country", + "state", + "congressional_district", + "county", + ] + assert declared["control_grains"] == ["country", "state"] + # No UK-style bridge or partition is in force: each mechanism ties a + # control to its rows by an exact measurement signature. + assert declared["bridges"] == [] and declared["partitions"] == [] + + +def test_each_mechanism_declares_its_rule() -> None: + declared = declarations.load_us_cross_grain_declarations() + mechanisms = declared["mechanisms"] + assert list(mechanisms) == [ + declarations.DISTRICT_SOI, + declarations.COUNTY_POPULATION, + declarations.COUNTY_SOI, + declarations.COUNTY_ACS_HOUSEHOLDS, + ] + assert { + mechanism_id: ( + mechanism["issue_row"], + mechanism["allocator"], + mechanism["control"]["kind"], + ) + for mechanism_id, mechanism in mechanisms.items() + } == { + declarations.DISTRICT_SOI: ( + 5, + "proportional_fsum", + "bound_row_or_scaled_by_sibling_ratio", + ), + declarations.COUNTY_POPULATION: (8, "scale_residual_to_largest", "bound_row"), + declarations.COUNTY_SOI: (6, "share_residual_to_largest", "bound_row"), + declarations.COUNTY_ACS_HOUSEHOLDS: ( + 7, + "share_residual_to_largest", + "sum_of_lower_rows", + ), + } + for mechanism in mechanisms.values(): + assert mechanism["allocator"] in cross_grain_controls.ALLOCATORS + assert mechanism["higher_grain"] in declared["control_grains"] + assert mechanism["members"]["source"] + assert mechanism["control"]["description"] + assert "lower_rows" in mechanism["metadata_keys"] + assert ( + _TEST_PATHS.repository / mechanism["tool_function"].split(":")[0] + ).exists() + + +def test_an_unknown_mechanism_is_refused() -> None: + with pytest.raises(ValueError, match="Unknown US cross-grain mechanism"): + declarations.us_cross_grain_mechanism("state_tract_soi") + + +def _block(state: str, values: tuple[float, ...], control: float, concept="quantity"): + return NestingBlock( + concept=concept, + filters=(("band", "all"),), + control_geography_id=target_nesting.geography_id("state", state), + control_value=control, + lower_geography_ids=tuple( + target_nesting.geography_id("county", f"{state}{index:03d}") + for index in range(1, len(values) + 1) + ), + lower_values=values, + ) + + +def test_blocks_go_through_the_operator_with_the_declared_allocator() -> None: + blocks = [ + _block("06", (30.0, 20.0), 100.0), + _block("36", (1.0, 3.0), 8.0), + _block("06", (5.0, 5.0), 40.0, concept="other_quantity"), + ] + nested, receipt = target_nesting.reconcile_blocks( + declarations.COUNTY_POPULATION, blocks + ) + + assert [rows.values for rows in nested] == [(60.0, 40.0), (2.0, 6.0), (20.0, 20.0)] + assert [(rows.factor, rows.lower_sum) for rows in nested] == [ + (2.0, 50.0), + (2.0, 4.0), + (4.0, 10.0), + ] + # One group for each quantity, one leg for each state, and the operator's + # receipt names the allocator the mechanism declares. + assert len(receipt["groups"]) == 2 + legs = [leg for group in receipt["groups"] for leg in group["legs"]] + assert sorted(leg["parent_geography_id"] for leg in legs) == [ + "state:06", + "state:06", + "state:36", + ] + assert {leg["allocator"] for leg in legs} == {"scale_residual_to_largest"} + assert {group["winning_grain"] for group in receipt["groups"]} == {"state"} + assert {group["lower_grain"] for group in receipt["groups"]} == {"county"} + + +def test_a_block_the_operator_cannot_place_is_refused() -> None: + mechanism = declarations.COUNTY_POPULATION + with pytest.raises(ValueError, match="two blocks"): + target_nesting.reconcile_blocks( + mechanism, [_block("06", (1.0,), 2.0), _block("06", (1.0,), 2.0)] + ) + stray = NestingBlock( + "quantity", + (), + target_nesting.geography_id("state", "36"), + 2.0, + (target_nesting.geography_id("county", "06001"),), + (1.0,), + ) + with pytest.raises(ValueError, match="sits under two controls"): + target_nesting.reconcile_blocks( + mechanism, + [ + NestingBlock( + "other", + (), + target_nesting.geography_id("state", "06"), + 2.0, + (target_nesting.geography_id("county", "06001"),), + (1.0,), + ), + stray, + ], + ) + with pytest.raises(ValueError, match="at least one row"): + target_nesting.reconcile_blocks(mechanism, [_block("06", (), 2.0)]) + # The operator's own refusals reach the caller. + with pytest.raises(ValueError, match="vanishing lower-leg total"): + target_nesting.reconcile_blocks(mechanism, [_block("06", (0.0, 0.0), 2.0)]) + + +def test_the_operators_receipts_are_recorded_only_when_asked(tmp_path) -> None: + blocks = [_block("06", (30.0, 20.0), 100.0)] + recorded = target_nesting.start_nesting_receipts() + _nested, receipt = target_nesting.reconcile_blocks( + declarations.COUNTY_POPULATION, blocks + ) + assert [entry["mechanism"] for entry in recorded] == [ + declarations.COUNTY_POPULATION + ] + assert recorded[0]["operator_receipt"] == receipt + assert (recorded[0]["issue_row"], recorded[0]["blocks"]) == (8, 1) + + path = target_nesting.write_nesting_receipts(tmp_path, recorded) + assert path.name == target_nesting.NESTING_RECEIPTS_FILENAME + written = json.loads(path.read_text()) + assert written["operator"] == "microcosm.build.cross_grain" + assert [entry["mechanism"] for entry in written["passes"]] == [ + declarations.COUNTY_POPULATION + ] + + # A new record starts empty, and the earlier list gains nothing more. + fresh = target_nesting.start_nesting_receipts() + target_nesting.reconcile_blocks(declarations.COUNTY_POPULATION, blocks) + assert len(fresh) == 1 and len(recorded) == 1 + # After a stop, a pass records nothing. + target_nesting.stop_nesting_receipts() + target_nesting.reconcile_blocks(declarations.COUNTY_POPULATION, blocks) + assert len(fresh) == 1 diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py b/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py index e0ff6f7d90..ec9b46249f 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_spine_blindness.py @@ -325,6 +325,9 @@ # 2020 tract/county -> 2023 county-equivalent metadata and its gate; # writes calibration geography only, no population treatment. "county_vintage.py", + # The US nesting declarations of the shared cross-grain operator + # (microcosm#1760): a typed read of a packaged JSON file. + "cross_grain_declarations.py", # Household location v1 (#696): one block per household within its # finest source geography; every geography derives from the block. # Reached by the stacked pool under --location-rule block_v1 and @@ -475,6 +478,10 @@ # Calibration loss weights computed from target specs alone; reads no # frame and treats no population. "target_loss_weights.py", + # Target nesting across geography levels on the shared cross-grain + # operator (microcosm#1760): reads target specs and facts only, no + # frame and no population. + "target_nesting.py", # Data-only final-owner matrix; provenance owner above. "us_late_overlap_ownership.py", # Data-only late input/output registry; provenance owner above. diff --git a/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py b/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py index 6be927d3a6..7a6a25b236 100644 --- a/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py +++ b/packages/microcosm-build/tests/engine_workflow/us/test_us_multispine_pool_tool.py @@ -373,7 +373,7 @@ def capture_equality(expected: object, actual: object) -> None: # microcosm#1686's shared SIPP person-file read moves it again. # The SIPP 2023 donor download tag and the financial-asset cache lookup # move it again. - "spec_sha256": "b94bfc6a5742de010443938a676d4d34e70df80dd405f89e2ff7a70f747c8107", + "spec_sha256": "9141b9bf0fa71678c7b7f0c55bc96e040cdfab378f09b54540659910560b0424", }, } diff --git a/test_support/microcosm_build/us_target_nesting_reference.py b/test_support/microcosm_build/us_target_nesting_reference.py new file mode 100644 index 0000000000..daa7cd8d2e --- /dev/null +++ b/test_support/microcosm_build/us_target_nesting_reference.py @@ -0,0 +1,1383 @@ +"""Verbatim copies of the US share code before microcosm#1760 moved it. + +``tools/us_acs_local_cd_surface.py`` and ``tools/us_acs_local_county_surface.py`` +held this code at ``e29843dc7``: ``state_cd_soi_surface`` (the district SOI +shares), ``with_county_populations`` (the county population rows), +``state_county_soi_surface`` (the county SOI shares) and +``acs_household_surface`` (the county household rows), with the constants and +helpers they read. The arithmetic now runs on the shared cross-grain operator +(``microcosm.build.cross_grain``), through +``microcosm.build.us_runtime.target_nesting``. The equivalence tests hold the +tool functions to these copies. Nothing changed: each definition is the +tool's source text, in the tool's order, district file first. + +``_release_tool`` imports the national release tool by name, as the district +tool does, so ``tools/`` must be on ``sys.path`` (loading the local release +tool puts it there). +""" + +# ruff: noqa + +from __future__ import annotations + +import dataclasses +import math +from collections import Counter, defaultdict +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass, replace + +import numpy as np +import pandas as pd + + +CD_FILE_RECORD_SET_SPEC_PREFIX = "irs_soi.congressional_district_" + + +STATE_CD_VINTAGE_RULE = "state_cd.historic_table_2_level_cd_file_shares.v1" + + +STATE_CD_DEFECTIVE_CD_FILE_MEASURES: Mapping[str, str] = { + "limited_state_local_taxes_amount": ( + "22incd.csv column A18425 is state and local income taxes (Schedule A " + "line 5a), not the limited SALT deduction (A18460); the district " + "file sums to 1.98x Historic Table 2 (microcosm#1038)." + ), + "limited_state_local_taxes_returns": ( + "22incd.csv column N18425 counts state and local income-tax " + "deductions, not the limited SALT deduction (microcosm#1038)." + ), + "premium_tax_credit_returns": ( + "22incd.csv column N85530 is the additional Medicare tax (Form 8959 " + "line 24), not the premium tax credit (N85770) (microcosm#1038)." + ), +} + + +STATE_CD_UNPARENTED_CD_MEASURES: Mapping[str, str] = { + "tax_filer_individual_count": ( + "The compiler drops this measure at state and national geography " + "(fiscal_targets._soi_reference_from_fact), so no state target exists " + "for its district rows to reconcile to." + ), +} + + +STATE_CD_LEVEL_BRIDGES: Mapping[str, str] = { + "charitable_amount": "itemized_deductions_amount", + "charitable_returns": "return_count", + "interest_paid_deduction_amount": "itemized_deductions_amount", + "interest_paid_deduction_returns": "return_count", + "qualified_business_income_deduction_amount": "adjusted_gross_income", + "qualified_business_income_deduction_returns": "return_count", +} + + +STATE_CD_EXCLUDED_CD_STATES: Mapping[str, str] = {} + + +STATE_CD_FACTOR_BAND = 1.25 + + +STATE_CD_INTERNAL_RTOL = 1e-6 + + +RECONCILIATION_RTOL = 1e-9 + + +GEOGRAPHY_STATE = "state" + + +GEOGRAPHY_CD = "congressional_district" + + +def _release_tool(): + """The sibling release tool (``tools/`` is on ``sys.path`` via the ACS tool).""" + + import build_us_fiscal_refresh_release as release_tool + + return release_tool + + +def _metadata(spec) -> Mapping[str, str]: + return spec.metadata + + +def geography_level(spec) -> str | None: + return _metadata(spec).get("ledger_geography_level") + + +def record_set_spec_id(spec) -> str: + return str(_metadata(spec).get("ledger_layout_record_set_spec_id") or "") + + +def is_cd_file_spec(spec) -> bool: + return record_set_spec_id(spec).startswith(CD_FILE_RECORD_SET_SPEC_PREFIX) + + +def soi_materializer_semantics(spec) -> tuple: + """Everything the SOI slice reads from a spec, except its geography. + + ``_base_simulation_household_columns`` builds an ``irs_soi`` column from + exactly these fields plus ``state_fips`` and + ``congressional_district_geoid``. Two specs with equal semantics + therefore materialize the same household column up to their geography + masks. + """ + + tool = _release_tool() + metadata = _metadata(spec) + return ( + spec.family, + spec.entity, + spec.filter, + metadata.get("source_variable", metadata.get("variable")), + repr(tool._as_bound(metadata["agi_lower_bound"])), + repr(tool._as_bound(metadata["agi_upper_bound"])), + metadata.get("taxable_only") == "true", + metadata.get("filing_status"), + tool._soi_eitc_child_count_filter(metadata), + tool._soi_requires_positive_eitc_filter(metadata), + metadata.get("itemized_only") == "true", + metadata.get("measure_mode") == "indicator_sum", + tool._unsupported_soi_ledger_filters(metadata), + ) + + +def soi_concept_identity(spec) -> tuple[str, ...]: + """The published concept a spec measures, independent of vintage. + + Historic Table 2 and the district file name the same concept with the + same ``source_measure_id``; the AGI band, filing status and EITC child + count separate the Historic Table 2 band rows from the all-income rows. + """ + + tool = _release_tool() + metadata = _metadata(spec) + return ( + str(metadata.get("source_measure_id")), + repr(tool._as_bound(metadata["agi_lower_bound"])), + repr(tool._as_bound(metadata["agi_upper_bound"])), + str(metadata.get("filing_status", "")).lower(), + str(tool._soi_eitc_child_count_filter(metadata)), + ) + + +@dataclass(frozen=True) +class StateCdSurface: + """The ``state_cd`` SOI specs and the receipt that explains them.""" + + specs: tuple + receipt: dict + + +def _crosswalk_district_sets(crosswalk: pd.DataFrame): + """(source districts per state, target districts per state) as SSDD.""" + + source: dict[str, set[str]] = defaultdict(set) + target: dict[str, set[str]] = defaultdict(set) + for source_id, target_id in zip( + crosswalk["source_geography_id"].astype(str), + crosswalk["target_geography_id"].astype(str), + strict=True, + ): + source[source_id[-4:-2]].add(source_id[-4:]) + target[target_id[-4:-2]].add(target_id[-4:]) + return dict(source), dict(target) + + +def _factor_summary(values: Sequence[float]) -> dict[str, float | int]: + array = np.asarray(values, dtype=np.float64) + return { + "n": int(array.size), + "min": float(array.min()), + "median": float(np.median(array)), + "max": float(array.max()), + } + + +def state_cd_soi_surface( + soi_specs: Sequence, + *, + state_surface_predicate: Callable[[object], bool], + crosswalk: pd.DataFrame, + crosswalk_sha256: str | None = None, + level_bridges: Mapping[str, str] = STATE_CD_LEVEL_BRIDGES, + factor_band: float = STATE_CD_FACTOR_BAND, +) -> StateCdSurface: + """Select and reconcile the ``state_cd`` SOI surface. + + Args: + soi_specs: Every compiled ``irs_soi`` spec (the ``full`` surface). + state_surface_predicate: The ``state`` mode's predicate; its specs + (Historic Table 2) are the state surface. + crosswalk: The 117th->119th CD crosswalk the compiler used; it names + each state's source-plan and current-plan districts. + crosswalk_sha256: Recorded in the receipt. + level_bridges: District-file-only measure -> sibling measure whose + Historic Table 2 / district-file ratio in the same state lifts + the district file's state level onto the Historic Table 2 basis. + factor_band: Largest allowed ratio between a state's Historic Table 2 + / district-file ratio and its measure's median across states + (either direction); see ``STATE_CD_FACTOR_BAND``. + + Returns: + The surface in a fixed order (Historic Table 2 state rows, district + file state rows, district rows) and its receipt. + + Raises: + ValueError: If a district concept is incomplete in a state, if its + district rows disagree on what they materialize, if a parent's + materialization differs from its children's, or if a parent + cannot absorb its children (zero sum under a nonzero parent, or + a sign conflict). + """ + + source_districts, target_districts = _crosswalk_district_sets(crosswalk) + at_large_source_states = sorted( + state for state, districts in source_districts.items() if len(districts) == 1 + ) + dropped: Counter = Counter() + dropped_examples: dict[str, str] = {} + + def drop(spec, reason: str) -> None: + dropped[reason] += 1 + dropped_examples.setdefault(reason, spec.name) + + ht2_state: list = [] + cd_file_state: list = [] + cd_rows: list = [] + for spec in soi_specs: + level = geography_level(spec) + if state_surface_predicate(spec): + ht2_state.append(spec) + elif is_cd_file_spec(spec) and level == GEOGRAPHY_STATE: + cd_file_state.append(spec) + elif is_cd_file_spec(spec) and level == GEOGRAPHY_CD: + cd_rows.append(spec) + elif level == GEOGRAPHY_CD: + drop(spec, "historic_table_2_at_large_proxy_district_row") + else: + drop(spec, f"not_state_cd_geography:{level}") + + ht2_by_key = {} + for spec in ht2_state: + key = (spec.metadata["state_fips"], soi_concept_identity(spec)) + if key in ht2_by_key: + raise ValueError( + f"Two Historic Table 2 state specs measure {key}: " + f"{ht2_by_key[key].name} and {spec.name}." + ) + ht2_by_key[key] = spec + cd_file_state_by_key = {} + for spec in cd_file_state: + key = (spec.metadata["state_fips"], soi_concept_identity(spec)) + if key in cd_file_state_by_key: + raise ValueError( + f"Two district-file state specs measure {key}: " + f"{cd_file_state_by_key[key].name} and {spec.name}." + ) + cd_file_state_by_key[key] = spec + + # Each state concept both files carry: its Historic Table 2 / district-file + # ratio, judged against the measure's median ratio across states. + vintage_ratio: dict[tuple, float] = {} + for key in ht2_by_key.keys() & cd_file_state_by_key.keys(): + ht2_value = float(ht2_by_key[key].value) + cd_value = float(cd_file_state_by_key[key].value) + vintage_ratio[key] = ( + ht2_value / cd_value + if cd_value != 0.0 and (ht2_value > 0) == (cd_value > 0) + else math.nan + ) + ratios_by_identity: dict[tuple, list[float]] = defaultdict(list) + for (_state, identity), ratio in vintage_ratio.items(): + if math.isfinite(ratio): + ratios_by_identity[identity].append(ratio) + median_ratio = { + identity: float(np.median(values)) + for identity, values in ratios_by_identity.items() + } + out_of_band: list[dict] = [] + + def within_band( + key: tuple, + ratio: float, + median: float, + basis: str, + measure: str, + *, + verdict: str, + ) -> bool: + relative = ratio / median if math.isfinite(ratio) and median else math.nan + ok = math.isfinite(relative) and 1 / factor_band <= relative <= factor_band + if not ok: + out_of_band.append( + { + "state_fips": key[0], + "measure": measure, + "concept": key[1][0], + "basis": basis, + "verdict": verdict, + "ratio": ratio, + "median_ratio": median, + "relative": relative, + } + ) + return ok + + kept_cd_by_key: dict[tuple, list] = defaultdict(list) + for spec in cd_rows: + metadata = spec.metadata + measure = str(metadata.get("source_measure_id")) + state = str(metadata["state_fips"]) + if measure in STATE_CD_DEFECTIVE_CD_FILE_MEASURES: + drop(spec, f"defective_cd_file_column:{measure}") + elif measure in STATE_CD_UNPARENTED_CD_MEASURES: + drop(spec, f"no_state_parent:{measure}") + elif state in at_large_source_states: + drop(spec, "at_large_on_source_plan") + elif state in STATE_CD_EXCLUDED_CD_STATES: + drop(spec, f"excluded_state:{state}") + else: + kept_cd_by_key[(state, soi_concept_identity(spec))].append(spec) + + # Each Historic-Table-2-parented block's rebase factor (parent over its + # district rows' sum), judged against its concept's median across states. + block_factor: dict[tuple, float] = {} + for key, block in kept_cd_by_key.items(): + parent = ht2_by_key.get(key) + child_sum = math.fsum(float(spec.value) for spec in block) + if parent is not None and child_sum != 0.0: + block_factor[key] = float(parent.value) / child_sum + factors_by_identity: dict[tuple, list[float]] = defaultdict(list) + for (_state, identity), factor in block_factor.items(): + if math.isfinite(factor) and factor > 0: + factors_by_identity[identity].append(factor) + median_factor = { + identity: float(np.median(values)) + for identity, values in factors_by_identity.items() + } + + # One basis for every state level: a concept Historic Table 2 lacks keeps + # the district file's state row, scaled by a sibling's two levels. + bridged: dict[str, object] = {} + bridge_factors: dict[str, list[float]] = defaultdict(list) + for key, spec in sorted(cd_file_state_by_key.items()): + state, identity = key + measure = identity[0] + if key in ht2_by_key or measure in STATE_CD_DEFECTIVE_CD_FILE_MEASURES: + continue + sibling = level_bridges.get(measure) + if sibling is None: + raise ValueError( + f"District-file-only concept {measure!r} has no level bridge; " + "register a sibling measure in STATE_CD_LEVEL_BRIDGES before " + "binding it." + ) + sibling_key = (state, (sibling, *identity[1:])) + ht2_sibling = ht2_by_key.get(sibling_key) + cd_sibling = cd_file_state_by_key.get(sibling_key) + if ht2_sibling is None or cd_sibling is None or float(cd_sibling.value) == 0: + raise ValueError( + f"Level bridge {measure} -> {sibling} in state {state} needs " + "the sibling's state total in both files." + ) + factor = float(ht2_sibling.value) / float(cd_sibling.value) + # A sign conflict is a data defect, not a level disagreement: refuse + # it before the band, which only judges finite positive ratios. + if not (math.isfinite(factor) and factor > 0.0): + raise ValueError( + f"Level bridge {measure} -> {sibling} in state {state} has " + f"factor {factor}." + ) + # The sibling is trusted for bridging only if both of the band's + # verdicts on it pass: its two state levels, and (where it has district + # rows) the rebase of its own district block. + trusted = within_band( + sibling_key, + factor, + median_ratio.get(sibling_key[1], math.nan), + f"level_bridge:{measure}", + measure, + verdict="sibling_vintage_ratio", + ) + if sibling_key in block_factor: + trusted = ( + within_band( + sibling_key, + block_factor[sibling_key], + median_factor.get(sibling_key[1], math.nan), + f"level_bridge:{measure}", + measure, + verdict="sibling_rebase_factor", + ) + and trusted + ) + if not trusted: + continue + metadata = dict(spec.metadata) + metadata.update( + { + "state_cd_vintage_rule": STATE_CD_VINTAGE_RULE, + "state_cd_cd_file_value": repr(float(spec.value)), + "state_cd_level_bridge_sibling": ht2_sibling.name, + "state_cd_level_bridge_cd_file_sibling": cd_sibling.name, + "state_cd_level_bridge_factor": repr(factor), + } + ) + value = float(spec.value) * factor + bridged[spec.name] = replace( + spec, value=value, signed=value < 0.0, metadata=metadata + ) + bridge_factors[measure].append(factor) + + rebased: dict[str, object] = {} + internal_gaps: list[float] = [] + factors_by_measure: dict[str, list[float]] = defaultdict(list) + parent_basis_counts: Counter = Counter() + kept_cd_file_parents: set[str] = set() + for key in sorted(kept_cd_by_key): + state, identity = key + children = sorted( + kept_cd_by_key[key], + key=lambda spec: spec.metadata["congressional_district_geoid"], + ) + districts = [spec.metadata["congressional_district_geoid"] for spec in children] + expected = sorted(target_districts.get(state, ())) + if districts != expected: + raise ValueError( + f"District concept {identity} in state {state} covers " + f"{districts}, expected the current plan's {expected}; " + "rebasing an incomplete set would misstate every district." + ) + semantics = {soi_materializer_semantics(spec) for spec in children} + if len(semantics) != 1: + raise ValueError( + f"District rows of {identity} in state {state} materialize " + f"differently: {sorted(map(repr, semantics))}." + ) + (child_semantics,) = semantics + parent = ht2_by_key.get(key) + basis = "historic_table_2" + if parent is None: + parent = cd_file_state_by_key.get(key) + basis = "cd_file_state_total_bridged" + if parent is None: + raise ValueError( + f"District concept {identity} in state {state} has no " + "state parent in either vintage." + ) + if parent.name not in bridged: + for child in children: + drop(child, f"level_bridge_out_of_band:{identity[0]}") + continue + parent = bridged[parent.name] + kept_cd_file_parents.add(parent.name) + if soi_materializer_semantics(parent) != child_semantics: + raise ValueError( + f"State parent {parent.name} materializes differently from " + f"its district rows ({identity}, state {state})." + ) + child_sum = math.fsum(float(spec.value) for spec in children) + parent_value = float(parent.value) + if child_sum == 0.0: + if parent_value != 0.0: + raise ValueError( + f"District rows of {identity} in state {state} sum to zero " + f"under a nonzero parent {parent.name}={parent_value}." + ) + factor = 1.0 + else: + factor = parent_value / child_sum + if factor < 0.0: + raise ValueError( + f"District rows of {identity} in state {state} sum to " + f"{child_sum}, opposite in sign to parent {parent.name}=" + f"{parent_value}." + ) + # The district file must agree with itself before its shares are used. + cd_state = cd_file_state_by_key.get(key) + if cd_state is not None: + cd_state_value = float(cd_state.value) + gap = abs(cd_state_value - child_sum) + internal_gaps.append(gap / max(abs(cd_state_value), 1.0)) + if gap > STATE_CD_INTERNAL_RTOL * max(abs(cd_state_value), 1.0): + raise ValueError( + f"District-file state row {cd_state.name}={cd_state_value} " + f"differs from the sum of its district rows ({child_sum}) " + f"for {identity} in state {state}: a column or crosswalk " + "defect inside the district file." + ) + # An all-zero block agrees with a zero parent whatever the median. + if ( + basis == "historic_table_2" + and child_sum != 0.0 + and not within_band( + key, + factor, + median_factor.get(identity, math.nan), + "rebase", + identity[0], + verdict="rebase_factor", + ) + ): + for child in children: + drop(child, f"rebase_out_of_band:{identity[0]}") + continue + factors_by_measure[identity[0]].append(factor) + parent_basis_counts[basis] += len(children) + for child in children: + metadata = dict(child.metadata) + metadata.update( + { + "state_cd_vintage_rule": STATE_CD_VINTAGE_RULE, + "state_cd_parent_target_name": parent.name, + "state_cd_parent_basis": basis, + "state_cd_parent_value": repr(parent_value), + "state_cd_cd_file_value": repr(float(child.value)), + "state_cd_cd_file_state_sum": repr(child_sum), + "state_cd_rebase_factor": repr(factor), + } + ) + value = float(child.value) * factor + rebased[child.name] = replace( + child, + value=value, + signed=value < 0.0, + metadata=metadata, + ) + + kept_cd_file_state = [] + for spec in cd_file_state: + measure = str(spec.metadata.get("source_measure_id")) + key = (spec.metadata["state_fips"], soi_concept_identity(spec)) + if measure in STATE_CD_DEFECTIVE_CD_FILE_MEASURES: + drop(spec, f"defective_cd_file_column:{measure}") + elif key in ht2_by_key: + drop(spec, "second_vintage_of_state_concept") + elif spec.name not in bridged: + drop(spec, f"level_bridge_out_of_band:{measure}") + else: + kept_cd_file_state.append(bridged[spec.name]) + missing_parents = kept_cd_file_parents - {spec.name for spec in kept_cd_file_state} + if missing_parents: + raise ValueError( + f"District-file state parents {sorted(missing_parents)[:5]} were " + "dropped while their district rows were kept." + ) + + cd_specs = tuple(rebased[spec.name] for spec in cd_rows if spec.name in rebased) + specs = (*ht2_state, *kept_cd_file_state, *cd_specs) + # Fail closed on the invariant the whole surface rests on. + unreconciled = [ + block for block in state_parent_reconciliation(specs) if not block["ok"] + ] + if unreconciled: + raise ValueError( + f"{len(unreconciled)} district block(s) do not add up to a bound " + f"state parent, e.g. {unreconciled[:2]}." + ) + with_sigma = sum(1 for spec in specs if getattr(spec, "se", None) is not None) + receipt = { + "vintage_rule": STATE_CD_VINTAGE_RULE, + "vintage_rule_description": ( + "Historic Table 2 (TY2022) is the single vintage of every state " + "concept it carries. District-file (22incd.csv) district rows " + "keep only their within-state shares and are rebased to sum to " + "that parent. Concepts only the district file carries keep its " + "own state row as their parent, lifted onto the Historic Table 2 " + "basis by a sibling concept's ratio of the two files' state " + "totals in the same state (STATE_CD_LEVEL_BRIDGES)." + ), + "counts": { + "historic_table_2_state": len(ht2_state), + "cd_file_state": len(kept_cd_file_state), + "congressional_district": len(cd_specs), + "congressional_district_by_parent_basis": dict(parent_basis_counts), + "total": len(specs), + }, + "dropped": dict(sorted(dropped.items())), + "dropped_examples": dict(sorted(dropped_examples.items())), + "defective_cd_file_measures": dict(STATE_CD_DEFECTIVE_CD_FILE_MEASURES), + "unparented_cd_measures": dict(STATE_CD_UNPARENTED_CD_MEASURES), + "excluded_cd_states": dict(STATE_CD_EXCLUDED_CD_STATES), + "at_large_on_source_plan": at_large_source_states, + "internal_consistency": { + "rtol": STATE_CD_INTERNAL_RTOL, + "blocks_checked": len(internal_gaps), + "max_relative_gap": max(internal_gaps, default=0.0), + }, + "factor_band": { + "tolerance": factor_band, + "relative_to": "the measure's median Historic Table 2 / " + "district-file ratio across states", + "out_of_band": sorted( + out_of_band, key=lambda row: (row["concept"], row["state_fips"]) + ), + }, + "level_bridges": dict(level_bridges), + "level_bridge_factor_by_measure": { + measure: _factor_summary(values) + for measure, values in sorted(bridge_factors.items()) + }, + "rebase_factor_by_measure": { + measure: _factor_summary(values) + for measure, values in sorted(factors_by_measure.items()) + }, + "crosswalk": { + "source_plan": "117th_congress", + "target_plan": "119th_congress", + "method": "packaged 2020-block population crosswalk", + "sha256": crosswalk_sha256, + }, + "sigma": { + "targets_with_sigma": with_sigma, + "targets_without_sigma": len(specs) - with_sigma, + "note": ( + "The pinned feed carries no uncertainty field for any fact; " + "IRS SOI tables are administrative. target_roles.json records " + "sigma and sigma_basis for every target, null wherever a spec " + "carries none." + ), + }, + } + return StateCdSurface(specs=specs, receipt=receipt) + + +def state_parent_reconciliation( + specs: Sequence, *, rtol: float = RECONCILIATION_RTOL +) -> list[dict]: + """Every (state parent, district rows) block and whether it adds up. + + A block is the district specs naming one ``state_cd_parent_target_name``. + Returns one entry per block with the parent value, the district sum and + ``ok`` (relative difference within ``rtol``). + """ + + by_name = {spec.name: spec for spec in specs} + blocks: dict[str, list] = defaultdict(list) + for spec in specs: + parent = spec.metadata.get("state_cd_parent_target_name") + if parent is not None: + blocks[parent].append(spec) + report = [] + for parent_name, children in sorted(blocks.items()): + parent = by_name.get(parent_name) + child_sum = math.fsum(float(spec.value) for spec in children) + parent_value = None if parent is None else float(parent.value) + scale = max(abs(parent_value or 0.0), 1.0) + report.append( + { + "parent": parent_name, + "parent_bound": parent is not None, + "parent_value": parent_value, + "district_sum": child_sum, + "n_districts": len(children), + "ok": parent is not None + and abs(child_sum - parent_value) <= rtol * scale, + } + ) + return report + + +COUNTY_COLUMN = "county_fips" + + +SOI_MODE = "state_county" + + +COUNTY_PREFIX = "0500000US" + + +COUNTY_SOI_REQUIRED_MEASURES = ("return_count", "adjusted_gross_income") + + +PUERTO_RICO_STATE = 72 + + +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 _codes(values, *, column: str) -> np.ndarray: + numeric = pd.to_numeric(pd.Series(values), errors="raise").to_numpy(float) + if not np.isfinite(numeric).all() or (numeric != np.floor(numeric)).any(): + raise ValueError(f"{column} must contain finite integer geography codes.") + return numeric.astype(np.int64) + + +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 + result = {key: dict(value) for key, value in populations.items()} + if "state" not in result: + states = np.asarray(ladder.puma) // 100_000 + result["state"] = { + int(state): float(np.asarray(ladder.puma_population)[states == state].sum()) + for state in np.unique(states) + } + 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() + or (values < 0).any() + ): + raise ValueError("County overlap populations must be finite and nonnegative.") + raw = { + int(code): math.fsum(values[counties == code]) for code in np.unique(counties) + } + result["county"] = {} + for state, target in sorted(result["state"].items()): + block = sorted(code for code in raw if code // 1000 == int(state)) + total = math.fsum(raw[code] for code in block) + if not block or total <= 0 or not math.isfinite(target) or target <= 0: + raise ValueError(f"State {state} has no positive county/state population.") + scaled = [float(target) * raw[code] / total for code in block] + # Assign the rounding residual to the largest cell, never a small county. + largest = max(range(len(block)), key=lambda index: scaled[index]) + scaled[largest] += float(target) - math.fsum(scaled) + result["county"].update(zip(block, scaled, strict=True)) + unknown = sorted(set(raw) - set(result["county"])) + if unknown: + raise ValueError(f"County populations have no state parent: {unknown}.") + return result + + +def _hierarchy(name, code, *, parent=None): + from microcosm.calibrate import ( + CalibrationHierarchy, + HierarchyCategory, + HierarchyGeography, + HierarchyNode, + ) + + # One deterministic label for a county in all families. Source labels are + # retained in metadata; no mutable county-name registry is needed. + geography = HierarchyGeography(f"{COUNTY_PREFIX}{code}", f"County {code}", "county") + if parent is not None and parent.hierarchy is not None: + return dataclasses.replace( + parent.hierarchy, + geography=geography, + target=HierarchyNode( + name, f"{parent.hierarchy.target.label}, county {code}" + ), + ) + provider = HierarchyNode("census_population", "Census population") + return CalibrationHierarchy( + provider=provider, + category=HierarchyCategory( + "census_population.resident_population", "Resident population", provider.id + ), + geography=geography, + dimensions=(), + target=HierarchyNode(name, f"County {code} resident population"), + ) + + +def _broad_parent(spec): + metadata = spec.metadata + return ( + spec.family == "irs_soi" + and metadata.get("ledger_geography_level") == "state" + and str(metadata.get("filing_status", "all")).lower() == "all" + and float(metadata.get("agi_lower_bound", "-inf")) == -math.inf + and float(metadata.get("agi_upper_bound", "inf")) == math.inf + and metadata.get("soi_return_universe", "all_returns") == "all_returns" + and metadata.get("itemized_only", "false").lower() != "true" + and metadata.get("taxable_only", "false").lower() != "true" + and spec.filter is None + and all( + str(metadata.get(key, "all")).lower() == "all" + for key in ("ledger_filter_filing_status", "ledger_filter_income_range") + ) + ) + + +@dataclasses.dataclass(frozen=True) +class CountySurface: + specs: tuple + receipt: dict + + +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. + 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: + observed = fact.get("observed_measure", {}) + if observed.get("source_name") != "irs_soi": + continue + code = county_code_of(fact, source="SOI") + dimensions = fact.get("dimensions", {}) + if any( + str(dimensions.get(key, "all")).lower() != "all" + for key in ("filing_status", "income_range") + ): + raise ValueError( + "County SOI requires all-return facts without AGI classes." + ) + measure = observed.get("source_measure_id") + period = str(fact.get("period", {}).get("value", "")) + if fact.get("period", {}).get("type") != "tax_year": + raise ValueError("County SOI facts must carry a tax_year period.") + key = (code // 1000, measure, period) + if code in blocks[key]: + raise ValueError(f"Duplicate county SOI fact for {key}, {code:05d}.") + value = float(fact["value"]) + if not math.isfinite(value) or value < 0: + raise ValueError( + f"County SOI shares require finite nonnegative values: {code:05d}." + ) + blocks[key][code] = (value, fact) + if not blocks: + raise ValueError( + "County facts carry no IRS SOI county rows; pass the pinned " + "--county-facts file (us/chronicle_county_facts.json, microcosm#922)." + ) + parents = {} + for spec in state_specs: + if not _broad_parent(spec): + continue + metadata = spec.metadata + state = int(metadata["state_fips"]) + key = ( + state, + metadata.get("source_measure_id"), + str(metadata.get("source_period", "")), + ) + if key[1] not in COUNTY_SOI_REQUIRED_MEASURES and key[1] not in { + block[1] for block in blocks + }: + continue + if key in parents: + raise ValueError(f"Two state SOI parents for county concept {key}.") + parents[key] = spec + if not parents: + raise ValueError( + "No county SOI concept has an already materialized broad state parent." + ) + for state in sorted({int(code) // 1000 for code in county_populations}): + for measure in COUNTY_SOI_REQUIRED_MEASURES: + if not any(key[:2] == (state, measure) for key in parents): + raise ValueError( + f"Missing broad state SOI parent state={state:02d}, concept={measure}; " + "state_county requires return count and AGI in every state." + ) + 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(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; " + "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(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 expected) + for code, share, target in zip(codes, shares, targets, strict=True): + raw, fact = block[code] + unit = fact.get("observed_measure", {}).get("unit") + if ( + parent.metadata.get("ledger_measure_unit") is not None + and unit != parent.metadata["ledger_measure_unit"] + ): + raise ValueError( + 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, + "ledger_geography_level": "county", + "ledger_geography_id": f"{COUNTY_PREFIX}{county}", + "ledger_geography_vintage": str( + fact["geography"].get("vintage", period) + ), + "ledger_layout_record_set_spec_id": str( + fact.get("layout", {}).get("record_set_spec_id", "county_soi") + ), + "county_fips": county, + "county_label": str(fact["geography"].get("name", county)), + "state_county_parent_target_name": parent.name, + "state_county_share": str(share), + "state_county_source_value": str(raw), + "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, + name=name, + measure=name, + value=target, + se=None, + metadata=metadata, + hierarchy=_hierarchy(name, county, parent=parent), + source=f"{parent.source}; IRS SOI county {period} within-state shares", + ) + ) + receipts.append( + { + "state_fips": f"{state:02d}", + "concept": measure, + "parent": parent.name, + "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(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}.") + return CountySurface( + tuple(specs), + { + "soi_mode": SOI_MODE, + "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"])] + + +ACS_SOURCE_NAME = "census_acs" + + +ACS_TABLES = "ACS 2020-2024 5-year" + + +ACS_HOUSEHOLDS_FAMILY = "acs_households" + + +ACS_HOUSEHOLDS_MEASURE = "B11001_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, + }, + ) diff --git a/tools/generate_us_bundle_from_constants.py b/tools/generate_us_bundle_from_constants.py index bb5fea9a9c..7bbf2b2c63 100644 --- a/tools/generate_us_bundle_from_constants.py +++ b/tools/generate_us_bundle_from_constants.py @@ -143,6 +143,9 @@ def _domain_builders() -> dict[str, Callable[[], object]]: "chronicle_county_facts_scope.json", "chronicle_feed.json", "chronicle_feed_scope.json", + # The US nesting declarations of the shared cross-grain operator + # (microcosm#1760). + "cross_grain_declarations.json", "ecps_parity_known_gaps.json", "ecps_parity_reference.json", "federal_eitc_by_state.json", diff --git a/tools/spec_engine_coverage.py b/tools/spec_engine_coverage.py index 06ddab569f..8d5af2fa27 100644 --- a/tools/spec_engine_coverage.py +++ b/tools/spec_engine_coverage.py @@ -41,7 +41,7 @@ REPORT_SCHEMA_VERSION = 3 EXPECTED_POINTER_INVENTORY_SHA256 = ( - "38fc67ba13d62a5c0eaff36abb8f04d4d2974e21baaed6d2966d76480e643608" + "b7565bf43ff7139460a8345d3858a6950c4fdcf4cb61afe6b056550040b1c710" ) DEFAULT_REPORT_PATH = ( Path(__file__).resolve().parents[1] diff --git a/tools/us_acs_local_cd_surface.py b/tools/us_acs_local_cd_surface.py index e2a8e08078..55e5bca40b 100644 --- a/tools/us_acs_local_cd_surface.py +++ b/tools/us_acs_local_cd_surface.py @@ -46,90 +46,56 @@ #: Ledger record-set specs from the congressional-district SOI file. CD_FILE_RECORD_SET_SPEC_PREFIX = "irs_soi.congressional_district_" -#: How the ``state_cd`` surface resolves the two vintages of a state concept. -STATE_CD_VINTAGE_RULE = "state_cd.historic_table_2_level_cd_file_shares.v1" + +def _district_soi_nesting(): + """The declared choices of the ``state_cd`` surface (microcosm#1760). + + ``us/cross_grain_declarations.json`` holds them with their reasons: the + vintage rule, the registers of defective, unparented and excluded + district measures, the level bridges, the factor band and the two + tolerances. The names below are those choices under the names they had as + literals here. + """ + + from microcosm.build.us_runtime.cross_grain_declarations import ( + us_district_soi_nesting, + ) + + return us_district_soi_nesting() + + +_DISTRICT_SOI_NESTING = _district_soi_nesting() +#: How the ``state_cd`` surface resolves the two vintages of a state concept. +STATE_CD_VINTAGE_RULE = _DISTRICT_SOI_NESTING.vintage_rule #: District-file measures that read the wrong IRS column (microcosm#1038). -#: The compiler's ``US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS`` drops these -#: facts by (measure id, IRS column) before this surface sees them; this -#: register stays as a second fence on the ``state_cd`` surface, at both -#: geographies, and records the reason in the receipt. -STATE_CD_DEFECTIVE_CD_FILE_MEASURES: Mapping[str, str] = { - "limited_state_local_taxes_amount": ( - "22incd.csv column A18425 is state and local income taxes (Schedule A " - "line 5a), not the limited SALT deduction (A18460); the district " - "file sums to 1.98x Historic Table 2 (microcosm#1038)." - ), - "limited_state_local_taxes_returns": ( - "22incd.csv column N18425 counts state and local income-tax " - "deductions, not the limited SALT deduction (microcosm#1038)." - ), - "premium_tax_credit_returns": ( - "22incd.csv column N85530 is the additional Medicare tax (Form 8959 " - "line 24), not the premium tax credit (N85770) (microcosm#1038)." - ), -} -#: District-file measures with no state parent in either vintage, so their -#: district rows could not nest in a bound state target. -STATE_CD_UNPARENTED_CD_MEASURES: Mapping[str, str] = { - "tax_filer_individual_count": ( - "The compiler drops this measure at state and national geography " - "(fiscal_targets._soi_reference_from_fact), so no state target exists " - "for its district rows to reconcile to." - ), -} -#: District-file-only concepts (Historic Table 2 lacks them) and the sibling -#: concept whose two state levels bridge theirs onto the Historic Table 2 -#: basis. The district file's own state levels sit below Historic Table 2's -#: for two reasons: it covers only the returns processed in its window (about -#: 1.7% fewer), and the feed stamps it one tax year late, so its amounts are -#: aged one year less. A sibling both files carry, in the same state, estimates -#: that gap, on the assumption that the measure shares the sibling's ratio: -#: counts bridge by ``return_count`` (counts are not aged), amounts by the -#: closest amount Historic Table 2 carries. The factor band below applies to -#: the sibling. The bridge is stamp-invariant: if the stamp is corrected -#: (#1030) both levels move together. -STATE_CD_LEVEL_BRIDGES: Mapping[str, str] = { - "charitable_amount": "itemized_deductions_amount", - "charitable_returns": "return_count", - "interest_paid_deduction_amount": "itemized_deductions_amount", - "interest_paid_deduction_returns": "return_count", - "qualified_business_income_deduction_amount": "adjusted_gross_income", - "qualified_business_income_deduction_returns": "return_count", -} +STATE_CD_DEFECTIVE_CD_FILE_MEASURES: Mapping[str, str] = dict( + _DISTRICT_SOI_NESTING.defective_lower_measures +) +#: District-file measures with no state parent in either vintage. +STATE_CD_UNPARENTED_CD_MEASURES: Mapping[str, str] = dict( + _DISTRICT_SOI_NESTING.unparented_lower_measures +) +#: District-file-only concepts and the sibling concept that bridges their +#: state level onto the Historic Table 2 basis. +STATE_CD_LEVEL_BRIDGES: Mapping[str, str] = dict(_DISTRICT_SOI_NESTING.level_bridges) #: States whose district SOI rows stay off the surface, with the evidence. -#: Empty since #1043 rebuilt the 117th->119th crosswalk from the block plan -#: registry: the packaged crosswalk before it (sha256 c7cb040b...) carried -#: North Carolina's 2016 plan instead of the 2019 plan the 117th Congress used, -#: and 37.0% of NC's population mapped to a different 119th district, so NC's -#: district rows were held off until then. -STATE_CD_EXCLUDED_CD_STATES: Mapping[str, str] = {} +STATE_CD_EXCLUDED_CD_STATES: Mapping[str, str] = dict( + _DISTRICT_SOI_NESTING.excluded_legs +) #: How far a state's Historic Table 2 / district-file ratio may sit from its -#: measure's median across states before the district file's data for that -#: (state, concept) is refused. The ratio mixes a common part (the file's -#: coverage and aging gap, or a measure-wide rebase such as taxable interest's -#: x2.47 onto Table 4.3), which the median absorbs, with a state-specific part. -#: A state-specific part beyond 25% means the two publications disagree about -#: that state (Hawaii's dividends differ 2.4x from the typical gap on the -#: pinned feed), so the district file's shares, or a bridge built on that -#: sibling, are not trusted: the block's district rows and any bridged state -#: row are dropped and recorded; the Historic Table 2 state row stays. -STATE_CD_FACTOR_BAND = 1.25 -#: The district file's own state row must equal the sum of its district rows -#: to this relative tolerance wherever both are present (the receipt records -#: the largest gap; the feed-gated contract test pins it on the pinned feed). -#: A gap means a column or crosswalk defect inside the file (#1038 class), -#: which no median absorbs. -STATE_CD_INTERNAL_RTOL = 1e-6 -#: The packaged crosswalk the exclusions above were reviewed against. A test +#: measure's median across states. +STATE_CD_FACTOR_BAND = _DISTRICT_SOI_NESTING.factor_band +#: Relative tolerance between the district file's own state row and the sum +#: of its district rows. +STATE_CD_INTERNAL_RTOL = _DISTRICT_SOI_NESTING.internal_rtol +#: The packaged crosswalk the registers above were reviewed against. A test #: pins it, so regenerating the crosswalk forces a second look at them. -STATE_CD_REVIEWED_CROSSWALK_SHA256 = ( - "a347303fff3fea145f758488c43cb94355df5a8cb5e512552b2ee3791d2aa233" -) +STATE_CD_REVIEWED_CROSSWALK_SHA256 = _DISTRICT_SOI_NESTING.reviewed_crosswalk_sha256 #: Relative tolerance for "district rows sum to their state parent". The #: rebase makes it exact up to float64 rounding. -RECONCILIATION_RTOL = 1e-9 +RECONCILIATION_RTOL = _DISTRICT_SOI_NESTING.closure_rtol SIGMA_BASIS_FEED = "feed_standard_error" SIGMA_BASIS_NONE = "not_provided_by_feed" diff --git a/tools/us_acs_local_county_surface.py b/tools/us_acs_local_county_surface.py index 502cb5086e..bce22d4271 100644 --- a/tools/us_acs_local_county_surface.py +++ b/tools/us_acs_local_county_surface.py @@ -49,30 +49,36 @@ # 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") + + +def _county_soi_nesting(): + """The declared choices of the county SOI shares (microcosm#1760). + + ``us/cross_grain_declarations.json`` holds them with their reasons: the + measures every state must carry, and the combined cells with their basis. + The names below are those choices under the names they had as literals + here. + """ + + from microcosm.build.us_runtime.cross_grain_declarations import ( + us_county_soi_nesting, + ) + + return us_county_soi_nesting() + + +_COUNTY_SOI_NESTING = _county_soi_nesting() +COUNTY_SOI_REQUIRED_MEASURES = _COUNTY_SOI_NESTING.required_measures #: 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." -) +#: host county of the same state for the SOI families only (Kalawao County, +#: HI, into Maui). Any other absent county is refused unless declared. +DECLARED_SOI_COMBINED_CELLS = dict(_COUNTY_SOI_NESTING.combined_cells) +SOI_COMBINED_CELL_BASIS = _COUNTY_SOI_NESTING.combined_cell_basis def _concatenate(parts, dtype): From 6da6e3b12e10716d39b3ef383639bb8a03389a04 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:09:45 +0000 Subject: [PATCH 05/23] Make the district SOI shares on the shared cross-grain operator state_cd_soi_surface (row 5 of microcosm#1760) rebased each state's district rows onto the Historic Table 2 state row with its own arithmetic. The shared operator now divides each state control among its district rows, with the proportional_fsum allocator the US declaration names. The adapter (us_runtime.target_nesting.district_soi_surface) keeps the US side: the choice of the control, the level bridge by a sibling ratio, the factor band, the plan completeness check, the self-consistency check, the refusals with their texts, and the old metadata keys and receipt. The tool functions state_cd_soi_surface and state_parent_reconciliation keep their names and signatures and call the adapter. About 450 lines leave tools/us_acs_local_cd_surface.py. No target changes. On the pinned feed and ladder the state_cd surface has the bytes it had: 26,912 targets, and the same sha256 of target_registry.json, target_roles.json and the receipts (test_us_acs_local_surface_bytes.py). Proof: - test_us_target_nesting_district.py holds the tool function to the verbatim copy of the code it replaces on 160 seeded surfaces: the same specs in the same order, value bits, metadata key order, receipt bytes and refusal texts. The draws include signed rows, all-zero blocks, blocks out of the band (with NaN in the receipt), bridged concepts, a state with one district and four kinds of refusal. - The district property tests, the sparse tests and the feed contract tests pass unchanged. Co-Authored-By: Claude Fable 5.2 --- .../build/us_runtime/target_nesting.py | 603 +++++++++++++++++- .../us/test_us_target_nesting_district.py | 406 ++++++++++++ tools/us_acs_local_cd_surface.py | 479 +------------- 3 files changed, 1030 insertions(+), 458 deletions(-) create mode 100644 packages/microcosm-build/tests/engine_free/us/test_us_target_nesting_district.py diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/target_nesting.py b/packages/microcosm-build/src/microcosm/build/us_runtime/target_nesting.py index a07cfa6ce8..fe42f111fe 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/target_nesting.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/target_nesting.py @@ -24,23 +24,28 @@ from __future__ import annotations import json -from collections.abc import Mapping, Sequence +import math +import struct +from collections import Counter, defaultdict +from collections.abc import Callable, Mapping, Sequence from contextvars import ContextVar -from dataclasses import dataclass +from dataclasses import dataclass, replace from pathlib import Path from typing import Any import numpy as np import pandas as pd +from microcosm.build import cross_grain_controls as controls from microcosm.build.cross_grain import ( CrossGrainRule, apply_cross_grain_reconciliation, ) -from microcosm.build.cross_grain_controls import allocator_named from microcosm.build.us_runtime.cross_grain_declarations import ( + DISTRICT_SOI, load_us_cross_grain_declarations, us_cross_grain_mechanism, + us_district_soi_nesting, ) #: The file a materialize stage writes the operator's own receipts to. @@ -179,7 +184,7 @@ def reconcile_blocks( for _control_id, control_geography in sorted(controls_seen) }, control_grains=tuple(declarations["control_grains"]), - allocator=allocator_named(str(mechanism["allocator"])), + allocator=controls.allocator_named(str(mechanism["allocator"])), ) reconciled, receipt = apply_cross_grain_reconciliation( surface, bound, signatures, rule @@ -276,3 +281,593 @@ def write_nesting_receipts( ) ) return path + + +# --------------------------------------------------------------------------- +# State to congressional district: IRS SOI shares (issue row 5) +# --------------------------------------------------------------------------- + +#: The filters of a district SOI signature, in the order the caller's concept +#: identity gives them after the measure id. +DISTRICT_SOI_IDENTITY_FILTERS = ( + "agi_lower_bound", + "agi_upper_bound", + "filing_status", + "eitc_child_count", +) + + +@dataclass(frozen=True) +class NestedSurface: + """The specs of one nested surface, its receipt and the operator's.""" + + specs: tuple + receipt: dict + operator_receipt: dict + + +def crosswalk_district_sets(crosswalk: pd.DataFrame): + """(source districts per state, target districts per state) as SSDD.""" + + source: dict[str, set[str]] = defaultdict(set) + target: dict[str, set[str]] = defaultdict(set) + for source_id, target_id in zip( + crosswalk["source_geography_id"].astype(str), + crosswalk["target_geography_id"].astype(str), + strict=True, + ): + source[source_id[-4:-2]].add(source_id[-4:]) + target[target_id[-4:-2]].add(target_id[-4:]) + return dict(source), dict(target) + + +def _factor_summary(values: Sequence[float]) -> dict[str, float | int]: + array = np.asarray(values, dtype=np.float64) + return { + "n": int(array.size), + "min": float(array.min()), + "median": float(np.median(array)), + "max": float(array.max()), + } + + +def district_soi_surface( + soi_specs: Sequence, + *, + state_surface_predicate: Callable[[object], bool], + crosswalk: pd.DataFrame, + crosswalk_sha256: str | None, + level_bridges: Mapping[str, str], + factor_band: float, + concept_identity: Callable[[object], tuple[str, ...]], + materializer_semantics: Callable[[object], tuple], + is_lower_file_spec: Callable[[object], bool], + closure_report: Callable[[Sequence], list[dict]], +) -> NestedSurface: + """Select and reconcile the ``state_cd`` SOI surface. + + Historic Table 2 supplies a state concept's level wherever it has that + concept. The district file then supplies only each district's share of + its state: the operator divides the Historic Table 2 state row among the + district rows (``proportional_fsum``). A concept only the district file + has keeps the district file's own state row as its control, lifted onto + the Historic Table 2 basis by a sibling concept's ratio + (``scaled_by_sibling_ratio``). A block whose ratio sits outside the + factor band of its concept's median across states is dropped and + recorded. + + Args: + soi_specs: Every compiled ``irs_soi`` spec (the ``full`` surface). + state_surface_predicate: The ``state`` mode's predicate; its specs + (Historic Table 2) are the state surface. + crosswalk: The 117th->119th CD crosswalk the compiler used; it names + each state's source-plan and current-plan districts. + crosswalk_sha256: Recorded in the receipt. + level_bridges: District-file-only measure -> sibling measure. + factor_band: Largest allowed ratio between a block's ratio and its + concept's median across states (either direction). + concept_identity: The published concept a spec measures, independent + of vintage: the measure id, then the filters of + ``DISTRICT_SOI_IDENTITY_FILTERS``. + materializer_semantics: Everything the SOI slice reads from a spec + except its geography. + is_lower_file_spec: Whether a spec comes from the district file. + closure_report: Every (state parent, district rows) block of the + finished surface and whether it adds up; a block that does not is + refused. + + Returns: + The surface in a fixed order (Historic Table 2 state rows, district + file state rows, district rows), its receipt and the operator's. + + Raises: + ValueError: If a district concept is incomplete in a state, if its + district rows disagree on what they materialize, if a parent's + materialization differs from its children's, or if a parent + cannot absorb its children (zero sum under a nonzero parent, or + a sign conflict). + """ + + nesting = us_district_soi_nesting() + mechanism = us_cross_grain_mechanism(DISTRICT_SOI) + state_level = str(mechanism["higher_grain"]) + district_level = str(mechanism["lower_grain"]) + defective = nesting.defective_lower_measures + unparented = nesting.unparented_lower_measures + excluded_states = nesting.excluded_legs + + source_districts, target_districts = crosswalk_district_sets(crosswalk) + at_large_source_states = sorted( + state for state, districts in source_districts.items() if len(districts) == 1 + ) + dropped: Counter = Counter() + dropped_examples: dict[str, str] = {} + + def drop(spec, reason: str) -> None: + dropped[reason] += 1 + dropped_examples.setdefault(reason, spec.name) + + ht2_state: list = [] + cd_file_state: list = [] + cd_rows: list = [] + for spec in soi_specs: + level = spec.metadata.get("ledger_geography_level") + if state_surface_predicate(spec): + ht2_state.append(spec) + elif is_lower_file_spec(spec) and level == state_level: + cd_file_state.append(spec) + elif is_lower_file_spec(spec) and level == district_level: + cd_rows.append(spec) + elif level == district_level: + drop(spec, "historic_table_2_at_large_proxy_district_row") + else: + drop(spec, f"not_state_cd_geography:{level}") + + ht2_by_key = {} + for spec in ht2_state: + key = (spec.metadata["state_fips"], concept_identity(spec)) + if key in ht2_by_key: + raise ValueError( + f"Two Historic Table 2 state specs measure {key}: " + f"{ht2_by_key[key].name} and {spec.name}." + ) + ht2_by_key[key] = spec + cd_file_state_by_key = {} + for spec in cd_file_state: + key = (spec.metadata["state_fips"], concept_identity(spec)) + if key in cd_file_state_by_key: + raise ValueError( + f"Two district-file state specs measure {key}: " + f"{cd_file_state_by_key[key].name} and {spec.name}." + ) + cd_file_state_by_key[key] = spec + + # Each state concept both files carry: its Historic Table 2 / district-file + # ratio, judged against the measure's median ratio across states. + vintage_ratio = { + key: controls.level_ratio( + ht2_by_key[key].value, cd_file_state_by_key[key].value + ) + for key in ht2_by_key.keys() & cd_file_state_by_key.keys() + } + median_ratio = controls.median_by_group(vintage_ratio, lambda key: key[1]) + out_of_band: list[dict] = [] + + def within_band( + key: tuple, + ratio: float, + median: float, + basis: str, + measure: str, + *, + verdict: str, + ) -> bool: + judged = controls.band_verdict(ratio, median, factor_band) + if not judged.ok: + out_of_band.append( + { + "state_fips": key[0], + "measure": measure, + "concept": key[1][0], + "basis": basis, + "verdict": verdict, + "ratio": ratio, + "median_ratio": median, + "relative": judged.relative, + } + ) + return judged.ok + + kept_cd_by_key: dict[tuple, list] = defaultdict(list) + for spec in cd_rows: + metadata = spec.metadata + measure = str(metadata.get("source_measure_id")) + state = str(metadata["state_fips"]) + if measure in defective: + drop(spec, f"defective_cd_file_column:{measure}") + elif measure in unparented: + drop(spec, f"no_state_parent:{measure}") + elif state in at_large_source_states: + drop(spec, "at_large_on_source_plan") + elif state in excluded_states: + drop(spec, f"excluded_state:{state}") + else: + kept_cd_by_key[(state, concept_identity(spec))].append(spec) + + # Each Historic-Table-2-parented block's rebase factor (parent over its + # district rows' sum), judged against its concept's median across states. + block_factor: dict[tuple, float] = {} + for key, block in kept_cd_by_key.items(): + parent = ht2_by_key.get(key) + if parent is None: + continue + ratio, _child_sum = controls.control_ratio( + parent.value, (spec.value for spec in block) + ) + if ratio is not None: + block_factor[key] = ratio + median_factor = controls.median_by_group( + block_factor, lambda key: key[1], positive_only=True + ) + + # One basis for every state level: a concept Historic Table 2 lacks keeps + # the district file's state row, scaled by a sibling's two levels. + bridged: dict[str, object] = {} + bridge_factors: dict[str, list[float]] = defaultdict(list) + for key, spec in sorted(cd_file_state_by_key.items()): + state, identity = key + measure = identity[0] + if key in ht2_by_key or measure in defective: + continue + sibling = level_bridges.get(measure) + if sibling is None: + raise ValueError( + f"District-file-only concept {measure!r} has no level bridge; " + "register a sibling measure in STATE_CD_LEVEL_BRIDGES before " + "binding it." + ) + sibling_key = (state, (sibling, *identity[1:])) + ht2_sibling = ht2_by_key.get(sibling_key) + cd_sibling = cd_file_state_by_key.get(sibling_key) + if ht2_sibling is None or cd_sibling is None or float(cd_sibling.value) == 0: + raise ValueError( + f"Level bridge {measure} -> {sibling} in state {state} needs " + "the sibling's state total in both files." + ) + value, factor = controls.scaled_by_sibling_ratio( + spec.value, ht2_sibling.value, cd_sibling.value + ) + # A sign conflict is a data defect, not a level disagreement: refuse + # it before the band, which only judges finite positive ratios. + if not (math.isfinite(factor) and factor > 0.0): + raise ValueError( + f"Level bridge {measure} -> {sibling} in state {state} has " + f"factor {factor}." + ) + # The sibling is trusted for bridging only if both of the band's + # verdicts on it pass: its two state levels, and (where it has district + # rows) the rebase of its own district block. + trusted = within_band( + sibling_key, + factor, + median_ratio.get(sibling_key[1], math.nan), + f"level_bridge:{measure}", + measure, + verdict="sibling_vintage_ratio", + ) + if sibling_key in block_factor: + trusted = ( + within_band( + sibling_key, + block_factor[sibling_key], + median_factor.get(sibling_key[1], math.nan), + f"level_bridge:{measure}", + measure, + verdict="sibling_rebase_factor", + ) + and trusted + ) + if not trusted: + continue + metadata = dict(spec.metadata) + metadata.update( + { + "state_cd_vintage_rule": nesting.vintage_rule, + "state_cd_cd_file_value": repr(float(spec.value)), + "state_cd_level_bridge_sibling": ht2_sibling.name, + "state_cd_level_bridge_cd_file_sibling": cd_sibling.name, + "state_cd_level_bridge_factor": repr(factor), + } + ) + bridged[spec.name] = replace( + spec, value=value, signed=value < 0.0, metadata=metadata + ) + bridge_factors[measure].append(factor) + + # Every check a block must pass before the operator divides its control. + internal_gaps: list[float] = [] + kept_cd_file_parents: set[str] = set() + kept_blocks: list[tuple] = [] + for key in sorted(kept_cd_by_key): + state, identity = key + children = sorted( + kept_cd_by_key[key], + key=lambda spec: spec.metadata["congressional_district_geoid"], + ) + districts = [spec.metadata["congressional_district_geoid"] for spec in children] + expected = sorted(target_districts.get(state, ())) + if not controls.leg_completeness(districts, expected).complete: + raise ValueError( + f"District concept {identity} in state {state} covers " + f"{districts}, expected the current plan's {expected}; " + "rebasing an incomplete set would misstate every district." + ) + semantics = {materializer_semantics(spec) for spec in children} + if len(semantics) != 1: + raise ValueError( + f"District rows of {identity} in state {state} materialize " + f"differently: {sorted(map(repr, semantics))}." + ) + (child_semantics,) = semantics + parent = ht2_by_key.get(key) + basis = "historic_table_2" + if parent is None: + parent = cd_file_state_by_key.get(key) + basis = "cd_file_state_total_bridged" + if parent is None: + raise ValueError( + f"District concept {identity} in state {state} has no " + "state parent in either vintage." + ) + if parent.name not in bridged: + for child in children: + drop(child, f"level_bridge_out_of_band:{identity[0]}") + continue + parent = bridged[parent.name] + kept_cd_file_parents.add(parent.name) + if materializer_semantics(parent) != child_semantics: + raise ValueError( + f"State parent {parent.name} materializes differently from " + f"its district rows ({identity}, state {state})." + ) + parent_value = float(parent.value) + ratio, child_sum = controls.control_ratio( + parent_value, (spec.value for spec in children) + ) + if ratio is None: + if parent_value != 0.0: + raise ValueError( + f"District rows of {identity} in state {state} sum to zero " + f"under a nonzero parent {parent.name}={parent_value}." + ) + factor = 1.0 + else: + factor = ratio + if factor < 0.0: + raise ValueError( + f"District rows of {identity} in state {state} sum to " + f"{child_sum}, opposite in sign to parent {parent.name}=" + f"{parent_value}." + ) + # The district file must agree with itself before its shares are used. + cd_state = cd_file_state_by_key.get(key) + if cd_state is not None: + cd_state_value = float(cd_state.value) + gap = controls.sum_gap(cd_state_value, child_sum) + internal_gaps.append(gap.relative) + if gap.exceeds(nesting.internal_rtol): + raise ValueError( + f"District-file state row {cd_state.name}={cd_state_value} " + f"differs from the sum of its district rows ({child_sum}) " + f"for {identity} in state {state}: a column or crosswalk " + "defect inside the district file." + ) + # An all-zero block agrees with a zero parent whatever the median. + if ( + basis == "historic_table_2" + and ratio is not None + and not within_band( + key, + factor, + median_factor.get(identity, math.nan), + "rebase", + identity[0], + verdict="rebase_factor", + ) + ): + for child in children: + drop(child, f"rebase_out_of_band:{identity[0]}") + continue + kept_blocks.append( + (key, parent, basis, parent_value, children, child_sum, factor) + ) + + # The operator divides each control among its district rows. + nested, operator_receipt = reconcile_blocks( + DISTRICT_SOI, + [ + NestingBlock( + concept=f"{children[0].family}.{identity[0]}", + filters=tuple( + zip(DISTRICT_SOI_IDENTITY_FILTERS, identity[1:], strict=True) + ), + control_geography_id=geography_id(state_level, state), + control_value=parent_value, + lower_geography_ids=tuple( + geography_id( + district_level, child.metadata["congressional_district_geoid"] + ) + for child in children + ), + lower_values=tuple(float(child.value) for child in children), + ) + for (state, identity), _p, _b, parent_value, children, _s, _f in kept_blocks + ], + ) + rebased: dict[str, object] = {} + factors_by_measure: dict[str, list[float]] = defaultdict(list) + parent_basis_counts: Counter = Counter() + for (key, parent, basis, parent_value, children, child_sum, factor), rows in zip( + kept_blocks, nested, strict=True + ): + _state, identity = key + if _bits(rows.lower_sum, rows.factor) != _bits(child_sum, factor): + raise ValueError( + f"The operator's factor for {identity} under {parent.name} " + f"({rows.factor!r} on {rows.lower_sum!r}) is not the factor the " + f"band judged ({factor!r} on {child_sum!r})." + ) + factors_by_measure[identity[0]].append(rows.factor) + parent_basis_counts[basis] += len(children) + for child, value in zip(children, rows.values, strict=True): + metadata = dict(child.metadata) + metadata.update( + { + "state_cd_vintage_rule": nesting.vintage_rule, + "state_cd_parent_target_name": parent.name, + "state_cd_parent_basis": basis, + "state_cd_parent_value": repr(parent_value), + "state_cd_cd_file_value": repr(float(child.value)), + "state_cd_cd_file_state_sum": repr(rows.lower_sum), + "state_cd_rebase_factor": repr(rows.factor), + } + ) + rebased[child.name] = replace( + child, + value=value, + signed=value < 0.0, + metadata=metadata, + ) + + kept_cd_file_state = [] + for spec in cd_file_state: + measure = str(spec.metadata.get("source_measure_id")) + key = (spec.metadata["state_fips"], concept_identity(spec)) + if measure in defective: + drop(spec, f"defective_cd_file_column:{measure}") + elif key in ht2_by_key: + drop(spec, "second_vintage_of_state_concept") + elif spec.name not in bridged: + drop(spec, f"level_bridge_out_of_band:{measure}") + else: + kept_cd_file_state.append(bridged[spec.name]) + missing_parents = kept_cd_file_parents - {spec.name for spec in kept_cd_file_state} + if missing_parents: + raise ValueError( + f"District-file state parents {sorted(missing_parents)[:5]} were " + "dropped while their district rows were kept." + ) + + cd_specs = tuple(rebased[spec.name] for spec in cd_rows if spec.name in rebased) + specs = (*ht2_state, *kept_cd_file_state, *cd_specs) + # Fail closed on the invariant the whole surface rests on. + unreconciled = [block for block in closure_report(specs) if not block["ok"]] + if unreconciled: + raise ValueError( + f"{len(unreconciled)} district block(s) do not add up to a bound " + f"state parent, e.g. {unreconciled[:2]}." + ) + with_sigma = sum(1 for spec in specs if getattr(spec, "se", None) is not None) + receipt = { + "vintage_rule": nesting.vintage_rule, + "vintage_rule_description": ( + "Historic Table 2 (TY2022) is the single vintage of every state " + "concept it carries. District-file (22incd.csv) district rows " + "keep only their within-state shares and are rebased to sum to " + "that parent. Concepts only the district file carries keep its " + "own state row as their parent, lifted onto the Historic Table 2 " + "basis by a sibling concept's ratio of the two files' state " + "totals in the same state (STATE_CD_LEVEL_BRIDGES)." + ), + "counts": { + "historic_table_2_state": len(ht2_state), + "cd_file_state": len(kept_cd_file_state), + "congressional_district": len(cd_specs), + "congressional_district_by_parent_basis": dict(parent_basis_counts), + "total": len(specs), + }, + "dropped": dict(sorted(dropped.items())), + "dropped_examples": dict(sorted(dropped_examples.items())), + "defective_cd_file_measures": dict(defective), + "unparented_cd_measures": dict(unparented), + "excluded_cd_states": dict(excluded_states), + "at_large_on_source_plan": at_large_source_states, + "internal_consistency": { + "rtol": nesting.internal_rtol, + "blocks_checked": len(internal_gaps), + "max_relative_gap": max(internal_gaps, default=0.0), + }, + "factor_band": { + "tolerance": factor_band, + "relative_to": "the measure's median Historic Table 2 / " + "district-file ratio across states", + "out_of_band": sorted( + out_of_band, key=lambda row: (row["concept"], row["state_fips"]) + ), + }, + "level_bridges": dict(level_bridges), + "level_bridge_factor_by_measure": { + measure: _factor_summary(values) + for measure, values in sorted(bridge_factors.items()) + }, + "rebase_factor_by_measure": { + measure: _factor_summary(values) + for measure, values in sorted(factors_by_measure.items()) + }, + "crosswalk": { + "source_plan": "117th_congress", + "target_plan": "119th_congress", + "method": "packaged 2020-block population crosswalk", + "sha256": crosswalk_sha256, + }, + "sigma": { + "targets_with_sigma": with_sigma, + "targets_without_sigma": len(specs) - with_sigma, + "note": ( + "The pinned feed carries no uncertainty field for any fact; " + "IRS SOI tables are administrative. target_roles.json records " + "sigma and sigma_basis for every target, null wherever a spec " + "carries none." + ), + }, + } + return NestedSurface( + specs=specs, receipt=receipt, operator_receipt=operator_receipt + ) + + +def district_block_closure(specs: Sequence, *, rtol: float) -> list[dict]: + """Every (state parent, district rows) block and whether it adds up. + + A block is the district specs naming one ``state_cd_parent_target_name``. + Returns one entry per block with the parent value, the district sum and + ``ok`` (relative difference within ``rtol``). + """ + + by_name = {spec.name: spec for spec in specs} + blocks: dict[str, list] = defaultdict(list) + for spec in specs: + parent = spec.metadata.get("state_cd_parent_target_name") + if parent is not None: + blocks[parent].append(spec) + report = [] + for parent_name, children in sorted(blocks.items()): + parent = by_name.get(parent_name) + child_sum = controls.sum_of_lower_rows(spec.value for spec in children) + parent_value = None if parent is None else float(parent.value) + report.append( + { + "parent": parent_name, + "parent_bound": parent is not None, + "parent_value": parent_value, + "district_sum": child_sum, + "n_districts": len(children), + "ok": parent is not None + and controls.sum_gap(parent_value, child_sum).within(rtol), + } + ) + return report + + +def _bits(*values: float) -> bytes: + return b"".join(struct.pack(" (engine variable, measure mode). The last two are in the +#: declared registers: a defective district-file column and a measure with no +#: state parent. +_MEASURES = { + "return_count": ("count", "sum"), + "adjusted_gross_income": ("adjusted_gross_income", "sum"), + "itemized_deductions_amount": ("itemized_deductions", "sum"), + "net_capital_gain_amount": ("net_capital_gain", "sum"), + "charitable_amount": ("charitable_deduction", "sum"), + "interest_paid_deduction_returns": ("interest_deduction", "indicator_sum"), + "limited_state_local_taxes_amount": ("salt", "sum"), + "tax_filer_individual_count": ("count", "sum"), +} +#: Concepts only the district file carries, bridged by the declared siblings. +_DISTRICT_FILE_ONLY = ("charitable_amount", "interest_paid_deduction_returns") +SEEDS = range(160) + + +@pytest.fixture(scope="module") +def tool(): + path = _TEST_PATHS.repository / "tools" / "build_us_acs_local_release.py" + spec = importlib.util.spec_from_file_location( + "build_us_acs_local_release_nesting_district", path + ) + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + spec.loader.exec_module(module) + return module + + +def _soi_spec(name, measure, value, *, level, record_set, state=None, district=None): + variable, mode = _MEASURES[measure] + metadata = { + "ledger_geography_level": level, + "ledger_layout_record_set_spec_id": record_set, + "source_measure_id": measure, + "variable": variable, + "source_variable": variable, + "measure_mode": mode, + "agi_lower_bound": "-inf", + "agi_upper_bound": "inf", + "filing_status": "All", + } + if state is not None: + metadata["state_fips"] = state + if district is not None: + metadata["congressional_district_geoid"] = district + return TargetSpec( + name=name, + entity="household", + measure=name, + value=value, + source="property", + family="irs_soi", + signed=value < 0, + metadata=metadata, + ) + + +def _inputs(seed: int): + """Compiled-looking SOI specs and a crosswalk, with the hard cases. + + Some draws are refused (an incomplete plan, a zero sum under a nonzero + parent, a sign conflict, a district file that disagrees with itself); + the old and the new code must then refuse with the same text. + """ + + rng = np.random.default_rng(seed) + states = [f"{10 + index:02d}" for index in range(int(rng.integers(1, 7)))] + measures = ["return_count", "adjusted_gross_income", "itemized_deductions_amount"] + measures += [ + measure + for measure in list(_MEASURES)[3:] + if rng.random() < (0.25 if measure in list(_MEASURES)[-2:] else 0.6) + ] + specs, crosswalk = [], [] + hazard = rng.random() + # The first three measures are in both files in every state: two of them + # are the declared bridge siblings, which need a positive level in both. + siblings = measures[:3] + # A measure whose Historic Table 2 level is zero in every state has no + # median factor, so its blocks are dropped with NaN in the receipt. + zero_everywhere = { + measure + for measure in measures + if measure not in siblings and rng.random() < 0.08 + } + for state in states: + n_target = int(rng.integers(1, 6)) + roll = rng.random() + if n_target <= 2 and roll < 0.3: + # At-large on the source plan: the file has no district rows worth + # keeping, whatever the current plan says. + source = [f"{state}00"] + elif n_target == 1: + # One current district made from two source districts: a kept + # block of one row, a copy of its state row. + source = [f"{state}01", f"{state}02"] + else: + source = [f"{state}{index + 1:02d}" for index in range(n_target)] + districts = [f"{state}{index + 1:02d}" for index in range(n_target)] + for position, target in enumerate(districts): + origins = source if len(source) != n_target else [source[position]] + crosswalk += [ + { + "source_geography_id": f"5001700US{origin}", + "target_geography_id": f"5001900US{target}", + } + for origin in origins + ] + for measure in measures: + signed = measure == "net_capital_gain_amount" + values = rng.lognormal(mean=10.0, sigma=1.5, size=n_target) + if rng.random() < 0.3: + values = np.round(values) + if signed and rng.random() < 0.6: + values[int(rng.integers(n_target))] *= -0.2 + if measure not in siblings and rng.random() < 0.05: + values[:] = 0.0 + district_sum = math.fsum(values.tolist()) + # The state level of the other vintage: a common gap, a small + # state part, and now and then a state the two files disagree on. + gap = 1.02 * float(rng.uniform(0.97, 1.03)) + if rng.random() < 0.08: + gap *= float(rng.choice([0.5, 2.0])) + ht2_value = district_sum * gap + if district_sum == 0.0 and rng.random() < 0.5: + ht2_value = 0.0 if hazard < 0.9 else 5.0 # zero under nonzero + if measure in zero_everywhere: + ht2_value = 0.0 + if hazard > 0.97 and rng.random() < 0.2: + ht2_value = -abs(ht2_value) - 1.0 # a sign conflict + # The compiler drops the unparented measure at state level. + unparented = measure == "tax_filer_individual_count" + if measure not in _DISTRICT_FILE_ONLY and not unparented: + specs.append( + _soi_spec( + f"ht2.{state}.{measure}", + measure, + ht2_value, + level="state", + record_set=_HT2, + state=state, + ) + ) + own_total = district_sum + if len(source) == 1: + own_total = float(rng.lognormal(mean=11.0, sigma=1.0)) + elif 0.94 < hazard <= 0.97 and rng.random() < 0.15: + own_total = district_sum * 1.01 # the file disagrees with itself + if not unparented: + specs.append( + _soi_spec( + f"cdfile.{state}_total.{measure}", + measure, + own_total, + level="state", + record_set=_CD_FILE, + state=state, + ) + ) + kept_districts = districts + if 0.90 < hazard <= 0.94 and n_target > 1 and rng.random() < 0.1: + kept_districts = districts[:-1] # an incomplete plan + for district, value in zip(districts, values.tolist(), strict=True): + if district in kept_districts: + specs.append( + _soi_spec( + f"cdfile.{district}.{measure}", + measure, + value, + level="congressional_district", + record_set=_CD_FILE, + state=state, + district=district, + ) + ) + if rng.random() < 0.2: + specs.append( + _soi_spec( + f"ht2.{state}00.return_count", + "return_count", + 1.0, + level="congressional_district", + record_set=_HT2, + state=state, + district=f"{state}00", + ) + ) + if rng.random() < 0.3: + specs.append( + _soi_spec( + "ht2.us.return_count", + "return_count", + 1.0, + level="country", + record_set=_HT2, + ) + ) + order = rng.permutation(len(specs)) + band = math.inf if rng.random() < 0.3 else 1.25 + return [specs[index] for index in order], pd.DataFrame(crosswalk), band + + +def _spec_image(spec) -> tuple: + """Everything a spec holds, with the value's bits and the key order.""" + + fields = { + field.name: getattr(spec, field.name) for field in dataclasses.fields(spec) + } + return ( + struct.pack(" tuple: + return ( + [_spec_image(spec) for spec in surface.specs], + json.dumps(surface.receipt, indent=1), + ) + + +def _run(module, specs, crosswalk, band, predicate): + try: + surface = module.state_cd_soi_surface( + specs, + state_surface_predicate=predicate, + crosswalk=crosswalk, + crosswalk_sha256="0" * 64, + factor_band=band, + ) + except ValueError as error: + return ("refused", str(error)) + return ("surface", *_surface_image(surface)) + + +def test_the_district_surface_is_the_old_surface_on_random_inputs(tool) -> None: + predicate = tool.soi_surface_predicate("state") + outcomes = {"surface": 0, "refused": 0} + refusals: set[str] = set() + rows = out_of_band = bridged = signed = single = nan_rows = 0 + for seed in SEEDS: + specs, crosswalk, band = _inputs(seed) + new = _run(tool.cd_surface, specs, crosswalk, band, predicate) + old = _run(reference, specs, crosswalk, band, predicate) + assert new == old, seed + outcomes[new[0]] += 1 + if new[0] == "refused": + refusals.add(new[1].split(" ")[0] + " " + new[1].split(" ")[1]) + continue + receipt = json.loads(new[2]) + rows += receipt["counts"]["congressional_district"] + out_of_band += len(receipt["factor_band"]["out_of_band"]) + nan_rows += sum( + row["relative"] != row["relative"] + for row in receipt["factor_band"]["out_of_band"] + ) + bridged += receipt["counts"]["cd_file_state"] + surface = tool.cd_surface.state_cd_soi_surface( + specs, + state_surface_predicate=predicate, + crosswalk=crosswalk, + factor_band=band, + ) + children: dict[str, int] = {} + for spec in surface.specs: + parent = spec.metadata.get("state_cd_parent_target_name") + if parent is not None: + children[parent] = children.get(parent, 0) + 1 + signed += spec.value < 0 + single += sum(count == 1 for count in children.values()) + # The closure report of the tool is the old report. + assert tool.cd_surface.state_parent_reconciliation( + surface.specs + ) == reference.state_parent_reconciliation(surface.specs) + # The draws reach the hard cases the move must keep. + assert outcomes["surface"] >= 100 and outcomes["refused"] >= 10 + assert len(refusals) >= 3 + assert rows >= 2_000 + assert min(out_of_band, bridged, signed, single, nan_rows) >= 5 + + +def _two_district_case(parent_value: float, values: tuple[float, float]): + crosswalk = pd.DataFrame( + { + "source_geography_id": ["5001700US1001", "5001700US1002"], + "target_geography_id": ["5001900US1001", "5001900US1002"], + } + ) + specs = [ + _soi_spec( + "ht2.10.adjusted_gross_income", + "adjusted_gross_income", + parent_value, + level="state", + record_set=_HT2, + state="10", + ), + *( + _soi_spec( + f"cdfile.100{index}.adjusted_gross_income", + "adjusted_gross_income", + value, + level="congressional_district", + record_set=_CD_FILE, + state="10", + district=f"100{index}", + ) + for index, value in enumerate(values, start=1) + ), + ] + return specs, crosswalk + + +@pytest.mark.parametrize( + ("parent_value", "values"), + [ + (100.0, (5.0, 15.0)), # a plain rebase + (0.0, (0.0, 0.0)), # an all-zero block under a zero parent + (0.0, (5.0, 15.0)), # a zero parent: out of band, with NaN in the receipt + (100.0, (0.1, 0.2)), # shares whose products round + (10.0, (-5.0, 15.0)), # a signed row + ], +) +def test_the_hard_cases_are_the_old_surface(tool, parent_value, values) -> None: + specs, crosswalk = _two_district_case(parent_value, values) + predicate = tool.soi_surface_predicate("state") + specs = [ + dataclasses.replace(spec, signed=True) if spec.value < 0 else spec + for spec in specs + ] + new = _run(tool.cd_surface, specs, crosswalk, 1.25, predicate) + assert new == _run(reference, specs, crosswalk, 1.25, predicate) + assert new[0] == "surface" + + +def test_the_district_pass_records_the_operators_receipt(tool) -> None: + specs, crosswalk = _two_district_case(100.0, (5.0, 15.0)) + recorded = target_nesting.start_nesting_receipts() + try: + surface = tool.cd_surface.state_cd_soi_surface( + specs, + state_surface_predicate=tool.soi_surface_predicate("state"), + crosswalk=crosswalk, + ) + finally: + target_nesting.stop_nesting_receipts() + (entry,) = recorded + assert (entry["mechanism"], entry["allocator"], entry["blocks"]) == ( + declarations.DISTRICT_SOI, + "proportional_fsum", + 1, + ) + (group,) = entry["operator_receipt"]["groups"] + (leg,) = group["legs"] + assert (group["winning_grain"], group["lower_grain"]) == ( + "state", + "congressional_district", + ) + assert (leg["old_total"], leg["declared_factor"], leg["new_total"]) == ( + 20.0, + 5.0, + 100.0, + ) + # The old metadata reads the same factor and sum. + district = surface.specs[-1] + assert district.metadata["state_cd_rebase_factor"] == repr(leg["declared_factor"]) + assert district.metadata["state_cd_cd_file_state_sum"] == repr(leg["old_total"]) + # The old receipt does not hold the operator's receipt. + assert "groups" not in surface.receipt diff --git a/tools/us_acs_local_cd_surface.py b/tools/us_acs_local_cd_surface.py index 55e5bca40b..4d9ebeaa23 100644 --- a/tools/us_acs_local_cd_surface.py +++ b/tools/us_acs_local_cd_surface.py @@ -241,29 +241,12 @@ class StateCdSurface: receipt: dict -def _crosswalk_district_sets(crosswalk: pd.DataFrame): - """(source districts per state, target districts per state) as SSDD.""" - - source: dict[str, set[str]] = defaultdict(set) - target: dict[str, set[str]] = defaultdict(set) - for source_id, target_id in zip( - crosswalk["source_geography_id"].astype(str), - crosswalk["target_geography_id"].astype(str), - strict=True, - ): - source[source_id[-4:-2]].add(source_id[-4:]) - target[target_id[-4:-2]].add(target_id[-4:]) - return dict(source), dict(target) +def _target_nesting(): + """The US adapter to the shared cross-grain operator (microcosm#1760).""" + from microcosm.build.us_runtime import target_nesting -def _factor_summary(values: Sequence[float]) -> dict[str, float | int]: - array = np.asarray(values, dtype=np.float64) - return { - "n": int(array.size), - "min": float(array.min()), - "median": float(np.median(array)), - "max": float(array.max()), - } + return target_nesting def state_cd_soi_surface( @@ -277,6 +260,12 @@ def state_cd_soi_surface( ) -> StateCdSurface: """Select and reconcile the ``state_cd`` SOI surface. + The work is in + :func:`microcosm.build.us_runtime.target_nesting.district_soi_surface`: + the shared cross-grain operator divides each state control among its + district rows, with the choices declared in + ``us/cross_grain_declarations.json`` (microcosm#1760). + Args: soi_specs: Every compiled ``irs_soi`` spec (the ``full`` surface). state_surface_predicate: The ``state`` mode's predicate; its specs @@ -303,416 +292,21 @@ def state_cd_soi_surface( a sign conflict). """ - source_districts, target_districts = _crosswalk_district_sets(crosswalk) - at_large_source_states = sorted( - state for state, districts in source_districts.items() if len(districts) == 1 + surface = _target_nesting().district_soi_surface( + soi_specs, + state_surface_predicate=state_surface_predicate, + crosswalk=crosswalk, + crosswalk_sha256=crosswalk_sha256, + level_bridges=level_bridges, + factor_band=factor_band, + concept_identity=soi_concept_identity, + materializer_semantics=soi_materializer_semantics, + is_lower_file_spec=is_cd_file_spec, + # Read at call time: the builder re-checks its own output with the + # report this module holds. + closure_report=lambda specs: state_parent_reconciliation(specs), ) - dropped: Counter = Counter() - dropped_examples: dict[str, str] = {} - - def drop(spec, reason: str) -> None: - dropped[reason] += 1 - dropped_examples.setdefault(reason, spec.name) - - ht2_state: list = [] - cd_file_state: list = [] - cd_rows: list = [] - for spec in soi_specs: - level = geography_level(spec) - if state_surface_predicate(spec): - ht2_state.append(spec) - elif is_cd_file_spec(spec) and level == GEOGRAPHY_STATE: - cd_file_state.append(spec) - elif is_cd_file_spec(spec) and level == GEOGRAPHY_CD: - cd_rows.append(spec) - elif level == GEOGRAPHY_CD: - drop(spec, "historic_table_2_at_large_proxy_district_row") - else: - drop(spec, f"not_state_cd_geography:{level}") - - ht2_by_key = {} - for spec in ht2_state: - key = (spec.metadata["state_fips"], soi_concept_identity(spec)) - if key in ht2_by_key: - raise ValueError( - f"Two Historic Table 2 state specs measure {key}: " - f"{ht2_by_key[key].name} and {spec.name}." - ) - ht2_by_key[key] = spec - cd_file_state_by_key = {} - for spec in cd_file_state: - key = (spec.metadata["state_fips"], soi_concept_identity(spec)) - if key in cd_file_state_by_key: - raise ValueError( - f"Two district-file state specs measure {key}: " - f"{cd_file_state_by_key[key].name} and {spec.name}." - ) - cd_file_state_by_key[key] = spec - - # Each state concept both files carry: its Historic Table 2 / district-file - # ratio, judged against the measure's median ratio across states. - vintage_ratio: dict[tuple, float] = {} - for key in ht2_by_key.keys() & cd_file_state_by_key.keys(): - ht2_value = float(ht2_by_key[key].value) - cd_value = float(cd_file_state_by_key[key].value) - vintage_ratio[key] = ( - ht2_value / cd_value - if cd_value != 0.0 and (ht2_value > 0) == (cd_value > 0) - else math.nan - ) - ratios_by_identity: dict[tuple, list[float]] = defaultdict(list) - for (_state, identity), ratio in vintage_ratio.items(): - if math.isfinite(ratio): - ratios_by_identity[identity].append(ratio) - median_ratio = { - identity: float(np.median(values)) - for identity, values in ratios_by_identity.items() - } - out_of_band: list[dict] = [] - - def within_band( - key: tuple, - ratio: float, - median: float, - basis: str, - measure: str, - *, - verdict: str, - ) -> bool: - relative = ratio / median if math.isfinite(ratio) and median else math.nan - ok = math.isfinite(relative) and 1 / factor_band <= relative <= factor_band - if not ok: - out_of_band.append( - { - "state_fips": key[0], - "measure": measure, - "concept": key[1][0], - "basis": basis, - "verdict": verdict, - "ratio": ratio, - "median_ratio": median, - "relative": relative, - } - ) - return ok - - kept_cd_by_key: dict[tuple, list] = defaultdict(list) - for spec in cd_rows: - metadata = spec.metadata - measure = str(metadata.get("source_measure_id")) - state = str(metadata["state_fips"]) - if measure in STATE_CD_DEFECTIVE_CD_FILE_MEASURES: - drop(spec, f"defective_cd_file_column:{measure}") - elif measure in STATE_CD_UNPARENTED_CD_MEASURES: - drop(spec, f"no_state_parent:{measure}") - elif state in at_large_source_states: - drop(spec, "at_large_on_source_plan") - elif state in STATE_CD_EXCLUDED_CD_STATES: - drop(spec, f"excluded_state:{state}") - else: - kept_cd_by_key[(state, soi_concept_identity(spec))].append(spec) - - # Each Historic-Table-2-parented block's rebase factor (parent over its - # district rows' sum), judged against its concept's median across states. - block_factor: dict[tuple, float] = {} - for key, block in kept_cd_by_key.items(): - parent = ht2_by_key.get(key) - child_sum = math.fsum(float(spec.value) for spec in block) - if parent is not None and child_sum != 0.0: - block_factor[key] = float(parent.value) / child_sum - factors_by_identity: dict[tuple, list[float]] = defaultdict(list) - for (_state, identity), factor in block_factor.items(): - if math.isfinite(factor) and factor > 0: - factors_by_identity[identity].append(factor) - median_factor = { - identity: float(np.median(values)) - for identity, values in factors_by_identity.items() - } - - # One basis for every state level: a concept Historic Table 2 lacks keeps - # the district file's state row, scaled by a sibling's two levels. - bridged: dict[str, object] = {} - bridge_factors: dict[str, list[float]] = defaultdict(list) - for key, spec in sorted(cd_file_state_by_key.items()): - state, identity = key - measure = identity[0] - if key in ht2_by_key or measure in STATE_CD_DEFECTIVE_CD_FILE_MEASURES: - continue - sibling = level_bridges.get(measure) - if sibling is None: - raise ValueError( - f"District-file-only concept {measure!r} has no level bridge; " - "register a sibling measure in STATE_CD_LEVEL_BRIDGES before " - "binding it." - ) - sibling_key = (state, (sibling, *identity[1:])) - ht2_sibling = ht2_by_key.get(sibling_key) - cd_sibling = cd_file_state_by_key.get(sibling_key) - if ht2_sibling is None or cd_sibling is None or float(cd_sibling.value) == 0: - raise ValueError( - f"Level bridge {measure} -> {sibling} in state {state} needs " - "the sibling's state total in both files." - ) - factor = float(ht2_sibling.value) / float(cd_sibling.value) - # A sign conflict is a data defect, not a level disagreement: refuse - # it before the band, which only judges finite positive ratios. - if not (math.isfinite(factor) and factor > 0.0): - raise ValueError( - f"Level bridge {measure} -> {sibling} in state {state} has " - f"factor {factor}." - ) - # The sibling is trusted for bridging only if both of the band's - # verdicts on it pass: its two state levels, and (where it has district - # rows) the rebase of its own district block. - trusted = within_band( - sibling_key, - factor, - median_ratio.get(sibling_key[1], math.nan), - f"level_bridge:{measure}", - measure, - verdict="sibling_vintage_ratio", - ) - if sibling_key in block_factor: - trusted = ( - within_band( - sibling_key, - block_factor[sibling_key], - median_factor.get(sibling_key[1], math.nan), - f"level_bridge:{measure}", - measure, - verdict="sibling_rebase_factor", - ) - and trusted - ) - if not trusted: - continue - metadata = dict(spec.metadata) - metadata.update( - { - "state_cd_vintage_rule": STATE_CD_VINTAGE_RULE, - "state_cd_cd_file_value": repr(float(spec.value)), - "state_cd_level_bridge_sibling": ht2_sibling.name, - "state_cd_level_bridge_cd_file_sibling": cd_sibling.name, - "state_cd_level_bridge_factor": repr(factor), - } - ) - value = float(spec.value) * factor - bridged[spec.name] = replace( - spec, value=value, signed=value < 0.0, metadata=metadata - ) - bridge_factors[measure].append(factor) - - rebased: dict[str, object] = {} - internal_gaps: list[float] = [] - factors_by_measure: dict[str, list[float]] = defaultdict(list) - parent_basis_counts: Counter = Counter() - kept_cd_file_parents: set[str] = set() - for key in sorted(kept_cd_by_key): - state, identity = key - children = sorted( - kept_cd_by_key[key], - key=lambda spec: spec.metadata["congressional_district_geoid"], - ) - districts = [spec.metadata["congressional_district_geoid"] for spec in children] - expected = sorted(target_districts.get(state, ())) - if districts != expected: - raise ValueError( - f"District concept {identity} in state {state} covers " - f"{districts}, expected the current plan's {expected}; " - "rebasing an incomplete set would misstate every district." - ) - semantics = {soi_materializer_semantics(spec) for spec in children} - if len(semantics) != 1: - raise ValueError( - f"District rows of {identity} in state {state} materialize " - f"differently: {sorted(map(repr, semantics))}." - ) - (child_semantics,) = semantics - parent = ht2_by_key.get(key) - basis = "historic_table_2" - if parent is None: - parent = cd_file_state_by_key.get(key) - basis = "cd_file_state_total_bridged" - if parent is None: - raise ValueError( - f"District concept {identity} in state {state} has no " - "state parent in either vintage." - ) - if parent.name not in bridged: - for child in children: - drop(child, f"level_bridge_out_of_band:{identity[0]}") - continue - parent = bridged[parent.name] - kept_cd_file_parents.add(parent.name) - if soi_materializer_semantics(parent) != child_semantics: - raise ValueError( - f"State parent {parent.name} materializes differently from " - f"its district rows ({identity}, state {state})." - ) - child_sum = math.fsum(float(spec.value) for spec in children) - parent_value = float(parent.value) - if child_sum == 0.0: - if parent_value != 0.0: - raise ValueError( - f"District rows of {identity} in state {state} sum to zero " - f"under a nonzero parent {parent.name}={parent_value}." - ) - factor = 1.0 - else: - factor = parent_value / child_sum - if factor < 0.0: - raise ValueError( - f"District rows of {identity} in state {state} sum to " - f"{child_sum}, opposite in sign to parent {parent.name}=" - f"{parent_value}." - ) - # The district file must agree with itself before its shares are used. - cd_state = cd_file_state_by_key.get(key) - if cd_state is not None: - cd_state_value = float(cd_state.value) - gap = abs(cd_state_value - child_sum) - internal_gaps.append(gap / max(abs(cd_state_value), 1.0)) - if gap > STATE_CD_INTERNAL_RTOL * max(abs(cd_state_value), 1.0): - raise ValueError( - f"District-file state row {cd_state.name}={cd_state_value} " - f"differs from the sum of its district rows ({child_sum}) " - f"for {identity} in state {state}: a column or crosswalk " - "defect inside the district file." - ) - # An all-zero block agrees with a zero parent whatever the median. - if ( - basis == "historic_table_2" - and child_sum != 0.0 - and not within_band( - key, - factor, - median_factor.get(identity, math.nan), - "rebase", - identity[0], - verdict="rebase_factor", - ) - ): - for child in children: - drop(child, f"rebase_out_of_band:{identity[0]}") - continue - factors_by_measure[identity[0]].append(factor) - parent_basis_counts[basis] += len(children) - for child in children: - metadata = dict(child.metadata) - metadata.update( - { - "state_cd_vintage_rule": STATE_CD_VINTAGE_RULE, - "state_cd_parent_target_name": parent.name, - "state_cd_parent_basis": basis, - "state_cd_parent_value": repr(parent_value), - "state_cd_cd_file_value": repr(float(child.value)), - "state_cd_cd_file_state_sum": repr(child_sum), - "state_cd_rebase_factor": repr(factor), - } - ) - value = float(child.value) * factor - rebased[child.name] = replace( - child, - value=value, - signed=value < 0.0, - metadata=metadata, - ) - - kept_cd_file_state = [] - for spec in cd_file_state: - measure = str(spec.metadata.get("source_measure_id")) - key = (spec.metadata["state_fips"], soi_concept_identity(spec)) - if measure in STATE_CD_DEFECTIVE_CD_FILE_MEASURES: - drop(spec, f"defective_cd_file_column:{measure}") - elif key in ht2_by_key: - drop(spec, "second_vintage_of_state_concept") - elif spec.name not in bridged: - drop(spec, f"level_bridge_out_of_band:{measure}") - else: - kept_cd_file_state.append(bridged[spec.name]) - missing_parents = kept_cd_file_parents - {spec.name for spec in kept_cd_file_state} - if missing_parents: - raise ValueError( - f"District-file state parents {sorted(missing_parents)[:5]} were " - "dropped while their district rows were kept." - ) - - cd_specs = tuple(rebased[spec.name] for spec in cd_rows if spec.name in rebased) - specs = (*ht2_state, *kept_cd_file_state, *cd_specs) - # Fail closed on the invariant the whole surface rests on. - unreconciled = [ - block for block in state_parent_reconciliation(specs) if not block["ok"] - ] - if unreconciled: - raise ValueError( - f"{len(unreconciled)} district block(s) do not add up to a bound " - f"state parent, e.g. {unreconciled[:2]}." - ) - with_sigma = sum(1 for spec in specs if getattr(spec, "se", None) is not None) - receipt = { - "vintage_rule": STATE_CD_VINTAGE_RULE, - "vintage_rule_description": ( - "Historic Table 2 (TY2022) is the single vintage of every state " - "concept it carries. District-file (22incd.csv) district rows " - "keep only their within-state shares and are rebased to sum to " - "that parent. Concepts only the district file carries keep its " - "own state row as their parent, lifted onto the Historic Table 2 " - "basis by a sibling concept's ratio of the two files' state " - "totals in the same state (STATE_CD_LEVEL_BRIDGES)." - ), - "counts": { - "historic_table_2_state": len(ht2_state), - "cd_file_state": len(kept_cd_file_state), - "congressional_district": len(cd_specs), - "congressional_district_by_parent_basis": dict(parent_basis_counts), - "total": len(specs), - }, - "dropped": dict(sorted(dropped.items())), - "dropped_examples": dict(sorted(dropped_examples.items())), - "defective_cd_file_measures": dict(STATE_CD_DEFECTIVE_CD_FILE_MEASURES), - "unparented_cd_measures": dict(STATE_CD_UNPARENTED_CD_MEASURES), - "excluded_cd_states": dict(STATE_CD_EXCLUDED_CD_STATES), - "at_large_on_source_plan": at_large_source_states, - "internal_consistency": { - "rtol": STATE_CD_INTERNAL_RTOL, - "blocks_checked": len(internal_gaps), - "max_relative_gap": max(internal_gaps, default=0.0), - }, - "factor_band": { - "tolerance": factor_band, - "relative_to": "the measure's median Historic Table 2 / " - "district-file ratio across states", - "out_of_band": sorted( - out_of_band, key=lambda row: (row["concept"], row["state_fips"]) - ), - }, - "level_bridges": dict(level_bridges), - "level_bridge_factor_by_measure": { - measure: _factor_summary(values) - for measure, values in sorted(bridge_factors.items()) - }, - "rebase_factor_by_measure": { - measure: _factor_summary(values) - for measure, values in sorted(factors_by_measure.items()) - }, - "crosswalk": { - "source_plan": "117th_congress", - "target_plan": "119th_congress", - "method": "packaged 2020-block population crosswalk", - "sha256": crosswalk_sha256, - }, - "sigma": { - "targets_with_sigma": with_sigma, - "targets_without_sigma": len(specs) - with_sigma, - "note": ( - "The pinned feed carries no uncertainty field for any fact; " - "IRS SOI tables are administrative. target_roles.json records " - "sigma and sigma_basis for every target, null wherever a spec " - "carries none." - ), - }, - } - return StateCdSurface(specs=specs, receipt=receipt) + return StateCdSurface(specs=surface.specs, receipt=surface.receipt) def state_parent_reconciliation( @@ -725,30 +319,7 @@ def state_parent_reconciliation( ``ok`` (relative difference within ``rtol``). """ - by_name = {spec.name: spec for spec in specs} - blocks: dict[str, list] = defaultdict(list) - for spec in specs: - parent = spec.metadata.get("state_cd_parent_target_name") - if parent is not None: - blocks[parent].append(spec) - report = [] - for parent_name, children in sorted(blocks.items()): - parent = by_name.get(parent_name) - child_sum = math.fsum(float(spec.value) for spec in children) - parent_value = None if parent is None else float(parent.value) - scale = max(abs(parent_value or 0.0), 1.0) - report.append( - { - "parent": parent_name, - "parent_bound": parent is not None, - "parent_value": parent_value, - "district_sum": child_sum, - "n_districts": len(children), - "ok": parent is not None - and abs(child_sum - parent_value) <= rtol * scale, - } - ) - return report + return _target_nesting().district_block_closure(specs, rtol=rtol) # --------------------------------------------------------------------------- From 55fa55c36dc67b1be5f3dc400c5cea2d54d31f0e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:19:48 +0000 Subject: [PATCH 06/23] Make the county rows on the shared cross-grain operator Three county mechanisms of the ACS local release made rows from a state control with their own arithmetic (rows 8, 6 and 7 of microcosm#1760). The shared operator now divides each state control among its counties, with the allocator the US declaration names: - with_county_populations: the ladder's county overlaps, scaled to the state total (scale_residual_to_largest); - state_county_soi_surface: county SOI facts as shares of the broad state row, with the declared combined cell (share_residual_to_largest); - acs_household_surface: the state target is the sum of the county estimates (sum_of_lower_rows), and the counties divide it (share_residual_to_largest). The adapter (us_runtime.target_nesting) keeps the US side of each one: the fact checks, the completeness checks, the refusals with their texts and their order, and the old metadata keys and receipts. The tool functions keep their names and signatures. county_code_of, the county hierarchy, cell_members and the broad-parent test moved with them and stay in the tool under their old names. About 460 lines leave tools/us_acs_local_county_surface.py. The materialize stage records the operator's own receipt of each nesting pass and writes it to a new file, target_nesting.json. No stage reads it and it is not in the run identity. The old receipts keep their bytes. No target changes. Proof: - test_us_target_nesting_county.py holds each tool function to the verbatim copy of the code it replaces on 120 seeded inputs: the same specs in the same order, value bits, metadata key order, receipt bytes, refusal texts and refusal order. The draws include equal largest rows, zero rows, the combined cell, optional measures and ten kinds of refusal. - The three county test files, the tests that run the materialize stage and the pinned non-county surfaces pass unchanged. Not covered: the county rows on the pinned county facts file. The file is not a local test input, so these blocks are synthetic. Co-Authored-By: Claude Fable 5.2 --- .../build/us_runtime/target_nesting.py | 626 ++++++++++++++++++ .../us/test_us_target_nesting_county.py | 571 ++++++++++++++++ tools/build_us_acs_local_release.py | 8 + tools/us_acs_local_county_surface.py | 512 ++------------ 4 files changed, 1254 insertions(+), 463 deletions(-) create mode 100644 packages/microcosm-build/tests/engine_free/us/test_us_target_nesting_county.py diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/target_nesting.py b/packages/microcosm-build/src/microcosm/build/us_runtime/target_nesting.py index fe42f111fe..efb64a74b0 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/target_nesting.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/target_nesting.py @@ -42,8 +42,12 @@ apply_cross_grain_reconciliation, ) from microcosm.build.us_runtime.cross_grain_declarations import ( + COUNTY_ACS_HOUSEHOLDS, + COUNTY_POPULATION, + COUNTY_SOI, DISTRICT_SOI, load_us_cross_grain_declarations, + us_county_soi_nesting, us_cross_grain_mechanism, us_district_soi_nesting, ) @@ -871,3 +875,625 @@ def district_block_closure(specs: Sequence, *, rtol: float) -> list[dict]: def _bits(*values: float) -> bytes: return b"".join(struct.pack(" dict[int, float]: + """County populations from ladder overlaps, reconciled to state levels. + + Sums the ladder's overlap populations by county, then the operator + divides each state's total among its counties + (``scale_residual_to_largest``): the rounding residual goes to the largest + county, never a small one. + + Raises: + ValueError: If a state has no county or no positive population, or + if a county has no state. + """ + + raw = { + int(code): controls.sum_of_lower_rows(overlap_values[overlap_counties == code]) + for code in np.unique(overlap_counties) + } + mechanism = us_cross_grain_mechanism(COUNTY_POPULATION) + state_level, county_level = mechanism["higher_grain"], mechanism["lower_grain"] + blocks, block_codes = [], [] + for state, target in sorted(state_populations.items()): + block = sorted(code for code in raw if code // 1000 == int(state)) + total = controls.sum_of_lower_rows(raw[code] for code in block) + if not block or total <= 0 or not math.isfinite(target) or target <= 0: + raise ValueError(f"State {state} has no positive county/state population.") + blocks.append( + NestingBlock( + concept=POPULATION_CONCEPT, + filters=(), + control_geography_id=geography_id(state_level, f"{int(state):02d}"), + control_value=float(target), + lower_geography_ids=tuple( + geography_id(county_level, f"{code:05d}") for code in block + ), + lower_values=tuple(raw[code] for code in block), + ) + ) + block_codes.append(block) + nested, _operator_receipt = reconcile_blocks(COUNTY_POPULATION, blocks) + counties: dict[int, float] = {} + for block, rows in zip(block_codes, nested, strict=True): + counties.update(zip(block, rows.values, strict=True)) + unknown = sorted(set(raw) - set(counties)) + if unknown: + raise ValueError(f"County populations have no state parent: {unknown}.") + return counties + + +# --------------------------------------------------------------------------- +# State to county: IRS SOI shares (issue row 6) +# --------------------------------------------------------------------------- + + +def is_broad_state_parent(spec) -> bool: + """A state SOI row county facts can divide: all returns, no class.""" + + metadata = spec.metadata + return ( + spec.family == "irs_soi" + and metadata.get("ledger_geography_level") == "state" + and str(metadata.get("filing_status", "all")).lower() == "all" + and float(metadata.get("agi_lower_bound", "-inf")) == -math.inf + and float(metadata.get("agi_upper_bound", "inf")) == math.inf + and metadata.get("soi_return_universe", "all_returns") == "all_returns" + and metadata.get("itemized_only", "false").lower() != "true" + and metadata.get("taxable_only", "false").lower() != "true" + and spec.filter is None + and all( + str(metadata.get(key, "all")).lower() == "all" + for key in ("ledger_filter_filing_status", "ledger_filter_income_range") + ) + ) + + +def validated_combined_cells(combined_cells): + """Declared combined cells as ``{absent: host}`` codes, refusing bad ones.""" + + 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 county_soi_surface( + state_specs, facts, county_populations, *, combined_cells, soi_mode +) -> NestedSurface: + """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. + 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. The operator + divides each state row among its cells (``share_residual_to_largest``). + """ + + nesting = us_county_soi_nesting() + mechanism = us_cross_grain_mechanism(COUNTY_SOI) + state_level, county_level = mechanism["higher_grain"], mechanism["lower_grain"] + combined = validated_combined_cells(combined_cells) + blocks = defaultdict(dict) + for fact in facts: + observed = fact.get("observed_measure", {}) + if observed.get("source_name") != "irs_soi": + continue + code = county_code_of(fact, source="SOI") + dimensions = fact.get("dimensions", {}) + if any( + str(dimensions.get(key, "all")).lower() != "all" + for key in ("filing_status", "income_range") + ): + raise ValueError( + "County SOI requires all-return facts without AGI classes." + ) + measure = observed.get("source_measure_id") + period = str(fact.get("period", {}).get("value", "")) + if fact.get("period", {}).get("type") != "tax_year": + raise ValueError("County SOI facts must carry a tax_year period.") + key = (code // 1000, measure, period) + if code in blocks[key]: + raise ValueError(f"Duplicate county SOI fact for {key}, {code:05d}.") + value = float(fact["value"]) + if not math.isfinite(value) or value < 0: + raise ValueError( + f"County SOI shares require finite nonnegative values: {code:05d}." + ) + blocks[key][code] = (value, fact) + if not blocks: + raise ValueError( + "County facts carry no IRS SOI county rows; pass the pinned " + "--county-facts file (us/chronicle_county_facts.json, microcosm#922)." + ) + parents = {} + for spec in state_specs: + if not is_broad_state_parent(spec): + continue + metadata = spec.metadata + state = int(metadata["state_fips"]) + key = ( + state, + metadata.get("source_measure_id"), + str(metadata.get("source_period", "")), + ) + if key[1] not in nesting.required_measures and key[1] not in { + block[1] for block in blocks + }: + continue + if key in parents: + raise ValueError(f"Two state SOI parents for county concept {key}.") + parents[key] = spec + if not parents: + raise ValueError( + "No county SOI concept has an already materialized broad state parent." + ) + for state in sorted({int(code) // 1000 for code in county_populations}): + for measure in nesting.required_measures: + if not any(key[:2] == (state, measure) for key in parents): + raise ValueError( + f"Missing broad state SOI parent state={state:02d}, concept={measure}; " + "state_county requires return count and AGI in every state." + ) + # Every check a block must pass before the operator divides its control. + merges = defaultdict(list) + checked = [] + 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, {}) + completeness = controls.leg_completeness( + block, expected, combined_cells=combined + ) + if not expected or not completeness.complete: + raise ValueError( + f"Incomplete county SOI block state={state:02d}, concept={measure}, period={period}; " + f"missing={[f'{code:05d}' for code in completeness.missing]}, unexpected={[f'{code:05d}' for code in completeness.unexpected]}. " + "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(completeness.merged.items()): + members[host].append(code) + merges[(host, code)].append(f"{measure}|{period}") + codes = sorted(block) + raw_values = [block[code][0] for code in codes] + if controls.sum_of_lower_rows(raw_values) <= 0: + raise ValueError( + f"County SOI block {key} has no positive share denominator." + ) + shares, _total, _largest = controls.residual_shares(raw_values) + for code in codes: + unit = block[code][1].get("observed_measure", {}).get("unit") + if ( + parent.metadata.get("ledger_measure_unit") is not None + and unit != parent.metadata["ledger_measure_unit"] + ): + raise ValueError( + f"County SOI units differ from state parent {parent.name}: {unit!r}." + ) + checked.append((key, parent, expected, block, members, codes, shares)) + + # The operator divides each state row among its county cells. + nested, operator_receipt = reconcile_blocks( + COUNTY_SOI, + [ + NestingBlock( + concept=f"{parent.family}.{measure}", + filters=(("source_period", period),), + control_geography_id=geography_id(state_level, f"{state:02d}"), + control_value=float(parent.value), + lower_geography_ids=tuple( + geography_id(county_level, f"{code:05d}") for code in codes + ), + lower_values=tuple(block[code][0] for code in codes), + ) + for (state, measure, period), parent, _e, block, _m, codes, _s in checked + ], + ) + specs, receipts = [], [] + for (key, parent, expected, block, members, codes, shares), rows in zip( + checked, nested, strict=True + ): + state, measure, period = key + targets = list(rows.values) + state_population = controls.sum_of_lower_rows( + county_populations[code] for code in expected + ) + for code, share, target in zip(codes, shares, targets, strict=True): + raw, fact = block[code] + county = f"{code:05d}" + cell = sorted(members[code]) + name = f"county_{county}__{parent.name}" + metadata = { + **parent.metadata, + "ledger_geography_level": "county", + "ledger_geography_id": f"{COUNTY_PREFIX}{county}", + "ledger_geography_vintage": str( + fact["geography"].get("vintage", period) + ), + "ledger_layout_record_set_spec_id": str( + fact.get("layout", {}).get("record_set_spec_id", "county_soi") + ), + "county_fips": county, + "county_label": str(fact["geography"].get("name", county)), + "state_county_parent_target_name": parent.name, + "state_county_share": str(share), + "state_county_source_value": str(raw), + "county_population": str( + controls.sum_of_lower_rows( + 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"] = nesting.combined_cell_basis + specs.append( + replace( + parent, + name=name, + measure=name, + value=target, + se=None, + metadata=metadata, + hierarchy=county_hierarchy(name, county, parent=parent), + source=f"{parent.source}; IRS SOI county {period} within-state shares", + ) + ) + receipts.append( + { + "state_fips": f"{state:02d}", + "concept": measure, + "parent": parent.name, + "counties": len(expected), + "cells": len(codes), + "share_sum": controls.sum_of_lower_rows(shares), + "target_sum": controls.sum_of_lower_rows(targets), + } + ) + # Counties without a state parent cannot silently disappear. + 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}.") + receipt = { + "soi_mode": soi_mode, + "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": nesting.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", + } + return NestedSurface( + specs=tuple(specs), receipt=receipt, operator_receipt=operator_receipt + ) + + +# --------------------------------------------------------------------------- +# County to state: ACS households (issue row 7) +# --------------------------------------------------------------------------- + + +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, source_name, *, state=None, county=None): + from microcosm.calibrate import ( + CalibrationHierarchy, + HierarchyCategory, + HierarchyGeography, + HierarchyNode, + ) + from microcosm.calibrate.provider_labels import calibration_provider_label + + provider = HierarchyNode(source_name, calibration_provider_label("us", source_name)) + if county is not None: + # The same label every county family gives this county + # (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 county_acs_household_surface( + values, county_populations, *, period, source_name, tables, family, measure +) -> NestedSurface: + """State households parents and their county children (trained, levels). + + ``values`` is ``{county: (estimate, margin of error or None, name)}`` for + the households measure. Each state parent is the sum of its counties' + estimates (``sum_of_lower_rows``), a new state target that moves state + household counts to ACS 5-year levels; the operator then divides it among + the counties by share (``share_residual_to_largest``), so they sum to it. + ACS margins of error ride in metadata. + """ + from microcosm.calibrate import TargetSpec + + mechanism = us_cross_grain_mechanism(COUNTY_ACS_HOUSEHOLDS) + state_level, county_level = mechanism["higher_grain"], mechanism["lower_grain"] + source = ( + f"US Census Bureau {tables} B11001_001E (households), county; " + "state = sum of its counties" + ) + checked = [] + 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 = controls.sum_of_lower_rows(public) + if not codes or total <= 0: + raise ValueError( + f"ACS county households for state {state:02d} have no positive " + "share denominator." + ) + shares, _total, _largest = controls.residual_shares(public) + # Naming the state parent refuses a state with no Census name here, + # in state order, as it did when the parent was built in this loop. + parent_name = acs_households_parent_name(state) + parent_hierarchy = _acs_hierarchy(parent_name, source_name, state=state) + checked.append((state, codes, public, total, shares, parent_hierarchy)) + + # The operator divides each state's sum among its counties. + nested, operator_receipt = reconcile_blocks( + COUNTY_ACS_HOUSEHOLDS, + [ + NestingBlock( + concept=f"{source_name}.{measure}", + filters=(), + control_geography_id=geography_id(state_level, f"{state:02d}"), + control_value=total, + lower_geography_ids=tuple( + geography_id(county_level, f"{code:05d}") for code in codes + ), + lower_values=tuple(public), + ) + for state, codes, public, total, _shares, _hierarchy in checked + ], + ) + specs, receipts = [], [] + for (state, codes, _public, total, shares, parent_hierarchy), rows in zip( + checked, nested, strict=True + ): + parent_name = acs_households_parent_name(state) + state_population = controls.sum_of_lower_rows( + 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=family, + metadata={ + "geography_level": "state", + "state_fips": f"{state:02d}", + "source_measure_id": measure, + "acs_state_parent_basis": "sum of county estimates", + "household_universe": "excludes ACS group quarters (TYPEHUGQ 2, 3)", + "new_state_target": "true", + }, + hierarchy=parent_hierarchy, + ) + ) + targets = list(rows.values) + 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": 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 {tables} B11001_001E " + "(households), county share of the state sum", + family=family, + metadata=metadata, + hierarchy=_acs_hierarchy(name, source_name, county=county), + ) + ) + receipts.append( + { + "state_fips": f"{state:02d}", + "state_target": parent_name, + "state_households": total, + "counties": len(codes), + "share_sum": controls.sum_of_lower_rows(shares), + "target_sum": controls.sum_of_lower_rows(targets), + "counties_with_moe": sum(values[code][1] is not None for code in codes), + } + ) + receipt = { + "family": family, + "source_measure_id": measure, + "source": f"{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, + } + return NestedSurface( + specs=tuple(specs), receipt=receipt, operator_receipt=operator_receipt + ) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_target_nesting_county.py b/packages/microcosm-build/tests/engine_free/us/test_us_target_nesting_county.py new file mode 100644 index 0000000000..3fd5e0605b --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_target_nesting_county.py @@ -0,0 +1,571 @@ +"""The county rows on the shared operator give what the tool gave. + +microcosm#1760 moved three county mechanisms of the ACS local release onto +the shared cross-grain operator (``microcosm.build.cross_grain``), through +``microcosm.build.us_runtime.target_nesting``: the county populations +(``with_county_populations``), the county SOI shares +(``state_county_soi_surface``) and the county household rows +(``acs_household_surface``). These tests hold the tool functions, which now +call the adapter, to verbatim copies of the code they replace +(``test_support/microcosm_build/us_target_nesting_reference.py``) on seeded +random blocks: the same specs in the same order, the same value bits, the +same metadata keys in the same order, the same receipt bytes and the same +refusal texts. + +The blocks are synthetic. No test here reads the pinned county facts file +(``us/chronicle_county_facts.json``), which is not a test input on every +machine; a pin of the county rows on that file is a separate step. +""" + +from __future__ import annotations + +import dataclasses +import importlib.util +import json +import struct +from types import SimpleNamespace + +import numpy as np +import pytest + +from microcosm.build.us_runtime import cross_grain_declarations as declarations +from microcosm.build.us_runtime import target_nesting +from microcosm.calibrate import ( + CalibrationHierarchy, + HierarchyCategory, + HierarchyGeography, + HierarchyNode, + TargetSpec, +) +from test_support.microcosm_build import us_target_nesting_reference as reference +from test_support.paths import paths_for + +_TEST_PATHS = paths_for("microcosm-build") +SEEDS = range(120) +#: County SOI measures: the two every state must carry, and two optional ones. +_SOI_MEASURES = ( + "return_count", + "adjusted_gross_income", + "wages_salaries_amount", + "taxable_interest_amount", +) + + +@pytest.fixture(scope="module") +def county(): + path = _TEST_PATHS.repository / "tools" / "build_us_acs_local_release.py" + spec = importlib.util.spec_from_file_location( + "build_us_acs_local_release_nesting_county", path + ) + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + spec.loader.exec_module(module) + return module.county_surface + + +def _bits(values) -> bytes: + return b"".join(struct.pack(" tuple: + fields = { + field.name: getattr(spec, field.name) for field in dataclasses.fields(spec) + } + return ( + struct.pack(" tuple: + return ( + [_spec_image(spec) for spec in surface.specs], + json.dumps(surface.receipt, indent=1), + ) + + +def _outcome(function, *args, **kwargs): + try: + result = function(*args, **kwargs) + except ValueError as error: + return ("refused", str(error)) + return ("result", result) + + +def _county_codes(rng, *, hawaii: bool) -> dict[int, float]: + """Counties of one to four states with their ladder populations.""" + + populations: dict[int, float] = {} + # State codes with a Census name. Hawaii (15) enters only as the + # declared combined-cell case below. + candidates = np.setdiff1d(np.arange(1, 57), [3, 7, 14, 15, 43, 52]) + states = sorted(rng.choice(candidates, size=int(rng.integers(1, 5)), replace=False)) + for state in states: + for index in range(int(rng.integers(1, 9))): + populations[int(state) * 1000 + 2 * index + 1] = float( + rng.lognormal(mean=10.0, sigma=1.5) + ) + if hawaii: + populations.update({15001: 200.0, 15003: 1000.0, 15005: 80.0, 15009: 160.0}) + return dict(sorted(populations.items())) + + +# --------------------------------------------------------------------------- +# County populations (issue row 8) +# --------------------------------------------------------------------------- + + +def _ladder(seed: int): + rng = np.random.default_rng(seed) + populations = _county_codes(rng, hawaii=False) + overlap_county, overlap_population, overlap_puma = [], [], [] + for code in populations: + for piece in range(int(rng.integers(1, 5))): + overlap_county.append(code) + overlap_puma.append(code * 100 + piece) + value = float(rng.lognormal(mean=8.0, sigma=2.0)) + if rng.random() < 0.3: + value = float(round(value)) + if rng.random() < 0.05: + value = 0.0 + overlap_population.append(value) + states = sorted({code // 1000 for code in populations}) + hazard = rng.random() + if hazard > 0.95: + # A county whose state has no total, or a state with no county. + overlap_county.append(57001) + overlap_puma.append(5700100) + overlap_population.append(10.0) + puma = np.asarray([state * 100_000 + 1 for state in states]) + puma_population = rng.lognormal(mean=13.0, sigma=1.0, size=len(states)) + if 0.90 < hazard <= 0.95: + puma_population[0] = 0.0 + order = rng.permutation(len(overlap_county)) + ladder = SimpleNamespace( + puma=puma, + puma_population=puma_population, + county_overlap_puma=np.asarray(overlap_puma)[order], + county_overlap_county=np.asarray(overlap_county)[order], + county_overlap_population=np.asarray(overlap_population)[order], + ) + given = ( + {} + if rng.random() < 0.5 + else { + "state": { + int(state): float(rng.lognormal(mean=13.0, sigma=1.0)) + for state in states + }, + "cd": {int(states[0]) * 100 + 1: 5.0}, + } + ) + return ladder, given + + +def _population_image(result) -> tuple: + return ( + list(result), + { + level: (list(cells), _bits(cells.values())) + for level, cells in result.items() + }, + ) + + +def test_county_populations_are_the_old_populations_on_random_ladders(county) -> None: + outcomes = {"result": 0, "refused": 0} + cells = 0 + for seed in SEEDS: + ladder, given = _ladder(seed) + new = _outcome(county.with_county_populations, ladder, given, ["county"]) + old = _outcome(reference.with_county_populations, ladder, given, ["county"]) + assert new[0] == old[0], seed + if new[0] == "refused": + assert new[1] == old[1], seed + else: + assert _population_image(new[1]) == _population_image(old[1]), seed + cells += len(new[1]["county"]) + outcomes[new[0]] += 1 + # Without the county level the populations pass through untouched. + assert county.with_county_populations(ladder, given, ["state", "cd"]) is given + assert outcomes["result"] >= 90 and outcomes["refused"] >= 5 + assert cells >= 1_000 + + +# --------------------------------------------------------------------------- +# County SOI shares (issue row 6) +# --------------------------------------------------------------------------- + + +def _hierarchy(name: str, state: str) -> CalibrationHierarchy: + provider = HierarchyNode("irs_soi", "IRS Statistics of Income") + return CalibrationHierarchy( + provider=provider, + category=HierarchyCategory("irs_soi.returns", "Returns", provider.id), + geography=HierarchyGeography(f"0400000US{state}", f"State {state}", "state"), + dimensions=(), + target=HierarchyNode(name, f"State {state} {name}"), + ) + + +def _state_spec(measure, value, *, state, with_hierarchy, **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", + 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, + "measure_mode": "sum", + "agi_lower_bound": "-inf", + "agi_upper_bound": "inf", + "filing_status": "All", + **metadata, + }, + hierarchy=_hierarchy(name, state) if with_hierarchy else None, + ) + + +def _soi_fact(code: int, measure: str, value: float, *, unit=None, with_layout=True): + fact = { + "geography": { + "id": f"0500000US{code:05d}", + "level": "county", + "name": f"County {code:05d}", + "vintage": "2022", + }, + "period": {"type": "tax_year", "value": 2022}, + "observed_measure": { + "source_measure_id": measure, + "source_name": "irs_soi", + "unit": unit or ("count" if measure == "return_count" else "usd"), + }, + "dimensions": {"filing_status": "all", "income_range": "all"}, + "value": value, + } + if with_layout: + fact["layout"] = { + "record_set_spec_id": "irs_soi.county_totals.v1", + "groupby_value_id": f"{code:05d}", + } + return fact + + +def _soi_inputs(seed: int): + """State parents, county facts and populations, with the hard cases.""" + + rng = np.random.default_rng(seed) + hawaii = rng.random() < 0.25 + populations = _county_codes(rng, hawaii=hawaii) + states = sorted({code // 1000 for code in populations}) + measures = list(_SOI_MEASURES[:2]) + [ + measure for measure in _SOI_MEASURES[2:] if rng.random() < 0.6 + ] + hazard = rng.random() + parents, facts = [], [] + for state in states: + codes = [code for code in populations if code // 1000 == state] + for measure in measures: + if measure not in _SOI_MEASURES[:2] and rng.random() < 0.2: + continue # an optional measure with no state parent here + parents.append( + _state_spec( + measure, + float(rng.lognormal(mean=14.0, sigma=1.0)), + state=f"{state:02d}", + with_hierarchy=rng.random() < 0.7, + ) + ) + values = rng.lognormal(mean=9.0, sigma=2.0, size=len(codes)) + if rng.random() < 0.4: + values = np.round(values) + if len(codes) > 2 and rng.random() < 0.3: + values[int(rng.integers(len(codes)))] = values.max() # a tie + if rng.random() < 0.2: + values[int(rng.integers(len(codes)))] = 0.0 + if 0.86 < hazard <= 0.89 and rng.random() < 0.3: + values[:] = 0.0 # no positive share denominator + for code, value in zip(codes, values.tolist(), strict=True): + if code == 15005: + continue # absent from the SOI file: a declared combined cell + unit = ( + "returns" if 0.89 < hazard <= 0.92 and rng.random() < 0.05 else None + ) + facts.append( + _soi_fact( + code, measure, value, unit=unit, with_layout=rng.random() < 0.9 + ) + ) + # An AGI-band parent is no broad parent: it is passed over. + if rng.random() < 0.3: + parents.append( + _state_spec( + "return_count", + 7.0, + state=f"{state:02d}", + with_hierarchy=False, + agi_lower_bound="100000", + ) + ) + if 0.92 < hazard <= 0.95 and facts: + del facts[int(rng.integers(len(facts)))] # a county absent from a block + if 0.95 < hazard <= 0.97 and facts: + facts.append(dict(facts[0])) # a duplicate fact + if hazard > 0.97: + parents = [spec for spec in parents if "adjusted_gross" not in spec.name][:-1] + # A fact of another source is not a county SOI fact. + facts.append({"observed_measure": {"source_name": "census_acs"}}) + order = rng.permutation(len(facts)) + return parents, [facts[index] for index in order], populations + + +def _surface_outcome(function, *args, **kwargs): + outcome = _outcome(function, *args, **kwargs) + if outcome[0] == "refused": + return outcome + return ("surface", *_surface_image(outcome[1])) + + +def test_the_county_soi_surface_is_the_old_surface_on_random_blocks(county) -> None: + outcomes = {"surface": 0, "refused": 0} + refusals: set[str] = set() + rows = combined = 0 + for seed in SEEDS: + parents, facts, populations = _soi_inputs(seed) + new = _surface_outcome( + county.state_county_soi_surface, parents, facts, populations + ) + old = _surface_outcome( + reference.state_county_soi_surface, parents, facts, populations + ) + assert new == old, seed + outcomes[new[0]] += 1 + if new[0] == "refused": + refusals.add(" ".join(new[1].split(" ")[:3])) + continue + receipt = json.loads(new[2]) + rows += receipt["county_targets"] + combined += len(receipt["combined_cells"]) + assert outcomes["surface"] >= 80 and outcomes["refused"] >= 10 + assert len(refusals) >= 4 + assert rows >= 2_000 and combined >= 10 + + +def test_a_combined_cell_other_than_the_declared_one_is_the_old_refusal(county) -> None: + parents, facts, populations = _soi_inputs(3) + for cells in ({1001: 1001}, {1001: 2001}, {1003: 1001, 1001: 1005}): + new = _surface_outcome( + county.state_county_soi_surface, + parents, + facts, + populations, + combined_cells=cells, + ) + old = _surface_outcome( + reference.state_county_soi_surface, + parents, + facts, + populations, + combined_cells=cells, + ) + assert new == old and new[0] == "refused" + + +# --------------------------------------------------------------------------- +# County households (issue row 7) +# --------------------------------------------------------------------------- + + +def _acs_fact(code: int, measure: str, value, *, statistic=None, name=None): + return { + "geography": { + "id": f"0500000US{code:05d}", + "level": "county", + **({} if name is None else {"name": name}), + "vintage": "2024", + }, + "observed_measure": { + "source_measure_id": measure, + "source_name": "census_acs", + "unit": "count", + }, + "dimensions": { + "statistic": statistic + or ("estimate" if measure.endswith("E") else "margin_of_error") + }, + "period": {"type": "calendar_year", "value": 2024}, + "value": value, + "layout": {"groupby_value_id": f"{code:05d}"}, + } + + +def _acs_inputs(seed: int): + rng = np.random.default_rng(seed) + populations = _county_codes(rng, hawaii=False) + hazard = rng.random() + facts = [] + for code in populations: + households = float(round(rng.lognormal(mean=8.0, sigma=2.0))) + if rng.random() < 0.1: + households = 0.0 + if 0.90 < hazard <= 0.94: + households = 0.0 # no positive share denominator + name = None if rng.random() < 0.2 else f"Fixture County {code:05d}" + facts.append(_acs_fact(code, "B11001_001E", households, name=name)) + if rng.random() < 0.7: + facts.append(_acs_fact(code, "B11001_001M", max(1.0, households * 0.05))) + # Another ACS measure is not the households measure. + facts.append(_acs_fact(code, "B01003_001E", households * 2.5)) + if 0.94 < hazard <= 0.97: + del facts[0] # an incomplete inventory + if 0.97 < hazard <= 0.985: + facts.append(_acs_fact(56999, "B11001_001E", 5.0)) # outside the ladder + if hazard > 0.985: + # A state code with no Census name, between two states that have one. + populations[14001] = 10.0 + populations = dict(sorted(populations.items())) + facts.append(_acs_fact(14001, "B11001_001E", 5.0)) + order = rng.permutation(len(facts)) + return [facts[index] for index in order], populations + + +def test_the_county_household_surface_is_the_old_surface_on_random_blocks( + county, +) -> None: + outcomes = {"surface": 0, "refused": 0} + rows = 0 + for seed in SEEDS: + facts, populations = _acs_inputs(seed) + period = 2024 if seed % 3 else 2026 + new = _surface_outcome( + county.acs_household_surface, facts, populations, period=period + ) + old = _surface_outcome( + reference.acs_household_surface, facts, populations, period=period + ) + assert new == old, seed + outcomes[new[0]] += 1 + if new[0] == "surface": + rows += json.loads(new[2])["county_targets"] + assert outcomes["surface"] >= 90 and outcomes["refused"] >= 5 + assert rows >= 1_000 + + +def test_household_refusals_come_in_state_order_as_before(county) -> None: + """A state with no Census name is refused before a later state's zero sum.""" + + populations = {14001: 10.0, 34001: 10.0} + facts = [ + _acs_fact(14001, "B11001_001E", 5.0), + _acs_fact(34001, "B11001_001E", 0.0), + ] + new = _surface_outcome(county.acs_household_surface, facts, populations) + old = _surface_outcome(reference.acs_household_surface, facts, populations) + assert new == old == ("refused", "State 14 has no Census state name.") + # The other way round, the zero sum of the earlier state comes first. + populations = {1001: 10.0, 14001: 10.0} + facts = [ + _acs_fact(1001, "B11001_001E", 0.0), + _acs_fact(14001, "B11001_001E", 5.0), + ] + new = _surface_outcome(county.acs_household_surface, facts, populations) + old = _surface_outcome(reference.acs_household_surface, facts, populations) + assert new == old and "no positive share denominator" in new[1] + + +# --------------------------------------------------------------------------- +# What the wrappers keep, and the operator's receipts +# --------------------------------------------------------------------------- + + +def test_the_helpers_the_tool_keeps_by_name_are_the_adapters(county) -> None: + assert ( + county.COUNTY_PREFIX == target_nesting.COUNTY_PREFIX == reference.COUNTY_PREFIX + ) + assert county.PUERTO_RICO_STATE == reference.PUERTO_RICO_STATE + assert county._hierarchy is target_nesting.county_hierarchy + assert county.cell_members is target_nesting.cell_members + assert county.county_code_of is target_nesting.county_code_of + assert county._broad_parent is target_nesting.is_broad_state_parent + # The moved helpers give what the old ones gave. + spec = _state_spec("return_count", 5.0, state="06", with_hierarchy=True) + assert county._hierarchy("n", "06001", parent=spec) == reference._hierarchy( + "n", "06001", parent=spec + ) + assert county._hierarchy("n", "06001") == reference._hierarchy("n", "06001") + assert county.acs_households_parent_name(6) == reference.acs_households_parent_name( + 6 + ) + for metadata in ( + {"county_fips": "15009"}, + {"county_fips": "15009", "state_county_cell_members": "15005,15009"}, + ): + assert county.cell_members(metadata) == reference.cell_members(metadata) + + +def test_each_county_pass_records_the_operators_receipt(county) -> None: + def first_accepted(inputs, function): + """The first seeded inputs the tool accepts.""" + + for seed in SEEDS: + arguments = inputs(seed) + if _outcome(function, *arguments)[0] == "result": + return arguments + raise AssertionError("no seed was accepted") + + ladder, given = first_accepted( + _ladder, lambda *a: county.with_county_populations(*a, ["county"]) + ) + parents, facts, populations = first_accepted( + _soi_inputs, county.state_county_soi_surface + ) + acs_facts, acs_populations = first_accepted( + _acs_inputs, county.acs_household_surface + ) + recorded = target_nesting.start_nesting_receipts() + try: + county.with_county_populations(ladder, given, ["county"]) + soi = county.state_county_soi_surface(parents, facts, populations) + acs = county.acs_household_surface(acs_facts, acs_populations) + finally: + target_nesting.stop_nesting_receipts() + assert [(entry["mechanism"], entry["allocator"]) for entry in recorded] == [ + (declarations.COUNTY_POPULATION, "scale_residual_to_largest"), + (declarations.COUNTY_SOI, "share_residual_to_largest"), + (declarations.COUNTY_ACS_HOUSEHOLDS, "share_residual_to_largest"), + ] + for entry, blocks in zip( + recorded[1:], (soi.receipt["blocks"], acs.receipt["blocks"]), strict=True + ): + legs = [ + leg + for group in entry["operator_receipt"]["groups"] + for leg in group["legs"] + ] + assert len(legs) == entry["blocks"] == len(blocks) + assert { + group["winning_grain"] for group in entry["operator_receipt"]["groups"] + } == {"state"} + # Each leg closed on its control; the old receipt's target sum is that + # control under an exactly rounded sum. + for leg in legs: + assert leg["new_total"] == pytest.approx( + leg["old_total"] * leg["declared_factor"], rel=1e-12 + ) + # The old receipts do not hold the operator's receipt. + assert "groups" not in soi.receipt and "groups" not in acs.receipt diff --git a/tools/build_us_acs_local_release.py b/tools/build_us_acs_local_release.py index 5ee1c236fb..dead8ac88d 100644 --- a/tools/build_us_acs_local_release.py +++ b/tools/build_us_acs_local_release.py @@ -2296,6 +2296,11 @@ def _require_pro_rata_populations(targets: list[dict]) -> None: def do_materialize(args) -> None: from scipy import sparse + from microcosm.build.us_runtime import target_nesting + + # microcosm#1760: the shared cross-grain operator makes the district and + # county share rows. Record its own receipt of each pass from here on. + nesting_receipts = target_nesting.start_nesting_receipts() families = [item.strip() for item in args.families.split(",") if item.strip()] geographies = [item.strip() for item in args.geographies.split(",") if item.strip()] holdout_fraction = _cd_holdout_fraction(args) @@ -2545,6 +2550,9 @@ def do_materialize(args) -> None: indent=2, ) ) + # A receipt only: no stage reads it and the run identity does not hold it. + target_nesting.write_nesting_receipts(args.checkpoint_dir, nesting_receipts) + target_nesting.stop_nesting_receipts() log(f"materialize stage complete, peak RSS {rss():.2f}GB") diff --git a/tools/us_acs_local_county_surface.py b/tools/us_acs_local_county_surface.py index bce22d4271..469699d967 100644 --- a/tools/us_acs_local_county_surface.py +++ b/tools/us_acs_local_county_surface.py @@ -67,12 +67,20 @@ def _county_soi_nesting(): return us_county_soi_nesting() +def _target_nesting(): + """The US adapter to the shared cross-grain operator (microcosm#1760).""" + + from microcosm.build.us_runtime import target_nesting + + return target_nesting + + _COUNTY_SOI_NESTING = _county_soi_nesting() COUNTY_SOI_REQUIRED_MEASURES = _COUNTY_SOI_NESTING.required_measures #: 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 +PUERTO_RICO_STATE = _target_nesting().PUERTO_RICO_STATE #: Counties absent from an IRS SOI county file, each merged into one declared #: host county of the same state for the SOI families only (Kalawao County, @@ -180,23 +188,12 @@ def with_county_populations( or (values < 0).any() ): raise ValueError("County overlap populations must be finite and nonnegative.") - raw = { - int(code): math.fsum(values[counties == code]) for code in np.unique(counties) - } - result["county"] = {} - for state, target in sorted(result["state"].items()): - block = sorted(code for code in raw if code // 1000 == int(state)) - total = math.fsum(raw[code] for code in block) - if not block or total <= 0 or not math.isfinite(target) or target <= 0: - raise ValueError(f"State {state} has no positive county/state population.") - scaled = [float(target) * raw[code] / total for code in block] - # Assign the rounding residual to the largest cell, never a small county. - largest = max(range(len(block)), key=lambda index: scaled[index]) - scaled[largest] += float(target) - math.fsum(scaled) - result["county"].update(zip(block, scaled, strict=True)) - unknown = sorted(set(raw) - set(result["county"])) - if unknown: - raise ValueError(f"County populations have no state parent: {unknown}.") + # The shared cross-grain operator divides each state's total among its + # counties (microcosm#1760); the rounding residual goes to the largest + # county, never a small one. + result["county"] = _target_nesting().county_population_rows( + result["state"], counties, values + ) return result @@ -262,35 +259,10 @@ def population_rows( ) -def _hierarchy(name, code, *, parent=None): - from microcosm.calibrate import ( - CalibrationHierarchy, - HierarchyCategory, - HierarchyGeography, - HierarchyNode, - ) - - # One deterministic label for a county in all families. Source labels are - # retained in metadata; no mutable county-name registry is needed. - geography = HierarchyGeography(f"{COUNTY_PREFIX}{code}", f"County {code}", "county") - if parent is not None and parent.hierarchy is not None: - return dataclasses.replace( - parent.hierarchy, - geography=geography, - target=HierarchyNode( - name, f"{parent.hierarchy.target.label}, county {code}" - ), - ) - provider = HierarchyNode("census_population", "Census population") - return CalibrationHierarchy( - provider=provider, - category=HierarchyCategory( - "census_population.resident_population", "Resident population", provider.id - ), - geography=geography, - dimensions=(), - target=HierarchyNode(name, f"County {code} resident population"), - ) +#: The hierarchy of a county row, its member counties, a county fact's code +#: and the test for a state row that county facts can divide now live with +#: the county mechanisms in ``us_runtime.target_nesting`` (microcosm#1760). +_hierarchy = _target_nesting().county_hierarchy def population_spec(name, value, *, period=2024): @@ -310,23 +282,7 @@ def population_spec(name, value, *, period=2024): ) -def _broad_parent(spec): - metadata = spec.metadata - return ( - spec.family == "irs_soi" - and metadata.get("ledger_geography_level") == "state" - and str(metadata.get("filing_status", "all")).lower() == "all" - and float(metadata.get("agi_lower_bound", "-inf")) == -math.inf - and float(metadata.get("agi_upper_bound", "inf")) == math.inf - and metadata.get("soi_return_universe", "all_returns") == "all_returns" - and metadata.get("itemized_only", "false").lower() != "true" - and metadata.get("taxable_only", "false").lower() != "true" - and spec.filter is None - and all( - str(metadata.get(key, "all")).lower() == "all" - for key in ("ledger_filter_filing_status", "ledger_filter_income_range") - ) - ) +_broad_parent = _target_nesting().is_broad_state_parent @dataclasses.dataclass(frozen=True) @@ -335,55 +291,7 @@ class CountySurface: receipt: dict -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 +county_code_of = _target_nesting().county_code_of def state_county_soi_surface( @@ -401,209 +309,23 @@ def state_county_soi_surface( 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. + + The work is in + :func:`microcosm.build.us_runtime.target_nesting.county_soi_surface`: the + shared cross-grain operator divides each state row among its county cells + (microcosm#1760). """ - combined = _validated_combined_cells(combined_cells) - blocks = defaultdict(dict) - for fact in facts: - observed = fact.get("observed_measure", {}) - if observed.get("source_name") != "irs_soi": - continue - code = county_code_of(fact, source="SOI") - dimensions = fact.get("dimensions", {}) - if any( - str(dimensions.get(key, "all")).lower() != "all" - for key in ("filing_status", "income_range") - ): - raise ValueError( - "County SOI requires all-return facts without AGI classes." - ) - measure = observed.get("source_measure_id") - period = str(fact.get("period", {}).get("value", "")) - if fact.get("period", {}).get("type") != "tax_year": - raise ValueError("County SOI facts must carry a tax_year period.") - key = (code // 1000, measure, period) - if code in blocks[key]: - raise ValueError(f"Duplicate county SOI fact for {key}, {code:05d}.") - value = float(fact["value"]) - if not math.isfinite(value) or value < 0: - raise ValueError( - f"County SOI shares require finite nonnegative values: {code:05d}." - ) - blocks[key][code] = (value, fact) - if not blocks: - raise ValueError( - "County facts carry no IRS SOI county rows; pass the pinned " - "--county-facts file (us/chronicle_county_facts.json, microcosm#922)." - ) - parents = {} - for spec in state_specs: - if not _broad_parent(spec): - continue - metadata = spec.metadata - state = int(metadata["state_fips"]) - key = ( - state, - metadata.get("source_measure_id"), - str(metadata.get("source_period", "")), - ) - if key[1] not in COUNTY_SOI_REQUIRED_MEASURES and key[1] not in { - block[1] for block in blocks - }: - continue - if key in parents: - raise ValueError(f"Two state SOI parents for county concept {key}.") - parents[key] = spec - if not parents: - raise ValueError( - "No county SOI concept has an already materialized broad state parent." - ) - for state in sorted({int(code) // 1000 for code in county_populations}): - for measure in COUNTY_SOI_REQUIRED_MEASURES: - if not any(key[:2] == (state, measure) for key in parents): - raise ValueError( - f"Missing broad state SOI parent state={state:02d}, concept={measure}; " - "state_county requires return count and AGI in every state." - ) - 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(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; " - "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(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 expected) - for code, share, target in zip(codes, shares, targets, strict=True): - raw, fact = block[code] - unit = fact.get("observed_measure", {}).get("unit") - if ( - parent.metadata.get("ledger_measure_unit") is not None - and unit != parent.metadata["ledger_measure_unit"] - ): - raise ValueError( - 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, - "ledger_geography_level": "county", - "ledger_geography_id": f"{COUNTY_PREFIX}{county}", - "ledger_geography_vintage": str( - fact["geography"].get("vintage", period) - ), - "ledger_layout_record_set_spec_id": str( - fact.get("layout", {}).get("record_set_spec_id", "county_soi") - ), - "county_fips": county, - "county_label": str(fact["geography"].get("name", county)), - "state_county_parent_target_name": parent.name, - "state_county_share": str(share), - "state_county_source_value": str(raw), - "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, - name=name, - measure=name, - value=target, - se=None, - metadata=metadata, - hierarchy=_hierarchy(name, county, parent=parent), - source=f"{parent.source}; IRS SOI county {period} within-state shares", - ) - ) - receipts.append( - { - "state_fips": f"{state:02d}", - "concept": measure, - "parent": parent.name, - "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(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}.") - return CountySurface( - tuple(specs), - { - "soi_mode": SOI_MODE, - "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", - }, + surface = _target_nesting().county_soi_surface( + state_specs, + facts, + county_populations, + combined_cells=combined_cells, + soi_mode=SOI_MODE, ) + return CountySurface(surface.specs, surface.receipt) -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"])] +cell_members = _target_nesting().cell_members def split_state_rows( @@ -887,50 +609,7 @@ def acs_county_values(facts, measure_ids, *, required=None): 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}" +acs_households_parent_name = _target_nesting().acs_households_parent_name def acs_household_surface(facts, county_populations, *, period=2024): @@ -941,118 +620,25 @@ def acs_household_surface(facts, county_populations, *, period=2024): 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 + The work is in + :func:`microcosm.build.us_runtime.target_nesting.county_acs_household_surface`: + the shared cross-grain operator divides each state's sum among its + counties (microcosm#1760). + """ 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, - }, + surface = _target_nesting().county_acs_household_surface( + values, + county_populations, + period=period, + source_name=ACS_SOURCE_NAME, + tables=ACS_TABLES, + family=ACS_HOUSEHOLDS_FAMILY, + measure=ACS_HOUSEHOLDS_MEASURE, ) + return CountySurface(surface.specs, surface.receipt) def _spines(households): From c3dc13b4ce2db29ae95e7f400f9861fe1cf1f100 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:24:42 +0000 Subject: [PATCH 07/23] Declare the US nesting inventory, with docs and a coverage test us/cross_grain_declarations.json gains an inventory: each US family that two geography levels measure, with the route that ties the levels today or the reason none does (microcosm#1760). It records what the code does. It decides no nesting rule: the decisions of the issue are open, and Stage B applies them. - Rows 1 to 4 of the issue (capital gains, taxable interest, state AGI bands, the district file's own state row) are compile rules. Each entry says why its arithmetic stays where it is in Stage A and names the metadata the rule writes. - Rows 5 to 8 name their mechanism on the shared operator. - The families that do not nest have a reason and an issue: the SOI families with two national rows, the state age rows, the program families whose state rows are not checked against their national row, the families with no national row, and the district ACS rows that are not in the fit. us_cross_grain_coverage_violations checks a set of compiled specs against the inventory. It is a receipt and a test of the declaration. No build calls it and it refuses nothing. docs/us-target-nesting.md describes the operator, the allocators, the four mechanisms, the receipts, the inventory and what Stage A leaves open. Proof: test_us_cross_grain_coverage.py checks each entry, that rows 1 to 8 each have one entry and each mechanism has one, and each kind of gap on synthetic specs. With the pinned feed it compiles the registry: no violation, and the families below the national level are exactly the ones the compiled entries name. The inventory does not move the US pins (both --check modes pass). Co-Authored-By: Claude Fable 5.2 --- ...s-target-nesting-on-cross-grain.changed.md | 1 + docs/us-acs-local-county-rung.md | 7 + docs/us-acs-local-soi-target-surface.md | 6 +- docs/us-target-nesting.md | 205 +++++++++++ .../build/us/cross_grain_declarations.json | 322 +++++++++++++++++- .../us_runtime/cross_grain_declarations.py | 192 ++++++++++- .../us/test_us_cross_grain_coverage.py | 255 ++++++++++++++ 7 files changed, 984 insertions(+), 4 deletions(-) create mode 100644 changelog.d/1760-us-target-nesting-on-cross-grain.changed.md create mode 100644 docs/us-target-nesting.md create mode 100644 packages/microcosm-build/tests/engine_free/us/test_us_cross_grain_coverage.py diff --git a/changelog.d/1760-us-target-nesting-on-cross-grain.changed.md b/changelog.d/1760-us-target-nesting-on-cross-grain.changed.md new file mode 100644 index 0000000000..57983111e8 --- /dev/null +++ b/changelog.d/1760-us-target-nesting-on-cross-grain.changed.md @@ -0,0 +1 @@ +The US share mechanisms of the ACS local release run on the shared cross-grain operator that the UK uses (`microcosm.build.cross_grain`), with no target change (microcosm#1760, Stage A). `CrossGrainRule` takes an optional `allocator`: with none, the operator runs its standing rule with no float operation added or removed, so the UK outputs are the same; the UK graph hashes the file, so UK target nodes and the nodes after them compute again on the next UK run. The new shared `microcosm.build.cross_grain_controls` holds the allocators, derived controls, factor band, completeness and self-consistency helpers. `us/cross_grain_declarations.json` declares the US levels, the four mechanisms (district SOI shares, county population, county SOI shares, county households) with their registers, and an inventory of each family that two levels measure; `us_runtime.target_nesting` is the adapter. `state_cd_soi_surface`, `with_county_populations`, `state_county_soi_surface` and `acs_household_surface` keep their names and signatures. Every surface on the pinned feed and ladder has the bytes it had. The materialize stage also writes the operator's own receipts to `target_nesting.json`. See `docs/us-target-nesting.md`. diff --git a/docs/us-acs-local-county-rung.md b/docs/us-acs-local-county-rung.md index 15114e06f9..99f2ae201d 100644 --- a/docs/us-acs-local-county-rung.md +++ b/docs/us-acs-local-county-rung.md @@ -9,6 +9,13 @@ 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. +Since microcosm#1760 the three share mechanisms of the rung (county +population, county SOI shares, county households) run on the shared +cross-grain operator, through `us_runtime.target_nesting`, with their choices +declared in `us/cross_grain_declarations.json`. The tool functions keep their +names, and every row, metadata key and receipt is as it was. See +[US target nesting](us-target-nesting.md). + ## Plan and invariants - Population measures are household size times county membership. County diff --git a/docs/us-acs-local-soi-target-surface.md b/docs/us-acs-local-soi-target-surface.md index c3fec3c67c..98385be2df 100644 --- a/docs/us-acs-local-soi-target-surface.md +++ b/docs/us-acs-local-soi-target-surface.md @@ -179,7 +179,11 @@ storage](#target-matrix-storage) replaces this. the TY2022 SOI congressional-district file (`22incd.csv`, record-set spec `irs_soi.congressional_district_2022.all_returns.v1`), reconciled so that every state concept has one vintage. The rule is -`us_acs_local_cd_surface.state_cd_soi_surface`. +`us_acs_local_cd_surface.state_cd_soi_surface`. Since microcosm#1760 that +function calls `us_runtime.target_nesting.district_soi_surface`: the shared +cross-grain operator divides each state row among its district rows, with the +choices below declared in `us/cross_grain_declarations.json`. The surface has +the bytes it had. See [US target nesting](us-target-nesting.md). ### One vintage per state concept diff --git a/docs/us-target-nesting.md b/docs/us-target-nesting.md new file mode 100644 index 0000000000..e08d3c236c --- /dev/null +++ b/docs/us-target-nesting.md @@ -0,0 +1,205 @@ +# US target nesting across geography levels + +A target for a small area must agree with the target of the area that +contains it. This page says how the US build makes the rows of a lower +geography level from a control at a higher level, and where each choice is +declared. The tracking issue is microcosm#1760. Stage A, described here, +changes no target value. + +## What Stage A decides: nothing + +Stage A moves the mechanisms that exist to one operator and writes their +choices down as data. Each mechanism is declared as the code ran it before +the move. These decisions of microcosm#1760 are open, and Stage B applies +them: + +1. Which level holds the level value, for each family. +2. Two sources at two levels: whether district rows from a survey are shares + of a state row from estimates, or stay as levels. +3. Row 7: whether the state households target stays the sum of the county + values, or becomes a state level that the counties divide. +4. The parent row in the loss, when all its children are in the loss too. +5. The factor bound: one declared bound for each bridge, as in the UK, or + the median band of row 5. +6. Children that are not complete: district plans, a county with no IRS row, + a state with one district. + +After Stage A, each decision is an edit to the declaration, and for some an +allocator. It is not a new mechanism. + +## One operator, one declaration + +The US uses the cross-grain operator that the UK uses, +`microcosm.build.cross_grain`. The operator groups the rows of one quantity, +finds the control of each lower leg, divides the control among the leg's rows, +checks that the rows sum to the control, and writes a receipt. It changes +target values only, never loss weights. + +| Part | Where | What it holds | +|---|---|---| +| The operator | `microcosm.build.cross_grain` | Grouping, the control of each leg, the division, the sum check, the receipt. Shared with the UK. | +| The helpers | `microcosm.build.cross_grain_controls` | Allocators, derived controls, the factor band, the completeness check, the self-consistency check. No country in it. | +| The US declaration | `us/cross_grain_declarations.json` | The levels, the levels that hold controls, each mechanism with its registers and reasons, and the inventory. | +| The reader | `us_runtime/cross_grain_declarations.py` | Typed views of the declaration. | +| The US adapter | `us_runtime/target_nesting.py` | Which specs or facts are the control and the rows, the refusals with their US texts, the old metadata keys and receipts. | + +The declaration uses the key names of `uk/cross_grain_declarations.json` where +the meaning is the same: `grain_precedence`, `control_grains`, +`signature_fields`, `bridges` and `partitions`. The US levels are the feed's +own geography levels: `country`, `state`, `congressional_district`, `county`. +Districts and counties both divide a state. They do not nest in each other, +and only `country` and `state` hold controls. + +### The allocator + +The operator's standing rule is `row x control / numpy sum of the rows`. The +US rows were made with `math.fsum`, and the county rows with a residual rule. +On the pinned feed the numpy sum changes the last bit of 5,533 of the 21,743 +district values. So a rule can declare an allocator +(`CrossGrainRule.allocator`), a function that divides one control among its +rows. With no allocator the operator runs the standing rule, with no float +operation added or removed; the UK declares none. + +| Allocator | Rule | Used by | +|---|---|---| +| `proportional_fsum` | `row x control / exactly rounded sum` | District SOI shares | +| `share_residual_to_largest` | `control x share`; the rounding residual of the shares, then of the products, goes to the largest row | County SOI shares, county households | +| `scale_residual_to_largest` | `control x row / total`; the rounding residual goes to the largest row | County population | + +The two residual allocators only reproduce the old county arithmetic. Stage B +replaces them with one allocator. + +## The four mechanisms on the operator + +Each one is declared under `mechanisms`. The tool function keeps its name and +signature and calls the adapter. + +| Row of the issue | Mechanism | Tool function | The control | The rows | +|---|---|---|---|---| +| 5 | `state_congressional_district_soi` | `us_acs_local_cd_surface.state_cd_soi_surface` | The Historic Table 2 state row. For a concept that only the district file has: the district file's state row, multiplied by a sibling concept's ratio of the two files (`scaled_by_sibling_ratio`) | District file rows of the state | +| 8 | `state_county_population` | `us_acs_local_county_surface.with_county_populations` | The state total of the 2020 PUMA ladder | The ladder's county overlaps, summed by county | +| 6 | `state_county_soi` | `us_acs_local_county_surface.state_county_soi_surface` | The broad state SOI row that exists | County facts of the state. One declared combined cell covers a county with no IRS row | +| 7 | `county_state_acs_households` | `us_acs_local_county_surface.acs_household_surface` | The sum of the county estimates (`sum_of_lower_rows`). It is a new state target | The county estimates | + +### What the adapter does before the operator runs + +These checks are US rules. They run first, with the texts they always had, so +a refusal reads the same as before. + +- **District SOI.** + - The district rows of a block must be exactly the current plan's districts + of the state (from the district crosswalk). A state with one district on + the source plan has no district rows. + - The district file's own state row must equal the sum of its district rows + within `1e-6` (`self_consistency`). + - A block whose ratio (control over the sum of its rows) is more than 1.25 + from its concept's median across states is dropped and recorded + (`factor_band`). The Historic Table 2 state row stays. + - The registers of defective, unparented and excluded district measures and + the six level bridges are in the declaration, with their reasons. +- **County population.** Each state needs a positive total and at least one + county with a positive population. Each county needs a state. +- **County SOI.** Each state block must hold every county of the ladder. + A county with no fact is refused unless it is a declared combined cell. + Return count and adjusted gross income must have a state parent in every + state. +- **County households.** Every county of the ladder must carry an estimate, + and each state needs a positive sum. + +### What the operator refuses + +The operator applies its own refusals to every block: a total that is not +finite, a lower sum below `1e-9` of the control, a negative factor, and rows +that do not sum to the control within `1e-9`. On valid data the result is the +old result. Three cases that the old code computed are now refused: + +- a block whose rows sum to a value that is not zero but is below `1e-9` of + its control; +- a county SOI block under a negative state row; +- a control of `-0.0`. + +None occurs on the pinned feed. The pinned county facts hold return counts +and adjusted gross income only, and both are positive in every state. + +## Receipts + +- **The old receipts and metadata keys stay**, with the same bytes: the + `state_cd_*` and `state_county_*` keys, the `soi_surface` receipt in + `materialize_rss.json`, and `county_surface.json`. Other code reads these + keys (the loss weights, the pro-rata baselines, the reviewed limitations). +- **The operator's own receipt goes to a new file**, `target_nesting.json`, + which the materialize stage writes beside its other files. It holds one + entry for each pass: the mechanism, the allocator, the number of blocks and + the operator's receipt (each group and each leg with its control, its old + and new totals and its factor). No stage reads the file, and it is not in + the run identity. + +One receipt format for both countries is a Stage B step, because it changes +the bytes of the registry. + +## The inventory + +`inventory` in the declaration lists each US family that two levels measure, +with one route: + +| Route | Meaning | +|---|---| +| `mechanism` | The shared operator makes the rows (rows 5 to 8). | +| `compile_rule` | A pass of the compile makes them and stays where it is in Stage A (rows 1 to 4). | +| `same_source` | Both levels are sums of one source's cells. | +| `no_higher_control` | No row at a higher level measures the quantity. | +| `not_reconciled` | Two levels measure it and no rule ties them yet. The entry gives the reason and the issue. | +| `not_in_the_fit` | The rows are not compiled. | + +### Why rows 1 to 4 stay in the compile + +- **Rows 1 and 2 (capital gains, taxable interest).** Each row is multiplied + by one factor, `control / published national total`. The rows are not scaled + to sum to the control, and the control and the total are read from the + facts, not from rows of the registry. +- **Row 3 (state AGI bands).** It is a partition inside one area. The + partition is read from the facts, and only some of its bands bind. +- **Row 4 (the district file's own state row).** It is already shared code + with its rule as data (`reconcile_ledger_target_hierarchy`, declared in + `us/fiscal_target_references.json`). It sums with the builtin `sum`, formats + its factor with 15 significant digits and writes `hierarchy_*` keys. The + bytes of the `full` and `state_cd` surfaces depend on all three. + +### Families that do not nest today + +- The SOI families with two national rows (microcosm#1243). +- State age rows and state totals (microcosm#1528, #1526, #1531). +- The state rows of SNAP, Medicaid and CHIP, SSI and TANF against the national + row of each family. This is not checked yet. +- District age and household rows from ACS, which are not in the fit + (microcosm#1731). + +## The coverage test + +`test_us_cross_grain_coverage.py` reads the inventory. It checks that each +entry is well formed, that rows 1 to 8 each have one entry, and that each +mechanism has one. With the pinned feed it also compiles the registry and +checks that each family at a level below `country` has an entry, that no +entry names rows that are gone, and that each compile rule's marker is on +rows of the declared family and levels. + +It is a test of the declaration. It refuses nothing in a build and it is not +a release gate. + +## The UK + +The UK graph hashes `cross_grain.py`. The edit that added the allocator makes +the UK target nodes, and every node after them, compute again on the next UK +run. The outputs are the same: `test_cross_grain_allocator.py` compares the +operator with a copy of the file before the edit, bit for bit, on 400 seeded +surfaces. The UK graph does not hash `cross_grain_controls`. + +## Not in Stage A + +- Every target change (Stage B of microcosm#1760): one allocator for the + county rows, one receipt format, the ACS district rows, district and county + rows in one run, the families of microcosm#1243, row 4 on the operator. +- One function for the two matrix splits (`split_carriers_into`, + `split_state_rows`). They do no arithmetic on target values. +- A pin of the county rows on the pinned county facts file. The equivalence + tests of the county rows use synthetic blocks. diff --git a/packages/microcosm-build/src/microcosm/build/us/cross_grain_declarations.json b/packages/microcosm-build/src/microcosm/build/us/cross_grain_declarations.json index d0253a90fa..8e99c4259a 100644 --- a/packages/microcosm-build/src/microcosm/build/us/cross_grain_declarations.json +++ b/packages/microcosm-build/src/microcosm/build/us/cross_grain_declarations.json @@ -1,6 +1,6 @@ { "schema_version": 1, - "description": "US cross-grain nesting declarations (microcosm#1760). Each mechanism makes the rows of a lower geography level from a control at a higher level, on the shared operator microcosm.build.cross_grain, with the helpers of microcosm.build.cross_grain_controls. This file holds the US choices: the order of the levels, which levels hold controls, the allocator of each mechanism, the rule for its control, its bounds, the source of its member lists, and its reviewed registers with their reasons. Tools and tests read it through microcosm.build.us_runtime.cross_grain_declarations; the adapter is microcosm.build.us_runtime.target_nesting. Stage A changes no target value. docs/us-target-nesting.md describes each mechanism.", + "description": "US cross-grain nesting declarations (microcosm#1760). Each mechanism makes the rows of a lower geography level from a control at a higher level, on the shared operator microcosm.build.cross_grain, with the helpers of microcosm.build.cross_grain_controls. This file holds the US choices: the order of the levels, which levels hold controls, the allocator of each mechanism, the rule for its control, its bounds, the source of its member lists, and its reviewed registers with their reasons. Tools and tests read it through microcosm.build.us_runtime.cross_grain_declarations; the adapter is microcosm.build.us_runtime.target_nesting. Stage A changes no target value and decides no nesting rule: each mechanism is declared as the code ran it before the move. docs/us-target-nesting.md describes each mechanism.", "grain_precedence": [ "country", "state", @@ -194,5 +194,325 @@ }, "receipt": "county_surface.json: acs_households" } + }, + "inventory": { + "description": "What the code does today, as data. It decides no rule: the decisions of microcosm#1760 (which level holds the level value of a family, two sources at two levels, the direction of the county households rows, the parent row in the loss, the factor bound, children that are not complete) are open, and Stage B applies them. How each US family that two geography levels measure gets its lower level from its higher one, or why it does not. An entry names a family, its lower levels and the higher level, and one route: 'mechanism' (the shared cross-grain operator makes the rows; mechanisms above), 'compile_rule' (a pass of the compile makes them and stays where it is in Stage A, with the reason), 'same_source' (both levels are sums of one source's cells), 'no_higher_control' (no row at a higher level measures the quantity), 'not_reconciled' (two levels measure it and no rule ties them yet, with the reason and the issue) or 'not_in_the_fit' (the rows are not compiled). 'compiled' says whether the compiled registry of the pinned feed holds the rows; 'marker' names the metadata that the rule writes on them. The coverage test reads this section; it refuses nothing in a build.", + "routes": [ + "mechanism", + "compile_rule", + "same_source", + "no_higher_control", + "not_reconciled", + "not_in_the_fit" + ], + "entries": [ + { + "id": "soi_capital_gains_shares_of_national_control", + "issue_row": 1, + "family": "irs_soi", + "levels": [ + "state", + "congressional_district" + ], + "higher_level": "country", + "route": "compile_rule", + "compiled": true, + "code": "microcosm.build.us_runtime.fiscal_targets._rebase_stale_soi_capital_gains_distributions", + "marker": { + "metadata_key": "soi_control_concept" + }, + "level_holder": "country: the Table 1.4 national control at or after the row's period", + "reason": "Each Historic Table 2 or district-file capital-gains row ships as its share of its own family's national total, scaled to the control: one factor for each family, quantity and period. A row with no control is dropped. It stays in the compile because it is another operation than the operator's: every row takes one factor, control / published national total, the rows are not scaled to sum to the control, and the control and the total are read from the facts, not from rows of the registry. The operator divides a control that is a row of its surface.", + "issues": [ + "microcosm#1035", + "microcosm#1038" + ] + }, + { + "id": "soi_taxable_interest_national_factor", + "issue_row": 2, + "family": "irs_soi", + "levels": [ + "state", + "congressional_district" + ], + "higher_level": "country", + "route": "compile_rule", + "compiled": true, + "code": "microcosm.build.us_runtime.fiscal_targets._rebase_stale_soi_taxable_interest_distributions", + "marker": { + "metadata_key": "uprating_index", + "value_prefix": "total_taxable_interest_" + }, + "level_holder": "country: the latest Pub 1304 national value", + "reason": "Every stale Historic Table 2 taxable-interest row is multiplied by one national factor onto the latest national value; the TY2022 shares across states stay. It stays in the compile for the reason of row 1: one factor from the facts, no scaling of rows to a control row.", + "issues": [ + "microcosm#489" + ] + }, + { + "id": "soi_state_agi_bands_share_of_state_total", + "issue_row": 3, + "family": "irs_soi", + "levels": [ + "state" + ], + "higher_level": "state", + "route": "compile_rule", + "compiled": true, + "code": "microcosm.build.us_runtime.fiscal_targets._rebase_soi_state_agi_bands", + "marker": { + "metadata_key": "state_agi_band_share" + }, + "level_holder": "state: the all-returns row that binds", + "reason": "A partition inside one area, not a relation between levels: each flagged AGI band becomes control x band / published partition. The partition is the sum of the state's published bands over the whole AGI line, read from the facts, and only the bands from the $100k floor up bind. It stays in the compile because the operator's partitions need every member on the surface.", + "issues": [ + "microcosm#940" + ] + }, + { + "id": "soi_district_file_children_scale_to_state_parent", + "issue_row": 4, + "family": "irs_soi", + "levels": [ + "congressional_district" + ], + "higher_level": "state", + "route": "compile_rule", + "compiled": true, + "code": "microcosm.build.ledger_targets.reconcile_ledger_target_hierarchy, declared in us/fiscal_target_references.json (congressional_district_children_scale_to_state_parent)", + "marker": { + "metadata_key": "hierarchy_reconciliation_rule", + "value": "congressional_district_children_scale_to_state_parent" + }, + "level_holder": "state: the district file's own state row", + "reason": "A second shared rule for the same job, with its rule as data: the district rows of the district file are scaled to sum to that file's own state row, and a missing district fails the compile. It stays where it is in Stage A because it sums with the builtin sum, formats its factor with 15 significant digits and writes its own hierarchy_* keys, and the bytes of the full and state_cd surfaces depend on all three. Folding it into the operator is a Stage B step or a consolidation issue.", + "issues": [ + "microcosm#1760" + ] + }, + { + "id": "soi_district_shares_of_historic_table_2_state", + "issue_row": 5, + "family": "irs_soi", + "levels": [ + "congressional_district" + ], + "higher_level": "state", + "route": "mechanism", + "mechanism": "state_congressional_district_soi", + "compiled": true, + "surfaces": [ + "state_cd" + ], + "level_holder": "state: the Historic Table 2 state row, or the district file's state row lifted by a sibling ratio", + "issues": [ + "microcosm#1760", + "microcosm#1731" + ] + }, + { + "id": "soi_county_shares_of_state", + "issue_row": 6, + "family": "irs_soi", + "levels": [ + "county" + ], + "higher_level": "state", + "route": "mechanism", + "mechanism": "state_county_soi", + "compiled": false, + "surfaces": [ + "state_county" + ], + "level_holder": "state: the broad state row that exists", + "issues": [ + "microcosm#922", + "microcosm#1760" + ] + }, + { + "id": "acs_households_state_is_the_county_sum", + "issue_row": 7, + "family": "acs_households", + "levels": [ + "county" + ], + "higher_level": "state", + "route": "mechanism", + "mechanism": "county_state_acs_households", + "compiled": false, + "surfaces": [ + "state_county" + ], + "level_holder": "county: the state target is the sum of the county estimates", + "issues": [ + "microcosm#922", + "microcosm#1760" + ] + }, + { + "id": "ladder_county_population_scaled_to_state", + "issue_row": 8, + "family": "census_population", + "levels": [ + "county" + ], + "higher_level": "state", + "route": "mechanism", + "mechanism": "state_county_population", + "compiled": false, + "surfaces": [ + "state_county" + ], + "level_holder": "state: the total of the 2020 PUMA ladder", + "issues": [ + "microcosm#922", + "microcosm#1760" + ] + }, + { + "id": "ladder_state_and_district_population_from_one_ladder", + "family": "census_population_ladder", + "levels": [ + "congressional_district" + ], + "higher_level": "state", + "route": "same_source", + "compiled": false, + "reason": "The state and district population totals of the local build are sums of the cells of one 2020 PUMA ladder. No rule runs.", + "issues": [ + "microcosm#1760" + ] + }, + { + "id": "soi_state_rows_under_two_national_rows", + "family": "irs_soi", + "levels": [ + "state" + ], + "higher_level": "country", + "route": "not_reconciled", + "compiled": true, + "reason": "Several SOI families bind a Historic Table 2 US row beside a newer Table 1.x row, and no rule ties their state rows to either. Rows 1 and 2 are the treatment that the issue asks for the others. It waits for Stage A.", + "issues": [ + "microcosm#1243" + ] + }, + { + "id": "state_age_rows_and_state_totals", + "family": "census_population", + "levels": [ + "state" + ], + "higher_level": "country", + "route": "not_reconciled", + "compiled": true, + "reason": "The national build fits Census age bands for each state. The local build fits state totals from the 2020 ladder and no age row. No rule ties the age rows of a state to its total, or to the national age rows.", + "issues": [ + "microcosm#1528", + "microcosm#1526", + "microcosm#1531" + ] + }, + { + "id": "usda_snap_state_rows_and_national_row", + "family": "usda_snap", + "levels": [ + "state" + ], + "higher_level": "country", + "route": "not_reconciled", + "compiled": true, + "reason": "Not checked yet: whether the state rows of SNAP sum to the national row of the family. No rule ties them.", + "issues": [ + "microcosm#1760" + ] + }, + { + "id": "cms_medicaid_state_rows_and_national_row", + "family": "cms_medicaid", + "levels": [ + "state" + ], + "higher_level": "country", + "route": "not_reconciled", + "compiled": true, + "reason": "Not checked yet: whether the state rows of Medicaid and CHIP sum to the national row of the family. No rule ties them.", + "issues": [ + "microcosm#1760" + ] + }, + { + "id": "ssa_state_rows_and_national_row", + "family": "ssa", + "levels": [ + "state" + ], + "higher_level": "country", + "route": "not_reconciled", + "compiled": true, + "reason": "Not checked yet: whether the state rows of SSI sum to the national row of the family. No rule ties them.", + "issues": [ + "microcosm#1760" + ] + }, + { + "id": "hhs_acf_tanf_state_rows_and_national_row", + "family": "hhs_acf_tanf", + "levels": [ + "state" + ], + "higher_level": "country", + "route": "not_reconciled", + "compiled": true, + "reason": "Not checked yet: whether the state rows of TANF sum to the national row of the family. No rule ties them.", + "issues": [ + "microcosm#1760" + ] + }, + { + "id": "cms_aca_state_rows_have_no_national_row", + "family": "cms_aca", + "levels": [ + "state" + ], + "higher_level": "country", + "route": "no_higher_control", + "compiled": true, + "reason": "The compiled registry holds the ACA marketplace rows at state level only: no national row of the family binds.", + "issues": [ + "microcosm#1760" + ] + }, + { + "id": "state_income_tax_state_rows_have_no_national_row", + "family": "state_income_tax", + "levels": [ + "state" + ], + "higher_level": "country", + "route": "no_higher_control", + "compiled": true, + "reason": "The compiled registry holds the state income tax rows at state level only: no national row of the family binds.", + "issues": [ + "microcosm#1760" + ] + }, + { + "id": "acs_district_age_and_households", + "family": "census_acs", + "levels": [ + "congressional_district" + ], + "higher_level": "state", + "route": "not_in_the_fit", + "compiled": false, + "reason": "District age and household rows from ACS are not in the fit. Their state parent would come from another source: the districts from a survey, the states from the Census estimates.", + "issues": [ + "microcosm#1731" + ] + } + ] } } diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/cross_grain_declarations.py b/packages/microcosm-build/src/microcosm/build/us_runtime/cross_grain_declarations.py index 95f585a6ff..cff3e9f8f8 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/cross_grain_declarations.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/cross_grain_declarations.py @@ -9,8 +9,14 @@ registers with their reasons. The key names follow ``uk/cross_grain_declarations.json`` wherever the meaning is the same. +The file's ``inventory`` lists each US family that two geography levels +measure, with the route that ties the levels or the reason none does. +:func:`us_cross_grain_coverage_violations` checks a set of compiled specs +against it. That check is a receipt and a test of the declaration: no build +calls it and it refuses nothing. + This module reads the file and hands out typed views of it. It does no -arithmetic and reads no target; the adapter that runs the operator is +arithmetic on targets; the adapter that runs the operator is :mod:`microcosm.build.us_runtime.target_nesting`. """ @@ -18,7 +24,7 @@ import functools import json -from collections.abc import Mapping +from collections.abc import Iterable, Mapping from dataclasses import dataclass from importlib import resources as importlib_resources from typing import Any @@ -38,6 +44,16 @@ "bound_row_or_scaled_by_sibling_ratio", "sum_of_lower_rows", ) +#: Inventory routes that need a written reason. +_REASONED_ROUTES = frozenset( + { + "compile_rule", + "same_source", + "no_higher_control", + "not_reconciled", + "not_in_the_fit", + } +) @functools.lru_cache(maxsize=1) @@ -84,9 +100,181 @@ def load_us_cross_grain_declarations() -> Mapping[str, Any]: f"control kind {mechanism['control']['kind']!r}; expected one " f"of {_CONTROL_KINDS}." ) + _validate_inventory(payload) return payload +def _validate_inventory(payload: Mapping[str, Any]) -> None: + """Refuse an inventory entry that names no route, level or reason.""" + + grains = tuple(payload["grain_precedence"]) + inventory = payload["inventory"] + routes = tuple(inventory["routes"]) + seen: set[str] = set() + for entry in inventory["entries"]: + entry_id = str(entry.get("id", "")) + if not entry_id or entry_id in seen: + raise ValueError( + f"US cross-grain inventory entry id {entry_id!r} is blank or repeated." + ) + seen.add(entry_id) + levels = tuple(entry.get("levels") or ()) + higher = entry.get("higher_level") + if ( + not entry.get("family") + or not levels + or any(level not in grains for level in levels) + or higher not in grains + or any(grains.index(higher) > grains.index(level) for level in levels) + ): + raise ValueError( + f"US cross-grain inventory entry {entry_id!r} must name a " + "family, its levels and a higher level that is not below them." + ) + route = entry.get("route") + if route not in routes: + raise ValueError( + f"US cross-grain inventory entry {entry_id!r} names unknown " + f"route {route!r}; expected one of {routes}." + ) + if not isinstance(entry.get("compiled"), bool) or not entry.get("issues"): + raise ValueError( + f"US cross-grain inventory entry {entry_id!r} must say whether " + "its rows are compiled and name an issue." + ) + if route == "mechanism": + mechanism = payload["mechanisms"].get(entry.get("mechanism")) + if ( + mechanism is None + or mechanism["issue_row"] != entry.get("issue_row") + or mechanism["family"] != entry["family"] + or (mechanism["lower_grain"],) != levels + or mechanism["higher_grain"] != higher + ): + raise ValueError( + f"US cross-grain inventory entry {entry_id!r} does not " + "match the mechanism it names." + ) + elif route in _REASONED_ROUTES and not str(entry.get("reason", "")).strip(): + raise ValueError( + f"US cross-grain inventory entry {entry_id!r} has route " + f"{route!r} and no reason." + ) + if route == "compile_rule" and not (entry.get("code") and entry.get("marker")): + raise ValueError( + f"US cross-grain inventory entry {entry_id!r} must name the " + "compile rule's code and the marker it writes." + ) + + +def us_cross_grain_inventory() -> tuple[Mapping[str, Any], ...]: + """The inventory entries, in declared order.""" + + return tuple(load_us_cross_grain_declarations()["inventory"]["entries"]) + + +def _marker_matches(marker: Mapping[str, Any], metadata: Mapping[str, Any]) -> bool: + value = metadata.get(str(marker["metadata_key"])) + if value is None: + return False + if "value" in marker: + return str(value) == str(marker["value"]) + if "value_prefix" in marker: + return str(value).startswith(str(marker["value_prefix"])) + return True + + +def us_cross_grain_coverage_violations( + specs: Iterable[Any], + *, + level_key: str = "ledger_geography_level", +) -> list[dict[str, str]]: + """Every gap between a set of compiled specs and the inventory. + + ``specs`` are compiled target specs (anything with ``family`` and + ``metadata``). The top level of ``grain_precedence`` nests in nothing. A + violation is one of: + + * ``family_level_without_route``: a family has rows at a lower level and + no inventory entry names that family and level; + * ``stale_inventory_entry``: an entry says its rows are compiled, and the + specs hold none at one of its levels; + * ``compile_rule_marker_absent``: a compile rule's marker is on no row of + one of its declared levels. + + Returns the violations; an empty list means the inventory covers the + specs. The caller decides what a violation means: this function refuses + nothing. + """ + + declared = load_us_cross_grain_declarations() + top = declared["grain_precedence"][0] + compiled: dict[tuple[str, str], list[Mapping[str, Any]]] = {} + for spec in specs: + level = spec.metadata.get(level_key) + if level is None or level == top: + continue + compiled.setdefault((str(spec.family), str(level)), []).append(spec.metadata) + entries = us_cross_grain_inventory() + routed = { + (str(entry["family"]), str(level)) + for entry in entries + for level in entry["levels"] + } + violations = [ + { + "kind": "family_level_without_route", + "family": family, + "level": level, + "where": "compiled specs", + } + for family, level in sorted(set(compiled) - routed) + ] + for entry in entries: + if not entry["compiled"]: + continue + for level in entry["levels"]: + rows = compiled.get((str(entry["family"]), str(level))) + if not rows: + violations.append( + { + "kind": "stale_inventory_entry", + "family": str(entry["family"]), + "level": str(level), + "where": str(entry["id"]), + } + ) + elif entry["route"] == "compile_rule" and not any( + _marker_matches(entry["marker"], metadata) for metadata in rows + ): + violations.append( + { + "kind": "compile_rule_marker_absent", + "family": str(entry["family"]), + "level": str(level), + "where": str(entry["id"]), + } + ) + return violations + + +def us_cross_grain_coverage_receipt(specs: Iterable[Any]) -> dict[str, Any]: + """The coverage of a set of compiled specs, as a receipt. + + It records the violations and never raises on one. + """ + + specs = tuple(specs) + violations = us_cross_grain_coverage_violations(specs) + return { + "declarations": US_CROSS_GRAIN_DECLARATIONS_RESOURCE, + "checked_specs": len(specs), + "inventory_entries": len(us_cross_grain_inventory()), + "violations": violations, + "covered": not violations, + } + + def us_cross_grain_mechanism(mechanism_id: str) -> Mapping[str, Any]: """One declared mechanism; an unknown id is refused.""" diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_cross_grain_coverage.py b/packages/microcosm-build/tests/engine_free/us/test_us_cross_grain_coverage.py new file mode 100644 index 0000000000..9bcc2bd74b --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_cross_grain_coverage.py @@ -0,0 +1,255 @@ +"""The US nesting inventory covers every family that two levels measure. + +``us/cross_grain_declarations.json`` lists, under ``inventory``, each US +family that two geography levels measure, with the route that ties the levels +today or the reason none does (microcosm#1760). It records what the code +does; it decides no rule. These tests read it: + +- each entry is well formed, the eight rows of the issue each have one entry, + and each mechanism on the shared operator has one; +- ``us_cross_grain_coverage_violations`` finds a family at a lower level with + no entry, an entry whose rows are gone, and a compile rule whose marker is + on no row; +- on the pinned feed, the compiled registry has no violation. That test runs + only when ``MICROCOSM_US_CHRONICLE_FACTS`` names the pinned feed, because + ``main`` has no committed list of the US families and levels. + +The check is a test of the declaration. No build calls it and it refuses +nothing. +""" + +from __future__ import annotations + +import copy +import importlib.util +import os +import re +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from microcosm.build.us_runtime import cross_grain_declarations as declarations +from test_support.paths import paths_for + +_TEST_PATHS = paths_for("microcosm-build") + + +def _entries(): + return declarations.us_cross_grain_inventory() + + +def test_each_row_of_the_issue_has_one_entry() -> None: + rows = [entry["issue_row"] for entry in _entries() if "issue_row" in entry] + assert sorted(rows) == [1, 2, 3, 4, 5, 6, 7, 8] + routes = { + entry["issue_row"]: entry["route"] + for entry in _entries() + if "issue_row" in entry + } + # Rows 1 to 4 stay in the compile; rows 5 to 8 run on the shared operator. + assert routes == { + **dict.fromkeys((1, 2, 3, 4), "compile_rule"), + **dict.fromkeys((5, 6, 7, 8), "mechanism"), + } + + +def test_each_mechanism_has_one_entry_that_matches_it() -> None: + mechanisms = declarations.load_us_cross_grain_declarations()["mechanisms"] + named = [ + entry["mechanism"] for entry in _entries() if entry["route"] == "mechanism" + ] + assert sorted(named) == sorted(mechanisms) + for entry in _entries(): + if entry["route"] != "mechanism": + continue + mechanism = mechanisms[entry["mechanism"]] + assert entry["issue_row"] == mechanism["issue_row"] + assert entry["family"] == mechanism["family"] + assert entry["levels"] == [mechanism["lower_grain"]] + assert entry["higher_level"] == mechanism["higher_grain"] + + +def test_each_entry_gives_a_route_and_what_the_route_needs() -> None: + declared = declarations.load_us_cross_grain_declarations() + routes = declared["inventory"]["routes"] + ids = [entry["id"] for entry in _entries()] + assert len(ids) == len(set(ids)) + for entry in _entries(): + assert entry["route"] in routes + assert entry["issues"] and all( + re.fullmatch(r"microcosm#\d+", issue) for issue in entry["issues"] + ) + if entry["route"] != "mechanism": + # A route with no mechanism says why in words. + assert len(entry["reason"]) > 40 + if entry["route"] == "compile_rule": + module, _, function = entry["code"].split(",")[0].strip().rpartition(".") + source = ( + _TEST_PATHS.package / "src" / Path(*module.split(".")) + ).with_suffix(".py") + assert f"def {function}(" in source.read_text() + assert entry["marker"]["metadata_key"] + assert entry["compiled"] is True + # Every route the file lists is in use, so none is a dead name. + assert {entry["route"] for entry in _entries()} == set(routes) + + +def _tampered(change) -> dict: + payload = copy.deepcopy(dict(declarations.load_us_cross_grain_declarations())) + change(payload["inventory"]["entries"]) + return payload + + +@pytest.mark.parametrize( + ("change", "message"), + [ + (lambda entries: entries[0].update(route="merged"), "unknown route"), + (lambda entries: entries[0].update(reason=" "), "no reason"), + (lambda entries: entries[0].pop("marker"), "the marker it writes"), + (lambda entries: entries[4].update(family="usda_snap"), "does not match"), + (lambda entries: entries[1].update(id=entries[0]["id"]), "blank or repeated"), + (lambda entries: entries[0].update(levels=["tract"]), "must name a family"), + ( + lambda entries: entries[0].update(higher_level="county"), + "must name a family", + ), + (lambda entries: entries[0].update(issues=[]), "name an issue"), + ], +) +def test_a_malformed_entry_is_refused_when_the_file_loads(change, message) -> None: + with pytest.raises(ValueError, match=message): + declarations._validate_inventory(_tampered(change)) + + +def _spec(family: str, level: str, **metadata): + return SimpleNamespace( + family=family, metadata={"ledger_geography_level": level, **metadata} + ) + + +def _covered_specs() -> list: + """One spec for each compiled entry and level, with the rule's marker.""" + + specs = [_spec("irs_soi", "country"), _spec("bea", "country")] + for entry in _entries(): + if not entry["compiled"]: + continue + marker = entry.get("marker") or {} + metadata = ( + { + marker["metadata_key"]: marker.get( + "value", marker.get("value_prefix", "") + "x" + ) + } + if marker + else {} + ) + specs += [ + _spec(entry["family"], level, **metadata) for level in entry["levels"] + ] + return specs + + +def test_the_coverage_check_finds_each_kind_of_gap() -> None: + covered = _covered_specs() + assert declarations.us_cross_grain_coverage_violations(covered) == [] + + # A family at a lower level with no entry. + unrouted = [*covered, _spec("usda_wic", "state")] + assert declarations.us_cross_grain_coverage_violations(unrouted) == [ + { + "kind": "family_level_without_route", + "family": "usda_wic", + "level": "state", + "where": "compiled specs", + } + ] + # An entry whose compiled rows are gone. + without_tanf = [spec for spec in covered if spec.family != "hhs_acf_tanf"] + assert declarations.us_cross_grain_coverage_violations(without_tanf) == [ + { + "kind": "stale_inventory_entry", + "family": "hhs_acf_tanf", + "level": "state", + "where": "hhs_acf_tanf_state_rows_and_national_row", + } + ] + # A compile rule that marks no row of its declared level. + unmarked = [spec for spec in covered if "state_agi_band_share" not in spec.metadata] + assert declarations.us_cross_grain_coverage_violations(unmarked) == [ + { + "kind": "compile_rule_marker_absent", + "family": "irs_soi", + "level": "state", + "where": "soi_state_agi_bands_share_of_state_total", + } + ] + # Rows at the top level, and rows with no level, nest in nothing. + top_only = [ + *covered, + _spec("jct", "country"), + SimpleNamespace(family="x", metadata={}), + ] + assert declarations.us_cross_grain_coverage_violations(top_only) == [] + + +def test_the_coverage_check_is_a_receipt_and_refuses_nothing() -> None: + receipt = declarations.us_cross_grain_coverage_receipt( + [*_covered_specs(), _spec("usda_wic", "state")] + ) + assert receipt["covered"] is False + assert [violation["kind"] for violation in receipt["violations"]] == [ + "family_level_without_route" + ] + assert receipt["inventory_entries"] == len(_entries()) + assert declarations.us_cross_grain_coverage_receipt(_covered_specs())["covered"] + + +def test_no_build_code_calls_the_coverage_check() -> None: + """It is a test of the declaration, not a gate: nothing in a build runs it.""" + + repository = _TEST_PATHS.repository + callers = [ + path.relative_to(repository).as_posix() + for root in (repository / "tools", repository / "packages") + for path in root.rglob("*.py") + if "/tests/" not in path.as_posix() + and "us_cross_grain_coverage" in path.read_text(encoding="utf-8") + ] + assert callers == [ + "packages/microcosm-build/src/microcosm/build/us_runtime/" + "cross_grain_declarations.py" + ] + + +def test_the_pinned_feeds_compiled_registry_is_covered() -> None: + feed = os.environ.get("MICROCOSM_US_CHRONICLE_FACTS", "") + if not feed or not Path(feed).exists(): + pytest.skip("set MICROCOSM_US_CHRONICLE_FACTS to the pinned 41b2fb2 feed") + path = _TEST_PATHS.repository / "tools" / "build_us_acs_local_release.py" + spec = importlib.util.spec_from_file_location( + "build_us_acs_local_release_nesting_coverage", path + ) + tool = importlib.util.module_from_spec(spec) + assert spec.loader is not None + spec.loader.exec_module(tool) + registry, _substitutions = tool._compiled_fiscal_registry(feed) + + receipt = declarations.us_cross_grain_coverage_receipt(registry.specs) + assert receipt["violations"] == [] + assert receipt["checked_specs"] == len(registry.specs) + # The families the registry holds below the national level are the ones + # the inventory's compiled entries name: no more and no fewer. + compiled = { + (spec.family, spec.metadata["ledger_geography_level"]) + for spec in registry.specs + if spec.metadata.get("ledger_geography_level") not in (None, "country") + } + declared = { + (entry["family"], level) + for entry in _entries() + if entry["compiled"] + for level in entry["levels"] + } + assert compiled == declared From 350cd9de2ae1118e0a06e86d47baf16871a33fa3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Fri, 27 Nov 2026 12:34:39 +0000 Subject: [PATCH 08/23] Propose the US nesting rule for rulings (design page, no code) docs/us-target-nesting-rule-design.md is the design step of Stage B of microcosm#1760. It is a proposal: no code reads it and no target changes. It records the two rulings so far, the second from 27 Nov 2026 (the Historic Table 2 state row is the state parent of a district row on every surface, and a parent that it does not contain is not removed). It then proposes one rule in nine statements, shows what each family does today with the sum of its lower rows over its higher row on the pinned feed, and lists nine decisions, each with a recommendation: the level holder, national to state for the SOI families, the program families, the state population vintage, the county households, bounds and members, the ACS district rows, the parent in the loss, and one allocator, key set and receipt. docs/us-target-nesting.md points to it and notes the 27 Nov ruling. Co-Authored-By: Claude Fable 5.2 --- docs/us-target-nesting-rule-design.md | 219 ++++++++++++++++++++++++++ docs/us-target-nesting.md | 7 + 2 files changed, 226 insertions(+) create mode 100644 docs/us-target-nesting-rule-design.md diff --git a/docs/us-target-nesting-rule-design.md b/docs/us-target-nesting-rule-design.md new file mode 100644 index 0000000000..c5528d9fc3 --- /dev/null +++ b/docs/us-target-nesting-rule-design.md @@ -0,0 +1,219 @@ +# US target nesting rule: design for rulings + +**Status: a proposal. It is not in force, and no code reads this page.** It +is the design step of Stage B of microcosm#1760. Stage A, which is on this +branch, changes no target ([US target nesting](us-target-nesting.md)). + +Each number is one of two kinds: + +- **measured**: run on the pinned feed (Chronicle `41b2fb2b`), compiled at + 2024 as the release does; +- **read**: read in the code or in an issue. + +## 1. What is decided + +| Date | Ruling | Where | +|---|---|---| +| 26 Nov 2026 | Stage A uses the cross-grain operator that the UK uses. No target changes for now, so that PR #1719 keeps its behavior. | microcosm#1760 | +| 27 Nov 2026 | The Historic Table 2 state row is the state parent of a district row on every surface, for every parent that it contains. A parent that it does not contain is not removed. | [comment on #1760](https://github.com/PolicyEngine/microcosm/issues/1760#issuecomment-7217969778) | + +Everything below is open. + +## 2. The proposed rule + +Nine statements. Each decision in section 4 is one of them. + +1. **One level holds the level value of a quantity.** It is the highest + geography level at which a current source publishes a complete total of + the same concept. +2. **Every level below it holds shares.** The operator divides the parent + among the lower rows, so they sum to it. The lower source supplies the + shares only. +3. **Levels stack as a chain.** Country, then state, then district and + county. Districts and counties both divide a state. They do not nest in + each other. A lower leg takes its nearest control. +4. **The same parent on every surface.** A surface that binds a lower row + uses the parent that the rule names. *(Ruled for state to district.)* +5. **A parent that the higher source lacks is kept** from the source that + has it. Its control is then the lower source's own total, or the sum of + the lower rows. *(Ruled.)* +6. **Lower rows that do not cover the parent keep their shares of their own + file's total.** When the lower rows are not all the parts of the parent + (the 50 states and DC against a US row that also counts other areas), + each lower row takes one factor: the control over its own file's total. + The lower rows are not scaled to sum to the control. +7. **Two sources of one concept nest. Two concepts do not.** Lower rows from + another source than the parent are shares of the parent when both measure + the same concept. When they measure different concepts, both stay as + levels, and the pair is declared with a reason. +8. **Each mechanism declares its bound and its members.** A block whose + factor is out of its bound is dropped and recorded, and the parent stays. + A leg must hold exactly its declared members, or the compile refuses. A + leg with one member is a copy of its parent and does not bind. +9. **Nesting changes values, never weights.** Whether a parent and its + children both stay in the loss is a rule of the loss (microcosm#1729). + +## 3. What each family does today, and what the rule gives + +"Sum" is the sum of the lower rows over the higher row, in the compiled +registry of the pinned feed. **(measured)** + +| Family | Levels bound | Today | Sum (measured) | Under the rule | +|---|---|---|---|---| +| IRS SOI, capital gains and taxable interest | country, state, district | Rows 1 and 2: each row times one factor onto the newer national control | by construction | Statement 6. No change in values. The arithmetic moves to the operator | +| IRS SOI, the 14 families of microcosm#1243 | country (two rows), state | Two national rows for one quantity. No rule | Historic Table 2 states over the Historic Table 2 US row, 61 pairs: median 0.995. Lowest all-returns pair: 0.981 | Statement 6: the newer Table 1.x row is the control, the state rows keep their shares, and the Historic Table 2 US row stops binding | +| IRS SOI, district file | state, district | Row 4: the district file's own state row (factor 1). Row 5 (`state_cd`): the Historic Table 2 state row | district file states over its own US row: 1.000 (40 concepts) | Statements 2, 4 and 5. Ruled | +| IRS SOI, county file | state, county | Row 6: shares of the Historic Table 2 state row | not measured (the county facts are not on this machine) | Statement 2. No change | +| Census population by age | country, state | 18 age bands at each level, from one vintage. No rule | 1.0000 in each of the 18 bands | Statement 2 holds already. No rule needed | +| Ladder population (local build) | state, district, county | Totals from the 2020 ladder. Row 8 scales counties to the state | 1 by construction | Decision 4 | +| ACS households (county rung) | state, county | Row 7: the state target is the sum of the county values | 1 by construction | Decision 5 | +| SNAP | country, state | No rule | households 0.9990, benefits 0.9980 (51 states) | Decision 3 | +| Medicaid and CHIP | country, state | No rule | Medicaid 1.0038 (51 states); Medicaid with CHIP 1.0000 (50); CHIP 0.5875 (31) | Decision 3 | +| TANF | country, state | No rule | 0.9096 (29 states) | Decision 3 | +| ACA, SSI by state, state income tax | state | No national row of the same role | none | Nothing to nest | +| ACS district age and households | district | Not in the fit (microcosm#1731) | none | Decision 7 | + +CHIP has 31 state rows because a reviewed rule drops the 20 M-CHIP states. +TANF has 29 state rows in the compiled registry. + +## 4. Decisions, each with a recommendation + +### Decision 1. The level holder (statements 1 to 3) + +The level value of a quantity is held by the highest level that has a +current source with a complete total of the same concept. Lower levels hold +shares. + +**Recommended: yes.** It is the proposal of the issue, and the 27 Nov ruling +is one case of it. + +### Decision 2. National to state for the SOI families (statement 6) + +This covers rows 1 and 2 and the 14 families of microcosm#1243. + +- **(a) One factor.** Each state row is multiplied by the national control + over the US total of its own file. The states keep their shares. Returns + from other areas stay out of the states. Rows 1 and 2 do this today. +- **(b) States scaled to sum to the control.** The states then take the + returns of other areas too. At the median that is 0.5% of a quantity. The + largest gap of an all-returns concept is 2% (dividends). **(measured)** + +**Recommended: (a).** On the operator, the control of the states is a +derived control: the national control times the states' share of their +file's US total. Where a newer Table 1.x row is the control, the Historic +Table 2 US row stops binding, as it does for capital gains and taxable +interest. Each of the 14 concept matches must be verified first, as +microcosm#1243 says. + +### Decision 3. Program families: SNAP, Medicaid, CHIP, TANF + +- **(a) No scaling.** The national row and the state rows are cells of one + publication of one vintage. Declare them `same_source`, and report the sum + of the states over the national row in the nesting receipt. +- **(b) Scale the states to the national row** where all states are present + (SNAP, Medicaid). + +**Recommended: (a).** Where all states are present, the gaps are 0.1% to +0.4%. Their causes are not established here: SNAP's national row may count +areas outside the 50 states and DC, and one state's Medicaid row is from +another month. CHIP and TANF do not have all states, so scaling them would +put the missing states' mass on the present ones. + +### Decision 4. State population on one vintage (microcosm#1526, PR #1531) + +Today the national build fits the Census estimates by age for each state. +The local build fits state, district and county totals from the 2020 ladder +and no age row. + +- **(a) The current Census estimate holds the state level.** The ladder + supplies the shares of districts and counties in that state total. The + local build can then bind the state age rows too. +- **(b) The ladder keeps its own levels.** + +**Recommended: (a).** It changes the local state totals. Which vintage and +which age groups is the decision of PR #1531, not of this rule. + +### Decision 5. County households, row 7 + +- **(a) Keep.** The state target is the sum of the county values. It is the + case of statement 5: no higher source of the same concept is bound. +- **(b) Bind a state level from a current source**, and let the counties + divide it. It needs a state households fact of the same concept. Whether + the feed holds one is not checked. + +**Recommended: (a) now, and (b) when the state fact exists.** + +### Decision 6. Bounds and members (statement 8) + +- **The bound.** A mechanism between two sources declares the band around + the median factor (1.25 for district SOI today). A mechanism inside one + source declares none (ladder population, county households). + **Recommended: yes.** For county SOI, which has no bound today: add the + band as a report first, and decide to enforce it after the factors are + measured on the county facts. +- **Members.** A leg holds exactly its declared members: the district plan + of the crosswalk, the counties of the ladder. A declared combined cell + covers a county with no IRS row. An area with one district does not bind + at district level. **Recommended: keep all three, as today.** + +### Decision 7. ACS district age and household rows (microcosm#1731) + +The district rows come from a survey. The state rows come from the Census +estimates. + +- **(a) Shares of the state row**, with the band of decision 6. +- **(b) Levels.** + +**Recommended: (a) for the age rows.** The household rows follow decision 5. + +### Decision 8. The parent in the loss (statement 9) + +When a parent and all its children bind, the loss counts the parent two +times. + +- **(a) Both stay.** The weight rule by level of microcosm#1729 sets their + weights. +- **(b) The parent leaves the loss** where all its children bind. + +**Recommended: (a).** It keeps this rule about values only. + +### Decision 9. One allocator, one key set, one receipt + +At the re-pin the bytes of the registry move anyway. + +- **One allocator**, `proportional_fsum`, for every mechanism. The two + residual allocators of the county rows go. County values move in the last + bits. +- **One set of metadata keys** in place of `state_cd_*`, `state_county_*` + and `hierarchy_*`. Three readers change with it: the loss weights, the + pro-rata baselines and the reviewed limitations. +- **One receipt**: `target_nesting.json`. + +**Recommended: yes to all three, in the re-pin PR.** + +## 5. What each decision changes + +| Decision | Data | Code | Targets move | +|---|---|---|---| +| Ruled, 27 Nov | `us/cross_grain_declarations.json`, `us/fiscal_target_references.json` | Row 1 keeps district capital-gains rows as shares. The `full` surface nests its district rows | Yes, with the re-pin | +| 2 | A mechanism for national to state | A derived control. Rows 1 and 2 call the operator | The 14 families: yes. Rows 1 and 2: no | +| 3 | Inventory routes | A line in the receipt | No | +| 4 | A mechanism for the ladder under the state estimate | The local population rows | Yes | +| 5 | None now | None now | No | +| 6 | The bound of each mechanism | A report for county SOI | No | +| 7 | A mechanism for the ACS district rows | The rows of microcosm#1731 | New targets | +| 8 | None | None | No | +| 9 | Allocator names, key names | Three readers | Last bits, and key names | + +## 6. Order + +1. Rulings on section 4. +2. Chronicle PR #451 merges. Microcosm re-pins its feed. +3. One set of commits on this branch for the ruled decisions and the re-pin, + with one build. Decisions 4 and 7 can come later in their own PRs. + +## 7. Not measured + +- The county factors. The pinned county facts file is not on this machine. +- Anything on a feed after Chronicle PR #451. +- The concept match of each of the 14 families of microcosm#1243. diff --git a/docs/us-target-nesting.md b/docs/us-target-nesting.md index e08d3c236c..74626ca8a6 100644 --- a/docs/us-target-nesting.md +++ b/docs/us-target-nesting.md @@ -27,6 +27,13 @@ them: After Stage A, each decision is an edit to the declaration, and for some an allocator. It is not a new mechanism. +One point is ruled since (27 Nov 2026): the Historic Table 2 state row is the +state parent of a district row on every surface, and a parent that it does +not contain is not removed. The proposed rule for all levels, with a +recommendation for each open decision, is in +[US target nesting rule: design for rulings](us-target-nesting-rule-design.md). +No code applies it yet. + ## One operator, one declaration The US uses the cross-grain operator that the UK uses, From 17ee67085b5741a3d4d232ee7e84768d69cfae56 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Fri, 27 Nov 2026 13:08:23 +0000 Subject: [PATCH 09/23] Record the nine nesting rulings and how they are declared in the UK's constructs docs/us-target-nesting-rule-design.md: the nine decisions of the nesting rule were accepted on 27 Nov 2026 (the recommended option of each). The page now says so, and gains a section on how the rulings are declared. The principle of that section: the US declares its nesting with the constructs that the UK declares in uk/cross_grain_declarations.json, under the same key names (exact signatures, bridges, bridges with a derived control, partitions, relations, local routes, licensed empty legs, the cross_grain_* metadata keys and the pass receipt). The section maps each ruling to one of them, gives sketches, and lists the four additions that the shared tooling needs, each optional and beside the operator: bridge families, two kinds of derived control, a bound around a common factor, and a US contract derived from declared metadata fields. It also says what the US-only keys of Stage A (mechanisms, inventory) become at the re-pin. Docs only. No code applies the rulings yet; the target changes wait for the feed re-pin. Co-Authored-By: Claude Fable 5.2 --- docs/us-target-nesting-rule-design.md | 187 ++++++++++++++++++++++++-- docs/us-target-nesting.md | 4 +- 2 files changed, 177 insertions(+), 14 deletions(-) diff --git a/docs/us-target-nesting-rule-design.md b/docs/us-target-nesting-rule-design.md index c5528d9fc3..68200cd00b 100644 --- a/docs/us-target-nesting-rule-design.md +++ b/docs/us-target-nesting-rule-design.md @@ -1,8 +1,11 @@ -# US target nesting rule: design for rulings +# US target nesting rule: design and rulings -**Status: a proposal. It is not in force, and no code reads this page.** It -is the design step of Stage B of microcosm#1760. Stage A, which is on this -branch, changes no target ([US target nesting](us-target-nesting.md)). +**Status: the rule is ruled, and no code applies it yet.** The nine decisions +of section 4 were accepted on 27 Nov 2026. Section 5, how the rulings are +declared, is a proposal. This page is the design step of Stage B of +microcosm#1760. Stage A, which is on this branch, changes no target +([US target nesting](us-target-nesting.md)). The target changes wait for the +feed re-pin after PolicyEngine/chronicle#451. Each number is one of two kinds: @@ -16,10 +19,10 @@ Each number is one of two kinds: |---|---|---| | 26 Nov 2026 | Stage A uses the cross-grain operator that the UK uses. No target changes for now, so that PR #1719 keeps its behavior. | microcosm#1760 | | 27 Nov 2026 | The Historic Table 2 state row is the state parent of a district row on every surface, for every parent that it contains. A parent that it does not contain is not removed. | [comment on #1760](https://github.com/PolicyEngine/microcosm/issues/1760#issuecomment-7217969778) | +| 27 Nov 2026 | The nine recommendations of section 4 are accepted. | This page | +| 27 Nov 2026 | The way the rulings are declared must follow how the UK declares its own (section 5). | This page | -Everything below is open. - -## 2. The proposed rule +## 2. The rule Nine statements. Each decision in section 4 is one of them. @@ -76,7 +79,10 @@ registry of the pinned feed. **(measured)** CHIP has 31 state rows because a reviewed rule drops the 20 M-CHIP states. TANF has 29 state rows in the compiled registry. -## 4. Decisions, each with a recommendation +## 4. The nine decisions + +**Ruled, 27 Nov 2026: the recommended option of each decision is accepted.** +The other options stay on the page as the record of what was considered. ### Decision 1. The level holder (statements 1 to 3) @@ -191,7 +197,164 @@ At the re-pin the bytes of the registry move anyway. **Recommended: yes to all three, in the re-pin PR.** -## 5. What each decision changes +## 5. How the rulings are declared + +**The principle.** The US declares its nesting with the constructs that the +UK declares in `uk/cross_grain_declarations.json`, under the same key names. +A new key is added only where the UK has no construct for the need. It then +goes into the shared tooling, with a default that leaves the UK as it is. + +### 5.1 The constructs that the UK has + +Read in `uk/cross_grain_declarations.json` and in the UK runtime. + +| Construct | What it declares | The UK has | +|---|---|---| +| `signature_fields`, and the measurement of each target | Two targets with the same measurement at two levels are one quantity. Nothing else is declared | The regional capital-gains cells under the UK total | +| `bridges` | **The bridge between concepts.** Two targets with different measurements that measure one quantity. Fields: `bridge_id`, `concept`, `higher_target_ids`, `lower_side`, `per_geography`, `max_factor_shift`, `reason` | 11. One example: the GB Universal Credit caseload over the area cells, with a bound of 0.02 | +| Bridges with a derived control (`fanout_sum_bridges`, `sum_bridges`, `band_bridges`) | A control that no source publishes as one row. Code computes the control row and puts it on the surface under its own id. A bridge ties it to the lower rows. Bounds: `max_factor_shift`, `min_factor_shift`, `max_index_shift` | 30 | +| `partitions` | Members and their parent at one geography: `exhaustive` or `share_of_parent` | 3 | +| `relations` | A pair that is not reconciled, with a reason: `subset` (the part is at most the whole) or `independent` | 36 | +| `local_routes` | A lower target with no higher control, with a reason | 8 | +| Licensed empty legs | A leg that may hold no lower row of a target | From the membership file | +| Metadata and receipt | `cross_grain_value_before`, `cross_grain_factor`, `cross_grain_control` on each reconciled row, and one pass receipt | Every build | + +Two more facts about the UK: + +- It runs the operator one time on one joint surface of all the bound + target cells. +- A static check refuses a pair, or a local target, that no construct + covers. + +### 5.2 Each ruling in those constructs + +| Ruling | Construct | Note | +|---|---|---| +| The level holder and the chain (decision 1) | `grain_precedence`, `control_grains` | In the US file already | +| One source at two levels: the ladder from state to county, the Census age bands | Exact signature | Nothing to declare | +| State to district SOI (ruled 27 Nov), and state to county SOI. The parent and the children come from two sources | `bridges` | One bridge for each measure, written as one bridge family (5.4). The measure ids that differ between the two files are named in the family | +| National to state SOI: rows 1 and 2, and the 14 families (decision 2) | A bridge with a derived control | The control is the national value times the states' share of their own file's US total. The `reason` of each bridge holds the verified concept match | +| Capital gains: Form 1040 line 7 against the concept of the model | The `concept` and the `reason` of that bridge | Python constants hold it today | +| County households (decision 5) | A bridge with a derived control: the sum of the lower rows | The UK's `sum_bridges` is the same idea | +| SNAP, Medicaid, CHIP, TANF (decision 3) | `relations`, `subset`: the state rows are part of the national row | The UK tests that a part is at most its whole. See 5.5 for Medicaid | +| ACA, SSI by state, state income tax | `local_routes`, `no_higher_control` | | +| State AGI bands (row 3) | `partitions`, `share_of_parent` | When row 3 moves to the operator | +| At-large areas and excluded states (decision 6) | Licensed empty legs | The operator records them. The adapter does not drop them on its own | +| The bound of a bridge (decision 6) | `max_factor_shift` and `min_factor_shift`, around a common factor | One new optional key (5.4). The band of 1.25 is a shift from -0.20 to +0.25 around the median factor | +| One set of metadata keys (decision 9) | The UK's `cross_grain_*` keys | No new US names | +| One receipt (decision 9) | The operator's pass receipt | | +| One allocator (decision 9) | `allocator` on the rule: `proportional_fsum` | | + +### 5.3 Sketches + +The target ids are examples. A US target id is the record set and the +measure of a compiled row, as a UK contract target is one target with many +cells. + +A bridge between two concepts, as the operator takes it (the UK's fields): + +```json +{ + "bridge_id": "historic_table_2_state_vs_district_file:qbi_amount", + "concept": "irs_soi.qualified_business_income_deduction", + "higher_target_ids": ["irs_soi.historic_table_2.state_broad_totals:qbi_amount"], + "lower_side": "contract:irs_soi.congressional_district_2022.all_returns:qualified_business_income_deduction_amount", + "reason": "Both read IRS column A04475. Historic Table 2 holds the complete state total (IRS district data guide)." +} +``` + +The bridge family that makes one such bridge for each measure: + +```json +{ + "bridge_family_id": "historic_table_2_state_vs_district_file", + "higher": {"grain": "state", "record_set_spec_prefix": "irs_soi.historic_table_2."}, + "lower": {"grain": "congressional_district", "record_set_spec_prefix": "irs_soi.congressional_district_"}, + "match_on": ["source_measure_id", "agi_lower_bound", "agi_upper_bound", "filing_status"], + "measure_id_map": {"qbi_amount": "qualified_business_income_deduction_amount"}, + "common_factor": "median_across_legs", + "max_factor_shift": 0.25, + "min_factor_shift": -0.2, + "on_out_of_bound": "unbind_lower_rows", + "reason": "The district file gives each district's share of its state. Historic Table 2 gives the complete state total." +} +``` + +A bridge with a derived control, for national to state: + +```json +{ + "bridge_id": "table_1_4_vs_historic_table_2_states:taxable_pension_income_amount", + "higher_target_id": "irs_soi.table_1_4:taxable_pension_income_amount", + "lower_target_id": "irs_soi.historic_table_2.state_broad_totals:taxable_pension_income_amount", + "coverage_total_target_id": "irs_soi.historic_table_2.us:taxable_pension_income_amount", + "reason": "The same Form 1040 line in both tables (microcosm#1243). The states keep their shares of the Historic Table 2 US total." +} +``` + +A pair that is not reconciled: + +```json +{ + "targets": ["usda_snap.state:total_benefits", "usda_snap.national:total_benefits"], + "relation": "subset", + "part": "usda_snap.state:total_benefits", + "whole": "usda_snap.national:total_benefits", + "reason": "Cells of one publication. The national row may count areas outside the 50 states and DC." +} +``` + +### 5.4 What the shared tooling needs + +Each addition is optional, has no country in it, and has a default that +leaves the UK as it is. + +1. **Bridge families.** One declared entry that expands to one bridge for + each measure. The UK wrote its 24 band bridges one by one; a family is + the same thing as data. +2. **Two kinds of derived control** in `microcosm.build.cross_grain_controls`: + the sum of the lower rows (it exists since Stage A) and the coverage + control of statement 6. +3. **A bound around a common factor.** The UK bounds a factor around one, or + around a declared index. The US needs the bound around the median factor + across the legs of a bridge, because two files of two vintages differ by + a common gap. It also needs a second answer when a leg is out of bound: + the UK refuses the build, and the US unbinds the lower rows of that leg + and records it. +4. **A US contract.** The UK has a written contract with a measurement for + each target. The US rows come from the feed, so the adapter derives the + target id and the measurement of each compiled row from declared metadata + fields. + +**Where they go: beside the operator, not in it.** The four additions fit in +`cross_grain_controls` and in the US adapter. `cross_grain.py` then needs no +other edit, so the UK graph re-keys one time for this branch (the allocator +of Stage A) and not again. + +### 5.5 What changes in the Stage A files + +Stage A kept the old bytes. For that it runs the operator one block at a +time, on a surface that the adapter builds, and it holds the US choices +under two keys that the UK does not have (`mechanisms` and `inventory`). At +the re-pin: + +- `mechanisms` becomes `bridges` (as families) and the lists of bridges with + a derived control. +- The routes of `inventory` become `relations` and `local_routes`. The + entries of rows 1 to 4 stay until those rows move to the operator. +- The four passes become one pass on one joint surface, as in the UK. +- The coverage test reads the same keys as the UK check. One shared check + for both countries belongs with microcosm#1759. + +Two points to settle when the code is written: + +- **Medicaid.** The state rows sum to 1.0038 of the national row, so a + `subset` relation needs a declared allowance, or the pair is `independent`. +- **The surface rows that bind nothing.** The UK puts cells that do not bind + on the surface so that they take their share of a control. The US has the + same need for a state row that a surface leaves out of its loss. + +## 6. What each decision changes | Decision | Data | Code | Targets move | |---|---|---|---| @@ -205,14 +368,14 @@ At the re-pin the bytes of the registry move anyway. | 8 | None | None | No | | 9 | Allocator names, key names | Three readers | Last bits, and key names | -## 6. Order +## 7. Order -1. Rulings on section 4. +1. Agreement on section 5, the way the rulings are declared. 2. Chronicle PR #451 merges. Microcosm re-pins its feed. 3. One set of commits on this branch for the ruled decisions and the re-pin, with one build. Decisions 4 and 7 can come later in their own PRs. -## 7. Not measured +## 8. Not measured - The county factors. The pinned county facts file is not on this machine. - Anything on a feed after Chronicle PR #451. diff --git a/docs/us-target-nesting.md b/docs/us-target-nesting.md index 74626ca8a6..c8981578ef 100644 --- a/docs/us-target-nesting.md +++ b/docs/us-target-nesting.md @@ -31,8 +31,8 @@ One point is ruled since (27 Nov 2026): the Historic Table 2 state row is the state parent of a district row on every surface, and a parent that it does not contain is not removed. The proposed rule for all levels, with a recommendation for each open decision, is in -[US target nesting rule: design for rulings](us-target-nesting-rule-design.md). -No code applies it yet. +[US target nesting rule: design and rulings](us-target-nesting-rule-design.md). +Its nine decisions were accepted on 27 Nov 2026. No code applies them yet. ## One operator, one declaration From 035881105e2fae327eccb100405c201b78abdcb6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Fri, 27 Nov 2026 13:19:26 +0000 Subject: [PATCH 10/23] Restate how the nesting rulings are declared as one general model Ruled on 27 Nov 2026: clean country-agnostic code comes first, the simpler and the more general the better, with no construct for one country only, and a UK re-key is accepted for it. So section 5 of docs/us-target-nesting-rule-design.md no longer adds US parts beside the operator. It states one model for every country in the shared operator, in six things: the measurement, the bridge (by id or by a selector), the derived control (sum or scaled), the bound (limits around a reference, and refuse or unbind), the members of a leg, and the pairs that are not reconciled. It lists what goes: the allocator hook and the three allocators at the re-pin, the US-only keys and checks, the sibling-ratio bridge, the US metadata keys and receipts, and the four separate passes. It maps each ruling to the model and gives three steps. Docs only. Co-Authored-By: Claude Fable 5.2 --- docs/us-target-nesting-rule-design.md | 221 ++++++++++++-------------- 1 file changed, 103 insertions(+), 118 deletions(-) diff --git a/docs/us-target-nesting-rule-design.md b/docs/us-target-nesting-rule-design.md index 68200cd00b..e2ed5845e3 100644 --- a/docs/us-target-nesting-rule-design.md +++ b/docs/us-target-nesting-rule-design.md @@ -1,8 +1,9 @@ # US target nesting rule: design and rulings **Status: the rule is ruled, and no code applies it yet.** The nine decisions -of section 4 were accepted on 27 Nov 2026. Section 5, how the rulings are -declared, is a proposal. This page is the design step of Stage B of +of section 4 were accepted on 27 Nov 2026. Section 5 says how the rulings +are declared: its principle is ruled, and its model is the design that +follows from it. This page is the design step of Stage B of microcosm#1760. Stage A, which is on this branch, changes no target ([US target nesting](us-target-nesting.md)). The target changes wait for the feed re-pin after PolicyEngine/chronicle#451. @@ -21,6 +22,7 @@ Each number is one of two kinds: | 27 Nov 2026 | The Historic Table 2 state row is the state parent of a district row on every surface, for every parent that it contains. A parent that it does not contain is not removed. | [comment on #1760](https://github.com/PolicyEngine/microcosm/issues/1760#issuecomment-7217969778) | | 27 Nov 2026 | The nine recommendations of section 4 are accepted. | This page | | 27 Nov 2026 | The way the rulings are declared must follow how the UK declares its own (section 5). | This page | +| 27 Nov 2026 | Clean country-agnostic code comes first: the simpler and the more general, the better, with no exceptions for one country. A UK re-key is accepted for it. | This page, section 5 | ## 2. The rule @@ -197,102 +199,106 @@ At the re-pin the bytes of the registry move anyway. **Recommended: yes to all three, in the re-pin PR.** -## 5. How the rulings are declared +## 5. How the rulings are declared: one general model -**The principle.** The US declares its nesting with the constructs that the -UK declares in `uk/cross_grain_declarations.json`, under the same key names. -A new key is added only where the UK has no construct for the need. It then -goes into the shared tooling, with a default that leaves the UK as it is. +**The principle (ruled 27 Nov 2026).** Clean country-agnostic code comes +first. The simpler and the more general, the better. No construct exists for +one country only. The UK graph may re-key for it: its nodes compute again, +with the same outputs. -### 5.1 The constructs that the UK has +So this section does not add US parts beside the operator. It states one +model for every country, in the shared operator, and it lists what goes. -Read in `uk/cross_grain_declarations.json` and in the UK runtime. +### 5.1 The model -| Construct | What it declares | The UK has | -|---|---|---| -| `signature_fields`, and the measurement of each target | Two targets with the same measurement at two levels are one quantity. Nothing else is declared | The regional capital-gains cells under the UK total | -| `bridges` | **The bridge between concepts.** Two targets with different measurements that measure one quantity. Fields: `bridge_id`, `concept`, `higher_target_ids`, `lower_side`, `per_geography`, `max_factor_shift`, `reason` | 11. One example: the GB Universal Credit caseload over the area cells, with a bound of 0.02 | -| Bridges with a derived control (`fanout_sum_bridges`, `sum_bridges`, `band_bridges`) | A control that no source publishes as one row. Code computes the control row and puts it on the surface under its own id. A bridge ties it to the lower rows. Bounds: `max_factor_shift`, `min_factor_shift`, `max_index_shift` | 30 | -| `partitions` | Members and their parent at one geography: `exhaustive` or `share_of_parent` | 3 | -| `relations` | A pair that is not reconciled, with a reason: `subset` (the part is at most the whole) or `independent` | 36 | -| `local_routes` | A lower target with no higher control, with a reason | 8 | -| Licensed empty legs | A leg that may hold no lower row of a target | From the membership file | -| Metadata and receipt | `cross_grain_value_before`, `cross_grain_factor`, `cross_grain_control` on each reconciled row, and one pass receipt | Every build | - -Two more facts about the UK: - -- It runs the operator one time on one joint surface of all the bound - target cells. -- A static check refuses a pair, or a local target, that no construct - covers. - -### 5.2 Each ruling in those constructs +Six things. The first, the second and the last are the UK's constructs as +they are. The other three make general what each country does in its own +code today. -| Ruling | Construct | Note | -|---|---|---| -| The level holder and the chain (decision 1) | `grain_precedence`, `control_grains` | In the US file already | -| One source at two levels: the ladder from state to county, the Census age bands | Exact signature | Nothing to declare | -| State to district SOI (ruled 27 Nov), and state to county SOI. The parent and the children come from two sources | `bridges` | One bridge for each measure, written as one bridge family (5.4). The measure ids that differ between the two files are named in the family | -| National to state SOI: rows 1 and 2, and the 14 families (decision 2) | A bridge with a derived control | The control is the national value times the states' share of their own file's US total. The `reason` of each bridge holds the verified concept match | -| Capital gains: Form 1040 line 7 against the concept of the model | The `concept` and the `reason` of that bridge | Python constants hold it today | -| County households (decision 5) | A bridge with a derived control: the sum of the lower rows | The UK's `sum_bridges` is the same idea | -| SNAP, Medicaid, CHIP, TANF (decision 3) | `relations`, `subset`: the state rows are part of the national row | The UK tests that a part is at most its whole. See 5.5 for Medicaid | -| ACA, SSI by state, state income tax | `local_routes`, `no_higher_control` | | -| State AGI bands (row 3) | `partitions`, `share_of_parent` | When row 3 moves to the operator | -| At-large areas and excluded states (decision 6) | Licensed empty legs | The operator records them. The adapter does not drop them on its own | -| The bound of a bridge (decision 6) | `max_factor_shift` and `min_factor_shift`, around a common factor | One new optional key (5.4). The band of 1.25 is a shift from -0.20 to +0.25 around the median factor | -| One set of metadata keys (decision 9) | The UK's `cross_grain_*` keys | No new US names | -| One receipt (decision 9) | The operator's pass receipt | | -| One allocator (decision 9) | `allocator` on the rule: `proportional_fsum` | | - -### 5.3 Sketches +| # | Thing | What it is | Today | +|---|---|---|---| +| 1 | **Measurement** | Each target has a measurement. Two targets with the same measurement at two levels are one quantity. Nothing else is declared | UK: yes. US: Stage A makes one for each block | +| 2 | **Bridge** | The bridge between concepts: two targets with different measurements that measure one quantity, with a `reason`. A bridge names its sides by id, or by a selector that makes one bridge for each measure | UK: `bridges`, by id. Its 24 band bridges are written one by one | +| 3 | **Derived control** | A control that no source publishes as one row. Two kinds: `sum` (of declared rows) and `scaled` (a value times a numerator over a denominator) | UK: three kinds in UK code (`fanout_sum_bridges`, `sum_bridges`, `band_bridges`), all sums. US: three helpers | +| 4 | **Bound** | Limits on the factor of a bridge (`max_factor_shift`, `min_factor_shift`), around a reference: one, or the median across the legs of the bridge. And the action out of bound: `refuse` or `unbind` the lower rows of that leg | UK: around one, refuse, in the operator. US: around the median, unbind, in US code | +| 5 | **Members** | The members that each leg must hold. A member can stand for two geographies. A leg can be licensed empty | UK: a membership file and licensed empty legs. US: three checks in US code | +| 6 | **Not reconciled** | `relations` (`subset`, `independent`) and `local_routes`, each with a reason | UK: yes. US: the `inventory` routes of Stage A | + +Partitions at one geography stay as they are. The operator runs one time on +one joint surface of all the bound rows, and it writes one receipt and the +`cross_grain_*` metadata keys. + +### 5.2 What goes + +| What | Why it goes | +|---|---| +| The allocator hook and the three allocators | Every country uses the operator's one rule: the row times the control over the sum of the rows. Stage A needs the allocators only to prove the move with the old bytes. They go at the re-pin. District and county values then move in the last bits. This narrows decision 9 from one allocator to none | +| The US keys `mechanisms` and `inventory` | The US file has the UK's keys only | +| The US checks before the operator (factor band, completeness, self-consistency) | They are things 4 and 5 of the model | +| The sibling-ratio bridge | After the re-pin, Historic Table 2 holds the six parents | +| The US metadata keys (`state_cd_*`, `state_county_*`) and the two US receipts | The `cross_grain_*` keys and the pass receipt | +| Four passes in four tool functions | One pass | +| Later, in the UK: `fanout_sum_bridges`, `sum_bridges`, `band_bridges` as three kinds | Each is a derived control of the kind `sum`. `max_index_shift` is a bound around a declared reference. This is a consolidation of its own, not part of this branch | + +One option is not taken: an exactly rounded sum as the operator's one rule. +It does not depend on the order of the rows, but it would change UK values +in the last bits. A re-key is accepted; a change of UK values is not asked +for here. + +### 5.3 Each ruling in the model + +| Ruling | In the model | +|---|---| +| The level holder and the chain (decision 1) | `grain_precedence`, `control_grains` | +| One source at two levels: the ladder, the Census age bands | Thing 1. Nothing to declare | +| State to district SOI (ruled 27 Nov) and state to county SOI | Thing 2: one bridge selector for each, from the Historic Table 2 state rows to the district rows or the county rows. The measure ids that differ between the two files are named in it | +| National to state SOI: rows 1 and 2 and the 14 families (decision 2) | Things 2 and 3: a bridge whose control is `scaled`: the national value, times the sum of the state rows, over the US total of the states' own file. The `reason` holds the verified concept match | +| County households (decision 5) | Things 2 and 3: a bridge whose control is the `sum` of the county rows | +| The band of 1.25 (decision 6) | Thing 4: `max_factor_shift` 0.25 and `min_factor_shift` -0.20, around the median across the legs, with `unbind` | +| District plans, the combined cell, at-large areas (decision 6) | Thing 5 | +| SNAP, Medicaid, CHIP, TANF (decision 3) | Thing 6: `relations`, `subset` | +| ACA, SSI by state, state income tax | Thing 6: `local_routes` | +| State AGI bands (row 3) | A partition, `share_of_parent`, when row 3 moves | +| One key set, one receipt (decision 9) | The operator's own | + +### 5.4 Sketches The target ids are examples. A US target id is the record set and the measure of a compiled row, as a UK contract target is one target with many -cells. +cells. The US has no written contract, so the measurement of a row comes +from declared metadata fields. -A bridge between two concepts, as the operator takes it (the UK's fields): +A bridge selector, with its bound: ```json { - "bridge_id": "historic_table_2_state_vs_district_file:qbi_amount", - "concept": "irs_soi.qualified_business_income_deduction", - "higher_target_ids": ["irs_soi.historic_table_2.state_broad_totals:qbi_amount"], - "lower_side": "contract:irs_soi.congressional_district_2022.all_returns:qualified_business_income_deduction_amount", - "reason": "Both read IRS column A04475. Historic Table 2 holds the complete state total (IRS district data guide)." -} -``` - -The bridge family that makes one such bridge for each measure: - -```json -{ - "bridge_family_id": "historic_table_2_state_vs_district_file", + "bridge_id": "historic_table_2_state_vs_district_file", "higher": {"grain": "state", "record_set_spec_prefix": "irs_soi.historic_table_2."}, "lower": {"grain": "congressional_district", "record_set_spec_prefix": "irs_soi.congressional_district_"}, - "match_on": ["source_measure_id", "agi_lower_bound", "agi_upper_bound", "filing_status"], - "measure_id_map": {"qbi_amount": "qualified_business_income_deduction_amount"}, - "common_factor": "median_across_legs", - "max_factor_shift": 0.25, - "min_factor_shift": -0.2, - "on_out_of_bound": "unbind_lower_rows", - "reason": "The district file gives each district's share of its state. Historic Table 2 gives the complete state total." + "pair_on": ["source_measure_id", "agi_lower_bound", "agi_upper_bound", "filing_status"], + "paired_ids": {"qbi_amount": "qualified_business_income_deduction_amount"}, + "bound": {"max_factor_shift": 0.25, "min_factor_shift": -0.2, "around": "median_across_legs", "out_of_bound": "unbind"}, + "reason": "The district file gives each district's share of its state. Historic Table 2 gives the complete state total (IRS district data guide)." } ``` -A bridge with a derived control, for national to state: +A bridge with a derived control of the kind `scaled`: ```json { "bridge_id": "table_1_4_vs_historic_table_2_states:taxable_pension_income_amount", - "higher_target_id": "irs_soi.table_1_4:taxable_pension_income_amount", - "lower_target_id": "irs_soi.historic_table_2.state_broad_totals:taxable_pension_income_amount", - "coverage_total_target_id": "irs_soi.historic_table_2.us:taxable_pension_income_amount", + "control": { + "derive": "scaled", + "value": "irs_soi.table_1_4:taxable_pension_income_amount", + "numerator": {"sum_of": "irs_soi.historic_table_2.state_broad_totals:taxable_pension_income_amount"}, + "denominator": "irs_soi.historic_table_2.us:taxable_pension_income_amount" + }, + "lower_side": "irs_soi.historic_table_2.state_broad_totals:taxable_pension_income_amount", "reason": "The same Form 1040 line in both tables (microcosm#1243). The states keep their shares of the Historic Table 2 US total." } ``` -A pair that is not reconciled: +A pair that is not reconciled, in the UK's own shape: ```json { @@ -304,55 +310,34 @@ A pair that is not reconciled: } ``` -### 5.4 What the shared tooling needs - -Each addition is optional, has no country in it, and has a default that -leaves the UK as it is. - -1. **Bridge families.** One declared entry that expands to one bridge for - each measure. The UK wrote its 24 band bridges one by one; a family is - the same thing as data. -2. **Two kinds of derived control** in `microcosm.build.cross_grain_controls`: - the sum of the lower rows (it exists since Stage A) and the coverage - control of statement 6. -3. **A bound around a common factor.** The UK bounds a factor around one, or - around a declared index. The US needs the bound around the median factor - across the legs of a bridge, because two files of two vintages differ by - a common gap. It also needs a second answer when a leg is out of bound: - the UK refuses the build, and the US unbinds the lower rows of that leg - and records it. -4. **A US contract.** The UK has a written contract with a measurement for - each target. The US rows come from the feed, so the adapter derives the - target id and the measurement of each compiled row from declared metadata - fields. - -**Where they go: beside the operator, not in it.** The four additions fit in -`cross_grain_controls` and in the US adapter. `cross_grain.py` then needs no -other edit, so the UK graph re-keys one time for this branch (the allocator -of Stage A) and not again. - -### 5.5 What changes in the Stage A files - -Stage A kept the old bytes. For that it runs the operator one block at a -time, on a surface that the adapter builds, and it holds the US choices -under two keys that the UK does not have (`mechanisms` and `inventory`). At -the re-pin: - -- `mechanisms` becomes `bridges` (as families) and the lists of bridges with - a derived control. -- The routes of `inventory` become `relations` and `local_routes`. The - entries of rows 1 to 4 stay until those rows move to the operator. -- The four passes become one pass on one joint surface, as in the UK. -- The coverage test reads the same keys as the UK check. One shared check - for both countries belongs with microcosm#1759. +### 5.5 Steps + +Each step is one or more ordered commits on this branch. + +1. **The model in the shared operator.** Derived controls, the reference and + the action of a bound, members, and bridge selectors. The UK declares + none of the new options. A test holds the UK outputs to the operator + before the change, bit for bit. The UK graph re-keys. +2. **The US on the model.** One US file in the UK's key names, and one pass + on one joint surface. **The target values stay as Stage A left them. The + metadata keys and the receipts change**, so the pinned bytes of the US + registry move. The readers of the old keys move with them: the loss + weights, the hold-outs and their pro-rata baselines, the county reports. +3. **After Chronicle PR #451: the re-pin and the ruled target changes.** The + allocators go here. + +Step 2 meets PR #1755 in two places: its pin test holds the registry bytes, +and its hold-out declaration reads the old key +(`state_cd_parent_target_name`). The PR that merges second takes the other's +change. Two points to settle when the code is written: - **Medicaid.** The state rows sum to 1.0038 of the national row, so a `subset` relation needs a declared allowance, or the pair is `independent`. -- **The surface rows that bind nothing.** The UK puts cells that do not bind - on the surface so that they take their share of a control. The US has the - same need for a state row that a surface leaves out of its loss. +- **Rows that bind nothing.** The UK puts cells that do not bind on the + surface, so that they take their share of a control. The US has the same + need for a state row that a surface leaves out of its loss. ## 6. What each decision changes @@ -370,7 +355,7 @@ Two points to settle when the code is written: ## 7. Order -1. Agreement on section 5, the way the rulings are declared. +1. Steps 1 and 2 of section 5.5. They change no target value. 2. Chronicle PR #451 merges. Microcosm re-pins its feed. 3. One set of commits on this branch for the ruled decisions and the re-pin, with one build. Decisions 4 and 7 can come later in their own PRs. From 947978c4650c1fc305645fe1a9e07f2ab9714ff5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Fri, 27 Nov 2026 13:35:41 +0000 Subject: [PATCH 11/23] Make the bound, the members and the bridge selector general in the operator Three things that each country did in its own code are now parts of the shared cross-grain operator (microcosm#1760, design section 5), each off by default: - The bound of a bridge. CrossGrainBridge gains min_factor_shift (a one-sided bound), shift_around ("one", or "median" for the median factor across the legs of the bridge, which takes out a gap that every leg shares) and out_of_bound ("refuse", or "unbind": the leg's lower rows stay as given and the receipt names them, so the caller takes them off its surface). The US band of 1.25 around the median is a shift from -0.20 to +0.25 around "median" with "unbind". - The members of a leg. apply_cross_grain_reconciliation takes expected_members (lower target -> leg -> geographies) and refuses a leg that holds other rows than those. A leg with no row stays with the empty-leg licences. - The bridge selector. CrossGrainBridgeSelector and expand_bridge_selectors make one bridge for each pair of targets from one declared entry, and name the lower targets that no higher target pairs with. The UK declares none of these. Its outputs are the same: the bit-for-bit test still holds the default path to the operator at e29843dc7 on 400 seeded surfaces (values, receipts, refusal texts), and a receipt gains the unbound_legs key only when a bridge of its rule unbinds. The UK graph hashes this file, so the UK target nodes and the nodes after them compute again. Proof: test_cross_grain_model.py (20 tests); the pinned list of changed definitions in test_cross_grain_allocator.py; the operator tests and the 17 UK test files that use the operator pass unchanged (787 passed, 7 skipped). Co-Authored-By: Claude Fable 5.2 --- .../src/microcosm/build/cross_grain.py | 358 ++++++++++++++++- .../shared/test_cross_grain_allocator.py | 29 +- .../shared/test_cross_grain_model.py | 377 ++++++++++++++++++ 3 files changed, 755 insertions(+), 9 deletions(-) create mode 100644 packages/microcosm-build/tests/engine_free/shared/test_cross_grain_model.py diff --git a/packages/microcosm-build/src/microcosm/build/cross_grain.py b/packages/microcosm-build/src/microcosm/build/cross_grain.py index 674887d59c..27dd371fb0 100644 --- a/packages/microcosm-build/src/microcosm/build/cross_grain.py +++ b/packages/microcosm-build/src/microcosm/build/cross_grain.py @@ -52,6 +52,16 @@ class CrossGrainBridge: signature group putting one leg's authorities on its constituencies) rescales them by whatever factor it needs. The bound must lie in (0, 1): at one or more it would accept every factor below one. + + Three more fields shape the bound, and each default is the bound above. + ``min_factor_shift`` is the lowest signed shift a factor may take, where + a gap is known to run one way; without it the bound is symmetric. + ``shift_around`` names what the shift is measured from: ``"one"``, or + ``"median"`` for the median factor across the legs of the bridge, which + takes out a gap that every leg shares (two sources of two vintages). + ``out_of_bound`` says what an out-of-bound leg does: ``"refuse"`` stops + the pass; ``"unbind"`` leaves the leg's lower rows as they are and + records them, so that the caller takes them off its surface. """ bridge_id: str @@ -60,6 +70,114 @@ class CrossGrainBridge: lower_side: str per_geography: bool = False max_factor_shift: float | None = None + min_factor_shift: float | None = None + shift_around: str = "one" + out_of_bound: str = "refuse" + + +SHIFT_REFERENCES = ("one", "median") +OUT_OF_BOUND_ACTIONS = ("refuse", "unbind") + + +@dataclass(frozen=True) +class CrossGrainBridgeSelector: + """One declared entry that makes one bridge for each pair of targets. + + Two sources that publish the same measures at two levels need one bridge + for each measure. A selector states the pairing once: ``higher`` and + ``lower`` choose the targets of each side by their attributes (a value, + or ``{"prefix": ...}``), and ``pair_on`` names the attributes on which a + higher and a lower target must agree. ``paired_values`` maps a higher + target's value of an attribute to the lower side's value, where the two + sources name one thing differently. The bound fields are those of + :class:`CrossGrainBridge`, and every bridge of the selector takes them. + """ + + bridge_id: str + concept: str + higher: Mapping[str, Any] + lower: Mapping[str, Any] + pair_on: tuple[str, ...] + paired_values: Mapping[str, Mapping[str, str]] | None = None + max_factor_shift: float | None = None + min_factor_shift: float | None = None + shift_around: str = "one" + out_of_bound: str = "refuse" + + +def expand_bridge_selectors( + selectors: Iterable[CrossGrainBridgeSelector], + targets: Mapping[str, Mapping[str, Any]], +) -> tuple[tuple[CrossGrainBridge, ...], dict[str, tuple[str, ...]]]: + """The bridges that the selectors make over ``targets``. + + ``targets`` maps a target id to its attributes. Returns the bridges, each + named ``:``, and for each selector the lower + targets that no higher target pairs with: the caller refuses them or + declares why they have no control. Two higher targets that pair with one + lower target are refused, since a lower target has one control. + """ + + bridges: list[CrossGrainBridge] = [] + unpaired: dict[str, tuple[str, ...]] = {} + for selector in selectors: + if not selector.pair_on: + raise ValueError( + f"cross-grain bridge selector {selector.bridge_id!r} must name " + "the attributes its two sides are paired on." + ) + mapped = selector.paired_values or {} + higher_by_key: dict[tuple[Any, ...], str] = {} + for target_id, attributes in targets.items(): + if not _selects(selector.higher, attributes): + continue + key = tuple( + mapped.get(name, {}).get(attributes.get(name), attributes.get(name)) + for name in selector.pair_on + ) + if key in higher_by_key: + raise ValueError( + f"cross-grain bridge selector {selector.bridge_id!r} pairs " + f"two higher targets on {key!r}: {higher_by_key[key]!r} and " + f"{target_id!r}." + ) + higher_by_key[key] = target_id + without_control: list[str] = [] + for target_id, attributes in targets.items(): + if not _selects(selector.lower, attributes): + continue + key = tuple(attributes.get(name) for name in selector.pair_on) + higher = higher_by_key.get(key) + if higher is None: + without_control.append(target_id) + continue + bridges.append( + CrossGrainBridge( + bridge_id=f"{selector.bridge_id}:{target_id}", + concept=selector.concept, + higher_target_ids=(higher,), + lower_side=target_id, + max_factor_shift=selector.max_factor_shift, + min_factor_shift=selector.min_factor_shift, + shift_around=selector.shift_around, + out_of_bound=selector.out_of_bound, + ) + ) + unpaired[selector.bridge_id] = tuple(without_control) + return tuple(bridges), unpaired + + +def _selects(side: Mapping[str, Any], attributes: Mapping[str, Any]) -> bool: + """Whether a target's attributes meet every test of a selector side.""" + + for name, wanted in side.items(): + value = attributes.get(name) + if isinstance(wanted, Mapping): + if not str(value).startswith(str(wanted["prefix"])): + return False + elif value != wanted: + return False + return True @dataclass(frozen=True) @@ -301,6 +419,10 @@ def _reconcile_cross_grain_surface_with_control_receipts( list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]], + list[dict[str, Any]], + list[dict[str, Any]], + list[dict[str, Any]], + list[dict[str, Any]], ]: """Return a copied surface with every detected lower grain rescaled. @@ -331,6 +453,7 @@ def _reconcile_cross_grain_surface_with_control_receipts( first_pair_id: dict[tuple[str, str], str] = {} absent_middle_tier_legs: list[dict[str, Any]] = [] deferred_legs_without_control: list[dict[str, Any]] = [] + unbound_legs: list[dict[str, Any]] = [] pairs_per_key: dict[tuple[str, str], int] = {} for group in materialized_groups: key = (group.inconsistency_id.rsplit(":", 1)[0], group.lower_grain) @@ -541,6 +664,24 @@ def _reconcile_cross_grain_surface_with_control_receipts( ) controls = populated_controls + bridge = bridges_by_id.get(group.bridge_id or "") + bound = None if bridge is None else bridge.max_factor_shift + general_bound = bound is not None and ( + bridge.shift_around != "one" + or bridge.min_factor_shift is not None + or bridge.out_of_bound != "refuse" + ) + reference = 1.0 + if bound is not None and bridge.shift_around == "median": + reference = _median_input_factor( + local_frame, + controls, + lower_by_leg, + row_legs, + columns, + rule, + group.inconsistency_id, + ) leg_receipts: list[dict[str, Any]] = [] used_controls: set[tuple[str, tuple[str, ...]]] = set() for control in controls: @@ -597,10 +738,63 @@ def _reconcile_cross_grain_surface_with_control_receipts( f"cross-grain inconsistency {group.inconsistency_id!r} " "cannot reconcile opposite-signed lower and control targets." ) - bridge = bridges_by_id.get(group.bridge_id or "") - bound = None if bridge is None else bridge.max_factor_shift input_factor = None - if bound is not None: + if general_bound: + input_factor, input_sum = _input_factor( + local_frame.iloc[positions][columns["value"]].to_numpy( + dtype=np.float64 + ), + parent_value, + rule, + group.inconsistency_id, + ) + # A leg that sums to zero under a zero control has nothing to + # judge. Otherwise the shift is the factor over the reference. + relative = ( + input_factor / reference + if np.isfinite(input_factor) and reference + else float("nan") + ) + lowest = ( + -bound + if bridge.min_factor_shift is None + else bridge.min_factor_shift + ) + in_bound = input_sum == 0.0 or bool( + np.isfinite(relative) and 1.0 + lowest <= relative <= 1.0 + bound + ) + if check_factor_bounds and not in_bound: + if bridge.out_of_bound == "unbind": + already.update(positions) + unbound_legs.append( + { + "inconsistency_id": group.inconsistency_id, + "bridge_id": bridge.bridge_id, + "leg": "+".join(control["covered_legs"]), + "parent_geography_id": str( + control["parent_geography_id"] + ), + "higher_target_ids": list(control["higher_target_ids"]), + "positions": [int(p) for p in positions], + "factor_on_input_totals": input_factor, + "factor_reference": reference, + "relative_factor": relative, + "max_factor_shift": bound, + "min_factor_shift": lowest, + "shift_around": bridge.shift_around, + } + ) + continue + raise ValueError( + f"cross-grain bridge {bridge.bridge_id!r} would scale the " + f"{group.lower_grain} rows of leg " + f"{'+'.join(control['covered_legs'])!r} by {input_factor!r} " + f"on their input totals, {relative!r} of the " + f"{bridge.shift_around} reference {reference!r}, outside " + f"its declared shift from {lowest} to {bound}: the two " + "sides no longer measure one quantity." + ) + elif bound is not None: # The bound reads the lower rows as given, not as an earlier # group left them: an exact-signature group that rescales this # grain onto a nearer tier first would leave a factor of one @@ -674,6 +868,15 @@ def _reconcile_cross_grain_surface_with_control_receipts( "factor_bound_checked": check_factor_bounds, } ), + **( + {} + if not general_bound + else { + "min_factor_shift": lowest, + "shift_around": bridge.shift_around, + "factor_reference": reference, + } + ), "reason": ( "standing cross-grain rule: " f"{group.winning_grain} controls {group.lower_grain}" @@ -726,6 +929,7 @@ def _reconcile_cross_grain_surface_with_control_receipts( delegated_legs, absent_middle_tier_legs, deferred_legs_without_control, + unbound_legs, ) @@ -796,6 +1000,7 @@ def apply_cross_grain_reconciliation( licensed_empty_legs: Mapping[str, frozenset[str]] | None = None, check_factor_bounds: bool = True, frame_only_positions: Iterable[int] = (), + expected_members: Mapping[str, Mapping[str, frozenset[str]]] | None = None, ) -> tuple[pd.DataFrame, dict[str, Any]]: """Detect, reconcile, and return the always-present pass receipt. @@ -805,8 +1010,14 @@ def apply_cross_grain_reconciliation( ``frame_only_positions`` names the rows that bind nothing (deferred cells); a leg holding only those needs no control (``deferred_legs_without_control``). + ``expected_members`` maps a lower target to the geographies that each of + its legs must hold. A leg that holds other rows than those is refused: + rescaling a set that is not complete would move the missing members' + mass onto the present ones. A leg with no row at all is left to the + empty-leg licences. """ + _assert_expected_members(local_frame, rule, expected_members) bound = tuple(str(target_id) for target_id in bound_higher_targets) groups = detect_cross_grain_inconsistencies( local_frame, @@ -829,6 +1040,7 @@ def apply_cross_grain_reconciliation( delegated_legs, absent_middle_tier_legs, deferred_legs_without_control, + unbound_legs, ) = _reconcile_cross_grain_surface_with_control_receipts( local_frame, groups, @@ -848,6 +1060,13 @@ def apply_cross_grain_reconciliation( "delegated_legs": delegated_legs, "absent_middle_tier_legs": absent_middle_tier_legs, "deferred_legs_without_control": deferred_legs_without_control, + # Only a rule with a bridge that unbinds carries the key, so the + # receipt of every other rule keeps the keys it had. + **( + {"unbound_legs": unbound_legs} + if any(bridge.out_of_bound == "unbind" for bridge in rule.bridges) + else {} + ), "absence": ( None if groups @@ -1143,6 +1362,36 @@ def _validate_rule(rule: CrossGrainRule) -> None: f"{bound!r}; a bound must be a number in (0, 1): at one or more " "it would accept every factor below one." ) + floor = bridge.min_factor_shift + if ( + bridge.shift_around not in SHIFT_REFERENCES + or bridge.out_of_bound not in OUT_OF_BOUND_ACTIONS + ): + raise ValueError( + f"cross-grain bridge {bridge.bridge_id!r} declares shift_around " + f"{bridge.shift_around!r} and out_of_bound {bridge.out_of_bound!r}; " + f"expected one of {SHIFT_REFERENCES} and one of " + f"{OUT_OF_BOUND_ACTIONS}." + ) + if bound is None and ( + floor is not None + or bridge.shift_around != "one" + or bridge.out_of_bound != "refuse" + ): + raise ValueError( + f"cross-grain bridge {bridge.bridge_id!r} shapes a bound it does " + "not declare; set max_factor_shift." + ) + if floor is not None and ( + isinstance(floor, bool) + or not isinstance(floor, int | float) + or not -1.0 < floor < bound + ): + raise ValueError( + f"cross-grain bridge {bridge.bridge_id!r} declares min_factor_shift " + f"{floor!r}; it must be a number above -1 and below " + f"max_factor_shift {bound!r}." + ) for geography_id, legs in rule.parent_geography_legs.items(): if not str(geography_id) or not legs or any(not str(leg) for leg in legs): raise ValueError( @@ -1376,6 +1625,109 @@ def _allocator_name(allocator: Callable[..., Any]) -> str: return str(getattr(allocator, "__name__", type(allocator).__name__)) +def _input_factor( + input_values: np.ndarray, + parent_value: float, + rule: CrossGrainRule, + inconsistency_id: str, +) -> tuple[float, float]: + """``(factor, lower total)`` of a leg on its rows as given. + + The factor and the total are those of the rule's own division: the + allocator's when it declares one, else the control over the numpy sum. + """ + + if rule.allocator is not None: + _values, factor, input_sum = _allocation( + rule.allocator, input_values, parent_value, inconsistency_id + ) + return factor, input_sum + input_sum = float(input_values.sum()) + if input_sum != 0.0: + return parent_value / input_sum, input_sum + return (1.0 if parent_value == 0.0 else float("inf")), input_sum + + +def _median_input_factor( + local_frame: pd.DataFrame, + controls: Iterable[Mapping[str, Any]], + lower_by_leg: Mapping[str, list[int]], + row_legs: Mapping[int, tuple[str, ...]], + columns: Mapping[str, str], + rule: CrossGrainRule, + inconsistency_id: str, +) -> float: + """The median factor across a bridge's legs, on their rows as given. + + Only a leg with a nonzero total and a positive finite factor counts, so + a leg that cannot be scaled does not move the reference. With no such + leg the reference is ``NaN``, and every judged leg is out of bound. + """ + + factors: list[float] = [] + seen: set[tuple[str, tuple[str, ...]]] = set() + for control in controls: + key = (str(control["parent_geography_id"]), tuple(control["covered_legs"])) + if key in seen: + continue + seen.add(key) + positions = _control_positions( + control, lower_by_leg, row_legs, inconsistency_id + ) + factor, input_sum = _input_factor( + local_frame.iloc[positions][columns["value"]].to_numpy(dtype=np.float64), + float(control["value"]), + rule, + inconsistency_id, + ) + if input_sum != 0.0 and np.isfinite(factor) and factor > 0: + factors.append(factor) + return float(np.median(factors)) if factors else float("nan") + + +def _assert_expected_members( + local_frame: pd.DataFrame, + rule: CrossGrainRule, + expected_members: Mapping[str, Mapping[str, frozenset[str]]] | None, +) -> None: + """Refuse a leg of a target that holds other rows than its members.""" + + if not expected_members: + return + columns = _surface_columns(local_frame) + expected = { + _contract_target_id(str(target_id)): by_leg + for target_id, by_leg in expected_members.items() + } + held: dict[tuple[str, str], set[str]] = {} + for side, area in zip( + local_frame[columns["target_id"]].tolist(), + local_frame[columns["geography_id"]].tolist(), + strict=True, + ): + target_id = _contract_target_id(str(side)) + if target_id not in expected: + continue + for leg in _row_legs(str(area), rule): + held.setdefault((target_id, leg), set()).add(str(area)) + for (target_id, leg), present in sorted(held.items()): + members = expected[target_id].get(leg) + if members is None: + raise ValueError( + f"cross-grain target {target_id!r} has rows on leg {leg!r}, " + "which declares no members for it." + ) + missing = sorted(set(members) - present) + unexpected = sorted(present - set(members)) + if missing or unexpected: + raise ValueError( + f"cross-grain target {target_id!r} does not hold the declared " + f"members of leg {leg!r}: missing {missing}, unexpected " + f"{unexpected}. Rescaling a set that is not complete would " + "misstate every member." + ) + + def _controls_agree(left: float, right: float) -> bool: return bool( np.isclose(float(left), float(right), rtol=_CONTROL_AGREEMENT_RTOL, atol=0.0) diff --git a/packages/microcosm-build/tests/engine_free/shared/test_cross_grain_allocator.py b/packages/microcosm-build/tests/engine_free/shared/test_cross_grain_allocator.py index ea6e4da683..b4bc4cdcb4 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_cross_grain_allocator.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_cross_grain_allocator.py @@ -38,10 +38,27 @@ #: sha256 of ``cross_grain.py`` at ``e29843dc7``. REFERENCE_SHA256 = "f61f83dd4577f322cfbc5a1276c4454c36877b56b2d480480ac74155623cd7f3" -#: What the hook changed or added in the module; everything else is the -#: reference, source line for source line. -CHANGED = {"CrossGrainRule", "_reconcile_cross_grain_surface_with_control_receipts"} -ADDED = {"_allocation", "_allocator_name"} +#: What this branch changed or added in the module; everything else is the +#: reference, source line for source line. The allocator is the first two of +#: each set. The rest is the general model (``test_cross_grain_model.py``): +#: the bound of a bridge, the members of a leg and the bridge selector. +CHANGED = { + "CrossGrainRule", + "_reconcile_cross_grain_surface_with_control_receipts", + "CrossGrainBridge", + "apply_cross_grain_reconciliation", + "_validate_rule", +} +ADDED = { + "_allocation", + "_allocator_name", + "CrossGrainBridgeSelector", + "expand_bridge_selectors", + "_selects", + "_input_factor", + "_median_input_factor", + "_assert_expected_members", +} _LEGS = ("E", "W", "S", "N") @@ -66,7 +83,7 @@ def _definitions(module) -> dict[str, str]: } -def test_the_hook_touches_one_rule_field_and_one_function() -> None: +def test_the_branch_touches_only_these_definitions() -> None: new, old = _definitions(cross_grain), _definitions(cross_grain_reference) assert set(new) - set(old) == ADDED assert set(old) - set(new) == set() @@ -81,7 +98,7 @@ def _imports(module) -> list[str]: ] -def test_the_hook_adds_no_import() -> None: +def test_the_branch_adds_no_import() -> None: """The UK graph hashes the modules a target module imports by name.""" assert _imports(cross_grain) == _imports(cross_grain_reference) diff --git a/packages/microcosm-build/tests/engine_free/shared/test_cross_grain_model.py b/packages/microcosm-build/tests/engine_free/shared/test_cross_grain_model.py new file mode 100644 index 0000000000..614293e15a --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/shared/test_cross_grain_model.py @@ -0,0 +1,377 @@ +"""The general parts of the cross-grain model (microcosm#1760). + +Three things that a country once did in its own code are part of the shared +operator, each off by default: + +- the bound of a bridge can be measured from the median factor across the + bridge's legs, can be one-sided, and can unbind an out-of-bound leg where + the default refuses the pass; +- ``expected_members`` refuses a leg of a target that does not hold exactly + its declared members; +- a bridge selector makes one bridge for each pair of targets. + +``test_cross_grain_allocator.py`` holds the default path to the operator as +it stood before any of this, bit for bit. +""" + +from __future__ import annotations + +import math + +import pandas as pd +import pytest + +from microcosm.build.cross_grain import ( + CrossGrainBridge, + CrossGrainBridgeSelector, + CrossGrainRule, + apply_cross_grain_reconciliation, + expand_bridge_selectors, +) + +_STATES = ("A", "B", "C", "D", "E") + + +def _signature(concept: str) -> dict[str, object]: + return {"measurement": {"concept": concept, "filters": []}} + + +_SIGNATURES = {"total": _signature("source one"), "parts": _signature("source two")} + + +def _rule(bridge: CrossGrainBridge | None = None, **overrides) -> CrossGrainRule: + arguments = { + "grain_precedence": ("nation", "state", "district"), + "signature_fields": ("concept", "filters"), + "bridges": () if bridge is None else (bridge,), + "leg_of_area": lambda area: area[0], + "parent_geography_legs": {state: (state,) for state in _STATES}, + "control_grains": ("nation", "state"), + } + return CrossGrainRule(**{**arguments, **overrides}) + + +def _bridge(**bound) -> CrossGrainBridge: + return CrossGrainBridge( + "total_vs_parts", + concept="one quantity", + higher_target_ids=("total",), + lower_side="parts", + **bound, + ) + + +def _surface(factors: dict[str, float], *, parts=(30.0, 70.0)) -> pd.DataFrame: + """A state total and two districts in each state; the factor is their gap.""" + + rows = [] + for state, factor in factors.items(): + rows.append(("state", state, "total", sum(parts) * factor)) + rows += [ + ("district", f"{state}{index}", "parts", value) + for index, value in enumerate(parts, start=1) + ] + return pd.DataFrame(rows, columns=["grain", "geography_id", "target_id", "value"]) + + +_MEDIAN_BAND = { + "max_factor_shift": 0.25, + "min_factor_shift": -0.2, + "shift_around": "median", +} + + +def test_a_median_bound_takes_out_the_gap_that_every_leg_shares() -> None: + """Every leg is 2.4 times its rows: far from one, and no shift at all.""" + + factors = dict.fromkeys(_STATES, 2.4) + surface = _surface(factors) + reconciled, receipt = apply_cross_grain_reconciliation( + surface, ("total",), _SIGNATURES, _rule(_bridge(**_MEDIAN_BAND)) + ) + assert reconciled["value"].tolist() == pytest.approx([240.0, 72.0, 168.0] * 5) + (group,) = receipt["groups"] + assert len(group["legs"]) == 5 + for leg in group["legs"]: + assert leg["factor_reference"] == pytest.approx(2.4) + assert leg["shift_around"] == "median" + assert (leg["max_factor_shift"], leg["min_factor_shift"]) == (0.25, -0.2) + # The same legs under a bound around one are refused. + with pytest.raises(ValueError, match="max_factor_shift 0.25 from one"): + apply_cross_grain_reconciliation( + surface, ("total",), _SIGNATURES, _rule(_bridge(max_factor_shift=0.25)) + ) + + +def test_an_out_of_bound_leg_is_refused_by_default() -> None: + factors = {"A": 1.0, "B": 1.02, "C": 1.04, "D": 0.98, "E": 2.0} + with pytest.raises( + ValueError, match="outside its declared shift from -0.2 to 0.25" + ) as refused: + apply_cross_grain_reconciliation( + _surface(factors), ("total",), _SIGNATURES, _rule(_bridge(**_MEDIAN_BAND)) + ) + assert "leg 'E'" in str(refused.value) + + +def test_unbind_leaves_the_leg_as_given_and_records_it() -> None: + factors = {"A": 1.0, "B": 1.02, "C": 1.04, "D": 0.98, "E": 2.0} + surface = _surface(factors) + reconciled, receipt = apply_cross_grain_reconciliation( + surface, + ("total",), + _SIGNATURES, + _rule(_bridge(**_MEDIAN_BAND, out_of_bound="unbind")), + ) + values = reconciled["value"].tolist() + # The four legs in bound close on their controls. + for index, state in enumerate("ABCD"): + assert values[3 * index + 1] + values[3 * index + 2] == pytest.approx( + 100.0 * factors[state] + ) + # The leg out of bound keeps its rows as given. + assert values[13:15] == [30.0, 70.0] + (unbound,) = receipt["unbound_legs"] + assert (unbound["leg"], unbound["parent_geography_id"]) == ("E", "E") + assert unbound["positions"] == [13, 14] + assert unbound["factor_on_input_totals"] == pytest.approx(2.0) + assert unbound["factor_reference"] == pytest.approx(1.02) + assert unbound["relative_factor"] == pytest.approx(2.0 / 1.02) + (group,) = receipt["groups"] + assert sorted(leg["leg"] for leg in group["legs"]) == ["A", "B", "C", "D"] + + +def test_the_bound_is_one_sided_when_it_declares_a_floor() -> None: + low, high = {"A": 1.0, "B": 0.85}, {"A": 1.0, "B": 1.15} + bound = {"max_factor_shift": 0.2, "min_factor_shift": -0.1} + # 0.85 is below the floor of -0.1; 1.15 is inside the ceiling of 0.2. + with pytest.raises(ValueError, match="outside its declared shift"): + apply_cross_grain_reconciliation( + _surface(low), ("total",), _SIGNATURES, _rule(_bridge(**bound)) + ) + reconciled, _receipt = apply_cross_grain_reconciliation( + _surface(high), ("total",), _SIGNATURES, _rule(_bridge(**bound)) + ) + assert reconciled["value"].tolist()[4:6] == pytest.approx([34.5, 80.5]) + + +def test_a_leg_that_sums_to_zero_under_a_zero_control_is_not_judged() -> None: + surface = _surface({"A": 1.0, "B": 1.1, "C": 0.9}) + surface.loc[surface["geography_id"].isin(["C", "C1", "C2"]), "value"] = 0.0 + reconciled, receipt = apply_cross_grain_reconciliation( + surface, + ("total",), + _SIGNATURES, + _rule(_bridge(**_MEDIAN_BAND, out_of_bound="unbind")), + ) + assert receipt["unbound_legs"] == [] + assert reconciled["value"].tolist()[6:] == [0.0, 0.0, 0.0] + + +def test_with_no_positive_factor_the_reference_is_missing_and_all_unbind() -> None: + """A zero control over rows that are not zero: no leg gives a reference.""" + + surface = _surface({"A": 0.0, "B": 0.0}) + reconciled, receipt = apply_cross_grain_reconciliation( + surface, + ("total",), + _SIGNATURES, + _rule(_bridge(**_MEDIAN_BAND, out_of_bound="unbind")), + ) + assert [leg["leg"] for leg in receipt["unbound_legs"]] == ["A", "B"] + assert all(math.isnan(leg["factor_reference"]) for leg in receipt["unbound_legs"]) + assert reconciled["value"].tolist() == surface["value"].tolist() + + +def test_a_pass_that_does_not_check_bounds_unbinds_nothing() -> None: + factors = {"A": 1.0, "B": 1.02, "C": 2.0} + reconciled, receipt = apply_cross_grain_reconciliation( + _surface(factors), + ("total",), + _SIGNATURES, + _rule(_bridge(**_MEDIAN_BAND, out_of_bound="unbind")), + check_factor_bounds=False, + ) + assert receipt["unbound_legs"] == [] + assert reconciled["value"].tolist()[7:9] == pytest.approx([60.0, 140.0]) + + +def test_only_a_rule_that_unbinds_carries_the_unbound_legs_key() -> None: + surface = _surface(dict.fromkeys(_STATES, 1.0)) + for bridge in (_bridge(), _bridge(max_factor_shift=0.1), _bridge(**_MEDIAN_BAND)): + _reconciled, receipt = apply_cross_grain_reconciliation( + surface, ("total",), _SIGNATURES, _rule(bridge) + ) + assert "unbound_legs" not in receipt + (leg, *_others) = receipt["groups"][0]["legs"] + general = bridge.shift_around != "one" + assert ("factor_reference" in leg) == general + + +@pytest.mark.parametrize( + ("bound", "message"), + [ + ({"shift_around": "mean", "max_factor_shift": 0.1}, "shift_around"), + ({"out_of_bound": "drop", "max_factor_shift": 0.1}, "out_of_bound"), + ({"shift_around": "median"}, "shapes a bound it does not declare"), + ({"out_of_bound": "unbind"}, "shapes a bound it does not declare"), + ({"min_factor_shift": -0.1}, "shapes a bound it does not declare"), + ({"max_factor_shift": 0.1, "min_factor_shift": 0.2}, "min_factor_shift"), + ({"max_factor_shift": 0.1, "min_factor_shift": -1.0}, "min_factor_shift"), + ], +) +def test_a_malformed_bound_is_refused(bound, message) -> None: + with pytest.raises(ValueError, match=message): + apply_cross_grain_reconciliation( + _surface({"A": 1.0}), ("total",), _SIGNATURES, _rule(_bridge(**bound)) + ) + + +def _members(**by_state) -> dict[str, dict[str, frozenset[str]]]: + return {"parts": {state: frozenset(areas) for state, areas in by_state.items()}} + + +def test_expected_members_refuse_a_leg_that_is_not_complete() -> None: + surface = _surface({"A": 1.1, "B": 1.1}) + complete = _members(A=["A1", "A2"], B=["B1", "B2"]) + reconciled, _receipt = apply_cross_grain_reconciliation( + surface, ("total",), _SIGNATURES, _rule(_bridge()), expected_members=complete + ) + assert reconciled["value"].tolist()[1:3] == pytest.approx([33.0, 77.0]) + + with pytest.raises(ValueError, match=r"leg 'B': missing \['B3'\], unexpected \[\]"): + apply_cross_grain_reconciliation( + surface, + ("total",), + _SIGNATURES, + _rule(_bridge()), + expected_members=_members(A=["A1", "A2"], B=["B1", "B2", "B3"]), + ) + with pytest.raises(ValueError, match=r"missing \[\], unexpected \['A2'\]"): + apply_cross_grain_reconciliation( + surface, + ("total",), + _SIGNATURES, + _rule(_bridge()), + expected_members=_members(A=["A1"], B=["B1", "B2"]), + ) + # A leg that the target has rows on must declare its members. + with pytest.raises(ValueError, match="declares no members"): + apply_cross_grain_reconciliation( + surface, + ("total",), + _SIGNATURES, + _rule(_bridge()), + expected_members=_members(A=["A1", "A2"]), + ) + + +def test_a_leg_with_no_row_is_left_to_the_licences() -> None: + surface = _surface({"A": 1.1, "B": 1.1}) + surface = surface[~surface["geography_id"].isin(["B1", "B2"])].reset_index( + drop=True + ) + members = _members(A=["A1", "A2"], B=["B1", "B2"]) + with pytest.raises(ValueError, match="lacks a licence"): + apply_cross_grain_reconciliation( + surface, ("total",), _SIGNATURES, _rule(_bridge()), expected_members=members + ) + _reconciled, receipt = apply_cross_grain_reconciliation( + surface, + ("total",), + _SIGNATURES, + _rule(_bridge()), + expected_members=members, + licensed_empty_legs={"parts": frozenset({"B"})}, + ) + assert [entry["leg"] for entry in receipt["empty_legs_licensed"]] == ["B"] + + +_TARGETS = { + "ht2:agi": {"source": "table_2.broad", "grain": "state", "measure": "agi"}, + "ht2:qbi": {"source": "table_2.broad", "grain": "state", "measure": "qbi"}, + "ht2:wages": {"source": "table_2.broad", "grain": "state", "measure": "wages"}, + "cd:agi": {"source": "district.2022", "grain": "district", "measure": "agi"}, + "cd:qbid": {"source": "district.2022", "grain": "district", "measure": "qbid"}, + "cd:eitc": {"source": "district.2022", "grain": "district", "measure": "eitc"}, + "other:agi": {"source": "table_1", "grain": "nation", "measure": "agi"}, +} + + +def _selector(**overrides) -> CrossGrainBridgeSelector: + arguments = { + "bridge_id": "table_2_vs_district", + "concept": "one tax quantity", + "higher": {"source": {"prefix": "table_2."}, "grain": "state"}, + "lower": {"source": {"prefix": "district."}}, + "pair_on": ("measure",), + "paired_values": {"measure": {"qbi": "qbid"}}, + **_MEDIAN_BAND, + "out_of_bound": "unbind", + } + return CrossGrainBridgeSelector(**{**arguments, **overrides}) + + +def test_a_selector_makes_one_bridge_for_each_pair() -> None: + bridges, unpaired = expand_bridge_selectors([_selector()], _TARGETS) + assert [ + (bridge.bridge_id, bridge.higher_target_ids, bridge.lower_side) + for bridge in bridges + ] == [ + ("table_2_vs_district:cd:agi", ("ht2:agi",), "cd:agi"), + ("table_2_vs_district:cd:qbid", ("ht2:qbi",), "cd:qbid"), + ] + # A lower target with no higher target is named, never bridged. + assert unpaired == {"table_2_vs_district": ("cd:eitc",)} + # Each bridge takes the selector's concept and bound. + for bridge in bridges: + assert bridge.concept == "one tax quantity" + assert ( + bridge.max_factor_shift, + bridge.min_factor_shift, + bridge.shift_around, + bridge.out_of_bound, + ) == (0.25, -0.2, "median", "unbind") + + +def test_a_selector_refuses_two_controls_for_one_lower_target() -> None: + targets = {**_TARGETS, "ht2b:agi": {**_TARGETS["ht2:agi"]}} + with pytest.raises(ValueError, match="pairs two higher targets"): + expand_bridge_selectors([_selector()], targets) + with pytest.raises(ValueError, match="must name the attributes"): + expand_bridge_selectors([_selector(pair_on=())], _TARGETS) + + +def test_selected_bridges_run_on_the_operator() -> None: + bridges, _unpaired = expand_bridge_selectors([_selector()], _TARGETS) + rows = [] + for state, factor in {"A": 1.02, "B": 1.0, "C": 1.04, "D": 3.0}.items(): + for higher, lower in (("ht2:agi", "cd:agi"), ("ht2:qbi", "cd:qbid")): + rows.append(("state", state, higher, 100.0 * factor)) + rows += [("district", f"{state}{i}", lower, 50.0) for i in (1, 2)] + surface = pd.DataFrame( + rows, columns=["grain", "geography_id", "target_id", "value"] + ) + signatures = {target: _signature(target) for target in _TARGETS} + reconciled, receipt = apply_cross_grain_reconciliation( + surface, ("ht2:agi", "ht2:qbi"), signatures, _rule(bridges=bridges) + ) + assert len(receipt["groups"]) == 2 + # State D is out of the band in both bridges; its rows keep their values. + assert sorted( + (leg["bridge_id"], leg["leg"]) for leg in receipt["unbound_legs"] + ) == [ + ("table_2_vs_district:cd:agi", "D"), + ("table_2_vs_district:cd:qbid", "D"), + ] + values = { + (area, target): value + for area, target, value in zip( + surface["geography_id"], + surface["target_id"], + reconciled["value"], + strict=True, + ) + } + assert values[("A1", "cd:agi")] == pytest.approx(51.0) + assert values[("D1", "cd:qbid")] == 50.0 From 938c7faa6ca8201c1904b606ac5cce90f1a5f939 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Fri, 27 Nov 2026 13:38:44 +0000 Subject: [PATCH 12/23] Annotate the adapter's parameters that the spine-blindness check reads as frames CI's engine-free job failed on the Stage A head in test_runtime_population_operators_are_source_spine_blind. The check treats a function parameter with no annotation as a possible frame, and refuses a subscript on it whose key it cannot resolve. us_runtime/target_nesting.py had nine: two lambdas over a block key, and the county populations and county values of the two county functions, which came from the tool with no annotations. The two county functions now annotate their parameters, and the block key is read by a named function. No behavior changes. The whole test file passes. I had run one test of that file locally, not the file. Co-Authored-By: Claude Fable 5.2 --- .../build/us_runtime/target_nesting.py | 28 +++++++++++++++---- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/target_nesting.py b/packages/microcosm-build/src/microcosm/build/us_runtime/target_nesting.py index efb64a74b0..f3c7908053 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/target_nesting.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/target_nesting.py @@ -27,7 +27,7 @@ import math import struct from collections import Counter, defaultdict -from collections.abc import Callable, Mapping, Sequence +from collections.abc import Callable, Iterable, Mapping, Sequence from contextvars import ContextVar from dataclasses import dataclass, replace from pathlib import Path @@ -454,7 +454,7 @@ def drop(spec, reason: str) -> None: ) for key in ht2_by_key.keys() & cd_file_state_by_key.keys() } - median_ratio = controls.median_by_group(vintage_ratio, lambda key: key[1]) + median_ratio = controls.median_by_group(vintage_ratio, _identity_of_block) out_of_band: list[dict] = [] def within_band( @@ -511,7 +511,7 @@ def within_band( if ratio is not None: block_factor[key] = ratio median_factor = controls.median_by_group( - block_factor, lambda key: key[1], positive_only=True + block_factor, _identity_of_block, positive_only=True ) # One basis for every state level: a concept Historic Table 2 lacks keeps @@ -873,6 +873,12 @@ def district_block_closure(specs: Sequence, *, rtol: float) -> list[dict]: return report +def _identity_of_block(key: tuple) -> tuple: + """The concept identity of a (state, identity) block key.""" + + return key[1] + + def _bits(*values: float) -> bytes: return b"".join(struct.pack(" NestedSurface: """Rebase complete county fact blocks onto existing broad state totals. @@ -1350,7 +1361,14 @@ def acs_households_parent_name(state): def county_acs_household_surface( - values, county_populations, *, period, source_name, tables, family, measure + values: Mapping[int, tuple[float, float | None, str]], + county_populations: Mapping[int, float], + *, + period: int, + source_name: str, + tables: str, + family: str, + measure: str, ) -> NestedSurface: """State households parents and their county children (trained, levels). From d91ae5b3752e2875da33d108a3d67e4c65ef186b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:19:51 +0000 Subject: [PATCH 13/23] Refuse a declared leg with no row, and hold the keys of a reconciled row in the operator Two general changes to the shared cross-grain operator, for step 2 of microcosm#1760 (the US on the model). The UK declares neither. - expected_members reads every declared leg, with or without rows. A leg whose members were all absent was left to the empty-leg licences. So a target with no row at all formed no group, and the pass left its totals as they were without a word. Such a leg is now refused like a leg that lacks one member. A leg that declares no member holds no row, and the licences still decide it. - The metadata of a reconciled row is in the operator: the UK's key names (cross_grain_value_before, cross_grain_factor, cross_grain_control), two new general keys (cross_grain_parent, the name of the control row, and cross_grain_members, the geographies a row stands for), and cross_grain_metadata, which writes them in a fixed order. A country takes the names from one place. No UK code changes. The default path is the operator before any edit, bit for bit (test_cross_grain_allocator.py, 400 seeded surfaces; its pinned list of added definitions gains cross_grain_metadata). The UK graph hashes this file, so UK target nodes compute again on the next UK run, with the same outputs. Co-Authored-By: Claude Fable 5.2 --- .../src/microcosm/build/cross_grain.py | 55 +++++++++++++++++-- .../shared/test_cross_grain_allocator.py | 2 + .../shared/test_cross_grain_model.py | 35 ++++++++++-- 3 files changed, 83 insertions(+), 9 deletions(-) diff --git a/packages/microcosm-build/src/microcosm/build/cross_grain.py b/packages/microcosm-build/src/microcosm/build/cross_grain.py index 27dd371fb0..60ae9fd83b 100644 --- a/packages/microcosm-build/src/microcosm/build/cross_grain.py +++ b/packages/microcosm-build/src/microcosm/build/cross_grain.py @@ -78,6 +78,42 @@ class CrossGrainBridge: SHIFT_REFERENCES = ("one", "median") OUT_OF_BOUND_ACTIONS = ("refuse", "unbind") +#: The metadata that a reconciled target row keeps. Target metadata is text, +#: so the numbers are exact ``repr`` strings. +VALUE_BEFORE_KEY = "cross_grain_value_before" +FACTOR_KEY = "cross_grain_factor" +#: What reconciled the row: a bridge id, a partition id, or +#: :data:`EXACT_SIGNATURE_CONTROL`. +CONTROL_KEY = "cross_grain_control" +EXACT_SIGNATURE_CONTROL = "exact_signature" +#: The name of the control row, when the control is one row. +PARENT_KEY = "cross_grain_parent" +#: The geographies a row stands for, when it stands for more than its own. +MEMBERS_KEY = "cross_grain_members" + + +def cross_grain_metadata( + *, + value_before: float, + factor: float, + control: str, + parent: str | None = None, + members: Iterable[str] = (), +) -> dict[str, str]: + """The metadata of one reconciled row, in a fixed key order.""" + + metadata = { + VALUE_BEFORE_KEY: repr(float(value_before)), + FACTOR_KEY: repr(float(factor)), + CONTROL_KEY: str(control), + } + if parent is not None: + metadata[PARENT_KEY] = str(parent) + members = tuple(str(member) for member in members) + if members: + metadata[MEMBERS_KEY] = ",".join(members) + return metadata + @dataclass(frozen=True) class CrossGrainBridgeSelector: @@ -1013,8 +1049,9 @@ def apply_cross_grain_reconciliation( ``expected_members`` maps a lower target to the geographies that each of its legs must hold. A leg that holds other rows than those is refused: rescaling a set that is not complete would move the missing members' - mass onto the present ones. A leg with no row at all is left to the - empty-leg licences. + mass onto the present ones. A declared leg with no row is refused in the + same way. A leg that declares no member holds no row, and the empty-leg + licences decide it. """ _assert_expected_members(local_frame, rule, expected_members) @@ -1690,7 +1727,11 @@ def _assert_expected_members( rule: CrossGrainRule, expected_members: Mapping[str, Mapping[str, frozenset[str]]] | None, ) -> None: - """Refuse a leg of a target that holds other rows than its members.""" + """Refuse a leg of a target that does not hold exactly its members. + + The check reads every declared leg, with or without rows, so a leg whose + members are all absent is refused like a leg that lacks one member. + """ if not expected_members: return @@ -1710,7 +1751,13 @@ def _assert_expected_members( continue for leg in _row_legs(str(area), rule): held.setdefault((target_id, leg), set()).add(str(area)) - for (target_id, leg), present in sorted(held.items()): + declared = { + (target_id, str(leg)) + for target_id, by_leg in expected.items() + for leg in by_leg + } + for target_id, leg in sorted(declared | held.keys()): + present = held.get((target_id, leg), set()) members = expected[target_id].get(leg) if members is None: raise ValueError( diff --git a/packages/microcosm-build/tests/engine_free/shared/test_cross_grain_allocator.py b/packages/microcosm-build/tests/engine_free/shared/test_cross_grain_allocator.py index b4bc4cdcb4..e42c515be8 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_cross_grain_allocator.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_cross_grain_allocator.py @@ -58,6 +58,8 @@ "_input_factor", "_median_input_factor", "_assert_expected_members", + # The metadata of a reconciled row, for a caller that holds target rows. + "cross_grain_metadata", } _LEGS = ("E", "W", "S", "N") diff --git a/packages/microcosm-build/tests/engine_free/shared/test_cross_grain_model.py b/packages/microcosm-build/tests/engine_free/shared/test_cross_grain_model.py index 614293e15a..98120ed3da 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_cross_grain_model.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_cross_grain_model.py @@ -266,22 +266,47 @@ def test_expected_members_refuse_a_leg_that_is_not_complete() -> None: ) -def test_a_leg_with_no_row_is_left_to_the_licences() -> None: +def test_a_declared_leg_holds_its_members_with_or_without_rows() -> None: surface = _surface({"A": 1.1, "B": 1.1}) - surface = surface[~surface["geography_id"].isin(["B1", "B2"])].reset_index( + without_b = surface[~surface["geography_id"].isin(["B1", "B2"])].reset_index( drop=True ) members = _members(A=["A1", "A2"], B=["B1", "B2"]) + with pytest.raises(ValueError, match=r"leg 'B': missing \['B1', 'B2'\]"): + apply_cross_grain_reconciliation( + without_b, + ("total",), + _SIGNATURES, + _rule(_bridge()), + expected_members=members, + ) + # A target with no row at all forms no group. Its declared legs are still + # read, so the pass cannot leave the totals as they are without a word. + totals_only = surface[surface["target_id"] == "total"].reset_index(drop=True) + with pytest.raises(ValueError, match=r"leg 'A': missing \['A1', 'A2'\]"): + apply_cross_grain_reconciliation( + totals_only, + ("total",), + _SIGNATURES, + _rule(_bridge()), + expected_members=members, + ) + # A leg that declares no member holds no row. The licences decide it. + empty_b = _members(A=["A1", "A2"], B=[]) with pytest.raises(ValueError, match="lacks a licence"): apply_cross_grain_reconciliation( - surface, ("total",), _SIGNATURES, _rule(_bridge()), expected_members=members + without_b, + ("total",), + _SIGNATURES, + _rule(_bridge()), + expected_members=empty_b, ) _reconciled, receipt = apply_cross_grain_reconciliation( - surface, + without_b, ("total",), _SIGNATURES, _rule(_bridge()), - expected_members=members, + expected_members=empty_b, licensed_empty_legs={"parts": frozenset({"B"})}, ) assert [entry["leg"] for entry in receipt["empty_legs_licensed"]] == ["B"] From 2264fb3774675430834e9954cabf14505ea0369e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:19:51 +0000 Subject: [PATCH 14/23] Put the US on the cross-grain model: the UK's key names, the operator's keys and receipts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Step 2 of microcosm#1760 (docs/us-target-nesting-rule-design.md, section 5.5), on María's go of 27 Nov 2026. No target value changes: on the pinned feed and ladder each of the 26,272 rows of the state_cd SOI surface has the bits of the value it had, and the full, state and totals surfaces have the bytes they had. What is general now, and where: - cross_grain_controls holds one row-level pass, reconcile_rows: it runs the operator on target rows and says, for each row, its value, what reconciled it, the factor, and the control row. The helpers that only the US used (factor band, completeness, self-consistency, sibling ratio) are gone: the operator's bound, members and selectors do that work. - us/cross_grain_declarations.json is in the UK's key names: bridge_selectors (Historic Table 2 state rows over district-file rows, with the bound +0.25 / -0.20 around the median and unbind; state SOI rows over county-file rows), derived_controls (county households), same_measurement (the ladder population), relations (six subset pairs, Medicaid with max_excess), local_routes, members, registers. What goes at the feed re-pin is under until_the_feed_repin: the allocators, the level bridges of the six district-only concepts, the compile rules of rows 1 to 4 and two known gaps. The keys mechanisms and inventory are gone. - us_runtime/target_nesting.py runs each of the four passes through one function, run_pass. What changes by design: - Metadata keys: cross_grain_parent, cross_grain_value_before, cross_grain_factor, cross_grain_control and cross_grain_members replace the state_cd_* and state_county_* keys. Six old keys have no new one: the parent row, the operator's receipt or the declaration holds the value. - Receipts: the district receipt has bridge (with the unbound legs), level_bridge_out_of_band and factor_by_measure. factor_band, rebase_factor_by_measure and internal_consistency are gone. County blocks lose share_sum. target_nesting.json entries are pass, allocator and the operator's receipt. - So three pins of state_cd move (registry, roles, receipts). The target count and the population matrix are the same. - A refusal that the operator makes has the operator's text. - The check that the district file's own state row is the sum of its district rows is gone. Row 4 of the compile scales the district rows to that state row before this pass (22,236 district rows carry its marker on the pinned feed; the 436 that do not are never bound). - A concept that takes its state parent from Historic Table 2 in some states and from the district file in others is refused. It does not occur on the pinned feed. - With the bound turned off (tests only), a concept whose Historic Table 2 level is zero in every state keeps district rows of zero. The readers of the keys move with them: the loss weights, the hold-outs and their pro-rata baselines, the county reports, and one field of the reviewed limitations. The dated runs under experiments/ are not changed. Proof: test_us_target_nesting_district.py and test_us_target_nesting_county.py hold the tool functions to verbatim copies of the code they replace (160 and 120 seeded inputs, and the pinned feed): the same rows in the same order, the same value bits, the same parent, factor, value before and members under the new keys, the same counts, drops and summaries. Both US pin tools ran and wrote no file; --check passes. PR #1755 declares the old parent keys in us/local_target_construction.json and pins the state_cd registry bytes. The PR that merges second takes the other's change. Co-Authored-By: Claude Fable 5.2 --- .../microcosm/build/cross_grain_controls.py | 413 +++--- .../build/us/cross_grain_declarations.json | 581 +++----- .../us_runtime/cross_grain_declarations.py | 591 +++++--- .../build/us_runtime/target_loss_weights.py | 15 +- .../build/us_runtime/target_nesting.py | 1297 ++++++++--------- .../shared/test_cross_grain_controls.py | 217 +-- .../us/test_us_acs_local_cd_properties.py | 101 +- .../us/test_us_acs_local_county_production.py | 28 +- .../us/test_us_acs_local_county_properties.py | 8 +- .../us/test_us_acs_local_county_surface.py | 34 +- .../test_us_acs_local_no_county_regression.py | 12 +- .../us/test_us_acs_local_sparse_cd.py | 65 +- .../us/test_us_acs_local_surface_bytes.py | 17 +- .../test_us_acs_local_target_loss_weights.py | 8 +- .../us/test_us_cross_grain_coverage.py | 259 ++-- .../us/test_us_cross_grain_declarations.py | 428 ++++-- .../us/test_us_target_loss_weights.py | 11 +- .../us/test_us_target_nesting_county.py | 205 ++- .../us/test_us_target_nesting_district.py | 324 +++- tools/build_us_acs_local_release.py | 2 +- tools/us_acs_local_cd_surface.py | 58 +- tools/us_acs_local_county_surface.py | 33 +- 22 files changed, 2538 insertions(+), 2169 deletions(-) diff --git a/packages/microcosm-build/src/microcosm/build/cross_grain_controls.py b/packages/microcosm-build/src/microcosm/build/cross_grain_controls.py index 7edec120dd..76d94c6231 100644 --- a/packages/microcosm-build/src/microcosm/build/cross_grain_controls.py +++ b/packages/microcosm-build/src/microcosm/build/cross_grain_controls.py @@ -1,45 +1,200 @@ -"""Controls, allocators and checks that sit beside the cross-grain operator. - -:mod:`microcosm.build.cross_grain` groups the rows of one quantity, finds the -control of each lower leg, divides the control among the leg's rows, checks -the sum and writes the receipt. A country's sources can need more than that -around the same job (microcosm#1760): - -- **allocators**: another way to divide a control among its rows than the - operator's standing rule. A country names one in its declarations and passes - it as ``CrossGrainRule.allocator``; -- **derived controls**: a control that no source publishes as one row, computed - before the operator runs and placed on the surface as the control row; -- **the factor band**: how far one control's ratio to its lower rows may sit - from the median ratio across the controls of the same quantity; -- **completeness**: whether a leg holds exactly the members it must, with - declared combined cells; -- **self-consistency**: a source's own total against the sum of its own lower - rows. - -Every function here is plain arithmetic on values and keys. None knows a -country, a source or a geography: the caller's declarations supply them. The -operator does not import this module, so the graphs that hash the operator do -not hash it. +"""The row-level pass and the allocators beside the cross-grain operator. + +:mod:`microcosm.build.cross_grain` reconciles a surface that is a data frame, +and its receipt names legs, not rows. A caller that holds target rows wants +the answer for each row: its new value, what reconciled it, with which +factor, and under which control row. :func:`reconcile_rows` runs the operator +and gives that answer. It holds no country: the caller supplies the rows, +the measurements and the rule. + +The module also holds: + +- :func:`sum_of_lower_rows`, the arithmetic of a derived control that is the + sum of its lower rows; +- three allocators for ``CrossGrainRule.allocator``. They keep, bit for bit, + rows that were first made outside the operator. They go when the feed that + holds those rows is pinned again, and the operator's own rule then divides + every control (microcosm#1760). """ from __future__ import annotations import math -from collections.abc import Callable, Hashable, Iterable, Mapping +from collections.abc import Callable, Iterable, Mapping, Sequence from dataclasses import dataclass +from typing import Any import numpy as np +import pandas as pd + +from microcosm.build.cross_grain import ( + EXACT_SIGNATURE_CONTROL, + CrossGrainRule, + _contract_target_id, + _control_grains, + _inconsistency_identity, + _measurement_signature, + _row_legs, + apply_cross_grain_reconciliation, +) -#: ``(values, factor, raw_sum)``, as ``CrossGrainRule.allocator`` returns it. -Allocation = tuple[np.ndarray, float, float] -Allocator = Callable[[np.ndarray, float], Allocation] +# --------------------------------------------------------------------------- +# The row-level pass +# --------------------------------------------------------------------------- + +RECONCILED = "reconciled" +UNBOUND = "unbound" +UNTOUCHED = "untouched" + + +@dataclass(frozen=True) +class SurfaceRow: + """One row of a reconciliation surface.""" + + grain: str + geography_id: str + target_id: str + value: float + + +@dataclass(frozen=True) +class RowOutcome: + """What a pass did with one surface row. + + ``status`` is :data:`RECONCILED` (the row was divided from a control), + :data:`UNBOUND` (its leg was out of the bound of a bridge that unbinds, so + the row keeps its value and the caller takes it off its surface) or + :data:`UNTOUCHED` (a control row, or a row that no group covers). + ``control`` is the bridge id, or ``exact_signature``. ``factor`` and + ``lower_total`` are those of the row's leg. ``parent`` is the position of + the control row, when the control is one row. + """ + + value: float + status: str = UNTOUCHED + control: str | None = None + factor: float | None = None + lower_total: float | None = None + parent: int | None = None + + +def reconcile_rows( + rows: Sequence[SurfaceRow], + bound_higher_targets: Iterable[str], + signatures: Mapping[str, Mapping[str, Any]], + rule: CrossGrainRule, + *, + expected_members: Mapping[str, Mapping[str, frozenset[str]]] | None = None, + licensed_empty_legs: Mapping[str, frozenset[str]] | None = None, +) -> tuple[list[RowOutcome], dict[str, Any]]: + """Run the operator on ``rows`` and say what it did with each row. + + Returns one :class:`RowOutcome` for each row, in the order of ``rows``, + and the operator's pass receipt. + """ + + frame = pd.DataFrame( + [ + (row.grain, row.geography_id, row.target_id, float(row.value)) + for row in rows + ], + columns=["grain", "geography_id", "target_id", "value"], + ) + reconciled, receipt = apply_cross_grain_reconciliation( + frame, + bound_higher_targets, + signatures, + rule, + expected_members=expected_members, + licensed_empty_legs=licensed_empty_legs, + ) + values = reconciled["value"].to_numpy(dtype=np.float64).tolist() + control_grains = set(_control_grains(rule)) + target_ids = [_contract_target_id(row.target_id) for row in rows] + controls: dict[tuple[str, str], int] = {} + lower: dict[tuple[str, str, str], list[int]] = {} + for position, (row, target_id) in enumerate(zip(rows, target_ids, strict=True)): + if row.grain in control_grains: + controls.setdefault((target_id, row.geography_id), position) + for leg in _row_legs(row.geography_id, rule): + lower.setdefault((target_id, row.grain, leg), []).append(position) + identities: dict[str, list[str]] = {} + for target_id in dict.fromkeys(target_ids): + if target_id in signatures: + identity = _inconsistency_identity( + "signature", + "", + _measurement_signature(signatures[target_id], rule.signature_fields), + ) + identities.setdefault(identity, []).append(target_id) + lower_side = { + bridge.bridge_id: _contract_target_id(bridge.lower_side) + for bridge in rule.bridges + } + + def parent_of(leg: Mapping[str, Any]) -> int | None: + higher = leg["higher_target_ids"] + if len(higher) != 1: + return None + return controls.get((str(higher[0]), str(leg["parent_geography_id"]))) + + outcomes = [RowOutcome(value=value) for value in values] + for group in receipt["groups"]: + bridge_id = group["bridge_id"] + if bridge_id is None: + control = EXACT_SIGNATURE_CONTROL + lower_targets = identities.get( + group["inconsistency_id"].rsplit(":", 1)[0], [] + ) + else: + control = str(bridge_id) + lower_targets = [lower_side[bridge_id]] + for leg in group["legs"]: + parent = parent_of(leg) + for target_id in lower_targets: + for name in str(leg["leg"]).split("+"): + for position in lower.get( + (target_id, group["lower_grain"], name), () + ): + outcomes[position] = RowOutcome( + value=values[position], + status=RECONCILED, + control=control, + factor=float(leg["declared_factor"]), + lower_total=float(leg["old_total"]), + parent=parent, + ) + for leg in receipt.get("unbound_legs", ()): + parent = parent_of(leg) + for position in leg["positions"]: + outcomes[position] = RowOutcome( + value=values[position], + status=UNBOUND, + control=str(leg["bridge_id"]), + factor=float(leg["factor_on_input_totals"]), + parent=parent, + ) + return outcomes, receipt + + +# --------------------------------------------------------------------------- +# A derived control +# --------------------------------------------------------------------------- + + +def sum_of_lower_rows(values: Iterable[float]) -> float: + """A total that is the exactly rounded sum of its own lower rows.""" + + return math.fsum(float(value) for value in values) # --------------------------------------------------------------------------- -# Allocators +# Allocators (until the feed that holds their rows is pinned again) # --------------------------------------------------------------------------- +Allocation = tuple[np.ndarray, float, float] +Allocator = Callable[[np.ndarray, float], Allocation] + def proportional_fsum(raw_values: np.ndarray, parent_value: float) -> Allocation: """Each row times the control over the rows' exactly rounded sum. @@ -81,8 +236,7 @@ def share_residual_to_largest( rows' total; no single factor reproduces the rows. This allocator and :func:`scale_residual_to_largest` reproduce, bit for - bit, rows that were first made outside the operator. Stage B of - microcosm#1760 replaces the two with one allocator. + bit, rows that were first made outside the operator. """ if math.fsum(raw_values.tolist()) == 0.0: @@ -136,202 +290,3 @@ def allocator_named(name: str) -> Allocator: f"Unknown cross-grain allocator {name!r}; expected one of " f"{sorted(ALLOCATORS)}." ) from None - - -# --------------------------------------------------------------------------- -# Derived controls -# --------------------------------------------------------------------------- - - -def sum_of_lower_rows(values: Iterable[float]) -> float: - """A total that is the exactly rounded sum of its own lower rows.""" - - return math.fsum(float(value) for value in values) - - -def sibling_ratio(sibling_higher: float, sibling_lower: float) -> float: - """A sibling quantity's level in the higher source over the lower one's.""" - - return float(sibling_higher) / float(sibling_lower) - - -def scaled_by_sibling_ratio( - value: float, sibling_higher: float, sibling_lower: float -) -> tuple[float, float]: - """A lower-source level lifted onto the higher source's basis. - - Only the lower source publishes this quantity. A sibling quantity that - both sources publish at the same geography estimates the gap between - them. Returns ``(value * factor, factor)`` with the sibling's ratio as - the factor. The caller refuses a missing or zero sibling first. - """ - - factor = sibling_ratio(sibling_higher, sibling_lower) - return float(value) * factor, factor - - -# --------------------------------------------------------------------------- -# The factor band -# --------------------------------------------------------------------------- - - -def level_ratio(higher: float, lower: float) -> float: - """Two levels of one quantity as a ratio; ``NaN`` where none is defined. - - No ratio is defined against a zero lower level, or when the two levels - disagree on being positive. - """ - - higher, lower = float(higher), float(lower) - if lower != 0.0 and (higher > 0) == (lower > 0): - return higher / lower - return math.nan - - -def control_ratio( - control_value: float, lower_values: Iterable[float] -) -> tuple[float | None, float]: - """``(control / lower sum, lower sum)``, with the sum exactly rounded. - - The ratio is the factor :func:`proportional_fsum` gives the same rows. It - is ``None`` when the rows sum to zero. - """ - - lower_sum = sum_of_lower_rows(lower_values) - if lower_sum == 0.0: - return None, lower_sum - return float(control_value) / lower_sum, lower_sum - - -def median_by_group[Key: Hashable, Group: Hashable]( - ratios: Mapping[Key, float], - group_of: Callable[[Key], Group], - *, - positive_only: bool = False, -) -> dict[Group, float]: - """The median finite ratio of each group of keys. - - ``positive_only`` also leaves out ratios that are zero or negative. - """ - - grouped: dict[Group, list[float]] = {} - for key, ratio in ratios.items(): - if math.isfinite(ratio) and (ratio > 0 or not positive_only): - grouped.setdefault(group_of(key), []).append(ratio) - return {group: float(np.median(values)) for group, values in grouped.items()} - - -@dataclass(frozen=True) -class BandVerdict: - """One ratio judged against its group's median.""" - - ok: bool - ratio: float - median: float - relative: float - - -def band_verdict(ratio: float, median: float, band: float) -> BandVerdict: - """Whether ``ratio`` sits within ``band`` of ``median``, either way. - - ``relative`` is the ratio over the median. It is ``NaN``, and the verdict - fails, when the ratio is not finite or the median is zero or unknown. - """ - - relative = ratio / median if math.isfinite(ratio) and median else math.nan - ok = math.isfinite(relative) and 1 / band <= relative <= band - return BandVerdict(ok=ok, ratio=ratio, median=median, relative=relative) - - -# --------------------------------------------------------------------------- -# Completeness -# --------------------------------------------------------------------------- - - -@dataclass(frozen=True) -class LegCompleteness: - """A leg's present members against the members it must hold.""" - - missing: tuple - unexpected: tuple - duplicated: tuple - #: Absent member -> the present host whose row covers it. - merged: Mapping - - @property - def complete(self) -> bool: - return not (self.missing or self.unexpected or self.duplicated) - - -def leg_completeness[Member: Hashable]( - present: Iterable[Member], - expected: Iterable[Member], - *, - combined_cells: Mapping[Member, Member] | None = None, -) -> LegCompleteness: - """Compare the members a leg holds with the members it must hold. - - ``combined_cells`` maps a member that may be absent to its declared host. - An absent member is covered, not missing, when its host is present and - expected: the host's row then stands for both. - """ - - held = list(present) - held_set, expected_set = set(held), set(expected) - combined = dict(combined_cells or {}) - absent = expected_set - held_set - merged = { - member: combined[member] - for member in sorted(absent) - if member in combined - and combined[member] in held_set - and combined[member] in expected_set - } - seen: set = set() - duplicated = sorted( - {member for member in held if member in seen or seen.add(member)} - ) - return LegCompleteness( - missing=tuple(sorted(absent - merged.keys())), - unexpected=tuple(sorted(held_set - expected_set)), - duplicated=tuple(duplicated), - merged=merged, - ) - - -# --------------------------------------------------------------------------- -# Self-consistency -# --------------------------------------------------------------------------- - - -@dataclass(frozen=True) -class SumGap: - """The distance between a total and the sum of its lower rows.""" - - gap: float - scale: float - - @property - def relative(self) -> float: - return self.gap / self.scale - - def within(self, rtol: float) -> bool: - """The gap is at most ``rtol`` of the scale.""" - - return self.gap <= rtol * self.scale - - def exceeds(self, rtol: float) -> bool: - """The gap is more than ``rtol`` of the scale.""" - - return self.gap > rtol * self.scale - - -def sum_gap(total: float, lower_sum: float, *, floor: float = 1.0) -> SumGap: - """A total against the sum of its lower rows. - - The scale is the total's size, and at least ``floor``, so a total near - zero is judged on an absolute gap. - """ - - total = float(total) - return SumGap(gap=abs(total - lower_sum), scale=max(abs(total), floor)) diff --git a/packages/microcosm-build/src/microcosm/build/us/cross_grain_declarations.json b/packages/microcosm-build/src/microcosm/build/us/cross_grain_declarations.json index 8e99c4259a..ebf95db8c6 100644 --- a/packages/microcosm-build/src/microcosm/build/us/cross_grain_declarations.json +++ b/packages/microcosm-build/src/microcosm/build/us/cross_grain_declarations.json @@ -1,6 +1,6 @@ { "schema_version": 1, - "description": "US cross-grain nesting declarations (microcosm#1760). Each mechanism makes the rows of a lower geography level from a control at a higher level, on the shared operator microcosm.build.cross_grain, with the helpers of microcosm.build.cross_grain_controls. This file holds the US choices: the order of the levels, which levels hold controls, the allocator of each mechanism, the rule for its control, its bounds, the source of its member lists, and its reviewed registers with their reasons. Tools and tests read it through microcosm.build.us_runtime.cross_grain_declarations; the adapter is microcosm.build.us_runtime.target_nesting. Stage A changes no target value and decides no nesting rule: each mechanism is declared as the code ran it before the move. docs/us-target-nesting.md describes each mechanism.", + "description": "US cross-grain nesting declarations (microcosm#1760). A target for a small area must agree with the target of the area that contains it. This file holds the US choices of the shared operator microcosm.build.cross_grain, under the key names of uk/cross_grain_declarations.json where the meaning is the same: the order of the levels, the levels that hold controls, the bridges between two sources of one quantity (written as selectors, one entry for all the measures of a pair of sources), the pairs that are not reconciled, and the lower targets with no higher control. Tools and tests read it through microcosm.build.us_runtime.cross_grain_declarations; the adapter is microcosm.build.us_runtime.target_nesting. Target values are as they were before the operator made them; docs/us-target-nesting.md and docs/us-target-nesting-rule-design.md say what changes at the feed re-pin.", "grain_precedence": [ "country", "state", @@ -16,196 +16,217 @@ "filters" ], "bridges": [], - "partitions": [], - "mechanisms": { - "state_congressional_district_soi": { + "bridge_selectors": [ + { + "bridge_id": "historic_table_2_state_vs_district_file", "issue_row": 5, - "title": "State to congressional district, IRS SOI (--soi-mode state_cd)", - "tool_function": "tools/us_acs_local_cd_surface.py:state_cd_soi_surface", "family": "irs_soi", - "higher_grain": "state", - "lower_grain": "congressional_district", - "allocator": "proportional_fsum", - "vintage_rule": "state_cd.historic_table_2_level_cd_file_shares.v1", - "control": { - "kind": "bound_row_or_scaled_by_sibling_ratio", - "description": "Historic Table 2 (TY2022) is the single vintage of every state concept it carries, and its state row is the control. A concept only the district file carries keeps the district file's own state row as its control, lifted onto the Historic Table 2 basis by a sibling concept's ratio of the two files' state totals in the same state.", - "level_bridges": { - "description": "District-file-only concepts (Historic Table 2 lacks them) and the sibling concept whose two state levels bridge theirs onto the Historic Table 2 basis. The district file's own state levels sit below Historic Table 2's for two reasons: it covers only the returns processed in its window (about 1.7% fewer), and the feed stamps it one tax year late, so its amounts are aged one year less. A sibling both files carry, in the same state, estimates that gap, on the assumption that the measure shares the sibling's ratio: counts bridge by return_count (counts are not aged), amounts by the closest amount Historic Table 2 carries. The factor band applies to the sibling. The bridge is stamp-invariant: if the stamp is corrected (#1030) both levels move together.", - "siblings": { - "charitable_amount": "itemized_deductions_amount", - "charitable_returns": "return_count", - "interest_paid_deduction_amount": "itemized_deductions_amount", - "interest_paid_deduction_returns": "return_count", - "qualified_business_income_deduction_amount": "adjusted_gross_income", - "qualified_business_income_deduction_returns": "return_count" - } - } - }, - "factor_band": { - "tolerance": 1.25, - "on_out_of_band": "drop_block", - "description": "How far a state's Historic Table 2 / district-file ratio may sit from its measure's median across states before the district file's data for that (state, concept) is refused. The ratio mixes a common part (the file's coverage and aging gap, or a measure-wide rebase such as taxable interest's x2.47 onto Table 4.3), which the median absorbs, with a state-specific part. A state-specific part beyond 25% means the two publications disagree about that state (Hawaii's dividends differ 2.4x from the typical gap on the pinned feed), so the district file's shares, or a bridge built on that sibling, are not trusted: the block's district rows and any bridged state row are dropped and recorded; the Historic Table 2 state row stays." - }, - "self_consistency": { - "rtol": 1e-06, - "description": "The district file's own state row must equal the sum of its district rows to this relative tolerance wherever both are present (the receipt records the largest gap; the feed-gated contract test pins it on the pinned feed). A gap means a column or crosswalk defect inside the file (#1038 class), which no median absorbs." - }, - "closure": { - "rtol": 1e-09, - "description": "Relative tolerance for 'district rows sum to their state parent'. The rebase makes it exact up to float64 rounding." - }, - "members": { - "source": "congressional_district_vintage_crosswalk", - "reviewed_crosswalk_sha256": "a347303fff3fea145f758488c43cb94355df5a8cb5e512552b2ee3791d2aa233", - "single_member_legs": "dropped", - "description": "The 117th->119th congressional-district crosswalk the compiler used names each state's source-plan and current-plan districts. A district block must cover exactly the current plan's districts of its state. A state with one source-plan district is at-large there: the district file has no sub-state rows for it, so its district rows are dropped (at_large_on_source_plan). reviewed_crosswalk_sha256 is the packaged crosswalk the registers below were reviewed against; a test pins it, so regenerating the crosswalk forces a second look at them." - }, - "registers": { - "defective_lower_measures": { - "description": "District-file measures that read the wrong IRS column (microcosm#1038). The compiler's US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS drops these facts by (measure id, IRS column) before this surface sees them; this register stays as a second fence on the state_cd surface, at both geographies, and records the reason in the receipt.", - "entries": { - "limited_state_local_taxes_amount": "22incd.csv column A18425 is state and local income taxes (Schedule A line 5a), not the limited SALT deduction (A18460); the district file sums to 1.98x Historic Table 2 (microcosm#1038).", - "limited_state_local_taxes_returns": "22incd.csv column N18425 counts state and local income-tax deductions, not the limited SALT deduction (microcosm#1038).", - "premium_tax_credit_returns": "22incd.csv column N85530 is the additional Medicare tax (Form 8959 line 24), not the premium tax credit (N85770) (microcosm#1038)." - } - }, - "unparented_lower_measures": { - "description": "District-file measures with no state parent in either vintage, so their district rows could not nest in a bound state target.", - "entries": { - "tax_filer_individual_count": "The compiler drops this measure at state and national geography (fiscal_targets._soi_reference_from_fact), so no state target exists for its district rows to reconcile to." - } - }, - "excluded_legs": { - "description": "States whose district SOI rows stay off the surface, with the evidence. Empty since #1043 rebuilt the 117th->119th crosswalk from the block plan registry: the packaged crosswalk before it (sha256 c7cb040b...) carried North Carolina's 2016 plan instead of the 2019 plan the 117th Congress used, and 37.0% of NC's population mapped to a different 119th district, so NC's district rows were held off until then.", - "entries": {} - } + "concept": "irs_soi", + "higher": { + "source": "state_surface", + "grain": "state" }, - "metadata_keys": { - "lower_rows": [ - "state_cd_vintage_rule", - "state_cd_parent_target_name", - "state_cd_parent_basis", - "state_cd_parent_value", - "state_cd_cd_file_value", - "state_cd_cd_file_state_sum", - "state_cd_rebase_factor" - ], - "derived_controls": [ - "state_cd_vintage_rule", - "state_cd_cd_file_value", - "state_cd_level_bridge_sibling", - "state_cd_level_bridge_cd_file_sibling", - "state_cd_level_bridge_factor" - ] - }, - "receipt": "materialize_rss.json: soi_surface" - }, - "state_county_population": { - "issue_row": 8, - "title": "State to county, resident population (PUMA ladder)", - "tool_function": "tools/us_acs_local_county_surface.py:with_county_populations", - "family": "census_population", - "higher_grain": "state", - "lower_grain": "county", - "allocator": "scale_residual_to_largest", - "control": { - "kind": "bound_row", - "description": "The state total from the 2020 PUMA ladder. The county rows are the ladder's (PUMA, county) population overlaps, summed by county and scaled to the state total; the rounding residual goes to the largest county, never a small one." - }, - "members": { - "source": "us_puma_ladder_county_overlaps", - "description": "Every county of the ladder's overlaps, on the boundaries of the county column (county_fips: 2020 counties; county_fips_2023: Connecticut's planning regions, from the tract overlaps). A state with no positive county or state population is refused, and so is a county with no state." + "lower": { + "source": "lower_file", + "grain": "congressional_district" }, - "metadata_keys": { - "lower_rows": [] - }, - "receipt": "none before microcosm#1760" + "pair_on": [ + "identity" + ], + "max_factor_shift": 0.25, + "min_factor_shift": -0.2, + "shift_around": "median", + "out_of_bound": "unbind", + "vintage_rule": "state_cd.historic_table_2_level_cd_file_shares.v1", + "reason": "Historic Table 2 (TY2022) is the single vintage of every state concept it carries, and its state row is the control. The district file (22incd.csv) gives each district's share of its state: its district rows are divided from that control. The two files differ by a gap that every state shares (the district file covers only the returns processed in its window, and the feed ages it one year less; taxable interest also has a measure-wide rebase), so the bound is around the median factor across states. A state whose factor is more than 25% from that median means that the two publications disagree about that state: its district rows are unbound and recorded, and the Historic Table 2 state row stays." }, - "state_county_soi": { + { + "bridge_id": "state_soi_vs_county_file", "issue_row": 6, - "title": "State to county, IRS SOI (--soi-mode state_county)", - "tool_function": "tools/us_acs_local_county_surface.py:state_county_soi_surface", "family": "irs_soi", - "higher_grain": "state", - "lower_grain": "county", - "allocator": "share_residual_to_largest", - "control": { - "kind": "bound_row", - "description": "The broad state row that already exists on the state surface: all returns, no AGI class, no filing status. County SOI facts supply shares, never a second state level." - }, + "concept": "irs_soi", + "higher": { + "source": "state_surface", + "grain": "state" + }, + "lower": { + "source": "county_file", + "grain": "county" + }, + "pair_on": [ + "source_measure_id", + "source_period" + ], "required_measures": [ "return_count", "adjusted_gross_income" ], - "members": { - "source": "us_puma_ladder_county_populations", - "description": "Every county of the state in the ladder's county populations. A county absent from a block is refused unless combined_cells declares it with its host present: then one child row covers both counties.", - "combined_cells": [ - { - "absent": "15005", - "host": "15009" - } - ], - "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.", - "combined_cell_description": "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." - }, - "metadata_keys": { - "lower_rows": [ - "state_county_parent_target_name", - "state_county_share", - "state_county_source_value", - "county_population", - "state_population", - "state_county_cell_members", - "state_county_cell_basis" - ] - }, - "receipt": "county_surface.json" - }, - "county_state_acs_households": { + "reason": "The broad state row that exists on the state surface (all returns, no AGI class, no filing status) is the control. County SOI facts supply shares, never a second state level. Return count and adjusted gross income must have a state row in every state." + } + ], + "derived_controls": [ + { + "bridge_id": "acs_households_state_is_the_county_sum", "issue_row": 7, - "title": "County to state, ACS households (--soi-mode state_county)", - "tool_function": "tools/us_acs_local_county_surface.py:acs_household_surface", "family": "acs_households", + "derive": "sum_of_lower_rows", "higher_grain": "state", "lower_grain": "county", - "allocator": "share_residual_to_largest", - "control": { - "kind": "sum_of_lower_rows", - "description": "The children make the parent: each state's households target is the sum of its counties' ACS 5-year B11001_001E estimates, a new state target. The county rows then divide it by county share, so they sum to it." - }, - "members": { - "source": "us_puma_ladder_county_populations", - "description": "Every county of the ladder's county populations must carry an estimate; a missing or unexpected county is refused." - }, - "metadata_keys": { - "lower_rows": [ - "state_county_parent_target_name", - "state_county_share", - "state_county_source_value", - "county_population", - "state_population" - ], - "derived_controls": [ - "acs_state_parent_basis", - "new_state_target" - ] - }, - "receipt": "county_surface.json: acs_households" + "reason": "The children make the parent: each state's households target is the sum of its counties' ACS 5-year B11001_001E estimates, a new state target. The county rows then divide it by county share, so they sum to it." + } + ], + "same_measurement": [ + { + "id": "ladder_population_state_vs_county", + "issue_row": 8, + "family": "census_population", + "higher_grain": "state", + "lower_grain": "county", + "reason": "The state total from the 2020 PUMA ladder. The county rows are the ladder's (PUMA, county) population overlaps, summed by county and scaled to the state total; the rounding residual goes to the largest county, never a small one. One source at two levels has one measurement, so nothing else is declared." + } + ], + "partitions": [], + "relations": [ + { + "targets": [ + "usda_snap.snap_total@state", + "usda_snap.snap_total@country" + ], + "relation": "subset", + "part": "usda_snap.snap_total@state", + "whole": "usda_snap.snap_total@country", + "reason": "Cells of one publication of one fiscal year. The state rows are the 50 states and DC; they sum to 0.998 of the national row on the pinned feed, and are not scaled to it." + }, + { + "targets": [ + "usda_snap.snap_households@state", + "usda_snap.snap_households@country" + ], + "relation": "subset", + "part": "usda_snap.snap_households@state", + "whole": "usda_snap.snap_households@country", + "reason": "Cells of one publication of one fiscal year. The state rows sum to 0.999 of the national row on the pinned feed, and are not scaled to it." + }, + { + "targets": [ + "cms_medicaid.medicaid_enrollment@state", + "cms_medicaid.medicaid_enrollment@country" + ], + "relation": "subset", + "part": "cms_medicaid.medicaid_enrollment@state", + "whole": "cms_medicaid.medicaid_enrollment@country", + "max_excess": 0.01, + "reason": "Cells of one publication. The state rows sum to 1.0038 of the national row on the pinned feed (one state's row is from another month); the cause is not established, so the pair is declared with an allowance and is not scaled." + }, + { + "targets": [ + "cms_medicaid.medicaid_chip_enrollment@state", + "cms_medicaid.medicaid_chip_enrollment@country" + ], + "relation": "subset", + "part": "cms_medicaid.medicaid_chip_enrollment@state", + "whole": "cms_medicaid.medicaid_chip_enrollment@country", + "max_excess": 0.001, + "reason": "Cells of one publication. The 50 state rows sum to the national row on the pinned feed." + }, + { + "targets": [ + "cms_medicaid.chip_enrollment@state", + "cms_medicaid.chip_enrollment@country" + ], + "relation": "subset", + "part": "cms_medicaid.chip_enrollment@state", + "whole": "cms_medicaid.chip_enrollment@country", + "reason": "Only 31 states bind a CHIP row: a reviewed rule drops the 20 M-CHIP states. Scaling the present states to the national row would give them the mass of the missing ones." + }, + { + "targets": [ + "hhs_acf_tanf.tanf_total@state", + "hhs_acf_tanf.tanf_total@country" + ], + "relation": "subset", + "part": "hhs_acf_tanf.tanf_total@state", + "whole": "hhs_acf_tanf.tanf_total@country", + "reason": "Only 29 states bind a TANF row. Scaling them to the national row would give them the mass of the missing ones." + } + ], + "local_routes": { + "cms_aca@state": { + "route": "no_higher_control", + "reason": "The compiled registry holds the ACA marketplace rows at state level only: no national row of the family binds." + }, + "state_income_tax@state": { + "route": "no_higher_control", + "reason": "The compiled registry holds the state income tax rows at state level only: no national row of the family binds." + }, + "ssa@state": { + "route": "no_higher_control", + "reason": "The state rows are SSI recipients and state payments by state. No national row of the same role binds." } }, - "inventory": { - "description": "What the code does today, as data. It decides no rule: the decisions of microcosm#1760 (which level holds the level value of a family, two sources at two levels, the direction of the county households rows, the parent row in the loss, the factor bound, children that are not complete) are open, and Stage B applies them. How each US family that two geography levels measure gets its lower level from its higher one, or why it does not. An entry names a family, its lower levels and the higher level, and one route: 'mechanism' (the shared cross-grain operator makes the rows; mechanisms above), 'compile_rule' (a pass of the compile makes them and stays where it is in Stage A, with the reason), 'same_source' (both levels are sums of one source's cells), 'no_higher_control' (no row at a higher level measures the quantity), 'not_reconciled' (two levels measure it and no rule ties them yet, with the reason and the issue) or 'not_in_the_fit' (the rows are not compiled). 'compiled' says whether the compiled registry of the pinned feed holds the rows; 'marker' names the metadata that the rule writes on them. The coverage test reads this section; it refuses nothing in a build.", - "routes": [ - "mechanism", - "compile_rule", - "same_source", - "no_higher_control", - "not_reconciled", - "not_in_the_fit" - ], - "entries": [ + "members": { + "congressional_district": { + "source": "congressional_district_vintage_crosswalk", + "reviewed_crosswalk_sha256": "a347303fff3fea145f758488c43cb94355df5a8cb5e512552b2ee3791d2aa233", + "single_member_legs": "not bound", + "description": "The 117th->119th congressional-district crosswalk the compiler used names each state's source-plan and current-plan districts. A district block must cover exactly the current plan's districts of its state. A state with one source-plan district is at-large there: the district file has no sub-state rows for it, so its district rows are dropped (at_large_on_source_plan). reviewed_crosswalk_sha256 is the packaged crosswalk the registers below were reviewed against; a test pins it, so regenerating the crosswalk forces a second look at them." + }, + "county": { + "source": "us_puma_ladder_county_populations", + "description": "Every county of the state in the ladder's county populations. A county absent from a block is refused unless combined_cells declares it with its host present: then one child row covers both counties.", + "combined": [ + { + "bridge_id": "state_soi_vs_county_file", + "absent": "15005", + "host": "15009", + "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.", + "description": "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." + } + ] + } + }, + "registers": { + "description": "Which rows of the district file enter the surface. These are choices of selection, not of nesting; each entry has its reason.", + "defective_lower_measures": { + "description": "District-file measures that read the wrong IRS column (microcosm#1038). The compiler's US_FISCAL_TARGET_SOURCE_COLUMN_EXCLUSIONS drops these facts by (measure id, IRS column) before this surface sees them; this register stays as a second fence on the state_cd surface, at both geographies, and records the reason in the receipt.", + "entries": { + "limited_state_local_taxes_amount": "22incd.csv column A18425 is state and local income taxes (Schedule A line 5a), not the limited SALT deduction (A18460); the district file sums to 1.98x Historic Table 2 (microcosm#1038).", + "limited_state_local_taxes_returns": "22incd.csv column N18425 counts state and local income-tax deductions, not the limited SALT deduction (microcosm#1038).", + "premium_tax_credit_returns": "22incd.csv column N85530 is the additional Medicare tax (Form 8959 line 24), not the premium tax credit (N85770) (microcosm#1038)." + } + }, + "unparented_lower_measures": { + "description": "District-file measures with no state parent in either vintage, so their district rows could not nest in a bound state target.", + "entries": { + "tax_filer_individual_count": "The compiler drops this measure at state and national geography (fiscal_targets._soi_reference_from_fact), so no state target exists for its district rows to reconcile to." + } + }, + "excluded_legs": { + "description": "States whose district SOI rows stay off the surface, with the evidence. Empty since #1043 rebuilt the 117th->119th crosswalk from the block plan registry: the packaged crosswalk before it (sha256 c7cb040b...) carried North Carolina's 2016 plan instead of the 2019 plan the 117th Congress used, and 37.0% of NC's population mapped to a different 119th district, so NC's district rows were held off until then.", + "entries": {} + } + }, + "until_the_feed_repin": { + "description": "What stays only until Microcosm re-pins its feed after PolicyEngine/chronicle#451. Then the operator's own rule divides every control, Historic Table 2 holds the six parents, and rows 1 to 4 and the known gaps get their ruled treatment (docs/us-target-nesting-rule-design.md).", + "allocators": { + "historic_table_2_state_vs_district_file": "proportional_fsum", + "state_soi_vs_county_file": "share_residual_to_largest", + "acs_households_state_is_the_county_sum": "share_residual_to_largest", + "ladder_population_state_vs_county": "scale_residual_to_largest" + }, + "level_bridges": { + "description": "District-file-only concepts (Historic Table 2 lacks them) and the sibling concept whose two state levels bridge theirs onto the Historic Table 2 basis. The district file's own state levels sit below Historic Table 2's for two reasons: it covers only the returns processed in its window (about 1.7% fewer), and the feed stamps it one tax year late, so its amounts are aged one year less. A sibling both files carry, in the same state, estimates that gap, on the assumption that the measure shares the sibling's ratio: counts bridge by return_count (counts are not aged), amounts by the closest amount Historic Table 2 carries. The factor band applies to the sibling. The bridge is stamp-invariant: if the stamp is corrected (#1030) both levels move together.", + "siblings": { + "charitable_amount": "itemized_deductions_amount", + "charitable_returns": "return_count", + "interest_paid_deduction_amount": "itemized_deductions_amount", + "interest_paid_deduction_returns": "return_count", + "qualified_business_income_deduction_amount": "adjusted_gross_income", + "qualified_business_income_deduction_returns": "return_count" + } + }, + "closure_rtol": 1e-09, + "compile_rules": [ { "id": "soi_capital_gains_shares_of_national_control", "issue_row": 1, @@ -215,13 +236,10 @@ "congressional_district" ], "higher_level": "country", - "route": "compile_rule", - "compiled": true, "code": "microcosm.build.us_runtime.fiscal_targets._rebase_stale_soi_capital_gains_distributions", "marker": { "metadata_key": "soi_control_concept" }, - "level_holder": "country: the Table 1.4 national control at or after the row's period", "reason": "Each Historic Table 2 or district-file capital-gains row ships as its share of its own family's national total, scaled to the control: one factor for each family, quantity and period. A row with no control is dropped. It stays in the compile because it is another operation than the operator's: every row takes one factor, control / published national total, the rows are not scaled to sum to the control, and the control and the total are read from the facts, not from rows of the registry. The operator divides a control that is a row of its surface.", "issues": [ "microcosm#1035", @@ -237,14 +255,11 @@ "congressional_district" ], "higher_level": "country", - "route": "compile_rule", - "compiled": true, "code": "microcosm.build.us_runtime.fiscal_targets._rebase_stale_soi_taxable_interest_distributions", "marker": { "metadata_key": "uprating_index", "value_prefix": "total_taxable_interest_" }, - "level_holder": "country: the latest Pub 1304 national value", "reason": "Every stale Historic Table 2 taxable-interest row is multiplied by one national factor onto the latest national value; the TY2022 shares across states stay. It stays in the compile for the reason of row 1: one factor from the facts, no scaling of rows to a control row.", "issues": [ "microcosm#489" @@ -258,13 +273,10 @@ "state" ], "higher_level": "state", - "route": "compile_rule", - "compiled": true, "code": "microcosm.build.us_runtime.fiscal_targets._rebase_soi_state_agi_bands", "marker": { "metadata_key": "state_agi_band_share" }, - "level_holder": "state: the all-returns row that binds", "reason": "A partition inside one area, not a relation between levels: each flagged AGI band becomes control x band / published partition. The partition is the sum of the state's published bands over the whole AGI line, read from the facts, and only the bands from the $100k floor up bind. It stays in the compile because the operator's partitions need every member on the surface.", "issues": [ "microcosm#940" @@ -278,113 +290,18 @@ "congressional_district" ], "higher_level": "state", - "route": "compile_rule", - "compiled": true, "code": "microcosm.build.ledger_targets.reconcile_ledger_target_hierarchy, declared in us/fiscal_target_references.json (congressional_district_children_scale_to_state_parent)", "marker": { "metadata_key": "hierarchy_reconciliation_rule", "value": "congressional_district_children_scale_to_state_parent" }, - "level_holder": "state: the district file's own state row", "reason": "A second shared rule for the same job, with its rule as data: the district rows of the district file are scaled to sum to that file's own state row, and a missing district fails the compile. It stays where it is in Stage A because it sums with the builtin sum, formats its factor with 15 significant digits and writes its own hierarchy_* keys, and the bytes of the full and state_cd surfaces depend on all three. Folding it into the operator is a Stage B step or a consolidation issue.", "issues": [ "microcosm#1760" ] - }, - { - "id": "soi_district_shares_of_historic_table_2_state", - "issue_row": 5, - "family": "irs_soi", - "levels": [ - "congressional_district" - ], - "higher_level": "state", - "route": "mechanism", - "mechanism": "state_congressional_district_soi", - "compiled": true, - "surfaces": [ - "state_cd" - ], - "level_holder": "state: the Historic Table 2 state row, or the district file's state row lifted by a sibling ratio", - "issues": [ - "microcosm#1760", - "microcosm#1731" - ] - }, - { - "id": "soi_county_shares_of_state", - "issue_row": 6, - "family": "irs_soi", - "levels": [ - "county" - ], - "higher_level": "state", - "route": "mechanism", - "mechanism": "state_county_soi", - "compiled": false, - "surfaces": [ - "state_county" - ], - "level_holder": "state: the broad state row that exists", - "issues": [ - "microcosm#922", - "microcosm#1760" - ] - }, - { - "id": "acs_households_state_is_the_county_sum", - "issue_row": 7, - "family": "acs_households", - "levels": [ - "county" - ], - "higher_level": "state", - "route": "mechanism", - "mechanism": "county_state_acs_households", - "compiled": false, - "surfaces": [ - "state_county" - ], - "level_holder": "county: the state target is the sum of the county estimates", - "issues": [ - "microcosm#922", - "microcosm#1760" - ] - }, - { - "id": "ladder_county_population_scaled_to_state", - "issue_row": 8, - "family": "census_population", - "levels": [ - "county" - ], - "higher_level": "state", - "route": "mechanism", - "mechanism": "state_county_population", - "compiled": false, - "surfaces": [ - "state_county" - ], - "level_holder": "state: the total of the 2020 PUMA ladder", - "issues": [ - "microcosm#922", - "microcosm#1760" - ] - }, - { - "id": "ladder_state_and_district_population_from_one_ladder", - "family": "census_population_ladder", - "levels": [ - "congressional_district" - ], - "higher_level": "state", - "route": "same_source", - "compiled": false, - "reason": "The state and district population totals of the local build are sums of the cells of one 2020 PUMA ladder. No rule runs.", - "issues": [ - "microcosm#1760" - ] - }, + } + ], + "known_gaps": [ { "id": "soi_state_rows_under_two_national_rows", "family": "irs_soi", @@ -392,8 +309,6 @@ "state" ], "higher_level": "country", - "route": "not_reconciled", - "compiled": true, "reason": "Several SOI families bind a Historic Table 2 US row beside a newer Table 1.x row, and no rule ties their state rows to either. Rows 1 and 2 are the treatment that the issue asks for the others. It waits for Stage A.", "issues": [ "microcosm#1243" @@ -406,112 +321,12 @@ "state" ], "higher_level": "country", - "route": "not_reconciled", - "compiled": true, "reason": "The national build fits Census age bands for each state. The local build fits state totals from the 2020 ladder and no age row. No rule ties the age rows of a state to its total, or to the national age rows.", "issues": [ "microcosm#1528", "microcosm#1526", "microcosm#1531" ] - }, - { - "id": "usda_snap_state_rows_and_national_row", - "family": "usda_snap", - "levels": [ - "state" - ], - "higher_level": "country", - "route": "not_reconciled", - "compiled": true, - "reason": "Not checked yet: whether the state rows of SNAP sum to the national row of the family. No rule ties them.", - "issues": [ - "microcosm#1760" - ] - }, - { - "id": "cms_medicaid_state_rows_and_national_row", - "family": "cms_medicaid", - "levels": [ - "state" - ], - "higher_level": "country", - "route": "not_reconciled", - "compiled": true, - "reason": "Not checked yet: whether the state rows of Medicaid and CHIP sum to the national row of the family. No rule ties them.", - "issues": [ - "microcosm#1760" - ] - }, - { - "id": "ssa_state_rows_and_national_row", - "family": "ssa", - "levels": [ - "state" - ], - "higher_level": "country", - "route": "not_reconciled", - "compiled": true, - "reason": "Not checked yet: whether the state rows of SSI sum to the national row of the family. No rule ties them.", - "issues": [ - "microcosm#1760" - ] - }, - { - "id": "hhs_acf_tanf_state_rows_and_national_row", - "family": "hhs_acf_tanf", - "levels": [ - "state" - ], - "higher_level": "country", - "route": "not_reconciled", - "compiled": true, - "reason": "Not checked yet: whether the state rows of TANF sum to the national row of the family. No rule ties them.", - "issues": [ - "microcosm#1760" - ] - }, - { - "id": "cms_aca_state_rows_have_no_national_row", - "family": "cms_aca", - "levels": [ - "state" - ], - "higher_level": "country", - "route": "no_higher_control", - "compiled": true, - "reason": "The compiled registry holds the ACA marketplace rows at state level only: no national row of the family binds.", - "issues": [ - "microcosm#1760" - ] - }, - { - "id": "state_income_tax_state_rows_have_no_national_row", - "family": "state_income_tax", - "levels": [ - "state" - ], - "higher_level": "country", - "route": "no_higher_control", - "compiled": true, - "reason": "The compiled registry holds the state income tax rows at state level only: no national row of the family binds.", - "issues": [ - "microcosm#1760" - ] - }, - { - "id": "acs_district_age_and_households", - "family": "census_acs", - "levels": [ - "congressional_district" - ], - "higher_level": "state", - "route": "not_in_the_fit", - "compiled": false, - "reason": "District age and household rows from ACS are not in the fit. Their state parent would come from another source: the districts from a survey, the states from the Census estimates.", - "issues": [ - "microcosm#1731" - ] } ] } diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/cross_grain_declarations.py b/packages/microcosm-build/src/microcosm/build/us_runtime/cross_grain_declarations.py index cff3e9f8f8..1ddef62d5c 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/cross_grain_declarations.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/cross_grain_declarations.py @@ -1,22 +1,25 @@ """US cross-grain nesting declarations (microcosm#1760). -``us/cross_grain_declarations.json`` holds every US choice the shared -cross-grain operator (:mod:`microcosm.build.cross_grain`) and its helpers -(:mod:`microcosm.build.cross_grain_controls`) need: the order of the geography -levels, the levels that hold controls, and, for each mechanism that makes the -rows of a lower level from a control at a higher one, its allocator, the rule -for its control, its bounds, the source of its member lists and its reviewed -registers with their reasons. The key names follow -``uk/cross_grain_declarations.json`` wherever the meaning is the same. - -The file's ``inventory`` lists each US family that two geography levels -measure, with the route that ties the levels or the reason none does. +``us/cross_grain_declarations.json`` holds the US choices of the shared +cross-grain operator (:mod:`microcosm.build.cross_grain`), under the key names +of ``uk/cross_grain_declarations.json`` where the meaning is the same: + +- ``grain_precedence``, ``control_grains``, ``signature_fields``; +- ``bridge_selectors``: the bridges between two sources of one quantity, one + entry for all the measures of a pair of sources; +- ``derived_controls``: a control that no source publishes as one row; +- ``same_measurement``: one source at two levels, where nothing else is + declared; +- ``relations`` and ``local_routes``: the pairs that are not reconciled and + the lower targets with no higher control, each with a reason; +- ``members`` and ``registers``: what each leg must hold, and which rows of + a source enter the surface; +- ``until_the_feed_repin``: what goes when the feed is re-pinned. + +This module reads the file and hands out typed views of it. :func:`us_cross_grain_coverage_violations` checks a set of compiled specs against it. That check is a receipt and a test of the declaration: no build -calls it and it refuses nothing. - -This module reads the file and hands out typed views of it. It does no -arithmetic on targets; the adapter that runs the operator is +calls it and it refuses nothing. The adapter that runs the operator is :mod:`microcosm.build.us_runtime.target_nesting`. """ @@ -24,36 +27,26 @@ import functools import json +import math from collections.abc import Iterable, Mapping from dataclasses import dataclass from importlib import resources as importlib_resources from typing import Any +from microcosm.build.cross_grain import CrossGrainBridgeSelector from microcosm.build.cross_grain_controls import ALLOCATORS US_CROSS_GRAIN_DECLARATIONS_RESOURCE = "cross_grain_declarations.json" -#: The mechanisms of the issue's rows 5 to 8, by their declared id. -DISTRICT_SOI = "state_congressional_district_soi" -COUNTY_POPULATION = "state_county_population" -COUNTY_SOI = "state_county_soi" -COUNTY_ACS_HOUSEHOLDS = "county_state_acs_households" - -_CONTROL_KINDS = ( - "bound_row", - "bound_row_or_scaled_by_sibling_ratio", - "sum_of_lower_rows", -) -#: Inventory routes that need a written reason. -_REASONED_ROUTES = frozenset( - { - "compile_rule", - "same_source", - "no_higher_control", - "not_reconciled", - "not_in_the_fit", - } -) +#: The four passes of the local build, by their declared id. +DISTRICT_SOI = "historic_table_2_state_vs_district_file" +COUNTY_SOI = "state_soi_vs_county_file" +COUNTY_ACS_HOUSEHOLDS = "acs_households_state_is_the_county_sum" +COUNTY_POPULATION = "ladder_population_state_vs_county" + +_RELATION_KINDS = ("subset", "independent") +_LOCAL_ROUTE_KINDS = ("no_higher_control",) +_DERIVATIONS = ("sum_of_lower_rows",) @functools.lru_cache(maxsize=1) @@ -70,251 +63,243 @@ def load_us_cross_grain_declarations() -> Mapping[str, Any]: "US cross-grain declarations schema_version must be 1, got " f"{payload.get('schema_version')!r}." ) + _validate(payload) + return payload + + +def _validate(payload: Mapping[str, Any]) -> None: grains = tuple(payload["grain_precedence"]) - unknown_controls = [g for g in payload["control_grains"] if g not in grains] + controls = tuple(payload["control_grains"]) + unknown_controls = [grain for grain in controls if grain not in grains] if unknown_controls: raise ValueError( f"US cross-grain control_grains {unknown_controls} are not in " "grain_precedence." ) - for mechanism_id, mechanism in payload["mechanisms"].items(): - higher, lower = mechanism["higher_grain"], mechanism["lower_grain"] + + def nests(pass_id: str, higher: object, lower: object) -> None: if ( - higher not in payload["control_grains"] + higher not in controls or lower not in grains or grains.index(higher) >= grains.index(lower) ): raise ValueError( - f"US cross-grain mechanism {mechanism_id!r} must name a control " - f"grain above its lower grain, got {higher!r} over {lower!r}." + f"US cross-grain pass {pass_id!r} must name a control grain " + f"above its lower grain, got {higher!r} over {lower!r}." ) - if mechanism["allocator"] not in ALLOCATORS: + + pass_ids: list[str] = [] + for selector in payload["bridge_selectors"]: + nests( + selector["bridge_id"], + selector["higher"].get("grain"), + selector["lower"].get("grain"), + ) + if not selector["pair_on"] or not str(selector.get("reason", "")).strip(): raise ValueError( - f"US cross-grain mechanism {mechanism_id!r} names unknown " - f"allocator {mechanism['allocator']!r}; expected one of " - f"{sorted(ALLOCATORS)}." + f"US cross-grain bridge selector {selector['bridge_id']!r} must " + "name what its sides are paired on, and give a reason." ) - if mechanism["control"]["kind"] not in _CONTROL_KINDS: + pass_ids.append(selector["bridge_id"]) + for derived in payload["derived_controls"]: + nests(derived["bridge_id"], derived["higher_grain"], derived["lower_grain"]) + if derived["derive"] not in _DERIVATIONS: raise ValueError( - f"US cross-grain mechanism {mechanism_id!r} names unknown " - f"control kind {mechanism['control']['kind']!r}; expected one " - f"of {_CONTROL_KINDS}." + f"US cross-grain derived control {derived['bridge_id']!r} names " + f"unknown derivation {derived['derive']!r}; expected one of " + f"{_DERIVATIONS}." ) - _validate_inventory(payload) - return payload - - -def _validate_inventory(payload: Mapping[str, Any]) -> None: - """Refuse an inventory entry that names no route, level or reason.""" - - grains = tuple(payload["grain_precedence"]) - inventory = payload["inventory"] - routes = tuple(inventory["routes"]) - seen: set[str] = set() - for entry in inventory["entries"]: - entry_id = str(entry.get("id", "")) - if not entry_id or entry_id in seen: + pass_ids.append(derived["bridge_id"]) + for same in payload["same_measurement"]: + nests(same["id"], same["higher_grain"], same["lower_grain"]) + pass_ids.append(same["id"]) + if len(set(pass_ids)) != len(pass_ids): + raise ValueError(f"US cross-grain pass ids repeat: {sorted(pass_ids)}.") + allocators = payload["until_the_feed_repin"]["allocators"] + for pass_id, name in allocators.items(): + if pass_id not in pass_ids or name not in ALLOCATORS: raise ValueError( - f"US cross-grain inventory entry id {entry_id!r} is blank or repeated." + f"US cross-grain allocator {name!r} for {pass_id!r} must name a " + f"declared pass and one of {sorted(ALLOCATORS)}." ) - seen.add(entry_id) - levels = tuple(entry.get("levels") or ()) - higher = entry.get("higher_level") + for relation in payload["relations"]: + targets = [str(target) for target in relation["targets"]] + subset_sides = {str(relation.get("part")), str(relation.get("whole"))} if ( - not entry.get("family") - or not levels - or any(level not in grains for level in levels) - or higher not in grains - or any(grains.index(higher) > grains.index(level) for level in levels) + len(targets) != 2 + or relation.get("relation") not in _RELATION_KINDS + or (relation["relation"] == "subset" and subset_sides != set(targets)) + or not str(relation.get("reason", "")).strip() ): raise ValueError( - f"US cross-grain inventory entry {entry_id!r} must name a " - "family, its levels and a higher level that is not below them." - ) - route = entry.get("route") - if route not in routes: - raise ValueError( - f"US cross-grain inventory entry {entry_id!r} names unknown " - f"route {route!r}; expected one of {routes}." + f"US cross-grain relation over {targets} is malformed: it needs " + f"two targets, one of {_RELATION_KINDS}, a part and a whole for " + "a subset, and a reason." ) - if not isinstance(entry.get("compiled"), bool) or not entry.get("issues"): + for target in targets: + _relation_target(target, grains) + for target, route in payload["local_routes"].items(): + _route_target(target, grains) + if ( + route.get("route") not in _LOCAL_ROUTE_KINDS + or not str(route.get("reason", "")).strip() + ): raise ValueError( - f"US cross-grain inventory entry {entry_id!r} must say whether " - "its rows are compiled and name an issue." + f"US cross-grain local route {target!r} must be one of " + f"{_LOCAL_ROUTE_KINDS} with a reason." ) - if route == "mechanism": - mechanism = payload["mechanisms"].get(entry.get("mechanism")) - if ( - mechanism is None - or mechanism["issue_row"] != entry.get("issue_row") - or mechanism["family"] != entry["family"] - or (mechanism["lower_grain"],) != levels - or mechanism["higher_grain"] != higher - ): - raise ValueError( - f"US cross-grain inventory entry {entry_id!r} does not " - "match the mechanism it names." - ) - elif route in _REASONED_ROUTES and not str(entry.get("reason", "")).strip(): + transitional = payload["until_the_feed_repin"] + for entry in (*transitional["compile_rules"], *transitional["known_gaps"]): + levels = tuple(entry.get("levels") or ()) + if ( + not entry.get("id") + or not entry.get("family") + or not levels + or any(level not in grains for level in levels) + or not str(entry.get("reason", "")).strip() + or not entry.get("issues") + ): raise ValueError( - f"US cross-grain inventory entry {entry_id!r} has route " - f"{route!r} and no reason." + f"US cross-grain entry {entry.get('id')!r} must name a family, " + "its levels, a reason and an issue." ) - if route == "compile_rule" and not (entry.get("code") and entry.get("marker")): + for rule in transitional["compile_rules"]: + if not rule.get("code") or not rule.get("marker"): raise ValueError( - f"US cross-grain inventory entry {entry_id!r} must name the " - "compile rule's code and the marker it writes." + f"US cross-grain compile rule {rule['id']!r} must name its code " + "and the marker it writes." ) -def us_cross_grain_inventory() -> tuple[Mapping[str, Any], ...]: - """The inventory entries, in declared order.""" - - return tuple(load_us_cross_grain_declarations()["inventory"]["entries"]) +def _relation_target(target: str, grains: tuple[str, ...]) -> tuple[str, str, str]: + """``family.role@level`` as ``(family, role, level)``.""" + name, _, level = target.partition("@") + family, _, role = name.partition(".") + if not family or not role or level not in grains: + raise ValueError( + f"US cross-grain relation target {target!r} must read " + "family.role@level, with a declared level." + ) + return family, role, level -def _marker_matches(marker: Mapping[str, Any], metadata: Mapping[str, Any]) -> bool: - value = metadata.get(str(marker["metadata_key"])) - if value is None: - return False - if "value" in marker: - return str(value) == str(marker["value"]) - if "value_prefix" in marker: - return str(value).startswith(str(marker["value_prefix"])) - return True +def _route_target(target: str, grains: tuple[str, ...]) -> tuple[str, str]: + """``family@level`` as ``(family, level)``.""" -def us_cross_grain_coverage_violations( - specs: Iterable[Any], - *, - level_key: str = "ledger_geography_level", -) -> list[dict[str, str]]: - """Every gap between a set of compiled specs and the inventory. + family, _, level = target.partition("@") + if not family or level not in grains: + raise ValueError( + f"US cross-grain local route {target!r} must read family@level, " + "with a declared level." + ) + return family, level - ``specs`` are compiled target specs (anything with ``family`` and - ``metadata``). The top level of ``grain_precedence`` nests in nothing. A - violation is one of: - * ``family_level_without_route``: a family has rows at a lower level and - no inventory entry names that family and level; - * ``stale_inventory_entry``: an entry says its rows are compiled, and the - specs hold none at one of its levels; - * ``compile_rule_marker_absent``: a compile rule's marker is on no row of - one of its declared levels. +# --------------------------------------------------------------------------- +# Views +# --------------------------------------------------------------------------- - Returns the violations; an empty list means the inventory covers the - specs. The caller decides what a violation means: this function refuses - nothing. - """ - declared = load_us_cross_grain_declarations() - top = declared["grain_precedence"][0] - compiled: dict[tuple[str, str], list[Mapping[str, Any]]] = {} - for spec in specs: - level = spec.metadata.get(level_key) - if level is None or level == top: - continue - compiled.setdefault((str(spec.family), str(level)), []).append(spec.metadata) - entries = us_cross_grain_inventory() - routed = { - (str(entry["family"]), str(level)) - for entry in entries - for level in entry["levels"] - } - violations = [ - { - "kind": "family_level_without_route", - "family": family, - "level": level, - "where": "compiled specs", - } - for family, level in sorted(set(compiled) - routed) - ] - for entry in entries: - if not entry["compiled"]: - continue - for level in entry["levels"]: - rows = compiled.get((str(entry["family"]), str(level))) - if not rows: - violations.append( - { - "kind": "stale_inventory_entry", - "family": str(entry["family"]), - "level": str(level), - "where": str(entry["id"]), - } - ) - elif entry["route"] == "compile_rule" and not any( - _marker_matches(entry["marker"], metadata) for metadata in rows - ): - violations.append( - { - "kind": "compile_rule_marker_absent", - "family": str(entry["family"]), - "level": str(level), - "where": str(entry["id"]), - } - ) - return violations +def _selector_entry(bridge_id: str) -> Mapping[str, Any]: + for selector in load_us_cross_grain_declarations()["bridge_selectors"]: + if selector["bridge_id"] == bridge_id: + return selector + raise ValueError(f"Unknown US cross-grain bridge selector {bridge_id!r}.") -def us_cross_grain_coverage_receipt(specs: Iterable[Any]) -> dict[str, Any]: - """The coverage of a set of compiled specs, as a receipt. +def us_bridge_selector( + bridge_id: str, *, bounded: bool = True +) -> CrossGrainBridgeSelector: + """A declared selector as the operator takes it. - It records the violations and never raises on one. + ``bounded=False`` leaves the declared bound out, for a caller that turns + the bound off. """ - specs = tuple(specs) - violations = us_cross_grain_coverage_violations(specs) - return { - "declarations": US_CROSS_GRAIN_DECLARATIONS_RESOURCE, - "checked_specs": len(specs), - "inventory_entries": len(us_cross_grain_inventory()), - "violations": violations, - "covered": not violations, - } + declared = _selector_entry(bridge_id) + bound = ( + { + "max_factor_shift": declared.get("max_factor_shift"), + "min_factor_shift": declared.get("min_factor_shift"), + "shift_around": declared.get("shift_around", "one"), + "out_of_bound": declared.get("out_of_bound", "refuse"), + } + if bounded and declared.get("max_factor_shift") is not None + else {} + ) + return CrossGrainBridgeSelector( + bridge_id=str(declared["bridge_id"]), + concept=str(declared["concept"]), + higher=dict(declared["higher"]), + lower=dict(declared["lower"]), + pair_on=tuple(str(name) for name in declared["pair_on"]), + paired_values=declared.get("paired_values"), + **bound, + ) -def us_cross_grain_mechanism(mechanism_id: str) -> Mapping[str, Any]: - """One declared mechanism; an unknown id is refused.""" +def us_pass_grains(pass_id: str) -> tuple[str, str]: + """``(higher grain, lower grain)`` of a declared pass.""" - mechanisms = load_us_cross_grain_declarations()["mechanisms"] - if mechanism_id not in mechanisms: - raise ValueError( - f"Unknown US cross-grain mechanism {mechanism_id!r}; declared: " - f"{sorted(mechanisms)}." - ) - return mechanisms[mechanism_id] + declared = load_us_cross_grain_declarations() + for selector in declared["bridge_selectors"]: + if selector["bridge_id"] == pass_id: + return str(selector["higher"]["grain"]), str(selector["lower"]["grain"]) + for entry in declared["derived_controls"]: + if entry["bridge_id"] == pass_id: + return str(entry["higher_grain"]), str(entry["lower_grain"]) + for entry in declared["same_measurement"]: + if entry["id"] == pass_id: + return str(entry["higher_grain"]), str(entry["lower_grain"]) + raise ValueError(f"Unknown US cross-grain pass {pass_id!r}.") + + +def us_allocator_name(pass_id: str) -> str | None: + """The allocator of a pass until the feed is re-pinned, if it has one.""" + + return load_us_cross_grain_declarations()["until_the_feed_repin"]["allocators"].get( + pass_id + ) @dataclass(frozen=True) class DistrictSoiNesting: - """The declared choices of the state-to-district SOI mechanism.""" + """The declared choices of the state-to-district SOI pass.""" vintage_rule: str - allocator: str + max_factor_shift: float + min_factor_shift: float + #: District-file-only measure -> sibling measure, until the feed re-pin. level_bridges: Mapping[str, str] - factor_band: float - internal_rtol: float closure_rtol: float reviewed_crosswalk_sha256: str defective_lower_measures: Mapping[str, str] unparented_lower_measures: Mapping[str, str] excluded_legs: Mapping[str, str] + @property + def factor_band(self) -> float: + """The bound as a ratio to the median: one plus the highest shift.""" + + return 1.0 + self.max_factor_shift + @functools.lru_cache(maxsize=1) def us_district_soi_nesting() -> DistrictSoiNesting: - declared = us_cross_grain_mechanism(DISTRICT_SOI) + declared = load_us_cross_grain_declarations() + selector = _selector_entry(DISTRICT_SOI) registers = declared["registers"] + transitional = declared["until_the_feed_repin"] return DistrictSoiNesting( - vintage_rule=str(declared["vintage_rule"]), - allocator=str(declared["allocator"]), - level_bridges=dict(declared["control"]["level_bridges"]["siblings"]), - factor_band=declared["factor_band"]["tolerance"], - internal_rtol=declared["self_consistency"]["rtol"], - closure_rtol=declared["closure"]["rtol"], - reviewed_crosswalk_sha256=str(declared["members"]["reviewed_crosswalk_sha256"]), + vintage_rule=str(selector["vintage_rule"]), + max_factor_shift=selector["max_factor_shift"], + min_factor_shift=selector["min_factor_shift"], + level_bridges=dict(transitional["level_bridges"]["siblings"]), + closure_rtol=transitional["closure_rtol"], + reviewed_crosswalk_sha256=str( + declared["members"]["congressional_district"]["reviewed_crosswalk_sha256"] + ), defective_lower_measures=dict(registers["defective_lower_measures"]["entries"]), unparented_lower_measures=dict( registers["unparented_lower_measures"]["entries"] @@ -325,9 +310,8 @@ def us_district_soi_nesting() -> DistrictSoiNesting: @dataclass(frozen=True) class CountySoiNesting: - """The declared choices of the state-to-county SOI mechanism.""" + """The declared choices of the state-to-county SOI pass.""" - allocator: str required_measures: tuple[str, ...] #: Absent county -> host county, as five-digit integer codes. combined_cells: Mapping[int, int] @@ -336,13 +320,166 @@ class CountySoiNesting: @functools.lru_cache(maxsize=1) def us_county_soi_nesting() -> CountySoiNesting: - declared = us_cross_grain_mechanism(COUNTY_SOI) - members = declared["members"] + declared = load_us_cross_grain_declarations() + combined = [ + cell + for cell in declared["members"]["county"]["combined"] + if cell["bridge_id"] == COUNTY_SOI + ] + bases = {str(cell["basis"]) for cell in combined} + if len(bases) > 1: + raise ValueError("US combined county cells of one pass must share a basis.") return CountySoiNesting( - allocator=str(declared["allocator"]), - required_measures=tuple(str(m) for m in declared["required_measures"]), - combined_cells={ - int(cell["absent"]): int(cell["host"]) for cell in members["combined_cells"] - }, - combined_cell_basis=str(members["combined_cell_basis"]), + required_measures=tuple( + str(measure) for measure in _selector_entry(COUNTY_SOI)["required_measures"] + ), + combined_cells={int(cell["absent"]): int(cell["host"]) for cell in combined}, + combined_cell_basis=next(iter(bases), ""), + ) + + +# --------------------------------------------------------------------------- +# Coverage +# --------------------------------------------------------------------------- + + +def _marker_matches(marker: Mapping[str, Any], metadata: Mapping[str, Any]) -> bool: + value = metadata.get(str(marker["metadata_key"])) + if value is None: + return False + if "value" in marker: + return str(value) == str(marker["value"]) + if "value_prefix" in marker: + return str(value).startswith(str(marker["value_prefix"])) + return True + + +def us_cross_grain_coverage_violations( + specs: Iterable[Any], + *, + level_key: str = "ledger_geography_level", + role_key: str = "target_role", +) -> list[dict[str, str]]: + """Every gap between a set of compiled specs and the declarations. + + ``specs`` are compiled target specs (anything with ``family``, ``value`` + and ``metadata``). The top level of ``grain_precedence`` nests in + nothing. A family at a lower level is covered by a bridge selector, a + derived control, a same-measurement entry, a relation, a local route, a + compile rule or a known gap. A violation is one of: + + * ``family_level_without_route``: a family has rows at a lower level + that nothing covers; + * ``stale_declaration``: a relation, a local route, a compile rule or a + known gap names rows that the specs do not hold; + * ``compile_rule_marker_absent``: a compile rule's marker is on no row of + one of its levels; + * ``subset_exceeded``: the parts of a ``subset`` relation sum to more + than their whole, beyond the declared ``max_excess``. + + Returns the violations. The caller decides what one means: this function + refuses nothing. + """ + + declared = load_us_cross_grain_declarations() + grains = tuple(declared["grain_precedence"]) + top = grains[0] + rows: dict[tuple[str, str], list[Any]] = {} + for spec in specs: + level = spec.metadata.get(level_key) + if level is not None: + rows.setdefault((str(spec.family), str(level)), []).append(spec) + compiled = {key for key in rows if key[1] != top} + transitional = declared["until_the_feed_repin"] + covered: set[tuple[str, str]] = set() + for selector in declared["bridge_selectors"]: + covered.add((str(selector["family"]), str(selector["lower"]["grain"]))) + for entry in (*declared["derived_controls"], *declared["same_measurement"]): + covered.add((str(entry["family"]), str(entry["lower_grain"]))) + violations: list[dict[str, str]] = [] + + def stale(family: str, level: str, where: str) -> None: + violations.append( + { + "kind": "stale_declaration", + "family": family, + "level": level, + "where": where, + } + ) + + for relation in declared["relations"]: + sides = {} + for target in relation["targets"]: + family, role, level = _relation_target(str(target), grains) + held = [ + spec + for spec in rows.get((family, level), ()) + if spec.metadata.get(role_key) == role + ] + sides[str(target)] = held + if level != top: + covered.add((family, level)) + if not held: + stale(family, level, str(target)) + if relation["relation"] == "subset": + part, whole = sides[str(relation["part"])], sides[str(relation["whole"])] + if part and len(whole) == 1 and whole[0].value: + ratio = math.fsum(spec.value for spec in part) / whole[0].value + if ratio > 1.0 + float(relation.get("max_excess", 0.0)): + violations.append( + { + "kind": "subset_exceeded", + "family": str(part[0].family), + "level": str(part[0].metadata.get(level_key)), + "where": f"{relation['part']} is {ratio!r} of its whole", + } + ) + for target in declared["local_routes"]: + family, level = _route_target(str(target), grains) + covered.add((family, level)) + if (family, level) not in rows: + stale(family, level, str(target)) + for entry in (*transitional["compile_rules"], *transitional["known_gaps"]): + for level in entry["levels"]: + key = (str(entry["family"]), str(level)) + covered.add(key) + if key not in rows: + stale(*key, str(entry["id"])) + elif "marker" in entry and not any( + _marker_matches(entry["marker"], spec.metadata) for spec in rows[key] + ): + violations.append( + { + "kind": "compile_rule_marker_absent", + "family": key[0], + "level": key[1], + "where": str(entry["id"]), + } + ) + violations.extend( + { + "kind": "family_level_without_route", + "family": family, + "level": level, + "where": "compiled specs", + } + for family, level in sorted(compiled - covered) ) + return violations + + +def us_cross_grain_coverage_receipt(specs: Iterable[Any]) -> dict[str, Any]: + """The coverage of a set of compiled specs, as a receipt. + + It records the violations and never raises on one. + """ + + specs = tuple(specs) + violations = us_cross_grain_coverage_violations(specs) + return { + "declarations": US_CROSS_GRAIN_DECLARATIONS_RESOURCE, + "checked_specs": len(specs), + "violations": violations, + "covered": not violations, + } diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/target_loss_weights.py b/packages/microcosm-build/src/microcosm/build/us_runtime/target_loss_weights.py index f25a04b881..1569a0779e 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/target_loss_weights.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/target_loss_weights.py @@ -66,6 +66,7 @@ import numpy as np +from microcosm.build.cross_grain import PARENT_KEY, VALUE_BEFORE_KEY from microcosm.calibrate.target_loss_rules import ( TargetLossRows, TargetWeightRule, @@ -333,10 +334,10 @@ def _ledger_concept_budget_key( #: :data:`US_FISCAL_TARGET_CONCEPT_METADATA_EXCLUSIONS` does not list them, #: so under the national mapping every compiled district row is its own #: group; the national mapping is kept as it is here. -#: - ``state_cd_cd_file_value``: the district file's own value of the row, -#: which the ``state_cd`` rebase (``tools/us_acs_local_cd_surface.py``) -#: stamps before rescaling it. The rebase's block-level stamps (parent, -#: basis, factor, file state sum) are equal across a block and may stay. +#: - ``cross_grain_value_before``: the district file's own value of the row, +#: which the shared cross-grain operator's pass stamps when it divides the +#: state row among the districts. The pass's block-level stamps (parent, +#: control, factor) are equal across a block and may stay. #: #: :func:`validate_acs_local_concept_groups` refuses a surface where any other #: per-district key splits a reconciliation block. @@ -344,7 +345,7 @@ def _ledger_concept_budget_key( { "ledger_fact_label", "ledger_layout_groupby_value_label", - "state_cd_cd_file_value", + VALUE_BEFORE_KEY, } ) US_ACS_LOCAL_CONCEPT_METADATA_EXCLUSIONS = ( @@ -535,7 +536,7 @@ def validate_acs_local_concept_groups( per-district metadata key reaching the key would split them into one group per district, whatever the SOI mode. - Each ``state_cd`` reconciliation block (the district rows sharing one - ``state_cd_parent_target_name``) must be exactly one concept group, and + ``cross_grain_parent``) must be exactly one concept group, and no group may hold two blocks. - Each district group must lie in one state. """ @@ -557,7 +558,7 @@ def validate_acs_local_concept_groups( continue states_of_group.setdefault(key, set()).add(str(metadata.get("state_fips"))) groups_of_identity.setdefault(district_concept_identity(spec), set()).add(key) - parent = metadata.get("state_cd_parent_target_name") + parent = metadata.get(PARENT_KEY) if parent: group_of_parent.setdefault(str(parent), set()).add(key) parent_of_group.setdefault(key, set()).add(str(parent)) diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/target_nesting.py b/packages/microcosm-build/src/microcosm/build/us_runtime/target_nesting.py index f3c7908053..43bf07dadb 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/target_nesting.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/target_nesting.py @@ -1,22 +1,24 @@ """US target nesting on the shared cross-grain operator (microcosm#1760). A target for a small area must agree with the target of the area that -contains it. This module makes the rows of a lower geography level from a -control at a higher level, for each mechanism that -``us/cross_grain_declarations.json`` declares. The arithmetic is not here: - -- :func:`microcosm.build.cross_grain.apply_cross_grain_reconciliation` groups - the rows of one quantity, finds the control of each lower leg, divides it - among the leg's rows with the mechanism's declared allocator, checks the sum - and writes its receipt; -- :mod:`microcosm.build.cross_grain_controls` supplies the allocators, the - derived controls, the factor band, the completeness check and the - self-consistency check. - -What is here is the US side of each mechanism: which specs or facts are the -control and the lower rows, the refusals with their US wording, and the -metadata keys and receipts the local tools wrote before the operator made the -rows. Stage A changes no value: every surface has the bytes it had. +contains it. Each pass here makes the rows of a lower geography level from a +control at a higher level. The arithmetic and the checks are not here: + +- :func:`microcosm.build.cross_grain_controls.reconcile_rows` runs the shared + operator (:mod:`microcosm.build.cross_grain`) on the rows of a pass and + says what it did with each row. The operator divides each control among + its lower rows, bounds the factor of each bridge, refuses a leg that does + not hold its declared members, and writes the receipt. +- ``us/cross_grain_declarations.json`` declares the passes, under the key + names of the UK file: the bridge between Historic Table 2 and the district + file, the bridge between the state rows and the county file, the derived + control of the county households, and the ladder population, which is one + source at two levels. + +What is here is the US side of each pass: which specs or facts are the +control and the lower rows, which rows a reviewed register keeps off the +surface, and the validation of the county facts. A reconciled row keeps the +``cross_grain_*`` metadata keys that the UK rows keep. The module reads specs and facts only. It reads no frame and no household. """ @@ -25,7 +27,6 @@ import json import math -import struct from collections import Counter, defaultdict from collections.abc import Callable, Iterable, Mapping, Sequence from contextvars import ContextVar @@ -38,54 +39,42 @@ from microcosm.build import cross_grain_controls as controls from microcosm.build.cross_grain import ( + MEMBERS_KEY, + PARENT_KEY, + CrossGrainBridge, CrossGrainRule, - apply_cross_grain_reconciliation, + cross_grain_metadata, + expand_bridge_selectors, ) +from microcosm.build.cross_grain_controls import SurfaceRow from microcosm.build.us_runtime.cross_grain_declarations import ( COUNTY_ACS_HOUSEHOLDS, COUNTY_POPULATION, COUNTY_SOI, DISTRICT_SOI, load_us_cross_grain_declarations, + us_allocator_name, + us_bridge_selector, us_county_soi_nesting, - us_cross_grain_mechanism, us_district_soi_nesting, + us_pass_grains, ) -#: The file a materialize stage writes the operator's own receipts to. +#: The file a materialize stage writes the operator's receipts to. NESTING_RECEIPTS_FILENAME = "target_nesting.json" # --------------------------------------------------------------------------- -# Blocks through the operator +# One pass on the operator # --------------------------------------------------------------------------- @dataclass(frozen=True) -class NestingBlock: - """One control and the lower rows it is divided among. - - ``concept`` and ``filters`` are the measurement signature that ties the - control to its rows. ``lower_values`` are in the order the allocator must - see them: a residual rule gives its residual to the first of equal - largest rows. - """ - - concept: str - filters: tuple[tuple[str, str], ...] - control_geography_id: str - control_value: float - lower_geography_ids: tuple[str, ...] - lower_values: tuple[float, ...] - - -@dataclass(frozen=True) -class NestedRows: - """A block's rows as the operator left them, with its leg receipt.""" +class NestedSurface: + """The specs of one nested surface, its receipt and the operator's.""" - values: tuple[float, ...] - #: The factor and the lower-row total the allocator reported. - factor: float - lower_sum: float + specs: tuple + receipt: dict + operator_receipt: dict def geography_id(grain: str, code: str) -> str: @@ -94,132 +83,69 @@ def geography_id(grain: str, code: str) -> str: return f"{grain}:{code}" -def _signature_key(block: NestingBlock) -> str: - return "|".join( - [block.concept, *(f"{name}={value}" for name, value in block.filters)] - ) +def _own_measurement(target_id: str) -> dict[str, Any]: + """A measurement that only this target has. + A US target is one source's rows of one concept. Two sources have two + measurements, so only a declared bridge ties them. One target at two + levels is one measurement at both. + """ -def reconcile_blocks( - mechanism_id: str, blocks: Sequence[NestingBlock] -) -> tuple[list[NestedRows], dict[str, Any]]: - """Divide each block's control among its rows on the shared operator. + return {"measurement": {"concept": target_id, "filters": []}} - Builds one surface for the mechanism (a control row and the lower rows of - every block), runs :func:`apply_cross_grain_reconciliation` with the - mechanism's declared allocator, and returns each block's rows, in block - order, with the operator's receipt. A block is one leg: its control row - parents exactly its own lower rows. - Raises: - ValueError: If two blocks share a signature and a control geography, - if a lower row sits under two controls, if a block has no lower - row, or if the operator refuses a block (a vanishing or - non-finite total, a negative factor, or rows off their control). +def run_pass( + pass_id: str, + rows: Sequence[SurfaceRow], + *, + bound_higher_targets: Iterable[str], + legs: Mapping[str, str], + bridges: Sequence[CrossGrainBridge] = (), + expected_members: Mapping[str, Mapping[str, frozenset[str]]] | None = None, + measurements: Mapping[str, str] | None = None, +) -> tuple[list[controls.RowOutcome], dict[str, Any]]: + """Run one declared pass on the shared operator. + + ``legs`` maps each lower geography to the control geography it sits + under. ``measurements`` names the measurement of a target where it is + not the target's own. Returns the outcome of each row and the operator's + receipt. """ declarations = load_us_cross_grain_declarations() - mechanism = us_cross_grain_mechanism(mechanism_id) - higher, lower = str(mechanism["higher_grain"]), str(mechanism["lower_grain"]) - rows: list[tuple[str, str, str, float]] = [] - signatures: dict[str, dict[str, Any]] = {} - bound: list[str] = [] - area_legs: dict[str, str] = {} - spans: list[tuple[str, int, int]] = [] - controls_seen: set[tuple[str, str]] = set() - for block in blocks: - key = _signature_key(block) - control_id = f"{mechanism_id}:{higher}:{key}" - lower_id = f"{mechanism_id}:{lower}:{key}" - if (control_id, block.control_geography_id) in controls_seen: - raise ValueError( - f"Nesting mechanism {mechanism_id!r} has two blocks for {key!r} " - f"at {block.control_geography_id!r}." - ) - controls_seen.add((control_id, block.control_geography_id)) - if not block.lower_geography_ids or len(block.lower_geography_ids) != len( - block.lower_values - ): - raise ValueError( - f"Nesting mechanism {mechanism_id!r} block {key!r} at " - f"{block.control_geography_id!r} needs one value for each of " - "its lower rows, and at least one row." - ) - if control_id not in signatures: - measurement = { - "concept": block.concept, - "filters": [{name: value} for name, value in block.filters], - } - signatures[control_id] = {"measurement": measurement} - signatures[lower_id] = {"measurement": measurement} - bound.append(control_id) - rows.append( - (higher, block.control_geography_id, control_id, block.control_value) - ) - start = len(rows) - for area, value in zip( - block.lower_geography_ids, block.lower_values, strict=True - ): - if area_legs.setdefault(area, block.control_geography_id) != ( - block.control_geography_id - ): - raise ValueError( - f"Nesting mechanism {mechanism_id!r}: lower geography " - f"{area!r} sits under two controls." - ) - rows.append((lower, area, lower_id, float(value))) - spans.append((control_id, start, len(rows))) - if not blocks: - receipt: dict[str, Any] = { - "absence": f"Mechanism {mechanism_id} had no block to reconcile." - } - _record(mechanism_id, 0, receipt) - return [], receipt - surface = pd.DataFrame( - rows, columns=["grain", "geography_id", "target_id", "value"] - ) + control_grains = tuple(declarations["control_grains"]) + allocator = us_allocator_name(pass_id) rule = CrossGrainRule( grain_precedence=tuple(declarations["grain_precedence"]), signature_fields=tuple(declarations["signature_fields"]), - bridges=(), - leg_of_area=area_legs.__getitem__, + bridges=tuple(bridges), + leg_of_area=legs.__getitem__, parent_geography_legs={ - control_geography: (control_geography,) - for _control_id, control_geography in sorted(controls_seen) + row.geography_id: (row.geography_id,) + for row in rows + if row.grain in control_grains }, - control_grains=tuple(declarations["control_grains"]), - allocator=controls.allocator_named(str(mechanism["allocator"])), - ) - reconciled, receipt = apply_cross_grain_reconciliation( - surface, bound, signatures, rule + control_grains=control_grains, + allocator=None if allocator is None else controls.allocator_named(allocator), ) - values = reconciled["value"].to_numpy(dtype=np.float64) - legs = { - (leg["higher_target_ids"][0], leg["parent_geography_id"]): leg - for group in receipt["groups"] - for leg in group["legs"] - } - nested: list[NestedRows] = [] - for block, (control_id, start, stop) in zip(blocks, spans, strict=True): - leg = legs.get((control_id, block.control_geography_id)) - if leg is None: - raise ValueError( - f"Nesting mechanism {mechanism_id!r}: the operator did not " - f"reconcile the block at {block.control_geography_id!r}." - ) - nested.append( - NestedRows( - values=tuple(values[start:stop].tolist()), - factor=leg["declared_factor"], - lower_sum=leg["old_total"], + outcomes, receipt = controls.reconcile_rows( + rows, + tuple(dict.fromkeys(bound_higher_targets)), + { + row.target_id: _own_measurement( + (measurements or {}).get(row.target_id, row.target_id) ) - ) - _record(mechanism_id, len(blocks), receipt) - return nested, receipt + for row in rows + }, + rule, + expected_members=expected_members, + ) + _record(pass_id, receipt) + return outcomes, receipt # --------------------------------------------------------------------------- -# The operator's own receipts +# The operator's receipts # --------------------------------------------------------------------------- _RECEIPTS: ContextVar[list[dict[str, Any]] | None] = ContextVar( @@ -230,9 +156,7 @@ def reconcile_blocks( def start_nesting_receipts() -> list[dict[str, Any]]: """Start a fresh record of the nesting passes that run from here on. - The four tool functions keep the signatures and the receipts they had, so - the operator's own receipt cannot travel in their results. A stage that - wants it calls this first and writes the list with + A stage calls this first and writes the list with :func:`write_nesting_receipts` when its targets are made. Without a call, nothing is recorded. """ @@ -248,16 +172,13 @@ def stop_nesting_receipts() -> None: _RECEIPTS.set(None) -def _record(mechanism_id: str, blocks: int, receipt: Mapping[str, Any]) -> None: +def _record(pass_id: str, receipt: Mapping[str, Any]) -> None: receipts = _RECEIPTS.get() if receipts is not None: - mechanism = us_cross_grain_mechanism(mechanism_id) receipts.append( { - "mechanism": mechanism_id, - "issue_row": mechanism["issue_row"], - "allocator": mechanism["allocator"], - "blocks": blocks, + "pass": pass_id, + "allocator": us_allocator_name(pass_id), "operator_receipt": dict(receipt), } ) @@ -288,26 +209,14 @@ def write_nesting_receipts( # --------------------------------------------------------------------------- -# State to congressional district: IRS SOI shares (issue row 5) +# State to congressional district: IRS SOI (issue row 5) # --------------------------------------------------------------------------- -#: The filters of a district SOI signature, in the order the caller's concept -#: identity gives them after the measure id. -DISTRICT_SOI_IDENTITY_FILTERS = ( - "agi_lower_bound", - "agi_upper_bound", - "filing_status", - "eitc_child_count", -) - - -@dataclass(frozen=True) -class NestedSurface: - """The specs of one nested surface, its receipt and the operator's.""" - - specs: tuple - receipt: dict - operator_receipt: dict +#: The sources of a district SOI target, as the declared selector names them. +STATE_SURFACE = "state_surface" +LOWER_FILE = "lower_file" +#: The lower file's own state total, where it is the parent of its districts. +LOWER_FILE_STATE = "lower_file_state" def crosswalk_district_sets(crosswalk: pd.DataFrame): @@ -352,13 +261,11 @@ def district_soi_surface( Historic Table 2 supplies a state concept's level wherever it has that concept. The district file then supplies only each district's share of - its state: the operator divides the Historic Table 2 state row among the - district rows (``proportional_fsum``). A concept only the district file - has keeps the district file's own state row as its control, lifted onto - the Historic Table 2 basis by a sibling concept's ratio - (``scaled_by_sibling_ratio``). A block whose ratio sits outside the - factor band of its concept's median across states is dropped and - recorded. + its state. The declared bridge ``historic_table_2_state_vs_district_file`` + ties the two files, one bridge for each concept, and the operator divides + each state row among its district rows. A state whose factor is outside + the bridge's bound around the median across states is unbound: its + district rows leave the surface and the receipt names them. Args: soi_specs: Every compiled ``irs_soi`` spec (the ``full`` surface). @@ -367,12 +274,13 @@ def district_soi_surface( crosswalk: The 117th->119th CD crosswalk the compiler used; it names each state's source-plan and current-plan districts. crosswalk_sha256: Recorded in the receipt. - level_bridges: District-file-only measure -> sibling measure. - factor_band: Largest allowed ratio between a block's ratio and its - concept's median across states (either direction). + level_bridges: District-file-only measure -> sibling measure (until + the feed re-pin; see :func:`_bridged_state_parents`). + factor_band: The bound as a ratio to the median factor: a state may + sit between ``1 / factor_band`` and ``factor_band`` of it. + Infinity turns the bound off. concept_identity: The published concept a spec measures, independent - of vintage: the measure id, then the filters of - ``DISTRICT_SOI_IDENTITY_FILTERS``. + of vintage. materializer_semantics: Everything the SOI slice reads from a spec except its geography. is_lower_file_spec: Whether a spec comes from the district file. @@ -385,17 +293,16 @@ def district_soi_surface( file state rows, district rows), its receipt and the operator's. Raises: - ValueError: If a district concept is incomplete in a state, if its + ValueError: If a district concept is not complete in a state, if its district rows disagree on what they materialize, if a parent's - materialization differs from its children's, or if a parent - cannot absorb its children (zero sum under a nonzero parent, or - a sign conflict). + materialization differs from its children's, if a concept takes + its parent from two sources, or if the operator refuses a block + (rows that sum to zero under a control that is not zero, or a + sign conflict). """ nesting = us_district_soi_nesting() - mechanism = us_cross_grain_mechanism(DISTRICT_SOI) - state_level = str(mechanism["higher_grain"]) - district_level = str(mechanism["lower_grain"]) + state_level, district_level = us_pass_grains(DISTRICT_SOI) defective = nesting.defective_lower_measures unparented = nesting.unparented_lower_measures excluded_states = nesting.excluded_legs @@ -446,42 +353,7 @@ def drop(spec, reason: str) -> None: ) cd_file_state_by_key[key] = spec - # Each state concept both files carry: its Historic Table 2 / district-file - # ratio, judged against the measure's median ratio across states. - vintage_ratio = { - key: controls.level_ratio( - ht2_by_key[key].value, cd_file_state_by_key[key].value - ) - for key in ht2_by_key.keys() & cd_file_state_by_key.keys() - } - median_ratio = controls.median_by_group(vintage_ratio, _identity_of_block) - out_of_band: list[dict] = [] - - def within_band( - key: tuple, - ratio: float, - median: float, - basis: str, - measure: str, - *, - verdict: str, - ) -> bool: - judged = controls.band_verdict(ratio, median, factor_band) - if not judged.ok: - out_of_band.append( - { - "state_fips": key[0], - "measure": measure, - "concept": key[1][0], - "basis": basis, - "verdict": verdict, - "ratio": ratio, - "median_ratio": median, - "relative": judged.relative, - } - ) - return judged.ok - + # Which district rows enter the surface: the reviewed registers. kept_cd_by_key: dict[tuple, list] = defaultdict(list) for spec in cd_rows: metadata = spec.metadata @@ -498,114 +370,31 @@ def within_band( else: kept_cd_by_key[(state, concept_identity(spec))].append(spec) - # Each Historic-Table-2-parented block's rebase factor (parent over its - # district rows' sum), judged against its concept's median across states. - block_factor: dict[tuple, float] = {} - for key, block in kept_cd_by_key.items(): - parent = ht2_by_key.get(key) - if parent is None: - continue - ratio, _child_sum = controls.control_ratio( - parent.value, (spec.value for spec in block) - ) - if ratio is not None: - block_factor[key] = ratio - median_factor = controls.median_by_group( - block_factor, _identity_of_block, positive_only=True + bridged, bridge_factors, bridge_verdicts = _bridged_state_parents( + ht2_by_key, + cd_file_state_by_key, + kept_cd_by_key, + level_bridges=level_bridges, + factor_band=factor_band, + defective=defective, ) - # One basis for every state level: a concept Historic Table 2 lacks keeps - # the district file's state row, scaled by a sibling's two levels. - bridged: dict[str, object] = {} - bridge_factors: dict[str, list[float]] = defaultdict(list) - for key, spec in sorted(cd_file_state_by_key.items()): - state, identity = key - measure = identity[0] - if key in ht2_by_key or measure in defective: - continue - sibling = level_bridges.get(measure) - if sibling is None: - raise ValueError( - f"District-file-only concept {measure!r} has no level bridge; " - "register a sibling measure in STATE_CD_LEVEL_BRIDGES before " - "binding it." - ) - sibling_key = (state, (sibling, *identity[1:])) - ht2_sibling = ht2_by_key.get(sibling_key) - cd_sibling = cd_file_state_by_key.get(sibling_key) - if ht2_sibling is None or cd_sibling is None or float(cd_sibling.value) == 0: - raise ValueError( - f"Level bridge {measure} -> {sibling} in state {state} needs " - "the sibling's state total in both files." - ) - value, factor = controls.scaled_by_sibling_ratio( - spec.value, ht2_sibling.value, cd_sibling.value - ) - # A sign conflict is a data defect, not a level disagreement: refuse - # it before the band, which only judges finite positive ratios. - if not (math.isfinite(factor) and factor > 0.0): - raise ValueError( - f"Level bridge {measure} -> {sibling} in state {state} has " - f"factor {factor}." - ) - # The sibling is trusted for bridging only if both of the band's - # verdicts on it pass: its two state levels, and (where it has district - # rows) the rebase of its own district block. - trusted = within_band( - sibling_key, - factor, - median_ratio.get(sibling_key[1], math.nan), - f"level_bridge:{measure}", - measure, - verdict="sibling_vintage_ratio", - ) - if sibling_key in block_factor: - trusted = ( - within_band( - sibling_key, - block_factor[sibling_key], - median_factor.get(sibling_key[1], math.nan), - f"level_bridge:{measure}", - measure, - verdict="sibling_rebase_factor", - ) - and trusted - ) - if not trusted: - continue - metadata = dict(spec.metadata) - metadata.update( - { - "state_cd_vintage_rule": nesting.vintage_rule, - "state_cd_cd_file_value": repr(float(spec.value)), - "state_cd_level_bridge_sibling": ht2_sibling.name, - "state_cd_level_bridge_cd_file_sibling": cd_sibling.name, - "state_cd_level_bridge_factor": repr(factor), - } - ) - bridged[spec.name] = replace( - spec, value=value, signed=value < 0.0, metadata=metadata - ) - bridge_factors[measure].append(factor) - - # Every check a block must pass before the operator divides its control. - internal_gaps: list[float] = [] + # The surface: for each block, its state row and its district rows. + rows: list[SurfaceRow] = [] + blocks: list[tuple] = [] + legs: dict[str, str] = {} + expected: dict[str, dict[str, frozenset[str]]] = {} + bound: list[str] = [] + targets: dict[str, dict[str, str]] = {} + measurements: dict[str, str] = {} + parent_source: dict[tuple, str] = {} kept_cd_file_parents: set[str] = set() - kept_blocks: list[tuple] = [] for key in sorted(kept_cd_by_key): state, identity = key children = sorted( kept_cd_by_key[key], key=lambda spec: spec.metadata["congressional_district_geoid"], ) - districts = [spec.metadata["congressional_district_geoid"] for spec in children] - expected = sorted(target_districts.get(state, ())) - if not controls.leg_completeness(districts, expected).complete: - raise ValueError( - f"District concept {identity} in state {state} covers " - f"{districts}, expected the current plan's {expected}; " - "rebasing an incomplete set would misstate every district." - ) semantics = {materializer_semantics(spec) for spec in children} if len(semantics) != 1: raise ValueError( @@ -614,133 +403,123 @@ def within_band( ) (child_semantics,) = semantics parent = ht2_by_key.get(key) - basis = "historic_table_2" + basis, source = "historic_table_2", STATE_SURFACE if parent is None: - parent = cd_file_state_by_key.get(key) - basis = "cd_file_state_total_bridged" - if parent is None: + own = cd_file_state_by_key.get(key) + basis, source = "cd_file_state_total_bridged", LOWER_FILE_STATE + if own is None: raise ValueError( f"District concept {identity} in state {state} has no " "state parent in either vintage." ) - if parent.name not in bridged: + if own.name not in bridged: for child in children: drop(child, f"level_bridge_out_of_band:{identity[0]}") continue - parent = bridged[parent.name] + parent = bridged[own.name] kept_cd_file_parents.add(parent.name) + if parent_source.setdefault(identity, source) != source: + raise ValueError( + f"District concept {identity} takes its state parent from " + "Historic Table 2 in some states and from the district file in " + "others; one concept has one parent source." + ) if materializer_semantics(parent) != child_semantics: raise ValueError( f"State parent {parent.name} materializes differently from " f"its district rows ({identity}, state {state})." ) - parent_value = float(parent.value) - ratio, child_sum = controls.control_ratio( - parent_value, (spec.value for spec in children) - ) - if ratio is None: - if parent_value != 0.0: - raise ValueError( - f"District rows of {identity} in state {state} sum to zero " - f"under a nonzero parent {parent.name}={parent_value}." - ) - factor = 1.0 - else: - factor = ratio - if factor < 0.0: - raise ValueError( - f"District rows of {identity} in state {state} sum to " - f"{child_sum}, opposite in sign to parent {parent.name}=" - f"{parent_value}." - ) - # The district file must agree with itself before its shares are used. - cd_state = cd_file_state_by_key.get(key) - if cd_state is not None: - cd_state_value = float(cd_state.value) - gap = controls.sum_gap(cd_state_value, child_sum) - internal_gaps.append(gap.relative) - if gap.exceeds(nesting.internal_rtol): - raise ValueError( - f"District-file state row {cd_state.name}={cd_state_value} " - f"differs from the sum of its district rows ({child_sum}) " - f"for {identity} in state {state}: a column or crosswalk " - "defect inside the district file." - ) - # An all-zero block agrees with a zero parent whatever the median. - if ( - basis == "historic_table_2" - and ratio is not None - and not within_band( - key, - factor, - median_factor.get(identity, math.nan), - "rebase", - identity[0], - verdict="rebase_factor", + identity_text = "|".join(identity) + lower_id = f"{LOWER_FILE}|{identity_text}" + higher_id = f"{source}|{identity_text}" + state_area = geography_id(state_level, state) + targets[higher_id] = { + "source": source, + "grain": state_level, + "identity": identity_text, + } + targets[lower_id] = { + "source": LOWER_FILE, + "grain": district_level, + "identity": identity_text, + } + # The lower file's own state total has the measurement of its + # district rows, so the operator ties them with no bridge. + measurements[higher_id] = lower_id if source == LOWER_FILE_STATE else higher_id + measurements[lower_id] = lower_id + bound.append(higher_id) + blocks.append((key, parent, basis, children, len(rows))) + rows.append(SurfaceRow(state_level, state_area, higher_id, float(parent.value))) + for child in children: + area = geography_id( + district_level, child.metadata["congressional_district_geoid"] ) - ): - for child in children: - drop(child, f"rebase_out_of_band:{identity[0]}") - continue - kept_blocks.append( - (key, parent, basis, parent_value, children, child_sum, factor) + legs[area] = state_area + rows.append(SurfaceRow(district_level, area, lower_id, float(child.value))) + expected.setdefault(lower_id, {})[state_area] = frozenset( + geography_id(district_level, district) + for district in target_districts.get(state, ()) ) - # The operator divides each control among its district rows. - nested, operator_receipt = reconcile_blocks( + selector = us_bridge_selector(DISTRICT_SOI, bounded=not math.isinf(factor_band)) + if not math.isinf(factor_band) and factor_band != nesting.factor_band: + selector = replace( + selector, + max_factor_shift=factor_band - 1.0, + min_factor_shift=1.0 / factor_band - 1.0, + ) + bridges, _unpaired = expand_bridge_selectors([selector], targets) + outcomes, operator_receipt = run_pass( DISTRICT_SOI, - [ - NestingBlock( - concept=f"{children[0].family}.{identity[0]}", - filters=tuple( - zip(DISTRICT_SOI_IDENTITY_FILTERS, identity[1:], strict=True) - ), - control_geography_id=geography_id(state_level, state), - control_value=parent_value, - lower_geography_ids=tuple( - geography_id( - district_level, child.metadata["congressional_district_geoid"] - ) - for child in children - ), - lower_values=tuple(float(child.value) for child in children), - ) - for (state, identity), _p, _b, parent_value, children, _s, _f in kept_blocks - ], + rows, + bound_higher_targets=bound, + legs=legs, + bridges=bridges, + expected_members=expected, + measurements=measurements, ) + rebased: dict[str, object] = {} factors_by_measure: dict[str, list[float]] = defaultdict(list) parent_basis_counts: Counter = Counter() - for (key, parent, basis, parent_value, children, child_sum, factor), rows in zip( - kept_blocks, nested, strict=True - ): - _state, identity = key - if _bits(rows.lower_sum, rows.factor) != _bits(child_sum, factor): - raise ValueError( - f"The operator's factor for {identity} under {parent.name} " - f"({rows.factor!r} on {rows.lower_sum!r}) is not the factor the " - f"band judged ({factor!r} on {child_sum!r})." - ) - factors_by_measure[identity[0]].append(rows.factor) - parent_basis_counts[basis] += len(children) - for child, value in zip(children, rows.values, strict=True): - metadata = dict(child.metadata) - metadata.update( + unbound: list[dict] = [] + for key, parent, basis, children, start in blocks: + state, identity = key + block = outcomes[start + 1 : start + 1 + len(children)] + statuses = {outcome.status for outcome in block} + if statuses == {controls.UNBOUND}: + unbound.append( { - "state_cd_vintage_rule": nesting.vintage_rule, - "state_cd_parent_target_name": parent.name, - "state_cd_parent_basis": basis, - "state_cd_parent_value": repr(parent_value), - "state_cd_cd_file_value": repr(float(child.value)), - "state_cd_cd_file_state_sum": repr(rows.lower_sum), - "state_cd_rebase_factor": repr(rows.factor), + "state_fips": state, + "concept": identity[0], + "parent": parent.name, + "factor": block[0].factor, } ) + for child in children: + drop(child, f"rebase_out_of_band:{identity[0]}") + continue + if statuses != {controls.RECONCILED}: + raise ValueError( + f"The operator did not reconcile the district rows of " + f"{identity} under {parent.name}." + ) + factors_by_measure[identity[0]].append(block[0].factor) + parent_basis_counts[basis] += len(children) + for child, outcome in zip(children, block, strict=True): rebased[child.name] = replace( child, - value=value, - signed=value < 0.0, - metadata=metadata, + value=outcome.value, + signed=outcome.value < 0.0, + metadata={ + **child.metadata, + **cross_grain_metadata( + value_before=child.value, + factor=outcome.factor, + control=outcome.control, + parent=parent.name, + ), + }, ) kept_cd_file_state = [] @@ -777,11 +556,11 @@ def within_band( "vintage_rule_description": ( "Historic Table 2 (TY2022) is the single vintage of every state " "concept it carries. District-file (22incd.csv) district rows " - "keep only their within-state shares and are rebased to sum to " - "that parent. Concepts only the district file carries keep its " - "own state row as their parent, lifted onto the Historic Table 2 " - "basis by a sibling concept's ratio of the two files' state " - "totals in the same state (STATE_CD_LEVEL_BRIDGES)." + "keep only their within-state shares and are divided from that " + "parent by the shared cross-grain operator. Concepts only the " + "district file carries keep its own state row as their parent, " + "lifted onto the Historic Table 2 basis by a sibling concept's " + "ratio of the two files' state totals in the same state." ), "counts": { "historic_table_2_state": len(ht2_state), @@ -796,17 +575,14 @@ def within_band( "unparented_cd_measures": dict(unparented), "excluded_cd_states": dict(excluded_states), "at_large_on_source_plan": at_large_source_states, - "internal_consistency": { - "rtol": nesting.internal_rtol, - "blocks_checked": len(internal_gaps), - "max_relative_gap": max(internal_gaps, default=0.0), - }, - "factor_band": { - "tolerance": factor_band, - "relative_to": "the measure's median Historic Table 2 / " - "district-file ratio across states", - "out_of_band": sorted( - out_of_band, key=lambda row: (row["concept"], row["state_fips"]) + "bridge": { + "bridge_id": DISTRICT_SOI, + "max_factor_shift": selector.max_factor_shift, + "min_factor_shift": selector.min_factor_shift, + "shift_around": selector.shift_around, + "out_of_bound": selector.out_of_bound, + "unbound": sorted( + unbound, key=lambda row: (row["concept"], row["state_fips"]) ), }, "level_bridges": dict(level_bridges), @@ -814,7 +590,10 @@ def within_band( measure: _factor_summary(values) for measure, values in sorted(bridge_factors.items()) }, - "rebase_factor_by_measure": { + "level_bridge_out_of_band": sorted( + bridge_verdicts, key=lambda row: (row["concept"], row["state_fips"]) + ), + "factor_by_measure": { measure: _factor_summary(values) for measure, values in sorted(factors_by_measure.items()) }, @@ -840,25 +619,169 @@ def within_band( ) +def _bridged_state_parents( + ht2_by_key: Mapping[tuple, Any], + cd_file_state_by_key: Mapping[tuple, Any], + kept_cd_by_key: Mapping[tuple, Sequence], + *, + level_bridges: Mapping[str, str], + factor_band: float, + defective: Mapping[str, str], +) -> tuple[dict[str, Any], dict[str, list[float]], list[dict]]: + """The state parents of the concepts that only the district file has. + + **Until the feed re-pin** (microcosm#1760). On the pinned feed, Historic + Table 2 lacks six concepts that the district file has. Their state parent + is the district file's own state row, lifted onto the Historic Table 2 + basis by a sibling concept that both files carry: the row is multiplied by + the sibling's Historic Table 2 level over its district-file level in the + same state. The sibling is trusted only if that ratio, and the factor of + its own district block, sit within ``factor_band`` of their medians across + states. After the re-pin Historic Table 2 holds the six parents, and this + function and ``level_bridges`` go. + + Returns the lifted state rows by name, the factors by measure, and the + verdicts that refused a sibling. + """ + + def by_identity( + ratios: Mapping[tuple, float], *, positive_only: bool + ) -> dict[tuple, float]: + grouped: dict[tuple, list[float]] = defaultdict(list) + for block_key, ratio in ratios.items(): + if math.isfinite(ratio) and (ratio > 0 or not positive_only): + grouped[_identity_of_block(block_key)].append(ratio) + return { + identity: float(np.median(values)) for identity, values in grouped.items() + } + + vintage_ratio: dict[tuple, float] = {} + for key in ht2_by_key.keys() & cd_file_state_by_key.keys(): + higher = float(ht2_by_key[key].value) + lower = float(cd_file_state_by_key[key].value) + vintage_ratio[key] = ( + higher / lower if lower != 0.0 and (higher > 0) == (lower > 0) else math.nan + ) + median_ratio = by_identity(vintage_ratio, positive_only=False) + block_factor: dict[tuple, float] = {} + for key, block in kept_cd_by_key.items(): + parent = ht2_by_key.get(key) + child_sum = controls.sum_of_lower_rows(spec.value for spec in block) + if parent is not None and child_sum != 0.0: + block_factor[key] = float(parent.value) / child_sum + median_factor = by_identity(block_factor, positive_only=True) + verdicts: list[dict] = [] + + def trusted( + sibling_key: tuple, ratio: float, median: float, measure: str, verdict: str + ) -> bool: + relative = ratio / median if math.isfinite(ratio) and median else math.nan + ok = math.isfinite(relative) and 1 / factor_band <= relative <= factor_band + if not ok: + verdicts.append( + { + "state_fips": sibling_key[0], + "measure": measure, + "concept": _identity_of_block(sibling_key)[0], + "verdict": verdict, + "ratio": ratio, + "median_ratio": median, + "relative": relative, + } + ) + return ok + + bridged: dict[str, Any] = {} + factors: dict[str, list[float]] = defaultdict(list) + for key, spec in sorted(cd_file_state_by_key.items()): + state, identity = key + measure = identity[0] + if key in ht2_by_key or measure in defective: + continue + sibling = level_bridges.get(measure) + if sibling is None: + raise ValueError( + f"District-file-only concept {measure!r} has no level bridge; " + "register a sibling measure in the level bridges of " + "us/cross_grain_declarations.json before binding it." + ) + sibling_key = (state, (sibling, *identity[1:])) + ht2_sibling = ht2_by_key.get(sibling_key) + cd_sibling = cd_file_state_by_key.get(sibling_key) + if ht2_sibling is None or cd_sibling is None or float(cd_sibling.value) == 0: + raise ValueError( + f"Level bridge {measure} -> {sibling} in state {state} needs " + "the sibling's state total in both files." + ) + factor = float(ht2_sibling.value) / float(cd_sibling.value) + # A sign conflict is a data defect, not a level disagreement. + if not (math.isfinite(factor) and factor > 0.0): + raise ValueError( + f"Level bridge {measure} -> {sibling} in state {state} has " + f"factor {factor}." + ) + ok = trusted( + sibling_key, + factor, + median_ratio.get(_identity_of_block(sibling_key), math.nan), + measure, + "sibling_vintage_ratio", + ) + if sibling_key in block_factor: + ok = ( + trusted( + sibling_key, + block_factor[sibling_key], + median_factor.get(_identity_of_block(sibling_key), math.nan), + measure, + "sibling_factor", + ) + and ok + ) + if not ok: + continue + value = float(spec.value) * factor + bridged[spec.name] = replace( + spec, + value=value, + signed=value < 0.0, + metadata={ + **spec.metadata, + **cross_grain_metadata( + value_before=spec.value, + factor=factor, + control=f"level_bridge:{sibling}", + ), + }, + ) + factors[measure].append(factor) + return bridged, factors, verdicts + + def district_block_closure(specs: Sequence, *, rtol: float) -> list[dict]: """Every (state parent, district rows) block and whether it adds up. - A block is the district specs naming one ``state_cd_parent_target_name``. - Returns one entry per block with the parent value, the district sum and - ``ok`` (relative difference within ``rtol``). + A block is the district specs that name one parent + (``cross_grain_parent``). Returns one entry per block with the parent + value, the district sum and ``ok`` (relative difference within ``rtol``). """ + _state_level, district_level = us_pass_grains(DISTRICT_SOI) by_name = {spec.name: spec for spec in specs} blocks: dict[str, list] = defaultdict(list) for spec in specs: - parent = spec.metadata.get("state_cd_parent_target_name") - if parent is not None: + parent = spec.metadata.get(PARENT_KEY) + if ( + parent is not None + and spec.metadata.get("ledger_geography_level") == district_level + ): blocks[parent].append(spec) report = [] for parent_name, children in sorted(blocks.items()): parent = by_name.get(parent_name) child_sum = controls.sum_of_lower_rows(spec.value for spec in children) parent_value = None if parent is None else float(parent.value) + scale = max(abs(parent_value or 0.0), 1.0) report.append( { "parent": parent_name, @@ -867,7 +790,7 @@ def district_block_closure(specs: Sequence, *, rtol: float) -> list[dict]: "district_sum": child_sum, "n_districts": len(children), "ok": parent is not None - and controls.sum_gap(parent_value, child_sum).within(rtol), + and abs(child_sum - parent_value) <= rtol * scale, } ) return report @@ -879,12 +802,8 @@ def _identity_of_block(key: tuple) -> tuple: return key[1] -def _bits(*values: float) -> bytes: - return b"".join(struct.pack(" list[int]: """The county codes one county child row covers (one unless combined).""" - members = metadata.get("state_county_cell_members") + members = metadata.get(MEMBERS_KEY) if members: return [int(member) for member in str(members).split(",")] return [int(metadata["county_fips"])] -# --------------------------------------------------------------------------- -# State to county: resident population (issue row 8) -# --------------------------------------------------------------------------- - -#: The quantity the county population mechanism reconciles. -POPULATION_CONCEPT = "census_population.resident_population" - - -def county_population_rows( - state_populations: Mapping, overlap_counties: np.ndarray, overlap_values: np.ndarray -) -> dict[int, float]: - """County populations from ladder overlaps, reconciled to state levels. - - Sums the ladder's overlap populations by county, then the operator - divides each state's total among its counties - (``scale_residual_to_largest``): the rounding residual goes to the largest - county, never a small one. - - Raises: - ValueError: If a state has no county or no positive population, or - if a county has no state. - """ - - raw = { - int(code): controls.sum_of_lower_rows(overlap_values[overlap_counties == code]) - for code in np.unique(overlap_counties) - } - mechanism = us_cross_grain_mechanism(COUNTY_POPULATION) - state_level, county_level = mechanism["higher_grain"], mechanism["lower_grain"] - blocks, block_codes = [], [] - for state, target in sorted(state_populations.items()): - block = sorted(code for code in raw if code // 1000 == int(state)) - total = controls.sum_of_lower_rows(raw[code] for code in block) - if not block or total <= 0 or not math.isfinite(target) or target <= 0: - raise ValueError(f"State {state} has no positive county/state population.") - blocks.append( - NestingBlock( - concept=POPULATION_CONCEPT, - filters=(), - control_geography_id=geography_id(state_level, f"{int(state):02d}"), - control_value=float(target), - lower_geography_ids=tuple( - geography_id(county_level, f"{code:05d}") for code in block - ), - lower_values=tuple(raw[code] for code in block), - ) - ) - block_codes.append(block) - nested, _operator_receipt = reconcile_blocks(COUNTY_POPULATION, blocks) - counties: dict[int, float] = {} - for block, rows in zip(block_codes, nested, strict=True): - counties.update(zip(block, rows.values, strict=True)) - unknown = sorted(set(raw) - set(counties)) - if unknown: - raise ValueError(f"County populations have no state parent: {unknown}.") - return counties - - -# --------------------------------------------------------------------------- -# State to county: IRS SOI shares (issue row 6) -# --------------------------------------------------------------------------- - - def is_broad_state_parent(spec) -> bool: """A state SOI row county facts can divide: all returns, no class.""" @@ -1073,6 +929,114 @@ def validated_combined_cells(combined_cells): return cells +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, source_name, *, state=None, county=None): + from microcosm.calibrate import ( + CalibrationHierarchy, + HierarchyCategory, + HierarchyGeography, + HierarchyNode, + ) + from microcosm.calibrate.provider_labels import calibration_provider_label + + provider = HierarchyNode(source_name, calibration_provider_label("us", source_name)) + if county is not None: + # The same label every county family gives this county + # (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}" + + +# --------------------------------------------------------------------------- +# State to county: resident population (issue row 8) +# --------------------------------------------------------------------------- + +#: The quantity of the ladder population. The ladder is one source at two +#: levels, so its state row and its county rows have one measurement. +POPULATION_TARGET = "census_population.resident_population" + + +def county_population_rows( + state_populations: Mapping[int, float], + overlap_counties: np.ndarray, + overlap_values: np.ndarray, +) -> dict[int, float]: + """County populations from ladder overlaps, reconciled to state levels. + + Sums the ladder's overlap populations by county. The operator then + divides each state's total among its counties. A state with no county, a + county with no state, and a state whose counties sum to zero are refused + by the operator. + """ + + state_level, county_level = us_pass_grains(COUNTY_POPULATION) + raw = { + int(code): controls.sum_of_lower_rows(overlap_values[overlap_counties == code]) + for code in np.unique(overlap_counties) + } + rows: list[SurfaceRow] = [] + legs: dict[str, str] = {} + for state, target in sorted(state_populations.items()): + if not math.isfinite(target) or target <= 0: + raise ValueError(f"State {state} has no positive county/state population.") + rows.append( + SurfaceRow( + state_level, + geography_id(state_level, f"{int(state):02d}"), + POPULATION_TARGET, + float(target), + ) + ) + codes = sorted(raw) + for code in codes: + area = geography_id(county_level, f"{code:05d}") + legs[area] = geography_id(state_level, f"{code // 1000:02d}") + rows.append(SurfaceRow(county_level, area, POPULATION_TARGET, raw[code])) + outcomes, _receipt = run_pass( + COUNTY_POPULATION, rows, bound_higher_targets=[POPULATION_TARGET], legs=legs + ) + counties: dict[int, float] = {} + for code, outcome in zip(codes, outcomes[len(rows) - len(codes) :], strict=True): + if outcome.status != controls.RECONCILED: + raise ValueError(f"County {code:05d} population has no state parent.") + counties[code] = outcome.value + return counties + + +# --------------------------------------------------------------------------- +# State to county: IRS SOI (issue row 6) +# --------------------------------------------------------------------------- + +COUNTY_FILE = "county_file" + + def county_soi_surface( state_specs: Sequence, facts: Iterable[Mapping[str, Any]], @@ -1081,20 +1045,19 @@ def county_soi_surface( combined_cells: Mapping[int, int], soi_mode: str, ) -> NestedSurface: - """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. - 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. The operator - divides each state row among its cells (``share_residual_to_largest``). + """Divide the broad state SOI rows among the counties of the county facts. + + Every state must carry county return count and AGI with broad state + parents. Other measures need both county facts and a state parent. The + declared bridge ``state_soi_vs_county_file`` ties each state row to the + county facts of its measure and period, and the operator divides it. A + county absent from a block is refused unless ``combined_cells`` declares + it with its host present: then the host's row stands for both counties, + and ``cross_grain_members`` lists them. """ nesting = us_county_soi_nesting() - mechanism = us_cross_grain_mechanism(COUNTY_SOI) - state_level, county_level = mechanism["higher_grain"], mechanism["lower_grain"] + state_level, county_level = us_pass_grains(COUNTY_SOI) combined = validated_combined_cells(combined_cells) blocks = defaultdict(dict) for fact in facts: @@ -1157,36 +1120,44 @@ def county_soi_surface( f"Missing broad state SOI parent state={state:02d}, concept={measure}; " "state_county requires return count and AGI in every state." ) - # Every check a block must pass before the operator divides its control. + + # The surface: for each state row, the county facts of its measure. + rows: list[SurfaceRow] = [] + legs: dict[str, str] = {} + expected: dict[str, dict[str, frozenset[str]]] = {} + bound: list[str] = [] + targets: dict[str, dict[str, str]] = {} merges = defaultdict(list) checked = [] for key, parent in sorted(parents.items()): state, measure, period = key - expected = { + counties = { int(code) for code in county_populations if int(code) // 1000 == state } - block = blocks.get(key, {}) - completeness = controls.leg_completeness( - block, expected, combined_cells=combined - ) - if not expected or not completeness.complete: + if not counties: raise ValueError( - f"Incomplete county SOI block state={state:02d}, concept={measure}, period={period}; " - f"missing={[f'{code:05d}' for code in completeness.missing]}, unexpected={[f'{code:05d}' for code in completeness.unexpected]}. " - "County facts, ladder and county column must use matching boundaries; " - "only a declared combined SOI cell may cover an absent county." + f"State {state:02d} has a broad SOI parent for {measure} and no " + "county in the ladder. County facts, ladder and county column " + "must use matching boundaries." ) + block = blocks.get(key, {}) + absent = counties - block.keys() + merged = { + code: combined[code] + for code in absent + if code in combined + and combined[code] in block + and combined[code] in counties + } members = {code: [code] for code in sorted(block)} - for code, host in sorted(completeness.merged.items()): + for code, host in sorted(merged.items()): members[host].append(code) merges[(host, code)].append(f"{measure}|{period}") codes = sorted(block) - raw_values = [block[code][0] for code in codes] - if controls.sum_of_lower_rows(raw_values) <= 0: + if codes and controls.sum_of_lower_rows(block[code][0] for code in codes) <= 0: raise ValueError( f"County SOI block {key} has no positive share denominator." ) - shares, _total, _largest = controls.residual_shares(raw_values) for code in codes: unit = block[code][1].get("observed_measure", {}).get("unit") if ( @@ -1196,35 +1167,52 @@ def county_soi_surface( raise ValueError( f"County SOI units differ from state parent {parent.name}: {unit!r}." ) - checked.append((key, parent, expected, block, members, codes, shares)) + attributes = {"source_measure_id": str(measure), "source_period": period} + higher_id = f"{STATE_SURFACE}|{measure}|{period}" + lower_id = f"{COUNTY_FILE}|{measure}|{period}" + targets[higher_id] = { + "source": STATE_SURFACE, + "grain": state_level, + **attributes, + } + targets[lower_id] = {"source": COUNTY_FILE, "grain": county_level, **attributes} + state_area = geography_id(state_level, f"{state:02d}") + bound.append(higher_id) + checked.append((key, parent, counties, block, members, codes, len(rows))) + rows.append(SurfaceRow(state_level, state_area, higher_id, float(parent.value))) + for code in codes: + area = geography_id(county_level, f"{code:05d}") + legs[area] = state_area + rows.append(SurfaceRow(county_level, area, lower_id, block[code][0])) + expected.setdefault(lower_id, {})[state_area] = frozenset( + geography_id(county_level, f"{code:05d}") + for code in counties - merged.keys() + ) - # The operator divides each state row among its county cells. - nested, operator_receipt = reconcile_blocks( + bridges, _unpaired = expand_bridge_selectors( + [us_bridge_selector(COUNTY_SOI)], targets + ) + outcomes, operator_receipt = run_pass( COUNTY_SOI, - [ - NestingBlock( - concept=f"{parent.family}.{measure}", - filters=(("source_period", period),), - control_geography_id=geography_id(state_level, f"{state:02d}"), - control_value=float(parent.value), - lower_geography_ids=tuple( - geography_id(county_level, f"{code:05d}") for code in codes - ), - lower_values=tuple(block[code][0] for code in codes), - ) - for (state, measure, period), parent, _e, block, _m, codes, _s in checked - ], + rows, + bound_higher_targets=bound, + legs=legs, + bridges=bridges, + expected_members=expected, ) specs, receipts = [], [] - for (key, parent, expected, block, members, codes, shares), rows in zip( - checked, nested, strict=True - ): + for key, parent, counties, block, members, codes, start in checked: state, measure, period = key - targets = list(rows.values) + block_outcomes = outcomes[start + 1 : start + 1 + len(codes)] state_population = controls.sum_of_lower_rows( - county_populations[code] for code in expected + county_populations[code] for code in counties ) - for code, share, target in zip(codes, shares, targets, strict=True): + for code, outcome in zip(codes, block_outcomes, strict=True): + if outcome.status != controls.RECONCILED: + raise ValueError( + f"The operator did not reconcile county {code:05d} under " + f"{parent.name}." + ) raw, fact = block[code] county = f"{code:05d}" cell = sorted(members[code]) @@ -1241,9 +1229,15 @@ def county_soi_surface( ), "county_fips": county, "county_label": str(fact["geography"].get("name", county)), - "state_county_parent_target_name": parent.name, - "state_county_share": str(share), - "state_county_source_value": str(raw), + **cross_grain_metadata( + value_before=raw, + factor=outcome.factor, + control=outcome.control, + parent=parent.name, + members=( + [f"{member:05d}" for member in cell] if len(cell) > 1 else () + ), + ), "county_population": str( controls.sum_of_lower_rows( county_populations[member] for member in cell @@ -1251,17 +1245,12 @@ def county_soi_surface( ), "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"] = nesting.combined_cell_basis specs.append( replace( parent, name=name, measure=name, - value=target, + value=outcome.value, se=None, metadata=metadata, hierarchy=county_hierarchy(name, county, parent=parent), @@ -1273,10 +1262,11 @@ def county_soi_surface( "state_fips": f"{state:02d}", "concept": measure, "parent": parent.name, - "counties": len(expected), + "counties": len(counties), "cells": len(codes), - "share_sum": controls.sum_of_lower_rows(shares), - "target_sum": controls.sum_of_lower_rows(targets), + "target_sum": controls.sum_of_lower_rows( + outcome.value for outcome in block_outcomes + ), } ) # Counties without a state parent cannot silently disappear. @@ -1288,6 +1278,7 @@ def county_soi_surface( "soi_mode": soi_mode, "county_targets": len(specs), "concepts": sorted({key[1] for key in parents}), + "bridge": COUNTY_SOI, "blocks": receipts, "combined_cells": [ { @@ -1315,51 +1306,6 @@ def county_soi_surface( # --------------------------------------------------------------------------- -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, source_name, *, state=None, county=None): - from microcosm.calibrate import ( - CalibrationHierarchy, - HierarchyCategory, - HierarchyGeography, - HierarchyNode, - ) - from microcosm.calibrate.provider_labels import calibration_provider_label - - provider = HierarchyNode(source_name, calibration_provider_label("us", source_name)) - if county is not None: - # The same label every county family gives this county - # (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 county_acs_household_surface( values: Mapping[int, tuple[float, float | None, str]], county_populations: Mapping[int, float], @@ -1373,20 +1319,22 @@ def county_acs_household_surface( """State households parents and their county children (trained, levels). ``values`` is ``{county: (estimate, margin of error or None, name)}`` for - the households measure. Each state parent is the sum of its counties' - estimates (``sum_of_lower_rows``), a new state target that moves state - household counts to ACS 5-year levels; the operator then divides it among - the counties by share (``share_residual_to_largest``), so they sum to it. - ACS margins of error ride in metadata. + the households measure. No source in the feed publishes the state level, + so the control of each state is derived: the sum of its counties' + estimates. It is a new state target. The operator then divides it among + the counties, so they sum to it. ACS margins of error ride in metadata. """ from microcosm.calibrate import TargetSpec - mechanism = us_cross_grain_mechanism(COUNTY_ACS_HOUSEHOLDS) - state_level, county_level = mechanism["higher_grain"], mechanism["lower_grain"] + state_level, county_level = us_pass_grains(COUNTY_ACS_HOUSEHOLDS) + lower_id = f"{source_name}|{measure}" + higher_id = f"{lower_id}#sum" source = ( f"US Census Bureau {tables} B11001_001E (households), county; " "state = sum of its counties" ) + rows: list[SurfaceRow] = [] + legs: dict[str, str] = {} checked = [] for state in sorted({int(code) // 1000 for code in county_populations}): codes = sorted(code for code in values if code // 1000 == state) @@ -1397,35 +1345,31 @@ def county_acs_household_surface( f"ACS county households for state {state:02d} have no positive " "share denominator." ) - shares, _total, _largest = controls.residual_shares(public) - # Naming the state parent refuses a state with no Census name here, - # in state order, as it did when the parent was built in this loop. parent_name = acs_households_parent_name(state) parent_hierarchy = _acs_hierarchy(parent_name, source_name, state=state) - checked.append((state, codes, public, total, shares, parent_hierarchy)) - - # The operator divides each state's sum among its counties. - nested, operator_receipt = reconcile_blocks( + state_area = geography_id(state_level, f"{state:02d}") + checked.append((state, codes, total, parent_name, parent_hierarchy, len(rows))) + rows.append(SurfaceRow(state_level, state_area, higher_id, total)) + for code, estimate in zip(codes, public, strict=True): + area = geography_id(county_level, f"{code:05d}") + legs[area] = state_area + rows.append(SurfaceRow(county_level, area, lower_id, estimate)) + bridge = CrossGrainBridge( + bridge_id=COUNTY_ACS_HOUSEHOLDS, + concept=f"{source_name}.{measure}", + higher_target_ids=(higher_id,), + lower_side=lower_id, + ) + outcomes, operator_receipt = run_pass( COUNTY_ACS_HOUSEHOLDS, - [ - NestingBlock( - concept=f"{source_name}.{measure}", - filters=(), - control_geography_id=geography_id(state_level, f"{state:02d}"), - control_value=total, - lower_geography_ids=tuple( - geography_id(county_level, f"{code:05d}") for code in codes - ), - lower_values=tuple(public), - ) - for state, codes, public, total, _shares, _hierarchy in checked - ], + rows, + bound_higher_targets=[higher_id], + legs=legs, + bridges=[bridge], ) specs, receipts = [], [] - for (state, codes, _public, total, shares, parent_hierarchy), rows in zip( - checked, nested, strict=True - ): - parent_name = acs_households_parent_name(state) + for state, codes, total, parent_name, parent_hierarchy, start in checked: + block_outcomes = outcomes[start + 1 : start + 1 + len(codes)] state_population = controls.sum_of_lower_rows( county_populations[code] for code in codes ) @@ -1449,8 +1393,12 @@ def county_acs_household_surface( hierarchy=parent_hierarchy, ) ) - targets = list(rows.values) - for code, share, target in zip(codes, shares, targets, strict=True): + for code, outcome in zip(codes, block_outcomes, strict=True): + if outcome.status != controls.RECONCILED: + raise ValueError( + f"The operator did not reconcile county {code:05d} under " + f"{parent_name}." + ) county = f"{code:05d}" name = f"county_{county}__{parent_name}" estimate, moe, label = values[code] @@ -1459,9 +1407,12 @@ def county_acs_household_surface( "county_fips": county, "state_fips": f"{state:02d}", "source_measure_id": measure, - "state_county_parent_target_name": parent_name, - "state_county_share": str(share), - "state_county_source_value": str(estimate), + **cross_grain_metadata( + value_before=estimate, + factor=outcome.factor, + control=outcome.control, + parent=parent_name, + ), "county_population": str(county_populations[code]), "state_population": str(state_population), "household_universe": "excludes ACS group quarters (TYPEHUGQ 2, 3)", @@ -1475,7 +1426,7 @@ def county_acs_household_surface( name=name, entity="household", measure=name, - value=target, + value=outcome.value, period=period, source=f"US Census Bureau {tables} B11001_001E " "(households), county share of the state sum", @@ -1490,8 +1441,9 @@ def county_acs_household_surface( "state_target": parent_name, "state_households": total, "counties": len(codes), - "share_sum": controls.sum_of_lower_rows(shares), - "target_sum": controls.sum_of_lower_rows(targets), + "target_sum": controls.sum_of_lower_rows( + outcome.value for outcome in block_outcomes + ), "counties_with_moe": sum(values[code][1] is not None for code in codes), } ) @@ -1499,6 +1451,7 @@ def county_acs_household_surface( "family": family, "source_measure_id": measure, "source": f"{tables} county B11001", + "bridge": COUNTY_ACS_HOUSEHOLDS, "new_state_targets": len(receipts), "county_targets": len(specs) - len(receipts), "note": ( diff --git a/packages/microcosm-build/tests/engine_free/shared/test_cross_grain_controls.py b/packages/microcosm-build/tests/engine_free/shared/test_cross_grain_controls.py index e06e705a50..1826c58e4a 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_cross_grain_controls.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_cross_grain_controls.py @@ -1,8 +1,8 @@ -"""The controls, allocators and checks beside the cross-grain operator. +"""The row-level pass and the allocators beside the cross-grain operator. -``microcosm.build.cross_grain_controls`` holds what a country's sources can -need around the operator (microcosm#1760). The allocators must give, bit for -bit, the arithmetic they replace; the ``_old_*`` functions here state that +``microcosm.build.cross_grain_controls`` runs the operator on target rows and +says what it did with each row (microcosm#1760). Its allocators must give, bit +for bit, the arithmetic they replace; the ``_old_*`` functions here state that arithmetic as it was written before the operator ran it. """ @@ -20,6 +20,8 @@ from microcosm.build import cross_grain_controls as controls from microcosm.build.cross_grain import ( + EXACT_SIGNATURE_CONTROL, + CrossGrainBridge, CrossGrainRule, apply_cross_grain_reconciliation, ) @@ -197,107 +199,119 @@ def test_the_operator_runs_each_allocator(name: str) -> None: ) -def test_derived_controls() -> None: - # Exactly rounded: a running float total would lose the 1.0. +def test_sum_of_lower_rows_is_exactly_rounded() -> None: + # A running float total would lose the 1.0. assert controls.sum_of_lower_rows([1e16, 1.0, -1e16]) == 1.0 assert controls.sum_of_lower_rows([0.1] * 10) == 1.0 - assert controls.sibling_ratio(110.0, 100.0) == 110.0 / 100.0 - scaled, factor = controls.scaled_by_sibling_ratio(40.0, 110.0, 100.0) - assert (scaled, factor) == (40.0 * (110.0 / 100.0), 110.0 / 100.0) -def test_level_ratio_is_undefined_at_zero_or_across_signs() -> None: - assert controls.level_ratio(6.0, 4.0) == 1.5 - assert controls.level_ratio(-6.0, -4.0) == 1.5 - assert controls.level_ratio(0.0, 0.0) != controls.level_ratio(0.0, 0.0) # NaN - for higher, lower in ((6.0, 0.0), (6.0, -4.0), (-6.0, 4.0), (0.0, 4.0)): - assert math.isnan(controls.level_ratio(higher, lower)), (higher, lower) - # Zero over a negative level: neither is positive, so a ratio is defined. - assert controls.level_ratio(0.0, -4.0) == 0.0 +def _row_rule(*bridges: CrossGrainBridge) -> CrossGrainRule: + return CrossGrainRule( + grain_precedence=("nation", "state", "district"), + signature_fields=("concept",), + bridges=bridges, + leg_of_area=lambda area: area[0], + parent_geography_legs={state: (state,) for state in "ABCDE"}, + control_grains=("nation", "state"), + ) -def test_control_ratio_is_the_proportional_factor() -> None: - for seed in range(40): - values, parent = _block(seed, signed=True) - ratio, lower_sum = controls.control_ratio(parent, values.tolist()) - _values, factor, raw_sum = controls.proportional_fsum(values, parent) - if raw_sum == 0.0: - assert ratio is None - else: - assert (ratio, lower_sum) == (factor, raw_sum) - assert controls.control_ratio(5.0, [1.0, -1.0]) == (None, 0.0) - - -def test_median_by_group_reads_finite_ratios_only() -> None: - ratios = { - ("a", "x"): 1.0, - ("b", "x"): 3.0, - ("c", "x"): math.nan, - ("d", "x"): math.inf, - ("a", "y"): -2.0, - ("b", "y"): 0.0, - ("c", "y"): 4.0, - ("a", "z"): math.nan, - } - assert controls.median_by_group(ratios, lambda key: key[1]) == { - "x": 2.0, - "y": 0.0, - } - assert controls.median_by_group(ratios, lambda key: key[1], positive_only=True) == { - "x": 2.0, - "y": 4.0, - } +def _rows(target: str, factors: dict[str, float]) -> list[controls.SurfaceRow]: + """A state total and two districts in each state; the factor is their gap.""" + rows = [] + for state, factor in factors.items(): + rows.append(controls.SurfaceRow("state", state, "total", 100.0 * factor)) + rows.append(controls.SurfaceRow("district", f"{state}1", target, 30.0)) + rows.append(controls.SurfaceRow("district", f"{state}2", target, 70.0)) + return rows -def test_band_verdict() -> None: - inside = controls.band_verdict(1.2, 1.0, 1.25) - assert inside == controls.BandVerdict(True, 1.2, 1.0, 1.2) - assert controls.band_verdict(1.25, 1.0, 1.25).ok - assert controls.band_verdict(0.8, 1.0, 1.25).ok - assert not controls.band_verdict(1.26, 1.0, 1.25).ok - assert not controls.band_verdict(0.79, 1.0, 1.25).ok - # No median, a zero median or a ratio that is not finite: no verdict. - for ratio, median in ((1.0, math.nan), (1.0, 0.0), (math.nan, 1.0), (math.inf, 1)): - verdict = controls.band_verdict(ratio, median, 1.25) - assert not verdict.ok and math.isnan(verdict.relative), (ratio, median) - # An unbounded band still refuses a ratio on the other side of zero. - assert controls.band_verdict(1e9, 1.0, math.inf).ok - assert not controls.band_verdict(-1.0, 1.0, math.inf).ok - - -def test_leg_completeness() -> None: - complete = controls.leg_completeness(["a", "b"], {"a", "b"}) - assert complete.complete and complete.merged == {} - report = controls.leg_completeness(["a", "a", "x"], ["a", "b", "c"]) - assert not report.complete - assert (report.missing, report.unexpected, report.duplicated) == ( - ("b", "c"), - ("x",), - ("a",), + +def test_reconcile_rows_names_the_control_of_each_row() -> None: + """Rows of the control's own measurement: no bridge, one parent row.""" + + signatures = { + "total": {"measurement": {"concept": "quantity"}}, + "parts": {"measurement": {"concept": "quantity"}}, + } + rows = _rows("parts", {"A": 1.1, "B": 0.5}) + outcomes, receipt = controls.reconcile_rows( + rows, ("total",), signatures, _row_rule() + ) + assert len(outcomes) == len(rows) + assert [outcome.status for outcome in outcomes] == [ + controls.UNTOUCHED, + controls.RECONCILED, + controls.RECONCILED, + ] * 2 + assert [outcome.value for outcome in outcomes] == pytest.approx( + [110.0, 33.0, 77.0, 50.0, 15.0, 35.0] + ) + # A control row keeps its value and names nothing. + assert outcomes[0] == controls.RowOutcome(value=rows[0].value) + for position, parent, factor in ((1, 0, 1.1), (2, 0, 1.1), (4, 3, 0.5)): + outcome = outcomes[position] + assert outcome.control == EXACT_SIGNATURE_CONTROL + assert outcome.parent == parent + assert outcome.factor == pytest.approx(factor) + assert outcome.lower_total == 100.0 + assert len(receipt["groups"]) == 1 + + +def test_reconcile_rows_reads_a_bridge_and_its_unbound_legs() -> None: + """Two sources: the bridge is the control, and a leg out of bound unbinds.""" + + signatures = { + "total": {"measurement": {"concept": "source one"}}, + "parts": {"measurement": {"concept": "source two"}}, + } + bridge = CrossGrainBridge( + "total_vs_parts", + concept="one quantity", + higher_target_ids=("total",), + lower_side="parts", + max_factor_shift=0.25, + min_factor_shift=-0.2, + shift_around="median", + out_of_bound="unbind", + ) + factors = {"A": 2.0, "B": 2.0, "C": 2.0, "D": 2.0, "E": 4.0} + rows = _rows("parts", factors) + outcomes, receipt = controls.reconcile_rows( + rows, ("total",), signatures, _row_rule(bridge) ) - # A declared combined cell covers an absent member through its host. - merged = controls.leg_completeness( - ["a", "b"], ["a", "b", "c"], combined_cells={"c": "b", "z": "a"} + for index, state in enumerate(factors): + total, first, second = outcomes[3 * index : 3 * index + 3] + assert total.status == controls.UNTOUCHED + assert first.control == second.control == "total_vs_parts" + assert first.parent == second.parent == 3 * index + if state == "E": + # The leg keeps its values. The caller takes it off its surface. + assert first.status == second.status == controls.UNBOUND + assert (first.value, second.value) == (30.0, 70.0) + assert first.factor == pytest.approx(4.0) + else: + assert first.status == second.status == controls.RECONCILED + assert (first.value, second.value) == pytest.approx((60.0, 140.0)) + assert first.factor == pytest.approx(2.0) + assert first.lower_total == 100.0 + assert [leg["leg"] for leg in receipt["unbound_legs"]] == ["E"] + + +def test_reconcile_rows_leaves_a_row_that_no_group_covers() -> None: + signatures = { + "total": {"measurement": {"concept": "quantity"}}, + "parts": {"measurement": {"concept": "quantity"}}, + "other": {"measurement": {"concept": "another quantity"}}, + } + rows = [ + *_rows("parts", {"A": 1.0}), + controls.SurfaceRow("district", "A1", "other", 7.0), + ] + outcomes, _receipt = controls.reconcile_rows( + rows, ("total",), signatures, _row_rule() ) - assert merged.complete and merged.merged == {"c": "b"} - # The host must be present and expected. - for present, expected in ((["a"], ["a", "b", "c"]), (["a", "b"], ["a", "c"])): - report = controls.leg_completeness(present, expected, combined_cells={"c": "b"}) - assert "c" in report.missing and report.merged == {} - - -def test_sum_gap() -> None: - gap = controls.sum_gap(100.0, 99.0) - assert (gap.gap, gap.scale, gap.relative) == (1.0, 100.0, 0.01) - assert gap.within(0.01) and not gap.exceeds(0.01) - assert gap.exceeds(0.001) and not gap.within(0.001) - # A total near zero is judged on the absolute gap. - small = controls.sum_gap(0.0, 0.5) - assert (small.gap, small.scale) == (0.5, 1.0) - assert controls.sum_gap(0.0, 0.5, floor=0.25).scale == 0.25 - # A gap that is not a number is neither within nor beyond a tolerance. - undefined = controls.sum_gap(math.nan, 1.0) - assert not undefined.within(1.0) and not undefined.exceeds(1.0) + assert outcomes[-1] == controls.RowOutcome(value=7.0) def test_the_module_holds_no_country_and_the_operator_does_not_import_it() -> None: @@ -305,13 +319,20 @@ def test_the_module_holds_no_country_and_the_operator_does_not_import_it() -> No source = inspect.getsource(controls) imported = { - (node.module if isinstance(node, ast.ImportFrom) else alias.name).split(".")[0] + (node.module if isinstance(node, ast.ImportFrom) else alias.name) for node in ast.walk(ast.parse(source)) if isinstance(node, ast.Import | ast.ImportFrom) for alias in node.names } - assert imported <= {"__future__", "collections", "dataclasses", "math", "numpy"} | { - "typing" + assert imported <= { + "__future__", + "collections.abc", + "dataclasses", + "math", + "typing", + "numpy", + "pandas", + "microcosm.build.cross_grain", } named = re.findall( r"\b(us|uk|us_runtime|uk_runtime|irs|soi|census|hmrc)\b", source.lower() diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_cd_properties.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_cd_properties.py index 243568e5e3..a477369a9f 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_cd_properties.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_cd_properties.py @@ -17,7 +17,6 @@ from __future__ import annotations -import dataclasses import importlib.util import math @@ -196,6 +195,12 @@ def _state_cd_inputs(draw): unique=True, ) ) + # One concept has one parent source: Historic Table 2 has a measure in + # every state or in none. + in_table_2 = { + measure: measure == "return_count" or draw(st.booleans()) + for measure in measures + } positive = st.floats(1.0, 1e10, allow_nan=False, allow_infinity=False) specs, crosswalk, layout = [], [], {} for state in states: @@ -215,7 +220,7 @@ def _state_cd_inputs(draw): # file has no sub-state rows for it, whatever the current plan says. layout[state] = (districts, len(source) == 1) for measure in measures: - if measure == "return_count" or draw(st.booleans()): + if in_table_2[measure]: specs.append( _soi_spec( f"ht2.{state}.{measure}", @@ -293,14 +298,12 @@ def test_district_targets_add_up_to_one_state_vintage(inputs) -> None: ] by_parent: dict[str, list] = {} for spec in districts: - by_parent.setdefault(spec.metadata["state_cd_parent_target_name"], []).append( - spec - ) + by_parent.setdefault(spec.metadata["cross_grain_parent"], []).append(spec) state = spec.metadata["state_fips"] measure = spec.metadata["source_measure_id"] ht2 = f"ht2.{state}.{measure}" expected_parent = ht2 if ht2 in original else f"cdfile.{state}_total.{measure}" - assert spec.metadata["state_cd_parent_target_name"] == expected_parent + assert spec.metadata["cross_grain_parent"] == expected_parent assert expected_parent in kept if expected_parent != ht2: # A district-file-only state level is lifted onto the Historic @@ -365,19 +368,22 @@ def district(index, value): ) predicate = _TOOL.soi_surface_predicate("state") - with pytest.raises(ValueError, match="expected the current plan"): + with pytest.raises( + ValueError, + match=r"leg 'state:10': missing \['congressional_district:1002'\]", + ): _CD.state_cd_soi_surface( [parent, district(1, 5.0)], state_surface_predicate=predicate, crosswalk=crosswalk, ) - with pytest.raises(ValueError, match="sum to zero"): + with pytest.raises(ValueError, match="vanishing lower-leg total"): _CD.state_cd_soi_surface( [parent, district(1, 0.0), district(2, 0.0)], state_surface_predicate=predicate, crosswalk=crosswalk, ) - with pytest.raises(ValueError, match="opposite in sign"): + with pytest.raises(ValueError, match="opposite-signed lower and control"): _CD.state_cd_soi_surface( [parent, district(1, -5.0), district(2, -1.0)], state_surface_predicate=predicate, @@ -440,7 +446,7 @@ def _records(draw): ] ) ), - "state_cd_parent_target_name": "parent", + "cross_grain_parent": "parent", } ) records.append(record) @@ -572,7 +578,7 @@ def test_a_pro_rata_block_sums_to_its_state_parent(parent_value, populations) -> { "name": f"cd_{index}", "value": 0.0, - "state_cd_parent_target_name": "parent", + "cross_grain_parent": "parent", "cd_population": population, "state_population": state_population, } @@ -663,11 +669,7 @@ def test_blocks_off_their_concepts_median_ratio_are_dropped_and_recorded( for spec in surface.specs if spec.metadata["ledger_geography_level"] == "congressional_district" } - recorded = { - row["state_fips"] - for row in surface.receipt["factor_band"]["out_of_band"] - if row["basis"] == "rebase" - } + recorded = {row["state_fips"] for row in surface.receipt["bridge"]["unbound"]} for index, factor in enumerate(factors): state = f"{10 + index:02d}" relative = factor / typical @@ -753,6 +755,18 @@ def _bridge_surface(ratios, at_large=None): ) +def _verdicts(surface): + """The legs the bridge unbound, and the level bridges it distrusts.""" + + return { + (row["state_fips"], row["concept"], "rebase_factor") + for row in surface.receipt["bridge"]["unbound"] + } | { + (row["state_fips"], row["measure"], row["verdict"]) + for row in surface.receipt["level_bridge_out_of_band"] + } + + def _bound(surface, state, measure, level): return [ spec.name @@ -770,14 +784,11 @@ def test_a_bridge_through_an_out_of_band_sibling_drops_its_state_and_districts() # 1. State 14's two levels disagree 2x: both verdicts fail there. surface = _bridge_surface({"10": 1.0, "11": 1.0, "12": 1.0, "13": 1.0, "14": 2.0}) - verdicts = { - (row["state_fips"], row["measure"], row["verdict"]) - for row in surface.receipt["factor_band"]["out_of_band"] - } + verdicts = _verdicts(surface) assert verdicts == { ("14", "return_count", "rebase_factor"), ("14", "charitable_amount", "sibling_vintage_ratio"), - ("14", "charitable_amount", "sibling_rebase_factor"), + ("14", "charitable_amount", "sibling_factor"), } assert not _bound(surface, "14", "charitable_amount", "state") assert not _bound(surface, "14", "charitable_amount", "congressional_district") @@ -798,13 +809,10 @@ def test_a_bridge_through_an_out_of_band_sibling_drops_its_state_and_districts() {"10": 1.0, "11": 1.0, "12": 1.0, "13": 1.0, "14": 1.3}, {f"{20 + index}": 1.2 for index in range(8)}, ) - verdicts = { - (row["state_fips"], row["measure"], row["verdict"]) - for row in surface.receipt["factor_band"]["out_of_band"] - } + verdicts = _verdicts(surface) assert verdicts == { ("14", "return_count", "rebase_factor"), - ("14", "charitable_amount", "sibling_rebase_factor"), + ("14", "charitable_amount", "sibling_factor"), } assert not _bound(surface, "14", "charitable_amount", "state") assert not _bound(surface, "14", "charitable_amount", "congressional_district") @@ -812,8 +820,8 @@ def test_a_bridge_through_an_out_of_band_sibling_drops_its_state_and_districts() assert _bound(surface, "20", "charitable_amount", "state") -def test_a_sign_conflict_or_a_self_contradicting_district_file_is_refused() -> None: - """Defects inside the data are refused, not dropped as level gaps.""" +def test_a_sign_conflict_is_refused() -> None: + """A defect inside the data is refused, not dropped as a level gap.""" specs, crosswalk = _bridge_world({"10": 1.0, "11": 1.0, "12": -1.0}, {}) with pytest.raises(ValueError, match="has factor"): @@ -823,30 +831,27 @@ def test_a_sign_conflict_or_a_self_contradicting_district_file_is_refused() -> N crosswalk=crosswalk, level_bridges={"charitable_amount": "return_count"}, ) + + +def test_a_concept_with_two_parent_sources_is_refused() -> None: + """Historic Table 2 holds a concept in every state or in none.""" + specs, crosswalk = _bridge_world({"10": 1.0, "11": 1.0, "12": 1.0}, {}) - broken = [ - dataclasses.replace(spec, value=spec.value * (1 + 1e-4)) - if spec.name == "cdfile.1101.return_count" - else spec - for spec in specs + mixed = [ + *specs, + _soi_spec( + "ht2.10.charitable_amount", + "charitable_amount", + 500.0, + level="state", + record_set=_HT2, + state="10", + ), ] - with pytest.raises(ValueError, match="differs from the sum of its district"): + with pytest.raises(ValueError, match="one concept has one parent source"): _CD.state_cd_soi_surface( - broken, + mixed, state_surface_predicate=_TOOL.soi_surface_predicate("state"), crosswalk=crosswalk, level_bridges={"charitable_amount": "return_count"}, ) - # Inside the tolerance (float noise) it is accepted. - nudged = [ - dataclasses.replace(spec, value=spec.value * (1 + 1e-9)) - if spec.name == "cdfile.1101.return_count" - else spec - for spec in specs - ] - _CD.state_cd_soi_surface( - nudged, - state_surface_predicate=_TOOL.soi_surface_predicate("state"), - crosswalk=crosswalk, - level_bridges={"charitable_amount": "return_count"}, - ) 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 fae1b8362f..17cc5f9636 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 @@ -450,7 +450,7 @@ def test_acs_household_children_sum_to_their_new_state_parent(layout) -> None: children = [ spec for spec in surface.specs - if spec.metadata.get("state_county_parent_target_name") == parent.name + if spec.metadata.get("cross_grain_parent") == parent.name ] assert {child.metadata["county_fips"] for child in children} == { code for code in values if code[:2] == state @@ -569,7 +569,7 @@ def test_acs_household_rows_partition_each_state_row(draws) -> None: children = [ child for child, other in enumerate(specs) - if other.metadata.get("state_county_parent_target_name") == spec.name + if other.metadata.get("cross_grain_parent") == spec.name ] parent = rows[[index]].toarray()[0] np.testing.assert_array_equal(rows[children].toarray().sum(axis=0), parent) @@ -609,15 +609,14 @@ def test_kalawao_shares_a_declared_soi_cell_with_maui() -> None: 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 + parents = {parent.name: parent.value for parent in _hawaii_parents()} 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"] + assert spec.metadata["cross_grain_members"] == "15005,15009" published = sum( population for code, population in _HAWAII.items() if code != 15005 ) - assert float(spec.metadata["state_county_share"]) == pytest.approx( - 160.0 / published - ) + parent_value = parents[spec.metadata["cross_grain_parent"]] + assert spec.value / parent_value == 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" @@ -625,6 +624,7 @@ def test_kalawao_shares_a_declared_soi_cell_with_maui() -> None: (merge,) = surface.receipt["combined_cells"] assert merge["members"] == ["15005", "15009"] assert merge["absent_from_soi"] == "15005" + assert "fewer than 20 returns" in merge["basis"] assert set(merge["concepts"]) == { "return_count|2022", "adjusted_gross_income|2022", @@ -634,11 +634,11 @@ def test_kalawao_shares_a_declared_soi_cell_with_maui() -> None: def test_an_undeclared_absent_county_is_still_refused() -> None: county = _county() - with pytest.raises(ValueError, match="missing=\\['15007'\\]"): + with pytest.raises(ValueError, match="missing \\['county:15007'\\]"): county.state_county_soi_surface( _hawaii_parents(), _hawaii_soi(without=(15005, 15007)), _HAWAII ) - with pytest.raises(ValueError, match="missing=\\['15005'\\]"): + with pytest.raises(ValueError, match="missing \\['county:15005'\\]"): county.state_county_soi_surface( _hawaii_parents(), _hawaii_soi(), _HAWAII, combined_cells={} ) @@ -672,7 +672,7 @@ def test_a_present_declared_county_keeps_its_own_soi_row() -> None: assert {spec.metadata["county_fips"] for spec in surface.specs} == set( _codes(_HAWAII) ) - assert "state_county_cell_members" not in surface.specs[0].metadata + assert "cross_grain_members" not in surface.specs[0].metadata @_SETTINGS @@ -694,7 +694,7 @@ def test_combined_cells_partition_the_parent_row_exactly(codes, values) -> None: rows = [ row for row, spec in enumerate(surface.specs) - if spec.metadata["state_county_parent_target_name"] == parent.name + if spec.metadata["cross_grain_parent"] == parent.name ] dense = children[rows].toarray() np.testing.assert_array_equal( @@ -716,7 +716,7 @@ def test_combined_cells_partition_the_parent_row_exactly(codes, values) -> None: assert math.fsum( spec.value for spec in surface.specs - if spec.metadata["state_county_parent_target_name"] == parents[0].name + if spec.metadata["cross_grain_parent"] == parents[0].name ) == pytest.approx(parents[0].value) @@ -732,7 +732,7 @@ def test_split_rows_refuse_overlapping_member_sets() -> None: **{field: getattr(spec, field) for field in spec.__dataclass_fields__}, "metadata": { **spec.metadata, - "state_county_cell_members": "15001,15005", + "cross_grain_members": "15001,15005", }, } ) @@ -1347,7 +1347,7 @@ def test_combined_soi_cell_errors_count_toward_both_member_counties() -> None: "name": "county_15009__returns", "geography_level": "county", "county_fips": "15009", - "state_county_cell_members": "15005,15009", + "cross_grain_members": "15005,15009", "value": 10.0, "role": "holdout", } diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_properties.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_properties.py index e96b27ae25..c558b10e78 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_properties.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_properties.py @@ -157,7 +157,7 @@ def test_county_soi_shares_sum_to_one_and_preserve_parent_household_measures( children = [ (index, spec) for index, spec in enumerate(surface.specs) - if spec.metadata["state_county_parent_target_name"] == parent_name + if spec.metadata["cross_grain_parent"] == parent_name ] assert len(children) == sum( code // 1000 == int(parent.metadata["state_fips"]) for code in populations @@ -228,7 +228,7 @@ def test_county_holdout_is_deterministic_order_independent_and_nested( "state_fips": f"{code // 1000:02d}", "county_fips": f"{code:05d}", "source_measure_id": measure, - "state_county_parent_target_name": f"state.{code // 1000}.{measure}", + "cross_grain_parent": f"state.{code // 1000}.{measure}", } for code in np.unique(codes) for measure in ("return_count", "adjusted_gross_income") @@ -253,9 +253,7 @@ def held(rows): # trained sibling counties from revealing the held-out county total. by_parent = {} for record in original: - by_parent.setdefault(record["state_county_parent_target_name"], set()).add( - record["role"] - ) + by_parent.setdefault(record["cross_grain_parent"], set()).add(record["role"]) assert all(len(values) == 1 for values in by_parent.values()) 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 c10e552da9..0c63f86ef8 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 @@ -333,15 +333,10 @@ def test_county_soi_reconciles_only_existing_broad_state_concepts() -> None: for spec in surface.specs: assert spec.metadata["ledger_geography_level"] == "county" assert spec.period == 2024 - by_parent.setdefault( - spec.metadata["state_county_parent_target_name"], [] - ).append(spec) + by_parent.setdefault(spec.metadata["cross_grain_parent"], []).append(spec) record = _county().target_record(spec) assert record["county_fips"] == spec.metadata["county_fips"] - assert ( - record["state_county_parent_target_name"] - == spec.metadata["state_county_parent_target_name"] - ) + assert record["cross_grain_parent"] == spec.metadata["cross_grain_parent"] assert set(by_parent) == {parent.name for parent in parents[:2]} assert [s.value for s in by_parent[parents[0].name]] == pytest.approx([25.0, 75.0]) assert [s.value for s in by_parent[parents[1].name]] == pytest.approx( @@ -396,7 +391,14 @@ def test_state_county_requires_both_concepts_and_parents_in_every_state( and omitted_state in (None, code[:2]) ) ] - with pytest.raises(ValueError, match=f"concept={measure}"): + # A state row with no parent is the adapter's refusal. County facts that + # are absent are the operator's: the leg does not hold its declared members. + message = ( + f"concept={measure}" + if omission == "state_parent" + else f"county_file\\|{measure}\\|.* does not hold the declared members" + ) + with pytest.raises(ValueError, match=message): _county().state_county_soi_surface( parents, facts, {1001: 50.0, 1003: 50.0, 6001: 100.0} ) @@ -451,7 +453,7 @@ def test_all_return_county_facts_do_not_become_sliced_state_targets( ) assert len(surface.specs) == 4 assert { - spec.metadata["state_county_parent_target_name"] + spec.metadata["cross_grain_parent"] for spec in surface.specs if spec.metadata["source_measure_id"] == "return_count" } == {parent.name} @@ -485,7 +487,7 @@ def test_county_soi_uses_exact_parent_household_values_including_signed_values() [ spec for spec in surface.specs - if spec.metadata["state_county_parent_target_name"] == parent.name + if spec.metadata["cross_grain_parent"] == parent.name ], households, county_column="county_fips_2023", @@ -521,7 +523,7 @@ def test_county_holdout_preserves_existing_roles_and_uses_a_population_baseline( "state_fips": "01", "county_fips": code, "source_measure_id": "adjusted_gross_income", - "state_county_parent_target_name": "state_agi", + "cross_grain_parent": "state_agi", "county_population": population, "state_population": 100.0, } @@ -1113,7 +1115,7 @@ def test_county_hooks_materialize_a_fixture_and_preserve_configured_geography( == 0 ) for record in records: - if record.get("state_county_parent_target_name"): + if record.get("cross_grain_parent"): record["role"] = "holdout" evidence = module.calibration_evidence( frame=loaded, @@ -1267,7 +1269,7 @@ def test_support_moves_reach_materialize_the_checkpoint_and_the_export( 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"): + if record.get("cross_grain_parent"): record["role"] = "holdout" weights = np.full(len(ids), 10.0) evidence = module.calibration_evidence( @@ -1393,7 +1395,7 @@ def test_county_loss_weights_share_a_state_concept_budget_without_changing_other indices = [ index for index, spec in enumerate(specs) - if spec.metadata.get("state_county_parent_target_name") == parent.name + if spec.metadata.get("cross_grain_parent") == parent.name ] assert len({mapping.concept_budget_key(specs[index]) for index in indices}) == 1 assert weights[indices[0]] / weights[indices[1]] == pytest.approx( @@ -1838,7 +1840,7 @@ def test_a_county_whose_households_all_have_zero_agi_refuses_or_drops_its_row( # Calibrate grades 01003 without its AGI row; the packaged report and its # CSV name the row in 01003's cell (review of #1660). for record in records: - if record.get("state_county_parent_target_name"): + if record.get("cross_grain_parent"): record["role"] = "holdout" evidence = run.module.calibration_evidence( frame=loaded, @@ -1956,7 +1958,7 @@ def test_dropping_empty_soi_rows_never_drops_a_county_without_households() -> No metadata={ "county_fips": code, "source_measure_id": "adjusted_gross_income", - "state_county_parent_target_name": "agi", + "cross_grain_parent": "agi", }, ) for code in ("01001", "01003") diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_no_county_regression.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_no_county_regression.py index a856627d2e..4f68fa01f0 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_no_county_regression.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_no_county_regression.py @@ -214,10 +214,14 @@ def _expected_admin_record(name, mode): record.update( { "value": value * 2, - "state_cd_parent_target_name": parent, - "state_cd_parent_basis": "historic_table_2", - "state_cd_rebase_factor": "2.0", - "state_cd_cd_file_value": repr(value), + "cross_grain_parent": parent, + # The bridge that the selector makes for this measure. + "cross_grain_control": ( + "historic_table_2_state_vs_district_file:" + f"lower_file|{measure}|-inf|inf|all|None" + ), + "cross_grain_factor": "2.0", + "cross_grain_value_before": repr(value), "cd_population": 40.0 if district == "0601" else 60.0, "state_population": 100.0, "holdout_unit": "06|return" 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 a299e07f0a..8f5745e638 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 @@ -424,7 +424,7 @@ def _parented_surface_specs(fixtures) -> tuple: spec, metadata={ **spec.metadata, - "state_cd_parent_target_name": parents[state].name, + "cross_grain_parent": parents[state].name, }, ) specs.append(spec) @@ -551,14 +551,8 @@ def test_a_state_cd_row_without_a_compiled_parent_is_refused() -> None: module = _load_tool_module() fixtures = _load_fixtures() - specs = [] - for spec in _parented_surface_specs(fixtures): - if spec.name == "cd_0601_agi": - spec = dataclasses.replace( - spec, - metadata={**spec.metadata, "state_cd_vintage_rule": "fixture"}, - ) - specs.append(spec) + # Each district row of the fixture names its parent (``cross_grain_parent``). + specs = list(_parented_surface_specs(fixtures)) plan = module.cd_surface.plan_carriers(specs) compiled = {spec.name for spec in plan.engine_specs} parents, _unchecked = module.cd_surface.district_row_parents(plan, compiled) @@ -611,7 +605,7 @@ def test_calibration_never_sees_a_held_out_target(monkeypatch, tmp_path) -> None if record.get("geography_level") is None and record["family"] == "irs_soi": if record.get("congressional_district_geoid"): record["geography_level"] = "congressional_district" - record["state_cd_parent_target_name"] = "agi_amount" + record["cross_grain_parent"] = "agi_amount" module.cd_surface.assign_target_roles(records, fraction=0.5) held = {record["name"] for record in records if record["role"] == "holdout"} assert held, "the fixture must hold something out at 0.5" @@ -742,7 +736,7 @@ def test_holdout_scoring_against_the_pro_rata_baseline() -> None: "state_fips": "06", "congressional_district_geoid": d, "source_measure_id": "adjusted_gross_income", - "state_cd_parent_target_name": "state_agi", + "cross_grain_parent": "state_agi", "cd_population": population, "state_population": 100.0, } @@ -955,35 +949,38 @@ def test_pinned_feed_state_cd_surface_matches_its_contract() -> None: if module.cd_surface.is_cd_file_spec(spec) and spec.metadata["source_measure_id"] in defective ] - assert all(spec.metadata.get("state_cd_parent_target_name") for spec in districts) + assert all(spec.metadata.get("cross_grain_parent") for spec in districts) assert receipt["sigma"]["targets_with_sigma"] == 0 - # The factor band drops these (state, measure) pairs, and only these: - # four district blocks whose two publications disagree about the state, - # and the itemized bridge of two at-large states (no district rows). - # The district file agrees with itself in every block, to float precision. - internal = receipt["internal_consistency"] - assert internal["blocks_checked"] == 2193 - assert internal["max_relative_gap"] < 1e-12 - band = receipt["factor_band"] - assert band["tolerance"] == module.cd_surface.STATE_CD_FACTOR_BAND == 1.25 + # The bridge's bound is measured from each concept's median factor. It + # unbinds these four district blocks, and only these: the two publications + # disagree about the state. + bridge = receipt["bridge"] + assert bridge["bridge_id"] == "historic_table_2_state_vs_district_file" + assert bridge["max_factor_shift"] == 0.25 + assert bridge["min_factor_shift"] == -0.2 + assert (bridge["shift_around"], bridge["out_of_bound"]) == ("median", "unbind") + assert module.cd_surface.STATE_CD_FACTOR_BAND == 1.25 + assert {(row["state_fips"], row["concept"]) for row in bridge["unbound"]} == { + ("15", "ordinary_dividends_amount"), + ("15", "qualified_dividends_amount"), + ("36", "rental_royalty_income_amount"), + ("49", "tax_exempt_interest_amount"), + } + # The itemized level bridge of two at-large states is distrusted (they + # have no district rows). assert { - (row["state_fips"], row["measure"], row["basis"].split(":")[0]) - for row in band["out_of_band"] + (row["state_fips"], row["measure"]) + for row in receipt["level_bridge_out_of_band"] } == { - ("15", "ordinary_dividends_amount", "rebase"), - ("15", "qualified_dividends_amount", "rebase"), - ("36", "rental_royalty_income_amount", "rebase"), - ("49", "tax_exempt_interest_amount", "rebase"), - ("46", "charitable_amount", "level_bridge"), - ("46", "interest_paid_deduction_amount", "level_bridge"), - ("56", "charitable_amount", "level_bridge"), - ("56", "interest_paid_deduction_amount", "level_bridge"), + ("46", "charitable_amount"), + ("46", "interest_paid_deduction_amount"), + ("56", "charitable_amount"), + ("56", "interest_paid_deduction_amount"), } # 43 states carry district rows (51 minus the 8 at-large on the 117th - # plan), less the band's four blocks. + # plan), less the bridge's four unbound blocks. rebase_n = { - measure: entry["n"] - for measure, entry in receipt["rebase_factor_by_measure"].items() + measure: entry["n"] for measure, entry in receipt["factor_by_measure"].items() } banded = { "ordinary_dividends_amount", diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_surface_bytes.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_surface_bytes.py index 79576aac9a..5efbe4777a 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_surface_bytes.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_surface_bytes.py @@ -17,7 +17,16 @@ gives the population rows a small household table that supports every ladder cell, and pins the rows' matrix on that table too. -The pins were measured at ``3316038cc``, before any code moved. They run only +The pins were measured at ``3316038cc``, before any code moved. Three pins of +``state_cd`` (the registry, the roles and the receipts) were measured again +for microcosm#1760, when the district rows took the metadata keys of the +shared cross-grain operator (``cross_grain_*`` in place of ``state_cd_*``) and +the receipt took its fields. No target value moved: +``test_us_target_nesting_district.py`` holds each row of that surface, on the +same feed, to the bits of its old value. The other modes hold no row that the +operator makes, and their pins are the first ones. + +The pins run only when ``MICROCOSM_US_CHRONICLE_FACTS`` names the pinned feed and ``MICROCOSM_US_PUMA_LADDER_ARTIFACT`` names the pinned PUMA ladder. The county mode (``state_county``) needs the pinned county facts and a household @@ -89,13 +98,13 @@ "state_cd": { "targets": 26_912, "target_registry_sha256": ( - "fad3ddf61915407fe187d9c739bd379d17c804347dc446e85f3e0303e8518bf3" + "596ae9ab155a6f5e99c615fbe33d5567d0194c7f28acc9e4dfeb973cc02510f7" ), "target_roles_sha256": ( - "ffa9c4c964ea84385f0bfe5ef3c1053937897bfcecff941315d0a61f0ab0cca4" + "14bbdc62e2c1dd6bf8bc11938db013928cd1587aa99f2f76f1c087ea78fc3b72" ), "receipts_sha256": ( - "9c67654cd7c8ab53b68969bf7ea30134871a1407af37d87ae3b2067294efed7f" + "f4e925d799e68d889d1cd54ba3f28aeeb403834f67eec6b89befcd1c60a3e5bb" ), "population_matrix_sha256": ( "ae7785b655538f802e9ef7203c3ae6160ad250ed9e22c06c39475ae4614994f4" diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_target_loss_weights.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_target_loss_weights.py index 4a04827ae5..9e136541c2 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_target_loss_weights.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_target_loss_weights.py @@ -123,10 +123,10 @@ def _district(name, value, unit, district, parent) -> TargetSpec: ledger_geography_id=f"5001900US{district}", ledger_layout_groupby_value_label=f"congressional district {district}", ledger_fact_label=f"Congressional District {district} {name}", - state_cd_parent_target_name=parent, - state_cd_parent_basis="historic_table_2", - state_cd_cd_file_value=repr(value * 0.97), - state_cd_rebase_factor="1.03", + cross_grain_parent=parent, + cross_grain_control="historic_table_2_state_vs_district_file", + cross_grain_value_before=repr(value * 0.97), + cross_grain_factor="1.03", ) return TargetSpec( **{ diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_cross_grain_coverage.py b/packages/microcosm-build/tests/engine_free/us/test_us_cross_grain_coverage.py index 9bcc2bd74b..7c342f8bf6 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_cross_grain_coverage.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_cross_grain_coverage.py @@ -1,15 +1,16 @@ -"""The US nesting inventory covers every family that two levels measure. - -``us/cross_grain_declarations.json`` lists, under ``inventory``, each US -family that two geography levels measure, with the route that ties the levels -today or the reason none does (microcosm#1760). It records what the code -does; it decides no rule. These tests read it: - -- each entry is well formed, the eight rows of the issue each have one entry, - and each mechanism on the shared operator has one; -- ``us_cross_grain_coverage_violations`` finds a family at a lower level with - no entry, an entry whose rows are gone, and a compile rule whose marker is - on no row; +"""The US nesting declarations cover every family that two levels measure. + +``us/cross_grain_declarations.json`` says, for each US family that two +geography levels measure, what ties the levels (microcosm#1760): a bridge +selector, a derived control, a same-measurement entry, a relation that is not +reconciled, a local route with no higher control, a compile rule that stays +until the feed re-pin, or a known gap. These tests read it: + +- the eight rows of the issue each have one entry, and each compile rule + names code that exists; +- ``us_cross_grain_coverage_violations`` finds a family at a lower level that + nothing covers, a declaration whose rows are gone, a compile rule whose + marker is on no row, and a subset that is larger than its whole; - on the pinned feed, the compiled registry has no violation. That test runs only when ``MICROCOSM_US_CHRONICLE_FACTS`` names the pinned feed, because ``main`` has no committed list of the US families and levels. @@ -20,7 +21,6 @@ from __future__ import annotations -import copy import importlib.util import os import re @@ -35,106 +35,84 @@ _TEST_PATHS = paths_for("microcosm-build") -def _entries(): - return declarations.us_cross_grain_inventory() +def _declared(): + return declarations.load_us_cross_grain_declarations() + + +def _transitional_entries() -> list: + transitional = _declared()["until_the_feed_repin"] + return [*transitional["compile_rules"], *transitional["known_gaps"]] def test_each_row_of_the_issue_has_one_entry() -> None: - rows = [entry["issue_row"] for entry in _entries() if "issue_row" in entry] - assert sorted(rows) == [1, 2, 3, 4, 5, 6, 7, 8] - routes = { - entry["issue_row"]: entry["route"] - for entry in _entries() - if "issue_row" in entry + declared = _declared() + passes = { + entry["issue_row"]: section + for section in ("bridge_selectors", "derived_controls", "same_measurement") + for entry in declared[section] + } + compile_rules = { + rule["issue_row"]: "compile_rules" + for rule in declared["until_the_feed_repin"]["compile_rules"] } - # Rows 1 to 4 stay in the compile; rows 5 to 8 run on the shared operator. - assert routes == { - **dict.fromkeys((1, 2, 3, 4), "compile_rule"), - **dict.fromkeys((5, 6, 7, 8), "mechanism"), + assert not set(passes) & set(compile_rules) + # Rows 1 to 4 stay in the compile until the feed re-pin. Rows 5 to 8 run + # on the shared operator. + assert {**passes, **compile_rules} == { + **dict.fromkeys((1, 2, 3, 4), "compile_rules"), + 5: "bridge_selectors", + 6: "bridge_selectors", + 7: "derived_controls", + 8: "same_measurement", } -def test_each_mechanism_has_one_entry_that_matches_it() -> None: - mechanisms = declarations.load_us_cross_grain_declarations()["mechanisms"] - named = [ - entry["mechanism"] for entry in _entries() if entry["route"] == "mechanism" - ] - assert sorted(named) == sorted(mechanisms) - for entry in _entries(): - if entry["route"] != "mechanism": - continue - mechanism = mechanisms[entry["mechanism"]] - assert entry["issue_row"] == mechanism["issue_row"] - assert entry["family"] == mechanism["family"] - assert entry["levels"] == [mechanism["lower_grain"]] - assert entry["higher_level"] == mechanism["higher_grain"] - - -def test_each_entry_gives_a_route_and_what_the_route_needs() -> None: - declared = declarations.load_us_cross_grain_declarations() - routes = declared["inventory"]["routes"] - ids = [entry["id"] for entry in _entries()] +def test_each_entry_gives_a_reason_and_a_compile_rule_names_its_code() -> None: + declared = _declared() + ids = [entry["id"] for entry in _transitional_entries()] assert len(ids) == len(set(ids)) - for entry in _entries(): - assert entry["route"] in routes - assert entry["issues"] and all( - re.fullmatch(r"microcosm#\d+", issue) for issue in entry["issues"] + for entry in _transitional_entries(): + assert len(entry["reason"]) > 40 + assert all(re.fullmatch(r"microcosm#\d+", issue) for issue in entry["issues"]) + for rule in declared["until_the_feed_repin"]["compile_rules"]: + module, _, function = rule["code"].split(",")[0].strip().rpartition(".") + source = (_TEST_PATHS.package / "src" / Path(*module.split("."))).with_suffix( + ".py" ) - if entry["route"] != "mechanism": - # A route with no mechanism says why in words. + assert f"def {function}(" in source.read_text() + assert rule["marker"]["metadata_key"] + for section in ("bridge_selectors", "derived_controls", "same_measurement"): + for entry in declared[section]: assert len(entry["reason"]) > 40 - if entry["route"] == "compile_rule": - module, _, function = entry["code"].split(",")[0].strip().rpartition(".") - source = ( - _TEST_PATHS.package / "src" / Path(*module.split(".")) - ).with_suffix(".py") - assert f"def {function}(" in source.read_text() - assert entry["marker"]["metadata_key"] - assert entry["compiled"] is True - # Every route the file lists is in use, so none is a dead name. - assert {entry["route"] for entry in _entries()} == set(routes) - - -def _tampered(change) -> dict: - payload = copy.deepcopy(dict(declarations.load_us_cross_grain_declarations())) - change(payload["inventory"]["entries"]) - return payload - - -@pytest.mark.parametrize( - ("change", "message"), - [ - (lambda entries: entries[0].update(route="merged"), "unknown route"), - (lambda entries: entries[0].update(reason=" "), "no reason"), - (lambda entries: entries[0].pop("marker"), "the marker it writes"), - (lambda entries: entries[4].update(family="usda_snap"), "does not match"), - (lambda entries: entries[1].update(id=entries[0]["id"]), "blank or repeated"), - (lambda entries: entries[0].update(levels=["tract"]), "must name a family"), - ( - lambda entries: entries[0].update(higher_level="county"), - "must name a family", - ), - (lambda entries: entries[0].update(issues=[]), "name an issue"), - ], -) -def test_a_malformed_entry_is_refused_when_the_file_loads(change, message) -> None: - with pytest.raises(ValueError, match=message): - declarations._validate_inventory(_tampered(change)) - - -def _spec(family: str, level: str, **metadata): + for entry in (*declared["relations"], *declared["local_routes"].values()): + assert len(entry["reason"]) > 40 + + +def _spec(family: str, level: str | None, value: float = 1.0, **metadata): + level_metadata = {} if level is None else {"ledger_geography_level": level} return SimpleNamespace( - family=family, metadata={"ledger_geography_level": level, **metadata} + family=family, value=value, metadata={**level_metadata, **metadata} ) def _covered_specs() -> list: - """One spec for each compiled entry and level, with the rule's marker.""" + """Rows for each declared relation, local route, compile rule and gap.""" + declared = _declared() + grains = tuple(declared["grain_precedence"]) specs = [_spec("irs_soi", "country"), _spec("bea", "country")] - for entry in _entries(): - if not entry["compiled"]: - continue + for relation in declared["relations"]: + for target in relation["targets"]: + family, role, level = declarations._relation_target(target, grains) + if target == relation["part"]: + # Two parts that sum to nine tenths of their whole. + specs.append(_spec(family, level, 40.0, target_role=role)) + specs.append(_spec(family, level, 50.0, target_role=role)) + else: + specs.append(_spec(family, level, 100.0, target_role=role)) + for target in declared["local_routes"]: + specs.append(_spec(*declarations._route_target(target, grains))) + for entry in _transitional_entries(): marker = entry.get("marker") or {} metadata = ( { @@ -155,7 +133,7 @@ def test_the_coverage_check_finds_each_kind_of_gap() -> None: covered = _covered_specs() assert declarations.us_cross_grain_coverage_violations(covered) == [] - # A family at a lower level with no entry. + # A family at a lower level that nothing covers. unrouted = [*covered, _spec("usda_wic", "state")] assert declarations.us_cross_grain_coverage_violations(unrouted) == [ { @@ -165,14 +143,25 @@ def test_the_coverage_check_finds_each_kind_of_gap() -> None: "where": "compiled specs", } ] - # An entry whose compiled rows are gone. + # A relation whose rows are gone, at both of its levels. without_tanf = [spec for spec in covered if spec.family != "hhs_acf_tanf"] assert declarations.us_cross_grain_coverage_violations(without_tanf) == [ { - "kind": "stale_inventory_entry", + "kind": "stale_declaration", "family": "hhs_acf_tanf", + "level": level, + "where": f"hhs_acf_tanf.tanf_total@{level}", + } + for level in ("state", "country") + ] + # A local route whose rows are gone. + without_ssa = [spec for spec in covered if spec.family != "ssa"] + assert declarations.us_cross_grain_coverage_violations(without_ssa) == [ + { + "kind": "stale_declaration", + "family": "ssa", "level": "state", - "where": "hhs_acf_tanf_state_rows_and_national_row", + "where": "ssa@state", } ] # A compile rule that marks no row of its declared level. @@ -186,23 +175,45 @@ def test_the_coverage_check_finds_each_kind_of_gap() -> None: } ] # Rows at the top level, and rows with no level, nest in nothing. - top_only = [ - *covered, - _spec("jct", "country"), - SimpleNamespace(family="x", metadata={}), - ] + top_only = [*covered, _spec("jct", "country"), _spec("x", None)] assert declarations.us_cross_grain_coverage_violations(top_only) == [] +def test_a_subset_larger_than_its_whole_is_a_violation() -> None: + covered = _covered_specs() + + def with_part(family: str, role: str, value: float) -> list: + return [*covered, _spec(family, "state", value, target_role=role)] + + # SNAP declares no excess: 110 of 100 is beyond it. + assert declarations.us_cross_grain_coverage_violations( + with_part("usda_snap", "snap_total", 20.0) + ) == [ + { + "kind": "subset_exceeded", + "family": "usda_snap", + "level": "state", + "where": "usda_snap.snap_total@state is 1.1 of its whole", + } + ] + # Medicaid declares an excess of one percent. + within = with_part("cms_medicaid", "medicaid_enrollment", 10.5) + assert declarations.us_cross_grain_coverage_violations(within) == [] + beyond = with_part("cms_medicaid", "medicaid_enrollment", 11.5) + (violation,) = declarations.us_cross_grain_coverage_violations(beyond) + assert violation["kind"] == "subset_exceeded" + assert violation["where"].startswith("cms_medicaid.medicaid_enrollment@state is ") + + def test_the_coverage_check_is_a_receipt_and_refuses_nothing() -> None: - receipt = declarations.us_cross_grain_coverage_receipt( - [*_covered_specs(), _spec("usda_wic", "state")] - ) + specs = [*_covered_specs(), _spec("usda_wic", "state")] + receipt = declarations.us_cross_grain_coverage_receipt(specs) assert receipt["covered"] is False assert [violation["kind"] for violation in receipt["violations"]] == [ "family_level_without_route" ] - assert receipt["inventory_entries"] == len(_entries()) + assert receipt["checked_specs"] == len(specs) + assert receipt["declarations"] == "cross_grain_declarations.json" assert declarations.us_cross_grain_coverage_receipt(_covered_specs())["covered"] @@ -236,20 +247,22 @@ def test_the_pinned_feeds_compiled_registry_is_covered() -> None: spec.loader.exec_module(tool) registry, _substitutions = tool._compiled_fiscal_registry(feed) + # No violation: each family that the registry holds below the national + # level is covered, no declaration names rows that are gone, each compile + # rule's marker is on its rows, and no subset is larger than its whole. receipt = declarations.us_cross_grain_coverage_receipt(registry.specs) assert receipt["violations"] == [] assert receipt["checked_specs"] == len(registry.specs) - # The families the registry holds below the national level are the ones - # the inventory's compiled entries name: no more and no fewer. - compiled = { - (spec.family, spec.metadata["ledger_geography_level"]) - for spec in registry.specs - if spec.metadata.get("ledger_geography_level") not in (None, "country") - } - declared = { - (entry["family"], level) - for entry in _entries() - if entry["compiled"] - for level in entry["levels"] - } - assert compiled == declared + # The relations read real rows: each side holds at least one. + declared = _declared() + grains = tuple(declared["grain_precedence"]) + for relation in declared["relations"]: + for target in relation["targets"]: + family, role, level = declarations._relation_target(target, grains) + assert [ + row + for row in registry.specs + if row.family == family + and row.metadata.get("ledger_geography_level") == level + and row.metadata.get("target_role") == role + ], target diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_cross_grain_declarations.py b/packages/microcosm-build/tests/engine_free/us/test_us_cross_grain_declarations.py index cc54f2d8ac..710edb198f 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_cross_grain_declarations.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_cross_grain_declarations.py @@ -1,16 +1,21 @@ """The US nesting declarations and the adapter's path to the operator. ``us/cross_grain_declarations.json`` holds the US choices of the shared -cross-grain operator (microcosm#1760). The registers in it were Python -literals in the local tools; the tools read them from the declaration under -their old names. These tests hold each one to the literal it replaces -(``test_support/microcosm_build/us_target_nesting_reference.py`` is the tool -code before the move), and check the declaration's shape and the adapter's -block interface. +cross-grain operator (microcosm#1760), under the key names of the UK's file. +These tests check: + +- the registers that were Python literals in the local tools: the tools read + them from the declaration under their old names, and each one is the + literal it replaces (``test_support/microcosm_build/ + us_target_nesting_reference.py`` is the tool code before the move); +- the declaration's shape, and that a malformed one is refused when it loads; +- the typed views of it; +- one pass on the operator, and the record of the operator's receipts. """ from __future__ import annotations +import copy import importlib import json import sys @@ -18,10 +23,13 @@ import pytest -from microcosm.build import cross_grain_controls +from microcosm.build import cross_grain_controls as controls +from microcosm.build.cross_grain import ( + EXACT_SIGNATURE_CONTROL, + CrossGrainBridgeSelector, +) from microcosm.build.us_runtime import cross_grain_declarations as declarations from microcosm.build.us_runtime import target_nesting -from microcosm.build.us_runtime.target_nesting import NestingBlock from test_support.microcosm_build import us_target_nesting_reference as reference from test_support.paths import paths_for @@ -34,7 +42,6 @@ "STATE_CD_LEVEL_BRIDGES", "STATE_CD_EXCLUDED_CD_STATES", "STATE_CD_FACTOR_BAND", - "STATE_CD_INTERNAL_RTOL", "RECONCILIATION_RTOL", ) COUNTY_REGISTERS = ( @@ -42,6 +49,12 @@ "DECLARED_SOI_COMBINED_CELLS", "SOI_COMBINED_CELL_BASIS", ) +PASSES = ( + declarations.DISTRICT_SOI, + declarations.COUNTY_SOI, + declarations.COUNTY_ACS_HOUSEHOLDS, + declarations.COUNTY_POPULATION, +) def _load_tool(name: str): @@ -91,6 +104,9 @@ def test_the_tools_hold_copies_not_the_cached_declaration(district_tool) -> None assert district_tool.STATE_CD_LEVEL_BRIDGES is not declared.level_bridges +# --- The shape of the declaration -------------------------------------------- + + def test_the_declaration_names_the_operators_keys_as_the_uk_file_does() -> None: declared = declarations.load_us_cross_grain_declarations() uk = json.loads( @@ -98,9 +114,15 @@ def test_the_declaration_names_the_operators_keys_as_the_uk_file_does() -> None: .joinpath("cross_grain_declarations.json") .read_text(encoding="utf-8") ) - # Every US key but the US-only sections is a key of the UK file. - us_only = {"mechanisms", "inventory"} - assert set(declared) - us_only <= set(uk) + # A key of the US file is a key of the UK file, or one of the general + # constructs that the UK does not use yet, or the section that goes at + # the feed re-pin. + general = {"bridge_selectors", "derived_controls", "same_measurement"} + assert set(declared) - set(uk) == general | { + "members", + "registers", + "until_the_feed_repin", + } assert declared["schema_version"] == uk["schema_version"] == 1 # The US levels are the feed's own geography levels, widest first. assert declared["grain_precedence"] == [ @@ -110,162 +132,296 @@ def test_the_declaration_names_the_operators_keys_as_the_uk_file_does() -> None: "county", ] assert declared["control_grains"] == ["country", "state"] - # No UK-style bridge or partition is in force: each mechanism ties a - # control to its rows by an exact measurement signature. + assert set(declared["signature_fields"]) <= set(uk["signature_fields"]) + # No bridge by id and no partition: a selector makes the US bridges. assert declared["bridges"] == [] and declared["partitions"] == [] + # A relation and a local route read as the UK's do. + relation_keys = {key for relation in uk["relations"] for key in relation} + relation_kinds = {relation["relation"] for relation in uk["relations"]} + for relation in declared["relations"]: + assert set(relation) <= relation_keys + assert relation["relation"] in relation_kinds + for route in declared["local_routes"].values(): + assert route["route"] in { + entry["route"] for entry in uk["local_routes"].values() + } + + +def test_each_pass_is_declared_once_with_its_issue_row() -> None: + declared = declarations.load_us_cross_grain_declarations() + rows = { + entry.get("bridge_id", entry.get("id")): entry["issue_row"] + for section in ("bridge_selectors", "derived_controls", "same_measurement") + for entry in declared[section] + } + assert rows == { + declarations.DISTRICT_SOI: 5, + declarations.COUNTY_SOI: 6, + declarations.COUNTY_ACS_HOUSEHOLDS: 7, + declarations.COUNTY_POPULATION: 8, + } + # Districts and counties both divide a state. + assert {pass_id: declarations.us_pass_grains(pass_id) for pass_id in PASSES} == { + declarations.DISTRICT_SOI: ("state", "congressional_district"), + declarations.COUNTY_SOI: ("state", "county"), + declarations.COUNTY_ACS_HOUSEHOLDS: ("state", "county"), + declarations.COUNTY_POPULATION: ("state", "county"), + } + with pytest.raises(ValueError, match="Unknown US cross-grain pass"): + declarations.us_pass_grains("state_tract_soi") -def test_each_mechanism_declares_its_rule() -> None: +def test_the_allocators_are_declared_to_go_at_the_feed_repin() -> None: declared = declarations.load_us_cross_grain_declarations() - mechanisms = declared["mechanisms"] - assert list(mechanisms) == [ - declarations.DISTRICT_SOI, - declarations.COUNTY_POPULATION, - declarations.COUNTY_SOI, - declarations.COUNTY_ACS_HOUSEHOLDS, - ] - assert { - mechanism_id: ( - mechanism["issue_row"], - mechanism["allocator"], - mechanism["control"]["kind"], - ) - for mechanism_id, mechanism in mechanisms.items() - } == { - declarations.DISTRICT_SOI: ( - 5, - "proportional_fsum", - "bound_row_or_scaled_by_sibling_ratio", - ), - declarations.COUNTY_POPULATION: (8, "scale_residual_to_largest", "bound_row"), - declarations.COUNTY_SOI: (6, "share_residual_to_largest", "bound_row"), - declarations.COUNTY_ACS_HOUSEHOLDS: ( - 7, - "share_residual_to_largest", - "sum_of_lower_rows", - ), + assert "allocator" not in json.dumps( + {key: value for key, value in declared.items() if key != "until_the_feed_repin"} + ) + assert {pass_id: declarations.us_allocator_name(pass_id) for pass_id in PASSES} == { + declarations.DISTRICT_SOI: "proportional_fsum", + declarations.COUNTY_SOI: "share_residual_to_largest", + declarations.COUNTY_ACS_HOUSEHOLDS: "share_residual_to_largest", + declarations.COUNTY_POPULATION: "scale_residual_to_largest", } - for mechanism in mechanisms.values(): - assert mechanism["allocator"] in cross_grain_controls.ALLOCATORS - assert mechanism["higher_grain"] in declared["control_grains"] - assert mechanism["members"]["source"] - assert mechanism["control"]["description"] - assert "lower_rows" in mechanism["metadata_keys"] - assert ( - _TEST_PATHS.repository / mechanism["tool_function"].split(":")[0] - ).exists() - - -def test_an_unknown_mechanism_is_refused() -> None: - with pytest.raises(ValueError, match="Unknown US cross-grain mechanism"): - declarations.us_cross_grain_mechanism("state_tract_soi") - - -def _block(state: str, values: tuple[float, ...], control: float, concept="quantity"): - return NestingBlock( - concept=concept, - filters=(("band", "all"),), - control_geography_id=target_nesting.geography_id("state", state), - control_value=control, - lower_geography_ids=tuple( - target_nesting.geography_id("county", f"{state}{index:03d}") - for index in range(1, len(values) + 1) - ), - lower_values=values, + assert set(declared["until_the_feed_repin"]["allocators"].values()) <= set( + controls.ALLOCATORS ) + assert declarations.us_allocator_name("another_pass") is None + + +def test_a_selector_is_the_operators_selector() -> None: + district = declarations.us_bridge_selector(declarations.DISTRICT_SOI) + assert district == CrossGrainBridgeSelector( + bridge_id=declarations.DISTRICT_SOI, + concept="irs_soi", + higher={"source": "state_surface", "grain": "state"}, + lower={"source": "lower_file", "grain": "congressional_district"}, + pair_on=("identity",), + max_factor_shift=0.25, + min_factor_shift=-0.2, + shift_around="median", + out_of_bound="unbind", + ) + # A caller can turn the bound off. The pairing stays. + unbounded = declarations.us_bridge_selector( + declarations.DISTRICT_SOI, bounded=False + ) + assert unbounded.max_factor_shift is None and unbounded.out_of_bound == "refuse" + assert (unbounded.higher, unbounded.lower) == (district.higher, district.lower) + county = declarations.us_bridge_selector(declarations.COUNTY_SOI) + assert county.pair_on == ("source_measure_id", "source_period") + assert county.max_factor_shift is None + with pytest.raises(ValueError, match="Unknown US cross-grain bridge selector"): + declarations.us_bridge_selector(declarations.COUNTY_POPULATION) -def test_blocks_go_through_the_operator_with_the_declared_allocator() -> None: - blocks = [ - _block("06", (30.0, 20.0), 100.0), - _block("36", (1.0, 3.0), 8.0), - _block("06", (5.0, 5.0), 40.0, concept="other_quantity"), - ] - nested, receipt = target_nesting.reconcile_blocks( - declarations.COUNTY_POPULATION, blocks +def test_the_typed_views_read_the_declaration() -> None: + declared = declarations.load_us_cross_grain_declarations() + district = declarations.us_district_soi_nesting() + assert district.factor_band == 1.25 + assert (district.max_factor_shift, district.min_factor_shift) == (0.25, -0.2) + # The two-sided bound is the old band: 1 / 1.25 is 1 - 0.2 in floats too. + assert 1.0 + district.min_factor_shift == 1.0 / district.factor_band + assert district.level_bridges == dict( + declared["until_the_feed_repin"]["level_bridges"]["siblings"] ) + county = declarations.us_county_soi_nesting() + assert county.required_measures == ("return_count", "adjusted_gross_income") + assert county.combined_cells == {15005: 15009} + assert "fewer than 20 returns" in county.combined_cell_basis + + +def _tampered(change) -> dict: + payload = copy.deepcopy(dict(declarations.load_us_cross_grain_declarations())) + change(payload) + return payload + + +@pytest.mark.parametrize( + ("change", "message"), + [ + (lambda d: d.update(control_grains=["country", "tract"]), "control_grains"), + ( + lambda d: d["bridge_selectors"][0]["lower"].update(grain="state"), + "a control grain above its lower grain", + ), + ( + lambda d: d["bridge_selectors"][0].update(pair_on=[]), + "what its sides are paired on", + ), + ( + lambda d: d["bridge_selectors"][1].update(reason=" "), + "what its sides are paired on", + ), + ( + lambda d: d["derived_controls"][0].update(derive="mean_of_lower_rows"), + "unknown derivation", + ), + ( + lambda d: d["same_measurement"][0].update(higher_grain="county"), + "a control grain above its lower grain", + ), + ( + lambda d: d["same_measurement"][0].update( + id=d["derived_controls"][0]["bridge_id"] + ), + "pass ids repeat", + ), + ( + lambda d: d["until_the_feed_repin"]["allocators"].update( + {declarations.COUNTY_SOI: "numpy_sum"} + ), + "must name a declared pass and one of", + ), + ( + lambda d: d["until_the_feed_repin"]["allocators"].update( + {"another_pass": "proportional_fsum"} + ), + "must name a declared pass and one of", + ), + (lambda d: d["relations"][0].update(relation="equal"), "is malformed"), + (lambda d: d["relations"][0].update(reason=""), "is malformed"), + ( + lambda d: d["relations"][0].update(whole="usda_snap.snap_total@state"), + "is malformed", + ), + ( + lambda d: d["relations"][0].update( + targets=["usda_snap.snap_total@tract", "usda_snap.snap_total@country"], + part="usda_snap.snap_total@tract", + ), + "family.role@level", + ), + ( + lambda d: d["local_routes"].update( + {"ssa@tract": d["local_routes"]["ssa@state"]} + ), + "family@level", + ), + ( + lambda d: d["local_routes"]["ssa@state"].update(route="merged"), + "with a reason", + ), + ( + lambda d: d["until_the_feed_repin"]["compile_rules"][0].update(issues=[]), + "a reason and an issue", + ), + ( + lambda d: d["until_the_feed_repin"]["known_gaps"][0].update( + levels=["tract"] + ), + "a reason and an issue", + ), + ( + lambda d: d["until_the_feed_repin"]["compile_rules"][0].pop("marker"), + "the marker it writes", + ), + ], +) +def test_a_malformed_declaration_is_refused_when_the_file_loads( + change, message +) -> None: + with pytest.raises(ValueError, match=message): + declarations._validate(_tampered(change)) + declarations._validate(_tampered(lambda payload: None)) + + +# --- One pass on the operator ------------------------------------------------ + - assert [rows.values for rows in nested] == [(60.0, 40.0), (2.0, 6.0), (20.0, 20.0)] - assert [(rows.factor, rows.lower_sum) for rows in nested] == [ - (2.0, 50.0), - (2.0, 4.0), - (4.0, 10.0), +def _population_rows(*states: tuple[str, float, tuple[float, ...]]): + """A state control row and its county rows, for each state.""" + + rows, legs = [], {} + for state, control, values in states: + area = target_nesting.geography_id("state", state) + rows.append(controls.SurfaceRow("state", area, "population", control)) + for index, value in enumerate(values, start=1): + county = target_nesting.geography_id("county", f"{state}{index:03d}") + legs[county] = area + rows.append(controls.SurfaceRow("county", county, "population", value)) + return rows, legs + + +def test_a_pass_runs_on_the_operator_with_its_declared_allocator() -> None: + rows, legs = _population_rows(("06", 100.0, (30.0, 20.0)), ("36", 8.0, (1.0, 3.0))) + outcomes, receipt = target_nesting.run_pass( + declarations.COUNTY_POPULATION, + rows, + bound_higher_targets=["population"], + legs=legs, + ) + assert [outcome.value for outcome in outcomes] == [ + 100.0, + 60.0, + 40.0, + 8.0, + 2.0, + 6.0, ] - # One group for each quantity, one leg for each state, and the operator's - # receipt names the allocator the mechanism declares. - assert len(receipt["groups"]) == 2 - legs = [leg for group in receipt["groups"] for leg in group["legs"]] - assert sorted(leg["parent_geography_id"] for leg in legs) == [ - "state:06", + assert [(outcome.status, outcome.parent) for outcome in outcomes] == [ + (controls.UNTOUCHED, None), + (controls.RECONCILED, 0), + (controls.RECONCILED, 0), + (controls.UNTOUCHED, None), + (controls.RECONCILED, 3), + (controls.RECONCILED, 3), + ] + assert {outcome.control for outcome in outcomes[1:3]} == {EXACT_SIGNATURE_CONTROL} + # One group for the quantity, one leg for each state, and the operator's + # receipt names the allocator that the declaration gives the pass. + (group,) = receipt["groups"] + assert (group["winning_grain"], group["lower_grain"]) == ("state", "county") + assert sorted(leg["parent_geography_id"] for leg in group["legs"]) == [ "state:06", "state:36", ] - assert {leg["allocator"] for leg in legs} == {"scale_residual_to_largest"} - assert {group["winning_grain"] for group in receipt["groups"]} == {"state"} - assert {group["lower_grain"] for group in receipt["groups"]} == {"county"} - - -def test_a_block_the_operator_cannot_place_is_refused() -> None: - mechanism = declarations.COUNTY_POPULATION - with pytest.raises(ValueError, match="two blocks"): - target_nesting.reconcile_blocks( - mechanism, [_block("06", (1.0,), 2.0), _block("06", (1.0,), 2.0)] - ) - stray = NestingBlock( - "quantity", - (), - target_nesting.geography_id("state", "36"), - 2.0, - (target_nesting.geography_id("county", "06001"),), - (1.0,), - ) - with pytest.raises(ValueError, match="sits under two controls"): - target_nesting.reconcile_blocks( - mechanism, - [ - NestingBlock( - "other", - (), - target_nesting.geography_id("state", "06"), - 2.0, - (target_nesting.geography_id("county", "06001"),), - (1.0,), - ), - stray, - ], - ) - with pytest.raises(ValueError, match="at least one row"): - target_nesting.reconcile_blocks(mechanism, [_block("06", (), 2.0)]) + assert {leg["allocator"] for leg in group["legs"]} == {"scale_residual_to_largest"} # The operator's own refusals reach the caller. + rows, legs = _population_rows(("06", 2.0, (0.0, 0.0))) with pytest.raises(ValueError, match="vanishing lower-leg total"): - target_nesting.reconcile_blocks(mechanism, [_block("06", (0.0, 0.0), 2.0)]) + target_nesting.run_pass( + declarations.COUNTY_POPULATION, + rows, + bound_higher_targets=["population"], + legs=legs, + ) def test_the_operators_receipts_are_recorded_only_when_asked(tmp_path) -> None: - blocks = [_block("06", (30.0, 20.0), 100.0)] + rows, legs = _population_rows(("06", 100.0, (30.0, 20.0))) + + def run(): + return target_nesting.run_pass( + declarations.COUNTY_POPULATION, + rows, + bound_higher_targets=["population"], + legs=legs, + ) + recorded = target_nesting.start_nesting_receipts() - _nested, receipt = target_nesting.reconcile_blocks( - declarations.COUNTY_POPULATION, blocks - ) - assert [entry["mechanism"] for entry in recorded] == [ - declarations.COUNTY_POPULATION + _outcomes, receipt = run() + assert recorded == [ + { + "pass": declarations.COUNTY_POPULATION, + "allocator": "scale_residual_to_largest", + "operator_receipt": receipt, + } ] - assert recorded[0]["operator_receipt"] == receipt - assert (recorded[0]["issue_row"], recorded[0]["blocks"]) == (8, 1) path = target_nesting.write_nesting_receipts(tmp_path, recorded) assert path.name == target_nesting.NESTING_RECEIPTS_FILENAME written = json.loads(path.read_text()) assert written["operator"] == "microcosm.build.cross_grain" - assert [entry["mechanism"] for entry in written["passes"]] == [ + assert written["declarations"] == "us/cross_grain_declarations.json" + assert [entry["pass"] for entry in written["passes"]] == [ declarations.COUNTY_POPULATION ] # A new record starts empty, and the earlier list gains nothing more. fresh = target_nesting.start_nesting_receipts() - target_nesting.reconcile_blocks(declarations.COUNTY_POPULATION, blocks) + run() assert len(fresh) == 1 and len(recorded) == 1 # After a stop, a pass records nothing. target_nesting.stop_nesting_receipts() - target_nesting.reconcile_blocks(declarations.COUNTY_POPULATION, blocks) + run() assert len(fresh) == 1 diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_target_loss_weights.py b/packages/microcosm-build/tests/engine_free/us/test_us_target_loss_weights.py index b7054d5a90..236ca3f029 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_target_loss_weights.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_target_loss_weights.py @@ -632,13 +632,10 @@ def _district(name, district, *, parent, value=100.0, unit="usd", **metadata): ledger_source_record_id=f"{name}.record", ledger_layout_groupby_value_label=f"CA congressional district {district}", ledger_fact_label=f"California Congressional District {district} {name}", - state_cd_vintage_rule="state_cd.historic_table_2_level_cd_file_shares.v1", - state_cd_parent_target_name=parent, - state_cd_parent_basis="historic_table_2", - state_cd_parent_value="500.0", - state_cd_cd_file_value=repr(value * 0.9), - state_cd_cd_file_state_sum="450.0", - state_cd_rebase_factor="1.11", + cross_grain_parent=parent, + cross_grain_control="historic_table_2_state_vs_district_file", + cross_grain_value_before=repr(value * 0.9), + cross_grain_factor="1.11", **metadata, ) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_target_nesting_county.py b/packages/microcosm-build/tests/engine_free/us/test_us_target_nesting_county.py index 3fd5e0605b..31a635723c 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_target_nesting_county.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_target_nesting_county.py @@ -1,16 +1,18 @@ -"""The county rows on the shared operator give what the tool gave. +"""The county rows on the cross-grain model are the rows the tool made. -microcosm#1760 moved three county mechanisms of the ACS local release onto -the shared cross-grain operator (``microcosm.build.cross_grain``), through +microcosm#1760 runs three county passes of the ACS local release on the +shared cross-grain operator (``microcosm.build.cross_grain``), through ``microcosm.build.us_runtime.target_nesting``: the county populations -(``with_county_populations``), the county SOI shares +(``with_county_populations``), the county SOI rows (``state_county_soi_surface``) and the county household rows -(``acs_household_surface``). These tests hold the tool functions, which now -call the adapter, to verbatim copies of the code they replace +(``acs_household_surface``). These tests hold the tool functions to verbatim +copies of the code they replace (``test_support/microcosm_build/us_target_nesting_reference.py``) on seeded -random blocks: the same specs in the same order, the same value bits, the -same metadata keys in the same order, the same receipt bytes and the same -refusal texts. +random blocks: the same specs in the same order, the same value bits, the same +parent, value before and members under the operator's metadata keys, and the +same receipt. Where the old code refused, the new code refuses: with the same +text when the adapter refuses, and with the operator's text when the operator +does. The blocks are synthetic. No test here reads the pinned county facts file (``us/chronicle_county_facts.json``), which is not a test input on every @@ -28,6 +30,12 @@ import numpy as np import pytest +from microcosm.build.cross_grain import ( + CONTROL_KEY, + MEMBERS_KEY, + PARENT_KEY, + VALUE_BEFORE_KEY, +) from microcosm.build.us_runtime import cross_grain_declarations as declarations from microcosm.build.us_runtime import target_nesting from microcosm.calibrate import ( @@ -67,22 +75,98 @@ def _bits(values) -> bytes: return b"".join(struct.pack(" tuple: +_OLD_KEYS = "state_county_" +_NEW_KEYS = "cross_grain_" + + +def _plain_image(spec, prefix: str) -> tuple: + """Everything a spec holds but its nesting keys, with the value's bits.""" + fields = { field.name: getattr(spec, field.name) for field in dataclasses.fields(spec) } return ( struct.pack(" tuple | None: + """What the old keys say: (parent, value before, members).""" + + metadata = spec.metadata + if "state_county_parent_target_name" not in metadata: + assert not any(key.startswith(_OLD_KEYS) for key in metadata), spec.name + return None + return ( + metadata["state_county_parent_target_name"], + metadata["state_county_source_value"], + metadata.get("state_county_cell_members"), ) -def _surface_image(surface) -> tuple: +def _new_nesting(spec) -> tuple | None: + """The same three things from the operator's keys.""" + + metadata = spec.metadata + if CONTROL_KEY not in metadata: + assert not any(key.startswith(_NEW_KEYS) for key in metadata), spec.name + return None return ( - [_spec_image(spec) for spec in surface.specs], - json.dumps(surface.receipt, indent=1), + metadata[PARENT_KEY], + metadata[VALUE_BEFORE_KEY], + metadata.get(MEMBERS_KEY), + ) + + +def _receipt_image(receipt: dict, *, old: bool) -> str: + """The receipt without what only one side writes. + + The old blocks hold ``share_sum``, the float sum of the shares (one, or + one bit from it). The new receipt names its declared pass under ``bridge``. + """ + + image = {key: value for key, value in receipt.items() if key != "bridge"} + if old: + image["blocks"] = [ + {key: value for key, value in block.items() if key != "share_sum"} + for block in receipt["blocks"] + ] + return json.dumps(image, indent=1) + + +def _assert_same_surface(new, old, pass_id: str, seed: int) -> None: + assert [ + (_plain_image(spec, _NEW_KEYS), _new_nesting(spec)) for spec in new.specs + ] == [(_plain_image(spec, _OLD_KEYS), _old_nesting(spec)) for spec in old.specs], ( + seed ) + assert _receipt_image(new.receipt, old=False) == _receipt_image( + old.receipt, old=True + ), seed + assert new.receipt["bridge"] == pass_id + + +def _assert_same_refusal(new: tuple, old: tuple, seed: int) -> bool: + """Both refuse. True when the text is the old text. + + The operator checks the members of a block after the adapter's own + checks. So for inputs with two defects, where the old code named the + block that is not complete, the new code can name the other defect. + """ + + assert new[0] == old[0] == "refused", (seed, new[1], old[1]) + if new[1] == old[1]: + return True + assert new[1].startswith("cross-grain ") or old[1].startswith( + "Incomplete county SOI block" + ), (seed, new[1], old[1]) + return False def _outcome(function, *args, **kwargs): @@ -175,6 +259,7 @@ def _population_image(result) -> tuple: def test_county_populations_are_the_old_populations_on_random_ladders(county) -> None: outcomes = {"result": 0, "refused": 0} + texts = {True: 0, False: 0} cells = 0 for seed in SEEDS: ladder, given = _ladder(seed) @@ -182,7 +267,7 @@ def test_county_populations_are_the_old_populations_on_random_ladders(county) -> old = _outcome(reference.with_county_populations, ladder, given, ["county"]) assert new[0] == old[0], seed if new[0] == "refused": - assert new[1] == old[1], seed + texts[_assert_same_refusal(new, old, seed)] += 1 else: assert _population_image(new[1]) == _population_image(old[1]), seed cells += len(new[1]["county"]) @@ -190,6 +275,8 @@ def test_county_populations_are_the_old_populations_on_random_ladders(county) -> # Without the county level the populations pass through untouched. assert county.with_county_populations(ladder, given, ["state", "cd"]) is given assert outcomes["result"] >= 90 and outcomes["refused"] >= 5 + # Both kinds of refusal occur: the adapter's and the operator's. + assert min(texts.values()) >= 1 assert cells >= 1_000 @@ -334,49 +421,43 @@ def _soi_inputs(seed: int): return parents, [facts[index] for index in order], populations -def _surface_outcome(function, *args, **kwargs): - outcome = _outcome(function, *args, **kwargs) - if outcome[0] == "refused": - return outcome - return ("surface", *_surface_image(outcome[1])) - - def test_the_county_soi_surface_is_the_old_surface_on_random_blocks(county) -> None: - outcomes = {"surface": 0, "refused": 0} + outcomes = {"result": 0, "refused": 0} + texts = {True: 0, False: 0} refusals: set[str] = set() rows = combined = 0 for seed in SEEDS: parents, facts, populations = _soi_inputs(seed) - new = _surface_outcome( - county.state_county_soi_surface, parents, facts, populations - ) - old = _surface_outcome( - reference.state_county_soi_surface, parents, facts, populations - ) - assert new == old, seed + new = _outcome(county.state_county_soi_surface, parents, facts, populations) + old = _outcome(reference.state_county_soi_surface, parents, facts, populations) + assert new[0] == old[0], (seed, new[1], old[1]) outcomes[new[0]] += 1 if new[0] == "refused": - refusals.add(" ".join(new[1].split(" ")[:3])) + texts[_assert_same_refusal(new, old, seed)] += 1 + refusals.add(" ".join(old[1].split(" ")[:3])) continue - receipt = json.loads(new[2]) - rows += receipt["county_targets"] - combined += len(receipt["combined_cells"]) - assert outcomes["surface"] >= 80 and outcomes["refused"] >= 10 + _assert_same_surface(new[1], old[1], declarations.COUNTY_SOI, seed) + rows += new[1].receipt["county_targets"] + combined += len(new[1].receipt["combined_cells"]) + assert outcomes["result"] >= 80 and outcomes["refused"] >= 10 assert len(refusals) >= 4 + # A county absent from a block is the operator's refusal. The others are + # the adapter's, with their old text. + assert min(texts.values()) >= 2 assert rows >= 2_000 and combined >= 10 def test_a_combined_cell_other_than_the_declared_one_is_the_old_refusal(county) -> None: parents, facts, populations = _soi_inputs(3) for cells in ({1001: 1001}, {1001: 2001}, {1003: 1001, 1001: 1005}): - new = _surface_outcome( + new = _outcome( county.state_county_soi_surface, parents, facts, populations, combined_cells=cells, ) - old = _surface_outcome( + old = _outcome( reference.state_county_soi_surface, parents, facts, @@ -447,22 +528,24 @@ def _acs_inputs(seed: int): def test_the_county_household_surface_is_the_old_surface_on_random_blocks( county, ) -> None: - outcomes = {"surface": 0, "refused": 0} + outcomes = {"result": 0, "refused": 0} rows = 0 for seed in SEEDS: facts, populations = _acs_inputs(seed) period = 2024 if seed % 3 else 2026 - new = _surface_outcome( - county.acs_household_surface, facts, populations, period=period - ) - old = _surface_outcome( + new = _outcome(county.acs_household_surface, facts, populations, period=period) + old = _outcome( reference.acs_household_surface, facts, populations, period=period ) - assert new == old, seed + assert new[0] == old[0], (seed, new[1], old[1]) outcomes[new[0]] += 1 - if new[0] == "surface": - rows += json.loads(new[2])["county_targets"] - assert outcomes["surface"] >= 90 and outcomes["refused"] >= 5 + if new[0] == "refused": + # Each household refusal is the adapter's, with its old text. + assert _assert_same_refusal(new, old, seed), seed + continue + _assert_same_surface(new[1], old[1], declarations.COUNTY_ACS_HOUSEHOLDS, seed) + rows += new[1].receipt["county_targets"] + assert outcomes["result"] >= 90 and outcomes["refused"] >= 5 assert rows >= 1_000 @@ -474,8 +557,8 @@ def test_household_refusals_come_in_state_order_as_before(county) -> None: _acs_fact(14001, "B11001_001E", 5.0), _acs_fact(34001, "B11001_001E", 0.0), ] - new = _surface_outcome(county.acs_household_surface, facts, populations) - old = _surface_outcome(reference.acs_household_surface, facts, populations) + new = _outcome(county.acs_household_surface, facts, populations) + old = _outcome(reference.acs_household_surface, facts, populations) assert new == old == ("refused", "State 14 has no Census state name.") # The other way round, the zero sum of the earlier state comes first. populations = {1001: 10.0, 14001: 10.0} @@ -483,8 +566,8 @@ def test_household_refusals_come_in_state_order_as_before(county) -> None: _acs_fact(1001, "B11001_001E", 0.0), _acs_fact(14001, "B11001_001E", 5.0), ] - new = _surface_outcome(county.acs_household_surface, facts, populations) - old = _surface_outcome(reference.acs_household_surface, facts, populations) + new = _outcome(county.acs_household_surface, facts, populations) + old = _outcome(reference.acs_household_surface, facts, populations) assert new == old and "no positive share denominator" in new[1] @@ -511,11 +594,12 @@ def test_the_helpers_the_tool_keeps_by_name_are_the_adapters(county) -> None: assert county.acs_households_parent_name(6) == reference.acs_households_parent_name( 6 ) - for metadata in ( - {"county_fips": "15009"}, - {"county_fips": "15009", "state_county_cell_members": "15005,15009"}, - ): - assert county.cell_members(metadata) == reference.cell_members(metadata) + assert county.cell_members({"county_fips": "15009"}) == [15009] + # The members of a combined cell, under the operator's key. + combined = {"county_fips": "15009", MEMBERS_KEY: "15005,15009"} + assert county.cell_members(combined) == reference.cell_members( + {"county_fips": "15009", "state_county_cell_members": "15005,15009"} + ) def test_each_county_pass_records_the_operators_receipt(county) -> None: @@ -544,7 +628,7 @@ def first_accepted(inputs, function): acs = county.acs_household_surface(acs_facts, acs_populations) finally: target_nesting.stop_nesting_receipts() - assert [(entry["mechanism"], entry["allocator"]) for entry in recorded] == [ + assert [(entry["pass"], entry["allocator"]) for entry in recorded] == [ (declarations.COUNTY_POPULATION, "scale_residual_to_largest"), (declarations.COUNTY_SOI, "share_residual_to_largest"), (declarations.COUNTY_ACS_HOUSEHOLDS, "share_residual_to_largest"), @@ -557,15 +641,14 @@ def first_accepted(inputs, function): for group in entry["operator_receipt"]["groups"] for leg in group["legs"] ] - assert len(legs) == entry["blocks"] == len(blocks) + assert len(legs) == len(blocks) assert { group["winning_grain"] for group in entry["operator_receipt"]["groups"] } == {"state"} - # Each leg closed on its control; the old receipt's target sum is that - # control under an exactly rounded sum. + # Each leg closed on its control. for leg in legs: assert leg["new_total"] == pytest.approx( leg["old_total"] * leg["declared_factor"], rel=1e-12 ) - # The old receipts do not hold the operator's receipt. + # The surfaces' receipts do not hold the operator's receipt. assert "groups" not in soi.receipt and "groups" not in acs.receipt diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_target_nesting_district.py b/packages/microcosm-build/tests/engine_free/us/test_us_target_nesting_district.py index d985a0268a..a91532b0bf 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_target_nesting_district.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_target_nesting_district.py @@ -1,14 +1,24 @@ -"""The district SOI shares on the shared operator give what the tool gave. +"""The district SOI rows on the cross-grain model are the rows the tool made. -microcosm#1760 moved ``state_cd_soi_surface`` of the ACS local release onto -the shared cross-grain operator (``microcosm.build.cross_grain``), through +microcosm#1760 runs ``state_cd_soi_surface`` of the ACS local release on the +shared cross-grain operator (``microcosm.build.cross_grain``), through ``microcosm.build.us_runtime.target_nesting``. These tests hold the tool -function, which now calls the adapter, to a verbatim copy of the code it -replaces (``test_support/microcosm_build/us_target_nesting_reference.py``) on -seeded random surfaces: the same specs in the same order, the same value bits, -the same metadata keys in the same order, the same receipt bytes and the same -refusal texts. ``test_us_acs_local_surface_bytes.py`` checks the same on the -pinned feed. +function to a verbatim copy of the code it replaces +(``test_support/microcosm_build/us_target_nesting_reference.py``) on seeded +random surfaces: the same specs in the same order, the same value bits, the +same parent, factor and value before under the operator's metadata keys, and +the same counts, drops and summaries in the receipt. +``test_us_acs_local_surface_bytes.py`` pins the bytes on the pinned feed. + +Three things differ by design, and the tests state each one: + +- A refusal that the operator makes has the operator's text. +- The check that the district file's own state row is the sum of its district + rows is gone. Row 4 of the compile makes that sum hold, and the state row is + not a control of a concept that Historic Table 2 holds. +- With the bound turned off (only tests do that), a concept whose Historic + Table 2 level is zero in every state keeps district rows of zero. The old + code dropped them, because such a concept has no median factor. """ from __future__ import annotations @@ -17,12 +27,22 @@ import importlib.util import json import math +import os import struct +from collections import Counter +from pathlib import Path import numpy as np import pandas as pd import pytest +from microcosm.build.cross_grain import ( + CONTROL_KEY, + EXACT_SIGNATURE_CONTROL, + FACTOR_KEY, + PARENT_KEY, + VALUE_BEFORE_KEY, +) from microcosm.build.us_runtime import cross_grain_declarations as declarations from microcosm.build.us_runtime import target_nesting from microcosm.calibrate import TargetSpec @@ -95,8 +115,9 @@ def _inputs(seed: int): """Compiled-looking SOI specs and a crosswalk, with the hard cases. Some draws are refused (an incomplete plan, a zero sum under a nonzero - parent, a sign conflict, a district file that disagrees with itself); - the old and the new code must then refuse with the same text. + parent, a sign conflict): the old and the new code must then both refuse. + Some hold a district file that disagrees with itself, which only the old + code refused. """ rng = np.random.default_rng(seed) @@ -236,23 +257,134 @@ def _inputs(seed: int): return [specs[index] for index in order], pd.DataFrame(crosswalk), band -def _spec_image(spec) -> tuple: - """Everything a spec holds, with the value's bits and the key order.""" +_OLD_KEYS = "state_cd_" +_NEW_KEYS = "cross_grain_" +_SHARED_RECEIPT_KEYS = ( + "vintage_rule", + "counts", + "dropped", + "dropped_examples", + "defective_cd_file_measures", + "unparented_cd_measures", + "excluded_cd_states", + "at_large_on_source_plan", + "level_bridges", + "level_bridge_factor_by_measure", + "crosswalk", + "sigma", +) + + +def _plain_image(spec, prefix: str) -> tuple: + """Everything a spec holds but its nesting keys, with the value's bits.""" fields = { field.name: getattr(spec, field.name) for field in dataclasses.fields(spec) } return ( struct.pack(" tuple | None: + """What the old keys say: (parent, value before, factor, kind of control).""" + + metadata = spec.metadata + if "state_cd_level_bridge_factor" in metadata: + sibling = metadata["state_cd_level_bridge_sibling"].rsplit(".", 1)[-1] + return ( + None, + metadata["state_cd_cd_file_value"], + metadata["state_cd_level_bridge_factor"], + f"level_bridge:{sibling}", + ) + if "state_cd_parent_target_name" not in metadata: + assert not any(key.startswith(_OLD_KEYS) for key in metadata), spec.name + return None + return ( + metadata["state_cd_parent_target_name"], + metadata["state_cd_cd_file_value"], + metadata["state_cd_rebase_factor"], + metadata["state_cd_parent_basis"], + ) + + +def _new_nesting(spec) -> tuple | None: + """The same four things from the operator's keys.""" + + metadata = spec.metadata + if CONTROL_KEY not in metadata: + assert not any(key.startswith(_NEW_KEYS) for key in metadata), spec.name + return None + control = metadata[CONTROL_KEY] + if control.startswith(f"{declarations.DISTRICT_SOI}:"): + control = "historic_table_2" + elif control == EXACT_SIGNATURE_CONTROL: + # The district file's own state row, lifted by a level bridge. + control = "cd_file_state_total_bridged" + return ( + metadata.get(PARENT_KEY), + metadata[VALUE_BEFORE_KEY], + metadata[FACTOR_KEY], + control, + ) + + +def _band_row(row: dict, verdict: str) -> str: + return json.dumps( + { + "state_fips": row["state_fips"], + "measure": row["measure"], + "concept": row["concept"], + "verdict": verdict, + "ratio": row["ratio"], + "median_ratio": row["median_ratio"], + "relative": row["relative"], + } + ) + + +def _old_image(surface) -> tuple: + receipt = surface.receipt + out_of_band = receipt["factor_band"]["out_of_band"] + return ( + [(_plain_image(spec, _OLD_KEYS), _old_nesting(spec)) for spec in surface.specs], + json.dumps({key: receipt[key] for key in _SHARED_RECEIPT_KEYS}), + json.dumps(receipt["rebase_factor_by_measure"]), + sorted( + (row["state_fips"], row["concept"]) + for row in out_of_band + if row["verdict"] == "rebase_factor" + ), + sorted( + _band_row(row, row["verdict"].replace("sibling_rebase_", "sibling_")) + for row in out_of_band + if row["verdict"] != "rebase_factor" + ), + json.dumps(reference.state_parent_reconciliation(surface.specs)), ) -def _surface_image(surface) -> tuple: +def _new_image(surface, closure_report) -> tuple: + receipt = surface.receipt return ( - [_spec_image(spec) for spec in surface.specs], - json.dumps(surface.receipt, indent=1), + [(_plain_image(spec, _NEW_KEYS), _new_nesting(spec)) for spec in surface.specs], + json.dumps({key: receipt[key] for key in _SHARED_RECEIPT_KEYS}), + json.dumps(receipt["factor_by_measure"]), + sorted( + (row["state_fips"], row["concept"]) for row in receipt["bridge"]["unbound"] + ), + sorted( + _band_row(row, row["verdict"]) + for row in receipt["level_bridge_out_of_band"] + ), + json.dumps(closure_report(surface.specs)), ) @@ -267,53 +399,72 @@ def _run(module, specs, crosswalk, band, predicate): ) except ValueError as error: return ("refused", str(error)) - return ("surface", *_surface_image(surface)) + return ("surface", surface) def test_the_district_surface_is_the_old_surface_on_random_inputs(tool) -> None: predicate = tool.soi_surface_predicate("state") + closure_report = tool.cd_surface.state_parent_reconciliation outcomes = {"surface": 0, "refused": 0} - refusals: set[str] = set() - rows = out_of_band = bridged = signed = single = nan_rows = 0 + same_text = operator_text = self_disagreements = unbounded_zero = 0 + rows = unbound = bridged = signed = single = distrusted = 0 for seed in SEEDS: specs, crosswalk, band = _inputs(seed) new = _run(tool.cd_surface, specs, crosswalk, band, predicate) old = _run(reference, specs, crosswalk, band, predicate) - assert new == old, seed + if old[0] == "refused" and "differs from the sum of its district" in old[1]: + # By design: the new code does not make this check. + self_disagreements += 1 + continue + assert new[0] == old[0], (seed, new[1], old[1]) outcomes[new[0]] += 1 if new[0] == "refused": - refusals.add(new[1].split(" ")[0] + " " + new[1].split(" ")[1]) + # The adapter's refusals keep their text. The operator's have its. + if new[1] == old[1]: + same_text += 1 + else: + assert new[1].startswith("cross-grain "), (seed, new[1], old[1]) + operator_text += 1 + continue + old_surface, surface = old[1], new[1] + zero_levels = [ + row + for row in old_surface.receipt["factor_band"]["out_of_band"] + if row["verdict"] == "rebase_factor" and math.isnan(row["median_ratio"]) + ] + if math.isinf(band) and zero_levels: + # By design: with no bound, the rows of a concept that is zero in + # every state stay, with a value of zero. + dropped = {row["concept"] for row in zero_levels} + kept = [ + spec + for spec in surface.specs + if PARENT_KEY in spec.metadata + and spec.metadata["source_measure_id"] in dropped + ] + assert kept and {spec.value for spec in kept} == {0.0}, seed + unbounded_zero += 1 continue - receipt = json.loads(new[2]) + assert _new_image(surface, closure_report) == _old_image(old_surface), seed + receipt = surface.receipt rows += receipt["counts"]["congressional_district"] - out_of_band += len(receipt["factor_band"]["out_of_band"]) - nan_rows += sum( - row["relative"] != row["relative"] - for row in receipt["factor_band"]["out_of_band"] - ) + unbound += len(receipt["bridge"]["unbound"]) + distrusted += len(receipt["level_bridge_out_of_band"]) bridged += receipt["counts"]["cd_file_state"] - surface = tool.cd_surface.state_cd_soi_surface( - specs, - state_surface_predicate=predicate, - crosswalk=crosswalk, - factor_band=band, - ) children: dict[str, int] = {} for spec in surface.specs: - parent = spec.metadata.get("state_cd_parent_target_name") + parent = spec.metadata.get(PARENT_KEY) if parent is not None: children[parent] = children.get(parent, 0) + 1 signed += spec.value < 0 single += sum(count == 1 for count in children.values()) - # The closure report of the tool is the old report. - assert tool.cd_surface.state_parent_reconciliation( - surface.specs - ) == reference.state_parent_reconciliation(surface.specs) # The draws reach the hard cases the move must keep. - assert outcomes["surface"] >= 100 and outcomes["refused"] >= 10 - assert len(refusals) >= 3 + assert outcomes["surface"] >= 100 and outcomes["refused"] >= 8 + assert min(same_text, operator_text) >= 2 assert rows >= 2_000 - assert min(out_of_band, bridged, signed, single, nan_rows) >= 5 + assert min(unbound, bridged, signed, single) >= 5 + # And the three differences that are by design. + assert min(self_disagreements, unbounded_zero) >= 1 def _two_district_case(parent_value: float, values: tuple[float, float]): @@ -351,9 +502,9 @@ def _two_district_case(parent_value: float, values: tuple[float, float]): @pytest.mark.parametrize( ("parent_value", "values"), [ - (100.0, (5.0, 15.0)), # a plain rebase + (100.0, (5.0, 15.0)), # a plain division (0.0, (0.0, 0.0)), # an all-zero block under a zero parent - (0.0, (5.0, 15.0)), # a zero parent: out of band, with NaN in the receipt + (0.0, (5.0, 15.0)), # a zero parent: unbound, with no median factor (100.0, (0.1, 0.2)), # shares whose products round (10.0, (-5.0, 15.0)), # a signed row ], @@ -366,8 +517,11 @@ def test_the_hard_cases_are_the_old_surface(tool, parent_value, values) -> None: for spec in specs ] new = _run(tool.cd_surface, specs, crosswalk, 1.25, predicate) - assert new == _run(reference, specs, crosswalk, 1.25, predicate) - assert new[0] == "surface" + old = _run(reference, specs, crosswalk, 1.25, predicate) + assert new[0] == old[0] == "surface" + assert _new_image( + new[1], tool.cd_surface.state_parent_reconciliation + ) == _old_image(old[1]) def test_the_district_pass_records_the_operators_receipt(tool) -> None: @@ -382,10 +536,9 @@ def test_the_district_pass_records_the_operators_receipt(tool) -> None: finally: target_nesting.stop_nesting_receipts() (entry,) = recorded - assert (entry["mechanism"], entry["allocator"], entry["blocks"]) == ( + assert (entry["pass"], entry["allocator"]) == ( declarations.DISTRICT_SOI, "proportional_fsum", - 1, ) (group,) = entry["operator_receipt"]["groups"] (leg,) = group["legs"] @@ -393,14 +546,79 @@ def test_the_district_pass_records_the_operators_receipt(tool) -> None: "state", "congressional_district", ) + # The bridge that the declared selector makes for this measure. + bridge_id = f"{declarations.DISTRICT_SOI}:lower_file|adjusted_gross_income|-inf|inf|all|None" + assert group["bridge_id"] == bridge_id assert (leg["old_total"], leg["declared_factor"], leg["new_total"]) == ( 20.0, 5.0, 100.0, ) - # The old metadata reads the same factor and sum. + # A district row names the same bridge, factor and parent. district = surface.specs[-1] - assert district.metadata["state_cd_rebase_factor"] == repr(leg["declared_factor"]) - assert district.metadata["state_cd_cd_file_state_sum"] == repr(leg["old_total"]) - # The old receipt does not hold the operator's receipt. + assert district.metadata[CONTROL_KEY] == bridge_id + assert district.metadata[FACTOR_KEY] == repr(leg["declared_factor"]) + assert district.metadata[PARENT_KEY] == "ht2.10.adjusted_gross_income" + assert district.metadata[VALUE_BEFORE_KEY] == repr(15.0) + assert not [key for key in district.metadata if key.startswith(_OLD_KEYS)] + # The surface's receipt does not hold the operator's receipt. assert "groups" not in surface.receipt + + +def test_the_pinned_feed_surface_is_the_old_surface(tool) -> None: + """On the pinned feed: the old rows and value bits, under the new keys. + + ``test_us_acs_local_surface_bytes.py`` pins the bytes of the ``state_cd`` + surface. Those bytes moved with the metadata keys. This test holds what + did not move: each row, the bits of its value, its parent, its factor and + its value before, and the counts, drops and summaries of the receipt. + """ + + feed = os.environ.get("MICROCOSM_US_CHRONICLE_FACTS", "") + if not feed or not Path(feed).exists(): + pytest.skip("set MICROCOSM_US_CHRONICLE_FACTS to the pinned 41b2fb2 feed") + from microcosm.build.us_runtime import ( + default_congressional_district_vintage_crosswalk_path, + load_congressional_district_vintage_crosswalk, + ) + + registry, _substitutions = tool._compiled_fiscal_registry(feed) + candidates = registry.select( + family="irs_soi", predicate=tool.soi_surface_predicate("state_cd") + ).specs + crosswalk = load_congressional_district_vintage_crosswalk( + default_congressional_district_vintage_crosswalk_path() + ) + predicate = tool.soi_surface_predicate("state") + new = _run(tool.cd_surface, candidates, crosswalk, 1.25, predicate) + old = _run(reference, candidates, crosswalk, 1.25, predicate) + assert new[0] == old[0] == "surface" + assert _new_image( + new[1], tool.cd_surface.state_parent_reconciliation + ) == _old_image(old[1]) + controls = Counter( + (_new_nesting(spec) or (None, None, None, "no nesting"))[3] + for spec in new[1].specs + ) + assert controls == { + "historic_table_2": 19_181, + "cd_file_state_total_bridged": 2_562, + "no nesting": 4_227, + **{ + f"level_bridge:{sibling}": count + for sibling, count in Counter( + _new_nesting(spec)[3].split(":", 1)[1] + for spec in new[1].specs + if (_new_nesting(spec) or ("",) * 4)[3].startswith("level_bridge:") + ).items() + }, + } + assert sum(controls.values()) == 26_272 + assert ( + sum( + count + for kind, count in controls.items() + if kind.startswith("level_bridge:") + ) + == 302 + ) diff --git a/tools/build_us_acs_local_release.py b/tools/build_us_acs_local_release.py index dead8ac88d..d8e02c819a 100644 --- a/tools/build_us_acs_local_release.py +++ b/tools/build_us_acs_local_release.py @@ -5147,7 +5147,7 @@ def state_cd_reviewed_limitations(materialize_rss: dict) -> list[dict]: "id": "cd_soi_one_vintage_per_state_concept", "status": "reviewed_construction", "reason": surface.get("vintage_rule_description"), - "rebase_factor_by_measure": surface.get("rebase_factor_by_measure"), + "factor_by_measure": surface.get("factor_by_measure"), "level_bridges": surface.get("level_bridges"), "level_bridge_factor_by_measure": surface.get( "level_bridge_factor_by_measure" diff --git a/tools/us_acs_local_cd_surface.py b/tools/us_acs_local_cd_surface.py index 4d9ebeaa23..cc20ecc9a8 100644 --- a/tools/us_acs_local_cd_surface.py +++ b/tools/us_acs_local_cd_surface.py @@ -52,10 +52,10 @@ def _district_soi_nesting(): """The declared choices of the ``state_cd`` surface (microcosm#1760). ``us/cross_grain_declarations.json`` holds them with their reasons: the - vintage rule, the registers of defective, unparented and excluded - district measures, the level bridges, the factor band and the two - tolerances. The names below are those choices under the names they had as - literals here. + bridge between Historic Table 2 and the district file with its bound, the + registers of defective, unparented and excluded district measures, and + the level bridges that stay until the feed re-pin. The names below are + those choices under the names this module always had. """ from microcosm.build.us_runtime.cross_grain_declarations import ( @@ -65,7 +65,25 @@ def _district_soi_nesting(): return us_district_soi_nesting() +def _cross_grain(): + """The shared cross-grain operator module (its metadata key names).""" + + from microcosm.build import cross_grain + + return cross_grain + + _DISTRICT_SOI_NESTING = _district_soi_nesting() +#: The metadata that a reconciled district row keeps, as every row that the +#: shared cross-grain operator reconciles does (the UK rows too): its parent +#: row, what reconciled it, the factor, and its value before. +PARENT_KEY = _cross_grain().PARENT_KEY +NESTING_KEYS = ( + PARENT_KEY, + _cross_grain().CONTROL_KEY, + _cross_grain().FACTOR_KEY, + _cross_grain().VALUE_BEFORE_KEY, +) #: How the ``state_cd`` surface resolves the two vintages of a state concept. STATE_CD_VINTAGE_RULE = _DISTRICT_SOI_NESTING.vintage_rule #: District-file measures that read the wrong IRS column (microcosm#1038). @@ -77,24 +95,21 @@ def _district_soi_nesting(): _DISTRICT_SOI_NESTING.unparented_lower_measures ) #: District-file-only concepts and the sibling concept that bridges their -#: state level onto the Historic Table 2 basis. +#: state level onto the Historic Table 2 basis (until the feed re-pin). STATE_CD_LEVEL_BRIDGES: Mapping[str, str] = dict(_DISTRICT_SOI_NESTING.level_bridges) #: States whose district SOI rows stay off the surface, with the evidence. STATE_CD_EXCLUDED_CD_STATES: Mapping[str, str] = dict( _DISTRICT_SOI_NESTING.excluded_legs ) -#: How far a state's Historic Table 2 / district-file ratio may sit from its -#: measure's median across states. +#: How far a state's Historic Table 2 / district-file factor may sit from its +#: measure's median across states: the declared bound of the bridge, as a +#: ratio to that median. STATE_CD_FACTOR_BAND = _DISTRICT_SOI_NESTING.factor_band -#: Relative tolerance between the district file's own state row and the sum -#: of its district rows. -STATE_CD_INTERNAL_RTOL = _DISTRICT_SOI_NESTING.internal_rtol #: The packaged crosswalk the registers above were reviewed against. A test #: pins it, so regenerating the crosswalk forces a second look at them. STATE_CD_REVIEWED_CROSSWALK_SHA256 = _DISTRICT_SOI_NESTING.reviewed_crosswalk_sha256 -#: Relative tolerance for "district rows sum to their state parent". The -#: rebase makes it exact up to float64 rounding. +#: Relative tolerance for "district rows sum to their state parent". RECONCILIATION_RTOL = _DISTRICT_SOI_NESTING.closure_rtol SIGMA_BASIS_FEED = "feed_standard_error" @@ -314,7 +329,7 @@ def state_parent_reconciliation( ) -> list[dict]: """Every (state parent, district rows) block and whether it adds up. - A block is the district specs naming one ``state_cd_parent_target_name``. + A block is the district specs naming one parent (``cross_grain_parent``). Returns one entry per block with the parent value, the district sum and ``ok`` (relative difference within ``rtol``). """ @@ -601,7 +616,7 @@ def district_row_parents( Returns ``{row index: (parent name, strict)}`` and the rows with no parent, over the rows whose carrier compiled. - - A ``state_cd`` row names its parent (``state_cd_parent_target_name``), + - A ``state_cd`` row names its parent (``cross_grain_parent``), and its block partitions that parent's state, so the check is strict: the stored district rows, laid side by side, must equal the parent's column on every household. A ``state_cd`` row without a compiled parent @@ -635,8 +650,8 @@ def district_row_parents( continue # the row is not materialized, so not on the surface spec = plan.declared[index] metadata = spec.metadata - named = metadata.get("state_cd_parent_target_name") - if "state_cd_vintage_rule" in metadata and named not in compiled: + named = metadata.get(PARENT_KEY) + if PARENT_KEY in metadata and named not in compiled: raise ValueError( f"state_cd district row {spec.name} has no compiled state " f"parent ({named!r}); its per-chunk check would be vacuous." @@ -807,12 +822,7 @@ def target_record(spec) -> dict: "sigma": None if se is None else float(se), "sigma_basis": SIGMA_BASIS_NONE if se is None else SIGMA_BASIS_FEED, } - for key in ( - "state_cd_parent_target_name", - "state_cd_parent_basis", - "state_cd_rebase_factor", - "state_cd_cd_file_value", - ): + for key in NESTING_KEYS: if key in metadata: record[key] = metadata[key] return record @@ -825,7 +835,7 @@ def cd_holdout_unit_key(record: Mapping) -> str | None: return None if record.get("geography_level") != GEOGRAPHY_CD: return None - if not record.get("state_cd_parent_target_name"): + if not record.get(PARENT_KEY): return None return ( f"{record['state_fips']}|" @@ -993,7 +1003,7 @@ def pro_rata_baseline(records: Sequence[Mapping], rows: Sequence[int]) -> np.nda values = [] for index in rows: record = records[index] - parent = by_name.get(record.get("state_cd_parent_target_name")) + parent = by_name.get(record.get(PARENT_KEY)) if parent is None: raise ValueError( f"{record['name']} has no bound state parent for the baseline." diff --git a/tools/us_acs_local_county_surface.py b/tools/us_acs_local_county_surface.py index 469699d967..374f7d8fcc 100644 --- a/tools/us_acs_local_county_surface.py +++ b/tools/us_acs_local_county_surface.py @@ -76,6 +76,10 @@ def _target_nesting(): _COUNTY_SOI_NESTING = _county_soi_nesting() +#: The metadata keys of a row that the shared cross-grain operator +#: reconciled: its parent row, and the counties a combined cell stands for. +PARENT_KEY = cd_surface.PARENT_KEY +MEMBERS_KEY = _target_nesting().MEMBERS_KEY COUNTY_SOI_REQUIRED_MEASURES = _COUNTY_SOI_NESTING.required_measures #: 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 @@ -308,7 +312,7 @@ def state_county_soi_surface( 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. + ``cross_grain_members`` lists the member counties. The work is in :func:`microcosm.build.us_runtime.target_nesting.county_soi_surface`: the @@ -347,7 +351,7 @@ def split_state_rows( by_name = {spec.name: index for index, spec in enumerate(state_specs)} blocks = defaultdict(list) for index, spec in enumerate(county_specs): - blocks[spec.metadata["state_county_parent_target_name"]].append(index) + blocks[spec.metadata[PARENT_KEY]].append(index) rows, cols, data = [], [], [] for parent_name, indices in blocks.items(): parent_index = by_name[parent_name] @@ -1165,20 +1169,13 @@ def target_record(spec): record["geography_level"] = record["geography_level"] or spec.metadata.get( "geography_level" ) - for key in ( - "county_fips", - "state_county_parent_target_name", - "state_county_share", - "county_population", - "state_population", - "state_county_cell_members", - ): + # The parent, control, factor and value before are on the record already. + for key in ("county_fips", "county_population", "state_population", MEMBERS_KEY): if key in spec.metadata: value = spec.metadata[key] record[key] = ( float(value) - if key - in {"state_county_share", "county_population", "state_population"} + if key in {"county_population", "state_population"} else value ) return record @@ -1202,7 +1199,7 @@ def assign_target_roles( if record.get("geography_level") != "county": continue unit = None - if record.get("state_county_parent_target_name"): + if record.get(PARENT_KEY): family = ( cd_surface.soi_concept_family(str(record.get("source_measure_id"))) if record.get("family") == "irs_soi" @@ -1237,7 +1234,7 @@ def pro_rata_baseline(records, rows): values = [] for index in rows: record = records[index] - parent = by_name.get(record.get("state_county_parent_target_name")) + parent = by_name.get(record.get(PARENT_KEY)) county, state = ( float(record.get("county_population", 0)), float(record.get("state_population", 0)), @@ -1311,7 +1308,7 @@ def reliability_grade(ess, error): def record_counties(record): """The counties a county record's error counts toward (combined cells: all).""" - members = record.get("state_county_cell_members") + members = record.get(MEMBERS_KEY) if members: return [int(member) for member in str(members).split(",")] return [int(record["county_fips"])] @@ -2003,7 +2000,7 @@ def zero_measure_soi_rows(specs, households, empty, *, county_column=COUNTY_COLU "county_fips": str(spec.metadata["county_fips"]), "cell_members": [f"{member:05d}" for member in members], "concept": spec.metadata.get("source_measure_id"), - "parent": spec.metadata.get("state_county_parent_target_name"), + "parent": spec.metadata.get(PARENT_KEY), "target_value": float(spec.value), "households": int(in_cell), "reason": ( @@ -2788,9 +2785,7 @@ def key(spec): if not _is_county(spec): return base.concept_budget_key(spec) code = spec.metadata["county_fips"] - concept = spec.metadata.get( - "state_county_parent_target_name", "resident_population" - ) + concept = spec.metadata.get(PARENT_KEY, "resident_population") return ( basis(spec), spec.entity, From 011651554cb7c9e145f7b27b6a899d93b9644a8f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:19:51 +0000 Subject: [PATCH 15/23] Describe the US on the cross-grain model in the pages and the changelog docs/us-target-nesting.md is the page of the code as it is after step 2 of microcosm#1760: the six things of the model, the four passes, what the operator checks and what the adapter checks, what stays until the feed re-pin, the metadata keys with the keys they replace, and each difference from the code before. The SOI surface page and the county page name the new keys and receipt fields. The design page records that steps 1 and 2 are on the branch and which two parts of the model are not built yet (the scaled derived control, and one pass on one joint surface). Co-Authored-By: Claude Fable 5.2 --- ...s-target-nesting-on-cross-grain.changed.md | 2 +- docs/us-acs-local-county-rung.md | 2 +- docs/us-acs-local-soi-target-surface.md | 35 +- docs/us-target-nesting-rule-design.md | 15 +- docs/us-target-nesting.md | 397 ++++++++++-------- 5 files changed, 258 insertions(+), 193 deletions(-) diff --git a/changelog.d/1760-us-target-nesting-on-cross-grain.changed.md b/changelog.d/1760-us-target-nesting-on-cross-grain.changed.md index 57983111e8..8ac65eeaf3 100644 --- a/changelog.d/1760-us-target-nesting-on-cross-grain.changed.md +++ b/changelog.d/1760-us-target-nesting-on-cross-grain.changed.md @@ -1 +1 @@ -The US share mechanisms of the ACS local release run on the shared cross-grain operator that the UK uses (`microcosm.build.cross_grain`), with no target change (microcosm#1760, Stage A). `CrossGrainRule` takes an optional `allocator`: with none, the operator runs its standing rule with no float operation added or removed, so the UK outputs are the same; the UK graph hashes the file, so UK target nodes and the nodes after them compute again on the next UK run. The new shared `microcosm.build.cross_grain_controls` holds the allocators, derived controls, factor band, completeness and self-consistency helpers. `us/cross_grain_declarations.json` declares the US levels, the four mechanisms (district SOI shares, county population, county SOI shares, county households) with their registers, and an inventory of each family that two levels measure; `us_runtime.target_nesting` is the adapter. `state_cd_soi_surface`, `with_county_populations`, `state_county_soi_surface` and `acs_household_surface` keep their names and signatures. Every surface on the pinned feed and ladder has the bytes it had. The materialize stage also writes the operator's own receipts to `target_nesting.json`. See `docs/us-target-nesting.md`. +The US nests its local target rows on the shared cross-grain operator that the UK uses (`microcosm.build.cross_grain`), with no target change (microcosm#1760). The operator gains general options that the UK does not declare, so the UK outputs are the same; the UK graph hashes the file, so UK target nodes and the nodes after them compute again on the next UK run. The options: a bound of a bridge measured from the median factor, one-sided, that can unbind a leg; the declared members of a leg; bridge selectors; an optional `allocator`; and `cross_grain_metadata`, the keys of a reconciled row. The shared `microcosm.build.cross_grain_controls` holds the row-level pass (`reconcile_rows`) and the allocators that keep the US values bit for bit until the feed re-pin. `us/cross_grain_declarations.json` declares the US choices under the UK's key names (bridge selectors, a derived control, relations, local routes, members). `state_cd_soi_surface`, `with_county_populations`, `state_county_soi_surface` and `acs_household_surface` keep their names and signatures, and each target value on the pinned feed and ladder is the value it was. **The metadata keys change**: district and county rows carry `cross_grain_parent`, `cross_grain_value_before`, `cross_grain_factor`, `cross_grain_control` and `cross_grain_members` in place of the `state_cd_*` and `state_county_*` keys, and the district receipt takes the fields `bridge`, `level_bridge_out_of_band` and `factor_by_measure`. So the bytes of the `state_cd` registry, roles and receipts move. A refusal that the operator makes has the operator's text; the check that the district file agrees with itself is gone (the compile holds that sum); a concept with two parent sources is refused. The materialize stage also writes the operator's receipts to `target_nesting.json`. See `docs/us-target-nesting.md`. diff --git a/docs/us-acs-local-county-rung.md b/docs/us-acs-local-county-rung.md index 99f2ae201d..ebe8ee7643 100644 --- a/docs/us-acs-local-county-rung.md +++ b/docs/us-acs-local-county-rung.md @@ -352,7 +352,7 @@ The inspected Chronicle publisher inputs have two concrete issues: 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 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` + `combined_cells`, and each Maui row carries `cross_grain_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` diff --git a/docs/us-acs-local-soi-target-surface.md b/docs/us-acs-local-soi-target-surface.md index 98385be2df..13fca17df5 100644 --- a/docs/us-acs-local-soi-target-surface.md +++ b/docs/us-acs-local-soi-target-surface.md @@ -236,7 +236,7 @@ district rows, are mostly 1.00 to 1.10. state's level. The factor band below drops those blocks. `materialize_rss.json` records the full table under -`soi_surface.rebase_factor_by_measure`. +`soi_surface.factor_by_measure`. ### The factor band @@ -259,16 +259,20 @@ bridge built on that sibling is trusted there: bridge loses the bridged state row and its district rows (`level_bridge_out_of_band:`). -Every failing verdict is recorded in the receipt under -`factor_band.out_of_band` with the verdict, its ratio, the median and the -relative gap. The band only judges finite positive ratios: a sibling whose -two levels differ in sign is a data defect and is refused outright. So is a -district file that disagrees with itself: wherever the file carries a state -row beside its district rows, the two must agree to 1e-6 -(`STATE_CD_INTERNAL_RTOL`), since no median absorbs a column or crosswalk -defect inside the file. On the pinned feed all 2,193 blocks agree to float -precision (largest relative gap 4e-16; the receipt records it under -`internal_consistency`, and the feed-gated test pins it). +The band is the declared bound of the bridge between the two files +(`historic_table_2_state_vs_district_file` in +`us/cross_grain_declarations.json`), and the shared cross-grain operator +applies it (see [US target nesting](us-target-nesting.md)). The receipt +records each block that the bound takes off under `bridge.unbound`, with its +factor, and each distrusted bridge under `level_bridge_out_of_band`, with the +verdict, its ratio, the median and the relative gap. The band only judges +finite positive ratios: a sibling whose two levels differ in sign is a data +defect and is refused outright. + +Until microcosm#1760 this stage also refused a district file whose own state +row was not the sum of its district rows. That check is gone: the compile +scales the district rows to that state row before this stage runs +(`reconcile_ledger_target_hierarchy`), so the sum holds by construction. On the pinned feed the band drops eight: @@ -313,9 +317,12 @@ amounts (median 1.062; the two above 1.25x the median are dropped) and stamp, the sibling ratio shrinks with it. Its district rows keep their within-state shares, as every other district row does. -Every district row records its parent (`state_cd_parent_target_name`), the -parent's basis, the district file's own value and the rebase factor; a -bridged state row records its sibling and bridge factor. +Every district row records its parent (`cross_grain_parent`), what +reconciled it (`cross_grain_control`), the district file's own value +(`cross_grain_value_before`) and the factor (`cross_grain_factor`). A bridged +state row records its sibling (`cross_grain_control` reads +`level_bridge:`) and its bridge factor. These are the keys of every +row that the shared cross-grain operator reconciles. ### What stays off the surface diff --git a/docs/us-target-nesting-rule-design.md b/docs/us-target-nesting-rule-design.md index e2ed5845e3..e0e8886d1a 100644 --- a/docs/us-target-nesting-rule-design.md +++ b/docs/us-target-nesting-rule-design.md @@ -328,8 +328,19 @@ Each step is one or more ordered commits on this branch. Step 2 meets PR #1755 in two places: its pin test holds the registry bytes, and its hold-out declaration reads the old key -(`state_cd_parent_target_name`). The PR that merges second takes the other's -change. +(`state_cd_parent_target_name`, now `cross_grain_parent`). The PR that merges +second takes the other's change. + +**Status, 27 Nov 2026.** Steps 1 and 2 are on the branch. Two parts of the +model are not built, because no rule in force uses them yet: + +- the derived control of the kind `scaled`, which decision 2 needs; +- one pass on one joint surface. In step 2 the four passes call one function, + each on its own surface: each pass keeps its allocator until the re-pin, + and the county rows are made at a later stage than the district rows. + +Step 2 also settled the two open points below. Medicaid is a `subset` with a +declared `max_excess`. No US surface needs rows that bind nothing yet. Two points to settle when the code is written: diff --git a/docs/us-target-nesting.md b/docs/us-target-nesting.md index c8981578ef..4a0d10cfc1 100644 --- a/docs/us-target-nesting.md +++ b/docs/us-target-nesting.md @@ -3,36 +3,22 @@ A target for a small area must agree with the target of the area that contains it. This page says how the US build makes the rows of a lower geography level from a control at a higher level, and where each choice is -declared. The tracking issue is microcosm#1760. Stage A, described here, -changes no target value. - -## What Stage A decides: nothing - -Stage A moves the mechanisms that exist to one operator and writes their -choices down as data. Each mechanism is declared as the code ran it before -the move. These decisions of microcosm#1760 are open, and Stage B applies -them: - -1. Which level holds the level value, for each family. -2. Two sources at two levels: whether district rows from a survey are shares - of a state row from estimates, or stay as levels. -3. Row 7: whether the state households target stays the sum of the county - values, or becomes a state level that the counties divide. -4. The parent row in the loss, when all its children are in the loss too. -5. The factor bound: one declared bound for each bridge, as in the UK, or - the median band of row 5. -6. Children that are not complete: district plans, a county with no IRS row, - a state with one district. - -After Stage A, each decision is an edit to the declaration, and for some an -allocator. It is not a new mechanism. - -One point is ruled since (27 Nov 2026): the Historic Table 2 state row is the -state parent of a district row on every surface, and a parent that it does -not contain is not removed. The proposed rule for all levels, with a -recommendation for each open decision, is in -[US target nesting rule: design and rulings](us-target-nesting-rule-design.md). -Its nine decisions were accepted on 27 Nov 2026. No code applies them yet. +declared. The tracking issue is microcosm#1760. The work so far changes no +target value. + +## What is decided, and what the code applies + +- **Ruled, 27 Nov 2026.** The Historic Table 2 state row is the state parent + of a district row on every surface, and a parent that it does not contain + is not removed. The nine decisions of + [US target nesting rule: design and rulings](us-target-nesting-rule-design.md) + are accepted. The declaration is one general model in the shared operator, + with no construct for one country only. +- **In the code.** The US nests its rows on that model: one operator, one + declaration in the UK's key names, one set of metadata keys, one receipt + format. The values are the values the tools made before. +- **Not in the code yet.** Each ruled change of a target. Those need the + Chronicle feed after PolicyEngine/chronicle#451, and a re-pin of the feed. ## One operator, one declaration @@ -44,169 +30,230 @@ target values only, never loss weights. | Part | Where | What it holds | |---|---|---| -| The operator | `microcosm.build.cross_grain` | Grouping, the control of each leg, the division, the sum check, the receipt. Shared with the UK. | -| The helpers | `microcosm.build.cross_grain_controls` | Allocators, derived controls, the factor band, the completeness check, the self-consistency check. No country in it. | -| The US declaration | `us/cross_grain_declarations.json` | The levels, the levels that hold controls, each mechanism with its registers and reasons, and the inventory. | -| The reader | `us_runtime/cross_grain_declarations.py` | Typed views of the declaration. | -| The US adapter | `us_runtime/target_nesting.py` | Which specs or facts are the control and the rows, the refusals with their US texts, the old metadata keys and receipts. | - -The declaration uses the key names of `uk/cross_grain_declarations.json` where -the meaning is the same: `grain_precedence`, `control_grains`, -`signature_fields`, `bridges` and `partitions`. The US levels are the feed's -own geography levels: `country`, `state`, `congressional_district`, `county`. -Districts and counties both divide a state. They do not nest in each other, -and only `country` and `state` hold controls. - -### The allocator - -The operator's standing rule is `row x control / numpy sum of the rows`. The -US rows were made with `math.fsum`, and the county rows with a residual rule. -On the pinned feed the numpy sum changes the last bit of 5,533 of the 21,743 -district values. So a rule can declare an allocator -(`CrossGrainRule.allocator`), a function that divides one control among its -rows. With no allocator the operator runs the standing rule, with no float -operation added or removed; the UK declares none. - -| Allocator | Rule | Used by | +| The operator | `microcosm.build.cross_grain` | Grouping, the control of each leg, bridges and bridge selectors, the bound of a bridge, the members of a leg, the division, the sum check, the receipt, and the metadata keys of a reconciled row. Shared with the UK | +| The row-level pass | `microcosm.build.cross_grain_controls` | `reconcile_rows` runs the operator on target rows and says what it did with each row. `sum_of_lower_rows` is the arithmetic of a derived control. The three allocators stay until the feed re-pin. No country in it | +| The US declaration | `us/cross_grain_declarations.json` | The US choices, under the key names of `uk/cross_grain_declarations.json` | +| The reader | `us_runtime/cross_grain_declarations.py` | Typed views of the declaration, and the coverage check | +| The US adapter | `us_runtime/target_nesting.py` | Which specs or facts are the rows of each pass, the checks that are US rules, and the specs made from the operator's answer | + +The US levels are the feed's own geography levels: `country`, `state`, +`congressional_district`, `county`. Districts and counties both divide a +state. They do not nest in each other, and only `country` and `state` hold +controls. + +## The model + +The model has six things. Each one is general: a country declares it, and the +shared code runs it. + +| Thing | What it is | In the US declaration | |---|---|---| -| `proportional_fsum` | `row x control / exactly rounded sum` | District SOI shares | -| `share_residual_to_largest` | `control x share`; the rounding residual of the shares, then of the products, goes to the largest row | County SOI shares, county households | -| `scale_residual_to_largest` | `control x row / total`; the rounding residual goes to the largest row | County population | +| Measurement | Two targets with the same measurement at two levels are one quantity. Nothing else is declared | `same_measurement`: the ladder population of a state and of its counties | +| Bridge | Two targets with different measurements that measure one quantity. A bridge names its sides by id, or by a selector that makes one bridge for each pair of targets | `bridge_selectors`: Historic Table 2 state rows over district-file rows; state SOI rows over county-file rows | +| Derived control | A control that no source publishes as one row | `derived_controls`: a state's households are the sum of its county estimates | +| Bound | The limits on the factor of a bridge, around one or around the median factor across the legs, and the action out of bound: `refuse` the pass or `unbind` the leg | The district selector: +0.25 and -0.20 around the median, `unbind` | +| Members | The members that each leg must hold. A member can stand for two geographies | `members`: the districts of the current plan; the counties of the ladder, with one combined cell | +| Not reconciled | A pair of levels that is not scaled, with a reason | `relations` (six `subset` pairs) and `local_routes` (three families with no higher control) | + +`bridges` (by id) and `partitions` are empty in the US file. -The two residual allocators only reproduce the old county arithmetic. Stage B -replaces them with one allocator. +### What the bound of the district bridge does -## The four mechanisms on the operator +The factor of a leg is its control over the sum of its rows. A factor mixes a +part that every state shares (coverage, aging) with a part of one state. The +median across states takes the shared part out. A state whose factor is more +than 1.25 times the median, or less than 0.8 times it, is one where the two +publications disagree about that state. The operator unbinds that leg: its +district rows leave the surface, and its Historic Table 2 state row stays. On +the pinned feed that is four legs. -Each one is declared under `mechanisms`. The tool function keeps its name and -signature and calls the adapter. +## The four passes -| Row of the issue | Mechanism | Tool function | The control | The rows | +| Row of the issue | Declared pass | Tool function | The control | The rows | |---|---|---|---|---| -| 5 | `state_congressional_district_soi` | `us_acs_local_cd_surface.state_cd_soi_surface` | The Historic Table 2 state row. For a concept that only the district file has: the district file's state row, multiplied by a sibling concept's ratio of the two files (`scaled_by_sibling_ratio`) | District file rows of the state | -| 8 | `state_county_population` | `us_acs_local_county_surface.with_county_populations` | The state total of the 2020 PUMA ladder | The ladder's county overlaps, summed by county | -| 6 | `state_county_soi` | `us_acs_local_county_surface.state_county_soi_surface` | The broad state SOI row that exists | County facts of the state. One declared combined cell covers a county with no IRS row | -| 7 | `county_state_acs_households` | `us_acs_local_county_surface.acs_household_surface` | The sum of the county estimates (`sum_of_lower_rows`). It is a new state target | The county estimates | +| 5 | `historic_table_2_state_vs_district_file` | `us_acs_local_cd_surface.state_cd_soi_surface` | The Historic Table 2 state row | District-file rows of the state | +| 6 | `state_soi_vs_county_file` | `us_acs_local_county_surface.state_county_soi_surface` | The broad state SOI row that exists | County facts of the state. One declared combined cell covers a county with no IRS row | +| 7 | `acs_households_state_is_the_county_sum` | `us_acs_local_county_surface.acs_household_surface` | The sum of the county estimates. It is a new state target | The county estimates | +| 8 | `ladder_population_state_vs_county` | `us_acs_local_county_surface.with_county_populations` | The state total of the 2020 PUMA ladder | The ladder's county overlaps, summed by county | + +Each tool function keeps its name and signature. Each one calls the adapter, +and the adapter calls one function, `run_pass`, which builds the rule from +the declaration and runs the row-level pass. -### What the adapter does before the operator runs +The four passes do not yet run on one joint surface. Until the feed re-pin +each pass has its own allocator, and the county rows are made at a later +stage than the district rows. -These checks are US rules. They run first, with the texts they always had, so -a refusal reads the same as before. +### What the operator checks + +- **Members.** A leg must hold exactly its declared members: the districts of + the current plan, or the counties of the ladder (less a county that a + combined cell covers). A declared leg with no row is refused in the same + way. +- **The bound** of the district bridge, as above. +- **Arithmetic.** A total that is not finite, a lower sum below `1e-9` of the + control, a control and rows of opposite sign, and rows that do not sum to + the control within `1e-9` are refused. + +### What the adapter checks + +These are US rules, with US texts. - **District SOI.** - - The district rows of a block must be exactly the current plan's districts - of the state (from the district crosswalk). A state with one district on - the source plan has no district rows. - - The district file's own state row must equal the sum of its district rows - within `1e-6` (`self_consistency`). - - A block whose ratio (control over the sum of its rows) is more than 1.25 - from its concept's median across states is dropped and recorded - (`factor_band`). The Historic Table 2 state row stays. - - The registers of defective, unparented and excluded district measures and - the six level bridges are in the declaration, with their reasons. -- **County population.** Each state needs a positive total and at least one - county with a positive population. Each county needs a state. -- **County SOI.** Each state block must hold every county of the ladder. - A county with no fact is refused unless it is a declared combined cell. - Return count and adjusted gross income must have a state parent in every - state. + - The registers of defective, unparented and excluded district measures + (`registers` in the declaration). + - A state with one district on the source plan has no district rows. + - The rows of a block and their parent must materialize in the same way. + - A concept takes its state parent from one source in every state. + - The surface is checked again after the pass: each district block must add + up to a bound state parent (`closure_rtol`). +- **County population.** The operator refuses a county with no state and a + state with no positive county population. +- **County SOI.** Each fact is an all-return fact of a tax year, finite and + not negative, with the unit of its parent. Return count and adjusted gross + income need a state parent in every state. A block needs a positive sum. + A combined cell joins two counties of one state. - **County households.** Every county of the ladder must carry an estimate, - and each state needs a positive sum. - -### What the operator refuses - -The operator applies its own refusals to every block: a total that is not -finite, a lower sum below `1e-9` of the control, a negative factor, and rows -that do not sum to the control within `1e-9`. On valid data the result is the -old result. Three cases that the old code computed are now refused: - -- a block whose rows sum to a value that is not zero but is below `1e-9` of - its control; -- a county SOI block under a negative state row; -- a control of `-0.0`. - -None occurs on the pinned feed. The pinned county facts hold return counts -and adjusted gross income only, and both are positive in every state. - -## Receipts - -- **The old receipts and metadata keys stay**, with the same bytes: the - `state_cd_*` and `state_county_*` keys, the `soi_surface` receipt in - `materialize_rss.json`, and `county_surface.json`. Other code reads these - keys (the loss weights, the pro-rata baselines, the reviewed limitations). -- **The operator's own receipt goes to a new file**, `target_nesting.json`, - which the materialize stage writes beside its other files. It holds one - entry for each pass: the mechanism, the allocator, the number of blocks and - the operator's receipt (each group and each leg with its control, its old - and new totals and its factor). No stage reads the file, and it is not in - the run identity. - -One receipt format for both countries is a Stage B step, because it changes -the bytes of the registry. - -## The inventory - -`inventory` in the declaration lists each US family that two levels measure, -with one route: - -| Route | Meaning | -|---|---| -| `mechanism` | The shared operator makes the rows (rows 5 to 8). | -| `compile_rule` | A pass of the compile makes them and stays where it is in Stage A (rows 1 to 4). | -| `same_source` | Both levels are sums of one source's cells. | -| `no_higher_control` | No row at a higher level measures the quantity. | -| `not_reconciled` | Two levels measure it and no rule ties them yet. The entry gives the reason and the issue. | -| `not_in_the_fit` | The rows are not compiled. | - -### Why rows 1 to 4 stay in the compile - -- **Rows 1 and 2 (capital gains, taxable interest).** Each row is multiplied - by one factor, `control / published national total`. The rows are not scaled - to sum to the control, and the control and the total are read from the - facts, not from rows of the registry. -- **Row 3 (state AGI bands).** It is a partition inside one area. The - partition is read from the facts, and only some of its bands bind. -- **Row 4 (the district file's own state row).** It is already shared code - with its rule as data (`reconcile_ledger_target_hierarchy`, declared in - `us/fiscal_target_references.json`). It sums with the builtin `sum`, formats - its factor with 15 significant digits and writes `hierarchy_*` keys. The - bytes of the `full` and `state_cd` surfaces depend on all three. - -### Families that do not nest today - -- The SOI families with two national rows (microcosm#1243). -- State age rows and state totals (microcosm#1528, #1526, #1531). -- The state rows of SNAP, Medicaid and CHIP, SSI and TANF against the national - row of each family. This is not checked yet. -- District age and household rows from ACS, which are not in the fit - (microcosm#1731). + each state needs a Census name and a positive sum. + +## What stays until the feed re-pin + +`until_the_feed_repin` in the declaration holds what goes when Microcosm +pins the feed after PolicyEngine/chronicle#451. + +- **The allocators.** The operator's own rule is + `row x control / numpy sum of the rows`. The US rows were made with + `math.fsum`, and the county rows with a residual rule. So a rule can name + an allocator (`CrossGrainRule.allocator`) that divides one control among + its rows. With no allocator the operator runs its own rule, with no float + operation added or removed; the UK declares none. The US declares one for + each pass, to keep the values bit for bit. At the re-pin they go, and + district and county values move in the last bits. + + | Allocator | Rule | Pass | + |---|---|---| + | `proportional_fsum` | `row x control / exactly rounded sum` | District SOI | + | `share_residual_to_largest` | `control x share`; the rounding residual of the shares, then of the products, goes to the largest row | County SOI, county households | + | `scale_residual_to_largest` | `control x row / total`; the rounding residual goes to the largest row | County population | + +- **The level bridges.** Six concepts are only in the district file. Their + state parent is the district file's own state row, multiplied by a sibling + concept's ratio of the two files. One function of the adapter makes these + parents, as before. The rows under them are tied by their own measurement + (`cross_grain_control` reads `exact_signature`), and a bridged state row + reads `level_bridge:`. After the re-pin Historic Table 2 holds the + six parents, and this function goes. +- **The compile rules of rows 1 to 4**, which stay in the compile: + - Rows 1 and 2 (capital gains, taxable interest): each row is multiplied by + one factor, `control / published national total`. + - Row 3 (state AGI bands): a partition inside one area. + - Row 4 (the district file's own state row): shared code with its rule as + data (`reconcile_ledger_target_hierarchy`). Its factor is 1 on the pinned + feed. +- **The known gaps.** The SOI families with two national rows + (microcosm#1243), and state age rows against state totals (microcosm#1528, + #1526, #1531). + +## Metadata keys and receipts + +A row that the operator reconciles keeps the operator's keys. A UK row and a +US row have the same ones. + +| Key | What it holds | The key before | +|---|---|---| +| `cross_grain_parent` | The name of the control row | `state_cd_parent_target_name`, `state_county_parent_target_name` | +| `cross_grain_value_before` | The row's value before the pass | `state_cd_cd_file_value`, `state_county_source_value` | +| `cross_grain_factor` | The factor of the row's leg | `state_cd_rebase_factor`, `state_cd_level_bridge_factor` | +| `cross_grain_control` | What reconciled the row: a bridge id, `exact_signature`, or `level_bridge:` | `state_cd_parent_basis`, `state_cd_level_bridge_sibling` | +| `cross_grain_members` | The counties that a combined cell stands for | `state_county_cell_members` | + +These old keys have no new one, because another place holds the value: the +parent's value and the sum of the rows (the parent row, and the operator's +receipt), the share of a county row (its value over its parent's), the +vintage rule and the basis of a combined cell (the declaration and the +receipt). + +The readers of the keys read the new ones: the loss weights +(`us_runtime/target_loss_weights.py`), the hold-outs and their pro-rata +baselines, and the county reports. The dated runs under `experiments/` read +registries of their own date and are not changed. + +Receipts: + +- **The surface receipts** (`soi_surface` in `materialize_rss.json`, and + `county_surface.json`) keep their counts, drops and summaries. The district + receipt names the bridge and its bound under `bridge`, with the legs it + unbound; it lists the level bridges it distrusts under + `level_bridge_out_of_band`, and the factors under `factor_by_measure`. The + county receipts name their pass under `bridge`. +- **The operator's receipt** goes to `target_nesting.json`, which the + materialize stage writes beside its other files. It holds one entry for + each pass: the pass id, the allocator, and the operator's receipt (each + group and each leg with its control, its old and new totals and its + factor). No stage reads the file, and it is not in the run identity. + +## What differs from the code before + +On valid data the rows and their values are the same. These things differ. + +1. **Keys and receipt fields**, as above. So the bytes of the `state_cd` + registry, roles and receipts moved, and their pins were measured again. + `test_us_target_nesting_district.py` holds each row of that surface on the + pinned feed to the bits of its old value. +2. **Refusal texts.** A refusal that the operator makes has the operator's + text: a leg that does not hold its members, a sum of zero under a control, + opposite signs, a county with no state. +3. **One check is gone:** that the district file's own state row is the sum + of its district rows within `1e-6`. Row 4 of the compile makes that sum + hold before this pass runs, and the district file's state row is not a + control of a concept that Historic Table 2 holds. +4. **One refusal is new:** a concept that takes its state parent from + Historic Table 2 in some states and from the district file in others. The + old code accepted that. It does not occur on the pinned feed. +5. **With the bound turned off** (only tests do that), a concept whose + Historic Table 2 level is zero in every state keeps district rows of + zero. The old code dropped them, because such a concept has no median + factor. +6. **Three cases that the oldest code computed are refused**, as since the + first move to the operator: a block whose rows sum to a value that is not + zero but is below `1e-9` of its control, a county SOI block under a + negative state row, and a control of `-0.0`. None occurs on the pinned + feed. ## The coverage test -`test_us_cross_grain_coverage.py` reads the inventory. It checks that each -entry is well formed, that rows 1 to 8 each have one entry, and that each -mechanism has one. With the pinned feed it also compiles the registry and -checks that each family at a level below `country` has an entry, that no -entry names rows that are gone, and that each compile rule's marker is on -rows of the declared family and levels. +`test_us_cross_grain_coverage.py` reads the declaration. With the pinned feed +it compiles the registry and checks that each family at a level below +`country` is covered by a selector, a derived control, a same-measurement +entry, a relation, a local route, a compile rule or a known gap; that no +declaration names rows that are gone; that each compile rule's marker is on +rows of its family and levels; and that no `subset` part is larger than its +whole beyond the declared `max_excess`. It is a test of the declaration. It refuses nothing in a build and it is not a release gate. ## The UK -The UK graph hashes `cross_grain.py`. The edit that added the allocator makes -the UK target nodes, and every node after them, compute again on the next UK -run. The outputs are the same: `test_cross_grain_allocator.py` compares the -operator with a copy of the file before the edit, bit for bit, on 400 seeded -surfaces. The UK graph does not hash `cross_grain_controls`. - -## Not in Stage A - -- Every target change (Stage B of microcosm#1760): one allocator for the - county rows, one receipt format, the ACS district rows, district and county - rows in one run, the families of microcosm#1243, row 4 on the operator. -- One function for the two matrix splits (`split_carriers_into`, - `split_state_rows`). They do no arithmetic on target values. -- A pin of the county rows on the pinned county facts file. The equivalence +The UK graph hashes `cross_grain.py`. The edits to that file make the UK +target nodes, and every node after them, compute again on the next UK run. +The outputs are the same: `test_cross_grain_allocator.py` compares the +operator with a copy of the file before any edit, bit for bit, on 400 seeded +surfaces, and it pins the list of definitions that the branch changed or +added. The UK declares none of the new options. The UK graph does not hash +`cross_grain_controls`. + +## Not done yet + +After PolicyEngine/chronicle#451 and the feed re-pin: + +- the ruled target changes: Historic Table 2 parents for the six concepts, + district capital gains under the Historic Table 2 state row, the `full` + surface nests its district rows, row 4 goes; +- the allocators go, and the four passes run on one joint surface; +- the derived control of the kind `scaled`, for the national controls of the + state rows (decision 2); +- the ACS district rows (decision 7) and the ladder under the state estimate + (decision 4), each of which can have its own PR; +- a pin of the county rows on the pinned county facts file. The equivalence tests of the county rows use synthetic blocks. From 625c93702ebf7eb517ad6159b9c8e175f4d03662 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:39:47 +0000 Subject: [PATCH 16/23] Record the ten rulings on the steps in the design page Ruled on 27 Nov 2026, after steps 1 and 2 of microcosm#1760 were written: no allocator after the re-pin; one parent source for a concept; the district file's self-consistency check stays out; the county rows are compared and pinned on the pinned county facts file now; the merge waits for a gap between UK releases; PR #1755 merges first; the rulings go on the issue after the text is approved; Medicaid stays a subset with a declared excess; the full surface and district capital gains nest in the Historic Table 2 state row at step 3; decisions 4 and 7 go in their own PRs. Docs only. Co-Authored-By: Claude Fable 5.2 --- docs/us-target-nesting-rule-design.md | 33 ++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/docs/us-target-nesting-rule-design.md b/docs/us-target-nesting-rule-design.md index e0e8886d1a..7651e61516 100644 --- a/docs/us-target-nesting-rule-design.md +++ b/docs/us-target-nesting-rule-design.md @@ -199,6 +199,37 @@ At the re-pin the bytes of the registry move anyway. **Recommended: yes to all three, in the re-pin PR.** +**Ruled later on 27 Nov 2026: no allocator.** After the re-pin the US divides +a control with the operator's own rule, as the UK does (section 5.2). + +### Rulings of 27 Nov 2026 on the steps + +Ten calls came up when steps 1 and 2 of section 5.5 were written. Each is +ruled, with the recommended option. + +1. **No allocator after the re-pin.** Decision 9 narrows from one allocator + to none. Before the allocators go, check that no reader needs rows that + sum exactly to their control. +2. **A concept takes its state parent from one source in every state.** A + concept with a Historic Table 2 parent in some states and a district-file + parent in others is refused. A concept that Historic Table 2 lacks in + every state keeps its district-file parent. +3. **The check that the district file agrees with itself stays out.** The + compile holds that sum before the pass, and after Chronicle PR #451 the + file has no state row to compare. +4. **The county rows are compared and pinned on the pinned county facts + file now**, not at step 3. +5. **Merge timing.** This branch does not merge while a UK release is between + its first build and its sign-off, because the UK graph re-keys. +6. **PR #1755 merges first.** This branch then takes its changes. +7. **The rulings are posted on microcosm#1760**, after the text is approved. +8. **Medicaid stays a `subset`** with an allowed excess of 1%, and Medicaid + with CHIP 0.1%. +9. **Two readings of the first ruling, for step 3.** The `full` surface nests + its district rows in the Historic Table 2 state row. District capital + gains nest in the Historic Table 2 state row. +10. **Decisions 4 and 7 go in their own PRs.** + ## 5. How the rulings are declared: one general model **The principle (ruled 27 Nov 2026).** Clean country-agnostic code comes @@ -232,7 +263,7 @@ one joint surface of all the bound rows, and it writes one receipt and the | What | Why it goes | |---|---| -| The allocator hook and the three allocators | Every country uses the operator's one rule: the row times the control over the sum of the rows. Stage A needs the allocators only to prove the move with the old bytes. They go at the re-pin. District and county values then move in the last bits. This narrows decision 9 from one allocator to none | +| The allocator hook and the three allocators | Every country uses the operator's one rule: the row times the control over the sum of the rows. Stage A needs the allocators only to prove the move with the old bytes. They go at the re-pin. District and county values then move in the last bits. This narrows decision 9 from one allocator to none (ruled 27 Nov 2026) | | The US keys `mechanisms` and `inventory` | The US file has the UK's keys only | | The US checks before the operator (factor band, completeness, self-consistency) | They are things 4 and 5 of the model | | The sibling-ratio bridge | After the re-pin, Historic Table 2 holds the six parents | From 6e76eaee6716b39d352fcdacc167559b9face14c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:49:46 +0000 Subject: [PATCH 17/23] Hold the county rows of the pinned county facts to the old code, and pin them Call 4 of the rulings of 27 Nov 2026 on microcosm#1760: the county rows are compared and pinned on the real inputs now, not at the feed re-pin. test_us_target_nesting_county.py gains two tests that read the pinned feed, the pinned PUMA ladder and the pinned county facts file (us/chronicle_county_facts.json, 922 MB, sha256 67b0998a...). They run when MICROCOSM_US_CHRONICLE_FACTS, MICROCOSM_US_PUMA_LADDER_ARTIFACT and the new MICROCOSM_US_CHRONICLE_COUNTY_FACTS name those files, and skip without them. - The three county passes give the rows of the code before the move to the shared operator, in the same order, with the same value bits, parent, value before and members: 3,143 county populations on 2020 counties and 3,144 on the 2023 county-equivalents, 6,286 county SOI rows (two measures for 3,143 cells; one cell stands for Kalawao and Maui), and 51 state and 3,144 county household rows. - The bytes of those rows and of their receipts are pinned. Measured on the same inputs, for decision 6: the factor of each of the 51 county SOI legs is within 0.998 to 1.052 of the median for adjusted gross income (median 1.1207) and within 0.9997 to 1.0005 for the return count (median 1.0000). No leg is outside the band of 0.8 to 1.25 that the district bridge declares. The pages record it. Whether the county bridge declares the band is still to rule. Co-Authored-By: Claude Fable 5.2 --- docs/us-target-nesting-rule-design.md | 12 +- docs/us-target-nesting.md | 38 +++- .../us/test_us_target_nesting_county.py | 168 +++++++++++++++++- 3 files changed, 207 insertions(+), 11 deletions(-) diff --git a/docs/us-target-nesting-rule-design.md b/docs/us-target-nesting-rule-design.md index 7651e61516..4efa638279 100644 --- a/docs/us-target-nesting-rule-design.md +++ b/docs/us-target-nesting-rule-design.md @@ -158,7 +158,12 @@ which age groups is the decision of PR #1531, not of this rule. source declares none (ladder population, county households). **Recommended: yes.** For county SOI, which has no bound today: add the band as a report first, and decide to enforce it after the factors are - measured on the county facts. + measured on the county facts. **Measured, 27 Nov 2026:** on the pinned + county facts, the factor of each of the 51 legs is within 0.998 to 1.052 + of the median for adjusted gross income (median 1.1207), and within 0.9997 + to 1.0005 for the return count (median 1.0000). No leg is outside the band + of 0.8 to 1.25. Whether the county bridge declares the band is still to + rule. - **Members.** A leg holds exactly its declared members: the district plan of the crosswalk, the counties of the ladder. A declared combined cell covers a county with no IRS row. An area with one district does not bind @@ -218,7 +223,9 @@ ruled, with the recommended option. compile holds that sum before the pass, and after Chronicle PR #451 the file has no state row to compare. 4. **The county rows are compared and pinned on the pinned county facts - file now**, not at step 3. + file now**, not at step 3. Done on 27 Nov 2026: the three county passes + give the old rows with the same value bits, and + `test_us_target_nesting_county.py` pins them. 5. **Merge timing.** This branch does not merge while a UK release is between its first build and its sign-off, because the UK graph re-keys. 6. **PR #1755 merges first.** This branch then takes its changes. @@ -404,6 +411,5 @@ Two points to settle when the code is written: ## 8. Not measured -- The county factors. The pinned county facts file is not on this machine. - Anything on a feed after Chronicle PR #451. - The concept match of each of the 14 families of microcosm#1243. diff --git a/docs/us-target-nesting.md b/docs/us-target-nesting.md index 4a0d10cfc1..32c16fd7ac 100644 --- a/docs/us-target-nesting.md +++ b/docs/us-target-nesting.md @@ -220,6 +220,40 @@ On valid data the rows and their values are the same. These things differ. negative state row, and a control of `-0.0`. None occurs on the pinned feed. +## The county rows on the pinned inputs + +`test_us_target_nesting_county.py` reads the real inputs when three +environment variables name them: `MICROCOSM_US_CHRONICLE_FACTS` (the pinned +feed), `MICROCOSM_US_PUMA_LADDER_ARTIFACT` (the pinned PUMA ladder) and +`MICROCOSM_US_CHRONICLE_COUNTY_FACTS` (the pinned county facts file of +`us/chronicle_county_facts.json`, 922 MB). Without them the two tests skip. + +On those inputs the three county passes give the rows of the code before, +with the same value bits: + +| Pass | Rows | +|---|---| +| County population, 2020 counties | 3,143 | +| County population, 2023 county-equivalents | 3,144 | +| County SOI (return count, adjusted gross income) | 6,286: two for each of 3,143 cells. One cell stands for Kalawao and Maui | +| County households | 51 state rows and 3,144 county rows | + +The same test file pins the bytes of those rows. + +The county SOI bridge declares no bound. Its factors (the state row over the +sum of the county facts) were measured on those inputs: + +| Measure | Legs | Median factor | Lowest and highest, as a ratio to the median | Legs outside 0.8 to 1.25 | +|---|---:|---:|---|---:| +| `adjusted_gross_income` | 51 | 1.1207 | 0.998 to 1.052 | 0 | +| `return_count` | 51 | 1.0000 | 0.9997 to 1.0005 | 0 | + +The median of 1.12 for adjusted gross income is a gap that every state has. +It is consistent with the aging of an amount from tax year 2022 to the target +year; a count is not aged. The states farthest from the median are Montana +(1.052) and Wyoming (1.038). So the band of the district bridge would unbind +no county leg today. + ## The coverage test `test_us_cross_grain_coverage.py` reads the declaration. With the pinned feed @@ -254,6 +288,4 @@ After PolicyEngine/chronicle#451 and the feed re-pin: - the derived control of the kind `scaled`, for the national controls of the state rows (decision 2); - the ACS district rows (decision 7) and the ladder under the state estimate - (decision 4), each of which can have its own PR; -- a pin of the county rows on the pinned county facts file. The equivalence - tests of the county rows use synthetic blocks. + (decision 4), each in its own PR. diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_target_nesting_county.py b/packages/microcosm-build/tests/engine_free/us/test_us_target_nesting_county.py index 31a635723c..c920805049 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_target_nesting_county.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_target_nesting_county.py @@ -14,17 +14,24 @@ text when the adapter refuses, and with the operator's text when the operator does. -The blocks are synthetic. No test here reads the pinned county facts file -(``us/chronicle_county_facts.json``), which is not a test input on every -machine; a pin of the county rows on that file is a separate step. +The seeded blocks are synthetic. Two tests at the end read the real inputs: +the pinned feed, the pinned PUMA ladder and the pinned county facts file +(``us/chronicle_county_facts.json``). They hold the county rows of those +inputs to the old code, and they pin the bytes of the rows. They run only +when ``MICROCOSM_US_CHRONICLE_FACTS``, ``MICROCOSM_US_PUMA_LADDER_ARTIFACT`` +and ``MICROCOSM_US_CHRONICLE_COUNTY_FACTS`` name those files, because the +county facts file (922 MB) is not a test input on every machine. """ from __future__ import annotations import dataclasses +import hashlib import importlib.util import json +import os import struct +from pathlib import Path from types import SimpleNamespace import numpy as np @@ -60,7 +67,7 @@ @pytest.fixture(scope="module") -def county(): +def local_tool(): path = _TEST_PATHS.repository / "tools" / "build_us_acs_local_release.py" spec = importlib.util.spec_from_file_location( "build_us_acs_local_release_nesting_county", path @@ -68,7 +75,12 @@ def county(): module = importlib.util.module_from_spec(spec) assert spec.loader is not None spec.loader.exec_module(module) - return module.county_surface + return module + + +@pytest.fixture(scope="module") +def county(local_tool): + return local_tool.county_surface def _bits(values) -> bytes: @@ -652,3 +664,149 @@ def first_accepted(inputs, function): ) # The surfaces' receipts do not hold the operator's receipt. assert "groups" not in soi.receipt and "groups" not in acs.receipt + + +# --------------------------------------------------------------------------- +# The real inputs: the pinned feed, ladder and county facts +# --------------------------------------------------------------------------- + +#: The household county columns: 2020 counties, and the 2023 county-equivalents +#: of the county facts (Connecticut's planning regions), which a full run uses. +_COUNTY_COLUMNS = ("county_fips", "county_fips_2023") +_COUNTY_FACTS_ENV = "MICROCOSM_US_CHRONICLE_COUNTY_FACTS" + +#: The county rows on the pinned inputs: their counts, and the sha256 of the +#: rows as a registry file writes them (keys in insertion order), of the +#: populations (county code and the bits of the value) and of the receipts. +#: Measured on the code of microcosm#1760 after the county rows took the +#: operator's metadata keys. +#: ``test_the_pinned_county_rows_are_the_old_rows`` holds the same rows to +#: the code before that: the same values, bit for bit. +PINNED_COUNTY_ROWS: dict[str, object] = { + "population_county_fips": { + "counties": 3143, + "sha256": "5a93db95e287a549ce4fb01126475382765e55f70a8a6e47670b63afb342c2e1", + }, + "population_county_fips_2023": { + "counties": 3144, + "sha256": "636f344557d3b06b8c3363d10683df251aea099bfa7368346f3c4af294e5a2f9", + }, + "soi": { + "rows": 6286, + "rows_sha256": "dce48ac26c326d3c11c01908a7a9ad3aa6fc43b88acf87037fc85271b9ddaf46", + "receipt_sha256": "a77f6326b9921878e10aac4e39af65bc4c607f763bc4caf6023aceb152083cc5", + }, + "households": { + "rows": 3195, + "rows_sha256": "ad642af8198354d8508e6d581a6028fc89c8beac6d9339021cdce9fee2df3430", + "receipt_sha256": "c06dc6f2a45724d3a7160cdd71c1b8f07be7c6bd5cd4d75351b3cc6edf3406bd", + }, +} + + +def _sha256(text: str) -> str: + return hashlib.sha256(text.encode()).hexdigest() + + +def _rows_sha256(specs) -> str: + return _sha256(json.dumps([spec.to_dict() for spec in specs], indent=1)) + + +def _population_sha256(cells) -> str: + return _sha256( + json.dumps([[int(code), float(value).hex()] for code, value in cells.items()]) + ) + + +@pytest.fixture(scope="module") +def pinned_county(local_tool): + """The three county passes on the pinned inputs, by the new and the old code.""" + + paths = {} + for name, what in ( + ("MICROCOSM_US_CHRONICLE_FACTS", "the pinned 41b2fb2 feed"), + ("MICROCOSM_US_PUMA_LADDER_ARTIFACT", "the pinned PUMA ladder"), + (_COUNTY_FACTS_ENV, "the pinned county facts file"), + ): + value = os.environ.get(name, "") + if not value or not Path(value).exists(): + pytest.skip(f"set {name} to {what}") + paths[name] = Path(value) + from microcosm.build.us_runtime.county_facts import load_us_county_facts + from microcosm.build.us_runtime.puma_ladder import load_us_puma_ladder + + county = local_tool.county_surface + ladder_path = paths["MICROCOSM_US_PUMA_LADDER_ARTIFACT"] + ladder = load_us_puma_ladder(ladder_path) + states = local_tool.ladder_population(ladder_path, ["state"]) + populations = { + column: tuple( + module.with_county_populations( + ladder, states, ["state", "county"], county_column=column + ) + for module in (county, reference) + ) + for column in _COUNTY_COLUMNS + } + state_specs = local_tool.state_admin_surface( + str(paths["MICROCOSM_US_CHRONICLE_FACTS"]), + ["snap", "medicaid", "soi"], + soi_mode=county.SOI_MODE, + ).registry.specs + # The loader refuses a file that is not the pinned one. + facts = load_us_county_facts(paths[_COUNTY_FACTS_ENV]).rows + counties = populations["county_fips_2023"][0]["county"] + return SimpleNamespace( + populations=populations, + soi=tuple( + module.state_county_soi_surface(state_specs, facts, counties) + for module in (county, reference) + ), + acs=tuple( + module.acs_household_surface(facts, counties) + for module in (county, reference) + ), + ) + + +def test_the_pinned_county_rows_are_the_old_rows(pinned_county) -> None: + """On the real inputs: the old rows and value bits, under the new keys.""" + + for column in _COUNTY_COLUMNS: + new, old = pinned_county.populations[column] + assert _population_image(new) == _population_image(old), column + _assert_same_surface(*pinned_county.soi, declarations.COUNTY_SOI, 0) + _assert_same_surface(*pinned_county.acs, declarations.COUNTY_ACS_HOUSEHOLDS, 0) + # Kalawao has no IRS row: one Maui cell stands for both counties in each + # of the two measures, so the SOI rows are two fewer than two per county. + soi, acs = pinned_county.soi[0], pinned_county.acs[0] + combined = [spec for spec in soi.specs if MEMBERS_KEY in spec.metadata] + assert {spec.metadata[MEMBERS_KEY] for spec in combined} == {"15005,15009"} + assert len(soi.specs) == 2 * 3_144 - len(combined) == 6_286 + assert len(acs.specs) == 51 + 3_144 + + +def test_the_pinned_county_rows_have_their_pinned_bytes(pinned_county) -> None: + soi, acs = pinned_county.soi[0], pinned_county.acs[0] + measured = { + **{ + f"population_{column}": { + "counties": len(pinned_county.populations[column][0]["county"]), + "sha256": _population_sha256( + pinned_county.populations[column][0]["county"] + ), + } + for column in _COUNTY_COLUMNS + }, + "soi": { + "rows": len(soi.specs), + "rows_sha256": _rows_sha256(soi.specs), + "receipt_sha256": _sha256(json.dumps(soi.receipt, indent=1)), + }, + "households": { + "rows": len(acs.specs), + "rows_sha256": _rows_sha256(acs.specs), + "receipt_sha256": _sha256(json.dumps(acs.receipt, indent=1)), + }, + } + assert measured == PINNED_COUNTY_ROWS From fa297a018a5e508839b1c8859c7ca7c69e9f26dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:34:38 +0000 Subject: [PATCH 18/23] Declare the district bridge's bound on the county SOI bridge Ruled on 27 Nov 2026 (microcosm#1760, decision 6), after the county factors were measured on the pinned county facts: the county bridge declares the band of the district bridge. No county value changes. - us/cross_grain_declarations.json: the selector state_soi_vs_county_file takes max_factor_shift 0.25, min_factor_shift -0.2, shift_around median and out_of_bound unbind. - us_runtime/target_nesting.py: the county pass handles a leg that the operator unbinds. Its county rows of that measure leave the surface, the receipt names the leg under bridge.unbound, and its counties do not count as missing. One helper gives both passes their selector, and one gives each surface receipt the same bridge entry (the bridge, its bound, the legs it unbound), the households receipt too. - tools/us_acs_local_county_surface.py: state_county_soi_surface takes factor_band, as state_cd_soi_surface does. The default is the declared band, and an infinite band turns the bound off (tests with random factors use that). On the pinned county facts the factor of each of the 51 legs is within 0.998 to 1.052 of the median for adjusted gross income and 0.9997 to 1.0005 for the return count, so no leg is unbound: the 6,286 county SOI rows keep their pinned bytes. The two receipt pins of the county rows move, because the receipt names its bridge in the new shape. The state_cd pins do not move. Tests: a state that is off the median loses its county rows of that measure and the receipt names it; a state off in both measures is not refused; the old-against-new comparison on random blocks runs with the bound off, because the old code had none. Co-Authored-By: Claude Fable 5.2 --- ...s-target-nesting-on-cross-grain.changed.md | 2 +- docs/us-acs-local-county-rung.md | 7 ++ docs/us-target-nesting-rule-design.md | 10 +- docs/us-target-nesting.md | 37 +++--- .../build/us/cross_grain_declarations.json | 6 +- .../us_runtime/cross_grain_declarations.py | 13 +- .../build/us_runtime/target_nesting.py | 114 +++++++++++++----- .../us/test_us_acs_local_county_properties.py | 5 +- .../us/test_us_cross_grain_declarations.py | 9 +- .../us/test_us_target_nesting_county.py | 95 ++++++++++++++- tools/us_acs_local_county_surface.py | 11 ++ 11 files changed, 250 insertions(+), 59 deletions(-) diff --git a/changelog.d/1760-us-target-nesting-on-cross-grain.changed.md b/changelog.d/1760-us-target-nesting-on-cross-grain.changed.md index 8ac65eeaf3..02c6ed837d 100644 --- a/changelog.d/1760-us-target-nesting-on-cross-grain.changed.md +++ b/changelog.d/1760-us-target-nesting-on-cross-grain.changed.md @@ -1 +1 @@ -The US nests its local target rows on the shared cross-grain operator that the UK uses (`microcosm.build.cross_grain`), with no target change (microcosm#1760). The operator gains general options that the UK does not declare, so the UK outputs are the same; the UK graph hashes the file, so UK target nodes and the nodes after them compute again on the next UK run. The options: a bound of a bridge measured from the median factor, one-sided, that can unbind a leg; the declared members of a leg; bridge selectors; an optional `allocator`; and `cross_grain_metadata`, the keys of a reconciled row. The shared `microcosm.build.cross_grain_controls` holds the row-level pass (`reconcile_rows`) and the allocators that keep the US values bit for bit until the feed re-pin. `us/cross_grain_declarations.json` declares the US choices under the UK's key names (bridge selectors, a derived control, relations, local routes, members). `state_cd_soi_surface`, `with_county_populations`, `state_county_soi_surface` and `acs_household_surface` keep their names and signatures, and each target value on the pinned feed and ladder is the value it was. **The metadata keys change**: district and county rows carry `cross_grain_parent`, `cross_grain_value_before`, `cross_grain_factor`, `cross_grain_control` and `cross_grain_members` in place of the `state_cd_*` and `state_county_*` keys, and the district receipt takes the fields `bridge`, `level_bridge_out_of_band` and `factor_by_measure`. So the bytes of the `state_cd` registry, roles and receipts move. A refusal that the operator makes has the operator's text; the check that the district file agrees with itself is gone (the compile holds that sum); a concept with two parent sources is refused. The materialize stage also writes the operator's receipts to `target_nesting.json`. See `docs/us-target-nesting.md`. +The US nests its local target rows on the shared cross-grain operator that the UK uses (`microcosm.build.cross_grain`), with no target change (microcosm#1760). The operator gains general options that the UK does not declare, so the UK outputs are the same; the UK graph hashes the file, so UK target nodes and the nodes after them compute again on the next UK run. The options: a bound of a bridge measured from the median factor, one-sided, that can unbind a leg; the declared members of a leg; bridge selectors; an optional `allocator`; and `cross_grain_metadata`, the keys of a reconciled row. The shared `microcosm.build.cross_grain_controls` holds the row-level pass (`reconcile_rows`) and the allocators that keep the US values bit for bit until the feed re-pin. `us/cross_grain_declarations.json` declares the US choices under the UK's key names (bridge selectors, a derived control, relations, local routes, members). `state_cd_soi_surface`, `with_county_populations`, `state_county_soi_surface` and `acs_household_surface` keep their names and signatures, and each target value on the pinned feed and ladder is the value it was. **The metadata keys change**: district and county rows carry `cross_grain_parent`, `cross_grain_value_before`, `cross_grain_factor`, `cross_grain_control` and `cross_grain_members` in place of the `state_cd_*` and `state_county_*` keys, and the district receipt takes the fields `bridge`, `level_bridge_out_of_band` and `factor_by_measure`. So the bytes of the `state_cd` registry, roles and receipts move. A refusal that the operator makes has the operator's text; the check that the district file agrees with itself is gone (the compile holds that sum); a concept with two parent sources is refused. The county SOI bridge declares the bound of the district bridge (1.25 around the median factor across states, unbind): a state outside it loses its county rows of that measure and the receipt names it; no state is outside it on the pinned county facts, so no county value changes. The materialize stage also writes the operator's receipts to `target_nesting.json`. See `docs/us-target-nesting.md`. diff --git a/docs/us-acs-local-county-rung.md b/docs/us-acs-local-county-rung.md index ebe8ee7643..1a468be3b6 100644 --- a/docs/us-acs-local-county-rung.md +++ b/docs/us-acs-local-county-rung.md @@ -89,6 +89,13 @@ to USD in the county facts file; the county rung does not apply another scale fa duplicate facts, negative or nonfinite shares, zero share denominators, incomplete county inventories, incompatible boundaries, and missing or ambiguous state parents. No unsupported concept receives a new engine measure. +A state whose factor (its state target over the sum of its county source +values) is more than 1.25 times its measure's median across states, or less +than 0.8 times it, loses its county rows of that measure: the receipt names +it under `bridge.unbound`, and its state target stays. This is the declared +bound of the county bridge in `us/cross_grain_declarations.json`, the same as +the district bridge's (see [US target nesting](us-target-nesting.md)). On the +pinned county facts no state is outside it. Full runs also require the ladder to declare all 3,144 county-equivalents; matching omissions from both ladder and SOI cannot pass as a complete release. An ACS county family can later provide child targets with the same state-parent diff --git a/docs/us-target-nesting-rule-design.md b/docs/us-target-nesting-rule-design.md index 4efa638279..6f652151db 100644 --- a/docs/us-target-nesting-rule-design.md +++ b/docs/us-target-nesting-rule-design.md @@ -162,8 +162,8 @@ which age groups is the decision of PR #1531, not of this rule. county facts, the factor of each of the 51 legs is within 0.998 to 1.052 of the median for adjusted gross income (median 1.1207), and within 0.9997 to 1.0005 for the return count (median 1.0000). No leg is outside the band - of 0.8 to 1.25. Whether the county bridge declares the band is still to - rule. + of 0.8 to 1.25. **Ruled, 27 Nov 2026: the county bridge declares the + band**, as the district bridge does. It unbinds no leg on those inputs. - **Members.** A leg holds exactly its declared members: the district plan of the crosswalk, the counties of the ladder. A declared combined cell covers a county with no IRS row. An area with one district does not bind @@ -237,6 +237,12 @@ ruled, with the recommended option. gains nest in the Historic Table 2 state row. 10. **Decisions 4 and 7 go in their own PRs.** +One more call came from the county factors that call 4 measured: + +11. **The county SOI bridge declares the band of the district bridge** + (+0.25 and -0.20 around the median, `unbind`). No leg is outside it on + the pinned county facts, so no county value changes. + ## 5. How the rulings are declared: one general model **The principle (ruled 27 Nov 2026).** Clean country-agnostic code comes diff --git a/docs/us-target-nesting.md b/docs/us-target-nesting.md index 32c16fd7ac..cec5f03743 100644 --- a/docs/us-target-nesting.md +++ b/docs/us-target-nesting.md @@ -51,21 +51,24 @@ shared code runs it. | Measurement | Two targets with the same measurement at two levels are one quantity. Nothing else is declared | `same_measurement`: the ladder population of a state and of its counties | | Bridge | Two targets with different measurements that measure one quantity. A bridge names its sides by id, or by a selector that makes one bridge for each pair of targets | `bridge_selectors`: Historic Table 2 state rows over district-file rows; state SOI rows over county-file rows | | Derived control | A control that no source publishes as one row | `derived_controls`: a state's households are the sum of its county estimates | -| Bound | The limits on the factor of a bridge, around one or around the median factor across the legs, and the action out of bound: `refuse` the pass or `unbind` the leg | The district selector: +0.25 and -0.20 around the median, `unbind` | +| Bound | The limits on the factor of a bridge, around one or around the median factor across the legs, and the action out of bound: `refuse` the pass or `unbind` the leg | Both selectors: +0.25 and -0.20 around the median, `unbind` | | Members | The members that each leg must hold. A member can stand for two geographies | `members`: the districts of the current plan; the counties of the ladder, with one combined cell | | Not reconciled | A pair of levels that is not scaled, with a reason | `relations` (six `subset` pairs) and `local_routes` (three families with no higher control) | `bridges` (by id) and `partitions` are empty in the US file. -### What the bound of the district bridge does +### What the bound of a bridge does + +The district bridge and the county bridge declare the same bound. The factor of a leg is its control over the sum of its rows. A factor mixes a part that every state shares (coverage, aging) with a part of one state. The median across states takes the shared part out. A state whose factor is more than 1.25 times the median, or less than 0.8 times it, is one where the two publications disagree about that state. The operator unbinds that leg: its -district rows leave the surface, and its Historic Table 2 state row stays. On -the pinned feed that is four legs. +district or county rows leave the surface, the receipt names the leg, and its +state row stays. On the pinned inputs that is four district legs and no +county leg. ## The four passes @@ -112,7 +115,8 @@ These are US rules, with US texts. - **County SOI.** Each fact is an all-return fact of a tax year, finite and not negative, with the unit of its parent. Return count and adjusted gross income need a state parent in every state. A block needs a positive sum. - A combined cell joins two counties of one state. + A combined cell joins two counties of one state. A county that no row + covers is refused, unless its leg is unbound and the receipt names it. - **County households.** Every county of the ladder must carry an estimate, each state needs a Census name and a positive sum. @@ -181,11 +185,11 @@ registries of their own date and are not changed. Receipts: - **The surface receipts** (`soi_surface` in `materialize_rss.json`, and - `county_surface.json`) keep their counts, drops and summaries. The district - receipt names the bridge and its bound under `bridge`, with the legs it - unbound; it lists the level bridges it distrusts under - `level_bridge_out_of_band`, and the factors under `factor_by_measure`. The - county receipts name their pass under `bridge`. + `county_surface.json`) keep their counts, drops and summaries. Each one + names its bridge under `bridge`, with the bound and the legs that the + bound unbound. The district receipt also lists the level bridges it + distrusts under `level_bridge_out_of_band`, and the factors under + `factor_by_measure`. - **The operator's receipt** goes to `target_nesting.json`, which the materialize stage writes beside its other files. It holds one entry for each pass: the pass id, the allocator, and the operator's receipt (each @@ -214,7 +218,9 @@ On valid data the rows and their values are the same. These things differ. Historic Table 2 level is zero in every state keeps district rows of zero. The old code dropped them, because such a concept has no median factor. -6. **Three cases that the oldest code computed are refused**, as since the +6. **One rule is new for the county SOI rows:** the bound of the county + bridge. The code before had none. It unbinds no leg on the pinned inputs. +7. **Three cases that the oldest code computed are refused**, as since the first move to the operator: a block whose rows sum to a value that is not zero but is below `1e-9` of its control, a county SOI block under a negative state row, and a control of `-0.0`. None occurs on the pinned @@ -240,8 +246,9 @@ with the same value bits: The same test file pins the bytes of those rows. -The county SOI bridge declares no bound. Its factors (the state row over the -sum of the county facts) were measured on those inputs: +The county SOI bridge declares the bound of the district bridge (ruled 27 Nov +2026). Its factors (the state row over the sum of the county facts) were +measured on those inputs: | Measure | Legs | Median factor | Lowest and highest, as a ratio to the median | Legs outside 0.8 to 1.25 | |---|---:|---:|---|---:| @@ -251,8 +258,8 @@ sum of the county facts) were measured on those inputs: The median of 1.12 for adjusted gross income is a gap that every state has. It is consistent with the aging of an amount from tax year 2022 to the target year; a count is not aged. The states farthest from the median are Montana -(1.052) and Wyoming (1.038). So the band of the district bridge would unbind -no county leg today. +(1.052) and Wyoming (1.038). So the bound unbinds no county leg on these +inputs, and it changes no county value. ## The coverage test diff --git a/packages/microcosm-build/src/microcosm/build/us/cross_grain_declarations.json b/packages/microcosm-build/src/microcosm/build/us/cross_grain_declarations.json index ebf95db8c6..5ccfae082a 100644 --- a/packages/microcosm-build/src/microcosm/build/us/cross_grain_declarations.json +++ b/packages/microcosm-build/src/microcosm/build/us/cross_grain_declarations.json @@ -57,11 +57,15 @@ "source_measure_id", "source_period" ], + "max_factor_shift": 0.25, + "min_factor_shift": -0.2, + "shift_around": "median", + "out_of_bound": "unbind", "required_measures": [ "return_count", "adjusted_gross_income" ], - "reason": "The broad state row that exists on the state surface (all returns, no AGI class, no filing status) is the control. County SOI facts supply shares, never a second state level. Return count and adjusted gross income must have a state row in every state." + "reason": "The broad state row that exists on the state surface (all returns, no AGI class, no filing status) is the control. County SOI facts supply shares, never a second state level. Return count and adjusted gross income must have a state row in every state. The bound is the district bridge's: the state row and the county file differ by a gap that every state shares (the aging of an amount), which the median across states takes out, and a state whose factor is outside the bound around that median is one where the two publications disagree, so its county rows are unbound and its state row stays. On the pinned county facts the factors are within 0.998 to 1.052 of the median (adjusted gross income) and 0.9997 to 1.0005 (return count), so no leg is unbound (microcosm#1760, decision 6, ruled 27 Nov 2026)." } ], "derived_controls": [ diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/cross_grain_declarations.py b/packages/microcosm-build/src/microcosm/build/us_runtime/cross_grain_declarations.py index 1ddef62d5c..41e0e8d9b0 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/cross_grain_declarations.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/cross_grain_declarations.py @@ -313,10 +313,18 @@ class CountySoiNesting: """The declared choices of the state-to-county SOI pass.""" required_measures: tuple[str, ...] + max_factor_shift: float + min_factor_shift: float #: Absent county -> host county, as five-digit integer codes. combined_cells: Mapping[int, int] combined_cell_basis: str + @property + def factor_band(self) -> float: + """The bound as a ratio to the median: one plus the highest shift.""" + + return 1.0 + self.max_factor_shift + @functools.lru_cache(maxsize=1) def us_county_soi_nesting() -> CountySoiNesting: @@ -329,10 +337,13 @@ def us_county_soi_nesting() -> CountySoiNesting: bases = {str(cell["basis"]) for cell in combined} if len(bases) > 1: raise ValueError("US combined county cells of one pass must share a basis.") + selector = _selector_entry(COUNTY_SOI) return CountySoiNesting( required_measures=tuple( - str(measure) for measure in _selector_entry(COUNTY_SOI)["required_measures"] + str(measure) for measure in selector["required_measures"] ), + max_factor_shift=selector["max_factor_shift"], + min_factor_shift=selector["min_factor_shift"], combined_cells={int(cell["absent"]): int(cell["host"]) for cell in combined}, combined_cell_basis=next(iter(bases), ""), ) diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/target_nesting.py b/packages/microcosm-build/src/microcosm/build/us_runtime/target_nesting.py index 43bf07dadb..05075382cf 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/target_nesting.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/target_nesting.py @@ -42,6 +42,7 @@ MEMBERS_KEY, PARENT_KEY, CrossGrainBridge, + CrossGrainBridgeSelector, CrossGrainRule, cross_grain_metadata, expand_bridge_selectors, @@ -144,6 +145,43 @@ def run_pass( return outcomes, receipt +def bounded_selector(pass_id: str, factor_band: float) -> CrossGrainBridgeSelector: + """The declared selector of a pass, with the bound that a caller asks for. + + ``factor_band`` is the bound as a ratio to the median factor: a leg may + sit between ``1 / factor_band`` and ``factor_band`` of it. The declared + band gives the declared selector. An infinite band turns the bound off. + """ + + if math.isinf(factor_band): + return us_bridge_selector(pass_id, bounded=False) + declared = us_bridge_selector(pass_id) + if factor_band == 1.0 + declared.max_factor_shift: + return declared + return replace( + declared, + max_factor_shift=factor_band - 1.0, + min_factor_shift=1.0 / factor_band - 1.0, + ) + + +def bridge_receipt( + bridge_id: str, + bridge: CrossGrainBridge | CrossGrainBridgeSelector, + unbound: Sequence[Mapping[str, Any]] = (), +) -> dict[str, Any]: + """What a surface receipt says of its bridge: the bound, and the legs it unbound.""" + + return { + "bridge_id": bridge_id, + "max_factor_shift": bridge.max_factor_shift, + "min_factor_shift": bridge.min_factor_shift, + "shift_around": bridge.shift_around, + "out_of_bound": bridge.out_of_bound, + "unbound": sorted(unbound, key=lambda row: (row["concept"], row["state_fips"])), + } + + # --------------------------------------------------------------------------- # The operator's receipts # --------------------------------------------------------------------------- @@ -461,13 +499,7 @@ def drop(spec, reason: str) -> None: for district in target_districts.get(state, ()) ) - selector = us_bridge_selector(DISTRICT_SOI, bounded=not math.isinf(factor_band)) - if not math.isinf(factor_band) and factor_band != nesting.factor_band: - selector = replace( - selector, - max_factor_shift=factor_band - 1.0, - min_factor_shift=1.0 / factor_band - 1.0, - ) + selector = bounded_selector(DISTRICT_SOI, factor_band) bridges, _unpaired = expand_bridge_selectors([selector], targets) outcomes, operator_receipt = run_pass( DISTRICT_SOI, @@ -575,16 +607,7 @@ def drop(spec, reason: str) -> None: "unparented_cd_measures": dict(unparented), "excluded_cd_states": dict(excluded_states), "at_large_on_source_plan": at_large_source_states, - "bridge": { - "bridge_id": DISTRICT_SOI, - "max_factor_shift": selector.max_factor_shift, - "min_factor_shift": selector.min_factor_shift, - "shift_around": selector.shift_around, - "out_of_bound": selector.out_of_bound, - "unbound": sorted( - unbound, key=lambda row: (row["concept"], row["state_fips"]) - ), - }, + "bridge": bridge_receipt(DISTRICT_SOI, selector, unbound), "level_bridges": dict(level_bridges), "level_bridge_factor_by_measure": { measure: _factor_summary(values) @@ -1043,6 +1066,7 @@ def county_soi_surface( county_populations: Mapping[int, float], *, combined_cells: Mapping[int, int], + factor_band: float, soi_mode: str, ) -> NestedSurface: """Divide the broad state SOI rows among the counties of the county facts. @@ -1054,6 +1078,12 @@ def county_soi_surface( county absent from a block is refused unless ``combined_cells`` declares it with its host present: then the host's row stands for both counties, and ``cross_grain_members`` lists them. + + ``factor_band`` is the bound of the bridge, as a ratio to the median + factor of a measure across states. A state whose factor is outside it is + one where the state row and the county file disagree: the operator + unbinds that leg, its county rows leave the surface, the receipt names + it, and its state row stays. """ nesting = us_county_soi_nesting() @@ -1152,7 +1182,6 @@ def county_soi_surface( 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}") codes = sorted(block) if codes and controls.sum_of_lower_rows(block[code][0] for code in codes) <= 0: raise ValueError( @@ -1178,7 +1207,9 @@ def county_soi_surface( targets[lower_id] = {"source": COUNTY_FILE, "grain": county_level, **attributes} state_area = geography_id(state_level, f"{state:02d}") bound.append(higher_id) - checked.append((key, parent, counties, block, members, codes, len(rows))) + checked.append( + (key, parent, counties, block, members, merged, codes, len(rows)) + ) rows.append(SurfaceRow(state_level, state_area, higher_id, float(parent.value))) for code in codes: area = geography_id(county_level, f"{code:05d}") @@ -1189,9 +1220,8 @@ def county_soi_surface( for code in counties - merged.keys() ) - bridges, _unpaired = expand_bridge_selectors( - [us_bridge_selector(COUNTY_SOI)], targets - ) + selector = bounded_selector(COUNTY_SOI, factor_band) + bridges, _unpaired = expand_bridge_selectors([selector], targets) outcomes, operator_receipt = run_pass( COUNTY_SOI, rows, @@ -1201,18 +1231,37 @@ def county_soi_surface( expected_members=expected, ) specs, receipts = [], [] - for key, parent, counties, block, members, codes, start in checked: + unbound: list[dict] = [] + unbound_counties: set[int] = set() + for key, parent, counties, block, members, merged, codes, start in checked: state, measure, period = key block_outcomes = outcomes[start + 1 : start + 1 + len(codes)] + statuses = {outcome.status for outcome in block_outcomes} + if statuses == {controls.UNBOUND}: + # The state row and the county file disagree about this state: + # its county rows of this measure leave the surface. + unbound.append( + { + "state_fips": f"{state:02d}", + "concept": measure, + "parent": parent.name, + "factor": block_outcomes[0].factor, + "counties": len(counties), + } + ) + unbound_counties |= counties + continue + if statuses != {controls.RECONCILED}: + raise ValueError( + f"The operator did not reconcile the county rows of {measure} " + f"under {parent.name}." + ) + for code, host in sorted(merged.items()): + merges[(host, code)].append(f"{measure}|{period}") state_population = controls.sum_of_lower_rows( county_populations[code] for code in counties ) for code, outcome in zip(codes, block_outcomes, strict=True): - if outcome.status != controls.RECONCILED: - raise ValueError( - f"The operator did not reconcile county {code:05d} under " - f"{parent.name}." - ) raw, fact = block[code] county = f"{code:05d}" cell = sorted(members[code]) @@ -1269,16 +1318,17 @@ def county_soi_surface( ), } ) - # Counties without a state parent cannot silently disappear. + # Counties without a state parent cannot silently disappear. The counties + # of an unbound leg are named in the receipt. covered = {int(member) for spec in specs for member in cell_members(spec.metadata)} - missing = sorted(set(county_populations) - covered) + missing = sorted(set(county_populations) - covered - unbound_counties) if missing: raise ValueError(f"Counties have no materialized SOI state parent: {missing}.") receipt = { "soi_mode": soi_mode, "county_targets": len(specs), "concepts": sorted({key[1] for key in parents}), - "bridge": COUNTY_SOI, + "bridge": bridge_receipt(COUNTY_SOI, selector, unbound), "blocks": receipts, "combined_cells": [ { @@ -1451,7 +1501,7 @@ def county_acs_household_surface( "family": family, "source_measure_id": measure, "source": f"{tables} county B11001", - "bridge": COUNTY_ACS_HOUSEHOLDS, + "bridge": bridge_receipt(COUNTY_ACS_HOUSEHOLDS, bridge), "new_state_targets": len(receipts), "county_targets": len(specs) - len(receipts), "note": ( diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_properties.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_properties.py index c558b10e78..5e98559345 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_properties.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_county_properties.py @@ -144,7 +144,10 @@ def test_county_soi_shares_sum_to_one_and_preserve_parent_household_measures( dtype=np.float32, ) rows.append(np.where(codes // 1000 == state, values, 0.0)) - surface = county.state_county_soi_surface(parents, facts, populations) + # Random parents make random factors. The bound has its own test. + surface = county.state_county_soi_surface( + parents, facts, populations, factor_band=math.inf + ) state_matrix = sparse.csr_array(np.stack(rows)) matrix = county.split_state_rows( parents, diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_cross_grain_declarations.py b/packages/microcosm-build/tests/engine_free/us/test_us_cross_grain_declarations.py index 710edb198f..e5f7bbde38 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_cross_grain_declarations.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_cross_grain_declarations.py @@ -207,9 +207,15 @@ def test_a_selector_is_the_operators_selector() -> None: ) assert unbounded.max_factor_shift is None and unbounded.out_of_bound == "refuse" assert (unbounded.higher, unbounded.lower) == (district.higher, district.lower) + # The county bridge has the bound of the district bridge. county = declarations.us_bridge_selector(declarations.COUNTY_SOI) assert county.pair_on == ("source_measure_id", "source_period") - assert county.max_factor_shift is None + assert ( + county.max_factor_shift, + county.min_factor_shift, + county.shift_around, + county.out_of_bound, + ) == (0.25, -0.2, "median", "unbind") with pytest.raises(ValueError, match="Unknown US cross-grain bridge selector"): declarations.us_bridge_selector(declarations.COUNTY_POPULATION) @@ -225,6 +231,7 @@ def test_the_typed_views_read_the_declaration() -> None: declared["until_the_feed_repin"]["level_bridges"]["siblings"] ) county = declarations.us_county_soi_nesting() + assert county.factor_band == district.factor_band == 1.25 assert county.required_measures == ("return_count", "adjusted_gross_income") assert county.combined_cells == {15005: 15009} assert "fewer than 20 returns" in county.combined_cell_basis diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_target_nesting_county.py b/packages/microcosm-build/tests/engine_free/us/test_us_target_nesting_county.py index c920805049..18bb43cc53 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_target_nesting_county.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_target_nesting_county.py @@ -29,6 +29,7 @@ import hashlib import importlib.util import json +import math import os import struct from pathlib import Path @@ -140,7 +141,8 @@ def _receipt_image(receipt: dict, *, old: bool) -> str: """The receipt without what only one side writes. The old blocks hold ``share_sum``, the float sum of the shares (one, or - one bit from it). The new receipt names its declared pass under ``bridge``. + one bit from it). The new receipt names its declared bridge, its bound + and the legs it unbound under ``bridge``. """ image = {key: value for key, value in receipt.items() if key != "bridge"} @@ -161,7 +163,8 @@ def _assert_same_surface(new, old, pass_id: str, seed: int) -> None: assert _receipt_image(new.receipt, old=False) == _receipt_image( old.receipt, old=True ), seed - assert new.receipt["bridge"] == pass_id + assert new.receipt["bridge"]["bridge_id"] == pass_id + assert new.receipt["bridge"]["unbound"] == [] def _assert_same_refusal(new: tuple, old: tuple, seed: int) -> bool: @@ -440,7 +443,15 @@ def test_the_county_soi_surface_is_the_old_surface_on_random_blocks(county) -> N rows = combined = 0 for seed in SEEDS: parents, facts, populations = _soi_inputs(seed) - new = _outcome(county.state_county_soi_surface, parents, facts, populations) + # The old code had no bound, and the draws make random factors: the + # bound is off here and has its own test below. + new = _outcome( + county.state_county_soi_surface, + parents, + facts, + populations, + factor_band=math.inf, + ) old = _outcome(reference.state_county_soi_surface, parents, facts, populations) assert new[0] == old[0], (seed, new[1], old[1]) outcomes[new[0]] += 1 @@ -479,6 +490,78 @@ def test_a_combined_cell_other_than_the_declared_one_is_the_old_refusal(county) assert new == old and new[0] == "refused" +def _banded_case(factors: dict[str, tuple[float, float]]): + """States with two counties each; a state's factors for the two measures.""" + + parents, facts, populations = [], [], {} + for state, by_measure in factors.items(): + codes = [int(state) * 1000 + 1, int(state) * 1000 + 3] + populations.update(dict.fromkeys(codes, 50.0)) + for measure, factor in zip(_SOI_MEASURES[:2], by_measure, strict=True): + parents.append( + _state_spec(measure, 100.0 * factor, state=state, with_hierarchy=False) + ) + facts += [ + _soi_fact(codes[0], measure, 30.0), + _soi_fact(codes[1], measure, 70.0), + ] + return parents, facts, dict(sorted(populations.items())) + + +def test_a_state_off_the_median_factor_loses_its_county_rows(county) -> None: + """The bound of the county bridge is the district bridge's: 1.25, unbind.""" + + assert county.COUNTY_SOI_FACTOR_BAND == 1.25 + # Every state is 1.12 times its county file, as an aged amount is. State + # 05 is 2.0 times it for adjusted gross income only. + factors = {state: (1.0, 1.12) for state in ("01", "02", "04", "05", "06")} + factors["05"] = (1.0, 2.0) + parents, facts, populations = _banded_case(factors) + surface = county.state_county_soi_surface(parents, facts, populations) + bridge = surface.receipt["bridge"] + assert bridge["bridge_id"] == declarations.COUNTY_SOI + assert (bridge["max_factor_shift"], bridge["min_factor_shift"]) == (0.25, -0.2) + assert (bridge["shift_around"], bridge["out_of_bound"]) == ("median", "unbind") + (unbound,) = bridge["unbound"] + assert unbound == { + "state_fips": "05", + "concept": "adjusted_gross_income", + "parent": "state.05.adjusted_gross_income", + "factor": pytest.approx(2.0), + "counties": 2, + } + # The leg's county rows are off the surface. Every other row is bound, + # and a shared factor of 1.12 is no shift at all. + by_parent: dict[str, list[float]] = {} + for spec in surface.specs: + by_parent.setdefault(spec.metadata[PARENT_KEY], []).append(spec.value) + assert "state.05.adjusted_gross_income" not in by_parent + assert len(by_parent) == 2 * 5 - 1 and len(surface.specs) == 2 * (2 * 5 - 1) + assert by_parent["state.05.return_count"] == pytest.approx([30.0, 70.0]) + assert by_parent["state.06.adjusted_gross_income"] == pytest.approx([33.6, 78.4]) + assert surface.receipt["county_targets"] == 18 + assert len(surface.receipt["blocks"]) == 9 + + # A state that is off in both measures loses all its county rows. Its + # counties are named in the receipt, so the surface is not refused. + factors["05"] = (0.5, 2.0) + parents, facts, populations = _banded_case(factors) + surface = county.state_county_soi_surface(parents, facts, populations) + assert [ + (row["state_fips"], row["concept"]) + for row in surface.receipt["bridge"]["unbound"] + ] == [("05", "adjusted_gross_income"), ("05", "return_count")] + assert not [spec for spec in surface.specs if spec.metadata["state_fips"] == "05"] + + # With the bound off, every leg is divided from its state row. + surface = county.state_county_soi_surface( + parents, facts, populations, factor_band=math.inf + ) + assert surface.receipt["bridge"]["unbound"] == [] + assert surface.receipt["bridge"]["max_factor_shift"] is None + assert len(surface.specs) == 2 * 2 * 5 + + # --------------------------------------------------------------------------- # County households (issue row 7) # --------------------------------------------------------------------------- @@ -694,12 +777,12 @@ def first_accepted(inputs, function): "soi": { "rows": 6286, "rows_sha256": "dce48ac26c326d3c11c01908a7a9ad3aa6fc43b88acf87037fc85271b9ddaf46", - "receipt_sha256": "a77f6326b9921878e10aac4e39af65bc4c607f763bc4caf6023aceb152083cc5", + "receipt_sha256": "3f2e1ae71564973455aff2c882af482e2ae88ce3aa47eb653e0b434e2e439e45", }, "households": { "rows": 3195, "rows_sha256": "ad642af8198354d8508e6d581a6028fc89c8beac6d9339021cdce9fee2df3430", - "receipt_sha256": "c06dc6f2a45724d3a7160cdd71c1b8f07be7c6bd5cd4d75351b3cc6edf3406bd", + "receipt_sha256": "8646315a07cb55789cb3a4d0c37fef0776d25d19f91096018a64fcc3fd73c01d", }, } @@ -777,6 +860,8 @@ def test_the_pinned_county_rows_are_the_old_rows(pinned_county) -> None: assert _population_image(new) == _population_image(old), column _assert_same_surface(*pinned_county.soi, declarations.COUNTY_SOI, 0) _assert_same_surface(*pinned_county.acs, declarations.COUNTY_ACS_HOUSEHOLDS, 0) + # The declared bound of the county bridge unbinds no leg on these inputs + # (``_assert_same_surface`` holds ``bridge.unbound`` empty). # Kalawao has no IRS row: one Maui cell stands for both counties in each # of the two measures, so the SOI rows are two fewer than two per county. soi, acs = pinned_county.soi[0], pinned_county.acs[0] diff --git a/tools/us_acs_local_county_surface.py b/tools/us_acs_local_county_surface.py index 374f7d8fcc..34e5fe32cc 100644 --- a/tools/us_acs_local_county_surface.py +++ b/tools/us_acs_local_county_surface.py @@ -91,6 +91,10 @@ def _target_nesting(): #: HI, into Maui). Any other absent county is refused unless declared. DECLARED_SOI_COMBINED_CELLS = dict(_COUNTY_SOI_NESTING.combined_cells) SOI_COMBINED_CELL_BASIS = _COUNTY_SOI_NESTING.combined_cell_basis +#: How far a state's factor (its state SOI row over the sum of its county +#: facts) may sit from its measure's median across states: the declared bound +#: of the bridge, as a ratio to that median. It is the district bridge's. +COUNTY_SOI_FACTOR_BAND = _COUNTY_SOI_NESTING.factor_band def _concatenate(parts, dtype): @@ -304,6 +308,7 @@ def state_county_soi_surface( county_populations, *, combined_cells=DECLARED_SOI_COMBINED_CELLS, + factor_band: float = COUNTY_SOI_FACTOR_BAND, ): """Rebase complete county fact blocks onto existing broad state totals. @@ -314,6 +319,11 @@ def state_county_soi_surface( share is the host's published value over the state's published sum, and ``cross_grain_members`` lists the member counties. + A state whose factor (its state row over the sum of its county facts) is + more than ``factor_band`` from its measure's median across states loses + its county rows of that measure; the receipt names it under + ``bridge.unbound``, and its state row stays. + The work is in :func:`microcosm.build.us_runtime.target_nesting.county_soi_surface`: the shared cross-grain operator divides each state row among its county cells @@ -324,6 +334,7 @@ def state_county_soi_surface( facts, county_populations, combined_cells=combined_cells, + factor_band=factor_band, soi_mode=SOI_MODE, ) return CountySurface(surface.specs, surface.receipt) From f1c17c5e13c84e77d1e40e8af706795c2b986645 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Fri, 27 Nov 2026 19:19:06 +0000 Subject: [PATCH 19/23] Hold each declared member one time, and compare more operator shapes with the old copy From the adversarial review of PR #1791 (microcosm#1760), findings 2, 8 and 9. - The members check of the operator counted each member once, so a row that appeared two times passed. The old US district code refused that. The rule is now one public function, assert_leg_members: a leg holds each declared member one time; a member that is absent, a row of another area, and a member that two rows hold are refused. A caller that takes a leg off its surface before a pass checks it with the same function. The UK passes no expected_members, so no UK call reaches this. - reconcile_rows named a wrong factor, or no status, in two shapes that the operator accepts: a row under two controls (a bridge and a control of its own measurement), and a leg id that holds "+". It refuses both. No US pass reaches either. - The bit-for-bit test had one shape of surface. Two tests add the others: seeded surfaces with a bridge that is valued for each geography (200 seeds: 241 results and 159 refusals, all equal to the copy of the file at e29843dc7), and a replay of the operator's own tests (test_cross_grain.py) in which each call also runs that copy: 59 reconciliation calls, 6 partition calls and 4 detection calls, with bounded bridges, rows that bind nothing, reviewed unbound targets, licensed empty legs and unchecked bounds. Co-Authored-By: Claude Fable 5.2 --- .../src/microcosm/build/cross_grain.py | 46 ++- .../microcosm/build/cross_grain_controls.py | 24 ++ .../shared/test_cross_grain_allocator.py | 273 +++++++++++++++++- .../shared/test_cross_grain_controls.py | 50 ++++ .../shared/test_cross_grain_model.py | 28 ++ 5 files changed, 405 insertions(+), 16 deletions(-) diff --git a/packages/microcosm-build/src/microcosm/build/cross_grain.py b/packages/microcosm-build/src/microcosm/build/cross_grain.py index 60ae9fd83b..60091baa83 100644 --- a/packages/microcosm-build/src/microcosm/build/cross_grain.py +++ b/packages/microcosm-build/src/microcosm/build/cross_grain.py @@ -1047,7 +1047,8 @@ def apply_cross_grain_reconciliation( cells); a leg holding only those needs no control (``deferred_legs_without_control``). ``expected_members`` maps a lower target to the geographies that each of - its legs must hold. A leg that holds other rows than those is refused: + its legs must hold, each one time. A leg that holds other rows than those, + or one of them two times, is refused: rescaling a set that is not complete would move the missing members' mass onto the present ones. A declared leg with no row is refused in the same way. A leg that declares no member holds no row, and the empty-leg @@ -1740,7 +1741,7 @@ def _assert_expected_members( _contract_target_id(str(target_id)): by_leg for target_id, by_leg in expected_members.items() } - held: dict[tuple[str, str], set[str]] = {} + held: dict[tuple[str, str], list[str]] = {} for side, area in zip( local_frame[columns["target_id"]].tolist(), local_frame[columns["geography_id"]].tolist(), @@ -1750,29 +1751,48 @@ def _assert_expected_members( if target_id not in expected: continue for leg in _row_legs(str(area), rule): - held.setdefault((target_id, leg), set()).add(str(area)) + held.setdefault((target_id, leg), []).append(str(area)) declared = { (target_id, str(leg)) for target_id, by_leg in expected.items() for leg in by_leg } for target_id, leg in sorted(declared | held.keys()): - present = held.get((target_id, leg), set()) members = expected[target_id].get(leg) if members is None: raise ValueError( f"cross-grain target {target_id!r} has rows on leg {leg!r}, " "which declares no members for it." ) - missing = sorted(set(members) - present) - unexpected = sorted(present - set(members)) - if missing or unexpected: - raise ValueError( - f"cross-grain target {target_id!r} does not hold the declared " - f"members of leg {leg!r}: missing {missing}, unexpected " - f"{unexpected}. Rescaling a set that is not complete would " - "misstate every member." - ) + assert_leg_members(target_id, leg, held.get((target_id, leg), ()), members) + + +def assert_leg_members( + target_id: str, leg: str, present: Iterable[str], members: Iterable[str] +) -> None: + """Refuse a leg that does not hold each of its declared members one time. + + ``present`` is the geography of each row of the target on the leg, with a + geography that two rows hold given two times. A caller that takes a leg + off its surface before a pass checks the leg with this function, so one + rule and one text hold for every leg. + """ + + counts: dict[str, int] = {} + for area in present: + counts[str(area)] = counts.get(str(area), 0) + 1 + declared = {str(member) for member in members} + missing = sorted(declared - counts.keys()) + unexpected = sorted(counts.keys() - declared) + repeated = sorted(area for area, count in counts.items() if count > 1) + if missing or unexpected or repeated: + twice = f", repeated {repeated}" if repeated else "" + raise ValueError( + f"cross-grain target {target_id!r} does not hold the declared " + f"members of leg {leg!r}: missing {missing}, unexpected " + f"{unexpected}{twice}. Rescaling a set that is not complete would " + "misstate every member." + ) def _controls_agree(left: float, right: float) -> bool: diff --git a/packages/microcosm-build/src/microcosm/build/cross_grain_controls.py b/packages/microcosm-build/src/microcosm/build/cross_grain_controls.py index 76d94c6231..3708d35fd6 100644 --- a/packages/microcosm-build/src/microcosm/build/cross_grain_controls.py +++ b/packages/microcosm-build/src/microcosm/build/cross_grain_controls.py @@ -91,8 +91,25 @@ def reconcile_rows( Returns one :class:`RowOutcome` for each row, in the order of ``rows``, and the operator's pass receipt. + + Two shapes that the operator accepts are refused here, because the + answer for a row would be wrong: + + - a leg whose id holds ``+``: the operator's receipt joins the legs of + one control with ``+``, so such a leg cannot be found again; + - a row that two groups reconcile (a lower target under a bridge and + under a control of its own measurement): a row names one control and + one factor. """ + for row in rows: + joined = [leg for leg in _row_legs(row.geography_id, rule) if "+" in leg] + if joined: + raise ValueError( + f"cross-grain row at {row.geography_id!r} sits on leg " + f"{joined[0]!r}; a leg id that holds '+' cannot be named for " + "each row." + ) frame = pd.DataFrame( [ (row.grain, row.geography_id, row.target_id, float(row.value)) @@ -156,6 +173,13 @@ def parent_of(leg: Mapping[str, Any]) -> int | None: for position in lower.get( (target_id, group["lower_grain"], name), () ): + if outcomes[position].status != UNTOUCHED: + raise ValueError( + f"cross-grain row {position} of target " + f"{target_id!r} is reconciled by " + f"{outcomes[position].control!r} and by " + f"{control!r}; a row names one control." + ) outcomes[position] = RowOutcome( value=values[position], status=RECONCILED, diff --git a/packages/microcosm-build/tests/engine_free/shared/test_cross_grain_allocator.py b/packages/microcosm-build/tests/engine_free/shared/test_cross_grain_allocator.py index e42c515be8..13346a154a 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_cross_grain_allocator.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_cross_grain_allocator.py @@ -7,18 +7,27 @@ ``test_support/microcosm_build/cross_grain_reference.py`` is the module as it stood at ``e29843dc7``, before the hook; its sha256 is pinned here. The -differential test runs seeded random surfaces through both modules. When the -standing rule changes on purpose, delete the reference copy and the tests that -read it: they prove only that the hook changed nothing. +differential test runs seeded random surfaces through both modules. A second +test runs the operator's own tests (``test_cross_grain.py``) with every call +of the operator compared with the reference copy: those tests hold the shapes +that the seeded surfaces lack (a bridge valued for each geography, rows that +bind nothing, reviewed unbound targets, partitions). When the standing rule +changes on purpose, delete the reference copy and the tests that read it: +they prove only that the hook changed nothing. """ from __future__ import annotations import ast +import dataclasses import hashlib +import importlib.util import inspect import json import math +from collections import Counter +from collections.abc import Iterator +from pathlib import Path import numpy as np import pandas as pd @@ -60,6 +69,8 @@ "_assert_expected_members", # The metadata of a reconciled row, for a caller that holds target rows. "cross_grain_metadata", + # The rule of the declared members, for a leg that a caller checks itself. + "assert_leg_members", } _LEGS = ("E", "W", "S", "N") @@ -223,6 +234,7 @@ def _outcome(module, case, *, check_factor_bounds: bool): concept=bridge.concept, higher_target_ids=bridge.higher_target_ids, lower_side=bridge.lower_side, + per_geography=bridge.per_geography, max_factor_shift=bridge.max_factor_shift, ) for bridge in rule_arguments["bridges"] @@ -268,6 +280,261 @@ def test_the_default_path_is_the_operator_before_the_hook_bit_for_bit() -> None: assert rescaled_legs >= 1_000 +def _per_geography_case(seed: int): + """A bridge whose higher targets are each the control of their own geography. + + The UK declares such bridges (each nation's estimate over its own legs). + A geography can carry no estimate, a leg can be empty, and the bound is + sometimes close, so the draws reach the refusals too. + """ + + rng = np.random.default_rng(10_000 + seed) + legs = tuple(leg for leg in _LEGS if rng.random() < 0.9) or ("E",) + rows: list[tuple[str, str, str, float]] = [] + signatures = {"bridged_local": _signature("bridged_local_concept")} + estimates: list[str] = [] + empty: set[str] = set() + for leg in legs: + total = float(rng.lognormal(mean=math.log(1e5), sigma=1.0)) + 1.0 + if rng.random() < 0.9: + estimate = f"estimate_{leg}" + signatures[estimate] = _signature("bridged_concept") + estimates.append(estimate) + rows.append(("region", leg, estimate, total)) + if rng.random() < 0.06: + empty.add(leg) + continue + target = total * float(rng.uniform(0.6, 1.4)) + for grain in ("constituency", "la"): + shares = rng.dirichlet(np.ones(int(rng.integers(1, 5)))) + rows += [ + ( + grain, + f"{leg}{grain[0]}{index}", + "bridged_local", + float(target * share), + ) + for index, share in enumerate(shares) + ] + bridge = CrossGrainBridge( + "estimates", + concept="bridged_concept", + higher_target_ids=tuple(estimates) or ("estimate_E",), + lower_side="contract:bridged_local", + per_geography=True, + max_factor_shift=( + None if rng.random() < 0.3 else float(rng.choice([0.2, 0.5, 0.9])) + ), + ) + order = rng.permutation(len(rows)) + surface = pd.DataFrame( + [rows[index] for index in order], + columns=["grain", "geography_id", "target_id", "value"], + ) + rule_arguments = { + "grain_precedence": ("country", "region", "constituency", "la"), + "signature_fields": ("concept", "entity", "map_to", "filters"), + "bridges": (bridge,), + "leg_of_area": lambda area: area[0], + "parent_geography_legs": {"UK": legs, **{leg: (leg,) for leg in legs}}, + "control_grains": ("country", "region"), + } + licences = {"bridged_local": frozenset(empty)} if rng.random() < 0.85 else {} + return surface, tuple(estimates), signatures, rule_arguments, licences + + +def test_a_bridge_for_each_geography_is_the_operator_before_bit_for_bit() -> None: + outcomes = {"reconciled": 0, "refused": 0} + rescaled_legs = 0 + for seed in range(200): + case = _per_geography_case(seed) + for check_factor_bounds in (True, False): + new = _outcome(cross_grain, case, check_factor_bounds=check_factor_bounds) + old = _outcome( + cross_grain_reference, case, check_factor_bounds=check_factor_bounds + ) + assert new == old, seed + outcomes[new[0]] += 1 + if new[0] == "reconciled": + rescaled_legs += sum( + len(group["legs"]) for group in json.loads(new[2])["groups"] + ) + # The draws reach both the rescaling and the refusals. + assert outcomes["reconciled"] >= 150 + assert outcomes["refused"] >= 80 + assert rescaled_legs >= 1_000 + + +# --------------------------------------------------------------------------- +# The operator's own tests, with each call compared with the reference +# --------------------------------------------------------------------------- + +#: Tests of ``test_cross_grain.py`` that change the operator itself with +#: ``monkeypatch``: the reference copy would not have the change. +_NOT_REPLAYED = {"test_off_control_reconciliation_is_refused"} + + +def _as_reference(value): + """``value`` as the reference module's class, field for field.""" + + for name in ("CrossGrainRule", "CrossGrainBridge", "CrossGrainPartition"): + if isinstance(value, getattr(cross_grain, name)): + old_class = getattr(cross_grain_reference, name) + return old_class( + **{ + field.name: _as_reference(getattr(value, field.name)) + for field in dataclasses.fields(old_class) + } + ) + if isinstance(value, tuple): + return tuple(_as_reference(item) for item in value) + if isinstance(value, pd.DataFrame): + return value.copy() + return value + + +def _uses_a_general_option(arguments) -> bool: + """A call that the reference cannot run: it has options the branch added.""" + + rules = [value for value in arguments if isinstance(value, CrossGrainRule)] + return any( + rule.allocator is not None + or any( + bridge.min_factor_shift is not None + or bridge.shift_around != "one" + or bridge.out_of_bound != "refuse" + for bridge in rule.bridges + ) + for rule in rules + ) + + +def _call_image(function, arguments, keywords) -> tuple: + try: + result = function(*arguments, **keywords) + except Exception as error: # the refusal is part of the result + return ("raised", type(error).__name__, str(error)), error + if isinstance(result, tuple) and isinstance(result[0], pd.DataFrame): + frame, receipt = result + image = ( + "returned", + frame.to_json(double_precision=15), + frame["value"].to_numpy(dtype=np.float64).tobytes(), + json.dumps(receipt, default=str), + ) + else: + # Detected groups: frozen dataclasses with the same name in both + # modules, so their text is the same when their content is. + image = ("returned", repr(result)) + return image, result + + +def _compared_with_the_reference(name: str, stats: Counter): + new_function = getattr(cross_grain, name) + old_function = getattr(cross_grain_reference, name) + + def run(*arguments, **keywords): + arguments = tuple( + tuple(value) if isinstance(value, Iterator) else value + for value in arguments + ) + keywords = { + key: tuple(value) if isinstance(value, Iterator) else value + for key, value in keywords.items() + } + assert not _uses_a_general_option(arguments) and ( + "expected_members" not in keywords + ), "test_cross_grain.py uses an option that the reference does not have" + new_image, result = _call_image(new_function, arguments, keywords) + old_image, _ = _call_image( + old_function, + tuple(_as_reference(value) for value in arguments), + {key: _as_reference(value) for key, value in keywords.items()}, + ) + assert new_image == old_image, name + stats[name] += 1 + stats[new_image[0]] += 1 + for value in arguments: + if isinstance(value, CrossGrainRule): + stats["a bounded bridge"] += any( + bridge.max_factor_shift is not None for bridge in value.bridges + ) + for key in ( + "frame_only_positions", + "reviewed_unbound_higher_targets", + "licensed_empty_legs", + ): + stats[key] += bool(keywords.get(key)) + stats["bounds not checked"] += keywords.get("check_factor_bounds") is False + if isinstance(result, Exception): + raise result + return result + + return run + + +def _parameter_sets(test) -> list[dict]: + """The arguments of each case of a test: its ``parametrize`` mark, or none.""" + + marks = [ + mark for mark in getattr(test, "pytestmark", []) if mark.name == "parametrize" + ] + if not marks: + return [{}] + (mark,) = marks + names, cases = mark.args + if isinstance(names, str): + names = [name.strip() for name in names.split(",")] + return [ + dict(zip(names, case if len(names) > 1 else (case,), strict=True)) + for case in cases + ] + + +def test_the_operators_own_tests_give_the_reference_results(monkeypatch) -> None: + """Every operator call of ``test_cross_grain.py`` is the reference's result.""" + + path = Path(__file__).with_name("test_cross_grain.py") + spec = importlib.util.spec_from_file_location("cross_grain_suite_replay", path) + suite = importlib.util.module_from_spec(spec) + assert spec.loader is not None + spec.loader.exec_module(suite) + stats: Counter = Counter() + for name in ( + "apply_cross_grain_reconciliation", + "apply_cross_grain_partitions", + "detect_cross_grain_inconsistencies", + ): + monkeypatch.setattr(suite, name, _compared_with_the_reference(name, stats)) + tests = { + name: test + for name, test in vars(suite).items() + if name.startswith("test_") and callable(test) + } + assert _NOT_REPLAYED <= set(tests) + for name, test in tests.items(): + if name in _NOT_REPLAYED: + continue + for case in _parameter_sets(test): + test(**case) + stats["cases"] += 1 + # The replay reached the operator, with both results and refusals, and + # with each shape that the seeded surfaces above do not have. + assert stats["cases"] >= 40 + assert stats["apply_cross_grain_reconciliation"] >= 40 + assert stats["returned"] >= 15 and stats["raised"] >= 15 + for shape in ( + "apply_cross_grain_partitions", + "detect_cross_grain_inconsistencies", + "a bounded bridge", + "frame_only_positions", + "reviewed_unbound_higher_targets", + "licensed_empty_legs", + "bounds not checked", + ): + assert stats[shape] >= 1, shape + + def _fsum_allocator(raw_values, parent_value): raw_sum = math.fsum(raw_values.tolist()) factor = 1.0 if raw_sum == 0.0 else parent_value / raw_sum diff --git a/packages/microcosm-build/tests/engine_free/shared/test_cross_grain_controls.py b/packages/microcosm-build/tests/engine_free/shared/test_cross_grain_controls.py index 1826c58e4a..6df06d3b29 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_cross_grain_controls.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_cross_grain_controls.py @@ -314,6 +314,56 @@ def test_reconcile_rows_leaves_a_row_that_no_group_covers() -> None: assert outcomes[-1] == controls.RowOutcome(value=7.0) +def test_reconcile_rows_refuses_a_row_under_two_controls() -> None: + """A row names one control and one factor.""" + + signatures = { + "bridged": {"measurement": {"concept": "source one"}}, + "total": {"measurement": {"concept": "quantity"}}, + "parts": {"measurement": {"concept": "quantity"}}, + } + bridge = CrossGrainBridge( + "bridged_vs_parts", + concept="one quantity", + higher_target_ids=("bridged",), + lower_side="parts", + ) + rows = [ + controls.SurfaceRow("state", "A", "bridged", 120.0), + controls.SurfaceRow("state", "A", "total", 120.0), + controls.SurfaceRow("district", "A1", "parts", 20.0), + controls.SurfaceRow("district", "A2", "parts", 40.0), + ] + with pytest.raises(ValueError, match="a row names one control"): + controls.reconcile_rows( + rows, ("bridged", "total"), signatures, _row_rule(bridge) + ) + + +def test_reconcile_rows_refuses_a_leg_id_that_holds_a_plus() -> None: + """The operator's receipt joins the legs of one control with ``+``.""" + + signatures = { + "total": {"measurement": {"concept": "quantity"}}, + "parts": {"measurement": {"concept": "quantity"}}, + } + rule = CrossGrainRule( + grain_precedence=("nation", "state", "district"), + signature_fields=("concept",), + bridges=(), + leg_of_area=lambda area: "A+B", + parent_geography_legs={"A+B": ("A+B",)}, + control_grains=("nation", "state"), + ) + rows = [ + controls.SurfaceRow("state", "A+B", "total", 120.0), + controls.SurfaceRow("district", "A+B-1", "parts", 20.0), + controls.SurfaceRow("district", "A+B-2", "parts", 40.0), + ] + with pytest.raises(ValueError, match=r"a leg id that holds '\+'"): + controls.reconcile_rows(rows, ("total",), signatures, rule) + + def test_the_module_holds_no_country_and_the_operator_does_not_import_it() -> None: from microcosm.build import cross_grain diff --git a/packages/microcosm-build/tests/engine_free/shared/test_cross_grain_model.py b/packages/microcosm-build/tests/engine_free/shared/test_cross_grain_model.py index 98120ed3da..7a47a7a40f 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_cross_grain_model.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_cross_grain_model.py @@ -26,6 +26,7 @@ CrossGrainBridgeSelector, CrossGrainRule, apply_cross_grain_reconciliation, + assert_leg_members, expand_bridge_selectors, ) @@ -266,6 +267,33 @@ def test_expected_members_refuse_a_leg_that_is_not_complete() -> None: ) +def test_a_leg_holds_each_member_one_time() -> None: + """Two rows of one member would put that member on the surface twice.""" + + surface = _surface({"A": 1.1, "B": 1.1}) + members = _members(A=["A1", "A2"], B=["B1", "B2"]) + twice = pd.concat( + [surface, surface[surface["geography_id"] == "A1"]], ignore_index=True + ) + with pytest.raises( + ValueError, + match=r"leg 'A': missing \[\], unexpected \[\], repeated \['A1'\]", + ): + apply_cross_grain_reconciliation( + twice, ("total",), _SIGNATURES, _rule(_bridge()), expected_members=members + ) + # A caller checks a leg that it takes off its surface with the same rule. + assert_leg_members("parts", "A", ["A1", "A2"], {"A1", "A2"}) + assert_leg_members("parts", "A", [], set()) + for present, message in ( + (["A1"], r"missing \['A2'\], unexpected \[\]\."), + (["A1", "A2", "A3"], r"missing \[\], unexpected \['A3'\]\."), + (["A1", "A2", "A2"], r"unexpected \[\], repeated \['A2'\]\."), + ): + with pytest.raises(ValueError, match=message): + assert_leg_members("parts", "A", present, {"A1", "A2"}) + + def test_a_declared_leg_holds_its_members_with_or_without_rows() -> None: surface = _surface({"A": 1.1, "B": 1.1}) without_b = surface[~surface["geography_id"].isin(["B1", "B2"])].reset_index( From bb6776f87a3fe1e3144a55be366ba325d26eeac8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Fri, 27 Nov 2026 19:19:06 +0000 Subject: [PATCH 20/23] Put back a lost district refusal, and tighten the US declaration and its coverage check From the adversarial review of PR #1791 (microcosm#1760), findings 1, 6, 10 and 11. The district pass: - A block whose level bridge is distrusted leaves the surface before the pass, so the operator never saw it, and a block that lacked a district was dropped in silence. The old code refused it. The adapter now checks such a block with the operator's rule (assert_leg_members). With the operator change before this commit, a district row that appears two times is refused again too. - A district-file target that the selector pairs with no Historic Table 2 target, and that no state row of its own measurement controls, is refused. The pass threw that list away. - The trust band of a level bridge reads both limits of the declared bound. It read the upper one and took its inverse. The declaration: - An unknown top-level key, a bridge by id and a partition are refused when the file loads: no US pass would read them. - The part of a subset relation must be at a lower level than its whole. - The higher level of a compile rule or a known gap must be a declared level. The derivation of a derived control is read by the adapter, which hard-coded the sum. - single_member_legs goes: nothing read it. The coverage check: - A role that the top level and a lower level both hold must be named: by a relation of its own, or by a compile rule or a known gap that lists it. A family was covered as a whole, so a new role in a covered family passed unseen. On the pinned feed ten roles are at two levels. Six had a relation. The two premium tax credit roles of Historic Table 2 get a subset relation (their 51 state rows sum to 0.9996 and 0.9997 of the US row). The general SOI role and the Census age rows are listed by the two known gaps that are about them. - A subset whose whole is more than one row, or is not positive, is a violation. It was skipped in silence. Co-Authored-By: Claude Fable 5.2 --- .../build/us/cross_grain_declarations.json | 27 +++- .../us_runtime/cross_grain_declarations.py | 142 +++++++++++++++--- .../build/us_runtime/target_nesting.py | 100 +++++++++--- .../us/test_us_acs_local_cd_properties.py | 44 ++++++ .../us/test_us_cross_grain_coverage.py | 84 ++++++++++- .../us/test_us_cross_grain_declarations.py | 53 +++++++ 6 files changed, 408 insertions(+), 42 deletions(-) diff --git a/packages/microcosm-build/src/microcosm/build/us/cross_grain_declarations.json b/packages/microcosm-build/src/microcosm/build/us/cross_grain_declarations.json index 5ccfae082a..b0ba19c557 100644 --- a/packages/microcosm-build/src/microcosm/build/us/cross_grain_declarations.json +++ b/packages/microcosm-build/src/microcosm/build/us/cross_grain_declarations.json @@ -152,6 +152,26 @@ "part": "hhs_acf_tanf.tanf_total@state", "whole": "hhs_acf_tanf.tanf_total@country", "reason": "Only 29 states bind a TANF row. Scaling them to the national row would give them the mass of the missing ones." + }, + { + "targets": [ + "irs_soi.aca_ptc_returns@state", + "irs_soi.aca_ptc_returns@country" + ], + "relation": "subset", + "part": "irs_soi.aca_ptc_returns@state", + "whole": "irs_soi.aca_ptc_returns@country", + "reason": "Cells of one publication: the state rows and the US row of Historic Table 2 for tax year 2022 (returns with a premium tax credit). The 51 state rows sum to 0.9996 of the US row, which also counts returns of other areas. No rule scales them." + }, + { + "targets": [ + "irs_soi.aca_spending@state", + "irs_soi.aca_spending@country" + ], + "relation": "subset", + "part": "irs_soi.aca_spending@state", + "whole": "irs_soi.aca_spending@country", + "reason": "Cells of one publication: the state rows and the US row of Historic Table 2 for tax year 2022 (premium tax credit amount). The 51 state rows sum to 0.9997 of the US row, which also counts returns of other areas. No rule scales them." } ], "local_routes": { @@ -172,7 +192,6 @@ "congressional_district": { "source": "congressional_district_vintage_crosswalk", "reviewed_crosswalk_sha256": "a347303fff3fea145f758488c43cb94355df5a8cb5e512552b2ee3791d2aa233", - "single_member_legs": "not bound", "description": "The 117th->119th congressional-district crosswalk the compiler used names each state's source-plan and current-plan districts. A district block must cover exactly the current plan's districts of its state. A state with one source-plan district is at-large there: the district file has no sub-state rows for it, so its district rows are dropped (at_large_on_source_plan). reviewed_crosswalk_sha256 is the packaged crosswalk the registers below were reviewed against; a test pins it, so regenerating the crosswalk forces a second look at them." }, "county": { @@ -313,6 +332,9 @@ "state" ], "higher_level": "country", + "roles": [ + "soi_fiscal_distribution" + ], "reason": "Several SOI families bind a Historic Table 2 US row beside a newer Table 1.x row, and no rule ties their state rows to either. Rows 1 and 2 are the treatment that the issue asks for the others. It waits for Stage A.", "issues": [ "microcosm#1243" @@ -325,6 +347,9 @@ "state" ], "higher_level": "country", + "roles": [ + "population_age" + ], "reason": "The national build fits Census age bands for each state. The local build fits state totals from the 2020 ladder and no age row. No rule ties the age rows of a state to its total, or to the national age rows.", "issues": [ "microcosm#1528", diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/cross_grain_declarations.py b/packages/microcosm-build/src/microcosm/build/us_runtime/cross_grain_declarations.py index 41e0e8d9b0..65446fd6c0 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/cross_grain_declarations.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/cross_grain_declarations.py @@ -46,7 +46,28 @@ _RELATION_KINDS = ("subset", "independent") _LOCAL_ROUTE_KINDS = ("no_higher_control",) -_DERIVATIONS = ("sum_of_lower_rows",) +#: The derivations that the adapter can run for a derived control. +US_DERIVATIONS = ("sum_of_lower_rows",) +#: Every key of the file. A key outside this set would be read by nothing. +_KEYS = frozenset( + { + "schema_version", + "description", + "grain_precedence", + "control_grains", + "signature_fields", + "bridges", + "bridge_selectors", + "derived_controls", + "same_measurement", + "partitions", + "relations", + "local_routes", + "members", + "registers", + "until_the_feed_repin", + } +) @functools.lru_cache(maxsize=1) @@ -68,6 +89,20 @@ def load_us_cross_grain_declarations() -> Mapping[str, Any]: def _validate(payload: Mapping[str, Any]) -> None: + unknown = sorted(set(payload) - _KEYS) + if unknown: + raise ValueError( + f"US cross-grain declarations hold unknown key(s) {unknown}; " + "nothing would read them." + ) + # The US passes take their bridges from ``bridge_selectors`` and declare no + # partition. A bridge by id or a partition written here would not run. + for key in ("bridges", "partitions"): + if payload[key]: + raise ValueError( + f"US cross-grain declarations hold {key!r} entries, and no US " + "pass runs them yet; declare a bridge selector, or add the pass." + ) grains = tuple(payload["grain_precedence"]) controls = tuple(payload["control_grains"]) unknown_controls = [grain for grain in controls if grain not in grains] @@ -103,11 +138,11 @@ def nests(pass_id: str, higher: object, lower: object) -> None: pass_ids.append(selector["bridge_id"]) for derived in payload["derived_controls"]: nests(derived["bridge_id"], derived["higher_grain"], derived["lower_grain"]) - if derived["derive"] not in _DERIVATIONS: + if derived["derive"] not in US_DERIVATIONS: raise ValueError( f"US cross-grain derived control {derived['bridge_id']!r} names " f"unknown derivation {derived['derive']!r}; expected one of " - f"{_DERIVATIONS}." + f"{US_DERIVATIONS}." ) pass_ids.append(derived["bridge_id"]) for same in payload["same_measurement"]: @@ -136,8 +171,17 @@ def nests(pass_id: str, higher: object, lower: object) -> None: f"two targets, one of {_RELATION_KINDS}, a part and a whole for " "a subset, and a reason." ) - for target in targets: - _relation_target(target, grains) + levels = { + target: grains.index(_relation_target(target, grains)[2]) + for target in targets + } + if relation["relation"] == "subset" and ( + levels[str(relation["part"])] <= levels[str(relation["whole"])] + ): + raise ValueError( + f"US cross-grain relation over {targets} is malformed: the part " + "of a subset is at a lower level than its whole." + ) for target, route in payload["local_routes"].items(): _route_target(target, grains) if ( @@ -156,8 +200,10 @@ def nests(pass_id: str, higher: object, lower: object) -> None: or not entry.get("family") or not levels or any(level not in grains for level in levels) + or entry.get("higher_level") not in grains or not str(entry.get("reason", "")).strip() or not entry.get("issues") + or ("roles" in entry and not entry["roles"]) ): raise ValueError( f"US cross-grain entry {entry.get('id')!r} must name a family, " @@ -255,6 +301,15 @@ def us_pass_grains(pass_id: str) -> tuple[str, str]: raise ValueError(f"Unknown US cross-grain pass {pass_id!r}.") +def us_derivation(pass_id: str) -> str: + """The declared derivation of the control of a derived-control pass.""" + + for entry in load_us_cross_grain_declarations()["derived_controls"]: + if entry["bridge_id"] == pass_id: + return str(entry["derive"]) + raise ValueError(f"Unknown US cross-grain derived control {pass_id!r}.") + + def us_allocator_name(pass_id: str) -> str | None: """The allocator of a pass until the feed is re-pinned, if it has one.""" @@ -381,12 +436,24 @@ def us_cross_grain_coverage_violations( * ``family_level_without_route``: a family has rows at a lower level that nothing covers; + * ``role_at_two_levels_without_relation``: rows of one family and one + role (``role_key``) are at the top level and at a lower level, and no + relation names that role, nor a compile rule or a known gap that lists + it under ``roles``. A family is covered as a whole, so without this a + new role in a covered family would pass unseen; * ``stale_declaration``: a relation, a local route, a compile rule or a known gap names rows that the specs do not hold; * ``compile_rule_marker_absent``: a compile rule's marker is on no row of one of its levels; * ``subset_exceeded``: the parts of a ``subset`` relation sum to more - than their whole, beyond the declared ``max_excess``. + than their whole, beyond the declared ``max_excess``; + * ``subset_whole_not_one_positive_row``: the whole of a ``subset`` + relation is more than one row, or is not positive, so the sum of its + parts cannot be compared with it. + + What the check does not read: a row with no ``level_key`` in its + metadata. The rows that a pass makes (the ladder population, the county + households) are such rows, and their pass declares them. Returns the violations. The caller decides what one means: this function refuses nothing. @@ -419,10 +486,12 @@ def stale(family: str, level: str, where: str) -> None: } ) + related: set[tuple[str, str]] = set() for relation in declared["relations"]: sides = {} for target in relation["targets"]: family, role, level = _relation_target(str(target), grains) + related.add((family, role)) held = [ spec for spec in rows.get((family, level), ()) @@ -435,23 +504,42 @@ def stale(family: str, level: str, where: str) -> None: stale(family, level, str(target)) if relation["relation"] == "subset": part, whole = sides[str(relation["part"])], sides[str(relation["whole"])] - if part and len(whole) == 1 and whole[0].value: - ratio = math.fsum(spec.value for spec in part) / whole[0].value - if ratio > 1.0 + float(relation.get("max_excess", 0.0)): - violations.append( - { - "kind": "subset_exceeded", - "family": str(part[0].family), - "level": str(part[0].metadata.get(level_key)), - "where": f"{relation['part']} is {ratio!r} of its whole", - } - ) + if not part or not whole: + continue # A side with no row is a stale declaration, above. + if len(whole) != 1 or not whole[0].value > 0: + violations.append( + { + "kind": "subset_whole_not_one_positive_row", + "family": str(whole[0].family), + "level": str(whole[0].metadata.get(level_key)), + "where": f"{relation['whole']} holds {len(whole)} row(s)", + } + ) + continue + ratio = math.fsum(spec.value for spec in part) / whole[0].value + if ratio > 1.0 + float(relation.get("max_excess", 0.0)): + violations.append( + { + "kind": "subset_exceeded", + "family": str(part[0].family), + "level": str(part[0].metadata.get(level_key)), + "where": f"{relation['part']} is {ratio!r} of its whole", + } + ) for target in declared["local_routes"]: family, level = _route_target(str(target), grains) covered.add((family, level)) if (family, level) not in rows: stale(family, level, str(target)) for entry in (*transitional["compile_rules"], *transitional["known_gaps"]): + for role in entry.get("roles", ()): + related.add((str(entry["family"]), str(role))) + if not any( + spec.metadata.get(role_key) == role + for level in entry["levels"] + for spec in rows.get((str(entry["family"]), str(level)), ()) + ): + stale(str(entry["family"]), "/".join(entry["levels"]), str(role)) for level in entry["levels"]: key = (str(entry["family"]), str(level)) covered.add(key) @@ -477,6 +565,26 @@ def stale(family: str, level: str, where: str) -> None: } for family, level in sorted(compiled - covered) ) + # A family is covered as a whole. A role that two levels measure must be + # named: by a relation of its own, or by a compile rule or a known gap + # that lists it. + levels_of_role: dict[tuple[str, str], set[str]] = {} + for (family, level), held in rows.items(): + for spec in held: + role = spec.metadata.get(role_key) + if role is not None: + levels_of_role.setdefault((family, str(role)), set()).add(level) + for (family, role), levels in sorted(levels_of_role.items()): + if top in levels and len(levels) > 1 and (family, role) not in related: + violations.extend( + { + "kind": "role_at_two_levels_without_relation", + "family": family, + "level": level, + "where": f"{family}.{role}", + } + for level in sorted(levels - {top}) + ) return violations diff --git a/packages/microcosm-build/src/microcosm/build/us_runtime/target_nesting.py b/packages/microcosm-build/src/microcosm/build/us_runtime/target_nesting.py index 05075382cf..408ee2a205 100644 --- a/packages/microcosm-build/src/microcosm/build/us_runtime/target_nesting.py +++ b/packages/microcosm-build/src/microcosm/build/us_runtime/target_nesting.py @@ -44,6 +44,7 @@ CrossGrainBridge, CrossGrainBridgeSelector, CrossGrainRule, + assert_leg_members, cross_grain_metadata, expand_bridge_selectors, ) @@ -57,6 +58,7 @@ us_allocator_name, us_bridge_selector, us_county_soi_nesting, + us_derivation, us_district_soi_nesting, us_pass_grains, ) @@ -165,6 +167,45 @@ def bounded_selector(pass_id: str, factor_band: float) -> CrossGrainBridgeSelect ) +def bound_limits( + bridge: CrossGrainBridge | CrossGrainBridgeSelector, +) -> tuple[float, float]: + """The lowest and the highest ratio to its reference that a bound allows.""" + + if bridge.max_factor_shift is None: + return 0.0, math.inf + lowest = ( + -bridge.max_factor_shift + if bridge.min_factor_shift is None + else bridge.min_factor_shift + ) + return 1.0 + lowest, 1.0 + bridge.max_factor_shift + + +def refuse_unpaired( + pass_id: str, + unpaired: Mapping[str, Sequence[str]], + *, + own_control: Iterable[str] = (), +) -> None: + """Refuse a lower target that the declared selector gives no higher target. + + ``own_control`` names the lower targets that a row of their own + measurement controls: they need no bridge. + """ + + left = sorted(set(unpaired.get(pass_id, ())) - set(own_control)) + if left: + raise ValueError( + f"US cross-grain pass {pass_id!r} pairs no higher target with " + f"lower target(s) {left[:5]}; their rows would have no control." + ) + + +#: The derivations of a derived control, by their declared name. +DERIVATIONS = {"sum_of_lower_rows": controls.sum_of_lower_rows} + + def bridge_receipt( bridge_id: str, bridge: CrossGrainBridge | CrossGrainBridgeSelector, @@ -408,12 +449,13 @@ def drop(spec, reason: str) -> None: else: kept_cd_by_key[(state, concept_identity(spec))].append(spec) + selector = bounded_selector(DISTRICT_SOI, factor_band) bridged, bridge_factors, bridge_verdicts = _bridged_state_parents( ht2_by_key, cd_file_state_by_key, kept_cd_by_key, level_bridges=level_bridges, - factor_band=factor_band, + limits=bound_limits(selector), defective=defective, ) @@ -440,6 +482,17 @@ def drop(spec, reason: str) -> None: f"differently: {sorted(map(repr, semantics))}." ) (child_semantics,) = semantics + identity_text = "|".join(identity) + lower_id = f"{LOWER_FILE}|{identity_text}" + state_area = geography_id(state_level, state) + areas = [ + geography_id(district_level, child.metadata["congressional_district_geoid"]) + for child in children + ] + members = frozenset( + geography_id(district_level, district) + for district in target_districts.get(state, ()) + ) parent = ht2_by_key.get(key) basis, source = "historic_table_2", STATE_SURFACE if parent is None: @@ -451,6 +504,9 @@ def drop(spec, reason: str) -> None: "state parent in either vintage." ) if own.name not in bridged: + # The block leaves the surface before the pass, so the pass + # cannot check it. It must hold its members all the same. + assert_leg_members(lower_id, state_area, areas, members) for child in children: drop(child, f"level_bridge_out_of_band:{identity[0]}") continue @@ -467,10 +523,7 @@ def drop(spec, reason: str) -> None: f"State parent {parent.name} materializes differently from " f"its district rows ({identity}, state {state})." ) - identity_text = "|".join(identity) - lower_id = f"{LOWER_FILE}|{identity_text}" higher_id = f"{source}|{identity_text}" - state_area = geography_id(state_level, state) targets[higher_id] = { "source": source, "grain": state_level, @@ -488,19 +541,21 @@ def drop(spec, reason: str) -> None: bound.append(higher_id) blocks.append((key, parent, basis, children, len(rows))) rows.append(SurfaceRow(state_level, state_area, higher_id, float(parent.value))) - for child in children: - area = geography_id( - district_level, child.metadata["congressional_district_geoid"] - ) + for child, area in zip(children, areas, strict=True): legs[area] = state_area rows.append(SurfaceRow(district_level, area, lower_id, float(child.value))) - expected.setdefault(lower_id, {})[state_area] = frozenset( - geography_id(district_level, district) - for district in target_districts.get(state, ()) - ) + expected.setdefault(lower_id, {})[state_area] = members - selector = bounded_selector(DISTRICT_SOI, factor_band) - bridges, _unpaired = expand_bridge_selectors([selector], targets) + bridges, unpaired = expand_bridge_selectors([selector], targets) + refuse_unpaired( + DISTRICT_SOI, + unpaired, + # A concept that only the lower file has: its own state total, which + # has the measurement of its district rows, is the control. + own_control={ + measured for target, measured in measurements.items() if target != measured + }, + ) outcomes, operator_receipt = run_pass( DISTRICT_SOI, rows, @@ -648,7 +703,7 @@ def _bridged_state_parents( kept_cd_by_key: Mapping[tuple, Sequence], *, level_bridges: Mapping[str, str], - factor_band: float, + limits: tuple[float, float], defective: Mapping[str, str], ) -> tuple[dict[str, Any], dict[str, list[float]], list[dict]]: """The state parents of the concepts that only the district file has. @@ -659,9 +714,10 @@ def _bridged_state_parents( basis by a sibling concept that both files carry: the row is multiplied by the sibling's Historic Table 2 level over its district-file level in the same state. The sibling is trusted only if that ratio, and the factor of - its own district block, sit within ``factor_band`` of their medians across - states. After the re-pin Historic Table 2 holds the six parents, and this - function and ``level_bridges`` go. + its own district block, sit within ``limits`` of their medians across + states: the lowest and the highest ratio to the median that the bound of + the district bridge allows. After the re-pin Historic Table 2 holds the + six parents, and this function and ``level_bridges`` go. Returns the lifted state rows by name, the factors by measure, and the verdicts that refused a sibling. @@ -699,7 +755,7 @@ def trusted( sibling_key: tuple, ratio: float, median: float, measure: str, verdict: str ) -> bool: relative = ratio / median if math.isfinite(ratio) and median else math.nan - ok = math.isfinite(relative) and 1 / factor_band <= relative <= factor_band + ok = math.isfinite(relative) and limits[0] <= relative <= limits[1] if not ok: verdicts.append( { @@ -1221,7 +1277,8 @@ def county_soi_surface( ) selector = bounded_selector(COUNTY_SOI, factor_band) - bridges, _unpaired = expand_bridge_selectors([selector], targets) + bridges, unpaired = expand_bridge_selectors([selector], targets) + refuse_unpaired(COUNTY_SOI, unpaired) outcomes, operator_receipt = run_pass( COUNTY_SOI, rows, @@ -1386,10 +1443,11 @@ def county_acs_household_surface( rows: list[SurfaceRow] = [] legs: dict[str, str] = {} checked = [] + derive = DERIVATIONS[us_derivation(COUNTY_ACS_HOUSEHOLDS)] 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 = controls.sum_of_lower_rows(public) + total = derive(public) if not codes or total <= 0: raise ValueError( f"ACS county households for state {state:02d} have no positive " diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_cd_properties.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_cd_properties.py index a477369a9f..ba2d2c4aca 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_cd_properties.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_cd_properties.py @@ -17,6 +17,7 @@ from __future__ import annotations +import dataclasses import importlib.util import math @@ -855,3 +856,46 @@ def test_a_concept_with_two_parent_sources_is_refused() -> None: crosswalk=crosswalk, level_bridges={"charitable_amount": "return_count"}, ) + + +def test_a_block_that_leaves_the_surface_still_holds_its_members() -> None: + """A distrusted level bridge drops its block. An incomplete block is refused.""" + + ratios = {"10": 1.0, "11": 1.0, "12": 1.0, "13": 1.0, "14": 2.0} + specs, crosswalk = _bridge_world(ratios, {}) + + def surface(candidates): + return _CD.state_cd_soi_surface( + candidates, + state_surface_predicate=_TOOL.soi_surface_predicate("state"), + crosswalk=crosswalk, + level_bridges={"charitable_amount": "return_count"}, + ) + + # State 14's bridge is out of band, so its charitable block is dropped. + assert ( + surface(specs).receipt["dropped"]["level_bridge_out_of_band:charitable_amount"] + == 3 + ) + # The same block with one district absent is refused, as a kept block is. + incomplete = [ + spec for spec in specs if spec.name != "cdfile.1402.charitable_amount" + ] + with pytest.raises( + ValueError, + match=r"leg 'state:14': missing \['congressional_district:1402'\]", + ): + surface(incomplete) + + +def test_a_district_row_that_appears_twice_is_refused() -> None: + specs, crosswalk = _bridge_world({"10": 1.0, "11": 1.0, "12": 1.0}, {}) + twin = next(spec for spec in specs if spec.name == "cdfile.1001.return_count") + twice = [*specs, dataclasses.replace(twin, name="cdfile.1001.return_count.copy")] + with pytest.raises(ValueError, match=r"repeated \['congressional_district:1001'\]"): + _CD.state_cd_soi_surface( + twice, + state_surface_predicate=_TOOL.soi_surface_predicate("state"), + crosswalk=crosswalk, + level_bridges={"charitable_amount": "return_count"}, + ) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_cross_grain_coverage.py b/packages/microcosm-build/tests/engine_free/us/test_us_cross_grain_coverage.py index 7c342f8bf6..91508c1fb1 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_cross_grain_coverage.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_cross_grain_coverage.py @@ -9,8 +9,10 @@ - the eight rows of the issue each have one entry, and each compile rule names code that exists; - ``us_cross_grain_coverage_violations`` finds a family at a lower level that - nothing covers, a declaration whose rows are gone, a compile rule whose - marker is on no row, and a subset that is larger than its whole; + nothing covers, a role that two levels measure with no relation of its own, + a declaration whose rows are gone, a compile rule whose marker is on no + row, a subset that is larger than its whole, and a whole that is not one + positive row; - on the pinned feed, the compiled registry has no violation. That test runs only when ``MICROCOSM_US_CHRONICLE_FACTS`` names the pinned feed, because ``main`` has no committed list of the US families and levels. @@ -123,8 +125,13 @@ def _covered_specs() -> list: if marker else {} ) + # An entry that lists roles is about rows that carry them. specs += [ - _spec(entry["family"], level, **metadata) for level in entry["levels"] + _spec(entry["family"], level, **metadata, **role) + for level in entry["levels"] + for role in ( + [{"target_role": name} for name in entry.get("roles", ())] or [{}] + ) ] return specs @@ -205,6 +212,77 @@ def with_part(family: str, role: str, value: float) -> list: assert violation["where"].startswith("cms_medicaid.medicaid_enrollment@state is ") +def test_a_role_at_two_levels_needs_a_relation_of_its_own() -> None: + """A family is covered as a whole, so a new role in it must not pass unseen.""" + + covered = _covered_specs() + # A new role of a covered family, at state level and at the top level. + two_levels = [ + *covered, + _spec("usda_snap", "state", 5.0, target_role="snap_new_role"), + _spec("usda_snap", "country", 9.0, target_role="snap_new_role"), + ] + assert declarations.us_cross_grain_coverage_violations(two_levels) == [ + { + "kind": "role_at_two_levels_without_relation", + "family": "usda_snap", + "level": "state", + "where": "usda_snap.snap_new_role", + } + ] + # A known gap can list the role: then the gap is declared, with its issue. + listed = [ + *covered, + _spec("irs_soi", "country", 9.0, target_role="soi_fiscal_distribution"), + ] + assert declarations.us_cross_grain_coverage_violations(listed) == [] + # The rows of the gap are there, and none carries the role it lists. + without_listed_role = [ + _spec(spec.family, spec.metadata["ledger_geography_level"]) + if spec.metadata.get("target_role") == "population_age" + else spec + for spec in covered + ] + assert declarations.us_cross_grain_coverage_violations(without_listed_role) == [ + { + "kind": "stale_declaration", + "family": "census_population", + "level": "state", + "where": "population_age", + } + ] + # A role at one level only measures nothing twice. + one_level = [*covered, _spec("usda_snap", "state", 5.0, target_role="snap_other")] + assert declarations.us_cross_grain_coverage_violations(one_level) == [] + + +def test_a_subset_whole_must_be_one_positive_row() -> None: + covered = _covered_specs() + second_whole = [ + *covered, + _spec("usda_snap", "country", 100.0, target_role="snap_total"), + ] + assert declarations.us_cross_grain_coverage_violations(second_whole) == [ + { + "kind": "subset_whole_not_one_positive_row", + "family": "usda_snap", + "level": "country", + "where": "usda_snap.snap_total@country holds 2 row(s)", + } + ] + negative = [ + _spec(spec.family, "country", -100.0, **spec.metadata) + if spec.family == "usda_snap" + and spec.metadata.get("target_role") == "snap_total" + and spec.metadata["ledger_geography_level"] == "country" + else spec + for spec in covered + ] + (violation,) = declarations.us_cross_grain_coverage_violations(negative) + assert violation["kind"] == "subset_whole_not_one_positive_row" + assert violation["where"] == "usda_snap.snap_total@country holds 1 row(s)" + + def test_the_coverage_check_is_a_receipt_and_refuses_nothing() -> None: specs = [*_covered_specs(), _spec("usda_wic", "state")] receipt = declarations.us_cross_grain_coverage_receipt(specs) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_cross_grain_declarations.py b/packages/microcosm-build/tests/engine_free/us/test_us_cross_grain_declarations.py index e5f7bbde38..69fb3a26e2 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_cross_grain_declarations.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_cross_grain_declarations.py @@ -188,6 +188,38 @@ def test_the_allocators_are_declared_to_go_at_the_feed_repin() -> None: assert declarations.us_allocator_name("another_pass") is None +def test_a_derived_control_names_a_derivation_that_the_adapter_runs() -> None: + assert declarations.us_derivation(declarations.COUNTY_ACS_HOUSEHOLDS) == ( + "sum_of_lower_rows" + ) + assert set(declarations.US_DERIVATIONS) == set(target_nesting.DERIVATIONS) + with pytest.raises(ValueError, match="Unknown US cross-grain derived control"): + declarations.us_derivation(declarations.COUNTY_SOI) + + +def test_the_limits_of_a_bound_and_a_lower_target_with_no_pair() -> None: + district = declarations.us_bridge_selector(declarations.DISTRICT_SOI) + assert target_nesting.bound_limits(district) == (0.8, 1.25) + unbounded = declarations.us_bridge_selector( + declarations.DISTRICT_SOI, bounded=False + ) + assert target_nesting.bound_limits(unbounded) == (0.0, float("inf")) + # A band that a caller asks for, as a ratio to the median. + wider = target_nesting.bounded_selector(declarations.COUNTY_SOI, 1.5) + assert target_nesting.bound_limits(wider) == pytest.approx((1 / 1.5, 1.5)) + assert target_nesting.bounded_selector( + declarations.COUNTY_SOI, 1.25 + ) == declarations.us_bridge_selector(declarations.COUNTY_SOI) + # A lower target that the selector pairs with nothing has no control. + unpaired = {declarations.COUNTY_SOI: ("county_file|wages|2022",)} + with pytest.raises(ValueError, match="pairs no higher target"): + target_nesting.refuse_unpaired(declarations.COUNTY_SOI, unpaired) + target_nesting.refuse_unpaired( + declarations.COUNTY_SOI, unpaired, own_control=["county_file|wages|2022"] + ) + target_nesting.refuse_unpaired(declarations.COUNTY_SOI, {}) + + def test_a_selector_is_the_operators_selector() -> None: district = declarations.us_bridge_selector(declarations.DISTRICT_SOI) assert district == CrossGrainBridgeSelector( @@ -285,6 +317,27 @@ def _tampered(change) -> dict: ), "must name a declared pass and one of", ), + (lambda d: d.update(inventory=[]), "unknown key"), + ( + lambda d: d.update(bridges=[{"bridge_id": "by_id"}]), + "no US pass runs them yet", + ), + ( + lambda d: d.update(partitions=[{"partition_id": "bands"}]), + "no US pass runs them yet", + ), + ( + lambda d: d["relations"][0].update( + part=d["relations"][0]["whole"], whole=d["relations"][0]["part"] + ), + "a lower level than its whole", + ), + ( + lambda d: d["until_the_feed_repin"]["compile_rules"][0].update( + higher_level="tract" + ), + "a reason and an issue", + ), (lambda d: d["relations"][0].update(relation="equal"), "is malformed"), (lambda d: d["relations"][0].update(reason=""), "is malformed"), ( From ff0b9fa15207c936eb3aa0f7bf56c5df371ed835 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Fri, 27 Nov 2026 19:19:07 +0000 Subject: [PATCH 21/23] Refuse targets and district receipts that a materialize stage of older code wrote MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From the adversarial review of PR #1791 (microcosm#1760), finding 4, on María's go of 27 Nov 2026 ("Fix all"). A run that is resumed across the change of the metadata keys reads files of older code. The run identity holds no code hash, so nothing stopped it: calibrate failed with a text about concept groups, finalize wrote an empty value in one reviewed limitation, and a county report could lose the SOI evidence of the county that a combined cell covers. - The checkpoint loader refuses a target_registry.json or a target_roles.json that holds a key with the prefix state_cd_ or state_county_. - The finalize stage refuses a district receipt in materialize_rss.json that holds rebase_factor_by_measure, factor_band or internal_consistency. Each refusal says that the file was materialized by older code and to run --stage materialize again. No key of this code has one of the two prefixes. Co-Authored-By: Claude Fable 5.2 --- .../us/test_us_acs_local_sparse_cd.py | 61 ++++++++++++++++++- tools/build_us_acs_local_release.py | 10 +++ tools/us_acs_local_cd_surface.py | 47 ++++++++++++++ 3 files changed, 117 insertions(+), 1 deletion(-) 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 8f5745e638..3a41ceda0a 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 @@ -21,7 +21,7 @@ import pytest from scipy import sparse -from microcosm.calibrate import TargetSpec +from microcosm.calibrate import TargetRegistry, TargetSpec from microcosm.calibrate.matrix import build_constraint_matrix from microcosm.calibrate.target import TargetSet from microcosm.frame import US_SCHEMA, Frame, SharedColumnChangedError @@ -717,11 +717,70 @@ def test_checkpoint_refuses_changed_bytes_and_dense_predecessors(tmp_path) -> No ) with pytest.raises(ValueError, match="row-aligned"): module.write_lean_checkpoint(struct, matrix, specs, records[::-1], checkpoint) + # Targets that older code saved (before microcosm#1760) carry the retired + # nesting keys. This code would read no parent from them: refuse them. + roles_path = checkpoint / module.TARGET_ROLES_FILENAME + registry_path = checkpoint / "target_registry.json" + saved_roles, saved_registry = roles_path.read_text(), registry_path.read_text() + old_roles = json.loads(saved_roles) + old_roles[1]["state_cd_parent_target_name"] = "t0" + roles_path.write_text(json.dumps(old_roles)) + with pytest.raises(SystemExit, match="target_roles.json holds the metadata key"): + module.load_checkpoint_surface(checkpoint) + roles_path.write_text(saved_roles) + TargetRegistry( + [ + specs[0], + dataclasses.replace(specs[1], metadata={"state_county_share": "0.5"}), + ], + country="us", + ).to_json(registry_path) + with pytest.raises(SystemExit, match="target_registry.json holds the metadata key"): + module.load_checkpoint_surface(checkpoint) + registry_path.write_text(saved_registry) + module.load_checkpoint_surface(checkpoint, identity) (checkpoint / module.TARGET_MATRIX_FILENAME).unlink() with pytest.raises(SystemExit, match="predates the sparse target matrix"): module.load_checkpoint_surface(checkpoint, identity) +def test_targets_and_receipts_of_older_code_are_refused() -> None: + """A stage that resumes on files of older code must not read them in silence.""" + + module = _load_tool_module() + cd_surface = module.cd_surface + record = {"name": "cd_0601_agi", "family": "irs_soi", "role": "train"} + spec = TargetSpec( + name="county_15009__agi", + entity="household", + measure="county_15009__agi", + value=1.0, + source="x", + metadata={"county_fips": "15009", "cross_grain_parent": "agi"}, + ) + # Records and specs of this code pass. + cd_surface.refuse_targets_of_older_code([record, spec], where="targets") + for key in ( + "state_cd_parent_target_name", + "state_cd_cd_file_value", + "state_county_parent_target_name", + "state_county_cell_members", + ): + old_spec = dataclasses.replace(spec, metadata={**spec.metadata, key: "x"}) + for target in ({**record, key: "x"}, old_spec): + with pytest.raises(SystemExit, match=f"holds the metadata key '{key}'"): + cd_surface.refuse_targets_of_older_code([record, target], where="t") + # The district receipt of older code names its factors under other fields. + new_receipt = {"soi_mode": "state_cd", "soi_surface": {"factor_by_measure": {}}} + assert module.state_cd_reviewed_limitations(new_receipt) + for field in cd_surface.RETIRED_SURFACE_RECEIPT_FIELDS: + old_receipt = {"soi_mode": "state_cd", "soi_surface": {field: {}}} + with pytest.raises(SystemExit, match="materialized by older code"): + module.state_cd_reviewed_limitations(old_receipt) + # Another mode has no district receipt to read. + assert module.state_cd_reviewed_limitations({"soi_mode": "state"}) == [] + + def test_holdout_scoring_against_the_pro_rata_baseline() -> None: module = _load_tool_module() cd_surface = module.cd_surface diff --git a/tools/build_us_acs_local_release.py b/tools/build_us_acs_local_release.py index d8e02c819a..cce6064062 100644 --- a/tools/build_us_acs_local_release.py +++ b/tools/build_us_acs_local_release.py @@ -3135,6 +3135,10 @@ def load_checkpoint_surface(checkpoint_dir: Path, identity: dict | None = None): f"materialize with the current tool. {error}" ) from error roles = json.loads(roles_path.read_text()) + # Targets written before microcosm#1760 name their parent, their value + # before and their factor under keys that this code does not read. + cd_surface.refuse_targets_of_older_code(registry.specs, where=registry_path.name) + cd_surface.refuse_targets_of_older_code(roles, where=TARGET_ROLES_FILENAME) matrix = cd_surface.load_target_matrix(matrix_path) frame, design_weights = load_lean_frame(checkpoint_dir / "target_frame_lean.h5") n_households = frame.n("household") @@ -5110,6 +5114,11 @@ def state_cd_reviewed_limitations(materialize_rss: dict) -> list[dict]: if materialize_rss.get("soi_mode") != SOI_MODE_STATE_CD: return [] surface = materialize_rss.get("soi_surface") or {} + # A receipt of older code names its factors under another field, and the + # limitation below would record nothing for them. + cd_surface.refuse_surface_receipt_of_older_code( + surface, where="materialize_rss.json (soi_surface)" + ) holdout = materialize_rss.get("cd_holdout") or {} excluded = surface.get("excluded_cd_states") or {} exclusion = ( @@ -6012,6 +6021,7 @@ def do_finalize(args) -> None: roles_path = args.checkpoint_dir / TARGET_ROLES_FILENAME if roles_path.is_file(): targets = json.loads(roles_path.read_text()) + cd_surface.refuse_targets_of_older_code(targets, where=TARGET_ROLES_FILENAME) elif registry_path.is_file(): registry = TargetRegistry.from_json(registry_path) targets = [ diff --git a/tools/us_acs_local_cd_surface.py b/tools/us_acs_local_cd_surface.py index cc20ecc9a8..b2b398ee43 100644 --- a/tools/us_acs_local_cd_surface.py +++ b/tools/us_acs_local_cd_surface.py @@ -802,6 +802,53 @@ def measure(frame) -> np.ndarray: # --------------------------------------------------------------------------- +#: The metadata keys of district and county rows until microcosm#1760, when +#: the keys of the shared cross-grain operator (``cross_grain_*``) replaced +#: them, and the fields of the district receipt that went with them. A saved +#: target or receipt that still holds one was written by older code. A later +#: stage that read it with this code would find no parent, no value before +#: and no factor, without an error. +RETIRED_NESTING_KEY_PREFIXES = ("state_cd_", "state_county_") +RETIRED_SURFACE_RECEIPT_FIELDS = ( + "rebase_factor_by_measure", + "factor_band", + "internal_consistency", +) +_OLDER_CODE = ( + "it was materialized by older code, before the keys of the shared " + "cross-grain operator (microcosm#1760). Re-run --stage materialize with " + "the current tool." +) + + +def refuse_targets_of_older_code(targets, *, where: str) -> None: + """Refuse saved targets that carry the retired nesting keys. + + ``targets`` are role records (mappings) or specs (their metadata is + read). ``where`` names the file, for the message. + """ + + for target in targets: + metadata = target if isinstance(target, Mapping) else target.metadata + retired = sorted( + key + for key in metadata + if str(key).startswith(RETIRED_NESTING_KEY_PREFIXES) + ) + if retired: + raise SystemExit( + f"{where} holds the metadata key {retired[0]!r}: {_OLDER_CODE}" + ) + + +def refuse_surface_receipt_of_older_code(surface: Mapping, *, where: str) -> None: + """Refuse a saved district surface receipt with the retired fields.""" + + retired = sorted(set(RETIRED_SURFACE_RECEIPT_FIELDS) & set(surface)) + if retired: + raise SystemExit(f"{where} holds the field {retired[0]!r}: {_OLDER_CODE}") + + def target_record(spec) -> dict: """The target_roles.json record for one admin spec (metadata subset).""" From 672e82936c92ff565257894bb766eb075c15dee8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Fri, 27 Nov 2026 19:19:07 +0000 Subject: [PATCH 22/23] Correct the pages after the review of the nesting PR From the adversarial review of PR #1791 (microcosm#1760), findings 3, 5, 7, 10 and 11. - Two sentences from Stage A said that every metadata key and receipt, and the bytes of the surface, were as before. Step 2 made them untrue. - docs/us-target-nesting.md: what the removed self-consistency check leaves open for the six concepts that only the district file has; the two refusals that were lost and are back; a band of 2.0 or more is refused; the guard for a run resumed across the change; which proofs run in CI and which only where the pinned inputs are; what the coverage check proves and what it does not; that the pairs that are not reconciled are read by the coverage check only. Co-Authored-By: Claude Fable 5.2 --- ...s-target-nesting-on-cross-grain.changed.md | 2 +- docs/us-acs-local-county-rung.md | 5 +- docs/us-acs-local-soi-target-surface.md | 6 +- docs/us-target-nesting.md | 108 +++++++++++++++--- 4 files changed, 98 insertions(+), 23 deletions(-) diff --git a/changelog.d/1760-us-target-nesting-on-cross-grain.changed.md b/changelog.d/1760-us-target-nesting-on-cross-grain.changed.md index 02c6ed837d..97510c70ce 100644 --- a/changelog.d/1760-us-target-nesting-on-cross-grain.changed.md +++ b/changelog.d/1760-us-target-nesting-on-cross-grain.changed.md @@ -1 +1 @@ -The US nests its local target rows on the shared cross-grain operator that the UK uses (`microcosm.build.cross_grain`), with no target change (microcosm#1760). The operator gains general options that the UK does not declare, so the UK outputs are the same; the UK graph hashes the file, so UK target nodes and the nodes after them compute again on the next UK run. The options: a bound of a bridge measured from the median factor, one-sided, that can unbind a leg; the declared members of a leg; bridge selectors; an optional `allocator`; and `cross_grain_metadata`, the keys of a reconciled row. The shared `microcosm.build.cross_grain_controls` holds the row-level pass (`reconcile_rows`) and the allocators that keep the US values bit for bit until the feed re-pin. `us/cross_grain_declarations.json` declares the US choices under the UK's key names (bridge selectors, a derived control, relations, local routes, members). `state_cd_soi_surface`, `with_county_populations`, `state_county_soi_surface` and `acs_household_surface` keep their names and signatures, and each target value on the pinned feed and ladder is the value it was. **The metadata keys change**: district and county rows carry `cross_grain_parent`, `cross_grain_value_before`, `cross_grain_factor`, `cross_grain_control` and `cross_grain_members` in place of the `state_cd_*` and `state_county_*` keys, and the district receipt takes the fields `bridge`, `level_bridge_out_of_band` and `factor_by_measure`. So the bytes of the `state_cd` registry, roles and receipts move. A refusal that the operator makes has the operator's text; the check that the district file agrees with itself is gone (the compile holds that sum); a concept with two parent sources is refused. The county SOI bridge declares the bound of the district bridge (1.25 around the median factor across states, unbind): a state outside it loses its county rows of that measure and the receipt names it; no state is outside it on the pinned county facts, so no county value changes. The materialize stage also writes the operator's receipts to `target_nesting.json`. See `docs/us-target-nesting.md`. +The US nests its local target rows on the shared cross-grain operator that the UK uses (`microcosm.build.cross_grain`), with no target change (microcosm#1760). The operator gains general options that the UK does not declare, so the UK outputs are the same; the UK graph hashes the file, so UK target nodes and the nodes after them compute again on the next UK run. The options: a bound of a bridge measured from the median factor, one-sided, that can unbind a leg; the declared members of a leg; bridge selectors; an optional `allocator`; and `cross_grain_metadata`, the keys of a reconciled row. The shared `microcosm.build.cross_grain_controls` holds the row-level pass (`reconcile_rows`) and the allocators that keep the US values bit for bit until the feed re-pin. `us/cross_grain_declarations.json` declares the US choices under the UK's key names (bridge selectors, a derived control, relations, local routes, members). `state_cd_soi_surface`, `with_county_populations`, `state_county_soi_surface` and `acs_household_surface` keep their names and signatures, and each target value on the pinned feed and ladder is the value it was. **The metadata keys change**: district and county rows carry `cross_grain_parent`, `cross_grain_value_before`, `cross_grain_factor`, `cross_grain_control` and `cross_grain_members` in place of the `state_cd_*` and `state_county_*` keys, and the district receipt takes the fields `bridge`, `level_bridge_out_of_band` and `factor_by_measure`. So the bytes of the `state_cd` registry, roles and receipts move. A refusal that the operator makes has the operator's text; the check that the district file agrees with itself is gone (the compile holds that sum); a concept with two parent sources is refused. The county SOI bridge declares the bound of the district bridge (1.25 around the median factor across states, unbind): a state outside it loses its county rows of that measure and the receipt names it; no state is outside it on the pinned county facts, so no county value changes. A later stage refuses targets or a district receipt that a materialize stage of older code wrote, and says to run `--stage materialize` again. The materialize stage also writes the operator's receipts to `target_nesting.json`. See `docs/us-target-nesting.md`. diff --git a/docs/us-acs-local-county-rung.md b/docs/us-acs-local-county-rung.md index 1a468be3b6..471851cd13 100644 --- a/docs/us-acs-local-county-rung.md +++ b/docs/us-acs-local-county-rung.md @@ -13,8 +13,9 @@ Since microcosm#1760 the three share mechanisms of the rung (county population, county SOI shares, county households) run on the shared cross-grain operator, through `us_runtime.target_nesting`, with their choices declared in `us/cross_grain_declarations.json`. The tool functions keep their -names, and every row, metadata key and receipt is as it was. See -[US target nesting](us-target-nesting.md). +names, and every row has the value it had. The metadata keys and the receipts +changed with microcosm#1760: the rows carry the operator's `cross_grain_*` +keys. See [US target nesting](us-target-nesting.md). ## Plan and invariants diff --git a/docs/us-acs-local-soi-target-surface.md b/docs/us-acs-local-soi-target-surface.md index 13fca17df5..9e5d39db5d 100644 --- a/docs/us-acs-local-soi-target-surface.md +++ b/docs/us-acs-local-soi-target-surface.md @@ -182,8 +182,10 @@ every state concept has one vintage. The rule is `us_acs_local_cd_surface.state_cd_soi_surface`. Since microcosm#1760 that function calls `us_runtime.target_nesting.district_soi_surface`: the shared cross-grain operator divides each state row among its district rows, with the -choices below declared in `us/cross_grain_declarations.json`. The surface has -the bytes it had. See [US target nesting](us-target-nesting.md). +choices below declared in `us/cross_grain_declarations.json`. Each row has the +value it had. The metadata keys and the receipt changed with microcosm#1760, +so the bytes of the surface moved. See +[US target nesting](us-target-nesting.md). ### One vintage per state concept diff --git a/docs/us-target-nesting.md b/docs/us-target-nesting.md index cec5f03743..11444f31aa 100644 --- a/docs/us-target-nesting.md +++ b/docs/us-target-nesting.md @@ -31,7 +31,7 @@ target values only, never loss weights. | Part | Where | What it holds | |---|---|---| | The operator | `microcosm.build.cross_grain` | Grouping, the control of each leg, bridges and bridge selectors, the bound of a bridge, the members of a leg, the division, the sum check, the receipt, and the metadata keys of a reconciled row. Shared with the UK | -| The row-level pass | `microcosm.build.cross_grain_controls` | `reconcile_rows` runs the operator on target rows and says what it did with each row. `sum_of_lower_rows` is the arithmetic of a derived control. The three allocators stay until the feed re-pin. No country in it | +| The row-level pass | `microcosm.build.cross_grain_controls` | `reconcile_rows` runs the operator on target rows and says what it did with each row. It refuses two shapes for which that answer would be wrong: a row under two controls, and a leg id that holds `+`. `sum_of_lower_rows` is the arithmetic of a derived control. The three allocators stay until the feed re-pin. No country in it | | The US declaration | `us/cross_grain_declarations.json` | The US choices, under the key names of `uk/cross_grain_declarations.json` | | The reader | `us_runtime/cross_grain_declarations.py` | Typed views of the declaration, and the coverage check | | The US adapter | `us_runtime/target_nesting.py` | Which specs or facts are the rows of each pass, the checks that are US rules, and the specs made from the operator's answer | @@ -43,8 +43,10 @@ controls. ## The model -The model has six things. Each one is general: a country declares it, and the -shared code runs it. +The model has six things, and each one is general: no construct is for one +country only. The shared operator runs the first five. The sixth, the pairs +that are not reconciled, is read only by the coverage check (a test and a +receipt); no build acts on it. | Thing | What it is | In the US declaration | |---|---|---| @@ -53,7 +55,7 @@ shared code runs it. | Derived control | A control that no source publishes as one row | `derived_controls`: a state's households are the sum of its county estimates | | Bound | The limits on the factor of a bridge, around one or around the median factor across the legs, and the action out of bound: `refuse` the pass or `unbind` the leg | Both selectors: +0.25 and -0.20 around the median, `unbind` | | Members | The members that each leg must hold. A member can stand for two geographies | `members`: the districts of the current plan; the counties of the ladder, with one combined cell | -| Not reconciled | A pair of levels that is not scaled, with a reason | `relations` (six `subset` pairs) and `local_routes` (three families with no higher control) | +| Not reconciled | A pair of levels that is not scaled, with a reason | `relations` (eight `subset` pairs) and `local_routes` (three families with no higher control) | `bridges` (by id) and `partitions` are empty in the US file. @@ -89,11 +91,13 @@ stage than the district rows. ### What the operator checks -- **Members.** A leg must hold exactly its declared members: the districts of - the current plan, or the counties of the ladder (less a county that a - combined cell covers). A declared leg with no row is refused in the same - way. -- **The bound** of the district bridge, as above. +- **Members.** A leg must hold each of its declared members one time: the + districts of the current plan, or the counties of the ladder (less a county + that a combined cell covers). A member that is absent, a row of another + area, and a member that two rows hold are refused. A declared leg with no + row is refused in the same way. +- **The bound** of a bridge, as above. A band of 2.0 or more cannot be + declared: the highest shift of a bound is below one. - **Arithmetic.** A total that is not finite, a lower sum below `1e-9` of the control, a control and rows of opposite sign, and rows that do not sum to the control within `1e-9` are refused. @@ -108,6 +112,12 @@ These are US rules, with US texts. - A state with one district on the source plan has no district rows. - The rows of a block and their parent must materialize in the same way. - A concept takes its state parent from one source in every state. + - A block that leaves the surface before the pass (the level bridge of its + state is distrusted) must hold its members all the same. The adapter + checks it with the operator's rule. + - A district-file target that the selector pairs with no Historic Table 2 + target, and that no state row of its own measurement controls, is + refused. - The surface is checked again after the pass: each district block must add up to a bound state parent (`closure_rtol`). - **County population.** The operator refuses a county with no state and a @@ -208,9 +218,16 @@ On valid data the rows and their values are the same. These things differ. text: a leg that does not hold its members, a sum of zero under a control, opposite signs, a county with no state. 3. **One check is gone:** that the district file's own state row is the sum - of its district rows within `1e-6`. Row 4 of the compile makes that sum - hold before this pass runs, and the district file's state row is not a - control of a concept that Historic Table 2 holds. + of its district rows within `1e-6`. Row 4 of the compile scales the + district rows to that state row before this pass runs, so the sum holds. + What this leaves open: for the six concepts that only the district file + has, the district file's state row is the control (2,562 district rows on + the pinned feed). This pass does not check that row 4 ran. If it did not, + district rows that do not sum to their state row would be divided from it + without a refusal. On the pinned feed 22,236 district-file district rows + carry row 4's marker; the 436 that do not are a measure that is never + bound. After the feed re-pin those six concepts take a Historic Table 2 + parent, and the bound of the bridge then guards them. 4. **One refusal is new:** a concept that takes its state parent from Historic Table 2 in some states and from the district file in others. The old code accepted that. It does not occur on the pinned feed. @@ -225,6 +242,46 @@ On valid data the rows and their values are the same. These things differ. zero but is below `1e-9` of its control, a county SOI block under a negative state row, and a control of `-0.0`. None occurs on the pinned feed. +8. **A band of 2.0 or more is refused.** The old code accepted any band. + No command-line flag sets the band, so only a test or a direct caller can + meet this. + +Two refusals of the old code were lost when the passes moved, and are back +with the operator's text: a district block that lacks a district while its +level bridge is distrusted, and a district row that appears two times. + +## A run that is resumed across this change + +A materialize stage of older code wrote targets with the old keys. A later +stage of this code would read no parent, no value before and no factor from +them, without an error. So a later stage refuses such files and names the +cure: run `--stage materialize` again. + +- The checkpoint loader refuses a `target_registry.json` or a + `target_roles.json` that holds a key with the prefix `state_cd_` or + `state_county_`. +- The finalize stage refuses a district receipt in `materialize_rss.json` + that holds `rebase_factor_by_measure`, `factor_band` or + `internal_consistency`. + +## What runs in CI, and what does not + +CI has no feed, no ladder and no county facts file. So these proofs run only +on a machine where `MICROCOSM_US_CHRONICLE_FACTS`, +`MICROCOSM_US_PUMA_LADDER_ARTIFACT` and `MICROCOSM_US_CHRONICLE_COUNTY_FACTS` +name the pinned files, and they skip in CI: + +- the pinned bytes of the four surfaces (`test_us_acs_local_surface_bytes.py`); +- the district rows of the pinned feed against the old code + (`test_us_target_nesting_district.py`); +- the county rows of the pinned inputs against the old code, and their pins + (`test_us_target_nesting_county.py`); +- the coverage of the pinned feed's compiled registry + (`test_us_cross_grain_coverage.py`). + +A commit that breaks one of them keeps CI green. Run these four files with +the three variables set before a merge. CI does run the old code against the +new code on seeded random inputs, and the bit-for-bit tests of the operator. ## The county rows on the pinned inputs @@ -264,12 +321,27 @@ inputs, and it changes no county value. ## The coverage test `test_us_cross_grain_coverage.py` reads the declaration. With the pinned feed -it compiles the registry and checks that each family at a level below -`country` is covered by a selector, a derived control, a same-measurement -entry, a relation, a local route, a compile rule or a known gap; that no -declaration names rows that are gone; that each compile rule's marker is on -rows of its family and levels; and that no `subset` part is larger than its -whole beyond the declared `max_excess`. +it compiles the registry and checks these things: + +- each family at a level below `country` is covered by a selector, a derived + control, a same-measurement entry, a relation, a local route, a compile + rule or a known gap; +- each role that the top level and a lower level both hold is named: by a + relation of its own, or by a compile rule or a known gap that lists the + role. A family is covered as a whole, so without this a new role in a + covered family would pass unseen. On the pinned feed ten roles are at two + levels: eight have a relation (SNAP, Medicaid, CHIP, TANF and the two + premium tax credit roles of Historic Table 2), and two are listed by a + known gap (the general SOI role and the Census age rows); +- no declaration names rows that are gone; +- each compile rule's marker is on a row of its family and levels; +- no `subset` part is larger than its whole beyond the declared + `max_excess`, and each whole is one positive row. + +What it does not prove: that a compile rule marks every row it should (it +asks for one marked row), and anything about a row with no ledger level in +its metadata. The rows that a pass makes are such rows, and their pass +declares them. It is a test of the declaration. It refuses nothing in a build and it is not a release gate. From ca5e864bc0fb0471ddc6d833540c76478862f04e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Sat, 28 Nov 2026 07:28:35 +0000 Subject: [PATCH 23/23] Keep the district property test inside the operator's limit, and test the refusal CI runs the property tests with a fixed seed. On that seed, this test drew a district block of 2.0 under a Historic Table 2 state row of 2,000,000,001, with the bound turned off. The operator refuses a lower total that is below 1e-9 of its control, by design. So the two engine-free jobs failed on this test on each run. A local run draws a random seed, and passed. The test now draws values from 1 to 1e8, so no block is below the limit. The case that CI drew is now a fixed case of the refusal test. Only the test file changes. Co-Authored-By: Claude Fable 5.2 --- .../us/test_us_acs_local_cd_properties.py | 22 ++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_cd_properties.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_cd_properties.py index ba2d2c4aca..92a9ddd3fe 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_cd_properties.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_cd_properties.py @@ -202,7 +202,10 @@ def _state_cd_inputs(draw): measure: measure == "return_count" or draw(st.booleans()) for measure in measures } - positive = st.floats(1.0, 1e10, allow_nan=False, allow_infinity=False) + # The operator refuses a block whose total is below 1e-9 of its control + # (the refusal has its own test). Eight orders of magnitude keep every + # block of this test above that limit, with the bound turned off. + positive = st.floats(1.0, 1e8, allow_nan=False, allow_infinity=False) specs, crosswalk, layout = [], [], {} for state in states: n_districts = draw(st.integers(1, 5)) @@ -384,6 +387,23 @@ def district(index, value): state_surface_predicate=predicate, crosswalk=crosswalk, ) + # The limit is relative to the control: a block of positive rows below + # 1e-9 of its state parent is refused too, also with the bound turned off. + large_parent = _soi_spec( + "ht2.10.adjusted_gross_income", + "adjusted_gross_income", + 2000000001.0, + level="state", + record_set=_HT2, + state="10", + ) + with pytest.raises(ValueError, match=r"vanishing lower-leg total 2\.0"): + _CD.state_cd_soi_surface( + [large_parent, district(1, 1.0), district(2, 1.0)], + state_surface_predicate=predicate, + crosswalk=crosswalk, + factor_band=math.inf, + ) with pytest.raises(ValueError, match="opposite-signed lower and control"): _CD.state_cd_soi_surface( [parent, district(1, -5.0), district(2, -1.0)],