climada_petals.engine package

Contents

climada_petals.engine package#

climada_petals.engine.supplychain module#

class climada_petals.engine.supplychain.DirectShocksSet(mriot_name: str, mriot_sectors: Index, mriot_regions: Index, exposure_assets: Series, impacted_assets: DataFrame, event_dates: ndarray, monetary_factor: int, shock_name: str = 'unnamed')[source]#

Bases: object

DirectShocksSet class

The DirectShocksSet class provides methods for ‘translating’ Impact and Exposure objects into economic shocks, corresponding to a specific MRIOT table, from which indirect economic costs can be computed.

mriot_name#

The name of the MRIOT defining the typology of assets.

Type:

str

mriot_sectors#

The list of possible sectors.

Type:

pd.Index

mriot_regions#

The list of possible regions.

Type:

pd.Index

name#

A name to identify the object. For convenience only.

Type:

str, default “unnamed”

monetary_factor#

The monetary factor of the correponding MRIOT.

Type:

int

exposure_assets#

Exposure translated in the region/sector typology of the MRIOT. The index of the Series are the possible (region, sector).

Type:

pd.Series

impacted_assets#

Impact translated in the region/sector typology of the MRIOT. The columns index are the possible (region, sector), and the row index correspond to event_ids of the Impact.

Type:

pd.DataFrame

event_dates#

Series of the dates of the events, as ordinals, with event ids as index.

Type:

pd.Series

__init__(mriot_name: str, mriot_sectors: Index, mriot_regions: Index, exposure_assets: Series, impacted_assets: DataFrame, event_dates: ndarray, monetary_factor: int, shock_name: str = 'unnamed') None[source]#
classmethod combine(direct_shocks: list[DirectShocksSet], kind: Literal['merge', 'concat'] = 'merge', combine_name: str = 'unnamed_combine')[source]#

Combine multiple DirectShocksSet instances into a single instance.

This method supports two modes of combination: merging and concatenating. - In “merge” mode, the direct shocks are summed together for each matching event

and per region/sector.

  • In “concat” mode, the direct shocks are assumed to originate from independent events and are concatenated along the event axis.

Parameters:
  • direct_shocks (list of DirectShocksSet) – A list of DirectShocksSet instances to be combined.

  • kind ({“merge”, “concat”}, optional (Default: “merge”)) – The type of combination to apply. - “merge”: Sum the shocks across all events. - “concat”: Concatenate shocks assuming independent events.

  • combine_name (str, optional) – Name for the combined DirectShocksSet. Default is “unnamed_combine”.

Returns:

A new DirectShocksSet instance representing the combination of the input shocks.

Return type:

DirectShocksSet

Raises:

ValueError – If the DirectShocksSet instances do not share the same mriot_name.

Notes

  • All DirectShocksSet instances must share the same mriot_name.

  • Merging sums the shocks and combines the corresponding impacted and exposed assets.

  • Concatenating assumes independent events and stacks the shocks along the event axis.

Examples

Assuming: - mriot is an IOSystem object representing a MRIOT with (at least) Agriculture and Manufacture sectors. - exp_agri contains exposure data for the Agriculture sector - exp_manu contains exposure data for the for the Manufacture sector. - imp_TC_agri is an Impact object with impacts on the agriculture sector from different tropical cyclones - imp_TC_manu is an Impact object with impacts on the manufacture sector from different tropical cyclones - imp_FL_agri is an Impact object with impacts on the manufacture sector from different floods on the agriculture sector - imp_TC_surges_manu is an Impact object with impacts from surges that occurred during the same tropical cyclones as defined in imp_TC_manu

>>> shocks_TC_agri = DirectShocksSet.from_assets_and_imp(mriot=mriot, exposure=exp_agri, impact=imp_TC_agri, affected_sectors=["Agriculture"])
>>> shocks_TC_manu = DirectShocksSet.from_assets_and_imp(mriot=mriot, exposure=exp_manu, impact=imp_TC_manu, affected_sectors=["Manufacture"])
>>> shocks_FL_agri = DirectShocksSet.from_assets_and_imp(mriot=mriot, exposure=exp_agri, impact=imp_FL_agri, affected_sectors=["Agriculture"])
>>> shocks_TC_surges_manu = DirectShocksSet.from_assets_and_imp(mriot=mriot, exposure=exp_manu, impact=imp_TC_surges_agri, affected_sectors=["Manufacture"])

Assume you want to compute the impacts from TCs on both Agriculture and Manufacture sectors, you can “merge” shocks_TC_agri and shocks_TC_manu for that purpose:

>>> combined_set = DirectShocksSet.combine([shock_TC_agri, shock_TC_manu], kind="merge")

