climada.hazard package

climada.hazard.base module

class climada.hazard.base.Hazard(haz_type='', pool=None)[source]

Bases: object

Contains events of some hazard type defined at centroids. Loads from files with format defined in FILE_EXT.

tag

information about the source

Type

TagHazard

units

units of the intensity

Type

str

centroids

centroids of the events

Type

Centroids

event_id

id (>0) of each event

Type

np.array

event_name

name of each event (default: event_id)

Type

list(str)

date

integer date corresponding to the proleptic Gregorian ordinal, where January 1 of year 1 has ordinal 1 (ordinal format of datetime library)

Type

np.array

orig

flags indicating historical events (True) or probabilistic (False)

Type

np.array

frequency

frequency of each event in years

Type

np.array

intensity

intensity of the events at centroids

Type

sparse.csr_matrix

fraction

fraction of affected exposures for each event at each centroid

Type

sparse.csr_matrix

intensity_thres = 10

Intensity threshold per hazard used to filter lower intensities. To be set for every hazard type

vars_oblig = {'centroids', 'event_id', 'fraction', 'frequency', 'intensity', 'tag', 'units'}

scalar, str, list, 1dim np.array of size num_events, scipy.sparse matrix of shape num_events x num_centroids, Centroids and Tag.

Type

Name of the variables needed to compute the impact. Types

vars_def = {'date', 'event_name', 'orig'}

Name of the variables used in impact calculation whose value is descriptive and can therefore be set with default values. Types: scalar, string, list, 1dim np.array of size num_events.

vars_opt = {}

Name of the variables that aren’t need to compute the impact. Types: scalar, string, list, 1dim np.array of size num_events.

__init__(haz_type='', pool=None)[source]

Initialize values.

Parameters

haz_type (str, optional) – acronym of the hazard type (e.g. ‘TC’).

Examples

Fill hazard values by hand:

>>> haz = Hazard('TC')
>>> haz.intensity = sparse.csr_matrix(np.zeros((2, 2)))
>>> ...

Take hazard values from file:

>>> haz = Hazard('TC', HAZ_DEMO_MAT)
>>> haz.read_mat(HAZ_DEMO_MAT, 'demo')
clear()[source]

Reinitialize attributes (except the process Pool).

check()[source]

Check dimension of attributes.

Raises

ValueError

set_raster(files_intensity, files_fraction=None, attrs=None, band=None, src_crs=None, window=False, geometry=False, dst_crs=False, transform=None, width=None, height=None, resampling=<Resampling.nearest: 0>)[source]

Append intensity and fraction from raster file. 0s put to the masked values. File can be partially read using window OR geometry. Alternatively, CRS and/or transformation can be set using dst_crs and/or (transform, width and height).

Parameters
  • files_intensity (list(str)) – file names containing intensity

  • files_fraction (list(str)) – file names containing fraction

  • attrs (dict, optional) – name of Hazard attributes and their values

  • band (list(int), optional) – bands to read (starting at 1), default [1]

  • src_crs (crs, optional) – source CRS. Provide it if error without it.

  • window (rasterio.windows.Windows, optional) – window where data is extracted

  • geometry (shapely.geometry, optional) – consider pixels only in shape

  • dst_crs (crs, optional) – reproject to given crs

  • transform (rasterio.Affine) – affine transformation to apply

  • wdith (float) – number of lons for transform

  • height (float) – number of lats for transform

  • resampling (rasterio.warp,.Resampling optional) – resampling function used for reprojection to dst_crs

set_vector(files_intensity, files_fraction=None, attrs=None, inten_name=None, frac_name=None, dst_crs=None)[source]

Read vector files format supported by fiona. Each intensity name is considered an event.

Parameters
  • files_intensity (list(str)) – file names containing intensity, default: [‘intensity’]

  • files_fraction (list(str)) – file names containing fraction, default: [‘fraction’]

  • attrs (dict, optional) – name of Hazard attributes and their values

  • inten_name (list(str), optional) – name of variables containing the intensities of each event

  • frac_name (list(str), optional) – name of variables containing the fractions of each event

  • dst_crs (crs, optional) – reproject to given crs

reproject_raster(dst_crs=False, transform=None, width=None, height=None, resampl_inten=<Resampling.nearest: 0>, resampl_fract=<Resampling.nearest: 0>)[source]

Change current raster data to other CRS and/or transformation

Parameters
  • dst_crs (crs, optional) – reproject to given crs

  • transform (rasterio.Affine) – affine transformation to apply

  • wdith (float) – number of lons for transform

  • height (float) – number of lats for transform

  • resampl_inten (rasterio.warp,.Resampling optional) – resampling function used for reprojection to dst_crs for intensity

  • resampl_fract (rasterio.warp,.Resampling optional) – resampling function used for reprojection to dst_crs for fraction

reproject_vector(dst_crs, scheduler=None)[source]

Change current point data to a a given projection

Parameters
  • dst_crs (crs) – reproject to given crs

  • scheduler (str, optional) – used for dask map_partitions. “threads”, “synchronous” or “processes”

raster_to_vector()[source]

Change current raster to points (center of the pixels)

vector_to_raster(scheduler=None)[source]

Change current point data to a raster with same resolution

Parameters

scheduler (str, optional) – used for dask map_partitions. “threads”, “synchronous” or “processes”

read_mat(file_name, description='', var_names=None)[source]

Read climada hazard generate with the MATLAB code.

Parameters
  • file_name (str) – absolute file name

  • description (str, optional) – description of the data

  • var_names (dict, default) – name of the variables in the file, default: DEF_VAR_MAT constant

Raises

KeyError

read_excel(file_name, description='', var_names=None)[source]

Read climada hazard generate with the MATLAB code.

Parameters
  • file_name (str) – absolute file name

  • description (str, optional) – description of the data

  • centroids (Centroids, optional) – provide centroids if not contained in the file

  • var_names (dict, default) – name of the variables in the file, default: DEF_VAR_EXCEL constant

Raises

KeyError

