Metadata-Version: 2.4
Name: arealinterp
Version: 0.1.0
Summary: Areal interpolation between incompatible zone systems: exact-overlay area weighting, target-density weighting, binary/multi-class dasymetric mapping and Tobler's pycnophylactic interpolation, with volume-preservation diagnostics.
Author-email: Yusuf Eminoğlu <geospacephilo@gmail.com>
License-Expression: MIT
Project-URL: Homepage, https://github.com/YusufEminoglu/arealinterp_sdk
Project-URL: Repository, https://github.com/YusufEminoglu/arealinterp_sdk
Project-URL: Issues, https://github.com/YusufEminoglu/arealinterp_sdk/issues
Project-URL: Changelog, https://github.com/YusufEminoglu/arealinterp_sdk/blob/main/CHANGELOG.md
Keywords: areal-interpolation,dasymetric-mapping,pycnophylactic,area-weighting,polygon-overlay,census,zone-systems,change-of-support,population,geojson,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: shapely
Requires-Dist: shapely>=2.0; extra == "shapely"
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

# arealinterp

[![PyPI version](https://img.shields.io/pypi/v/arealinterp.svg)](https://pypi.org/project/arealinterp/)
[![Python versions](https://img.shields.io/pypi/pyversions/arealinterp.svg)](https://pypi.org/project/arealinterp/)
[![CI](https://github.com/YusufEminoglu/arealinterp_sdk/actions/workflows/ci.yml/badge.svg)](https://github.com/YusufEminoglu/arealinterp_sdk/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/YusufEminoglu/arealinterp_sdk/blob/main/LICENSE)

**Areal interpolation between incompatible zone systems.**

Census tracts never line up with planning districts, school catchments or
grid cells. `arealinterp` moves counts and rates from one set of polygons to
another with the classic methods, and it tells you how much of the total survived:

- **Areal weighting** for extensive (counts) and intensive (rates) variables
  (Goodchild & Lam 1980), on an **exact polygon overlay**. A pure-Python
  engine handles concave polygons, holes, multipolygons and shared
  boundaries. The optional `shapely` backend is faster.
- **Target-density weighting** with an ancillary count on the target zones (Schroeder 2007).
- **Dasymetric mapping** with a land-cover **raster** or land-cover **polygons**:
  - binary (inhabited / uninhabited),
  - multi-class relative density (for example three-class), with densities
    estimated by percent-cover sampling (Mennis 2003; Mennis & Hultgren 2006),
  - fixed percentages per class (Eicher & Brewer 2001).
- **Pycnophylactic interpolation** on a grid (Tobler 1979) in numpy, with
  each zone's volume preserved after every iteration and no negative values.
- **Volume-preservation diagnostics** for every extensive variable: totals,
  relative error and the worst source zone.
- **GeoJSON / CSV / ESRI ASCII grid** I/O, plus a command-line tool.

```bash
pip install arealinterp              # numpy only
pip install "arealinterp[shapely]"   # + shapely overlay backend
```

Requires Python 3.9 or newer.

> Need more? [`tobler`](https://github.com/pysal/tobler) (PySAL) is a fuller
> alternative built on geopandas. It adds regression-based and model-based
> interpolation, H3 / hexagon utilities and raster masking through rasterio.
> `arealinterp` is a smaller package for when you don't want the geopandas
> stack. It has a dependency-free overlay engine, explicit diagnostics and a CLI.

---

## Quick start (Python)

```python
from arealinterp import area_weighted, read_geojson, write_geojson

tracts = read_geojson("tracts.geojson", id_field="GEOID")        # projected CRS!
districts = read_geojson("districts.geojson", id_field="code")

res = area_weighted(tracts, districts, extensive=["pop", "households"], intensive="median_rent")
print(res.as_dict("pop"))
print(res.volume["pop"])          # pop: source=152340 target=152340 diff=+0 (+0.000e+00)
write_geojson("districts_pop.geojson", districts, res)
```

Dasymetric and pycnophylactic variants share the same inputs and result type:

```python
from arealinterp import (binary_dasymetric, dasymetric, estimate_class_densities,
                         pycnophylactic_interpolate, read_ascii_grid)

lc = read_ascii_grid("landcover.asc")            # 0 water, 1 low-, 2 high-density

bd = binary_dasymetric(tracts, districts, lc, "pop", inhabited=[1, 2])

est = estimate_class_densities(tracts, lc, "pop", threshold=0.8, presets={0: 0})
dd = dasymetric(tracts, districts, lc, "pop", densities=est.densities)
dd.details["surfaces"]["pop"]                    # the dasymetric population surface (Raster)

eb = dasymetric(tracts, districts, lc, "pop", percentages={2: 60, 1: 35, 0: 5})

pp = pycnophylactic_interpolate(tracts, districts, "pop", cell_size=100)
pp.details["pycno"]["pop"].surface               # smooth surface, volume-preserving
```

`examples/quickstart.py` runs all four methods on a synthetic town.

## Quick start (command line)

```bash
# area weighting, GeoJSON out (the legacy "crs" member of the target file is copied)
arealinterp areal tracts.geojson districts.geojson --source-id GEOID --target-id code \
    -e pop -e households -i median_rent -o districts_pop.geojson

# attributes in a separate CSV
arealinterp areal tracts.geojson districts.geojson --source-id GEOID \
    --join census.csv -e pop -o out.csv

# target-density weighting
arealinterp tdw tracts_2000.geojson tracts_2020.geojson -e pop2000 --target-weight pop2020 -o out.csv

# dasymetric: binary / densities / percentages / estimated densities
arealinterp dasymetric tracts.geojson districts.geojson -e pop --raster lc.asc --inhabited 1,2
arealinterp dasymetric tracts.geojson districts.geojson -e pop --landcover lc.geojson \
    --class-field code --density high=10,low=3,other=0
arealinterp dasymetric tracts.geojson districts.geojson -e pop --raster lc.asc \
    --estimate --threshold 0.8 --preset 0=0 --surface pop_surface.asc

# pycnophylactic surface only, or summed over targets
arealinterp pycno tracts.geojson -e pop --cell-size 100 --surface pop.asc
arealinterp pycno tracts.geojson districts.geojson -e pop --cell-size 100 -o out.csv

# the raw intersection table
arealinterp overlay tracts.geojson districts.geojson -o overlay.csv
```

Without `-o` the estimates are written as CSV on stdout. The method summary
and the volume report go to stderr.

## API overview

| Function | Purpose |
|---|---|
| `overlay(sources, targets, backend=)` | Exact intersection areas (`Overlay`: sparse table, `.matrix()`, `.records()`). |
| `area_weighted(sources, targets, extensive, intensive, allocate_total=)` | Goodchild & Lam areal weighting. |
| `target_density_weighted(sources, targets, extensive, target_variable)` | Schroeder TDW. |
| `dasymetric(sources, targets, ancillary, extensive, densities= / percentages=)` | Density or fixed-percentage dasymetric mapping (raster or polygons). |
| `binary_dasymetric(..., inhabited=[...])` | Binary dasymetric mapping. |
| `estimate_class_densities(sources, ancillary, variable, threshold=, presets=)` | Percent-cover sampling of class densities. |
| `pycnophylactic(sources, variable, cell_size)` / `pycnophylactic_interpolate(...)` | Tobler surface / surface summed over targets. |
| `intersection`, `intersection_area`, `make_polygon`, `box`, `region_area` | Pure-Python polygon geometry. |
| `read_geojson`, `write_geojson`, `write_csv`, `join_csv`, `read_ascii_grid`, `write_ascii_grid` | I/O. |
| `volume_report`, `VolumeReport`, `InterpolationResult` | Diagnostics and results. |

Zones are `Zone(id, geometry, properties)`. Geometries are lists of oriented
rings: exteriors counter-clockwise, holes clockwise. `region_from_geojson`
converts any GeoJSON Polygon or MultiPolygon, whatever its ring orientation.
Every method returns an `InterpolationResult`, which holds `values`
(`{variable: numpy array}`), `volume` (`{variable: VolumeReport}`), `notes`
(fallbacks and warnings) and `details` (backend, fallback sources,
surfaces, class densities).

## Methods and sources

Notation: `y_s` is the source value, `A_s` the source area, `A_t` the target
area, `A_st` the area of `s ∩ t`, and `A_sc` / `A_stc` the area of land-cover
class `c` inside `s` / `s ∩ t`.

**Areal weighting** (Goodchild & Lam 1980):

- extensive: `y_t = Σ_s y_s · A_st / A_s`
- intensive: `y_t = Σ_s y_s · A_st / Σ_s A_st`. This is the area-weighted
  mean over the part of `t` that the sources cover, NaN where nothing covers it.

With `allocate_total=True` the extensive denominator becomes `Σ_t A_st`. Each
source's whole value then goes to the targets it touches, which helps when
coastlines were digitised differently.

**Target-density weighting** (Schroeder 2007): `w_st = A_st · z_t / A_t`, and
`y_t = Σ_s y_s · w_st / Σ_t' w_st'`. Here `z_t` is an ancillary count on the
targets. Sources that touch only `z = 0` targets fall back to areal weighting.

**Dasymetric mapping**:

- density weighting: `y_t = Σ_s y_s · Σ_c d_c A_stc / Σ_c d_c A_sc`. Binary
  mapping is `d_c ∈ {0, 1}`. Mennis (2003) uses a three-class urban density
  layer.
- fixed percentages (Eicher & Brewer 2001): `p'_sc = p_c / Σ_{c present in s} p_c`,
  and `y_t = Σ_s y_s · Σ_c p'_sc · A_stc / A_sc`.

With raster ancillary data, each cell belongs to the zones that contain its
centre, and the dasymetric surface is returned. With polygon ancillary data,
the triple overlay `s ∩ t ∩ c` is computed exactly. Area not covered by any
ancillary polygon, and nodata cells, form the class `UNCOVERED`. Sources with
no weighted area fall back to areal weighting. Sources too small to contain a
cell centre are interpolated with exact areal weighting. Both cases are
reported.

**Density estimation** (Mennis 2003; Mennis & Hultgren 2006): for each class,
the source zones covered by that class to at least `threshold` are pooled,
and `d_c = Σ y_s / Σ A_s`. Mennis & Hultgren (2006) compared 70 %, 80 % and
90 % thresholds; `threshold=1.0` is "contained" sampling. You can preset
classes with `presets=`, for example water = 0. Classes that no zone samples
get one shared *residual* density: the population left after the known
classes, divided by their area. This rule is a simplification (see
Limitations).

**Pycnophylactic interpolation** (Tobler 1979). Each cell starts at its
zone's value divided by its cell count. Each iteration then:

1. relaxes every cell towards the mean of its four rook neighbours, a Jacobi
   step towards the Laplace equation that minimises roughness;
2. adds each zone's mean residual back;
3. clips negative cells to zero;
4. rescales each zone multiplicatively.

Every zone's volume therefore holds to rounding error after every
iteration, which the tests check. The edge condition is either `neumann`
(zero gradient) or `zero` (zero density outside the study area). Both are
discussed by Tobler.

**Polygon overlay engine**. The boundary of `A ∩ B` is made of three parts:
the parts of ∂A inside B, the parts of ∂B inside A, and the boundary pieces
the two share running in the *same* direction. Pieces shared in *opposite*
directions are common edges of adjacent zones and are dropped. The engine
splits each edge at every intersection point and classifies each piece by
its midpoint. The area then follows from the shoelace / Green's theorem sum
over the kept pieces, and the pieces are chained back into rings. Nearly
coincident vertices are snapped together within a relative tolerance
(default 1e‑9 of the extent). The tests compare the engine with shapely on
random concave polygons with holes, to 1e‑12.

### References

- Eicher, C. L. & Brewer, C. A. (2001). Dasymetric mapping and areal interpolation: implementation and evaluation. *Cartography and Geographic Information Science* 28(2), 125–138.
- Goodchild, M. F. & Lam, N. S.-N. (1980). Areal interpolation: a variant of the traditional spatial problem. *Geo-Processing* 1, 297–312.
- Mennis, J. (2003). Generating surface models of population using dasymetric mapping. *The Professional Geographer* 55(1), 31–42.
- Mennis, J. & Hultgren, T. (2006). Intelligent dasymetric mapping and its application to areal interpolation. *Cartography and Geographic Information Science* 33(3), 179–194.
- Schroeder, J. P. (2007). Target-density weighting interpolation and uncertainty evaluation for temporal analysis of census data. *Geographical Analysis* 39(3), 311–335.
- Tobler, W. R. (1979). Smooth pycnophylactic interpolation for geographical regions. *Journal of the American Statistical Association* 74(367), 519–530.

## Limitations

- **Planar coordinates only.** Areas are shoelace areas in map units, so
  reproject longitude/latitude data to an equal-area or local projected CRS
  first. The CLI warns when coordinates look geographic. There is no CRS
  handling or reprojection.
- Input polygons must be valid: rings must not self-intersect, and the zones
  within one layer must not overlap. Ancillary land-cover polygons must not
  overlap each other.
- The pure-Python overlay is O(n·m) in the vertex counts of each candidate
  pair. That is fine for thousands of ordinary census polygons, but use
  `backend="shapely"` for large or very detailed layers.
- Raster dasymetric mapping and the pycnophylactic grid assign cells by their
  centres, so precision depends on the cell size relative to the zones. Small
  zones may contain no cell centre. The dasymetric method then falls back to
  exact areal weighting. The pycnophylactic method loses their volume and
  reports them.
- The residual density for unsampled classes in `estimate_class_densities`
  is a pragmatic simplification. It is not a line-by-line reimplementation of
  Mennis & Hultgren's (2006) intelligent dasymetric mapping. Preset classes
  you know better, or give `densities=` directly.
- Fixed-percentage weights (Eicher & Brewer 2001) are analyst choices. The
  package ships no default percentages.
- Pycnophylactic iteration uses a relaxed Jacobi scheme with a relative
  stopping tolerance (default `1e-4`). The surface is smooth but is not
  solved to machine precision.
- ESRI ASCII grid is the only raster format. Convert GeoTIFFs with GDAL
  (`gdal_translate -of AAIGrid`) or pass a numpy array as `Raster(data, Grid(...))`.

## Academic citation

```bibtex
@software{eminoglu_arealinterp,
  author  = {Eminoğlu, Yusuf},
  title   = {arealinterp},
  year    = {2026},
  version = {0.1.0},
  url     = {https://github.com/YusufEminoglu/arealinterp_sdk}
}
```

See also `CITATION.cff`.

## License

MIT © 2026 Yusuf Eminoğlu. See [LICENSE](LICENSE).
