_functionalities module

User functionalities in pyrockfall

This module implements functions to facilitate rockfall simulation.

pyrockfall._functionalities.singleMaterialSlope(slope: Slope, material: Material | int) → List[Slope][source]

Create a list of slopes, each containing only a single material from the original slope.

Parameters:
  • slope (Slope) – The original slope.

  • material (Material or int) – The material to isolate. Can be the material instance or its index (int).

Returns:

A list of slopes, each containing only one material.

Return type:

List[Slope]

pyrockfall._functionalities.removeMaterial(slope: Slope, material: Material | int) → Slope[source]

Remove a material from the slope.

Parameters:
  • slope (Slope) – The original slope.

  • material (Material or int) – The material to remove. Can be the material instance or its index (int).

Returns:

The modified slope.

Return type:

Slope

pyrockfall._functionalities.findClosest(slope: Slope, height: float) → Tuple[float, int][source]

Find the closest point on the slope to a given height.

Parameters:

height (float) – The height (y-coordinate) to find the closest point to.

Returns:

A tuple (x_closest, element_id) with the x coordinate in the slope for the given height and the ID of the element where the closest point is located.

Return type:

Tuple[float, int]

pyrockfall._functionalities.extrudePolyline(nodes_2d: ndarray, dy: float) → tuple[ndarray, ndarray][source]

Extrudes a 2D polyline into a 3D surface mesh.

Parameters:
  • nodes_2d (np.ndarray) – The input 2D nodes (N, 2) where columns are (x, z).

  • dy (float) – The extrusion distance along the y-axis.

Returns:

  • nodes_3d: (2N, 3) with (x, 0, z) and (x, 1, z)

  • tris: (2*(N-1), 3) with triangles per segment:

    [i, i+1, N+i], [N+i, i+1, N+i+1]

Return type:

tuple[np.ndarray, np.ndarray]

pyrockfall._functionalities.grid2mesh(x: ndarray, y: ndarray, z0: float = 0.0)[source]

Build a 2-triangle-per-cell mesh over a rectilinear grid defined by x -> (nx,) and y -> (ny,). Vertices lie on the z=z0 plane.

Returns:

(ny*nx, 3) in row-major (y major, then x) triangles: (2*(ny-1)*(nx-1), 3) int32, CCW winding

Return type:

points

pyrockfall._functionalities.mesh2PointCloud(mesh: Mesh) → PointCloud[source]

Build a PointCloud from a mesh’s nodes.

Only per-node attributes are carried over (any attribute whose first dimension matches the triangle count instead of the point count is treated as per-triangle and dropped). Triangle connectivity is discarded entirely.

Parameters:

mesh (Mesh) – The source mesh.

Returns:

A new point cloud with the mesh’s nodes and per-node attributes.

Return type:

PointCloud

pyrockfall._functionalities.pointCloud2Mesh(pc: PointCloud, *, method: Literal['uv', 'plane'] = 'uv', max_edge: float | None = None) → Mesh[source]

Build a Mesh from a point cloud via automatic Delaunay triangulation.

By default the points are triangulated in the (u, v) plane of the point cloud’s curvilinear frame (see Model.uvw()), where the wall is unrolled flat along its strike. This also works for walls that change direction (corners, curved walls), which no single plane can represent. The triangle connectivity is attached to the original (untouched) points, and all per-point attributes are carried over as per-node attributes. The mesh shares the frame of the point cloud.

Parameters:
  • pc (PointCloud) – The source point cloud.

  • method ({"uv", "plane"}) – "uv" (default) triangulates in the unrolled (u, v) plane. "plane" levels a copy of the cloud with one rotation (strike onto X, then the dip about X) and triangulates its (X, Y); only suitable for a wall that is close to a single plane.

  • max_edge (float, optional) – Drop triangles with an edge longer than this (measured in 3D). A Delaunay triangulation fills the convex outline of the points, so long triangles bridge gaps and concave parts of the outline. None keeps every triangle.

Returns:

A new mesh with the point cloud’s nodes, automatically triangulated connectivity, and per-node attributes. Points outside the frame (NaN coordinates) are kept as nodes but belong to no triangle.

Return type:

Mesh

pyrockfall._functionalities.sampleRealisations(pc: PointCloud, n_realisations: int, label: str, *, std: str = 'kriging_std', correlated: bool = True, info: Dict[str, Any] | None = None, frame=None, variogram: str = 'spherical', geometry_aniso: float = 3.0, aniso: float = 10.0, bedding_angle: float = 0.0, ring_scale: float = 1.0, max_train: int = 2000, uncertain_only: bool = False, seed: int = 0) → List[PointCloud][source]