select(event_names=None, date=None, orig=None, reg_id=None, reset_frequency=False)[source]

Select events matching provided criteria

The frequency of events may need to be recomputed (see reset_frequency)!

Parameters
  • event_names (list of str, optional) – Names of events.

  • date (array-like of length 2 containing str or int, optional) – (initial date, final date) in string ISO format (‘2011-01-02’) or datetime ordinal integer.

  • orig (bool, optional) – Select only historical (True) or only synthetic (False) events.

  • reg_id (int, optional) – Region identifier of the centroids’ region_id attibute.

  • reset_frequency (bool, optional) – Change frequency of events proportional to difference between first and last year (old and new). Default: False.

Returns

haz – If no event matching the specified criteria is found, None is returned.

Return type

Hazard or None

local_exceedance_inten(return_periods=(25, 50, 100, 250))[source]

Compute exceedance intensity map for given return periods.

Parameters

return_periods (np.array) – return periods to consider

Returns

np.array

plot_rp_intensity(return_periods=(25, 50, 100, 250), smooth=True, axis=None, figsize=(9, 13), **kwargs)[source]

Compute and plot hazard exceedance intensity maps for different return periods. Calls local_exceedance_inten.

Parameters
  • return_periods (tuple(int), optional) – return periods to consider

  • smooth (bool, optional) – smooth plot to plot.RESOLUTIONxplot.RESOLUTION

  • axis (matplotlib.axes._subplots.AxesSubplot, optional) – axis to use

  • figsize (tuple, optional) – figure size for plt.subplots

  • kwargs (optional) – arguments for pcolormesh matplotlib function used in event plots

Returns

matplotlib.axes._subplots.AxesSubplot, np.ndarray (return_periods.size x num_centroids)

plot_intensity(event=None, centr=None, smooth=True, axis=None, **kwargs)[source]

Plot intensity values for a selected event or centroid.

Parameters
  • event (int or str, optional) – If event > 0, plot intensities of event with id = event. If event = 0, plot maximum intensity in each centroid. If event < 0, plot abs(event)-largest event. If event is string, plot events with that name.

  • centr (int or tuple, optional) – If centr > 0, plot intensity of all events at centroid with id = centr. If centr = 0, plot maximum intensity of each event. If centr < 0, plot abs(centr)-largest centroid where higher intensities are reached. If tuple with (lat, lon) plot intensity of nearest centroid.

  • smooth (bool, optional) – Rescale data to RESOLUTIONxRESOLUTION pixels (see constant in module climada.util.plot)

  • axis (matplotlib.axes._subplots.AxesSubplot, optional) – axis to use

  • kwargs (optional) – arguments for pcolormesh matplotlib function used in event plots or for plot function used in centroids plots

Returns

matplotlib.axes._subplots.AxesSubplot

Raises

ValueError

plot_fraction(event=None, centr=None, smooth=True, axis=None, **kwargs)[source]

Plot fraction values for a selected event or centroid.

Parameters
  • event (int or str, optional) – If event > 0, plot fraction of event with id = event. If event = 0, plot maximum fraction in each centroid. If event < 0, plot abs(event)-largest event. If event is string, plot events with that name.

  • centr (int or tuple, optional) – If centr > 0, plot fraction of all events at centroid with id = centr. If centr = 0, plot maximum fraction of each event. If centr < 0, plot abs(centr)-largest centroid where highest fractions are reached. If tuple with (lat, lon) plot fraction of nearest centroid.

  • smooth (bool, optional) – Rescale data to RESOLUTIONxRESOLUTION pixels (see constant in module climada.util.plot)

  • axis (matplotlib.axes._subplots.AxesSubplot, optional) – axis to use

  • kwargs (optional) – arguments for pcolormesh matplotlib function used in event plots or for plot function used in centroids plots

Returns

matplotlib.axes._subplots.AxesSubplot

Raises

ValueError

sanitize_event_ids()[source]

Make sure that event ids are unique

get_event_id(event_name)[source]

Get an event id from its name. Several events might have the same name.

Parameters

event_name (str) – Event name

Returns

np.array(int)

get_event_name(event_id)[source]

Get the name of an event id.

Parameters

event_id (int) – id of the event

Returns

str

Raises

ValueError

get_event_date(event=None)[source]

Return list of date strings for given event or for all events, if no event provided.

Parameters

event (str or int, optional) – event name or id.

Returns

list(str)

calc_year_set()[source]

From the dates of the original events, get number yearly events.

Returns

key are years, values array with event_ids of that year

Return type

dict

append(hazard)[source]

Append events and centroids in hazard.

Parameters

hazard (Hazard) – Hazard instance to append to current

Raises

ValueError

remove_duplicates()[source]

Remove duplicate events (events with same name and date).

set_frequency(yearrange=None)[source]

Set hazard frequency from yearrange or intensity matrix.

Optional parameters:
yearrange (tuple or list): year range to be used to compute frequency

per event. If yearrange is not given (None), the year range is derived from self.date

property size

Returns number of events

write_raster(file_name, intensity=True)[source]

Write intensity or fraction as GeoTIFF file. Each band is an event

Parameters
  • file_name (str) – file name to write in tif format

  • intensity (bool) – if True, write intensity, otherwise write fraction

write_hdf5(file_name, todense=False)[source]

Write hazard in hdf5 format.

Parameters

file_name (str) – file name to write, with h5 format

read_hdf5(file_name)[source]

Read hazard in hdf5 format.

Parameters

file_name (str) – file name to read, with h5 format

concatenate(haz_src, append=False)[source]

Concatenate events of several hazards

Parameters
  • haz_src (list) – Hazard instances with same centroids and units

  • append (bool) – If True, append the concatenated hazards to this instance, otherwise replace all data in this instance by the concatenated data. Default: False.

climada.hazard.drought module

class climada.hazard.drought.Drought[source]

Bases: climada.hazard.base.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.

__init__()[source]

Empty constructor.

set_area(latmin, lonmin, latmax, lonmax)[source]

Set the area to analyse

set_file_path(path)[source]

Set path of the SPEI data

