_utils module

Utility functions for geometric and mesh operations in model3d.

Includes helpers for angles, mesh processing, and PLY scalar field reading.

pyrockfall._utils.rot2AlignWithX(direction: ndarray) → ndarray[source]

Return a 3x3 rotation matrix R such that v_rot = v @ R aligns direction to +X.

pyrockfall._utils.angleBetweenVectors(cc: ndarray, cn: ndarray) → float[source]

Calculate the angle between two vectors.

Parameters:
Returns:

The angle between the two vectors in degrees.

Return type:

float

pyrockfall._utils.triangleCentroids(coords, connect)[source]

Compute centroids for triangles defined by connectivity.

Parameters:
  • coords (np.ndarray) – Vertex coordinates.

  • connect (np.ndarray) – Connectivity indices.

Returns:

Centroids of each triangle.

Return type:

np.ndarray

pyrockfall._utils.getSubMesh(V: ndarray, T: ndarray, ids: ndarray) → Tuple[ndarray, ndarray, ndarray][source]

Extract a sub-mesh by keeping only the given triangles, dropping any vertex not referenced by them and remapping connectivity accordingly.

Parameters:
  • V – Vertex coordinates, shape (N, D).

  • T – Triangle connectivity, shape (E, 3) (0-based indices into V).

  • ids – Indices of triangles (rows of T) to keep.

Returns:

Reindexed vertex coordinates, shape (N_sub, D). T_sub: Reindexed triangle connectivity, shape (len(ids), 3), indices

into V_sub.

vertex_ids: Original vertex indices kept, shape (N_sub,), such that

V_sub == V[vertex_ids].

Return type:

V_sub

pyrockfall._utils.build_neighbours_mesh(triangles: ndarray) → ndarray[source]

Build triangle adjacency for a triangle mesh.

Parameters:

triangles ((E, 3) int array (0-based)) – Each row is a face with three vertex indices.

Returns:

neighbours – For each face, neighbour across the edge opposite local vertex 0, 1, 2. -1 indicates a boundary (no neighbouring face).

Return type:

(E, 3) int32

pyrockfall._utils.build_neighbours_polygon(elements: ndarray) → ndarray[source]

Build segment adjacency for a polygonal chain / polygon.

Parameters:

elements ((E, 2) int array) – Each row is a segment with two vertex indices.

Returns:

neighbours – neighbours[i, 0] = segment adjacent through elements[i, 0] neighbours[i, 1] = segment adjacent through elements[i, 1] -1 indicates a boundary node.

Return type:

(E, 2) int32

Notes

This assumes a manifold 1D topology: each node is connected to at most two segments.

pyrockfall._utils.angle(vert)[source]

Calculate the rotation angle needed to align a set of 3D points with a reference axis.

Parameters:

vert (np.ndarray) – Array of vertex coordinates.

Returns:

The rotation angle in degrees.

Return type:

float

pyrockfall._utils.read_scalar_field_from_ply(filename)[source]

Read a scalar field from a PLY file.

Parameters:

filename (str) – Path to the PLY file.

Returns:

Scalar field as a numpy array.

Return type:

np.ndarray

pyrockfall._utils.uniqueMaterialList(seq)[source]

Unify objects from the input list while preserving their order.

Generic identity-based deduplication; used both for lists of Material (Slope) and lists of Drag (Vegetation).

Returns:

  • table – Unique objects in first-appearance order.

  • ids ((E,) int32) – Per-element indices into the returned table.

pyrockfall._utils.getTriPoints(points: ndarray, triangle: ndarray, samples: ndarray) → ndarray[source]
pyrockfall._utils.isInsideTriangle(p: ndarray, points: ndarray, tol: float = 1e-12) → ndarray[source]

Edge-function inside test using cross products in 3D.

Inputs:

p : (3, S) points to test (columns are samples) points : (3, 3, S) or (3, 3, 1) triangle vertices per sample:

v0 = points[:, 0, :], v1 = points[:, 1, :], v2 = points[:, 2, :] If points.shape[2] == 1, it’s broadcast to S.

