-
Notifications
You must be signed in to change notification settings - Fork 4
/
spatialBehaviour.R
1468 lines (1200 loc) · 49.1 KB
/
spatialBehaviour.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
##########
# MODELS #
##########
#' Compute the Radius of Maximum Wind
#'
#' It is an empirical formula extracted from Willoughby et al. 2006 model
#' @noRd
#' @param msw numeric. Maximum Sustained Wind (m/s)
#' @param lat numeric. Should be between -90 and 90. Latitude of the eye of the
#' storm
#'
#' @returns Radius of Maximum Wind (km)
getRmw <- function(msw, lat) {
return(round(46.4 * exp(-0.0155 * msw + 0.0169 * abs(lat))))
}
#' Willoughby et al. (2006) model
#'
#' Compute tangential wind speed according to Willoughby et al. (2006) model
#'
#' @noRd
#' @param r numeric. Distance to the eye of the storm (km) where the value must
#' be computed
#' @param rmw numeric. Radius of Maximum Wind (km)
#' @param msw numeric. Maximum Sustained Wind (m/s)
#' @param lat numeric. Should be between -60 and 60. Latitude of the eye of the
#' storm
#'
#' @returns tangential wind speed value (m/s) according to Willoughby model at
#' distance `r` to the eye of the storm located in latitude `lat`
willoughby <- function(r, rmw, msw, lat) {
x1 <- 287.6 - 1.942 * msw + 7.799 * log(rmw) + 1.819 * abs(lat)
x2 <- 25
a <- 0.5913 + 0.0029 * msw - 0.1361 * log(rmw) - 0.0042 * abs(lat)
n <- 2.1340 + 0.0077 * msw - 0.4522 * log(rmw) - 0.0038 * abs(lat)
vr <- r
vr[r >= rmw] <- msw * ((1 - a) * exp(-abs((r[r >= rmw] - rmw) / x1)) + a * exp(-abs(r[r >= rmw] - rmw) / x2))
vr[r < rmw] <- msw * abs((r[r < rmw] / rmw)^n)
return(round(vr, 3))
}
#' Holland (1980) model
#'
#' Compute tangential wind speed according to Holland (1980) model
#'
#' @noRd
#' @param r numeric. Distance to the eye of the storm (km) where the value must
#' be computed
#' @param rmw numeric. Radius of Maximum Wind (km)
#' @param msw numeric. Maximum Sustained Wind (m/s)
#' @param pc numeric. Pressure at the center of the storm (hPa)
#' @param poci Pressure at the Outermost Closed Isobar (hPa)
#' @param lat numeric. Should be between -90 and 90. Latitude of the eye of the
#' storm
#' @returns tangential wind speed value (m/s) according to Holland 80 model at
#' distance `r` to the eye of the storm located in latitude `lat`
holland <- function(r, rmw, msw, pc, poci, lat) {
rho <- 1.15 # air densiy
f <- 2 * 7.29 * 10**(-5) * sin(lat) # Coriolis parameter
b <- rho * exp(1) * msw**2 / (poci - pc)
vr <- r
vr <- sqrt(b / rho * (rmw / r)**b * (poci - pc) * exp(-(rmw / r)**b) + (r * f / 2)**2) - r * f / 2
return(round(vr, 3))
}
#' Boose et al. (2004) model
#'
#' Compute tangential wind speed according to Boose et al. (2004) model
#'
#' @noRd
#' @param r numeric. Distance to the eye of the storm (km) where the value must
#' be computed
#' @param rmw numeric. Radius of Maximum Wind (km)
#' @param msw numeric. Maximum Sustained Wind (m/s)
#' @param pc numeric. Pressure at the center of the storm (hPa)
#' @param poci Pressure at the Outermost Closed Isobar (hPa)
#' @param x numeric vector. Distance(s) to the eye of the storm in the x
#' direction (deg)
#' @param y numeric vector. Distance(s) to the eye of the storm in the y
#' direction (deg)
#' @param vx numeric. Velocity of the storm in the x direction (deg/h)
#' @param vy numeric. Velociy of the storm in the y direction (deg/h)
#' @param vh numeric. Velociy of the storm (m/s)
#' @param landIntersect numeric array. 1 if coordinates intersect with land, 0 otherwise
#' @param lat numeric. Should be between -90 and 90. Latitude of the eye of the
#' storm
#'
#' @returns tangential wind speed value (m/s) according to Boose04 model at distance
#' `r` to the eye of the storm located in latitude
boose <- function(r, rmw, msw, pc, poci, x, y, vx, vy, vh, landIntersect, lat) {
rho <- 1 # air densiy
b <- rho * exp(1) * msw**2 / (poci - pc)
vr <- r
vr <- sqrt((rmw / r)**b * exp(1 - (rmw / r)**b))
if (lat >= 0) {
# Northern Hemisphere, t is clockwise
angle <- atan2(vy, vx) - atan2(y, x)
} else {
# Southern Hemisphere, t is counterclockwise
angle <- atan2(y, x) - atan2(vy, vx)
}
vr[landIntersect == 1] <- 0.8 * (msw - (1 - sin(angle[landIntersect == 1])) * vh / 2) * vr[landIntersect == 1]
vr[landIntersect == 0] <- (msw - (1 - sin(angle[landIntersect == 0])) * vh / 2) * vr[landIntersect == 0]
return(round(vr, 3))
}
########################
# Helper to check inputs#
########################
#' Check inputs for spatialBehaviour function
#'
#' @noRd
#' @param sts StormsList object
#' @param product character
#' @param windThreshold numeric
#' @param method character
#' @param asymmetry character
#' @param empiricalRMW logical
#' @param spaceRes character
#' @param tempRes numeric
#' @param verbose numeric
#' @return NULL
checkInputsSpatialBehaviour <- function(sts, product, windThreshold, method, asymmetry,
empiricalRMW, spaceRes, tempRes, verbose) {
# Checking sts input
stopifnot("no data found" = !missing(sts))
# Checking product input
stopifnot("Invalid product" = product %in% c("MSW", "PDI", "Exposure", "Profiles"))
# Checking windThreshold input
if ("Exposure" %in% product) {
stopifnot("windThreshold must be numeric" = identical(class(windThreshold), "numeric"))
stopifnot("invalid value(s) for windThreshold input (must be > 0)" = windThreshold > 0)
}
# Checking method input
stopifnot("Invalid method input" = method %in% c("Willoughby", "Holland", "Boose"))
stopifnot("Only one method must be chosen" = length(method) == 1)
if (method == "Holland") {
stopifnot("Cannot perform Holland method (missing pressure input)" = "pres" %in% colnames(sts@data[[1]]@obs.all))
stopifnot("Cannot perform Holland method (missing poci input)" = "poci" %in% colnames(sts@data[[1]]@obs.all))
}
# Checking asymmetry input
stopifnot("Invalid asymmetry input" = asymmetry %in% c("None", "Chen", "Miyazaki"))
stopifnot("Only one asymmetry must be chosen" = length(asymmetry) == 1)
# Checking empiricalRMW input
stopifnot("empiricalRMW must be logical" = identical(class(empiricalRMW), "logical"))
# Checking spaceRes input
stopifnot("spaceRes must be character" = identical(class(spaceRes), "character"))
stopifnot("spaceRes must be length 1" = length(spaceRes) == 1)
stopifnot(
"invalid spaceRes: must be either 30s, 2.5min, 5min or 10min" =
spaceRes %in% c("30sec", "2.5min", "5min", "10min")
)
# Checking tempRes input
stopifnot("tempRes must be numeric" = identical(class(tempRes), "numeric"))
stopifnot("tempRes must be length 1" = length(tempRes) == 1)
stopifnot("invalid tempRes: must be either 60, 30 or 15" = tempRes %in% c(60, 30, 15))
# 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))
}
#################################
# Helpers to make template rasters#
#################################
#' Generate raster template for the computations
#'
#' @noRd
#' @param buffer sf object. LOI + buffer extention
#' @param res numeric. Space resolution min for the template
#'
#' @return a SpatRaster
makeTemplateRaster <- function(buffer, res) {
# Deriving the raster template
ext <- terra::ext(
sf::st_bbox(buffer)$xmin,
sf::st_bbox(buffer)$xmax,
sf::st_bbox(buffer)$ymin,
sf::st_bbox(buffer)$ymax
)
template <- terra::rast(
xmin = ext$xmin,
xmax = ext$xmax,
ymin = ext$ymin,
ymax = ext$ymax,
resolution = res,
vals = NA,
)
terra::origin(template) <- c(0, 0)
return(template)
}
#' Generate raster template to compute wind speed according to the different
#' models
#'
#' @noRd
#' @param rasterTemplate SpatRaster. Raster generated with makeTemplateRaster
#' function
#' @param buffer numeric. Buffer size in degree
#' @param data data.frame. Data generated with getInterpolatedData function
#' @param index numeric. Index of interpolated observation in data to use to
#' generate raster
#'
#' @return SpatRaster
makeTemplateModel <- function(rasterTemplate, buffer, data, index) {
template <- terra::rast(
xmin = data$lon[index] - buffer,
xmax = data$lon[index] + buffer,
ymin = data$lat[index] - buffer,
ymax = data$lat[index] + buffer,
resolution = terra::res(rasterTemplate),
vals = NA,
time = as.POSIXct(data$isoTimes[index])
)
terra::origin(template) <- c(0, 0)
return(template)
}
###############################
# Helpers to get the right data#
###############################
#' Get indices for computations
#'
#' Whether to get only observations inside LOI + buffer extention (+ offset) or
#' getting all the observations
#'
#' @noRd
#' @param st Storm Object
#' @param offset numeric. Offset to apply at the begining and at the end
#' @param product character. product input from spatialBehaviour
#'
#' @return numeric vector gathering the indices of observation to use to perform
#' the further computations
getIndices <- function(st, offset, product) {
# Use observations within the loi for the computations
ind <- seq(st@obs[1], st@obs[length(st@obs)], 1)
if ("MSW" %in% product || "PDI" %in% product || "Exposure" %in% product) {
# Handling indices and offset (outside of loi at entry and exit)
for (o in 1:offset) {
ind <- c(st@obs[1] - o, ind)
ind <- c(ind, st@obs[length(st@obs)] + o)
}
# Remove negative values and values beyond the number of observations
ind <- ind[ind > 0 & ind <= getNbObs(st)]
}
return(ind)
}
#' Get data associated with one storm to perform further computations
#'
#' @noRd
#' @param st Storm object
#' @param indices numeric vector extracted from getIndices
#' @param tempRes numeric. time step for interpolated data, in minutes
#' @param empiricalRMW logical. Whether to use rmw from the data or to compute
#' them according to getRmw function
#' @param method character. method input from spatialBehaviour
#'
#' @return a data.frame of dimension length(indices) : 9. Columns are
#' \itemize{
#' \item lon: numeric. Longitude coordinates (degree)
#' \item lat: numeric. Latitude coordinates (degree)
#' \item msw: numeric. Maximum Sustained Wind (m/s)
#' \item rmw: numeric. Radius of Maximum Wind (km)
#' \item pc: numeric. Pressure at the center of the storm (mb)
#' \item poci: numeric. Pressure of Outermost Closed Isobar (mb)
#' \item stormSpeed: numeric. Velocity of the storm (m/s)
#' \item vxDeg: numeric. Velocity of the speed in the x direction (deg/h)
#' \item vyDeg: numeric Velocity of the speed in the y direction (deg/h)
#' }
getDataInterpolate <- function(st, indices, tempRes, empiricalRMW, method) {
# Nb of observations of storm and time associated
lenIndices <- length(indices)
timeObs <- st@obs.all$iso.time[indices]
# If data has irregular temporal resolution, we have to find the gcd of the time series
timeStepData <- as.numeric(difftime(timeObs[2:lenIndices],
timeObs[1:lenIndices - 1],
units = "mins"))
gcd2 <- function(a, b) {
if (b == 0) a else Recall(b, a %% b)
}
gcd <- function(...) Reduce(gcd2, c(...))
timeStepDataGCD <- gcd(timeStepData)
# Determine temporal interpolation time step
interpolatedRes <- min(timeStepDataGCD, tempRes)
# Get the total time of the storm (in mins)
timeInit <- timeObs[1]
timeEnd <- timeObs[lenIndices]
timeDiffObs <- as.numeric(difftime(timeEnd,
timeInit,
units = "mins"))
# Deal with length and time of interpolated data
lenInterpolated <- as.integer(timeDiffObs / interpolatedRes) + 1
timeInterpolated <- format(seq.POSIXt(as.POSIXct(timeInit),
as.POSIXct(timeEnd),
by = paste0(interpolatedRes, " min")),
"%Y-%m-%d %H:%M:%S")
indicesObsInterpolated <- match(timeObs, timeInterpolated)
if (interpolatedRes == tempRes) {
# Case where interpolation is done at the frequency requested by the user
timeData <- timeInterpolated
indicesFinal <- seq(1, lenInterpolated)
} else {
# Case where interpolation time is smaller than requested by user
# (if the dataset has really short observation intervals,
# usualy when irregular observations).
timeData <- format(seq.POSIXt(as.POSIXct(timeInit),
as.POSIXct(timeEnd),
by = paste0(tempRes, " min")),
"%Y-%m-%d %H:%M:%S")
indicesFinal <- match(timeData, timeInterpolated)
}
# Initiate the final data.frame
data <- data.frame(
lon = rep(NA, lenInterpolated),
lat = rep(NA, lenInterpolated),
stormSpeed = rep(NA, lenInterpolated),
vxDeg = rep(NA, lenInterpolated),
vyDeg = rep(NA, lenInterpolated),
msw = rep(NA, lenInterpolated),
rmw = rep(NA, lenInterpolated),
indices = rep(NA, lenInterpolated),
isoTimes = rep(NA, lenInterpolated)
)
# Filling indices and isoTimes
ind <- c()
for (i in seq(1, lenInterpolated)) {
timeIntervals <- as.numeric(difftime(timeObs,
timeInterpolated[i],
units = "mins"))
# Case of interpolation time equal to observation time
indObs <- which(timeIntervals > 0)[1]
ind <- c(ind,
formatC(indices[[1]] - 1 + indObs - timeIntervals[indObs] / (timeIntervals[indObs] - timeIntervals[indObs - 1]),
digits = 2,
format = "f")
)
}
# When interpolation time matches observation time, we keep "integer" indices
ind <- gsub(".00", "", ind)
data$indices <- ind
data$isoTimes <- timeInterpolated
# Get lon & lat
lon <- st@obs.all$lon[indices]
lat <- st@obs.all$lat[indices]
stormSpeed <- rep(NA, lenIndices)
vxDeg <- rep(NA, lenIndices)
vyDeg <- rep(NA, lenIndices)
# Computing storm velocity (m/s)
for (i in 1:(lenIndices - 1)) {
stormSpeed[i] <- terra::distance(
x = cbind(lon[i], lat[i]),
y = cbind(lon[i + 1], lat[i + 1]),
lonlat = TRUE
) * (0.001 / 3) / 3.6
# component wise velocity in both x and y direction (degree/h)
vxDeg[i] <- (lon[i + 1] - lon[i]) / 3
vyDeg[i] <- (lat[i + 1] - lat[i]) / 3
}
# Prepare all fields
data$msw[indicesObsInterpolated] <- st@obs.all$msw[indices]
data$lon[indicesObsInterpolated] <- lon
data$lat[indicesObsInterpolated] <- lat
data$stormSpeed[indicesObsInterpolated] <- stormSpeed
data$vxDeg[indicesObsInterpolated] <- vxDeg
data$vyDeg[indicesObsInterpolated] <- vyDeg
if (empiricalRMW) {
data$rmw[indicesObsInterpolated] <- getRmw(data$msw[indicesObsInterpolated], lat)
} else {
if (!("rmw" %in% colnames(st@obs.all)) || (all(is.na(st@obs.all$rmw[indices])))) {
warning("Missing rmw data to perform model. empiricalRMW set to TRUE")
data$rmw[indicesObsInterpolated] <- getRmw(data$msw[indicesObsInterpolated], lat)
} else {
##interpolatedRMW[indicesObsInterpolated] <- st@obs.all$rmw[indices]
data$rmw[indicesObsInterpolated] <- st@obs.all$rmw[indices]
}
}
# Interpolate data
data$lon <- zoo::na.approx(data$lon)
data$lat <- zoo::na.approx(data$lat)
data$msw <- zoo::na.approx(data$msw, rule = 2)
data$rmw <- zoo::na.approx(data$rmw, rule = 2)
# For velocities, we use na.locf instead of linear interpolation
data$stormSpeed <- zoo::na.locf(data$stormSpeed)
data$vxDeg <- zoo::na.locf(data$vxDeg)
data$vyDeg <- zoo::na.locf(data$vyDeg)
if (method == "Holland" || method == "Boose") {
if (all(is.na(st@obs.all$poci[indices])) || all(is.na(st@obs.all$pres[indices]))) {
stop("Missing pressure data to perform Holland model")
}
data$poci <- rep(NA, lenInterpolated)
data$pc <- rep(NA, lenInterpolated)
data$poci[indicesObsInterpolated] <- st@obs.all$poci[indices]
data$pc[indicesObsInterpolated] <- st@obs.all$pres[indices]
# Interpolate data
data$poci <- zoo::na.approx(data$poci)
data$pc <- zoo::na.approx(data$pc)
}
return(data[indicesFinal, ])
}
##############################################
# Helpers to handle Models/Asymmetry/Direction#
##############################################
#' Compute wind profile according to the selected method and asymmetry
#'
#' @noRd
#' @param data data.frame. Data generated with getInterpolatedData function
#' @param index numeric. Index of interpolated observation in data to use for
#' the computations
#' @param method character. method input form stormBehaviour_sp
#' @param asymmetry character. Asymmetry input form stormBehaviour
#' @param x numeric vector. Distance(s) to the eye of the storm in the x
#' direction (deg)
#' @param y numeric vector. Distance(s) to the eye of the storm in the y
#' direction (deg)
#' @param crds numeric array (1 column lon, 1 column lat). coordinates of raster
#' @param distEye numeric array. Distance in meter from the eye of the storm for
#' each coordinate of the rasterTemplate_model
#' @param buffer numeric. Buffer size (in degree) for the storm
#' @param loi sf. loi to intersect for Boose model
#' @param world sf. world for Boose model
#' @param indCountries numeric vector. Indices of countries to intersect for
#' Boose model
#'
#' @return numeric vector. Wind speed values (m/s)
computeWindProfile <- function(data, index, method, asymmetry, x, y, crds, distEye, buffer, loi, world, indCountries) {
# Computing wind speed according to the input model
if (method == "Willoughby") {
wind <- willoughby(
msw = data$msw[index],
lat = data$lat[index],
r = distEye * 0.001,
rmw = data$rmw[index]
)
} else if (method == "Holland") {
wind <- holland(
r = distEye * 0.001,
rmw = data$rmw[index],
msw = data$msw[index],
pc = data$pc[index],
poci = data$poci[index],
lat = data$lat[index]
)
} else if (method == "Boose") {
# Intersect points coordinates with land
pts <- sf::st_as_sf(as.data.frame(crds), coords = c("x", "y"))
sf::st_crs(pts) <- wgs84
landIntersect <- rep(0, length(x))
for (i in indCountries) {
ind <- which(sf::st_intersects(pts, world$geometry[i], sparse = FALSE) == TRUE)
landIntersect[ind] <- 1
}
wind <- boose(
r = distEye * 0.001,
rmw = data$rmw[index],
msw = data$msw[index],
pc = data$pc[index],
poci = data$poci[index],
x = x,
y = y,
vx = data$vxDeg[index],
vy = data$vyDeg[index],
vh = data$stormSpeed[index],
landIntersect = landIntersect,
lat = data$lat[index]
)
direction <- computeDirectionBoose(x, y, data$lat[index], landIntersect)
}
# Compute wind direction
if (method != "Boose") {
direction <- computeDirection(x, y, data$lat[index])
}
# Adding asymmetry
if (asymmetry != "None") {
output <- computeAsymmetry(
asymmetry, wind, x, y,
data$vxDeg[index], data$vyDeg[index],
data$stormSpeed[index],
distEye * 0.001, data$rmw[index], data$lat[index]
)
} else {
output <- list(wind = round(wind, 3), direction = round(direction, 3))
}
# Remove cells outside of buffer
dist <- sqrt(x * x + y * y)
output$wind[dist > buffer] <- NA
output$direction[dist > buffer] <- NA
return(output)
}
#' Compute asymmetry
#'
#' @noRd
#' @param asymmetry character. Asymmetry input form stormBehaviour
#' @param wind numeric vector. Wind values
#' @param x numeric vector. Distance(s) to the eye of the storm in the x
#' direction (deg)
#' @param y numeric vector. Distance(s) to the eye of the storm in the y
#' direction (deg)
#' @param vx numeric. Velocity of the storm in the x direction (deg/h)
#' @param vy numeric. Velocity of the storm in the y direction (deg/h)
#' @param vh numeric. Velocity of the storm (m/s)
#' @param r numeric. Distance to the eye of the storm (km) where the value must
#' be computed
#' @param rmw numeric. Radius of Maximum Wind (km)
#' @param lat numeric. Should be between -90 and 90. Latitude of the eye of the
#' storm
#'
#' @return numeric vectors. Wind speed values (m/s) and wind direction (rad) at
#' each (x,y) position
computeAsymmetry <- function(asymmetry, wind, x, y, vx, vy, vh, r, rmw, lat) {
# Circular symmetrical wind
dir <- -(atan2(y, x) - pi / 2)
if (lat >= 0) {
dir <- dir - pi / 2
} else {
dir <- dir + pi / 2
}
dir[dir < 0] <- dir[dir < 0] + 2 * pi
dir[dir > 2 * pi] <- dir[dir > 360] - 2 * pi
windX <- wind * cos(dir)
windY <- wind * sin(dir)
# Moving wind
stormDir <- -(atan2(vy, vx) - pi / 2)
if (stormDir < 0) {
stormDir <- stormDir + 2 * pi
}
mWindX <- vh * cos(stormDir)
mWindY <- vh * sin(stormDir)
# Formula for asymmetry
if (asymmetry == "Chen") {
formula <- 3 * rmw**(3 / 2) * r**(3 / 2) / (rmw**3 + r**3 + rmw**(3 / 2) * r**(3 / 2))
} else if (asymmetry == "Miyazaki") {
formula <- exp(-r / 500 * pi)
}
# New total wind speed
tWindX <- windX + formula * mWindX
tWindY <- windY + formula * mWindY
wind <- sqrt(tWindX**2 + tWindY**2)
# New wind direction
direction <- atan2(tWindY, tWindX) * 180 / pi
direction[direction < 0] <- direction[direction < 0] + 360
return(list(wind = round(wind, 3), direction = round(direction, 3)))
}
#' Compute wind direction according to Boose et al. (2004) model
#' @noRd
#' @param x numeric vector. Distance(s) to the eye of the storm in the x
#' direction (deg)
#' @param y numeric vector. Distance(s) to the eye of the storm in the y
#' direction (deg)
#' @param lat numeric. Should be between -90 and 90. Latitude of the eye of the
#' storm
#' @param landIntersect numeric array. 1 if coordinates intersect with land, 0 otherwise
#'
#' @return wind directions (rad) at each (x,y) position
computeDirectionBoose <- function(x, y, lat, landIntersect) {
azimuth <- -(atan2(y, x) - pi / 2)
azimuth[azimuth < 0] <- azimuth[azimuth < 0] + 2 * pi
if (lat >= 0) {
direction <- azimuth * 180 / pi - 90
direction[landIntersect == 1] <- direction[landIntersect == 1] - 40
direction[landIntersect == 0] <- direction[landIntersect == 0] - 20
} else {
direction <- azimuth * 180 / pi + 90
direction[landIntersect == 1] <- direction[landIntersect == 1] + 40
direction[landIntersect == 0] <- direction[landIntersect == 0] + 20
}
direction[direction < 0] <- direction[direction < 0] + 360
direction[direction > 360] <- direction[direction > 360] - 360
return(direction)
}
#' Compute symetrical wind direction
#' @noRd
#' @param x numeric vector. Distance(s) to the eye of the storm in the x
#' direction (deg)
#' @param y numeric vector. Distance(s) to the eye of the storm in the y
#' direction (deg)
#' @param lat numeric. Should be between -90 and 90. Latitude of the eye of the
#' storm
#'
#' @return wind directions (rad) at each (x,y) position
computeDirection <- function(x, y, lat) {
azimuth <- -(atan2(y, x) - pi / 2)
azimuth[azimuth < 0] <- azimuth[azimuth < 0] + 2 * pi
if (lat >= 0) {
direction <- azimuth * 180 / pi - 90
} else {
direction <- azimuth * 180 / pi + 90
}
direction[direction < 0] <- direction[direction < 0] + 360
direction[direction > 360] <- direction[direction > 360] - 360
return(direction)
}
###########################
# Helpers to stack products#
###########################
#' Stack a computed layer in a raster stack
#'
#' @noRd
#' @param stack list of SpatRaster. where to stack the layer
#' @param rasterTemplate SpatRaster. Raster template generated with
#' makeTemplateRaster function
#' @param rasterWind SpatRaster. Layer to add to the stack
#'
#' @return list of SpatRaster
stackRaster <- function(stack, rasterTemplate, rasterWind) {
ras <- rasterTemplate
extent <- terra::ext(ras)
ras <- terra::merge(rasterWind, ras)
ras <- terra::crop(ras, extent)
return(c(stack, ras))
}
#' Stack a computed PDI layer in a PDI raster stack
#'
#' @noRd
#' @param stack list of SpatRaster. where to stack the layer
#' @param rasterTemplate SpatRaster. Raster template generated with
#' makeTemplateRaster function
#' @param rasterWind SpatRaster. Layer to add to the stack
#'
#' @return list of SpatRaster
stackRasterPDI <- function(stack, rasterTemplate, rasterWind) {
rho <- 1
cd <- 0.002
# Raising to power 3
rasterWind <- rasterWind**3
# Applying both rho and surface drag coefficient
rasterWind <- rasterWind * rho * cd
return(stackRaster(stack, rasterTemplate, rasterWind))
}
#' Stack a computed Exposure layer in a Exposure raster stack
#'
#' @noRd
#' @param stack list of SpatRaster. where to stack the layer
#' @param rasterTemplate SpatRaster. Raster template generated with
#' makeTemplateRaster function
#' @param rasterWind SpatRaster. Layer to add to the stack
#' @param threshold numeric. Wind threshold
#'
#' @return list of SpatRaster
stackRasterExposure <- function(stack, rasterTemplate, rasterWind, threshold) {
for (t in threshold) {
rasterCModel <- rasterWind
terra::values(rasterCModel) <- NA
ind <- which(terra::values(rasterWind) >= t)
rasterCModel[ind] <- 1
stack <- stackRaster(stack, rasterTemplate, rasterCModel)
}
return(stack)
}
#' Select the stack function to use depending on the product
#'
#' @noRd
#' @param product character. Product input from spatialBehaviour
#' @param stack list of SpatRaster. where to stack the layer
#' @param rasterTemplate SpatRaster. Raster template generated with
#' makeTemplateRaster function
#' @param rasterWind SpatRaster. Layer to add to the stack
#' @param threshold numeric vector. Wind threshold
#'
#' @return list of SpatRaster
stackProduct <- function(product, stack, rasterTemplate, rasterWind, threshold) {
if (product == "MSW") {
stack <- stackRaster(stack, rasterTemplate, rasterWind)
} else if (product == "PDI") {
stack <- stackRasterPDI(stack, rasterTemplate, rasterWind)
} else if (product == "Exposure") {
stack <- stackRasterExposure(stack, rasterTemplate, rasterWind, threshold)
}
return(stack)
}
#' Compute MSW raster
#'
#' @noRd
#' @param finalStack list of SpatRaster. Where to add the computed MSW raster
#' @param stack SpatRaster stack. All the wind speed rasters used to compute MSW
#' @param name character. Name of the storm. Used to give the correct layer name
#' in finalStack
#' @param spaceRes character. spaceRes input from spatialBehaviour
#'
#' @return list of SpatRaster
rasterizeMSW <- function(finalStack, stack, spaceRes, name) {
nbg <- switch(spaceRes,
"30sec" = 59,
"2.5min" = 11,
"5min" = 5,
"10min" = 3
)
msw <- max(stack, na.rm = TRUE)
# Applying focal function to smooth results
msw <- terra::focal(msw, w = matrix(1, nbg, nbg), mean, na.rm = TRUE, pad = TRUE)
names(msw) <- paste0(name, "_MSW")
return(c(finalStack, msw))
}
#' Compute PDI raster
#'
#' @noRd
#' @param finalStack list of SpatRaster. Where to add the computed MSW raster
#' @param tempRes numeric. Time resolution, used for the numerical integration
#' over the whole track
#' @param stack SpatRaster stack. All the PDI rasters used to compute MSW
#' @param name character. Name of the storm. Used to give the correct layer name
#' in finalStack
#' @param spaceRes character. spaceRes input from spatialBehaviour
#' @param threshold numeric vector. Wind threshold
#'
#'
#' @return list of SpatRaster
rasterizePDI <- function(finalStack, stack, tempRes, spaceRes, name, threshold) {
nbg <- switch(spaceRes,
"30sec" = 59,
"2.5min" = 11,
"5min" = 5,
"10min" = 3
)
# Integrating over the whole track
prod <- sum(stack, na.rm = TRUE) * tempRes
# Applying focal function to smooth results
prod <- terra::focal(prod, w = matrix(1, nbg, nbg), mean, na.rm = TRUE, pad = TRUE)
names(prod) <- paste0(name, "_PDI")
return(c(finalStack, prod))
}
#' Compute PDI raster
#'
#' @noRd
#' @param finalStack list of SpatRaster. Where to add the computed MSW raster
#' @param tempRes numeric. Time resolution, used for the numerical integration
#' over the whole track
#' @param stack SpatRaster stack. All the PDI rasters used to compute MSW
#' @param name character. Name of the storm. Used to give the correct layer name
#' in finalStack
#' @param spaceRes character. spaceRes input from spatialBehaviour
#' @param threshold numeric vector. Wind threshold
#'
#'
#' @return list of SpatRaster
rasterizeExp <- function(finalStack, stack, tempRes, spaceRes, name, threshold) {
nbg <- switch(spaceRes,
"30sec" = 59,
"2.5min" = 11,
"5min" = 5,
"10min" = 3
)
for (l in seq_along(threshold)) {
ind <- seq(l, terra::nlyr(stack), length(threshold))
# Integrating over the whole track
prod <- sum(terra::subset(stack, ind), na.rm = TRUE) * tempRes
# Applying focal function to smooth results
prod <- terra::focal(prod, w = matrix(1, nbg, nbg), mean, na.rm = TRUE)
names(prod) <- paste0(name, "_Exposure_", threshold[l])
finalStack <- c(finalStack, prod)
}
return(finalStack)
}
#' Select the rasterizeProduct function to use depending on the product
#'
#' @noRd
#' @param product character. Product input from spatialBehaviour
#' @param finalStack list of SpatRaster. Where to add the computed MSW raster
#' @param tempRes numeric. Time resolution, used for the numerical integration
#' over the whole track
#' @param stack SpatRaster stack. All the Exposure rasters used to compute MSW
#' @param name character. Name of the storm. Used to give the correct layer name
#' in finalStack
#' @param spaceRes character. spaceRes input from spatialBehaviour
#' @param threshold numeric vector. Wind threshold
#'
#' @return list of SpatRaster
rasterizeProduct <- function(product, finalStack, stack, tempRes, spaceRes, name, threshold) {
if (product == "MSW") {
# Computing MSW analytic raster
finalStack <- rasterizeMSW(finalStack, stack, spaceRes, name)
} else if (product == "PDI") {
# Computing PDI analytic raster
finalStack <- rasterizePDI(finalStack, stack, tempRes, spaceRes, name, NULL)
} else if (product == "Exposure") {
# Computing Exposure analytic raster
finalStack <- rasterizeExp(finalStack, stack, tempRes, spaceRes, name, threshold)
}
return(finalStack)
}
#' Whether or not to mask final computed products
#'
#' @noRd
#' @param finalStack SpatRaster stack. Where all final computed products are