_model module

model.py

Base class Model for storing and manipulating rockface geometries. Provides translation, rotation, clipping, centroid computation, and slicing utilities. Subclasses must implement storage and I/O logic.

class pyrockfall._model.Model[source]

Bases: ABC

Base class for geometric data used in rockfall workflows.

This class stores and manipulates point coordinates (2D or 3D) and provides general-purpose geometric utilities (translate, rotate, centroid, bounding box). Simulation-agnostic. Subclasses are responsible for concrete storage, loading/saving, and any topology (e.g., faces/triangles).

### Subclassing requirements - You must implement:

  • points property (getter & setter): returns/sets an array of shape (N, D), D in {2, 3}.

  • save(output_file): persist model to disk in your preferred format.

  • segment(dx, du): produce windowed segments as model objects.

  • split(dx, minPerc): split into two model objects using your rule.

  • slice(direction, increment, **kwargs): return extracted Geometry objects.

  • You may override:
    • clip(min_val, max_val): default raises NotImplementedError because clipping model may require updating topology; base class cannot guess that.

abstract property points: ndarray

(N, D) array view of point coordinates.

property attrs: Mapping[str, ndarray]

name -> ndarray. Each value has shape (N,) or (N, k) where N == number of points.

Type:

Read-only mapping of per-point attributes

has_attr(name: str) → bool[source]
get_attr(name: str) → ndarray[source]

Return the attribute array (by reference). Raises KeyError if missing.

set_attr(name: str, value: ndarray | None) → None[source]

Set/replace a per-point attribute. value must have first dimension N. Accepts (N,), (N, k) with any dtype. Use None or empty to remove. Stores by reference (no forced copy).

del_attr(name: str) → None[source]

Remove an attribute if present.

list_attrs() → list[str][source]

List available attribute names.

attr_shape(name: str) → tuple[int, ...][source]
attr_dtype(name: str)[source]
apply_point_mask_(mask: ndarray) → None[source]

Keep only points[mask]. Subclasses must override to update topology; this base method only handles attributes.

apply_point_index_map_(new_index_of_old: ndarray, new_N: int | None = None) → None[source]

Reorder/duplicate/drop points according to an index map. new_index_of_old[i] = j means old point i goes to new row j. If new_N is omitted, it is inferred as max(j)+1.

This supports decimation, duplication, or arbitrary reindexing.

save(filename: str, attributes: Sequence[str] | str | None = '*', *, overwrite: bool = False, allow_lossy: bool = False, comments: dict[str, str] | None = None) → None[source]

Save model to various formats.

Parameters:
  • filename (str) – Path with extension: .ply, .npz, .xyz, .pcd (limited), …

  • attributes ({'*', None, sequence of names}) – Which attributes from self._attrs to include (when supported). - ‘*’: include all attributes - None: include none - sequence: include only those present

  • overwrite (bool) – Overwrite target file if exists.

  • allow_lossy (bool) – If False (default), refuse formats that would drop attributes.

  • tri_reduce ({'mean','mode',None}) – For Mesh only: reduce per-triangle attributes to per-vertex before saving PLY/XYZ.

  • comments (dict[str,str] | None) – Stored as PLY comments (e.g., {‘units’:’m’,’crs’:’EPSG:28356’}).

classmethod load(filename: str, attributes: Sequence[str] | None = None, **kwargs) → Model[source]
  1. Build a minimal instance via subclass hook.

  2. If attributes requested, read & attach them post-construction.

clip(min_val: ndarray, max_val: ndarray) → None[source]

Clip the model to an axis-aligned bounding box (AABB).

NOTE: The base class cannot safely implement this because clipping often requires updating topology (faces/edges). Subclasses should implement their own logic (e.g., remove points outside AABB and rebuild connectivity, or perform polygon/mesh clipping).

Parameters:
  • min_val (array-like (D,)) – Minimum coordinates of the AABB.

  • max_val (array-like (D,)) – Maximum coordinates of the AABB.

boundingBox() → Tuple[NDArray[float64], NDArray[float64]][source]

Compute the axis-aligned bounding box of the current points.

Returns:

