-
Notifications
You must be signed in to change notification settings - Fork 4
/
defStormsList.R
1210 lines (962 loc) · 36 KB
/
defStormsList.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
#############
#storm Class#
#############
#' `storm` object
#'
#' Gather all the needed informations to model a single storm
#'
#' @slot name character. Name of the storm
#' @slot season numeric. Cyclonic season in which the storm has occured
#' @slot scale numeric. Maximum scale category reached
#' @slot obs numeric vector. Indices of observations within the location of
#' interest extented with its corresponding buffer (See `stormsList` class)
#' @slot obs.all data.frame. Contains all of the observations available. An
#' observation is made up of several fields which are:
#' \itemize{
#' \item `iso.time`, Date and hours of observations (UTC)
#' \item `lon`, Longitude coordinate (Eastern degree)
#' \item `lat`, Latitude coordinate (Northern degree)
#' \item `msw`, Maximum Sustained Wind (m/s)
#' \item `scale`, Level in the chosen scale
#' }
#' The following field is not mandatory but highly recommended
#' \itemize{
#' \item `rmw`, Radius of Maximum Wind (km)
#' }
#' Also, the following fields are only mandatory to perform Holland and Boose
#' models (See `Details`)
#' \itemize{
#' \item `pres`, Pressure at the center (pa)
#' \item `poci`, Pressure of the Outermost Closed Isobar (pa)
#' }
#' @return A `storm` object.
#' \itemize{
#' \item `name`, character.
#' \item `season`, numeric.
#' \item `scale`, numeric.
#' \item `obs`, numeric.
#' \item `obs.all`, data.frame.
#' }
#' @importFrom methods new
#' @export
storm <- methods::setClass("storm",
slots = c(name = "character",
season = "numeric",
scale = "numeric",
obs = "numeric",
obs.all = "data.frame"))
##############
#stormsList Class#
##############
setOldClass("sf")
#' `stormsList` object
#'
#' Gather all the needed informations to model a set of storms
#'
#' @slot data A list of `storm` (See `storm` class)
#' @slot buffer numeric. Buffer used to extent `spatialLoi` (km)
#' @slot spatialLoi sf object. Represents the location of interest. Projection
#' is EPSG:4326
#' @slot spatialLoiBuffer sf object. Buffer extension of `spatialLoi`
#' @slot scale numeric. List of storm scale thresholds to use in all functions of
#' the package. Default value is set to the Saffir Simpson Hurricane Scale
#' @slot scalePalette character. Named vector containing the color hex code
#' corresponding to each category in `scale` slot. Default value is the palette associated with the Saffir Simpson Hurricane Scale
#' @return A `stormsList` object.
#' \itemize{
#' \item `data`, list.
#' \item `buffer`, numeric.
#' \item `spatialLoi`, sf.
#' \item `spatialLoiBuffer`, sf.
#' }
#' @importFrom methods new
#' @importFrom methods show
#' @export
stormsList <- methods::setClass("stormsList",
slots = c(data = "list",
buffer = "numeric",
spatialLoi = "sf",
spatialLoiBuffer = "sf",
scale = "numeric",
scalePalette = "character"))
##############
#Show methods#
##############
#' Show a `storm`/`stormsList`
#'
#' Display the `storm`/`stormsList` object
#'
#' @param object `storm`/`stormsList` object
#'
#' @return NULL, only display information about the object
#' @keywords internal
#' @export
#' @docType methods
#' @rdname show-methods
#' @examples
#' \donttest{
#' sds <- defStormsDataset()
#' sts <- defStormsList(sds = sds, loi = "New Caledonia", names = c("LUCAS","NIRAN"))
#' ## Display information about Niran in sts
#' getStorm(sts, name = "NIRAN")
#'
#' ## Display information about sts
#' sts
#' }
setMethod("show",
signature("storm"),
function(object) {
cat("Name:", object@name, "\n")
cat("Season:", object@season, "\n")
cat("Maximum level reached in scale:", object@scale, "\n")
cat("Indices of observations within buffer:", object@obs, "\n")
cat("Observations:\n")
print(object@obs.all)
})
#' @rdname show-methods
setMethod("show",
signature("stormsList"),
function(object) {
cat("***** stormsList *****\n\n")
cat("Number of storms:", getNbStorms(object), "\n")
cat("Storms availables:\n\n")
for (i in 1:getNbStorms(object)) {
cat("*", i, "\n")
show(object@data[[i]])
cat("\n")
}
cat("\n***** End stormsList *****\n")
})
##############################
#Getters for stormsList class#
##############################
#' Extracting a `storm`
#'
#' The `getStorm()` function extracts a specific `storm` object
#' from a `stormsList` object.
#'
#' @param sts `stormsList`
#' @param name character. Name of the storm to extract.
#' @param season numeric vector. Seasons of occurrence of the storms
#' (e.g., c(2020,2022)). In the Southern Hemisphere,
#' the cyclone season extends across two consecutive years.
#' Therefore, to capture the 2021 to 2022 cyclone season both
#' years should be specified, with cyclones assigned for the year
#' #' that originated in. By default all storms occurring since
#' 1980 are extracted.
#' @return A `storm` object.
#' @export
#' @docType methods
#' @rdname getStorm-methods
#' @examples
#' #Creating a stormsDataset
#' \donttest{
#' sds <- defStormsDataset()
#'
#' #Getting storm track data for all storms near New Caledonia
#' sts <- defStormsList(sds=sds, loi = "New Caledonia")
#'
#' #Getting `storm` for the tropical cyclone Niran
#' st <- getStorm(sts, name = "NIRAN")
#' }
setGeneric("getStorm", function(sts, name, season = NULL) standardGeneric("getStorm"))
#' @rdname getStorm-methods
setMethod("getStorm", signature("stormsList"), function(sts, name, season = NULL) {
if (!is.null(season)) {
seasons <- getSeasons(sts)
ind <- which(names(seasons) == name & seasons == season)
if (!identical(unname(ind), integer(0))) {
sts@data[[ind]]
} else {
stop(paste("No cyclone named", name, "for season", season))
}
}else {
if (length(which(getNames(sts) == name)) > 1)
stop(paste("More than 1 storm named", name, ".Please specify season\n"))
sts@data[[name]]
}
})
#' Getting the number of `storm`
#'
#' The `getNbStorms()` returns the number of `storm` objects
#' in the given `stormsList` object.
#'
#' @param sts `stormsList`
#'
#' @return numeric, the number of `storm` objects.
#' @export
#' @docType methods
#' @rdname getNbStorms-methods
#' @examples
#' #Creating a stormsDataset
#' \donttest{
#' sds <- defStormsDataset()
#'
#' #Getting storm track data for all storms near New Caledonia
#' sts <- defStormsList(sds=sds, loi = "New Caledonia")
#'
#' #Getting the number of storms in the sts object
#' getNbStorms(sts)
#' }
setGeneric("getNbStorms", function(sts) standardGeneric("getNbStorms"))
#' @rdname getNbStorms-methods
setMethod("getNbStorms", signature("stormsList"), function(sts) length(sts@data))
#' Getting the location of interest
#'
#' The `getLOI()` functions returns the location of interest for the given `stormsList`.
#'
#' @param sts `stormsList` object
#'
#' @return sf object.
#' @export
#' @docType methods
#' @rdname getLOI-methods
#' @examples
#' #Creating a stormsDataset
#' \donttest{
#' sds <- defStormsDataset()
#'
#' #Getting storm track data for all storms near New Caledonia
#' sts <- defStormsList(sds=sds, loi = "New Caledonia")
#'
#' #Getting the location of interest for the sts object
#' loi <- getLOI(sts)
#' }
setGeneric("getLOI", function(sts) standardGeneric("getLOI"))
#' @rdname getLOI-methods
setMethod("getLOI", signature("stormsList"), function(sts) sts@spatialLoi)
#' Getting the buffered location of interest
#'
#' The `getBuffer()` function returns the buffered location
#' of interest from a `stormsList` object.
#'
#' @param sts `stormsList`
#'
#' @return A `sf` object.
#'
#' @export
#' @docType methods
#' @rdname getBuffer-methods
#' @examples
#' \donttest{
#' #Creating a stormsDataset
#' sds <- defStormsDataset()
#'
#' #Getting storm track data for all storms near New Caledonia
#' sts <- defStormsList(sds=sds, loi = "New Caledonia")
#'
#' #Getting the buffered location of interest from the sts object
#' buff <- getBuffer(sts)
#' }
setGeneric("getBuffer", function(sts) standardGeneric("getBuffer"))
#' @rdname getBuffer-methods
setMethod("getBuffer", signature("stormsList"), function(sts) sts@spatialLoiBuffer)
#' Getting the buffer size
#'
#' The `getBufferSize()` returns the buffer size used to generate
#' the buffered location of interest for a `stormsList` object.
#'
#' @param sts `stormsList`
#'
#' @return numeric.
#' @export
#' @docType methods
#' @rdname getBufferSize-methods
#' @examples
#' #Creating a stormsDataset
#' \donttest{
#' sds <- defStormsDataset()
#'
#' #Getting storm track data for all storms near New Caledonia
#' sts <- defStormsList(sds=sds, loi = "New Caledonia")
#'
#' #Getting the buffer size from the sts object
#' buffsize <- getBufferSize(sts)
#' }
setGeneric("getBufferSize", function(sts) standardGeneric("getBufferSize"))
#' @rdname getBufferSize-methods
setMethod("getBufferSize", signature("stormsList"), function(sts) sts@buffer)
###############################################
#Getters for both stormsList and storm classes#
###############################################
#' Getting the names of the storms
#'
#' The `getNames()` function returns the names of the storms
#' in a `storm` or a `stormsList` object.
#'
#' @param s `storm` or `stormsList` object.
#'
#' @return character vector.
#' @export
#' @docType methods
#' @rdname getNames-methods
#' @examples
#' \donttest{
#' #Creating a stormsDataset
#' sds <- defStormsDataset()
#'
#' #Getting storm track data for all storms near New Caledonia
#' sts <- defStormsList(sds=sds, loi = "New Caledonia")
#'
#' #Getting the names of the storms from the sts object
#' getNames(sts)
#' }
setGeneric("getNames", function(s) standardGeneric("getNames"))
#' @rdname getNames-methods
setMethod("getNames", signature("storm"), function(s) s@name)
#' @rdname getNames-methods
setMethod("getNames", signature("stormsList"), function(s) {
l <- unlist(lapply(s@data, getNames))
names(l) <- NULL
l
})
#' Getting cyclonic seasons of the storms
#'
#' The `getSeasons()` function returns the cyclonic season
#' of each storm in a `storm` or `stormsList` object.
#'
#' @param s `storm` or `stormsList` object.
#'
#' @return numeric vector.
#' @export
#' @docType methods
#' @rdname getSeasons-methods
#' @examples
#' \donttest{
#' #Creating a stormsDataset
#' sds <- defStormsDataset()
#'
#' #Getting storm track data for all storms near New Caledonia
#' sts <- defStormsList(sds=sds, loi = "New Caledonia")
#'
#' #Getting the cyclonic seasons of the storms from the sts object
#' getSeasons(sts)
#' }
setGeneric("getSeasons", function(s) standardGeneric("getSeasons"))
#' @rdname getSeasons-methods
setMethod("getSeasons", signature("storm"), function(s) s@season)
#' @rdname getSeasons-methods
setMethod("getSeasons", signature("stormsList"), function(s) unlist(lapply(s@data, getSeasons)))
#' Getting maximum level in the wind scale
#'
#' The `getScale()` function return the maximum wind scale category reached by
#' each storm in the `storm` or `stormsList` object.
#'
#' @param s `storm` or `stormsList` object.
#'
#' @return numeric vector.
#' @export
#' @docType methods
#' @rdname getScale-methods
#' @examples
#' \donttest{
#' #Creating a stormsDataset
#' sds <- defStormsDataset()
#'
#' #Getting storm track data for all storms near New Caledonia
#' sts <- defStormsList(sds=sds, loi = "New Caledonia")
#'
#' #Getting maximum level in the wind scale
#' #reached by each storm in the sts object
#' getScale(sts)
#' }
setGeneric("getScale", function(s) standardGeneric("getScale"))
#' @rdname getScale-methods
setMethod("getScale", signature("storm"), function(s) s@scale)
#' @rdname getScale-methods
setMethod("getScale", signature("stormsList"), function(s) unlist(lapply(s@data, getScale)))
#' Getting the number of observations
#'
#' The getNbObs() function returns the number of observations
#' for a storm in a `storm` or `stormsList` object.
#'
#' @param ... extra arguments for `stormsList`
#' @param s `storm` or `stormsList` object.
#' @param name character. Name of the storm in capital letters.
#' @param season numeric. Cyclonic season of the `storm`. Required only
#' if several `storm` in the `s` have the same name. Default value is set to
#' `NULL`.
#'
#' @return numeric.
#' @export
#' @docType methods
#' @rdname getNbObs-methods
#' @examples
#' \donttest{
#' #Creating a stormsDataset
#' sds <- defStormsDataset()
#'
#' #Getting storm track data for all storms near New Caledonia
#' sts <- defStormsList(sds=sds, loi = "New Caledonia")
#'
#' ##Getting the number of observations for the tropical cyclone Niran in the sts object
#' getNbObs(getStorm(sts, name = "NIRAN"))
#' getNbObs(sts, name = "NIRAN")
#' }
setGeneric("getNbObs", function(s, ...) standardGeneric("getNbObs"))
#' @rdname getNbObs-methods
setMethod("getNbObs", signature("storm"),
function(s) dim(s@obs.all)[1])
#' @rdname getNbObs-methods
setMethod("getNbObs", signature("stormsList"),
function(s, name, season = NULL) dim(getStorm(s, name, season)@obs.all)[1])
#' Getting observations
#'
#' The `getObs()` function returns observed track data for a storm
#' in a `storm` or `stormsList` object.
#'
#' @param ... extra argument for `stormsList`
#' @param s `storm` or `stormsList` object
#' @param name character. Name of the storm in capital letters.
#' @param season numeric. Cyclonic season of the `storm`. Required only
#' if several `storm` in the `s` object have the same name.
#' Default value is set to `NULL`.
#'
#' @return A data.frame.
#' @export
#' @docType methods
#' @rdname getObs-methods
#' @examples
#' \donttest{
#' #Creating a stormsDataset
#' sds <- defStormsDataset()
#'
#' #Getting storm track data for all storms near New Caledonia
#' sts <- defStormsList(sds=sds, loi = "New Caledonia")
#'
#' #Getting the observed track data for the tropical
#' #cyclone Niran in the sts object
#' getObs(getStorm(sts, name = "NIRAN"))
#' getObs(sts, name = "NIRAN")
#' }
setGeneric("getObs", function(s, ...) standardGeneric("getObs"))
#' @rdname getObs-methods
setMethod("getObs", signature("stormsList"), function(s, name, season = NULL) getStorm(s, name, season)@obs.all)
#' @rdname getObs-methods
setMethod("getObs", signature("storm"), function(s) s@obs.all)
#' Getting the number of the observations
#'
#' The `getInObs()` function returns the number of the
#' observations in a given `storm` or `stormsList` object.
#'
#' @param ... extra argument for `stormsList`
#' @param s `storm` or `stormsList` object.
#' @param name character. Name of the storm in capital letters.
#' @param season numeric. Cyclonic season of the `storm`. Required only
#' if several `storm` in `s` object have the same name. Default value is set
#' to `NULL`
#'
#' @return Numeric vector.
#'
#' @export
#' @docType methods
#' @rdname getInObs-methods
#' @examples
#' #Creating a stormsDataset
#' \donttest{
#' sds <- defStormsDataset()
#'
#' #Getting storm track data for all storms near New Caledonia
#' sts <- defStormsList(sds=sds, loi = "New Caledonia")
#'
#' #Getting the number of the observation for the tropical cyclone Niran in the sts object
#' getInObs(getStorm(sts, name = "NIRAN"))
#' getInObs(sts, name = "NIRAN")
#' }
setGeneric("getInObs", function(s, ...) standardGeneric("getInObs"))
#' @rdname getInObs-methods
setMethod("getInObs", signature("stormsList"), function(s, name, season = NULL) getStorm(s, name, season)@obs)
#' @rdname getInObs-methods
setMethod("getInObs", signature("storm"), function(s) s@obs)
########
#storms#
########
#' Check inputs for defStormsList function
#'
#' @noRd
#' @param sds stormsDataset object
#' @param loi Either:
#' \itemize{
#' \item a SpatialPolygon (shapefile)
#' \item a sf object
#' \item a point of longitude/latitude coordinates
#' \item a character representing a country,
#' }
#' @param seasons, numeric vector
#' @param names character vector
#' @param maxDist numeric
#' @param scale numeric vector
#' @param scalePalette character vector
#' @param verbose logical
#' @param removeUnder numeric
#' @return NULL, stops the function if an error is detected
checkInputsDefStormsList <- function(sds, loi, seasons, names, maxDist, scale, scalePalette, verbose, removeUnder) {
#checking sds input
stopifnot("sds is missing" = !missing(sds))
#Checking loi input
if (!missing(loi)) {
stopifnot("Invalid class for loi" = identical(class(loi), c("sf", "data.frame")) ||
identical(class(loi)[1], "SpatialPolygonsDataFrame") ||
identical(class(loi), "numeric") ||
identical(class(loi), "character"))
if (identical(class(loi), "numeric")) {
stopifnot("loi must have valid lon/lat coordinates " = length(loi) == 2
& loi[1] >= -180 & loi[1] <= 360 & loi[2] >= -90 & loi[2] <= 90)
}
if (identical(class(loi), "character"))
stopifnot("loi must be length 1 " = length(loi) == 1)
}else {
stop("loi is missing")
}
#Checking seasons input
stopifnot("seasons must be numeric" = identical(class(as.numeric(seasons)), "numeric"))
stopifnot("seasons must be as integer" = all(round(seasons) == seasons))
stopifnot("lower bound of seasons is lower than the minimum season of the stormsDataset.
This is not allowed. Please correct your seasons bounds or check your
stormsDataset if this is not expected" = seasons >= sds@seasons["min"])
stopifnot("upper bound of seasons is larger than the maximum season of the stormsDataset.
This is not allowed. Please correct your seasons bounds or check your
stormsDataset if this is not expected" = seasons <= sds@seasons["max"])
#Checking names input
if (!is.null(names)) {
stopifnot("names must be a vector of character" = identical(class(names), "character"))
} else {
stopifnot("Incompatible format for seasons (must be either length 1 or 2)" = length(seasons) == 1 ||
length(seasons) == 2)
}
#Checking maxDist input
stopifnot("maxDist must be numeric " = identical(class(maxDist), "numeric"))
stopifnot("maxDist must be a length 1 vector " = length(maxDist) == 1)
stopifnot("maxDist must greater or equal than 0 " = maxDist >= 0)
# Checking scale input
stopifnot("scale must be vector of numeric" = identical(class(scale), "numeric"))
stopifnot("invalid scale input" = all(scale>=0))
# Checking scalePalette input
if(!is.null(scalePalette)){
stopifnot("scalePalette must be a (named) character vector" = identical(class(scalePalette), "character"))
stopifnot("(lenght(scalePalette) must be equal to lenght(scale) + 1)" =
length(scalePalette) == length(scale) + 1)
}
#Checking verbose input
stopifnot("verbose must be numeric" = identical(class(verbose), "numeric"))
stopifnot("verbose must length 1" = length(verbose) == 1)
stopifnot("verbose must be either 0, 1 or 2" = verbose %in% c(0, 1, 2))
#Checking removeUnder input
if(!is.null(removeUnder)){
stopifnot("removeUnder must be numeric" = identical(class(removeUnder), "numeric"))
stopifnot("removeUnder must a single integer" = length(removeUnder) == 1)
stopifnot("Invalid removeUnder input" = removeUnder %in% seq(1, length(scale)))
}
}
#' Convert loi into a sf object
#'
#' @noRd
#' @param loi loi input from `stormsList`
#'
#' @return loi in a sf format
convertLoi <- function(loi) {
if (identical(class(loi)[1], c("SpatialPolygonsDataFrame"))) {
loiSf <- sf::st_as_sf(loi)
loiSf <- sf::st_geometry(loiSf)
loiSf <- sf::st_sf(loiSf)
loiSf <- sf::st_as_sf(loiSf)
if (sf::st_crs(loiSf) != wgs84) {
loiSf <- sf::st_transform(loiSf, crs = wgs84)
}
} else if (identical(class(loi), c("sf", "data.frame"))) {
loiSf <- sf::st_geometry(loi)
loiSf <- sf::st_sf(loiSf)
loiSf <- sf::st_as_sf(loiSf)
if (sf::st_crs(loiSf) != wgs84) {
loiSf <- sf::st_transform(loiSf, crs = wgs84)
}
} else if (identical(class(loi), c("numeric"))) {
if (loi[1] < 0) {
loi[1] <- loi[1] + 360
warning("longitude coordinate for loi has been corrected and set between 0 and 360 degree")
}
loiDf <- data.frame(lon = loi[1], lat = loi[2])
loiSf <- sf::st_as_sf(loiDf, coords = c("lon", "lat"))
sf::st_crs(loiSf) <- wgs84
loiSf <- sf::st_transform(loiSf, crs = wgs84)
} else if (identical(class(loi), c("character"))) {
if (loi %in% c("NA", "SA", "EP", "WP", "SP", "SI", "NI", "ALL")) {
loiSf <- sf::st_as_sf(basins[basins$Name == loi, ][[2]])
}else {
map <- rworldmap::getMap(resolution = "high")
idCountry <- which(map@data$ADMIN == loi)
stopifnot("invalid entry for loi" = length(idCountry) > 0)
loiSf <- map[idCountry, ] |> sf::st_as_sf()
loiSf <- loiSf$geometry |> sf::st_as_sf()
sf::st_crs(loiSf) <- wgs84
}
}
#Handling time line for Fiji
loiSf <- sf::st_shift_longitude(loiSf)
return(loiSf)
}
#' make loi buffer
#'
#' @noRd
#' @param loi character. loi input from `storms`
#' @param loiSf sf object. loi input from `storms` already converted into sf
#' object
#' @param buffer numeric. Buffer size to use (in km)
#'
#' @return loi extended with buffer in a sf format
makeBuffer <- function(loi, loiSf, buffer) {
if (buffer == 0){
loiBuffer <- loiSf
}else if ((identical(class(loi), c("character"))) && (loi %in% c("NA", "SA", "EP", "WP", "SP", "SI", "NI", "ALL"))) {
loiBuffer <- loiSf
}else {
loiBuffer <- sf::st_buffer(loiSf, dist = buffer)
loiBuffer <- sf::st_shift_longitude(loiBuffer)
}
return(loiBuffer)
}
#' Retrieving the matching indices of storms
#'
#' @noRd
#' @param database storms database
#' @param filterNames character vector. Contains names input from the storms
#' @param filterSeasons numeric vector. Contains seasons input from the storms
#' @param scale numeric vector. CF defStormsList function
#' @param removeUnder numeric. Whether or not to remove storms under this level.
#' Default value is set to NULL
#'
#' @return indices of storms in the database, that match the filter inputs
retrieveStorms <- function(database, filterNames, filterSeasons, scale, removeUnder) {
if (length(filterSeasons) == 1) {
#We are interested in only one cyclonic season
indices <- which(database$seasons == filterSeasons)
} else {
#We are interested in successive cyclonic seasons
indices <- seq(from = which(database$seasons == filterSeasons[1])[1],
to = max(which(database$seasons == filterSeasons[2])))
}
if (!is.null(filterNames)) {
#We are interested in one or several storms given by their name (and season)
ind <- c()
for (n in 1:seq_along(filterNames)) {
id <- NULL
id <- which(database$names == filterNames[n])
stopifnot("Storm not found, invalid name ?" = !is.null(id))
ind <- c(ind, id)
}
indices <- intersect(indices, ind)
stopifnot("No storm(s) found " = !is.null(indices))
}
#Removing NOT_NAMED storms
indices <- indices[which(database$names[indices] != "NOT_NAMED")]
# Filter Storms if removeUnder is not NULL
if (!is.null(removeUnder)) {
suppressWarnings({
suppressWarnings(i <- which(apply(array(database$msw[, indices],
dim = c(dim(database$msw)[1], length(indices))),
2, max, na.rm = TRUE) >= scale[removeUnder]))
indices <- indices[i]
})
}
return(indices)
}
#' Get the level in the scale associated with a msw
#'
#' @noRd
#' @param msw numeric maximum sustained wind
#' @param scale list of values that defines the scale
#' intensity of the storm, e.g. `sshs`
#'
#' @return numeric, scale
computeScaleIndice <- function(msw, scale) {
if (is.na(msw)) {
res <- NA
} else {
res <- findInterval(msw, scale)
}
return(res)
}
#' Write data to initialize a `storm` object
#'
#' Whether or not to add a storm (with id index in database) in the upcoming
#' storms object
#'
#' @noRd
#' @param stormList list of `storm` object. To further integrate in a
#' `stormsList` object
#' @param stormNames list of storm names. To further integrate in a
#' `stormsList` object
#' @param sds stormsDataset object. sds input from storms
#' @param index numeric, index of the storm in the database
#' @param loiSfBuffer sf object. Location of interest extended with buffer
#' @param scale numeric vector. Thresholds for the scale used
#' @return a list with 2 slots:
#' \itemize{
#' \item list of storm objects
#' \item list of character (names of storms)
#' }
writeStorm <- function(stormList, stormNames, sds, index, loiSfBuffer, scale) {
#Getting lon/lat coordinates
lon <- sds@database$longitude[, index]
lat <- sds@database$latitude[, index]
coords <- data.frame(lon = lon, lat = lat)
#Keep only non NA data (that are either the first or last observations)
validIndices <- which(!is.na(coords$lon))
coords <- coords[validIndices, ]
#Removing invalid iso_time
isotime <- sds@database$isotimes[validIndices, index]
listIsotime <- as.numeric(stringr::str_sub(isotime, 12, 13))
# database should not contain irregular isotimes
validTimeStep <- listIsotime[2] - listIsotime[1]
#Keep only valid iso times
indIsotime <- which(listIsotime %% validTimeStep == 0)
coords <- coords[indIsotime, ]
if (dim(coords)[1] == 0) {
#ERROR
return(list(NULL, NULL, NULL, NULL, NULL))
}
row.names(coords) <- seq(1, dim(coords)[1])
#Creating sf point coordinates to intersect with loiSfBuffer
pts <- sf::st_as_sf(coords, coords = c("lon", "lat"))
sf::st_crs(pts) <- wgs84
#Intersect points coordinates with loiSfBuffer
ind <- which(sf::st_intersects(pts, loiSfBuffer, sparse = FALSE) == TRUE)
#Add TC only if it intersects with loiSfBuffer
if (length(ind) > 0) {
storm <- storm()
storm@name <- sds@database$names[index]
storm@season <- sds@database$seasons[index]
storm@obs.all <- data.frame(iso.time = isotime,
lon = lon[validIndices],
lat = lat[validIndices],
msw = zoo::na.approx(round(sds@database$msw[validIndices, index]),
na.rm = FALSE, rule = 2))
# scale is calculated using the scale input and the wind speed data
storm@obs.all$scale <- unlist(lapply(X = storm@obs.all$msw, FUN = computeScaleIndice, scale = scale))
if ("rmw" %in% names(sds@fields))
storm@obs.all$rmw <- zoo::na.approx(round(sds@database$rmw[validIndices, index]), na.rm = FALSE, rule = 2)
if ("pressure" %in% names(sds@fields))
storm@obs.all$pres <- zoo::na.approx(sds@database$pres[validIndices, index], na.rm = FALSE, rule = 2)
if ("poci" %in% names(sds@fields))
storm@obs.all$poci <- zoo::na.approx(sds@database$poci[validIndices, index], na.rm = FALSE, rule = 2)
#Wrapping longitudes from -180/180 to 0/360
lg <- which(storm@obs.all$lon < 0)
storm@obs.all$lon[lg] <- storm@obs.all$lon[lg] + 360
#Removing invalid isotime from obs.all
storm@obs.all <- storm@obs.all[indIsotime, ]
row.names(storm@obs.all) <- seq(1, dim(storm@obs.all)[1])
storm@obs <- ind
storm@scale <- max(storm@obs.all$scale, na.rm = TRUE)
return(list(append(stormList, storm),
append(stormNames, storm@name)))
}else {
return(list(NULL, NULL))
}
}
#' Creating a `stormsList` object
#'
#' The `defStormsList()` function extracts storm track data from a `stormsDataset`
#' and creates a `stormsList` object based on specified arguments relating to location of interest,
#' seasons, and names of the storms.
#'
#' @param sds `stormsDataset` object.
#' @param loi Location of interest. Can be defined using,
#' \itemize{
#' \item character, a country name (e.g., "Vanuatu")
#' \item character, a basin name among "NA", "SA", "EP", "WP", "SP", "SI" and "NI"
#' \item numeric vector, a point coordinate (lon, lat in decimal degrees, e.g., c(169.5, -19.2))
#' \item sp (SpatialPolygon) or a sf (simple features) object (e.g., created from a shapefile)
#' }
#' @param seasons numeric vector. Seasons of occurrence of the storms (e.g., c(2020,2022)).
#' In the Southern Hemisphere, the cyclone season extends across two consecutive years.
#' Therefore, to capture the 2021 to 2022 cyclone season both years should be specified,
#' with cyclones assigned for the year that originated in. By default all storms from `sds` are extracted.
#' @param names character vector. Names of specific storms (in capital letters).
#' @param maxDist numeric. Maximum distance between the location of interest and the
#' storm for which track data are extracted. Default `maxDist` is set to 300 km.
#' @param scale numeric. List of storm scale thresholds used for the database.
#' Default value is set to the Saffir Simpson Hurricane Scale
#' @param scalePalette character. Named vector containing the color hex code
#' corresponding to each category interval of `scale` input
#' @param removeUnder numeric. Storms reaching this maximum level or less in the scale are removed.
#' Default value is set to NULL.
#' @param verbose numeric. Type of information the function displays. Can be:
#' \itemize{
#' \item `2`, information about both the processes and the outputs are displayed (default value),
#' \item `1`, only information about the processes are displayed, or