-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathff_functions_library.R
1491 lines (1250 loc) · 72 KB
/
ff_functions_library.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
#################################### LIBRARIES ####################################
library(lubridate)
library(utf8)
library(rgdal)
library(pBrackets)
#################################### HELPER FUNCTIONS ####################################
#LAT/LON TO UTM CONVERSIONS (AND VICE VERSA)
#Converts a matrix of lons and lats (lons first column, lats second column) to UTM
#Inputs:
# LonsLats: [N x 2 matrix] of lons (col 1) and lats (col2)
# utm.zone: [numeric or string], by default 34 (this is where the KRR is)
# southern_hemisphere: [boolean], by default TRUE
# EastingsCol1: whether eastings should be given in first column of output (default) or not
#Outputs:
# EastNorths or NorthEasts: [N x 2 matrix] of Eastings and Northings - eastings are first column by default
latlon.to.utm <- function(LonsLats,EastingsCol1 = TRUE,utm.zone='34',southern_hemisphere=TRUE){
latlons <- data.frame(X=LonsLats[,2],Y=LonsLats[,1])
non.na.idxs <- which(!is.na(latlons$X) & !is.na(latlons$Y))
len <- nrow(latlons)
non.na.latlons <- latlons[non.na.idxs,]
coordinates(non.na.latlons) <- ~Y + X ##HERE
proj4string(non.na.latlons) <- CRS('+proj=longlat +ellps=WGS84 +datum=WGS84')
if(southern_hemisphere){
projection.string <- paste('+proj=utm +zone=',utm.zone, '+ellps=WGS84 +south',sep='')
} else{
projection.string <- paste('+proj=utm +zone=',utm.zone, '+ellps=WGS84 +north',sep='')
}
utm <- spTransform(non.na.latlons,CRS(projection.string))
EastNorths <- matrix(NA,nrow=len,ncol=2)
EastNorths[non.na.idxs,] <- utm@coords
if(!EastingsCol1){
NorthEasts <- EastNorths[,c(2,1)]
return(NorthEasts)
} else{
return(EastNorths)
}
}
#Converts a matrix of eastings and northings (eastings first column, northings second column) to UTM
#Inputs:
# EastNorths: [N x 2 matrix] of eastings (col 1) and northings (col2)
# utm.zone: [numeric or string], by default 34 (this is where the KRR is)
# southern_hemisphere: [boolean], by default TRUE
# LonsCol1: whether lons should be given in first column of output (default) or not
#Outputs:
# LonLats or LatLons: [N x 2 matrix] of longitudes and latitudes - lons are first column by default
utm.to.latlon <- function(EastNorths,LonsCol1=TRUE,utm.zone = '34',southern_hemisphere=TRUE){
utms <- data.frame(X=EastNorths[,1],Y=EastNorths[,2])
non.na.idxs <- which(!is.na(utms$X) & !is.na(utms$Y))
len <- nrow(utms)
if(southern_hemisphere){
projection.string <- paste('+proj=utm +zone=',utm.zone, '+ellps=WGS84 +south',sep='')
} else{
projection.string <- paste('+proj=utm +zone=',utm.zone, '+ellps=WGS84 +north',sep='')
}
non.na.utms <- SpatialPoints(utms[non.na.idxs,],proj4string=CRS(projection.string))
lonlat <- spTransform(non.na.utms,CRS('+proj=longlat +ellps=WGS84 +datum=WGS84'))
LonLats <- matrix(NA,nrow=len,ncol=2)
LonLats[non.na.idxs,] <- lonlat@coords
if(!LonsCol1){
LatLons <- LonLats[,c(2,1)]
return(LatLons)
} else{
return(LonLats)
}
}
### This function outputs the "canonical shape" of a fission-fusion event based on a set of input parameters
# The canonical shape is a u-shaped function defined by the parameters described below
# The input parameters include a set of parameters that will be fitted (x, b1, and b2) as well as a
# set that remains fixed based on the starting and ending times and distances of the two individuals (fixed.parameters)
#Inputs:
# x: [vector] of time points where the function will be evaluated
# b1: [numeric] time point associated with the first "break point" in the u shape
# b2: [numeric] time point associated with the second "break point" in the u shape
# b.y.intercept: [numeric] height of the flat part of the function (from b1 to b2)
# fixed.parameters: [named list] rest of the parameters that are needed to describe the u-shaped function, but which are held fixed and not fitted
# fixed.parameters$x0: initial time point (start of the fission-fusion event)
# fixed.parameters$y0: initial distance apart (at the start of the fission-fusion event)
# fixed.parameters$xf: final time point (end of the fission-fusion event)
# fixed.parameters$yf: final distance apart (at the end of the fission-fusion event)
#Outputs:
# val: [vector] of y values, created by applying the function to the vector of time points
fission_fusion_function <- function(x, b1, b2, b.y.intercept, fixed.parameters){
#extract the fixed parameters
x0 <- fixed.parameters$x0
y0 <- fixed.parameters$y0
xf <- fixed.parameters$xf
yf <- fixed.parameters$yf
#val will hold the y values of the function
val <- rep(NA, length(x))
## Aproach segment
m1 <- (b.y.intercept - y0)/(b1 - x0)
val[which(x < b1)] <- y0 + m1*(x[which(x < b1)]-x0)
## Together segment (flat part)
val[which(x < b2 & x >= b1)] <- b.y.intercept
## Depart segment
m2 <- (yf-b.y.intercept)/(xf - b2)
val[which(x >= b2)] <- b.y.intercept + m2*(x[which(x >= b2)] - b2)
return(val)
}
### Calculate least squared error for fission_fusion_function. This funciton is used for optimizing the
# parameters b1, b2, and b.y.intercept in the function fission.fusion.function for a given fission-fusion event
#Inputs:
# params: [vector] containing the parameters eventually being fitted (b1, b2, and b.y.intercept)
# fixed.parameters: [named list] containing the fixed parameters associated with a given event (to be passed in to fission.fusion.function)
# x: [vector] of time points from the beginning to the end of the fission-fusion event
# y: [vector] of distances between the two individuals during the fission-fusion event
#Outputs:
# error: [numeric] sum of squared error between data (x,y) and model (fission.fusion.function with the specified parameter set)
ls_error <- function(params, fixed.parameters, x, y){
y.fit <- fission_fusion_function(x = x, b1 = params[1], b2 = params[2],
b.y.intercept = params[3], fixed.parameters = fixed.parameters)
error <- sum((y.fit - y)^2, na.rm = TRUE)
return(error)
}
#Calculate the angle between two vectors (i and j) using law of cosines
# The vectors are defined by two end points each (1 and 2)
#Inputs:
# x1.i: [numeric] x value of the first point (1) of the vector i
# x2.i: [numeric] x value of the second point (2) of the vector i
# y1.i: [numeric] y value of the first point (1) of the vector i
# y2.i: [numeric] y value of the second point (2) of the vector i
# x1.j: [numeric] x value of the first point (1) of the vector j
# x2.j: [numeric] x value of the second point (2) of the vector j
# y1.j: [numeric] y value of the first point (1) of the vector j
# y2.j: [numeric] y value of the second point (2) of the vector j
#Outputs:
# angle: angle between the two vectors (in radians)
get_angle_between_vectors <- function(x1.i, x2.i, y1.i, y2.i,
x1.j, x2.j, y1.j, y2.j){
dx.i <- x2.i - x1.i
dy.i <- y2.i - y1.i
dx.j <- x2.j - x1.j
dy.j <- y2.j - y1.j
s.i <- sqrt((x2.i - x1.i)^2 + (y2.i - y1.i)^2)
s.j <- sqrt((x2.j - x1.j)^2 + (y2.j - y1.j)^2)
cos.a <- ((dx.i * dx.j) + (dy.i * dy.j))/(s.i * s.j)
angle <- acos(cos.a)
return(angle)
}
#Read in den locations from a file
#Inputs:
# den.file.path: [string] full path to the file containing the den locations (as well as other locations)
# den.names: [vector of strings] the names of the dens to use (defaults to the dens used for the current study, i.e. 2017 pilot field season)
#Outputs:
# den.locs: data frame containing information about the dens, including
# $name: name of the den
# $lat: latitude coordinate of the den
# $lon: longitude coordinate of the den
# $east: easting coordinate of the den
# $north: northing coordinate of the den
get_dens <- function(den.file.path,
den.names = c('DAVE D','RBEND D','RES M D1','DICK D')){
known.locs <- read.csv(den.file.path,stringsAsFactors=F)
eastsNorths <- latlon.to.utm(cbind(known.locs$lon,known.locs$lat),southern_hemisphere=T,utm.zone=36)
known.locs$east <- eastsNorths[,1]
known.locs$north <- eastsNorths[,2]
den.locs <- known.locs[which(known.locs$name %in% den.names),]
den.locs$name <- as.character(den.locs$name)
return(den.locs)
}
#Calculate spatially discretized heading over time for an individual's trajectory
#The spatially discretized heading of an individual at a given time point is defined as the vector
#pointing from its current location to its location after it has moved a fixed distance R
#Spatially discretized headings are useful to use when individuals often stop moving,
#as the headings of stationary individuals (if calculated using a time window) will bounce around randomly with the GPS noise
#Inputs:
# x: [vector] x coordinates of an individual trajectory
# y: [vector] y coordinates of an individual trajectory
# R: [numeric] spatial radius to use for spatial discretization of the headings
# t.idxs: [vector] time indices at which to calculate the heading
# backward: [boolean] whether to calculate the heading at a given time point based on where it was in the past (backward = T)
# or where it is heading in the future (backward = F). Defaults to F.
# fpt.thresh: [numeric] threshold for the first passage time, below which the heading will not be calculated and will be filled in with NA. This is to prevent individuals from getting 'headings' when they are stationary for too long.
# subsample: [numeric] rate to subsample data at (to save time). Defaults to 1 (use all data, no subsampling)
#Outputs:
# spat.heads: [vector] giving the headings (in radians) of the individual over time
spatial.headings <- function(x,y,R,t.idxs=1:length(x),backward=F, fpt.thresh, subsample = 1){
#initialize
n.times <- length(x)
spat.heads <- rep(NA,n.times)
fpt <- rep(NA,n.times)
#go backwards for backwards vectors
if(backward){
t.idxs <- rev(t.idxs)
}
#loop over all times
for(t in t.idxs){
## Skip time points that aren't a multiple of subsampling unit (start at 0 instead of 1)
if((t-1) %% subsample != 0)
next
#get current location
x0 <- x[t]
y0 <- y[t]
if(is.na(x0)){
next
}
#move forward (or backward) until radius reached
found <- 0
na.found <- 0
time.vec <- t:n.times
if(backward){
time.vec <- seq(t,1,-1)
}
for(j in 1:length(time.vec)){
i <- time.vec[j]
if(backward){
dx <- x0 - x[i]
dy <- y0 - y[i]
} else{
dx <- x[i] - x0
dy <- y[i] - y0
}
dist <- sqrt(dx^2+dy^2)
if(is.na(dist)){
spat.heads[t] <- NA
found <- 1
na.found <- 1
break
}
else{
if(dist >= R){
found <- 1
break
}
}
}
#if you reach the end of the trajectory, return (and leave rest as NAs)
#also make sure that first passage time is less than fpt.thresh
if(found){
if(!na.found & (i - t) <= fpt.thresh){
spat.heads[t] <- atan2(dy,dx)
}
} else{
return(spat.heads)
}
}
return(spat.heads)
}
#Count the number of fission-fusion events per dyad
#Inputs:
# events: [data frame] containing information about the extracted fission-fusion events
# symmetrize: [boolean] indicating whether the lower part of the output matrix should be filled in or not
#Outputs:
# net: [matrix] of size n.inds x n.inds, where net[i,j] gives the number of ff events involving individuals i and j
count_events_per_dyad <- function(events, symmetrize = T){
n.inds <- length(unique(c(events$i, events$j)))
net <- matrix(NA, nrow = n.inds, ncol = n.inds)
for(i in 1:(n.inds-1)){
for(j in (i+1):n.inds){
net[i,j] <- length(which((events$i==i & events$j==j) | (events$i==j & events$j==i)))
if(symmetrize){
net[j,i] <- net[i,j]
}
}
}
return(net)
}
##### Make table of contiguous runs in a vector v
# Helper function for extract ff events and phases
#Inputs:
# v: [vector] Any type of vector
# Outputs:
# runs.table: data frame containing all contiguous runs in vector v with columns values (run value), t0 (first coordinate of run in v) and tf (last coordinate of run in v)
# (Note: Runs of NA's are not recognized, but returned as multiple one-element runs)
make_run_table = function(v){
runs = rle(v)
tf = cumsum(runs$lengths)
t0 = tf+1
t0 = c(1,t0[1:(length(t0)-1)])
if (length(tf)==1){
t0=1
}
runs.table = data.frame(runs$values,t0, tf)
return(runs.table)
}
#################################### MAIN FUNCTIONS ####################################
##### Extract ff events and phases
#This is the main function for extracting fission-fusion events from spatial data, fitting the phases for each event, and classifying them into types
#Inputs:
# xs: [matrix] n.inds x n.times matrix of x coordinates (eastings) for all individuals. xs[i,t] gives the x coordinate of hyena i at time index t
# ys: [matrix] same as xs, but for y coordinates (northings)
# params: [named list] of parameters for extracting ff events, including
# params$R.fusion: [numeric] inner radius for ff events - individuals must come closer to one another than this distance to for something to count as a ff event
# params$R.fission: [numeric] outer radius for ff events - when individuals cross this radius, the ff event begins (or ends)
# params$max.break: [numeric] maximum number of time steps between two events connected by NAs to concatenate them together into 1 event
# params$move.thresh: [numeric] minimum amount moved (meters) to be considered 'moving' during the fusion or fission phase
# params$together.travel.thresh: [numeric] minimum amount moved (meters) to be considered 'moving' during the together phase
# params$local.time.diff: [numeric] time difference between local time and UTC (hours)
# params$den.dist.thresh: [numeric] threshold distance to consider something to be happening 'at the den'
# params$last.day.used: [numeric] last day in the data set to use (this should be the day before the first collar died)
#verbose: [boolean] whether to print progress updates as the function runs
#Outputs:
# together.seqs: data frame containing all the fission-fusion events as rows, with information about each event contained in the columns, including
# together.seqs$i: [numeric] index of the first individual in the ff event
# together.seqs$j: [numeric] index of the second individual in the ff event
# together.seqs$t0: [numeric] time point associated with crossing the R.fusion threshold for the first time in an event (note: this is NOT the beginning of the ff event - for this we need to look back in time to when the individuals crossed the R.fission threshold!)
# together.seqs$tf: [numeric] time point associated with crossing the R.fusion threshold to end the event (note: this is NOT the end of the ff event - for this we need to look to when the individuals cross the R.fission threshold!)
# together.seqs$t.start: [numeric] time point associated with the start of the event (R.fission crossed)
# together.seqs$t.end: [numeric] time point associated with the end of the event (R.fission crossed)
# together.seqs$start.exact: [boolean] whether the start time of the event is exact (will be FALSE if the distance between the pair immediately before t.start is NA)
# together.seqs$end.exact: [boolean] whether the end time of the event is exact (will be FALSE if the distance between the pair immediately after t.end is NA)
# together.seqs$closest.app: [numeric] closest approach distance during the event (m)
# together.seqs$t.closest: [numeric] time index associated with the closest approach during the event
# together.seqs$b1: [numeric] time index associated with the first break point (beginning of the "together phase")
# together.seqs$b2: [numeric] time index assocaited with the second break point (end of the "together phase")
# together.seqs$y.intercept: [numeric] dyadic distance associated with the together phase (the 'height' of the bottom of the "u" of the canonical ff curve)
get_ff_events_and_phases <- function(xs, ys, params, verbose = TRUE){
#Get basic parameters
n.inds <- nrow(xs)
n.times <- ncol(xs)
if(verbose)
print('Computing dyadic distances')
#Compute dyadic distance over time
dyad.dists <- array(NA, dim=c(n.inds, n.inds, n.times))
for (i in 1:n.inds) {
dyad.dists[i,,] <- sqrt( (sweep(xs,2,xs[i,],FUN='-'))^2 + (sweep(ys,2,ys[i,],FUN='-'))^2 )
dyad.dists[i,i,] <- NA
}
################################################################################
#### Identify together sequences
if(verbose) print('Identifying fission-fusion events')
#Get contiguous sequences of "together" times for each pair and store in data frame
#data frame has columns:
# i, j (the two individuals)
# t0, tf (beginning and ending time of 'bout' of being together)
#- find t0, tf as start and end points of runs <100m
together.seqs <- data.frame()
for(i in 1:(n.inds-1)){
for(j in (i+1):n.inds){
dists <- dyad.dists[i,j,]
below.Rfusion = dists<params$R.fusion
runs.table = make_run_table(below.Rfusion) # Table of all runs and their start and end points
true.runs = subset(runs.table, runs.values == TRUE) # Select only runs of TRUEs (below R.fusion)
together.seqs = rbind(together.seqs, data.frame(i=i, j=j, t0=true.runs$t0, tf=true.runs$tf))
}
}
# Aggregate events that are close together in time and separated only by a sequence of NAs of maximum length max.break
together.seqs.orig = together.seqs
together.seqs = data.frame()
for(i in 1:(n.inds-1)){
for(j in (i+1):n.inds){
dists = dyad.dists[i,j,]
sub.together = together.seqs.orig[(together.seqs.orig$i == i & together.seqs.orig$j == j), ]
# identify rows that should be merged (with previous row)
for (r in 2:(nrow(sub.together))){
end_prev = sub.together[r-1,'tf']
start_next = sub.together[r,'t0']
time.between = (start_next-end_prev)-1
if ((time.between <= params$max.break) & sum(is.na(dists[end_prev:start_next]))==time.between){
sub.together[r,'merge.w.prev'] = T} else {sub.together[r,'merge.w.prev']= F
}
}
# merge
runs.table = make_run_table(sub.together$merge.w.prev)
true.runs = subset(runs.table, runs.values == TRUE)
if(nrow(true.runs)>0){
# replace old end with new end
for (l in 1:nrow(true.runs)){
sub.together[true.runs[l,'t0']-1, 'tf'] = sub.together[true.runs[l,'tf'], 'tf']
}
# remove the other rows that have been merged
k=1
while(k<=nrow(sub.together)){
sub.together = sub.together[!((sub.together$t0>sub.together[k,'t0'] & sub.together$t0<=sub.together[k,'tf'])),]
k=k+1
}
}
together.seqs = rbind(together.seqs, sub.together)
}
}
# drop merge column
together.seqs = together.seqs[,c("i", "j", "t0", "tf")]
if(verbose) print('Identifying the correct start and end times of ff events')
#- find t.start and t.end by extending t0 and tf to R.fission threshold (200m)
together.seqs$t.start = together.seqs$t0 # default value (no elongation)
together.seqs$t.end = together.seqs$tf # default value (no elongation)
for(i in 1:nrow(together.seqs)){
ind.i <- together.seqs[i,'i']
ind.j <- together.seqs[i,'j']
t0 <- together.seqs$t0[i]
tf <- together.seqs$tf[i]
dists = dyad.dists[ind.i, ind.j,]
# Find t.start
## Identify time points
prev.dists <- dists[1:t0]
far.times <- which(prev.dists > params$R.fission)
## Exclude events that are too early to have prior data where they are apart
if(length(far.times) > 0){
t.start = max(far.times, na.rm = TRUE)+1
# check if the sequence to be added contains any long NA stretches which should break the seq
to.add = dists[t.start:t0]
runs.table = make_run_table(is.na(to.add))
true.runs = subset(runs.table, runs.values == TRUE)
true.runs$len = true.runs$tf-true.runs$t0
break.runs = subset(true.runs, len >= params$max.break)
# if it does, start after last stretch
if (nrow(break.runs)>0){
last.break = break.runs[nrow(break.runs), 'tf']
t.start = t.start + last.break
}
together.seqs$t.start[i] = t.start
}
# Find t.end
## Identify time points
following.dists <- dists[tf:length(dists)]
far.times <- which(following.dists > params$R.fission)
## Exclude events that are too late to have following data where they are apart
if(length(far.times) > 0){
t.end = tf+min(far.times, na.rm = TRUE)-2
# check if the sequence to be added contains any long NA stretches which should break the seq
to.add = dists[(tf+1):t.end]
runs.table = make_run_table(is.na(to.add))
true.runs = subset(runs.table, runs.values == TRUE)
true.runs$len = true.runs$tf-true.runs$t0
break.runs = subset(true.runs, len >= params$max.break)
# if it does, end before first stretch
if (nrow(break.runs)>0){
first.break = break.runs[1, 't0']
t.end = tf + first.break
}
together.seqs$t.end[i] = t.end
}
}
#- remove duplicates
together.seqs = together.seqs[!duplicated(together.seqs[,c("i", "j", "t.start", "t.end")]),]
# Remove NA's from start and ends of runs
for (r in 1:nrow(together.seqs)){
between.dists = dyad.dists[together.seqs$i[r], together.seqs$j[r], together.seqs$t.start[r]:together.seqs$t.end[r]]
ori.start = together.seqs$t.start[r]
ori.end = together.seqs$t.end[r]
first.non.na = min(which(!is.na(between.dists)))
last.non.na = max(which(!is.na(between.dists)))
together.seqs$t.start[r] = ori.start + first.non.na - 1
together.seqs$t.end[r] = ori.start + last.non.na - 1
}
# Set start.exact and end.exact
start.exact <- end.exact <- rep(TRUE, nrow(together.seqs))
together.seqs$start.exact = start.exact
together.seqs$end.exact = end.exact
# Get whether start and end are exact by checking whether the point right before and right after are NAs
for(r in 1:nrow(together.seqs)){
ind.i <- together.seqs[r,'i']
ind.j <- together.seqs[r,'j']
t.start = together.seqs[r,'t.start']
t.end = together.seqs[r,'t.end']
if (is.na(dyad.dists[ind.i, ind.j, (t.start-1)])){
together.seqs[r, 'start.exact'] = FALSE
}
if (is.na(dyad.dists[ind.i, ind.j, (t.end+1)])){
together.seqs[r, 'end.exact'] = FALSE
}
}
#get closest approach distance
together.seqs$closest.app <- NA
for(i in 1:nrow(together.seqs)){
dists <- dyad.dists[together.seqs$i[i], together.seqs$j[i], together.seqs$t.start[i]:together.seqs$t.end[i]]
together.seqs$closest.app[i] <- min(dists,na.rm=T)
}
#add column for time until next event
together.seqs$dt <- NA
for(i in 1:(n.inds-1)){
for(j in (i+1):n.inds){
rows <- which(together.seqs$i == i & together.seqs$j == j)
dt <- together.seqs$t.start[rows[2:length(rows)]] - together.seqs$t.end[rows[1:(length(rows)-1)]] -1
together.seqs$dt[rows[1:(length(rows)-1)]] <- dt
}
}
#Identify phases
if(verbose)
print('Identifying phases')
together.seqs[,c('b1', 'b2', 'y.intercept')] <- NA
for(r in 1:nrow(together.seqs)){
if(!together.seqs$start.exact[r] | !together.seqs$end.exact[r])
next
y <- dyad.dists[together.seqs$i[r], together.seqs$j[r], together.seqs$t.start[r]:together.seqs$t.end[r]]
x <- together.seqs$t.start[r]:together.seqs$t.end[r]
fp <- list(x0 = x[1],
y0 = y[1],
xf = x[length(x)],
yf = y[length(y)])
p <- constrOptim(theta = c(fp$x0+5, fp$xf-5, .001), f = ls_error, fixed.parameters = fp, x = x, y =y,
ui = matrix(nrow = 7, ncol = 3, byrow = TRUE,
data = c(1,0,0,
-1,0,0,
0,1,0,
0,-1,0,
0,0,1,
0,0,-1,
-1,1,0)),
ci = c(fp$x0+1, -fp$xf-1, fp$x0+1, -fp$xf-1, 0, -fp$yf , 0),
grad = NULL)
together.seqs[r,c('b1', 'b2', 'y.intercept')] <-p$par
}
together.seqs$b1 <- round(together.seqs$b1)
together.seqs$b2 <- round(together.seqs$b2)
return(together.seqs)
}
#### Extract features from fission fusion events
#Inputs:
# xs: [matrix] n.inds x n.times matrix of x coordinates (eastings) for all individuals. xs[i,t] gives the x coordinate of hyena i at time index t
# ys: [matrix] same as xs, but for y coordinates (northings)
# together.seqs: [data frame] of fission-fusion events and associated information (output from get_ff_events_and_phases)
# params: [named list] of parameters for extracting ff events (see above for what it includes)
# den.names: [vector of strings] the names of the dens to use (defaults to the dens used for the current study, i.e. 2017 pilot field season)
# vedbaas: [matrix] of vedba values, of same dimensions and structure as xs and ys matrices
# get.sync.measures: [boolean] whether to calculate the synchrony measures associated with the together phase (this step is computationally intensive)
# sync.subsample: [numeric] by what factor to downsample the data when computing sync measurse (defaults to 10, 1 means no downsampling)
#Outputs:
# together.seqs: [data frame] same as the input, but updated with additional metrics computed including
# displacements during each phase of each individual, duration, phase types and event type, heading correlation, activity synchrony
# (column names should be self-explanatory - see how everything is computed inside the function for details)
get_ff_features <- function(xs, ys, together.seqs, params, den.file.path, den.names, vedbas = vedbas, get.sync.measures = FALSE, sync.subsample = 10){
empty.vec <- rep(NA, nrow(together.seqs))
positions <- data.frame(x.before.i = empty.vec,
x.start.i = empty.vec,
x.b1.i = empty.vec,
x.b2.i = empty.vec,
x.end.i = empty.vec,
x.after.i = empty.vec,
x.closest.i = empty.vec,
y.before.i = empty.vec,
y.start.i = empty.vec,
y.b1.i = empty.vec,
y.b2.i = empty.vec,
y.end.i = empty.vec,
y.after.i = empty.vec,
y.closest.i = empty.vec,
x.before.j = empty.vec,
x.start.j = empty.vec,
x.b1.j = empty.vec,
x.b2.j = empty.vec,
x.end.j = empty.vec,
x.after.j = empty.vec,
x.closest.j = empty.vec,
y.before.j = empty.vec,
y.start.j = empty.vec,
y.b1.j = empty.vec,
y.b2.j = empty.vec,
y.end.j = empty.vec,
y.after.j = empty.vec,
y.closest.j = empty.vec)
### Get locations for relevant time points
idxs.start.end.exact <- which(together.seqs$start.exact & together.seqs$end.exact)
idxs.start.exact <- which(together.seqs$start.exact)
idxs.end.exact <- which(together.seqs$end.exact)
#####i
# start exact
positions$x.start.i[idxs.start.exact] <- xs[cbind(together.seqs$i, together.seqs$t.start)[idxs.start.exact,]]
positions$y.start.i[idxs.start.exact] <- ys[cbind(together.seqs$i, together.seqs$t.start)[idxs.start.exact,]]
#both exact
positions$x.b1.i[idxs.start.end.exact] <- xs[cbind(together.seqs$i, together.seqs$b1)[idxs.start.end.exact,]]
positions$y.b1.i[idxs.start.end.exact] <- ys[cbind(together.seqs$i, together.seqs$b1)[idxs.start.end.exact,]]
positions$x.b2.i[idxs.start.end.exact] <- xs[cbind(together.seqs$i, together.seqs$b2)[idxs.start.end.exact,]]
positions$y.b2.i[idxs.start.end.exact] <- ys[cbind(together.seqs$i, together.seqs$b2)[idxs.start.end.exact,]]
#end exact
positions$x.end.i[idxs.end.exact] <- xs[cbind(together.seqs$i, together.seqs$t.end)[idxs.end.exact,]]
positions$y.end.i[idxs.end.exact] <- ys[cbind(together.seqs$i, together.seqs$t.end)[idxs.end.exact,]]
positions$x.closest.i <- xs[cbind(together.seqs$i, together.seqs$t.closest)]
positions$y.closest.i <- ys[cbind(together.seqs$i, together.seqs$t.closest)]
#####j
# start exact
positions$x.start.j[idxs.start.exact] <- xs[cbind(together.seqs$j, together.seqs$t.start)[idxs.start.exact,]]
positions$y.start.j[idxs.start.exact] <- ys[cbind(together.seqs$j, together.seqs$t.start)[idxs.start.exact,]]
#both exact
positions$x.b1.j[idxs.start.end.exact] <- xs[cbind(together.seqs$j, together.seqs$b1)[idxs.start.end.exact,]]
positions$y.b1.j[idxs.start.end.exact] <- ys[cbind(together.seqs$j, together.seqs$b1)[idxs.start.end.exact,]]
positions$x.b2.j[idxs.start.end.exact] <- xs[cbind(together.seqs$j, together.seqs$b2)[idxs.start.end.exact,]]
positions$y.b2.j[idxs.start.end.exact] <- ys[cbind(together.seqs$j, together.seqs$b2)[idxs.start.end.exact,]]
#end exact
positions$x.end.j[idxs.end.exact] <- xs[cbind(together.seqs$j, together.seqs$t.end)[idxs.end.exact,]]
positions$y.end.j[idxs.end.exact] <- ys[cbind(together.seqs$j, together.seqs$t.end)[idxs.end.exact,]]
positions$x.closest.j <- xs[cbind(together.seqs$j, together.seqs$t.closest)]
positions$y.closest.j <- ys[cbind(together.seqs$j, together.seqs$t.closest)]
##### Extract features
### Displacement - no before or after because they are defined a priori as 100m
together.seqs$disp.fusion.i <- sqrt((positions$x.start.i-positions$x.b1.i)^2 + (positions$y.start.i-positions$y.b1.i)^2)
together.seqs$disp.together.i <- sqrt((positions$x.b2.i-positions$x.b1.i)^2 + (positions$y.b2.i-positions$y.b1.i)^2)
together.seqs$disp.fission.i <- sqrt((positions$x.end.i-positions$x.b2.i)^2 + (positions$y.end.i-positions$y.b2.i)^2)
together.seqs$disp.fusion.j <- sqrt((positions$x.start.j-positions$x.b1.j)^2 + (positions$y.start.j-positions$y.b1.j)^2)
together.seqs$disp.together.j <- sqrt((positions$x.b2.j-positions$x.b1.j)^2 + (positions$y.b2.j-positions$y.b1.j)^2)
together.seqs$disp.fission.j <- sqrt((positions$x.end.j-positions$x.b2.j)^2 + (positions$y.end.j-positions$y.b2.j)^2)
### Time
together.seqs$duration.fusion <- together.seqs$b1 - together.seqs$t.start
together.seqs$duration.together <- together.seqs$b2 - together.seqs$b1
together.seqs$duration.fission <- together.seqs$t.end - together.seqs$b2
### Angle
together.seqs$angle.fusion <- get_angle_between_vectors(x1.i = positions$x.start.i, x2.i = positions$x.b1.i, y1.i = positions$y.start.i, y2.i = positions$y.b1.i,
x1.j = positions$x.start.j, x2.j = positions$x.b1.j, y1.j = positions$y.start.j, y2.j = positions$y.b1.j)
together.seqs$angle.together <- get_angle_between_vectors(x1.i = positions$x.b1.i, x2.i = positions$x.b2.i, y1.i = positions$y.b1.i, y2.i = positions$y.b2.i,
x1.j = positions$x.b1.j, x2.j = positions$x.b2.j, y1.j = positions$y.b1.j, y2.j = positions$y.b2.j)
together.seqs$angle.fission <- get_angle_between_vectors(x1.i = positions$x.b2.i, x2.i = positions$x.end.i, y1.i = positions$y.b2.i, y2.i = positions$y.end.i,
x1.j = positions$x.b2.j, x2.j = positions$x.end.j, y1.j = positions$y.b2.j, y2.j = positions$y.end.j)
#### Categorize into types
#defining clusters - fusion
fusion.stay.move.idxs <- which(together.seqs$disp.fusion.i <= params$move.thresh)
fusion.move.stay.idxs <- which(together.seqs$disp.fusion.j <= params$move.thresh)
fusion.move.move.idxs <- which(together.seqs$disp.fusion.i > params$move.thresh & together.seqs$disp.fusion.j > params$move.thresh)
#defining clusters - together
together.local.idxs <- which(together.seqs$disp.together.i <= params$together.travel.thresh | together.seqs$disp.together.j <= params$together.travel.thresh)
together.travel.idxs <- which(together.seqs$disp.together.i > params$together.travel.thresh & together.seqs$disp.together.j > params$together.travel.thresh)
#defining clusters - fission
fission.stay.move.idxs <- which(together.seqs$disp.fission.i <= params$move.thresh)
fission.move.stay.idxs <- which(together.seqs$disp.fission.j <= params$move.thresh)
fission.move.move.idxs <- which(together.seqs$disp.fission.i > params$move.thresh & together.seqs$disp.fission.j > params$move.thresh)
#store clusters in events data frame
together.seqs$fusion.type <- together.seqs$together.type <- together.seqs$fission.type <- NA
together.seqs$fusion.type[fusion.stay.move.idxs] <- 'fusion.stay.move'
together.seqs$fusion.type[fusion.move.stay.idxs] <- 'fusion.move.stay'
together.seqs$fusion.type[fusion.move.move.idxs] <- 'fusion.move.move'
together.seqs$together.type[together.local.idxs] <- 'together.local'
together.seqs$together.type[together.travel.idxs] <- 'together.travel'
together.seqs$fission.type[fission.stay.move.idxs] <- 'fission.stay.move'
together.seqs$fission.type[fission.move.stay.idxs] <- 'fission.move.stay'
together.seqs$fission.type[fission.move.move.idxs] <- 'fission.move.move'
#combine into event types
together.seqs$event.type <- paste(together.seqs$fusion.type, together.seqs$together.type, together.seqs$fission.type, sep = '__')
#create a column for the collapsed event type (collapsing the symmetry of move.stay and stay.move)
together.seqs$event.type.sym <- together.seqs$event.type
#fusion move.stay --> fusion.stay.move in cases where fission has a mover and a stayer
fusion.move.stay.idxs <- which(together.seqs$fusion.type == 'fusion.move.stay') #get indexes where fusion type is move.stay
fission.asymmetric.idxs <- which(grepl('move',together.seqs$fission.type) & grepl('stay', together.seqs$fission.type)) #get indexes where fusion type is stay.move or move.stay
idxs.to.swap <- intersect(fusion.move.stay.idxs, fission.asymmetric.idxs)
together.seqs$event.type.sym[idxs.to.swap] <- textclean::swap(together.seqs$event.type[idxs.to.swap], 'move','stay')
#fusion.move.stay --> fusion.stay.move in cases where fission has only movers
fission.move.move.idxs <- which(!grepl('stay', together.seqs$fission.type))
idxs.to.change <- intersect(fusion.move.stay.idxs, fission.move.move.idxs)
together.seqs$event.type.sym[idxs.to.change] <- sub('fusion.move.stay', 'fusion.stay.move', together.seqs$event.type[idxs.to.change])
#fission.move.stay --> fission.stay.move in cases where fusion has only movers
fission.move.stay.idxs <- which(together.seqs$fission.type == 'fission.move.stay') #get indexes where fission type is move.stay
fusion.move.move.idxs <- which(!grepl('stay', together.seqs$fusion.type))
idxs.to.change <- intersect(fission.move.stay.idxs, fusion.move.move.idxs)
together.seqs$event.type.sym[idxs.to.change] <- sub('fission.move.stay', 'fission.stay.move', together.seqs$event.type[idxs.to.change])
#distance from nearest den
den.locs <- get_dens(den.file.path, den.names)
dist.to.den.start <- dist.to.den.end <- matrix(nrow = nrow(together.seqs), ncol = nrow(den.locs))
for(i in 1:nrow(den.locs)){
x.d <- den.locs$east[i]
y.d <- den.locs$north[i]
#start of event
dxi <- xs[cbind(together.seqs$i, together.seqs$t.start)] - x.d
dyi <- ys[cbind(together.seqs$i, together.seqs$t.start)] - y.d
ddi <- sqrt(dxi^2 + dyi^2)
dxj <- xs[cbind(together.seqs$j, together.seqs$t.start)] - x.d
dyj <- ys[cbind(together.seqs$j, together.seqs$t.start)] - y.d
ddj <- sqrt(dxj^2 + dyj^2)
dist.to.den.start[,i] <- apply(X = cbind(ddi,ddj), MARGIN = 1, FUN = min, na.rm=T)
#end of event
dxi <- xs[cbind(together.seqs$i, together.seqs$t.end)] - x.d
dyi <- ys[cbind(together.seqs$i, together.seqs$t.end)] - y.d
ddi <- sqrt(dxi^2 + dyi^2)
dxj <- xs[cbind(together.seqs$j, together.seqs$t.end)] - x.d
dyj <- ys[cbind(together.seqs$j, together.seqs$t.end)] - y.d
ddj <- sqrt(dxj^2 + dyj^2)
dist.to.den.end[,i] <- apply(X = cbind(ddi,ddj), MARGIN = 1, FUN = min, na.rm=T)
}
#min dist to den at start and end of events
together.seqs$dist.den.start <- apply(dist.to.den.start, 1, min, na.rm=T)
together.seqs$dist.den.end <- apply(dist.to.den.end, 1, min, na.rm=T)
## Calculate sync measures
if(get.sync.measures == TRUE){
## Heading correlation
together.seqs$together.heading.similarity <- NA
together.seqs$together.heading.samples <- NA
together.seqs$vedba.similarity <- NA
together.seqs$vedba.samples <- NA
pb <- txtProgressBar(min = 0, max = nrow(together.seqs), char = '..ᕕ(ᐛ)ᕗ..', style = 3)
for(r in 1:nrow(together.seqs)){
if(is.na(together.seqs$b1[r]) | is.na(together.seqs$b2[r]))
next
## Headings of individual i
i.heads <- spatial.headings(x = xs[together.seqs$i[r], together.seqs$b1[r]:together.seqs$b2[r]],
y = ys[together.seqs$i[r], together.seqs$b1[r]:together.seqs$b2[r]],
R = 5,
fpt.thresh = 10,
subsample = sync.subsample)
## Headings of individual j
j.heads <- spatial.headings(x = xs[together.seqs$j[r], together.seqs$b1[r]:together.seqs$b2[r]],
y = ys[together.seqs$j[r], together.seqs$b1[r]:together.seqs$b2[r]],
R = 5,
fpt.thresh = 10,
subsample = sync.subsample)
## xs and ys of unit vectors of headings
x.i <- cos(i.heads)
y.i <- sin(i.heads)
x.j <- cos(j.heads)
y.j <- sin(j.heads)
## Dot product of these two vectors
heading.cors <- (x.i*x.j)+(y.i*y.j)
## Save mean of dot products and number of non NA dot products
together.seqs$together.heading.similarity[r] <- mean(heading.cors, na.rm = TRUE)
together.seqs$together.heading.samples[r] <- sum(!is.na(heading.cors))
### Vedba correlation
i.vedba <- vedbas[together.seqs$i[r], together.seqs$b1[r]:together.seqs$b2[r]]
j.vedba <- vedbas[together.seqs$j[r], together.seqs$b1[r]:together.seqs$b2[r]]
if(sum(!is.na(i.vedba + j.vedba)) >= 2){
together.seqs$vedba.similarity[r] <- cor(i.vedba, j.vedba, use = 'complete')
together.seqs$vedba.samples[r] <- sum(!is.na(i.vedba + j.vedba))
}
setTxtProgressBar(pb, r)
}
cat('\n')
}
return(together.seqs)
}
########################## RANDOMIZATION ######################################
#Generate a randomization plan where hyena trajectories from each day will be shuffled
#If rand.params$ensure.no.day.matches == T, make sure that the trajectories don't 'align' on any day
#(i.e. the hyenas are actually randomized to have the same day represented at the same time in the randomized data)
#Inputs:
# rand.params: [named list] of parameters associated with the randomization, including
# rand.params$break.hour: [numeric] which hour to "break" at when randomizing days (0 = midnight, 12 = noon), defaults to 12
# rand.params$last.day.used: [numeric] last day to use in the randomizations (and real data)
# rand.params$den.blocks: [list of vectors of length n.inds] blocks to keep together for each individual (e.g. to keep den attendance roughly constant)
# rand.params$ensure.no.day.matches: [boolean] whether to ensure that no pair of individuals is randomized to the same day
# rand.params$n.rands: [numeric] how many randomizations to do
# max.tries: maximum number of tries at generating the randomization plan before giving up and trying again (only relevant if ensure.no.day.matches == T)
#Outputs:
# rand.plan: [matrix] of dimension n.inds x n.days x n.rands specifying indexes for day swaps. rand.plan[i,j,k] gives the day that should be swapped in for individual i on day j in randomization k
generate_randomization_plan <- function(rand.params, n.inds, max.tries = 10000){
#Set seed for reproducibility
set.seed(177823)
#initialize array to hold randomization plan
n.rands <- rand.params$n.rands
rand.plan <- array(NA, dim = c(n.inds, rand.params$last.day.used, n.rands))
#get blocks
if(is.null(rand.params$blocks)){
#if no blocks specified, all days are counted as one big block
blocks <- list()
for(i in 1:n.inds){
blocks[[i]] <- c(1, rand.params$last.day.used+1)
}
} else{
#if blocks were specified, use those and add end points at 1 and last.day.used
blocks <- rand.params$blocks
for(i in 1:n.inds){
blocks[[i]] <- rand.params$blocks[[i]]
blocks[[i]] <- blocks[[i]][which(blocks[[i]] < rand.params$last.day.used)]
blocks[[i]] <- c(1, blocks[[i]], rand.params$last.day.used+1)
}
}
#generate permutation plans
r <- 1
while(r <= n.rands){
rand.plan.curr <- array(NA, dim = c(n.inds, rand.params$last.day.used))
#generate an initial possibility
for(i in 1:n.inds){
for(j in 1:(length(blocks[[i]])-1)){
d0 <- blocks[[i]][j]
df <- blocks[[i]][j+1] - 1
rand.plan.curr[i,d0:df] <- sample(d0:df, replace=F) #shuffle within block #TODO - fix so don't need to use replace, possible to efficiently find possibilities satisfying constraint?
}
}
converged <- T
if(rand.params$ensure.no.day.matches){
converged <- F
tries <- 1
while(!converged){
uniques <- apply(rand.plan.curr, 2, FUN = function(x){return(length(unique(x)))})
match.cols <- which(uniques < n.inds)
if(length(match.cols)==0){
converged <- T
break
}
if(length(match.cols)>1){
c <- sample(match.cols,1) #get a column at random from the ones that have duplicates
} else{
c <- match.cols
}
dup.inds <- which(duplicated(rand.plan.curr[,c])) #for now this prioritizes keeping the first individual in place and shuffling the next individual
dup.ind <- dup.inds[1]
block <- max(which(blocks[[dup.ind]] <= c))
d0 <- blocks[[dup.ind]][block]
df <- blocks[[dup.ind]][block+1] - 1
rand.plan.curr[dup.ind,d0:df] <- sample(d0:df, replace = F) #try again
tries <- tries + 1
#ensure no infinite looping by setting a maximum number of tries before the whole thing is reinitialized
if(tries > max.tries){
warning('reached maximum number of tries when generating randomization plans - tried again')
break
}
}
}
#add to the big array storing all plans (unless not converged, then try again for the same randomization index)
if(converged){
rand.plan[,,r] <- rand.plan.curr
r <- r +1
}
}
return(rand.plan)
}
########################## ANALYSIS + PLOTTING #################################
#get distributions of phase types
#Inputs:
# together.seqs: [data frame] of information about all ff events (output from get_ff_features)
#Outputs:
# out: [vector] number of events of each type
get_event_type_distributions <- function(together.seqs){
event.types.all <- c('fusion.stay.move__together.local__fission.stay.move',
'fusion.stay.move__together.local__fission.move.stay',
'fusion.stay.move__together.local__fission.move.move',
'fusion.move.move__together.local__fission.stay.move',
'fusion.move.move__together.local__fission.move.move',
'fusion.stay.move__together.travel__fission.stay.move',
'fusion.stay.move__together.travel__fission.move.stay',
'fusion.stay.move__together.travel__fission.move.move',
'fusion.move.move__together.travel__fission.stay.move',
'fusion.move.move__together.travel__fission.move.move')
events.all <- together.seqs$event.type.sym
out <- rep(NA, length(event.types.all))
for(i in 1:length(event.types.all)){
out[i] <- sum(events.all == event.types.all[i])
}
names(out) <- event.types.all
return(out)
}
#remove events around day breaks
#Inputs:
# together.seqs: [data frame] of information about all ff events (output from get_ff_features)
# timestamps: [vector] of timestamps associated with the data in POSIX format
# rand.params: [named list] of randomization parameters (see above for what it includes)
#Outputs:
# together.seqs: [data frame] of information for all ff events, with events spanning day breaks removed
remove_events_around_day_breaks <- function(together.seqs, timestamps, rand.params){
idx.rem <- c()
for(i in 1:nrow(together.seqs)){
t.interval <- seq.POSIXt(from = timestamps[together.seqs$t.start[i]],to = timestamps[together.seqs$t.end[i]], by = 'sec')
break.time <- as.POSIXct(paste(format(t.interval[[1]], '%Y-%m-%d'), paste0(rand.params$break.hour, ':00:00')), tz = tz(timestamps[together.seqs$t.start[i]]))
if(break.time %in% t.interval){
idx.rem <- c(idx.rem, i)
}
}