-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTallerEbola-qmd.qmd
1101 lines (697 loc) · 30.2 KB
/
TallerEbola-qmd.qmd
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: "Estadísticas y métodos para el análisis de la respuesta a brotes."
subtitle: "Día 2"
format: revealjs
editor: visual
---
## Agenda:
1. Introducción (10min)
2. Taller (100min)
3. Discusión (30min)
## Contexto:
- La **enfermedad por el virus del ébola (EVE)** apareció en **1976** en brotes casi simultáneos en la República **Democrática del Congo (RDC)** y **Sudán del Sur**
- Entre **1979 y 1994** no se detectaron casos ni brotes
- Desde **1994 se han reconocido brotes** con una frecuencia cada vez mayor
- El mayor brote hasta la fecha tuvo lugar en **África Occidental** entre **marzo de 2014 y junio de 2016**
::: notes
**Oubreaks of EBOV**
- The **disease caused by the Ebola virus (EVE)** appeared in **1976** in almost simultaneous outbreaks in the **Democratic Republic of the Congo (DRC)** and **South Sudan.**
<!-- -->
- Between **1979** ndefinedand **1994**ndefined, no cases or outbreak
- Since 1994, **outbreaks have been recognized** with increasing frequency.
- The largest outbreak to date occurred in **West Africa** between **March 2014 and June 2016.**
:::
## Taxonomía y transmisión del virus del Ébola

::: notes
**Filovirus taxonomy and Ebola virus transmission.**
**a** Taxonomy of the genus *Ebolavirus.* Thus far, five ebolaviruses have been associated with human infections, and four of them have been identified as pathogens.
**b.**
- The natural reservoir host(s) of Ebola virus (EBOV) has (have) yet to be identified. Multiple data indicate a direct or indirect role of bats in EBOV ecology, but to date, EBOV has not been isolated from, nor its near-complete genome been detected in any wild animal.
<!-- -->
- **It is tempting to speculate that Ebola virus disease (EVD) spread is a zoonotic** because identified index cases of EVD outbreaks had been identified to be individuals that had been in contact with wild animals or had handled the carcass of a possible accidental EBOV host.
:::
## Brotes del virus del ébola

::: notes
**Oubreaks of EBOV**
- **Between 1979 and 1994 no cases or outbreaks were detected**. However, since that time, outbreaks have been recognized with increasing frequency.
<!-- -->
- The largest outbreak to date took place in **West AFrica between March 2014 and June 2016**, affecting primarily Guinea, Liberia and Sierra Leone. **Over 28000 cases were recorded.**
:::
## Curso clínico
::: columns
::: {.column width="70%"}

:::
::: {.column width="30%"}
 <font size="5">