set_threshold(threshold)[source]

Set threshold

set_intensity_def(intensity_definition)[source]

Set intensity definition

setup()[source]

Set up the hazard drought

hazard_def(intensity_matrix)[source]

return hazard set Parameters: see intensity_from_spei :returns: Drought, full hazard set

check using new_haz.check()

plot_intensity_drought(event=None)[source]

plot drought intensity

post_processing(date)[source]

Date in format ‘2003-08-01’ Sets intensity of events starting after that date to zero

plot_start_end_date(event=None)[source]

plot start and end date of the chosen event

climada.hazard.isimip_data module

climada.hazard.landslide module

class climada.hazard.landslide.Landslide[source]

Bases: climada.hazard.base.Hazard

Landslide Hazard set generation. Attributes:

__init__()[source]

Empty constructor.

set_ls_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

bboxtuple

(minx, miny, maxx, maxy) geographic extent of interest

input_gdfstr or or geopandas geodataframe

path to shapefile (.shp) with ls point data or already laoded gdf

resfloat

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.

self (Landslide() inst.): instance filled with historic LS hazard

set for either point hazards or polygons with specified surrounding extent.

set_ls_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 of course 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; intensity takes a binary value (0 - no ls occurrence; 1 - ls occurrence) and fraction stores the actual the occurrence count (0 to n) per grid cell. Frequency is occurrence count / 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

self – probabilistic LS hazard

Return type

climada.hazard.Landslide instance

See also

sample_events_from_probs

climada.hazard.low_flow module

class climada.hazard.low_flow.LowFlow(pool=None)[source]

Bases: climada.hazard.base.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

1

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
__init__(pool=None)[source]

Empty constructor.

