Skip to content

Loss Estimation#

The loss estimation module turns the damage-state probability library into expected loss ratios, building-by-event loss ratios, expected annual loss (EAL) and zone aggregates. It consumes the STARR-compatible export of the Exposure module (M, C, continuous hazard IDs, building values and zone ids) together with the annual event probabilities.

Class Diagram#

classDiagram
    class DamageProbabilityProvider {
        +np.ndarray damage_states
        +np.ndarray wind_speeds
        +np.ndarray flood_depths
        +Dict prob_damage_states
        +load_damage_state_probabilities()
        +calculate_damage_ratio()
    }
    class BaseLossEstimation {
        +Optional~str~ prob_ds_file_path
        +Optional~np.ndarray~ hurricane_probabilities
        +np.ndarray hurricane_prob
        +Dict prob_damage_states
        +load_damage_library()
        +load_hurricane_probabilities()
    }
    class LookupTableBuilder {
        +np.ndarray wind_lookup
        +np.ndarray flood_lookup
        +calculate_marginal_lookups()
        +calculate_expected_ratio_surface()
        +save_lookup_tables()
        +load_lookup_tables()
    }
    class BuildingLossEstimator {
        +str index_mode
        +str combine_mode
        +str value_basis
        +pd.DataFrame building_table
        +np.ndarray wind_ids
        +np.ndarray flood_ids
        +pd.DataFrame building_eal
        +load_exposure_inputs()
        +load_from_exposure()
        +calculate_lookup_loss_ratio()
        +calculate_joint_loss_ratio()
        +calculate_eal_ratios()
        +calculate_building_eal()
    }
    class RegionalLossEstimator {
        +Optional~str~ aggregation_col
        +np.ndarray aggregation_key
        +pd.DataFrame zone_eal
        +pd.DataFrame event_losses
        +calculate_zone_lookup()
        +calculate_aggregation_key()
        +calculate_zone_eal()
        +calculate_event_losses()
    }
    class LossEstimation {
        +estimate_all_losses()
        +save_all_outputs()
    }

    BaseLossEstimation <|-- LookupTableBuilder
    LookupTableBuilder <|-- BuildingLossEstimator
    BuildingLossEstimator <|-- RegionalLossEstimator
    RegionalLossEstimator <|-- LossEstimation
    BaseLossEstimation o-- DamageProbabilityProvider

Base Classes#

base #

Shared inputs of the loss-estimation chain.

BaseLossEstimation owns the damage library (through the unchanged DamageProbabilityProvider), the discrete damage-state, wind and flood tables and the annual hurricane probabilities. Subclasses add lookup tables, building-level loss ratios, expected annual loss and regional aggregation.

Classes:

Name Description
BaseLossEstimation

Inputs shared by every loss-estimation class.

BaseLossEstimation dataclass #

BaseLossEstimation(
    damage_state_path: Optional[str] = None,
    wind_speed_path: Optional[str] = None,
    flood_depth_path: Optional[str] = None,
    hurricane_prob_path: Optional[str] = None,
    hurricane_probabilities: Optional[ndarray] = None,
    prob_ds_file_path: Optional[str] = None,
    damage_provider: Optional[
        DamageProbabilityProvider
    ] = None,
    output_dir: Optional[str] = None,
    datasets_loaded: bool = False,
)

Inputs shared by every loss-estimation class.

Attributes:

Name Type Description
damage_state_path Optional[str]

DamageState.json (id, damage ratio); defaults under Config.INPUTS_PATH.

wind_speed_path Optional[str]

WindSpeed.json (id, mph, m/s).

flood_depth_path Optional[str]

FloodDepth.json (id, inches, m).

hurricane_prob_path Optional[str]

Hurricane_ProbWindFlood.json holding Hurricane_Prob.

hurricane_probabilities Optional[ndarray]

Explicit annual event probabilities, shape (n_events,) or (n_events, 2); overrides the JSON file when given.

prob_ds_file_path Optional[str]

Damage-library pickle dict[(m, c)] -> (n_wind, n_flood, n_states).

damage_provider Optional[DamageProbabilityProvider]

Existing provider to reuse instead of loading.

output_dir Optional[str]

Output folder; defaults to <Config.OUTPUTS_PATH>/loss_estimation.

damage_states ndarray

Damage-state table, shape (n_states, 2).

wind_speeds ndarray

Wind table, shape (n_wind, 3).

flood_depths ndarray

Flood table, shape (n_flood, 3).

hurricane_prob ndarray

Event ids and annual probabilities, shape (n_events, 2).

prob_damage_states Dict[Tuple[int, int], ndarray]

Damage library keyed by (m, c).

datasets_loaded bool

Whether the loaders have run.

Methods:

Name Description
load_damage_library

Load the damage library and tables through the provider.

load_hurricane_probabilities

Load or validate the annual event probabilities.

update_outputs

Reload inputs and rerun the automatic steps.

load_damage_library #

load_damage_library() -> None

Load the damage library and the discrete tables through DamageProbabilityProvider.

A provider is created from the configured paths unless one was injected. Its arrays are copied onto this object so the rest of the chain never touches the provider directly.

Outputs

Sets damage_provider, damage_states, wind_speeds, flood_depths and prob_damage_states; logs a warning when the library is empty.

Returns:

Type Description
None

None

load_hurricane_probabilities #

load_hurricane_probabilities() -> None

Load the annual event probabilities as an (n_events, 2) array of ids and probabilities.

Outputs

Sets hurricane_prob.

Returns:

Type Description
None

None

Raises:

Type Description
ValueError

If the array is not two columns wide or its ids are not 1..n_events in order.

update_outputs #

update_outputs() -> None

Reload all inputs and rerun the automatic steps of the subclass chain.

Outputs

Resets datasets_loaded and reruns __post_init__.

Returns:

Type Description
None

None

Building Loss#

building_loss #

Building-by-event loss ratios and expected annual loss.

Continuous hazard IDs from the exposure module are mapped onto lookup-table bins with a selectable index convention, combined across wind and flood, and weighted by the annual event probabilities to give each building's expected annual loss (EAL). Large exports are processed in row chunks so the (n_buildings, n_events) arrays can stay memory-mapped on disk.

Classes:

Name Description
BuildingLossEstimator

Building-by-event loss ratios and expected annual loss from an exposure export.

Attributes:

Name Type Description
COMBINE_MODES Tuple[str, ...]

Ways of combining wind and flood into a single loss ratio.

INDEX_MODES Tuple[str, ...]

Conventions mapping a continuous 1-based hazard ID onto lookup-table bins.

VALUE_BASES Tuple[str, ...]

Inventory columns that may serve as the monetary basis of the loss.

COMBINE_MODES module-attribute #

COMBINE_MODES: Tuple[str, ...] = ('additive', 'joint')

Ways of combining wind and flood into a single loss ratio.

INDEX_MODES module-attribute #

INDEX_MODES: Tuple[str, ...] = (
    "floor",
    "ceil",
    "round",
    "linear",
)

Conventions mapping a continuous 1-based hazard ID onto lookup-table bins.

VALUE_BASES module-attribute #

VALUE_BASES: Tuple[str, ...] = (
    "structure_value",
    "contents_value",
    "home_value",
)

Inventory columns that may serve as the monetary basis of the loss.

BuildingLossEstimator dataclass #

BuildingLossEstimator(
    damage_state_path: Optional[str] = None,
    wind_speed_path: Optional[str] = None,
    flood_depth_path: Optional[str] = None,
    hurricane_prob_path: Optional[str] = None,
    hurricane_probabilities: Optional[ndarray] = None,
    prob_ds_file_path: Optional[str] = None,
    damage_provider: Optional[
        DamageProbabilityProvider
    ] = None,
    output_dir: Optional[str] = None,
    datasets_loaded: bool = False,
    n_building_types: int = 8,
    n_component_configurations: int = 192,
    lookup_dtype: str = "float32",
    normalization_tolerance: float = 0.001,
    inventory_csv_path: Optional[str] = None,
    wind_ids_path: Optional[str] = None,
    flood_ids_path: Optional[str] = None,
    zone_id_col: Optional[str] = "i_lh740",
    index_mode: str = "floor",
    combine_mode: str = "additive",
    value_basis: str = "structure_value",
    chunk_size: int = 100000,
    exposure_loaded: bool = False,
)

Bases: LookupTableBuilder

Building-by-event loss ratios and expected annual loss from an exposure export.

Attributes:

Name Type Description
inventory_csv_path Optional[str]

STARR Inventory.csv; defaults to <Config.OUTPUTS_PATH>/exposure/Inventory.csv.

wind_ids_path Optional[str]

Wind_Tr.npy next to the inventory by default.

flood_ids_path Optional[str]

Flood_Tr.npy next to the inventory by default.

zone_id_col Optional[str]

Zone column of the inventory carried into the building results.

index_mode str

"floor" (default, the published maps), "ceil" (the verified STARR searchsorted export), "round" or "linear".

combine_mode str

"additive" (wind plus flood marginals, the STARR convention) or "joint" (full wind-flood surface from the damage library).

value_basis str

"structure_value" (default), "contents_value" or "home_value".

chunk_size int

Rows processed per chunk when scanning the hazard-ID arrays.

building_table DataFrame

The inventory table.

wind_ids ndarray

Continuous wind IDs, shape (n_buildings, n_events).

flood_ids ndarray

Continuous flood IDs, shape (n_buildings, n_events).

event_names List[str]

Event names aligned with the array columns.

expected_ratio_surface Optional[ndarray]

Joint surface, built on demand for joint mode.

building_eal DataFrame

Expected annual loss per building.

exposure_loaded bool

Whether an exposure export has been loaded.

Methods:

Name Description
load_exposure_inputs

Read the exposure export from disk.

load_from_exposure

Take the export from an in-memory Exposure object.

calculate_lookup_loss_ratio

Table lookup with a given index convention.

calculate_joint_loss_ratio

Joint-surface lookup with a given index convention.

calculate_event_loss_ratios

Wind, flood and combined loss ratios for a row chunk.

calculate_eal_ratios

Probability-weighted loss ratios per building.

calculate_building_eal

Expected annual loss table per building.

save_loss_ratios

Write per-event loss-ratio arrays as memory-mapped files.

save_building_eal

Write the building EAL table.

calculate_building_eal #

calculate_building_eal(
    building_table: DataFrame,
    wind_ids: ndarray,
    flood_ids: ndarray,
    probabilities: ndarray,
    surface: Optional[ndarray] = None,
) -> DataFrame

Expected annual loss per building in ratio and monetary terms.

Parameters:

Name Type Description Default
building_table DataFrame

Inventory table with M, C and the value_basis column.

required
wind_ids ndarray

Continuous wind IDs, shape (n_buildings, n_events).

required
flood_ids ndarray

Continuous flood IDs, shape (n_buildings, n_events).

required
probabilities ndarray

Annual event probabilities, shape (n_events,).

required
surface Optional[ndarray]

Joint surface for joint mode.

None
Outputs

None beyond the returned value.

Returns:

Type Description
DataFrame

pd.DataFrame: Columns building_key and building_ID (when present), M, C,

DataFrame

the zone column (when present), value, eal_wind_ratio, eal_flood_ratio,

DataFrame

eal_combined_ratio, eal_wind, eal_flood and eal_combined (monetary,

DataFrame

ratio * value).

Raises:

Type Description
ValueError

If value_basis is unknown or missing from the table.

calculate_eal_ratios #

calculate_eal_ratios(
    building_types: ndarray,
    component_configurations: ndarray,
    wind_ids: ndarray,
    flood_ids: ndarray,
    probabilities: ndarray,
    surface: Optional[ndarray] = None,
) -> Tuple[ndarray, ndarray, ndarray]

Probability-weighted expected loss ratios per building.

eal_ratio[b] = sum_h p_h * loss_ratio[b, h], evaluated in row chunks of chunk_size so memory-mapped arrays are streamed rather than loaded.

Parameters:

Name Type Description Default
building_types ndarray

1-based M per building.

required
component_configurations ndarray

1-based C per building.

required
wind_ids ndarray

Continuous wind IDs, shape (n_buildings, n_events).

required
flood_ids ndarray

Continuous flood IDs, shape (n_buildings, n_events).

required
probabilities ndarray

Annual event probabilities, shape (n_events,); not normalized.

required
surface Optional[ndarray]

Joint surface for joint mode.

None
Outputs

None beyond the returned value.

Returns:

Type Description
Tuple[ndarray, ndarray, ndarray]

Tuple[np.ndarray, np.ndarray, np.ndarray]: Wind, flood and combined EAL ratios, each (n_buildings,).

calculate_event_loss_ratios #

calculate_event_loss_ratios(
    m0: ndarray,
    c0: ndarray,
    wind_id: ndarray,
    flood_id: ndarray,
    surface: Optional[ndarray] = None,
) -> Tuple[ndarray, ndarray, ndarray]

Wind, flood and combined loss ratios for a chunk of buildings.

Parameters:

Name Type Description Default
m0 ndarray

0-based archetype indices, shape (n_buildings, 1).

required
c0 ndarray

0-based configuration indices, shape (n_buildings, 1).

required
wind_id ndarray

Continuous wind IDs, shape (n_buildings, n_events).

required
flood_id ndarray

Continuous flood IDs, shape (n_buildings, n_events).

required
surface Optional[ndarray]

Joint surface for combine_mode="joint"; defaults to expected_ratio_surface.

None
Outputs

None beyond the returned value.

Returns:

Type Description
Tuple[ndarray, ndarray, ndarray]

Tuple[np.ndarray, np.ndarray, np.ndarray]: (wind, flood, combined) loss ratios.

Raises:

Type Description
ValueError

If combine_mode is unknown or joint mode has no surface.

calculate_joint_loss_ratio #

calculate_joint_loss_ratio(
    surface: ndarray,
    m0: ndarray,
    c0: ndarray,
    wind_id: ndarray,
    flood_id: ndarray,
    index_mode: str,
) -> ndarray

Look up combined loss ratios on the joint wind-flood surface.

Parameters:

Name Type Description Default
surface ndarray

Surface of shape (n_m, n_c, n_wind, n_flood).

required
m0 ndarray

0-based archetype indices, shape (n_buildings, 1).

required
c0 ndarray

0-based configuration indices, shape (n_buildings, 1).

required
wind_id ndarray

Continuous wind IDs, shape (n_buildings, n_events).

required
flood_id ndarray

Continuous flood IDs, shape (n_buildings, n_events).

required
index_mode str

Discrete conventions index both axes; "linear" interpolates bilinearly.

required
Outputs

None beyond the returned value.

Returns:

Type Description
ndarray

np.ndarray: Combined loss ratios of shape (n_buildings, n_events).

Raises:

Type Description
ValueError

If the mode is unknown.

calculate_lookup_loss_ratio #

calculate_lookup_loss_ratio(
    lookup: ndarray,
    m0: ndarray,
    c0: ndarray,
    hazard_id: ndarray,
    index_mode: str,
) -> ndarray

Look up loss ratios for one hazard with the given index convention.

Parameters:

Name Type Description Default
lookup ndarray

Marginal table of shape (n_m, n_c, n_bins).

required
m0 ndarray

0-based archetype indices, shape (n_buildings, 1).

required
c0 ndarray

0-based configuration indices, shape (n_buildings, 1).

required
hazard_id ndarray

Continuous 1-based IDs, shape (n_buildings, n_events).

required
index_mode str

"floor" truncates (int(id) - 1); "ceil" takes the first bin at or above the ID (the verified STARR searchsorted mode); "round" takes the nearest bin (ties to even); "linear" interpolates between neighbouring bins.

required
Outputs

None beyond the returned value.

Returns:

Type Description
ndarray

np.ndarray: Loss ratios of shape (n_buildings, n_events).

Raises:

Type Description
ValueError

If the mode is unknown.

load_exposure_inputs #

load_exposure_inputs() -> None

Read the exposure export (Inventory.csv, Wind_Tr.npy, Flood_Tr.npy) from disk.

The hazard-ID arrays are memory-mapped so the full-scale export does not have to fit in memory. Event names come from Hurricane_name.npy next to the wind file when present.

Outputs

Sets building_table, wind_ids, flood_ids, event_names and exposure_loaded.

Returns:

Type Description
None

None

Raises:

Type Description
ValueError

If the pieces are inconsistent (see _validate_exposure_arrays).

load_from_exposure #

load_from_exposure(exposure: Exposure) -> None

Take the export directly from an in-memory cheersafe.exposure.Exposure object.

The same Exposure.calculate_starr_export output that save_starr_inputs writes is used, so zone filtering is identical on both paths.

Parameters:

Name Type Description Default
exposure Exposure

A completed Exposure instance.

required
Outputs

Sets building_table, wind_ids, flood_ids, event_names and exposure_loaded.

Returns:

Type Description
None

None

save_building_eal #

save_building_eal(path: Optional[str] = None) -> str

Write building_eal to CSV.

Parameters:

Name Type Description Default
path Optional[str]

Output file; defaults to <output_dir>/building_eal.csv.

None
Outputs

Writes the CSV file.

Returns:

Name Type Description
str str

The written path.

save_loss_ratios #

save_loss_ratios(
    output_dir: Optional[str] = None,
) -> Dict[str, str]

Write the per-event wind, flood and combined loss ratios as memory-mapped .npy files.

Parameters:

Name Type Description Default
output_dir Optional[str]

Folder to write into; defaults to <Config.OUTPUTS_PATH>/loss_estimation.

None
Outputs

Writes LossRatio_WIND.npy, LossRatio_FLOOD.npy and LossRatio_COMBINED.npy, each (n_buildings, n_events) float32, filled chunk by chunk.

Returns:

Type Description
Dict[str, str]

Dict[str, str]: Written paths keyed by wind_loss_ratio, flood_loss_ratio and combined_loss_ratio.

update_outputs #

update_outputs() -> None

Reload every input, including the exposure export, and rerun the automatic steps.

Outputs

Resets exposure_loaded and datasets_loaded and reruns __post_init__.

Returns:

Type Description
None

None

Damage Probability#

damage_probability #

Classes:

Name Description
DamageProbabilityProvider

Class for providing damage probability data.

DamageProbabilityProvider dataclass #

DamageProbabilityProvider(
    damage_state_path: str = "Inputs/DamageState.json",
    wind_speed_path: str = "Inputs/WindSpeed.json",
    flood_depth_path: str = "Inputs/FloodDepth.json",
    prob_ds_file_path: Optional[str] = None,
    legacy_dir: str = "Outputs/ProbDS_wfd_mc_CV0p3_OldGeometry_OldResistance_Run2",
)

Class for providing damage probability data.

Attributes:

Name Type Description
damage_states ndarray

Array containing damage state definitions

prob_damage_states Dict

Dictionary mapping (m, c) tuples to probability arrays

Methods:

Name Description
load_damage_state_probabilities

Load damage state probabilities for a specific building type and resistance type

calculate_damage_ratio

Calculate damage ratio for given hazard intensities and building attributes

calculate_damage_ratio #

calculate_damage_ratio(
    wind_speed: float, flood_depth: float, m: int, c: int
) -> float

Calculate damage ratio for given wind speed, flood depth, building type, and resistance type

Parameters:

Name Type Description Default
wind_speed float

Wind speed in m/s

required
flood_depth float

Flood depth in meters

required
m int

Building type index

required
c int

Resistance type index

required

Returns:

Name Type Description
float float

Damage ratio (0-1)

Outputs

None beyond the returned value.

load_damage_state_probabilities #

load_damage_state_probabilities(m: int, c: int) -> ndarray

Load damage state probabilities for a specific building type and resistance type

Parameters:

Name Type Description Default
m int

Building type index

required
c int

Resistance type index

required

Returns:

Type Description
ndarray

np.ndarray: Damage state probabilities array (wind speeds × flood depths × damage states)

load_damage_states #

load_damage_states()

Load damage state definitions

load_flood_depths #

load_flood_depths()

Load flood depth bins

load_prob_damage_states #

load_prob_damage_states()

Load probability damage states from pickle file

load_wind_speeds #

load_wind_speeds()

Load wind speed bins

Lookup Tables#

lookup_tables #

Expected loss-ratio lookup tables derived from the damage library.

For every archetype m and configuration c the damage library holds a probability distribution over the damage states for each (wind ID, flood ID) pair. Multiplying those probabilities by the damage-state ratios gives the expected loss ratio. The marginal tables L_mcw_wd (wind only, flood at the zero-hazard ID) and L_mcf_fld (flood only, wind at the zero-hazard ID) are the STARR-compatible artefacts of the verified workflow; the optional full surface keeps the joint wind-flood interaction.

Classes:

Name Description
LookupTableBuilder

Build the wind-only and flood-only expected loss-ratio tables.

LookupTableBuilder dataclass #

LookupTableBuilder(
    damage_state_path: Optional[str] = None,
    wind_speed_path: Optional[str] = None,
    flood_depth_path: Optional[str] = None,
    hurricane_prob_path: Optional[str] = None,
    hurricane_probabilities: Optional[ndarray] = None,
    prob_ds_file_path: Optional[str] = None,
    damage_provider: Optional[
        DamageProbabilityProvider
    ] = None,
    output_dir: Optional[str] = None,
    datasets_loaded: bool = False,
    n_building_types: int = 8,
    n_component_configurations: int = 192,
    lookup_dtype: str = "float32",
    normalization_tolerance: float = 0.001,
)

Bases: BaseLossEstimation

Build the wind-only and flood-only expected loss-ratio tables.

Attributes:

Name Type Description
n_building_types int

Number of archetypes m (first table axis).

n_component_configurations int

Number of configurations c (second table axis).

lookup_dtype str

Storage dtype of the tables (float32 matches the frozen artefacts).

normalization_tolerance float

Rows whose probabilities differ from one by more than this are counted and reported.

wind_lookup ndarray

L_mcw_wd[m-1, c-1, w-1], shape (n_m, n_c, n_wind).

flood_lookup ndarray

L_mcf_fld[m-1, c-1, f-1], shape (n_m, n_c, n_flood).

Methods:

Name Description
calculate_marginal_lookups

Wind-only and flood-only expected loss ratios.

calculate_expected_ratio_surface

Full (m, c, wind, flood) expected loss ratios.

save_lookup_tables

Write the two tables and a metadata file.

load_lookup_tables

Load previously saved tables.

calculate_expected_ratio_surface #

calculate_expected_ratio_surface(
    prob_damage_states: Dict[Tuple[int, int], ndarray],
    damage_ratios: ndarray,
    n_building_types: int,
    n_component_configurations: int,
) -> ndarray

Compute the full expected loss-ratio surface over wind and flood IDs.

Parameters:

Name Type Description Default
prob_damage_states Dict[Tuple[int, int], ndarray]

Damage library keyed by 1-based (m, c).

required
damage_ratios ndarray

Damage-state loss ratios, shape (n_states,).

required
n_building_types int

Size of the m axis.

required
n_component_configurations int

Size of the c axis.

required
Outputs

None beyond the returned value.

Returns:

Type Description
ndarray

np.ndarray: Surface of shape (n_m, n_c, n_wind, n_flood) in lookup_dtype;

ndarray

missing pairs are NaN. Used by the joint combination mode.

calculate_marginal_lookups #

calculate_marginal_lookups(
    prob_damage_states: Dict[Tuple[int, int], ndarray],
    damage_ratios: ndarray,
    n_building_types: int,
    n_component_configurations: int,
) -> Tuple[ndarray, ndarray]

Compute the wind-only and flood-only expected loss-ratio tables.

wind[m-1, c-1, w] = sum_d P[m, c][w, 0, d] * ratios[d] holds flood at its zero-hazard ID; flood[m-1, c-1, f] = sum_d P[m, c][0, f, d] * ratios[d] holds wind at its zero-hazard ID. The products are summed row by row in float64 and cast to lookup_dtype, which reproduces the frozen source tables bit for bit.

Parameters:

Name Type Description Default
prob_damage_states Dict[Tuple[int, int], ndarray]

Damage library keyed by 1-based (m, c).

required
damage_ratios ndarray

Damage-state loss ratios, shape (n_states,).

required
n_building_types int

Size of the m axis.

required
n_component_configurations int

Size of the c axis.

required
Outputs

None beyond the returned value.

Returns:

Type Description
ndarray

Tuple[np.ndarray, np.ndarray]: Wind table (n_m, n_c, n_wind) and flood table

ndarray

(n_m, n_c, n_flood). Pairs absent from the library are NaN; one warning

Tuple[ndarray, ndarray]

reports how many pairs are missing and one how many probability rows do not sum to one.

load_lookup_tables #

load_lookup_tables(wind_path: str, flood_path: str) -> None

Load previously saved lookup tables instead of building them from a library.

Parameters:

Name Type Description Default
wind_path str

Path to L_mcw_wd.npy.

required
flood_path str

Path to L_mcf_fld.npy.

required
Outputs

Sets wind_lookup and flood_lookup.

Returns:

Type Description
None

None

save_lookup_tables #

save_lookup_tables(
    output_dir: Optional[str] = None,
) -> Dict[str, str]

Write L_mcw_wd.npy, L_mcf_fld.npy and STARR_lookup_metadata.txt.

Parameters:

Name Type Description Default
output_dir Optional[str]

Folder to write into; defaults to <Config.OUTPUTS_PATH>/loss_estimation.

None
Outputs

Writes the two tables and the metadata file.

Returns:

Type Description
Dict[str, str]

Dict[str, str]: Written paths keyed by wind_lookup, flood_lookup and metadata.

Loss Estimation Workflow#

main #

End-to-end loss estimation: lookup tables, building EAL, zone EAL and event totals.

Classes:

Name Description
LossEstimation

Orchestrate the full loss-estimation chain from the current inputs.

LossEstimation dataclass #

LossEstimation(
    damage_state_path: Optional[str] = None,
    wind_speed_path: Optional[str] = None,
    flood_depth_path: Optional[str] = None,
    hurricane_prob_path: Optional[str] = None,
    hurricane_probabilities: Optional[ndarray] = None,
    prob_ds_file_path: Optional[str] = None,
    damage_provider: Optional[
        DamageProbabilityProvider
    ] = None,
    output_dir: Optional[str] = None,
    datasets_loaded: bool = False,
    n_building_types: int = 8,
    n_component_configurations: int = 192,
    lookup_dtype: str = "float32",
    normalization_tolerance: float = 0.001,
    inventory_csv_path: Optional[str] = None,
    wind_ids_path: Optional[str] = None,
    flood_ids_path: Optional[str] = None,
    zone_id_col: Optional[str] = "i_lh740",
    index_mode: str = "floor",
    combine_mode: str = "additive",
    value_basis: str = "structure_value",
    chunk_size: int = 100000,
    exposure_loaded: bool = False,
    aggregation_col: Optional[str] = None,
    zones_path: Optional[str] = None,
)

Bases: RegionalLossEstimator

Orchestrate the full loss-estimation chain from the current inputs.

Construct it with the damage library, the exposure export and (optionally) a zone layer; with the automatic execution flags on, every result is available as an attribute after construction. estimate_all_losses recomputes every result from the current inputs and returns them without mutating the object.

Methods:

Name Description
estimate_all_losses

Recompute lookup tables, building EAL, zone EAL and event totals.

save_all_outputs

Write every result to the output folder.

estimate_all_losses #

estimate_all_losses() -> Dict[str, Any]

Compute every loss result from the current inputs.

Outputs

None beyond the returned value.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: wind_lookup, flood_lookup (existing tables, or tables built

Dict[str, Any]

from the library), building_eal, zone_eal and event_losses.

save_all_outputs #

save_all_outputs(
    output_dir: Optional[str] = None,
) -> Dict[str, str]

Write the lookup tables and the three result tables.

Parameters:

Name Type Description Default
output_dir Optional[str]

Folder to write into; defaults to <Config.OUTPUTS_PATH>/loss_estimation.

None
Outputs

Writes L_mcw_wd.npy, L_mcf_fld.npy, STARR_lookup_metadata.txt, building_eal.csv, zone_eal.csv and event_losses.csv.

Returns:

Type Description
Dict[str, str]

Dict[str, str]: Written paths keyed by wind_lookup, flood_lookup, metadata,

Dict[str, str]

building_eal, zone_eal and event_losses.

Regional Loss#

regional_loss #

Regional aggregation of expected annual loss and per-event regional totals.

Building EAL is summed within zones (for example the LEAPHI 740 system carried by the exposure export), optionally after remapping to a coarser nested zone system through the zone layer, and per-event regional losses are summed over all buildings.

Classes:

Name Description
RegionalLossEstimator

Aggregate building EAL to zones and total per-event losses over the region.

RegionalLossEstimator dataclass #

RegionalLossEstimator(
    damage_state_path: Optional[str] = None,
    wind_speed_path: Optional[str] = None,
    flood_depth_path: Optional[str] = None,
    hurricane_prob_path: Optional[str] = None,
    hurricane_probabilities: Optional[ndarray] = None,
    prob_ds_file_path: Optional[str] = None,
    damage_provider: Optional[
        DamageProbabilityProvider
    ] = None,
    output_dir: Optional[str] = None,
    datasets_loaded: bool = False,
    n_building_types: int = 8,
    n_component_configurations: int = 192,
    lookup_dtype: str = "float32",
    normalization_tolerance: float = 0.001,
    inventory_csv_path: Optional[str] = None,
    wind_ids_path: Optional[str] = None,
    flood_ids_path: Optional[str] = None,
    zone_id_col: Optional[str] = "i_lh740",
    index_mode: str = "floor",
    combine_mode: str = "additive",
    value_basis: str = "structure_value",
    chunk_size: int = 100000,
    exposure_loaded: bool = False,
    aggregation_col: Optional[str] = None,
    zones_path: Optional[str] = None,
)

Bases: BuildingLossEstimator

Aggregate building EAL to zones and total per-event losses over the region.

Attributes:

Name Type Description
aggregation_col Optional[str]

Coarser zone system to aggregate to (e.g. "i_lh503"); None aggregates by zone_id_col itself.

zones_path Optional[str]

Zone layer needed to map zone_id_col onto aggregation_col.

zones Optional[GeoDataFrame]

Loaded zone layer.