Alta letalidad:
De 5986 casos a nivel mundial fuera del brote de África Occidental han muerto 3963 (CFR 66%)
</font>
:::
:::
::: notes
**High lethatility:**
From 5986 global cases besides the West Africa outbreak cases, 3963 died (CFR 66%)
:::
# Instrucciones del taller
## Introducción
- Esta práctica simula **la evaluación temprana** y la **reconstrucción** de un **brote** de enfermedad por el **virus del Ébola (EVE).**
<font size="6">
- Conceptos básicos a desarrollar:
- **Probabilidad de muerte por caso reportado** (CFR - *Case Fatality **Ratio***)
- **Curvas epidémicas** (e.g. Incidencia de casos - $I_t$)
- **Tiempo de duplicación** y **tasa de crecimiento**
- **Intervalo Serial** (SI - *Serial Inverval*)
- **Número reproductivo instantáneo** ($R_t$)
</font>
::: notes
This practice simulates the early assessment and reconstruction of an outbreak of Ebola virus disease (EVD)
- Case Fatality Ratio (CFR)
- Epidemic curves (e.g., Case incidence)
- Doubling time and growth rate
- Serial Interval (SI)
- Instantaneous Reproductive Number
:::
## Objetivos
<font size="6">
- Estimar la **probabilidad de muerte por caso reportado (CFR)**
- Calcular, visualizar la **incidencia de casos** ($I_t$)
- Identificar parámetros descriptivos de la transmisión de una **enfermedad infecciosa (humano-humano)**.
- Estimar e interpretar la **tasa de crecimiento** y el **tiempo de duplicación** de la epidemia.
- Estimar e interpretar el **número de reproducción instantáneo** de la epidemia ($R_t$)
</font>
::: notes
- Estimate the CFR.
- Calculate and visualize the incidence of cases ($I_t$)
- Identify descriptive parameters of the transmission of an infectious disease (human-to-human).
- Estimate and interpret the growth rate and doubling time of the epidemic.
- Estimate and interpret the instantaneous reproduction number of the epidemic ($R_t$).
:::
# Situación a analizar
::: notes
<font size="15">**Situation to analyse** </font>
:::
## Hay un nuevo brote de EVE en un país ficticio de África occidental
<br>
- Se ha notificado un nuevo brote de EVE en un país ficticio de África occidental.
<br>
- El Ministerio de Salud se encarga de coordinar la respuesta al brote, y lo ha contratado a usted como consultor en análisis epidémico para informar la respuesta en tiempo real.
::: notes
**There is a new outbreak of EVD in a fictional country in West Africa.\
**
- A new outbreak of EVD has been reported in a fictional country in West Africa
- The Ministry of Health is responsible for coordinating the response to the outbreak and has hired you as an epidemiological analysis consultant to provide real-time information for the response
:::
## Al inicio del brote
::: columns
::: {.column width="70%"}

:::
::: {.column width="30%"}
Análisis rápido de la situación para orientar la toma de decisiones
<br><br>
**¿Qué preguntas surgen inmediatamente?**
:::
:::
::: notes
Quick analysis of the situation to guide decision-making<br>
**What questions arise immediately?**
:::
## Al inicio del brote
Se requieren datos para **planear la respuesta a:**
- ¿Qué tan rápido crece una epidemia?
- ¿Cuál es el riesgo de muerte?
- ¿Cuántos casos puedo esperar en los próximos días?
- ¿Cuánta capacidad hospitalaria y del sistema de salud requeriremos en los próximos días?
<center>
### ¿Qué datos necesito?
</center>
::: notes
**Data is needed to plan the response to:**
- How quickly is an epidemic spreading?
- What is the risk of death?
- How many cases can I expect in the coming days?
- How much hospital and healthcare system capacity will we need in the coming days?
<center>**What data do you need?**</center>
:::
## Datos disponibles usuales en epidemias nuevas
- Fecha de inicio de síntomas: *date of onset*
- Fecha de exposición/infección: *infection date*
- Fecha del desenlace (recuperación, muerte): *outcome date*
- Datos generales del individuo: edad, género, ocupación, etc
- Datos de brotes anteriores
::: notes
**Commonly available data in new epidemics:**
- Date of onset of symptoms: date of onset
- Date of exposure/infection: infection date
- Outcome date (recovery, death): outcome date
- General individual data: age, gender, occupation, etc.
- Data from previous outbreaks
:::
## Metodología del taller
La práctica está divida en 6 secciones. En cada una de ellas vamos a tener:
1. Explicaciones de los conceptos a trabajar
2. Espacio de lectura y ejecución del código
3. Espacios de reflexión y discusión
::: notes
The practice is divided into 6 sections. In each of them, we will:
1. Get explanations of the concepts to be worked on.
2. Read guide and run the code.
3. Discuss the results.
:::
# Pasemos a R 👩💻👨💻
## Instrucciones:
<br>
### Desarrolle la sección *1. Preparación*
```{r}
countdown::countdown(minutes = 5, seconds = 00, left=0, right=0)
```
## Cargue las librerías necesarias:
<br>
```{r echo=TRUE, message=FALSE, warning=FALSE,comment=""}
library(tidyverse) # contiene ggplot2, dplyr, tidyr, readr, purrr, tibble
library(readxl) # para leer archivos Excel
library(binom) # para intervalos de confianza binomiales
library(knitr) # para crear tablas bonitas con kable()
library(incidence) # para calcular incidencia y ajustar modelos
library(EpiEstim) # para estimar R(t)
```
## Cargue las bases de datos:
<br>
```{r echo=TRUE, message=FALSE, warning=FALSE,comment=""}
directorio_casos <- read_rds("data/directorio_casos.rds")
contactos <- read_excel("data/contactos_20140701.xlsx", na = c("", "NA"))
```
## Estructura de los datos:
<font size="6">
<div>
```{r, echo=TRUE}
glimpse(contactos)
```
```{r, echo=TRUE}
glimpse(directorio_casos)
```
</div>
</font>
<font size="5">
- ¿Son los datos y el formato similares a bases de datos de casos que ha visto en el pasado?
- ¿Qué otra información le gustaría recopilar?
</font>
::: notes
- Are the data and format similar to case databases you have seen in the past?
- What other information would you like to gather?
:::
## Probabilidad de muerte en los casos reportados (CFR)
**CFR: *Case Fatality Ratio***

