Skip to content

Exposure#

The exposure module links a building inventory to the CHEERSafe damage model. It maps user attributes onto the structural archetype M and the resistance configuration C, assigns per-event wind and flood intensities from hazard control points to building centroids, converts them to the package's continuous hazard IDs (Wind_Tr, Flood_Tr), assigns zone ids and writes the STARR-compatible export consumed by Loss Estimation.

Class Diagram#

classDiagram
    class InventorySchema {
        +str bldgtype_col
        +str roof_col
        +str story_col
        +str garage_col
        +str occupancy_col
        +str year_col
        +str coast_distance_col
        +float coast_distance_to_miles
        +str structure_value_col
        +str contents_value_col
        +Optional~str~ building_key_col
    }
    class BaseExposure {
        +Optional~str~ inventory_path
        +Optional~str~ hazard_dir
        +Optional~str~ zones_path
        +InventorySchema schema
        +gpd.GeoDataFrame inventory
        +np.ndarray hazard_wind
        +np.ndarray hazard_flood
        +load_inventory()
        +load_hazard_events()
        +load_zones()
    }
    class ArchetypeAssigner {
        +float coast_threshold_miles
        +bool drop_unmatched_occupancy
        +Optional~int~ seed
        +gpd.GeoDataFrame archetype_inventory
        +calculate_archetype_m()
        +calculate_component_probabilities()
        +calculate_component_configuration()
        +calculate_archetypes()
    }
    class HazardMapper {
        +str average_mode
        +float wind_to_mph
        +float flood_to_inches
        +np.ndarray wind_ids
        +np.ndarray flood_ids
        +calculate_neighbor_match()
        +calculate_event_intensity()
        +calculate_hazard_id()
        +calculate_hazard_ids()
    }
    class Exposure {
        +Optional~str~ zone_id_col
        +bool drop_unassigned_zones
        +np.ndarray zone_ids
        +pd.DataFrame starr_inventory
        +calculate_zone_assignment()
        +calculate_starr_inventory()
        +calculate_starr_export()
        +save_starr_inputs()
    }
    class SyntheticExposureData {
        +make_inventory()
        +make_hazard_events()
        +make_zones()
        +make_damage_library()
        +make_hurricane_probabilities()
        +save_inputs()
    }

    BaseExposure <|-- ArchetypeAssigner
    ArchetypeAssigner <|-- HazardMapper
    HazardMapper <|-- Exposure
    BaseExposure o-- InventorySchema

Archetype Assignment#

archetype #

Structural archetype (M) and resistance-configuration (C) assignment.

M (1-8) follows Peng (2013, Table 3.1): number of stories, hip versus gable roof and garage presence. C (1-192) is one row of the package's ComponentCombination_All.json table, sampled per building from the product of six component-state distributions that depend on the construction period and the distance to the coast (Peng 2013, Tables 3.6 and 3.7). The rule tables and the archetype encoding reproduce the verified Eastern North Carolina scripts; the sampling is seeded through :class:cheersafe.tools.Sampling.

Classes:

Name Description
ArchetypeAssigner

Assign the structural archetype M and resistance configuration C to buildings.

Attributes:

Name Type Description
ARCHETYPE_CHOICES Tuple[int, ...]

Archetype codes in the order of the eight (stories, roof, garage) conditions of the source.

COMPONENT_NAMES Tuple[str, ...]

Component columns of ComponentCombination_All.json: roof covering, roof

COMPONENT_RULES_FAR_COAST Dict[int, Dict[str, Dict[int, float]]]

Component-state probabilities at 2 miles or more from the coast, by year group (Peng 2013, Table 3.7).

COMPONENT_RULES_NEAR_COAST Dict[int, Dict[str, Dict[int, float]]]

Component-state probabilities within 2 miles of the coast, by year group (Peng 2013, Table 3.6).

YEAR_GROUP_LABELS Tuple[str, ...]

Construction-period labels for year groups 0, 1 and 2 (the STARR export spelling).

ARCHETYPE_CHOICES module-attribute #

ARCHETYPE_CHOICES: Tuple[int, ...] = (
    1,
    3,
    2,
    4,
    5,
    7,
    6,
    8,
)

Archetype codes in the order of the eight (stories, roof, garage) conditions of the source.

COMPONENT_NAMES module-attribute #

COMPONENT_NAMES: Tuple[str, ...] = (
    "RC",
    "RF",
    "RTW",
    "O",
    "W",
    "F",
)

Component columns of ComponentCombination_All.json: roof covering, roof sheathing, roof-to-wall connection, openings, walls and flood mitigation.

COMPONENT_RULES_FAR_COAST module-attribute #

COMPONENT_RULES_FAR_COAST: Dict[
    int, Dict[str, Dict[int, float]]
] = {
    0: dict(_PRE_1968),
    1: {
        "RC": {1: 0.9, 2: 0.1},
        "RF": {1: 1.0, 2: 0.0},
        "RTW": {1: 0.9, 2: 0.1},
        "O": {1: 0.9, 2: 0.05, 3: 0.05},
        "W": {1: 1.0, 2: 0.0},
        "F": {1: 0.85, 2: 0.05, 3: 0.05, 4: 0.05},
    },
    2: {
        "RC": {1: 0.8, 2: 0.2},
        "RF": {1: 0.9, 2: 0.1},
        "RTW": {1: 0.8, 2: 0.2},
        "O": {1: 0.8, 2: 0.1, 3: 0.1},
        "W": {1: 0.9, 2: 0.1},
        "F": {1: 0.85, 2: 0.05, 3: 0.05, 4: 0.05},
    },
}

Component-state probabilities at 2 miles or more from the coast, by year group (Peng 2013, Table 3.7).

COMPONENT_RULES_NEAR_COAST module-attribute #

COMPONENT_RULES_NEAR_COAST: Dict[
    int, Dict[str, Dict[int, float]]
] = {
    0: dict(_PRE_1968),
    1: {
        "RC": {1: 0.1, 2: 0.9},
        "RF": {1: 1.0, 2: 0.0},
        "RTW": {1: 0.5, 2: 0.5},
        "O": {1: 0.8, 2: 0.1, 3: 0.1},
        "W": {1: 0.7, 2: 0.3},
        "F": {1: 0.2, 2: 0.2, 3: 0.2, 4: 0.4},
    },
    2: {
        "RC": {1: 0.0, 2: 1.0},
        "RF": {1: 0.5, 2: 0.5},
        "RTW": {1: 0.1, 2: 0.9},
        "O": {1: 0.5, 2: 0.25, 3: 0.25},
        "W": {1: 0.1, 2: 0.9},
        "F": {1: 0.0, 2: 0.1, 3: 0.1, 4: 0.8},
    },
}

