Metadata-Version: 2.4
Name: sprawlmetrics
Version: 0.1.1
Summary: Urban expansion and sprawl metrics from multi-date binary built-up rasters: growth rates, Landscape Expansion Index, patch metrics, compactness, entropy, density gradients and SDG 11.3.1.
Author-email: Yusuf Eminoğlu <geospacephilo@gmail.com>
License-Expression: MIT
Project-URL: Homepage, https://gitlab.com/geophilo1/sprawlmetrics_sdk
Project-URL: Repository, https://gitlab.com/geophilo1/sprawlmetrics_sdk
Project-URL: Issues, https://gitlab.com/geophilo1/sprawlmetrics_sdk/-/work_items
Project-URL: Changelog, https://gitlab.com/geophilo1/sprawlmetrics_sdk/-/blob/main/CHANGELOG.md
Keywords: urban-expansion,urban-sprawl,landscape-expansion-index,lei,landscape-metrics,fragstats,shannon-entropy,density-gradient,compactness,built-up,sdg-11,remote-sensing,urban-planning,gis
Classifier: Development Status :: 4 - Beta
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: Operating System :: OS Independent
Classifier: Environment :: Console
Classifier: Topic :: Scientific/Engineering :: GIS
Classifier: Intended Audience :: Science/Research
Classifier: Intended Audience :: Developers
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.21
Provides-Extra: fast
Requires-Dist: scipy>=1.7; extra == "fast"
Provides-Extra: raster
Requires-Dist: rasterio>=1.2; extra == "raster"
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
Requires-Dist: ruff>=0.1.0; extra == "dev"
Requires-Dist: mypy>=1.0.0; extra == "dev"
Dynamic: license-file

# sprawlmetrics

