From eae8675df8deb2c4b0c73597cd34b9607a05f8a7 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 2 Jun 2026 09:24:19 -0400 Subject: [PATCH 1/4] Bump pypa/gh-action-pypi-publish in /.github/workflows (#1) Bumps [pypa/gh-action-pypi-publish](https://github.com/pypa/gh-action-pypi-publish) from 1.4.2 to 1.13.0. - [Release notes](https://github.com/pypa/gh-action-pypi-publish/releases) - [Commits](https://github.com/pypa/gh-action-pypi-publish/compare/v1.4.2...v1.13.0) --- updated-dependencies: - dependency-name: pypa/gh-action-pypi-publish dependency-version: 1.13.0 dependency-type: direct:production ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/build-main.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build-main.yml b/.github/workflows/build-main.yml index be8fe67..62bcb73 100644 --- a/.github/workflows/build-main.yml +++ b/.github/workflows/build-main.yml @@ -89,7 +89,7 @@ jobs: python -m build --sdist --wheel - name: Publish to PyPI - uses: pypa/gh-action-pypi-publish@v1.4.2 + uses: pypa/gh-action-pypi-publish@v1.13.0 with: user: __token__ password: ${{ secrets.PYPI_TOKEN }} From 3aa1ae9bb31b5d58314c63255d847887906ea3a2 Mon Sep 17 00:00:00 2001 From: Keisuke Ishihara Date: Sat, 30 May 2026 22:57:49 -0400 Subject: [PATCH 2/4] Add high-level mesh-based API for SPHARM parametrization Closes #3. Adds public entry points to compute spherical harmonics coefficients directly from a surface mesh, exposing functionality the library already implemented internally (get_shcoeffs voxelizes/re-meshes an image before fitting on mesh point coordinates). shparam.py: - get_shcoeffs_from_mesh(mesh, lmax, ...): fit directly from a vtkPolyData. - get_shcoeffs_from_vertices_faces(vertices, faces, lmax, ...): wrapper for raw numpy arrays. - Factor the shared fitting math into _get_shcoeffs_from_mesh_coords so the image and mesh paths use one implementation. Return shape matches get_shcoeffs; the image_ slot is None for mesh input. - Center on the vertex-mean centroid and align on the mesh point cloud; the caller's mesh is deep-copied so it is not mutated. shtools.py: - get_mesh_from_vertices_faces: build a triangular vtkPolyData with hard-error validation (shape, finite values, index bounds). - check_mesh_for_parametrization: warn (never raise) on non-watertight meshes (vtkFeatureEdges, after cleaning coincident points) and off-center centroids (vtkSelectEnclosedPoints). - get_alignment_angle_2d / align_points_2d: factor the PCA angle math out of align_image_2d so image and point-cloud alignment share it. Co-Authored-By: Claude Code --- README.md | 26 +++ src/aicsshparam/shparam.py | 192 ++++++++++++++++- src/aicsshparam/shtools.py | 237 ++++++++++++++++++++- src/aicsshparam/tests/test_shparam_mesh.py | 184 ++++++++++++++++ 4 files changed, 625 insertions(+), 14 deletions(-) create mode 100644 src/aicsshparam/tests/test_shparam_mesh.py diff --git a/README.md b/README.md index 5a2f5a2..80803f7 100644 --- a/README.md +++ b/README.md @@ -117,6 +117,32 @@ plt.show() ![PC1 vs. PC2](https://github.com/AllenCell/aics-shparam/blob/main/docs/pc12.png?raw=true) +## Parametrizing a mesh directly + +If you already have a surface mesh, you can compute the coefficients without +voxelizing it back into an image. Pass either a `vtkPolyData` object or raw +`vertices` + `faces` arrays: + +```python +from aicsshparam import shparam, shtools + +# From a vtkPolyData mesh: +(coeffs, grid_rec), (_, mesh, grid, transform) = shparam.get_shcoeffs_from_mesh( + mesh=mesh, lmax=4 +) + +# Or directly from numpy arrays (vertices: (N, 3), faces: (M, 3) triangles): +(coeffs, grid_rec), (_, mesh, grid, transform) = shparam.get_shcoeffs_from_vertices_faces( + vertices=vertices, faces=faces, lmax=4 +) + +mse = shtools.get_reconstruction_error(grid, grid_rec) +``` + +The return shape matches `get_shcoeffs`; the `image_` slot is `None` for mesh +input. The surface is expected to be closed and star-shaped about its centroid; +a warning (not an error) is raised when those assumptions appear to be violated. + ## Reference diff --git a/src/aicsshparam/shparam.py b/src/aicsshparam/shparam.py index 58d9cb9..e0d1a23 100644 --- a/src/aicsshparam/shparam.py +++ b/src/aicsshparam/shparam.py @@ -1,3 +1,4 @@ +import vtk import warnings import pyshtools import numpy as np @@ -131,11 +132,47 @@ def get_shcoeffs( mesh, image_, centroid = shtools.get_mesh_from_image(image=image_, sigma=sigma) if not image_[tuple([int(u) for u in centroid[::-1]])]: - warnings.warn( - "Mesh centroid seems to fall outside the object. This indicates\ + warnings.warn("Mesh centroid seems to fall outside the object. This indicates\ the mesh may not be a manifold suitable for spherical harmonics\ - parameterization." - ) + parameterization.") + + transform = centroid + ((angle,) if alignment_2d else ()) + + # Fit the SH expansion on the mesh point coordinates. The mesh is + # assumed to be centered at the origin at this point. + coeffs_dict, grid_rec, grid_down, mesh = _get_shcoeffs_from_mesh_coords(mesh, lmax) + + return (coeffs_dict, grid_rec), (image_, mesh, grid_down, transform) + + +def _get_shcoeffs_from_mesh_coords(mesh, lmax: int): + """Fit the spherical harmonics expansion on the point coordinates of a + mesh that is already centered at the origin. + + This is the shared fitting core used by both the image-based + (``get_shcoeffs``) and mesh-based (``get_shcoeffs_from_mesh``) entry + points. It extracts the mesh point coordinates, converts them to + spherical coordinates, interpolates the radius onto a regular + (lon, lat) grid and expands it with pyshtools. + + Parameters + ---------- + mesh : vtkPolyData + Mesh centered at the origin. + lmax : int + Order of the spherical harmonics parametrization. + + Returns + ------- + coeffs_dict : dict + Dictionary with the spherical harmonics coefficients. + grid_rec : ndarray + Parametric grid representing the SH parametrization. + grid_down : ndarray + Parametric grid representing the input object. + mesh : vtkPolyData + Mesh with updated point normals. + """ # Get coordinates of mesh points coords = numpy_support.vtk_to_numpy(mesh.GetPoints().GetData()) @@ -143,9 +180,7 @@ def get_shcoeffs( y = coords[:, 1] z = coords[:, 2] - transform = centroid + ((angle,) if alignment_2d else ()) - - # Translate and update mesh normals + # Update mesh normals mesh = shtools.update_mesh_points(mesh, x, y, z) # Cartesian to spherical coordinates convertion @@ -185,4 +220,145 @@ def get_shcoeffs( coeffs_dict = dict(zip(keys, coeffs.flatten())) - return (coeffs_dict, grid_rec), (image_, mesh, grid_down, transform) + return coeffs_dict, grid_rec, grid_down, mesh + + +def get_shcoeffs_from_mesh( + mesh: vtk.vtkPolyData, + lmax: int, + alignment_2d: bool = True, + make_unique: bool = False, +): + """Compute spherical harmonics coefficients that describe an object + stored as a surface mesh. + + This is the high-level entry point for users who already have a mesh + (e.g. from a meshing pipeline, CAD or simulation) and want to avoid + voxelizing it back into an image. It reuses the same fitting core as + the image-based ``get_shcoeffs``. + + The surface is represented as a single radius per direction + r(lon, lat), so it is expected to be closed and star-shaped about its + centroid. ``check_mesh_for_parametrization`` is called to warn (not + raise) when these assumptions appear to be violated. + + Parameters + ---------- + mesh : vtkPolyData + Input surface mesh. + lmax : int + Order of the spherical harmonics parametrization. The higher the + order the more shape details are represented. + alignment_2d : bool + Whether the mesh should be aligned in 2d before parametrization. + The alignment is computed on the mesh vertex point cloud (PCA of + the xy coordinates) and applied as a rotation in the xy plane, + leaving z unchanged. Default is True. + make_unique : bool + Set true to make sure the alignment rotation is unique. + + Returns + ------- + coeffs_dict : dict + Dictionary with the spherical harmonics coefficients. + grid_rec : ndarray + Parametric grid representing the SH parametrization. + image\\_ : None + Always None for mesh input; the slot is kept so the return shape + matches ``get_shcoeffs`` and callers can unpack both identically. + mesh : vtkPolyData + The centered (and optionally aligned) mesh with updated normals. + grid_down : ndarray + Parametric grid representing the input object. + transform : tuple of floats + (xc, yc, zc, angle) if alignment_2d is True or (xc, yc, zc) + otherwise. (xc, yc, zc) is the centroid of the input mesh; angle + is the rotation used to align it. + + Examples + -------- + + .. code-block:: python + + from aicsshparam import shparam, shtools + + mesh = shtools.get_mesh_from_vertices_faces(vertices, faces) + + (coeffs, grid_rec), (_, mesh, grid, transform) = + shparam.get_shcoeffs_from_mesh(mesh=mesh, lmax=2) + mse = shtools.get_reconstruction_error(grid, grid_rec) + """ + + if mesh.GetPoints() is None or mesh.GetNumberOfPoints() == 0: + raise ValueError("No mesh points found. Is the input mesh empty?") + + # Warn (without raising) on violations of the geometric assumptions. + shtools.check_mesh_for_parametrization(mesh) + + # Work on a copy so the caller's mesh is not mutated. + mesh_aligned = vtk.vtkPolyData() + mesh_aligned.DeepCopy(mesh) + mesh = mesh_aligned + + # Center the mesh on its centroid (origin), then align on the point + # cloud so the parametrization is computed in a canonical frame. + coords = numpy_support.vtk_to_numpy(mesh.GetPoints().GetData()) + centroid = tuple(coords.mean(axis=0)) + x = coords[:, 0] - centroid[0] + y = coords[:, 1] - centroid[1] + z = coords[:, 2] - centroid[2] + + if alignment_2d: + x, y, angle = shtools.align_points_2d(x=x, y=y, make_unique=make_unique) + + mesh.GetPoints().SetData(numpy_support.numpy_to_vtk(np.c_[x, y, z], deep=True)) + mesh.Modified() + + transform = centroid + ((angle,) if alignment_2d else ()) + + coeffs_dict, grid_rec, grid_down, mesh = _get_shcoeffs_from_mesh_coords(mesh, lmax) + + return (coeffs_dict, grid_rec), (None, mesh, grid_down, transform) + + +def get_shcoeffs_from_vertices_faces( + vertices: np.array, + faces: np.array, + lmax: int, + alignment_2d: bool = True, + make_unique: bool = False, +): + """Compute spherical harmonics coefficients from raw mesh arrays. + + Convenience wrapper around ``get_shcoeffs_from_mesh`` for users who + have a mesh as numpy arrays of vertices and faces rather than as a + vtkPolyData object. + + Parameters + ---------- + vertices : np.array + Array of vertex coordinates with shape (N, 3). + faces : np.array + Array of triangular faces with shape (M, 3) of vertex indices. + lmax : int + Order of the spherical harmonics parametrization. + alignment_2d : bool + Whether the mesh should be aligned in 2d. Default is True. + make_unique : bool + Set true to make sure the alignment rotation is unique. + + Returns + ------- + Same as ``get_shcoeffs_from_mesh``. + """ + + mesh = shtools.get_mesh_from_vertices_faces( + vertices=vertices, faces=faces, translate_to_origin=False + ) + + return get_shcoeffs_from_mesh( + mesh=mesh, + lmax=lmax, + alignment_2d=alignment_2d, + make_unique=make_unique, + ) diff --git a/src/aicsshparam/shtools.py b/src/aicsshparam/shtools.py index 29974ba..c1274a5 100644 --- a/src/aicsshparam/shtools.py +++ b/src/aicsshparam/shtools.py @@ -1,4 +1,5 @@ import vtk +import warnings import pyshtools import numpy as np from typing import Tuple, List @@ -10,7 +11,6 @@ from vtk.util import numpy_support as vtknp from sklearn import decomposition as skdecomp - EPS = 1e-12 @@ -132,6 +132,150 @@ def get_mesh_from_image( return mesh, img_output, tuple(centroid.squeeze()) +def get_mesh_from_vertices_faces( + vertices: np.array, + faces: np.array, + translate_to_origin: bool = True, +): + """Build a triangular vtkPolyData mesh from arrays of vertices and + faces. + + This is a convenience helper for users who have a surface mesh as raw + numpy arrays rather than as a vtkPolyData object, so they can feed it + to the mesh-based spherical harmonics parametrization. + + Parameters + ---------- + vertices : np.array + Array of vertex coordinates with shape (N, 3). + faces : np.array + Array of triangular faces with shape (M, 3), where each row holds + the three vertex indices of a triangle. + translate_to_origin : bool, optional + Whether or not to translate the mesh so its centroid sits at the + origin (0, 0, 0), default is True. + + Returns + ------- + mesh : vtkPolyData + 3d mesh in VTK format. + """ + + vertices = np.asarray(vertices) + faces = np.asarray(faces) + + # Hard errors: input that cannot be turned into a usable mesh. + if vertices.ndim != 2 or vertices.shape[1] != 3: + raise ValueError(f"Invalid vertices shape {vertices.shape}. Expected (N, 3).") + if vertices.shape[0] == 0: + raise ValueError("No vertices found. Is the input mesh empty?") + if not np.isfinite(vertices).all(): + raise ValueError("Vertices contain non-finite values (NaN or inf).") + if faces.ndim != 2 or faces.shape[1] != 3: + raise ValueError( + f"Invalid faces shape {faces.shape}. Expected (M, 3) triangular faces." + ) + if faces.shape[0] == 0: + raise ValueError("No faces found. Is the input mesh empty?") + if faces.min() < 0 or faces.max() >= vertices.shape[0]: + raise ValueError("Face indices are out of range for the provided vertices.") + + points = vtk.vtkPoints() + points.SetData(vtknp.numpy_to_vtk(vertices.astype(float), deep=True)) + + cells = vtk.vtkCellArray() + for face in faces.astype(np.int64): + cells.InsertNextCell(3) + for idx in face: + cells.InsertCellPoint(int(idx)) + + mesh = vtk.vtkPolyData() + mesh.SetPoints(points) + mesh.SetPolys(cells) + + if translate_to_origin is True: + coords = vtknp.vtk_to_numpy(mesh.GetPoints().GetData()) + centroid = coords.mean(axis=0, keepdims=True) + coords = coords - centroid + mesh.GetPoints().SetData(vtknp.numpy_to_vtk(coords, deep=True)) + + return mesh + + +def check_mesh_for_parametrization(mesh: vtk.vtkPolyData): + """Warn (without raising) when an input mesh violates the geometric + assumptions of the spherical harmonics parametrization. + + The parametrization represents the surface as a single radius per + direction r(lon, lat), which is only valid for a closed surface that + is star-shaped about its centroid. This function emits warnings for + the two cheap, mesh-native proxies of those assumptions; it never + raises, matching the library's tolerance for slightly imperfect + meshes. + + Parameters + ---------- + mesh : vtkPolyData + Surface mesh to check. + + Notes + ----- + - Watertightness is checked first with vtkFeatureEdges (counting + boundary and non-manifold edges) because the enclosed-point test + below is only meaningful on a closed surface. + - The centroid-inside test uses vtkSelectEnclosedPoints and is a + necessary-but-not-sufficient proxy for the star-shaped assumption. + """ + + # Merge coincident points first. A normals filter (e.g. the one in + # update_mesh_points) may split points at sharp edges, which would + # otherwise show up as spurious boundary/non-manifold edges below. + clean = vtk.vtkCleanPolyData() + clean.SetInputData(mesh) + clean.Update() + cleaned = clean.GetOutput() + + # Watertight / closed check. + feature_edges = vtk.vtkFeatureEdges() + feature_edges.SetInputData(cleaned) + feature_edges.BoundaryEdgesOn() + feature_edges.NonManifoldEdgesOn() + feature_edges.FeatureEdgesOff() + feature_edges.ManifoldEdgesOff() + feature_edges.Update() + + n_open_edges = feature_edges.GetOutput().GetNumberOfCells() + if n_open_edges > 0: + warnings.warn( + f"Input mesh has {n_open_edges} boundary/non-manifold edge(s) and " + "does not appear to be a closed manifold. The spherical harmonics " + "parametrization may be invalid." + ) + # The enclosed-point test is unreliable on open surfaces. + return + + # Centroid-inside check (star-shaped proxy). + coords = vtknp.vtk_to_numpy(cleaned.GetPoints().GetData()) + centroid = coords.mean(axis=0) + + centroid_points = vtk.vtkPoints() + centroid_points.InsertNextPoint(centroid[0], centroid[1], centroid[2]) + centroid_polydata = vtk.vtkPolyData() + centroid_polydata.SetPoints(centroid_points) + + enclosed = vtk.vtkSelectEnclosedPoints() + enclosed.SetInputData(centroid_polydata) + enclosed.SetSurfaceData(cleaned) + enclosed.Update() + + if not enclosed.IsInside(0): + warnings.warn( + "Mesh centroid seems to fall outside the object. This indicates " + "the mesh may not be star-shaped about its centroid and may not be " + "suitable for spherical harmonics parameterization." + ) + + def rotate_image_2d(image: np.array, angle: float, interpolation_order: int = 0): """Rotate multichannel image in 2D by a given angle. The expected shape of image is (C,Z,Y,X). The rotation will @@ -227,7 +371,45 @@ def align_image_2d( z, y, x = np.where(image[alignment_channel]) - xy = np.hstack([x.reshape(-1, 1), y.reshape(-1, 1)]) + angle = get_alignment_angle_2d(x=x, y=y, make_unique=make_unique) + + if compute_aligned_image is True: + # Apply skimage rotation clock-wise + img_aligned = rotate_image_2d(image=image, angle=angle) + + return img_aligned, angle + + return angle + + +def get_alignment_angle_2d(x: np.array, y: np.array, make_unique: bool = False): + """Compute the 2D alignment angle of a set of points via PCA. + + The angle is defined such that rotating the points by it makes the + longest (principal) axis of the 2d point cloud horizontal (along x). + This is the shared core used by both the image-based alignment + (``align_image_2d``) and the mesh/point-cloud alignment + (``align_points_2d``). + + Parameters + ---------- + x : np.array + x coordinates of the points. + y : np.array + y coordinates of the points. + make_unique : bool + Set true to make sure the alignment rotation is unique. The + principal axis is otherwise ambiguous up to a 180 degree flip; + when set, the flip is resolved using the skewness of the rotated + x coordinate so the result is deterministic. + + Returns + ------- + angle : float + Angle in degrees used to align the shape. + """ + + xy = np.hstack([np.asarray(x).reshape(-1, 1), np.asarray(y).reshape(-1, 1)]) pca = skdecomp.PCA(n_components=2) @@ -258,11 +440,54 @@ def align_image_2d( if np.abs(eigenvecs[0][0]) > EPS: angle = 180.0 * np.arctan(eigenvecs[0][1] / eigenvecs[0][0]) / np.pi - if compute_aligned_image is True: - # Apply skimage rotation clock-wise - img_aligned = rotate_image_2d(image=image, angle=angle) + return angle - return img_aligned, angle + +def align_points_2d( + x: np.array, + y: np.array, + make_unique: bool = False, + compute_aligned_points: bool = True, +): + """Align a 2d point cloud so that its longest (principal) axis is + horizontal (along x). This is the point-cloud analog of + ``align_image_2d`` and is used by the mesh-based parametrization to + reproduce the image alignment without going through an image. + + The rotation is applied in the xy plane only; any z coordinates are + left untouched by the caller, matching the 2d-alignment intent. + + Parameters + ---------- + x : np.array + x coordinates of the points. + y : np.array + y coordinates of the points. + make_unique : bool + Set true to make sure the alignment rotation is unique. + compute_aligned_points : bool + Set false to only compute and return the alignment angle. + + Returns + ------- + x_rot : np.array + Aligned x coordinates (only if compute_aligned_points is True). + y_rot : np.array + Aligned y coordinates (only if compute_aligned_points is True). + angle : float + Angle in degrees used to align the shape. + """ + + angle = get_alignment_angle_2d(x=x, y=y, make_unique=make_unique) + + if compute_aligned_points is True: + rad = np.pi * angle / 180.0 + # Rotate so the principal axis aligns with x. This matches the + # x_rot convention used inside get_alignment_angle_2d. + x_rot = x * np.cos(rad) + y * np.sin(rad) + y_rot = -x * np.sin(rad) + y * np.cos(rad) + + return x_rot, y_rot, angle return angle diff --git a/src/aicsshparam/tests/test_shparam_mesh.py b/src/aicsshparam/tests/test_shparam_mesh.py new file mode 100644 index 0000000..1d5c452 --- /dev/null +++ b/src/aicsshparam/tests/test_shparam_mesh.py @@ -0,0 +1,184 @@ +"""Tests for the mesh-based SPHARM entry points in aicsshparam.shparam. + +Covers: +- get_shcoeffs_from_mesh / get_shcoeffs_from_vertices_faces happy path +- Return-value shape matches the image path (image_ slot is None) +- Consistency with the image path on a shared mesh +- Hard-error validation for malformed vertices/faces +- Warnings for non-watertight meshes and off-center centroids +""" + +import numpy as np +import pytest +import vtk +from vtk.util import numpy_support + +from aicsshparam import shparam, shtools + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +def _sphere_vertices_faces(radius=10.0, theta_res=24, phi_res=24): + """Build a triangulated sphere as (vertices, faces) numpy arrays.""" + source = vtk.vtkSphereSource() + source.SetRadius(radius) + source.SetThetaResolution(theta_res) + source.SetPhiResolution(phi_res) + source.Update() + + tri = vtk.vtkTriangleFilter() + tri.SetInputData(source.GetOutput()) + tri.Update() + poly = tri.GetOutput() + + vertices = numpy_support.vtk_to_numpy(poly.GetPoints().GetData()) + + faces = numpy_support.vtk_to_numpy(poly.GetPolys().GetData()).reshape(-1, 4) + assert np.all(faces[:, 0] == 3), "Expected triangular faces" + faces = faces[:, 1:] + + return vertices.astype(float), faces.astype(np.int64) + + +def _sphere_image(radius=10, shape=32): + """Build a binary ZYX image containing a centered sphere.""" + zz, yy, xx = np.indices((shape, shape, shape)) + c = shape // 2 + img = ((xx - c) ** 2 + (yy - c) ** 2 + (zz - c) ** 2) <= radius**2 + return img.astype(np.uint8) + + +# --------------------------------------------------------------------------- +# Happy path +# --------------------------------------------------------------------------- + + +def test_vertices_faces_happy_path(): + vertices, faces = _sphere_vertices_faces() + + (coeffs, grid_rec), (image_, mesh, grid_down, transform) = ( + shparam.get_shcoeffs_from_vertices_faces(vertices, faces, lmax=4) + ) + + # image_ slot must be None for mesh input (shape parity with get_shcoeffs). + assert image_ is None + assert isinstance(coeffs, dict) + assert "shcoeffs_L0M0C" in coeffs + # transform carries centroid + angle when aligned. + assert len(transform) == 4 + + # A sphere should reconstruct well: L0M0C dominates, error is small. + mse = shtools.get_reconstruction_error(grid_down, grid_rec) + assert mse < 1.0 + l0 = abs(coeffs["shcoeffs_L0M0C"]) + assert l0 > 0 + # Higher-order energy is tiny relative to the mean radius term. + high = sum(abs(v) for k, v in coeffs.items() if not k.startswith("shcoeffs_L0")) + assert high < 0.1 * l0 + + +def test_alignment_2d_false_drops_angle(): + vertices, faces = _sphere_vertices_faces() + + (_, _), (_, _, _, transform) = shparam.get_shcoeffs_from_vertices_faces( + vertices, faces, lmax=2, alignment_2d=False + ) + + assert len(transform) == 3 # only the centroid, no angle + + +def test_consistency_with_image_path(): + """Feeding the image path's mesh to the mesh path should reproduce + essentially the same coefficients.""" + img = _sphere_image() + + (coeffs_img, _), (_, mesh, _, _) = shparam.get_shcoeffs(image=img, lmax=4) + + # mesh from get_shcoeffs is already centered + aligned. + (coeffs_mesh, _), (image_, _, _, _) = shparam.get_shcoeffs_from_mesh( + mesh=mesh, lmax=4 + ) + + assert image_ is None + for key in coeffs_img: + assert coeffs_mesh[key] == pytest.approx(coeffs_img[key], abs=1e-6) + + +def test_does_not_mutate_input_mesh(): + vertices, faces = _sphere_vertices_faces() + mesh = shtools.get_mesh_from_vertices_faces( + vertices, faces, translate_to_origin=False + ) + before = numpy_support.vtk_to_numpy(mesh.GetPoints().GetData()).copy() + + shparam.get_shcoeffs_from_mesh(mesh=mesh, lmax=2) + + after = numpy_support.vtk_to_numpy(mesh.GetPoints().GetData()) + np.testing.assert_array_equal(before, after) + + +# --------------------------------------------------------------------------- +# Validation: hard errors +# --------------------------------------------------------------------------- + + +def test_bad_vertices_shape_raises(): + with pytest.raises(ValueError): + shtools.get_mesh_from_vertices_faces(np.zeros((5, 2)), np.zeros((1, 3))) + + +def test_bad_faces_shape_raises(): + vertices, _ = _sphere_vertices_faces() + with pytest.raises(ValueError): + shtools.get_mesh_from_vertices_faces(vertices, np.zeros((4, 4), dtype=int)) + + +def test_out_of_range_face_index_raises(): + vertices, faces = _sphere_vertices_faces() + faces = faces.copy() + faces[0, 0] = len(vertices) + 10 + with pytest.raises(ValueError): + shtools.get_mesh_from_vertices_faces(vertices, faces) + + +def test_non_finite_vertices_raises(): + vertices, faces = _sphere_vertices_faces() + vertices = vertices.copy() + vertices[0, 0] = np.nan + with pytest.raises(ValueError): + shtools.get_mesh_from_vertices_faces(vertices, faces) + + +def test_empty_mesh_raises(): + empty = vtk.vtkPolyData() + empty.SetPoints(vtk.vtkPoints()) + with pytest.raises(ValueError): + shparam.get_shcoeffs_from_mesh(mesh=empty, lmax=2) + + +# --------------------------------------------------------------------------- +# Validation: warnings (compute still proceeds) +# --------------------------------------------------------------------------- + + +def test_open_mesh_warns(): + """A single triangle is an open surface and should warn, not raise.""" + vertices = np.array([[0, 0, 0], [10, 0, 0], [0, 10, 0]], dtype=float) + faces = np.array([[0, 1, 2]], dtype=np.int64) + mesh = shtools.get_mesh_from_vertices_faces(vertices, faces) + + with pytest.warns(UserWarning, match="closed manifold"): + shtools.check_mesh_for_parametrization(mesh) + + +def test_closed_centered_mesh_no_warning(): + vertices, faces = _sphere_vertices_faces() + mesh = shtools.get_mesh_from_vertices_faces(vertices, faces) + + import warnings as _warnings + + with _warnings.catch_warnings(): + _warnings.simplefilter("error") + shtools.check_mesh_for_parametrization(mesh) From 14d2106f3c6299b64ec7ae2a487daf376f816b06 Mon Sep 17 00:00:00 2001 From: Keisuke Ishihara Date: Sat, 30 May 2026 23:08:32 -0400 Subject: [PATCH 3/4] Document image-vs-mesh alignment difference in get_shcoeffs_from_mesh Add a Notes section clarifying that alignment_2d/make_unique behave the same as in get_shcoeffs, but the mesh path aligns on surface vertices and rotates points directly (vs. voxel-volume PCA + image rotation), so the two paths are not guaranteed to produce bit-identical orientations. Co-Authored-By: Claude Code --- src/aicsshparam/shparam.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/aicsshparam/shparam.py b/src/aicsshparam/shparam.py index e0d1a23..d8407f5 100644 --- a/src/aicsshparam/shparam.py +++ b/src/aicsshparam/shparam.py @@ -242,6 +242,25 @@ def get_shcoeffs_from_mesh( centroid. ``check_mesh_for_parametrization`` is called to warn (not raise) when these assumptions appear to be violated. + Notes + ----- + The ``alignment_2d`` and ``make_unique`` options behave the same way as + in ``get_shcoeffs``, but the alignment is computed differently and the + two paths are not guaranteed to produce bit-identical orientations for + the same object: + + - The image path runs PCA on all foreground *voxel* (x, y) coordinates + (a volume point set), rotates the *image* (with interpolation), then + re-meshes. + - This mesh path runs PCA on the *surface vertex* (x, y) coordinates + and rotates the vertices directly (no interpolation). + + The principal-axis angle formula is shared, but because the two point + sets differ the resulting angle can differ slightly. For a clean, + well-aligned object the two paths agree closely. Reproducing the image + path exactly would require voxelizing and aligning as an image, which + defeats the purpose of this entry point. + Parameters ---------- mesh : vtkPolyData From 8fc4a36362b31b17fa6685ec1e31c59d4c33983a Mon Sep 17 00:00:00 2001 From: Keisuke Ishihara Date: Tue, 2 Jun 2026 17:17:26 -0400 Subject: [PATCH 4/4] Export get_shcoeffs_from_mesh and get_shcoeffs_from_vertices_faces from package Co-Authored-By: Claude Sonnet 4.6 --- src/aicsshparam/__init__.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/aicsshparam/__init__.py b/src/aicsshparam/__init__.py index 9fb5d84..5bcdb59 100644 --- a/src/aicsshparam/__init__.py +++ b/src/aicsshparam/__init__.py @@ -8,6 +8,8 @@ # Details in CONTRIBUTING.md __version__ = "0.1.11" +from .shparam import get_shcoeffs_from_mesh, get_shcoeffs_from_vertices_faces # noqa: E402,F401 + def get_module_version(): return __version__