Component-state probabilities within 2 miles of the coast, by year group (Peng 2013, Table 3.6).

YEAR_GROUP_LABELS module-attribute #

YEAR_GROUP_LABELS: Tuple[str, ...] = (
    "before1968",
    "1968to1997",
    "1997to2010",
)

Construction-period labels for year groups 0, 1 and 2 (the STARR export spelling).

ArchetypeAssigner dataclass #

ArchetypeAssigner(
    inventory_path: Optional[str] = None,
    hazard_dir: Optional[str] = None,
    hazard_file_pattern: str = "*.parquet",
    wind_col: str = "Wind",
    flood_col: str = "Flood",
    nodata_value: float = -9999.0,
    zones_path: Optional[str] = None,
    wind_speed_path: Optional[str] = None,
    flood_depth_path: Optional[str] = None,
    component_combination_path: Optional[str] = None,
    output_dir: Optional[str] = None,
    schema: InventorySchema = InventorySchema(),
    datasets_loaded: bool = False,
    coast_threshold_miles: float = 2.0,
    year_breaks: Tuple[int, int] = (1968, 1997),
    drop_unmatched_occupancy: bool = False,
    seed: Optional[int] = None,
)

Bases: BaseExposure

Assign the structural archetype M and resistance configuration C to buildings.

Attributes:

Name Type Description
coast_threshold_miles float

Buildings closer than this use the near-coast rules.

year_breaks Tuple[int, int]

Year-built breakpoints separating the three construction periods.

drop_unmatched_occupancy bool

When True, drop buildings that are not wood-frame single-family residences. The default False reproduces the verified scripts, where these two filters had no effect.

seed Optional[int]

Seed of the configuration sampling stream; None uses Config.RANDOM_SEED.

archetype_inventory GeoDataFrame

Normalized inventory with M, C and component columns.

Methods:

Name Description
calculate_normalized_attributes

Map user columns onto the archetype attributes and drop incomplete rows.

calculate_archetype_m

Archetype code from stories, roof shape and garage.

calculate_year_group

Construction-period index from year built.

calculate_component_probabilities

Probability of each of the 192 configurations for one rule set.

calculate_component_configuration

Seeded configuration draw per building.

calculate_archetypes

Full normalized inventory with M, C and component states.

save_archetype_inventory

Write the archetype inventory to GeoParquet.

calculate_archetype_m #

calculate_archetype_m(
    n_story: ndarray, is_hip: ndarray, has_garage: ndarray
) -> ndarray

Compute the structural archetype M (Peng 2013, Table 3.1).

Parameters:

Name Type Description Default
n_story ndarray

Number of stories; one story versus more than one.

required
is_hip ndarray

True for hip roofs, False for gable roofs.

required
has_garage ndarray

1 with an attached garage, 0 without.

required
Outputs

None beyond the returned value.

Returns:

Type Description
ndarray

np.ndarray: Archetype codes 1-8. One-story hip roofs with a garage are 1,

ndarray

one-story gable with a garage 2, one-story hip without 3, one-story gable

ndarray

without 4; two-story buildings follow the same pattern as 5-8.

calculate_archetypes #

calculate_archetypes(
    inventory: GeoDataFrame,
) -> GeoDataFrame

Normalize the inventory and assign M, C and the six component states.

Parameters:

Name Type Description Default
inventory GeoDataFrame

Inventory layer with a building_key column.

required
Outputs

None beyond the returned value.

Returns:

Type Description
GeoDataFrame

gpd.GeoDataFrame: The normalized attributes plus M, year_group,

GeoDataFrame

near_coast, C and the columns RC, RF, RTW, O, W, F.

calculate_component_configuration #

calculate_component_configuration(
    year_group: ndarray,
    near_coast: ndarray,
    seed: Optional[int] = None,
) -> ndarray

Draw one resistance configuration C per building.

Buildings are grouped by (year group, coast class); each group shares one cumulative distribution and consumes uniform draws from a single seeded stream, so results are reproducible for a given seed and row order.

Parameters:

Name Type Description Default
year_group ndarray

Construction-period index per building.

required
near_coast ndarray

Near-coast flag per building.

required
seed Optional[int]

Seed override; defaults to seed, then Config.RANDOM_SEED.

None
Outputs

None beyond the returned value.

Returns:

Type Description
ndarray

np.ndarray: Configuration codes 1-192 (int64).

calculate_component_probabilities #

calculate_component_probabilities(
    year_group: int, near_coast: bool
) -> ndarray

Probability of each configuration for one construction period and coast class.

The six component states of every row of the configuration table are treated as independent, so the row probability is the product of the six marginal probabilities of the selected rule set, normalized to one.

Parameters:

Name Type Description Default
year_group int

Construction-period index (0, 1 or 2).

required
near_coast bool

True to use the near-coast rules.

required
Outputs

None beyond the returned value.

Returns:

Type Description
ndarray

np.ndarray: Probabilities over the configuration rows, summing to one.

Raises:

Type Description
ValueError

If the rule set assigns zero mass to every configuration.

calculate_normalized_attributes #

calculate_normalized_attributes(
    inventory: GeoDataFrame,
) -> GeoDataFrame

Map the user inventory onto the archetype attributes and drop incomplete rows.

Category values not listed in the schema become missing values. Rows missing any of roof shape, stories, garage, year built, coast distance or the two values are dropped. Non-wood or non-single-family rows are kept (flagged in is_wood_frame / is_single_family) unless drop_unmatched_occupancy is enabled.

Parameters:

Name Type Description Default
inventory GeoDataFrame

Inventory layer with a building_key column (see BaseExposure.load_inventory).

required
Outputs

None beyond the returned value.

Returns:

Type Description
GeoDataFrame

gpd.GeoDataFrame: Columns building_key, the schema key column when present,

GeoDataFrame

is_wood_frame, roof_shape, n_story, has_garage, is_single_family,

GeoDataFrame

year_built, coast_distance_miles, structure_value, contents_value,

GeoDataFrame

any present passthrough columns and geometry, with a fresh integer index.

calculate_year_group #

calculate_year_group(year_built: ndarray) -> ndarray

Compute the construction-period index from the year built.

Parameters:

Name Type Description Default
year_built ndarray

Year built per building.

required
Outputs

None beyond the returned value.

Returns:

Type Description
ndarray

np.ndarray: 0 before the first break (1968), 1 before the second (1997), else 2.

save_archetype_inventory #

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

Write archetype_inventory to GeoParquet.

Parameters:

