-
Notifications
You must be signed in to change notification settings - Fork 13
/
tc_rainfield.py
1782 lines (1550 loc) · 74 KB
/
tc_rainfield.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
This file is part of CLIMADA.
Copyright (C) 2017 ETH Zurich, CLIMADA contributors listed in AUTHORS.
CLIMADA is free software: you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free
Software Foundation, version 3.
CLIMADA is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with CLIMADA. If not, see <https://www.gnu.org/licenses/>.
---
Define TC rain hazard (TCRain class).
"""
__all__ = ['TCRain']
import datetime as dt
import itertools
import logging
from pathlib import Path
from typing import Optional, Tuple, List, Union
import numpy as np
import pathos.pools
from scipy import sparse
import xarray as xr
from climada.hazard import Hazard, TCTracks, TropCyclone, Centroids
from climada.hazard.trop_cyclone import (
get_close_centroids,
compute_angular_windspeeds,
tctrack_to_si,
H_TO_S,
KM_TO_M,
KN_TO_MS,
MODEL_VANG,
)
from climada.util import ureg
from climada.util.api_client import Client
import climada.util.constants as u_const
import climada.util.coordinates as u_coord
LOGGER = logging.getLogger(__name__)
HAZ_TYPE = 'TR'
"""Hazard type acronym for TC rain"""
DEF_MAX_DIST_EYE_KM = 300
"""Default value for the maximum distance (in km) of a centroid to the TC center at which rain
rate calculations are done."""
DEF_INTENSITY_THRES = 0.1
"""Default value for the threshold below which rain amounts (in mm) are stored as 0."""
DEF_MAX_MEMORY_GB = 8
"""Default value of the memory limit (in GB) for rain computations (in each thread)."""
MODEL_RAIN = {'R-CLIPER': 0, 'TCR': 1}
"""Enumerate different parametric TC rain models."""
D_TO_H = (1.0 * ureg.days).to(ureg.hours).magnitude
IN_TO_MM = (1.0 * ureg.inches).to(ureg.millimeters).magnitude
M_TO_MM = (1.0 * ureg.meter).to(ureg.millimeter).magnitude
"""Unit conversion factors for JIT functions that can't use ureg"""
H_TROP = 4000
"""Depth (in m) of lower troposphere"""
DELTA_T_TROPOPAUSE = 100
"""Difference between surface and tropopause temperature (in K): T_s - T_t"""
T_ICE_K = 273.16
"""Freezing temperatur of water (in K), for conversion between K and °C"""
L_EVAP_WATER = 2.5e6
"""Latent heat of the evaporation of water (in J/kg)"""
M_WATER = 18.01528
"""Molar mass of water vapor (in g/mol)"""
M_DRY_AIR = 28.9634
"""Molar mass of dry air (in g/mol)"""
R_GAS = 8.3144621
"""Molar gas constant (in J/molK)"""
R_DRY_AIR = 1000 * R_GAS / M_DRY_AIR
"""Specific gas constant of dry air (in J/kgK)"""
RHO_A_OVER_RHO_L = 0.00117
"""Density of water vapor divided by density of liquid water"""
GRADIENT_LEVEL_TO_SURFACE_WINDS = 0.8
"""Gradient-to-surface wind reduction factor according to Table 2 in:
Franklin, J.L., Black, M.L., Valde, K. (2003): GPS Dropwindsonde Wind Profiles in Hurricanes and
Their Operational Implications. Weather and Forecasting 18(1): 32–44.
https://doi.org/10.1175/1520-0434(2003)018<0032:GDWPIH>2.0.CO;2
Note that we here use a value different from the one in ``climada.hazard.trop_cyclone`` because the
focus is not only on the eyewall region, but also on the outer vortex, which is a little more
important for precipitation than for wind effects.
"""
def default_elevation_tif():
"""Topography (land surface elevation, 0 over oceans) raster data at 0.1 degree resolution
SRTM data upscaled to 0.1 degree resolution using the "average" method of gdalwarp.
"""
client = Client()
dsi = client.get_dataset_info(name='topography_land_360as', status='package-data')
_, [elevation_tif] = client.download_dataset(dsi)
return elevation_tif
def default_drag_tif():
"""Gradient-level drag coefficient raster data at 0.25 degree resolution
The ERA5 'forecast_surface_roughness' (fsr) variable has been transformed into drag
coefficients (C_D) following eqs. (7) and (8) in the following work:
Feldmann et al. (2019): Estimation of Atlantic Tropical Cyclone Rainfall Frequency in the
United States. Journal of Applied Meteorology and Climatology 58(8): 1853–1866.
https://doi.org/10.1175/JAMC-D-19-0011.1
"""
client = Client()
dsi = client.get_dataset_info(name='c_drag_500', status='package-data')
_, [drag_tif] = client.download_dataset(dsi)
return drag_tif
class TCRain(Hazard):
"""
Contains rainfall from tropical cyclone events.
Attributes
----------
category : np.ndarray of ints
for every event, the TC category using the Saffir-Simpson scale:
* -1 tropical depression
* 0 tropical storm
* 1 Hurrican category 1
* 2 Hurrican category 2
* 3 Hurrican category 3
* 4 Hurrican category 4
* 5 Hurrican category 5
basin : list of str
Basin where every event starts:
* 'NA' North Atlantic
* 'EP' Eastern North Pacific
* 'WP' Western North Pacific
* 'NI' North Indian
* 'SI' South Indian
* 'SP' Southern Pacific
* 'SA' South Atlantic
rainrates : list of csr_matrix
For each event, the rain rates (in mm/h) at each centroid and track position in a sparse
matrix of shape (npositions, ncentroids).
"""
intensity_thres = DEF_INTENSITY_THRES
"""intensity threshold for storage in mm"""
vars_opt = Hazard.vars_opt.union({'category'})
"""Name of the variables that aren't needed to compute the impact."""
def __init__(
self,
category: Optional[np.ndarray] = None,
basin: Optional[List] = None,
rainrates: Optional[List[sparse.csr_matrix]] = None,
**kwargs,
):
"""Initialize values.
Parameters
----------
category : np.ndarray of int, optional
For every event, the TC category using the Saffir-Simpson scale:
-1 tropical depression
0 tropical storm
1 Hurrican category 1
2 Hurrican category 2
3 Hurrican category 3
4 Hurrican category 4
5 Hurrican category 5
basin : list of str, optional
Basin where every event starts:
'NA' North Atlantic
'EP' Eastern North Pacific
'WP' Western North Pacific
'NI' North Indian
'SI' South Indian
'SP' Southern Pacific
'SA' South Atlantic
rainrates : list of csr_matrix, optional
For each event, the rain rates (in mm/h) at each centroid and track position in a
sparse matrix of shape (npositions, ncentroids).
**kwargs : Hazard properties, optional
All other keyword arguments are passed to the Hazard constructor.
"""
kwargs.setdefault('haz_type', HAZ_TYPE)
Hazard.__init__(self, **kwargs)
self.category = category if category is not None else np.array([], int)
self.basin = basin if basin is not None else []
self.rainrates = rainrates if rainrates is not None else []
def set_from_tracks(self, *args, **kwargs):
"""This function is deprecated, use TCRain.from_tracks instead."""
LOGGER.warning("The use of TCRain.set_from_tracks is deprecated."
"Use TCRain.from_tracks instead.")
if "intensity_thres" not in kwargs:
# some users modify the threshold attribute before calling `set_from_tracks`
kwargs["intensity_thres"] = self.intensity_thres
if self.pool is not None and 'pool' not in kwargs:
kwargs['pool'] = self.pool
self.__dict__ = TCRain.from_tracks(*args, **kwargs).__dict__
@classmethod
def from_tracks(
cls,
tracks: TCTracks,
centroids: Centroids = None,
pool: Optional[pathos.pools.ProcessPool] = None,
model: str = 'R-CLIPER',
model_kwargs: Optional[dict] = None,
ignore_distance_to_coast: bool = False,
store_rainrates: bool = False,
metric: str = "equirect",
intensity_thres: float = DEF_INTENSITY_THRES,
max_latitude: float = 61,
max_dist_inland_km: float = 1000,
max_dist_eye_km: float = DEF_MAX_DIST_EYE_KM,
max_memory_gb: float = DEF_MAX_MEMORY_GB,
):
"""
Create new TCRain instance that contains rainfields from the specified tracks
This function sets the ``intensity`` attribute to contain, for each centroid,
the total amount of rain experienced over the whole period of each TC event in mm.
The amount of rain is set to 0 if it does not exceed the threshold ``intensity_thres``.
The ``category`` attribute is set to the value of the ``category``-attribute
of each of the given track data sets.
The ``basin`` attribute is set to the genesis basin for each event, which
is the first value of the ``basin``-variable in each of the given track data sets.
Optionally, the time-dependent rain rates can be stored using the ``store_rainrates``
function parameter (see below).
Currently, two models are supported to compute the rain rates: R-CLIPER and TCR. The
R-CLIPER model is documented in Tuleya et al. 2007. The TCR model was used by
Zhu et al. 2013 and Emanuel 2017 for the first time and is documented in detail in
Lu et al. 2018. This implementation of TCR includes improvements proposed in
Feldmann et al. 2019. TCR's accuracy is much higher than R-CLIPER's at the cost of
additional computational and data requirements.
When using the TCR model make sure that your TC track data includes the along-track
variables "t600" (temperature at 600 hPa) and "u850"/"v850" (wind speed at 850 hPa). Both
can be extracted from reanalysis or climate model outputs. For "t600", use the value at the
storm center. For "u850"/"v850", use the average over the 200-500 km annulus around the
storm center. If "u850"/"v850" is missing, this implementation sets the shear component of
the vertical velocity to 0. If "t600" is missing, the saturation specific humidity is set
to a universal estimate of 0.01 kg/kg. Both assumptions can have a large effect on the
results (see Lu et al. 2018).
Emanuel (2017): Assessing the present and future probability of Hurricane Harvey’s
rainfall. Proceedings of the National Academy of Sciences 114(48): 12681–12684.
https://doi.org/10.1073/pnas.1716222114
Lu et al. (2018): Assessing Hurricane Rainfall Mechanisms Using a Physics-Based Model:
Hurricanes Isabel (2003) and Irene (2011). Journal of the Atmospheric
Sciences 75(7): 2337–2358. https://doi.org/10.1175/JAS-D-17-0264.1
Feldmann et al. (2019): Estimation of Atlantic Tropical Cyclone Rainfall Frequency in the
United States. Journal of Applied Meteorology and Climatology 58(8): 1853–1866.
https://doi.org/10.1175/JAMC-D-19-0011.1
Tuleya et al. (2007): Evaluation of GFDL and Simple Statistical Model Rainfall Forecasts
for U.S. Landfalling Tropical Storms. Weather and Forecasting 22(1): 56–70.
https://doi.org/10.1175/WAF972.1
Zhu et al. (2013): Estimating tropical cyclone precipitation risk in Texas. Geophysical
Research Letters 40(23): 6225–6230. https://doi.org/10.1002/2013GL058284
Parameters
----------
tracks : climada.hazard.TCTracks
Tracks of storm events.
centroids : Centroids, optional
Centroids where to model TC. Default: centroids at 360 arc-seconds resolution within
tracks' bounds.
pool : pathos.pool, optional
Pool that will be used for parallel computation of rain fields. Default: None
model : str, optional
Parametric rain model to use: "R-CLIPER" (faster and requires less inputs, but
much less accurate, statistical approach, Tuleya et al. 2007), "TCR" (physics-based
approach, requires non-standard along-track variables, Zhu et al. 2013).
Default: "R-CLIPER".
model_kwargs: dict, optional
If given, forward these kwargs to the selected model. The implementation of the
R-CLIPER model currently does not allow modifications, so that ``model_kwargs`` is
ignored with ``model="R-CLIPER"``. While the TCR model can be configured in several ways,
it is usually safe to go with the default settings. Here is the complete list of
``model_kwargs`` and their meaning with ``model="TCR"`` (in alphabetical order):
c_drag_tif : Path or str, optional
Path to a GeoTIFF file containing gridded drag coefficients (bottom friction). If
not specified, an ERA5-based data set provided with CLIMADA is used. Default: None
e_precip : float, optional
Precipitation efficiency (unitless), the fraction of the vapor flux falling to the
surface as rainfall (Lu et al. 2018, eq. (14)). Note that we follow the MATLAB
reference implementation and use 0.5 as a default value instead of the 0.9 that was
proposed in Lu et al. 2018. Default: 0.5
elevation_tif : Path or str, optional
Path to a GeoTIFF file containing digital elevation model data (in m). If not
specified, an SRTM-based topography at 0.1 degree resolution provided with CLIMADA
is used. Default: None
matlab_ref_mode : bool, optional
This implementation is based on a (proprietary) reference implementation in MATLAB.
However, some (minor) changes have been applied in the CLIMADA implementation
compared to the reference:
* In the computation of horizontal wind speeds, we compute the Coriolis parameter
from latitude. The MATLAB code assumes a constant parameter value (5e-5).
* As a rescaling factor from surface to gradient winds, we use a factor from the
literature. The factor in MATLAB is very similar, but does not specify a
source.
* Instead of the "specific humidity", the (somewhat simpler) formula for the
"mixing ratio" is used in the MATLAB code. These quantities are almost the same
in practice.
* We use the approximation of the Clausius-Clapeyron equation used by the ECMWF
(Buck 1981) instead of the one used in the MATLAB code (Bolton 1980).
Since it might be useful to have a version that replicates the behavior of the
reference implementation, this parameter can be set to True to enforce the exact
behavior of the reference implementation. Default: False
max_w_foreground : float, optional
The maximum value (in m/s) at which to clip the vertical velocity w before
subtracting the background subsidence velocity w_rad. Default: 7.0
min_c_drag : float, optional
The drag coefficient is clipped to this minimum value (esp. over ocean).
Default: 0.001
q_950 : float, optional
If the track data does not include "t600" values, assume this constant value of
saturation specific humidity (in kg/kg) at 950 hPa. Default: 0.01
res_radial_m : float, optional
Resolution (in m) in radial direction. This is used for the computation of discrete
derivatives of the horizontal wind fields and derived quantities. Default: 2000.0
w_rad : float, optional
Background subsidence velocity (in m/s) under radiative cooling. Default: 0.005
wind_model : str, optional
Parametric wind field model to use, see the ``TropCyclone`` class. Default: "ER11".
Default: None
ignore_distance_to_coast : boolean, optional
If True, centroids far from coast are not ignored. Default: False.
store_rainrates : boolean, optional
If True, the Hazard object gets a list ``rainrates`` of sparse matrices. For each track,
the rain rates (in mm/h) at each centroid and track position are stored in a sparse
matrix of shape (npositions, ncentroids). Default: False.
metric : str, optional
Specify an approximation method to use for earth distances:
* "equirect": Distance according to sinusoidal projection. Fast, but inaccurate for
large distances and high latitudes.
* "geosphere": Exact spherical distance. Much more accurate at all distances, but slow.
Default: "equirect".
intensity_thres : float, optional
Rain amounts (in mm) below this threshold are stored as 0. Default: 0.1
max_latitude : float, optional
No rain calculation is done for centroids with latitude larger than this parameter.
Default: 61
max_dist_inland_km : float, optional
No rain calculation is done for centroids with a distance (in km) to the coast larger
than this parameter. Default: 1000
max_dist_eye_km : float, optional
No rain calculation is done for centroids with a distance (in km) to the
TC center ("eye") larger than this parameter. Default: 300
max_memory_gb : float, optional
To avoid memory issues, the computation is done for chunks of the track sequentially.
The chunk size is determined depending on the available memory (in GB). Note that this
limit applies to each thread separately if a ``pool`` is used. Default: 8
Returns
-------
TCRain
"""
num_tracks = tracks.size
if centroids is None:
centroids = Centroids.from_pnt_bounds(tracks.get_bounds(), res=0.1)
if ignore_distance_to_coast:
# Select centroids with lat <= max_latitude
[idx_centr_filter] = (np.abs(centroids.lat) <= max_latitude).nonzero()
else:
# Select centroids which are inside max_dist_inland_km and lat <= max_latitude
[idx_centr_filter] = (
(centroids.get_dist_coast() <= max_dist_inland_km * 1000)
& (np.abs(centroids.lat) <= max_latitude)
).nonzero()
# Filter early with a larger threshold, but inaccurate (lat/lon) distances.
# Later, there will be another filtering step with more accurate distances in km.
max_dist_eye_deg = max_dist_eye_km / (
u_const.ONE_LAT_KM * np.cos(np.radians(max_latitude))
)
# Restrict to coastal centroids within reach of any of the tracks
t_lon_min, t_lat_min, t_lon_max, t_lat_max = tracks.get_bounds(deg_buffer=max_dist_eye_deg)
t_mid_lon = 0.5 * (t_lon_min + t_lon_max)
filtered_centroids = centroids.coord[idx_centr_filter]
u_coord.lon_normalize(filtered_centroids[:, 1], center=t_mid_lon)
idx_centr_filter = idx_centr_filter[
(t_lon_min <= filtered_centroids[:, 1])
& (filtered_centroids[:, 1] <= t_lon_max)
& (t_lat_min <= filtered_centroids[:, 0])
& (filtered_centroids[:, 0] <= t_lat_max)
]
LOGGER.info('Mapping %s tracks to %s coastal centroids.', str(tracks.size),
str(idx_centr_filter.size))
if pool:
chunksize = max(min(num_tracks // pool.ncpus, 1000), 1)
tc_haz_list = pool.map(
cls._from_track, tracks.data,
itertools.repeat(centroids, num_tracks),
itertools.repeat(idx_centr_filter, num_tracks),
itertools.repeat(model, num_tracks),
itertools.repeat(model_kwargs, num_tracks),
itertools.repeat(store_rainrates, num_tracks),
itertools.repeat(metric, num_tracks),
itertools.repeat(intensity_thres, num_tracks),
itertools.repeat(max_dist_eye_km, num_tracks),
itertools.repeat(max_memory_gb, num_tracks),
chunksize=chunksize)
else:
last_perc = 0
tc_haz_list = []
for track in tracks.data:
perc = 100 * len(tc_haz_list) / len(tracks.data)
if perc - last_perc >= 10:
LOGGER.info("Progress: %d%%", perc)
last_perc = perc
tc_haz_list.append(
cls._from_track(track, centroids, idx_centr_filter,
model=model, model_kwargs=model_kwargs,
store_rainrates=store_rainrates,
metric=metric, intensity_thres=intensity_thres,
max_dist_eye_km=max_dist_eye_km,
max_memory_gb=max_memory_gb))
if last_perc < 100:
LOGGER.info("Progress: 100%")
LOGGER.debug('Concatenate events.')
haz = cls.concat(tc_haz_list)
haz.pool = pool
haz.intensity_thres = intensity_thres
LOGGER.debug('Compute frequency.')
TropCyclone.frequency_from_tracks(haz, tracks.data)
return haz
@classmethod
def _from_track(
cls,
track: xr.Dataset,
centroids: Centroids,
idx_centr_filter: np.ndarray,
model: str = 'R-CLIPER',
model_kwargs: Optional[dict] = None,
store_rainrates: bool = False,
metric: str = "equirect",
intensity_thres: float = DEF_INTENSITY_THRES,
max_dist_eye_km: float = DEF_MAX_DIST_EYE_KM,
max_memory_gb: float = DEF_MAX_MEMORY_GB,
):
"""
Generate a TC rain hazard object from a single track dataset
Parameters
----------
track : xr.Dataset
Single tropical cyclone track.
centroids : Centroids
Centroids instance.
idx_centr_filter : np.ndarray
Indices of centroids to restrict to (e.g. sufficiently close to coast).
model : str, optional
Parametric rain model to use: "R-CLIPER" (faster and requires less inputs, but
much less accurate, statistical approach), "TCR" (physics-based approach, requires
non-standard along-track variables). Default: "R-CLIPER".
model_kwargs: dict, optional
If given, forward these kwargs to the selected model. Default: None
store_rainrates : boolean, optional
If True, store rain rates (in mm/h). Default: False.
metric : str, optional
Specify an approximation method to use for earth distances: "equirect" (faster) or
"geosphere" (more accurate). See ``dist_approx`` function in ``climada.util.coordinates``.
Default: "equirect".
intensity_thres : float, optional
Rain amounts (in mm) below this threshold are stored as 0. Default: 0.1
max_dist_eye_km : float, optional
No rain calculation is done for centroids with a distance (in km) to the TC
center ("eye") larger than this parameter. Default: 300
max_memory_gb : float, optional
To avoid memory issues, the computation is done for chunks of the track sequentially.
The chunk size is determined depending on the available memory (in GB). Default: 8
Returns
-------
TCRain
"""
intensity_sparse, rainrates_sparse = _compute_rain_sparse(
track=track,
centroids=centroids,
idx_centr_filter=idx_centr_filter,
model=model,
model_kwargs=model_kwargs,
store_rainrates=store_rainrates,
metric=metric,
intensity_thres=intensity_thres,
max_dist_eye_km=max_dist_eye_km,
max_memory_gb=max_memory_gb,
)
new_haz = cls(haz_type=HAZ_TYPE)
new_haz.intensity_thres = intensity_thres
new_haz.intensity = intensity_sparse
if store_rainrates:
new_haz.rainrates = [rainrates_sparse]
new_haz.units = 'mm'
new_haz.centroids = centroids
new_haz.event_id = np.array([1])
new_haz.frequency = np.array([1])
new_haz.event_name = [track.sid]
new_haz.fraction = sparse.csr_matrix(new_haz.intensity.shape)
# store first day of track as date
new_haz.date = np.array([dt.datetime(
track["time"].dt.year.values[0],
track["time"].dt.month.values[0],
track["time"].dt.day.values[0]
).toordinal()])
new_haz.orig = np.array([track.orig_event_flag])
new_haz.category = np.array([track.category])
new_haz.basin = [str(track["basin"].values[0])]
return new_haz
def _compute_rain_sparse(
track: xr.Dataset,
centroids: Centroids,
idx_centr_filter: np.ndarray,
model: str = 'R-CLIPER',
model_kwargs: Optional[dict] = None,
store_rainrates: bool = False,
metric: str = "equirect",
intensity_thres: float = DEF_INTENSITY_THRES,
max_dist_eye_km: float = DEF_MAX_DIST_EYE_KM,
max_memory_gb: float = DEF_MAX_MEMORY_GB,
) -> Tuple[sparse.csr_matrix, Optional[sparse.csr_matrix]]:
"""Version of ``compute_rain`` that returns sparse matrices and limits memory usage
Parameters
----------
track : xr.Dataset
Single tropical cyclone track.
centroids : Centroids
Centroids instance.
idx_centr_filter : np.ndarray
Indices of centroids to restrict to (e.g. sufficiently close to coast).
model : str, optional
Parametric rain model to use: "R-CLIPER" (faster and requires less inputs, but
much less accurate, statistical approach), "TCR" (physics-based approach, requires
non-standard along-track variables). Default: "R-CLIPER".
model_kwargs: dict, optional
If given, forward these kwargs to the selected model. Default: None
store_rainrates : boolean, optional
If True, store rain rates. Default: False.
metric : str, optional
Specify an approximation method to use for earth distances: "equirect" (faster) or
"geosphere" (more accurate). See ``dist_approx`` function in ``climada.util.coordinates``.
Default: "equirect".
intensity_thres : float, optional
Wind speeds (in m/s) below this threshold are stored as 0. Default: 17.5
max_dist_eye_km : float, optional
No rain calculation is done for centroids with a distance (in km) to the TC
center ("eye") larger than this parameter. Default: 300
max_memory_gb : float, optional
To avoid memory issues, the computation is done for chunks of the track sequentially.
The chunk size is determined depending on the available memory (in GB). Default: 8
Raises
------
ValueError
Returns
-------
intensity : csr_matrix
Total amount of rain (in mm) in each centroid over the whole storm life time.
rainrates : csr_matrix or None
If store_rainrates is True, the rain rates at each centroid and track position
are stored in a sparse matrix of shape (npositions, ncentroids ).
If store_rainrates is False, ``None`` is returned.
"""
model_kwargs = {} if model_kwargs is None else model_kwargs
try:
mod_id = MODEL_RAIN[model]
except KeyError as err:
raise ValueError(f'Model not implemented: {model}.') from err
ncentroids = centroids.coord.shape[0]
npositions = track.sizes["time"]
rainrates_shape = (npositions, ncentroids)
intensity_shape = (1, ncentroids)
# initialise arrays for the assumption that no centroids are within reach
rainrates_sparse = (
sparse.csr_matrix(([], ([], [])), shape=rainrates_shape)
if store_rainrates else None
)
intensity_sparse = sparse.csr_matrix(([], ([], [])), shape=intensity_shape)
# The TCR model requires at least three track positions because both forward and backward
# differences in time are used.
if npositions == 0 or model == "TCR" and npositions < 3:
return intensity_sparse, rainrates_sparse
# convert track variables to SI units
si_track = _track_to_si_with_q_and_shear(track, metric=metric, **model_kwargs)
# when done properly, finding and storing the close centroids is not a memory bottle neck and
# can be done before chunking:
centroids_close, mask_centr, mask_centr_alongtrack = get_close_centroids(
si_track=si_track,
centroids=centroids.coord[idx_centr_filter],
buffer_km=max_dist_eye_km,
metric=metric,
)
idx_centr_filter = idx_centr_filter[mask_centr]
n_centr_close = centroids_close.shape[0]
if n_centr_close == 0:
return intensity_sparse, rainrates_sparse
# the total memory requirement in GB if we compute everything without chunking:
# 8 Bytes per entry (float64), 25 arrays
total_memory_gb = npositions * n_centr_close * 8 * 25 / 1e9
if total_memory_gb > max_memory_gb and npositions > 3:
# If the number of positions is down to 3 already, we do not split any further. In that
# case, we just take the risk and try to do the computation anyway. It might still work
# since we have only computed an upper bound for the number of affected centroids.
# Split the track into chunks, compute the result for each chunk, and combine:
return _compute_rain_sparse_chunked(
mask_centr_alongtrack,
track,
centroids,
idx_centr_filter,
model=model,
model_kwargs=model_kwargs,
store_rainrates=store_rainrates,
metric=metric,
intensity_thres=intensity_thres,
max_dist_eye_km=max_dist_eye_km,
max_memory_gb=max_memory_gb,
)
rainrates, idx_centr_reachable = compute_rain(
si_track,
centroids_close,
mod_id,
model_kwargs=model_kwargs,
metric=metric,
max_dist_eye_km=max_dist_eye_km,
)
idx_centr_filter = idx_centr_filter[idx_centr_reachable]
npositions = rainrates.shape[0]
# obtain total rainfall in mm by multiplying by time step size (in hours) and summing up
intensity = (rainrates * track["time_step"].values[:, None]).sum(axis=0)
intensity[intensity < intensity_thres] = 0
intensity_sparse = sparse.csr_matrix(
(intensity, idx_centr_filter, [0, intensity.size]),
shape=intensity_shape)
intensity_sparse.eliminate_zeros()
rainrates_sparse = None
if store_rainrates:
n_centr_filter = idx_centr_filter.size
indices = np.broadcast_to(idx_centr_filter[None], (npositions, n_centr_filter)).ravel()
indptr = np.arange(npositions + 1) * n_centr_filter
rainrates_sparse = sparse.csr_matrix((rainrates.ravel(), indices, indptr),
shape=rainrates_shape)
rainrates_sparse.eliminate_zeros()
return intensity_sparse, rainrates_sparse
def _compute_rain_sparse_chunked(
mask_centr_alongtrack: np.ndarray,
track: xr.Dataset,
*args,
max_memory_gb: float = DEF_MAX_MEMORY_GB,
**kwargs,
) -> Tuple[sparse.csr_matrix, Optional[sparse.csr_matrix]]:
"""Call ``_compute_rain_sparse`` for chunks of the track and re-assemble the results
Parameters
----------
mask_centr_alongtrack : np.ndarray of shape (npositions, ncentroids)
Each row is a mask that indicates the centroids within reach for one track position.
track : xr.Dataset
Single tropical cyclone track.
max_memory_gb : float, optional
Maximum memory requirements (in GB) for the computation of a single chunk of the track.
Default: 8
args, kwargs :
The remaining arguments are passed on to ``_compute_rain_sparse``.
Returns
-------
intensity, rainrates :
See ``_compute_rain_sparse`` for a description of the return values.
"""
npositions = track.sizes["time"]
# The memory requirements for each track position are estimated for the case of 25 arrays
# containing `nreachable` float64 (8 Byte) values each. The chunking is only relevant in
# extreme cases with a very high temporal and/or spatial resolution.
max_nreachable = max_memory_gb * 1e9 / (8 * 25 * npositions)
split_pos = [0]
chunk_size = 3
while split_pos[-1] + chunk_size < npositions:
chunk_size += 1
# create overlap between consecutive chunks
chunk_start = max(0, split_pos[-1] - 2)
chunk_end = chunk_start + chunk_size
nreachable = mask_centr_alongtrack[chunk_start:chunk_end].any(axis=0).sum()
if nreachable > max_nreachable:
split_pos.append(chunk_end - 1)
chunk_size = 3
split_pos.append(npositions)
intensity = []
rainrates = []
for prev_chunk_end, chunk_end in zip(split_pos[:-1], split_pos[1:]):
chunk_start = max(0, prev_chunk_end - 2)
inten, rainr = _compute_rain_sparse(
track.isel(time=slice(chunk_start, chunk_end)), *args,
max_memory_gb=max_memory_gb, **kwargs,
)
intensity.append(inten)
rainrates.append(rainr)
intensity = sparse.csr_matrix(sparse.vstack(intensity).max(axis=0))
if rainrates[0] is not None:
# eliminate the overlap between consecutive chunks
rainrates = (
[rainrates[0][:-1, :]]
+ [rainr[1:-1, :] for rainr in rainrates[1:-1]]
+ [rainrates[-1][1:, :]]
)
rainrates = sparse.vstack(rainrates, format="csr")
return intensity, rainrates
def compute_rain(
si_track: xr.Dataset,
centroids: np.ndarray,
model: int,
model_kwargs: Optional[dict] = None,
metric: str = "equirect",
max_dist_eye_km: float = DEF_MAX_DIST_EYE_KM,
) -> Tuple[np.ndarray, np.ndarray]:
"""Compute rain rate (in mm/h) of the tropical cyclone
In a first step, centroids within reach of the track are determined so that rain rates will
only be computed and returned for those centroids. Still, since computing the distance of
the storm center to the centroids is computationally expensive, make sure to pre-filter the
centroids and call this function only for those centroids that are potentially affected.
Parameters
----------
si_track : xr.Dataset
Output of ``tctrack_to_si``. Which data variables are used in the computation of the rain
rates depends on the selected model.
centroids : np.ndarray with two dimensions
Each row is a centroid [lat, lon]. Centroids that are not within reach of the track are
ignored. Longitudinal coordinates are assumed to be normalized consistently with the
longitudinal coordinates in ``si_track``.
model : int
TC rain model selection according to MODEL_RAIN.
model_kwargs: dict, optional
If given, forward these kwargs to the selected model. Default: None
metric : str, optional
Specify an approximation method to use for earth distances: "equirect" (faster) or
"geosphere" (more accurate). See ``dist_approx`` function in ``climada.util.coordinates``.
Default: "equirect".
max_dist_eye_km : float, optional
No rain calculation is done for centroids with a distance (in km) to the TC center
("eye") larger than this parameter. Default: 300
Returns
-------
rainrates : np.ndarray of shape (npositions, nreachable)
Rain rates for each track position on those centroids within reach of the TC track.
idx_centr_reachable : np.ndarray of shape (nreachable,)
List of indices of input centroids within reach of the TC track.
"""
model_kwargs = {} if model_kwargs is None else model_kwargs
# start with the assumption that no centroids are within reach
npositions = si_track.sizes["time"]
idx_centr_reachable = np.zeros((0,), dtype=np.int64)
rainrates = np.zeros((npositions, 0), dtype=np.float64)
# exclude centroids that are too far from or too close to the eye
d_centr = _centr_distances(si_track, centroids, metric=metric, **model_kwargs)
mask_centr_close = (d_centr[""] <= max_dist_eye_km * KM_TO_M) & (d_centr[""] > 1)
if not np.any(mask_centr_close):
return rainrates, idx_centr_reachable
# restrict to the centroids that are within reach of any of the positions
mask_centr_close_any = mask_centr_close.any(axis=0)
mask_centr_close = mask_centr_close[:, mask_centr_close_any]
d_centr = {key: d[:, mask_centr_close_any, ...] for key, d in d_centr.items()}
centroids = centroids[mask_centr_close_any]
if model == MODEL_RAIN["R-CLIPER"]:
rainrates = _rcliper(si_track, d_centr[""], mask_centr_close, **model_kwargs)
elif model == MODEL_RAIN["TCR"]:
rainrates = _tcr(
si_track, centroids, d_centr, mask_centr_close, **model_kwargs,
)
else:
raise NotImplementedError
[idx_centr_reachable] = mask_centr_close_any.nonzero()
return rainrates, idx_centr_reachable
def _track_to_si_with_q_and_shear(
track: xr.Dataset,
metric: str = "equirect",
q_950: float = 0.01,
matlab_ref_mode: bool = False,
**_kwargs,
) -> xr.Dataset:
"""Convert track data to SI units and add Q (humidity) and vshear variables
If the track data set does not contain the "q950" variable, but "t600", we compute the humidity
assuming a moist adiabatic lapse rate (see ``_qs_from_t_diff_level``).
If the track data set does not contain the "vshear" variable, but "v850", we compute the wind
shear based on the Beta Advection Model (BAM):
v_trans = 0.8 * v850 + 0.2 * v250 + v_beta
=> 5 * (v_trans - v_beta - v850) v250 - v850 =: v_shear
Paramaters
----------
track : xr.Dataset
TC track data.
metric : str, optional
Specify an approximation method to use for earth distances: "equirect" (faster) or
"geosphere" (more accurate). See ``dist_approx`` function in ``climada.util.coordinates``.
Default: "equirect".
q_950 : float, optional
If the track data does not include "t600" values, assume this constant value of saturation
specific humidity (in kg/kg) at 950 hPa. Default: 0.01
matlab_ref_mode : bool, optional
Do not apply the changes to the reference MATLAB implementation. Default: False
_kwargs : dict
Additional kwargs are ignored.
Returns
-------
xr.Dataset
"""
si_track = tctrack_to_si(track, metric=metric)
if "q950" in track.variables:
si_track["q950"] = track["q950"].copy()
elif "t600" not in track.variables:
si_track["q950"] = ("time", np.full_like(si_track["lat"].values, q_950))
else:
# Note that we follow the MATLAB reference in computing Q at 950 hPa as opposed to the
# pressure level used in Lu et al. 2018 (900 hPa)
pres_in = 600
pres_out = 950
si_track["q950"] = ("time", _qs_from_t_diff_level(
track["t600"].values,
si_track["vmax"].values,
pres_in,
pres_out,
matlab_ref_mode=matlab_ref_mode,
))
if "ushear" in track.variables:
si_track["vshear"] = (["time", "component"], (
np.stack([track[f"{d}shear"].values.copy() for d in ["v", "u"]], axis=1)
))
elif "u850" in track.variables:
si_track["v850"] = (["time", "component"], (
np.stack([track[f"{d}850"].values.copy() for d in ["v", "u"]], axis=1)
))
# v_drift (or v_beta) is set to be a 1.4 m/s drift in meridional direction (away from the
# equator), because that's the value used in the proprietary synthetic track generator by
# WindRiskTech. Note, however, that a value of 2.5 m/s seems to be more common in the
# literature (e.g. Emanuel et al. 2006 or Lee et al. 2018).
v_beta_lat = 1.4
si_track["vdrift"] = xr.zeros_like(si_track["v850"])
si_track["vdrift"].values[:, 0] = (
v_beta_lat
* si_track.attrs["latsign"]
* np.cos(np.radians(si_track["lat"].values))
)
si_track["vshear"] = 5 * (si_track["vtrans"] - si_track["vdrift"] - si_track["v850"])
return si_track
def _centr_distances(
si_track: xr.Dataset,
centroids: np.ndarray,
metric: str = "equirect",
res_radial_m: float = 2000.0,
**_kwargs,
) -> dict:
"""Compute distances of centroids to storm locations required for ``_compute_vertical_velocity``
In addition to the distances to the centroids, the distances to staggered centroid locations,
as well as the unit vectors pointing from the storm center to each centroid are returned.
Parameters
----------
si_track : xr.Dataset
TC track data in SI units, see ``tctrack_to_si``.
centroids : ndarray
Each row is a pair of lat/lon coordinates.
metric : str, optional
Approximation method to use for earth distances: "equirect" (faster) or "geosphere" (more
accurate). See ``dist_approx`` function in ``climada.util.coordinates``.
Default: "equirect".
res_radial_m : float, optional
Spatial resolution (in m) in radial direction. Default: 2000
_kwargs : dict
Additional keyword arguments are ignored.
Returns
-------
dict
"""
# d_centr : Distance (in m) from eyes to centroids .
# v_centr : Vector pointing from storm center to centroids. The directional components are
# lat-lon, i. e. the y (meridional) direction is listed first.
[d_centr], [v_centr] = u_coord.dist_approx(
si_track["lat"].values[None], si_track["lon"].values[None],
centroids[None, :, 0], centroids[None, :, 1],
log=True, normalize=False, method=metric, units="m")
return {
"": d_centr,
"+": d_centr + res_radial_m,
"-": np.fmax(0, d_centr - res_radial_m),
"+h": d_centr + 0.5 * res_radial_m,
"-h": np.fmax(0, d_centr - 0.5 * res_radial_m),
"dir": v_centr / np.fmax(1e-3, d_centr[:, :, None]),
}
def _rcliper(
si_track: xr.Dataset,
d_centr: np.ndarray,
mask_centr_close: np.ndarray,
) -> np.ndarray:
"""Compute rain rate (in mm/h) from maximum wind speeds using the R-CLIPER model
The model is defined in equations (3)-(5) and Table 2 (NHC) in the following publication:
Tuleya et al. (2007): Evaluation of GFDL and Simple Statistical Model Rainfall Forecasts for
U.S. Landfalling Tropical Storms. Weather and Forecasting 22(1): 56–70.
https://doi.org/10.1175/WAF972.1
Parameters
----------
si_track : xr.Dataset
Output of ``tctrack_to_si``. Only the "vmax" data variable is used.
d_centr : np.ndarray of shape (npositions, ncentroids)
Distance (in m) between centroids and track positions.
mask_centr_close : np.ndarray of shape (npositions, ncentroids)
For each track position one row indicating which centroids are within reach.
Returns
-------