Metadata-Version: 2.4
Name: pykarambola
Version: 0.5.1
Summary: Python implementation of Karambola – Minkowski tensor morphometry of 3D structures
License: BSD 3-Clause License
        
        Copyright (c) 2026 Keisuke Ishihara, Yajushi Khurana
        
        Redistribution and use in source and binary forms, with or without
        modification, are permitted provided that the following conditions are met:
        
        1. Redistributions of source code must retain the above copyright notice, this
           list of conditions and the following disclaimer.
        
        2. Redistributions in binary form must reproduce the above copyright notice,
           this list of conditions and the following disclaimer in the documentation
           and/or other materials provided with the distribution.
        
        3. Neither the name of the copyright holder nor the names of its
           contributors may be used to endorse or promote products derived from
           this software without specific prior written permission.
        
        THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
        AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
        IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
        DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
        FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
        DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
        SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
        CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
        OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
        OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
        
Project-URL: Homepage, https://github.com/Ishihara-SynthMorph/pykarambola
Project-URL: Documentation, https://github.com/Ishihara-SynthMorph/pykarambola#readme
Project-URL: Bug Tracker, https://github.com/Ishihara-SynthMorph/pykarambola/issues
Keywords: minkowski,tensors,bioimage,morphometry,3d-shape-analysis,mesh,geometry,surface-analysis,computational-geometry,shape-descriptor,materials-science,minkowski-functionals,triangulated-surface,image-analysis
Classifier: License :: OSI Approved :: BSD License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
Classifier: Topic :: Scientific/Engineering :: Image Processing
Classifier: Topic :: Scientific/Engineering :: Mathematics
Classifier: Topic :: Scientific/Engineering :: Physics
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.22
Requires-Dist: scipy>=1.8
Provides-Extra: dev
Requires-Dist: pytest; extra == "dev"
Requires-Dist: scikit-image>=0.19; extra == "dev"
Provides-Extra: accel
Requires-Dist: cython>=3.0; extra == "accel"
Provides-Extra: glb
Requires-Dist: trimesh; extra == "glb"
Provides-Extra: stl
Requires-Dist: numpy-stl; extra == "stl"
Provides-Extra: notebooks
Requires-Dist: scikit-image>=0.19; extra == "notebooks"
Requires-Dist: matplotlib; extra == "notebooks"
Requires-Dist: seaborn; extra == "notebooks"
Requires-Dist: pandas; extra == "notebooks"
Requires-Dist: medmnist; extra == "notebooks"
Requires-Dist: tifffile; extra == "notebooks"
Requires-Dist: scikit-learn; extra == "notebooks"
Requires-Dist: pooch; extra == "notebooks"
Dynamic: license-file