Name Type Description Default
path Optional[str]

Output file; defaults to <output_dir>/archetype_inventory.parquet.

None
Outputs

Writes the GeoParquet file and creates its folder if needed.

Returns:

Name Type Description
str str

The written path.

Base Classes#

base #

Base dataclasses and loaders for the exposure module.

InventorySchema describes how a user inventory maps onto the attributes the archetype rules need. BaseExposure owns every input of the exposure workflow: the inventory layer, the per-event hazard control-point layers, the optional zone layer and the package's discrete hazard and component tables. Subclasses add the archetype, hazard-mapping and export calculations.

Classes:

Name Description
BaseExposure

Inputs of the exposure workflow: inventory, hazard control points, zones and tables.

InventorySchema

Column names and category values that map a user inventory onto archetype attributes.

Attributes:

Name Type Description
BUILDING_KEY_COLUMN

Name of the stable per-building key carried through every exposure table.

BUILDING_KEY_COLUMN module-attribute #

BUILDING_KEY_COLUMN = 'building_key'

Name of the stable per-building key carried through every exposure table.

BaseExposure dataclass #

BaseExposure(
    inventory_path: Optional[str] = None,
    hazard_dir: Optional[str] = None,
    hazard_file_pattern: str = "*.parquet",
    wind_col: str = "Wind",
    flood_col: str = "Flood",
    nodata_value: float = -9999.0,
    zones_path: Optional[str] = None,
    wind_speed_path: Optional[str] = None,
    flood_depth_path: Optional[str] = None,
    component_combination_path: Optional[str] = None,
    output_dir: Optional[str] = None,
    schema: InventorySchema = InventorySchema(),
    datasets_loaded: bool = False,
)

Inputs of the exposure workflow: inventory, hazard control points, zones and tables.

Paths left as None resolve under Config.INPUTS_PATH at load time. Hazard events are read from every file in hazard_dir matching hazard_file_pattern, ordered by the integer embedded in the file name, and must share identical control-point geometry.

Attributes:

Name Type Description
inventory_path Optional[str]

Inventory layer (GeoParquet, shapefile, GeoPackage).

hazard_dir Optional[str]

Folder holding one control-point layer per event.

hazard_file_pattern str

Glob pattern selecting the event files.

wind_col str

Wind-speed column of the hazard layers, in m/s.

flood_col str

Flood-depth column of the hazard layers, in metres.

nodata_value float

Sentinel for missing hazard values, treated as zero hazard.

zones_path Optional[str]

Optional polygon zone layer.

wind_speed_path Optional[str]

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

flood_depth_path Optional[str]

FloodDepth.json table (id, inches, m).

component_combination_path Optional[str]

ComponentCombination_All.json table.

output_dir Optional[str]

Output folder; defaults under Config.OUTPUTS_PATH.

schema InventorySchema

Column and category mapping of the inventory.

inventory GeoDataFrame

Loaded inventory with a building_key column.

wind_speeds ndarray

Wind table of shape (n_wind_ids, 3).

flood_depths ndarray

Flood table of shape (n_flood_ids, 3).

component_combinations ndarray

Component states per configuration, (192, 6).

hazard_files List[str]

Event files in event order.

event_names List[str]

Event names (file stems) in event order.

hazard_points_xy ndarray

Control-point coordinates, (n_points, 2).

hazard_crs object

CRS of the hazard layers.

hazard_bounds Tuple[float, float, float, float]

Bounding box of the control points.

hazard_wind ndarray

Raw wind values, (n_events, n_points).

hazard_flood ndarray

Raw flood values, (n_events, n_points).

zones Optional[GeoDataFrame]

Zone layer, or None.

datasets_loaded bool

Whether the loaders have run.

Methods:

Name Description
load_hazard_tables

Load the wind and flood ID tables.

load_component_combinations

Load the component-configuration table.

load_inventory

Load the inventory layer and mint the building key.

load_hazard_events

Load and stack the per-event hazard layers.

load_zones

Load the optional zone layer.

update_outputs

Reload inputs and rerun the automatic steps.

load_component_combinations #

load_component_combinations() -> None

Load the component-configuration table that defines C.

Outputs

Sets component_combinations as an integer array of shape (192, 6).

Returns:

Type Description
None

None

Raises:

Type Description
ValueError

If the table does not have six component columns.

load_hazard_events #

load_hazard_events() -> None

Load every hazard event layer and stack the wind and flood values.

Files are ordered by the integer embedded in their names. Values are kept in their raw units (m/s and m); the nodata sentinel is handled during mapping.

Outputs

Sets hazard_files, event_names, hazard_points_xy, hazard_crs, hazard_bounds, hazard_wind and hazard_flood.

Returns:

Type Description
None

None

Raises:

Type Description
FileNotFoundError

If no file matches the pattern in the hazard folder.

ValueError

If an event layer lacks the hazard columns or its control points differ from the first event.

load_hazard_tables #

load_hazard_tables() -> None

Load the discrete wind-speed and flood-depth ID tables.

Outputs

Sets wind_speeds and flood_depths.

Returns:

Type Description
None

None

load_inventory #

load_inventory() -> None

Load the inventory layer and add the building_key column.

The key is copied from InventorySchema.building_key_col when that column exists and is numeric; otherwise it is the 0-based row position. The key is assigned before any filtering so that every downstream table can be joined back to the source rows.

Outputs

Sets inventory.

Returns:

Type Description
None

None

Raises:

Type Description
ValueError

If the layer has no coordinate reference system.

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

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

InventorySchema dataclass #

InventorySchema(
    bldgtype_col: str = "bldgtype",
    wood_frame_values: Tuple[str, ...] = ("W",),
    roof_col: str = "roof_shape_1",
    gable_values: Tuple[str, ...] = (
        "Cross Gable",
        "Complex Gable",
        "Gable",
    ),
    hip_values: Tuple[str, ...] = ("Hip", "Cross Hip"),
    story_col: str = "Story_AI",
    one_story_values: Tuple[int, ...] = (1,),
    two_story_values: Tuple[int, ...] = (2,),
    garage_col: str = "Garage",
    no_garage_values: Tuple[int, ...] = (0,),
    garage_values: Tuple[int, ...] = (1,),
    occupancy_col: str = "PRIM_OCC",
    single_family_values: Tuple[str, ...] = (
        "Single Family Dwelling",
    ),
    year_col: str = "med_yr_blt",
    coast_distance_col: str = "Coast_D (miles)",
    coast_distance_to_miles: float = 1.0,
    structure_value_col: str = "val_struct",
    contents_value_col: str = "val_cont",
    building_key_col: Optional[str] = "fd_id_nsi",
    passthrough_cols: Tuple[str, ...] = (
        "is_vacant",
        "H_TEN_syn",
        "AGEP_syn",
        "H_HINCP_syn",
    ),
)

