Skip to main content

Geo Polygonize

A native Rust port of the JTS/GEOS polygonization algorithm. This crate allows you to reconstruct valid polygons from a set of lines, including handling of complex topologies like holes, nested shells, and disconnected components.

Ask DeepWiki

Features

  • Robust Polygonization: Extracts polygons from unstructured linework.
  • Iterative Grid Noding (Unchecked): Splits and snaps dirty linework, without claiming certified snap-rounding guarantees.
  • Certified Fixed-Precision Noding: Optional hot-pixel snap rounding with an independent full-noding postcondition check.
  • Hardware Acceleration: Uses SIMD instructions (via wide crate) for critical geometric predicates like Point-in-Polygon checks.
  • Wasm Optimized: Tailored for WebAssembly with talc allocator and binary GeoArrow support.
  • Performance: SIMD, spatial indexing, and optional parallel execution, with checked-in benchmark tooling.
  • Geo Ecosystem: Fully integrated with geo-types and geo crates.
  • GeoArrow Support: Arrow C Data Interface and Arrow IPC integration with GeoArrow metadata.

Engineering Roadmap

For an ambitious, prioritized plan covering performance, security, API consistency, and maintainability, see ROADMAP.md.

Usage

Library

use geo_polygonize_core::{polygonize, Coord3D, Line3D};
use geo_polygonize_core::options::PolygonizerOptions;

fn main() {
    let points = [
        Coord3D::new(0.0, 0.0, 0.0),
        Coord3D::new(10.0, 0.0, 0.0),
        Coord3D::new(10.0, 10.0, 0.0),
        Coord3D::new(0.0, 10.0, 0.0),
    ];
    let lines = (0..4).map(|i| Line3D::new(points[i], points[(i + 1) % 4], i as u32));

    let result = polygonize(lines, &PolygonizerOptions::default())
        .expect("Polygonization failed");

    for polygon in result.polygons {
        println!("Found polygon with area: {}", polygon.unsigned_area_2d());
    }
}

Choosing noding and precision

Polygonization quality is heavily influenced by input noding strategy.

  • node_input = false (default): Fastest path. Use this when your input linework is already noded (all intersections are explicit vertices).
  • node_input = true: Enables unchecked iterative grid noding. Use this for real-world datasets that may contain slight misalignments, overlaps, or self-intersections, and validate outputs when correctness must be certified.
  • PrecisionModel::Floating (default) preserves input coordinates and uses floating-point intersections.
  • PrecisionModel::FixedGrid { grid_size } rounds topology coordinates to an explicit positive grid, even when input noding is disabled. Choose the grid in the units of your data; oversnapping can collapse narrow features.

Practical workflow:

  1. Run with node_input = false first on trusted data.
  2. If you observe missing polygons, sliver artifacts, or unresolved intersections, enable node_input.
  3. Use a fixed precision model only when your application has an explicit coordinate grid contract.

Canonical options now use precision_model instead of snap_grid_size. Legacy positional Python, Wasm, and C APIs still translate their grid argument when noding is enabled and ignore it on the non-noding fast path.

Set options.noding.guarantee to NodingGuarantee::Validate to run an independent full-noding check before graph construction. Validation reports the first pair with an interior intersection or unnormalized collinear overlap. Use NodingGuarantee::CertifiedFixedPrecision with node_input, FixedGrid, the Snap backend, and SnapStrategy::Grid for hot-pixel snap rounding plus that validation. Certified coordinates must fit exact integer grid indices.

Output semantics

The polygonizer intentionally returns only valid polygonal areas that can be formed from closed cycles:

  • Dangles are removed: dead-end edges do not appear in output polygons.
  • Cut edges are excluded: edges that are connected but cannot bound a face are ignored.
  • Holes and nested shells are preserved when enough boundary information is present.

This behavior matches classical JTS/GEOS polygonization semantics and is useful for cleaning linework before area analysis.

