climada_petals.engine package#

climada_petals.engine.supplychain module#

class climada_petals.engine.supplychain.SupplyChain(mriot)[source]#

Bases: object

SupplyChain class.

The SupplyChain class provides methods for loading Multi-Regional Input-Output Tables (MRIOT) and computing direct, indirect and total impacts.

mriot#
An object containing all MRIOT related info (see also pymrio package):

mriot.Z : transaction matrix, or interindustry flows matrix mriot.Y : final demand mriot.x : industry or total output mriot.meta : metadata

Type:

pymrio.IOSystem

secs_exp#

Exposure dataframe of each country/sector in the MRIOT. Columns are the same as the chosen MRIOT.

Type:

pd.DataFrame

secs_imp#

Impact dataframe for the directly affected countries/sectors for each event with impacts. Columns are the same as the chosen MRIOT and rows are the hazard events ids.

Type:

pd.DataFrame

secs_shock#

Shocks (i.e. impact / exposure) dataframe for the directly affected countries/sectors for each event with impacts. Columns are the same as the chosen MRIOT and rows are the hazard events ids.

Type:

pd.DataFrame

inverse#

Dictionary with keys being the chosen approach (ghosh, leontief or eeioa) and values the Leontief (L, if approach is leontief or eeioa) or Ghosh (G, if approach is ghosh) inverse matrix.

Type:

dict

coeffs#

Dictionary with keys being the chosen approach (ghosh, leontief or eeioa) and values the Technical (A, if approach is leontief or eeioa) or allocation (B, if approach is ghosh) coefficients matrix.

Type:

dict

supchain_imp#

Dictionary with keys the chosen approach (ghosh, leontief or eeioa) and values dataframes of indirect impacts to countries/sectors for each event with direct impacts. For each dataframe, columns are the same as the chosen MRIOT and rows are the hazard events ids.

Type:

dict

__init__(mriot)[source]#

Initialize SupplyChain.

Parameters:

mriot (pymrio.IOSystem) –

An object containing all MRIOT related info (see also pymrio package):

mriot.Z : transaction matrix, or interindustry flows matrix mriot.Y : final demand mriot.x : industry or total output mriot.meta : metadata

classmethod from_mriot(mriot_type, mriot_year, mriot_dir=PosixPath('/home/docs/climada/data/MRIOT'), del_downloads=True)[source]#

Download, parse and read WIOD16, EXIOBASE3, or OECD21 Multi-Regional Input-Output Tables.

Parameters:
  • mriot_type (str) – Type of mriot table to use. The three possible types are: ‘EXIOBASE3’, ‘WIOD16’, ‘OECD21’

  • mriot_year (int) – Year of MRIOT

  • mriot_dir (pathlib.PosixPath) – Path to the MRIOT folder. Default is CLIMADA storing directory.

  • del_downloads (bool) – If the downloaded files are deleted after saving the parsed data. Default is True. WIOD16 and OECD21 data are downloaded as group of years.

Returns:

mriot

An object containing all MRIOT related info (see also pymrio package):

mriot.Z : transaction matrix, or interindustry flows matrix mriot.Y : final demand mriot.x : total output mriot.meta : metadata

Return type:

pymrio.IOSystem

calc_shock_to_sectors(exposure, impact, impacted_secs=None, shock_factor=None)[source]#

Calculate exposure, impact and shock at the sectorial level. This function translate spatially-distrubted exposure and impact information into exposure and impact of MRIOT’s country/sectors and for each hazard event.

Parameters:
  • exposure (climada.entity.Exposure) – CLIMADA Exposure object of direct impact calculation

  • impact (climada.engine.Impact) – CLIMADA Impact object of direct impact calculation

  • impacted_secs ((range, np.ndarray, str, list)) – Information regarding the impacted sectors. This can be provided as positions of the impacted sectors in the MRIOT (as range or np.ndarray) or as sector names (as string or list).

  • shock_factor (np.array) – It has lenght equal to the number of sectors. For each sector, it defines to what extent the fraction of indirect losses differs from the one of direct losses (i.e., impact / exposure). Deafult value is None, which means that shock factors for all sectors are equal to 1, i.e., that production and stock losses fractions are the same.