Column names and category values that map a user inventory onto archetype attributes.

The defaults reproduce the verified Eastern North Carolina call. Category values that do not appear in the listed tuples map to missing values; only the roof, story, garage, year, coast-distance and value attributes are required, while the building-type and occupancy filters are applied only when ArchetypeAssigner.drop_unmatched_occupancy is enabled.

Attributes:

Name Type Description
bldgtype_col str

Building material column.

wood_frame_values Tuple[str, ...]

Values denoting wood-frame construction.

roof_col str

Roof shape column.

gable_values Tuple[str, ...]

Values mapped to a gable roof.

hip_values Tuple[str, ...]

Values mapped to a hip roof.

story_col str

Number-of-stories column.

one_story_values Tuple[int, ...]

Values mapped to one story.

two_story_values Tuple[int, ...]

Values mapped to two stories.

garage_col str

Garage indicator column.

no_garage_values Tuple[int, ...]

Values meaning no garage.

garage_values Tuple[int, ...]

Values meaning an attached garage.

occupancy_col str

Occupancy column.

single_family_values Tuple[str, ...]

Values denoting single-family residences.

year_col str

Year-built column.

coast_distance_col str

Distance-to-coast column.

coast_distance_to_miles float

Multiplier converting the coast distance to miles.

structure_value_col str

Structure value column.

contents_value_col str

Contents value column.

building_key_col Optional[str]

Existing unique key column used as the building key when present.

passthrough_cols Tuple[str, ...]

Extra columns carried into the export when present.

Exposure Workflow#

main #

End-to-end exposure workflow: zones and STARR-compatible export.

Exposure completes the chain started by BaseExposure, ArchetypeAssigner and HazardMapper: it assigns a zone id to every building by a centroid spatial join and assembles the STARR inventory table together with the Wind_Tr / Flood_Tr hazard-ID arrays. STARR looks up wind-only and flood-only loss ratios during its own simulation with the current resistance configuration, which is why hazard IDs rather than loss ratios are exported.

Classes:

Name Description
Exposure

Complete exposure workflow with zone assignment and STARR export.

Attributes:

Name Type Description
STARR_BASE_COLUMNS List[str]

Fixed columns of the STARR Inventory.csv; the zone column is inserted after YearBuiltGroup.

UNASSIGNED_ZONE

Zone id of buildings whose centroid lies outside every zone polygon.

STARR_BASE_COLUMNS module-attribute #

STARR_BASE_COLUMNS: List[str] = [
    "building_ID",
    "t",
    "YearBuilt",
    "YearBuiltGroup",
    "M",
    "C",
    "RC",
    "RF",
    "RTW",
    "O",
    "W",
    "F",
    "structure_value",
    "contents_value",
    "home_value",
]

Fixed columns of the STARR Inventory.csv; the zone column is inserted after YearBuiltGroup.

UNASSIGNED_ZONE module-attribute #

UNASSIGNED_ZONE = -1

Zone id of buildings whose centroid lies outside every zone polygon.

Exposure dataclass #

Exposure(
    inventory_path: Optional[str] = None,
    hazard_dir: Optional[str] = None,
    hazard_file_pattern: str = "*.parquet",
    wind_col: str = "Wind",
    flood_col: str = "Flood",
    nodata_value: float = -9999.0,
    zones_path: Optional[str] = None,
    wind_speed_path: Optional[str] = None,
    flood_depth_path: Optional[str] = None,
    component_combination_path: Optional[str] = None,
    output_dir: Optional[str] = None,
    schema: InventorySchema = InventorySchema(),
    datasets_loaded: bool = False,
    coast_threshold_miles: float = 2.0,
    year_breaks: Tuple[int, int] = (1968, 1997),
    drop_unmatched_occupancy: bool = False,
    seed: Optional[int] = None,
    average_mode: str = "Nearest",
    idw_neighbors: int = 4,
    idw_power: float = 4.0,
    wind_to_mph: float = 2.23694,
    flood_to_inches: float = 39.3701,
    clip_to_hazard_bounds: bool = True,
    hazard_id_dtype: str = "float32",
    zone_id_col: Optional[str] = "i_lh740",
    drop_unassigned_zones: bool = False,
)

Bases: HazardMapper

Complete exposure workflow with zone assignment and STARR export.

Attributes:

Name Type Description
zone_id_col Optional[str]

Zone-id column of the zone layer (e.g. "i_lh740"); None skips zone assignment and omits the zone column from the export.

drop_unassigned_zones bool

When True, the export excludes buildings outside every zone, reproducing the frozen source export's valid-zone filter.

zone_ids ndarray

Zone id per clipped building, -1 when unassigned.

starr_inventory DataFrame

STARR Inventory.csv table for the clipped inventory.

Methods:

Name Description
calculate_zone_assignment

Zone id per building by centroid spatial join.

calculate_starr_inventory

STARR inventory table from the clipped inventory.

calculate_starr_export

Consistently filtered export tuple (table, wind IDs, flood IDs, event names).

save_starr_inputs

Write the export files and the intermediate inventories.

calculate_starr_export #

calculate_starr_export() -> Tuple[
    DataFrame, ndarray, ndarray, List[str]
]

Return the export tuple with the zone filter applied consistently.

This is the single place where drop_unassigned_zones acts, so the files written by save_starr_inputs and the in-memory hand-off consumed by the loss-estimation module always hold the same rows.

Outputs

None beyond the returned value.

Returns:

Type Description
DataFrame

Tuple[pd.DataFrame, np.ndarray, np.ndarray, List[str]]: The STARR inventory

ndarray

table, wind_ids, flood_ids (both (n_buildings, n_events)) and the

ndarray

event names.

calculate_starr_inventory #

calculate_starr_inventory(
    inventory: GeoDataFrame, zone_ids: ndarray
) -> DataFrame

Assemble the STARR Inventory.csv table.

Parameters:

Name Type Description Default
inventory GeoDataFrame

Clipped inventory with archetype columns and building_ID.

required
zone_ids ndarray

Zone id per building.

required
Outputs

None beyond the returned value.

Returns:

Type Description
DataFrame

pd.DataFrame: Columns ``building_ID, t, YearBuilt, YearBuiltGroup,

DataFrame

, M, C, RC, RF, RTW, O, W, F, structure_value,

DataFrame

contents_value, home_value``, the schema key column and any passthrough

DataFrame