GeoArrow Integration

The library supports ingesting data directly from Arrow arrays via the arrow_api module and ffi.

use geo_polygonize_core::arrow_api::{polygonize_arrow, PolygonizerOptions};
// ... create Arrow array ...
// let result = polygonize_arrow(&array, &field, options);

Python

The Python package is published as geo-polygonize-py and imported as geo_polygonize.

pip install geo-polygonize-py
import numpy as np
from geo_polygonize import polygonize, import_probe

# 1. Using Shapely LineStrings or coordinate lists directly
lines = [
    [(0, 0), (10, 0), (10, 10), (0, 10), (0, 0)],
    [(0, 0), (10, 10)]
]

# return_polygons=True returns a list of shapely.geometry.Polygon objects
polygons = polygonize(lines=lines, return_polygons=True)
for p in polygons:
    print(p.area)

# 2. Using High-Performance Flat Arrays
# Flat buffers avoid Python object-per-coordinate overhead
coords = np.array([
    0.0, 0.0, 10.0, 0.0, 10.0, 10.0, 0.0, 10.0, 0.0, 0.0,
    0.0, 0.0, 10.0, 10.0
], dtype=np.float64)

# Start indices for each line segment.
# The final closing offset is computed implicitly.
offsets = np.array([0, 5], dtype=np.uint32)

# Returns a stable dictionary with 'polygons', diagnostics, and provenance.
result_dict = polygonize(coords=coords, offsets=offsets)

# Native-extension probes are cheap and safe for optional integrations.
ok, error = import_probe()

CFB/autograder integrations should use the versioned production profile rather than assembling caller-side knobs or using legacy polygonize(..., node=True, snap=0.5) calls:

from geo_polygonize import cfb_robust_options, polygonize_with_options

result = polygonize_with_options(
    coords=coords,
    offsets=offsets,
    options=cfb_robust_options(),
)

The default return shape is a stable dictionary with polygons as SimplePolygon values. Use return_polygons=True only when you want Shapely Polygon objects.

When provenance is enabled, coincident and partially overlapping input lines are dissolved into one topology edge while every contributing nonzero line_id remains in the polygon's sorted boundary_line_ids.

SnapStrategy::Grid keeps topology and output coordinates on a configured fixed precision grid. The CFB profile uses GeosCompat: the grid establishes robust topology, then output nodes regain deterministic source coordinates to better match Shapely snap plus full-precision noding. It is not set_precision emulation, and exact parity is not guaranteed for many-to-one snaps.

For Shapely parity checks, compare report-mode outputs with the built-in mismatch helper:

from geo_polygonize import explain_mismatch, polygonize_with_options

options = cfb_robust_options()
result_a = polygonize_with_options(coords=coords_a, offsets=offsets_a, options=options)
result_b = polygonize_with_options(coords=coords_b, offsets=offsets_b, options=options)
result_a["options"] = options
result_b["options"] = options

mismatch = explain_mismatch(result_a, result_b)

For a minimal Shapely smoke comparison, use area signatures:

from shapely.ops import polygonize as shapely_polygonize

rust_polys = polygonize_with_options(lines=lines, options=cfb_robust_options(), return_polygons=True)
rust_areas = sorted(round(poly.area, 6) for poly in rust_polys)
shapely_areas = sorted(round(poly.area, 6) for poly in shapely_polygonize(lines))

WebAssembly (WASM)

This library supports WebAssembly with an ergonomic dual-build configuration that automatically utilizes SIMD instructions where available.

Installation:

npm install geo-polygonize

Standard Usage (Quick Demos): The default entry point automatically handles feature detection (SIMD) and lazy-loading of the Wasm binary. The Wasm is inlined as a Base64 Data URI, so no extra bundler configuration is needed. For app builds, prefer the slim entry point below so your bundler keeps the Wasm assets out of the JavaScript chunk.

import init, { polygonize, polygonize_geoarrow } from "geo-polygonize";

