-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy path011_FiguresSummary.R
2268 lines (2038 loc) · 111 KB
/
011_FiguresSummary.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
# This is the central figure script to create final output figures
# for all global and sub analyses
# Selection of parameters at the start specifies which files are to be loaded
## Paths
results_path <- 'results' # Results path
figure_path <- 'figures' # Figure output path
output_path <- 'data' # Data path
temp_path <- tempdir()
if(!dir.exists(figure_path)) dir.create(figure_path)
target_resolution <- "10km";target_resolution_number <- as.numeric(gsub("\\D","",target_resolution))
projection <- "mollweide"
rij_path <- paste0(output_path,"/table_puspecies",'_',target_resolution,'.fst') # The final output table
feature_path <- paste0(output_path,"/speciesID_table_",target_resolution,".fst") # The table for feature preparation
biome_path <- paste0(output_path,"/pu_biome_",target_resolution,".fst")
path_data <- '/media/martin/data/'
ecoregion_path <- paste0(path_data,"raw/Ecoregions2017/Ecoregions2017.shp")
gadm_path <- paste0(path_data,"raw/gadm36_shp")
carbon_path <- paste0("features_esh/carbon_agbc")
water_path <- paste0("features_esh/water")
repr_id <- TRUE # Where representative sets used?
repr_run_path <- paste0('REPrun_') # The path for the representative sets
# Output data formats
target_range <- c("","_esh")[2] # Range or ESH?
curr = "15perc";curr_number <- 15 # What is the current data if existing
pa_fname <- c("",'withPA')[2] # Solution with PA's excluded ?
pa_carbon <- c("",'_carbon_')[1] # Carbon be included as linear feature ?
pa_water <- c("","_water_")[1] # Water included
split_id <- c("","_biome.id_")[2] # Was a biome stratification used?
pa_carbmult <- c("","_carbweight2_")[1] # Differing carbon weights
pa_watermult <- c("","_waterweight2_")[1] # Different water weight
pa_plants <- c("_waPlants","")[2] # Plants included?
pa_phylo <- c('','_phylo-rank_weight-comparison_','_phylo-ed-comparison_',
'_phylo-edge-comparison_','_phylo-noweight-comparison_')[1] # Phylogenetic weights included
# ------------------------ #
# Code start #
library(ggplot2)
library(colorspace);library(scico);library(wesanderson)
library(extrafont)
library(ggrepel)
library(ggridges)
library(scales)
library(colorspace)
library(raster)
library(gdalUtils)
library(sf)
library(ggthemes)
library(tidyverse)
library(fst)
library(pbapply)
library(RStoolbox)
library(tmap);library(tmaptools)
library(assertthat)
source('src/000_ConvenienceFunctions.R')
stopifnot(
assert_that(
file.exists(ecoregion_path),
dir.exists(output_path),
dir.exists(results_path),
file.exists(feature_path),
exists("makeStack")
)
)
# Land area
land <- raster(paste0("data/globalgrid_",projection,"_",target_resolution,".tif"))
land <- setMinMax(land)
land.mask <- land
land.mask[land.mask>0] <- 1;land.mask[land.mask!=1] <- NA
# ------------------------ #
#### [Figure] Global ranked asset mapping ####
# Organized part to rank all computed assets globally
# Get budgets
if(repr_id){
dd <- list.dirs(paste0(results_path,"/",target_resolution,target_range,"/"))
dd <- dd[grep(repr_run_path,dd)]
# Get list of representative files
ll <- list.files(path = dd,
pattern = paste0(
'minshort_speciestargets',
split_id,
ifelse(pa_fname=="","",pa_fname),
pa_carbon,
pa_water,
pa_carbmult,
pa_watermult,
pa_plants,
pa_phylo,
target_range,
target_resolution
),
full.names = TRUE
)
number_representativesets <- length(dd)
# Get list of files with shortfall
ll.short <- list.files(path = dd,
pattern = paste0(
'minshort_speciestargets',
split_id,
ifelse(pa_fname=="","",pa_fname),
pa_carbon,
pa_water,
pa_carbmult,
pa_watermult,
pa_plants,
pa_phylo,
target_range,
target_resolution
),
full.names = TRUE
)
ll.short <- ll.short[has_extension(ll.short,'fst')]
} else {
ll <- list.files(path = paste0(results_path,"/",target_resolution,target_range,"/"),
pattern = paste0(
'minshort_speciestargets',
split_id,
ifelse(pa_fname=="","",pa_fname),
pa_carbon,
pa_water,
pa_carbmult,
pa_watermult,
pa_plants,
pa_phylo,
target_range,
target_resolution
),
full.names = TRUE
)
}
stopifnot(assert_that(length(ll)>0))
# Get tif files
ll.tif <- ll[has_extension(ll,"tif")]
(ll.tif)
# Output filename
out_dir <- paste0(results_path,"/",target_resolution,target_range,"_ranked")
if(!dir.exists(out_dir)) dir.create(out_dir)
(fname <- paste0(out_dir,"/minshort_speciestargets",
split_id,pa_fname,pa_carbon,pa_water,pa_carbmult,pa_watermult,pa_plants,pa_phylo,target_range,target_resolution,
ifelse(repr_id,paste0('_repruns',number_representativesets),""),
"_ranked.tif"))
(fname.cv <- paste0(out_dir,"/minshort_speciestargets",
split_id,pa_fname,pa_carbon,pa_water,pa_carbmult,pa_watermult,pa_plants,pa_phylo,target_range,target_resolution,
ifelse(repr_id,paste0('_repruns',number_representativesets),""),
"_cv.tif"))
# Biodiversity value(s)
gc(); raster::removeTmpFiles(.2)
# Load individual solutions (raster) from the representative sets
ras2 <- makeStack(ll.tif)
# Reclassifies all PUs in the stack to have 0 instead of NA so that
# averaging the selected proportion takes account of non-selected cells
ras2 <- reclassify(ras2, cbind(NA, NA, 0), right = FALSE)
# Average stack with all proportions
mcp_ilp_hier <- mean(ras2, na.rm = T) # Mean!
# Mask with global land area mask
mcp_ilp_hier <- raster::mask(mcp_ilp_hier, land.mask)
# Multiply with 100 (precision of input layers) for the ranking
mcp_ilp_hier_norm <- mcp_ilp_hier * 100
# Remove 0 fractional estimates so that equal-width bins are constructed correctly
mcp_ilp_hier_norm[mcp_ilp_hier_norm==0] <- NA
# Convert to ranks and then bin (equal-width) averages across PUs. Ocassional ties are resolved randomly
# The resulting ranked map is then inverted so that priority ranks go from 1 to 100
mcp_ilp_hier_norm <- abs( raster_to_ranks(mcp_ilp_hier_norm,
globalgrid = globalgrid,
method = 'area',n = 101,plot = T) # - 100
)
# land30 <- mcp_ilp_hier_norm
# land30[land30 > 30] <- NA; land30[land30 > 0] <- 1; (cellStats(land30 * globalgrid,'sum') - (cellStats(globalgrid, 'sum') * .3) )/(cellStats(globalgrid, 'sum') * .3)
# Add least important areas as 100 so that proportions match again. This is necessary for prioritization variants where not all PUs have value in reaching the targets
mcp_ilp_hier_norm[is.na(mcp_ilp_hier_norm)] <- 100
# Mask again with global land area mask
mcp_ilp_hier_norm <- raster::mask(mcp_ilp_hier_norm, land.mask)
assertthat::assert_that(cellStats(mcp_ilp_hier_norm,min)==1, cellStats(mcp_ilp_hier_norm,max)==100)
NAvalue(mcp_ilp_hier_norm) <- -9999
proj4string(mcp_ilp_hier_norm) <- proj4string(globalgrid)
# Test plot
plot(mcp_ilp_hier_norm,col = scico::scico(10,palette = 'roma'))
# Save outputs #
writeGeoTiff(mcp_ilp_hier_norm, fname = fname) # Save outputs and clear
# --- #
# For variation across representative sets, use the coefficient of variation
co.var <- function(x, na.rm = TRUE) ( sd(x,na.rm = TRUE) / mean(x,na.rm = TRUE) )
ras3 <- abs((ras2*100)-100)
mcp_covar <- calc(ras3 ,co.var)
# Mask with global land area mask
mcp_covar[is.na(mcp_covar)] <- 0
mcp_covar <- raster::mask(mcp_covar,land)
NAvalue(mcp_covar) <- -9999
plot(mcp_covar, col = scico(10,palette = 'tokyo',direction = -1))
# Save outputs #
writeGeoTiff(mcp_covar, fname = fname.cv, dt='FLT4S') # Save outputs and clear
# ----------------------------------------------------------- #
#### [Figure] Nice plotting of full maps for Figure 1 and SI-Figure 1 ####
# ----------------------------------------------------------- #
ras_mean <- raster(fname)
ras_cv <- raster(fname.cv)
(out_fname <- paste0(figure_path, "/",tools::file_path_sans_ext(basename(fname)), ".png" ))
# Nice plotting of the selected priority map
g <- ggR(ras_mean, layer = 1, maxpixels = 1e10,
geom_raster = TRUE, coord_equal = TRUE,stretch = "none", ggObj = TRUE) +
ggthemes::theme_map(base_size = 11,base_family = 'Arial') +
scale_fill_gradientn(breaks = c(100,75,50,25,1),colours = scico(10,palette = 'roma'),na.value = 'transparent',
guide = guide_colourbar(title = "Priority rank",title.theme = element_text(size = 14),
title.position = 'bottom',title.hjust = 0.5,label.position = 'bottom',barwidth = unit(1.5,'in'),
direction = 'horizontal',ticks = F,reverse = T) ) +
theme(legend.position = c(.05,.15),legend.background = element_rect(fill = 'transparent')) +
labs(x = "", y = "")
ggsave(filename = out_fname, plot = g,width = 8, height = 8, dpi = 400)
# Plot for the uncertainty only
(out_fname_cv <- paste0(figure_path, "/",tools::file_path_sans_ext(basename(fname.cv)), ".png" ))
g <- ggR(ras_cv, layer = 1, maxpixels = 1e10,
geom_raster = TRUE, coord_equal = TRUE,stretch = "none", ggObj = TRUE) +
theme_map(base_size = 11,base_family = 'Arial') +
scale_fill_viridis_c(option = 'D',direction = -1, na.value = 'transparent',breaks = c(0,2.5,5,7.5,10),
guide = guide_colourbar(title = "Rank uncertainty (%)",title.theme = element_text(size = 14),
title.position = 'bottom',title.hjust = 0.5,label.position = 'bottom',barwidth = unit(1.5,'in'),
direction = 'horizontal',ticks = F,reverse = T) ) +
theme(legend.position = c(.05,.3),legend.background = element_rect(fill = 'transparent')) +
labs(x = "", y = "" )
ggsave(filename = out_fname_cv, plot = g,width = 8, height = 8, dpi = 400)
# inverted and as SVG
# Insert radial legend in here
library(ggradar)
stopifnot( assert_that(length(ll.short)>0))
perc10 <- bind_rows(
pblapply(ll.short[grep('10perc',ll.short)], function(x) {calc_shortfall(read_fst(x)) %>%
dplyr::mutate(run = basename(dirname(x)),budget = "10") } ),
pblapply(ll.short[grep('30perc',ll.short)], function(x) {calc_shortfall(read_fst(x)) %>%
dplyr::mutate(run = basename(dirname(x)),budget = "30") } )
)
perc10 <- perc10[-which(is.na(perc10$shortfall)),]
df <- bind_rows(
perc10 %>% dplyr::filter(feature %notin% c('AGB_carbon','Water')) %>%
dplyr::group_by(feature,budget) %>%
dplyr::summarise(prop = mean(shortfall, na.rm = TRUE) ) %>% ungroup() %>%
dplyr::group_by(budget) %>%
dplyr::summarise(prop = sum(prop==0, na.rm = TRUE) / n() ) %>%
dplyr::mutate(biocarbongroup = 'Biodiversity'),
perc10 %>% dplyr::filter(feature %in% c('AGB_carbon','Water')) %>%
dplyr::group_by(budget,feature) %>%
dplyr::summarise(prop = mean(shortfall) ) %>%
dplyr::mutate(feature = factor(feature, levels = c('AGB_carbon','Water'), labels = c('Carbon','Water') )) %>%
dplyr::rename(biocarbongroup = feature)
) %>%
tidyr::spread(biocarbongroup, prop) %>% dplyr::mutate(group = 1) %>% dplyr::select(group,budget,Biodiversity:Water) %>%
mutate(budget = as.numeric(budget))
df %>% dplyr::select(budget,Biodiversity,Carbon,Water) %>%
dplyr::mutate_at(c('Biodiversity','Carbon','Water'), function(x) { abs( (x * 100) - 100 ) } ) %>%
dplyr::mutate(Biodiversity = abs(Biodiversity - 100))
# Colours
cols = c( scico(10,palette = 'roma')[c(1,3)] )
gr <- df %>% dplyr::select(budget,Biodiversity,Carbon,Water) %>%
dplyr::mutate_at(c('Biodiversity','Carbon','Water'), function(x) { abs( (x * 100) - 100 ) } ) %>%
dplyr::mutate(Biodiversity = abs(Biodiversity - 100)) %>%
ggradar(.,
grid.min = 0,grid.mid = 50, grid.max = 100,
axis.label.size = 6, grid.label.size = 7, gridline.label.offset = 0,legend.text.size = 10,
base.size = 20, group.point.size = 4,group.line.width = 1.05
# axis.labels = c('Biodiversity','Carbon','Water'), plot.title = ''
) +
theme_void(base_size = 8) +
theme(legend.title = element_text(size = 12, angle = 90),legend.text = element_text(size = 12),
legend.position = 'left') + guides(colour = guide_legend(title = "Total land area (%)",nrow = 1)) +
scale_colour_manual(values = cols) #+ guides(colour = 'none')
gr
(out_fname <- paste0(figure_path, "/",tools::file_path_sans_ext(basename(fname)), "_spiderplot.png" ))
(out_fname <- paste0(figure_path, "/",tools::file_path_sans_ext(basename(fname)), "_spiderplot.svg" ))
ggsave(filename = out_fname,plot = gr, width = 5, height = 5, dpi = 400,bg = 'transparent')
# -------------------------------- #
#### [Figure] Effect of adding plant species - Shift of global ranks ####
# First create the global map
number_representativesets = 10
out_dir <- paste0(results_path,"/",target_resolution,target_range,"_ranked")
ras_withplants <- raster( 'results/10km_esh_ranked/minshort_speciestargets_biome.id__esh10km_repruns10_ranked.tif')
ras_explants <- raster( 'results/10km_esh_ranked/minshort_speciestargets_biome.id__waPlants_esh10km_ranked.tif' )
# Figure output
(
out_fname <- paste0(figure_path, "/minshort_speciestargets_waPlants",target_range,target_resolution,
ifelse(repr_id,paste0('_repruns',number_representativesets),""),
"_ranked_difference.png")
)
# Positive values mean higher priorities
# Negative: Removing plants increased priorities
# Positive: Removing plants decreased priorities
ras_viz <- (ras_explants - ras_withplants)
writeGeoTiff(ras_viz, fname = paste0(out_dir,paste0("/waplants_",
ifelse(repr_id,paste0('_repruns',number_representativesets),""),
"_rank_difference.tif")),'INT2S') # Save outputs and clear
cols <- scico(n = 7,palette = 'vikO',direction = -1) # cork or broc or lisbon or tofino
cols[4] <- "#F2F2F2"
# The plot
g <- ggR(ras_viz, layer = 1, maxpixels = 1e10,
geom_raster = TRUE, coord_equal = TRUE,stretch = "none", ggObj = TRUE) +
ggthemes::theme_map(base_size = 11,base_family = 'Arial') +
scale_fill_gradientn(colours = cols,na.value = 'transparent',
guide = guide_colourbar(title = "Change in\npriority rank",title.theme = element_text(size = 14),
title.position = 'bottom',title.hjust = 0,label.position = 'bottom',barwidth = unit(1.5,'in'),
direction = 'horizontal',ticks = F,reverse = F) ) +
theme(legend.position = c(.1,.1),legend.background = element_rect(fill = 'transparent')) +
labs(x = "", y = "" )
ggsave(filename = out_fname, plot = g,width = 10, height = 14, dpi = 400)
# Also make a histogram of t he differences
vals <- data.frame(values = ras_viz[]) %>% drop_na()
gg <- ggplot(vals,aes(x = values)) +
theme_classic(base_size = 20,base_family = 'Arial') +
geom_histogram(bins = 50,fill = NA,colour = 'black') +
scale_y_continuous(expand = c(0,0),limits = c(0,220000),position = 'left') +
labs(x = "Change in priority rank", y = 'Frequency (10km² grid cells)')
gg
ggsave(filename = "figures/minshort_speciestargets_waPlants_esh10km_repruns10_ranked_difference_histogram.png",
plot = gg,width = 6, height = 5, dpi = 400,bg = 'transparent')
# --- #
# Next calculate species representation curves with and without plants
target_resolution <- '10km'
pa_fname = ''
split_id = '_biome.id_'
dd <- list.dirs(paste0(results_path,"/",target_resolution,target_range,"/"))
if(repr_id) { dd <- dd[grep(repr_run_path,dd)] } else { dd <- dd[1]}
list_withplants <- list.files(path = dd,
pattern = paste0(
'minshort_speciestargets',
split_id,
"",
"", #pa_carbon,
"", #pa_water,
pa_carbmult,
pa_watermult,
"",
pa_phylo,
target_range,
target_resolution
),
full.names = TRUE
)
list_withplants <- list_withplants[has_extension(list_withplants,"fst")]
list_withoutplants <- list.files(path = list.dirs(paste0(results_path,"/",target_resolution,target_range,"/"))[1],
pattern = paste0(
'minshort_speciestargets',
split_id,
"",
"", #pa_carbon,
"", #pa_water,
pa_carbmult,
pa_watermult,
"_waPlants", #pa_plants,
pa_phylo,
target_range,
target_resolution
),
full.names = TRUE
)
list_withoutplants <- list_withoutplants[has_extension(list_withoutplants,"fst")]
stopifnot(assert_that(length(list_withplants) > 0, length(list_withoutplants) > 0 ))
# All representation budgets
rr <- bind_rows(
do.call(rbind, pblapply(list_withplants, function(x,nr = 6) { #4
read.fst(x) %>% calc_shortfall %>%
dplyr::mutate(run = basename(dirname(x)), budget = str_split(tools::file_path_sans_ext( basename(x) ),"_",simplify = TRUE)[,nr] )
}) ) %>% dplyr::mutate(type = "Vertebrates and plants"),
do.call(rbind, pblapply(list_withoutplants, function(x,nr = 7) { #5
read.fst(x) %>% calc_shortfall %>%
dplyr::mutate(run = basename(dirname(x)), budget = str_split(tools::file_path_sans_ext( basename(x) ),"_",simplify = TRUE)[,nr] )
})
) %>% dplyr::mutate(type = "Vertebrates only")
)
rr$budget <- gsub('\\D','',rr$budget)
rr$budget <- factor(rr$budget, levels = c(if(pa_fname!="") {15}, seq(ifelse(pa_fname=="",10,20),100,10)) )
rr <- rr[-which(is.na(rr$shortfall)),]
# Assure that only vertebrate species are included and identical in both
vertebrate_species <- rr %>% filter(type == "Vertebrates only") %>% select(feature) %>% distinct()
rr <- rr %>% filter(feature %in% vertebrate_species$feature)
# Summarize
rr_full <- rr %>% dplyr::group_by(type, run,budget) %>%
dplyr::summarise(target_reached = sum(target_reached,na.rm = TRUE) / n() ) %>% ungroup() %>%
dplyr::mutate(budget = as.numeric( as.character( budget ) )) %>%
# Average + sd per run
dplyr::group_by(type,budget) %>%
dplyr::summarise(target_reached_avg = mean(target_reached*100,na.rm=TRUE),
target_reached_ymin = mean(target_reached*100,na.rm=TRUE) - sd(target_reached*100,na.rm=TRUE),
target_reached_ymax = mean(target_reached*100,na.rm=TRUE) + sd(target_reached*100,na.rm=TRUE))
# Plot for plants only
gp <- rr_full %>%
# ----- #
#dplyr::filter(budget <= 60) %>%
ggplot(., aes(x = budget, y = target_reached_avg, group = type, linetype = type)) +
theme_few(base_size = 20) +
#geom_hline(yintercept = 100,linetype = "dotted", size = .5) +
geom_line(size = 2,alpha = .65) +
#geom_ribbon(aes(ymin = target_reached_ymin, ymax = target_reached_ymax), fill = 'grey80', alpha = .1) +
scale_linetype_manual(values = c('solid','twodash'),guide = guide_legend("")) +
theme(legend.position = c(.65,.15),legend.key.width = unit(.5,'in'),legend.key = element_rect(fill = 'transparent') ) +
scale_colour_manual(values = 'black') + guides(colour = 'none', fill = 'none') +
scale_x_continuous(breaks = pretty_breaks(5),limits = c(as.numeric(levels(rr$budget)[1]),100)) +
scale_y_continuous(breaks = pretty_breaks(5),limits = c(0,100)) +
ylab("Targets reached (% of all assets)") + xlab("Area managed for conservation\n(% of land area)") +
theme(plot.background = element_blank())
gp
ggsave(filename = paste0(figure_path, "/minshort_speciestargets_waPlants",target_range,target_resolution,"_repruns10_representation_difference.png"),
plot = gp, width = 6, height = 6,dpi = 400)
# Stats
rr_full %>% dplyr::filter(budget == '10')
rr_full %>% select(type, budget,target_reached_avg) %>%
tidyr::pivot_wider(id_cols = 'budget',names_from = 'type', values_from = 'target_reached_avg') %>%
mutate(diff = (`Vertebrates and plants` - `Vertebrates only`))
# Which biomes overall ?
biomes <- raster(paste0( '/media/martin/data/constraints/biomes_',target_resolution,'_',projection,'_modal.tif') )
biomes <- alignRasters(biomes, ras_viz, method = 'ngb', func = raster::modal, cl = TRUE)
stopifnot( assert_that( compareRaster(ras_viz,biomes) ) )
# The biomes colour code for plotting
biomes_code <- sf::read_sf('/media/martin/data/raw/Ecoregions2017/Ecoregions2017.shp') %>%
dplyr::select(BIOME_NUM,BIOME_NAME,COLOR_BIO) %>% sf::st_drop_geometry() %>% distinct() %>%
dplyr::slice(-15) %>%
dplyr::arrange(BIOME_NUM)
biomes_code$BIOME_NAME <- factor(biomes_code$BIOME_NAME,levels = biomes_code$BIOME_NAME) # Convert to factor using current order
# Recode the biome names
# Calculate the mean difference at each
df <- data.frame(biome = getValues(biomes),
diff = getValues(ras_viz)
) %>% drop_na() %>%
# Summarise
dplyr::group_by(biome) %>%
dplyr::summarise(diff_mean = mean(diff),
diff_ymin = mean(diff) - sd(diff),
diff_ymax = mean(diff) + sd(diff)
)
# Left_join with calculation
df <- left_join(df, biomes_code, by = c('biome' = 'BIOME_NUM'))
# Make the plot
gb <- ggplot(df, aes(x = fct_reorder(BIOME_NAME,diff_mean), y = diff_mean)) +
theme_few(base_size = 20) +
coord_flip() +
geom_point(size = 2, colour = 'black') +
geom_pointrange(aes(ymin = diff_ymin, ymax = diff_ymax), size = 1.5, stroke = 1.5) +
geom_hline(yintercept = 0, linetype = 'dotted') +
#scale_colour_manual(values = df$COLOR_BIO,guide = guide_legend(title = "",ncol = 3)) +
scale_y_continuous(breaks = pretty_breaks(5),expand = c(0,0)) +
scale_x_discrete(position = "top") +
theme(axis.text.y = element_text(size = 18)) +
#theme(axis.text.y = element_blank(), axis.ticks.y = element_blank()) +
theme(legend.position = 'bottom',legend.text = element_text(size = 10)) +
labs(x = "", y = "Change in priority rank") +
guides(colour = 'none')
gb
ggsave(filename = paste0(figure_path, "/minshort_speciestargets_waPlants",target_range,target_resolution,"_repruns10_biome_difference.png"),
plot = gb, width = 12, height = 6,dpi = 400)
# --------------------- #
#### [Figure] Representation analysis per budget and groups of species ####
# Make plots for the representation
# Load all the files of the given solution
myLog("Loading results now with increasing budget")
# Load
target_resolution <- '10km'
pa_fname <- c("","withPA")[1] # Locked in
pa_carbon <- c("",'_carbon_')[1] # Carbon be included as linear feature ?
pa_water <- c("","_water_")[1] # Water included
split_id <- c("","_biome.id_")[1]
dd <- list.dirs(paste0(results_path,"/",target_resolution,target_range,"/"))
if(repr_id) { dd <- dd[grep(repr_run_path,dd)] } else { dd <- dd[1]}
# Get list of files with shortfall
ll <- list.files(path = dd,
pattern = paste0(
'minshort_speciestargets',
split_id,
ifelse(pa_fname=="","",pa_fname),
pa_carbon,
pa_water,
pa_carbmult,
pa_watermult,
pa_plants,
pa_phylo,
target_range,
target_resolution
),
full.names = TRUE
)
ll <- ll[has_extension(ll,'fst')]
stopifnot(length(ll)>0);length(ll)
# All representation budgets
rr <- do.call(rbind, pblapply(ll, function(x) {
nr = str_split(tools::file_path_sans_ext( basename(x) ),"_",simplify = TRUE)
nr = which(apply(nr, 2, function(y) str_detect(y,'perc')))
read.fst(x) %>% calc_shortfall %>%
dplyr::mutate(run = basename(dirname(x)), budget = str_split(tools::file_path_sans_ext( basename(x) ),"_",simplify = TRUE)[,nr] )
})
)
stopifnot( assert_that('100perc' %in% rr$budget) )
# Join in species ids
if(split_id != "_biome.id_"){
rr <- rr %>% left_join(.,
read_fst(feature_path) %>% mutate(feature = paste0(iucn_id_no,'__',binomial) ) %>%
dplyr::select(feature,category, data, kingdom, class) %>%
dplyr::bind_rows( tibble() ), # Add Carbon!
by ='feature' )
stopifnot( assert_that(anyNA(rr$feature)==FALSE) )
} else {
# In case we use the biome split
ff <- read_fst(feature_path) %>% mutate(feature = str_to_lower( binomial ) ) %>%
dplyr::select(iucn_id_no,feature,category, data, kingdom, class) %>%
dplyr::bind_rows( tibble() )
# Get ids from sets and only those species that in the id list
lf <- list.files('sets','splist',full.names = T)
repr_id_file <- lapply(lf, function(x) { read_csv(x) %>% dplyr::select(2) } ) %>%
bind_rows() %>% distinct()
ff <- ff %>% filter(iucn_id_no %in% repr_id_file$x) %>% dplyr::select(-iucn_id_no)
rm(lf, repr_id_file)
# --- #
rr <- rr %>% mutate(feature = str_to_lower( str_split(rr$feature,"__",simplify = T)[,1]) ) %>%
left_join(.,ff, # Add Carbon!
by ='feature' )
stopifnot( assert_that(anyNA(rr$feature)==FALSE) )
}
# Reformat
rr$budget <- gsub('\\D','',rr$budget)
if(pa_fname!=""){ rr$budget[rr$budget %in% c(14,15)] <- "15"}
rr$budget <- factor(rr$budget, levels = c(if(pa_fname!="") {15}, seq(ifelse(pa_fname=="",10,20),100,10)) )
# Set data for carbon and water
rr[which(rr$feature=="agb_carbon"),c('data')] <- 'Carbon'
rr[which(rr$feature=="water"),c('data')] <- 'Water'
# Make a class for taxonomic grouping
stopifnot( assert_that(!all(is.na(rr$budget)),anyNA(rr$data)==FALSE ) )
# --------------------------------------------------------- #
# Link with taxonomic information
rr <- rr %>% # Assign taxonomic grouping
mutate(TGrouping = factor(data,
levels = c( "IUCN Mammal", "IUCN Reptiles", "IUCN Amphibians", "IUCN Bird", "GARD Shai",
"IUCN Plants", "Kew IUCN Plants", "Kew BGCI Plants", "BIEN Plantae Points", "New Plants - PPM",
"New Plants - Rangebag","BIEN Plantae PPM", "New Plants - Points",
"Carbon", "Water"
),
labels = c('Mammals', 'Reptiles', 'Amphibians', 'Birds','Reptiles',
'Plants','Plants','Plants','Plants','Plants','Plants','Plants','Plants',
'Carbon','Water') )
) %>% mutate(category = ifelse(is.na(category),"DD",category )) %>%
mutate(category = fct_collapse(category, DD = c("LR/cd","LR/lc","LR/nt","DD"))) %>%
mutate(
category = factor(category,levels = c("EX","EW","CR","EN","VU","NT","LC","DD"))
) %>% mutate(category = droplevels(category)) %>% # Ensure that extinct species are truly removed!
# Another group for threatened / non-threatened species
mutate(category.threatened = fct_collapse(category, threatened = c("CR","EN","VU"),
`non-threatened` = c("NT","LC","DD"))
)
# Remove carbon and water here
rr <- rr %>% dplyr::filter(TGrouping %notin% c('Carbon','Water'))
if(pa_carbon == "_carbon_" && pa_water == "_water_"){
myLog('Bio,Water and Carbon')
write_fst(rr,paste0("temporary_results/temporary_biocarbonwater",pa_fname,"_",target_resolution,split_id,"_reprsave.fst"))
} else
if(pa_carbon == "_carbon_" && pa_water == "") {
myLog('BioCarbon only')
write_fst(rr,paste0("temporary_results/temporary_biocarbon",pa_fname,"_",target_resolution,split_id,"_reprsave.fst"))
} else
if(pa_water == "_water_" && pa_carbon == ""){
myLog('BioWater only')
write_fst(rr,paste0("temporary_results/temporary_biowater",pa_fname,"_",target_resolution,split_id,"_reprsave.fst"))
} else
{ myLog('Bio only')
write_fst(rr,paste0("temporary_results/temporary_bioonly",pa_fname,"_",target_resolution,split_id,"_reprsave.fst"))
}
# ------------------------------ #
rr <- read_fst(paste0("temporary_results/temporary_bioonly",pa_fname,"_",target_resolution,split_id,"_reprsave.fst"))
rr2 <- read_fst(paste0("temporary_results/temporary_biocarbon",pa_fname,"_",target_resolution,split_id,"_reprsave.fst")) # Get the separate results
rr3 <- read_fst(paste0("temporary_results/temporary_biocarbonwater",pa_fname,"_",target_resolution,split_id,"_reprsave.fst"))
rr4 <- read_fst(paste0("temporary_results/temporary_biowater",pa_fname,"_",target_resolution,split_id,"_reprsave.fst"))
# Build overall dataset
rr_full <- bind_rows(
rr %>% dplyr::group_by(run,feature,budget) %>%
dplyr::summarise(target_reached = sum(target_reached,na.rm = TRUE) / n() ) %>% ungroup() %>%
dplyr::mutate(budget = as.numeric( as.character( budget ) )) %>%
# Average + sd per run
dplyr::group_by(feature,budget) %>%
dplyr::summarise(target_reached = mean(target_reached,na.rm = TRUE)) %>% ungroup() %>%
dplyr::group_by(budget) %>%
dplyr::summarise(target_reached_avg = mean(target_reached*100,na.rm = TRUE)
# target_reached_ymin = mean(target_reached*100,na.rm = TRUE) - sd(target_reached*100,na.rm = TRUE),
# target_reached_ymax = mean(target_reached*100,na.rm = TRUE) + sd(target_reached*100,na.rm = TRUE)
) %>%
dplyr::mutate(type = 'Biodiversity only'),
rr2 %>% dplyr::group_by(run,feature,budget) %>%
dplyr::summarise(target_reached = sum(target_reached,na.rm = TRUE) / n() ) %>% ungroup() %>%
dplyr::mutate(budget = as.numeric( as.character( budget ) )) %>%
# Average + sd per run
dplyr::group_by(feature,budget) %>%
dplyr::summarise(target_reached = mean(target_reached,na.rm = TRUE)) %>% ungroup() %>%
dplyr::group_by(budget) %>%
dplyr::summarise(target_reached_avg = mean(target_reached*100,na.rm = TRUE)
# target_reached_ymin = mean(target_reached*100,na.rm = TRUE) - sd(target_reached*100,na.rm = TRUE),
# target_reached_ymax = mean(target_reached*100,na.rm = TRUE) + sd(target_reached*100,na.rm = TRUE)
) %>%
dplyr::mutate(type = 'Biodiversity and Carbon'),
rr4 %>% dplyr::group_by(run,feature,budget) %>%
dplyr::summarise(target_reached = sum(target_reached,na.rm = TRUE) / n() ) %>% ungroup() %>%
dplyr::mutate(budget = as.numeric( as.character( budget ) )) %>%
# Average + sd per run
dplyr::group_by(feature,budget) %>%
dplyr::summarise(target_reached = mean(target_reached,na.rm = TRUE)) %>% ungroup() %>%
dplyr::group_by(budget) %>%
dplyr::summarise(target_reached_avg = mean(target_reached*100,na.rm = TRUE)
# target_reached_ymin = mean(target_reached*100,na.rm = TRUE) - sd(target_reached*100,na.rm = TRUE),
# target_reached_ymax = mean(target_reached*100,na.rm = TRUE) + sd(target_reached*100,na.rm = TRUE)
) %>%
dplyr::mutate(type = 'Biodiversity and Water'),
rr3 %>% dplyr::group_by(run,feature,budget) %>%
dplyr::summarise(target_reached = sum(target_reached,na.rm = TRUE) / n() ) %>% ungroup() %>%
dplyr::mutate(budget = as.numeric( as.character( budget ) )) %>%
# Average + sd per run
dplyr::group_by(feature,budget) %>%
dplyr::summarise(target_reached = mean(target_reached)) %>% ungroup() %>%
dplyr::group_by(budget) %>%
dplyr::summarise(target_reached_avg = mean(target_reached*100,na.rm = TRUE)
# target_reached_ymin = mean(target_reached*100,na.rm = TRUE) - sd(target_reached*100,na.rm = TRUE),
# target_reached_ymax = mean(target_reached*100,na.rm = TRUE) + sd(target_reached*100,na.rm = TRUE)
) %>%
dplyr::mutate(type = 'Biodiversity, Carbon and Water')
)
rr_full$type <- factor(rr_full$type, levels = c("Biodiversity only", "Biodiversity and Carbon","Biodiversity and Water", "Biodiversity, Carbon and Water"))
rr_full_forexport <- rr_full
# -------------------------- #
# Some summary stats - Shortfall at given budgets or taxonimic groups
# Overall shortfall for all assets
stopifnot(assert_that('Carbon' %in% unique(rr$TGrouping)))
stat <- rr %>% filter(budget %in% c(10,30,50)) %>%
dplyr::group_by(run,feature,budget) %>%
dplyr::summarise(shortfall = mean(shortfall,na.rm = T) ) %>% ungroup() %>%
dplyr::mutate(budget = as.numeric( as.character( budget ) )) %>%
# Average per run
dplyr::group_by(feature,budget) %>%
dplyr::summarise(shortfall = mean(shortfall,na.rm = T)) %>% ungroup() %>%
dplyr::mutate(gr = ifelse(feature %in% c('agb_carbon','water'),feature,'Biodiversity') )
# Shortfall for carbon and water globally
stat %>% filter(gr %in% c('agb_carbon','water')) %>% mutate(shortfall = 1 - shortfall)
stat %>% filter(gr %notin% c('AGB_carbon','Water')) %>%
dplyr::group_by(gr,budget) %>%
dplyr::summarise(avg_shortfall = mean(shortfall,na.rm = TRUE),
target_reached = sum(shortfall==0,na.rm = TRUE) / n() )
# What we get for 10% and 30%
rr_full %>% filter(budget %in% c(10,30,50))
# Amount of land for biodiversity only
rr_full %>% filter(type == 'Biodiversity only')
rr_full %>% filter(type == 'Biodiversity, Carbon and Water')
# Shortfall and targets reached of currently protected sites
rr %>% dplyr::filter(budget == '15') %>%
dplyr::group_by(run,feature,kingdom,budget) %>%
dplyr::summarise(shortfall = mean(shortfall,na.rm = T)) %>% ungroup() %>%
group_by(budget) %>%
summarise(mean_shortfall = 1- mean(shortfall,na.rm = T),
target_reached = sum(shortfall == 0,na.rm = T) / n() )
# Plants that have target reached at given budget
x = #rr %>% dplyr::filter(budget == '15',kingdom == "PLANTAE") %>%
rr3 %>% dplyr::filter(budget == '10',kingdom == "PLANTAE") %>% # From bio+carbon+water
dplyr::group_by(run,feature,kingdom,budget) %>%
dplyr::summarise(shortfall = mean(shortfall,na.rm = T)) %>% ungroup() %>%
dplyr::group_by(feature,kingdom,budget) %>%
dplyr::summarise(shortfall = mean(shortfall,na.rm = T)) %>% ungroup()
x %>% summarise(prop_plants = sum(shortfall==0,na.rm = TRUE) / n())
# Shortfall of carbon and water at 30 and 50%
rr %>% dplyr::filter(budget %in% c('10','30','50'), data %in% c('Carbon','Water')) %>% dplyr::group_by(budget,data) %>% dplyr::summarise(shortfall = 1-mean(shortfall))
# And improvement in conservation status
rr_full %>% dplyr::filter(budget %in% c('30','50')) %>% filter(type == 'Biodiversity, Carbon and Water')
# Summary per overall assets
rr %>% dplyr::mutate(gr = ifelse(feature %in% c('AGB_carbon','Water'),feature,'Biodiversity') ) %>%
dplyr::filter(budget %in% c('30','50')) %>%
dplyr::group_by(run,gr,feature,budget) %>%
dplyr::summarise(shortfall = mean(shortfall,na.rm = T) ) %>% ungroup() %>%
# Average per feature
dplyr::group_by(gr,feature,budget) %>%
dplyr::summarise(shortfall = mean(shortfall,na.rm = T) ) %>% ungroup() %>%
# Average per group
dplyr::group_by(gr, budget) %>% dplyr::summarise(shortfall = mean(shortfall,na.rm=T))
# --- #
if(!repr_id){
# Full comparison with all species
rr_full <- bind_rows(
rr %>% dplyr::group_by(run,feature,budget) %>%
dplyr::summarise(target_reached = sum(target_reached, na.rm = TRUE) / n() ) %>% ungroup() %>%
dplyr::mutate(budget = as.numeric( as.character( budget ) )) %>%
# Average + sd per run
dplyr::group_by(budget) %>%
dplyr::summarise(target_reached_avg = mean(target_reached*100, na.rm = TRUE),
target_reached_ymin = mean(target_reached*100, na.rm = TRUE) - sd(target_reached*100, na.rm = TRUE),
target_reached_ymax = mean(target_reached*100, na.rm = TRUE) + sd(target_reached*100, na.rm = TRUE)) %>%
dplyr::mutate(type = 'Biodiversity only (representative)'),
readRDS("temporary_SIallspecies_reprsave.rds") %>%
dplyr::group_by(run,feature,budget) %>%
dplyr::summarise(target_reached = sum(target_reached, na.rm = TRUE) / n() ) %>% ungroup() %>%
dplyr::mutate(budget = as.numeric( as.character( budget ) )) %>%
# Average + sd per run
dplyr::group_by(budget) %>%
dplyr::summarise(target_reached_avg = mean(target_reached*100, na.rm = TRUE),
target_reached_ymin = mean(target_reached*100, na.rm = TRUE) - sd(target_reached*100, na.rm = TRUE),
target_reached_ymax = mean(target_reached*100, na.rm = TRUE) + sd(target_reached*100, na.rm = TRUE)) %>%
dplyr::mutate(type = 'Biodiversity only (all data)')
)
}
# -------------------------- #
# Plotting below
# -------------------------- #
# The plot for overall
g1 <- rr_full %>%
# ----- #
#dplyr::filter(budget <= 60) %>%
ggplot(., aes(x = budget, y = target_reached_avg, group = type,colour = type)) +
theme_few(base_size = 20) +
# geom_hline(yintercept = 100,linetype = "dotted", size = .5) +
# geom_ribbon(aes(ymin = target_reached_ymin, ymax = target_reached_ymax), fill = 'grey80', alpha = .7) +
geom_line(size = 2) +
# Protected area indication
geom_point(data = rr_full %>% filter(budget == 15), colour = 'red', alpha = .2, size = 3,stroke = 2) +
scale_colour_manual(values = c("#00A087","#B09C85","#72bcd4","grey30"),guide = guide_legend("",override.aes = aes(fill = NA))) + #scale_colour_manual(values = 'black') +
# scale_linetype_manual(values = c('solid','dotted','longdash','twodash'),guide = guide_legend("",override.aes = aes(fill = NA))) +
theme(legend.position = c(.51,.15),legend.key.width = unit(1,'in'),legend.background = element_rect(fill = 'transparent'),
legend.key = element_rect(fill = 'transparent') ) +
guides(fill = 'none') +
scale_x_continuous(breaks = pretty_breaks(5),limits = c(as.numeric(levels(rr$budget)[1]),100)) +
scale_y_continuous(breaks = pretty_breaks(5),limits = c(0,100)) +
ylab("Targets reached (% of all species)") + xlab("Area managed for conservation\n(% of land area)") +
theme(plot.background = element_blank())
g1
if(pa_fname == ""){
ggsave(paste0(figure_path,"/Figure1_budgetrepresentation_overall.png"),plot =g1,dpi = 400)
} else {
ggsave( paste0(figure_path,"/SIFigure1_budgetrepresentation_overall_withPA.png"),plot = g1,dpi = 400)
}
cols.tgrouping <- c(Plants = "#144720",Reptiles = "#871e7e",
Amphibians = "#1c98ba", Birds = "#b89216", Mammals = "#940303",
Carbon = 'grey10', Water = 'blue',
Overall = "#000000")
# Summarise per feature and group
rr_full_tgrouping <- rr %>% dplyr::group_by(TGrouping,feature,run,budget) %>%
dplyr::summarise(target_reached = sum(target_reached, na.rm = TRUE) / n() ) %>% ungroup() %>%
dplyr::mutate(budget = as.numeric( as.character( budget ) )) %>%
# Average + sd per run
dplyr::group_by(TGrouping,feature,budget) %>%
dplyr::summarise(target_reached = mean(target_reached, na.rm = TRUE)) %>% ungroup() %>%
dplyr::group_by(TGrouping, budget) %>%
dplyr::summarise(target_reached_avg = mean(target_reached*100, na.rm = TRUE)
)
# The plot for taxonomic groups
g2 <- rr_full_tgrouping %>%
# ----- #
#dplyr::filter(budget <= 60) %>%
ggplot(., aes(x = budget, y = target_reached_avg, color = TGrouping, fill = TGrouping)) +
theme_few(base_size = 20) +
# geom_hline(yintercept = 100,linetype = "dotted", size = .5) +
# geom_ribbon(aes(ymin = target_reached_ymin, ymax = target_reached_ymax), colour = NA, alpha = .4) +
geom_line(size = 2,linejoin = "round",lineend = "butt") +
# Protected area indication
geom_point(data = rr_full_tgrouping %>% filter(budget == 15), colour = 'red', alpha = .2, size = 3, stroke = 2) +
scale_colour_manual(values = cols.tgrouping,guide = guide_legend("")) + theme(legend.position = c(.72,.15),legend.background = element_rect(fill = 'transparent') ) +
scale_fill_manual(values = cols.tgrouping,guide = guide_legend("")) + guides(fill = 'none') +
#scale_color_brewer(palette = "Set1",guide = guide_legend("")) + theme(legend.position = c(.85,.25)) +
# Ablines
#geom_vline(xintercept = 14,linetype = 'dotted',size=1) + annotate("label",x =17, y = 100, label = "2019") +
#geom_vline(xintercept = 50,linetype = 'dotted',size=1) + annotate("label",x =53, y = 90, label = "Half-Earth") +
scale_x_continuous(breaks = pretty_breaks(5),limits = c(as.numeric(levels(rr$budget)[1]),100)) +
scale_y_continuous(breaks = pretty_breaks(5),limits = c(0,100)) +
ylab("Targets reached (% of all assets)") + xlab("Areas managed for conservation\n(% of land area)") +
theme(plot.background = element_blank())
g2
if(pa_fname == ""){
ggsave(paste0(figure_path,"/Figure1_budgetrepresentation_tgrouping.png"),plot =g2,dpi = 400)
} else {
ggsave(paste0(figure_path,"/SIFigure1_budgetrepresentation_tgrouping_withPA.png"),plot =g2,dpi = 400)
}
cols.category.threatened <- c(threatened = "#85052e",`non-threatened` = "#524f49")
# Overall
rr_full_threatened <- rr %>%
dplyr::filter(kingdom == "ANIMALIA") %>%
dplyr::group_by(category.threatened,run,feature,budget) %>%
dplyr::summarise(target_reached = sum(target_reached, na.rm = TRUE) / n() ) %>% ungroup() %>%
dplyr::mutate(budget = as.numeric( as.character( budget ) )) %>%
# Average + sd per run
dplyr::group_by(category.threatened,feature,budget) %>%
dplyr::summarise(target_reached = mean(target_reached, na.rm = TRUE)) %>% ungroup() %>%
dplyr::group_by(category.threatened, budget) %>%
dplyr::summarise(target_reached_avg = mean(target_reached*100, na.rm = TRUE)
# target_reached_ymin = mean(target_reached*100) - sd(target_reached*100),
# target_reached_ymax = mean(target_reached*100) + sd(target_reached*100)
)
# The plot for Threatened species
g3 <- rr_full_threatened %>%
# ----- #
#dplyr::filter(budget <= 60) %>%
ggplot(., aes(x = budget, y = target_reached_avg, color = category.threatened,
fill = category.threatened)) +
theme_few(base_size = 20) +
# geom_hline(yintercept = 100,linetype = "dotted", size = .5) +
# geom_ribbon(aes(ymin = target_reached_ymin, ymax = target_reached_ymax, fill = category.threatened), colour = NA, alpha = .4) +
geom_line(size = 2,linejoin = "round",lineend = "butt") +
# Protected area indication
geom_point(data = rr_full_threatened %>% filter(budget == 15), colour = 'red', alpha = .2, size = 3, stroke = 2) +
scale_colour_manual(values = cols.category.threatened,guide = guide_legend("")) + theme(legend.position = c(.72,.15),legend.background = element_rect(fill = 'transparent') ) +
scale_fill_manual(values = cols.category.threatened,guide = guide_legend("")) + guides(fill = 'none') +
scale_x_continuous(breaks = pretty_breaks(5),limits = c(as.numeric(levels(rr$budget)[1]),100)) +
scale_y_continuous(breaks = pretty_breaks(5),limits = c(0,100)) +
ylab("Targets reached (% of all species)") + xlab("Areas managed for conservation\n(% of land area)") +
theme(plot.background = element_blank())
g3
if(pa_fname == ""){
ggsave(paste0(figure_path,"/Figure1_budgetrepresentation_threatened.png"),plot = g3,dpi = 400)
} else {
ggsave(paste0(figure_path,"/SIFigure1_budgetrepresentation_threatened_withPA.png"),plot = g3,dpi = 400)
}
# Composite and export #
library(cowplot)
remYaxis <- theme(axis.line.y = element_blank(), axis.text.y = element_blank(),axis.ticks.y = element_blank(),axis.title.y = element_blank())
pg <- plot_grid(g1,g2 + remYaxis,g3 + remYaxis ,nrow = 1,labels = 'auto',align = 'hv',axis = 'l', label_size = 24,label_fontface = 'bold')
if(pa_fname == ""){
cowplot::ggsave2(filename = paste0(figure_path,"/Figure1_budgetrepresentation.png"),width = 18, height = 9,
plot = pg,dpi = 400)
} else {
# Separate for PA lockedin
cowplot::ggsave2(filename = paste0(figure_path,"/SIFigure1_budgetrepresentation_withPA.png"),width = 18, height = 9,
plot = pg,dpi = 400)
}
# ------------------------- #
# Assemble joint plot with protected areas locked in
out <- bind_rows(rr_full_forexport,rr_full_tgrouping,rr_full_threatened)
if(pa_fname == ""){ out1 <- out %>% mutate(Lockin_currentlyprotected = FALSE);rm(out) }
if(pa_fname != ""){ out2 <- out %>% mutate(Lockin_currentlyprotected = TRUE);rm(out) }
if(pa_fname == ""){ g1_woPA <- g1;g2_woPA <- g2; g3_woPA <- g3 }
# ------------------- #
write_csv(bind_rows(out1,out2),paste0("figures/Figure3_Extendenddata",split_id,".csv"))
stopifnot(pa_fname != "")
remYaxis <- theme(axis.line.y = element_blank(), axis.text.y = element_blank(),axis.ticks.y = element_blank(),axis.title.y = element_blank())
if(split_id != ""){
fig3 <- plot_grid(
# Overall
g1_woPA + labs(x = "",title = "Optimal",tag = "a") + guides(colour = 'none',linetype = 'none') + theme(plot.title = element_text(hjust = .5)),
g1 + labs(x = "", title = "Current protection",tag = "b") + remYaxis + guides(linetype = 'none',colour = 'none') + theme(plot.title = element_text(hjust = .5)),
# Taxonomic groups
g2_woPA + labs(x="",tag = "c") + guides(colour = 'none',linetype = 'none') + theme(plot.title = element_text(hjust = .5)),
g2 + labs(x="",tag = "d") + remYaxis + guides(linetype = 'none',colour = 'none'),
# Threatened species
g3_woPA + labs(tag = "e") + guides(colour = 'none',linetype = 'none') + theme(plot.title = element_text(hjust = .5)),
g3 + labs(tag = "f") + remYaxis + guides(linetype = 'none',colour = 'none'),
nrow = 3,align = 'hv',axis = 'l',label_x = .05, label_size = 20,label_fontface = 'bold')
cowplot::ggsave2(filename = paste0(figure_path,"/Figure3.png"),width = 14, height = 15,
plot = fig3,dpi = 400)
cowplot::ggsave2(filename = paste0(figure_path,"/Figure3.svg"),width = 14, height = 15,
plot = fig3,dpi = 400)
} else {
fig3 <- plot_grid(
# Overall
g1_woPA + labs(x = "",title = "Optimal",tag = "b") + guides(colour = 'none',linetype = 'none') + theme(plot.title = element_text(hjust = .5)),
g1 + labs(x = "", title = "Current protection",tag = "c") + remYaxis + guides(linetype = 'none',colour = 'none') + theme(plot.title = element_text(hjust = .5)),
# Taxonomic groups
g2_woPA + labs(x="",tag = "d") + guides(colour = 'none',linetype = 'none') + theme(plot.title = element_text(hjust = .5)),
g2 + labs(x="",tag = "e") + remYaxis + guides(linetype = 'none',colour = 'none'),
# Threatened species
g3_woPA + labs(tag = "f") + guides(colour = 'none',linetype = 'none') + theme(plot.title = element_text(hjust = .5)),
g3 + labs(tag = "g") + remYaxis + guides(linetype = 'none',colour = 'none'),
nrow = 3,align = 'hv',axis = 'l',label_x = .05, label_size = 20,label_fontface = 'bold')
cowplot::ggsave2(filename = paste0(figure_path,"/SIFigure10_nobiomesplit.png"),width = 14, height = 15,
plot = fig3,dpi = 400)
cowplot::ggsave2(filename = paste0(figure_path,"/SIFigure10_nobiomesplit.svg"),width = 14, height = 15,
plot = fig3,dpi = 400)
}
# Save the legends separately and add them manually to the plot
pl <- plot_grid(
ggpubr::as_ggplot(ggpubr::get_legend(g1 + theme(legend.key.width = unit(1,'in'))
)),
ggpubr::as_ggplot(ggpubr::get_legend(g2 + theme(legend.key.width = unit(1,'in'))# +
# guides(colour = guide_legend(title = "",label.position = 'top',direction = 'horizontal',
# label.hjust = 0.5,ncol=1,byrow = TRUE))
)),
ggpubr::as_ggplot(ggpubr::get_legend(g3 + theme(legend.key.width = unit(1,'in'))# +
# guides(colour = guide_legend(title = "",label.position = 'top',direction = 'horizontal',
# label.hjust = 0.5,ncol=1,byrow = TRUE))
))
)
cowplot::ggsave2(filename = paste0(figure_path,"/Figure3_legends.svg"),width = 18, height = 15,
plot = pl,dpi = 400)
# ---------------------------- #
#### [Figure] Differing weights for carbon and water ####
# Idea:
# Run varying weights for carbon and water at 50km for a representative set
# Make a ternary plot with biodiversity, carbon and water and each axis
library(fst)
library(tidyverse)
library(ggplot2)
library(scales)
library(scico)
library(pbapply)
library(assertthat)
# Results path to the varying carbon_water weights
results_path = 'results/50km_esh_carbonwaterweights' #
# List of files
ll_results <- list.files(results_path,full.names = T)
ll_results <- ll_results[has_extension(ll_results,'fst')]
ll_results <- ll_results[str_detect(ll_results,'securitysave',negate = T)] # Remove the securitysaves
# --- #
# Preprocessing function - Calculates shortfall and extracts the weight from filename
format_fname <- function(f){
#print(basename(f))
target_carbonweight = as.numeric( str_remove(str_split(tools::file_path_sans_ext( basename(f) ),"__",simplify = T)[,4],'carbweight') )
target_waterweight = as.numeric( str_remove(str_split(tools::file_path_sans_ext( basename(f) ),"__",simplify = T)[,5],'waterweight') )
target_budget = as.numeric( str_remove(str_split(tools::file_path_sans_ext( basename(f) ),"_",simplify = T)[,14],'perc') )
# Load in File
df <- read_fst(f) %>%
dplyr::filter(feature_abundance_pu > 0) %>% # No features with zero abundance
dplyr::mutate(biocarbongroup = c(rep('Biodiversity',n()-2),'Carbon','Water')) %>% # Carbon and Water come last
# Calculate the shortfall for each target / feature
mutate(
short_pu = pmax(absolute_target - absolute_held, 0)
) %>%
# express the shortfalls as a percentage of the targets
mutate(
shortfall = short_pu / absolute_target
)
if(str_detect(f,'_biome.id_')){
df$feature <- str_split(df$feature,"__",simplify = T)[,1]
# df <- df %>% group_by(biocarbongroup,feature) %>%
# dplyr::summarise(absolute_held = mean(absolute_held),
# absolute_target = mean(absolute_target),
# shortfall = mean(shortfall)
# )
out <- df %>% group_by(biocarbongroup, feature) %>%
dplyr::summarise(shortfall = mean(shortfall,na.rm = TRUE) ) %>% ungroup() %>%
dplyr::group_by(biocarbongroup) %>%
dplyr::summarise(avg_shortfall = mean(shortfall,na.rm = TRUE),
target_reached = sum(shortfall==0,na.rm = TRUE) / n() ) %>%
dplyr::mutate(carbonweight = target_carbonweight,
waterweight = target_waterweight, budget = target_budget)
} else {
# Now average and calculate
out <- df %>% dplyr::group_by(biocarbongroup) %>%
dplyr::summarise(target_reached = length(which( absolute_held >= absolute_target )) / n() ,