-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
467 lines (397 loc) · 15.5 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
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
# Import required libraries
import pickle
import copy
import pathlib
import dash
import math
import datetime as dt
import pandas as pd
from dash.dependencies import Input, Output, State, ClientsideFunction
import plotly.graph_objs as go
import dash_core_components as dcc
import dash_html_components as html
import dash
import dash_dangerously_set_inner_html
from dateutil.relativedelta import relativedelta
from dash.dependencies import Input, Output, State
import urllib.request, json
# Multi-dropdown options
# get relative data folder
PATH = pathlib.Path(__file__).parent
DATA_PATH = PATH.joinpath("data").resolve()
app = dash.Dash(
__name__, meta_tags=[{"name": "viewport", "content": "width=device-width"}]
)
server = app.server
# Load data
with urllib.request.urlopen("https://us-central1-mh-kwann.cloudfunctions.net/fetch") as url:
opioid_data = json.loads(url.read().decode())
df = pd.json_normalize(opioid_data['reports'])
print(df.columns)
df = df.rename(columns={'location.lat': 'lon', 'location.lng': 'lat'})
df["id"] = df.index
print(df.columns)
#df = pd.json_normalize(data['results'])
#df = pd.read_csv("opioid_data.csv", header=0, low_memory=False)
print(df['timestamp'])
df['timestamp'] = df.apply(lambda x: x['timestamp'][12:17] + x['timestamp'][8:12] + x['timestamp'][5:8] + x['timestamp'][18:-4], axis=1) # fixes timestamp
df['timestamp'] = pd.to_datetime(df['timestamp']) # converts the timestamp to date_time objects
external_stylesheets = ['https://use.fontawesome.com/releases/v5.8.1/css/all.css',
'https://wet-boew.github.io/themes-dist/GCWeb/css/theme.min.css',
'https://wet-boew.github.io/themes-dist/GCWeb/wet-boew/css/noscript.min.css'] # Link to external CSS
external_scripts = [
'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.js',
'https://wet-boew.github.io/themes-dist/GCWeb/wet-boew/js/wet-boew.min.js',
'https://wet-boew.github.io/themes-dist/GCWeb/js/theme.min.js'
]
# Create global chart template
mapbox_access_token = "pk.eyJ1IjoiamFja2x1byIsImEiOiJjajNlcnh3MzEwMHZtMzNueGw3NWw5ZXF5In0.fk8k06T96Ml9CLGgKmk81w"
layout = dict(
autosize=True,
automargin=True,
margin=dict(l=30, r=30, b=20, t=40),
hovermode="closest",
plot_bgcolor="#F9F9F9",
paper_bgcolor="#F9F9F9",
legend=dict(font=dict(size=10), orientation="h"),
title="Satellite Overview",
mapbox=dict(
accesstoken=mapbox_access_token,
style="light",
center=dict(lon=-78.05, lat=42.54),
zoom=4,
),
)
# Builds the layout for the header
def build_header():
return html.Div(
[
html.Div(
[
html.H1(
"Canada Opioid Overdose Dashboard",
style={"margin-top": "20px", "margin-bottom": "0px"},
),
],
className="three column",
id="title",
),
],
id="header",
className="row flex-display",
style={"margin-bottom": "25px"},
)
# Builds the layout and components for the inputs to filter the data, as well as the overdoses/month graph and the overdose map
def build_filtering():
return html.Div([
html.Div(
[
html.H3(
id="select-data"
),
],
style={"margin-top": "10px", "margin-left": "auto", "margin-right": "auto", "text-align": "center"},
className="twelve columns"
),
html.Div(
[
html.Div(
[
html.Div(
[dcc.Graph(id="selector_map")],
className="pretty_container",
),
html.Div(
[
html.P(
id="overdoses-text",
className="control_label",
),
html.H5(
"", style={"margin-top": "10px"}
),
],
id="map-options",
),
],
id="left-column-1",
style={"flex-grow": 1},
className="nine columns",
),
html.Div(
[
html.Div(
[
html.H5("Total overdoses"),
html.H3(id="overdoses_text"),
html.H5("+22% from last month"),
],
# id="info-container",
className="mini_container",
style={"text-align": "center"},
),
html.Div(
[
html.H5("Nalaxone provided"),
html.H3(id="naloxone_text", children="19221"),
html.H5("-10% from target"),
],
className="mini_container",
style={"text-align": "center"},
),
html.Div(
[
html.H5("Fatal cases"),
html.H3(id="fatal_text", children="9041"),
html.H5("+6% from last month"),
],
className="mini_container",
style={"text-align": "center"},
),
],
className="three columns"
),
],
className="row",
),
html.Div(
[
html.Div(
[
html.Div(
[dcc.Graph(id="count_graph")],
id="countGraphContainer",
),
],
id="right-column-1",
style={"flex-grow": 1},
className="eight columns pretty_container",
),
html.Div(
[
html.H2("Filter"),
html.H5("Region"),
html.Label(
dcc.Input(
id="input_text",
type="text",
placeholder="Kitchener-Waterloo",
),
),
html.H5("Date range"),
html.Div([
html.Label(
dcc.DatePickerRange(
id='date_picker_range',
min_date_allowed=dt.datetime(2019, 1, 1),
max_date_allowed=dt.datetime(2020, 12, 31),
start_date=dt.datetime(2019, 1, 1),
end_date=dt.datetime(2020, 12, 31),
start_date_placeholder_text='Select start date',
end_date_placeholder_text='Select end date',
style={"margin-top": "5px"}
),
),
html.Div(id='output-container-date-picker-range')
]),
html.H5(
"", style={"margin-top": "30px", "margin-bottom": "25px"}
),
],
id="cross-filter-options",
style={"flex-grow": 1},
className="four columns pretty_container",
),
],
className="row flex-display",
style={"justify-content": "space-evenly"}
),
])
# Create app layout
app.layout = html.Div(
[
html.Div(
[
html.Div(id="output-clientside"), # empty Div to trigger javascript file for graph resizing
build_header(),
build_filtering(),
],
id="mainContainer",
style={"font-family": "sans-serif", "display": "flex", "flex-direction": "column", "margin": "auto", "width":"75%"},
),
],
)
# Helper functions
def filter_dataframe(df, start_date_dt, end_date_dt):
"""Filter the extracted overdose dataframe on multiple parameters.
Called for every component.
Parameters
----------
df : DataFrame (note: SciPy/NumPy documentation usually refers to this as array_like)
The DataFrame with overdose data to be filtered.
start_date_dt : datetime object
Starting date stored as a datetime object
end_date_dt : datetime object
Ending date stored as a datetime object
Returns
-------
DataFrame
The filtered DataFrame
"""
dff = df
# df[
# (df["timestamp"].dt.date >= dt.date(start_date_dt.year, start_date_dt.month, start_date_dt.day))
# & (df["timestamp"].dt.date <= dt.date(end_date_dt.year, end_date_dt.month, end_date_dt.day))
# ]
# if (lat_min != -90) or (lat_max != 90):
# dff = dff[
# (dff["lat"] >= lat_min)
# & (dff["lat"] <= lat_max)
# ]
# if (lon_min != -90) or (lon_max != 90):
# dff = dff[
# (dff["lon"] >= lon_min)
# & (dff["lon"] <= lon_max)
# ]
return dff
# Selectors -> overdose count
@app.callback(
Output("overdoses_text", "children"),
[
Input("date_picker_range", "start_date"),
Input("date_picker_range", "end_date")
],
)
def update_overdoses_text(start_date, end_date):
"""Update the component that counts the number of overdoses selected.
Parameters
----------
start_date : str
Starting date stored as a str
end_date : str
Ending date stored as a str
Returns
-------
int
The number of overdoses present in the dataframe after filtering
"""
start_time = dt.datetime.now()
start_date = dt.datetime.strptime(start_date.split('T')[0], '%Y-%m-%d') # Convert strings to datetime objects
end_date = dt.datetime.strptime(end_date.split('T')[0], '%Y-%m-%d')
dff = filter_dataframe(df, start_date, end_date)
print('update_overdoses_text:', (dt.datetime.now()-start_time).total_seconds())
return "{:n}".format(dff.shape[0])
# Selectors -> count graph
@app.callback(
Output("count_graph", "figure"),
# [Input("visualize-button", "n_clicks")],
[
Input("date_picker_range", "start_date"),
Input("date_picker_range", "end_date"),
],
)
def make_count_figure(start_date, end_date):
"""Create and update the histogram of selected iongograms over the given time range.
Parameters
----------
start_date : str
Starting date stored as a str
end_date : str
Ending date stored as a str
Returns
-------
dict
A dictionary containing 2 key-value pairs: the selected data as an array of dictionaries and the histogram's
layout as as a Plotly layout graph object.
"""
start_time = dt.datetime.now()
start_date = dt.datetime.strptime(start_date.split('T')[0], '%Y-%m-%d') # Convert strings to datetime objects
end_date = dt.datetime.strptime(end_date.split('T')[0], '%Y-%m-%d')
layout_count = copy.deepcopy(layout)
dff = filter_dataframe(df, start_date, end_date)
g = dff[["id", "timestamp"]]
g.index = g["timestamp"]
g = g.resample("M").count()
data = [
dict(
type="scatter",
mode="markers",
x=g.index,
y=g['id'] / 2,
name="All overdoses",
opacity=0,
hoverinfo="skip",
),
dict(
type="bar",
x=g.index,
y=g['id'],
name="All overdoses",
marker=dict(color="rgb(18, 99, 168)"),
),
]
layout_count["title"] = "Overdoses Per Month"
layout_count["xaxis"] = {"title": "Date", "automargin": True}
layout_count["yaxis"] = {"title": "Number of Overdoses", "automargin": True}
layout_count["dragmode"] = "select"
layout_count["showlegend"] = False
layout_count["autosize"] = True
layout_count["transition"] = {'duration': 500}
figure = dict(data=data, layout=layout_count)
print('make_count_figure:', (dt.datetime.now()-start_time).total_seconds())
return figure
@app.callback(
Output("selector_map", "figure"),
# [Input("visualize-button", "n_clicks")],
[
Input("date_picker_range", "start_date"),
Input("date_picker_range", "end_date"),
],
)
def generate_geo_map(start_date, end_date):
"""Create and update the map of selected overdoses.
Parameters
----------
start_date : str
Starting date stored as a str
end_date : str
Ending date stored as a str
Returns
-------
dict
A dictionary containing 2 key-value pairs: the selected data as an array of Plotly scattermapbox graph objects
and the map's layout as a Plotly layout graph object.
"""
start_time = dt.datetime.now()
start_date = dt.datetime.strptime(start_date.split('T')[0], '%Y-%m-%d') # Convert strings to datetime objects
end_date = dt.datetime.strptime(end_date.split('T')[0], '%Y-%m-%d')
filtered_data = filter_dataframe(df, start_date, end_date)
dff = filtered_data
traces = []
data = [ dict(
type = 'scattermapbox',
lon = dff['lat'],
lat = dff['lon'],
text = dff['timestamp'],
mode = 'markers',
marker = dict(
size = 8,
opacity = 0.8,
color = 'orange'
))]
# relayoutData is None by default, and {'autosize': True} without relayout action
# if main_graph_layout is not None and selector is not None and "locked" in selector:
# if "mapbox.center" in main_graph_layout.keys():
# lon = float(main_graph_layout["mapbox.center"]["lon"])
# lat = float(main_graph_layout["mapbox.center"]["lat"])
# zoom = float(main_graph_layout["mapbox.zoom"])
# layout["mapbox"]["center"]["lon"] = lon
# layout["mapbox"]["center"]["lat"] = lat
# layout["mapbox"]["zoom"] = zoom
print('generate_geo_map:', (dt.datetime.now()-start_time).total_seconds())
figure = dict(data=data, layout=layout)
return figure
# Main
if __name__ == '__main__':
app.run_server(debug=True) # For development/testing
# app.run_server(debug=False, host='0.0.0.0', port=8888) # For the server