columns when present, x, y (hazard CRS centroids), lon, lat

DataFrame

(EPSG:4326) and building_key. Row order matches the hazard-ID arrays.

calculate_zone_assignment #

calculate_zone_assignment(
    inventory: GeoDataFrame,
    zones: Optional[GeoDataFrame],
    zone_id_col: Optional[str],
) -> ndarray

Assign a zone id to every building from the polygon containing its centroid.

Parameters:

Name Type Description Default
inventory GeoDataFrame

Clipped inventory.

required
zones Optional[GeoDataFrame]

Zone layer, or None.

required
zone_id_col Optional[str]

Zone-id column of the layer.

required
Outputs

None beyond the returned value.

Returns:

Type Description
ndarray

np.ndarray: Integer zone id per building; -1 outside every zone or when no

ndarray

layer is given. A centroid inside several polygons keeps the first match.

save_starr_inputs #

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

Write the STARR hazard inputs and the intermediate inventories.

Parameters:

Name Type Description Default
output_dir Optional[str]

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

None
Outputs

Writes Inventory.csv, Wind_Tr.npy, Flood_Tr.npy, Hurricane_name.npy, HazardInput_metadata.txt, archetype_inventory.parquet and clipped_inventory.parquet.

Returns:

Type Description
Dict[str, str]

Dict[str, str]: Written paths keyed by inventory_csv, wind_ids,

Dict[str, str]

flood_ids, event_names, metadata, archetype_inventory and

Dict[str, str]

clipped_inventory.

Hazard Mapping#

hazard_mapping #

Hazard-to-building mapping and hazard-ID transformation.

Per-event wind speeds (m/s) and flood depths (m) at hazard control points are assigned to building centroids with a nearest-neighbour or inverse-distance scheme, converted to mph and inches, and interpolated onto the package's discrete hazard IDs (WindSpeed.json and FloodDepth.json). The resulting Wind_Tr and Flood_Tr values are continuous, 1-based IDs; how they are rounded onto lookup-table bins is decided later by the loss-estimation module.

The module also exposes grid helpers used by the Eastern North Carolina figure notebook: cell indexing on the 1 km control-point grid and probability-weighted hazard summaries.

Classes:

Name Description
HazardMapper

Assign per-event hazard intensities to buildings and transform them to hazard IDs.

Functions:

Name Description
calculate_cell_index

Bin coordinates onto the control-point grid.

calculate_grid_mask

Build the occupancy mask of control points on the grid.

calculate_probability_weighted_intensity

Probability-weighted mean hazard intensity per control point.

Attributes:

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

Supported hazard averaging modes.

BUILDING_ID_COLUMN

1-based positional id of the clipped inventory, as used by the STARR export.

AVERAGE_MODES module-attribute #

AVERAGE_MODES: Tuple[str, ...] = ('Nearest', 'Inverse_d4')

Supported hazard averaging modes.

BUILDING_ID_COLUMN module-attribute #

BUILDING_ID_COLUMN = 'building_ID'

1-based positional id of the clipped inventory, as used by the STARR export.

HazardMapper dataclass #

HazardMapper(
    inventory_path: Optional[str] = None,
    hazard_dir: Optional[str] = None,
    hazard_file_pattern: str = "*.parquet",
    wind_col: str = "Wind",
    flood_col: str = "Flood",
    nodata_value: float = -9999.0,
    zones_path: Optional[str] = None,
    wind_speed_path: Optional[str] = None,
    flood_depth_path: Optional[str] = None,
    component_combination_path: Optional[str] = None,
    output_dir: Optional[str] = None,
    schema: InventorySchema = InventorySchema(),
    datasets_loaded: bool = False,
    coast_threshold_miles: float = 2.0,
    year_breaks: Tuple[int, int] = (1968, 1997),
    drop_unmatched_occupancy: bool = False,
    seed: Optional[int] = None,
    average_mode: str = "Nearest",
    idw_neighbors: int = 4,
    idw_power: float = 4.0,
    wind_to_mph: float = 2.23694,
    flood_to_inches: float = 39.3701,
    clip_to_hazard_bounds: bool = True,
    hazard_id_dtype: str = "float32",
)

Bases: ArchetypeAssigner

Assign per-event hazard intensities to buildings and transform them to hazard IDs.

Attributes:

Name Type Description
average_mode str

"Nearest" (default, the verified run) or "Inverse_d4".

idw_neighbors int

Neighbours used by inverse-distance weighting.

idw_power float

Exponent of the inverse-distance weights.

wind_to_mph float

Factor from the hazard wind unit (m/s) to mph.

flood_to_inches float

Factor from the hazard flood unit (m) to inches.

clip_to_hazard_bounds bool

Drop buildings whose centroid lies outside the control-point bounding box.

hazard_id_dtype str

Storage dtype of the hazard-ID arrays.

clipped_inventory GeoDataFrame

Archetype inventory in the hazard CRS with building_ID.

neighbor_index ndarray

Control-point indices per building, shape (n_buildings, k).

neighbor_distance ndarray

Distances to those control points, shape (n_buildings, k).

wind_ids ndarray

Continuous wind IDs, shape (n_buildings, n_events).

flood_ids ndarray

Continuous flood IDs, shape (n_buildings, n_events).

Methods:

Name Description
calculate_clipped_inventory

Reproject and clip the archetype inventory to the hazard grid.

calculate_neighbor_match

Nearest control points per building.

calculate_event_intensity

Per-building intensity for one event.

calculate_hazard_id

Physical intensity to continuous hazard ID.

calculate_hazard_ids

Wind and flood IDs for all events.

save_hazard_ids

Write Wind_Tr.npy, Flood_Tr.npy and Hurricane_name.npy.

calculate_clipped_inventory #

calculate_clipped_inventory(
    inventory: GeoDataFrame,
) -> GeoDataFrame

Reproject the inventory to the hazard CRS and clip it to the control-point bounding box.

Parameters:

Name Type Description Default
inventory GeoDataFrame

Archetype inventory (any CRS).

required
Outputs

None beyond the returned value.

Returns:

Type Description
GeoDataFrame

gpd.GeoDataFrame: Buildings whose centroid lies within the hazard bounds

GeoDataFrame

(all buildings when clip_to_hazard_bounds is False), re-indexed

GeoDataFrame

from zero, with a 1-based building_ID column.

calculate_event_intensity #

calculate_event_intensity(
    values: ndarray,
    neighbor_index: ndarray,
    neighbor_distance: ndarray,
    mode: Optional[str] = None,
    power: Optional[float] = None,
) -> ndarray

Assign one event's control-point intensities to buildings.

