Skip to content

About

Fast, landscape ecology analysis for Python.

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

Terraflux

Terraflux's Python library: fast landscape analysis for Python.
Habitat patterns, fragmentation, landscape metrics and ecological connectivity,
from a single raster to maps larger than memory.

PyPI Python 3.10+ C++17 / OpenMP License: GPL-3.0-or-later

Documentation · Getting started · API reference · Terraflux, the desktop application

Installed as terraflux-py, imported as terraflux. It was called landschaft until 1.58: pip install landschaft and import landschaft keep working.


terraflux brings the established methods of landscape ecology together in one Python package, with a C++17/OpenMP core behind a numpy / xarray / dask / rasterio API. It reproduces the reference tools of each method, checked against their outputs in the test suite, and runs from a few to several hundred times faster.

It is the library behind Terraflux, the desktop application where the same methods are nodes of a model drawn on a canvas: Terraflux runs this library's C++ core, and any model made there can be exported as a Python script of terraflux (File > Python script...), for a paper, a reviewer or a cluster.

Area What it covers Reproduces
Habitat patterns MSPA, SPA, object accounting, contortion GuidosToolbox
Fragmentation density at many scales (FAD, FOS), landscape mosaics, contagion, entropy GuidosToolbox
Landscape metrics 133 patch, class and landscape metrics, sample plots, moving windows, time series landscapemetrics, FRAGSTATS
Habitat networks PC, IIC, ECA, node and link importance, ProtConn Conefor, Makurhini
Circuit connectivity omnidirectional and pairwise current flow, rasters and networks Circuitscape, Omniscape
Distance & restoration cost surfaces, least-cost paths and corridors, isochrone maps GuidosToolbox
Change detection simple and morphological change, fragmentation transitions GuidosToolbox
Routes on grids transitions from any rule, travel-time surfaces, least-cost distances and paths, random walks, randomised shortest paths, route overlap gdistance
Surface metrics texture of continuous rasters (ISO 25178): roughness, height distribution, bearing area curve, slopes, peaks and valleys, autocorrelation, orientation, fractal dimension, trend surfaces, texture images; terrain indices (TPI, TRI, VRM, curvature, HLI...) geodiv, spatialEco
Terrain hydrology depression filling, D8, D-infinity and multiple flow directions, flow accumulation, streams, height above the nearest drainage (HAND), wetness, stream power and sediment transport indices WhiteboxTools
Neutral landscape models simulated landscapes as null models: random, percolation, gradients, fractal surfaces, Gaussian fields, mosaics, clusters, classification NLMR
Biodiversity analysis species records in grid cells: richness, endemism, phylogenetic diversity and endemism, randomisations, CANAPE, clustering Biodiverse
Spatial prioritization ranking of whole landscapes for many features (CAZ and ABF rules), weights, costs, hierarchic masks, connectivity transforms, performance curves, post-processing, impact assessment; maps larger than memory Zonation 5
Species distributions cleaning and thinning occurrence records, accessible area, collinearity filters, background points, spatial cross-validation folds, evaluation (AUC, TSS, Boyce index), Maxent (MaxNet), ensembles of scikit-learn models, projection and extrapolation (MESS, MOP, ExDet) CoordinateCleaner, spThin, usdm, dismo, blockCV, ENMeval, ecospat, predicts, maxnet, mop
Land change simulation change analysis (intensity, components of difference, Markov chains), transition potential (weights of evidence, logistic regression, any scikit-learn model), allocation (CLUE-S, ordered, land systems, Expander/Patcher, random patch seeds, patch growing), dynamic variables, regional demands, validation at several resolutions, fuzzy similarity, calibration, scenarios with replicates lulcc, OpenLand, diffeR, CLUMondo, FUTURES, MOLUSCE, Dinamica EGO, PLUS
Ecosystem services carbon storage and sequestration with valuation, habitat degradation, quality and rarity, crop pollination by wild bees InVEST
Large data out-of-core tiles and row blocks, parallel batches of rasters, tasks shared with the other computers of a lab (terraflux-py worker)

Installation

pip install terraflux-py

The package is terraflux-py on PyPI and terraflux in Python (import terraflux as tf). Binary wheels are published for CPython 3.10 to 3.14 on Windows (x86-64), macOS (Apple silicon and Intel, 11+) and Linux (x86-64, ARM64), with the OpenMP runtime included: no compiler is needed, and everything every tool uses is installed with the package. In a conda environment, install the geospatial libraries from conda-forge first and terraflux with pip:

conda create -n terraflux -c conda-forge python=3.12 rasterio rioxarray geopandas
conda activate terraflux
pip install terraflux-py

Building from source (other platforms, development) needs a C++17 compiler; see the installation guide.