# pykarambola
<!-- CI badge disabled: GitHub Actions disabled at org level -->
<!-- [![CI](https://github.com/Ishihara-SynthMorph/pykarambola/actions/workflows/ci.yml/badge.svg)](https://github.com/Ishihara-SynthMorph/pykarambola/actions/workflows/ci.yml) -->
[![PyPI version](https://img.shields.io/pypi/v/pykarambola)](https://pypi.org/project/pykarambola/)
[![Python versions](https://img.shields.io/pypi/pyversions/pykarambola)](https://pypi.org/project/pykarambola/)
[![License: BSD-3-Clause](https://img.shields.io/badge/License-BSD_3--Clause-blue.svg)](https://opensource.org/licenses/BSD-3-Clause)

**pykarambola** computes Minkowski tensors for 3D objects represented as triangulated meshes — a family of shape descriptors rooted in integral geometry that rigorously quantify size, shape, and orientation.

<p align="center">
  <img src="assets/banner.png" alt="pykarambola — Minkowski tensor morphometry of 3D structures" width="75%"/>
</p>

Given a mesh, it returns scalar, vector, and tensor quantities including volume, surface area, integrated mean curvature, and Euler characteristic (the Minkowski functionals), as well as higher-rank tensors that capture anisotropy and preferred orientation independently of coordinate frame.
pykarambola is a Python implementation of [karambola](https://github.com/morphometry/karambola), the reference C++ package for Minkowski tensor computation on 3D triangulated surfaces.
Minkowski tensors are widely applicable to analyzing 3D structures in biomedical imaging, astrophysics, and materials science.
For background, see [Schroder-Turk et al. (2013)](https://doi.org/10.1088/1367-2630/15/8/083028), [Mickel et al. (2013)](https://doi.org/10.1063/1.4774084), and [morphometry.org](https://morphometry.org/).

### End-to-end pipeline: confocal nuclei → segmentation → shape clustering

<table align="center">
  <tr>
    <td align="center"><img src="assets/demo_raw.png" width="220"/><br/><sub>Raw confocal (nuclei channel)</sub></td>
    <td align="center"><img src="assets/demo_segmented.png" width="220"/><br/><sub>Segmented nuclei</sub></td>
  </tr>
  <tr>
    <td align="center"><img src="assets/demo_pca_full.png" width="220"/><br/><sub>PCA — scalars + β + eigvals + trace + msm</sub></td>
    <td align="center"><img src="assets/demo_mesh_full.png" width="220"/><br/><sub>Meshes coloured by cluster</sub></td>
  </tr>
</table>

## New in pykarambola

Compared to the original C++ karambola, this Python port adds:

- **OBJ, GLB, and STL parsers** — read Wavefront OBJ, binary glTF (`.glb`), and STL (ASCII and binary) meshes directly via `parse_stl_file()`, in addition to the original `.poly` and `.off` formats.
- **High-level API** — `minkowski_tensors()` accepts NumPy arrays and returns a plain dict, making it easy to integrate into pipelines without dealing with the lower-level triangulation types.
- **`labels='auto'`** — pass `labels='auto'` to detect connected mesh components automatically and compute tensors for each body separately, without supplying a face-label array.
- **`return_count=True`** — append the number of connected objects to the return value as a `(results, n_objects)` tuple.
- **Derived scalar quantities** — each rank-2 tensor (e.g. `w020`) additionally yields `{name}_beta` (anisotropy index: ratio of smallest to largest eigenvalue magnitude), `{name}_trace` (matrix trace), and `{name}_trace_ratio` (trace divided by the corresponding Minkowski scalar, e.g. `w020_trace_ratio = Tr(w020) / w000`).
  These are pykarambola-specific extensions not present in C++ karambola; they are included in the `compute='all'` preset.
- **Label-image API** — `minkowski_tensors_from_label_image()` extracts surfaces from a 3D integer label image via marching cubes and computes tensors for every label in one call.

## Requirements

- Python ≥ 3.9
- [NumPy](https://numpy.org/)
- [SciPy](https://scipy.org/)

**Optional:**
- [Cython](https://cython.org/) ≥ 3.0 — compiled C acceleration (`pip install "pykarambola[accel]"`)
- [scikit-image](https://scikit-image.org/) — label-image API (`pip install "pykarambola[notebooks]"`)
- [trimesh](https://trimesh.org/) — GLB/glTF file support (`pip install "pykarambola[glb]"`)
- [numpy-stl](https://github.com/WoLpH/numpy-stl) — STL file support (`pip install "pykarambola[stl]"`)

## Installation

```bash
pip install pykarambola
```

For optional Cython acceleration:

```bash
pip install "pykarambola[accel]"
```

For development (includes pytest and scikit-image):

```bash
pip install "pykarambola[dev]"
```

To run the example notebooks (includes scikit-image and tifffile):

```bash
pip install "pykarambola[notebooks]"
```

GLB/glTF support requires [trimesh](https://trimesh.org/):

```bash
pip install "pykarambola[glb]"
```

You can combine extras in a single install:

```bash
pip install "pykarambola[dev,notebooks,accel]"
```

## High-level API

### From NumPy arrays

`minkowski_tensors()` is the main entry point. Pass vertices and faces as NumPy arrays and get back a plain dict:

```python
import pykarambola as pk

result = pk.minkowski_tensors(
    verts,   # (V, 3) float64 array of vertex positions
    faces,   # (F, 3) int64 array of vertex indices
)

print(result["w000"])   # volume
print(result["w100"])   # surface area
print(result["w200"])   # integrated mean curvature
print(result["w300"])   # Euler characteristic
print(result["w020"])   # 3×3 Minkowski tensor
print(result["w020_eigvals"])   # eigenvalues of w020
print(result["w020_eigvecs"])   # eigenvectors of w020 (columns)
```

Control which quantities are computed with the `compute` argument:

```python
# default: 14 standard tensors + eigensystems for rank-2 tensors
result = pk.minkowski_tensors(verts, faces, compute="standard")

# include higher-order tensors (w103, w104) and spherical Minkowski metrics
result = pk.minkowski_tensors(verts, faces, compute="all")

# compute only specific quantities
result = pk.minkowski_tensors(verts, faces, compute=["w000", "w100", "w020"])
```

If the mesh has boundary edges (open surface), `w000` and `w020` are set to `NaN` and a `UserWarning` is emitted. Non-manifold meshes also emit a `UserWarning` but are otherwise computed.

### From a 3D label image

`minkowski_tensors_from_label_image()` takes a 3D integer array, runs marching cubes on each label, and returns a dict of results keyed by label value. Requires [scikit-image](https://scikit-image.org/).

```python
import numpy as np
import pykarambola as pk

label_image = np.zeros((64, 64, 64), dtype=int)
label_image[10:40, 10:40, 10:40] = 1
label_image[40:60, 40:60, 40:60] = 2

result = pk.minkowski_tensors_from_label_image(
    label_image,
    spacing=(0.5, 0.5, 0.5),   # voxel size in physical units
    center="centroid_mesh",     # shift tensors to per-label centroid
)

print(result[1]["w000"])   # volume of label 1
print(result[2]["w100"])   # surface area of label 2
```

By default a 1-voxel zero border is added before running marching cubes (`pad=True`), so objects touching the array boundary produce closed surfaces. Pass `pad=False` to skip this.

The `center` argument controls the reference point for position-dependent tensors:

| Value | Behaviour |
|-------|-----------|
| `None` (default for mesh API) | Use the array origin `(0, 0, 0)` |
| `'centroid_mesh'` (default for label-image API) | Shift each object to its volume-weighted centre of mass |
| `'centroid_voxel'` | Use the mean voxel coordinate (label-image API only) |
| `'reference_centroid'` | Reproduce the C++ karambola `--reference_centroid` flag |
| `(3,)` array | Apply an explicit fixed shift |

### Multi-label meshes

Pass per-face integer labels to compute tensors for multiple bodies in a single mesh:

```python
result = pk.minkowski_tensors(verts, faces, labels=face_labels)
# result is dict[int, dict]
print(result[1]["w000"])
print(result[2]["w000"])
```

Or let pykarambola detect connected components automatically:

```python
result = pk.minkowski_tensors(verts, faces, labels="auto")
# bodies are numbered 1, 2, … by connected component
print(result[1]["w000"])
```

## Example notebooks

| Notebook | What it covers |
|----------|----------------|
| [`examples/demo.ipynb`](examples/demo.ipynb) | A hands-on tour of the mesh API: passing vertices and faces as NumPy arrays, supplying per-face labels or using `labels='auto'` to separate connected bodies, retrieving the object count with `return_count`, and computing derived scalars (`_beta`, `_trace`, `_trace_ratio`) |
| [`examples/segmentation_workflow.ipynb`](examples/segmentation_workflow.ipynb) | End-to-end pipeline: confocal stack → segmentation → Minkowski tensors → PCA + clustering |
| [`examples/multilabel_image_workflow.ipynb`](examples/multilabel_image_workflow.ipynb) | Working with 3D segmentation images: measures whole-cell morphology from a single label, compares nucleus and cell body separately using two labels, and runs per-nuclear object anisotropy analysis across three connected components from a real AllenCell hiPSC dataset |
| [`examples/minkowski_additivity.ipynb`](examples/minkowski_additivity.ipynb) | How the `center` parameter affects additivity of Minkowski tensors; when per-body vs. global centering matters |
| [`examples/parallel_processing.ipynb`](examples/parallel_processing.ipynb) | Parallel tensor computation with `joblib`: sequential baseline, multi-core speedup, keyword arguments, and processing mesh files in bulk |

## File I/O

pykarambola can read four mesh formats. The parsers return a `Triangulation` object that can be passed directly to `minkowski_tensors()`.

```python
surface = pk.parse_poly_file("my_surface.poly")   # karambola native
surface = pk.parse_off_file("my_surface.off")     # Object File Format
surface = pk.parse_obj_file("my_surface.obj")     # Wavefront OBJ  (new)
surface = pk.parse_glb_file("my_surface.glb")     # binary glTF    (new, requires trimesh)
surface = pk.parse_stl_file("my_surface.stl")     # STL ASCII/binary (new, requires numpy-stl)

result = pk.minkowski_tensors(surface)
```

| Extension | Description |
|-----------|-------------|
| `.poly`   | karambola native format |
| `.off`    | Object File Format |
| `.obj`    | Wavefront OBJ |
| `.glb`    | GL Transmission Format (binary glTF) — requires `trimesh` |
| `.stl`    | STereoLithography (ASCII and binary) — requires `numpy-stl` |

## Command-line interface

```
python -m pykarambola [options] <surface_file>
```

Supported input formats: `.poly`, `.off`, `.obj`, `.glb`, `.stl`.
Run `python -m pykarambola --help` for the full list of options.

## Computed quantities

All quantities below are returned by `compute='standard'` unless noted `(compute='all')`.

> **Normalization convention.** pykarambola follows the karambola/Hadwiger convention in which
> each Minkowski functional carries a factor of 1/3: `w100` = surface area / 3,
> `w200` = integrated mean curvature / 3, `w300` = 2π χ / 3.
> Recover physical quantities as `A = 3·w100`, `M = 3·w200`, `χ = 3·w300 / (2π)`.
> For full mathematical definitions, discrete formulas, and normalization derivations see
> [`docs/minkowski_tensors.md`](docs/minkowski_tensors.md).

| Name | Type | Description |
|------|------|-------------|
| `w000` | scalar | Volume |
| `w100` | scalar | Surface area / 3 |
| `w200` | scalar | Integrated mean curvature / 3 |
| `w300` | scalar | 2π × Euler characteristic / 3 |
| `w010` | vector | Minkowski vector (volume) |
| `w110` | vector | Minkowski vector (surface) |
| `w210` | vector | Minkowski vector (curvature) |
| `w310` | vector | Minkowski vector (topology) |
| `w020` | rank-2 tensor | Minkowski tensor (volume) |
| `w120` | rank-2 tensor | Minkowski tensor (surface) |
| `w220` | rank-2 tensor | Minkowski tensor (curvature) |
| `w320` | rank-2 tensor | Minkowski tensor (topology) |
| `w102` | rank-2 tensor | Minkowski tensor (surface, normal-normal) |
| `w202` | rank-2 tensor | Minkowski tensor (curvature, normal-normal) |
| `w103` | rank-3 tensor | Higher-order tensor (`compute='all'`) |
| `w104` | rank-4 tensor | Higher-order tensor (`compute='all'`) |
| `msm_ql`, `msm_wl` | arrays | Minkowski structure metrics (spherical, `compute='all'`) |
| `{name}_beta` | scalar | Anisotropy index: min\|λ\| / max\|λ\| for each rank-2 tensor (`compute='all'`) |
| `{name}_trace` | scalar | Trace of each rank-2 tensor matrix (`compute='all'`) |
| `{name}_trace_ratio` | scalar | Trace divided by corresponding Minkowski scalar, e.g. `Tr(w020)/w000` (wX20 family only; `compute='all'`) |

Rank-2 tensors additionally yield `{name}_eigvals` and `{name}_eigvecs` entries.

## FAQ

**My mesh is not water-tight. What should I do?**

pykarambola will still run on open (non-water-tight) meshes and will emit a `UserWarning` listing the affected labels.
Volume-dependent quantities (`w000`, `w020`) are set to `NaN` for open labels because the divergence theorem requires a closed surface to define volume unambiguously.
All other quantities — surface area (`w100`), curvature integrals (`w200`, `w300`), and their associated vectors and tensors — remain valid and are computed normally.

If you need volume, the recommended fix is to close the surface before calling pykarambola.
Common tools for this are [PyMeshFix](https://github.com/pyvista/pymeshfix) (`pymeshfix.MeshFix(verts, faces).repair()`) and [Open3D](http://www.open3d.org/) (`mesh.fill_holes()`).
Alternatively, if your mesh comes from a 3D label image, use `minkowski_tensors_from_label_image` directly — it always produces closed surfaces via marching cubes and automatically pads the image at boundaries to prevent open surfaces.

**I have point cloud data. Can I use pykarambola?**

Not directly — pykarambola requires a triangulated surface mesh (vertex array + face array), not raw point positions.
You first need to reconstruct a surface from your point cloud.
[Open3D](http://www.open3d.org/) provides two common approaches: Poisson surface reconstruction (`o3d.geometry.TriangleMesh.create_from_point_cloud_poisson`) for smooth, water-tight surfaces, and ball-pivoting (`create_from_point_cloud_ball_pivoting`) for locally faithful but potentially open surfaces.
Once you have a mesh, pass its vertex and face arrays to `minkowski_tensors(verts, faces)` directly.

## Citation

If you use pykarambola in your work, please cite pykarambola and Schröder-Turk group's publication on Minkowski tensors:

> Ishihara, K., & Khurana, Y.
> *pykarambola: Minkowski tensor morphometry of 3D structures* (v0.5.0).
> https://doi.org/10.5281/zenodo.20418801

> Schröder-Turk, G. E., Mickel, W., Kapfer, S. C., Schaller, F. M., Breidenbach, B., Hug, D., & Mecke, K.
> *Minkowski tensors of anisotropic spatial structure.*
> *New Journal of Physics*, 15, 083028 (2013).
> https://doi.org/10.1088/1367-2630/15/8/083028

## Contributing

See [`CONTRIBUTING.md`](CONTRIBUTING.md) for development setup, Git workflow, versioning, and release instructions.
See [`CHANGELOG.md`](CHANGELOG.md) for a history of changes between versions.

## License

pykarambola is released under the [BSD 3-Clause License](LICENSE).

The authors of [karambola](https://github.com/morphometry/karambola) — Schaller, Kapfer, and Schröder-Turk — kindly agreed to pykarambola being distributed under the BSD 3-Clause License.