(min_corner, max_corner) – Each is shape (D,). Raises ValueError if there are no points.

Return type:

tuple of np.ndarray

centroid() → NDArray[float64][source]

Compute the centroid (arithmetic mean) of the points.

Returns:

Shape (D,). Raises ValueError if there are no points.

Return type:

np.ndarray

translate(value: float | Iterable | ndarray, direction: str = 'xyz') → None[source]

Translate the model along specified axes.

Parameters:
  • value (float | array-like) – If scalar, applied to all axes listed in direction. If array-like, it is zipped with direction (1:1).

  • direction (str) – Axes along which to translate, subset of {‘x’,’y’,’z’}. For 2D data, only ‘x’ and ‘y’ are meaningful.

Notes

  • If value is scalar and direction=’xyz’ on a 2D model, the ‘z’ component is ignored.

  • Values are applied in the order given by direction.

rotate(theta: float, axis: str = 'z') → None[source]

Rotate the model by an angle around a principal axis (in-place).

Parameters:
  • theta (float) – Rotation angle in degrees.

  • axis ({'x','y','z'}) – Axis of rotation. For 2D data, only ‘z’ is meaningful.

Notes

  • Rotation is performed about the origin. If you want to rotate about the centroid, call c = centroid(); translate(-c); rotate(…); translate(c).

normalVector() → NDArray[float64][source]

Fit a plane z = a x + b y + d.

Returns:

plane_normal: unit normal vector (-a, -b, 1) normalized. Orientation is adjusted to have a positive Z component (for stable convention).

Return type:

np.ndarray

Notes

  • For 2D data, this method is not defined and raises a ValueError.

  • Plane is fit in the least squares sense.

dip(return_normal: bool = False) → float[source]

Dip angle of the fitted plane z = a x + b y + d.

Returns:

Dip angle in degrees, defined as atan(b) where z ≈ a x + b y + d. This follows the convention of tilt along Y used in the original implementation.

Return type:

float

Notes

  • For 2D data, this method is not defined and raises a ValueError.

  • Plane is fit in the least squares sense.

dipDirection() → float[source]

Dip direction of the fitted plane z = a x + b y + d.

Returns:

Dip direction in degrees, defined as atan2(a, b) where z ≈ a x + b y + d.

Return type:

float

alignWithX(sense: int = 1) → None[source]

Rotate model in the XY-plane so that the fitted plane’s horizontal strike vector aligns with X. :param sense: Sense of direction: 1 = X+, -1 = X-. :type sense: {1, -1}

Notes

  • The plane is fit as z = a x + b y + d (vertical least squares)

via normalVector(). - The plane’s unit normal is projected into XY. Its perpendicular (strike) is rotated onto +X using a single atan2. - If the fitted normal points downward (n_z < 0), it is flipped upward for consistency. - Translation to and from the centroid is applied so that rotation is about the global origin.

coneApproximation() → Tuple[float, float, float, float][source]
fitFrame(*, tol: float = 1.0, res: float = 0.5, corner_length: str | float | None = 'auto', **kwargs) → CurvilinearFrame[source]

Fit the curvilinear frame of the model and keep it as frame.

A plan-view polyline is fitted along the wall and the points are unrolled along it, which gives the coordinates returned by sde() and uvw().

Parameters:
  • tol (float) – How far the centreline of the wall may stray from each straight segment of the polyline (model units).

  • res (float) – Bin width along the wall used by the fit (model units).

  • corner_length ({"auto", float, None}) – Length either side of each bend over which the slicing direction turns. None spreads the turn along each whole segment.

  • **kwargs – Passed to CurvilinearFrame.fit().

Return type:

CurvilinearFrame

property frame: CurvilinearFrame

Curvilinear frame of the model. Fitted with default settings on first use (see fitFrame()). It can also be assigned, e.g. a frame loaded with CurvilinearFrame.load() or shared with another model.

sde(store: bool = False) → NDArray[float64][source]

Curvilinear coordinates of the points.

Returns:

Shape (N, 3): s distance along the strike, d distance along the dip direction (increasing down-dip) and e elevation (equal to z). Points outside the invertible region of the frame are NaN.

