-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_detections.R
1665 lines (1562 loc) · 88.1 KB
/
get_detections.R
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
######################################
######################################
#### get_detection_pr()
#' @title A detection probability function based on distance
#' @description This function calculates detection probability (e.g., of an acoustic detection) at specified distances from the sampling device (e.g., a passive acoustic telemetry receiver) using user-defined parameters (i.e., a model intercept, a coefficient for the effect of distance and an inverse link function). The function returns a plot of detection probability with distance and/or a vector of detection probabilities.
#'
#' @param distance A numeric vector of distances at which to calculate detection probability.
#' @param beta_0,beta_1 Single numbers that define the model coefficients (i.e., the intercept and gradient on the scale of the link function).
#' @param inv_link A function that defines the inverse link function. The default function is the logistic (inverse logit) function.
#' @param output An integer (\code{1L}, \code{2L} or \code{3L}) that defines the output type. \code{1L} returns a plot of detection probability against distance; \code{2L} returns a numeric vector of detection probabilities; and \code{3L} returns both of the above.
#' @param ... Additional arguments, passed to \code{\link[prettyGraphics]{pretty_plot}}, to customise the plot. These are only implemented if \code{output = 1L} or \code{output = 3L}.
#'
#' @return The function calculates detection probability at each specified distance and returns a plot, a vector of detection probabilities, or both, depending on the value of the \code{output} argument. If a vector of detection probabilities is returned, this contains the following attributes: `X', the model matrix; `beta', the regression coefficients; and `inv_link', the inverse link function.
#'
#' @examples
#' #### Example (1): Implement the function using the default parameters
#' # The function returns a graph and a vector of detection probabilities
#' det_pr <- get_detection_pr()
#' utils::head(det_pr)
#' # The vector has attributes:
#' # ... 'X' (the model matrix)
#' # ... 'beta' (the regression coefficient)
#' # ... 'inv_link' (the inverse link function)
#' utils::str(det_pr)
#'
#' #### Example (2): Adjust model parameters
#' # Change regression coefficients
#' det_pr <- get_detection_pr(beta_0 = 2.5, beta_1 = -0.006)
#' # Use inverse probit link function
#' det_pr <- get_detection_pr(beta_0 = 2.5, beta_1 = -0.006, inv_link = stats::pnorm)
#'
#' #### Example (3): Modify graphical properties
#' det_pr <- get_detection_pr(
#' beta_0 = 2.5,
#' beta_1 = -0.006,
#' type = "l",
#' xlab = "Distance (m)",
#' ylab = "Detection Probability"
#' )
#'
#' #### Example (4): Modify return options
#' # Only graph
#' get_detection_pr(output = 1L)
#' # Only values
#' get_detection_pr(output = 2L)
#' # Both graph and values (the default)
#' get_detection_pr(output = 3L)
#'
#' @author Edward Lavender
#' @export
#'
get_detection_pr <- function(distance = 1:1000,
beta_0 = 2.5,
beta_1 = -0.01,
inv_link = stats::plogis,
output = 3L, ...) {
#### Checks
stopifnot(length(beta_0) == 1 & length(beta_1) == 1)
output <- check_value(input = output, supp = 1:3, warn = TRUE, default = 3L)
#### Calculate detection probabilities
X <- matrix(c(rep(1, length(distance)), distance), ncol = 2, byrow = FALSE)
beta <- matrix(c(beta_0, beta_1), nrow = 2)
rownames(beta) <- c("beta_0", "beta_1")
Y <- inv_link(X %*% beta)
Y <- as.numeric(Y)
# Add attributes
attributes(Y)$X <- X
attributes(Y)$beta <- beta
attributes(Y)$inv_link <- inv_link
#### Visualise detection probabilities
if (output %in% c(1, 3)) {
prettyGraphics::pretty_plot(X[, 2], Y, ...)
}
#### Return detection probabilities
if (output %in% c(2, 3)) {
return(Y)
} else {
return(invisible())
}
}
######################################
######################################
#### get_detection_containers()
#' @title Define detection containers around receivers
#' @description This function defines the areas surveyed by receivers (termed `detection containers') as a spatial object, based on an estimate of the detection range (m) and any barriers to detection. To implement the function, receiver locations must be supplied as a SpatialPoints or SpatialPointsDataFrame object with the Universe Transverse Mercator coordinate reference system. The function defines a spatial buffer around each receiver according to the estimated detection range, cuts out any barriers to detection, such as the coastline, and returns a SpatialPolygons object that defines the combined detection container across all receivers or receiver-specific detection containers.
#'
#' @param xy A \code{\link[sp]{SpatialPoints-class}} or \code{\link[sp]{SpatialPointsDataFrame-class}} object that defines receiver locations. The coordinate reference system should be the Universe Transverse Mercator coordinate reference system.
#' @param detection_range A number that defines the detection range (m) of receivers.
#' @param resolution A number that defines the number of linear segments used to approximate the detection container (see the \code{quadsegs} argument in \code{\link[rgeos]{gBuffer}}).
#' @param boundaries An \code{\link[raster]{extent}} object (on an object from which this can be extracted) that defines the boundaries of the study area.
#' @param coastline (optional) A \code{\link[sp]{SpatialPolygonsDataFrame-class}} object that defines barriers (such as the coastline) that block receivers from surveying areas within their detection range.
#' @param plot A logical input that defines whether or not to plot receivers, their containers, and the buffer (if specified).
#' @param ... Additional arguments passed to \code{\link[rgeos]{gBuffer}}, such as \code{byid}.
#'
#' @return The function returns a \code{\link[sp]{SpatialPolygons-class}} object of the detection containers around receivers that represents the area they survey under the assumption of a constant detection range, accounting for any barriers to detection. By default, this will contain a single feature, which is suitable for the calculation of the total area surveyed by receivers (see \code{\link[flapper]{get_detection_area_sum}}) because it accounts for the overlap in the detection ranges of receivers. However, if \code{byid = TRUE} is passed via \code{...} to \code{\link[rgeos]{gBuffer}}, the returned object will have a feature for each pair of coordinates in \code{xy} (i.e., receiver). This is less appropriate for calculating the area surveyed by receivers, since areas surveyed by multiple receivers will be over-counted, but it is suitable when the containers for particular receivers are required (e.g., to extract environmental conditions within a specific receiver's detection range) (see \code{\link[flapper]{get_detection_containers_envir}}).
#'
#' @examples
#' #### Define receiver locations as a SpatialPoints object with a UTM CRS
#' proj_wgs84 <- sp::CRS(SRS_string = "EPSG:4326")
#' proj_utm <- sp::CRS(SRS_string = "EPSG:32629")
#' xy <- sp::SpatialPoints(
#' dat_moorings[, c("receiver_long", "receiver_lat")],
#' proj_wgs84
#' )
#' xy <- sp::spTransform(xy, proj_utm)
#' xy@data <- as.data.frame(xy)
#'
#' #### Example (1): Get the simplest containers around receivers
#' get_detection_containers(xy)
#'
#' #### Example (2): Account for barriers in the study area
#' get_detection_containers(xy, coastline = dat_coast)
#'
#' #### Example (3): Adjust the detection range
#' get_detection_containers(xy, detection_range = 400, coastline = dat_coast)
#' get_detection_containers(xy, detection_range = 500, coastline = dat_coast)
#'
#' #### Example (4): Suppress the plot
#' get_detection_containers(xy, coastline = dat_coast, plot = FALSE)
#'
#' #### Example (5): Output characteristics are controlled via byid
#' # A SpatialPolygons object with one feature is the implicit output
#' sp_1 <- get_detection_containers(xy, coastline = dat_coast, byid = FALSE)
#' sp_1
#' # A SpatialPolygons object with one feature for each element in xy
#' # ... can be returned via byid = TRUE
#' sp_2 <- get_detection_containers(xy, coastline = dat_coast, byid = TRUE)
#' sp_2
#' # The total area of the former will be smaller, since areas covered
#' # ... by multiple receivers are merged
#' rgeos::gArea(sp_1)
#' rgeos::gArea(sp_2)
#' # But it can be more convenient to use the latter format in some cases
#' # ... because it is easy to isolate specific containers:
#' raster::plot(dat_coast)
#' raster::plot(sp_1[1], add = TRUE, col = "red") # single feature
#' raster::plot(sp_2[1], add = TRUE, col = "blue") # isolate specific features
#'
#' @author Edward Lavender
#' @export
get_detection_containers <- function(xy,
detection_range = 425,
resolution = 1000,
boundaries = NULL, coastline = NULL,
plot = TRUE, ...) {
#### Checks
# Check xy is a SpatialPoints object or similar
check_class(input = xy, to_class = c("SpatialPoints", "SpatialPointsDataFrame"), type = "stop")
check...(c("spgeom", "width", "quadsegs"), ...)
#### Define buffers around receivers equal to detection radius
xy_buf <- rgeos::gBuffer(xy, width = detection_range, quadsegs = resolution, ...)
#### Clip around boundaries/coastline (if applicable)
if (!is.null(boundaries)) {
if (length(xy_buf) == 1) {
xy_buf <- raster::crop(xy_buf, boundaries)
} else {
xy_buf <- lapply(1:length(xy_buf), function(i) raster::crop(xy_buf[i, ], boundaries))
xy_buf <- do.call(raster::bind, xy_buf)
}
}
if (!is.null(coastline)) {
if (length(xy_buf) == 1) {
xy_buf <- rgeos::gDifference(xy_buf, coastline)
} else {
xy_buf <- lapply(1:length(xy_buf), function(i) rgeos::gDifference(xy_buf[i, ], coastline))
xy_buf <- do.call(raster::bind, xy_buf)
}
}
#### Plot [update to use pretty_map()]
if (plot) {
if (!is.null(coastline)) {
raster::plot(coastline)
graphics::points(xy, pch = 4)
} else {
raster::plot(xy, pch = 4)
}
raster::lines(xy_buf)
}
#### Return outputs
return(xy_buf)
}
########################################
########################################
#### get_detection_containers_overlap()
#' @title Get detection container overlaps
#' @importFrom lubridate `%within%`
#' @description This functions identifies receivers with overlapping detection containers in space and time.
#'
#' @param containers A \code{\link[sp]{SpatialPolygonsDataFrame}} that defines detection containers (see \code{\link[flapper]{get_detection_containers}}). The \code{data} slot must include a dataframe with the following columns: an unique, integer identifier for each receiver (`receiver_id') and receiver deployment \code{\link[base]{Dates}} (`receiver_start_date' and `receiver_end_date').
#' @param services (optional) A dataframe that defines receiver IDs and servicing \code{\link[base]{Dates}} (times during the deployment period of a receiver when it was not active due to servicing). If provided, this must contain the following columns: an integer identifier for serviced receivers (named ‘receiver_id’) and two columns that define the time of the service(s) (‘service_start_date’ and ‘service_end_date’) (see \code{\link[flapper]{make_matrix_receivers}}).
#'
#' @details This function requires the \code{\link[tidyr]{tidyr-package}} (specifically \code{\link[tidyr]{pivot_longer}}).
#'
#' @return The function returns a list with two elements:
#' \itemize{
#' \item \strong{overlap_by_receiver} is list, with one element for all integers from \code{1:max(containers$receiver_id)}. Any elements that do not correspond to receivers contain a NULL element. List elements that correspond to receivers contain a dataframe that defines, for each day over the deployment period (defined in `timestamp') of that receiver (defined in `receiver_id'), whether (1) or not (0) that receiver overlapped in space with every other receiver (defined in the remaining columns by their receiver IDs).
#' \item \strong{overlap_by_date} is a named list, with one element for each date from the start until the end of the study (\code{min(containers$receiver_start_date):max(containers$receiver_end_date)}), that records an integer vector of all receivers with overlapping containers on that date. In this vector, each receiver overlaps with at least one other receiver (but not every receiver will necessarily overlap with every other receiver).
#' }
#'
#' @examples
#' #### Define receiver containers
#' ## Define receiver locations as a SpatialPoints object with a UTM CRS
#' proj_wgs84 <- sp::CRS(SRS_string = "EPSG:4326")
#' proj_utm <- sp::CRS(SRS_string = "EPSG:32629")
#' rownames(dat_moorings) <- dat_moorings$receiver_id
#' xy <- sp::SpatialPoints(
#' dat_moorings[, c("receiver_long", "receiver_lat")],
#' proj_wgs84
#' )
#' xy <- sp::spTransform(xy, proj_utm)
#' xy@data <- as.data.frame(xy)
#' rownames(xy@data) <- dat_moorings$receiver_id
#' ## Get receiver-specific detection containers
#' # ... via get_detection_containers with byid = TRUE
#' containers <- get_detection_containers(xy, byid = TRUE)
#' ## Link detection containers with receiver IDs and deployment dates
#' # ... in a SpatialPointsDataFrame, as required for this function.
#' containers_df <- dat_moorings[, c(
#' "receiver_id",
#' "receiver_start_date",
#' "receiver_end_date"
#' )]
#' row.names(containers_df) <- dat_moorings$receiver_id
#' containers <- sp::SpatialPolygonsDataFrame(containers, containers_df)
#'
#' ## Simulate some receiver 'servicing' dates for demonstration purposes
#' set.seed(1)
#' # Loop over each receiver...
#' services_by_receiver <- lapply(split(dat_moorings, 1:nrow(dat_moorings)), function(din) {
#' # For the receiver, simulate the number of servicing events
#' n <- sample(0:3, 1)
#' dout <- NULL
#' if (n > 0) {
#' # simulate the timing of servicing events
#' dates <- sample(seq(min(din$receiver_start_date), max(din$receiver_end_date), "days"), n)
#' dout <- data.frame(
#' receiver_id = rep(din$receiver_id, length(dates)),
#' service_start_date = dates,
#' service_end_date = dates
#' )
#' }
#' return(dout)
#' })
#' services <- do.call(rbind, services_by_receiver)
#' rownames(services) <- NULL
#' if (nrow(services) == 0) services <- NULL
#'
#' #### Example (1): Implement function using containers alone
#' overlaps_1 <- get_detection_containers_overlap(containers = containers)
#' summary(overlaps_1)
#'
#' #### Example (2): Account for servicing dates
#' overlaps_2 <- get_detection_containers_overlap(
#' containers = containers,
#' services = services
#' )
#' # Examine the first few simulated servicing events
#' services[1:3, ]
#' # Show that the list_by_date element for the first servicing event
#' # ... includes the first receiver in services$receiver_id
#' # ... for overlaps_1 but not overlaps_2,
#' # ... which accounts for that fact that the receiver was serviced then:
#' overlaps_1$list_by_date[[as.character(services$service_start_date[1])]]
#' overlaps_2$list_by_date[[as.character(services$service_start_date[1])]]
#' # Likewise, show that the list_by_receiver element for that receiver
#' # ... includes overlapping receivers in overlaps_1 but not overlaps_2:
#' r_id <- services$receiver_id[1]
#' overlaps_1$list_by_receiver[[r_id]][overlaps_1$list_by_receiver[[r_id]]$timestamp %in%
#' services$service_start_date[services$receiver_id == r_id], ]
#' overlaps_2$list_by_receiver[[r_id]][overlaps_2$list_by_receiver[[r_id]]$timestamp %in%
#' services$service_start_date[services$receiver_id == r_id], ]
#'
#' @seealso \code{\link[flapper]{get_detection_containers}} creates detection containers.
#' @author Edward Lavender
#' @export
get_detection_containers_overlap <- function(containers, services = NULL) {
#### Checks
## packages
if (!requireNamespace("tidyr", quietly = TRUE)) stop("Please install 'tidyr': this function requires the tidyr::pivot_longer() routine.")
## containers
if (!inherits(containers, "SpatialPolygonsDataFrame")) stop("'containers' must be a SpatialPolygonsDataFrame.")
## moorings
moorings <- data.frame(containers)
check_names(
input = moorings, req = c("receiver_id", "receiver_start_date", "receiver_end_date"),
extract_names = colnames, type = all
)
if (is.numeric(moorings$receiver_id)) moorings$receiver_id <- as.integer(moorings$receiver_id)
if (!is.integer(moorings$receiver_id)) {
stop(paste("Argument 'xy$receiver_id' must be of class 'integer', not class(es):"), class(moorings$receiver_id))
}
if (any(moorings$receiver_id <= 0)) {
stop("Argument 'xy$receiver_id' cannot contain receiver IDs <= 0.")
}
if (any(duplicated(moorings$receiver_id))) {
stop("Argument 'xy$receiver_id' contains duplicate elements.")
}
## services
if (!is.null(services)) {
check_names(
input = services, req = c("receiver_id", "service_start_date", "service_end_date"),
extract_names = colnames, type = all
)
if (is.numeric(services$receiver_id)) services$receiver_id <- as.integer(services$receiver_id)
if (!is.integer(services$receiver_id)) {
stop(paste("Argument 'services$receiver_id' must be of class 'integer', not class(es):"), class(services$receiver_id))
}
if (!all(unique(services$receiver_id) %in% unique(moorings$receiver_id))) {
message("Not all receivers in services$receiver_id are in moorings$receiver_id.")
}
services$interval <- lubridate::interval(
services$service_start_date,
services$service_end_date
)
}
#### Define receiver activity status matrix
# This defines whether or not each receiver was active on each date (0, 1)
# We'll start from this point because it accounts for receiver activity status (including servicing).
# We'll then update this, for each receiver, to define whether or not, if that receiver was active on a given date
# ... which other receivers (if any) it overlapped in space (and time) with.
rs_active_mat <- make_matrix_receivers(
moorings = moorings,
services = services,
delta_t = "days",
as_POSIXct = NULL
)
#### Define a list, with one dataframe element per receiver, that defines, for each time step, the overlapping receivers (0, 1)
# Loop over each container...
containers_ls <- lapply(1:length(containers), function(i) containers[i, ])
list_by_receiver <- pbapply::pblapply(containers_ls, function(container) {
#### Collect container and receiver status information
# container <- containers_ls[[2]]
# Copy receiver activity status matrix
info <- rs_active_mat
# Focus on receiver's deployment window
info <- info[as.Date(rownames(info)) %within% lubridate::interval(container$receiver_start_date, container$receiver_end_date), , drop = FALSE]
#### Convert receiver 'active' index (0, 1) to 'overlapping' index
# ... A) Check for overlapping receivers
# ... B) If there are overlapping receivers,
# ... ... then we force all dates when the receiver of interest was not active to take 0 (no receivers could overlap with it then)
# ... ... and we force all receivers that didn't overlap in space to 0
# ... C) If there are no overlapping receivers, the whole matrix just gets forced to 0
## (A) Get an index of the receivers that intersected with the current receiver (in space)
containers_sbt <- containers[!(containers$receiver_id %in% container$receiver_id), ]
int_1 <- rgeos::gIntersects(container, containers_sbt, byid = TRUE)
## (B) If there are any overlapping receivers,
if (any(int_1)) {
## Process 'overlap' when the receiver was not active
# ... Any time there is a '0' for activity status of the current receiver (e.g., due to servicing),
# ... there can be no overlap with that receiver
# ... so we will set a '0' to all other receivers
# ... some of which may have been active on that date
# ... Note the implementation of this step before the step below, when all rows for the receiver
# ... of interest are (inadvertently) set to 0.
info[which(info[, as.character(container$receiver_id)] == 0), ] <- 0
## Process 'overlap' for overlapping/non-overlapping receivers
# For overlapping receivers, we'll leave these as defined in the activity matrix
# ... (if active, then they overlap;
# ... if not active, e.g., due to a servicing event for that receiver, then they can't overlap).
# ... For the non-overlapping receivers, we'll force '0' for the overlap (even if they were active).
# Get receiver IDs
containers_that_overlapped <- data.frame(containers_sbt[which(int_1), ])
# For all non-overlapping receivers, set '0' for overlap
# ... Note that this will include the receiver of interest
# ... But that doesn't matter because we'll drop that column anyway
info[, !(colnames(info) %in% containers_that_overlapped$receiver_id)] <- 0
## (C) If there aren't any spatially overlapping receivers, then the whole matrix just takes on 0
} else {
info[] <- 0
}
#### Process dataframe
rnms <- rownames(info)
info <- data.frame(info)
colnames(info) <- colnames(rs_active_mat)
info[, as.character(container$receiver_id)] <- NULL
cnms <- colnames(info)
info$timestamp <- as.Date(rnms)
info$receiver_id <- container$receiver_id
info <- info[, c("timestamp", "receiver_id", cnms)]
return(info)
})
names(list_by_receiver) <- as.character(containers$receiver_id)
#### On each date, get the vector of overlapping receivers
# Note that not every receiver in this list will necessarily overlap with every other receiver though.
lbd <- lapply(list_by_receiver, function(d) {
tidyr::pivot_longer(
data = d,
cols = 3:ncol(d),
names_to = "receiver_id_2",
names_transform = list(receiver_id_2 = as.integer)
)
})
lbd <- dplyr::bind_rows(lbd) %>% dplyr::filter(.data$value == 1)
lbd <- lapply(split(lbd, lbd$timestamp), function(d) unique(c(d$receiver_id[1], d$receiver_id_2)))
##### Process outputs
# For the list_by_receiver, we will have one element for each receiver from 1:max(moorings$receiver_id)
# ... (for each indexing)
list_by_receiver <- lapply(as.integer(1:max(moorings$receiver_id)), function(i) {
if (i %in% moorings$receiver_id) {
return(list_by_receiver[[as.character(i)]])
} else {
return(NULL)
}
})
# For the list_by_date (lbd), we will have one element for each date from the start to the end of the array
list_by_date <- list()
for (day in as.character(seq(min(moorings$receiver_start_date), max(moorings$receiver_end_date), "days"))) {
if (is.null(lbd[[day]])) list_by_date[[day]] <- NULL else list_by_date[[day]] <- lbd[[day]]
}
#### Return outputs
out <- list()
out$list_by_receiver <- list_by_receiver
out$list_by_date <- list_by_date
return(out)
}
######################################
######################################
#### get_detection_area_sum()
#' @title Calculate the total area sampled by acoustic receivers
#' @description This function calculates the total area sampled by receivers, under the assumption of a constant detection range. To implement the function, receiver locations must be supplied as a SpatialPoints or SpatialPointsDataFrame object with the Universe Transverse Mercator coordinate reference system. The \code{\link[flapper]{get_detection_containers}} is used to calculate the detection containers around receivers, given a specified detection range (m) and any barriers to detection, such as coastline, and then the total area covered by receivers is calculated, accounting for overlapping containers.
#'
#' @param xy,detection_range,coastline,plot,... Arguments required to calculate and visualise detection containers via \code{\link[flapper]{get_detection_containers}}; namely, receiver locations (\code{xy}), the detection range (\code{detection_range}), barriers to detection (\code{coastline}), and whether or not to plot the containers (\code{plot}).
#' @param scale A number that scales the total area (m). The default (\code{1/(1000^2)}) converts the units of \eqn{m^2} to \eqn{km^2}.
#'
#' @details This is a simple metric of the overall receiver sampling effort. This may be a poor metric if the assumption of a single detection range across all receivers is substantially incorrect or if there are substantial changes in the receiver array over the course of a study.
#'
#' @return The function returns a number that represents the total area surveyed by receivers (by default in \eqn{km^2}) and, if \code{plot = TRUE}, a plot of the area with receivers and their detection ranges.
#'
#' @seealso \code{\link[flapper]{get_detection_containers}} defines detection containers, across which the detection area is calculated. \code{\link[flapper]{get_detection_area_ts}} calculates the area sampled by receivers through time.
#'
#' @examples
#' #### Define receiver locations as a SpatialPoints object with a UTM CRS
#' proj_wgs84 <- sp::CRS(SRS_string = "EPSG:4326")
#' proj_utm <- sp::CRS(SRS_string = "EPSG:32629")
#' xy <- sp::SpatialPoints(
#' dat_moorings[, c("receiver_long", "receiver_lat")],
#' proj_wgs84
#' )
#' xy <- sp::spTransform(xy, proj_utm)
#'
#' #### Example (1): Calculate the total area sampled by receivers
#' get_detection_area_sum(xy)
#'
#' #### Example (2): Account for barriers in the study area
#' get_detection_area_sum(xy, coastline = dat_coast)
#'
#' #### Example (3): Adjust the detection range
#' get_detection_area_sum(xy, detection_range = 400, coastline = dat_coast)
#' get_detection_area_sum(xy, detection_range = 500, coastline = dat_coast)
#'
#' #### Example (4): Adjust the units
#' get_detection_area_sum(xy, coastline = dat_coast, scale = 1) # m2
#'
#' #### Example (5): Suppress the plot
#' get_detection_area_sum(xy, coastline = dat_coast, plot = FALSE)
#'
#' @author Edward Lavender
#' @export
#'
get_detection_area_sum <- function(xy,
detection_range = 425,
coastline = NULL,
scale = 1 / (1000^2),
plot = TRUE, ...) {
#### Checks
# If xy is empty, return area = 0
if (length(xy) == 0) {
return(0)
}
#### Define detection containers
xy_buf <- get_detection_containers(
xy = xy,
detection_range = detection_range,
coastline = coastline,
plot = plot, ...
)
#### Calculate area (m2) covered by buffers overall
xy_area <- rgeos::gArea(xy_buf) * scale
return(xy_area)
}
######################################
######################################
#### get_detection_area_ts()
#' @title Calculate the area sampled by receivers through time
#' @description This function extends \code{\link[flapper]{get_detection_area_sum}} to calculate how the total area sampled by receivers changes through time.
#'
#' @param xy,detection_range,coastline,scale Arguments required to calculate the total area surveyed by receivers (at each time point) via \code{\link[flapper]{get_detection_area_sum}}. For this function, \code{xy} should be a \code{\link[sp]{SpatialPolygonsDataFrame-class}} object that includes both receiver locations and corresponding deployment times (in columns named `receiver_start_date' and `receiver_end_date' respectively).
#' @param plot A logical input that defines whether or not to plot a time series of the total area sampled by receivers.
#' @param verbose A logical input that defines whether or not to print messages to the console to relay function progress.
#' @param cl,varlist (optional) Parallelisation options. \code{cl} is (a) a cluster object from \code{\link[parallel]{makeCluster}} or (b) an integer that defines the number of child processes. \code{varlist} is a character vector of variables for export (see \code{\link[flapper]{cl_export}}). Exported variables must be located in the global environment. If a cluster is supplied, the connection to the cluster is closed within the function (see \code{\link[flapper]{cl_stop}}). For further information, see \code{\link[flapper]{cl_lapply}} and \code{\link[flapper]{flapper-tips-parallel}}.
#' @param ... Additional arguments, passed to \code{\link[prettyGraphics]{pretty_plot}}, to customise the plot produced.
#'
#' @return The function returns a dataframe with, for each date (`date') from the time of the first receiver's deployment to the time of the last receiver's retrieval, the number of receivers operational on that date (`n') and the total area sampled (`receiver_area'). If \code{plot = TRUE}, the function also returns a plot of the area sampled by receivers through time.
#'
#' @examples
#' #### Define SpatialPointsDataFrame with receiver locations and deployment dates
#' proj_wgs84 <- sp::CRS(SRS_string = "EPSG:4326")
#' proj_utm <- sp::CRS(SRS_string = "EPSG:32629")
#' xy <- sp::SpatialPoints(
#' dat_moorings[, c("receiver_long", "receiver_lat")],
#' proj_wgs84
#' )
#' xy <- sp::spTransform(xy, proj_utm)
#' xy <- sp::SpatialPointsDataFrame(xy, data = dat_moorings)
#'
#' #### Example (1): Implement function with default arguments
#' dat <- get_detection_area_ts(xy)
#'
#' #### Example (2): Adjust detection range, include coastline and use parallel processing
#' # For areas with complex coastline, this will reduce the speed of the algorithm
#' # So we will also supply a cluster to improve the computation time.
#' if (flapper_run_parallel) {
#' dat <- get_detection_area_ts(xy,
#' detection_range = 500,
#' coastline = dat_coast,
#' cl = parallel::makeCluster(2L),
#' varlist = "dat_coast"
#' )
#' }
#'
#' #### Example (3) Hide or customise the plot
#' dat <- get_detection_area_ts(xy, plot = FALSE)
#' dat <-
#' get_detection_area_ts(xy,
#' pretty_axis_args =
#' list(
#' axis = list(
#' list(format = "%b-%y"),
#' list()
#' )
#' ),
#' xlab = "Time (month-year)",
#' ylab = expression(paste("Area (", m^2, ")")),
#' type = "l"
#' )
#'
#' @author Edward Lavender
#' @export
#'
get_detection_area_ts <- function(xy,
detection_range = 425,
coastline = NULL,
scale = 1 / (1000^2),
plot = TRUE,
verbose = TRUE,
cl = NULL,
varlist = NULL, ...) {
#### Checks
t_onset <- Sys.time()
cat_to_console <- function(..., show = verbose) if (show) cat(paste(..., "\n"))
cat_to_console(paste0("flapper::get_detection_area_ts() called (@ ", t_onset, ")..."))
cat_to_console("... Implementing function checks...")
check_class(input = xy, to_class = "SpatialPointsDataFrame", type = "stop")
check_names(input = xy, req = c("receiver_start_date", "receiver_end_date"))
#### Implement algorithm
cat_to_console("... Implementing algorithm...")
rdate_seq <- seq.Date(min(xy$receiver_start_date), max(xy$receiver_end_date), 1)
rcov <- cl_lapply(rdate_seq, cl = cl, varlist = varlist, fun = function(rdate) {
pos <- which(xy$receiver_start_date <= rdate & xy$receiver_end_date >= rdate)
receiver_area <- get_detection_area_sum(
xy = xy[pos, ],
detection_range = detection_range,
coastline = coastline,
scale = scale,
plot = FALSE
)
d <- data.frame(date = rdate, n = length(pos), receiver_area = receiver_area)
return(d)
})
rcov <- dplyr::bind_rows(rcov)
#### Visualise time series
cat_to_console("... Visualising time series")
if (plot) prettyGraphics::pretty_plot(rcov$date, rcov$receiver_area, ...)
#### Return outputs
t_end <- Sys.time()
duration <- difftime(t_end, t_onset, units = "mins")
cat_to_console(paste0("... flapper::get_detection_area_ts() call completed (@ ", t_end, ") after ~", round(duration, digits = 2), " minutes."))
return(rcov)
}
######################################
######################################
#### get_n_operational_ts()
#' @title Calculate the number of operational units through time
#' @importFrom lubridate `%within%`
#'
#' @description This function calculates the number of operational units through time (e.g., the number of individuals at liberty or the number of active acoustic receivers over the course of a study). To implement the function, a dataframe (\code{data}) must be supplied that defines the start and end time of each unit's operational period. Then, for each time step in a user-specified sequence of times, or an automatically generated sequence of times from the earliest start time to the latest end time in \code{data}, the function counts the number of units that were operational on each time step and returns a dataframe (and, if specified, a plot) with this information.
#'
#' @param data A dataframe of observations. At a minimum, this should contain two columns that define the start and end of each unit's operational period, identified by \code{start} and \code{stop} below.
#' @param start A character string that defines the name of the column in \code{data} that defines the start time of each unit's operational period.
#' @param stop A character string that defines the name of the column in \code{data} that defines the end time of each unit's operational period.
#' @param times A vector of times for which to calculate the number of units that were operational at each time. If \code{times = NULL}, a regular sequence of dates from the first to the last date in \code{data} is used.
#' @param plot A logical variable that defines whether or not to plot the time series of the number of operational units.
#' @param ... Additional arguments, passed to \code{\link[prettyGraphics]{pretty_plot}}, to customise the plot.
#'
#' @details This is a simple metric of sampling effort. For acoustic receivers, \code{\link[flapper]{get_detection_area_ts}} provides another metric of sampling effort.
#'
#' @return The function returns a dataframe that, for each time step (`time'), defines the number of operational units at that time (`n'). If \code{plot = TRUE}, the function also plots a time series of the number of operational units.
#'
#' @examples
#' #### Example (1): Number of operational receivers over an acoustic telemetry study
#' dat_n <- get_n_operational_ts(
#' data = dat_moorings,
#' start = "receiver_start_date",
#' stop = "receiver_end_date"
#' )
#' utils::head(dat_n)
#'
#' #### Example (2): Number of individuals at liberty over a tagging study
#' # Define 'tag_end_date' as hypothetical end date of a study
#' # ... and assume that all individuals remained tagged until this time
#' dat_ids$tag_end_date <- as.Date("2017-06-05")
#' dat_n <- get_n_operational_ts(
#' data = dat_ids,
#' start = "tag_start_date",
#' stop = "tag_end_date"
#' )
#'
#' #### Example (3): Specify the time period under consideration
#' dat_n <- get_n_operational_ts(
#' data = dat_ids,
#' start = "tag_start_date",
#' stop = "tag_end_date",
#' times = seq(
#' min(dat_moorings$receiver_start_date),
#' max(dat_moorings$receiver_end_date), 1
#' )
#' )
#'
#' #### Example (4): Suppress or customise the plot
#' dat_n <- get_n_operational_ts(
#' data = dat_ids,
#' start = "tag_start_date",
#' stop = "tag_end_date",
#' plot = FALSE
#' )
#' dat_n <- get_n_operational_ts(
#' data = dat_ids,
#' start = "tag_start_date",
#' stop = "tag_end_date",
#' xlab = "Time", ylab = "N (individuals)",
#' type = "l"
#' )
#'
#' #### Example (5): Additional examples with simulated data
#' # Example with one unit deployed on each day
#' tmp <- data.frame(
#' id = 1:3L,
#' start = as.Date(c("2016-01-01", "2016-01-02", "2016-01-03")),
#' stop = as.Date(c("2016-01-01", "2016-01-02", "2016-01-03"))
#' )
#' get_n_operational_ts(data = tmp, start = "start", stop = "stop")
#' # Example with one unit deployed over a longer period
#' tmp <- data.frame(
#' id = 1:3L,
#' start = as.Date(c("2016-01-01", "2016-01-02", "2016-01-03")),
#' stop = as.Date(c("2016-01-10", "2016-01-02", "2016-01-03"))
#' )
#' get_n_operational_ts(data = tmp, start = "start", stop = "stop")
#'
#' @author Edward Lavender
#' @export
#'
get_n_operational_ts <- function(data, start, stop, times = NULL, plot = TRUE, ...) {
#### Define a sequence of times that span the range of the data, if required.
if (is.null(times)) {
times <- seq(min(data[, start], na.rm = TRUE), max(data[, stop], na.rm = TRUE), by = "days")
}
#### Count the number of operational units at each time step
count <- data.frame(time = times)
count$n <- 0
data$interval <- lubridate::interval(data[, start], data[, stop])
for (i in 1:nrow(count)) {
count$n[i] <- sum(count$time[i] %within% data$interval)
}
#### Plot the results
if (plot) prettyGraphics::pretty_plot(count$time, count$n, ...)
#### Return the dataframe
return(count)
}
######################################
######################################
#### get_id_rec_overlap()
#' @title Calculate the overlap between individuals' time at liberty and receivers' operational periods
#' @description This function calculates the duration of the overlap (in days) between individuals' time at liberty and receivers' operational periods. To implement this function, a dataframe with individual deployment periods and another with receiver deployment periods must be specified. The duration of the overlap between these intervals can be calculated for all combinations of individuals and receivers within these two dataframes, for all combinations of specified individuals and receivers, or for specific individual/receiver pairs. The function returns a dataframe of the overlap duration for these individual/receiver combinations or a vector of values that is matched against another dataframe.
#' @param ids A dataframe that defines individual deployment periods. This must contain a column that defines individual IDs (named `individual_id') and the time of tagging (named `tag_start_date') and time of tag retrieval (`tag_end_date') (see \code{\link[flapper]{dat_ids}} for an example).
#' @param moorings A dataframe that defines receiver deployment periods. This must contain a column that defines receiver IDs (named `receiver_id') and the time of receiver deployment (named `receiver_start_date') and retrieval (named `receiver_end_date') (see \code{\link[flapper]{dat_moorings}} for an example).
#' @param individual_id (optional) A vector of individuals for which to calculate overlap duration.
#' @param receiver_id (optional) A vector of receivers for which to calculate overlap duration.
#' @param type If both \code{individual_id} and \code{receiver_id} are specified, then \code{type} is an integer that defines whether or not to calculate overlap duration for (a) each individual/receiver pair (\code{type = 1L}) or (b) all combinations of specified individuals/receivers (\code{type = 2L}).
#' @param match_to (optional) A dataframe against which to match the calculated overlap duration(s). This must contain an `individual_id' and `receiver_id' column, as in \code{ids} and \code{moorings} respectively. If supplied, an integer vector of overlap durations for individual/receiver combinations, matched against the individuals/receivers in this dataframe, is returned (see also Value).
#'
#' @return The function returns a dataframe with the deployment overlap duration for specific or all combinations of individuals and receivers, with the `individual_id', `receiver_id', `tag_start_date', `tag_end_date', `receiver_start_date' and `receiver_end_date' columns retained, plus `tag_interval' and `receiver_interval' columns that define individual and receiver deployment periods as \code{\link[lubridate]{Interval-class}} objects. The `id_rec_overlap' column defines the temporal overlap (days). Alternatively, if \code{match_to} is supplied, a vector of overlap durations that matches each individual/receiver observation in that dataframe is returned.
#'
#' @examples
#' #### Prepare data to include required columns
#' # moorings requires 'receiver_id', 'receiver_start_date' and 'receiver_end_date'
#' # ids requires 'individual_id', 'tag_start_date' and 'tag_end_date'
#' # These columns are already supplied in the example datasets
#' # ... except tag_end_date:
#' dat_ids$tag_end_date <- as.Date("2017-06-05")
#'
#' #### Example (1): Temporal overlap between all combinations
#' # ... of individuals and receivers
#' dat <- get_id_rec_overlap(dat_ids, dat_moorings)
#'
#' #### Example (2): Temporal overlap between all combinations of specified
#' # ... individuals/receivers
#' dat <- get_id_rec_overlap(dat_ids,
#' dat_moorings,
#' individual_id = c(25, 26),
#' receiver_id = c(3, 4),
#' type = 2L
#' )
#'
#' #### Example (3): Temporal overlap between specified individual/receiver pairs
#' dat <- get_id_rec_overlap(dat_ids,
#' dat_moorings,
#' individual_id = c(25, 26),
#' receiver_id = c(3, 4),
#' type = 1L
#' )
#'
#' #### Example (4): Match temporal overlap to another dataframe
#' dat_acoustics$get_id_rec_overlap <-
#' get_id_rec_overlap(dat_ids,
#' dat_moorings,
#' match_to = dat_acoustics,
#' type = 1L
#' )
#'
#' @author Edward Lavender
#' @export
#'
get_id_rec_overlap <- function(ids,
moorings,
individual_id = NULL,
receiver_id = NULL,
type = 1L,
match_to = NULL) {
#### Checks
# Dataframes must contains required names
check_names(input = ids, req = c("individual_id", "tag_start_date", "tag_end_date"), extract_names = colnames, type = all)
check_names(input = moorings, req = c("receiver_id", "receiver_start_date", "receiver_end_date"), extract_names = colnames, type = all)
if (!is.null(match_to)) check_names(input = match_to, req = c("individual_id", "receiver_id"), extract_names = colnames, type = all)
# Check input to type
type <- check_value(input = type, supp = 1:2L)
#### Define dataframe with individuals and receivers
## Option (1) Both individual_id and receiver_id have been supplied
# ... in which case we will define a dataframe for these specific individuals based on type
if (!is.null(individual_id) & !is.null(receiver_id)) {
# If type == 1, then we will consider each pair of individuals and receivers
if (type == 1L) {
if (length(individual_id) != length(receiver_id)) {
stop("Both 'individual_id' and 'receiver_id' have been specified and type = 1L but length(individual_id) != length(receiver_id).")
}
dat <- data.frame(individual_id = individual_id, receiver_id = receiver_id)
# Otherwise, we will focus on all combinations of specified individuals and receivers
} else if (type == 2L) {
dat <- expand.grid(individual_id = individual_id, receiver_id = receiver_id)
}
## Option (2) Use all combinations of individuals/receivers
} else {
# Filter out any unwanted individuals or receivers
if (!is.null(individual_id)) ids <- ids[which(ids$individual_id %in% individual_id), ]
if (!is.null(receiver_id)) moorings <- moorings[which(moorings$receiver_id %in% receiver_id), ]
# Define dataframe
# This will only include receivers that recorded detections
dat <- expand.grid(
individual_id = unique(ids$individual_id),
receiver_id = unique(moorings$receiver_id)
)
}
#### Define dates
# Define start/end dates for individuals' time at liberty
dat$tag_start_date <- ids$tag_start_date[match(dat$individual_id, ids$individual_id)]
dat$tag_end_date <- ids$tag_end_date[match(dat$individual_id, ids$individual_id)]
# Define start/end dates for receivers' deployment time
dat$receiver_start_date <- moorings$receiver_start_date[match(dat$receiver_id, moorings$receiver_id)]
dat$receiver_end_date <- moorings$receiver_end_date[match(dat$receiver_id, moorings$receiver_id)]
# Define intervals
dat$tag_interval <- lubridate::interval(dat$tag_start_date, dat$tag_end_date)
dat$receiver_interval <- lubridate::interval(dat$receiver_start_date, dat$receiver_end_date)
#### Calculate overlap
# Define the overlap in days, including the first day of overlap (+1)
dat$id_rec_overlap <- lubridate::day(lubridate::as.period(lubridate::intersect(dat$tag_interval, dat$receiver_interval), "days")) + 1
#### Match detection days to another dataframe, if requested
if (!is.null(match_to)) {
dat$key <- paste0(dat$individual_id, "-", dat$receiver_id)
match_to$key <- paste0(match_to$individual_id, "-", match_to$receiver_id)
match_to$id_rec_overlap <- dat$id_rec_overlap[match(match_to$key, dat$key)]
out <- match_to$id_rec_overlap
if (any(is.na(out))) {
message(sum(is.na(out)), "NAs identified in matched vector of id_rec_overlap.")
}
} else {
out <- dat
}
#### Return outputs
return(out)
}
######################################
######################################
#### get_detection_containers_envir()
#' @title Sample environmental conditions around receivers
#' @description This function is used to sample environmental conditions from within the detection containers of receivers. To implement the function, a SpatialPoints object that defines receiver locations (\code{xy}) must be provided, along with the detection range (\code{detection_range}) of receivers. This information is used to define detection containers, via \code{\link[flapper]{get_detection_containers}}. Within each receiver's container, all values of an environmental variable, or a random sample of values, are extracted from a user-defined \code{\link[raster]{raster}} (\code{envir}). Under random sampling, values can be sampled according to a detection probability function (\code{sample_probs}). The function returns a list of dataframes, one for each receiver, that include the sampled values.
#' @param xy,detection_range,coastline,plot,... Arguments required to calculate and visualise detection containers via \code{\link[flapper]{get_detection_containers}}; namely, receiver locations (\code{xy}), the detection range (\code{detection_range}), barriers to detection (\code{coastline}) and whether or not to plot the containers (\code{plot}). Additional arguments can be passed via \code{...} but note that \code{byid} is necessarily \code{TRUE} and should not be provided.
#' @param envir A \code{\link[raster]{raster}} that defines the values of an environmental variable across the study area. The coordinate reference system should be the Universal Transverse Mercator system.
#' @param sample_size (optional) An integer that defines the number of samples of the environmental variable to draw from the area around each receiver (see the `size' argument of \code{\link[base]{sample}}). If this is provided, \code{sample_size} samples are taken from this area; otherwise, all values are extracted.
#' @param sample_replace (optional) If \code{sample_size} is specified, \code{sample_replace} is a logical input that defines whether to implement sampling with (\code{sample_replace = TRUE}, the default) or without (\code{sample_replace = FALSE}) replacement (see the `replace' argument of \code{\link[base]{sample}}).
#' @param sample_probs (optional) If \code{sample_size} is specified, \code{sample_probs} is a function that calculates the detection probability given the distance (m) between a cell and a receiver.
#' @param cl,varlist (optional) Parallelisation options. \code{cl} is (a) a cluster object from \code{\link[parallel]{makeCluster}} or (b) an integer that defines the number of child processes. \code{varlist} is a character vector of variables for export (see \code{\link[flapper]{cl_export}}). Exported variables must be located in the global environment. If a cluster is supplied, the connection to the cluster is closed within the function (see \code{\link[flapper]{cl_stop}}). For further information, see \code{\link[flapper]{cl_lapply}} and \code{\link[flapper]{flapper-tips-parallel}}.
#' @param verbose A logical variable that defines whether or not relay messages to the console to monitor function progress.
#'
#' @return The function returns a list of dataframes (one for each element in \code{xy}; i.e., each receiver), each of which includes the cell IDs of \code{envir} from which values were extracted (`cell'), the value of the environmental variable in that cell (`envir') and, if applicable, the distance between that cell and the receiver (`dist', m) and the detection probability in that cell (`prob').
#'
#' @examples
#' #### Define receiver locations as a SpatialPoints object with a UTM CRS
#' proj_wgs84 <- sp::CRS(SRS_string = "EPSG:4326")
#' proj_utm <- sp::CRS(SRS_string = "EPSG:32629")
#' xy <- sp::SpatialPoints(
#' dat_moorings[, c("receiver_long", "receiver_lat")],
#' proj_wgs84
#' )
#' xy <- sp::spTransform(xy, proj_utm)
#' xy@data <- as.data.frame(xy)
#'
#' #### Example (1): Extract all depth values within each receiver's container
#' depths_by_container <-
#' get_detection_containers_envir(
#' xy = xy,
#' detection_range = 425,
#' coastline = dat_coast,
#' envir = dat_gebco
#' )
#' # The function returns a list of dataframes, one for each receiver
#' # ... with the cell IDs and the value of the environmental variable
#' utils::str(depths_by_container)
#' # Collapse the list and compare conditions across receivers
#' depths_by_container <-
#' lapply(1:length(depths_by_container), function(i) {
#' d <- depths_by_container[[i]]
#' d$receiver_id <- dat_moorings$receiver_id[i]
#' return(d)
#' })
#' depths_by_container <- dplyr::bind_rows(depths_by_container)
#' prettyGraphics::pretty_boxplot(
#' depths_by_container$receiver_id,
#' depths_by_container$envir
#' )
#'
#' #### Example (2): Extract a random sample of values
#' # (We'll keep the values small for speed)
#' depths_by_container <-
#' get_detection_containers_envir(
#' xy = xy,
#' detection_range = 425,
#' coastline = dat_coast,
#' envir = dat_gebco,
#' sample_size = 2
#' )
#' utils::str(depths_by_container)
#'
#' #### Example (3) Extract a random sample of values with weighted probabilities
#' # Define detection probability function based only on distance
#' calc_detection_pr <-
#' function(dist) {
#' dpr <- get_detection_pr(
#' distance = dist,
#' beta_0 = 2.5,
#' beta_1 = -0.01,
#' inv_link = stats::plogis,
#' output = 2L
#' )
#' return(dpr)
#' }
#' # Implement sampling with replacement according to detection probability
#' depths_by_container <-
#' get_detection_containers_envir(
#' xy = xy,
#' detection_range = 425,
#' coastline = dat_coast,
#' envir = dat_gebco,
#' sample_size = 2,
#' sample_probs = calc_detection_pr
#' )
#' # Each element of the outputted list includes the 'cell' and 'envir' column
#' # ... as well as 'dist' and 'prob' that define the distance of that cell
#' # ... from the location in xy and the corresponding detection probability
#' # ... at that distance respectively
#' utils::str(depths_by_container)
#'
#' #### Example (4) Sampling without replacement via sample_replace = FALSE
#' depths_by_container <-
#' get_detection_containers_envir(
#' xy = xy,
#' detection_range = 425,
#' coastline = dat_coast,
#' envir = dat_gebco,
#' sample_size = 2,
#' sample_probs = calc_detection_pr,
#' sample_replace = FALSE
#' )
#' utils::str(depths_by_container)
#'
#' #### Example (5) Parallelise the algorithm via cl and varlist arguments
#' depths_by_container <-
#' get_detection_containers_envir(
#' xy = xy,
#' detection_range = 425,
#' coastline = dat_coast,
#' envir = dat_gebco,
#' sample_size = 2,
#' sample_probs = calc_detection_pr,
#' sample_replace = FALSE,
#' cl = parallel::makeCluster(2L),
#' varlist = c("dat_gebco", "calc_detection_pr")
#' )
#' utils::str(depths_by_container)
#'
#' @author Edward Lavender
#' @export
#'
get_detection_containers_envir <- function(xy,
detection_range,
coastline,
plot = FALSE,
envir,
sample_size = NULL,
sample_replace = TRUE,
sample_probs = NULL,
cl = NULL,
varlist = NULL,
verbose = TRUE, ...) {
#### Checks
t_onset <- Sys.time()
cat_to_console <- function(..., show = verbose) if (show) cat(paste(..., "\n"))