-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAcousticTagAnalyseLumphus.R
5713 lines (4173 loc) · 330 KB
/
AcousticTagAnalyseLumphus.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
#Delousing efficiency project data analysis
#Adam Brooker
#29th August 2016
# LIST OF FUNCTIONS ------------------------------------------------------------------------------------------------
# 1. locations() = returns a summary matrix of pen locations for all fish
# 2a. batch.locations() = returns a summary matrix of locations for all dayfiles in working directory and saves to an Excel spreadsheet
# 2b. daily.locations() = Daily location summary for loaded dataset
# 3a. depact() = returns depth and activity summary for all fish with standard deviations
# 3b. depact.se() = returns depth and activity summary for all fish with standard errors
# 4. depth.sum() = returns depth summary for each fish
# 5. batch.depth() = creates spreadsheet of mean depths +/- st dev for individual fish over multiple days
# 6. batch.totdepth() = batch function to return matrix of mean and standard error depths for all fish combined over multiple days
# 7. batch.activity() = creates spreadsheet of mean activity +/- st dev for each dayfile in working dir
# 8. batch.totactivity() = batch function to return matrix of mean and standard error activity for all fish combined over multiple days
# 9a. prop.coverage() = calculates fish coverage of pens 7 and 8
# 9b. hmean.prop.coverage() = calculates hourly mean fish coverage of pens 7 and 8
# 10a. batch.coverage() = calculates fish coverage of pens 7 and 8 over multiple days
# 10b. hmean.batch.coverage() = caculates hourly mean fish coverage of pens 7 and 8 over multiple days
# 10c. hmean.day.coverage() = caculates hourly mean fish coverage of pens 12, 14 and 15 over multiple days for loaded dayfile
# 10d. hmean.perfish.coverage() = calculated hourly mean fish coverage per fish over multiple days for loaded dayfile
# 11a. fish.depth(period) = draws a plot of fish depth for the fish id specified
# 11b. fish.act(period) = draws a plot of fish activity for the fish id specified
# 12. fish.3depth(period1, period2, period3) = draws a plot of depths of 3 fish
# 13. fish.plot(period) = draws a plot of fish location for the fish id specified
# 14. fish.3plot(period1, period2, period3) = draws a plot of locations of 3 fish
# 15. add.fish(period, fishcol) = add a fish to the current plot (period = fish id, fishcol = number from 1-20)
# 16a. fish.hexplot(period) = draws a plot of fish location density for the fish id specified
# 16b. hexplot.all(pen) = draws a plot of fish location density for all fish in the specified pen (7 or 8)
# 17. fish.3dplot(period) = draws a 3d plot of fish location and depth
# 18. fish.3dmove(period) = draws a 3d interactive plot of fish location and depth
# 19a. plot.bydepth(period) = draws a plot of fish locations coloured by depth (blue = >15m, red = <15m)
# 19b. plot.byactivity(period) = draws a plot of fish locations coloured by activity
# 19c. plot.bylight(period) = draws a plot of fish locations coloured by time of day (dawn, day, dusk, night)
# 20. add.depthfish(period) = add a fish to the current plot coloured by depth
# 21. fractal() = calculate fractal dimensions for pens 7 & 8 using the box counting method. Returns plot of box counts with fractal dimension and R2
# 22. batch.fractals() = calculate fractal dimensions for each fish over several day files in a folder. Returns an Excel spreadsheet of fractal dimension and R2 for all fish each day
# 23. id.fractals() = calculate fractal dimensions for each fish on one day file. Returns table of fractal dimesions and R2 values and saves to Excel spreadsheet
# 24. plot.bytime(period) = draws a plot of fish locations colour coded according number of time divisions (bins)
# 25. batch.remove(period, start.day, no.days) = Removes single fish id from specified day files
# 26. prop.coverage.3d() = proportion coverage 3D (not sure this is working properly!)
# 27. ma.filter(period, smooth, thresh) = moving average filter function. Period = fish id, smooth = size of smoothing filter, thresh = data removal threshold in metres
# 28. add(period) = add a single fish to a dayfile after cleaning data using ma.filter function
# 29. recode() = function to recode fish speeds and save to dayfile after cleaning data
# 30. batch.subset(variable, factors) = batch function to subset and save data according to specified variable and factors, variable = column to subset by, factors = list of variables in column
# 31a. heatplot.anim(pen, frames) = Create series of plots for animation (pen = pen number 7 or 8, frames = No. of frames, set to No. of hours in dataset)
# 31b. fishplot.anim <- function(pen, frames, framedur, animdur) = Create series of individual fish plots for animation. pen = pen to plot, frames = No. of frames to create, framedur = portion of time to plot for each frame in secs, animdur = length of fish trails in No. of frames (0 = cumulative frames)
# 32. fish.hist(pt) = draw histogram of fish depth or activity from fish files (pt = 'activity' or 'depth')
# 33. load.all() = Load all data files (.csv) in folder into single data frame
# 34. crop(xmin, xmax, ymin, ymax) = Crop edges of dataset to remove multipath
# 35. save() = Save loaded dayfile to .csv file of original name
# 36. distance() = calculate distance travelled for all individual fish in day file
# 37. batch.dist() = calculate distance travelled for all fish files in a folder
# 38. Load.dayfile() = load specified dayfile
# 39. multiplot() = off-the-shelf function to draw multiple ggplots
# 40. headplot() = draws two polar plots of headings for pens 7 and 8
# 41. turnplot() = draws two polar plots of turn angles for pens 7 and 8
# 42. bplot(period, step) = draw turn and velocity plots for period and step specified for whole dayfile
# 43. bcalc() = Perform behaviour calculations for loaded dayfile and add to dayfile
# 44. batch.bscalc() = calculate behaviour states for all dayfiles in working directory and save results to dayfiles
# 45. batch.bsprop() = calculate proportions of behaviour states for each dayfile in working directory
# 50a. bsf(static, cruise, save) = calculate behaviour state frequencies (static, cruise, burst) for pens 7 and 8. static = upper limit of static state, cruise = upper limit of cruise state, save = save plot and data file(T/F)
# 50b. bsf2(save) = calculate behaviour state frequencies (Rr, Rf, Ra, Ep, Ef, Ea) for pens 7 and 8. save = save plot and data file(T/F)
# 51. add.daynum(startday = 1) = Add day number column to dayfile. Specify start day if required.
# 52. save.dayfiles() = Save dataset as dayfiles. Working directory must be location of dataset to save. Creates new folder called 'saved'
# NOTES -------------------------------------------------------------------------------------------------------------
# coverage grid size:
# mean swimming speed = 0.03m/s, max ping rate = 10 sec. Mean distan ce covered between pings = 0.03*10 = 0.3m
# Therefore: grid size = 0.3m
# Need to run the code below to get some functions to work (maybe!)
#library(devtools)
#install_github("plotflow", "trinker")
# ------
library(hexbin)
library(scatterplot3d)
library(rgl)
#Sys.setenv(JAVA_HOME='C:/Program Files/Java/jre7')
library(rJava)
library(XLConnectJars)
library(XLConnect)
library(RColorBrewer)
library(colorspace)
library(colorRamps)
library(stats)
library(ggplot2)
library(animation)
detach("package:dplyr")
library(openxlsx)
library(xlsx)
library(chron)
library(lubridate)
library(magick)
#library(plyr)
#library(plotflow)
library(gridExtra)
library(cowplot)
library(zoo)
library(adehabitat)
library(adehabitatHR)
library(maptools)
library(sp)
library(Rwave)
#library(sowas)
library(WaveletComp)
library(dplyr)
library(tidyr)
library(data.table)
library(emdbook)
library(scales)
#ENTER YOUR VARIABLES HERE
#workingdir = "G:/Data/2018 Lumpfish Husbandry/Data processing/6a. Coded Day CSV" # change to location of data
workingdir <- ifelse(Sys.info()['user'] == 'Laptop', "G:/Data/2018 Lumpfish Husbandry/Data processing/6a. Coded Day CSV/substudies/1. General behaviour/cropped", '/Volumes/My Book/Lumpfish Husbandry') # change to location of data
setwd(workingdir)
dayfile.loc = "R1_LBF18S100197_1_day_coded.csv" # change to file to be analysed
masterfileloc = "G:/Data/2018 Lumpfish Husbandry/AcousticTagFile_2018v6.xlsx" # change to location of AcousticTagFile.xlsx
masterfileloc <- ifelse(Sys.info()['user'] == 'Laptop', "G:/Data/2018 Lumpfish Husbandry/AcousticTagFile_2018v6.xlsx", '/Volumes/My Book/Lumpfish Husbandry/Results/AcousticTagFile_2018v6.xlsx') # change to location of data
workingdir = "H:/Data processing/2016 Conditioning study B/Filtered Data/Recoded Fish CSV/Unconditioned" # change to location of data
dayfile.loc = "run_1LLF16S1007045_fish_coded.csv" # change to file to be analysed
masterfileloc = "H:/Data processing/AcousticTagFile_2016.xlsx" # change to location of AcousticTagFile.xlsx
#new dayfile classes
dayfile.classes = c('NULL', 'numeric', 'numeric', # Period
'factor', # Pen number
'POSIXct', 'double', 'double', 'double', # EchoTime and coordinates
'double', 'double', 'double', 'double', 'double', 'double', 'double', 'double', # calculated swimming parameters
'factor', 'factor', 'factor', 'factor', 'factor', # biofouling, visibility, moon
'factor', 'factor', 'factor', 'factor', 'factor', 'factor', 'factor', 'factor', 'factor', 'factor', 'factor',
'factor', 'factor', 'factor', 'factor', 'factor', 'factor', 'factor', 'factor', 'factor', 'factor', # sea lice numbers
'factor', 'factor', 'factor', 'factor', 'factor', 'factor', 'factor', # Locations
'factor', 'factor', 'factor', # Sun, tide stage and phase
'factor', 'factor', 'factor', # salmon feeding times
'factor', 'factor', 'factor', 'factor', 'factor', 'factor', 'factor',
'factor', 'factor', 'factor', 'factor', 'factor' # Environmental probes
)
#half-coded dayfile classes
dayfile.classes = c('NULL', 'numeric', 'factor', 'factor', 'POSIXct', 'double', 'double',
'double', 'double', 'double', 'double', 'double', 'double', 'double', 'double', 'double', 'factor',
'factor', 'factor', 'factor', 'factor', 'factor', 'factor', 'factor',
'factor', 'factor', 'factor', 'factor', 'factor', 'factor'
)
#old dayfile classes
dayfile.classes = c('NULL', 'numeric', 'factor', 'factor', 'POSIXct', 'double', 'double',
'double', 'double', 'double', 'double', 'double', 'double', 'factor',
'factor', 'factor', 'factor', 'factor', 'factor', 'factor', 'factor',
'double', 'double', 'double', 'double', 'double', 'double', 'double',
'double', 'double', 'double', 'double', 'double', 'double', 'double',
'factor', 'factor', 'factor', 'factor', 'factor', 'factor', 'factor',
'factor', 'factor', 'factor', 'factor', 'factor', 'factor', 'factor',
'factor', 'factor', 'double', 'double', 'double', 'double', 'double',
'double', 'double', 'double', 'double', 'double', 'double', 'double'
)
# uncoded CSV dayfile classes
dayfile.classes = c('NULL', 'NULL', 'NULL', 'NULL', 'character', 'character', 'NULL',
'character', 'character', 'character', 'character', 'NULL', 'NULL',
'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL',
'NULL')
workingdir = "G:/Data/2018 Lumpfish Husbandry/Data processing/6a. Coded Day CSV/hides" # change to location of data
hidefile.loc = "run_1LLF16S100258_day_hides.csv" # change to file to be analysed
hidefile.classes = c('NULL', 'factor', 'NULL', 'factor', 'POSIXct', 'double', 'double', 'double')
# LOAD FILES-------------------------------------------------------------------------------------------------------------------
#LOAD LOCATIONS CODING DATA
locations.lookup <- read.xlsx(masterfileloc, sheetIndex = 11, startRow = 1, endRow = 61, colIndex = seq(1, 7)) # read in codes from Locations Coding spreadsheet
#locations.lookup <- readWorksheetFromFile(masterfileloc, sheet = 12, startRow = 1, endCol = 7) # read in codes from Locations Coding spreadsheet
rownames(locations.lookup) <- locations.lookup$Code
# Load fish IDs
fishids <- xlsx::read.xlsx(masterfileloc, sheetIndex = 3, startRow = 19, endRow = 103, colIndex = 8)
fishids <- as.vector(fishids$Period)
# LOAD DAYFILE
setwd(workingdir)
dayfile <- read.csv(dayfile.loc, header = TRUE, sep = ",", colClasses = dayfile.classes)
dayfile[,c(seq(20, 40, 1), seq(54,65, 1))] <- apply(dayfile[,c(seq(20, 40, 1), seq(54,65, 1))], 2, function(x) as.numeric(as.character(x))) # convert factors to numbers
#)) #read data into table
#SORT BY TIME AND TAG
dayfile <- dayfile[order(dayfile$EchoTime, na.last = FALSE, decreasing = FALSE, method = c("shell")),] # sort by time
dayfile <- dayfile[order(dayfile$Period, na.last = FALSE, decreasing = FALSE, method = c("shell")),] # sort by tag
#LOAD HIDEFILE
setwd(workingdir)
hidefile <- read.csv(hidefile.loc, header = TRUE, sep = ",", colClasses = hidefile.classes)
load.all.hides()
# Temporary code to convert uncoded data into correct formats-------------------------------------
rot.ang <- 14.24 # grid rotation angle in radians
UTMeast <- -1230064.57 # grid origin x-axis
UTMnorth <- 6170474.26 # grid origin y-axis
dayfile$PosX2 <- round((cos(rot.ang*pi/180)*dayfile$PosX-sin(rot.ang*pi/180)*dayfile$PosY)-UTMeast, digits = 2)
dayfile$PosY2 <- round((sin(rot.ang*pi/180)*dayfile$PosX+cos(rot.ang*pi/180)*dayfile$PosY)-UTMnorth, digits = 2)
dayfile$PosX <- dayfile$PosX2
dayfile$PosY <- dayfile$PosY2
dayfile$PosX2 <- NULL
dayfile$PosY2 <- NULL
#CONVERT FIELDS INTO CORRECT FORMATS
water.height <- 35
dayfile$Period <- sapply(dayfile$Period, as.numeric)
dayfile$SubCode <- sapply(dayfile$SubCode, as.numeric)
dayfile[, 'EchoTime'] <- as.POSIXct(strptime(dayfile[,'EchoTime'], "%d/%m/%Y %H:%M:%S", tz = "UTC")) # convert character format to date and time format
dayfile$PosX <- as.numeric(dayfile$PosX)
dayfile$PosY <- as.numeric(dayfile$PosY)
dayfile$PosZ <- as.numeric(dayfile$PosZ)
dayfile$PosZ <- water.height-dayfile$PosZ
# SANDPIT-----------------------------------------------------------------------------------------------------------------
days <- sort(paste0(unique(as.Date(dayfile$EchoTime)), ' 00:00:00')) # create vector of all days in dayfile at midnight for subsetting
# animated 3d plot
plot3d(fish.id$PosX, fish.id$PosY, fish.id$PosZ, pch = 20, xlim = c(0, 35), ylim = c(5, 40), zlim = c(0, 26), xlab = 'X', ylab = 'Y', zlab = 'Z', type = 'l')
dir.create("animation")
for (i in 1:1000){
view3d(userMatrix=rotationMatrix(pi/2 * i/1000, 0, 1, -1))
rgl.snapshot(filename=paste("animation/frame-", sprintf("%03d", i), ".png", sep=""))
}
# hexplot for all fish
bin <- hexbin(dayfile$PosX, dayfile$PosY, xbins = 50)
plot(hexbin(dayfile$PosX, dayfile$PosY, xbins = 50), xlab = 'X', ylab = 'Y')
# pen 7 x,y plots
par(mfrow=c(3,3))
fish.3plot('7829', '8081', '7213')
fish.3plot('7269', '7045', '9229')
fish.3plot('9873', '7381', '9901')
fish.3plot('9453', '7129', '9397')
fish.3plot('8025', '8417', '9649')
fish.plot(9425)
fish.plot(8053)
# pen 8 x,y plots
par(mfrow=c(3,3))
fish.3plot('7857', '7773', '7437')
fish.3plot('9145', '8165', '9173')
fish.3plot('9677', '7745', '8529')
fish.3plot('9033', '7101', '8277')
fish.3plot('8109', '9537', '7661')
fish.plot('7241')
fish.plot('7409')
# pen 7 x,y plot
par(mfrow=c(1,1))
fishpal <- rainbow_hcl(20, c=100, l=63, start=-360, end=-32, alpha = 0.2)
fish.plot('9425')
add.fish('7829', fishcol = fishpal[19])
add.fish('8081', fishcol = fishpal[18])
add.fish('7213', fishcol = fishpal[17])
add.fish('7269', fishcol = fishpal[16])
add.fish('7045', fishcol = fishpal[15])
add.fish('9229', fishcol = fishpal[14])
add.fish('9873', fishcol = fishpal[13])
add.fish('7381', fishcol = fishpal[12])
add.fish('9901', fishcol = fishpal[11])
add.fish('9453', fishcol = fishpal[10])
add.fish('7129', fishcol = fishpal[9])
add.fish('9397', fishcol = fishpal[8])
add.fish('8025', fishcol = fishpal[7])
add.fish('8417', fishcol = fishpal[6])
add.fish('9649', fishcol = fishpal[5])
add.fish('8053', fishcol = fishpal[4])
# pen 8 x,y plot
par(mfrow=c(1,1))
fishpal <- rainbow_hcl(20, c=100, l=63, start=-360, end=-32, alpha = 0.2)
fish.plot('7857')
add.fish('7773', fishcol = fishpal[19])
add.fish('7437', fishcol = fishpal[18])
add.fish('9145', fishcol = fishpal[17])
add.fish('8165', fishcol = fishpal[16])
add.fish('9173', fishcol = fishpal[15])
add.fish('9677', fishcol = fishpal[14])
add.fish('7745', fishcol = fishpal[13])
add.fish('8529', fishcol = fishpal[12])
add.fish('9033', fishcol = fishpal[11])
add.fish('7101', fishcol = fishpal[10])
add.fish('8277', fishcol = fishpal[9])
add.fish('8109', fishcol = fishpal[8])
add.fish('9537', fishcol = fishpal[7])
add.fish('7661', fishcol = fishpal[6])
add.fish('7241', fishcol = fishpal[5])
add.fish('7409', fishcol = fishpal[4])
# pen 7 depth plots
par(mfrow=c(3,3))
fish.3depth('7829', '8081', '7213')
fish.3depth('7269', '7045', '9229')
fish.3depth('9873', '7381', '9901')
fish.3depth('9453', '7129', '9397')
fish.3depth('8025', '8417', '9649')
fish.depth(9425)
fish.depth(8053)
# pen 8 depth plots
par(mfrow=c(3,3))
fish.3depth('7857', '7773', '7437')
fish.3depth('9145', '8165', '9173')
fish.3depth('9677', '7745', '8529')
fish.3depth('9033', '7101', '8277')
fish.3depth('8109', '9537', '7661')
fish.depth('7241')
fish.depth('7409')
# pen 7 x,y plot by depth
par(mfrow=c(1,1))
depthpal <- diverge_hcl(30, h = c(11,266), c = 100, l = c(21,85), power = 0.6, alpha = 0.2)
plot.bydepth('9425')
add.depthfish('7829')
add.depthfish('8081')
add.depthfish('7213')
add.depthfish('7269')
add.depthfish('7045')
add.depthfish('9229')
add.depthfish('9873')
add.depthfish('7381')
add.depthfish('9901')
add.depthfish('9453')
add.depthfish('7129')
add.depthfish('9397')
add.depthfish('8025')
add.depthfish('8417')
add.depthfish('9649')
add.depthfish('8053')
rect(locations.lookup['7EW', 'xmin'], locations.lookup['7EW', 'ymin'], locations.lookup['7EW', 'xmax'], locations.lookup['7EW', 'ymax'], lty = 2) # 7EW edge
rect(locations.lookup['7ES', 'xmin'], locations.lookup['7ES', 'ymin'], locations.lookup['7ES', 'xmax'], locations.lookup['7ES', 'ymax'], lty = 2) # 7ES edge
rect(locations.lookup['7EE', 'xmin'], locations.lookup['7EE', 'ymin'], locations.lookup['7EE', 'xmax'], locations.lookup['7EE', 'ymax'], lty = 2) # 7EE edge
rect(locations.lookup['7EN', 'xmin'], locations.lookup['7EN', 'ymin'], locations.lookup['7EN', 'xmax'], locations.lookup['7EN', 'ymax'], lty = 2) # 7EN edge
rect(locations.lookup['7WHSE', 'xmin'], locations.lookup['7WHSE', 'ymin'], locations.lookup['7WHSE', 'xmax'], locations.lookup['7WHSE', 'ymax'], lty = 3, col = rgb(1, 0.6, 0, 0.4)) # 7WHSE
rect(locations.lookup['7WHNW', 'xmin'], locations.lookup['7WHNW', 'ymin'], locations.lookup['7WHNW', 'xmax'], locations.lookup['7WHNW', 'ymax'], lty = 3, col = rgb(1, 0.6, 0, 0.4)) # 7WHNW
rect(locations.lookup['7EW', 'xmin'], locations.lookup['7ES', 'ymin'], locations.lookup['7EE', 'xmax'], locations.lookup['7EN', 'ymax'], lwd = 2) # cage limits
#legend(32, 42, c(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), fill = depthpal, pch = 20, cex = 0.7)
# pen 8 x,y plot by depth
par(mfrow=c(1,1))
depthpal <- diverge_hcl(30, h = c(11,266), c = 100, l = c(21,85), power = 0.6, alpha = 0.2)
plot.bydepth('7857')
add.depthfish('7773')
add.depthfish('7437')
add.depthfish('9145')
add.depthfish('8165')
add.depthfish('9173')
add.depthfish('9677')
add.depthfish('7745')
add.depthfish('8529')
add.depthfish('9033')
add.depthfish('7101')
add.depthfish('8277')
add.depthfish('8109')
add.depthfish('9537')
add.depthfish('7661')
add.depthfish('7241')
add.depthfish('7409')
rect(locations.lookup['8EW', 'xmin'], locations.lookup['8EW', 'ymin'], locations.lookup['8EW', 'xmax'], locations.lookup['8EW', 'ymax'], lty = 2) # 7EW edge
rect(locations.lookup['8ES', 'xmin'], locations.lookup['8ES', 'ymin'], locations.lookup['8ES', 'xmax'], locations.lookup['8ES', 'ymax'], lty = 2) # 7ES edge
rect(locations.lookup['8EE', 'xmin'], locations.lookup['8EE', 'ymin'], locations.lookup['8EE', 'xmax'], locations.lookup['8EE', 'ymax'], lty = 2) # 7EE edge
rect(locations.lookup['8EN', 'xmin'], locations.lookup['8EN', 'ymin'], locations.lookup['8EN', 'xmax'], locations.lookup['8EN', 'ymax'], lty = 2) # 7EN edge
rect(locations.lookup['8WHSW', 'xmin'], locations.lookup['8WHSW', 'ymin'], locations.lookup['8WHSW', 'xmax'], locations.lookup['8WHSW', 'ymax'], lty = 3, col = rgb(1, 0.6, 0, 0.4)) # 7WHSE
rect(locations.lookup['8WHNE', 'xmin'], locations.lookup['8WHNE', 'ymin'], locations.lookup['8WHNE', 'xmax'], locations.lookup['8WHNE', 'ymax'], lty = 3, col = rgb(1, 0.6, 0, 0.4)) # 7WHNW
rect(locations.lookup['8EW', 'xmin'], locations.lookup['8ES', 'ymin'], locations.lookup['8EE', 'xmax'], locations.lookup['8EN', 'ymax'], lwd = 2) # cage limits
# plot hides
temp <- dayfile
dayfile <- subset(temp, temp$Period == '11805' | temp$Period == '11553' | temp$Period == '11217' | temp$Period == '10965' | temp$Period == '10657' | temp$Period == '10377' | temp$Period == '9761' | temp$Period == '9313')
fishpal <- rainbow_hcl(20, c=100, l=63, start=-360, end=-32, alpha = 0.2)
dayfile$PEN <- '7'
fish.plot(11805)
add.fish('11553', fishcol = fishpal[1])
add.fish('11217', fishcol = fishpal[15])
add.fish('10965', fishcol = fishpal[5])
dayfile$PEN <- '8'
fish.plot(10657)
add.fish('10377', fishcol = fishpal[1])
add.fish('9761', fishcol = fishpal[13])
add.fish('9313', fishcol = fishpal[4])
#1 plot
par(mfrow=c(1,1))
#subset all fish from 1 pen
fish.id <- subset(dayfile, PEN == '7')
#mean fish swim speed
mean(fish.id$MSEC)
#create list of all files in working directory
files <- list.files(path = workingdir, pattern = '*.csv', all.files = FALSE, recursive = FALSE)
# code for manaully removing dead fish ------------------------------------------------------------------------------------
tot.days <- unique(format(as.Date(dayfile$EchoTime, format='%Y-%m-%d %H:%M:%S'), '%Y-%m-%d')) # returns list of days in file
tot.days
dayfile <- dayfile[!(dayfile$Period == 7017),] # remove dead fish
write.csv(dayfile, file = dayfile.loc) #write output to file
# probability density functions
df = ggplot(subset(dayfile, PEN == '7' | PEN == '8'), aes(x=BLSEC, colour = PEN)) + theme(panel.background = element_rect(fill = 'white', colour = 'black'))
df = df + scale_x_log10(breaks = c(0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100), labels = c(0.01, '', '', '', '', '', '', '', '', 0.1, '', '', '', '', '', '', '', '', 1, '', '', '', '', '', '', '', '', 10, '', '', '', '', '', '', '', '', 100))
df = df + scale_y_log10(breaks = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000), labels = c(1, '', '', '', '', '', '', '', '', 10, '', '', '', '', '', '', '', '', 100, '', '', '', '', '', '', '', '', 1000, '', '', '', '', '', '', '', '', 10000))
df + geom_freqpoly(binwidth = 0.5, size = 1)
# calculate behaviour state frequencies
bsffile <- dayfile[,c('Period', 'PEN', 'SEC', 'BLSEC')]
bsffile$BSF <- ifelse(bsffile$BLSEC <= 0.1, 'static', ifelse(bsffile$BLSEC > 0.1 & bsffile$BLSEC <= 1, 'cruise', 'burst'))
#dayfile$BSF <- ifelse(dayfile$BLSEC <= 0.1, 1, ifelse(dayfile$BLSEC > 0.1 & dayfile$BLSEC <= 1, 2, 3))
bsffile$BSFcount <- sequence(rle(bsffile$BSF)$lengths)
bsffile$CountTF <- c(ifelse(diff(bsffile$BSFcount, 1, 1) < 1, T, F), F)
bsfsum <- 0
for (i in 1:nrow(bsffile)){
bsfsum <- bsfsum + bsffile[i, 'SEC']
if(bsffile[i, 'CountTF'] == T & is.na(bsffile[i, 'SEC']) == F){
bsffile[i,'BSFdur'] <- bsfsum
bsfsum <- 0
} else {
bsffile[i,'BSFdur'] <- NA
}
}
# bsffile$round <- ifelse(bsffile$BSFdur < 100, round(bsffile$BSFdur, -1), ifelse(bsffile$BSFdur > 99, bsffile$round <- round(bsffile$BSFdur, -2), bsffile$round <- round(bsffile$BSFdur, -3)))
bsffile$round <- as.numeric(as.character(cut(bsffile$BSFdur, breaks = c(0, 1, 2, 5, 10, 20, 50, 100, 200, 500, 1000), labels = c('1', '2', '5', '10', '20', '50', '100', '200', '500', '1000'))))
# generates table of BSF frequencies and draws plot
dayfile$BSF <- as.factor(dayfile$BSF)
bsftab <- as.data.frame(table(bsffile$round, bsffile$BSF, bsffile$PEN)) # tabulate frequencies of each duration and BSF
names(bsftab) <- c('dur', 'BSF', 'pen', 'freq')
bsftab$dur <- as.numeric(as.character(bsftab$dur))
bsftab$freq <- as.numeric(bsftab$freq)
# bsftab$bin <- .bincode(bsftab$freq, seq(1, 10000, 10))
# df = ggplot(bsftab, aes(x=dur, y=freq, colour = BSF)) + theme(panel.background = element_rect(fill = 'white', colour = 'black'))
sp = ggplot(subset(bsftab, BSF == 'static'), aes(x=dur, y=freq, colour = pen)) + theme(panel.background = element_rect(fill = 'white', colour = 'black'))
sp = sp + scale_x_log10(limits = c(10, 1000), breaks = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000), labels = c(1, '', '', '', '', '', '', '', '', 10, '', '', '', '', '', '', '', '', 100, '', '', '', '', '', '', '', '', 1000, '', '', '', '', '', '', '', '', 10000))
sp = sp + scale_y_log10(breaks = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000), labels = c(1, '', '', '', '', '', '', '', '', 10, '', '', '', '', '', '', '', '', 100, '', '', '', '', '', '', '', '', 1000, '', '', '', '', '', '', '', '', 10000))
sp = sp + geom_path(size = 1) + labs(title = 'Static', x = 'duration', y = 'frequency')
cp = ggplot(subset(bsftab, BSF == 'cruise'), aes(x=dur, y=freq, colour = pen)) + theme(panel.background = element_rect(fill = 'white', colour = 'black'))
cp = cp + scale_x_log10(limits = c(10, 1000), breaks = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000), labels = c(1, '', '', '', '', '', '', '', '', 10, '', '', '', '', '', '', '', '', 100, '', '', '', '', '', '', '', '', 1000, '', '', '', '', '', '', '', '', 10000))
cp = cp + scale_y_log10(breaks = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000), labels = c(1, '', '', '', '', '', '', '', '', 10, '', '', '', '', '', '', '', '', 100, '', '', '', '', '', '', '', '', 1000, '', '', '', '', '', '', '', '', 10000))
cp = cp + geom_path(size = 1) + labs(title = 'Cruise', x = 'duration', y = 'frequency')
bp = ggplot(subset(bsftab, BSF == 'burst'), aes(x=dur, y=freq, colour = pen)) + theme(panel.background = element_rect(fill = 'white', colour = 'black'))
bp = bp + scale_x_log10(limits = c(10, 1000), breaks = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000), labels = c(1, '', '', '', '', '', '', '', '', 10, '', '', '', '', '', '', '', '', 100, '', '', '', '', '', '', '', '', 1000, '', '', '', '', '', '', '', '', 10000))
bp = bp + scale_y_log10(breaks = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000), labels = c(1, '', '', '', '', '', '', '', '', 10, '', '', '', '', '', '', '', '', 100, '', '', '', '', '', '', '', '', 1000, '', '', '', '', '', '', '', '', 10000))
bp = bp + geom_path(size = 1) + labs(title = 'Burst', x = 'duration', y = 'frequency')
plot_grid(sp, cp, bp, align = 'hv', nrow = 2, ncol = 2)
#-------------------------------------------------------------------------------------------------------------------------------
ani.options(interval = 0.01)
saveGIF({
for (i in 1:100){
plot(fish.id[1:i,'PosX'], fish.id[1:i,'PosY'], xlab = 'X (m)', ylab = 'Y (m)', pch = 20, cex = 0.8, xlim = c(5, 36), ylim = c(8, 41), type = 'p', col = fishpal[20]) # tight plot
}
})
fish.id <- subset(dayfile, dayfile$PosY > 10 & dayfile$Period == 7409)
dayfile <- subset(dayfile, !(dayfile$Period == 7409))
dayfile <- rbind(dayfile, fish.id)
fish.id <- subset(dayfile, dayfile$Period == 8949)
fish.id <- subset(fish.id, duplicated(fish.id$EchoTime) == FALSE)
# code to day average env probe data
probe <- probe.DOT2
probe$day <- as.Date(probe$DO.time.2m)
mean.temp2m <- tapply(probe$Temp.2m, probe$day, mean)
# code to create animated gif from sequence of plot images
system.time({
setwd(paste0(workingdir, '/animate'))
files <- list.files(path = paste0(workingdir, '/animate'), pattern = '*.png', all.files = FALSE, recursive = FALSE)
anim.frames <- image_read(files)
animation <- image_animate(anim.frames, fps = 2, loop = 0, dispose = 'previous')
image_write(animation, 'anim.gif')
}
)
# log scale and labels for activity histograms
# conditioned wrasse
hdep + scale_x_log10(breaks = c(0.001, 0.002, 0.003, 0.004, 0.005, 0.006, 0.007, 0.008, 0.009, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.8, 0.09, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10), labels = c('0.001', '', '', '', '', '', '', '', '', '0.01', '', '', '', '', '', '', '', '', '0.1', '', '', '', '', '', '', '', '', '1', '', '', '', '', '', '', '', '', '10')) + scale_y_continuous(limits = c(0, 100000)) + ggtitle('Conditioned wrasse activity histogram')
# unconditioned wrasse
hdep + scale_x_log10(breaks = c(0.001, 0.002, 0.003, 0.004, 0.005, 0.006, 0.007, 0.008, 0.009, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.8, 0.09, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10), labels = c('0.001', '', '', '', '', '', '', '', '', '0.01', '', '', '', '', '', '', '', '', '0.1', '', '', '', '', '', '', '', '', '1', '', '', '', '', '', '', '', '', '10')) + scale_y_continuous(limits = c(0, 100000)) + ggtitle('Unconditioned wrasse activity histogram')
# Analysis of behaviour states
daytemp <- dayfile
dayfile <- subset(daytemp, BS == 'Rr')
bstab <- table(dayfile$BS)
round(bstab/sum(bstab)*100, 2)
# code to create sequence of date/times for env. probe data
start <- as.POSIXct('05/28/18 16:30:00', format = '%m/%d/%y %H:%M:%S', tz = 'GMT')
interval <- 60
end <- start + as.difftime(67, units = 'days')
timeseq <- as.character(seq(from = start, by = interval*30, to = end))
write.csv(timeseq, 'timesequence.csv')
# kernel utilisation distributions using adehabitat
kudcols <- c(brewer.pal(4, 'Accent')[[1]], brewer.pal(4, 'Accent')[[4]]) # create colour palette for KUDs
x <- seq(0, 60, by = 0.5)
y <- seq(0, 60, by = 0.5)
xy <- expand.grid(x=x, y=y)
coordinates(xy) <- ~x+y
gridded(xy) <- TRUE
class(xy)
coords <- dayfile[,c(1, 5, 6)] # extract x,y coords and fish id from dayfile
coordinates(coords) <- c('PosX', 'PosY') # convert to spatial points data frame object
ud <- kernelUD(coords, h = 'href', grid = xy, kern = 'bivnorm') # KUD calculation for adehabitatHR package
mcp100 <- mcp(coords, percent = 100)
ver50 <- getverticeshr(ud, 50) # extract 50% vertex for plotting
ver95 <- getverticeshr(ud, 95) # extract 95% vertex for plotting
plot(mcp100, col = NULL, axes = T, xlim = c(10, 45), ylim = c(0, 45)) # plot MCP100
plot(ver95, col = kudcols[[1]], axes = F, xlim = c(10, 45), ylim = c(0, 45), add=T) # plot KUD95
plot(ver50, col = kudcols[[2]], axes = F, xlim = c(10, 45), ylim = c(0, 45), add=T) # plot KUD50
ka <- kernel.area(ud, percent = c(50, 95), unin = 'm', unout = 'm2') # calculates area of KUD50, KUD95 and MCP100
ud <- kernelUD(dayfile[,5:6], h = 'href', grid = 50, same4all = T, kern = 'bivnorm') # KUD calculation for adehabitat package
mcpest <- mcp(dayfile[,5:6], id = dayfile$Period, percent = 100)
getvolumeUD(ud)
image(ud, axes = T, addpoints = F, xlim = c(0, 45))
image.khr(ud, addpoints = F, axes = T, xlim = c(10, 45), ylim = c(10, 50))
plot(mcpest, xlim = c(10, 45), ylim = c(0, 45))
par(new=T)
plot(ver, xlim = c(10, 45), ylim = c(0, 45), axes = F, fg = 'blue')
par(new=F)
# Code to calculate KUD50 and KUD95 for all fish in loaded dayfile and save as csv-----------------------------------------------------------
# N.B. this code will only work properly if all fish are from the same pen, so loading all fish from one group works best
fish <- unique(dayfile$Period)
if(unique(dayfile$PEN == 7)){
x <- seq(0, 50, by = 0.5)
y <- seq(0, 50, by = 0.5)
xy <- expand.grid(x=x, y=y)
coordinates(xy) <- ~x+y
gridded(xy) <- TRUE
class(xy)
} else {
x <- seq(25, 70, by = 0.5)
y <- seq(0, 50, by = 0.5)
xy <- expand.grid(x=x, y=y)
coordinates(xy) <- ~x+y
gridded(xy) <- TRUE
class(xy)
}
kud50 <- numeric()
kud95 <- numeric()
kudtab <- data.frame()
for (i in 1:length(fish)){
daytemp <- subset(dayfile, Period == fish[[i]])
coords <- daytemp[,c(1, 5, 6)] # extract x,y coords and fish id from dayfile
coordinates(coords) <- c('PosX', 'PosY') # convert to spatial points data frame object
ud <- kernelUD(coords, h = 'href', grid = xy, kern = 'bivnorm') # KUD calculation for adehabitatHR package
ka <- kernel.area(ud, percent = c(50, 95), unin = 'm', unout = 'm2') # calculates area of KUD50, KUD95
kud50 <- c(kud50, ka[1,1])
kud95 <- c(kud95, ka[2,1])
}
kudtab <- cbind(fish, kud50, kud95)
# Code to calculate 3D KUD50 and KUD95 for all fish in loaded dayfile and save as csv-----------------------------------------------------------
fish <- unique(dayfile$Period)
if(unique(dayfile$PEN == 7)){
x <- seq(0, 50, by = 0.5)
y <- seq(0, 50, by = 0.5)
xy <- expand.grid(x=x, y=y)
coordinates(xy) <- ~x+y
gridded(xy) <- TRUE
class(xy)
} else {
x <- seq(25, 70, by = 0.5)
y <- seq(0, 50, by = 0.5)
xy <- expand.grid(x=x, y=y)
coordinates(xy) <- ~x+y
gridded(xy) <- TRUE
class(xy)
}
kud50 <- numeric()
kud95 <- numeric()
kudtab <- data.frame()
max.depth <- ceiling(max(dayfile$PosZ))
for (i in 1:length(fish)){
daytemp <- subset(dayfile, Period == fish[[i]])
#depth <- 0
k50 <- 0
k95 <- 0
for (j in 1:max.depth){
depthtemp <- subset(daytemp, PosZ > j-1 & PosZ < j)
if (nrow(depthtemp) >4){
coords <- depthtemp[,c(1, 5, 6)] # extract x,y coords and fish id from dayfile
coordinates(coords) <- c('PosX', 'PosY') # convert to spatial points data frame object
ud <- kernelUD(coords, h = 'href', grid = xy, kern = 'bivnorm') # KUD calculation for adehabitatHR package
ka <- kernel.area(ud, percent = c(50, 95), unin = 'm', unout = 'm2') # calculates area of KUD50, KUD95
k50 <- k50 + ka[1,1]
k95 <- k95 + ka[2,1]
#depth <- depth+1
} else {
k50 <- k50 + 0
k95 <- k95 + 0
#depth <- depth+1
}
}
kud50 <- c(kud50, k50)
kud95 <- c(kud95, k95)
}
kudtab <- cbind(fish, kud50, kud95)
# code to add day number to dayfile (need to do this for KUD code to work)
exp.dates <- unique(as.Date(dayfile$EchoTime))
exp.start <- 258
exp.length <- 29
exp.days <- seq(exp.start, exp.start+exp.length-1, 1)
names(exp.days) <- exp.dates
dayfile$day <- as.numeric(exp.days[as.character(as.Date(dayfile$EchoTime))])
# code to calculate cumulative KUD50s and KUD95s for each fish in loaded dayfile and save as csv -------------------------------------------
fish <- unique(dayfile$Period)
if(unique(dayfile$PEN == 7)){
x <- seq(0, 50, by = 0.5)
y <- seq(0, 50, by = 0.5)
xy <- expand.grid(x=x, y=y)
coordinates(xy) <- ~x+y
gridded(xy) <- TRUE
class(xy)
} else {
x <- seq(25, 70, by = 0.5)
y <- seq(0, 50, by = 0.5)
xy <- expand.grid(x=x, y=y)
coordinates(xy) <- ~x+y
gridded(xy) <- TRUE
class(xy)
}
kud50.cum <- data.frame()
kud95.cum <- data.frame()
for (i in 1:length(fish))
{
kud50 <- numeric()
kud95 <- numeric()
fishsub <- subset(dayfile, Period == fish[[i]])
days <- unique(fishsub$day)
prevdays <- dayfile[1,]
prevdays <- prevdays[-c(1),]
for (j in 1:length(unique(fishsub$day)))
{
daysub <- rbind(prevdays, subset(fishsub, day == days[[j]]))
coords <- daysub[,c(1, 5, 6)] # extract x,y coords and fish id from dayfile
coordinates(coords) <- c('PosX', 'PosY') # convert to spatial points data frame object
ud <- kernelUD(coords, h = 'href', grid = xy, kern = 'bivnorm') # KUD calculation for adehabitatHR package
ka <- kernel.area(ud, percent = c(50, 95), unin = 'm', unout = 'm2') # calculates area of KUD50, KUD95
kud50 <- c(kud50, ka[1,1])
kud95 <- c(kud95, ka[2,1])
prevdays <- daysub
}
kud50.cum <- rbind(kud50.cum, kud50)
kud95.cum <- rbind(kud95.cum, kud95)
}
kud50.cum <- t(kud50.cum)
rownames(kud50.cum) <- days
colnames(kud50.cum) <- fish
kud95.cum <- t(kud95.cum)
rownames(kud95.cum) <- days
colnames(kud95.cum) <- fish
#plot cumulative kuds for all fish
par(mfrow=c(1,2))
plot(kud50.cum[,as.character(fish[1])], type = 'o', ylim = c(0,signif(max(kud50.cum), 2)))
for (k in 2:length(fish)){lines(kud50.cum[,as.character(fish[k])], type = 'o')}
plot(kud95.cum[,as.character(fish[1])], type = 'o', ylim = c(0,signif(max(kud95.cum), 2)))
for (k in 2:length(fish)){lines(kud95.cum[,as.character(fish[k])], type = 'o')}
par(mfrow=c(1,1))
# calculate asymptotes
asym <- numeric()
for (m in 1:length(fish))
{
kuddiff <- round(c(NA, abs(diff(kud50.cum[,as.character(fish[m])], 1)))/kud50.cum[,as.character(fish[m])], 3)
for (n in 2:(length(kuddiff)-1))
{
if (kuddiff[n] <0.05 & kuddiff[n+1] <0.05){
day.asym <- n+1
break
} else {
day.asym <- NA
}
}
asym <- c(asym, day.asym)
}
asym <- as.double(rownames(kud50.cum)[1])+asym-1
kud50.cum <- rbind(kud50.cum, asym)
asym <- numeric()
for (m in 1:length(fish))
{
kuddiff <- round(c(NA, abs(diff(kud95.cum[,as.character(fish[m])], 1)))/kud95.cum[,as.character(fish[m])], 3)
for (n in 2:(length(kuddiff)-1))
{
if (kuddiff[n] <0.05 & kuddiff[n+1] <0.05){
day.asym <- n+1
break
} else {
day.asym <- NA
}
}
asym <- c(asym, day.asym)
}
asym <- as.double(rownames(kud95.cum)[1])+asym-1
kud95.cum <- rbind(kud95.cum, asym)
write.csv(kud50.cum, 'cumulativeKUD50.csv')
write.csv(kud95.cum, 'cumulativeKUD95.csv')
# code to calculate index of reuse (IOR) for each fish in loaded dayfile and save as csv -------------------------------------------
fish <- unique(dayfile$Period)
if(unique(dayfile$PEN == 7)){
x <- seq(0, 50, by = 0.5)
y <- seq(0, 50, by = 0.5)
xy <- expand.grid(x=x, y=y)
coordinates(xy) <- ~x+y
gridded(xy) <- TRUE
class(xy)
} else {
x <- seq(25, 70, by = 0.5)
y <- seq(0, 50, by = 0.5)
xy <- expand.grid(x=x, y=y)
coordinates(xy) <- ~x+y
gridded(xy) <- TRUE
class(xy)
}
kud50.ior <- data.frame()
kud95.ior <- data.frame()
for (i in 1:length(fish))
{
ior50 <- numeric()
ior95 <- numeric()
fishsub <- subset(dayfile, Period == fish[[i]])
days <- unique(fishsub$day)
#prevdays <- dayfile[1,]
#prevdays <- prevdays[-c(1),]
daysub <- subset(fishsub, day == days[[1]])
# calculate kuds for day 1
coords <- daysub[,c(1, 5, 6)] # extract x,y coords and fish id from dayfile
coordinates(coords) <- c('PosX', 'PosY') # convert to spatial points data frame object
ud <- kernelUD(coords, h = 'href', grid = xy, kern = 'bivnorm') # KUD calculation for adehabitatHR package
ka1 <- kernel.area(ud, percent = c(50, 95), unin = 'm', unout = 'm2') # calculates area of KUD50, KUD95
kud1 <- coords # send coords to day 1 kud matrix
kud1$Period <- 1 # recode ID to 1
# calculae kuds for subsequent days and calculate iors
for (j in 2:length(unique(fishsub$day)))
{
daysub <- subset(fishsub, day == days[[j]])
coords <- daysub[,c(1, 5, 6)] # extract x,y coords and fish id from dayfile
coordinates(coords) <- c('PosX', 'PosY') # convert to spatial points data frame object
ud <- kernelUD(coords, h = 'href', grid = xy, kern = 'bivnorm') # KUD calculation for adehabitatHR package
ka2 <- kernel.area(ud, percent = c(50, 95), unin = 'm', unout = 'm2') # calculates area of KUD50, KUD95
kud2 <- coords # send coords to day 2 kud matrix
kud2$Period <- 2 # recode ID to 2
kud <- rbind(kud2, kud1) # combine coords for 2 days
ov95 <- kerneloverlap(kud, method = 'HR', percent = 95) # calculate proportion 95% overlap of 2 days
ov50 <- kerneloverlap(kud, method = 'HR', percent = 50) # calculate proportion 50% overlap of 2 days
ov95 <- ov95[1,2]*ka2[2,1] # calculate area of kud95 overlap from proportion
ov50 <- ov50[1,2]*ka2[1,1] # calculate area of kud50 overlap from proportion
ta95 <- ka1[2,1]+ka2[2,1]
ta50 <- ka1[1,1]+ka2[1,1]
ior95 <- c(ior95, ov95/ta95)
ior50 <- c(ior50, ov50/ta50)
#kud50 <- c(kud50, ka[1,1])
#kud95 <- c(kud95, ka[2,1])
#prevdays <- daysub
kud1 <- kud2
kud1$Period <- 1
ka1 <- ka2
}
kud50.ior <- rbind(kud50.ior, ior50)
kud95.ior <- rbind(kud95.ior, ior95)
}
kud50.ior <- t(kud50.ior)
rownames(kud50.ior) <- days[-1]
colnames(kud50.ior) <- fish
kud50.ior[is.nan(kud50.ior)] <- 0 # replace NaNs with 0
kud95.ior <- t(kud95.ior)
rownames(kud95.ior) <- days[-1]
colnames(kud95.ior) <- fish
kud95.ior[is.nan(kud95.ior)] <- 0 # replace NaNs with 0
#plot daily IORs for all fish
par(mfrow=c(1,2))
plot(kud50.ior[,as.character(fish[1])], type = 'o', ylim = c(0,signif(max(kud50.ior), 2)))
for (k in 2:length(fish)){lines(kud50.ior[,as.character(fish[k])], type = 'o')}
plot(kud95.ior[,as.character(fish[1])], type = 'o', ylim = c(0,signif(max(kud95.ior), 2)))
for (k in 2:length(fish)){lines(kud95.ior[,as.character(fish[k])], type = 'o')}