tol : tolerance for inside test

Returns:

(S,) int32
-1 if inside (or on edges within tol),

0 if outside “to the right” of edge v0->v1, 1 if outside “to the right” of edge v1->v2, 2 if outside “to the right” of edge v2->v0.

Return type:

idx

Notes

  • The triangle winding defines “right/left”. Winding is v0->v1->v2; the normal is n = (v1-v0)×(v2-v0).

  • We do not normalise n; signs are preserved and it’s faster.

pyrockfall._utils.timeParabolaPlane(p: ndarray, v: ndarray, a: ndarray, points: ndarray, tol: float = 1e-12, t_min: float = 0.0, t_max: float = inf) → ndarray[source]

Vectorised intersection: x(t)=p + v t + 0.5 a t^2 with plane(points[:,0],points[:,1],points[:,2]).

Inputs

p, v, a : (3, s) points : (3, 3, s) or (3, 3, 1) tol : tolerance used in plane/roots checks t_min : lower time window (inclusive, with tolerance) t_max : upper time window (inclusive, with tolerance)

Returns

t_hit : (s,) time to hit in [t_min, t_max] (np.inf if none)

Quadratic selection when both roots acceptable:

choose min(root) if min(root) > t_min + tol, else choose max(root).

pyrockfall._utils.timeRaySegment(p: ndarray, v: ndarray, points: ndarray, tol: float = 1e-12, t_min: float = 0.0, t_max: float = inf) → ndarray[source]

Vectorised time t such that p + v*t intersects segment [p1, p2].

Inputs

p, v : (3, S) points : (3, 2, S) or (3, 2, 1) with points[:,0,:]=p1, points[:,1,:]=p2 tol : absolute tolerance t_min : lower time window (inclusive with tol) t_max : upper time window (inclusive with tol)

Returns
t_hit(S,) time of intersection; np.inf if no intersection.

Parallel rule: if line ∥ segment and p at t=0 lies on the finite segment, return 0 (then windowed/clipped); else inf.

pyrockfall._utils.timeClosest(p: ndarray, v: ndarray, a: ndarray, pt: ndarray, *, t_min: float = 0.0, t_max: float | None = None, tol: float = 1e-12) → ndarray[source]

Vectorised closest-approach time for uniformly accelerated motion.

Returns:

t_star – Time that minimises ||p + v t + 0.5 a t^2 - pt|| within [t_min, t_max].

Return type:

(S,) array

Notes

If a ≈ 0 => linear solution t* = -(r0·v)/(v·v) clamped to [t_min, t_max]. If also v ≈ 0 => returns t* = t_min.

pyrockfall._utils.rotationAlign2x(vector: ndarray) → ndarray[source]

Return R such that R @ vector == ex (to numerical tolerance).

pyrockfall._utils.tri_plane_intersections_yz_per_triangle(tri_coords: ndarray, xs: ndarray, eps: float = 1e-09) → Tuple[ndarray, ndarray, ndarray][source]

For each triangle i, intersect it with the plane x=xs[i]. Returns exactly two intersections (y,z) and their edge ids (0,1,2). If a triangle does not intersect properly, outputs NaNs and -1s.

Parameters:
  • tri_coords – (E,3,3) float

  • xs – (E,) float, one slice-x per triangle

  • eps – float, tolerance

Returns:

(E,2) float, y coords of intersections (NaN if not cut) Z : (E,2) float, z coords of intersections Eids: (E,2) int, edge ids (0,1,2) or -1 if invalid

Return type:

Y

pyrockfall._utils.pcWalk(p_init, p_end, slab_points, dlt_x, dlt_z)[source]

Algorithm to walk from p_init to p_end through slab_points. slab_points: (N,2) array of (x,y) points in the slab dlt_x: (N,) array of local spacing between points dlt_z: float, global step size Returns: (M,2) array of (x,y) points along the path 1. Start at p_init 2. Move in the direction of p_end, but only as far as dlt_z 3. At each step, look for points in slab_points within dlt_z

