Metadata-Version: 2.5
Name: jaxscape
Version: 0.0.19
Summary: A minimal JAX library for connectivity modelling at scale
Project-URL: Documentation, https://github.com/vboussange/jaxscape#readme
Project-URL: Issues, https://github.com/vboussange/jaxscape/issues
Project-URL: Source, https://github.com/vboussange/jaxscape
Author-email: Victor Boussange <vic.boussange@gmail.com>
License: MIT License
        
        Copyright (c) 2024-present Victor Boussange <vic.boussange@gmail.com>
        
        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: graph,jax,machine-learning,network
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: Intended Audience :: Information Technology
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Natural Language :: English
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
Classifier: Topic :: Scientific/Engineering :: GIS
Classifier: Topic :: Scientific/Engineering :: Information Analysis
Classifier: Topic :: Scientific/Engineering :: Mathematics
Requires-Python: >=3.12
Requires-Dist: equinox>=0.13.2
Requires-Dist: jax>=0.11
Requires-Dist: lineax>=0.1.0
Requires-Dist: numpy>2.4.0
Requires-Dist: tqdm>=4.66.1
Provides-Extra: amjax
Requires-Dist: amjax<0.1,>=0.0.3; extra == 'amjax'
Requires-Dist: pyamg>=5.1.0; extra == 'amjax'
Provides-Extra: cholespy
Requires-Dist: cholespy>=2.2.0; extra == 'cholespy'
Provides-Extra: cuda
Requires-Dist: jax[cuda]>=0.11; extra == 'cuda'
Provides-Extra: cudss
Requires-Dist: nvidia-cudss-cu13<1,>=0.8; (python_version >= '3.12' and sys_platform == 'linux' and platform_machine == 'x86_64') and extra == 'cudss'
Requires-Dist: spineax==0.0.5; (python_version >= '3.12' and sys_platform == 'linux' and platform_machine == 'x86_64') and extra == 'cudss'
Provides-Extra: dev
Requires-Dist: ipykernel>=6.29.5; extra == 'dev'
Provides-Extra: docs
Requires-Dist: mkdocs-include-exclude-files==0.1.0; extra == 'docs'
Requires-Dist: mkdocs-ipynb==0.1.1; extra == 'docs'
Requires-Dist: mkdocs-material>=9.5.0; extra == 'docs'
Requires-Dist: mkdocs>=1.5.0; extra == 'docs'
Requires-Dist: mkdocstrings[python]>=0.24.0; extra == 'docs'
Requires-Dist: pymdown-extensions>=10.7.0; extra == 'docs'
Provides-Extra: examples
Requires-Dist: flax; extra == 'examples'
Requires-Dist: geopandas; extra == 'examples'
Requires-Dist: matplotlib; extra == 'examples'
Requires-Dist: optimistix; extra == 'examples'
Requires-Dist: rioxarray; extra == 'examples'
Requires-Dist: scikit-learn; extra == 'examples'
Provides-Extra: lint
Requires-Dist: pre-commit>=4.0; extra == 'lint'
Requires-Dist: pyright[nodejs]==1.1.414; extra == 'lint'
Requires-Dist: ruff==0.17.4; extra == 'lint'
Provides-Extra: tests
Requires-Dist: networkx>=3.4; extra == 'tests'
Requires-Dist: pytest-xdist>=3.6; extra == 'tests'
Requires-Dist: pytest>=8.3.5; extra == 'tests'
Description-Content-Type: text/markdown

