{ } JustinGeoSci

Operations

Operations that rearrange, select from or remove the input’s own coordinates: boundaries and canonical forms, line work, hulls and triangulations, and simplification. None of them constructs a coordinate.

Basic operations

The basic operations rearrange a geometry’s own coordinates. boundary returns ring vertices and line endpoints, normalize and reverse reorder the input, and unique_points drops repeats. Every output coordinate is an input coordinate, and every decision is a comparison of stored f64 values or the exact location the predicates use, so nothing is approximate. All four are in geometres::ops.

Where these operations sort, they use the lexicographic order: by x, then y, comparing stored values exactly. -0.0 and 0.0 compare equal; a tie falls to the next key and then to the original position, so every result is deterministic.

boundary

pub fn boundary(g: &Geometry) -> Result<Geometry, GeometryError>

boundary returns the topological boundary of g, as relate defines it:

  • Point, MultiPoint: the empty MultiPoint; a point has no boundary.
  • LineString, MultiLineString: the OGC mod-2 boundary (the points that are an endpoint of an odd number of line strings) as a MultiPoint in exact lexicographic order. A closed line string’s endpoints cancel, so its boundary is empty. This is the boundary relate uses, computed by the same function.
  • Polygon, MultiPolygon: every ring as a closed LineString (its first vertex repeated last), exterior then holes, part by part, as a MultiLineString. Rings keep their orientation.
  • GeometryCollection: every ring of its polygonal leaves, and the mod-2 endpoints of its line leaves that lie outside the polygonal leaves. The result is a MultiLineString when there are only rings, a MultiPoint when there are only points, a GeometryCollection of the two (rings first) when there are both, and the empty MultiPoint when the boundary is empty.

Errors: GeometryError::CollectionElementsOverlap for a collection whose polygonal leaves overlap, which relate refuses for the same reason: the boundary would be the boundary of their union, which boundary does not construct.

use geometres::ops::boundary;
use geometres::types::{Coord2d, CoordSeq, Geometry, LineString, LinearRing, Polygon};

let c = Coord2d::new;

// An open line: its two endpoints, in lexicographic order rather than input order.
let line = LineString::new(CoordSeq::new(vec![c(2.0, 0.0), c(0.0, 0.0), c(1.0, 1.0)])).unwrap();
let Geometry::MultiPoint(ends) = boundary(&Geometry::LineString(line)).unwrap() else { panic!() };
assert_eq!(ends.num_points(), 2);
assert_eq!(ends.points()[0].coord(), c(1.0, 1.0));
assert_eq!(ends.points()[1].coord(), c(2.0, 0.0));

// A closed line has no boundary.
let closed = LineString::new(CoordSeq::new(vec![
    c(0.0, 0.0), c(1.0, 0.0), c(1.0, 1.0), c(0.0, 0.0),
])).unwrap();
let Geometry::MultiPoint(none) = boundary(&Geometry::LineString(closed)).unwrap() else { panic!() };
assert!(none.is_empty());

// A polygon's boundary is its ring, closed.
let square = Polygon::new_simple(LinearRing::new(CoordSeq::new(vec![
    c(0.0, 0.0), c(1.0, 0.0), c(1.0, 1.0), c(0.0, 1.0),
])).unwrap()).unwrap();
let Geometry::MultiLineString(rings) = boundary(&Geometry::Polygon(square)).unwrap() else { panic!() };
assert_eq!(rings.num_line_strings(), 1);
assert_eq!(rings.line_strings()[0].num_points(), 5);

normalize

pub fn normalize(g: &Geometry) -> Geometry

normalize returns the canonical form of g. Equal geometries written differently (rings starting at different vertices, parts or holes in different orders, line strings in either direction) normalize to the same value, byte for byte in the codec.

  • Rings start at their lexicographically smallest vertex and keep their orientation: exteriors stay counterclockwise and holes clockwise.
  • Holes are sorted by their rotated vertex sequence.
  • Parts of a multi-geometry are sorted by their normalized vertex sequence, a polygon by its exterior.
  • A LineString is reversed if its coordinate sequence compares greater than its reverse. A closed one, which has no meaningful start, starts at its smallest vertex, as a ring does, and runs in whichever direction makes its sequence smaller.
  • A MultiPoint’s points are sorted.
  • A GeometryCollection’s elements are normalized, then sorted by type (codec tag order), then by their whole coordinate sequence.

normalize is idempotent, and every coordinate of the result is a coordinate of g, bit for bit.

use geometres::ops::normalize;
use geometres::types::{Coord2d, CoordSeq, Geometry, LineString, LinearRing, Polygon};

let c = Coord2d::new;
let square = |v: Vec<Coord2d>| {
    Geometry::Polygon(Polygon::new_simple(LinearRing::new(CoordSeq::new(v)).unwrap()).unwrap())
};

// The same square, its ring started at two different vertices.
let a = square(vec![c(0.0, 0.0), c(1.0, 0.0), c(1.0, 1.0), c(0.0, 1.0)]);
let b = square(vec![c(1.0, 1.0), c(0.0, 1.0), c(0.0, 0.0), c(1.0, 0.0)]);
assert_ne!(a, b);
assert_eq!(normalize(&a), normalize(&b));

