-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsimulator.js
1501 lines (1334 loc) · 53.2 KB
/
simulator.js
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
// COVID-19 Simulation Tool in JavaScript
// Copyright 2020 Savithru Jayasinghe and Dushan Wadduwage
// Licensed under the MIT License (LICENSE.txt)
'use strict';
// var date_format = 'DD-MM-YYYY';
var date_format = 'YYYY-MM-DD';
//Data about any quarantined index individuals in each country (required for Iq category)
var quarantine_data = {
"Sri Lanka" : [{t: "2020-03-13", y: 2},
{t: "2020-03-14", y: 2},
{t: "2020-03-15", y: 7},
{t: "2020-03-16", y: 6},
{t: "2020-03-17", y: 4},
{t: "2020-03-18", y: 1},
{t: "2020-03-19", y: 2},
{t: "2020-03-20", y: 3},
{t: "2020-03-21", y: 6},
{t: "2020-05-24", y: 49}, //should be distributed over many days
{t: "2020-05-25", y: 41},
{t: "2020-05-26", y: 127},
{t: "2020-05-27", y: 97},
{t: "2020-05-28", y: 35},
{t: "2020-05-29", y: 11},
{t: "2020-05-30", y: 38},
{t: "2020-05-31", y: 9},
{t: "2020-06-01", y: 8},
{t: "2020-06-02", y: 32},
{t: "2020-06-03", y: 35},
{t: "2020-06-04", y: 6},
{t: "2020-06-05", y: 2},
{t: "2020-06-06", y: 4},
{t: "2020-06-07", y: 21},
{t: "2020-06-08", y: 12},
{t: "2020-06-09", y: 1},
{t: "2020-06-10", y: 2},
{t: "2020-06-11", y: 0},
{t: "2020-06-12", y: 1},
{t: "2020-06-13", y: 3},
{t: "2020-06-14", y: 0},
{t: "2020-06-15", y: 13},
{t: "2020-06-16", y: 4},
{t: "2020-06-17", y: 7},
{t: "2020-06-18", y: 23},
{t: "2020-06-19", y: 3},
{t: "2020-06-20", y: 0},
{t: "2020-06-21", y: 0},
{t: "2020-06-22", y: 1},
{t: "2020-06-23", y: 40},
{t: "2020-06-24", y: 7},
{t: "2020-06-25", y: 3},
{t: "2020-06-26", y: 4},
{t: "2020-06-27", y: 19},
{t: "2020-06-28", y: 4}]
}
var data_start_dates = {
"Sri Lanka" : ["2020-09-15", "2020-03-01"],
"Sri Lanka - Colombo" : ["2020-10-22"],
"Sri Lanka - Gampaha" : ["2020-09-05"],
"Sri Lanka - Kurunegala": ["2020-10-02"],
};
var custom_country_data = {
"Sri Lanka-2020-03-01" : {
//Mar 1, Mar 15, Mar 25, Apr 10, Apr 15, Apr 25, Apr 30, Jun 1, Aug 1, Sep 15
t_start: [0, 14, 24, 40, 45, 55, 60, 92, 153, 198], //indices to start dates of any interventions
b1N: [0.8, 0.1, 0.05, 0.470, 0.6, 0.48, 0.48, 0.45, 0.45, 0.53], //values of b1N for each intervention segment defined in t_start
b2N: new Array(10).fill(0), //values of b2N
b3N: new Array(10).fill(0),
ce: [0, 0, 0, 0, 0, 0.5, 0.5, 0.5, 0.4, 0.4],
c0: [0, 0, 0, 0, 0.7, 0.7, 0.7, 0.4, 0.3, 0.3],
c1: [0.03, 0.03, 0.03, 0.965, 0.965, 0.965, 0.1, 0.1, 0.1, 0.1],
c2: new Array(10).fill(1.0),
c3: new Array(10).fill(1.0),
E0_0: 5, //no. of individuals exposed at start
// Rd_0: 1, //no. of recovered-diagnosed individuals at start
},
"Sri Lanka-2020-09-15" : {
//Sep 15, Oct 10, Nov 1, Nov 18, Dec 10, Jan 6, Feb 1, Feb 10, Mar 1, Apr 5, Apr 15, Apr 28, May 8, May 16, Jun 3, Jul 7, Jul 20, Aug 10, Sep 11, Sep 20, Oct 1, Oct 15, Jan 1, Feb 15
t_start: [0, 26, 47, 64, 86, 113, 139, 148, 167, 202, 212, 225, 235, 243, 261, 295, 308, 329, 361, 370, 381, 395, 473, 518], //indices to start dates of any interventions
b1N: [1.0, 0.44, 0.39, 0.425, 0.365, 0.43, 0.37, 0.31, 0.343, 0.53, 0.66, 0.477, 0.425, 0.405, 0.36, 0.437, 0.52, 0.58, 0.53, 0.4, 0.4, 0.55, 0.71, 0.45], //values of b1N for each intervention segment defined in t_start
b2N: new Array(24).fill(0), //values of b2N
b3N: new Array(24).fill(0),
ce: [0.176, 0.176, 0.176, 0.176, 0.176, 0.176, 0.176, 0.176, 0.176, 0.176, 0.176, 0.176, 0.176, 0.176, 0.176, 0.176, 0.176, 0.176, 0.176, 0.1, 0.05, 0.05, 0.05, 0.05],
c0: [0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.1, 0.05, 0.05, 0.05, 0.05],
c1: [0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.2, 0.1, 0.1, 0.1, 0.1, 0.1],
c2: new Array(24).fill(1.0),
c3: new Array(24).fill(1.0),
E0_0: 5, //no. of individuals exposed at start
// Rd_0: 1, //no. of recovered-diagnosed individuals at start
},
"Sri Lanka - Kurunegala-2020-10-02" : {
//Oct2, Oct13, Nov13, Jan15, Jan29, Feb12, Apr1, Apr22
t_start: [0, 11, 42, 105, 119, 133, 181, 202], //indices to start dates of any interventions
b1N: [0.900, 0.204, 0.239, 0.349, 0.239, 0.146, 0.506, 0.280], //values of b1N for each intervention segment defined in t_start
b2N: new Array(8).fill(0), //values of b2N
b3N: new Array(8).fill(0),
ce: new Array(8).fill(0.0),
c0: new Array(8).fill(0.0),
c1: new Array(8).fill(0.5),
c2: new Array(8).fill(1.0),
c3: new Array(8).fill(1.0),
E0_0: 5, //no. of individuals exposed at start
// Rd_0: 1, //no. of recovered-diagnosed individuals at start
}
}
//The control parameters will be set to these default values when the user first loads the page.
var default_controls = {
T_pred: 14, //prediction length
b1N: 0.0, //beta_1 value
b2N: 0.0, //beta_2 value
b3N: 0.0, //beta_3 value
ce: 0.0, //fraction of exposed patients diagnosed daily
c0: 0.0, //fraction of asymptomatic patients diagnosed daily
c1: 0.5, //fraction of mild patients diagnosed daily
c2: 1.0, //fraction of severe patients diagnosed daily
c3: 1.0, //fraction of critical patients diagnosed daily
IFR: 0.0055, //infection fatality ratio
param_error: 0.0 //error in parameters
}
//Storage for real and predicted data to be plotted on chart: {categorized, total}
var data_real;
var data_predicted;
var sim_params;
//Chart objects
var main_chart, control_chart;
var control_chart_active_point = null;
var control_chart_canvas = null;
var last_active_tooltip_day = 0;
var active_control_parameter = "b1N";
var active_country = "Sri Lanka";
var logarithmic_ticks = {
min: 0,
//max: 100000,
callback: function (value, index, values) {
if (value === 10000000) return "10M";
if (value === 1000000) return "1M";
if (value === 100000) return "100k";
if (value === 10000) return "10k";
if (value === 1000) return "1k";
if (value === 100) return "100";
if (value === 10) return "10";
if (value === 0) return "0";
return null;
}
};
var linear_ticks = {
min: 0,
//max: 100000,
callback: function (value, index, values) {
if (value == 0) return "0";
if (value < 1e3) return value.toFixed(0);
if (value < 1e6) return (value/1e3).toFixed(1) + "k";
if (value < 1e9) return (value/1e6).toFixed(1) + "M";
if (value < 1e12) return (value/1e9).toFixed(1) + "B";
return null;
}
};
window.onload = function()
{
populatePredictionHistoryTable();
readDistrictData();
generateCountryDropDown();
changeCountry(active_country);
//Update UI controls to match default values
document.getElementById("slider_finalT").value = default_controls.T_pred;
document.getElementById("slider_finalT_value").innerHTML = default_controls.T_pred;
document.getElementById("slider_param_IFR").value = default_controls.IFR * 100;
document.getElementById("slider_param_IFR_value").innerHTML = (default_controls.IFR * 100).toFixed(2);
document.getElementById("slider_param_error").value = default_controls.param_error * 100;
document.getElementById("slider_param_error_value").innerHTML = (default_controls.param_error * 100).toFixed(1);
}
//Function for merging district-level data to the global dataset.
function readDistrictData()
{
let district_names = ["Colombo", "Gampaha", "Kurunegala"];
world_population["Sri Lanka - Colombo"] = 2.31E6;
world_population["Sri Lanka - Gampaha"] = 2.295E6;
world_population["Sri Lanka - Kurunegala"] = 1.61E6;
for (const name of district_names)
{
const data_vec = SL_district_data[name];
let obj_vec = [];
const T_avg = 30;
const num_days = moment(data_vec[T_avg].x, date_format).diff(data_vec[0].x, 'days');
let avg_rate = (data_vec[T_avg].y - data_vec[0].y) / num_days;
const num_days_to_zero = Math.round(data_vec[0].y / avg_rate);
//Linearly extrapolate data to the zero-case date.
let T_extrap = num_days_to_zero + 7;
const start_date = moment(data_vec[0].x, date_format).subtract(T_extrap, 'days');
for (let i = 0; i < T_extrap; ++i)
{
obj_vec.push({"date": start_date.clone().add(i, 'days').format(date_format),
"confirmed": Math.round(Math.max(data_vec[0].y - avg_rate*(T_extrap - i), 0)),
"deaths": 0,
"recovered": 0});
}
//Append actual reported data
for (const data of data_vec)
{
obj_vec.push({"date": data.x,
"confirmed": data.y,
"deaths": 0,
"recovered": 0});
}
world_data["Sri Lanka - " + name] = obj_vec;
}
}
function generateCountryDropDown()
{
let country_menu = document.getElementById("dropdown_country");
let country_list = [];
for (let key of Object.keys(world_data))
country_list.push(key);
country_list.sort();
for (let name of country_list)
{
let option = document.createElement("option");
option.text = name;
country_menu.add(option);
}
country_menu.value = active_country;
}
function changeCountry(country_name)
{
active_country = country_name;
let startdate_menu = document.getElementById("dropdown_startdate");
startdate_menu.innerHTML = "";
let start_date_list = data_start_dates[active_country];
if (start_date_list)
{
for (let start_date of start_date_list)
{
let option = document.createElement("option");
option.text = start_date;
startdate_menu.add(option);
}
startdate_menu.value = start_date_list[0];
}
else {
let option = document.createElement("option");
option.text = "2020-02-01";
startdate_menu.add(option);
startdate_menu.value = option.text;
}
updateCountryData();
}
function updateCountryData()
{
data_real = getCountryData();
sim_params = initializeSimulationParameters(data_real.total.length, default_controls.T_pred);
data_predicted = getPredictionData(data_real.total[0].t);
document.getElementById("prediction_error").innerHTML = getCurrentPredictionError().toFixed(3);
document.getElementById("R_value").innerHTML = getReff(sim_params, 0).toFixed(3);
document.getElementById("estimated_CFR").innerHTML = (data_predicted.CFR*100).toFixed(2);
if (main_chart)
refreshAllChartData();
else {
setupChart();
setupControlChart();
}
}
function getCountryData()
{
let data_array = world_data[active_country];
let startdate_menu = document.getElementById("dropdown_startdate");
let start_date = startdate_menu.value;
if (start_date)
start_date = moment(start_date, date_format);
let data_cat = []; //{time t, y = [#confirmed, #recovered, #fatal, #quarantined, #vaccinated]}
let data_total = [], data_fatal = [];
if (start_date)
{
for (let data of data_array)
{
let data_t = moment(data.date, date_format);
if (start_date <= data_t)
{
data_total.push({t: data_t, y: data.confirmed});
data_cat.push({t: data_t, y: [data.confirmed, data.recovered, data.deaths, 0, 0]});
data_fatal.push({t: data_t, y: data.deaths});
}
}
}
else
{
let first_time = true;
for (let data of data_array)
{
let data_t = moment(data.date, date_format);
if (data.confirmed + data.recovered + data.deaths > 0)
{
if (first_time) //Add buffer days before first confirmed case
{
for (let i = 5; i > 0; --i)
{
let t_tmp = data_t.clone().subtract(i, 'days');
data_total.push({t: t_tmp, y: 0});
data_cat.push({t: t_tmp, y: [0, 0, 0, 0, 0]});
data_fatal.push({t: t_tmp, y: 0});
}
first_time = false;
}
data_total.push({t: data_t, y: data.confirmed});
data_cat.push({t: data_t, y: [data.confirmed, data.recovered, data.deaths, 0, 0]});
data_fatal.push({t: data_t, y: data.deaths});
}
}
}
//Check if country has any quarantine data
let qdata = quarantine_data[active_country];
if (qdata)
{
for (let data of qdata)
{
let data_t = moment(data.t, date_format);
let ind = data_t.diff(data_cat[0].t, 'days');
if (ind > 0)
data_cat[ind].y[3] = data.y;
}
}
//Check if country has any vaccine data
let vac_data = world_vaccine_data[active_country];
if (vac_data)
{
for (let i = 1; i < vac_data.length; ++i)
{
let data_t = moment(vac_data[i].t, date_format);
let ind = data_t.diff(data_cat[0].t, 'days');
if (ind >= 0 && ind < data_cat.length)
data_cat[ind].y[4] = vac_data[i].dose2 - vac_data[i-1].dose2;
}
}
return {total: data_total, categorized: data_cat, fatal: data_fatal};
}
function customizeParametersByCountry(country_name, params)
{
let country_name_with_start_date = country_name;
let start_date = document.getElementById("dropdown_startdate").value;
//if (country_name == "Sri Lanka" && start_date)
country_name_with_start_date += "-" + start_date;
let data = custom_country_data[country_name_with_start_date];
if (data)
{
for (let i = 0; i < data.t_start.length; ++i)
{
let j_end = (i < data.t_start.length-1) ? data.t_start[i+1] : params.b1N.length;
for (let j = data.t_start[i]; j < j_end; ++j)
{
params.b1N[j] = data.b1N[i];
params.b2N[j] = data.b2N[i];
params.b3N[j] = data.b3N[i];
params.ce[j] = data.ce[i];
params.c0[j] = data.c0[i];
params.c1[j] = data.c1[i];
params.c2[j] = data.c2[i];
params.c3[j] = data.c3[i];
}
}
//Update initial E0 and Rd
if (data.E0_0)
params.E0_0 = data.E0_0;
if (data.Rd_0)
params.Rd_0 = data.Rd_0;
}
//Update quarantine input data
for (let i = 0; i < data_real.categorized.length; ++i)
params.quarantine_input[i] = data_real.categorized[i].y[3];
//Update vaccine data
for (let i = 0; i < data_real.categorized.length; ++i)
params.vaccine_rate[i] = data_real.categorized[i].y[4];
//Update population
let N = world_population[country_name];
if (N)
params.population = N;
else
console.log("Population data not found for " + country_name + "!");
}
function formatNumber(num) {
return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
}
function setupChart()
{
let canvas = document.getElementById('chart_canvas');
//canvas.width = 0.7*window.innerWidth;
canvas.height = 0.65*window.innerHeight;
let ctx = canvas.getContext('2d');
let check_logy = document.getElementById('check_log_y');
let xaxis_config = {
type: 'time',
distribution: 'linear',
time: {
tooltipFormat: 'MMM D',
unit: 'day'
},
offset: true,
scaleLabel: {
display: true,
labelString: 'Date',
fontSize: 15
},
stacked: true
};
let yaxis_config = {
gridLines: {
drawBorder: false
},
type: 'linear',
scaleLabel: {
display: true,
labelString: 'No. of cases',
fontSize: 15
}
};
if (check_logy.checked)
{
yaxis_config.type = 'logarithmic';
yaxis_config.ticks = logarithmic_ticks;
}
else {
yaxis_config.type = 'linear';
yaxis_config.ticks = linear_ticks;
}
const bar_width_frac = 1.0;
const cat_width_frac = 0.9;
let main_chart_config = {
data: {
datasets: [
// {
// label: 'Susceptible',
// backgroundColor: '#eeeeec',
// data: data_predicted.categorized[0],
// type: 'bar',
// stack: 'stack0',
// hidden: true,
// barPercentage: bar_width_frac,
// categoryPercentage: cat_width_frac,
// order: 13
// },
{
label: 'Exposed',
backgroundColor: 'rgba(255, 220, 160, 0.75)',
type: 'bar',
stack: 'stack0',
barPercentage: bar_width_frac,
categoryPercentage: cat_width_frac,
order: 10
},
{
label: 'Asymptomatic',
backgroundColor: 'rgba(180, 240, 255, 0.75)',
type: 'bar',
stack: 'stack0',
barPercentage: bar_width_frac,
categoryPercentage: cat_width_frac,
order: 9
},
{
label: 'Recovered',
backgroundColor: 'rgba(130, 210, 50, 0.75)', //#73d216',
type: 'bar',
stack: 'stack0',
barPercentage: bar_width_frac,
categoryPercentage: cat_width_frac,
order: 8
},
{
label: 'Fatal',
backgroundColor: 'rgba(10, 10, 10, 0.75)',
type: 'bar',
stack: 'stack0',
barPercentage: bar_width_frac,
categoryPercentage: cat_width_frac,
order: 7
},
{
label: 'Mildly infected',
backgroundColor: 'rgba(255, 200, 0, 0.75)',
type: 'bar',
stack: 'stack0',
barPercentage: bar_width_frac,
categoryPercentage: cat_width_frac,
order: 6
},
{
label: 'Severely infected',
backgroundColor: 'rgba(240, 150, 40, 0.75)',
type: 'bar',
stack: 'stack0',
barPercentage: bar_width_frac,
categoryPercentage: cat_width_frac,
order: 5
},
{
label: 'Critically infected',
backgroundColor: 'rgba(200, 0, 0, 0.75)',
type: 'bar',
stack: 'stack0',
barPercentage: bar_width_frac,
categoryPercentage: cat_width_frac,
order: 4
},
{
label: 'Actual reported (avg)',
backgroundColor: 'rgba(1,1,1,0)',
borderColor: '#3465a4',
type: 'line',
fill: true,
borderWidth: 2,
pointRadius: 2,
order: 0
},
{
label: 'Predicted reported',
backgroundColor: 'rgba(1,1,1,0)',
borderColor: '#729fcf',
borderDash: [5, 5],
type: 'line',
fill: true,
borderWidth: 2,
pointRadius: 2,
order: 1
},
{
label: 'Actual deaths',
backgroundColor: 'rgba(1,1,1,0)',
borderColor: 'rgb(10, 10, 10)',
hidden: true,
type: 'line',
fill: true,
borderWidth: 2,
pointRadius: 2,
order: 2
},
{
label: 'Predicted deaths',
backgroundColor: 'rgba(1,1,1,0)',
borderColor: 'rgb(80, 80, 80)',
borderDash: [5, 5],
hidden: true,
type: 'line',
fill: true,
borderWidth: 2,
pointRadius: 2,
order: 3
},
{
label: 'Predicted lower',
backgroundColor: 'rgba(200,200,200,0.4)',
borderColor: 'rgba(100,100,100, 0.4)',
type: 'line',
fill: '+1',
borderWidth: 1,
pointRadius: 0,
order: 11
},
{
label: 'Predicted upper',
backgroundColor: 'rgba(200,200,200,0.4)',
borderColor: 'rgba(100,100,100, 0.4)',
type: 'line',
fill: '-1',
borderWidth: 1,
pointRadius: 0,
order: 12
},
{
label: 'Actual reported',
backgroundColor: 'rgba(1,1,1,0)',
borderColor: '#3465a4',
borderDash: [1, 1],
type: 'line',
fill: true,
borderWidth: 1,
pointRadius: 0,
order: 13
},
]
},
options: {
responsive: false,
maintainAspectRatio: false,
animation: {
duration: 500 // general animation time
},
scales: {
xAxes: [xaxis_config],
yAxes: [yaxis_config]
},
legend: {
display: true,
boxWidth: 10
},
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
updateLegend(tooltipItem.index);
document.getElementById("R_value").innerHTML = getReff(sim_params, tooltipItem.index).toFixed(3);
if (tooltipItem.datasetIndex >= 7)
return (data.datasets[tooltipItem.datasetIndex].label +
": " + formatNumber(data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index].y));
// Loop through all datasets to get the actual total of the index
// var total = 0;
// let labels = [];
// for (var i = 2; i < 10; i++)
// {
// labels.push(data.datasets[i].label + ": " + formatNumber(data.datasets[i].data[tooltipItem.index].y));
// total += data.datasets[i].data[tooltipItem.index].y;
// }
// labels.push("Total: " + formatNumber(total));
// return labels;
}
}
},
// annotation: {
// drawTime: 'afterDatasetsDraw',
// // Array of annotation configuration objects
// // See below for detailed descriptions of the annotation options
// annotations: [{
// drawTime: 'afterDraw', // overrides annotation.drawTime if set
// id: 'vertline_T0', // optional
// type: 'line',
// mode: 'vertical',
// scaleID: 'x-axis-0',
// value: data_predicted.total[default_controls.T0-1].t,
// borderColor: 'rgba(50,50,50,0.5)',
// borderWidth: 2,
// borderDash: [2, 2]
// },
// {
// drawTime: 'afterDraw', // overrides annotation.drawTime if set
// id: 'vertline_T1', // optional
// type: 'line',
// mode: 'vertical',
// scaleID: 'x-axis-0',
// value: data_predicted.total[data_predicted.total.length-1].t,
// borderColor: 'rgba(50,50,50,0.0)',
// borderWidth: 2,
// borderDash: [2, 2],
// hidden: true
// }]
// },
plugins: {
zoom: {
// Container for pan options
pan: {
enabled: true,
mode: 'x',
rangeMin: { x: null, y: 0 },
rangeMax: { x: null, y: null },
speed: 20, // On category scale, factor of pan velocity
threshold: 10, // Minimal pan distance required before actually applying pan
onPan: function () { syncPanAndZoom(main_chart, control_chart); }
},
// Container for zoom options
zoom: {
enabled: true,
drag: false, // Enable drag-to-zoom behavior
mode: 'x',
rangeMin: { x: null, y: 0 },
rangeMax: { x: null, y: null },
speed: 0.1, // (percentage of zoom on a wheel event)
sensitivity: 3, // On category scale, minimal zoom level before actually applying zoom
onZoom: function () { syncPanAndZoom(main_chart, control_chart); }
}
}
}
}
};
main_chart = new Chart(ctx, main_chart_config);
//Save off original axes (before any pan/zoom is applied)
main_chart.$zoom._originalOptions[main_chart.options.scales.xAxes[0].id] = main_chart.options.scales.xAxes[0];
main_chart.$zoom._originalOptions[main_chart.options.scales.yAxes[0].id] = main_chart.options.scales.yAxes[0];
refreshMainChartData();
};
function setupControlChart()
{
control_chart_canvas = document.getElementById('control_chart_canvas');
control_chart_canvas.height = 0.2*window.innerHeight;
let ctx = control_chart_canvas.getContext('2d');
let xaxis_config = {
type: 'time',
distribution: 'linear',
time: {
tooltipFormat: 'MMM D',
unit: 'day'
},
offset: true,
scaleLabel: {
display: false
},
ticks: {
display: false //this will remove only the label
}
};
let yaxis_config = {
gridLines: {
drawBorder: false
},
type: 'linear',
scaleLabel: {
display: true,
labelString: 'Beta1',
fontSize: 15
},
ticks: {
min: 0,
max: 1
}
};
let control_chart_config = {
data: {
datasets: [{
label: 'Beta1',
backgroundColor: 'rgba(1,1,1,0)',
borderColor: 'rgb(50, 160, 220)',
data: getControlChartData(),
type: 'line',
fill: true,
borderWidth: 2,
order: 1,
cubicInterpolationMode: 'monotone'
}]
},
options: {
responsive: false,
maintainAspectRatio: false,
animation: {
duration: 200 // general animation time
},
scales: {
xAxes: [xaxis_config],
yAxes: [yaxis_config]
},
legend: {
display: false,
},
hover: {
onHover: function(e, el) {
if (el[0])
{
control_chart_canvas.style.cursor = "pointer";
document.getElementById("R_value").innerHTML = getReff(sim_params, el[0]._index).toFixed(3);
}
else {
control_chart_canvas.style.cursor = "default";
}
}
},
plugins: {
zoom: {
// Container for pan options
pan: {
enabled: true,
mode: 'x',
rangeMin: { x: null, y: 0 },
rangeMax: { x: null, y: 1 },
speed: 20, // On category scale, factor of pan velocity
threshold: 10, // Minimal pan distance required before actually applying pan
onPan: function () { syncPanAndZoom(control_chart, main_chart); }
},
// Container for zoom options
zoom: {
enabled: true,
drag: false, // Enable drag-to-zoom behavior
mode: 'x',
rangeMin: { x: null, y: 0 },
rangeMax: { x: null, y: 1 },
speed: 0.1, // (percentage of zoom on a wheel event)
sensitivity: 3, // On category scale, minimal zoom level before actually applying zoom
onZoom: function () { syncPanAndZoom(control_chart, main_chart); }
},
}
}
}
};
control_chart = new Chart(ctx, control_chart_config);
// set pointer event handlers for canvas element
control_chart_canvas.onpointerdown = down_handler;
control_chart_canvas.onpointerup = up_handler;
control_chart_canvas.onpointermove = null;
//Save off original axes (before any pan/zoom is applied)
control_chart.$zoom._originalOptions[control_chart.options.scales.xAxes[0].id] = control_chart.options.scales.xAxes[0];
control_chart.$zoom._originalOptions[control_chart.options.scales.yAxes[0].id] = control_chart.options.scales.yAxes[0];
}
function down_handler(event)
{
// check for data point near event location
const points = control_chart.getElementAtEvent(event, {intersect: false});
if (points.length > 0) {
// grab nearest point, start dragging
control_chart_active_point = points[0];
control_chart_canvas.onpointermove = move_handler;
};
};
function up_handler(event)
{
// release grabbed point, stop dragging
control_chart_active_point = null;
control_chart_canvas.onpointermove = null;
};
function move_handler(event)
{
// locate grabbed point in chart data
if (control_chart_active_point != null) {
let data = control_chart_active_point._chart.data;
let datasetIndex = control_chart_active_point._datasetIndex;
// read mouse position
const helpers = Chart.helpers;
let position = helpers.getRelativePosition(event, control_chart);
// convert mouse position to chart y axis value
let chart_area = control_chart.chartArea;
let yaxis = control_chart.scales["y-axis-0"];
let yval_new = map(position.y, chart_area.bottom, chart_area.top, yaxis.min, yaxis.max);
if (active_control_parameter == "vaccine_rate") {
yval_new = Math.round(yval_new/1000)*1000; //round to nearest thousand
yval_new = Math.min(Math.max(yval_new, 0.0), 300000); //limit to [0,300000]
}
else { //parameters in [0,1] range
yval_new = Math.round(yval_new*1000)/1000; //round to nearest 0.001
yval_new = Math.min(Math.max(yval_new, 0.0), 1.0); //limit to [0,1]
}
//Update values to the right of the current index, until a different value is encountered.
let datavec = sim_params[active_control_parameter]; //get the data vector of the parameter current selected for editing
let yval_old = datavec[control_chart_active_point._index];
if (yval_new != yval_old)
{
for (let i = control_chart_active_point._index; i < datavec.length; ++i)
{
if (Math.abs(datavec[i] - yval_old) > 2e-3)
break;
datavec[i] = yval_new;
}
updateParameters(true);
}
};
};
// map value to other coordinate system
function map(value, start1, stop1, start2, stop2) {
return start2 + (stop2 - start2) * ((value - start1) / (stop1 - start1))
};
function syncPanAndZoom(chart_from, chart_to)
{
chart_to.options.scales.xAxes[0].time.min = chart_from.options.scales.xAxes[0].time.min;
chart_to.options.scales.xAxes[0].time.max = chart_from.options.scales.xAxes[0].time.max;
chart_to.update();
};
function changeControlChartParameter(parameter)
{
active_control_parameter = parameter;
refreshControlChartData();
}
function getControlChartData()
{
let data = [];
for (let i = 0; i < data_predicted.total.length; ++i)
data.push({t: data_predicted.total[i].t, y: sim_params[active_control_parameter][i]});
return data;
}
function refreshAllChartData()
{
refreshMainChartData();
refreshControlChartData();
}
function refreshMainChartData()
{
if (main_chart)
{
let array_name = document.querySelector('input[name="plot_data_type"]:checked').value; //returns cat_diag or cat_sum
let data_freq = document.querySelector('input[name="plot_data_freq"]:checked').value; //returns cumulative or daily
let calibration_mode = document.getElementById("check_calibration_mode").checked;
let n_cat = data_predicted[array_name].length;
for (let i = 0; i < n_cat; ++i)
main_chart.data.datasets[i].data = copyDataArray(data_predicted[array_name][i]);
main_chart.data.datasets[n_cat].data = copyDataArray(data_real.total); //This will be time-averaged below
main_chart.data.datasets[n_cat+1].data = copyDataArray(data_predicted.total);
main_chart.data.datasets[n_cat+2].data = copyDataArray(data_real.fatal);
main_chart.data.datasets[n_cat+3].data = copyDataArray(data_predicted[array_name][3]);
main_chart.data.datasets[n_cat+4].data = copyDataArray(data_predicted.lower);
main_chart.data.datasets[n_cat+5].data = copyDataArray(data_predicted.upper);
main_chart.data.datasets[n_cat+6].data = copyDataArray(data_real.total); //Actual reported data
if (data_freq == "daily")
{
for (let i = 0; i < main_chart.data.datasets.length; ++i)
{
for (let j = main_chart.data.datasets[i].data.length-1; j > 0; --j)
main_chart.data.datasets[i].data[j].y -= main_chart.data.datasets[i].data[j-1].y;
main_chart.data.datasets[i].data[0].y = 0;
}
}
//Compute 7-day moving average
const T_avg = 7;
let moving_avg = [];
let real_data_vec = main_chart.data.datasets[n_cat].data;
for (let i = T_avg-1; i < real_data_vec.length; ++i)
{
let sum = 0.0;
for (let j = 0; j < T_avg; ++j)
sum += real_data_vec[i-j].y;
moving_avg.push({t: real_data_vec[i].t, y: Math.round(sum/T_avg)});
}
main_chart.data.datasets[n_cat].data = moving_avg;
for (let i = 0; i < 7; ++i)
main_chart.data.datasets[i].hidden = calibration_mode || (data_freq == "daily");
main_chart.update();
delete main_chart.$zoom._originalOptions[main_chart.options.scales.xAxes[0].id].time.min;
delete main_chart.$zoom._originalOptions[main_chart.options.scales.xAxes[0].id].time.max;
updateLegend();
}