set_from_nc(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):

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) – (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

set_intensity_from_clusters(centroids=None, min_intensity=1, min_number_cells=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)[source]

Build low flow hazards with events from clustering and centroids and add 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

Optional 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

Returns

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

Returns

Hazard

climada.hazard.relative_cropyield module

class climada.hazard.relative_cropyield.RelativeCropyield(pool=None)[source]

Bases: climada.hazard.base.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__(pool=None)[source]

Empty constructor.

set_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

Raises

NameError

calc_mean(yearrange_mean=None, save=False, output_dir=None)[source]

Calculates mean of the hazard for a given reference time period

Optional 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(hist_mean)[source]

Sets relative yield (yearly yield / historic mean) as intensity

Parameters

hist_mean (array) – historic mean per centroid

Returns

hazard with modified intensity [unitless]

set_percentile_to_int(reference_intensity=None)[source]

Sets percentile to intensity

Parameters

reference_intensity (AD) – intensity to be used as reference (e.g. the historic intensity can be used in order to be able

to directly compare historic and future projection data)

Returns

hazard with modified intensity

plot_intensity_cp(event=None, dif=False, axis=None, **kwargs)[source]

Plots intensity with predefined settings depending on the intensity definition

Optional 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

Returns

axes (geoaxes)

plot_time_series(event=None)[source]

Plots a time series of intensities (a series of sub plots)

Optional Parameters:

event (int or str): event_id or event_name

Returns

figure

climada.hazard.river_flood module

class climada.hazard.river_flood.RiverFlood[source]

Bases: climada.hazard.base.Hazard

Contains flood events Flood intensities are calculated by means of the CaMa-Flood global hydrodynamic model

fla_event
Type

1d array(n_events)

fla_annual
Type

1d array (n_years)

fla_ann_av
Type

float

fla_ev_av
Type

float

fla_ann_centr

every centroid for every event

Type

2d array(n_years x n_centroids)

fla_ev_centr

every centroid for every event

Type

2d array(n_events x n_centroids)

__init__()[source]

Empty constructor

set_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 (string) – Flood file to read (depth)

  • frc_path (string) – Flood file to read (fraction)

  • origin (bool) – Historical or probabilistic event

  • centroids (Centroids) – centroids to extract

  • countries (list of countries ISO3) – (reg must be None!)

  • reg (list of regions) – can be set with region code if whole areas are considered (if not None, countries and centroids are ignored)

  • ISINatIDGrid (Bool) – Indicates whether ISIMIP_NatIDGrid is used

  • years (int list) – years that are considered

Raises

NameError

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 NameErroris function:

set_flooded_area(save_centr=False)[source]
Calculates flooded area for hazard. sets yearly flooded area and

flooded area per event

Raises

MemoryError

set_flood_volume(save_centr=False)[source]
Calculates flooded area for hazard. sets yearly flooded area and

flooded area per event

Raises

MemoryError

climada.hazard.storm_europe module

class climada.hazard.storm_europe.StormEurope[source]

Bases: climada.hazard.base.Hazard

A hazard set containing european winter storm events. Historic storm events can be downloaded at http://wisc.climate.copernicus.eu/ and read read_footprints(). Weather forecasts can be automatically downloaded from https://opendata.dwd.de/ and read with read_icon_grib(). Weather forecast from the COSMO-Consortium http://www.cosmo-model.org/ can be read with read_cosmoe_file().

ssi_wisc

Storm Severity Index (SSI) as recorded in the footprint files; apparently not reproducible from the footprint values only.

Type

np.array, float

ssi

SSI as set by set_ssi; uses the Dawkins definition by default.

Type

np.array, float

intensity_thres = 14.7

Intensity threshold for storage in m/s; same as used by WISC SSI calculations.

vars_opt = {'ssi', 'ssi_full_area', 'ssi_wisc'}

Name of the variables that aren’t need to compute the impact.

__init__()[source]

Calls the Hazard init dunder. Sets unit to ‘m/s’.

read_footprints(path, description=None, ref_raster=None, centroids=None, files_omit='fp_era20c_1990012515_701_0.nc', combine_threshold=None)[source]

Clear instance and read WISC footprints into it. Read Assumes that all footprints have the same coordinates as the first file listed/first file in dir.

Parameters
  • path (str, list(str)) – A location in the filesystem. Either a path to a single netCDF WISC footprint, or a folder containing only footprints, or a globbing pattern to one or more footprints.

  • description (str, optional) – description of the events, defaults to ‘WISC historical hazard set’

  • ref_raster (str, optional) – Reference netCDF file from which to construct a new barebones Centroids instance. Defaults to the first file in path.

  • centroids (Centroids, optional) – A Centroids struct, overriding ref_raster

  • files_omit (str, list(str), optional) – List of files to omit; defaults to one duplicate storm present in the WISC set as of 2018-09-10.

  • combine_threshold (int, optional) – threshold for combining events in number of days. if the difference of the dates (self.date) of two events is smaller or equal to this threshold, the two events are combined into one. Default is None, Advised for WISC is 2

read_cosmoe_file(fp_file, run_datetime, event_date=None, model_name='COSMO-2E', description=None)[source]

Clear instance and read gust footprint from weather forecast into it. The funciton is designed for the COSMO ensemble model used by the COSMO Consortium http://www.cosmo-model.org/ and postprocessed to an netcdf file using fieldextra. One event is one full day in UTC. Works for MeteoSwiss model output of COSMO-1E (11 members, resolution 1.1 km, forecast period 33-45 hours) COSMO-2E (21 members, resolution 2.2 km, forecast period 5 days)

Parameters
  • fp_file (str) – string directing to one netcdf file

  • run_datetime (datetime) – The starting timepoint of the forecast run of the cosmo model

  • event_date (datetime, optional) – one day within the forecast period, only this day (00H-24H) will be included in the hazard

  • model_name (str,optional) – provide the name of the COSMO model, for the description (e.g., ‘COSMO-1E’, ‘COSMO-2E’)

  • description (str, optional) – description of the events, defaults to a combination of model_name and run_datetime

read_icon_grib(run_datetime, event_date=None, model_name='icon-eu-eps', description=None, grib_dir=None, delete_raw_data=True)[source]

Clear instance and download and read dwd icon weather forecast footprints into it. New files are available for 24 hours on https://opendata.dwd.de, old files can be processed if they are already stored in grib_dir. One event is one full day in UTC. Current setup works for runs starting at 00H and 12H. Otherwise the aggregation is inaccurate, because of the given file structure with 1-hour, 3-hour and 6-hour maxima provided.

Parameters
  • run_datetime (datetime) – The starting timepoint of the forecast run of the icon model

  • event_date (datetime, optional) – one day within the forecast period, only this day (00H-24H) will be included in the hazard

  • model_name (str,optional) – select the name of the icon model to be downloaded. Must match the url on https://opendata.dwd.de (see download_icon_grib for further info)

  • description (str, optional) – description of the events, defaults to a combination of model_name and run_datetime

  • grib_dir (str, optional) – path to folder, where grib files are or should be stored

  • delete_raw_data (bool,optional) – select if downloaded raw data in .grib.bz2 file format should be stored on the computer or removed

calc_ssi(method='dawkins', intensity=None, on_land=True, threshold=None, sel_cen=None)[source]

Calculate the SSI, method must either be ‘dawkins’ or ‘wisc_gust’.

‘dawkins’, after Dawkins et al. (2016), doi:10.5194/nhess-16-1999-2016, matches the MATLAB version. ssi = sum_i(area_cell_i * intensity_cell_i^3)

‘wisc_gust’, according to the WISC Tier 1 definition found at https://wisc.climate.copernicus.eu/wisc/#/help/products#tier1_section ssi = sum(area_on_land) * mean(intensity)^3

In both definitions, only raster cells that are above the threshold are used in the computation. Note that this method does not reproduce self.ssi_wisc, presumably because the footprint only contains the maximum wind gusts instead of the sustained wind speeds over the 72 hour window. The deviation may also be due to differing definitions of what lies on land (i.e. Syria, Russia, Northern Africa and Greenland are exempt).

Parameters
  • method (str) – Either ‘dawkins’ or ‘wisc_gust’

  • intensity (scipy.sparse.csr) – Intensity matrix; defaults to self.intensity

  • on_land (bool) – Only calculate the SSI for areas on land, ignoring the intensities at sea. Defaults to true, whereas the MATLAB version did not.

  • threshold (float, optional) – Intensity threshold used in index definition. Cannot be lower than the read-in value.

  • sel_cen (np.array, bool) – A boolean vector selecting centroids. Takes precendence over on_land.

self.ssi_dawkins

SSI per event

Type

np.array

set_ssi(**kwargs)[source]

Wrapper around calc_ssi for setting the self.ssi attribute.

Parameters

**kwargs – passed on to calc_ssi

ssi

SSI per event

Type

np.array

plot_ssi(full_area=False)[source]
Plot the distribution of SSIs versus their cumulative exceedance

frequencies, highlighting historical storms in red.

Returns

fig (matplotlib.figure.Figure) ax (matplotlib.axes._subplots.AxesSubplot)

generate_prob_storms(reg_id=528, spatial_shift=4, ssi_args=None, **kwargs)[source]

Generates a new hazard set with one original and 29 probabilistic storms per historic storm. This represents a partial implementation of the Monte-Carlo method described in section 2.2 of Schwierz et al. (2010), doi:10.1007/s10584-009-9712-1. It omits the rotation of the storm footprints, as well as the pseudo- random alterations to the intensity.

In a first step, the original intensity and five additional intensities are saved to an array. In a second step, those 6 possible intensity levels are shifted by n raster pixels into each direction (N/S/E/W).

Caveats:
  • Memory safety is an issue; trial with the entire dataset resulted in 60GB of swap memory being used…

  • Can only use numeric region_id for country selection

  • Drops event names as provided by WISC

Parameters
  • region_id (int, list of ints, or None) – iso_n3 code of the countries we want the generated hazard set to be returned for.

  • spatial_shift (int) – amount of raster pixels to shift by

  • ssi_args (dict) – A dictionary of arguments passed to calc_ssi

  • **kwargs – keyword arguments passed on to self._hist2prob()

Returns

A new hazard set for the given country.

Centroid attributes are preserved. self.orig attribute is set to True for original storms (event_id ending in 00). Also contains a ssi_prob attribute,

Return type

new_haz (StormEurope)

climada.hazard.tag module

class climada.hazard.tag.Tag(haz_type='', file_name='', description='')[source]

Bases: object

Contain information used to tag a Hazard.

file_name

name of the source file(s)

Type

str or list(str)

haz_type

acronym defining the hazard type (e.g. ‘TC’)

Type

str

description

description(s) of the data

Type

str or list(str)

__init__(haz_type='', file_name='', description='')[source]

Initialize values.

Parameters
  • haz_type (str, optional) – acronym of the hazard type (e.g. ‘TC’).

  • file_name (str or list(str), optional) – file name(s) to read

  • description (str or list(str), optional) – description of the data

append(tag)[source]

Append input Tag instance information to current Tag.

join_file_names()[source]

Get a string with the joined file names.

join_descriptions()[source]

Get a string with the joined descriptions.

climada.hazard.tc_clim_change module

climada.hazard.tc_clim_change.TOT_RADIATIVE_FORCE = PosixPath('/home/docs/climada/data/rcp_db.xls')

//www.iiasa.ac.at/web-apps/tnt/RcpDb. generated: 2018-07-04 10:47:59.

Type

© RCP Database (Version 2.0.5) http

climada.hazard.tc_clim_change.get_knutson_criterion()[source]

Fill changes in TCs according to Knutson et al. 2015 Global projections of intense tropical cyclone activity for the late twenty-first century from dynamical downscaling of CMIP5/RCP4.5 scenarios.

Returns

list(dict) with items ‘criteria’ (dict with variable_name and list(possible values)), ‘year’ (int), ‘change’ (float), ‘variable’ (str), ‘function’ (np function)

climada.hazard.tc_clim_change.calc_scale_knutson(ref_year=2050, rcp_scenario=45)[source]

Comparison 2081-2100 (i.e., late twenty-first century) and 2001-20 (i.e., present day). Late twenty-first century effects on intensity and frequency per Saffir-Simpson-category and ocean basin is scaled to target year and target RCP proportional to total radiative forcing of the respective RCP and year.

Parameters
  • ref_year (int) – year between 2000 ad 2100. Default: 2050

  • rcp_scenario (int) – 26 for RCP 2.6, 45 for RCP 4.5 (default), 60 for RCP 6.0 and 85 for RCP 8.5.

Returns

float

climada.hazard.tc_rainfield module

class climada.hazard.tc_rainfield.TCRain(pool=None)[source]

Bases: climada.hazard.base.Hazard

Contains rainfall from tropical cyclone events.

intensity_thres = 0.1

intensity threshold for storage in mm

__init__(pool=None)[source]

Empty constructor.

set_from_tracks(tracks, centroids=None, dist_degree=3, description='')[source]

Computes rainfield from tracks based on the RCLIPER model. Parallel process. :Parameters: * tracks (TCTracks) – tracks of events

  • centroids (Centroids, optional) – Centroids where to model TC. Default: global centroids.

  • disr_degree (int) – distance (in degrees) from node within which the rainfield is processed (default 3 deg,~300km)

  • description (str, optional) – description of the events

climada.hazard.tc_surge_bathtub module

class climada.hazard.tc_surge_bathtub.TCSurgeBathtub[source]

Bases: climada.hazard.base.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’).