calc_matrices(io_approach)[source]#

Build technical coefficient and Leontief inverse matrixes (if leontief or eeioa approach) or allocation coefficients and Ghosh matrixes (if ghosh approach).

Parameters:

io_approach (str) – The adopted input-output modeling approach. Possible choices are ‘leontief’, ‘ghosh’ and ‘eeioa’.

calc_impacts(io_approach, exposure=None, impact=None, impacted_secs=None)[source]#

Calculate indirect production impacts based on to the chosen input-output approach.

Parameters:
  • io_approach (str) – The adopted input-output modeling approach. Possible choices are ‘leontief’, ‘ghosh’ and ‘eeioa’.

  • exposure (climada.entity.Exposure) – CLIMADA Exposure object of direct impact calculation. Default is None.

  • impact (climada.engine.Impact) – CLIMADA Impact object of direct impact calculation. Default is None.

  • impacted_secs ((range, np.ndarray, str, list)) – Information regarding the impacted sectors. This can be provided as positions of the impacted sectors in the MRIOT (as range or np.ndarray) or as sector names (as string or list). Default is None.

  • shock_factor (np.array) – It has lenght equal to the number of sectors. For each sector, it defines to what extent the fraction of indirect losses differs from the one of direct losses (i.e., impact / exposure). Deafult value is None, which means that shock factors for all sectors are equal to 1, i.e., that production and stock losses fractions are the same.

References

[1] W. W. Leontief, Output, employment, consumption, and investment, The Quarterly Journal of Economics 58, 1944. [2] Ghosh, A., Input-Output Approach in an Allocation System, Economica, New Series, 25, no. 97: 58-64. doi:10.2307/2550694, 1958. [3] Kitzes, J., An Introduction to Environmentally-Extended Input-Output Analysis, Resources, 2, 489-503; doi:10.3390/resources2040489, 2013.

map_exp_to_mriot(exp_regid, mriot_type)[source]#

Map regions names in exposure into Input-Output regions names. exp_regid must follow ISO 3166 numeric country codes.

climada_petals.engine.warn module#

climada_petals.engine.warn.dilation(bin_map, size)[source]#

Dilate binary input map. The operation is based on a convolution. During translation of the filter, a point is included to the region (changed or kept to 1), if one or more elements correspond with the filter. Else, it is 0. This results in more and larger regions of interest. Larger filter sizes - more area of interest. For more information: https://scikit-image.org/docs/stable/auto_examples/applications/plot_morphology.html

Parameters:
  • bin_map (np.ndarray) – Rectangle 2d map of values which are used to generate the warning.

  • size (int) – Size of filter.

Returns:

Generated binary map with enlarged regions of interest.

Return type:

np.ndarray

climada_petals.engine.warn.erosion(bin_map, size)[source]#

Erode binary input map. The operation is based on a convolution. During translation of the filter, a point is included to the region (changed or kept to 1), if all elements correspond with the filter. Else, it is 0. This results in less and smaller regions of interest and reduces heterogeneity in map. Larger sizes - more reduction. For more information: https://scikit-image.org/docs/stable/auto_examples/applications/plot_morphology.html

Parameters:
  • bin_map (np.ndarray) – Rectangle 2d map of values which are used to generate the warning.

  • size (int) – Size of filter.

Returns:

Generated binary map with reduced regions of interest.

Return type:

np.ndarray

climada_petals.engine.warn.median_filtering(bin_map, size)[source]#

Smooth binary input map. The operation is based on a convolution. During translation of the filter, a point is included to the region (changed or kept to 1), if the median of the filter is 1. Else, it is 0. This results in smoother regions of interest and reduces heterogeneity in map. Larger sizes - smoother regions.

Parameters:
  • bin_map (np.ndarray) – Rectangle 2d map of values which are used to generate the warning.

  • size (int) – Size of filter.

Returns:

Generated binary map with smoothed regions of interest.

Return type:

np.ndarray

class climada_petals.engine.warn.Operation(value)[source]#

Bases: Enum

Available Operations. Links operations to functions. More operations can be added.

dilation#

Links to dilation operation.

Type:

function

erosion#

Links to erosion operation.

Type:

function

median_filtering#

