-
Notifications
You must be signed in to change notification settings - Fork 0
/
dataprocessor.py
1613 lines (1402 loc) · 91.2 KB
/
dataprocessor.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 json
from constants_and_util import *
import math
from dask import dataframe as dd
from dask.diagnostics import ProgressBar
import dask
import fiona
from shapely.geometry import shape, Point, LineString, Polygon
from shapely import wkt
import pandas as pd
from scipy.stats import scoreatpercentile
from sklearn.neighbors import KDTree
from sklearn.cluster import DBSCAN, KMeans, AgglomerativeClustering
import numpy as np
import sys
import pickle
from IPython import embed
import itertools
import time
import copy
import random
import pytz
from timezonefinder import TimezoneFinder
from scipy.interpolate import interp1d
import zipfile
import io
from scipy.spatial import cKDTree
import geohash as geohash_lib
from collections import Counter, defaultdict
import xmltodict
import reverse_geocoder
import requests
import json
from geopy.geocoders import Nominatim, GoogleV3, Photon, AzureMaps, GeoNames, What3Words, MapBox
from traceback import print_exc
import matplotlib.pyplot as plt
import warnings
import hashlib
import csv
import glob
from geopandas.tools import sjoin
import os
import shutil
import argparse
import geopandas
def run_all_jobs_for_extract_middle_of_night_locations():
for id_prefix in VALID_ID_PREFIXES:
outfile_name = get_middle_of_night_locations_outfile(id_prefix)
os.makedirs(os.path.dirname(outfile_name), exist_ok=True)
outfile = open_file_for_exclusive_writing(outfile_name)
if outfile is None: continue # No need to run job.
with outfile: # The 'with' will close the file when done.
extract_middle_of_night_locations(id_prefix=id_prefix, outfile=outfile,
**MIDDLE_OF_NIGHT_HYPERPARAMS)
def get_middle_of_night_locations_outfile(id_prefix):
"""
Gives the path for the middle of night locations for a given id prefix.
This is grouped by id_prefix.
We save inferred home locations for each user (as a pickle).
annotations_string is a string which we concatenate onto the filename so we don't overwrite previous files as we do data processing.
"""
return os.path.join(MIDDLE_OF_NIGHT_LOCATIONS_DIR, 'inferred_home_locations_id_prefix_%s.pkl' % id_prefix)
def extract_middle_of_night_locations(id_prefix,
outfile,
local_start_hour,
local_end_hour,
weekdays_only,
min_nights_required,
max_distance,
min_frac_near_median,
min_total_pings_a_user_must_have):
"""
Method for inferring home location of each user based on where they are at night.
Parameters for filtering users with reliable locations (We will likely have to change these.)
local_start_hour,local_end_hour range is inclusive, specifies what times we look at as "middle of night locations".
weekdays_only: only look at Mon-Fri for middle of night locations.
min_nights_required, max_distance, min_frac_near_median: hyperparameters for new_infer_home_or_work_location_for_single_user.
min_total_pings_a_user_must_have: only look at users with this number of pings.
write_out_middle_of_night_locations: if false, do not write out the inferred locations (if we're just testing different hyperparameter settings, for example)
"""
assert type(local_start_hour) is int
assert type(local_end_hour) is int
local_start_before_noon = local_start_hour < 12
local_end_before_noon = local_end_hour < 12
valid_days_and_hours = set() # Filter for hours/days in the range we are looking for. This involves some annoying case-by-case code.
weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
all_days = weekdays + ['Saturday' ,'Sunday']
if local_start_before_noon and local_end_before_noon:
assert local_start_hour < local_end_hour
if weekdays_only:
days_to_use = weekdays
else:
days_to_use = all_days
for hour in range(local_start_hour, local_end_hour + 1):
for day in days_to_use:
valid_days_and_hours.add('%s %02d' % (day, hour))
elif (not local_start_before_noon) and local_end_before_noon:
if weekdays_only:
for hour in range(local_start_hour, 24):
for day in ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday']:
valid_days_and_hours.add('%s %02d' % (day, hour))
for hour in range(0, local_end_hour + 1):
for day in weekdays:
valid_days_and_hours.add('%s %02d' % (day, hour))
else:
for hour in range(local_start_hour, 24):
for day in all_days:
valid_days_and_hours.add('%s %02d' % (day, hour))
for hour in range(0, local_end_hour + 1):
for day in all_days:
valid_days_and_hours.add('%s %02d' % (day, hour))
else:
raise Exception("Something is weird here.")
print("Valid weekdays and hours:\n%s" % '\n'.join(sorted(list(valid_days_and_hours))))
all_outfiles = list_files_in_range('locations',
min_id_prefix=id_prefix,
max_id_prefix=id_prefix,
utc_days=UTC_DAYS_TO_USE_IN_ANALYSIS)
all_dataframes = []
total_pings_by_user = {} # we are only interested in people who have a minimum number of pings.
for filename in all_outfiles:
d = load_ping_file(file_path=filename, filter_horizontal_acc=False)
assert d['safegraph_id'].map(lambda x:x[:2] == id_prefix).all()
pings_by_user = Counter(d['safegraph_id'])
for user in pings_by_user:
if user not in total_pings_by_user:
total_pings_by_user[user] = pings_by_user[user]
else:
total_pings_by_user[user] += pings_by_user[user]
d['local_weekday_and_hour'] = d['local_datetime'].map(
lambda x:datetime.datetime.strptime(x, DATETIME_FORMATTER_STRING).strftime('%A %H'))
old_len = len(d)
d = d.loc[d['local_weekday_and_hour'].map(lambda x:x in valid_days_and_hours)] # filter for middle-of-night pings.
def get_day_to_group_by(x):
as_datetime = datetime.datetime.strptime(x, DATETIME_FORMATTER_STRING)
if as_datetime.hour < 12:
datetime_to_group_by = as_datetime
else:
datetime_to_group_by = datetime.datetime(as_datetime.year, as_datetime.month, as_datetime.day) + datetime.timedelta(days=1)
return datetime_to_group_by.strftime('%Y-%m-%d')
print("original length of %s is %i; after filtering for middle-of-night locs, %i; users in this dataframe, %i, total users in all dataframes seen thus far, %i" % (
filename, old_len, len(d), len(pings_by_user), len(total_pings_by_user)))
d['day_to_group_by'] = d['local_datetime'].map(get_day_to_group_by)
if len(d) > 0:
all_dataframes.append(d[['safegraph_id',
'latitude',
'longitude',
'day_to_group_by',
'horizontal_accuracy',
'utc_datetime',
'local_datetime']])
n_total_users = len(total_pings_by_user)
users_with_enough_pings_to_try_to_infer_homes = set([a for a in total_pings_by_user if total_pings_by_user[a] >= min_total_pings_a_user_must_have])
n_users_with_enough_pings_to_try_to_infer_homes = len(users_with_enough_pings_to_try_to_infer_homes)
print("Number of users with the required number of pings: %i/%i" %
(n_users_with_enough_pings_to_try_to_infer_homes, n_total_users))
combined_df = pd.concat(all_dataframes)
combined_df = combined_df.loc[combined_df['safegraph_id'].map(lambda x:x in users_with_enough_pings_to_try_to_infer_homes)]
combined_df.index = range(len(combined_df))
grouped_d = combined_df.groupby('safegraph_id')
users_with_home_locations = {}
filter_out_reasons = {}
for safegraph_id, user_d in grouped_d:
filter_out_reason, data_to_save = new_infer_home_or_work_location_for_single_user(
user_d,
min_nights_required=min_nights_required,
max_distance=max_distance,
min_frac_near_median=min_frac_near_median)
if filter_out_reason is None:
users_with_home_locations[safegraph_id] = data_to_save
else:
if filter_out_reason not in filter_out_reasons:
filter_out_reasons[filter_out_reason] = 0
filter_out_reasons[filter_out_reason] += 1
print("Total number of user-night observations: %i" % len(combined_df))
print("Was able to infer locations for %i users. Reasons for removing users are:" % (len(users_with_home_locations)),
filter_out_reasons)
pickle.dump(users_with_home_locations, outfile)
def new_infer_home_or_work_location_for_single_user(d,
min_nights_required,
max_distance,
min_frac_near_median,
min_nights_near_median=0,
clustering_algorithm_for_centroid=None,
clustering_kwargs=None):
"""
Given a dataframe of pings for a single user, infer home or work location.
This is the inner method in home/work location inference methods: it doesn't do things like filter for pings during workplace hours.
Rather, it looks for clusters of pings for a single user.
Return two arguments: an error message if home/work cannot be inferred (None if it can)
and a dictionary of information about the home if it can be inferred (None otherwise)
basic idea: interpolate user's location at each hour, filter for hours where they don't move, take median of those hours.
Parameters:
min_nights_required: we need data from at least this many nights. Note that we only count a night if the user also has an interpolated hour which is stationary.
max_distance: we use this to determine what constitutes too much movement between hours, and also when locations are too scattered around the median.
min_frac_near_median: at least this proportion of hours must be near the median.
Because this was originally designed to infer home locations, some of the naming is a little confusing -- it uses "nights" when actually it means to refer to "days or nights". In general, it refers to distinct days -- eg, 9 AM-5 PM periods for workplace inference, and 1-5 AM periods for home inference.
"""
clustering_kwargs = copy.deepcopy(clustering_kwargs)
if len(set(d['day_to_group_by'])) < min_nights_required:
return 'too_few_nights', None
grouped_by_night = d.groupby('day_to_group_by')
all_good_lats = []
all_good_lons = []
all_groups = [] # what day does each interpolated ping occur on.
n_nights = 0
for night, night_d in grouped_by_night:
interpolated_timestamps, interpolated_latitudes, interpolated_longitudes = interpolate_locations_at_timestamps(
datetime_strings=night_d['utc_datetime'].values,
latitudes=night_d['latitude'].values,
longitudes=night_d['longitude'].values)
if len(interpolated_timestamps) > 1:
dists = compute_distance_between_two_lat_lons(lat1=interpolated_latitudes[1:],
lon1=interpolated_longitudes[1:],
lat2=interpolated_latitudes[:-1],
lon2=interpolated_longitudes[:-1])
dists = np.array(list(dists) + [np.inf]) # automatically drop last interpolated timestamp.
good_lats = interpolated_latitudes[dists < max_distance]
good_lons = interpolated_longitudes[dists < max_distance]
if len(good_lons) > 0:
n_nights += 1
all_good_lats += list(good_lats)
all_good_lons += list(good_lons)
all_groups += [night for i in range(len(good_lons))]
if n_nights < min_nights_required:
return 'too_few_nights', None
all_good_lats = np.array(all_good_lats)
all_good_lons = np.array(all_good_lons)
all_groups = np.array(all_groups)
if clustering_algorithm_for_centroid is not None:
x, y, z = lonlat_to_xyz(lon=all_good_lons, lat=all_good_lats)
n_unique_locs = len(pd.DataFrame({'a':all_good_lons, 'b':all_good_lats}).drop_duplicates())
spatial_locs = np.array([x, y, z]).transpose()
if clustering_algorithm_for_centroid == 'kmeans':
clustering_kwargs['n_clusters'] = min(clustering_kwargs['n_clusters'], n_unique_locs)
clustering_model = KMeans(random_state=0, **clustering_kwargs)
elif clustering_algorithm_for_centroid == 'DBSCAN':
clustering_model = DBSCAN(min_samples=3, **clustering_kwargs)
elif clustering_algorithm_for_centroid == 'hierarchical_clustering':
clustering_kwargs['n_clusters'] = min(clustering_kwargs['n_clusters'], n_unique_locs)
clustering_model = AgglomerativeClustering(linkage='single', **clustering_kwargs)
else:
raise Exception("Invalid clustering algorithm")
clustering_model.fit(spatial_locs)
clustering_labels = clustering_model.labels_
cluster_counts = Counter(clustering_labels)
largest_cluster_idx = cluster_counts.most_common()[0][0]
largest_cluster_members = clustering_labels == largest_cluster_idx
median_lat = np.median(all_good_lats[largest_cluster_members]) # Convert back to lat,lon space by taking the median.
median_lon = np.median(all_good_lons[largest_cluster_members])
else:
median_lat = np.median(all_good_lats)
median_lon = np.median(all_good_lons)
distance_from_median = compute_distance_between_two_lat_lons(lat1=median_lat,
lon1=median_lon,
lat2=all_good_lats,
lon2=all_good_lons)
not_outliers = (distance_from_median < max_distance)
n_nights_near_median = len(set(all_groups[not_outliers])) # in case we want to filter for people who return to the place on several unique days.
frac_near_median = not_outliers.mean()
if frac_near_median < min_frac_near_median:
return 'too_scattered', None
if n_nights_near_median < min_nights_near_median:
return 'too_few_nights_near_median', None
all_good_lats = all_good_lats[not_outliers]
all_good_lons = all_good_lons[not_outliers]
median_lat = np.median(all_good_lats)
median_lon = np.median(all_good_lons)
lat_std_err = np.std(all_good_lats, ddof=1) / np.sqrt(len(all_good_lats)) # this is very heuristic.
lon_std_err = np.std(all_good_lons, ddof=1) / np.sqrt(len(all_good_lons))
std_err_in_meters = compute_distance_between_two_lat_lons(lat1=median_lat,
lat2=median_lat + lat_std_err,
lon1=median_lon,
lon2=median_lon + lon_std_err)
results_to_return = {'inferred_home_location_lat':median_lat,
'inferred_home_location_lon':median_lon,
'n_nights_used_to_infer_including_outliers':n_nights,
'n_hourly_pings_used_to_infer_including_outliers':len(not_outliers),
'n_hourly_pings_used_to_infer_not_including_outliers':not_outliers.sum(),
'frac_near_median':frac_near_median,
'std_err_in_meters':std_err_in_meters,
'n_nights_went_near_median':n_nights_near_median}
return None, results_to_return
class CensusBlockGroups:
"""
A class for loading geographic and demographic data from the ACS.
A census block group is a relatively small area (I think it's a couple hundred households).
Less good than houses but still pretty granular. https://en.wikipedia.org/wiki/Census_block_group
Data was downloaded from https://www.census.gov/geographies/mapping-files/time-series/geo/tiger-data.html
We use the most recent ACS 5-year estimates: 2013-2017, eg:
wget https://www2.census.gov/geo/tiger/TIGER_DP/2017ACS/ACS_2017_5YR_BG.gdb.zip
These files are convenient because they combine both geographic boundaries + demographic data, leading to a cleaner join.
Documentation of column names is at /projects/p30458/non_safegraph_datasets/census_block_group_data/ACS_5_year_2013_to_2017_joined_to_blockgroup_shapefiles/documentation_ACS_2017_joined_to_blockgroup_shapefile.txt
The main method for data access is get_demographic_stats_of_point. Sample usage:
x = CensusBlockGroups(gdb_files=['ACS_2017_5YR_BG_51_VIRGINIA.gdb'])
x.get_demographic_stats_of_points(latitudes=[38.8816], longitudes=[-77.0910], desired_cols=['p_black', 'p_white', 'mean_household_income'])
"""
def __init__(self, base_directory=BASE_DIRECTORY_FOR_EVERYTHING,
gdb_files=None,
county_to_msa_mapping_file='august_2017_county_to_metropolitan_mapping.csv'):
self.base_directory = base_directory
if gdb_files is None:
self.gdb_files = ['ACS_2017_5YR_BG.gdb']
else:
self.gdb_files = gdb_files
self.crs_to_use = WGS_84_CRS # https://epsg.io/4326, WGS84 - World Geodetic System 1984, used in GPS.
self.county_to_msa_mapping_file = county_to_msa_mapping_file
self.load_raw_dataframes() # Load in raw geometry and demographic dataframes.
self.annotate_with_race()
self.annotate_with_education()
self.annotate_with_income()
self.annotate_with_rent_as_percentage_of_block_group_income()
self.annotate_with_counties_to_msa_mapping()
def annotate_with_race(self):
"""
Note that the Experienced Segregation paper only considers black/white.
B03002e1 HISPANIC OR LATINO ORIGIN BY RACE: Total: Total population -- (Estimate)
B03002e3 HISPANIC OR LATINO ORIGIN BY RACE: Not Hispanic or Latino: White alone: Total population -- (Estimate)
B03002e4 HISPANIC OR LATINO ORIGIN BY RACE: Not Hispanic or Latino: Black or African American alone: Total population -- (Estimate)
B03002e6 HISPANIC OR LATINO ORIGIN BY RACE: Not Hispanic or Latino: Asian alone: Total population -- (Estimate)
B03002e12 HISPANIC OR LATINO ORIGIN BY RACE: Hispanic or Latino: Total population -- (Estimate)
"""
print("annotating with race")
self.block_group_d['p_black'] = self.block_group_d['B03002e4'] / self.block_group_d['B03002e1']
self.block_group_d['p_white'] = self.block_group_d['B03002e3'] / self.block_group_d['B03002e1']
self.block_group_d['p_asian'] = self.block_group_d['B03002e6'] / self.block_group_d['B03002e1']
self.block_group_d['p_hispanic'] = self.block_group_d['B03002e12'] / self.block_group_d['B03002e1']
print(self.block_group_d[['p_black', 'p_white', 'p_asian', 'p_hispanic']].describe())
def annotate_with_education(self):
keys = [f'B15003e{i}' for i in range(2, 19)]
high_school_or_lower = self.block_group_d[keys].sum(axis=1)
total = self.block_group_d['B15003e1']
self.block_group_d['p_high_school_or_lower'] = high_school_or_lower / total
print(self.block_group_d[['p_high_school_or_lower']].describe())
def load_raw_dataframes(self):
"""
Read in the original demographic + geographic data.
"""
self.block_group_d = None
self.geometry_d = None
demographic_layer_names = ['X25_HOUSING_CHARACTERISTICS', 'X01_AGE_AND_SEX', 'X03_HISPANIC_OR_LATINO_ORIGIN', 'X19_INCOME', 'X15_EDUCATIONAL_ATTAINMENT']
for file in self.gdb_files:
full_path = os.path.join(self.base_directory, file)
layer_list = fiona.listlayers(full_path)
print(file)
print(layer_list)
geographic_layer_name = [a for a in layer_list if a[:15] == 'ACS_2017_5YR_BG']
assert len(geographic_layer_name) == 1
geographic_layer_name = geographic_layer_name[0]
geographic_data = geopandas.read_file(full_path, layer=geographic_layer_name).to_crs(self.crs_to_use)
print(geographic_data.columns)
geographic_data = geographic_data.sort_values(by='GEOID_Data')[['GEOID_Data', 'geometry', 'STATEFP', 'COUNTYFP', 'TRACTCE']]
for demographic_idx, demographic_layer_name in enumerate(demographic_layer_names):
assert demographic_layer_name in layer_list
if demographic_idx == 0:
demographic_data = geopandas.read_file(full_path, layer=demographic_layer_name)
else:
old_len = len(demographic_data)
new_df = geopandas.read_file(full_path, layer=demographic_layer_name)
assert sorted(new_df['GEOID']) == sorted(demographic_data['GEOID'])
demographic_data = demographic_data.merge(new_df, on='GEOID', how='inner')
assert old_len == len(demographic_data)
demographic_data = demographic_data.sort_values(by='GEOID')
shared_geoids = set(demographic_data['GEOID'].values).intersection(set(geographic_data['GEOID_Data'].values))
print("Length of demographic data: %i; geographic data %i; %i GEOIDs in both" % (len(demographic_data), len(geographic_data), len(shared_geoids)))
demographic_data = demographic_data.loc[demographic_data['GEOID'].map(lambda x:x in shared_geoids)]
geographic_data = geographic_data.loc[geographic_data['GEOID_Data'].map(lambda x:x in shared_geoids)]
demographic_data.index = range(len(demographic_data))
geographic_data.index = range(len(geographic_data))
assert (geographic_data['GEOID_Data'] == demographic_data['GEOID']).all()
assert len(geographic_data) == len(set(geographic_data['GEOID_Data']))
if self.block_group_d is None:
self.block_group_d = demographic_data
else:
self.block_group_d = pd.concat([self.block_group_d, demographic_data])
if self.geometry_d is None:
self.geometry_d = geographic_data
else:
self.geometry_d = pd.concat([self.geometry_d, geographic_data])
assert pd.isnull(self.geometry_d['STATEFP']).sum() == 0
good_idxs = self.geometry_d['STATEFP'].map(lambda x:x in FIPS_CODES_FOR_50_STATES_PLUS_DC).values
print("Warning: the following State FIPS codes are being filtered out")
print(self.geometry_d.loc[~good_idxs, 'STATEFP'].value_counts())
print("%i/%i Census Block Groups in total removed" % ((~good_idxs).sum(), len(good_idxs)))
self.geometry_d = self.geometry_d.loc[good_idxs]
self.block_group_d = self.block_group_d.loc[good_idxs]
self.geometry_d.index = self.geometry_d['GEOID_Data'].values
self.block_group_d.index = self.block_group_d['GEOID'].values
def annotate_with_income(self):
"""
We want a single income number for each block group. This method computes that.
"""
print("Computing household income")
codebook_string = """
B19001e2 HOUSEHOLD INCOME IN THE PAST 12 MONTHS (IN 2017 INFLATION-ADJUSTED DOLLARS): Less than $10,000: Households -- (Estimate)
B19001e3 HOUSEHOLD INCOME IN THE PAST 12 MONTHS (IN 2017 INFLATION-ADJUSTED DOLLARS): $10,000 to $14,999: Households -- (Estimate)
B19001e4 HOUSEHOLD INCOME IN THE PAST 12 MONTHS (IN 2017 INFLATION-ADJUSTED DOLLARS): $15,000 to $19,999: Households -- (Estimate)
B19001e5 HOUSEHOLD INCOME IN THE PAST 12 MONTHS (IN 2017 INFLATION-ADJUSTED DOLLARS): $20,000 to $24,999: Households -- (Estimate)
B19001e6 HOUSEHOLD INCOME IN THE PAST 12 MONTHS (IN 2017 INFLATION-ADJUSTED DOLLARS): $25,000 to $29,999: Households -- (Estimate)
B19001e7 HOUSEHOLD INCOME IN THE PAST 12 MONTHS (IN 2017 INFLATION-ADJUSTED DOLLARS): $30,000 to $34,999: Households -- (Estimate)
B19001e8 HOUSEHOLD INCOME IN THE PAST 12 MONTHS (IN 2017 INFLATION-ADJUSTED DOLLARS): $35,000 to $39,999: Households -- (Estimate)
B19001e9 HOUSEHOLD INCOME IN THE PAST 12 MONTHS (IN 2017 INFLATION-ADJUSTED DOLLARS): $40,000 to $44,999: Households -- (Estimate)
B19001e10 HOUSEHOLD INCOME IN THE PAST 12 MONTHS (IN 2017 INFLATION-ADJUSTED DOLLARS): $45,000 to $49,999: Households -- (Estimate)
B19001e11 HOUSEHOLD INCOME IN THE PAST 12 MONTHS (IN 2017 INFLATION-ADJUSTED DOLLARS): $50,000 to $59,999: Households -- (Estimate)
B19001e12 HOUSEHOLD INCOME IN THE PAST 12 MONTHS (IN 2017 INFLATION-ADJUSTED DOLLARS): $60,000 to $74,999: Households -- (Estimate)
B19001e13 HOUSEHOLD INCOME IN THE PAST 12 MONTHS (IN 2017 INFLATION-ADJUSTED DOLLARS): $75,000 to $99,999: Households -- (Estimate)
B19001e14 HOUSEHOLD INCOME IN THE PAST 12 MONTHS (IN 2017 INFLATION-ADJUSTED DOLLARS): $100,000 to $124,999: Households -- (Estimate)
B19001e15 HOUSEHOLD INCOME IN THE PAST 12 MONTHS (IN 2017 INFLATION-ADJUSTED DOLLARS): $125,000 to $149,999: Households -- (Estimate)
B19001e16 HOUSEHOLD INCOME IN THE PAST 12 MONTHS (IN 2017 INFLATION-ADJUSTED DOLLARS): $150,000 to $199,999: Households -- (Estimate)
B19001e17 HOUSEHOLD INCOME IN THE PAST 12 MONTHS (IN 2017 INFLATION-ADJUSTED DOLLARS): $200,000 or more: Households -- (Estimate)
"""
self.income_bin_edges = [0] + list(range(10000, 50000, 5000)) + [50000, 60000, 75000, 100000, 125000, 150000, 200000]
income_column_names_to_vals = {}
column_codes = codebook_string.split('\n')
for f in column_codes:
if len(f.strip()) == 0:
continue
col_name = f.split('HOUSEHOLD INCOME')[0].strip()
if col_name == 'B19001e2':
val = 10000
elif col_name == 'B19001e17':
val = 200000
else:
lower_bound = float(f.split('$')[1].split()[0].replace(',', ''))
upper_bound = float(f.split('$')[2].split(':')[0].replace(',', ''))
val = (lower_bound + upper_bound) / 2
income_column_names_to_vals[col_name] = val
print("The value for column %s is %2.1f" % (col_name, val))
self.block_group_d['total_household_income'] = 0.
self.block_group_d['total_households'] = 0.
for col in income_column_names_to_vals:
self.block_group_d['total_household_income'] += self.block_group_d[col] * income_column_names_to_vals[col]
self.block_group_d['total_households'] += self.block_group_d[col]
self.block_group_d['mean_household_income'] = 1.*self.block_group_d['total_household_income'] / self.block_group_d['total_households']
self.block_group_d['median_household_income'] = self.block_group_d['B19013e1'] # MEDIAN HOUSEHOLD INCOME IN THE PAST 12 MONTHS (IN 2017 INFLATION-ADJUSTED DOLLARS): Median household income in the past 12 months (in 2017 inflation-adjusted dollars): Households -- (Estimate)
assert (self.block_group_d['total_households'] == self.block_group_d['B19001e1']).all() # sanity check: our count should agree with theirs.
assert (pd.isnull(self.block_group_d['mean_household_income']) == (self.block_group_d['B19001e1'] == 0)).all()
print("Warning: missing income data for %2.1f%% of census blocks with 0 households" % (pd.isnull(self.block_group_d['mean_household_income']).mean() * 100))
self.income_column_names_to_vals = income_column_names_to_vals
assert len(self.income_bin_edges) == len(self.income_column_names_to_vals)
print(self.block_group_d[['mean_household_income', 'total_households']].describe())
def annotate_with_counties_to_msa_mapping(self):
"""
Annotate with metropolitan area info for consistency with Experienced Segregation paper.
"""
print("Loading county to MSA mapping")
self.counties_to_msa_df = pd.read_csv(os.path.join(self.base_directory, self.county_to_msa_mapping_file), skiprows=2, dtype={'FIPS State Code':str, 'FIPS County Code':str})
print("%i rows read" % len(self.counties_to_msa_df))
self.counties_to_msa_df = self.counties_to_msa_df[['CBSA Title',
'Metropolitan/Micropolitan Statistical Area',
'State Name',
'FIPS State Code',
'FIPS County Code']]
self.counties_to_msa_df.columns = ['CBSA Title',
'Metropolitan/Micropolitan Statistical Area',
'State Name',
'STATEFP',
'COUNTYFP']
self.counties_to_msa_df = self.counties_to_msa_df.dropna(how='all') # remove a couple blank rows.
assert self.counties_to_msa_df['Metropolitan/Micropolitan Statistical Area'].map(lambda x:x in ['Metropolitan Statistical Area', 'Micropolitan Statistical Area']).all()
print("Number of unique Metropolitan statistical areas: %i" %
len(set(self.counties_to_msa_df.loc[self.counties_to_msa_df['Metropolitan/Micropolitan Statistical Area'] == 'Metropolitan Statistical Area', 'CBSA Title'])))
print("Number of unique Micropolitan statistical areas: %i" %
len(set(self.counties_to_msa_df.loc[self.counties_to_msa_df['Metropolitan/Micropolitan Statistical Area'] == 'Micropolitan Statistical Area', 'CBSA Title'])))
old_len = len(self.geometry_d)
assert len(self.counties_to_msa_df.drop_duplicates(['STATEFP', 'COUNTYFP'])) == len(self.counties_to_msa_df)
self.geometry_d = self.geometry_d.merge(self.counties_to_msa_df,
on=['STATEFP', 'COUNTYFP'],
how='left')
self.geometry_d.index = self.geometry_d['GEOID_Data'].values
assert len(self.geometry_d) == old_len
assert (self.geometry_d.index == self.block_group_d.index).all()
def annotate_with_rent_as_percentage_of_block_group_income(self):
print("Computing monthly rent -> annual income multiplier")
"""
B25070e1 GROSS RENT AS A PERCENTAGE OF HOUSEHOLD INCOME IN THE PAST 12 MONTHS: Total: Renter-occupied housing units -- (Estimate)
B25070e2 GROSS RENT AS A PERCENTAGE OF HOUSEHOLD INCOME IN THE PAST 12 MONTHS: Less than 10.0 percent: Renter-occupied housing units -- (Estimate)
B25070e3 GROSS RENT AS A PERCENTAGE OF HOUSEHOLD INCOME IN THE PAST 12 MONTHS: 10.0 to 14.9 percent: Renter-occupied housing units -- (Estimate)
B25070e4 GROSS RENT AS A PERCENTAGE OF HOUSEHOLD INCOME IN THE PAST 12 MONTHS: 15.0 to 19.9 percent: Renter-occupied housing units -- (Estimate)
B25070e5 GROSS RENT AS A PERCENTAGE OF HOUSEHOLD INCOME IN THE PAST 12 MONTHS: 20.0 to 24.9 percent: Renter-occupied housing units -- (Estimate)
B25070e6 GROSS RENT AS A PERCENTAGE OF HOUSEHOLD INCOME IN THE PAST 12 MONTHS: 25.0 to 29.9 percent: Renter-occupied housing units -- (Estimate)
B25070e7 GROSS RENT AS A PERCENTAGE OF HOUSEHOLD INCOME IN THE PAST 12 MONTHS: 30.0 to 34.9 percent: Renter-occupied housing units -- (Estimate)
B25070e8 GROSS RENT AS A PERCENTAGE OF HOUSEHOLD INCOME IN THE PAST 12 MONTHS: 35.0 to 39.9 percent: Renter-occupied housing units -- (Estimate)
B25070e9 GROSS RENT AS A PERCENTAGE OF HOUSEHOLD INCOME IN THE PAST 12 MONTHS: 40.0 to 49.9 percent: Renter-occupied housing units -- (Estimate)
B25070e10 GROSS RENT AS A PERCENTAGE OF HOUSEHOLD INCOME IN THE PAST 12 MONTHS: 50.0 percent or more: Renter-occupied housing units -- (Estimate)
B25070e11 GROSS RENT AS A PERCENTAGE OF HOUSEHOLD INCOME IN THE PAST 12 MONTHS: Not computed: Renter-occupied housing units -- (Estimate)
"""
cols_to_vals = {'B25070e2':0.1,
'B25070e3':0.125,
'B25070e4':0.175,
'B25070e5':0.225,
'B25070e6':0.275,
'B25070e7':0.325,
'B25070e8':0.375,
'B25070e9':0.45,
'B25070e10':0.50}
not_computed = self.block_group_d['B25070e11'] / self.block_group_d['B25070e1']
print('Median fraction of people lacking data: %2.3f' % np.median(not_computed.values[self.block_group_d['B25070e1'] > 0]))
total_count = self.block_group_d['B25070e1'].values - self.block_group_d['B25070e11'].values
multiplier = 0
fracs = 0
for k in cols_to_vals:
multiplier = (multiplier +
12 * # number of months
(1 / cols_to_vals[k]) * # how much monthly income monthly rent implies
(self.block_group_d[k].values/total_count) # fraction of households
)
fracs = fracs + self.block_group_d[k].values/total_count
assert np.isclose(fracs[total_count > 0], 1).all()
self.block_group_d['monthly_rent_to_annual_income_multiplier'] = multiplier
assert ((total_count == 0) == np.isnan(multiplier)).all()
print("Median n: %2.3f; mean n %2.3f" % (
np.median(total_count),
np.mean(total_count)))
self.block_group_d['median_monthly_rent_to_annual_income_multiplier'] = 12. / (self.block_group_d['B25071e1'].values / 100.) # This returns the median.
print(self.block_group_d[['monthly_rent_to_annual_income_multiplier', 'median_monthly_rent_to_annual_income_multiplier']].describe())
def get_demographic_stats_of_points(self, latitudes, longitudes, desired_cols):
"""
Given a list or array of latitudes and longitudes, matches to Census Block Group.
Returns a dictionary which includes the state and county FIPS code, along with any columns in desired_cols.
This method assumes the latitudes and longitudes are in https://epsg.io/4326, which is what I think is used for Android/iOS -> SafeGraph coordinates.
"""
assert not dtype_pandas_series(latitudes)
assert not dtype_pandas_series(longitudes)
assert len(latitudes) == len(longitudes)
t0 = time.time()
start_idx = 0
end_idx = start_idx + int(1e6)
merged = []
while start_idx < len(longitudes):
print("Doing spatial join on points with indices from %i-%i" % (start_idx, min(end_idx, len(longitudes))))
points = geopandas.GeoDataFrame(pd.DataFrame({'placeholder':np.array(range(start_idx, min(end_idx, len(longitudes))))}), # this column doesn't matter. We just have to create a geo data frame.
geometry=geopandas.points_from_xy(longitudes[start_idx:end_idx], latitudes[start_idx:end_idx]),
crs=self.crs_to_use)
merged.append(sjoin(points, self.geometry_d[['geometry']], how='left', op='within'))
assert len(merged[-1]) == len(points)
start_idx += int(1e6)
end_idx += int(1e6)
merged = pd.concat(merged)
merged.index = range(len(merged))
assert list(merged.index) == list(merged['placeholder'])
could_not_match = pd.isnull(merged['index_right']).values
print("Cannot match to a CBG for a fraction %2.3f of points" % could_not_match.mean())
results = {}
for k in desired_cols + ['state_fips_code', 'county_fips_code', 'Metropolitan/Micropolitan Statistical Area', 'CBSA Title', 'GEOID_Data', 'TRACTCE']:
results[k] = [None] * len(latitudes)
results = pd.DataFrame(results)
matched_geoids = merged['index_right'].values[~could_not_match]
for c in desired_cols:
results.loc[~could_not_match, c] = self.block_group_d.loc[matched_geoids, c].values
if c in ['p_white', 'p_black', 'mean_household_income', 'median_household_income', 'new_census_monthly_rent_to_annual_income_multiplier', 'new_census_median_monthly_rent_to_annual_income_multiplier']:
results[c] = results[c].astype('float')
results.loc[~could_not_match, 'state_fips_code'] = self.geometry_d.loc[matched_geoids, 'STATEFP'].values
results.loc[~could_not_match, 'county_fips_code'] = self.geometry_d.loc[matched_geoids, 'COUNTYFP'].values
results.loc[~could_not_match, 'Metropolitan/Micropolitan Statistical Area'] = self.geometry_d.loc[matched_geoids,'Metropolitan/Micropolitan Statistical Area'].values
results.loc[~could_not_match, 'CBSA Title'] = self.geometry_d.loc[matched_geoids, 'CBSA Title'].values
results.loc[~could_not_match, 'GEOID_Data'] = self.geometry_d.loc[matched_geoids, 'GEOID_Data'].values
results.loc[~could_not_match, 'TRACTCE'] = self.geometry_d.loc[matched_geoids, 'TRACTCE'].values
print("Total query time is %2.3f" % (time.time() - t0))
return results
def home_locations_for_id_prefix_path(id_prefix):
"""
Get the path for home locations for a single ID prefix.
"""
assert id_prefix in VALID_ID_PREFIXES
return os.path.join(HOME_LOCATIONS_DIR, 'home_locations_id_prefix_%s.csv.gz' % id_prefix)
def create_final_zestimate_files(new_cbg_data=None):
d = []
for id_prefix in VALID_ID_PREFIXES:
pf = pickle.load(open(get_middle_of_night_locations_outfile(id_prefix), 'rb'))
for safegraph_id, row in pf.items():
d.append({'safegraph_id': safegraph_id, **row})
d = pd.DataFrame(d)
zillow_df = pd.read_csv(ZILLOW_QUERY_RESULTS_FILE)
d = d.merge(zillow_df, how='inner', on=['inferred_home_location_lat', 'inferred_home_location_lon'])
ses_col_to_use = 'rent_zestimate' # insist everyone has non null values for this.
if new_cbg_data is None:
new_cbg_data = CensusBlockGroups()
zestimates = load_filtered_zestimate_data(d=d,
zestimate_truncation_threshold=1e7,
rent_zestimate_truncation_threshold=2e4,
zillow_distance_threshold_in_meters=100,
corelogic_distance_threshold_in_meters=100,
max_count_by_location_for_single_family_residence=10,
ses_col_to_use=ses_col_to_use,
new_cbg_data=new_cbg_data)
zestimates = zestimates.rename(columns={'inferred_home_location_lat':'inferred_home_location_lat_DO_NOT_USE',
'inferred_home_location_lon':'inferred_home_location_lon_DO_NOT_USE'})
zestimates['id_prefix'] = zestimates['safegraph_id'].str.slice(stop=2)
for id_prefix, df in zestimates.groupby('id_prefix'):
outfile_name = home_locations_for_id_prefix_path(id_prefix)
os.makedirs(os.path.dirname(outfile_name), exist_ok=True)
df.drop(columns='id_prefix').to_csv(outfile_name, compression='gzip')
def load_filtered_zestimate_data(d, zestimate_truncation_threshold, rent_zestimate_truncation_threshold, zillow_distance_threshold_in_meters, corelogic_distance_threshold_in_meters, max_count_by_location_for_single_family_residence, ses_col_to_use, new_cbg_data):
"""
Given paths zestimates_filepaths for the Zestimates data, load into a single dataframe after applying various filters and sanity checks.
Also annotate with Census data.
Arguments:
zestimate_truncation_threshold: If a Zestimate is greater than this, truncate to this number.
zillow_distance_threshold_in_meters: remove zestimates further than this many meters from the original SafeGraph lat,lon.
corelogic_distance_threshold_in_meters: remove Zestimates where the CoreLogic match is further than this from the original SafeGraph lat,lon.
max_count_by_location_for_single_family_residence: remove single family addresses with more than this many lat,lons matched to them. If None, don't filter out addresses.
ses_col_to_use: should be rent_zestimate or zestimate.
new_cbg_data: a CensusBlockGroup data structure, used for annotating with Census data.
These are not the only filters we apply; they are just the filters which require parameters.
"""
assert d['safegraph_id'].duplicated().sum() == 0
print("Total number loaded: %i" % len(d))
assert ses_col_to_use in ['rent_zestimate', 'zestimate']
print("Linking to new Census data")
link_to_new_census_data = new_cbg_data.get_demographic_stats_of_points(
latitudes=d['zillow_lat'].values,
longitudes=d['zillow_lon'].values,
desired_cols=['p_black', 'p_white', 'p_asian', 'p_hispanic', 'p_high_school_or_lower', 'mean_household_income', 'median_household_income', 'monthly_rent_to_annual_income_multiplier', 'median_monthly_rent_to_annual_income_multiplier'])
for k in link_to_new_census_data:
d['new_census_%s' % k] = link_to_new_census_data[k].values
for c in d.columns:
col_null = pd.isnull(d[c])
print('%-60s is null %2.5f of the time' % (c, col_null.mean()))
duplicate_lat_lons = d[['inferred_home_location_lat', 'inferred_home_location_lon']].duplicated(keep=False)
print("fraction %2.5f of rows have duplicate lat,lons; removing" % duplicate_lat_lons.mean())
d = d.loc[~duplicate_lat_lons]
zestimate_null = pd.isnull(d[ses_col_to_use])
print("%ss are null proportion %2.5f of time; removing" % (ses_col_to_use, zestimate_null.mean()))
d = d.loc[~zestimate_null]
assert pd.isnull(d['zillow_distance']).mean() == 0
assert (d[ses_col_to_use] > 0).all()
zestimate_out_of_range = d['zestimate'] > zestimate_truncation_threshold
d['zestimate_prior_to_truncation_DO_NOT_USE'] = d['zestimate']
print("Zestimates are out of range proportion %2.5f of the time; truncating" % zestimate_out_of_range.mean())
d.loc[zestimate_out_of_range, 'zestimate'] = zestimate_truncation_threshold
rent_zestimate_out_of_range = d['rent_zestimate'] > rent_zestimate_truncation_threshold
d['rent_zestimate_prior_to_truncation_DO_NOT_USE'] = d['rent_zestimate']
print("Rent zestimates are out of range proportion %2.5f of the time; truncating" % rent_zestimate_out_of_range.mean())
d.loc[rent_zestimate_out_of_range, 'rent_zestimate'] = rent_zestimate_truncation_threshold
geo_fields_we_need = ['new_census_p_black',
'new_census_p_white',
'new_census_mean_household_income',
'new_census_median_household_income',
'new_census_state_fips_code',
'new_census_county_fips_code',
'new_census_GEOID_Data',
'new_census_TRACTCE',
'census_tract',
'city',
'addr_zip',
'addr_zip_first_5']
for c in geo_fields_we_need:
is_null = pd.isnull(d[c])
print("Removing a small number of rows where %s is null: %i rows (proportion %2.5f)" % (c, is_null.sum(), is_null.mean()))
d = d.loc[~is_null]
zillow_match_too_far_away = d['zillow_distance'] > zillow_distance_threshold_in_meters
print("Fraction of zillow matches further than %2.3f meters: %2.5f; filtering out" % (zillow_distance_threshold_in_meters, zillow_match_too_far_away.mean()))
d = d.loc[~zillow_match_too_far_away]
assert pd.isnull(d['zillow_lat']).sum() == 0
assert pd.isnull(d['zillow_lon']).sum() == 0
corelogic_match_too_far_away = d['dist_cl'] > corelogic_distance_threshold_in_meters
print("Fraction of CoreLogic matches further than %2.3f meters: %2.5f; filtering out" % (corelogic_distance_threshold_in_meters, corelogic_match_too_far_away.mean()))
d = d.loc[~corelogic_match_too_far_away]
assert d['state'].map(lambda x:x in JUST_50_STATES_PLUS_DC).all()
print("Analyzing many people mapped to exactly the same address")
counts_by_location = d.groupby(['full_addr', 'addr_zip_first_5', 'state']).size().reset_index()
counts_by_location.columns = ['full_addr', 'addr_zip_first_5', 'state', 'n_mapped_to_this_location']
for cutoff in range(1, 100):
print('Fraction %2.3f of addresses have count greater than %i' %
(counts_by_location.loc[counts_by_location['n_mapped_to_this_location'] > cutoff, 'n_mapped_to_this_location'].sum() / counts_by_location['n_mapped_to_this_location'].sum(), cutoff))
old_len = len(d)
d = pd.merge(d, counts_by_location, on=['full_addr', 'addr_zip_first_5', 'state'], how='left')
assert len(d) == old_len
assert pd.isnull(d['n_mapped_to_this_location']).sum() == 0
if max_count_by_location_for_single_family_residence is not None:
bad_idxs = (d['n_mapped_to_this_location'] > max_count_by_location_for_single_family_residence) & (d['use_code'] == 'SingleFamily')
print("Removing fraction %2.3f which have too many people at the same location for a single family residence" % (bad_idxs.mean()))
d = d.loc[~bad_idxs]
d.index = range(len(d))
print("Final number of rows returned: %i" % len(d))
return d
def load_home_locations_for_prefixes(prefixes, verbose=True, usecols=None, filter_users_with_high_fraction_of_duplicate_pings=True, add_other_msa=True, dask_kwargs=None):
if dask_kwargs is None:
dask_kwargs = {}
print("loading home locations for %i prefixes" % len(prefixes))
filenames = [home_locations_for_id_prefix_path(prefix) for prefix in prefixes]
d = load_csv_possibly_with_dask(filenames, use_dask=True, usecols=usecols, **dask_kwargs)
if verbose:
print("After reading in all home locations for prefixes, %i rows" % len(d))
if filter_users_with_high_fraction_of_duplicate_pings:
frac_duplicate = pd.read_csv(FRACTION_OF_DUPLICATE_PINGS_PER_USER_PATH)
safegraph_ids_to_filter = set(frac_duplicate[frac_duplicate['frac_duplicate'] >
DUPLICATE_PINGS_BLACKLIST_FRACTION_THRESHOLD]['safegraph_id'])
d = d[~d['safegraph_id'].isin(safegraph_ids_to_filter)]
if verbose:
print("After filtering for users with over %f fraction of duplicate pings, %i rows" % (
DUPLICATE_PINGS_BLACKLIST_FRACTION_THRESHOLD, len(d)))
if add_other_msa and 'new_census_CBSA Title' in d.columns:
assert not (d['new_census_CBSA Title'] == 'Other').any()
assert d.loc[d['new_census_CBSA Title'].isna()]['new_census_Metropolitan/Micropolitan Statistical Area'].isna().all()
d = d.fillna({'new_census_CBSA Title': 'Other'})
assert not d['new_census_CBSA Title'].isna().any()
d.index = range(len(d))
return d
def load_all_home_locations(**kwargs):
return load_home_locations_for_prefixes(VALID_ID_PREFIXES, **kwargs)
def compute_users_whose_paths_cross():
"""
Compute all users whose paths cross.
"""
all_users_with_home_locations = set(load_all_home_locations(usecols=['safegraph_id'])['safegraph_id'])
for utc_day, utc_hour in itertools.product(UTC_DAYS_TO_USE_IN_ANALYSIS, VALID_UTC_HOURS):
outfile_name = get_UNFILTERED_path_crossings_outfile(utc_day=utc_day, utc_hour=utc_hour)
os.makedirs(os.path.dirname(outfile_name), exist_ok=True)
outfile = open_file_for_exclusive_writing(outfile_name)
if outfile is None: continue # No need to run job.
with outfile: # The 'with' will close the file when done.
do_compute_users_whose_paths_cross(utc_day, utc_hour, all_users_with_home_locations, outfile, outfile_name)
def do_compute_users_whose_paths_cross(utc_day, utc_hour, all_users_with_home_locations, outfile, outfile_name):
"""
Compute all users whose paths cross in a given UTC day and hour, and dump to an outfile.
"""
t_start = time.time()
separation_in_seconds = 300
separation_in_meters = MAX_PATH_CROSSING_THRESHOLD_TO_USE_IN_INITIAL_FILTERING # we can filter down further if we want because we store distances.
all_files = list_files_in_range('locations',
min_utc_hour=utc_hour,
max_utc_hour=utc_hour,
utc_days=[utc_day])
current_datetime = datetime.datetime.strptime(utc_day + ' ' + utc_hour, '%Y_%m_%d %H')
previous_datetime = current_datetime - datetime.timedelta(hours=1)
previous_utc_day = previous_datetime.strftime('%Y_%m_%d')
previous_utc_hour = previous_datetime.strftime('%H')
min_timestamp = current_datetime.replace(tzinfo=pytz.utc).timestamp() - separation_in_seconds # used for filtering out rows in the preceding dataframe which are not near the boundary.
if previous_utc_day not in UTC_DAYS_TO_USE_IN_ANALYSIS:
all_preceding_files = []
else:
all_preceding_files = list_files_in_range('locations',
min_utc_hour=previous_utc_hour,
max_utc_hour=previous_utc_hour,
utc_days=[previous_utc_day])
assert len(all_preceding_files) == len(all_files)
print("Number of files to read: %i" % len(all_files))
all_dataframes = []
for file_idx, filename in enumerate(all_files):
cols_to_keep = ['safegraph_id', 'latitude', 'longitude', 'utc_timestamp', 'geo_hash', 'local_datetime', 'horizontal_accuracy']
d_for_id_prefix = load_ping_file(file_path=filename, usecols=cols_to_keep)
all_dataframes.append(d_for_id_prefix)
print("Reading file %i/%i; %i rows added" % (file_idx+1, len(all_files), len(d_for_id_prefix)))
if len(all_preceding_files) > 0:
preceding_d = load_ping_file(file_path=all_preceding_files[file_idx], usecols=cols_to_keep)
preceding_d = preceding_d.loc[preceding_d['utc_timestamp'] >= min_timestamp]
preceding_d.index = range(len(preceding_d))
print("%i rows added from preceding dataframe" % len(preceding_d))
all_dataframes.append(preceding_d)
d = pd.concat(all_dataframes)
print("prior to filtering for %i users with home locations, %i rows" % (len(all_users_with_home_locations), len(d)))
d = d.loc[d['safegraph_id'].isin(all_users_with_home_locations)].copy()
print("After filtering for %i users with home locations, %i rows" % (len(all_users_with_home_locations), len(d)))
print("Number of rows: %i" % len(d))
all_path_crossings = kd_tree_pairs_of_users_whose_paths_cross(d,
separation_in_seconds=separation_in_seconds,
separation_in_meters=separation_in_meters,
utc_day=utc_day,
utc_hour=utc_hour)
print("writing outfile to %s" % outfile_name)
temp_outfile_name = outfile_name + '.tmp'
all_path_crossings.to_csv(temp_outfile_name, compression='gzip')
shutil.copyfileobj(open(temp_outfile_name, 'rb'), outfile)
os.unlink(temp_outfile_name)
print("Successfully computed path crossings for UTC day %s and UTC hour %s in %2.3f seconds" % (utc_day, utc_hour, time.time() - t_start))
def kd_tree_pairs_of_users_whose_paths_cross(d, separation_in_seconds, separation_in_meters, utc_day, utc_hour):
"""
Given a dataframe of timestamped locations for users, return a set of pairs of users (ie, pairs of safegraph ids)
who are within separation_in_meters meters of each other within separation_in_seconds.
Use a KD tree to compute all pairs that cross.
Seems 4x faster than previous method creating one kd tree for each geohash.
All this is done over narrow timeslices (because we shouldn't be comparing rows that are like an hour apart).
"""
current_start_time = d['utc_timestamp'].min()
max_time = d['utc_timestamp'].max()
d = d.sort_values(by=['safegraph_id'])
timeslice_width = separation_in_seconds * 2
all_pairs = []
pairs_found = 0
while (current_start_time <= max_time + 60):
start_of_computation_time_for_timeslice = time.time() # keep track of how long all this takes to do.
current_end_time = min(max_time + 60, current_start_time + timeslice_width)
print("\n\n\n*****Computing pairs for timeslice %s - %s" %
(datetime_from_utc_timestamp(current_start_time),
datetime_from_utc_timestamp(current_end_time)))
time_slice_idxs = (d['utc_timestamp'] >= current_start_time) & (d['utc_timestamp'] < current_end_time)
d_for_timeslice = copy.deepcopy(d.loc[time_slice_idxs]) # avoid modifying original dataframe.
d_for_timeslice.index = range(len(d_for_timeslice))
current_start_time += separation_in_seconds # increment time slice.
print('Number of rows: %i' % len(d_for_timeslice))
if len(d_for_timeslice) == 0:
continue
xs, ys, zs = lonlat_to_xyz(lon=d_for_timeslice['longitude'].values,
lat=d_for_timeslice['latitude'].values)
print("Computing KD tree")
t_start = time.time() # monitor how long this takes to do.
spatial_locs = np.array([xs, ys, zs]).transpose()
kd_tree = cKDTree(spatial_locs)
print("Seconds to compute tree: %2.3f" % (time.time() - t_start))
t_start = time.time()
pairs_indices = kd_tree.query_pairs(separation_in_meters, output_type='ndarray')
pairs_ts_diff = np.abs(d_for_timeslice['utc_timestamp'].iloc[pairs_indices[:,0]].values -
d_for_timeslice['utc_timestamp'].iloc[pairs_indices[:,1]].values)
pairs_indices = pairs_indices[pairs_ts_diff <= separation_in_seconds]
pairs_diff_safegraph_id = (d_for_timeslice['safegraph_id'].iloc[pairs_indices[:,0]].values !=
d_for_timeslice['safegraph_id'].iloc[pairs_indices[:,1]].values)
pairs_indices = pairs_indices[pairs_diff_safegraph_id]
pairs_dists = np.linalg.norm(
spatial_locs[pairs_indices[:,0]] - spatial_locs[pairs_indices[:,1]],
axis=1)
pairs_dataframe = {
'dist': pairs_dists,
}
desired_fields = ['safegraph_id', 'local_datetime', 'utc_timestamp', 'latitude', 'longitude', 'geo_hash', 'horizontal_accuracy']
for field in desired_fields:
pairs_dataframe['a_'+field] = d_for_timeslice[field].iloc[pairs_indices[:,0]].values
pairs_dataframe['b_'+field] = d_for_timeslice[field].iloc[pairs_indices[:,1]].values
pairs_dataframe = pd.DataFrame(pairs_dataframe)
pairs_found += len(pairs_dataframe)
all_pairs.append(pairs_dataframe)
print("Seconds to compute neighbors using tree: %2.3f" % (time.time() - t_start))
print("Total time to process timeslice: %2.3f seconds" % (time.time() - start_of_computation_time_for_timeslice))
print("Total number of path crossings identified after analyzing this timeslice (including all previous timeslices): %i" % pairs_found)
all_pairs_whose_paths_cross = pd.concat(all_pairs)
print("Prior to dropping duplicates, %i rows" % len(all_pairs_whose_paths_cross))
all_pairs_whose_paths_cross = all_pairs_whose_paths_cross.drop_duplicates() # because timeslices overlap, have to deduplicate
print("Identified %i path crossings after de-duplicating" % len(all_pairs_whose_paths_cross))
all_pairs_of_users_whose_paths_cross = consolidate_path_crossings(
all_pairs_whose_paths_cross, utc_day, utc_hour)
return all_pairs_of_users_whose_paths_cross
def consolidate_path_crossings(all_pairs_whose_paths_cross, utc_day, utc_hour):
"""
all_pairs_whose_paths_cross may have multiple rows for each user pair.
Here we combine all these rows into one row for every PATH_CROSSING_CONSOLIDATION_INTERVAL seconds.
"""
print("Condensing path crossings dataframe into a dataframe with one row for each pair of users every %d seconds" %
PATH_CROSSING_CONSOLIDATION_INTERVAL)
assert (all_pairs_whose_paths_cross['a_safegraph_id'] < all_pairs_whose_paths_cross['b_safegraph_id']).all()
assert len(all_pairs_whose_paths_cross.drop_duplicates()) == len(all_pairs_whose_paths_cross)
t_start = time.time()
crossing_timestamps = pd.concat([all_pairs_whose_paths_cross['a_utc_timestamp'], all_pairs_whose_paths_cross['b_utc_timestamp']], axis=1).min(axis=1)
assert crossing_timestamps.isna().sum() == 0
all_pairs_whose_paths_cross = all_pairs_whose_paths_cross.assign(
utc_timestamp=crossing_timestamps,
consolidation_key=crossing_timestamps.floordiv(PATH_CROSSING_CONSOLIDATION_INTERVAL),
)
grouped_d = all_pairs_whose_paths_cross.groupby(['a_safegraph_id', 'b_safegraph_id', 'consolidation_key'])
one_row_d = []
total_groups = len(grouped_d)
n = 0
for group_id, small_d in grouped_d:
if n % 10000 == 0:
print('%i/%i consolidated path crossings processed' % (n, total_groups))
n += 1
a_safegraph_id, b_safegraph_id, consolidation_key = group_id
min_utc_timestamp = min(small_d['a_utc_timestamp'].min(), small_d['b_utc_timestamp'].min())
max_utc_timestamp = max(small_d['a_utc_timestamp'].max(), small_d['b_utc_timestamp'].max())
assert small_d['dist'].min() < MAX_PATH_CROSSING_THRESHOLD_TO_USE_IN_INITIAL_FILTERING
ts_diff = (small_d['a_utc_timestamp'] - small_d['b_utc_timestamp']).abs()