If you want to evaluate the perturbations from TCs and floods on the Agriculture sectors, you can “concat” shocks_TC_agri and shocks_FL_agri for that purpose:

>>> combined_set = DirectShocksSet.combine([shocks_TC_agri, shocks_FL_agri], kind="concat", combine_name="impact from floods and TCs")

Finally if you want to look at the shocks of “co-occurence” of surges and TCs for which the impacts were computed independently, you can merge shocks_TC_manu and shocks_TC_surge_manu.

Of course you can use more that one sectors at once per individual DirectShocksSet. The purpose of this combine method is to allow flexibility with employing different exposure layers and impact computation.

property event_ids_with_impact: Index#

Get the IDs of events that have a non-zero impact on assets.

This property filters the impacted_assets DataFrame to retrieve the indices of rows where at least one asset has a non-zero impact.

Returns:

Index of events with at least one impacted asset.

Return type:

pandas.Index

property exposure_assets_not_null: Series#

Get a subset of the exposure_assets DataFrame containing only non-null exposure.

This property filters the exposure_assets DataFrame to include only rows with non-zero values.

Returns:

A Series containing the impacted assets with non-zero values.

Return type:

pandas.Series

classmethod from_assets_and_imp(mriot: IOSystem, exposure_assets: Series, impact: Impact, shock_name: str | None, affected_sectors: Iterable[str] | dict[str, float] | Series | Literal['all'], impact_distribution: dict[str, float] | Series | None, custom_mriot: bool = False)[source]#

Build a DirectShocksSetfrom an MRIOT, assets Series, and Impact objects.

This method translates the given Impact object to the MRIOT typology (see from_exp_and_imp()).

Parameters:
  • mriot (pymrio.IOSystem) – The MRIOT to use for the typology of region and sectors.

  • exposure_assets (pd.Series) – A pandas Series with (region,sector) as index and assets value.

  • impact (Impact) – The Impact object to derive the impact on assets from.

  • shock_name (str or None) – An optional name to identify the object.

  • affected_sectors (Iterable[str] | dict[str, float] | pd.Series | Literal[“all”]) – The sectors of the MRIOT that are impacted. If given as a collection of string, or “all”, then the total assets of the region are distributed proportionally to each sectors gross output. A dictionary sector:share can also be passed to specify which share of the total regional assets should be distributed to each sector.

  • impact_distribution (dict[str, float] | pd.Series, optional) – This argument specify how the impact per region should be distributed to the impacted sectors. Using None will distribute proportionally to each sectors gross output in the MRIOT. A dictionary in the form sector:share or similarly a Series can be used to specify a custom distribution.

  • custom_mriot (bool) – Whether to consider the MRIOT as a custom one (skips name checking), defaults to False. Note that its regions has to be ISO3 countries name for it to work.

classmethod from_exp_and_imp(mriot: IOSystem, exposure: Exposures, impact: Impact, affected_sectors: Iterable[str] | dict[str, float] | Series | Literal['all'], impact_distribution: dict[str, float] | Series | None, shock_name: str | None = None, exp_value_col: str = 'value', custom_mriot: bool = False)[source]#

Build a DirectShocksSet from MRIOT, Exposure and Impact objects.

This method translates both the given Exposure and Impact objects to the MRIOT typology.pd.Series First, it aggregates exposure values by region_id and then maps them to the regions of the given mriot. Assets are then distributed to the different sectors specified by affected_sectors. It proceeds with a similar process for the Impact object, using impact_distribution to distribute the impact across sectors.

Parameters:
  • mriot (pymrio.IOSystem) – The MRIOT to use for the typology of region and sectors.

  • exposure (Exposures) – The Exposures object to use to derive total assets from.

  • impact (Impact) – The Impact object to derive the impact on assets from.

  • shock_name (str | None) – An optional name to identify the object, defaults to “unnamed”.

  • affected_sectors (Iterable[str] | dict[str, float] | pd.Series | Literal[“all”]) – The sectors of the MRIOT that are impacted. If given as a collection of string, or “all”, then the total assets of the region are distributed proportionally to each sectors gross output. A dictionary sector:share can also be passed to specify which share of the total regional assets should be distributed to each sector.

  • impact_distribution (dict[str, float] | pd.Series, optional) – This argument specify how the impact per region should be distributed to the impacted sectors. Using None will distribute proportionally to each sectors gross output in the MRIOT. A dictionary in the form sector:share or similarly a Series can be used to specify a custom distribution.

  • exp_value_col (str) – The name of the column of the Exposure data representing the value of assets in each centroids.

  • custom_mriot (bool) – Whether to consider the MRIOT as a custom one (skips name checking), defaults to False. Note that its regions has to be ISO3 countries name for it to work.

