spectralbrain.core.base#

Core geometric objects and shared processing functions.

This module defines:

  • SpectralDecomposition — the central object of the library, holding eigenvalues/eigenvectors and providing access to all spectral descriptors.

  • GeometricObject — abstract protocol that both BrainMesh and BrainPointCloud implement.

  • Shared geometric functions that operate on raw (N, 3) coordinate arrays regardless of mesh or point-cloud origin.

Design principle#

SpectralBrain’s data flow is:

io.loaders → core.meshes / core.pointclouds → core.base.SpectralDecomposition → spectral.*

The SpectralDecomposition is what core/ produces and spectral/ consumes. It is the single handoff point between geometry and analysis.

Functions

align_to_pca(points)

Align points so principal axes coincide with coordinate axes.

center_points(points)

Translate points so the centroid is at the origin.

chamfer_distance(A, B)

L² Chamfer distance between two point sets.

compute_adjacency_from_knn(points[, k, ...])

Build a kNN adjacency matrix (binary or weighted).

compute_bounding_box(points)

Axis-aligned bounding box.

compute_centroid(points)

Compute the centroid (center of mass) of a point set.

compute_pca_axes(points)

PCA of a point set — principal axes and explained variance.

convex_hull_area(points)

Convex hull surface area.

convex_hull_volume(points)

Convex hull volume of a point set.

detect_density_outliers(points[, k, ...])

Flag points with anomalously low or high local density.

estimate_point_density(points[, k])

Estimate local point density via k-NN distance.

farthest_point_sampling(points, n_samples, *)

Farthest-point sampling (FPS) for uniform subsampling.

hausdorff_distance(A, B, *[, symmetric])

Hausdorff distance between two point sets.

knn_search(points[, k, query_points])

k-nearest-neighbour search using a KD-tree.

marching_cubes(volume, affine, *[, level, ...])

Extract a mesh from a volumetric label/mask via marching cubes.

mesh_surface_area(vertices, faces)

Total surface area of a triangle mesh.

normalize_scale(points[, method, area])

Scale points to unit bounding-box diagonal, unit RMS, or unit area.

procrustes_align(source, target)

Rigid + uniform scale alignment (Procrustes).

radius_search(points, radius, *[, query_points])

Fixed-radius neighbour search.

triangle_areas(vertices, faces)

Compute per-triangle areas.

Classes

GeometricObject(*args, **kwargs)

Protocol that BrainMesh and BrainPointCloud both implement.

SpectralDecomposition(eigenvalues, ...[, ...])

Eigenvalues and eigenvectors of a Laplace–Beltrami operator.

class spectralbrain.core.base.GeometricObject(*args, **kwargs)[source]#

Bases: Protocol

Protocol that BrainMesh and BrainPointCloud both implement.

Any function that accepts a GeometricObject can work with either representation.

compute_normals()[source]#

Estimate per-vertex/point normals.

Return type:

ndarray[tuple[Any, …], dtype[floating]]

decompose(k=100, **kwargs)[source]#

Compute the spectral decomposition.

Parameters:
Return type:

SpectralDecomposition

surface_area()[source]#

Total surface area.

Return type:

float

property coordinates: ndarray#

Vertex/point coordinates, shape (N, 3).

property n_points: int#

Number of vertices/points.

class spectralbrain.core.base.SpectralDecomposition(eigenvalues, eigenvectors, *, stiffness=None, mass=None, surface_area=None, metadata=None)[source]#

Bases: object

Eigenvalues and eigenvectors of a Laplace–Beltrami operator.

This is the central object of SpectralBrain. It is produced by core.meshes.BrainMesh.decompose() or core.pointclouds.BrainPointCloud.decompose() and consumed by every function in spectral/.