Examples

Fill hazard values by hand:

>>> haz = Hazard('TC')
>>> haz.intensity = sparse.csr_matrix(np.zeros((2, 2)))
>>> ...

Take hazard values from file:

>>> haz = Hazard('TC', HAZ_DEMO_MAT)
>>> haz.read_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.hazard.tc_tracks module

climada.hazard.tc_tracks.CAT_NAMES = {-1: 'Tropical Depression', 0: 'Tropical Storm', 1: 'Hurricane Cat. 1', 2: 'Hurricane Cat. 2', 3: 'Hurricane Cat. 3', 4: 'Hurricane Cat. 4', 5: 'Hurricane Cat. 5'}

Saffir-Simpson category names.

climada.hazard.tc_tracks.SAFFIR_SIM_CAT = [34, 64, 83, 96, 113, 137, 1000]

Saffir-Simpson Hurricane Wind Scale in kn based on NOAA

class climada.hazard.tc_tracks.TCTracks(pool=None)[source]

Bases: object

Contains tropical cyclone tracks.

data
List of tropical cyclone tracks. Each track contains following attributes:
  • time (coords)

  • lat (coords)

  • lon (coords)

  • time_step (in hours)

  • radius_max_wind (in nautical miles)

  • max_sustained_wind

  • central_pressure

  • environmental_pressure

  • max_sustained_wind_unit (attrs)

  • central_pressure_unit (attrs)

  • name (attrs)

  • sid (attrs)

  • orig_event_flag (attrs)

  • data_provider (attrs)

  • basin (attrs)

  • id_no (attrs)

  • category (attrs)

Computed during processing:
  • on_land

  • dist_since_lf

Type

list(xarray.Dataset)

__init__(pool=None)[source]

Empty constructor. Read csv IBTrACS files if provided.

append(tracks)[source]

Append tracks to current.

Parameters

tracks (xarray.Dataset or list(xarray.Dataset)) – tracks to append.

get_track(track_name=None)[source]

Get track with provided name.

Returns the first matching track based on the assumption that no other track with the same name or sid exists in the set.

Parameters

track_name (str, optional) – Name or sid (ibtracsID for IBTrACS) of track. If None (default), return all tracks.

Returns

result – Usually, a single track is returned. If no track with the specified name is found, an empty list [] is returned. If called with track_name=None, the list of all tracks is returned.

Return type

xarray.Dataset or list of xarray.Dataset

subset(filterdict)[source]

Subset tracks based on track attributes.

Select all tracks matching exactly the given attribute values.

Parameters

filterdict (dict or OrderedDict) – Keys are attribute names, values are the corresponding attribute values to match. In case of an ordered dict, the filters are applied in the given order.

Returns