Links to median filtering operation.

Type:

function

dilation = functools.partial(<function dilation>)#
erosion = functools.partial(<function erosion>)#
median_filtering = functools.partial(<function median_filtering>)#
class climada_petals.engine.warn.Warn(warning, coord, warn_params)[source]#

Bases: object

Warn definition. Generate a warning, i.e., 2D map of coordinates with assigned warn levels. Operations, their order, and their influence (filter sizes) can be selected to generate the warning. Further properties can be chosen which define the warning generation. The functionality of reducing heterogeneity in a map can be applied to different inputs, e.g. MeteoSwiss windstorm data (COSMO data), TCs, impacts, etc.

warning#

Warning generated by warning generation algorithm. Warn level for every coordinate of map.

Type:

np.ndarray

coord#

Coordinates of warning map.

Type:

np.ndarray

warn_levels#

Warn levels that define the bins in which the input_map will be classified in. E.g., for windspeeds: [0, 10, 40, 80, 150, 200.0]

Type:

list

class WarnParameters(warn_levels: ~typing.List[float], operations: ~typing.List[~typing.Tuple[~climada_petals.engine.warn.Operation, int]] = <factory>, gradual_decr: bool = False, change_sm: bool = False)[source]#

Bases: object

WarnParameters data class definition. It stores the relevant information needed during the warning generation. The operations and its sizes, as well as the algorithms properties $(gradual decrease of warning levels and changing of small warning regions formed) are saved.

warn_levels#

Warn levels that define the bins in which the input_map will be classified in.

Type:

list

operations#

Tuples saving operations and their filter sizes to be applied in filtering algorithm.

Type:

list

gradual_decr#

Defines whether the highest warn levels should be gradually decreased by its neighboring regions (if True) to the lowest level (e.g., level 3, 2, 1, 0) or larger steps are allowed (e.g., from warn level 5 directly to 1).

Type:

bool

change_sm#

If strictly larger than 1, the levels of too small regions are changed to its surrounding levels. If 0 or None, the levels are not changed.

Type:

int

warn_levels: List[float]#
operations: List[Tuple[Operation, int]]#
gradual_decr: bool = False#
change_sm: bool = False#
__init__(warn_levels: ~typing.List[float], operations: ~typing.List[~typing.Tuple[~climada_petals.engine.warn.Operation, int]] = <factory>, gradual_decr: bool = False, change_sm: bool = False) None#
__init__(warning, coord, warn_params)[source]#

Initialize Warn.

Parameters:
  • warning (np.ndarray) – Warn level for every coordinate of input map.

  • coord (np.ndarray) – Coordinates of warning map.

  • warn_params (WarnParameters) – Contains information on how to generate the warning (operations and details).

classmethod from_map(input_map, coord, warn_params)[source]#

