Metadata-Version: 2.4
Name: isolines
Version: 0.1.1
Summary: Contour lines and filled contours (isobands) from grids and scattered points: marching squares with saddle disambiguation, valid polygons with holes, smoothing, simplification, IDW/TIN gridding and GeoJSON output, numpy only.
Author-email: Yusuf Eminoğlu <geospacephilo@gmail.com>
License-Expression: MIT
Project-URL: Homepage, https://gitlab.com/geophilo1/isolines_sdk
Project-URL: Repository, https://gitlab.com/geophilo1/isolines_sdk
Project-URL: Issues, https://gitlab.com/geophilo1/isolines_sdk/-/work_items
Project-URL: Changelog, https://gitlab.com/geophilo1/isolines_sdk/-/blob/main/CHANGELOG.md
Keywords: contour,contours,isolines,isobands,marching-squares,filled-contours,dem,isochrone,noise-map,idw,interpolation,geojson,gis,raster
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: Topic :: Scientific/Engineering :: Mathematics
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: scipy
Requires-Dist: scipy>=1.7; extra == "scipy"
Provides-Extra: raster
Requires-Dist: rasterio>=1.3; 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"
Requires-Dist: shapely>=2.0; extra == "dev"
Dynamic: license-file

# isolines

[![PyPI version](https://img.shields.io/pypi/v/isolines.svg?color=3b82f6)](https://pypi.org/project/isolines/)
[![Python version support](https://img.shields.io/pypi/pyversions/isolines.svg?color=10b981)](https://pypi.org/project/isolines/)
[![pipeline](https://gitlab.com/geophilo1/isolines_sdk/badges/main/pipeline.svg)](https://gitlab.com/geophilo1/isolines_sdk/-/pipelines)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://gitlab.com/geophilo1/isolines_sdk/-/blob/main/LICENSE)
[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.24235578.svg)](https://doi.org/10.5281/zenodo.24235578)

**Contour lines and filled contours (isobands) from grids and scattered points, numpy only.**

`isolines` turns a 2-D grid (a DEM, a travel-time surface, a noise
raster) or a set of scattered measurements into:

- **contour lines**: continuous `LineString`s, one per connected piece, with
  closed-ring detection, `level` and `label` attributes, and a consistent
  direction (higher values on the left);
- **isobands**: `MultiPolygon`s with holes for each value interval, with
  correct nesting (islands inside holes inside polygons), RFC 7946 ring
  orientation, and bands that tile the valid grid without gaps or overlaps.

It handles no-data (NaN, masked arrays, a `nodata` value), georeferences
through an affine geotransform, smooths (Chaikin) and simplifies
(Douglas-Peucker), interpolates scattered points to a grid (IDW, nearest,
linear TIN), and writes GeoJSON. Its only dependency is numpy.

```bash
pip install isolines             # numpy only
pip install "isolines[scipy]"    # + linear (Delaunay TIN) interpolation
pip install "isolines[raster]"   # + GeoTIFF and other rasters through rasterio
```

Requires Python 3.9 or newer.

Typical uses: DEM contours, travel-time isochrones from sampled network
times, noise maps from receiver levels, any "contour this surface" job
where you don't want a GDAL install.

---

## Quick start (Python)

```python
import math
import numpy as np
import isolines

# A gridded surface with georeferencing (GDAL-style, north-up, 25 m cells)
yy, xx = np.mgrid[0:200, 0:300]
dem = 50 + 40 * np.exp(-((xx - 150) ** 2 + (yy - 100) ** 2) / 2000)
gt = isolines.GeoTransform.north_up(500000.0, 4200000.0, 25.0)

levels = isolines.interval_levels(dem.min(), dem.max(), 5)        # 55, 60, ..., 90
lines = isolines.contour_lines(dem, levels, transform=gt, smooth=2, label_format="{:g} m")
bands = isolines.isobands(dem, [-math.inf, 60, 70, 80, math.inf], transform=gt)

for band in bands:
    print(band.label, round(band.area / 1e4, 1), "ha")

isolines.write_geojson("contours.geojson", lines, precision=2)
isolines.write_geojson("bands.geojson", bands, precision=2)
```

From scattered points (for example travel times at network nodes):

```python
z, gt = isolines.points_to_grid(x, y, minutes, cell_size=50.0, method="idw", k=8)
isochrones = isolines.isobands(z, [0, 5, 10, 15], transform=gt)
```

A rasterio dataset can be used directly:

```python
r = isolines.read_raster("dem.tif")          # needs the "raster" extra; NaN for no-data
lines = isolines.contour_lines(r.z, isolines.nice_levels(r.z), transform=r.transform)
```

See [`examples/quickstart.py`](examples/quickstart.py) for a DEM, a noise
map and an isochrone example.

## Quick start (command line)

```bash
# contour lines every 10 m from a GeoTIFF (or an Esri ASCII .asc grid)
isolines lines dem.tif --interval 10 --smooth 2 -o contours.geojson

# filled bands with explicit breaks, open-ended below and above
isolines bands noise.asc --breaks 55,60,65,70 --open-ends -o noise.geojson

# bands straight from a point CSV (interpolated to a 50 m grid first)
isolines bands times.csv --value-col minutes --cell-size 50 --method idw \
    --breaks 0,5,10,15 -o isochrones.geojson

# just the interpolation, written as an Esri ASCII grid
isolines grid times.csv --value-col minutes --cell-size 50 -o times.asc
```

Without `--levels`/`--breaks`/`--interval`, about ten round-numbered levels
are chosen. `--simplify`, `--precision`, `--label-format`, `--min-length`
and `--min-area` are available; `isolines <command> --help` lists all
options.

## API overview

| Function / class | Purpose |
|---|---|
| `contour_lines(z, levels, *, x, y, transform, nodata, pixel_is_area, smooth, simplify, min_length, label_format)` | List of `ContourLine(level, coords, closed, label)` |
| `isobands(z, breaks, *, ..., min_area, keep_empty)` | List of `IsoBand(lower, upper, polygons, label)`, one per interval `[lower, upper)` |
| `GeoTransform` / `as_geotransform` | GDAL 6-coefficient transform; accepts GDAL tuples and rasterio `Affine` |
| `idw`, `nearest`, `linear`, `points_to_grid`, `GridSpec` | Scattered points to grid |
| `interval_levels`, `nice_interval`, `nice_levels` | Level selection |
| `chaikin`, `douglas_peucker`, `signed_area`, `line_length`, `point_in_ring` | Geometry helpers |
| `assemble_polygons`, `orient_polygon`, `validate_polygon` | Polygon building and validity checking |
| `read_ascii_grid`, `write_ascii_grid`, `read_raster`, `load_grid`, `read_points_csv` | Input |
| `to_geojson`, `write_geojson`, `.to_feature()` | GeoJSON output |

Coordinates: with `transform`, grid value `z[row, col]` is placed at the
pixel centre (`pixel_is_area=True`, the GDAL/rasterio convention) or the
pixel corner (`False`). With `x`/`y` (1-D, strictly monotonic), at
`(x[col], y[row])`. With neither, at `(col, row)`.

GeoJSON properties: lines carry `level`, `label`, `closed`, `length`;
bands carry `lower`, `upper` (`null` for infinite), `label`, `area`.

## Method and sources

- **Marching squares.** Each grid cell is classified by which corners are
  `>= level` (16 cases); crossing points are placed on cell edges by linear
  interpolation between the two edge nodes. This is the 2-D case of
  Lorensen, W. E. & Cline, H. E. (1987), *Marching cubes: a high resolution
  3D surface construction algorithm*, SIGGRAPH Computer Graphics 21(4),
  163-169; see also Maple, C. (2003), *Geometric design and space planning
  using the marching squares and marching cube algorithms*, Proc.
  GMAG 2003, 90-95.
- **Saddle disambiguation.** In the two ambiguous cases (diagonal corners
  above), the mean of the four corner values stands in for the value at the
  cell centre: when it is `>= level` the high corners are joined through the
  cell, otherwise the low corners are. (The asymptotic decider of Nielson,
  G. M. & Hamann, B. (1991), *The asymptotic decider*, Proc. IEEE
  Visualization '91, 83-91, is the bilinear-exact alternative; it is not
  used here.)
- **Joining and orientation.** Every segment is directed so that the
  `>= level` side lies on its left. Each edge crossing then starts exactly
  one segment and ends exactly one, so joining is unambiguous and closed
  rings are detected exactly by shared crossing identities, not by
  coordinate tolerance.
- **Isobands.** The boundary of the band `lower <= z < upper` is made of
  the oriented contour segments of `lower`, the reversed contour segments of
  `upper`, and the parts of the valid-domain boundary (grid edge and no-data
  cells) whose values fall in the band. These are traced into closed rings;
  counter-clockwise rings are exteriors, clockwise rings are holes and go to
  the smallest exterior containing them. Rings that touch themselves where
  the no-data domain pinches are split, so polygons are valid under the OGC
  Simple Features rules. Output rings follow **RFC 7946, section 3.1.6**
  (exterior counter-clockwise, holes clockwise; first and last positions
  equal).
- **Exact level values.** A node equal to a level counts as above it.
  Crossing parameters are clamped to `[1e-7, 1 - 1e-7]` of the edge, so a
  contour through a node never produces coincident points on two edges;
  the microscopic rings this would leave around an isolated node equal to
  the level (for example a peak equal to the top level) are dropped.
- **Smoothing:** Chaikin, G. M. (1974), *An algorithm for high-speed curve
  generation*, Computer Graphics and Image Processing 3(4), 346-349.
- **Simplification:** Douglas, D. H. & Peucker, T. K. (1973), *Algorithms
  for the reduction of the number of points required to represent a
  digitized line or its caricature*, Cartographica 10(2), 112-122.
- **IDW:** Shepard, D. (1968), *A two-dimensional interpolation function
  for irregularly-spaced data*, Proc. 23rd ACM National Conference,
  517-524. Weights `d ** -power`; a query on a sample takes its value.
- **Linear TIN:** Delaunay triangulation and barycentric interpolation via
  `scipy.interpolate.LinearNDInterpolator`; NaN outside the convex hull.
- **Geotransform:** the GDAL six-coefficient affine model (GDAL Raster Data
  Model documentation). **Esri ASCII grid:** header keys and row order as in
  the Esri "Esri ASCII raster format" documentation.

The test suite checks analytic surfaces with known answers: a plane
(contour position and band area exact), a cone (contours within the
`1/(8r)` interpolation error of a circle, annulus area), the saddle `z = x*y`
(contour on the axes, saddle-cell areas computed by hand), nested
peak/pit/plateau surfaces (island in a hole), no-data holes and pinches,
plus 40 random integer grids whose values sit exactly on the breaks. Every
band polygon is validated, and the bands are checked to tile the valid
domain; shapely (`is_valid`, areas) is used as an independent check when
installed.

## Limitations

- Linear interpolation along edges means contours of curved surfaces are
  chords; refine the grid for more accuracy.
- The saddle rule uses the cell mean, not the bilinear asymptotic decider;
  in rare saddle cells the topology can differ from bilinear interpolation.
- `smooth` and `simplify` work ring by ring and are not topology-preserving:
  neighbouring bands may slightly overlap or leave slivers, and a smoothed
  line can cross a neighbouring level. Leave them off when exact tiling
  matters.
- Rounding coordinates (`precision`) can merge points that are only `1e-7`
  cells apart at exact-level nodes; keep enough decimals for your units.
- `idw` and `nearest` are brute force (chunked numpy), fine for tens of
  thousands of samples; IDW is an exact interpolator but not a statistical
  one (no kriging, no barriers). A noise or travel-time surface interpolated
  from points is only as good as the sample coverage.
- GeoJSON output carries no CRS (RFC 7946 assumes WGS 84); projected
  coordinates are written as given.
- Lines and polygons are built in memory; very large grids (10^8 cells)
  need tiling.

## Development

```bash
python -m pip install -e ".[dev,scipy,raster]"
python -m pytest tests
python -m ruff check . && python -m ruff format --check src tests
python -m mypy src
```

## Academic citation

```bibtex
@software{eminoglu_isolines,
  author  = {Eminoğlu, Yusuf},
  title   = {isolines},
  year    = {2026},
  version = {0.1.1},
  doi     = {10.5281/zenodo.24235578},
  url     = {https://gitlab.com/geophilo1/isolines_sdk}
}
```

## License

MIT License. Copyright (c) 2026 Yusuf Eminoğlu. See [LICENSE](LICENSE).