in the current direction and within dlt_x locally

  1. If points are found, move towards the average position of those points, weighted by 1/distance^2

  2. If no points are found, reset direction towards p_end

  3. Stop when p_end is reached or no progress can be made

pyrockfall._utils.profile_from_slab(points: ndarray, step: float, axis: ndarray, *, refine: bool = True, min_count: int = 1, min_fraction: float = 0.1) → ndarray[source]

Profile through a slab of points, by interpolation instead of a walk.

The slab is treated as a height field over a straight axis lying in the profile plane (for a wall: the direction up its face). Points are binned along that axis and each bin gives one node at the median offset from the axis, so a sparse layer of stray points does not move the profile and there is nothing to converge.

Parameters:
  • points ((N, 2) array) – Slab points in the profile plane, e.g. (d, e).

  • step (float) – Node spacing.

  • axis ((2,) array) – Direction, in the profile plane, along which the surface is single-valued.

  • refine (bool) – Second pass: re-bin the points along the arclength of the first profile and take the median position per bin. This evens out the node spacing where the surface is steep relative to axis (floor, bench edges).

  • min_count (int) – Bins with fewer points give no node.

  • min_fraction (float) – Bins with fewer points than this fraction of the median bin give no node either. This drops bins that hold only a few isolated stray points, e.g. above the crest.

Returns:

Profile nodes ordered from the highest to the lowest second coordinate (crest to toe). Fewer than two rows if the slab is too sparse.

Return type:

(M, 2) array

Notes

A surface that folds back over axis (an overhang relative to it) cannot be represented; pcWalk() remains available for that case.

pyrockfall._utils.unit(v: ndarray, fallback: ndarray | None = None, eps: float = 1e-12) → ndarray[source]
pyrockfall._utils.normal2d(t: ndarray) → ndarray[source]
pyrockfall._utils.limit_turn(e_new: ndarray, e_old: ndarray, max_turn_angle: float | None) → ndarray[source]
pyrockfall._utils.weighted_centroid(xy: ndarray, centre: ndarray, power: float = 1.0, eps: float = 1e-06) → ndarray[source]
pyrockfall._utils.strip_indices_along_tangent(xy: ndarray, tree: cKDTree, centre: ndarray, tangent: ndarray, half_width: float, transverse_radius: float) → ndarray[source]

Select points in a finite strip.

tangent:

Marching direction.

half_width:

Half-thickness of the strip along the marching direction.

transverse_radius:

Search extent along the section direction, i.e. normal to tangent.

pyrockfall._utils.refine_next_node(xy: ndarray, tree: cKDTree, x_prev: ndarray, e_prev: ndarray, increment: float, transverse_radius: float, *, min_points: int = 20, max_iter: int = 20, tol: float = 0.001, max_turn_angle: float | None = np.float64(0.7853981633974483), weight_power: float = 1.0) → tuple[ndarray, ndarray, ndarray][source]

Find the next polyline node.

The next node is constrained to be exactly increment away from x_prev.

pyrockfall._utils.trace_nodes_from_seed(points: ndarray, increment: float, *, x0: ndarray, e0: ndarray, transverse_radius: float, min_points: int = 20, max_nodes: int | None = None, max_iter: int = 20, tol: float = 0.001, max_turn_angle: float | None = np.float64(0.7853981633974483), weight_power: float = 1.0, min_new_fraction: float = 0.1) → ndarray[source]
pyrockfall._utils.trace_polyline_nodes(points: ndarray, increment: float, *, transverse_radius: float, buffer_steps: int = 5, initial_direction: tuple[float, float] = (1.0, 0.0), min_points: int = 20, max_nodes: int | None = None, max_iter: int = 20, tol: float = 0.001, max_turn_angle: float | None = np.float64(0.7853981633974483), weight_power: float = 1.0, min_new_fraction: float = 0.1) → ndarray[source]
pyrockfall._utils.profile_geometry_from_nodes(nodes: ndarray) → tuple[ndarray, ndarray, ndarray][source]

Convert node polyline into profile centres and directions.

