diff --git a/changelog.d/1729-county-rows-loss-cap-scope.added.md b/changelog.d/1729-county-rows-loss-cap-scope.added.md new file mode 100644 index 0000000000..b327402952 --- /dev/null +++ b/changelog.d/1729-county-rows-loss-cap-scope.added.md @@ -0,0 +1 @@ +The ACS local release takes `--county-target-loss-cap-scope`. `run` (default) applies the county profile's loss cap to every row of a county build, as before. `county_rows` applies it to the county rows only, so the state and district rows keep `--target-loss-cap` when county rows join the solve. The caps are declared by level through the shared `target_loss_caps`, and the solver gets the equivalent one-cap loss, so its cap stays one number. Under `county_rows` the summary and `calibration_diagnostics.json` carry a `target_loss_caps` block: the declared caps and the past-cap census against each row's own cap (`row_cap_census`), because the solver's own census reads every row against the equivalent cap (microcosm#1729). diff --git a/changelog.d/1729-shared-area-support.changed.md b/changelog.d/1729-shared-area-support.changed.md new file mode 100644 index 0000000000..c9b6ddcbcb --- /dev/null +++ b/changelog.d/1729-shared-area-support.changed.md @@ -0,0 +1 @@ +`microcosm.build.gates.area_support_gate` takes each floor as optional and gains `minimum_effective_sample_size_ratio`, a floor relative to the area's starting ESS (the rule microcosm#1078 adopted). With the three absolute floors the UK local build declares, its result is unchanged. `microcosm.build.area_support` adds the Kish ESS of each area, the long-form area support table from a weight vector, and the gate's verdict area by area. The ACS local release's district ESS gate declares its floors to the shared gate and lays out the same entry as before; `ess_by_group` and the inline Kish arithmetic are gone from the US tools. The district gate stays report-only by default. `gates.py` is in the UK full-gates kernel's hash, so that node re-keys (microcosm#1729). diff --git a/changelog.d/1729-shared-target-loss-rules.added.md b/changelog.d/1729-shared-target-loss-rules.added.md new file mode 100644 index 0000000000..8b0cf1389c --- /dev/null +++ b/changelog.d/1729-shared-target-loss-rules.added.md @@ -0,0 +1 @@ +Add shared target-loss rules (`microcosm.calibrate.target_loss_rules`): a loss weight and a loss cap for each target from its level, family, value basis and value, with the rule declared by name and parameters. Both countries now compute their loss weights with them, with the same vectors as before, bit for bit: the US formula is the shared rule `sqrt_value_concept_budget`; the UK local rules (`uk_runtime.target_weights`) are `uniform`, `level_equal` and `level_family_equal`, and the UK national `family_equal` (`uk_runtime.national_doctrine`) is `level_equal`. Each country declares its rule names as shared rules. The ACS local release takes `--target-weight-rule` (default: the formula every build has used). The UK problem, national and rotated-holdout kernels hash the shared module, so those UK nodes re-key (microcosm#1729). diff --git a/changelog.d/1729-spine-target-shares.added.md b/changelog.d/1729-spine-target-shares.added.md new file mode 100644 index 0000000000..a7440d85ae --- /dev/null +++ b/changelog.d/1729-spine-target-shares.added.md @@ -0,0 +1 @@ +Add a spine and target diagnostic for any pooled build (`microcosm.calibrate.spine_target_shares`, `tools/spine_target_shares.py`): for each target, the share of its weighted total that each set of rows (spine) carries, against that spine's share of the weight among the records the target is about. It is report-only, reads a saved constraint matrix, weights and spine labels (or an ACS local checkpoint directory), runs no engine and no solve, and can withhold targets with few distinct carriers (microcosm#1729). diff --git a/changelog.d/1729-us-acs-local-l2-anchor.added.md b/changelog.d/1729-us-acs-local-l2-anchor.added.md new file mode 100644 index 0000000000..97cc072c58 --- /dev/null +++ b/changelog.d/1729-us-acs-local-l2-anchor.added.md @@ -0,0 +1 @@ +The ACS local release takes `--l2-anchor` and `--l2-anchor-weights`, which it passes to the shared solver's `l2_anchor` and `l2_anchor_weights`. `initial` (default) is each record's own starting weight, as every solve has used; `uniform` is the mean starting weight; `--l2-anchor-weights FILE` makes the `--l2-lambda` penalty pull toward a declared design without a change to the starting weights. The default adds no keyword to the solve and no key to the solver stamp (microcosm#1729). diff --git a/changelog.d/1729-us-acs-local-weight-bound-reference.added.md b/changelog.d/1729-us-acs-local-weight-bound-reference.added.md new file mode 100644 index 0000000000..c635ead2de --- /dev/null +++ b/changelog.d/1729-us-acs-local-weight-bound-reference.added.md @@ -0,0 +1 @@ +The ACS local release takes `--weight-bound-reference`. `own` (default) bounds each household at `--max-weight-ratio` times its own starting weight, as before. `mean`, `state_mean` and `district_mean` bound it at `--max-weight-ratio` times one shared weight (the mean starting weight overall, or of its state or district), through the solver's `max_weight_reference`, so a donor row gets no larger a bound than the ACS rows beside it. The default adds no keyword to the solve and no key to the solver stamp (microcosm#1729). diff --git a/changelog.d/1729-weight-bound-contract.added.md b/changelog.d/1729-weight-bound-contract.added.md new file mode 100644 index 0000000000..ca7f90885a --- /dev/null +++ b/changelog.d/1729-weight-bound-contract.added.md @@ -0,0 +1 @@ +State one contract for the solver's weight bound (`microcosm.calibrate.weight_bound`, docs/calibration-local-area-machinery.md): `max_weight_ratio` bounds each record against its weight on the frame the solve was given, never against a warm start, and a new frame is a new reference. Tests hold the solver to it. `calibrate` and `solve_constraint_system` take an opt-in `max_weight_reference`: the bound is then `max_weight_ratio` times a declared weight for each record (for example the mean weight, from `weight_bound_reference`), so a record that starts heavier gets no larger a bound. Without it the solve is unchanged byte for byte. `weight_bound_report` measures any weight vector against a reference, report-only. The calibrate parity pin is re-recorded for the edit to `solve.py` (microcosm#1729, microcosm#493). diff --git a/docs/calibration-local-area-machinery.md b/docs/calibration-local-area-machinery.md new file mode 100644 index 0000000000..78d69ea7ab --- /dev/null +++ b/docs/calibration-local-area-machinery.md @@ -0,0 +1,220 @@ +# Shared calibration machinery for local areas + +The UK local build and the US local build each calibrate a pooled file to +targets at several geography levels. This page lists the pieces of that work +that are shared code, what each country declares, and how to turn each option +on. It is the reference for microcosm#1729. + +Two rules hold for every piece: + +- **A default changes nothing.** With the default declarations each build + calls the solver with the arguments it used before and gets the same + weights. An option changes an output only when a build asks for it. +- **Nothing here blocks a release.** The gate and the diagnostics report. A + caller decides what a failure means. + +## What is shared, and what each country declares + +| Piece | Shared code | UK local | US local (ACS) | +|---|---|---|---| +| L2 penalty anchor | `calibrate(l2_anchor=, l2_anchor_weights=)` | `uniform` on the refit stage (`UK_LOCAL_SIZE_REFIT_L2_ANCHOR`) | `--l2-anchor` (default `initial`), `--l2-anchor-weights` | +| Target loss weights | `microcosm.calibrate.target_loss_rules` | `UK_LOCAL_TARGET_WEIGHT_RULE_DECLARATIONS` (`uk_runtime.target_weights`), `UK_NATIONAL_TARGET_WEIGHT_RULE_DECLARATIONS` (`uk_runtime.national_doctrine`) | `US_ACS_LOCAL_TARGET_WEIGHT_RULES`, `--target-weight-rule` | +| Loss cap for a level or a family | `target_loss_caps`, `single_cap_equivalent` | one number (`UK_LOCAL_TARGET_LOSS_CAP`) | one number; `--county-target-loss-cap-scope county_rows` | +| Area support | `gates.area_support_gate`; measurement in `microcosm.build.area_support` | three absolute floors in `uk/gates.json` | `district_ess_collapse_gate` declares a relative and an absolute ESS floor | +| Weight bound | `max_weight_ratio`, `max_weight_reference`; contract in `microcosm.calibrate.weight_bound` | `UK_LOCAL_MAX_WEIGHT_RATIO`, against each record's own weight | `--max-weight-ratio`, `--weight-bound-reference` (default `own`) | +| Which rows carry each target | `microcosm.calibrate.spine_target_shares`, `tools/spine_target_shares.py` | not run | run on a checkpoint | + +## Target loss weights + +A rule gives each target a loss weight from what the target is: its **level** +(nation, state, district, local authority), its **family**, its value +**basis** (`count` or `amount`) and its **value**. A country says what each row +is (`TargetLossRows`) and declares the rule by name with its parameters +(`TargetWeightRule`). + +| Rule | What it does | +|---|---| +| `uniform` | Every target weighs one. | +| `level_equal` | Each level takes one equal share; rows in a level share it equally. | +| `level_family_equal` | Each level takes one equal share, each family in a level one equal share of it. With `count_power` (for example `0.5`), the count rows of a family share its count budget in proportion to `max(abs(value), 1) ** count_power`. | +| `sqrt_value_concept_budget` | The US formula: value weight over its basis mean, a budget for each concept group, an equal split between counts and amounts. It reads no level. | + +Any rule may carry `family_multipliers`. + +- **US.** The default, `concept_budget`, is the formula every build has used. + It is the shared rule `sqrt_value_concept_budget`, and gives the same + weights bit for bit. `--target-weight-rule level_family_equal_sqrt_count` + gives each geography level one equal share of the loss. On the September + surface the state SOI rows held about 90% of the loss weight under the + default. +- **UK.** The UK computes every loss weight with the shared rules. + `uk_runtime.target_weights` says what a UK row is and declares each local + rule name as a shared rule: the doctrine's + `nation_grain_family_equal_sqrt_count` is `level_family_equal` with + `count_power` 0.5, over the UK's own mapping of rows to levels. The national + build's `family_equal` (`uk_runtime.national_doctrine`) is `level_equal` + with each family as one level. The vectors are the same as before, bit for + bit: the tests hold them to verbatim copies of the UK arithmetic as it + stood before the move. + + The shared module is in the hash of the UK nodes that bind loss weights + (`uk.full.problem@1`, the two national kernels and the rotated holdout), so + an edit to a shared rule re-keys them. + +## A loss cap for a level or a family + +The solver's loss is `sum(w * min(abs(miss) / s, cap)) / sum(w)` with one cap. +`target_loss_caps(default, by_level=..., by_family=...)` declares a cap for +each row: one number when nothing is declared, a vector otherwise. A family +cap wins over a level cap, and an override that matches no row is an error. + +The solver needs no change to honor a vector. For row caps `c`, weights `w` +and scales `s`, `single_cap_equivalent` returns + +- `cap0 = sum(w * c) / sum(w)`, +- `w' = w * c / cap0` and `s' = s * c / cap0`. + +Then `w' * min(abs(miss) / s', cap0) == w * min(abs(miss) / s, c)` for every +row and `sum(w') == sum(w)`. The loss value, each row's contribution and the +gradient are those of the loss with row caps. When every row has the same cap +the weights and scales come back unchanged. + +How to read a run with row caps: + +- The solver records the transformed weights and scales, and `cap0` as its + cap. So in `calibration_diagnostics.json` the top-level `past_cap_census` + and each target's `target_loss_scale` and `target_loss_weight` read every + row against `cap0`, not against the row's own cap. +- The declared caps and the census against them are in the `target_loss_caps` + block, in the tool's summary and in the `build` block of + `calibration_diagnostics.json`: the default cap, the cap of each level, the + rows at each cap, each row that is not at the default, and + `past_cap_census` against each row's own cap (`row_cap_census`). A run with + one cap has no such block. + +**US county builds.** By default the county profile's cap (10) applies to +every row of a county build, as before. With +`--county-target-loss-cap-scope county_rows` it applies to the county rows +only, and the state and district rows keep `--target-loss-cap`. The weight +ratio is a bound on records, not on targets, so it stays one number for the +run. + +## Area support + +There is one gate, `microcosm.build.gates.area_support_gate`. It checks every +area of a declared roster against the floors a country declares. Each floor +is optional: `minimum_rows`, `minimum_distinct_sources`, +`minimum_effective_sample_size`, and `minimum_effective_sample_size_ratio`, a +floor relative to the area's starting ESS (the rule microcosm#1078 adopted). + +The UK local build declares the three absolute floors (50 rows, ESS 50 and 50 +distinct sources). With those three and no relative floor the gate gives the +result it always gave: a test holds it to a verbatim copy of the gate as it +stood before the floors became optional, reviewed exclusions included. + +`microcosm.build.area_support` measures what the gate reads: + +- `effective_sample_size_by_group` is the Kish ESS of the records in each + area. +- `area_support_table` builds the long-form table from a weight vector and + each record's area: positive-weight rows, distinct positive-weight source + households, ESS, and the ESS under the starting weights. +- `area_support_floor_table` gives the gate's verdict area by area, with one + flag for each declared floor. + +The US district gate (`us_local_district_ess_collapse` in `us/gates.json`) +declares a relative floor of 0.25 and an absolute floor of 15 to the shared +gate. Its entry in `gate_summary.json` is the same as before. It is +report-only unless a build passes the existing `--district-ess-gate-blocking`. + +## The weight bound + +`max_weight_ratio` is a hard bound on each record: no returned weight exceeds +`max_weight_ratio` times the record's **reference**, which is its weight on +the frame the solve was given. + +1. The reference is the frame, never the warm start. An epoch-batched solve + keeps the bound against the frame's weights on every batch. +2. A new frame is a new reference. A stage whose frame carries an earlier + stage's calibrated weights bounds against those, so two stages at ratio `R` + admit `R ** 2` against the first stage's starting weights. +3. The bound is relative, so a heavy record gets a larger absolute bound. In + the US local file a donor row starts about 27 times heavier than an ACS + row, so its absolute bound is about 27 times higher under the same ratio. + +**A declared reference.** Point 3 is a choice. `calibrate` and +`solve_constraint_system` take `max_weight_reference`, one positive weight for +each record, and then bound each record at `max_weight_ratio` times that +reference. `weight_bound_reference` builds one: `mean`, or `group_mean` for +the mean starting weight of the record's area. The frame's weights still set +the starting point, the mass and the L2 anchor. A record that starts above its +bound starts from the bound, with the mass it gives up spread below the +bounds. Under mass conservation the bounds must admit the total, or the solve +refuses. Without `max_weight_reference` the solve is the historical one, byte +for byte. + +In the US local tool, `--weight-bound-reference mean`, `state_mean` or +`district_mean` turns it on. The default, `own`, is each household's own +starting weight. + +`weight_bound_report` measures any weight vector against a reference: the +largest ratio, the records above the bound, the records that start above it, +and whether the bounds admit the starting mass. Read it on a finished solve +before you turn a declared reference on: in the pooled US file the donor rows +start far above a shared bound at the default ratio, so the bound moves +starting mass off them. + +## Which rows carry each target + +`spine_target_shares` reports, for each target, the share of its weighted +total that each spine's rows carry, against that spine's share of the weight +among the records the target is about. A target that the donor rows carry +almost alone pulls weight onto them. `excess` (share minus mass share) and +`lift` (their ratio) rank the targets. + +The tool reads saved inputs and needs no build: + +```bash +uv run python tools/spine_target_shares.py \ + --us-acs-local-checkpoint /checkpoints --out shares.json --spine +``` + +It reports at the design weights, and at the calibrated weights when +`weights_latest.npz` is in the checkpoint. For any other pooled build pass +`--matrix`, `--weights` and `--spines`. `--minimum-carriers N` withholds a +target that a spine carries with fewer than `N` distinct source households; +pass the disclosure floor for a build on licensed microdata. + +## What only a full build can show + +The tests prove that the default declarations send the solver the same +arguments and return the same arrays on small fixtures, and that the UK +vectors and the UK gate result are those of the code before the move. They do +not run a full ACS local build or a UK build. A full build is the only proof +for the full surface, the full pool and the stages around the solve. + +## What re-keys in the UK graph + +The UK graph hashes the bytes of the modules its kernels name. This work +edits some of them, with the same outputs, so these nodes compute again on +the next run instead of reading a cached result: + +- every UK solve node, through `calibrate.adam@1` (`calibrate/solve.py`); +- the kernels of `uk_runtime/graph_targets.py`, which hash their own module: + `uk.full.target_compilation@1`, `target_selection@1`, `measures@1` and + `problem@1`. The problem also hashes the modules that decide its loss + weights, which now include the shared rules. Those modules are named in + `uk_runtime/target_compile_modules.py` + (`UK_FULL_PROBLEM_LOSS_WEIGHT_MODULE_NAMES`) and no longer imported by + `graph_targets`, so the other three kernels have no import edge to them; +- the kernels of `uk_runtime/graph_national.py`: `uk.full.national_targets@1`, + `national_problem@1`, `national-gates@1` and `national-readback@1`; +- the kernels of `uk_runtime/graph_terminal.py`: the rotated holdout, + `uk.full-gates@1` (which also hashes `build/gates.py`), its preflight, and + the three export kernels; +- outside the UK, the transport gate kernel, which hashes `build/gates.py`. + +The UK spine kernels are not among them. + +No `uk/gates.json` digest, gate replay or receipt moves. The calibrate parity +pin is re-recorded. diff --git a/docs/evidence/spec-engine/us-f0-coverage.json b/docs/evidence/spec-engine/us-f0-coverage.json index 7b76e7220a..b613307197 100644 --- a/docs/evidence/spec-engine/us-f0-coverage.json +++ b/docs/evidence/spec-engine/us-f0-coverage.json @@ -1642,13 +1642,13 @@ "compiler_ir.node_slices" ], "expected": { - "map_sha256": "65677b9b7f7a7504e611451d2d494525efd774aba7dd3ca0b6332dcdb03d8976", - "protocol_sha256": "4fc066840c23d994a6b52a6b510eedd99b6ca5bed522c6837f7ff258b91596eb" + "map_sha256": "20648ca766969baf424f491150ab3d12b3edeb89a0544433e64e88c8efb42bb2", + "protocol_sha256": "c321797d65496f01b3186c83dee038c10dec9ed504d1d08a84b452d5f6538c15" }, "failures": [], "observed": { - "map_sha256": "65677b9b7f7a7504e611451d2d494525efd774aba7dd3ca0b6332dcdb03d8976", - "protocol_sha256": "4fc066840c23d994a6b52a6b510eedd99b6ca5bed522c6837f7ff258b91596eb" + "map_sha256": "20648ca766969baf424f491150ab3d12b3edeb89a0544433e64e88c8efb42bb2", + "protocol_sha256": "c321797d65496f01b3186c83dee038c10dec9ed504d1d08a84b452d5f6538c15" }, "status": "covered" }, @@ -1663,7 +1663,7 @@ "compiler_ir.seed_stream_map" ], "expected": { - "implementation_sha256": "4fc066840c23d994a6b52a6b510eedd99b6ca5bed522c6837f7ff258b91596eb", + "implementation_sha256": "c321797d65496f01b3186c83dee038c10dec9ed504d1d08a84b452d5f6538c15", "protocol": "legacy-v1", "streams": [ "build_model", @@ -1684,7 +1684,7 @@ }, "failures": [], "observed": { - "implementation_sha256": "4fc066840c23d994a6b52a6b510eedd99b6ca5bed522c6837f7ff258b91596eb", + "implementation_sha256": "c321797d65496f01b3186c83dee038c10dec9ed504d1d08a84b452d5f6538c15", "protocol": "legacy-v1", "streams": [ "build_model", @@ -2585,7 +2585,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "9f56635edf7da4efa90d01e6ab263eb5f17267ab4bf5b2ad843d76b27f00cfb2" + "spec_sha256": "b94bfc6a5742de010443938a676d4d34e70df80dd405f89e2ff7a70f747c8107" } }, "report_schema_version": 3, @@ -2595,7 +2595,7 @@ "country": "us", "schema_id": "country_spec", "schema_version": 1, - "spec_sha256": "9f56635edf7da4efa90d01e6ab263eb5f17267ab4bf5b2ad843d76b27f00cfb2" + "spec_sha256": "b94bfc6a5742de010443938a676d4d34e70df80dd405f89e2ff7a70f747c8107" }, "status": "pass" } diff --git a/packages/microcosm-build/src/microcosm/build/area_support.py b/packages/microcosm-build/src/microcosm/build/area_support.py new file mode 100644 index 0000000000..3f491b5ad6 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/area_support.py @@ -0,0 +1,250 @@ +"""Support of each local area: its table and its floors (microcosm#1729). + +A local-area file is reliable in an area only when enough records carry that +area's weight. This module measures that for any country and any pooled +build: + +- :func:`effective_sample_size_by_group` is the Kish effective sample size + (ESS) of the records in each area. +- :func:`area_support_table` builds the long-form support table the gate + reads, from a weight vector and each record's area: positive-weight rows, + distinct positive-weight source households, ESS, and (with the starting + weights) the ESS the area started with. +- :func:`area_support_floor_table` checks each area against each floor a + country declares, one flag column for each floor, for a report that lists + the areas. + +The gate itself is :func:`microcosm.build.gates.area_support_gate`, which +this module re-exports. Each of its floors is optional: ``minimum_rows``, +``minimum_distinct_sources``, ``minimum_effective_sample_size``, and +``minimum_effective_sample_size_ratio``, an ESS floor relative to the area's +starting ESS (the rule microcosm#1078 adopted for US districts). The gate +reports; whether a failure blocks a release is the caller's choice, declared +with the country's gates. +""" + +from __future__ import annotations + +from collections.abc import Sequence + +import numpy as np +import pandas as pd + +from microcosm.build.gates import ( + AREA_SUPPORT_COLUMNS, + area_support_gate, + area_support_required_columns, + checked_area_support_floors, +) +from microcosm.build.gates import AREA_SUPPORT_ESS as ESS +from microcosm.build.gates import AREA_SUPPORT_ROWS as ROWS +from microcosm.build.gates import AREA_SUPPORT_SOURCES as SOURCES +from microcosm.build.gates import AREA_SUPPORT_STARTING_ESS as STARTING_ESS + +__all__ = [ + "AREA_SUPPORT_COLUMNS", + "area_support_floor_table", + "area_support_gate", + "area_support_table", + "effective_sample_size_by_group", +] + +ESS_RATIO = "effective_sample_size_ratio" + + +# --------------------------------------------------------------------------- +# Measuring support +# --------------------------------------------------------------------------- + + +def _checked_weights(weights: Sequence[float] | np.ndarray, label: str) -> np.ndarray: + weights = np.asarray(weights, dtype=np.float64) + if weights.ndim != 1: + raise ValueError(f"{label} must be one-dimensional.") + if not np.isfinite(weights).all() or (weights < 0.0).any(): + raise ValueError(f"{label} must be finite and non-negative.") + return weights + + +def effective_sample_size_by_group( + weights: Sequence[float] | np.ndarray, codes: Sequence | np.ndarray +) -> dict[str, float]: + """Kish ESS, ``(sum w)^2 / sum(w^2)``, of the records in each group. + + Groups are keyed by ``str(code)``, in sorted order. A group whose weights + are all zero has ESS ``0.0``. Refuses negative, NaN or infinite weights, + as :func:`microcosm.calibrate.solve.effective_sample_size` does. + """ + + weights = _checked_weights(weights, "weights") + codes = np.asarray(codes) + if codes.shape != weights.shape: + raise ValueError( + f"{codes.shape} group codes do not align with {weights.shape} weights." + ) + frame = pd.DataFrame({"code": codes.astype(str), "w": weights}) + frame["w2"] = frame["w"] ** 2 + sums = frame.groupby("code", sort=True)[["w", "w2"]].sum() + return { + str(code): float(row.w**2 / row.w2) if row.w2 > 0 else 0.0 + for code, row in sums.iterrows() + } + + +def area_support_table( + weights: Sequence[float] | np.ndarray, + area_codes: Sequence | np.ndarray, + *, + geography_level: str, + source_ids: Sequence | np.ndarray | None = None, + starting_weights: Sequence[float] | np.ndarray | None = None, +) -> pd.DataFrame: + """The support of each area under ``weights``, one row per area. + + Columns: ``geography_level``, ``area_code``, ``nonzero_households`` (the + records with a positive weight), ``effective_sample_size`` (Kish ESS over + records), and + + - with ``source_ids``: ``nonzero_source_households``, the distinct source + households among the positive-weight records. A source id is whatever + identifies one source household across its copies and clones (for a + pooled build, a pair such as spine and source id joined into one key); + - with ``starting_weights``: ``starting_effective_sample_size``, the ESS + of the same records under the weights the solve started from. + + Areas come in sorted order of ``str(area_code)``. An area appears when at + least one record names it, whatever its weight. + """ + + weights = _checked_weights(weights, "weights") + codes = np.asarray(area_codes) + if codes.shape != weights.shape: + raise ValueError( + f"{codes.shape} area codes do not align with {weights.shape} weights." + ) + frame = pd.DataFrame({"area_code": codes.astype(str), "weight": weights}) + positive = frame["weight"] > 0.0 + table = pd.DataFrame( + { + ROWS: positive.groupby(frame["area_code"], sort=True).sum().astype(int), + } + ) + if source_ids is not None: + sources = np.asarray(source_ids) + if sources.shape != weights.shape: + raise ValueError( + f"{sources.shape} source ids do not align with {weights.shape} weights." + ) + distinct = ( + pd.DataFrame({"area_code": frame["area_code"], "source": sources})[ + positive.to_numpy() + ] + .groupby("area_code", sort=True)["source"] + .nunique() + ) + table[SOURCES] = distinct.reindex(table.index, fill_value=0).astype(int) + ess = effective_sample_size_by_group(weights, codes) + table[ESS] = [ess[code] for code in table.index] + if starting_weights is not None: + starting = _checked_weights(starting_weights, "starting_weights") + if starting.shape != weights.shape: + raise ValueError( + f"{starting.shape} starting weights do not align with " + f"{weights.shape} weights." + ) + starting_ess = effective_sample_size_by_group(starting, codes) + table[STARTING_ESS] = [starting_ess[code] for code in table.index] + table = table.reset_index().rename(columns={"index": "area_code"}) + table.insert(0, "geography_level", str(geography_level)) + return table + + +# --------------------------------------------------------------------------- +# Floors +# --------------------------------------------------------------------------- + + +def _checked_rows(area_support: pd.DataFrame, required: Sequence[str]) -> pd.DataFrame: + if not isinstance(area_support, pd.DataFrame): + raise TypeError("area_support must be a pandas DataFrame.") + missing_columns = sorted(set(required) - set(area_support.columns)) + if missing_columns: + raise ValueError( + f"area_support is missing required column(s): {missing_columns}." + ) + rows = area_support.copy() + rows["geography_level"] = rows["geography_level"].astype(str) + rows["area_code"] = rows["area_code"].astype(str) + present = [column for column in AREA_SUPPORT_COLUMNS if column in rows.columns] + values = rows.loc[:, present].to_numpy(dtype=np.float64) + if not np.isfinite(values).all() or (values < 0).any(): + raise ValueError("area_support contains invalid support values.") + return rows + + +def area_support_floor_table( + area_support: pd.DataFrame, + *, + minimum_rows: int | None = None, + minimum_effective_sample_size: float | None = None, + minimum_distinct_sources: int | None = None, + minimum_effective_sample_size_ratio: float | None = None, +) -> pd.DataFrame: + """Each area against each declared floor, one row per area, in input order. + + Beside the input's columns: ``below_`` (bool) for each declared + floor, ``below_any_floor``, and, when the table carries the starting ESS, + ``effective_sample_size_ratio`` (ESS over starting ESS; NaN where the + starting ESS is zero). + + An area is below the relative floor when its ESS is less than + ``minimum_effective_sample_size_ratio`` times its starting ESS. The test + multiplies, so an area whose starting ESS is zero is never below it. + """ + + checked_area_support_floors( + minimum_rows, + minimum_effective_sample_size, + minimum_distinct_sources, + minimum_effective_sample_size_ratio, + ) + rows = _checked_rows( + area_support, + area_support_required_columns( + minimum_rows, + minimum_effective_sample_size, + minimum_distinct_sources, + minimum_effective_sample_size_ratio, + ), + ) + flags: list[str] = [] + if STARTING_ESS in rows.columns and ESS in rows.columns: + ess = rows[ESS].to_numpy(dtype=np.float64) + starting = rows[STARTING_ESS].to_numpy(dtype=np.float64) + ratio = np.full(len(rows), np.nan, dtype=np.float64) + # A ratio too large for a float is infinite, as plain division gives. + with np.errstate(over="ignore"): + np.divide(ess, starting, out=ratio, where=starting > 0) + rows[ESS_RATIO] = ratio + if minimum_rows is not None: + rows["below_minimum_rows"] = rows[ROWS] < minimum_rows + flags.append("below_minimum_rows") + if minimum_effective_sample_size is not None: + rows["below_minimum_effective_sample_size"] = ( + rows[ESS] < minimum_effective_sample_size + ) + flags.append("below_minimum_effective_sample_size") + if minimum_distinct_sources is not None: + rows["below_minimum_distinct_sources"] = ( + rows[SOURCES] < minimum_distinct_sources + ) + flags.append("below_minimum_distinct_sources") + if minimum_effective_sample_size_ratio is not None: + rows["below_minimum_effective_sample_size_ratio"] = rows[ESS] < ( + minimum_effective_sample_size_ratio * rows[STARTING_ESS] + ) + flags.append("below_minimum_effective_sample_size_ratio") + rows["below_any_floor"] = ( + rows[flags].any(axis=1) if flags else np.zeros(len(rows), dtype=bool) + ) + return rows diff --git a/packages/microcosm-build/src/microcosm/build/gates.py b/packages/microcosm-build/src/microcosm/build/gates.py index 85fc8e8f07..1daba7f05b 100644 --- a/packages/microcosm-build/src/microcosm/build/gates.py +++ b/packages/microcosm-build/src/microcosm/build/gates.py @@ -2541,44 +2541,150 @@ def support_gate( ) +#: The support columns of the long-form area support table, beside +#: ``geography_level`` and ``area_code``. A gate needs only the columns of the +#: floors it declares. +AREA_SUPPORT_ROWS = "nonzero_households" +AREA_SUPPORT_SOURCES = "nonzero_source_households" +AREA_SUPPORT_ESS = "effective_sample_size" +AREA_SUPPORT_STARTING_ESS = "starting_effective_sample_size" +AREA_SUPPORT_COLUMNS = ( + AREA_SUPPORT_ROWS, + AREA_SUPPORT_SOURCES, + AREA_SUPPORT_ESS, + AREA_SUPPORT_STARTING_ESS, +) + + +def checked_area_support_floors( + minimum_rows: int | None, + minimum_effective_sample_size: float | None, + minimum_distinct_sources: int | None, + minimum_effective_sample_size_ratio: float | None = None, +) -> None: + """Refuse a floor that is not a valid declaration (``None`` is unchecked).""" + + if minimum_rows is not None and ( + isinstance(minimum_rows, bool) + or not isinstance(minimum_rows, int) + or minimum_rows < 1 + ): + raise ValueError("minimum_rows must be a positive integer.") + if minimum_distinct_sources is not None and ( + isinstance(minimum_distinct_sources, bool) + or not isinstance(minimum_distinct_sources, int) + or minimum_distinct_sources < 1 + ): + raise ValueError("minimum_distinct_sources must be a positive integer.") + if minimum_effective_sample_size is not None and ( + isinstance(minimum_effective_sample_size, bool) + or not math.isfinite(float(minimum_effective_sample_size)) + or minimum_effective_sample_size <= 0 + ): + raise ValueError("minimum_effective_sample_size must be positive and finite.") + if minimum_effective_sample_size_ratio is not None and ( + isinstance(minimum_effective_sample_size_ratio, bool) + or not math.isfinite(float(minimum_effective_sample_size_ratio)) + or not 0.0 < minimum_effective_sample_size_ratio <= 1.0 + ): + raise ValueError("minimum_effective_sample_size_ratio must be in (0, 1].") + + +def area_support_required_columns( + minimum_rows: int | None, + minimum_effective_sample_size: float | None, + minimum_distinct_sources: int | None, + minimum_effective_sample_size_ratio: float | None = None, +) -> list[str]: + """The table columns the declared floors read.""" + + columns = ["geography_level", "area_code"] + if minimum_rows is not None: + columns.append(AREA_SUPPORT_ROWS) + if minimum_distinct_sources is not None: + columns.append(AREA_SUPPORT_SOURCES) + if ( + minimum_effective_sample_size is not None + or minimum_effective_sample_size_ratio is not None + ): + columns.append(AREA_SUPPORT_ESS) + if minimum_effective_sample_size_ratio is not None: + columns.append(AREA_SUPPORT_STARTING_ESS) + return columns + + def area_support_shortfalls( rows: float, effective_sample_size: float, sources: float, *, - minimum_rows: int, - minimum_effective_sample_size: float, - minimum_distinct_sources: int, + minimum_rows: int | None, + minimum_effective_sample_size: float | None, + minimum_distinct_sources: int | None, + starting_effective_sample_size: float | None = None, + minimum_effective_sample_size_ratio: float | None = None, ) -> list[str]: """The support floors one area misses, worded as :func:`area_support_gate` reports them. Each shortfall states the area's measured value beside the floor: the release ships per-area support figures since María's ruling of 2026-10-26, which dropped their withholding (microcosm#1301). + + A floor that is ``None`` is not declared and not checked. The relative + floor (microcosm#1729) is missed when the ESS is below + ``minimum_effective_sample_size_ratio`` times the area's starting ESS. The + test multiplies, so an area whose starting ESS is zero never misses it. """ shortfalls = [] - if rows < minimum_rows: + if minimum_rows is not None and rows < minimum_rows: shortfalls.append(f"rows {int(rows)} < {minimum_rows}") - if effective_sample_size < minimum_effective_sample_size: + if ( + minimum_effective_sample_size is not None + and effective_sample_size < minimum_effective_sample_size + ): shortfalls.append( "ESS " f"{float(effective_sample_size):.6g} < " f"{float(minimum_effective_sample_size):.6g}" ) - if sources < minimum_distinct_sources: + if minimum_distinct_sources is not None and sources < minimum_distinct_sources: shortfalls.append( f"distinct sources {int(sources)} < {minimum_distinct_sources}" ) + if ( + minimum_effective_sample_size_ratio is not None + and effective_sample_size + < minimum_effective_sample_size_ratio * starting_effective_sample_size + ): + shortfalls.append( + "ESS " + f"{float(effective_sample_size):.6g} < " + f"{float(minimum_effective_sample_size_ratio):.6g} x starting ESS " + f"{float(starting_effective_sample_size):.6g}" + ) return shortfalls +def _area_shortfalls(row, floors: Mapping[str, object]) -> list[str]: + """One table row's shortfalls under ``floors`` (undeclared columns unread).""" + + return area_support_shortfalls( + getattr(row, AREA_SUPPORT_ROWS, 0), + getattr(row, AREA_SUPPORT_ESS, 0.0), + getattr(row, AREA_SUPPORT_SOURCES, 0), + starting_effective_sample_size=getattr(row, AREA_SUPPORT_STARTING_ESS, None), + **floors, + ) + + def area_support_below_floor( area_support: pd.DataFrame, *, - minimum_rows: int, - minimum_effective_sample_size: float, - minimum_distinct_sources: int, + minimum_rows: int | None, + minimum_effective_sample_size: float | None, + minimum_distinct_sources: int | None, + minimum_effective_sample_size_ratio: float | None = None, ) -> pd.Series: """Whether each area of a support table misses any floor, by the gate's rule. @@ -2586,18 +2692,22 @@ def area_support_below_floor( below the floor, which is what a consumer of the area's estimates needs. """ + floors = { + "minimum_rows": minimum_rows, + "minimum_effective_sample_size": minimum_effective_sample_size, + "minimum_distinct_sources": minimum_distinct_sources, + "minimum_effective_sample_size_ratio": minimum_effective_sample_size_ratio, + } + missing_columns = sorted( + set(area_support_required_columns(**floors)) - set(area_support.columns) + ) + if missing_columns: + raise ValueError( + f"area_support is missing required column(s): {missing_columns}." + ) return pd.Series( [ - bool( - area_support_shortfalls( - row.nonzero_households, - row.effective_sample_size, - row.nonzero_source_households, - minimum_rows=minimum_rows, - minimum_effective_sample_size=minimum_effective_sample_size, - minimum_distinct_sources=minimum_distinct_sources, - ) - ) + bool(_area_shortfalls(row, floors)) for row in area_support.itertuples(index=False) ], index=area_support.index, @@ -2610,9 +2720,10 @@ def area_support_gate( *, area_roster: Mapping[str, Iterable[str]], geography_levels: Iterable[str], - minimum_rows: int, - minimum_effective_sample_size: float, - minimum_distinct_sources: int, + minimum_rows: int | None = None, + minimum_effective_sample_size: float | None = None, + minimum_distinct_sources: int | None = None, + minimum_effective_sample_size_ratio: float | None = None, reviewed_exclusions: Mapping[str, Mapping[str, object]] | None = None, ) -> GateResult: """Require adequate positive-weight support in every declared local area. @@ -2625,38 +2736,57 @@ def area_support_gate( beside the floors it misses, and each geography level reports how many areas were checked and sit below a floor, and its minima (María's ruling of 2026-10-26 dropped the withholding of microcosm#1301). + + Each floor is a country's declaration, and ``None`` leaves it unchecked + (microcosm#1729). The table needs only the columns of the declared + floors. + + - ``minimum_rows``, ``minimum_effective_sample_size`` and + ``minimum_distinct_sources`` are absolute floors. With these three and + no relative floor, the result is the one this gate always gave. + - ``minimum_effective_sample_size_ratio`` (in ``(0, 1]``) fails an area + whose ESS is below that share of its + ``starting_effective_sample_size``: the rule microcosm#1078 adopted. A + gate that declares it also reports, for each level, how many areas are + below it and the smallest ratio. + + The result reports. Whether a failure blocks a release is the caller's + declaration, not this function's. """ levels = tuple(str(level) for level in geography_levels) if not levels or len(set(levels)) != len(levels): raise ValueError("geography_levels must be non-empty and unique.") - if ( - isinstance(minimum_rows, bool) - or not isinstance(minimum_rows, int) - or minimum_rows < 1 - ): - raise ValueError("minimum_rows must be a positive integer.") - if ( - isinstance(minimum_distinct_sources, bool) - or not isinstance(minimum_distinct_sources, int) - or minimum_distinct_sources < 1 - ): - raise ValueError("minimum_distinct_sources must be a positive integer.") - if ( - not math.isfinite(float(minimum_effective_sample_size)) - or minimum_effective_sample_size <= 0 - ): - raise ValueError("minimum_effective_sample_size must be positive and finite.") + checked_area_support_floors( + minimum_rows, + minimum_effective_sample_size, + minimum_distinct_sources, + minimum_effective_sample_size_ratio, + ) + ratio_floor = ( + None + if minimum_effective_sample_size_ratio is None + else float(minimum_effective_sample_size_ratio) + ) + floors = { + "minimum_rows": minimum_rows, + "minimum_effective_sample_size": ( + None + if minimum_effective_sample_size is None + else float(minimum_effective_sample_size) + ), + "minimum_distinct_sources": minimum_distinct_sources, + "minimum_effective_sample_size_ratio": ratio_floor, + } if not isinstance(area_support, pd.DataFrame): raise TypeError("area_support must be a pandas DataFrame.") - required_columns = { - "geography_level", - "area_code", - "nonzero_households", - "nonzero_source_households", - "effective_sample_size", - } - missing_columns = sorted(required_columns - set(area_support.columns)) + required_columns = area_support_required_columns( + minimum_rows, + minimum_effective_sample_size, + minimum_distinct_sources, + minimum_effective_sample_size_ratio, + ) + missing_columns = sorted(set(required_columns) - set(area_support.columns)) if missing_columns: raise ValueError( f"area_support is missing required column(s): {missing_columns}." @@ -2702,12 +2832,10 @@ def area_support_gate( f"missing={missing_areas[:10]}, extra={extra_areas[:10]}." ) - numeric_columns = ( - "nonzero_households", - "nonzero_source_households", - "effective_sample_size", - ) - values = rows.loc[:, list(numeric_columns)].to_numpy(dtype=np.float64) + numeric_columns = [ + column for column in required_columns if column in AREA_SUPPORT_COLUMNS + ] + values = rows.loc[:, numeric_columns].to_numpy(dtype=np.float64) if not np.isfinite(values).all() or (values < 0).any(): raise ValueError("area_support contains invalid support values.") @@ -2716,29 +2844,29 @@ def area_support_gate( used_exclusions: dict[str, dict[str, object]] = {} stale_exclusions: list[str] = [] below_floor = dict.fromkeys(levels, 0) + below_ratio = dict.fromkeys(levels, 0) for row in rows.sort_values(["geography_level", "area_code"]).itertuples( index=False ): key = f"{row.geography_level}/{row.area_code}" - shortfalls = area_support_shortfalls( - row.nonzero_households, - row.effective_sample_size, - row.nonzero_source_households, - minimum_rows=minimum_rows, - minimum_effective_sample_size=minimum_effective_sample_size, - minimum_distinct_sources=minimum_distinct_sources, - ) + shortfalls = _area_shortfalls(row, floors) if shortfalls: below_floor[row.geography_level] += 1 + if ratio_floor is not None and getattr( + row, AREA_SUPPORT_ESS + ) < ratio_floor * getattr(row, AREA_SUPPORT_STARTING_ESS): + below_ratio[row.geography_level] += 1 record = exclusions.get(key) if record is not None and shortfalls: - used_exclusions[key] = { - "shortfalls": shortfalls, - "rows": int(row.nonzero_households), - "ess": float(row.effective_sample_size), - "sources": int(row.nonzero_source_households), - "record": dict(record), - } + used: dict[str, object] = {"shortfalls": shortfalls} + if AREA_SUPPORT_ROWS in rows.columns: + used["rows"] = int(getattr(row, AREA_SUPPORT_ROWS)) + if AREA_SUPPORT_ESS in rows.columns: + used["ess"] = float(getattr(row, AREA_SUPPORT_ESS)) + if AREA_SUPPORT_SOURCES in rows.columns: + used["sources"] = int(getattr(row, AREA_SUPPORT_SOURCES)) + used["record"] = dict(record) + used_exclusions[key] = used elif record is not None: stale_exclusions.append(key) failures.append( @@ -2758,27 +2886,45 @@ def area_support_gate( by_level: dict[str, dict[str, object]] = {} for level in levels: level_rows = rows.loc[rows["geography_level"] == level] - by_level[level] = { + summary: dict[str, object] = { "areas_checked": int(len(level_rows)), "areas_below_floor": below_floor[level], - "minimum_rows": int(level_rows["nonzero_households"].min()), - "minimum_effective_sample_size": float( - level_rows["effective_sample_size"].min() - ), - "minimum_distinct_sources": int( - level_rows["nonzero_source_households"].min() - ), } + if AREA_SUPPORT_ROWS in level_rows.columns: + summary["minimum_rows"] = int(level_rows[AREA_SUPPORT_ROWS].min()) + if AREA_SUPPORT_ESS in level_rows.columns: + summary["minimum_effective_sample_size"] = float( + level_rows[AREA_SUPPORT_ESS].min() + ) + if AREA_SUPPORT_SOURCES in level_rows.columns: + summary["minimum_distinct_sources"] = int( + level_rows[AREA_SUPPORT_SOURCES].min() + ) + if ratio_floor is not None: + ess = level_rows[AREA_SUPPORT_ESS].to_numpy(dtype=np.float64) + starting = level_rows[AREA_SUPPORT_STARTING_ESS].to_numpy(dtype=np.float64) + rated = starting > 0 + # A ratio too large for a float is infinite, as plain division gives. + with np.errstate(over="ignore"): + ratios = ess[rated] / starting[rated] + summary["areas_below_effective_sample_size_ratio"] = below_ratio[level] + summary["minimum_effective_sample_size_ratio"] = ( + float(ratios.min()) if rated.any() else None + ) + by_level[level] = summary + # A gate that declares no relative floor reports the three absolute + # floors alone, as it always has. + declared_floors = { + key: value + for key, value in floors.items() + if key != "minimum_effective_sample_size_ratio" or value is not None + } return GateResult( name="area_support", passed=not failures, failures=tuple(failures), details={ - "floors": { - "minimum_rows": minimum_rows, - "minimum_effective_sample_size": float(minimum_effective_sample_size), - "minimum_distinct_sources": minimum_distinct_sources, - }, + "floors": declared_floors, "by_geography_level": by_level, "areas_checked": len(expected_pairs), "areas_failed": len(failures), diff --git a/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py b/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py index 0a3ebf244c..acb3e86c87 100644 --- a/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py +++ b/packages/microcosm-build/src/microcosm/build/spec_engine/inventory_coverage.py @@ -415,8 +415,8 @@ # SIPP donor tables are byte-identical, and no draw changes. # The SIPP 2023 donor download tag and the financial-asset cache lookup # move both again: the donor bytes are unchanged, and no draw changes. - "seed_map": "65677b9b7f7a7504e611451d2d494525efd774aba7dd3ca0b6332dcdb03d8976", - "seed_protocol": "4fc066840c23d994a6b52a6b510eedd99b6ca5bed522c6837f7ff258b91596eb", + "seed_map": "20648ca766969baf424f491150ab3d12b3edeb89a0544433e64e88c8efb42bb2", + "seed_protocol": "c321797d65496f01b3186c83dee038c10dec9ed504d1d08a84b452d5f6538c15", "source_manifest": "dc3879886d2a69f20fb982a675d7fb322c0e4017afef6471be54b0ee3cbd2af6", "take_up": "9522ce40f7dea569312dd7a7beb474e5a5afadd2f1e10cb5876534c3ef623d35", "tail": "565f0ceeadab69d3e96a886a00dd0305f7425fa3acde24d12ba48db2b37d5fc0", diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_national.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_national.py index c8a574003f..70345e6d73 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_national.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_national.py @@ -474,6 +474,7 @@ class _NationalKernel(KernelBase): def implementation_hash(self) -> str: import microcosm.calibrate.artifacts as calibrate_artifacts import microcosm.calibrate.matrix as calibrate_matrix + import microcosm.calibrate.target_loss_rules as calibrate_target_loss_rules from . import receipt_counts, weighted_integrity from .target_compile_modules import uk_target_compile_modules @@ -492,6 +493,10 @@ def implementation_hash(self) -> str: measure_simulation, national_calibration, national_doctrine, + # national_doctrine computes the problem's loss weights with the + # shared rules (microcosm#1729): an edit to a shared rule must + # re-key the national problem. + calibrate_target_loss_rules, support_floor_rules, # The constraint matrices and their encoding, as the dense kernels # hash them (microcosm#1492). Not calibrate.solve: neither the diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_targets.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_targets.py index ff981b7994..88f59b7155 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_targets.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_targets.py @@ -16,9 +16,7 @@ import pandas as pd import microcosm.calibrate.artifacts as calibrate_artifacts -import microcosm.calibrate.geography_constants as geography_constants import microcosm.calibrate.matrix as calibrate_matrix -import microcosm.calibrate.solve as calibrate_solve import microcosm.calibrate.target_selection as calibrate_target_selection from microcosm.build import cross_grain from microcosm.calibrate import CalibrationHierarchy, TargetRegistry, TargetSpec @@ -55,8 +53,6 @@ ladder_targets, ledger_targets, local_doctrine, - local_rowwise, - national_doctrine, support_floor, target_weights, ) @@ -668,27 +664,19 @@ class UKFullProblemKernel(_TargetKernel): ref = "uk.full.problem@1" def implementation_hash(self) -> str: - # The loss weights the problem binds are built by - # ``local_rowwise.prepare_uk_full_solve`` from the rules in - # ``target_weights`` and ``national_doctrine`` (microcosm#1124), so an - # edit there re-keys the problem instead of replaying a stale vector. - # ``target_weights`` reads the UK-wide geography codes from - # ``geography_constants``, and the loss scales the problem stores from - # ``calibrate.solve.default_target_loss_scales`` (microcosm#1492). All - # of ``calibrate.solve`` is hashed: ``calibrate.adam@1``, whose hash - # every UK solve kernel embeds, already hashes it, so an edit there - # re-solves anyway and re-keys only this node besides. + # Beside the target modules, the problem hashes the modules that + # decide the loss weights and scales it binds, so an edit to one of + # them re-keys the problem instead of replaying a stale vector. + # ``target_compile_modules`` names them and says why each is there. + # They are named, not imported here: the other kernels of this module + # run none of that code (microcosm#1729). + from .target_compile_modules import uk_full_problem_loss_weight_modules + return hashlib.sha256( canonical_json( { "targets": super().implementation_hash(), - "weights": source_hash( - local_rowwise, - national_doctrine, - target_weights, - geography_constants, - calibrate_solve, - ), + "weights": source_hash(*uk_full_problem_loss_weight_modules()), } ) ).hexdigest() diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_terminal.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_terminal.py index 15f0f6e85b..496fad4f2d 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_terminal.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/graph_terminal.py @@ -1353,6 +1353,8 @@ class UKFullHoldoutKernel(KernelBase): ) def implementation_hash(self) -> str: + import microcosm.calibrate.target_loss_rules as calibrate_target_loss_rules + from . import ( dataset_size, graph_targets, @@ -1374,6 +1376,9 @@ def implementation_hash(self) -> str: local_doctrine, national_doctrine, target_weights, + # The shared rules that compute the weights the + # holdout re-applies (microcosm#1729). + calibrate_target_loss_rules, dependencies=self.capabilities.dependencies, ), # The holdout repeats the solve: it keys on the solve diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/national_doctrine.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/national_doctrine.py index 21f446219a..4ece5be93d 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/national_doctrine.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/national_doctrine.py @@ -10,12 +10,18 @@ from __future__ import annotations -from collections import Counter -from collections.abc import Sequence +from collections.abc import Mapping, Sequence from dataclasses import dataclass, fields, replace +from types import MappingProxyType import numpy as np +from microcosm.calibrate.target_loss_rules import ( + TargetLossRows, + TargetWeightRule, + target_loss_weights_for_rule, +) + __all__ = [ "UK_NATIONAL_LEARNING_RATE", "UK_NATIONAL_L0_LAMBDA", @@ -26,6 +32,7 @@ "UK_NATIONAL_SOLVE_EPOCHS", "UK_NATIONAL_TARGET_LOSS_CAP", "UK_NATIONAL_TARGET_WEIGHT_RULE", + "UK_NATIONAL_TARGET_WEIGHT_RULE_DECLARATIONS", "uk_doctrine_with_overrides", "uk_national_target_loss_weights", "UKNationalSolveDoctrine", @@ -67,6 +74,19 @@ # records no overrides. "uniform" stays vocabulary: a receipted per-run # override, never silently reachable. _ALLOWED_TARGET_WEIGHT_RULES = ("uniform", "family_equal") +#: Each national rule name as a shared rule of +#: :mod:`microcosm.calibrate.target_loss_rules`: the UK's declaration +#: (microcosm#1729). ``family_equal`` is the shared ``level_equal`` with each +#: family as one level: one equal share for each family, divided evenly among +#: its members. +UK_NATIONAL_TARGET_WEIGHT_RULE_DECLARATIONS: Mapping[str, TargetWeightRule] = ( + MappingProxyType( + { + "uniform": TargetWeightRule("uniform"), + "family_equal": TargetWeightRule("level_equal"), + } + ) +) _ALLOWED_MASS_RULES = ("free",) _OVERRIDABLE_FIELDS = frozenset( {"epochs", "learning_rate", "target_weight_rule", "target_loss_cap"} @@ -223,9 +243,8 @@ def uk_national_target_loss_weights( raise ValueError("family_equal weighting requires a non-empty register.") if any(not label for label in labels): raise ValueError("every target must declare a family for family_equal.") - counts = Counter(labels) - family_count = len(counts) - return np.asarray( - [1.0 / (family_count * counts[label]) for label in labels], - dtype=np.float64, + # The arithmetic is the shared rule's; this rule reads no target value. + return target_loss_weights_for_rule( + TargetLossRows(values=np.zeros(len(labels)), levels=labels), + UK_NATIONAL_TARGET_WEIGHT_RULE_DECLARATIONS[rule], ) diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/target_compile_modules.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/target_compile_modules.py index 0cf7b3007d..7edec3c404 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/target_compile_modules.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/target_compile_modules.py @@ -25,6 +25,14 @@ the modules hashed beside this tuple included, and records the imports no review has classified yet (microcosm#1497). This module is not hashed, so an edit to a reason re-keys nothing; an edit to the tuple re-keys the kernels. + +``UK_FULL_PROBLEM_LOSS_WEIGHT_MODULE_NAMES`` is a second tuple of the same +kind: the modules whose source decides the loss weights and loss scales that +``uk.full.problem@1`` binds. That kernel alone hashes them, beside the target +modules. They are named here, not imported by ``graph_targets``, because the +target, selection and measures kernels share that module and run none of +this code: an import there would be an edge from their hashed module to code +they do not hash (microcosm#1729). """ from __future__ import annotations @@ -151,6 +159,40 @@ ) +#: The modules whose source decides the loss weights and scales of the full +#: problem, in the order ``uk.full.problem@1`` hashes them: +#: +#: - ``local_rowwise.prepare_uk_full_solve`` builds the weights from the rules +#: in ``target_weights`` and ``national_doctrine`` (microcosm#1124); +#: - ``target_weights`` reads the UK-wide geography codes from +#: ``geography_constants``; +#: - the loss scales the problem stores come from +#: ``calibrate.solve.default_target_loss_scales`` (microcosm#1492). All of +#: ``calibrate.solve`` is hashed: ``calibrate.adam@1``, whose hash every UK +#: solve kernel embeds, already hashes it, so an edit there re-solves anyway +#: and re-keys only the problem besides; +#: - the arithmetic of every rule is the shared +#: ``calibrate.target_loss_rules`` (microcosm#1729), which ``target_weights`` +#: and ``national_doctrine`` call. +UK_FULL_PROBLEM_LOSS_WEIGHT_MODULE_NAMES: tuple[str, ...] = ( + "microcosm.build.uk_runtime.local_rowwise", + "microcosm.build.uk_runtime.national_doctrine", + "microcosm.build.uk_runtime.target_weights", + "microcosm.calibrate.geography_constants", + "microcosm.calibrate.solve", + "microcosm.calibrate.target_loss_rules", +) + + +def uk_full_problem_loss_weight_modules() -> tuple[ModuleType, ...]: + """The modules of :data:`UK_FULL_PROBLEM_LOSS_WEIGHT_MODULE_NAMES`, imported.""" + + return tuple( + importlib.import_module(name) + for name in UK_FULL_PROBLEM_LOSS_WEIGHT_MODULE_NAMES + ) + + def uk_target_compile_modules() -> tuple[ModuleType, ...]: """The modules of :data:`UK_TARGET_COMPILE_MODULE_NAMES`, imported.""" diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/target_weights.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/target_weights.py index 47c0161f7b..9e94d4fae0 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/target_weights.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/target_weights.py @@ -10,6 +10,12 @@ from a stored ordered problem (:func:`uk_target_rows_from_problem`, used by the size-experiment harness), so a rule computed either way is one vector. +The arithmetic of every rule is the shared, country-agnostic one of +:mod:`microcosm.calibrate.target_loss_rules` (microcosm#1729). This module +says what a UK row is (its weighting grain, its family, its value basis) and +declares each UK rule name as a shared rule with its parameters +(:data:`UK_LOCAL_TARGET_WEIGHT_RULE_DECLARATIONS`). + Rules (G grains, F_g families in grain g, n rows in a (grain, family) cell; every vector sums to one): @@ -66,14 +72,22 @@ ) from microcosm.build.uk_runtime.local_targets import AREA_TYPES, area_groups_from_codes from microcosm.calibrate.geography_constants import UK_WIDE_GEOGRAPHY_IDS +from microcosm.calibrate.target_loss_rules import ( + TargetLossRows, + TargetWeightRule, + target_loss_weights_for_rule, +) __all__ = [ "NATIONAL_GRAIN", "NATION_REGION_GRAIN", + "UK_LOCAL_NATION_LEVEL_RULES", + "UK_LOCAL_TARGET_WEIGHT_RULE_DECLARATIONS", "UK_TARGET_WEIGHT_RULE_VERSION", "UKStageTargetWeighting", "UKTargetRows", "uk_rule_loss_weights", + "uk_target_loss_rows", "uk_target_loss_weight_receipt", "uk_target_loss_weights_for_rows", "uk_target_loss_weights_sha256", @@ -95,6 +109,35 @@ LOCAL_SURFACE_MATERIALIZATION = "uk_local_surface" _COUNT, _AMOUNT = "count", "amount" +#: The UK count-row power inside a (level, family) cell: the square root, as +#: the US value weight (microcosm#1104, microcosm#1124). +UK_LOCAL_COUNT_POWER = 0.5 +#: Each UK local rule name as a shared rule with its parameters: the UK's +#: declaration (microcosm#1729). The shared rule reads each row's level, +#: family, basis and value, which :func:`uk_target_loss_rows` supplies. +UK_LOCAL_TARGET_WEIGHT_RULE_DECLARATIONS: Mapping[str, TargetWeightRule] = ( + MappingProxyType( + { + "uniform": TargetWeightRule("uniform"), + "grain_equal": TargetWeightRule("level_equal"), + "grain_family_equal": TargetWeightRule("level_family_equal"), + "grain_family_equal_sqrt_count": TargetWeightRule( + "level_family_equal", {"count_power": UK_LOCAL_COUNT_POWER} + ), + "nation_grain_family_equal": TargetWeightRule("level_family_equal"), + "nation_grain_family_equal_sqrt_count": TargetWeightRule( + "level_family_equal", {"count_power": UK_LOCAL_COUNT_POWER} + ), + } + ) +) +#: The rules under which a national row that is not a UK-wide aggregate (a +#: nation or an English region) weighs in a level of its own, +#: ``nation_region``. Under the others every national row weighs in the +#: national level. +UK_LOCAL_NATION_LEVEL_RULES = frozenset( + {"nation_grain_family_equal", "nation_grain_family_equal_sqrt_count"} +) #: The reviewed scale rule of the UK local solve: the canonical target-defined #: default (``max(|target|, 1)``) with a floor per local count family whose #: cells are too thin for a unit-scale miss to mean anything. microcosm#1240 @@ -444,40 +487,47 @@ def uk_family_floored_loss_scales( return scales, receipt +def uk_target_loss_rows(rows: UKTargetRows, *, rule: str) -> TargetLossRows: + """What each UK row is, as the shared rule ``rule`` names reads it. + + The level is the row's weighting grain (a BRMA row weighs in the + local-authority grain; under a nation rule a nation or region row leaves + the national grain). The basis is read only for a rule with a count + power, so a rule without one still accepts a row whose basis is not + declared. + """ + + if rule not in UK_LOCAL_TARGET_WEIGHT_RULES: + raise ValueError( + f"target_weight_rule must be one of {UK_LOCAL_TARGET_WEIGHT_RULES}, " + f"got {rule!r}." + ) + declaration = UK_LOCAL_TARGET_WEIGHT_RULE_DECLARATIONS[rule] + return TargetLossRows( + values=rows.values, + levels=_rule_grains(rows, nation=rule in UK_LOCAL_NATION_LEVEL_RULES), + families=rows.family, + bases=( + uk_target_value_basis(rows) + if declaration.parameters.get("count_power") is not None + else None + ), + ) + + def uk_target_loss_weights_for_rows(rows: UKTargetRows, *, rule: str) -> np.ndarray: - """The loss-weight vector of a row-metadata rule (sums to one).""" + """The loss-weight vector of a row-metadata rule (sums to one). + + Computed by the shared rule the UK declares for ``rule``. + """ _check_row_rule(rule) if not len(rows): raise ValueError("target weighting requires at least one target.") - nation = rule.startswith("nation_") - sqrt_count = rule.endswith("_sqrt_count") - grains = np.asarray(_rule_grains(rows, nation=nation), dtype=object) - families = np.asarray(rows.family, dtype=object) - bases = ( - np.asarray(uk_target_value_basis(rows), dtype=object) if sqrt_count else None + return target_loss_weights_for_rule( + uk_target_loss_rows(rows, rule=rule), + UK_LOCAL_TARGET_WEIGHT_RULE_DECLARATIONS[rule], ) - magnitudes = np.maximum(np.abs(rows.values), 1.0) ** 0.5 if sqrt_count else None - grain_order = list(dict.fromkeys(grains.tolist())) - weights = np.zeros(len(rows), dtype=np.float64) - for grain in grain_order: - in_grain = grains == grain - family_order = list(dict.fromkeys(families[in_grain].tolist())) - budget = 1.0 / (len(grain_order) * len(family_order)) - for family in family_order: - cell = np.flatnonzero(in_grain & (families == family)) - if bases is None: - weights[cell] = budget / cell.size - continue - counts = cell[bases[cell] == _COUNT] - amounts = cell[bases[cell] == _AMOUNT] - weights[amounts] = budget / cell.size - if counts.size: - share = magnitudes[counts] - weights[counts] = ( - (budget * counts.size / cell.size) * share / share.sum() - ) - return weights def uk_rule_loss_weights(rows: UKTargetRows, *, rule: str) -> np.ndarray: 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 1ecefe38b7..f25a04b881 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,11 +66,41 @@ import numpy as np +from microcosm.calibrate.target_loss_rules import ( + TargetLossRows, + TargetWeightRule, + apply_family_multipliers, + budget_group_weights, + budget_groups, + target_loss_weights_for_rule, + value_basis_weights, +) + #: The loss formula's identifier, recorded in release diagnostics. US_FISCAL_TARGET_LOSS_WEIGHTING = ( "sqrt_value_concept_budget_weighted_mape_50_50_amount_count_target_scale_cap_100pct" ) US_FISCAL_TARGET_VALUE_WEIGHT_POWER = 0.5 +#: The US releases' declaration of the formula above: the shared rule +#: (:mod:`microcosm.calibrate.target_loss_rules`) and its parameters. The row +#: mapping says what each row is; the arithmetic is the shared rule's +#: (microcosm#1729). +US_FISCAL_TARGET_WEIGHT_RULE = TargetWeightRule( + "sqrt_value_concept_budget", + {"value_power": US_FISCAL_TARGET_VALUE_WEIGHT_POWER}, +) +#: The weight rules the ACS local-area release may run under, by name. The +#: first is its default and the only one any build has used. The second is +#: the shared level and family rule, which gives each geography level one +#: equal share of the loss; it changes the weights, so a build must ask for it +#: by name. +US_ACS_LOCAL_TARGET_WEIGHT_RULE = "concept_budget" +US_ACS_LOCAL_TARGET_WEIGHT_RULES: Mapping[str, TargetWeightRule] = { + US_ACS_LOCAL_TARGET_WEIGHT_RULE: US_FISCAL_TARGET_WEIGHT_RULE, + "level_family_equal_sqrt_count": TargetWeightRule( + "level_family_equal", {"count_power": 0.5} + ), +} #: Metadata that identifies a target's place, record or reconciliation rather #: than its concept. The concept-budget key of a congressional-district target #: ignores it, so that the districts of one concept in one state share one @@ -130,14 +160,21 @@ def target_loss_weights_from_rows( concept_budget_keys: Sequence[Hashable], families: Sequence[str | None], family_multipliers: Mapping[str, float] | None = None, + *, + rule: TargetWeightRule = US_FISCAL_TARGET_WEIGHT_RULE, + levels: Sequence[str] | None = None, ) -> np.ndarray: """Steps 2-6 of the formula, over row-aligned per-target inputs. + The arithmetic is the shared rule ``rule`` names, by default + :data:`US_FISCAL_TARGET_WEIGHT_RULE`. ``levels`` is each row's geography + level, which only a rule that balances across levels reads. + Returns float64 weights, row-aligned with the inputs. With at least one - row they are positive and of mean 1, given positive finite multipliers - whose products stay within float64 range (the CLI parser admits only - positive finite ones; this function, like the national helper it came - from, does not check them). + row they are positive, and of mean 1 under the default rule, given + positive finite multipliers whose products stay within float64 range (the + CLI parser admits only positive finite ones; this function, like the + national helper it came from, does not check them). """ n_rows = len(values) @@ -147,49 +184,30 @@ def target_loss_weights_from_rows( f"{n_rows} values, {len(bases)} bases, " f"{len(concept_budget_keys)} concept keys, {len(families)} families." ) - basis_array = np.asarray(list(bases), dtype=object) - weights = _concept_budget_weights( - _value_basis_weights(values, basis_array), concept_budget_keys + rows = TargetLossRows( + values=values, + levels=levels, + families=families, + bases=bases, + groups=concept_budget_keys, ) - unique_bases = sorted(set(basis_array.tolist())) - if not unique_bases: - return weights - basis_total = len(weights) / len(unique_bases) - for basis in unique_bases: - mask = basis_array == basis - current_total = weights[mask].sum() - if current_total > 0: - weights[mask] *= basis_total / current_total - weights = weights / weights.mean() - if not family_multipliers: + weights = target_loss_weights_for_rule(rows, rule.with_family_multipliers(None)) + if not family_multipliers or not n_rows: return weights - family_array = np.asarray(list(families), dtype=object) - for family, multiplier in sorted(family_multipliers.items()): - mask = family_array == family - if not mask.any(): + present = set(families) + for family in sorted(family_multipliers): + if family not in present: raise ValueError( f"--target-family-loss-multiplier family {family!r} matches " "no compiled target." ) - weights[mask] *= multiplier - return weights / weights.mean() + return apply_family_multipliers(weights, families, family_multipliers) def _value_basis_weights(values: Sequence[float], bases: np.ndarray) -> np.ndarray: """Step 2: ``max(|value|, 1) ** 0.5`` over its basis mean.""" - weights = np.ones(len(bases), dtype=np.float64) - magnitudes = np.asarray( - [max(abs(float(value)), 1.0) for value in values], - dtype=np.float64, - ) - raw_weights = magnitudes**US_FISCAL_TARGET_VALUE_WEIGHT_POWER - for basis in sorted(set(bases.tolist())): - mask = bases == basis - mean_value = raw_weights[mask].mean() - if mean_value > 0: - weights[mask] = raw_weights[mask] / mean_value - return weights + return value_basis_weights(values, bases, power=US_FISCAL_TARGET_VALUE_WEIGHT_POWER) def _concept_budget_weights( @@ -197,13 +215,7 @@ def _concept_budget_weights( ) -> np.ndarray: """Step 3: each group sums to its largest member's weight.""" - for indices in concept_budget_groups(concept_budget_keys): - group_weights = weights[indices] - group_total = float(group_weights.sum()) - group_budget = float(group_weights.max(initial=0.0)) - if group_total > 0 and group_budget > 0: - weights[indices] *= group_budget / group_total - return weights + return budget_group_weights(weights, concept_budget_keys) def concept_budget_groups( @@ -211,10 +223,7 @@ def concept_budget_groups( ) -> list[list[int]]: """Row indices sharing each concept-budget key, in first-row order.""" - group_indices: dict[Hashable, list[int]] = {} - for index, key in enumerate(concept_budget_keys): - group_indices.setdefault(key, []).append(index) - return list(group_indices.values()) + return budget_groups(concept_budget_keys) # --------------------------------------------------------------------------- @@ -608,8 +617,15 @@ def target_loss_weights( family_multipliers: Mapping[str, float] | None = None, *, row_mapping: TargetLossRowMapping = US_FISCAL_TARGET_LOSS_ROW_MAPPING, + rule: TargetWeightRule = US_FISCAL_TARGET_WEIGHT_RULE, ) -> np.ndarray: - """The formula's weights for ``specs``, row-aligned, under one mapping.""" + """The weights ``rule`` gives ``specs``, row-aligned, under one mapping. + + The mapping says what each row is (its basis and its concept budget + group); its level is :func:`target_geography_level`. ``rule`` is the + shared rule that turns those into weights, by default the formula of the + module docstring. + """ specs = tuple(specs) bases = [row_mapping.value_basis(spec) for spec in specs] @@ -622,6 +638,8 @@ def target_loss_weights( keys, [spec.family for spec in specs], family_multipliers, + rule=rule, + levels=[target_geography_level(spec) for spec in specs], ) @@ -653,9 +671,23 @@ def fiscal_target_concept_budget_weights(registry) -> np.ndarray: ) +def acs_local_target_weight_rule(name: str) -> TargetWeightRule: + """The ACS local release's declared weight rule of that name.""" + + try: + return US_ACS_LOCAL_TARGET_WEIGHT_RULES[name] + except KeyError: + raise ValueError( + "the ACS local target weight rule must be one of " + f"{sorted(US_ACS_LOCAL_TARGET_WEIGHT_RULES)}, got {name!r}." + ) from None + + def us_acs_local_target_loss_weights( specs: Iterable[Any], family_multipliers: Mapping[str, float] | None = None, + *, + rule: str = US_ACS_LOCAL_TARGET_WEIGHT_RULE, ) -> np.ndarray: """The ACS local release's weights for its training target specs.""" @@ -669,6 +701,7 @@ def us_acs_local_target_loss_weights( specs, family_multipliers, row_mapping=US_ACS_LOCAL_TARGET_LOSS_ROW_MAPPING, + rule=acs_local_target_weight_rule(rule), ) diff --git a/packages/microcosm-build/tests/engine_free/shared/test_area_support.py b/packages/microcosm-build/tests/engine_free/shared/test_area_support.py new file mode 100644 index 0000000000..dd37834c56 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/shared/test_area_support.py @@ -0,0 +1,408 @@ +"""Area support: the table, the floors and one gate for any country (#1729). + +Every weight, code and count below is made up for the test. +""" + +from __future__ import annotations + +import numpy as np +import pandas as pd +import pytest +from hypothesis import given, settings +from hypothesis import strategies as st + +from microcosm.build import gates +from microcosm.build.area_support import ( + area_support_floor_table, + area_support_gate, + area_support_table, + effective_sample_size_by_group, +) +from microcosm.calibrate.solve import effective_sample_size +from test_support.microcosm_build import area_support_gate_reference as before + +LEVEL = "district" + + +def _legacy_ess_by_group(weights: np.ndarray, codes: np.ndarray) -> dict[str, float]: + """``ess_by_group`` of ``tools/us_acs_local_cd_surface.py`` at ac7ab99ae. + + A verbatim copy, kept to hold the shared function to the bytes the ACS + local release's weight-origin summaries recorded before the move. + """ + + frame = pd.DataFrame( + {"code": np.asarray(codes).astype(str), "w": np.asarray(weights, float)} + ) + frame["w2"] = frame["w"] ** 2 + sums = frame.groupby("code", sort=True)[["w", "w2"]].sum() + return { + str(code): float(row.w**2 / row.w2) if row.w2 > 0 else 0.0 + for code, row in sums.iterrows() + } + + +_WEIGHTED_GROUPS = st.lists( + st.tuples( + st.floats(0.0, 1e9, allow_nan=False), + st.sampled_from(["0601", "0602", "3601", "2401", "7"]), + ), + min_size=1, + max_size=60, +) + + +# --------------------------------------------------------------------------- +# Measuring support +# --------------------------------------------------------------------------- + + +@settings(max_examples=200, deadline=None) +@given(records=_WEIGHTED_GROUPS) +def test_grouped_ess_is_the_moved_function_bit_for_bit(records) -> None: + weights = np.asarray([weight for weight, _code in records]) + codes = np.asarray([code for _weight, code in records]) + + moved = effective_sample_size_by_group(weights, codes) + legacy = _legacy_ess_by_group(weights, codes) + + assert list(moved) == list(legacy) + assert [value.hex() for value in moved.values()] == [ + value.hex() for value in legacy.values() + ] + # And it is the Kish ESS of each group's records. + for code, ess in moved.items(): + assert ess == pytest.approx(effective_sample_size(weights[codes == code])) + + +def test_grouped_ess_refuses_weights_the_solver_refuses() -> None: + codes = np.asarray(["a", "a", "b"]) + for bad in ([1.0, -1.0, 1.0], [1.0, np.nan, 1.0], [1.0, np.inf, 1.0]): + with pytest.raises(ValueError, match="finite and non-negative"): + effective_sample_size_by_group(np.asarray(bad), codes) + with pytest.raises(ValueError, match="do not align"): + effective_sample_size_by_group(np.ones(2), codes) + assert effective_sample_size_by_group(np.zeros(3), codes) == {"a": 0.0, "b": 0.0} + + +def test_the_support_table_counts_positive_rows_and_distinct_sources() -> None: + weights = np.asarray([2.0, 2.0, 0.0, 5.0, 1.0, 0.0]) + areas = np.asarray(["A", "A", "A", "B", "B", "C"]) + # Two copies of one source household in A; the zero-weight row is a third. + sources = np.asarray(["s1", "s1", "s9", "s2", "s3", "s4"]) + starting = np.ones(6) + + table = area_support_table( + weights, + areas, + geography_level=LEVEL, + source_ids=sources, + starting_weights=starting, + ) + + assert table.to_dict("list") == { + "geography_level": [LEVEL, LEVEL, LEVEL], + "area_code": ["A", "B", "C"], + "nonzero_households": [2, 2, 0], + "nonzero_source_households": [1, 2, 0], + "effective_sample_size": [2.0, 36.0 / 26.0, 0.0], + "starting_effective_sample_size": [3.0, 2.0, 1.0], + } + # Without sources or starting weights the table carries neither column. + assert list(area_support_table(weights, areas, geography_level=LEVEL)) == [ + "geography_level", + "area_code", + "nonzero_households", + "effective_sample_size", + ] + + +# --------------------------------------------------------------------------- +# The gate +# --------------------------------------------------------------------------- + + +def _table(rows) -> pd.DataFrame: + return pd.DataFrame( + rows, + columns=[ + "area_code", + "nonzero_households", + "nonzero_source_households", + "effective_sample_size", + "starting_effective_sample_size", + ], + ).assign(geography_level=LEVEL) + + +_AREAS = st.lists( + st.tuples( + st.integers(0, 120), + st.integers(0, 120), + st.floats(0.0, 120.0, allow_nan=False), + st.floats(0.0, 400.0, allow_nan=False), + ), + min_size=1, + max_size=12, +) +_EXCLUDED = st.lists(st.integers(0, 14), max_size=4, unique=True) + + +def test_there_is_one_gate() -> None: + assert area_support_gate is gates.area_support_gate + + +@settings(max_examples=300, deadline=None) +@given( + areas=_AREAS, + floors=st.tuples(st.integers(1, 80), st.floats(0.5, 80.0), st.integers(1, 80)), + excluded=_EXCLUDED, +) +def test_the_absolute_floors_give_the_gate_of_before(areas, floors, excluded) -> None: + """With the three absolute floors the gate is the gate it always was. + + The UK local build calls it this way. The result, the per-area flag and + the wording are held to a verbatim copy of the code before the floors + became optional, reviewed exclusions included. + """ + + table = _table([(f"a{index:02d}", *area) for index, area in enumerate(areas)]) + declared = dict( + minimum_rows=floors[0], + minimum_effective_sample_size=floors[1], + minimum_distinct_sources=floors[2], + ) + arguments = dict( + area_roster={LEVEL: list(table["area_code"])}, + geography_levels=(LEVEL,), + # Some name areas of the table, some an area it does not have. + reviewed_exclusions={ + f"{LEVEL}/a{index:02d}": {"reviewer": "test"} for index in excluded + }, + **declared, + ) + + assert area_support_gate(table, **arguments) == before.area_support_gate( + table, **arguments + ) + assert gates.area_support_below_floor(table, **declared).equals( + before.area_support_below_floor(table, **declared) + ) + for row in table.itertuples(index=False): + measured = ( + row.nonzero_households, + row.effective_sample_size, + row.nonzero_source_households, + ) + assert gates.area_support_shortfalls(*measured, **declared) == ( + before.area_support_shortfalls(*measured, **declared) + ) + + +@pytest.mark.parametrize( + ("floor", "value", "match"), + [ + ("minimum_rows", 0, "minimum_rows must be a positive integer"), + ("minimum_distinct_sources", True, "minimum_distinct_sources must be"), + ("minimum_effective_sample_size", 0.0, "must be positive and finite"), + ], +) +def test_an_invalid_absolute_floor_keeps_its_refusal(floor, value, match) -> None: + table = _table([("a", 60, 60, 60.0, 60.0)]) + arguments = dict( + area_roster={LEVEL: ["a"]}, + geography_levels=(LEVEL,), + minimum_rows=50, + minimum_effective_sample_size=50.0, + minimum_distinct_sources=50, + ) + arguments[floor] = value + for gate in (area_support_gate, before.area_support_gate): + with pytest.raises(ValueError, match=match): + gate(table, **arguments) + + +def test_the_flag_needs_the_columns_of_its_floors() -> None: + table = _table([("a", 60, 60, 60.0, 60.0)]).drop(columns="nonzero_households") + with pytest.raises(ValueError, match="nonzero_households"): + gates.area_support_below_floor( + table, + minimum_rows=50, + minimum_effective_sample_size=50.0, + minimum_distinct_sources=50, + ) + # A floor that is not declared reads no column. + flags = gates.area_support_below_floor( + table, + minimum_rows=None, + minimum_effective_sample_size=70.0, + minimum_distinct_sources=None, + minimum_effective_sample_size_ratio=0.5, + ) + assert flags.tolist() == [True] + + +def test_the_relative_floor_fails_an_area_below_a_share_of_its_starting_ess() -> None: + table = _table( + [ + ("held", 0, 0, 30.0, 100.0), # 0.30 of its start + ("lost", 0, 0, 24.0, 100.0), # 0.24: below a quarter + ("thin", 0, 0, 9.0, 12.0), # 0.75, but below the absolute floor + ("edge", 0, 0, 25.0, 100.0), # exactly a quarter: not below + ("empty", 0, 0, 0.0, 0.0), # no starting ESS: never below the ratio + ] + ) + result = area_support_gate( + table, + area_roster={LEVEL: ["held", "lost", "thin", "edge", "empty"]}, + geography_levels=(LEVEL,), + minimum_effective_sample_size=15.0, + minimum_effective_sample_size_ratio=0.25, + ) + + assert not result.passed + assert result.failures == ( + f"{LEVEL}/empty: ESS 0 < 15", + f"{LEVEL}/lost: ESS 24 < 0.25 x starting ESS 100", + f"{LEVEL}/thin: ESS 9 < 15", + ) + assert result.details["floors"] == { + "minimum_rows": None, + "minimum_effective_sample_size": 15.0, + "minimum_distinct_sources": None, + "minimum_effective_sample_size_ratio": 0.25, + } + level = result.details["by_geography_level"][LEVEL] + assert level["areas_checked"] == 5 + assert level["areas_below_floor"] == 3 + assert level["areas_below_effective_sample_size_ratio"] == 1 + assert level["minimum_effective_sample_size_ratio"] == pytest.approx(0.24) + assert level["minimum_effective_sample_size"] == 0.0 + + +def test_a_gate_needs_only_the_columns_of_its_floors() -> None: + table = pd.DataFrame( + { + "geography_level": LEVEL, + "area_code": ["a", "b"], + "effective_sample_size": [40.0, 8.0], + "starting_effective_sample_size": [80.0, 80.0], + } + ) + roster = dict(area_roster={LEVEL: ["a", "b"]}, geography_levels=(LEVEL,)) + + relative = area_support_gate( + table, **roster, minimum_effective_sample_size_ratio=0.25 + ) + assert relative.failures == (f"{LEVEL}/b: ESS 8 < 0.25 x starting ESS 80",) + assert "minimum_rows" not in relative.details["by_geography_level"][LEVEL] + + # No floor declared: the gate checks the roster and reports the minima. + undeclared = area_support_gate(table, **roster) + assert undeclared.passed + assert undeclared.details["by_geography_level"][LEVEL] == { + "areas_checked": 2, + "areas_below_floor": 0, + "minimum_effective_sample_size": 8.0, + } + + with pytest.raises(ValueError, match="nonzero_households"): + area_support_gate(table, **roster, minimum_rows=50) + with pytest.raises(ValueError, match="starting_effective_sample_size"): + area_support_gate( + table.drop(columns="starting_effective_sample_size"), + **roster, + minimum_effective_sample_size_ratio=0.25, + ) + + +def test_the_roster_is_load_bearing_under_any_floors() -> None: + table = pd.DataFrame( + { + "geography_level": LEVEL, + "area_code": ["a"], + "effective_sample_size": [40.0], + "starting_effective_sample_size": [80.0], + } + ) + with pytest.raises(ValueError, match="exactly cover the declared roster"): + area_support_gate( + table, + area_roster={LEVEL: ["a", "b"]}, + geography_levels=(LEVEL,), + minimum_effective_sample_size_ratio=0.25, + ) + with pytest.raises(ValueError, match="duplicate area rows"): + area_support_gate( + pd.concat([table, table]), + area_roster={LEVEL: ["a"]}, + geography_levels=(LEVEL,), + minimum_effective_sample_size_ratio=0.25, + ) + + +@pytest.mark.parametrize( + ("floor", "value", "match"), + [ + ("minimum_effective_sample_size_ratio", 0.0, r"in \(0, 1\]"), + ("minimum_effective_sample_size_ratio", 1.5, r"in \(0, 1\]"), + ("minimum_effective_sample_size_ratio", float("nan"), r"in \(0, 1\]"), + ("minimum_effective_sample_size", 0.0, "positive and finite"), + ("minimum_rows", 0, "positive integer"), + ("minimum_distinct_sources", 2.5, "positive integer"), + ], +) +def test_an_invalid_floor_is_refused(floor, value, match) -> None: + table = _table([("a", 60, 60, 60.0, 60.0)]) + with pytest.raises(ValueError, match=match): + area_support_floor_table(table, **{floor: value}) + with pytest.raises(ValueError, match=match): + # A relative floor too, so the general rule checks the floors itself. + area_support_gate( + table, + area_roster={LEVEL: ["a"]}, + geography_levels=(LEVEL,), + **{"minimum_effective_sample_size_ratio": 0.5, floor: value}, + ) + + +_FLOORS = st.fixed_dictionaries( + { + "minimum_rows": st.none() | st.integers(1, 80), + "minimum_effective_sample_size": st.none() | st.floats(0.5, 80.0), + "minimum_distinct_sources": st.none() | st.integers(1, 80), + "minimum_effective_sample_size_ratio": st.none() | st.floats(0.01, 1.0), + } +) + + +@settings(max_examples=200, deadline=None) +@given(areas=_AREAS, floors=_FLOORS) +def test_the_floor_table_and_the_gate_give_one_verdict(areas, floors) -> None: + table = _table([(f"a{index:02d}", *area) for index, area in enumerate(areas)]) + + checked = area_support_floor_table(table, **floors) + result = area_support_gate( + table, + area_roster={LEVEL: list(table["area_code"])}, + geography_levels=(LEVEL,), + **floors, + ) + + below = sorted(checked.loc[checked["below_any_floor"], "area_code"]) + assert sorted(line.split(":")[0] for line in result.failures) == [ + f"{LEVEL}/{code}" for code in below + ] + assert result.passed == (not below) + assert result.details["by_geography_level"][LEVEL]["areas_below_floor"] == ( + len(below) + ) + # One flag column for each declared floor, and no other. + assert {column for column in checked.columns if column.startswith("below_")} == { + f"below_{floor}" for floor, value in floors.items() if value is not None + } | {"below_any_floor"} + # The ratio is the ESS over the starting ESS, undefined at a zero start. + starting = table["starting_effective_sample_size"].to_numpy() + assert np.isnan( + checked["effective_sample_size_ratio"].to_numpy()[starting == 0] + ).all() diff --git a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py index 0a4454adae..039139d1cc 100644 --- a/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py +++ b/packages/microcosm-build/tests/engine_free/shared/test_spec_engine_loader.py @@ -42,7 +42,7 @@ def test_semantic_hash_has_golden_vector_and_surface_separation(tmp_path) -> Non # The SIPP 2023 donor download tag and the financial-asset cache lookup # move it again. assert first.spec_sha256 == ( - "f8cf0b8a9f76ad869ff3dd1b9e724a76e5043862113e4990743274ceee85763c" + "9ef2736b6b2c8e9e02c6d12c76acb6b4349479cd7bfceb0124a7bb8264bc9219" ) second_root = _rich_minimal(tmp_path / "xy", note="second", store="local:b") diff --git a/packages/microcosm-build/tests/engine_free/shared/test_spine_target_shares_tool.py b/packages/microcosm-build/tests/engine_free/shared/test_spine_target_shares_tool.py new file mode 100644 index 0000000000..06577eed3c --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/shared/test_spine_target_shares_tool.py @@ -0,0 +1,210 @@ +"""tools/spine_target_shares.py reads saved inputs and needs no build (#1729). + +Every number below is made up for the test. +""" + +from __future__ import annotations + +import importlib.util +import json +import sys +from types import ModuleType, SimpleNamespace + +import numpy as np +import pandas as pd +import pytest +from scipy import sparse + +from test_support.paths import paths_for + + +def _tool(): + path = paths_for("microcosm-build").repository / "tools" / "spine_target_shares.py" + spec = importlib.util.spec_from_file_location("spine_target_shares_tool", path) + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + spec.loader.exec_module(module) + return module + + +#: Five households: two donor rows (heavy) and three survey rows. +_HOUSEHOLDS = pd.DataFrame( + { + "household_id": [1, 2, 3, 4, 5], + "household_spine": ["donor", "donor", "acs", "acs", "acs"], + "household_source_id": [10, 10, 1, 2, 3], + # Numeric codes, as the lean frame stores them. + "state_fips": [6, 36, 6, 6, 36], + "congressional_district_geoid": [601, 3601, 601, 602, 3601], + } +) +_DESIGN = np.asarray([27.0, 27.0, 1.0, 1.0, 1.0]) +_ROLES = [ + { + "name": "pop_state_06", + "family": "census_population_ladder", + "geography_level": "state", + "state_fips": "06", + "congressional_district_geoid": None, + "role": "train", + }, + { + "name": "pop_cd_0601", + "family": "census_population_ladder", + "geography_level": "congressional_district", + "state_fips": "06", + "congressional_district_geoid": "0601", + "role": "train", + }, + { + "name": "irs_soi.ca.capital_gains", + "family": "irs_soi", + "geography_level": "state", + "state_fips": "06", + "congressional_district_geoid": None, + "role": "holdout", + }, +] +_MATRIX = sparse.csr_array( + np.asarray( + [ + [2.0, 0.0, 3.0, 1.0, 0.0], # persons in California + [2.0, 0.0, 3.0, 0.0, 0.0], # persons in district 0601 + [900.0, 0.0, 0.0, 0.0, 0.0], # an amount only the donor row carries + ], + dtype=np.float32, + ) +) + + +def test_the_us_adapter_scopes_each_target_to_its_own_area() -> None: + inputs = _tool().us_acs_local_inputs(_HOUSEHOLDS, _ROLES) + + assert inputs["names"] == [role["name"] for role in _ROLES] + assert inputs["target_scopes"] == [ + ("state", "06"), + ("congressional_district", "0601"), + ("state", "06"), + ] + # Household codes are padded the way the roles spell them. + assert inputs["scope_codes"]["state"].tolist() == ["06", "36", "06", "06", "36"] + assert inputs["scope_codes"]["congressional_district"].tolist() == [ + "0601", + "3601", + "0601", + "0602", + "3601", + ] + assert "county" not in inputs["scope_codes"] + assert inputs["groups"][2] == "irs_soi/state" + assert inputs["roles"] == ["train", "train", "holdout"] + with pytest.raises(SystemExit, match="household_spine"): + _tool().us_acs_local_inputs(_HOUSEHOLDS.drop(columns="household_spine"), _ROLES) + + +def test_the_report_reads_a_checkpoint_at_design_and_calibrated_weights( + tmp_path, monkeypatch, capsys +) -> None: + tool = _tool() + # A stand-in for the release tool: the checkpoint loader and nothing else. + release = ModuleType("build_us_acs_local_release") + release.load_checkpoint_surface = lambda checkpoint_dir: ( + SimpleNamespace(table=lambda entity: _HOUSEHOLDS), + _DESIGN, + None, + _ROLES, + _MATRIX, + ) + monkeypatch.setitem(sys.modules, "build_us_acs_local_release", release) + np.savez(tmp_path / "weights_latest.npz", weights=[5.0, 27.0, 9.0, 8.0, 8.0]) + out = tmp_path / "report" / "shares.json" + + assert ( + tool.main( + [ + "--us-acs-local-checkpoint", + str(tmp_path), + "--out", + str(out), + "--spine", + "donor", + "--top", + "2", + ] + ) + == 0 + ) + + report = json.loads(out.read_text()) + assert set(report) == {"design", "calibrated"} + design = report["design"] + assert design["spines"] == ["acs", "donor"] + by_name = {row["name"]: row for row in design["targets"]} + # California holds 27 of 29 on its donor row, which carries 54 of 58 persons. + assert by_name["pop_state_06"]["mass_share"]["donor"] == pytest.approx(27 / 29) + assert by_name["pop_state_06"]["share"]["donor"] == pytest.approx(54 / 58) + # The amount is carried by the donor row alone, by one source household. + capital = by_name["irs_soi.ca.capital_gains"] + assert capital["share"] == {"acs": 0.0, "donor": 1.0} + assert capital["carriers"] == {"acs": 0, "donor": 1} + assert capital["role"] == "holdout" + assert design["by_family_and_level"][0]["group"] == ( + "census_population_ladder/state" + ) + # The calibrated weights moved mass off the California donor row. + calibrated = {row["name"]: row for row in report["calibrated"]["targets"]} + assert calibrated["pop_state_06"]["mass_share"]["donor"] == pytest.approx(5 / 22) + printed = capsys.readouterr().out + assert "[design] 3 targets" in printed + assert "irs_soi.ca.capital_gains" in printed + + +def test_the_generic_inputs_need_only_a_matrix_weights_and_spines( + tmp_path, capsys +) -> None: + tool = _tool() + sparse.save_npz(tmp_path / "matrix.npz", sparse.csr_matrix(_MATRIX)) + np.save(tmp_path / "weights.npy", _DESIGN) + np.savez( + tmp_path / "labels.npz", spines=_HOUSEHOLDS["household_spine"].to_numpy(str) + ) + (tmp_path / "names.json").write_text(json.dumps(["a", "b", "c"])) + out = tmp_path / "shares.json" + + assert ( + tool.main( + [ + "--matrix", + str(tmp_path / "matrix.npz"), + "--weights", + str(tmp_path / "weights.npy"), + "--spines", + str(tmp_path / "labels.npz"), + "--names", + str(tmp_path / "names.json"), + "--minimum-carriers", + "2", + "--out", + str(out), + ] # fmt: skip + ) + == 0 + ) + report = json.loads(out.read_text())["weights"] + assert report["minimum_carriers"] == 2 + # Each target has a spine with one carrier, so the floor withholds all. + assert report["n_withheld"] == 3 + assert all("share" not in row for row in report["targets"]) + assert "3 withheld" in capsys.readouterr().out + + +def test_the_cli_refuses_a_mix_of_the_two_inputs(tmp_path) -> None: + tool = _tool() + for argv in ( + [], + ["--matrix", "m.npz"], + ["--us-acs-local-checkpoint", str(tmp_path), "--matrix", "m.npz"], + ["--matrix", "m", "--weights", "w", "--spines", "s", "--minimum-carriers", "0"], + ): + with pytest.raises(SystemExit): + tool._parse_args(argv) diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_target_compile_modules.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_target_compile_modules.py index f58e4c8e4d..2c4e7f76e6 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_target_compile_modules.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_target_compile_modules.py @@ -21,6 +21,7 @@ import microcosm.calibrate.geography_constants as geography_constants_module import microcosm.calibrate.solve as calibrate_solve +import microcosm.calibrate.target_loss_rules as calibrate_target_loss_rules from microcosm.build import ledger_artifact from microcosm.build import ledger_targets as shared_ledger_targets from microcosm.build.uk_runtime import ( @@ -32,7 +33,9 @@ ) from microcosm.build.uk_runtime.target_compile_modules import ( EXCLUDED_DIRECT_IMPORTS, + UK_FULL_PROBLEM_LOSS_WEIGHT_MODULE_NAMES, UK_TARGET_COMPILE_MODULE_NAMES, + uk_full_problem_loss_weight_modules, uk_target_compile_modules, ) from test_support.microcosm_build.first_party_imports import ( @@ -171,6 +174,10 @@ def test_national_target_kernels_hash_the_fact_decoder(monkeypatch): # The full problem's loss scales (default_target_loss_scales). The # national kernels call nothing in it (see the test below). "microcosm.calibrate.solve": ("uk.full.problem@1",), + # The shared rules that compute the loss weights (microcosm#1729): + # target_weights and national_doctrine call them for the full problem, + # national_doctrine for the national problem. + "microcosm.calibrate.target_loss_rules": ("uk.full.problem@1",) + _NATIONAL_GRAPH, # full_targets' exclusion clock (exclusion_evaluation_date). "microcosm.build.uk_runtime.weighted_integrity": _FULL_GRAPH + _NATIONAL_GRAPH, # full_targets' surface provenance (_ledger_provenance) and band-edge @@ -446,9 +453,6 @@ def test_national_target_kernels_hash_the_fact_decoder(monkeypatch): FULL_TARGETS, FULL_PROBLEM, ), - "microcosm.build.uk_runtime.graph_targets -> microcosm.build.uk_runtime.national_doctrine": ( - FULL_TARGETS, - ), "microcosm.build.uk_runtime.local_doctrine -> microcosm.build.uk_runtime.national_doctrine": ( FULL_TARGETS, ), @@ -549,9 +553,6 @@ def test_national_target_kernels_hash_the_fact_decoder(monkeypatch): "microcosm.build.uk_runtime.graph_national -> microcosm.calibrate.solve": ( NATIONAL, ), - "microcosm.build.uk_runtime.graph_targets -> microcosm.calibrate.solve": ( - FULL_TARGETS, - ), "microcosm.calibrate.artifacts -> microcosm.calibrate.solve": ( FULL_TARGETS, NATIONAL, @@ -781,7 +782,9 @@ def test_full_problem_loss_weights_hash_what_target_weights_reads(monkeypatch): """target_weights takes UK_WIDE_GEOGRAPHY_IDS from geography_constants and the loss scales from calibrate.solve for the weights the problem binds, so the problem's weight hash covers both modules itself, not only - through the target modules' hash.""" + through the target modules' hash. It computes every rule with the shared + calibrate.target_loss_rules (microcosm#1729), so the hash covers that + module too.""" calls: list[tuple] = [] monkeypatch.setattr( graph_targets, @@ -792,6 +795,17 @@ def test_full_problem_loss_weights_hash_what_target_weights_reads(monkeypatch): (weights,) = [objects for objects in calls if target_weights in objects] assert geography_constants_module in weights assert calibrate_solve in weights + assert calibrate_target_loss_rules in weights + # The kernel hashes the declared tuple, whole and in its order. The + # modules are named there, not imported by graph_targets, whose other + # kernels run none of them (microcosm#1729). + assert weights == uk_full_problem_loss_weight_modules() + assert [module.__name__ for module in weights] == list( + UK_FULL_PROBLEM_LOSS_WEIGHT_MODULE_NAMES + ) + imported = first_party_imports(graph_targets.__name__) + assert calibrate_solve.__name__ not in imported + assert calibrate_target_loss_rules.__name__ not in imported def test_the_national_kernels_leave_calibrate_solve_unhashed(): diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_target_weight_declarations.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_target_weight_declarations.py new file mode 100644 index 0000000000..60cc05d432 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_target_weight_declarations.py @@ -0,0 +1,220 @@ +"""The UK loss weights come from the shared rules (microcosm#1729). + +``uk_runtime.target_weights`` and ``uk_runtime.national_doctrine`` say what a +UK row is and declare each UK rule name as a shared rule of +``microcosm.calibrate.target_loss_rules``; the shared rule does the +arithmetic. These tests hold the vectors equal, bit for bit, to verbatim +copies of the UK arithmetic as it stood before the move +(``test_support.microcosm_build.uk_target_weights_reference``), on synthetic +rows. Every name, code and value below is made up for the test; none comes +from a dataset. +""" + +from __future__ import annotations + +import numpy as np +import pytest + +from microcosm.build.uk_runtime.local_doctrine import ( + UK_LOCAL_ROW_METADATA_RULES, + UK_LOCAL_SOLVE_DOCTRINE, + UK_LOCAL_TARGET_WEIGHT_RULES, + uk_local_target_loss_weights, +) +from microcosm.build.uk_runtime.national_doctrine import ( + UK_NATIONAL_SOLVE_DOCTRINE, + UK_NATIONAL_TARGET_WEIGHT_RULE_DECLARATIONS, + uk_national_target_loss_weights, +) +from microcosm.build.uk_runtime.target_weights import ( + UK_LOCAL_NATION_LEVEL_RULES, + UK_LOCAL_TARGET_WEIGHT_RULE_DECLARATIONS, + uk_rule_loss_weights, + uk_target_loss_rows, + uk_target_loss_weights_for_rows, + uk_target_rows, +) +from microcosm.calibrate.target_loss_rules import TargetWeightRule +from test_support.microcosm_build import uk_target_weights_reference as before + +_LOCAL_METRICS = ( + ("households", "census_households"), + ("age/0_10", "age_structure"), + ("age/11_20", "age_structure"), + ("tenure/private_rent", "tenure"), + ("council_tax/band_a", "council_tax"), + ("hmrc/employment_income/amount", "hmrc_income_by_area"), + ("hmrc/employment_income/count", "hmrc_income_by_area"), + ("rent/private_mean", "private_rent"), + ("energy/electricity_kwh", "domestic_energy"), + ("energy/gas_connected_households", "domestic_energy"), +) +_NATIONAL = ( + ("ons_population", "K02000001", "count"), + ("ons_population", "W92000004", "count"), + ("ons_population", "E12000008", "count"), + ("ons_household_composition", "K03000001", "count"), + ("hmrc_spi_region", "E12000008", "gbp"), + ("hmrc_spi_region", "N92000002", "gbp"), + ("dwp_benefits", "E92000001", "gbp_2025"), + ("dwp_benefits", "K04000001", "count"), +) + + +def _synthetic_rows(seed: int, n_areas: int): + """A surface of every grain, with repeated families and both bases.""" + + rng = np.random.default_rng(seed) + names, metadata, values, local = [], [], [], [] + for grain, prefix in (("constituency", "E14"), ("la", "W06"), ("brma", "S33")): + for area in range(n_areas): + code = f"{prefix}{area:06d}" + for metric, family in _LOCAL_METRICS: + if grain == "brma" and not metric.startswith("rent/"): + continue + names.append(f"{grain}/{code}/{metric}") + metadata.append( + { + "area_type": grain, + "area_code": code, + "metric": metric, + "family": family, + } + ) + # Zero and sub-unit values exercise the max(|value|, 1) floor. + values.append(float(rng.choice([0.0, 0.25, rng.lognormal(8.0, 3.0)]))) + local.append(True) + for index, (family, geography, unit) in enumerate(_NATIONAL): + for repeat in range(1 + index % 3): + names.append(f"national/{family}/{geography}/{repeat}") + metadata.append( + { + "family": family, + "ledger_geography_id": geography, + "ledger_measure_unit": unit, + } + ) + values.append( + float( + -rng.lognormal(12.0, 2.0) + if repeat == 2 + else rng.lognormal(12.0, 2.0) + ) + ) + local.append(False) + order = rng.permutation(len(names)) + return uk_target_rows( + [names[i] for i in order], + [metadata[i] for i in order], + [values[i] for i in order], + local=[local[i] for i in order], + ) + + +def test_every_uk_rule_has_one_declaration() -> None: + assert tuple(UK_LOCAL_TARGET_WEIGHT_RULE_DECLARATIONS) == ( + UK_LOCAL_TARGET_WEIGHT_RULES + ) + assert UK_LOCAL_NATION_LEVEL_RULES == { + rule for rule in UK_LOCAL_TARGET_WEIGHT_RULES if rule.startswith("nation_") + } + for rule, declaration in UK_LOCAL_TARGET_WEIGHT_RULE_DECLARATIONS.items(): + assert ("count_power" in declaration.parameters) == rule.endswith("_sqrt_count") + assert dict(UK_NATIONAL_TARGET_WEIGHT_RULE_DECLARATIONS) == { + "uniform": TargetWeightRule("uniform"), + "family_equal": TargetWeightRule("level_equal"), + } + + +def test_the_doctrine_rules_are_shared_rules() -> None: + assert UK_LOCAL_SOLVE_DOCTRINE.target_weight_rule == ( + "nation_grain_family_equal_sqrt_count" + ) + assert UK_LOCAL_TARGET_WEIGHT_RULE_DECLARATIONS[ + UK_LOCAL_SOLVE_DOCTRINE.target_weight_rule + ].to_json() == { + "rule": "level_family_equal", + "parameters": {"count_power": 0.5}, + } + assert UK_NATIONAL_TARGET_WEIGHT_RULE_DECLARATIONS[ + UK_NATIONAL_SOLVE_DOCTRINE.target_weight_rule + ].to_json() == {"rule": "level_equal", "parameters": {}} + + +@pytest.mark.parametrize("rule", UK_LOCAL_ROW_METADATA_RULES) +@pytest.mark.parametrize(("seed", "n_areas"), [(0, 1), (1, 7), (2, 40)]) +def test_the_row_metadata_rules_give_the_vector_of_before(rule, seed, n_areas) -> None: + rows = _synthetic_rows(seed, n_areas) + + moved = uk_target_loss_weights_for_rows(rows, rule=rule) + reference = before.uk_target_loss_weights_for_rows(rows, rule=rule) + + assert moved.dtype == reference.dtype == np.float64 + # Equal bytes, not equal within a tolerance. + assert moved.tobytes() == reference.tobytes() + # And the vocabulary's entry point returns the same vector. + assert uk_rule_loss_weights(rows, rule=rule).tobytes() == reference.tobytes() + + +@pytest.mark.parametrize(("seed", "n_areas"), [(0, 1), (1, 7), (2, 40)]) +def test_the_family_and_grain_rules_give_the_vector_of_before(seed, n_areas) -> None: + rows = _synthetic_rows(seed, n_areas) + + # The national build's rule over the register's families. + moved = uk_national_target_loss_weights(rows.family, rule="family_equal") + reference = before.uk_national_target_loss_weights(rows.family, rule="family_equal") + assert moved.tobytes() == reference.tobytes() + assert moved.sum() == pytest.approx(1.0) + # The local grain rule, which weighs each grain as the national rule + # weighs each family (a BRMA row inside the local-authority grain). + grain_equal = uk_local_target_loss_weights(list(rows.grain), rule="grain_equal") + grains = ["la" if grain == "brma" else grain for grain in rows.grain] + assert grain_equal.tobytes() == ( + before.uk_national_target_loss_weights(grains, rule="family_equal").tobytes() + ) + assert uk_rule_loss_weights(rows, rule="grain_equal").tobytes() == ( + grain_equal.tobytes() + ) + # Uniform stays the kernel's own equal weighting. + assert uk_national_target_loss_weights(rows.family, rule="uniform") is None + assert before.uk_national_target_loss_weights(rows.family, rule="uniform") is None + + +def test_a_nation_rule_moves_nation_and_region_rows_to_their_own_level() -> None: + rows = _synthetic_rows(3, 2) + plain = uk_target_loss_rows(rows, rule="grain_family_equal") + nation = uk_target_loss_rows(rows, rule="nation_grain_family_equal") + assert set(plain.levels) == {"constituency", "la", "national"} + assert set(nation.levels) == {"constituency", "la", "national", "nation_region"} + # BRMA rows weigh inside the local-authority level under every rule. + assert "brma" in rows.grain and "brma" not in plain.levels + # Only a rule with a count power reads the basis. + assert plain.bases is None + assert ( + uk_target_loss_rows(rows, rule="grain_family_equal_sqrt_count").bases + is not None + ) + + +def test_refusals_keep_their_wording() -> None: + rows = _synthetic_rows(4, 1) + for function in ( + uk_target_loss_weights_for_rows, + before.uk_target_loss_weights_for_rows, + ): + with pytest.raises(ValueError, match="row-metadata target_weight_rule"): + function(rows, rule="grain_equal") + with pytest.raises(ValueError, match="at least one target"): + function(rows.take([]), rule="grain_family_equal") + for function in ( + uk_national_target_loss_weights, + before.uk_national_target_loss_weights, + ): + with pytest.raises(ValueError, match="requires a non-empty register"): + function([], rule="family_equal") + with pytest.raises(ValueError, match="must declare a family"): + function(["a", ""], rule="family_equal") + with pytest.raises(ValueError, match="must be one of"): + function(["a"], rule="level_equal") + with pytest.raises(ValueError, match="must be one of"): + uk_target_loss_rows(rows, rule="level_family_equal") diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_district_ess_gate.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_district_ess_gate.py index 63135b4b0b..86408491d7 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_district_ess_gate.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_district_ess_gate.py @@ -28,6 +28,7 @@ import numpy as np import pytest +from microcosm.build.area_support import effective_sample_size_by_group from test_support.paths import paths_for hypothesis = pytest.importorskip("hypothesis") @@ -524,7 +525,7 @@ def test_a_design_weight_solve_collapses_no_district(solve, relative_floor, floo assert gate["n_collapsed"] == 0 # The absolute floor is not relative: it flags the design's own thin # districts, and only those. - design_ess = _CD.ess_by_group(design, codes) + design_ess = effective_sample_size_by_group(design, codes) assert set(_districts(gate["below_floor"])) == { district for district, ess in design_ess.items() if ess < floor } diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_shared_calibration.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_shared_calibration.py new file mode 100644 index 0000000000..5e668c2862 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_shared_calibration.py @@ -0,0 +1,911 @@ +"""The ACS local release reads the shared calibration machinery (#1729). + +Two kinds of test: + +- **Defaults give the same solve.** With the default declarations the tool + calls ``calibrate`` with exactly the arguments it used before, and the + calibrated weights are the bytes a direct call with those arguments returns. + The loss weights are held to a verbatim copy of the formula as it stood + before it became a shared rule. +- **Each option is off until a build turns it on**, and then does what its + declaration says. + +A small checkpoint goes through the real ``do_calibrate``; the fixture is the +one ``test_us_acs_local_target_loss_weights.py`` builds. +""" + +from __future__ import annotations + +import importlib.util +import json +from pathlib import Path +from types import SimpleNamespace + +import numpy as np +import pytest +from hypothesis import given, settings +from hypothesis import strategies as st + +import microcosm.calibrate as calibrate_package +from microcosm.build.us_runtime import target_loss_weights as lw +from microcosm.calibrate.target_loss_rules import TargetWeightRule +from test_support.microcosm_build import us_target_loss_rows_reference as before +from test_support.microcosm_build.us_batched_target_materialization import ( + _nested_frame, +) + + +def _sibling(name: str): + spec = importlib.util.spec_from_file_location( + f"shared_calibration_{name}", Path(__file__).with_name(f"{name}.py") + ) + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + spec.loader.exec_module(module) + return module + + +_FIXTURE = _sibling("test_us_acs_local_target_loss_weights") + +#: Every keyword the calibrate stage passed to ``calibrate`` before #1729. +HISTORICAL_CALIBRATE_KEYWORDS = { + "weight_entity", + "method", + "epochs", + "learning_rate", + "mass", + "max_weight_ratio", + "target_loss_cap", + "l2_lambda", + "l2_basis", + "mass_parametrization", + "seed", + "target_loss_weights", + "warm_start_weights", +} + + +@pytest.fixture +def calibrate_run(monkeypatch, tmp_path): + """Run ``do_calibrate`` on the fixture; keep every ``calibrate`` call.""" + + module = _FIXTURE._load_tool_module() + registry, records, matrix, design = _FIXTURE._surface(module) + frame = _nested_frame() + identity = {"staging_sha256": "s", "target_roles_sha256": "r"} + monkeypatch.setattr(module, "_verify_run_identity", lambda args: identity) + monkeypatch.setattr( + module, + "load_checkpoint_surface", + lambda *_a, **_k: (frame, design, registry, records, matrix), + ) + calls: list[dict] = [] + real_calibrate = calibrate_package.calibrate + + def spy(frame, targets, **kwargs): + result = real_calibrate(frame, targets, **kwargs) + calls.append({"frame": frame, "targets": targets, "kwargs": dict(kwargs)}) + return result + + monkeypatch.setattr(calibrate_package, "calibrate", spy) + release_tool_tests = _FIXTURE._load_release_tool_tests() + + def run(**overrides): + calls.clear() + args = _FIXTURE._args(tmp_path, **overrides) + release_tool_tests._record_current_materialization(module, args, identity) + module.do_calibrate(args) + return calls + + held = {record["name"] for record in records if record["role"] == "holdout"} + return SimpleNamespace( + module=module, + run=run, + path=tmp_path, + real_calibrate=real_calibrate, + registry=registry, + train=[spec for spec in registry.specs if spec.name not in held], + ) + + +def _summary(run) -> dict: + return json.loads((run.path / "calibration_summary.json").read_text()) + + +def _saved_weights(run) -> np.ndarray: + return np.load(run.path / "weights_latest.npz")["weights"] + + +def _reference_weights(train) -> np.ndarray: + """The loss weights the formula gave before it became a shared rule.""" + + mapping = lw.US_ACS_LOCAL_TARGET_LOSS_ROW_MAPPING + return before.target_loss_weights_from_rows( + [spec.value for spec in train], + [mapping.value_basis(spec) for spec in train], + [mapping.concept_budget_key(spec) for spec in train], + [spec.family for spec in train], + ) + + +# --------------------------------------------------------------------------- +# Defaults give the same solve +# --------------------------------------------------------------------------- + + +def test_the_default_run_calls_calibrate_exactly_as_before(calibrate_run) -> None: + calls = calibrate_run.run() + reference = _reference_weights(calibrate_run.train) + + assert len(calls) == 2 # 6 epochs in batches of 3 + for index, call in enumerate(calls): + kwargs = call["kwargs"] + # No new keyword reaches the solver unless a build asks for it. + assert set(kwargs) == HISTORICAL_CALIBRATE_KEYWORDS + assert { + key: kwargs[key] + for key in HISTORICAL_CALIBRATE_KEYWORDS + - {"target_loss_weights", "warm_start_weights"} + } == { + "weight_entity": "household", + "method": "adam", + "epochs": 3, + "learning_rate": 0.02, + "mass": "conserve", + "max_weight_ratio": 5.0, + "target_loss_cap": 1.0, + "l2_lambda": 0.0, + "l2_basis": "record", + "mass_parametrization": "projection", + "seed": 0, + } + assert isinstance(kwargs["target_loss_cap"], float) + # The loss weights are the pre-change formula's bytes. + assert kwargs["target_loss_weights"].tobytes() == reference.tobytes() + assert (kwargs["warm_start_weights"] is None) == (index == 0) + + +def test_the_default_run_returns_the_weights_of_the_historical_call( + calibrate_run, +) -> None: + calls = calibrate_run.run() + produced = _saved_weights(calibrate_run) + + # The same two batches, called directly with the historical arguments and + # the pre-change loss weights: nothing of the tool or the shared rule. + warm = None + for call in calls: + result = calibrate_run.real_calibrate( + call["frame"], + call["targets"], + weight_entity="household", + method="adam", + epochs=3, + learning_rate=0.02, + mass="conserve", + max_weight_ratio=5.0, + target_loss_cap=1.0, + l2_lambda=0.0, + l2_basis="record", + mass_parametrization="projection", + seed=0, + target_loss_weights=_reference_weights(calibrate_run.train), + warm_start_weights=warm, + ) + warm = result.weights.copy() + + assert produced.tobytes() == warm.tobytes() + assert not np.array_equal(produced, [1.0, 2.0, 3.0, 4.0, 5.0]) + + +def test_the_default_stamp_and_summary_record_nothing_new(calibrate_run) -> None: + calibrate_run.run() + summary = _summary(calibrate_run) + + assert set(summary["solver_settings"]) == { + "method", + "learning_rate", + "mass", + "max_weight_ratio", + "target_loss_cap", + "l2_lambda", + "l2_basis", + "mass_parametrization", + "seed", + "epoch_batch", + "target_loss", + } + assert set(summary["solver_settings"]["target_loss"]) == { + "weighting", + "row_mapping", + "family_multipliers", + "n_targets", + "weights_sha256", + } + assert summary["solver_settings"]["target_loss"]["weighting"] == ( + lw.US_FISCAL_TARGET_LOSS_WEIGHTING + ) + + +_BASES = st.sampled_from(["count", "amount"]) +_ROWS = st.lists( + st.tuples( + st.floats(-1e12, 1e12, allow_nan=False), + _BASES, + st.integers(0, 6), + st.sampled_from(["irs_soi", "usda_snap", "census_population", None]), + ), + min_size=0, + max_size=40, +) + + +@settings(max_examples=200, deadline=None) +@given(rows=_ROWS, multiplier=st.sampled_from([None, 0.25, 3.0])) +def test_the_shared_rule_is_the_formula_bit_for_bit(rows, multiplier) -> None: + values = [row[0] for row in rows] + bases = [row[1] for row in rows] + keys = [row[2] for row in rows] + families = [row[3] for row in rows] + multipliers = ( + {"irs_soi": multiplier} + if multiplier is not None and "irs_soi" in families + else None + ) + + moved = lw.target_loss_weights_from_rows(values, bases, keys, families, multipliers) + reference = before.target_loss_weights_from_rows( + values, bases, keys, families, multipliers + ) + + assert moved.dtype == reference.dtype + assert moved.tobytes() == reference.tobytes() + + +def test_an_unmatched_multiplier_keeps_the_release_wording() -> None: + arguments = ([1.0, 2.0], ["count", "amount"], [0, 1], ["a", "b"]) + for function in ( + lw.target_loss_weights_from_rows, + before.target_loss_weights_from_rows, + ): + with pytest.raises( + ValueError, + match="--target-family-loss-multiplier family 'c' matches no compiled", + ): + function(*arguments, {"c": 2.0, "a": 3.0}) + + +# --------------------------------------------------------------------------- +# Item 2: the weight rule is a declaration +# --------------------------------------------------------------------------- + + +def test_the_release_declares_its_weight_rules_as_data() -> None: + assert lw.US_ACS_LOCAL_TARGET_WEIGHT_RULE == "concept_budget" + assert lw.US_ACS_LOCAL_TARGET_WEIGHT_RULES["concept_budget"] == TargetWeightRule( + "sqrt_value_concept_budget", {"value_power": 0.5} + ) + assert lw.acs_local_target_weight_rule("level_family_equal_sqrt_count") == ( + TargetWeightRule("level_family_equal", {"count_power": 0.5}) + ) + with pytest.raises(ValueError, match="must be one of"): + lw.acs_local_target_weight_rule("grain_equal") + + +def test_the_cli_defaults_to_the_formula_every_build_has_used(tmp_path) -> None: + module = _FIXTURE._load_tool_module() + base = [ + "--stage", "calibrate", + "--staging-h5", str(tmp_path / "s.h5"), + "--checkpoint-dir", str(tmp_path), + "--out-h5", str(tmp_path / "out.h5"), + ] # fmt: skip + assert module._parse_args(base).target_weight_rule == "concept_budget" + chosen = module._parse_args( + [*base, "--target-weight-rule", "level_family_equal_sqrt_count"] + ) + assert chosen.target_weight_rule == "level_family_equal_sqrt_count" + with pytest.raises(SystemExit): + module._parse_args([*base, "--target-weight-rule", "uniform"]) + + +def test_the_level_rule_gives_each_geography_level_one_share(calibrate_run) -> None: + calls = calibrate_run.run(target_weight_rule="level_family_equal_sqrt_count") + train = calibrate_run.train + weights = calls[0]["kwargs"]["target_loss_weights"] + levels = np.asarray([lw.target_geography_level(spec) for spec in train]) + + assert set(levels) == {"state", "congressional_district"} + for level in set(levels): + assert weights[levels == level].sum() / weights.sum() == pytest.approx(0.5) + # Under the default formula the two levels do not share equally. + default = _reference_weights(train) + state_share = default[levels == "state"].sum() / default.sum() + assert abs(state_share - 0.5) > 0.05 + + stamp = _summary(calibrate_run)["solver_settings"]["target_loss"] + assert stamp["weighting"] == "level_family_equal_sqrt_count" + assert stamp["rule"] == { + "rule": "level_family_equal", + "parameters": {"count_power": 0.5}, + } + + +def test_resume_refuses_weights_calibrated_under_another_rule(calibrate_run) -> None: + calibrate_run.run() + with pytest.raises(SystemExit, match="different solver settings"): + calibrate_run.run( + resume=True, target_weight_rule="level_family_equal_sqrt_count" + ) + + +# --------------------------------------------------------------------------- +# Item 3: a loss cap for the county rows only +# --------------------------------------------------------------------------- + + +def _cli(module, *options): + return module._parse_args( + [ + "--stage", + "calibrate", + "--staging-h5", + "staging.h5", + "--checkpoint-dir", + "checkpoint", + "--out-h5", + "calibrated.h5", + *options, + ] # fmt: skip + ) + + +def test_the_county_cap_applies_to_the_run_by_default() -> None: + module = _FIXTURE._load_tool_module() + args = _cli(module, "--geographies", "state,cd,county") + assert args.county_target_loss_cap_scope == "run" + assert args.target_loss_cap == 10.0 + assert args.county_rows_target_loss_cap is None + assert args.county_solver_profile == { + "scope": "run", + "target_loss_cap": 10.0, + "max_weight_ratio": 5.0, + } + + +def test_the_county_rows_scope_keeps_the_cap_of_the_other_rows() -> None: + module = _FIXTURE._load_tool_module() + args = _cli( + module, + "--geographies", "state,cd,county", + "--county-target-loss-cap-scope", "county_rows", + "--target-loss-cap", "2", + ) # fmt: skip + assert args.target_loss_cap == 2.0 + assert args.county_rows_target_loss_cap == 10.0 + settings = module._solver_settings(args, {}) + assert settings["target_loss_cap"] == 2.0 + # The scope is in the stamp, so a resume refuses weights of the other one. + assert settings["county_solver_profile"] == { + "scope": "county_rows", + "target_loss_cap": 10.0, + "max_weight_ratio": 5.0, + } + + +def test_the_scope_changes_nothing_without_county_rows() -> None: + module = _FIXTURE._load_tool_module() + plain = _cli(module) + scoped = _cli(module, "--county-target-loss-cap-scope", "county_rows") + assert scoped.county_rows_target_loss_cap is None + assert module._solver_settings(scoped, {}) == module._solver_settings(plain, {}) + + +def _joint_problem(module): + """Three households; a county row and a state row, each a 200% miss.""" + + import pandas as pd + from scipy import sparse + + from microcosm.frame import EntitySchema, Frame, WeightKind, Weights + + design = np.asarray([300.0, 300.0, 300.0]) + frame = Frame( + { + "person": pd.DataFrame( + {"person_id": [1, 2, 3], "person_household_id": [1, 2, 3]} + ), + "household": pd.DataFrame( + { + "household_id": [1, 2, 3], + "state_fips": [1, 1, 1], + "county_fips": [1001, 1003, 1005], + } + ), + }, + EntitySchema(group_entities=("household",)), + {"household": Weights(design, WeightKind.DESIGN)}, + ) + county = module.county_surface.population_spec("pop_county_01001", 100.0) + (state,) = module.population_target_specs(["pop_state_01"], [100.0]) + records = [ + {**module.county_surface.target_record(county), "role": "train"}, + {**module.cd_surface.target_record(state), "role": "train"}, + ] + targets = module.cd_surface.calibration_target_set( + records, + sparse.csr_array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], dtype=np.float32), + 3, + specs=[county, state], + ) + return frame, targets, [county, state], design + + +def _solve_joint(module, *options): + args = _cli(module, "--geographies", "state,county", *options) + frame, targets, specs, design = _joint_problem(module) + loss = module.release_target_loss_caps(args, targets, specs, np.ones(2)) + result, _done = module.calibrate_surface( + frame, + targets, + epochs=80, + epoch_batch=40, + max_weight_ratio=args.max_weight_ratio, + target_loss_cap=loss["cap"], + l2_lambda=0.0, + seed=0, + target_loss_weights=loss["weights"], + target_loss_scales=loss["scales"], + ) + return loss, result, design + + +def test_the_run_scope_passes_one_cap_and_no_scales() -> None: + module = _FIXTURE._load_tool_module() + loss, result, design = _solve_joint(module) + assert loss == { + "cap": 10.0, + "weights": loss["weights"], + "scales": None, + "receipt": None, + } + np.testing.assert_array_equal(loss["weights"], np.ones(2)) + # Cap 10 gives both rows a gradient, so both far misses are corrected. + assert result.weights[0] < design[0] and result.weights[1] < design[1] + + +def test_the_county_rows_scope_corrects_the_county_row_only() -> None: + module = _FIXTURE._load_tool_module() + loss, result, design = _solve_joint( + module, "--county-target-loss-cap-scope", "county_rows" + ) + # Declared caps: county 10, state 1 (the default --target-loss-cap). + assert loss["receipt"] == { + "default": 1.0, + "by_level": {"county": 10.0}, + "method": "single_cap_equivalent", + "equivalent_cap": 5.5, + "rows_by_cap": {"1.0": 1, "10.0": 1}, + } + # The solver's one-cap loss gives each row its own cap in its own units: + # scale * cap0 / (target scale) is the miss at which the row goes flat. + flat_at = loss["scales"] * loss["cap"] / 100.0 + np.testing.assert_allclose(flat_at, [10.0, 1.0]) + assert result.weights.sum() == pytest.approx(design.sum()) + # The county row (200% miss, cap 10) has a gradient and moves to its target. + assert abs(result.weights[0] - 100.0) < abs(design[0] - 100.0) + # The state row (200% miss, cap 1) is past its cap, as in a run without + # county rows: it has no gradient, so its household is not pulled down. + assert result.weights[1] >= design[1] + + +def test_a_county_rows_cap_without_a_county_training_row_is_refused() -> None: + module = _FIXTURE._load_tool_module() + args = _cli( + module, + "--geographies", "state,county", + "--county-target-loss-cap-scope", "county_rows", + ) # fmt: skip + frame, targets, specs, _design = _joint_problem(module) + with pytest.raises(SystemExit, match="level 'county' matches no target"): + module.release_target_loss_caps(args, targets[1:], specs[1:], np.ones(1)) + + +def test_the_caps_receipt_reads_each_row_against_its_own_cap() -> None: + from microcosm.calibrate.diagnostics import past_cap_census + + module = _FIXTURE._load_tool_module() + args = _cli( + module, + "--geographies", "state,county", + "--county-target-loss-cap-scope", "county_rows", + ) # fmt: skip + frame, targets, specs, _design = _joint_problem(module) + loss = module.release_target_loss_caps(args, targets, specs, np.ones(2)) + # Nothing to do in one epoch: the estimates stay the starting ones. + result, _done = module.calibrate_surface( + frame, + targets, + epochs=1, + epoch_batch=1, + max_weight_ratio=args.max_weight_ratio, + target_loss_cap=loss["cap"], + l2_lambda=0.0, + seed=0, + target_loss_weights=loss["weights"], + target_loss_scales=loss["scales"], + ) + + receipt = module.target_loss_caps_receipt(loss, result) + + assert receipt["default"] == 1.0 and receipt["by_level"] == {"county": 10.0} + assert receipt["rows_not_at_default"] == {"pop_county_01001@2024": 10.0} + census = receipt["past_cap_census"] + # Both rows miss by 200% at the start. That is past the state row's cap + # of 1 and inside the county row's cap of 10. + assert census["cap_basis"] == "each row's own cap" + assert census["initial_past_cap"] == 1 + assert census["by_cap"]["1.0"]["initial_past_cap"] == 1 + assert census["by_cap"]["10.0"]["initial_past_cap"] == 0 + # The solver's own census reads both rows against the equivalent cap, 5.5, + # and sees neither past it: the reason the receipt carries its own. + solver_census = past_cap_census(result) + assert solver_census["cap"] == pytest.approx(5.5) + assert solver_census["initial_past_cap"] == 0 + assert "equivalent_cap" in receipt["how_to_read_the_diagnostics"] + # One cap for the run records nothing. + plain = module.release_target_loss_caps( + _cli(module, "--geographies", "state,county"), targets, specs, np.ones(2) + ) + assert module.target_loss_caps_receipt(plain, result) is None + + +def test_diagnostics_of_a_row_cap_solve_match_the_published_schema( + calibrate_run, tmp_path +) -> None: + from microcosm.calibrate import default_target_loss_scales + from microcosm.calibrate.target_loss_rules import ( + single_cap_equivalent, + target_loss_caps, + ) + + module = calibrate_run.module + call = calibrate_run.run()[0] + train = calibrate_run.train + caps = target_loss_caps( + 1.0, + levels=[lw.target_geography_level(spec) for spec in train], + by_level={"congressional_district": 10.0}, + ) + scales = default_target_loss_scales( + np.asarray([target.value for target in call["targets"]]) + ) + equivalent = single_cap_equivalent( + caps, weights=call["kwargs"]["target_loss_weights"], scales=scales + ) + result = calibrate_run.real_calibrate( + call["frame"], + call["targets"], + **{ + **call["kwargs"], + "target_loss_cap": equivalent.cap, + "target_loss_weights": equivalent.weights, + "target_loss_scales": equivalent.scales, + }, + ) + # The block the calibrate stage puts in the diagnostics under row caps. + receipt = module.target_loss_caps_receipt( + { + "receipt": { + "default": 1.0, + "by_level": {"congressional_district": 10.0}, + **equivalent.receipt(), + }, + "row_caps": equivalent.caps, + "row_scales": scales, + }, + result, + ) + written = tmp_path / "row_cap_diagnostics.json" + outcome = calibrate_package.write_calibration_diagnostics( + result, + written, + target_registry=calibrate_run.registry, + build={"target_loss_cap": equivalent.cap, "target_loss_caps": receipt}, + ) + + assert outcome.status == "available" + document = _FIXTURE.load_strict_json(written.read_bytes()) + assert _FIXTURE.published_json_schema_errors(document) == [] + assert result.options["target_loss_scales"]["kind"] == "provided" + assert result.target_loss_cap == pytest.approx(equivalent.cap) + # The file itself says which rows have another cap, and carries the + # census against each row's own cap beside the solver's. + recorded = document["build"]["target_loss_caps"] + assert recorded["by_level"] == {"congressional_district": 10.0} + assert len(recorded["rows_not_at_default"]) == int((caps == 10.0).sum()) + assert recorded["past_cap_census"]["n_targets"] == len(train) + assert set(recorded["past_cap_census"]["by_cap"]) == {"1.0", "10.0"} + assert document["past_cap_census"]["cap"] == pytest.approx(equivalent.cap) + + +# --------------------------------------------------------------------------- +# Item 4: the district gate reads the shared area support gate +# --------------------------------------------------------------------------- + + +_ESS = st.floats(0.0, 500.0, allow_nan=False) | st.sampled_from([0.0, 15.0, 60.0]) +_DISTRICT_ESS = st.dictionaries( + st.sampled_from(["0601", "0602", "2401", "3601", "3602", "5000"]), + st.tuples(_ESS, _ESS), + min_size=1, +) +_GATE_FLOORS = st.tuples( + st.sampled_from([0.0, 0.25, 0.5, 1.0]) | st.floats(0.0, 1.0), + st.sampled_from([0.0, 15.0]) | st.floats(0.0, 100.0), + st.booleans(), +) + + +@settings(max_examples=300, deadline=None) +@given(districts=_DISTRICT_ESS, floors=_GATE_FLOORS) +def test_the_district_gate_entry_is_the_entry_of_before(districts, floors) -> None: + from test_support.microcosm_build import us_district_ess_gate_reference as old + + module = _FIXTURE._load_tool_module() + origin = { + "design": { + "effective_sample_size_by_district": { + district: design for district, (design, _c) in districts.items() + } + }, + "calibrated": { + "effective_sample_size_by_district": { + district: calibrated for district, (_d, calibrated) in districts.items() + } + }, + } + relative_floor, absolute_floor, blocking = floors + arguments = dict( + relative_floor=relative_floor, absolute_floor=absolute_floor, blocking=blocking + ) + + entry = module.district_ess_collapse_gate(origin, **arguments) + + assert entry == old.district_ess_collapse_gate(origin, **arguments) + assert entry["report_only"] is (not blocking) + if not blocking: + # Report-only: the entry passes whatever it measured. + assert entry["passed"] is True + + +def test_the_district_gate_is_report_only_by_default(tmp_path) -> None: + module = _FIXTURE._load_tool_module() + args = _cli(module) + assert args.district_ess_gate_blocking is False + collapsed = { + "design": {"effective_sample_size_by_district": {"0601": 400.0}}, + "calibrated": {"effective_sample_size_by_district": {"0601": 2.0}}, + } + entry = module.district_ess_collapse_gate(collapsed) + assert entry["criteria_met"] is False + assert entry["passed"] is True and entry["blocking"] is False + assert module.district_ess_collapse_failures(entry) == [] + + +def test_the_tools_hold_no_copy_of_the_ess_or_gate_code() -> None: + module = _FIXTURE._load_tool_module() + assert not hasattr(module.cd_surface, "ess_by_group") + repository = _FIXTURE._TEST_PATHS.repository + for tool in ("build_us_acs_local_release.py", "us_acs_local_cd_surface.py"): + source = (repository / "tools" / tool).read_text() + # No Kish arithmetic of its own: sum(w)^2 over sum(w^2). + assert "** 2 / (" not in source and '["w"] ** 2' not in source + gate = (repository / "tools" / "build_us_acs_local_release.py").read_text() + body = gate[ + gate.index("def district_ess_collapse_gate(") : gate.index( + "def district_ess_collapse_failures(" + ) + ] + # The floors are compared in the shared gate, not here. + assert "area_support_gate(" in body and "area_support_floor_table(" in body + assert "relative_floor *" not in body and "< absolute_floor" not in body + + +# --------------------------------------------------------------------------- +# Item 1: the L2 anchor +# --------------------------------------------------------------------------- + + +def test_the_cli_exposes_the_l2_anchor_with_the_default_of_every_solve( + tmp_path, +) -> None: + module = _FIXTURE._load_tool_module() + default = _cli(module) + assert (default.l2_anchor, default.l2_anchor_weights) == ("initial", None) + assert _cli(module, "--l2-anchor", "uniform").l2_anchor == "uniform" + anchor = tmp_path / "anchor.npy" + named = _cli( + module, + "--l2-anchor", + "household_proportional", + "--l2-anchor-weights", + str(anchor), + ) + assert (named.l2_anchor, named.l2_anchor_weights) == ( + "household_proportional", + anchor, + ) + for bad in ( + ("--l2-anchor", "household_proportional"), # a name with no vector + ("--l2-anchor-weights", str(anchor)), # a vector with no name + ("--l2-anchor", "uniform", "--l2-anchor-weights", str(anchor)), + ): + with pytest.raises(SystemExit): + _cli(module, *bad) + + +def test_the_default_anchor_adds_no_keyword_and_no_stamp() -> None: + module = _FIXTURE._load_tool_module() + args = _cli(module) + assert module.release_l2_anchor(args, np.arange(5)) == ({}, None) + assert "l2_anchor" not in module._solver_settings(args, {}, None) + + +def test_the_uniform_anchor_reaches_calibrate_and_the_stamp(calibrate_run) -> None: + calls = calibrate_run.run( + l2_anchor="uniform", l2_lambda=0.05, l2_basis="chi_square" + ) + for call in calls: + assert set(call["kwargs"]) == HISTORICAL_CALIBRATE_KEYWORDS | {"l2_anchor"} + assert call["kwargs"]["l2_anchor"] == "uniform" + summary = _summary(calibrate_run) + assert summary["l2_anchor"] == "uniform" + assert summary["solver_settings"]["l2_anchor"] == "uniform" + assert "l2_anchor_weights_sha256" not in summary["solver_settings"] + + +def test_anchor_weights_pull_toward_a_declared_design(calibrate_run) -> None: + from microcosm.calibrate import chi_square_distance + + module = calibrate_run.module + design = np.asarray([1.0, 2.0, 3.0, 4.0, 5.0]) + # A declared design that is not the starting weights: equal households. + declared = np.full(5, 3.0) + anchor = calibrate_run.path / "anchor.npz" + np.savez(anchor, weights=declared, household_id=np.arange(1, 6)) + penalty = dict(l2_lambda=5.0, l2_basis="chi_square", epochs=60, epoch_batch=30) + + calibrate_run.run(**penalty) + toward_start = _saved_weights(calibrate_run) + calls = calibrate_run.run( + **penalty, l2_anchor="equal_households", l2_anchor_weights=anchor + ) + toward_declared = _saved_weights(calibrate_run) + + for call in calls: + assert call["kwargs"]["l2_anchor"] == "equal_households" + np.testing.assert_array_equal(call["kwargs"]["l2_anchor_weights"], declared) + # The starting weights, and so the bound and the mass, did not change. + saved = np.load(calibrate_run.path / "weights_latest.npz") + np.testing.assert_array_equal(saved["initial_weights"], design) + assert toward_declared.sum() == pytest.approx(design.sum()) + assert (toward_declared <= 5.0 * design * (1 + 1e-12)).all() + # The penalty pulled toward the declared design instead of the start. + assert chi_square_distance(toward_declared, declared) < chi_square_distance( + toward_start, declared + ) + stamp = _summary(calibrate_run)["solver_settings"] + assert stamp["l2_anchor"] == "equal_households" + assert stamp["l2_anchor_weights_sha256"] == module._weights_digest(declared) + # Another anchor is another solve: a resume refuses these weights. + with pytest.raises(SystemExit, match="different solver settings"): + calibrate_run.run(**penalty, resume=True) + + +def test_anchor_weights_must_fit_the_checkpoint(calibrate_run, tmp_path) -> None: + module = calibrate_run.module + households = np.arange(1, 6) + + def anchor(name, **arrays): + path = tmp_path / name + if name.endswith(".npy"): + np.save(path, arrays["weights"]) + else: + np.savez(path, **arrays) + return SimpleNamespace(l2_anchor="declared", l2_anchor_weights=path) + + keywords, stamp = module.release_l2_anchor( + anchor("plain.npy", weights=np.ones(5)), households + ) + assert keywords["l2_anchor"] == "declared" and stamp["l2_anchor"] == "declared" + np.testing.assert_array_equal(keywords["l2_anchor_weights"], np.ones(5)) + for name, arrays, match in ( + ("short.npy", {"weights": np.ones(4)}, "has shape"), + ("zero.npy", {"weights": np.asarray([1.0, 1, 1, 1, 0])}, "strictly positive"), + ("nokey.npz", {"anchor": np.ones(5)}, "has no 'weights' array"), + ( + "order.npz", + {"weights": np.ones(5), "household_id": households[::-1]}, + "other households", + ), + ): + with pytest.raises(SystemExit, match=match): + module.release_l2_anchor(anchor(name, **arrays), households) + + +# --------------------------------------------------------------------------- +# Item 5: the weight bound against a declared reference +# --------------------------------------------------------------------------- + + +def test_the_cli_bounds_against_each_households_own_weight_by_default() -> None: + module = _FIXTURE._load_tool_module() + assert _cli(module).weight_bound_reference == "own" + assert _cli( + module, "--weight-bound-reference", "district_mean" + ).weight_bound_reference == ("district_mean") + with pytest.raises(SystemExit): + _cli(module, "--weight-bound-reference", "median") + households = SimpleNamespace(columns=[]) + assert module.release_weight_bound(_cli(module), households, np.ones(3)) == ( + {}, + None, + ) + + +def test_a_shared_reference_reaches_calibrate_and_the_stamp(calibrate_run) -> None: + design = np.asarray([1.0, 2.0, 3.0, 4.0, 5.0]) + calls = calibrate_run.run( + weight_bound_reference="mean", max_weight_ratio=1.5, epochs=60, epoch_batch=30 + ) + bound = 1.5 * design.mean() # 4.5 for every household + for call in calls: + assert set(call["kwargs"]) == HISTORICAL_CALIBRATE_KEYWORDS | { + "max_weight_reference" + } + np.testing.assert_allclose(call["kwargs"]["max_weight_reference"], 3.0) + weights = _saved_weights(calibrate_run) + # One absolute bound for every household, whatever its starting weight. + assert (weights <= bound * (1 + 1e-12)).all() + assert weights.sum() == pytest.approx(design.sum()) + summary = _summary(calibrate_run) + assert summary["weight_bound_reference"] == "mean" + assert summary["solver_settings"]["weight_bound_reference"] == "mean" + # The heaviest household (5) starts above the shared bound (4.5). + assert summary["weight_bound"]["reference"] == "declared" + assert summary["weight_bound"]["records_started_above_bound"] == 1 + assert summary["weight_bound"]["realized_max_ratio_to_reference"] <= 1.5 * ( + 1 + 1e-12 + ) + # Another reference is another solve: a resume refuses these weights. + with pytest.raises(SystemExit, match="different solver settings"): + calibrate_run.run(max_weight_ratio=1.5, epochs=60, epoch_batch=30, resume=True) + + +def test_an_area_mean_reference_reads_the_households_area() -> None: + import pandas as pd + + module = _FIXTURE._load_tool_module() + households = pd.DataFrame({"state_fips": [6, 6, 36, 36, 36]}) + design = np.asarray([27.0, 1.0, 27.0, 1.0, 2.0]) + args = SimpleNamespace(weight_bound_reference="state_mean", max_weight_ratio=5.0) + + keywords, stamp = module.release_weight_bound(args, households, design) + + np.testing.assert_allclose( + keywords["max_weight_reference"], [14.0, 14.0, 10.0, 10.0, 10.0] + ) + assert stamp == {"weight_bound_reference": "state_mean"} + args.weight_bound_reference = "district_mean" + with pytest.raises(SystemExit, match="congressional_district_geoid"): + module.release_weight_bound(args, households, design) + + +def test_bounds_that_cannot_hold_the_mass_stop_before_the_solve() -> None: + import pandas as pd + + module = _FIXTURE._load_tool_module() + args = SimpleNamespace(weight_bound_reference="mean", max_weight_ratio=0.5) + with pytest.raises(SystemExit, match="Raise --max-weight-ratio"): + module.release_weight_bound(args, pd.DataFrame(), np.asarray([1.0, 2.0, 3.0])) 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 1289e207db..6be927d3a6 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": "9f56635edf7da4efa90d01e6ab263eb5f17267ab4bf5b2ad843d76b27f00cfb2", + "spec_sha256": "b94bfc6a5742de010443938a676d4d34e70df80dd405f89e2ff7a70f747c8107", }, } diff --git a/packages/microcosm-calibrate/src/microcosm/calibrate/solve.py b/packages/microcosm-calibrate/src/microcosm/calibrate/solve.py index 483d2f920a..b413091678 100644 --- a/packages/microcosm-calibrate/src/microcosm/calibrate/solve.py +++ b/packages/microcosm-calibrate/src/microcosm/calibrate/solve.py @@ -28,7 +28,14 @@ exceed ``max_weight_ratio * initial_weight``. It is clamped after every step — the documented guard against the tail "landmine" (a rare high-value, near-zero-weight donor whose weight detonates on reweight and blows up an - aggregate). + aggregate). The bound is against the frame's weights, never against a warm + start, so a stage whose frame carries an earlier stage's weights bounds + against those (:mod:`microcosm.calibrate.weight_bound` states the contract). +- ``max_weight_reference`` (opt-in) bounds against a declared weight for each + record instead: no calibrated weight may exceed + ``max_weight_ratio * max_weight_reference``. A record that starts heavier + than the others then gets no larger a bound for it. The starting weights, + the mass and the L2 anchor stay the frame's. - ``target_records`` turns on hard-concrete L0 gates (:mod:`microcosm.calibrate.gates`) with **budget control**: the solver searches ``l0_lambda`` (a bisection on its log) so the achieved non-zero count tracks @@ -992,6 +999,33 @@ def _prepare_warm_start_weights( return prepared +def _prepare_reference_bound_start( + initial_weights: np.ndarray, + warm_start_weights: np.ndarray | None, + reference: np.ndarray, + *, + conserve_mass: bool, + max_weight_ratio: float, +) -> np.ndarray: + """The optimizer's start under a bound against a declared reference. + + Under ``max_weight_reference`` a record may start above its bound, + ``max_weight_ratio * reference``. The start is the starting weights (or + the warm start) held to the bound and, under mass conservation, brought + back to the input total below the bound. A warm start gets the same + projection under the default bound. + """ + w0 = np.asarray(initial_weights, dtype=np.float64) + # The warm start's checks and copy, with no bound and no projection. + start = _prepare_warm_start_weights( + w0, warm_start_weights, conserve_mass=False, max_weight_ratio=None + ) + start = np.minimum(start, max_weight_ratio * reference) + if conserve_mass: + start = _project_to_total(start, float(w0.sum()), max_weight_ratio, reference) + return start + + def _l2_penalty( pre_gate_weights: torch.Tensor, anchor: torch.Tensor, @@ -1257,6 +1291,7 @@ def _optimize( return_gate_open_probabilities: bool = False, selection_receipt: dict[str, object] | None = None, retain_best_objective: bool = False, + weight_bound_reference: np.ndarray | None = None, ) -> tuple[np.ndarray, np.ndarray] | tuple[np.ndarray, np.ndarray, np.ndarray | None]: """Run the torch optimization and return weights plus its trajectory. @@ -1277,14 +1312,29 @@ def _optimize( value without changing the two-item tuple used by existing workspace callers. The third value is aligned per-record ``pi_i`` for an L0 run and ``None`` when no gates were active. + + ``weight_bound_reference`` is the weight ``max_weight_ratio`` multiplies + for each record. ``None`` (default) is the record's own starting weight, + and every expression below is then the historical one. """ w0 = np.asarray(initial_weights, dtype=np.float64) - start = _prepare_warm_start_weights( - w0, - warm_start_weights, - conserve_mass=conserve_mass, - max_weight_ratio=max_weight_ratio, - ) + if weight_bound_reference is None: + bound_base = w0 + start = _prepare_warm_start_weights( + w0, + warm_start_weights, + conserve_mass=conserve_mass, + max_weight_ratio=max_weight_ratio, + ) + else: + bound_base = np.asarray(weight_bound_reference, dtype=np.float64) + start = _prepare_reference_bound_start( + w0, + warm_start_weights, + bound_base, + conserve_mass=conserve_mass, + max_weight_ratio=max_weight_ratio, + ) total0 = float(w0.sum()) # Same prune threshold the result's n_nonzero uses, so "pruned" here means # exactly what the reported non-zero count means. @@ -1319,7 +1369,7 @@ def _optimize( optimizer = torch.optim.Adam(params, lr=learning_rate) upper = ( - torch.tensor(max_weight_ratio * w0, dtype=torch.float32) + torch.tensor(max_weight_ratio * bound_base, dtype=torch.float32) if max_weight_ratio is not None else None ) @@ -1331,7 +1381,7 @@ def _optimize( softmax_max_cap_ratio = 0.0 if softmax_mass and upper is not None: softmax_log_upper = torch.log(upper).to(torch.float64) - softmax_cap = torch.tensor(max_weight_ratio * w0, dtype=torch.float64) + softmax_cap = torch.tensor(max_weight_ratio * bound_base, dtype=torch.float64) if l2_lambda > 0.0: # The L2 penalty's reference vector. "initial" divides by each record's # own starting weight; "uniform" divides by the shared mean weight; an @@ -1530,9 +1580,12 @@ def _optimize( # Make the hard ratio bound exact on the returned vector. The per-step # clamp is in float32, so exp() can overshoot the bound by a float epsilon # (~1e-7 relative); a closing float64 cap guarantees no returned weight - # exceeds max_weight_ratio * w0, which downstream code may assert. + # exceeds max_weight_ratio * w0 (or the declared reference), which + # downstream code may assert. if max_weight_ratio is not None: - final = np.minimum(final, max_weight_ratio * np.asarray(w0, dtype=np.float64)) + final = np.minimum( + final, max_weight_ratio * np.asarray(bound_base, dtype=np.float64) + ) # Exact mass conservation on the returned vector: a single closing rescale # to the input total. When a max_weight_ratio is also set, the rescale is @@ -1544,7 +1597,9 @@ def _optimize( pruned = ( final <= prune_atol if (gates is not None and l0_lambda > 0.0) else None ) - final = _project_to_total(final, total0, max_weight_ratio, w0, pruned=pruned) + final = _project_to_total( + final, total0, max_weight_ratio, bound_base, pruned=pruned + ) if return_gate_open_probabilities: return final, trajectory, gate_open_probabilities return final, trajectory @@ -2336,7 +2391,11 @@ def _check_mass(mass: str) -> None: def _check_epochs_and_weight_ratio( - epochs: int, max_weight_ratio: float | None, *, mass: str + epochs: int, + max_weight_ratio: float | None, + *, + mass: str, + reference_bound: bool = False, ) -> None: if epochs <= 0: raise ValueError(f"epochs must be positive, got {epochs!r}.") @@ -2344,7 +2403,14 @@ def _check_epochs_and_weight_ratio( raise ValueError( f"max_weight_ratio must be positive, got {max_weight_ratio!r}." ) - if max_weight_ratio is not None and max_weight_ratio < 1 and mass == CONSERVE_MASS: + # Against a declared reference a ratio below 1 can still admit the total; + # _check_max_weight_reference checks the bounds themselves. + if ( + max_weight_ratio is not None + and max_weight_ratio < 1 + and mass == CONSERVE_MASS + and not reference_bound + ): # Every capped weight is below its initial, so sum(cap) < input total: # mass conservation is infeasible a priori (Finding 7). Reject it here # with a named error rather than letting it surface later as the kernel's @@ -2421,6 +2487,82 @@ def _check_l2_anchor_shape( ) +def _checked_max_weight_reference( + max_weight_reference: np.ndarray | None, + max_weight_ratio: float | None, + *, + method: str, + l0_lambda: float, + target_records: int | None, +) -> np.ndarray | None: + """Check the declared weight-bound reference; return it as float64.""" + if max_weight_reference is None: + return None + if max_weight_ratio is None: + raise ValueError( + "max_weight_reference declares what max_weight_ratio multiplies; " + "pass max_weight_ratio too." + ) + if method != "adam" or l0_lambda > 0.0 or target_records is not None: + raise ValueError( + "max_weight_reference is implemented for the Adam solve without L0 " + "gates (method='adam', l0_lambda=0, target_records=None)." + ) + reference = np.asarray(max_weight_reference, dtype=np.float64) + if ( + reference.ndim != 1 + or not np.isfinite(reference).all() + or (reference <= 0).any() + ): + raise ValueError( + "max_weight_reference must be one finite, strictly positive weight " + "for each record." + ) + return reference + + +def _check_max_weight_reference( + reference: np.ndarray | None, + initial_weights: np.ndarray, + max_weight_ratio: float | None, + *, + mass: str, +) -> None: + """The reference fits the records, and its bounds admit a conserved total.""" + if reference is None: + return + if reference.shape != initial_weights.shape: + raise ValueError( + f"max_weight_reference shape {reference.shape} must match the " + f"calibrated weight vector shape {initial_weights.shape}." + ) + total = float(initial_weights.sum()) + admitted = float(max_weight_ratio * reference.sum()) + if mass == CONSERVE_MASS and admitted < total * (1.0 - 1e-12): + raise ValueError( + f"max_weight_ratio={max_weight_ratio!r} times max_weight_reference " + f"admits a total of {admitted!r}, below the input total {total!r}: " + "the mass cannot be conserved under these bounds. Raise " + "max_weight_ratio, declare a larger reference, or use mass='free'." + ) + + +def _weight_bound_options( + reference: np.ndarray, + initial_weights: np.ndarray, + final_weights: np.ndarray, + max_weight_ratio: float, +) -> dict[str, object]: + """What a solve under a declared reference records about its bound.""" + return { + "reference": "declared", + "records_started_above_bound": int( + (initial_weights > max_weight_ratio * reference).sum() + ), + "realized_max_ratio_to_reference": float((final_weights / reference).max()), + } + + def calibrate( frame: Frame, targets: TargetSet, @@ -2434,6 +2576,7 @@ def calibrate( mass_reason: str | None = None, mass_parametrization: str = MASS_PARAMETRIZATION_PROJECTION, max_weight_ratio: float | None = None, + max_weight_reference: np.ndarray | None = None, target_records: int | None = None, l0_lambda: float = 0.0, l1_lambda: float = 0.0, @@ -2517,6 +2660,25 @@ def calibrate( at the ACS local release's scale. max_weight_ratio: If given, a hard per-record cap: no calibrated weight exceeds ``max_weight_ratio * initial_weight``. The landmine guard. + max_weight_reference: Optional declared reference for the cap: one + finite, strictly positive weight for each ``weight_entity`` + record. The cap is then ``max_weight_ratio * + max_weight_reference`` instead of ``max_weight_ratio * + initial_weight``, so a record that starts heavier than the others + gets no larger a cap for it (for example one shared weight, or + the mean weight of the record's area; + :func:`microcosm.calibrate.weight_bound.weight_bound_reference`). + ``None`` (default) is the historical cap, unchanged bit for bit. + The frame's weights still define the starting point, mass + conservation, the L2 anchor and the diagnostics. A record may + start above its cap: the solve then starts from the starting + weights held to the cap and, under ``mass="conserve"``, brought + back to the input total below it, the projection a warm start + gets. Under ``mass="conserve"`` the caps must admit the total + (``max_weight_ratio * sum(max_weight_reference) >= sum(initial)``). + Requires ``max_weight_ratio`` and the Adam solve without L0 + gates. Recorded in ``options["weight_bound"]``, a key a solve + without a reference does not have. target_records: If given, enable L0 pruning with **budget control**: the solver searches ``l0_lambda`` (a bisection on its log, ``budget_iters`` optimizations) so the achieved non-zero count tracks this budget, and @@ -2653,6 +2815,10 @@ def calibrate( ``l2_lambda``, if ``l2_basis`` is unknown, if ``mass_parametrization`` is unknown or is ``"softmax"`` outside an Adam ``mass="conserve"`` solve without L0 gates, if + ``max_weight_reference`` is given without ``max_weight_ratio``, + outside the Adam solve without L0 gates, misaligned, not strictly + positive, or (under ``mass="conserve"``) too small to admit the + total, if ``budget_search_bracket`` is malformed or given without ``target_records``, if a ``target_records`` warm start (``l0_lambda``) lies outside the search bracket, or if no @@ -2685,7 +2851,19 @@ def calibrate( ) if not isinstance(mass_reason, str) or not mass_reason.strip(): raise ValueError("mass_reason must be a non-empty string when provided.") - _check_epochs_and_weight_ratio(epochs, max_weight_ratio, mass=mass) + _check_epochs_and_weight_ratio( + epochs, + max_weight_ratio, + mass=mass, + reference_bound=max_weight_reference is not None, + ) + max_weight_reference = _checked_max_weight_reference( + max_weight_reference, + max_weight_ratio, + method=method, + l0_lambda=l0_lambda, + target_records=target_records, + ) if gate_initialization is not None: if method != "adam" or (target_records is None and l0_lambda <= 0): raise ValueError("gate_initialization requires an Adam L0 solve.") @@ -2789,6 +2967,7 @@ def calibrate( w0 = initial.values prune_atol = _PRUNE_REL_ATOL * float(np.mean(w0)) _check_l2_anchor_shape(l2_anchor_weights, w0.shape) + _check_max_weight_reference(max_weight_reference, w0, max_weight_ratio, mass=mass) torch.manual_seed(seed) matrix_t = _torch_constraint_matrix(problem.matrix) @@ -2947,6 +3126,11 @@ def calibrate( if gate_initialization is None else {"gate_initialization": gate_initialization} ), + **( + {} + if max_weight_reference is None + else {"weight_bound_reference": max_weight_reference} + ), ) n_nonzero = int((final_weights > prune_atol).sum()) if effective_l0 > 0.0 and n_nonzero == 0: @@ -3058,6 +3242,17 @@ def calibrate( "matrix_format": ( "sparse_csr" if matrix_t.layout == torch.sparse_csr else "dense" ), + # Only a solve under a declared reference records its bound, so + # the options of every other solve are unchanged. + **( + {} + if max_weight_reference is None + else { + "weight_bound": _weight_bound_options( + max_weight_reference, w0, final_weights, max_weight_ratio + ) + } + ), }, gate_open_probabilities=gate_open_probabilities, ) @@ -3074,6 +3269,7 @@ def solve_constraint_system( mass: str = FREE_MASS, mass_parametrization: str = MASS_PARAMETRIZATION_PROJECTION, max_weight_ratio: float | None = None, + max_weight_reference: np.ndarray | None = None, l2_lambda: float = 0.0, l2_anchor: str = "initial", l2_anchor_weights: np.ndarray | None = None, @@ -3098,7 +3294,19 @@ def solve_constraint_system( and ``loss_trajectory``. """ _check_mass(mass) - _check_epochs_and_weight_ratio(epochs, max_weight_ratio, mass=mass) + _check_epochs_and_weight_ratio( + epochs, + max_weight_ratio, + mass=mass, + reference_bound=max_weight_reference is not None, + ) + max_weight_reference = _checked_max_weight_reference( + max_weight_reference, + max_weight_ratio, + method="adam", + l0_lambda=0.0, + target_records=None, + ) l2_anchor_weights = _checked_l2_options( l2_lambda, l2_basis, @@ -3120,6 +3328,7 @@ def solve_constraint_system( f"{(target_vector.shape[0], w0.shape[0])}." ) _check_l2_anchor_shape(l2_anchor_weights, w0.shape) + _check_max_weight_reference(max_weight_reference, w0, max_weight_ratio, mass=mass) target_loss_cap = _validate_target_loss_cap(target_loss_cap) target_loss_weights = _validate_target_loss_weights( target_loss_weights, target_vector.shape @@ -3163,6 +3372,11 @@ def solve_constraint_system( init_mean=0.999, temperature=0.25, progress_callback=progress_callback, + **( + {} + if max_weight_reference is None + else {"weight_bound_reference": max_weight_reference} + ), ) diff --git a/packages/microcosm-calibrate/src/microcosm/calibrate/spine_target_shares.py b/packages/microcosm-calibrate/src/microcosm/calibrate/spine_target_shares.py new file mode 100644 index 0000000000..a2615be57b --- /dev/null +++ b/packages/microcosm-calibrate/src/microcosm/calibrate/spine_target_shares.py @@ -0,0 +1,482 @@ +"""Which rows carry each target: a diagnostic for any pooled build (#1729). + +A pooled file stacks several sets of rows ("spines"): for example a national +release's households beside the households of a larger survey. A target that +one spine carries almost alone can only be hit by moving weight onto that +spine's rows, which concentrates the weights and lowers the effective sample +size. This module measures that, target by target: + +- **share**: the part of the target's weighted total that each spine's rows + carry, and +- **mass share**: the part of the weight that the spine holds among the + records the target is about (its *scope*: an area, or every record). + +``share`` far above ``mass share`` marks a target that pulls weight onto that +spine. ``excess`` is their difference and ``lift`` their ratio. + +The diagnostic reads a constraint matrix (targets x records), a weight vector +and each record's spine. It solves nothing and changes nothing, so it runs on +a saved calibration input or checkpoint, at the starting weights or at any +calibrated weights. It is report-only. + +Shares are taken on absolute contributions, ``sum(|a_ij| * w_i)``, so they +lie in ``[0, 1]`` and sum to one for every target. For a measure that is +never negative that is the share of the estimate itself; ``mixed_sign`` marks +the targets where it is not. +""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from dataclasses import dataclass + +import numpy as np +import pandas as pd +from scipy import sparse + +__all__ = [ + "SpineTargetShares", + "spine_target_shares", + "spine_target_shares_for_problem", +] + +Scope = tuple[str, str] + + +@dataclass(frozen=True) +class SpineTargetShares: + """The share of each target that each spine carries (see the module). + + Arrays are target-aligned on axis 0 and spine-aligned on axis 1. + + Attributes: + names: The target names. + spines: The spine labels, sorted. + estimates: Each target's weighted total, ``A @ w``. + carried: The signed part of the estimate each spine carries. + share: Each spine's share of the target's absolute contributions; + NaN for a target no positive-weight record carries. + mass_share: Each spine's share of the weight in the target's scope. + carriers: The positive-weight records of the spine with a nonzero + coefficient, counted as distinct sources when source ids were + given. + mixed_sign: Whether the target has positive and negative + contributions. + scopes: Each target's scope ``(kind, code)``, or ``None`` for every + record. + overall_mass_share: Each spine's share of the total weight. + withheld: Whether the target is withheld under ``minimum_carriers``. + A withheld target's ``estimates``, ``carried`` and ``share`` are + NaN and its ``carriers`` are ``-1``. + minimum_carriers: The floor targets were withheld under, if any. + """ + + names: tuple[str, ...] + spines: tuple[str, ...] + estimates: np.ndarray + carried: np.ndarray + share: np.ndarray + mass_share: np.ndarray + carriers: np.ndarray + mixed_sign: np.ndarray + scopes: tuple[Scope | None, ...] + overall_mass_share: np.ndarray + withheld: np.ndarray + minimum_carriers: int | None = None + + @property + def excess(self) -> np.ndarray: + """``share - mass_share``: positive where the spine over-carries.""" + + return self.share - self.mass_share + + @property + def lift(self) -> np.ndarray: + """``share / mass_share``; NaN where the spine holds no mass in scope.""" + + with np.errstate(divide="ignore", invalid="ignore"): + lift = self.share / self.mass_share + return np.where(self.mass_share > 0, lift, np.nan) + + def _cell(self, value: float) -> float | None: + return None if np.isnan(value) else float(value) + + def rows(self) -> list[dict[str, object]]: + """One JSON-ready record for each target, in target order.""" + + excess, lift = self.excess, self.lift + rows: list[dict[str, object]] = [] + for index, name in enumerate(self.names): + scope = self.scopes[index] + row: dict[str, object] = { + "name": name, + "scope": None + if scope is None + else {"kind": scope[0], "code": scope[1]}, + "mass_share": { + spine: self._cell(self.mass_share[index, column]) + for column, spine in enumerate(self.spines) + }, + } + if self.withheld[index]: + row["withheld"] = ( + f"a spine carries it with fewer than {self.minimum_carriers} " + "distinct carriers" + ) + rows.append(row) + continue + shares = self.share[index] + dominant = None if np.isnan(shares).all() else int(np.nanargmax(shares)) + row.update( + { + "estimate": float(self.estimates[index]), + "mixed_sign": bool(self.mixed_sign[index]), + "dominant_spine": None + if dominant is None + else self.spines[dominant], + "dominant_share": ( + None if dominant is None else float(shares[dominant]) + ), + "share": {}, + "excess": {}, + "lift": {}, + "carried": {}, + "carriers": {}, + } + ) + for column, spine in enumerate(self.spines): + row["share"][spine] = self._cell(shares[column]) + row["excess"][spine] = self._cell(excess[index, column]) + row["lift"][spine] = self._cell(lift[index, column]) + row["carried"][spine] = float(self.carried[index, column]) + row["carriers"][spine] = int(self.carriers[index, column]) + rows.append(row) + return rows + + def ranking(self, spine: str, *, top: int | None = None) -> list[dict[str, object]]: + """Targets by how much more of them ``spine`` carries than its mass. + + Sorted by ``excess`` for ``spine``, largest first: the targets that + pull weight onto that spine come first. Withheld targets and targets + no record carries are left out. + """ + + if spine not in self.spines: + raise ValueError(f"spine must be one of {self.spines}, got {spine!r}.") + column = self.spines.index(spine) + excess = self.excess[:, column] + lift = self.lift[:, column] + order = [ + int(index) + for index in np.argsort(-np.nan_to_num(excess, nan=-np.inf), kind="stable") + if not np.isnan(excess[index]) + ] + if top is not None: + order = order[:top] + return [ + { + "name": self.names[index], + "share": float(self.share[index, column]), + "mass_share": float(self.mass_share[index, column]), + "excess": float(excess[index]), + "lift": self._cell(lift[index]), + "carriers": int(self.carriers[index, column]), + } + for index in order + ] + + def summary( + self, groups: Sequence[str], *, alone_share: float = 0.9 + ) -> list[dict[str, object]]: + """Shares summarized over groups of targets (a family, a level, ...). + + ``groups`` labels each target. For each group and spine: the median + share, the mean excess, and how many targets the spine carries almost + alone (``share >= alone_share``). Withheld and uncarried targets do + not enter a group's statistics; ``n_targets`` counts them. + """ + + if len(groups) != len(self.names): + raise ValueError( + f"{len(groups)} group labels do not align with " + f"{len(self.names)} targets." + ) + if not 0.0 < alone_share <= 1.0: + raise ValueError("alone_share must be in (0, 1].") + labels = np.asarray([str(group) for group in groups], dtype=object) + measured = ~np.isnan(self.share).any(axis=1) + excess = self.excess + summary = [] + for label in dict.fromkeys(labels.tolist()): + members = labels == label + scored = members & measured + entry: dict[str, object] = { + "group": label, + "n_targets": int(members.sum()), + "n_measured": int(scored.sum()), + "spines": {}, + } + for column, spine in enumerate(self.spines): + entry["spines"][spine] = ( + { + "median_share": float(np.median(self.share[scored, column])), + "mean_excess": float(excess[scored, column].mean()), + "n_carried_almost_alone": int( + (self.share[scored, column] >= alone_share).sum() + ), + } + if scored.any() + else None + ) + summary.append(entry) + return summary + + def frame(self) -> pd.DataFrame: + """Long form: one row for each (target, spine).""" + + n_targets, n_spines = len(self.names), len(self.spines) + return pd.DataFrame( + { + "target": np.repeat(np.asarray(self.names, dtype=object), n_spines), + "spine": np.tile(np.asarray(self.spines, dtype=object), n_targets), + "share": self.share.ravel(), + "mass_share": self.mass_share.ravel(), + "excess": self.excess.ravel(), + "lift": self.lift.ravel(), + "carried": self.carried.ravel(), + "carriers": self.carriers.ravel(), + "withheld": np.repeat(self.withheld, n_spines), + } + ) + + def report(self) -> dict[str, object]: + """The whole diagnostic as JSON-serializable data.""" + + return { + "spines": list(self.spines), + "overall_mass_share": { + spine: float(self.overall_mass_share[column]) + for column, spine in enumerate(self.spines) + }, + "n_targets": len(self.names), + "n_withheld": int(self.withheld.sum()), + "minimum_carriers": self.minimum_carriers, + "share_basis": "sum(|coefficient| * weight) by spine over all spines", + "mass_share_basis": "weight by spine among the records of the target's scope", + "targets": self.rows(), + } + + +def _checked_vector(values, n_records: int, label: str) -> np.ndarray: + array = np.asarray(values) + if array.shape != (n_records,): + raise ValueError( + f"{label} has shape {array.shape}; the matrix has {n_records} records." + ) + return array + + +def _distinct_carriers( + nonzero: sparse.csr_array, + positive: np.ndarray, + spine_index: np.ndarray, + n_spines: int, + source_ids: np.ndarray | None, +) -> np.ndarray: + """Distinct positive-weight carriers of each target in each spine.""" + + n_records = nonzero.shape[1] + carriers = np.zeros((nonzero.shape[0], n_spines), dtype=np.int64) + for spine in range(n_spines): + members = np.flatnonzero(positive & (spine_index == spine)) + if not len(members): + continue + if source_ids is None: + keys = np.arange(len(members)) + else: + _, keys = np.unique(source_ids[members], return_inverse=True) + to_source = sparse.csr_array( + (np.ones(len(members)), (members, keys)), + shape=(n_records, int(keys.max()) + 1), + ) + # Stored entries of each row are the distinct sources that carry it. + by_source = (nonzero @ to_source).tocsr() + by_source.eliminate_zeros() + carriers[:, spine] = np.diff(by_source.indptr) + return carriers + + +def spine_target_shares( + matrix, + weights: Sequence[float] | np.ndarray, + spines: Sequence | np.ndarray, + *, + names: Sequence[str] | None = None, + target_scopes: Sequence[Scope | None] | None = None, + scope_codes: Mapping[str, Sequence | np.ndarray] | None = None, + source_ids: Sequence | np.ndarray | None = None, + minimum_carriers: int | None = None, +) -> SpineTargetShares: + """The share of each target each spine carries, against its share of mass. + + Args: + matrix: The constraint matrix, targets x records (SciPy sparse or + dense). + weights: One finite, non-negative weight for each record: the + starting weights, or any calibrated weights. + spines: Each record's spine label. + names: The target names (default ``target_0``, ``target_1``, ...). + target_scopes: For each target, the records it is about, as + ``(kind, code)`` (for example ``("state", "06")``), or ``None`` + for every record. Default: every record, for every target. + scope_codes: For each scope kind, each record's code of that kind. + Codes are compared as strings. + source_ids: Each record's source household, to count a household's + copies and clones once among a target's carriers. Two spines may + reuse an id; carriers are counted within a spine. + minimum_carriers: Withhold a target when a spine carries it with at + least one and fewer than this many distinct carriers. A build + under a disclosure rule passes its floor. A withheld target + reports its scope and mass shares only, since its shares sum to + one and one hidden cell could be read from the others. + + Returns: + A :class:`SpineTargetShares`. + """ + + constraint = sparse.csr_array(matrix) + n_targets, n_records = constraint.shape + weight = np.asarray(weights, dtype=np.float64) + if weight.shape != (n_records,): + raise ValueError( + f"weights have shape {weight.shape}; the matrix has {n_records} records." + ) + if not np.isfinite(weight).all() or (weight < 0.0).any(): + raise ValueError("weights must be finite and non-negative.") + total = float(weight.sum()) + if total <= 0.0: + raise ValueError("weights must have a positive total.") + labels = _checked_vector(spines, n_records, "spines").astype(str) + spine_order, spine_index = np.unique(labels, return_inverse=True) + n_spines = len(spine_order) + if names is None: + names = [f"target_{index}" for index in range(n_targets)] + names = tuple(str(name) for name in names) + if len(names) != n_targets: + raise ValueError(f"{len(names)} names for {n_targets} targets.") + if minimum_carriers is not None and ( + isinstance(minimum_carriers, bool) + or not isinstance(minimum_carriers, int) + or minimum_carriers < 1 + ): + raise ValueError("minimum_carriers must be a positive integer.") + sources = ( + None + if source_ids is None + else _checked_vector(source_ids, n_records, "source_ids") + ) + + records = np.arange(n_records) + weight_by_spine = sparse.csr_array( + (weight, (records, spine_index)), shape=(n_records, n_spines) + ) + constraint = constraint.astype(np.float64) + carried = (constraint @ weight_by_spine).toarray() + absolute = (abs(constraint) @ weight_by_spine).toarray() + row_total = absolute.sum(axis=1) + with np.errstate(divide="ignore", invalid="ignore"): + share = np.where(row_total[:, None] > 0, absolute / row_total[:, None], np.nan) + estimates = np.asarray(constraint @ weight, dtype=np.float64) + mixed_sign = (np.asarray(constraint.maximum(0) @ weight) > 0) & ( + np.asarray(constraint.minimum(0) @ weight) < 0 + ) + + nonzero = constraint.copy() + nonzero.data = (nonzero.data != 0).astype(np.float64) + nonzero.eliminate_zeros() + carriers = _distinct_carriers(nonzero, weight > 0, spine_index, n_spines, sources) + + overall = np.asarray(weight_by_spine.sum(axis=0), dtype=np.float64).ravel() / total + mass_share = np.tile(overall, (n_targets, 1)) + scopes: tuple[Scope | None, ...] = (None,) * n_targets + if target_scopes is not None: + if len(target_scopes) != n_targets: + raise ValueError(f"{len(target_scopes)} scopes for {n_targets} targets.") + scopes = tuple( + None if scope is None else (str(scope[0]), str(scope[1])) + for scope in target_scopes + ) + kinds = {scope[0] for scope in scopes if scope is not None} + missing = sorted(kinds - set(scope_codes or {})) + if missing: + raise ValueError(f"scope_codes has no record codes for {missing}.") + mass_by_scope: dict[str, dict[str, np.ndarray]] = {} + for kind in kinds: + codes = _checked_vector( + scope_codes[kind], n_records, f"scope_codes[{kind!r}]" + ) + grouped = ( + pd.DataFrame( + {"code": codes.astype(str), "spine": spine_index, "weight": weight} + ) + .groupby(["code", "spine"], sort=True)["weight"] + .sum() + .unstack("spine", fill_value=0.0) + .reindex(columns=range(n_spines), fill_value=0.0) + ) + mass_by_scope[kind] = { + str(code): row.to_numpy(dtype=np.float64) + for code, row in grouped.iterrows() + } + for index, scope in enumerate(scopes): + if scope is None: + continue + mass = mass_by_scope[scope[0]].get(scope[1]) + mass_total = 0.0 if mass is None else float(mass.sum()) + mass_share[index] = mass / mass_total if mass_total > 0 else np.nan + + withheld = np.zeros(n_targets, dtype=bool) + if minimum_carriers is not None: + withheld = ((carriers > 0) & (carriers < minimum_carriers)).any(axis=1) + estimates = np.where(withheld, np.nan, estimates) + carried = np.where(withheld[:, None], np.nan, carried) + share = np.where(withheld[:, None], np.nan, share) + carriers = np.where(withheld[:, None], -1, carriers) + return SpineTargetShares( + names=names, + spines=tuple(str(spine) for spine in spine_order), + estimates=estimates, + carried=carried, + share=share, + mass_share=mass_share, + carriers=carriers, + mixed_sign=mixed_sign, + scopes=scopes, + overall_mass_share=overall, + withheld=withheld, + minimum_carriers=minimum_carriers, + ) + + +def spine_target_shares_for_problem( + problem, + spines: Sequence | np.ndarray, + *, + weights: Sequence[float] | np.ndarray | None = None, + **options, +) -> SpineTargetShares: + """:func:`spine_target_shares` for a compiled ``CalibrationProblem``. + + Reads the problem's matrix and target names. ``weights`` defaults to the + problem's initial weights, so a saved calibration input needs no solve. + """ + + if weights is None: + weights = problem.initial_weights.values + return spine_target_shares( + problem.matrix, + weights, + spines, + names=options.pop("names", problem.names), + **options, + ) diff --git a/packages/microcosm-calibrate/src/microcosm/calibrate/target_loss_rules.py b/packages/microcosm-calibrate/src/microcosm/calibrate/target_loss_rules.py new file mode 100644 index 0000000000..8060550441 --- /dev/null +++ b/packages/microcosm-calibrate/src/microcosm/calibrate/target_loss_rules.py @@ -0,0 +1,720 @@ +"""Target-loss rules over plain row arrays, shared by every country. + +A calibration minimizes the weighted mean of each target's capped, scaled +miss. Two per-target vectors shape that loss: the loss *weight* and the loss +*cap*. This module computes both from what each target is, never from a +hand-written vector: + +- its **level** (the geography grain it is measured at: nation, state, + district, local authority, ...), +- its **family** (the source or concept family it belongs to), +- its value **basis** (``"count"`` or ``"amount"``), +- its **value**, and +- for the concept-budget rule, its budget **group**. + +A country says what each of its rows is (:class:`TargetLossRows`) and declares +the rule it uses by name with its parameters (:class:`TargetWeightRule`). The +arithmetic lives here once (microcosm#1729). + +Weight rules (:data:`TARGET_WEIGHT_RULES`; ``L`` levels, ``F_l`` families in +level ``l``, ``n`` rows in a (level, family) cell): + +``uniform`` + Every target weighs one. +``level_equal`` + Each level takes one equal share of the loss, rows inside a level equal + shares of it: ``w = 1 / (L * n_l)``. The vector sums to one. +``level_family_equal`` + Each level takes one equal share, each family inside a level one equal + share of it, rows inside a family equal shares: + ``w = 1 / (L * F_l * n)``. The vector sums to one. With the parameter + ``count_power`` (for example ``0.5``), the count rows of a cell share the + cell's count budget in proportion to ``max(|value|, 1) ** count_power``; + amount rows keep equal shares, and every level, family and cell budget is + unchanged. +``sqrt_value_concept_budget`` + Value weight ``max(|value|, 1) ** value_power`` over its basis mean; each + budget group rescaled to sum to its largest member's weight; each basis + rescaled to an equal share of the total; normalized to mean one. It reads + no level: a caller folds geography into the budget groups. + +Any rule may carry ``family_multipliers``: each named family's weights are +multiplied, in sorted family order, and the result is renormalized to mean +one. A multiplier that names no row's family is an error. + +Loss caps (:func:`target_loss_caps`): one number for the run by default, with +optional overrides for a level or a family, so that rows joining a solve do +not change the cap of the rows already in it. The solver takes one cap; +:func:`single_cap_equivalent` gives the one-cap loss that equals the loss +with a cap for each target, so a declared vector needs no solver change. + +This module imports no solver code and no country code. +""" + +from __future__ import annotations + +import math +from collections import Counter +from collections.abc import Callable, Hashable, Mapping, Sequence +from dataclasses import dataclass, field +from types import MappingProxyType + +import numpy as np + +__all__ = [ + "AMOUNT_BASIS", + "COUNT_BASIS", + "TARGET_WEIGHT_RULES", + "SingleCapEquivalent", + "TargetLossRows", + "TargetWeightRule", + "apply_family_multipliers", + "budget_group_weights", + "budget_groups", + "row_cap_census", + "single_cap_equivalent", + "target_loss_caps", + "target_loss_weight_shares", + "target_loss_weights_for_rule", + "value_basis_weights", +] + +COUNT_BASIS = "count" +AMOUNT_BASIS = "amount" +_BASES = (COUNT_BASIS, AMOUNT_BASIS) + + +# --------------------------------------------------------------------------- +# What a country says about its rows +# --------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class TargetLossRows: + """What each target is, row-aligned with the solve's target axis. + + Only ``values`` is always needed. A rule names the other fields it reads + and refuses rows that lack one of them. + + Attributes: + values: The target values, one finite number per row. + levels: Each row's level label. + families: Each row's family label (``None`` for a row with none). + bases: Each row's value basis, ``"count"`` or ``"amount"``. + groups: Each row's budget group (any hashable); rows that share a + group share one budget under ``sqrt_value_concept_budget``. + """ + + values: Sequence[float] | np.ndarray + levels: Sequence[str] | None = None + families: Sequence[str | None] | None = None + bases: Sequence[str] | None = None + groups: Sequence[Hashable] | None = None + + def __post_init__(self) -> None: + n_rows = len(self.values) + for label in ("levels", "families", "bases", "groups"): + column = getattr(self, label) + if column is not None and len(column) != n_rows: + raise ValueError( + f"target loss rows: {label} has {len(column)} entries for " + f"{n_rows} values." + ) + + def __len__(self) -> int: + return len(self.values) + + def require(self, label: str, *, rule: str) -> Sequence: + """The named column, refusing rows that do not carry it.""" + + column = getattr(self, label) + if column is None: + raise ValueError( + f"target weight rule {rule!r} reads each row's {label}; the " + "rows carry none." + ) + return column + + +# --------------------------------------------------------------------------- +# Building blocks (the arithmetic every rule shares) +# --------------------------------------------------------------------------- + + +def value_basis_weights( + values: Sequence[float], bases: np.ndarray, *, power: float +) -> np.ndarray: + """``max(|value|, 1) ** power``, divided by its mean over the row's basis.""" + + weights = np.ones(len(bases), dtype=np.float64) + magnitudes = np.asarray( + [max(abs(float(value)), 1.0) for value in values], + dtype=np.float64, + ) + raw_weights = magnitudes**power + for basis in sorted(set(bases.tolist())): + mask = bases == basis + mean_value = raw_weights[mask].mean() + if mean_value > 0: + weights[mask] = raw_weights[mask] / mean_value + return weights + + +def budget_groups(groups: Sequence[Hashable]) -> list[list[int]]: + """Row indices sharing each budget group, in first-row order.""" + + group_indices: dict[Hashable, list[int]] = {} + for index, key in enumerate(groups): + group_indices.setdefault(key, []).append(index) + return list(group_indices.values()) + + +def budget_group_weights(weights: np.ndarray, groups: Sequence[Hashable]) -> np.ndarray: + """Rescale each budget group, in place, to sum to its largest member.""" + + for indices in budget_groups(groups): + group_weights = weights[indices] + group_total = float(group_weights.sum()) + group_budget = float(group_weights.max(initial=0.0)) + if group_total > 0 and group_budget > 0: + weights[indices] *= group_budget / group_total + return weights + + +def apply_family_multipliers( + weights: np.ndarray, + families: Sequence[str | None], + family_multipliers: Mapping[str, float], +) -> np.ndarray: + """Multiply each named family's weights, then renormalize to mean one. + + Families are applied in sorted order. A multiplier that names no row's + family raises ``ValueError``. The multipliers are not checked here: a + caller admits only positive finite ones. + """ + + weights = np.array(weights, dtype=np.float64) + family_array = np.asarray(list(families), dtype=object) + for family, multiplier in sorted(family_multipliers.items()): + mask = family_array == family + if not mask.any(): + raise ValueError( + f"family multiplier for {family!r} matches no target family." + ) + weights[mask] *= multiplier + return weights / weights.mean() + + +# --------------------------------------------------------------------------- +# The rules +# --------------------------------------------------------------------------- + + +def _uniform(rows: TargetLossRows) -> np.ndarray: + return np.ones(len(rows), dtype=np.float64) + + +def _level_equal(rows: TargetLossRows) -> np.ndarray: + labels = [str(level) for level in rows.require("levels", rule="level_equal")] + if any(not label for label in labels): + raise ValueError("level_equal: every target must name its level.") + counts = Counter(labels) + level_count = len(counts) + return np.asarray( + [1.0 / (level_count * counts[label]) for label in labels], + dtype=np.float64, + ) + + +def _level_family_equal( + rows: TargetLossRows, *, count_power: float | None = None +) -> np.ndarray: + rule = "level_family_equal" + levels = np.asarray(list(rows.require("levels", rule=rule)), dtype=object) + families = np.asarray(list(rows.require("families", rule=rule)), dtype=object) + bases = None + magnitudes = None + if count_power is not None: + bases = np.asarray(list(rows.require("bases", rule=rule)), dtype=object) + unknown = sorted({str(basis) for basis in bases.tolist()} - set(_BASES)) + if unknown: + raise ValueError( + f"{rule}: count_power needs every row's basis to be one of " + f"{_BASES}; got {unknown}." + ) + magnitudes = ( + np.maximum(np.abs(np.asarray(rows.values, dtype=np.float64)), 1.0) + ** count_power + ) + level_order = list(dict.fromkeys(levels.tolist())) + weights = np.zeros(len(rows), dtype=np.float64) + for level in level_order: + in_level = levels == level + family_order = list(dict.fromkeys(families[in_level].tolist())) + budget = 1.0 / (len(level_order) * len(family_order)) + for family in family_order: + cell = np.flatnonzero(in_level & (families == family)) + if bases is None: + weights[cell] = budget / cell.size + continue + counts = cell[bases[cell] == COUNT_BASIS] + amounts = cell[bases[cell] == AMOUNT_BASIS] + weights[amounts] = budget / cell.size + if counts.size: + share = magnitudes[counts] + weights[counts] = ( + (budget * counts.size / cell.size) * share / share.sum() + ) + return weights + + +def _sqrt_value_concept_budget( + rows: TargetLossRows, *, value_power: float = 0.5 +) -> np.ndarray: + rule = "sqrt_value_concept_budget" + basis_array = np.asarray(list(rows.require("bases", rule=rule)), dtype=object) + weights = budget_group_weights( + value_basis_weights(rows.values, basis_array, power=value_power), + rows.require("groups", rule=rule), + ) + unique_bases = sorted(set(basis_array.tolist())) + if not unique_bases: + return weights + basis_total = len(weights) / len(unique_bases) + for basis in unique_bases: + mask = basis_array == basis + current_total = weights[mask].sum() + if current_total > 0: + weights[mask] *= basis_total / current_total + return weights / weights.mean() + + +@dataclass(frozen=True) +class _RuleSpec: + function: Callable[..., np.ndarray] + #: Parameter name -> whether ``None`` is admitted. + parameters: Mapping[str, bool] + + +#: The closed vocabulary of weight rules, by name. +TARGET_WEIGHT_RULES: Mapping[str, _RuleSpec] = MappingProxyType( + { + "uniform": _RuleSpec(_uniform, MappingProxyType({})), + "level_equal": _RuleSpec(_level_equal, MappingProxyType({})), + "level_family_equal": _RuleSpec( + _level_family_equal, MappingProxyType({"count_power": True}) + ), + "sqrt_value_concept_budget": _RuleSpec( + _sqrt_value_concept_budget, MappingProxyType({"value_power": False}) + ), + } +) + +_FAMILY_MULTIPLIERS = "family_multipliers" + + +@dataclass(frozen=True) +class TargetWeightRule: + """A named weight rule with its parameters: what a country declares. + + ``parameters`` holds the rule's own parameters (``count_power`` for + ``level_family_equal``, ``value_power`` for ``sqrt_value_concept_budget``) + and, for any rule, ``family_multipliers`` (family -> positive finite + multiplier). An unknown rule or parameter is refused when the declaration + is made, not when it is used. + """ + + name: str + parameters: Mapping[str, object] = field(default_factory=dict) + + def __post_init__(self) -> None: + spec = TARGET_WEIGHT_RULES.get(self.name) + if spec is None: + raise ValueError( + f"target weight rule must be one of {sorted(TARGET_WEIGHT_RULES)}, " + f"got {self.name!r}." + ) + parameters = dict(self.parameters) + unknown = sorted(set(parameters) - set(spec.parameters) - {_FAMILY_MULTIPLIERS}) + if unknown: + raise ValueError( + f"target weight rule {self.name!r} takes " + f"{sorted([*spec.parameters, _FAMILY_MULTIPLIERS])}, got {unknown}." + ) + for key, nullable in spec.parameters.items(): + if key not in parameters: + continue + value = parameters[key] + if value is None: + if not nullable: + raise ValueError(f"{self.name}: {key} must be a number.") + continue + if ( + isinstance(value, bool) + or not isinstance(value, int | float) + or not math.isfinite(value) + or value <= 0 + ): + raise ValueError( + f"{self.name}: {key} must be a positive finite number, " + f"got {value!r}." + ) + parameters[key] = float(value) + multipliers = parameters.get(_FAMILY_MULTIPLIERS) + if multipliers is not None: + checked: dict[str, float] = {} + for family, multiplier in dict(multipliers).items(): + if ( + isinstance(multiplier, bool) + or not isinstance(multiplier, int | float) + or not math.isfinite(multiplier) + or multiplier <= 0 + ): + raise ValueError( + f"{self.name}: the family multiplier for {family!r} must " + f"be positive and finite, got {multiplier!r}." + ) + checked[str(family)] = float(multiplier) + parameters[_FAMILY_MULTIPLIERS] = MappingProxyType(checked) + object.__setattr__(self, "parameters", MappingProxyType(parameters)) + + def with_family_multipliers( + self, family_multipliers: Mapping[str, float] | None + ) -> TargetWeightRule: + """This rule with ``family_multipliers`` in place of its own.""" + + parameters = { + key: value + for key, value in self.parameters.items() + if key != _FAMILY_MULTIPLIERS + } + if family_multipliers: + parameters[_FAMILY_MULTIPLIERS] = dict(family_multipliers) + return TargetWeightRule(self.name, parameters) + + def to_json(self) -> dict[str, object]: + """The declaration as JSON-serializable data, for a receipt.""" + + parameters: dict[str, object] = {} + for key, value in sorted(self.parameters.items()): + parameters[key] = ( + dict(sorted(value.items())) if isinstance(value, Mapping) else value + ) + return {"rule": self.name, "parameters": parameters} + + +def target_loss_weights_for_rule( + rows: TargetLossRows, rule: TargetWeightRule +) -> np.ndarray: + """The loss-weight vector ``rule`` gives ``rows``, row-aligned (float64). + + The solver normalizes loss weights by their sum, so a rule's own scale + (sum one or mean one) does not change the objective. + """ + + if not isinstance(rows, TargetLossRows): + raise TypeError("target loss weights need a TargetLossRows carrier.") + if not isinstance(rule, TargetWeightRule): + raise TypeError("target loss weights need a TargetWeightRule declaration.") + spec = TARGET_WEIGHT_RULES[rule.name] + parameters = { + key: value for key, value in rule.parameters.items() if key in spec.parameters + } + weights = spec.function(rows, **parameters) + multipliers = rule.parameters.get(_FAMILY_MULTIPLIERS) + if not multipliers: + return weights + return apply_family_multipliers( + weights, rows.require("families", rule=rule.name), multipliers + ) + + +def target_loss_weight_shares( + rows: TargetLossRows, weights: np.ndarray +) -> list[dict[str, object]]: + """Each (level, family) cell's share of the loss weight, for a receipt. + + ``loss_share`` is the cell's share of the total weight (the share of the + loss it carries at equal misses); ``equal_share`` is what it would carry + with every target weighted equally. Cells come in first-row order. + """ + + weights = np.asarray(weights, dtype=np.float64) + if weights.shape != (len(rows),): + raise ValueError( + f"{weights.shape} loss weights do not align with {len(rows)} rows." + ) + levels = np.asarray( + list(rows.require("levels", rule="target_loss_weight_shares")), dtype=object + ) + families = np.asarray( + list(rows.require("families", rule="target_loss_weight_shares")), + dtype=object, + ) + total = float(weights.sum()) + n_rows = len(rows) + cells = [] + for level, family in dict.fromkeys( + zip(levels.tolist(), families.tolist(), strict=True) + ): + mask = (levels == level) & (families == family) + cells.append( + { + "level": level, + "family": family, + "n_targets": int(mask.sum()), + "loss_share": float(weights[mask].sum()) / total if total else 0.0, + "equal_share": float(mask.sum()) / n_rows if n_rows else 0.0, + } + ) + return cells + + +# --------------------------------------------------------------------------- +# Loss caps +# --------------------------------------------------------------------------- + + +def _checked_cap(label: str, cap: object) -> float: + if ( + isinstance(cap, bool) + or not isinstance(cap, int | float) + or not math.isfinite(cap) + or cap <= 0 + ): + raise ValueError(f"{label} must be positive and finite, got {cap!r}.") + return float(cap) + + +def target_loss_caps( + default: float, + *, + levels: Sequence[str] | None = None, + families: Sequence[str | None] | None = None, + by_level: Mapping[str, float] | None = None, + by_family: Mapping[str, float] | None = None, +) -> float | np.ndarray: + """The loss cap of each target: one number, or a vector when declared. + + With no override the result is ``default`` itself, a plain number, so a + run that declares none calls the solver exactly as before. With + ``by_level`` or ``by_family`` it is a row-aligned float64 vector: every + row starts at ``default``, a row whose level is in ``by_level`` takes that + cap, and a row whose family is in ``by_family`` takes that cap (a family + cap wins over a level cap). An override that matches no row is an error, + so a misspelled level cannot silently leave a cap unchanged. + """ + + default = _checked_cap("the default target loss cap", default) + by_level = dict(by_level or {}) + by_family = dict(by_family or {}) + if not by_level and not by_family: + return default + columns = {"level": (levels, by_level), "family": (families, by_family)} + n_rows = None + for label, (column, overrides) in columns.items(): + if not overrides: + continue + if column is None: + raise ValueError(f"a target loss cap by {label} needs each row's {label}.") + if n_rows is not None and len(column) != n_rows: + raise ValueError("target loss caps: levels and families must align.") + n_rows = len(column) + caps = np.full(n_rows, default, dtype=np.float64) + for label, (column, overrides) in columns.items(): + if not overrides: + continue + labels = np.asarray(list(column), dtype=object) + for key, cap in sorted(overrides.items()): + mask = labels == key + if not mask.any(): + raise ValueError( + f"the target loss cap for {label} {key!r} matches no target." + ) + caps[mask] = _checked_cap(f"the target loss cap for {label} {key!r}", cap) + return caps + + +@dataclass(frozen=True) +class SingleCapEquivalent: + """A one-cap loss that equals a loss with a cap for each target. + + Pass ``cap``, ``weights`` and ``scales`` to the solver as + ``target_loss_cap``, ``target_loss_weights`` and ``target_loss_scales``. + ``caps`` keeps the declared row caps for the receipt. + """ + + cap: float + weights: np.ndarray + scales: np.ndarray + caps: np.ndarray + + def receipt(self) -> dict[str, object]: + """How many rows carry each declared cap, and the equivalent cap.""" + + values, counts = np.unique(self.caps, return_counts=True) + return { + "method": "single_cap_equivalent", + "equivalent_cap": float(self.cap), + "rows_by_cap": { + repr(float(value)): int(count) + for value, count in zip(values, counts, strict=True) + }, + } + + +def single_cap_equivalent( + caps: Sequence[float] | np.ndarray, + *, + weights: Sequence[float] | np.ndarray, + scales: Sequence[float] | np.ndarray, +) -> SingleCapEquivalent: + """The one-cap loss with exactly the value of a cap for each target. + + The solver's loss is ``sum(w * min(|miss| / s, cap)) / sum(w)`` with one + ``cap``. For row caps ``c``, weights ``w`` and scales ``s``, take + + - ``cap0 = sum(w * c) / sum(w)`` (the weighted mean cap), + - ``w' = w * c / cap0`` and ``s' = s * c / cap0``. + + Then ``w' * min(|miss| / s', cap0) == w * min(|miss| / s, c)`` for every + row, and ``sum(w') == sum(w)``. So the loss, each row's contribution to + it and its gradient are those of the loss with row caps. This is an + identity, not an approximation: a row past its own cap contributes the + constant ``w * c`` in both forms. It needs no change to the solver, whose + cap stays one number. + + When every row has the same cap, the weights and scales come back + unchanged and ``cap`` is that number, so equal caps call the solver + exactly as one cap does. + + The transformed scales and weights are what the solver records. A + diagnostic that reads the solver's ``target_loss_cap`` against the default + scales (the past-cap census of the calibration diagnostics) therefore + measures against ``cap0``, not against each row's own cap. + :func:`row_cap_census` is the census against each row's own cap; a build + that declares row caps records it beside the declared caps. + """ + + caps = np.array(caps, dtype=np.float64) + weights = np.array(weights, dtype=np.float64) + scales = np.array(scales, dtype=np.float64) + if caps.ndim != 1 or not (caps.shape == weights.shape == scales.shape): + raise ValueError( + "caps, weights and scales must be aligned vectors, got shapes " + f"{caps.shape}, {weights.shape} and {scales.shape}." + ) + if not caps.size: + raise ValueError("a loss needs at least one target.") + for label, values, strict in ( + ("caps", caps, True), + ("scales", scales, True), + ("weights", weights, False), + ): + if not np.isfinite(values).all() or ( + (values <= 0).any() if strict else (values < 0).any() + ): + raise ValueError( + f"target loss {label} must be finite and " + f"{'positive' if strict else 'non-negative'}." + ) + total = float(weights.sum()) + if total <= 0.0: + raise ValueError("target loss weights must have positive total weight.") + if (caps == caps[0]).all(): + return SingleCapEquivalent( + cap=float(caps[0]), weights=weights, scales=scales, caps=caps + ) + cap = float((weights * caps).sum() / total) + factor = caps / cap + return SingleCapEquivalent( + cap=cap, weights=weights * factor, scales=scales * factor, caps=caps + ) + + +def row_cap_census( + names: Sequence[str], + targets: Sequence[float] | np.ndarray, + initial_estimates: Sequence[float] | np.ndarray, + final_estimates: Sequence[float] | np.ndarray, + *, + scales: Sequence[float] | np.ndarray, + caps: Sequence[float] | np.ndarray, +) -> dict[str, object]: + """Rows past their own loss cap at the solve's start and end. + + The census of the calibration diagnostics, taken against each row's own + cap instead of one cap. A row whose scaled miss ``|estimate - target| / + scale`` is past its cap contributes a constant to the loss, so the solver + has no reason to improve it. ``scales`` are the declared scales, before + :func:`single_cap_equivalent` transforms them. + + - ``initial_past_cap`` / ``final_past_cap``: rows strictly past their cap + under the starting / final estimates; + - ``escaped``: past at the start, inside at the end; + - ``frozen``: past at both; + - ``pushed_out``: inside at the start, past at the end, listed in + ``pushed_out_rows`` with the worst final miss first; + - ``by_cap``: the same counts for the rows of each cap value. + """ + + names = [str(name) for name in names] + targets = np.asarray(targets, dtype=np.float64) + initial = np.asarray(initial_estimates, dtype=np.float64) + final = np.asarray(final_estimates, dtype=np.float64) + scales = np.asarray(scales, dtype=np.float64) + caps = np.asarray(caps, dtype=np.float64) + shape = (len(names),) + for label, values in ( + ("targets", targets), + ("initial_estimates", initial), + ("final_estimates", final), + ("scales", scales), + ("caps", caps), + ): + if values.shape != shape: + raise ValueError( + f"{label} has shape {values.shape}; there are {len(names)} names." + ) + if not np.isfinite(values).all(): + raise ValueError(f"{label} must be finite.") + if (scales <= 0).any() or (caps <= 0).any(): + raise ValueError("scales and caps must be positive.") + initial_miss = np.abs(initial - targets) / scales + final_miss = np.abs(final - targets) / scales + # Strictly past the cap, as the solver's census counts: a row exactly at + # its cap still has a gradient. + initial_past = initial_miss > caps + final_past = final_miss > caps + + def counts(rows: np.ndarray) -> dict[str, int]: + return { + "n_targets": int(rows.sum()), + "initial_past_cap": int((initial_past & rows).sum()), + "final_past_cap": int((final_past & rows).sum()), + "escaped": int((initial_past & ~final_past & rows).sum()), + "frozen": int((initial_past & final_past & rows).sum()), + "pushed_out": int((~initial_past & final_past & rows).sum()), + } + + pushed_out = np.flatnonzero(~initial_past & final_past) + pushed_out_rows = sorted( + ( + { + "name": names[index], + "cap": float(caps[index]), + "init_rel": float(initial_miss[index]), + "final_rel": float(final_miss[index]), + } + for index in pushed_out + ), + key=lambda row: (-row["final_rel"], row["name"]), + ) + return { + "cap_basis": "each row's own cap", + **counts(np.ones(len(names), dtype=bool)), + "pushed_out_rows": pushed_out_rows, + "by_cap": { + repr(float(cap)): counts(caps == cap) for cap in np.unique(caps).tolist() + }, + } diff --git a/packages/microcosm-calibrate/src/microcosm/calibrate/weight_bound.py b/packages/microcosm-calibrate/src/microcosm/calibrate/weight_bound.py new file mode 100644 index 0000000000..125bc13746 --- /dev/null +++ b/packages/microcosm-calibrate/src/microcosm/calibrate/weight_bound.py @@ -0,0 +1,185 @@ +"""The weight bound: one contract, declared references, and a measurement. + +**The contract** (microcosm#493, microcosm#1729). ``max_weight_ratio`` is a +hard bound on each record: + + no returned weight exceeds ``max_weight_ratio x reference``, + +where a record's *reference* is its weight on the frame the solve was given, +which is its starting weight. Three things follow, and they hold for every +caller of :func:`microcosm.calibrate.calibrate`: + +1. **The reference is the frame, never the warm start.** A solve that + continues from ``warm_start_weights`` (an epoch-batched solve does so on + every batch) keeps the bound against the frame's weights. Batches do not + compound the bound. +2. **A new frame is a new reference.** A stage whose frame carries an earlier + stage's calibrated weights bounds against those. Two stages at ratio ``R`` + then admit ``R ** 2`` against the first stage's starting weights. A build + that chains stages must say which weights its bound is against, and should + record the realized ratio against the first stage's weights too + (:func:`weight_bound_report` with ``reference`` set to them). +3. **The bound is relative, so a heavy record gets a larger absolute bound.** + In a pooled file where one set of rows starts ``k`` times heavier than + another, its rows may reach ``k`` times the absolute weight of the others + under the same ratio. + +**A declared reference.** Point 3 is a choice, not a law. A build may want +the bound against a weight it declares instead of each record's own start: +one shared weight, or the mean weight of the record's area +(:func:`weight_bound_reference`). ``calibrate(max_weight_reference=...)`` +enforces it: no returned weight exceeds ``max_weight_ratio x`` the declared +reference. Points 1 and 2 hold for a declared reference too. The frame's +weights still set the starting point, the mass and the L2 anchor; a record +that starts above its bound starts from the bound, with the mass it gives up +spread below the bounds. It is opt-in: without it the bound is against the +frame's weights, as before. + +:func:`weight_bound_report` measures any weight vector against a declared +reference, report-only, so the effect of such a bound can be read from a +finished solve before a solve enforces it. + +This module solves nothing and imports no solver code. +""" + +from __future__ import annotations + +import math +from collections.abc import Sequence + +import numpy as np +import pandas as pd + +__all__ = [ + "WEIGHT_BOUND_REFERENCES", + "weight_bound_reference", + "weight_bound_report", +] + +#: The declared references, by name. +#: +#: ``own``: each record's own starting weight (the solver's bound). +#: ``mean``: the mean starting weight, one number for every record. +#: ``group_mean``: the mean starting weight of the record's group (an area). +WEIGHT_BOUND_REFERENCES = ("own", "mean", "group_mean") + + +def _checked(values, label: str, *, positive: bool = False) -> np.ndarray: + array = np.asarray(values, dtype=np.float64) + if array.ndim != 1: + raise ValueError(f"{label} must be one-dimensional.") + if not np.isfinite(array).all() or ( + (array <= 0).any() if positive else (array < 0).any() + ): + raise ValueError( + f"{label} must be finite and " + f"{'strictly positive' if positive else 'non-negative'}." + ) + return array + + +def weight_bound_reference( + starting_weights: Sequence[float] | np.ndarray, + kind: str = "own", + *, + groups: Sequence | np.ndarray | None = None, +) -> np.ndarray: + """The reference weight of each record under a declared rule. + + ``own`` returns the starting weights. ``mean`` returns their mean for + every record. ``group_mean`` returns, for each record, the mean starting + weight of the records that share its ``groups`` label. Every reference is + positive, so every starting weight must be. + """ + + if kind not in WEIGHT_BOUND_REFERENCES: + raise ValueError( + f"the weight bound reference must be one of {WEIGHT_BOUND_REFERENCES}, " + f"got {kind!r}." + ) + starting = _checked(starting_weights, "starting_weights", positive=True) + if kind == "own": + return starting.copy() + if kind == "mean": + return np.full_like(starting, starting.mean()) + if groups is None: + raise ValueError("a group_mean reference needs each record's group.") + labels = np.asarray(groups) + if labels.shape != starting.shape: + raise ValueError( + f"{labels.shape} groups do not align with {starting.shape} weights." + ) + return ( + pd.Series(starting) + .groupby(labels.astype(str), sort=False) + .transform("mean") + .to_numpy(dtype=np.float64) + ) + + +def weight_bound_report( + weights: Sequence[float] | np.ndarray, + starting_weights: Sequence[float] | np.ndarray, + *, + max_weight_ratio: float, + reference: Sequence[float] | np.ndarray | None = None, +) -> dict[str, object]: + """How a weight vector sits against the bound, under one reference. + + ``reference`` defaults to the starting weights (the solver's bound). With + a declared reference the report answers what a bound against it would + mean, from weights a solve already returned: + + - ``realized_max_ratio``: the largest ``weight / reference``, + - ``records_above_bound`` and ``weight_share_above_bound``: the records + whose weight exceeds ``max_weight_ratio x reference``, and the share of + the total weight they hold, + - ``records_starting_above_bound``: the records whose *starting* weight + already exceeds the bound, which a solve under that bound would have to + pull down before it fits anything, + - ``admits_the_starting_mass``: whether the bounds sum to at least the + starting total, which a mass-conserving solve needs. + + Report-only: it measures and changes nothing. + """ + + if ( + isinstance(max_weight_ratio, bool) + or not isinstance(max_weight_ratio, int | float) + or not math.isfinite(max_weight_ratio) + or max_weight_ratio <= 0 + ): + raise ValueError( + f"max_weight_ratio must be positive and finite, got {max_weight_ratio!r}." + ) + weights = _checked(weights, "weights") + starting = _checked(starting_weights, "starting_weights", positive=True) + if weights.shape != starting.shape: + raise ValueError( + f"{weights.shape} weights do not align with {starting.shape} " + "starting weights." + ) + declared = reference is not None + bound_reference = ( + _checked(reference, "reference", positive=True) if declared else starting + ) + if bound_reference.shape != starting.shape: + raise ValueError( + f"{bound_reference.shape} reference weights do not align with " + f"{starting.shape} starting weights." + ) + bound = float(max_weight_ratio) * bound_reference + total = float(weights.sum()) + above = weights > bound + return { + "reference": "declared" if declared else "own_starting_weight", + "max_weight_ratio": float(max_weight_ratio), + "records": int(weights.size), + "realized_max_ratio": float((weights / bound_reference).max()), + "records_above_bound": int(above.sum()), + "weight_share_above_bound": ( + float(weights[above].sum() / total) if total > 0 else 0.0 + ), + "records_starting_above_bound": int((starting > bound).sum()), + "admits_the_starting_mass": bool(bound.sum() >= starting.sum()), + } diff --git a/packages/microcosm-calibrate/tests/engine_free/shared/test_spine_target_shares.py b/packages/microcosm-calibrate/tests/engine_free/shared/test_spine_target_shares.py new file mode 100644 index 0000000000..8c9dbf53c5 --- /dev/null +++ b/packages/microcosm-calibrate/tests/engine_free/shared/test_spine_target_shares.py @@ -0,0 +1,197 @@ +"""Which rows carry each target: the spine-target diagnostic (#1729). + +Every number below is made up for the test. +""" + +from __future__ import annotations + +import json + +import numpy as np +import pytest +from scipy import sparse + +from microcosm.calibrate.spine_target_shares import ( + spine_target_shares, + spine_target_shares_for_problem, +) + +# Six records: two donor rows (heavy) and four survey rows (light). +SPINES = np.asarray(["donor", "donor", "survey", "survey", "survey", "survey"]) +WEIGHTS = np.asarray([30.0, 30.0, 10.0, 10.0, 10.0, 10.0]) +AREAS = np.asarray(["A", "B", "A", "A", "B", "B"]) +MATRIX = np.asarray( + [ + # Population of area A: every record in A, one person each. + [1.0, 0.0, 1.0, 1.0, 0.0, 0.0], + # A tax amount only the donor rows carry. + [500.0, 300.0, 0.0, 0.0, 0.0, 0.0], + # A net amount with losses on one survey row. + [100.0, 0.0, -40.0, 0.0, 20.0, 0.0], + # Nothing carries it. + [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + ] +) +NAMES = ["pop_A", "tax", "net", "empty"] + + +@pytest.fixture +def shares(): + return spine_target_shares( + sparse.csr_array(MATRIX), + WEIGHTS, + SPINES, + names=NAMES, + target_scopes=[("area", "A"), None, None, ("area", "B")], + scope_codes={"area": AREAS}, + ) + + +def test_a_share_is_the_part_of_the_target_a_spine_carries(shares) -> None: + assert shares.spines == ("donor", "survey") + np.testing.assert_allclose(shares.estimates, MATRIX @ WEIGHTS) + # Area A's population: 30 on the donor row, 20 on two survey rows. + np.testing.assert_allclose(shares.share[0], [0.6, 0.4]) + np.testing.assert_allclose(shares.carried[0], [30.0, 20.0]) + # The donor rows carry the tax amount alone. + np.testing.assert_allclose(shares.share[1], [1.0, 0.0]) + # Shares sum to one for every carried target. + np.testing.assert_allclose(shares.share[:3].sum(axis=1), 1.0) + assert np.isnan(shares.share[3]).all() + + +def test_the_mass_share_is_taken_in_the_scope_of_the_target(shares) -> None: + np.testing.assert_allclose(shares.overall_mass_share, [0.6, 0.4]) + # In area A the donor row holds 30 of 50; an unscoped target reads all. + np.testing.assert_allclose(shares.mass_share[0], [0.6, 0.4]) + np.testing.assert_allclose(shares.mass_share[1], [0.6, 0.4]) + np.testing.assert_allclose(shares.mass_share[3], [0.6, 0.4]) + # Area A's population is carried in proportion to mass: no excess. + np.testing.assert_allclose(shares.excess[0], 0.0, atol=1e-12) + np.testing.assert_allclose(shares.lift[0], 1.0) + # The tax amount is over-carried by the donor rows. + assert shares.excess[1, 0] == pytest.approx(0.4) + assert shares.lift[1, 0] == pytest.approx(1.0 / 0.6) + + +def test_mixed_signs_are_shared_on_absolute_contributions(shares) -> None: + assert shares.mixed_sign.tolist() == [False, False, True, False] + # |100*30| donor against |-40*10| + |20*10| survey. + np.testing.assert_allclose(shares.share[2], [3000 / 3600, 600 / 3600]) + np.testing.assert_allclose(shares.carried[2], [3000.0, -200.0]) + + +def test_the_ranking_puts_the_targets_a_spine_over_carries_first(shares) -> None: + ranking = shares.ranking("donor") + assert [row["name"] for row in ranking] == ["tax", "net", "pop_A"] + assert ranking[0]["excess"] == pytest.approx(0.4) + assert shares.ranking("donor", top=1)[0]["name"] == "tax" + with pytest.raises(ValueError, match="spine must be one of"): + shares.ranking("puf") + + +def test_the_summary_counts_the_targets_a_spine_carries_almost_alone(shares) -> None: + summary = shares.summary(["pop", "money", "money", "money"]) + assert [entry["group"] for entry in summary] == ["pop", "money"] + money = summary[1] + assert (money["n_targets"], money["n_measured"]) == (3, 2) + assert money["spines"]["donor"]["n_carried_almost_alone"] == 1 + assert money["spines"]["survey"]["n_carried_almost_alone"] == 0 + with pytest.raises(ValueError, match="do not align"): + shares.summary(["pop"]) + + +def test_carriers_count_a_source_household_once() -> None: + # The two donor rows are copies of one source household. + sources = np.asarray(["d1", "d1", "s1", "s2", "s3", "s4"]) + by_row = spine_target_shares(MATRIX, WEIGHTS, SPINES) + by_source = spine_target_shares(MATRIX, WEIGHTS, SPINES, source_ids=sources) + assert by_row.carriers[1].tolist() == [2, 0] + assert by_source.carriers[1].tolist() == [1, 0] + # A zero-weight record is not a carrier. + zeroed = spine_target_shares(MATRIX, [30.0, 0.0, 10, 10, 10, 10], SPINES) + assert zeroed.carriers[1].tolist() == [1, 0] + + +def test_a_floor_withholds_a_target_with_few_carriers() -> None: + shares = spine_target_shares( + MATRIX, WEIGHTS, SPINES, names=NAMES, minimum_carriers=2 + ) + # pop_A has one donor carrier, net has one donor and one each... below 2. + assert shares.withheld.tolist() == [True, False, True, False] + assert np.isnan(shares.share[0]).all() and np.isnan(shares.carried[0]).all() + assert np.isnan(shares.estimates[0]) + assert (shares.carriers[0] == -1).all() + rows = shares.rows() + assert set(rows[0]) == {"name", "scope", "mass_share", "withheld"} + assert rows[1]["share"] == {"donor": 1.0, "survey": 0.0} + # The report is strict JSON, with no NaN in it. + report = shares.report() + assert report["n_withheld"] == 2 + json.dumps(report, allow_nan=False) + assert [row["name"] for row in shares.ranking("donor")] == ["tax"] + + +def test_the_report_names_each_target_and_its_dominant_spine(shares) -> None: + report = shares.report() + json.dumps(report, allow_nan=False) + assert report["spines"] == ["donor", "survey"] + assert report["overall_mass_share"] == pytest.approx({"donor": 0.6, "survey": 0.4}) + by_name = {row["name"]: row for row in report["targets"]} + assert by_name["tax"]["dominant_spine"] == "donor" + assert by_name["tax"]["dominant_share"] == 1.0 + assert by_name["pop_A"]["scope"] == {"kind": "area", "code": "A"} + assert by_name["empty"]["dominant_spine"] is None + assert by_name["empty"]["share"] == {"donor": None, "survey": None} + frame = shares.frame() + assert len(frame) == 8 and set(frame["spine"]) == {"donor", "survey"} + + +def test_a_compiled_problem_is_read_at_its_initial_weights() -> None: + from types import SimpleNamespace + + problem = SimpleNamespace( + matrix=sparse.csr_array(MATRIX), + names=tuple(NAMES), + initial_weights=SimpleNamespace(values=WEIGHTS), + ) + at_start = spine_target_shares_for_problem(problem, SPINES) + np.testing.assert_allclose(at_start.share[1], [1.0, 0.0]) + assert at_start.names == tuple(NAMES) + # Any other weights: a solve that moved weight off the donor rows. + moved = spine_target_shares_for_problem( + problem, SPINES, weights=[10.0, 10.0, 20.0, 20.0, 20.0, 20.0] + ) + assert moved.overall_mass_share[0] == pytest.approx(0.2) + + +@pytest.mark.parametrize( + ("arguments", "match"), + [ + (dict(weights=WEIGHTS[:5]), "weights have shape"), + (dict(weights=-WEIGHTS), "finite and non-negative"), + (dict(weights=np.zeros(6)), "positive total"), + (dict(spines=SPINES[:5]), "spines has shape"), + (dict(names=["only"]), "1 names for 4 targets"), + (dict(minimum_carriers=0), "positive integer"), + (dict(target_scopes=[None] * 3), "3 scopes for 4 targets"), + (dict(target_scopes=[("area", "A")] + [None] * 3), "no record codes"), + ], +) +def test_misaligned_or_invalid_inputs_are_refused(arguments, match) -> None: + call = dict(weights=WEIGHTS, spines=SPINES) + call.update(arguments) + with pytest.raises(ValueError, match=match): + spine_target_shares(MATRIX, call.pop("weights"), call.pop("spines"), **call) + + +def test_a_scope_no_record_is_in_has_no_mass_share() -> None: + shares = spine_target_shares( + MATRIX, + WEIGHTS, + SPINES, + target_scopes=[("area", "Z"), None, None, None], + scope_codes={"area": AREAS}, + ) + assert np.isnan(shares.mass_share[0]).all() + assert np.isnan(shares.lift[0]).all() diff --git a/packages/microcosm-calibrate/tests/engine_free/shared/test_target_loss_rules.py b/packages/microcosm-calibrate/tests/engine_free/shared/test_target_loss_rules.py new file mode 100644 index 0000000000..64637edcf4 --- /dev/null +++ b/packages/microcosm-calibrate/tests/engine_free/shared/test_target_loss_rules.py @@ -0,0 +1,388 @@ +"""Shared target-loss rules: weights and caps from what each row is (#1729).""" + +from __future__ import annotations + +import numpy as np +import pytest + +from microcosm.calibrate import relative_error_loss +from microcosm.calibrate.target_loss_rules import ( + AMOUNT_BASIS, + COUNT_BASIS, + TARGET_WEIGHT_RULES, + TargetLossRows, + TargetWeightRule, + apply_family_multipliers, + row_cap_census, + single_cap_equivalent, + target_loss_caps, + target_loss_weight_shares, + target_loss_weights_for_rule, +) + + +@pytest.fixture +def rows() -> TargetLossRows: + """Three levels with unequal row counts, families and bases.""" + + return TargetLossRows( + values=[4e6, 9e4, 1.6e5, 2.5e9, 100.0, 400.0, 0.0, 3e7], + levels=[ + "state", + "state", + "state", + "state", + "district", + "district", + "district", + "nation", + ], + families=["pop", "soi", "soi", "soi", "pop", "pop", "pop", "pop"], + bases=[ + COUNT_BASIS, + COUNT_BASIS, + COUNT_BASIS, + AMOUNT_BASIS, + COUNT_BASIS, + COUNT_BASIS, + COUNT_BASIS, + COUNT_BASIS, + ], + groups=["a", "b", "b", "c", "d", "d", "d", "e"], + ) + + +def _share(weights: np.ndarray, mask) -> float: + return float(weights[np.asarray(mask)].sum() / weights.sum()) + + +def test_the_vocabulary_is_closed() -> None: + assert sorted(TARGET_WEIGHT_RULES) == [ + "level_equal", + "level_family_equal", + "sqrt_value_concept_budget", + "uniform", + ] + + +def test_uniform_weighs_every_target_one(rows) -> None: + weights = target_loss_weights_for_rule(rows, TargetWeightRule("uniform")) + np.testing.assert_array_equal(weights, np.ones(len(rows))) + + +def test_level_equal_gives_each_level_one_share(rows) -> None: + weights = target_loss_weights_for_rule(rows, TargetWeightRule("level_equal")) + levels = np.asarray(rows.levels) + assert weights.sum() == pytest.approx(1.0) + for level in ("state", "district", "nation"): + assert _share(weights, levels == level) == pytest.approx(1 / 3) + # Uniform inside a level. + assert len(set(weights[levels == "state"].tolist())) == 1 + + +def test_level_family_equal_splits_a_level_across_its_families(rows) -> None: + weights = target_loss_weights_for_rule(rows, TargetWeightRule("level_family_equal")) + levels, families = np.asarray(rows.levels), np.asarray(rows.families) + assert weights.sum() == pytest.approx(1.0) + # The state level has two families: each takes half of the level's third. + assert _share(weights, (levels == "state") & (families == "pop")) == ( + pytest.approx(1 / 6) + ) + assert _share(weights, (levels == "state") & (families == "soi")) == ( + pytest.approx(1 / 6) + ) + # The three soi rows share their cell equally without count_power. + np.testing.assert_allclose(weights[1:4], 1 / 18) + assert _share(weights, levels == "district") == pytest.approx(1 / 3) + + +def test_count_power_moves_weight_only_between_the_count_rows_of_a_cell(rows) -> None: + equal = target_loss_weights_for_rule(rows, TargetWeightRule("level_family_equal")) + powered = target_loss_weights_for_rule( + rows, TargetWeightRule("level_family_equal", {"count_power": 0.5}) + ) + levels, families = np.asarray(rows.levels), np.asarray(rows.families) + # Every (level, family) cell keeps its budget. + for level, family in set(zip(rows.levels, rows.families, strict=True)): + cell = (levels == level) & (families == family) + assert powered[cell].sum() == pytest.approx(equal[cell].sum()) + # The amount row of the state soi cell keeps its equal share. + assert powered[3] == pytest.approx(equal[3]) + # Its two count rows split their budget as sqrt(9e4) : sqrt(1.6e5) = 3 : 4. + assert powered[1] / powered[2] == pytest.approx(300.0 / 400.0) + # A zero count weighs as one unit: sqrt(100) : sqrt(400) : 1 = 10 : 20 : 1. + np.testing.assert_allclose(powered[4:7] / powered[6], [10.0, 20.0, 1.0]) + + +def test_count_power_refuses_a_row_without_a_declared_basis(rows) -> None: + undeclared = TargetLossRows( + values=rows.values, + levels=rows.levels, + families=rows.families, + bases=[*rows.bases[:-1], "rate"], + ) + with pytest.raises(ValueError, match="basis"): + target_loss_weights_for_rule( + undeclared, TargetWeightRule("level_family_equal", {"count_power": 0.5}) + ) + # Without count_power the rule reads no basis. + target_loss_weights_for_rule(undeclared, TargetWeightRule("level_family_equal")) + + +def test_concept_budget_rule_halves_the_loss_between_the_bases(rows) -> None: + weights = target_loss_weights_for_rule( + rows, TargetWeightRule("sqrt_value_concept_budget", {"value_power": 0.5}) + ) + bases = np.asarray(rows.bases) + assert weights.mean() == pytest.approx(1.0) + assert (weights > 0).all() + assert _share(weights, bases == COUNT_BASIS) == pytest.approx(0.5) + assert _share(weights, bases == AMOUNT_BASIS) == pytest.approx(0.5) + # The three district rows share one budget group: before the basis step + # they sum to their largest member, so the largest keeps the largest share. + assert weights[5] > weights[4] > weights[6] + + +def test_a_rule_refuses_rows_that_lack_what_it_reads() -> None: + bare = TargetLossRows(values=[1.0, 2.0]) + with pytest.raises(ValueError, match="levels"): + target_loss_weights_for_rule(bare, TargetWeightRule("level_equal")) + with pytest.raises(ValueError, match="groups"): + target_loss_weights_for_rule( + TargetLossRows(values=[1.0], bases=[COUNT_BASIS]), + TargetWeightRule("sqrt_value_concept_budget"), + ) + with pytest.raises(ValueError, match="2 entries for 1 values"): + TargetLossRows(values=[1.0], levels=["a", "b"]) + + +@pytest.mark.parametrize( + ("name", "parameters", "match"), + [ + ("grain_equal", {}, "must be one of"), + ("uniform", {"count_power": 0.5}, "takes"), + ("level_family_equal", {"count_power": -1.0}, "positive finite"), + ("level_family_equal", {"count_power": True}, "positive finite"), + ("sqrt_value_concept_budget", {"value_power": None}, "must be a number"), + ("uniform", {"family_multipliers": {"pop": 0.0}}, "positive and finite"), + ], +) +def test_a_declaration_refuses_an_unknown_rule_or_parameter( + name, parameters, match +) -> None: + with pytest.raises(ValueError, match=match): + TargetWeightRule(name, parameters) + + +def test_a_declaration_is_data() -> None: + rule = TargetWeightRule( + "level_family_equal", + {"count_power": 1, "family_multipliers": {"soi": 2, "pop": 1.5}}, + ) + assert rule.to_json() == { + "rule": "level_family_equal", + "parameters": { + "count_power": 1.0, + "family_multipliers": {"pop": 1.5, "soi": 2.0}, + }, + } + assert rule.with_family_multipliers(None).to_json() == { + "rule": "level_family_equal", + "parameters": {"count_power": 1.0}, + } + with pytest.raises(TypeError): + rule.parameters["count_power"] = 2.0 # type: ignore[index] + + +def test_family_multipliers_apply_to_any_rule_and_renormalize(rows) -> None: + plain = target_loss_weights_for_rule(rows, TargetWeightRule("level_equal")) + doubled = target_loss_weights_for_rule( + rows, TargetWeightRule("level_equal", {"family_multipliers": {"soi": 2.0}}) + ) + families = np.asarray(rows.families) + assert doubled.mean() == pytest.approx(1.0) + ratio = doubled / plain + assert ratio[families == "soi"][0] == pytest.approx( + 2.0 * ratio[families == "pop"][0] + ) + with pytest.raises(ValueError, match="matches no target family"): + apply_family_multipliers(plain, rows.families, {"absent": 2.0}) + + +def test_weight_shares_report_each_level_and_family_cell(rows) -> None: + weights = target_loss_weights_for_rule(rows, TargetWeightRule("level_family_equal")) + cells = target_loss_weight_shares(rows, weights) + assert [(cell["level"], cell["family"]) for cell in cells] == [ + ("state", "pop"), + ("state", "soi"), + ("district", "pop"), + ("nation", "pop"), + ] + assert sum(cell["loss_share"] for cell in cells) == pytest.approx(1.0) + assert sum(cell["equal_share"] for cell in cells) == pytest.approx(1.0) + assert cells[1]["n_targets"] == 3 + + +# --------------------------------------------------------------------------- +# Loss caps +# --------------------------------------------------------------------------- + + +def test_the_default_cap_stays_one_number() -> None: + cap = target_loss_caps(1.0) + assert cap == 1.0 and isinstance(cap, float) + assert target_loss_caps(10, levels=["a"], families=["b"]) == 10.0 + + +def test_a_cap_by_level_leaves_the_other_rows_at_the_default(rows) -> None: + caps = target_loss_caps(1.0, levels=rows.levels, by_level={"district": 10.0}) + np.testing.assert_array_equal(caps, [1, 1, 1, 1, 10, 10, 10, 1]) + + +def test_a_family_cap_wins_over_a_level_cap(rows) -> None: + caps = target_loss_caps( + 1.0, + levels=rows.levels, + families=rows.families, + by_level={"state": 5.0}, + by_family={"soi": 2.0}, + ) + np.testing.assert_array_equal(caps, [5, 2, 2, 2, 1, 1, 1, 1]) + + +def test_a_cap_override_that_matches_no_row_is_refused(rows) -> None: + with pytest.raises(ValueError, match="matches no target"): + target_loss_caps(1.0, levels=rows.levels, by_level={"county": 10.0}) + with pytest.raises(ValueError, match="needs each row's level"): + target_loss_caps(1.0, by_level={"county": 10.0}) + with pytest.raises(ValueError, match="positive and finite"): + target_loss_caps(1.0, levels=rows.levels, by_level={"state": 0.0}) + with pytest.raises(ValueError, match="positive and finite"): + target_loss_caps(float("nan")) + + +def _row_capped_loss(estimates, targets, weights, scales, caps) -> np.ndarray: + """Each row's weighted contribution under its own cap, written directly.""" + + return ( + weights + * np.minimum(np.abs((estimates - targets) / scales), caps) + / weights.sum() + ) + + +def test_equal_caps_call_the_solver_exactly_as_one_cap_does() -> None: + weights = np.array([0.2, 0.5, 0.3]) + scales = np.array([10.0, 20.0, 1.0]) + equivalent = single_cap_equivalent(np.full(3, 10.0), weights=weights, scales=scales) + assert equivalent.cap == 10.0 + np.testing.assert_array_equal(equivalent.weights, weights) + np.testing.assert_array_equal(equivalent.scales, scales) + + +def test_the_one_cap_loss_equals_the_loss_with_a_cap_for_each_row() -> None: + rng = np.random.default_rng(1729) + n_rows = 400 + targets = rng.lognormal(8.0, 2.0, n_rows) + scales = np.maximum(np.abs(targets), 1.0) + # Misses from 0.01x to 100x the scale, so many rows sit past either cap. + estimates = targets + scales * rng.lognormal(0.0, 2.5, n_rows) * rng.choice( + [-1.0, 1.0], n_rows + ) + weights = rng.uniform(0.0, 3.0, n_rows) + weights[:5] = 0.0 + caps = np.where(rng.uniform(size=n_rows) < 0.6, 1.0, 10.0) + + equivalent = single_cap_equivalent(caps, weights=weights, scales=scales) + direct = _row_capped_loss(estimates, targets, weights, scales, caps) + transformed = _row_capped_loss( + estimates, + targets, + equivalent.weights, + equivalent.scales, + np.full(n_rows, equivalent.cap), + ) + + # Row by row, not only in total. + np.testing.assert_allclose(transformed, direct, rtol=1e-12, atol=0.0) + assert equivalent.weights.sum() == pytest.approx(weights.sum(), rel=1e-12) + # The solver's own loss on the transformed problem is the row-cap loss. + assert relative_error_loss( + estimates, + targets, + target_loss_weights=equivalent.weights, + target_loss_scales=equivalent.scales, + target_loss_cap=equivalent.cap, + ) == pytest.approx(float(direct.sum()), rel=1e-12) + # Both caps bind on some rows, so the identity is tested where it matters. + scaled = np.abs((estimates - targets) / scales) + assert ((scaled > 1.0) & (caps == 1.0)).any() + assert ((scaled > 1.0) & (scaled < 10.0) & (caps == 10.0)).any() + assert equivalent.receipt()["rows_by_cap"] == { + "1.0": int((caps == 1.0).sum()), + "10.0": int((caps == 10.0).sum()), + } + + +def test_the_equivalent_refuses_misaligned_or_invalid_inputs() -> None: + with pytest.raises(ValueError, match="aligned"): + single_cap_equivalent([1.0, 2.0], weights=[1.0], scales=[1.0]) + with pytest.raises(ValueError, match="caps must be finite and positive"): + single_cap_equivalent([1.0, 0.0], weights=[1.0, 1.0], scales=[1.0, 1.0]) + with pytest.raises(ValueError, match="positive total weight"): + single_cap_equivalent([1.0, 2.0], weights=[0.0, 0.0], scales=[1.0, 1.0]) + + +def test_the_census_reads_each_row_against_its_own_cap() -> None: + names = ["state_far", "county_far", "county_escaped", "state_pushed", "at_cap"] + targets = np.asarray([100.0, 100.0, 100.0, 100.0, 100.0]) + scales = np.asarray([100.0, 100.0, 100.0, 100.0, 100.0]) + caps = np.asarray([1.0, 10.0, 10.0, 1.0, 1.0]) + # Scaled misses at the start: 2, 2, 12, 0.5, 1. At the end: 2, 1.5, 3, 4, 1. + initial = np.asarray([300.0, 300.0, 1300.0, 150.0, 200.0]) + final = np.asarray([300.0, 250.0, 400.0, 500.0, 200.0]) + + census = row_cap_census(names, targets, initial, final, scales=scales, caps=caps) + + assert census["cap_basis"] == "each row's own cap" + assert census["n_targets"] == 5 + # A miss of 2 is past a cap of 1 and inside a cap of 10. + assert census["initial_past_cap"] == 2 # state_far, county_escaped + assert census["final_past_cap"] == 2 # state_far, state_pushed + assert (census["escaped"], census["frozen"], census["pushed_out"]) == (1, 1, 1) + assert census["pushed_out_rows"] == [ + {"name": "state_pushed", "cap": 1.0, "init_rel": 0.5, "final_rel": 4.0} + ] + assert census["by_cap"]["1.0"] == { + "n_targets": 3, + "initial_past_cap": 1, + "final_past_cap": 2, + "escaped": 0, + "frozen": 1, + "pushed_out": 1, + } + assert census["by_cap"]["10.0"]["escaped"] == 1 + # A row exactly at its cap still has a gradient: it is not past the cap. + assert census["by_cap"]["1.0"]["initial_past_cap"] == 1 + # One cap for every row gives the counts of a single-cap census. + single = row_cap_census( + names, targets, initial, final, scales=scales, caps=np.full(5, 1.0) + ) + assert single["initial_past_cap"] == 3 and single["final_past_cap"] == 4 + + +def test_the_census_refuses_misaligned_or_invalid_inputs() -> None: + arguments = dict(scales=[1.0, 1.0], caps=[1.0, 1.0]) + with pytest.raises(ValueError, match="there are 2 names"): + row_cap_census(["a", "b"], [1.0], [1.0, 1.0], [1.0, 1.0], **arguments) + with pytest.raises(ValueError, match="must be finite"): + row_cap_census(["a", "b"], [1.0, 1.0], [1.0, np.nan], [1.0, 1.0], **arguments) + with pytest.raises(ValueError, match="must be positive"): + row_cap_census( + ["a", "b"], + [1.0, 1.0], + [1.0, 1.0], + [1.0, 1.0], + scales=[1.0, 0.0], + caps=[1.0, 1.0], + ) diff --git a/packages/microcosm-calibrate/tests/engine_free/shared/test_weight_bound.py b/packages/microcosm-calibrate/tests/engine_free/shared/test_weight_bound.py new file mode 100644 index 0000000000..ebfdd4ae33 --- /dev/null +++ b/packages/microcosm-calibrate/tests/engine_free/shared/test_weight_bound.py @@ -0,0 +1,451 @@ +"""The weight bound's contract, declared references and measurement (#1729). + +The contract tests run the solver itself, so the statements in +``microcosm.calibrate.weight_bound`` are held to what it does. Every number +below is made up for the test. +""" + +from __future__ import annotations + +import numpy as np +import pandas as pd +import pytest + +from microcosm.calibrate import Target, TargetSet, calibrate +from microcosm.calibrate.weight_bound import ( + WEIGHT_BOUND_REFERENCES, + weight_bound_reference, + weight_bound_report, +) +from microcosm.frame import EntitySchema, Frame, WeightKind, Weights + +#: A pooled frame: two heavy rows (27) and four light rows (1). +STARTING = np.asarray([27.0, 27.0, 1.0, 1.0, 1.0, 1.0]) +RATIO = 5.0 + + +def _frame(weights: np.ndarray) -> Frame: + n = len(weights) + return Frame( + { + "person": pd.DataFrame( + { + "person_id": np.arange(n), + "person_household_id": np.arange(n), + } + ), + "household": pd.DataFrame( + { + "household_id": np.arange(n), + "heavy": [1.0, 1.0, 0.0, 0.0, 0.0, 0.0], + "first": [1.0, 0.0, 0.0, 0.0, 0.0, 0.0], + "light": [0.0, 0.0, 1.0, 1.0, 1.0, 1.0], + } + ), + }, + EntitySchema(group_entities=("household",)), + {"household": Weights(weights, WeightKind.DESIGN)}, + ) + + +def _targets(light: float) -> TargetSet: + # Far more mass on the light rows than their bound admits. + return TargetSet( + [ + Target( + name="light", + entity="household", + measure="light", + value=light, + period=2024, + ) + ] + ) + + +def _solve(frame: Frame, **options): + return calibrate( + frame, + _targets(40.0), + weight_entity="household", + epochs=200, + learning_rate=0.05, + mass="conserve", + max_weight_ratio=RATIO, + **options, + ) + + +def test_the_bound_is_against_the_frame_not_the_warm_start() -> None: + frame = _frame(STARTING) + first = _solve(frame) + # The light rows are pinned at five times their own starting weight. + np.testing.assert_allclose(first.weights[2:], RATIO * STARTING[2:], rtol=1e-6) + assert first.realized_max_weight_ratio <= RATIO * (1 + 1e-12) + + # A second batch that continues from the first batch's weights keeps the + # bound against the frame: batches do not compound it. + second = _solve(frame, warm_start_weights=first.weights) + assert (second.weights <= RATIO * STARTING * (1 + 1e-12)).all() + assert second.realized_max_weight_ratio <= RATIO * (1 + 1e-12) + + +def test_a_new_frame_is_a_new_reference() -> None: + first = _solve(_frame(STARTING)) + # A stage whose frame carries the first stage's weights bounds against + # those: against the original weights the two stages admit RATIO ** 2. + chained = _solve(_frame(first.weights)) + against_original = weight_bound_report( + chained.weights, STARTING, max_weight_ratio=RATIO + ) + assert chained.realized_max_weight_ratio <= RATIO * (1 + 1e-12) + assert RATIO < against_original["realized_max_ratio"] <= RATIO**2 * (1 + 1e-12) + assert against_original["records_above_bound"] == 4 + + +def test_a_heavy_record_gets_a_larger_absolute_bound() -> None: + result = _solve(_frame(STARTING)) + own = weight_bound_report(result.weights, STARTING, max_weight_ratio=RATIO) + assert own["reference"] == "own_starting_weight" + assert own["records_above_bound"] == 0 + assert own["admits_the_starting_mass"] is True + # Under the same ratio a heavy row may reach 27 times a light row's bound. + assert RATIO * STARTING[0] == 27 * RATIO * STARTING[2] + + # Against one shared weight (the mean, 58 / 6), the heavy rows start + # under the bound here, and the report says what the bound would admit. + shared = weight_bound_reference(STARTING, "mean") + declared = weight_bound_report( + result.weights, STARTING, max_weight_ratio=RATIO, reference=shared + ) + assert declared["reference"] == "declared" + assert declared["records_starting_above_bound"] == 0 + assert declared["realized_max_ratio"] == pytest.approx( + (result.weights / (58 / 6)).max() + ) + # At a tight ratio the heavy rows start above a shared bound. + tight = weight_bound_report( + result.weights, STARTING, max_weight_ratio=2.0, reference=shared + ) + assert tight["records_starting_above_bound"] == 2 + assert tight["admits_the_starting_mass"] is True + + +def test_the_declared_references() -> None: + assert WEIGHT_BOUND_REFERENCES == ("own", "mean", "group_mean") + np.testing.assert_array_equal(weight_bound_reference(STARTING), STARTING) + np.testing.assert_allclose(weight_bound_reference(STARTING, "mean"), 58 / 6) + areas = ["A", "B", "A", "A", "B", "B"] + np.testing.assert_allclose( + weight_bound_reference(STARTING, "group_mean", groups=areas), + [29 / 3] * 6, + ) + np.testing.assert_allclose( + weight_bound_reference([4.0, 2.0, 6.0], "group_mean", groups=[1, 2, 1]), + [5.0, 2.0, 5.0], + ) + with pytest.raises(ValueError, match="must be one of"): + weight_bound_reference(STARTING, "median") + with pytest.raises(ValueError, match="needs each record's group"): + weight_bound_reference(STARTING, "group_mean") + with pytest.raises(ValueError, match="do not align"): + weight_bound_reference(STARTING, "group_mean", groups=["A"]) + with pytest.raises(ValueError, match="strictly positive"): + weight_bound_reference([1.0, 0.0]) + + +def test_the_report_measures_and_refuses_bad_inputs() -> None: + weights = np.asarray([10.0, 1.0, 0.0, 9.0]) + starting = np.asarray([1.0, 1.0, 1.0, 1.0]) + report = weight_bound_report(weights, starting, max_weight_ratio=5.0) + assert report == { + "reference": "own_starting_weight", + "max_weight_ratio": 5.0, + "records": 4, + "realized_max_ratio": 10.0, + "records_above_bound": 2, + "weight_share_above_bound": 0.95, + "records_starting_above_bound": 0, + "admits_the_starting_mass": True, + } + # Bounds that sum below the starting total cannot conserve the mass. + assert ( + weight_bound_report( + weights, starting, max_weight_ratio=0.5, reference=starting + )["admits_the_starting_mass"] + is False + ) + for arguments, match in ( + (dict(max_weight_ratio=0.0), "positive and finite"), + (dict(max_weight_ratio=5.0, reference=[1.0, 1.0]), "do not align"), + (dict(max_weight_ratio=5.0, reference=[1.0, 1.0, 0.0, 1.0]), "positive"), + ): + with pytest.raises(ValueError, match=match): + weight_bound_report(weights, starting, **arguments) + with pytest.raises(ValueError, match="do not align"): + weight_bound_report(weights[:3], starting, max_weight_ratio=5.0) + + +# --------------------------------------------------------------------------- +# A declared reference, enforced by the solver +# --------------------------------------------------------------------------- + + +def _targets_first(value: float) -> TargetSet: + """A target on the first heavy row alone.""" + + return TargetSet( + [ + Target( + name="first", + entity="household", + measure="first", + value=value, + period=2024, + ) + ] + ) + + +def test_the_starting_weights_as_the_reference_are_the_default_solve() -> None: + frame = _frame(STARTING) + default = _solve(frame) + declared = _solve(frame, max_weight_reference=STARTING.copy()) + # The same bytes: the reference only replaces what the ratio multiplies. + assert declared.weights.tobytes() == default.weights.tobytes() + assert declared.loss_trajectory.tobytes() == default.loss_trajectory.tobytes() + assert "weight_bound" not in default.options + assert declared.options["weight_bound"] == { + "reference": "declared", + "records_started_above_bound": 0, + "realized_max_ratio_to_reference": pytest.approx(RATIO), + } + + +def test_a_shared_reference_gives_every_record_one_absolute_bound() -> None: + frame = _frame(STARTING) + shared = weight_bound_reference(STARTING, "mean") # 58 / 6 for every record + # The target asks 50 of the first heavy row, which starts at 27. + solve = dict( + weight_entity="household", + epochs=400, + learning_rate=0.05, + mass="conserve", + max_weight_ratio=3.0, + ) + own = calibrate(frame, _targets_first(50.0), **solve) + result = calibrate( + frame, _targets_first(50.0), **solve, max_weight_reference=shared + ) + bound = 3.0 * shared + # Against its own starting weight the row may reach 81, so it reaches 50. + assert own.weights[0] == pytest.approx(50.0, rel=0.02) + # Against the shared weight every record has the bound 29, and the row + # stops there. + assert (result.weights <= bound * (1 + 1e-12)).all() + assert result.weights[0] == pytest.approx(29.0, rel=1e-6) + assert result.weights.sum() == pytest.approx(STARTING.sum()) + assert result.options["weight_bound"] == { + "reference": "declared", + "records_started_above_bound": 0, + "realized_max_ratio_to_reference": pytest.approx(3.0), + } + # The frame's weights are still the solve's starting point and record. + np.testing.assert_array_equal(result.initial_weights, STARTING) + report = weight_bound_report( + result.weights, STARTING, max_weight_ratio=3.0, reference=shared + ) + assert report["records_above_bound"] == 0 + + +def test_a_record_that_starts_above_its_bound_starts_from_the_bound() -> None: + frame = _frame(STARTING) + shared = weight_bound_reference(STARTING, "mean") + # Two times the mean (19.3) is below the heavy rows' starting weight (27). + result = calibrate( + frame, + _targets(4.0), # the light rows already hit it: nothing to fit + weight_entity="household", + epochs=5, + mass="conserve", + max_weight_ratio=2.0, + max_weight_reference=shared, + ) + bound = 2.0 * shared + assert result.options["weight_bound"]["records_started_above_bound"] == 2 + assert (result.weights <= bound * (1 + 1e-12)).all() + assert result.weights.sum() == pytest.approx(STARTING.sum()) + # The mass the heavy rows gave up went to the light rows. + assert (result.weights[2:] > STARTING[2:]).all() + # Free mass: the heavy rows are held to the bound and nothing is refilled. + free = calibrate( + frame, + _targets(4.0), + weight_entity="household", + epochs=5, + mass="free", + max_weight_ratio=2.0, + max_weight_reference=shared, + ) + assert (free.weights <= bound * (1 + 1e-12)).all() + assert free.weights.sum() < STARTING.sum() + + +def test_a_warm_start_keeps_the_declared_bound() -> None: + frame = _frame(STARTING) + shared = weight_bound_reference(STARTING, "mean") + options = dict(max_weight_reference=shared) + first = _solve(frame, **options) + second = _solve(frame, warm_start_weights=first.weights, **options) + assert (second.weights <= RATIO * shared * (1 + 1e-12)).all() + assert second.weights.sum() == pytest.approx(STARTING.sum()) + + +def test_the_softmax_parametrization_holds_the_declared_bound() -> None: + """The softmax mass path bounds against the reference, in the loop too. + + Under ``mass_parametrization="softmax"`` the per-step projection and the + in-loop receipt read the cap the solver builds from the reference + (``softmax_cap``), not from the starting weights. + """ + + shared = weight_bound_reference(STARTING, "mean") + solve = dict( + weight_entity="household", + epochs=400, + learning_rate=0.05, + mass="conserve", + mass_parametrization="softmax", + ) + result = calibrate( + _frame(STARTING), + _targets_first(50.0), + **solve, + max_weight_ratio=3.0, + max_weight_reference=shared, + ) + assert (result.weights <= 3.0 * shared * (1 + 1e-12)).all() + assert result.weights[0] == pytest.approx(29.0, rel=1e-5) + assert result.weights.sum() == pytest.approx(STARTING.sum()) + assert result.options["mass_parametrization"] == "softmax" + # Every weight the loop evaluated stayed within its declared cap, up to + # the float32 error of the softmax normalizer. + in_loop = result.options["iterate_selection_receipt"][ + "softmax_in_loop_max_cap_ratio" + ] + assert in_loop == pytest.approx(1.0, abs=1e-5) + # Against its own starting weight the same solve takes the row to 50. + own = calibrate( + _frame(STARTING), _targets_first(50.0), **solve, max_weight_ratio=3.0 + ) + assert own.weights[0] == pytest.approx(50.0, rel=0.02) + + +def test_the_softmax_parametrization_starts_from_the_bound() -> None: + # Two times the mean (19.3) is below the heavy rows' starting weight (27). + shared = weight_bound_reference(STARTING, "mean") + result = calibrate( + _frame(STARTING), + _targets(4.0), # the light rows already hit it: nothing to fit + weight_entity="household", + epochs=5, + mass="conserve", + mass_parametrization="softmax", + max_weight_ratio=2.0, + max_weight_reference=shared, + ) + bound = 2.0 * shared + assert result.options["weight_bound"]["records_started_above_bound"] == 2 + assert (result.weights <= bound * (1 + 1e-12)).all() + assert result.weights.sum() == pytest.approx(STARTING.sum()) + # No weight the loop evaluated passed its cap, from the first epoch on. + assert ( + result.options["iterate_selection_receipt"]["softmax_in_loop_max_cap_ratio"] + <= 1.0 + 1e-5 + ) + + +def test_bounds_that_cannot_hold_the_mass_are_refused() -> None: + frame = _frame(STARTING) + small = np.full(6, 1.0) # 5 x 6 = 30 admitted, 58 to conserve + with pytest.raises(ValueError, match="mass cannot be conserved"): + _solve(frame, max_weight_reference=small) + # Free mass has no total to hold. + free = calibrate( + frame, + _targets(4.0), + weight_entity="household", + epochs=3, + mass="free", + max_weight_ratio=RATIO, + max_weight_reference=small, + ) + assert (free.weights <= RATIO * small * (1 + 1e-12)).all() + # A ratio below one is admitted when the reference is large enough. + large = np.full(6, 100.0) + below_one = calibrate( + frame, + _targets(4.0), + weight_entity="household", + epochs=3, + mass="conserve", + max_weight_ratio=0.5, + max_weight_reference=large, + ) + assert below_one.weights.sum() == pytest.approx(STARTING.sum()) + # Without a reference a ratio below one cannot conserve the mass. + with pytest.raises(ValueError, match="is infeasible"): + calibrate( + frame, + _targets(4.0), + weight_entity="household", + epochs=3, + mass="conserve", + max_weight_ratio=0.5, + ) + + +@pytest.mark.parametrize( + ("options", "match"), + [ + (dict(max_weight_ratio=None), "pass max_weight_ratio too"), + (dict(method="prox"), "Adam solve without L0 gates"), + (dict(l0_lambda=0.01), "Adam solve without L0 gates"), + (dict(target_records=3), "Adam solve without L0 gates"), + (dict(max_weight_reference=np.ones(5)), "must match"), + (dict(max_weight_reference=np.zeros(6)), "strictly positive"), + (dict(max_weight_reference=np.full(6, np.nan)), "strictly positive"), + ], +) +def test_an_invalid_declared_reference_is_refused(options, match) -> None: + call = dict( + weight_entity="household", + epochs=3, + mass="conserve", + max_weight_ratio=RATIO, + max_weight_reference=np.full(6, 20.0), + ) + call.update(options) + with pytest.raises(ValueError, match=match): + calibrate(_frame(STARTING), _targets(4.0), **call) + + +def test_the_prebuilt_system_solve_takes_the_reference_too() -> None: + import torch + + from microcosm.calibrate.solve import solve_constraint_system + + operator = torch.tensor([[1.0, 0.0, 0.0, 0.0, 0.0, 0.0]], dtype=torch.float32) + shared = weight_bound_reference(STARTING, "mean") + arguments = dict( + mass="conserve", max_weight_ratio=3.0, epochs=400, learning_rate=0.05 + ) + weights, _trajectory = solve_constraint_system( + operator, np.asarray([50.0]), STARTING, max_weight_reference=shared, **arguments + ) + assert (weights <= 3.0 * shared * (1 + 1e-12)).all() + assert weights[0] == pytest.approx(29.0, rel=1e-6) + own, _ = solve_constraint_system( + operator, np.asarray([50.0]), STARTING, **arguments + ) + assert own[0] == pytest.approx(50.0, rel=0.02) diff --git a/packages/microcosm-graph/tests/fixtures/parity/kernels/calibrate/pins.json b/packages/microcosm-graph/tests/fixtures/parity/kernels/calibrate/pins.json index da8d41937d..e20dffbd05 100644 --- a/packages/microcosm-graph/tests/fixtures/parity/kernels/calibrate/pins.json +++ b/packages/microcosm-graph/tests/fixtures/parity/kernels/calibrate/pins.json @@ -1 +1 @@ -{"dependencies":{"numpy":"2.4.6","pandas":"3.0.3","scipy":"1.17.1","torch":"2.12.0"},"implementation_hash":"e8ab1d370f02917ac073f7ac0e2413e259d66acf66adeab93d4bfa9057554673","kernel":"calibrate.adam@1","node":"calibrate","node_key":"18a16aefaba5c3fbbce77d193074a202ef1d58e0a3d90bd085bf8ae5853628b2","numeric":"bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"18a16aefaba5c3fbbce77d193074a202ef1d58e0a3d90bd085bf8ae5853628b2"}},"seed":0} +{"dependencies":{"numpy":"2.4.6","pandas":"3.0.3","scipy":"1.17.1","torch":"2.12.0"},"implementation_hash":"0f2dc8f6eb3c1c9d07626bea14593453905e8191b7c4c4d68428ac14b9d11e06","kernel":"calibrate.adam@1","node":"calibrate","node_key":"51931394a100e39dc4b3bb195cca7e84c96599228b2a8b8bb8a196511ae44bf7","numeric":"bitwise","platform":"arm64/darwin/py3.14","platforms":{"arm64/darwin/py3.14":{"direct":"direct.csv","node_key":"51931394a100e39dc4b3bb195cca7e84c96599228b2a8b8bb8a196511ae44bf7"}},"seed":0} diff --git a/test_support/microcosm_build/area_support_gate_reference.py b/test_support/microcosm_build/area_support_gate_reference.py new file mode 100644 index 0000000000..6aef501f05 --- /dev/null +++ b/test_support/microcosm_build/area_support_gate_reference.py @@ -0,0 +1,269 @@ +"""The area support gate exactly as it stood before #1729. + +Verbatim copies of ``area_support_shortfalls``, ``area_support_below_floor`` +and ``area_support_gate`` of ``microcosm.build.gates`` at fccd9a68b +(origin/main when the gate gained optional floors and a floor relative to the +starting ESS), under their original names, so ``git diff`` against that +commit's module shows them unchanged. The differential tests hold the new +gate, called with the three absolute floors as the UK local build calls it, +equal to this copy. Do not edit it; it is the "before" of the change. +""" + +from __future__ import annotations + +import math +from collections.abc import Iterable, Mapping + +import numpy as np +import pandas as pd + +from microcosm.build.gates import GateResult + + +def area_support_shortfalls( + rows: float, + effective_sample_size: float, + sources: float, + *, + minimum_rows: int, + minimum_effective_sample_size: float, + minimum_distinct_sources: int, +) -> list[str]: + """The support floors one area misses, worded as :func:`area_support_gate` reports them. + + Each shortfall states the area's measured value beside the floor: the + release ships per-area support figures since María's ruling of + 2026-10-26, which dropped their withholding (microcosm#1301). + """ + + shortfalls = [] + if rows < minimum_rows: + shortfalls.append(f"rows {int(rows)} < {minimum_rows}") + if effective_sample_size < minimum_effective_sample_size: + shortfalls.append( + "ESS " + f"{float(effective_sample_size):.6g} < " + f"{float(minimum_effective_sample_size):.6g}" + ) + if sources < minimum_distinct_sources: + shortfalls.append( + f"distinct sources {int(sources)} < {minimum_distinct_sources}" + ) + return shortfalls + + +def area_support_below_floor( + area_support: pd.DataFrame, + *, + minimum_rows: int, + minimum_effective_sample_size: float, + minimum_distinct_sources: int, +) -> pd.Series: + """Whether each area of a support table misses any floor, by the gate's rule. + + A reviewed exclusion does not lift the flag: an excluded area is still + below the floor, which is what a consumer of the area's estimates needs. + """ + + return pd.Series( + [ + bool( + area_support_shortfalls( + row.nonzero_households, + row.effective_sample_size, + row.nonzero_source_households, + minimum_rows=minimum_rows, + minimum_effective_sample_size=minimum_effective_sample_size, + minimum_distinct_sources=minimum_distinct_sources, + ) + ) + for row in area_support.itertuples(index=False) + ], + index=area_support.index, + dtype=bool, + ) + + +def area_support_gate( + area_support: pd.DataFrame, + *, + area_roster: Mapping[str, Iterable[str]], + geography_levels: Iterable[str], + minimum_rows: int, + minimum_effective_sample_size: float, + minimum_distinct_sources: int, + reviewed_exclusions: Mapping[str, Mapping[str, object]] | None = None, +) -> GateResult: + """Require adequate positive-weight support in every declared local area. + + ``area_support`` is the long-form candidate receipt. The independently + declared ``area_roster`` is load-bearing: a missing weak area cannot make + the gate look better by disappearing from the evidence table. + + A failure and a reviewed exclusion state the area's measured support + beside the floors it misses, and each geography level reports how many + areas were checked and sit below a floor, and its minima (María's ruling + of 2026-10-26 dropped the withholding of microcosm#1301). + """ + + levels = tuple(str(level) for level in geography_levels) + if not levels or len(set(levels)) != len(levels): + raise ValueError("geography_levels must be non-empty and unique.") + if ( + isinstance(minimum_rows, bool) + or not isinstance(minimum_rows, int) + or minimum_rows < 1 + ): + raise ValueError("minimum_rows must be a positive integer.") + if ( + isinstance(minimum_distinct_sources, bool) + or not isinstance(minimum_distinct_sources, int) + or minimum_distinct_sources < 1 + ): + raise ValueError("minimum_distinct_sources must be a positive integer.") + if ( + not math.isfinite(float(minimum_effective_sample_size)) + or minimum_effective_sample_size <= 0 + ): + raise ValueError("minimum_effective_sample_size must be positive and finite.") + if not isinstance(area_support, pd.DataFrame): + raise TypeError("area_support must be a pandas DataFrame.") + required_columns = { + "geography_level", + "area_code", + "nonzero_households", + "nonzero_source_households", + "effective_sample_size", + } + missing_columns = sorted(required_columns - set(area_support.columns)) + if missing_columns: + raise ValueError( + f"area_support is missing required column(s): {missing_columns}." + ) + unexpected_levels = sorted( + set(area_support["geography_level"].astype(str)) - set(levels) + ) + if unexpected_levels: + raise ValueError( + "area_support contains geography level(s) outside the declared " + f"scope: {unexpected_levels}." + ) + + rows = area_support.copy() + rows["geography_level"] = rows["geography_level"].astype(str) + rows["area_code"] = rows["area_code"].astype(str) + duplicate_mask = rows.duplicated(["geography_level", "area_code"], keep=False) + if duplicate_mask.any(): + duplicates = sorted( + { + f"{row.geography_level}/{row.area_code}" + for row in rows.loc[ + duplicate_mask, ["geography_level", "area_code"] + ].itertuples(index=False) + } + ) + raise ValueError(f"area_support contains duplicate area rows: {duplicates}.") + + expected_pairs: set[tuple[str, str]] = set() + for level in levels: + if level not in area_roster: + raise ValueError(f"area_roster is missing geography level {level!r}.") + codes = tuple(str(code) for code in area_roster[level]) + if not codes or len(set(codes)) != len(codes): + raise ValueError(f"area_roster[{level!r}] must be non-empty and unique.") + expected_pairs.update((level, code) for code in codes) + actual_pairs = set(zip(rows["geography_level"], rows["area_code"], strict=True)) + missing_areas = sorted(expected_pairs - actual_pairs) + extra_areas = sorted(actual_pairs - expected_pairs) + if missing_areas or extra_areas: + raise ValueError( + "area_support must exactly cover the declared roster; " + f"missing={missing_areas[:10]}, extra={extra_areas[:10]}." + ) + + numeric_columns = ( + "nonzero_households", + "nonzero_source_households", + "effective_sample_size", + ) + values = rows.loc[:, list(numeric_columns)].to_numpy(dtype=np.float64) + if not np.isfinite(values).all() or (values < 0).any(): + raise ValueError("area_support contains invalid support values.") + + exclusions = {} if reviewed_exclusions is None else dict(reviewed_exclusions) + failures: list[str] = [] + used_exclusions: dict[str, dict[str, object]] = {} + stale_exclusions: list[str] = [] + below_floor = dict.fromkeys(levels, 0) + for row in rows.sort_values(["geography_level", "area_code"]).itertuples( + index=False + ): + key = f"{row.geography_level}/{row.area_code}" + shortfalls = area_support_shortfalls( + row.nonzero_households, + row.effective_sample_size, + row.nonzero_source_households, + minimum_rows=minimum_rows, + minimum_effective_sample_size=minimum_effective_sample_size, + minimum_distinct_sources=minimum_distinct_sources, + ) + if shortfalls: + below_floor[row.geography_level] += 1 + record = exclusions.get(key) + if record is not None and shortfalls: + used_exclusions[key] = { + "shortfalls": shortfalls, + "rows": int(row.nonzero_households), + "ess": float(row.effective_sample_size), + "sources": int(row.nonzero_source_households), + "record": dict(record), + } + elif record is not None: + stale_exclusions.append(key) + failures.append( + f"{key}: reviewed exclusion is stale; every support floor is met, " + "so retire the exclusion." + ) + elif shortfalls: + failures.append(f"{key}: " + ", ".join(shortfalls)) + + known_keys = {f"{level}/{code}" for level, code in expected_pairs} + unknown_exclusions = sorted(set(exclusions) - known_keys) + failures.extend( + f"{key}: reviewed exclusion is unknown to the area roster." + for key in unknown_exclusions + ) + + by_level: dict[str, dict[str, object]] = {} + for level in levels: + level_rows = rows.loc[rows["geography_level"] == level] + by_level[level] = { + "areas_checked": int(len(level_rows)), + "areas_below_floor": below_floor[level], + "minimum_rows": int(level_rows["nonzero_households"].min()), + "minimum_effective_sample_size": float( + level_rows["effective_sample_size"].min() + ), + "minimum_distinct_sources": int( + level_rows["nonzero_source_households"].min() + ), + } + return GateResult( + name="area_support", + passed=not failures, + failures=tuple(failures), + details={ + "floors": { + "minimum_rows": minimum_rows, + "minimum_effective_sample_size": float(minimum_effective_sample_size), + "minimum_distinct_sources": minimum_distinct_sources, + }, + "by_geography_level": by_level, + "areas_checked": len(expected_pairs), + "areas_failed": len(failures), + "reviewed_exclusions": used_exclusions, + "excluded_area_count": len(used_exclusions), + "stale_exclusions": stale_exclusions, + "unknown_exclusions": unknown_exclusions, + }, + ) diff --git a/test_support/microcosm_build/uk_target_weights_reference.py b/test_support/microcosm_build/uk_target_weights_reference.py new file mode 100644 index 0000000000..0bb19fc696 --- /dev/null +++ b/test_support/microcosm_build/uk_target_weights_reference.py @@ -0,0 +1,106 @@ +"""The UK loss-weight arithmetic exactly as it stood before #1729. + +Verbatim copies of ``uk_target_loss_weights_for_rows`` +(``uk_runtime.target_weights``) and ``uk_national_target_loss_weights`` +(``uk_runtime.national_doctrine``) at fccd9a68b (origin/main when both moved +onto the shared rules of ``microcosm.calibrate.target_loss_rules``), under +their original names, so ``git diff`` against that commit's modules shows them +unchanged. The helpers they call say what a UK row is; those did not move, and +are imported from the live modules. The differential tests hold the shared +rules to these copies, bit for bit. Do not edit them; they are the "before" of +a pure move. +""" + +from __future__ import annotations + +from collections import Counter +from collections.abc import Sequence + +import numpy as np + +from microcosm.build.uk_runtime.national_doctrine import ( + _ALLOWED_TARGET_WEIGHT_RULES, + UK_NATIONAL_TARGET_WEIGHT_RULE, +) +from microcosm.build.uk_runtime.target_weights import ( + _AMOUNT, + _COUNT, + UKTargetRows, + _check_row_rule, + _rule_grains, + uk_target_value_basis, +) + + +def uk_target_loss_weights_for_rows(rows: UKTargetRows, *, rule: str) -> np.ndarray: + """The loss-weight vector of a row-metadata rule (sums to one).""" + + _check_row_rule(rule) + if not len(rows): + raise ValueError("target weighting requires at least one target.") + nation = rule.startswith("nation_") + sqrt_count = rule.endswith("_sqrt_count") + grains = np.asarray(_rule_grains(rows, nation=nation), dtype=object) + families = np.asarray(rows.family, dtype=object) + bases = ( + np.asarray(uk_target_value_basis(rows), dtype=object) if sqrt_count else None + ) + magnitudes = np.maximum(np.abs(rows.values), 1.0) ** 0.5 if sqrt_count else None + grain_order = list(dict.fromkeys(grains.tolist())) + weights = np.zeros(len(rows), dtype=np.float64) + for grain in grain_order: + in_grain = grains == grain + family_order = list(dict.fromkeys(families[in_grain].tolist())) + budget = 1.0 / (len(grain_order) * len(family_order)) + for family in family_order: + cell = np.flatnonzero(in_grain & (families == family)) + if bases is None: + weights[cell] = budget / cell.size + continue + counts = cell[bases[cell] == _COUNT] + amounts = cell[bases[cell] == _AMOUNT] + weights[amounts] = budget / cell.size + if counts.size: + share = magnitudes[counts] + weights[counts] = ( + (budget * counts.size / cell.size) * share / share.sum() + ) + return weights + + +def uk_national_target_loss_weights( + families: Sequence[str], + *, + rule: str = UK_NATIONAL_TARGET_WEIGHT_RULE, +) -> np.ndarray | None: + """The declared target-weight vector for one compiled register. + + ``uniform`` returns ``None`` — the kernel's own equal weighting, and the + identity this doctrine shipped with. ``family_equal`` gives each declared + family one equal share of the objective, divided evenly among its + members, so an over-supplied family cannot outvote the rest of the + surface by sheer count. + + The vector is derived from the compiled register's declared families and + nothing else: it is a rule, not a per-target vector, which is the + property the local doctrine requires of any weighting. + """ + + if rule not in _ALLOWED_TARGET_WEIGHT_RULES: + raise ValueError( + f"target_weight_rule must be one of {_ALLOWED_TARGET_WEIGHT_RULES}, " + f"got {rule!r}." + ) + if rule == "uniform": + return None + labels = [str(family) for family in families] + if not labels: + raise ValueError("family_equal weighting requires a non-empty register.") + if any(not label for label in labels): + raise ValueError("every target must declare a family for family_equal.") + counts = Counter(labels) + family_count = len(counts) + return np.asarray( + [1.0 / (family_count * counts[label]) for label in labels], + dtype=np.float64, + ) diff --git a/test_support/microcosm_build/us_district_ess_gate_reference.py b/test_support/microcosm_build/us_district_ess_gate_reference.py new file mode 100644 index 0000000000..61997d7e1e --- /dev/null +++ b/test_support/microcosm_build/us_district_ess_gate_reference.py @@ -0,0 +1,163 @@ +"""The ACS local district ESS gate exactly as it stood before #1729. + +A verbatim copy of the constants and the two functions +``tools/build_us_acs_local_release.py`` defined at ac7ab99ae (origin/main when +the gate's floors and comparisons moved to the shared +``microcosm.build.area_support``), under their original names, so ``git +diff`` against that commit's tool shows them unchanged. The differential test +holds the tool's gate entry equal to this copy's. Do not edit it; it is the +"before" of a pure move. +""" + +from __future__ import annotations + +import numpy as np + +#: Finalize's district ESS gate. A congressional district collapses when +#: calibration leaves its Kish ESS below this share of its Kish ESS at the +#: design weights. At the release's ACS share (0.5), microcosm#1078's solves +#: (full surface and two holdout folds) leave 15-24 districts below a quarter +#: unpenalized, and none with the chi-square design-weight penalty. +DISTRICT_ESS_RELATIVE_FLOOR = 0.25 +#: The absolute floor on a district's calibrated Kish ESS (0 turns it off). +#: Those solves' smallest district ESS is 7.8-11.7 unpenalized and at least +#: 18.5 penalized. +DISTRICT_ESS_FLOOR = 15.0 +DISTRICT_ESS_GATE = "district_ess_collapse" + + +def _district_ess(weight_summary) -> dict[str, float] | None: + """A weight summary's per-district Kish ESS as finite, nonnegative floats. + + None when the summary records none, or any value is not such a number. + """ + + by_district = ( + weight_summary.get("effective_sample_size_by_district") + if isinstance(weight_summary, dict) + else None + ) + if not isinstance(by_district, dict) or not by_district: + return None + values = {} + for district, ess in by_district.items(): + if isinstance(ess, bool) or not isinstance(ess, (int, float)): + return None + try: + value = float(ess) + except OverflowError: # a JSON integer too large for a float + return None + if not np.isfinite(value) or value < 0: + return None + values[str(district)] = value + return values + + +def district_ess_collapse_gate( + weight_origin: dict | None, + *, + relative_floor: float = DISTRICT_ESS_RELATIVE_FLOOR, + absolute_floor: float = DISTRICT_ESS_FLOOR, + blocking: bool = False, +) -> dict: + """The district ESS gate entry, from the calibration summary's weight origin. + + Reads ``effective_sample_size_by_district`` at the design and the + calibrated weights. A district collapses when its calibrated Kish ESS is + below ``relative_floor`` times its design-weight Kish ESS, and is below + the floor when its calibrated Kish ESS is below ``absolute_floor``; a + floor of 0 turns its check off. ``criteria_met`` says whether no district + does either (None when the evidence is missing or malformed). + + The release contract publishes only gates that pass, so a report-only + entry passes whatever it measured. Under ``blocking`` the entry passes + only when the criteria are met. + """ + + if not 0.0 <= relative_floor <= 1.0: + raise ValueError(f"relative_floor must be in [0, 1], got {relative_floor!r}.") + if not (np.isfinite(absolute_floor) and absolute_floor >= 0.0): + raise ValueError( + f"absolute_floor must be finite and >= 0, got {absolute_floor!r}." + ) + origin = weight_origin if isinstance(weight_origin, dict) else {} + design = _district_ess(origin.get("design")) + calibrated = _district_ess(origin.get("calibrated")) + gate = { + "blocking": bool(blocking), + "report_only": not blocking, + "relative_floor": float(relative_floor), + "absolute_floor": float(absolute_floor), + "note": ( + "A congressional district collapses when its calibrated Kish ESS " + "is below relative_floor x its design-weight Kish ESS, and is " + "below the floor when its calibrated Kish ESS is below " + "absolute_floor (0 turns a check off); from " + "calibration_summary.json weight_origin." + ), + } + failures = [] + if design is None or calibrated is None: + failures.append( + "calibration_summary.json weight_origin records no finite, " + "nonnegative effective_sample_size_by_district at both the design " + "and the calibrated weights" + ) + elif set(design) != set(calibrated): + failures.append( + "the design and calibrated per-district ESS cover different districts" + ) + if failures: + return { + **gate, + "passed": not blocking, + "criteria_met": None, + "failures": failures, + } + + rows = [ + { + "district": district, + "calibrated_ess": calibrated[district], + "design_ess": design[district], + "ratio": ( + calibrated[district] / design[district] + if design[district] > 0 + else None + ), + } + for district in sorted(design) + ] + collapsed = sorted( + ( + row + for row in rows + if row["calibrated_ess"] < relative_floor * row["design_ess"] + ), + key=lambda row: (row["ratio"], row["district"]), + ) + below_floor = sorted( + (row for row in rows if row["calibrated_ess"] < absolute_floor), + key=lambda row: (row["calibrated_ess"], row["district"]), + ) + smallest = min(rows, key=lambda row: (row["calibrated_ess"], row["district"])) + rated = [row for row in rows if row["ratio"] is not None] + lowest = ( + min(rated, key=lambda row: (row["ratio"], row["district"])) if rated else None + ) + criteria_met = not collapsed and not below_floor + return { + **gate, + "passed": criteria_met or not blocking, + "criteria_met": criteria_met, + "failures": [], + "n_districts": len(rows), + "n_collapsed": len(collapsed), + "n_below_floor": len(below_floor), + "min_calibrated_ess": smallest["calibrated_ess"], + "min_calibrated_ess_district": smallest["district"], + "min_ess_ratio": lowest["ratio"] if lowest else None, + "min_ess_ratio_district": lowest["district"] if lowest else None, + "collapsed": collapsed, + "below_floor": below_floor, + } diff --git a/test_support/microcosm_build/us_target_loss_rows_reference.py b/test_support/microcosm_build/us_target_loss_rows_reference.py new file mode 100644 index 0000000000..8f54100de2 --- /dev/null +++ b/test_support/microcosm_build/us_target_loss_rows_reference.py @@ -0,0 +1,111 @@ +"""The US rows-level target-loss formula exactly as it stood before #1729. + +A verbatim copy of the four functions ``microcosm.build.us_runtime. +target_loss_weights`` defined at ac7ab99ae (origin/main when the formula +became the shared rule ``sqrt_value_concept_budget`` of +``microcosm.calibrate.target_loss_rules``), under their original names, so +``git diff`` against that commit's module shows them unchanged. The +differential tests hold the shared rule to this copy, bit for bit. Do not +edit it; it is the "before" of a pure move. +""" + +from __future__ import annotations + +from collections.abc import Hashable, Mapping, Sequence + +import numpy as np + +US_FISCAL_TARGET_VALUE_WEIGHT_POWER = 0.5 + + +def target_loss_weights_from_rows( + values: Sequence[float], + bases: Sequence[str], + concept_budget_keys: Sequence[Hashable], + families: Sequence[str | None], + family_multipliers: Mapping[str, float] | None = None, +) -> np.ndarray: + """Steps 2-6 of the formula, over row-aligned per-target inputs. + + Returns float64 weights, row-aligned with the inputs. With at least one + row they are positive and of mean 1, given positive finite multipliers + whose products stay within float64 range (the CLI parser admits only + positive finite ones; this function, like the national helper it came + from, does not check them). + """ + + n_rows = len(values) + if not len(bases) == len(concept_budget_keys) == len(families) == n_rows: + raise ValueError( + "Target-loss inputs are not row-aligned: " + f"{n_rows} values, {len(bases)} bases, " + f"{len(concept_budget_keys)} concept keys, {len(families)} families." + ) + basis_array = np.asarray(list(bases), dtype=object) + weights = _concept_budget_weights( + _value_basis_weights(values, basis_array), concept_budget_keys + ) + unique_bases = sorted(set(basis_array.tolist())) + if not unique_bases: + return weights + basis_total = len(weights) / len(unique_bases) + for basis in unique_bases: + mask = basis_array == basis + current_total = weights[mask].sum() + if current_total > 0: + weights[mask] *= basis_total / current_total + weights = weights / weights.mean() + if not family_multipliers: + return weights + family_array = np.asarray(list(families), dtype=object) + for family, multiplier in sorted(family_multipliers.items()): + mask = family_array == family + if not mask.any(): + raise ValueError( + f"--target-family-loss-multiplier family {family!r} matches " + "no compiled target." + ) + weights[mask] *= multiplier + return weights / weights.mean() + + +def _value_basis_weights(values: Sequence[float], bases: np.ndarray) -> np.ndarray: + """Step 2: ``max(|value|, 1) ** 0.5`` over its basis mean.""" + + weights = np.ones(len(bases), dtype=np.float64) + magnitudes = np.asarray( + [max(abs(float(value)), 1.0) for value in values], + dtype=np.float64, + ) + raw_weights = magnitudes**US_FISCAL_TARGET_VALUE_WEIGHT_POWER + for basis in sorted(set(bases.tolist())): + mask = bases == basis + mean_value = raw_weights[mask].mean() + if mean_value > 0: + weights[mask] = raw_weights[mask] / mean_value + return weights + + +def _concept_budget_weights( + weights: np.ndarray, concept_budget_keys: Sequence[Hashable] +) -> np.ndarray: + """Step 3: each group sums to its largest member's weight.""" + + for indices in concept_budget_groups(concept_budget_keys): + group_weights = weights[indices] + group_total = float(group_weights.sum()) + group_budget = float(group_weights.max(initial=0.0)) + if group_total > 0 and group_budget > 0: + weights[indices] *= group_budget / group_total + return weights + + +def concept_budget_groups( + concept_budget_keys: Sequence[Hashable], +) -> list[list[int]]: + """Row indices sharing each concept-budget key, in first-row order.""" + + group_indices: dict[Hashable, list[int]] = {} + for index, key in enumerate(concept_budget_keys): + group_indices.setdefault(key, []).append(index) + return list(group_indices.values()) diff --git a/tools/build_us_acs_local_release.py b/tools/build_us_acs_local_release.py index 732c4372a3..5ee1c236fb 100644 --- a/tools/build_us_acs_local_release.py +++ b/tools/build_us_acs_local_release.py @@ -336,6 +336,28 @@ #: so parsing arguments never imports torch; a test pins them equal. L2_BASIS_CHOICES = ("chi_square", "record") MASS_PARAMETRIZATION_CHOICES = ("projection", "softmax") +#: The kernel's ``l2_anchor`` presets (``microcosm.calibrate.calibrate``): the +#: weights the ``--l2-lambda`` penalty pulls toward. ``initial`` is each +#: record's own starting weight and what every solve has used; ``uniform`` is +#: the mean starting weight. With ``--l2-anchor-weights`` the anchor is the +#: vector in that file and ``--l2-anchor`` names it (microcosm#1729). +L2_ANCHOR_INITIAL = "initial" +L2_ANCHOR_PRESETS = (L2_ANCHOR_INITIAL, "uniform") +#: What ``--max-weight-ratio`` multiplies for each household (microcosm#1729): +#: the declared reference of the weight bound. ``own`` is the household's own +#: starting weight, the bound every solve has used. The others are shared +#: weights (``microcosm.calibrate.weight_bound.weight_bound_reference``): the +#: mean starting weight, or the mean starting weight of the household's state +#: or district, so that a donor row, which starts about 27 times heavier than +#: an ACS row, gets no larger a bound than the ACS rows beside it. +WEIGHT_BOUND_OWN = "own" +#: Reference name -> (shared reference kind, household column of its groups). +WEIGHT_BOUND_REFERENCES = { + WEIGHT_BOUND_OWN: ("own", None), + "mean": ("mean", None), + "state_mean": ("group_mean", "state_fips"), + "district_mean": ("group_mean", "congressional_district_geoid"), +} #: The penalty settings every solve had before they were options: a solver #: stamp or summary that lacks them was solved with these. HISTORICAL_PENALTY = { @@ -2567,11 +2589,22 @@ def _verify_run_identity(args, *, require: bool = True) -> dict: SOLVER_LEARNING_RATE = 0.02 SOLVER_MASS = "conserve" -# Starting values from microcosm#1377's county pilot. The calibrator accepts -# only one scalar loss cap, so these apply to the joint run, not county rows -# individually. Ordinary ACS-local builds retain their historical settings. +# Starting values from microcosm#1377's county pilot. By default they apply to +# the joint run, not county rows individually. Ordinary ACS-local builds +# retain their historical settings. COUNTY_TARGET_LOSS_CAP = 10.0 COUNTY_MAX_WEIGHT_RATIO = 5.0 +#: Which rows the county profile's loss cap applies to (microcosm#1729). +#: ``run`` (default) is every row of a county run, as every county build has +#: solved. ``county_rows`` is the county rows only: the state and district +#: rows keep ``--target-loss-cap``, so county rows joining the solve do not +#: change their cap. The weight ratio is a bound on records, not on targets, +#: so it stays one number for the run under both. +COUNTY_CAP_SCOPE_RUN = "run" +COUNTY_CAP_SCOPE_COUNTY_ROWS = "county_rows" +COUNTY_CAP_SCOPES = (COUNTY_CAP_SCOPE_RUN, COUNTY_CAP_SCOPE_COUNTY_ROWS) +#: The geography level of a county row, as ``target_geography_level`` reads it. +COUNTY_LEVEL = "county" def _apply_county_solver_profile(args, *, identity=None) -> None: @@ -2592,26 +2625,36 @@ def _apply_county_solver_profile(args, *, identity=None) -> None: county_requested = "county" in {item.strip() for item in geographies.split(",")} county_requested |= soi_mode == SOI_MODE_STATE_COUNTY args.county_solver_profile = None + # Set only under the county_rows scope: the cap of the county rows, while + # args.target_loss_cap stays the cap of every other row. + args.county_rows_target_loss_cap = None if county_requested: - args.target_loss_cap = getattr( - args, "county_target_loss_cap", COUNTY_TARGET_LOSS_CAP - ) + county_cap = getattr(args, "county_target_loss_cap", COUNTY_TARGET_LOSS_CAP) + scope = getattr(args, "county_target_loss_cap_scope", COUNTY_CAP_SCOPE_RUN) + if scope == COUNTY_CAP_SCOPE_COUNTY_ROWS: + args.county_rows_target_loss_cap = county_cap + else: + args.target_loss_cap = county_cap args.max_weight_ratio = getattr( args, "county_max_weight_ratio", COUNTY_MAX_WEIGHT_RATIO ) args.county_solver_profile = { - "scope": "run", - "target_loss_cap": args.target_loss_cap, + "scope": scope, + "target_loss_cap": county_cap, "max_weight_ratio": args.max_weight_ratio, } -def _solver_settings(args, target_loss: dict) -> dict: +def _solver_settings(args, target_loss: dict, l2_anchor: dict | None = None) -> dict: """The calibrate-stage settings a resume or reuse must share. ``target_loss`` is the stamp :func:`release_target_loss_weights` returns, so weights calibrated under another loss weighting, or under none (a run - from before the weights), are never warm-started from. + from before the weights), are never warm-started from. ``l2_anchor`` holds + the stamps of the options a build asked for by name + (:func:`release_l2_anchor`, :func:`release_weight_bound`): ``None`` for + the defaults, which add no key, so a stamp from before the options + compares equal to a request for the defaults. """ return { @@ -2631,6 +2674,7 @@ def _solver_settings(args, target_loss: dict) -> dict: if getattr(args, "county_solver_profile", None) is not None else {} ), + **(l2_anchor or {}), } @@ -2645,8 +2689,12 @@ def release_target_loss_weights(args, train_specs) -> tuple[np.ndarray, dict]: """ multipliers = dict(args.target_family_loss_multipliers) + default_rule = loss_weighting.US_ACS_LOCAL_TARGET_WEIGHT_RULE + rule = getattr(args, "target_weight_rule", default_rule) try: - weights = county_surface.target_loss_weights(train_specs, multipliers) + weights = county_surface.target_loss_weights( + train_specs, multipliers, rule=rule + ) except ValueError as error: raise SystemExit(f"Target loss weights: {error}") from error stamp = { @@ -2661,9 +2709,214 @@ def release_target_loss_weights(args, train_specs) -> tuple[np.ndarray, dict]: [loss_weighting.target_row_name(spec) for spec in train_specs], weights ), } + if rule != default_rule: + # Only a run that asks for another declared rule records it, so the + # default stamp, and every resume that compares it, is unchanged. + stamp["weighting"] = rule + stamp["rule"] = loss_weighting.acs_local_target_weight_rule(rule).to_json() return weights, stamp +def release_l2_anchor(args, household_ids) -> tuple[dict, dict | None]: + """The L2 anchor keywords for ``calibrate``, and the stamp describing them. + + The default (``--l2-anchor initial``, no anchor weights) gives no keyword + and no stamp, so the solve and its settings are those of every release. + ``--l2-anchor uniform`` passes the preset. ``--l2-anchor-weights FILE`` + passes the vector in FILE (``.npy``, or ``.npz`` with ``weights``), one + positive weight for each checkpoint household in checkpoint order, under + the label ``--l2-anchor`` names; an ``.npz`` that also has + ``household_id`` must list the checkpoint's households. The stamp digests + the vector, so a resume refuses weights calibrated toward another anchor. + + The anchor changes only what the ``--l2-lambda`` penalty pulls toward. It + does not change the starting weights, the weight bound or the mass. + """ + + anchor = getattr(args, "l2_anchor", L2_ANCHOR_INITIAL) + path = getattr(args, "l2_anchor_weights", None) + if path is None: + if anchor == L2_ANCHOR_INITIAL: + return {}, None + return {"l2_anchor": anchor}, {"l2_anchor": anchor} + loaded = np.load(path, allow_pickle=False) + if isinstance(loaded, np.ndarray): + vector = loaded + else: + if "weights" not in loaded: + raise SystemExit(f"--l2-anchor-weights {path} has no 'weights' array.") + vector = loaded["weights"] + if "household_id" in loaded and not np.array_equal( + np.asarray(loaded["household_id"]), np.asarray(household_ids) + ): + raise SystemExit( + f"--l2-anchor-weights {path} lists other households, or another " + "order, than the checkpoint." + ) + vector = np.asarray(vector, dtype=np.float64) + if vector.shape != (len(household_ids),): + raise SystemExit( + f"--l2-anchor-weights {path} has shape {vector.shape}; the checkpoint " + f"has {len(household_ids)} households." + ) + if not np.isfinite(vector).all() or (vector <= 0).any(): + raise SystemExit( + f"--l2-anchor-weights {path} must be finite and strictly positive." + ) + return ( + {"l2_anchor": anchor, "l2_anchor_weights": vector}, + {"l2_anchor": anchor, "l2_anchor_weights_sha256": _weights_digest(vector)}, + ) + + +def release_weight_bound(args, households, design_weights) -> tuple[dict, dict | None]: + """The weight-bound keywords for ``calibrate``, and the stamp describing them. + + The default (``--weight-bound-reference own``) gives no keyword and no + stamp: ``--max-weight-ratio`` multiplies each household's own starting + weight, as in every release. Any other reference passes the shared + reference vector as ``max_weight_reference``, so the bound is + ``--max-weight-ratio`` times that reference. + """ + + name = getattr(args, "weight_bound_reference", WEIGHT_BOUND_OWN) + if name == WEIGHT_BOUND_OWN: + return {}, None + from microcosm.calibrate.weight_bound import weight_bound_reference + + kind, column = WEIGHT_BOUND_REFERENCES[name] + if column is not None and column not in households.columns: + raise SystemExit( + f"--weight-bound-reference {name} needs the household column " + f"{column}, which the checkpoint does not have." + ) + try: + reference = weight_bound_reference( + design_weights, + kind, + groups=None if column is None else households[column].to_numpy(), + ) + except ValueError as error: + raise SystemExit(f"--weight-bound-reference {name}: {error}") from error + admitted = float(args.max_weight_ratio * reference.sum()) + total = float(np.sum(design_weights)) + if admitted < total * (1.0 - 1e-12): + # The solver refuses the same bounds; say so before the solve starts. + raise SystemExit( + f"--weight-bound-reference {name} with --max-weight-ratio " + f"{args.max_weight_ratio!r} admits a total weight of {admitted:,.0f}, " + f"below the {total:,.0f} the solve conserves. Raise --max-weight-ratio." + ) + return {"max_weight_reference": reference}, {"weight_bound_reference": name} + + +def release_target_loss_caps(args, target_set, train_specs, loss_weights): + """The solver's loss cap, weights and scales, and the caps it stands for. + + One number for the run unless the county profile's cap applies to the + county rows only (``--county-target-loss-cap-scope county_rows``). Then + each row has its own cap, declared by level through the shared + ``target_loss_caps``, and the solver gets the one-cap loss that equals it + (``single_cap_equivalent``): the same loss value, row contributions and + gradient, with the cap still one number. + + Returns a mapping: ``cap``, ``weights`` and ``scales`` go to + ``calibrate`` (``scales`` is ``None`` for the default scales); ``receipt`` + is ``None`` unless row caps are declared. With row caps, ``row_caps`` and + ``row_scales`` are the declared cap and scale of each row, which + :func:`target_loss_caps_receipt` reads after the solve. + """ + + county_cap = getattr(args, "county_rows_target_loss_cap", None) + if county_cap is None: + return { + "cap": args.target_loss_cap, + "weights": loss_weights, + "scales": None, + "receipt": None, + } + from microcosm.calibrate import default_target_loss_scales + from microcosm.calibrate.target_loss_rules import ( + single_cap_equivalent, + target_loss_caps, + ) + + try: + caps = target_loss_caps( + args.target_loss_cap, + levels=[ + loss_weighting.target_geography_level(spec) for spec in train_specs + ], + by_level={COUNTY_LEVEL: county_cap}, + ) + except ValueError as error: + raise SystemExit(f"Target loss caps: {error}") from error + row_scales = default_target_loss_scales( + np.asarray([target.value for target in target_set], dtype=np.float64) + ) + equivalent = single_cap_equivalent(caps, weights=loss_weights, scales=row_scales) + return { + "cap": equivalent.cap, + "weights": equivalent.weights, + "scales": equivalent.scales, + "row_caps": equivalent.caps, + "row_scales": row_scales, + "receipt": { + "default": float(args.target_loss_cap), + "by_level": {COUNTY_LEVEL: float(county_cap)}, + **equivalent.receipt(), + }, + } + + +def target_loss_caps_receipt(solver_loss: dict, result) -> dict | None: + """What a solve under row caps records, for the summary and the diagnostics. + + ``None`` when the run has one cap. Otherwise the declared caps (the + default, the cap of each level, the rows at each cap, and by name each row + that is not at the default) and the past-cap census against each row's own + cap (``row_cap_census``). + + ``calibration_diagnostics.json`` needs this block. Its own + ``past_cap_census`` and the ``target_loss_scale`` and + ``target_loss_weight`` of each of its targets come from the solver, which + ran the equivalent one-cap loss: they read every row against + ``equivalent_cap`` on transformed scales, not against the row's own cap. + """ + + if solver_loss["receipt"] is None: + return None + from microcosm.calibrate.target_loss_rules import row_cap_census + + names = [diagnostic.name for diagnostic in result.diagnostics] + caps = solver_loss["row_caps"] + default = solver_loss["receipt"]["default"] + return { + **solver_loss["receipt"], + "rows_not_at_default": { + name: float(cap) + for name, cap in zip(names, caps, strict=True) + if cap != default + }, + "past_cap_census": row_cap_census( + names, + [diagnostic.target for diagnostic in result.diagnostics], + [diagnostic.initial_estimate for diagnostic in result.diagnostics], + [diagnostic.final_estimate for diagnostic in result.diagnostics], + scales=solver_loss["row_scales"], + caps=caps, + ), + "how_to_read_the_diagnostics": ( + "The solver ran the one-cap loss that equals these row caps. In " + "calibration_diagnostics.json the top-level past_cap_census and " + "each target's target_loss_scale and target_loss_weight are the " + "solver's: they read every row against equivalent_cap on " + "transformed scales. For a row's own cap and the census against " + "it, read this block." + ), + } + + def _stamped_settings(settings: dict | None) -> dict | None: """A recorded solver stamp, with the penalty keys it predates filled in. @@ -2910,6 +3163,9 @@ def calibrate_surface( on_batch=None, l2_basis: str = HISTORICAL_PENALTY["l2_basis"], mass_parametrization: str = HISTORICAL_PENALTY["mass_parametrization"], + target_loss_scales: np.ndarray | None = None, + l2_anchor: dict | None = None, + weight_bound: dict | None = None, ): """Epoch-batched warm-start calibration of ``target_set``. @@ -2920,10 +3176,19 @@ def calibrate_surface( row-aligned with ``target_set``; ``do_calibrate`` always passes the release weights (:func:`release_target_loss_weights`), and ``None`` (equal weights) is for harnesses. Returns ``(result, epochs_done)``. + + An option added after the first release (``target_loss_scales``, the + ``l2_anchor`` keywords :func:`release_l2_anchor` returns and the + ``weight_bound`` keywords :func:`release_weight_bound` returns) reaches + ``calibrate`` only when a caller sets it, so a run that sets none makes + the call every release has made. """ from microcosm.calibrate import calibrate + optional = {**(l2_anchor or {}), **(weight_bound or {})} + if target_loss_scales is not None: + optional["target_loss_scales"] = target_loss_scales batch = epoch_batch if epoch_batch > 0 else epochs result = None while done < epochs: @@ -2945,6 +3210,7 @@ def calibrate_surface( seed=seed, target_loss_weights=target_loss_weights, warm_start_weights=warm, + **optional, ) done += this_batch warm = result.weights.copy() @@ -2986,6 +3252,7 @@ def calibration_evidence( target_loss_cap: float, checkpoint_dir: Path | None = None, identity: dict | None = None, + county_target_loss_cap: float | None = None, ) -> dict: """The sparse-surface evidence the calibration summary adds. @@ -2993,7 +3260,9 @@ def calibration_evidence( and distinct households with household-weight share by spine, at the design and the calibrated weights. With the checkpoint directory and run identity, a county run also scores its held-out ACS validation families - (microcosm#922), which never reach the loss. + (microcosm#922), which never reach the loss. ``county_target_loss_cap`` + is the cap the county evidence is scored at when the county rows have a + cap of their own; ``None`` scores it at ``target_loss_cap``. """ origin = _origin_columns(frame) @@ -3022,7 +3291,9 @@ def calibration_evidence( matrix, design_weights, weights, - target_loss_cap, + target_loss_cap + if county_target_loss_cap is None + else county_target_loss_cap, checkpoint_dir=checkpoint_dir, identity=identity, ), @@ -3066,6 +3337,7 @@ def do_calibrate(args) -> None: "specs, so their loss weights would attach to the wrong targets." ) loss_weights, target_loss = release_target_loss_weights(args, train_specs) + solver_loss = release_target_loss_caps(args, target_set, train_specs, loss_weights) loss_distribution = loss_weighting.target_loss_weight_distribution( train_specs, loss_weights, @@ -3086,7 +3358,14 @@ def do_calibrate(args) -> None: ) stamp = _run_identity_digest(identity) - settings = _solver_settings(args, target_loss) + l2_anchor, l2_anchor_stamp = release_l2_anchor( + args, frame.table("household")["household_id"].to_numpy() + ) + weight_bound, weight_bound_stamp = release_weight_bound( + args, frame.table("household"), design_weights + ) + named_options = {**(l2_anchor_stamp or {}), **(weight_bound_stamp or {})} + settings = _solver_settings(args, target_loss, named_options or None) resume_npz = args.checkpoint_dir / "weights_latest.npz" warm, done = None, 0 if args.resume and resume_npz.exists(): @@ -3138,6 +3417,7 @@ def do_calibrate(args) -> None: target_loss_cap=args.target_loss_cap, checkpoint_dir=args.checkpoint_dir, identity=identity, + county_target_loss_cap=args.county_rows_target_loss_cap, ) stale = sorted( key @@ -3202,12 +3482,15 @@ def save(weights: np.ndarray, epochs_done: int) -> None: epochs=args.epochs, epoch_batch=args.epoch_batch, max_weight_ratio=args.max_weight_ratio, - target_loss_cap=args.target_loss_cap, + target_loss_cap=solver_loss["cap"], l2_lambda=args.l2_lambda, l2_basis=args.l2_basis, mass_parametrization=args.mass_parametrization, seed=args.seed, - target_loss_weights=loss_weights, + target_loss_weights=solver_loss["weights"], + target_loss_scales=solver_loss["scales"], + l2_anchor=l2_anchor, + weight_bound=weight_bound, warm=warm, done=done, on_batch=save, @@ -3220,6 +3503,7 @@ def save(weights: np.ndarray, epochs_done: int) -> None: f"(e.g. {skipped[:5]}); the surface silently shrank. Fix the " "measures or the targets before shipping." ) + caps_receipt = target_loss_caps_receipt(solver_loss, result) summary = { "run_identity_sha256": stamp, "solver_settings": settings, @@ -3235,10 +3519,21 @@ def save(weights: np.ndarray, epochs_done: int) -> None: "epochs": args.epochs, "epoch_batch": args.epoch_batch, "max_weight_ratio": args.max_weight_ratio, - "target_loss_cap": args.target_loss_cap, + # The solver's cap. With a cap for each row it is the equivalent + # single cap, the largest value the loss can take; target_loss_caps + # then records the declared row caps. + "target_loss_cap": solver_loss["cap"], + **({"target_loss_caps": caps_receipt} if caps_receipt is not None else {}), "target_loss": {**target_loss, "distribution": loss_distribution}, "l2_lambda": args.l2_lambda, "l2_basis": args.l2_basis, + **named_options, + # Only a solve under a declared reference records its bound. + **( + {"weight_bound": result.options["weight_bound"]} + if "weight_bound" in result.options + else {} + ), "mass_parametrization": args.mass_parametrization, "seed": args.seed, "initial_loss": round(result.initial_loss, 6), @@ -3266,6 +3561,7 @@ def save(weights: np.ndarray, epochs_done: int) -> None: target_loss_cap=args.target_loss_cap, checkpoint_dir=args.checkpoint_dir, identity=identity, + county_target_loss_cap=args.county_rows_target_loss_cap, ), "total_wall_seconds": round(time.time() - started, 1), "peak_rss_gb": round(rss(), 3), @@ -3301,7 +3597,10 @@ def save(weights: np.ndarray, epochs_done: int) -> None: # release names them, plus the ACS local row mapping and digest. "target_loss_weighting": target_loss["weighting"], "target_loss_family_multipliers": target_loss["family_multipliers"] or None, - "target_loss_cap": args.target_loss_cap, + "target_loss_cap": solver_loss["cap"], + # Only a solve under row caps: the caps and the census against + # them, so that this file says how to read its own census. + **({"target_loss_caps": caps_receipt} if caps_receipt is not None else {}), "target_loss_row_mapping": target_loss["row_mapping"], "target_loss_weights_sha256": target_loss["weights_sha256"], "target_loss_distribution": loss_distribution, @@ -3599,7 +3898,7 @@ def spine_composition(households: pd.DataFrame, persons: pd.DataFrame, weights): spine_person_weight / spine_weight if spine_weight else 0.0 ), } - ess = float(weights.sum() ** 2 / (weights**2).sum()) if len(weights) else 0.0 + ess = cd_surface.kish_ess(weights) composition["_all"] = { "households": int(len(weights)), "household_weight": total_weight, @@ -4895,6 +5194,9 @@ def state_cd_reviewed_limitations(materialize_rss: dict) -> list[dict]: #: 18.5 penalized. DISTRICT_ESS_FLOOR = 15.0 DISTRICT_ESS_GATE = "district_ess_collapse" +#: The geography level the district gate declares to the shared area support +#: gate (``microcosm.build.area_support``). +DISTRICT_ESS_LEVEL = "congressional_district" def _district_ess(weight_summary) -> dict[str, float] | None: @@ -4986,29 +5288,63 @@ def district_ess_collapse_gate( "failures": failures, } + # The floors, the comparisons and the verdict are the shared area support + # gate's (microcosm#1729): this function declares the district floors to + # it and lays its answer out as the release's gate entry. A floor of 0 is + # a floor that is not declared. + from microcosm.build.area_support import ( + area_support_floor_table, + area_support_gate, + ) + + districts = sorted(design) + floors = { + "minimum_effective_sample_size": absolute_floor or None, + "minimum_effective_sample_size_ratio": relative_floor or None, + } + support = pd.DataFrame( + { + "geography_level": DISTRICT_ESS_LEVEL, + "area_code": districts, + "effective_sample_size": [calibrated[district] for district in districts], + "starting_effective_sample_size": [ + design[district] for district in districts + ], + } + ) + verdict = area_support_gate( + support, + area_roster={DISTRICT_ESS_LEVEL: districts}, + geography_levels=(DISTRICT_ESS_LEVEL,), + **floors, + ) + checked = area_support_floor_table(support, **floors) rows = [ { - "district": district, - "calibrated_ess": calibrated[district], - "design_ess": design[district], + "district": row.area_code, + "calibrated_ess": float(row.effective_sample_size), + "design_ess": float(row.starting_effective_sample_size), "ratio": ( - calibrated[district] / design[district] - if design[district] > 0 - else None + None + if np.isnan(row.effective_sample_size_ratio) + else float(row.effective_sample_size_ratio) ), } - for district in sorted(design) + for row in checked.itertuples(index=False) ] + + def flagged(floor: str) -> list[dict]: + column = f"below_{floor}" + if column not in checked.columns: + return [] + return [row for row, below in zip(rows, checked[column], strict=True) if below] + collapsed = sorted( - ( - row - for row in rows - if row["calibrated_ess"] < relative_floor * row["design_ess"] - ), + flagged("minimum_effective_sample_size_ratio"), key=lambda row: (row["ratio"], row["district"]), ) below_floor = sorted( - (row for row in rows if row["calibrated_ess"] < absolute_floor), + flagged("minimum_effective_sample_size"), key=lambda row: (row["calibrated_ess"], row["district"]), ) smallest = min(rows, key=lambda row: (row["calibrated_ess"], row["district"])) @@ -5016,7 +5352,7 @@ def district_ess_collapse_gate( lowest = ( min(rated, key=lambda row: (row["ratio"], row["district"])) if rated else None ) - criteria_met = not collapsed and not below_floor + criteria_met = verdict.passed return { **gate, "passed": criteria_met or not blocking, @@ -6803,6 +7139,28 @@ def _version(package: str) -> str: f" --county-target-loss-cap {float(county_profile['target_loss_cap'])!r}" f" --county-max-weight-ratio {float(county_profile['max_weight_ratio'])!r}" ) + if county_profile.get("scope", COUNTY_CAP_SCOPE_RUN) != COUNTY_CAP_SCOPE_RUN: + refresh_recipe["release"] += ( + f" --county-target-loss-cap-scope {county_profile['scope']}" + ) + # Options a build asked for by name are named in the recipe; a default + # build records none of them and its recipe is unchanged. + recorded_settings = diagnostics.get("solver_settings") or {} + if (recorded_settings.get("target_loss") or {}).get("rule") is not None: + refresh_recipe["release"] += ( + f" --target-weight-rule {recorded_settings['target_loss']['weighting']}" + ) + if recorded_settings.get("weight_bound_reference") is not None: + refresh_recipe["release"] += ( + f" --weight-bound-reference {recorded_settings['weight_bound_reference']}" + ) + if recorded_settings.get("l2_anchor") is not None: + refresh_recipe["release"] += f" --l2-anchor {recorded_settings['l2_anchor']}" + if recorded_settings.get("l2_anchor_weights_sha256") is not None: + refresh_recipe["release"] += ( + " --l2-anchor-weights " + ) refresh_recipe["release"] += district_ess_refresh_flags( (gate_report.get("gates") or {}).get(DISTRICT_ESS_GATE) ) @@ -7146,6 +7504,21 @@ def _parse_args(argv: list[str] | None = None) -> argparse.Namespace: parser.add_argument("--epochs", type=int, default=800) parser.add_argument("--epoch-batch", type=int, default=400) parser.add_argument("--max-weight-ratio", type=float, default=5.0) + parser.add_argument( + "--weight-bound-reference", + choices=sorted(WEIGHT_BOUND_REFERENCES), + default=WEIGHT_BOUND_OWN, + help=( + "What --max-weight-ratio multiplies for each household. 'own' " + "(default) is its own starting weight, as every solve has used. " + "'mean', 'state_mean' and 'district_mean' are one shared weight: " + "the mean starting weight overall, or of the household's state or " + "district, so a row that starts heavier gets no larger a bound. A " + "row that starts above the bound is pulled down to it before the " + "solve, which moves starting mass off the heavy rows; it changes " + "the weights (microcosm.calibrate.weight_bound)." + ), + ) parser.add_argument("--target-loss-cap", type=float, default=1.0) parser.add_argument( "--county-target-loss-cap", @@ -7156,6 +7529,17 @@ def _parse_args(argv: list[str] | None = None) -> argparse.Namespace: "overrides --target-loss-cap only for county builds." ), ) + parser.add_argument( + "--county-target-loss-cap-scope", + choices=COUNTY_CAP_SCOPES, + default=COUNTY_CAP_SCOPE_RUN, + help=( + "Which rows --county-target-loss-cap applies to in a county build. " + "'run' (default) is every row, as every county build has solved. " + "'county_rows' is the county rows only: state and district rows " + "keep --target-loss-cap. It changes the weights of a county build." + ), + ) parser.add_argument( "--county-max-weight-ratio", type=float, @@ -7178,6 +7562,20 @@ def _parse_args(argv: list[str] | None = None) -> argparse.Namespace: "calibration summary and the diagnostics." ), ) + parser.add_argument( + "--target-weight-rule", + choices=sorted(loss_weighting.US_ACS_LOCAL_TARGET_WEIGHT_RULES), + default=loss_weighting.US_ACS_LOCAL_TARGET_WEIGHT_RULE, + help=( + "The declared target loss-weight rule (microcosm.calibrate." + "target_loss_rules). 'concept_budget' (default) is the national " + "release's formula, which every build has used. " + "'level_family_equal_sqrt_count' gives each geography level one " + "equal share of the loss and each family one equal share of its " + "level; it changes the weights. Recorded in the solver settings " + "when it is not the default." + ), + ) parser.add_argument("--l2-lambda", type=float, default=0.0) parser.add_argument( "--l2-basis", @@ -7191,6 +7589,30 @@ def _parse_args(argv: list[str] | None = None) -> argparse.Namespace: "design weights d themselves." ), ) + parser.add_argument( + "--l2-anchor", + default=L2_ANCHOR_INITIAL, + help=( + "What the --l2-lambda penalty pulls toward (microcosm.calibrate " + "l2_anchor). 'initial' (default) is each record's own starting " + "weight; 'uniform' is the mean starting weight. With " + "--l2-anchor-weights it is the name of that vector, for the " + "record (for example 'household_proportional'). It has no effect " + "at --l2-lambda 0." + ), + ) + parser.add_argument( + "--l2-anchor-weights", + type=Path, + default=None, + help=( + "A declared anchor for the --l2-lambda penalty: a .npy vector, or " + "a .npz with 'weights' (and optionally 'household_id'), one " + "positive weight per checkpoint household in checkpoint order. " + "The penalty then pulls toward this design; the starting weights " + "and the weight bound do not change. Needs a name in --l2-anchor." + ), + ) parser.add_argument( "--mass-parametrization", choices=MASS_PARAMETRIZATION_CHOICES, @@ -7338,6 +7760,18 @@ def _parse_args(argv: list[str] | None = None) -> argparse.Namespace: "--cd-holdout-fraction must be in " f"[0, {cd_surface.MAX_CD_HOLDOUT_FRACTION}]." ) + if args.l2_anchor_weights is None and args.l2_anchor not in L2_ANCHOR_PRESETS: + parser.error( + f"--l2-anchor must be one of {L2_ANCHOR_PRESETS} unless " + "--l2-anchor-weights gives the vector it names." + ) + if args.l2_anchor_weights is not None and ( + args.l2_anchor in L2_ANCHOR_PRESETS or not args.l2_anchor.strip() + ): + parser.error( + "--l2-anchor-weights needs a name for the vector in --l2-anchor " + f"(not one of {L2_ANCHOR_PRESETS})." + ) if not 0.0 <= args.district_ess_relative_floor <= 1.0: parser.error("--district-ess-relative-floor must be in [0, 1].") if not (np.isfinite(args.district_ess_floor) and args.district_ess_floor >= 0.0): diff --git a/tools/spine_target_shares.py b/tools/spine_target_shares.py new file mode 100644 index 0000000000..5cd3157ab2 --- /dev/null +++ b/tools/spine_target_shares.py @@ -0,0 +1,286 @@ +"""Report which rows carry each calibration target, from saved inputs. + +For each target: the share of its weighted total that each set of rows +("spine") carries, against that spine's share of the weight among the records +the target is about. A target one spine carries almost alone pulls weight +onto that spine and lowers the effective sample size +(``microcosm.calibrate.spine_target_shares``; microcosm#1729). + +The tool reads saved calibration inputs. It runs no engine, solves nothing +and writes only its report, so it needs no build. + +Two kinds of input: + +``--us-acs-local-checkpoint DIR`` + The checkpoint directory of ``tools/build_us_acs_local_release.py`` + (``--stage materialize`` wrote it). Reads the target matrix, the target + roles and the lean frame. Reports at the design weights, and at the + calibrated weights when ``weights_latest.npz`` is there. A target's scope + is its own state, district or county. + +``--matrix M.npz --weights W --spines S`` + Any pooled build: a SciPy sparse matrix saved with ``scipy.sparse. + save_npz`` (targets x records), a weight vector and each record's spine + label (``.npy``, or ``.npz`` with the key ``--weights-key`` / + ``--spines-key``). ``--names N.json`` names the targets. + +Examples: + + uv run python tools/spine_target_shares.py \\ + --us-acs-local-checkpoint /checkpoints --out shares.json + + uv run python tools/spine_target_shares.py \\ + --matrix problem.npz --weights weights.npy --spines spines.npy + +``--spine NAME`` prints the targets that spine over-carries most. ``--top`` +sets how many. ``--minimum-carriers N`` withholds a target that a spine +carries with fewer than ``N`` distinct carriers: pass the disclosure floor +for a build on licensed microdata. +""" + +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path + +import numpy as np + +#: The household columns of the ACS local lean frame. +US_SPINE_COLUMN = "household_spine" +US_SOURCE_COLUMN = "household_source_id" +#: Scope kind -> (household column, role key, digits of the code). +US_SCOPE_COLUMNS = { + "state": ("state_fips", "state_fips", 2), + "congressional_district": ( + "congressional_district_geoid", + "congressional_district_geoid", + 4, + ), + "county": ("county_fips", "county_fips", 5), +} + + +def _padded(values, digits: int) -> np.ndarray: + """Geography codes as zero-padded strings (``6`` and ``"06"`` are one).""" + + import pandas as pd + + numbers = pd.to_numeric(pd.Series(np.asarray(values)), errors="coerce") + return np.asarray( + [ + "" if np.isnan(number) else f"{int(number):0{digits}d}" + for number in numbers.to_numpy(dtype=np.float64) + ], + dtype=object, + ) + + +def us_acs_local_inputs(households, roles) -> dict: + """The spine, source, scope and group inputs of an ACS local checkpoint. + + ``households`` is the lean frame's household table and ``roles`` the + ``target_roles.json`` records, row-aligned with the target matrix. A + target's scope is the state, district or county its role names; a role + that names none of them is scoped to every record. + """ + + if US_SPINE_COLUMN not in households.columns: + raise SystemExit( + f"The lean frame has no {US_SPINE_COLUMN} column, so its rows " + "cannot be told apart by spine." + ) + # A county run records the household column its county rows bind. + county_column = next( + (role["county_column"] for role in roles if role.get("county_column")), + US_SCOPE_COLUMNS["county"][0], + ) + scope_codes = {} + for kind, (column, _key, digits) in US_SCOPE_COLUMNS.items(): + column = county_column if kind == "county" else column + if column in households.columns: + scope_codes[kind] = _padded(households[column].to_numpy(), digits) + scopes = [] + for role in roles: + kind = role.get("geography_level") + scope = None + if kind in scope_codes: + _column, key, digits = US_SCOPE_COLUMNS[kind] + code = role.get(key) + if code not in (None, ""): + scope = (kind, str(_padded([code], digits)[0])) + scopes.append(scope) + spine = households[US_SPINE_COLUMN].astype(str).to_numpy() + return { + "spines": spine, + "source_ids": ( + households[US_SOURCE_COLUMN].to_numpy() + if US_SOURCE_COLUMN in households.columns + else None + ), + "scope_codes": scope_codes, + "target_scopes": scopes, + "names": [role["name"] for role in roles], + "groups": [ + f"{role.get('family')}/{role.get('geography_level')}" for role in roles + ], + "roles": [role.get("role") for role in roles], + } + + +def _load_us_acs_local(checkpoint_dir: Path) -> tuple: + """``(matrix, inputs, weights by label)`` of an ACS local checkpoint.""" + + sys.path.insert(0, str(Path(__file__).resolve().parent)) + import build_us_acs_local_release as release + + frame, design_weights, _registry, roles, matrix = release.load_checkpoint_surface( + checkpoint_dir + ) + inputs = us_acs_local_inputs(frame.table("household"), roles) + weights = {"design": np.asarray(design_weights, dtype=np.float64)} + saved = checkpoint_dir / "weights_latest.npz" + if saved.exists(): + calibrated = np.load(saved)["weights"] + if len(calibrated) == matrix.shape[1]: + weights["calibrated"] = np.asarray(calibrated, dtype=np.float64) + return matrix, inputs, weights + + +def _load_vector(path: Path, key: str) -> np.ndarray: + loaded = np.load(path, allow_pickle=False) + if isinstance(loaded, np.ndarray): + return loaded + if key not in loaded: + raise SystemExit(f"{path} has no array {key!r} (it has {sorted(loaded)}).") + return loaded[key] + + +def _load_generic(args) -> tuple: + from scipy import sparse + + matrix = sparse.load_npz(args.matrix) + inputs = { + "spines": _load_vector(args.spines, args.spines_key).astype(str), + "source_ids": None, + "scope_codes": None, + "target_scopes": None, + "names": ( + None if args.names is None else json.loads(Path(args.names).read_text()) + ), + "groups": None, + "roles": None, + } + weights = {"weights": _load_vector(args.weights, args.weights_key)} + return matrix, inputs, weights + + +def build_report(matrix, inputs, weights, *, minimum_carriers=None) -> dict: + """The report for each weight vector, with group summaries when known.""" + + from microcosm.calibrate.spine_target_shares import spine_target_shares + + report: dict[str, object] = {} + for label, vector in weights.items(): + shares = spine_target_shares( + matrix, + vector, + inputs["spines"], + names=inputs["names"], + target_scopes=inputs["target_scopes"], + scope_codes=inputs["scope_codes"], + source_ids=inputs["source_ids"], + minimum_carriers=minimum_carriers, + ) + entry = shares.report() + if inputs["groups"] is not None: + entry["by_family_and_level"] = shares.summary(inputs["groups"]) + if inputs["roles"] is not None: + for row, role in zip(entry["targets"], inputs["roles"], strict=True): + row["role"] = role + report[label] = entry + return report + + +def _print_ranking(report: dict, spine: str, top: int) -> None: + for label, entry in report.items(): + if spine not in entry["spines"]: + raise SystemExit( + f"--spine must be one of {entry['spines']}, got {spine!r}." + ) + rows = [ + row + for row in entry["targets"] + if "share" in row and row["excess"][spine] is not None + ] + rows.sort(key=lambda row: -row["excess"][spine]) + mass = entry["overall_mass_share"][spine] + print(f"[{label}] {spine} holds {mass:.1%} of the weight; it over-carries:") + for row in rows[:top]: + print( + f" {row['share'][spine]:7.1%} of the target against " + f"{row['mass_share'][spine]:6.1%} of the mass {row['name']}" + ) + + +def _parse_args(argv: list[str] | None = None) -> argparse.Namespace: + parser = argparse.ArgumentParser( + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument("--us-acs-local-checkpoint", type=Path) + parser.add_argument("--matrix", type=Path) + parser.add_argument("--weights", type=Path) + parser.add_argument("--weights-key", default="weights") + parser.add_argument("--spines", type=Path) + parser.add_argument("--spines-key", default="spines") + parser.add_argument("--names", type=Path) + parser.add_argument("--minimum-carriers", type=int, default=None) + parser.add_argument("--spine", help="Print the targets this spine over-carries.") + parser.add_argument("--top", type=int, default=25) + parser.add_argument("--out", type=Path, help="Write the full report as JSON.") + args = parser.parse_args(argv) + generic = (args.matrix, args.weights, args.spines) + if args.us_acs_local_checkpoint is not None: + if any(value is not None for value in generic): + parser.error( + "--us-acs-local-checkpoint replaces --matrix/--weights/--spines." + ) + elif any(value is None for value in generic): + parser.error( + "pass --us-acs-local-checkpoint, or all of --matrix, --weights and --spines." + ) + if args.minimum_carriers is not None and args.minimum_carriers < 1: + parser.error("--minimum-carriers must be at least 1.") + return args + + +def main(argv: list[str] | None = None) -> int: + args = _parse_args(argv) + if args.us_acs_local_checkpoint is not None: + matrix, inputs, weights = _load_us_acs_local(args.us_acs_local_checkpoint) + else: + matrix, inputs, weights = _load_generic(args) + report = build_report( + matrix, inputs, weights, minimum_carriers=args.minimum_carriers + ) + if args.out is not None: + args.out.parent.mkdir(parents=True, exist_ok=True) + args.out.write_text(json.dumps(report, indent=2, allow_nan=False)) + print(f"wrote {args.out}") + for label, entry in report.items(): + shares = ", ".join( + f"{spine} {share:.1%}" + for spine, share in entry["overall_mass_share"].items() + ) + print( + f"[{label}] {entry['n_targets']} targets; weight by spine: {shares}" + + (f"; {entry['n_withheld']} withheld" if entry["n_withheld"] else "") + ) + if args.spine is not None: + _print_ranking(report, args.spine, args.top) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/us_acs_local_cd_surface.py b/tools/us_acs_local_cd_surface.py index 74fc9f352c..e2a8e08078 100644 --- a/tools/us_acs_local_cd_surface.py +++ b/tools/us_acs_local_cd_surface.py @@ -1582,20 +1582,6 @@ def top_weight_share(weights: np.ndarray, fraction: float = 0.01) -> float: return float(np.sort(weights)[-k:].sum() / weights.sum()) -def ess_by_group(weights: np.ndarray, codes: np.ndarray) -> dict[str, float]: - """Kish ESS of the records in each group, keyed by the group code.""" - - frame = pd.DataFrame( - {"code": np.asarray(codes).astype(str), "w": np.asarray(weights, float)} - ) - frame["w2"] = frame["w"] ** 2 - sums = frame.groupby("code", sort=True)[["w", "w2"]].sum() - return { - str(code): float(row.w**2 / row.w2) if row.w2 > 0 else 0.0 - for code, row in sums.iterrows() - } - - def _distribution(values: Mapping[str, float]) -> dict[str, float | int]: array = np.asarray(list(values.values()), dtype=np.float64) if not len(array): @@ -1625,6 +1611,8 @@ def weight_origin_summary( by spine. """ + from microcosm.build.area_support import effective_sample_size_by_group + weights = np.asarray(weights, dtype=np.float64) summary: dict[str, object] = { "rows": int(len(weights)), @@ -1634,7 +1622,7 @@ def weight_origin_summary( for label, codes in (("state", state), ("district", district)): if codes is None: continue - by_group = ess_by_group(weights, codes) + by_group = effective_sample_size_by_group(weights, codes) summary[f"effective_sample_size_by_{label}"] = by_group summary[f"effective_sample_size_by_{label}_distribution"] = _distribution( by_group diff --git a/tools/us_acs_local_county_surface.py b/tools/us_acs_local_county_surface.py index 3458ef90af..502cb5086e 100644 --- a/tools/us_acs_local_county_surface.py +++ b/tools/us_acs_local_county_surface.py @@ -3227,9 +3227,19 @@ def validate(rows, bases, keys): ) -def target_loss_weights(specs, multipliers): +def target_loss_weights(specs, multipliers, *, rule=None): + """The loss weights of ``specs`` under a declared ACS local weight rule. + + ``rule`` names one of ``US_ACS_LOCAL_TARGET_WEIGHT_RULES``; ``None`` is + the release's default, the formula every build has used. + """ from microcosm.build.us_runtime import target_loss_weights as weighting return weighting.target_loss_weights( - specs, multipliers, row_mapping=loss_row_mapping(specs) + specs, + multipliers, + row_mapping=loss_row_mapping(specs), + rule=weighting.acs_local_target_weight_rule( + weighting.US_ACS_LOCAL_TARGET_WEIGHT_RULE if rule is None else rule + ), )