Skip to content

Damage Probability Calculation#

The damage probability calculation module provides functionality for calculating damage probabilities.

Class Diagram#

classDiagram
    class BaseDamageProbabilityCalculation {
        +BuildingInventory
        +Sampling
        +Covariance
        +ProbDS_Flood
        +DamageStates
        +WindSpeeds
        +WindOrientations
        +MeanResistanceCV
        +MeanResistanceValue
        +ComponentCombination_Hip
        +ComponentCombination_Gable
        +ComponentCombination_All
        +IterationResult
        +ProbDS_wfd_dict
        +load_prob_ds_flood()
        +load_damage_states()
        +load_wind_speeds()
        +load_wind_orientations()
        +load_mean_resistance_cv()
        +load_mean_resistance_value()
        +load_component_combinations()
    }

    class DamageCalculator {
        +get_component_combination_hip()
        +get_component_combination_gable()
        +initialize_resistance_values()
        +calculate_resistance_values()
    }

    class DamageProbabilityCalculation {
        +DamageRatios
        +FailureChecks
        +building_types_to_process
        +cindex_to_process
        +set_building_types_to_process()
        +set_cindex_to_process()
        +should_process_combination()
        +save_result_per_building_and_cindex()
        +process_single_iteration()
        +process_component_combination()
        +get_available_building_types()
        +get_available_cindices()
        +get_average_damage_probability()
        +aggregate_results()
    }

    class DamageRatioExporter {
        <<dataclass>>
        +int building_type
        +int cindex
        +List~Dict~ collected_data
        +collect_detailed_ratios()$ Dict
        +add_record()
        +aggregate_and_save_to_csv() str
        +clear()
    }

    BaseDamageProbabilityCalculation <|-- DamageCalculator
    DamageCalculator <|-- DamageProbabilityCalculation
    DamageProbabilityCalculation o-- DamageRatioCalculation : contains
    DamageProbabilityCalculation o-- LoadingAndFailureCheck : contains
    DamageProbabilityCalculation ..> DamageRatioExporter : uses

Base Classes#

base #

Classes:

Name Description
BaseDamageProbabilityCalculation

A base class for the damage probability calculation.

BaseDamageProbabilityCalculation dataclass #

BaseDamageProbabilityCalculation(
    BuildingInventory: BuildingInventory,
    Sampling: Sampling,
    Covariance: Covariance,
    ProbDS_wfd_dict: dict[
        tuple[int, int], ndarray
    ] = dict(),
    datasets_loaded: bool = False,
)

A base class for the damage probability calculation.

Attributes:

Name Type Description
DamageRatios DamageRatioCalculation

An object of DamageRatioCalculation class.

FailureChecks LoadingAndFailureCheck

An object of LoadingAndFailureCheck class.

BuildingInventory BuildingInventory

An object of BuildingInventory class.

Sampling Sampling

An object of Sampling class.

Covariance Covariance

An object of Covariance class.

MaxIterations int

The maximum number of iterations.

OutputFolder str

The path to the output folder.

ProbDS_Flood ndarray

The probability of damage state for flood.

DamageStates ndarray

The damage states of the building.

WindSpeeds ndarray

The wind speeds.

WindOrientations ndarray

The wind orientations.

MeanResistanceCV ndarray

The mean resistance coefficient of variation.

MeanResistanceValue ndarray

The mean resistance value.

ComponentCombination_Hip ndarray

The component combination for hip roof.

ComponentCombination_Gable ndarray

The component combination for gable roof.

ComponentCombination_All ndarray

The component combination for all roofs.

Methods:

Name Description
load_prob_ds_flood

Load the probability of damage state for flood.

load_damage_states

Load the damage states of the building.

load_wind_speeds

Load the wind speeds.

load_wind_orientations

Load the wind orientations.

load_mean_resistance_cv

Load the mean resistance coefficient of variation.

load_mean_resistance_value

Load the mean resistance value.

load_component_combinations

Load the component combinations for hip and gable roof.

load_component_combinations #

load_component_combinations(file_names: dict = None)

This method loads the component combinations for hip and gable roof.

Parameters:

Name Type Description Default
file_names dict

The names of the JSON files.

None

load_damage_states #

load_damage_states(file_name: str = 'DamageState.json')

This method loads the damage state of the building.

Parameters:

Name Type Description Default
file_name str

The name of the JSON file.

'DamageState.json'

load_mean_resistance_cv #

