diff --git a/climada/entity/measures/helper.py b/climada/entity/measures/helper.py new file mode 100644 index 000000000..af61651b1 --- /dev/null +++ b/climada/entity/measures/helper.py @@ -0,0 +1,476 @@ +""" +This file is part of CLIMADA. + +Copyright (C) 2017 ETH Zurich, CLIMADA contributors listed in AUTHORS. + +CLIMADA is free software: you can redistribute it and/or modify it under the +terms of the GNU General Public License as published by the Free +Software Foundation, version 3. + +CLIMADA is distributed in the hope that it will be useful, but WITHOUT ANY +WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A +PARTICULAR PURPOSE. See the GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with CLIMADA. If not, see . + +--- + +Define Measure class. +""" + +from __future__ import annotations + +import logging +from functools import reduce +from typing import TYPE_CHECKING, Any, Callable, Optional, TypeVar, cast + +import numpy as np +import pandas as pd + +from climada.entity.exposures.base import Exposures +from climada.entity.impact_funcs.base import ImpactFunc +from climada.entity.impact_funcs.impact_func_set import ImpactFuncSet +from climada.entity.measures.measure_config import ( + ExposuresModifierConfig, + HazardModifierConfig, + ImpfsetModifierConfig, +) +from climada.hazard.base import Hazard + +if TYPE_CHECKING: + from climada.entity.impact_funcs.impact_func_set import ImpactFuncSet + from climada.entity.measures.types import ( + ExposuresChange, + HazardChange, + ImpfsetChange, + ) + from climada.hazard.base import Hazard + + T = TypeVar("T", Exposures, ImpactFuncSet, Hazard) + +LOGGER = logging.getLogger(__name__) + + +def identity_function(x: T, **_kwargs: Any) -> T: + """Return the input object unchanged. + + Parameters + ---------- + x : T + Object to return. + **_kwargs : Any + Accepted but ignored. + + Returns + ------- + T + The unchanged input object. + """ + + return x + + +def composite_fun(*funcs: Callable[..., T]) -> Callable[..., T]: + """Compose multiple functions right-to-left into a single callable. + + Given functions ``f, g, h``, returns a function equivalent to + ``lambda x, **kw: f(g(h(x, **kw), **kw), **kw)``. + If no functions are provided, returns :func:`identity_function`. + + Parameters + ---------- + *funcs : Callable[..., T] + Functions to compose, applied from right to left. + Each must accept an object of type ``T`` as its first positional + argument and forward ``**kwargs``. + + Returns + ------- + Callable[..., T] + A single callable equivalent to the right-to-left composition of + all provided functions. + + Examples + -------- + >>> composed = composite_fun(f, g, h) + >>> result = composed(x, year=2030) # equivalent to f(g(h(x, year=2030), year=2030), year=2030) + """ + + def compose(f: Callable[..., T], g: Callable[..., T]) -> Callable[..., T]: + def composed(x: T, **kwargs: Any) -> T: + return f(g(x, **kwargs), **kwargs) + + return composed + + return reduce(compose, funcs, identity_function) + + +def replace_hazard(new_hazard: Hazard) -> HazardChange: + """Return a change function that unconditionally replaces the hazard. + + The returned function ignores its input and always returns ``new_hazard``. + Note that ``new_hazard`` is a shared reference; callers should ensure the + object is not mutated after being passed here. + + Parameters + ---------- + new_hazard : Hazard + The hazard object to substitute in place of the original. + + Returns + ------- + HazardChange + A callable with signature ``(hazard: Hazard) -> Hazard`` + that discards its input and returns ``new_hazard``. + """ + + def hazard_change(_: Hazard) -> Hazard: + return new_hazard + + return hazard_change + + +def impact_intensity_rp_cutoff_helper( + cut_off_rp: float, +) -> HazardChange: + """Return a change function that zeros out low-impact events based on a + return period threshold. + + The returned function computes impacts on the *base* triplet + (``base_exposures``, ``base_impfset``, ``base_hazard``) and identifies + events whose cumulative exceedance frequency does not exceed ``1 / + cut_off_rp``. The intensity rows of those events are set to zero in the + hazard being transformed. + + Parameters + ---------- + cut_off_rp : float + Return period threshold in years. Events whose cumulative exceedance + frequency is at or below ``1 / cut_off_rp`` are zeroed out. + + Returns + ------- + HazardChange + A callable with the following signature: + + .. code-block:: python + + def hazard_change( + hazard: Hazard, + base_exposures: Exposures, + base_impfset: ImpactFuncSet, + base_hazard: Hazard, + exposures_region_id: Optional[list[int]] = None, + ) -> Hazard + + Parameters of the returned callable: + + hazard : Hazard + The hazard object to modify in-place (intensity rows zeroed). + base_exposures : Exposures + Exposures used for the reference impact computation. + base_impfset : ImpactFuncSet + Impact function set used for the reference impact computation. + base_hazard : Hazard + Original hazard used for the reference impact computation. + exposures_region_id : list of int, optional + If provided, the impact computation is restricted to exposure + points whose ``region_id`` is in this list. + + Notes + ----- + The exceedance frequency is computed on the *base* hazard, not on the + already-modified hazard. This ensures the cutoff decision is always + relative to the unmodified risk landscape. + """ + + from climada.engine.impact_calc import ImpactCalc + + def hazard_change( + hazard: Hazard, + base_exposures: Exposures, + base_impfset: ImpactFuncSet, + base_hazard: Hazard, + exposures_region_id: Optional[list[int]] = None, + **_kwargs, + ) -> Hazard: + exp_imp = base_exposures + if exposures_region_id: + # Narrowing the type for the LSP via boolean indexing + in_reg = base_exposures.gdf["region_id"].isin(exposures_region_id) + exp_imp = Exposures(base_exposures.gdf[in_reg], crs=base_exposures.crs) + + imp = ImpactCalc(exp_imp, base_impfset, base_hazard).impact(save_mat=False) + + # Calculate exceedance frequencies + sort_idxs = np.argsort(imp.at_event)[::-1] + exceed_freq = np.cumsum(imp.frequency[sort_idxs]) + events_below_cutoff = sort_idxs[exceed_freq >= (1 / cut_off_rp)] + # Modify sparse data structure + intensity_modified = hazard.intensity.copy() + for event in events_below_cutoff: + start, end = ( + intensity_modified.indptr[event], + intensity_modified.indptr[event + 1], + ) + intensity_modified.data[start:end] = 0 + + hazard.intensity = intensity_modified + hazard.intensity.eliminate_zeros() + return hazard + + return hazard_change + + +def helper_hazard(hazard_modifier: HazardModifierConfig) -> HazardChange: + """Return a change function that scales, shifts, and optionally + replaces hazard intensities and frequencies. + + Constructs a :class:`HazardChange` from a :class:`HazardModifierConfig`. + The returned function optionally loads a new hazard from disk, then applies + a linear transformation to all stored (non-zero) intensity values and to + the event frequencies. + + If :attr:`~HazardModifierConfig.impact_rp_cutoff` is set, the returned + function is further composed (via :func:`composite_fun`) with + :func:`impact_intensity_rp_cutoff_helper` so that events more frequent + than the cutoff return period are zeroed out after the linear + transformations. + + Parameters + ---------- + hazard_modifier : HazardModifierConfig + Configuration object specifying: + + - ``new_hazard_path`` : path to an HDF5 hazard file to load, or + ``None`` to transform the input hazard in-place. + - ``haz_int_mult`` : multiplicative factor applied to intensity data. + - ``haz_int_add`` : additive shift applied to intensity data. + - ``haz_freq_mult`` : multiplicative factor applied to event + frequencies. + - ``haz_freq_add`` : additive shift applied to event frequencies + (to every event). + - ``impact_rp_cutoff`` : return period threshold passed to + :func:`impact_intensity_rp_cutoff_helper`, or ``None`` to skip. + + Returns + ------- + HazardChange + A callable with signature ``(hazard: Hazard, **kwargs) -> Hazard``. + + Notes + ----- + The intensity transformation is applied directly to the sparse matrix's + ``.data`` array, so only explicitly stored (non-zero) entries are + affected. Structural zeros remain zero. Negative intensities and + frequencies are clipped to zero. + + The frequency transformation applies to all events, including those + with no stored intensity. + + ``impact_rp_cutoff`` ranks events using the frequencies of ``base_hazard``, + so the frequency modifiers do not influence which events are removed. + """ + + def hazard_change(hazard: Hazard, **_kwargs) -> Hazard: + changed_hazard = ( + Hazard.from_hdf5(hazard_modifier.new_hazard_path) + if hazard_modifier.new_hazard_path is not None + else hazard + ) + data_int = cast(np.ndarray, changed_hazard.intensity.data) + data_int *= hazard_modifier.haz_int_mult + data_int += hazard_modifier.haz_int_add + data_int[data_int < 0] = 0 + changed_hazard.intensity.eliminate_zeros() + + if hazard_modifier.haz_freq_mult is not None: + changed_hazard.frequency = ( + changed_hazard.frequency * hazard_modifier.haz_freq_mult + ) + + if hazard_modifier.haz_freq_add is not None: + changed_hazard.frequency = ( + changed_hazard.frequency + hazard_modifier.haz_freq_add + ) + + changed_hazard.frequency = changed_hazard.frequency.clip(0, None) + return changed_hazard + + if hazard_modifier.impact_rp_cutoff is not None: + hazard_change = composite_fun( + impact_intensity_rp_cutoff_helper(hazard_modifier.impact_rp_cutoff), + hazard_change, + ) + + return hazard_change + + +def helper_impfset(impfset_modifier: ImpfsetModifierConfig) -> ImpfsetChange: + """Return a change function that applies linear modifications to selected + impact functions. + + Constructs an :class:`ImpfsetChange` from an :class:`ImpfsetModifierConfig`. + The returned function optionally loads a new :class:`ImpactFuncSet` from + disk, then applies independent linear transformations to the ``intensity``, + ``mdd``, and ``paa`` arrays of each targeted impact function. + + Note that the rescale of the intensity axis uses the inverse of the + multiplicative factor and the negative of the additive one, such that a + [0-1] multiplicative factor or positive additive factor actually reduce the + impacts: + + ``impf_int_mult=0.75`` effectively rescale the axis by ``1/0.75`` thus + reducing the impacts for any given intensity by a factor of 0.75. + + Parameters + ---------- + impfset_modifier : ImpfsetModifierConfig + Configuration object specifying: + + - ``new_impfset_path`` : path to an Excel file to load as the new + :class:`ImpactFuncSet`, or ``None`` to modify the input in-place. + - ``haz_type`` : hazard type string used to look up functions. + - ``impf_ids`` : IDs of functions to modify. Accepts ``None`` or + ``"all"`` to target every function of ``haz_type``, a single + ``int`` or ``str``, or a ``list`` of IDs. Raises :class:`ValueError` + for any other type. + - ``impf_int_mult``, ``impf_int_add`` : scale (1/value) and shift (-value) for intensity. + - ``impf_mdd_mult``, ``impf_mdd_add`` : scale and shift for MDD. + - ``impf_paa_mult``, ``impf_paa_add`` : scale and shift for PAA. + + Returns + ------- + ImpfsetChange + A callable with signature ``(impfset: ImpactFuncSet, **kwargs) -> ImpactFuncSet``. + + Raises + ------ + ValueError + If ``impfset_modifier.impf_ids`` is not ``None``, ``"all"``, an + ``int``, a ``str``, or a ``list``. + """ + + def impfset_change(impfset: ImpactFuncSet, **_kwargs) -> ImpactFuncSet: + changed_impfset = ( + impfset.from_excel(impfset_modifier.new_impfset_path) + if impfset_modifier.new_impfset_path is not None + else impfset + ) + if impfset_modifier.impf_ids is None or impfset_modifier.impf_ids == "all": + ids_to_change = changed_impfset.get_ids(haz_type=impfset_modifier.haz_type) + elif isinstance(impfset_modifier.impf_ids, list): + ids_to_change = impfset_modifier.impf_ids + elif isinstance(impfset_modifier.impf_ids, (str, int)): + ids_to_change = [impfset_modifier.impf_ids] + else: + raise ValueError( + f"Impact function ids to changes are invalid: {impfset_modifier.impf_ids}" + ) + + funcs = changed_impfset.get_func(haz_type=impfset_modifier.haz_type) + funcs = [funcs] if isinstance(funcs, ImpactFunc) else funcs + + for impf in funcs: + # Apply Intensity Mod + if impf.id in ids_to_change: + mult, add = ( + impfset_modifier.impf_int_mult, + impfset_modifier.impf_int_add, + ) + impf.intensity = impf.intensity / mult - add + + mult, add = ( + impfset_modifier.impf_mdd_mult, + impfset_modifier.impf_mdd_add, + ) + impf.mdd = impf.mdd * mult + add + + mult, add = ( + impfset_modifier.impf_paa_mult, + impfset_modifier.impf_paa_add, + ) + impf.paa = impf.paa * mult + add + + return changed_impfset + + return impfset_change + + +def change_impfset(new_impfsets: ImpactFuncSet) -> ImpfsetChange: + """Return a change function that unconditionally replaces the impact function set. + + The returned function ignores its input and always returns ``new_impfsets``. + Note that ``new_impfsets`` is a shared reference; callers should ensure the + object is not mutated after being passed here. + + Parameters + ---------- + new_impfsets : ImpactFuncSet + The :class:`ImpactFuncSet` to substitute in place of the original. + + Returns + ------- + ImpfsetChange + A callable with signature ``(impfset: ImpactFuncSet, **kwargs) -> ImpactFuncSet`` + that discards its input and returns ``new_impfsets``. + """ + + def impfset_change(_: ImpactFuncSet) -> ImpactFuncSet: + return new_impfsets + + return impfset_change + + +def helper_exposure(exposures_modifier: ExposuresModifierConfig) -> ExposuresChange: + """Return a change function that reassigns impact function IDs and zeros + selected exposure values. + + Constructs an :class:`ExposuresChange` from an + :class:`ExposuresModifierConfig`. The returned function optionally loads a + new :class:`Exposures` from disk, then applies two optional modifications + to its underlying GeoDataFrame: + + 1. **Impact function ID remapping**: replaces values in + ``impf_`` columns according to a provided mapping dict. + 2. **Value zeroing**: sets ``value`` to ``0`` for rows matching a boolean + mask or index. + + Parameters + ---------- + exposures_modifier : ExposuresModifierConfig + Configuration object specifying: + + - ``new_exposures_path`` : path to an HDF5 file to load as the new + :class:`Exposures`, or ``None`` to modify the input in-place. + - ``reassign_impf_id`` : a ``dict[haz_type, {old_id: new_id}]`` + mapping used to replace impact function IDs in the GeoDataFrame, + or ``None`` to skip. + - ``set_to_zero`` : a boolean array, index, or label accepted by + ``DataFrame.loc`` identifying rows whose ``value`` should be set + to ``0``, or ``None`` to skip. + + Returns + ------- + ExposuresChange + A callable with signature ``(exposures: Exposures, **kwargs) -> Exposures``. + """ + + def exposures_change(exposures: Exposures, **_kwargs) -> Exposures: + changed_exposures = ( + exposures + if exposures_modifier.new_exposures_path is None + else Exposures.from_hdf5(exposures_modifier.new_exposures_path) + ) + gdf = cast(pd.DataFrame, changed_exposures.gdf) + if exposures_modifier.reassign_impf_id is not None: + for haz_type, mapping in exposures_modifier.reassign_impf_id.items(): + gdf[f"impf_{haz_type}"] = gdf[f"impf_{haz_type}"].replace(mapping) + + if exposures_modifier.set_to_zero is not None: + gdf.loc[exposures_modifier.set_to_zero, "value"] = 0 + + return changed_exposures + + return exposures_change diff --git a/climada/entity/measures/measure.py b/climada/entity/measures/measure.py index 9c3c4cbc7..38db9f7fc 100755 --- a/climada/entity/measures/measure.py +++ b/climada/entity/measures/measure.py @@ -31,6 +31,12 @@ from functools import wraps from typing import TYPE_CHECKING, Any, TypeVar +from climada.entity.measures.helper import ( + helper_exposure, + helper_hazard, + helper_impfset, + identity_function, +) from climada.entity.measures.measure_config import MeasureConfig from .cost_income import CostIncome @@ -52,18 +58,6 @@ # TODO: risk transfer? -# Note for review: -# This function will moved in helper.py in a future PR which will -# add I/O based on MeasureConfig dataclasses -def identity_function(x: T, **_kwargs: Any) -> T: - """Identity function - - Returns the provided parameter. Usefull to design measures without effect - on some of the risk components (Hazard, Exposures, Impact Function) - """ - return x - - def allow_kwargs(func): """ Decorator that allows a function to accept (and silently ignore) keyword arguments. @@ -217,6 +211,60 @@ def is_serializable(self) -> bool: return self._config is not None + @classmethod + def from_config(cls, config: MeasureConfig) -> "Measure": + """Create a ``Measure`` from a ``MeasureConfig`` object. + + The modifiers defined in the configuration are converted into change + functions for the exposures, impact function set and hazard. The + configuration is stored on the new measure, which therefore is + serializable (see :attr:`is_serializable`). + + Parameters + ---------- + config : MeasureConfig + Configuration defining the name, modifiers, cost and income, and + color of the measure. + + Returns + ------- + Measure + The measure built from ``config``. + """ + impfset_change = helper_impfset(config.impfset_modifier) + exp_change = helper_exposure(config.exposures_modifier) + haz_change = helper_hazard(config.hazard_modifier) + return cls( + name=config.name, + exposures_changes=exp_change, + impfset_changes=impfset_change, + hazard_changes=haz_change, + cost_income=CostIncome.from_config(config.cost_income), + color_rgb=config.color_rgb, + _config=config, + ) + + @classmethod + def from_dict(cls, d: dict) -> "Measure": + """Create a ``Measure`` from a dictionary. + + The dictionary is first converted to a ``MeasureConfig`` with + :py:meth:`MeasureConfig.from_dict`, then to a ``Measure`` with + :py:meth:`Measure.from_config`. + + Parameters + ---------- + d : dict + Dictionary describing a single measure, in the format expected by + :py:meth:`MeasureConfig.from_dict`. + + Returns + ------- + Measure + The measure built from ``d``. + """ + return cls.from_config(MeasureConfig.from_dict(d)) + def apply_exposures_changes( self, exposures: Exposures, enforce_copy: bool = True, **kwargs ) -> Exposures: diff --git a/climada/entity/measures/measure_config.py b/climada/entity/measures/measure_config.py index e19310615..77ec61d32 100644 --- a/climada/entity/measures/measure_config.py +++ b/climada/entity/measures/measure_config.py @@ -78,7 +78,7 @@ def _filter_out_default_fields(self) -> tuple[dict[str, Any], dict[str, Any]]: if defined_field.default_factory is not MISSING: default = defined_field.default_factory() - if val != default: + if (default is None and val is not None) or val != default: non_defaults[defined_field.name] = val else: defaults[defined_field.name] = val @@ -261,7 +261,7 @@ class HazardModifierConfig(ModifierConfig): Configuration for modifications to a hazard. Supports scaling or shifting hazard intensity, applying a return-period - frequency cutoff, and replacement of the hazard, loaded from a file path. + cutoff, and replacement of the hazard, loaded from a file path. If both a new file path and modifier values are provided, modifiers are applied after the replacement. @@ -275,6 +275,12 @@ class HazardModifierConfig(ModifierConfig): haz_int_add : float, optional Additive offset applied to hazard intensity after multiplication. Default is ``0.0``. + haz_freq_mult : float, optional + Multiplicative factor applied to hazard frequency. + Default is ``1.0`` (no change). + haz_freq_add : float, optional + Additive offset applied to hazard frequency after multiplication. + Default is ``0.0``. new_hazard_path : str, optional Path to an HDF5 file containing a replacement hazard. If provided alongside modifier values, a warning is issued and @@ -333,7 +339,8 @@ class ExposuresModifierConfig(ModifierConfig): impact function IDs in the exposures. If ``None``, no remapping is performed. set_to_zero : list of int, optional - Region IDs for which exposure values are set to zero. + Exposures GeoDataFrame indices for which exposure values + are set to zero. If ``None``, no zeroing is applied. new_exposures_path : str, optional Path to an HDF5 file containing replacement exposures. diff --git a/climada/entity/measures/test/conftest.py b/climada/entity/measures/test/conftest.py new file mode 100644 index 000000000..e7cd59a71 --- /dev/null +++ b/climada/entity/measures/test/conftest.py @@ -0,0 +1,307 @@ +""" +This file is part of CLIMADA. + +Copyright (C) 2017 ETH Zurich, CLIMADA contributors listed in AUTHORS. + +CLIMADA is free software: you can redistribute it and/or modify it under the +terms of the GNU General Public License as published by the Free +Software Foundation, version 3. + +CLIMADA is distributed in the hope that it will be useful, but WITHOUT ANY +WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A +PARTICULAR PURPOSE. See the GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with CLIMADA. If not, see . +--- + +A set of reusable fixtures for testing purpose. + +The objective of this file is to provide minimalistic, understandable and consistent +default objects for unit and integration testing. + +Values are chosen such that: + - Exposure value of the first points is 0. (First location should always have 0 impacts) + - Category / Group id of all points is 1, except for third point, valued at 2000 (Impacts on that category are always a share of 2000) + - Hazard centroids are the exposure centroids shifted by `HAZARD_JITTER` on both lon and lat. + - There are 4 events, with frequencies == 0.03, 0.01, 0.006, 0.004, 0, + such that impacts for RP250, 100 and 50 and 20 are at_event, + (freq sorted cumulate to 1/250, 1/100, 1/50 and 1/20). + - Hazard intensity is: + * Event 1: zero everywhere (always no impact) + * Event 2: max intensity at first centroid (also always no impact (first centroid is 0)) + * Event 3: half max intensity at second centroid (impact == half second centroid) + * Event 4: quarter max intensity everywhere (impact == 1/4 total value) + * Event 5: max intensity everywhere (but zero frequency) + With max intensity set at 100 + - Impact function is the "identity function", x intensity is x% damages + - Impact values should be: + * AAI = 18 = 1000*1/2*0.006+(1000+2000+3000+4000+5000)*0.25*0.004 + * RP20 = event1 = 0 + * RP50 = event2 = 0 + * RP100 = event3 = 500 = 1000*1/2 + * RP250 = event4 = 3750 = (1000+2000+3000+4000+5000)*0.25 + +""" + +import geopandas as gpd +import numpy as np +import pytest +from scipy.sparse import csr_matrix + +from climada.entity import Exposures, ImpactFunc, ImpactFuncSet +from climada.hazard import Centroids, Hazard + +# --------------------------------------------------------------------------- +# Coordinate system and metadata +# --------------------------------------------------------------------------- +CRS_WGS84 = "EPSG:4326" + +# --------------------------------------------------------------------------- +# Exposure attributes +# --------------------------------------------------------------------------- +EXP_DESC = "Test exposure dataset" +EXPOSURE_REF_YEAR = 2020 +EXPOSURE_VALUE_UNIT = "USD" +VALUES = np.array([0, 1000, 2000, 3000, 4000, 5000]) +CATEGORIES = np.array([1, 1, 2, 1, 1, 3]) + +# Exposure coordinates +EXP_LONS = np.array([4, 4.25, 4.5, 4, 4.25, 4.5]) +EXP_LATS = np.array([33, 33, 33, 33.25, 33.25, 33.25]) + +# --------------------------------------------------------------------------- +# Hazard definition +# --------------------------------------------------------------------------- +HAZARD_TYPE = "TEST_HAZARD_TYPE" +HAZARD_UNIT = "TEST_HAZARD_UNIT" + +# Hazard centroid positions +HAZ_JITTER = 0.1 # To test centroid matching +HAZ_LONS = EXP_LONS + HAZ_JITTER +HAZ_LATS = EXP_LATS + HAZ_JITTER + +# Hazard events +EVENT_IDS = np.array([1, 2, 3, 4, 5]) +EVENT_NAMES = ["ev1", "ev2", "ev3", "ev4", "ev5"] +DATES = np.array([1, 2, 3, 4, 5]) + +# Frequency are choosen so that they cumulate nicely +# to correspond to 250, 100, 50, and 20y return periods (for impacts) +FREQUENCY = np.array([0.03, 0.01, 0.006, 0.004, 0.0]) +FREQUENCY_UNIT = "1/year" + +# Hazard maximum intensity +# 100 to match 0 to 100% idea +# also in line with linear 1:1 impact function +# for easy mental calculus +HAZARD_MAX_INTENSITY = 100 + +# --------------------------------------------------------------------------- +# Impact function +# --------------------------------------------------------------------------- +IMPF_ID = 1 +IMPF_NAME = "IMPF_1" + + +@pytest.fixture +def exposures_factory(): + def _make_exposures( + values=VALUES, + exp_lons=EXP_LONS, + exp_lats=EXP_LATS, + value_factor=1.0, + ref_year=EXPOSURE_REF_YEAR, + hazard_type=HAZARD_TYPE, + group_id=None, + crs=CRS_WGS84, + impf_id=IMPF_ID, + description=EXP_DESC, + value_unit=EXPOSURE_VALUE_UNIT, + categories=None, + ): + gdf = gpd.GeoDataFrame( + { + "value": values * value_factor, + f"impf_{hazard_type}": impf_id, + "category": categories, + "geometry": gpd.points_from_xy(exp_lons, exp_lats, crs=crs), + }, + crs=crs, + ) + if group_id is not None: + gdf["group_id"] = group_id + + return Exposures( + data=gdf, + description=description, + ref_year=ref_year, + value_unit=value_unit, + ) + + return _make_exposures + + +@pytest.fixture +def exposures(exposures_factory): + return exposures_factory() + + +def hazard_frequency_factory(base=FREQUENCY): + def _make_frequency(scale=1.0): + return base * scale + + return _make_frequency + + +def hazard_frequency(): + return hazard_frequency_factory() + + +def hazard_intensity(max_intensity=HAZARD_MAX_INTENSITY, scale=1.0): + """ + Intensity matrix designed for analytical expectations: + - Event 1: zero + - Event 2: max intensity at first centroid + - Event 3: half max intensity at second centroid + - Event 4: quarter max intensity everywhere + """ + base = csr_matrix( + [ + [0, 0, 0, 0, 0, 0], + [max_intensity, 0, 0, 0, 0, 0], + [0, max_intensity / 2, 0, 0, 0, 0], + [ + max_intensity / 4, + max_intensity / 4, + max_intensity / 4, + max_intensity / 4, + max_intensity / 4, + max_intensity / 4, + ], + [ + max_intensity, + max_intensity, + max_intensity, + max_intensity, + max_intensity, + max_intensity, + ], + ] + ) + + return base * scale + + +@pytest.fixture +def centroids(): + return Centroids(lat=HAZ_LATS, lon=HAZ_LONS, crs=CRS_WGS84) + + +@pytest.fixture +def hazard_factory(): + def _make_hazard( + intensity_matrix=None, + frequency_array=FREQUENCY, + max_intensity=HAZARD_MAX_INTENSITY, + centroids=None, + intensity_scale=1.0, + frequency_scale=1.0, + hazard_type=HAZARD_TYPE, + hazard_unit=HAZARD_UNIT, + lat=HAZ_LATS, + lon=HAZ_LONS, + crs=CRS_WGS84, + event_id=EVENT_IDS, + event_name=EVENT_NAMES, + date=DATES, + frequency_unit=FREQUENCY_UNIT, + ): + if intensity_matrix is None: + intensity_matrix = hazard_intensity(max_intensity, intensity_scale) + + if centroids is None: + centroids = Centroids(lat=lat, lon=lon, crs=crs) + + return Hazard( + haz_type=hazard_type, + units=hazard_unit, + centroids=centroids, + event_id=event_id, + event_name=event_name, + date=date, + frequency=frequency_array * frequency_scale, + frequency_unit=frequency_unit, + intensity=intensity_matrix, + ) + + return _make_hazard + + +@pytest.fixture +def hazard(hazard_factory): + return hazard_factory() + + +@pytest.fixture +def impf_factory(): + def _make_impf( + paa_scale=1.0, + max_intensity=HAZARD_MAX_INTENSITY, + hazard_type=HAZARD_TYPE, + hazard_unit=HAZARD_UNIT, + impf_id=IMPF_ID, + negative_intensities=False, + ): + intensity = np.array([0, max_intensity / 2, max_intensity]) + mdd = np.array([0, 0.5, 1]) + if negative_intensities: + intensity = np.flip(intensity) * -1 + mdd = np.flip(mdd) + return ImpactFunc( + haz_type=hazard_type, + intensity_unit=hazard_unit, + name=IMPF_NAME, + intensity=intensity, + mdd=mdd, + paa=np.array([1, 1, 1]) * paa_scale, + id=impf_id, + ) + + return _make_impf + + +@pytest.fixture +def linear_impact_function(impf_factory): + return impf_factory() + + +@pytest.fixture +def impfset_factory(impf_factory): + def _make_impfset( + paa_scale=1.0, + max_intensity=HAZARD_MAX_INTENSITY, + hazard_type=HAZARD_TYPE, + hazard_unit=HAZARD_UNIT, + impf_id=IMPF_ID, + negative_intensities=False, + ): + return ImpactFuncSet( + [ + impf_factory( + paa_scale, + max_intensity, + hazard_type, + hazard_unit, + impf_id, + negative_intensities, + ) + ] + ) + + return _make_impfset + + +@pytest.fixture +def impfset(impfset_factory): + return impfset_factory() diff --git a/climada/entity/measures/test/test_helper.py b/climada/entity/measures/test/test_helper.py new file mode 100644 index 000000000..f507b658b --- /dev/null +++ b/climada/entity/measures/test/test_helper.py @@ -0,0 +1,446 @@ +""" +This file is part of CLIMADA. + +Copyright (C) 2017 ETH Zurich, CLIMADA contributors listed in AUTHORS. + +CLIMADA is free software: you can redistribute it and/or modify it under the +terms of the GNU General Public License as published by the Free +Software Foundation, version 3. + +CLIMADA is distributed in the hope that it will be useful, but WITHOUT ANY +WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A +PARTICULAR PURPOSE. See the GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with CLIMADA. If not, see . + +--- + + +Unit tests for the helper functions. +""" + +from unittest.mock import MagicMock + +import numpy as np +import pytest + +from climada.entity.measures.helper import ( + change_impfset, + composite_fun, + helper_exposure, + helper_hazard, + helper_impfset, + impact_intensity_rp_cutoff_helper, + replace_hazard, +) +from climada.entity.measures.measure_config import ( + ExposuresModifierConfig, + HazardModifierConfig, + ImpfsetModifierConfig, +) +from climada.entity.measures.test.conftest import ( + HAZARD_MAX_INTENSITY, + HAZARD_TYPE, + IMPF_ID, +) + + +class TestCompositeFun: + def test_single_function_applied(self): + double = lambda x, **kw: x * 2 + composed = composite_fun(double) + assert composed(3) == 6 + + def test_two_functions_applied_right_to_left(self): + add1 = lambda x, **kw: x + 1 + double = lambda x, **kw: x * 2 + # composite_fun(add1, double) => add1(double(x)) => 2*x + 1 + composed = composite_fun(add1, double) + assert composed(3) == 7 + + def test_three_functions_order(self): + f = lambda x, **kw: x + 10 + g = lambda x, **kw: x * 2 + h = lambda x, **kw: x - 1 + # f(g(h(x))) = f(g(x-1)) = f(2*(x-1)) = 2*(x-1) + 10 + composed = composite_fun(f, g, h) + assert composed(5) == 18 + + def test_no_functions_returns_identity(self): + composed = composite_fun() + obj = object() + assert composed(obj) is obj + + def test_kwargs_forwarded_to_all_functions(self): + received_by_f, received_by_g = {}, {} + + def f(x, **kw): + received_by_f.update(kw) + return x + + def g(x, **kw): + received_by_g.update(kw) + return x + + composite_fun(f, g)(42, year=2030) + assert received_by_f.get("year") == 2030 + assert received_by_g.get("year") == 2030 + + +# =========================================================================== +# replace_hazard +# =========================================================================== + + +class TestReplaceHazard: + def test_returns_new_hazard_ignoring_input(self): + new_haz = MagicMock() + original_haz = MagicMock() + fn = replace_hazard(new_haz) + result = fn(original_haz) + assert result is new_haz + + def test_different_inputs_always_return_same_object(self): + new_haz = MagicMock() + fn = replace_hazard(new_haz) + assert fn(MagicMock()) is new_haz + assert fn(MagicMock()) is new_haz + + +# =========================================================================== +# helper_hazard (no new hazard path, no rp cutoff) +# =========================================================================== + + +class TestHelperHazard: + def _config(self, mult=1.0, add=0.0, path=None, rp=None): + return HazardModifierConfig( + haz_type="TEST", + haz_int_mult=mult, + haz_int_add=add, + new_hazard_path=path, + impact_rp_cutoff=rp, + ) + + def test_identity_transform_leaves_data_unchanged(self, hazard_factory): + haz = hazard_factory() + original_data = haz.intensity.data.copy() + fn = helper_hazard(self._config(mult=1.0, add=0.0)) + result = fn(haz) + np.testing.assert_allclose(result.intensity.data, original_data) + + def test_multiplicative_scaling(self, hazard_factory): + haz = hazard_factory() + original_data = haz.intensity.data.copy() + fn = helper_hazard(self._config(mult=0.5)) + result = fn(haz) + np.testing.assert_allclose(result.intensity.data, original_data * 0.5) + + def test_additive_shift_on_nonzero_entries(self, hazard_factory): + haz = hazard_factory() + original_data = haz.intensity.data.copy() + fn = helper_hazard(self._config(add=10.0)) + result = fn(haz) + np.testing.assert_allclose(result.intensity.data, original_data + 10.0) + + def test_negative_results_clipped_to_zero(self, hazard_factory): + haz = hazard_factory() + fn = helper_hazard(self._config(mult=-1.0)) + result = fn(haz) + assert result.intensity.nnz == 0 + + def test_negative_after_add_clipped_and_eliminated(self, hazard_factory): + haz = hazard_factory() + fn = helper_hazard(self._config(add=-HAZARD_MAX_INTENSITY - 1)) + result = fn(haz) + assert (result.intensity.data >= 0).all() + + def test_combined_mult_and_add(self, hazard_factory): + haz = hazard_factory() + original_data = haz.intensity.data.copy() + fn = helper_hazard(self._config(mult=2.0, add=5.0)) + result = fn(haz) + np.testing.assert_allclose(result.intensity.data, original_data * 2.0 + 5.0) + + def test_returns_hazard_object(self, hazard_factory): + from climada.hazard.base import Hazard + + haz = hazard_factory() + fn = helper_hazard(self._config()) + assert isinstance(fn(haz), Hazard) + + +# =========================================================================== +# helper_hazard (with rp_cutoff — exercises impact_intensity_rp_cutoff_helper) +# =========================================================================== + + +class TestHelperHazardRpCutoff: + """ + Integration of helper_hazard + impact_intensity_rp_cutoff_helper. + + Using the conftest fixture setup: + - Event 1 (freq 0.03): zero impact everywhere → should be zeroed for any RP + - Event 2 (freq 0.01): zero impact (hits centroid 0, value=0) → zeroed for any RP + - Event 3 (freq 0.006): impact = 500 → RP ~167y + - Event 4 (freq 0.004): impact = 3750 → RP = 250y + - Event 5 (freq 0.0): zero frequency → never contributes + """ + + def _config_with_rp(self, rp): + return HazardModifierConfig( + haz_type=HAZARD_TYPE, + impact_rp_cutoff=rp, + ) + + def test_very_large_rp_zeros_all_events(self, hazard_factory, exposures, impfset): + """RP larger than any event → all intensities zeroed.""" + # Avoid the 0 freq of the default hazard_factory settings + haz = hazard_factory(frequency_array=np.array([0.1, 0.2, 0.3, 0.4, 0.5])) + fn = helper_hazard(self._config_with_rp(10_000)) + result = fn( + haz, + base_exposures=exposures, + base_impfset=impfset, + base_hazard=haz, + ) + assert result.intensity.nnz == 0 + + def test_very_small_rp_keeps_all_events(self, hazard_factory, exposures, impfset): + """RP smaller than all events → nothing is zeroed.""" + haz = hazard_factory() + original_nnz = haz.intensity.nnz + fn = helper_hazard(self._config_with_rp(1)) + result = fn( + haz, + base_exposures=exposures, + base_impfset=impfset, + base_hazard=haz, + ) + assert result.intensity.nnz == original_nnz + + +# =========================================================================== +# impact_intensity_rp_cutoff_helper (directly) +# =========================================================================== + + +class TestImpactIntensityRpCutoffHelper: + def test_returns_callable(self): + fn = impact_intensity_rp_cutoff_helper(100) + assert callable(fn) + + def test_region_id_filter_restricts_impact_computation( + self, hazard_factory, exposures_factory, impfset + ): + """Passing exposures_region_id should not raise and should return a Hazard.""" + from climada.hazard.base import Hazard + + exp = exposures_factory() + exp.gdf["region_id"] = [1, 1, 2, 2, 1, 1] + haz = hazard_factory() + + fn = impact_intensity_rp_cutoff_helper(50) + result = fn( + haz, + base_exposures=exp, + base_impfset=impfset, + base_hazard=haz, + exposures_region_id=[1], + ) + assert isinstance(result, Hazard) + + +# =========================================================================== +# change_impfset +# =========================================================================== + + +class TestChangeImpfset: + def test_returns_new_impfset_ignoring_input(self, impfset_factory): + new_ifs = impfset_factory() + original_ifs = impfset_factory() + fn = change_impfset(new_ifs) + assert fn(original_ifs) is new_ifs + + def test_repeated_calls_return_same_object(self, impfset_factory): + new_ifs = impfset_factory() + fn = change_impfset(new_ifs) + assert fn(impfset_factory()) is new_ifs + assert fn(impfset_factory()) is new_ifs + + +# =========================================================================== +# helper_impfset +# =========================================================================== + + +class TestHelperImpfset: + def _config( + self, + impf_ids=None, + int_mult=1.0, + int_add=0.0, + mdd_mult=1.0, + mdd_add=0.0, + paa_mult=1.0, + paa_add=0.0, + path=None, + ): + return ImpfsetModifierConfig( + haz_type=HAZARD_TYPE, + impf_ids=impf_ids, + impf_int_mult=int_mult, + impf_int_add=int_add, + impf_mdd_mult=mdd_mult, + impf_mdd_add=mdd_add, + impf_paa_mult=paa_mult, + impf_paa_add=paa_add, + new_impfset_path=path, + ) + + def test_identity_transform_leaves_functions_unchanged(self, impfset_factory): + ifs = impfset_factory() + original_mdd = ifs.get_func(haz_type=HAZARD_TYPE)[0].mdd.copy() + fn = helper_impfset(self._config()) + result = fn(ifs) + np.testing.assert_allclose( + result.get_func(haz_type=HAZARD_TYPE)[0].mdd, original_mdd + ) + + def test_mdd_multiplicative_scaling(self, impfset_factory): + ifs = impfset_factory() + original_mdd = ifs.get_func(haz_type=HAZARD_TYPE)[0].mdd.copy() + fn = helper_impfset(self._config(mdd_mult=0.5)) + result = fn(ifs) + np.testing.assert_allclose( + result.get_func(haz_type=HAZARD_TYPE)[0].mdd, original_mdd * 0.5 + ) + + def test_paa_additive_shift(self, impfset_factory): + ifs = impfset_factory() + original_paa = ifs.get_func(haz_type=HAZARD_TYPE)[0].paa.copy() + fn = helper_impfset(self._config(paa_add=0.1)) + result = fn(ifs) + np.testing.assert_allclose( + result.get_func(haz_type=HAZARD_TYPE)[0].paa, original_paa + 0.1 + ) + + def test_intensity_linear_transform(self, impfset_factory): + ifs = impfset_factory() + original_int = ifs.get_func(haz_type=HAZARD_TYPE)[0].intensity.copy() + fn = helper_impfset(self._config(int_mult=2.0, int_add=5.0)) + result = fn(ifs) + np.testing.assert_allclose( + result.get_func(haz_type=HAZARD_TYPE)[0].intensity, + original_int / 2.0 - 5.0, + ) + + def test_specific_impf_id_targeted(self, impfset_factory): + ifs = impfset_factory() + original_mdd = ifs.get_func(haz_type=HAZARD_TYPE)[0].mdd.copy() + fn = helper_impfset(self._config(impf_ids=IMPF_ID, mdd_mult=0.0)) + result = fn(ifs) + np.testing.assert_allclose( + result.get_func(haz_type=HAZARD_TYPE)[0].mdd, original_mdd * 0.0 + ) + + def test_non_matching_impf_id_not_modified(self, impfset_factory): + ifs = impfset_factory() + original_mdd = ifs.get_func(haz_type=HAZARD_TYPE)[0].mdd.copy() + fn = helper_impfset(self._config(impf_ids=IMPF_ID + 99, mdd_mult=0.0)) + result = fn(ifs) + np.testing.assert_allclose( + result.get_func(haz_type=HAZARD_TYPE)[0].mdd, original_mdd + ) + + def test_all_keyword_targets_every_function(self, impfset_factory): + ifs = impfset_factory() + fn = helper_impfset(self._config(impf_ids="all", paa_mult=0.0)) + result = fn(ifs) + for impf in result.get_func(haz_type=HAZARD_TYPE): + np.testing.assert_allclose(impf.paa, 0.0) + + def test_invalid_impf_ids_raises_value_error(self, impfset_factory): + ifs = impfset_factory() + fn = helper_impfset(self._config(impf_ids={"invalid": "dict"})) + with pytest.raises(ValueError, match="invalid"): + fn(ifs) + + def test_list_of_ids(self, impfset_factory): + ifs = impfset_factory() + fn = helper_impfset(self._config(impf_ids=[IMPF_ID], mdd_add=1.0)) + original_mdd = ifs.get_func(haz_type=HAZARD_TYPE)[0].mdd.copy() + result = fn(ifs) + np.testing.assert_allclose( + result.get_func(haz_type=HAZARD_TYPE)[0].mdd, original_mdd + 1.0 + ) + + +# =========================================================================== +# helper_exposure +# =========================================================================== + + +class TestHelperExposure: + def _config(self, reassign=None, set_to_zero=None, path=None): + return ExposuresModifierConfig( + new_exposures_path=path, + reassign_impf_id=reassign, + set_to_zero=set_to_zero, + ) + + def test_identity_config_leaves_exposure_unchanged(self, exposures_factory): + exp = exposures_factory() + original_values = exp.gdf["value"].copy() + fn = helper_exposure(self._config()) + result = fn(exp) + np.testing.assert_array_equal( + result.gdf["value"].values, original_values.values + ) + + def test_set_to_zero_by_boolean_mask(self, exposures_factory): + exp = exposures_factory() + mask = exp.gdf["value"] > 2000 + fn = helper_exposure(self._config(set_to_zero=mask)) + result = fn(exp) + assert (result.gdf.loc[mask, "value"] == 0).all() + + def test_set_to_zero_does_not_affect_other_rows(self, exposures_factory): + exp = exposures_factory() + mask = exp.gdf["value"] > 4000 + original_below = exp.gdf.loc[~mask, "value"].copy() + fn = helper_exposure(self._config(set_to_zero=mask)) + result = fn(exp) + np.testing.assert_array_equal( + result.gdf.loc[~mask, "value"].values, original_below.values + ) + + def test_reassign_impf_id_remaps_correctly(self, exposures_factory): + exp = exposures_factory(impf_id=1) + col = f"impf_{HAZARD_TYPE}" + fn = helper_exposure(self._config(reassign={HAZARD_TYPE: {1: 2}})) + result = fn(exp) + assert (result.gdf[col] == 2).all() + + def test_reassign_impf_id_unknown_value_left_unchanged(self, exposures_factory): + exp = exposures_factory(impf_id=1) + col = f"impf_{HAZARD_TYPE}" + fn = helper_exposure(self._config(reassign={HAZARD_TYPE: {99: 2}})) + result = fn(exp) + assert (result.gdf[col] == 1).all() + + def test_combined_set_to_zero_and_reassign(self, exposures_factory): + exp = exposures_factory(impf_id=1) + col = f"impf_{HAZARD_TYPE}" + mask = exp.gdf["value"] > 3000 + fn = helper_exposure( + self._config( + set_to_zero=mask, + reassign={HAZARD_TYPE: {1: 3}}, + ) + ) + result = fn(exp) + assert (result.gdf.loc[mask, "value"] == 0).all() + assert (result.gdf[col] == 3).all() diff --git a/doc/user-guide/climada_measures.ipynb b/doc/user-guide/climada_measures.ipynb index 8d2c9a7ba..d15ad4282 100644 --- a/doc/user-guide/climada_measures.ipynb +++ b/doc/user-guide/climada_measures.ipynb @@ -227,16 +227,74 @@ "id": "b5c1873f", "metadata": {}, "source": [ - "## Defining Measure using measure configuration" + "## Defining measures using measure configuration\n", + "\n", + "Defining adaptation measures with Python functions can be difficult if you are not familiar with Python. For common changes, a `Measure` can instead be described *declaratively* with a `MeasureConfig` object. A configuration can also be written to, and read from, a YAML file (see the [detailed tutorial](measure-config-tutorial)).\n", + "\n", + "A `MeasureConfig` aggregates one configuration object per component of the measure:\n", + "\n", + "| Field | Class | Main parameters |\n", + "|---|---|---|\n", + "| `hazard_modifier` | `HazardModifierConfig` | `haz_int_mult`, `haz_int_add`, `impact_rp_cutoff`, `new_hazard_path` |\n", + "| `impfset_modifier` | `ImpfsetModifierConfig` | `impf_ids`, `impf_{mdd,paa,int}_{mult,add}`, `new_impfset_path` |\n", + "| `exposures_modifier` | `ExposuresModifierConfig` | `reassign_impf_id`, `new_exposures_path` |\n", + "| `cost_income` | `CostIncomeConfig` | same parameters as `CostIncome` |\n", + "\n", + "All parameters default to \"no change\" (multipliers of `1.0`, offsets of `0.0`, `None` otherwise). A `new_*_path` loads a replacement object from file; if modifiers are also given, they are applied after the replacement (and a warning is issued)." + ] + }, + { + "cell_type": "markdown", + "id": "4e7a2c91", + "metadata": {}, + "source": [ + "### Creating a measure from a configuration\n", + "\n", + "The measure below reduces the mean damage degree of impact function `1` by 25 %, and removes the events that are more frequent than a 1-in-20-year event (ranked by their **impact** in the baseline situation not their intensity).\n", + "`Measure.from_config` converts the configuration into the corresponding transformation functions." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c3d90b57", + "metadata": {}, + "outputs": [], + "source": [ + "from climada.entity.measures.measure import Measure\n", + "from climada.entity.measures.measure_config import (\n", + " CostIncomeConfig,\n", + " ExposuresModifierConfig,\n", + " HazardModifierConfig,\n", + " ImpfsetModifierConfig,\n", + " MeasureConfig,\n", + ")\n", + "\n", + "config = MeasureConfig(\n", + " name=\"Flood proofing and protection standard\",\n", + " haz_type=\"FL\",\n", + " impfset_modifier=ImpfsetModifierConfig(\n", + " haz_type=\"FL\", impf_ids=1, impf_mdd_mult=0.75\n", + " ),\n", + " hazard_modifier=HazardModifierConfig(haz_type=\"FL\", impact_rp_cutoff=20),\n", + " exposures_modifier=ExposuresModifierConfig(), # no change, note that you can also just leave it out entirely\n", + " cost_income=CostIncomeConfig(init_cost=1_000_000, periodic_cost=50_000),\n", + " color_rgb=(0.1, 0.4, 0.8),\n", + ")\n", + "\n", + "measure = Measure.from_config(config)" ] }, { "cell_type": "markdown", - "id": "9a13d39e", + "id": "a81f6d02", "metadata": {}, "source": [ - "Defining adaptation measures with python functions can be a bit difficult if you are not too familiar with python.\n", - "In that case you can use `MeasureConfig` objects ([tutorial here](measure-config-tutorial))" + "The resulting `Measure` is used like any other. The `base_*` triplet needed by `impact_rp_cutoff` is provided automatically by `Measure.apply`.\n", + "\n", + "```python\n", + "imp_with_measure = measure.calc_impact(exp, impfset, haz)\n", + "```" ] }, {