-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
1680 lines (1405 loc) · 49.1 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
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 numpy as np
import pandas as pd
import streamlit as st
import datetime
import lmfit
from pathlib import Path
from PIL import Image
from sklearn.metrics import mean_absolute_error, mean_squared_error
from statsmodels.tsa.holtwinters import ExponentialSmoothing
from statsmodels.tsa.statespace.sarimax import SARIMAX
from statsmodels.tsa.stattools import acf, pacf
from src.utils import load_data, get_region_pop
from src.plots import (
ac_plot,
anomalies_plot,
autocorr_indicators_plot,
cross_corr_cases_plot,
custom_plot,
daily_main_indic_plot,
data_for_plot,
general_plot,
plot_fbp_comp,
plot_ts_decomp,
plot_tstat_models,
trend_corr_plot,
discsid_param_plot,
)
from src.sird import DeterministicSird, sird, Model
from src.ts import decompose_ts, adf_test_result, kpss_test_result
from fbprophet import Prophet
from fbprophet.plot import plot_plotly
import tensorflow as tf
from src.tfts import (
WindowGenerator,
Baseline,
compile_and_fit,
plot_comparison_results_plotly,
)
import os
os.chdir(os.path.dirname(os.path.realpath(__file__)))
DATA_PATH = "data"
@st.cache(show_spinner=False)
def load_df():
return load_data(DATA_PATH)
@st.cache(show_spinner=False)
def load_icu_df():
return pd.read_csv(Path(DATA_PATH, "icu.csv"))
@st.cache(show_spinner=False)
def compute_sird(
prov,
pop_prov_df,
prov_list_df=None,
r0_start=3.5,
r0_end=0.9,
k=0.9,
x0=20,
alpha=0.1,
gamma=1 / 7,
):
"""Compute the continuous SIRD model version."""
return sird(
province=prov,
pop_prov_df=pop_prov_df,
prov_list_df=prov_list_df,
gamma=gamma,
alpha=alpha,
R_0_start=r0_start,
k=k,
x0=x0,
R_0_end=r0_end,
)
@st.cache(show_spinner=False)
def data_sird_plot(df, column, comp_array, province_selectbox, is_regional):
"""Utility function that returns data useful for plots."""
return data_for_plot(
compart="Infected",
df=df,
column=column,
comp_array=comp_array,
province=province_selectbox,
is_regional=is_regional,
)
@st.cache(show_spinner=False)
def compute_daily_changes(df):
"""Gets daily variation of the regional indicators"""
df["ricoverati_con_sintomi_giorno"] = df["ricoverati_con_sintomi"] - df[
"ricoverati_con_sintomi"
].shift(1)
df["terapia_intensiva_giorno"] = df["terapia_intensiva"] - df[
"terapia_intensiva"
].shift(1)
df["deceduti_giorno"] = df["deceduti"] - df["deceduti"].shift(1)
df["tamponi_giorno"] = df["tamponi"] - df["tamponi"].shift(1)
df["casi_testati_giorno"] = df["casi_testati"] - df["casi_testati"].shift(1)
df["dimessi_guariti_giorno"] = df["dimessi_guariti"] - df["dimessi_guariti"].shift(
1
)
df["isolamento_domiciliare_giorno"] = df["isolamento_domiciliare"] - df[
"isolamento_domiciliare"
].shift(1)
return df
@st.cache(show_spinner=False)
def compute_autocorr_df(df, days, is_regional=True):
"""
Compute autocorrelations and cross-correlations
of the main indicators
"""
if not is_regional:
pos_col = "New_cases"
deaths_col = "Deaths"
else:
pos_col = "nuovi_positivi"
deaths_col = "deceduti_giorno"
data = pd.DataFrame(
{
"giorni": range(days),
"autocor_nuovi_positivi": [
df[pos_col].corr(df[pos_col].shift(i)) for i in range(days)
],
"autocor_nuovi_decessi": [
df[deaths_col].corr(df[deaths_col].shift(i)) for i in range(days)
],
"crosscor_decessi_nuovi_positivi": [
df[deaths_col]
.rolling(7, center=True)
.mean()
.corr(df[pos_col].rolling(7, center=True).mean().shift(i))
for i in range(days)
],
}
)
if is_regional:
data["autocor_tamponi_eseguiti"] = [
df["tamponi_giorno"].corr(df["tamponi_giorno"].shift(i))
for i in range(days)
]
data["autocor_casi_testati"] = [
df["casi_testati_giorno"].corr(df["casi_testati_giorno"].shift(i))
for i in range(days)
]
data["autocor_nuovi_ricoverati"] = [
df["ricoverati_con_sintomi_giorno"].corr(
df["ricoverati_con_sintomi_giorno"].shift(i)
)
for i in range(days)
]
data["autocor_nuove_TI"] = [
df["terapia_intensiva_giorno"].corr(df["terapia_intensiva_giorno"].shift(i))
for i in range(days)
]
return data
@st.cache(show_spinner=False)
def decompose_series(df, column):
return decompose_ts(df, column)
@st.cache
def get_train_df(df, date, column):
return df.query(date.strftime("%Y%m%d") + " >= " + column)
@st.cache
def get_test_df(df, date, column):
return df.query(date.strftime("%Y%m%d") + " < " + column)
@st.cache(show_spinner=False)
def compute_acf(data, lags):
return acf(data, nlags=lags, alpha=0.05)
@st.cache(show_spinner=False)
def compute_pacf(data, lags):
return pacf(data, nlags=lags, alpha=0.05)
@st.cache(show_spinner=False)
def run_fbp(train, data_column, column, days_to_pred):
train_df = train.reset_index()
train_df = train_df.loc[:, [data_column, column]]
train_df.columns = ["ds", "y"]
m = Prophet(interval_width=0.95)
m.add_country_holidays(country_name="IT")
m.fit(train_df)
future_df = m.make_future_dataframe(periods=days_to_pred)
forecast = m.predict(future_df)
return m, forecast
@st.cache(show_spinner=False)
def run_sarimax(train, test, order):
model = SARIMAX(train, order=order)
sarimax_res = model.fit()
yhat = sarimax_res.get_forecast(steps=len(test))
sarimax_sf = yhat.summary_frame()
return sarimax_res.fittedvalues, sarimax_res.summary(), sarimax_sf
def load_homepage():
"""Homepage"""
st.write(
"Welcome to the interactive dashboard of my thesis "
"for the MSc in Data Science and Economics at "
"Università degli Studi di Milano."
)
st.header("The Application")
st.write(
"This application is a Streamlit dashboard that can be used "
"to explore the work of my master degree thesis."
)
st.write(
"There are currently four pages available in the application "
"and they are described below. To navigate between pages, "
"use the dropdown menu in the sidebar. To reveal the sidebar, "
"click on the arrow > at top-left corner."
)
st.subheader("🗺️ Data exploration")
st.markdown("* This gives a general overview of the data with interactive plots.")
st.subheader("📈 Time Series")
st.markdown(
"* This page allows you to see predictions made using time "
"series models and the Prophet library."
)
st.subheader("👓 SIRD")
st.markdown(
"* This page allows you to see predictions made using "
"stochastic and deterministic SIRD models with time-dependent "
"parameters."
)
st.subheader("🗝️ TensorFlow")
st.markdown(
"* This page serves to show predictions made using "
"neural networks (such as LSTM) implemented through "
"TensorFlow."
)
st.write("")
st.write("")
st.write(
"If you are on a wide screen, you can make the app fit the entire "
"width of the page. In order to do this, click on the top-right "
'hamburger menu icon ☰, then click on "Settings", '
'check "Show app in wide mode" and finally click on "Save".'
)
st.write("")
st.write(
"To switch between Light and Dark mode, please click on"
'the top-right hamburger menu icon ☰, then click on "Settings"'
'and finally, under "Theme", you can toogle between Dark or Light mode.'
)
def load_ts_page(covidpro_df, dpc_regioni_df):
"""Time series analysis and forecast page"""
# Sidebar setup
st.sidebar.header("Options")
area_radio = st.sidebar.radio(
"Regional or provincial predictions:", ["Regional", "Provincial"], index=1
)
group_column = "denominazione_regione"
data_df = dpc_regioni_df
data_column = "data"
column = "nuovi_positivi"
if area_radio == "Regional":
area_selectbox = st.sidebar.selectbox(
"Region:",
dpc_regioni_df.denominazione_regione.unique(),
int((dpc_regioni_df.denominazione_regione == "Piemonte").argmax()),
key="area_selectbox_reg",
)
else:
area_selectbox = st.sidebar.selectbox(
"Province:",
covidpro_df.Province.unique(),
int((covidpro_df.Province == "Firenze").argmax()),
key="area_selectbox_prov",
)
group_column = "Province"
data_df = covidpro_df
data_column = "Date"
column = "New_cases"
last_avail_date = data_df.iloc[-1][data_column]
# Date pickers
start_date_ts = st.sidebar.date_input(
"Start date",
datetime.date(2020, 2, 24),
datetime.date(2020, 2, 24),
last_avail_date,
)
end_date_ts = st.sidebar.date_input(
"End date",
datetime.date(2020, 7, 1),
datetime.date(2020, 2, 24),
last_avail_date,
)
days_to_pred = st.sidebar.slider("Days to predict", 1, 30, 14)
# Filter data
df_filtered = data_df.query(
end_date_ts.strftime("%Y%m%d")
+ " >= "
+ data_column
+ " >= "
+ start_date_ts.strftime("%Y%m%d")
)
df_final = df_filtered.loc[(df_filtered[group_column] == area_selectbox), :]
df_date_idx = df_final.set_index(data_column)
# Decomposition
st.header("Series decomposition")
with st.spinner("Decomposing series"):
decomp_res = decompose_series(df_date_idx, column)
st.plotly_chart(
plot_ts_decomp(
x_dates=df_date_idx.index,
ts_true=df_date_idx[column],
decomp_res=decomp_res,
output_figure=True,
),
use_container_width=True,
)
with st.beta_expander("Stationarity tests"):
adf_res = adf_test_result(df_date_idx[column])
kpss_res = kpss_test_result(df_date_idx[column])
st.info(
f"""
ADF statistic: {adf_res[0]}
p-value: {adf_res[1]}
"""
)
st.write("")
st.info(
f"""
KPSS statistic: {kpss_res[0]}
p-value: {kpss_res[1]}
"""
)
st.write("")
st.write("")
max_lags = int(df_date_idx.shape[0] / 2) - 1
st.header("Auto-correlation")
with st.spinner("Plotting ACF and PACF"):
lags_start = max_lags if max_lags < 60 else 60
acf_val, ci_acf = compute_acf(df_date_idx[column], lags_start)
pacf_val, ci_pacf = compute_pacf(df_date_idx[column], lags_start)
st.plotly_chart(
ac_plot(acf_val, ci_acf, output_figure=True, title="Auto-correlation"),
use_container_width=True,
)
st.plotly_chart(
ac_plot(
pacf_val, ci_pacf, output_figure=True, title="Partial auto-correlation"
),
use_container_width=True,
)
p_value = adf_test_result(df_date_idx[column])[0]
st.write("Dickey-Fuller: p={0:.5f}".format(p_value))
st.write("")
st.write("")
st.header("Anomalies")
st.plotly_chart(
anomalies_plot(df_date_idx, column, 7, output_figure=True),
use_container_width=True,
)
# Forecasting
st.header("Forecasting")
test_date = pd.to_datetime(end_date_ts) - pd.Timedelta(days=days_to_pred)
train = get_train_df(df_date_idx, test_date, data_column)
test = get_test_df(df_date_idx, test_date, data_column)
# Exponential Smoothing
st.subheader("Exponential Smoothing")
with st.spinner("Training model"):
es_model = ExponentialSmoothing(
train[column].values, seasonal_periods=7, trend="add", seasonal="add"
)
es_res = es_model.fit()
es_yhat = es_res.predict(start=0, end=len(test) - 1)
st.plotly_chart(
plot_tstat_models(
df=df_date_idx,
train=train,
test=test,
fitted_vals=es_res.fittedvalues,
yhat=es_yhat,
column=column,
output_figure=True,
),
use_container_width=True,
)
mae = mean_absolute_error(test[column], es_yhat)
mse = mean_squared_error(test[column], es_yhat)
rmse = mean_squared_error(test[column], es_yhat, squared=False)
with st.beta_expander("Show training results"):
st.text("AIC: " + str(es_res.aic))
st.text("AICC: " + str(es_res.aicc))
st.text("BIC: " + str(es_res.bic))
st.text("k: " + str(es_res.k))
st.text("")
st.text("MAE: " + str(np.round(mae, 3)))
st.text("MSE: " + str(np.round(mse, 3)))
st.text("RMSE: " + str(np.round(rmse, 3)))
st.text("SSE: " + str(es_res.sse))
st.text("")
st.text("")
st.text(es_res.mle_retvals)
st.text(es_res.summary())
st.write("")
st.write("")
st.write("")
# ARIMA
st.subheader("ARIMA")
col1_arima, col2_arima, col3_arima = st.beta_columns(3)
lags_arima = col1_arima.slider("Lags (p)", 0, 15, 1)
dod_arima = col2_arima.slider("Degree of differencing (d)", 0, 15, 1)
window_arima = col3_arima.slider("Window (q)", 0, 30, 1)
with st.spinner("Training model"):
sarimax_fv, sarimax_summary, sarimax_sf = run_sarimax(
train[column], test, (lags_arima, dod_arima, window_arima)
)
st.plotly_chart(
plot_tstat_models(
df=df_date_idx,
train=train,
test=test,
fitted_vals=sarimax_fv,
yhat=sarimax_sf,
column=column,
output_figure=True,
),
use_container_width=True,
)
mae = mean_absolute_error(test[column], sarimax_sf["mean"])
mse = mean_squared_error(test[column], sarimax_sf["mean"])
rmse = mean_squared_error(test[column], sarimax_sf["mean"], squared=False)
with st.beta_expander("Show training results"):
st.text("MAE: " + str(np.round(mae, 3)))
st.text("MSE: " + str(np.round(mse, 3)))
st.text("RMSE: " + str(np.round(rmse, 3)))
st.text("")
st.text("")
st.text(sarimax_summary)
st.write("")
st.write("")
st.write("")
# Prophet
st.subheader("Facebook Prophet")
with st.spinner("Training model"):
m, forecast = run_fbp(train, data_column, column, days_to_pred)
fig1 = plot_plotly(m, forecast)
fig1.update_layout(
title="Forecast",
yaxis_title="Number of individuals",
template="plotly_white",
title_x=0.5,
)
st.plotly_chart(fig1, use_container_width=True)
st.plotly_chart(
plot_fbp_comp(df=forecast, title="Forecast components", output_figure=True),
use_container_width=True,
)
test_df = test.reset_index()
yhat_df = forecast.iloc[-days_to_pred:]
mae = mean_absolute_error(test_df[column], yhat_df.yhat)
mse = mean_squared_error(test_df[column], yhat_df.yhat)
rmse = mean_squared_error(test_df[column], yhat_df.yhat, squared=False)
with st.beta_expander("Show training results"):
st.text("MAE: " + str(np.round(mae, 3)))
st.text("MSE: " + str(np.round(mse, 3)))
st.text("RMSE: " + str(np.round(rmse, 3)))
st.dataframe(forecast)
def load_tf_page(covidpro_df, dpc_regioni_df):
"""Neural Networks with TensorFlow page"""
# Sidebar setup
st.sidebar.header("Options")
area_radio = st.sidebar.radio(
"Regional or provincial predictions:", ["Regional", "Provincial"], index=1
)
group_column = "denominazione_regione"
data_df = dpc_regioni_df
data_column = "data"
column = "nuovi_positivi"
if area_radio == "Regional":
area_selectbox = st.sidebar.selectbox(
"Region:",
dpc_regioni_df.denominazione_regione.unique(),
int((dpc_regioni_df.denominazione_regione == "Piemonte").argmax()),
key="area_selectbox_reg",
)
else:
area_selectbox = st.sidebar.selectbox(
"Province:",
covidpro_df.Province.unique(),
int((covidpro_df.Province == "Firenze").argmax()),
key="area_selectbox_prov",
)
group_column = "Province"
data_df = covidpro_df
data_column = "Date"
column = "New_cases"
last_avail_date = data_df.iloc[-1][data_column]
# Date pickers
start_date_ts = st.sidebar.date_input(
"Start date",
datetime.date(2020, 2, 24),
datetime.date(2020, 2, 24),
last_avail_date,
)
end_date_ts = st.sidebar.date_input(
"End date",
datetime.date(2020, 7, 1),
datetime.date(2020, 2, 24),
last_avail_date,
)
# Filter data
df_filtered = data_df.query(
end_date_ts.strftime("%Y%m%d")
+ " >= "
+ data_column
+ " >= "
+ start_date_ts.strftime("%Y%m%d")
)
df_final = df_filtered.loc[(df_filtered[group_column] == area_selectbox), :]
df_date_idx = df_final.set_index(data_column)
df_date_idx = df_date_idx.loc[:, [column]]
column_indices = {name: i for i, name in enumerate(df_date_idx.columns)}
days_to_pred = st.sidebar.slider("Input length/Days to predict", 1, 30, 14)
shift = st.sidebar.slider("Shift", 1, days_to_pred, days_to_pred)
n = len(df_date_idx)
train_df = df_date_idx[0 : int(n * 0.4)]
val_df = df_date_idx[int(n * 0.4) : int(n * 0.7)]
test_df = df_date_idx[int(n * 0.7) :]
train_mean = train_df.mean()
train_std = train_df.std()
train_df = (train_df - train_mean) / train_std
val_df = (val_df - train_mean) / train_std
test_df = (test_df - train_mean) / train_std
single_step_window = WindowGenerator(
input_width=1,
label_width=1,
shift=1,
train_df=train_df,
val_df=val_df,
test_df=test_df,
label_columns=[column],
)
wide_window = WindowGenerator(
input_width=days_to_pred,
label_width=days_to_pred,
shift=shift,
train_df=train_df,
val_df=val_df,
test_df=test_df,
label_columns=[column],
)
val_performance = {}
performance = {}
# Baseline
st.header("Baseline")
with st.spinner("Training model"):
baseline = Baseline(label_index=column_indices[column])
baseline.compile(
loss=tf.losses.MeanSquaredError(),
metrics=[tf.metrics.MeanAbsoluteError(), tf.metrics.MeanSquaredError()],
)
st.plotly_chart(
wide_window.plot_plotly(baseline, plot_col=column, output_figure=True),
use_container_width=True,
)
with st.beta_expander("Show training results"):
val_performance["Baseline"] = baseline.evaluate(wide_window.val, verbose=0)
performance["Baseline"] = baseline.evaluate(wide_window.test, verbose=0)
st.text("Val. MAE: " + str(val_performance["Baseline"][1]))
st.text("Test MAE: " + str(performance["Baseline"][1]))
st.text("")
st.text("Val. MSE: " + str(val_performance["Baseline"][2]))
st.text("Test MSE: " + str(performance["Baseline"][2]))
st.text("")
st.text("")
st.text("")
# Dense
st.header("Dense")
with st.spinner("Training model"):
dense = tf.keras.Sequential(
[
tf.keras.layers.Dense(units=64, activation="relu"),
tf.keras.layers.Dense(units=64, activation="relu"),
tf.keras.layers.Dense(units=1),
]
)
_ = compile_and_fit(dense, single_step_window, verbose=0)
st.plotly_chart(
wide_window.plot_plotly(dense, plot_col=column, output_figure=True),
use_container_width=True,
)
with st.beta_expander("Show training results"):
val_performance["Dense"] = dense.evaluate(single_step_window.val, verbose=0)
performance["Dense"] = dense.evaluate(single_step_window.test, verbose=0)
st.text("Val. MAE: " + str(val_performance["Dense"][1]))
st.text("Test MAE: " + str(performance["Dense"][1]))
st.text("")
st.text("Val. MSE: " + str(val_performance["Dense"][2]))
st.text("Test MSE: " + str(performance["Dense"][2]))
st.text("")
st.text("")
Path("results").mkdir(parents=True, exist_ok=True)
try:
_ = tf.keras.utils.plot_model(
dense, to_file="results/dense.png", show_shapes=True
)
image = Image.open("results/dense.png")
st.image(image, width=400)
except Exception:
st.warning("Cannot show model architecture plot")
st.text("")
st.text("")
st.text("")
# LSTM
st.header("LSTM")
with st.spinner("Training model"):
lstm_model = tf.keras.models.Sequential(
[
# Shape [batch, time, features] => [batch, time, lstm_units]
tf.keras.layers.LSTM(32, return_sequences=True),
# Shape => [batch, time, features]
tf.keras.layers.Dense(units=1),
]
)
_ = compile_and_fit(lstm_model, wide_window, verbose=0)
st.plotly_chart(
wide_window.plot_plotly(dense, plot_col=column, output_figure=True),
use_container_width=True,
)
with st.beta_expander("Show training results"):
val_performance["LSTM"] = lstm_model.evaluate(wide_window.val, verbose=0)
performance["LSTM"] = lstm_model.evaluate(wide_window.test, verbose=0)
st.text("Val. MAE: " + str(val_performance["LSTM"][1]))
st.text("Test MAE: " + str(performance["LSTM"][1]))
st.text("")
st.text("Val. MSE: " + str(val_performance["LSTM"][2]))
st.text("Test MSE: " + str(performance["LSTM"][2]))
st.text("")
st.text("")
Path("results").mkdir(parents=True, exist_ok=True)
try:
_ = tf.keras.utils.plot_model(
lstm_model, to_file="results/lstm.png", show_shapes=True
)
image = Image.open("results/lstm.png")
st.image(image, width=400)
except Exception:
st.warning("Cannot show model architecture plot")
st.text("")
st.text("")
st.text("")
# Comparison plot
st.header("Comparison")
st.plotly_chart(
plot_comparison_results_plotly(
lstm_model.metrics_names, val_performance, performance, output_figure=True
),
use_container_width=True,
)
with st.beta_expander("Show raw data"):
models = ["Baseline", "Dense", "LSTM"]
arrays = [
[item for item in models for i in range(2)],
["Validation", "Test"] * len(models),
]
index = pd.MultiIndex.from_arrays(arrays, names=("Model", "Split"))
all_maes_val = [v[1] for k, v in val_performance.items()]
all_maes_test = [v[1] for k, v in performance.items()]
all_mse_val = [v[2] for k, v in val_performance.items()]
all_mse_test = [v[2] for k, v in performance.items()]
df = pd.DataFrame(
{"MAE": all_maes_val + all_maes_test, "MSE": all_mse_val + all_mse_test},
index=index,
)
st.dataframe(df)
def load_sird_page(covidpro_df, dpc_regioni_df, pop_prov_df, prov_list_df):
"""Page of the SIRD model"""
# Sidebar setup
st.sidebar.header("Options")
area_radio = st.sidebar.radio(
"Regional or provincial predictions:", ["Regional", "Provincial"], index=1
)
is_regional = True
pcm_data = None
group_column = "denominazione_regione"
data_df = dpc_regioni_df
data_column = "data"
prov_df = prov_list_df
column = "totale_positivi"
traces_visibility = [True, "legendonly", True]
if area_radio == "Regional":
area_selectbox = st.sidebar.selectbox(
"Region:",
dpc_regioni_df.denominazione_regione.unique(),
int((dpc_regioni_df.denominazione_regione == "Piemonte").argmax()),
key="area_selectbox_reg",
)
N = get_region_pop(area_selectbox, pop_prov_df, prov_df)
else:
area_selectbox = st.sidebar.selectbox(
"Province:",
covidpro_df.Province.unique(),
int((covidpro_df.Province == "Firenze").argmax()),
key="area_selectbox_prov",
)
is_regional = False
pcm_data = dpc_regioni_df
group_column = "Province"
data_df = covidpro_df
data_column = "Date"
prov_df = None
column = "New_cases"
traces_visibility = ["legendonly"] + [True] * 2
N = pop_prov_df.loc[
(pop_prov_df.Territorio == area_selectbox) & (pop_prov_df.Eta == "Total")
]["Value"].values[0]
# ---------------
# Continuous SIRD
# ---------------
st.header("Continuous SIRD")
st.write(
"""
Here you can either manually choose the values for
the parameters of this SIRD model, or you can
automatically estimate them. If you choose automatic
estimation, be aware that:
1. The sliders below will not reflect the new optimized value
2. You can optimize the values only for one compartment at time
"""
)
# Manual parameters
st.subheader("Parameters - manual selection")
col1, col2, col3 = st.beta_columns(3)
r0_start = col1.slider("R0 start", 1.0, 6.0, 2.0)
r0_end = col1.slider("R0 end", 0.01, 3.5, 0.3)
k_value = col2.slider("R0 decrease rate", 0.01, 1.0, 0.2)
x0_value = col2.slider("Lockdown day", 0, 100, 40)
alpha_value = col3.slider("Death rate", 0.001, 1.0, 0.01)
gamma_value = col3.slider("Recovery rate", 0.001, 1.0, 1 / 7)
# Auto estimation
st.subheader("Parameters - auto estimation")
col1, col2 = st.beta_columns(2)
compart = col1.selectbox(
"Compartment:",
["Infected", "Deaths"],
0,
key="comp_param",
)
if is_regional:
if compart == "Infected":
column = "totale_positivi"
else:
column = "deceduti"
else:
if compart == "Infected":
column = "New_cases"
else:
column = "Tot_deaths"
traces_visibility = [True, "legendonly", True]
col2.text("")
col2.text("")
param_est_button = col2.button("Optimize")
# Compute SIRD
with st.spinner("Training continuous SIRD"):
sirsol = compute_sird(
area_selectbox,
pop_prov_df,
prov_df,
r0_start,
r0_end,
k_value,
x0_value,
alpha_value,
gamma_value,
)
if param_est_button:
mapping = {
"New_cases": 2,
"Curr_pos_cases": 2,
"Tot_deaths": 4,
"Deaths": 4,
"Infected": 2,
"nuovi_positivi": 2,
"totale_positivi": 2,
"deceduti_giorni": 4,
"deceduti": 4,
}
def fitter(x, R_0_start, k, x0, R_0_end, alpha, gamma):
ret = Model(days, N, R_0_start, k, x0, R_0_end, alpha, gamma)
return ret[mapping[column]][x]
def get_model(
compart,
data_df,
params_init_min_max=None,
outbreak_shift=0,
window=7,
):
data = data_df.query("20200603 > " + data_column)
data = data.loc[(data[group_column] == area_selectbox), compart]
if compart in [
"New_cases",
"Deaths",
"nuovi_positivi",
"deceduti_giorno",
]:
data = data.rolling(window).mean().fillna(0)
# {parameter: (initial guess, min value, max value)}
if params_init_min_max is None:
params_init_min_max = {
"R_0_start": (3.5, 1.0, 6),
"k": (0.3, 0.01, 5.0),
"x0": (20, 0, 100),
"R_0_end": (0.9, 0.01, 3.5),
"alpha": (0.1, 0.00000001, 1),
"gamma": (1 / 7, 0.00000001, 1),
}
days = outbreak_shift + len(data)
if outbreak_shift >= 0:
y_data = np.concatenate((np.zeros(outbreak_shift), data))
# [0, 1, ..., days]
x_data = np.linspace(0, days - 1, days, dtype=int)
mod = lmfit.Model(fitter)
for kwarg, (init, mini, maxi) in params_init_min_max.items():