Draw realisations of a point cloud whose position and material are uncertain, e.g. the output of PointCloud.fillHoles().

Each point carries the standard deviation of its height above the face plane (attribute std) and one probability per material (attributes <label>_P<class>, summing to 1). In every realisation:

  • Coordinates: the height above the face plane is drawn as w_r = w + std * z with z ~ N(0, 1), and the point moves by w_r - w along the w axis of the curvilinear frame, keeping its (u, v).

  • Material: q ~ U[0, 1) is drawn and the point gets the first class whose cumulative probability exceeds q (inverse CDF), so class k is drawn with probability P_k.

Points with std == 0 and a probability of 1 for one class are certain and are copied unchanged.

With correlated (default), z and q = Phi(g) come from spatially correlated Gaussian fields instead of independent draws, so each realisation is a smooth surface with coherent layers (“probability-field simulation”). The per-point distributions are the same either way: over many realisations each point’s w has mean w and standard deviation std, and class k appears with frequency P_k. Only neighbouring points become alike.

The correlation is set per hole (attribute "hole_id"; one group if it is missing):

  • from info, the dict returned by fillHoles(..., return_info=True), which holds the variograms used to fill each hole; or

  • otherwise fitted on the certain points around the hole, as PointCloud.fillHoles() does: the variogram of the detrended w, and the indicator variogram of the class whose proportion is closest to 0.5, with ranges aniso times longer along the layers.

Parameters:
  • pc (PointCloud) – Point cloud with the attributes std, <label>_P<class> and label.

  • n_realisations (int) – Number of realisations.

  • label (str) – Material attribute. Its probabilities are <label>_P<class>.

  • std (str) – Attribute with the standard deviation of the height above the face plane.

  • correlated (bool) – Spatially correlated draws (default) or independent draws per point.

  • info (dict, optional) – Output of fillHoles(..., return_info=True), to reuse its variograms.

  • frame (CurvilinearFrame, optional) – Frame in which w is measured. Defaults to the frame of pc (the one used to fill the holes, if pc came straight from fillHoles()).

  • variogram (str) – Variogram model fitted when info is not given.

  • geometry_aniso (float) – Anisotropy of the fitted w and material variograms (see PointCloud.fillHoles()).

  • aniso (float) – Anisotropy of the fitted w and material variograms (see PointCloud.fillHoles()).

  • bedding_angle (float) – Anisotropy of the fitted w and material variograms (see PointCloud.fillHoles()).

  • ring_scale (float) – Width of the ring of certain points used to fit the variograms, as a fraction of the hole’s size.

  • max_train (int) – Largest number of ring points used for a variogram fit.

  • uncertain_only (bool) – Return only the uncertain points of each realisation.

  • seed (int) – Random seed.

Returns:

n_realisations point clouds, each with all attributes of pc, the sampled material in label and the sampled displacement along w in "dw". Attributes other than label and "dw" are shared with pc, not copied.

Return type:

list[PointCloud]

Raises:

ValueError – If attributes are missing or the probabilities are not valid.

pyrockfall._functionalities.slopeBelow(slope: Slope, seeder: Seeder) → Slope[source]

Create a slope that extends below the seeder position down to the base of the slope.

Parameters:
  • slope (Slope) – The original slope.

  • seeder (Seeder) – The seeder with the position.

Returns:

The modified slope extending below the seeder.

Return type:

Slope

pyrockfall._functionalities.materialLayers(slope: Slope) → Tuple[List[Material], ndarray][source]

Get the list of material layers and their corresponding heights in the slope. :param slope: The slope to analyze. :type slope: Slope

Returns:

  • List of materials in the order they appear from bottom to top.

  • Corresponding heights (y-coordinates) where each material layer starts.

Return type:

Tuple[List[Material], np.ndarray]

pyrockfall._functionalities.interpPercentiles(data: NDArray[float64], percentiles: NDArray[float64], ranks: NDArray[float64] | None = None) → NDArray[float64][source]

Calculate in each percentile each value of data is in.

Parameters:
  • data ((K,) array of float) – The data find the percentiles they belong.

  • percentiles ((N,) array of float) – The desired percentile levels (in percent, within [0, 100]).

  • ranks ((N,) array of float, optional) – The percentile levels (in percent, within [0, 100]) corresponding to the values in percentiles. If not given, defaults to np.linspace(0, 100, N). (Used for validation only; no interpolation is performed here.)

pyrockfall._functionalities.combinePercentiles(percentiles: NDArray[float64], ranks: NDArray[float64] | None = None, likelihood: NDArray[float64] | None = None) → NDArray[float64][source]

Combine percentiles across N variables at matched ranks using per-variable weights.

Parameters:
  • percentiles ((N, M) array of float) – Percentile values for N variables evaluated at M percentile levels (ranks). Row i contains the M percentile values for variable i; column j aligns the j-th rank across variables.

  • ranks ((M,) array of float, optional) – The percentile levels (in percent, within [0, 100]) corresponding to the columns of percentiles. If not given, defaults to np.linspace(0, 100, M). (Used for validation only; no interpolation is performed here.)

  • likelihood ((N,) array of float, optional) – Per-variable nonnegative weights. If not given, uses uniform weights p = np.ones(N) / N. If an array is provided, it will be normalized to sum to 1.

Returns:

combined – The weighted combination of percentiles at each rank: combined[j] = sum_i w[i] * percentiles[i, j].

Return type:

(M,) array of float

Notes

  • This function assumes the j-th column of percentiles represents the same percentile level for all variables (i.e., columns are aligned by rank).

  • If you work with quantile levels in [0, 1], convert upstream (e.g., with np.quantile) and still pass ranks only for shape/monotonicity checks.

  • ranks are not numerically used unless you extend this function to interpolate.

pyrockfall._functionalities.interpAttributes(source: Model, destination: Model, attributes: List[str], *, method: Literal['nearest', 'knn', 'radius'] = 'knn', **kwargs: Any) → None[source]

Interpolate attributes from source to destination points in-place.

Parameters:
  • source (Geometry) – Must expose .points: (N,3) and .get_attr(name), .set_attr(name, values).

  • destination (Geometry) – Must expose .points: (N,3) and .get_attr(name), .set_attr(name, values).

  • attributes (list of str) – Attribute names to transfer. Each may be shape (N,), (N,D) with D>1.

  • method ({"nearest","knn","radius"}, default "knn") –

    • “nearest”: k=1

    • ”knn”: use k nearest neighbors (parameters[‘n_neighbors’] required; default 8)

    • ”radius”: use neighbors within radius (parameters[‘radius’] required; optional ‘max_k’)

  • parameters (dict) – Method-specific parameters, e.g. {‘n_neighbors’: 8}, {‘radius’: 2.0, ‘max_k’: 64}, IDW power via {‘power’: 2.0}, Gaussian sigma via {‘sigma’: 1.0}.

  • weighting ({"none","idw","gaussian"}, default "idw") – Aggregation weights for continuous attributes. Categorical uses (weighted) mode.

pyrockfall._functionalities.aggregateOnFloor(pointsOnWall: Model, profile_name: str, attributes: List[str], percentiles: NDArray[float64], likelihood: Callable[[NDArray[float64]], NDArray[float64]] | None = None) → Dict[str, NDArray[float64]][source]

Aggregate profile attributes from wall points onto corresponding floor points.

For each point along the floor (e.g. toe of the wall), this function identifies the set of wall points located directly above it (the profile). The specified attributes are then aggregated across the profile according to the requested percentiles. The result is a new set of attributes defined at the floor points, with names following the convention <attribute>_<percentile>. For example, providing attributes=['E1', 'df'] and percentiles=[5, 50, 95] will create attributes 'E1_5', 'E1_50', 'E1_95', 'df_5', 'df_50' and 'df_95'.

The aggregation accounts for the statistical likelihood of each wall point contributing to the profile. If likelihood is provided, it should be a callable that returns a vector of likelihood weights for the set of wall points above a given floor point. If likelihood is None, equal likelihood is assumed, corresponding to a uniform weighting np.full(n_points, 1.0 / n_points) for each profile.

Parameters:
  • pointsOnWall (Geometry) – Geometry object containing wall points where the original attributes are defined. Must support .get_attr(name) to access attributes.

  • attributes (List[str]) – Base names of the attributes to aggregate (e.g. ['E1', 'df']). For each base name and each percentile, a new attribute will be created on the floor.

  • percentiles (np.ndarray of float) – Percentile ranks to evaluate (e.g. [5, 10, ..., 95]). Must be within the range [0, 100].

  • likelihood (callable or None, optional) – Function returning a likelihood vector for the wall points above a given floor point. If None, equal likelihood are assumed. This allows different profiles with varying numbers of points to be handled consistently.

Notes

  • The function returns a dictionary of the aggregated attributes.

  • The likelihood weighting enables non-uniform treatment of wall points, which may be useful if probabilities of occurrence vary along the profile.

  • Percentile aggregation is performed independently for each attribute.