Missing values and the nodata sentinel are set to zero before averaging, as in the verified scripts. "Nearest" takes the closest control point; "Inverse_d4" weights the neighbours by distance ** -power with zero distances clamped to a nanometre.

Parameters:

Name Type Description Default
values ndarray

Intensities at the control points, shape (n_points,).

required
neighbor_index ndarray

Neighbour indices from calculate_neighbor_match.

required
neighbor_distance ndarray

Neighbour distances from calculate_neighbor_match.

required
mode Optional[str]

Averaging mode; defaults to average_mode.

None
power Optional[float]

Inverse-distance exponent; defaults to idw_power.

None
Outputs

None beyond the returned value.

Returns:

Type Description
ndarray

np.ndarray: One intensity per building.

Raises:

Type Description
ValueError

If the mode is not supported.

calculate_hazard_id #

calculate_hazard_id(
    values: ndarray, table: ndarray, unit_factor: float
) -> ndarray

Convert physical intensities to continuous hazard IDs.

The intensity is multiplied by unit_factor (to mph or inches) and interpolated linearly onto the ID column of the table using its physical-unit column as knots; values beyond the knots clamp to the first or last ID and missing values become ID 1.

Parameters:

Name Type Description Default
values ndarray

Intensities in the hazard layer unit (m/s or m).

required
table ndarray

WindSpeed.json or FloodDepth.json table (id, physical unit, SI unit).

required
unit_factor float

Multiplier from the hazard layer unit to the table's physical unit.

required
Outputs

None beyond the returned value.

Returns:

Type Description
ndarray

np.ndarray: Continuous 1-based IDs in hazard_id_dtype.

calculate_hazard_ids #

calculate_hazard_ids(
    neighbor_index: ndarray,
    neighbor_distance: ndarray,
    hazard_wind: ndarray,
    hazard_flood: ndarray,
) -> Tuple[ndarray, ndarray]

Compute wind and flood hazard IDs for every building and event.

Parameters:

Name Type Description Default
neighbor_index ndarray

Neighbour indices, shape (n_buildings, k).

required
neighbor_distance ndarray

Neighbour distances, shape (n_buildings, k).

required
hazard_wind ndarray

Raw wind values, shape (n_events, n_points).

required
hazard_flood ndarray

Raw flood values, shape (n_events, n_points).

required
Outputs

None beyond the returned value.

Returns:

Type Description
ndarray

Tuple[np.ndarray, np.ndarray]: wind_ids and flood_ids of shape

ndarray

(n_buildings, n_events); column j is event j of event_names.

calculate_neighbor_match #

calculate_neighbor_match(
    building_xy: ndarray, hazard_xy: ndarray, k: int
) -> Tuple[ndarray, ndarray]

Find the k nearest control points of every building.

Parameters:

Name Type Description Default
building_xy ndarray

Building centroids, shape (n_buildings, 2).

required
hazard_xy ndarray

Control-point coordinates, shape (n_points, 2).

required
k int

Number of neighbours.

required
Outputs

None beyond the returned value.

Returns:

Type Description
ndarray

Tuple[np.ndarray, np.ndarray]: Neighbour indices and distances, each of

ndarray

shape (n_buildings, k), nearest first.

save_hazard_ids #

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

Write the hazard-ID arrays and event names.

Parameters:

Name Type Description Default
output_dir Optional[str]

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

None
Outputs

Writes Wind_Tr.npy, Flood_Tr.npy ((n_buildings, n_events)) and Hurricane_name.npy (unicode event names).

Returns:

Type Description
Dict[str, str]

Dict[str, str]: Written paths keyed by wind_ids, flood_ids and event_names.

calculate_cell_index #

calculate_cell_index(
    x: ndarray,
    y: ndarray,
    origin_x: float = GRID_ORIGIN[0],
    origin_y: float = GRID_ORIGIN[1],
    cell_size: float = GRID_CELL_SIZE,
    method: str = "nearest",
) -> Tuple[ndarray, ndarray]

Bin coordinates onto the control-point grid.

Parameters:

Name Type Description Default
x ndarray

X coordinates in the grid CRS.

required
y ndarray

Y coordinates in the grid CRS.

required
origin_x float

X of the lower-left control point.

GRID_ORIGIN[0]
origin_y float

Y of the lower-left control point.

GRID_ORIGIN[1]
cell_size float

Grid spacing.

GRID_CELL_SIZE
method str

"nearest" assigns the cell whose centre (control point) is closest, which mirrors nearest-neighbour hazard mapping; "corner" assigns the cell whose lower-left corner is the nearest control point at or below the coordinate.

'nearest'
Outputs

None beyond the returned value.

Returns:

Type Description
Tuple[ndarray, ndarray]

Tuple[np.ndarray, np.ndarray]: Integer column (ix) and row (iy) indices.

Raises:

Type Description
ValueError

If method is not "nearest" or "corner".

calculate_grid_mask #

calculate_grid_mask(
    x: ndarray,
    y: ndarray,
    origin_x: float = GRID_ORIGIN[0],
    origin_y: float = GRID_ORIGIN[1],
    cell_size: float = GRID_CELL_SIZE,
) -> Tuple[ndarray, Tuple[float, float, float, float]]

Build the occupancy mask of control points on the grid.

Parameters:

Name Type Description Default
x ndarray

Control-point x coordinates; they must sit on the grid.

required
y ndarray

Control-point y coordinates.

required
origin_x float

X of the lower-left control point.

GRID_ORIGIN[0]
origin_y float

Y of the lower-left control point.

GRID_ORIGIN[1]
cell_size float

Grid spacing.

GRID_CELL_SIZE
Outputs

None beyond the returned value.

Returns:

Type Description
ndarray

Tuple[np.ndarray, Tuple[float, float, float, float]]: Boolean mask indexed

Tuple[float, float, float, float]

[iy, ix] and the raster extent (xmin, xmax, ymin, ymax) for

Tuple[ndarray, Tuple[float, float, float, float]]

imshow(..., origin="lower") with cells centred on the control points.

Raises:

Type Description
ValueError

If any point is further than a millionth of a cell from a grid node.

calculate_probability_weighted_intensity #

calculate_probability_weighted_intensity(
    values: ndarray,
    probabilities: ndarray,
    conditional_on_positive: bool = False,
) -> ndarray

Probability-weighted mean hazard intensity per control point.

Parameters:

Name Type Description Default
values ndarray

Intensities of shape (n_points, n_events).

required
probabilities ndarray

Annual event probabilities of shape (n_events,).

required
conditional_on_positive bool