Parameters:
  • eigenvalues (ndarray, shape (k,)) – Non-negative LBO eigenvalues, sorted ascending.

  • eigenvectors (ndarray, shape (N, k)) – Corresponding eigenvectors, M-orthonormal.

  • stiffness (SparseMatrix, optional) – The Laplacian matrix L.

  • mass (MassMatrix, optional) – The mass matrix M.

  • surface_area (float, optional) – Total surface area (for eigenvalue normalisation).

  • metadata (dict, optional) – Provenance info (subject, hemisphere, structure, backend, …).

eigenvalues#
Type:

ndarray

eigenvectors#
Type:

ndarray

stiffness#
Type:

SparseMatrix or None

mass#
Type:

MassMatrix or None

surface_area#
Type:

float or None

metadata#
Type:

dict

Examples

>>> mesh = sb.core.BrainMesh(vertices, faces)
>>> decomp = mesh.decompose(k=100)
>>> decomp.n_eigenvalues
100
>>> decomp.fiedler_value
0.0023
>>> decomp.truncate(50).n_eigenvalues
50
>>> # Pass to spectral descriptors:
>>> hks = sb.spectral.compute_hks(decomp, t_values)
classmethod load(path)[source]#

Load from an HDF5 cache file.

Parameters:

path (PathLike)

Returns:

SpectralDecomposition

Return type:

SpectralDecomposition

normalize_eigenvalues(method='area', area=None, volume=None)[source]#

Return a copy with normalised eigenvalues.

Parameters:
  • method (str) – "area" — multiply by surface area (Reuter convention). "volume" — multiply by volume^{2/3}. "fiedler" — divide by λ₁.

  • area (float, optional) – Override surface area.

  • volume (float, optional) – Override volume.

Returns:

SpectralDecomposition

Return type:

SpectralDecomposition

save(path, **kwargs)[source]#

Save to HDF5 via spectralbrain.io.export.save_hdf5().

Parameters:
Returns:

Path

Return type:

Path

truncate(k)[source]#

Return a copy with only the first k eigenpairs.

Parameters:

k (int) – Number of eigenpairs to keep (must be ≤ current k).

Returns:

SpectralDecomposition

Return type:

SpectralDecomposition

property fiedler_value: float#

First non-trivial eigenvalue λ₁ (the Fiedler value).

Encodes global connectivity of the shape. Larger values indicate tighter geometry.

property k: int#

Alias for n_eigenvalues.

property n_eigenvalues: int#

Number of stored eigenpairs.

property n_vertices: int#

Number of vertices/points.

property shape_dna: ndarray[tuple[Any, ...], dtype[floating]]#

ShapeDNA — the raw eigenvalue sequence (excluding λ₀ ≈ 0).

Returns:

ndarray, shape (k-1,)

property shape_dna_normalized: ndarray[tuple[Any, ...], dtype[floating]]#

Area-normalised ShapeDNA.

Eigenvalues scaled by surface area so that shapes of different sizes are comparable.

Returns:

ndarray, shape (k-1,)

Raises:

ValueError – If surface_area is not set.

property spectral_gap: float#

Gap between λ₁ and λ₂.

spectralbrain.core.base.align_to_pca(points)[source]#

Align points so principal axes coincide with coordinate axes.

Parameters:

points (ndarray, shape (N, 3))

Returns:

  • aligned (ndarray, shape (N, 3))

  • rotation (ndarray, shape (3, 3)) – Rotation matrix applied (rows = new axes).

Return type:

tuple[ndarray[tuple[Any, …], dtype[floating]], ndarray]

spectralbrain.core.base.center_points(points)[source]#

Translate points so the centroid is at the origin.

Parameters:

points (ndarray, shape (N, 3))

Returns:

ndarray, shape (N, 3)

Return type:

ndarray[tuple[Any, …], dtype[floating]]

spectralbrain.core.base.chamfer_distance(A, B)[source]#

L² Chamfer distance between two point sets.

Chamfer = (1/|A|) Σ_{a∈A} min_{b∈B} ||a−b||²
  • (1/|B|) Σ_{b∈B} min_{a∈A} ||b−a||²