## **No confundir CFR con IFR**
- **CFR:** Es la **probabilidad de muerte** a causa de la infección para los **casos reportados**:
$\rightarrow$ <font size="5"> El CFR se puede calcular con los datos de vigilancia epidemiológica </font>
$$
\text{CFR} = \frac{\text{# de muertes confirmadas}}{\text{# casos con desenlace conocido}}
$$
- **IFR:** Es la **probabilidad de muerte** a causa de la infección teniendo en cuenta **infecciones detectadas y no detectadas**
$\rightarrow$ <font size="5"> IFR sólo se puede calcular con datos de vigilancia epidemiológica + información adicional como estudios prevalencia </font>
::: notes
- CFR: It can be calculated from epidemic surveillance data as:
$$
\text{CFR} = \frac{\text{confirmed deaths}}{\text{cases with known outcome}}
$$
- IFR: Needs additional information to be computed, such as prevalence studies.
:::
## Instrucciones
<br>
### Lea y desarrolle la sección *2. CFR*
<br>
```{r, echo=FALSE}
countdown::countdown(minutes = 5, seconds = 00, left=0, right=0)
```
## Tasa de fatalidad de casos (CFR)
<font size="5">
::: columns
::: {.column width="55%"}
```{r echo=TRUE, message=FALSE, warning=FALSE,comment=""}
table(directorio_casos$desenlace, useNA = "ifany")
```
:::
::: {.column width="45%"}
¿Cómo calcularía el CFR a partir de esto?
Piense en qué hacer con los casos cuyo resultado es \`NA\`
:::
:::
</font>
::: notes
How would you calculate the CFR from this information? <br>\
Consider what to do with cases whose result is 'NA'
:::
## Tasa de fatalidad de casos (CFR)
<font size="5">
::: columns
::: {.column width="55%"}
```{r echo=TRUE, message=FALSE, warning=FALSE,comment=""}
table(directorio_casos$desenlace, useNA = "ifany")
```
:::
::: {.column width="45%"}
¿Cómo calcularía el CFR a partir de esto?
Piense en qué hacer con los casos cuyo resultado es \`NA\`
:::
:::
::: columns
::: {.column width="65%"}
```{r echo=TRUE, message=FALSE, warning=FALSE,comment="", results=FALSE}
numero_muertes <- sum(directorio_casos$desenlace %in% "Muerte")
numero_casos_resultado_conocido <- sum(directorio_casos$desenlace %in% c("Muerte", "Recuperacion"))
CFR <- numero_muertes / numero_casos_resultado_conocido
CFR
```
:::
::: {.column width="35%"}
Cálculo de CFR
:::
:::
::: columns
::: {.column width="65%"}
```{r echo=FALSE, message=FALSE, warning=FALSE,comment=""}
CFR_con_CI <- binom.confint(numero_muertes, numero_casos_resultado_conocido, method = "exact") %>%
kable(caption = "**CFR con intervalos de confianza**")
CFR_con_CI
```
:::
::: {.column width="35%"}
¿Cómo interpreta estos resultados?
:::
:::
</font>
::: notes
<center>**How would you interpret these results?**</center>
:::
## Incidencia
<font size="6">
**Número de casos nuevos en un período de tiempo determinado**
- Se basa en las fechas, por lo general, de inicio de síntomas.
- Se afecta por los **rezagos de reporte** (e.g. quienes iniciaron síntomas ayer sólo van a ser reportados algunos días después)
</font>

::: notes
**Incidence:**
- **Number of new cases in a specific time period.**
- It is based on dates, usually the **onset of symptoms**.
- It is affected by **reporting delays** (e.g., those who started symptoms yesterday will only be reported several days later).
:::
## Incidencia
<font size="6">
- El primer paso del análisis es descriptivo: **queremos dibujar una epicurva o curva epidémica**. Esto permite visualizar la incidencia a lo largo del tiempo por fecha de inicio de los síntomas.
- La primera pregunta que queremos responder es: **¿qué tan grave es la situación?**
</font>
### **Para ello, ¡miraremos las curvas de incidencia!**
::: notes
The first step of the analysis is descriptive: we want to draw an epicurve or epidemic curve. This allows visualizing the incidence over time by the date of symptom onset.
The first question we want to answer is: How severe is the situation?\
<center>
**To do that, we will look at the incidence curves!**
</center>
:::
## <font size=14>Curva epidémica con modelo log lineal</font>

<font size="5.5">
$$ \left. \begin{matrix} y:\text{número de casos incidentes} \\ r:\text{tasa de crecimiento} \\ \beta_0: \text{intercepto} \end{matrix} \right\} \log(y) = \beta_0 + rt + \epsilon \Rightarrow \hat{y} = \exp^{rt+\beta_0} $$
</font>
<center>
<font size="6">
[**¡La tasa de crecimiento es la pendiente de la recta en escala logarítmica!**]{.underline}
</font>
</center>
::: notes
<center>**The growth rate** corresponds to the **slope of the line in log-scale**</center>
:::
## Tiempo de duplicación
::: columns
::: {.column width="60%"}
<font size="5"> [{alt="https://www.reconlearn.org/post/outbreakstatsprimer.html"}](#0)
$$ \left. \begin{matrix} y:\text{número de casos incidentes} \\ r:\text{tasa de crecimiento} \\ \beta_0: \text{intercepto} \end{matrix} \right\} \hat{y} = \exp^{rt + \beta_0} $$
</font>
:::
::: {.column width="40%"}
$T$ es el tiempo que le toma a la curva epidémica para **duplicarse:**
$$ \hat{y}_2 = 2\hat{y}_1 \\ 2 = \frac{\hat{y}_2}{\hat{y}_1} = \frac{\exp^{rt_2 + \beta_0}}{\exp^{rt_1 + \beta_0}} \\ 2 = \exp^{r(t_2-t_1)} = \exp^{rT}\\ \Rightarrow T = \frac{\log(2)}{r} $$
:::
:::
::: notes
$T$ is the time that the time epidemic curve takes to double its value
:::
## Instrucciones
### <br>
### Lea y desarrolle las secciones:
### *3. Incidencia*
### *4. Tasa de crecimiento*
<br>
```{r}
countdown::countdown(minutes = 15, seconds = 00)
```
## <font size="9">Incidencia diaria según fecha de inicio de síntomas</font>
```{r, eval=FALSE, echo=TRUE}
incidencia_diaria <- incidence(directorio_casos$fecha_inicio_sintomas)
incidencia_diaria
```
::: columns
::: {.column width="30%"}
```{r}
incidencia_diaria <- incidence(directorio_casos$fecha_inicio_sintomas)
incidencia_diaria
```
:::
::: {.column width="70%"}
```{r, echo=FALSE}
plot(incidencia_diaria, border = "black")
```
```{r, echo=TRUE, eval=FALSE}
plot(incidencia_diaria, border = "black")
```
:::
:::
<center>**¿Qué observa?**</center>
## Pregunta {visibility="hidden"}
### ¿Cuál es la mejor clasificación de la epidemia a partir de la información de la curva epidémica?
A. Fuente común puntual
B. Fuente común continua
C. Fuente común intermitente
D. Propagada (persona a persona)
## Pregunta {visibility="hidden"}
### Su jefe le pregunta, ¿en qué fecha inició síntomas el primer caso (caso índice)?
Usted diría que fue...
```{r echo=FALSE, message=FALSE, warning=FALSE,comment=""}
plot(incidencia_diaria, border = "black")
```
## Incidencia de casos semanal
<font size="6">
- **Puede ser difícil interpretar las tendencias al observar la incidencia diaria**
- Calcule la incidencia semanal:
```{r, eval=TRUE, echo=TRUE}
incidencia_semanal <- incidence(directorio_casos$fecha_inicio_sintomas,
interval = 7,
last_date = max(directorio_casos$fecha_de_hospitalizacion,
na.rm = TRUE))
incidencia_semanal
```
</font>
::: notes
**It can be hard to identify trends observing daily incidence**
<br>
Compute the **weekly incidence** instead
:::
## Incidencia de casos semanal
- Grafique la incidencia semanal:
```{r, eval=TRUE, echo=TRUE}
plot(incidencia_semanal, border = "black")
```
<center>**¿Qué opina de esta nueva gráfica?**</center>
::: notes
**What do you think about these new plot?**
:::
## Estimación de la tasa de crecimiento mediante un modelo log-lineal
- El modelo *log-lineal* es uno de los **modelos de incidencia más simple**
- Es un **modelo de regresión lineal implementado sobre incidencias transformadas logarítmicamente**
- Trabajaremos con **incidencia semanal**, para evitar tener problemas con valores de incidencia cero.
::: notes
**Estimation of the growth rate through a log-linear model:**
- The log-linear model is one of the simplest incidence models.
- It is a linear regression model implemented on logarithmically transformed incidences.
- We will work with weekly incidence to avoid issues with zero incidence values.
:::
## <font size=14>Curva epidémica con modelo log lineal</font>
::: columns
::: {.column width="30%"}
<font size="5">
- Grafique la incidencia transformada logarítmicamente
- ¿Qué le dice esta gráfica sobre la epidemia?
</font>

:::
::: {.column width="70%"}
```{r echo=TRUE, message=FALSE, warning=FALSE,comment=""}
incidencia_semanal_df <- as.data.frame(incidencia_semanal)
ggplot(incidencia_semanal_df) +
geom_point(aes(x = dates, y = log(counts))) +
scale_x_date(date_breaks = "1 week", date_labels = "%d-%b") +
xlab("Fecha") +
ylab("Incidencia semanal logarítmica") +
theme_minimal()
```
:::
:::
::: notes
**What does this plot tells you about the epidemic?**
**Respuesta:** Se observa un incremento exponencial de casos semanales hasta la semana 23 (mediados de junio) / An exponential growth can be observed up to week 23
:::
## <font size=14>Curva epidémica con modelo log lineal</font>
#### Ajuste un modelo log-lineal a los datos de incidencia
```{r echo=TRUE, message=FALSE, warning=FALSE,comment=""}
ajuste_modelo <- incidence::fit(incidencia_semanal)
ajuste_modelo
```
<center>**¿Qué le dicen estos resultados?**</center>
::: notes
<center>**What do you think about the results?**</center>
:::
## <font size=14>Curva epidémica con modelo log lineal</font>
```{r echo=TRUE, message=FALSE, warning=FALSE,comment=""}
plot(incidencia_semanal, fit = ajuste_modelo)
```
<center><font size="6">Mirando la gráfica y el ajuste, **¿cree que este es un ajuste razonable?**</font></center>
::: notes
<center>**Is this a reasonable fit?**</center>
**Respuesta:** Lo observado se ajundefinedndefinedsta a un crecimiento exponencial, sin embargo, no es un ajuste razonable debido a que se continuan incuyendo las últimas semanas, las cuales presentan datos atípicos que pueden sesgar la gráfica (rezago) / The observed data fits an exponential growth; however, it is not a reasonable fit because the last few weeks are still being included, which have atypical data that can bias the plot (delay).
:::
## <font size=12>Curva epidémica con modelo log lineal</font>
#### ¿Cuántas semanas debe descartar al final de la epicurva?
- Trunque la incidencia semanal según las semanas descartadas
```{r echo=TRUE, message=FALSE, warning=FALSE,comment="", results=FALSE}
semanas_a_descartar <- 2
fecha_minima <- min(incidencia_diaria$dates)
fecha_maxima <- max(incidencia_diaria$dates) - semanas_a_descartar * 7
# Para truncar la incidencia semanal
incidencia_semanal_truncada <- subset(incidencia_semanal,
from = fecha_minima,
to = fecha_maxima) # descarte las últimas semanas de datos
# Incidencia diaria truncada. No la usamos para la regresión lineal pero se puede usar más adelante
incidencia_diaria_truncada <- subset(incidencia_diaria,
from = fecha_minima,
to = fecha_maxima) # eliminamos las últimas dos semanas de datos
```
::: notes
**How many weeks should we discard from the epicurve?**
:::
## <font size=12>Curva epidémica con modelo log lineal</font>
<font size="6">
Vuelva a ajustar y a graficar el modelo logarítmico lineal, pero utilizando los datos truncados.
```{r, echo=TRUE, eval=FALSE}
ajuste_modelo_semanal <- incidence::fit(incidencia_semanal_truncada)
ajuste_modelo_semanal
```
::: columns
::: {.column width="35%"}
```{r echo=FALSE, message=FALSE, warning=FALSE,comment=""}
ajuste_modelo_semanal <- incidence::fit(incidencia_semanal_truncada)
ajuste_modelo_semanal
```
:::
::: {.column width="65%"}
```{r echo=FALSE, message=FALSE, warning=FALSE,comment=""}
plot(incidencia_semanal_truncada, fit = ajuste_modelo_semanal)
```
```{r echo=TRUE, eval=FALSE}
plot(incidencia_semanal_truncada, fit = ajuste_modelo_semanal)
```
:::
:::
<center>**¿Cree que este es un ajuste más razonable comparado con el anterior?**</center>
</font>
::: notes
**Is this fit more reasonable in comparison with the previous one?**
:::
## <font size=14>Curva epidémica con modelo log lineal</font>
#### Observe las estadísticas resumidas de su ajuste:
```{r echo=TRUE, message=FALSE, warning=FALSE,comment=""}
summary(ajuste_modelo_semanal$model)
```
**¿El modelo se ajusta bien a los datos?**
::: notes
**How good is this fit?**
:::
## <font size=14>Curva epidémica con modelo log lineal</font>
#### Estimacion de la tasa de crecimiento
¿Cuál es la tasa de crecimiento estimada de la epidemia?, ¿Cómo lo interpreta?
```{r echo=TRUE, message=FALSE, warning=FALSE,comment=""}
# Estimación de la tasa de crecimiento diaria
tasa_crecimiento_diaria <- ajuste_modelo_semanal$info$r
cat("La tasa de crecimiento diaria es:", tasa_crecimiento_diaria, "\n")
# Intervalo de confianza de la tasa de crecimiento diaria
tasa_crecimiento_IC <- ajuste_modelo_semanal$info$r.conf
cat("Intervalo de confianza de la tasa de crecimiento diaria (95%):", tasa_crecimiento_IC, "\n")
```
## Tiempo de duplicación
¿Cuál es el **tiempo de duplicación** estimado de la epidemia?,
¿Cómo lo interpreta?
::: notes
What's the value of the estimated **duplication time** of the epidemic?<br>
How do you interpret it?
:::
## Tiempo de duplicación
¿Cuál es el **tiempo de duplicación** estimado de la epidemia?,
¿Cómo lo interpreta?
```{r, echo=TRUE}
# Estimación del tiempo de duplicación en días
tiempo_duplicacion_dias <- ajuste_modelo_semanal$info$doubling
cat("El tiempo de duplicación de la epidemia en días es:", tiempo_duplicacion_dias, "\n")
# Intervalo de confianza del tiempo de duplicación
tiempo_duplicacion_IC <- ajuste_modelo_semanal$info$doubling.conf
cat("Intervalo de confianza del tiempo de duplicación (95%):", tiempo_duplicacion_IC, "\n")
```
::: notes
What's the value of the estimated **duplication time** of the epidemic?<br>
How do you interpret it?
:::
## Intervalo serial (SI):
El ***intervalo serial*** (SI - *Serial Interval*) es el tiempo entre la fecha de inicio de síntomas entre casos primarios y secundarios
::: columns
::: {.column width="50%"}
{alt="https://www.reconlearn.org/slides/outbreak-statistics/outbreak-statistics#16"}
:::
::: {.column width="50%"}

:::
:::
<font size="5">
<https://www.reconlearn.org/slides/outbreak-statistics/outbreak-statistics#16>
</font>
::: notes
[***Serial interval explanation***]{.underline}
:::
## Intervalo Serial (SI)

::: notes
[***Serial interval explanation***]{.underline}
:::
## Modelo de proceso de ramificación
- ¿Qué es el **número de reproducción** $R$ y para qué sirve?
- En las primeras etapas de un brote, y asumiendo una gran población sin inmunidad, esta cantidad corresponde al **número de reproducción básico** $R(0)$.
- Cuando la suposición de que $R$ es constante no es sostenible, **una alternativa es estimar la transmisibilidad variable en el tiempo utilizando el número de reproducción instantánea** $R_t$**.**
::: notes
**Branching process model:**
- What is the reproduction number R and what is it used for?
- In the early stages of an outbreak, assuming a large population without immunity, this quantity corresponds to the basic reproduction number R(0).
- When the assumption that R is constant is not sustainable, an alternative is to estimate time-varying transmissibility using the instantaneous reproduction number Rt.
:::
## Modelo de proceso de ramificación
::: columns
::: {.column width="40%"}

:::
::: {.column width="60%"}
<font size="5">
- El número reproductivo cuantifica el potencial de una enfermedad de propagarse en una población.
- Se puede estimar como el número promedio the casos secundarios producido por un solo caso en una población completamente susceptible ($R_0$)
- Para evaluar los cambios en la propagación a lo largo del tiempo, usamos el número reproductivo instantáneo ($R_t$)
</font>
:::
:::
<font size="3"><https://mrc-ide.github.io/EpiEstim/articles/full_EpiEstim_vignette.html></font>
::: notes
The Reproductive Number $R$ quantifies the potential for a disease to spread within a population
It represents the average number of secondary infections produced by a single infected individual in a completely susceptible population $R_0$
When considering spread over time we use $R_t$ instead
:::
## Modelo de Poisson para la incidencia
- El promedio e la incidencia en el tiempo $t$ se puede estimar por medio de la ecuación de renovación:
$$ \text{E}[I_t] \approx R_t \sum_{s=1}^{t-1} I_{s} w_{t-s} $$
En donde $R_t$ representa el número de reproducción efectiyo y $w$ la distribución del intervalo serial discreta.
- Si la incidencia en el tiempo $t$ es conocida, esta ecuación se puede usar para estimar $R_t$.
::: notes
The average incidence at time $t$ can be estimated according to the renewal equation.
If $I_t$ is known, the renewal equation can be used to estimate $R_t$
:::
## Modelo de Poisson para la incidencia
- El paquete de R `{EpiEstim}` estima $R_t$ para ventanas de tiempo personalizadas **utilizando la distribución de probabilidad de Poisson** \[Cori et al. 2013\]
$$
I_t \sim Poisson\left(R_{t} \sum_{s=1}^{t-1} I_{s} w_{t-s} \right)
$$
::: notes
- The {EpiEstim} package uses a Poisson distribution to estimate $R_t$ from given incidence data.
- Personlized time windows can be specified
:::
## Modelo de Poisson para la incidencia
:::: {.columns}
::: {.column width="50%"}
```{r, eval=TRUE, echo=FALSE}
eg_data <- data.frame(
time = c(1, 2, 3, 4),
si = c(0.2, 0.4, 0.3, 0.1),