Return type:

np.ndarray

Parameters:

store (bool) – Also store the columns as attributes "strike", "dip_direction" and "elevation".

uvw(store: bool = False) → NDArray[float64][source]

Principal coordinates of the unrolled points.

Returns:

Shape (N, 3): u and v span the best-fit plane of (s, d, e) (u along the strike, v up-dip) and w is the height above it.

Return type:

np.ndarray

Parameters:

store (bool) – Also store the columns as attributes "U", "V" and "W".

removePoints(mask_or_attr: str | ndarray, value=None) → int[source]

Remove points, either flagged by a boolean mask or selected by the value of an attribute (in-place).

The positions of the removed points are remembered, so that fillHoles() can rebuild the parts left empty, including those that reach the edge of the model.

Parameters:
  • mask_or_attr (str | array-like of bool) – Name of a per-point attribute, or a boolean mask of length N that is True for the points to remove.

  • value (scalar | sequence, optional) – With an attribute name: the value, or values, to remove.

Returns:

Number of points removed.

Return type:

int

Examples

>>> pc.removePoints("Material", 0)               # one class
>>> pc.removePoints("Material", [0, 3])          # several classes
>>> pc.removePoints(pc.get_attr("height") > 2)   # any condition
fillHoles(attributes: Sequence[str] | str = (), **kwargs) → Model[source]

Create points in the missing parts of the model and krige their coordinates and the selected attributes. See PointCloud.fillHoles().

Not available for this type of model: convert it to a point cloud (mesh2PointCloud()), fill the holes and triangulate again (pointCloud2Mesh()).

abstractmethod segment(dx: float, du: float = 0.0) → List[Model][source]

Segment the model into smaller sections/windows.

Parameters:
  • dx (float) – Window width (project-specific meaning).

  • du (float, default 0) – Overlap between segments (same units as dx).

Returns:

New model objects representing each segment/window.

Return type:

list[Model]

abstractmethod split(dx: float = 0.5, minPerc: float = 0.05) → List[Model][source]

Split the model into two parts according to your rule.

Parameters:
  • dx (float, default 0.5) – Cutting distance/parameter controlling the split.

  • minPerc (float, default 0.05) – Minimum fraction of points allowed in either output to avoid degenerate splits.

Returns:

Two model objects (or potentially more, per your design).

Return type:

list[Model]

abstractmethod slice(direction: NDArray[float64] | None = None, increment: float | None = None, label: str | None = None, **kwargs) → Tuple[List[Geometry], NDArray][source]

Slice the model into 2D profiles.

Parameters:
  • direction (np.ndarray, optional) – None (default) slices along the strike of the wall using the curvilinear frame: slices are surfaces of constant s and the profile coordinates are (d, e). A vector instead cuts parallel slices normal to that fixed direction.

  • increment (float) – Spacing between consecutive slices.

  • label (str) – Name of the attribute containing material IDs.

  • **kwargs – Implementation-specific options (e.g. frame to use a frame other than the model’s own).

Returns:

  • list[Geometry] – Extracted profiles as Geometry type.

  • ndarray – The slice positions (s, or the distance along direction).

section(increment: float, label: str, *, frame: CurvilinearFrame | None = None, **kwargs) → Tuple[List[Geometry], Model][source]

Extract 2D profiles along the strike of the model, and their points in 3D.

This is slice() along the strike (slices of constant s in the curvilinear frame), with each profile also mapped back to world coordinates. The model itself is not modified.

Parameters:
  • increment (float) – Spacing between consecutive sections along the strike.

  • label (str) – Name of the attribute holding material IDs.

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

  • **kwargs – Passed to slice() of the subclass.

Returns:

  • profiles (list[Geometry]) – One 2D profile per section, ordered from crest to toe, with node coordinates given as (horizontal distance from the crest node, height above the lowest node) and material IDs per segment as attributes.

  • sections_pc (PointCloud) – All section nodes as one point cloud in the model’s coordinates, with the material attribute (label, one value per node) and a "Profile" attribute numbering the sections along the strike.

Raises:

ValueError – If no valid sections are found.