climada.engine package¶
climada.engine.calibration_opt module¶
-
climada.engine.calibration_opt.calib_instance(hazard, exposure, impact_func, df_out=Empty DataFrame Columns: [] Index: [], yearly_impact=False, return_cost='False')[source]¶ calculate one impact instance for the calibration algorithm and write to given DataFrame
- Parameters
hazard – hazard set instance
exposure – exposure set instance
impact_func – impact function instance
- Optional Parameters:
- df_out: Output DataFrame with headers of columns defined and optionally with
first row (index=0) defined with values. If columns “impact”, “event_id”, or “year” are not included, they are created here. Data like reported impacts or impact function parameters can be given here; values are preserved.
- yearly_impact (boolean): if set True, impact is returned per year,
not per event
- return_cost: if not ‘False’ but any of ‘R2’, ‘logR2’,
cost is returned instead of df_out
- Returns
- DataFrame with modelled impact written to rows for each year
or event.
- Return type
df_out
-
climada.engine.calibration_opt.init_if(if_name_or_instance, param_dict, df_out=Empty DataFrame Columns: [] Index: [0])[source]¶ create an ImpactFunc based on the parameters in param_dict using the method specified in if_parameterisation_name and document it in df_out.
- Parameters
if_name_or_instance (str or ImpactFunc) – method of impact function parameterisation e.g. ‘emanuel’ or an instance of ImpactFunc
param_dict (dict of parameter_names and values) – e.g. {‘v_thresh’: 25.7, ‘v_half’: 70, ‘scale’: 1} or {‘mdd_shift’: 1.05, ‘mdd_scale’: 0.8, ‘paa_shift’: 1, paa_scale’: 1}
- Returns
imp_fun (ImpactFunc) – The Impact function based on the parameterisation
df_out (DataFrame) – Output DataFrame with headers of columns defined and with first row (index=0) defined with values. The impact function parameters from param_dict are represented here.
-
climada.engine.calibration_opt.change_if(if_instance, param_dict)[source]¶ apply a shifting or a scaling defined in param_dict to the impact function in if_istance and return it as a new ImpactFunc object. :Parameters: * if_instance (ImpactFunc) – an instance of ImpactFunc
param_dict – dict of parameter_names and values (interpreted as
factors, 1 = neutral) –
- e.g. {‘mdd_shift’: 1.05, ‘mdd_scale’: 0.8,
‘paa_shift’: 1, paa_scale’: 1}
- Returns
The Impact function based on the parameterisation
- Return type
-
climada.engine.calibration_opt.init_impact_data(hazard_type, region_ids, year_range, source_file, reference_year, impact_data_source='emdat', yearly_impact=True)[source]¶ creates a dataframe containing the recorded impact data for one hazard type and one area (countries, country or local split) :Parameters: * hazard_type – default = ‘TC’, type of hazard ‘WS’,’FL’ etc.
region_ids – name the region_ids or country names
year_range (list) – list containting start and end year. e.g. [1980, 2017]
reference_year – impacts will be scaled to this year
impact_data_source – default ‘emdat’, others maybe possible
- Optional Parameters:
- yearly_impact (boolean): if set True, impact is returned per year,
not per event
- Returns
- DataFrame with recorded impact written to rows for each year
or event.
- Return type
df_out
-
climada.engine.calibration_opt.calib_cost_calc(df_out, cost_function)[source]¶ calculate the cost function of the modelled impact impact_CLIMADA and the reported impact impact_scaled in df_out :Parameters: * df_out (pd.Dataframe) – DataFrame as created in calib_instance
cost_function (str) – chooses the cost function e.g. ‘R2’ or ‘logR2’
- Returns
- the results of the cost function when comparing modelled and
reported impact
- Return type
cost
-
climada.engine.calibration_opt.calib_all(hazard, exposure, if_name_or_instance, param_full_dict, impact_data_source, year_range, yearly_impact=True)[source]¶ portrait the difference between modelled and reported impacts for all impact functions described in param_full_dict and if_name_or_instance :Parameters: * hazard – list or instance of hazard
exposure – list or instance of exposure of full countries
if_name_or_instance (string or ImpactFunc) – the name of a parameterisation or an instance of class ImpactFunc e.g. ‘emanuel’
param_full_dict (dict) – a dict containing keys used for if_name_or_instance and values which are iterable (lists) e.g. {‘v_thresh’: [25.7, 20], ‘v_half’: [70], ‘scale’: [1, 0.8]}
impact_data_source (dict or dataframe) – with name of impact data source and file location or dataframe
year_range
yearly_impact
- Returns
- DataFrame with modelled impact written to rows for each year
or event.
- Return type
df_result
-
climada.engine.calibration_opt.calib_optimize(hazard, exposure, if_name_or_instance, param_dict, impact_data_source, year_range, yearly_impact=True, cost_fucntion='R2', show_details=False)[source]¶ portrait the difference between modelled and reported impacts for all impact functions described in param_full_dict and if_name_or_instance :Parameters: * hazard – list or instance of hazard
exposure – list or instance of exposure of full countries
if_name_or_instance (string or ImpactFunc) – the name of a parameterisation or an instance of class ImpactFunc e.g. ‘emanuel’
param_dict (dict) – a dict containing keys used for if_name_or_instance and one set of values e.g. {‘v_thresh’: 25.7, ‘v_half’: 70, ‘scale’: 1}
impact_data_source (dict or dataframe) – with name of impact data source and file location or dataframe
year_range
yearly_impact
cost_function (string) – the argument for function calib_cost_calc, default ‘R2’
show_details (bool) – if True, return a tuple with the parameters AND the details of the optimization like success, status, number of iterations etc
- Returns
- the parameters with the best calibration results
(or a tuple with (1) the parameters and (2) the optimization output)
- Return type
param_dict_result
climada.engine.cost_benefit module¶
-
class
climada.engine.cost_benefit.CostBenefit[source]¶ Bases:
objectImpact definition. Compute from an entity (exposures and impact functions) and hazard.
-
present_year¶ present reference year
- Type
int
-
future_year¶ future year
- Type
int
-
tot_climate_risk¶ total climate risk without measures
- Type
float
-
unit¶ unit used for impact
- Type
str
-
color_rgb¶ color code RGB for each measure. Key: measure name (‘no measure’ used for case without measure), Value: np.array
- Type
dict
-
benefit¶ benefit of each measure. Key: measure name, Value: float benefit
- Type
dict
-
cost_ben_ratio¶ cost benefit ratio of each measure. Key: measure name, Value: float cost benefit ratio
- Type
dict
-
imp_meas_future¶ impact of each measure at future or default. Key: measure name (‘no measure’ used for case without measure), Value: dict with:
‘cost’ (tuple): (cost measure, cost factor insurance), ‘risk’ (float): risk measurement, ‘risk_transf’ (float): annual expected risk transfer, ‘efc’ (ImpactFreqCurve): impact exceedance freq
(optional) ‘impact’ (Impact): impact instance
- Type
dict
-
imp_meas_present¶ impact of each measure at present. Key: measure name (‘no measure’ used for case without measure), Value: dict with:
‘cost’ (tuple): (cost measure, cost factor insurance), ‘risk’ (float): risk measurement, ‘risk_transf’ (float): annual expected risk transfer, ‘efc’ (ImpactFreqCurve): impact exceedance freq
(optional) ‘impact’ (Impact): impact instance
- Type
dict
-
calc(hazard, entity, haz_future=None, ent_future=None, future_year=None, risk_func=<function risk_aai_agg>, imp_time_depen=None, save_imp=False)[source]¶ Compute cost-benefit ratio for every measure provided current and, optionally, future conditions. Present and future measures need to have the same name. The measures costs need to be discounted by the user. If future entity provided, only the costs of the measures of the future and the discount rates of the present will be used.
- Parameters
hazard (Hazard) – hazard
entity (Entity) – entity
haz_future (Hazard, optional) – hazard in the future (future year provided at ent_future)
ent_future (Entity, optional) – entity in the future
future_year (int, optional) – future year to consider if no ent_future provided. The benefits are added from the entity.exposures.ref_year until ent_future.exposures.ref_year, or until future_year if no ent_future given. Default: entity.exposures.ref_year+1
risk_func (func, optional) – function describing risk measure to use to compute the annual benefit from the Impact. Default: average annual impact (aggregated).
imp_time_depen (float, optional) – parameter which represents time evolution of impact (super- or sublinear). If None: all years count the same when there is no future hazard nor entity and 1 (linear annual change) when there is future hazard or entity. Default: None.
save_imp (bool, optional) – True if Impact of each measure is saved. Default: False.
-
combine_measures(in_meas_names, new_name, new_color, disc_rates, imp_time_depen=None, risk_func=<function risk_aai_agg>)[source]¶ Compute cost-benefit of the combination of measures previously computed by calc with save_imp=True. The benefits of the measures per event are added. To combine with risk transfer options use apply_risk_transfer.
- Parameters
in_meas_names (list(str)) – list with names of measures to combine
new_name (str) – name to give to the new resulting measure
new_color (np.array) – color code RGB for new measure, e.g. np.array([0.1, 0.1, 0.1])
disc_rates (DiscRates) – discount rates instance
imp_time_depen (float, optional) – parameter which represents time evolution of impact (super- or sublinear). If None: all years count the same when there is no future hazard nor entity and 1 (linear annual change) when there is future hazard or entity. Default: None.
risk_func (func, optional) – function describing risk measure given an Impact. Default: average annual impact (aggregated).
- Returns
CostBenefit
-
apply_risk_transfer(meas_name, attachment, cover, disc_rates, cost_fix=0, cost_factor=1, imp_time_depen=None, risk_func=<function risk_aai_agg>)[source]¶ Applies risk transfer to given measure computed before with saved impact and compares it to when no measure is applied. Appended to dictionaries of measures.
- Paramters:
meas_name (str): name of measure where to apply risk transfer attachment (float): risk transfer values attachment (deductible) cover (float): risk transfer cover cost_fix (float): fixed cost of implemented innsurance, e.g.
transaction costs
- cost_factor (float): factor to which to multiply the insurance layer
to compute its cost. Default: 1
- imp_time_depen (float, optional): parameter which represents time
evolution of impact (super- or sublinear). If None: all years count the same when there is no future hazard nor entity and 1 (linear annual change) when there is future hazard or entity. Default: None.
- risk_func (func, optional): function describing risk measure given
an Impact. Default: average annual impact (aggregated).
-
remove_measure(meas_name)[source]¶ Remove computed values of given measure
- Parameters
meas_name (str) – name of measure to remove
-
plot_cost_benefit(cb_list=None, axis=None, **kwargs)[source]¶ Plot cost-benefit graph. Call after calc().
- Parameters
cb_list (list(CostBenefit), optional) – if other CostBenefit provided, overlay them all. Used for uncertainty visualization.
axis (matplotlib.axes._subplots.AxesSubplot, optional) – axis to use
kwargs (optional) – arguments for Rectangle matplotlib, e.g. alpha=0.5 (color is set by measures color attribute)
- Returns
matplotlib.axes._subplots.AxesSubplot
-
plot_event_view(return_per=(10, 25, 100), axis=None, **kwargs)[source]¶ Plot averted damages for return periods. Call after calc().
- Parameters
return_per (list, optional) – years to visualize. Default 10, 25, 100
axis (matplotlib.axes._subplots.AxesSubplot, optional) – axis to use
kwargs (optional) – arguments for bar matplotlib function, e.g. alpha=0.5 (color is set by measures color attribute)
- Returns
matplotlib.axes._subplots.AxesSubplot
-
static
plot_waterfall(hazard, entity, haz_future, ent_future, risk_func=<function risk_aai_agg>, axis=None, **kwargs)[source]¶ Plot waterfall graph at future with given risk metric. Can be called before and after calc().
- Parameters
hazard (Hazard) – hazard
entity (Entity) – entity
haz_future (Hazard) – hazard in the future (future year provided at ent_future)
ent_future (Entity) – entity in the future
risk_func (func, optional) – function describing risk measure given an Impact. Default: average annual impact (aggregated).
axis (matplotlib.axes._subplots.AxesSubplot, optional) – axis to use
kwargs (optional) – arguments for bar matplotlib function, e.g. alpha=0.5
- Returns
matplotlib.axes._subplots.AxesSubplot
-
plot_arrow_averted(axis, in_meas_names=None, accumulate=False, combine=False, risk_func=<function risk_aai_agg>, disc_rates=None, imp_time_depen=1, **kwargs)[source]¶ Plot waterfall graph with accumulated values from present to future year. Call after calc() with save_imp=True.
- Parameters
axis (matplotlib.axes._subplots.AxesSubplot) – axis from plot_waterfall or plot_waterfall_accumulated where arrow will be added to last bar
in_meas_names (list(str), optional) – list with names of measures to represented total averted damage. Default: all measures
accumulate (bool, optional) – accumulated averted damage (True) or averted damage in future (False). Default: False
combine (bool, optional) – use combine_measures to compute total averted damage (True) or just add benefits (False). Default: False
risk_func (func, optional) – function describing risk measure given an Impact used in combine_measures. Default: average annual impact (aggregated).
disc_rates (DiscRates, optional) – discount rates used in combine_measures
imp_time_depen (float, optional) – parameter which represent time evolution of impact used in combine_measures. Default: 1 (linear).
kwargs (optional) – arguments for bar matplotlib function, e.g. alpha=0.5
-
plot_waterfall_accumulated(hazard, entity, ent_future, risk_func=<function risk_aai_agg>, imp_time_depen=1, axis=None, **kwargs)[source]¶ Plot waterfall graph with accumulated values from present to future year. Call after calc() with save_imp=True. Provide same inputs as in calc.
- Parameters
hazard (Hazard) – hazard
entity (Entity) – entity
ent_future (Entity) – entity in the future
risk_func (func, optional) – function describing risk measure given an Impact. Default: average annual impact (aggregated).
imp_time_depen (float, optional) – parameter which represent time evolution of impact. Default: 1 (linear).
axis (matplotlib.axes._subplots.AxesSubplot, optional) – axis to use
kwargs (optional) – arguments for bar matplotlib function, e.g. alpha=0.5
- Returns
matplotlib.axes._subplots.AxesSubplot
-
-
climada.engine.cost_benefit.risk_aai_agg(impact)[source]¶ Risk measurement as average annual impact aggregated.
- Parameters
impact (Impact) – an Impact instance
- Returns
float
climada.engine.forecast module¶
-
class
climada.engine.forecast.Forecast(hazard_dict, exposure, impact_funcs, haz_model='NWP', exposure_name=None)[source]¶ Bases:
objectForecast definition. Compute an impact forecast with predefined hazard originating from a forecast (like numerical weather prediction models), exposure and impact. Use the calc() method to calculate a forecasted impact. Then use the plotting methods to illustrate the forecasted impacts. By default plots are saved under in a ‘/forecast/plots’ folder in the configurable save_dir in local_data (see climada.util.config) under a name summarizing the Hazard type, haz model name, initialization time of the forecast run, event date, exposure name and the plot title. As the class is relatively new, there might be future changes to the attributes, the methods, and the parameters used to call the methods. It was discovered at some point, that there might be a memory leak in matplotlib even when figures are closed (https://github.com/matplotlib/matplotlib/issues/8519). Due to this reason the plotting functions in this module have the flag close_fig, to close figures within the function scope, which might mitigate that problem if a script runs this plotting functions many times.
-
run_datetime¶ initialization time of the forecast model run used to create the Hazard
- Type
list of datetime.datetime
-
event_date¶ Date on which the Hazard event takes place
- Type
datetime.datetime
-
hazard¶ List of the hazard forecast with different lead times.
- Type
list of CLIMADA Hazard
-
haz_model¶ Short string specifying the model used to create the hazard, if possible three big letters.
- Type
str
-
exposure¶ an CLIMADA Exposures containg values at risk
- Type
Exposure
-
exposure_name¶ string specifying the exposure (e.g. ‘EU’), which is used to name output files.
- Type
str
-
vulnerability¶ Set of impact functions used in the impact calculation.
- Type
-
__init__(hazard_dict, exposure, impact_funcs, haz_model='NWP', exposure_name=None)[source]¶ Initialization with hazard, exposure and vulnerability.
- Parameters
hazard_dict (dict) – Dictionary of the format {run_datetime: Hazard} with run_datetime being the initialization time of a weather forecast run and Hazard being a CLIMADA Hazard derived from that forecast for one event. A probabilistic representation of that one event is possible, as long as the attribute Hazard.date is the same for all events. Several run_datetime:Hazard combinations for the same event can be provided.
exposure (Exposure)
impact_funcs (ImpactFuncSet)
haz_model (str, optional) – Short string specifying the model used to create the hazard, if possible three big letters. Default is ‘NWP’ for numerical weather prediction.
exposure_name (str, optional) – string specifying the exposure (e.g. ‘EU’), which is used to name output files.
-
ei_exp(run_datetime=None)[source]¶ Expected impact per exposure
- Parameters
run_datetime (datetime.datetime, optional) – Select the used hazard by the run_datetime, default is first element of attribute run_datetime.
- Returns
- Return type
float
-
ai_agg(run_datetime=None)[source]¶ average impact aggregated over all exposures
- Parameters
run_datetime (datetime.datetime, optional) – Select the used hazard by the run_datetime, default is first element of attribute run_datetime.
- Returns
- Return type
float
-
haz_summary_str(run_datetime=None)[source]¶ provide a summary string for the hazard part of the forecast
- Parameters
run_datetime (datetime.datetime, optional) – Select the used hazard by the run_datetime, default is first element of attribute run_datetime.
- Returns
summarizing the most important information about the hazard
- Return type
str
-
summary_str(run_datetime=None)[source]¶ provide a summary string for the impact forecast
- Parameters
run_datetime (datetime.datetime, optional) – Select the used hazard by the run_datetime, default is first element of attribute run_datetime.
- Returns
summarizing the most important information about the impact forecast
- Return type
str
-
lead_time(run_datetime=None)[source]¶ provide the lead time for the impact forecast
- Parameters
- run_datetime (datetime.datetime, optional) – Select the used hazard by the run_datetime,
default is first element of attribute run_datetime.
Returns
——-
datetime.timedelta – the difference between the initialization time of the forecast model run and the date of the event, commenly named lead time
-
calc(force_reassign=False)[source]¶ calculate the impacts for all lead times using exposure, all hazards of all run_datetime, and ImpactFunctionSet.
- Parameters
force_reassign (bool, optional) – Reassign hazard centroids to the exposure for all hazards, default is false.
-
plot_imp_map(run_datetime=None, save_fig=True, close_fig=False, polygon_file=None, polygon_file_crs='epsg:4326', proj=<cartopy.crs.PlateCarree object>, figsize=(9, 13))[source]¶ plot a map of the impacts
- Parameters
run_datetime (datetime.datetime, optional) – Select the used hazard by the run_datetime, default is first element of attribute run_datetime.
save_fig (bool, optional) – Figure is saved if True, folder is within your configurable save_dir and filename is derived from the method summary_str() (for more details see class docstring). Default is True.
close_fig (bool, optional) – Figure not drawn if True. Default is False.
polygon_file (str, optional) – Points to a .shp-file with polygons do be drawn as outlines on the plot, default is None to not draw the lines. please also specify the crs in the parameter polygon_file_crs.
polygon_file_crs (str, optional) – String of pattern <provider>:<code> specifying the crs. has to be readable by pyproj.Proj. Default is ‘epsg:4326’.
proj (ccrs) – coordinate reference system used in coordinates The default is ccrs.PlateCarree()
figsize (tuple) – figure size for plt.subplots, width, height in inches The default is (9, 13)
- Returns
axes
- Return type
cartopy.mpl.geoaxes.GeoAxesSubplot
-
plot_hist(run_datetime=None, save_fig=True, close_fig=False, figsize=(9, 8))[source]¶ plot histogram of the forecasted impacts all ensemble members
- Parameters
run_datetime (datetime.datetime, optional) – Select the used hazard by the run_datetime, default is first element of attribute run_datetime.
save_fig (bool, optional) – Figure is saved if True, folder is within your configurable save_dir and filename is derived from the method summary_str() (for more details see class docstring). Default is True.
close_fig (bool, optional) – Figure is not drawn if True. Default is False.
figsize (tuple) – figure size for plt.subplots, width, height in inches The default is (9, 8)
- Returns
axes
- Return type
matplotlib.axes.Axes
-
plot_exceedence_prob(threshold, explain_str=None, run_datetime=None, save_fig=True, close_fig=False, polygon_file=None, polygon_file_crs='epsg:4326', proj=<cartopy.crs.PlateCarree object>, figsize=(9, 13))[source]¶ plot exceedence map
- Parameters
threshold (float) – Threshold of impact unit for which exceedence probability should be plotted.
explain_str (str, optional) – Short str which explains threshold, explain_str is included in the title of the figure.
run_datetime (datetime.datetime, optional) – Select the used hazard by the run_datetime, default is first element of attribute run_datetime.
save_fig (bool, optional) – Figure is saved if True, folder is within your configurable save_dir and filename is derived from the method summary_str() (for more details see class docstring). Default is True.
close_fig (bool, optional) – Figure not drawn if True. Default is False.
polygon_file (str, optional) – Points to a .shp-file with polygons do be drawn as outlines on the plot, default is None to not draw the lines. please also specify the crs in the parameter polygon_file_crs.
polygon_file_crs (str, optional) – String of pattern <provider>:<code> specifying the crs. has to be readable by pyproj.Proj. Default is ‘epsg:4326’.
proj (ccrs) – coordinate reference system used in coordinates The default is ccrs.PlateCarree()
figsize (tuple) – figure size for plt.subplots, width, height in inches The default is (9, 13)
- Returns
axes
- Return type
cartopy.mpl.geoaxes.GeoAxesSubplot
-
plot_warn_map(polygon_file=None, polygon_file_crs='epsg:4326', thresholds='default', decision_level='exposure_point', probability_aggregation=0.5, area_aggregation=0.5, title='WARNINGS', explain_text='warn level based on thresholds', run_datetime=None, proj=<cartopy.crs.PlateCarree object>, figsize=(9, 13), save_fig=True, close_fig=False)[source]¶ plot map colored with 5 warning colors for all regions in provided shape file.
- Parameters
polygon_file (str, optional) – path to shp-file containing warning region polygons
polygon_file_crs (str, optional) – String of pattern <provider>:<code> specifying the crs. has to be readable by pyproj.Proj. Default is ‘epsg:4326’.
thresholds (list of 4 floats, optional) – Thresholds for coloring region in second, third, forth and fifth warning color.
decision_level (str, optional) – Either ‘exposure_point’ or ‘polygon’. Default value is ‘exposure_point’.
probability_aggregation (float or str, optional) – Either a float between [0..1] spezifying a quantile or ‘mean’ or ‘sum’. Default value is 0.5.
area_aggregation (float or str.) – Either a float between [0..1] specifying a quantile or ‘mean’ or ‘sum’. Default value is 0.5.
run_datetime (datetime.datetime, optional) – Select the used hazard by the run_datetime, default is first element of attribute run_datetime.
title (str, optional) – Default is ‘WARNINGS’.
explain_text (str, optional) – Defaut is ‘warn level based on thresholds’.
proj (ccrs) – coordinate reference system used in coordinates
figsize (tuple) – figure size for plt.subplots, width, height in inches The default is (9, 13)
save_fig (bool, optional) – Figure is saved if True, folder is within your configurable save_dir and filename is derived from the method summary_str() (for more details see class docstring). Default is True.
close_fig (bool, optional) – Figure is not drawn if True. The default is False.
- Returns
axes
- Return type
cartopy.mpl.geoaxes.GeoAxesSubplot
-
plot_hexbin_ei_exposure(run_datetime=None, figsize=(9, 13))[source]¶ plot the expected impact
- Parameters
run_datetime (datetime.datetime, optional) – Select the used hazard by the run_datetime, default is first element of attribute run_datetime.
figsize (tuple) – figure size for plt.subplots, width, height in inches The default is (9, 13)
- Returns
axes
- Return type
cartopy.mpl.geoaxes.GeoAxesSubplot
-
climada.engine.impact module¶
-
class
climada.engine.impact.ImpactFreqCurve[source]¶ Bases:
objectImpact exceedence frequency curve.
-
tag¶ dictionary of tags of exposures, impact functions set and hazard: {‘exp’: Tag(), ‘if_set’: Tag(), ‘haz’: TagHazard()}
- Type
dict
-
return_per¶ return period
- Type
np.array
-
impact¶ impact exceeding frequency
- Type
np.array
-
unit¶ value unit used (given by exposures unit)
- Type
str
-
label¶ string describing source data
- Type
str
-
plot(axis=None, log_frequency=False, **kwargs)[source]¶ Plot impact frequency curve.
- Parameters
axis (matplotlib.axes._subplots.AxesSubplot, optional) – axis to use
log_frequency (boolean) – plot logarithmioc exceedance frequency on x-axis
kwargs (optional) – arguments for plot matplotlib function, e.g. color=’b’
- Returns
matplotlib.axes._subplots.AxesSubplot
-
-
class
climada.engine.impact.Impact[source]¶ Bases:
objectImpact definition. Compute from an entity (exposures and impact functions) and hazard.
-
tag¶ dictionary of tags of exposures, impact functions set and hazard: {‘exp’: Tag(), ‘if_set’: Tag(), ‘haz’: TagHazard()}
- Type
dict
-
event_id¶ id (>0) of each hazard event
- Type
np.array
-
event_name¶ name of each hazard event
- Type
list
-
date¶ date if events as 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
-
coord_exp¶ exposures coordinates [lat, lon] (in degrees)
- Type
np.ndarray
-
eai_exp¶ expected annual impact for each exposure
- Type
np.array
-
at_event¶ impact for each hazard event
- Type
np.array
-
frequency¶ annual frequency of event
- Type
np.arrray
-
tot_value¶ total exposure value affected
- Type
float
-
aai_agg¶ average annual impact (aggregated)
- Type
float
-
unit¶ value unit used (given by exposures unit)
- Type
str
-
imp_mat¶ matrix num_events x num_exp with impacts. only filled if save_mat is True in calc()
- Type
sparse.csr_matrix
-
calc_freq_curve(return_per=None)[source]¶ Compute impact exceedance frequency curve.
- Parameters
return_per (np.array, optional) – return periods where to compute the exceedance impact. Use impact’s frequencies if not provided
- Returns
ImpactFreqCurve
-
calc(exposures, impact_funcs, hazard, save_mat=False)[source]¶ Compute impact of an hazard to exposures.
- Parameters
exposures (Exposures) – exposures
impact_funcs (ImpactFuncSet) – impact functions
hazard (Hazard) – hazard
self_mat (bool) – self impact matrix: events x exposures
Examples
Use Entity class:
>>> haz = Hazard('TC') # Set hazard >>> haz.read_mat(HAZ_DEMO_MAT) >>> haz.check() >>> ent = Entity() # Load entity with default values >>> ent.read_excel(ENT_TEMPLATE_XLS) # Set exposures >>> ent.check() >>> imp = Impact() >>> imp.calc(ent.exposures, ent.impact_funcs, haz) >>> imp.calc_freq_curve().plot()
Specify only exposures and impact functions:
>>> haz = Hazard('TC') # Set hazard >>> haz.read_mat(HAZ_DEMO_MAT) >>> haz.check() >>> funcs = ImpactFuncSet() >>> funcs.read_excel(ENT_TEMPLATE_XLS) # Set impact functions >>> funcs.check() >>> exp = Exposures(pd.read_excel(ENT_TEMPLATE_XLS)) # Set exposures >>> exp.check() >>> imp = Impact() >>> imp.calc(exp, funcs, haz) >>> imp.aai_agg
-
calc_risk_transfer(attachment, cover)[source]¶ Compute traaditional risk transfer over impact. Returns new impact with risk transfer applied and the insurance layer resulting Impact metrics.
- Parameters
attachment (float) – attachment (deductible)
cover (float) – cover
- Returns
Impact, Impact
-
plot_hexbin_eai_exposure(mask=None, ignore_zero=True, pop_name=True, buffer=0.0, extend='neither', axis=None, **kwargs)[source]¶ Plot hexbin expected annual impact of each exposure.
- Parameters
mask (np.array, optional) – mask to apply to eai_exp plotted.
ignore_zero (bool, optional) – flag to indicate if zero and negative values are ignored in plot. Default: False
pop_name (bool, optional) – add names of the populated places
buffer (float, optional) – border to add to coordinates. Default: 1.0.
extend (str, optional) – extend border colorbar with arrows. [ ‘neither’ | ‘both’ | ‘min’ | ‘max’ ]
axis (matplotlib.axes._subplots.AxesSubplot, optional) – axis to use
kwargs (optional) – arguments for hexbin matplotlib function
- Returns
cartopy.mpl.geoaxes.GeoAxesSubplot
-
plot_scatter_eai_exposure(mask=None, ignore_zero=True, pop_name=True, buffer=0.0, extend='neither', axis=None, **kwargs)[source]¶ Plot scatter expected annual impact of each exposure.
- Parameters
mask (np.array, optional) – mask to apply to eai_exp plotted.
ignore_zero (bool, optional) – flag to indicate if zero and negative values are ignored in plot. Default: False
pop_name (bool, optional) – add names of the populated places
buffer (float, optional) – border to add to coordinates. Default: 1.0.
extend (str, optional) – extend border colorbar with arrows. [ ‘neither’ | ‘both’ | ‘min’ | ‘max’ ]
axis (matplotlib.axes._subplots.AxesSubplot, optional) – axis to use
kwargs (optional) – arguments for hexbin matplotlib function
- Returns
cartopy.mpl.geoaxes.GeoAxesSubplot
-
plot_raster_eai_exposure(res=None, raster_res=None, save_tiff=None, raster_f=<function Impact.<lambda>>, label='value (log10)', axis=None, **kwargs)[source]¶ Plot raster expected annual impact of each exposure.
- Parameters
res (float, optional) – resolution of current data in units of latitude and longitude, approximated if not provided.
raster_res (float, optional) – desired resolution of the raster
save_tiff (str, optional) – file name to save the raster in tiff format, if provided
raster_f (lambda function) – transformation to use to data. Default: log10 adding 1.
label (str) – colorbar label
axis (matplotlib.axes._subplots.AxesSubplot, optional) – axis to use
kwargs (optional) – arguments for imshow matplotlib function
- Returns
cartopy.mpl.geoaxes.GeoAxesSubplot
-
plot_basemap_eai_exposure(mask=None, ignore_zero=False, pop_name=True, buffer=0.0, extend='neither', zoom=10, url='http://tile.stamen.com/terrain/tileZ/tileX/tileY.png', axis=None, **kwargs)[source]¶ Plot basemap expected annual impact of each exposure.
- Parameters
mask (np.array, optional) – mask to apply to eai_exp plotted.
ignore_zero (bool, optional) – flag to indicate if zero and negative values are ignored in plot. Default: False
pop_name (bool, optional) – add names of the populated places
buffer (float, optional) – border to add to coordinates. Default: 0.0.
extend (str, optional) – extend border colorbar with arrows. [ ‘neither’ | ‘both’ | ‘min’ | ‘max’ ]
zoom (int, optional) – zoom coefficient used in the satellite image
url (str, optional) – image source, e.g. ctx.sources.OSM_C
axis (matplotlib.axes._subplots.AxesSubplot, optional) – axis to use
kwargs (optional) – arguments for scatter matplotlib function, e.g. cmap=’Greys’. Default: ‘Wistia’
- Returns
cartopy.mpl.geoaxes.GeoAxesSubplot
-
plot_hexbin_impact_exposure(event_id=1, mask=None, ignore_zero=True, pop_name=True, buffer=0.0, extend='neither', axis=None, **kwargs)[source]¶ Plot hexbin impact of an event at each exposure. Requires attribute imp_mat.
- Parameters
event_id (int, optional) – id of the event for which to plot the impact. Default: 1.
mask (np.array, optional) – mask to apply to impact plotted.
ignore_zero (bool, optional) – flag to indicate if zero and negative values are ignored in plot. Default: False
pop_name (bool, optional) – add names of the populated places
buffer (float, optional) – border to add to coordinates. Default: 1.0.
extend (str, optional) – extend border colorbar with arrows. [ ‘neither’ | ‘both’ | ‘min’ | ‘max’ ]
kwargs (optional) – arguments for hexbin matplotlib function
axis (matplotlib.axes._subplots.AxesSubplot, optional) – axis to use
- Returns
matplotlib.figure.Figure, cartopy.mpl.geoaxes.GeoAxesSubplot
-
plot_basemap_impact_exposure(event_id=1, mask=None, ignore_zero=True, pop_name=True, buffer=0.0, extend='neither', zoom=10, url='http://tile.stamen.com/terrain/tileZ/tileX/tileY.png', axis=None, **kwargs)[source]¶ Plot basemap impact of an event at each exposure. Requires attribute imp_mat.
- Parameters
event_id (int, optional) – id of the event for which to plot the impact. Default: 1.
mask (np.array, optional) – mask to apply to impact plotted.
ignore_zero (bool, optional) – flag to indicate if zero and negative values are ignored in plot. Default: False
pop_name (bool, optional) – add names of the populated places
buffer (float, optional) – border to add to coordinates. Default: 0.0.
extend (str, optional) – extend border colorbar with arrows. [ ‘neither’ | ‘both’ | ‘min’ | ‘max’ ]
zoom (int, optional) – zoom coefficient used in the satellite image
url (str, optional) – image source, e.g. ctx.sources.OSM_C
axis (matplotlib.axes._subplots.AxesSubplot, optional) – axis to use
kwargs (optional) – arguments for scatter matplotlib function, e.g. cmap=’Greys’. Default: ‘Wistia’
- Returns
cartopy.mpl.geoaxes.GeoAxesSubplot
-
write_csv(file_name)[source]¶ Write data into csv file. imp_mat is not saved.
- Parameters
file_name (str) – absolute path of the file
-
write_excel(file_name)[source]¶ Write data into Excel file. imp_mat is not saved.
- Parameters
file_name (str) – absolute path of the file
-
calc_impact_year_set(all_years=True, year_range=None)[source]¶ Calculate yearly impact from impact data.
- Parameters
all_years (boolean) – return values for all years between first and
last year with event, including years without any events.
year_range (tuple or list with integers) – start and end year
- Returns
Impact year set of type numpy.ndarray with summed impact per year.
-
local_exceedance_imp(return_periods=(25, 50, 100, 250))[source]¶ Compute exceedance impact map for given return periods. Requires attribute imp_mat.
- Parameters
return_periods (np.array) – return periods to consider
- Returns
np.array
-
plot_rp_imp(return_periods=(25, 50, 100, 250), log10_scale=True, smooth=True, axis=None, **kwargs)[source]¶ Compute and plot exceedance impact maps for different return periods. Calls local_exceedance_imp.
- Parameters
return_periods (tuple(int), optional) – return periods to consider
log10_scale (boolean, optional) – plot impact as log10(impact)
smooth (bool, optional) – smooth plot to plot.RESOLUTIONxplot.RESOLUTION
kwargs (optional) – arguments for pcolormesh matplotlib function used in event plots
- Returns
matplotlib.axes._subplots.AxesSubplot, np.ndarray (return_periods.size x num_centroids)
-
static
read_sparse_csr(file_name)[source]¶ Read imp_mat matrix from numpy’s npz format.
- Parameters
file_name (str) – file name
- Returns
sparse.csr_matrix
-
read_csv(file_name)[source]¶ Read csv file containing impact data generated by write_csv.
- Parameters
file_name (str) – absolute path of the file
-
read_excel(file_name)[source]¶ Read excel file containing impact data generated by write_excel.
- Parameters
file_name (str) – absolute path of the file
-
static
video_direct_impact(exp, if_set, haz_list, file_name='', writer=<matplotlib.animation.PillowWriter object>, imp_thresh=0, args_exp=None, args_imp=None)[source]¶ Computes and generates video of accumulated impact per input events over exposure.
- Parameters
exp (Exposures) – exposures instance, constant during all video
if_set (ImpactFuncSet) – impact functions
haz_list (list(Hazard)) – every Hazard contains an event; all hazards use the same centroids
file_name (str, optional) – file name to save video, if provided
writer = (matplotlib.animation., optional*) – video writer. Default: pillow with bitrate=500
imp_thresh (float) – represent damages greater than threshold
args_exp (optional) – arguments for scatter (points) or hexbin (raster) matplotlib function used in exposures
args_imp (optional) – arguments for scatter (points) or hexbin (raster) matplotlib function used in impact
- Returns
list(Impact)
-
select(event_ids=None, event_names=None, dates=None, coord_exp=None)[source]¶ Select a subset of events and/or exposure points from the impact. If multiple input variables are not None, it returns all the impacts matching at least one of the conditions.
Note
the frequencies are NOT adjusted. Method to adjust frequencies
- and obtain correct eai_exp:
1- Select subset of impact according to your choice imp = impact.select(…) 2- Adjust manually the frequency of the subset of impact imp.frequency = […] 3- Use select without arguments to select all events and recompute the eai_exp with the updated frequencies. imp = imp.select()
- Parameters
event_ids (list[int], optional) – Selection of events by their id. The default is None.
event_names (list[str], optional) – Selection of events by their name. The default is None.
dates (tuple(), optional) – (start-date, end-date), events are selected if they are >= than start-date and <= than end-date. Dates in same format as impact.date (ordinal format of datetime library) The default is None.
coord_exp ((np.ndarray), optional]) – Selection of exposures coordinates [lat, lon] (in degrees) The default is None.
- Raises
ValueError – If the impact matrix is missing, the eai_exp and aai_agg cannot be updated for a selection of events and/or exposures.
- Returns
imp – A new impact object with a selection of events and/or exposures
- Return type
climada.engine.Impact
-
climada.engine.impact_data module¶
-
climada.engine.impact_data.assign_hazard_to_emdat(certainty_level, intensity_path_haz, names_path_haz, reg_id_path_haz, date_path_haz, emdat_data, start_time, end_time, keep_checks=False)[source]¶ - assign_hazard_to_emdat: link EMdat event to hazard
- Parameters:
- input files (paths):
intensity: sparse matrix with hazards as rows and grid points as cols, values only at location with impacts names: identifier for each hazard (i.e. IBtracID) (rows of the matrix) reg_id: ISO country ID of each grid point (cols of the matrix) date: start date of each hazard (rows of the matrix) emdat_data: pd.dataframe with EMdat data start: start date of events to be assigned ‘yyyy-mm-dd’ end: end date of events to be assigned ‘yyyy-mm-dd’ disaster_subtype: EMdat disaster subtype
- Returns
pd.dataframe with EMdat entries linked to a hazard
-
climada.engine.impact_data.hit_country_per_hazard(intensity_path, names_path, reg_id_path, date_path)[source]¶ hit_country_per_hazard: create list of hit countries from hazard set
- Parameters:
- input files:
intensity: sparse matrix with hazards as rows and grid points as cols, values only at location with impacts names: identifier for each hazard (i.e. IBtracID) (rows of the matrix) reg_id: ISO country ID of each grid point (cols of the matrix) date: start date of each hazard (rows of the matrix)
- Returns
pd.dataframe with all hit countries per hazard
-
climada.engine.impact_data.create_lookup(emdat_data, start, end, disaster_subtype='Tropical cyclone')[source]¶ create_lookup: prepare a lookup table of EMdat events to which hazards can be assigned
- Parameters
emdat_data – pd.dataframe with EMdat data
start – start date of events to be assigned ‘yyyy-mm-dd’
end – end date of events to be assigned ‘yyyy-mm-dd’
disaster_subtype – EMdat disaster subtype
- Returns
pd.dataframe lookup
-
climada.engine.impact_data.emdat_possible_hit(lookup, hit_countries, delta_t)[source]¶ relate EM disaster to hazard using hit countries and time
- Parameters
input files – lookup: pd.dataframe to relate EMdatID to hazard tracks: pd.dataframe with all hit countries per hazard delta_t: max time difference of start of EMdat event and hazard hit_countries: start: start date of events to be assigned end: end date of events to be assigned disaster_subtype: EMdat disaster subtype
- Returns
list with possible hits
-
climada.engine.impact_data.match_em_id(lookup, poss_hit)[source]¶ function to check if EM_ID has been assigned already and combine possible hits
- Parameters
lookup – pd.dataframe to relate EMdatID to hazard
poss_hit – list with possible hits
- Returns
list with all possible hits per EMdat ID
-
climada.engine.impact_data.assign_track_to_em(lookup, possible_tracks_1, possible_tracks_2, level)[source]¶ function to assign a hazard to an EMdat event to get some confidene into the procedure, hazards get only assigned if there is no other hazard occuring at a bigger time interval in that country Thus a track of possible_tracks_1 gets only assigned if there are no other tracks in possible_tracks_2. The confidence can be expressed with a certainty level
- Parameters
lookup – pd.dataframe to relate EMdatID to hazard
possible_tracks_1 – list of possible hits with smaller time horizon
possible_tracks_2 – list of possible hits with larger time horizon
level – level of confidence
- Returns
pd.dataframe lookup with assigend tracks and possible hits
-
climada.engine.impact_data.check_assigned_track(lookup, checkset)[source]¶ compare lookup with assigned tracks to a set with checked sets
- Parameters
lookup – pd.dataframe to relate EMdatID to hazard
checkset – pd.dataframe with already checked hazards
- Returns
error scores
-
climada.engine.impact_data.clean_emdat_df(emdat_file, countries=None, hazard=None, year_range=None, target_version=2020)[source]¶ Get a clean and standardized DataFrame from EM-DAT-CSV-file (1) load EM-DAT data from CSV to DataFrame and remove header/footer, (2) handle version, clean up, and add columns, and (3) filter by country, hazard type and year range (if any given)
- Parameters
emdat_file (str, Path, or DataFrame) – Either string with full path to CSV-file or pandas.DataFrame loaded from EM-DAT CSV
- Optional parameters:
- countries (list of str): country ISO3-codes or names, e.g. [‘JAM’, ‘CUB’].
countries=None for all countries (default)
- hazard (list or str): List of Disaster (sub-)type accordung EMDAT terminology, i.e.:
Animal accident, Drought, Earthquake, Epidemic, Extreme temperature, Flood, Fog, Impact, Insect infestation, Landslide, Mass movement (dry), Storm, Volcanic activity, Wildfire; Coastal Flooding, Convective Storm, Riverine Flood, Tropical cyclone, Tsunami, etc.; OR CLIMADA hazard type abbreviations, e.g. TC, BF, etc.
- year_range (list or tuple): Year range to be extracted, e.g. (2000, 2015);
(only min and max are considered)
- target_version (int): required EM-DAT data format version (i.e. year of download),
changes naming of columns/variables (default: 2020)
- Returns
DataFrame containing cleaned and filtered EM-DAT impact data
- Return type
df_data (pandas.DataFrame)
-
climada.engine.impact_data.emdat_countries_by_hazard(emdat_file_csv, hazard=None, year_range=None)[source]¶ return list of all countries exposed to a chosen hazard type from EMDAT data as CSV.
- Parameters
emdat_file (str or DataFrame) – Either string with full path to CSV-file or pandas.DataFrame loaded from EM-DAT CSV
- Optional Parameters:
- hazard (list or str): List of Disaster (sub-)type accordung EMDAT terminology, i.e.:
Animal accident, Drought, Earthquake, Epidemic, Extreme temperature, Flood, Fog, Impact, Insect infestation, Landslide, Mass movement (dry), Storm, Volcanic activity, Wildfire; Coastal Flooding, Convective Storm, Riverine Flood, Tropical cyclone, Tsunami, etc.; OR CLIMADA hazard type abbreviations, e.g. TC, BF, etc.:
- year_range (tuple of integers or None):
range of years to consider, i.e. (1950, 2000) default is None, i.e. consider all years
- Returns
- list
List of ISO3-codes of countries impacted by the disaster (sub-)types
- countries_nameslist
List of names of countries impacted by the disaster (sub-)types
- Return type
countries_iso3a
-
climada.engine.impact_data.scale_impact2refyear(impact_values, year_values, iso3a_values, reference_year=None)[source]¶ Scale give impact values proportional to GDP to the according value in a reference year (for normalization of monetary values)
- Parameters
impact_values (list or array) – Impact values to be scaled.
year_values (list or array) – Year of each impact (same length as impact_values)
iso3a_values (list or array) – ISO3alpha code of country for each impact (same length as impact_values)
- Optional Parameters:
- reference_year (int):
Impact is scaled proportional to GDP to the value of the reference year. No scaling for reference_year=None (default)
-
climada.engine.impact_data.emdat_impact_yearlysum(emdat_file_csv, countries=None, hazard=None, year_range=None, reference_year=None, imp_str="Total Damages ('000 US$)", version=2020)[source]¶ function to load EM-DAT data and sum impact per year :Parameters: emdat_file (str or DataFrame) – Either string with full path to CSV-file or
pandas.DataFrame loaded from EM-DAT CSV
- Optional parameters:
- countries (list of str): country ISO3-codes or names, e.g. [‘JAM’, ‘CUB’].
countries=None for all countries (default)
- hazard (list or str): List of Disaster (sub-)type accordung EMDAT terminology, i.e.:
Animal accident, Drought, Earthquake, Epidemic, Extreme temperature, Flood, Fog, Impact, Insect infestation, Landslide, Mass movement (dry), Storm, Volcanic activity, Wildfire; Coastal Flooding, Convective Storm, Riverine Flood, Tropical cyclone, Tsunami, etc.; OR CLIMADA hazard type abbreviations, e.g. TC, BF, etc.
- year_range (list or tuple): Year range to be extracted, e.g. (2000, 2015);
(only min and max are considered)
- version (int): given EM-DAT data format version (i.e. year of download),
changes naming of columns/variables (default: 2020)
- reference_year (int): reference year of exposures. Impact is scaled
proportional to GDP to the value of the reference year. No scaling for 0 (default)
- imp_str (str): Column name of impact metric in EMDAT CSV,
default = “Total Damages (‘000 US$)”
- Returns
- DataFrame with summed impact and scaled impact per
year and country.
- Return type
out (pd.DataFrame)
-
climada.engine.impact_data.emdat_impact_event(emdat_file_csv, countries=None, hazard=None, year_range=None, reference_year=None, imp_str="Total Damages ('000 US$)", version=2020)[source]¶ function to load EM-DAT data return impact per event
- Parameters
emdat_file_csv (str) – Full path to EMDAT-file (CSV), i.e.: emdat_file_csv = SYSTEM_DIR.joinpath(‘emdat_201810.csv’)
- Optional parameters:
- countries (list of str): country ISO3-codes or names, e.g. [‘JAM’, ‘CUB’].
countries=None for all countries (default)
- hazard (list or str): List of Disaster (sub-)type accordung EMDAT terminology, i.e.:
Animal accident, Drought, Earthquake, Epidemic, Extreme temperature, Flood, Fog, Impact, Insect infestation, Landslide, Mass movement (dry), Storm, Volcanic activity, Wildfire; Coastal Flooding, Convective Storm, Riverine Flood, Tropical cyclone, Tsunami, etc.; OR CLIMADA hazard type abbreviations, e.g. TC, BF, etc.
- year_range (list or tuple): Year range to be extracted, e.g. (2000, 2015);
(only min and max are considered)
- reference_year (int): reference year of exposures. Impact is scaled
proportional to GDP to the value of the reference year. No scaling for 0 (default)
- imp_str (str): Column name of impact metric in EMDAT CSV,
default = “Total Damages (‘000 US$)”
version (int): EM-DAT version to take variable/column names from (defaul: 2020)
- Returns
- EMDAT DataFrame with new columns “year”,
”region_id”, and “impact” and +impact_scaled” total impact per event with same unit as chosen impact, but multiplied by 1000 if impact is given as 1000 US$ (e.g. imp_str=”Total Damages (‘000 US$) scaled”).
- Return type
out (pandas DataFrame)
-
climada.engine.impact_data.emdat_to_impact(emdat_file_csv, hazard_type_climada, year_range=None, countries=None, hazard_type_emdat=None, reference_year=None, imp_str='Total Damages')[source]¶ function to load EM-DAT data return impact per event
- Parameters
emdat_file_csv (str) – Full path to EMDAT-file (CSV), i.e.: emdat_file_csv = SYSTEM_DIR.joinpath(‘emdat_201810.csv’)
hazard_type_climada (str) – Hazard type CLIMADA abbreviation, i.e. ‘TC’ for tropical cyclone
- Optional parameters:
- hazard_type_emdat (list or str): List of Disaster (sub-)type accordung
EMDAT terminology, e.g.: Animal accident, Drought, Earthquake, Epidemic, Extreme temperature, Flood, Fog, Impact, Insect infestation, Landslide, Mass movement (dry), Storm, Volcanic activity, Wildfire; Coastal Flooding, Convective Storm, Riverine Flood, Tropical cyclone, Tsunami, etc.; OR CLIMADA hazard type abbreviations, e.g. TC, BF, etc. If not given, it is deducted from hazard_type_climada
- year_range (list with 2 integers): start and end year e.g. [1980, 2017]
default: None –> take year range from EM-DAT file
- countries (list of str): country ISO3-codes or names, e.g. [‘JAM’].
Set to None or [‘all’] for all countries (default)
- reference_year (int): reference year of exposures. Impact is scaled
proportional to GDP to the value of the reference year. No scaling for reference_year=0 (default)
- imp_str (str): Column name of impact metric in EMDAT CSV,
default = “Total Damages (‘000 US$)”
- Returns
- impact object of same format as output from CLIMADA
impact computation. Values scaled with GDP to reference_year if reference_year is given. i.e. current US$ for imp_str=”Total Damages (‘000 US$) scaled” (factor 1000 is applied) impact_instance.eai_exp holds expected annual impact for each country. impact_instance.coord_exp holds rough central coordinates for each country.
countries (list): ISO3-codes of countries in same order as in impact_instance.eai_exp
- Return type
impact_instance (instance of climada.engine.Impact)
climada.engine.supplychain module¶
-
class
climada.engine.supplychain.SupplyChain[source]¶ Bases:
objectSupplyChain class.
The SupplyChain class provides methods for loading Multi-Regional Input-Output Tables (MRIOT) and computing direct, indirect and total impacts.
-
mriot_data¶ The input-output table data.
- Type
np.array
-
mriot_reg_names¶ Names of regions considered in the input-output table.
- Type
np.array
-
sectors¶ Sectors considered in the input-output table.
- Type
np.array
-
total_prod¶ Countries’ total production.
- Type
np.array
-
mriot_type¶ Type of the adopted input-output table.
- Type
str
-
reg_pos¶ Regions’ positions within the input-output table and impact arrays.
- Type
dict
-
reg_dir_imp¶ Regions undergoing direct impacts.
- Type
list
-
years¶ Years of the considered hazard events for which impact is calculated.
- Type
np.array
-
direct_impact¶ Direct impact array.
- Type
np.array
-
direct_aai_agg¶ Average annual direct impact array.
- Type
np.array
-
indirect_impact¶ Indirect impact array.
- Type
np.array
-
indirect_aai_agg¶ Average annual indirect impact array.
- Type
np.array
-
total_impact¶ Total impact array.
- Type
np.array
-
total_aai_agg¶ Average annual total impact array.
- Type
np.array
-
io_data¶ Dictionary with the coefficients, inverse and risk_structure matrixes and the selected input-output modeling approach.
- Type
dict
-
read_wiod16(year=2014, range_rows=(5, 2469), range_cols=(4, 2468), col_iso3=2, col_sectors=1)[source]¶ Read multi-regional input-output tables of the 2016 release of the WIOD project: http://www.wiod.org/database/wiots16
- Parameters
year (int) – Year of WIOD table to use. Valid years go from 2000 to 2014. Default year is 2014.
range_rows (tuple) – initial and end positions of data along rows. Default is (5,2469).
range_cols (tuple) – initial and end positions of data along columns. Default is (4,2468).
col_iso3 (int) – column with countries names in ISO3 codes. Default is 2.
col_sectors (int) – column with sector names. Default is 1.
References
[1] Timmer, M. P., Dietzenbacher, E., Los, B., Stehrer, R. and de Vries, G. J. (2015), “An Illustrated User Guide to the World Input–Output Database: the Case of Global Automotive Production”, Review of International Economics., 23: 575–605
-
calc_sector_direct_impact(hazard, exposure, imp_fun_set, selected_subsec='service')[source]¶ Calculate direct impacts.
- hazardHazard
Hazard object for impact calculation.
- exposureExposures
Exposures object for impact calculation. For WIOD tables, exposure.region_id must be country names following ISO3 codes.
- imp_fun_setImpactFuncSet
Set of impact functions.
- selected_subsecstr or list
Positions of the selected sectors. These positions can be either defined by the user by passing a list of values, or by using built-in sectors’ aggregations for the WIOD data passing a string with possible values being “service”, “manufacturing”, “agriculture” or “mining”. Default is “service”.
-
calc_indirect_impact(io_approach='ghosh')[source]¶ Calculate indirect impacts according to the specified input-output appraoch. This function needs to be run after calc_sector_direct_impact.
- Parameters
io_approach (str) – The adopted input-output modeling approach. Possible approaches are ‘leontief’, ‘ghosh’ and ‘eeioa’. Default is ‘gosh’.
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.
-