snail package¶
snail - the spatial networks impact assessment library
- class snail.DirectDamageResult(metadata: dict[str, Any], quantiles: DataFrame | None, ead_quantiles: DataFrame | None = None, total_quantiles: DataFrame | None = None, total_ead_quantiles: DataFrame | None = None)[source]¶
Bases:
objectSummarised sampled direct damages and their reproducibility metadata.
metadatarecords the seed and model inputs.quantilesis a long-form frame with one row per asset, scenario and intensity case, when requested.ead_quantilescontains one row per asset and scenario when requested. Quantile columns are namedq_05,q_50, etc.When asset aggregation is requested,
total_quantilesandtotal_ead_quantilessummarise sums across assets within each scenario. All raw samples are discarded after summarising.- Attributes:
- ead_quantiles
- total_ead_quantiles
- total_quantiles
- ead_quantiles: DataFrame | None = None¶
- metadata: dict[str, Any]¶
- quantiles: DataFrame | None¶
- total_ead_quantiles: DataFrame | None = None¶
- total_quantiles: DataFrame | None = None¶
- snail.calculate_direct_damages(splits: DataFrame, *, asset_id: str, quantity: str, intensity_columns: Mapping[Any, str], hazard_cv: float | Mapping[Any, float] = 0.0, curves: Mapping[str, DamageCurve], curve_weights: Mapping[str, float], eta_sd: float = 0.0, cost_mean: float | str, cost_asset_cv: float = 0.0, cost_systemic_cv: float = 0.0, n_samples: int = 1000, quantiles: Sequence[float] | None = None, return_periods: Mapping[Any, float] | None = None, ead_quantiles: Sequence[float] | None = None, seed: int | None = None, scenario: str | None = None, aggregate_assets: bool = False) DirectDamageResult[source]¶
Sample and summarise direct damages for pre-split assets.
Each row in
splitsis one asset split.intensity_columnsmaps intensity-case labels (such as named events or return-periods) to hazard intensity columns. Each simulation selects a weighted damage curve and draws a systemic cost multiplier shared across all assets and scenarios. Each asset/scenario group then receives independent hazard, damage-noise and local cost draws, shared across its splits and intensity cases. Hazard and cost values are clamped at zero, damage fractions are clipped to [0, 1], and asset splits damages are summed for each intensity case. The result returns requested quantiles and run metadata. Samples can optionally be accumulated across assets to calculate total quantiles.In the equations below,
Zdenotes a draw from a standard normal distribution with mean 0 and standard deviation 1.- Parameters:
- splitspandas.DataFrame
Pre-split asset data, with one row per split. Each split’s quantity and hazard intensities are used to calculate and aggregate its damage.
- asset_idstr
Name of the column identifying the parent asset for each split.
- quantitystr
Name of the column giving each split’s non-negative quantity: count (normally 1) for points, length for lines, or area for polygons. Units must match the per-unit rehabilitation cost. Each asset has one geometry type, but different assets may use different quantity units. Geometry measurement and unit consistency are the caller’s responsibility.
- intensity_columnsMapping[Any, str]
Mapping from an intensity-case label to the column containing its central hazard intensity for each segment. Labels identify the cases in the returned summaries and may represent any kind of event or return-period maps, for example.
- hazard_cvfloat or Mapping[Any, float], default 0.0
Coefficient of variation of hazard intensity before clamping. Supply one value for all cases or a mapping from each intensity-case label to its value; the mapping keys must exactly match
intensity_columns. A case’s sampled intensity ismax(0, mean * (1 + hazard_cv * Z)).- curvesMapping[str, DamageCurve]
Damage curves available for sampling, keyed by identifiers that match the keys in
curve_weights.- curve_weightsMapping[str, float]
Non-negative relative selection weights for the curves. Weights are normalised before sampling and must have a positive total.
- eta_sdfloat, default 0.0
Standard deviation of the normal damage-noise term. The sampled damage fraction is multiplied by
exp(eta_sd * Z - eta_sd**2 / 2)before clipping to [0, 1].- cost_meanfloat or str
Baseline rehabilitation cost per unit of quantity. Give a non-negative number to use the same mean for all assets, or a column name to read an asset-specific mean. Column values must be constant across that asset’s splits within each scenario. For a point with quantity 1, this is the whole-asset cost; for lines and polygons, value is assumed uniformly distributed per unit length or area.
- cost_asset_cvfloat, default 0.0
Coefficient of variation of the asset normal cost factor before clamping. Sampled unit cost is
max(0, systemic_cost * (1 + cost_asset_cv * Z)), with an independent draw for each asset/scenario group, shared across its splits and intensity cases. Zero disables asset-specific cost variation.- cost_systemic_cvfloat, default 0.0
Finite, non-negative coefficient of variation of the systemic normal cost factor before clamping. Each simulation uses
systemic_cost = cost_mean * max(0, 1 + cost_systemic_cv * Z_system). The same dimensionless multiplier applies to every asset/scenario baseline, including assets with different quantity units. Zero disables systemic cost variation.- n_samplesint, default 1000
Number of uncertainty realisations to draw for each asset or asset/scenario group.
- quantilesSequence[float] or None, default None
Quantiles to report for each asset and intensity case. Values must be in [0, 1]; output columns use percentile names such as
q_05. Set to None to omit per-intensity quantiles.- return_periodsMapping[Any, float] or None, default None
Mapping from intensity-case labels to return periods in years. Supply this together with
ead_quantilesto request expected annual damage (EAD) quantiles. Keys must exactly matchintensity_columns. Note that return periods RP are interpreted as the reciprocal of annual exceedance probability (AEP), soAEP = 1 / RP. If the hazard data instead defines return period R as the mean recurrence interval of events exceeding a theshold, it should be converted to1 / AEP. For example, assuming a Poisson process for events, R = 2 years corresponds to AEP ~0.393 or RP ~2.54. This distinction would affect expected annual damage (EAD) calculations.- ead_quantilesSequence[float] or None, default None
Quantiles to report for each asset/scenario EAD distribution. Requires
return_periods. Values use the same validation and column naming asquantiles.- seedint or None, default None
Seed for random number generator. Set a seed to make the sampled summaries reproducible for the same inputs and row order.
- scenariostr or None, default None
Optional column identifying scenarios. If supplied, aggregation and local random draws are grouped by both asset and scenario; otherwise they are grouped by asset alone. Systemic draws span all scenarios.
- aggregate_assetsbool, default False
Sum matching simulation samples across assets, separately within each scenario. Return
total_quantilesatquantileswhen supplied. When EAD is requested, integrate the summed event samples and returntotal_ead_quantilesatead_quantiles. Total summaries includen_assetsandn_splits.
- Returns:
- DirectDamageResult
quantilescontains one row per asset, scenario (if supplied), and intensity case when requested.ead_quantilescontains one row per asset/scenario group when requested. Both haven_splitsand one column per requested quantile.metadatarecords the seed and model configuration. Whenaggregate_assetsis True, thetotal_*fields contain corresponding total quantile summaries; otherwise these fields are None. Total event summaries use one row per scenario and intensity case; total EAD summaries use one row per scenario.
- Raises:
- KeyError
If a required input column is missing.
- ValueError
If parameters are invalid, numeric inputs are missing or non-finite, or a column-based cost mean varies within an asset/scenario group.
Notes
Curve choices and systemic cost multipliers are shared across the entire call at each simulation index. Hazard, damage noise and local cost draws are independent between asset/scenario groups and shared across all splits and intensity cases within each group. Both cost stages are clamped at zero; the final cost mean may therefore differ from the input baseline.
Global damage curve choices are made first, then systemic cost draws, then local draws for each group. Metadata records inputs and draw_scopes (“call” or “asset_scenario”).
Asset aggregation sums corresponding simulation indices before calculating total quantiles. This preserves shared systemic uncertainty and local variation. Total EAD integrates the summed event damages; the fixed integration weights make this equivalent to summing asset EAD samples.
If EAD is requested, each sample’s damage is assumed linear in the natural logarithm of annual exceedance probability between supplied events. These intervals are integrated analytically with respect to probability. We peform constant extrapolation in damage from the lowest supplied probability to zero probability. There is no extrapolation beyond the highest supplied probability. Quantiles are calculated from the integrated samples.
- snail.overlay_raster(features: GeoDataFrame, raster, bands: list[int] | None = None, column: str | None = None, experimental: bool = False, lazy: bool = False) GeoDataFrame[source]¶
Split features along a raster grid and attribute cell values
- Parameters:
- featuresgeopandas.GeoDataFrame
Point, LineString or Polygon features (multi-geometries are exploded)
- rasterstr | pathlib.Path | rasterio dataset | xarray.DataArray
Raster file path, open rasterio dataset or DataArray, defining the splitting grid and providing cell values
- bandslist of int, optional
Band numbers to attribute (default: all bands)
- columnstr, optional
Output column name (default: raster filename stem). Values from a single band are attributed under this name directly, multiple bands under “{column}_band_{n}” for each band n.
- experimentalbool
Use the experimental (faster, less robust) polygon splitting routine
- lazybool
Read raster bands lazily via xarray/dask rather than into memory. Only applies when raster is a file path.
- Returns:
- geopandas.GeoDataFrame
Split features in the CRS of the input features, with grid cell indices in columns “index_i” and “index_j” and one column of raster values per band. Features that fall outside the raster are attributed NaN. If the features and raster CRS differ, features are reprojected to the raster CRS for splitting and lookup, then reprojected back.
- snail.overlay_rasters(features: GeoDataFrame, rasters: list | DataFrame, experimental: bool = False, lazy: bool = False) GeoDataFrame[source]¶
Split features along multiple raster grids and attribute cell values
All features are intersected with all rasters: each raster band contributes one column of values to the output.
- Parameters:
- featuresgeopandas.GeoDataFrame
Point, LineString or Polygon features (multi-geometries are exploded)
- rasterslist | pandas.DataFrame
Either a sequence of raster file paths or open rasterio datasets, or a DataFrame with columns:
“path” (required): file path or open rasterio dataset
“bands” (optional): band numbers to attribute, as an int, a comma-separated string (“1,2,3”), or a list/tuple of ints - defaults to all bands
“key” (optional): output column name - defaults to the raster filename stem
- experimentalbool
Use the experimental (faster, less robust) polygon splitting routine
- lazybool
Read raster bands lazily via xarray/dask rather than into memory
- Returns:
- geopandas.GeoDataFrame
Split features in the CRS of the input features, with cell indices in columns “i_{n}”, “j_{n}” for each distinct grid n, and one column of raster values per raster band, named by raster key (with a “_band_{n}” suffix for each band of a multi-band raster)
- snail.split_features(features: GeoDataFrame, grid: GridDefinition, experimental: bool = False) GeoDataFrame[source]¶
Split point, linestring or polygon features along a grid
Features are implicitly reprojected to the grid CRS for splitting and indexing, then returned in their original CRS. If either the features or the grid have no CRS defined, they are assumed to share the same CRS.
- Parameters:
- featuresgeopandas.GeoDataFrame
Point, LineString or Polygon features (multi-geometries are exploded)
- gridGridDefinition
Grid to split features along
- experimentalbool
Use the experimental (faster, less robust) polygon splitting routine
- Returns:
- geopandas.GeoDataFrame
Split features with grid cell indices in columns “index_i” and “index_j” (set to -1 for features outside the grid)
Subpackages¶
Submodules¶
snail.cli module¶
snail.damage_library module¶
Utilities to access packaged damage curve data.
The library distributes a curated subset of the
Nirandjan et al. (2023) Physical Vulnerability Database. The upstream
work is licensed under CC-BY 4.0; see snail/data/damage_curves for the
packaged metadata and curve samples.
The helper functions defined here make it easy to enumerate available
curves, filter by hazard or infrastructure attributes, and instantiate
PiecewiseLinearDamageCurve objects ready for use in damage modelling.
- class snail.damage_library.DamageCurveMetadata(curve_id: str, hazard_type: str, hazard_name: str, sector: str, sheet_name: str, intensity_metric: str, intensity_axis: str, intensity_unit: str | None, exposed_element: str, additional_characteristics: str | None, curve_type: str | None, curve_characteristics: str | None, damage_states: str | None, cost_feature: str | None, uncertainty_range: str | None, derivation_methodology: str | None, geographical_application: str | None, readily_available: str | None, source: str, source_details: str | None, original_id: str | None)[source]¶
Bases:
objectMetadata describing a packaged damage curve.
- additional_characteristics: str | None¶
- cost_feature: str | None¶
- curve_characteristics: str | None¶
- curve_id: str¶
- curve_type: str | None¶
- damage_states: str | None¶
- derivation_methodology: str | None¶
- exposed_element: str¶
- geographical_application: str | None¶
- hazard_name: str¶
- hazard_type: str¶
- intensity_axis: str¶
- intensity_metric: str¶
- intensity_unit: str | None¶
- original_id: str | None¶
- readily_available: str | None¶
- sector: str¶
- sheet_name: str¶
- source: str¶
- source_details: str | None¶
- uncertainty_range: str | None¶
- snail.damage_library.available_curves(hazard: str | None = None, sector: str | None = None, exposed_element: str | None = None, curve_type: str | None = None) DataFrame[source]¶
Return metadata for available curves, with optional filters.
- snail.damage_library.get_metadata(curve_id: str) DamageCurveMetadata[source]¶
Return the metadata record for a specific curve.
snail.damages module¶
Damage assessment
- class snail.damages.DamageCurve[source]¶
Bases:
ABCA damage curve
Methods
Evaluate damage fraction for exposure to a given hazard intensity
- class snail.damages.DirectDamageResult(metadata: dict[str, Any], quantiles: DataFrame | None, ead_quantiles: DataFrame | None = None, total_quantiles: DataFrame | None = None, total_ead_quantiles: DataFrame | None = None)[source]¶
Bases:
objectSummarised sampled direct damages and their reproducibility metadata.
metadatarecords the seed and model inputs.quantilesis a long-form frame with one row per asset, scenario and intensity case, when requested.ead_quantilescontains one row per asset and scenario when requested. Quantile columns are namedq_05,q_50, etc.When asset aggregation is requested,
total_quantilesandtotal_ead_quantilessummarise sums across assets within each scenario. All raw samples are discarded after summarising.- Attributes:
- ead_quantiles
- total_ead_quantiles
- total_quantiles
- ead_quantiles: DataFrame | None = None¶
- metadata: dict[str, Any]¶
- quantiles: DataFrame | None¶
- total_ead_quantiles: DataFrame | None = None¶
- total_quantiles: DataFrame | None = None¶
- class snail.damages.PiecewiseLinearDamageCurve(curve: DataFrame[PiecewiseLinearDamageCurveSchema])[source]¶
Bases:
DamageCurveA piecewise-linear damage curve
Methods
clip_curve_data(intensity, damage)Clip damage curve values to valid 0-1 damage range
damage_fraction(exposure)Evaluate damage fraction for exposure to a given hazard intensity
from_csv(fname[, intensity_col, damage_col, ...])Read a damage curve from a CSV file.
from_excel(fname[, sheet_name, ...])Read a damage curve from an Excel file.
interpolate(a, b, factor)Interpolate damage values between two curves
plot([ax])Plot a line chart of the damage curve
scale_x(x)Scale intensity by a factor, x
scale_y(y)Scale damage by a factor, y
translate_x(x)Translate intensity by a factor, x
translate_y(y)Translate damage by a factor, y
- static clip_curve_data(intensity, damage)[source]¶
Clip damage curve values to valid 0-1 damage range
- damage: Series[float]¶
- damage_fraction(exposure: array) array[source]¶
Evaluate damage fraction for exposure to a given hazard intensity
- classmethod from_csv(fname, intensity_col='intensity', damage_col='damage_ratio', comment='#', **kwargs)[source]¶
Read a damage curve from a CSV file.
By default, the CSV should have columns named “intensity” and “damage_ratio”, with any additional header lines commented out by “#”.
Any additional keyword arguments are passed through to
pandas.read_csv- Parameters:
- fnamestr, path object or file-like object
- intensity_colstr, default “intensity”
Column name to read hazard intensity values
- damage_colstr, default “damage_ratio”
Column name to read damage values
- commentstr, default “#”
Indicates remainder of the line in the CSV should not be parsed. If found at the beginning of a line, the line will be ignored altogether.
- kwargs
see pandas.read_csv documentation
- Returns:
- PiecewiseLinearDamageCurve
- classmethod from_excel(fname, sheet_name=0, intensity_col='intensity', damage_col='damage_ratio', comment='#', **kwargs)[source]¶
Read a damage curve from an Excel file.
By default, the file should have columns named “intensity” and “damage_ratio”, with any additional header lines commented out by “#”.
Any additional keyword arguments are passed through to
pandas.read_excel- Parameters:
- fnamestr, path object or file-like object
- sheet_namestr or int
Strings are used for sheet names. Integers are used in zero-indexed sheet positions (chart sheets do not count as a sheet position).
- intensity_colstr, default “intensity”
Column name to read hazard intensity values
- damage_colstr, default “damage_ratio”
Column name to read damage values
- commentstr, default “#”
Indicates remainder of the line in the CSV should not be parsed. If found at the beginning of a line, the line will be ignored altogether.
- kwargs
see pandas.read_csv documentation
- Returns:
- PiecewiseLinearDamageCurve
- intensity: Series[float]¶
- classmethod interpolate(a, b, factor: float)[source]¶
Interpolate damage values between two curves
` new_curve_damage = a_damage + ((b_damage - a_damage) * factor) `- Parameters:
- aPiecewiseLinearDamageCurve
- bPiecewiseLinearDamageCurve
- factorfloat
Interpolation factor, used to calculate the new curve
- Returns:
- PiecewiseLinearDamageCurve
- class snail.damages.PiecewiseLinearDamageCurveSchema(*args, **kwargs)[source]¶
Bases:
DataFrameModelMethods
empty(*_args)Create an empty DataFrame with the schema of this model.
example(**kwargs)Generate an example of this data model specification.
from_json(source)Load a schema from JSON.
from_yaml(yaml_schema)Load a schema from YAML.
get_metadata()Provide metadata for columns and schema level
pydantic_validate(schema_model)Verify that the input is a compatible dataframe model.
strategy(**kwargs)Create a data synthesis strategy.
to_json([target])Convert this model's schema to JSON.
to_json_schema()Serialize schema metadata into json-schema format.
to_schema()Create
DataFrameSchemafrom theDataFrameModel.to_yaml([stream])Convert this model's schema to YAML.
validate(check_obj[, head, tail, sample, ...])Validate a DataFrame based on the schema specification.
Config
build_schema_
- class Config¶
Bases:
BaseConfig- Attributes:
- description
- dtype
- from_format
- from_format_kwargs
- metadata
- multiindex_name
- multiindex_unique
- on_missing_columns
- parser_source
- title
- to_format
- to_format_buffer
- to_format_kwargs
- unique
- name: str | None = 'PiecewiseLinearDamageCurveSchema'¶
name of schema
- damage: Series[float] = 'damage'¶
- intensity: Series[float] = 'intensity'¶
- snail.damages.calculate_direct_damages(splits: DataFrame, *, asset_id: str, quantity: str, intensity_columns: Mapping[Any, str], hazard_cv: float | Mapping[Any, float] = 0.0, curves: Mapping[str, DamageCurve], curve_weights: Mapping[str, float], eta_sd: float = 0.0, cost_mean: float | str, cost_asset_cv: float = 0.0, cost_systemic_cv: float = 0.0, n_samples: int = 1000, quantiles: Sequence[float] | None = None, return_periods: Mapping[Any, float] | None = None, ead_quantiles: Sequence[float] | None = None, seed: int | None = None, scenario: str | None = None, aggregate_assets: bool = False) DirectDamageResult[source]¶
Sample and summarise direct damages for pre-split assets.
Each row in
splitsis one asset split.intensity_columnsmaps intensity-case labels (such as named events or return-periods) to hazard intensity columns. Each simulation selects a weighted damage curve and draws a systemic cost multiplier shared across all assets and scenarios. Each asset/scenario group then receives independent hazard, damage-noise and local cost draws, shared across its splits and intensity cases. Hazard and cost values are clamped at zero, damage fractions are clipped to [0, 1], and asset splits damages are summed for each intensity case. The result returns requested quantiles and run metadata. Samples can optionally be accumulated across assets to calculate total quantiles.In the equations below,
Zdenotes a draw from a standard normal distribution with mean 0 and standard deviation 1.- Parameters:
- splitspandas.DataFrame
Pre-split asset data, with one row per split. Each split’s quantity and hazard intensities are used to calculate and aggregate its damage.
- asset_idstr
Name of the column identifying the parent asset for each split.
- quantitystr
Name of the column giving each split’s non-negative quantity: count (normally 1) for points, length for lines, or area for polygons. Units must match the per-unit rehabilitation cost. Each asset has one geometry type, but different assets may use different quantity units. Geometry measurement and unit consistency are the caller’s responsibility.
- intensity_columnsMapping[Any, str]
Mapping from an intensity-case label to the column containing its central hazard intensity for each segment. Labels identify the cases in the returned summaries and may represent any kind of event or return-period maps, for example.
- hazard_cvfloat or Mapping[Any, float], default 0.0
Coefficient of variation of hazard intensity before clamping. Supply one value for all cases or a mapping from each intensity-case label to its value; the mapping keys must exactly match
intensity_columns. A case’s sampled intensity ismax(0, mean * (1 + hazard_cv * Z)).- curvesMapping[str, DamageCurve]
Damage curves available for sampling, keyed by identifiers that match the keys in
curve_weights.- curve_weightsMapping[str, float]
Non-negative relative selection weights for the curves. Weights are normalised before sampling and must have a positive total.
- eta_sdfloat, default 0.0
Standard deviation of the normal damage-noise term. The sampled damage fraction is multiplied by
exp(eta_sd * Z - eta_sd**2 / 2)before clipping to [0, 1].- cost_meanfloat or str
Baseline rehabilitation cost per unit of quantity. Give a non-negative number to use the same mean for all assets, or a column name to read an asset-specific mean. Column values must be constant across that asset’s splits within each scenario. For a point with quantity 1, this is the whole-asset cost; for lines and polygons, value is assumed uniformly distributed per unit length or area.
- cost_asset_cvfloat, default 0.0
Coefficient of variation of the asset normal cost factor before clamping. Sampled unit cost is
max(0, systemic_cost * (1 + cost_asset_cv * Z)), with an independent draw for each asset/scenario group, shared across its splits and intensity cases. Zero disables asset-specific cost variation.- cost_systemic_cvfloat, default 0.0
Finite, non-negative coefficient of variation of the systemic normal cost factor before clamping. Each simulation uses
systemic_cost = cost_mean * max(0, 1 + cost_systemic_cv * Z_system). The same dimensionless multiplier applies to every asset/scenario baseline, including assets with different quantity units. Zero disables systemic cost variation.- n_samplesint, default 1000
Number of uncertainty realisations to draw for each asset or asset/scenario group.
- quantilesSequence[float] or None, default None
Quantiles to report for each asset and intensity case. Values must be in [0, 1]; output columns use percentile names such as
q_05. Set to None to omit per-intensity quantiles.- return_periodsMapping[Any, float] or None, default None
Mapping from intensity-case labels to return periods in years. Supply this together with
ead_quantilesto request expected annual damage (EAD) quantiles. Keys must exactly matchintensity_columns. Note that return periods RP are interpreted as the reciprocal of annual exceedance probability (AEP), soAEP = 1 / RP. If the hazard data instead defines return period R as the mean recurrence interval of events exceeding a theshold, it should be converted to1 / AEP. For example, assuming a Poisson process for events, R = 2 years corresponds to AEP ~0.393 or RP ~2.54. This distinction would affect expected annual damage (EAD) calculations.- ead_quantilesSequence[float] or None, default None
Quantiles to report for each asset/scenario EAD distribution. Requires
return_periods. Values use the same validation and column naming asquantiles.- seedint or None, default None
Seed for random number generator. Set a seed to make the sampled summaries reproducible for the same inputs and row order.
- scenariostr or None, default None
Optional column identifying scenarios. If supplied, aggregation and local random draws are grouped by both asset and scenario; otherwise they are grouped by asset alone. Systemic draws span all scenarios.
- aggregate_assetsbool, default False
Sum matching simulation samples across assets, separately within each scenario. Return
total_quantilesatquantileswhen supplied. When EAD is requested, integrate the summed event samples and returntotal_ead_quantilesatead_quantiles. Total summaries includen_assetsandn_splits.
- Returns:
- DirectDamageResult
quantilescontains one row per asset, scenario (if supplied), and intensity case when requested.ead_quantilescontains one row per asset/scenario group when requested. Both haven_splitsand one column per requested quantile.metadatarecords the seed and model configuration. Whenaggregate_assetsis True, thetotal_*fields contain corresponding total quantile summaries; otherwise these fields are None. Total event summaries use one row per scenario and intensity case; total EAD summaries use one row per scenario.
- Raises:
- KeyError
If a required input column is missing.
- ValueError
If parameters are invalid, numeric inputs are missing or non-finite, or a column-based cost mean varies within an asset/scenario group.
Notes
Curve choices and systemic cost multipliers are shared across the entire call at each simulation index. Hazard, damage noise and local cost draws are independent between asset/scenario groups and shared across all splits and intensity cases within each group. Both cost stages are clamped at zero; the final cost mean may therefore differ from the input baseline.
Global damage curve choices are made first, then systemic cost draws, then local draws for each group. Metadata records inputs and draw_scopes (“call” or “asset_scenario”).
Asset aggregation sums corresponding simulation indices before calculating total quantiles. This preserves shared systemic uncertainty and local variation. Total EAD integrates the summed event damages; the fixed integration weights make this equivalent to summing asset EAD samples.
If EAD is requested, each sample’s damage is assumed linear in the natural logarithm of annual exceedance probability between supplied events. These intervals are integrated analytically with respect to probability. We peform constant extrapolation in damage from the lowest supplied probability to zero probability. There is no extrapolation beyond the highest supplied probability. Quantiles are calculated from the integrated samples.
snail.intersection module¶
- class snail.intersection.GridDefinition(crs: str, width: int, height: int, transform: tuple[float])[source]¶
Bases:
objectStore a raster transform and CRS
A note on transform - these six numbers define the transform from i,j cell index (column/row) coordinates in the rectangular grid to x,y geographic coordinates, in the coordinate reference system of the input and output files. They effectively form the first two rows of a 3x3 matrix:
| x | | a b c | | i | | y | = | d e f | | j | | 1 | | 0 0 1 | | 1 |
In cases without shear or rotation, a and e define scaling or grid cell size, while c and f define the offset or grid upper-left corner:
| x_scale 0 x_offset | | 0 y_scale y_offset | | 0 0 1 |
Methods
from_extent(xmin, ymin, xmax, ymax, ...)GridDefinition for a given extent, cell size and CRS
from_raster(fname)GridDefinition for a raster file (readable by rasterio)
from_rasterio(dataset)GridDefinition for a rasterio dataset
from_xarray(data_array)GridDefinition for an xarray DataArray or Dataset with spatial metadata.
- crs: str¶
- classmethod from_extent(xmin: float, ymin: float, xmax: float, ymax: float, cell_width: float, cell_height: float, crs)[source]¶
GridDefinition for a given extent, cell size and CRS
- classmethod from_xarray(data_array: Dataset | DataArray)[source]¶
GridDefinition for an xarray DataArray or Dataset with spatial metadata.
Requires the DataArray to have a rioxarray accessor with CRS and transform information derived from explicit coordinates.
- height: int¶
- transform: tuple[float]¶
- width: int¶
- snail.intersection.SPLIT_BATCH_SIZE = 5000¶
Batch size for splitting an in-memory geometry column.
The extension splits one Arrow batch at a time, so an in-memory geometry column is presented to it in batches of this many features: splitting a whole table at once would give no sign of progress on a long job, and would hold every piece of every feature in memory at once. A source that brings its own batching - a GeoParquet reader, a Dataset scan - can be split directly, and keeps whatever batch size it was read with; this only governs the batches
to_geoarrow()slices an in-memory column into.Each batch costs something fixed to set up and read back, so batches much smaller than this measurably slow a large split down; much larger ones buy no more speed and only raise the peak memory.
- snail.intersection.aggregate_values_to_grid(splits: GeoDataFrame, value_column: str, grid: GridDefinition, index_i: str = 'index_i', index_j: str = 'index_j', fill_value: float = 0.0, dtype=None) ndarray[source]¶
Aggregate split-geometry attributes onto a raster-shaped array.
- Parameters:
- splits
GeoDataFrame containing split geometries and raster index columns.
- value_column
Name of the column to aggregate per cell (e.g.
length_km).- grid
A
GridDefinitionthat defines the raster bounds.- index_i, index_j
Column names storing raster column (
i) and row (j) indices.- fill_value
Initial fill value for cells without observations.
- dtype
Optional dtype for the resulting array. Defaults to promoting the column dtype with the fill value dtype.
- snail.intersection.apply_indices(features: GeoDataFrame, grid: GridDefinition, index_i='index_i', index_j='index_j') GeoDataFrame[source]¶
- snail.intersection.generate_grid_boxes(grid: GridDefinition)[source]¶
Generate all the box polygons for a grid
- snail.intersection.get_indices(geom, grid: GridDefinition, index_i='index_i', index_j='index_j') Series[source]¶
Given a geometry, find the cell index (i, j) of its midpoint for the enclosing grid.
N.B. There is no checking whether a geometry spans more than one cell.
- snail.intersection.get_raster_values_for_splits(splits: DataFrame, data: ndarray | DataArray | Array, index_i: str = 'index_i', index_j: str = 'index_j') Series[source]¶
For each split geometry, lookup the relevant raster value.
Cell indices must have been previously calculated and stored as index_i and index_j.
N.B. This will pass through no data values from the raster (no filtering).
- Parameters:
- splits: pandas.DataFrame
Table of features, each with cell indices to look up raster pixel. Indices must be stored under columns with names referenced by index_i and index_j.
- data: numpy.ndarray or xarray.DataArray or dask.array.Array
2D raster values. DataArray inputs must have two spatial dimensions (band dimensions should be squeezed prior to calling).
- index_i: str
Column name for i-indices
- index_j: str
Column name for j-indices
- Returns:
- pd.Series
Series of raster values, with same row indexing as df.
- snail.intersection.prepare_points(features: GeoDataFrame) GeoDataFrame[source]¶
Prepare points for splitting
- snail.intersection.read_split_stream(stream) tuple[ndarray, ndarray][source]¶
Read a stream of split pieces from the extension into memory
The split runs as the stream is read, a batch at a time, but this drains the stream fully and concatenates every batch: use it when you want the pieces as shapely geometries and are content to hold them all at once, which is what
split_linestrings()andsplit_polygons_experimental()do. To keep the streaming memory benefit - splitting a source larger than memory, for example - iterate the stream yourself instead, e.g. withpyarrow.RecordBatchReader.from_stream(stream),and consume each record batch as it arrives.
- Parameters:
- stream
A
snail.core.intersections.SplitStream, or any object implementing the Arrow PyCapsule stream interface (__arrow_c_stream__) with a"geometry"and a"parent"column, such as the result ofsnail.core.intersections.split_linestrings()orsnail.core.intersections.split_polygons().
- Returns:
- geometry: numpy.ndarray
The split pieces, as shapely geometries.
- parent: numpy.ndarray
For each piece, the index of the geometry it was split from.
- snail.intersection.split_features_for_rasters(features: GeoDataFrame, grids: list[GridDefinition], split_func: Callable)[source]¶
Split features on a list of grids, attaching cell indices
Features are implicitly reprojected to each grid CRS for splitting and indexing (columns “i_{n}”, “j_{n}” refer to cells of the nth grid), then returned in their original CRS. If either the features or a grid have no CRS defined, they are assumed to share the same CRS and no reprojection happens.
- snail.intersection.split_geometries(features: GeoDataFrame, grid: GridDefinition, bounded=False) GeoDataFrame[source]¶
Split features of any geometry type along a grid
Unlike
split_linestrings()andsplit_polygons_experimental(), this does not require every feature to be the same type. Each is handled on its own terms: LineStrings and Polygons are split, Points pass through unchanged, multi-part geometries are split part by part, and a GeometryCollection is split member by member. Every piece carries the attributes of the feature it came from, whatever that feature was, and an empty geometry comes back as itself rather than dropping its row.This is what to reach for when a layer holds more than one geometry type. For a layer that holds only one, the typed functions are cheaper: they read and write the coordinates as Arrow buffers, where this serialises every geometry through WKB in both directions.
- Parameters:
- features: geopandas.GeoDataFrame
Features to split; other columns are carried over onto each piece.
- grid: GridDefinition
Grid to split along.
- bounded: bool
As
split_linestrings(). Applies to the LineStrings among the features; Polygons are always split for their whole extent.
- Returns:
- geopandas.GeoDataFrame
One row per piece, with a
"split"column numbering each feature’s pieces from zero.
- snail.intersection.split_linestrings(linestring_features: GeoDataFrame, grid: GridDefinition, bounded=False) GeoDataFrame[source]¶
Split linestrings along a grid
Each piece lies within a single grid cell; together the pieces of a feature are that feature, cut up, so the split conserves its length.
Any MultiLineString geometries are coerced to LineStrings (merged where contiguous, then exploded to one row per part, resetting the index) with a warning. Call
prepare_linestrings()beforehand to opt in to this explicitly and keep control of the row index.- Parameters:
- linestring_features: geopandas.GeoDataFrame
Features to split; other columns are carried over onto each piece.
- grid: GridDefinition
Grid to split along.
- bounded: bool
If False (the default), a feature is split for its whole length, including any part that falls outside the grid. If True, splitting stops at the grid’s edge: pieces outside the grid are left whole rather than cut at every gridline they would otherwise cross.
- snail.intersection.split_points(points: GeoDataFrame, _: GridDefinition) GeoDataFrame[source]¶
Split points along a grid
This is a no-op, written for equivalence when processing multiple geometry types.
- snail.intersection.split_polygons(polygon_features: GeoDataFrame, grid: GridDefinition) GeoDataFrame[source]¶
Split polygons along a grid
- snail.intersection.split_polygons_experimental(polygon_features: GeoDataFrame, grid: GridDefinition) GeoDataFrame[source]¶
Split polygons along a grid
Experimental implementation of split_polygons, possibly faster than the shapely/GEOS overlay approach with some inputs.
Uses snail::splitPolygon to scan each polygon (which may have holes, and is assumed to be valid) along the grid lines and assemble the polygon pieces that cover each cell.
- snail.intersection.to_geoarrow(geometries: GeoSeries, batch_size: int = 5000, encoding: str = 'geoarrow')[source]¶
Geometry column as a stream of GeoArrow batches, for the extension
GeoArrow holds the geometries as flat coordinate and offset buffers, which the extension reads directly - no geometry object is built per feature on either side of the interface. Batches are zero-copy slices of the one Arrow array, and the geometry type travels with them.
This is what
split_linestrings()andsplit_polygons_experimental()use to feed a geometry column tosnail.core.intersections.split_linestrings()orsnail.core.intersections.split_polygons(); call it directly only if you are working with those lower-level, Arrow-native functions yourself.- Parameters:
- geometries: geopandas.GeoSeries
Column of LineString or Polygon geometries to split.
- batch_size: int
Number of features per batch. See
SPLIT_BATCH_SIZE.- encoding: str
"geoarrow"(the default) holds the coordinates in Arrow buffers, which the extension reads in place. It requires every geometry in the column to be the same, single-part type - geopandas raisesValueError: Geometry type combination is not supportedotherwise."WKB"serialises each geometry to a blob instead, which is slower to read but can carry a column of mixed or multi-part geometries; that is whatsplit_geometries()uses.
- Returns:
- pyarrow.Table
A single-column
"geometry"table, chunked into batches ofbatch_sizefeatures, implementing the Arrow PyCapsule stream interface (__arrow_c_stream__) that the extension consumes.
snail.io module¶
- snail.io.band_column_name(key: str, band_number: int, number_of_bands: int) str[source]¶
Name the output column for a raster band.
Single-band rasters attribute values in a column named by key, multi-band rasters in a column per band, named “{key}_band_{band_number}”.
- snail.io.extend_rasters_metadata(rasters: DataFrame) tuple[DataFrame, list[GridDefinition]][source]¶
- snail.io.read_raster_band_data(source: str | PathLike | xarray.DataArray, band_number: int = 1, lazy: bool = False) ndarray | xarray.DataArray[source]¶
Read a single band from a raster path, open rasterio dataset or DataArray
- snail.io.read_raster_metadata(source: str | PathLike | xarray.DataArray) tuple[GridDefinition, tuple[int]][source]¶
Read grid definition and band indexes from a raster path, an open rasterio dataset or an xarray DataArray
- snail.io.write_features(features: GeoDataFrame, path, layer=None)[source]¶
Write features to a vector file or GeoParquet, depending on file extension
Paths ending “.parquet” or “.geoparquet” are written with geopandas.GeoDataFrame.to_parquet, anything else is passed to geopandas.GeoDataFrame.to_file (with layer if provided, for formats such as GeoPackage which support multiple layers).
snail.overlay module¶
High-level overlay of raster values onto vector features
These functions wrap the lower-level steps in snail.intersection
(prepare, split, index, attribute) into single calls that work for point,
linestring and polygon features, handle single- or multi-band rasters, and
implicitly reproject features to the raster CRS (and back) if they differ.
- snail.overlay.overlay_raster(features: GeoDataFrame, raster, bands: list[int] | None = None, column: str | None = None, experimental: bool = False, lazy: bool = False) GeoDataFrame[source]¶
Split features along a raster grid and attribute cell values
- Parameters:
- featuresgeopandas.GeoDataFrame
Point, LineString or Polygon features (multi-geometries are exploded)
- rasterstr | pathlib.Path | rasterio dataset | xarray.DataArray
Raster file path, open rasterio dataset or DataArray, defining the splitting grid and providing cell values
- bandslist of int, optional
Band numbers to attribute (default: all bands)
- columnstr, optional
Output column name (default: raster filename stem). Values from a single band are attributed under this name directly, multiple bands under “{column}_band_{n}” for each band n.
- experimentalbool
Use the experimental (faster, less robust) polygon splitting routine
- lazybool
Read raster bands lazily via xarray/dask rather than into memory. Only applies when raster is a file path.
- Returns:
- geopandas.GeoDataFrame
Split features in the CRS of the input features, with grid cell indices in columns “index_i” and “index_j” and one column of raster values per band. Features that fall outside the raster are attributed NaN. If the features and raster CRS differ, features are reprojected to the raster CRS for splitting and lookup, then reprojected back.
- snail.overlay.overlay_rasters(features: GeoDataFrame, rasters: list | DataFrame, experimental: bool = False, lazy: bool = False) GeoDataFrame[source]¶
Split features along multiple raster grids and attribute cell values
All features are intersected with all rasters: each raster band contributes one column of values to the output.
- Parameters:
- featuresgeopandas.GeoDataFrame
Point, LineString or Polygon features (multi-geometries are exploded)
- rasterslist | pandas.DataFrame
Either a sequence of raster file paths or open rasterio datasets, or a DataFrame with columns:
“path” (required): file path or open rasterio dataset
“bands” (optional): band numbers to attribute, as an int, a comma-separated string (“1,2,3”), or a list/tuple of ints - defaults to all bands
“key” (optional): output column name - defaults to the raster filename stem
- experimentalbool
Use the experimental (faster, less robust) polygon splitting routine
- lazybool
Read raster bands lazily via xarray/dask rather than into memory
- Returns:
- geopandas.GeoDataFrame
Split features in the CRS of the input features, with cell indices in columns “i_{n}”, “j_{n}” for each distinct grid n, and one column of raster values per raster band, named by raster key (with a “_band_{n}” suffix for each band of a multi-band raster)
- snail.overlay.parse_bands(value) tuple | None[source]¶
Parse a band numbers value to a tuple of ints
Accepts an int, a comma-separated string (“1,2,3”), or a list/tuple of ints. Returns None for missing values (None or NaN), meaning “all bands”.
- snail.overlay.split_features(features: GeoDataFrame, grid: GridDefinition, experimental: bool = False) GeoDataFrame[source]¶
Split point, linestring or polygon features along a grid
Features are implicitly reprojected to the grid CRS for splitting and indexing, then returned in their original CRS. If either the features or the grid have no CRS defined, they are assumed to share the same CRS.
- Parameters:
- featuresgeopandas.GeoDataFrame
Point, LineString or Polygon features (multi-geometries are exploded)
- gridGridDefinition
Grid to split features along
- experimentalbool
Use the experimental (faster, less robust) polygon splitting routine
- Returns:
- geopandas.GeoDataFrame
Split features with grid cell indices in columns “index_i” and “index_j” (set to -1 for features outside the grid)
snail.routing module¶
- snail.routing.shortest_paths(sources, destinations, graph, weight)[source]¶
Compute all shortest paths from an ensemble of sources to an ensemble of destinations.
Positional arguments: sources – list of source node ids (string or int). destinations – list of destination node ids (string or int). graph: igraph.Graph instance representing the network. weight – Edge attribute according to which paths should be weighted (string)
Returns: A list of tuples (source, destination) A list of list of edge ids corresponding to shortest paths. For each (source, destination) pair, their is either 0, 1 or several shortest paths.