-
Notifications
You must be signed in to change notification settings - Fork 2
/
sala_etal_reply.Rmd
2071 lines (1465 loc) · 71.7 KB
/
sala_etal_reply.Rmd
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
---
title: |
| Global effects of marine protected areas
| on food security are unknown
output:
bookdown::pdf_document2:
latex_engine: xelatex
number_sections: false
bookdown::word_document2:
reference_docx: template.docx
bibliography: references.bib
linkcolor: blue
urlcolor: blue
csl: nature.csl
toc: FALSE
header-includes:
- \usepackage{setspace}\doublespacing
- \usepackage{lineno}\linenumbers
params:
results_name: ["local_dd"]
divide_stocks: [FALSE]
run_regional_sala_etal: [FALSE]
run_global_sala_etal: [FALSE]
local_dd: [1]
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, message = FALSE, warning = FALSE,include = FALSE)
set.seed(225)
# probably don't need all these but copying from Cabral et al
library(bookdown)
library(foreach)
library(doParallel)
library(raster)
library(rgdal)
library(maptools)
library(dplyr)
library(pryr)
library(ggplot2)
library(reshape)
library(data.table)
library(here)
library(scales)
library(tidyverse)
library(countrycode)
library(patchwork)
library(devtools)
library(ramlegacy)
library(sf)
library(smoothr)
library(rnaturalearth)
library(Rcpp)
library(ggrepel)
library(cowplot)
library(furrr)
options(timeout=2000)
rename <- dplyr::rename
Rcpp::sourceCpp(here('src', "sim_mpa.cpp"))
local_cores <- 6 # number of cores for parallel processing
theme_set(theme_cowplot(font_family = "Helvetica"))
sir_samps <- 2500 # set this to 1e9 or the like to do brute force instead of SIR
PICKSIZE <- 25 #number of MPA sites selected at once
results_name <- params$results_name # name of folder to store results
divide_stocks <- params$divide_stocks # FALSE load up prior stock division since it takes a while, TRUE recreate it
run_regional_sala_etal <- params$run_regional_sala_etal # run local resolution experiment
run_global_sala_etal <- params$run_global_sala_etal # run sala et al. version
local_dd <- params$local_dd # use local density dependence (1) or pooled (0)
use_ray <- TRUE # use megadata_ray or megadata
pt <- 1 # use pella tomlinson model or force schaefer
plim <- 0.2 # cuttoff for growth correction in pt model
upsides_r <- TRUE # use upsides based growth rate or FishLife based r
lower_m <- FALSE
mpa_sim_years <- 50 # number of years to run MPA simulation
results_path <- here("results", results_name)
get_fao_data <- FALSE
if (!dir.exists(results_path)){
dir.create(results_path, recursive = TRUE)
}
```
```{r load data}
# download data used in Cabral et al. 2020
if (!dir.exists("data")) {
options(timeout = max(600, getOption("timeout")))
download.file(
"https://figshare.com/ndownloader/files/35063767",
destfile = here("tmp.zip"),
mode = "wb",
timeout =
)
unzip(here("tmp.zip"))
# file.rename("food-provision-data","data")
file.remove("tmp.zip")
if (dir.exists("__MACOSX")) {
unlink("__MACOSX", recursive = TRUE)
}
download.file("https://github.com/rencabral/pnas-correction-food/raw/master/MegaData_Ray.rds", here("data","MegaData_Ray.rds"))
}
# pull in FAO capture statistics
if (get_fao_data | !dir.exists(here("data", "fao"))) {
if (!dir.exists(here("data", "fao"))) {
dir.create(here("data", "fao"))
download.file(
"http://www.fao.org/fishery/static/Data/Capture_2019.1.0.zip",
destfile = here("data", "fao.zip"),
mode = "wb"
)
unzip(here("data", "fao.zip"), exdir = here("data", "fao"))
file.remove(here("data", "fao.zip"))
download.file(
"http://www.fao.org/fishery/static/ASFIS/ASFIS_sp.zip",
destfile = here("data", "asfis.zip"),
mode = "wb"
)
unzip(here("data", "asfis.zip"), exdir = here("data", "fao"))
file.remove(here("data", "asfis.zip"))
}
find_asfis <- list.files(here("data", "fao"))
find_asfis <- find_asfis[str_detect(find_asfis,"^ASFIS.*.txt$")] # needed since years can change
asfis <-
read_delim(here("data", "fao", find_asfis), delim = ",") %>%
janitor::clean_names() %>%
rename(isscaap_code = isscaap) %>%
select(isscaap_code, scientific_name, taxocode) %>%
unique()
# major issue with NEIs here. There is no database that has both isscaap group and isscaap code, so you need
# to do a complicated merge based on scientific name.
fao_capture <-
read_csv(here("data", "fao", "TS_FI_CAPTURE.csv")) %>%
janitor::clean_names() %>%
mutate(country = as.integer(country),
fishing_area = as.integer(fishing_area))
sp_groups <-
read_csv(here("data", "fao", "CL_FI_SPECIES_GROUPS.csv")) %>%
janitor::clean_names() %>%
select(scientific_name,x3alpha_code:identifier, contains("_en"), author:cpc_group) %>%
rename(species_name_en = name_en) %>%
left_join(asfis, by = c("scientific_name"))
# sp_groups <-
# read_csv(here("data", "fao", "CL_FI_SPECIES_GROUPS.csv")) %>%
# janitor::clean_names() %>%
# select(x3alpha_code:identifier, contains("_en"), author:cpc_group) %>%
# rename(species_name_en = name_en) %>%
# left_join(asfis, by = c("taxonomic_code" = "taxocode"))
# sp_groups %>%
# group_by(x3alpha_code) %>%
# summarise(ni = n_distinct(isscaap_group)) %>%
# arrange(desc(ni))
country_groups <-
read_csv(here("data", "fao", "CL_FI_COUNTRY_GROUPS.csv")) %>%
janitor::clean_names() %>%
mutate(un_code = as.numeric(un_code)) %>%
select(un_code:iso3_code, contains("_en")) %>%
rename(country_name_en = name_en,
country_official_name_en = official_name_en)
fao_areas <-
read_csv(here("data", "fao", "CL_FI_WATERAREA_GROUPS.csv")) %>%
janitor::clean_names() %>%
mutate(fishing_area = as.numeric(code)) %>%
select(fishing_area, contains("_en"), contains("group"))
fao_capture <- fao_capture %>%
left_join(sp_groups, by = c("species" = "x3alpha_code"))
fao_capture <- fao_capture %>%
left_join(country_groups, by = c("country" = "un_code")) %>%
left_join(fao_areas, by = "fishing_area")
fao_capture$fao_country_name <-
countrycode::countrycode(fao_capture$country_name_en, "country.name", "un.name.en")
fao_capture <- fao_capture %>%
mutate(country = case_when(
is.na(fao_country_name) ~ country_name_en,
TRUE ~ fao_country_name
)) %>%
mutate(continent = countrycode::countrycode(country, "country.name", "continent"))
fao_capture <- fao_capture %>%
rename(
isscaap_number = isscaap_code,
common_name = species_name_en,
capture = quantity,
capture_units = unit,
fao_area_code = fishing_area,
fao_area = name_en
) %>%
mutate(fao_stock = paste(common_name, country, fao_area, sep = '_'))
fao_capture <- fao_capture %>%
group_by(fao_stock) %>%
nest() %>%
ungroup() %>%
mutate(id = 1:nrow(.)) %>%
unnest(cols = data)
fao_capture <- fao_capture %>%
select(id, fao_stock, everything())
fao <- fao_capture %>%
filter(capture_units == "t",
isscaap_number < 67)
fao_stock_lookup <- fao %>%
select(scientific_name,
common_name,
country,
fao_area,
fao_area_code) %>%
unique()
fao_species <- fao %>%
select(scientific_name, common_name, isscaap_group, isscaap_number) %>%
unique()
fao_genus <-
str_split(fao_species$scientific_name, ' ', simplify = TRUE)[, 1]
fao_genus <- fao_species %>%
mutate(genus = fao_genus) %>%
group_by(genus, isscaap_group) %>%
count() %>%
group_by(genus) %>%
filter(n == max(n)) %>%
select(-n) %>%
ungroup()
write_rds(fao_capture, file = here("data", "fao", "fao-capture.rds"))
} else {
fao_capture <-
read_rds(file = here("data", "fao", "fao-capture.rds"))
}
# get FAO shapefile
if (!dir.exists(here("data", "FAO_AREAS_NOCOASTLINE"))) {
download.file(url = "http://www.fao.org/fishery/geoserver/fifao/ows?service=WFS&request=GetFeature&version=1.0.0&typeName=fifao:FAO_AREAS_CWP_NOCOASTLINE&outputFormat=SHAPE-ZIP",
destfile = here("data", "FAO_AREAS_NOCOASTLINE.zip"), mode = "wb")
unzip(
here("data", "FAO_AREAS_NOCOASTLINE.zip"),
exdir = here("data", "FAO_AREAS_NOCOASTLINE")
)
}
fao_areas <- sf::st_read(here('data', "FAO_AREAS_NOCOASTLINE")) %>%
janitor::clean_names()
fao_areas <- sf::st_read(here('data', "FAO_AREAS_NOCOASTLINE"), promote_to_multi = FALSE) %>%
janitor::clean_names() %>%
filter(f_level == "MAJOR") %>%
mutate(fao_area_code = as.numeric(f_area)) #%>%
fao_areas %>% ggplot() + geom_sf()
# land_shp_moll <- readRDS(file = here("data", "land_shp_moll.rds"))
# land_shp_moll %>%
# ggplot() +
# geom_sf()
land_shp_moll = rnaturalearth::ne_download(category = "physical", type = "land",scale = 110, returnclass = "sf") %>%
st_transform(crs = "+proj=moll")
# test %>%
# ggplot() +
# geom_sf()
eezs <-
sf::read_sf(here("data", "World_EEZ_v11_20191118_LR", "eez_v11_lowres.shp")) %>%
mutate(iso3_code = countrycode(SOVEREIGN1, "country.name", "iso3c")) %>%
mutate(iso3c_name = countrycode(iso3_code, "iso3c", "country.name")) %>%
filter(!is.na(iso3_code)) %>%
sf::st_transform(sf::st_crs(land_shp_moll))
# run results with local density dependence and at local resolution
# redo with corrected ram -------------------------------------------------
scenario <- "BAU1"
MegaData <- readRDS(file = here("data", "MegaData.rds"))
og_mega_data <- MegaData
Cleanmegacell <-
readRDS(file = here("data", "Cleanmegacell_mollweide.rds"))
CleanCoordmegacell <-
readRDS(file = here("data", "CleanCoordmegacell_mollweide.rds"))
KprotectedPerCell_Library <-
readRDS(file = here("data", "KprotectedPerCell_Library_mollweide.rds"))
dimnames(KprotectedPerCell_Library) <- list(MegaData$stockid, 1:ncol(KprotectedPerCell_Library))
dimnames(Cleanmegacell) <- list(1:nrow(Cleanmegacell),MegaData$stockid)
megadata_ray <- readRDS(file = here("data", "MegaData_ray.rds")) %>%
filter(INCLUDE == 1)
if (use_ray){
MegaData <- readRDS(file = here("data", "MegaData_ray.rds")) %>%
filter(INCLUDE == 1,
stockid %in% unique(MegaData$stockid)) # because access is not provided for the underlying habitat layers, have to match it down to stocks with match in origial MegaData
og_mega_data <- readRDS(file = here("data", "MegaData_ray.rds")) %>%
filter(INCLUDE == 1)
KprotectedPerCell_Library <- KprotectedPerCell_Library[MegaData$stockid,]
Cleanmegacell <- Cleanmegacell[,MegaData$stockid]
}
MPA_coord <-
readRDS(file = here("data", "MPA_coord_mollweide.rds")) #this is my code
# load upsides
upsides <-
read_csv(here("data", "upsides", "ProjectionData.csv")) %>%
janitor::clean_names()
upsides$g <- pmin(upsides$g, 1.6) # weird things start to happen at higher values
phi <- unique(upsides$phi)
if (n_distinct(phi) > 1){
stop("Multiple phis present, assign individually to each stock")
}
# pull in RAM data
if (file.exists(here("data", "ram.zip")) == FALSE) {
download.file("https://zenodo.org/record/4824192/files/RAMLDB%20v4.495.zip?download=1", destfile = here("data","ram.zip"), mode = "wb"
)
unzip(here("data","ram.zip"), exdir = here("data","ram"))
}
ram_files <- list.files(here("data","ram","R Data"))
ram_files <- ram_files[str_detect(ram_files,".RData")]
load(here("data","ram","R Data",ram_files))
# the correct attribute to pull for food security is UdivUmsypref
ram_bau <-
timeseries_values_views %>%
dplyr::select(stockid, year, UdivUmsypref) %>%
janitor::clean_names() %>%
group_by(stockid) %>%
filter(!is.na(udiv_umsypref)) %>%
filter(year == max(year)) %>%
dplyr::select(-year) %>%
mutate(udiv_umsypref = pmin(2,udiv_umsypref)) # for consistencey of comparison, cap U/UMSY at 2 (even though can be higher in EQ under PT)
ram_msy <-
assessid_to_stockid <- assessment %>%
select(assessid, stockid)
upsides_ram_data <- upsides %>%
filter(dbase == "RAM",
policy == "Historic")
# sigh. stockid is in confusing places, but seems to always be before year. So, here we go
get_stockid <- function(x){
a = str_extract(x, "((?<=\\-).*?)(?=\\-\\d)") # give me everything after a dash and before the first digit after a dash
}
stockids <- map_chr(upsides_ram_data$id_orig, get_stockid) #annoying and very outdated issue with upsides using assessid that no longer exist
upsides_ram_data$stockid <- stockids #stockid is second column
# left_join(assessid_to_stockid, by = c("id_orig" = "assessid")) %>%
upsides_ram_data <- upsides_ram_data %>%
select(stockid, g, msy, k) %>%
unique()
# Update RAM stocks with most recent assessment values
MegaData <- MegaData %>%
left_join(ram_bau, by = "stockid")
MegaData$u_bau_ram <- MegaData$udiv_umsypref * (MegaData$r / 2) # calculate u given MegaData growth rate and RAM U/UMSY
MegaData$Efin_BAU1[MegaData$Manage == 1 & !is.na(MegaData$udiv_umsypref)] <- 1 - MegaData$u_bau_ram[MegaData$Manage == 1 & !is.na(MegaData$udiv_umsypref)] # convert to escapement for reasons that escape me. For RAM stocks that don't have a match, stick with old upsides methods...
# filter down to candidate stocks
# candidate stocks have exact matches for RAM, or have a species match for unassessed
# Also, removing problem trachurus trachurus stock
upsides_sciname <- upsides %>%
filter(dbase == "FAO") %>%
select(sci_name) %>%
unique()
unassessed_trachurus <- MegaData %>%
filter(str_detect(SciName, 'Trachurus trachurus'))
viable <-
which(
(MegaData$Manage == 1 & !is.na(MegaData$Efin_BAU1)) |
(
(MegaData$SciName %in% upsides_sciname$sci_name) &
MegaData$Manage == 0
) & MegaData$stockid != unassessed_trachurus$stockid
)
check <- MegaData[viable,]
# filter all the things down to only the stocks that have a viable match in the upsides
MegaData <- MegaData[viable,]
KprotectedPerCell_Library <- KprotectedPerCell_Library[viable,]
Cleanmegacell <- Cleanmegacell[,viable]
baseline_megadata <- MegaData
baseline_k <- KprotectedPerCell_Library
baseline_clean <- Cleanmegacell
# go through and first do the Pella-Tomlinson conversion for just the RAM stocks
# Ends up being much easier to do the unassesesd after
if (pt == 1){
MegaData <- MegaData %>%
left_join(upsides_ram_data, by= "stockid")
MegaData$uvumsy_ram_tmp <- (1 - MegaData$Efin_BAU1) / (MegaData$r/2) # keep track of target U/UMSY
MegaData$g[is.na(MegaData$g)] <- (MegaData$r / ((phi + 1) / phi))[is.na(MegaData$g)] # following Costello et al. 2016, for subset of stocks that look like were added in to MegaData post RAM
MegaData$u_bau_ram <- MegaData$uvumsy_ram_tmp * (MegaData$g) # Pella-Tomlinson so g = Fmsy in this formulation
ogr <- MegaData$r
MegaData$r[MegaData$Manage == 1] <- MegaData$g[MegaData$Manage == 1] # just to keep the rest of the code sane, "g" is now "r"
MegaData$Kfin[MegaData$Manage == 1] <-
((MegaData$MSYfin * ((phi + 1) ^ (1 / phi))) / MegaData$r)[MegaData$Manage == 1] # adjust K to preserve MSY given PT parameters
# check <- (MegaData$r * MegaData$Kfin) / ((phi + 1)^(1 / phi))
#
# plot(check, MegaData$MSYfin)
# abline(a = 0, b = 1)
#
MegaData <- MegaData %>%
select(-g, -msy, -k) # remove upsides thing to avoid confusion
}
MegaData$ram_escapement_bau = 1 - MegaData$u_bau_ram
MegaData %>%
filter(Manage == 1) %>%
ggplot(aes(Efin_BAU1, ram_escapement_bau)) +
geom_point() +
geom_abline(slope = 1, intercept = 0)
MegaData$Efin_BAU1[MegaData$Manage == 1] <-
MegaData$ram_escapement_bau[MegaData$Manage == 1]
MegaData %>%
filter(Manage == 1) %>%
ggplot(aes(Efin_BAU1, ram_escapement_bau)) +
geom_point() +
geom_abline(slope = 1, intercept = 0)
if (nrow(MegaData) != nrow(KprotectedPerCell_Library)){
stop("megadata and k library not same size")
}
# Prepare to split apart and generate the unassessed stocks
# pull out the BAU policy for the upsides
upsides_bau <- upsides %>%
filter(policy == "BAU",
scenario == "Con. Concern") %>%
filter(year == max(year)) %>%
dplyr::rename(bvbmsy_upsides = bv_bmsy,
fvfmsy_upsides = fv_fmsy) %>%
mutate(manage = ifelse(dbase == "FAO", 0, 1))
upsides_bau$iso3_country_code <-
countrycode::countrycode(upsides_bau$country, "country.name", "iso3c")
upsides_bau$iso3_country_name <-
countrycode::countrycode(upsides_bau$iso3_country_code, "iso3c", "country.name")
# get unassessed for megadata
ua_megadata <- MegaData %>%
filter(Manage == 0)
# get unassessed from upsides
ua_upsides_bau <- upsides_bau %>%
filter(sci_name %in% unique(ua_megadata$SciName),
dbase == "FAO",
id_level == "Species")
mean(tolower(unique(ua_megadata$SciName)) %in% tolower(unique(ua_upsides_bau$sci_name)))
# there are some stocks that for some reason MegaData marks as unmanaged but are in RAM
tmp <- CleanCoordmegacell %>%
sf::st_as_sf(coords = c("lon", "lat"),
crs = sf::st_crs(land_shp_moll))
# assign stocks to local resolution defined by upsides stocks
divide_stock <-
function(stock,
MegaData,
KprotectedPerCell_Library,
tmp,
upsides_r,
pt) {
upsides_country <- stock$country[1]
taxa <- stock$sci_name[1]
tmp_eez_code <- stock$iso3_country_code[1]
tmp_fao_area_code <- stock$region_fao[1]
tmp_mega <- ua_megadata %>%
filter(SciName == taxa)
# generate map:
# pull out the row for that taxa from Kprotected....
# convert to shapefile and mask with EEZ and FAO region
# set habitat to zero in all cells outside of intersected area
# return row
global_occurance <-
as.numeric(KprotectedPerCell_Library[which(MegaData$SciName == taxa &
MegaData$Manage == 0)[1], ])
tmp$habitat <- global_occurance
tmp_eez <- eezs %>%
filter(iso3_code == tmp_eez_code)
tmp_fao <- fao_areas %>%
filter(fao_area_code == tmp_fao_area_code) %>%
sf::st_transform(sf::st_crs(land_shp_moll))
tmp_layer <- st_intersects(tmp, tmp_eez, sparse = FALSE)
tmp_eez_layer <- apply(tmp_layer, 1, any)
tmp_layer <- st_intersects(tmp, tmp_fao, sparse = FALSE)
tmp_fao_layer <- apply(tmp_layer, 1, any)
if (upsides_country == "Multinational") {
mask <- tmp_fao_layer
} else {
mask <- tmp_eez_layer & tmp_fao_layer
if (all(mask == FALSE)) {
mask <- tmp_fao_layer
}
}
stock_occurance <- global_occurance
stock_occurance[!mask] <- 0
if (sum(stock_occurance) == 0) {
stock_occurance[mask] <- 1 # this checks for places with reported catch at the eez fao region level but no aquamaps abundance
}
# test <- t(as.matrix(stock_occurance))
tmp %>%
mutate(init = tmp_layer & tmp_fao_layer,
hab = stock_occurance) %>%
ggplot(aes(color = init))+
geom_sf()
# stock_occurance <- t(as.matrix(stock_occurance / sum(stock_occurance, na.rm = TRUE)))
stock_occurance <-
(stock_occurance / sum(stock_occurance, na.rm = TRUE))
if (any(is.na(stock_occurance))) {
stop()
}
# OK that generates a habitat layer for that specific stock
# now update "MegaData" with the correct
# MSYfin
# Efin_BAU1
# The BAU exploitation rate for the unassessed stocks appears to be set such that B/B~MSY~ BAU equals the MSY weighted mean B/B~MSY~ BAU from Costello et al. 2016
if (pt == 0){
if (upsides_r == TRUE){ # keep upsides MSY and K, and then solve for logistic r
tmp_mega$MSYfin <- stock$msy
tmp_mega$Kfin <- stock$k
tmp_mega$r <-
stock$msy * 4 / stock$k # hacky conversion from PT to Schaefer. We use this r instead of the same r due tot eh fact that different stocks of the same species can have different growth rates in the upsides. Hacky because MSY and K are a function of growth rate in PT model, but gets as close as possible
} else {
# keep upsides MSY but MegaData r and solve for local k
tmp_mega$MSYfin <- stock$msy
tmp_mega$Kfin <- (stock$msy * 4) / tmp_mega$r
}
f_fmsy_bau <- 2 - min(2, stock$bvbmsy_upsides)
tmp_mega$Efin_BAU1 <- 1 - f_fmsy_bau * (tmp_mega$r / 2)
} else {
tmp_mega$MSYfin <- stock$msy
tmp_mega$Kfin <- stock$k
tmp_mega$r <- pmin(1,stock$g) # PT model starts to do weird things above 1, and since fmsy = g, g >1 means overfishing is impossible
phi <- stock$phi
f_fmsy_bau <- (phi + 1) / phi * (1 - (stock$bvbmsy_upsides)^phi / (phi + 1)) # assume B is at EQ, I believe that's what they did for megadata
tmp_mega$Efin_BAU1 <- 1 - f_fmsy_bau * tmp_mega$r # pella tomlinson fmsy = g
} # close ifelse pt
out <- list(tmp_mega = tmp_mega, temp_occurance = stock_occurance)
}
if (divide_stocks |
(!file.exists(file.path(results_path, "divided-stocks.rds")))) {
plan(multisession, workers = 6)
divided_stocks <- ua_upsides_bau %>%
group_by(id_orig) %>%
nest() %>%
ungroup() %>%
mutate(
ds = future_map(
data,
divide_stock,
MegaData = MegaData,
KprotectedPerCell_Library = KprotectedPerCell_Library,
tmp = tmp,
upsides_r = upsides_r,
pt = pt,
.progress = TRUE
)
)
write_rds(divided_stocks, file.path(results_path, "divided-stocks.rds"))
} else {
divided_stocks <- read_rds(file.path(results_path, "divided-stocks.rds"))
}
baseline_megadata %>%
group_by(Manage) %>%
count()
MegaData %>%
group_by(Manage) %>%
summarise(n = n_distinct(stockid))
ram_stocks <- MegaData %>%
filter(Manage == 1)
ram_range <- KprotectedPerCell_Library[which(MegaData$Manage == 1), ]
# create unassessed
divided_megadata <- map_df(divided_stocks$ds, "tmp_mega")
if (pt == 1){
divided_megadata$MSYfin <- ua_upsides_bau$msy
divided_megadata$Kfin <- ua_upsides_bau$k
divided_megadata$r <- ua_upsides_bau$g
f_fmsy_bau <- (phi + 1) / phi * (1 - (ua_upsides_bau$bvbmsy_upsides)^phi / (phi + 1)) # assume B is at EQ, I believe that's what they did for megadata
divided_megadata$Efin_BAU1 <- 1 - f_fmsy_bau * divided_megadata$r # pella tomlinson fmsy = g
# plot(ua_upsides_bau$bvbmsy_upsides, f_fmsy_bau)
# plot(ua_upsides_bau$bvbmsy_upsides, (1 - divided_megadata$Efin_BAU1) / divided_megadata$r)
}
divided_k <-
matrix(
NA,
nrow = nrow(divided_megadata),
ncol = ncol(KprotectedPerCell_Library)
)
for (i in 1:nrow(divided_stocks)) {
if (any(is.na(as.numeric(divided_stocks$ds[[i]]$temp_occurance)))) {
stop("something very bad has happened")
}
divided_k[i, ] <-
as.numeric(divided_stocks$ds[[i]]$temp_occurance) # much faster this way
}
# knit it all together
MegaData <- ram_stocks %>%
bind_rows(divided_megadata)
KprotectedPerCell_Library <- ram_range %>%
as.matrix() %>%
rbind(divided_k)
rm(divided_k)
# make sure that your baseline matches the stocks that actually gets run on the local stocks
baseline_megadata <- baseline_megadata[baseline_megadata$stockid %in% unique(MegaData$stockid),]
baseline_k <- baseline_k[baseline_megadata$stockid,]
baseline_megadata %>%
group_by(Manage) %>%
count()
MegaData %>%
group_by(Manage) %>%
summarise(n = n_distinct(stockid))
```
```{r regional-res}
#get MPA positions
CleanCoordmegacell_MPA <-
left_join(CleanCoordmegacell, MPA_coord, by = c("lon", "lat"))
head(CleanCoordmegacell_MPA)
dim(CleanCoordmegacell_MPA)
sum(CleanCoordmegacell_MPA$MPA, na.rm = T)
#positions of 1s (MPAs)
MPAposition <- which(CleanCoordmegacell_MPA$MPA == 1)
head(MPAposition)
length(MPAposition)#2931 --- 2.44% are MPAs
length(MPAposition) * 100 / dim(Cleanmegacell)[1]
##TRY new approach
numcell <- dim(Cleanmegacell)[1]
celltoiterateFULL <- 1:numcell
MPAselect0 <- matrix(0, nrow = numcell, ncol = 1)
PriorityAreas <- c()
NetworkResult <- vector()
#Make MPAselect0==1 for MPAs
MPAselect0[MPAposition] <- 1
head(MPAselect0)
sum(MPAselect0)
#remove MPAs from celltoiterateFULL
celltoiterateFULL <- celltoiterateFULL[-MPAposition]
celltoiterate <- celltoiterateFULL
ncell <- length(celltoiterate)
###Compute spillover---PIXEL-LEVEL spillover
###
if (lower_m == TRUE){
MegaData$m <- MegaData$m * .5
}
K <- MegaData$Kfin # K per species
m <- MegaData$m # mobility per species
r <- MegaData$r
if (any(is.na(r) | is.na(phi))){
stop("something has gone wrong with life history")
}
# phi <- MegaData$phi
if (scenario == "all managed") {
E <- MegaData$Emsy
} else if (scenario == "OAconstant") {
E <- MegaData$Efin
} else if (scenario == "BAU1") {
E <- MegaData$Efin_BAU1
} else if (scenario == "Efin_msy") {
E <- MegaData$Efin_msy
} else if (scenario == "EBvK01fin") {
E <- MegaData$EBvK01fin
}
min(E)
# why is there negative escapement?????
ER <- 1 - E
ER <- 1 * (ER > 1) + ER * (ER <= 1)
hist(ER[MegaData$Manage == 0] / MegaData$r[MegaData$Manage == 0])
max(ER)
min(ER)
MPAselect <- MPAselect0
R <- pmax(1e-6,pmin(0.999,rowSums(KprotectedPerCell_Library[, which(MPAselect == 1), drop = FALSE])))
ER_redistribute <- pmin(0.999,1 - (1 - ER) ^ (1 / (1 - R)))
hbau <-
na.omit(ER_redistribute * ((m * K * (1 - R)) / ((ER_redistribute * R) +
m)) * (1 - ((
ER_redistribute * (1 - R) * m
) / (((ER_redistribute * R) + m
) * r))))
hbau <- hbau * (hbau > 0)
HBAU <- sum(hbau)
HBAU
nmax <- floor(length(celltoiterate) / PICKSIZE)
nmax #this is the number of iterations needed for PICKSIZE at a time!
Eevolve <- matrix(nrow = nmax, ncol = dim(MegaData)[1])
# k_per_cell <- t(as.datKprotectedPerCell_Library)
dhmpa_stockish <-
matrix(NA,
nrow = nmax,
ncol = nrow(KprotectedPerCell_Library))
missing <-
nrow(MegaData[MegaData$Manage == 1, ]) / nrow(og_mega_data[og_mega_data$Manage == 1, ])
missing_stocks <-
og_mega_data$stockid[!og_mega_data$stockid %in% MegaData$stockid]
n_missing = nrow(og_mega_data) - nrow(MegaData)
p_msy_missing = sum(MegaData$MSYfin) / sum(og_mega_data$MSYfin)
bau <-
sim_mpa(
r = r,
k = K,
m = m,
u = ER_redistribute,
p_mpa = R,
local_dd = local_dd,
years = mpa_sim_years,
phi = phi,
pt = pt,
plim = plim
)
if (any(is.na(bau))){
stop("something has gone wrong with BAU")
}
bad <- which(is.na(bau))
sum(bau) / HBAU
HBAU <- sum(bau)
upsides_megadata <- MegaData
write_rds(upsides_megadata, file.path(results_path, "upsides_megadata.rds"))
if (nrow(MegaData) != nrow(KprotectedPerCell_Library)){
stop("megadata and k library not same size")
}
print(paste0(n_distinct(MegaData$stockid)," distinct stocks"))
if (run_regional_sala_etal) {
sirframe <- data.frame(cell = celltoiterate,
weight = 0)
registerDoParallel(local_cores)
for (i in 1:nmax) {
MPAselectPrev <-