load_mean_resistance_cv(
    file_name: str = "MeanResistanceCV.json",
)

This method loads the mean resistance coefficient of variation.

Parameters:

Name Type Description Default
file_name str

The name of the JSON file.

'MeanResistanceCV.json'

load_mean_resistance_value #

load_mean_resistance_value(
    file_name: str = "MeanResistanceValue.json",
)

This method loads the mean resistance value.

Parameters:

Name Type Description Default
file_name str

The name of the JSON file.

'MeanResistanceValue.json'

load_prob_ds_flood #

load_prob_ds_flood(file_name: str = 'ProbDS_Flood.json')

This method loads the probability of damage state for flood.

load_wind_orientations #

load_wind_orientations(
    file_name: str = "WindOrientation.json",
)

This method loads the wind orientations.

Parameters:

Name Type Description Default
file_name str

The name of the JSON file.

'WindOrientation.json'

load_wind_speeds #

load_wind_speeds(file_name: str = 'WindSpeed.json')

This method loads the wind speeds.

Parameters:

Name Type Description Default
file_name str

The name of the JSON file.

'WindSpeed.json'

Damage Calculator#

damage_calculator #

Classes:

Name Description
DamageCalculator

DamageCalculator dataclass #

DamageCalculator(
    BuildingInventory: BuildingInventory,
    Sampling: Sampling,
    Covariance: Covariance,
    ProbDS_wfd_dict: dict[
        tuple[int, int], ndarray
    ] = dict(),
    datasets_loaded: bool = False,
)

Bases: BaseDamageProbabilityCalculation

Methods:

Name Description
calculate_resistance_values

Calculate resistance values based on the component number and resistance value index.

fn_damage_probability

Calculate probability of damage states based on provided iteration results.

get_component_combination_gable

Return the gable-roof component configuration columns used in damage calculations.

get_component_combination_hip

Return the hip-roof component configuration columns used in damage calculations.

initialize_resistance_values

Initialize resistance values based on the component combination index.

calculate_resistance_values staticmethod #

calculate_resistance_values(
    num_component_array: list[int],
    resistance_value_c_index: ndarray,
) -> ndarray

Calculate resistance values based on the component number and resistance value index.

Parameters:

Name Type Description Default
num_component_array list[int]

The number of each component.

required
resistance_value_c_index ndarray

The resistance value index array.

required

Returns:

Type Description
ndarray

np.ndarray: The calculated resistance array.

Outputs

None beyond the returned value.

fn_damage_probability staticmethod #

fn_damage_probability(
    iteration_result: ndarray, damage_states: ndarray
) -> ndarray

Calculate probability of damage states based on provided iteration results.

Parameters:

Name Type Description Default
iteration_result ndarray

The iteration results array [windSpeed, floodDepth, iteration]

required
damage_states ndarray

The damage states thresholds

required

Returns:

Type Description
ndarray

np.ndarray: Probability of damage states

Outputs

None beyond the returned value.

get_component_combination_gable #

get_component_combination_gable() -> ndarray

Return the gable-roof component configuration columns used in damage calculations.

Outputs

None beyond the returned value.

Returns:

Type Description
ndarray

np.ndarray: Component combination matrix for gable-roof buildings.

get_component_combination_hip #

get_component_combination_hip() -> ndarray

Return the hip-roof component configuration columns used in damage calculations.

Outputs

None beyond the returned value.

Returns:

Type Description
ndarray

np.ndarray: Component combination matrix for hip-roof buildings.

initialize_resistance_values staticmethod #

initialize_resistance_values(
    ComponentCombination_cIndex: ndarray,
    resistance_array: ndarray,
) -> ndarray

Initialize resistance values based on the component combination index.

Parameters:

Name Type Description Default
ComponentCombination_cIndex ndarray

The component combination index array.

required
resistance_array ndarray

The resistance array to be initialized.

required

Returns:

Type Description
ndarray

np.ndarray: The initialized resistance array.

Outputs

None beyond the returned value.

Main Calculation#

main #

Classes:

Name Description
DamageProbabilityCalculation

A class used to represent the damage probability calculation engine.

DamageProbabilityCalculation dataclass #

DamageProbabilityCalculation(
    BuildingInventory: BuildingInventory,
    Sampling: Sampling,
    Covariance: Covariance,
    ProbDS_wfd_dict: dict[
        tuple[int, int], ndarray
    ] = dict(),
    datasets_loaded: bool = False,
    building_types_to_process: Optional[List[int]] = None,
    cindex_to_process: Optional[List[int]] = None,
)

