Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/build-main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }}
26 changes: 26 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 2 additions & 0 deletions src/aicsshparam/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__
211 changes: 203 additions & 8 deletions src/aicsshparam/shparam.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import vtk
import warnings
import pyshtools
import numpy as np
Expand Down Expand Up @@ -131,21 +132,55 @@ 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())
x = coords[:, 0]
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
Expand Down Expand Up @@ -185,4 +220,164 @@ 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.

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
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,
)
Loading