async function run() {
    await init();

    const geojson = {
        "type": "FeatureCollection",
        "features": [
            // ... your line features
        ]
    };

    // Returns a GeoJSON FeatureCollection string
    // Pass explicitly matching backend configuration if desired
    const result = polygonize(
        JSON.stringify(geojson),
        true, // node_input
        0.5   // snap_grid_size
    );
    console.log(JSON.parse(result));

    // Or use Arrow IPC bytes
    // const ipcBuffer = ...;
    // const arrowResult = polygonize_geoarrow(ipcBuffer, false, 1e-10, false);
}

Slim Usage (Apps / Manual Loading): For Vite and other app bundlers, import from geo-polygonize/slim and pass explicit Wasm asset URLs.

import { cfbRobustOptions, initBest } from "geo-polygonize/slim";
import scalarUrl from "geo-polygonize/geo_polygonize.wasm?url";
import simdUrl from "geo-polygonize/geo_polygonize_simd.wasm?url";

async function run() {
    const wasm = await initBest(
        { module_or_path: scalarUrl },
        { module_or_path: simdUrl },
    );

    const result = wasm.polygonizeWithOptions(
        JSON.stringify(geojson),
        cfbRobustOptions,
    );
}

Multithreaded Usage (Experimental): This library provides a multithreaded build powered by wasm-bindgen-rayon.

import init, { initThreadPool, polygonize } from "geo-polygonize/threads";

async function run() {
    await init();

    // Initialize thread pool (e.g., with navigator.hardwareConcurrency)
    await initThreadPool(navigator.hardwareConcurrency);

    // ... use polygonize as usual
}

Important: Multithreaded WebAssembly requires SharedArrayBuffer, which is only available in secure contexts. You must serve your page with the following headers:

Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp

CLI Example

The repository includes a CLI tool to polygonize GeoJSON files.

# Build the example
cargo build -p geo-polygonize-core --example polygonize --release

# Run on input lines
cargo run -p geo-polygonize-core --release --example polygonize -- --input lines.geojson --output polygons.geojson --node

Visualization

You can visualize the results using the provided Python script (requires matplotlib and shapely).

python3 scripts/visualize.py --input lines.geojson --output polygons.geojson --save result.png

Examples

Below are some examples of what the polygonizer can do.

Nested Holes and Islands

The algorithm correctly identifies nested structures (Island inside a Hole inside a Shell).

Nested Holes

Incomplete Grid / Dangles

The algorithm prunes dangles (dead-end lines) and extracts only closed cycles.

Incomplete Grid

Touching Polygons (Shared Edges)

Using robust noding (--node), it can reconstruct adjacent polygons that share boundaries, even if the input lines are not perfectly noded.

Touching Polygons

Self-Intersecting Geometry (Bowtie)

Self-intersecting lines are split at intersection points, and valid cycles are extracted.

Bowtie

Complex Geometries

The polygonizer can handle complex, curved inputs (approximated by LineStrings) such as overlapping circles and shapes with multiple holes.

Overlapping Circles: Note how the intersection regions are correctly identified as separate polygons.

Overlapping Circles

Curved Holes: A complex polygon with multiple circular holes.

Curved Holes

Benchmarks

This library includes a "severe" comparison suite against shapely (GEOS).

See BENCHMARKS.md for detailed results and instructions on how to run them.

Architecture

This implementation moves away from the pointer-based graph structures of JTS/GEOS to a Rust-idiomatic Index Graph (Arena) approach.

See ARCHITECTURE.md for a deep dive into the optimization strategies.

Key optimizations include:

  1. Noding: Unchecked iterative grid noding with spatially dispatched intersection detection.
  2. Vectorization: SIMD-accelerated Ray Casting for efficient Hole Assignment.
  3. Memory Layout: Structure of Arrays (SoA) for graph nodes and talc allocator for Wasm.

License

MIT/Apache-2.0

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