When True, average only over events with a positive intensity at each point (flood depth conditional on inundation); points never affected are NaN.

False
Outputs

None beyond the returned value.

Returns:

Type Description
ndarray

np.ndarray: Weighted mean per control point, shape (n_points,).

Synthetic Test Data#

synthetic #

Realistic synthetic exposure inputs for tests and example notebooks.

The generators mirror the schema, category labels, value ranges, coordinate reference system and 1 km hazard grid of the Eastern North Carolina source data (the 2,000-row demo inventory, the Old97 hazard control points and the LEAPHI zone layer) without shipping any of that data. Every draw goes through :class:cheersafe.tools.Sampling, so a given seed always reproduces the same case.

Classes:

Name Description
SyntheticExposureData

Generators for small, realistic exposure test cases.

Attributes:

Name Type Description
CELL_ID_OFFSET int

Offset of the source cell_ID numbering.

CELL_ID_STRIDE int

Column stride of the source cell_ID numbering (cell_ID = ix * 350 + iy + 149103).

DEMO_ROOF_LABELS Tuple[str, ...]

Roof-shape labels found in the demo inventory.

DEMO_ROOF_WEIGHTS Tuple[float, ...]

Gable-heavy roof mix, matching the dominance of gable archetypes in the full inventory.

EDGE_CASE_KEY_START int

fd_id_nsi values at or above this mark the appended edge-case rows.

GRID_CELL_SIZE float

Spacing of the hazard control points in metres.

GRID_CRS str

Coordinate reference system of the source hazard, inventory and zone layers.

GRID_ORIGIN Tuple[float, float]

Lower-left control point of the Eastern North Carolina 1 km hazard grid (EPSG:5070).

NODATA_VALUE float

Sentinel used for missing hazard values in the source control-point layers.

CELL_ID_OFFSET module-attribute #

CELL_ID_OFFSET: int = 149103

Offset of the source cell_ID numbering.

CELL_ID_STRIDE module-attribute #

CELL_ID_STRIDE: int = 350

Column stride of the source cell_ID numbering (cell_ID = ix * 350 + iy + 149103).

DEMO_ROOF_LABELS module-attribute #

DEMO_ROOF_LABELS: Tuple[str, ...] = (
    "Cross Gable",
    "Complex Gable",
    "Gable",
    "Hip",
    "Cross Hip",
)

Roof-shape labels found in the demo inventory.

DEMO_ROOF_WEIGHTS module-attribute #

DEMO_ROOF_WEIGHTS: Tuple[float, ...] = (
    0.25,
    0.2,
    0.3,
    0.15,
    0.1,
)

Gable-heavy roof mix, matching the dominance of gable archetypes in the full inventory.

EDGE_CASE_KEY_START module-attribute #

EDGE_CASE_KEY_START: int = 900000

fd_id_nsi values at or above this mark the appended edge-case rows.

GRID_CELL_SIZE module-attribute #

GRID_CELL_SIZE: float = 1000.0

Spacing of the hazard control points in metres.

GRID_CRS module-attribute #

GRID_CRS: str = 'EPSG:5070'

Coordinate reference system of the source hazard, inventory and zone layers.

GRID_ORIGIN module-attribute #

GRID_ORIGIN: Tuple[float, float] = (
    1479654.52465404,
    1345256.36347185,
)

Lower-left control point of the Eastern North Carolina 1 km hazard grid (EPSG:5070).

NODATA_VALUE module-attribute #

NODATA_VALUE: float = -9999.0

Sentinel used for missing hazard values in the source control-point layers.

SyntheticExposureData #

Generators for small, realistic exposure test cases.

The static methods return in-memory GeoDataFrames and arrays whose columns, labels, ranges, CRS and grid geometry follow the Eastern North Carolina source data. Tests and notebooks use them so that no external data is required.

Methods:

Name Description
make_inventory

Building inventory in the demo schema with optional edge-case rows.

make_hazard_events

Per-event hazard control-point layers on the 1 km grid.

make_zones

Two nested LEAPHI-style zone polygons.

make_damage_library

Damage-state probability tensors for selected (m, c) pairs.

make_hurricane_probabilities

Annual event probabilities in Hurricane_Prob layout.

save_inputs

Write a complete Inputs tree for a synthetic case.

make_damage_library staticmethod #

make_damage_library(
    keys: Sequence[Tuple[int, int]] = (
        (1, 1),
        (2, 101),
        (8, 192),
    ),
    n_wind: int = 25,
    n_flood: int = 136,
    n_damage_states: int = 50,
    seed: Optional[int] = None,
    unnormalized_rows: int = 1,
) -> Dict[Tuple[int, int], ndarray]

Generate damage-state probability tensors for selected (m, c) pairs.

Each tensor has shape (n_wind, n_flood, n_damage_states). Rows are discretized bell-shaped distributions whose centre rises monotonically with wind and flood, the zero-hazard row is a point mass on the first damage state, and a configurable number of rows is scaled by 0.9 so consumers can exercise their non-normalized-row warning.

Parameters:

Name Type Description Default
keys Sequence[Tuple[int, int]]

(m, c) pairs to generate.

((1, 1), (2, 101), (8, 192))
n_wind int

Number of wind IDs.

25
n_flood int

Number of flood IDs.

136
n_damage_states int

Number of damage states.

50
seed Optional[int]

Seed for the per-key random streams.

None
unnormalized_rows int

Number of rows whose probabilities are scaled by 0.9, assigned to the keys in order starting from the highest hazard row.

1
Outputs

None beyond the returned value.

Returns:

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

Dict[Tuple[int, int], np.ndarray]: Float32 probability tensors keyed by (m, c).

make_hazard_events staticmethod #

make_hazard_events(
    event_names: Sequence[str] = ("h1", "h2", "h10"),
    nx: int = 3,
    ny: int = 3,
    seed: Optional[int] = None,
    origin: Tuple[float, float] = GRID_ORIGIN,
    crs: str = GRID_CRS,
    nodata_cells: Optional[Dict[str, Iterable[int]]] = None,
) -> Dict[str, GeoDataFrame]

Generate per-event hazard control-point layers on the source grid.

Control points sit exactly on the 1 km grid, share geometry and order across events, and carry Wind in m/s and Flood in metres. The first point of every event is dry so a zero-flood case always exists.

Parameters:

Name Type Description Default
event_names Sequence[str]

Event names, e.g. ("h1", "h2", "h10").

('h1', 'h2', 'h10')
nx int

Number of control points along x.

3
ny int

Number of control points along y.

3
seed Optional[int]

Seed for the derived random streams.

None
origin Tuple[float, float]

Lower-left control point of the grid.

