-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathcreate_json.py
1388 lines (1221 loc) · 38.6 KB
/
create_json.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
# -*- coding: utf-8 -*-
import copy, csv, json, math, os, re
from scipy.ndimage import filters
import shapefile
import matplotlib.pyplot as plt
import numpy as np
import os
pjoin = os.path.join
from shapely import geometry
from shapely.geometry import Point
import pandas as pd
def flatten_json(j, r = None, prefix = [], delimiter = '/'):
if r is None:
r = {}
for k in j:
assert delimiter not in k, k
if type(j[k]) is dict:
flatten_json(j[k], r, prefix + [k])
else:
r[delimiter.join(prefix + [k])] = j[k]
return r
def pad(t, n, c=' '):
t = str(t)
return max(n - len(t), 0) * c + t
state_abbreviation_to_name = {
"AL": "Alabama",
"AK": "Alaska",
"AZ": "Arizona",
"AR": "Arkansas",
"CA": "California",
"CO": "Colorado",
"CT": "Connecticut",
"DE": "Delaware",
"DC": "District of Columbia",
"FL": "Florida",
"GA": "Georgia",
"GU": "Guam",
"HI": "Hawaii",
"ID": "Idaho",
"IL": "Illinois",
"IN": "Indiana",
"IA": "Iowa",
"KS": "Kansas",
"KY": "Kentucky",
"LA": "Louisiana",
"ME": "Maine",
"MD": "Maryland",
"MA": "Massachusetts",
"MI": "Michigan",
"MN": "Minnesota",
"MS": "Mississippi",
"MO": "Missouri",
"MT": "Montana",
"NE": "Nebraska",
"NV": "Nevada",
"NH": "New Hampshire",
"NJ": "New Jersey",
"NM": "New Mexico",
"NY": "New York",
"NC": "North Carolina",
"ND": "North Dakota",
"OH": "Ohio",
"OK": "Oklahoma",
"OR": "Oregon",
"PA": "Pennsylvania",
"RI": "Rhode Island",
"SC": "South Carolina",
"SD": "South Dakota",
"TN": "Tennessee",
"TX": "Texas",
"UT": "Utah",
"VT": "Vermont",
"VI": "Virgin Islands",
"VA": "Virginia",
"WA": "Washington",
"WV": "West Virginia",
"WI": "Wisconsin",
"WY": "Wyoming",
}
state_name_to_abbreviation = {}
for k in state_abbreviation_to_name:
state_name_to_abbreviation[state_abbreviation_to_name[k]] = k
fips_code_to_name = {
"01": "Alabama",
"02": "Alaska",
"04": "Arizona",
"05": "Arkansas",
"06": "California",
"08": "Colorado",
"09": "Connecticut",
"10": "Delaware",
"11": "District of Columbia",
"12": "Florida",
"13": "Georgia",
"15": "Hawaii",
"16": "Idaho",
"17": "Illinois",
"18": "Indiana",
"19": "Iowa",
"20": "Kansas",
"21": "Kentucky",
"22": "Louisiana",
"23": "Maine",
"24": "Maryland",
"25": "Massachusetts",
"26": "Michigan",
"27": "Minnesota",
"28": "Mississippi",
"29": "Missouri",
"30": "Montana",
"31": "Nebraska",
"32": "Nevada",
"33": "New Hampshire",
"34": "New Jersey",
"35": "New Mexico",
"36": "New York",
"37": "North Carolina",
"38": "North Dakota",
"39": "Ohio",
"40": "Oklahoma",
"41": "Oregon",
"42": "Pennsylvania",
"44": "Rhode Island",
"45": "South Carolina",
"46": "South Dakota",
"47": "Tennessee",
"48": "Texas",
"49": "Utah",
"50": "Vermont",
"51": "Virginia",
"53": "Washington",
"54": "West Virginia",
"55": "Wisconsin",
"56": "Wyoming",
"60": "American Samoa",
"66": "Guam",
"69": "Northern Mariana Islands",
"72": "Puerto Rico",
"78": "Virgin Islands",
}
state_name_to_fips_code = {
"Alabama": "01",
"Alaska": "02",
"Arizona": "04",
"Arkansas": "05",
"California": "06",
"Colorado": "08",
"Connecticut": "09",
"Delaware": "10",
"District of Columbia": "11",
"Florida": "12",
"Georgia": "13",
"Hawaii": "15",
"Idaho": "16",
"Illinois": "17",
"Indiana": "18",
"Iowa": "19",
"Kansas": "20",
"Kentucky": "21",
"Louisiana": "22",
"Maine": "23",
"Maryland": "24",
"Massachusetts": "25",
"Michigan": "26",
"Minnesota": "27",
"Mississippi": "28",
"Missouri": "29",
"Montana": "30",
"Nebraska": "31",
"Nevada": "32",
"New Hampshire": "33",
"New Jersey": "34",
"New Mexico": "35",
"New York": "36",
"North Carolina": "37",
"North Dakota": "38",
"Ohio": "39",
"Oklahoma": "40",
"Oregon": "41",
"Pennsylvania": "42",
"Rhode Island": "44",
"South Carolina": "45",
"South Dakota": "46",
"Tennessee": "47",
"Texas": "48",
"Utah": "49",
"Vermont": "50",
"Virginia": "51",
"Washington": "53",
"West Virginia": "54",
"Wisconsin": "55",
"Wyoming": "56",
"American Samoa": "60",
"Guam": "66",
"Northern Mariana Islands": "69",
"Puerto Rico": "72",
"Virgin Islands": "78",
}
not_states = set([
"American Samoa",
"Guam",
"Northern Mariana Islands",
"Puerto Rico",
"Virgin Islands",
])
# Maps formly independent cities to the counties they
# now belong to. This way we can add the deaths from
# these cities (which the CDC keeps separate, since its
# data goes back to 1999) to the counties the cities
# now belong to.
former_independent_cities_to_counties = {
"Virginia": {
"clifton forge city": "alleghany county",
"bedford city": "bedford county",
}
}
class CountyNameMerger:
kHardCoded = {
"Alabama": {
"de kalb": "dekalb county",
},
"Alaska": {
"anchorage borough": "anchorage municipality",
"juneau borough": "juneau city and borough",
"petersburg borough/census area": "petersburg borough",
"sitka borough": "sitka city and borough",
"skagway-hoonah-angoon census area" : "skagway municipality",
"wrangell-petersburg census area": "wrangell city and borough",
"yakutat borough": "yakutat city and borough",
# Formerly known as Wade Hampton Census Area
"wade hampton census area": "kusilvak census area",
# Renamed in 2008
"prince of wales-outer ketchikan census area": "prince of wales-hyder census area",
"anchorage borough/municipality": "anchorage municipality",
"juneau borough/city": "juneau city and borough",
"sitka borough/city": "sitka city and borough",
"wrangell borough/city": "wrangell city and borough",
"yakutat borough/city": "yakutat city and borough",
"municipality of anchorage": "anchorage municipality",
"city and borough of juneau": "juneau city and borough",
"petersburg census area": "petersburg borough",
},
"California": {
"san francisco county/city": "san francisco county",
},
"Colorado": {
"broomfield county/city": "broomfield county",
},
"District of Columbia": {
"washington": "district of columbia",
"district of columbia county": "district of columbia",
},
"Florida": {
"de soto": "desoto county",
},
"Georgia": {
"de kalb": "dekalb county",
},
"Idaho": {
"fremont (includes yellowstone park)": "fremont county"
},
"Illinois": {
"la salle": "lasalle county",
"du page": "dupage county",
"de kalb": "dekalb county",
},
"Indiana": {
"de kalb": "dekalb county",
"de kalb county": "dekalb county",
"la porte county": "laporte county",
"la porte": "laporte county",
"de kalb": "dekalb county",
"la grange": "lagrange county",
},
"Iowa": {
"o brien": "o'brien county",
},
"Louisiana": {
"la salle parish": "lasalle parish",
"la salle": "lasalle parish",
},
"Maryland": {
"baltimore (independent city)": "baltimore city",
"baltimore city county": "baltimore city",
"prince georges": "prince george's county",
"queen annes": "queen anne's county",
"st. marys": "st. mary's county",
},
"Mississippi": {
"de soto": "desoto county",
},
"Missouri": {
"jackson county (including other portions of kansas city)": "jackson county",
"city of st. louis": "st. louis city",
"st. louis city county": "st. louis city",
"Jackson County (including other portions of Kansas City)": "Jackson County",
"de kalb": "dekalb county",
},
"Nevada": {
"carson city county": "carson city"
},
"New Mexico": {
"debaca county": "de baca county",
"dona ana county": "doña ana county",
"dona ana": "doña ana county",
},
"North Dakota": {
"la moure": "lamoure county",
},
"Pennsylvania": {
"mc kean county": "mckean county",
},
"South Dakota": {
"shannon county": "oglala lakota county",
"shannon": "oglala lakota county",
},
"Tennessee": {
"de kalb": "dekalb county",
},
"Texas": {
"de witt": "dewitt county",
},
"Virginia": {
"colonial heights cit": "colonial heights city"
}
}
# if county not in states[state] and county + ' county' in states[state]:
# county = county + ' county'
# if county not in states[state] and county + ' parish' in states[state]:
# county = county + ' parish'
# assert county in states[state], f'{county}, {state}'
def __init__(self):
with open('base.json', 'r') as f:
self.states = json.load(f)
def merge_state(self, state, list1, list2, allow_missing, missing):
if (not allow_missing) and len(missing.get(state, {})) == 0:
assert len(list1) == len(list2), f"{state}\n\n{sorted(list1)}\n\n{sorted(list2)}"
assert len(set(list1)) == len(list1)
assert len(set(list2)) == len(list2)
hardCoded = CountyNameMerger.kHardCoded.get(state, {})
M = {}
i = 0
while i < len(list1):
county = list1[i].lower()
if county[:3] == 'st ':
county = 'st. ' + county[3:]
if county[-19:] == ' (independent city)':
if county[-23:-18] != 'city ':
county = county[:-19] + ' city'
else:
county = county[:-19]
if county[-12:] == ' county/city':
county = county[:-5]
if county[-12:] == ' county/town':
county = county[:-5]
if county in hardCoded:
j = list2.index(hardCoded[county])
M[list1[i]] = list2[j]
del list1[i]
del list2[j]
elif county in list2:
j = list2.index(county)
M[list1[i]] = list2[j]
del list1[i]
del list2[j]
elif county + ' county' in list2:
j = list2.index(county + ' county')
M[list1[i]] = list2[j]
del list1[i]
del list2[j]
elif state == 'Louisiana' and county + ' parish' in list2:
j = list2.index(county + ' parish')
M[list1[i]] = list2[j]
del list1[i]
del list2[j]
else:
i += 1
list1.sort()
list2.sort()
if state not in missing:
assert len(list1) == 0, f"{state}\n\n{list1}\n\n{list2}"
else:
assert len([x for x in list1 if x not in missing[state]]) == 0
if not allow_missing:
assert len(list2) - len(missing.get(state, {})) == 0, list2
# Assert mapping is not many-to-1
assert len(M.values()) == len(set(M.values()))
return M
def merge_with_fips(self, counties, missing=set()):
kFipsConversions = {
# Shannon County renamed to Oglala Lakota County
"46113": "46102",
# kusilvak census area renamed to wade hampton census area
"02158": "02270",
}
for state_name in self.states:
for county_name in self.states[state_name]:
county = self.states[state_name][county_name]
fips = county["fips"]
if kFipsConversions.get(fips, None) in counties:
fips = kFipsConversions[fips]
if fips in missing:
continue
self.add_to_json(county, counties[fips])
def merge(self, states, allow_missing=False, missing={}):
if not allow_missing:
assert len(states) == 51
for state in states:
M = self.merge_state(
state,
list(states[state].keys()),
list(self.states[state].keys()),
allow_missing=allow_missing,
missing=missing
)
for county in M:
self.add_to_json(
self.states[state][M[county]],
states[state][county]
)
def add_to_json(self, base, addition):
for k in addition:
assert k not in base, f'base already has "{k}"'
base[k] = addition[k]
def get_geometry():
counties = {}
sf = shapefile.Reader(pjoin('data', 'tl_2017_us_county/tl_2017_us_county.shp'))
# Add geometric data for countries.
for s in sf:
state = fips_code_to_name[s.record.STATEFP]
if state in not_states:
continue
fips = s.record.GEOID
county_name = s.record.NAMELSAD.lower()
# There is one county that crosses from negative
# to positive longitudes, which screws up center-point
# computations. To fix this we subtact 360 from
# positive longitudes.
poly = geometry.Polygon([(x - 360 if x > 0 else x, y) for x, y in s.shape.points])
# We explicitly compute centroids rather than use
# s.record.INTPTLAT and s.record.INTPTLON, since
# I can't find any documentation of how these
# points are actually picked. We use the convex
# hull since some 'polygons' are weird, due to some
# islands containing islands of territory (figuratively
# and literally).
center = poly.convex_hull.centroid
counties[fips] = {
"land_area (km^2)": s.record.ALAND / 1e6,
"area (km^2)": (s.record.ALAND + s.record.AWATER) / 1e6,
# NOTE: we don't undo the "- 360" transformation
# above, since most use cases probably *prefer*
# not having to deal with the wrapping behavior.
"longitude (deg)": center.x,
"latitude (deg)": center.y,
}
return counties
def get_zips():
with open(pjoin('data', 'zip_county_fips_2018_03.csv'), 'r') as f:
reader = csv.reader(f, delimiter=',')
header = next(reader)
rows = [row for row in reader]
counties = {}
for zipcode, fips, city, state, county, _ in rows:
if state in ["PR", "GU", "VI"]:
continue
if fips not in counties:
counties[fips] = {
'zip-codes': []
}
counties[fips]['zip-codes'].append(zipcode)
# kusilvak census area
counties["02158"] = {
"zip-codes": [
"99554", "99563", "99581", "99585", "99604", "99620", "99632", "99650", "99657", "99658", "99662", "99666"
]
}
# oglala lakota county
counties["46113"] = {
"zip-codes": [
"57716", "57752", "57756", "57764", "57770", "57772", "57794",
]
}
return counties
def get_demographics():
age_code_to_group = {
0: "all",
1: "0-4",
2: "5-9",
3: "10-14",
4: "15-19",
5: "20-24",
6: "25-29",
7: "30-34",
8: "35-39",
9: "40-44",
10: "45-49",
11: "50-54",
12: "55-59",
13: "60-64",
14: "65-69",
15: "70-74",
16: "75-79",
17: "80-84",
18: "85+"
}
# https://www2.census.gov/programs-surveys/popest/technical-documentation/file-layouts/2010-2019/cc-est2019-alldata.pdf
year_code_to_year = {
"1": "4/1/2010",
"2": "4/1/2010", # sic
"3": "7/1/2010",
"4": "7/1/2011",
"5": "7/1/2012",
"6": "7/1/2013",
"7": "7/1/2014",
"8": "7/1/2015",
"9": "7/1/2016",
"10": "7/1/2017",
"11": "7/1/2018",
"12": "7/1/2019",
}
# After downloading this file you should open it with a text editor (
# I use Sublime) and re-encode it as utf8.
counties = {}
populations = {}
with open(pjoin('data', 'cc-est2019-alldata.csv'), 'r') as f:
reader = csv.reader(f, delimiter=',')
header = next(reader)
rows = [row for row in reader]
assert header[:7] == ['SUMLEV', 'STATE', 'COUNTY', 'STNAME', 'CTYNAME', 'YEAR', 'AGEGRP']
for row in rows:
fips = row[1] + row[2]
county = row[4].lower()
year = year_code_to_year[row[5]].split('/')[-1]
if fips not in populations:
populations[fips] = {}
age_group = int(row[6])
total = int(row[7])
if age_group == 0:
populations[fips][year] = total
# We only grab the latest year available and ignore the
# other rows.
if year_code_to_year[row[5]] != '7/1/2019':
continue
if age_group == 0:
# age group "0" is everyone. We grab racial data from
# this row. The racial break down done by the Census
# Bureau is... intense, with 73 different columns. To
# keep the file size reasonable I don't track them all.
# Fortunately the code and data is freely available so
# it is trivial for you to add more columns if you like!
# We assume this is the first row we see.
assert fips not in counties
counties[fips] = {}
counties[fips]['race'] = {}
counties[fips]['age'] = {}
counties[fips]['male'] = int(row[8])
counties[fips]['female'] = int(row[9])
counties[fips]['population'] = total
counties[fips]['race']['non_hispanic_white_alone_male'] = int(row[34]) / total
counties[fips]['race']['non_hispanic_white_alone_female'] = int(row[35]) / total
counties[fips]['race']['black_alone_male'] = int(row[12]) / total
counties[fips]['race']['black_alone_female'] = int(row[13]) / total
counties[fips]['race']['asian_alone_male'] = int(row[16]) / total
counties[fips]['race']['asian_alone_female'] = int(row[17]) / total
counties[fips]['race']['hispanic_male'] = int(row[56]) / total
counties[fips]['race']['hispanic_female'] = int(row[57]) / total
else:
counties[fips]['age'][age_code_to_group[int(row[6])]] = int(row[7]) / counties[fips]['population']
for fip in counties:
counties[fip]['population'] = populations[fip]
return counties
def get_cdc_deaths():
counties = {}
fns = [
"Compressed Mortality, 1999-2019 (all suicides).txt",
"Compressed Mortality, 1999-2019 (firearm suicides).txt",
"Compressed Mortality (assaults), 1999-2019.txt",
"Compressed Mortality (land vehicle deaths; ICD-10 codes V01-V89), 1999-2019.txt"
]
for varname, fn in zip(['suicides', 'firearm suicides', 'homicides', 'vehicle'], fns):
with open(pjoin('data', 'CDC', fn), 'r') as f:
reader = csv.reader(f, delimiter='\t', quotechar='"')
rows = [row for row in reader]
header = rows[0]
rows = rows[1:]
rows = rows[:rows.index(['---']) - 1]
former_independent_cities = {}
for row in rows:
_, county, fips, deaths, _, _ = row
county = county.lower()
state = state_abbreviation_to_name[county.split(', ')[-1].upper()]
county = ', '.join(county.split(', ')[:-1])
# These counties changed their names recently, and rows with
# both the old names and new names are found in the CDC
# dataset, so we simply ignore these names.
if county in ['prince of wales-outer ketchikan census area', 'skagway-hoonah-angoon census area', "wrangell-petersburg census area"]:
continue
if deaths == 'Suppressed':
deaths = None
elif deaths == 'Missing':
deaths = -1
else:
deaths = int(deaths) / 21.0
if state in former_independent_cities_to_counties and county in former_independent_cities_to_counties[state]:
county = former_independent_cities_to_counties[state][county]
if state not in former_independent_cities:
former_independent_cities[state] = {}
former_independent_cities[state][county] = deaths
continue
if fips not in counties:
counties[fips] = {
"deaths": {}
}
assert varname not in counties[fips]["deaths"]
counties[fips]["deaths"][varname] = deaths
# Add formly independent cities to their respective counties.
for state in former_independent_cities:
for county in former_independent_cities[state]:
# If either value was suppressed, we keep the concatenated
# value as None.
if counties[fips]["deaths"][varname] is None:
continue
if former_independent_cities[state][county] is None:
continue
counties[fips]["deaths"][varname] += former_independent_cities[state][county]
return counties
# Labor force data
# https://www.bls.gov/lau/#cntyaa
def get_labor_force():
counties = {}
years = ['2004', '2008', '2012', '2016', '2020']
for year in years:
with open(pjoin('data', 'bls', year + '.txt'), 'r') as f:
lines = f.readlines()
for line in lines[6:]:
line = line.strip()
if len(line) == 0:
break
laus_code, state_fips_code, county_fips_code, county_name, year, labor_force, employed, unemployed, unemployment_rate = re.sub(r" +", " ", line).split(" ")
if state_fips_code == '72': # PR
continue
fips = state_fips_code + county_fips_code
if fips not in counties:
counties[fips] = {'bls': {}}
c = {}
c['labor_force'] = float(labor_force.replace(",",""))
c['employed'] = float(employed.replace(",",""))
c['unemployed'] = float(unemployed.replace(",",""))
# NOTE: we exclude unemployment_rate since it is trivially computable as
# "unemployed / labor_force"
# c['unemployment_rate'] = float(unemployment_rate)
counties[fips]['bls'][year] = c
return counties
def get_fatal_police_shootings():
states = {}
for year in ['2017', '2018', '2019', '2020']:
for varname in [f'total-{year}', f'unarmed-{year}', f'firearmed-{year}']:
with open(pjoin('generated', 'police_shootings', varname + '.json'), 'r') as f:
shootings = json.load(f)
for k in shootings:
state_name = state_abbreviation_to_name[k[-2:].upper()]
if state_name not in states:
states[state_name] = {}
state = states[state_name]
county_name = k[:-4]
if county_name not in state:
state[county_name] = {
"fatal_police_shootings": {}
}
state[county_name]["fatal_police_shootings"][varname] = shootings[k]
return states
def get_police_deaths():
states = {}
with open(pjoin('data', 'police-deaths-2019.txt'), 'r') as f:
lines = f.readlines()[8:]
lines = [line.strip() for line in lines]
F = {}
for i in range(0, len(lines), 5):
name = lines[i + 0]
cause = lines[i + 2]
F[cause] = F.get(cause, 0) + 1
location = lines[i + 3]
state = state_abbreviation_to_name[location[-2:]]
county = location[:-4].lower()
if state not in states:
states[state] = {}
if county not in states[state]:
states[state][county] = {}
states[state][county]['police_deaths'] = states[state][county].get('police_deaths', 0) + 1
return states
def get_avg_income():
states = {}
for fn in os.listdir(pjoin('data', 'CAINC1')):
with open(pjoin('data', 'CAINC1', fn), 'r', encoding='Latin-1') as f:
reader = csv.reader(f, delimiter=',')
header = next(reader)
rows = [row for row in reader]
for row in rows[3:-1]:
if len(row) < 7:
continue
if row[6] != 'Per capita personal income (dollars) 2/':
continue
# This is an effective way to ensure the row is
# sensible (and not a footer / footnote).
try:
avg_income = int(row[-1])
except ValueError:
continue
loc = row[1]
# ignore fotenotes...
while loc[-1] == '*':
loc = loc[:-1]
assert loc[-4:-2] == ', '
county = loc[:-4].lower()
state = state_abbreviation_to_name[loc[-2:]]
if state not in states:
states[state] = {}
# These counties are combined...
if loc == 'Maui + Kalawao, HI':
assert "maui county" not in states[state]
assert "kalawao county" not in states[state]
states[state]['maui county'] = {
"avg_income": avg_income
}
states[state]['kalawao county'] = {
"avg_income": avg_income
}
continue
# Independent cities are merged with their surrounding counties.
# We un-merge them here.
if '+' in county:
parts = [x.strip() for x in re.findall(r"[^,\+]+", county)]
assert parts[0] + ' county' not in states[state]
states[state][parts[0] + ' county'] = {
"avg_income": avg_income
}
for part in parts[1:]:
if part[-5:] != ' city':
part += ' city'
assert part not in states[state]
states[state][part] = {}
states[state][part]['avg_income'] = avg_income
continue
assert county not in states[state]
states[state][county] = {
"avg_income": avg_income
}
for state in states:
for county in states[state]:
assert 'avg_income' in states[state][county]
return states
def get_poverty():
with open('data/poverty.tsv', 'r') as f:
reader = csv.reader(f, delimiter='\t')
header = next(reader)
rows = [row for row in reader]
fipsIdx = header.index('FIPStxt')
povertyIdx = header.index('PCTPOVALL_2019')
fips2poverty = {}
for row in rows:
p = row[povertyIdx]
p = p.replace(',', '')
fips2poverty[row[fipsIdx]] = {
'poverty-rate': float(p)
}
return fips2poverty
def get_education():
with open('data/education.tsv', 'r') as f:
reader = csv.reader(f, delimiter='\t')
header = next(reader)
rows = [row for row in reader]
fipsIdx = header.index('FIPS Code')
lessThanHighSchoolIdx = header.index('Percent of adults with less than a high school diploma, 2015-19')
highSchoolIdx = header.index('Percent of adults with a high school diploma only, 2015-19')
someCollegeIdx = header.index("Percent of adults completing some college or associate's degree, 2015-19")
bachelorsIdx = header.index("Percent of adults with a bachelor's degree or higher, 2015-19")
fips2edu = {}
for row in rows:
A = {
'less-than-high-school': row[lessThanHighSchoolIdx],
'high-school': row[highSchoolIdx],
'some-college': row[someCollegeIdx],
'bachelors+': row[bachelorsIdx]
}
for k in A:
if A[k] == '':
A[k] = None
else:
A[k] = float(A[k])
fips2edu[row[fipsIdx]] = { 'edu': A }
return fips2edu
def get_covid():
fips2covid = {}
for varname, fn in zip(['deaths', 'confirmed'], ['covid_deaths_usafacts.csv', 'covid_confirmed_usafacts.csv']):
with open(pjoin('data', fn), 'r') as f:
reader = csv.reader(f, delimiter=',')
header = next(reader)
countyColumn = header.index('countyFIPS')
stateColumn = header.index('State')
rows = [row for row in reader]
for row in rows:
for date in [date for date in header if re.match(r"\d{4}-\d\d-01", date)]:
column = header.index(date)
fips = row[countyColumn]
if fips == '0':
# Unallocated cases make up a vanishingly small proportion of data.
continue
if len(fips) == 4:
fips = '0' + fips
if fips not in fips2covid:
fips2covid[fips] = {}
if f"covid-{varname}" not in fips2covid[fips]:
fips2covid[fips][f"covid-{varname}"] = {}
assert date not in fips2covid[fips][f"covid-{varname}"], (date, fips)
fips2covid[fips][f"covid-{varname}"][date] = int(row[column])
with open(pjoin('data', 'COVID-19_Vaccinations_in_the_United_States_County.csv'), 'r') as f:
reader = csv.reader(f, delimiter=',')
header = next(reader)
rows = [row for row in reader]
def fix_vac_date(date):
month, day, year = date.split('/')
return '-'.join([year, month, day])
for row in rows[::-1]:
fips = row[1]
if not re.match(r"^\d\d/01/2021$", row[0]):
continue
if fips not in fips2covid:
continue
if 'covid-vaccination' not in fips2covid[fips]:
fips2covid[fips]['covid-vaccination'] = {}
fips2covid[fips]["covid-vaccination"][fix_vac_date(row[0])] = float(row[5])
return fips2covid
def get_elections():
states = {}
fips_to_county = {
'08014': ('broomfield county', 'Colorado')
}
with open(pjoin('data', 'fips_to_county.txt'), 'r') as f:
for line in f.readlines():
if len(line.strip()) == 0:
continue
code, county, state = line.strip().split('\t')
# American Samoa, Northern Mariana Islands, Puerto Rico
if state in ['AS', 'MP', 'PR']:
continue
fips_to_county[code] = (county.lower(), state_abbreviation_to_name[state])
with open(pjoin('data', 'US_County_Level_Presidential_Results_08-16.csv'), 'r') as f:
reader = csv.reader(f, delimiter=',')
header = next(reader)
assert header == ['fips_code', 'county', 'total_2008', 'dem_2008', 'gop_2008', 'oth_2008', 'total_2012', 'dem_2012', 'gop_2012', 'oth_2012', 'total_2016', 'dem_2016', 'gop_2016', 'oth_2016']
rows = [row for row in reader]
for row in rows:
county, state = fips_to_county[row[0]]
if state not in states:
states[state] = {}
all2008 = int(row[2])
dem2008 = int(row[3])
gop2008 = int(row[4])
all2012 = int(row[6])
dem2012 = int(row[7])
gop2012 = int(row[8])
all2016 = int(row[10])
dem2016 = int(row[11])
gop2016 = int(row[12])
states[state][county] = {
"elections": {
"2008": {
"total": all2008,
"dem": dem2008,
"gop": gop2008,
},
"2012": {
"total": all2012,
"dem": dem2012,
"gop": gop2012,