Parameters:
  • A (ndarray, shape (N, 3) and (M, 3))

  • B (ndarray, shape (N, 3) and (M, 3))

Returns:

float

Return type:

float

spectralbrain.core.base.compute_adjacency_from_knn(points, k=20, *, symmetric=True)[source]#

Build a kNN adjacency matrix (binary or weighted).

Parameters:
  • points (ndarray, shape (N, 3))

  • k (int) – Number of neighbours.

  • symmetric (bool) – Symmetrise the adjacency (A = max(A, A.T)).

Returns:

SparseMatrix, shape (N, N) – Binary adjacency.

Return type:

spmatrix

spectralbrain.core.base.compute_bounding_box(points)[source]#

Axis-aligned bounding box.

Parameters:

points (ndarray, shape (N, 3))

Returns:

  • bb_min (ndarray, shape (3,))

  • bb_max (ndarray, shape (3,))

  • extent (ndarray, shape (3,)) – bb_max - bb_min.

Return type:

tuple[ndarray, ndarray, ndarray]

spectralbrain.core.base.compute_centroid(points)[source]#

Compute the centroid (center of mass) of a point set.

Parameters:

points (ndarray, shape (N, 3))

Returns:

ndarray, shape (3,)

Return type:

ndarray

spectralbrain.core.base.compute_pca_axes(points)[source]#

PCA of a point set — principal axes and explained variance.

Parameters:

points (ndarray, shape (N, 3))

Returns:

  • components (ndarray, shape (3, 3)) – Rows are the principal directions, sorted by decreasing variance.

  • explained_variance (ndarray, shape (3,)) – Eigenvalues of the covariance matrix (variance along each axis).

  • centroid (ndarray, shape (3,))

Return type:

tuple[ndarray, ndarray, ndarray]

spectralbrain.core.base.convex_hull_area(points)[source]#

Convex hull surface area.

Parameters:

points (ndarray, shape (N, 3))

Returns:

float – Area in mm².

Return type:

float

spectralbrain.core.base.convex_hull_volume(points)[source]#

Convex hull volume of a point set.

Parameters:

points (ndarray, shape (N, 3))

Returns:

float – Volume in cubic mm.

Return type:

float

spectralbrain.core.base.detect_density_outliers(points, k=6, threshold_sigma=3.0)[source]#

Flag points with anomalously low or high local density.

Parameters:
  • points (ndarray, shape (N, 3))

  • k (int) – Neighbour count.

  • threshold_sigma (float) – Number of standard deviations from the mean log-density to flag as outlier.

Returns:

outlier_mask (ndarray, shape (N,), bool) – True for outlier points.

Return type:

ndarray

spectralbrain.core.base.estimate_point_density(points, k=6)[source]#

Estimate local point density via k-NN distance.

Density at each point is approximated as k / V_k where V_k = (4/3)π r_k³ and r_k is the distance to the k-th nearest neighbour.

Parameters:
  • points (ndarray, shape (N, 3))

  • k (int) – Neighbour count for density estimation.

Returns:

density (ndarray, shape (N,)) – Points per mm³ (approximate).

Return type:

ndarray[tuple[Any, …], dtype[floating]]

spectralbrain.core.base.farthest_point_sampling(points, n_samples, *, seed=None)[source]#

Farthest-point sampling (FPS) for uniform subsampling.

Iteratively selects the point farthest from the current set, producing an approximately uniform subset. Essential for standardising point-cloud density from volumetric segmentations.

Parameters:
  • points (ndarray, shape (N, 3))

  • n_samples (int) – Number of points to select.

  • seed (int, optional) – RNG seed for the initial point.

Returns:

  • sampled (ndarray, shape (n_samples, 3)) – Selected points.

  • indices (ndarray, shape (n_samples,)) – Indices into points.

Return type:

tuple[ndarray[tuple[Any, …], dtype[floating]], ndarray]

Notes

Complexity: O(N · n_samples). For N > 100 k, consider the approximate FPS in Open3D or PyTorch3D.