[![PyPI](https://img.shields.io/pypi/v/sprawlmetrics.svg)](https://pypi.org/project/sprawlmetrics/)
[![Python](https://img.shields.io/pypi/pyversions/sprawlmetrics.svg)](https://pypi.org/project/sprawlmetrics/)
[![pipeline](https://gitlab.com/geophilo1/sprawlmetrics_sdk/badges/main/pipeline.svg)](https://gitlab.com/geophilo1/sprawlmetrics_sdk/-/pipelines)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://gitlab.com/geophilo1/sprawlmetrics_sdk/-/blob/main/LICENSE)
[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.24235576.svg)](https://doi.org/10.5281/zenodo.24235576)

**Urban expansion and sprawl metrics from multi-date binary built-up rasters.**

`sprawlmetrics` takes two (or more) built-up / non-built-up rasters of the same grid, for
example classified Landsat or Sentinel-2 scenes or GHSL built-up layers, and computes the
standard indicators used in urban expansion studies:

- **Growth**: built-up area, total and annual growth rate (linear, compound, exponential),
  annual expansion area, and the **urban expansion intensity index** (UEII).
- **Landscape Expansion Index** (LEI; Liu et al. 2010): sorts every new patch into
  *infilling*, *edge-expansion* or *outlying* growth, and reports MEI and AWMEI.
- **Patch metrics** (FRAGSTATS definitions): number of patches, mean patch size, largest
  patch index, edge density, patch density, mean and area-weighted shape index, and patch
  compactness.
- **Footprint compactness**: normalised moment of inertia, exchange index and proximity
  index.
- **Shannon entropy** of built-up land across rings, sectors or any zones
  (Yeh & Li 2001).
- **Density gradient**: built-up density in concentric rings around a centre, with
  Clark's (1951) negative exponential fit `D(r) = D0 exp(-b r)`.
- **SDG 11.3.1**: land consumption rate, population growth rate and their ratio (LCRPGR).
- **Per-zone summaries** (districts, rings, grid cells), written as CSV.

It needs only NumPy. SciPy (optional) speeds up patch labelling, and rasterio (optional)
reads and writes GeoTIFFs. A command-line tool is included.

## Installation

```bash
pip install sprawlmetrics              # NumPy only
pip install "sprawlmetrics[fast]"      # + SciPy (faster connected-component labelling)
pip install "sprawlmetrics[raster]"    # + rasterio (GeoTIFF and other GDAL rasters)
```

Requires Python 3.9 or newer.

## Quickstart

```python
import numpy as np
import sprawlmetrics as sm

# 0/1 rasters on the same 30 m grid (here: a synthetic city)
t1 = np.zeros((200, 200), dtype=np.uint8)
t1[80:120, 80:120] = 1
t2 = t1.copy()
t2[75:125, 75:125] = 1          # edge expansion around the core
t2[20:24, 150:154] = 1          # an outlying settlement

report = sm.compare(t1, t2, years=10, cell_size=30, ring_width=300,
                    population=(250_000, 310_000))
print(report.growth["annual_growth_rate_compound_pct"])
print(report.lei.summary())       # patch counts and areas by growth type, MEI, AWMEI
print(report.gradient_t2.fit)     # Clark fit: D0, b, R²
print(report.sdg_11_3_1.ratio)    # LCRPGR

import json
json.dumps(report.to_dict())      # JSON-safe (NaN -> null)
```

Single metrics are plain functions:

```python
lei = sm.landscape_expansion_index(t1, t2, buffer_cells=1, cell_size=30)
lei.records()                      # one dict per new patch: area, A_o, A_v, LEI, type
lei.type_raster                    # 0 none, 1 infilling, 2 edge-expansion, 3 outlying

sm.patch_metrics(t2, cell_size=30).to_dict()
sm.compactness(t2, cell_size=30)
sm.zonal_entropy(t2, sm.ring_zones(t2.shape, (100, 100), 300, cell_size=30))
sm.density_gradient(t2, 300, centre=(100, 100), cell_size=30)
sm.expansion_intensity(area_t1=144.0, area_t2=225.0, total_area=3600.0, years=10)
sm.lcrpgr(area_t1=144.0, area_t2=225.0, pop_t1=250_000, pop_t2=310_000, years=10)
```

Reading rasters (`.npy` always works; GeoTIFF needs the `raster` extra):

```python
built, valid, info = sm.load_built("built_2000.tif", built_values=[1])   # class code
built, valid, info = sm.load_built("ghsl_2020.tif", threshold=0.2)       # share >= 20 %
info.cell_size   # (xres, yres) from the GeoTIFF transform
```

## Command line

```bash
sprawlmetrics compare built_2000.tif built_2020.tif --years 20 \
    --built-values 1 --ring-width 1000 --centre 512,498 \
    --zones districts.tif --population 1200000,1650000 \
    --lei-raster lei_types.tif --lei-csv lei.csv --zones-csv zones.csv -o report.json

sprawlmetrics patches built_2020.tif --threshold 0.2
sprawlmetrics gradient built_2020.tif --ring-width 500 --csv rings.csv
sprawlmetrics lcrpgr --area1 144 --area2 225 --pop1 250000 --pop2 310000 --years 10
```

All commands print JSON (or write it with `-o`). `.npy` inputs work without rasterio; set
`--cell-size` for them.

## API overview

| Area | Functions / classes |
| --- | --- |
| One call | `compare(t1, t2, years, ...) -> SprawlReport` (`.to_dict()`) |
| Growth | `built_area`, `built_share`, `growth_rate`, `annual_growth_rate(method=...)`, `annual_expansion_area`, `expansion_intensity` |
| LEI | `landscape_expansion_index -> LEIResult` (`mei`, `awmei`, `summary()`, `records()`, `type_raster`), `classify_lei` |
| Patches | `patch_metrics -> PatchMetrics`, `patch_table`, `shape_index`, `min_perimeter_cells`, `label` |
| Compactness | `compactness`, `normalized_moment_of_inertia`, `exchange_index`, `proximity_index`, `built_centroid` |
| Entropy | `shannon_entropy`, `zonal_entropy -> EntropyResult` |
| Gradient | `density_gradient -> GradientResult`, `fit_negative_exponential -> ExponentialFit` |
| Zones | `ring_zones`, `sector_zones`, `distance_grid`, `zonal_summary`, `write_csv` |
| SDG 11.3.1 | `land_consumption_rate`, `population_growth_rate`, `lcrpgr -> LCRPGRResult` |
| I/O | `read_raster`, `load_built`, `binarize`, `write_raster`, `RasterInfo` |

Conventions: rasters are 2-D arrays, non-zero = built-up. `cell_size` is a cell side or an
`(xres, yres)` pair in map units, so areas come out in map units squared. Centres are
`(row, col)` indices (fractional values allowed). An optional `valid` mask marks the study
area; cells outside it count neither as land nor as built-up.

## Methods and sources

| Metric | Definition | Source |
| --- | --- | --- |
| Growth rate | `100 (A2 - A1) / A1` | standard |
| Annual growth rate | linear `100 (A2-A1)/(A1 t)`; compound `100((A2/A1)^(1/t) - 1)`; exponential `100 ln(A2/A1)/t` | standard |
| UEII | `100 (A2 - A1) / (TA t)`, `TA` = land area of the unit | Liu, Zhan & Deng (2005) |
| LEI | `100 A_o / (A_o + A_v)` in a buffer ring around each new patch; infilling `> 50`, edge-expansion `(0, 50]`, outlying `= 0`; `MEI = mean(LEI)`, `AWMEI = sum(LEI_i a_i)/A` | Liu et al. (2010) |
| Patch metrics | NP, CA, AREA_MN, LPI `= 100 max(a)/A`, ED `= E/A * 10 000`, PD `= NP/A * 10^6`, SHAPE `= p / min p` (raster form), SHAPE_MN, SHAPE_AM | McGarigal et al. (FRAGSTATS) |
| Patch compactness | `2 sqrt(pi a) / p` | isoperimetric ratio |
| NMI | `A^2 / (2 pi I)`, `I` = polar moment of inertia about the centroid | Li et al. (2014) |
| Exchange, proximity | share of the footprint inside the equal-area circle; `(2r/3) / mean distance` | Angel, Parent & Civco (2010) |
| Entropy | `H = -sum p_i ln p_i`, `p_i = x_i / sum x`, `x_i` = built-up density of zone `i`; relative `H / ln n` | Yeh & Li (2001) |
| Density gradient | OLS of `ln D` on ring mid-distance: `D(r) = D0 exp(-b r)` | Clark (1951) |
| SDG 11.3.1 | `LCR = ln(Urb2/Urb1)/y`, `PGR = ln(Pop2/Pop1)/y`, ratio `LCR/PGR` | UN-Habitat SDG 11.3.1 metadata |

Raster details:

- Patches use the 8-cell rule by default (FRAGSTATS default); `connectivity=4` is
  available.
- **LEI buffer** = morphological dilation of the patch by `buffer_cells` cells (square or
  disc) minus the patch itself; cells outside the raster or the study area are left out.
  `A_v` counts every buffer cell not built at t1, including cells of other new patches.
- **Edge**: the class edge for ED counts cell sides between built-up and valid non-built
  cells; `count_boundary=True` also counts sides on the raster border or against invalid
  cells. A patch's own perimeter (for SHAPE and compactness) always includes them.
- **ED** is in map units of edge per hectare when cells are in metres (FRAGSTATS m/ha);
  **PD** is patches per 100 ha.
- **NMI** treats each cell as a uniform square, adding its own polar moment
  `c (xres² + yres²) / 12`, so a square footprint scores exactly `3/π ≈ 0.955` and a disc
  approaches 1.
- **Ring k** holds cells whose centre lies at `(k-1) w <= d < k w`.

### Relation to `sdg11`

The companion package [`sdg11`](https://pypi.org/project/sdg11/) implements the full SDG
11.3.1 reporting workflow (degree-of-urbanisation delineation, interpretation and report
bundles). `sprawlmetrics.lcrpgr` uses the same formula for quick use inside sprawl
analyses; use `sdg11` for official-style reporting.

## Limitations

- The LEI buffer is raster-based; Liu et al. (2010) describe a vector buffer. With one-cell
  buffers the results match the usual raster implementations, but values for very small
  patches depend on the buffer shape and width.
- No reprojection or resampling: both dates must already be on the same grid.
- Entropy and gradient results depend on the chosen centre and ring width; report them.
- The negative exponential fit is OLS on log density and drops rings with zero density;
  it is not a maximum-likelihood fit.
- UEII class thresholds (e.g. "high-speed", "slow") vary between studies and are not built
  in.
- Not an official UN product; check SDG values against the current UN-Habitat metadata.

## References

- Angel, S., Parent, J. & Civco, D. L. (2010). Ten compactness properties of circles:
  measuring shape in geography. *The Canadian Geographer* 54(4), 441-461.
- Clark, C. (1951). Urban population densities. *Journal of the Royal Statistical Society,
  Series A* 114(4), 490-496.
- Li, W., Chen, T., Wentz, E. A. & Fan, C. (2014). NMMI: A mass compactness measure for
  spatial pattern analysis of areal features. *Annals of the AAG* 104(6), 1116-1133.
- Liu, J., Zhan, J. & Deng, X. (2005). Spatio-temporal patterns and driving forces of urban
  land expansion in China during the economic reform era. *Ambio* 34(6), 450-455.
- Liu, X., Li, X., Chen, Y., Tan, Z., Li, S. & Ai, B. (2010). A new landscape index for
  quantifying urban expansion using multi-temporal remotely sensed data. *Landscape
  Ecology* 25, 671-682. https://doi.org/10.1007/s10980-010-9454-5
- McGarigal, K., Cushman, S. A. & Ene, E. FRAGSTATS v4: Spatial Pattern Analysis Program
  for Categorical Maps. University of Massachusetts, Amherst.
- UN-Habitat. SDG indicator metadata 11.3.1: Ratio of land consumption rate to population
  growth rate.
- Yeh, A. G.-O. & Li, X. (2001). Measurement and monitoring of urban sprawl in a rapidly
  growing region using entropy. *Photogrammetric Engineering & Remote Sensing* 67(1),
  83-90.

## Academic citation

```bibtex
@software{eminoglu_sprawlmetrics,
  author  = {Eminoğlu, Yusuf},
  title   = {sprawlmetrics},
  year    = {2026},
  version = {0.1.1},
  doi     = {10.5281/zenodo.24235576},
  url     = {https://gitlab.com/geophilo1/sprawlmetrics_sdk}
}
```

## License

MIT, see [LICENSE](LICENSE).