Bases: DamageCalculator

A class used to represent the damage probability calculation engine.

This implementation utilizes local variables to ensure thread safety. The per–iteration and per–orientation variables (including FailureChecks and DamageRatios) are stored locally. After computing damage probabilities per wind orientation, the results are averaged and saved directly to disk.

Methods:

Name Description
aggregate_results

Aggregates all individual building type and cIndex result files into a single dictionary.

get_available_building_types

Get a list of all available building types in the inventory.

get_available_cindices

Get a list of all available component indices.

get_average_damage_probability

Computes the damage probabilities over specified buildings and component configurations,

process_component_combination

Process the component combination for a building with parallelization over iterations.

process_single_iteration

Process a single iteration for a given orientation, building, and component combination.

save_result_per_building_and_cindex

Saves the damage probability array for a specific building type and cIndex to disk.

set_building_types_to_process

Set specific building types to process in this run.

set_cindex_to_process

Set specific component indices to process in this run.

should_process_combination

Determine if this building type and cindex combination should be processed

aggregate_results #

aggregate_results(
    output_dir: str = None,
) -> Dict[Tuple[str, int], ndarray]

Aggregates all individual building type and cIndex result files into a single dictionary. Populates the self.ProbDS_wfd_dict property.

Parameters:

Name Type Description Default
output_dir str

Directory containing the individual result files. Defaults to Config.OUTPUTS_PATH.

None

Returns:

Type Description
Dict[Tuple[str, int], ndarray]

Dict[Tuple[str, int], np.ndarray]: Dictionary containing all damage probability arrays keyed by (building_type, cindex).

get_available_building_types #

get_available_building_types() -> List[int]

Get a list of all available building types in the inventory.

Returns:

Type Description
List[int]

List[str]: List of building type identifiers

Outputs

None beyond the returned value.

get_available_cindices #

get_available_cindices() -> List[int]

Get a list of all available component indices.

Returns:

Type Description
List[int]

List[int]: List of 1-based component indices

Outputs

None beyond the returned value.

get_average_damage_probability #

get_average_damage_probability() -> bool

Computes the damage probabilities over specified buildings and component configurations, and saves them directly to individual files. Does not populate the ProbDS_wfd_dict to conserve memory.

Returns:

Name Type Description
bool bool

True if processing completed successfully

Outputs

None beyond the returned value.

process_component_combination #

process_component_combination(
    building: Building, ComponentCombination, cIndex: int
) -> tuple

Process the component combination for a building with parallelization over iterations.

This method processes a specific component configuration for a building across all wind orientations, wind speeds, and flood depths using Monte Carlo simulation with parallel processing over iterations.

Parameters:

Name Type Description Default
building Building

The building object to process.

required
ComponentCombination ndarray

Retained for compatibility with existing caller signatures.

required
cIndex int

The 1-based component configuration index to process.

required

Returns:

Name Type Description
tuple tuple

A tuple containing (building.BldgType, cIndex, averaged_damage_probability_array), or None if this combination should be skipped based on user filters.

Notes

When Config.EXPORT_DETAILED_DAMAGE_RATIOS is True, this method also exports detailed damage ratio breakdowns to a CSV file for each (building_type, cIndex) combination. The CSV file contains damage ratios averaged over Monte Carlo iterations for each (wind_orientation, wind_speed, flood_depth) combination.

The CSV file is saved to Config.OUTPUTS_PATH with the naming pattern: DetailedDR_m{building_type}_c{cIndex}_iter{NUM_OF_ITERATIONS}.csv

Outputs

None beyond the returned value.

process_single_iteration #

process_single_iteration(
    ComponentSample,
    Iter,
    building,
    WindOrientation_oIndex,
    NumComponent,
    wIndex_range,
    fIndex_range,
    cIndex,
    collect_detailed: bool = False,
    rng_seed: Optional[int] = None,
) -> Tuple[ndarray, Optional[List[Dict[str, Any]]]]

Process a single iteration for a given orientation, building, and component combination.

Parameters:

Name Type Description Default
ComponentSample ndarray

Array of component resistance samples.

required
Iter int

The current iteration number.

required
building Building

The building object being processed.

required
WindOrientation_oIndex float

The wind orientation angle value.

required
NumComponent List[int]