// A line and its reverse normalize to the same line.
let fwd = LineString::new(CoordSeq::new(vec![c(0.0, 0.0), c(2.0, 1.0)])).unwrap();
let rev = LineString::new(CoordSeq::new(vec![c(2.0, 1.0), c(0.0, 0.0)])).unwrap();
assert_eq!(normalize(&Geometry::LineString(fwd)), normalize(&Geometry::LineString(rev)));

// Idempotent.
assert_eq!(normalize(&normalize(&b)), normalize(&b));

reverse and Reversible

pub fn reverse<T: Reversible>(g: &T) -> T pub trait Reversible: Sized { fn reversed(&self) -> Self; }

reverse returns g with its direction reversed: a line string’s coordinates in reverse order, a multi line string’s components each reversed (in the same order), and a point unchanged.

Reversible marks a geometry whose direction can be reversed without leaving its type. It is implemented for the lineal types, whose direction is part of the value, and for Point and MultiPoint, which have none (reversal is the identity). Polygons are not offered: a reversed ring would invert its winding, which the polygon type’s invariant forbids.

use geometres::ops::reverse;
use geometres::types::{Coord2d, CoordSeq, LineString, Point};

let c = Coord2d::new;
let line = LineString::new(CoordSeq::new(vec![c(0.0, 0.0), c(1.0, 0.0), c(1.0, 1.0)])).unwrap();
let back = reverse(&line);
assert_eq!(back.start(), c(1.0, 1.0));
assert_eq!(back.end(), c(0.0, 0.0));
assert_eq!(reverse(&back), line);

// A point has no direction.
let p = Point::new(c(3.0, 4.0)).unwrap();
assert_eq!(reverse(&p), p);

unique_points

pub fn unique_points(g: &impl Relatable) -> MultiPoint

unique_points returns every distinct coordinate of g, in order of first occurrence: rings exterior then holes, without a closing vertex; parts in order; a collection’s leaves depth first.

Distinct means unequal under ==, so -0.0 and 0.0 count as one, and the first occurrence’s bits are kept.

use geometres::ops::unique_points;
use geometres::types::{Coord2d, CoordSeq, LineString};

let c = Coord2d::new;
// A closed line whose last vertex is written -0.0 rather than 0.0.
let line = LineString::new(CoordSeq::new(vec![
    c(0.0, 0.0), c(1.0, 0.0), c(1.0, 1.0), c(-0.0, 0.0),
])).unwrap();
let pts = unique_points(&line);
assert_eq!(pts.num_points(), 3);
// The first occurrence's bits are kept: +0.0, not -0.0.
assert!(pts.points()[0].x().is_sign_positive());

Line work

The line work operations join, order, cut and compare line strings. Merging and sequencing join and reorient whole input line strings at shared endpoints; they never cut one. Splitting cuts a line only at a point the caller supplied, and only where that point lies exactly on the line. Every output coordinate is an input coordinate, and every decision is exact: endpoints are matched by == on stored coordinates, and “on the line” is orient2d on stored coordinates. All are in geometres::ops.

Merging and sequencing operate on a node graph. Each input line string is an edge between its two endpoints; the nodes are the distinct endpoints under ==. A node’s degree counts edge ends, so a closed line string adds two to its own node.

line_merge

pub fn line_merge(g: &impl Relatable) -> MultiLineString

line_merge merges line strings that meet end to end at nodes of degree 2 into maximal line strings. Its input is g’s lineal leaves (a LineString, a MultiLineString’s components, or a collection’s lineal leaves); points and polygons are ignored. The lines are taken as given rather than noded: they are joined only at shared endpoints, matched exactly.

  • Nodes. A node of degree 2 joins its two lines; any other degree (1, or 3 and more) ends them.
  • Orientation. A merged line runs in the direction of the majority of its input lines. On a tie, an open line starts at its lexicographically smaller end.
  • Loops. A component whose nodes all have degree 2 becomes one closed line starting at its smallest node, oriented by majority; on a tie it leaves its start toward the smaller neighbor.
  • Output order is by vertex sequence, lexicographically.

Every output vertex is an input vertex, and every input segment appears in exactly one output line, once.

use geometres::ops::line_merge;
use geometres::types::{Coord2d, CoordSeq, LineString, MultiLineString};

let seg = |a: (f64, f64), b: (f64, f64)| {
    LineString::new(CoordSeq::new(vec![Coord2d::new(a.0, a.1), Coord2d::new(b.0, b.1)])).unwrap()
};
// Three pieces of one path; the middle one runs backward.
let lines = MultiLineString::new(vec![
    seg((0.0, 0.0), (1.0, 0.0)),
    seg((2.0, 0.0), (1.0, 0.0)),
    seg((2.0, 0.0), (3.0, 0.0)),
]);
let merged = line_merge(&lines);
assert_eq!(merged.num_line_strings(), 1);
let path = &merged.line_strings()[0];
assert_eq!(path.num_points(), 4);
// Two of the three pieces run left to right, so the merged line does too.
assert_eq!(path.start(), Coord2d::new(0.0, 0.0));
assert_eq!(path.end(), Coord2d::new(3.0, 0.0));

// A branch at (1, 0) gives that node degree 3, which ends the lines meeting there.
let branched = MultiLineString::new(vec![
    seg((0.0, 0.0), (1.0, 0.0)),
    seg((2.0, 0.0), (1.0, 0.0)),
    seg((2.0, 0.0), (3.0, 0.0)),
    seg((1.0, 0.0), (1.0, 1.0)),
]);
assert_eq!(line_merge(&branched).num_line_strings(), 3);

