-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathcps.py
More file actions
3404 lines (3058 loc) · 128 KB
/
cps.py
File metadata and controls
3404 lines (3058 loc) · 128 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
from contextlib import closing, contextmanager
from importlib.resources import files
from policyengine_core.data import Dataset
from policyengine_us_data.storage import STORAGE_FOLDER, DOCS_FOLDER
import h5py
from policyengine_us_data.datasets.cps.census_cps import (
CensusCPS,
CensusCPS_2018,
CensusCPS_2019,
CensusCPS_2020,
CensusCPS_2021,
CensusCPS_2022,
CensusCPS_2023,
CensusCPS_2024,
)
from pandas import DataFrame, Series
import numpy as np
import pandas as pd
import yaml
from typing import Type
from policyengine_us_data.utils.uprating import (
create_policyengine_uprating_factors_table,
)
from microimpute.models.qrf import QRF
import logging
from policyengine_us_data.parameters import load_take_up_rate
from policyengine_us_data.datasets.cps.takeup import (
align_reported_ssi_disability,
prioritize_reported_recipients,
)
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.downsample import downsample_dataset_arrays
from policyengine_us_data.utils.randomness import seeded_rng
from policyengine_us_data.utils.identification import (
_store_identification_variables,
)
from policyengine_us_data.datasets.cps.tipped_occupation import (
derive_treasury_tipped_occupation_code,
derive_is_tipped_occupation,
)
from policyengine_us_data.utils.takeup import (
_sum_person_values_to_tax_units,
_voluntary_filing_age_bin,
_voluntary_filing_children_bin,
_voluntary_filing_rate_by_tax_unit,
_voluntary_filing_wage_income_bin,
assign_takeup_with_reported_anchors,
reported_subsidized_marketplace_by_tax_unit,
)
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,
require_columns_present,
target_observed_source_masks,
)
ACS_RENT_TARGET_ALLOCATION_COLUMNS = {
"rent": ["rent_is_allocated"],
"real_estate_taxes": ["real_estate_taxes_is_allocated"],
}
CURRENT_HEALTH_COVERAGE_REPORTED_VAR_MAP = {
"reported_has_direct_purchase_health_coverage_at_interview": "NOW_DIR",
"reported_has_marketplace_health_coverage_at_interview": "NOW_MRK",
"reported_has_subsidized_marketplace_health_coverage_at_interview": "NOW_MRKS",
"reported_has_unsubsidized_marketplace_health_coverage_at_interview": "NOW_MRKUN",
"reported_has_non_marketplace_direct_purchase_health_coverage_at_interview": (
"NOW_NONM"
),
"reported_has_employer_sponsored_health_coverage_at_interview": "NOW_GRP",
"reported_has_medicare_health_coverage_at_interview": "NOW_MCARE",
"reported_has_medicaid_health_coverage_at_interview": "NOW_CAID",
"reported_has_means_tested_health_coverage_at_interview": "NOW_MCAID",
"reported_has_chip_health_coverage_at_interview": "NOW_PCHIP",
"reported_has_other_means_tested_health_coverage_at_interview": "NOW_OTHMT",
"reported_has_tricare_health_coverage_at_interview": "NOW_MIL",
"reported_has_champva_health_coverage_at_interview": "NOW_CHAMPVA",
"reported_has_va_health_coverage_at_interview": "NOW_VACARE",
"reported_has_indian_health_service_coverage_at_interview": "NOW_IHSFLG",
}
CURRENT_HEALTH_COVERAGE_RULE_INPUT_ALIAS_MAP = {
"has_marketplace_health_coverage_at_interview": (
"reported_has_marketplace_health_coverage_at_interview"
),
"has_non_marketplace_direct_purchase_health_coverage_at_interview": (
"reported_has_non_marketplace_direct_purchase_health_coverage_at_interview"
),
"has_medicaid_health_coverage_at_interview": (
"reported_has_medicaid_health_coverage_at_interview"
),
"has_other_means_tested_health_coverage_at_interview": (
"reported_has_other_means_tested_health_coverage_at_interview"
),
"has_tricare_health_coverage_at_interview": (
"reported_has_tricare_health_coverage_at_interview"
),
"has_champva_health_coverage_at_interview": (
"reported_has_champva_health_coverage_at_interview"
),
"has_va_health_coverage_at_interview": (
"reported_has_va_health_coverage_at_interview"
),
"has_indian_health_service_coverage_at_interview": (
"reported_has_indian_health_service_coverage_at_interview"
),
}
CPS_SSI_DISABILITY_DIFFICULTY_COLUMNS = {
"difficulty_dressing_or_bathing": "PEDISDRS",
"difficulty_hearing": "PEDISEAR",
"difficulty_seeing": "PEDISEYE",
"difficulty_doing_errands": "PEDISOUT",
"difficulty_walking_or_climbing_stairs": "PEDISPHY",
"difficulty_remembering_or_making_decisions": "PEDISREM",
}
# Census CPS ASEC 2024 technical documentation, PERRP:
# https://www2.census.gov/programs-surveys/cps/techdocs/cpsmar24.pdf
PERRP_UNMARRIED_PARTNER_OF_HOUSEHOLD_HEAD_CODES = {
43: "Opposite Sex Unmarried Partner with Relatives",
44: "Opposite Sex Unmarried Partner without Relatives",
46: "Same Sex Unmarried Partner with Relatives",
47: "Same Sex Unmarried Partner without Relatives",
}
ESI_POLICYHOLDER_VARIABLE = (
"reported_owns_employer_sponsored_health_insurance_at_interview"
)
ESI_SOURCE_COLUMNS = {"NOW_OWNGRP", "NOW_HIPAID", "NOW_GRPFTYP"}
_ESI_PLAN_PRIORS_2024 = {
# AHRQ MEPS-IC Table IV.A.1 (private sector, 2024). These plan-type
# averages seed CPS policyholder records; national calibration later
# aligns the aggregate to the BEA full-economy employer premium total.
"family": {
"total_premium": 21_207.52589669509,
"employee_contribution": 6_490.205059544782,
},
"self_only": {
"total_premium": 8_389.275834815255,
"employee_contribution": 1_909.5781466113417,
},
}
_HAS_CURRENT_OWN_ESI = 1
_EMPLOYER_PAYS_ALL = 1
_EMPLOYER_PAYS_SOME = 2
_ESI_FAMILY_PLAN = 1
_ESI_SELF_ONLY_PLAN = 2
def _person_column(person: DataFrame, column: str, default=0) -> np.ndarray:
if column in person:
return person[column].to_numpy()
return np.full(len(person), default)
def impute_employer_sponsored_insurance_premiums(person: DataFrame) -> np.ndarray:
"""Impute annual employer-paid ESI premiums for CPS policyholders."""
own_esi = _person_column(person, "NOW_OWNGRP").astype(int) == _HAS_CURRENT_OWN_ESI
premium_status = _person_column(person, "NOW_HIPAID").astype(int)
plan_type = _person_column(person, "NOW_GRPFTYP").astype(int)
employee_paid = np.clip(person.PHIP_VAL.to_numpy(dtype=float), 0, None)
total_premium = np.where(
plan_type == _ESI_SELF_ONLY_PLAN,
_ESI_PLAN_PRIORS_2024["self_only"]["total_premium"],
_ESI_PLAN_PRIORS_2024["family"]["total_premium"],
)
average_employee_contribution = np.where(
plan_type == _ESI_SELF_ONLY_PLAN,
_ESI_PLAN_PRIORS_2024["self_only"]["employee_contribution"],
_ESI_PLAN_PRIORS_2024["family"]["employee_contribution"],
)
employee_share = np.where(
employee_paid > 0,
employee_paid,
average_employee_contribution,
)
employer_paid_when_some = np.clip(
total_premium - employee_share,
0,
total_premium,
)
employer_paid = np.where(
premium_status == _EMPLOYER_PAYS_ALL,
total_premium,
np.where(
premium_status == _EMPLOYER_PAYS_SOME,
employer_paid_when_some,
0,
),
)
valid_owner_with_plan = own_esi & np.isin(
plan_type,
[_ESI_FAMILY_PLAN, _ESI_SELF_ONLY_PLAN],
)
return np.where(valid_owner_with_plan, employer_paid, 0)
@contextmanager
def _open_dataset_read_only(dataset_source):
dataset = dataset_source(require=True)
file_path = getattr(dataset, "file_path", None)
if file_path is not None:
with pd.HDFStore(file_path, mode="r") as store:
yield store
return
with closing(dataset.load()) as store:
yield store
class CPS(Dataset):
name = "cps"
label = "CPS"
raw_cps: Type[CensusCPS] = None
previous_year_raw_cps: Type[CensusCPS] = None
data_format = Dataset.ARRAYS
frac: float | None = 1
def generate(self):
"""Generates the Current Population Survey dataset for PolicyEngine US microsimulations.
Technical documentation and codebook here: https://www2.census.gov/programs-surveys/cps/techdocs/cpsmar21.pdf
Args:
frac (float, optional): Fraction of the dataset to keep. Defaults to 1. Example: To downsample to 25% of dataset,
set frac=0.25.
"""
if self.raw_cps is None:
raise ValueError(
f"Cannot generate {self.name}: raw_cps is not defined. "
"For future years, use PolicyEngine's uprating at simulation time."
)
cps = {}
ENTITIES = ("person", "tax_unit", "family", "spm_unit", "household")
with _open_dataset_read_only(self.raw_cps) as raw_data:
person, tax_unit, family, spm_unit, household = [
raw_data[entity] for entity in ENTITIES
]
_validate_raw_cps_schema(person, tax_unit, self.raw_cps.name)
logging.info("Adding ID variables")
add_id_variables(cps, person, tax_unit, family, spm_unit, household)
logging.info("Adding personal variables")
add_personal_variables(cps, person)
logging.info("Adding personal income variables")
add_personal_income_variables(cps, person, self.raw_cps.time_period)
logging.info("Adding previous year income variables")
add_previous_year_income(self, cps)
logging.info("Adding SSN card type")
ssn_card_type = add_ssn_card_type(
cps,
person,
spm_unit,
self.time_period,
undocumented_target=13e6,
undocumented_workers_target=8.3e6,
undocumented_students_target=0.21 * 1.9e6,
)
logging.info("Adding taxpayer ID variables")
_store_identification_variables(
cps,
person,
ssn_card_type,
self.time_period,
)
logging.info("Adding family variables")
add_spm_variables(self, cps, spm_unit)
logging.info("Adding household variables")
add_household_variables(cps, household)
logging.info("Adding rent")
add_rent(self, cps, person, household)
logging.info("Adding tips")
add_tips(self, cps)
logging.info("Adding ORG labor-market inputs")
add_org_labor_market_inputs(cps)
logging.info("Adding auto loan balance, interest and wealth")
add_auto_loan_interest_and_net_worth(self, cps)
logging.info("Added all variables")
self.save_dataset(cps)
logging.info("Adding takeup")
add_takeup(self)
logging.info("Imputing Marketplace plan benchmark ratio")
add_marketplace_plan_benchmark_ratio(self)
logging.info("Deriving other health insurance premiums")
derive_other_health_insurance_premiums(self)
logging.info("Downsampling")
# Downsample
if self.frac is not None and self.frac < 1.0:
self.downsample(frac=self.frac)
@pipeline_node(
PipelineNode(
id="downsample",
label="Downsample CPS",
node_type="library",
description="Subsample CPS arrays for released CPS vintages while full variants skip this step.",
source_file="policyengine_us_data/datasets/cps/cps.py",
status="current",
stability="stable",
pathways=["data_build"],
validation_commands=["uv run pytest validation/stage_1/test_cps.py"],
)
)
def downsample(self, frac: float) -> None:
"""Subsample the loaded CPS dataset and preserve downsampled arrays.
Args:
frac: Fraction of records to retain.
"""
from policyengine_us import Microsimulation
original_data: dict = self.load_dataset()
sim = Microsimulation(dataset=self)
sim.subsample(frac=frac)
self.save_dataset(
downsample_dataset_arrays(
original_data=original_data,
sim=sim,
dataset_name=self.name,
)
)
@pipeline_node(
PipelineNode(
id="add_rent",
label="Rent Imputation",
node_type="library",
description="Impute rent and real estate taxes using ACS donor data.",
source_file="policyengine_us_data/datasets/cps/cps.py",
status="legacy",
stability="moving",
pathways=["data_build"],
validation_commands=["uv run pytest validation/stage_1/test_cps.py"],
)
)
def add_rent(self, cps: h5py.File, person: DataFrame, household: DataFrame):
cps["tenure_type"] = household.H_TENURE.map(
{
0: "NONE",
1: "OWNED_WITH_MORTGAGE",
2: "RENTED",
3: "NONE",
}
).astype("S")
if self.file_path.exists():
try:
with pd.HDFStore(self.file_path, mode="r") as store:
stale_keys = [
key.lstrip("/")
for key in store.keys()
if key.lstrip("/") not in cps
]
if stale_keys:
logging.warning(
f"Stale H5 at {self.file_path} has {len(stale_keys)} "
f"extra vars before first save: {stale_keys[:5]}"
)
except (BlockingIOError, OSError, ValueError) as error:
logging.warning(
"Unable to inspect stale H5 at %s before replacement: %s",
self.file_path,
error,
)
self.file_path.unlink()
self.save_dataset(cps)
from policyengine_us_data.datasets.acs.acs import ACS_2022
from policyengine_us import Microsimulation
acs = Microsimulation(dataset=ACS_2022)
cps_sim = Microsimulation(dataset=self)
PREDICTORS = [
"is_household_head",
"age",
"is_male",
"tenure_type",
"employment_income",
"self_employment_income",
"social_security",
"pension_income",
"state_code_str",
"household_size",
]
IMPUTATIONS = ["rent", "real_estate_taxes"]
train_df = acs.calculate_dataframe(PREDICTORS + IMPUTATIONS, map_to="person")
# TODO(PolicyEngine/policyengine-core#482): policyengine-core 3.24.0+
# silently drops user-supplied ETERNITY inputs on dataset reload because
# _user_input_keys records the user-supplied period instead of the
# canonicalized ETERNITY key. is_household_head therefore comes back as
# all False from calculate_dataframe and the household-head filter below
# produces an empty frame. For ACS we read it directly from the source
# H5; for CPS we use the in-memory dict (already populated upstream in
# add_id_variables). Remove both overrides once pyproject.toml's
# policyengine-core upper bound is lifted.
required_acs_flags = [
column
for columns in ACS_RENT_TARGET_ALLOCATION_COLUMNS.values()
for column in columns
]
with h5py.File(ACS_2022.file_path, "r") as acs_h5:
train_df["is_household_head"] = np.asarray(
acs_h5["is_household_head"], dtype=bool
)
require_columns_present(
acs_h5,
required_acs_flags,
source_name="ACS_2022 artifact",
)
for flag_columns in ACS_RENT_TARGET_ALLOCATION_COLUMNS.values():
for flag_column in flag_columns:
train_df[flag_column] = np.asarray(acs_h5[flag_column], dtype=bool)
train_df.tenure_type = train_df.tenure_type.map(
{
"OWNED_OUTRIGHT": "OWNED_WITH_MORTGAGE",
},
na_action="ignore",
).fillna(train_df.tenure_type)
train_df = train_df[train_df.is_household_head].copy()
inference_df = cps_sim.calculate_dataframe(PREDICTORS, map_to="person")
inference_df["is_household_head"] = np.asarray(cps["is_household_head"], dtype=bool)
mask = inference_df.is_household_head.values
inference_df = inference_df[mask]
logging.info("Training imputation model for rent and real estate taxes.")
rent_target_filters = target_observed_source_masks(
train_df,
targets=IMPUTATIONS,
target_allocation_flag_columns=ACS_RENT_TARGET_ALLOCATION_COLUMNS,
)
train_df, rent_target_filters = cap_training_sample(
train_df,
max_train_samples=10_000,
seed_name="legacy_acs_rent_training_sample",
target_filters=rent_target_filters,
)
fitted_model = QRF().fit(
X_train=train_df,
predictors=PREDICTORS,
imputed_variables=IMPUTATIONS,
target_filters=rent_target_filters,
)
logging.info("Imputing rent and real estate taxes.")
imputed_values = fitted_model.predict(X_test=inference_df)
logging.info("Imputation complete.")
# ``cps["age"]`` has an integer dtype, so ``np.zeros_like(cps["age"])``
# would silently truncate the float QRF imputations to int on assignment.
# Force float so the imputed rent and real-estate-tax values keep
# full precision (and do not deterministically floor toward zero).
cps["rent"] = np.zeros(len(cps["age"]), dtype=float)
cps["rent"][mask] = imputed_values["rent"]
cps["pre_subsidy_rent"] = cps["rent"]
cps["real_estate_taxes"] = np.zeros(len(cps["age"]), dtype=float)
cps["real_estate_taxes"][mask] = imputed_values["real_estate_taxes"]
TEMPORARY_TAKEUP_SOURCE_ANCHORS = ("snap_reported", "ssi_reported")
TEMPORARY_IMPUTATION_SOURCE_VARIABLES = (
"pension_income",
"retirement_distributions",
)
def _drop_persisted_dataset_variables(file_path, variable_names):
with h5py.File(file_path, "a") as dataset_file:
for variable_name in variable_names:
if variable_name in dataset_file:
del dataset_file[variable_name]
@pipeline_node(
PipelineNode(
id="add_takeup",
label="Benefit Takeup",
node_type="library",
description="Apply stochastic takeup and reported-anchor alignment for benefit programs.",
source_file="policyengine_us_data/datasets/cps/cps.py",
status="current",
stability="moving",
pathways=["data_build"],
validation_commands=["uv run pytest validation/stage_1/test_cps.py"],
)
)
def add_takeup(self):
data = self.load_dataset()
from policyengine_us import Microsimulation
baseline = Microsimulation(dataset=self)
n_persons = len(data["person_id"])
n_tax_units = len(data["tax_unit_id"])
n_spm_units = len(data["spm_unit_id"])
# Load take-up rates
eitc_rates_by_children = load_take_up_rate("eitc", self.time_period)
dc_ptc_rate = load_take_up_rate("dc_ptc", self.time_period)
snap_rate = load_take_up_rate("snap", self.time_period)
aca_rate = load_take_up_rate("aca", self.time_period)
medicaid_rates_by_state = load_take_up_rate("medicaid", self.time_period)
head_start_rate = load_take_up_rate("head_start", self.time_period)
early_head_start_rate = load_take_up_rate("early_head_start", self.time_period)
ssi_rate = load_take_up_rate("ssi", self.time_period)
housing_assistance_rate = load_take_up_rate("housing_assistance", self.time_period)
voluntary_filing_rates = load_take_up_rate("voluntary_filing", self.time_period)
# EITC: varies by number of children
eitc_child_count = baseline.calculate("eitc_child_count").values
potential_eitc = baseline.calculate("eitc").values
eitc_takeup_rate = np.array(
[eitc_rates_by_children.get(min(int(c), 3), 0.85) for c in eitc_child_count]
)
rng = seeded_rng("takes_up_eitc")
data["takes_up_eitc"] = rng.random(n_tax_units) < eitc_takeup_rate
# DC Property Tax Credit
rng = seeded_rng("takes_up_dc_ptc")
data["takes_up_dc_ptc"] = rng.random(n_tax_units) < dc_ptc_rate
# SNAP: prioritize reported recipients
rng = seeded_rng("takes_up_snap_if_eligible")
reported_snap = data["snap_reported"] > 0
data["takes_up_snap_if_eligible"] = prioritize_reported_recipients(
reported_snap,
snap_rate,
rng.random(n_spm_units),
)
# ACA
rng = seeded_rng("takes_up_aca_if_eligible")
reported_marketplace_by_tax_unit = reported_subsidized_marketplace_by_tax_unit(
data["person_tax_unit_id"],
data["tax_unit_id"],
data["reported_has_subsidized_marketplace_health_coverage_at_interview"],
)
data["takes_up_aca_if_eligible"] = assign_takeup_with_reported_anchors(
rng.random(n_tax_units),
aca_rate,
reported_mask=reported_marketplace_by_tax_unit,
)
# Medicaid: state-specific rates
state_codes = baseline.calculate("state_code_str").values
hh_ids = data["household_id"]
person_hh_ids = data["person_household_id"]
hh_to_state = dict(zip(hh_ids, state_codes))
person_states = np.array([hh_to_state.get(hh_id, "CA") for hh_id in person_hh_ids])
medicaid_rate_by_person = np.array(
[medicaid_rates_by_state.get(s, 0.93) for s in person_states]
)
rng = seeded_rng("takes_up_medicaid_if_eligible")
data["takes_up_medicaid_if_eligible"] = assign_takeup_with_reported_anchors(
rng.random(n_persons),
medicaid_rate_by_person,
reported_mask=data["has_medicaid_health_coverage_at_interview"],
group_keys=person_states,
)
# Head Start
rng = seeded_rng("takes_up_head_start_if_eligible")
data["takes_up_head_start_if_eligible"] = rng.random(n_persons) < head_start_rate
# Early Head Start
rng = seeded_rng("takes_up_early_head_start_if_eligible")
data["takes_up_early_head_start_if_eligible"] = (
rng.random(n_persons) < early_head_start_rate
)
# SSI: prioritize reported recipients
rng = seeded_rng("takes_up_ssi_if_eligible")
reported_ssi = data["ssi_reported"] > 0
data["takes_up_ssi_if_eligible"] = prioritize_reported_recipients(
reported_ssi,
ssi_rate,
rng.random(n_persons),
)
# TANF
tanf_rate = load_take_up_rate("tanf", self.time_period)
rng = seeded_rng("takes_up_tanf_if_eligible")
data["takes_up_tanf_if_eligible"] = rng.random(n_spm_units) < tanf_rate
# Housing assistance: prioritize SPM-reported recipients, then fill the
# remaining draw pool up to the national receipt rate.
rng = seeded_rng("takes_up_housing_assistance_if_eligible")
reported_housing_assistance = np.asarray(
data.get(
"receives_housing_assistance",
np.zeros(n_spm_units, dtype=bool),
),
dtype=bool,
)
housing_assistance_eligible = baseline.calculate(
"is_eligible_for_housing_assistance"
).values
data["takes_up_housing_assistance_if_eligible"] = prioritize_reported_recipients(
reported_housing_assistance,
housing_assistance_rate,
rng.random(n_spm_units),
eligible_mask=housing_assistance_eligible,
)
# WIC: resolve draws to bools using category-specific rates
wic_categories = baseline.calculate("wic_category_str").values
wic_takeup_rates = load_take_up_rate("wic_takeup", self.time_period)
wic_takeup_rate_by_person = np.array(
[wic_takeup_rates.get(c, 0) for c in wic_categories]
)
rng = seeded_rng("would_claim_wic")
data["would_claim_wic"] = rng.random(n_persons) < wic_takeup_rate_by_person
# WIC nutritional risk — fully resolved
wic_risk_rates = load_take_up_rate("wic_nutritional_risk", self.time_period)
wic_risk_rate_by_person = np.array(
[wic_risk_rates.get(c, 0) for c in wic_categories]
)
receives_wic = baseline.calculate("receives_wic").values
rng = seeded_rng("is_wic_at_nutritional_risk")
imputed_risk = rng.random(n_persons) < wic_risk_rate_by_person
data["is_wic_at_nutritional_risk"] = receives_wic | imputed_risk
# Pregnancy: stochastically assign is_pregnant to women 15-44
# using CDC/Census-derived state-level pregnancy rates.
# CPS does not ask about pregnancy; calibration will fine-tune.
from policyengine_us_data.db.etl_pregnancy import (
get_state_pregnancy_rates,
)
pregnancy_rates = get_state_pregnancy_rates(
cdc_year=self.time_period,
acs_year=self.time_period,
)
national_rate = 0.041 # fallback
pregnancy_rate_by_person = np.array(
[pregnancy_rates.get(s, national_rate) for s in person_states]
)
ages = data["age"]
is_female = data["is_female"]
is_eligible = is_female & (ages >= 15) & (ages <= 44)
rng = seeded_rng("is_pregnant")
data["is_pregnant"] = is_eligible & (
rng.random(n_persons) < pregnancy_rate_by_person
)
# Voluntary tax filing: some tax units file even when not required and not
# claiming EITC. Assign rates by a simple demographic table that
# concentrates elective filing among low-wage parents and sharply reduces
# it among older childless households.
claims_eitc = data["takes_up_eitc"] & (potential_eitc > 0)
tax_unit_child_dependents = baseline.calculate("tax_unit_child_dependents").values
tax_unit_wage_income = _sum_person_values_to_tax_units(
data["employment_income"],
data["person_tax_unit_id"],
data["tax_unit_id"],
)
age_head = baseline.calculate("age_head").values
voluntary_filing_rate = _voluntary_filing_rate_by_tax_unit(
voluntary_filing_rates,
_voluntary_filing_children_bin(tax_unit_child_dependents),
_voluntary_filing_wage_income_bin(tax_unit_wage_income),
_voluntary_filing_age_bin(age_head),
)
rng = seeded_rng("would_file_taxes_voluntarily")
data["would_file_taxes_voluntarily"] = ~claims_eitc & (
rng.random(n_tax_units) < voluntary_filing_rate
)
# --- SSI: align disability to CPS-reported receipt ---
# CPS disability flags miss some under-65 SSI recipients, but SSI
# requires under-65 recipients to be disabled or blind.
reported_ssi = data["ssi_reported"] > 0
data["is_disabled"] = align_reported_ssi_disability(
data["is_disabled"],
reported_ssi,
data["age"],
)
for source_anchor in TEMPORARY_TAKEUP_SOURCE_ANCHORS:
data.pop(source_anchor, None)
self.save_dataset(data)
_drop_persisted_dataset_variables(
self.file_path,
TEMPORARY_TAKEUP_SOURCE_ANCHORS,
)
def add_marketplace_plan_benchmark_ratio(self):
"""Impute `selected_marketplace_plan_benchmark_ratio` per tax unit.
PolicyEngine-US's ACA PTC formulas assume the selected Marketplace plan
costs exactly the Second Lowest Cost Silver Plan (SLCSP). That under- or
over-states household out-of-pocket premium for the ~50% of Marketplace
enrollees who select Bronze or Gold / Platinum plans instead.
For tax units that CPS flags as taking up Marketplace coverage, back out
the implied plan-to-SLCSP ratio from:
reported_net_premium ≈ selected_plan_cost − APTC
selected_plan_cost = SLCSP × benchmark_ratio
→ benchmark_ratio = (reported_net_premium + computed_PTC) / SLCSP
The CPS private-health-premium field is net of APTC for subsidized
enrollees, so adding back PolicyEngine's computed PTC recovers the
sticker cost. Non-Marketplace tax units keep the default 1.0; the
ratio is only consumed through `selected_marketplace_plan_premium_proxy`,
which is zero when `takes_up_aca_if_eligible` is false, so the default
value does not affect their downstream calculations.
Ratios are clipped to [0.5, 1.5] to handle CPS reporting noise and
Marketplace-flag false positives. Outliers usually indicate the
household reported a private or employer premium rather than a true
Marketplace plan.
"""
data = self.load_dataset()
from policyengine_us import Microsimulation
baseline = Microsimulation(dataset=self)
period = self.time_period
slcsp = baseline.calculate("slcsp", map_to="tax_unit", period=period).values
aca_ptc = baseline.calculate("aca_ptc", map_to="tax_unit", period=period).values
reported_premium = baseline.calculate(
"health_insurance_premiums_without_medicare_part_b",
map_to="tax_unit",
period=period,
).values
takes_up_aca = baseline.calculate(
"takes_up_aca_if_eligible",
map_to="tax_unit",
period=period,
).values.astype(bool)
data["selected_marketplace_plan_benchmark_ratio"] = (
compute_marketplace_plan_benchmark_ratio(
reported_premium=reported_premium,
aca_ptc=aca_ptc,
slcsp=slcsp,
takes_up_aca=takes_up_aca,
)
)
self.save_dataset(data)
OTHER_HEALTH_INSURANCE_PREMIUM_TARGETS = {
"other_health_insurance_premiums": {
"reported_variable": "health_insurance_premiums_without_medicare_part_b",
"modeled_variables": (
"chip_premium",
"marketplace_net_premium",
"medicaid_premium",
),
},
}
def derive_other_health_insurance_premiums(self):
"""Create other premium inputs net of baseline computed premiums.
The model adds computed premiums back explicitly, so it needs a separate
other-premium input for the parts of CPS-reported non-Medicare premiums
not explained by baseline computed Marketplace, CHIP, or Medicaid
premiums. The original CPS-reported premium inputs remain unchanged as raw
source fields. The data package requires a policyengine-us release with
these modeled premium variables, so missing variables fail fast instead of
silently producing an incomplete decomposition.
"""
from policyengine_us import Microsimulation
data = self.load_dataset()
baseline = Microsimulation(dataset=self)
tbs = baseline.tax_benefit_system
period = self.time_period
changed = False
for output_variable, config in OTHER_HEALTH_INSURANCE_PREMIUM_TARGETS.items():
reported_variable = config["reported_variable"]
premium_variables = config["modeled_variables"]
if reported_variable not in data:
continue
computed_premium = np.zeros(len(data[reported_variable]), dtype=float)
for variable in premium_variables:
values = np.asarray(
baseline.calculate(variable, period=period).values,
dtype=float,
)
computed_premium += _premium_values_to_person(
data=data,
source_entity=tbs.variables[variable].entity.key,
values=values,
)
data[output_variable] = compute_other_health_insurance_premiums(
reported_premium=data[reported_variable],
baseline_computed_premium=computed_premium,
)
logging.info(
"Created %s from %s by subtracting baseline computed premiums: %s",
output_variable,
reported_variable,
", ".join(premium_variables),
)
changed = True
if changed:
self.save_dataset(data)
def compute_other_health_insurance_premiums(
reported_premium: np.ndarray,
baseline_computed_premium: np.ndarray,
) -> np.ndarray:
"""Return other premiums after subtracting baseline computed premiums."""
return np.asarray(reported_premium, dtype=float) - np.asarray(
baseline_computed_premium, dtype=float
)
def _premium_values_to_person(
data: dict,
source_entity: str,
values: np.ndarray,
) -> np.ndarray:
"""Map computed premiums to person rows for person-level premium accounting."""
person_ids = data["person_id"]
if source_entity == "person":
if len(values) != len(person_ids):
raise ValueError(
"Person-level computed premium length does not match person rows: "
f"got {len(values)}, expected {len(person_ids)}."
)
return values
entity_id_variable = f"{source_entity}_id"
person_entity_id_variable = f"person_{source_entity}_id"
if entity_id_variable not in data or person_entity_id_variable not in data:
raise ValueError(
f"Cannot allocate {source_entity}-level premiums to people: missing "
f"{entity_id_variable} or {person_entity_id_variable}."
)
entity_ids = data[entity_id_variable]
person_entity_ids = data[person_entity_id_variable]
if len(values) != len(entity_ids):
raise ValueError(
f"{source_entity}-level computed premium length does not match "
f"{source_entity} rows: got {len(values)}, expected {len(entity_ids)}."
)
entity_position = {entity_id: index for index, entity_id in enumerate(entity_ids)}
allocated = np.zeros(len(person_ids), dtype=float)
seen_entities = set()
for person_index, entity_id in enumerate(person_entity_ids):
if entity_id in seen_entities:
continue
allocated[person_index] = values[entity_position[entity_id]]
seen_entities.add(entity_id)
return allocated
MARKETPLACE_PLAN_BENCHMARK_RATIO_MIN = 0.5
MARKETPLACE_PLAN_BENCHMARK_RATIO_MAX = 1.5
def compute_marketplace_plan_benchmark_ratio(
reported_premium: np.ndarray,
aca_ptc: np.ndarray,
slcsp: np.ndarray,
takes_up_aca: np.ndarray,
) -> np.ndarray:
"""Back out the Marketplace plan-to-SLCSP ratio per tax unit.
Returns 1.0 for tax units that don't take up Marketplace coverage or that
have no SLCSP (zero benchmark). Ratios for Marketplace takers are clipped
to ``[MARKETPLACE_PLAN_BENCHMARK_RATIO_MIN, MARKETPLACE_PLAN_BENCHMARK_RATIO_MAX]``.
Args:
reported_premium: CPS-reported annual private health insurance premium
(net of APTC for subsidized Marketplace takers), at the tax-unit
level in USD.
aca_ptc: PolicyEngine-computed annual advance premium tax credit at
the tax-unit level in USD.
slcsp: Second Lowest Cost Silver Plan annual premium at the tax-unit
level in USD.
takes_up_aca: Boolean array at the tax-unit level, True when the
household is modeled as taking up Marketplace coverage.
Returns:
Array of benchmark ratios (unitless), same shape as the inputs.
"""
with np.errstate(divide="ignore", invalid="ignore"):
raw = (reported_premium + aca_ptc) / np.where(slcsp > 0, slcsp, 1.0)
clipped = np.clip(
raw,
MARKETPLACE_PLAN_BENCHMARK_RATIO_MIN,
MARKETPLACE_PLAN_BENCHMARK_RATIO_MAX,
)
applicable = takes_up_aca.astype(bool) & (slcsp > 0)
return np.where(applicable, clipped, 1.0)
def uprate_cps_data(data, from_period, to_period):
uprating = create_policyengine_uprating_factors_table()
for variable in uprating.index.unique():
if variable in data:
current_index = uprating[uprating.index == variable][to_period].values[0]
start_index = uprating[uprating.index == variable][from_period].values[0]
growth = current_index / start_index
data[variable] = data[variable] * growth
return data
def _validate_raw_cps_schema(
person: DataFrame,
tax_unit: DataFrame,
raw_cps_name: str,
) -> None:
required_person_columns = {
"CENSUS_TAX_ID",
"PERRP",
*ESI_SOURCE_COLUMNS,
}
required_tax_unit_columns = set()
missing_person = sorted(required_person_columns - set(person.columns))
missing_tax_unit = sorted(required_tax_unit_columns - set(tax_unit.columns))
if not missing_person and not missing_tax_unit:
return
missing_parts = []
if missing_person:
missing_parts.append("person: " + ", ".join(missing_person))
if missing_tax_unit:
missing_parts.append("tax_unit: " + ", ".join(missing_tax_unit))
raise ValueError(
f"Raw CPS dataset {raw_cps_name} is stale and must be regenerated; "
f"missing constructed tax-unit columns ({'; '.join(missing_parts)})."
)
@pipeline_node(
PipelineNode(
id="add_id_variables",
label="Add ID Variables",
node_type="library",
description="Create person, household, tax-unit, SPM-unit, family, and marital-unit IDs.",
source_file="policyengine_us_data/datasets/cps/cps.py",
status="current",
stability="stable",
pathways=["data_build"],
validation_commands=[
"uv run pytest tests/unit/datasets/test_cps_identification.py"
],
)
)
def add_id_variables(
cps: h5py.File,
person: DataFrame,
tax_unit: DataFrame,