List containing the number of each component type.

required
wIndex_range range

Range of wind speed indices to process.

required
fIndex_range range

Range of flood depth indices to process.

required
cIndex int

The 0-based component configuration index into ComponentCombination_All.

required
collect_detailed bool

If True, collect detailed component-level damage ratios for CSV export. Default is False. This is controlled by Config.EXPORT_DETAILED_DAMAGE_RATIOS.

False
rng_seed Optional[int]

Seed for the per-iteration damage-ratio random stream.

None

Raises:

Type Description
IndexError

If cIndex is out of bounds for ComponentCombination_All.

Returns:

Name Type Description
tuple Tuple[ndarray, Optional[List[Dict[str, Any]]]]

A tuple containing: - numpy.ndarray: Iteration results for this iteration across all wind speeds and flood depths, shape (len(wIndex_range), len(fIndex_range)). - List[Dict[str, Any]] or None: If collect_detailed is True, a list of dictionaries containing detailed damage ratio breakdowns for each (wind_speed, flood_depth) combination. Each dict includes keys for wind_speed_index, flood_depth_index, and all component damage ratios. If collect_detailed is False, returns None.

Notes

When collect_detailed is True, the detailed ratios include:

  • dr_total: Total building damage ratio
  • dr_explicit: Explicit damage ratio
  • dr_implicit: Implicit damage ratio
  • dr_exp_wind_RC, dr_exp_wind_RS, dr_exp_wind_RWC, dr_exp_wind_O, dr_exp_wind_W: Explicit wind damage ratios for each component
  • dr_imp_wind_I, dr_imp_wind_E, dr_imp_wind_M, dr_imp_wind_P: Implicit wind damage ratios for each component
  • dr_imp_flood: Implicit flood damage ratio
Outputs

None beyond the returned value.

save_result_per_building_and_cindex #

save_result_per_building_and_cindex(
    building_type: int, cindex: int, probds_wfd: ndarray
)

Saves the damage probability array for a specific building type and cIndex to disk. Includes the number of iterations in the filename.

Parameters:

Name Type Description Default
building_type int

The building type identifier

required
cindex int

The component configuration index

required
probds_wfd ndarray

The damage probability array to save

required

set_building_types_to_process #

set_building_types_to_process(
    building_types: List[int],
) -> None

Set specific building types to process in this run.

Parameters:

Name Type Description Default
building_types List[int]

List of building type identifiers to process

required
Outputs

Updates building_types_to_process.

Returns:

Type Description
None

None

set_cindex_to_process #

set_cindex_to_process(cindices: List[int]) -> None

Set specific component indices to process in this run.

Parameters:

Name Type Description Default
cindices List[int]

List of 1-based component indices to process. For example, value 1 maps to internal index 0.

required
Outputs

Updates cindex_to_process.

Returns:

Type Description
None

None

should_process_combination #

should_process_combination(
    building_type: int, cindex: int
) -> bool

Determine if this building type and cindex combination should be processed based on user-specified filters.

Parameters:

Name Type Description Default
building_type int

Building type identifier

required
cindex int

1-based component configuration index

required

Returns:

Name Type Description
bool bool

True if this combination should be processed, False otherwise

Outputs

None beyond the returned value.

Damage Ratio Exporter#

damage_ratio_exporter #

Module for exporting detailed damage ratio results to CSV files.

This module provides utilities for collecting, aggregating, and exporting detailed damage ratio breakdowns from Monte Carlo simulations. The exported CSV files contain per-component damage ratios averaged over iterations.

Classes:

Name Description
DamageRatioExporter

Utility class for collecting and exporting detailed damage ratios.

DamageRatioExporter dataclass #

DamageRatioExporter(
    building_type: int,
    cindex: int,
    collected_data: List[Dict[str, Any]] = list(),
)

Utility class for collecting and exporting detailed damage ratio results.

This class provides methods to extract component-level damage ratios from DamageRatioCalculation objects and export them as CSV files. Results are averaged over Monte Carlo iterations before export.