line_merge_directed

pub fn line_merge_directed(g: &impl Relatable) -> MultiLineString

line_merge_directed merges as line_merge does, but joins only lines that agree in direction: two lines meet at a node only when one ends there, the other starts there, and no other line touches it. Every output line keeps its input lines’ direction, and a directed loop starts at its smallest node.

use geometres::ops::line_merge_directed;
use geometres::types::{Coord2d, CoordSeq, LineString, MultiLineString};

let seg = |a: (f64, f64), b: (f64, f64)| {
    LineString::new(CoordSeq::new(vec![Coord2d::new(a.0, a.1), Coord2d::new(b.0, b.1)])).unwrap()
};
// Head to tail: merged.
let agree = MultiLineString::new(vec![seg((0.0, 0.0), (1.0, 0.0)), seg((1.0, 0.0), (2.0, 0.0))]);
assert_eq!(line_merge_directed(&agree).num_line_strings(), 1);

// Head to head: the directions disagree, so the lines stay apart.
let disagree = MultiLineString::new(vec![seg((0.0, 0.0), (1.0, 0.0)), seg((2.0, 0.0), (1.0, 0.0))]);
assert_eq!(line_merge_directed(&disagree).num_line_strings(), 2);

line_sequence

pub fn line_sequence(g: &impl Relatable) -> Result<MultiLineString, GeometryError>

line_sequence orders and orients g’s lineal leaves so that each starts where the previous one ended, one sequence per connected component. The lines are not merged: the result holds each input line once, possibly reversed. A component can be sequenced exactly when it has at most two nodes of odd degree, so that an Euler path exists.

Three rules make the result deterministic:

  • Start node: the smallest odd-degree node, preferring one where an input line already starts; with no odd-degree node, the smallest node.
  • Next line: at each node, the unused incident line whose far node is smallest, then the one earliest in the input (Hierholzer’s algorithm, so the path covers every line once).
  • Components in order of their start nodes.

Errors: GeometryError::NotSequenceable if some component has more than two nodes of odd degree.

use geometres::GeometryError;
use geometres::ops::line_sequence;
use geometres::types::{Coord2d, CoordSeq, LineString, MultiLineString};

let c = Coord2d::new;
let seg = |a: Coord2d, b: Coord2d| LineString::new(CoordSeq::new(vec![a, b])).unwrap();

// The second line is reversed so that it starts where the first ends.
let lines = MultiLineString::new(vec![seg(c(0.0, 0.0), c(1.0, 0.0)), seg(c(2.0, 0.0), c(1.0, 0.0))]);
let seq = line_sequence(&lines).unwrap();
assert_eq!(seq.num_line_strings(), 2); // sequenced, not merged
assert_eq!(seq.line_strings()[0].end(), seq.line_strings()[1].start());
assert_eq!(seq.line_strings()[1].end(), c(2.0, 0.0));

// A star of three lines has four odd-degree nodes: no Euler path exists.
let star = MultiLineString::new(vec![
    seg(c(1.0, 0.0), c(0.0, 0.0)),
    seg(c(1.0, 0.0), c(2.0, 0.0)),
    seg(c(1.0, 0.0), c(1.0, 1.0)),
]);
assert!(matches!(line_sequence(&star), Err(GeometryError::NotSequenceable)));

split_by_point

pub fn split_by_point(line: &LineString, p: Coord2d) -> Result<MultiLineString, GeometryError>

split_by_point cuts line at every passage through p: a line through p once gives two line strings meeting at p, and one through it k times gives k + 1. A passage is a vertex equal to p other than the first and last, or a segment with p exactly on its interior (orient2d on stored coordinates, and p within the segment’s box).

p is written into the result as given, so every output coordinate is a vertex of line or p. A point near the line is not snapped to it, because it is not on the line. Bringing a point onto a line constructs a coordinate, which this crate does not do.

Errors:

  • GeometryError::PointNotOnLineInterior if p is the line’s first or last vertex (for a closed line, its closing vertex), or not on the line at all.
  • GeometryError::NonFiniteCoordinate (position 0) if p is not finite.
use geometres::GeometryError;
use geometres::ops::split_by_point;
use geometres::types::{Coord2d, CoordSeq, LineString};

let c = Coord2d::new;
let line = LineString::new(CoordSeq::new(vec![c(0.0, 0.0), c(3.0, 1.0)])).unwrap();

// (1.5, 0.5) lies exactly on the segment.
let parts = split_by_point(&line, c(1.5, 0.5)).unwrap();
assert_eq!(parts.num_line_strings(), 2);
assert_eq!(parts.line_strings()[0].end(), c(1.5, 0.5));
assert_eq!(parts.line_strings()[1].start(), c(1.5, 0.5));

// (1, 1/3) is not: 1.0 / 3.0 rounds, so the point is off the line by a rounding
// error, and it is not snapped onto it.
assert!(matches!(split_by_point(&line, c(1.0, 1.0 / 3.0)), Err(GeometryError::PointNotOnLineInterior)));

// An endpoint is not a passage.
assert!(matches!(split_by_point(&line, c(0.0, 0.0)), Err(GeometryError::PointNotOnLineInterior)));

