-
Notifications
You must be signed in to change notification settings - Fork 6
/
compile.R
3934 lines (3247 loc) · 141 KB
/
compile.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
## ---- oceanadapt
# OceanAdapt requires the following versions of packages. These versions are based on the last successful date that the script ran. This will install these versions on your machine, proceed with caution. The dates on the following lines can be updated if the script successfully runs with different versions on a subsequent date.
library(devtools)
install_version("readr", repos = "https://mran.revolutionanalytics.com/snapshot/2019-12-05/") # 1.3.1
install_version("purrr", repos = "https://mran.revolutionanalytics.com/snapshot/2019-12-05/") # 0.3.3
install_version("stringr", repos = "https://mran.revolutionanalytics.com/snapshot/2019-12-05/") # 1.4.0
install_version("forcats", repos = "https://mran.revolutionanalytics.com/snapshot/2019-12-05/") # 0.4.0
install_version("tidyr", repos = "https://mran.revolutionanalytics.com/snapshot/2019-12-05/") # 1.0.0
install_version("ggplot2", repos = "https://mran.revolutionanalytics.com/snapshot/2019-12-05/") # 3.2.1
install_version("dplyr", repos = "https://mran.revolutionanalytics.com/snapshot/2020-07-01/") # 0.8.3 or 1.0.0
# note: dplyr 0.8.3 (12/5/19) would not install in R v3.5.2 during last test so v1.0.0 (7/1/20) was used
install_version("tibble", repos = "https://mran.revolutionanalytics.com/snapshot/2020-07-01/") # 2.1.3 or 3.0.1
# note: used v3.0.1 (7/1/20) during test to match dplyr (instead of v2.1.3 from 12/5/19)
install_version("lubridate", repos = "https://mran.revolutionanalytics.com/snapshot/2019-12-05/") # 1.7.4
install_version("PBSmapping", repos = "https://mran.revolutionanalytics.com/snapshot/2019-12-05/") # 2.72.1
install_version("data.table", repos = "https://mran.revolutionanalytics.com/snapshot/2019-12-05/") # 1.12.6
install_version("gridExtra", repos = "https://mran.revolutionanalytics.com/snapshot/2019-12-05/") # 2.3
install_version("questionr", repos = "https://mran.revolutionanalytics.com/snapshot/2019-12-05/") # 0.7.0
install_version("geosphere", repos = "https://mran.revolutionanalytics.com/snapshot/2019-12-05/") # 1.5-10
install_version("here", repos = "https://mran.revolutionanalytics.com/snapshot/2019-12-05/") # 0.1
# Load required packages
library(lubridate)
library(PBSmapping)
library(gridExtra)
library(questionr)
library(geosphere)
library(here)
library(dplyr)
library(readr)
library(purrr)
library(forcats)
library(tidyr)
library(tibble)
library(ggplot2)
library(stringr)
library(data.table)
# If running from R instead of RStudio, please set the working directory to the folder containing this script before running this script.
# This script is designed to run within the following directory structure:
# Directory 1 contains:
# 1. compile.R script - this script
# 2. data_raw directory - folder containing all raw data files
# 3. R directory - folder containing scripts used in the making of this script
# The zip file you downloaded created this directory structure for you.
# a note on species name adjustment ####
# At some point during certain surveys it was realized that what was believed to be one species was actually a different species or more than one species. Species have been lumped together as a genus in those instances.
# Answer the following questions using all caps TRUE or FALSE to direct the actions of the script =====================================
# 1. Some strata and years have very little data, should they be removed and saved as fltr data? #DEFAULT: TRUE.
HQ_DATA_ONLY <- TRUE
# 2. View plots of removed strata for HQ_DATA. #OPTIONAL, DEFAULT:FALSE
# It takes a while to generate these plots.
HQ_PLOTS <- FALSE
# 3. Remove ai,ebs,gmex,goa,neus,seus,wcann,wctri, scot. Keep `dat`. #DEFAULT: FALSE
REMOVE_REGION_DATASETS <- FALSE
# 4. Create graphs based on the data similar to those shown on the website and outputs them to pdf. #DEFAULT:FALSE
PLOT_CHARTS <- FALSE
# This used to be called OPTIONAL_PLOT_CHARTS, do I need to change it back?
# 5. If you would like to write out the clean data, would you prefer it in Rdata or CSV form? Note the CSV's are much larger than the Rdata files. #DEFAULT:TRUE, FALSE generates CSV's instead of Rdata.
PREFER_RDATA <- FALSE
# 6. Output the clean full master data frame. #DEFAULT:FALSE
WRITE_MASTER_DAT <- TRUE
# This used to be called OPTIONAL_OUTPUT_DAT_MASTER_TABLE, do I need to change the name back?
# 7. Output the clean trimmed data frame. #DEFAULT:FALSE
WRITE_TRIMMED_DAT <- TRUE
# 7. Generate dat.exploded table. #OPTIONAL, DEFAULT:TRUE
DAT_EXPLODED <- TRUE
# 9. Output the dat.exploded table #DEFAULT:FALSE
WRITE_DAT_EXPLODED <- FALSE
# 10. Output the BY_SPECIES, BY_REGION, and BY_NATIONAL tables. #DEFAULT:FALSE
WRITE_BY_TABLES <- TRUE
# Workspace setup ---------------------------------------------------------
print("Workspace setup")
# This script works best when the repository is downloaded from github,
# especially when that repository is loaded as a project into RStudio.
# The working directory is assumed to be the OceanAdapt directory of this repository.
# library(tidyverse)# use ggplot2, tibble, readr, dplyr, stringr, purrr
# Functions ===========================================================
print("Functions")
# function to calculate convex hull area in km2
#developed from http://www.nceas.ucsb.edu/files/scicomp/GISSeminar/UseCases/CalculateConvexHull/CalculateConvexHullR.html
calcarea <- function(lon,lat){
hullpts = chull(x=lon, y=lat) # find indices of vertices
hullpts = c(hullpts,hullpts[1]) # close the loop
lonlat <- data.frame(cbind(lon, lat))
ps = appendPolys(NULL,mat=as.matrix(lonlat[hullpts,]),1,1,FALSE) # create a Polyset object
attr(ps,"projection") = "LL" # set projection to lat/lon
psUTM = convUL(ps, km=TRUE) # convert to UTM in km
polygonArea = calcArea(psUTM,rollup=1)
return(polygonArea$area)
}
sumna <- function(x){
#acts like sum(na.rm=T) but returns NA if all are NA
if(!all(is.na(x))) return(sum(x, na.rm=T))
if(all(is.na(x))) return(NA)
}
meanna = function(x){
if(!all(is.na(x))) return(mean(x, na.rm=T))
if(all(is.na(x))) return(NA)
}
# weighted mean for use with summarize(). values in col 1, weights in col 2
wgtmean = function(x, na.rm=FALSE) {questionr::wtd.mean(x=x[,1], weights=x[,2], na.rm=na.rm)}
wgtse = function(x, na.rm=TRUE){
if(sum(!is.na(x[,1]) & !is.na(x[,2]))>1){
if(na.rm){
return(sqrt(wtd.var(x=x[,1], weights=x[,2], na.rm=TRUE, normwt=TRUE))/sqrt(sum(!is.na(x[,1] & !is.na(x[,2])))))
} else {
return(sqrt(wtd.var(x=x[,1], weights=x[,2], na.rm=FALSE, normwt=TRUE))/sqrt(length(x))) # may choke on wtd.var without removing NAs
}
} else {
return(NA) # NA if vector doesn't have at least 2 values
}
}
se <- function(x) sd(x)/sqrt(length(x)) # assumes no NAs
lunique = function(x) length(unique(x)) # number of unique values in a vector
present_every_year <- function(dat, ...){
presyr <- dat %>%
filter(wtcpue > 0) %>%
group_by(...) %>%
summarise(pres = n())
return(presyr)
}
num_year_present <- function(presyr, ...){
presyrsum <- presyr %>%
filter(pres > 0) %>%
group_by(...) %>%
summarise(presyr = n())
return(presyrsum)
}
max_year_surv <- function(presyrsum, ...){
maxyrs <- presyrsum %>%
group_by(...) %>%
summarise(maxyrs = max(presyr))
return(maxyrs)
}
explode0 <- function(x, by=c("region")){
# x <- copy(x)
stopifnot(is.data.table(x))
# print(x[1])
# x <- as.data.table(x)
# x <- as.data.table(trimmed_dat)[region=="Scotian Shelf Summer"]
# setkey(x, haulid, stratum, year, lat, lon, stratumarea, depth)
# group the data by these columns
setorder(x, haulid, stratum, year, lat, lon, stratumarea, depth)
# pull out all of the unique spp
u.spp <- x[,as.character(unique(spp))]
# pull out all of the unique common names
u.cmmn <- x[,common[!duplicated(as.character(spp))]]
# pull out these location related columns and sort by haul_id and year
x.loc <- x[,list(haulid, year, stratum, stratumarea, lat, lon, depth)]
setkey(x.loc, haulid, year)
# attatch all spp to all locations
x.skele <- x.loc[,list(spp=u.spp, common=u.cmmn), by=eval(colnames(x.loc))]
setkey(x.skele, haulid, year, spp)
x.skele <- unique(x.skele)
setcolorder(x.skele, c("haulid","year","spp", "common", "stratum", "stratumarea","lat","lon","depth"))
# pull in multiple observations of the same species
x.spp.dat <- x[,list(haulid, year, spp, wtcpue)]
setkey(x.spp.dat, haulid, year, spp)
x.spp.dat <- unique(x.spp.dat)
out <- x.spp.dat[x.skele, allow.cartesian = TRUE]
out$wtcpue[is.na(out$wtcpue)] <- 0
out
}
#convert factors to numeric
as.numeric.factor <- function(x) {as.numeric(levels(x))[x]}
#Reformat string - first letter uppercase
firstup <- function(x) {
x <- tolower(x)
substr(x, 1, 1) <- toupper(substr(x, 1, 1))
x
}
#add one to odd numbers
oddtoeven <- function(x) {
ifelse(x %% 2 == 1,x+1,x)
}
#add one to even numbers
eventoodd <- function(x) {
ifelse(x %% 2 == x+1,1,x)
}
# Compile AI =====================================================
print("Compile AI")
## Special fix
#there is a comment that contains a comma in the 2014-2018 file that causes the delimiters to read incorrectly. Fix that here::here:
temp <- read_lines(here::here("data_raw", "ai2014_2018.csv"))
# replace the string that causes the problem
temp_fixed <- str_replace_all(temp, "Stone et al., 2011", "Stone et al. 2011")
# read the result in as a csv
temp_csv <- read_csv(temp_fixed)
## End special fix
files <- as.list(dir(pattern = "ai", path = "data_raw", full.names = T))
# exclude the strata file and the raw 2014-2016 data file which has been fixed in temp_csv
files <- files[-c(grep("strata", files),grep("2014", files))]
# combine all of the data files into one table
ai_data <- files %>%
# read in all of the csv's in the files list
purrr::map_dfr(read_csv) %>%
# add in the data fixed above
rbind(temp_csv) %>%
# remove any data rows that have headers as data rows
filter(LATITUDE != "LATITUDE", !is.na(LATITUDE)) %>%
mutate(stratum = as.integer(STRATUM)) %>%
# remove unused columns
select(-STATION, -DATETIME, -NUMCPUE, -SID, -BOT_TEMP, -SURF_TEMP, -STRATUM) %>%
# remove any extra white space from around spp and common names
mutate(COMMON = str_trim(COMMON),
SCIENTIFIC = str_trim(SCIENTIFIC))
# The warning of 13 parsing failures is pointing to a row in the middle of the data set that contains headers instead of the numbers expected, this row is removed by the filter above.
ai_strata <- read_csv(here::here("data_raw", "ai_strata.csv"), col_types = cols(NPFMCArea = col_character(),
SubareaDescription = col_character(),
StratumCode = col_integer(),
DepthIntervalm = col_character(),
Areakm2 = col_integer()
)) %>%
select(StratumCode, Areakm2) %>%
mutate(stratum = StratumCode)
ai <- left_join(ai_data, ai_strata, by = "stratum")
# are there any strata in the data that are not in the strata file?
stopifnot(nrow(filter(ai, is.na(Areakm2))) == 0)
# the following chunk of code reformats and fixes this region's data
ai <- ai %>%
mutate(
# Create a unique haulid
haulid = paste(formatC(VESSEL, width=3, flag=0), CRUISE, formatC(HAUL, width=3, flag=0), sep='-'),
# change -9999 wtcpue to NA
wtcpue = ifelse(WTCPUE == "-9999", NA, WTCPUE)) %>%
# rename columns
rename(year = YEAR,
lat = LATITUDE,
lon = LONGITUDE,
depth = BOT_DEPTH,
spp = SCIENTIFIC,
stratumarea = Areakm2) %>%
# remove rows that are eggs
filter(spp != "" &
# remove all spp that contain the word "egg"
!grepl("egg", spp)) %>%
# adjust spp names
mutate(
# catch A. stomias and A. evermanii (as of 2018 both spp appear as "valid" so not sure why they are being changed)
spp = ifelse(grepl("Atheresthes", spp), "Atheresthes sp.", spp),
# catch L. polystryxa (valid in 2018), and L. bilineata (valid in 2018)
spp = ifelse(grepl("Lepidopsetta", spp), "Lepidopsetta sp.", spp),
# catch M. jaok (valid in 2018), M. niger (valid in 2018), M. polyacanthocephalus (valid in 2018), M. quadricornis (valid in 2018), M. verrucosus (changed to scorpius), M. scorpioides (valid in 2018), M. scorpius (valid in 2018) (M. scorpius is in the data set but not on the list so it is excluded from the change)
spp = ifelse(grepl("Myoxocephalus", spp ) & !grepl("scorpius", spp), "Myoxocephalus sp.", spp),
# catch B. maculata (valid in 2018), abyssicola (valid in 2018), aleutica (valid in 2018), interrupta (valid in 2018), lindbergi (valid in 2018), mariposa (valid in 2018), minispinosa (valid in 2018), parmifera (valid in 2018), smirnovi (valid in 2018), cf parmifera (Orretal), spinosissima (valid in 2018), taranetzi (valid in 2018), trachura (valid in 2018), violacea (valid in 2018)
# B. panthera is not on the list of spp to change
spp = ifelse(grepl("Bathyraja", spp) & !grepl("panthera", spp), 'Bathyraja sp.', spp)
) %>%
select(haulid, year, lat, lon, stratum, stratumarea, depth, spp, wtcpue) %>%
type_convert(col_types = cols(
lat = col_double(),
lon = col_double(),
year = col_integer(),
wtcpue = col_double(),
spp = col_character(),
depth = col_integer(),
haulid = col_character()
)) %>%
group_by(haulid, stratum, stratumarea, year, lat, lon, depth, spp) %>%
summarise(wtcpue = sumna(wtcpue)) %>%
# Calculate a corrected longitude for Aleutians (all in western hemisphere coordinates)
ungroup() %>%
mutate(lon = ifelse(lon > 0, lon - 360, lon),
region = "Aleutian Islands") %>%
select(region, haulid, year, lat, lon, stratum, stratumarea, depth, spp, wtcpue)
if (HQ_DATA_ONLY == TRUE){
# look at the graph and make sure decisions to keep or eliminate data make sense
# plot the strata by year
p1 <- ai %>%
select(stratum, year) %>%
ggplot(aes(x = as.factor(stratum), y = as.factor(year))) +
geom_jitter()
p2 <- ai %>%
select(lat, lon) %>%
ggplot(aes(x = lon, y = lat)) +
geom_jitter()
test <- ai %>%
select(stratum, year) %>%
distinct() %>%
group_by(stratum) %>%
summarise(count = n()) %>%
filter(count >= 13)
# how many rows will be lost if only stratum trawled ever year are kept?
test2 <- ai %>%
filter(stratum %in% test$stratum)
nrow(ai) - nrow(test2)
# percent that will be lost
print((nrow(ai) - nrow(test2))/nrow(ai))
# 0% of rows are removed
ai_fltr <- ai %>%
filter(stratum %in% test$stratum)
# plot the results after editing
p3 <- ai_fltr %>%
select(stratum, year) %>%
ggplot(aes(x = as.factor(stratum), y = as.factor(year))) +
geom_jitter()
p4 <- ai_fltr %>%
select(lat, lon) %>%
ggplot(aes(x = lon, y = lat)) +
geom_jitter()
if (HQ_PLOTS == TRUE){
temp <- grid.arrange(p1, p2, p3, p4, nrow = 2)
ggsave(plot = temp, filename = here::here("plots", "ai_hq_dat_removed.png"))
rm(temp)
}
rm(test, test2, p1, p2, p3, p4)
}# clean up
rm(ai_data, ai_strata, files, temp_fixed, temp_csv)
# Compile EBS ============================================================
print("Compile EBS")
files <- as.list(dir(pattern = "ebs", path = "data_raw", full.names = T))
# exclude the strata file
files <- files[-grep("strata", files)]
# combine all of the data files into one table
ebs_data <- files %>%
# read in all of the csv's in the files list
map_dfr(read_csv) %>%
# remove any data rows that have headers as data rows
filter(LATITUDE != "LATITUDE", !is.na(LATITUDE)) %>%
mutate(stratum = as.integer(STRATUM)) %>%
# remove unused columns
select(-STATION, -DATETIME, -NUMCPUE, -SID, -BOT_TEMP, -SURF_TEMP, -STRATUM) %>%
# remove any extra white space from around spp and common names
mutate(COMMON = str_trim(COMMON),
SCIENTIFIC = str_trim(SCIENTIFIC))
# import the strata data
ebs_strata <- read_csv(here::here("data_raw", "ebs_strata.csv"), col_types = cols(
SubareaDescription = col_character(),
StratumCode = col_integer(),
Areakm2 = col_integer()
)) %>%
select(StratumCode, Areakm2) %>%
rename(stratum = StratumCode)
ebs <- left_join(ebs_data, ebs_strata, by = "stratum")
# are there any strata in the data that are not in the strata file?
stopifnot(nrow(filter(ebs, is.na(Areakm2))) == 0)
ebs <- ebs %>%
mutate(
# Create a unique haulid
haulid = paste(formatC(VESSEL, width=3, flag=0), CRUISE, formatC(HAUL, width=3, flag=0), sep='-'),
# convert -9999 to NA
wtcpue = ifelse(WTCPUE == "-9999", NA, WTCPUE)) %>%
# rename columns
rename(year = YEAR,
lat = LATITUDE,
lon = LONGITUDE,
depth = BOT_DEPTH,
spp = SCIENTIFIC,
stratumarea = Areakm2) %>%
# remove eggs
filter(spp != '' &
!grepl("egg", spp)) %>%
# adjust spp names
mutate(spp = ifelse(grepl("Atheresthes", spp), "Atheresthes sp.", spp),
spp = ifelse(grepl("Lepidopsetta", spp), "Lepidopsetta sp.", spp),
spp = ifelse(grepl("Myoxocephalus", spp), "Myoxocephalus sp.", spp),
spp = ifelse(grepl("Bathyraja", spp), 'Bathyraja sp.', spp),
spp = ifelse(grepl("Hippoglossoides", spp), "Hippoglossoides sp.", spp)) %>%
# change from all character to fitting column types
type_convert(col_types = cols(
lat = col_double(),
lon = col_double(),
STATION = col_character(),
year = col_integer(),
DATETIME = col_character(),
wtcpue = col_double(),
NUMCPUE = col_double(),
COMMON = col_character(),
spp = col_character(),
SID = col_integer(),
depth = col_integer(),
BOT_TEMP = col_double(),
SURF_TEMP = col_double(),
VESSEL = col_integer(),
CRUISE = col_integer(),
HAUL = col_integer(),
haulid = col_character()
)) %>%
group_by(haulid, stratum, stratumarea, year, lat, lon, depth, spp) %>%
summarise(wtcpue = sumna(wtcpue)) %>%
# add region column
mutate(region = "Eastern Bering Sea") %>%
select(region, haulid, year, lat, lon, stratum, stratumarea, depth, spp, wtcpue) %>%
ungroup()
if (HQ_DATA_ONLY == TRUE){
# look at the graph and make sure decisions to keep or eliminate data make sense
p1 <- ebs %>%
select(stratum, year) %>%
ggplot(aes(x = as.factor(stratum), y = as.factor(year))) +
geom_jitter()
p2 <- ebs %>%
select(lat, lon) %>%
ggplot(aes(x = lon, y = lat)) +
geom_jitter()
test <- ebs %>%
select(stratum, year) %>%
distinct() %>%
group_by(stratum) %>%
summarise(count = n()) %>%
filter(count >= 36)
# how many rows will be lost if only stratum trawled ever year are kept?
test2 <- ebs %>%
filter(stratum %in% test$stratum)
nrow(ebs) - nrow(test2)
# percent that will be lost
print((nrow(ebs) - nrow(test2))/nrow(ebs))
# 4.7% of rows are removed
ebs_fltr <- ebs %>%
filter(stratum %in% test$stratum)
p3 <- ebs_fltr %>%
select(stratum, year) %>%
ggplot(aes(x = as.factor(stratum), y = as.factor(year))) +
geom_jitter()
p4 <- ebs_fltr %>%
select(lat, lon) %>%
ggplot(aes(x = lon, y = lat)) +
geom_jitter()
if (HQ_PLOTS == TRUE){
temp <- grid.arrange(p1, p2, p3, p4, nrow = 2)
ggsave(plot = temp, filename = here::here("plots", "ebs_hq_dat_removed.png"))
rm(temp)
}
rm(test, test2, p1, p2, p3, p4)
}
# clean up
rm(files, ebs_data, ebs_strata)
# Compile GOA =============================================================
print("Compile GOA")
files <- as.list(dir(pattern = "goa", path = "data_raw", full.names = T))
# exclude the 2 strata files; the 1 and 2 elements
files <- files[-grep("strata", files)]
# combine all of the data files into one table
goa_data <- files %>%
# read in all of the csv's in the files list
purrr::map_dfr(read_csv) %>%
# remove any data rows that have headers as data rows
filter(LATITUDE != "LATITUDE", !is.na(LATITUDE)) %>%
mutate(stratum = as.integer(STRATUM)) %>%
# remove unused columns
select(-STATION, -DATETIME, -NUMCPUE, -SID, -BOT_TEMP, -SURF_TEMP, -STRATUM)
# import the strata data
files <- as.list(dir(pattern = "goa_strata", path = "data_raw", full.names = T))
goa_strata <- files %>%
# read in all of the csv's in the files list
purrr::map_dfr(read_csv) %>%
select(StratumCode, Areakm2) %>%
distinct() %>%
rename(stratum = StratumCode)
goa <- left_join(goa_data, goa_strata, by = "stratum")
# are there any strata in the data that are not in the strata file?
stopifnot(nrow(filter(goa, is.na(Areakm2))) == 0)
goa <- goa %>%
mutate(
# Create a unique haulid
haulid = paste(formatC(VESSEL, width=3, flag=0), CRUISE, formatC(HAUL, width=3, flag=0), sep='-'),
wtcpue = ifelse(WTCPUE == "-9999", NA, WTCPUE)) %>%
rename(year = YEAR,
lat = LATITUDE,
lon = LONGITUDE,
depth = BOT_DEPTH,
spp = SCIENTIFIC,
stratumarea = Areakm2) %>%
# remove non-fish
filter(
spp != '' &
!grepl("egg", spp)) %>%
# adjust spp names
mutate(
spp = ifelse(grepl("Lepidopsetta", spp), "Lepidopsetta sp.", spp),
spp = ifelse(grepl("Myoxocephalus", spp ) & !grepl("scorpius", spp), "Myoxocephalus sp.", spp),
spp = ifelse(grepl("Bathyraja", spp) & !grepl("panthera", spp), 'Bathyraja sp.', spp)
) %>%
type_convert(col_types = cols(
lat = col_double(),
lon = col_double(),
STATION = col_character(),
year = col_integer(),
DATETIME = col_character(),
wtcpue = col_double(),
NUMCPUE = col_double(),
COMMON = col_character(),
spp = col_character(),
SID = col_integer(),
depth = col_integer(),
BOT_TEMP = col_double(),
SURF_TEMP = col_double(),
VESSEL = col_integer(),
CRUISE = col_integer(),
HAUL = col_integer(),
haulid = col_character()
)) %>%
group_by(haulid, stratum, stratumarea, year, lat, lon, depth, spp) %>%
summarise(wtcpue = sumna(wtcpue)) %>%
mutate(region = "Gulf of Alaska") %>%
select(region, haulid, year, lat, lon, stratum, stratumarea, depth, spp, wtcpue) %>%
ungroup()
if (HQ_DATA_ONLY == TRUE){
# look at the graph and make sure decisions to keep or eliminate data make sense
p1 <- goa %>%
select(stratum, year) %>%
ggplot(aes(x = as.factor(stratum), y = as.factor(year))) +
geom_jitter()
p2 <- goa %>%
select(lat, lon) %>%
ggplot(aes(x = lon, y = lat)) +
geom_jitter()
# for GOA in 2018, 2001 missed 27 strata and will be removed, stratum 50 is
# missing from 3 years but will be kept, 410, 420, 430, 440, 450 are missing
#from 3 years but will be kept, 510 and higher are missing from 7 or more years
# of data and will be removed
test <- goa %>%
filter(year != 2001) %>%
select(stratum, year) %>%
distinct() %>%
group_by(stratum) %>%
summarise(count = n()) %>%
filter(count >= 14)
# how many rows will be lost if only stratum trawled ever year are kept?
test2 <- goa %>%
filter(stratum %in% test$stratum)
nrow(goa) - nrow(test2)
# percent that will be lost
print ((nrow(goa) - nrow(test2))/nrow(goa))
# 4% of rows are removed
goa_fltr <- goa %>%
filter(stratum %in% test$stratum) %>%
filter(year != 2001)
p3 <- goa_fltr %>%
select(stratum, year) %>%
ggplot(aes(x = as.factor(stratum), y = as.factor(year))) +
geom_jitter()
p4 <- goa_fltr %>%
select(lat, lon) %>%
ggplot(aes(x = lon, y = lat)) +
geom_jitter()
if (HQ_PLOTS == TRUE){
temp <- grid.arrange(p1, p2, p3, p4, nrow = 2)
ggsave(plot = temp, filename = here::here("plots", "goa_hq_dat_removed.png"))
rm(temp)
}
rm(test, test2, p1, p2, p3, p4)
}
rm(files, goa_data, goa_strata)
# Compile WCTRI ===========================================================
print("Compile WCTRI")
wctri_catch <- read_csv(here::here("data_raw", "wctri_catch.csv"), col_types = cols(
CRUISEJOIN = col_integer(),
HAULJOIN = col_integer(),
CATCHJOIN = col_integer(),
REGION = col_character(),
VESSEL = col_integer(),
CRUISE = col_integer(),
HAUL = col_integer(),
SPECIES_CODE = col_integer(),
WEIGHT = col_double(),
NUMBER_FISH = col_integer(),
SUBSAMPLE_CODE = col_character(),
VOUCHER = col_character(),
AUDITJOIN = col_integer()
)) %>%
select(CRUISEJOIN, HAULJOIN, VESSEL, CRUISE, HAUL, SPECIES_CODE, WEIGHT)
wctri_haul <- read_csv(here::here("data_raw", "wctri_haul.csv"), col_types =
cols(
CRUISEJOIN = col_integer(),
HAULJOIN = col_integer(),
REGION = col_character(),
VESSEL = col_integer(),
CRUISE = col_integer(),
HAUL = col_integer(),
HAUL_TYPE = col_integer(),
PERFORMANCE = col_double(),
START_TIME = col_character(),
DURATION = col_double(),
DISTANCE_FISHED = col_double(),
NET_WIDTH = col_double(),
NET_MEASURED = col_character(),
NET_HEIGHT = col_double(),
STRATUM = col_integer(),
START_LATITUDE = col_double(),
END_LATITUDE = col_double(),
START_LONGITUDE = col_double(),
END_LONGITUDE = col_double(),
STATIONID = col_character(),
GEAR_DEPTH = col_integer(),
BOTTOM_DEPTH = col_integer(),
BOTTOM_TYPE = col_integer(),
SURFACE_TEMPERATURE = col_double(),
GEAR_TEMPERATURE = col_double(),
WIRE_LENGTH = col_integer(),
GEAR = col_integer(),
ACCESSORIES = col_integer(),
SUBSAMPLE = col_integer(),
AUDITJOIN = col_integer()
)) %>%
select(CRUISEJOIN, HAULJOIN, VESSEL, CRUISE, HAUL, HAUL_TYPE, PERFORMANCE, START_TIME, DURATION, DISTANCE_FISHED, NET_WIDTH, STRATUM, START_LATITUDE, END_LATITUDE, START_LONGITUDE, END_LONGITUDE, STATIONID, BOTTOM_DEPTH)
wctri_species <- read_csv(here::here("data_raw", "wctri_species.csv"), col_types = cols(
SPECIES_CODE = col_integer(),
SPECIES_NAME = col_character(),
COMMON_NAME = col_character(),
REVISION = col_character(),
BS = col_character(),
GOA = col_character(),
WC = col_character(),
AUDITJOIN = col_integer()
)) %>%
select(SPECIES_CODE, SPECIES_NAME, COMMON_NAME)
# Add haul info to catch data
wctri <- left_join(wctri_catch, wctri_haul, by = c("CRUISEJOIN", "HAULJOIN", "VESSEL", "CRUISE", "HAUL"))
# add species names
wctri <- left_join(wctri, wctri_species, by = "SPECIES_CODE")
wctri <- wctri %>%
# trim to standard hauls and good performance
filter(HAUL_TYPE == 3 & PERFORMANCE == 0) %>%
# Create a unique haulid
mutate(
haulid = paste(formatC(VESSEL, width=3, flag=0), formatC(CRUISE, width=3, flag=0), formatC(HAUL, width=3, flag=0), sep='-'),
# Extract year where needed
year = substr(CRUISE, 1, 4),
# Add "strata" (define by lat, lon and depth bands) where needed # degree bins # 100 m bins # no need to use lon grids on west coast (so narrow)
stratum = paste(floor(START_LATITUDE)+0.5, floor(BOTTOM_DEPTH/100)*100 + 50, sep= "-"),
# adjust for tow area # weight per hectare (10,000 m2)
wtcpue = (WEIGHT*10000)/(DISTANCE_FISHED*1000*NET_WIDTH)
)
# Calculate stratum area where needed (use convex hull approach)
wctri_strats <- wctri %>%
group_by(stratum) %>%
summarise(stratumarea = calcarea(START_LONGITUDE, START_LATITUDE))
wctri <- left_join(wctri, wctri_strats, by = "stratum")
wctri <- wctri %>%
rename(
svvessel = VESSEL,
lat = START_LATITUDE,
lon = START_LONGITUDE,
depth = BOTTOM_DEPTH,
spp = SPECIES_NAME
) %>%
filter(
spp != "" &
!grepl("egg", spp)
) %>%
# adjust spp names
mutate(spp = ifelse(grepl("Lepidopsetta", spp), "Lepidopsetta sp.", spp),
spp = ifelse(grepl("Bathyraja", spp), 'Bathyraja sp.', spp),
spp = ifelse(grepl("Squalus", spp), 'Squalus suckleyi', spp)) %>%
group_by(haulid, stratum, stratumarea, year, lat, lon, depth, spp) %>%
summarise(wtcpue = sumna(wtcpue)) %>%
# add region column
mutate(region = "West Coast Triennial") %>%
select(region, haulid, year, lat, lon, stratum, stratumarea, depth, spp, wtcpue) %>%
ungroup()
if (HQ_DATA_ONLY == TRUE){
# look at the graph and make sure decisions to keep or eliminate data make sense
p1 <- wctri %>%
select(stratum, year) %>%
ggplot(aes(x = as.factor(stratum), y = as.factor(year))) +
geom_jitter()
p2 <- wctri %>%
select(lat, lon) %>%
ggplot(aes(x = lon, y = lat)) +
geom_jitter()
test <- wctri %>%
select(stratum, year) %>%
distinct() %>%
group_by(stratum) %>%
summarise(count = n()) %>%
filter(count >= 10)
# how many rows will be lost if only stratum trawled ever year are kept?
test2 <- wctri %>%
filter(stratum %in% test$stratum)
nrow(wctri) - nrow(test2)
# percent that will be lost
print((nrow(wctri) - nrow(test2))/nrow(wctri))
# 23% of rows are removed
wctri_fltr <- wctri %>%
filter(stratum %in% test$stratum)
p3 <- wctri_fltr %>%
select(stratum, year) %>%
ggplot(aes(x = as.factor(stratum), y = as.factor(year))) +
geom_jitter()
p4 <- wctri_fltr %>%
select(lat, lon) %>%
ggplot(aes(x = lon, y = lat)) +
geom_jitter()
if (HQ_PLOTS == TRUE){
temp <- grid.arrange(p1, p2, p3, p4, nrow = 2)
ggsave(plot = temp, filename = here::here("plots", "wctri_hq_dat_removed.png"))
rm(temp)
}
rm(test, test2, p1, p2, p3, p4)
}
rm(wctri_catch, wctri_haul, wctri_species, wctri_strats)
# Compile WCANN ===========================================================
print("Compile WCANN")
# commented line previously unzipped the zipped csv file, but current line reads directly from the csv
wcann_catch <- read_csv(unz(here::here("data_raw", "wcann_catch.csv.zip"), "wcann_catch.csv"), col_types = cols(
#wcann_catch <- read_csv(here::here("data_raw", "wcann_catch.csv"), col_types = cols(
catch_id = col_integer(),
common_name = col_character(),
cpue_kg_per_ha_der = col_double(),
cpue_numbers_per_ha_der = col_double(),
date_yyyymmdd = col_integer(),
depth_m = col_double(),
latitude_dd = col_double(),
longitude_dd = col_double(),
pacfin_spid = col_character(),
partition = col_character(),
performance = col_character(),
program = col_character(),
project = col_character(),
sampling_end_hhmmss = col_character(),
sampling_start_hhmmss = col_character(),
scientific_name = col_character(),
station_code = col_double(),
subsample_count = col_integer(),
subsample_wt_kg = col_double(),
total_catch_numbers = col_integer(),
total_catch_wt_kg = col_double(),
tow_end_timestamp = col_datetime(format = ""),
tow_start_timestamp = col_datetime(format = ""),
trawl_id = col_double(),
vessel = col_character(),
vessel_id = col_integer(),
year = col_integer(),
year_stn_invalid = col_integer()
)) %>%
select("trawl_id","year","longitude_dd","latitude_dd","depth_m","scientific_name","total_catch_wt_kg","cpue_kg_per_ha_der", "partition")
wcann_haul <- read_csv(here::here("data_raw", "wcann_haul.csv"), col_types = cols(
area_swept_ha_der = col_double(),
date_yyyymmdd = col_integer(),
depth_hi_prec_m = col_double(),
invertebrate_weight_kg = col_double(),
latitude_hi_prec_dd = col_double(),
longitude_hi_prec_dd = col_double(),
mean_seafloor_dep_position_type = col_character(),
midtow_position_type = col_character(),
nonspecific_organics_weight_kg = col_double(),
performance = col_character(),
program = col_character(),
project = col_character(),
sample_duration_hr_der = col_double(),
sampling_end_hhmmss = col_character(),
sampling_start_hhmmss = col_character(),
station_code = col_double(),
tow_end_timestamp = col_datetime(format = ""),
tow_start_timestamp = col_datetime(format = ""),
trawl_id = col_double(),
vertebrate_weight_kg = col_double(),
vessel = col_character(),
vessel_id = col_integer(),
year = col_integer(),
year_stn_invalid = col_integer()
)) %>%
select("trawl_id","year","longitude_hi_prec_dd","latitude_hi_prec_dd","depth_hi_prec_m","area_swept_ha_der")
# It is ok to get warning message that missing column names filled in: 'X1' [1].
wcann <- left_join(wcann_haul, wcann_catch, by = c("trawl_id", "year"))
wcann <- wcann %>%
mutate(
# create haulid
haulid = trawl_id,
# Add "strata" (define by lat, lon and depth bands) where needed # no need to use lon grids on west coast (so narrow)
stratum = paste(floor(latitude_dd)+0.5, floor(depth_m/100)*100 + 50, sep= "-"),
# adjust for tow area # kg per hectare (10,000 m2)
wtcpue = total_catch_wt_kg/area_swept_ha_der
)
wcann_strats <- wcann %>%
filter(!is.na(longitude_dd)) %>%
group_by(stratum) %>%
summarise(stratumarea = calcarea(longitude_dd, latitude_dd), na.rm = T)
wcann <- left_join(wcann, wcann_strats, by = "stratum")
wcann <- wcann %>%
rename(lat = latitude_dd,
lon = longitude_dd,
depth = depth_m,
spp = scientific_name) %>%
# remove non-fish
filter(!grepl("Egg", partition),
!grepl("crushed", spp)) %>%
# adjust spp names
mutate(
spp = ifelse(grepl("Lepidopsetta", spp), "Lepidopsetta sp.", spp),
spp = ifelse(grepl("Bathyraja", spp), 'Bathyraja sp.', spp)
) %>%
group_by(haulid, stratum, stratumarea, year, lat, lon, depth, spp) %>%
summarise(wtcpue = sumna(wtcpue)) %>%
# add region column
mutate(region = "West Coast Annual") %>%
select(region, haulid, year, lat, lon, stratum, stratumarea, depth, spp, wtcpue) %>%
ungroup()
if (HQ_DATA_ONLY == TRUE){
# keep the same footprint as wctri
# how many rows of data will be lost?
nrow(wcann) - nrow(filter(wcann, stratum %in% wctri$stratum))
# percent that will be lost - 61% !
(nrow(wcann) - nrow(filter(wcann, stratum %in% wctri$stratum)))/nrow(wcann)
wcann_fltr <- wcann %>%
filter(stratum %in% wcann$stratum)
# see what these data look like - pretty solid
p1 <- wcann_fltr %>%
select(stratum, year) %>%
ggplot(aes(x = as.factor(stratum), y = as.factor(year))) +
geom_jitter()
p2 <- wcann_fltr %>%
select(lat, lon) %>%
ggplot(aes(x = lon, y = lat)) +
geom_jitter()
if (HQ_PLOTS == TRUE){
temp <- grid.arrange(p1, p2, nrow = 2)
ggsave(plot = temp, filename = here::here("plots", "wcann_hq_dat_removed.png"))
rm(temp)
}
rm(p1, p2)
}
# cleanup
rm(wcann_catch, wcann_haul, wcann_strats)
# Compile GMEX ===========================================================
print("Compile GMEX")
gmex_station_raw <- read_lines(here::here("data_raw", "gmex_STAREC.csv"))
# remove oddly quoted characters
#gmex_station_clean <- str_replace_all(gmex_station_raw, "\\\\\\\"", "\\\"\\\"")
gmex_station_clean <- str_replace_all(gmex_station_raw, "\\\\\"", "")
#gmex_station_clean <- gsub('\"', "", gmex_station_clean)
gmex_station <- read_csv(gmex_station_clean, col_types = cols(.default = col_character())) %>%
select('STATIONID', 'CRUISEID', 'CRUISE_NO', 'P_STA_NO', 'TIME_ZN', 'TIME_MIL', 'S_LATD', 'S_LATM', 'S_LOND', 'S_LONM', 'E_LATD', 'E_LATM', 'E_LOND', 'E_LONM', 'DEPTH_SSTA', 'MO_DAY_YR', 'VESSEL_SPD', 'COMSTAT')
problems <- problems(gmex_station) %>%
filter(!is.na(col))
stopifnot(nrow(problems) == 0)
gmex_station <- type_convert(gmex_station, col_types = cols(
STATIONID = col_integer(),
CRUISEID = col_integer(),
CRUISE_NO = col_integer(),
P_STA_NO = col_character(),
TIME_ZN = col_integer(),
TIME_MIL = col_character(),
S_LATD = col_integer(),
S_LATM = col_double(),
S_LOND = col_integer(),
S_LONM = col_double(),
E_LATD = col_integer(),
E_LATM = col_double(),
E_LOND = col_integer(),
E_LONM = col_double(),
DEPTH_SSTA = col_double(),
MO_DAY_YR = col_date(format = ""),
VESSEL_SPD = col_double(),
COMSTAT = col_character()
))
gmex_tow <-read_csv(here::here("data_raw", "gmex_INVREC.csv"), col_types = cols(
INVRECID = col_integer(),
STATIONID = col_integer(),
CRUISEID = col_integer(),
VESSEL = col_integer(),
CRUISE_NO = col_integer(),