geo_polygonize_py-0.43.0.tar.gz (152.9 kB view details)

Uploaded Source

Built Distributions

If you're not sure about the file name format, learn more about wheel file names.

geo_polygonize_py-0.43.0-cp38-abi3-win_amd64.whl (918.8 kB view details)

Uploaded CPython 3.8+Windows x86-64

geo_polygonize_py-0.43.0-cp38-abi3-manylinux_2_35_x86_64.whl (1.1 MB view details)

Uploaded CPython 3.8+manylinux: glibc 2.35+ x86-64

geo_polygonize_py-0.43.0-cp38-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl (1.0 MB view details)

Uploaded CPython 3.8+manylinux: glibc 2.17+ ARM64

geo_polygonize_py-0.43.0-cp38-abi3-macosx_11_0_arm64.whl (908.2 kB view details)

Uploaded CPython 3.8+macOS 11.0+ ARM64

File details

Details for the file geo_polygonize_py-0.43.0.tar.gz.

File metadata

  • Download URL: geo_polygonize_py-0.43.0.tar.gz
  • Upload date:
  • Size: 152.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.14

File hashes

Hashes for geo_polygonize_py-0.43.0.tar.gz
Algorithm Hash digest
SHA256 0a26a9084bd91452992578703c29dc5fe5b9c5625bd6c9e1f67f499b1635004d
MD5 9a89f3ffe1e3070c8a5a1c7cf703e3ab
BLAKE2b-256 4273fb2d74182ceff818a0860ae2602ce9281ae95106404514596fcbc42e9468

See more details on using hashes here.

Provenance

The following attestation bundles were made for geo_polygonize_py-0.43.0.tar.gz:

Publisher: publish-python.yml on graydonpleasants/geo-polygonize

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file geo_polygonize_py-0.43.0-cp38-abi3-win_amd64.whl.

File metadata

File hashes

Hashes for geo_polygonize_py-0.43.0-cp38-abi3-win_amd64.whl
Algorithm Hash digest
SHA256 acc7703ad4c1962ea9a454a9534ccd32f2cd70c106c144421d55a3a6f1883e19
MD5 3e658fbc97e0a18735c32c12888efffa
BLAKE2b-256 353d2a00fd0d64aba3a0b5a960a811b9cf9e66d6be47b6943c76fa26138c150f

See more details on using hashes here.

Provenance

The following attestation bundles were made for geo_polygonize_py-0.43.0-cp38-abi3-win_amd64.whl:

Publisher: publish-python.yml on graydonpleasants/geo-polygonize

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file geo_polygonize_py-0.43.0-cp38-abi3-manylinux_2_35_x86_64.whl.

File metadata

File hashes

Hashes for geo_polygonize_py-0.43.0-cp38-abi3-manylinux_2_35_x86_64.whl
Algorithm Hash digest
SHA256 aae4f2c85bb0fa365212c121ba187c1e7ab05eb1c7708d28b277f214960a6999
MD5 d72d4fa46da08363f72fca1066aa7d2a
BLAKE2b-256 4c660a2157208c5f9a3895575f71552868acac8ab05c74ec02e5eb5167caa170

See more details on using hashes here.

Provenance

The following attestation bundles were made for geo_polygonize_py-0.43.0-cp38-abi3-manylinux_2_35_x86_64.whl:

Publisher: publish-python.yml on graydonpleasants/geo-polygonize

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file geo_polygonize_py-0.43.0-cp38-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl.

File metadata

File hashes

Hashes for geo_polygonize_py-0.43.0-cp38-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
Algorithm Hash digest
SHA256 5f43e539803eb6c24e810e6bc1b2d537f0f4b267e03528d7083e7acfb9c52ba7
MD5 ed6e685b08b1a54809ac5cacd97aeb2d
BLAKE2b-256 b35e53699752a43268f9e2dd598d5f3c38bd3d072699fcc39411af52ea1ecf96

