Reference manual
GenMR.environment module
GenMR Virtual Environment Generator
This module defines the environmental layers and objects used in the GenMR digital template. Environmental layers are implemented as classes, and associated environmental objects are defined as classes or methods.
Planned Additions (v1.1.2)
Atmosphere
Power grid
Population
- Author:
Arnaud Mignan, Mignan Risk Analytics GmbH
- Version:
1.1.1
- Date:
2025-12-08
- License:
AGPL-3
- class GenMR.environment.CriticalInfrastructure(name: str, zone_type: str, area: float, centroid: tuple, polygon: Polygon, distance_to_coast: float, distance_to_river: float, Ex_S_kton: float)
Bases:
objectRepresents a critical infrastructure facility or asset.
- Parameters:
name (str) – Name or identifier of the infrastructure.
zone_type (str) – Type of industrial zone.
area (float) – Area of the facility.
centroid (tuple of float) – Coordinates (x, y) of the facility’s centroid.
polygon (shapely.geometry.Polygon) – Polygon representing the infrastructure footprint.
distance_to_coast (float) – Minimum distance from the infrastructure to the nearest coastline [km].
distance_to_river (float) – Minimum distance from the infrastructure to the nearest river [km].
Ex_S_kton (float) – Explosive or hazard-related characteristic, e.g., explosive stock in kilotons.
- Ex_S_kton: float
- area: float
- centroid: tuple
- distance_to_coast: float
- distance_to_river: float
- name: str
- polygon: Polygon
- zone_type: str
- class GenMR.environment.EnvLayer_natLand(soil, par)
Bases:
objectDefines an environmental layer for natural land classification, including water, forest, and grassland.
- Parameters:
soil (EnvLayer_soil) – Soil layer object containing topography, soil thickness, and wetness information.
par (dict) –
Dictionary of parameters controlling land classification. Keys include: - ve_treeline_m : float
Elevation threshold (m) above which forest does not grow.
- ID
Identifier of the layer, set to ‘natLand’.
- Type:
str
- soil
Copy of the input soil layer.
- Type:
- grid
Grid object defining the spatial domain and resolution.
- Type:
- topo
Copy of the topography layer associated with the soil layer.
- Type:
- src
Source object containing original RasterGrid and perils information.
- Type:
object
- par
Dictionary of parameters controlling land classification.
- Type:
dict
- S
Integer array of land class codes: - -1 : water - 0 : grassland - 1 : forest
- Type:
numpy.ndarray
- hW
River height (m) in river cells, zeros elsewhere.
- Type:
numpy.ndarray
- class GenMR.environment.EnvLayer_soil(topo, par)
Bases:
objectEnvironmental layer representing soil properties over a raster grid.
The state variable is soil thickness h. Additional characteristics include water height hw and optional corrections for unstable soil.
- Parameters:
topo (EnvLayer_topo) – The topography layer used as reference for the soil layer.
par (dict) –
Dictionary of parameters for the soil layer. Expected keys include: - ‘h0_m’ : float
Reference soil thickness in meters.
- ’wat_h_m’float
Water height in meters.
- ’corr’str
Correction method for unstable soil, e.g., ‘remove_unstable’.
- ID
Identifier of the layer (‘soil’).
- Type:
str
- topo
Reference topography layer.
- Type:
- par
Parameter dictionary provided at initialization.
- Type:
dict
- grid
Grid associated with the topography layer.
- Type:
- h
Soil thickness in meters.
- Type:
ndarray, shape (grid.nx, grid.ny)
- hw
Water height in meters.
- Type:
float
- property FS_state
Determine the categorical FS state from FS values.
- Returns:
FS_code – 2D array of integers representing soil stability: - 0: stable (FS > 1.5) - 1: critical (1 < FS <= 1.5) - 2: unstable (FS <= 1)
- Return type:
numpy.ndarray
- property FS_value
Compute the factor of safety (FS) for slope stability.
- Returns:
FS – 2D array of FS values computed using soil thickness, wetness, slope, and soil parameters.
- Return type:
numpy.ndarray
- property wetness
Compute the soil wetness ratio for each grid cell.
- Returns:
wetness – 2D array of wetness ratio (dimensionless) in [0,1].
- Return type:
numpy.ndarray
- class GenMR.environment.EnvLayer_topo(src, par)
Bases:
objectDefine an environmental layer for the topography on a coarser grid before interpolating back to default. The state variable is the altitude z(x,y).
- Parameters:
src (object) – Source object containing the original RasterGrid and perils information.
par (dict) –
Dictionary of parameters controlling topography generation. Keys include: - lores_f : int
Downscaling factor for the raster grid.
- bg_tan(phi)float
Background slope factor for altitude construction.
- thbool
Include earthquake-related topography (EQ).
- vobool
Include volcanic eruption cone (VE).
- frbool
Include fractal diamondsquare topography.
- fr_etafloat
Scaling factor for fractal topography.
- rvbool
Include river valley damped sine topography (FF).
- csbool
Include compound bevel topography.
- ID
Identifier of the environmental layer (‘topo’).
- Type:
str
- src
Copy of the source object passed as parameter.
- Type:
object
- grid
Default-resolution grid associated with the source.
- Type:
- par
Parameter dictionary passed at initialization.
- Type:
dict
- z
2D array of altitude values in meters at the default resolution.
- Type:
numpy.ndarray
- gridlow
Coarser downscaled grid used temporarily during topography construction (deleted after upscaling).
- Type:
- algo_diamondsquare(i, roughness, sig, rng)
Generate a fractal topography using the Diamond-Square algorithm.
The algorithm creates a 2D height matrix with fractal properties, controlled by the roughness parameter. The final matrix size is (2^i + 1) × (2^i + 1).
- Parameters:
i (int) – Number of iterations; determines the size of the final matrix as 2^i + 1.
roughness (float) – Roughness parameter (0 < roughness < 1). Equivalent to 1-H, where H is the Hurst exponent (fractal dimension D = 3-H).
sig (float) – Standard deviation of the random deviations added at each step.
rng (numpy.random.Generator) – Random number generator used to create Gaussian noise for the surface.
- Returns:
m – 2D array representing the generated fractal topography.
- Return type:
ndarray, shape (2^i + 1, 2^i + 1)
- property aspect
Compute the aspect (orientation) of the topography in degrees.
Aspect is calculated from the x- and y- gradients of the elevation field z(x, y) using a 3x3 kernel finite-difference method.
- Returns:
aspect – 2D array of aspect values in degrees at each grid point. Values indicate the downslope direction.
- Return type:
ndarray of float
- property coastline_coord
Compute the coordinates of the coastline based on the topography.
- Returns:
xc (list of float) – x-coordinates of the coastline points, taken as the last grid cell in each column where elevation z <= 0.
yc (ndarray of float) – y-coordinates of the grid columns corresponding to the coastline.
- model_cs_compoundbevel()
Generate a compound bevel topography along the coastline.
For each column in the grid, the topography is adjusted near the coastline using a linear slope (bevel) over a specified width (cs_w_km) and blended with the existing elevation using a scaling factor (cs_eta). The slope does not exceed the maximum defined by cs_tan(phi) or the inland elevation.
- Returns:
zcs – 2D array representing the adjusted elevation with compound bevels along the coastline.
- Return type:
ndarray, shape (gridlow.nx, gridlow.ny)
- model_fr_diamondsquare()
Generate fractal topography using the Diamond-Square algorithm.
The fractal surface is created on the downscaled grid (gridlow) with roughness determined by the Hurst exponent derived from the fractal dimension parameter fr_Df.
- Returns:
zfr_cropped – 2D array representing the fractal elevation field (unitless or in km depending on scaling). Cropped to match the low-resolution grid size.
- Return type:
ndarray, shape (gridlow.nx, gridlow.ny)
- model_rv_dampedsine()
Generate river valley topography using a damped sine function along the x-axis.
Each river is modeled with an exponentially decaying sinusoidal profile in the north-south direction and a linear slope along the west-east direction. River depth is blended with the existing topography using a scaling factor.
- Returns:
zrv – 2D array representing the elevation adjustments for all river valleys. Values are additive to the existing low-resolution topography.
- Return type:
ndarray, shape (gridlow.nx, gridlow.ny)
- model_th_ellipsoid()
Generate a topography perturbation due to earthquake fault segments using ellipsoidal shapes.
Each fault segment is represented as a 3D ellipsoid based on its geometry (length, width, strike, dip) and mechanical parameters.
- Returns:
zth – 2D array representing the additional topography induced by all earthquake fault segments. Values are added to the existing topography during intrusion/extrusion.
- Return type:
ndarray, shape (gridlow.nx, gridlow.ny)
- model_vo_cone()
Generate topography perturbations for volcanic eruptions using conical shapes.
Each volcanic eruption source is represented as a truncated cone, with height and base width defined in the parameters.
- Returns:
zvo – 2D array of elevation contributions from all volcanic cones. Values are additive to the existing topography.
- Return type:
ndarray, shape (gridlow.nx, gridlow.ny)
- property river_coord
Compute the coordinates and identifiers of rivers using a damped sine model.
- Returns:
river_xi (ndarray of float) – x-coordinates of river points.
river_yi (ndarray of float) – y-coordinates of river points.
river_zi (ndarray of float) – Elevation values at river points.
river_id (ndarray of int) – Identifier for each river segment.
- property slope
Compute the slope of the topography in degrees.
Uses a 3x3 kernel finite-difference method to estimate gradients of the elevation field z(x, y).
- Returns:
slope – 2D array of slope values in degrees at each grid point.
- Return type:
ndarray of float
- class GenMR.environment.EnvLayer_urbLand(natLand, par)
Bases:
objectGenerate an urban land use environmental layer.
This model combines: - The SLEUTH city growth cellular automaton (CA), based on Clarke et al. (1997); Candau (2002) - A road network growth CA, based on Koenig & Bauriedel (2009) - Land use state transformation methods, based on White et al. (1997)
- Parameters:
natLand (EnvLayer_natLand) – Natural land layer providing initial land cover, grid, and topography.
par (dict) – Dictionary of parameters controlling urban growth and SLEUTH CA behavior. Keys include: - city_yr0 : int, initial year of the city - city_seed : tuple(float, float), coordinates of the initial city center - SLEUTH_maxslope : float, maximum slope allowed for urban expansion - SLEUTH_disp : float, dispersion parameter - SLEUTH_roadg : float, road gravity parameter - lores_f : int, downscaling factor for grids used in road CA
- ID
Layer identifier, here ‘urbLand’.
- Type:
str
- grid
The computational grid for the urban layer.
- Type:
- topo
Topography layer used for slope calculations and urban constraints.
- Type:
- par
Parameters controlling urban growth and CA rules (same as input par).
- Type:
dict
- S
Land use classification grid. -1: water
0: grassland 1: forest 2: residential 3: industrial 4: commercial
- Type:
ndarray
- year
Current simulation year.
- Type:
int
- urban_yes
Boolean mask indicating which forest cells are eligible for urbanization.
- Type:
ndarray
- disp_val
Dispersion value for SLEUTH CA.
- Type:
int
- max_roadsearch
Maximum search radius for road network growth.
- Type:
int
- roadNet
Road network sublayer initialized on a coarsened grid.
- Type:
- built
Boolean/int grid indicating whether a cell has built structures (0: no, 1: yes).
- Type:
ndarray
- roads
Grid indicating presence of roads (0: none, 1: road).
- Type:
ndarray
- built_type
Grid indicating type of built-up area: 0: commercial, 1: industry, 2: residential, 3: water, etc.
- Type:
ndarray
- built_yr
Grid storing the year each cell was built.
- Type:
ndarray
References
Candau JT (2002), Temporal calibration sensitivity of the SLEUTH urban growth model. Master Thesis, University of California Santa Barbara, 130 pp. Clarke KC, Hoppen S, Gaydos L (1997), A self-modifying cellular automaton model of historical urbanization in the San Francisco Bay area. Environment and Planning B: Planning and Design, 24, 247-261. Koenig R, Bauriedel C (2009), Generating settlement structures: a method for urban planning and analysis supported by cellular automata. Environment and Planning B: Planning and Design, 36, 602-624. White R, Engelen G, Uljee I (1997), The use of constrained cellular automata for high-resolution modelling of urban land-use dynamics. Environment and Planning B: Planning and Design, 24, 323-343.
- property CI_refinery
Identify and construct the critical infrastructure object representing the main coastal refinery.
This property selects the largest polygon classified as an industrial harbor zone from
industrialZones, and returns aCriticalInfrastructureinstance located at its centroid.- Returns:
An object describing the refinery, including its name, zone type, polygon geometry, area, centroid coordinates, and distances to coastline and river.
- Return type:
- property bldg_roofpitch
Assign a roof pitch type to buildings based on urban land class. Not used yet in damage assessment.
- Returns:
val – Array storing roof pitch type for each grid cell: - ‘H’ : high-pitch roof (residential) - ‘L’ : low-pitch roof (industrial) - ‘M’ : medium-pitch roof (commercial) Cells not built or outside urban areas are nan.
- Return type:
ndarray(dtype=object, shape=(nx, ny))
- property bldg_type
Assign building construction types based on urban land class and probability rules.
- Returns:
val – Array storing building types for each grid cell: - ‘M’ : masonry (residential) - ‘W’ : wood (residential) - ‘S’ : steel (industrial) - ‘RC’: reinforced concrete (commercial) Cells not built or outside urban areas are nan.
- Return type:
ndarray(dtype=object, shape=(nx, ny))
- property bldg_value
Estimate the replacement/building value for each urban cell according to Huizinga et al. (2017)
- Returns:
val – Array of building values (USD) per grid cell based on: - Residential (S==2) - Industrial (S==3) - Commercial (S==4) Computed as: c1 * (GDP_percapita_USD)**c2 * (cell_area_m2) Cells not built or outside urban areas are nan.
- Return type:
ndarray(dtype=float, shape=(nx, ny))
References
Huizinga J, de Moel H, Szewczyk W (2017), Global Flood Depth-Damage Functions. Methodology and the Database with Guidelines. JRC Technical Reports. EUR 28552 EN.
- calc_Pr_urbanise(slope, par)
Calculate the probability of urbanisation based on local slope using the SLEUTH model.
- Parameters:
slope (float or ndarray) – Local slope [degrees] at a grid cell or array of slopes.
par (dict) –
Dictionary of SLEUTH parameters: - ‘SLEUTH_maxslope’ : float
Maximum slope that can be urbanized [degrees].
- ’SLEUTH_slope’float
Slope influence coefficient [%].
- Returns:
pr – Probability of urbanisation for the given slope(s), in the range [0, 1]. Returns 0 if slope exceeds ‘SLEUTH_maxslope’.
- Return type:
float or ndarray
- get_S_urban(built, built_type)
Classify built land-use states using the White et al. (1997) land-use transition model.
- Parameters:
built (ndarray of shape (nx, ny)) – Binary grid where 1 indicates a built cell and 0 indicates non-built.
built_type (ndarray of shape (nx, ny)) –
Integer grid encoding the preliminary building type: -1 : unclassified
0 : commercial 1 : industry 2 : housing 3 : water 4 : road
- Returns:
built_type – Updated building type grid following land-use transitions from White et al. (1997).
- Return type:
ndarray of shape (nx, ny)
- get_d4mkd(ic, jc, i_test, j_test)
Return the distance-class indices for a set of test coordinates.
This computes distance classes used in the White et al. (1997) land-use transition potentials. Each (i_test[k], j_test[k]) pair is assigned to one of 18 discrete distance bins based on its Euclidean distance from the reference cell (ic, jc).
- Parameters:
ic (int) – Indices of the reference grid cell.
jc (int) – Indices of the reference grid cell.
i_test (array_like) – Arrays of test cell indices for which distance classes will be computed. Must be equal-length and indexable.
j_test (array_like) – Arrays of test cell indices for which distance classes will be computed. Must be equal-length and indexable.
- Returns:
neighbor_d – Flattened array of distance-class indices in the range [0, 17]. For each test coordinate, the returned value is the index of the corresponding distance bin.
- Return type:
ndarray of int
- get_industrialZones()
Extract and classify industrial zones from the current land-use grid.
Industrial areas (state
3) are grouped into connected components using a von Neumann neighbourhood. Each component is converted into a polygon via contour extraction, and the resulting polygon is classified based on proximity to the coastline or river.- Returns:
One dictionary per detected industrial zone. Each dictionary contains: -
state: str Always"industrial". -zone_type: str One of"industrial harbor","riverside industrial park", or"inland industrial park". -vertices: (N, 2) ndarray Closed polygon vertex coordinates. -area: float Polygon area. -distance_to_coast: float Minimum distance to coastline. -distance_to_river: float Minimum distance to river. -closed: bool AlwaysTrue.- Return type:
list of dict
- get_state_built(state0, neighbor_k, neighbor_d, m_kd)
Determine the new built-type state based on transition potentials.
Computes the Commercial/Industrial/Housing (C/I/H) transition potentials following White et al. (1997), using: - neighbor land-use classes
neighbor_k- distance classesneighbor_d- the transition matrixm_kd(shape: 3 x 5 x 18)- Parameters:
state0 (int) – Current land-use state of the cell (0=C, 1=I, 2=H, 3=W, 4=R).
neighbor_k (ndarray of int) – Land-use types of neighbors.
-1marks invalid neighbors.neighbor_d (ndarray of int) – Distance-class indices of the neighbors (0-17).
m_kd (ndarray) – Transition potential matrix of shape (3, 5, 18), as returned by
transform_landUse().
- Returns:
new_state – The selected new state among: - 0 → Commercial - 1 → Industrial - 2 → Housing
If no valid neighbors exist, the function returns
state0.- Return type:
int
- property industrialZones
Cached version of industrial zones.
- property roadNet_coord
Return the coordinates of the road network nodes and edges for plotting.
- Returns:
node_x (list of float) – X-coordinates of all road network nodes.
node_y (list of float) – Y-coordinates of all road network nodes.
edge_x (list of float) – X-coordinates of edges, formatted for plotting line segments as [x0, x1, None, x0, x1, None, …].
edge_y (list of float) – Y-coordinates of edges, formatted similarly to edge_x.
- transform_landUse()
Return the land-use transition potential matrix from White et al. (1997).
This function constructs the mₖd matrix, which encodes the potentials for converting existing land-use classes into new urban land-use types (Commercial, Industrial, Housing) as a function of distance classes.
The formulation follows White et al. (1997), where each entry
m_kd[k, current_state, d]represents the potential for land of typecurrent_stateto transform into target classkat distance indexd.Notes
Number of target land-use classes:
nk = 5
(0 = C, 1 = I, 2 = H, 3 = W, 4 = R) - Number of distance classes:
nd = 18- Only the 3 urbanising target classes have potentials:k = 0 → Commercial,k = 1 → Industrial,k = 2 → Housing.- Returns:
m_kd – Transition potential matrix where: - Axis 0 → target land-use class (C, I, H) - Axis 1 → current land-use class - Axis 2 → distance classes (0-17)
Values are integers representing conversion strengths, with positive values indicating attraction and negative values indicating repulsion for conversion.
- Return type:
ndarray, shape (3, 5, 18)
References
White R, Engelen G, Uljee I (1997), The use of constrained cellular automata for high-resolution modelling of urban land-use dynamics. Environment and Planning B: Planning and Design, 24, 323-343.
- class GenMR.environment.EnvObj_roadNetwork(topo, land, par)
Bases:
objectGenerate a road network on a raster grid using a cellular automaton (CA) approach. Based on the approach developed by Koenig & Bauriedel (2009).
- Parameters:
topo (EnvLayer_topo) – Environmental topography layer object containing elevation z and slope.
land (EnvLayer_natLand) – Natural land classification layer, indicating vegetation, water, and land types.
par (dict) –
Dictionary of parameters controlling road network generation. Key entries include: - city_seed : tuple(float, float)
Coordinates of the initial city node (x, y).
- road_Rmaxfloat
Maximum connection distance in units of grid cell width.
- road_maxslopefloat
Maximum slope (degrees) allowed for road construction.
- topo
Copy of the input topography layer.
- Type:
- land
Copy of the input land layer.
- Type:
- par
Copy of the input parameter dictionary.
- Type:
dict
- grid
Raster grid associated with the topography layer.
- Type:
- net
Graph object storing nodes and edges of the road network.
- Type:
networkx.Graph
- Rmax
Maximum Euclidean distance for road connections.
- Type:
float
- mask
Boolean array marking unbuildable locations (e.g., water, steep slopes, buffer areas).
- Type:
numpy.ndarray
- S
Status array of each grid cell: 0 = empty, 1 = node, 2 = node neighbor, 3 = available for node.
- Type:
numpy.ndarray
- id
Grid cell IDs for nodes (-1 for empty).
- Type:
numpy.ndarray
- eps
Random number array for stochastic CA processes, masked for invalid locations.
- Type:
numpy.ndarray
- nodeID
Current maximum node ID in the network.
- Type:
int
References
Koenig R, Bauriedel C (2009), Generating settlement structures: a method for urban planning and analysis supported by cellular automata. Environment and Planning B: Planning and Design, 36, 602-624
- class GenMR.environment.RasterGrid(par)
Bases:
objectDefine the coordinates (x, y) of the square pixels of a 2D raster grid.
Notes
If x0, xbuffer, ybuffer, and/or lat_deg are not provided by the user, they are set to defaults: x0 = xmin, xbuffer = 0, ybuffer = 0, lat_deg = 45.
- Parameters:
par (dict) – Dictionary containing the input parameters: - w (float) : Pixel width in km - xmin (float) : Minimum abscissa of buffer box - xmax (float) : Maximum abscissa of buffer box - ymin (float) : Minimum ordinate of buffer box - ymax (float) : Maximum ordinate of buffer box - xbuffer (float, optional) : Buffer width in x direction (default 0) - ybuffer (float, optional) : Buffer width in y direction (default 0) - x0 (float, optional) : Abscissa of reference N-S coastline (default xmin) - lat_deg (float, optional) : Latitude at center of grid (default 45)
Examples
Create a grid
>>> grid = RasterGrid({'w': 1, 'xmin': 0, 'xmax': 2, 'ymin': 0, 'ymax': 3}) >>> grid.x array([0., 1., 2.]) >>> grid.y array([0., 1., 2., 3.]) >>> grid.xx array([[0., 0., 0., 0.], [1., 1., 1., 1.], [2., 2., 2., 2.]]) >>> grid.yy array([[0., 1., 2., 3.], [0., 1., 2., 3.], [0., 1., 2., 3.]])
- GenMR.environment.calc_FS(slope, h, w, par)
Calculate the Factor of Safety (FS) for slope stability using the SINMAP approach (Pack et al., 1998).
- Parameters:
slope (numpy.ndarray) – 2D array of slope angles in degrees.
h (numpy.ndarray) – 2D array of soil thickness (m).
w (numpy.ndarray) – 2D array of wetness ratio (dimensionless, typically between 0 and 1).
par (dict) –
Dictionary of soil and material parameters: - Ceff_Pa : float
Effective cohesion (Pa).
- rho_kg/m3float
Soil density (kg/m³).
- phieff_degfloat
Effective friction angle (degrees).
(optional) Other constants: g_earth, rho_wat used in calculations.
- Returns:
FS – 2D array of Factor of Safety values for each grid cell. Values > 1 indicate stability; values < 1 indicate potential failure.
- Return type:
numpy.ndarray
References
Pack RT, Tarboton DG, Goodwin CN (1998), The SINMAP Approach to Terrain Stability Mapping. Proceedings of the 8th Congress of the International Association of Engineering Geology, Vancouver, BC, Canada, 21 September 1998
- GenMR.environment.calc_coord_river_dampedsine(grid, par, z='')
Calculate the (x, y, z) coordinates of river channels defined by damped sine waves.
- Parameters:
grid (RasterGrid) – Raster grid object containing x and y coordinates of the spatial domain.
par (dict) –
Dictionary containing river parameters. Keys include: - riv_y0 : list or array
Reference y-coordinate of each river source.
- riv_A_kmlist or array
Amplitude of the damped sine wave (km).
- riv_lbdlist or array
Exponential decay coefficient of the wave.
- riv_omelist or array
Angular frequency of the sine wave.
z (numpy.ndarray or str, optional) – Elevation array of shape (nx, ny). If provided, only points with z >= 0 are included. Default is empty string, which treats all points as land (z = 0).
- Returns:
river_xi (numpy.ndarray) – X-coordinates of river points.
river_yi (numpy.ndarray) – Y-coordinates of river points.
river_zi (numpy.ndarray) – Z-coordinates (elevation) of river points.
river_id (numpy.ndarray) – Integer array indicating the river index for each point.
- GenMR.environment.calc_topo_attributes(z, w)
Compute slope and aspect of a 2D topography grid using finite differences.
The topography is first converted from meters to kilometers. Gradients are computed with a 3x3 kernel (central differences) using np.gradient. Slope is expressed in degrees, and aspect is calculated following standard geographic conventions.
- Parameters:
z (ndarray, shape (nx, ny)) – 2D array of elevation values in meters.
w (float) – Grid spacing (pixel width) in km.
- Returns:
tan_slope (ndarray, shape (nx, ny)) – Tangent of the slope at each grid point (unitless).
aspect (ndarray, shape (nx, ny)) – Aspect angle at each grid point in degrees, measured clockwise from north.
- GenMR.environment.downscale_RasterGrid(grid, factor, appl='pooling')
Reduce the resolution of a RasterGrid for specific applications.
The
applparameter controls how the downscaling is performed: -topo: for topography generation (with outer layer) for later upscaling. -pooling: for max- or mean-pooling.- Parameters:
grid (RasterGrid) – Input raster grid.
factor (int) – Downscaling factor; the width of each new pixel will be factor * grid.w.
appl (str, optional) – Application mode. Options are
'topo'or'pooling'. Default is'pooling'.
- Returns:
Downscaled raster grid with modified pixel width and adjusted boundaries.
- Return type:
- GenMR.environment.get_FS_state(FS)
Assign a stability code based on the Factor of Safety (FS).
- Parameters:
FS (numpy.ndarray) – Array of Factor of Safety values for each grid cell.
- Returns:
FS_code – Array of integer stability codes corresponding to FS: - 0 : stable (FS > 1.5) - 1 : critical (1 < FS <= 1.5) - 2 : unstable (FS <= 1)
- Return type:
numpy.ndarray
- GenMR.environment.plot_EnvLayer_attr(envLayer, attr, hillshading_z='', file_ext='-')
Plot a specific attribute of an environmental layer.
This function handles plotting for multiple environmental layers including topography, soil, natural land, and urban land. Optionally, hillshading can be applied for topography visualization. Legends are added for categorical variables, and continuous variables display colorbars.
- Parameters:
envLayer (object) – Instance of an environmental layer class (e.g., EnvLayer_topo, EnvLayer_soil, EnvLayer_natLand, EnvLayer_urbLand).
attr (str) – Name of the attribute to plot. Examples: - Topography: ‘z’, ‘slope’, ‘aspect’ - Soil: ‘h’, ‘FS’ - Natural/Urban Land: ‘S’, ‘roadNet’, ‘bldg_value’, ‘built_yr’, ‘industrialZones’
hillshading_z (ndarray, optional) – 2D array of elevation values for hillshading overlay. Default is empty string, meaning no hillshading.
file_ext (str, optional) – File extension for saving the figure (e.g., ‘jpg’, ‘pdf’). Default is ‘-’ meaning the figure is not saved.
- Returns:
Displays the plot. Optionally saves the figure if file_ext is not ‘-‘.
- Return type:
None
Notes
The attribute argument attr must match the string name of the variable inside the envLayer object.
Legends and colormaps are automatically selected based on the layer type and attribute.
For urban layers, industrial zones are plotted as polygons with colors corresponding to their zone type.
- GenMR.environment.plot_EnvLayers(envLayers, file_ext='-')
Plot multiple environmental layers with up to three attributes per layer.
This function creates a multi-panel figure where each row corresponds to an environmental layer. It supports topography, soil, natural land, and urban land layers. The function automatically handles legends, color maps, and optional hillshading for topography.
- Parameters:
envLayers (list of objects) – List of environmental layer instances (e.g., EnvLayer_topo, EnvLayer_soil, EnvLayer_natLand, EnvLayer_urbLand).
file_ext (str, optional) – File extension to save the figure (‘jpg’, ‘pdf’, etc.). Default is ‘-’ which means the figure is not saved.
- Returns:
Displays the multi-panel plot. Optionally saves the figure if file_ext is not ‘-‘.
- Return type:
None
Notes
For topography layers, the three columns correspond to: altitude z, slope, and aspect.
For soil layers, the three columns correspond to: thickness h, factor of safety, and an empty panel.
For natural land layers, the first column shows land classes (S), the other two columns are empty.
For urban land layers, the three columns correspond to: state S, road network, and building value.
Legends, color maps, and hillshading are applied automatically depending on the layer type.
GenMR.perils module
GenMR Peril Implementation
This module offers functions for defining and implementing perils within the GenMR digital template. It provides tools for comprehensive catastrophe risk modeling, including event loss table (ELT) creation, as well as intensity and loss footprint calculations.
Peril models (v1.1.1)
AI: Asteroid impact
EQ: Earthquake
FF: Fluvial flood
LS: Landslide
RS: Rainstorm
SS: Storm surge
TC: Tropical cyclone
VE: Volcanic eruption
WF: Wildfire
Ex: Explosion (industrial)
Planned peril models (v1.1.2)
Dr: Drought
HW: Heatwave
Li: Lightning
PI: Pest infestation
To: Tornado
WS: Windstorm
BO: Blackout
BI: Business interruption
Sf: Public service failure
SU: Social unrest
- Author:
Arnaud Mignan, Mignan Risk Analytics GmbH
- Version:
1.1.1
- Date:
2025-12-08
- License:
AGPL-3
- class GenMR.perils.CellularAutomaton_FF(I_RS, src, grid, topoLayer_z, movie)
Bases:
objectCellular Automaton model for flood (FF) propagation.
- Parameters:
I_RS (ndarray) – Rainfall intensity (m) at FF source
src (Src) – Hazard source object containing flood source parameters and catchment information.
grid (class) – Spatial grid object with attributes such as nx, ny, x, y, and cell width.
topoLayer_z (ndarray) – Topography elevation field (m) corresponding to the spatial grid.
movie (dict) –
- Dictionary containing movie settings:
’create’ (bool): whether to save CA frames.
’path’ (str): folder path to store frames; hardcoded to ‘figs/FF_CA_frames/’.
- result()
- run()
- write_gif()
- class GenMR.perils.CellularAutomaton_LS(soilLayer, wetness, movie, kmax=20)
Bases:
objectCellular Automaton model for landslide (LS) propagation.
- Parameters:
soilLayer (class) – Soil layer object containing topography, soil thickness, and related properties.
wetness (ndarray) – Field of soil wetness or saturation across the spatial grid.
movie (dict) –
- Dictionary containing movie settings:
’create’ (bool): whether to save CA frames.
’path’ (str): folder path to store frames; hardcoded to ‘figs/LS_CA_frames/’.
kmax (int, optional) – Maximum number of CA iterations; default is 20.
- result()
- run()
- write_gif()
- class GenMR.perils.CellularAutomaton_WF(src, urbLandLayer, frame_plot)
Bases:
objectCellular Automaton model for wildfire (WF) propagation.
- Parameters:
src (class) – Source object containing wildfire parameters, including spread ratio and related settings.
urbLandLayer (class) – Urban land layer object containing land-use map, building types, and grid information.
frame_plot (bool) – Flag indicating whether to generate CA frame plots during simulation.
- run()
- class GenMR.perils.DynamicHazardFootprintGenerator(stochset, src, soilLayer, urbLandLayer)
Bases:
objectGenerate dynamical hazard footprints for a given stochastic event set.
This class computes dynamic hazard footprints (e.g., landslides, fluvial floods, wildfires) over a spatial grid, using stochastic events and environmental layers.
- Parameters:
stochset (pandas.DataFrame) – Stochastic event set.
src (Src) – Source object defining peril sources and their characteristics.
soilLayer (class) – Environmental layer object representing soil characteristics.
urbLandLayer (class) – Environmental layer object representing urban land-use
- generate(selected_perils=None, force_recompute=False)
- load_WF_CA_footprints(path_WF_CA_data)
- class GenMR.perils.EventSetGenerator(src, sizeDistr, utils)
Bases:
objectGenerates stochastic event set based on source and size distribution parameters.
- src
Source object (e.g., instance of Src) containing hazard source locations and characteristics.
- Type:
object
- sizeDistr
Size distribution object defining the probability distribution of event magnitudes, volumes, or intensities.
- Type:
object
- utils
Utility module (e.g., GenMR_utils) providing helper functions.
- Type:
module
- ev_stoch
DataFrame storing stochastic event realizations with columns: - ‘ID’: unique event identifier - ‘srcID’: source identifier - ‘evID’: event identifier - ‘S’: event size - ‘lbd’: rate or frequency
- Type:
pandas.DataFrame
- ev_char
DataFrame storing event characteristics with columns: - ‘evID’: event identifier - ‘x’: x-coordinate of event - ‘y’: y-coordinate of event
- Type:
pandas.DataFrame
- generate()
- class GenMR.perils.HazardFootprintGenerator(stochset, evchar, src, topo_z)
Bases:
objectGenerate hazard footprints for a given stochastic event set.
This class takes a stochastic set of hazard events, their characteristics, the hazard source information, and the topography to generate hazard footprints (e.g., spatial distribution of hazard intensity). The footprints are stored in a catalog for further analysis or visualization.
- Parameters:
stochset (pandas.DataFrame) – DataFrame containing the stochastic event set with event IDs, source IDs, event sizes, and occurrence rates.
evchar (pandas.DataFrame) – DataFrame with event characteristics, including event coordinates and any other metadata.
src (object) – Source object containing hazard source information (e.g., locations, type, geometry).
topo_z (ndarray) – 2D array representing the topographic elevation grid (used for footprint modeling).
- static add_v_forward(vf, vtan, track_x, track_y, grid, t_i)
Combine forward and tangential wind components to compute total wind field.
This function calculates the total wind speed and its x and y components at each grid point, accounting for the forward motion of the storm along its track and the tangential wind profile.
- Parameters:
vf (float) – Forward speed of the storm (m/s).
vtan (ndarray) – Tangential wind speed array (m/s) at each grid point relative to storm center.
track_x (ndarray) – X-coordinates of the storm track (km).
track_y (ndarray) – Y-coordinates of the storm track (km).
grid (object) – Grid object containing xx and yy 2D arrays for spatial coordinates.
t_i (int) – Current time step index along the storm track.
- Returns:
vtot (ndarray) – Total wind speed at each grid point (m/s).
vtot_x (ndarray) – X-component of total wind speed (m/s).
vtot_y (ndarray) – Y-component of total wind speed (m/s).
vtan_x (ndarray) – X-component of tangential wind (m/s).
vtan_y (ndarray) – Y-component of tangential wind (m/s).
- static calc_I_ash_m(S, r)
Calculate volcanic ash deposit thickness at a distance from the eruption.
The model assumes an exponential decay of deposit thickness with distance, calibrated from historical eruptions (e.g., Mt. St. Helens 1980).
- Parameters:
S (float) – Erupted volume in km³.
r (float) – Distance from the volcanic vent (km).
- Returns:
Ash deposit thickness (m).
- Return type:
float
- static calc_I_blast_kPa(S, r)
Calculate blast overpressure in kPa from an explosive event.
- Parameters:
S (float) – Explosive yield in kilotons TNT equivalent.
r (float) – Distance from the explosion center (km).
- Returns:
Blast overpressure (kPa).
- Return type:
float
- static calc_I_shaking_ms2(S, r)
Calculate peak ground acceleration (PGA) in m/s² from earthquake magnitude and distance.
- Parameters:
S (float) – Earthquake magnitude.
r (float) – Distance from the source to the site (km).
- Returns:
Peak ground acceleration (m/s²).
- Return type:
float
- static calc_I_v_ms(S, r, par)
Calculate the maximum wind speed (m/s) of a tropical cyclone at a given distance.
This model accounts for atmospheric density, Coriolis effect, and storm parameters following the approach in Mignan (2024:fig. 2.19).
- Parameters:
S (float) – Windspeed (m/s) at point along track.
r (float) – Distance from the storm center (km).
par (dict) – Dictionary of cyclone parameters, including: - ‘lat_deg’ : Latitude in degrees - ‘pn_mbar’ : Ambient pressure in mbar - ‘B_Holland’ : Holland B parameter for wind profile
- Returns:
Maximum wind speed in meters per second (m/s) at distance r from the storm center.
- Return type:
float
- static calc_S_track(stochset, src, Track_coord)
Calculate along-track hazard intensity for tropical cyclones (TC) accounting for decay over land after coastal landfall.
The method computes the intensity of each TC event along its track, reducing the intensity after landfall based on distance from coast.
- Parameters:
stochset (pandas.DataFrame) – Stochastic event set containing columns [‘ID’, ‘evID’, ‘S’, …].
src (object) – Source object containing storm characteristics, including SS_char (storm source coordinates) and par parameters.
Track_coord (pandas.DataFrame) – DataFrame containing storm track coordinates with columns [‘evID’, ‘x’, ‘y’].
- Returns:
S_alongtrack – Dictionary mapping each TC event ID to an array of along-track maximum intensity values (same length as track points).
- Return type:
dict
- generate()
- get_TC_timeshot(evID, t)
Compute a single time-step (snapshot) of a tropical cyclone (TC) event.
This method calculates both the symmetric and asymmetric wind fields at time index t along the cyclone track, as well as the tangential and total wind velocity components.
- Parameters:
evID (str) – Event ID of the tropical cyclone.
t (int) – Time index along the cyclone track (0 ≤ t < npt), where npt is the number of points along the track.
- Returns:
- I_sym_tndarray
Symmetric wind field at time step t (storm without motion effects).
- I_asym_tndarray
Asymmetric wind field at time step t (storm including motion effects).
- vtot_xndarray
Total wind velocity component along x-axis.
- vtot_yndarray
Total wind velocity component along y-axis.
- vtan_xndarray
Tangential velocity component along x-axis.
- vtan_yndarray
Tangential velocity component along y-axis.
- Return type:
tuple of ndarray
- static model_SS_Bathtub(I_trigger, src, topo_z)
Simple Bathtub model to estimate storm surge (SS) height over a grid.
This method computes the storm surge height at each grid cell using a “bathtub” approach: starting from the coastline, the surge height is reduced inland according to topography.
- Parameters:
I_trigger (ndarray, shape (nx, ny)) – Grid of triggering intensity (windspeed, m/s) along the coastline.
src (object) – Source object containing: - grid: grid coordinates with nx, ny, x, y - SS_char: storm surge source coordinates - par[‘SS’][‘bathy’]: bathymetry decay parameter
topo_z (ndarray, shape (nx, ny)) – Elevation grid of the terrain.
- Returns:
I_SS – Storm surge height (m) at each grid cell.
- Return type:
ndarray, shape (nx, ny)
- class GenMR.perils.RiskFootprintGenerator(catalog_hazFootprints, urbLandLayer, evtable)
Bases:
objectGenerate risk footprints (damage and loss) for a set of hazard footprints.
- Parameters:
catalog_hazFootprints (dict) – Dictionary of hazard footprints with event IDs as keys and 2D arrays as values.
urbLandLayer (object) – Urban land layer containing building values (attribute bldg_value).
evtable (pandas.DataFrame) – Event table with at least a column ‘evID’; a ‘loss’ column will be added.
- class GenMR.perils.Src(par, grid)
Bases:
objectDefine the characteristics of the peril sources.
This class stores the parameters and derived attributes of different peril sources
- Parameters:
par (dict) – Dictionary containing the peril source parameters, with nested keys.
grid (RasterGrid) – Instance of RasterGrid class defining the computational domain.
- property AI_char
Generate the characteristics of asteroid impact (AI) sources, if defined.
- Returns:
Dictionary containing: - ‘srcID’ (list of str): Unique identifiers for each asteroid impact source. - ‘x’ (ndarray): x-coordinates of asteroid impact sources. - ‘y’ (ndarray): y-coordinates of asteroid impact sources.
- Return type:
dict
- property EQ_char
Return the characteristics of earthquake (EQ) sources.
This property calls the helper function _get_char_srcEQline to compute the coordinates and identifiers of EQ sources if they exist. Results are cached to avoid repeated computation.
- Returns:
A dictionary with keys: - ‘srcID’ (list of str): Unique source identifiers for each earthquake. - ‘x’ (ndarray): x-coordinates of the source points. - ‘y’ (ndarray): y-coordinates of the source points.
- Return type:
dict
- property FF_char
Generate characteristics of flood (FF) sources.
This property returns the coordinates and identifiers of riverine flood sources defined in the model parameters.
- Returns:
Dictionary containing: - ‘srcID’ (ndarray of str): Unique identifiers for each flood source. - ‘x’ (ndarray of float): x-coordinates of the flood source points. - ‘y’ (ndarray of float): y-coordinates of the flood source points.
- Return type:
dict
- property TC_char
Generate characteristics of tropical cyclone (TC) sources.
This property returns the coordinates and identifiers of tropical cyclone tracks defined in the model parameters. The track points are generated stochastically according to the number of cyclones (N), number of points per track (npt), maximum deviation (max_dev), and random seed (rdm_seed). Each TC source is assigned a unique identifier.
- Returns:
Dictionary containing: - ‘srcID’ (ndarray of str): Unique identifiers for each tropical cyclone source. - ‘x’ (ndarray of float): x-coordinates of the TC track points. - ‘y’ (ndarray of float): y-coordinates of the TC track points.
- Return type:
dict
- property VE_char
Retrieve the characteristics of volcanic eruption (VE) sources.
- Returns:
Dictionary containing: - ‘srcID’ (ndarray of str): Unique identifiers for each volcanic eruption source. - ‘x’ (ndarray of float): x-coordinates of the flood source points. - ‘y’ (ndarray of float): y-coordinates of the flood source points.
- Return type:
dict
- GenMR.perils.calc_EQ_length2magnitude(L)
Convert earthquake rupture length to moment magnitude.
Given the rupture length of an earthquake fault (km), this function calculates the corresponding earthquake magnitude using the empirical relation from Wells and Coppersmith (1994:fig. 2.6b).
- Parameters:
L (float or ndarray) – Earthquake rupture length in kilometers.
- Returns:
M – Calculated moment magnitude, rounded to one decimal place.
- Return type:
float or ndarray
- GenMR.perils.calc_EQ_magnitude2length(M)
Convert earthquake magnitude to rupture length.
Given a moment magnitude, this function calculates the expected rupture length (in kilometers) using the empirical relation from Wells and Coppersmith (1994:fig. 2.6b). Useful for floating rupture computations.
- Parameters:
M (float or ndarray) – Earthquake moment magnitude.
- Returns:
L – Estimated rupture length in kilometers.
- Return type:
float or ndarray
- GenMR.perils.calc_Lbd_GPD(S, mu, xi, sigma, Lbdmin)
Calculate the cumulative rate of events following a Generalised Pareto Distribution (GPD).
This corresponds to Mignan (2024:eq. 2.50), where the cumulative occurrence rate Lbd is derived from the GPD parameters.
- Parameters:
S (float or ndarray) – Event size (e.g., magnitude, intensity, or volume).
mu (float) – Threshold parameter (location) of the GPD.
xi (float) – Shape parameter of the GPD.
sigma (float) – Scale parameter of the GPD.
Lbdmin (float) – Minimum cumulative rate (normalization factor).
- Returns:
Lbd – Cumulative rate corresponding to event size S.
- Return type:
float or ndarray
- GenMR.perils.calc_Lbd_exponential(S, a, b)
Calculate the cumulative rate of events following an exponential law.
This corresponds to Mignan (2024:eq. 2.39), where the cumulative occurrence rate Lbd decreases exponentially with event size S.
- Parameters:
S (float or ndarray) – Event size (e.g., magnitude, intensity, or volume).
a (float) – Intercept parameter in the exponential relation (log10 scale).
b (float) – Exponential decay parameter controlling how fast the rate decreases with S.
- Returns:
Lbd – Cumulative rate corresponding to event size S.
- Return type:
float or ndarray
- GenMR.perils.calc_Lbd_powerlaw(S, a, b)
Calculate the cumulative rate of events following a power-law distribution.
This corresponds to Mignan (2024:eq. 2.38), where the cumulative occurrence rate Lbd is a function of event size S.
- Parameters:
S (float or ndarray) – Event size (e.g., magnitude, intensity, or volume).
a (float) – Intercept parameter in the power-law relation (log10 scale).
b (float) – Exponent parameter controlling the slope of the power-law in log10 scale.
- Returns:
Lbd – Cumulative rate corresponding to event size S.
- Return type:
float or ndarray
- GenMR.perils.get_peril_evID(evIDs)
Extract the peril identifiers from an array of event identifiers.
Each event identifier is assumed to be a string where the first two characters correspond to the peril type.
- Parameters:
evIDs (array-like of str) – Array or list of event identifiers.
- Returns:
Array of peril identifiers corresponding to each event ID.
- Return type:
np.ndarray
- GenMR.perils.incrementing(xmin, xmax, xbin, scale)
Generate an array of evenly spaced values within a specified interval.
The spacing can be either linear or logarithmic, depending on the scale parameter.
- Parameters:
xmin (float) – The minimum value of the interval.
xmax (float) – The maximum value of the interval.
xbin (float) – The increment (step size) between consecutive values. For logarithmic scale, this represents the step in log10 space.
scale ({'linear', 'log'}) – Type of spacing. ‘linear’ for evenly spaced linear values, ‘log’ for logarithmically spaced values.
- Returns:
xi – Array of values from xmin to xmax spaced according to xbin and scale.
- Return type:
ndarray
- GenMR.perils.plot_hazFootprints(catalog_hazFootprints, grid, topoLayer_z, plot_Imax, nstoch=5, file_ext='-')
Plot stochastic hazard footprints for multiple events and perils on a spatial grid.
- Parameters:
catalog_hazFootprints (dict) – Dictionary of hazard footprints keyed by event ID. Each value is a 2D array of intensities.
grid (object) – Grid object with attributes xx, yy, xmin, xmax, ymin, ymax.
topoLayer_z (ndarray) – 2D array of topographic elevations for hillshading.
plot_Imax (dict) – Dictionary of maximum intensity values for each peril (keyed by peril code).
nstoch (int, optional) – Number of stochastic realizations to plot per peril (default 5).
file_ext (str, optional) – File extension to save figure (e.g., ‘png’, ‘pdf’). If ‘-’, figure is not saved (default ‘-‘).
- GenMR.perils.plot_src(src, hillshading_z='', file_ext='-')
Plot the spatial locations of peril sources on a 2D grid.
Optionally overlays hillshading of the terrain and saves the figure.
- Parameters:
src (object) – An instance of the Src class containing peril source definitions and grid.
hillshading_z (ndarray or str, optional) – 2D array of topographic elevation values for hillshading (default is ‘’).
file_ext (str, optional) – If not ‘-’, saves the figure with this file extension (e.g., ‘jpg’, ‘pdf’).
- Returns:
Displays the plot and optionally saves it to file.
- Return type:
None
- GenMR.perils.plot_vulnFunctions()
Plot vulnerability (MDR) functions for different perils.
- GenMR.perils.vuln_f(I, peril)
Calculate the mean damage ratio (MDR) given hazard intensity for different perils.
- Parameters:
I (float or ndarray) – Hazard intensity, interpreted according to the peril type: - ‘AI’ or ‘Ex’: overpressure (kPa) - ‘EQ’: peak ground acceleration (m/s²) - ‘FF’ or ‘SS’: inundation depth (m) - ‘LS’: landslide thickness (m) - ‘VE’: volcanic ash thickness (m) - ‘TC’, ‘To’, ‘WS’: wind speed (m/s) - ‘WF’: wildfire state (1 for burnt, 0 otherwise)
peril (str) – Type of peril (‘AI’, ‘Ex’, ‘EQ’, ‘FF’, ‘SS’, ‘LS’, ‘VE’, ‘TC’, ‘To’, ‘WS’, ‘WF’).
- Returns:
MDR – Mean damage ratio corresponding to the given hazard intensity and peril.
- Return type:
float or ndarray
GenMR.utils module
GenMR Utility Functions
This module provides miscellaneous utility functions for input/output management, computing, and plotting within the GenMR package. These functions support core GenMR workflows by streamlining data handling, computation, and visualisation tasks.
- Author:
Arnaud Mignan, Mignan Risk Analytics GmbH
- Version:
1.1.1
- Date:
2025-12-03
- License:
AGPL-3
- GenMR.utils.calc_EP(lbd)
Calculate the cumulative event frequency and the exceedance probability for a series of event rates.
- Parameters:
lbd (array-like) – An array of event rates (lambda) for individual events.
- Returns:
EFi (numpy.ndarray) – Cumulative event frequencies, computed as the cumulative sum of the event rates.
EPi (numpy.ndarray) – Exceedance probabilities corresponding to each cumulative frequency, calculated as 1 - exp(-EFi) (following Mignan, 2024, eq. 3.22).
- GenMR.utils.calc_riskmetrics_fromELT(ELT, q_VAR)
Calculate key risk metrics from an Event Loss Table (ELT), including Average Annual Loss (AAL), Value-at-Risk (VaR), and Tail Value-at-Risk (TVaR).
- Parameters:
ELT (pandas.DataFrame) – Event Loss Table containing at least the following columns: - ‘L’ : Loss for each event - ‘lbd’ : Event rate (lambda) for each event
q_VAR (float) – Confidence level for Value-at-Risk (e.g., 0.95 for 95% VaR)
- Returns:
ELT (pandas.DataFrame) – Input ELT augmented with cumulative event frequency (‘EF’) and exceedance probability (‘EP’) columns.
AAL (float) – Average Annual Loss, computed as the sum of lbd * L (Mignan, 2024:eq. 3.18).
VaRq_interp (float) – Interpolated Value-at-Risk at the given confidence level.
TVaRq_interp (float) – Interpolated Tail Value-at-Risk at the given confidence level.
VaRq (float) – Discrete VaR from the ELT.
TVaRq (float) – Discrete TVaR from the ELT.
- GenMR.utils.cmap_peril(peril)
Create a two-color matplotlib colormap transitioning from white to the color associated with a given peril.
- Parameters:
peril (str) – The type of peril for which to generate the colormap. Passed to col_peril(peril) to get the corresponding color.
- Returns:
cmap_peril – A two-color colormap transitioning from white to the color representing the peril.
- Return type:
matplotlib.colors.LinearSegmentedColormap
- GenMR.utils.col_peril(peril)
Return a color code corresponding to a given point-source or natural peril.
- Parameters:
peril (str) – The type of peril. Options include: - ‘AI’ : Asteroid impact - ‘EQ’ : Earthquake - ‘LS’ : Landslide - ‘VE’ : Volcanic eruption - ‘FF’ : Fluvial flood - ‘SS’ : Storm surge - ‘RS’ : Rainstorm - ‘TC’ : Tropical cyclone - ‘WS’ : Windstorm - ‘Ex’ : Explosion
- Returns:
col – The hexadecimal color code assigned to the peril: - ‘#663399’ : ‘AI’ (Rebeccapurple) - ‘#CD853F’ : ‘EQ’, ‘LS’, ‘VE’ (Peru) - ‘#20B2AA’ : ‘FF’, ‘SS’ (MediumSeaGreen) - ‘#4169E1’ : ‘RS’, ‘TC’, ‘WS’ (RoyalBlue) - ‘#FF8C00’ : ‘Ex’ (Safety Orange)
- Return type:
str
- GenMR.utils.col_state_h(h, h0)
Assign integer state codes to a height matrix based on erosion and landslide conditions relative to a reference height.
- Parameters:
h (numpy.ndarray) – The height matrix.
h0 (float) – The reference height for scaling the erosion/landslide thresholds.
- Returns:
h_plot – An array of the same shape as h, where each element is an integer code representing the state:
0 : erosion +++ (scarp)
1 : intact
2 : erosion ++
3 : erosion +
4 : landslide +
5 : landslide ++
- Return type:
numpy.ndarray
- GenMR.utils.fetch_A0(level)
Fetch the predefined area value corresponding to a specified geographical level.
- Parameters:
level (str) – The geographical level. Options include: - ‘global’ - ‘CONUS’ - ‘IT’ - ‘JP’ - ‘US_CA’ - ‘US_FL’
- Returns:
A0 – The area value associated with the specified level.
- Return type:
float
- GenMR.utils.get_ind_aspect2moore(ind_old)
Convert neighborhood indices defined by an aspect-angle system into standard Moore neighborhood indices.
- Parameters:
ind_old (int or array-like) – Index or array of indices derived from the aspect-angle convention (0-8), where orientation is computed as np.round(aspect * 8 / 360).astype(int).
- Returns:
ind_new – The corresponding Moore neighborhood indices, following the ordering used in get_neighborhood_ind().
- Return type:
int or numpy.ndarray
Notes
The aspect-angle system assigns indices as follows:
7 6 5 0 4 1 2 3
Moore neighborhood indices (used in get_neighborhood_ind) follow this pattern:
0 1 2 3 4 5 6 7
The conversion maps aspect-angle indices to Moore indices.
- GenMR.utils.get_neighborhood_ind(i, j, grid_shape, r_v, method='Moore')
Get the indices of neighboring cells around a focal cell in a 2D grid, based on a specified neighborhood type and radius of vision.
- Parameters:
i (int) – Row index of the focal cell.
j (int) – Column index of the focal cell.
grid_shape (tuple of int) – The shape of the 2D grid as (nx, ny).
r_v (int) – The radius of vision (neighborhood radius).
method (str, optional) – The neighborhood definition (default is ‘Moore’). Options are: - ‘Moore’ : all cells within a square radius r_v, excluding the center. - ‘vonNeumann’ : cross-shaped neighborhood with Manhattan distance r_v. - ‘White_etal1997’ : circular neighborhood based on Euclidean distance.
- Returns:
neigh_ind – A list containing two arrays: - neigh_ind[0] : row indices of neighboring cells. - neigh_ind[1] : column indices of neighboring cells. Both arrays exclude the focal cell (i, j).
- Return type:
list of numpy.ndarray
- GenMR.utils.get_net_coord(net)
Extract node and edge coordinates from a NetworkX graph for visualization.
- Parameters:
net (networkx.Graph) – A NetworkX graph whose nodes contain a ‘pos’ attribute storing (x, y) coordinates.
- Returns:
node_x (list of float) – The x-coordinates of all nodes.
node_y (list of float) – The y-coordinates of all nodes.
edge_x (list of float) – The x-coordinates of edges, arranged as [x0, x1, None, x0, x1, None, …] for plotting line segments.
edge_y (list of float) – The y-coordinates of edges, arranged as [y0, y1, None, y0, y1, None, …] for plotting line segments.
- GenMR.utils.incrementing(xmin, xmax, xbin, method)
Return evenly spaced values within a given interval in linear or logarithmic space, or repeat a value a specified number of times.
- Parameters:
xmin (float) – The minimum value of the interval.
xmax (float) – The maximum value of the interval.
xbin (float or int) – Step size for ‘lin’ or ‘log’ methods, or the number of repetitions for ‘rep’.
method (str) – The spacing method. Options are: - ‘lin’ : linear spacing - ‘log’ : logarithmic spacing - ‘rep’ : repeat xmax xbin times
- Returns:
xi – The array of incremented values according to the selected method.
- Return type:
numpy.ndarray
- GenMR.utils.init_io()
Initialise required I/O directories for GenMR.
Creates the following directories if they do not already exist:
io/
figs/
movs/
- GenMR.utils.load_json2dict(filename)
Load a JSON file and return its contents as a dictionary.
- Parameters:
filename (str) – Path to the JSON file, relative to the current working directory.
- Returns:
data – The dictionary obtained from the JSON file.
- Return type:
dict
- GenMR.utils.load_pickle2class(filename)
Load a pickle file and reconstruct the original Python object.
- Parameters:
filename (str) – Path to the pickle file, relative to the current working directory.
- Returns:
data – The Python object loaded from the pickle file.
- Return type:
object
- GenMR.utils.marker_peril(peril)
Return a marker symbol corresponding to a given point-source peril.
- Parameters:
peril (str) – The type of point-source peril. Options include: - ‘AI’ : Asteroid impact - ‘Ex’ : Explosion - ‘VE’ : Volcanic eruption
- Returns:
marker – The symbol used to represent the peril: - ‘+’ : for ‘AI’ or ‘Ex’ - ‘^’ : for ‘VE’ - ‘’ : empty string if the peril is unrecognized
- Return type:
str
- class GenMR.utils.norm_z(vmin=None, vmax=None, sealevel=0, col_val=0.2, clip=False)
Bases:
Normalize
- GenMR.utils.partitioning(IDs, w, n)
Partition weighted IDs into a 1D array of length n using cumulative probability.
- Parameters:
IDs (array-like) – A list or array of identifiers.
w (array-like) – The weights associated with each ID. Must be non-negative and typically normalized.
n (int) – The number of partitions or samples to generate.
- Returns:
vec_IDs – A sorted 1D array of length n containing IDs selected according to their weights.
- Return type:
numpy.ndarray
- GenMR.utils.pooling(m, f, method='max')
Downscale a 2D matrix by applying pooling (max, min, or mean) over non-overlapping f x f blocks.
- Parameters:
m (numpy.ndarray) – The 2D matrix to be pooled.
f (int) – The pooling factor, defining the size of each block.
method (str, optional) – The pooling method to apply (default is ‘max’). Options are: - ‘max’ : maximum value in each block - ‘min’ : minimum value in each block - ‘mean’ : mean value in each block
- Returns:
m_pool – The pooled matrix of shape (ceil(nx/f), ceil(ny/f)), where nx and ny are the dimensions of the input matrix.
- Return type:
numpy.ndarray
- GenMR.utils.save_class2pickle(data, filename='envLayer_tmpsave')
Save a class instance to a pickle file.
- Parameters:
data (object) – The class instance to save.
filename (str, optional) – The name of the pickle file (default is ‘envLayer_tmpsave’). The file is saved in the ‘io/’ directory.
- Returns:
This function writes the class instance to a pickle file and does not return a value.
- Return type:
None
- GenMR.utils.save_dict2json(data, filename='par_tmpsave')
Save a dictionary to a JSON file.
- Parameters:
data (dict) – The dictionary to save.
filename (str, optional) – The name of the JSON file (default is ‘par_tmpsave’). The file is saved in the ‘io/’ directory.
- Returns:
This function writes the dictionary to a JSON file and does not return a value.
- Return type:
None
- GenMR.utils.zero_boundary_2d(arr, nx, ny)
Set the outer boundary of a 2D array to zero along all four edges.
- Parameters:
arr (numpy.ndarray) – The 2D array to be modified.
nx (int) – The number of rows to zero out at the top and bottom edges.
ny (int) – The number of columns to zero out at the left and right edges.
- Returns:
arr – The input array with its boundary regions set to zero.
- Return type:
numpy.ndarray