Skip to content
5 changes: 5 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,11 @@ the pull request which of these it reaches and why the rest don't apply:
`cargo xtask test-hygiene` (also in CI) requires `// test-wait: reason` on timer waits in tests and
`#[ignore = "reason"]` on ignored tests, and refuses an `assert_eq!` or `assert_ne!` (or `debug_assert_*`)
whose two sides are the same tokens; prefer completion or progress signals, and a fixed expected value.
`clippy.toml` refuses the four sphere measures in `rustgis-geom` (`haversine_m`, `geodesic_length_m`,
`geodesic_ring_perimeter_m`, `geodesic_ring_area_m2`): the Earth measures on the WGS 84 ellipsoid
(`wgs84_distance_m`, `wgs84_length_m`, `wgs84_step_m`, `wgs84_ring_perimeter_area_m2`), and a call kept on
the sphere, for another body or a comparison it can't change, says why in its
`#[expect(clippy::disallowed_methods, reason = "…")]`.
`cargo xtask memory` (in CI on Linux) fails when a command line workflow's peak memory grows past
its limit in `xtask/memory-limits.txt`; a change that lowers one commits the lower limit with it.
`cargo xtask rows` (also in CI) fails when code outside `rustgis-data` uses a layer's rows directly
Expand Down
11 changes: 11 additions & 0 deletions clippy.toml
Original file line number Diff line number Diff line change
@@ -1,3 +1,14 @@
allow-unwrap-in-tests = true
allow-expect-in-tests = true
allow-panic-in-tests = true

# The Earth measures on the WGS 84 ellipsoid (`wgs84_distance_m`, `wgs84_length_m`,
# `wgs84_ring_perimeter_area_m2`), as the Measure tool does (#939, #2568). These measure on a sphere:
# a call says why with `#[expect(clippy::disallowed_methods, reason = "…")]`, for another body
# (scaled by `Body`) or a comparison the sphere can't change.
disallowed-methods = [
{ path = "rustgis_geom::haversine_m", reason = "the sphere; the Earth measures with `wgs84_distance_m`" },
{ path = "rustgis_geom::geodesic_length_m", reason = "the sphere; the Earth measures with `wgs84_length_m`" },
{ path = "rustgis_geom::geodesic_ring_perimeter_m", reason = "the sphere; the Earth measures with `wgs84_ring_perimeter_area_m2`" },
{ path = "rustgis_geom::geodesic_ring_area_m2", reason = "the sphere; the Earth measures with `wgs84_ring_perimeter_area_m2`" },
]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR adds a check (the disallowed-methods lint over the four spherical measures), but its rule is only listed under "Suggested AGENTS.md additions". AGENTS.md's "This file" section says a PR that adds a check updates its line in the Quality gates section. A line for this check belongs in this PR, and the suggested addition covers the agent-facing rule. A maintainer may still decide otherwise.

Category: agents-md

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in c45eb23: AGENTS.md › Quality gates now has the lint's line, and the description no longer carries it as a suggestion.

