Defining Adaptation Measures with python functions#
The Measure object is the core component of the Adaptation module in CLIMADA. It acts as a wrapper for transformation logic, allowing you to model how specific interventions alter the risk landscape (like building sea walls, retrofitting houses, or implementing early warning systems).
The primary purpose of a Measure is to modify one or more parts of the “Risk Triplet”: Exposures, Impact Functions, and Hazard.
Quickstart#
from climada.entity.measures.measure import Measure
from climada.entity.measures.cost_income import CostIncome
# Define one or more transformation function
# It must take an Exposures, Hazard or ImpactFuncSEt as the first argument
# and return an object of the same type.
def reduce_exposure_value_at_risk(exposures, reduction_factor=0.2):
"""Reduces the value of all assets by a fixed percentage."""
exposures.gdf["value"] *= 1 - reduction_factor
return exposures
def sea_wall_protection(hazard, threshold=2.0):
"""Cuts off flood intensity below a certain threshold."""
# intensity is typically a sparse matrix in CLIMADA hazards
hazard.intensity.data[hazard.intensity.data < threshold] = 0
return hazard
# Define financial aspects
cost_income = CostIncome(init_cost=1_000_000)
# Initialize the Measure object
retrofitting_and_seawall = Measure(
name="Building Retrofit and seawall construction",
exposures_changes=reduce_exposure_value_at_risk,
hazard_changes=sea_wall_protection,
cost_income=cost_income,
)
The measure can then be used either to create a new triplet corresponding to the situation with measure in effect or to compute the impact directly (both lines are independant):
new_exp, new_impf, new_haz = retrofitting_and_seawall.apply(exp, impf, haz, kwargs_hazard={'threshold': 3.5})
# or directly:
impact_with_measure = retrofitting_and_seawall.calc_impact(exp, impf, haz, kwargs_hazard={'threshold': 3.5})
Core logic of the Measure object#
When you initialize a Measure, you can provide one to three callables (python functions):
exposures_changes: Modifies theExposuresobject, the asset location, value, or metadata (e.g., relocating houses from a flood zone).impfset_changes: Modifies theImpactFuncSetobject, the vulnerability of assets (e.g., updating an impact function because houses were elevated).hazard_changes: Modifies theHazardobject, the intensity or frequency of events (e.g., a dam reducing flood depths).
Note
By default, changes are the identity_function, so if you do not provide a function e.g., “exposures_changes” the measure once applied will return the exposure unchanged.
The only requirement for these python functions is to take and return an Exposures object (or ImpactFuncSet or Hazard objects respectively). This enables high modeling flexibility where changes from an adaptation option can be modelled from a simple “loading another file for the hazard or exposure”, to an advanced function.
One thing to note, is that the apply() method of a measure always passes the entire triplet (base_exposures, base_impfset, base_hazard, i.e., the risk triplet before the measure is applied) to every transformation function. This means you can easily write complex logic that relie on any of these component. For example:
“Only reduce the exposure value (Exposure change) in areas where the peak water depth (Hazard context) exceeds 2 meters.”
Could be defined like this:
import numpy as np
def reduce_exposure_by_depth(exposures, reduction_factor=0.2, threshold=2.0, **kwargs):
"""
Reduces asset value by a percentage, but only for assets located where
the peak hazard intensity (e.g., water depth) exceeds the threshold.
"""
# Retrieve the hazard context passed by Measure.apply
base_hazard = kwargs.get("base_hazard")
# Get the peak intensity for each centroid across all events
peak_depths = np.array(base_hazard.intensity.max(axis=0).todense()).flatten()
# Ensure exposures are mapped to hazard centroids
if "centr_ID" not in exposures.gdf.columns:
exposures.assign_centroids(base_hazard)
# Identify which exposure points meet the depth criteria
# 'centr_ID' maps each exposure row to a column index in
# the hazard intensity matrix
centr_indices = exposures.gdf["centr_ID"].values
point_peak_depths = peak_depths[centr_indices]
# We apply the reduction only where Depth > threshold
mask = point_peak_depths > threshold
exposures.gdf.loc[mask, "value"] *= 1 - reduction_factor
return exposures
# --- Usage Example ---
# Define the measure
flood_protection = Measure(
name="High-Threshold Value Protection",
exposures_changes=reduce_exposure_by_depth
)
# When you call apply, the `Hazard` haz is automatically passed to the function
# as 'base_hazard'
new_exp, _, _ = flood_protection.apply(
exp, impf, haz,
kwargs_exposures={'reduction_factor': 0.5, 'threshold': 2.0}
)
# You can also overide this with another "base" hazard in the
# `kwarg_exposures` if you want.
#
# This could be for instance if the flood protection is
# now defined not for the full probabilistic hazard set
# but for a specific event, or a subset.
new_exp, _, _ = flood_protection.apply(
exp, impf, haz,
kwargs_exposures={'base_hazard'= other_hazard,
'reduction_factor': 0.5, 'threshold': 2.0}
)
Note
The functions you define yourself are automatically made to accept keyword arguments if they do not already.
Note
The functions do not necessarily need to use the Exposures|Hazard|ImpactFuncSet object, but they still have to accept it as an argument.
Deep copies#
To prevent accidental “in-place” modification of your baseline data, Measure utilizes copy.deepcopy().
If enforce_copy=True in apply() (the default case), the object is cloned before the transformation function runs, ensuring the original objects remains untouched.
Measure cash flow (CostIncome)#
The cost_income attribute allows the measure to carry its own. It can notably store:
Initial investment costs.
Maintenance costs over time.
Potential indirect income generated by the measure.
For more information and advanced usage see the detailed tutorial on cost income object.
Defining Measure using measure configuration#
Defining adaptation measures with python functions can be a bit difficult if you are not too familiar with python.
In that case you can use MeasureConfig objects (tutorial here)
Advanced examples of measures#
Measures are often modelled as a fixed change. In practice, the effect of an adaptation action often depends on when it is evaluated (for instance, a relocation programme that is phased in over several years) or on additional parameters (regions targeted, share of value removed, protection threshold).
The examples below illustrate three patterns:
Exposures: a linear phase-in of asset relocation (
year,start_year,full_year,fraction,regions).Impact functions: a year-dependent reduction of the mean damage ratio.
Hazard: a step-function protection standard that needs the baseline impacts, and therefore the
base_*triplet.
import numpy as np
def phase_in(year, start_year, full_year):
"""Linear effectiveness ramp. (Helper function)
Parameters
----------
year : int
Year at which the measure is evaluated.
start_year : int
Year at which the measure starts having an effect.
full_year : int
Year at which the measure is fully effective.
Returns
-------
float
Effectiveness in [0, 1].
"""
return float(np.clip((year - start_year) / (full_year - start_year), 0, 1))
def relocate_assets(exposures, *, year, start_year, full_year, fraction, regions):
"""Progressively remove asset value from exposed regions.
Parameters
----------
exposures : climada.entity.exposures.base.Exposures
Exposures to modify (already a copy if ``enforce_copy=True``).
year : int
Evaluation year.
start_year, full_year : int
Start and end of the linear phase-in.
fraction : float
Share of value removed once the measure is fully implemented.
regions : list of int
``region_id`` values targeted by the measure.
Returns
-------
climada.entity.exposures.base.Exposures
Exposures with reduced value in the targeted regions.
"""
ramp = phase_in(year, start_year, full_year)
mask = exposures.gdf["region_id"].isin(regions)
exposures.gdf.loc[mask, "value"] *= 1 - fraction * ramp
return exposures
def flood_proofing(
impfset, *, year, start_year, full_year, reduction, haz_type="FL", impf_id=1
):
"""Scale down the mean damage ratio of one impact function.
Parameters
----------
impfset : climada.entity.impact_funcs.impact_func_set.ImpactFuncSet
Impact function set to modify.
year : int
Evaluation year.
start_year, full_year : int
Start and end of the linear phase-in.
reduction : float
Relative MDD reduction once fully effective.
haz_type : str, optional
Hazard type of the targeted function.
impf_id : int, optional
Id of the targeted function.
Returns
-------
climada.entity.impact_funcs.impact_func_set.ImpactFuncSet
Impact function set with the modified function.
"""
ramp = phase_in(year, start_year, full_year)
impf = impfset.get_func(haz_type=haz_type, fun_id=impf_id)
impf.mdd = impf.mdd * (1 - reduction * ramp)
return impfset
def protection_standard(
hazard, *, year, start_year, threshold, base_exposures, base_impfset, base_hazard
):
"""Remove events whose baseline impact is below a protection threshold.
Parameters
----------
hazard : climada.hazard.base.Hazard
Hazard to modify.
year : int
Evaluation year.
start_year : int
Year the protection is in place (no effect before).
threshold : float
Events with baseline total impact below this value are removed.
base_exposures, base_impfset, base_hazard
Unmodified triplet, provided by ``Measure.apply``.
Returns
-------
climada.hazard.base.Hazard
Hazard without the protected events. Frequencies of the remaining
events are left unchanged.
"""
from climada.engine.impact_calc import ImpactCalc
if year < start_year:
return hazard
imp = ImpactCalc(base_exposures, base_impfset, base_hazard).impact(
assign_centroids=False
)
return hazard.select(event_id=imp.event_id[imp.at_event >= threshold])
The parameters can then be provided when the measure is applied, or the impact is computed:
from climada.entity.measures.measure import Measure
meas_relocation = Measure(
"relocation",
exposures_changes=relocate_assets,
)
meas_relocation_and_standard = Measure(
"relocation_and_standard",
exposures_changes=relocate_assets,
hazard_changes=protection_standard,
)
exp_relocated, _, _ = meas_relocation.apply(
exp,
impfset,
haz,
kwargs_exposures=dict(
year=2030, start_year=2025, full_year=2045, fraction=0.3, regions=[1, 2]
),
)
imp_with_relocation_and_standards = meas_relocation_and_standard.calc_impact(
exp,
impfset,
haz,
kwargs_exposures=dict(
year=2030, start_year=2025, full_year=2045, fraction=0.3, regions=[1, 2]
),
kwargs_hazard=dict(year=2030, start_year=2025, full_year=2045, threshold=100000),
)