-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
295 lines (248 loc) · 10.9 KB
/
app.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
from collections import OrderedDict
from flask import Flask, render_template, request
import pandas as pd
import geopandas as gpd
import folium
import json
app = Flask(__name__)
route_id_to_stops = pd.read_csv('data/route_id_to_stops.csv')
stops_delay_count = pd.read_csv('data/stops_delay_count.csv')
gdf_stops_delay_count = gpd.GeoDataFrame(stops_delay_count, geometry=gpd.points_from_xy(stops_delay_count['GTFS Longitude'], stops_delay_count['GTFS Latitude']), crs='EPSG:4326')
gdf_subway = gpd.read_file('data/my_subway_lines.geojson')
gdf_avg_inc = gpd.read_file('data/average_income_2021.geojson')
total_delays_by_line = pd.read_csv('data/total_delay_time_by_lines.csv')
total_delays_by_stop = pd.read_csv('data/total_delay_time_by_stops.csv')
race = gpd.read_file('data/nyc-race.geojson')
on_time = pd.read_csv("data/avg_terminal_on_time_performance.csv")
def make_map(line, default_map):
rt_id_to_stops = route_id_to_stops.set_index('route_id').T.to_dict('list')
rt_id_to_stops = {k: v[0].split(', ') for k, v in rt_id_to_stops.items()}
if line:
zoom = 12
center = gdf_stops_delay_count[gdf_stops_delay_count['stop_id'].isin(rt_id_to_stops[line])][['GTFS Latitude', 'GTFS Longitude']].mean().tolist()
else:
center = [40.7128, -74.0060]
zoom = 11
base_map = 'CartoDB Voyager'
m = folium.Map(location=center, zoom_start=zoom, control_scale=True, prefer_canvas=True, tiles=base_map)
income_choropleth = folium.Choropleth(
geo_data=gdf_avg_inc,
name='Income by Zip Code',
data=gdf_avg_inc,
columns=['ZipCode', 'B19013001'],
key_on='feature.properties.ZipCode',
fill_color='YlGnBu',
fill_opacity=0.7,
line_opacity=0.2,
legend_name='Average Income',
highlight=True,
smooth_factor=0
)
income_tooltip = folium.GeoJsonTooltip(
fields=['ZipCode', 'B19013001', 'Neighborhood', 'Borough'],
aliases=['Zip Code:', 'Average Income:', 'Neighborhood:', 'Borough:'],
sticky=True,
opacity=0.9,
direction='top',
style="font-size: 12px; max-width: 300px;",
)
income_choropleth.geojson.add_child(income_tooltip)
race_choropleth = folium.Choropleth(
geo_data=race,
name='NYC Race Map',
data=race,
columns=['name', 'Total Population'],
key_on='feature.properties.name',
fill_color='YlOrBr',
fill_opacity=0.7,
line_opacity=0.2,
legend_name='Total Population',
highlight=True,
smooth_factor=1.0
)
fields = ['Total Population', 'White alone', 'Black or African American Alone', 'American Indian and Alaska Native alone', 'Asian alone', 'Native Hawaiian and Other Pacific Islander Alone', 'Some other race alone', 'Two or more races','Hispanic or Latino (Total)']
aliases = [field + ':' for field in fields]
race_tooltip = folium.GeoJsonTooltip(
fields=['name', *fields],
aliases=['Zip Code:', *aliases],
sticky=True,
opacity=0.9,
direction='top',
style="font-size: 12px; width: 100 vw;",
)
if default_map == "income":
m.add_child(income_choropleth)
else:
m.add_child(race_choropleth)
race_choropleth.geojson.add_child(race_tooltip)
if line:
gdf_line = gdf_subway[gdf_subway['name'].str.contains(line)]
else:
gdf_line = gdf_subway
folium.GeoJson(data=gdf_line,
name='Subway Lines',
style_function=lambda feature: {
'color': feature['properties']['RGB Hex'],
'weight': 7,
'opacity': 1,
},
tooltip=folium.GeoJsonTooltip(
fields=['Line/Branch'],
aliases=['Subway Line:'],
sticky=True,
opacity=0.9,
direction='top',
style="font-size: 12px;",
labels=True
)
).add_to(m)
if line:
stops = rt_id_to_stops[line]
gdf_stops = gdf_stops_delay_count[gdf_stops_delay_count['stop_id'].isin(stops)]
else:
gdf_stops = gdf_stops_delay_count
markers = folium.FeatureGroup(name='Stops')
m.add_child(markers)
marker_tooltip = 'Click for more info.'
for _, row in gdf_stops.iterrows():
delay = row['Average Delay per Line']
if delay <= 0:
color = 'blue'
elif delay <= 60:
color = 'green'
else:
color = 'red'
# remove '[' and ']' from the list of branches
branch = row['branch'].replace('[', '').replace(']', '')
pop_up = f"""<p style='font-size: 16px'><b>Stop</b>: {row['Stop Name']}</p>
<p style='font-size: 14px'><b>Borough</b>: {row['Borough']}</p>
<p style='font-size: 14px'><b>Train Lines</b>: {branch}</p>
<p style='font-size: 14px'><b>Average Delay per Line</b>: {row['Average Delay per Line (mins)']}</p>
<p style='font-size: 14px'><b>Delays</b>: {row['Delay Count']}</p>
"""
marker = folium.Marker(
location=[row['GTFS Latitude'], row['GTFS Longitude']],
popup=folium.Popup(pop_up, max_width=300),
icon=folium.Icon(color=color, icon='info-sign'),
tooltip=marker_tooltip
).add_to(m)
marker.add_to(markers)
# explain the colors of the subway lines
legend_html = '''
<div style="position: fixed;
bottom: 10px; left: 50px; width: 200px; height: 230px; z-index:9999; font-size:14px; color: white;
"> Subway Lines <br>
1 2 3 <i class="fa fa-circle" style="color:#EE352E"></i><br>
4 5 6 <i class="fa fa-circle" style="color:#00933C"></i><br>
7 <i class="fa fa-circle" style="color:#B933AD"></i><br>
A/C/E <i class="fa fa-circle" style="color:#0039A6"></i><br>
B/D/F/M <i class="fa fa-circle" style="color:#FF6319"></i><br>
G <i class="fa fa-circle" style="color:#6CBE45"></i><br>
J/Z <i class="fa fa-circle" style="color:#996633"></i><br>
L <i class="fa fa-circle" style="color:#A7A9AC"></i><br>
N/Q/R <i class="fa fa-circle" style="color:#FCCC0A"></i><br>
S <i class="fa fa-circle" style="color:#808183"></i><br>
</div>
'''
mp = m.get_name()
mrk = markers.get_name()
js_callback = f'''
function show_hide_markers() {{
var map = {mp};
var markers = {mrk};
function show_markers() {{
var zoomlevel = map.getZoom();
if (zoomlevel < 13) {{
markers.removeFrom(map);
}} else {{
markers.addTo(map);
}}
}}
map.on('zoomend', show_markers);
show_markers();
}}
window.onload = show_hide_markers;
'''
m.get_root().html.add_child(folium.Element(legend_html))
m.get_root().script.add_child(folium.Element(js_callback))
m.get_root().header.add_child(folium.Element('<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">'))
m.get_root().header.add_child(folium.Element('<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>'))
folium.LayerControl().add_to(m)
return m
@app.route('/')
def index():
return render_template('index.html')
@app.route('/map', methods=['GET', 'POST'])
def map():
# Define your project title
project_title = "Is The Mta Racist?"
# Pass the project title to the template
if request.method == 'POST':
selected_line = request.form.get('train_line')
default = request.form.get('map_type')
print(default)
else:
selected_line = 'default'
default = 'race'
context = {
'title': project_title,
'default_map': default,
'train_lines': get_train_lines(),
'selected_train_line': selected_line
}
line = get_train_lines().get(selected_line)
m = make_map(line, default)
context['map'] = m.get_root().render()
return render_template("map.html", **context)
@app.route('/delay_list')
def get_delay_list():
delay_lines = total_delays_by_line.set_index('Line')['Total Delay Time'].to_dict()
# convert the values to seconds timedelta
delay_lines = {k: pd.to_timedelta(v) for k, v in delay_lines.items()}
# sort the dictionary by the values
sorted_delay_lines = {k: v for k, v in sorted(delay_lines.items(), key=lambda item: item[1].total_seconds())}
# convert the values back to string
sorted_delay_lines = {k: str(v) for k, v in sorted_delay_lines.items()}
return json.dumps(sorted_delay_lines)
@app.route('/performance_list')
def get_performance_list():
performance_lines = on_time.set_index('Line')['Average Terminal On-Time Performance'].to_dict()
return json.dumps(performance_lines)
@app.route('/fun-facts')
def fun_facts():
return render_template('fun_facts.html')
@app.route('/about-us')
def about_us():
return render_template('about-us.html')
def get_train_lines():
return {
"1 train (Broadway-7 Avenue local)" : "1",
"2 train (7 Avenue express)" : "2",
"3 train (7 Avenue express)" : "3",
"4 train (Lexington Avenue express)" : "4",
"5 train (Lexington Avenue express)" : "5",
"6 train (Lexington Avenue local/Pelham express)" : "6",
"7 train (Flushing local and Flushing express)" : "7",
"A train (8 Avenue express)" : "A",
"B train (Central Park West local/6 Avenue express)" : "B",
"C train (8 Avenue local)" : "C",
"D train (6 Avenue express)" : "D",
"E train (8 Avenue local)" : "E",
"F train (6 Avenue local)" : "F",
"G train (Brooklyn-Queens crosstown local)" : "G",
"J train (Nassau Street express)" : "J",
"L train (14 Street-Canarsie local)" : "L",
"M train (Queens Boulevard local/6 Avenue local/Myrtle Avenue local)" : "M",
"N train (Broadway express)" : "N",
"Q train (2 Avenue/Broadway express)" : "Q",
"R train (Queens Boulevard/Broadway/4 Avenue local)" : "R",
"S 42 St Shuttle, Franklin Av Shuttle, and Rockaway Park Shuttle trains (shuttle service)" : "S",
"W train (Broadway local)" : "W",
"Z train (Nassau Street express) " : "Z",
"Select Train Line": None
}
@app.route('/about')
def about():
return render_template('about-us.html')
if __name__ == '__main__':
app.run(debug=True)