-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathloss.py
More file actions
2096 lines (1753 loc) · 76.1 KB
/
loss.py
File metadata and controls
2096 lines (1753 loc) · 76.1 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
import gc
import pandas as pd
import numpy as np
import logging
import sqlite3
from policyengine_us_data.storage import CALIBRATION_FOLDER, STORAGE_FOLDER
from policyengine_us_data.storage.calibration_targets.pull_soi_targets import (
STATE_ABBR_TO_FIPS,
)
from policyengine_us_data.storage.calibration_targets.aca_ptc_targets import (
load_aca_ptc_state_targets,
)
from policyengine_us_data.storage.calibration_targets.soi_metadata import (
RETIREMENT_CONTRIBUTION_TARGETS,
)
from policyengine_us_data.utils.cms_medicare import (
get_beneficiary_paid_medicare_part_b_premiums_target,
get_medicare_enrollment_target,
)
from policyengine_us_data.utils.bea_regional import get_bea_state_wage_targets
from policyengine_us_data.db.etl_irs_soi import (
get_national_geography_soi_target,
get_state_geography_soi_targets,
)
from policyengine_core.reforms import Reform
from policyengine_us_data.utils.soi import pe_to_soi, get_soi, get_tracked_soi_row
from policyengine_us_data.utils.ssi_targets import (
SSI_RECIPIENT_TARGETS_2024,
get_ssi_annual_payment_target,
)
from policyengine_us_data.utils.target_variables import (
target_variable_components,
)
MEDICARE_PART_B_PREMIUM_VARIABLE = "medicare_part_b_premium"
# National calibration targets consumed by build_loss_matrix().
# These values are specific to 2024 — they should NOT be applied to
# other years without re-sourcing. They must stay registered here for
# ECPS calibration, in db/etl_national_targets.py for policy_data.db,
# and in calibration/target_config.yaml when the default calibration
# include list should train on them. A future PR should wire
# build_loss_matrix() to read from the database so this duplication can
# be deleted. See PR #488.
BEA_NIPA_WAGES_AND_SALARIES_2024 = 12_387_929_000_000
BEA_NIPA_PROPRIETORS_INCOME_2024 = 2_023_080_000_000
NIPA_PROPRIETORS_INCOME_VARIABLE = (
"self_employment_income_before_lsr"
"+sstb_self_employment_income_before_lsr"
"+farm_operations_income"
"+partnership_s_corp_income"
)
# CBO's individual income tax model computes AGI with "taxable interest
# and ordinary dividends" explicitly excluding qualified dividends, which
# are reported on the next line. Keep this mapped to the tax-return concept
# for filer tax units, not total interest plus all dividends.
TAXABLE_INTEREST_AND_ORDINARY_DIVIDENDS_VARIABLE = (
"taxable_interest_income+non_qualified_dividend_income"
)
# Only use direct NIPA totals when the PolicyEngine variable expression is a
# close microdata concept. BEA personal interest/dividends include imputed
# interest, pension-plan dividends, and trust flows, so those macro totals
# should not directly calibrate tax/CPS interest and dividend variables.
BEA_NIPA_DIRECT_SUM_TARGETS = (
(
"nation/bea/nipa_wages_and_salaries",
"employment_income_before_lsr",
BEA_NIPA_WAGES_AND_SALARIES_2024,
),
(
"nation/bea/nipa_proprietors_income",
NIPA_PROPRIETORS_INCOME_VARIABLE,
BEA_NIPA_PROPRIETORS_INCOME_2024,
),
)
BEA_NIPA_DIRECT_SUM_LOSS_WEIGHT = 1_000.0
BEA_WAGES_AND_SALARIES_LOSS_WEIGHT = 1_000.0
CBO_INCOME_BY_SOURCE_TARGETS = [
("irs_employment_income", "employment_income"),
("self_employment_income", "self_employment_income"),
("taxable_pension_income", "taxable_pension_income"),
("taxable_social_security", "taxable_social_security"),
("qualified_dividend_income", "qualified_dividend_income"),
("loss_limited_net_capital_gains", "net_capital_gain"),
(
TAXABLE_INTEREST_AND_ORDINARY_DIVIDENDS_VARIABLE,
"taxable_interest_and_ordinary_dividends",
),
]
CBO_PROGRAMS = [
"income_tax_positive",
"snap",
"social_security",
"ssi",
"unemployment_compensation",
]
CBO_PARAM_NAME_MAP = {
"income_tax_positive": "income_tax",
}
HARD_CODED_TOTALS = {
MEDICARE_PART_B_PREMIUM_VARIABLE: (
get_beneficiary_paid_medicare_part_b_premiums_target(2024)
),
"tanf": 7_788_317_474.55,
# Table 5A from https://www.irs.gov/statistics/soi-tax-stats-individual-information-return-form-w2-statistics
# shows $38,316,190,000 in Box 7: Social security tips (2018)
# Wages and salaries grew 32% from 2018 to 2023: https://fred.stlouisfed.org/graph/?g=1J0CC
# Assume 40% through 2024
"tip_income": 38e9 * 1.4,
# SSA benefit-type totals for 2024, derived from:
# - Total OASDI: $1,452B (CBO projection)
# - OASI trust fund: $1,227.4B in 2023
# https://www.ssa.gov/OACT/STATS/table4a3.html
# - DI trust fund: $151.9B in 2023
# https://www.ssa.gov/OACT/STATS/table4a3.html
# - SSA 2024 fact sheet type shares: retired+deps=78.5%,
# survivors=11.0%, disabled+deps=10.5%
# https://www.ssa.gov/OACT/FACTS/
# - SSA Annual Statistical Supplement Table 5.A1
# https://www.ssa.gov/policy/docs/statcomps/supplement/2024/5a.html
"social_security_retirement": 1_060e9, # ~73% of total
"social_security_disability": 148e9, # ~10.2% (disabled workers)
"social_security_survivors": 160e9, # ~11.0% (widows, children of deceased)
"social_security_dependents": 84e9, # ~5.8% (spouses/children of retired+disabled)
# Retirement contribution calibration targets.
#
# traditional_ira_contributions: IRS SOI Publication 1304, Table 1.4
# (TY 2023), "IRA payments" deduction — $13.77B (col DU, row
# "All returns, total"). This is the above-the-line deduction
# claimed on returns. The variable flows directly into the ALD
# with no deductibility logic in policyengine-us, so the
# target must match the deduction, not total contributions.
# https://www.irs.gov/statistics/soi-tax-stats-individual-statistical-tables-by-size-of-adjusted-gross-income
"traditional_ira_contributions": RETIREMENT_CONTRIBUTION_TARGETS[
"traditional_ira_contributions"
]["value"],
# traditional_401k_contributions & roth_401k_contributions:
# BEA/FRED National Income Accounts. Total DC employer+employee
# = $815.4B (Y351RC1A027NBEA), employer-only = $247.5B
# (W351RC0A144NBEA), employee elective deferrals = $567.9B.
# Split into traditional/Roth using estimated 15% Roth dollar
# share (Vanguard How America Saves 2024: 18% participation,
# ~15% dollar share; PSCA 67th Annual Survey: 21% participation).
# Traditional: $567.9B × 85% = $482.7B
# Roth: $567.9B × 15% = $85.2B
# https://fred.stlouisfed.org/series/Y351RC1A027NBEA
# https://fred.stlouisfed.org/series/W351RC0A144NBEA
# https://corporate.vanguard.com/content/dam/corp/research/pdf/how_america_saves_report_2024.pdf
"traditional_401k_contributions": 482.7e9,
"roth_401k_contributions": 85.2e9,
# self_employed_pension_contributions: IRS SOI Publication
# 1304, Table 1.4 (TY 2023), "Payments to a Keogh plan" —
# $30.13B (col DM, row "All returns, total"). Includes
# SEP-IRAs, SIMPLE-IRAs, and traditional Keogh/HR-10 plans.
# Targeting the contribution output because policyengine-us applies
# statutory limits before the ALD formula.
# https://www.irs.gov/statistics/soi-tax-stats-individual-statistical-tables-by-size-of-adjusted-gross-income
"self_employed_pension_contributions": RETIREMENT_CONTRIBUTION_TARGETS[
"self_employed_pension_contributions"
]["value"],
# roth_ira_contributions: IRS SOI IRA Accumulation Tables 5 & 6
# (TY 2022, latest published). Total Roth IRA contributions =
# $34.95B (10.04M contributors). Direct administrative source.
# https://www.irs.gov/statistics/soi-tax-stats-accumulation-and-distribution-of-individual-retirement-arrangements
"roth_ira_contributions": RETIREMENT_CONTRIBUTION_TARGETS["roth_ira_contributions"][
"value"
],
}
AGE_BUCKETED_HEALTH_TARGETS = (
(MEDICARE_PART_B_PREMIUM_VARIABLE, "medicare_part_b_premiums"),
)
BLS_CE_TOTALS = {
# BLS Consumer Expenditure Surveys, CE LABSTAT series
# CXU670320LB0101M, aggregate expenditure (AG) in 2024.
# Item: "Babysitting, childcare, daycare, preschool";
# AG is reported in millions of dollars.
"childcare_expenses": 63_092e6,
}
TRANSFER_BALANCE_TARGETS = {
"nation/accounting/alimony_paid_minus_received": (
"alimony_expense",
"alimony_income",
),
"nation/accounting/child_support_paid_minus_received": (
"child_support_expense",
"child_support_received",
),
}
ABSOLUTE_ERROR_SCALE_TARGETS = {
# These are accounting identities, not gross flow targets. Use a
# target-specific scale so zero-dollar targets do not get dropped
# by sparse ECPS or dominate the dense reweighting objective.
target: 1e9
for target in TRANSFER_BALANCE_TARGETS
}
def _add_medicare_enrollment_target(loss_matrix, targets_array, sim, time_period):
label = "nation/cms/medicare_enrollment"
enrolled = sim.calculate(
"medicare_enrolled", map_to="person", period=time_period
).values
loss_matrix[label] = sim.map_result(enrolled.astype(float), "person", "household")
targets_array.append(get_medicare_enrollment_target(time_period))
return targets_array, loss_matrix
def _add_ssi_recipient_targets(loss_matrix, targets_array, sim, time_period):
"""Add SSA SSI recipient count controls by age group."""
ssi = sim.calculate("ssi", map_to="person", period=time_period).values
age = sim.calculate("age", map_to="person", period=time_period).values
receives_ssi = ssi > 0
for key, target in SSI_RECIPIENT_TARGETS_2024.items():
in_group = receives_ssi.copy()
for operation, value in target["age_constraints"]:
threshold = float(value)
if operation == "<":
in_group &= age < threshold
elif operation == ">=":
in_group &= age >= threshold
else:
raise ValueError(f"Unsupported SSI age constraint {operation!r}")
label = f"nation/ssa/ssi_recipients/{key}"
loss_matrix[label] = sim.map_result(
in_group.astype(float),
"person",
"household",
)
targets_array.append(target["person_count"])
return targets_array, loss_matrix
def _cbo_program_target_value(sim, variable_name: str, time_period):
if variable_name == "ssi":
ssi_target = get_ssi_annual_payment_target(time_period)
if ssi_target is not None:
return ssi_target["value"]
param_name = CBO_PARAM_NAME_MAP.get(variable_name, variable_name)
return sim.tax_benefit_system.parameters(time_period).calibration.gov.cbo._children[
param_name
]
ACA_SPENDING_TARGETS = {
2024: 98e9,
}
ACA_ENROLLMENT_TARGETS = {
2024: 19_743_689,
}
MEDICAID_SPENDING_TARGETS = {
2024: 9e11,
# CMS projects Medicaid spending growth of 7.4% in 2025.
# Apply that projection to 2024 Medicaid spending of $931.7B.
# Source: CMS National Health Expenditure projections, 2024-2033.
2025: 931.7e9 * 1.074,
}
MEDICAID_ENROLLMENT_TARGETS = {
2024: 72_429_055,
}
LOW_AGI_INVESTMENT_INCOME_SOI_VARIABLES = {
"capital_gains_gross",
"long_term_capital_gains",
"ordinary_dividends",
"qualified_dividends",
"taxable_interest_income",
}
AGI_LEVEL_TARGETED_VARIABLES = (
"adjusted_gross_income",
"count",
"employment_income",
"business_net_profits",
"capital_gains_gross",
"long_term_capital_gains",
"ordinary_dividends",
"partnership_and_s_corp_income",
"qualified_dividends",
"taxable_interest_income",
"total_pension_income",
"total_social_security",
)
AGGREGATE_LEVEL_TARGETED_VARIABLES = (
"business_net_losses",
"capital_gains_distributions",
"capital_gains_losses",
"estate_income",
"estate_losses",
"exempt_interest",
"ira_distributions",
"partnership_and_s_corp_losses",
"rent_and_royalty_net_income",
"rent_and_royalty_net_losses",
# The current SOI source only exposes taxable-only aggregate targets for
# mortgage-interest deductions, not the AGI-bin detail used above.
"mortgage_interest_deductions",
# Keep the legacy loss matrix aligned with the national QBI amount and
# claimant-count controls used by the target-config calibration path.
"qualified_business_income_deduction",
"taxable_pension_income",
"taxable_social_security",
"unemployment_compensation",
)
IRS_SOI_AGGREGATE_TARGETS = [
# This complements the net capital gains target with the source-specific
# control used by downstream preferential-rate reforms.
("long_term_capital_gains", ["long_term_capital_gains"], "long_term_capital_gains"),
]
EITC_NATIONAL_GEO_ID = "0100000US"
EITC_INTERNATIONAL_GEO_ID = "INTL"
def fmt(x):
if x == -np.inf:
return "-inf"
if x == np.inf:
return "inf"
if x < 1e3:
return f"{x:.0f}"
if x < 1e6:
return f"{x / 1e3:.0f}k"
if x < 1e9:
return f"{x / 1e6:.0f}m"
return f"{x / 1e9:.1f}bn"
def _target_expression_entity(sim, variable):
entities = {
sim.tax_benefit_system.variables[component].entity.key
for component in target_variable_components(variable)
}
if len(entities) != 1:
raise ValueError(
"Additive target expressions must use variables with one "
f"entity; got {variable!r} with entities {entities}"
)
return entities.pop()
def _calculate_expression(sim, variable, map_to, period):
result = None
for component in target_variable_components(variable):
values = sim.calculate(component, map_to=map_to, period=period).values
result = values if result is None else result + values
return result
def _calculate_filer_target_values(sim, variable, time_period):
entity = _target_expression_entity(sim, variable)
values = _calculate_expression(sim, variable, entity, time_period)
is_filer = (
sim.calculate("tax_unit_is_filer", map_to=entity, period=time_period).values > 0
)
return sim.map_result(values * is_filer, entity, "household")
def _calculate_household_target_values(sim, variable, time_period):
return _calculate_expression(sim, variable, "household", time_period)
def _parse_constraint_value(value):
if value == "True":
return True
if value == "False":
return False
try:
return int(value)
except (TypeError, ValueError):
try:
return float(value)
except (TypeError, ValueError):
return value
def _apply_constraint(values, operation: str, raw_value: str):
if operation == "in":
allowed_values = [part.strip() for part in raw_value.split("|")]
return np.isin(values, allowed_values)
value = _parse_constraint_value(raw_value)
if operation in ("equals", "==", "="):
return values == value
if operation in ("greater_than", ">"):
return values > value
if operation in ("greater_than_or_equal", ">="):
return values >= value
if operation in ("less_than", "<"):
return values < value
if operation in ("less_than_or_equal", "<="):
return values <= value
if operation in ("not_equals", "!=", "<>"):
return values != value
raise ValueError(f"Unsupported stratum constraint operation: {operation}")
def _geo_label_from_ucgid(ucgid_str: str) -> str:
if ucgid_str in (None, "", "0100000US"):
return "nation"
return f"geo/{ucgid_str}"
def _add_liheap_targets_from_db(loss_matrix, targets_list, sim, time_period):
db_path = STORAGE_FOLDER / "calibration" / "policy_data.db"
if not db_path.exists():
return targets_list, loss_matrix
query = """
SELECT
t.target_id,
t.variable,
t.value AS target_value,
s.notes,
sc.constraint_variable,
sc.operation,
sc.value AS constraint_value
FROM targets t
JOIN strata s
ON s.stratum_id = t.stratum_id
JOIN stratum_constraints sc
ON sc.stratum_id = s.stratum_id
WHERE
t.active = 1
AND t.reform_id = 0
AND t.period = ?
AND s.notes LIKE '%LIHEAP%'
ORDER BY t.target_id
"""
with sqlite3.connect(db_path) as conn:
target_rows = pd.read_sql_query(query, conn, params=[time_period])
if target_rows.empty:
return targets_list, loss_matrix
household_values_cache = {
"household_weight": sim.calculate("household_weight").values
}
def get_household_values(variable: str):
if variable not in household_values_cache:
household_values_cache[variable] = sim.calculate(
variable,
map_to="household",
).values
return household_values_cache[variable]
n_households = len(household_values_cache["household_weight"])
for _, target_df in target_rows.groupby("target_id", sort=False):
mask = np.ones(n_households, dtype=bool)
for row in target_df.itertuples(index=False):
if (
row.constraint_variable == "ucgid_str"
and row.constraint_value == "0100000US"
):
continue
values = get_household_values(row.constraint_variable)
mask &= _apply_constraint(
values,
row.operation,
row.constraint_value,
)
variable = target_df["variable"].iat[0]
if variable == "household_count":
metric = mask.astype(float)
else:
metric = np.where(mask, get_household_values(variable), 0.0)
ucgid_constraints = target_df.loc[
target_df.constraint_variable == "ucgid_str", "constraint_value"
]
geo_label = _geo_label_from_ucgid(
ucgid_constraints.iat[0] if not ucgid_constraints.empty else None
)
label = f"{geo_label}/db/liheap/{variable}"
loss_matrix[label] = metric
targets_list.append(target_df["target_value"].iat[0])
logging.info(
f"Loaded {target_rows['target_id'].nunique()} LIHEAP targets from the local targets DB"
)
return targets_list, loss_matrix
def _best_available_year(targets_by_year: dict, requested_year: int) -> int:
if not targets_by_year:
raise ValueError("No target years available")
eligible_years = [year for year in targets_by_year if year <= requested_year]
if not eligible_years:
return min(targets_by_year)
return max(eligible_years)
def _load_yeared_target_csv(
prefix: str, requested_year: int
) -> tuple[pd.DataFrame, int]:
candidates = {}
for path in CALIBRATION_FOLDER.glob(f"{prefix}_*.csv"):
suffix = path.stem.removeprefix(f"{prefix}_")
if suffix.isdigit():
candidates[int(suffix)] = path
data_year = _best_available_year(candidates, requested_year)
return pd.read_csv(candidates[data_year]), data_year
def _load_aca_spending_and_enrollment_targets(
requested_year: int,
) -> tuple[pd.DataFrame, int]:
return _load_yeared_target_csv("aca_spending_and_enrollment", requested_year)
def _load_aca_ptc_state_targets(requested_year: int) -> pd.DataFrame | None:
return load_aca_ptc_state_targets(requested_year)
def _load_medicaid_enrollment_targets(
requested_year: int,
) -> tuple[pd.DataFrame, int]:
return _load_yeared_target_csv("medicaid_enrollment", requested_year)
def _get_aca_national_targets(requested_year: int) -> tuple[float, float, int]:
targets, data_year = _load_aca_spending_and_enrollment_targets(requested_year)
aca_ptc_state = _load_aca_ptc_state_targets(requested_year)
if aca_ptc_state is not None:
return (
float(aca_ptc_state["TotalPTCAmount"].sum()),
float(targets["enrollment"].sum()),
data_year,
)
if data_year in ACA_SPENDING_TARGETS and data_year in ACA_ENROLLMENT_TARGETS:
return (
ACA_SPENDING_TARGETS[data_year],
ACA_ENROLLMENT_TARGETS[data_year],
data_year,
)
# Newer CMS ACA state files encode monthly total APTC spending by state and
# APTC enrollment counts. Annualize the spending for the national target.
return (
float(targets["spending"].sum() * 12),
float(targets["enrollment"].sum()),
data_year,
)
def _get_medicaid_national_targets(requested_year: int) -> tuple[float, float, int]:
targets, data_year = _load_medicaid_enrollment_targets(requested_year)
spending_year = _best_available_year(MEDICAID_SPENDING_TARGETS, data_year)
enrollment_target = MEDICAID_ENROLLMENT_TARGETS.get(
data_year, float(targets["enrollment"].sum())
)
return (
MEDICAID_SPENDING_TARGETS[spending_year],
enrollment_target,
data_year,
)
def _skip_unverified_target(value) -> bool:
"""Return True when a CSV value is a placeholder instead of a real target.
CSV rows containing "[TO BE CALCULATED]" (or an empty cell) are
intentionally skipped. This matches the repo-wide convention of
``[TO BE CALCULATED]`` for unverified IRS extractions and keeps the
optimizer from consuming fabricated numbers. See CLAUDE.md §
"NEVER FABRICATE DATA OR RESULTS".
"""
if value is None:
return True
if isinstance(value, float) and pd.isna(value):
return True
if isinstance(value, str) and value.strip() in (
"",
"[TO BE CALCULATED]",
"TBD",
):
return True
return False
def _load_eitc_claim_controls(requested_year: int) -> tuple[pd.DataFrame, int]:
"""Load the best available IRS EITC claim controls for a target year.
The checked-in control file uses the IRS EITC Central state table, whose
latest release can lead detailed SOI geography workbooks. It measures net
EITC credited on returns, which is the claim concept closest to the
microsim's ``eitc`` variable.
"""
requested_year = int(requested_year)
path = CALIBRATION_FOLDER / "eitc_claim_controls.csv"
controls = pd.read_csv(path, comment="#")
years = {int(year): year for year in controls["year"].unique()}
data_year = _best_available_year(years, requested_year)
return controls[controls["year"] == data_year].copy(), data_year
def _domestic_eitc_claim_totals(controls: pd.DataFrame) -> tuple[float, float]:
"""Return national EITC controls excluding the international row.
The local calibration universe assigns US states and DC, but not the IRS
table's separate "International" row. Subtract it from the published
national line so state and AGI-shape targets describe the same universe.
"""
national = controls[controls["GEO_ID"] == EITC_NATIONAL_GEO_ID]
if national.empty:
state_rows = controls[controls["GEO_ID"].str.startswith("0400000US")]
return float(state_rows["Returns"].sum()), float(state_rows["Amount"].sum())
returns = float(national["Returns"].iloc[0])
amount = float(national["Amount"].iloc[0])
international = controls[controls["GEO_ID"] == EITC_INTERNATIONAL_GEO_ID]
if not international.empty:
returns -= float(international["Returns"].iloc[0])
amount -= float(international["Amount"].iloc[0])
return returns, amount
def _get_eitc_claim_targets(
requested_year: int,
sim,
) -> tuple[pd.DataFrame, float, float, int]:
"""Return state rows and national totals for EITC claim calibration.
For the latest IRS EITC Central year, use the published claim controls.
For later years, roll the control year forward transparently: counts by
total population and dollar amounts by CPI-U. Do not use Treasury or CBO
outlay series here; those are fiscal-year refundable-outlay concepts.
"""
requested_year = int(requested_year)
controls, data_year = _load_eitc_claim_controls(requested_year)
params = sim.tax_benefit_system.parameters
population = params.calibration.gov.census.populations.total
cpi = params.gov.bls.cpi.cpi_u
returns_uprating = float(population(requested_year) / population(data_year))
amount_uprating = float(cpi(requested_year) / cpi(data_year))
national_returns, national_amount = _domestic_eitc_claim_totals(controls)
national_returns *= returns_uprating
national_amount *= amount_uprating
state_targets = controls[controls["GEO_ID"].str.startswith("0400000US")].copy()
state_returns = float(state_targets["Returns"].sum())
state_amount = float(state_targets["Amount"].sum())
if state_returns:
state_targets["Returns"] = (
state_targets["Returns"].astype(float) * national_returns / state_returns
)
if state_amount:
state_targets["Amount"] = (
state_targets["Amount"].astype(float) * national_amount / state_amount
)
return state_targets, national_returns, national_amount, data_year
def _get_eitc_shape_scaling(
national_returns: float,
national_amount: float,
) -> tuple[float, float]:
"""Scale detailed TY2022 SOI EITC shape cells to claim controls."""
eitc_agi_path = CALIBRATION_FOLDER / "eitc_by_agi_and_children.csv"
eitc_by_agi = pd.read_csv(eitc_agi_path, comment="#")
returns_total = float(eitc_by_agi["returns"].sum())
amount_total = float(eitc_by_agi["amount"].sum())
returns_scaling = national_returns / returns_total if returns_total else 1.0
amount_scaling = national_amount / amount_total if amount_total else 1.0
return returns_scaling, amount_scaling
def _add_state_eitc_targets(
loss_matrix: pd.DataFrame,
targets_list: list,
sim,
amount_uprating: float,
returns_uprating: float,
state_targets: pd.DataFrame | None = None,
):
"""Add per-state EITC returns and amount targets.
By default this consumes IRS SOI Historical Table 2 (``eitc_state.csv``).
``build_loss_matrix`` passes the newer IRS EITC Central state controls
instead, with the rounded state rows normalized to the published domestic
national control. ``amount_uprating`` and ``returns_uprating`` are generic
scale factors; they are not tied to Treasury outlays.
"""
if state_targets is None:
eitc_state_path = CALIBRATION_FOLDER / "eitc_state.csv"
if not eitc_state_path.exists():
return targets_list, loss_matrix
eitc_state = pd.read_csv(eitc_state_path, comment="#")
else:
eitc_state = state_targets.copy()
eitc = sim.calculate("eitc").values # tax-unit level
eitc_returns_tu = (eitc > 0).astype(float)
state = sim.calculate("state_code", map_to="person").values
state = sim.map_result(state, "person", "household", how="value_from_first_person")
state_fips = pd.Series(state).apply(lambda s: STATE_ABBR_TO_FIPS.get(s, None))
eitc_returns_hh = sim.map_result(eitc_returns_tu, "tax_unit", "household")
eitc_amount_hh = sim.map_result(eitc, "tax_unit", "household")
for _, row in eitc_state.iterrows():
fips = str(row["GEO_ID"])[-2:]
in_state = (state_fips == fips).to_numpy()
returns_label = f"nation/irs/eitc/returns/state_{fips}"
loss_matrix[returns_label] = np.where(in_state, eitc_returns_hh, 0.0)
if not _skip_unverified_target(row["Returns"]):
targets_list.append(float(row["Returns"]) * returns_uprating)
else:
# Remove the column we just added since we aren't appending a
# target for it; otherwise loss_matrix/targets_array go out of
# alignment.
del loss_matrix[returns_label]
amount_label = f"nation/irs/eitc/amount/state_{fips}"
loss_matrix[amount_label] = np.where(in_state, eitc_amount_hh, 0.0)
if not _skip_unverified_target(row["Amount"]):
targets_list.append(float(row["Amount"]) * amount_uprating)
else:
del loss_matrix[amount_label]
return targets_list, loss_matrix
def _add_state_aca_ptc_targets(
loss_matrix: pd.DataFrame,
targets_list: list,
sim,
time_period: int,
):
"""Add per-state total ACA PTC return and amount targets from IRS SOI."""
aca_ptc_state = _load_aca_ptc_state_targets(time_period)
if aca_ptc_state is None:
return targets_list, loss_matrix
aca_ptc = sim.calculate("aca_ptc", period=time_period).values
aca_ptc_returns_tu = (aca_ptc > 0).astype(float)
aca_ptc_returns_hh = sim.map_result(
aca_ptc_returns_tu,
"tax_unit",
"household",
)
aca_ptc_amount_hh = sim.map_result(aca_ptc, "tax_unit", "household")
state = sim.calculate("state_code", map_to="person").values
state = sim.map_result(state, "person", "household", how="value_from_first_person")
state_fips = pd.Series(state).apply(lambda s: STATE_ABBR_TO_FIPS.get(s, None))
for row in aca_ptc_state.itertuples(index=False):
fips = str(row.GEO_ID)[-2:]
in_state = (state_fips == fips).to_numpy()
returns_label = f"nation/irs/aca_ptc/returns/state_{fips}"
loss_matrix[returns_label] = np.where(in_state, aca_ptc_returns_hh, 0.0)
if not _skip_unverified_target(row.Returns):
targets_list.append(float(row.Returns))
else:
del loss_matrix[returns_label]
amount_label = f"nation/irs/aca_ptc/amount/state_{fips}"
loss_matrix[amount_label] = np.where(in_state, aca_ptc_amount_hh, 0.0)
if not _skip_unverified_target(row.TotalPTCAmount):
targets_list.append(float(row.TotalPTCAmount))
else:
del loss_matrix[amount_label]
return targets_list, loss_matrix
def _add_eitc_by_agi_and_children_targets(
loss_matrix: pd.DataFrame,
targets_list: list,
sim,
amount_uprating: float,
returns_uprating: float,
):
"""Add per-(qualifying-children x AGI bucket) EITC returns and amount
targets.
Sourced from IRS SOI Publication 1304 Table 2.5
(``eitc_by_agi_and_children.csv``). The SOI table buckets qualifying
children as 0, 1, 2, "3 or more" (coded as ``count_children = 3``)
and uses the half-open [lower, upper) AGI convention.
The loss-matrix labels embed child count and AGI bucket so the
optimizer can distinguish, e.g., EITC claims by 2-child families
with AGI in [$20k, $25k) from 2-child families with AGI in
[$25k, $30k).
"""
eitc_agi_path = CALIBRATION_FOLDER / "eitc_by_agi_and_children.csv"
if not eitc_agi_path.exists():
return targets_list, loss_matrix
eitc_by_agi = pd.read_csv(eitc_agi_path, comment="#")
eitc_by_agi["agi_lower"] = eitc_by_agi["agi_lower"].astype(float)
eitc_by_agi["agi_upper"] = eitc_by_agi["agi_upper"].astype(float)
eitc_eligible_children = sim.calculate("eitc_child_count").values
eitc = sim.calculate("eitc").values
agi_tu = sim.calculate("adjusted_gross_income").values
for _, row in eitc_by_agi.iterrows():
count_children = int(row["count_children"])
agi_lower = float(row["agi_lower"])
agi_upper = float(row["agi_upper"])
if count_children < 3:
meets_child_criteria = eitc_eligible_children == count_children
else:
meets_child_criteria = eitc_eligible_children >= count_children
in_agi = (agi_tu >= agi_lower) & (agi_tu < agi_upper)
in_bucket = meets_child_criteria & in_agi
slug = f"c{count_children}_{fmt(agi_lower)}_{fmt(agi_upper)}"
returns_label = f"nation/irs/eitc/returns/{slug}"
loss_matrix[returns_label] = sim.map_result(
(eitc > 0) * in_bucket,
"tax_unit",
"household",
)
if not _skip_unverified_target(row["returns"]):
targets_list.append(float(row["returns"]) * returns_uprating)
else:
del loss_matrix[returns_label]
amount_label = f"nation/irs/eitc/amount/{slug}"
loss_matrix[amount_label] = sim.map_result(
eitc * in_bucket,
"tax_unit",
"household",
)
if not _skip_unverified_target(row["amount"]):
targets_list.append(float(row["amount"]) * amount_uprating)
else:
del loss_matrix[amount_label]
return targets_list, loss_matrix
def _add_ctc_targets(loss_matrix, targets_list, sim, time_period):
"""Add legacy national CTC component amount and recipient-count targets."""
for variable in ("refundable_ctc", "non_refundable_ctc"):
target = get_national_geography_soi_target(variable, time_period)
label = f"nation/irs/{variable}"
loss_matrix[label] = sim.calculate(variable, map_to="household").values
if any(pd.isna(loss_matrix[label])):
raise ValueError(f"Missing values for {label}")
targets_list.append(target["amount"])
label = f"nation/irs/{variable}_count"
amount = sim.calculate(variable).values
loss_matrix[label] = sim.map_result(
(amount > 0).astype(float),
"tax_unit",
"household",
)
if any(pd.isna(loss_matrix[label])):
raise ValueError(f"Missing values for {label}")
targets_list.append(target["count"])
return targets_list, loss_matrix
def _get_refundable_aotc_target(time_period: int) -> dict:
"""Return national refundable AOTC amount and count from IRS SOI Table 3.3."""
variable = "refundable_american_opportunity_credit"
amount_row = get_tracked_soi_row(variable, time_period, count=False)
count_row = get_tracked_soi_row(variable, time_period, count=True)
amount_year = int(amount_row["Year"])
count_year = int(count_row["Year"])
if amount_year != count_year:
raise ValueError(
f"AOTC count and amount source years differ: {count_year} vs {amount_year}"
)
return {
"source_year": amount_year,
"amount": float(amount_row["Value"]),
"count": float(count_row["Value"]),
}
def _add_aotc_targets(loss_matrix, targets_list, sim, time_period):
"""Add legacy national refundable AOTC amount and recipient-count targets."""
variable = "refundable_american_opportunity_credit"
target = _get_refundable_aotc_target(time_period)
label = f"nation/irs/{variable}"
loss_matrix[label] = sim.calculate(
variable, map_to="household", period=time_period
).values
targets_list.append(target["amount"])
tax_unit_values = sim.calculate(variable, period=time_period).values
loss_matrix[f"{label}_count"] = sim.map_result(
(tax_unit_values > 0).astype(float),
"tax_unit",
"household",
)
targets_list.append(target["count"])
return targets_list, loss_matrix
def _get_education_credit_target(time_period: int) -> dict:
"""Return national nonrefundable education credit target from IRS SOI Table 3.3."""
variable = "education_tax_credits"
amount_row = get_tracked_soi_row(variable, time_period, count=False)
count_row = get_tracked_soi_row(variable, time_period, count=True)
amount_year = int(amount_row["Year"])
count_year = int(count_row["Year"])
if amount_year != count_year:
raise ValueError(
f"Education credit count and amount source years differ: {count_year} vs {amount_year}"
)
return {
"source_year": amount_year,
"amount": float(amount_row["Value"]),
"count": float(count_row["Value"]),
}
def _add_education_credit_targets(loss_matrix, targets_list, sim, time_period):
"""Add legacy national nonrefundable education credit amount and count targets."""
variable = "education_tax_credits"
target = _get_education_credit_target(time_period)
label = f"nation/irs/{variable}"
loss_matrix[label] = sim.calculate(
variable, map_to="household", period=time_period
).values
targets_list.append(target["amount"])
tax_unit_values = sim.calculate(variable, period=time_period).values
loss_matrix[f"{label}_count"] = sim.map_result(
(tax_unit_values > 0).astype(float),
"tax_unit",
"household",
)
targets_list.append(target["count"])
return targets_list, loss_matrix
def _add_real_estate_tax_targets(loss_matrix, targets_list, sim, time_period):
"""Add IRS SOI real-estate-tax amount and count targets.
These targets correspond to itemizing filers with positive Schedule A
real-estate-tax amounts from the IRS geography file, not total
owner-occupied property-tax payments.
"""
target = get_national_geography_soi_target("real_estate_taxes", time_period)
real_estate_taxes_person = sim.calculate(
"real_estate_taxes",