shared_paths and SharedPaths

pub fn shared_paths(a: &impl Lineal, b: &impl Lineal) -> SharedPaths pub struct SharedPaths { pub same_direction: MultiLineString, pub opposite_direction: MultiLineString }

shared_paths returns the paths a and b share, split by whether they run the same way. For each segment of a, the stretches it shares with segments of b (collinear and overlapping in more than a point, decided exactly) are found, unioned where b overlaps itself, and classed by the direction of b along them. Stretches of one class that meet at a vertex of a, consecutive along a, are joined into one line string. A single shared point is not a path and is not reported.

Both fields of SharedPaths are oriented as a runs and listed in a’s order. The inputs are taken as line strings rather than point sets: where a runs over the same stretch more than once, each pass is reported, with the direction b has there.

No point is constructed. Collinearity is orient2d being zero for both endpoints of one segment against the other. On their common line every point is fixed by one stored coordinate, so the shared stretch runs between two segment endpoints, and every output coordinate is a vertex of a or of b. The cost is one exact collinearity test per pair of segments.

use geometres::ops::shared_paths;
use geometres::types::{Coord2d, CoordSeq, LineString};

let c = Coord2d::new;
let line = |v: Vec<Coord2d>| LineString::new(CoordSeq::new(v)).unwrap();

let a = line(vec![c(0.0, 0.0), c(4.0, 0.0)]);
let with = line(vec![c(1.0, 0.0), c(3.0, 0.0)]);
let against = line(vec![c(3.0, 0.0), c(1.0, 0.0), c(1.0, 5.0)]);

let same = shared_paths(&a, &with);
assert_eq!(same.same_direction.num_line_strings(), 1);
assert!(same.opposite_direction.is_empty());

// The shared stretch is reported oriented as `a` runs: from (1, 0) to (3, 0).
let opp = shared_paths(&a, &against);
assert!(opp.same_direction.is_empty());
let path = &opp.opposite_direction.line_strings()[0];
assert_eq!((path.start(), path.end()), (c(1.0, 0.0), c(3.0, 0.0)));

Hulls and triangulation

The convex hull, the concave hull and the Delaunay triangulation of a geometry’s points, in geometres::ops. Each returns input points, bit for bit, and constructs no coordinate. The convex hull and the triangulation decide every step with exact predicates on stored coordinates; the concave hull selects its erosion in f64 and certifies its result exactly.

convex_hull

pub fn convex_hull(g: &impl Relatable) -> Result<Geometry, GeometryError>

convex_hull returns the convex hull of every coordinate of g:

  • the empty MultiPoint for a geometry with no coordinates;
  • a Point for one distinct coordinate;
  • a LineString of the two extreme points (lexicographically smallest first) when every coordinate is collinear;
  • otherwise a counterclockwise Polygon without holes, whose vertices are the hull’s corners: input vertices where the hull turns strictly left, starting at the lexicographically smallest.

The algorithm is Andrew’s monotone chain, and it makes two kinds of decision: the order of the points, which is the exact lexicographic order, and whether three points turn left, which is orient2d. Both are exact for every finite input. A point stays on a chain only on a strict left turn, so a point on the segment between two hull vertices is not a hull vertex.

Errors: none for valid input. The polygon is built through Polygon::new, which re-checks the ring and its winding; its error, which cannot occur, is returned rather than unwrapped.

use geometres::ops::convex_hull;
use geometres::types::{Coord2d, Geometry, MultiPoint, Point};

let pts = |v: &[(f64, f64)]| {
    MultiPoint::new(v.iter().map(|&(x, y)| Point::new(Coord2d::new(x, y)).unwrap()).collect())
};

// A square's corners, its center, and the midpoint (1, 0) of its bottom edge.
let g = pts(&[(1.0, 1.0), (2.0, 2.0), (1.0, 0.0), (0.0, 2.0), (2.0, 0.0), (0.0, 0.0)]);
let Geometry::Polygon(hull) = convex_hull(&g).unwrap() else { panic!() };
// (1, 0) is on the hull's boundary but is not a corner, so it is not a vertex.
assert_eq!(hull.exterior().num_vertices(), 4);
assert_eq!(hull.exterior().coords().as_slice()[0], Coord2d::new(0.0, 0.0));

// Collinear input: the segment between the two extremes.
let Geometry::LineString(seg) = convex_hull(&pts(&[(1.0, 1.0), (2.0, 2.0), (0.0, 0.0)])).unwrap() else {
    panic!()
};
assert_eq!((seg.start(), seg.end()), (Coord2d::new(0.0, 0.0), Coord2d::new(2.0, 2.0)));

concave_hull and ConcaveHullParameter

pub fn concave_hull(g: &impl Relatable, parameter: ConcaveHullParameter) -> Result<Geometry, GeometryError> pub enum ConcaveHullParameter { MaxEdgeLength(f64), MaxEdgeLengthRatio(f64) }

concave_hull returns a polygon containing every distinct vertex of g, tighter than the convex hull. The method is that of JTS’s ConcaveHull (Martin Davis): starting from the Delaunay triangulation, whose union is the convex hull, it repeatedly removes the border triangle with the longest boundary edge, while that edge is longer than the threshold and the removal keeps the region whole. A border triangle is removable exactly when it has one boundary edge and the vertex opposite that edge is not on the boundary.