Returns:

  • centres ((N, 2) ndarray) – Profile locations, placed at segment midpoints.

  • tangents ((N, 2) ndarray) – Marching tangent of each segment.

  • section_dirs ((N, 2) ndarray) – XY direction of the 2D section, normal to the marching tangent.

pyrockfall._utils.assign_sections_from_nodes(points: ndarray, nodes: ndarray, *, transverse_radius: float, min_points: int = 20) → tuple[list[ndarray], ndarray, ndarray, ndarray][source]

Stage 2.

Assign points to profiles located at segment midpoints.

Each section i owns points whose projected coordinate along the segment tangent lies between the two segment endpoints:

abs((p - centre_i) . tangent_i) <= length_i / 2

The section direction is normal to the segment tangent.

pyrockfall._utils.brentq(f: Callable[[ndarray], ndarray], a: ndarray, b: ndarray, xtol: float = 1e-10, rtol: float = np.float64(8.881784197001252e-16), ftol: float = 0.0, maxiter: int = 100) → Tuple[ndarray, ndarray, ndarray][source]

Vectorised Brent root finder for many independent 1D brackets.

Parameters:
  • f (callable) – Vectorised function. For input x with shape (N,), must return shape (N,).

  • a (array_like) – Initial bracketing intervals. Must have the same shape.

  • b (array_like) – Initial bracketing intervals. Must have the same shape.

  • xtol (float, optional) – Absolute tolerance on x.

  • rtol (float, optional) – Relative tolerance on x.

  • ftol (float, optional) – Absolute tolerance on f(x). If |f(x)| <= ftol, root is accepted.

  • maxiter (int, optional) – Maximum number of iterations.

Returns:

  • root (np.ndarray) – Estimated roots. Entries that never had a valid bracket are NaN.

  • converged (np.ndarray of bool) – True where convergence was achieved.

  • iters (np.ndarray of int) – Number of iterations performed for each problem.

Notes

This is a batched version of Brent’s method. Each root keeps its own state, but updates are performed with boolean masks.

pyrockfall._utils.rk4_step(dt: float | ndarray, x: ndarray, v: ndarray, accel, *args) → Tuple[ndarray, ndarray][source]

Vectorised RK4 step for many blocks at once.

Parameters:
  • dt (float) – Time step.

  • x ((3, n) ndarray) – Positions.

  • v ((3, n) ndarray) – Velocities.

  • accel (callable) – Function a = accel(x, v, *args), returning (3, n) acceleration.

  • *args – Extra data passed to accel.

Returns:

  • x_new ((3, n) ndarray)

  • v_new ((3, n) ndarray)

pyrockfall._utils.getSubSamples(index: ndarray, *arrays: ndarray) → tuple[ndarray, ...][source]

Get sub-samples.

pyrockfall._utils.setSubSamples(index: ndarray, values: Tuple, *arrays: ndarray) → None[source]

Set sub-samples back into arrays.

pyrockfall._utils.scatterSubSamples(index: ndarray, fill: float, *values: ndarray) → tuple[ndarray, ...][source]

Inverse of getSubSamples: scatter values selected by index (a boolean mask over the last axis) back into full-size arrays of shape value.shape[:-1] + index.shape, filling non-selected entries with fill.

pyrockfall._utils.sampleNormals(position: ndarray, elementsIDs: ndarray, elementNormals: ndarray) → ndarray[source]

Sample the normal vectors at the given positions.

pyrockfall._utils.decompose(vector: ndarray, normal: ndarray, eps: float = 1e-12) → tuple[ndarray, ndarray][source]

Decompose vector into normal and tangential components w.r.t. normal.

Parameters:
  • vector – (D, S) vectors to decompose.

  • normal – (D, S) normals; can be non-unit and vary per sample.

  • eps – small number to guard division by zero.

Returns:

(1, S) normal velocity (scalar) vn_vec = n * vn. vt: (D, S) tangential component in Cartesian coordinates.

Return type:

vn

Notes

  • Works for D = 2 or 3, S arbitrary.

  • If a normal has ~zero length, the output for that sample is:

    vn_vec = 0, vt_vec = vector, vn = 0, vt = ||vector||.