<!-- docs:exclude-start -->
[![tests](https://github.com/vboussange/jaxscape/actions/workflows/run_tests.yml/badge.svg)](https://github.com/vboussange/jaxscape/actions/workflows/run_tests.yml)
[![Build documentation](https://github.com/vboussange/jaxscape/actions/workflows/build_docs.yml/badge.svg)](https://github.com/vboussange/jaxscape/actions/workflows/build_docs.yml)
[![DOI](https://zenodo.org/badge/883274673.svg)](https://doi.org/10.5281/zenodo.15267703)
<!-- docs:exclude-end -->

<div align="center">
  <img src="docs/examples/logo/logo.gif" alt="JAXScape logo: corridors restored through the letters of JAXscape" width="832">
  <p><sub>Generated by <a href="docs/examples/logo/make_logo.py"><code>make_logo.py</code></a>.</sub></p>
</div>

---

JAXScape is a minimal JAX library for connectivity modelling at scale. It provides the building blocks of a connectivity analysis workflow:

- differentiable and GPU-accelerated distances on graphs
- differentiable raster-to-graph and graph-to-raster mappings
- moving-window utilities for connectivity analyses of large rasters

JAXScape runs on CPUs, GPUs and TPUs through JAX. Its computations are differentiable, for sensitivity analysis and optimization, and it implements its own linear solvers and differentiation rules where JAX provides none.

## Why JAXScape?

<!-- Update this section from each published benchmark run: docs/agents/benchmark-table.md -->

The table marks the quantities that each package computes.

| Package | Distance on a graph: least-cost path | Distance on a graph: resistance | Distance on a graph: free energy | Connected habitat | Movement corridors and pinch points |
| --- | :-: | :-: | :-: | :-: | :-: |
| **JAXScape** | ✓ | ✓ | ✓ | ✓ | ✓ |
| [Circuitscape.jl](https://github.com/Circuitscape/Circuitscape.jl) |  | ✓ |  |  | ✓ |
| [Omniscape.jl](https://github.com/Circuitscape/Omniscape.jl) |  |  |  |  | ✓ |
| [gdistance](https://cran.r-project.org/package=gdistance) | ✓ | ✓ |  |  | ✓ |
| [ConScape.jl](https://conscape.org) | ✓ |  | ✓ | ✓ | ✓ |
| [skimage.graph.MCP](https://scikit-image.org/docs/stable/api/skimage.graph.html#skimage.graph.MCP) | ✓ |  |  |  |  |
| [Graphab](https://thema.umlp.fr/productions/software/graphab/en/home.html) | ✓ | ✓ |  | ✓ | ✓ |
| [Conefor](http://www.conefor.org/) |  |  |  | ✓ |  |
| [eco-connectivity](https://github.com/csiro/connectivity) |  |  |  | ✓ |  |
| [EcoScape](https://github.com/ecoscape-earth/ecoscape-connectivity) |  |  |  |  | ✓ |
| [samc](https://cran.r-project.org/package=samc) |  |  |  |  | ✓ |
| **Smallest speed-up of JAXScape over another package** | 1.2x over skimage.graph.MCP | 24x over Circuitscape.jl | 2.2x over ConScape.jl | 0.57x over Graphab (on habitat patches) | 5.2x over Omniscape.jl |

Speed-up: the smallest speed-up of JAXScape on one GPU over another package in the benchmark of JAXScape 0.0.16, that is, the warm runtime of the package divided by that of JAXScape, each in its fastest setting on the largest synthetic raster that both completed, with JAXScape under the distance or setting with which the benchmark compares the package. The [benchmark page](https://vboussange.github.io/jaxscape/benchmark/) of the [documentation](https://vboussange.github.io/jaxscape/) details the comparison.

[ilg-toolkit](https://github.com/vboussange/ilg-toolkit) builds on JAXScape for **inverse landscape genetics**, the inference of landscape permeability from geolocated molecular data. It works with the JAX scientific machine learning ecosystem, including [Equinox](https://github.com/patrick-kidger/equinox) and [Flax](https://github.com/google/flax), whose layers can be used to build neural networks that map landscape features to permeability. [ResistanceGA](https://github.com/wpeterman/ResistanceGA) (genetic algorithm) and [radish](https://github.com/nspope/radish) (gradient-based optimization) address the same problem.

## Installation

```console
uv add jaxscape
```

The default installation is CPU-only. For NVIDIA GPUs, use `uv add 'jaxscape[cuda]'`, or install JAX following the [official JAX installation guide](https://jax.readthedocs.io/en/latest/installation.html). JAXScape will automatically use the JAX backend you have configured.

Least-cost path and resistance distances on rasters work with the default installation. Free-energy distances on large rasters, and resistance or free-energy distances on large graphs that are not rasters, such as networks of habitat patches, need an optional linear solver. See [Linear solvers](https://vboussange.github.io/jaxscape/api/linear_solvers/).

## Quick start

**1. Download sample data**

```bash
curl -sL https://github.com/vboussange/jaxscape/releases/download/v0.0.6/data.zip -o data.zip && unzip -q data.zip && rm data.zip
```

**2. Run the analysis**

```python
import jax.numpy as jnp
import matplotlib.pyplot as plt
import numpy as np
from jaxscape import FreeEnergyDistance, GridGraph, LCPDistance, ResistanceDistance

permeability = jnp.array(
    np.loadtxt("data/permeability.csv", delimiter=","), dtype=jnp.float32
) + 0.01
barriers = np.asarray(permeability <= 0.1)

# Symmetric conductances are the mean permeability of neighbouring cells.
grid = GridGraph(grid=permeability, fun=lambda x, y: (x + y) / 2)

# Compute distances from the top-left pixel to every other pixel.
source = grid.coord_to_index(jnp.array([0]), jnp.array([0]))
distances = {
    "Least-cost path": LCPDistance()(grid, sources=source),
    "Resistance": ResistanceDistance()(grid, sources=source),
    r"Free energy, $\theta = 0.03$": FreeEnergyDistance(theta=0.03)(grid, sources=source),
}

distance_cmap = plt.cm.magma.copy()
distance_cmap.set_bad(color="lightgray")

fig, axs = plt.subplots(1, 4, figsize=(12, 3.3))

permeability_im = axs[0].imshow(permeability, cmap="gray", vmin=0, vmax=1)
axs[0].set_xticks([])
axs[0].set_yticks([])
for spine in axs[0].spines.values():
    spine.set_visible(True)
axs[0].set_title("Permeability")
fig.colorbar(permeability_im, ax=axs[0], shrink=0.2)

for ax, (title, dist_to_node) in zip(axs[1:], distances.items()):
    # Convert from node values to a 2D array and hide barrier cells
    dist_array = np.asarray(grid.node_values_to_array(dist_to_node.ravel()))
    dist_array = np.ma.masked_where(barriers, dist_array)

    # Plotting
    im = ax.imshow(dist_array, cmap=distance_cmap)
    ax.axis("off")
    ax.set_title(title)
    fig.colorbar(im, ax=ax, shrink=0.2)

fig.suptitle("Distance from the top-left pixel")
plt.tight_layout()
plt.show()
```

`theta` is the inverse temperature of the free-energy distance: larger values
bring it closer to the least-cost path distance. For other graphs and larger
landscapes, see [Linear solvers](https://vboussange.github.io/jaxscape/api/linear_solvers/)
for the choice of solver.

<div align="center"><img src="docs/examples/distance_calculation/distances.png" alt="Distances"  width="600"></div>

These distances are differentiable: `jax.grad` of a scalar function of them,
such as their mean, gives its derivative with respect to the permeability of
every pixel. The
[distance calculation example](https://vboussange.github.io/jaxscape/examples/distance_calculation/distance_calculation/)
maps this derivative.

<!-- docs:exclude-start -->
## Documentation

The documentation is at [https://vboussange.github.io/jaxscape](https://vboussange.github.io/jaxscape/).

<!-- docs:exclude-end -->

## Contributing

See [CONTRIBUTING.md](CONTRIBUTING.md).

## Benchmarking

JAXScape includes a benchmark workspace that profiles JAXScape's own
implementations and compares them with other landscape connectivity software.
The [benchmark page](https://vboussange.github.io/jaxscape/benchmark/) of the
documentation describes the questions and publishes the results. To reproduce the
benchmark or run it on your own CPU or GPU, follow the instructions in
[`benchmark/README.md`](benchmark/README.md).

## License

`jaxscape` is distributed under the terms of the [MIT](https://spdx.org/licenses/MIT.html) license.

## Citation

If you use JAXScape in your research, please cite:

```bibtex
@software{jaxscape2024,
  author = {Boussange, Victor},
  title = {JAXScape: A minimal JAX library for connectivity modelling at scale},
  year = {2025},
  doi = {10.5281/zenodo.15267703},
  url = {https://github.com/vboussange/jaxscape}
}
```

## Acknowledgements

Development of JAXScape was supported by the Swiss National Science Foundation
(SNSF), grant 237783.