The threshold is a selection rule; the claim is exact. Which triangles are eroded is decided by comparing edge lengths in f64, which selects among valid results. The claim, that the result is a valid polygon whose vertices are input points and which contains every input point, is certified exactly: the boundary is traced as one cycle or refused, the ring goes through the validating polygon constructor, and every input point is located against the result by exact point location.

The result is canonical: it depends only on the point set, and permutations of the input give identical results. Its ring starts at its lexicographically smallest vertex. Collinear boundary points stay on the ring, so the ratio-1 result equals the convex hull as a region, with every boundary point as a vertex. Degenerate input (fewer than three distinct points, or all collinear) follows convex_hull’s convention.

Variant Threshold
MaxEdgeLength(len) Erode boundary edges strictly longer than len, in map units.
MaxEdgeLengthRatio(r) The target length is shortest + r · (longest − shortest) over the Delaunay triangulation’s edge lengths, with r in [0, 1]. 0 erodes everything the removal rule allows; 1 keeps the convex hull.

Errors:

  • GeometryError::InvalidTolerance for a non-finite or negative length, or a ratio outside [0, 1].
  • GeometryError::TooManyEntries as delaunay refuses it.
  • GeometryError::Unvouched with UnvouchedReason::NotAHull if the certification re-check fails, which is not expected to occur.
use geometres::ops::{ConcaveHullParameter, area, concave_hull};
use geometres::types::{Coord2d, Geometry, MultiPoint, Point};

// The integer grid on [0, 4] x [0, 4], with a notch: no points at
// x = 1, 2, 3 in the top two rows.
let mut v = Vec::new();
for i in 0..5 {
    for j in 0..5 {
        if !((1..=3).contains(&i) && j >= 3) { v.push((f64::from(i), f64::from(j))); }
    }
}
let g = MultiPoint::new(v.iter().map(|&(x, y)| Point::new(Coord2d::new(x, y)).unwrap()).collect());

// Ratio 1 keeps the convex hull, with the collinear boundary points as vertices.
let Geometry::Polygon(full) = concave_hull(&g, ConcaveHullParameter::MaxEdgeLengthRatio(1.0)).unwrap()
else { panic!() };
assert_eq!(full.exterior().num_vertices(), 13);
assert_eq!(area(&full), 16.0);

// Eroding edges longer than 1.5 removes the triangle (0, 4), (2, 2), (4, 4),
// of area 4: the hull's boundary now dips to (2, 2).
let Geometry::Polygon(notched) = concave_hull(&g, ConcaveHullParameter::MaxEdgeLength(1.5)).unwrap()
else { panic!() };
assert_eq!(area(&notched), 12.0);
assert!(notched.exterior().coords().as_slice().contains(&Coord2d::new(2.0, 2.0)));
assert_eq!(notched.exterior().coords().as_slice()[0], Coord2d::new(0.0, 0.0));

assert!(concave_hull(&g, ConcaveHullParameter::MaxEdgeLengthRatio(1.5)).is_err());

delaunay

pub fn delaunay(g: &impl Relatable) -> Result<Triangulation, GeometryError>

delaunay computes the Delaunay triangulation of the distinct vertices of g, exactly and canonically. Every decision is orient2d or incircle on stored input coordinates, and the defining property is decided exactly: no input point lies strictly inside any output triangle’s circumcircle. Duplicate points are used once (-0.0 and 0.0 are the same point), and an input with no coordinates gives the empty triangulation.

Cocircular ties are cut by a fixed rule. A point set with four or more cocircular points has more than one Delaunay triangulation. The output triangles are grouped across every shared edge whose fourth point is exactly cocircular (incircle is zero); each group is a face of the unique Delaunay subdivision, a convex polygon inscribed in one empty circle, and each face is cut into triangles by the fan from its lexicographically smallest vertex. So the result depends only on the point set, not on the input order or the construction.

The construction is incremental insertion (Bowyer 1981; Watson 1981). The pass that finds the tie groups computes incircle for every internal edge, so the Delaunay property of the whole result is re-checked on every call, and each output triangle’s orientation is certified by one orient2d. Fewer than three distinct points, or all collinear, admit no triangle: the triangle list is empty, and the edges are the chain between lexicographically consecutive points along the line.

Errors:

  • GeometryError::TooManyEntries for more than u32::MAX - 1 distinct points, never a truncation.
  • GeometryError::Unvouched with UnvouchedReason::NotDelaunay if the certification re-check fails, which is expected never to occur.
use geometres::ops::delaunay;
use geometres::types::{Coord2d, MultiPoint, Point};

let pts = |v: &[(f64, f64)]| {
    MultiPoint::new(v.iter().map(|&(x, y)| Point::new(Coord2d::new(x, y)).unwrap()).collect())
};
let tri_coords = |t: &geometres::ops::Triangulation| -> Vec<[Coord2d; 3]> {
    let p = t.points();
    t.triangles().iter().map(|&[a, b, c]| [p[a as usize], p[b as usize], p[c as usize]]).collect()
};

