|
| 1 | +""" |
| 2 | +Post-solve validation of state weight files. |
| 3 | +
|
| 4 | +These tests verify that the actual state weight outputs are valid. |
| 5 | +They are skipped if weight files have not been generated yet |
| 6 | +(i.e., solve_weights --scope states has not been run). |
| 7 | +
|
| 8 | +Run after: |
| 9 | + python -m tmd.areas.prepare_targets --scope states |
| 10 | + python -m tmd.areas.solve_weights --scope states --workers 8 |
| 11 | +""" |
| 12 | + |
| 13 | +import io |
| 14 | +from pathlib import Path |
| 15 | + |
| 16 | +import numpy as np |
| 17 | +import pandas as pd |
| 18 | +import pytest |
| 19 | + |
| 20 | +from tmd.areas.create_area_weights import ( |
| 21 | + AREA_CONSTRAINT_TOL, |
| 22 | + STATE_TARGET_DIR, |
| 23 | + STATE_WEIGHT_DIR, |
| 24 | + _build_constraint_matrix, |
| 25 | + _drop_impossible_targets, |
| 26 | + _load_taxcalc_data, |
| 27 | +) |
| 28 | +from tmd.areas.prepare.constants import ALL_STATES |
| 29 | +from tmd.imputation_assumptions import TAXYEAR |
| 30 | + |
| 31 | +# Skip entire module if weight files haven't been generated |
| 32 | +_WEIGHT_FILES = list(STATE_WEIGHT_DIR.glob("*_tmd_weights.csv.gz")) |
| 33 | +pytestmark = pytest.mark.skipif( |
| 34 | + len(_WEIGHT_FILES) < 51, |
| 35 | + reason="State weight files not generated yet", |
| 36 | +) |
| 37 | + |
| 38 | +# Also need cached data files for target accuracy checks |
| 39 | +_CACHED = Path(__file__).parent.parent / "tmd" / "storage" / "output" |
| 40 | +_HAS_CACHED = (_CACHED / "tmd.csv.gz").exists() and ( |
| 41 | + _CACHED / "cached_c00100.npy" |
| 42 | +).exists() |
| 43 | + |
| 44 | + |
| 45 | +class TestStateWeightFiles: |
| 46 | + """Basic validity checks on all 51 state weight files.""" |
| 47 | + |
| 48 | + def test_all_states_have_weight_files(self): |
| 49 | + """Every state has a weight file.""" |
| 50 | + for st in ALL_STATES: |
| 51 | + wpath = STATE_WEIGHT_DIR / f"{st.lower()}_tmd_weights.csv.gz" |
| 52 | + assert wpath.exists(), f"Missing weight file for {st}" |
| 53 | + |
| 54 | + def test_all_states_have_log_files(self): |
| 55 | + """Every state has a solver log.""" |
| 56 | + for st in ALL_STATES: |
| 57 | + logpath = STATE_WEIGHT_DIR / f"{st.lower()}.log" |
| 58 | + assert logpath.exists(), f"Missing log file for {st}" |
| 59 | + |
| 60 | + def test_weight_columns(self): |
| 61 | + """Weight files have expected year columns.""" |
| 62 | + wpath = STATE_WEIGHT_DIR / "mn_tmd_weights.csv.gz" |
| 63 | + wdf = pd.read_csv(wpath) |
| 64 | + expected = [f"WT{yr}" for yr in range(TAXYEAR, 2035)] |
| 65 | + assert list(wdf.columns) == expected |
| 66 | + |
| 67 | + def test_weight_row_count(self): |
| 68 | + """Weight files have one row per TMD record.""" |
| 69 | + wpath = STATE_WEIGHT_DIR / "mn_tmd_weights.csv.gz" |
| 70 | + wdf = pd.read_csv(wpath) |
| 71 | + # Should match TMD record count (215,494 for 2022) |
| 72 | + assert len(wdf) > 200_000 |
| 73 | + |
| 74 | + @pytest.mark.parametrize( |
| 75 | + "state", |
| 76 | + [s.lower() for s in ALL_STATES], |
| 77 | + ) |
| 78 | + def test_weights_nonnegative(self, state): |
| 79 | + """All weights are non-negative.""" |
| 80 | + wpath = STATE_WEIGHT_DIR / f"{state}_tmd_weights.csv.gz" |
| 81 | + wdf = pd.read_csv(wpath) |
| 82 | + assert (wdf >= 0).all().all(), f"{state}: negative weights found" |
| 83 | + |
| 84 | + @pytest.mark.parametrize( |
| 85 | + "state", |
| 86 | + [s.lower() for s in ALL_STATES], |
| 87 | + ) |
| 88 | + def test_weights_no_nan(self, state): |
| 89 | + """No NaN or inf values in weights.""" |
| 90 | + wpath = STATE_WEIGHT_DIR / f"{state}_tmd_weights.csv.gz" |
| 91 | + wdf = pd.read_csv(wpath) |
| 92 | + assert not wdf.isna().any().any(), f"{state}: NaN values found" |
| 93 | + assert np.isfinite(wdf.values).all(), f"{state}: inf values found" |
| 94 | + |
| 95 | + @pytest.mark.parametrize( |
| 96 | + "state", |
| 97 | + [s.lower() for s in ALL_STATES], |
| 98 | + ) |
| 99 | + def test_solver_status_solved(self, state): |
| 100 | + """Solver log reports Solved status.""" |
| 101 | + logpath = STATE_WEIGHT_DIR / f"{state}.log" |
| 102 | + log_text = logpath.read_text() |
| 103 | + assert ( |
| 104 | + "Solver status: Solved" in log_text |
| 105 | + ), f"{state}: solver did not report Solved" |
| 106 | + |
| 107 | + |
| 108 | +@pytest.mark.skipif( |
| 109 | + not _HAS_CACHED, |
| 110 | + reason="Cached TMD data files not available", |
| 111 | +) |
| 112 | +class TestStateTargetAccuracy: |
| 113 | + """Verify weighted sums hit targets within tolerance.""" |
| 114 | + |
| 115 | + @pytest.fixture(scope="class") |
| 116 | + def vdf(self): |
| 117 | + """Load TMD data once for all accuracy tests.""" |
| 118 | + return _load_taxcalc_data() |
| 119 | + |
| 120 | + @pytest.mark.parametrize( |
| 121 | + "state", |
| 122 | + ["al", "ca", "mn", "ny", "tx"], |
| 123 | + ) |
| 124 | + def test_targets_hit(self, vdf, state): |
| 125 | + """Weighted sums match targets within constraint tolerance.""" |
| 126 | + out = io.StringIO() |
| 127 | + B_csc, targets, labels, pop_share = _build_constraint_matrix( |
| 128 | + state, |
| 129 | + vdf, |
| 130 | + out, |
| 131 | + target_dir=STATE_TARGET_DIR, |
| 132 | + ) |
| 133 | + B_csc, targets, labels = _drop_impossible_targets( |
| 134 | + B_csc, |
| 135 | + targets, |
| 136 | + labels, |
| 137 | + out, |
| 138 | + ) |
| 139 | + |
| 140 | + # Load weights and compute multipliers |
| 141 | + wpath = STATE_WEIGHT_DIR / f"{state}_tmd_weights.csv.gz" |
| 142 | + wdf = pd.read_csv(wpath) |
| 143 | + area_weights = wdf[f"WT{TAXYEAR}"].values |
| 144 | + w0 = pop_share * vdf["s006"].values |
| 145 | + # Avoid division by zero for zero-weight records |
| 146 | + safe_w0 = np.where(w0 > 0, w0, 1.0) |
| 147 | + x = area_weights / safe_w0 |
| 148 | + x = np.where(w0 > 0, x, 0.0) |
| 149 | + |
| 150 | + # Check target accuracy |
| 151 | + achieved = np.asarray(B_csc @ x).ravel() |
| 152 | + rel_errors = np.abs(achieved - targets) / np.maximum( |
| 153 | + np.abs(targets), 1.0 |
| 154 | + ) |
| 155 | + # Allow small margin above solver tolerance for floating-point |
| 156 | + # differences between solver internals and weight-file roundtrip |
| 157 | + eps = 1e-4 |
| 158 | + n_violated = int((rel_errors > AREA_CONSTRAINT_TOL + eps).sum()) |
| 159 | + max_err = rel_errors.max() |
| 160 | + assert n_violated == 0, ( |
| 161 | + f"{state}: {n_violated} targets violated, " |
| 162 | + f"max error = {max_err * 100:.3f}%" |
| 163 | + ) |
0 commit comments