-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstatacode.py
1300 lines (1005 loc) · 46.4 KB
/
statacode.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
import pandas as pd
import numpy as np
from datetime import datetime
import os
# from IPython.core.display import display, HTML
import missingno as msno
import subprocess
import os
import shutil
import argparse
# import subprocess
# new versions
def dependent_variable_construction(T2):
###### (0) for LeastOne Vaccination
for col in ['CvdVax_WhiteNum', 'CvdVax_NHWhiteNum']:
index = - T2[col].isna()
T2.loc[index, 'CvdVax_ZWhiteNum'] = T2.loc[index, col]
# for Full Vaccination
try:
for col in ['FullCvdVax_WhiteNum', 'FullCvdVax_NHWhiteNum']:
index = - T2[col].isna()
T2.loc[index, 'FullCvdVax_ZWhiteNum'] = T2.loc[index, col]
except:
print('No Full Vaccine Data')
###### (1) Disparity
suffix = '_Disparity'
new_cols = []
for i in ['CvdVax', 'CvdVaxAbove15', 'CvdVaxAbove20']:
new_col = i+suffix
T2[new_col] = T2[ i + '_MWhiteRate'] - T2[i+'_MBlackRate']
new_cols.append(new_col)
for i in ['FluVax', 'HighSchool', 'Bachelor', 'IT', 'Unempl', 'A15T74', 'A20T74', 'Above75', 'Above65', 'Above15', 'Above20',]:
new_col = i+suffix
T2[new_col] = T2[ i + '_NHWhiteRate'] - T2[i+'_BlackRate']
new_cols.append(new_col)
for i in [ 'MeanInc', 'MedianInc']:
new_col = i+suffix
T2[new_col] = T2[ i + '_NHWhiteAvg'] - T2[i+'_BlackAvg']
new_cols.append(new_col)
try:
for i in ['FullCvdVax', 'FullCvdVaxAbove15', 'FullCvdVaxAbove20']:
new_col = i+suffix
T2[new_col] = T2[ i + '_MWhiteRate'] - T2[i+'_MBlackRate']
new_cols.append(new_col)
except:
print('No Full Cvd')
# ZWhiteRate - MBlackRate
try:
for i in ['CvdVax', 'CvdVaxAbove15', 'CvdVaxAbove20']:
new_col ='Z' + i + suffix
T2[new_col] = T2[ i + '_ZWhiteRate'] - T2[i+'_MBlackRate']
new_cols.append(new_col)
except:
print('No ZCvd Info')
###### (2) Ratio Disparity
new_cols = []
suffix = '_RD'
for i in ['CvdVax', 'CvdVaxAbove15', 'CvdVaxAbove20']:
new_col = i+suffix
T2[new_col] = (T2[ i + '_MWhiteRate'] + 0.0001) /( T2[i+'_MBlackRate'] + 0.0001)
new_cols.append(new_col)
for i in ['FluVax', 'HighSchool', 'Bachelor', 'IT', 'Unempl', 'A15T74', 'A20T74', 'Above75', 'Above65', 'Above15', 'Above20',]:
new_col = i+suffix
T2[new_col] = (T2[ i + '_NHWhiteRate']+ 0.0001) / (T2[i+'_BlackRate'] + 0.0001)
new_cols.append(new_col)
for i in [ 'MeanInc', 'MedianInc']:
new_col = i+suffix
T2[new_col] = (T2[ i + '_NHWhiteAvg'] + 0.0001)/ (T2[i+'_BlackAvg'] + 0.0001)
new_cols.append(new_col)
try:
for i in ['FullCvdVax', 'FullCvdVaxAbove15', 'FullCvdVaxAbove20']:
new_col = i+suffix
T2[new_col] = (T2[ i + '_MWhiteRate'] + 0.0001)/( T2[i+'_MBlackRate'] + 0.0001)
new_cols.append(new_col)
except:
print('No Full Cvd')
try:
for i in ['CvdVax', 'CvdVaxAbove15', 'CvdVaxAbove20']:
new_col ='Z' + i + suffix
T2[new_col] = (T2[ i + '_ZWhiteRate'] + 0.0001) /( T2[i+'_MBlackRate'] + 0.0001)
new_cols.append(new_col)
except:
print('No ZCvd Info')
T2[new_cols].describe()
###### (3) Log Ratio Disparity
new_cols = []
suffix = '_LogRD'
for i in ['CvdVax', 'CvdVaxAbove15', 'CvdVaxAbove20']:
new_col = i+suffix
T2[new_col] = np.log( (T2[ i + '_MWhiteRate'] + 0.0001) /( T2[i+'_MBlackRate'] + 0.0001) )
new_cols.append(new_col)
for i in ['FluVax', 'HighSchool', 'Bachelor', 'IT', 'Unempl', 'A15T74', 'A20T74', 'Above75', 'Above65', 'Above15', 'Above20',]:
new_col = i+suffix
T2[new_col] = np.log( (T2[ i + '_NHWhiteRate']+ 0.0001) / (T2[i+'_BlackRate'] + 0.0001) )
new_cols.append(new_col)
for i in [ 'MeanInc', 'MedianInc']:
new_col = i+suffix
T2[new_col] = np.log((T2[ i + '_NHWhiteAvg'] + 0.0001)/ (T2[i+'_BlackAvg'] + 0.0001) )
new_cols.append(new_col)
try:
for i in ['FullCvdVax', 'FullCvdVaxAbove15', 'FullCvdVaxAbove20']:
new_col = i+suffix
T2[new_col] = np.log( (T2[ i + '_MWhiteRate'] + 0.0001)/( T2[i+'_MBlackRate'] + 0.0001) )
new_cols.append(new_col)
except:
print('No Full Cvd')
try:
for i in ['CvdVax', 'CvdVaxAbove15', 'CvdVaxAbove20']:
new_col ='Z' + i+suffix
T2[new_col] = np.log( (T2[ i + '_ZWhiteRate'] + 0.0001) /( T2[i+'_MBlackRate'] + 0.0001) )
new_cols.append(new_col)
except:
print('No ZCvd Info')
T2[new_cols].describe()
########## (4) Scaled Disparity
new_cols = []
suffix = '_SD'
# LeastOne CVD
for i in ['CvdVax', 'CvdVaxAbove15', 'CvdVaxAbove20']:
popu_type = i.replace('CvdVax', '')
popu_type = popu_type + '_' if len(popu_type) > 0 else popu_type
new_col = i+ suffix
AvgWBRate = (T2['CvdVax_ZWhiteNum'] + T2['CvdVax_BlackNum']) / ( T2[popu_type + 'NHWhiteNum'] + T2[popu_type + 'BlackNum'])
T2[new_col] = T2[i + '_Disparity'] / (AvgWBRate * 100)
new_cols.append(new_col)
# Rate Predictors
for i in ['FluVax', 'HighSchool', 'Bachelor', 'IT', 'Unempl', 'A15T74', 'A20T74', 'Above75', 'Above65', 'Above15', 'Above20',]:
new_col = i+suffix
# T2[i + '_WhiteNum'] = T2[i + '_WhiteRate'] * T2['NHWhiteNum'] # Error here, keep here
NHWhiteNum = T2[i + '_NHWhiteRate'] * T2['NHWhiteNum']
BlackNum = T2[i + '_BlackRate'] * T2['BlackNum']
AvgWBRate = (NHWhiteNum + BlackNum) / ( T2['NHWhiteNum'] + T2['BlackNum'])
T2[new_col] = T2[i + '_Disparity'] / (AvgWBRate * 100)
new_cols.append(new_col)
# Income Predictors
for i in [ 'MeanInc', 'MedianInc']:
new_col = i+suffix
T2[new_col] = T2[i+'_Disparity'] / T2[i+'_WholeAvg']
new_cols.append(new_col)
# Full CVD
try:
for i in ['FullCvdVax', 'FullCvdVaxAbove15', 'FullCvdVaxAbove20']:
popu_type = i.replace('FullCvdVax', '')
popu_type = popu_type + '_' if len(popu_type) > 0 else popu_type
new_col = i+ suffix
AvgWBRate = (T2['CvdVax_ZWhiteNum'] + T2['CvdVax_BlackNum']) / ( T2[popu_type + 'NHWhiteNum'] + T2[popu_type + 'BlackNum'])
T2[new_col] = T2[i + '_Disparity'] / (AvgWBRate * 100)
new_cols.append(new_col)
except:
print('No Full Cvd')
T2[new_cols].describe()
return T2
def independent_variable_construction(T2):
# How about other disparity. There unit is not meaningful. Maybe we can just leave them.
# Absolute
T2['CvdVax_DisparityY'] = T2['CvdVax_Disparity']# *100
T2['CvdVaxAbove15_DisparityY'] = T2['CvdVaxAbove15_Disparity']# *100
T2['CvdVaxAbove20_DisparityY'] = T2['CvdVaxAbove20_Disparity']# *100
T2['FluVax_DisparityY'] = T2['FluVax_Disparity']# *100
# Ratio
T2['CvdVax_RDY'] = T2['CvdVax_RD']
T2['CvdVaxAbove15_RDY'] = T2['CvdVaxAbove15_RD']
T2['CvdVaxAbove20_RDY'] = T2['CvdVaxAbove20_RD']
T2['FluVax_RDY'] = T2['FluVax_RD']# *100
# logRatio
T2['CvdVax_LogRDY'] = T2['CvdVax_LogRD']
T2['CvdVaxAbove15_LogRDY'] = T2['CvdVaxAbove15_LogRD']
T2['CvdVaxAbove20_LogRDY'] = T2['CvdVaxAbove20_LogRD']
T2['FluVax_LogRDY'] = T2['FluVax_LogRD']
# Scaled
T2['CvdVax_SDY'] = T2['CvdVax_SD']
T2['CvdVaxAbove15_SDY'] = T2['CvdVaxAbove15_SD']
T2['CvdVaxAbove20_SDY'] = T2['CvdVaxAbove20_SD']
T2['FluVax_SDY'] = T2['FluVax_SD']# *100
try:
T2['FullCvdVax_DisparityY'] = T2['FullCvdVax_Disparity']# *100
T2['FullCvdVaxAbove15_DisparityY'] = T2['FullCvdVaxAbove15_Disparity']# *100
T2['FullCvdVaxAbove20_DisparityY'] = T2['FullCvdVaxAbove20_Disparity']# *100
# Ratio
T2['FullCvdVax_RDY'] = T2['FullCvdVax_RD']
T2['FullCvdVaxAbove15_RDY'] = T2['FullCvdVaxAbove15_RD']
T2['FullCvdVaxAbove20_RDY'] = T2['FullCvdVaxAbove20_RD']
# Scaled
T2['FullCvdVax_SDY'] = T2['FullCvdVax_SD']
T2['FullCvdVaxAbove15_SDY'] = T2['FullCvdVaxAbove15_SD']
T2['FullCvdVaxAbove20_SDY'] = T2['FullCvdVaxAbove20_SD']
except:
print('No Full Cvd')
T2['ZCvdVax_DisparityY'] = T2['ZCvdVax_Disparity']# *100
T2['FacNum'] = T2[['FQHC', 'HOPD', 'PHMCY', 'RUHC']].sum(axis = 1)
T2['vehicle'] = 1- T2['EP_NOVEH']
T2['logFacNum' ] = np.log(T2['FacNum' ] + 1)
T2['logcases' ] = np.log(T2['cases' ] + 1)
T2['FacNumRate' ] = T2['FacNum' ]/T2['WholeNum']
T2['CaseRate' ] = T2['cases' ]/T2['WholeNum']
T2['Black_Prop' ] = T2['BlackNum' ]/T2['WholeNum']
T2['Segregation'] = T2['Segregation'] / 100
T2['log_WholeNum'] = np.log(T2['WholeNum'])
T2['org_WholeNum'] = T2['WholeNum'] + 0
T2['Selected'] = [1]*len(T2)
money_cols = ['MedianInc_WholeAvg', 'MedianInc_Disparity',]
for i in money_cols:
T2[i] = T2[i] / 1000
rate1_cols = ['FacNumRate', 'CaseRate', 'republican_rate', 'vehicle',
'Segregation','racial_weighted_bias','hesitancy','Black_Prop']
for i in rate1_cols:
T2[i] = T2[i] * 100
rate100_cols = ['HighSchool_WholeRate','HighSchool_Disparity',
'IT_WholeRate','IT_Disparity',
'FluVax_WholeRate', 'FluVax_Disparity',
'A15T74_WholeRate', 'A15T74_Disparity',
'A20T74_WholeRate', 'A20T74_Disparity',
'Above75_WholeRate', 'Above75_Disparity',
'Above65_WholeRate', 'Above65_Disparity',
'Above20_WholeRate', 'Above20_Disparity',
'Above15_WholeRate', 'Above15_Disparity']
# display(HTML(T2[money_cols].describe().to_html()))
# display(HTML(T2[rate1_cols].describe().to_html()))
# display(HTML(T2[rate100_cols].describe().to_html()))
# print(T2['State'].unique())
# print('State Number:', len(T2['State'].value_counts().sort_index()))
return T2
def prep_process(T2, cols, path):
# cols: Y + Xs
prefix_cols = ['State', 'County']
addtion_cols = [i for i in ['org_WholeNum', 'log_WholeNum', 'Black_Prop', 'BlackNum', 'NotInHighMobility', 'ReportNH'] if i not in cols]
addtion_cols = addtion_cols if 'IT_Disparity' in cols else addtion_cols + ['IT_Disparity']
# print('prefix cols:', prefix_cols)
# print('addition cols:', addtion_cols)
T2['Selected'] = 1
print('Original Sample:', T2['Selected'].sum())
selected_columns = prefix_cols + cols + addtion_cols
### Here
critieria_nonan = {}
critieria_nonan_list = selected_columns
if 'FluVax_Disparity' not in selected_columns:
critieria_nonan_list.append('FluVax_Disparity')
for col in critieria_nonan_list:
# print(col)
critieria_nonan[col] = (-T2[col].isna()).astype(int)
for col in critieria_nonan:
T2['Selected'] = T2['Selected']*critieria_nonan[col]
print('The object after Dropping Nan:', col, T2['Selected'].sum())
cirteria_within01 = {}
cirteria_within01_list = ['CvdVax_MWhiteRate', 'CvdVax_MBlackRate']
for col in cirteria_within01_list:
cirteria_within01[col] = (T2[col] < 100).astype(int)
### Here
cirteria_others = {}
cirteria_others['LargeBlackNum'] = (T2['BlackNum'] >= 273).astype(int)
for col in cirteria_others:
T2['Selected'] = T2['Selected']*cirteria_others[col]
print('The object after the process of:', col, T2['Selected'].sum())
pathT2 = os.path.join(path, 'T2.csv')
print('Write T2 to:', pathT2 )
T2.to_csv(pathT2)
return T2, selected_columns
def standardize_data(T2, YXcols, selected_columns, path):
T3 = T2[T2['Selected'] == 1][selected_columns]
pathDict = os.path.join(path, 'DataVarDict.csv')
pathStata = os.path.join(path, 'Data.dta')
T3.describe().T.to_csv(pathDict)
T3.to_stata(pathStata)
print('Write T3 to:', pathStata )
# Do not normalize
dummy_cols = ['republican', 'urban', 'ReportNH']
# DependentVariables = [i for i in YXcols if i[-1] == 'Y']
# DependentVariables = [i for i in YXcols if 'DisparityY' in i or 'RDY' in i or 'SDY' in i]
DependentVariables = [i for i in YXcols if 'DisparityY' in i]
print('Dependent Variables are:', DependentVariables)
not_normalized_cols = DependentVariables + dummy_cols
print('\n\nnot normalized:', not_normalized_cols, '\n\n')
T3Norm = T3.copy()
for col in YXcols:
if col in not_normalized_cols:
continue
df = T3Norm[col]
T3Norm[col]=(df-df.mean())/df.std()
pathNormDict = os.path.join(path, 'DataNormVarDict.csv')
pathNormStata = os.path.join(path, 'DataNorm.dta')
T3Norm.describe().T.to_csv(pathNormDict)
T3Norm.to_stata(pathNormStata)
print('Write T3Norm to:', pathNormStata )
return T3, T3Norm
def get_regression(Y, X, addText, state_dummy_num = '16'):
# Y: string
# X: list, including all the dependent variable
reg_string = ' '.join(['reg', Y] + X) #+ sum([v for k, v in CV.items()], []))
# reg_string = reg_string+'dummy
reg_string = reg_string + ' state_dummy1-state_dummy{} '.format(state_dummy_num)
if addText.get('W'):
reg_string = reg_string + ' [pweight=org_WholeNum] ' ###
if addText.get('R'):
reg_string = reg_string + ', r ' if ',' not in reg_string else reg_string + 'cluster(State) '
if addText.get('C'):
reg_string = reg_string + ', cluster(State) ' if ',' not in reg_string else reg_string + 'cluster(State)'
# reg_string = reg_string + ', level()'
return reg_string
def get_outreg2(Y, X, DocName, addText, replace = False):
# Title = '_'.join(['Mdl', '.'.join([k for k, v in addText.items() if v] )])
# Title = Title[:-1] if Title[-1] == '_' else Title
# omit = "state_dummy1-state_dummy" + max_state + " o.state_dummy1-o.state_dummy" + max_state
Title = Y
TitleString = 'append ctitle({})'.format(Title) if not replace else 'replace ctitle({})'.format(Title)
addTextString = 'addtext(SD, True, ' + ', '.join([k + ', ' + str(v) for k, v in addText.items()]) + ')'
d = ' '.join(['outreg2 using',
DocName + ',',
TitleString,
addTextString,
" keep (" +' '.join(X) + ') '
'excel',
"alpha(0.001, 0.01, 0.05, 0.10) symbol(***, **, *, +)"
])
return d
def gen_regression_code(YXLists,
additonal_stata = [],
state_dummy_num = 16,
winsor = 95,
Norm = True):
# Use the dataset: Normalized or not
if Norm == True:
DataPath = os.path.join(os.getcwd(), path, 'DataNorm.dta')
else:
DataPath = os.path.join(os.getcwd(), path, 'Data.dta')
winsor_range = '(' + str(100- winsor) + ',' + str(winsor) + ')'
winsor_code = 'winsor2 {}, replace cuts ' + winsor_range
L1 = ['clear all', 'set more off', 'use "' + DataPath + '"', '\n']
L2 = ['\n', "tab State, generate(state_dummy)", '\n']
# Winsor variable
L = L1 + additonal_stata + L2 + [winsor_code.format(i) for i in list(set(sum(YXLists, [])))] + ['\n\n']
# Regression
addText = {'R': True, 'C': True, 'W': True}
DocName = os.path.join(path, 'RegResult.doc')
Regression_Commands = []
for idx, YXCols in enumerate(YXLists):
# print(state_dummy_num)
Y, X_used = YXCols[0], YXCols[1:]
# X_used = Xlist
reg_string = get_regression(Y, X_used, addText, state_dummy_num)
Regression_Commands.append(reg_string)
replace = True if idx == 0 else False
Title = Y.replace('Y', '').replace('Disparity', 'D')
out = get_outreg2(Title, X_used, DocName, addText, replace)
L = L + [reg_string + '\n', out, '\n']
# End Part
stata_string = '\n'.join(L)
do_suffix = 'norm' if Norm else 'orig'
StataCodePath = os.path.join(os.getcwd(), path, 'do_file_{}.do'.format(do_suffix))
print(StataCodePath, '\n\n\n')
print(stata_string)
with open(StataCodePath, 'w') as f:
f.write(stata_string)
return StataCodePath
def prepare_YX(Vax, Disparity, Var_list):
##############
# Vax = 'CvdVax' # FullCvdVax, CvdVaxAbove20, CvdVaxAbove15. 'FluVax
# Disparity = 'Disparity' # 'RD', 'LogRD', 'SD'
# Var_list = ['Base']
##############
Y = Vax + '_' + Disparity + 'Y'
X_dict = {
'Base': [
'MedianInc_WholeAvg', 'MedianInc_' + Disparity,
'HighSchool_WholeRate', 'HighSchool_' + Disparity,
'FacNumRate', 'CaseRate',
'IT_WholeRate', 'IT_' + Disparity,
'urban', 'vehicle',
'republican_rate', 'Segregation', 'racial_weighted_bias',
'hesitancy', 'Black_Prop',
],
'FluVax':['FluVax_WholeRate', 'FluVax_' + Disparity],
'Above75': ['Above75_WholeRate', 'Above75_' + Disparity],
'A15T74':['A15T74_WholeRate', 'A15T74_' + Disparity],
'RecentPositive':['positivity'],
}
X_used = sum([X_dict[var_name] for var_name in Var_list], [])
YXcols = [Y] + X_used
return YXcols
if __name__ =='__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--task', type=str, default='main_regression', help=' ')
args = parser.parse_args()
task = args.task
if task == 'main_regression':
# create folder
folder = task #+ str(datetime.now()).split('.')[0].replace(':', '-').replace(' ', '_')
path = os.path.join('StataCode', folder)
print('Generate Path:', path)
if not os.path.exists(path):
os.makedirs(path)
# update T2
RawDataPath = 'StataReg/CountyVaccine-04-19.csv'
T2 = pd.read_csv(RawDataPath)
T2 = dependent_variable_construction(T2)
T2 = independent_variable_construction(T2)
# generate YXLists and cols
YXLists = []
cols = []
# Vax = 'CvdVax' # FullCvdVax, CvdVaxAbove20, CvdVaxAbove15. 'FluVax
for Vax in ['CvdVax', 'FluVax']:
# Disparity = 'Disparity' # 'RD', 'LogRD', 'SD'
for Disparity in ['Disparity']:
# 'Base'
for Var_list in [
['Base']
# ['Base', 'FluVax', 'Above75', 'A15T74', 'RecentPositive'],
]:
YXcols = prepare_YX(Vax, Disparity, Var_list)
YXLists.append(YXcols)
cols = cols + [i for i in YXcols if i not in cols]
# generate T3
# print(all_variables)
T2, selected_columns = prep_process(T2, cols, path)
T3, T3Norm = standardize_data(T2, cols, selected_columns, path)
state_dummy_num = T3Norm['State'].nunique()
additonal_stata = []
# additonal_stata = ['drop if NotInHighMobility == 0']
# for Norm in [True, False]:
Norm = True
StataCodePath = gen_regression_code(YXLists,
additonal_stata,
state_dummy_num,
winsor = 95,
Norm = Norm)
## Do some processing in Python
## Set do-file information
# dofile = StataCodePath
# stata_app_path = '/Applications/Stata/StataSE.app/Contents/MacOS/StataSE'
# cmd = [stata_app_path, "do", dofile, "mpg", "weight", "foreign"]
# ## Run do-file
# subprocess.call(cmd)
elif task == 'main_regression_originalX':
# create folder
folder = task #+ str(datetime.now()).split('.')[0].replace(':', '-').replace(' ', '_')
path = os.path.join('StataCode', folder)
print('Generate Path:', path)
if not os.path.exists(path):
os.makedirs(path)
# update T2
RawDataPath = 'StataReg/CountyVaccine-04-19.csv'
T2 = pd.read_csv(RawDataPath)
T2 = dependent_variable_construction(T2)
T2 = independent_variable_construction(T2)
# generate YXLists and cols
YXLists = []
cols = []
# Vax = 'CvdVax' # FullCvdVax, CvdVaxAbove20, CvdVaxAbove15. 'FluVax
for Vax in ['CvdVax', 'FluVax']:
# Disparity = 'Disparity' # 'RD', 'LogRD', 'SD'
for Disparity in ['Disparity']:
# 'Base'
for Var_list in [
['Base']
# ['Base', 'FluVax', 'Above75', 'A15T74', 'RecentPositive'],
]:
YXcols = prepare_YX(Vax, Disparity, Var_list)
YXLists.append(YXcols)
cols = cols + [i for i in YXcols if i not in cols]
# generate T3
# print(all_variables)
T2, selected_columns = prep_process(T2, cols, path)
T3, T3Norm = standardize_data(T2, cols, selected_columns, path)
state_dummy_num = T3Norm['State'].nunique()
additonal_stata = []
# additonal_stata = ['drop if NotInHighMobility == 0']
# for Norm in [True, False]:
Norm = False
StataCodePath = gen_regression_code(YXLists,
additonal_stata,
state_dummy_num,
winsor = 95,
Norm = Norm)
## Do some processing in Python
## Set do-file information
# dofile = StataCodePath
# stata_app_path = '/Applications/Stata/StataSE.app/Contents/MacOS/StataSE'
# cmd = [stata_app_path, "do", dofile, "mpg", "weight", "foreign"]
# ## Run do-file
# subprocess.call(cmd)
elif task == 'check_age_all':
# create folder
folder = task #+ str(datetime.now()).split('.')[0].replace(':', '-').replace(' ', '_')
path = os.path.join('StataCode', folder)
print('Generate Path:', path)
if not os.path.exists(path):
os.makedirs(path)
# update T2
RawDataPath = 'StataReg/CountyVaccine-04-19.csv'
T2 = pd.read_csv(RawDataPath)
T2 = dependent_variable_construction(T2)
T2 = independent_variable_construction(T2)
# generate YXLists and cols
YXLists = []
cols = []
# Vax = 'CvdVax' # FullCvdVax, CvdVaxAbove20, CvdVaxAbove15. 'FluVax
for Vax in ['CvdVax']:
# Disparity = 'Disparity' # 'RD', 'LogRD', 'SD'
for Disparity in ['Disparity']:
# 'Base'
for Var_list in [
['Base'],
['Base', 'FluVax'],
['Base', 'FluVax', 'Above75'],
['Base', 'FluVax', 'Above75', 'A15T74'],
]:
YXcols = prepare_YX(Vax, Disparity, Var_list)
YXLists.append(YXcols)
cols = cols + [i for i in YXcols if i not in cols]
# generate T3
# print(all_variables)
T2, selected_columns = prep_process(T2, cols, path)
T3, T3Norm = standardize_data(T2, cols, selected_columns, path)
state_dummy_num = T3Norm['State'].nunique()
additonal_stata = []
# additonal_stata = ['drop if NotInHighMobility == 0']
# for Norm in [True, False]:
Norm = True
StataCodePath = gen_regression_code(YXLists,
additonal_stata,
state_dummy_num,
winsor = 95,
Norm = Norm)
## Do some processing in Python
## Set do-file information
# dofile = StataCodePath
# stata_app_path = '/Applications/Stata/StataSE.app/Contents/MacOS/StataSE'
# cmd = [stata_app_path, "do", dofile, "mpg", "weight", "foreign"]
# ## Run do-file
# subprocess.call(cmd)
elif task == 'check_age_above15':
# create folder
folder = task #+ str(datetime.now()).split('.')[0].replace(':', '-').replace(' ', '_')
path = os.path.join('StataCode', folder)
print('Generate Path:', path)
if not os.path.exists(path):
os.makedirs(path)
# update T2
RawDataPath = 'StataReg/CountyVaccine-04-19.csv'
T2 = pd.read_csv(RawDataPath)
T2 = dependent_variable_construction(T2)
T2 = independent_variable_construction(T2)
# generate YXLists and cols
YXLists = []
cols = []
# Vax = 'CvdVax' # FullCvdVax, CvdVaxAbove20, CvdVaxAbove15. 'FluVax
for Vax in ['CvdVaxAbove15']:
# Disparity = 'Disparity' # 'RD', 'LogRD', 'SD'
for Disparity in ['Disparity']:
# 'Base'
for Var_list in [
['Base'],
['Base', 'FluVax'],
['Base', 'FluVax', 'Above75'],
['Base', 'FluVax', 'Above75', 'A15T74'],
]:
YXcols = prepare_YX(Vax, Disparity, Var_list)
YXLists.append(YXcols)
cols = cols + [i for i in YXcols if i not in cols]
# generate T3
# print(all_variables)
T2, selected_columns = prep_process(T2, cols, path)
T3, T3Norm = standardize_data(T2, cols, selected_columns, path)
state_dummy_num = T3Norm['State'].nunique()
additonal_stata = []
# additonal_stata = ['drop if NotInHighMobility == 0']
# for Norm in [True, False]:
Norm = True
StataCodePath = gen_regression_code(YXLists,
additonal_stata,
state_dummy_num,
winsor = 95,
Norm = Norm)
## Do some processing in Python
## Set do-file information
# dofile = StataCodePath
# stata_app_path = '/Applications/Stata/StataSE.app/Contents/MacOS/StataSE'
# cmd = [stata_app_path, "do", dofile, "mpg", "weight", "foreign"]
# ## Run do-file
# subprocess.call(cmd)
elif task == 'check_age_above20':
# create folder
folder = task #+ str(datetime.now()).split('.')[0].replace(':', '-').replace(' ', '_')
path = os.path.join('StataCode', folder)
print('Generate Path:', path)
if not os.path.exists(path):
os.makedirs(path)
# update T2
RawDataPath = 'StataReg/CountyVaccine-04-19.csv'
T2 = pd.read_csv(RawDataPath)
T2 = dependent_variable_construction(T2)
T2 = independent_variable_construction(T2)
# generate YXLists and cols
YXLists = []
cols = []
# Vax = 'CvdVax' # FullCvdVax, CvdVaxAbove20, CvdVaxAbove15. 'FluVax
for Vax in ['CvdVaxAbove20']:
# Disparity = 'Disparity' # 'RD', 'LogRD', 'SD'
for Disparity in ['Disparity']:
# 'Base'
for Var_list in [
['Base'],
['Base', 'FluVax'],
['Base', 'FluVax', 'Above75'],
['Base', 'FluVax', 'Above75', 'A15T74'],
]:
YXcols = prepare_YX(Vax, Disparity, Var_list)
YXLists.append(YXcols)
cols = cols + [i for i in YXcols if i not in cols]
# generate T3
# print(all_variables)
T2, selected_columns = prep_process(T2, cols, path)
T3, T3Norm = standardize_data(T2, cols, selected_columns, path)
state_dummy_num = T3Norm['State'].nunique()
additonal_stata = []
# additonal_stata = ['drop if NotInHighMobility == 0']
# for Norm in [True, False]:
Norm = True
StataCodePath = gen_regression_code(YXLists,
additonal_stata,
state_dummy_num,
winsor = 95,
Norm = Norm)
## Do some processing in Python
## Set do-file information
# dofile = StataCodePath
# stata_app_path = '/Applications/Stata/StataSE.app/Contents/MacOS/StataSE'
# cmd = [stata_app_path, "do", dofile, "mpg", "weight", "foreign"]
# ## Run do-file
# subprocess.call(cmd)
elif task == 'check_disparity_types':
# create folder
folder = task #+ str(datetime.now()).split('.')[0].replace(':', '-').replace(' ', '_')
path = os.path.join('StataCode', folder)
print('Generate Path:', path)
if not os.path.exists(path):
os.makedirs(path)
# update T2
RawDataPath = 'StataReg/CountyVaccine-04-19.csv'
T2 = pd.read_csv(RawDataPath)
T2 = dependent_variable_construction(T2)
T2 = independent_variable_construction(T2)
# generate YXLists and cols
YXLists = []
cols = []
# Vax = 'CvdVax' # FullCvdVax, CvdVaxAbove20, CvdVaxAbove15. 'FluVax
for Vax in ['CvdVax']:
# Disparity = 'Disparity' # 'RD', 'LogRD', 'SD'
for Disparity in ['Disparity', 'RD', 'LogRD', 'SD']:
# 'Base'
for Var_list in [
['Base'],
# ['Base', 'FluVax'],
# ['Base', 'FluVax', 'Above75'],
# ['Base', 'FluVax', 'Above75', 'A15T74'],
]:
YXcols = prepare_YX(Vax, Disparity, Var_list)
YXLists.append(YXcols)
cols = cols + [i for i in YXcols if i not in cols]
# generate T3
# print(all_variables)
T2, selected_columns = prep_process(T2, cols, path)
T3, T3Norm = standardize_data(T2, cols, selected_columns, path)
state_dummy_num = T3Norm['State'].nunique()
additonal_stata = []
# additonal_stata = ['drop if NotInHighMobility == 0']
# for Norm in [True, False]:
Norm = True
StataCodePath = gen_regression_code(YXLists,
additonal_stata,
state_dummy_num,
winsor = 95,
Norm = Norm)
## Do some processing in Python
## Set do-file information
# dofile = StataCodePath
# stata_app_path = '/Applications/Stata/StataSE.app/Contents/MacOS/StataSE'
# cmd = [stata_app_path, "do", dofile, "mpg", "weight", "foreign"]
# ## Run do-file
# subprocess.call(cmd)
elif task == 'diff_dates':
# create folder
folder = task #+ str(datetime.now()).split('.')[0].replace(':', '-').replace(' ', '_')
for date in ['03-27', '04-07', '04-19', '05-20', '05-20_FullVax']:
path = os.path.join('StataCode', folder, date)
print('Generate Path:', path)
if not os.path.exists(path):
os.makedirs(path)
# update T2
RawDataPath = 'StataReg/CountyVaccine-{}.csv'.format(date.split('_')[0])
print(RawDataPath)
T2 = pd.read_csv(RawDataPath)
T2 = dependent_variable_construction(T2)
T2 = independent_variable_construction(T2)
# generate YXLists and cols
YXLists = []
cols = []
Vax = 'CvdVax' if 'FullVax' not in date else 'FullCvdVax'
Disparity = 'Disparity'
Var_list = ['Base']
YXcols = prepare_YX(Vax, Disparity, Var_list)
YXLists.append(YXcols)
cols = cols + [i for i in YXcols if i not in cols]
# generate T3
# print(all_variables)
T2, selected_columns = prep_process(T2, cols, path)
T3, T3Norm = standardize_data(T2, cols, selected_columns, path)
state_dummy_num = T3Norm['State'].nunique()
additonal_stata = []
# additonal_stata = ['drop if NotInHighMobility == 0']
# for Norm in [True, False]:
Norm = True
StataCodePath = gen_regression_code(YXLists,
additonal_stata,
state_dummy_num,
winsor = 95,
Norm = Norm)
## Do some processing in Python
## Set do-file information
dofile = StataCodePath
stata_app_path = '/Applications/Stata/StataSE.app/Contents/MacOS/StataSE'
cmd = [stata_app_path, "do", dofile, "mpg", "weight", "foreign"]
## Run do-file
# subprocess.call(cmd)
# pro = subprocess.Popen(cmd, stdout=subprocess.PIPE,
# shell=True, preexec_fn=os.setsid)
# os.killpg(os.getpgid(pro.pid), signal.SIGTERM)
elif task == 'residential_mobility':
# create folder
folder = task #+ str(datetime.now()).split('.')[0].replace(':', '-').replace(' ', '_')
path = os.path.join('StataCode', folder)
print('Generate Path:', path)
if os.path.exists(path):
shutil.rmtree(path)
os.makedirs(path)
# update T2
RawDataPath = 'StataReg/CountyVaccine-04-19.csv'
T2 = pd.read_csv(RawDataPath)
T2 = dependent_variable_construction(T2)
T2 = independent_variable_construction(T2)
# generate YXLists and cols
YXLists = []
cols = []
# Vax = 'CvdVax' # FullCvdVax, CvdVaxAbove20, CvdVaxAbove15. 'FluVax
for Vax in ['CvdVax']:
# Disparity = 'Disparity' # 'RD', 'LogRD', 'SD'
for Disparity in ['Disparity']:
# 'Base'
for Var_list in [
['Base'],
['Base', 'FluVax', ],
['Base', 'FluVax', 'Above75', ],
['Base', 'FluVax', 'Above75', 'A15T74'],
# ['Base', 'FluVax', 'Above75', 'A15T74', 'RecentPositive'],
]:
YXcols = prepare_YX(Vax, Disparity, Var_list)
YXLists.append(YXcols)
cols = cols + [i for i in YXcols if i not in cols]
# generate T3
# print(all_variables)
T2, selected_columns = prep_process(T2, cols, path)
T3, T3Norm = standardize_data(T2, cols, selected_columns, path)