aggregation_key ndarray

Aggregation unit per building, -1 when unassigned.

zone_eal DataFrame

EAL sums per unit.

event_losses DataFrame

Regional loss per event.

Methods:

Name Description
load_zones

Load the zone layer.

calculate_zone_lookup

Fine-to-coarse zone mapping with a nesting check.

calculate_aggregation_key

Aggregation unit per building.

calculate_zone_eal

EAL sums per unit.

calculate_event_losses

Regional monetary loss per event.

save_zone_eal

Write the zone table.

save_event_losses

Write the event table.

calculate_aggregation_key #

calculate_aggregation_key(
    building_table: DataFrame,
    zones: Optional[DataFrame],
    zone_id_col: Optional[str],
    aggregation_col: Optional[str],
) -> ndarray

Aggregation unit per building.

Parameters:

Name Type Description Default
building_table DataFrame

Inventory table holding zone_id_col.

required
zones Optional[DataFrame]

Zone layer, required only when remapping to aggregation_col.

required
zone_id_col Optional[str]

Zone column of the inventory.

required
aggregation_col Optional[str]

Target zone system, or None / the same column for no remapping.

required
Outputs

None beyond the returned value.

Returns:

Type Description
ndarray

np.ndarray: Integer unit per building; -1 for unassigned buildings and for fine zones

ndarray

absent from the zone layer.

Raises:

Type Description
ValueError

If a remapping is requested without a zone layer.

calculate_event_losses #

calculate_event_losses(
    building_table: DataFrame,
    wind_ids: ndarray,
    flood_ids: ndarray,
    probabilities: ndarray,
    surface: Optional[ndarray] = None,
) -> DataFrame

Regional monetary loss per event.

Parameters:

Name Type Description Default
building_table DataFrame

Inventory table with M, C and the value_basis column.

required
wind_ids ndarray

Continuous wind IDs, shape (n_buildings, n_events).

required
flood_ids ndarray

Continuous flood IDs, shape (n_buildings, n_events).

required
probabilities ndarray

Annual event probabilities, shape (n_events,).

required
surface Optional[ndarray]

Joint surface for joint mode.

None
Outputs

None beyond the returned value.

Returns:

Type Description
DataFrame

pd.DataFrame: Indexed by event with columns probability, loss_wind,

DataFrame

loss_flood and loss_combined (sums of loss_ratio * value over buildings).

calculate_zone_eal #

calculate_zone_eal(
    building_eal: DataFrame, aggregation_key: ndarray
) -> DataFrame

Sum the building EAL within aggregation units.

Parameters:

Name Type Description Default
building_eal DataFrame

Output of calculate_building_eal.

required
aggregation_key ndarray

Unit per building.

required
Outputs

None beyond the returned value.

Returns:

Type Description
DataFrame

pd.DataFrame: Indexed by unit (ascending, with -1 last) with columns

DataFrame

eal_wind, eal_flood, eal_combined, n_buildings and value.

calculate_zone_lookup #

calculate_zone_lookup(
    zones: DataFrame, fine_col: str, coarse_col: str
) -> Dict[int, int]

Map every fine zone id onto its coarser zone id.

Parameters:

Name Type Description Default
zones DataFrame

Zone table holding both id columns.

required
fine_col str

Fine zone-id column (e.g. "i_lh740").

required
coarse_col str

Coarse zone-id column (e.g. "i_lh503").

required
Outputs

None beyond the returned value.

Returns:

Type Description
Dict[int, int]

Dict[int, int]: Fine id to coarse id.

Raises:

Type Description
ValueError

If a fine zone maps to more than one coarse zone (the systems do not nest).

load_zones #

load_zones() -> None

Load the optional zone layer.

Outputs

Sets zones to the layer, or None when no path is configured.

Returns:

Type Description
None

None

save_event_losses #

save_event_losses(path: Optional[str] = None) -> str

Write event_losses to CSV.

Parameters:

Name Type Description Default
path Optional[str]

Output file; defaults to <output_dir>/event_losses.csv.

None
Outputs

Writes the CSV file.

Returns:

Name Type Description
str str

The written path.

save_zone_eal #

save_zone_eal(path: Optional[str] = None) -> str

Write zone_eal to CSV.

Parameters:

Name Type Description Default
path Optional[str]

Output file; defaults to <output_dir>/zone_eal.csv.

None
Outputs

Writes the CSV file.

Returns:

Name Type Description
str str

The written path.