pyrockfall._functionalities.wallFloorElevation(model: Model, profile_spacing: float, *, label: str | None = None, ignore_ids: List[int] = [], frame=None) → float[source]

Common floor elevation for all profiles of a wall.

The wall is cut into slabs of width profile_spacing along the strike (the s coordinate of the curvilinear frame). Slabs that do not span the full height of the wall are ignored; the floor is the highest of the lowest elevations of the remaining slabs, so every complete profile reaches it.

Parameters:
  • model (Model) – Wall geometry.

  • profile_spacing (float) – Width of the slabs along the strike.

  • label (str, optional) – Attribute holding material IDs. Needed only with ignore_ids.

  • ignore_ids (list[int], optional) – Material IDs left out when looking for the floor (e.g. talus). Their elevation range sets the tolerance used to decide whether a slab is complete; without them the tolerance is profile_spacing.

  • frame (CurvilinearFrame, optional) – Frame to use. Defaults to the frame of the model.

Returns:

Floor elevation.

Return type:

float

pyrockfall._functionalities.runWallProfiles(model: Model, segment_length: float, profile_spacing: float, profile_resolution: float, material_label: str, materials: Dict[int, Material], runner: Callable[[Slope], Tuple[NDArray[float64], NDArray[float64]]], *, do_remove_talus: bool = True, results_labels: List[str] = []) → Tuple[PointCloud, PointCloud][source]

Generate wall and floor point clouds by slicing a geological model into profiles and running block-release analyses.

This function extracts vertical profiles along a given slope (wall), removes talus if requested, and runs a user-specified analysis (runner) for each profile. The function consolidates the results into two point clouds:

  • Wall point cloud: points at block release locations with associated result attributes.

  • Floor point cloud: points at the floor with direction vectors, representing the projection of block trajectories to the base of the slope.

Profiles are slices of constant s in the curvilinear frame of the model (see Model.sde()), so they follow the strike of the wall around bends. The model itself is not modified.

Parameters:
  • model (Geometry) – Geological wall geometry to be sliced into segments and profiles.

  • segment_length (float) – Length of wall segments (along strike) used for profile slicing.

  • profile_spacing (float) – Horizontal spacing between consecutive vertical profiles.

  • profile_resolution (float) – Vertical discretization step used when slicing profiles.

  • material_label (str) – Attribute name in the model that indicates material IDs.

  • materials (Dict[int, Material]) – Dictionary mapping material IDs to material definitions, including talus if present.

  • runner (Callable[[Slope], Tuple[NDArray[np.float64], NDArray[np.float64]]]) –

    Function that runs the block-release analysis for a single slope profile. Must return a tuple of:

    • positions (ndarray, shape (N, 2)): x,y positions of block release points.

    • results (ndarray, shape (N, M)): analysis results for each release point, with M result metrics.

  • do_remove_talus (bool, optional) – Whether to identify and remove talus layers from profiles. Defaults to True.

  • results_labels (List[str], optional) – Names of result metrics to be stored in the wall point cloud. If empty, generic labels (result_0, result_1, …) will be created automatically.

Returns:

  • pc_wall (PointCloud): Point cloud of release points on the wall. Each point stores results from the analysis (results_labels).

  • pc_floor (PointCloud): Point cloud of points projected onto the floor with an attribute “direction” storing trajectory direction vectors.

Return type:

Tuple[PointCloud, PointCloud]

Raises:

ValueError – If the output of runner does not match expected shapes: - positions not 2D (x,y), - number of results inconsistent across profiles, - mismatch in number of positions and results.

Notes

  • Profile coordinates are (d, e): distance along the dip direction and elevation.

  • Profiles containing incomplete or ambiguous talus sections are skipped.

  • The returned point clouds are in the model’s own coordinates.

Example

>>> pc_wall, pc_floor = runWallProfiles(
...     model=geom,
...     segment_length=5.0,
...     profile_spacing=2.0,
...     profile_resolution=0.5,
...     material_label="material",
...     materials=mat_list,
...     runner=my_runner,
...     do_remove_talus=True,
...     results_labels=["first_impact", "runout"]
... )
>>> pc_wall.points.shape
(1200, 3)
>>> pc_wall.get_attr("first_impact").shape
(1200,)
>>> pc_floor.get_attr("direction").shape
(100, 3)
pyrockfall._functionalities.rocksSeeders(seeders: List[Seeder]) → List[Rock][source]
pyrockfall._functionalities.slopeFeatures(slope: Slope) → Tuple[float, float, float][source]