-
Notifications
You must be signed in to change notification settings - Fork 0
/
importationSummaryMultiState.Rmd
1763 lines (1498 loc) · 92.3 KB
/
importationSummaryMultiState.Rmd
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
---
title: "SARS-CoV-2 State Introductions"
subtitle: "Importation Summary for states"
date: '`r format(Sys.time(), "Last modified: %d %b %Y")`'
output:
pdf_document:
toc: true
toc_depth: 3
number_sections: true
keep_tex: false
fig_crop: false
layout: page
editor_options:
chunk_output_type: inline
params:
inputpath : "../../../data/phylogenetic/"
casefile : "../data/cases-rki-by-state.csv"
infectionfile : "../../../data/epidemiological/flaxman-results.csv"
epimobilitypath : "../../epidemiological/results/"
asymptomatic : 31
cluster_f : "DTA"
alpha : 0.7189865
beta : 28.91369
startDate : "2020-10-01"
endDate : "2021-06-01"
device : "pdf"
metadata : "../../../../data/data/gisaid-20210602-metadata.tsv"
outputfolder : "../results/beast/run/lin-ius/"
---
```{r rsetup, include=FALSE}
# metadata : "../results/gisaid-20210602-metadata-sampled-unsampled.tsv"
# outputpath : "../results/trees-gisaid-Hamburg-20210417-lin-rich/"
# state : "Hamburg"
library(lubridate)
library(plyr)
library(gplots)
library(beastio)
library(knitr)
library(tictoc)
library(stringr)
source("../reports/palettes.R")
source("../reports/plotutils.R")
source("../reports/clusterutils.R")
inputpath <- params$inputpath
casefile <- params$casefile
infectionfile<- params$infectionfile
epipath <- params$epimobilitypath
mobilitypath <- params$epimobilitypath
asymptomatic <- params$asymptomatic
cluster_f <- params$cluster_f
alpha <- params$alpha
beta <- params$beta
startDate <- as.Date(params$startDate)
endDate <- as.Date(params$endDate)
outputfolder <- params$outputfolder
# outputpath <- params$outputpath
# state <- params$state
figpath <- paste0(outputfolder, "figures/importation_figures_", params$device, "/")
dir.create(figpath, recursive = TRUE, showWarnings = FALSE)
cachepath <- paste0(outputfolder, "figures/cache/importationSummary_", params$device, "/")
knitr::opts_chunk$set(tidy=FALSE, cache=FALSE, cache.path = cachepath,
dev=params$device, fig.path=figpath, dpi=300,
message=FALSE, error=TRUE, warning=TRUE, echo=FALSE)
plotList <- c("China",
"Italy",
"Spain",
"France",
"Belgium",
"Netherlands",
"Ireland",
"Switzerland",
"US")
travelDates <- list(china = as.Date("2020-01-28"),
italy = as.Date("2020-02-25"),
lockdown = as.Date("2020-03-23"))
############
# Metadata #
############
#metadata <- read.csv(paste0(inputpath, "metadata.csv"))
metadata <- read.table(params$metadata, sep="\t", head=TRUE, na.strings=c("NA", ""), fill=TRUE, stringsAsFactors=FALSE, quote="|")
metadata <- metadata[metadata$Virus.name != "Virus.name",]
metadata$sample_date_orig <- ymd(metadata$Collection.date)
# metadata$sample_date <- ymd(metadata$date_corrected)
metadata$sample_date <- metadata$sample_date_orig
metadata$decimal_date <- decimal_date(metadata$sample_date)
metadata$taxon_label <- metadata$Accession.ID
metadata$country <- str_trim(sapply(str_split(metadata$Location, "/"), "[[", 2))
# metadata$state <- str_trim(sapply(str_split(paste0(metadata$Location,"/",metadata$Additional.location.information), "/"), "[[", 3))
set_instate <- function(metadata, state) {
return(sapply(str_split(paste0(metadata$Location,"/",metadata$Additional.location.information), "/"), function(x) {return(str_trim(x[2]) == "Germany" & (grepl(state, x[3], fixed=TRUE) | ( length(x) >= 4 & grepl(state, x[4], fixed=TRUE) )) );}))
}
# metadata$instate <- set_instate(metadata, state)
smooth <- function(cs) {
x <- cs
x[8:length(x)] <- (cs[8:length(x)] - cs[1:(length(x)-7)])/7
x[1:7] <- cs[1:7] / 1:7
return(x);
}
# case_data <- read.csv(params$casefile)
# case_data$case <- smooth(case_data$sum_cases)
# case_data$date <- ymd(as.POSIXct(case_data$time_iso8601))
# case_data$seq <- sapply(case_data$date, function(x) sum(!is.na(metadata$sample_date_orig) & metadata$sample_date_orig == x & metadata$instate))
# case_data$seq_smooth <- smooth(cumsum(case_data$seq))
stateFiles = data.frame(state = c("Germany"),
state.name = c("Germany"),
adm.level = c(2),
outputpath=c("../results/beast/run/lin-ius/") )
# outputpath=c("../results/beast/run/lin/") )
# outputpath=c("../results/beast/run/lin-rich-sk/") )
stateInfo <- list()
stateInfo$metadata_instate <- data.frame(matrix(0, nrow=nrow(metadata), ncol=0))
for (i in 1:nrow(stateFiles)) {
state <- stateFiles$state[i]
state.name <- stateFiles$state.name[i]
# DEBUG TODO
#stateInfo$metadata_instate <- cbind(stateInfo$metadata_instate, rep(FALSE, nrow(metadata)))
if (stateFiles$adm.level[i] == 3)
stateInfo$metadata_instate <- cbind(stateInfo$metadata_instate, set_instate(metadata, state.name))
else if (stateFiles$adm.level[i] == 2)
stateInfo$metadata_instate <- cbind(stateInfo$metadata_instate, metadata$country == state)
colnames(stateInfo$metadata_instate)[ncol(stateInfo$metadata_instate)] <- state
}
stateInfo$stateOrder <- c(1)
# for comments and documents before codes.
states <- paste(stateFiles$state)
rsumstate <- function(f) {
return(sapply(seq(nrow(stateFiles)), function(s) { return (paste(stateFiles$state[s], ":", f(stateFiles$state[s], s, stateInfo$clusterStatsMCC[[s]]))); }))
}
```
# Summary
This notebook plots figures about the dataset, applies the importation lag model to the `r states` transmission lineage TMRCAs and plots figures with lineage importations.
## Data and Method
- GISAID tree until ???? as initial tree.
- The tree contains ??? `r state` sequences.
- The tree is time-calibrated by TreeTime.
- Sankoff algorithm is used to assign location (`r states` and non-`r states`) to inner vertices of the tree.
```{r load-data, cache=TRUE}
stateInfo$clusterStatsMCC <- stateInfo$clusterSamplesMCC <- list()
for (i in 1:nrow(stateFiles)) {
state <- stateFiles$state[i]
outputpath <- stateFiles$outputpath[i]
#################################
# Load and shift lineage TMRCAs #
#################################
#clusterStats <- read.csv(paste0(outputpath, "clusters_", cluster_f, ".csv"))
#clusterStatsMCC <- read.csv(paste0(outputpath, "clusters_", cluster_f, "_MCC_0.5.csv"))
# clusterStatsMCC <- read.csv(paste0(outputpath, "clusters_", cluster_f, "_MCC.csv"))
clusterStatsMCC <- read.table(paste0(outputpath, "clusters_", cluster_f, "_MCC_0.5.tsv"), sep="\t", head=TRUE, na.strings=c("NA", ""), fill=TRUE, stringsAsFactors=FALSE, quote="|")
#clusterSamplesMCC <- read.csv(paste0(outputpath, "clusterSamples_", cluster_f, "_MCC_0.5.csv"))
# clusterSamplesMCC <- read.csv(paste0(outputpath, "clusterSamples_", cluster_f, "_MCC.csv"))
clusterSamplesMCC <- read.table(paste0(outputpath, "clusterSamples_", cluster_f, "_MCC_0.5.tsv"), sep="\t", head=TRUE, na.strings=c("NA", ""), fill=TRUE, stringsAsFactors=FALSE, quote="|")
clusterStatsMCC$cluster <- sapply(clusterStatsMCC$cluster, function(cluster) paste(strsplit( gsub("-", "_", cluster), split="_")[[1]][c(3,6,7)], collapse="_"))
clusterSamplesMCC$cluster <- sapply(clusterSamplesMCC$cluster, function(cluster) paste(strsplit( gsub("-", "_", cluster), split="_")[[1]][c(3,6,7)], collapse="_"))
clusterSamplesMCC$country <- str_trim(sapply(str_split(clusterSamplesMCC$Location, "/"), "[[", 2))
# clusterStats$tmrca_calendar <- ymd(clusterStats$tmrca_calendar)
clusterStatsMCC$tmrca_calendar <- ymd(clusterStatsMCC$tmrca_calendar)
#clusterSamplesMCC$sample_date <- ymd(clusterSamplesMCC$sample_date)
clusterStatsMCC$shift <- alpha + beta/clusterStatsMCC$seqs
clusterStatsMCC$tmrca_shifted <- clusterStatsMCC$tmrca - (clusterStatsMCC$shift/366)
clusterStatsMCC$tmrca_shifted_calendar <- as.Date(round_date(date_decimal(clusterStatsMCC$tmrca_shifted), unit = "day"))
clusterStatsMCC$detection_lag <- as.Date(round_date(date_decimal(clusterStatsMCC$oldest), unit = "day")) - clusterStatsMCC$tmrca_shifted_calendar
# #write.csv(clusterStatsMCC, paste0(outputpath, "clusters_", cluster_f, "_MCC_0.5_shifted.csv"), quote=FALSE, row.names=FALSE)
# write.csv(clusterStatsMCC, paste0(outputpath, "clusters_", cluster_f, "_MCC_shifted.csv"), quote=FALSE, row.names=FALSE)
stateInfo$clusterStatsMCC[[i]] = clusterStatsMCC
stateInfo$clusterSamplesMCC[[i]] = clusterSamplesMCC
# ############################################
# # Germany weekly cases and estimated infections #
# ############################################
#
# ukCases <- read.csv(casefile)
# ukCases$date <- as.Date(ukCases$date)
#
# europeInfections <- read.csv(infectionfile)
# europeInfections$time <- as.Date(europeInfections$time)
#
# weekBreaks <- seq.Date(as.Date("2020-01-19"), as.Date("2020-06-28"), by="weeks")
# ukWeekly <- data.frame(date = weekBreaks[2:length(weekBreaks)],
# seqs = hist(metadata$sample_date[metadata$country == "UK"], breaks=weekBreaks, plot=FALSE, right=FALSE)$counts,
# cases = getHistogram(ukCases$date, ukCases$newCasesBySpecimenDate,
# breaks=weekBreaks)$counts,
# infections = getHistogram(europeInfections$time[europeInfections$country == "United_Kingdom"],
# europeInfections$predicted_infections_mean[europeInfections$country == "United_Kingdom"],
# breaks=weekBreaks)$counts,
# infectionsLower = getHistogram(europeInfections$time[europeInfections$country == "United_Kingdom"],
# europeInfections$predicted_infections_lower_CI_95[europeInfections$country == "United_Kingdom"],
# breaks=weekBreaks)$counts,
# infectionsUpper = getHistogram(europeInfections$time[europeInfections$country == "United_Kingdom"],
# europeInfections$predicted_infections_higher_CI_95_cumulative.1[europeInfections$country == "United_Kingdom"],
# breaks=weekBreaks)$counts)
# ukWeekly$seqsCum <- cumsum(ukWeekly$seqs)
# ukWeekly$casesCum <- cumsum(ukWeekly$cases)
# ukWeekly$infectionsCum <- cumsum(ukWeekly$infections)
# ukWeekly$infectionsLowerCum <- cumsum(ukWeekly$infectionsLower)
# ukWeekly$infectionsUpperCum <- cumsum(ukWeekly$infectionsUpper)
#
#
# # dayBreaks <- seq.Date(as.Date("2020-01-19"), as.Date("2020-06-28"), by="day")
# # ukDaily <- data.frame(date = dayBreaks[2:length(dayBreaks)],
# # seqs = hist(metadata$sample_date[metadata$country == "UK"], breaks=dayBreaks, plot=FALSE, right=FALSE)$counts,
# # cases = getHistogram(ukCases$date, ukCases$newCasesBySpecimenDate,
# # breaks=dayBreaks)$counts,
# # infections = getHistogram(europeInfections$time[europeInfections$country == "United_Kingdom"],
# # europeInfections$predicted_infections_mean[europeInfections$country == "United_Kingdom"],
# # breaks=dayBreaks)$counts,
# # infectionsLower = getHistogram(europeInfections$time[europeInfections$country == "United_Kingdom"],
# # europeInfections$predicted_infections_lower_CI_95[europeInfections$country == "United_Kingdom"],
# # breaks=dayBreaks)$counts,
# # infectionsUpper = getHistogram(europeInfections$time[europeInfections$country == "United_Kingdom"],
# # europeInfections$predicted_infections_higher_CI_95_cumulative.1[europeInfections$country == "United_Kingdom"],
# # breaks=dayBreaks)$counts)
# # ukDaily$seqsCum <- cumsum(ukDaily$seqs)
# # ukDaily$casesCum <- cumsum(ukDaily$cases)
# # ukDaily$infectionsCum <- cumsum(ukDaily$infections)
# # ukDaily$infectionsLowerCum <- cumsum(ukDaily$infectionsLower)
# # ukDaily$infectionsUpperCum <- cumsum(ukDaily$infectionsUpper)
#
#
#
# #######
# # EII #
# #######
#
# eii <- read.csv(paste0(epipath, "estimated-introduction-index-", asymptomatic, ".csv"))
# eii$date <- as.Date(eii$date)
# colnames(eii)[2] <- "location"
# eii$location <- revalue(eii$location, c("other"="Other"))
#
# countryList <- levels(eii$location)
# countryList <- countryList[-which(countryList == "Other")]
#
# dates <- sort(unique(eii$date))
# eiiAll <- data.frame(date = dates,
# location = rep("all", length(dates)),
# num_intros = sapply(dates, function(x) sum(eii$num_intros[eii$date == x])))
#
# eii <- rbind(eiiAll, eii)
#
# # plot(eii$date[eii$location == "all"], eii$num_intros[eii$location == "all"], type='l')
# # lines(eii$date[eii$location == "Spain"], eii$num_intros[eii$location == "Spain"], type='l', lty=2)
# # lines(eii$date[eii$location == "France"], eii$num_intros[eii$location == "France"], type='l', lty=2)
#
#
# #########################################
# # Estimated daily numbers of infections #
# #########################################
#
# infections <- read.csv(paste0(epipath, "estimated-daily-infections.csv"))
# infections$date <- as.Date(infections$date)
#
# infectionsSpecific <- remove <- c()
# for (country in countryList) {
# mask <- which(infections$location == country)
# remove <- c(remove, mask)
# infectionsSpecific <- rbind(infectionsSpecific, infections[mask, ])
# }
# infectionsSpecific$location <- as.character(infectionsSpecific$location)
#
# dates <- sort(unique(infections$date))
# infectionsAll <- data.frame(date = dates,
# num_infs = sapply(dates, function(x) sum(infections$num_infs[infections$date == x])),
# location = rep("all", length(dates)))
#
# infections <- infections[-remove, ]
# infectionsOther <- data.frame(date = dates,
# num_infs = sapply(dates, function(x) sum(infections$num_infs[infections$date == x])),
# location = rep("Other", length(dates)))
#
# infections <- rbind(infectionsAll, rbind(infectionsSpecific, infectionsOther))
#
# # Smooth with 7-day rolling mean
# infections$num_infs_smoothed <- rep(0, nrow(infections))
# for (country in levels(infections$location)) {
#
# mask <- which(infections$location == country)
# dateOrder <- mask[order(infections$date[mask])]
#
# infections$num_infs_smoothed[dateOrder] <- sapply(1:length(dateOrder), function(i) mean(infections$num_infs[dateOrder[max(i-3,1):min(i+3, length(dateOrder))]], na.rm = TRUE))
# }
#
# # Total number of infected in each country by the end of the dataset
# totalInfected <- sort(sapply(levels(infections$location), function(x) sum(infections$num_infs[infections$location == x], na.rm=TRUE)), decreasing = TRUE)
#
# # loc <- "Switzerland"
# # plot(infections$date[infections$location == loc], infections$num_infs[infections$location == loc], type='l', lty=2)
# # lines(infections$date[infections$location == loc], infections$num_infs_smoothed[infections$location == loc])
#
#
# ############################
# # Estimated daily arrivals #
# ############################
#
# arrivals <- read.csv(paste0(epipath, "estimated-arrivals.csv"))
# arrivals$date <- as.Date(arrivals$date)
# arrivals$location <- revalue(arrivals$location, c("United States" = "US",
# "Czech Republic" = "Czechia",
# "Dominican Rep" = "Dominican Republic",
# "Korea (South)" = "Korea, South"))
#
# arrivalsSpecific <- remove <- c()
# for (country in countryList) {
# mask <- which(arrivals$location == country)
# remove <- c(remove, mask)
# arrivalsSpecific <- rbind(arrivalsSpecific, arrivals[mask, c("date", "location", "estimate")])
# }
# arrivalsSpecific$location <- as.character(arrivalsSpecific$location)
#
# dates <- sort(unique(arrivals$date))
# arrivalsAll <- data.frame(date = dates,
# location = rep("all", length(dates)),
# estimate = sapply(dates, function(x) sum(arrivals$estimate[arrivals$date == x])))
#
# arrivals <- arrivals[-remove, ]
# arrivalsOther <- data.frame(date = dates,
# location = rep("Other", length(dates)),
# estimate = sapply(dates, function(x) sum(arrivals$estimate[arrivals$date == x])))
#
# arrivals <- rbind(arrivalsAll, rbind(arrivalsSpecific, arrivalsOther))
#
# # Smooth with 7-day rolling mean
# arrivals$estimate_smoothed <- rep(0, nrow(arrivals))
# for (country in levels(arrivals$location)) {
#
# mask <- which(arrivals$location == country)
# dateOrder <- mask[order(arrivals$date[mask])]
#
# arrivals$estimate_smoothed[dateOrder] <- sapply(1:length(dateOrder), function(i) mean(arrivals$estimate[dateOrder[max(i-3,1):min(i+3, length(dateOrder))]], na.rm = TRUE))
# }
#
# # plot(arrivals$date[arrivals$location == "Spain"], arrivals$estimate[arrivals$location == "Spain"], type='l')
# #lines(arrivals$date[arrivals$location == "Spain"], arrivals$estimate_smoothed[arrivals$location == "Spain"], type='l', lty=2)
# #lines(arrivals$date[arrivals$location == "France"], arrivals$estimate[arrivals$location == "France"], type='l', lty=2)
#
#
# #################################
# # Lag model parameter estimates #
# #################################
# lagmodel <- read.csv(paste0(epipath, "tree-varying-lag-estimates.csv"))
}
```
\clearpage
# `r states` Sequenced Genomes
```{r sample-histogram, fig.width=7, fig.height=3, fig.cap = "Collection dates of the `nrow(metadata)` genomes analysed here (left-hand axis). Genomes are coloured by sampling location."}
sampleBreaks <- seq.Date(startDate,
max(metadata$sample_date_orig, na.rm = TRUE)+1, by="1 day")
seq_hist_oth <- hist(metadata$sample_date_orig[metadata$sample_date_orig> startDate],
breaks=sampleBreaks, plot=FALSE, right=FALSE)
seq_hist_names <- c()
seq_hist_breakdown <- data.frame(matrix(0, nrow=length(seq_hist_oth$counts), ncol=0))
# seq_hist_names <- c(seq_hist_names, "all")
# seq_hist_breakdown <- cbind(seq_hist_breakdown, seq_hist_oth$counts)
for (s in 1:nrow(stateFiles)) {
state <- stateFiles$state[s]
seq_hist_state <- hist(metadata$sample_date_orig[stateInfo$metadata_instate[s] & metadata$sample_date_orig> startDate],
breaks=sampleBreaks, plot=FALSE, right=FALSE)
seq_hist_breakdown <- cbind(seq_hist_breakdown, seq_hist_state$count)
seq_hist_names <- c(seq_hist_names, state)
seq_hist_state <- hist(metadata$sample_date_orig[!stateInfo$metadata_instate[s] & metadata$sample_date_orig> startDate],
breaks=sampleBreaks, plot=FALSE, right=FALSE)
seq_hist_breakdown <- cbind(seq_hist_breakdown, seq_hist_state$count)
seq_hist_names <- c(seq_hist_names, paste("Non", state))
}
colnames(seq_hist_breakdown) <- seq_hist_names
# seq_hist_eng <- hist(metadata$sample_date[metadata$adm1 == "UK-ENG"], breaks=sampleBreaks, plot=FALSE, right=FALSE)
# seq_hist_sct <- hist(metadata$sample_date[metadata$adm1 == "UK-SCT"], breaks=sampleBreaks, plot=FALSE, right=FALSE)
# seq_hist_wls <- hist(metadata$sample_date[metadata$adm1 == "UK-WLS"], breaks=sampleBreaks, plot=FALSE, right=FALSE)
# seq_hist_nir <- hist(metadata$sample_date[metadata$adm1 == "UK-NIR"], breaks=sampleBreaks, plot=FALSE, right=FALSE)
# seq_hist_oth <- hist(metadata$sample_date[metadata$country != "UK"], breaks=sampleBreaks, plot=FALSE, right=FALSE)
# seq_hist_breakdown <- data.frame("eng" = seq_hist_eng$counts,
# "sct" = seq_hist_sct$counts,
# "wls" = seq_hist_wls$counts,
# "nir" = seq_hist_nir$counts,
# "oth" = seq_hist_oth$counts)
draw_seq_freq_states <- function(selected_names, ymax = NA) {
selected_columns <- seq_hist_names %in% selected_names
if (is.na(ymax)) {
if (sum(selected_columns) > 1) {
ymax = max(rowSums(seq_hist_breakdown[,selected_columns])) * 1.05
} else {
ymax = max(seq_hist_breakdown[,selected_columns]) * 1.05
}
}
if (sum(selected_columns) == 1)
pal <- dePal[which(names(dePal) == seq_hist_names[selected_columns])]
else {
pal <- dePal[match(seq_hist_names, names(dePal))]
pal <- pal[selected_columns]
}
cat(paste(pal))
dateFreqDistribution(t(seq_hist_breakdown[,selected_columns]), sampleBreaks, plot.ci=FALSE, barplot=TRUE,
startDate = sampleBreaks[1],
endDate = sampleBreaks[length(sampleBreaks)-1],
col=mPal(unlist(pal), 0.75), border=mPal(unlist(pal)), ymax=ymax,
ylab = "Frequency of genomes\n(per day)")
legend("top", horiz=FALSE, inset=c(0,-0.3), bty='n', xpd=TRUE, ncol=3,
fill=mPal(unlist(pal), 0.75), border = mPal(unlist(pal)),
legend = seq_hist_names[selected_columns],
# legend = c("Germany", "Other countries"),
#legend = c("England", "Scotland", "Wales"#FF7F00, "Northern Ireland", "Other countries"),
cex=0.8)
}
# Sequence histogram
par(mar=c(4,6,2.5,6), cex.axis=0.7, cex.lab=0.8, mgp=c(3,0.75,0))
draw_seq_freq_states(c("Germany", "Non Germany"))
draw_seq_freq_states(c("Germany"), ymax=max(seq_hist_breakdown[, "Germany"]) * 1.05)
ymax=400 * 1.05
# draw_seq_freq_states(c("Hamburg"), ymax=ymax)
# draw_seq_freq_states(c("Bavaria"), ymax=ymax)
# draw_seq_freq_states(c("North_Rhine-Westphalia"), ymax=ymax)
# draw_seq_freq_states(c("Saarland"), ymax=ymax)
# # draw_seq_freq_states(c("Saxony"))
# draw_seq_freq_states(c("Lower_Saxony"), ymax=ymax)
#
# draw_seq_freq_states(c("Munich"), ymax=ymax)
# draw_seq_freq_states(c("Dusseldorf"), ymax=ymax)
# # dateFreqDistribution(t(seq_hist_breakdown), sampleBreaks, plot.ci=FALSE, barplot=TRUE,
# # startDate = sampleBreaks[1], endDate = sampleBreaks[length(sampleBreaks)-1], col=mPal(unlist(ukPal)[1], 0.75), border=mPal(unlist(ukPal))[1], ymax=1100,
# # ylab = "Frequency of genomes\n(per day)")
#
# dateFreqDistribution(t(seq_hist_breakdown), sampleBreaks, plot.ci=FALSE, barplot=TRUE,
# startDate = sampleBreaks[1],
# endDate = sampleBreaks[length(sampleBreaks)-1],
# col=mPal(unlist(dePal), 0.75), border=mPal(unlist(dePal)), ymax=max(seq_hist_breakdown)+2,
# ylab = "Frequency of genomes\n(per day)")
#
#
# legend("top", horiz=FALSE, inset=c(0,-0.3), bty='n', xpd=TRUE, ncol=3,
# fill=mPal(unlist(ukPal), 0.75), border = mPal(unlist(ukPal)),
# legend = seq_hist_names,
# # legend = c("Germany", "Other countries"),
# #legend = c("England", "Scotland", "Wales", "Northern Ireland", "Other countries"),
# cex=0.8)
#
# dateFreqDistribution(t(seq_hist_breakdown), sampleBreaks, plot.ci=FALSE, barplot=TRUE,
# startDate = sampleBreaks[1],
# endDate = sampleBreaks[length(sampleBreaks)-1],
# col=mPal(unlist(dePal), 0.75), border=mPal(unlist(dePal)), ymax=max(seq_hist_breakdown)+2,
# ylab = "Frequency of genomes\n(per day)")
#
#
#
# legend("top", horiz=FALSE, inset=c(0,-0.3), bty='n', xpd=TRUE, ncol=3,
# fill=mPal(unlist(ukPal), 0.75), border = mPal(unlist(ukPal)),
# legend = seq_hist_names,
# # legend = c("Germany", "Other countries"),
# #legend = c("England", "Scotland", "Wales", "Northern Ireland", "Other countries"),
# cex=0.8)
# seq_hist_breakdown <- data.frame("de" = seq_hist_de$counts)
#
# dateFreqDistribution(t(seq_hist_breakdown), sampleBreaks, plot.ci=FALSE, barplot=TRUE,
# startDate = sampleBreaks[1], endDate = sampleBreaks[length(sampleBreaks)-1], col=mPal(unlist(dePal)[1], 0.75), border=mPal(unlist(dePal))[1], ymax=max(seq_hist_breakdown)+2,
# ylab = "Frequency of genomes\n(per day)")
#
#
# legend("top", horiz=FALSE, inset=c(0,-0.3), bty='n', xpd=TRUE, ncol=3,
# fill=mPal(unlist(ukPal), 0.75), border = mPal(unlist(ukPal)),
# legend = c(state, "Other places"),
# # legend = c("Germany", "Other countries"),
# #legend = c("England", "Scotland", "Wales", "Northern Ireland", "Other countries"),
# cex=0.8)
normalize_hist <- function(counts, breaks, normalization_break, normalization_value) {
hist_index <- match(breaks[-length(breaks)], normalization_break)
hist_weighted <- counts * normalization_value[hist_index]
valid_index <- !is.na(hist_weighted) & !is.nan(hist_weighted)
hist_weighted <- hist_weighted[valid_index]
valid_index[max(which(valid_index))+1] <- TRUE
hist_breaks <- breaks[valid_index]
return (list("hist"=hist_weighted, "breaks"=hist_breaks));
}
# x <- normalize_hist(seq_hist_de$counts, sampleBreaks, case_data$date, case_data$case / case_data$seq_smooth)
# seq_hist_de_weighted = x$hist;
# sampleBreaks_weighted = x$breaks;
#
# # hist_index <- match(sampleBreaks[-length(sampleBreaks)], case_data$date)
# # seq_hist_de_weighted <- seq_hist_de$counts / case_data$seq_smooth[hist_index] * case_data$case[hist_index]
# #
# # valid_index <- !is.na(seq_hist_de_weighted) & !is.nan(seq_hist_de_weighted)
# # seq_hist_de_weighted <- seq_hist_de_weighted[valid_index]
# # valid_index[max(which(valid_index))+1] <- TRUE
# # sampleBreaks_weighted <- sampleBreaks[valid_index]
#
# seq_hist_breakdown <- data.frame("de" = seq_hist_de_weighted)
#
# # dateFreqDistribution(t(seq_hist_breakdown), sampleBreaks_weighted, plot.ci=FALSE, barplot=TRUE,
# # startDate = sampleBreaks_weighted[1], endDate = sampleBreaks_weighted[length(sampleBreaks_weighted)-1], col=mPal(unlist(dePal)[1], 0.75), border=mPal(unlist(dePal))[1], ymax=50000,
# # ylab = "Frequency of genomes\n(per day)")
# #
# #
# # legend("top", horiz=FALSE, inset=c(0,-0.3), bty='n', xpd=TRUE, ncol=3,
# # fill=mPal(unlist(ukPal), 0.75), border = mPal(unlist(ukPal)),
# # legend = c("Germany", "Other countries"),
# # #legend = c("England", "Scotland", "Wales", "Northern Ireland", "Other countries"),
# # cex=0.8)
# #
# # Cumulative sequences, cases and infections
# # par(new = TRUE)
# # ylims <- c(1,1E7)
# # plot(1, type='n', xlim=c(startDate, as.Date("2020-06-21")), ylim=ylims,
# # axes=FALSE, xlab="", ylab="", log='y', yaxs='i', xaxs='i')
# #
# # #axis(4, las=1, at=axTicks(4), labels=format(axTicks(4), scientific=FALSE))
# # plotLogAxis(lim=ylims, side=4)
# # mtext(side=4, text="Cumulative cases and genomes", line=2, cex=0.8)
#
#
# #ukseqs_daily <- data.frame(date = sampleBreaks[1:(length(sampleBreaks)-1)],
# # seqs = rowSums(seq_hist_breakdown[, -c(5)]))
# #lines(ukseqs_daily$date, cumsum(ukseqs_daily$seqs), lwd=2)
#
# # polygon(c(europeInfections$time[europeInfections$country == "United_Kingdom"],
# # rev(europeInfections$time[europeInfections$country == "United_Kingdom"])),
# # c(europeInfections$predicted_infections_higher_CI_95_cumulative[europeInfections$country == "United_Kingdom"],
# # rev(europeInfections$predicted_infections_lower_CI_95_cumulative[europeInfections$country == "United_Kingdom"])),
# # border=NA, col = mPal(ukPal$oth, 0.75))
# # lines(europeInfections$time[europeInfections$country == "United_Kingdom"], europeInfections$predicted_infections_mean_cumulative[europeInfections$country == "United_Kingdom"],
# # lty=3, lwd=2)
# #lines(c(ukCases$date, min(ukCases$date)-1), c(ukCases$cumCasesBySpecimenDate, 1E-10), lwd=2, lty=2)
#
# # idx <- which(ukWeekly$date == as.Date("2020-05-17"))
# # text(x = as.Date("2020-05-17"), y = ukWeekly$infectionsCum[idx]+5E6, "Estimated UK\ninfections",
# # pos=1, xpd=TRUE, cex=0.6)
# # text(x = as.Date("2020-05-17"), y = ukWeekly$casesCum[idx]+1.5E5, "Reported UK\ncases",
# # pos=1, xpd=TRUE, cex=0.6)
# # text(x = as.Date("2020-05-17"), y = ukWeekly$seqsCum[idx], "UK genomes\nsequenced",
# # pos=1, xpd=TRUE, cex=0.6)
#
```
```{r sample-density, fig.width=6, fig.height=3, fig.cap = "Top row: Proportions of laborotory-confirmed cases sequenced. Bottom row: Proportions of the estimated number of infections (estimate from Flaxman et al. 2020)."}
# layout(matrix(1:4, nrow = 2, byrow=FALSE))
#
# idx <- which(ukWeekly$date == as.Date("2020-04-05"))
#
# # Sequencing proportions
# par(mar=c(0,0,1,2))
# plotPieProp(ukWeekly$seqsCum[idx], ukWeekly$casesCum[idx], title="Reported cases by 5 April", col=ukPal$sct, line=0)
#
# par(mar=c(0,0,1,2))
# plotPieProp(ukWeekly$seqsCum[idx], ukWeekly$infectionsCum[idx], title="Estimated infections by 5 April", col=ukPal$sct, line=0)
#
# idx <- which(ukWeekly$date == as.Date("2020-05-03"))
#
# # Sequencing proportions
# par(mar=c(0,0,1,2))
# plotPieProp(ukWeekly$seqsCum[idx], ukWeekly$casesCum[idx], title="Reported cases by May 3", col=ukPal$sct, line=0)
#
# par(mar=c(0,0,1,2))
# plotPieProp(ukWeekly$seqsCum[idx], ukWeekly$infectionsCum[idx], title="Estimated infections by May 3", col=ukPal$sct, line=0)
#
```
```{r sampling-proportion-weekly, fig.width=7, fig.height=3, fig.cap = "Proportion of weekly reported cases (solid line) and estimated infections (dotted line; Flaxman et al. 2020) included in our genome sequence dataset."}
# cleanProp <- function(x) {
# x[is.nan(x)] <- NA
# x[is.infinite(x)] <- NA
# x[x > 1] <- 1
# return(x)
# }
#
# caseProp <- cleanProp(ukWeekly$seqs/ukWeekly$cases)
# infProp <- cleanProp(ukWeekly$seqs/ukWeekly$infections)
# infMask <- !is.na(infProp)
#
# par(mar=c(4,6,2.5,6), cex.axis=0.7, cex.lab=0.8, mgp=c(3,0.75,0))
#
# plotShadedAxes(xlim=c(startDate, as.Date("2020-06-21")), ylim=c(0, 1.015), yaxs='i', ylab="Proportion")
#
# #polygon(c(ukWeekly$date[infMask], rev(ukWeekly$date[infMask])), c(cleanProp(ukWeekly$seqs/ukWeekly$infectionsLower)[infMask], rev(cleanProp(ukWeekly$seqs/ukWeekly$infectionsUpper)[infMask])),
# # col = mPal(ukPal$oth, 0.75), border=NA)
# infPropLower <- cleanProp(ukWeekly$seqs/ukWeekly$infectionsLower)
# infPropUpper <- cleanProp(ukWeekly$seqs/ukWeekly$infectionsUpper)
# for (i in 2:length(infMask)) {
# rect(ukWeekly$date[i-1], infPropLower[i], ukWeekly$date[i], infPropUpper[i], col = mPal(ukPal$oth, 0.75), border=NA)
# }
# lines(ukWeekly$date, infProp, lty=3, lwd=2, type='S')
# idx <- min(which(infMask))
# lines(ukWeekly$date[(idx-1):idx], rep(infProp[idx],2), lty=3, lwd=2)
# lines(ukWeekly$date, caseProp, lty=1, lwd=2, type='S')
#
#
# legend("bottom", horiz=FALSE, inset=c(0,1), bty='n', xpd=TRUE, ncol=2,
# lty=c(1,3), lwd=2,
# legend = c("reported cases", "estimated infections"), title="Sequenced proportion of weekly", cex=par("cex.lab"))
#
# # Inset start
# ymax <- 0.1
# insetStart <- as.Date("2020-02-16")
# insetEnd <- as.Date("2020-05-10")
#
# rect(insetStart, 0, insetEnd, ymax, lty=2)
#
# par(mar=c(2,2,0.5,0.5), cex.axis=0.7, cex.lab=0.8, mgp=c(3,0.75,0), fig=c(0.445, 0.875, 0.45, 0.88), new=TRUE)
#
# plotShadedAxes(xlim=c(insetStart, insetEnd), ylim=c(0, ymax), yaxs='i', side=4)
#
# #polygon(c(ukWeekly$date[infMask], rev(ukWeekly$date[infMask])), c(cleanProp(ukWeekly$seqs/ukWeekly$infectionsLower)[infMask], rev(cleanProp(ukWeekly$seqs/ukWeekly$infectionsUpper)[infMask])),
# # col = mPal(ukPal$oth, 0.75), border=NA)
# for (i in 2:length(infMask)) {
# rect(ukWeekly$date[i-1], infPropLower[i], ukWeekly$date[i], infPropUpper[i], col = mPal(ukPal$oth, 0.75), border=NA)
# }
# lines(ukWeekly$date, infProp, lty=3, lwd=2, type='S')
# idx <- min(which(infMask))
# lines(ukWeekly$date[(idx-1):idx], rep(infProp[idx],2), lty=3, lwd=2)
# lines(ukWeekly$date, caseProp, lty=1, lwd=2, type='S')
#
# rect(insetStart, 0, insetEnd, ymax, xpd=TRUE)
#
#
# #plotShadedAxes(xlim=c(startDate, as.Date("2020-06-21")), ylim=c(0, 10000), yaxs='i')
# #lines(ukCases$date, ukCases$newCasesBySpecimenDate)
#
# #dateFreqDistribution(rev(ukCases$newCasesBySpecimenDate[2:nrow(ukCases)]), rev(ukCases$date), startDate="2020-01-31", endDate="2020-06-21", barplot=TRUE)
```
```{r sampling-proportion-weekly-flipped, fig.width=7, fig.height=3, fig.cap = "Proportion of weekly reported cases (solid line) and estimated infections (dotted line; Flaxman et al. 2020) included in our genome sequence dataset."}
# cleanProp <- function(x) {
# x[is.nan(x)] <- NA
# x[is.infinite(x)] <- NA
# x[x > 1] <- 1
# return(x)
# }
#
# caseProp <- cleanProp(ukWeekly$seqs/ukWeekly$cases)
# infProp <- cleanProp(ukWeekly$seqs/ukWeekly$infections)
# infMask <- !is.na(infProp)
#
# par(mar=c(4,6,2.5,6), cex.axis=0.7, cex.lab=0.8, mgp=c(3,0.75,0))
#
# plotShadedAxes(xlim=c(startDate, as.Date("2020-06-21")), ylim=c(0, 0.1), yaxs='i', ylab="Proportion")
#
# infPropLower <- cleanProp(ukWeekly$seqs/ukWeekly$infectionsLower)
# infPropUpper <- cleanProp(ukWeekly$seqs/ukWeekly$infectionsUpper)
# for (i in 2:length(infMask)) {
# rect(ukWeekly$date[i-1], infPropLower[i], ukWeekly$date[i], infPropUpper[i], col = mPal(ukPal$oth, 0.75), border=NA)
# }
# lines(ukWeekly$date, infProp, lty=3, lwd=2, type='S')
# idx <- min(which(infMask))
# lines(ukWeekly$date[(idx-1):idx], rep(infProp[idx],2), lty=3, lwd=2)
# lines(ukWeekly$date, caseProp, lty=1, lwd=2, type='S')
#
#
# legend("bottomleft", horiz=FALSE, inset=c(0,1), bty='n', xpd=TRUE, ncol=2,
# lty=c(1,3), lwd=2,
# legend = c("reported cases", "estimated infections"), title="Sequenced proportion of weekly", cex=par("cex.lab"))
#
# # Inset start
# ymax <- 1
# insetStart <- as.Date("2020-01-19")
# insetEnd <- as.Date("2020-06-21")
#
# #rect(insetStart, 0, insetEnd, ymax, lty=2)
#
# par(mar=c(2,2,0.5,0.5), cex.axis=0.7, cex.lab=0.8, mgp=c(3,0.75,0), fig=c(0.65, 0.95, 0.55, 0.95), new=TRUE)
#
# plotShadedAxes(xlim=c(insetStart, insetEnd), ylim=c(0, ymax), yaxs='i', side=2, smallBreaks = "weeks", thinXLabel = 4, thinYLabel=5)
#
# #polygon(c(ukWeekly$date[infMask], rev(ukWeekly$date[infMask])), c(cleanProp(ukWeekly$seqs/ukWeekly$infectionsLower)[infMask], rev(cleanProp(ukWeekly$seqs/ukWeekly$infectionsUpper)[infMask])),
# # col = mPal(ukPal$oth, 0.75), border=NA)
# for (i in 2:length(infMask)) {
# rect(ukWeekly$date[i-1], infPropLower[i], ukWeekly$date[i], infPropUpper[i], col = mPal(ukPal$oth, 0.75), border=NA)
# }
# lines(ukWeekly$date, infProp, lty=3, lwd=2, type='S')
# idx <- min(which(infMask))
# lines(ukWeekly$date[(idx-1):idx], rep(infProp[idx],2), lty=3, lwd=2)
# lines(ukWeekly$date, caseProp, lty=1, lwd=2, type='S')
#
# rect(insetStart, 0, insetEnd, ymax, xpd=TRUE)
```
```{r sampling-proportion-weekly-infections, fig.width=7, fig.height=3, fig.cap = "Proportion of weekly estimated infections (Flaxman et al. 2020) included in our genome sequence dataset."}
#
# cleanProp <- function(x) {
# x[is.nan(x)] <- NA
# x[is.infinite(x)] <- NA
# x[x > 1] <- 1
# return(x)
# }
#
#
# par(mar=c(4,6,2.5,6), cex.axis=0.7, cex.lab=0.8, mgp=c(3,0.75,0))
#
# plotShadedAxes(xlim=c(startDate, as.Date("2020-06-21")), ylim=c(0, 0.1), yaxs='i', ylab="Proportion")
#
# infProp <- cleanProp(ukWeekly$seqs/ukWeekly$infections)
# infMask <- !is.na(infProp)
# infPropLower <- cleanProp(ukWeekly$seqs/ukWeekly$infectionsLower)
# infPropUpper <- cleanProp(ukWeekly$seqs/ukWeekly$infectionsUpper)
# for (i in 2:length(infMask)) {
# rect(ukWeekly$date[i-1], infPropLower[i], ukWeekly$date[i], infPropUpper[i], col = mPal(ukPal$oth, 0.75), border=NA)
# }
# lines(ukWeekly$date, infProp, lty=3, lwd=2, type='S')
# idx <- min(which(infMask))
# lines(ukWeekly$date[(idx-1):idx], rep(infProp[idx],2), lty=3, lwd=2)
#
# #legend("bottomleft", horiz=FALSE, inset=c(0,1), bty='n', xpd=TRUE, ncol=2,
# # lty=c(1,3), lwd=2,
# # legend = c("reported cases", "estimated infections"), title="Sequenced proportion of weekly", cex=par("cex.lab"))
#
#
#
```
```{r sampling-proportion-cumulative, fig.width=7, fig.height=3, fig.cap = "Proportion of the cumulative weekly reported cases (solid line) and estimated infections (dotted line; Flaxman et al. 2020) included in our genome sequence dataset over time."}
#
# getCumulativeSequences <- function(dateRange, seqDates) {
#
# return <- data.frame(date = dateRange,
# seqs = sapply(dateRange, function(x) sum(seqDates <= x)))
#
# }
#
# seqsCum <- getCumulativeSequences(ukCases$date, metadata$sample_date[metadata$country == "UK"])
# cumCaseProp <- cleanProp(seqsCum$seqs/ukCases$cumCasesBySpecimenDate)
#
# seqsCum <- getCumulativeSequences(europeInfections$time[europeInfections$country == "United_Kingdom"], metadata$sample_date[metadata$country == "UK"])
# cumInfProp <- cleanProp(seqsCum$seqs/europeInfections$predicted_infections_mean_cumulative[europeInfections$country == "United_Kingdom"])
# cumInfPropL <- cleanProp(seqsCum$seqs/europeInfections$predicted_infections_lower_CI_95_cumulative[europeInfections$country == "United_Kingdom"])
# cumInfPropU <- cleanProp(seqsCum$seqs/europeInfections$predicted_infections_higher_CI_95_cumulative[europeInfections$country == "United_Kingdom"])
#
# par(mar=c(4,6,2.5,6), cex.axis=0.7, cex.lab=0.8, mgp=c(3,0.75,0))
#
# plotShadedAxes(xlim=c(startDate, as.Date("2020-06-21")), ylim=c(0, 1.015), yaxs='i', ylab="Cumulative proportion")
#
# polygon(c(seqsCum$date, rev(seqsCum$date)), c(cumInfPropL, rev(cumInfPropU)), col = mPal(ukPal$oth, 0.75), border=NA)
# lines(seqsCum$date, cumInfProp, lty=3, lwd=2)
# lines(ukCases$date, cumCaseProp, lty=1, lwd=2)
#
# legend("bottom", horiz=FALSE, inset=c(0,1), bty='n', xpd=TRUE, ncol=2,
# lty=c(1,3), lwd=2,
# legend = c("reported cases", "estimated infections"), title="Sequenced proportion of cumulative", cex=par("cex.lab"))
#
# # Inset start
# ymax <- 0.05
# insetStart <- as.Date("2020-02-16")
# insetEnd <- as.Date("2020-05-10")
#
# rect(insetStart, 0, insetEnd, ymax, lty=2)
#
# par(mar=c(2,2,0.5,0.5), cex.axis=0.7, cex.lab=0.8, mgp=c(3,0.75,0), fig=c(0.445, 0.875, 0.45, 0.88), new=TRUE)
#
# plotShadedAxes(xlim=c(insetStart, insetEnd), ylim=c(0, ymax), yaxs='i', side=4)
#
# polygon(c(seqsCum$date, rev(seqsCum$date)), c(cumInfPropL, rev(cumInfPropU)), col = mPal(ukPal$oth, 0.75), border=NA)
# lines(seqsCum$date, cumInfProp, lty=3, lwd=2)
# lines(ukCases$date, cumCaseProp, lty=1, lwd=2)
#
# rect(insetStart, 0, insetEnd, ymax, xpd=TRUE)
#
```
```{r travel-cases-all, fig.width=5, fig.height=3, fig.cap="Estimated number of inbound travellers to the per day (black) and estimated number of infectious cases worldwide (dashed red, 7-day rolling average). Arrows here shows from left to right the first self-isolation advice for returning travellers from China, Italy, and the start of the national lockdown."}
#
# par(mar=c(4,6,2.5,6), cex.axis=0.7, cex.lab=0.8, mgp=c(3.25,0.75,0))
# plotArrivalsInfections(arrivals, infections, location="all", startDate = startDate, endDate = endDate, cex.lab=0.8)
#
# # Mark lockdown
# points(x=travelDates$lockdown, y=0.1*1E6, pch=175, font=5, cex=1.5, xpd=TRUE, col=mPal(ukPal$eng))
#
# # Mark self-isolation advice
# points(x=travelDates$china, y=0.1*1E6, pch=175, font=5, cex=1.5, xpd=TRUE, col=mPal(countryPal$China))
# points(x=travelDates$italy, y=0.1*1E6, pch=175, font=5, cex=1.5, xpd=TRUE, col=mPal(countryPal$Italy))
```
```{r travel-cases-countries-top12, fig.width=15, fig.height=12, fig.cap="Estimated numbers of inbound travellers to the `r state` per day, and estimated number of new infections per day, for the 12 countries we estimate to have been responsible for the most importations to the (see Table 3). We estimate that these 12 countries contributed 97.6% of importations to the `r states`"}
#
# layout(matrix(c(1:12), nrow=4, byrow=TRUE))
# par(mar=c(4,6,2.5,6), cex.axis=0.8, cex.lab=1.2, cex.main=1.5, mgp=c(3.25,0.5,0))
#
# countries1 <- c("Spain",
# "France",
# "Italy",
# "US",
# "Netherlands",
# "Belgium",
# "Ireland",
# "Germany",
# "Switzerland",
# "Portugal",
# "Sweden",
# "China")
#
# # Specific countries
# for (i in 1:length(countries1)) {
# plotArrivalsInfections(arrivals, infections, location=countries1[i], startDate = startDate, endDate = endDate, cex.lab=0.8, label=LETTERS[i])
# title(capitalise(countries1[i]))
# }
```
```{r travel-cases-countries-other, fig.width=15, fig.height=12, fig.cap="Estimated numbers of inbound travellers to the `r states` per day, and estimated number of new infections per day, for a range of countries. (A-F) shows the 6 countries that made the largest contribution to importations after the 12 in the previous figure (see Table 3). Together these 6 countries contributed 1.19% of estimated importations to the `r states` (G-L) 6 countries with large epidemics that did not contribute many importations to the `r states`, either because of low numbers of inbound travellers or because their epidemics started later. These 6 countries combined contributed less than 0.5% of importations into `r states`."}
#
# layout(matrix(c(1:12), nrow=4, byrow=TRUE))
# par(mar=c(4,6,2.5,6), cex.axis=0.7, cex.lab=1.2, cex.main=1.5, mgp=c(3.25,0.5,0))
#
# countries2 <- c("Denmark", "Austria", "Romania", "Norway", "Poland", "Canada", "Iran", "Brazil", "India", "Russia", "Mexico", "South Africa") # Japan, Korea, South
#
# # Specific countries
# for (i in 1:length(countries2)) {
# plotArrivalsInfections(arrivals, infections, location=countries2[i], startDate = startDate, endDate = endDate, cex.lab=0.8, label=LETTERS[i])
# title(capitalise(countries2[i]))
# }
#
```
```{r eii-tmrca-all, fig.width=5, fig.height=3, fig.cap="Estimated importation intensity (EII) curve (black) and the histogram of lineage TMRCAs (grey). Arrows here shows from left to right the first self-isolation advice for returning travellers from China, Italy, and the start of the `r states` national lockdown."}
#tmrcaBreaks <- seq.Date(as.Date("2019-12-01"), as.Date("2020-06-26"), by="days")
# tmrcaBreaks <- seq.Date(min(clusterStatsMCC$tmrca_shifted_calendar), max(clusterStatsMCC$tmrca_calendar), by="1 days")
# tmrca_hist <- hist(clusterStatsMCC$tmrca_calendar, breaks=tmrcaBreaks, plot=FALSE, right=FALSE)
# par(mar=c(4,6,2.5,6), cex.axis=0.7, cex.lab=0.8, mgp=c(3,0.75,0))
# dateFreqDistribution(tmrca_hist$counts, tmrcaBreaks, plot.ci=FALSE, side=4, ylab="",
# #startDate = startDate, endDate = endDate, col=mPal(ukPal$oth), ymax=70)
# startDate = tmrcaBreaks[1], endDate = tmrcaBreaks[length(tmrcaBreaks)-1], col=mPal(ukPal$oth), ymax=30)
# mtext(side=4, text="Frequency of TMRCAs\n(per day)", line=3, cex=par("cex.lab"))
#
# par(new=TRUE)
# ymax <- 1200
#
# plot(1, type='n', xlim=c(startDate, endDate), ylim=c(0,1200), axes=FALSE,
# xaxs='i', yaxs='i', xlab="", ylab="")
# lines(eii$date[eii$location == "all"], eii$num_intros[eii$location == "all"], lwd=2)
# axis(2, las=1)
# mtext(side=2, text="Estimated importation intensity\n(solid line)", line=2, cex=par("cex.lab"))
#
# # Mark lockdown
# points(x=travelDates$lockdown, y=0.1*ymax, pch=175, font=5, cex=1.5, xpd=TRUE, col=mPal(ukPal$eng))
#
# # Mark self-isolation advice
# points(x=travelDates$china, y=0.1*ymax, pch=175, font=5, cex=1.5, xpd=TRUE, col=mPal(countryPal$China))
# points(x=travelDates$italy, y=0.1*ymax, pch=175, font=5, cex=1.5, xpd=TRUE, col=mPal(countryPal$Italy))
```
```{r eii-tmrca-countries, fig.width=10, fig.height=8, fig.cap="Estimated importation intensity (EII) curves for the 12 countries estimated to have contributed the most importations to the `r states` epidemic (see Table 3). Panel A shows the EII for all countries. The red arrows indicate the start of the `r states` lockdown."}
#
# layout(matrix(c(1,2,5,6,3,4,7,8), nrow=4, byrow=TRUE), heights=c(3,1,3,1))
# par(mar=c(4,6,2.5,6), cex.axis=1, cex.lab=1.2, cex.main=1.5, mgp=c(3,0.75,0))
#
# plotShadedAxes(xlim=c(startDate, endDate), ylim=c(0, 1200), axes=FALSE, label="A", line=0, yaxs='i',
# ylab = "Estimated importation intensity")
# lines(eii$date[eii$location == "all"], eii$num_intros[eii$location == "all"], lwd=2)
# abline(v=as.Date(c("2020-03-12", "2020-03-16", "2020-03-20")), lty=3, col="black")
# abline(v=as.Date("2020-03-23"), lty=1, col=ukPal$eng)
#
# #points(x=travelDates$lockdown, y=0.075*1200, pch=175, font=5, cex=1.5, xpd=TRUE, col=mPal(ukPal$eng))
#
#
# ymax <- list(B=500, C=100, D=20)
# panelCountries <- list(B=c("Spain", "France", "Italy", "Belgium"),
# C=c("Netherlands", "Ireland", "Switzerland", "US"),
# D=c("Germany", "Sweden", "Portugal", "China", "Other"))
# for (i in names(panelCountries)) {
#
#
# plotCountries <- panelCountries[[i]]
#
# plotShadedAxes(xlim=c(startDate, endDate), ylim=c(0, ymax[[i]]), axes=FALSE, label=i, line=0, yaxs='i',
# ylab = "Estimated importation intensity")
#
# for (country in plotCountries) {
# lines(eii$date[eii$location == country], eii$num_intros[eii$location == country], col=mPal(countryPal[[country]]), lwd=2)
# #points(eii$date[eii$location == country], eii$num_intros[eii$location == country], col=mPal(countryPal[[country]]), pch=20)
# }
#
# legend('bottom', horiz=FALSE, inset=c(0, 1), bty='n',
# col = sapply(plotCountries, function(x) countryPal[[x]]),
# legend=plotCountries,
# ncol=ceiling(length(plotCountries)/2), seg.len=1, lwd=2, lty=1, xpd=TRUE, cex=par("cex.axis"))
#
# # Mark lockdown
# #points(x=travelDates$lockdown, y=0.075*ymax[[i]], pch=175, font=5, cex=1.5, xpd=TRUE, col=mPal(ukPal$eng))
# abline(v=as.Date("2020-03-23"), lty=1, col=ukPal$eng)
#
# if (i == "B") {
# abline(v=as.Date("2020-02-25"), lty=3, col=countryPal$Italy)
# } else
# if (i == "D") {
# abline(v=as.Date("2020-01-28"), lty=3, col=countryPal$China)
# }
#
# }
#
#
#
# ###################################
# # NPIs and travel recommendations #
# ###################################
# par(mar=c(1,6,0,6))
#
# plot(1, type='n', ylim=c(0,8.5), xlim=c(startDate, endDate),
# xaxs='i', yaxs='i', bty='n', axes=FALSE, xlab="", ylab="", las=2)
#
# # Self isolate if symptomatic (experiencing a cough or fever symptoms)