-
Notifications
You must be signed in to change notification settings - Fork 0
/
strandingsPontoporia.R
1895 lines (1570 loc) · 77.1 KB
/
strandingsPontoporia.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
# Code for:
## Fransiscana dolphin 'Pontoporia blainvillei' stranding patterns in
## southeast-south Brazil, Fransiscana Management Area (FMA) II,
## between 2015-2020
##
## Code by Jonatas H F do Prado, Jessica L Schattschneider, Nicholas W Daudt
##
### General tidy rules - - - - -
# variable_names <- write with lower case and underlines
# dataframeNames <- cammelCase style (startLowerCaseAndEveryNewWordStartWithCapital)
# package::function notation, unless from 'base' packages
# Sessions delimited by "# Session name ####"
# Every step within the Session, use ## and a quick comment
###- - - - - - - - - - - - - - -
rm(list = ls())
# Libraries ####
library(plyr)
library(reshape2)
library(tidyverse)
library(mapview)
library(sf)
library(ggspatial)
library(janitor)
library(KernSmooth)
library(raster)
library(maptools)
library(rgdal)
# local functions: ##
source("./functionEnvData.R")
################################################################################
############################## Dataset manipulation ############################
################################################################################
##----------------------------------------------------------------------------##
## Stranding dataset ##
##----------------------------------------------------------------------------##
## Open stranding dataset
pontoporia <- as.data.frame(
readxl::read_xlsx("./data/Pontoporia_PMP_2015_08_24_a_2020_06_11 SC_PR_SP_RJ.xlsx",
sheet = 2))
## Filter columns
pontoporia <-
pontoporia %>%
dplyr::select(`Identificador do indivíduo`, Estado, Praia, Trecho,
`Estratégia do trecho`, `Tipo do monitoramento`, `Data/Hora`,
`Ponto - Lat`, `Ponto - Long`, `Condição da carcaça`,
`OFAI - Sexo`)
## Rename columns and levels
names(pontoporia) <- c("id_individual", "state", "beach",
"stretch", "stretch_scheme", "monitoring_type",
"date_hour", "lat", "long", "cod_decomposition", "sex")
pontoporia$stretch_scheme <- as.factor(pontoporia$stretch_scheme)
levels(pontoporia$stretch_scheme) <- list(daily = "Diário",
weekly = "Semanal",
fortnightly = "Diário 15",
call = "Acionamento")
pontoporia$monitoring_type <- as.factor(pontoporia$monitoring_type)
levels(pontoporia$monitoring_type) <- list(regular = "Regular",
call = "Acionamento")
pontoporia$sex <- as.factor(pontoporia$sex)
levels(pontoporia$sex) <- list(female = "Fêmea",
male = "Macho",
unkwown = "Indefinido")
pontoporia$state <- as.factor(pontoporia$state)
## Remove stretch_scheme == "call", monitoring_type == "call" &
## stretch_scheme == "weekly", monitoring_type == "call"
## & stretch_scheme == "fortnightly" and "date_hour" column;
## Create columns date, year, month, day, week, semester, year_n, season and fortnight_month;
## Filter survey effort from date > "September2015" and <= "2020-06-07".
pontoporia <-
pontoporia %>%
dplyr::filter(stretch_scheme!= "call") %>%
dplyr::filter(!((monitoring_type == "call" & stretch_scheme == "weekly") |
(monitoring_type == "call" &
stretch_scheme == "fortnightly"))) %>%
dplyr::mutate(date = lubridate::as_date(date_hour)) %>%
dplyr::select(- date_hour) %>%
dplyr::filter(date > "2015-08-31" & date <= "2020-06-07") %>%
dplyr::mutate(year = lubridate::year(date),
month = lubridate::month(date),
day = lubridate::day(date),
week = lubridate::week(date),
semester = lubridate::semester(date, with_year = TRUE),
season =
ifelse(month >= 1 & month <=3, "summer",
ifelse(month >= 4 & month <= 6, "autumn",
ifelse(month >= 7 & month <= 9, "winter", "spring"))),
year_n =
ifelse(date > "2015-08-31" & date < "2016-09-01", "Year1",
ifelse(date > "2016-08-31" & date < "2017-09-01", "Year2",
ifelse(date > "2017-08-31" & date < "2018-09-01", "Year3",
ifelse(date > "2018-08-31" & date < "2019-09-01", "Year4",
"Year5")))),
fortnight_month = as.numeric(ifelse(day <= 15, "1", "2")))
## Create a continuous id for fortnight periods through the year
fortnight_df <-
pontoporia %>%
dplyr::select(id_individual, month, fortnight_month)
fortnight_df <-
fortnight_df %>%
dplyr::group_by(month, fortnight_month) %>%
dplyr::mutate(fortnight_id = dplyr::cur_group_id()) %>%
dplyr::ungroup() %>%
dplyr::select(id_individual, fortnight_id)
## Join 'fortnight_df' into 'pontoporia'
pontoporia <-
dplyr::left_join(pontoporia, fortnight_df, by = "id_individual")
## Create column back_date and zone for environment variables gathering
pontoporia <-
pontoporia %>%
dplyr::mutate(back_date =
lubridate::as_date(ifelse(cod_decomposition == 2,date - 1,date - 6))) %>%
dplyr::mutate(zone =
ifelse(lat > -23.75, "1",
ifelse(lat < -23.75 & lat > -26.2, "2", "3")))
#- - - - - - -
## Zones were defined based on summaries related to mean drifting
## distances from the 'drift_experiment'.
## See in general results 'table4'.
#- - - - - - -
## Assign mesoregions
# Transform 'pontoporia' into a geospatial feature
pontoporia <-
pontoporia %>%
dplyr::mutate(long1 = long)%>%
dplyr::mutate(lat1 = lat)
pontoporiaSpatial <-
pontoporia %>%
sf::st_as_sf(coords = c("long1","lat1"), crs = 4326)
# Read mesoregions shapefile
mesoregions <- sf::read_sf("./data/shp_mesoregiao/poligonos_meso.shp")
# Filtering and selecting to make it lighter to run
mesoregions <-
mesoregions %>%
dplyr::filter(PROF == "0 - 20") %>%
dplyr::select(MESORREGIA, geometry) %>%
sf::st_transform(crs = 4326)
# mapview::mapview(mesoregions)
# Merge 'pontoporiaSpatial' with 'mesoregions'
pontoporiaSpatial <- sf::st_join(pontoporiaSpatial, mesoregions)
# Check if there is any 'NA' coerced after joining attributes
# plyr::count(is.na(pontoporiaSpatial$MESORREGIA))
# mapview::mapview(pontoporiaSpatial, zcol = "MESORREGIA")
## Manual assignment of "MESORREGIA" (mesoregion) for the 'NA' records
# South of Tubarao city, inside Babitonga Bay, and
# id_individual == "156651" & "167513" (North Sao Paulo),
# were not assigned to any 'mesoregion' because in a next step they
# will be dropped out.
# Close to Barra do Sai
pontoporiaSpatial$MESORREGIA[pontoporiaSpatial$id_individual == "061824"] <- "Litoral Paranaense"
# Border between Central/North SP regions
pontoporiaSpatial$MESORREGIA[pontoporiaSpatial$id_individual == "184419" |
pontoporiaSpatial$id_individual == "159986"] <- "Litoral Norte Paulista"
## Return spatial feature to data.frame format
pontoporia <-
pontoporiaSpatial %>%
as.data.frame() %>%
dplyr::select(- geometry)
## Remove records from state == "Rio de Janeiro", cod_decomposition == "5",
## and date == "NA".
pontoporia <-
pontoporia %>%
dplyr::filter(state != "Rio de Janeiro") %>%
dplyr::filter(cod_decomposition != 5) %>%
dplyr::filter(!is.na(date))
## Remove records distant more than 300 m from the coast line
# Open shapefiles (shp) of beach monitoring lines
# Create a list with all subdirectories containing the shp
ff <- as.list(list.files(path = "./data", pattern = "linha.shp$",
recursive = TRUE, full.names = TRUE))
# Function to open the shp in subdirectories
open_shp <- function(ff){
linha <- sf::read_sf(ff[i])
linha
}
# Loop creating a list with all shp
lines <- list()
for (i in 1:length(ff)) {
lines[[i]] <- open_shp(ff)
}
# Merge all beach monitoring lines into one shp
originalStretches <- do.call(rbind, lines)
# Remove streches with strategy == "noneeffort", compriment == "0",
# and beach_name == "Ponta do Itaguá"; create an id for streches.
originalStretches <-
originalStretches %>%
dplyr::filter(stretch_st != "noneffort") %>%
dplyr::filter(compriment != 0) %>%
dplyr::rename(original_length = compriment) %>%
dplyr::filter(beach_name != "Ponta do Itaguá") %>%
dplyr::rename(beach = beach_name) %>%
dplyr::rename(stretch = stretch_na) %>%
dplyr::mutate(id_original = dplyr::row_number()) %>%
sf::st_cast("MULTILINESTRING")
# Create a buffer of 300 m around the beach monitoring lines
originalStretches <-
sf::st_transform(originalStretches, crs = 31982)
buffer <-
sf::st_buffer(originalStretches, dist = 300)
# Transform 'pontoporia' into a geospatial feature
pontoporia <-
pontoporia %>%
dplyr::mutate(long1 = long)%>%
dplyr::mutate(lat1 = lat)
pontoporiaSpatial <-
pontoporia %>%
sf::st_as_sf(coords = c("long1","lat1"), crs = 4326) %>%
sf::st_transform(pontoporiaSpatial, crs = 31982) # Same 'crs' as 'originalStreches'
# Remove records outside the buffer
pontoporiaSpatial$on_buffer <-
lengths(sf::st_within(pontoporiaSpatial, buffer))
pontoporiaSpatial <-
pontoporiaSpatial %>%
dplyr::filter(on_buffer > 0) %>%
dplyr::select(- on_buffer)
# mapview::mapview(buffer) + pontoporiaSpatial
## Clean environment
rm(list = "buffer", "ff", "lines", "i")
##----------------------------------------------------------------------------##
## Survey effort dataset ##
##----------------------------------------------------------------------------##
## Open survey effort dataset
ef_SP <- read.csv2("data/Effort_SP_aug2019_jul_2020.csv",
header = TRUE, encoding = "UTF-8")
ef_SC_PR <- read.csv2("data/Effort_SC_PR_aug2019_jul_2020.csv",
header = TRUE, encoding = "UTF-8")
ef_SP_PR_SC <- read.csv2("data/Effort_SC_PR_SP_aug2015_aug_2019.csv",
header = TRUE, encoding = "UTF-8")
eff <- rbind(ef_SP, ef_SC_PR, ef_SP_PR_SC)
rm(list = ls(pattern = "ef_"))
## Split data and hour
eff$date <-
lubridate::dmy(
sapply(strsplit(as.character(eff$Data.Hora.início), " "), "[", 1))
## Removing unused columns
eff[c(2:3, 10:12, 15:16)] <- list(NULL)
## Rename columns and levels
colnames(eff) <- c("code", "state", "city", "beach", "stretch", "type",
"stretch_scheme", "initial_lat", "initial_long", "complete",
"date")
eff$stretch_scheme <- as.factor(eff$stretch_scheme)
levels(eff$stretch_scheme) <- list(daily = "Diário",
weekly = "Semanal",
fortnightly = "Diário 15",
call = "Acionamento")
eff$type <- as.factor(eff$type)
levels(eff$type) <- list(boat = "Embarcado",
land = "Terrestre")
eff$complete <- as.factor(eff$complete)
levels(eff$complete) <- list(yes = "Sim",
no = "Não")
## Filter survey effort from date > "September2015" and <= "2020-06-07";
## Remove stretch_scheme == "call" and complete == "NA";
## Create columns year, month, day, week, semester, season, year_n and fortnight_month
eff <-
eff %>%
dplyr::filter(date > "2015-08-31" & date <= "2020-06-07") %>%
dplyr::filter(stretch_scheme != "call") %>%
dplyr::filter(complete != "NA") %>%
dplyr::mutate(year = lubridate::year(date),
month = lubridate::month(date),
day = lubridate::day(date),
week = lubridate::week(date),
semester = lubridate::semester(date, with_year = TRUE),
season =
ifelse(month >= 1 & month <= 3, "summer",
ifelse(month >= 4 & month <= 6, "autumn",
ifelse(month >= 7 & month <= 9, "winter", "spring"))),
year_n =
ifelse(date > "2015-08-31" & date < "2016-09-01", "Year1",
ifelse(date > "2016-08-31" & date < "2017-09-01", "Year2",
ifelse(date > "2017-08-31" & date < "2018-09-01", "Year3",
ifelse(date > "2018-08-31" & date < "2019-09-01", "Year4",
"Year5")))),
fortnight_month = ifelse(day <= 15, "1", "2"))
## Create a continuous id for fortnight periods through the year
fortnight_df_eff <-
eff %>%
dplyr::select(code, month, fortnight_month)
fortnight_df_eff <-
fortnight_df_eff %>%
dplyr::group_by(month, fortnight_month) %>%
dplyr::mutate(fortnight_id = dplyr::cur_group_id()) %>%
dplyr::ungroup() %>%
dplyr::select(code, fortnight_id)
## Join 'fortnight_df_eff' into 'eff'
eff <- dplyr::left_join(eff, fortnight_df_eff, by = "code")
##----------------------------------------------------------------------------##
## Standardize the numbers and names of beach surveyed ##
## in eff and originalStretches ##
##----------------------------------------------------------------------------##
## Removing excess of spaces between characters
eff$beach <- gsub("\\s+", " ", eff$beach)
eff$stretch <-gsub("\\s+", " ", eff$stretch)
originalStretches$beach <- gsub("\\s+", " ", originalStretches$beach)
originalStretches$stretch <- gsub("\\s+", " ", originalStretches$stretch)
## Identify beaches and stretches in 'eff'
## that are not in 'originalStretches' and vice verse
identify1 <- dplyr::setdiff(eff$beach, originalStretches$beach)
identify2 <- dplyr::setdiff(originalStretches$beach, eff$beach)
identify3 <- dplyr::setdiff(eff$stretch, originalStretches$stretch)
identify4 <- dplyr::setdiff(originalStretches$stretch, eff$stretch)
## Select and view the beaches and stretches in the above conditions
## Transform 'eff' into a geospatial feature
effSpatial <-
eff %>%
sf::st_as_sf(coords = c("initial_long", "initial_lat"), crs = 4326)
select1 <-
effSpatial %>%
dplyr::filter(beach == "Bal. Barra do Sul" | beach == "Itararé")
select3 <-
effSpatial %>%
dplyr::filter(stretch == "antigo D15- Ilha Comprida" |
stretch == "Antigo Superagui Sul e trapiche-Rio" |
stretch == "Ipanema" | stretch == "Matinhos 1" |
stretch == "Matinhos 2" | stretch == "Pontal do Sul" |
stretch == "Praia da Barra N" | stretch == "Praia da Barra S" |
stretch == "Praia de Garopaba N" | stretch =="Praia de Garopaba S" |
stretch == "Praia de Leste")
# mapview::mapview(originalStretches) + select1
# mapview::mapview(originalStretches) + select3
## Verify duplicated beach names
eff_BeachNames <-
effSpatial %>%
dplyr::group_by(beach, stretch, city, state) %>%
dplyr::summarise(n = n()) %>%
dplyr::group_by(beach) %>%
dplyr::filter(n() > 1)
## Select and view the duplicated beaches
# select_duplicated_BeachNames <-
# originalStretches %>%
# dplyr::filter(beach == "...") # insert the beach name in "..." to visualize
# mapview::mapview(select_duplicated_BeachNames)
#---------------
# Conclusions:
# C1: Same beaches with different names in 'eff' and 'originalStretches':
# "Bal. Barra do Sul" == ""Barra do Sul - 2 - 395 - 396 - 67" and
# "Itararé" == "Praia do José Menino, Praia do Gonzaga, Praia do Boqueirão,
# Praia do Embaré, Praia Aparecida, Ponta da Praia".
# C2: Different beaches identified with the same name in 'eff' and
# 'originalStretches': "Armação", "Brava","Camburizinho","Estaleiro","Pereque",
# "Praia Brava","Praia Grande".
# C3: Beaches with two or more stretches in 'eff' and one in 'originalStretches':
# "Praia da Barra N" and "Praia da Barra S" == "Praia da Barra";
# "Praia de Garopaba N" and "Praia de Garopaba S" == "Praia de Garopara";
# "antigo D15- Ilha Comprida" and "Ilha Comprida" == "Ilha Comprida";
# "Ipanema","Matinhos,Matinhos 2", "Pontal do Sul","Pontal do Sul/ Flamingo" and
# "Praia de Leste" == "Pontal do Sul/ Flamingo".
# C3.1: The stretch name "antigo D15- Ilha Comprida" was the unique stretch used
# for "Ilha Comprida" beach until 2017/03/23. Since then it was
# rename to "Ilha Comprida".
# C3.2: The stretch "Pontal do Sul/ Flamingo" was used from spetember2015 to
# 2019/08/19.Since then it was split in five new strecthes: "Ipanema","Matinhos,
# Matinhos 2", "Pontal do Sul" and "Praia de Leste".
# C4:The stretch name "Antigo Superagui Sul e trapiche-Rio" was the unique
# stretch used for "Ilha do Superagui" beach until 2017/10/21. Since then it was
# split in two new stretches: "Superagui Trapiche-Rio Novo" and
# "Superagui Sul Novo.
#---------------
## Standardize beaches and stretches in 'eff' and 'originalStretches' according
## to above conclusions
## C1: rename beaches "Bal. Barra do Sul" and "Itararé" as in 'originalStreches'
effStandardize <-
eff %>%
dplyr::mutate(beach = recode_factor(beach,
"Bal. Barra do Sul" = "Barra do Sul - 2 - 395 - 396 - 67",
"Itararé" = "Praia do José Menino, Praia do Gonzaga, Praia do Boqueirão, Praia do Embaré, Praia Aparecida, Ponta da Praia"))
## C2: rename different beaches identified with the same name in 'eff' and
## 'originalStreches'
effStandardize$beach <- as.character(effStandardize$beach)
effStandardize$city <- as.character(effStandardize$city)
effStandardize <-
effStandardize %>%
dplyr::mutate(beach =
ifelse(beach == "Armação" & city == "Florianópolis", "ArmaçãoFloripa",
ifelse(beach == "Armação" & city == "Ilhabela", "ArmaçãoIlhaBela",
ifelse(beach == "Armação" & city == "Penha", "ArmaçãoPenha",
ifelse(beach == "Brava" & city == "Florianópolis", "BravaFloripa",
ifelse(beach == "Brava" & city == "Balneário Camboriú", "BravaItajaí",
ifelse(beach == "Brava" & city == "Balneário Camboriú, Itajaí", "BravaItajaí",
ifelse(beach == "Camburizinho" & city == "Guarujá", "CamburizinhoGuarujá",
ifelse(beach == "Camburizinho" & city == "São Sebastião", "CamburizinhoSebastião",
ifelse(beach == "Estaleiro" & city == "Balneário Camboriú", "EstaleiroCamburiú",
ifelse(beach == "Estaleiro" & city == "Ubatuba", "EstaleiroUbatuba",
ifelse(beach == "Pereque" & city == "Guarujá", "PerequeGarujá",
ifelse(beach == "Pereque" & city == "Ilhabela", "PerequeIlhaBela",
ifelse(beach == "Pereque" & city == "Porto Belo", "PerequePortoBelo",
ifelse(beach == "Praia Brava" & city == "Ilhabela", "Praia BravaIlhaBela",
ifelse(beach == "Praia Brava" & city == "Matinhos", "Praia BravaMatinhos",
ifelse(beach == "Praia Grande" & city == "Praia Grande","Praia Grande",
ifelse(beach == "Praia Grande" & city == "Penha","Praia GrandePenha",
beach))))))))))))))))))
originalStretchesStandardize <-
originalStretches %>%
dplyr::mutate(beach =
ifelse(beach == "Armação" & id_original == 282, "ArmaçãoFloripa",
ifelse(beach == "Armação" & id_original == 89, "ArmaçãoIlhaBela",
ifelse(beach == "Armação" & id_original == 339, "ArmaçãoPenha",
ifelse(beach == "Brava" & id_original == 287, "BravaFloripa",
ifelse(beach == "Brava" & id_original == 334, "BravaItajaí",
ifelse(beach == "Brava" & id_original == 371, "BravaItajaí",
ifelse(beach == "Camburizinho" & id_original == 234, "CamburizinhoGuarujá",
ifelse(beach == "Camburizinho" & id_original == 75, "CamburizinhoSebastião",
ifelse(beach == "Estaleiro" & id_original == 338, "EstaleiroCamburiú",
ifelse(beach == "Estaleiro" & id_original == 146, "EstaleiroUbatuba",
ifelse(beach == "Pereque" & id_original == 254, "PerequeGarujá",
ifelse(beach == "Pereque" & id_original == 77, "PerequeIlhaBela",
ifelse(beach == "Pereque" & id_original == 359, "PerequePortoBelo",
ifelse(beach == "Praia Brava" & id_original == 202, "Praia BravaIlhaBela",
ifelse(beach == "Praia Brava" & id_original == 312, "Praia BravaMatinhos",
ifelse(beach == "Praia Grande" & id_original == 222, "Praia Grande",
ifelse(beach == "Praia Grande" & id_original == 352, "Praia GrandePenha",
beach))))))))))))))))))
## C3: For those beaches with multiple stretches in the same period, choose one
## stretches, rename it as in 'originalStretches' and remove the remain stretches.
## For those beaches with multiple stretches, but in different periods
## (e.g. "Ilha Comprida"), just rename the stretch as in 'originalStretches'.
## Step1: remove the stretches
effStandardize <-
effStandardize %>%
dplyr::filter(stretch != "Praia da Barra N") %>%
dplyr::filter(stretch != "Praia de Garopaba N") %>%
dplyr::filter(stretch != "Matinhos 1") %>%
dplyr::filter(stretch != "Matinhos 2") %>%
dplyr::filter(stretch != "Ipanema") %>%
dplyr::filter(stretch != "Praia de Leste")
## Step2: rename the stretches as in originalStretches
effStandardize <-
effStandardize %>%
dplyr::mutate(stretch =
ifelse(beach == "Praia da Barra" & stretch == "Praia da Barra S", "Praia da Barra",
ifelse(beach == "Praia de Garopaba" & stretch == "Praia de Garopaba S", "Praia de Garopaba",
ifelse(beach == "Pontal do Sul/ Flamingo" & stretch == "Pontal do Sul", "Pontal do Sul/ Flamingo",
ifelse(beach == "Ilha Comprida" & stretch == "antigo D15- Ilha Comprida", "Ilha Comprida",
stretch)))))
## C4: split "Antigo Superagui Sul e trapiche-Rio" in two stretches:
## "Superagui Sul Novo" and "Superagui Trapiche-Rio Novo".
## Step1: remove repeted date for stretch == "Antigo Superagui Sul e
## trapiche-Rio" in 'eff'
Superagui_df <-
effStandardize %>%
dplyr::filter(stretch == "Antigo Superagui Sul e trapiche-Rio")
Superagui_df <-
Superagui_df[!duplicated(Superagui_df$date), ]
## Step2: rename "Antigo Superagui Sul e trapiche-Rio" as "Superagui Sul Novo"
Superagui_df$stretch <-
as.factor(Superagui_df$stretch)
Superagui_df_SulNovo <-
Superagui_df %>%
dplyr::mutate(stretch = recode_factor(stretch,
"Antigo Superagui Sul e trapiche-Rio" = "Superagui Sul Novo"))
## Step3: rename "Antigo Superagui Sul e trapiche-Rio" as
## "Superagui Trapiche-Rio Novo"
Superagui_df_TrapicheNovo <-
Superagui_df %>%
dplyr::mutate(stretch = recode_factor(stretch,
"Antigo Superagui Sul e trapiche-Rio" = "Superagui Trapiche-Rio Novo"))
## Step4: combine "Superagui_df_TrapicheNovo" and "Superagui_df_SulNovo"
Superagui_df <-
rbind(Superagui_df_SulNovo, Superagui_df_TrapicheNovo)
## Step5: combine "dfSuperagui" and "effStandardize"
effStandardize <-
effStandardize %>%
dplyr::filter(stretch != "Antigo Superagui Sul e trapiche-Rio")
effStandardize <-
rbind(effStandardize, Superagui_df)
## Create a id for 'effStandardize' and 'originaStrechesStandardize' based on
## "beach" and "stretch" columns.
eff2 <-
effStandardize %>%
dplyr::mutate(beach_id = paste(beach, stretch, sep = "/")) %>%
dplyr::relocate(stretch, .before = beach) %>%
dplyr::relocate(beach_id, .after = beach)
originalStretches2 <-
originalStretchesStandardize %>%
dplyr::select(-c(beach_id, pmp_id, stretch_id, executing_, geometry,
executin_1, OBJECTID, stretch__1)) %>%
dplyr::mutate(beach_id = paste(beach, stretch, sep = "/")) %>%
dplyr::select(id_original, executing1, stretch_st, stretch_ty,
stretch, beach, beach_id, original_length, geometry)
## sf::st_write(originalStretches2, "./data_out/originalStretchesFinal.shp")
## Check beaches and stretches in 'eff2'
## that are not in 'originalStretches2' and vice versa
identify1 <- dplyr::setdiff(eff2$beach_id,
originalStretches2$beach_id)
identify2 <- dplyr::setdiff(originalStretches2$beach_id,
eff2$beach_id)
## Clean environment
rm(list = "effStandardize", "eff_BeachNames", "fortnight_df", "fortnight_df_eff",
"originalStretchesStandardize", "select_duplicated_BeachNames",
"select1", "select3", "Superagui_df", "Superagui_df_SulNovo", "Superagui_df_TrapicheNovo")
##----------------------------------------------------------------------------##
## Split monitored beach segments based on polygon sectors ##
##----------------------------------------------------------------------------##
## Create a 30 latitudinal-band Sector polygon,
## which will be the basis for final analysis
## Transform crs
originalStretches <-
sf::st_transform(originalStretches2, crs = 4326)
# mapview(originalStretches)
## Latitudinal definition
n <-
diff(sf::st_bbox(originalStretches)[c(2, 4)])/30
## Longitudinal definition
m <-
diff(sf::st_bbox(originalStretches)[c(1, 3)])
## Create the 'sectorsPolygon' based on 'originalStretches' extend
sectorsPolygon <-
sf::st_make_grid(originalStretches, cellsize = c(m, n))
## Set the correct spatial attributes for 'sectorsPolygon' layer
## Define 'sectorsPolygon' as single feature
sectorsPolygon <-
sf::st_sf(sectorsPolygon)
## Create an identifier for each sector
sectorsPolygon$id_polygon <- 1:nrow(sectorsPolygon)
## Define 'sectorsPolygon' as a multipolygon
sectorsPolygon <-
sectorsPolygon %>%
sf::st_cast("MULTIPOLYGON")
# mapview::mapview(sectorsPolygon)+originalStretches
# sf::st_write(sectorsPolygon, "./data_out/sectorsPolygon.shp")
## Create a multiline feature based on 'sectorsPolygon' id limits
sectorsPolygon_lines <-
sf::st_cast(sectorsPolygon, "MULTILINESTRING",
group_or_split = FALSE)
# mapview::mapview(sectorsPolygon_lines)
# sf::st_write(sectorsPolygon_lines, "./data_out/sectorsPolygon_linesFinal.shp")
#------------
# Look for intersections between the 30 latitudinal-band 'sectorsPolygon' and
# the monitored beaches 'originalStretches'
# Cut features and calculate each segment length, for calculate effort (m)
#------------
## Calculate intersection between 'originalStretches' and 'sectorsPolygon'
newStretches <-
sf::st_intersection(originalStretches, sectorsPolygon)
## Add a new id for each segment line, called "id_newStretches"
newStretches$id_newStretches <- 1:nrow(newStretches)
## Calculate individual segment lengths
newStretches$new_length <- sf::st_length(newStretches)
## Set "new_length" and "original_length" in kilometers and obtain the
## difference between them
newStretches <-
newStretches %>%
dplyr::mutate(new_length = as.numeric(new_length / 1000),
original_length = as.numeric(original_length / 1000)) %>%
dplyr::mutate_if(is.numeric, round, digits = 2) %>%
dplyr::mutate(difference = original_length - new_length)
difference <-
newStretches %>%
dplyr::filter(difference > 0)
# mapview::mapView(difference) + sectorsPolygon_lines
## Clean 'newStretches' and and rename some columns.
newStretches <-
newStretches %>%
dplyr::select(id_original, id_newStretches,
id_polygon, executing1, beach,
stretch, beach_id, stretch_st,
new_length, geometry) %>%
dplyr::rename(stretch_scheme = stretch_st,
new_length_km = new_length) %>%
sf::st_as_sf() %>%
sf::st_set_crs(4326)
# mapview::mapview(sectorsPolygon) + newStretches
##----------------------------------------------------------------------------##
## Join 'pontoporia' & 'eff' with 'newStretches' ##
##----------------------------------------------------------------------------##
## Transform crs
pontoporiaSpatial <-
sf::st_transform(pontoporiaSpatial, crs = 4326)
## Join attributes from 'newStretches' into 'pontoporiaSpatial'
pontoporiaSpatialJoin <-
sf::st_join(pontoporiaSpatial, newStretches,
join = sf::st_nearest_feature)
## Return to df format clean, rename and reorganize the columns.
pontoporia <-
pontoporiaSpatialJoin %>%
as.data.frame() %>%
dplyr::rename(beach = beach.x,
stretch = stretch.x,
stretch_scheme = stretch_scheme.x) %>%
dplyr::select(id_original, id_newStretches, id_polygon, zone,
id_individual, state, beach, stretch, beach_id, new_length_km,
stretch_scheme, monitoring_type, lat, long,
date, year, year_n, semester, month, season, fortnight_id, week, day,
back_date, cod_decomposition, sex)
## Join attributes from 'newStretches' into 'eff2'
effJoin <-
merge(eff2, newStretches, by = "beach_id", all = TRUE)
## Clean, rename and reorganize the columns
eff <-
effJoin %>%
dplyr::rename(beach = beach.x,
stretch = stretch.x,
stretch_scheme = stretch_scheme.x) %>%
dplyr::select(code, id_original, id_newStretches, id_polygon, executing1,
state, beach, stretch, beach_id, new_length_km,
stretch_scheme, type, initial_lat, initial_long, complete,
date, year, year_n, semester, month, season, fortnight_id, week, day) %>%
dplyr::arrange(date)
## write.csv2(eff,"./data_out/effFinal.csv")
## Clean environment
rm(list = "difference", "effJoin", "eff2", "effSpatial",
"pontoporiaSpatial", "pontoporiaSpatialJoin")
##----------------------------------------------------------------------------##
## Stranding records collected in complete-made stretches ##
##----------------------------------------------------------------------------##
## Create 'eff_i' and "date_id_newStretches" column
eff_i <-
eff %>%
dplyr::filter(complete != "yes") %>%
dplyr::mutate(date_id_newStretches = paste(date, id_newStretches))
## Create "date_id_newStretches" column in 'pontoporia'
pontoporia <-
pontoporia %>%
dplyr::mutate(date_id_newStretches = paste(date, id_newStretches))
## Remove strandings in 'pontoporia' recorded during incomplete beach surveys.
pontoporia <-
dplyr::anti_join(pontoporia, eff_i, by = "date_id_newStretches")
## Remove "date_id_newStretches" from 'pontoporia'
pontoporia <-
pontoporia %>%
dplyr::select(- date_id_newStretches)
# write.csv2(pontoporia,"./data_out/pontoporia_stranding.csv")
##----------------------------------------------------------------------------##
## Join environment data with pontoporia df ##
##----------------------------------------------------------------------------##
## The environmental data was collected from ERA5
## through a Python routine files = {download_and_process_era5_data.py} + {requirements.txt}
## two different files are used in this step because the zone of 44 stranding
## was updated after reviewing the methodology during the the process of this
## consultancy. This step used source("./functionEnvData.R") to clean env data
## and merge with pontoporia df
envVariables_old_zones <- processing_env_data(
env_file = "./data/environmental_data/envVariables_old_zone.csv")
envVariables_new_zones <- processing_env_data(
env_file = "./data/environmental_data/envVariables_new_zone.csv"
)
## Substitute the 44 strandings with old Zones (between lat -26/ -26.2) by the
## the new and correct data (downloaded using the new Zone)
envVariables <- rbind((envVariables_old_zones %>% filter(!(id_individual %in%
envVariables_new_zones$id_individual))) ,
envVariables_new_zones)
## remove the two initial environmental dfs:
rm(list = "envVariables_new_zones", "envVariables_old_zones")
## save final environmental df:
# write.csv(envVariables, "./data_out/strandingAndEnv.csv")
##----------------------------------------------------------------------------##
## Summarize by polygon, month, fortnight and week ##
##----------------------------------------------------------------------------##
## Obtain completed survey effort df
eff_c <-
eff %>%
dplyr::filter(complete != "no")
## Summarise 'pontoporia' and 'eff_c':
## Per "week"
ponWeek <-
pontoporia %>%
dplyr::group_by(year_n, week, id_polygon) %>%
dplyr::summarise(y = n()) %>%
dplyr::mutate_at(c(1:3), as.factor)
effWeek <-
eff_c %>%
dplyr::group_by(year_n, id_polygon, week) %>%
dplyr::summarise(effort_km = sum(new_length_km)) %>%
dplyr::mutate_at(c(1:3), as.factor)
ponWeekFinal <-
dplyr::left_join(effWeek, ponWeek,
by = c("id_polygon", "year_n", "week")) %>%
replace(., is.na(.), 0)
## Per "fortnight"
ponFortnight <-
pontoporia %>%
dplyr::group_by(year_n, id_polygon, fortnight_id) %>%
dplyr::summarise(y = n()) %>%
dplyr::mutate_at(c(1:3), as.factor)
effFortnight <-
eff_c %>%
dplyr::group_by(year_n, id_polygon, fortnight_id) %>%
dplyr::summarise(effort_km = sum(new_length_km)) %>%
dplyr::mutate_at(c(1:3), as.factor)
ponFortnightFinal <-
dplyr::left_join(effFortnight, ponFortnight,
by = c("id_polygon", "year_n", "fortnight_id")) %>%
replace(., is.na(.), 0)
## Per "month"
ponMonth <-
pontoporia %>%
dplyr::group_by(id_polygon, year_n, month) %>%
dplyr::summarise(y = n()) %>%
dplyr::mutate_at(c(1:3), as.factor)
effMonth <-
eff_c %>%
dplyr::group_by(year_n, id_polygon, month) %>%
dplyr::summarise(effort_km = sum(new_length_km)) %>%
dplyr::mutate_at(c(1:3), as.factor)
ponMonthFinal <-
dplyr::left_join(effMonth, ponMonth,
by = c("id_polygon", "year_n", "month")) %>%
replace(., is.na(.), 0)
## Per "season"
ponSeason <-
pontoporia %>%
dplyr::group_by(id_polygon, year_n, season) %>%
dplyr::summarise(y = n()) %>%
dplyr::mutate_at(c(1:3), as.factor)
effSeason <-
eff_c %>%
dplyr::group_by(year_n, id_polygon, season) %>%
dplyr::summarise(effort_km = sum(new_length_km)) %>%
dplyr::mutate_at(c(1:3), as.factor)
ponSeasonFinal <-
dplyr::left_join(effSeason, ponSeason,
by = c("id_polygon","year_n", "season")) %>%
replace(., is.na(.), 0)
# write.csv2(ponWeekFinal,"./data_out/ponWeekFinal.csv")
# write.csv2(ponFortnightFinal,"./data_out/ponFortnightFinal.csv")
# write.csv2(ponMonthFinal,"./data_out/ponMonthFinal.csv")
# write.csv2(ponSeasonFinal,"./data_out/ponSeasonFinal.csv")
##----------------------------------------------------------------------------##
## Create fake stranding in the middle ##
## of each polygon ##
## using ponFortnightFinal ##
##----------------------------------------------------------------------------##
## Task 01: find start and end date of fortnight: ####
empty_fortnight <- read.csv("./data_out/ponFortnightFinal.csv", sep = ";") %>%
filter(y==0)
## to select fortnight
filter_dates <- pontoporia %>% dplyr::select(contains(c("year", "month", "fortnight_id"))) %>%
group_by(year_n, year, month) %>% distinct(fortnight_id)
empty_fortnight = empty_fortnight %>%
mutate(day_start = (ifelse(fortnight_id%%2 == 0, "16", "1"))) %>%
mutate(day_end = (ifelse(fortnight_id%%2 == 0, "30", "15"))) %>%
left_join(., filter_dates, by = c("year_n", "fortnight_id"), suffix(".y") ) %>%
mutate(day_end = (ifelse(month == 2, "28", day_end))) %>%
mutate(date = lubridate::ymd(paste(year,month,day_start, sep = "-"))) %>%
mutate(back_date = lubridate::ymd(paste(year, month,day_end, sep = "-"))) %>%
dplyr::select(!starts_with(c("month", "day_"))) %>%
dplyr::select(!ends_with("year")) %>% dplyr::rename(id=X)
## Task 2: find middle point of coastline ("fake stranding") for each polygon sector and merge with task 2: ####
# Open coastline, segment it using sectors and cast to linestring:
coastline <-
sf::st_intersection(st_read("./data/coastline_S_SE/lc_ilhas_tratada_UTM.shp"), sf::st_transform(sectorsPolygon, crs = 31982)) %>%
st_cast("MULTILINESTRING") %>% st_cast("LINESTRING", group_or_split = TRUE)
# calculate the length and select the longest stripe of coastline along each
# polygon sector and extract its middle point:
coastline_middle_pt <- coastline %>%
mutate(new_length = st_length(.)) %>%
mutate(new_length = as.numeric(new_length)) %>%
group_by(id_polygon) %>% filter(new_length == max(new_length))
# extract middle point:
coastline_middle_pt <- st_as_sf(maptools::SpatialLinesMidPoints(as(coastline_middle_pt, "Spatial")))
# extract lat, long column
coastline_middle_pt = coastline_middle_pt %>%
mutate(long = st_coordinates(st_transform(coastline_middle_pt, 4326))[,1]) %>%
mutate(lat = st_coordinates(st_transform(coastline_middle_pt, 4326))[,2])
# join
empty_fortnight_download <- left_join(empty_fortnight, (coastline_middle_pt %>% dplyr::select(contains(c("lat", "lon", "id_poly")))))
empty_fortnight_download$zone <- "2"
# viz:
# mapview(coastline_middle_pt) + coastline
# write.csv(empty_fortnight_download, "./data_out/empty_fortnight_download_era5.csv")
## The "empty_fortnight_download_era5.csv" created in the step above was used as
## input in the download_and_process_era5_data.py script. And the output file generated after running
## the code is called "envVariables_without_stranding_fortnight.csv" to be
## used in the next session
## Clean environment
rm(list = "ponWeek", "effWeek", "ponWeekFinal",
"ponFortnight", "effFortnight", "ponFortnightFinal",
"ponMonth", "effMonth", "ponMonthFinal",
"ponSeason", "effSeason", "ponSeasonFinal",
"eff_i", "eff_c", "empty_fortnight_download", "empty_fortnight")
##----------------------------------------------------------------------------##
## Process the env data downloaded for ##
## "fake stranding" (session above) and ##
## join it to the initial ponFortnightFinal df ##
##----------------------------------------------------------------------------##
envVariables_empty_fortnight <- processing_env_data(
env_file = "./data/environmental_data/envVariables_without_stranding_fortnight.csv",
corresponding_df = read.csv2("./data_out/ponFortnightFinal.csv"), id_column = "X")
# write csv:
# write.csv(envVariables_empty_fortnight, "./data_out/no_strandingAndEnv_fortnight.csv")
##----------------------------------------------------------------------------##
## Drift dataset ##
##----------------------------------------------------------------------------##
## Open drift experiment dataset
drift <- read.csv("./data/drift_experiment_data.csv", sep = ";")
# cf. if you need to run this -- just to fix bug on a variable name
drift <-
drift %>%
dplyr::rename(campaign=ï..campaign)
## Create "ReleaseStation" column
drift <-
drift %>%
dplyr::mutate(ReleaseStation =
ifelse(lat_r > -23.8, "1",
ifelse(lat_r < -23.8 & lat_r > -24.4,"2",
ifelse(lat_r < -24.4 & lat_r > -26, "3", "4"))))
drift$ReleaseStation <- as.factor(drift$ReleaseStation)
#------------
# PS: The 'ReleaseStation' represent the places where the drifters were released.
#------------
## Filter and set up date columns
drift_i <-
drift %>%
dplyr::filter(lat_s != is.na(lat_s)) %>%
dplyr::filter(date_s != is.na(date_s))
drift_i$date_r <- lubridate::dmy(drift_i$date_r)
drift_i$date_s <- lubridate::dmy(drift_i$date_s)
################################################################################
############################ Figures and Tables ################################
########################### Material and Methods ###############################
################################################################################
## Open shapefile
brazil <-
sf::read_sf(dsn = "./shape", layer = "brasil") %>%
sf::st_set_crs(4326)