{ } JustinGeoSci

Predicates

The exact DE-9IM matrix of any two geometries, the named OGC predicates read from it, point location, and prepared masks whose answers are identical to the unprepared ones.

The DE-9IM matrix

The Dimensionally Extended 9-Intersection Model records, for each pair of topological components (interior, boundary, exterior) of two geometries A and B, the largest dimension of their intersection. geometres::predicates::relate computes this matrix and returns it with the operands' dimensions; the matrix type is geometres::topology::de9im::IntersectionMatrix, and its cells are geometres::topology::label::Dimension values.

The matrix is exact. Every sign decision is arithmetica::orient2d on the input coordinates, and nothing constructs an intersection coordinate: a vertex exactly on an edge is Boundary, and a vertex one ulp off it is not. Each predicate is a fixed boolean function of the matrix and the two dimensions, so each predicate is exact too.

Interior(B) Boundary(B) Exterior(B)
Interior(A) II IB IE
Boundary(A) BI BB BE
Exterior(A) EI EB EE

relate

pub fn relate(a: &impl Relatable, b: &impl Relatable) -> Result<Relation, GeometryError>

relate computes one exact DE-9IM matrix for any two geometries, and every predicate is read from the Relation it returns. Every ordered pair of geometry types is supported, multipart included. Linear geometry uses the OGC mod-2 boundary rule: a point is on the boundary of a MultiLineString when it is the endpoint of an odd number of its components. Areal geometry uses the topological boundary, so a point where two parts of a MultiPolygon touch is boundary, as in OGC. Empty geometries are the empty point set.

relate(b, a) is the transpose of relate(a, b): II, BB and EE are unchanged, and IB ↔ BI, IE ↔ EI, BE ↔ EB. IntersectionMatrix::swap_ab computes it.

Errors: GeometryError::CollectionElementsOverlap if either operand is a GeometryCollection whose polygonal leaves overlap (see collection operands). No other pair fails.

use geometres::predicates::relate;
use geometres::types::{Coord2d, CoordSeq, LinearRing, Polygon};

let square = |x: f64, y: f64| {
    Polygon::new_simple(LinearRing::new(CoordSeq::new(vec![
        Coord2d::new(x, y), Coord2d::new(x + 1.0, y),
        Coord2d::new(x + 1.0, y + 1.0), Coord2d::new(x, y + 1.0),
    ])).unwrap()).unwrap()
};

// Two unit squares sharing the edge x = 1: the interiors are disjoint,
// and the boundaries meet in a line.
let r = relate(&square(0.0, 0.0), &square(1.0, 0.0)).unwrap();
assert_eq!(r.matrix().to_string(), "FF2F11212");
assert!(r.touches() && r.intersects());
assert!(!r.overlaps());

// Squares that overlap in a quarter: the interiors meet in an area.
let r = relate(&square(0.0, 0.0), &square(0.5, 0.5)).unwrap();
assert_eq!(r.matrix().to_string(), "212101212");
assert!(r.overlaps());

Relation

pub struct Relation

Relation is the spatial relation of one ordered pair: the exact matrix and the two operands' dimensions, with every predicate read from them. Because it holds the dimensions, every predicate method is authoritative for every ordered pair of geometry types, crosses and overlaps included. matrix() returns the matrix; equals(), disjoint(), intersects(), touches(), crosses(), within(), contains(), overlaps(), covers() and covered_by() read the predicates. Relation::from_matrix(m, dim_a, dim_b) builds one from a matrix and two dimensions.

use geometres::predicates::Relation;
use geometres::topology::de9im::IntersectionMatrix;
use geometres::topology::label::Dimension;

// The matrix of a line that starts outside a polygon and ends in its interior.
let m = IntersectionMatrix::from_pattern("1010F0212").unwrap();
let line_vs_area = Relation::from_matrix(&m, Dimension::Line, Dimension::Area);
assert!(line_vs_area.crosses());

// The same matrix read for two areas: crosses is never true for area by area.
let area_vs_area = Relation::from_matrix(&m, Dimension::Area, Dimension::Area);
assert!(!area_vs_area.crosses());

IntersectionMatrix

pub struct IntersectionMatrix { pub interior_interior: Dimension, pub interior_boundary: Dimension, pub interior_exterior: Dimension, pub boundary_interior: Dimension, pub boundary_boundary: Dimension, pub boundary_exterior: Dimension, pub exterior_interior: Dimension, pub exterior_boundary: Dimension, pub exterior_exterior: Dimension }

IntersectionMatrix holds the nine cells as named fields. Display renders the OGC 9-character string in row-major order, II IB IE BI BB BE EI EB EE, with F for empty and 0, 1, 2 for point, line and area; cells() returns the same nine values as an array. compute(a, b) computes the matrix of two polygons and compute_geometry(a, b) that of two Geometry values; relate is the general entry point.

Each predicate is also a method on the matrix, for a caller that already holds one. crosses and overlaps are defined by the operands' dimensions, so those two methods take them: crosses(dim_a, dim_b) and overlaps(dim_a, dim_b). The patterns are listed under the named predicates.

use geometres::topology::de9im::IntersectionMatrix;
use geometres::topology::label::Dimension;

let m = IntersectionMatrix::from_pattern("FF2F11212").unwrap(); // squares sharing an edge
assert_eq!(m.boundary_boundary, Dimension::Line);
assert!(m.touches() && !m.within());
assert!(!m.overlaps(Dimension::Area, Dimension::Area));

// The transpose exchanges IB/BI, IE/EI and BE/EB.
let t = IntersectionMatrix::from_pattern("F0FFFF212").unwrap().swap_ab();
assert_eq!(t.to_string(), "FF20F1FF2");

IntersectionMatrix::from_pattern and PatternError

pub fn from_pattern(pattern: &str) -> Result<IntersectionMatrix, PatternError>

from_pattern parses a 9-character DE-9IM string in the order Display writes it. The characters F, 0, 1 and 2 map to Empty, Point, Line and Area. The wildcard * is accepted but stored as Empty, so the parsed value is a concrete matrix rather than a pattern; a matrix from relate never contains wildcards. T is not accepted.

PatternError carries a static description in its public message field and implements Display.

Errors: PatternError if the string is not exactly 9 characters long, or if any character is not one of F, 0, 1, 2, *.

use geometres::topology::de9im::IntersectionMatrix;
use geometres::topology::label::Dimension;

let m = IntersectionMatrix::from_pattern("FF2FF1***").unwrap();
assert_eq!(m.interior_exterior, Dimension::Area);
assert_eq!(m.exterior_exterior, Dimension::Empty); // '*' is stored as Empty

assert!(IntersectionMatrix::from_pattern("FF2").is_err());
let e = IntersectionMatrix::from_pattern("T*F**FFF*").unwrap_err(); // 'T' is not a cell value
assert_eq!(e.message, "invalid character in pattern: expected F, 0, 1, 2, or *");

Location and Dimension

pub enum Location { Interior, Boundary, Exterior } pub enum Dimension { Empty = -1, Point = 0, Line = 1, Area = 2 }

Location is the topological location of a point or region relative to one geometry, as returned by point location. Dimension is the largest dimension of an intersection and the cell type of the matrix. Its discriminants match the OGC convention (F is −1), so the derived ordering is meaningful: Area > Line > Point > Empty. Both are in geometres::topology::label.

use geometres::topology::label::{Dimension, Location};

assert!(Dimension::Area > Dimension::Line);
assert!(Dimension::Point > Dimension::Empty);
assert_eq!(Dimension::Empty as i8, -1);
assert_ne!(Location::Boundary, Location::Interior);

Named predicates

The ten OGC predicates are free functions in geometres::predicates, each relate(a, b) read one way. They accept any two Relatable operands, in any combination of types.

The ten predicates

pub fn equals(a: &impl Relatable, b: &impl Relatable) -> Result<bool, GeometryError>

All ten share this signature, and each returns the same answer as the Relation method of the same name. intersects and disjoint do not build the matrix when both operands are areal: exact searches for one common point decide them, stopping at the first one found, with the same answer as relate(a, b)?.intersects().

Predicate Meaning DE-9IM pattern
equals The same point set. T*F**FFF*
disjoint No point in common. FF*FF****
intersects At least one point in common. complement of disjoint
touches The boundaries meet and the interiors do not. FT******* / F**T***** / F***T****
crosses a crosses b, by the definition for their dimensions. T*T****** if dim a < dim b; T*****T** if dim a > dim b; 0******** for line by line; false for point by point, area by area, or an empty operand
within a lies in b, their interiors meeting. T*F**F***
contains b lies in a, their interiors meeting. T*****FF*
overlaps Same dimension, interiors meeting in that dimension, and neither contains the other. T*T***T** for points, 1*T***T** for lines, 2*T***T** for areas; false for different dimensions or an empty operand
covers They meet, and no point of b lies outside a. T*****FF* / *T****FF* / ***T**FF* / ****T*FF*
covered_by They meet, and no point of a lies outside b; the same as covers(b, a). T*F**F*** / *TF**F*** / **FT*F*** / **F*TF***

Two edge cases follow from the definitions. Two empty geometries are equals as point sets, even though their matrix FFFFFFFF2 fails T*F**FFF* on II. And because covers requires the operands to meet, an empty b is covered by nothing.

For crosses and overlaps, a collection's dimension is that of its highest non-empty leaf.

Errors: as relate: CollectionElementsOverlap for a collection operand whose polygonal leaves overlap.

use geometres::predicates::{contains, covered_by, covers, intersects, relate, touches, within};
use geometres::types::{Coord2d, CoordSeq, LineString, LinearRing, Point, Polygon};

let square = Polygon::new_simple(LinearRing::new(CoordSeq::new(vec![
    Coord2d::new(0.0, 0.0), Coord2d::new(1.0, 0.0), Coord2d::new(1.0, 1.0), Coord2d::new(0.0, 1.0),
])).unwrap()).unwrap();

// A point exactly on the bottom edge is on the boundary, not inside:
// it touches the square and is covered by it, but is not within it.
let on_edge = Point::new(Coord2d::new(0.5, 0.0)).unwrap();
assert_eq!(relate(&on_edge, &square).unwrap().matrix().to_string(), "F0FFFF212");
assert!(intersects(&on_edge, &square).unwrap());
assert!(touches(&on_edge, &square).unwrap());
assert!(covered_by(&on_edge, &square).unwrap());
assert!(!within(&on_edge, &square).unwrap());

// The bottom edge itself, as a line: covered, but not contained,
// because it never meets the square's interior.
let edge = LineString::new(CoordSeq::new(vec![Coord2d::new(0.0, 0.0), Coord2d::new(1.0, 0.0)])).unwrap();
assert!(covers(&square, &edge).unwrap());
assert!(!contains(&square, &edge).unwrap());
assert!(touches(&edge, &square).unwrap());

crosses and overlaps depend on the dimensions as well as the matrix:

use geometres::predicates::{crosses, overlaps};
use geometres::types::{Coord2d, CoordSeq, LineString, LinearRing, Polygon};

let square = |x: f64, y: f64| {
    Polygon::new_simple(LinearRing::new(CoordSeq::new(vec![
        Coord2d::new(x, y), Coord2d::new(x + 1.0, y),
        Coord2d::new(x + 1.0, y + 1.0), Coord2d::new(x, y + 1.0),
    ])).unwrap()).unwrap()
};
// A line from outside the square into its interior crosses it.
let line = LineString::new(CoordSeq::new(vec![Coord2d::new(-1.0, 0.5), Coord2d::new(0.5, 0.5)])).unwrap();
assert!(crosses(&line, &square(0.0, 0.0)).unwrap());

// Areas overlap only when their interiors meet in an area.
assert!(overlaps(&square(0.0, 0.0), &square(0.5, 0.5)).unwrap());
assert!(!overlaps(&square(0.0, 0.0), &square(1.0, 0.0)).unwrap()); // shared edge only
assert!(!crosses(&square(0.0, 0.0), &square(0.5, 0.5)).unwrap());  // area by area

Relatable

pub trait Relatable: sealed::Sealed {}

Relatable marks the geometries the predicates accept: Point, LineString, Polygon, MultiPoint, MultiLineString, MultiPolygon, GeometryCollection and Geometry, and a reference to any of them, so a &&Geometry from iterating a slice of references can be passed as it is. A predicate call borrows its operands and never clones them into a Geometry.

The trait is sealed, implemented only in the crate, because the matrix computation relies on what the types promise: finite coordinates, and multipolygon parts meeting at most at finitely many points.

use geometres::predicates::{Relatable, intersects};
use geometres::types::{Coord2d, Geometry, Point};

fn hits(probe: &impl Relatable, targets: &[&Geometry]) -> usize {
    targets.iter().filter(|t| intersects(probe, t).unwrap()).count()
}

let a = Geometry::Point(Point::new(Coord2d::new(0.0, 0.0)).unwrap());
let b = Geometry::Point(Point::new(Coord2d::new(1.0, 0.0)).unwrap());
let probe = Point::new(Coord2d::new(1.0, 0.0)).unwrap();
assert_eq!(hits(&probe, &[&a, &b]), 1);

Collection operands

A GeometryCollection operand is accepted when its polygonal leaves together form a valid MultiPolygon: their interiors are disjoint and their boundaries share no stretch of positive length, decided exactly by the same placement test MultiPolygon::new applies. Line and point leaves are unrestricted. Such a collection is computed exactly.

Otherwise the call is refused with GeometryError::CollectionElementsOverlap { first, second }, rather than answered approximately. first and second are the two leaves' paths: element indices through nested collections, then, for a part of a multipolygon leaf, the part index. The collection itself is still valid, since OGC puts no condition between elements, so this is a refusal of relate rather than a validity issue. A caller that wants the relation of the union unions the elements first and relates the vouched result.

use geometres::GeometryError;
use geometres::predicates::{covers, relate};
use geometres::types::{Coord2d, CoordSeq, Geometry, GeometryCollection, LineString, LinearRing, Polygon};

let square = |x: f64, y: f64| {
    Polygon::new_simple(LinearRing::new(CoordSeq::new(vec![
        Coord2d::new(x, y), Coord2d::new(x + 1.0, y),
        Coord2d::new(x + 1.0, y + 1.0), Coord2d::new(x, y + 1.0),
    ])).unwrap()).unwrap()
};
let line = LineString::new(CoordSeq::new(vec![Coord2d::new(-1.0, 0.5), Coord2d::new(3.0, 0.5)])).unwrap();

// Squares meeting at one corner, plus a line through them: accepted.
let ok = GeometryCollection::new(vec![
    Geometry::Polygon(square(0.0, 0.0)),
    Geometry::Polygon(square(1.0, 1.0)),
    Geometry::LineString(line),
]).unwrap();
assert!(covers(&ok, &square(0.0, 0.0)).unwrap());

// Squares sharing an edge would be an invalid MultiPolygon: refused.
let shared = GeometryCollection::new(vec![
    Geometry::Polygon(square(0.0, 0.0)),
    Geometry::Polygon(square(1.0, 0.0)),
]).unwrap();
assert_eq!(
    relate(&shared, &square(0.0, 0.0)).unwrap_err(),
    GeometryError::CollectionElementsOverlap { first: vec![0], second: vec![1] }
);

Point location and dimension

Two helpers in geometres::predicates answer smaller questions than a full matrix: where one coordinate lies relative to a polygon, and what dimension a geometry has.

locate

pub fn locate(p: Coord2d, poly: &Polygon) -> Location

locate classifies a coordinate against a polygon, exactly: on any ring is Boundary; inside the exterior and outside every hole is Interior; anything else is Exterior. Every sign decision is arithmetica::orient2d on the original coordinates, so the verdict is correct rather than tolerance-dependent, and a point exactly on an edge is Boundary rather than falling to one side of it.

use geometres::predicates::locate;
use geometres::topology::label::Location;
use geometres::types::{Coord2d, CoordSeq, LinearRing, Polygon};

// The triangle below the diagonal y = x of the unit square.
let tri = Polygon::new_simple(LinearRing::new(CoordSeq::new(vec![
    Coord2d::new(0.0, 0.0), Coord2d::new(1.0, 0.0), Coord2d::new(1.0, 1.0),
])).unwrap()).unwrap();

// (0.1, 0.1) is exactly on the diagonal edge, whatever f64 value 0.1 rounds to.
let x = 0.1_f64;
assert_eq!(locate(Coord2d::new(x, x), &tri), Location::Boundary);
// One ulp above the edge is outside; one ulp below is inside.
assert_eq!(locate(Coord2d::new(x, x.next_up()), &tri), Location::Exterior);
assert_eq!(locate(Coord2d::new(x, x.next_down()), &tri), Location::Interior);

dimension

pub fn dimension(g: &impl Relatable) -> Dimension

dimension returns the topological dimension of a geometry, Empty for an empty one. It governs crosses and overlaps, and supplies the dimension arguments of the matrix methods IntersectionMatrix::crosses and IntersectionMatrix::overlaps. A collection's dimension is defined for every collection, including one relate refuses.

use geometres::predicates::dimension;
use geometres::topology::label::Dimension;
use geometres::types::{Coord2d, CoordSeq, LineString, MultiPolygon, Point};

let p = Point::new(Coord2d::new(0.0, 0.0)).unwrap();
let l = LineString::new(CoordSeq::new(vec![Coord2d::new(0.0, 0.0), Coord2d::new(1.0, 1.0)])).unwrap();
assert_eq!(dimension(&p), Dimension::Point);
assert_eq!(dimension(&l), Dimension::Line);
assert_eq!(dimension(&MultiPolygon::empty()), Dimension::Empty);

Prepared masks

A polygonal mask prepared once answers repeated queries in less time than the unprepared operation, and every prepared answer is identical to the unprepared one: the same matrix cell for cell, the same boolean, the same refusal with the same reason. Preparation changes the cost of a query rather than its result. The types are in geometres::prepared.

PreparedPolygonal

pub fn new(geom: &impl Polygonal) -> Result<PreparedPolygonal, GeometryError>

PreparedPolygonal is built once from a Polygon or a valid MultiPolygon. Preparation does the per-mask work once, including a simplicity verdict on every ring, so that each query pays only for itself. The prepared value is immutable and Sync, so it can be shared across threads. relate(other) returns exactly IntersectionMatrix::compute_geometry(mask, other), with the mask as A.

Method Returns
relate(&Geometry) The DE-9IM matrix of the mask against other.
intersects, disjoint, covers, contains, within The matrix predicate of relate, with the mask as A: within asks whether the mask lies within other. An exact envelope early-out returns what the matrix would.
locate(Coord2d) The exact Location of a point in the mask: on any part's ring is Boundary, inside some part is Interior.
locate_on_line(y, &xs) The location of every point (xs[i], y), in input order, each equal to locate's answer, for one pass over the edges that meet the line rather than one location each.
dwithin(&Geometry, d), distance(&Geometry) The same answers as ops::dwithin (exact) and ops::distance (bit for bit).
is_delegating(), delegation_reason() Whether every query runs the unprepared operation because some ring is not simple, and which ring.
parts(), envelope() The mask's parts, and the envelope of every part (None for an empty mask).

Errors: new returns TooManyEntries if the mask has more than u32::MAX parts or edges, its only failure. The query methods fail exactly as their unprepared counterparts do, for example with CollectionElementsOverlap for a collection whose polygonal leaves overlap; locate_on_line returns NonFiniteCoordinate for a non-finite y or xs[i].

use geometres::predicates::relate;
use geometres::prepared::PreparedPolygonal;
use geometres::topology::label::Location;
use geometres::types::{Coord2d, CoordSeq, Geometry, LinearRing, MultiPolygon, Point, Polygon};

let square = |x: f64| {
    Polygon::new_simple(LinearRing::new(CoordSeq::new(vec![
        Coord2d::new(x, 0.0), Coord2d::new(x + 1.0, 0.0),
        Coord2d::new(x + 1.0, 1.0), Coord2d::new(x, 1.0),
    ])).unwrap()).unwrap()
};
let mask = MultiPolygon::new(vec![square(0.0), square(2.0)]).unwrap();
let prepared = PreparedPolygonal::new(&mask).unwrap();
assert!(!prepared.is_delegating());

// A point on the second part's left edge: the prepared matrix is the unprepared one.
let g = Geometry::Point(Point::new(Coord2d::new(2.0, 0.5)).unwrap());
assert_eq!(prepared.relate(&g).unwrap(), relate(&mask, &g).unwrap().matrix());
assert_eq!(prepared.covers(&g).unwrap(), relate(&mask, &g).unwrap().covers());

// Many points on one row, located in a single pass.
use Location::{Boundary, Exterior, Interior};
assert_eq!(
    prepared.locate_on_line(0.5, &[-1.0, 0.5, 1.0, 1.5, 2.0, 2.5]).unwrap(),
    [Exterior, Interior, Boundary, Exterior, Boundary, Interior]
);

DelegationReason

pub struct DelegationReason { pub part: usize, pub ring: usize, pub edges: (usize, usize) }

A PreparedPolygonal whose rings are all simple uses its fast structures, which may assume simple rings. If any ring is not simple, which the polygon constructors allow, the mask delegates: every query calls the unprepared operation, and is correct but not faster. The verdict is visible, so a caller can see why a mask is slow.

DelegationReason names the first non-simple ring: part is the part index, ring is 0 for the exterior and k for hole k − 1, and edges is the first pair of that ring's edges that touch other than at a shared vertex.

use geometres::predicates::relate;
use geometres::prepared::PreparedPolygonal;
use geometres::types::{Coord2d, CoordSeq, Geometry, LinearRing, Point, Polygon};

// Two triangles joined at (2, 2): the ring passes through that vertex twice.
// Polygon::new accepts it, since simplicity is not checked at construction.
let pinched = Polygon::new_simple(LinearRing::new(CoordSeq::new(vec![
    Coord2d::new(0.0, 0.0), Coord2d::new(2.0, 2.0), Coord2d::new(4.0, 0.0),
    Coord2d::new(4.0, 4.0), Coord2d::new(2.0, 2.0), Coord2d::new(0.0, 4.0),
])).unwrap()).unwrap();

let prepared = PreparedPolygonal::new(&pinched).unwrap();
assert!(prepared.is_delegating());
let reason = prepared.delegation_reason().unwrap();
assert_eq!((reason.part, reason.ring), (0, 0));

// Delegating changes the cost, never the answer.
let g = Geometry::Point(Point::new(Coord2d::new(2.0, 2.0)).unwrap());
assert_eq!(prepared.relate(&g).unwrap(), relate(&pinched, &g).unwrap().matrix());