The exported CSV files contain the following columns. - m: Building type identifier - c: Component configuration index - wind_orientation_index: Wind orientation index - wind_speed_index: Wind speed index - flood_depth_index: Flood depth index - dr_total: Total building damage ratio - dr_explicit: Explicit damage ratio (wind components) - dr_implicit: Implicit damage ratio (interior + flood) - dr_exp_wind_RC: Explicit damage ratio for Roof Coverings - dr_exp_wind_RS: Explicit damage ratio for Roof Sheathings - dr_exp_wind_RWC: Explicit damage ratio for Roof-Wall Connections - dr_exp_wind_O: Explicit damage ratio for Openings - dr_exp_wind_W: Explicit damage ratio for Walls - dr_imp_wind_I: Implicit damage ratio for Interior - dr_imp_wind_E: Implicit damage ratio for Electrical - dr_imp_wind_M: Implicit damage ratio for Mechanical - dr_imp_wind_P: Implicit damage ratio for Plumbing - dr_imp_flood: Implicit damage ratio for Flood

Attributes:

Name Type Description
building_type int

The building type identifier.

cindex int

The component configuration index.

collected_data List[Dict[str, Any]]

List of collected damage ratio records.

Methods:

Name Description
collect_detailed_ratios

Extract detailed damage ratios from a DamageRatioCalculation object.

add_record

Add a single record to the collected data.

aggregate_and_save_to_csv

Average over iterations and save to CSV file.

clear

Clear all collected data.

add_record #

add_record(
    wind_orientation_index: int,
    wind_speed_index: int,
    flood_depth_index: int,
    iteration: int,
    detailed_ratios: Dict[str, float],
) -> None

Add a single damage ratio record to the collected data.

Parameters:

Name Type Description Default
wind_orientation_index int

The wind orientation index.

required
wind_speed_index int

The wind speed index.

required
flood_depth_index int

The flood depth index.

required
iteration int

The Monte Carlo iteration number.

required
detailed_ratios Dict[str, float]

Dictionary of damage ratio values as returned by collect_detailed_ratios().

required
Notes

The record is stored internally and will be aggregated when aggregate_and_save_to_csv() is called.

Outputs

Performs initialization or configuration side effects described above.

Returns:

Type Description
None

None

aggregate_and_save_to_csv #

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

Aggregate collected data by averaging over iterations and save to CSV.

This method groups the collected damage ratio records by (wind_orientation_index, wind_speed_index, flood_depth_index), computes the mean of all damage ratio columns over iterations, and saves the result to a CSV file.

Parameters:

Name Type Description Default
output_dir str

Directory path for output file. Defaults to Config.OUTPUTS_PATH if not provided.

None

Returns:

Name Type Description
str str

The file path of the saved CSV file.

Notes

The CSV file is named using the pattern: DetailedDR_m{building_type}_c{cindex}_iter{NUM_OF_ITERATIONS}.csv

The 'iteration' column is excluded from the output as values are averaged over all iterations.

clear #

clear() -> None

Clear all collected data.

Notes

This method resets the collected_data list to empty. Use this to free memory after saving results or to start fresh.

Outputs

Updates instance or class attributes described above.

Returns:

Type Description
None

None

collect_detailed_ratios staticmethod #

collect_detailed_ratios(
    damage_ratios: DamageRatioCalculation,
) -> Dict[str, float]

Extract detailed damage ratios from a DamageRatioCalculation object.

This method extracts all component-level damage ratios from the given DamageRatioCalculation object and returns them in a dictionary with standardized column names for CSV export.

Parameters:

Name Type Description Default
damage_ratios DamageRatioCalculation

The damage ratio calculation object containing computed damage ratios for all components.

required

Returns:

Type Description
Dict[str, float]

Dict[str, float]: A dictionary containing all damage ratio values with keys: - dr_total: Total building damage ratio - dr_explicit: Explicit damage ratio - dr_implicit: Implicit damage ratio - dr_exp_wind_RC: Roof Coverings explicit damage ratio - dr_exp_wind_RS: Roof Sheathings explicit damage ratio - dr_exp_wind_RWC: Roof-Wall Connections explicit damage ratio - dr_exp_wind_O: Openings explicit damage ratio - dr_exp_wind_W: Walls explicit damage ratio - dr_imp_wind_I: Interior implicit damage ratio - dr_imp_wind_E: Electrical implicit damage ratio - dr_imp_wind_M: Mechanical implicit damage ratio - dr_imp_wind_P: Plumbing implicit damage ratio - dr_imp_flood: Flood implicit damage ratio

Notes

This method accesses the ExplicitDamageRatioWind, ImplicitDamageRatioWind, and ImplicitDamageRatioFlood attributes of the DamageRatioCalculation object to extract component-level values.

Outputs

None beyond the returned value.