See more details on using hashes here.

Provenance

The following attestation bundles were made for geo_polygonize_py-0.43.0-cp38-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl:

Publisher: publish-python.yml on graydonpleasants/geo-polygonize

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file geo_polygonize_py-0.43.0-cp38-abi3-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for geo_polygonize_py-0.43.0-cp38-abi3-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 3911e52808b604b35042b27e091c02d4345099f5d0c5b6eaf4bf6b3c7ee21aa2
MD5 8c718e77b59df9c501dece087a07275a
BLAKE2b-256 538f3e12da466908c398f30a74ae25874f802a0dc50b0b305f5954d6ed30fce5

See more details on using hashes here.

Provenance

The following attestation bundles were made for geo_polygonize_py-0.43.0-cp38-abi3-macosx_11_0_arm64.whl:

Publisher: publish-python.yml on graydonpleasants/geo-polygonize

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Release history Release notifications | RSS feed

1.1.0

5 files

1.0.0

5 files

0.76.2

5 files

0.76.1

5 files

0.76.0

5 files

0.75.0

5 files

0.74.0

5 files

0.73.0

5 files

0.72.0

5 files

0.71.0

5 files

0.70.0

5 files

0.69.0

5 files

0.68.0

5 files

0.67.0

5 files

0.66.0

5 files

0.65.0

5 files

0.64.0

5 files

0.63.0

5 files

0.62.0

5 files

0.61.0

5 files

0.60.0

5 files

0.59.0

5 files

0.58.1

5 files

0.58.0

5 files

0.57.0

5 files

0.56.0

5 files

0.55.0

5 files

0.54.0

5 files

0.53.0

5 files

0.52.0

5 files

0.51.2

5 files

0.51.1

5 files

0.51.0

5 files

0.50.0

5 files

0.49.0

5 files

0.48.0

5 files

0.47.1

5 files

0.47.0

5 files

0.46.2

5 files

0.46.1

5 files

0.46.0

5 files

0.45.1

5 files

0.45.0

5 files

0.44.0

5 files

This release

0.43.0 This release

5 files

0.42.0

5 files

0.41.0

5 files

0.40.1

5 files

0.40.0

5 files

0.39.13

5 files

0.39.12

5 files

0.39.11

5 files

0.39.10

5 files

0.39.9

5 files

0.39.8

5 files

0.39.7

5 files

0.39.6

5 files

0.39.5

5 files

0.39.4

5 files

0.39.3

5 files

0.39.2

5 files

0.39.1

5 files

0.39.0

5 files

0.38.1

5 files

0.38.0

5 files

0.37.8

5 files

0.37.7

5 files

0.37.6

5 files

0.37.5

5 files

0.37.4

5 files

0.37.3

5 files

0.37.2

5 files

0.37.1

5 files

0.37.0

5 files

0.36.2

5 files

0.36.1

5 files

0.36.0

5 files

0.35.2

5 files

0.35.1

4 files

0.35.0

4 files

0.34.0

3 files

0.33.1

3 files

0.33.0

3 files

0.23.1

3 files

0.23.0

3 files

0.22.1

3 files

0.22.0

3 files

0.21.0

3 files

0.20.0

3 files

0.19.0

3 files

0.18.1

3 files

0.18.0

3 files

0.17.4

3 files

0.17.3

3 files

0.17.2

3 files

0.17.1

3 files

0.17.0

3 files

0.16.0

3 files

0.15.0

3 files

0.14.1

3 files

0.14.0

3 files

0.13.0

3 files

0.12.1

3 files

0.12.0

3 files

0.11.0

3 files

0.10.0

3 files

0.9.0

3 files

0.8.1

3 files

0.8.0

3 files

0.7.0

3 files

0.6.3

3 files

0.6.2

3 files

0.6.1

3 files

0.6.0

3 files

0.5.0

3 files

0.4.2

3 files

0.4.1

3 files

0.1.0

5 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page