Generate Warn object from map (value (e.g., windspeeds at coordinates).

Parameters:
  • input_map (np.ndarray) – Rectangle 2d map of values which are used to generate the warning.

  • coord (np.ndarray) – Coordinates of warning map. For every value of the map exactly one coordinate is needed.

  • warn_params (WarnParameters) – Contains information on how to generate the warning (operations and details).

Returns:

warn – Generated Warn object including warning, coordinates, warn levels, and metadata.

Return type:

Warn

classmethod wind_from_cosmo(path_to_cosmo, warn_params, lead_time, quant_nr=0.7)[source]#

Generate Warn object from COSMO windspeed data. The warn object is computed for the given date and time. The ensemble members of that date and time are grouped together to a single windspeed map.

Parameters:
  • path_to_cosmo (string) – Path including name to cosmo file.

  • warn_params (WarnParameters) – Contains information on how to generate the warning (operations and details).

  • lead_time (datetime) – Lead time when warning should be generated.

  • quant_nr (float) – Quantile number to group ensemble members of COSMO wind speeds.

Returns:

warn – Generated Warn object including warning, coordinates, warn levels, and metadata.

Return type:

Warn

classmethod from_hazard(hazard, warn_params)[source]#

Generate Warn object from hazard object. The intensity map is used therefore. It needs to be transferable to a dense matrix, else the computation of the warning is impossible.

Parameters:
  • hazard (Hazard) – Contains the information of which to generate a warning from.

  • warn_params (WarnParameters) – Contains information on how to generate the warning (operations and details).

Returns:

warn – Generated Warn object including warning, coordinates, warn levels, and metadata.

Return type:

Warn

static bin_map(input_map, levels)[source]#

Bin every value of input map into given levels.

Parameters:
  • input_map (np.ndarray) – Array containing data to generate binned map of.

  • levels (list) – List with levels to bin input map.

Returns:

binned_map – Map of binned values in levels, same shape as input map.

Return type:

np.ndarray

static zeropadding(lat, lon, val, res_rel_error=0.01)[source]#

Produces a rectangular shaped map from a non-rectangular map (e.g., country). For this, a regular grid is created in the rectangle enclosing the non-rectangular map. The values are mapped onto the regular grid according to their coordinates. The regular gird is filled with zeros where no values are defined. are defined. This only works if the lat lon values of the non-rectangular map can be accurately represented on a grid with a regular resolution.

Parameters:
  • lat (list) – Latitudes of values of map.

  • lon (list) – Longitudes of values of map.

  • val (list) – Values of quantity of interest at every coordinate given.

  • res_rel_error (float) – defines the relative error in terms of grid resolution by which the lat lon values of the returned coord_rec can maximally differ from the provided lat lon values. Default: 0.01

Returns:

  • map_rec (np.ndarray) – Rectangular map with a value for every grid point. Padded with zeros where no values in input map.

  • coord_rec (np.ndarray) – Longitudes and Latitudes of every value of the map.

plot_warning(var_name='Warn Levels', title='Categorical Warning Map', cat_name=None, adapt_fontsize=True, **kwargs)[source]#

Map plots for categorical data defined in array(s) over input coordinates. The categories must be a finite set of unique values as can be identified by np.unique() (mix of int, float, strings, …).

The categories are shared among all subplots, i.e. are obtained from np.unique(array_sub). Eg.:

>>> array_sub = [[1, 2, 1.0, 2], [1, 2, 'a', 'a']]
>>> -> category mapping is [[0, 2, 1, 2], [0, 2, 3, 3]]

Same category: 1 and ‘1’ Different categories: 1 and 1.0

This method wraps around util.geo_scatter_from_array and uses all its args and kwargs.

Parameters:
  • var_name (str or list(str)) – label to be shown in the colorbar. If one provided, the same is used for all subplots. Otherwise provide as many as subplots in array_sub.

  • title (str or list(str)) – subplot title. If one provided, the same is used for all subplots. Otherwise provide as many as subplots in array_sub.

  • cat_name (dict, optional) – Categories name for the colorbar labels. Keys are all the unique values in array_sub, values are their labels. The default is labels = unique values.

  • adapt_fontsize (bool, optional) – If set to true, the size of the fonts will be adapted to the size of the figure. Otherwise the default matplotlib font size is used. Default is True.

  • **kwargs – Arbitrary keyword arguments for hexbin matplotlib function

Return type:

cartopy.mpl.geoaxes.GeoAxesSubplot

plot_warning_meteoswiss_style(var_name='Warn Levels', title='Categorical Warning Map', cat_name=None, adapt_fontsize=True)[source]#

Map plots for categorical data defined in array(s) over input coordinates. The MeteoSwiss coloring scheme is used, therefore only 5 warn levels are allowed.

This method wraps around util.geo_scatter_from_array and uses all its args and kwargs.

Parameters:
  • var_name (str or list(str)) – label to be shown in the colorbar. If one provided, the same is used for all subplots. Otherwise provide as many as subplots in array_sub.

  • title (str or list(str)) – subplot title. If one provided, the same is used for all subplots. Otherwise provide as many as subplots in array_sub.

  • cat_name (dict, optional) – Categories name for the colorbar labels. Keys are all the unique values in array_sub, values are their labels. The default is labels = unique values.

  • adapt_fontsize (bool, optional) – If set to true, the size of the fonts will be adapted to the size of the figure. Otherwise the default matplotlib font size is used. Default is True.

  • **kwargs – Arbitrary keyword arguments for hexbin matplotlib function

Return type:

cartopy.mpl.geoaxes.GeoAxesSubplot