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 region/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) and values the Leontief (L, if approach is leontief) or Ghosh (G, if approach is ghosh) inverse matrix.

Type:

dict

coeffs#

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

Type:

dict

sim#

Boario’s simulation object. Only relevant when io_approach in “boario_aggregated” or “boario_disaggregated”. Default is None.

Type:

boario.simulation.Simulation

events_date#

Integer date corresponding to the proleptic Gregorian ordinal, where January 1 of year 1 has ordinal 1 (ordinal format of datetime library) of events leading to impact. Deafult is None.

Type:

np.array

supchain_imp#

Dictionary with keys the chosen approach (ghosh, leontief or boario and its variations) and values dataframes of production losses (ghosh, leontief) or production dynamics (boario and its variations) to countries/sectors for each event. 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.

Notes

EXIOBASE3 different world regions (WA, WF, WL, WM and WE) are aggregated to a single Rest of the World (ROW) region.

Sometime, the Change In Inventory (CII) column of final demand lead to total final demand being negative, which causes problem with some indirect impact computation. Current solution is to set CII to 0 for (region,sector) where final demand is negative. In such a case, production vector is recomputed accordingly, and a warning is raised.

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-distributed exposure and impact information into exposure and impact in the MRIOT’s region/sectors typology, 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) – Array length should equal the number of sectors. For each sector, it defines by which factor the ratio of direct losses over exposure translate into an economic shock (on production, final demand, capital stock, depending on the indirect impact method used). By default, the value is None, and the factor is 1 for all sectors.

calc_matrices(io_approach)[source]#

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

Parameters:

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

calc_impacts(io_approach, exposure=None, impact=None, impacted_secs=None, shock_factor=None, boario_params={}, boario_type='recovery', boario_aggregate='agg')[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’ or ‘boario’ ‘boario_recovery’, ‘boario_rebuild’ and ‘boario_shockprod’.

  • 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 length 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.

  • boario_params (dict) – Dictionary containing parameters to instantiate boario’s ARIOPsiModel (key ‘model’), Simulation (key ‘sim’) and Event (key ‘event’) classes. Parameters instantiating each class need to be stored in a dictionary, e.g., {‘model’: {}, ‘sim’: {}, ‘event’: {}}. You can also specify “show_progress=False” to remove the progress bar during simulations. Only meangingful when io_approach=’boario’. Default is None.

  • boario_type (str) – The chosen boario type. Possible choices are ‘recovery’, ‘rebuild’ and ‘production_shock’. Only meaningful when io_approach=’boario’. Default ‘recovery’.

  • boario_aggregate (str) – Whether events are aggregated or not. Possible choices are ‘agg’ or ‘sep’. Only meaningful when io_approach=’boario’. Default is ‘agg’.

Notes

  • The Leontief approach assumes the shock to degrade the final demand, and computes the resulting changed production.

  • The Ghosh approach assumes the shock to impact value added, and computes the resulting production.

  • The BoARIO approach assumes the shock to incapacitate productive capital (and possibly generate a reconstruction demand with boario_type="rebuild") and computes the change of production over time with the ARIO model. See the BoARIO documentation for more details (Note that not all features of BoARIO are included yet).

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.

conversion_factor()[source]#

Conversion factor based on unit specified in the Multi-Regional Input-Output Table.

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