spectralbrain.core.base.hausdorff_distance(A, B, *, symmetric=True)[source]#

Hausdorff distance between two point sets.

Parameters:
  • A (ndarray, shape (N, 3) and (M, 3))

  • B (ndarray, shape (N, 3) and (M, 3))

  • symmetric (bool) – If True, return max(d(A→B), d(B→A)).

Returns:

float

Return type:

float

k-nearest-neighbour search using a KD-tree.

Parameters:
  • points (ndarray, shape (N, 3)) – Reference point set.

  • k (int) – Number of neighbours.

  • query_points (ndarray, shape (M, 3), optional) – Query points. Defaults to points (self-query).

Returns:

  • distances (ndarray, shape (M, k))

  • indices (ndarray, shape (M, k))

Return type:

tuple[ndarray, ndarray]

spectralbrain.core.base.marching_cubes(volume, affine, *, level=None, step_size=1)[source]#

Extract a mesh from a volumetric label/mask via marching cubes.

Parameters:
  • volume (ndarray, shape (X, Y, Z)) – Binary mask or label volume (non-zero = inside).

  • affine (ndarray, shape (4, 4)) – Voxel-to-world affine.

  • level (float, optional) – Iso-surface level. Default 0.5 (for binary masks).

  • step_size (int) – Subsampling step for speed.

Returns:

  • vertices (ndarray, shape (N, 3)) – World-space coordinates.

  • faces (ndarray, shape (F, 3)) – Triangle indices, 0-indexed.

Return type:

tuple[ndarray[tuple[Any, …], dtype[floating]], ndarray[tuple[Any, …], dtype[int64]]]

spectralbrain.core.base.mesh_surface_area(vertices, faces)[source]#

Total surface area of a triangle mesh.

Parameters:
  • vertices (ndarray, shape (N, 3))

  • faces (ndarray, shape (F, 3))

Returns:

float – Total area in mm².

Return type:

float

spectralbrain.core.base.normalize_scale(points, method='bbox', *, area=None)[source]#

Scale points to unit bounding-box diagonal, unit RMS, or unit area.

Parameters:
  • points (ndarray, shape (N, 3))

  • method (str) – "bbox" — divide by bounding-box diagonal. "rms" — divide by RMS distance from centroid. "area" — divide by sqrt(surface_area).

  • area (float, optional) – Surface area (required for method="area").

Returns:

  • scaled (ndarray, shape (N, 3))

  • scale_factor (float) – The divisor applied.

Return type:

tuple[ndarray[tuple[Any, …], dtype[floating]], float]

spectralbrain.core.base.procrustes_align(source, target)[source]#

Rigid + uniform scale alignment (Procrustes).

Finds the rotation R, translation t, and scale s that minimise ||s·R·source + t − target||².

Parameters:
  • source (ndarray, shape (N, 3)) – Points to align.

  • target (ndarray, shape (N, 3)) – Reference points (must have the same N).

Returns:

  • aligned (ndarray, shape (N, 3)) – Transformed source.

  • rotation (ndarray, shape (3, 3)) – Rotation matrix.

  • scale (float) – Uniform scale factor.

Raises:

ValueError – If source and target have different shapes.

Return type:

tuple[ndarray[tuple[Any, …], dtype[floating]], ndarray, float]

Fixed-radius neighbour search.

Parameters:
  • points (ndarray, shape (N, 3))

  • radius (float) – Search radius.

  • query_points (ndarray, shape (M, 3), optional)

Returns:

list of ndarray – For each query point, an array of neighbour indices.

Return type:

list[ndarray]

spectralbrain.core.base.triangle_areas(vertices, faces)[source]#

Compute per-triangle areas.

Parameters:
  • vertices (ndarray, shape (N, 3))

  • faces (ndarray, shape (F, 3))

Returns:

areas (ndarray, shape (F,)) – Area of each triangle in mm².

Return type:

ndarray