7 changes: 7 additions & 0 deletions crates/analysis/src/geodesic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,10 @@ impl Plane {
/// from the same edge straight in the analysis plane ([`lonlat_to_plane`]: Web Mercator within
/// ±85.05°, straight in lon/lat beyond) by more than `tolerance` meters at its quarter points
/// or midpoint.
#[expect(
clippy::disallowed_methods,
reason = "a tolerance for splitting an edge, not a measurement: ellipsoid distances are within 0.6% of the sphere's"
)]
fn strays(&self, a: GC<f64>, b: GC<f64>, la: Coord, lb: Coord, tolerance: f64) -> bool {
let at = |t: f64| self.0.inverse(Coord::new(a.x + t * (b.x - a.x), a.y + t * (b.y - a.y)));
// `b` on `a`'s side of the antimeridian, so the straight edge is the short one.
Expand Down Expand Up @@ -495,6 +499,7 @@ fn finite(parts: &[Vec<Coord>]) -> Vec<Vec<Coord>> {
parts.iter().map(|p| p.iter().copied().filter(|c| c.is_finite()).collect::<Vec<_>>()).filter(|p| !p.is_empty()).collect()
}

#[expect(clippy::disallowed_methods, reason = "sizes the pieces a buffer is cut into, not a measurement")]
fn fits(pts: &[Coord], centre: Coord) -> bool {
pts.iter().all(|c| haversine_m(centre, *c) <= ONE_PIECE_M)
}
Expand All @@ -504,6 +509,7 @@ fn stretched(parts: &[Vec<Coord>], metres: f64) -> Vec<MultiPolygon<f64>> {
let mut out = Vec::new();
for part in parts {
let d = densify(part);
#[expect(clippy::disallowed_methods, reason = "sizes the pieces a buffer is cut into, not a measurement")]
let near = |a: usize, b: usize| d.get(a).zip(d.get(b)).is_some_and(|(a, b)| haversine_m(*a, *b) <= STRETCH_M);
let mut start = 0;
loop {
Expand All @@ -528,6 +534,7 @@ fn stretched(parts: &[Vec<Coord>], metres: f64) -> Vec<MultiPolygon<f64>> {

/// A line with every edge split along its geodesic on WGS 84 into pieces of at most [`DENSIFY_M`], or
/// longer ones for a line so long it would gain more than [`MAX_ADDED`] vertices.
#[expect(clippy::disallowed_methods, reason = "the densify step: it sets how many vertices an edge gains, not a measurement")]
fn densify(pts: &[Coord]) -> Vec<Coord> {
let step = DENSIFY_M.max(rustgis_geom::geodesic_length_m(pts) / MAX_ADDED);
let mut out: Vec<Coord> = pts.first().copied().into_iter().collect();
Expand Down
71 changes: 66 additions & 5 deletions crates/analysis/src/join.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@
//! they are found there and measured straight, in the system's unit times its length.

use rustgis_data::{Coord, Dataset, FieldType, Geometry, Value};
use rustgis_geom::{Aeqd, Extent, WGS84_MIN_RADIUS_M, geodesic_interpolate, geodesic_length_m, geodesic_ring_area_m2, wgs84_distance_m};
use rustgis_geom::{
Aeqd, Extent, WGS84_MIN_RADIUS_M, geodesic_interpolate, wgs84_distance_m, wgs84_length_m, wgs84_ring_perimeter_area_m2,
};
use serde_json::Value as Json;

/// Whether a coordinate is a place on the Earth in lon/lat: finite, with a latitude of ±90° at most
Expand Down Expand Up @@ -229,20 +231,24 @@ fn lon_gap(a: &Extent, b: &Extent) -> f64 {
[-360.0, 0.0, 360.0].iter().map(|k| (b.min_x + k - a.max_x).max(a.min_x - (b.max_x + k)).max(0.0)).fold(f64::INFINITY, f64::min)
}

/// The ground area (square metres) of a lon/lat polygon geometry, holes taken out.
/// The ground area (square metres) of a lon/lat polygon geometry on the WGS 84 ellipsoid, holes
/// taken out, as the Measure tool gives it. NaN for a ring whose winding is ambiguous.
pub fn area_m2(g: &Geometry) -> f64 {
let Geometry::Polygon(polys) = g else { return 0.0 };
polys
.iter()
.flat_map(|rings| rings.iter().enumerate())
.map(|(i, r)| if i == 0 { geodesic_ring_area_m2(r) } else { -geodesic_ring_area_m2(r) })
.map(|(i, r)| {
let (_, area) = wgs84_ring_perimeter_area_m2(r);
if i == 0 { area } else { -area }
})
.sum()
}

/// The ground length (metres) of a lon/lat line geometry.
/// The ground length (metres) of a lon/lat line geometry on the WGS 84 ellipsoid.
pub fn length_m(g: &Geometry) -> f64 {
let Geometry::Line(parts) = g else { return 0.0 };
parts.iter().map(|p| geodesic_length_m(p)).sum()
parts.iter().map(|p| wgs84_length_m(p)).sum()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Performance, medium-low confidence. The PR justifies the ellipsoid overlap cost as "small next to the overlay that cuts it out of the pair". That holds for areas, where the ellipsoid polygon pass sits beside a boolean overlay. For lines it looks weaker: from_line(&j.clip(t, false)) is one linear pass over the clipped vertices, while wgs84_length_m runs a GeographicLib inverse solve per segment. The PR's own figures put a solve at about 1.4 µs against about 65 ns for a haversine, so for a line target the length step may cost more than the clip. A line with hundreds of thousands of vertices, clipped by several polygons, adds seconds to one target. The tool checks Cancel per target, so this is not a hang, but the cost claim for lines is not measured.

Options: measure a dense line in the dev profile and update the PR's cost claim, or use rustgis_geom::wgs84_step_m per segment, as the routing change does. It agrees with wgs84_distance_m to within a millionth for steps up to 0.05°, and falls back to the solve beyond that, so the ranking is unchanged in practice.

Category: performance

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The line case was not measured. The largest-overlap line length moves to wgs84_step_m per segment in a follow-up pull request, measured on a dense line before and after.

}

/// How the values of a join field's matches become one value in a one-to-one join.
Expand Down Expand Up @@ -495,6 +501,7 @@ mod tests {
/// The ground distance from `p` to a line, by sampling each edge finely along its great circle.
/// Only the samples within 1.2% of the nearest on the sphere are measured on the ellipsoid,
/// whose distances are within 0.6% of the sphere's.
#[expect(clippy::disallowed_methods, reason = "the test ranks samples on the sphere and measures the nearest on the ellipsoid")]
fn brute(p: Coord, line: &[Coord]) -> f64 {
let samples: Vec<(Coord, f64)> = line
.windows(2)
Expand All @@ -506,6 +513,7 @@ mod tests {
}

#[test]
#[expect(clippy::disallowed_methods, reason = "the test tells the ellipsoid's distance from the sphere's")]
fn distances_are_on_the_wgs84_ellipsoid() {
// 0.0904369° north of the equator is 10,000 m on WGS 84 (GeographicLib) but 10,056 m on the
// mean sphere: within 10 km in the measure, and not ruled out before it (#888).
Expand All @@ -518,6 +526,59 @@ mod tests {
assert!(search_box(&ea, 10_000.0).is_some_and(|e| e.max_y >= b.y));
}

/// Spatial Join's Largest overlap ranks overlaps by their area or length on the WGS 84
/// ellipsoid, as the Measure tool measures them. A 1° square on the equator, listed first, and a
/// band at 60°N that the ellipsoid makes 0.5% larger but the sphere 0.5% smaller: the band
/// wins. Likewise for a line along a meridian through a 1° zone and a shorter one at 60°N.
#[test]
#[expect(clippy::disallowed_methods, reason = "the test sets the sphere's ranking against the ellipsoid's")]
fn largest_overlap_ranks_overlaps_on_the_ellipsoid() {
use crate::{Inputs, Output};
use rustgis_data::{Field, GeometryType};
use rustgis_geom::{geodesic_length_m, geodesic_ring_area_m2};
use std::collections::HashMap;
struct Layers(HashMap<String, Dataset>);
impl Inputs for Layers {
fn dataset(&self, layer: &str) -> Option<&Dataset> {
self.0.get(layer)
}
fn selection(&self, _: &str) -> &[usize] {
&[]
}
}
let ring = |x0: f64, x1: f64, y0: f64, y1: f64| {
vec![Coord::new(x0, y0), Coord::new(x1, y0), Coord::new(x1, y1), Coord::new(x0, y1), Coord::new(x0, y0)]
};
let zones = |band_top: f64| {
let mut ds = Dataset::new("zones", GeometryType::Polygon, vec![Field::new("zone", FieldType::Text)]);
for (name, r) in [("equator", ring(0.0, 1.0, 0.0, 1.0)), ("north", ring(0.0, 1.0, 60.0, band_top))] {
ds.push(Some(Geometry::Polygon(vec![vec![r]])), vec![Value::Text(name.into())]);
}
ds
};
let joined = |target: Dataset, zones: Dataset| {
let layers = Layers(HashMap::from([("t".to_string(), target), ("zones".to_string(), zones)]));
let r = crate::run("spatialJoin", &layers, &serde_json::json!({"target": "t", "join": "zones", "match": "Largest overlap"}));
let Ok(crate::ToolResult { output: Output::Layer(ds), .. }) = r else { panic!("a layer") };
ds.field_index("join_zone").map(|i| ds.value(0, i).clone())
};
let north = Some(Value::Text("north".into()));

let (square, band) = (ring(0.0, 1.0, 0.0, 1.0), ring(0.0, 1.0, 60.0, 62.054));
let area = |r: &Vec<Coord>| wgs84_ring_perimeter_area_m2(r).1;
assert!(area(&band) > area(&square) * 1.004 && geodesic_ring_area_m2(&band) < geodesic_ring_area_m2(&square) * 0.996);
let mut parcel = Dataset::new("t", GeometryType::Polygon, vec![]);
parcel.push(Some(Geometry::Polygon(vec![vec![ring(0.0, 1.0, -1.0, 63.0)]])), vec![]);
assert_eq!(joined(parcel, zones(62.054)), north);

let (near_equator, near_pole) = ([Coord::new(0.5, 0.0), Coord::new(0.5, 1.0)], [Coord::new(0.5, 60.0), Coord::new(0.5, 60.995)]);
assert!(wgs84_length_m(&near_pole) > wgs84_length_m(&near_equator) * 1.002);
assert!(geodesic_length_m(&near_pole) < geodesic_length_m(&near_equator) * 0.996);
let mut road = Dataset::new("t", GeometryType::Polyline, vec![]);
road.push(Some(Geometry::Line(vec![vec![Coord::new(0.5, -1.0), Coord::new(0.5, 63.0)]])), vec![]);
assert_eq!(joined(road, zones(60.995)), north);
}

#[test]
fn an_integer_sum_takes_decimals_over_the_whole_i64_range() {
let sum = Merge { field: 0, rule: Rule::Sum, delimiter: String::new() };
Expand Down
5 changes: 5 additions & 0 deletions crates/analysis/src/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,10 @@ fn shortest_route_with(
/// The closest point on any of `segs` to `p`: (segment, fraction along it, the point, metres
/// away). With `within`, only segments whose box comes within about that many metres of `p` are
/// measured; one farther can't be within it, so a nearer one is never missed.
#[expect(
clippy::disallowed_methods,
reason = "a lower bound that skips candidates, scaled to the ellipsoid's smallest radius; the distance kept is the ellipsoid's"
)]
fn nearest_segment(segs: &[Segment], nodes: &[Coord], p: Coord, within: Option<f64>) -> Result<Option<(usize, f64, Coord, f64)>, String> {
crate::control::check()?;
let window = within.and_then(|m| snap_window(p, m));
Expand Down Expand Up @@ -1733,6 +1737,7 @@ mod tests {
}

#[test]
#[expect(clippy::disallowed_methods, reason = "the test compares the sphere's ranking with the ellipsoid's")]
fn snap_acceptance_uses_the_nearest_ellipsoidal_candidate() {
let mut ds = Dataset::new("roads", GeometryType::Polyline, vec![]);
// At the equator, 0.001 degrees east is nearer on the sphere than 0.001003
Expand Down
4 changes: 4 additions & 0 deletions crates/analysis/src/rasterops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,10 @@ pub fn weighted_overlay(criteria: &[(Vec<f32>, f64)]) -> Result<Vec<f32>, String
}

/// Metres between two longitude/latitude points.
#[expect(
clippy::disallowed_methods,
reason = "the elevation profile's distances stay on the sphere for now: a solve per path vertex costs about 20 times as much on the ellipsoid, and the profile commands run on the command thread"
)]
fn dist_m(a: Coord, b: Coord) -> f64 {
rustgis_geom::haversine_m(a, b)
}
Expand Down
4 changes: 4 additions & 0 deletions crates/analysis/src/tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3840,6 +3840,7 @@ const ELLIPSOID_STRETCH: f64 = 1.005;
/// (Leaving out a vertex only shortens a part.) Coordinates are folded and clamped as GeographicLib
/// takes them, so the bound holds for any finite ones. In a projected system's own plane, the bound
/// is the edges' flat metres, as the walk adds them up, and a hair more.
#[expect(clippy::disallowed_methods, reason = "an upper bound, stretched by `ELLIPSOID_STRETCH` to cover the ellipsoid's longer paths")]
fn length_bound(line: &[Vec<Coord>], ring: bool) -> f64 {
if let Some(unit) = crate::convert::own_unit_m() {
let mut verts = line.iter().flatten().filter(|c| c.is_finite());
Expand Down Expand Up @@ -11139,6 +11140,7 @@ mod tests {
/// The distance on WGS 84 (km) from `c` to a line, sampled every `step` metres along it.
/// Only the samples within 1.2% of the nearest on the sphere are measured on the ellipsoid,
/// whose distances are within 0.6% of the sphere's.
#[expect(clippy::disallowed_methods, reason = "tests sample on the sphere and measure the nearest samples on the ellipsoid")]
fn km_to_every(c: Coord, line: &[Coord], step: f64) -> f64 {
let samples: Vec<(Coord, f64)> = line
.windows(2)
Expand Down Expand Up @@ -11203,6 +11205,7 @@ mod tests {
}

/// Points along the geodesic from `a` to `b` on WGS 84, at most 20 m apart.
#[expect(clippy::disallowed_methods, reason = "tests sample on the sphere and measure the nearest samples on the ellipsoid")]
fn geodesic_samples(a: Coord, b: Coord) -> Vec<Coord> {
use geo::InterpolatePoint;
let n = (rustgis_geom::haversine_m(a, b) / 20.0).ceil().max(1.0) as usize;
Expand All @@ -11216,6 +11219,7 @@ mod tests {
/// its nearest point is strictly between the ends: the nearest sample on the sphere (among
/// every 50th, then its neighbours), then the nearest point on the ellipsoid along the geodesic
/// either side of it, by golden-section search to well under a millimetre.
#[expect(clippy::disallowed_methods, reason = "tests sample on the sphere and measure the nearest samples on the ellipsoid")]
fn m_to_geodesic(c: Coord, samples: &[Coord]) -> (f64, bool) {
use geo::InterpolatePoint;
let near = |range: std::ops::Range<usize>, step: usize| {
Expand Down
21 changes: 21 additions & 0 deletions crates/engine/src/cmd/design.rs
Original file line number Diff line number Diff line change
Expand Up @@ -819,6 +819,10 @@ fn plane_at<'a>(geoms: impl IntoIterator<Item = &'a Geometry>, steps: &mut Cente
let mut last = a;
for k in 1..=n as usize {
let q = if k as f64 >= n { b } else { at(k as f64 / n) };
#[expect(
clippy::disallowed_methods,
reason = "weighs a centre by its pieces' lengths, not a measurement; polar edits wait on #2032 step C2f-6"
)]
edges.add_weighted(at((k as f64 - 0.5) / n), haversine_m(last, q));
last = q;
}
Expand Down Expand Up @@ -1412,6 +1416,10 @@ fn split(s: &mut Session, p: &Json) -> CmdResult {
let mut dists: Vec<f64> = Vec::new();
if ground {
dists.try_reserve(parts.iter().map(Vec::len).sum()).map_err(|_| "not enough memory to split the selected lines")?;
#[expect(
clippy::disallowed_methods,
reason = "finds the point of a line nearest the cut, a comparison, not a measurement; polar edits wait on #2032 step C2f-6"
)]
dists.extend(
parts
.iter()
Expand Down Expand Up @@ -1465,6 +1473,10 @@ fn split(s: &mut Session, p: &Json) -> CmdResult {
// nearer than the one found.
let unsure = d > steps.floor;
// At a vertex (to within a millimeter), the parts meet there, without it repeated.
#[expect(
clippy::disallowed_methods,
reason = "finds the point of a line nearest the cut, a comparison, not a measurement; polar edits wait on #2032 step C2f-6"
)]
let at_end = [part.get(si), part.get(si + 1)].into_iter().flatten().find(|v| rustgis_geom::haversine_m(**v, q) < 0.001);
let q = at_end.copied().unwrap_or(q);
let mut first: Vec<Coord> = part.iter().take(si + 1).copied().collect();
Expand All @@ -1474,6 +1486,10 @@ fn split(s: &mut Session, p: &Json) -> CmdResult {
let mut second = vec![q];
second.extend(part.iter().skip(si + 1).copied().skip_while(|c| *c == q));
// At (or within a centimetre of) the line's ends isn't a split.
#[expect(
clippy::disallowed_methods,
reason = "finds the point of a line nearest the cut, a comparison, not a measurement; polar edits wait on #2032 step C2f-6"
)]
let near = |a: Option<&Coord>| a.is_some_and(|a| rustgis_geom::haversine_m(*a, q) < 0.01);
if first.len() < 2 || second.len() < 2 || near(first.first()) || near(second.last()) {
whole += usize::from(unsure);
Expand Down Expand Up @@ -1545,6 +1561,10 @@ struct SplitSteps {
/// a millimeter, nearest first, while it could hold a point nearer than the nearest found, or than
/// `bound`. Each distance takes one of the command's `steps`; once they're spent, the nearest
/// found (the nearer end, at first) stands, and `steps` notes how near the rest might be.
#[expect(
clippy::disallowed_methods,
reason = "finds the point of a line nearest the cut, a comparison, not a measurement; polar edits wait on #2032 step C2f-6"
)]
fn nearest_on_ground(at: Coord, (a, b): (Coord, Coord), (da, db): (f64, f64), bound: f64, steps: &mut SplitSteps) -> Option<(f64, Coord)> {
const STEP_DEG: f64 = 22.5;
const PIECES_MIN: usize = 8;
Expand Down Expand Up @@ -2891,6 +2911,7 @@ mod tests {
}

#[test]
#[expect(clippy::disallowed_methods, reason = "the test checks the split's search on the sphere it uses")]
fn a_split_searches_a_segment_within_its_budget() {
// From 89°N on 0°, along 88°N from 30°W to 30°E: searched, its nearest point is on 0°, a
// kilometer nearer than its ends, and the search takes a few dozen of the budget; with
Expand Down
6 changes: 6 additions & 0 deletions crates/engine/src/cmd/imagery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1909,6 +1909,10 @@ fn measure(s: &mut Session, p: &Value) -> CmdResult {
}
// On the Earth, each leg's length on the sphere (as the profile below spaces its
// samples) and on the ellipsoid; the flat length is the ellipsoid's.
#[expect(
clippy::disallowed_methods,
reason = "the sphere spaces the profile's samples, as `rasterops::profile` does; the lengths are the ellipsoid's"
)]
let legs: Vec<(f64, f64)> = if earth {
pts.windows(2)
.map(|w| match w {
Expand All @@ -1919,6 +1923,7 @@ fn measure(s: &mut Session, p: &Value) -> CmdResult {
} else {
Vec::new()
};
#[expect(clippy::disallowed_methods, reason = "another body measures on its sphere, scaled by `Body`")]
let flat = if earth { legs.iter().map(|l| l.1).sum() } else { body.length(rustgis_geom::geodesic_length_m(&pts)) };
// Along the surface when there's an elevation raster. The profile spaces its samples
// along the path on the sphere; on the Earth each step's ground run is taken from the
Expand Down Expand Up @@ -1954,6 +1959,7 @@ fn measure(s: &mut Session, p: &Value) -> CmdResult {
if rustgis_geom::ring_area_is_ambiguous(&ring) {
return Err("the area is ambiguous: 1 ring winds beyond one whole surface".into());
}
#[expect(clippy::disallowed_methods, reason = "another body measures on its sphere, scaled by `Body`")]
let (perimeter, area) = if earth {
rustgis_geom::wgs84_ring_perimeter_area_m2(&ring)
} else {
Expand Down
Loading
Loading