-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathraking_bisg.py
1699 lines (1426 loc) · 58.3 KB
/
raking_bisg.py
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
"""
this module includes the primary statistical tools of this repository. it contains codes for creating
various predictions for (surname, county) pairs in various states in the united states.
the primary output of this code is a pandas dataframe (called df_agg), for one state,
that has various "predictions" of race/ethnicity given surname and geolocation. Each row
corresponds to one (surname, county) pair.
Functions
---------
make_df_agg
construct the dataframe of race/ethnicity predictions for a given state
load_voter_file
get the voter file
make_calib_map
calibration map by solving an optimization problem
dist_summary
pandas dataframe that has several useful subpopulation distributions
one_calib
a plot of tygert cumulative miscalibration
ll_tables
tables with negative log-likelihood
l1_l2_tables
tables with l1, l2 errors
get_v_given_r
(proportional to) probability of being a voter given race
subpopulation_preds
predictions for subpopulation estimates over geographical regions
ipf2d
two-way raking
ipf3d
three-way raking
two_way_tables
build the three two-way margins of (surname, geolocation, race) table
"""
import os
import numpy as np
import pandas as pd
from tabulate import tabulate
import cvxpy as cp
import fields
import process_census
import process_cps
import washington_vf as wa_vf
import vermont_vf as vt_vf
import oklahoma_vf as ok_vf
import ohio_vf
import north_carolina_vf as nc_vf
import new_york_vf as ny_vf
import florida_vf
# ignore certain numpy errors
np.seterr(divide="ignore", invalid="ignore")
def main():
state = "fl"
year = 2020
df_agg = make_df_agg(state, year, subsample=False, load=True)
df_cps_reg_voters = process_cps.cps_geo_race(state, year, voters=True)
calib_map = make_calib_map(df_cps_reg_voters, df_agg, verbose=False)
# table for rural and urban counties
df_state, df_rural, df_urban = plotting.vf_only_rural_tables(df_agg, cols = fields.BISG_BAYES_COLS, calib_map=calib_map)
print(tabulate(df_state, headers="keys"))
print(tabulate(df_urban, headers="keys"))
print(tabulate(df_rural, headers="keys"))
df_state, df_rural, df_urban = plotting.vf_only_rural_tables(df_agg, cols = fields.RAKE_COLS, calib_map=calib_map)
print(tabulate(df_state, headers="keys"))
print(tabulate(df_urban, headers="keys"))
print(tabulate(df_rural, headers="keys"))
# voterfile_state_table(filename, df_rural.loc['BISG', :].values, df_rural.loc['True', :].values)
quit()
# BISG estimate for race distribution in rural and non-rural counties
df_tmp = df_agg[['rural'] + fields.BISG_BAYES_COLS].groupby('rural').sum().astype(int)
df_tmp = df_tmp.div(df_tmp.sum(axis=1), axis=0)
# print(tabulate(df_tmp, headers="keys", tablefmt="psql"))
# total population
df_tmp = df_agg[fields.BISG_BAYES_COLS].sum().astype(int)
df_tmp = df_tmp.div(df_tmp.sum())
# print(df_tmp)
# print(tabulate(df_tmp, headers="keys", tablefmt="psql"))
# true race distribution rural and non-rural counties
df_tmp = df_agg[['rural'] + fields.VF_RACES].groupby('rural').sum().astype(int)
df_tmp = df_tmp.div(df_tmp.sum(axis=1), axis=0)
# print(tabulate(df_tmp, headers="keys", tablefmt="psql"))
# total population
df_tmp = df_agg[fields.VF_RACES].sum().astype(int)
df_tmp = df_tmp.div(df_tmp.sum())
# print(df_tmp)
# voter file only BISG for the full state
cols = fields.VF_BISG
preds_fl, true_pops_fl, true_probs1 = subpopulation_preds(
df_agg, cols, region="region", calib_map=None
)
preds_fl = np.sum(preds_fl, axis=0).astype(int)
true_pops_fl = np.sum(true_pops_fl, axis=0)
preds_fl_pct = preds_fl / preds_fl.sum()
true_pops_fl_pct = true_pops_fl / true_pops_fl.sum()
# print(f'fl, voter file BISG: {preds_fl}')
# print(f'fl, voter file true: {true_pops_fl}')
# print(f'fl, voter file BISG: {preds_fl / preds_fl.sum()}')
# print(f'fl, voter file true: {true_pops_fl / true_pops_fl.sum()}')
df_fl = pd.DataFrame(data=np.vstack((preds_fl, true_pops_fl, preds_fl_pct, true_pops_fl_pct,
preds_fl - true_pops_fl, (preds_fl - true_pops_fl)/true_pops_fl)),
columns=fields.PRETTY_PRINT, index=['BISG', 'True', 'BISG %', 'True %', 'Error', 'Relative Error'])
print('voter file only BISG and true for full state')
print(tabulate(df_fl, headers="keys", tablefmt="psql"))
# voter file only rural
cols = fields.VF_BISG
preds_rural, true_pops_rural, true_probs1 = subpopulation_preds(
df_agg[df_agg['rural']], cols, region="region", calib_map=None
)
preds_rural = np.sum(preds_rural, axis=0).astype(int)
true_pops_rural = np.sum(true_pops_rural, axis=0)
preds_rural_pct = preds_rural / preds_rural.sum()
true_pops_rural_pct = true_pops_rural / true_pops_rural.sum()
df_rural = pd.DataFrame(data=np.vstack((preds_rural, true_pops_rural, preds_rural_pct, true_pops_rural_pct,
preds_rural - true_pops_rural,
(preds_rural - true_pops_rural) / true_pops_rural)),
columns=fields.PRETTY_PRINT, index=['BISG', 'True', 'BISG %', 'True %', 'Error', 'Relative Error'])
print(tabulate(df_rural, headers="keys", tablefmt="psql"))
preds_urban, true_pops_urban, true_probs_urban = subpopulation_preds(
df_agg[~df_agg['rural']], cols, region="region", calib_map=None
)
preds_urban = np.sum(preds_urban, axis=0).astype(int)
true_pops_urban = np.sum(true_pops_urban, axis=0)
preds_urban_pct = preds_urban / preds_urban.sum()
true_pops_urban_pct = true_pops_urban / true_pops_urban.sum()
df_urban = pd.DataFrame(data=np.vstack((preds_urban, true_pops_urban, preds_urban_pct, true_pops_urban_pct,
preds_urban - true_pops_urban,
(preds_urban - true_pops_urban) / true_pops_urban)),
columns=fields.PRETTY_PRINT, index=['BISG', 'True', 'BISG %', 'True %', 'Error', 'Relative Error'])
print(tabulate(df_urban, headers="keys", tablefmt="psql"))
# bar plot
fig, axs = plt.subplots(1, 3, figsize=(20, 6))
# first plot, mean absolute deviation
labels = fields.PRETTY_PRINT
# ignore "other" category
labels = labels[:5]
preds1 = preds1[:, :5]
preds2 = preds2[:, :5]
true_pops2 = true_pops2[:, :5]
# x axis label locations
xlocs = np.arange(len(labels))
width = 0.35 # the width of the bars
# average errors
avg_errs1 = df_urban.loc['Relative Error']
avg_errs2 = preds2.sum(axis=0) / true_pops2.sum(axis=0) - 1
max_err = np.max(np.abs((avg_errs1, avg_errs2)))
# if errors are 0, make them small, but non-zero so that a small bar appears
fac = 0.004
avg_errs1[np.abs(avg_errs1) < max_err * fac] = max_err * fac
avg_errs2[np.abs(avg_errs2) < max_err * fac] = max_err * fac
axs[0].bar(xlocs - width / 2, avg_errs1, width, label=label1, color="b")
axs[0].bar(xlocs + width / 2, avg_errs2, width, label=label2, color="r")
axs[0].bar(labels, 0)
# Add some text for labels, title and custom x-axis tick labels, etc.
axs[0].set_xticks(xlocs, labels)
axs[0].legend(fontsize=26, frameon=False)
ymax = np.max(np.abs([avg_errs1, avg_errs2])) + 0.05
axs[0].axis(ymin=-ymax, ymax=ymax)
axs[0].tick_params(axis="x", labelsize=18)
axs[0].tick_params(axis="y", labelsize=18)
# titles
axs[0].set_title(f"Average Error", fontsize=35)
fig.tight_layout(h_pad=6)
fig.savefig(filename, bbox_inches="tight", dpi=fig.dpi)
quit()
# predictions
df_cps_reg_voters = process_cps.cps_geo_race(state, year, voters=True)
calib_map = make_calib_map(df_cps_reg_voters, df_agg, verbose=False)
# rural
cols = fields.BISG_BAYES_COLS
bisg_preds, true_pops_rural, true_probs1 = subpopulation_preds(
df_agg[~df_agg['rural']], cols, region="region", calib_map=calib_map
)
bisg_preds = np.sum(bisg_preds, axis=0).astype(int)
true_pops_rural = np.sum(true_pops_rural, axis=0)
bisg_preds_pct = bisg_preds / bisg_preds.sum()
true_pops_rural_pct = true_pops_rural / true_pops_rural.sum()
print(f'rural, BISG: {bisg_preds / bisg_preds.sum()}')
print(f'rural, true: {true_pops_rural / true_pops_rural.sum()}')
df_bisg = pd.DataFrame(data=np.vstack((bisg_preds, true_pops_rural, bisg_preds_pct, true_pops_rural_pct,
bisg_preds - true_pops_rural,
(bisg_preds - true_pops_rural) / true_pops_rural)),
columns=fields.PRETTY_PRINT, index=['BISG', 'True', 'BISG %', 'True %', 'Error', 'Relative Error'])
# print(tabulate(df_rural, headers="keys", tablefmt="psql"))
cols = fields.RAKE_COLS
rake_preds, true, _ = subpopulation_preds(
df_agg[~df_agg['rural']], cols, region="region", calib_map=calib_map
)
rake_preds = np.sum(rake_preds, axis=0).astype(int)
true = np.sum(true, axis=0)
rake_preds_pct = rake_preds / rake_preds.sum()
true_pct = true / true.sum()
df_rake = pd.DataFrame(data=np.vstack((rake_preds, true, rake_preds_pct, true_pct,
rake_preds - true, (rake_preds - true) / true)),
columns=fields.PRETTY_PRINT, index=['rake', 'True', 'rake %',
'True %', 'rake error', 'rake relative error'])
df_rural = pd.concat([df_bisg, df_rake])
print(tabulate(df_rural, headers="keys", tablefmt="psql"))
quit()
# urban
cols = fields.VF_BISG
preds_urban, true_pops_urban, true_probs1 = subpopulation_preds(
df_agg[~df_agg['rural']], cols, region="region", calib_map=None
)
preds_urban = np.sum(preds_urban, axis=0).astype(int)
true_pops_urban = np.sum(true_pops_urban, axis=0)
# print(f'urban, voter file BISG: {preds_urban}')
# print(f'urban, voter file true: {true_pops_urban}')
print(f'urban, voter file BISG: {preds_urban / preds_urban.sum()}')
print(f'urban, voter file true: {true_pops_urban / true_pops_urban.sum()}')
quit()
cols = fields.VF_BISG
preds1, true_pops1, true_probs1 = subpopulation_preds(
df_agg, cols, region="county", calib_map=None
)
cols1 = ['preds_' + race for race in fields.RACES]
cols2 = ['true_' + race for race in fields.RACES]
cols3 = ['prop_' + race for race in fields.RACES]
preds_df = pd.DataFrame(data=np.hstack((preds1, true_pops1, true_probs1)), columns=cols1 + cols2 + cols3)
cols_errs = ['rel_err_' + race for race in fields.RACES]
preds_df[cols_errs] = (preds_df[cols1].values - preds_df[cols2].values) / preds_df[cols2].values
preds_df = preds_df[preds_df['prop_nh_white'] > 0.85]
# preds_df = preds_df[cols_errs]
err_tot = (preds_df[cols1].sum(axis=0).values - preds_df[cols2].sum(axis=0).values) / preds_df[cols2].sum(axis=0).values
print(err_tot)
print(tabulate(preds_df, headers="keys", tablefmt="psql"))
print(preds_df.shape)
def write_dataverse_files():
"""
write df_agg dataframes that are put online. these only include names that appear at least
five times in the state.
"""
state = "nc"
year = 2020
states = ["fl", "ny", "nc", "nc", "oh", "ok", "vt", "wa"]
years = [2020, 2020, 2020, 2010, 2020, 2020, 2020, 2020]
for state, year in zip(states, years):
filename = f"generated_data/df_agg_{state}{year}.feather"
df_agg = pd.read_feather(filename)
df_agg = df_agg.drop(columns=["vf_tot"])
# cols_to_keep = ['name', 'county'] + fields.BISG_CEN_COUNTY_COLS + fields.BISG_BAYES_COLS + fields.RAKE_COLS
# df_agg = df_agg[cols_to_keep]
# filter out names that don't appear frequently enough (~1mil)
min_names = 5
df_tmp = df_agg.groupby(["name"]).size()
df_tmp = df_tmp.to_frame("count").reset_index()
df_tmp = df_tmp.loc[(df_tmp["count"] >= min_names), :]
names = df_tmp["name"].unique()
df_agg = df_agg.loc[df_agg["name"].isin(names), :]
print(df_agg.shape)
file_out = f"generated_data/df_agg_{state}{year}_dataverse.pkl"
df_agg.to_pickle(file_out)
def make_df_vf_sub(df_vf, df_cps_reg_voters, verbose=False):
"""
subsample the voter file such that the race distribution of the subsampled
voter file coincides with the race distribution of the cps (input df_cps_reg_voters)
Parameters
----------
df_vf : pandas dataframe
the original voter file with a "race" columns
df_cps_reg_voters : pandas dataframe
race distribution of registered voters estimated by cps
verbose : bool, optional
Returns
-------
pandas dataframe
the subsampled voter file
"""
# cps race/ethnicity distribution
dist_cps = df_cps_reg_voters[fields.RACES].values[0]
dist_vf = df_vf.groupby("race").size()[fields.RACES].values
dist_vf = dist_vf / np.sum(dist_vf)
ratios = dist_cps / dist_vf
# find race with maximum ration of cps / voter file
ind_max = np.argmax(ratios)
# construct adjusted voterfile totals that would match cps distribution
vf_count_dist = df_vf.groupby("race").size()[fields.RACES].values
vf_count_dist_adj = dist_cps * vf_count_dist[ind_max] / dist_cps[ind_max]
vf_count_dist_adj = vf_count_dist_adj.astype(int)
# subsample each race separately and combine dataframes at the end
dfs = []
for i, race in enumerate(fields.RACES):
df_tmp = df_vf[df_vf["race"] == race]
nsample = int(vf_count_dist_adj[i])
dfs.append(df_tmp.sample(n=nsample, replace=False, random_state=1))
df_vf_sub = pd.concat(dfs)
if verbose:
print(f"initial cps distribution: {dist_cps}")
print(f"initial voter file distribution: {dist_vf}")
print(
f"voter file target distribution: {vf_count_dist_adj / np.sum(vf_count_dist_adj)}"
)
print(
f'final voter file distribution: {df_vf_sub.groupby("race").size()[fields.RACES].values / df_vf_sub.shape[0]}'
)
return df_vf_sub
def load_voter_file(state, year, load=True):
"""
load the voter file of the inputted state (and in the case of north carolina, year)
Parameters
----------
state : string
state, e.g., 'fl'
year : integer
year, only relevant for north carolina
load : bool, optional
load the voter file if it has already been written
Returns
-------
pandas dataframe
the state voter file
"""
states = ["fl", "nc", "ny", "oh", "ok", "vt", "wa"]
assert state in states, f"no voter file for {state}"
# voter file
if state == "fl":
df_vf = florida_vf.fl_voter_file(min_names=0, verbose=False, load=load)
elif state == "nc":
df_vf = nc_vf.nc_voter_file(verbose=False, year=year, load=load)
elif state == "ny":
df_vf = ny_vf.ny_voter_file(load=load)
elif state == "oh":
df_vf = ohio_vf.oh_voter_file(load=load)
elif state == "ok":
df_vf = ok_vf.ok_voter_file(load=load)
elif state == "vt":
df_vf = vt_vf.vt_voter_file(load=load)
elif state == "wa":
df_vf = wa_vf.wa_voter_file(load=load)
else:
raise Exception(f"no voter file for {state}")
return df_vf
def make_df_agg(state, year, subsample=False, load=False):
"""
create the dataframe df_agg which contains various predictions for all
registered voters in a state. each row of df_agg corresponds to
one (surname, geolocation)
Parameters
----------
state : string
state
year : integer
year
subsample : bool, optional
construct subsampled df_agg where the race distribution of all people
matches the cps survey approximation
load : bool, optional
load df_agg if it has already been created and written to file
Returns
-------
pandas dataframe
df_agg
"""
# check if df_agg has already been created
if subsample:
filename_df_agg = f"generated_data/df_agg_{state}{year}_sub.feather"
else:
filename_df_agg = f"generated_data/df_agg_{state}{year}.feather"
# if df_agg has already been created, load and return it
if os.path.exists(filename_df_agg) and load:
print(f"*loading dataframe from {filename_df_agg}")
df_agg = pd.read_feather(filename_df_agg)
return df_agg
# load cps data
df_cps_reg_voters = process_cps.cps_geo_race(
state, year, voters=True, load=True, save=True
)
# load census data
df_cen_counties = process_census.county_census(state, year, load=True)
df_cen_usa = process_census.usa_census(year=year)
df_cen_surs = process_census.surnames()
# voter file
df_vf = load_voter_file(state, year, load=True)
# check if voter file contains race labels
race_labels = "race" in df_vf.columns
# subsample voter file?
if subsample and race_labels:
print("*subampling voter file")
df_vf = make_df_vf_sub(df_vf, df_cps_reg_voters, verbose=False)
# initialize df_agg, which will contain various name/county predictions
df_agg = construct_df_agg_init(state, df_vf)
# name in census surname list
df_agg["in_cen_surs"] = df_agg["name"].isin(df_cen_surs["name"].unique())
# add census data for surname, geolocation to df_agg
df_agg = process_census.append_r_given_g_cols(df_agg, df_cen_counties)
df_agg = process_census.append_r_given_s_cols(df_agg, df_cen_surs)
# add voter file race columns to df_agg if we have labels
if race_labels:
print("*appending to df_agg voter file race information")
df_agg = append_vf_race_cols(df_agg, df_vf, rake3=False, verbose=True)
# black box bisg
df_agg = black_box_bisg(df_agg, df_cen_counties, df_cen_surs, df_cen_usa)
# bisg for voters
print("*calculating voter bisg using cps")
df_agg = append_voter_bisg(df_agg, df_cps_reg_voters, df_cen_counties, df_cen_surs)
# raking w/ BISG initialization
print("*raking predictions to match cps and voter file margins")
df_agg = append_raking_preds(df_agg, df_cps_reg_voters)
# write df_agg to file
df_agg.to_feather(filename_df_agg)
return df_agg
def make_calib_map(df_cps_reg_voters, df_agg, verbose=False):
"""
find the stochastic 6 x 6 matrix a such that a * u = v
that minimizes | a - I |_F where u and v are the race distribution
of the cps and voter file respectively. by stochastic matrix, we mean
entries are non-negative and each column sums to 1
Parameters
----------
df_cps_reg_voters : pandas dataframe
race distribution of registered voters in a state approximated by cps
df_agg : pandas dataframe
df_agg
verbose : bool, optional
Returns
-------
6 x 6 numpy array
matrix that maps voter file distribution to cps distribution
"""
# create map from CPS predictions to VF predictions
print("*constructing calibration map")
u = df_cps_reg_voters[fields.RACES].values.T
# voter file race distribution
df_tmp = df_agg[fields.VF_RACES]
v = df_tmp.sum(axis=0).div(df_tmp.sum(axis=0).sum()).values.reshape((-1, 1))
cps_to_vf_map, _ = cps_to_vf_matrix(u, v, verbose=verbose)
return cps_to_vf_map
def dist_summary(state, year, df_cen_usa, df_cen_counties, df_vf, df_cps_reg_voters):
"""
create a dataframe with the race distribution of several important populations:
the full country, the state, the 18+ state, the cps estimate of registered voters,
and if available, the race distribution of registered voters from the voter file
Parameters
----------
state : string
state
year : integer
year
df_cen_usa : pandas dataframe
race distribution of all americans
df_cen_counties : pandas dataframe
race distribution of all counties in state
df_vf : pandas dataframe
voter file
df_cps_reg_voters : pandas dataframe
race distribution of registered voters in state
Returns
-------
pandas dataframe
several relevant race distributions
"""
# census, usa
dist_usa = df_cen_usa[fields.RACES] / df_cen_usa[fields.RACES].sum().sum()
# census, state
dist_cen_state = (
df_cen_counties[fields.RACES].sum(axis=0) / df_cen_counties[fields.RACES].sum().sum()
)
dist_cen_state = pd.DataFrame(dist_cen_state[fields.RACES]).T
# census, state, over18
dist_cen18_state = (
df_cen_counties[fields.RACES18].sum(axis=0) / df_cen_counties[fields.RACES18].sum().sum()
)
dist_cen18_state = pd.DataFrame(dist_cen18_state[fields.RACES18]).T
dist_cen18_state.columns = fields.RACES
# voter file, state
if "race" in df_vf.columns:
dist_vf_state = (
df_vf.groupby("race").size() / df_vf.groupby("race").size().sum()
)
dist_vf_state = pd.DataFrame(dist_vf_state[fields.RACES]).T
df = pd.concat(
[
dist_usa,
dist_cen_state,
dist_cen18_state,
df_cps_reg_voters,
dist_vf_state,
]
)
df["Population"] = [
f"USA census {year}",
f"{state.upper()} {year} census",
f"{state.upper()} {year} 18+ census",
f"{state.upper()} {year} CPS voters",
f"{state.upper()} {year} voter file",
]
else:
df = pd.concat([dist_usa, dist_cen_state, dist_cen18_state, df_cps_reg_voters])
df["Population"] = [
f"USA {year} census",
f"{state.upper()} {year} census",
f"{state.upper()} {year} 18+ census",
f"{state.upper()} {year} CPS voters",
]
# reorder columns so population is first
df = df[["Population"] + fields.RACES]
# and make the race columns pretty
df.columns = ["Population"] + fields.PRETTY_PRINT
return df
def one_calib(preds, trues, weights):
"""
one tygert calibration plot. this is basically a copy/paste of the code here --
https://github.com/facebookresearch/fbcdgraph/blob/main/codes/calibr_weighted.py
(as of 3/30/2023)
Parameters
----------
preds : numpy array
prediction with probabilities that various people are of one particular race
trues : numpy array
actual probability that various people are of one particular race
weights : numpy array
number of people corresponding to each entry of preds and trues
Returns
-------
numpy array
ordered weights with a 0 inserted at the beginning
numpy array
ordered predictions
numpy array
cumulative miscalibration
float
kuiper statistic
"""
w = weights.copy()
w /= w.sum()
# sort
args = np.argsort(preds)
r = trues[args]
s = preds[args]
w = w[args]
# Accumulate the weighted r and s, as well as w.
f = np.insert(np.cumsum(w * r), 0, [0])
ft = np.insert(np.cumsum(w * s), 0, [0])
x = np.insert(np.cumsum(w), 0, [0])
fft = f - ft
kuiper = np.max(fft) - np.min(fft)
return x, s, fft, kuiper
def ll_tables(state, df_agg, cols, calib_map=None):
"""
create a pandas dataframe with the negative log-likelihood of subpopulation predictions.
specifically, in each geographical region, g, sum over all surnames and races the following
-x_{sgr} * log(m_{sgr} / x_{+g+}
where x_{sgr} is the correct number of people of a particular surname, geolocation, race,
and m_{sgr} is the prediction.
Parameters
----------
state : string
state
df_agg : pandas dataframe
dataframe with predictions
cols : list
the columns with the (normalized) predictions
calib_map : 6 x 6 numpy array, optional
apply a calibration map to the predictions
Returns
-------
pandas dataframe
negative loglikelihood at region level
pandas dataframe
negative loglikelihood at county level
"""
# create list of columns
agg_cols = ["county", "region", "vf_tot"] + fields.VF_RACES
for col_list in cols:
agg_cols = agg_cols + col_list
df_tmp = df_agg.loc[:, agg_cols]
# filter out rows without predictions
mask = ~df_tmp[agg_cols].isnull().any(axis=1)
df_tmp = df_tmp.loc[mask, :]
# create columns with lls
ncomps = len(cols)
ll_cols = [f"ll_{cols[i][0][:-8]}" for i in range(ncomps)]
# for each prediction scheme, compute errors
for i in range(ncomps):
# compute predictions
if calib_map is not None:
arrtmp = np.dot(calib_map, df_tmp[cols[i]].values.T).T
else:
arrtmp = df_tmp[cols[i]].values
arrtmp = np.log10(arrtmp)
arrtmp[arrtmp == -np.inf] = 0
arrtmp = np.sum(df_tmp[fields.VF_RACES].values * arrtmp, axis=1)
df_tmp[ll_cols[i]] = -arrtmp
# florida-wide
df_tmp_state = df_tmp[ll_cols].sum() / df_tmp["vf_tot"].sum()
if state == "nc":
df_tmp_state["region"] = "North Carolina"
df_tmp_state["county"] = "North Carolina"
elif state == "fl":
df_tmp_state["region"] = "Florida"
df_tmp_state["county"] = "Florida"
# regions
df_region = df_tmp.groupby("region").sum(numeric_only=True)
df_region = df_region.div(df_region["vf_tot"].values[:, np.newaxis])
df_region = df_region[ll_cols].reset_index()
df_region = df_region.append(df_tmp_state[["region"] + ll_cols], ignore_index=True)
df_region["region"] = df_region["region"].str.title()
# counties
df_tmp_county = df_tmp.groupby("county").sum(numeric_only=True)
df_tmp_county = df_tmp_county.div(df_tmp_county["vf_tot"].values[:, np.newaxis])
df_tmp_county = df_tmp_county[ll_cols].reset_index()
# replace county abbreviations with full county name
if state == "fl":
df_tmp_county["county"] = df_tmp_county["county"].map(florida_vf.COUNTY_DICT)
df_tmp_county = df_tmp_county.sort_values("county")
df_tmp_county = df_tmp_county.append(
df_tmp_state[["county"] + ll_cols], ignore_index=True
)
return df_region, df_tmp_county
def l1_l2_tables(state, df_agg, cols, calib_map=None):
"""
create a pandas dataframe with the l1 and l2 errors of subpopulation predictions.
specifically, for a geographical region, g, sum over all surnames and races
l1: |x_{sgr} - m_{sgr}| / x_{+g+}
l2: \frac{1}{x_{+g+}} \sum_{s} ||x_{sgr} - m_{sgr}||_2
where x_{sgr} is the correct number of people of a particular surname, geolocation, race,
and m_{sgr} is the prediction.
Parameters
----------
state : string
state
df_agg : pandas dataframe
dataframe with predictions
cols : list
the columns with the (normalized) predictions
calib_map : 6 x 6 numpy array, optional
apply a calibration map to the predictions
Returns
-------
pandas dataframe
l1 and l2 errors at region level
pandas dataframe
l1 and l2 errors at county level
"""
# create list of columns
agg_cols = ["county", "region", "vf_tot"]
if fields.VF_BAYES_OPT_COLS not in cols:
agg_cols += fields.VF_BAYES_OPT_COLS
for colsi in cols:
agg_cols = agg_cols + colsi
df_tmp = df_agg.loc[:, agg_cols]
# filter out rows without predictions
mask = ~df_tmp[agg_cols].isnull().any(axis=1)
df_tmp = df_tmp.loc[mask, :]
ncomps = len(cols)
# names of columns
l1_cols = [f"l1_{cols[i][0][:-8]}" for i in range(ncomps)]
l2_cols = [f"l2_{cols[i][0][:-8]}" for i in range(ncomps)]
# for each prediction scheme, compute errors
for i in range(ncomps):
# compute unweighted errors for each (surname, geolocation)
if calib_map is not None:
arrtmp = (
df_tmp[fields.VF_BAYES_OPT_COLS].values
- np.dot(calib_map, df_tmp[cols[i]].values.T).T
)
# if we're checking accuracy of the ground truth for debugging purposes,
# then don't apply the calibration map
if cols[i] == fields.VF_BAYES_OPT_COLS:
arrtmp = df_tmp[fields.VF_BAYES_OPT_COLS].values - df_tmp[cols[i]].values
else:
arrtmp = df_tmp[fields.VF_BAYES_OPT_COLS].values - df_tmp[cols[i]].values
# scale errors by number of appearances of (surname, geolocation)
arrtmp = arrtmp.astype(np.float64)
df_tmp[l1_cols[i]] = np.sum(np.abs(arrtmp), axis=1) * df_tmp["vf_tot"].values
df_tmp[l2_cols[i]] = (
np.sqrt(np.sum(arrtmp**2, axis=1)) * df_tmp["vf_tot"].values
)
# florida-wide, this will be added as the last row of the county/region dataframes
df_tmp_state = df_tmp[l1_cols + l2_cols].sum() / df_tmp["vf_tot"].sum()
if state == "nc":
df_tmp_state["region"] = "North Carolina"
df_tmp_state["county"] = "North Carolina"
elif state == "fl":
df_tmp_state["region"] = "Florida"
df_tmp_state["county"] = "Florida"
# regions
df_region = df_tmp.groupby("region").sum(numeric_only=True)
df_region = df_region.div(df_region["vf_tot"].values[:, np.newaxis])
df_region = df_region[l1_cols + l2_cols].reset_index()
df_region = df_region.append(
df_tmp_state[["region"] + l1_cols + l2_cols], ignore_index=True
)
df_region["region"] = df_region["region"].str.title()
# counties
df_county = df_tmp.groupby("county").sum(numeric_only=True)
df_county = df_county.div(df_county["vf_tot"].values[:, np.newaxis])
df_county = df_county[l1_cols + l2_cols].reset_index()
# replace county abbreviations with full county name
if state == "fl":
df_county["county"] = df_county["county"].map(florida_vf.COUNTY_DICT)
df_county = df_county.sort_values("county")
df_county = df_county.append(
df_tmp_state[["county"] + l1_cols + l2_cols], ignore_index=True
)
return df_region, df_county
def construct_df_agg_init(state, df_vf):
"""
construct a dataframe with columns "name", "county", "vf_tot", and in the case of labeled voter file, VF_RACES
Parameters
----------
state : string
abbreviation of one of the states supported by this package
df_vf : pandas dataframe
name, county, and possibly race of registered voters
Returns
-------
pandas dataframe
containing name, county, total appearances in voter file, possible race totals
"""
df_agg = df_vf.copy()
# is race is labeled, then create a column for each race corresponding to the
# number of people of that race of a particular (surname, geolocation) pair
if "race" in df_vf.columns:
df_agg[fields.VF_RACES] = 0
# add race columns with hot-one encoding
for i, race in enumerate(fields.RACES):
df_agg[fields.VF_RACES[i]] = df_agg["race"] == race
# create dataframe with county, name, race columns
df_agg = df_agg.groupby(["name", "county"]).sum(numeric_only=True).reset_index()
# total number of people with a given surname in a given region
df_agg["vf_tot"] = df_agg[fields.VF_RACES].sum(axis=1)
else:
# create dataframe with name and county
df_agg = df_agg.groupby(["name", "county"]).size().reset_index()
df_agg.columns = ["name", "county", "vf_tot"]
# add regions
if state == "fl":
df_agg["county_long"] = df_agg["county"].map(
lambda x: florida_vf.COUNTY_DICT.get(x, x)
)
df_agg["region"] = df_agg["county_long"].map(
lambda x: florida_vf.COUNTY_TO_REGION_DICT.get(x, x)
)
df_agg['rural'] = df_agg['county_long'].isin(florida_vf.FL_RURAL_COUNTIES)
elif state == "nc":
df_agg["region"] = df_agg["county"].map(
lambda x: nc_vf.COUNTY_TO_REGION_DICT.get(x, x)
)
return df_agg
def append_vf_race_cols(df_agg, df_vf, rake3=False, verbose=True):
"""
append columns to df_agg that require the race labels of, e.g. florida and north carolina's
voter file.
Parameters
----------
df_agg : pandas dataframe
df_vf : pandas dataframe
rake3 : bool, optional
include three-way raking predictions
verbose : bool, optional
Returns
-------
pandas dataframe
df_agg
"""
# two-way margins
df_vf_sr, _, df_vf_gr = two_way_tables(df_vf)
# vf bayes optimal, race given surname, race given geo, bisg
df_agg = basic_cols(df_agg, df_vf_sr, df_vf_gr)
# vf bayes 2way and 3way raking
if verbose:
print("*two-way raking on voter file")
df_agg = two_way_raking(df_agg)
if rake3:
if verbose:
print("*three-way raking on voter file")
df_agg = three_way_raking(df_agg, tol=1e-3)
return df_agg
def black_box_bisg(df_agg, df_cen_counties, df_cen_surs, df_cen_usa):
"""
append black box bisg (full usa population) columns to df_agg
Parameters
----------
df_agg : pandas dataframe
df_cen_counties : pandas dataframe
df_cen_surs : pandas dataframe
df_cen_usa : pandas dataframe
Returns
-------
pandas dataframe
df_agg
"""
# add census data for surname, geolocation to df_agg
df_agg = process_census.append_r_given_g_cols(df_agg, df_cen_counties)
df_agg = process_census.append_r_given_s_cols(df_agg, df_cen_surs)
# census bisg, compute three factors in bisg formula
prob_of_r = df_cen_usa[fields.PROB_COLS].values
r_given_surname = df_agg[fields.CEN_R_GIVEN_SUR_COLS].values
r_given_geo = df_agg[fields.CEN_R_GIVEN_GEO_COLS].values
# construct prediction (county-level)
bisg_preds = r_given_geo * r_given_surname / prob_of_r
bisg_preds = bisg_preds / np.sum(bisg_preds, axis=1)[:, np.newaxis]
df_agg[fields.BISG_CEN_COUNTY_COLS] = bisg_preds
return df_agg
def bisg_np(prob_of_r, r_given_surname, r_given_geo):
"""
compute the bisg formula
Parameters
----------
prob_of_r : numpy array of length m
probability of each race in population
r_given_surname : n x m numpy array
probability of race given surname
r_given_geo : n x m numpy array
probability of race given geolocation
Returns
-------
n x m numpy array
bisg predictions
"""
bisg_preds = r_given_geo * r_given_surname / prob_of_r
bisg_preds = bisg_preds / np.sum(bisg_preds, axis=1)[:, np.newaxis]
return bisg_preds
def get_v_given_r(df_cps_reg_voters, df_cen_counties):
"""
compute P(V | R), or rather something proportional to that via the formula
C(R, V) / C(R) where C(R, V) is, up to a multiplicative
constant independent of R, equal to the number of voters of each race obtained
from the cps. C(R), the count of each race comes from the census
over-18 population
Parameters
----------
df_cps_reg_voters : pandas dataframe
subpopulation distribution of registered voters
df_cen_counties : pandas dataframe
subpopulation distribution in each county
Returns
-------
numpy array
probability of being a registered voter given race, up to a constant
"""
# P(R, V) up to a constant independent of R
rv_dist = df_cps_reg_voters[fields.RACES].values