-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRFunction.R
More file actions
1657 lines (1323 loc) · 56.4 KB
/
Copy pathRFunction.R
File metadata and controls
1657 lines (1323 loc) · 56.4 KB
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
library('move2')
library('lubridate')
library('magrittr')
library('dplyr')
library('ggplot2')
library('data.table')
library('sf')
library('units')
library('tidyr')
library('MRSea')
library("purrr")
library("zoo")
library("spatstat.utils")
library("furrr")
library("future")
library("progressr")
library("patchwork")
#library("splines")
library("rlang")
library("grid")
library("sandwich") # undisclosed dependency of MRSea
`%!in%` <- Negate(`%in%`)
not_null <- Negate(is.null)
# Main RFunction ====================================================================
rFunction = function(data,
travelcut = 3,
altbound = 25,
sunrise_leeway = 0,
sunset_leeway = 0,
create_plots = TRUE,
keepAllCols = FALSE) {
#' TODO (very low priority)
#'
#' - make use of 'dplyr::' consistent
#' - drop "ID" and "timestamp" redefinition and use "mt_" functions instead
#' - improve error messages with {cli}
## Globals --------------------------------------
ggplot2::theme_set(ggplot2::theme_bw())
## Validate Input Data --------------------------------------------
logger.trace(paste0(
"\nInput data provided: \n",
"travelcut: ", toString(travelcut), "\n",
"sunrise_leeway: ", toString(sunrise_leeway), "\n",
"sunset_leeway: ", toString(sunset_leeway), "\n",
"altbound: ", toString(altbound), "\n",
"input data dimensions: ", toString(dim(data))
))
logger.info("Starting input validation")
if(nrow(data) == 0) {
logger.warn("Input data is empty. Returning input.")
return(data)}
### travelcut ----
if(is.null(travelcut)){
logger.fatal("Missing input value for stationary speed upper-bound (`travelcut`). Terminating App.")
stop("Missing input value for stationary speed upper-bound (`travelcut`). Please provide a valid input.")
} else if(travelcut <= 0) {
logger.fatal("Speed upper-bound for stationary behavour (`travelcut`) must be > 0. Terminating App.")
stop("Invalid speed upper-bound for stationary behavour (`travelcut`). Please provide values > 0.")
}
### altbound ----
### (only if column named "altitude" is in input dataset)
if("altitude" %in% colnames(data)){
if(is.null(altbound)){
logger.fatal("Missing input value for altitude change threshold (`altbound`). Terminating App.")
stop("Missing input value for altitude change threshold (`altbound`). Please provide a valid input.")
} else if(altbound < 0) {
logger.fatal("`altbound` must be >= 0. Terminating computation.")
stop("Invalid altitude change threshold (`altbound`). Please provide values >= 0.")
} else if(altbound == 0){
logger.warn(
paste0(" |- Altitude threshold (`altbound`) is set to 0m, and thus ",
"ANY change is altitude will be considered as ascencing/descending ",
"movement.")
)
}
# set with expected units (meters)
altbound <- units::set_units(altbound, "m")
}
### 'leeway' inputs ----
if(is.null(sunrise_leeway)) {
logger.warn(" |- No sunrise leeway provided as input. Defaulting to no leeway.")
sunrise_leeway <- 0
}
if(is.null(sunset_leeway)) {
logger.warn(" |- No sunset leeway provided as input. Defaulting to no leeway.")
sunset_leeway <- 0
}
### Input data: relevant columns -----
if("altitude" %!in% colnames(data)){
logger.warn(" |- Column `altitude` is absent from input data.")
} else{
logger.info(" |- `altitude` column identified. Able to detect altitude changes.")
# ensure `altitude` is in meters
data$altitude <- units::set_units(data$altitude, "m")
}
if ("timestamp_local" %!in% colnames(data)) {
logger.fatal(" |- `timestamp_local` is not comprised in input data. Terminating App execution.")
stop(
paste0(
"Column `timestamp_local` is not comprised in input data. Local time is ",
"a fundamental requirement for the classification process.\n",
" Please deploy the App 'Add Local and Solar Time' earlier in the Workflow ",
"to bind local time to the input dataset."),
call. = FALSE
)
}else{
logger.info(" |- Local Time column identified")
}
if ("sunrise_timestamp" %!in% colnames(data) | "sunset_timestamp" %!in% colnames(data)) {
logger.fatal("`sunrise_timestamp` and/or `sunset timestamp` columns are missing in the input data. Terminating App.")
stop(
paste0(
"`sunrise_timestamp` and/or `sunset timestamp` are not a columns in the ",
"input data.\n Identification of night-time points is fundamental for the ",
"classification process. Please deploy the App 'Add Local and Solar Time' ",
"earlier in the workflow to add the required columns."),
call. = FALSE
)
} else {
logger.info(" |- Sunrise and sunset columns identified. Able to perform night-time identification.")
}
logger.info(" |- Input is in correct format. Proceeding with data preparation.")
## Data Preparation ===========================================================
logger.info("Initiate Data Preparation Steps")
### Generate general variables ------------------------------
logger.info(" |- Generate general variables")
data %<>%
dplyr::mutate(
ID = mt_track_id(.),
timestamp = mt_time(.)
) %>%
# drop events with missing timestamps
dplyr::filter(!is.na(timestamp)) %>%
# order by time within track
arrange(ID, timestamp)
# distinct(timestamp, .keep_all = TRUE)
# Add date label, day hours-since-midnight and hours-since-sunrise (i.e. a proxy for day-light intensity)
data %<>%
mutate(
yearmonthday = gsub("-", "", substr(timestamp_local, 1, 10)),
hrs_since_sunrise =
as.double(
difftime(
lubridate::with_tz(timestamp, lubridate::tz(sunrise_timestamp)), # ensures TZ consistency
sunrise_timestamp,
units = "hour"
))
)
#' NOTE:`timediff_hrs`, `dist_m` & `kmph` are variables expected to provide
#' information between consecutive locations. If the Standardizing App (or
#' other) has been used earlier in the WF, these cols could already be present
#' in the input. However, there is no guarantee input data has not been
#' thinned by other in-between App. For insurance, we (re)generate these
#' columns here.
data %<>%
mutate(
timediff_hrs = as.vector(mt_time_lags(., units = "hours")),
kmph = as.vector(mt_speed(., units = "km/h")),
dist_m = as.vector(mt_distance(., units = "m"))
)
### Identify stationary points -----------------------------------
logger.info(" |- Identify stationary points")
#' Identify stationary points
#' - events with speed <= travelcut == stationary (1),
#' - events where speed > travelcut == non-stationary (0),
#' - events with NA speed == stationary (1)
data %<>%
mutate(
stationary = case_when(
kmph <= travelcut ~ 1,
kmph > travelcut ~ 0,
is.na(kmph) | is.nan(kmph) ~ 1 # assume stationary if no data
)
)
### Detect Altitude Changes -------------------------------------
#' Categorize vertical movement based on altitude change
#' (i) change in altitude to next location > threshold: altchange == "ascent"
#' (ii) change in altitude to next location < -threshold: altchange == "descent"
#' (iii) else (including NAs): altchange == "flatline"
if ("altitude" %in% colnames(data)) {
if(!all(is.na(data$altitude))){
logger.info(" |- Categorize altitude change between consecutive locations")
# Classify altitude changes
data %<>%
# Reset altitude change each day:
group_by(ID, yearmonthday) %>%
dplyr::mutate(
altdiff = dplyr::lead(altitude) - altitude,
altchange = case_when(
altdiff < -altbound ~ "descent",
altdiff > altbound ~ "ascent",
.default = "flatline"
)) %>%
ungroup()
alt_classify <- TRUE
} else{
alt_classify <- FALSE
}
} else {
alt_classify <- FALSE
}
if(!alt_classify){
logger.warn(
paste0(" |- Column `altitude` is either not present in input data or is entirely ",
"filled with NAs - skipping altitude change calculations."))
}
### Night-time identification ----------------------------
#' (i) nightpoint == 0 if sunrise_timestamp < timestamp < sunrise_timestamp (+/- leeway),
#' (ii) otherwise nightpoint == 1
logger.info(" |- Identify night-time locations")
data %<>% mutate(
nightpoint = ifelse(
between(
lubridate::with_tz(timestamp, lubridate::tz(sunrise_timestamp)), # with_tz() ensures TZs consistency
sunrise_timestamp + lubridate::minutes(sunrise_leeway),
sunset_timestamp + lubridate::minutes(sunset_leeway)
),
0, 1)
)
### Calculate ACC variance ----------------------------
#' If ACC data is available, calculate variance in acceleration bursts
#' till subsequent location event - expect one variance statistic for each enabled ACC axes
if ("acc_dt" %in% colnames(data)) {
# logical flag for all-NULL 'acc_dt' column
acc_null <- all(purrr::map_lgl(data$acc_dt, is.null))
if(!acc_null){
logger.info(" |- ACC data identified: calculating variance in acceleration between locations.")
# Unnest ACC data and compute ACC variance between consecutive locations
data <- acc_var(data, interpolate = FALSE) |>
dplyr::select(-acc_dt)
ACCclassify <- TRUE
} else {
data <- dplyr::select(data, -acc_dt)
ACCclassify <- FALSE
}
} else{
ACCclassify <- FALSE
}
if(!ACCclassify) logger.info(" |- No accelerometer data detected in any of the tracks: skipping ACC preparation.")
# Behaviour Classification Steps [1 -7] ========================================================
logger.info("All data prepared. Performing all classification steps")
### [1] Speed Classification -------------------
logger.info("[1] Performing speed classification")
data %<>% mutate(
# Add column to explain classification:
RULE = ifelse(stationary == 1, "[1] Low speed","[1] High speed"),
behav = ifelse(stationary == 1, "SResting", "STravelling")
)
# Log results
logger.info(paste0(" |> ", sum(data$behav == "SResting", na.rm = T), " locations classified as SResting"))
logger.info(paste0(" |> ", sum(data$behav == "STravelling", na.rm = T), " locations classified as STravelling"))
### [2] Altitude Classification --------------------
#' Remaining resting locations reclassified as travelling according to the following rules:
#' (i) If a bird is ascending ==> STravelling
#' (ii) If a bird is descending AND:
#' Next location is ascending/descending ==> STravelling
#' Next location is flatlining ==> remains SResting
#' (iii) If a bird is flatlining, it remains SResting
if(alt_classify){
logger.info("[2] Performing altitude classification")
data %<>%
# QUESTION (BC): shouldn't this step be grouped by bird given we're using `lead()`?
# group_by(ID) %>%
mutate(
RULE = case_when(
(behav == "SResting") & (altchange == "ascent") ~ "[2] Altitude increasing",
(behav == "SResting") & (altchange == "descent") & (lead(altchange) %in% c("descent", "ascent")) ~ "[2] Altitude decreasing",
TRUE ~ RULE
),
behav = case_when(
(behav == "SResting") & (altchange == "ascent") ~ "STravelling",
(behav == "SResting") & (altchange == "descent") & (lead(altchange) %in% c("descent", "ascent")) ~ "STravelling",
TRUE ~ behav
)
)
#### <!> Update stationary status -------------
data <- data |> mutate(stationary = ifelse(behav == "STravelling", 0, stationary))
# Log results
logger.info(paste0(" |> ", sum(data$RULE == "[2] Altitude increasing" | data$RULE == "[2] Altitude decreasing", na.rm = T), " locations re-classified as STravelling"))
} else {
logger.warn("[2] Skipping altitude classification due to absence of altitude data")
}
### [3] Night-time Classification ---------------
#' Remaining resting locations re-classified as (night-time) roosting if they've
#' been identified as a night point (i.e. occurred between sunset and sunrise)
#'
#' NOTE: STravelling locations are kept unchanged, i.e. night-time travelling
#' treated as a valid behaviour
logger.info("[3] Performing night-time classification")
data %<>%
mutate(
RULE = case_when(
(behav == "SResting") & (nightpoint == 1) ~ "[3] Stationary at night",
TRUE ~ RULE
),
behav = case_when(
(behav == "SResting") & (nightpoint == 1) ~ "SRoosting",
TRUE ~ behav
)
)
logger.trace(paste0(" |> ", sum(data$RULE == "[3] Stationary at night", na.rm = T), " locations re-classified as SRoosting"))
#### <!> Estimate ACC thresholds at night-time roosting locations -----
if (ACCclassify == TRUE) {
roostpoints <- data %>%
filter(behav == "SRoosting") %>%
as.data.frame() %>%
group_by(ID) %>%
dplyr::summarise(
thresx = quantile(var_acc_x, probs = 0.95, na.rm = T) %>% as.vector(),
thresy = quantile(var_acc_y, probs = 0.95, na.rm = T) %>% as.vector(),
thresz = quantile(var_acc_z, probs = 0.95, na.rm = T) %>% as.vector()
)
}
### [4] Roosting-site Classification -------------
logger.info("[4] Performing roosting-site classification")
#' Remaining (daytime) resting locations re-classified as roosting if
#' identified as part of a roosting-site, which is defined as:
#'
#' Consecutive stationary locations (`roostgroup`) encompassing night-time
#' locations with total overnight distance travelled less than 15 meters
#' (`roostsite`)
#'
#' NOTE: STravelling locations not affected by this step, even if they were
#' tagged as part of a roost-site
#### [4.1] Identify overnight roosting sites ------
logger.info(" |- Deriving overnight roosting sites.")
data <- add_roost_cols(data, sunrise_leeway, sunset_leeway)
#### [4.2] Apply roosting-site rule ---------
logger.info(" |- Apply roost-site rule")
data %<>%
group_by(ID, roostgroup) %>%
mutate(
# Reclassify any stationary runs that involve an overnight roost to SRoosting
RULE = ifelse(!is.na(roostgroup) & any(roostsite == 1) & (behav != "STravelling"), "[4] Stationary at roost site", RULE),
behav = ifelse(!is.na(roostgroup) & any(roostsite == 1) & (behav != "STravelling"), "SRoosting", behav)
) %>%
ungroup()
# Log results
logger.info(paste0(" |> ", sum(data$RULE == "[4] Stationary at roost site", na.rm = T), " locations re-classified as SRoosting"))
### [5] Non-roosting Stationary Cumulative-time Classification ------------
#' Remaining Resting locations re-classified as Feeding if they are part of a
#' sequence of non-roosting time-points that remain stationary for an
#' unusually long period of time
logger.info("[5] Performing non-roosting stationary cumulative-time classification")
#### [5.1] Derive non-roosting stationary runs -----
data <- add_nonroost_stationary_cols(data)
#### [5.2] Apply non-roosting stationary Rule ---------
#' Re-classify Resting locations assigned with cumulative stationary times
#' that exceed the 95th percentile of stationary run durations. Percentile
#' thresholds are individual-based and calculated from the input data
data %<>%
mutate(
RULE = ifelse(!is.na(cumtimestat) & cumtimestat > dayRunThresh & behav == "SResting", "[5] Extended stationary behaviour", RULE),
behav = ifelse(!is.na(cumtimestat) & cumtimestat > dayRunThresh & behav == "SResting", "SFeeding", behav),
#RULE = ifelse(cumtimestat_pctl < 0.05 & behav == "SResting", "[5] Extended stationary behaviour", RULE),
#behav = ifelse(cumtimestat_pctl < 0.05 & behav == "SResting", "SFeeding", behav),
) %>%
ungroup()
# Log results
logger.trace(paste0(" |> ", sum(data$RULE == "[5] Extended stationary behaviour", na.rm = T), " locations re-classified as SFeeding"))
### [6] Speed-Time Classification --------------
#' Remaining Resting locations re-classified as Feeding if the speed to next
#' location is greater the 97.5th percentile of the predicted stationary
#' speeds at that time of the day (hours-since-sunrise)
logger.info("[6] Performing speed-given-time classification")
#### [6.1] Fit Stationary Speed Vs hour-since-sunrise model ----------------
logger.info(" |- Deriving thresholds for stationary-speed given hours-since-sunrise.")
progressr::handlers("cli")
#' setting parallel processing using availableCores() to set # workers.
#' {future} imports that function from {parallelly}, which is safe to use in
#' container environments (e.g. Docker)
future::plan("cluster", workers = future::availableCores(omit = 1))
progressr::with_progress({
# initiate progress signaler
pb <- progressr::progressor(steps = mt_n_tracks(data))
data <- data |>
group_by(ID) |>
dplyr::group_split() |>
furrr::future_map(
.f = ~speed_time_model(
.x, pb = pb, diag_plots = create_plots, void_non_converging = TRUE
),
.options = furrr_options(
seed = TRUE,
conditions = character(),
packages = c("move2", "MRSea", "dplyr", "lubridate", "rlang",
"purrr", "patchwork", "ggplot2", "grid")
)
) |>
mt_stack()
})
future::plan("sequential")
# data <- data |>
# group_by(ID) |>
# dplyr::group_split() |>
# purrr::map(
# .f = ~speed_time_model(
# .x, pb = NULL, diag_plots = create_plots, void_non_converging = TRUE
# )
# ) |>
# mt_stack()
#### [6.2] Apply speed-time rule ----------------
logger.info(" |- Apply speed-time rule")
data %<>%
ungroup() %>%
mutate(
RULE = ifelse(!is.na(kmphCI97.5) & !is.na(kmph) & kmph > kmphCI97.5 & behav == "SResting", "[6] Exceed Speed-Time threshold", RULE),
behav = ifelse(!is.na(kmphCI97.5) & !is.na(kmph) & kmph > kmphCI97.5 & behav == "SResting", "SFeeding", behav)
)
# Log results
logger.trace(paste0(" |> ", sum(data$RULE == "[6] Exceed Speed-Time threshold", na.rm = T), " locations re-classified as SFeeding"))
### [7] Accelerometer Classification -----
#' Remaining Resting locations re-classified as Feeding if the variance in
#' acceleration to the next location exceeds the 95th percentile of
#' acceleration variation values during night-time roosting, in any of the
#' active accelerometer axis. Percentile thresholds are calculated for each
#' individual from input data.
if (ACCclassify == TRUE) {
logger.info("[7] Performing accelerometer classification")
data %<>%
left_join(roostpoints, by = "ID") %>%
mutate(
RULE = case_when(
# For ACC values that exceed their threshold, reclassify to feeding
(behav == "SResting") & (var_acc_x > thresx) ~ "[7] ACC not similar to roosting",
(behav == "SResting") & (var_acc_y > thresy) ~ "[7] ACC not similar to roosting",
(behav == "SResting") & (var_acc_z > thresz) ~ "[7] ACC not similar to roosting",
TRUE ~ RULE
),
behav = case_when(
# For ACC values that exceed their threshold, reclassify to feeding
(behav == "SResting") & (var_acc_x > thresx) ~ "SFeeding",
(behav == "SResting") & (var_acc_y > thresy) ~ "SFeeding",
(behav == "SResting") & (var_acc_z > thresz) ~ "SFeeding",
TRUE ~ behav
)
) %>%
# Move these attributes to track data:
mt_as_track_attribute(c("thresx", "thresy", "thresz"))
# Log results
logger.trace(paste0(" ", sum(data$RULE == "[7] ACC not similar to roosting", na.rm = T), " locations re-classified as SFeeding"))
}else{
logger.warn("[7] Skipping accelerometer classification due to absence of ACC data in all tracks.")
}
# Summarise classified behaviour
logger.info(" |- Behaviour Classification Summary")
logger.info(paste0(" |> ", sum(data$behav == "SResting", na.rm = T), " locations classified as SResting"))
logger.info(paste0(" |> ", sum(data$behav == "STravelling", na.rm = T), " locations classified as STravelling"))
logger.info(paste0(" |> ", sum(data$behav == "SRoosting", na.rm = T), " locations classified as SRoosting"))
logger.info(paste0(" |> ", sum(data$behav == "SFeeding", na.rm = T), " locations classified as SFeeding"))
## Create plots, if selected ------------------------------------------------------
logger.info("Classification complete. Generating app artifacts")
if(create_plots == TRUE) {
# create simple plot
for (id in unique(mt_track_id(data))) {
birddat <- filter_track_data(data, .track_id = id)
birdplot <- birddat |>
ggplot(aes(x = sf::st_coordinates(birddat)[, 1]/1000, y = sf::st_coordinates(birddat)[, 2]/1000) ) +
geom_path(col = "gray80") +
geom_point(aes(colour = behav)) +
scale_color_brewer(palette = "Set1") +
labs(
title = paste0("Behaviour classification for track ID ", id),
x = "Easting (km)", y = "Northing (km)"
) +
coord_equal()
ggsave(
file = appArtifactPath(paste0("birdtrack_", toString(id), ".png")),
height = 10,
width = 10
)
# birdplot2 <- birddat |>
# mutate(xc = sf::st_coordinates(birddat)[, 1],
# yc = sf::st_coordinates(birddat)[, 2]) |>
# filter(behav != "STravelling") |>
# ggplot(aes(x = xc, y = yc) ) +
# geom_path(col = "gray80") +
# geom_point(aes(colour = behav)) +
# scale_color_brewer(palette = "Set1") +
# labs(
# title = paste0("Behaviour classification for track ID ", id),
# x = "Easting", y = "Northing"
# ) +
# coord_equal()
#
# ggsave(
# file = appArtifactPath(paste0("birdtrack_notravel_", toString(id), ".png")),
# height = 10,
# width = 10
# )
}
}
# Generate summary table
behavsummary <- table(mt_track_id(data), data$behav)
write.csv(behavsummary, file = appArtifactPath("behavsummary.csv"))
## Remove nonessential behavioural columns -----------------------------------
if (keepAllCols == FALSE) {
logger.trace("Removing all nonessential columns")
data %<>% dplyr::select(-any_of(
c(
"ID", "altdiff", "endofday", "endofday_dist_m", "roostsite", "travel01", "cum_trav", "revcumtrav",
"roostgroup", "stationaryNotRoost", "stationary_runLts", "cumtimestat",
"cumtimestat_pctl", "kmphCI2.5", "kmphpreds",
"revcum_trav", "runtime", "dayRunThresh"
)
))
} else {
# Just get rid of the unuseful columns
logger.trace("Removing select nonessential columns")
data %<>% dplyr::select(-any_of(
c(
"ID", "endofday_dist_m", "roostsite", "travel01", "cum_trav", "revcumtrav"
)
))
}
# Return final result
return(data)
}
# Helper Functions ====================================================================
#' //////////////////////////////////////////////////////////////////////////////
#' Compute acceleration variance till next location
#'
acc_var <- function(data, interpolate = FALSE) {
# Store track data for later recall
tracklevel <- mt_track_data(data)
tm_col <- mt_time_column(data)
trk_col <- mt_track_id_column(data)
# Unnest into variances
data <- data |>
dplyr::mutate(
var = purrr::map(acc_dt, \(acc_events){
if(!is.null(acc_events$acc_burst)){
# bind list of matrices (one per ACC event) by row
all_bursts <- do.call(rbind, acc_events$acc_burst)
# variance in each active ACC axis
apply(all_bursts, 2, var)
} else{
NULL
}
},
.progress = "Summarising ACC")
) %>%
tidyr::unnest_wider(var, names_sep = "_") |>
# convert back to move2 object (property lost in the last unnest step)
mt_as_move2(time_column = tm_col, track_id_column = trk_col) |>
# re-append track data
mt_set_track_data(tracklevel)
if (interpolate == TRUE) {
#' Interpolate missing ACCs using the nearest two values on the condition that
#' both values are within 30mins of the location's timestamp
data <- data |>
dplyr::group_by(.data[[trk_col]]) |>
dplyr::mutate(
# add temp columns
null_acc = purrr::map_lgl(acc_dt, is.null),
# max of lag to next and previous locations
acc_max_lag = pmax(
# time till next location
difftime(dplyr::lead(.data[[tm_col]]), .data[[tm_col]], units = "mins"),
# time since previous location
difftime(.data[[tm_col]], dplyr::lag(.data[[tm_col]]), units = "mins"),
na.rm = TRUE)
) |>
dplyr::mutate(
# interpolate, keeping leading/trailing NAs and not interpolating more than 4 consecutive NAs
dplyr::across(dplyr::matches("var_acc_[xyz]"), ~ zoo::na.approx(.x, na.rm = FALSE, maxgap = 4)),
# nullify interpolated values if lag to previous or next location > 30mins
dplyr::across(dplyr::matches("var_acc_[xyz]"), ~ ifelse(null_acc & acc_max_lag > 30, NA, .x))
) |>
# identify locations with interpolated ACC
dplyr::mutate(interpACC = null_acc & !is.na(var_acc_x)) |>
# remove temp columns
dplyr::select(-null_acc, -acc_max_lag) |>
dplyr::ungroup()
}
return(data)
}
#' /////////////////////////////////////////////////////////////////////////////////////////////
#' Derive and add roosting columns to data
#'
#' New columns relevant for classification:
#' - `roostsite`: identifies overnight roosting sites (based on overnight
#' traveled distance < 15m)
#' - `roostgroup`: identifies groups of locations with roost-like behaviour
#' (consecutive non-travelling locations)
#'
add_roost_cols <- function(data, sunrise_leeway, sunset_leeway){
data %<>%
group_by(ID, yearmonthday) %>%
mutate(
temptime = lubridate::with_tz(timestamp, lubridate::tz(sunrise_timestamp)), # ensuring all timestamps are in same tz
# Mark the final and first daytime points in each day
endofday = case_when(
nightpoint == 1 & lag(nightpoint) == 0 ~ "FINAL",
nightpoint == 1 & lead(nightpoint) == 0 ~ "FIRST",
TRUE ~ NA
) ) %>%
# Calculate time difference from each timestamp to sunrise/sunset (and their leeways):
mutate(
sunrise_difference = difftime(temptime, sunrise_timestamp + minutes(sunrise_leeway), units = "mins") %>% abs(),
sunset_difference = difftime(temptime, sunset_timestamp + minutes(sunset_leeway), units = "mins") %>% abs()
) %>%
mutate(closest = case_when(
# Mark the closest timestamps to sunrise/sunset, which will proxy for the absence of night points:
sunrise_difference == min(sunrise_difference, na.rm = T) ~ "SUNRISE",
sunset_difference == min(sunset_difference, na.rm = T) ~ "SUNSET",
TRUE ~ NA
))
logger.trace(" |> Identifying locations for overnight roosting checks")
# Identify which days don't have night points in the morning/at night:
missing_nightpoints <- data %>%
as.data.frame() %>%
group_by(ID, yearmonthday) %>%
summarise(
morning = ifelse(any(endofday == "FIRST"), 1, 0),
evening = ifelse(any(endofday == "FINAL"), 1, 0),
.groups = "keep"
)
# Join to data:
data %<>% left_join(missing_nightpoints, by = c("ID", "yearmonthday"))
# And 'patch' these days up using the sunrise/sunset time-difference proxies:
data %<>% mutate(
endofday = case_when(
# If there is no morning point, but this is the nearest timestamp to sunset,
# use it as a proxy:
is.na(endofday) & is.na(morning) & closest == "SUNRISE" ~ "FIRST",
# Same applies to evening:
is.na(endofday) & is.na(evening) & closest == "SUNSET" ~ "FINAL",
TRUE ~ endofday
)
) %>% dplyr::select(-c("temptime", "morning", "evening", "closest", "sunrise_difference", "sunset_difference"))
# Shortcut for calculating night-distances:
# Filter dataset to only the marked final/first point
# Bind distance using mt_distance and keep only overnight distances
# then merge back into main dataset
logger.trace(" |> Generating overnight roosting distances")
nightdists <- data %>%
filter(!is.na(endofday)) %>%
ungroup() %>%
mutate(
endofday_dist_m = mt_distance(., units = "m"),
endofday_dist_m = ifelse(endofday == "FINAL", endofday_dist_m, NA)
) %>%
as.data.frame() %>%
dplyr::select(c(ID, mt_time_column(.), endofday_dist_m))
data %<>% left_join(nightdists, by = c("ID", mt_time_column(.)))
# This gives us one overnight-distance measure at the end of each bird's day
data %<>% mutate(
roostsite = ifelse(
!is.na(endofday_dist_m) & endofday_dist_m < 15,
1, 0
)
)
logger.trace(" |> Generating roost-group data")
# Calculate cumulative travel and reverse cumulative travel per day
data %<>%
group_by(ID, yearmonthday) %>%
mutate(travel01 = ifelse(stationary == 1, 0, 1)) %>%
mutate(cum_trav = cumsum(travel01),
revcum_trav = spatstat.utils::revcumsum(travel01)) %>%
ungroup() %>%
mutate(
# Generate runs of stationary behaviour before/after final/first location:
roostgroup = ifelse(cum_trav == 0 | revcum_trav == 0, 1, 0),
roostgroup = data.table::rleid(roostgroup),
roostgroup = ifelse(cum_trav != 0 & revcum_trav != 0, NA, roostgroup)
)
}
#' /////////////////////////////////////////////////////////////////////////////////////////////
#' Derive columns required for the non-roosting stationary cumulative time
#'
#' Relevant added columns
#' - `cumtimestat`: cumulative time spent, up to each location, in a run of
#' non-roosting stationary time-points. 0's attributed to locations that are
#' not part of a stationary run
#' - `dayRunThresh`: 95th percentile of stationary run durations, per bird
add_nonroost_stationary_cols <- function(data){
# Generate non-roosting stationary run-length data
data %<>%
group_by(ID) %>%
mutate(
stationaryNotRoost = ifelse(stationary == 1 & behav %!in% c("SRoosting"), 1, 0),
# Adding condition to break runs spreading over large time gaps in GPS
# transmission, in order to stop inflation of run durations in `cumtimestat`.
# For now, hard-coding boundary to 3/4 of 24hrs has a value greater than
# regular and acceptable overnight transmission gaps seen in some studies
stationaryNotRoost = ifelse(stationaryNotRoost == 1 & timediff_hrs > 16, NA, stationaryNotRoost),
stationary_runLts = data.table::rleid(stationaryNotRoost == 1), # id runs of stationary & non-stationary entries
stationary_runLts = ifelse(stationaryNotRoost == 0, NA, stationary_runLts)
) %>%
group_by(ID, stationary_runLts) %>%
mutate(
cumtimestat = cumsum(as.numeric(timediff_hrs)), # compute cumulative time (hrs) spent stationary & non-stationary
cumtimestat = ifelse(stationaryNotRoost == 0 | cumtimestat < 0, 0, cumtimestat)
) %>%
group_by(ID) %>%
mutate(
# cumtimestat_pctl = 1 - (match(cumtimestat, sort(cumtimestat))/(length(which(cumtimestat!="NA")) + 1)), # From original code, which perhaps is not doing what's suppposed to do
cumtimestat_pctl = ifelse(all(is.na(cumtimestat)), NA, 1 - ecdf(cumtimestat)(cumtimestat))
)
# find the duration of every stationary run
eventtimes <- data %>% data.frame() %>%
group_by(ID, stationary_runLts) %>%
summarise(
runtime = suppressWarnings(max(cumtimestat, na.rm = TRUE)),
runtime = ifelse(is.infinite(runtime), 0, runtime),
.groups = "drop"
) %>%
group_by(ID) %>%
mutate(dayRunThresh = quantile(runtime, probs = 0.95))
# add run time back to main data
data %<>% left_join(., eventtimes, by = c("ID", "stationary_runLts"))
data
}
#' /////////////////////////////////////////////////////////////////////////////////////////////
#' Fit stationary-speed given decimal hours-since-sunrise, for one single track
#'
#' @param dt a move2 object for one single track
#' @param pb a Progressor Function generated via `progressr::progressor` to
#' signal updates
#' @param diag_plots logical, whether to generate model diagnostic plots and
#' export them as App artifacts
#' @param model_obj logical, whether to return the fitted model object.
#'
#' @return If `model_obj = TRUE`, a list with: (i) the input data with 3 extra
#' columns for the predicted values and 95% CIs and (ii) the fitted model
#' object. Otherwise, only the input data with model predictions.
#'
speed_time_model <- function(dt,
pb = NULL,
diag_plots = TRUE,
void_non_converging = TRUE,
model_obj = FALSE
){
#browser()
id <- mt_track_id(dt) |> unique() |> as.character()
if(length(id) > 1){
stop("`dt` contains data for more than one track. Please provide a move2 object with a single track")
}
#logger.info(paste0(" |> Fitting model for track ", id, " @ ", lubridate::now()))
logger.info(paste0(" |> Fitting model for track ", id))
# Check number of days covered in dataset
n_days <- round(difftime(max(dt$timestamp), min(dt$timestamp), units = "day"), 1)
n_datadays <- length(unique(dt$yearmonthday))
#' Impose condition where fitting only performed if there is more than 10 days
#' of data, otherwise data deemed insufficient to robustly describe the
#' relationship between stationary speeds and time-of-the-day (expressed as
#' hours-since-sunrise)
if(n_datadays < 10){
logger.warn(
paste0(
" |x Track data reported on < 10 days. This is deemed insufficient to model speed-give-time robustly.\n",
" |i Speed-time classification will not be applied to this track."
))
fit <- NULL
} else {
#' --------------------------------------------------------------------------
#' Partitioning data into 30-day windows, each ID-ed by column `day30window`
cycles <- as.numeric(floor(n_days/30))
if(cycles == 0) cycles <- 1
if(cycles > 1){
cutdata <- max(dt$timestamp)
for(c in 1:(cycles-1)){
cutdata <- c(cutdata, cutdata[c] - days(30))
}
cutdata <- c(cutdata, min(dt$timestamp))
cutdataf <- data.frame(cut = 1:cycles, start = cutdata[length(cutdata):2], end = cutdata[(length(cutdata)-1):1])
dt$day30window <- NA
for(i in 1:nrow(cutdataf)){
dt$day30window <- ifelse(dplyr::between(dt$timestamp, cutdataf$start[i], cutdataf$end[i]), cutdataf$cut[i], dt$day30window)
}
# check that each window has more than 10 days
# merge with previous or next window
# keep going till all windows have >10 days
flag <- 1
while(flag==1){