climada.entity.measures package#
Note
This package implements the new way of defining measures. For the previous way, see climada.entity._legacy_measures
climada.entity.measures.base module#
- class climada.entity.measures.base.Measure(name: str, *, exposures_changes: ExposuresChange = <function identity_function>, impfset_changes: ImpfsetChange = <function identity_function>, hazard_changes: HazardChange = <function identity_function>, sub_measures: Optional[list[str]] = None, cost_income: Optional[CostIncome] = None, implementation_duration: Optional[BaseOffset] = None, color_rgb: Optional[Tuple[float, float, float]] = None, _config: Optional[MeasureConfig] = None)[source]#
Bases:
objectContains a measure to be applied to a set of exposures, impact functions, and hazard.
A
Measurerepresents a single adaptation or risk-reduction action. It holds three (optional) transformation functions, one each forExposures,ImpactFuncSet, andHazard, that are can be applied to a triplet of(Exposures, ImpactFuncSet, Hazard), to reflect the effect of the measure.It also holds a CostIncome object to define the financial aspects of the measure (see
CostIncomeand Measure cash flows with CostIncome).Finally it holds an implementation_duration attribute, in the form of a pandas
DateOffset, which is used when the time dimension is considered.Notes
The only requirement for each function is to return an object of the same class (e.g.
Hazardforhazard_change). Functions can accept keyword arguments to enable advanced effect (depending on a year of application for instance). These arguments can be passed when theMeasureis applied (seeapply()). Note that for convenience, each functions receive the by default “base”(Exposures, ImpactFuncSet, Hazard)triplet as keyword arguments (base_exposure, base_impfset, base_hazard).If the
Measurewas defined from aMeasureConfigobject, the configuration is stored and the measure can be serialized to a file. (see Defining Adaptation Measures with configurations and measure-tutorial).- name#
Name of the measure.
- Type:
str
- exposures_change#
Function to change exposures.
- Type:
ExposuresChange
- impfset_change#
Function to change impact function set.
- Type:
ImpfsetChange
- hazard_change#
Function to change hazard.
- Type:
HazardChange
- sub_measures#
List of measure names that this measure is a combination of.
- Type:
list of str, optional
- cost_income#
Cost and income object associated with the measure.
- implementation_duration#
Duration of implementation before the measure is fully functional.
- Type:
pd.DateOffset, optional
- __init__(name: str, *, exposures_changes: ExposuresChange = <function identity_function>, impfset_changes: ImpfsetChange = <function identity_function>, hazard_changes: HazardChange = <function identity_function>, sub_measures: Optional[list[str]] = None, cost_income: Optional[CostIncome] = None, implementation_duration: Optional[BaseOffset] = None, color_rgb: Optional[Tuple[float, float, float]] = None, _config: Optional[MeasureConfig] = None)[source]#
Initialize a new Measure object.
- Parameters:
name (str) – Name of the measure.
exposures_change (callable, optional) – Transformation function for Exposures. Defaults to identity.
impfset_change (callable, optional) – Transformation function for ImpactFuncSet. Defaults to identity.
hazard_change (callable, optional) – Transformation function for Hazard. Defaults to identity.
sub_measures (list of str, optional) – Names of component measures.
cost_income (CostIncome, optional) – Financial data. If None, an empty CostIncome is initialized.
implementation_duration (pd.DateOffset, optional) – Time offset for full implementation.
- property is_serializable: bool#
Returns True if the
Measurewas created from aMeasureConfigobject and can be serialized.
- apply_exposures_changes(exposures: Exposures, enforce_copy: bool = True, **kwargs) Exposures[source]#
Apply the changes from the measure to the given
Exposuresobject.This method applies the exposures_changes function of the measure to the provided
Exposuresobject. Ifenforce_copyis True (default), a deep copy of the exposures is created before modification to ensure immutability of the original object.Additional keyword arguments to the function can be passed directly.
- Parameters:
exposures (Exposures) – The input exposures object to be transformed.
enforce_copy (bool, optional) – If True (default), creates a deep copy of exposures before applying changes, provided the transformation function is not the identity function. If False, the original object may be modified in-place depending on the behavior of exposures_changes.
**kwargs (dict, optional) – Additional keyword arguments passed directly to the exposures_changes function.
- Returns:
The resulting
Exposuresobject after the transformation has been applied. If enforce_copy was True, this is a new object.- Return type:
Notes
The deep copy operation is skipped if enforce_copy is False or if self.exposures_changes is the identity function, optimizing performance when no actual changes are expected or when in-place modification is desired.
- apply_impfset_changes(impfset: ImpactFuncSet, enforce_copy: bool = True, **kwargs) ImpactFuncSet[source]#
Apply the changes from the measure to the given
ImpactFuncSetobject.This method applies the impfset_changes function of the measure to the provided
ImpactFuncSetobject. If enforce_copy is True (default), a deep copy of the impfset is created before modification to ensure immutability of the original object.- Parameters:
impfset (ImpactFuncSet) – The input impfset object to be transformed.
enforce_copy (bool, optional) – If True (default), creates a deep copy of impfset before applying changes, provided the transformation function is not the identity function. If False, the original object may be modified in-place depending on the behavior of impfset_changes.
**kwargs (dict, optional) – Additional keyword arguments passed directly to the impfset_changes function.
- Returns:
The resulting
ImpactFuncSetafter the transformation has been applied. If enforce_copy was True, this is a new object.- Return type:
Notes
The deep copy operation is skipped if enforce_copy is False or if self.impfset_changes is the identity function, optimizing performance when no actual changes are expected or when in-place modification is desired.
- apply_hazard_changes(hazard: Hazard, enforce_copy: bool = True, **kwargs) Hazard[source]#
Apply the changes from the measure to the given
Hazardobject.This method applies the hazard_changes function of the measure to the provided
Hazardobject. If enforce_copy is True (default), a deep copy of the hazard is created before modification to ensure immutability of the original object.- Parameters:
hazard (Hazard) – The input hazard object to be transformed.
enforce_copy (bool, optional) – If True (default), creates a deep copy of hazard before applying changes, provided the transformation function is not the identity function. If False, the original object may be modified in-place depending on the behavior of hazard_changes.
**kwargs (dict, optional) – Additional keyword arguments passed directly to the hazard_changes function.
- Returns:
The resulting hazard object after the transformation has been applied. If enforce_copy was True, this is a new object.
- Return type:
Notes
The deep copy operation is skipped if enforce_copy is False or if self.hazard_changes is the identity function, optimizing performance when no actual changes are expected or when in-place modification is desired.
- apply(exposures: Exposures, impfset: ImpactFuncSet, hazard: Hazard, enforce_copy: bool = True, **kwargs) Tuple[Exposures, ImpactFuncSet, Hazard][source]#
Apply all measure transformations to the provided triplet of
Exposures,ImpactFuncSet,Hazard.This method applies the measure changes across all three risk parts: exposures, impact function set, and hazard data.
The method implements a flexible keyword arguments merging strategy where the original triplet is provided as default context to each transformation, which can then be overridden by entity-specific kwargs dictionaries. This enables transformation requiring the information from other risk components (for instance, removing events based on impact threshold) or additional information (for instance, effect depending on year of implementation).
Refer to measure-tutorial for more details.
- Parameters:
exposures (Exposures) – The input exposures object to be transformed.
impfset (ImpactFuncSet) – The impact function set to be transformed.
hazard (Hazard) – The hazard data to be transformed.
enforce_copy (bool, optional) – If True (default), creates deep copies of entities before applying changes, provided the transformation functions are not identity functions. If False, entities may be modified in-place depending on the behavior of the underlying transformation methods.
**kwargs (dict, optional) – Additional keyword arguments for configuring transformations. Supports nested dictionaries for entity-specific customization:
kwargs_exposures: Dict of kwargs passed to apply_exposures_changeskwargs_impfset: Dict of kwargs passed to apply_impfset_changeskwargs_hazard: Dict of kwargs passed to apply_hazard_changes
Each nested dict is merged with the default triplet context (exposures, impfset, hazard), allowing transformations to access related entities while permitting entity-specific overrides.
- Returns:
A tuple containing the transformed entities in the order: (changed_exposures, changed_impfset, changed_hazard). If enforce_copy was True, these are new objects; otherwise, they may reference the original inputs or modified versions thereof.
- Return type:
Tuple[Exposures, ImpactFuncSet, Hazard]
Notes
The kwargs merging follows this priority order:
Default context: The original triplet (exposures, impfset, hazard)
Entity-specific overrides: Values from
kwargs_exposures,kwargs_impfset, orkwargs_hazardrespectively
This ensures that each transformation receives full context about all entities while allowing fine-grained control over individual transformations.
The transformation order is: exposures → hazard → impact function set. Each transformation is independent, so changes to one entity do not affect the others during processing.
climada.entity.measures.measure_config module#
- class climada.entity.measures.measure_config.HazardModifierConfig(haz_type: str, haz_int_mult: float | None = 1.0, haz_int_add: float | None = 0.0, haz_freq_mult: float | None = 1.0, haz_freq_add: float | None = 0.0, new_hazard_path: str | None = None, impact_rp_cutoff: float | None = None)[source]#
Bases:
ModifierConfigConfiguration 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. If both a new file path and modifier values are provided, modifiers are applied after the replacement.
- Parameters:
haz_type (str) – Hazard type identifier (e.g.
"TC") that this modifier targets.haz_int_mult (float, optional) – Multiplicative factor applied to hazard intensity. Default is
1.0(no change).haz_int_add (float, optional) – Additive offset applied to hazard intensity 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 modifiers are applied after loading the new hazard.
impact_rp_cutoff (float, optional) – Return period (in years) below which hazard events are discarded. If
None, no cutoff is applied.
- Warns:
UserWarning – If
new_hazard_pathis set alongside any non-default modifier values or a non-Noneimpact_rp_cutoff.
- haz_type: str#
- haz_int_mult: float | None = 1.0#
- haz_int_add: float | None = 0.0#
- haz_freq_mult: float | None = 1.0#
- haz_freq_add: float | None = 0.0#
- new_hazard_path: str | None = None#
- impact_rp_cutoff: float | None = None#
- __init__(haz_type: str, haz_int_mult: float | None = 1.0, haz_int_add: float | None = 0.0, haz_freq_mult: float | None = 1.0, haz_freq_add: float | None = 0.0, new_hazard_path: str | None = None, impact_rp_cutoff: float | None = None) None#
- class climada.entity.measures.measure_config.ExposuresModifierConfig(reassign_impf_id: Dict[str, Dict[int | str, int | str]] | None = None, set_to_zero: list[int] | None = None, new_exposures_path: str | None = None)[source]#
Bases:
ModifierConfigConfiguration for modifications to an exposures object.
Supports remapping impact function IDs, zeroing out selected regions, and replacement of the exposures from a new file. If both a new file path and modifier values are provided, modifiers are applied after the replacement.
- Parameters:
reassign_impf_id (dict of {str: dict of {int or str: int or str}}, optional) – Nested mapping
{haz_type: {old_id: new_id}}used to reassign impact function IDs in the exposures. IfNone, no remapping is performed.set_to_zero (list of int, optional) – Region IDs 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. If provided alongside modifier values, a warning is issued and modifiers are applied after loading the new exposures.
- Warns:
UserWarning – If
new_exposures_pathis set alongside any non-Nonemodifier values.
- reassign_impf_id: Dict[str, Dict[int | str, int | str]] | None = None#
- set_to_zero: list[int] | None = None#
- new_exposures_path: str | None = None#
- __init__(reassign_impf_id: Dict[str, Dict[int | str, int | str]] | None = None, set_to_zero: list[int] | None = None, new_exposures_path: str | None = None) None#
- class climada.entity.measures.measure_config.ImpfsetModifierConfig(haz_type: str, impf_ids: int | str | list[int | str] | None = None, impf_mdd_mult: float = 1.0, impf_mdd_add: float = 0.0, impf_paa_mult: float = 1.0, impf_paa_add: float = 0.0, impf_int_mult: float = 1.0, impf_int_add: float = 0.0, new_impfset_path: str | None = None)[source]#
Bases:
ModifierConfigConfiguration for modifications to an impact function set.
Supports scaling or shifting MDD, PAA, and intensity curves, as well as replacement of the impact function set, loaded from a file path. If both a new file path and modifier values are provided, modifiers are applied after the replacement (and a warning is issued).
- Parameters:
haz_type (str) – Hazard type identifier (e.g.
"TC") that this modifier targets.impf_ids (int or str or list of int or str, optional) – Impact function ID(s) to which modifications are applied. If
None, all impact functions are affected.impf_mdd_mult (float, optional) – Multiplicative factor applied to the mean damage degree (MDD) curve. Default is
1.0(no change).impf_mdd_add (float, optional) – Additive offset applied to the MDD curve after multiplication. Default is
0.0.impf_paa_mult (float, optional) – Multiplicative factor applied to the percentage of affected assets (PAA) curve. Default is
1.0.impf_paa_add (float, optional) – Additive offset applied to the PAA curve after multiplication. Default is
0.0.impf_int_mult (float, optional) – Multiplicative factor applied to the intensity axis. Default is
1.0.impf_int_add (float, optional) – Additive offset applied to the intensity axis after multiplication. Default is
0.0.new_impfset_path (str, optional) – Path to an Excel file containing a replacement impact function set. If provided alongside modifier values, a warning is issued and modifiers are applied after loading the new set.
- Warns:
UserWarning – If
new_impfset_pathis set alongside any non-default modifier values.
- haz_type: str#
- impf_ids: int | str | list[int | str] | None = None#
- impf_mdd_mult: float = 1.0#
- impf_mdd_add: float = 0.0#
- impf_paa_mult: float = 1.0#
- impf_paa_add: float = 0.0#
- impf_int_mult: float = 1.0#
- impf_int_add: float = 0.0#
- new_impfset_path: str | None = None#
- __init__(haz_type: str, impf_ids: int | str | list[int | str] | None = None, impf_mdd_mult: float = 1.0, impf_mdd_add: float = 0.0, impf_paa_mult: float = 1.0, impf_paa_add: float = 0.0, impf_int_mult: float = 1.0, impf_int_add: float = 0.0, new_impfset_path: str | None = None) None#
- class climada.entity.measures.measure_config.CostIncomeConfig(mkt_price_year: int | None = <factory>, init_cost: float = 0.0, periodic_cost: float = 0.0, periodic_income: float = 0.0, cost_yearly_growth_rate: float = 0.0, income_yearly_growth_rate: float = 0.0, freq: str = 'Y', custom_cash_flows: list[dict] | None = None)[source]#
Bases:
ModifierConfigSerializable configuration for a
CostIncomeobject.Encodes all parameters required to construct a
CostIncomeinstance, including optional custom cash flow schedules.- Parameters:
mkt_price_year (int, optional) – Reference year for market prices. Defaults to the current year.
init_cost (float, optional) – One-time initial investment cost (positive value). Default is
0.0.periodic_cost (float, optional) – Recurring cost per period (positive value). Default is
0.0.periodic_income (float, optional) – Recurring income per period. Default is
0.0.cost_yearly_growth_rate (float, optional) – Annual growth rate applied to periodic costs. Default is
0.0.income_yearly_growth_rate (float, optional) – Annual growth rate applied to periodic income. Default is
0.0.freq (str, optional) – Pandas period alias defining the period length (e.g.
"Y"for yearly,"M"for monthly). Default is"Y". See [pandas documentation](https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#period-aliases).custom_cash_flows (list of dict, optional) – Explicit cash flow schedule as a list of records with at minimum a
"date"key (ISO 8601 string) and a value key. If provided, overrides the periodic cost/income logic.
- mkt_price_year: int | None#
- init_cost: float = 0.0#
- periodic_cost: float = 0.0#
- periodic_income: float = 0.0#
- cost_yearly_growth_rate: float = 0.0#
- income_yearly_growth_rate: float = 0.0#
- freq: str = 'Y'#
- custom_cash_flows: list[dict] | None = None#
- classmethod from_cost_income(cost_income: CostIncome) CostIncomeConfig[source]#
Construct a
CostIncomeConfigfrom a liveCostIncomeobject.- Parameters:
cost_income (CostIncome) – The live
CostIncomeinstance to serialise.- Returns:
The config instance equivalent to the
CostIncome.- Return type:
- __init__(mkt_price_year: int | None = <factory>, init_cost: float = 0.0, periodic_cost: float = 0.0, periodic_income: float = 0.0, cost_yearly_growth_rate: float = 0.0, income_yearly_growth_rate: float = 0.0, freq: str = 'Y', custom_cash_flows: list[dict] | None = None) None#
- class climada.entity.measures.measure_config.MeasureConfig(name: str, haz_type: str, impfset_modifier: ImpfsetModifierConfig, hazard_modifier: HazardModifierConfig, exposures_modifier: ExposuresModifierConfig, cost_income: CostIncomeConfig, implementation_duration: str | None = None, color_rgb: Tuple[float, float, float] | None = None)[source]#
Bases:
ModifierConfigTop-level serializable configuration for a single adaptation measure.
Aggregates all modifier sub-configs (hazard, impact functions, exposures, cost/income) into a single object that can be round-tripped through dict, YAML, or a legacy Excel row.
This class is the primary entry point for defining measures in a declarative, file-based workflow and serves as the serialization counterpart to
Measure.- Parameters:
name (str) – Unique name identifying this measure.
haz_type (str) – Hazard type identifier (e.g.
"TC") this measure is designed for.impfset_modifier (ImpfsetModifierConfig) – Configuration describing modifications to the impact function set.
hazard_modifier (HazardModifierConfig) – Configuration describing modifications to the hazard.
exposures_modifier (ExposuresModifierConfig) – Configuration describing modifications to the exposures.
cost_income (CostIncomeConfig) – Financial parameters associated with implementing this measure.
implementation_duration (str, optional) – Pandas period alias (e.g.
"2Y") representing the time before the measure is fully operational. IfNone, the measure takes effect immediately.color_rgb (tuple of float, optional) – RGB colour triple in the range
[0, 1]used for visualisation. IfNone, defaults to black(0, 0, 0).
- name: str#
- haz_type: str#
- impfset_modifier: ImpfsetModifierConfig#
- hazard_modifier: HazardModifierConfig#
- exposures_modifier: ExposuresModifierConfig#
- cost_income: CostIncomeConfig#
- implementation_duration: str | None = None#
- color_rgb: Tuple[float, float, float] | None = None#
- to_dict(omit_default: bool = True) dict[source]#
Serialize the measure configuration to a flat dictionary.
Sub-config dictionaries are merged into the top-level dict (i.e. their keys are inlined, not nested).
haz_typeis always included at the top level. Fields withNonevalues are preserved.- Returns:
Flat dictionary representation suitable for YAML or Excel serialization.
- Return type:
dict
- classmethod from_dict(kwargs_dict: dict) MeasureConfig[source]#
Instantiate a
MeasureConfigfrom a flat dictionary.Delegates sub-config construction to the respective
from_dictclassmethods. Unknown keys are silently discarded by each sub-config parser.- Parameters:
kwargs_dict (dict) – Flat dictionary, as produced by
to_dict()or read from a legacy Excel row. Must contain at minimum"name"and"haz_type".- Returns:
A fully populated configuration instance.
- Return type:
- to_yaml(path: str) None[source]#
Write this configuration to a YAML file.
The file is structured as
{"measures": [<this config as dict>]}, matching the expected format forfrom_yaml().- Parameters:
path (str) – Destination file path. Will be created or overwritten.
- classmethod from_yaml(path: str) MeasureConfig[source]#
Load a
MeasureConfigfrom a YAML file.Expects the file to contain a top-level
"measures"list; reads only the first entry.- Parameters:
path (str) – Path to the YAML file to read.
- Returns:
The configuration parsed from the first entry in
measures.- Return type:
- classmethod from_row(row: Series) MeasureConfig[source]#
Construct a
MeasureConfigfrom a legacy Excel row.Converts the row to a dictionary and delegates to
from_dict(). This is the primary migration path for measures currently stored in the legacy Excel-basedMeasureSetformat.- Parameters:
row (pd.Series) – A single row from a legacy measures Excel sheet, with column names matching the flat dictionary keys expected by
from_dict().- Returns:
A configuration instance populated from the row data.
- Return type:
- __init__(name: str, haz_type: str, impfset_modifier: ImpfsetModifierConfig, hazard_modifier: HazardModifierConfig, exposures_modifier: ExposuresModifierConfig, cost_income: CostIncomeConfig, implementation_duration: str | None = None, color_rgb: Tuple[float, float, float] | None = None) None#
climada.entity.measures.cost_income module#
- class climada.entity.measures.cost_income.CostIncome(*, mkt_price_year: int | None = None, init_cost: float = 0.0, periodic_cost: float = 0.0, periodic_income: float = 0.0, cost_yearly_growth_rate: float = 0.0, income_yearly_growth_rate: float = 0.0, custom_cash_flows: DataFrame | None = None, freq: str = 'Y')[source]#
Bases:
objectManages costs and incomes related to a measure over time.
Income are stored a positive numbers and costs as negative ones.
- mkt_price_year#
The reference year for market prices.
- Type:
datetime, default to today’s year.
- init_cost#
Initial implementation cost (stored as negative).
- Type:
float
- periodic_cost#
Recurring cost per period (stored as negative).
- Type:
float
- periodic_income#
Recurring income per period.
- Type:
float
- cost_yearly_growth_rate#
Yearly growth rate of costs.
- Type:
float
- income_yearly_growth_rate#
Yearly growth rate of income.
- Type:
float
- custom_cash_flows#
User-defined cash flows indexed by date.
- Type:
pd.DataFrame, optional
- freq#
Frequency of the cash flows (e.g., ‘Y’, ‘3M’, ‘7D’).
- Type:
str
- __init__(*, mkt_price_year: int | None = None, init_cost: float = 0.0, periodic_cost: float = 0.0, periodic_income: float = 0.0, cost_yearly_growth_rate: float = 0.0, income_yearly_growth_rate: float = 0.0, custom_cash_flows: DataFrame | None = None, freq: str = 'Y')[source]#
Initialize CostIncome with parameters.
- Parameters:
mkt_price_year (datetime, default to today’s year.) – The reference year for market prices.
init_cost (float) – Initial implementation cost (stored as negative).
periodic_cost (float) – Recurring cost per period (stored as negative).
periodic_income (float) – Recurring income per period.
cost_yearly_growth_rate (float) – Yearly growth rate of costs.
income_yearly_growth_rate (float) – Yearly growth rate of income.
custom_cash_flows (pd.DataFrame, optional) – User-defined cash flows indexed by date.
freq (str) – Frequency of the cash flows (e.g., ‘Y’, ‘3M’, ‘7D’).
- property custom_cash_flows: DataFrame | None#
Get or set the optional user-defined cash flows.
Input cash flow have to contain a “date” column as well as at least one of “cost” and “income”. The custom cash flow is coerced to the internal period frequency.
- Type:
pd.DataFrame
- classmethod from_config(config: CostIncomeConfig) CostIncome[source]#
Create a CostIncome from a CostIncomeConfig.
- Parameters:
config (CostIncomeConfig)
- Return type:
- classmethod from_dict(args_dict: dict) CostIncome[source]#
Create a CostIncome from a dictionary.
- Parameters:
args_dict (dict)
- Return type:
- classmethod from_yaml(path: str) CostIncome[source]#
Create a CostIncome from a yaml file.
- Parameters:
path (str) – Path to the yaml file.
- Return type:
- calc_at_date(impl_date: Timestamp, curr_date: Timestamp) Tuple[float, float, float][source]#
Calculate cash flows for a single timestamp.
Computes the total cash flow, total cost, and total income for a given evaluation date, accounting for growth rates applied to base costs and incomes, as well as the custom cash flow if provided.
The calculation applies compound growth to both costs and incomes based on the number of years elapsed since the market price reference date (self.mkt_price_year).
- Parameters:
impl_date (pd.Timestamp) – The implementation date that determines which cost/income regime applies. Dates before this use have no cost or income; “at the date” uses the implementation cost, and dates after use the initialized or periodic amounts respectively.
curr_date (pd.Timestamp) – The evaluation date for which cash flows are being calculated. This is compared against impl_date to determine the applicable base amounts and is also used to index into custom_cash_flows if present.
- Returns:
A tuple containing:
- total_cash_flowfloat
Net cash flow for the period, calculated as total_income + total_cost. Note: Costs are typically negative values in financial contexts, so this represents the net position.
- total_costfloat
Total cost amount for the period, including both standard and custom cost components.
- total_incomefloat
Total income amount for the period, including both standard and custom income components.
- Return type:
Tuple[float, float, float]
Notes
Growth calculations use compound interest formula:
\[factor = (1 + rate)^{years\_passed}\]where years_passed is computed as (curr_date - mkt_price_year).days / 365.0.
Cost and income regimes:
Before impl_date: Both base cost and income are zero
At impl_date: Uses init_cost for cost
After impl_date: Uses periodic_cost for cost and periodic_income for income
Custom cash flows (if self.custom_cash_flows is not None) are added on top of the calculated standard amounts. Missing dates in the custom cash flow DataFrame will raise a KeyError.
- calc_cash_flows(impl_date, start_date, end_date) Tuple[ndarray, ndarray, ndarray][source]#
Calculate net cash flows, costs, and incomes over a period.
Computes cash flow metrics across a specified date range by iterating through each period.
The method creates a period range based on the configured frequency (self.freq) and evaluates cash flows at the start time of each period. Results are returned as NumPy arrays for efficient downstream processing.
- Parameters:
impl_date – The implementation date that determines which cost/income regime applies.
start_date – The beginning of the calculation period.
end_date – The end of the calculation period.
- Returns:
A tuple containing three NumPy arrays of equal length:
- netnp.ndarray
Net cash flow for each period (income + cost).
- costsnp.ndarray
Total costs for each period.
- incomesnp.ndarray
Total incomes for each period.
- Return type:
Tuple[np.ndarray, np.ndarray, np.ndarray]
- calc_total(impl_date, start_date, end_date) Tuple[float, float, float][source]#
Calculate the total value of the cash flows over a given period.
Parameters:#
- impl_date:
The date the measure is implemented.
- start_year:
The start date of the period.
- end_year: int
The end year of the period.
Returns:#
- Tuple[float, float, float]
the total net, cost, and income values over the given period.
- plot_cash_flows(impl_date: Any, start_date: Any, end_date: Any, figsize: Tuple[int, int] = (12, 7), title: str | None = None)[source]#
Plot periodic and cumulative cash flows over a given period.
Displays a two-panel figure: - Top panel: stacked bar chart of costs and incomes per period,
with a net cash flow line overlay.
Bottom panel: cumulative net cash flow over time.
- Parameters:
impl_date – The date the measure is implemented.
start_date – Start of the evaluation period.
end_date – End of the evaluation period.
figsize (tuple, optional) – Figure size as (width, height). Default is (12, 7).
title (str, optional) – Overall figure title. Defaults to ‘Cash Flow Analysis’.
- Return type:
plt.Figure
- to_dataframe(impl_date, start_date, end_date) DataFrame[source]#
Return cash flows as a formatted DataFrame.
- static comb_cost_income(cost_incomes: list[CostIncome]) CostIncome[source]#
Combine multiple CostIncomes together.
Combination sums the costs and incomes from all provided CostIncome objects.