GRID_ORIGIN
crs str

Coordinate reference system of the layers.

GRID_CRS
nodata_cells Optional[Dict[str, Iterable[int]]]

Mapping of event name to row indices whose Wind and Flood are set to NODATA_VALUE.

None
Outputs

None beyond the returned value.

Returns:

Type Description
Dict[str, GeoDataFrame]

Dict[str, gpd.GeoDataFrame]: Event name to layer with columns

Dict[str, GeoDataFrame]

cell_ID, x, y, Wind, Flood, geometry, in the given order.

make_hurricane_probabilities staticmethod #

make_hurricane_probabilities(
    n_events: int = 3,
    seed: Optional[int] = None,
    annual_rate: float = 0.32,
) -> ndarray

Generate annual event probabilities in the Hurricane_Prob layout.

Parameters:

Name Type Description Default
n_events int

Number of events.

3
seed Optional[int]

Seed for the derived random stream.

None
annual_rate float

Sum of the probabilities, mirroring the source catalogue's total annual rate of roughly 0.32 per year.

0.32
Outputs

None beyond the returned value.

Returns:

Type Description
ndarray

np.ndarray: Array of shape (n_events, 2) with 1-based event ids in

ndarray

column 0 and probabilities in column 1.

make_inventory staticmethod #

make_inventory(
    n: int = 40,
    seed: Optional[int] = None,
    crs: str = GRID_CRS,
    origin: Tuple[float, float] = GRID_ORIGIN,
    extent_cells: Tuple[int, int] = (3, 3),
    include_edge_cases: bool = True,
    spread_full_window: bool = False,
) -> GeoDataFrame

Generate a building inventory in the demo-inventory schema.

Regular rows are wood-frame single-family dwellings with 10 m square footprints placed inside the hazard control-point bounding box and, by default, inside the zones returned by :meth:make_zones (which caps the x extent at 1.5 km); spread_full_window places them across the whole control-point window instead, for map-style examples. Year built spans 1950-2020 so all three construction periods occur, and coastal distance spans both sides of the 2-mile threshold. Contents value is half the structure value, as in the frozen source export.

Parameters:

Name Type Description Default
n int

Number of regular buildings.

40
seed Optional[int]

Seed for the derived random stream; None uses Config.RANDOM_SEED.

None
crs str

Coordinate reference system of the returned layer.

GRID_CRS
origin Tuple[float, float]

Lower-left control point of the hazard grid.

GRID_ORIGIN
extent_cells Tuple[int, int]

Number of control points along x and y.

(3, 3)
spread_full_window bool

Spread regular buildings over the full control-point window rather than the zone-safe 1.5 km strip.

False
include_edge_cases bool

Append five flagged rows exercising missing roof shape, a non-wood building type, a non-single-family occupancy, a centroid outside the hazard bounding box and a centroid outside all zones. Their fd_id_nsi is at least EDGE_CASE_KEY_START.

True
Outputs

None beyond the returned value.

Returns:

Type Description
GeoDataFrame

gpd.GeoDataFrame: Inventory with columns ``bldgtype, roof_shape_1,

GeoDataFrame

Story_AI, Garage, PRIM_OCC, med_yr_blt, Coast_D (miles), val_struct,

GeoDataFrame

val_cont, fd_id_nsi, is_vacant, H_TEN_syn, geometry``.

make_zones staticmethod #

make_zones(
    origin: Tuple[float, float] = GRID_ORIGIN,
    extent_cells: Tuple[int, int] = (3, 3),
    crs: str = GRID_CRS,
) -> GeoDataFrame

Generate two LEAPHI-style zone polygons that nest into one coarser zone.

Zone 1 covers the southern band of the grid window and zone 2 the north-western part, leaving the north-eastern corner unassigned so that a building can fall inside the hazard bounding box but outside all zones.

Parameters:

Name Type Description Default
origin Tuple[float, float]

Lower-left control point of the grid.

GRID_ORIGIN
extent_cells Tuple[int, int]

Number of control points along x and y.

(3, 3)
crs str

Coordinate reference system of the layer.

GRID_CRS
Outputs

None beyond the returned value.

Returns:

Type Description
GeoDataFrame

gpd.GeoDataFrame: Zones with columns ``COUNTYFP00, zone, i_lh503,

GeoDataFrame

i_lh1509, i_lh708, i_lh740, geometry;i_lh740is[1, 2]`` and

GeoDataFrame

both rows share i_lh503 == 1.

save_inputs staticmethod #

save_inputs(
    directory: str,
    inventory: GeoDataFrame,
    hazard_events: Dict[str, GeoDataFrame],
    zones: Optional[GeoDataFrame],
    hurricane_probabilities: ndarray,
    wind_speeds: ndarray,
    flood_depths: ndarray,
    damage_states: ndarray,
    component_combinations: ndarray,
    damage_library: Optional[
        Dict[Tuple[int, int], ndarray]
    ] = None,
    inventory_name: str = "Inventory.parquet",
    zones_name: str = "zones.gpkg",
) -> Dict[str, str]

Write a complete synthetic Inputs tree.

Parameters:

Name Type Description Default
directory str

Root directory; files are written under <directory>/Inputs.

required
inventory GeoDataFrame

Inventory layer from :meth:make_inventory.

required
hazard_events Dict[str, GeoDataFrame]

Event layers from :meth:make_hazard_events.

required
zones Optional[GeoDataFrame]

Zone layer from :meth:make_zones, or None to skip.

required
hurricane_probabilities ndarray

Array from :meth:make_hurricane_probabilities.

required
wind_speeds ndarray

Canonical WindSpeed.json table.

required
flood_depths ndarray

Canonical FloodDepth.json table.

required
damage_states ndarray

Canonical DamageState.json table.

required
component_combinations ndarray

Canonical ComponentCombination_All.json table.

required
damage_library Optional[Dict[Tuple[int, int], ndarray]]

Tensors from :meth:make_damage_library, pickled when given.

None
inventory_name str

File name of the inventory layer (GeoParquet).

'Inventory.parquet'
zones_name str

File name of the zone layer (GeoPackage or shapefile suffix).

'zones.gpkg'
Outputs

Writes the inventory, one parquet file per hazard event under Inputs/Hazards, the zone layer, the four canonical JSON tables, Hurricane_ProbWindFlood.json and optionally damage_library.pkl.

Returns:

Type Description
Dict[str, str]

Dict[str, str]: Written paths keyed by inventory, hazard_dir,

Dict[str, str]

zones, wind_speeds, flood_depths, damage_states,

Dict[str, str]

component_combinations, hurricane_prob and damage_library.