-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathunified_matrix_builder.py
More file actions
2611 lines (2324 loc) · 96.3 KB
/
unified_matrix_builder.py
File metadata and controls
2611 lines (2324 loc) · 96.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Unified sparse matrix builder for clone-based calibration.
Builds a sparse calibration matrix for cloned+geography-assigned CPS
records. Processes clone-by-clone: for each clone, sets each
record's state_fips to its assigned value, simulates, and extracts
variable values.
Matrix shape: (n_targets, n_records * n_clones)
Column ordering: index i = clone_idx * n_records + record_idx
"""
import logging
from collections import defaultdict
from typing import Dict, List, Optional, Tuple
import numpy as np
import pandas as pd
from scipy import sparse
from sqlalchemy import create_engine, text
from policyengine_us_data.db.create_database_tables import create_or_replace_views
from policyengine_us_data.storage import STORAGE_FOLDER
from policyengine_us_data.utils.census import STATE_NAME_TO_FIPS
from policyengine_us_data.calibration.calibration_utils import (
get_calculated_variables,
apply_op,
get_geo_level,
)
logger = logging.getLogger(__name__)
_GEO_VARS = {
"state_fips",
"state_code",
"congressional_district_geoid",
}
COUNTY_DEPENDENT_VARS = {
"aca_ptc",
}
def _make_neutralize_variable_reform(variable_name: str):
from policyengine_core.reforms import Reform
class NeutralizeVariable(Reform):
def apply(self):
self.neutralize_variable(variable_name)
NeutralizeVariable.__name__ = f"Neutralize_{variable_name}"
return NeutralizeVariable
def _compute_reform_household_values(
dataset_path: str,
time_period: int,
state: int,
n_hh: int,
reform_vars: list,
baseline_income_tax: np.ndarray,
) -> dict:
"""Compute repeal-based household income tax deltas for target vars."""
from policyengine_us import Microsimulation
reform_hh = {}
if not reform_vars:
return reform_hh
state_input = np.full(n_hh, state, dtype=np.int32)
for var in reform_vars:
try:
reform_sim = Microsimulation(
dataset=dataset_path,
reform=_make_neutralize_variable_reform(var),
)
reform_sim.set_input("state_fips", time_period, state_input)
for calc_var in get_calculated_variables(reform_sim):
reform_sim.delete_arrays(calc_var)
reform_income_tax = reform_sim.calculate(
"income_tax",
time_period,
map_to="household",
).values.astype(np.float32)
reform_hh[var] = reform_income_tax - baseline_income_tax
except Exception as exc:
logger.warning(
"Cannot calculate tax expenditure '%s' for state %d: %s",
var,
state,
exc,
)
return reform_hh
def _compute_single_state(
dataset_path: str,
time_period: int,
state: int,
n_hh: int,
target_vars: list,
constraint_vars: list,
reform_vars: list,
rerandomize_takeup: bool,
affected_targets: dict,
):
"""Compute household/person/entity values for one state.
Top-level function (not a method) so it is picklable for
``ProcessPoolExecutor``.
Args:
dataset_path: Path to the base CPS h5 file.
time_period: Tax year for simulation.
state: State FIPS code.
n_hh: Number of household records.
target_vars: Target variable names (list for determinism).
constraint_vars: Constraint variable names (list).
rerandomize_takeup: Force takeup=True if True.
affected_targets: Takeup-affected target info dict.
Returns:
(state_fips, {"hh": {...}, "person": {...}, "entity": {...}})
"""
from policyengine_us import Microsimulation
from policyengine_us_data.utils.takeup import SIMPLE_TAKEUP_VARS
from policyengine_us_data.calibration.calibration_utils import (
get_calculated_variables,
)
state_sim = Microsimulation(dataset=dataset_path)
state_sim.set_input(
"state_fips",
time_period,
np.full(n_hh, state, dtype=np.int32),
)
for var in get_calculated_variables(state_sim):
state_sim.delete_arrays(var)
hh = {}
for var in target_vars:
if var.endswith("_count"):
continue
try:
hh[var] = state_sim.calculate(
var,
time_period,
map_to="household",
).values.astype(np.float32)
except Exception as exc:
logger.warning(
"Cannot calculate '%s' for state %d: %s",
var,
state,
exc,
)
person = {}
for var in constraint_vars:
try:
person[var] = state_sim.calculate(
var,
time_period,
map_to="person",
).values.astype(np.float32)
except Exception as exc:
logger.warning(
"Cannot calculate constraint '%s' for state %d: %s",
var,
state,
exc,
)
baseline_income_tax = None
reform_hh = {}
if reform_vars:
baseline_income_tax = state_sim.calculate(
"income_tax",
time_period,
map_to="household",
).values.astype(np.float32)
reform_hh = _compute_reform_household_values(
dataset_path,
time_period,
state,
n_hh,
reform_vars,
baseline_income_tax,
)
if rerandomize_takeup:
for spec in SIMPLE_TAKEUP_VARS:
entity = spec["entity"]
n_ent = len(state_sim.calculate(f"{entity}_id", map_to=entity).values)
state_sim.set_input(
spec["variable"],
time_period,
np.ones(n_ent, dtype=bool),
)
for var in get_calculated_variables(state_sim):
state_sim.delete_arrays(var)
entity_vals = {}
if rerandomize_takeup:
for tvar, info in affected_targets.items():
entity_level = info["entity"]
try:
entity_vals[tvar] = state_sim.calculate(
tvar,
time_period,
map_to=entity_level,
).values.astype(np.float32)
except Exception as exc:
logger.warning(
"Cannot calculate entity-level '%s' (map_to=%s) for state %d: %s",
tvar,
entity_level,
state,
exc,
)
entity_wf_false = {}
if rerandomize_takeup:
has_tu_target = any(
info["entity"] == "tax_unit" for info in affected_targets.values()
)
if has_tu_target:
n_tu = len(state_sim.calculate("tax_unit_id", map_to="tax_unit").values)
state_sim.set_input(
"would_file_taxes_voluntarily",
time_period,
np.zeros(n_tu, dtype=bool),
)
for var in get_calculated_variables(state_sim):
state_sim.delete_arrays(var)
for tvar, info in affected_targets.items():
if info["entity"] != "tax_unit":
continue
entity_wf_false[tvar] = state_sim.calculate(
tvar,
time_period,
map_to="tax_unit",
).values.astype(np.float32)
return (
state,
{
"hh": hh,
"person": person,
"reform_hh": reform_hh,
"entity": entity_vals,
"entity_wf_false": entity_wf_false,
},
)
def _compute_single_state_group_counties(
dataset_path: str,
time_period: int,
state_fips: int,
counties: list,
n_hh: int,
county_dep_targets: list,
rerandomize_takeup: bool,
affected_targets: dict,
):
"""Compute county-dependent values for all counties in one state.
Top-level function (not a method) so it is picklable for
``ProcessPoolExecutor``. Creates one ``Microsimulation`` per
state and reuses it across counties within that state.
Args:
dataset_path: Path to the base CPS h5 file.
time_period: Tax year for simulation.
state_fips: State FIPS code for this group.
counties: List of county FIPS strings in this state.
n_hh: Number of household records.
county_dep_targets: County-dependent target var names.
rerandomize_takeup: Force takeup=True if True.
affected_targets: Takeup-affected target info dict.
Returns:
list of (county_fips_str, {"hh": {...}, "entity": {...}})
"""
from policyengine_us import Microsimulation
from policyengine_us_data.utils.takeup import SIMPLE_TAKEUP_VARS
from policyengine_us_data.calibration.calibration_utils import (
get_calculated_variables,
)
from policyengine_us_data.calibration.block_assignment import (
get_county_enum_index_from_fips,
)
state_sim = Microsimulation(dataset=dataset_path)
state_sim.set_input(
"state_fips",
time_period,
np.full(n_hh, state_fips, dtype=np.int32),
)
original_takeup = {}
if rerandomize_takeup:
for spec in SIMPLE_TAKEUP_VARS:
entity = spec["entity"]
original_takeup[spec["variable"]] = (
entity,
state_sim.calculate(
spec["variable"],
time_period,
map_to=entity,
).values.copy(),
)
results = []
for county_fips in counties:
county_idx = get_county_enum_index_from_fips(county_fips)
state_sim.set_input(
"county",
time_period,
np.full(n_hh, county_idx, dtype=np.int32),
)
if county_fips == "06037":
state_sim.set_input(
"zip_code",
time_period,
np.full(n_hh, "90001"),
)
if rerandomize_takeup:
for vname, (ent, orig) in original_takeup.items():
state_sim.set_input(vname, time_period, orig)
for var in get_calculated_variables(state_sim):
if var not in ("county", "zip_code"):
state_sim.delete_arrays(var)
hh = {}
for var in county_dep_targets:
if var.endswith("_count"):
continue
try:
hh[var] = state_sim.calculate(
var,
time_period,
map_to="household",
).values.astype(np.float32)
except Exception as exc:
logger.warning(
"Cannot calculate '%s' for county %s: %s",
var,
county_fips,
exc,
)
if rerandomize_takeup:
for spec in SIMPLE_TAKEUP_VARS:
entity = spec["entity"]
n_ent = len(state_sim.calculate(f"{entity}_id", map_to=entity).values)
state_sim.set_input(
spec["variable"],
time_period,
np.ones(n_ent, dtype=bool),
)
for var in get_calculated_variables(state_sim):
if var not in ("county", "zip_code"):
state_sim.delete_arrays(var)
entity_vals = {}
if rerandomize_takeup:
for tvar, info in affected_targets.items():
entity_level = info["entity"]
try:
entity_vals[tvar] = state_sim.calculate(
tvar,
time_period,
map_to=entity_level,
).values.astype(np.float32)
except Exception as exc:
logger.warning(
"Cannot calculate entity-level '%s' for county %s: %s",
tvar,
county_fips,
exc,
)
results.append(
(
county_fips,
{
"hh": hh,
"entity": entity_vals,
},
)
)
return results
# ---------------------------------------------------------------
# Clone-loop parallelisation helpers (module-level for pickling)
# ---------------------------------------------------------------
_CLONE_SHARED: dict = {}
def _init_clone_worker(shared_data: dict) -> None:
"""Initialise worker process with shared read-only data.
Called once per worker at ``ProcessPoolExecutor`` startup so the
~50-200 MB payload is pickled *per worker* (not per clone).
"""
_CLONE_SHARED.update(shared_data)
def _assemble_clone_values_standalone(
state_values: dict,
clone_states: np.ndarray,
person_hh_indices: np.ndarray,
target_vars: set,
constraint_vars: set,
reform_vars: set = None,
county_values: dict = None,
clone_counties: np.ndarray = None,
county_dependent_vars: set = None,
) -> tuple:
"""Standalone clone-value assembly (no ``self``).
Identical logic to
``UnifiedMatrixBuilder._assemble_clone_values`` but usable
from a worker process.
"""
n_records = len(clone_states)
n_persons = len(person_hh_indices)
person_states = clone_states[person_hh_indices]
unique_clone_states = np.unique(clone_states)
cdv = county_dependent_vars or set()
state_masks = {int(s): clone_states == s for s in unique_clone_states}
unique_person_states = np.unique(person_states)
person_state_masks = {int(s): person_states == s for s in unique_person_states}
county_masks = {}
unique_counties = None
if clone_counties is not None and county_values:
unique_counties = np.unique(clone_counties)
county_masks = {c: clone_counties == c for c in unique_counties}
hh_vars: dict = {}
for var in target_vars:
if var.endswith("_count"):
continue
if var in cdv and county_values and clone_counties is not None:
first_county = unique_counties[0]
if var not in county_values.get(first_county, {}).get("hh", {}):
continue
arr = np.empty(n_records, dtype=np.float32)
for county in unique_counties:
mask = county_masks[county]
county_hh = county_values.get(county, {}).get("hh", {})
if var in county_hh:
arr[mask] = county_hh[var][mask]
else:
st = int(county[:2])
arr[mask] = state_values[st]["hh"][var][mask]
hh_vars[var] = arr
else:
if var not in state_values[unique_clone_states[0]]["hh"]:
continue
arr = np.empty(n_records, dtype=np.float32)
for state in unique_clone_states:
mask = state_masks[int(state)]
arr[mask] = state_values[int(state)]["hh"][var][mask]
hh_vars[var] = arr
person_vars: dict = {}
for var in constraint_vars:
if var not in state_values[unique_clone_states[0]]["person"]:
continue
arr = np.empty(n_persons, dtype=np.float32)
for state in unique_person_states:
mask = person_state_masks[int(state)]
arr[mask] = state_values[int(state)]["person"][var][mask]
person_vars[var] = arr
reform_hh_vars: dict = {}
for var in reform_vars or set():
if not any(
var in state_values[int(state)].get("reform_hh", {})
for state in unique_clone_states
):
continue
arr = np.zeros(n_records, dtype=np.float32)
for state in unique_clone_states:
mask = state_masks[int(state)]
reform_data = state_values[int(state)].get("reform_hh", {})
if var in reform_data:
arr[mask] = reform_data[var][mask]
reform_hh_vars[var] = arr
return hh_vars, person_vars, reform_hh_vars
def _evaluate_constraints_standalone(
constraints,
person_vars: dict,
entity_rel: pd.DataFrame,
household_ids: np.ndarray,
n_households: int,
) -> np.ndarray:
"""Standalone constraint evaluation (no class instance).
Evaluates person-level constraints and aggregates to
household level via .any().
"""
if not constraints:
return np.ones(n_households, dtype=bool)
n_persons = len(entity_rel)
person_mask = np.ones(n_persons, dtype=bool)
for c in constraints:
var = c["variable"]
if var not in person_vars:
logger.warning(
"Constraint var '%s' not in precomputed person_vars",
var,
)
return np.zeros(n_households, dtype=bool)
vals = person_vars[var]
person_mask &= apply_op(vals, c["operation"], c["value"])
df = entity_rel.copy()
df["satisfies"] = person_mask
hh_mask = df.groupby("household_id")["satisfies"].any()
return np.array([hh_mask.get(hid, False) for hid in household_ids])
def _calculate_target_values_standalone(
target_variable: str,
non_geo_constraints: list,
n_households: int,
hh_vars: dict,
reform_hh_vars: dict,
person_vars: dict,
entity_rel: pd.DataFrame,
household_ids: np.ndarray,
variable_entity_map: dict,
reform_id: int = 0,
) -> np.ndarray:
"""Standalone target-value calculation (no class instance).
Uses ``variable_entity_map`` dict for entity resolution
(picklable, unlike ``tax_benefit_system``).
"""
is_count = target_variable.endswith("_count")
if not is_count:
mask = _evaluate_constraints_standalone(
non_geo_constraints,
person_vars,
entity_rel,
household_ids,
n_households,
)
source_vars = reform_hh_vars if reform_id > 0 else hh_vars
vals = source_vars.get(target_variable)
if vals is None:
return np.zeros(n_households, dtype=np.float32)
return (vals * mask).astype(np.float32)
# Count target: entity-aware counting
n_persons = len(entity_rel)
person_mask = np.ones(n_persons, dtype=bool)
for c in non_geo_constraints:
var = c["variable"]
if var not in person_vars:
return np.zeros(n_households, dtype=np.float32)
cv = person_vars[var]
person_mask &= apply_op(cv, c["operation"], c["value"])
target_entity = variable_entity_map.get(target_variable)
if target_entity is None:
return np.zeros(n_households, dtype=np.float32)
if target_entity == "household":
if non_geo_constraints:
mask = _evaluate_constraints_standalone(
non_geo_constraints,
person_vars,
entity_rel,
household_ids,
n_households,
)
return mask.astype(np.float32)
return np.ones(n_households, dtype=np.float32)
if target_entity == "person":
er = entity_rel.copy()
er["satisfies"] = person_mask
filtered = er[er["satisfies"]]
counts = filtered.groupby("household_id")["person_id"].nunique()
else:
eid_col = f"{target_entity}_id"
er = entity_rel.copy()
er["satisfies"] = person_mask
entity_ok = er.groupby(eid_col)["satisfies"].any()
unique = er[["household_id", eid_col]].drop_duplicates()
unique["entity_ok"] = unique[eid_col].map(entity_ok)
filtered = unique[unique["entity_ok"]]
counts = filtered.groupby("household_id")[eid_col].nunique()
return np.array(
[counts.get(hid, 0) for hid in household_ids],
dtype=np.float32,
)
def _process_single_clone(
clone_idx: int,
col_start: int,
col_end: int,
cache_path: str,
) -> tuple:
"""Process one clone in a worker process.
Reads shared read-only data from ``_CLONE_SHARED``
(populated by ``_init_clone_worker``). Writes COO
entries as a compressed ``.npz`` file to *cache_path*.
Args:
clone_idx: Zero-based clone index.
col_start: First column index for this clone.
col_end: One-past-last column index.
cache_path: File path for output ``.npz``.
Returns:
(clone_idx, n_nonzero) tuple.
"""
sd = _CLONE_SHARED
# Unpack shared data
geo_states = sd["geography_state_fips"]
geo_counties = sd["geography_county_fips"]
geo_blocks = sd["geography_block_geoid"]
state_values = sd["state_values"]
county_values = sd["county_values"]
person_hh_indices = sd["person_hh_indices"]
unique_variables = sd["unique_variables"]
unique_constraint_vars = sd["unique_constraint_vars"]
county_dep_targets = sd["county_dep_targets"]
target_variables = sd["target_variables"]
target_reform_ids = sd["target_reform_ids"]
target_geo_info = sd["target_geo_info"]
non_geo_constraints_list = sd["non_geo_constraints_list"]
reform_vars = sd["reform_vars"]
n_records = sd["n_records"]
n_total = sd["n_total"]
n_targets = sd["n_targets"]
state_to_cols = sd["state_to_cols"]
cd_to_cols = sd["cd_to_cols"]
entity_rel = sd["entity_rel"]
household_ids = sd["household_ids"]
variable_entity_map = sd["variable_entity_map"]
do_takeup = sd["rerandomize_takeup"]
affected_target_info = sd["affected_target_info"]
entity_hh_idx_map = sd.get("entity_hh_idx_map", {})
entity_to_person_idx = sd.get("entity_to_person_idx", {})
precomputed_rates = sd.get("precomputed_rates", {})
# Slice geography for this clone
clone_states = geo_states[col_start:col_end]
clone_counties = geo_counties[col_start:col_end]
# Assemble hh/person values from precomputed state/county
hh_vars, person_vars, reform_hh_vars = _assemble_clone_values_standalone(
state_values,
clone_states,
person_hh_indices,
unique_variables,
unique_constraint_vars,
reform_vars=reform_vars,
county_values=county_values,
clone_counties=clone_counties,
county_dependent_vars=county_dep_targets,
)
# Takeup re-randomisation
if do_takeup and affected_target_info:
from policyengine_us_data.utils.takeup import (
SIMPLE_TAKEUP_VARS,
compute_block_takeup_for_entities,
)
clone_blocks = geo_blocks[col_start:col_end]
# Phase 1: compute non-target draws (would_file) FIRST
wf_draws = {}
for spec in SIMPLE_TAKEUP_VARS:
if spec.get("target") is not None:
continue
var_name = spec["variable"]
entity = spec["entity"]
rate_key = spec["rate_key"]
if rate_key not in precomputed_rates:
continue
ent_hh = entity_hh_idx_map[entity]
ent_blocks = clone_blocks[ent_hh]
ent_hh_ids = household_ids[ent_hh]
ent_ci = np.full(len(ent_hh), clone_idx, dtype=np.int64)
draws = compute_block_takeup_for_entities(
var_name,
precomputed_rates[rate_key],
ent_blocks,
ent_hh_ids,
ent_ci,
)
wf_draws[entity] = draws
if var_name in person_vars:
pidx = entity_to_person_idx[entity]
person_vars[var_name] = draws[pidx].astype(np.float32)
# Phase 2: target loop with would_file blending
for tvar, info in affected_target_info.items():
if tvar.endswith("_count"):
continue
entity_level = info["entity"]
takeup_var = info["takeup_var"]
ent_hh = entity_hh_idx_map[entity_level]
n_ent = len(ent_hh)
ent_states = clone_states[ent_hh]
ent_eligible = np.zeros(n_ent, dtype=np.float32)
if tvar in county_dep_targets and county_values:
ent_counties = clone_counties[ent_hh]
for cfips in np.unique(ent_counties):
m = ent_counties == cfips
cv = county_values.get(cfips, {}).get("entity", {})
if tvar in cv:
ent_eligible[m] = cv[tvar][m]
else:
st = int(cfips[:2])
sv = state_values[st]["entity"]
if tvar in sv:
ent_eligible[m] = sv[tvar][m]
else:
for st in np.unique(ent_states):
m = ent_states == st
sv = state_values[int(st)]["entity"]
if tvar in sv:
ent_eligible[m] = sv[tvar][m]
# Blend: for tax_unit targets, select between
# all-takeup-true and would_file=false values
if entity_level == "tax_unit" and "tax_unit" in wf_draws:
ent_wf_false = np.zeros(n_ent, dtype=np.float32)
if tvar in county_dep_targets and county_values:
ent_counties = clone_counties[ent_hh]
for cfips in np.unique(ent_counties):
m = ent_counties == cfips
cv = county_values.get(cfips, {}).get("entity_wf_false", {})
if tvar in cv:
ent_wf_false[m] = cv[tvar][m]
else:
st = int(cfips[:2])
sv = state_values[st].get("entity_wf_false", {})
if tvar in sv:
ent_wf_false[m] = sv[tvar][m]
else:
for st in np.unique(ent_states):
m = ent_states == st
sv = state_values[int(st)].get("entity_wf_false", {})
if tvar in sv:
ent_wf_false[m] = sv[tvar][m]
ent_eligible = np.where(
wf_draws["tax_unit"],
ent_eligible,
ent_wf_false,
)
ent_blocks = clone_blocks[ent_hh]
ent_hh_ids = household_ids[ent_hh]
ent_ci = np.full(n_ent, clone_idx, dtype=np.int64)
ent_takeup = compute_block_takeup_for_entities(
takeup_var,
precomputed_rates[info["rate_key"]],
ent_blocks,
ent_hh_ids,
ent_ci,
)
ent_values = (ent_eligible * ent_takeup).astype(np.float32)
hh_result = np.zeros(n_records, dtype=np.float32)
np.add.at(hh_result, ent_hh, ent_values)
hh_vars[tvar] = hh_result
if tvar in person_vars:
pidx = entity_to_person_idx[entity_level]
person_vars[tvar] = ent_values[pidx]
# Build COO entries for every target row
mask_cache: dict = {}
count_cache: dict = {}
rows_list: list = []
cols_list: list = []
vals_list: list = []
for row_idx in range(n_targets):
variable = target_variables[row_idx]
reform_id = target_reform_ids[row_idx]
geo_level, geo_id = target_geo_info[row_idx]
non_geo = non_geo_constraints_list[row_idx]
if geo_level == "district":
all_geo_cols = cd_to_cols.get(
str(geo_id),
np.array([], dtype=np.int64),
)
elif geo_level == "state":
all_geo_cols = state_to_cols.get(
int(geo_id),
np.array([], dtype=np.int64),
)
else:
all_geo_cols = np.arange(n_total)
clone_cols = all_geo_cols[
(all_geo_cols >= col_start) & (all_geo_cols < col_end)
]
if len(clone_cols) == 0:
continue
rec_indices = clone_cols - col_start
constraint_key = tuple(
sorted(
(
c["variable"],
c["operation"],
c["value"],
)
for c in non_geo
)
)
if variable.endswith("_count"):
vkey = (variable, constraint_key, reform_id)
if vkey not in count_cache:
count_cache[vkey] = _calculate_target_values_standalone(
variable,
non_geo,
n_records,
hh_vars,
reform_hh_vars,
person_vars,
entity_rel,
household_ids,
variable_entity_map,
reform_id=reform_id,
)
values = count_cache[vkey]
else:
source_vars = reform_hh_vars if reform_id > 0 else hh_vars
if variable not in source_vars:
continue
if constraint_key not in mask_cache:
mask_cache[constraint_key] = _evaluate_constraints_standalone(
non_geo,
person_vars,
entity_rel,
household_ids,
n_records,
)
mask = mask_cache[constraint_key]
values = source_vars[variable] * mask
vals = values[rec_indices]
nonzero = vals != 0
if nonzero.any():
rows_list.append(
np.full(
nonzero.sum(),
row_idx,
dtype=np.int32,
)
)
cols_list.append(clone_cols[nonzero].astype(np.int32))
vals_list.append(vals[nonzero])
# Write COO
if rows_list:
cr = np.concatenate(rows_list)
cc = np.concatenate(cols_list)
cv = np.concatenate(vals_list)
else:
cr = np.array([], dtype=np.int32)
cc = np.array([], dtype=np.int32)
cv = np.array([], dtype=np.float32)
np.savez_compressed(cache_path, rows=cr, cols=cc, vals=cv)
return clone_idx, len(cv)
class UnifiedMatrixBuilder:
"""Build sparse calibration matrix for cloned CPS records.
Processes clone-by-clone: each clone's records get their
assigned geography, are simulated, and the results fill
the corresponding columns.
Args:
db_uri: SQLAlchemy database URI.
time_period: Tax year for calibration (e.g. 2024).
dataset_path: Path to the base extended CPS h5 file.
"""
def __init__(
self,
db_uri: str,
time_period: int,
dataset_path: Optional[str] = None,
):
self.db_uri = db_uri
self.engine = create_engine(db_uri)
# Existing SQLite checkpoints may carry an older target_overview view.
create_or_replace_views(self.engine)
self.time_period = time_period
self.dataset_path = dataset_path
self._entity_rel_cache = None
self._target_overview_columns = None
# ---------------------------------------------------------------
# Entity relationships
# ---------------------------------------------------------------
def _build_entity_relationship(self, sim) -> pd.DataFrame:
if self._entity_rel_cache is not None:
return self._entity_rel_cache
self._entity_rel_cache = pd.DataFrame(
{
"person_id": sim.calculate("person_id", map_to="person").values,
"household_id": sim.calculate("household_id", map_to="person").values,
"tax_unit_id": sim.calculate("tax_unit_id", map_to="person").values,
"spm_unit_id": sim.calculate("spm_unit_id", map_to="person").values,
}
)
return self._entity_rel_cache
# ---------------------------------------------------------------
# Per-state precomputation
# ---------------------------------------------------------------
def _build_state_values(
self,
sim,
target_vars: set,
constraint_vars: set,
reform_vars: set = None,
geography=None,
rerandomize_takeup: bool = True,
workers: int = 1,
) -> dict:
"""Precompute household/person/entity values per state.
Creates a fresh Microsimulation per state to prevent
cross-state cache pollution (stale intermediate values
from one state leaking into another's calculations).
County-dependent variables (e.g. aca_ptc) are computed
here as a state-level fallback; county-level overrides
are applied later via ``_build_county_values``.
Args:
sim: Microsimulation instance (unused; kept for API
compatibility).
target_vars: Set of target variable names.
constraint_vars: Set of constraint variable names.
geography: GeographyAssignment with state_fips.
rerandomize_takeup: If True, force takeup=True and
also store entity-level eligible amounts for
takeup-affected targets.
workers: Number of parallel worker processes.
When >1, uses ProcessPoolExecutor.
Returns:
{state_fips: {
'hh': {var: array},
'person': {var: array},
'entity': {var: array} # only if rerandomize
}}
"""
from policyengine_us_data.utils.takeup import (
TAKEUP_AFFECTED_TARGETS,
)
if geography is None: