Validity
Exact validation in the OGC sense: every reason raw coordinates cannot form a geometry, the two issues a constructed geometry can still have, and simplicity.
Validation in geometres works at two levels. The constructors reject:
LinearRing::new and Polygon::new return the first defect they meet and nothing
else. The functions on this page are the complementary non-rejecting form: they run every check and
return every issue found, so a caller fixing a geometry sees the whole list at once. Every decision is exact.
Orientation is decided by a certified area sign, and self-contact, ring placement and the connectivity of the
interior by exact tests. No issue is reported by constructing a point.
An operation does not refuse its input because the input is invalid. validate
is the tool for detecting invalid geometry, and a caller who operates on invalid geometry receives a result
that is not vouched for.
Validating raw coordinates
validate, validate_line and validate_multipolygon take raw
coordinates and return every reason they cannot form a valid geometry, by ring and vertex index, rather than
failing on the first. They take CoordSeq values because a Polygon that exists is
already valid. CoordSeq is the one type in the crate that can hold anything a constructor
refuses (too few vertices, repeats, a self-crossing, either winding, a non-finite coordinate) while still
being coordinates and nothing else. All four items are in geometres::ops.
The conventions are the constructors’ own:
- A closing vertex (the first repeated as the last) is accepted and stripped, as
LinearRing::newdoes. It is not aDuplicatePoint. - Orientation is the certified sign of the ring’s area: ring 0 must be positive
(counterclockwise), every other ring negative (clockwise). An exactly zero area is a
DegenerateRing, and no orientation is reported for it. - Indices are vertex or edge indices into the ring as given, less the closing vertex if
it
had one. Edge
eis the edge that leaves vertexetoward the next distinct vertex. - A ring with a non-finite coordinate gets that issue for each offending vertex and nothing else. A ring
with fewer than three distinct vertices gets
TooFewPoints(and anyDuplicatePoints) and nothing else.
validate
pub fn validate(rings: &[CoordSeq]) -> Vec<ValidityIssue>
Every issue that would keep rings from becoming a Polygon: ring 0 is the
would-be exterior, rings 1.. the would-be holes. An empty Vec means the rings pass every
check.
An empty slice has no rings and no issues.
The issues come in a fixed order. The per-ring issues come first, in ring order. Then the placement
issues, in Polygon::new’s order (each hole against the exterior, then each pair of
holes), decided by the same exact test, so a placement issue is reported if and only if
Polygon::new refuses the placement, and the first one names the hole or pair
Polygon::new names. Last comes a disconnected interior, if every other check passed (an
orientation issue aside). Placement is skipped for a ring that is non-finite, has too few points, has an
area that is not a number, or is degenerate: it bounds no region to place.
use geometres::ops::{ValidityIssue, validate};
use geometres::types::{Coord2d, CoordSeq};
let seq = |v: &[(f64, f64)]| CoordSeq::new(v.iter().map(|&(x, y)| Coord2d::new(x, y)).collect());
// A clockwise exterior with a repeated vertex, and a "hole" far outside it.
let exterior = seq(&[(0.0, 0.0), (0.0, 4.0), (0.0, 4.0), (4.0, 4.0), (4.0, 0.0)]);
let hole = seq(&[(10.0, 10.0), (10.0, 11.0), (11.0, 11.0), (11.0, 10.0)]);
// Every issue is reported, not only the first.
assert_eq!(
validate(&[exterior, hole]),
vec![
ValidityIssue::DuplicatePoint { ring: 0, index: 1 },
ValidityIssue::RingOrientation { ring: 0 },
ValidityIssue::HoleOutsideExterior { ring: 1 },
]
);
// A counterclockwise square passes every check.
assert!(validate(&[seq(&[(0.0, 0.0), (4.0, 0.0), (4.0, 4.0), (0.0, 4.0)])]).is_empty());
validate_line
pub fn validate_line(line: &CoordSeq) -> Vec<ValidityIssue>
Every issue that would keep line from becoming a LineString: a non-finite
coordinate, fewer than two vertices, a consecutive repeat. Issues name ring 0.
A line is not closed, so a last vertex equal to the first is an ordinary pair of vertices. A line may cross itself, so no self-contact is reported.
use geometres::ops::{ValidityIssue, validate_line};
use geometres::types::{Coord2d, CoordSeq};
let seq = |v: &[(f64, f64)]| CoordSeq::new(v.iter().map(|&(x, y)| Coord2d::new(x, y)).collect());
assert_eq!(
validate_line(&seq(&[(0.0, 0.0), (0.0, 0.0)])),
vec![
ValidityIssue::DuplicatePoint { ring: 0, index: 0 },
ValidityIssue::TooFewPoints { ring: 0, found: 1, required: 2 },
]
);
// A closed line, and a line that crosses itself, are both valid lines.
assert!(validate_line(&seq(&[(0.0, 0.0), (1.0, 0.0), (0.0, 0.0)])).is_empty());
assert!(validate_line(&seq(&[(0.0, 0.0), (2.0, 2.0), (2.0, 0.0), (0.0, 2.0)])).is_empty());
validate_multipolygon
pub fn validate_multipolygon(parts: &[Vec<CoordSeq>]) -> Vec<(usize,
ValidityIssue)>
Every issue that would keep parts from becoming a MultiPolygon: each
part’s
rings as validate takes them (ring 0 the exterior), tagged with the part’s index. The
issues of each part come first, in part order. Then come the issues between parts, for every pair of parts
that would each construct, in the order MultiPolygon::new checks pairs:
NestedPartswhen one part’s exterior lies inside the other’s and meets none of its holes beyond isolated points;PartsOverlapfor any other overlap: crossing exteriors, a shared stretch, or a part’s exterior meeting the other’s holes.
A pair draws one of these if and only if MultiPolygon::new would refuse it
with GeometryError::OverlappingParts, by the same exact test. A pair involving a part that
would
not construct is not judged, since its regions are not defined. Parts that meet at a single point are
valid.
use geometres::ops::{ValidityIssue, validate_multipolygon};
use geometres::types::{Coord2d, CoordSeq};
// A counterclockwise square with lower-left corner (x, y) and side s.
let square = |x: f64, y: f64, s: f64| {
vec![CoordSeq::new(vec![
Coord2d::new(x, y),
Coord2d::new(x + s, y),
Coord2d::new(x + s, y + s),
Coord2d::new(x, y + s),
])]
};
// Two squares that share an edge: a shared stretch is an overlap.
assert_eq!(
validate_multipolygon(&[square(0.0, 0.0, 4.0), square(4.0, 0.0, 4.0)]),
vec![(1, ValidityIssue::PartsOverlap { part: 1, other: 0 })]
);
// A square inside another.
assert_eq!(
validate_multipolygon(&[square(0.0, 0.0, 4.0), square(1.0, 1.0, 2.0)]),
vec![(1, ValidityIssue::NestedParts { part: 1, inside: 0 })]
);
// Two squares that touch at one corner are valid parts.
assert!(validate_multipolygon(&[square(0.0, 0.0, 4.0), square(4.0, 4.0, 4.0)]).is_empty());
ValidityIssue
#[non_exhaustive]
pub enum ValidityIssue
One reason a ring could not become part of a valid Polygon or LineString, or a
set of parts a valid MultiPolygon. Every variant is a statement about coordinates and indices
into the caller’s input. Nothing here names a record, a schema, a reference system or a format, and
no variant carries a constructed point: a contact is located by the indices of the edges
involved.
| Variant | Meaning | Constructor’s counterpart |
|---|---|---|
NonFiniteCoordinate { ring, index } |
A coordinate of the ring is NaN or infinite. Reported once per offending vertex;
index
is the vertex in the ring as given. |
GeometryError::NonFiniteCoordinate |
TooFewPoints { ring, found, required } |
Too few distinct vertices: three for a polygon ring, two for a line. found counts the
vertices after the closing vertex (if any) and consecutive repeats are removed. |
GeometryError::InsufficientVertices |
DuplicatePoint { ring, index } |
Two consecutive vertices are identical. index is the first of the pair; the second is
index + 1, or vertex 0 across the closing edge of a ring.
|
GeometryError::ConsecutiveDuplicateVertices |
NonFiniteArea { ring } |
The ring’s area is not a finite number: its coordinates are so large that the shoelace products overflow. No orientation is reported, and the ring is not placed. | GeometryError::NonFiniteResult |
DegenerateRing { ring } |
The ring’s exact signed area is zero (every vertex collinear, or lobes that cancel exactly, as in a symmetric bow tie). A permanent contract with no tolerance: a ring with any nonzero area is not degenerate. | GeometryError::DegenerateRing |
RingOrientation { ring } |
The ring is wound the wrong way for its position: ring 0 must be counterclockwise and every other ring clockwise. | IncorrectWindingOrder, IncorrectHoleWindingOrder |
SelfIntersection { ring, edges } |
Two edges of the ring meet somewhere other than the vertex two consecutive edges share: a proper
crossing, a vertex on a non-adjacent edge, a vertex visited twice, or a fold-back. One contact is
reported per pair of edges; the lower index comes first, except that a fold-back across the closing
edge is (n − 1, 0). |
None: constructors do not test simplicity |
HoleOutsideExterior { ring } |
A hole that is not inside the exterior: disjoint from it, or surrounding it, touching it at points at most. | GeometryError::HoleNotInsideExterior |
NestedHoles { ring, inside } |
Hole ring is inside hole inside. |
GeometryError::OverlappingHoles |
RingsCross { ring, other, edges } |
Two different rings cross, or overlap along a stretch of positive length. ring is the
later in input order, other the earlier, and edges a witnessing pair
(edge of ring, edge of other).
|
HoleNotInsideExterior (against the exterior), OverlappingHoles (between
holes) |
DuplicateRings { ring, other } |
Two rings bound the same point set: the same ring listed twice, perhaps from another start, in the other direction, or with extra collinear vertices. | HoleNotInsideExterior, OverlappingHoles |
DisconnectedInterior { ring, vertex } |
The rings touch one another in a cycle, which cuts the interior into two or more pieces. The touch
at
vertex vertex of ring ring closes a cycle (ring is the lowest
ring with the touch point as a vertex). One is reported per polygon. |
None: Polygon::new admits it |
PartsOverlap { part, other } |
Two parts of a multipolygon overlap: their interiors meet, or their boundaries share a stretch.
part is the later part, other the earlier.
|
GeometryError::OverlappingParts |
NestedParts { part, inside } |
Part part lies inside the body of part inside (its exterior inside the
other’s exterior, meeting none of its holes beyond isolated points). |
GeometryError::OverlappingParts |
Two methods classify an issue. ring() returns the ring the issue is about (0 the exterior):
for an issue between rings, the later ring; for an issue between parts, 0.
constructor_refuses() is true for every issue a constructor refuses, which is
everything except SelfIntersection and DisconnectedInterior.
use geometres::ops::ValidityIssue;
let crossing = ValidityIssue::RingsCross { ring: 2, other: 0, edges: (1, 3) };
assert_eq!(crossing.ring(), 2); // the later of the two rings
assert!(crossing.constructor_refuses());
// The two issues construction leaves to `validity_issues`.
assert!(!ValidityIssue::SelfIntersection { ring: 0, edges: (2, 5) }.constructor_refuses());
assert!(!ValidityIssue::DisconnectedInterior { ring: 1, vertex: 2 }.constructor_refuses());
assert_eq!(ValidityIssue::PartsOverlap { part: 3, other: 1 }.ring(), 0);
Validating constructed geometry
A constructed geometry has passed every check except two: ring self-intersection and a
disconnected interior. Polygon::new does not test ring simplicity, and it
accepts holes that touch the exterior or each other at points, which can chain into a cycle of touches that
cuts the interior in two. OGC calls both invalid. validity_issues reports them, at any depth of
a
collection, and is_valid answers yes or no. All three items are in
geometres::ops.
validity_issues
pub fn validity_issues(g: &impl Relatable) -> Vec<LocatedIssue>
Every validity issue of g that its construction does not check:
ValidityIssue::SelfIntersection and ValidityIssue::DisconnectedInterior.
Everything else OGC requires, construction has already refused.
Points and lines have no such issue, since OGC lets a line cross itself. A polygon reports each ring’s self-contacts by edge index and, only if no ring has one, a disconnected interior. A multipolygon reports each part’s issues, and a collection each element’s, at every depth. Issues come in the order the polygons are met, each with its path. The self-contact test and the touch graph are exact on the stored coordinates.
use geometres::ops::{ValidityIssue, validity_issues};
use geometres::types::{Coord2d, CoordSeq, LinearRing, Polygon};
let ring = |v: &[(f64, f64)]| {
LinearRing::new(CoordSeq::new(v.iter().map(|&(x, y)| Coord2d::new(x, y)).collect()))
};
// A 4 x 4 square with a diamond hole whose left and right corners touch
// the exterior: the touches cut the interior into two pieces.
let exterior = ring(&[(0.0, 0.0), (4.0, 0.0), (4.0, 4.0), (0.0, 4.0)]).unwrap();
let hole = ring(&[(0.0, 2.0), (2.0, 3.0), (4.0, 2.0), (2.0, 1.0)]).unwrap();
let polygon = Polygon::new(exterior, vec![hole]).unwrap(); // constructible
let issues = validity_issues(&polygon);
assert_eq!(issues.len(), 1);
assert!(issues[0].path.is_empty()); // a polygon passed directly
assert_eq!(issues[0].issue, ValidityIssue::DisconnectedInterior { ring: 1, vertex: 2 });
is_valid
pub fn is_valid(g: &impl Relatable) -> bool
true if g is valid in the OGC sense, that is, when validity_issues
is empty.
use geometres::ops::is_valid;
use geometres::types::{Coord2d, CoordSeq, LineString, LinearRing, Polygon};
let seq = |v: &[(f64, f64)]| CoordSeq::new(v.iter().map(|&(x, y)| Coord2d::new(x, y)).collect());
let square = Polygon::new(
LinearRing::new(seq(&[(0.0, 0.0), (4.0, 0.0), (4.0, 4.0), (0.0, 4.0)])).unwrap(),
vec![],
).unwrap();
assert!(is_valid(&square));
// An exterior that passes through (2, 4) twice is constructible but not valid.
let pinched = Polygon::new(
LinearRing::new(seq(&[
(0.0, 0.0), (4.0, 0.0), (4.0, 4.0), (2.0, 4.0),
(3.0, 2.0), (1.0, 2.0), (2.0, 4.0), (0.0, 4.0),
])).unwrap(),
vec![],
).unwrap();
assert!(!is_valid(&pinched));
// A line that crosses itself is valid.
let bow = LineString::new(seq(&[(0.0, 0.0), (2.0, 2.0), (2.0, 0.0), (0.0, 2.0)])).unwrap();
assert!(is_valid(&bow));
LocatedIssue
#[non_exhaustive]
pub struct LocatedIssue { pub path: Vec<usize>, pub issue: ValidityIssue }
A validity issue of a constructed geometry, with where it is. path leads from the geometry
passed to the polygon the issue is about: for a collection, the element index at each level of nesting;
then,
for a multipolygon, the part index. The ring and any vertex or edge indices are in issue,
counted in the polygon’s stored rings.
- A
Polygonpassed directly has an empty path. - Part 2 of a multipolygon has
[2]. - Part 0 of a multipolygon that is element 1 of a collection has
[1, 0].
use geometres::ops::{ValidityIssue, validity_issues};
use geometres::types::{Coord2d, CoordSeq, LinearRing, MultiPolygon, Polygon};
let ring = |v: &[(f64, f64)]| {
LinearRing::new(CoordSeq::new(v.iter().map(|&(x, y)| Coord2d::new(x, y)).collect())).unwrap()
};
let valid = Polygon::new(ring(&[(10.0, 0.0), (11.0, 0.0), (11.0, 1.0), (10.0, 1.0)]), vec![]).unwrap();
let cut = Polygon::new(
ring(&[(0.0, 0.0), (4.0, 0.0), (4.0, 4.0), (0.0, 4.0)]),
vec![ring(&[(0.0, 2.0), (2.0, 3.0), (4.0, 2.0), (2.0, 1.0)])],
).unwrap();
// The disconnected polygon is part 1 of the multipolygon.
let parts = MultiPolygon::new(vec![valid, cut]).unwrap();
let issues = validity_issues(&parts);
assert_eq!(issues.len(), 1);
assert_eq!(issues[0].path, vec![1]);
assert_eq!(issues[0].issue, ValidityIssue::DisconnectedInterior { ring: 1, vertex: 2 });
Simplicity and pinches
is_simple decides OGC simplicity for every geometry type, and split_pinches cuts
a
ring that passes through one of its vertices twice into loops that do not. Both are in
geometres::ops, and both are exact: neither constructs a coordinate.
is_simple
pub fn is_simple(g: &impl Relatable) -> bool
true if g is simple in the OGC sense. The rule depends on the type:
| Type | Simple when |
|---|---|
Point |
always |
MultiPoint |
no point repeats (coordinates compared by value) |
LineString |
it passes through no point twice, except that a closed line’s first and last vertex coincide |
MultiLineString |
each element is simple, and two elements meet only at points on the boundary of both: an endpoint of each, neither element closed (a closed line has no boundary under the mod-2 rule) |
Polygon, MultiPolygon |
every ring is simple (OGC reads polygon simplicity as ring simplicity) |
GeometryCollection |
every element is simple; elements are not compared with each other |
An empty geometry is simple. Every decision is arithmetica::orient2d on stored coordinates
or
an exact comparison of stored coordinates. Two segments that touch without crossing properly meet at an
endpoint of one of them, so every contact is located at an input coordinate, and none is
constructed.
use geometres::ops::is_simple;
use geometres::types::{Coord2d, CoordSeq, LineString, MultiLineString, MultiPoint, Point};
let line = |v: &[(f64, f64)]| {
LineString::new(CoordSeq::new(v.iter().map(|&(x, y)| Coord2d::new(x, y)).collect())).unwrap()
};
assert!(!is_simple(&line(&[(0.0, 0.0), (2.0, 2.0), (2.0, 0.0), (0.0, 2.0)]))); // crosses itself
assert!(is_simple(&line(&[(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 0.0)]))); // closed
// Two lines meeting end to end are simple; a crossing is not.
let a = line(&[(0.0, 0.0), (1.0, 0.0)]);
let b = line(&[(1.0, 0.0), (2.0, 0.0)]);
let c = line(&[(0.5, -1.0), (0.5, 1.0)]);
assert!(is_simple(&MultiLineString::new(vec![a.clone(), b])));
assert!(!is_simple(&MultiLineString::new(vec![a, c])));
// A repeated point.
let p = Point::new(Coord2d::new(1.0, 1.0)).unwrap();
assert!(!is_simple(&MultiPoint::new(vec![p, p])));
split_pinches
pub fn split_pinches(ring: &CoordSeq) -> Vec<CoordSeq>
Splits a closed coordinate sequence at every vertex it passes through twice, exactly. A pinch is a ring that visits one of its own vertices twice, such as an exterior that loops in to draw a hole touching it at a point, or a figure eight. It is not an OGC-simple ring, but it bounds a well-defined region, and cutting it at the repeated vertex gives that region in OGC form without moving a point: every loop is a run of the ring’s own edges, and together the loops use each edge once.
The sequence is first normalized: consecutive duplicate vertices are collapsed and the closing vertex, if
present, is dropped. Each returned loop visits no vertex twice, runs in the ring’s own direction,
and
starts at a pinch vertex, except possibly the last, which starts where the input does. Vertices are
compared
by their stored f64 bits, after −0.0 is mapped to 0.0, with
no
tolerance and no arithmetic. A sequence with a non-finite coordinate is returned whole.
The split does not decide which loop is a hole and which an exterior, whether a loop is a valid ring, or whether the fill rules agree on the region. That remains the caller’s job. The loops come out in the pop order of a single stack pass. To reproduce the normalized input, start from the last loop and, taking the others in reverse order, insert each one immediately before the first occurrence of its first vertex.
use geometres::ops::split_pinches;
use geometres::types::{Coord2d, CoordSeq};
let seq = |v: &[(f64, f64)]| CoordSeq::new(v.iter().map(|&(x, y)| Coord2d::new(x, y)).collect());
// A square exterior that loops in at (2, 4) to draw a triangular hole.
let pinched = seq(&[
(0.0, 0.0), (4.0, 0.0), (4.0, 4.0), (2.0, 4.0),
(3.0, 2.0), (1.0, 2.0), (2.0, 4.0), (0.0, 4.0),
]);
let loops = split_pinches(&pinched);
assert_eq!(
loops,
vec![
// The inner loop, starting at the pinch vertex (clockwise: the hole).
seq(&[(2.0, 4.0), (3.0, 2.0), (1.0, 2.0)]),
// What remained: the outer square, starting where the input does.
seq(&[(0.0, 0.0), (4.0, 0.0), (4.0, 4.0), (2.0, 4.0), (0.0, 4.0)]),
]
);