// The four corners of a square are cocircular: two triangulations are Delaunay.
// The fan from the smallest vertex, (0, 0), picks the diagonal (0, 0)-(1, 1).
let t1 = delaunay(&pts(&[(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)])).unwrap();
let t2 = delaunay(&pts(&[(1.0, 1.0), (0.0, 1.0), (1.0, 0.0), (0.0, 0.0)])).unwrap();
let c = Coord2d::new;
assert_eq!(tri_coords(&t1), vec![
    [c(0.0, 0.0), c(1.0, 0.0), c(1.0, 1.0)],
    [c(0.0, 0.0), c(1.0, 1.0), c(0.0, 1.0)],
]);
assert_eq!(tri_coords(&t1), tri_coords(&t2)); // independent of input order
assert_eq!(t1.edges().num_line_strings(), 5);

// Collinear points: no triangle, and the chain of consecutive points as edges.
let line = delaunay(&pts(&[(2.0, 2.0), (0.0, 0.0), (1.0, 1.0)])).unwrap();
assert!(line.triangles().is_empty());
assert_eq!(line.edges().num_line_strings(), 2);

Triangulation

pub struct Triangulation

Triangulation holds the distinct input points and triangles over them whose circumcircles contain no input point strictly inside. Everything it reports is in canonical order: each triangle is counterclockwise and starts at its lexicographically smallest vertex, triangles are sorted by their vertex coordinates, and edges run from their lexicographically smaller endpoint, sorted.

Method Returns
points(&self) -> &[Coord2d] The distinct input points, in order of first occurrence, as unique_points reports them.
triangles(&self) -> &[[u32; 3]] The triangles, as indices into points(), each counterclockwise, in canonical order.
to_polygons(&self) -> GeometryCollection The triangles as polygons, in triangles() order. A GeometryCollection rather than a MultiPolygon, because neighboring triangles share edges, which a valid MultiPolygon does not allow.
edges(&self) -> MultiLineString Every edge exactly once, as two-point line strings: the triangles’ edges or, for degenerate input, the chain of collinear points.
use geometres::ops::{area, delaunay};
use geometres::types::{Coord2d, Geometry, MultiPoint, Point};

// A 3-4-5 right triangle and a point inside it.
let g = MultiPoint::new(
    [(0.0, 0.0), (4.0, 0.0), (0.0, 3.0), (1.0, 1.0)]
        .iter()
        .map(|&(x, y)| Point::new(Coord2d::new(x, y)).unwrap())
        .collect(),
);
let t = delaunay(&g).unwrap();
assert_eq!(t.points().len(), 4);
assert_eq!(t.triangles().len(), 3);

// The triangles tile the hull: their areas sum to 6.
let polys = t.to_polygons();
let total: f64 = polys
    .geometries()
    .iter()
    .map(|g| match g { Geometry::Polygon(p) => area(p), _ => unreachable!() })
    .sum();
assert_eq!(total, 6.0);
assert_eq!(t.edges().num_line_strings(), 6);

Simplification

Three simplifiers remove vertices; none moves or adds one, so every vertex of a result is a vertex of the input. All three share one structure. The choice of which vertices to remove is a selection rule evaluated in f64, and a choice within rounding of the tolerance may go either way. That choice is never a correctness claim, because the result is then vouched for exactly or refused: the f64 test decides which valid answer is returned, not whether it is valid.

Simplifier Guarantee
simplify (methods on the types) Vertex choice is f64; the result is vouched exactly or refused.
simplify_vw Vertex choice is f64 (effective areas, a selection rule); the result is vouched exactly by the constructors and validity_issues, or refused.
simplify_preserve_topology Vertex choice is f64; every topological check is exact, and the result is vouched exactly.

The first two do not preserve topology: rings can come to cross, holes to escape, parts to overlap. Their vouch refuses those results. simplify_preserve_topology never produces them. For a polygonal coverage, use coverage_simplify.

simplify and simplify_unvouched

pub fn simplify(&self, tolerance: f64) -> Result<Polygon, GeometryError> pub fn simplify_unvouched(&self, tolerance: f64) -> Result<MaybeVouched<Polygon>, GeometryError>

simplify is Ramer–Douglas–Peucker vertex reduction, vouched. It is a method on Polygon, MultiPolygon, LineString and MultiLineString; the contract is documented in the geometres::ops::simplify module. tolerance is a distance in the coordinates’ units: a vertex is dropped when its distance from the chord replacing it is not greater than tolerance. Zero is the identity.

The vouch is assembled from checks the crate already makes exactly: ring construction, simplicity by the exact self-contact test, winding and degeneracy by the certified sign of the area, hole placement by exact ring placement, and (for a multipolygon) parts meeting at most at points. A ring has no start, so its first chord is degenerate: vertex 0 and the vertex farthest from it are kept, and the two arcs between them are simplified as open chains. A LineString keeps its endpoints, a closed line is simplified as a ring, and lines are vouched by their constructor only, since a line string may cross itself.

simplify_unvouched, on Polygon and MultiPolygon, runs the same vouch and returns Ok(MaybeVouched::Unvouched(..)) exactly when the result is a constructible polygon whose only defect is a ring that touches or crosses itself. A result that is not a polygon at all is an error from both entry points. Nothing is repaired, dropped or reversed to make a value fit, and a refused result is not retried at a smaller tolerance.

