-
Notifications
You must be signed in to change notification settings - Fork 30
/
DELPHI_utils_V4_static.py
2018 lines (1932 loc) · 106 KB
/
DELPHI_utils_V4_static.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
# Authors: Hamza Tazi Bouardi ([email protected]), Michael L. Li ([email protected]), Omar Skali Lami ([email protected])
import os
import pandas as pd
import numpy as np
import scipy.stats
from datetime import datetime, timedelta
from typing import Union
import json
from logging import Logger
from DELPHI_params_V4 import (
TIME_DICT,
default_policy,
default_policy_enaction_time,
)
from DELPHI_utils_V4_dynamic import make_increasing
class DELPHIDataSaver:
def __init__(
self,
path_to_folder_danger_map: str,
path_to_website_predicted: str,
df_global_parameters: Union[pd.DataFrame, None],
df_global_predictions_since_today: pd.DataFrame,
df_global_predictions_since_100_cases: pd.DataFrame,
logger: Logger = None
):
self.PATH_TO_FOLDER_DANGER_MAP = path_to_folder_danger_map
self.PATH_TO_WEBSITE_PREDICTED = path_to_website_predicted
self.df_global_parameters = df_global_parameters
self.df_global_predictions_since_today = df_global_predictions_since_today
self.df_global_predictions_since_100_cases = (
df_global_predictions_since_100_cases
)
self.logger = logger
@staticmethod
def save_dataframe(df, path, logger):
attempt = 0
success = False
filename = path
while attempt <= 5 and not success:
success = True
attempt+=1
try:
df.to_csv(filename, index=False)
except OSError:
success = False
filename = path.replace(".csv", f"_try_{attempt}.csv")
if not success:
logger.error(
f"Unable to save file {path}, skipping after {attempt} attempts"
)
return attempt
return 0
def save_all_datasets(
self, optimizer: str, save_since_100_cases: bool = False, website: bool = False
):
"""
Saves the parameters and predictions datasets (since 100 cases and since the day of running)
based on the different flags and the inputs to the DELPHIDataSaver initializer
:param optimizer: needs to be in (tnc, trust-constr, annealing) and will save files differently accordingly; the
default name corresponds to tnc where we don't specify the optimizer because that's the default one
:param save_since_100_cases: boolean, whether or not we also want to save the predictions since 100 cases
for all the areas (instead of since the day we actually ran the optimization)
:param website: boolean, whether or not we want to save the files in the website repository as well
:return:
"""
today_date_str = "".join(str(datetime.now().date()).split("-"))
if optimizer == "tnc":
subname_file = "Global_V4"
elif optimizer == "annealing":
subname_file = "Global_V4_annealing"
elif optimizer == "trust-constr":
subname_file = "Global_V4_trust"
else:
raise ValueError("Optimizer not supported in this implementation")
# Save parameters
DELPHIDataSaver.save_dataframe(
self.df_global_parameters,
self.PATH_TO_FOLDER_DANGER_MAP + f"/predicted/Parameters_{subname_file}_{today_date_str}.csv",
self.logger
)
# Save predictions since today
DELPHIDataSaver.save_dataframe(
self.df_global_predictions_since_today,
self.PATH_TO_FOLDER_DANGER_MAP + f"/predicted/{subname_file}_{today_date_str}.csv",
self.logger
)
if website:
DELPHIDataSaver.save_dataframe(
self.df_global_parameters,
self.PATH_TO_WEBSITE_PREDICTED + f"data/predicted/Parameters_{subname_file}_{today_date_str}.csv",
self.logger
)
DELPHIDataSaver.save_dataframe(
self.df_global_predictions_since_today,
self.PATH_TO_WEBSITE_PREDICTED
+ f"data/predicted/{subname_file}_{today_date_str}.csv",
self.logger
)
DELPHIDataSaver.save_dataframe(
self.df_global_predictions_since_today,
self.PATH_TO_WEBSITE_PREDICTED + f"data/predicted/Global.csv",
self.logger
)
if save_since_100_cases:
# Save predictions since 100 cases
DELPHIDataSaver.save_dataframe(
self.df_global_predictions_since_100_cases,
self.PATH_TO_FOLDER_DANGER_MAP + f"/predicted/{subname_file}_since100_{today_date_str}.csv",
self.logger
)
if website:
DELPHIDataSaver.save_dataframe(
self.df_global_predictions_since_100_cases,
self.PATH_TO_WEBSITE_PREDICTED + f"data/predicted/{subname_file}_since100_{today_date_str}.csv",
self.logger
)
DELPHIDataSaver.save_dataframe(
self.df_global_predictions_since_100_cases,
self.PATH_TO_WEBSITE_PREDICTED + f"data/predicted/{subname_file}_since100.csv",
self.logger
)
def save_policy_predictions_to_json(self, website: bool = False, local_delphi: bool = False):
"""
Saves the policy predictions as a JSON file based on the different flags
:param website: boolean, whether or not we want to save the JSON file in the website repository as well
:param local_delphi: boolean, whether or not we want to save the JSON file in the DELPHI repository as well
:return:
"""
today_date_str = "".join(str(datetime.now().date()).split("-"))
dict_predictions_policies_world_since_100_cases = DELPHIDataSaver.create_nested_dict_from_final_dataframe(
self.df_global_predictions_since_100_cases
)
with open(
self.PATH_TO_FOLDER_DANGER_MAP
+ f"/predicted/world_Python_{today_date_str}_Scenarios_since_100_cases.json",
"w",
) as handle:
json.dump(dict_predictions_policies_world_since_100_cases, handle)
with open(
self.PATH_TO_FOLDER_DANGER_MAP
+ f"/predicted/world_Python_Scenarios_since_100_cases.json",
"w",
) as handle:
json.dump(dict_predictions_policies_world_since_100_cases, handle)
if local_delphi:
with open(
f"./world_Python_{today_date_str}_Scenarios_since_100_cases.json", "w"
) as handle:
json.dump(dict_predictions_policies_world_since_100_cases, handle)
if website:
with open(
self.PATH_TO_WEBSITE_PREDICTED
+ f"assets/policies/World_Scenarios.json",
"w",
) as handle:
json.dump(dict_predictions_policies_world_since_100_cases, handle)
@staticmethod
def create_nested_dict_from_final_dataframe(df_predictions: pd.DataFrame) -> dict:
"""
Generates the nested dictionary with all the policy predictions which will then be saved as a JSON file
to be used on the website
:param df_predictions: dataframe with all policy predictions
:return: dictionary with nested keys and policy predictions to be saved as a JSON file
"""
dict_all_results = {
continent: {} for continent in df_predictions.Continent.unique()
}
for continent in dict_all_results.keys():
countries_in_continent = list(
df_predictions[df_predictions.Continent == continent].Country.unique()
)
dict_all_results[continent] = {
country: {} for country in countries_in_continent
}
keys_country_province = list(
set(
[
(continent, country, province)
for continent, country, province in zip(
df_predictions.Continent.tolist(),
df_predictions.Country.tolist(),
df_predictions.Province.tolist(),
)
]
)
)
for continent, country, province in keys_country_province:
df_predictions_province = df_predictions[
(df_predictions.Country == country)
& (df_predictions.Province == province)
].reset_index(drop=True)
# The first part contains only ground truth value, so it doesn't matter which
# policy/enaction time we choose to report these values
dict_all_results[continent][country][province] = {
"Day": sorted(list(df_predictions_province.Day.unique())),
"Total Detected True": df_predictions_province[
(df_predictions_province.Policy == default_policy)
& (df_predictions_province.Time == default_policy_enaction_time)
]
.sort_values("Day")["Total Detected True"]
.tolist(),
"Total Detected Deaths True": df_predictions_province[
(df_predictions_province.Policy == default_policy)
& (df_predictions_province.Time == default_policy_enaction_time)
]
.sort_values("Day")["Total Detected Deaths True"]
.tolist(),
}
dict_all_results[continent][country][province].update(
{
policy: {
policy_enaction_time: {
"Total Detected": df_predictions_province[
(df_predictions_province.Policy == policy)
& (df_predictions_province.Time == policy_enaction_time)
]
.sort_values("Day")["Total Detected"]
.tolist(),
"Total Detected Deaths": df_predictions_province[
(df_predictions_province.Policy == policy)
& (df_predictions_province.Time == policy_enaction_time)
]
.sort_values("Day")["Total Detected Deaths"]
.tolist(),
}
for policy_enaction_time in df_predictions_province.Time.unique()
}
for policy in df_predictions_province.Policy.unique()
}
)
return dict_all_results
class DELPHIDataCreator:
def __init__(
self,
x_sol_final: np.array,
date_day_since100: datetime,
best_params: np.array,
continent: str,
country: str,
province: str,
testing_data_included: bool = False,
):
if testing_data_included:
assert (
len(best_params) == 15
), f"Expected 9 best parameters, got {len(best_params)}"
else:
assert (
len(best_params) == 12
), f"Expected 7 best parameters, got {len(best_params)}"
self.x_sol_final = x_sol_final
self.date_day_since100 = date_day_since100
self.best_params = best_params
self.continent = continent
self.country = country
self.province = province
self.testing_data_included = testing_data_included
def create_dataset_parameters(self, mape: float) -> pd.DataFrame:
"""
Creates the parameters dataset with the results from the optimization and the pre-computed MAPE
:param mape: MAPE on the last 15 days (or less if less historical days available) for that particular area
:return: dataframe with parameters and MAPE
"""
if self.testing_data_included:
print(
f"Parameters dataset created without the testing data parameters"
+ " beta_0, beta_1: code will have to be modified"
)
df_parameters = pd.DataFrame(
{
"Continent": [self.continent],
"Country": [self.country],
"Province": [self.province],
"Data Start Date": [self.date_day_since100],
"MAPE": [mape],
"Infection Rate": [self.best_params[0]],
"Median Day of Action": [self.best_params[1]],
"Rate of Action": [self.best_params[2]],
"Rate of Death": [self.best_params[3]],
"Mortality Rate": [self.best_params[4]],
"Rate of Mortality Rate Decay": [self.best_params[5]],
"Internal Parameter 1": [self.best_params[6]],
"Internal Parameter 2": [self.best_params[7]],
"Jump Magnitude": [self.best_params[8]],
"Jump Time": [self.best_params[9]],
"Jump Decay": [self.best_params[10]],
"Internal Parameter 3": [self.best_params[11]],
}
)
return df_parameters
def create_datasets_predictions(self) -> (pd.DataFrame, pd.DataFrame):
"""
Creates two dataframes with the predictions of the DELPHI model, the first one since the day of the prediction,
the second since the day the area had 100 cases
:return: tuple of dataframes with predictions from DELPHI model
"""
n_days_btw_today_since_100 = (datetime.now() - self.date_day_since100).days
n_days_since_today = self.x_sol_final.shape[1] - n_days_btw_today_since_100
all_dates_since_today = [
str((datetime.now() + timedelta(days=i)).date())
for i in range(n_days_since_today)
]
# Predictions
total_detected = self.x_sol_final[15, :] # DT
total_detected = [int(round(x, 0)) for x in total_detected]
active_cases = (
self.x_sol_final[4, :]
+ self.x_sol_final[5, :]
+ self.x_sol_final[7, :]
+ self.x_sol_final[8, :]
) # DHR + DQR + DHD + DQD
active_cases = [int(round(x, 0)) for x in active_cases]
active_hospitalized = (
self.x_sol_final[4, :] + self.x_sol_final[7, :]
) # DHR + DHD
active_hospitalized = [int(round(x, 0)) for x in active_hospitalized]
cumulative_hospitalized = self.x_sol_final[11, :] # TH
cumulative_hospitalized = [int(round(x, 0)) for x in cumulative_hospitalized]
total_detected_deaths = self.x_sol_final[14, :] # DD
total_detected_deaths = [int(round(x, 0)) for x in total_detected_deaths]
active_ventilated = (
self.x_sol_final[12, :] + self.x_sol_final[13, :]
) # DVR + DVD
active_ventilated = [int(round(x, 0)) for x in active_ventilated]
# Generation of the dataframe since today
df_predictions_since_today_cont_country_prov = pd.DataFrame(
{
"Continent": [self.continent for _ in range(n_days_since_today)],
"Country": [self.country for _ in range(n_days_since_today)],
"Province": [self.province for _ in range(n_days_since_today)],
"Day": all_dates_since_today,
"Total Detected": total_detected[n_days_btw_today_since_100:],
"Active": active_cases[n_days_btw_today_since_100:],
"Active Hospitalized": active_hospitalized[n_days_btw_today_since_100:],
"Cumulative Hospitalized": cumulative_hospitalized[
n_days_btw_today_since_100:
],
"Total Detected Deaths": total_detected_deaths[
n_days_btw_today_since_100:
],
"Active Ventilated": active_ventilated[n_days_btw_today_since_100:],
}
)
# Generation of the dataframe from the day since 100th case
all_dates_since_100 = [
str((self.date_day_since100 + timedelta(days=i)).date())
for i in range(self.x_sol_final.shape[1])
]
df_predictions_since_100_cont_country_prov = pd.DataFrame(
{
"Continent": [self.continent for _ in range(len(all_dates_since_100))],
"Country": [self.country for _ in range(len(all_dates_since_100))],
"Province": [self.province for _ in range(len(all_dates_since_100))],
"Day": all_dates_since_100,
"Total Detected": total_detected,
"Active": active_cases,
"Active Hospitalized": active_hospitalized,
"Cumulative Hospitalized": cumulative_hospitalized,
"Total Detected Deaths": total_detected_deaths,
"Active Ventilated": active_ventilated,
}
)
return (
df_predictions_since_today_cont_country_prov,
df_predictions_since_100_cont_country_prov,
)
def create_datasets_raw(self) -> (pd.DataFrame, pd.DataFrame):
"""
Creates a dataset in the right format (with values for all 16 states of the DELPHI model)
for the Optimal Vaccine Allocation team
"""
n_days_btw_today_since_100 = (datetime.now() - self.date_day_since100).days
n_days_since_today = self.x_sol_final.shape[1] - n_days_btw_today_since_100
all_dates_since_today = [
str((datetime.now() + timedelta(days=i)).date())
for i in range(n_days_since_today)
]
df_predictions_since_today_cont_country_prov = pd.DataFrame(
{
"Continent": [self.continent for _ in range(n_days_since_today)],
"Country": [self.country for _ in range(n_days_since_today)],
"Province": [self.province for _ in range(n_days_since_today)],
"Day": all_dates_since_today,
}
)
intr_since_today = pd.DataFrame(
self.x_sol_final[:, n_days_btw_today_since_100:].transpose()
)
intr_since_today.columns = [
"S",
"E",
"I",
"AR",
"DHR",
"DQR",
"AD",
"DHD",
"DQD",
"R",
"D",
"TH",
"DVR",
"DVD",
"DD",
"DT",
]
df_predictions_since_today_cont_country_prov = pd.concat(
[df_predictions_since_today_cont_country_prov, intr_since_today], axis=1
)
# Generation of the dataframe from the day since 100th case
all_dates_since_100 = [
str((self.date_day_since100 + timedelta(days=i)).date())
for i in range(self.x_sol_final.shape[1])
]
df_predictions_since_100_cont_country_prov = pd.DataFrame(
{
"Continent": [self.continent for _ in range(len(all_dates_since_100))],
"Country": [self.country for _ in range(len(all_dates_since_100))],
"Province": [self.province for _ in range(len(all_dates_since_100))],
"Day": all_dates_since_100,
}
)
intr_since_100 = pd.DataFrame(self.x_sol_final.transpose())
intr_since_100.columns = [
"S",
"E",
"I",
"AR",
"DHR",
"DQR",
"AD",
"DHD",
"DQD",
"R",
"D",
"TH",
"DVR",
"DVD",
"DD",
"DT",
]
df_predictions_since_100_cont_country_prov = pd.concat(
[df_predictions_since_100_cont_country_prov, intr_since_100], axis=1
)
return (
df_predictions_since_today_cont_country_prov,
df_predictions_since_100_cont_country_prov,
)
def create_datasets_with_confidence_intervals(
self,
cases_data_fit: list,
deaths_data_fit: list,
past_prediction_file: str = "I://covid19orc//danger_map//predicted//Global_V2_20200720.csv",
past_prediction_date: str = "2020-07-04",
q: float = 0.5,
) -> (pd.DataFrame, pd.DataFrame):
"""
Generates the prediction datasets from the date with 100 cases and from the day of running, including columns
containing Confidence Intervals used in the website for cases and deaths
:param cases_data_fit: list, contains data used to fit on number of cases
:param deaths_data_fit: list, contains data used to fit on number of deaths
:param past_prediction_file: past prediction file's path for CI generation
:param past_prediction_date: past prediction's date for CI generation
:param q: quantile used for the CIs
:return: tuple of dataframes (since day of optimization & since 100 cases in the area) with predictions and
confidence intervals
"""
n_days_btw_today_since_100 = (datetime.now() - self.date_day_since100).days
n_days_since_today = self.x_sol_final.shape[1] - n_days_btw_today_since_100
all_dates_since_today = [
str((datetime.now() + timedelta(days=i)).date())
for i in range(n_days_since_today)
]
# Predictions
total_detected = self.x_sol_final[15, :] # DT
total_detected = [int(round(x, 0)) for x in total_detected]
active_cases = (
self.x_sol_final[4, :]
+ self.x_sol_final[5, :]
+ self.x_sol_final[7, :]
+ self.x_sol_final[8, :]
) # DHR + DQR + DHD + DQD
active_cases = [int(round(x, 0)) for x in active_cases]
active_hospitalized = (
self.x_sol_final[4, :] + self.x_sol_final[7, :]
) # DHR + DHD
active_hospitalized = [int(round(x, 0)) for x in active_hospitalized]
cumulative_hospitalized = self.x_sol_final[11, :] # TH
cumulative_hospitalized = [int(round(x, 0)) for x in cumulative_hospitalized]
total_detected_deaths = self.x_sol_final[14, :] # DD
total_detected_deaths = [int(round(x, 0)) for x in total_detected_deaths]
active_ventilated = (
self.x_sol_final[12, :] + self.x_sol_final[13, :]
) # DVR + DVD
active_ventilated = [int(round(x, 0)) for x in active_ventilated]
past_predictions = pd.read_csv(past_prediction_file)
past_predictions = (
past_predictions[
(past_predictions["Day"] > past_prediction_date)
& (past_predictions["Country"] == self.country)
& (past_predictions["Province"] == self.province)
]
).sort_values("Day")
if len(past_predictions) > 0:
known_dates_since_100 = [
str((self.date_day_since100 + timedelta(days=i)).date())
for i in range(len(cases_data_fit))
]
cases_data_fit_past = [
y
for x, y in zip(known_dates_since_100, cases_data_fit)
if x > past_prediction_date
]
deaths_data_fit_past = [
y
for x, y in zip(known_dates_since_100, deaths_data_fit)
if x > past_prediction_date
]
total_detected_past = past_predictions["Total Detected"].values[
: len(cases_data_fit_past)
]
total_detected_deaths_past = past_predictions[
"Total Detected Deaths"
].values[: len(deaths_data_fit_past)]
residual_cases_lb = np.sqrt(
np.mean(
[(x - y) ** 2 for x, y in zip(cases_data_fit_past, total_detected_past)]
)
) * scipy.stats.norm.ppf(0.5 - q / 2)
residual_cases_ub = np.sqrt(
np.mean(
[(x - y) ** 2 for x, y in zip(cases_data_fit_past, total_detected_past)]
)
) * scipy.stats.norm.ppf(0.5 + q / 2)
residual_deaths_lb = np.sqrt(
np.mean(
[
(x - y) ** 2
for x, y in zip(deaths_data_fit_past, total_detected_deaths_past)
]
)
) * scipy.stats.norm.ppf(0.5 - q / 2)
residual_deaths_ub = np.sqrt(
np.mean(
[
(x - y) ** 2
for x, y in zip(deaths_data_fit_past, total_detected_deaths_past)
]
)
) * scipy.stats.norm.ppf(0.5 + q / 2)
# Generation of the dataframe since today
df_predictions_since_today_cont_country_prov = pd.DataFrame(
{
"Continent": [self.continent for _ in range(n_days_since_today)],
"Country": [self.country for _ in range(n_days_since_today)],
"Province": [self.province for _ in range(n_days_since_today)],
"Day": all_dates_since_today,
"Total Detected": total_detected[n_days_btw_today_since_100:],
"Active": active_cases[n_days_btw_today_since_100:],
"Active Hospitalized": active_hospitalized[
n_days_btw_today_since_100:
],
"Cumulative Hospitalized": cumulative_hospitalized[
n_days_btw_today_since_100:
],
"Total Detected Deaths": total_detected_deaths[
n_days_btw_today_since_100:
],
"Active Ventilated": active_ventilated[n_days_btw_today_since_100:],
"Total Detected True": [np.nan for _ in range(n_days_since_today)],
"Total Detected Deaths True": [
np.nan for _ in range(n_days_since_today)
],
"Total Detected LB": make_increasing([
max(int(round(v + residual_cases_lb * np.sqrt(c), 0)), 0)
for c, v in enumerate(
total_detected[n_days_btw_today_since_100:]
)
]),
# "Active LB": [
# max(
# int(round(v + residual_cases_lb * np.sqrt(c) * v / u, 0)), 0
# )
# for c, (v, u) in enumerate(
# zip(
# active_cases[n_days_btw_today_since_100:],
# total_detected[n_days_btw_today_since_100:],
# )
# )
# ],
# "Active Hospitalized LB": [
# max(
# int(round(v + residual_cases_lb * np.sqrt(c) * v / u, 0)), 0
# )
# for c, (v, u) in enumerate(
# zip(
# active_hospitalized[n_days_btw_today_since_100:],
# total_detected[n_days_btw_today_since_100:],
# )
# )
# ],
# "Cumulative Hospitalized LB": make_increasing([
# max(
# int(round(v + residual_cases_lb * np.sqrt(c) * v / u, 0)), 0
# )
# for c, (v, u) in enumerate(
# zip(
# cumulative_hospitalized[n_days_btw_today_since_100:],
# total_detected[n_days_btw_today_since_100:],
# )
# )
# ]),
"Total Detected Deaths LB": make_increasing([
max(int(round(v + residual_deaths_lb * np.sqrt(c), 0)), 0)
for c, v in enumerate(
total_detected_deaths[n_days_btw_today_since_100:]
)
]),
# "Active Ventilated LB": [
# max(
# int(round(v + residual_cases_lb * np.sqrt(c) * v / u, 0)), 0
# )
# for c, (v, u) in enumerate(
# zip(
# active_ventilated[n_days_btw_today_since_100:],
# total_detected[n_days_btw_today_since_100:],
# )
# )
# ],
"Total Detected UB": [
max(int(round(v + residual_cases_ub * np.sqrt(c), 0)), 0)
for c, v in enumerate(
total_detected[n_days_btw_today_since_100:]
)
],
# "Active UB": [
# max(
# int(round(v + residual_cases_ub * np.sqrt(c) * v / u, 0)), 0
# )
# for c, (v, u) in enumerate(
# zip(
# active_cases[n_days_btw_today_since_100:],
# total_detected[n_days_btw_today_since_100:],
# )
# )
# ],
# "Active Hospitalized UB": [
# max(
# int(round(v + residual_cases_ub * np.sqrt(c) * v / u, 0)), 0
# )
# for c, (v, u) in enumerate(
# zip(
# active_hospitalized[n_days_btw_today_since_100:],
# total_detected[n_days_btw_today_since_100:],
# )
# )
# ],
# "Cumulative Hospitalized UB": [
# max(
# int(round(v + residual_cases_ub * np.sqrt(c) * v / u, 0)), 0
# )
# for c, (v, u) in enumerate(
# zip(
# cumulative_hospitalized[n_days_btw_today_since_100:],
# total_detected[n_days_btw_today_since_100:],
# )
# )
# ],
"Total Detected Deaths UB": [
max(int(round(v + residual_deaths_ub * np.sqrt(c), 0)), 0)
for c, v in enumerate(
total_detected_deaths[n_days_btw_today_since_100:]
)
],
# "Active Ventilated UB": [
# max(
# int(round(v + residual_cases_ub * np.sqrt(c) * v / u, 0)), 0
# )
# for c, (v, u) in enumerate(
# zip(
# active_ventilated[n_days_btw_today_since_100:],
# total_detected[n_days_btw_today_since_100:],
# )
# )
# ],
}
)
# Generation of the dataframe from the day since 100th case
all_dates_since_100 = [
str((self.date_day_since100 + timedelta(days=i)).date())
for i in range(self.x_sol_final.shape[1])
]
df_predictions_since_100_cont_country_prov = pd.DataFrame(
{
"Continent": [
self.continent for _ in range(len(all_dates_since_100))
],
"Country": [self.country for _ in range(len(all_dates_since_100))],
"Province": [
self.province for _ in range(len(all_dates_since_100))
],
"Day": all_dates_since_100,
"Total Detected": total_detected,
"Active": active_cases,
"Active Hospitalized": active_hospitalized,
"Cumulative Hospitalized": cumulative_hospitalized,
"Total Detected Deaths": total_detected_deaths,
"Active Ventilated": active_ventilated,
"Total Detected True": cases_data_fit
+ [
np.nan
for _ in range(len(all_dates_since_100) - len(cases_data_fit))
],
"Total Detected Deaths True": deaths_data_fit
+ [
np.nan for _ in range(len(all_dates_since_100) - len(deaths_data_fit))
],
"Total Detected LB": make_increasing([
max(
int(
round(
v
+ residual_cases_lb
* np.sqrt(max(c - n_days_btw_today_since_100, 0)),
0,
)
),
0,
)
for c, v in enumerate(total_detected)
]),
# "Active LB": [
# max(
# int(
# round(
# v
# + residual_cases_lb
# * np.sqrt(max(c - n_days_btw_today_since_100, 0))
# * v
# / u,
# 0,
# )
# ),
# 0,
# )
# for c, (v, u) in enumerate(zip(active_cases, total_detected))
# ],
# "Active Hospitalized LB": [
# max(
# int(
# round(
# v
# + residual_cases_lb
# * np.sqrt(max(c - n_days_btw_today_since_100, 0))
# * v
# / u,
# 0,
# )
# ),
# 0,
# )
# for c, (v, u) in enumerate(
# zip(active_hospitalized, total_detected)
# )
# ],
# "Cumulative Hospitalized LB": make_increasing([
# max(
# int(
# round(
# v
# + residual_cases_lb
# * np.sqrt(max(c - n_days_btw_today_since_100, 0))
# * v
# / u,
# 0,
# )
# ),
# 0,
# )
# for c, (v, u) in enumerate(
# zip(cumulative_hospitalized, total_detected)
# )
# ]),
"Total Detected Deaths LB": make_increasing([
max(
int(
round(
v
+ residual_deaths_lb
* np.sqrt(max(c - n_days_btw_today_since_100, 0)),
0,
)
),
0,
)
for c, v in enumerate(total_detected_deaths)
]),
# "Active Ventilated LB": [
# max(
# int(
# round(
# v
# + residual_cases_lb
# * np.sqrt(max(c - n_days_btw_today_since_100, 0))
# * v
# / u,
# 0,
# )
# ),
# 0,
# )
# for c, (v, u) in enumerate(
# zip(active_ventilated, total_detected)
# )
# ],
"Total Detected UB": [
max(
int(
round(
v
+ residual_cases_ub
* np.sqrt(max(c - n_days_btw_today_since_100, 0)),
0,
)
),
0,
)
for c, v in enumerate(total_detected)
],
# "Active UB": [
# max(
# int(
# round(
# v
# + residual_cases_ub
# * np.sqrt(max(c - n_days_btw_today_since_100, 0))
# * v
# / u,
# 0,
# )
# ),
# 0,
# )
# for c, (v, u) in enumerate(zip(active_cases, total_detected))
# ],
# "Active Hospitalized UB": [
# max(
# int(
# round(
# v
# + residual_cases_ub
# * np.sqrt(max(c - n_days_btw_today_since_100, 0))
# * v
# / u,
# 0,
# )
# ),
# 0,
# )
# for c, (v, u) in enumerate(
# zip(active_hospitalized, total_detected)
# )
# ],
# "Cumulative Hospitalized UB": [
# max(
# int(
# round(
# v
# + residual_cases_ub
# * np.sqrt(max(c - n_days_btw_today_since_100, 0))
# * v
# / u,
# 0,
# )
# ),
# 0,
# )
# for c, (v, u) in enumerate(
# zip(cumulative_hospitalized, total_detected)
# )
# ],
"Total Detected Deaths UB": [
max(
int(
round(
v
+ residual_deaths_ub
* np.sqrt(max(c - n_days_btw_today_since_100, 0)),
0,
)
),
0,
)
for c, v in enumerate(total_detected_deaths)
],
# "Active Ventilated UB": [
# max(
# int(
# round(
# v
# + residual_cases_ub
# * np.sqrt(max(c - n_days_btw_today_since_100, 0))
# * v
# / u,
# 0,
# )
# ),
# 0,
# )
# for c, (v, u) in enumerate(
# zip(active_ventilated, total_detected)
# )
# ],
}
)
else:
df_predictions_since_today_cont_country_prov = pd.DataFrame(
{
"Continent": [self.continent for _ in range(n_days_since_today)],
"Country": [self.country for _ in range(n_days_since_today)],
"Province": [self.province for _ in range(n_days_since_today)],
"Day": all_dates_since_today,
"Total Detected": total_detected[n_days_btw_today_since_100:],
"Active": active_cases[n_days_btw_today_since_100:],
"Active Hospitalized": active_hospitalized[
n_days_btw_today_since_100:
],
"Cumulative Hospitalized": cumulative_hospitalized[
n_days_btw_today_since_100:
],
"Total Detected Deaths": total_detected_deaths[
n_days_btw_today_since_100:
],
"Active Ventilated": active_ventilated[n_days_btw_today_since_100:],
"Total Detected True": [np.nan for _ in range(n_days_since_today)],
"Total Detected Deaths True": [
np.nan for _ in range(n_days_since_today)
],
"Total Detected LB": [np.nan for _ in range(n_days_since_today)],
# "Active LB": [np.nan for _ in range(n_days_since_today)],
# "Active Hospitalized LB": [
# np.nan for _ in range(n_days_since_today)
# ],
# "Cumulative Hospitalized LB": [
# np.nan for _ in range(n_days_since_today)
# ],
"Total Detected Deaths LB": [
np.nan for _ in range(n_days_since_today)
],
# "Active Ventilated LB": [np.nan for _ in range(n_days_since_today)],
"Total Detected UB": [np.nan for _ in range(n_days_since_today)],
# "Active UB": [np.nan for _ in range(n_days_since_today)],
# "Active Hospitalized UB": [
# np.nan for _ in range(n_days_since_today)
# ],
# "Cumulative Hospitalized UB": [
# np.nan for _ in range(n_days_since_today)
# ],
"Total Detected Deaths UB": [
np.nan for _ in range(n_days_since_today)
]
# "Active Ventilated UB": [np.nan for _ in range(n_days_since_today)],
}
)
# Generation of the dataframe from the day since 100th case
all_dates_since_100 = [
str((self.date_day_since100 + timedelta(days=i)).date())
for i in range(self.x_sol_final.shape[1])
]
df_predictions_since_100_cont_country_prov = pd.DataFrame(
{
"Continent": [