tc_tracks – A new instance of TCTracks containing only the matching tracks.

Return type

TCTracks

tracks_in_exp(exposure, buffer=1.0)[source]

Select only the tracks that are in the vicinity (buffer) of an exposure.

Each exposure point/geometry is extended to a disc of radius buffer. Each track is converted to a line and extended by a radius buffer.

Parameters
  • exposure (Exposure) – Exposure used to select tracks.

  • buffer (float, optional) – Size of buffer around exposure geometries (in the units of exposure.crs), see geopandas.distance. Default: 1.0

Returns

filtered_tracks – TCTracks object with tracks from tc_tracks intersecting the exposure whitin a buffer distance.

Return type

climada.hazard.TCTracks()

read_ibtracs_netcdf(provider=None, rescale_windspeeds=True, storm_id=None, year_range=None, basin=None, interpolate_missing=True, estimate_missing=False, correct_pres=False, file_name='IBTrACS.ALL.v04r00.nc')[source]

Read track data from IBTrACS databse.

When using data from IBTrACS, make sure to be familiar with the scope and limitations of IBTrACS, e.g. by reading the official documentation (https://www.ncdc.noaa.gov/ibtracs/pdf/IBTrACS_version4_Technical_Details.pdf). Reading the CLIMADA documentation can’t replace a thorough understanding of the underlying data. This function only provides a (hopefully useful) interface for the data input, but cannot provide any guidance or make recommendations about if and how to use IBTrACS data for your particular project.

Resulting tracks are required to have both pressure and wind speed information at all time steps. Therefore, all track positions where one of wind speed or pressure are missing are discarded unless one of interpolate_missing or estimate_missing are active.

Some corrections are automatically applied, such as: environmental_pressure is enforced to be larger than central_pressure.

Note that the tracks returned by this function might contain irregular time steps since that is often the case for the original IBTrACS records. Apply the equal_timestep function afterwards to enforce regular time steps.

Parameters
  • provider (str or list of str, optional) – Either specify an agency, such as “usa”, “newdelhi”, “bom”, “cma”, “tokyo”, or the special values “official” and “official_3h”: * “official” means using the (usually 6-hourly) officially reported values of the

    officially responsible agencies.

    • “official_3h” means to include (inofficial) 3-hourly data of the officially responsible agencies (whenever available).

    If you want to restrict to the officially reported values by the officially responsible agencies (provider=”official”) without any modifications to the original official data, make sure to also set estimate_missing=False and interpolate_missing=False. Otherwise, gaps in the official reporting will be filled using interpolation and/or statistical estimation procedures (see below). If a list is given, the following logic is applied: For each storm, the variables that are not reported by the first agency for this storm are taken from the next agency in the list that did report this variable for this storm. For different storms, the same variable might be taken from different agencies. Default: [‘official_3h’, ‘usa’, ‘tokyo’, ‘newdelhi’, ‘reunion’, ‘bom’, ‘nadi’, ‘wellington’, ‘cma’, ‘hko’, ‘ds824’, ‘td9636’, ‘td9635’, ‘neumann’, ‘mlc’]

  • rescale_windspeeds (bool, optional) – If True, all wind speeds are linearly rescaled to 1-minute sustained winds. Note however that the IBTrACS documentation (Section 5.2, https://www.ncdc.noaa.gov/ibtracs/pdf/IBTrACS_version4_Technical_Details.pdf) includes a warning about this kind of conversion: “While a multiplicative factor can describe the numerical differences, there are procedural and observational differences between agencies that can change through time, which confounds the simple multiplicative factor.” Default: True

  • storm_id (str or list of str, optional) – IBTrACS ID of the storm, e.g. 1988234N13299, [1988234N13299, 1989260N11316].

  • year_range (tuple (min_year, max_year), optional) – Year range to filter track selection. Default: (1980, 2018)

  • basin (str, optional) – E.g. US, SA, NI, SI, SP, WP, EP, NA. If not provided, consider all basins.

  • interpolate_missing (bool, optional) – If True, interpolate temporal reporting gaps within a variable (such as pressure, wind speed, or radius) linearly if possible. Temporal interpolation is with respect to the time steps defined in IBTrACS for a particular storm. No new time steps are added that are not originally defined in IBTrACS. For each time step with a missing value, this procedure is only able to fill in that value if there are other time steps before and after this time step for which values have been reported. This procedure will be applied before the statistical estimations referred to by estimate_missing. It is applied to all variables (eye position, wind speed, environmental and central pressure, storm radius and radius of maximum winds). Default: True

  • estimate_missing (bool, optional) – For each fixed time step, estimate missing pressure, wind speed and radius using other variables that are available at that time step. The relationships between the variables are purely statistical. In comparison to interpolate_missing, this procedure is able to estimate values for variables that haven’t been reported by any agency at any time step, as long as other variables are available. A typical example are storms before 1950, for which there are often no reported values for pressure, but for wind speed. In this case, a rough statistical pressure-wind relationship is applied to estimate the missing pressure values from the available wind-speed values. Make sure to set rescale_windspeeds=True when using this option because the statistical relationships are calibrated using rescaled wind speeds. Default: False

  • correct_pres (bool, optional) – For backwards compatibility, alias for estimate_missing. This is deprecated, use estimate_missing instead!

  • file_name (str, optional) – Name of NetCDF file to be dowloaded or located at climada/data/system. Default: ‘IBTrACS.ALL.v04r00.nc’

read_processed_ibtracs_csv(file_names)[source]

Fill from processed ibtracs csv file(s).

Parameters

file_names (str or list of str) – Absolute file name(s) or folder name containing the files to read.

read_simulations_emanuel(file_names, hemisphere='S')[source]

Fill from Kerry Emanuel tracks.

Parameters
  • file_names (str or list of str) – Absolute file name(s) or folder name containing the files to read.

  • hemisphere (str, optional) – ‘S’, ‘N’ or ‘both’. Default: ‘S’

read_one_gettelman(nc_data, i_track)[source]

Fill from Andrew Gettelman tracks.

Parameters
  • nc_data (str) – netCDF4.Dataset Objekt

  • i_tracks (int) – track number

read_simulations_chaz(file_names, year_range=None, ensemble_nums=None)[source]

Read track output from CHAZ simulations

Lee, C.-Y., Tippett, M.K., Sobel, A.H., Camargo, S.J. (2018): An Environmentally Forced Tropical Cyclone Hazard Model. J Adv Model Earth Sy 10(1): 223–241.

Parameters
  • file_names (str or list of str) – Absolute file name(s) or folder name containing the files to read.

  • year_range (tuple (min_year, max_year), optional) – Filter by year, if given.

  • ensemble_nums (list, optional) – Filter by ensembleNum, if given.

read_simulations_storm(path, years=None)[source]

Read track output from STORM simulations

Bloemendaal et al. (2020): Generation of a global synthetic tropical cyclone hazard dataset using STORM. Scientific Data 7(1): 40.

Track data available for download from

Parameters
  • path (str) – Full path to a txt-file as contained in the data.zip archive from the official source linked above.

  • years (list of int, optional) – If given, only read the specified “years” from the txt-File. Note that a “year” refers to one ensemble of tracks in the data set that represents one sample year.

equal_timestep(time_step_h=1, land_params=False)[source]

Generate interpolated track values to time steps of time_step_h.

Parameters
  • time_step_h (float or int, optional) – Temporal resolution in hours (positive, may be non-integer-valued). Default: 1.

  • land_params (bool, optional) – If True, recompute on_land and dist_since_lf at each node. Default: False.

calc_random_walk(**kwargs)[source]

Deprecated. Use TCTracks.calc_perturbed_trajectories instead.

calc_perturbed_trajectories(**kwargs)[source]

See function in climada.hazard.tc_tracks_synth.

property size

Get longitude from coord array.

get_bounds(deg_buffer=0.1)[source]

Get bounds as (lon_min, lat_min, lon_max, lat_max) tuple.

Parameters

deg_buffer (float) – A buffer to add around the bounding box

Returns

bounds

Return type

tuple (lon_min, lat_min, lon_max, lat_max)

property bounds

Exact bounds of trackset as tuple, no buffer.

get_extent(deg_buffer=0.1)[source]

Get extent as (lon_min, lon_max, lat_min, lat_max) tuple.

Parameters

deg_buffer (float) – A buffer to add around the bounding box

Returns

extent

Return type

tuple (lon_min, lon_max, lat_min, lat_max)

property extent

Exact extent of trackset as tuple, no buffer.

plot(axis=None, figsize=(9, 13), legend=True, **kwargs)[source]

Track over earth. Historical events are blue, probabilistic black.

Parameters
  • axis (matplotlib.axes._subplots.AxesSubplot, optional) – axis to use

  • figsize ((float, float), optional) – figure size for plt.subplots The default is (9, 13)

  • legend (bool, optional) – whether to display a legend of Tropical Cyclone categories. Default: True.

  • kwargs (optional) – arguments for LineCollection matplotlib, e.g. alpha=0.5

Returns

axis

Return type

matplotlib.axes._subplots.AxesSubplot

write_netcdf(folder_name)[source]

Write a netcdf file per track with track.sid name in given folder.

Parameters

folder_name (str) – Folder name where to write files.

read_netcdf(folder_name)[source]

Read all netcdf files contained in folder and fill a track per file.

Parameters

folder_name (str) – Folder name where to write files.

to_geodataframe(as_points=False, split_lines_antimeridian=True)[source]

Transform this TCTracks instance into a GeoDataFrame.

Parameters
  • as_points (bool, optional) – If False (default), one feature (row) per track with a LineString or MultiLineString as geometry (or Point geometry for tracks of length one) and all track attributes (sid, name, orig_event_flag, etc) as dataframe columns. If True, one feature (row) per track time step, with variable values per time step (radius_max_wind, max_sustained_wind, etc) as columns in addition to attributes.

  • split_lines_antimeridian (bool, optional) – If True, tracks that cross the antimeridian are split into multiple Lines as a MultiLineString, with each Line on either side of the meridian. This ensures all Lines are within (-180, +180) degrees longitude. Note that lines might be split at more locations than strictly necessary, due to the underlying splitting algorithm (https://github.com/Toblerity/Shapely/issues/572).

Returns

gdf

Return type

GeoDataFrame

climada.hazard.tc_tracks.set_category(max_sus_wind, wind_unit='kn', saffir_scale=None)[source]

Add storm category according to Saffir-Simpson hurricane scale.

Parameters
  • max_sus_wind (np.array) – Maximum sustained wind speed records for a single track.

  • wind_unit (str, optional) – Units of wind speed. Default: ‘kn’.

  • saffir_scale (list, optional) – Saffir-Simpson scale in same units as wind (default scale valid for knots).

Returns

category

Intensity of given track according to the Saffir-Simpson hurricane scale:
  • -1 : tropical depression

  • 0 : tropical storm

  • 1 : Hurricane category 1

  • 2 : Hurricane category 2

  • 3 : Hurricane category 3

  • 4 : Hurricane category 4

  • 5 : Hurricane category 5

Return type

int

climada.hazard.tc_tracks_forecast module

class climada.hazard.tc_tracks_forecast.TCForecast(pool=None)[source]

Bases: climada.hazard.tc_tracks.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)

Type

list(xarray.Dataset)

fetch_ecmwf(path=None, files=None)[source]

Fetch and read latest ECMWF TC track predictions from the FTP dissemination server into instance. Use path argument to use local files instead.

Parameters
  • path (str, list(str)) – 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) – An explicit list of file objects, bypassing get_file_names

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

Returns

[str] or [filelike]

read_one_bufr_tc(file, id_no=None, fcast_rep=None)[source]

Read a single BUFR TC track file.

Parameters
  • file (str, filelike) – Path object, string, or file-like object

  • id_no (int) – Numerical ID; optional. Else use date + random int.

  • fcast_rep (int) – Of the form 1xx000, indicating the delayed replicator containing the forecast values; optional.

climada.hazard.tc_tracks_synth module

climada.hazard.tc_tracks_synth.calc_perturbed_trajectories(tracks, nb_synth_tracks=9, max_shift_ini=0.75, max_dspeed_rel=0.3, max_ddirection=0.008726646259971648, autocorr_dspeed=0.85, autocorr_ddirection=0.5, seed=54, decay=True)[source]

Generate synthetic tracks based on directed random walk. An ensemble of nb_synth_tracks synthetic tracks is computed for every track contained in self.

The methodology perturbs the tracks locations, and if decay is True it additionally includes decay of wind speed and central pressure drop after landfall. No other track parameter is perturbed. The track starting point location is perturbed by random uniform values of magnitude up to max_shift_ini in both longitude and latitude. Then, each segment between two consecutive points is perturbed in direction and distance (i.e., translational speed). These perturbations can be correlated in time, i.e., the perturbation in direction applied to segment i is correlated with the perturbation in direction applied to segment i-1 (and similarly for the perturbation in translational speed). Perturbations in track direction and temporal auto-correlations in perturbations are on an hourly basis, and the perturbations in translational speed is relative. Hence, the parameter values are relatively insensitive to the temporal resolution of the tracks. Note however that all tracks should be at the same temporal resolution, which can be achieved using equal_timestep(). max_dspeed_rel and autocorr_dspeed control the spread along the track (‘what distance does the track run for’), while max_ddirection and autocorr_ddirection control the spread perpendicular to the track movement (‘how does the track diverge in direction’). max_dspeed_rel and max_ddirection control the amplitude of perturbations at each track timestep but perturbations may tend to compensate each other over time, leading to a similar location at the end of the track, while autocorr_dspeed and autocorr_ddirection control how these perturbations persist in time and hence the amplitude of the perturbations towards the end of the track.

Note that the default parameter values have been only roughly calibrated so that the frequency of tracks in each 5x5degree box remains approximately constant. This is not an in-depth calibration and should be treated as such. The object is mutated in-place.

Parameters
  • tracks (climada.hazard.TCTracks) – Tracks data.

  • nb_synth_tracks (int, optional) – Number of ensemble members per track. Default: 9.

  • max_shift_ini (float, optional) – Amplitude of max random starting point shift in decimal degree (up to +/-max_shift_ini for longitude and latitude). Default: 0.75.

  • max_dspeed_rel (float, optional) – Amplitude of translation speed perturbation in relative terms (e.g., 0.2 for +/-20%). Default: 0.3.

  • max_ddirection (float, optional) – Amplitude of track direction (bearing angle) perturbation per hour, in radians. Default: pi/360.

  • autocorr_dspeed (float, optional) – Temporal autocorrelation in translation speed perturbation at a lag of 1 hour. Default: 0.85.

  • autocorr_ddirection (float, optional) – Temporal autocorrelation of translational direction perturbation at a lag of 1 hour. Default: 0.5.

  • seed (int, optional) – Random number generator seed for replicability of random walk. Put negative value if you don’t want to use it. Default: configuration file.

  • decay (bool, optional) – Whether to compute land decay in probabilistic tracks. Default: True.

climada.hazard.trop_cyclone module

class climada.hazard.trop_cyclone.TropCyclone(pool=None)[source]

Bases: climada.hazard.base.Hazard

Contains tropical cyclone events. .. attribute:: 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.array(int)

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(str)

intensity_thres = 17.5

intensity threshold for storage in m/s

vars_opt = {'category'}

Name of the variables that aren’t need to compute the impact.

__init__(pool=None)[source]

Empty constructor.

set_from_tracks(tracks, centroids=None, description='', model='H08', ignore_distance_to_coast=False, store_windfields=False, metric='equirect')[source]

Clear and fill with windfields from specified tracks.

Parameters
  • tracks (TCTracks) – Tracks of storm events.

  • centroids (Centroids, optional) – Centroids where to model TC. Default: global centroids at 360 arc-seconds resolution.

  • description (str, optional) – Description of the event set. Default: “”.

  • model (str, optional) – Model to compute gust. Currently only ‘H08’ is supported for the one implemented in _stat_holland according to Greg Holland. Default: “H08”.

  • ignore_distance_to_coast (boolean, optional) – If True, centroids far from coast are not ignored. Default: False.

  • store_windfields (boolean, optional) – If True, the Hazard object gets a list windfields of sparse matrices. For each track, the full velocity vectors at each centroid and track position are stored in a sparse matrix of shape (npositions, ncentroids * 2) that can be reshaped to a full ndarray of shape (npositions, ncentroids, 2). 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”.

Raises

ValueError

set_climate_scenario_knu(ref_year=2050, rcp_scenario=45)[source]

Compute future events for given RCP scenario and year. RCP 4.5 from Knutson et al 2015. :Parameters: * ref_year (int) – year between 2000 ad 2100. Default: 2050

  • rcp_scenario (int) – 26 for RCP 2.6, 45 for RCP 4.5 (default), 60 for RCP 6.0 and 85 for RCP 8.5.

Returns

TropCyclone

static video_intensity(track_name, tracks, centroids, file_name=None, writer=<matplotlib.animation.PillowWriter object>, figsize=(9, 13), **kwargs)[source]

Generate video of TC wind fields node by node and returns its corresponding TropCyclone instances and track pieces.

Parameters
  • track_name (str) – name of the track contained in tracks to record

  • tracks (TCTracks) – tracks

  • centroids (Centroids) – centroids where wind fields are mapped

  • file_name (str, optional) – file name to save video, if provided

  • writer = (matplotlib.animation., optional*) – video writer. Default: pillow with bitrate=500

  • figsize (tuple, optional) – figure size for plt.subplots

  • kwargs (optional) – arguments for pcolormesh matplotlib function used in event plots

Returns

list(TropCyclone), list(np.array)

Raises

ValueError

frequency_from_tracks(tracks)[source]

Set hazard frequency from tracks data.

Parameters

tracks (list of xarray.Dataset)