climada_petals.hazard package#
- climada_petals.hazard.emulator package
- River Flood from GloFAS River Discharge Data Module
- Main Module
RiverFloodCachePaths
RiverFloodInundation
RiverFloodInundation.store_intermediates
RiverFloodInundation.cache_paths
RiverFloodInundation.flood_maps
RiverFloodInundation.gumbel_fits
RiverFloodInundation.flopros
RiverFloodInundation.regridder
RiverFloodInundation.__init__()
RiverFloodInundation.clear_cache()
RiverFloodInundation.compute()
RiverFloodInundation.download_forecast()
RiverFloodInundation.download_reanalysis()
RiverFloodInundation.return_period()
RiverFloodInundation.return_period_resample()
RiverFloodInundation.regrid()
RiverFloodInundation.apply_protection()
RiverFloodInundation.flood_depth()
- Transformation Operations
- Helper Functions
- CDS Glofas Downloader
- Main Module
climada_petals.hazard.drought module#
- class climada_petals.hazard.drought.Drought[source]#
Bases:
Hazard
Contains drought events.
- SPEI#
Standardize Precipitation Evapotraspiration Index
- Type:
float
- vars_opt = {'spei'}#
Name of the variables that aren’t need to compute the impact.
- hazard_def(intensity_matrix)[source]#
return hazard set
- Parameters:
see intensity_from_spei
- Returns:
Drought, full hazard set
check using new_haz.check()
climada_petals.hazard.landslide module#
- class climada_petals.hazard.landslide.Landslide[source]#
Bases:
Hazard
Landslide Hazard set generation.
- classmethod from_hist(bbox, input_gdf, res=0.0083333)[source]#
Set historic landslide (ls) raster hazard from historical point records, for example as can be retrieved from the NASA COOLR initiative, which is the largest global ls repository, for a specific geographic extent. Points are assigned to the gridcell they fall into, and the whole grid- cell hence counts as equally affected. Event frequencies from an incomplete dataset are not meaningful and hence aren’t set by default. probabilistic calculations! Use the probabilistic method for this!
See tutorial for details; the global ls catalog from NASA COOLR can bedownloaded from https://maps.nccs.nasa.gov/arcgis/apps/webappviewer/index.html?id=824ea5864ec8423fb985b33ee6bc05b7
Note
The grid which is generated has the same projection as the geodataframe with point occurrences. By default, this is EPSG:4326, which is a non- projected, geographic CRS. This means, depending on where on the globe the analysis is performed, the area per gridcell differs vastly. Consider this when setting your resoluton (e.g. at the equator, 1° ~ 111 km). In turn, one can use projected CRS which preserve angles and areas within the reference area for which they are defined. To do this, reproject the input_gdf to the desired projection. For more on projected & geographic CRS, see https://desktop.arcgis.com/en/arcmap/10.3/guide-books/map-projections/about-projected-coordinate-systems.htm
- Parameters:
bbox (tuple) – (minx, miny, maxx, maxy) geographic extent of interest
input_gdf (str or or geopandas geodataframe) – path to shapefile (.shp) with ls point data or already laoded gdf
res (float) – resolution in units of the input_gdf crs of the final grid cells which are created. Whith EPSG:4326, this is degrees. Default is 0.008333.
- Returns:
Landslide – instance filled with historic LS hazard set for either point hazards or polygons with specified surrounding extent.
- Return type:
- classmethod from_prob(bbox, path_sourcefile, corr_fact=10000000.0, n_years=500, dist='poisson')[source]#
Set probabilistic landslide hazard (fraction, intensity and frequency) for a defined bounding box and time period from a raster. The hazard data for which this function is explicitly written is readily provided by UNEP & the Norwegian Geotechnical Institute (NGI), and can be downloaded and unzipped from https://preview.grid.unep.ch/index.php?preview=data&events=landslides&evcat=2&lang=eng for precipitation-triggered landslide and from https://preview.grid.unep.ch/index.php?preview=data&events=landslides&evcat=1&lang=eng for earthquake-triggered landslides. It works with any similar raster file. Original data is given in expected annual probability and percentage of pixel of occurrence of a potentially destructive landslide event x 1000000 (so be sure to adjust this by setting the correction factor). More details can be found in the landslide tutorial and under above- mentioned links.
Events are sampled from annual occurrence probabilites via binomial or poisson distribution. An event therefore includes all landslides sampled to occur within a year for the given area. intensity takes a binary value (occurrence or no occurrene of a LS); frequency is set to 1 / n_years.
Impact functions, since they act on the intensity, should hence be in the form of a step function, defining impact for intensity 0 and (close to) 1.
- Parameters:
bbox (tuple) – (minx, miny, maxx, maxy) geographic extent of interest
path_sourcefile (str) – path to UNEP/NGI ls hazard file (.tif)
corr_fact (float or int) – factor by which to divide the values in the original probability file, in case it is not scaled to [0,1]. Default is 1’000’000
n_years (int) – sampling period
dist (str) – distribution to sample from. ‘poisson’ (default) and ‘binom’
- Returns:
haz – probabilistic LS hazard
- Return type:
climada.hazard.Landslide instance
See also
sample_events
climada_petals.hazard.low_flow module#
- class climada_petals.hazard.low_flow.LowFlow(pool=None)[source]#
Bases:
Hazard
Contains river low flow events (surface water scarcity). The intensity of the hazard is number of days below a threshold (defined as percentile in reference data). The method set_from_nc can be used to create a LowFlow hazard set populated with data based on gridded hydrological model runs as provided by the ISIMIP project (https://www.isimip.org/), e.g. ISIMIP2a/b. grid cells with a minimum number of days below threshold per month are clustered in space (lat/lon) and time (monthly) to identify and set connected events.
- clus_thresh_t#
maximum time difference in months to be counted as$ connected points during clustering, default = 1
- Type:
int
- clus_thresh_xy#
maximum spatial grid cell distance in number of cells to be counted as connected points during clustering, default = 2
- Type:
int
- min_samples#
Minimum amount of data points in one cluster to consider as event, default = 1.
- Type:
int
- date_start#
for each event, the date of the first month of the event (ordinal) Note: Hazard attribute ‘date’ contains the date of maximum event intensity.
- Type:
np.array(int)
- date_end#
for each event, the date of the last month of the event (ordinal)
- Type:
np.array(int)
- resolution#
spatial resoultion of gridded discharge input data in degree lat/lon, default = 0.5°
- Type:
float
- clus_thresh_t = 1#
- clus_thresh_xy = 2#
- min_samples = 1#
- resolution = 0.5#
- classmethod from_netcdf(input_dir=None, centroids=None, countries=None, reg=None, bbox=None, percentile=2.5, min_intensity=1, min_number_cells=1, min_days_per_month=1, yearrange=(2001, 2005), yearrange_ref=(1971, 2005), gh_model=None, cl_model=None, scenario='historical', scenario_ref='historical', soc='histsoc', soc_ref='histsoc', fn_str_var='co2_dis_global_daily', keep_dis_data=False, yearchunks='default', mask_threshold=('mean', 1))[source]#
Wrapper to fill hazard from NetCDF file containing variable dis (daily), e.g. as provided from from ISIMIP Water Sectior (Global): https://esg.pik-potsdam.de/search/isimip/
- Parameters:
input_dir (string) – path to input data directory. In this folder, netCDF files with gridded hydrological model output are required, containing the variable dis (discharge) on a daily temporal resolution as f.i. provided by the ISIMIP project (https://www.isimip.org/)
centroids (Centroids) – centroids (area that is considered, reg and country must be None)
countries (list of countries ISO3) – selection of countries (reg must be None!) [not yet implemented]
reg (list of regions) – can be set with region code if whole areas are considered (if not None, countries and centroids are ignored) [not yet implemented]
bbox (tuple of four floats) – bounding box: (lon min, lat min, lon max, lat max)
percentile (float) – percentile used to compute threshold, 0.0 < percentile < 100.0
min_intensity (int) – minimum intensity (nr of days) in an event event; events with lower max. intensity are dropped
min_number_cells (int) – minimum spatial extent (nr of grid cells) in an event event; events with lower geographical extent are dropped
min_days_per_month (int) – minimum nr of days below threshold in a month; months with lower nr of days below threshold are not considered for the event creation (clustering)
yearrange (int tuple) – year range for hazard set, f.i. (2001, 2005)
yearrange_ref (int tuple) – year range for reference (threshold), f.i. (1971, 2000)
gh_model (str) – abbrev. hydrological model (only when input_dir is selected) f.i. ‘H08’, ‘CLM45’, ‘ORCHIDEE’, ‘LPJmL’, ‘WaterGAP2’, ‘JULES-W1’, ‘MATSIRO’
cl_model (str) – abbrev. climate model (only when input_dir is selected) f.i. ‘gfdl-esm2m’, ‘hadgem2-es’, ‘ipsl-cm5a-lr’, ‘miroc5’, ‘gswp3’, ‘wfdei’, ‘princeton’, ‘watch’
scenario (str) – climate change scenario (only when input_dir is selected) f.i. ‘historical’, ‘rcp26’, ‘rcp60’, ‘hist’
scenario_ref (str) – climate change scenario for reference (only when input_dir is selected)
soc (str) – socio-economic trajectory (only when input_dir is selected) f.i. ‘histsoc’, # historical trajectory ‘2005soc’, # constant at 2005 level ‘rcp26soc’, # RCP6.0 trajectory ‘rcp60soc’, # RCP6.0 trajectory ‘pressoc’ # constant at pre-industrial socio-economic level
soc_ref (str) – csocio-economic trajectory for reference, like soc. (only when input_dir is selected)
fn_str_var (str) – FileName STRing depending on VARiable and ISIMIP simuation round
keep_dis_data (boolean) – keep monthly data (variable ndays = days below threshold) as dataframe (attribute “data”) and save additional field ‘relative_dis’ (relative discharge compared to the long term)
yearchunks – list of year chunks corresponding to each nc flow file. If set to ‘default’, uses the chunking corresponding to the scenario.
mask_threshold – tuple with threshold value [1] for criterion [0] for mask: Threshold below which the grid is masked out. e.g.: (‘mean’, 1.) –> grid cells with a mean discharge below 1 are ignored (‘percentile’, .3) –> grid cells with a value of the computed percentile discharge values below 0.3 are ignored. default: (‘mean’, 1}). Set to None for no threshold. Provide a list of tuples for multiple thresholds.
- Raises:
NameError –
- Returns:
hazard set with lowflow calculated from netcdf file containing discharge data
- Return type:
- set_intensity_from_clusters(centroids=None, min_intensity=1, min_number_cells=1, yearrange=(2001, 2005), keep_dis_data=False)[source]#
Build low flow hazards with events from clustering and centroids and (re)set attributes.
- events_from_clusters(centroids)[source]#
Initiate hazard events from connected clusters found in self.lowflow_df
- Parameters:
centroids (Centroids)
- identify_clusters(clus_thresh_xy=None, clus_thresh_t=None, min_samples=None)[source]#
call clustering functions to identify the clusters inside the dataframe
- Parameters:
clus_thresh_xy (int) – new value of maximum grid cell distance (number of grid cells) to be counted as connected points during clustering
clus_thresh_t (int) – new value of maximum timse step difference (months) to be counted as connected points during clustering
min_samples (int) – new value or minimum amount of data points in one cluster to retain the cluster as an event, smaller clusters will be ignored
- Return type:
pandas.DataFrame
- filter_events(min_intensity=1, min_number_cells=1)[source]#
Remove events with max intensity below min_intensity or spatial extend below min_number_cells
- Parameters:
min_intensity (int or float) – Minimum criterion for intensity
min_number_cells (int or float) – Minimum crietrion for number of grid cell
- Return type:
Hazard
climada_petals.hazard.relative_cropyield module#
- class climada_petals.hazard.relative_cropyield.RelativeCropyield(crop: str = '', intensity_def: str = 'Yearly Yield', **kwargs)[source]#
Bases:
Hazard
Agricultural climate risk: Relative Cropyield (relative to historical mean); Each year corresponds to one hazard event; Based on modelled crop yield, from ISIMIP (www.isimip.org, required input data). Attributes as defined in Hazard and the here defined additional attributes.
- crop_type#
crop type (‘whe’ for wheat, ‘mai’ for maize, ‘soy’ for soybeans and ‘ric’ for rice)
- Type:
str
- intensity_def#
intensity defined as: ‘Yearly Yield’ [t/(ha*y)], ‘Relative Yield’, or ‘Percentile’
- Type:
str
- __init__(crop: str = '', intensity_def: str = 'Yearly Yield', **kwargs)[source]#
Initialize values.
- Parameters:
crop_type (str, optional) – crop type (‘whe’ for wheat, ‘mai’ for maize, ‘soy’ for soybeans and ‘ric’ for rice). Default: ‘’
intensity_def (str, optional) – intensity defined as: ‘Yearly Yield’ [t/(ha*y)], ‘Relative Yield’, or ‘Percentile’ Default: ‘Yearly Yield’
**kwargs (Hazard properties, optional) – All other keyword arguments are passed to the Hazard constructor.
- set_from_isimip_netcdf(*args, **kwargs)[source]#
This function is deprecated, use RelativeCropyield.from_isimip_netcdf instead.
- classmethod from_isimip_netcdf(input_dir=None, filename=None, bbox=None, yearrange=None, ag_model=None, cl_model=None, bias_corr=None, scenario=None, soc=None, co2=None, crop=None, irr=None, fn_str_var=None)[source]#
Wrapper to fill hazard from crop yield NetCDF file. Build and tested for output from ISIMIP2 and ISIMIP3, but might also work for other NetCDF containing gridded crop model output from other sources.
- Parameters:
input_dir (Path or str) – path to input data directory, default: {CONFIG.exposures.crop_production.local_data}/Input/Exposure
filename (string) – name of netcdf file in input_dir. If filename is given, the other parameters specifying the model run are not required!
bbox (list of four floats) – bounding box: [lon min, lat min, lon max, lat max]
yearrange (int tuple) – year range for hazard set, f.i. (1976, 2005)
ag_model (str) – abbrev. agricultural model (only when input_dir is selected) f.i. ‘clm-crop’, ‘gepic’,’lpjml’,’pepic’
cl_model (str) – abbrev. climate model (only when input_dir is selected) f.i. [‘gfdl-esm2m’, ‘hadgem2-es’,’ipsl-cm5a-lr’,’miroc5’
bias_corr (str) – bias correction of climate forcing, f.i. ‘ewembi’ (ISIMIP2b, default) or ‘w5e5’ (ISIMIP3b)
scenario (str) – climate change scenario (only when input_dir is selected) f.i. ‘historical’ or ‘rcp60’ or ‘ISIMIP2a’
soc (str) – socio-economic trajectory (only when input_dir is selected) f.i. ‘2005soc’ or ‘histsoc’
co2 (str) – CO2 forcing scenario (only when input_dir is selected) f.i. ‘co2’ or ‘2005co2’
crop (str) – crop type (only when input_dir is selected) f.i. ‘whe’, ‘mai’, ‘soy’ or ‘ric’
irr (str) – irrigation type (only when input_dir is selected) f.i ‘noirr’ or ‘irr’
fn_str_var (str) – FileName STRing depending on VARiable and ISIMIP simuation round
- Return type:
- Raises:
NameError –
- calc_mean(yearrange_mean=None, save=False, output_dir=None)[source]#
Calculates mean of the hazard for a given reference time period
- Parameters:
yearrange_mean (array) – time period used to calculate the mean intensity default: 1976-2005 (historical)
save (boolean) – save mean to file? default: False
output_dir (str or Path) – path of output directory, default: {CONFIG.exposures.crop_production.local_data}/Output
- Returns:
contains mean value over the given reference time period for each centroid
- Return type:
hist_mean(array)
- set_rel_yield_to_int(*args, **kwargs)[source]#
This function is deprecated, use function rel_yield_to_int instead.
- set_percentile_to_int(*args, **kwargs)[source]#
This function is deprecated, use function percentile_to_int instead.
- plot_intensity_cp(event=None, dif=False, axis=None, **kwargs)[source]#
Plots intensity with predefined settings depending on the intensity definition
- Parameters:
event (int or str) – event_id or event_name
dif (boolean) – variable signilizing whether absolute values or the difference between future and historic are plotted (False: his/fut values; True: difference = fut-his)
axis (geoaxes) – axes to plot on
- Return type:
axes (geoaxes)
climada_petals.hazard.river_flood module#
- class climada_petals.hazard.river_flood.RiverFlood(*args, **kwargs)[source]#
Bases:
Hazard
Contains flood events Flood intensities are calculated by means of the CaMa-Flood global hydrodynamic model
- fla_event#
total flooded area for every event
- Type:
1d array(n_events)
- fla_annual#
total flooded area for every year
- Type:
1d array (n_years)
- fla_ann_av#
average flooded area per year
- Type:
float
- fla_ev_av#
average flooded area per event
- Type:
float
- fla_ann_centr#
flooded area in every centroid for every event
- Type:
2d array(n_years x n_centroids)
- fla_ev_centr#
flooded area in every centroid for every event
- Type:
2d array(n_events x n_centroids)
- classmethod from_nc(dph_path=None, frc_path=None, origin=False, centroids=None, countries=None, reg=None, shape=None, ISINatIDGrid=False, years=None)[source]#
Wrapper to fill hazard from nc_flood file
- Parameters:
dph_path (str, optional) – Flood file to read (depth)
frc_path (str, optional) – Flood file to read (fraction)
origin (bool, optional) – Historical or probabilistic event. Default: False
centroids (Centroids, optional) – centroids to extract
countries (list of str, optional) – If reg is None, use this selection of countries (ISO3). Default: None
reg (list of str, optional) – Use region code to consider whole areas. If not None, countries and centroids are ignored. Default: None
shape (str or Path, optional) – If reg and countries are None, use the first geometry in this shape file to cut out the area of interest. Default: None
ISINatIDGrid (bool, optional) – Indicates whether ISIMIP_NatIDGrid is used. Default: False
years (list of int) – Years that are considered. Default: None
- Returns:
haz
- Return type:
RiverFlood instance
- Raises:
NameError –
- exclude_trends(fld_trend_path, dis)[source]#
Function allows to exclude flood impacts that are caused in areas exposed discharge trends other than the selected one. (This function is only needed for very specific applications)
- Raises:
NameError –
- exclude_returnlevel(frc_path)[source]#
Function allows to exclude flood impacts below a certain return level by manipulating flood fractions in a way that the array flooded more frequently than the treshold value is excluded. (This function is only needed for very specific applications)
- Raises:
NameError –
climada_petals.hazard.tc_rainfield module#
- class climada_petals.hazard.tc_rainfield.TCRain(category: ndarray | None = None, basin: List | None = None, rainrates: List[csr_matrix] | None = None, **kwargs)[source]#
Bases:
Hazard
Contains rainfall from tropical cyclone events.
- category#
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
- Type:
np.ndarray of ints
- basin#
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
- Type:
list of str
- rainrates#
For each event, the rain rates (in mm/h) at each centroid and track position in a sparse matrix of shape (npositions, ncentroids).
- Type:
list of csr_matrix
- intensity_thres = 0.1#
intensity threshold for storage in mm
- vars_opt = {'category'}#
Name of the variables that aren’t needed to compute the impact.
- __init__(category: ndarray | None = None, basin: List | None = None, rainrates: List[csr_matrix] | None = None, **kwargs)[source]#
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.
- set_from_tracks(*args, **kwargs)[source]#
This function is deprecated, use TCRain.from_tracks instead.
- classmethod from_tracks(tracks: TCTracks, centroids: Centroids = None, pool: ProcessPool | None = None, model: str = 'R-CLIPER', model_kwargs: dict | None = None, ignore_distance_to_coast: bool = False, store_rainrates: bool = False, metric: str = 'equirect', intensity_thres: float = 0.1, max_latitude: float = 61, max_dist_inland_km: float = 1000, max_dist_eye_km: float = 300, max_memory_gb: float = 8)[source]#
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 thresholdintensity_thres
.The
category
attribute is set to the value of thecategory
-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 thebasin
-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 withmodel="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 ofmodel_kwargs
and their meaning withmodel="TCR"
(in alphabetical order):- c_drag_tifPath 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_precipfloat, 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_tifPath 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_modebool, 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_foregroundfloat, 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_dragfloat, optional
The drag coefficient is clipped to this minimum value (esp. over ocean). Default: 0.001
- q_950float, 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_mfloat, 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_radfloat, optional
Background subsidence velocity (in m/s) under radiative cooling. Default: 0.005
- wind_modelstr, 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
- Return type:
climada_petals.hazard.tc_surge_bathtub module#
- class climada_petals.hazard.tc_surge_bathtub.TCSurgeBathtub[source]#
Bases:
Hazard
TC surge heights in m, a bathtub model with wind-surge relationship and inland decay.
- __init__()[source]#
Initialize values.
- Parameters:
haz_type (str, optional) – acronym of the hazard type (e.g. ‘TC’).
pool (pathos.pool, optional) – Pool that will be used for parallel computation when applicable. Default: None
units (str, optional) – units of the intensity. Defaults to empty string.
centroids (Centroids, optional) – centroids of the events. Defaults to empty Centroids object.
event_id (np.array, optional) – id (>0) of each event. Defaults to empty array.
event_name (list(str), optional) – name of each event (default: event_id). Defaults to empty list.
date (np.array, optional) – integer date corresponding to the proleptic Gregorian ordinal, where January 1 of year 1 has ordinal 1 (ordinal format of datetime library). Defaults to empty array.
orig (np.array, optional) – flags indicating historical events (True) or probabilistic (False). Defaults to empty array.
frequency (np.array, optional) – frequency of each event. Defaults to empty array.
frequency_unit (str, optional) – unit of the frequency (default: “1/year”).
intensity (sparse.csr_matrix, optional) – intensity of the events at centroids. Defaults to empty matrix.
fraction (sparse.csr_matrix, optional) – fraction of affected exposures for each event at each centroid. Defaults to empty matrix.
Examples
Initialize using keyword arguments:
>>> haz = Hazard('TC', intensity=sparse.csr_matrix(np.zeros((2, 2))))
Take hazard values from file:
>>> haz = Hazard.from_mat(HAZ_DEMO_MAT, 'demo')
- static from_tc_winds(wind_haz, topo_path, inland_decay_rate=0.2, add_sea_level_rise=0.0)[source]#
Compute tropical cyclone surge from input winds.
- Parameters:
wind_haz (TropCyclone) – Tropical cyclone wind hazard object.
topo_path (str) – Path to a raster file containing gridded elevation data.
inland_decay_rate (float, optional) – Decay rate of surge when moving inland in meters per km. Set to 0 to deactivate this effect. The default value of 0.2 is taken from Section 5.2.1 of the monograph Pielke and Pielke (1997): Hurricanes: their nature and impacts on society. https://rogerpielkejr.com/2016/10/10/hurricanes-their-nature-and-impacts-on-society/
add_sea_level_rise (float, optional) – Sea level rise effect in meters to be added to surge height.
climada_petals.hazard.tc_tracks_forecast module#
- class climada_petals.hazard.tc_tracks_forecast.TCForecast(data: List[Dataset] | None = None, pool: ProcessPool | None = None)[source]#
Bases:
TCTracks
An extension of the TCTracks construct adapted to forecast tracks obtained from numerical weather prediction runs.
- data#
- Same as in parent class, adding the following attributes
ensemble_member (int)
is_ensemble (bool; if False, the simulation is a high resolution deterministic run)
run_datetime (numpy.datetime64): timepoint of the initialisation of the numerical weather prediction run
- Type:
list of xarray.Dataset
- fetch_ecmwf(path=None, files=None, target_dir=None, remote_dir=None)[source]#
Fetch and read latest ECMWF TC track predictions from the FTP dissemination server into instance. Use path or files argument to use local files instead.
Assumes file naming conventions consistent with ECMWF: all files are assumed to have ‘tropical_cyclone’ and ‘ECEP’ in their name, denoting tropical cyclone ensemble forecast files.
- Parameters:
path (str, list(str), optional) – A location in the filesystem. Either a path to a single BUFR TC track file, or a folder containing only such files, or a globbing pattern. Passed to climada.util.files_handler.get_file_names
files (file-like, optional) – An explicit list of file objects, bypassing get_file_names
target_dir (str, optional) – An existing directory in the filesystem. When set, downloaded BUFR files will be saved here, otherwise they will be downloaded as temporary files.
remote_dir (str, optional) – If set, search the ECMWF FTP folder for forecast files in the directory; otherwise defaults to the latest. Format: yyyymmddhhmmss, e.g. 20200730120000
- static fetch_bufr_ftp(target_dir=None, remote_dir=None)[source]#
Fetch and read latest ECMWF TC track predictions from the FTP dissemination server. If target_dir is set, the files get downloaded persistently to the given location. A list of opened file-like objects gets returned.
- Parameters:
target_dir (str) – An existing directory to write the files to. If None, the files get returned as tempfiles.
remote_dir (str, optional) – If set, search this ftp folder for forecast files; defaults to the latest. Format: yyyymmddhhmmss, e.g. 20200730120000
- Return type:
[filelike]
- read_one_bufr_tc(file, id_no=None)[source]#
Read a single BUFR TC track file tailored to the ECMWF TC track predictions format.
- Parameters:
file (str, filelike) – Path object, string, or file-like object
id_no (int) – Numerical ID; optional. Else use date + random int.
- write_hdf5(file_name, complevel=5)[source]#
Write TC tracks in NetCDF4-compliant HDF5 format. This method overrides the method of the base class.
- Parameters:
file_name (str or Path) – Path to a new HDF5 file. If it exists already, the file is overwritten.
complevel (int, optional) – Specifies a compression level (0-9) for the zlib compression of the data. A value of 0 or None disables compression. Default: 5
- classmethod from_hdf5(file_name)[source]#
Create new TCTracks object from a NetCDF4-compliant HDF5 file. This method overrides the method of the base class.
- Parameters:
file_name (str or Path) – Path to a file that has been generated with TCForecast.write_hdf.
- Returns:
tracks – TCTracks with data from the given HDF5 file.
- Return type:
- classmethod read_cxml(cxml_path: str, xsl_path: str = None)[source]#
Reads a cxml (cyclone xml) file and returns a class instance.
- Parameters:
cxml_path (str) – Path to the cxml file
xsl_path (str, optional) – Path to the xsl tranformation file needed to read the cxml data. Default: None
- Returns:
TCTracks with data from the given cxml file.
- Return type:
climada_petals.hazard.wildfire module#
- class climada_petals.hazard.wildfire.WildFire[source]#
Bases:
Hazard
Contains wild fire events.
Wildfires comprise the challenge that the definition of an event is unclear. Reporting standards vary accross regions and over time. Hence, to have consistency, we consider an event as a whole fire season. A fire season is defined as a whole year (Jan-Dec in the NHS, Jul-Jun in SHS). This allows consistent risk assessment across the globe and over time. Hazard for which events refer to a fire season have the haz_type ‘WFseason’.
In order to perform concrete case studies or calibrate impact functions, events can be displayed as single fires. In that case they have the haz_type ‘WFsingle’.
- date_end#
integer date corresponding to the proleptic Gregorian ordinal, where January 1 of year 1 has ordinal 1 (ordinal format of datetime library). Represents last day of a wild fire instance where the fire was still active.
- Type:
array
- n_fires#
number of single fires in a fire season
- Type:
array
- class FirmsParams(clean_thresh: int = 30, days_thres_firms: int = 2, clus_thres_firms: int = 15, remove_minor_fires_firms: bool = True, minor_fire_thres_firms: int = 3)[source]#
Bases:
object
DataClass as container for firms parameters.
- clean_thresh#
Minimal confidence value for the data from MODIS instrument to be use as input
- Type:
int, default = 30
- days_thres_firms#
Minimum number of days to consider different fires
- Type:
int, default = 2
- clus_thres_firms#
Clustering factor which multiplies instrument resolution
- Type:
int, default = 15
- remove_minor_fires_firms#
removes FIRMS fires below defined theshold of entries
- Type:
bool, default = True
- minor_fire_thres_firms#
number of FIRMS entries required to be considered a fire
- Type:
int, default = 3
- clean_thresh: int = 30#
- days_thres_firms: int = 2#
- clus_thres_firms: int = 15#
- remove_minor_fires_firms: bool = True#
- minor_fire_thres_firms: int = 3#
- __init__(clean_thresh: int = 30, days_thres_firms: int = 2, clus_thres_firms: int = 15, remove_minor_fires_firms: bool = True, minor_fire_thres_firms: int = 3) None #
- class ProbaParams(blurr_steps: int = 4, prop_proba: float = 0.21, max_it_propa: int = 500000)[source]#
Bases:
object
Dataclass as container for parameters for generation of probabilistic events.
PLEASE BE AWARE: Parameter values did not undergo any calibration.
- blurr_steps#
steps with exponential decay for fire propagation matrix
- Type:
int, default = 4
- prop_proba#
- Type:
float, default = 0.21
- max_it_propa#
- Type:
int, default = 500000
- blurr_steps: int = 4#
- prop_proba: float = 0.21#
- max_it_propa: int = 500000#
- __init__(blurr_steps: int = 4, prop_proba: float = 0.21, max_it_propa: int = 500000) None #
- classmethod from_hist_fire_FIRMS(df_firms, centr_res_factor=1.0, centroids=None)[source]#
Parse FIRMS data and generate historical fires by temporal and spatial clustering. Single fire events are defined as a set of data points that are geographically close and/or have consecutive dates. The unique identification is made in two steps. First a temporal clustering is applied to cleaned data obtained from FIRMS. Data points with acquisition dates more than days_thres_firms days apart are in different temporal clusters. Second, for each temporal cluster, unique event are identified by performing a spatial clustering. This is done iteratively until all firms data points are assigned to an event.
This method sets the attributes self.n_fires, self.date_end, in addition to all attributes required by the hazard class.
This method creates a centroids raster if centroids=None with resolution given by centr_res_factor. The centroids can be retrieved from Wildfire.centroids()
- Parameters:
df_firms (pd.DataFrame) – FIRMS data as pd.Dataframe (https://firms.modaps.eosdis.nasa.gov/download/)
centr_res_factor (float, optional, default=1.0) – resolution factor with respect to the satellite data to use for centroids creation. Hence, if MODIS data (1 km res) is used and centr_res_factor is set to 0.2, the grid spacing of the generated centroids will equal 5 km (=1/0.2). If centroids are defined, this parameter has no effect.
centroids (Centroids, optional) – centroids in degrees to map data, centroids need to be on a regular raster grid in order for the clustrering to work.
- Returns:
haz
- Return type:
WildFire instance
- set_hist_fire_FIRMS(*args, **kwargs)[source]#
This function is deprecated, use WildFire.from_hist_fire_FIRMS instead.
- classmethod from_hist_fire_seasons_FIRMS(df_firms, centr_res_factor=1.0, centroids=None, hemisphere=None, year_start=None, year_end=None, keep_all_fires=False)[source]#
Parse FIRMS data and generate historical fire seasons.
Individual fires are created using temporal and spatial clustering according to the ‘set_hist_fire_FIRMS’ method. single fires are then summarized to seasons using max intensity at each centroid for each year.
This method sets the attributes self.n_fires, self.date_end, in addition to all attributes required by the hazard class.
This method creates a centroids raster if centroids=None with resolution given by centr_res_factor. The centroids can be retrieved from Wildfire.centroids()
- Parameters:
df_firms (pd.DataFrame) – FIRMS data as pd.Dataframe (https://firms.modaps.eosdis.nasa.gov/download/)
centr_res_factor (float, optional, default=1.0) – resolution factor with respect to the satellite data to use for centroids creation
centroids (Centroids, optional) – centroids in degrees to map data, centroids need to be on a regular grid in order for the clustrering to work.
hemisphere (str, optional) – ‘SHS’ or ‘NHS’ to define fire seasons. The hemisphere parameter is only used for the definition of the start of the fire season
year_start (int, optional) – start year; FIRMS fires before that are cut; no cut if not specified
year_end (int, optional) – end year; FIRMS fires after that are cut; no cut if not specified
keep_all_fires (bool, optional) – keep list of all individual fires; default is False to save memory. If set to true, fires are stored in self.hist_fire_seasons
- Returns:
haz
- Return type:
WildFire instance
- set_hist_fire_seasons_FIRMS(*args, **kwargs)[source]#
This function is deprecated, use WildFire.from_hist_fire_seasons_FIRMS instead.
- set_proba_fire_seasons(n_fire_seasons=1, n_ignitions=None, keep_all_fires=False)[source]#
Generate probabilistic fire seasons.
Fire seasons are created by running n probabilistic fires per year which are then summarized into a probabilistic fire season by calculating the max intensity at each centroid for each probabilistic fire season. Probabilistic fires are created using the logic described in the method ‘_run_one_bushfire’.
The fire propagation matrix can be assigned separately, if that is not done it will be generated on the available historic fire (seasons).
Intensities are drawn randomly from historic events. Thus, this method requires at least one fire to draw from.
This method modifies self (climada.hazard.WildFire instance) by adding probabilistic wildfire seasons.
- Parameters:
self (climada.Hazard.WildFire) – must have calculated historic fire seasons before
n_fire_seasons (int, optional) – number of fire seasons to be generated
n_ignitions (array, optional) – [min, max]: min/max of uniform distribution to sample from, in order to determin n_fire per probabilistic year set. If none, min/max is taken from hist.
keep_all_fires (bool, optional) – keep detailed list of all fires; default is False to save memory.
- combine_fires(event_id_merge=None, remove_rest=False, probabilistic=False)[source]#
Combine events that are identified as different fire to one event
Orig fires are removed and a new fire id created; max intensity at overlapping centroids is assigned.
This method modifies self (climada.hazard.WildFire instance) by combining single fires.
- Parameters:
event_id_merge (array of int, optional) – events to be merged
remove_rest (bool, optional) – if set to true, only the merged event is returned.
probabilistic (bool, optional) – differentiate, because probabilistic events have no date.
- summarize_fires_to_seasons(year_start=None, year_end=None, hemisphere=None)[source]#
Summarize historic fires into fire seasons.
Fires are summarized by taking the max intensity at each grid point.
This method modifies self (climada.hazard.WildFire instance) by summarizing individual fires into seasons.
- Parameters:
year_start (int, optional) – start year; fires before that are cut; no cut if not specified
year_end (int, optional) – end year; fires after that are cut; no cut if not specified
hemisphere (str, optional) – ‘SHS’ or ‘NHS’ to define fire seasons
- plot_fire_prob_matrix()[source]#
Plots fire propagation probability matrix as contour plot. At this point just to check the matrix but could easily be improved to normal map.
- Parameters:
self (climada.hazard.WildFire instance)
- Returns:
contour plot – contour plot of fire_propa_matrix
- Return type:
plt