-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvpm_eBird.Rmd
5409 lines (4479 loc) · 218 KB
/
vpm_eBird.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: "**Supporting Information**"
subtitle: "Monitoring population extinction risk with community science data"
author: "Authors...(removed for peer review in Journal of Applied Ecology)"
date: "`r format(Sys.time(), '%d %B %Y')`"
output:
pdf_document:
toc: yes
number_sections: true
latex_engine: xelatex
extra_dependencies: ["flafter","caption"]
header-includes:
- \usepackage{placeins}
- \usepackage{caption}
- \renewcommand{\thefigure}{SI-\arabic{figure}}
editor_options:
chunk_output_type: console
---
\clearpage
# Read me (begin here)
This file is the code used for a paper \textit{submitted} to \textbf{\textit{Journal of Applied Ecology}}. We hope this code serve as a practical tutorial and is applied for different users in an intuitive way. Our aim is to describe and test a quantitative approach that fits continuous state-space models iteratively to a time series of community science data ([eBird](https://ebird.org/home)), with teh ultimate goal of estimating local persistence probability through time. We evaluated model accuracy by comparing estimates and trends from eBird with those from the endangered Everglade’s snail kite long-term standardized monitoring project. We also perform a sensitivity analysis to assess how robust the persistence estimates are to a reduction in the number of eBird observations available. We used the risk-based viable population monitoring (VPM) framework ([Staples *et al.*, 2005](https://conbio.onlinelibrary.wiley.com/doi/full/10.1111/j.1523-1739.2005.00283.x)), fitting continuous state-space population models under density-independent dynamics ([Humbert *et al.*, 2009](https://nsojournals.onlinelibrary.wiley.com/doi/pdfdirect/10.1111/j.1600-0706.2009.17839.x)).
This population dynamic can be (and we provide the code for) extended to density-dependent dynamics ([Dennis & Ponciano, 2014](https://esajournals.onlinelibrary.wiley.com/doi/abs/10.1890/13-1486.1)). We focused on the recent (since 2018) expanded population of Everglade's snail kite ([*Rostrhamus sociabilis plumbeus*](https://birdsoftheworld.org/bow/species/snakit/cur/introduction)) in north-central Florida, US, a species with standardized monitoring efforts that provide benchmark population trends for comparison (see Section 2.1 in the main text).
Two continuous versions of the discrete-time equal sampling Gompertz State-Space model can be fitted with our quantitative approach:
1. The density-dependent Ornstein-Uhlenbeck State-Space model (OUSS)
2. The density-independent Exponential Growth State Space model (EGSS)
We present the risk-based viable population monitoring framework (see
[Staples *et al.*, 2005](https://conbio.onlinelibrary.wiley.com/doi/full/10.1111/j.1523-1739.2005.00283.x)),
estimating the probability of local persistence $\phi$;
1-probability of crashing abundance below a specified threshold given a simulation window in near future.
The statistical properties for our proceedings are based on [Dennis *et al.* (1991)](https://esajournals.onlinelibrary.wiley.com/doi/10.2307/1943004),
[Dennis *et al.* (2006)](https://esajournals.onlinelibrary.wiley.com/doi/10.1890/0012-9615%282006%2976%5B323%3Aeddpna%5D2.0.co%3B2),
[Dennis & Ponciano, (2014)](https://esajournals.onlinelibrary.wiley.com/doi/abs/10.1890/13-1486.1),
[Humbert *et al.*, (2009)](https://nsojournals.onlinelibrary.wiley.com/doi/pdfdirect/10.1111/j.1600-0706.2009.17839.x),
and reference therein. We adjusted the functions and code published as
supplementary information in [Humbert *et al.*, (2009)](https://nsojournals.onlinelibrary.wiley.com/doi/pdfdirect/10.1111/j.1600-0706.2009.17839.x)
and [Dennis & Ponciano, (2014)](https://esajournals.onlinelibrary.wiley.com/doi/abs/10.1890/13-1486.1).
Thus, users should first run all the packages and functions in the next
section. Then, access eBird data and organize it as time series in spatiotemporal subsamples and estimate local persistence - monitoring population risk with community science data.
![*Figure 1 in Main text* The risk-based viable population monitoring (VPM) framework for estimating local persistence probabilities over time. Observed counts (blue points) inform a population model fitted from $t_{1}$ to $t_{i}$ (black lines). Using estimated parameters (e.g., growth rate, environmental or observation noise), stochastic trajectories are simulated beyond vertical dotted line ($t_{i}$) within moving windows of S years (gray ribbons, lines, and shapes). These simulations estimate the probability of counts falling below a quasi-extinction threshold (dashed line, red crosses); the complement is the local persistence probability. The VPM iteratively updates these estimates with new data. Panels (a-f) show monitoring progress: abundance from standardized monitoring (SM; left), from community science data (CS; center) and persistence probability (right), with simulation windows increasing in tone (dark to light) and time advancing downward. Probabilities are calculated for window lengths $S_{3}$ (3 years, circles), $S_{5}$ (5 years, squares), and $S_{10}$ (10 years, diamonds) across each time that persistence is estimated, $i=1$ (a) to $i=6$ (f). Simulated trajectories change between iterations, reflecting changes in persistence estimates before abundance drops below the threshold. Lower count estimation in CS resembles the dynamic of the population, resulting in similar persistence estimate (filled vs hollowed points). Extending simulations enhances the estimate robustness.](results/Figure1.png){width=60%}
\clearpage
# Packages, models, and functions
## Packages required
```{r package-loading, message=FALSE, warning=FALSE}
#R functions and datasets to support "Modern Applied Statistics with S",
#a book from W.N. Venables and B.D. Ripley
library(MASS);
#Kernel Density Estimation
library(kde1d)
#To conduct eBird data filtering and manipulation (see Strimas et al. 2018 and 2023)
library(auk);
#To data management and visualization - sevent packages in one
library(tidyverse)
#To conduct Spatiotemporal Subsampling
library(dggridR)
#Simple features to encode spatial vector data
library(sf)
#load maps
library(maps);
#composite figure
library(gridExtra);
#equation in figure with panels (`ggplot2::ggplot()`; `facet_wrap()`)
library(ggpubr);
```
## Special cases of the Gompertz state-space population dynamics model
We provide the rationale to use two special cases (continuous, diffusion process) models of the discrete-time Gompertz State Space model ([Dennis *et al.*, 2006](https://esajournals.onlinelibrary.wiley.com/doi/10.1890/0012-9615%282006%2976%5B323%3Aeddpna%5D2.0.co%3B2)); the density-dependent version that we heretofore denotes as the GSS model and the density-independent model (EGSS) from [Humbert *et al.* (2009)](https://nsojournals.onlinelibrary.wiley.com/doi/pdfdirect/10.1111/j.1600-0706.2009.17839.x).
Let $N_t$ be the latent unobserved abundance population at time $t$, the ecological process in the GSS model. This abundance is defined as $N_t = N_{t-1} ~e^{a+b*\ln{N_{t-1}} + E_t}$), where $a$ and $b$ are constants representing population growth rate and strength of density dependence, respectively, and $E_t$ is the environmental stochasticity or process noise, $E_t\sim \text{Normal}(0,\sigma^2)$ ([Dennis *et al.*, 2006](https://esajournals.onlinelibrary.wiley.com/doi/10.1890/0012-9615%282006%2976%5B323%3Aeddpna%5D2.0.co%3B2)). On the logarithmic scale ($X_t = \ln{N_t}$), the GSS becomes linear and follows an autoregressive model of order 1: $X_t = X_{t-1} + a + b*X_{t-1} + E_t$, which can be simplify as $X_t = a + c*X_{t-1} + E_t$, where $c = b+1$ is a constant that represents the strength of density dependence ([Dennis *et al.*, 2006](https://esajournals.onlinelibrary.wiley.com/doi/10.1890/0012-9615%282006%2976%5B323%3Aeddpna%5D2.0.co%3B2); [Ponciano *et al.*, 2018](https://doi.org/10.1016/j.tpb.2018.04.002); [Reddingius, 1971 in Acta Biotheor, 20, 1-208](https://scholar.google.com/scholar?hl=en&as_sdt=0%2C10&q=Gambling+for+existence.+A+discussion+of+some+theoretical+problems+in+animal+population+ecology&btnG=)). If $b=0$ ($c=1$), the GSS reduces to the density-independent model fully treated in state-space model form by [Humbert *et al.* (2009)](https://nsojournals.onlinelibrary.wiley.com/doi/pdfdirect/10.1111/j.1600-0706.2009.17839.x).
The discrete GSS population model has four unknown parameters: $a$, $c$, $\sigma^2$, and $\tau^2$ ([Dennis *et al.*, 2006](https://esajournals.onlinelibrary.wiley.com/doi/10.1890/0012-9615%282006%2976%5B323%3Aeddpna%5D2.0.co%3B2)). The transition probability distribution of this logarithmic abundance model is normal, with mean and variance changing as a function of time. The parameter $c$ represents the strength of density-dependence ([Ponciano *et al.*, 2018](https://doi.org/10.1016/j.tpb.2018.04.002)). If the strength of density dependence ($c$) ranges $-1<c<1$, the long-run probability distribution of log-abundance approaches a time-independent normal stationary distribution ($X_t→X_∞$), with mean $\frac{a}{1-c}$ and variance $\frac{\sigma^2}{1-c^2}$. Thus, instead of approaching a single population abundance value, or a deterministic carrying capacity, the density-dependent stochastic GSS model approaches a stationary distribution, a cloud of points around which the population fluctuates ([Dennis & Taper, 1994](https://doi.org/10.2307/2937041); [Wolda, 1989](https://doi.org/10.1007/BF00377095)). The mean of this distribution, $\frac{a}{1-c}$, represents a long-term expected population size ([Dennis *et al.*, 2006](https://esajournals.onlinelibrary.wiley.com/doi/10.1890/0012-9615%282006%2976%5B323%3Aeddpna%5D2.0.co%3B2)). As mentioned above, the density-independent stochastic exponential growth model of [Dennis *et al.* (1991)](https://esajournals.onlinelibrary.wiley.com/doi/10.2307/1943004) is attained when $b=0$ ($c=1$); the state equation then becomes $N_t = N_{t-1} ~e^{a + E_t}$ ([Dennis *et al.*, 1991](https://esajournals.onlinelibrary.wiley.com/doi/10.2307/1943004)). The state-space model formulation for these two models is completed with the specification of the sampling (observation) error model. Following [Dennis *et al.* (2006)](https://esajournals.onlinelibrary.wiley.com/doi/10.1890/0012-9615%282006%2976%5B323%3Aeddpna%5D2.0.co%3B2), we assumed that the log-observation at time $t$, $Y_t$, is a sample from the (stochastic) process model according to the equation $Y_t = X_t + F_t$; where the $F_t$ are independent and identically distributed normal random variables, i.e. $F_t \sim \text{Normal}(0,\tau^2)$. During transition growth dynamics, the EGSS model may more accurately represents population trends (but see [Dennis & Ponciano, 2014](https://esajournals.onlinelibrary.wiley.com/doi/abs/10.1890/13-1486.1) for details in non-stationary continuous GSS).
Fitting both state-space models when equally sampled population abundances are available is straightforward ([Dennis *et al.*, 2006](https://esajournals.onlinelibrary.wiley.com/doi/10.1890/0012-9615%282006%2976%5B323%3Aeddpna%5D2.0.co%3B2)), yet unequally sampled populations over time tend to be the norm rather than the exception in ecology ([Dennis et al., 2010](https://doi.org/10.1890/08-1095.1)). By exploiting the connection of the EGSS and GSS models to diffusion processes, here we show how to connect these models to unequally sampled data to later extend inferences to the dynamic of local persistence (as mathematical complement of local quasi-extinction risk). Indeed, the logarithmic transformation in the GSS discrete model opens the opportunity for estimating the infinitesimal mean and variance under diffusion processes for unequal sampling; Brownian motion diffusion in the EGSS model ([Humbert *et al.*, 2009](https://nsojournals.onlinelibrary.wiley.com/doi/pdfdirect/10.1111/j.1600-0706.2009.17839.x)) and Ornstein-Uhlenbeck diffusion in the GSS model ([Dennis & Ponciano, 2014](https://esajournals.onlinelibrary.wiley.com/doi/abs/10.1890/13-1486.1)). Specific statistical properties can be found in the following section with the specific functions per model.
## Functions
The following functions are required to manipulate data and fit the
models correctly.
### Miscelaneous functions
Function to convert time observation to hours since midnight in eBird
data
```{r load-time_to_decimal}
time_to_decimal <- function(x) {
x <- hms(x, quiet = TRUE)
hour(x) + minute(x) / 60 + second(x) / 3600
}
```
Multivariate normal random number generator - State Space models
```{r load-randmvn}
randmvn <- function(n, mu.vec, cov.mat){
# Save the length of the mean vector of the multivariate normal distribution to sample
p <- length(mu.vec);
# The Cholesky decomposition
#(factorization of a real symmetric positive-definite sqr matriz)
Tau <- chol(cov.mat, pivot=TRUE);
# generate normal deviates outside loop
Zmat <- matrix(rnorm(n=p*n,mean=0,sd=1),nrow=p,ncol=n);
# empty matrix
out <- matrix(0,nrow=p,ncol=n);
# iterate
for(i in 1:n){
Z <- Zmat[,i];
out[,i] <- t(Tau)%*%Z + mu.vec
}
return(out)
}
```
Function to generate equation of a simple linear model in the figures
```{r load-lm_eqn}
lm_eqn <- function(df, x, y){
m <- lm(y ~ x, df);
eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(R)^2~"="~r2,
list(a = format(unname(coef(m)[1]), digits = 2),
b = format(unname(coef(m)[2]), digits = 2),
r2 = format(summary(m)$r.squared, digits = 3)))
as.character(as.expression(eq));
}
```
### Functions for the Brownian diffusion EGSS model
The stochastic exponential growth model serve as a null hypothesis of density-dependence models ([Dennis *et al.*, 2006](https://esajournals.onlinelibrary.wiley.com/doi/10.1890/0012-9615%282006%2976%5B323%3Aeddpna%5D2.0.co%3B2)). The exponential stochastic process for $N_t$ could be defined as $N_t = N_0 \lambda^t + E_t$, where $λ^t$ expresses the finite rate of change ($\lambda^t = e^{a(t)}$); $a$ being the instantaneous, intrinsic, or maximum per capita rate of change), $N_0$ is the initial population ($N(0)$), and $E_t$ is the environmental stochasticity or process noise at time $t$, which follows a normal distribution with mean $0$ and variance $\sigma^2$ ($E_t\sim\text{Normal}(0,\sigma^2)$). On the logarithmic scale ($X_t=\text{ln}(N_t)$), the discrete-time process can be defined as a continuous Brownian diffusion process with the stochastic differential equation:
$$
\begin{array}{ccc}
dX(t) &=& \ln \lambda dt+\beta dW(t) \\
&=& \theta\ dt+\beta dW(t)
\end{array}
$$
where $X(t) = \ln{N(t)}$ or the log-normal population abundance at
time $t$, $\theta = \ln{\lambda}$ is a constant of
population growth rate ($\ln{\lambda}-(\frac{\sigma^2}{2})$ as in the
***Eq13*** in [Dennis *et al.* (1991)](https://esajournals.onlinelibrary.wiley.com/doi/10.2307/1943004);
named $\mu = \ln{\lambda}$ in [Humbert *et al.* (2009)](https://nsojournals.onlinelibrary.wiley.com/doi/pdfdirect/10.1111/j.1600-0706.2009.17839.x),
although this notation is confusing for the OUSS notation), and $dW(t)$ is a random perturbation representing the environmental stochasticity or process
noise (Itô log-transformation of $E_t$ from GSS in [Dennis *et al.* (2006)](https://esajournals.onlinelibrary.wiley.com/doi/10.1890/0012-9615%282006%2976%5B323%3Aeddpna%5D2.0.co%3B2)), with mean $0$ and variance $\sigma^2dt$, or the intensity of environmental noise scaled by $\beta$, with $\beta>0$ ([Humbert *et al.*, 2009](https://nsojournals.onlinelibrary.wiley.com/doi/pdfdirect/10.1111/j.1600-0706.2009.17839.x)).
The EGSS model includes a component in sampling times $t_i$ not equally spaced. Thus, we denoted the latent realized abundance (e.g., weekly high counts in our case) as $n(0), n(t_1), n(t_2), ..., n(t_q)$. Let $x(t) = \ln{n(t)}$ and let $Y(t_i)$ be a value of $x(t)$ observed with error at time $t_i$. Then, our log-abundance observation model equation becomes $Y(t_i) = X(t_i) + F_i$, where $F_i$ follows a normal distribution with mean $0$ and variance $\tau^2$ ($F_i \sim \text{Normal}(0,\tau^2)$). This state-space model has four unknown parameters: $\ln \lambda = \theta_{density~independent}$ (the trend parameter or population growth rate under density independence; note the notation differs from [Humbert *et al.* (2009)](https://nsojournals.onlinelibrary.wiley.com/doi/pdfdirect/10.1111/j.1600-0706.2009.17839.x)), $\sigma^2$ (variability of process noise), $\tau^2$ (variability of observer noise), and $x_0$ (the initial log-abundance population).
The EGSS model has a multivariate normal log-likelihood function given
by (***EqA17*** in [Humbert *et al.*, (2009)](https://nsojournals.onlinelibrary.wiley.com/doi/pdfdirect/10.1111/j.1600-0706.2009.17839.x)):
$$
\ln{L}(x_0, \theta, \sigma^2, \tau^2) = -\frac{(q+1)}{2}\ln(2\pi)-\frac{1}{2}\ln(|\mathbf{V}|)-\frac{1}{2}(\mathbf{y}-\mathbf{m})'\mathbf{V}^{-1}(\mathbf{y}-\mathbf{m})
$$
For the numerical optimization, we will need three arguments:
1. A vector of time-series log-observed abundances `yt` ($\mathbf{y}$)
2. A vector of observation times `tt`
3. A vector of initial parameters `fguess` (a first guess for the
**four** parameters in EGSS), that could be roughly computing by
provide the vector of log-abundance observations `yt` ($\mathbf{y}$)
and the vector of observation times `tt` with function
`guess_eggs()`
```{r load-guess_egss}
guess_egss <- function(yt,tt){
# Time-vector starting in 0.
t.i <- tt-tt[1];
# Number of time-series transitions
q <- length(yt)-1;
# length of time-series
qp1 <- q+1;
# time intervals (named as S.t in H_O and sometimes in DP_E)
t.s <- t.i[2:qp1]-t.i[1:q];
#The Exponential Growth Observation Error (EGOE in H_O) initial values
# mean of the observations as assumed to arise from stationary distribution
Ybar <- mean(yt);
# mean of the time series
Tbar <- mean(t.i)
# trend parameter for EGOE (theta = ln(lambda) in H_O)
theta.egoe <- sum((t.i-Tbar)*(yt-Ybar))/sum((t.i-Tbar)*(t.i-Tbar));
# Initial population of EGOE
x0.egoe <- Ybar-theta.egoe*Tbar
# sigma square for EGOE is 0 (assume no ecological process variation)
ssq.egoe <- 0
# estimate of initial population observed under EGOE
Yhat.egoe <- x0.egoe+theta.egoe*t.i;
# initial value for tau^2
tsq.egoe <- sum((yt-Yhat.egoe)*(yt-Yhat.egoe))/(q-1);
#The Exponential Growth Process Noise (EGPN in H_O) initial values
# Square root of time intervals (time trend?)
Ttr <- sqrt(t.s);
# Observed trend?
Ytr <- (yt[2:qp1]- yt[1:q])/Ttr;
# trend parameter for EGPN (mu = ln(lambda) in H_O)
theta.egpn <- sum(Ttr*Ytr)/sum(Ttr*Ttr);
# Trend of observed estimated
Ytrhat <- theta.egpn*Ttr;
# initial value for sigma^2
ssq.egpn <- sum((Ytr-Ytrhat)*(Ytr-Ytrhat))/(q-1);
# tau square for EGPN is 0 (assume no observation variation)
tsq.egpn <- 0;
# Initial population of EGPN is the first observation
x0.egpn <- yt[1];
#four parameters needed in EGSS and OUSS.NoSt
theta0 <- (theta.egoe+theta.egpn)/2;
ssq0 <- ssq.egpn/2;
tsq0 <- tsq.egoe/2;
x0.out <- (x0.egoe+x0.egpn)/2;
return(c(theta0, ssq0, tsq0, x0.out))
}
```
The numerical optimization for computing the Restricted Maximum Likelihood
Estimates for the multivariate normal distribution of parameters in `R` is:
```{r load-negloglike_egss_remle}
negloglike_egss_remle <- function(fguess,yt,tt){
sigmasq <- exp(fguess[1]); #in egss_remle, this have only the two parameters
tausq <- exp(fguess[2]);
q <- length(yt) - 1;
qp1 <- q+1;
ss <- tt[2:qp1]-tt[1:q];
wt <- (yt[2:qp1]-yt[1:q])/ss;
ut <- wt[2:q]-wt[1:q-1];
vx <- matrix(0,qp1,qp1);
for(i in 1:q){
vx[(i+1):qp1,(i+1):qp1] <- matrix(1,(qp1-i),(qp1-i))*tt[i+1];
}
Sigma.mat<- sigmasq*vx;
Itausq <- matrix(rep(0,(qp1*qp1)), nrow=qp1, ncol=qp1);
diag(Itausq)<- rep(tausq,qp1);
V <- Sigma.mat + Itausq;
D1mat <- cbind(-diag(1/ss),matrix(0,q,1))+cbind(matrix(0,q,1),diag(1/ss));
D2mat <- cbind(-diag(1,(q-1)),matrix(0,(q-1),1)) + cbind(matrix(0,(q-1),1),diag(1,(q-1)));
V2 <- D2mat%*%D1mat%*%V%*%t(D1mat)%*%t(D2mat);
ofn=((q-1)/2)*log(2*pi)+(0.5*log(det(V2))) + (0.5*(ut%*%ginv(V2)%*%ut));
return(ofn)
}
```
To compute the EGSS-REMLEs we use the function `egss_remle()`
```{r load-egss_remle}
egss_remle <- function(yt,tt,fguess){
#Temporal vectors
t.i <- tt-tt[1];
q <- length(t.i)-1;
qp1 <- q+1;
t.s <- t.i[2:qp1] - t.i[1:q];
# initial guesses (sigmasq and tausq at log scale)
guess.optim <- c(log(fguess[2:3]))
# numerical optimization
optim.out <- optim(par=guess.optim,
fn=negloglike_egss_remle,
method="Nelder-Mead",
yt=yt,
tt=t.i)
#extract parameters estimated by REML
sigmasq <- exp(optim.out$par)[1]
tausq <- exp(optim.out$par)[1]
#to estimate trend parameter (theta) and initial population (x0)
vx <- matrix(0,qp1,qp1);
for(i in 1:q){
vx[((i+1):qp1),((i+1):qp1)] <- matrix(1,(qp1-i),(qp1-i))*t.i[(i+1)];
}
Sigma.mat <- sigmasq*vx;
Itausq <- matrix(rep(0,(qp1*qp1)),
nrow=qp1,
ncol=qp1);
diag(Itausq) <- rep(tausq,qp1);
V <- Sigma.mat + Itausq;
D1mat=cbind(-diag(1/t.s),
matrix(0,q,1))+cbind(matrix(0,q,1),
diag(1/t.s));
V1mat=D1mat%*%V%*%t(D1mat);
W.t=(yt[2:qp1]-yt[1:q])/t.s;
j1=matrix(1,q,1);
V1inv=ginv(V1mat);
#Trend parameter
theta.remle=(t(j1)%*%V1inv%*%W.t)/(t(j1)%*%V1inv%*%j1);
j=matrix(1,qp1,1);
Vinv=ginv(V);
#initial population
x0.remle=(t(j)%*%Vinv%*%(yt-as.numeric(theta.remle)*t.i))/(t(j)%*%Vinv%*%j);
#Extract REMLEs and AIC
remles <- c(theta.remle,exp(optim.out$par[1:2]),x0.remle)
lnL.hat <- - optim.out$value[1]
AIC <- -2*lnL.hat + 2*2 #where 2 = length(REMLEs)...
out <- list(remles=remles,
lnL.hat = lnL.hat,
AIC=AIC)
return(out)
}
```
With the EGSS-REMLE values, we can predict the trajectory of the latent ecological process with the function `egss_predict()`
```{r load-egss_predict}
egss_predict <- function(yt,tt,parms,plot.it="TRUE"){
# Time-vector starting in 0.
t.i <- tt-tt[1];
q <- length(t.i)-1;
qp1 <- q+1;
t.s <- t.i[2:qp1] - t.i[1:q];
# parameters ()
theta.remle <- parms[1];
sigmasq <- parms[2];
tausq <- parms[3];
x0.remle <- parms[4];
#Calculate estimated population size for EGSS model
m=rep(1,qp1); # Will contain Kalman means for Kalman calculations.
v=rep(1,qp1); # Will contain variances for Kalman calculations.
m[1]=x0.remle; # Initial mean of Y(t).
v[1]=tausq; # Initial variance of Y(t).
for (ti in 1:q) # Loop to generate estimated population abundances
{ # using Kalman filter (see equations 6 & 7, # Dennis et al. (2006)).
m[ti+1]=theta.remle+(m[ti]+((v[ti]-tausq)/v[ti])*(yt[ti]-m[ti]));
v[ti+1]=tausq*((v[ti]-tausq)/v[ti])+sigmasq+tausq;
}
# The following statement calculates exp{E[X(t) | Y(t), Y(t-1),...,Y(0)]};
# see equation 54 in Dennis et al. (2006).
Predict.EGSS.REML = exp(m+((v-tausq)/v)*(yt-m));
if(plot.it=="TRUE"){
# Plot the data & model-fitted values
#X11()
plot(tt,exp(yt),xlab="Time",ylab="Population abundance",
type="b",cex=1.5, lwd = 1.5, lty = 1,
main="Predicted (--) and observed (-o-) abundances");
# Population data are circles.
points(tt,Predict.EGSS.REML, type="l", lwd=1, lty = 2);
}
return(list(cbind(Time = tt, Predict.EGSS.REML, Observed.y = exp(yt))))
}
```
And also simulate trajectories with the function `egss_sim()`
```{r load-egss_sim}
egss_sim <- function(nsims,tt,parms){
# time and temporal scale
t.i <- tt-tt[1];
q <- length(t.i)-1;
qp1 <- q+1;
# parameters
theta <- parms[1];
sigmasq<- parms[2];
tausq <- parms[3];
x0 <- parms[4];
vx <- matrix(0,qp1,qp1);
for(i in 1:q){
vx[((i+1):qp1),((i+1):qp1)] <- matrix(1,(qp1-i),(qp1-i))*t.i[(i+1)];
}
Sigma.mat<- sigmasq*vx;
Itausq<- matrix(rep(0,(qp1*qp1)),
nrow=qp1,
ncol=qp1);
diag(Itausq) <- rep(tausq,qp1);
V <- Sigma.mat + Itausq;
theta.vec <- matrix((x0+theta*t.i),
nrow=qp1,
ncol=1);
out <- randmvn(n=nsims,
mu.vec=theta.vec,
cov.mat=V);
return(out)
}
```
### Functions for the Ornstein-Uhlenbeck diffusion GSS - OUSS model
The key to generalize the GSS for unequal sampling intervals lies in the mathematical insight that the solution of the discrete-time GSS model matches the solution at discrete time points of a diffusion process, which is a continuous time stochastic process. Specifically, the solution of the discrete time Gompertz model in the log scale matches exactly the well-known Ornstein-Uhlenbeck (OU) Gaussian diffusion process ([Dennis & Ponciano, 2014](https://esajournals.onlinelibrary.wiley.com/doi/abs/10.1890/13-1486.1)). Let $N_t$ represent the population abundance in the Gompertz diffusion with environmental stochasticity and no demographic stochasticity ([Dennis & Ponciano, 2014](https://esajournals.onlinelibrary.wiley.com/doi/abs/10.1890/13-1486.1); [Ponciano, 2018](https://doi.org/10.1016/j.tpb.2017.10.007)). This diffusion process is a well-known continuous-time version of an autoregressive process of order 1, characterized by a joint multivariate normal distribution of values across time points. The process is defined by its infinitesimal mean, variance, and covariance parameters ([Dennis & Ponciano, 2014](https://esajournals.onlinelibrary.wiley.com/doi/abs/10.1890/13-1486.1); [Ponciano, 2018](https://doi.org/10.1016/j.tpb.2017.10.007)).
The infinitesimal mean and variance of the process are given by:
$m_N (n)= \theta n[\ln \kappa - \ln n]$ and $\sigma_N^2 (n)= \beta^2 n^2$, respectively; here $\theta$ represents the speed of equilibration, $\kappa$ the equilibrium abundance, and $\beta$ scales the random perturbation by environment stochasticity, $dW$. The OU diffusion process is usually presented in its stochastic differential equation form $dN_t = \theta N_t [\ln\kappa - \ln{N_t})dt + \beta N_t dW_t$. A smooth transformation to $N_t$, given by $X_t=g(N_t)$ (e.g. $X_t=\ln N_t$), is also a diffusion process whose infinitesimal mean is given by $m_X (x)=m_N (n) g'(n) + 1/2 \sigma_N^2 (n)g''(n)$ and infinitesimal variance by $\sigma_X^2 (x) = \sigma_N^2 n [g' (n)]^2$, where $n=g^{-1} (x)$. This result is the well-known Itô-transformation for diffusion processes widely used in stochastic population dynamics modeling. For $g(n) = \lnn$, the infinitesimal mean simplifies to $m_X (x)= \theta (\mu - x)$, where $\mu = \ln\kappa - \frac{\beta^2}{2 \theta}$, and the infinitesimal variance becomes $\sigma_X^2 (x)= \beta^2$. Thus, the stochastic differential equation of the logarithmic process $X_t$ is $dX_t= \theta(\mu - X_t)dt + \beta dW_t$. If the process starts at an initial log-abundance $X_0=x_0$, the expected value and variance at any time $t$ are given by $\text{E}[X_t | X_0 = x_0] = \mu - (\mu - x_0) e^{\theta - t}$ and $\text{V}[X_t|X_0 = x_0] = \frac{\beta^2}{2\theta} (1-e^{-2\theta})$ respectively ([Dennis & Ponciano, 2014](https://esajournals.onlinelibrary.wiley.com/doi/abs/10.1890/13-1486.1)). Over time, the process converges to a stationary distribution with mean $\mu$ and variance $\frac{\beta^2}{2\theta}$.
The one-to-one relationships of the discrete equal sampling GSS model parameters to the continuous OUSS model parameters are ([Dennis & Ponciano, 2014](https://esajournals.onlinelibrary.wiley.com/doi/abs/10.1890/13-1486.1)):
$$
\begin{array}{ccc}
a &=& \mu(1- e^{-\theta}) \\
c &=& e^{-\theta} \\
\sigma^2 &=& \frac{(1-e^{-2\theta})\beta^2}{2\theta} \\
\tau^2 &=& \tau^2 \\
\end{array}
$$
Thus, the OUSS model has four unknown parameters under stationary distribution: $\mu$ (mean stationary log-abundance), $\theta_{density~dependent}$ (the trend parameter under density dependence, or rate to approach stationarity), $\beta^2$ (variability of the process noise), and $\tau^2$ (variability of sampling). The OUSS model also adds a component in sampling times $t_i$ not equally spaced $Y(t_i) = X(t_i) + F_i$, where the observation error keeps a normal distribution and the same unknown parameter ($F_i \sim \text{Normal}(0,\tau^2)$), and the underlying unobserved population $X(t_i)$ follows a continuous-time version of the GSS model. With the strength of density dependence parameter ($c$) ranging between $0$ and $1$, the dynamic of the population is stationary.
The inverse relationship between the OUSS and the GSS model parameters are:
$$
\begin{array}{ccc}
\mu &=& \frac{a}{1-c} \\
\theta &=& -\ln{c} \\
\beta^2 &=& -\frac{2\sigma^2 \ln{c}}{1-c^2} \\
\tau^2 &=& \tau^2 \\
\end{array}
$$
The normal stationary probability distribution has mean $\mu$ and variance $\frac{\beta^2}{2\theta}$ ([Dennis & Ponciano, 2014](https://esajournals.onlinelibrary.wiley.com/doi/abs/10.1890/13-1486.1)). If the initial log-abundance of the population does not meet this assumption (e.g., it is under transition growth), a nonstationary distribution could be modeled with a different maximum likelihood estimation approach ([Dennis & Ponciano, 2014](https://esajournals.onlinelibrary.wiley.com/doi/abs/10.1890/13-1486.1)). The normal transition in nonstationary cases has a mean $\mu - (\mu-x_0) e^{-\theta t}$ and variance ($\frac{\beta^2}{2\theta} (1-e^{-2\theta})$), adding an extra parameter to estimate ($x_0$). Given that a restricted maximum likelihood estimation is not available for nonstationary OUSS ([Dennis & Ponciano, 2014](https://esajournals.onlinelibrary.wiley.com/doi/abs/10.1890/13-1486.1)), we modeled the dynamic of the populations for density-independent (including initial nonstationary distributions) as EGSS, while stationary distributions as OUSS.
The multivariate normal log-likelihood for the stationary OUSS model is given by (see ***Eq. 19*** [Dennis & Ponciano, (2014)](https://esajournals.onlinelibrary.wiley.com/doi/abs/10.1890/13-1486.1)).
$$
\ln{L}(\mu, \theta, \beta^2, \tau^2) = -\frac{(q+1)}{2}\ln(2\pi)-\frac{1}{2}\ln(|\mathbf{V}|)-\frac{1}{2}(\mathbf{y}-\mathbf{m})'\mathbf{V}^{-1}(\mathbf{y}-\mathbf{m})
$$
where $q$ is the number of time-series transitions (thus, $q+1$ reflect
the length of the time-series, with the initial population estimation
$y_0$ as a realized value of the random variable $Y(0)$), $\mathbf{V}$
is the variance-covariance matrix (with diagonal computed from
$\text{V}[Y(t_i)] = \tau^2+\frac{\beta^2}{2\theta}$; ***Eq. 17*** in [Dennis & Ponciano, (2014)](https://esajournals.onlinelibrary.wiley.com/doi/abs/10.1890/13-1486.1)),
$\mathbf{y}$ is the data values ($y_0$, $y_1$, $y_2$, ..., $y_q$), and
$\mathbf{m}$ is the vector of same $\mu$ in all $q+1$ times
($E[Y(t_i)] = \mu]$; ***Eq. 16*** in [Dennis & Ponciano, (2014)](https://esajournals.onlinelibrary.wiley.com/doi/abs/10.1890/13-1486.1)).
This function requires three arguments for the numerical optimization in
`R`:
1. A vector of time-series of log-observed abundances `yt`
($\mathbf{y}$)
2. A vector of observation times `tt`
3. A vector of parameters `fguess` (a first guess for the **four**
parameters), that could be roughly computing by provide the vector
of log-abundance observations `yt` ($\mathbf{y}$) and the vector of
observation times `tt` with the function `guess_ouss()`
```{r load-guess_ouss}
guess_ouss <- function(yt,tt){
# Time-vector starting in 0.
t.i <- tt-tt[1];
# Number of time-series transitions
q <- length(yt)-1;
# length of time-series
qp1 <- q+1;
# time intervals
t.s <- t.i[2:qp1]-t.i[1:q];
# mean of the observations as assumed to arise from stationary distribution
Ybar <- mean(yt);
# Variance of the observations
Yvar <- sum((yt-Ybar)*(yt-Ybar))/q;
# Initial mu estimate (at stationary distribution)
mu1 <- Ybar;
# Kludge an initial value for theta based on mean of Y(t+s) given Y(t).
th1 <- -mean(log(abs((yt[2:qp1]-mu1)/(yt[1:q]-mu1)))/t.s);
# Moment estimate using stationary distribution
bsq1 <- 2*th1*Yvar/(1+2*th1);
# Observation error variance, assumed as first guess as betasq=tausq.
tsq1 <- bsq1;
# What to do if initial guesses is three 0's (or NAs)? Assume arbitrary values
three0s <- sum(c(th1,bsq1,tsq1))
if(three0s==0|is.na(three0s)){
th1 <- 0.5;
bsq1 <- 0.09;
tsq1 <- 0.23;}
out1 <- c(th1,bsq1,tsq1);
# What to do if initial guesses are too little? Assume arbitrary values
if(sum(out1<1e-7)>=1){
out1 <- c(0.5,0.09,0.23)}
out <- c(mu1,out1);
return(abs(out))
}
```
The numerical optimization for computing the parameters Restricted Maximum Likelihood
Estimate within the multivariate log-likelihood for the
stationary Ornstein-Uhlenbeck State-Space (OUSS) in `R` is:
```{r load-negloglike_ouss_remle}
negloglike_ouss_remle=function(yt,tt,fguess){
# Constrains parameters theta, beta^2, and tau^2 > 0
# speed of equilibration (Eq1 in DP_E)
theta <- exp(fguess[2]);
# variability of process noise
betasq <- exp(fguess[3]);
# variability of sampling
tausq <- exp(fguess[4]);
# number of time-series transitions
q <- length(yt) - 1;
# length of time-series
qp1 <- q+1;
# Variance (Eq11 in DP_E)
Var.inf<- betasq/(2*theta);
# time intervals (not used here?)
t.s <- tt[2:qp1] - tt[1:q];
# part of Eq18 in DP_E
t.cols <- matrix(rep(tt,each=qp1),
nrow=qp1,
ncol=qp1,
byrow=FALSE);
# (part of Eq18 in DP_E)
t.rows <- t(t.cols);
# (part of Eq18 in DP_E)
abs.diffs <- abs(t.rows-t.cols);
# Covariance of the process (Eq18 in DP_E)
Sigma.mat <- Var.inf*exp(-theta*abs.diffs);
# Create a matrix full of 0s of the length of time series
Itausq <- matrix(0,qp1,qp1);
# Repeat the observation error variance guess in the diagonal of the matrix
diag(Itausq) <- rep(tausq,qp1);
# add Covariance with the matrix
V <- Sigma.mat+Itausq;
# Create the differencing matrix **D**
Dmat <- cbind(-diag(1,q),matrix(0,q,1)) + cbind(matrix(0,q,1),diag(1,q));
# Variance-covariance matrix **Phi** (Eq20 DP_E)
Phi.mat<- Dmat%*%V%*%t(Dmat);
# simple differencing of the observations (W_i? )
wt <- yt[2:qp1]-yt[1:q];
# note the signs change because we want here the negative log-likelihood (Eq22*-1)
neglogl<- (q/2)*log(2*pi) + (1/2)*log(det(Phi.mat)) + (1/2)*wt%*%ginv(Phi.mat)%*%wt;
# What to do if the `neglogl` is not finite? assign a big number of 50000
if(is.infinite(neglogl)==TRUE){
return(50000)}else{
return(neglogl)}
}
```
To compute the OUSS-REMLEs we implement the function `ouss_remle()`
```{r load-ouss_remle}
ouss_remle <- function(yt, tt, fguess){
# Time-vector starting in 0.
t.i <- tt-tt[1];
# Number of time-series transitions
# length of time-series
q <- length(yt)-1;
qp1 <- q+1;
# time intervals
t.s <- t.i[2:qp1]-t.i[1:q];
# initial guesses (all, but negloglike.OU.remle will use only fguess[2:4])
guess.optim <- c(fguess[1],
log(fguess[2:4]));
# numerical optimization
optim.out <- optim(par = guess.optim,
fn=negloglike_ouss_remle,
method="Nelder-Mead",
yt=yt,
tt=t.i);
# Restricted maximum likelihood estimates (REMLE) and lnL.hat
remles <- exp(optim.out$par);
theta.remle <- remles[2];
betasq.remle <- remles[3];
tausq.remle <- remles[4];
lnL.hat <- -optim.out$value[1];
# Variance (Eq11 in DP_E)
Var.inf <- betasq.remle/(2*theta.remle)
# creates an matrix full of 1 dim qp1 x qp1
vx <- matrix(1,qp1,qp1);
# iterate to fill the matrix (couldn't find vx in DP_E!)
for (t.i in 1:q){
vx[(t.i+1):qp1,t.i]=exp(-theta.remle*cumsum(t.s[t.i:q]));
vx[t.i,(t.i+1):qp1]=vx[(t.i+1):qp1,t.i];
}
# ?
Sigma.mat <- vx*Var.inf;
# Create a matrix full of 0s of the length of time series
Itausq <- matrix(0,qp1,qp1);
# Repeat the observation error variance remle in the diagonal of the matrix
diag(Itausq) <- rep(tausq.remle,qp1);
# Variance-covariance matrix (V.hat) evaluated with remles to estimate mu.hat
V.remle <- Sigma.mat+Itausq;
# column vector matrix of ones
j <- matrix(1,qp1,1);
# Inverse matrix (part of Eq23 in DP_E)
Vinv <- ginv(V.remle);
# REMLE of mu (mu.hat) with Eq23 in DP_E
mu.remle <- (t(j)%*%Vinv%*%yt)/(t(j)%*%Vinv%*%j);
#AIC
AIC <- -2*lnL.hat + 2*4 #where 4 = length(mles)...
#Results
out <- list(remles = c(mu.remle,
theta.remle,
betasq.remle,
tausq.remle),
lnLhat = lnL.hat,
AIC = AIC)
return(out)
}
```
With the OUSS-REMLE values, we can predict the trajectory with the
function `ouss_predict()`
```{r load-ouss_predict}
ouss_predict <- function(yt,tt,parms, plot.it="TRUE"){
t.i <- tt-tt[1];
q <- length(t.i)-1;
qp1 <- q+1;
# parameters
mu <- parms[1];
theta <- parms[2];
betasq <- parms[3];
tausq <- parms[4];
Var.inf <- betasq/(2*theta);
t.s <- t.i[2:qp1] - t.i[1:q];
t.cols <- matrix(rep(t.i,each=qp1),nrow=qp1,ncol=qp1, byrow=FALSE);
t.rows <- t(t.cols);
abs.diffs <- abs(t.rows-t.cols);
nmiss <- t.s-1;
long.nmiss <- c(0,nmiss);
Nmiss <- sum(nmiss)
long.t <- t.i[1]:max(t.i)
where.miss <- which(is.na(match(x=long.t,table=t.i)),
arr.ind=TRUE)
lt.cols <- matrix(rep(long.t),
nrow=(qp1+Nmiss),
ncol=(qp1+Nmiss),
byrow=FALSE);
lt.rows <- t(lt.cols);
labs.diffs <- abs(lt.rows-lt.cols);
Sigma.mat <- Var.inf*exp(-theta*abs.diffs);
Itausq <- matrix(0,qp1,qp1);
diag(Itausq) <- rep(tausq,qp1);
V <- Sigma.mat+Itausq;
long.V <- Var.inf*exp(-theta*labs.diffs) + diag(rep(tausq,(qp1+Nmiss)))
Predict.t <- rep(0,qp1);
Muvec <- rep(mu,q);
miss.predict <- list()
Muvec.miss <- rep(mu,qp1);
start.miss <- 1
stop.miss <- 0
for (tj in 1:qp1){
Y.omitj <- yt[-tj]; # Omit observation at time tj.
V.omitj <- V[-tj,-tj]; # Omit row tj and col tj from var-cov matrix.
V12 <- V[tj,-tj]; # Submatrix: row tj without col tj.
Predict.t[tj] <- mu+V12%*%ginv(V.omitj)%*%(Y.omitj-Muvec); # Graybill's 1976 Thm.
if(long.nmiss[tj]==0){
miss.predict[[tj]] <- Predict.t[tj]}else
if(long.nmiss[tj]>0){
start.miss <- stop.miss+1
ntjmiss <- long.nmiss[tj]
mu.miss <- rep(mu,ntjmiss);
ind.tjmiss <- where.miss[start.miss:(start.miss+(ntjmiss-1))]
stop.miss <- stop.miss+ntjmiss
longV12 <- long.V[ind.tjmiss,-where.miss]
miss.predict[[tj]] <- c(mu.miss + longV12%*%ginv(V)%*%(yt-Muvec.miss),
Predict.t[tj])
}
}
Predict.t <- exp(Predict.t);
LPredict.t <- exp(as.vector(unlist(miss.predict)))
isinf <- sum(is.infinite(Predict.t))
if(isinf>0){
where.infs <- which(is.infinite(Predict.t)==TRUE, arr.ind=TRUE)
Predict.t[where.infs] <- .Machine$double.xmax
}
isinf2 <- sum(is.infinite(LPredict.t))
if(isinf2>0){
where.infs <- which(is.infinite(LPredict.t)==TRUE, arr.ind=TRUE)
LPredict.t[where.infs] <- .Machine$double.xmax
}
if(plot.it=="TRUE"){
# Plot the data & model-fitted values
#X11()
plot(tt,exp(yt),xlab="Time",ylab="Population abundance",type="b",cex=1.5,
main="Predicted (--) and observed (-o-) abundances");
# Population data are circles.
par(lty="dashed"); # Predicted abundances are dashed line.
points(tt,Predict.t, type="l", lwd=1);
}
return(list(cbind(tt,Predict.t,exp(yt)), cbind(long.t,LPredict.t) ))
}
```
And also simulate trajectories with `ouss_sim()`
```{r load-ouss_sim}
ouss_sim <- function(nsims,tt,parms){
# Time-vector starting in 0.
t.i <- tt-tt[1];
# Number of time-series transitions
q <- length(t.i)-1;
# length of time-series
qp1 <- q+1;
# parameters
mu <- parms[1];
theta <- parms[2];
betasq <- parms[3];
tausq <- parms[4];
Var.inf <- betasq/(2*theta);
t.s <- t.i[2:qp1] - t.i[1:q];
t.cols <- matrix(rep(t.i,each=qp1),
nrow=qp1,
ncol=qp1,
byrow=FALSE);
t.rows <- t(t.cols);
abs.diffs <- abs(t.rows-t.cols);
V <- Var.inf*exp(-theta*abs.diffs);
diag(V) <- diag(V) + rep(tausq,qp1);
m.vec <- rep(mu,qp1);
out <- randmvn(n=nsims,
mu.vec=m.vec,
cov.mat = V)
return(out)
}
```
\clearpage
# eBird data organization
Users should download the `ebd` file from
[eBird](https://ebird.org/data/download). See the supplement to
[Johnston *et al.* (2021)](https://doi.org/10.1111/ddi.13271) in
[Strimas-Mackey *et al.* (2023)](https://ebird.github.io/ebird-best-practices/), which is a key reference for the next section.
## Download eBird data
### Go to eBird and sign in
Go to [eBird](https://ebird.org/data/download). You have to sign-in into
eBird:
![Log in your eBird account](data_raw/Sign_in_eBird.png){width=50%}
### Request data
If you are in the home page, check you are signed-in and move down on the
page to "Request data".
![eBird home](data_raw/eBird_home_ed.png){width=50%}
You have to submit an application to have access to the data. Once you
have access, click on "Basic dataset (EBD)" (it will show the window of access).
![eBird data access](data_raw/eBird_access.png){width=50%}
Then, you can select by species, region, and/or date. In our case, lets
download *Rostrhamus sociabilis* in Florida (US).
![Requesting eBird data for snail kites in Florida, US - screenshot of the downloaded data for November 2024](data_raw/SnailKite_Florida_access_eBird.png){width=50%}
In the options, include the sampling event data always is a good recommendation. In snail kite for US it will save the sampling event, but for other Neotropical species tested in preliminary attempts, the sampling data was not included and the user should download the "Sampling event data" of 5.5 GB (comprised in `.tar` format). This step is highly recommended if you are interested in control for imperfect detection!!
After submitting the request, the link to download will arrive to the
email registered in your eBird account. You can save the `.txt` files
in a `data_raw` directory to be called during the refining process through filtering.
![Downloaded file - this image represent the version up to June 2024 of a previous run of the method](data_raw/files_deployment.png){width=50%}
This file will have the detection and observer counts for our species.
## Pre-filtering
We can simplify the eBird data selecting only columns of our interest
(it will reduce the size of the dataset)
```{r columns to filter-ebd, eval=FALSE}
colsE <- c("observer_id", "sampling_event_identifier",
"group identifier",
"common_name", "scientific_name",
"observation_count",
"country", "state_code", "locality_id", "latitude", "longitude",
"protocol_type", "all_species_reported",
"observation_date",
"time_observations_started",
"duration_minutes", "effort_distance_km",
"number_observers")
```
To conduct some filters, we will generate temporal files in our
computer. Here we generate only a single temporal file that can be
overwritten to assess different species.
```{r temporary filter files, eval=FALSE}
f_ebd <- "data_tmp/ebd_Examples.txt"
f_sed <- "data_tmp/sed_Examples.txt"
```
The construction of time-series of the individuals counted from
eBird will assume spatiotemporal subsampling, selecting a single value
with the high counts (assuming to be the minimum number of individuals detected) per week in spatial sampling units of \~ $100 \text{ km}^2$. To construct a discrete global grid system, we can use the function `dgconstruct()` in the package `dgconstruct`; the argument `spacing` indicates the spacing between the center of adjacent cells (related with Characteristic Length Scale - CLS), in our case `spacing = 11` indicates a diameter of \~$11\ km$, representing an area of $95.98\ km^2$ (\~ $100\ km^2$).
```{r construct discrete global grid}
#specify seed for random number generation
dggs_pop <- dgconstruct(spacing = 11)
```
## Refinament data by filtering
The package `auk`, in combination with `tidyverse`, allows the filtering
of the eBird data (see [Strimas-Mackey *et al.* 2023](https://ebird.github.io/ebird-best-practices/)). Note that the
first function `auk_ebd()` includes the path of the eBird data downloaded and saved in your working directory (up to November 2024), and it is the initial creation of an `auk_ebd` object. Then, different functions serve to filter the data by the metadata of the checklists. We followed the next order below:
* by protocol (`auk_protocol()`; only traveling or stationary),
* by distance (`auk_distance()`; $≤5$ km),
* by duration (`auk_duration()`; $≤5$ hours, note the units are in minutes: $300$), and
* only complete lists (`auk_complete()`).
Then, the filters defined are converted to an AWK script with the function `auk_filter()`, generating a filtered eBird Reference Dataset (ERD), storing in the temporal files `f_ebd` with only the selected columns (defined in the pre-filtering). Finally, the function `read_ebd()` read the filtered file.
```{r ebd-filter, eval=FALSE}
ebd_filt <- auk_ebd("data_raw/ebd_US-FL_snakit_smp_relNov-2024.txt") %>%
auk_protocol(c("Traveling", "Stationary")) %>%
auk_distance(distance = c(0,5)) %>%
auk_duration(duration = c(0,300))%>%
auk_complete() %>%
auk_filter(f_ebd,overwrite=T, keep = colsE) %>%
read_ebd()
```
![head of the ebd_filt file](data_raw/ebd_filt_head.png){width=50%}
Then, just for the sake of double checking and organization, we can remove
the observations without counts, add distance $0$ to
stationary protocols, modify the time of observations started to decimal,
round hour sampling to an integer, extract year, month, week, and
day_of_year. Also, we can confirm and filter out by effort, such as
observers $≤10$, distance $≤5 \text{ km}$, duration $≤5 \text{ hours}$,
and only records with counts included. These covariates could be further used to test their effects on population dynamic estimates (see [Fink *et al.* 2023](https://besjournals.onlinelibrary.wiley.com/doi/10.1111/2041-210X.14186)).
```{r ebd-filter2, eval=FALSE}
#Some effort extraction and confirmation
ebd_filt <- ebd_filt %>%
mutate(
# We don't want here count in 'X', to convert to NA we use `as.integer()`
observation_count = as.integer(observation_count),
# effort_distance_km to 0 for non-travelling counts
effort_distance_km = if_else(protocol_type == "Stationary",
0, effort_distance_km),
# convert time to decimal hours since midnight
time_observations_started = time_to_decimal(time_observations_started),
hour_sampling = round(time_observations_started, 0),
# split date into year, month, week, and day of year
year = year(observation_date),
month = month(observation_date),
week = week(observation_date),
day_of_year = yday(observation_date)) %>%
filter(number_observers <= 10, #Only list with less than 10 observers
effort_distance_km <= 5, #be sure of distance effort
duration_minutes %in% (0:300), #be sure of duration effort
!is.na(observation_count)) #only records with counts reported
```
![head of the ebd_filt file - note new columns were added](data_raw/ebd_filt_head2.png){width=50%}
Now we can add a new variable that identify each `cell` from a grid of
hexagons (spatial sampling units), using the `longitude` and `latitude`
information of our `ebd_filt` dataset and the function
`dgGEO_to_SEQNUM()`. With the new variable, we can extract the maximum
count of individuals and number of checklists per week per cell.
```{r add cellID, eval=FALSE}
SnailKite <- ebd_filt %>%
mutate(cell = dgGEO_to_SEQNUM(dggs_pop, #id for cells
longitude, latitude)$seqnum) %>%
group_by(cell, year, month, week) %>%
mutate(max_count = max(observation_count, na.rm = T),
n_lists = n()) |>
ungroup()
```
![head of the ebd_filt file - adding cell](data_raw/ebd_filt_head_cell.png){width=50%}
This file is saved as a backup
```{r save SnailKite-rds, eval=FALSE}
#and save the filter
saveRDS(SnailKite, "data_tmp/SnailKiteCellsID_filtered.rds")
```
\FloatBarrier
## Time series of eBird weekly high-counts
We adjusted the time-series from the 1st week of 2018 (January) to the
last with data of 2024 (November). Since 2018, snail kites reached more than 1000 annual records.
```{r temporal bias}
SnailKite <- readRDS("data_tmp/SnailKiteCellsID_filtered.rds")
png('data_tmp/FigSI-1_HistogramTemporalBias.png',
width = 10, height = 5, units = "in", res = 300)
hist(SnailKite$year,
breaks = 50,
main = "Florida Snail kites, checklists per year",
xlab = "Year")
abline(h = 1000, v = 2017, col = "red")
dev.off()
```
![Histogram of the number of eBird checklists per year for Florida Snail kites. Red lines indicate our temporal sampling bias threshold (more than 1000 checklists per year), concentrating our sampling between January 2018 and November 2024.](data_tmp/FigSI-1_HistogramTemporalBias.png)
In addition, the spatial cell with higher records overlaps with the
Payne's Prairie State Park wetland in Alachua County, north central
Florida, where snail kites established in 2018. We
extracted the high count per week in the cell of Payne's Prairie to illustrate our method.
But first, we filter by observation data greater than or equal to
`2018-01-01`, and generate a new variable called `Time.t`, to have the
accumulated id of weeks from 2018 to the end of our time series. We used
the function `case_when()` based on `year`.
```{r filter snailkites since 2018}
snailkites.week <- SnailKite |>
filter(observation_date >= "2018-01-01") |>
mutate(Time.t = case_when(year == 2018 ~ week,
year > 2018 ~ week+(52*(year-2018))))
summary(snailkites.week$observation_date)
summary(snailkites.week$Time.t)
```
Then, we group by the `cell` and `Time.t`, summarizing the maximum
integer count per week, named `Observed.y` in our data set.
```{r week counts snailkites}
snailkites.week.counts <- snailkites.week |>
group_by(cell, Time.t) |>
summarise(Observed.y = round(max(max_count),0))
head(snailkites.week.counts)
```