From 2a2eb7d05243f5fa2d1fd23be06ebaaf6b4b5467 Mon Sep 17 00:00:00 2001 From: choupeanut Date: Sun, 29 Nov 2026 00:13:05 +0800 Subject: [PATCH 01/13] fix(analysis): IDW and Kriging say which features they leave out, and IDW looks at Cancel as it reads them (#2918) --- crates/analysis/src/tools.rs | 206 ++++++++++++++++++++++-- crates/engine/src/tests/cancellation.rs | 1 + docs/user-guide/analysis.md | 8 +- xtask/row-uses.txt | 2 +- 4 files changed, 202 insertions(+), 15 deletions(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index b35730f4ae..4ccac6b51e 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -5151,15 +5151,35 @@ fn idw_interpolation(inp: &dyn Inputs, p: &Json) -> Result { let field = s(p, "field"); let fi = find_field_case_insensitive(ds, field)?; let mut pts: Vec<(Coord, f64)> = Vec::new(); - for r in rows(inp, p, "input", ds) { - let Some(g) = ds.features.get(r).and_then(|f| f.geometry.as_ref()) else { continue }; - let Some(v) = ds.value(r, fi).as_f64().filter(|v| v.is_finite()) else { continue }; + let mut left_out = PointsLeftOut::default(); + let picked = rows(inp, p, "input", ds); + // A single geometry's coordinates are walked without a look at Cancel: one feature is short next to the features. + for (n, r) in picked.iter().copied().enumerate() { + if n % LOOK_EVERY == 0 { + crate::control::check()?; + } + let Some(g) = ds.features.geometry(r) else { + left_out.no_geometry += 1; + continue; + }; + let Some(v) = ds.value(r, fi).as_f64().filter(|v| v.is_finite()) else { + left_out.no_value += 1; + continue; + }; + let (kept, skipped) = (pts.len(), left_out.no_place); g.for_each_coord(|c| { if c.is_finite() { pts.push((c, v)); + } else { + left_out.no_place += 1; } }); + // A geometry with no coordinate at all (an empty multipoint) is an empty one. + if pts.len() == kept && left_out.no_place == skipped { + left_out.no_geometry += 1; + } } + let why = left_out.why(); let (crs, crs_note) = raster_crs_in(ds, inp.work_crs(), inp.project_crs(), p, "IDW Interpolation")?; let (pts, beyond_note) = points_from(inp.work_crs(), crs, pts)?; let extent = match s(p, "extent").trim() { @@ -5192,12 +5212,12 @@ fn idw_interpolation(inp: &dyn Inputs, p: &Json) -> Result { None => 2.0, }; let name = out_name(p, format!("{}_{field}_idw", ds.name)); - let r = - crate::rasterops::idw(&pts, &extent, cell, power, 0, &name, crs).map_err(|e| with_note(with_note(e, &beyond_note), &crs_note))?; + let r = crate::rasterops::idw(&pts, &extent, cell, power, 0, &name, crs) + .map_err(|e| with_note(with_note(with_note(e, &beyond_note), &crs_note), &why))?; let bytes = rustgis_data::raster::geotiff::write(&r, 0).map_err(|e| e.to_string())?; let msg = format!("IDW Interpolation: {} × {} cells from {} points", r.width, r.height, pts.len()); Ok(ToolResult { - losses: Vec::new(), + losses: left_out.losses("IDW Interpolation", picked.len(), field, "a coordinate is not a finite number"), output: Output::Layers(vec![OutputLayer::Raster { file_name: format!("{name}.tif"), name, bytes }]), messages: std::iter::once(msg).chain(beyond_note).chain(crs_note).collect(), }) @@ -5223,22 +5243,35 @@ fn kriging_interpolation(inp: &dyn Inputs, p: &Json) -> Result = Vec::new(); - for (n, r) in rows(inp, p, "input", ds).into_iter().enumerate() { + let mut left_out = PointsLeftOut::default(); + let picked = rows(inp, p, "input", ds); + for (n, r) in picked.iter().copied().enumerate() { if n % LOOK_EVERY == 0 { crate::control::check()?; } - let Some(g) = ds.features.get(r).and_then(|f| f.geometry.as_ref()) else { continue }; - let Some(v) = ds.value(r, fi).as_f64().filter(|v| v.is_finite()) else { continue }; + let Some(g) = ds.features.geometry(r) else { + left_out.no_geometry += 1; + continue; + }; + let Some(v) = ds.value(r, fi).as_f64().filter(|v| v.is_finite()) else { + left_out.no_value += 1; + continue; + }; + let (kept, skipped) = (raw_pts.len(), left_out.no_place); match g { Geometry::Point(c) => { if c.is_finite() { raw_pts.push((*c, v)); + } else { + left_out.no_place += 1; } } Geometry::MultiPoint(cs) => { for c in cs { if c.is_finite() { raw_pts.push((*c, v)); + } else { + left_out.no_place += 1; } } } @@ -5248,17 +5281,24 @@ fn kriging_interpolation(inp: &dyn Inputs, p: &Json) -> Result Result Result Vec { + use rustgis_data::loss::{LossCode, LossMessage}; + let mut losses = Vec::new(); + if self.no_geometry > 0 { + losses.push(LossMessage { + code: LossCode::DroppedFeature, + text: format!("{tool}: {} of {total} feature(s) left out: they have no geometry, or an empty one", self.no_geometry), + }); + } + if self.no_value > 0 { + losses.push(LossMessage { + code: LossCode::DroppedFeature, + text: format!( + "{tool}: {} of {total} feature(s) left out: their {field} value is empty or not a finite number", + self.no_value + ), + }); + } + if self.no_place > 0 { + losses.push(LossMessage { + code: LossCode::DroppedGeometry, + text: format!("{tool}: {} point(s) left out: {place}", self.no_place), + }); + } + losses + } + + /// What was left out, for the error of a run with too few points to go on. + fn why(&self) -> Option { + let parts: Vec = [ + (self.no_geometry, "with no geometry"), + (self.no_value, "whose value isn't a number"), + (self.no_place, "with a coordinate that isn't a number"), + ] + .into_iter() + .filter(|(n, _)| *n > 0) + .map(|(n, what)| format!("{n} {what}")) + .collect(); + (!parts.is_empty()).then(|| format!("{} left out", parts.join(", "))) + } +} + /// Kriging's sample points with those at the same place (within 1e-9 in x and in y) as one, their /// values averaged: in x then y order, each point joins the latest point kept before it that is /// less than 1e-9 to its left and less than 1e-9 above or below it, else is kept. The points kept @@ -12239,6 +12339,88 @@ mod tests { assert_eq!(control.progress(), Some((40, 40))); } + /// A layer of three good points and three that interpolation can't use: no geometry, a null value, + /// a coordinate that isn't a number. + fn lossy_points() -> Map { + let mut pts = Dataset::new("lossy", GeometryType::Point, vec![Field::new("v", FieldType::Double)]); + for (x, y, v) in [(0.5, 0.5, 1.0), (1.5, 0.5, 2.0), (1.0, 1.5, 3.0)] { + pts.push(Some(Geometry::Point(Coord::new(x, y))), vec![Value::Float(v)]); + } + pts.push(None, vec![Value::Float(4.0)]); + pts.push(Some(Geometry::Point(Coord::new(1.0, 1.0))), vec![Value::Null]); + pts.push(Some(Geometry::Point(Coord::new(f64::NAN, 1.0))), vec![Value::Float(5.0)]); + Map(HashMap::from([("lossy".to_string(), pts)])) + } + + /// Features interpolation leaves out are said, one notice per kind with a count; a layer that loses + /// none says nothing. + #[test] + fn interpolation_says_the_features_it_leaves_out() { + use rustgis_data::loss::LossCode::{DroppedFeature, DroppedGeometry}; + let m = lossy_points(); + for (tool, name, place) in [ + ("idwInterpolation", "IDW Interpolation", "a coordinate is not a finite number"), + ("kriging", "Ordinary Kriging", "a coordinate (or, for a line or polygon, its centre) is not a finite number"), + ] { + let p = serde_json::json!({"input": "lossy", "field": "v", "extent": "0,0,2,2", "pixelSize": 0.5}); + let r = crate::run(tool, &m, &p).unwrap_or_else(|e| panic!("{tool}: {e}")); + let got: Vec<(rustgis_data::loss::LossCode, String)> = r.losses.iter().map(|l| (l.code, l.text.clone())).collect(); + let want = vec![ + (DroppedFeature, format!("{name}: 1 of 6 feature(s) left out: they have no geometry, or an empty one")), + (DroppedFeature, format!("{name}: 1 of 6 feature(s) left out: their v value is empty or not a finite number")), + (DroppedGeometry, format!("{name}: 1 point(s) left out: {place}")), + ]; + assert_eq!(got, want, "{tool}"); + } + // Clean input: no loss. + let clean = inputs(); + for tool in ["idwInterpolation", "kriging"] { + let p = serde_json::json!({"input": "pts", "field": "v", "extent": "0,0,2,2", "pixelSize": 0.5}); + let r = crate::run(tool, &clean, &p).unwrap_or_else(|e| panic!("{tool}: {e}")); + assert!(r.losses.is_empty(), "{tool}: {:?}", r.losses); + } + } + + /// With too few points left, the error says what was left out. + #[test] + fn interpolation_with_too_few_points_says_why() { + let mut pts = Dataset::new("few", GeometryType::Point, vec![Field::new("v", FieldType::Double)]); + pts.push(Some(Geometry::Point(Coord::new(0.5, 0.5))), vec![Value::Float(1.0)]); + pts.push(Some(Geometry::Point(Coord::new(1.5, 1.5))), vec![Value::Null]); + pts.push(Some(Geometry::Point(Coord::new(1.0, 1.0))), vec![Value::Null]); + let m = Map(HashMap::from([("few".to_string(), pts)])); + for tool in ["idwInterpolation", "kriging"] { + let e = crate::run(tool, &m, &serde_json::json!({"input": "few", "field": "v"})).err().unwrap_or_default(); + assert!(e.contains("at least two points"), "{tool}: {e}"); + assert!(e.ends_with("(2 whose value isn't a number left out)"), "{tool}: {e}"); + } + // Nothing usable at all: the error still says what was left out. + let mut none = Dataset::new("none", GeometryType::Point, vec![Field::new("v", FieldType::Double)]); + none.push(None, vec![Value::Float(1.0)]); + let m = Map(HashMap::from([("none".to_string(), none)])); + for tool in ["idwInterpolation", "kriging"] { + let e = crate::run(tool, &m, &serde_json::json!({"input": "none", "field": "v"})).err().unwrap_or_default(); + assert!(e.ends_with("(1 with no geometry left out)"), "{tool}: {e}"); + } + } + + /// IDW looks at Cancel while it reads its points, as Kriging does, not only once its grid is + /// being made. + #[test] + fn idw_interpolation_looks_at_cancel_while_it_reads_its_points() { + let mut pts = Dataset::new("many", GeometryType::Point, vec![Field::new("v", FieldType::Double)]); + for i in 0..(2 * LOOK_EVERY + 1) { + let (x, y) = ((i % 100) as f64 / 100.0, (i / 100 % 100) as f64 / 100.0); + pts.push(Some(Geometry::Point(Coord::new(x, y))), vec![Value::Float(i as f64)]); + } + let m = Map(HashMap::from([("many".to_string(), pts)])); + let control = crate::control::Control::cancelled_at_look(u64::MAX); + let p = serde_json::json!({"input": "many", "field": "v", "extent": "0,0,1,1", "pixelSize": 1}); + crate::run_with("idwInterpolation", &m, &p, &control).unwrap_or_else(|e| panic!("{e}")); + // Three looks while reading (features 0, 4096, 8192), then the grid's one row. + assert!(control.looked() >= 4, "looked {} times", control.looked()); + } + #[test] fn idw_interpolation_writes_a_raster() { let m = inputs(); diff --git a/crates/engine/src/tests/cancellation.rs b/crates/engine/src/tests/cancellation.rs index d53a184630..a17f816211 100644 --- a/crates/engine/src/tests/cancellation.rs +++ b/crates/engine/src/tests/cancellation.rs @@ -370,6 +370,7 @@ pub(super) fn long_commands(boundaries: bool) { ("convexHull", json!({"input": "Countries", "group": "None", "output": "Hulls_each"})), ("convexHull", json!({"input": "Countries", "group": "All", "output": "Hulls_all"})), ("kernelDensity", json!({"input": "Cities", "crs": "EPSG:3857", "pixelSize": if boundaries { 2000 } else { 1000000 }})), + ("idwInterpolation", json!({"input": "Cities", "field": "pop_max", "pixelSize": if boundaries { 0.01 } else { 1.0 }})), ("kriging", json!({"input": "Cities", "field": "pop_max", "pixelSize": if boundaries { 0.01 } else { 1.0 }})), ("tabulateArea", json!({"raster": dem, "zones": "Countries"})), ("tabulateIntersection", json!({"zones": "Countries", "classes": "Squares", "includeEmptyZones": true})), diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 260edd831d..f127884dba 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -764,7 +764,10 @@ gp.run={"tool":"pointsAlongLines","params":{"input":"Rivers","distance":500,"uni cell by 1/distanceᴾ, where P is the distance coefficient (2 by default). Lines and polygons contribute their vertices. Leave the extent empty to use the input's, or give it as `xmin,ymin,xmax,ymax`. `pixelSize` sets the cell size; when omitted it starts at 300 cells -across the extent and coarsens for large inputs. The result is a Float32 GeoTIFF layer. The +across the extent and coarsens for large inputs. The result is a Float32 GeoTIFF layer. Features +with no geometry, or whose field isn't a finite number, and coordinates that aren't finite numbers, +are left out and said, once for each kind with its count (`dropped.feature`, `dropped.geometry`); +when fewer than two points are left, the error says how many were left out. The **Geostatistical Wizard** is a separate IDW workflow, with its coordinate system from Environments (below): it uses 12 nearest neighbours by default (`neighbors`), rather than every point. @@ -790,7 +793,8 @@ override the defaults: zero nugget, the sample variance (1 for near-constant val third of the extent's diagonal. `range`, `extent` and `pixelSize` are in the units of `crs`, or in degrees without it (see above). Points at the same location are averaged; multipoints contribute their points, while lines and polygons contribute their bounding-box centres. At least -two distinct locations with numeric values are needed. It adds **two separate Float32 GeoTIFF +two distinct locations with numeric values are needed. Features with no geometry or no numeric +value, and points that aren't finite numbers, are left out and said, as for IDW Interpolation. It adds **two separate Float32 GeoTIFF layers**: the prediction, named by `output`, and `_variance`. **Clip** (`clip`) keeps the parts of `input` inside the `clip` polygons. It gives one notice with diff --git a/xtask/row-uses.txt b/xtask/row-uses.txt index 9b9e9b2c53..d449074834 100644 --- a/xtask/row-uses.txt +++ b/xtask/row-uses.txt @@ -4,4 +4,4 @@ # down: new code reads and changes rows through the accessors on `Features` # (crates/data/src/row_access.rs). When a change lowers it, run `cargo xtask rows --update` and # commit this file with it. -count = 764 +count = 760 From 82fbbb05728d8ab825ec560e056949c5f70a432f Mon Sep 17 00:00:00 2001 From: choupeanut Date: Sun, 29 Nov 2026 00:21:20 +0800 Subject: [PATCH 02/13] =?UTF-8?q?fix(analysis):=20Project=20Raster=20avera?= =?UTF-8?q?ges=20a=20cell=20across=20=C2=B1180=C2=B0=20from=20the=20pixels?= =?UTF-8?q?=20on=20both=20sides=20of=20the=20seam=20(#2918)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/analysis/src/warp.rs | 98 ++++++++++++++++++++++++++++++++++--- docs/user-guide/analysis.md | 3 +- 2 files changed, 93 insertions(+), 8 deletions(-) diff --git a/crates/analysis/src/warp.rs b/crates/analysis/src/warp.rs index 7317c4afed..6e2af95142 100644 --- a/crates/analysis/src/warp.rs +++ b/crates/analysis/src/warp.rs @@ -855,7 +855,10 @@ fn aggregated( return canvas.finish(r, g, bands, if mode { Method::Mode } else { Method::Average }, name); } let x_at = |i: usize| g.min_x + i as f64 * g.cell_x; - let each = Aggregate { r, canvas: &canvas, nearest, mode, round }; + // A source that spans the globe wraps at ±180°: its width in pixels is one turn of longitude. + let pixel = r.transform.pixel_width.abs(); + let wrap = (r.crs.is_geographic() && (w as f64 * pixel - 360.0).abs() <= pixel).then_some(w as f64); + let each = Aggregate { r, canvas: &canvas, nearest, mode, round, wrap }; // A cell's work in `MIN_ROW_WORK`'s units (some 30 ns): its corners, and the pixels it takes // per band (the source's pixels, shared among the cells that cover them). let work = ow.saturating_mul(oh).saturating_add(w.saturating_mul(h)).saturating_mul(canvas.nb.saturating_add(1)); @@ -874,6 +877,7 @@ fn aggregated( weights: vec![Vec::new(); canvas.nb], sums: vec![(0.0, 0.0); canvas.nb], cell: vec![f32::NAN; canvas.nb], + pace: crate::control::Pace::default(), }, |s, oy, mut line| { let Corners { last, top, bottom, nodes, .. } = &mut *s; @@ -904,6 +908,8 @@ struct Corners { weights: Vec>, sums: Vec<(f64, f64)>, cell: Vec, + /// Looks at Cancel within a row of cells that take many pixels. + pace: crate::control::Pace, } /// What each row of [`aggregated`] takes from the source. @@ -914,6 +920,8 @@ struct Aggregate<'a> { nearest: Sampler<'a>, mode: bool, round: bool, + /// The width in pixels of a source that spans the globe, where a cell across ±180° wraps. + wrap: Option, } impl Aggregate<'_> { @@ -922,21 +930,37 @@ impl Aggregate<'_> { let (r, canvas, nearest, mode, round) = (self.r, self.canvas, &self.nearest, self.mode, self.round); let (w, h) = (r.width as usize, r.height as usize); let alpha = canvas.alpha_src; - let Corners { top, bottom, values, weights, sums, cell, .. } = s; + let Corners { top, bottom, values, weights, sums, cell, pace, .. } = s; let ow = top.len().saturating_sub(1); for ox in 0..ow { let corners = (top.get(ox), top.get(ox + 1), bottom.get(ox + 1), bottom.get(ox)); let (Some(Some(tl)), Some(Some(tr)), Some(Some(br)), Some(Some(bl))) = corners else { continue }; - let quad = [*tl, *tr, *br, *bl]; - let (c0, c1) = quad.iter().fold((f64::MAX, f64::MIN), |(lo, hi), p| (lo.min(p.0), hi.max(p.0))); + let mut quad = [*tl, *tr, *br, *bl]; + let mut span = quad.iter().fold((f64::MAX, f64::MIN), |(lo, hi), p| (lo.min(p.0), hi.max(p.0))); + // A cell across ±180° has corners at columns near both ends of the image: the pixels + // between are the far side of the globe. Its corners in the west go on past the east + // edge instead, and the pixels past it are the west's again (`i % w`). + let mut wrapped = false; + if let Some(turn) = self.wrap.filter(|turn| span.1 - span.0 > turn / 2.0) { + let shifted = quad.map(|p| if p.0 < turn / 2.0 { (p.0 + turn, p.1) } else { p }); + let moved = shifted.iter().fold((f64::MAX, f64::MIN), |(lo, hi), p| (lo.min(p.0), hi.max(p.0))); + if moved.1 - moved.0 < span.1 - span.0 { + (quad, span, wrapped) = (shifted, moved, true); + } + } + let (c0, c1) = span; let (r0, r1) = quad.iter().fold((f64::MAX, f64::MIN), |(lo, hi), p| (lo.min(p.1), hi.max(p.1))); - if c1 <= 0.0 || r1 <= 0.0 || c0 >= w as f64 || r0 >= h as f64 { + if c1 <= 0.0 || r1 <= 0.0 || c0 >= if wrapped { 2.0 } else { 1.0 } * w as f64 || r0 >= h as f64 { continue; } // The pixels whose centres (at half integers) may be inside. let first = |lo: f64| (lo - 0.5).ceil().max(0.0) as usize; let past = |hi: f64, n: usize| ((hi - 0.5).floor() + 1.0).clamp(0.0, n as f64) as usize; - let (i0, i1, j0, j1) = (first(c0), past(c1, w), first(r0), past(r1, h)); + let (i0, i1, j0, j1) = (first(c0), past(c1, if wrapped { 2 * w } else { w }), first(r0), past(r1, h)); + // The pixels of a wide cell take long on their own: Cancel is looked at between cells. + if pace.stop(i1.saturating_sub(i0).saturating_mul(j1.saturating_sub(j0))) { + return; + } values.iter_mut().for_each(Vec::clear); weights.iter_mut().for_each(Vec::clear); // The mean is summed as the pixels come (no copy of the cell's values); mode keeps them. @@ -948,7 +972,7 @@ impl Aggregate<'_> { continue; } inside = true; - let idx = j * w + i; + let idx = j * w + i % w; // An alpha with no value (the raster's no-data) or below 0 weighs nothing. let opacity = alpha .and_then(|a| r.bands.get(a)) @@ -991,6 +1015,7 @@ impl Aggregate<'_> { } else { // A grid finer than the raster: the pixel under the cell's centre. let (cx, cy) = (quad.iter().map(|p| p.0).sum::() / 4.0, quad.iter().map(|p| p.1).sum::() / 4.0); + let cx = if wrapped && cx >= w as f64 { cx - w as f64 } else { cx }; if !(cx >= 0.0 && cy >= 0.0 && cx < w as f64 && cy < h as f64) { continue; } @@ -1726,4 +1751,63 @@ mod tests { let _installed = crate::control::install(Some(run)); assert_eq!(rasterize(&g, &shapes, -1.0).unwrap_err(), crate::control::CANCELLED); } + + /// A global source of 8 × 2 pixels (45° across): column 7 holds 3, column 0 holds 1, the rest 100. + fn globe(width_deg: f64) -> Raster { + let gt = GeoTransform { origin_x: -180.0, origin_y: 90.0, pixel_width: width_deg / 8.0, pixel_height: -90.0 }; + let column = |c: usize| match c { + 0 => 1.0, + 7 => 3.0, + _ => 100.0, + }; + let v: Vec = (0..16).map(|i| column(i % 8)).collect(); + Raster::new("globe", 8, 2, vec![v], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap() + } + + /// One output cell from `x0` to `x1` whose corners the `source` places on the 8 × 2 image. + fn one_cell(r: &Raster, x0: f64, x1: f64, mode: bool, source: &Source) -> Option { + let g = Grid { crs: Crs::LonLat, min_x: x0, max_y: 90.0, cell_x: x1 - x0, cell_y: 180.0, width: 1, height: 1 }; + let out = aggregated(Some(1), r, &g, Canvas::of(r, false), mode, source, "seam".into()).unwrap(); + out.value(0, 0, 0) + } + + /// An output cell across ±180° of a source that spans the globe takes the pixels either side of + /// the seam, not the far side of the globe its corners' columns (7 and 1) span. + #[test] + fn average_and_mode_across_the_antimeridian_take_the_pixels_on_both_sides() { + let r = globe(360.0); + // Output longitudes (0..360 east of Greenwich) folded into the source's -180..180, as an + // output system centred on 180° gives them back. + let folded = |x: f64, y: f64| Some((((x + 180.0).rem_euclid(360.0)) / 360.0 * 8.0, (90.0 - y) / 90.0)); + // 135°..225°: the centres of column 7 (3) and column 0 (1). + assert_eq!(one_cell(&r, 135.0, 225.0, false, &folded), Some(2.0)); + // Of the two tied values, the one that reaches the top count first, the pixels taken in order. + assert_eq!(one_cell(&r, 135.0, 225.0, true, &folded), Some(3.0)); + // A corner placed at column 8 (exactly 180°) rather than column 0 wraps the same way. + let at_eight = |x: f64, y: f64| if x == 180.0 { Some((8.0, (90.0 - y) / 90.0)) } else { folded(x, y) }; + assert_eq!(one_cell(&r, 180.0, 270.0, false, &at_eight), Some(50.5)); + assert_eq!(one_cell(&r, 180.0, 270.0, false, &folded), Some(50.5)); + // No seam: columns 6 and 7 (180° is column 8, both corners in the image). + assert_eq!(one_cell(&r, 90.0, 180.0, false, &at_eight), Some(51.5)); + // A source that doesn't span the globe has no seam to wrap: the quad keeps its columns. + let part = globe(180.0); + let none = |x: f64, y: f64| Some((if x < 180.0 { 7.0 } else { 1.0 }, (90.0 - y) / 90.0)); + assert_eq!(one_cell(&part, 135.0, 225.0, false, &none), Some(100.0)); + } + + /// The same through `project`: a global image into UTM zone 60, whose grid runs on past 180°. + #[test] + fn project_averages_and_takes_the_mode_across_the_antimeridian() { + // 720 × 360 pixels of 0.5°: 10 in the 60° either side of ±180°, 1000 elsewhere. + let gt = GeoTransform { origin_x: -180.0, origin_y: 90.0, pixel_width: 0.5, pixel_height: -0.5 }; + let v: Vec = (0..720 * 360).map(|i| if !(120..600).contains(&(i % 720)) { 10.0 } else { 1000.0 }).collect(); + let r = Raster::new("globe", 720, 360, vec![v], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + // Fiji: 177.5°E to about 186°E, at 10°N. + let crs = Crs::from_epsg(32660).unwrap(); + let g = Grid::snapped(crs, [700_000.0, 1_050_000.0, 900_000.0, 1_150_000.0], (50_000.0, 50_000.0), (0.0, 0.0)).unwrap(); + for method in [Method::Average, Method::Mode] { + let out = project(&r, &g, method, "fiji".into()).unwrap(); + assert!(values(&out).iter().all(|v| *v == Some(10.0)), "{method:?}: {:?}", values(&out)); + } + } } diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index f127884dba..165f2dd7e5 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -2161,7 +2161,8 @@ commands described here aren't on the tab or part of the extension, and run whet value (of those tied, the one that reaches the top count first, the pixels taken row by row, as in GDAL), which is what a coarser grid of elevation or land-cover classes should hold. A cell no pixel centre falls in, on a grid finer than the raster, takes the pixel under its - centre. Classes take `nearest` or `mode`, continuous values `bilinear` or `cubic`, or `average` + centre. A cell across the antimeridian of a source that spans the globe takes the pixels on both + sides of it. Classes take `nearest` or `mode`, continuous values `bilinear` or `cubic`, or `average` going coarser. A whole-number pixel type keeps its type, so its mean is rounded. On a colour image the colours count as much as their pixels are opaque, and `mode` is taken band by band (each channel's most frequent value among the pixels that show). Class names are kept with From c3cc15ad53fd6b191edefe802030834665890eeb Mon Sep 17 00:00:00 2001 From: choupeanut Date: Sun, 29 Nov 2026 01:08:19 +0800 Subject: [PATCH 03/13] fix(analysis): a cell the width of the globe is not a seam cell, and Cancel tests for the new looks (#2918) --- crates/analysis/src/tools.rs | 44 ++++++++++++++++++------------ crates/analysis/src/warp.rs | 53 +++++++++++++++++++++++++++++++----- docs/user-guide/analysis.md | 12 +++++--- 3 files changed, 80 insertions(+), 29 deletions(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 4ccac6b51e..602256fc95 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -5182,6 +5182,10 @@ fn idw_interpolation(inp: &dyn Inputs, p: &Json) -> Result { let why = left_out.why(); let (crs, crs_note) = raster_crs_in(ds, inp.work_crs(), inp.project_crs(), p, "IDW Interpolation")?; let (pts, beyond_note) = points_from(inp.work_crs(), crs, pts)?; + // Too few points to go on: the error says what was left out of them. + if pts.len() < 2 { + return Err(with_note(with_note("interpolation needs at least two points with values".into(), &beyond_note), &why)); + } let extent = match s(p, "extent").trim() { "" => { let mut e = Extent::EMPTY; @@ -5212,8 +5216,8 @@ fn idw_interpolation(inp: &dyn Inputs, p: &Json) -> Result { None => 2.0, }; let name = out_name(p, format!("{}_{field}_idw", ds.name)); - let r = crate::rasterops::idw(&pts, &extent, cell, power, 0, &name, crs) - .map_err(|e| with_note(with_note(with_note(e, &beyond_note), &crs_note), &why))?; + let r = + crate::rasterops::idw(&pts, &extent, cell, power, 0, &name, crs).map_err(|e| with_note(with_note(e, &beyond_note), &crs_note))?; let bytes = rustgis_data::raster::geotiff::write(&r, 0).map_err(|e| e.to_string())?; let msg = format!("IDW Interpolation: {} × {} cells from {} points", r.width, r.height, pts.len()); Ok(ToolResult { @@ -5354,7 +5358,7 @@ fn kriging_interpolation(inp: &dyn Inputs, p: &Json) -> Result 0 { losses.push(LossMessage { code: LossCode::DroppedGeometry, - text: format!("{tool}: {} point(s) left out: {place}", self.no_place), + text: format!("{tool}: {} coordinate(s) left out: {place}", self.no_place), }); } losses @@ -5422,7 +5426,7 @@ impl PointsLeftOut { let parts: Vec = [ (self.no_geometry, "with no geometry"), (self.no_value, "whose value isn't a number"), - (self.no_place, "with a coordinate that isn't a number"), + (self.no_place, "coordinate(s) that aren't numbers"), ] .into_iter() .filter(|(n, _)| *n > 0) @@ -12368,7 +12372,7 @@ mod tests { let want = vec![ (DroppedFeature, format!("{name}: 1 of 6 feature(s) left out: they have no geometry, or an empty one")), (DroppedFeature, format!("{name}: 1 of 6 feature(s) left out: their v value is empty or not a finite number")), - (DroppedGeometry, format!("{name}: 1 point(s) left out: {place}")), + (DroppedGeometry, format!("{name}: 1 coordinate(s) left out: {place}")), ]; assert_eq!(got, want, "{tool}"); } @@ -12405,20 +12409,24 @@ mod tests { } /// IDW looks at Cancel while it reads its points, as Kriging does, not only once its grid is - /// being made. + /// being made: the same run over more features looks once more for each 4096 of them. #[test] fn idw_interpolation_looks_at_cancel_while_it_reads_its_points() { - let mut pts = Dataset::new("many", GeometryType::Point, vec![Field::new("v", FieldType::Double)]); - for i in 0..(2 * LOOK_EVERY + 1) { - let (x, y) = ((i % 100) as f64 / 100.0, (i / 100 % 100) as f64 / 100.0); - pts.push(Some(Geometry::Point(Coord::new(x, y))), vec![Value::Float(i as f64)]); - } - let m = Map(HashMap::from([("many".to_string(), pts)])); - let control = crate::control::Control::cancelled_at_look(u64::MAX); - let p = serde_json::json!({"input": "many", "field": "v", "extent": "0,0,1,1", "pixelSize": 1}); - crate::run_with("idwInterpolation", &m, &p, &control).unwrap_or_else(|e| panic!("{e}")); - // Three looks while reading (features 0, 4096, 8192), then the grid's one row. - assert!(control.looked() >= 4, "looked {} times", control.looked()); + let looks = |features: usize| { + let mut pts = Dataset::new("many", GeometryType::Point, vec![Field::new("v", FieldType::Double)]); + for i in 0..features { + let (x, y) = ((i % 100) as f64 / 100.0, (i / 100 % 100) as f64 / 100.0); + pts.push(Some(Geometry::Point(Coord::new(x, y))), vec![Value::Float(i as f64)]); + } + let m = Map(HashMap::from([("many".to_string(), pts)])); + let control = crate::control::Control::cancelled_at_look(u64::MAX); + let p = serde_json::json!({"input": "many", "field": "v", "extent": "0,0,1,1", "pixelSize": 1}); + crate::run_with("idwInterpolation", &m, &p, &control).unwrap_or_else(|e| panic!("{e}")); + control.looked() + }; + // Features 0, 4096 and 8192 are looked at, against feature 0 alone. + let (few, many) = (looks(2), looks(2 * LOOK_EVERY + 1)); + assert!(many >= few + 2, "{few} looks over 2 features, {many} over {}", 2 * LOOK_EVERY + 1); } #[test] diff --git a/crates/analysis/src/warp.rs b/crates/analysis/src/warp.rs index 6e2af95142..5a7f337528 100644 --- a/crates/analysis/src/warp.rs +++ b/crates/analysis/src/warp.rs @@ -855,9 +855,10 @@ fn aggregated( return canvas.finish(r, g, bands, if mode { Method::Mode } else { Method::Average }, name); } let x_at = |i: usize| g.min_x + i as f64 * g.cell_x; - // A source that spans the globe wraps at ±180°: its width in pixels is one turn of longitude. + // A source that spans -180° to 180° wraps at ±180°: its width in pixels is one turn of longitude. let pixel = r.transform.pixel_width.abs(); - let wrap = (r.crs.is_geographic() && (w as f64 * pixel - 360.0).abs() <= pixel).then_some(w as f64); + let (west, east) = (r.transform.origin_x, r.transform.origin_x + w as f64 * r.transform.pixel_width); + let wrap = (r.crs.is_geographic() && pixel > 0.0 && (west + 180.0).abs() <= pixel && (east - 180.0).abs() <= pixel).then_some(w as f64); let each = Aggregate { r, canvas: &canvas, nearest, mode, round, wrap }; // A cell's work in `MIN_ROW_WORK`'s units (some 30 ns): its corners, and the pixels it takes // per band (the source's pixels, shared among the cells that cover them). @@ -937,11 +938,20 @@ impl Aggregate<'_> { let (Some(Some(tl)), Some(Some(tr)), Some(Some(br)), Some(Some(bl))) = corners else { continue }; let mut quad = [*tl, *tr, *br, *bl]; let mut span = quad.iter().fold((f64::MAX, f64::MIN), |(lo, hi), p| (lo.min(p.0), hi.max(p.0))); - // A cell across ±180° has corners at columns near both ends of the image: the pixels - // between are the far side of the globe. Its corners in the west go on past the east - // edge instead, and the pixels past it are the west's again (`i % w`). + // A cell across ±180° has its west corners at columns near the east end of the image + // and its east corners near the west end: going east along an edge, the column drops by + // more than half the image. The pixels between are the far side of the globe. Its + // corners in the west go on past the east edge instead, and the pixels past it are the + // west's again (`i % w`). A cell wide enough to take in the whole image, or one whose + // columns grow eastward as they do in an ordinary cell, is not across the seam. (An + // output that runs east to west, or a cell over half the globe wide in one, cannot be + // told from one across it and is read as before.) let mut wrapped = false; - if let Some(turn) = self.wrap.filter(|turn| span.1 - span.0 > turn / 2.0) { + let drop = |from: &(f64, f64), to: &(f64, f64)| from.0 - to.0; + if let Some(turn) = self.wrap.filter(|turn| { + let whole = span.0 <= 0.0 && span.1 >= *turn; + !whole && (drop(tl, tr) > turn / 2.0 || drop(bl, br) > turn / 2.0) + }) { let shifted = quad.map(|p| if p.0 < turn / 2.0 { (p.0 + turn, p.1) } else { p }); let moved = shifted.iter().fold((f64::MAX, f64::MIN), |(lo, hi), p| (lo.min(p.0), hi.max(p.0))); if moved.1 - moved.0 < span.1 - span.0 { @@ -1795,6 +1805,19 @@ mod tests { assert_eq!(one_cell(&part, 135.0, 225.0, false, &none), Some(100.0)); } + /// A cell that is wide but not across the seam keeps the pixels between its corners: the whole + /// globe in one cell (corners at columns 0 and 8), or three fifths of it. + #[test] + fn a_wide_cell_that_is_not_across_the_antimeridian_keeps_its_pixels() { + let r = globe(360.0); + let plain = |x: f64, y: f64| Some((((x + 180.0) / 360.0) * 8.0, (90.0 - y) / 90.0)); + // Every column: (1 + 6 × 100 + 3) / 8. + assert_eq!(one_cell(&r, -180.0, 180.0, false, &plain), Some(75.5)); + // Columns 2.8 to 7.6: the centres of 3 to 7 are 100, 100, 100, 100 and 3. + let wide = one_cell(&r, -54.0, 162.0, false, &plain).unwrap(); + assert!((wide - 80.6).abs() < 1e-4, "{wide}"); + } + /// The same through `project`: a global image into UTM zone 60, whose grid runs on past 180°. #[test] fn project_averages_and_takes_the_mode_across_the_antimeridian() { @@ -1802,7 +1825,7 @@ mod tests { let gt = GeoTransform { origin_x: -180.0, origin_y: 90.0, pixel_width: 0.5, pixel_height: -0.5 }; let v: Vec = (0..720 * 360).map(|i| if !(120..600).contains(&(i % 720)) { 10.0 } else { 1000.0 }).collect(); let r = Raster::new("globe", 720, 360, vec![v], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); - // Fiji: 177.5°E to about 186°E, at 10°N. + // Fiji, at 10°N: eastings of 700 to 900 km are 178.8°E to 180.7°E. let crs = Crs::from_epsg(32660).unwrap(); let g = Grid::snapped(crs, [700_000.0, 1_050_000.0, 900_000.0, 1_150_000.0], (50_000.0, 50_000.0), (0.0, 0.0)).unwrap(); for method in [Method::Average, Method::Mode] { @@ -1810,4 +1833,20 @@ mod tests { assert!(values(&out).iter().all(|v| *v == Some(10.0)), "{method:?}: {:?}", values(&out)); } } + /// A cell that takes millions of pixels looks at Cancel as it goes: one cancelled at its second + /// look (the row's was the first) is left empty, not computed. + #[test] + fn a_cell_of_millions_of_pixels_looks_at_cancel() { + let n = 2100; + let gt = GeoTransform { origin_x: 0.0, origin_y: f64::from(n), pixel_width: 1.0, pixel_height: -1.0 }; + let r = + Raster::new("big", n, n, vec![vec![100.0; (n * n) as usize]], gt, Crs::Epsg(32613), None, ColorHint::Gray, "Float32").unwrap(); + let g = Grid { crs: r.crs, min_x: 0.0, max_y: f64::from(n), cell_x: f64::from(n), cell_y: f64::from(n), width: 1, height: 1 }; + let source = |x: f64, y: f64| Some((x, f64::from(n) - y)); + let run = crate::control::Control::cancelled_at_look(2); + let _installed = crate::control::install(Some(run.clone())); + let out = aggregated(Some(1), &r, &g, Canvas::of(&r, false), false, &source, "big".into()).unwrap(); + assert_eq!(out.value(0, 0, 0), None); + assert_eq!(run.looked(), 2); + } } diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 165f2dd7e5..79f728c55c 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -794,8 +794,9 @@ third of the extent's diagonal. `range`, `extent` and `pixelSize` are in the uni in degrees without it (see above). Points at the same location are averaged; multipoints contribute their points, while lines and polygons contribute their bounding-box centres. At least two distinct locations with numeric values are needed. Features with no geometry or no numeric -value, and points that aren't finite numbers, are left out and said, as for IDW Interpolation. It adds **two separate Float32 GeoTIFF -layers**: the prediction, named by `output`, and `_variance`. +value, and coordinates that aren't finite numbers, are left out and said, as for IDW +Interpolation. It adds **two separate Float32 GeoTIFF layers**: the prediction, named by +`output`, and `_variance`. **Clip** (`clip`) keeps the parts of `input` inside the `clip` polygons. It gives one notice with the count of output polygon features whose total area is less than one millionth (`1e-6`) of @@ -2161,8 +2162,11 @@ commands described here aren't on the tab or part of the extension, and run whet value (of those tied, the one that reaches the top count first, the pixels taken row by row, as in GDAL), which is what a coarser grid of elevation or land-cover classes should hold. A cell no pixel centre falls in, on a grid finer than the raster, takes the pixel under its - centre. A cell across the antimeridian of a source that spans the globe takes the pixels on both - sides of it. Classes take `nearest` or `mode`, continuous values `bilinear` or `cubic`, or `average` + centre. A cell across the antimeridian of a source that spans -180° to 180° takes the pixels on + both sides of it (in an output whose x grows eastward; a cell over half the globe wide in one + that runs east to west can't be told from one across it). A source that runs from 0° to 360° + is not wrapped, and `bilinear` and `cubic` still clamp at the seam instead of reading across + it. Classes take `nearest` or `mode`, continuous values `bilinear` or `cubic`, or `average` going coarser. A whole-number pixel type keeps its type, so its mean is rounded. On a colour image the colours count as much as their pixels are opaque, and `mode` is taken band by band (each channel's most frequent value among the pixels that show). Class names are kept with From 351a76a44a428f752bd892d3f0c0ee4a0576c34f Mon Sep 17 00:00:00 2001 From: choupeanut Date: Sun, 29 Nov 2026 01:12:14 +0800 Subject: [PATCH 04/13] docs(analysis): say where IDW looks at Cancel, and a blank line in the warp tests (#2918) --- crates/analysis/src/tools.rs | 3 ++- crates/analysis/src/warp.rs | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 602256fc95..52ddf6094a 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -5153,7 +5153,8 @@ fn idw_interpolation(inp: &dyn Inputs, p: &Json) -> Result { let mut pts: Vec<(Coord, f64)> = Vec::new(); let mut left_out = PointsLeftOut::default(); let picked = rows(inp, p, "input", ds); - // A single geometry's coordinates are walked without a look at Cancel: one feature is short next to the features. + // Cancel is looked at between features; one feature with millions of vertices is read through + // `for_each_coord` without a look inside it. for (n, r) in picked.iter().copied().enumerate() { if n % LOOK_EVERY == 0 { crate::control::check()?; diff --git a/crates/analysis/src/warp.rs b/crates/analysis/src/warp.rs index 5a7f337528..de0cb9e778 100644 --- a/crates/analysis/src/warp.rs +++ b/crates/analysis/src/warp.rs @@ -1833,6 +1833,7 @@ mod tests { assert!(values(&out).iter().all(|v| *v == Some(10.0)), "{method:?}: {:?}", values(&out)); } } + /// A cell that takes millions of pixels looks at Cancel as it goes: one cancelled at its second /// look (the row's was the first) is left empty, not computed. #[test] From 42fb39065a62c03384739aa7a08ef81c902ba6b0 Mon Sep 17 00:00:00 2001 From: Li-Sheng Chou <142213184+choupeanut@users.noreply.github.com> Date: Sun, 29 Nov 2026 02:28:52 +0800 Subject: [PATCH 05/13] analysis: Kriging counts rejected line and polygon coordinates as coordinates (#2918) --- crates/analysis/src/tools.rs | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 52ddf6094a..7d163f88dd 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -5282,7 +5282,10 @@ fn kriging_interpolation(inp: &dyn Inputs, p: &Json) -> Result { let ext = g.extent(); - if !ext.is_empty() { + if ext.is_empty() { + // The extent skips coordinates that aren't numbers: empty with coordinates, all were rejected. + left_out.no_place += g.coord_count(); + } else { let center = Coord::new((ext.min_x + ext.max_x) * 0.5, (ext.min_y + ext.max_y) * 0.5); if center.is_finite() { raw_pts.push((center, v)); @@ -12386,6 +12389,30 @@ mod tests { } } + /// Kriging counts the coordinates of a line or polygon it rejects as such, not as a feature with + /// no geometry; an empty line is the geometry-less one. + #[test] + fn kriging_counts_rejected_line_coordinates_as_coordinates() { + use rustgis_data::loss::LossCode::{DroppedFeature, DroppedGeometry}; + let mut ds = Dataset::new("lines", GeometryType::Polyline, vec![Field::new("v", FieldType::Double)]); + for (x, y, v) in [(0.5, 0.5, 1.0), (1.5, 0.5, 2.0), (1.0, 1.5, 3.0)] { + ds.push(Some(Geometry::Point(Coord::new(x, y))), vec![Value::Float(v)]); + } + let bad = vec![Coord::new(f64::NAN, 1.0), Coord::new(1.0, f64::INFINITY), Coord::new(f64::NAN, f64::NAN)]; + ds.push(Some(Geometry::Line(vec![bad])), vec![Value::Float(4.0)]); + ds.push(Some(Geometry::Line(vec![])), vec![Value::Float(5.0)]); + let m = Map(HashMap::from([("lines".to_string(), ds)])); + let p = serde_json::json!({"input": "lines", "field": "v", "extent": "0,0,2,2", "pixelSize": 0.5}); + let r = crate::run("kriging", &m, &p).unwrap_or_else(|e| panic!("{e}")); + let got: Vec<(rustgis_data::loss::LossCode, String)> = r.losses.iter().map(|l| (l.code, l.text.clone())).collect(); + let place = "a coordinate (or, for a line or polygon, its centre) is not a finite number"; + let want = vec![ + (DroppedFeature, "Ordinary Kriging: 1 of 5 feature(s) left out: they have no geometry, or an empty one".to_string()), + (DroppedGeometry, format!("Ordinary Kriging: 3 coordinate(s) left out: {place}")), + ]; + assert_eq!(got, want); + } + /// With too few points left, the error says what was left out. #[test] fn interpolation_with_too_few_points_says_why() { From 284457674d4ddba8fa3ea4f7acd949542f226b3f Mon Sep 17 00:00:00 2001 From: Li-Sheng Chou <142213184+choupeanut@users.noreply.github.com> Date: Sun, 29 Nov 2026 02:28:52 +0800 Subject: [PATCH 06/13] analysis: Project Raster wraps a seam by one turn of longitude and looks at Cancel by the row (#2918) --- crates/analysis/src/warp.rs | 105 ++++++++++++++++++++++++------------ 1 file changed, 72 insertions(+), 33 deletions(-) diff --git a/crates/analysis/src/warp.rs b/crates/analysis/src/warp.rs index de0cb9e778..c971e49e2a 100644 --- a/crates/analysis/src/warp.rs +++ b/crates/analysis/src/warp.rs @@ -855,10 +855,13 @@ fn aggregated( return canvas.finish(r, g, bands, if mode { Method::Mode } else { Method::Average }, name); } let x_at = |i: usize| g.min_x + i as f64 * g.cell_x; - // A source that spans -180° to 180° wraps at ±180°: its width in pixels is one turn of longitude. + // A source that spans -180° to 180° wraps at ±180°. One turn of longitude is `360 / pixel` + // columns: the image's width when it spans exactly that, a little more or less when its edges + // are a pixel short of ±180° or past it. let pixel = r.transform.pixel_width.abs(); let (west, east) = (r.transform.origin_x, r.transform.origin_x + w as f64 * r.transform.pixel_width); - let wrap = (r.crs.is_geographic() && pixel > 0.0 && (west + 180.0).abs() <= pixel && (east - 180.0).abs() <= pixel).then_some(w as f64); + let wrap = + (r.crs.is_geographic() && pixel > 0.0 && (west + 180.0).abs() <= pixel && (east - 180.0).abs() <= pixel).then_some(360.0 / pixel); let each = Aggregate { r, canvas: &canvas, nearest, mode, round, wrap }; // A cell's work in `MIN_ROW_WORK`'s units (some 30 ns): its corners, and the pixels it takes // per band (the source's pixels, shared among the cells that cover them). @@ -921,7 +924,7 @@ struct Aggregate<'a> { nearest: Sampler<'a>, mode: bool, round: bool, - /// The width in pixels of a source that spans the globe, where a cell across ±180° wraps. + /// One turn of longitude in columns, for a source that spans the globe, where a cell across ±180° wraps. wrap: Option, } @@ -941,8 +944,8 @@ impl Aggregate<'_> { // A cell across ±180° has its west corners at columns near the east end of the image // and its east corners near the west end: going east along an edge, the column drops by // more than half the image. The pixels between are the far side of the globe. Its - // corners in the west go on past the east edge instead, and the pixels past it are the - // west's again (`i % w`). A cell wide enough to take in the whole image, or one whose + // corners in the west go on past the east edge instead (by one turn of longitude, not + // always the image's width), and the pixels past it are the west's again. A cell wide enough to take in the whole image, or one whose // columns grow eastward as they do in an ordinary cell, is not across the seam. (An // output that runs east to west, or a cell over half the globe wide in one, cannot be // told from one across it and is read as before.) @@ -960,44 +963,51 @@ impl Aggregate<'_> { } let (c0, c1) = span; let (r0, r1) = quad.iter().fold((f64::MAX, f64::MIN), |(lo, hi), p| (lo.min(p.1), hi.max(p.1))); - if c1 <= 0.0 || r1 <= 0.0 || c0 >= if wrapped { 2.0 } else { 1.0 } * w as f64 || r0 >= h as f64 { + let turn = if wrapped { self.wrap.unwrap_or(0.0) } else { 0.0 }; + if c1 <= 0.0 || r1 <= 0.0 || c0 >= w as f64 + turn || r0 >= h as f64 { continue; } // The pixels whose centres (at half integers) may be inside. let first = |lo: f64| (lo - 0.5).ceil().max(0.0) as usize; let past = |hi: f64, n: usize| ((hi - 0.5).floor() + 1.0).clamp(0.0, n as f64) as usize; - let (i0, i1, j0, j1) = (first(c0), past(c1, if wrapped { 2 * w } else { w }), first(r0), past(r1, h)); - // The pixels of a wide cell take long on their own: Cancel is looked at between cells. - if pace.stop(i1.saturating_sub(i0).saturating_mul(j1.saturating_sub(j0))) { - return; - } + let (j0, j1) = (first(r0), past(r1, h)); + // The columns of the image the cell takes: its own, and for a wrapped one the west's + // again, `turn` columns on. + let columns: Vec<(usize, usize, f64)> = + [0.0, turn].into_iter().take(if wrapped { 2 } else { 1 }).map(|off| (first(c0 - off), past(c1 - off, w), off)).collect(); values.iter_mut().for_each(Vec::clear); weights.iter_mut().for_each(Vec::clear); // The mean is summed as the pixels come (no copy of the cell's values); mode keeps them. sums.iter_mut().for_each(|s| *s = (0.0, 0.0)); let mut inside = false; for j in j0..j1 { - for i in i0..i1 { - if !holds(&quad, (i as f64 + 0.5, j as f64 + 0.5)) { - continue; - } - inside = true; - let idx = j * w + i % w; - // An alpha with no value (the raster's no-data) or below 0 weighs nothing. - let opacity = alpha - .and_then(|a| r.bands.get(a)) - .and_then(|band| band.data.get(idx)) - .copied() - .filter(|a| r.is_valid(*a) && *a > 0.0) - .unwrap_or(0.0); - for (b, ((v, k), sum)) in values.iter_mut().zip(weights.iter_mut()).zip(sums.iter_mut()).enumerate() { - if let Some(x) = r.bands.get(b).and_then(|band| band.data.get(idx)).filter(|x| r.is_valid(**x)) { - let weight = if alpha.is_some_and(|a| a != b) { opacity } else { 1.0 }; - if mode { - v.push(*x); - k.push(weight); - } else { - *sum = (sum.0 + f64::from(*x) * f64::from(weight), sum.1 + f64::from(weight)); + // The pixels of a wide cell take long on their own: Cancel is looked at by the row. + if pace.stop(columns.iter().map(|(a, b, _)| b.saturating_sub(*a)).sum()) { + return; + } + for &(i0, i1, off) in &columns { + for i in i0..i1 { + if !holds(&quad, (i as f64 + 0.5 + off, j as f64 + 0.5)) { + continue; + } + inside = true; + let idx = j * w + i; + // An alpha with no value (the raster's no-data) or below 0 weighs nothing. + let opacity = alpha + .and_then(|a| r.bands.get(a)) + .and_then(|band| band.data.get(idx)) + .copied() + .filter(|a| r.is_valid(*a) && *a > 0.0) + .unwrap_or(0.0); + for (b, ((v, k), sum)) in values.iter_mut().zip(weights.iter_mut()).zip(sums.iter_mut()).enumerate() { + if let Some(x) = r.bands.get(b).and_then(|band| band.data.get(idx)).filter(|x| r.is_valid(**x)) { + let weight = if alpha.is_some_and(|a| a != b) { opacity } else { 1.0 }; + if mode { + v.push(*x); + k.push(weight); + } else { + *sum = (sum.0 + f64::from(*x) * f64::from(weight), sum.1 + f64::from(weight)); + } } } } @@ -1025,7 +1035,7 @@ impl Aggregate<'_> { } else { // A grid finer than the raster: the pixel under the cell's centre. let (cx, cy) = (quad.iter().map(|p| p.0).sum::() / 4.0, quad.iter().map(|p| p.1).sum::() / 4.0); - let cx = if wrapped && cx >= w as f64 { cx - w as f64 } else { cx }; + let cx = if wrapped && cx >= turn { cx - turn } else { cx }; if !(cx >= 0.0 && cy >= 0.0 && cx < w as f64 && cy < h as f64) { continue; } @@ -1834,6 +1844,18 @@ mod tests { } } + /// A source whose columns stop short of a whole turn (8 of 44° end at 172°) isn't wrapped: a + /// cell across ±180° keeps its corners' columns, and takes nothing from the far side for the part + /// of the globe the source doesn't cover. + #[test] + fn a_source_short_of_a_whole_turn_does_not_wrap() { + let r = globe(352.0); + // Longitudes folded into -180..180, as the output system centred on 180° gives them. + let folded = |x: f64, y: f64| Some((((x + 180.0).rem_euclid(360.0)) / 44.0, (90.0 - y) / 90.0)); + // 160°..190° has its centre (175°) in the uncovered 172°..180°: no data, not column 7 or 0. + assert_eq!(one_cell(&r, 160.0, 190.0, false, &folded), None); + } + /// A cell that takes millions of pixels looks at Cancel as it goes: one cancelled at its second /// look (the row's was the first) is left empty, not computed. #[test] @@ -1850,4 +1872,21 @@ mod tests { assert_eq!(out.value(0, 0, 0), None); assert_eq!(run.looked(), 2); } + + /// A cell of several times the pixels between two looks looks within its rows: cancelled at the + /// third look (the row's was the first), it is left empty rather than finished. + #[test] + fn a_cell_looks_at_cancel_again_after_its_traversal_starts() { + let n = 3000; + let gt = GeoTransform { origin_x: 0.0, origin_y: f64::from(n), pixel_width: 1.0, pixel_height: -1.0 }; + let r = + Raster::new("big", n, n, vec![vec![100.0; (n * n) as usize]], gt, Crs::Epsg(32613), None, ColorHint::Gray, "Float32").unwrap(); + let g = Grid { crs: r.crs, min_x: 0.0, max_y: f64::from(n), cell_x: f64::from(n), cell_y: f64::from(n), width: 1, height: 1 }; + let source = |x: f64, y: f64| Some((x, f64::from(n) - y)); + let run = crate::control::Control::cancelled_at_look(3); + let _installed = crate::control::install(Some(run.clone())); + let out = aggregated(Some(1), &r, &g, Canvas::of(&r, false), false, &source, "big".into()).unwrap(); + assert_eq!(out.value(0, 0, 0), None); + assert_eq!(run.looked(), 3); + } } From 649fb3e4dd4fce7f09de08605bc86dabb37e60ea Mon Sep 17 00:00:00 2001 From: Li-Sheng Chou <142213184+choupeanut@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:26:14 +0800 Subject: [PATCH 07/13] analysis: Project Raster looks at Cancel while it finds a mode and wraps a half-globe cell; Kriging counts a line's skipped coordinates (#2918) --- crates/analysis/src/tools.rs | 26 ++++++++++++++ crates/analysis/src/warp.rs | 70 +++++++++++++++++++++++++++++------- 2 files changed, 84 insertions(+), 12 deletions(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 7d163f88dd..388d79d493 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -5286,6 +5286,10 @@ fn kriging_interpolation(inp: &dyn Inputs, p: &Json) -> Result = r.losses.iter().map(|l| (l.code, l.text.clone())).collect(); + let place = "a coordinate (or, for a line or polygon, its centre) is not a finite number"; + assert_eq!(got, vec![(DroppedGeometry, format!("Ordinary Kriging: 3 coordinate(s) left out: {place}"))]); + } + /// With too few points left, the error says what was left out. #[test] fn interpolation_with_too_few_points_says_why() { diff --git a/crates/analysis/src/warp.rs b/crates/analysis/src/warp.rs index c971e49e2a..3c27ec65f4 100644 --- a/crates/analysis/src/warp.rs +++ b/crates/analysis/src/warp.rs @@ -943,7 +943,7 @@ impl Aggregate<'_> { let mut span = quad.iter().fold((f64::MAX, f64::MIN), |(lo, hi), p| (lo.min(p.0), hi.max(p.0))); // A cell across ±180° has its west corners at columns near the east end of the image // and its east corners near the west end: going east along an edge, the column drops by - // more than half the image. The pixels between are the far side of the globe. Its + // half the image or more. The pixels between are the far side of the globe. Its // corners in the west go on past the east edge instead (by one turn of longitude, not // always the image's width), and the pixels past it are the west's again. A cell wide enough to take in the whole image, or one whose // columns grow eastward as they do in an ordinary cell, is not across the seam. (An @@ -953,11 +953,12 @@ impl Aggregate<'_> { let drop = |from: &(f64, f64), to: &(f64, f64)| from.0 - to.0; if let Some(turn) = self.wrap.filter(|turn| { let whole = span.0 <= 0.0 && span.1 >= *turn; - !whole && (drop(tl, tr) > turn / 2.0 || drop(bl, br) > turn / 2.0) + !whole && (drop(tl, tr) >= turn / 2.0 || drop(bl, br) >= turn / 2.0) }) { let shifted = quad.map(|p| if p.0 < turn / 2.0 { (p.0 + turn, p.1) } else { p }); let moved = shifted.iter().fold((f64::MAX, f64::MIN), |(lo, hi), p| (lo.min(p.0), hi.max(p.0))); - if moved.1 - moved.0 < span.1 - span.0 { + // (A cell of exactly half the image is as wide either way: the wrapped one is the cell.) + if moved.1 - moved.0 <= span.1 - span.0 { (quad, span, wrapped) = (shifted, moved, true); } } @@ -1020,14 +1021,26 @@ impl Aggregate<'_> { // see-through ones count for nothing, as in the mean. A cell where none // shows takes the mode of all (see-through, alpha 0). let shows = |(x, k): (&f32, &f32)| if alpha == Some(b) { *x > 0.0 } else { *k > 0.0 }; - let shown: Vec = v.iter().zip(k).filter(|p| shows(*p)).map(|(x, _)| *x).collect(); - match (shown.is_empty(), alpha) { - (false, _) => mode_of(&shown), + // The scans below can take long on a big cell: Cancel is looked at as they go, + // and a cell stopped is left unwritten. + let mut shown: Vec = Vec::new(); + for p in v.iter().zip(k) { + if pace.stop(1) { + return; + } + if shows(p) { + shown.push(*p.0); + } + } + let found = match (shown.is_empty(), alpha) { + (false, _) => mode_of(&shown, pace), // No pixel that shows has a colour here: none is taken from one that // doesn't. - (true, Some(a)) if a != b => f32::NAN, - (true, _) => mode_of(v), - } + (true, Some(a)) if a != b => Some(f32::NAN), + (true, _) => mode_of(v, pace), + }; + let Some(found) = found else { return }; + found } else { mean_of(*sum, round) }; @@ -1075,11 +1088,16 @@ fn mean_of((sum, weight): (f64, f64), round: bool) -> f32 { /// The most frequent value of `v`; NaN when it is empty. Of the values tied, the one that reaches /// the top count first, `v` taken in its order (the cell's pixels, row by row), as GDAL's `mode` /// does: a cell of 3, 5, 5, 3 takes 5, one of 5, 3, 3, 5 takes 3. -fn mode_of(v: &[f32]) -> f32 { +/// +/// `None` when `pace` says to stop (Cancel was asked for) before it is found. +fn mode_of(v: &[f32], pace: &mut crate::control::Pace) -> Option { // Capped: a cell can take many pixels, and a few distinct values are the common case. let mut counts: HashMap = HashMap::with_capacity(v.len().min(256)); let (mut best, mut best_n) = (f32::NAN, 0usize); for &x in v { + if pace.stop(1) { + return None; + } // `+ 0.0` counts -0.0 and 0.0 as one value, as `==` does. let n = counts.entry((x + 0.0).to_bits()).or_insert(0); *n += 1; @@ -1087,7 +1105,7 @@ fn mode_of(v: &[f32]) -> f32 { (best, best_n) = (x, *n); } } - best + Some(best) } #[cfg(test)] @@ -1505,7 +1523,7 @@ mod tests { let mirrored = project(&utm(4, 4, classes, "UInt8"), &g, Method::Mode, "m".into()).unwrap(); assert_eq!(values(&mirrored)[0], Some(3.0)); // -0.0 and 0.0 are one value: the zero reaches two first, the 1 before it doesn't. - assert_eq!(mode_of(&[1.0, -0.0, 0.0]), 0.0); + assert_eq!(mode_of(&[1.0, -0.0, 0.0], &mut crate::control::Pace::default()), Some(0.0)); // A whole-number type's mean is rounded: (3 + 5 + 5 + 3) / 4 = 4, (7 + 7 + 7 + 2) / 4 = 5.75. let avg = project(&r, &g, Method::Average, "a".into()).unwrap(); assert_eq!(values(&avg)[..2], [Some(4.0), Some(6.0)]); @@ -1889,4 +1907,32 @@ mod tests { assert_eq!(out.value(0, 0, 0), None); assert_eq!(run.looked(), 3); } + + /// A cell of millions of pixels looks at Cancel while its mode is found too (the values are + /// scanned to drop the see-through ones, then counted): cancelled at the fourth look (the row's + /// was the first, the traversal's the second and third), it is left empty, not finished. + #[test] + fn a_cell_looks_at_cancel_while_its_mode_is_found() { + let n = 3000; + let gt = GeoTransform { origin_x: 0.0, origin_y: f64::from(n), pixel_width: 1.0, pixel_height: -1.0 }; + let r = + Raster::new("big", n, n, vec![vec![100.0; (n * n) as usize]], gt, Crs::Epsg(32613), None, ColorHint::Gray, "Float32").unwrap(); + let g = Grid { crs: r.crs, min_x: 0.0, max_y: f64::from(n), cell_x: f64::from(n), cell_y: f64::from(n), width: 1, height: 1 }; + let source = |x: f64, y: f64| Some((x, f64::from(n) - y)); + let run = crate::control::Control::cancelled_at_look(4); + let _installed = crate::control::install(Some(run.clone())); + let out = aggregated(Some(1), &r, &g, Canvas::of(&r, false), true, &source, "big".into()).unwrap(); + assert_eq!(out.value(0, 0, 0), None); + assert_eq!(run.looked(), 4); + } + + /// An eastward cell exactly half the globe wide across ±180° (corners at columns 7 and 3 of 8) + /// takes the pixels either side of the seam (columns 7, 0, 1, 2), not the ones west of its start. + #[test] + fn a_cell_exactly_half_the_globe_wide_across_the_antimeridian_wraps() { + let r = globe(360.0); + let folded = |x: f64, y: f64| Some((((x + 180.0).rem_euclid(360.0)) / 360.0 * 8.0, (90.0 - y) / 90.0)); + // Columns 7, 0, 1, 2: (3 + 1 + 100 + 100) / 4. + assert_eq!(one_cell(&r, 135.0, 315.0, false, &folded), Some(51.0)); + } } From 1607a76f15ab1468d8472d2040a29ec9f30cc64d Mon Sep 17 00:00:00 2001 From: Li-Sheng Chou <142213184+choupeanut@users.noreply.github.com> Date: Sun, 29 Nov 2026 04:24:31 +0800 Subject: [PATCH 08/13] analysis: keep the westward cell at the half-turn tie (#2918) --- crates/analysis/src/warp.rs | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/crates/analysis/src/warp.rs b/crates/analysis/src/warp.rs index 3c27ec65f4..1f2602b004 100644 --- a/crates/analysis/src/warp.rs +++ b/crates/analysis/src/warp.rs @@ -862,7 +862,7 @@ fn aggregated( let (west, east) = (r.transform.origin_x, r.transform.origin_x + w as f64 * r.transform.pixel_width); let wrap = (r.crs.is_geographic() && pixel > 0.0 && (west + 180.0).abs() <= pixel && (east - 180.0).abs() <= pixel).then_some(360.0 / pixel); - let each = Aggregate { r, canvas: &canvas, nearest, mode, round, wrap }; + let each = Aggregate { r, canvas: &canvas, nearest, mode, round, wrap, eastward: g.cell_x > 0.0 }; // A cell's work in `MIN_ROW_WORK`'s units (some 30 ns): its corners, and the pixels it takes // per band (the source's pixels, shared among the cells that cover them). let work = ow.saturating_mul(oh).saturating_add(w.saturating_mul(h)).saturating_mul(canvas.nb.saturating_add(1)); @@ -926,6 +926,9 @@ struct Aggregate<'a> { round: bool, /// One turn of longitude in columns, for a source that spans the globe, where a cell across ±180° wraps. wrap: Option, + /// Whether the output's columns run east (its cell width is positive): at a half-turn tie only an + /// eastward cell is read as across the seam. + eastward: bool, } impl Aggregate<'_> { @@ -957,8 +960,10 @@ impl Aggregate<'_> { }) { let shifted = quad.map(|p| if p.0 < turn / 2.0 { (p.0 + turn, p.1) } else { p }); let moved = shifted.iter().fold((f64::MAX, f64::MIN), |(lo, hi), p| (lo.min(p.0), hi.max(p.0))); - // (A cell of exactly half the image is as wide either way: the wrapped one is the cell.) - if moved.1 - moved.0 <= span.1 - span.0 { + // (A cell of exactly half the image is as wide either way: an eastward one is read as + // across the seam, a westward one, whose corners are the same, as the pixels it starts west over.) + let (shifted_width, width) = (moved.1 - moved.0, span.1 - span.0); + if shifted_width < width || (shifted_width == width && self.eastward) { (quad, span, wrapped) = (shifted, moved, true); } } @@ -1935,4 +1940,13 @@ mod tests { // Columns 7, 0, 1, 2: (3 + 1 + 100 + 100) / 4. assert_eq!(one_cell(&r, 135.0, 315.0, false, &folded), Some(51.0)); } + + /// A westward cell exactly half the globe wide (min_x 135, cell_x -180) has the same corners as the + /// eastward one, but takes the pixels west of its start (columns 3, 4, 5, 6), not the ones across the seam. + #[test] + fn a_westward_cell_exactly_half_the_globe_wide_keeps_its_own_pixels() { + let r = globe(360.0); + let folded = |x: f64, y: f64| Some((((x + 180.0).rem_euclid(360.0)) / 360.0 * 8.0, (90.0 - y) / 90.0)); + assert_eq!(one_cell(&r, 135.0, -45.0, false, &folded), Some(100.0)); + } } From d1a3c99806f30a57241be9295e36811858eea10a Mon Sep 17 00:00:00 2001 From: Li-Sheng Chou <142213184+choupeanut@users.noreply.github.com> Date: Sun, 29 Nov 2026 05:26:50 +0800 Subject: [PATCH 09/13] analysis: Project Raster moves the half-turn corner that ends a drop from the seam (#2918) --- crates/analysis/src/warp.rs | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/crates/analysis/src/warp.rs b/crates/analysis/src/warp.rs index 1f2602b004..111a1e5aeb 100644 --- a/crates/analysis/src/warp.rs +++ b/crates/analysis/src/warp.rs @@ -958,7 +958,16 @@ impl Aggregate<'_> { let whole = span.0 <= 0.0 && span.1 >= *turn; !whole && (drop(tl, tr) >= turn / 2.0 || drop(bl, br) >= turn / 2.0) }) { - let shifted = quad.map(|p| if p.0 < turn / 2.0 { (p.0 + turn, p.1) } else { p }); + // A corner at exactly half a turn moves too when it ends a drop of half the image or more + // (the east end of a cell from the seam at column 8 to column 4); one that starts the drop stays. + let half = turn / 2.0; + let ends = [false, drop(tl, tr) >= half, drop(bl, br) >= half, false]; + let mut shifted = quad; + for (p, end) in shifted.iter_mut().zip(ends) { + if p.0 < half || (p.0 == half && end) { + p.0 += turn; + } + } let moved = shifted.iter().fold((f64::MAX, f64::MIN), |(lo, hi), p| (lo.min(p.0), hi.max(p.0))); // (A cell of exactly half the image is as wide either way: an eastward one is read as // across the seam, a westward one, whose corners are the same, as the pixels it starts west over.) @@ -1949,4 +1958,20 @@ mod tests { let folded = |x: f64, y: f64| Some((((x + 180.0).rem_euclid(360.0)) / 360.0 * 8.0, (90.0 - y) / 90.0)); assert_eq!(one_cell(&r, 135.0, -45.0, false, &folded), Some(100.0)); } + + /// An eastward cell from 180° to 360° (corners at columns 8 and 4: a drop of exactly half the image) + /// takes columns 0 to 3, the same pixels as the folded cell from -180° to 0°; the corner at column 4 + /// ends the drop, so it moves a turn east. A cell whose column-4 corner starts the drop (to column 0) + /// keeps it, and reads columns 4 to 7. + #[test] + fn a_half_turn_cell_starting_at_180_takes_the_columns_east_of_the_seam() { + let r = globe(360.0); + let folded = |x: f64, y: f64| Some((((x + 180.0).rem_euclid(360.0)) / 360.0 * 8.0, (90.0 - y) / 90.0)); + let at_eight = |x: f64, y: f64| if x == 180.0 { Some((8.0, (90.0 - y) / 90.0)) } else { folded(x, y) }; + // Columns 0 to 3: (1 + 100 + 100 + 100) / 4. + assert_eq!(one_cell(&r, 180.0, 360.0, false, &at_eight), Some(75.25)); + assert_eq!(one_cell(&r, -180.0, 0.0, false, &folded), Some(75.25)); + // Columns 4 to 7, from 0° east to 180° (corners at 4 and 0, the seam crossed at the east end). + assert_eq!(one_cell(&r, 0.0, 180.0, false, &folded), Some(75.75)); + } } From aefa984b70844f5760a1828b5e825335f359dcf4 Mon Sep 17 00:00:00 2001 From: Li-Sheng Chou <142213184+choupeanut@users.noreply.github.com> Date: Sun, 29 Nov 2026 05:33:13 +0800 Subject: [PATCH 10/13] analysis: a Cancel during the last row stops the one-thread row loop too (#2918) --- crates/analysis/src/parallel.rs | 3 ++- crates/analysis/src/tools.rs | 10 ++++++---- crates/analysis/src/warp.rs | 24 ++++++++++++------------ 3 files changed, 20 insertions(+), 17 deletions(-) diff --git a/crates/analysis/src/parallel.rs b/crates/analysis/src/parallel.rs index 6a5ebbbef5..76aa7ff512 100644 --- a/crates/analysis/src/parallel.rs +++ b/crates/analysis/src/parallel.rs @@ -103,7 +103,8 @@ pub(crate) fn for_each_row( f(&mut s, i, row); control::advance(1); } - return Ok(()); + // A cancel raised during the last row left its cell unwritten: as after the threads join below. + return control::check(); } let run = control::current(); let plane = crate::convert::run_plane(); diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 388d79d493..170359ba54 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -12757,8 +12757,9 @@ mod tests { let _ = crate::run_with("kriging", &m, ¶ms, &counting); // Reading the rows and merging the points, each every 4,096: at least 20 looks before the grid. assert!(counting.looked() >= 20, "{}", counting.looked()); - // The reading's ten looks (rows 0, 4096, … 36864), the merge's ten, then the grid's few. - assert!(counting.looked() <= 25, "{}", counting.looked()); + // The reading's ten looks (rows 0, 4096, … 36864), the merge's ten, then the grid's few + // (and the one after its last row). + assert!(counting.looked() <= 26, "{}", counting.looked()); // Cancelled at the merge's fifth look, after 16,384 points merged: it stops there. (A look // added to reading the rows would move this.) let cancelled = crate::control::Control::cancelled_at_look(15); @@ -12780,8 +12781,9 @@ mod tests { let counting = crate::control::Control::cancelled_at_look(u64::MAX); let _ = crate::run_with("kriging", &m, ¶ms, &counting); // Ten looks each reading, projecting and merging, then the grid's few: the count is what - // shows the projection's ten (without them it is 20 and a few). - assert!((30..=35).contains(&counting.looked()), "{}", counting.looked()); + // shows the projection's ten (without them it is 20 and a few; the grid's include the look + // after its last row). + assert!((30..=36).contains(&counting.looked()), "{}", counting.looked()); // Cancelled at its 15th look (the projection's fifth): it stops there. let cancelled = crate::control::Control::cancelled_at_look(15); let e = crate::run_with("kriging", &m, ¶ms, &cancelled).unwrap_err(); diff --git a/crates/analysis/src/warp.rs b/crates/analysis/src/warp.rs index 111a1e5aeb..883a126092 100644 --- a/crates/analysis/src/warp.rs +++ b/crates/analysis/src/warp.rs @@ -1889,7 +1889,7 @@ mod tests { } /// A cell that takes millions of pixels looks at Cancel as it goes: one cancelled at its second - /// look (the row's was the first) is left empty, not computed. + /// look (the row's was the first) comes back Cancelled, not computed. The check after the last row is the third. #[test] fn a_cell_of_millions_of_pixels_looks_at_cancel() { let n = 2100; @@ -1900,13 +1900,13 @@ mod tests { let source = |x: f64, y: f64| Some((x, f64::from(n) - y)); let run = crate::control::Control::cancelled_at_look(2); let _installed = crate::control::install(Some(run.clone())); - let out = aggregated(Some(1), &r, &g, Canvas::of(&r, false), false, &source, "big".into()).unwrap(); - assert_eq!(out.value(0, 0, 0), None); - assert_eq!(run.looked(), 2); + let out = aggregated(Some(1), &r, &g, Canvas::of(&r, false), false, &source, "big".into()); + assert_eq!(out.unwrap_err(), crate::control::CANCELLED); + assert_eq!(run.looked(), 3); } /// A cell of several times the pixels between two looks looks within its rows: cancelled at the - /// third look (the row's was the first), it is left empty rather than finished. + /// third look (the row's was the first), it comes back Cancelled rather than finished. #[test] fn a_cell_looks_at_cancel_again_after_its_traversal_starts() { let n = 3000; @@ -1917,14 +1917,14 @@ mod tests { let source = |x: f64, y: f64| Some((x, f64::from(n) - y)); let run = crate::control::Control::cancelled_at_look(3); let _installed = crate::control::install(Some(run.clone())); - let out = aggregated(Some(1), &r, &g, Canvas::of(&r, false), false, &source, "big".into()).unwrap(); - assert_eq!(out.value(0, 0, 0), None); - assert_eq!(run.looked(), 3); + let out = aggregated(Some(1), &r, &g, Canvas::of(&r, false), false, &source, "big".into()); + assert_eq!(out.unwrap_err(), crate::control::CANCELLED); + assert_eq!(run.looked(), 4); } /// A cell of millions of pixels looks at Cancel while its mode is found too (the values are /// scanned to drop the see-through ones, then counted): cancelled at the fourth look (the row's - /// was the first, the traversal's the second and third), it is left empty, not finished. + /// was the first, the traversal's the second and third), it comes back Cancelled, not finished. #[test] fn a_cell_looks_at_cancel_while_its_mode_is_found() { let n = 3000; @@ -1935,9 +1935,9 @@ mod tests { let source = |x: f64, y: f64| Some((x, f64::from(n) - y)); let run = crate::control::Control::cancelled_at_look(4); let _installed = crate::control::install(Some(run.clone())); - let out = aggregated(Some(1), &r, &g, Canvas::of(&r, false), true, &source, "big".into()).unwrap(); - assert_eq!(out.value(0, 0, 0), None); - assert_eq!(run.looked(), 4); + let out = aggregated(Some(1), &r, &g, Canvas::of(&r, false), true, &source, "big".into()); + assert_eq!(out.unwrap_err(), crate::control::CANCELLED); + assert_eq!(run.looked(), 5); } /// An eastward cell exactly half the globe wide across ±180° (corners at columns 7 and 3 of 8) From fe47215ba6366e53d3ec7e18291eb642233003c4 Mon Sep 17 00:00:00 2001 From: Li-Sheng Chou <142213184+choupeanut@users.noreply.github.com> Date: Sun, 29 Nov 2026 06:26:17 +0800 Subject: [PATCH 11/13] analysis: shift the corner ending a half-turn drop whatever the source origin (#2918) --- crates/analysis/src/warp.rs | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/crates/analysis/src/warp.rs b/crates/analysis/src/warp.rs index 883a126092..9e3fa867c2 100644 --- a/crates/analysis/src/warp.rs +++ b/crates/analysis/src/warp.rs @@ -958,13 +958,14 @@ impl Aggregate<'_> { let whole = span.0 <= 0.0 && span.1 >= *turn; !whole && (drop(tl, tr) >= turn / 2.0 || drop(bl, br) >= turn / 2.0) }) { - // A corner at exactly half a turn moves too when it ends a drop of half the image or more - // (the east end of a cell from the seam at column 8 to column 4); one that starts the drop stays. + // A corner that ends a drop of half the image or more moves too, wherever the seam falls + // (the east end of a cell from the seam at column 8 to column 4, or 8.25 to 4.25 when the + // source's origin is not at -180°); one that starts the drop stays. let half = turn / 2.0; let ends = [false, drop(tl, tr) >= half, drop(bl, br) >= half, false]; let mut shifted = quad; for (p, end) in shifted.iter_mut().zip(ends) { - if p.0 < half || (p.0 == half && end) { + if p.0 < half || end { p.0 += turn; } } @@ -1974,4 +1975,18 @@ mod tests { // Columns 4 to 7, from 0° east to 180° (corners at 4 and 0, the seam crossed at the east end). assert_eq!(one_cell(&r, 0.0, 180.0, false, &folded), Some(75.75)); } + + /// The same half-turn cell over a source whose first column starts at -191.25° (a quarter pixel + /// short of the seam each side): the seam is at column 0.25, so the cell from 180° to 360° has corners + /// at columns 8.25 and 4.25, and still takes columns 0 to 3, not 4 to 7. + #[test] + fn a_half_turn_cell_over_a_shifted_origin_takes_the_columns_east_of_the_seam() { + let mut r = globe(360.0); + r.transform.origin_x = -191.25; + let folded = |x: f64, y: f64| Some((((x + 191.25).rem_euclid(360.0)) / 45.0, (90.0 - y) / 90.0)); + // 180° is kept at the east end of the image (column 8.25); 360° folds to 0° (column 4.25). + let at_eight = |x: f64, y: f64| if x == 180.0 { Some((8.25, (90.0 - y) / 90.0)) } else { folded(x, y) }; + // Columns 0 to 3: (1 + 100 + 100 + 100) / 4. + assert_eq!(one_cell(&r, 180.0, 360.0, false, &at_eight), Some(75.25)); + } } From 349890965d630da6f14ab130f5da6e229aadc531 Mon Sep 17 00:00:00 2001 From: Li-Sheng Chou <142213184+choupeanut@users.noreply.github.com> Date: Sun, 29 Nov 2026 10:26:32 +0800 Subject: [PATCH 12/13] analysis: whole-image wrap exception compares against image width (#2918) --- crates/analysis/src/warp.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/crates/analysis/src/warp.rs b/crates/analysis/src/warp.rs index 9e3fa867c2..1292505417 100644 --- a/crates/analysis/src/warp.rs +++ b/crates/analysis/src/warp.rs @@ -955,7 +955,7 @@ impl Aggregate<'_> { let mut wrapped = false; let drop = |from: &(f64, f64), to: &(f64, f64)| from.0 - to.0; if let Some(turn) = self.wrap.filter(|turn| { - let whole = span.0 <= 0.0 && span.1 >= *turn; + let whole = span.0 <= 0.0 && span.1 >= w as f64; !whole && (drop(tl, tr) >= turn / 2.0 || drop(bl, br) >= turn / 2.0) }) { // A corner that ends a drop of half the image or more moves too, wherever the seam falls @@ -1951,6 +1951,17 @@ mod tests { assert_eq!(one_cell(&r, 135.0, 315.0, false, &folded), Some(51.0)); } + /// A source short of a whole turn (8 columns of 40° end at 140°, one pixel short of 180°, so a turn is + /// 9 columns) still takes the whole image for a westward cell from its east edge to -180° (corners at + /// columns 8 and 0): the span is compared with the image's width, not the turn. + #[test] + fn a_westward_cell_over_the_whole_of_a_short_source_takes_every_pixel() { + let r = globe(320.0); + let plain = |x: f64, y: f64| Some(((x + 180.0) / 40.0, (90.0 - y) / 90.0)); + // Every column: (1 + 6 × 100 + 3) / 8. + assert_eq!(one_cell(&r, 140.0, -180.0, false, &plain), Some(75.5)); + } + /// A westward cell exactly half the globe wide (min_x 135, cell_x -180) has the same corners as the /// eastward one, but takes the pixels west of its start (columns 3, 4, 5, 6), not the ones across the seam. #[test] From e6c1160b11dba3072d739c0823e6fc0a06da983b Mon Sep 17 00:00:00 2001 From: Li-Sheng Chou <142213184+choupeanut@users.noreply.github.com> Date: Sun, 29 Nov 2026 11:00:26 +0800 Subject: [PATCH 13/13] analysis: whole-image wrap exception applies to a westward cell only (#2918) --- crates/analysis/src/warp.rs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/crates/analysis/src/warp.rs b/crates/analysis/src/warp.rs index 1292505417..31af58ea23 100644 --- a/crates/analysis/src/warp.rs +++ b/crates/analysis/src/warp.rs @@ -948,14 +948,16 @@ impl Aggregate<'_> { // and its east corners near the west end: going east along an edge, the column drops by // half the image or more. The pixels between are the far side of the globe. Its // corners in the west go on past the east edge instead (by one turn of longitude, not - // always the image's width), and the pixels past it are the west's again. A cell wide enough to take in the whole image, or one whose - // columns grow eastward as they do in an ordinary cell, is not across the seam. (An + // always the image's width), and the pixels past it are the west's again. A westward cell + // that takes in the whole image (its span reaches from column 0 to the image's width, not a + // turn) is not across the seam, nor is a cell whose columns grow eastward as they do in + // an ordinary one. (An // output that runs east to west, or a cell over half the globe wide in one, cannot be // told from one across it and is read as before.) let mut wrapped = false; let drop = |from: &(f64, f64), to: &(f64, f64)| from.0 - to.0; if let Some(turn) = self.wrap.filter(|turn| { - let whole = span.0 <= 0.0 && span.1 >= w as f64; + let whole = !self.eastward && span.0 <= 0.0 && span.1 >= w as f64; !whole && (drop(tl, tr) >= turn / 2.0 || drop(bl, br) >= turn / 2.0) }) { // A corner that ends a drop of half the image or more moves too, wherever the seam falls @@ -1960,6 +1962,10 @@ mod tests { let plain = |x: f64, y: f64| Some(((x + 180.0) / 40.0, (90.0 - y) / 90.0)); // Every column: (1 + 6 × 100 + 3) / 8. assert_eq!(one_cell(&r, 140.0, -180.0, false, &plain), Some(75.5)); + // An eastward cell from 140° to 180° has the same corner columns (8 and 0) but is across the seam, in + // the part of the globe the source doesn't cover: no value, not every pixel. + let folded = |x: f64, y: f64| Some((((x + 180.0).rem_euclid(360.0)) / 40.0, (90.0 - y) / 90.0)); + assert_eq!(one_cell(&r, 140.0, 180.0, false, &folded), None); } /// A westward cell exactly half the globe wide (min_x 135, cell_x -180) has the same corners as the