-
Notifications
You must be signed in to change notification settings - Fork 6
/
compute_neighborhood_histogram.py
78 lines (57 loc) · 2.05 KB
/
compute_neighborhood_histogram.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
import numpy as np
import matplotlib.pyplot as plt
from osgeo import ogr
import json
# Load GPS data from url or file
#f = urllib2.urlopen("https://feeds.citibikenyc.com/stations/stations.json")
#jsonData = json.load(f)
with open('../data/citibike.json', 'r') as f:
jsonData = json.load(f)
# Collect GPS points as OGR points
points = []
for i in range(len(jsonData['stationBeanList'])):
lon = jsonData['stationBeanList'][i]['longitude']
lat = jsonData['stationBeanList'][i]['latitude']
point = ogr.Geometry(ogr.wkbPoint)
point.AddPoint(lon, lat)
points.append(point)
# Read in the neighborhoods from geojson file
histogram = {}
shp = ogr.Open("../nyc_data/nyc_neighborhoods.json")
layer = shp.GetLayer(0)
for feature in layer:
#if feature.GetField("boroughCode") == "1":
neighborhoodName = feature.GetField("neighborhood")
histogram[neighborhoodName] = 0
geometry = feature.GetGeometryRef()
if geometry is not None and geometry.GetGeometryType() == ogr.wkbPolygon:
count = 0
for point in points:
count += point.Within(geometry)
histogram[neighborhoodName] = count
print("%s, count: %i" % (neighborhoodName, count))
# Write neighborhood histogram to npy file
np.save('neighborhood_histogram.npy', histogram)
# Load: d = np.load('neighborhood_histogram.npy').item()
# Write neighborhood histogram to csv file
#f = open("neighborhood_histogram.txt", 'w')
#for key in histogram:
# f.write("%s;%i\n" % (key, histogram[key]))
#f.close()
# Visualize histogram
keys, values = np.array(histogram.keys()), np.array(histogram.values())
# Mask out all zero values
mask = values != 0
keys, values = keys[mask], values[mask]
# Sort all values
idx = np.argsort(values)
keys, values = keys[idx], values[idx]
pos = np.arange(len(values)) + 0.5
fig, ax = plt.subplots()
fig.set_size_inches(20, 20)
ax.barh(pos, values, color='k')
for i in range(len(keys)):
ax.text(0, pos[i] + 0.2, keys[i], color='white', fontweight='bold')
plt.ylim([pos[0], pos[-1]+1])
plt.axis('off')
plt.savefig('../visualization/neighborhood_histogram.png', bbox_inches='tight', pad_inches=0)