property impacted_assets_not_null: DataFrame#

Get a subset of the impacted_assets DataFrame containing only non-null impacts.

This property filters the impacted_assets DataFrame to include only rows and columns where at least one non-zero impact exists.

Returns:

A DataFrame containing the impacted assets with non-zero values.

Return type:

pandas.DataFrame

property relative_impact: DataFrame#

The ratio of impacted assets over total assets (0. if total assets are 0.).

property relative_impact_not_null: DataFrame#

Get a subset of the relative_impact DataFrame containing only non-null values.

This property filters the relative_impact DataFrame to include only rows and columns where at least one non-zero impact exists.

Returns:

A DataFrame containing the impacted assets with non-zero values.

Return type:

pandas.DataFrame

class climada_petals.engine.supplychain.IndirectCostModel(mriot: IOSystem, direct_shocks: DirectShocksSet | None = None)[source]#

Bases: ABC

Abstract base class for modeling indirect costs using a Multi-Regional Input-Output Table (MRIOT).

This class provides a structure for incorporating direct shocks into an indirect cost model.

Parameters:
  • mriot (pymrio.IOSystem) – The Multi-Regional Input-Output System used in the model.

  • direct_shocks (DirectShocksSet or None, optional) – The direct shocks to apply to the model. If provided, the model will initialize with these shocks. Default is None.

mriot#

The Multi-Regional Input-Output System used in the model.

Type:

pymrio.IOSystem

direct_shocks#

The direct shocks applied to the model. None if no shocks have been applied.

Type:

DirectShocksSet or None

__init__(mriot: IOSystem, direct_shocks: DirectShocksSet | None = None) None[source]#
shock_model_with(direct_shocks: DirectShocksSet | list[DirectShocksSet], combine_mode: Literal['concat', 'merge'] = 'concat')[source]#

Apply direct shocks to the model, combining them if multiple shocks are provided.

Parameters:
  • direct_shocks (DirectShocksSet or list of DirectShocksSet) – The direct shocks to apply to the model. If a list is provided, the shocks will be combined based on the combine_mode.

  • combine_mode ({“concat”, “merge”}, optional) – The method for combining multiple shocks. Default is “concat”. - “concat”: Concatenate shocks assuming independent events. - “merge”: Merge shocks by summing their impacts for matching (event,region,sector).

Raises:

ValueError – If the MRIOT name of the provided shocks does not match the model’s MRIOT name.

Notes

  • The combine_mode is only applicable if direct_shocks is provided as a list.

  • The shocks must correspond to the same MRIOT used in the model.

class climada_petals.engine.supplychain.StaticIOModel(mriot: IOSystem, direct_shocks: DirectShocksSet | None = None)[source]#

Bases: IndirectCostModel

Static Input-Output Model for analyzing indirect economic impacts.

Extends and makes concrete the IndirectCostModel abstract class by providing methods to calculate degraded economic metrics and indirect impacts using Leontief and Ghosh models.

Parameters:
  • mriot (pymrio.IOSystem) – The Multi-Regional Input-Output System used in the model.

  • direct_shocks (DirectShocksSet or None, optional) – The direct shocks to apply to the model. Default is None.

mriot#

The Multi-Regional Input-Output System used in the model.

Type:

pymrio.IOSystem

direct_shocks#

The direct shocks applied to the model. None if no shocks have been applied.

Type:

DirectShocksSet or None

__init__(mriot: IOSystem, direct_shocks: DirectShocksSet | None = None) None[source]#
calc_ghosh(event_ids: list[int] | Index | None = None) DataFrame[source]#

Computes indirect impacts using the Ghosh model.

Parameters:

event_ids (list[int] or pd.Index or None, optional) – A list of event IDs to calculate impacts for. If None, all events are used.

Returns:

A DataFrame of indirect outputs for the specified events.

Return type:

pd.DataFrame

calc_indirect_impacts(event_ids: list[int] | Index | Literal['with_impact'] | None = 'with_impact') DataFrame | None[source]#

Calculates detailed indirect impacts using both Leontief and Ghosh models.

Parameters:

event_ids (“with_impact” or list[int] or pd.Index or None, default “with_impact”) – A list of event IDs to calculate impacts for. Only events with non null impacts by default. If None, all events are used.

Returns:

A DataFrame containing indirect impacts with various metrics and methods, or None if no shocks are defined for the model.

Return type:

pd.DataFrame or None

calc_leontief(event_ids: list[int] | Index | None = None) DataFrame[source]#

Computes indirect impacts using the Leontief model.

Parameters:

event_ids (list[int] or pd.Index or None, optional) – A list of event IDs to calculate impacts for. If None, all events are used.

Returns:

A DataFrame of indirect outputs for the specified events.