Errors (for Polygon::simplify):

  • GeometryError::InvalidTolerance for a negative or non-finite tolerance.
  • GeometryError::Unvouched with a SelfIntersecting reason (exterior) or RingSelfIntersecting reason (a hole, by ring index) when a simplified ring touches or crosses itself; the result is available from simplify_unvouched.
  • The constructor’s error when no polygon can be built: a ring collapsed below three vertices (InsufficientVertices), lost its area (DegenerateRing) or inverted (IncorrectWindingOrder, IncorrectHoleWindingOrder); a hole pushed outside its exterior (HoleNotInsideExterior); holes that now overlap (OverlappingHoles).

MultiPolygon::simplify adds OverlappingParts when two simplified parts overlap or share a stretch of boundary, and refuses a self-intersecting part with a PartSelfIntersecting reason. LineString::simplify and MultiLineString::simplify return InvalidTolerance, or ConsecutiveDuplicateVertices if a closed line collapses to its anchor alone.

use geometres::GeometryError;
use geometres::types::{Coord2d, CoordSeq, LineString, LinearRing, Polygon};

let c = Coord2d::new;
// A 2 x 2 square whose top edge bulges by 0.05 at (1, 2.05).
let poly = Polygon::new_simple(LinearRing::new(CoordSeq::new(vec![
    c(0.0, 0.0), c(2.0, 0.0), c(2.0, 2.0), c(1.0, 2.05), c(0.0, 2.0),
])).unwrap()).unwrap();

assert_eq!(poly.simplify(0.1).unwrap().exterior().num_vertices(), 4);
assert_eq!(poly.simplify(0.0).unwrap(), poly); // zero is the identity
assert!(matches!(poly.simplify(-1.0), Err(GeometryError::InvalidTolerance { .. })));

// A line keeps its endpoints.
let line = LineString::new(CoordSeq::new(vec![c(0.0, 0.0), c(1.0, 0.1), c(2.0, 0.0)])).unwrap();
assert_eq!(line.simplify(0.2).unwrap().num_points(), 2);
use geometres::GeometryError;
use geometres::types::{Coord2d, CoordSeq, LinearRing, MaybeVouched, Polygon};

let c = Coord2d::new;
// A square with a slight dip in its bottom edge, at (5, -0.5), and a deep notch
// from the top whose tip, (5, -0.2), sits 0.3 above the dip.
let poly = Polygon::new_simple(LinearRing::new(CoordSeq::new(vec![
    c(0.0, 0.0), c(5.0, -0.5), c(10.0, 0.0), c(10.0, 10.0),
    c(6.0, 10.0), c(5.0, -0.2), c(4.0, 10.0), c(0.0, 10.0),
])).unwrap()).unwrap();

// Removing the dip makes the bottom edge cut through the notch: the ring
// crosses itself, so the vouch refuses the result.
assert!(matches!(poly.simplify(0.6), Err(GeometryError::Unvouched { .. })));

// The unvouched entry point hands it back, marked as not vouched for.
let out = poly.simplify_unvouched(0.6).unwrap();
assert!(!out.is_vouched());
assert!(matches!(out, MaybeVouched::Unvouched(_)));

simplify_vw and Simplifiable

pub fn simplify_vw<G: Simplifiable>(g: &G, threshold: f64) -> Result<G, GeometryError>

simplify_vw is Visvalingam–Whyatt simplification, vouched. Visvalingam and Whyatt (Line generalisation by repeated elimination of points, The Cartographic Journal 30(1), 1993) rank every vertex by its effective area: the area of the triangle it forms with its two current neighbors. The vertex with the smallest effective area is removed while that area is below threshold (or is exactly 0), its neighbors’ areas are recomputed, and the elimination repeats. Ties go to the vertex earlier in the input, so the result is deterministic.

threshold is an area, in the coordinates’ units squared, and must be finite and at least 0. JTS’s VWSimplifier takes a distance tolerance and squares it, so a JTS tolerance t corresponds to a threshold of t * t here. A threshold of 0 removes exactly the vertices whose effective area computes as 0.0 in f64.

Each line and ring is simplified independently. A line’s endpoints are never removed, whether or not they coincide; a ring keeps at least three vertices. A vertex whose two neighbors are the same point is not removable while they are. The result has the same type as g, and is built through the checked constructors and judged by validity_issues.

Simplifiable is the sealed trait of the types simplify_vw accepts: LineString, MultiLineString, Polygon, MultiPolygon and GeometryCollection. A collection’s points and multipoints are kept unchanged.

Errors: GeometryError::InvalidTolerance for a negative or non-finite threshold. A result with any validity issue (a ring that crosses or touches itself, a hole outside its exterior, overlapping parts) is refused as GeometryError::Unvouched with UnvouchedReason::SimplifiedInvalid. A result that cannot be built at all, such as a ring left with three collinear vertices (DegenerateRing) or an inverted one, is refused with its constructor’s error.

use geometres::ops::simplify_vw;
use geometres::types::{Coord2d, CoordSeq, LineString};

let line = LineString::new(CoordSeq::new(vec![
    Coord2d::new(0.0, 0.0),
    Coord2d::new(5.0, 0.1), // effective area 0.5 * 10 * 0.1 = 0.5
    Coord2d::new(10.0, 0.0),
    Coord2d::new(10.0, 10.0), // effective area 50
])).unwrap();

assert_eq!(simplify_vw(&line, 1.0).unwrap().num_points(), 3);
assert_eq!(simplify_vw(&line, 0.5).unwrap().num_points(), 4); // 0.5 is not below 0.5
assert!(simplify_vw(&line, f64::NAN).is_err());

