-
Notifications
You must be signed in to change notification settings - Fork 0
/
AcousticTagAnalyseWildVsFarmed.R
5782 lines (4246 loc) · 314 KB
/
AcousticTagAnalyseWildVsFarmed.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
# 2. batch.locations() = returns a summary matrix of locations for all dayfiles in working directory and saves to an Excel spreadsheet
# 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.perfish.coverage - daily hourly coverage per fish for all days loaded as one file using load.all()
# 10d. hmean.perday.coverage - hourly coverage of each fish per day for all days loaded as one file using load.all()
# 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
# 13a. fish.plot(period) = draws a plot of fish location for the fish id specified
# 13b. fish.plotf(period, factor) = draws a plot of fish location for the fish id specified coloured by the factor 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)
# 19d. plot.bytide(period) = draws a plot of fish positions coloured by phase of tide (High, running out, low, running in)
# 19f. plot.bybs(period) = draws a plot of fish positions coloured by behaviour state (Resident resting, resident active, cruising, foraging and active)
# 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')
# 33a. load.all() = Load all data files from a folder into single data frame
# 33b. load.allhides() = load all hide data files from a folder into a single data frame
# 34a. crop(xmin, xmax, ymin, ymax) = Crop edges of dataset to remove multipath
# 34b. batch.crop(xmin, xmax, ymin, ymax) = Crop edges of all files in working directory 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 specified fish ID and step specified for whole dayfile
# 43. bcalc() = Perform behaviour calculations for loaded dayfile and add to dayfile to plot with bplot function
# 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
# 46. kudcalc() = Calculate kernel distribution utilisation for single fish file
# 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)
# 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)
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(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(tidyverse)
library(data.table)
#ENTER YOUR VARIABLES HERE
workingdir = "H:/Acoustic tag - Wild vs. Farmed/Data processing/Cropped data/Coded Day CSV" # change to location of data
dayfile.loc = "run_2LLF15S100157_day_coded.csv" # change to file to be analysed
masterfileloc = "H:/Acoustic tag - Wild vs. Farmed/AcousticTagFile_2015.xlsx" # change to location of AcousticTagFile.xlsx
workingdir = "H:/Acoustic tag - Wild vs. Farmed/Data processing/Cropped data/Coded Fish CSV" # change to location of data
dayfile.loc = "run_1LLF15S1006331_fish_coded.csv" # change to file to be analysed
masterfileloc = "H:/Data processing/AcousticTagFile_2015.xlsx" # change to location of AcousticTagFile.xlsx
#new dayfile classes
dayfile.classes <- c('NULL', 'numeric', 'factor', 'factor', # Period, subcode, pen
'POSIXct', 'double', 'double', 'double', # EchoTime and fish coordinates
'double', 'double', 'double', 'double', 'double', 'double', 'double', 'double', # derived fish behaviour parameters
'factor', 'factor', 'factor', 'factor', 'factor', 'factor', 'factor', 'factor', # pen husbandry, water vis, moon phase & species
'double', 'double', 'double', 'double', 'double', 'double', 'double', # pen 7 lice numbers
'double', 'double', 'double', 'double', 'double', 'double', 'double', # pen 8 lice numbers
'factor', 'factor', 'factor', 'factor', 'factor', 'factor', 'factor', 'factor', # fish location codes
'factor', 'factor', 'factor', # sun and tide times and tide height
'factor', 'factor', 'factor', 'factor', 'factor', 'factor', 'factor', # salmon, wrasse and lumpfish feeding times
'double', 'double', 'double', 'double', 'double', 'double',
'double', 'double', 'double', 'double', 'double', 'double', # Water quality probe data
'double' # fish temperature at depth
)
#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'
)
#temporary dayfile classes
dayfile.classes <- c('NULL', 'factor', 'factor', 'character', 'double', 'double',
'double', 'double', 'double', 'double', 'double', 'double', 'NULL',
'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL',
'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL',
#'double', 'double', 'double', 'double', 'double', 'double', 'double',
#'factor', 'factor', 'factor', 'factor', 'factor', 'factor', 'factor',
'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL',
'factor', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL'
, 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL'
, 'NULL', 'NULL'
#, 'double', 'double', 'double', 'double', 'double',
#'double', 'double', 'double', 'double', 'double', 'double', 'double'
)
#temporary dayfile classes
dayfile.classes <- c('character', 'character', 'character', 'character', 'character', 'character', 'character', 'character',
'character', 'character', 'character', 'character', 'character', 'character', 'character', 'character',
'character', 'character', 'character', 'character', 'character', 'character', 'character', 'character',
'character', 'character', 'character', 'character', 'character', 'character', 'character', 'character',
'character', 'character', 'character', 'character', 'character', 'character', 'character', 'character',
'character', 'character', 'character', 'character', 'character', 'character', 'character', 'character',
'character', 'character', 'character', 'character', 'character', 'character'
)
workingdir = "H:/Data processing/2015 Wild vs. Farmed/6a. Coded Day CSV/hides" # change to location of data
hidefile.loc = "Day184_hides.csv" # change to file to be analysed
hidefile.classes = c('NULL', 'numeric', 'factor', 'factor', 'POSIXct', 'double', 'double', 'double')
# LOAD FILES-------------------------------------------------------------------------------------------------------------------
#LOAD LOCATIONS CODING DATA
locations.lookup <- read.xlsx(masterfileloc, sheetName = 'Locations coding (old)', startRow = 1, endRow = 47, 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 DAYFILE
setwd(workingdir)
dayfile <- read.csv(dayfile.loc, header = TRUE, sep = ",", colClasses = dayfile.classes)
dayfile <- fread(dayfile.loc)
dayfile$EchoTime <- as.POSIXct(dayfile$EchoTime)
#LOAD HIDEFILE
setwd(workingdir)
hidefile <- read.csv(hidefile.loc, header = TRUE, sep = ",", colClasses = hidefile.classes)
#load.dayfile(dayfile.loc)
#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
# SANDPIT-----------------------------------------------------------------------------------------------------------------
# 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')
# wild ballan 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('6331')
add.fish('6387', fishcol = fishpal[19])
add.fish('6499', fishcol = fishpal[18])
add.fish('6639', fishcol = fishpal[17])
add.fish('6695', fishcol = fishpal[16])
add.fish('6863', fishcol = fishpal[15])
add.fish('7087', fishcol = fishpal[14])
add.fish('7367', fishcol = fishpal[13])
add.fish('7423', fishcol = fishpal[12])
add.fish('7563', fishcol = fishpal[11])
add.fish('7843', fishcol = fishpal[10])
add.fish('8011', fishcol = fishpal[9])
add.fish('8347', fishcol = fishpal[8])
add.fish('8599', fishcol = fishpal[7])
add.fish('8711', fishcol = fishpal[6])
add.fish('8935', fishcol = fishpal[5])
add.fish('8991', fishcol = fishpal[4])
add.fish('9383', fishcol = fishpal[3])
# farmed ballan 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('6275')
add.fish('6751', fishcol = fishpal[19])
add.fish('6975', fishcol = fishpal[18])
add.fish('7199', fishcol = fishpal[17])
add.fish('7311', fishcol = fishpal[16])
add.fish('7675', fishcol = fishpal[15])
add.fish('7787', fishcol = fishpal[14])
add.fish('7899', fishcol = fishpal[13])
add.fish('8123', fishcol = fishpal[12])
add.fish('8235', fishcol = fishpal[11])
add.fish('8459', fishcol = fishpal[10])
add.fish('8823', fishcol = fishpal[9])
add.fish('9047', fishcol = fishpal[8])
add.fish('9159', fishcol = fishpal[7])
add.fish('9271', fishcol = fishpal[6])
add.fish('9495', fishcol = fishpal[5])
add.fish('9635', fishcol = fishpal[4])
add.fish('9859', fishcol = fishpal[3])
# 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('6331')
add.depthfish('6387')
add.depthfish('6499')
add.depthfish('6639')
add.depthfish('6695')
add.depthfish('6863')
add.depthfish('7087')
add.depthfish('7367')
add.depthfish('7423')
add.depthfish('7563')
add.depthfish('7843')
add.depthfish('8011')
add.depthfish('8347')
add.depthfish('8599')
add.depthfish('8711')
add.depthfish('8935')
add.depthfish('8991')
add.depthfish('9383')
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
# 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('9859')
add.depthfish('6751')
add.depthfish('6975')
add.depthfish('7199')
add.depthfish('7311')
add.depthfish('7675')
add.depthfish('7787')
add.depthfish('7899')
add.depthfish('8123')
add.depthfish('8235')
add.depthfish('8459')
add.depthfish('8823')
add.depthfish('9047')
add.depthfish('9159')
add.depthfish('9271')
add.depthfish('9495')
add.depthfish('9635')
add.depthfish('6275')
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
#-------------------------------------------------------------------------------------------------------------------------------
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
}
})
# code for manually cropping edges of data for specified fish
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 for manually cropping edges of data for all fish
fish.id <- subset(dayfile, dayfile$PosY > 7 & dayfile$PosY < 40 & dayfile$PosX > 30 & dayfile$PosX < 64)
# code to day average env probe data
probe <- probe.sal4
probe$day <- as.Date(probe$Sal.time.4m)
mean.sal4m <- tapply(probe$Sal.4m, 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')
}
)
# code to recode wild ballans as pen 7 so the subsetting works with current functions (even though they were really in pen 8!)
setwd(workingdir)
files <- list.files(path = workingdir, pattern = '*.csv', all.files = FALSE, recursive = FALSE)
for (i in 1:length(files))
{
dayfile.loc <- files[[i]]
dayfile <- read.csv(dayfile.loc, header = TRUE, sep = ",", colClasses = dayfile.classes)
dayfile$PEN <- ifelse(dayfile$SPEC == 'Ballan Wild', '7', '8') # change wild ballans to pen 7
write.csv(dayfile, file = dayfile.loc) #write output to file
}
# log scale and labels for activity histograms
# farmed 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, 250000)) + ggtitle('Farmed wrasse activity histogram')
# Wild 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, 250000)) + ggtitle('Wild wrasse activity histogram')
# box and whisker plots
# depth for wild, conditioned and unconditioned
ggplot() +
geom_boxplot(data = allwild, aes(x = SPEC, y = PosZ), fill = '#00CC99', alpha = 0.7, size = 0.75, outlier.color = 'white') +
geom_boxplot(data = allconditioned, aes(x = SPEC, y = PosZ), fill = '#8585E0', alpha = 0.7, size = 0.75, outlier.color = 'white') +
geom_boxplot(data = allunconditioned, aes(x = SPEC, y = PosZ), fill = '#002060', alpha = 0.7, size = 0.75, outlier.color = 'white') +
scale_x_discrete(limits = c('W', 'U', 'C'), labels = c('Wild', 'Unconditioned', 'Conditioned')) +
scale_y_reverse(limits = c(20, 0), breaks = c(0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20), labels = c('0', '2', '4', '6', '8', '10', '12', '14', '16', '18', '20')) +
#ylim(c(30, 0)) +
labs(x = '', y = '')
ggplot() +
geom_boxplot(data = dayfile, aes(x = SPEC, y = PosZ), fill = '#00CC99', alpha = 0.5, size = 0.75, outlier.color = 'white') +
scale_x_discrete(labels = c('Farmed', 'Wild')) +
scale_y_reverse(limits = c(24, 0), breaks = c(0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24), labels = c('0', '2', '4', '6', '8', '10', '12', '14', '16', '18', '20', '22', '24')) +
#ylim(c(30, 0)) +
labs(x = '', y = 'Depth (m)')
# activity for wild, conditioned and unconditioned
ggplot() +
geom_boxplot(data = allwild, aes(x = SPEC, y = BLSEC), fill = '#00CC99', alpha = 0.7, size = 0.75, outlier.color = 'white') +
geom_boxplot(data = allconditioned, aes(x = SPEC, y = BLSEC), fill = '#8585E0', alpha = 0.7, size = 0.75, outlier.color = 'white') +
geom_boxplot(data = allunconditioned, aes(x = SPEC, y = BLSEC), fill = '#002060', alpha = 0.7, size = 0.75, outlier.color = 'white') +
scale_x_discrete(limits = c('W', 'U', 'C'), labels = c('Wild', 'Unconditioned', 'Conditioned')) +
scale_y_continuous(limits = c(0, 1), breaks = c(0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1), labels = c('0', '0.1', '0.2', '0.3', '0.4', '0.5', '0.6', '0.7', '0.8', '0.9', '1.0')) +
#ylim(c(30, 0)) +
labs(x = '', y = '')
# Polar plots of headings
p7 <- subset(dayfile, PEN == 7)
p8 <- subset(dayfile, PEN == 8)
pplot7 <- ggplot(p7, aes(HEAD))
pplot7 <- pplot7 + geom_histogram(breaks = seq(0, 360, 10), color = 'black', alpha = 0, size = 0.75, closed = 'left') +
theme_minimal() + theme(axis.text.y = element_blank(), axis.title.y = element_blank()) +
scale_x_continuous('', limits = c(0, 360), expand = c(0, 0), breaks = c(0, 30, 60, 90, 120, 150, 180, 210, 240, 270, 300, 330)) +
coord_polar(theta = 'x', start = 0) +
ggtitle('Wild wrasse')
pplot8 <- ggplot(p8, aes(HEAD))
pplot8 <- pplot8 + geom_histogram(breaks = seq(0, 360, 10), color = 'black', alpha = 0, size = 0.75) +
theme_minimal() + theme(axis.text.y = element_blank(), axis.title.y = element_blank()) +
scale_x_continuous('', limits = c(0, 360), breaks = c(0, 30, 60, 90, 120, 150, 180, 210, 240, 270, 300, 330)) +
coord_polar(theta = 'x', start = 0) +
ggtitle('Farmed wrasse')
multiplot(pplot7, pplot8, cols = 2)
# code for splitting whole dataset loaded as dayfile into files of seperate days--------------------------
dayfile <- dayfile[order(dayfile$EchoTime, na.last = FALSE, decreasing = FALSE, method = c("shell")),] # sort by time
dayfile$date <- as.Date(dayfile$EchoTime + hours(1))
dayfile <- subset(dayfile, EchoTime < as.POSIXct('2015-07-27 00:00:01')) # remove unwanted days
days <- c(paste0(sort(unique(dayfile$date)), ' 00:00:00'), paste0(max(unique(dayfile$date))+days(1), ' 00:00:00'))
daynum <- c(seq(156,169, 1), seq(174, 181, 1), seq(184, 198, 1))
for(i in 1:length(days)-1){
daycut <- dayfile[dayfile$EchoTime > days[i] & dayfile$EchoTime < days[i+1],]
daycut$date <- NULL
write.csv(daycut, paste0('run_2LLF15S100', as.character(daynum[i]), '_day_coded.csv'))
}
# Behaviour analysis code -------------------------------------------------------------------------------------------------------------
f5 <- rep(1/5, 5) # 5 step moving average filter
ylag <- filter(dayfile$TURN, f5, sides=1) # filter turn
lines(dayfile$EchoTime, ylag, col = 'red') # add moving average to plot
dayfile <- subset(dayfile, Period == 6331)
daytemp <- dayfile
dayfile <- daytemp[3000:4000,] # subset dayfile
fish.plot(6331)
par(new=F)
par(mar = c(4, 4, 4, 4) + 0.1)
plot(dayfile$EchoTime, dayfile$TURN, xlab = 'Time', type = 'l', lwd = 2, col = 'lightgreen', ylab = '', yaxt = 'n', ylim = c(0, 360)) # plot turn
lines(dayfile$EchoTime, dayfile$HEAD, lwd = 2, lty = 1, col = 'lightblue') # plot heading
axis(2, ylim = c(0, 180), at = c(0, 30, 60, 90, 120, 150, 180, 210, 240, 270, 300, 330, 360), labels = c('0', '30', '60', '90', '120', '150', '180', '210', '240', '270', '300', '330', '360'))
mtext(2, text = 'Turn/heading (degrees)', line = 2.5)
par(new = T)
plot(dayfile$EchoTime, dayfile$MSEC, col = 'red', axes = F, xlab = '', ylab = '', type = 'l', lwd = 2, ylim = c(0, 0.8))
axis(4, ylim = c(0, 1), at = c(0, 0.2, 0.4, 0.6, 0.8), labels = c('0', '0.2', '0.4', '0.6', '0.8'))
mtext(text = 'velocity (m/sec)', side = 4, line = 2.5)
legend('topleft', legend = c('Turn', 'Heading', 'Velocity'), lty = 1, lwd = 2, col = c('lightgreen', 'blue', 'red'))
# subset hidefile
hidetemp <- hidefile
hidefile <- subset(hidetemp, Period == 13527)
hidefile <- hidefile[1610:1679,]
# add hidefile to fish.plot
par(new = T)
plot(hidefile$PosX, hidefile$PosY, type = 'l', col = 'red', xlim = c(29, 65), ylim = c(6, 41), xlab = '', ylab = '')
# add hidefile to fish.depth
lines(hidefile$EchoTime, hidefile$PosZ)
#calculate difference in turn and 10 width rolling sum of turn
dayfile$turndiff <- c(NA, abs(diff(dayfile$TURN, lag = 1)))
dayfile$rollturnsumpersec <- c(rep(NA,4), rollapply(dayfile$turndiff, width = 10, FUN = sum, na.rm = T, align = 'center')/rollapply(dayfile$SEC, width = 10, FUN = sum, na.rm = T, align = 'center'), rep(NA, 5))
# Displacement code
# calculate rolling mean of x,y,z coords over 20 points
dayfile$rollx <- c(rep(NA,19), rollapply(dayfile$PosX, width = 20, FUN = mean, na.rm = T, align = 'right'))#, rep(NA, 10))
dayfile$rolly <- c(rep(NA,19), rollapply(dayfile$PosY, width = 20, FUN = mean, na.rm = T, align = 'right'))#, rep(NA, 10))
dayfile$rollz <- c(rep(NA,19), rollapply(dayfile$PosZ, width = 20, FUN = mean, na.rm = T, align = 'right'))#, rep(NA, 10))
# calculate rolling sum of time between pings over 20 points
dayfile$rollsec <- c(rep(NA,19), rollapply(dayfile$SEC, width = 20, FUN = sum, na.rm = T, align = 'right'))#, rep(NA, 10))
#calculate displacement
dayfile$displace <- round(sqrt(abs(dayfile$PosX-dayfile$rollx)^2+abs(dayfile$PosY-dayfile$rolly)^2+abs(dayfile$PosZ-dayfile$rollz)^2)/dayfile$rollsec, digits = 3)
# calculate rolling mean of velocity/sec
dayfile$rollvel <- c(rep(NA,9), rollapply(dayfile$M, width = 10, FUN = sum, na.rm = T, align = 'right')/rollapply(dayfile$SEC, width = 10, FUN = sum, na.rm = T, align = 'center'))
# calculate instantanous acceleration
dayfile$acc <- c(NA, abs(diff(dayfile$MSEC, lag = 1)))
#calculate acceleration mean over 10 points
dayfile$accmean <- c(rep(NA,4), rollapply(dayfile$acc, width = 10, FUN = mean, na.rm = T, align = 'center'), rep(NA, 5)) # acceleration mean over 10 points
# Analysis of behaviour states
daytemp <- dayfile
dayfile <- subset(daytemp, BS == 'Rr')
bstab <- table(dayfile$BS)
round(bstab/sum(bstab)*100, 2)
# Code to calculate KUD50 and KUD95 for all fish in loaded dayfile and save as csv-----------------------------------------------------------
fish <- unique(dayfile$Period)
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 add day number to dayfile
exp.dates <- unique(as.Date(dayfile$EchoTime))
exp.start <- 1 # change this to the start day
exp.length <- 37 # change this to the length of the experiment
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)
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),]
#coords <- data.frame('Period' = integer, 'PosX' = numeric, 'PosY' = numeric)
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)
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),]
# calculate kuds for day 1
daysub <- subset(fishsub, day == days[[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')}
par(mfrow=c(1,1))
write.csv(kud50.ior, 'IOR50.csv')
write.csv(kud95.ior, 'IOR95.csv')
# rearrange date format from crappy Excel format and convert to POSIXct--------------------------------------
substr(dayfile$EchoTime, 1, 10) <- paste0(substr(dayfile$EchoTime, 7, 10), '-', substr(dayfile$EchoTime, 4, 5), '-', substr(dayfile$EchoTime, 1, 2))
dayfile$EchoTime <- as.POSIXct(dayfile$EchoTime)
# load all dayfiles in working directory and extract some variables and sort and rearrange date format
files <- list.files(path = workingdir, pattern = '*.csv', all.files = FALSE, recursive = FALSE)
dayfile <- data.frame()
myvars <- c('Period', 'EchoTime', 'PosX', 'PosY', 'PosZ', 'SEC', 'M', 'MSEC', 'BL', 'BLSEC', 'SUN', 'TID')
for(i in 1:length(files)){
daytemp <- read.csv(files[[i]], header = TRUE, sep = ",", colClasses = dayfile.classes)
daytemp <- daytemp[myvars]
daytemp <- subset(daytemp, Period != '')
daytemp$Period <- as.double(daytemp$Period)
# daytemp$temp <- daytemp$EchoTime
if (substr(daytemp[1,2], 2, 2) == '/'){
substr(daytemp$EchoTime, 1, 8) <- paste0(substr(daytemp$EchoTime, 5, 8), '-', substr(daytemp$EchoTime, 3, 3), '-', substr(daytemp$EchoTime, 1, 1))
} else {
if (substr(daytemp[1,2], 5, 5) == '/'){
substr(daytemp$EchoTime, 1, 9) <- paste0(substr(daytemp$EchoTime, 6, 9), '-', substr(daytemp$EchoTime, 4, 4), '-', substr(daytemp$EchoTime, 1, 2))
} else {
substr(daytemp$EchoTime, 1, 10) <- paste0(substr(daytemp$EchoTime, 7, 10), '-', substr(daytemp$EchoTime, 4, 5), '-', substr(daytemp$EchoTime, 1, 2))
}
}
daytemp$EchoTime <- as.POSIXct(daytemp$EchoTime)
daytemp$PosX <- as.double(daytemp$PosX)
daytemp$PosY <- as.double(daytemp$PosY)
daytemp$PosZ <- as.double(daytemp$PosZ)
daytemp$SEC <- as.double(daytemp$SEC)
daytemp$M <- as.double(daytemp$M)
daytemp$MSEC <- as.double(daytemp$MSEC)
daytemp$BL <- as.double(daytemp$BL)
daytemp$BLSEC <- as.double(daytemp$BLSEC)
daytemp$SUN <- as.factor(daytemp$SUN)
dayfile <- rbind(dayfile, daytemp)
}
# Add species code to wrasse vs. lumps dataset---------------------
fishid.species.lookup <- c('L', 'L', 'L', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'B', 'B', 'B', 'B') # create fish origin lookup table
names(fishid.species.lookup) <- c('7507', '9523', '10503', '6583', '8515', '11511', '7395', '8319', '8907', '8095', '7171', '6471', '8431', '7647', '8683', '8795', '6835', '9243', '7535', '8571', '6723', '7983', '7059', '6247', '9467', '9131', '9355')
dayfile$SPEC <- as.factor(fishid.species.lookup[as.character(dayfile$Period)]) # add fish species to day file
# Spectrum wavelet sampling ---------------------------------------------------------------------------------------
# load all data into dayfile then move to daytemp and subset single fish to dayfile, then subset by parameter to test for periodicity, e.g. below 15m
#daytemp <- dayfile
wavfunc <- function(fish.id, subtype, subcode){
# fish/group subset
dayfile <- subset(daytemp, Period == fish.id) # fish subset
#dayfile <- subset(daytemp, PEN == 7) # pen subset
#dayfile <- subset(daytemp, Period == 6331 | Period == 6387 | Period == 6499 | Period == 6695 | Period == 6863 | Period == 7423 | Period == 7563 | Period == 8011 | Period == 8347 | Period == 8599 | Period == 8935 | Period == 8991)
#calculate standardised detection frequencies
dayfile <- dayfile[order(dayfile$EchoTime, na.last = FALSE, decreasing = FALSE, method = c("shell")),] # sort by time
datacut <- data.frame(dayfile$EchoTime, cuts = cut.POSIXt(dayfile$EchoTime, breaks = 'hour', labels = F)) # code hour by factor
datacut$floor <- floor_date(datacut$dayfile.EchoTime, unit = 'hour') # floor dates to nearest hour
hourbins <- data.frame(unique(datacut$floor), rle(datacut$cuts)$lengths) # create new data frame of hours and sum of pings for each hour
colnames(hourbins) <- c('Date', 'sum')
binlist <- data.frame(seq(floor_date(min(daytemp$EchoTime), unit = 'hour'), floor_date(max(daytemp$EchoTime), unit = 'hour'), by = 'hour')) # create list of all hours in dataset
colnames(binlist) <- 'Date'
hourbins <- binlist %>%
left_join(hourbins, by = c('Date'='Date')) %>% # join time list to hourly ping sum list
replace_na(list(sum = 1)) # replace nas with 1
rownames(hourbins) <- hourbins$Date
#hourbins <- data.frame(hourbins, daycuts = cut.POSIXt(hourbins$Date, breaks = 'day', labels = F)) # code day by factor
#daymeans <- data.frame(tapply(hourbins$sum, hourbins$daycuts, mean)) # calculate daily mean ping rate and create new data frame of results
#hourbins$daymean <- as.numeric(daymeans[as.character(hourbins$daycuts),]) # add daily mean ping rate to hourbins dataset
#hourbins$SDF <- hourbins$sum/hourbins$daymean