Return type:

pd.DataFrame

property degraded_final_demand: DataFrame | Series#

Calculates and returns the degraded final demand considering the direct shocks.

Returns:

A series representing the degraded final demand by sector.

Return type:

pd.Series

property degraded_value_added: DataFrame | Series#

Calculates and returns the degraded value added considering the direct shocks.

Returns:

A series representing the degraded value added by sector.

Return type:

pd.Series

property final_demand: Series#

Retrieves the (total) final demand addressed to each sectors from the MRIOT.

Returns:

A series representing the final demand by sector.

Return type:

pd.Series

property value_added: Series#

Calculates and returns the value added from the MRIOT.

Returns:

A series representing the value added by sector.

Return type:

pd.Series

class climada_petals.engine.supplychain.BoARIOModel(mriot: IOSystem, direct_shocks: DirectShocksSet, model_kwargs: Dict[str, Any] | None = None, simulation_kwargs: Dict[str, Any] | None = None, event_kwargs: Dict[str, Any] | None = None)[source]#

Bases: IndirectCostModel

BoARIO Model for simulating the economic impacts of shocks using the ARIO model.

Extends and makes concrete the IndirectCostModel abstract class by integrating the ARIOPsiModel and Simulation classes to simulate the effects of direct shocks over time, with customizable event parameters.

Parameters:
  • mriot (pymrio.IOSystem) – The Multi-Regional Input-Output System used in the model.

  • direct_shocks (DirectShocksSet) – The direct shocks to apply to the model.

  • model_kwargs (dict, optional) – A dictionary of model parameters to be passed to the ARIOPsiModel.

  • simulation_kwargs (dict, optional) – A dictionary of simulation parameters to be passed to the Simulation class.

  • event_kwargs (dict, optional) – A dictionary of event-specific parameters (e.g., recovery time) to be passed to the event creation logic.

mriot#

The Multi-Regional Input-Output System used in the model.

Type:

pymrio.IOSystem

model#

The ARIO model used to represent the economy.

Type:

ARIOPsiModel

sim#

The simulation object used to run the model.

Type:

Simulation

direct_shocks#

The direct shocks applied to the model.

Type:

DirectShocksSet or None

Notes

We highly recommend users to go through BoARIO’s documentation <https://spjuhel.github.io/BoARIO>

__init__(mriot: IOSystem, direct_shocks: DirectShocksSet, model_kwargs: Dict[str, Any] | None = None, simulation_kwargs: Dict[str, Any] | None = None, event_kwargs: Dict[str, Any] | None = None) None[source]#
run_sim()[source]#

Run the simulation for the model.

Executes the simulation loop and returns the simulation object.

Returns:

The simulation object after running the simulation loop.

Return type:

Simulation

shock_model_with(direct_shocks: DirectShocksSet | list[DirectShocksSet], combine_mode: Literal['concat', 'merge'] = 'concat', event_kwargs: Dict[str, Any] | None = None)[source]#

Apply direct shocks to the model, adding events for recovery if necessary.

Parameters:
  • direct_shocks (DirectShocksSet or list of DirectShocksSet) – The direct shocks to apply to the model. If a list is provided, the shocks will be combined based on the combine_mode.

  • combine_mode ({“concat”, “merge”}, optional) – The method for combining multiple shocks. Default is “concat”. - “concat”: Concatenate shocks assuming independent events. - “merge”: Merge shocks by summing their impacts.

  • event_kwargs (dict, optional) – A dictionary of event-specific parameters to be passed to event creation. See BoARIO documentation on Events <https://spjuhel.github.io/BoARIO/tutorials/boario-events.html>

climada_petals.engine.supplychain.get_mriot(mriot_type: str, mriot_year: int, redownload: bool = False, save: bool = True)[source]#

Retrieves and optionally saves the Multi-Regional Input-Output Table (MRIOT) for a specified type and year. It handles downloading, parsing, and managing the directory structure for MRIOT files.

Files are stored in the climada data folder, within a “MRIOT” folder by default.

Parameters:
  • mriot_type (str) – The type of MRIOT to retrieve (e.g., “OECD23”).

  • mriot_year (int) – The specific year of the MRIOT to retrieve.

  • redownload (bool, optional) – Indicates whether to force redownload (and parsing) of the data (default is False).

  • save (bool, optional) – Indicates whether to save the processed MRIOT data (default is True).

Returns:

The loaded or newly parsed MRIOT represented as an IOSystem.

Return type:

pymrio.IOSystem

Notes

The function manages both the downloading of the MRIOT data and the parsing of the data into an appropriate format. If the data for the specified year and type is already available, it will load the existing data unless redownload is set to True. If the data must be parsed, it can optionally be saved to the designated location.

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