simplify_preserve_topology

pub fn simplify_preserve_topology<G: TopologySimplifiable>(g: &G, tolerance: f64) -> Result<G, GeometryError>

simplify_preserve_topology is Douglas–Peucker vertex reduction that removes a vertex only where doing so changes no topological relationship, decided exactly. Its promise:

  1. Every output vertex is an input vertex, unchanged, bit for bit.
  2. Every removed vertex lies within tolerance of the chord that replaced it, as evaluated in f64, by the same distance test as Polygon::simplify.
  3. No two elements gain or lose a contact. The elements are the rings of every polygon, the lines and the points. Disjoint elements stay disjoint, touching ones still touch at the same points, and a line’s own self-intersections are unchanged.
  4. No element moves across another. Every hole stays inside its exterior, every part outside the others, and every point and vertex on the same side of every ring.
  5. The output is valid whenever the input is.

The endpoints of every line, every vertex whose coordinate occurs more than once in the input, and every vertex lying on another segment other than at that segment’s endpoints are never removed. A candidate chord from Douglas–Peucker is accepted only when, apart from its two ends, no other segment or point meets the closed region between the chord and the run it replaces, and the run does not touch itself. That condition is decided by orient2d and comparisons of stored coordinates. A rejected chord is split at the run’s farthest vertex, as Douglas–Peucker recurses. tolerance follows Polygon::simplify: not greater than, zero is the identity.

TopologySimplifiable is the sealed trait of the accepted types: LineString, MultiLineString, Polygon, MultiPolygon and GeometryCollection. A collection’s points and multipoints are kept unchanged, as obstacles.

Errors:

  • GeometryError::InvalidTolerance for a negative or non-finite tolerance.
  • GeometryError::Unvouched with UnvouchedReason::InvalidInput when g has a validity issue; the result exists and is available from simplify_preserve_topology_unvouched. With UnvouchedReason::InvalidResult if the defensive check of the output ever fires, which is not expected.
  • GeometryError::TooManyEntries for an input with more than u32::MAX vertices and points.
  • A constructor’s error if the output cannot be built, which the argument rules out for a valid input.
use geometres::GeometryError;
use geometres::ops::simplify_preserve_topology;
use geometres::types::{Coord2d, CoordSeq, LinearRing, MultiPolygon, Polygon};

let poly = |v: &[(f64, f64)]| {
    Polygon::new_simple(LinearRing::new(CoordSeq::new(
        v.iter().map(|&(x, y)| Coord2d::new(x, y)).collect(),
    )).unwrap()).unwrap()
};
// A square with a small bump at (5, -0.5) and a dip at (5, 9) in its top edge,
// and a triangle whose tip, (5, 9.5), sits inside the dip.
let square = poly(&[(0.0, 0.0), (5.0, -0.5), (10.0, 0.0), (10.0, 10.0), (5.0, 9.0), (0.0, 10.0)]);
let tri = poly(&[(5.0, 9.5), (6.0, 12.0), (4.0, 12.0)]);
let mp = MultiPolygon::new(vec![square, tri]).unwrap();

// Plain Douglas-Peucker removes the dip, and the square's top edge now runs
// through the triangle: the vouch refuses the result.
assert!(matches!(mp.simplify(1.5), Err(GeometryError::OverlappingParts { .. })));

// The topology-preserving simplifier removes the bump but keeps the dip.
let out = simplify_preserve_topology(&mp, 1.5).unwrap();
let ext = out.polygons()[0].exterior().coords().as_slice();
assert_eq!(ext.len(), 5);
assert!(ext.contains(&Coord2d::new(5.0, 9.0)));
assert!(!ext.contains(&Coord2d::new(5.0, -0.5)));

simplify_preserve_topology_unvouched

pub fn simplify_preserve_topology_unvouched<G: TopologySimplifiable>(g: &G, tolerance: f64) -> Result<MaybeVouched<G>, GeometryError>

simplify_preserve_topology_unvouched returns a result that is not vouched for as MaybeVouched::Unvouched rather than refusing it. A valid input gives MaybeVouched::Vouched. An invalid input gives the computed result with UnvouchedReason::InvalidInput and the input’s first validity issue. Promises 1 to 4 hold for it all the same, so its defects are exactly the input’s, and no new ones.

Errors: as simplify_preserve_topology, minus the Unvouched refusal.

use geometres::GeometryError;
use geometres::ops::{simplify_preserve_topology, simplify_preserve_topology_unvouched};
use geometres::types::{Coord2d, CoordSeq, LinearRing, MaybeVouched, Polygon};

let c = Coord2d::new;
// The last edge, (0, 4) to (2, -1), crosses the first: the ring is not simple.
// Polygon constructors do not check simplicity, so this polygon exists.
let bad = Polygon::new_simple(LinearRing::new(CoordSeq::new(vec![
    c(0.0, 0.0), c(4.0, 0.0), c(4.0, 4.0), c(0.0, 4.0), c(2.0, -1.0),
])).unwrap()).unwrap();

assert!(matches!(simplify_preserve_topology(&bad, 0.5), Err(GeometryError::Unvouched { .. })));
assert!(matches!(simplify_preserve_topology_unvouched(&bad, 0.5), Ok(MaybeVouched::Unvouched(_))));