Metadata-Version: 2.5
Name: kintsugi-st
Version: 0.2.0
Summary: Adaptive spatial tessellation for sub-cellular resolution transcriptomics
Project-URL: Homepage, https://github.com/cafferychen777/kintsugi
Project-URL: Repository, https://github.com/cafferychen777/kintsugi
Project-URL: Issues, https://github.com/cafferychen777/kintsugi/issues
Project-URL: Documentation, https://github.com/cafferychen777/kintsugi#readme
Author: Kintsugi authors
Maintainer: Kintsugi authors
License: MIT License
        
        Copyright (c) 2026 Kintsugi authors
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
License-File: LICENSE
Keywords: segmentation,spatial transcriptomics,tessellation,visium hd
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
Requires-Python: >=3.10
Requires-Dist: anndata>=0.10
Requires-Dist: h5py>=3.10
Requires-Dist: numpy>=1.24
Requires-Dist: pandas>=2.0
Requires-Dist: pyarrow>=14.0
Requires-Dist: scipy>=1.11
Provides-Extra: dev
Requires-Dist: pytest-cov>=5.0; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Description-Content-Type: text/markdown

# Kintsugi

Kintsugi builds adaptive tissue regions for subcellular spatial transcriptomics.
It takes a regular grid of UMI counts, follows local changes in captured
transcript density, and returns region-level measurements for downstream
analysis.

The package is meant to sit between raw binned counts and biological analysis.
It does not perform clustering, marker testing, plotting, or manuscript-specific
analysis. Those choices stay downstream, usually in Scanpy, Squidpy, or another
AnnData-based workflow.

## Install

Install the current source:

```bash
python -m pip install git+https://github.com/cafferychen777/kintsugi.git
```

Then import the Python package:

```python
import kintsugi
```

From a source checkout or reviewer archive:

```bash
python -m pip install .
```

The PyPI distribution name is `kintsugi-st` because `kintsugi` is a different
package on PyPI. Do not use `pip install kintsugi` for this project. If
installing from PyPI after a public release:

```bash
python -m pip install kintsugi-st
```

For editable development:

```bash
python -m pip install -e ".[dev]"
```

## Quick Check

After installation, run the bundled command-line demo:

```bash
kintsugi-demo
```

It generates a small synthetic grid, runs tessellation, prints a diagnostic
report, and exports the result to AnnData. A successful run ends with output
like:

```text
4. AnnData export:
   Shape: (67, 100)
   obs:   ['area', 'depth']
   obsm:  ['spatial']
   obsp:  ['adjacency']
   layers: ['counts']

Done.
```

`kintsugi-demo` is an installed command, not a second package.

## Typical Workflow

For a 10x Genomics Space Ranger output directory:

```text
sample/
├── filtered_feature_bc_matrix.h5
└── spatial/
    └── tissue_positions.parquet
```

run:

```python
import kintsugi

grid = kintsugi.load_visium_hd_from_dir("sample/")
result = grid.tessellate()

print(kintsugi.tessellation_report(result, grid))

adata = kintsugi.to_anndata(result, grid=grid, use_raw_counts=True)
adata.write("kintsugi_regions.h5ad")
```

The returned AnnData object uses:

| Field | Content |
| --- | --- |
| `adata.X` | Region-level Pearson residuals |
| `adata.obs["area"]` | Number of grid bins in each region |
| `adata.obs["depth"]` | Total UMI depth in each region |
| `adata.obsm["spatial"]` | Region centroids as `(row, col)` coordinates |
| `adata.obsp["adjacency"]` | Spatial adjacency graph between regions |
| `adata.layers["counts"]` | Raw aggregated UMI counts when `use_raw_counts=True` |

If the count matrix and tissue positions are in non-standard locations:

```python
grid = kintsugi.load_visium_hd(
    "path/to/filtered_feature_bc_matrix.h5",
    "path/to/tissue_positions.parquet",
)
```

## Input Format

Kintsugi operates on a normalized grid:

- `counts`: SciPy sparse matrix with shape `(rows * cols, genes)`.
- `rows`, `cols`: dimensions of the 2D grid.
- `mask`: optional boolean array with shape `(rows, cols)`, where `True` marks
  in-tissue bins.
- Matrix rows are in row-major order: row `r * cols + c` corresponds to grid
  bin `(r, c)`.
- Count values must be finite and non-negative.

`GridData` is the package container for this format.

For regular-grid data that are not in 10x Visium HD layout:

```python
grid = kintsugi.build_regular_grid(
    counts,      # sparse matrix with one row per occupied bin
    row_coords,  # row coordinate for each occupied bin
    col_coords,  # column coordinate for each occupied bin
    rows=R,
    cols=C,
)
result = grid.tessellate()
```

## Parameters

The default parameters target 8 micrometre Visium HD grids.

| Parameter | Default | Meaning |
| --- | --- | --- |
| `lag` | `2` | Grid offset for directional semivariance. On a 2 micrometre grid, `lag=2` is a 4 micrometre offset. |
| `kappa` | `2.0` | Stationarity tolerance during region refinement, in standard-error units. Larger values allow broader regions. |
| `min_seed_distance` | `4` | Minimum distance between seed points in grid bins. Larger values produce fewer, larger regions. |
| `smooth_sigma` | `4.0` | Gaussian sigma for smoothing the trace field before seed detection. Larger values favor smoother boundaries. |

For very small synthetic grids, use smaller `min_seed_distance` and
`smooth_sigma` values.

## API Overview

Most users need these functions:

- `kintsugi.load_visium_hd_from_dir(...)`: load a Space Ranger output directory.
- `kintsugi.load_visium_hd(...)`: load a feature matrix and tissue-position file.
- `kintsugi.build_regular_grid(...)`: build a grid from custom coordinates.
- `kintsugi.tessellate(...)`: run the full tessellation pipeline.
- `kintsugi.tessellation_report(...)`: summarize region diagnostics.
- `kintsugi.to_anndata(...)`: export regions to AnnData.

Lower-level functions are also available for method development:

- `directional_semivariance`
- `boundary_tensor`
- `adaptive_tessellation`
- `aggregate_counts`
- `build_spatial_graph`

## Requirements

- Python 3.10, 3.11, or 3.12.
- NumPy, SciPy, h5py, pandas, PyArrow, and AnnData.
- No GPU is required.

Memory use depends mainly on the number of regions and genes, because Kintsugi
stores a dense region-by-gene residual matrix. Filtering uninformative genes
upstream is the main lever for very large datasets.

## Containers

Docker:

```bash
docker build -t kintsugi .
docker run --rm kintsugi
```

Singularity or Apptainer:

```bash
singularity build kintsugi.sif Singularity.def
singularity run kintsugi.sif
```

## Development Checks

```bash
python -m ruff check kintsugi tests
python -m pytest --cov=kintsugi --cov-report=term-missing
```

## Citation

If you use Kintsugi in your research, please cite the associated manuscript when
it becomes available.

## License

Kintsugi is released under the [MIT License](LICENSE).