Docker

The image needs no compiler or Python on the host and includes every optional feature:

docker build -t terraflux .
docker run --rm -it -v "$PWD:/data" terraflux                 # Python shell
docker run --rm -v "$PWD:/data" terraflux python analysis.py  # run a script from the current folder

The current folder is mounted at /data, the working directory of the container. --build-arg PYTHON_VERSION=3.11 picks another Python, and docker build --target test -t terraflux:test . && docker run --rm terraflux:test runs the test suite in the container.

Quick start

import terraflux as tf

forest = tf.load_raster(tf.example_data("input"))    # bundled sample map
morph = tf.mspa(forest, edge_width=2)                # cores, edges, bridges, loops...
tf.write_raster(morph, "forest_mspa.tif")            # GeoTIFF with its colour table
print(tf.mspa_stats(morph))

landcover = tf.load_raster(tf.example_data("clc"))
tf.landscape_metrics(landcover, level="landscape", metric=["shdi", "contag", "ed"])

Every function takes numpy arrays, georeferenced xarray.DataArrays or dask arrays, and returns the same type. Parallel functions use the cores less a quarter (15 of 20, 6 of 8), never all of them, as the desktop application does; n_threads or the variable TERRAFLUX_THREADS sets fewer.

Coming from landschaft

Nothing has to change at once: pip install landschaft installs terraflux, import landschaft as ls gives the same modules (with a DeprecationWarning), the LANDSCHAFT_* environment variables are still read, and the files landschaft wrote (GeoTIFF tags, bio sessions, batch records, pickles) load in terraflux. To move over, replace import landschaft as ls with import terraflux as tf and ls. with tf.; the command landschaft is now terraflux-py.

Documentation

The documentation is part of Terraflux's website, https://sacridini.github.io/terraflux/python/: a getting-started guide, tutorials by topic (each of Terraflux's tutorials has its Python version), the full API reference with runnable examples, the algorithms behind the tools, and the validation and benchmarks report. The website is built from Terraflux's repository (sacridini/terraflux, website/), whose API pages are read from this library's docstrings.

Validation and performance

Each tool is compared in the test suite with the program it reproduces: pixel for pixel where the output is a map, value for value (to the last bit where the original arithmetic can be reproduced) for tables, and to the original's own precision for floating-point solvers. Typical speed-ups on the benchmark cases:

Tools Compared with Agreement Speed-up
MSPA GuidosToolbox mspa 2.3 identical pixels 10–17×
Landscape metrics landscapemetrics 2.2.2 identical bits 35–500×
Habitat networks Makurhini, Conefor to 1e-12 13–620×
Omniscape, Circuitscape Omniscape 0.7, Circuitscape 6.1 to 2e-11 3–45×
Grid distances gdistance 1.6 identical bits (least cost); 1e-14 (random walks) 3–400×
Neutral landscape models NLMR 1.4 (same seed) identical bits 2–6000×
Spatial prioritization Zonation 5 v2.4 identical rank maps and output files 4–11×
Species distributions CoordinateCleaner, spThin, usdm, dismo, blockCV, ENMeval, predicts, maxnet identical bits, random steps included (same seed) maxnet 14×, kmeans 8×, weighted sampling 70×
Land change simulation lulcc, OpenLand, diffeR, CLUMondo, r.futures, MOLUSCE; Dinamica EGO (measured) identical bits (R's and NumPy's random numbers included); Dinamica to its 15 digits 7–43×

Methods, machines, full tables and the known differences are on the validation and benchmarks page. To run the tests:

pip install -e ".[test]"
pytest

Versioning

terraflux follows Semantic Versioning: from 1.0 on, the public API changes incompatibly only in a new major version. Its version numbers continue landschaft's (the first release as terraflux is 1.59.0). Changes are listed in the changelog.

License and credits

GPL-3.0-or-later. terraflux ports code from GuidosToolbox and miallib, © European Union (Joint Research Centre), authors Pierre Soille, Peter Vogt et al., both GPL-3.0-or-later; the example maps in src/terraflux/data come from the GTB repository. GTB's mspa notes that its interface is made available for non-commercial purposes: contact the JRC for commercial use of MSPA.

Please cite the methods you use. For MSPA:

  • Soille, P. & Vogt, P. (2009). Morphological segmentation of binary patterns. Pattern Recognition Letters 30(4), 456–459. doi:10.1016/j.patrec.2008.10.015
  • Vogt, P. & Riitters, K. (2017). GuidosToolbox: universal digital image object analysis. European Journal of Remote Sensing 50(1), 352–361. doi:10.1080/22797254.2017.1330650

About

Fast, landscape ecology analysis for Python.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages