-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathsource_impute.py
More file actions
1401 lines (1258 loc) · 45.9 KB
/
source_impute.py
File metadata and controls
1401 lines (1258 loc) · 45.9 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
"""Non-PUF QRF imputations from donor surveys.
Re-imputes variables from ACS, SIPP, ORG, and SCF donor surveys.
Only ACS and ORG include state_fips as a QRF predictor. SIPP and SCF
lack state data, so their imputations use only demographic and
financial predictors.
Sources and variables:
ACS -> rent, real_estate_taxes (with state predictor)
SIPP -> tip_income, bank_account_assets, stock_assets,
bond_assets, household_vehicles_owned,
household_vehicles_value (no state predictor)
ORG -> hourly_wage, is_paid_hourly,
is_union_member_or_covered
SCF -> net_worth, auto_loan_balance, auto_loan_interest,
SCF-only balance-sheet components, and
50/50 source-model averaging for overlapping financial assets
(no state predictor)
Usage in unified calibration pipeline:
1. Load raw CPS
2. Clone Nx, assign geography
3. impute_source_variables() <-- this module
4. PUF clone + QRF impute (puf_impute.py)
5. PE simulate, build matrix, calibrate
"""
import gc
import h5py
import logging
from typing import Dict, Optional
import numpy as np
import pandas as pd
from microimpute.models.qrf import QRF
from policyengine_us_data.datasets.cps.tipped_occupation import (
derive_any_treasury_tipped_occupation_code,
derive_is_tipped_occupation,
)
from policyengine_us_data.datasets.sipp.sipp import (
ASSET_JOB_EARNINGS_COLUMNS,
ASSET_PREDICTORS,
SIPP_ASSET_ALLOCATION_COLUMNS,
SIPP_ASSET_TARGET_ALLOCATION_COLUMNS,
SIPP_ASSET_TARGET_SOURCE_COLUMNS,
SIPP_TIP_AMOUNT_COLUMNS,
SIPP_TIP_AMOUNT_TO_ALLOCATION_COLUMN,
SIPP_VEHICLE_TARGET_ALLOCATION_COLUMNS,
SSI_DISABILITY_CRITERIA_VARIABLE,
SSI_DISABILITY_DIFFICULTY_PREDICTORS,
SSI_DISABILITY_EXPORT_VARIABLES,
VEHICLE_MODEL_PREDICTORS,
build_vehicle_training_frame,
get_ssi_disability_model,
predict_ssi_disability_criteria,
preserve_under_65_ssi_disability_criteria,
)
from policyengine_us_data.datasets.org import (
ORG_BOOL_VARIABLES,
ORG_IMPUTED_VARIABLES,
build_org_receiver_frame,
predict_org_features,
)
from policyengine_us_data.utils.asset_imputation import (
SCF_NET_WORTH_TARGET,
SCF_FINANCIAL_ASSET_POLICY_VARIABLES,
SCF_HOUSEHOLD_ASSET_POLICY_VARIABLES,
SCF_NET_WORTH_COMPONENT_VARIABLES,
add_scf_financial_asset_targets,
add_scf_household_asset_targets,
add_scf_net_worth_target,
add_scf_net_worth_component_targets,
aggregate_person_values_to_reference_households,
align_household_values_to_reference_households,
build_household_vehicle_receiver,
combine_sipp_and_scf_financial_assets,
combine_sipp_and_scf_household_assets,
compute_net_worth_from_components,
rebalance_scf_net_worth_components,
require_scf_net_worth_formula_targets,
)
from policyengine_us_data.pipeline_metadata import pipeline_node
from policyengine_us_data.pipeline_schema import PipelineNode
from policyengine_us_data.utils.source_quality import (
cap_training_sample,
filter_positive_finite_weight_rows,
require_columns_present,
target_observed_source_masks,
)
logger = logging.getLogger(__name__)
ACS_IMPUTED_VARIABLES = [
"rent",
"real_estate_taxes",
]
ACS_TARGET_ALLOCATION_COLUMNS = {
"rent": ["rent_is_allocated"],
"real_estate_taxes": ["real_estate_taxes_is_allocated"],
}
SIPP_IMPUTED_VARIABLES = [
"tip_income",
"bank_account_assets",
"stock_assets",
"bond_assets",
*SSI_DISABILITY_EXPORT_VARIABLES,
"household_vehicles_owned",
"household_vehicles_value",
]
SCF_CORE_IMPUTED_VARIABLES = [
"auto_loan_balance",
"auto_loan_interest",
]
SCF_IMPUTED_VARIABLES = [
"net_worth",
*SCF_CORE_IMPUTED_VARIABLES,
*SCF_NET_WORTH_COMPONENT_VARIABLES,
]
ALL_SOURCE_VARIABLES = (
ACS_IMPUTED_VARIABLES
+ SIPP_IMPUTED_VARIABLES
+ ORG_IMPUTED_VARIABLES
+ SCF_IMPUTED_VARIABLES
)
SOURCE_IMPUTATION_CONSTRUCTION_ONLY_VARIABLES = tuple(
SSI_DISABILITY_DIFFICULTY_PREDICTORS
)
def drop_source_imputation_construction_variables(
data: Dict[str, Dict[int, np.ndarray]],
) -> Dict[str, Dict[int, np.ndarray]]:
"""Drop predictors needed during source imputation but not final exports."""
for variable in SOURCE_IMPUTATION_CONSTRUCTION_ONLY_VARIABLES:
data.pop(variable, None)
return data
ACS_PREDICTORS = [
"is_household_head",
"age",
"is_male",
"tenure_type",
"employment_income",
"self_employment_income",
"social_security",
"pension_income",
"household_size",
]
SIPP_TIPS_PREDICTORS = [
"employment_income",
"age",
"count_under_18",
"count_under_6",
"is_tipped_occupation",
]
SIPP_ASSETS_PREDICTORS = ASSET_PREDICTORS
SCF_PREDICTORS = [
"age",
"is_female",
"cps_race",
"is_married",
"own_children_in_household",
"employment_income",
"interest_dividend_income",
"social_security_pension_income",
]
TENURE_TYPE_MAP = {
"OWNED_WITH_MORTGAGE": 1,
"OWNED_OUTRIGHT": 1,
"RENTED": 2,
"NONE": 0,
}
SIPP_JOB_OCCUPATION_COLUMNS = [f"TJB{i}_OCC" for i in range(1, 8)]
def _encode_tenure_type(df: pd.DataFrame) -> pd.DataFrame:
"""Convert tenure_type enum strings to numeric codes."""
if "tenure_type" in df.columns:
df["tenure_type"] = (
df["tenure_type"]
.astype(str)
.map(TENURE_TYPE_MAP)
.fillna(0)
.astype(np.float32)
)
return df
@pipeline_node(
PipelineNode(
id="source_impute",
label="Source-Impute Stratified CPS",
node_type="entrypoint",
description="Apply ACS, SIPP, ORG, and SCF donor imputations to the stratified CPS calibration input.",
source_file="policyengine_us_data/calibration/source_impute.py",
status="current",
stability="moving",
pathways=["data_build"],
artifacts_in=["stratified_extended_cps_2024.h5"],
artifacts_out=["source_imputed_stratified_extended_cps_2024.h5"],
validation_commands=[
"uv run pytest tests/unit/calibration/test_source_impute.py"
],
)
)
def impute_source_variables(
data: Dict[str, Dict[int, np.ndarray]],
state_fips: np.ndarray,
time_period: int = 2024,
dataset_path: Optional[str] = None,
skip_acs: bool = False,
skip_sipp: bool = False,
skip_org: bool = False,
skip_scf: bool = False,
) -> Dict[str, Dict[int, np.ndarray]]:
"""Re-impute ACS/SIPP/ORG/SCF variables from donor surveys.
Overwrites existing imputed values in data. ACS uses
state_fips as a QRF predictor; ORG uses state plus labor-market
predictors; SIPP and SCF use only demographic and financial
predictors (no state data).
Args:
data: CPS dataset dict {variable: {time_period: array}}.
state_fips: State FIPS per household.
time_period: Tax year.
dataset_path: Path to CPS h5 for Microsimulation.
skip_acs: Skip ACS imputation.
skip_sipp: Skip SIPP imputation.
skip_org: Skip ORG imputation.
skip_scf: Skip SCF imputation.
Returns:
Updated data dict with re-imputed variables.
"""
data["state_fips"] = {
time_period: state_fips.astype(np.int32),
}
if not skip_acs:
logger.info("Imputing ACS variables with state predictor")
data = _impute_acs(data, state_fips, time_period, dataset_path)
if not skip_sipp:
logger.info("Imputing SIPP variables")
data = _impute_sipp(data, state_fips, time_period, dataset_path)
if not skip_org:
logger.info("Imputing ORG variables")
data = _impute_org(data, state_fips, time_period, dataset_path)
if not skip_scf:
logger.info("Imputing SCF variables")
data = _impute_scf(data, state_fips, time_period, dataset_path)
return data
def _build_cps_receiver(
data: Dict[str, Dict[int, np.ndarray]],
time_period: int,
dataset_path: Optional[str],
pe_variables: list,
) -> pd.DataFrame:
"""Build CPS receiver DataFrame from Microsimulation.
Args:
data: CPS data dict.
time_period: Tax year.
dataset_path: Path to CPS h5 for Microsimulation.
pe_variables: List of PE variable names to compute.
Returns:
DataFrame with requested columns.
"""
if dataset_path is not None:
from policyengine_us import Microsimulation
sim = Microsimulation(dataset=dataset_path)
tbs = sim.tax_benefit_system
valid_vars = [v for v in pe_variables if v in tbs.variables]
if valid_vars:
df = sim.calculate_dataframe(valid_vars)
else:
df = pd.DataFrame(index=range(len(data["person_id"][time_period])))
del sim
else:
df = pd.DataFrame()
for var in pe_variables:
if var not in df.columns and var in data:
df[var] = data[var][time_period].astype(np.float32)
return df
def _get_variable_entity(variable_name: str) -> str:
"""Return the entity key for a PE variable."""
from policyengine_us import CountryTaxBenefitSystem
tbs = CountryTaxBenefitSystem()
var = tbs.variables.get(variable_name)
if var is None:
return "person"
return var.entity.key
def _person_state_fips(
data: Dict[str, Dict[int, np.ndarray]],
state_fips: np.ndarray,
time_period: int,
) -> np.ndarray:
"""Map household-level state_fips to person level.
Args:
data: CPS data dict.
state_fips: State FIPS per household.
time_period: Tax year.
Returns:
Person-level state FIPS array.
"""
hh_ids_person = data.get("person_household_id", {}).get(time_period)
if hh_ids_person is not None:
hh_ids = data["household_id"][time_period]
hh_to_idx = {int(hh_id): i for i, hh_id in enumerate(hh_ids)}
return np.array([state_fips[hh_to_idx[int(hh_id)]] for hh_id in hh_ids_person])
# Fallback: distribute persons across households as evenly
# as possible (first households get any remainder).
n_hh = len(data["household_id"][time_period])
n_persons = len(data["person_id"][time_period])
base, remainder = divmod(n_persons, n_hh)
counts = np.full(n_hh, base, dtype=int)
counts[:remainder] += 1
return np.repeat(state_fips, counts)
def _person_is_married(
data: Dict[str, Dict[int, np.ndarray]],
time_period: int,
n_persons: int,
) -> np.ndarray:
"""Return a person-level married flag from CPS-compatible inputs."""
if "is_married" in data and time_period in data["is_married"]:
values = np.asarray(data["is_married"][time_period])
if len(values) == n_persons:
return values.astype(np.float32)
marital_unit_id = data.get("person_marital_unit_id", {}).get(time_period)
if marital_unit_id is not None and len(marital_unit_id) == n_persons:
marital_unit_id = np.asarray(marital_unit_id)
counts = pd.Series(marital_unit_id).map(
pd.Series(marital_unit_id).value_counts()
)
return (counts.to_numpy() > 1).astype(np.float32)
return np.zeros(n_persons, dtype=np.float32)
def _add_person_household_counts(
df: pd.DataFrame,
data: Dict[str, Dict[int, np.ndarray]],
time_period: int,
) -> pd.DataFrame:
"""Add household composition predictors to a person-level CPS frame."""
if "age" not in df.columns and "age" in data:
df["age"] = data["age"][time_period].astype(np.float32)
hh_ids_person = data.get("person_household_id", {}).get(time_period)
if hh_ids_person is None or "age" not in df.columns:
df["count_under_18"] = 0.0
df["count_under_6"] = 0.0
df["household_size"] = 1.0
return df
age_df = pd.DataFrame(
{
"hh": hh_ids_person,
"age": np.asarray(df["age"]),
}
)
grouped = age_df.groupby("hh")["age"]
df["count_under_18"] = (
grouped.transform(lambda values: (values < 18).sum())
.to_numpy()
.astype(np.float32)
)
df["count_under_6"] = (
grouped.transform(lambda values: (values < 6).sum())
.to_numpy()
.astype(np.float32)
)
df["household_size"] = grouped.transform("size").to_numpy().astype(np.float32)
return df
def _add_sipp_asset_predictors(asset_df: pd.DataFrame) -> pd.DataFrame:
"""Add SIPP-side liquid-asset model predictors without SSI receipt."""
asset_df = asset_df.copy()
asset_df["bank_account_assets"] = asset_df["TVAL_BANK"].fillna(0)
asset_df["stock_assets"] = asset_df["TVAL_STMF"].fillna(0)
asset_df["bond_assets"] = asset_df["TVAL_BOND"].fillna(0)
asset_df["age"] = asset_df.TAGE
asset_df["is_female"] = asset_df.ESEX == 2
asset_df["is_married"] = asset_df.EMS == 1
job_cols = [col for col in ASSET_JOB_EARNINGS_COLUMNS if col in asset_df]
if job_cols:
asset_df["employment_income"] = asset_df[job_cols].fillna(0).sum(axis=1) * 12
elif "TPTOTINC" in asset_df:
asset_df["employment_income"] = asset_df.TPTOTINC.fillna(0) * 12
else:
asset_df["employment_income"] = 0.0
asset_df["interest_income"] = (
asset_df["TINC_BANK"].fillna(0) + asset_df["TINC_BOND"].fillna(0)
) * 12
asset_df["dividend_income"] = asset_df["TINC_STMF"].fillna(0) * 12
asset_df["rental_income"] = asset_df["TINC_RENT"].fillna(0) * 12
asset_df["social_security"] = asset_df["TSSSAMT"].fillna(0) * 12
asset_df["retirement_income"] = asset_df["TRETINCAMT"].fillna(0) * 12
asset_df["non_ssi_income"] = (
asset_df["employment_income"]
+ asset_df["social_security"]
+ asset_df["retirement_income"]
)
asset_df["household_weight"] = asset_df.WPFINWGT
asset_df["is_under_18"] = asset_df.TAGE < 18
asset_df["is_under_6"] = asset_df.TAGE < 6
grouped = asset_df.groupby("SSUID")
asset_df["count_under_18"] = grouped["is_under_18"].transform("sum")
asset_df["count_under_6"] = grouped["is_under_6"].transform("sum")
asset_df["household_size"] = grouped["PNUM"].transform("count")
return asset_df
def _add_cps_asset_predictors(
cps_asset_df: pd.DataFrame,
data: Dict[str, Dict[int, np.ndarray]],
time_period: int,
) -> pd.DataFrame:
"""Add CPS-side predictors aligned to the SIPP liquid-asset model."""
cps_asset_df = cps_asset_df.copy()
n_persons = len(cps_asset_df)
if "is_male" in cps_asset_df.columns:
cps_asset_df["is_female"] = (~cps_asset_df["is_male"].astype(bool)).astype(
np.float32
)
elif "is_female" in data:
cps_asset_df["is_female"] = data["is_female"][time_period].astype(np.float32)
else:
cps_asset_df["is_female"] = 0.0
cps_asset_df["is_married"] = _person_is_married(
data,
time_period,
n_persons,
)
cps_asset_df = _add_person_household_counts(cps_asset_df, data, time_period)
for var in [
"employment_income",
"interest_income",
"dividend_income",
"rental_income",
"social_security",
"pension_income",
"retirement_distributions",
]:
if var in cps_asset_df.columns:
continue
if var in data:
cps_asset_df[var] = data[var][time_period].astype(np.float32)
else:
cps_asset_df[var] = 0.0
cps_asset_df["retirement_income"] = cps_asset_df["pension_income"].fillna(
0
) + cps_asset_df["retirement_distributions"].fillna(0)
cps_asset_df["non_ssi_income"] = (
cps_asset_df["employment_income"].fillna(0)
+ cps_asset_df["social_security"].fillna(0)
+ cps_asset_df["retirement_income"].fillna(0)
)
for predictor in SIPP_ASSETS_PREDICTORS:
if predictor not in cps_asset_df.columns:
cps_asset_df[predictor] = 0.0
cps_asset_df[predictor] = cps_asset_df[predictor].fillna(0).astype(np.float32)
return cps_asset_df
@pipeline_node(
PipelineNode(
id="acs_qrf",
label="ACS QRF Imputation",
node_type="library",
description="Impute rent and real estate tax variables from ACS donor data.",
source_file="policyengine_us_data/calibration/source_impute.py",
status="current",
stability="moving",
pathways=["data_build"],
validation_commands=[
"uv run pytest tests/unit/calibration/test_source_impute.py"
],
)
)
def _impute_acs(
data: Dict[str, Dict[int, np.ndarray]],
state_fips: np.ndarray,
time_period: int,
dataset_path: Optional[str] = None,
) -> Dict[str, Dict[int, np.ndarray]]:
"""Impute rent and real_estate_taxes from ACS with state.
Args:
data: CPS data dict.
state_fips: State FIPS per household.
time_period: Tax year.
dataset_path: Path to CPS h5 for Microsimulation.
Returns:
Updated data dict.
"""
from policyengine_us import Microsimulation
from policyengine_us_data.datasets.acs.acs import ACS_2022
acs = Microsimulation(dataset=ACS_2022)
predictors = ACS_PREDICTORS + ["state_fips"]
acs_df = acs.calculate_dataframe(
ACS_PREDICTORS + ACS_IMPUTED_VARIABLES, map_to="person"
)
acs_df["state_fips"] = acs.calculate("state_fips", map_to="person").values.astype(
np.float32
)
required_acs_flags = [
column
for columns in ACS_TARGET_ALLOCATION_COLUMNS.values()
for column in columns
]
with h5py.File(ACS_2022.file_path, "r") as acs_h5:
require_columns_present(
acs_h5,
required_acs_flags,
source_name="ACS_2022 artifact",
)
for flag_columns in ACS_TARGET_ALLOCATION_COLUMNS.values():
for flag_column in flag_columns:
acs_df[flag_column] = np.asarray(acs_h5[flag_column], dtype=bool)
train_df = acs_df[acs_df.is_household_head].copy()
train_df = _encode_tenure_type(train_df)
del acs
if dataset_path is not None:
cps_sim = Microsimulation(dataset=dataset_path)
cps_df = cps_sim.calculate_dataframe(ACS_PREDICTORS, map_to="person")
del cps_sim
else:
cps_df = pd.DataFrame()
for pred in ACS_PREDICTORS:
if pred in data:
cps_df[pred] = data[pred][time_period].astype(np.float32)
cps_df = _encode_tenure_type(cps_df)
person_states = _person_state_fips(data, state_fips, time_period)
cps_df["state_fips"] = person_states.astype(np.float32)
mask = (
cps_df.is_household_head.values
if "is_household_head" in cps_df.columns
else np.ones(len(cps_df), dtype=bool)
)
cps_heads = cps_df[mask]
logger.info(
"ACS QRF: %d train, %d test, %d predictors",
len(train_df),
len(cps_heads),
len(predictors),
)
acs_target_filters = target_observed_source_masks(
train_df,
targets=ACS_IMPUTED_VARIABLES,
target_allocation_flag_columns=ACS_TARGET_ALLOCATION_COLUMNS,
)
train_df, acs_target_filters = cap_training_sample(
train_df,
max_train_samples=10_000,
seed_name="calibration_acs_source_imputation_training_sample",
target_filters=acs_target_filters,
)
fitted = QRF().fit(
X_train=train_df,
predictors=predictors,
imputed_variables=ACS_IMPUTED_VARIABLES,
target_filters=acs_target_filters,
)
predictions = fitted.predict(X_test=cps_heads)
n_persons = len(data["person_id"][time_period])
for var in ACS_IMPUTED_VARIABLES:
values = np.zeros(n_persons, dtype=np.float32)
values[mask] = predictions[var].values
data[var] = {time_period: values}
data["pre_subsidy_rent"] = {time_period: data["rent"][time_period].copy()}
del fitted, predictions
gc.collect()
logger.info("ACS imputation complete: rent, real_estate_taxes")
return data
@pipeline_node(
PipelineNode(
id="sipp_qrf",
label="SIPP QRF Imputation",
node_type="library",
description="Impute tips, liquid assets, and vehicle assets from SIPP donor data.",
source_file="policyengine_us_data/calibration/source_impute.py",
status="current",
stability="moving",
pathways=["data_build"],
validation_commands=[
"uv run pytest tests/unit/calibration/test_source_impute.py"
],
)
)
def _impute_sipp(
data: Dict[str, Dict[int, np.ndarray]],
state_fips: np.ndarray,
time_period: int,
dataset_path: Optional[str] = None,
) -> Dict[str, Dict[int, np.ndarray]]:
"""Impute tip_income, liquid assets, and vehicle signals from SIPP.
Args:
data: CPS data dict.
state_fips: State FIPS per household.
time_period: Tax year.
dataset_path: Path to CPS h5 for Microsimulation.
Returns:
Updated data dict.
"""
from huggingface_hub import hf_hub_download
from policyengine_us_data.storage import STORAGE_FOLDER
hf_hub_download(
repo_id="PolicyEngine/policyengine-us-data",
filename="pu2023_slim.csv",
repo_type="model",
local_dir=STORAGE_FOLDER,
)
sipp_df = pd.read_csv(STORAGE_FOLDER / "pu2023_slim.csv")
tip_amount_columns = [
column for column in SIPP_TIP_AMOUNT_COLUMNS if column in sipp_df
]
tip_allocation_columns = [
SIPP_TIP_AMOUNT_TO_ALLOCATION_COLUMN[column] for column in tip_amount_columns
]
require_columns_present(
sipp_df.columns,
tip_allocation_columns,
source_name="SIPP slim tip donor file",
)
sipp_df["tip_income"] = sipp_df[tip_amount_columns].fillna(0).sum(axis=1) * 12
sipp_df["employment_income"] = sipp_df.TPTOTINC * 12
sipp_df["age"] = sipp_df.TAGE
sipp_df["household_weight"] = sipp_df.WPFINWGT
sipp_df["household_id"] = sipp_df.SSUID
sipp_df["treasury_tipped_occupation_code"] = (
derive_any_treasury_tipped_occupation_code(sipp_df[SIPP_JOB_OCCUPATION_COLUMNS])
)
sipp_df["is_tipped_occupation"] = derive_is_tipped_occupation(
sipp_df["treasury_tipped_occupation_code"]
)
if "MONTHCODE" in sipp_df:
sipp_df = sipp_df[sipp_df["MONTHCODE"] == 12].copy()
sipp_df["is_under_18"] = sipp_df.TAGE < 18
sipp_df["is_under_6"] = sipp_df.TAGE < 6
sipp_df["count_under_18"] = (
sipp_df.groupby("SSUID")["is_under_18"].sum().loc[sipp_df.SSUID.values].values
)
sipp_df["count_under_6"] = (
sipp_df.groupby("SSUID")["is_under_6"].sum().loc[sipp_df.SSUID.values].values
)
tip_target_filters = target_observed_source_masks(
sipp_df,
targets=["tip_income"],
target_source_columns={"tip_income": tip_amount_columns},
target_allocation_flag_columns={"tip_income": tip_allocation_columns},
require_nonmissing_source=False,
)
tip_cols = [
"household_id",
"employment_income",
"tip_income",
"count_under_18",
"count_under_6",
"age",
"is_tipped_occupation",
"household_weight",
]
tip_train = sipp_df[tip_cols].dropna()
tip_train, tip_target_filters = filter_positive_finite_weight_rows(
tip_train,
weight_col="household_weight",
target_filters=tip_target_filters,
context_name="SIPP source tip donor",
)
tip_train, tip_target_filters = cap_training_sample(
tip_train,
max_train_samples=10_000,
seed_name="calibration_sipp_tip_training_sample",
target_filters=tip_target_filters,
)
cps_tip_df = _build_cps_receiver(
data, time_period, dataset_path, ["employment_income", "age"]
)
person_ages = data["age"][time_period]
hh_ids_person = data.get("person_household_id", {}).get(time_period)
if hh_ids_person is not None:
age_df = pd.DataFrame({"hh": hh_ids_person, "age": person_ages})
under_18 = age_df.groupby("hh")["age"].apply(lambda x: (x < 18).sum())
under_6 = age_df.groupby("hh")["age"].apply(lambda x: (x < 6).sum())
cps_tip_df["count_under_18"] = under_18.loc[hh_ids_person].values.astype(
np.float32
)
cps_tip_df["count_under_6"] = under_6.loc[hh_ids_person].values.astype(
np.float32
)
else:
cps_tip_df["count_under_18"] = 0.0
cps_tip_df["count_under_6"] = 0.0
if "treasury_tipped_occupation_code" in data:
cps_tip_df["is_tipped_occupation"] = derive_is_tipped_occupation(
data["treasury_tipped_occupation_code"][time_period]
).astype(np.float32)
else:
cps_tip_df["is_tipped_occupation"] = 0.0
logger.info(
"SIPP tips QRF: %d train, %d test",
len(tip_train),
len(cps_tip_df),
)
fitted = QRF().fit(
X_train=tip_train,
predictors=SIPP_TIPS_PREDICTORS,
imputed_variables=["tip_income"],
target_filters=tip_target_filters,
weight_col="household_weight",
)
tip_preds = fitted.predict(X_test=cps_tip_df)
data["tip_income"] = {
time_period: tip_preds["tip_income"].values,
}
del fitted, tip_preds
gc.collect()
logger.info("SIPP tip imputation complete")
# Asset imputation
try:
hf_hub_download(
repo_id="PolicyEngine/policyengine-us-data",
filename="pu2023.csv",
repo_type="model",
local_dir=STORAGE_FOLDER,
)
asset_cols = (
[
"SSUID",
"PNUM",
"MONTHCODE",
"WPFINWGT",
"TAGE",
"ESEX",
"EMS",
"TSSSAMT",
"TRETINCAMT",
"TVAL_BANK",
"TVAL_STMF",
"TVAL_BOND",
"TINC_BANK",
"TINC_STMF",
"TINC_BOND",
"TINC_RENT",
]
+ ASSET_JOB_EARNINGS_COLUMNS
+ SIPP_ASSET_ALLOCATION_COLUMNS
)
asset_df = pd.read_csv(
STORAGE_FOLDER / "pu2023.csv",
delimiter="|",
usecols=asset_cols,
)
asset_df = asset_df[asset_df.MONTHCODE == 12]
asset_df = _add_sipp_asset_predictors(asset_df)
asset_train_cols = [
"bank_account_assets",
"stock_assets",
"bond_assets",
"household_weight",
*SIPP_ASSETS_PREDICTORS,
*[
column
for columns in SIPP_ASSET_TARGET_SOURCE_COLUMNS.values()
for column in columns
],
*SIPP_ASSET_ALLOCATION_COLUMNS,
]
asset_train = asset_df[asset_train_cols].copy()
cps_asset_df = _build_cps_receiver(
data,
time_period,
dataset_path,
[
"employment_income",
"interest_income",
"dividend_income",
"rental_income",
"social_security",
"pension_income",
"retirement_distributions",
"age",
"is_male",
],
)
cps_asset_df = _add_cps_asset_predictors(
cps_asset_df,
data,
time_period,
)
asset_vars = [
"bank_account_assets",
"stock_assets",
"bond_assets",
]
asset_target_filters = target_observed_source_masks(
asset_train,
targets=asset_vars,
target_source_columns=SIPP_ASSET_TARGET_SOURCE_COLUMNS,
target_allocation_flag_columns=SIPP_ASSET_TARGET_ALLOCATION_COLUMNS,
)
asset_train, asset_target_filters = filter_positive_finite_weight_rows(
asset_train,
weight_col="household_weight",
target_filters=asset_target_filters,
context_name="SIPP source asset donor",
)
asset_train, asset_target_filters = cap_training_sample(
asset_train,
max_train_samples=20_000,
seed_name="calibration_sipp_asset_training_sample",
target_filters=asset_target_filters,
)
logger.info(
"SIPP assets QRF: %d train, %d test",
len(asset_train),
len(cps_asset_df),
)
fitted = QRF().fit(
X_train=asset_train,
predictors=SIPP_ASSETS_PREDICTORS,
imputed_variables=asset_vars,
target_filters=asset_target_filters,
weight_col="household_weight",
)
asset_preds = fitted.predict(X_test=cps_asset_df)
for var in asset_vars:
data[var] = {
time_period: asset_preds[var].values,
}
del fitted, asset_preds
gc.collect()
logger.info("SIPP asset imputation complete")
cps_ssi_df = _build_cps_receiver(
data,
time_period,
dataset_path,
[
"employment_income",
"interest_income",
"dividend_income",
"rental_income",
"age",
"is_male",
*SSI_DISABILITY_DIFFICULTY_PREDICTORS,
"social_security_disability",
"disability_benefits",
],
)
if "is_male" in cps_ssi_df.columns:
cps_ssi_df["is_female"] = (~cps_ssi_df["is_male"].astype(bool)).astype(
np.float32
)
else:
cps_ssi_df["is_female"] = 0.0
if "is_married" in data:
cps_ssi_df["is_married"] = data["is_married"][time_period].astype(
np.float32
)
else:
cps_ssi_df["is_married"] = 0.0
cps_ssi_df["count_under_18"] = (
cps_tip_df["count_under_18"]
if "count_under_18" in cps_tip_df.columns
else 0.0
)
for var in asset_vars:
cps_ssi_df[var] = data[var][time_period].astype(np.float32)
for var in [
"interest_income",
"dividend_income",
"rental_income",
*SSI_DISABILITY_DIFFICULTY_PREDICTORS,
"social_security_disability",
]:
if var not in cps_ssi_df.columns:
cps_ssi_df[var] = data.get(var, {}).get(
time_period, np.zeros(len(cps_ssi_df))
)
if "disability_benefits" in cps_ssi_df.columns:
disability_benefits = cps_ssi_df["disability_benefits"]
else:
disability_benefits = data.get("disability_benefits", {}).get(
time_period, np.zeros(len(cps_ssi_df))
)
cps_ssi_df["has_disability_income"] = (
np.asarray(disability_benefits).astype(float) > 0
)
ssi_disability_model = get_ssi_disability_model(time_period=time_period)
meets_ssi_disability_criteria = predict_ssi_disability_criteria(
ssi_disability_model,
cps_ssi_df,
)
existing_meets_ssi_disability_criteria = data.get(
SSI_DISABILITY_CRITERIA_VARIABLE, {}
).get(time_period)
ssi_reported = data.get("ssi_reported", {}).get(time_period)
meets_ssi_disability_criteria = preserve_under_65_ssi_disability_criteria(
meets_ssi_disability_criteria,
age=data["age"][time_period],
ssi_reported=ssi_reported,
existing_meets_ssi_disability_criteria=existing_meets_ssi_disability_criteria,
)
data[SSI_DISABILITY_CRITERIA_VARIABLE] = {
time_period: meets_ssi_disability_criteria
}
logger.info("SIPP SSI disability criteria imputation complete")
vehicle_train = build_vehicle_training_frame()
cps_vehicle_df = _build_cps_receiver(
data,
time_period,
dataset_path,
[
"employment_income",
"interest_income",
"dividend_income",
"rental_income",
"age",
"is_male",
"is_household_head",