From 1c4f8b8145ed601e40f21b400e655301ca17aba2 Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 25 Nov 2026 09:01:23 -0500 Subject: [PATCH 1/7] fix(geom,analysis,render): fix NaN/overflow panics, hole bridging, antimeridian profile, and cancel checks Fixes nine correctness, crash, and responsiveness bugs across geom, analysis, and render: - render::effects::extrude_tilted: skip non-finite vertices and depths and sort with total_cmp to avoid driftsort panics on NaN. - render::gradient_fill::edt_1d: square indices in f64 before dividing to avoid 32-bit usize overflow on wasm32 and f32 precision loss past 65,536. - analysis::topology::self_crossing: filter non-finite segments out of sweep order (preserving original segment indices for adjacency) and sort with total_cmp. - analysis::neural: accumulate standardization mean and variance in f64, check scaling finiteness before returning a trained model, mark non-finite softmax inputs as NaN, and add Mlp::predict_checked so classify_on leaves overflowing pixels as nodata. - geom::triangulate: verify local interior wedges at both bridge endpoints and reject bridges crossing edges, passing through intermediate vertices, or overlapping collinear edges. - analysis::network::random_points: skip empty or non-finite polygon extents and check control::cancelled inside the rejection loop. - analysis::density::silverman_bandwidth: filter to finite positive-weight points matching accumulate_density and sort distances with total_cmp. - analysis::rasterops::profile: guard non-finite path coordinates and totals, and unwrap longitude deltas across the antimeridian into [-180, 180]. - analysis::attribute_join::join_field: report progress and check control::check periodically across indexing and join loops. --- crates/analysis/src/attribute_join.rs | 53 +++++++++++- crates/analysis/src/density.rs | 78 ++++++++++++------ crates/analysis/src/network.rs | 59 +++++++++++++- crates/analysis/src/neural.rs | 102 +++++++++++++++++++---- crates/analysis/src/rasterops.rs | 59 +++++++++++++- crates/analysis/src/topology.rs | 37 ++++++++- crates/geom/src/triangulate.rs | 113 +++++++++++++++++++++++++- crates/render/src/effects.rs | 68 +++++++++++++++- crates/render/src/gradient_fill.rs | 19 ++++- 9 files changed, 530 insertions(+), 58 deletions(-) diff --git a/crates/analysis/src/attribute_join.rs b/crates/analysis/src/attribute_join.rs index dc914abca1..9576d1795b 100644 --- a/crates/analysis/src/attribute_join.rs +++ b/crates/analysis/src/attribute_join.rs @@ -278,10 +278,19 @@ pub fn join_field(target: &Dataset, source: &Dataset, opts: &JoinFieldOptions<'_ } // 5. Index source records: Map JoinKey -> source feature index - let mut source_index: HashMap = HashMap::with_capacity(source.features.len()); + let source_len = source.features.len(); + let extra_len = if comparison == KeyComparison::NumberAsText { source_len } else { 0 }; + let target_len = target.features.len(); + crate::control::begin(source_len.saturating_add(extra_len).saturating_add(target_len)); + + let mut source_index: HashMap = HashMap::with_capacity(source_len); let mut duplicate_count = 0usize; for (s_idx, s_feat) in source.features.iter().enumerate() { + if s_idx & 1023 == 0 { + crate::control::check()?; + crate::control::reached(s_idx); + } let val = s_feat.attrs.get(source_key_idx).unwrap_or(&Value::Null); let Some(key) = JoinKey::from_value_compared(val, comparison) else { // Null or non-finite keys in source cannot match @@ -312,6 +321,10 @@ pub fn join_field(target: &Dataset, source: &Dataset, opts: &JoinFieldOptions<'_ let mut zero_padded_sources: HashMap = HashMap::new(); if comparison == KeyComparison::NumberAsText { for (s_idx, s_feat) in source.features.iter().enumerate() { + if s_idx & 1023 == 0 { + crate::control::check()?; + crate::control::reached(source_len.saturating_add(s_idx)); + } if let Some(Value::Text(text)) = s_feat.attrs.get(source_key_idx) && let Some(digits) = without_leading_zeros(text) { @@ -324,11 +337,14 @@ pub fn join_field(target: &Dataset, source: &Dataset, opts: &JoinFieldOptions<'_ let mut leading_zero_example = None; // 6. Join records into target - let target_len = target.features.len(); let mut matched_records = 0usize; let mut out_features = Vec::with_capacity(target_len); - for t_feat in &target.features { + for (t_idx, t_feat) in (0..target_len).zip(&target.features) { + if t_idx & 1023 == 0 { + crate::control::check()?; + crate::control::reached(source_len.saturating_add(extra_len).saturating_add(t_idx)); + } if t_feat.attrs.len() > target.fields.len() { return Err(format!( "target feature {} has {} attributes, exceeding schema field count {}", @@ -378,6 +394,9 @@ pub fn join_field(target: &Dataset, source: &Dataset, opts: &JoinFieldOptions<'_ out_features.push(rustgis_data::Feature { id: t_feat.id, geometry: t_feat.geometry.clone(), attrs: new_attrs }); } + crate::control::check()?; + crate::control::finish(); + out.features = out_features.into(); let report = JoinFieldReport { @@ -1311,4 +1330,32 @@ mod tests { assert_eq!(out_col.fields[2].alias, None); assert_eq!(out_col.fields[2].display(), "cost_2"); } + + #[test] + fn join_field_respects_cancel_and_reports_progress() { + let target_rows: Vec> = (0..2500).map(|i| vec![Value::Int(i), Value::Text(format!("t{i}"))]).collect(); + let source_rows: Vec> = (0..2500).map(|i| vec![Value::Int(i), Value::Float(i as f64)]).collect(); + let target = make_table("target", vec![("id", FieldType::Integer), ("name", FieldType::Text)], target_rows); + let source = make_table("source", vec![("id", FieldType::Integer), ("val", FieldType::Double)], source_rows); + let opts = JoinFieldOptions { + target_field: "id", + join_field: "id", + fields_to_transfer: None, + prefix: "", + duplicate_strategy: DuplicateStrategy::First, + output_name: "joined".into(), + }; + + let cancel_ctrl = crate::control::Control::cancelled_once_started(); + let err = crate::run_under("Join Field", &cancel_ctrl, || join_field(&target, &source, &opts)).unwrap_err(); + assert!(err.contains("cancelled"), "expected cancellation error, got {err}"); + assert!(cancel_ctrl.looked() >= 1); + + let prog_ctrl = crate::control::Control::new(); + let _installed = crate::control::install(Some(prog_ctrl.clone())); + let (_, rep) = join_field(&target, &source, &opts).unwrap(); + assert_eq!(rep.matched_records, 2500); + let (done, total) = prog_ctrl.progress().expect("join_field should report progress"); + assert!(total > 0 && done == total, "done={done} total={total}"); + } } diff --git a/crates/analysis/src/density.rs b/crates/analysis/src/density.rs index 32bc049017..c6549f7917 100644 --- a/crates/analysis/src/density.rs +++ b/crates/analysis/src/density.rs @@ -70,37 +70,29 @@ const DEFAULT_GRID_STEPS: f64 = 250.0; /// small samples or identical coordinates (span / 30.0 when extent > 0, or 1000.0 coordinate-space /// units for single or coincident points). pub fn silverman_bandwidth(points: &[(Coord, f64)], extent: &Extent) -> f64 { - let n = points.len(); - if n < 2 { + let fallback = || { let span = extent.width().max(extent.height()); - return if span > 1e-4 { span / 30.0 } else { 1000.0 }; + if span.is_finite() && span > 1e-4 { (span / 30.0).max(1e-4) } else { 1000.0 } + }; + + let valid: Vec<(Coord, f64)> = points.iter().copied().filter(|(p, w)| p.is_finite() && w.is_finite() && *w > 0.0).collect(); + let n = valid.len(); + if n < 2 { + return fallback(); } - let (sum_x, sum_y, sum_w) = points.iter().fold((0.0, 0.0, 0.0), |(sx, sy, sw), (p, w)| { - let weight = if w.is_finite() && *w > 0.0 { *w } else { 1.0 }; - (sx + p.x * weight, sy + p.y * weight, sw + weight) - }); - if sum_w <= 0.0 || !sum_w.is_finite() { - let span = extent.width().max(extent.height()); - return if span.is_finite() && span > 1e-4 { (span / 30.0).max(1e-4) } else { 1000.0 }; + let (sum_x, sum_y, sum_w) = valid.iter().fold((0.0, 0.0, 0.0), |(sx, sy, sw), (p, w)| (sx + p.x * w, sy + p.y * w, sw + w)); + if sum_w <= 0.0 || !sum_w.is_finite() || !sum_x.is_finite() || !sum_y.is_finite() { + return fallback(); } let mean_x = sum_x / sum_w; let mean_y = sum_y / sum_w; - let sum_sq_dist = points.iter().fold(0.0, |acc, (p, w)| { - let weight = if w.is_finite() && *w > 0.0 { *w } else { 1.0 }; - acc + weight * ((p.x - mean_x).powi(2) + (p.y - mean_y).powi(2)) - }); + let sum_sq_dist = valid.iter().fold(0.0, |acc, (p, w)| acc + w * ((p.x - mean_x).powi(2) + (p.y - mean_y).powi(2))); let std_dist = (sum_sq_dist / sum_w).sqrt(); - let mut dists: Vec<(f64, f64)> = points - .iter() - .map(|(p, w)| { - let weight = if w.is_finite() && *w > 0.0 { *w } else { 1.0 }; - (((p.x - mean_x).powi(2) + (p.y - mean_y).powi(2)).sqrt(), weight) - }) - .collect(); - dists.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal)); + let mut dists: Vec<(f64, f64)> = valid.iter().map(|(p, w)| (((p.x - mean_x).powi(2) + (p.y - mean_y).powi(2)).sqrt(), *w)).collect(); + dists.sort_by(|a, b| a.0.total_cmp(&b.0)); let half_w = sum_w * 0.5; let mut cum_w = 0.0; @@ -117,7 +109,7 @@ pub fn silverman_bandwidth(points: &[(Coord, f64)], extent: &Extent) -> f64 { let a = (1.0 / 2.0f64.ln()).sqrt(); let term = std_dist.min(a * median_dist); - if term > 1e-6 { + if term.is_finite() && term > 1e-6 { let n_factor = (n as f64).powf(-0.2); let h = 0.9 * term * n_factor; if h.is_finite() && h > 1e-4 { @@ -125,9 +117,7 @@ pub fn silverman_bandwidth(points: &[(Coord, f64)], extent: &Extent) -> f64 { } } - // Fallback: fraction of extent or fixed distance - let span = extent.width().max(extent.height()); - if span.is_finite() && span > 1e-4 { (span / 30.0).max(1e-4) } else { 1000.0 } + fallback() } /// Automatically calculates cell size so the grid spans approximately 250 cells across its maximum dimension. @@ -705,4 +695,40 @@ mod tests { assert_eq!(e, crate::control::CANCELLED, "{threads}"); } } + + #[test] + fn silverman_bandwidth_matches_valid_points_and_handles_non_finite() { + let base = vec![ + (Coord::new(0.0, 0.0), 1.0), + (Coord::new(100.0, 0.0), 2.0), + (Coord::new(0.0, 100.0), 1.5), + (Coord::new(100.0, 100.0), 1.0), + (Coord::new(50.0, 50.0), 3.0), + ]; + let ext = Extent::new(0.0, 0.0, 100.0, 100.0); + let h_base = silverman_bandwidth(&base, &ext); + + let mut noisy = base.clone(); + for i in 0..30 { + match i % 5 { + 0 => noisy.push((Coord::new(f64::NAN, 10.0), 1.0)), + 1 => noisy.push((Coord::new(f64::INFINITY, 10.0), 1.0)), + 2 => noisy.push((Coord::new(25.0, 25.0), 0.0)), + 3 => noisy.push((Coord::new(75.0, 75.0), -2.0)), + _ => noisy.push((Coord::new(50.0, 50.0), f64::NAN)), + } + } + let h_noisy = silverman_bandwidth(&noisy, &ext); + assert_eq!(h_noisy, h_base, "invalid and non-positive points must not change bandwidth"); + + // Fewer than 2 valid points falls back to extent scaling. + let one_valid = vec![ + (Coord::new(50.0, 50.0), 1.0), + (Coord::new(0.0, 0.0), 0.0), + (Coord::new(100.0, 100.0), -1.0), + (Coord::new(f64::NAN, 0.0), 1.0), + ]; + let h_one = silverman_bandwidth(&one_valid, &ext); + assert!((h_one - 100.0 / 30.0).abs() < 1e-12, "got {h_one}"); + } } diff --git a/crates/analysis/src/network.rs b/crates/analysis/src/network.rs index 907f4b7150..481cdc0c74 100644 --- a/crates/analysis/src/network.rs +++ b/crates/analysis/src/network.rs @@ -785,17 +785,32 @@ pub fn random_points(ds: &Dataset, rows: &[usize], per: usize, seed: u64) -> Vec }; let mut out = Vec::new(); crate::control::begin(rows.len()); - for (i, r) in rows.iter().enumerate() { + 'rows: for (i, r) in rows.iter().enumerate() { if crate::control::cancelled() { break; } crate::control::reached(i); let Some(Geometry::Polygon(polys)) = ds.features.get(*r).and_then(|f| f.geometry.as_ref()) else { continue }; let e = ds.features.get(*r).and_then(|f| f.geometry.as_ref()).map(|g| g.extent()).unwrap_or_default(); + if e.is_empty() + || !e.min_x.is_finite() + || !e.max_x.is_finite() + || !e.min_y.is_finite() + || !e.max_y.is_finite() + || !e.width().is_finite() + || !e.height().is_finite() + || e.width() <= 0.0 + || e.height() <= 0.0 + { + continue; + } let mut placed = 0; let mut tries = 0usize; while placed < per && tries < per.saturating_mul(200) && budget > 0 && out.len() < MAX_POINTS { tries += 1; + if tries & 1023 == 0 && crate::control::cancelled() { + break 'rows; + } budget -= 1; let c = Coord::new(e.min_x + rnd() * e.width(), e.min_y + rnd() * e.height()); if polys.iter().any(|rings| rustgis_data::geometry::polygon_contains(rings, c)) { @@ -1900,4 +1915,46 @@ mod tests { ds.push(Some(Geometry::Point(point)), vec![]); assert!(within(&ds, &[0], center, 100_000.0).is_empty()); } + + #[test] + fn random_points_skips_empty_extents_and_checks_cancel_inside_loop() { + // 1,000 empty polygons (each would burn 250 * 200 = 50,000 tries = 50,000,000 total) + // followed by one valid unit square: the empty polygons must not exhaust the try budget. + let mut ds = Dataset::new("p", GeometryType::Polygon, vec![]); + for _ in 0..1000 { + ds.push(Some(Geometry::Polygon(vec![])), vec![]); + } + ds.push( + Some(Geometry::Polygon(vec![vec![vec![ + Coord::new(0.0, 0.0), + Coord::new(1.0, 0.0), + Coord::new(1.0, 1.0), + Coord::new(0.0, 1.0), + Coord::new(0.0, 0.0), + ]]])), + vec![], + ); + let rows: Vec = (0..ds.features.len()).collect(); + let pts = random_points(&ds, &rows, 250, 7); + assert_eq!(pts.len(), 250); + assert!(pts.iter().all(|(r, _)| *r == 1000)); + + // A very thin diagonal sliver polygon forces many rejection tries; cancellation must be + // observed inside the rejection loop rather than only between features. + let mut sliver = Dataset::new("sliver", GeometryType::Polygon, vec![]); + sliver.push( + Some(Geometry::Polygon(vec![vec![vec![ + Coord::new(0.0, 0.0), + Coord::new(1.0, 1.0), + Coord::new(1.0, 1.0 - 1e-6), + Coord::new(0.0, 0.0), + ]]])), + vec![], + ); + let ctrl = crate::control::Control::cancelled_at_look(2); + let _installed = crate::control::install(Some(ctrl.clone())); + let got = random_points(&sliver, &[0], 10_000, 7); + assert!(ctrl.looked() >= 2, "expected cancel check inside rejection loop, looked {}", ctrl.looked()); + assert!(got.len() < 10_000); + } } diff --git a/crates/analysis/src/neural.rs b/crates/analysis/src/neural.rs index 74488112b3..8656eeff29 100644 --- a/crates/analysis/src/neural.rs +++ b/crates/analysis/src/neural.rs @@ -106,22 +106,46 @@ impl Mlp { a } - /// The most likely class (0-based) and its probability. - pub fn predict(&self, x: &[f32]) -> (usize, f32) { + /// The most likely class (0-based) and its probability, or `None` when the pixel's values + /// overflowed the network and produced non-finite probabilities. + pub fn predict_checked(&self, x: &[f32]) -> Option<(usize, f32)> { let p = self.probabilities(x); - p.iter().enumerate().fold((0, f32::MIN), |best, (i, v)| if *v > best.1 { (i, *v) } else { best }) + if p.is_empty() || !p.iter().all(|v| v.is_finite()) { + return None; + } + let mut best = (0, f32::NEG_INFINITY); + for (i, &v) in p.iter().enumerate() { + if v > best.1 { + best = (i, v); + } + } + Some(best) + } + + /// The most likely class (0-based) and its probability (`(0, NaN)` when non-finite). + pub fn predict(&self, x: &[f32]) -> (usize, f32) { + self.predict_checked(x).unwrap_or((0, f32::NAN)) } } fn softmax(a: &mut [f32]) { - let m = a.iter().copied().fold(f32::MIN, f32::max); + if a.is_empty() { + return; + } + if a.iter().any(|v| !v.is_finite()) { + a.fill(f32::NAN); + return; + } + let m = a.iter().copied().fold(f32::NEG_INFINITY, f32::max); let mut sum = 0.0; for v in a.iter_mut() { *v = (*v - m).exp(); sum += *v; } - if sum > 0.0 { + if sum > 0.0 && sum.is_finite() { a.iter_mut().for_each(|v| *v /= sum); + } else { + a.fill(f32::NAN); } } @@ -306,17 +330,25 @@ pub fn train( if samples.len() < 2 * k { return Err("too few training pixels: draw larger training polygons".into()); } - // Input scaling from the samples. - let mut mean = vec![0.0f32; n_in]; - let mut std = vec![0.0f32; n_in]; + // Input scaling from the samples, accumulated in f64 so large finite f32 values don't overflow. + let mut mean64 = vec![0.0f64; n_in]; + let mut var64 = vec![0.0f64; n_in]; + let n_samples = samples.len() as f64; for (x, _) in &samples { - mean.iter_mut().zip(x).for_each(|(m, v)| *m += v); + mean64.iter_mut().zip(x).for_each(|(m, v)| *m += f64::from(*v)); } - mean.iter_mut().for_each(|m| *m /= samples.len() as f32); + mean64.iter_mut().for_each(|m| *m /= n_samples); for (x, _) in &samples { - std.iter_mut().zip(x.iter().zip(&mean)).for_each(|(s, (v, m))| *s += (v - m) * (v - m)); + var64.iter_mut().zip(x.iter().zip(&mean64)).for_each(|(s, (v, m))| { + let d = f64::from(*v) - m; + *s += d * d; + }); + } + let mean: Vec = mean64.iter().map(|m| *m as f32).collect(); + let std: Vec = var64.iter().map(|s| ((s / n_samples).sqrt() as f32).max(1e-6)).collect(); + if !mean.iter().chain(&std).all(|v| v.is_finite()) || std.iter().any(|s| *s <= 0.0) { + return Err("training values are out of range to scale".into()); } - std.iter_mut().for_each(|s| *s = (*s / samples.len() as f32).sqrt().max(1e-6)); // Layers, He-initialised. let mut rng = Rng(0x9E37_79B9_7F4A_7C15); let mut sizes = vec![n_in]; @@ -443,11 +475,12 @@ pub fn train( } // A cancelled run makes no model: the accuracy check on held-back samples can take long too. crate::control::check()?; - if !layers.iter().all(|l| l.w.iter().chain(&l.b).all(|v| v.is_finite())) { + if !mean.iter().chain(&std).all(|v| v.is_finite()) || !layers.iter().all(|l| l.w.iter().chain(&l.b).all(|v| v.is_finite())) { return Err("training diverged; try fewer epochs or smaller layers".into()); } let model = Mlp { bands: bands.to_vec(), mean, std, layers, classes }; - let correct = test.iter().filter(|&&i| samples.get(i).is_some_and(|(x, c)| model.predict(x).0 == *c)).count(); + let correct = + test.iter().filter(|&&i| samples.get(i).is_some_and(|(x, c)| model.predict_checked(x).is_some_and(|(p, _)| p == *c))).count(); let accuracy = if test.is_empty() { 1.0 } else { correct as f64 / test.len() as f64 }; Ok(Trained { model, accuracy, samples: samples.len(), epochs, epochs_asked, fitted: fit.len(), training }) } @@ -503,8 +536,7 @@ fn classify_on(r: &Raster, model: &Mlp, nodata: f32, threads: Option) -> None => false, } }); - if ok { - let (c, p) = model.predict(x); + if ok && let Some((c, p)) = model.predict_checked(x) { (*c_out, *p_out) = ((c + 1) as f32, p); } } @@ -657,4 +689,42 @@ mod tests { assert_eq!((whole.fitted, whole.epochs, whole.limited()), (whole.training, 3, None)); assert!(train(&[0, 1], vec!["a".into(), "b".into()], &samples[..2], &[4], 1).is_err(), "too few"); } + + #[test] + fn large_scale_training_and_overflowing_inference_stay_finite() { + use rustgis_data::raster::{ColorHint, Crs, GeoTransform}; + // Large finite f32 samples overflow `(v - m) * (v - m)` if variance is summed in f32. + let mut samples = Vec::new(); + for i in 0..40 { + let class = usize::from(i >= 20); + let base = if class == 0 { 1.0e25f32 } else { 2.0e25f32 }; + samples.push((vec![base + (i % 5) as f32 * 1.0e23f32], class)); + } + let trained = train(&[0], vec!["low".into(), "high".into()], &samples, &[4], 30).unwrap(); + trained.model.validate().unwrap(); + assert!(trained.model.mean.iter().all(|v| v.is_finite())); + assert!(trained.model.std.iter().all(|v| v.is_finite() && *v > 0.0)); + assert_eq!(trained.model.predict(&[1.0e25]).0, 0); + assert_eq!(trained.model.predict(&[2.0e25]).0, 1); + + // An extreme finite pixel overflowing logits to +/-inf must stay nodata rather than + // writing a bogus class or f32::MIN probability. + let model = Mlp { + bands: vec![0], + mean: vec![0.0], + std: vec![1.0], + layers: vec![Dense { inp: 1, out: 2, w: vec![10.0, -10.0], b: vec![0.0, 0.0] }], + classes: vec!["a".into(), "b".into()], + }; + model.validate().unwrap(); + let gt = GeoTransform { origin_x: 0.0, origin_y: 1.0, pixel_width: 1.0, pixel_height: -1.0 }; + let r = Raster::new("img", 2, 1, vec![vec![1.0, 1.0e38]], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + let (class, prob) = classify(&r, &model, -1.0).unwrap(); + assert_eq!(model.predict_checked(&[1.0e38]), None); + assert!(model.predict(&[1.0e38]).1.is_nan()); + assert_eq!(class[0], 1.0); + assert!(prob[0] > 0.9 && prob[0].is_finite()); + assert_eq!(class[1], -1.0, "overflowing pixel stays nodata, got class {} prob {}", class[1], prob[1]); + assert_eq!(prob[1], -1.0, "overflowing pixel stays nodata, got prob {}", prob[1]); + } } diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index 1fab346287..6a37c32739 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -439,6 +439,9 @@ pub fn elevation_at(r: &Raster, b: usize, ll: Coord) -> Option { /// An elevation profile along a path: (distance from the start in metres, point, elevation). pub fn profile(r: &Raster, b: usize, path: &[Coord], samples: usize) -> Vec<(f64, Coord, Option)> { let samples = samples.clamp(2, 10_000); + if path.iter().any(|p| !p.is_finite()) { + return Vec::new(); + } let legs: Vec = path .windows(2) .map(|w| match w { @@ -447,7 +450,7 @@ pub fn profile(r: &Raster, b: usize, path: &[Coord], samples: usize) -> Vec<(f64 }) .collect(); let total: f64 = legs.iter().sum(); - if total <= 0.0 { + if !(total.is_finite() && total > 0.0) { return path.first().map(|p| vec![(0.0, *p, elevation_at(r, b, *p))]).unwrap_or_default(); } // Samples are in order along the path, so the legs are walked once. @@ -462,7 +465,21 @@ pub fn profile(r: &Raster, b: usize, path: &[Coord], samples: usize) -> Vec<(f64 let len = legs.get(li).copied().unwrap_or(0.0); let t = if len > 0.0 { ((d - acc) / len).clamp(0.0, 1.0) } else { 0.0 }; let at = match (path.get(li), path.get(li + 1)) { - (Some(a), Some(c)) => Coord::new(a.x + (c.x - a.x) * t, a.y + (c.y - a.y) * t), + (Some(a), Some(c)) => { + let mut dx = c.x - a.x; + if dx > 180.0 { + dx -= 360.0; + } else if dx < -180.0 { + dx += 360.0; + } + let mut x = a.x + dx * t; + if x > 180.0 { + x -= 360.0; + } else if x < -180.0 { + x += 360.0; + } + Coord::new(x, a.y + (c.y - a.y) * t) + } _ => path.last().copied().unwrap_or_default(), }; out.push((d, at, elevation_at(r, b, at))); @@ -3255,4 +3272,42 @@ mod tests { assert_eq!(got, Some((vec![1.0], inside)), "{x0} {x1} {y0} {y1}"); } } + + #[test] + fn profile_guards_nan_and_interpolates_across_antimeridian() { + // Global 1-degree LonLat raster: elevation 100 near +/-180 deg, 0 elsewhere. + let (w, h) = (360u32, 10u32); + let mut data = vec![0.0f32; (w * h) as usize]; + for row in 0..h { + for col in 0..w { + let lon = -180.0 + col as f64 + 0.5; + if lon.abs() >= 178.0 { + data[(row * w + col) as usize] = 100.0; + } + } + } + let gt = GeoTransform { origin_x: -180.0, origin_y: 5.0, pixel_width: 1.0, pixel_height: -1.0 }; + let r = Raster::new("dem", w, h, vec![data], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + + // A path with a NaN coordinate must not emit NaN samples. + let nan_prof = profile(&r, 0, &[Coord::new(0.0, 0.0), Coord::new(f64::NAN, 0.0)], 500); + assert!(nan_prof.is_empty(), "expected empty profile for NaN path, got {} samples", nan_prof.len()); + + // Crossing the antimeridian from 179 to -179 must interpolate along the 2-degree arc + // across +/-180 rather than sweeping across longitude 0. + let prof = profile(&r, 0, &[Coord::new(179.0, 0.0), Coord::new(-179.0, 0.0)], 20); + assert_eq!(prof.len(), 20); + for &(d, c, z) in &prof { + assert!(d.is_finite() && c.is_finite()); + assert!(c.x.abs() >= 178.999 && c.x.abs() <= 180.0, "sample swept away from antimeridian: {c:?}"); + assert_eq!(z, Some(100.0), "expected antimeridian elevation at {c:?}"); + } + // Westbound across the antimeridian (-179 to 179) also stays on the short arc. + let prof_west = profile(&r, 0, &[Coord::new(-179.0, 0.0), Coord::new(179.0, 0.0)], 21); + assert_eq!(prof_west.len(), 21); + for &(d, c, _) in &prof_west { + assert!(d.is_finite() && c.is_finite()); + assert!(c.x.abs() >= 178.999 && c.x.abs() <= 180.0, "westbound sample swept away: {c:?}"); + } + } } diff --git a/crates/analysis/src/topology.rs b/crates/analysis/src/topology.rs index 873e45b5c8..f17007fafb 100644 --- a/crates/analysis/src/topology.rs +++ b/crates/analysis/src/topology.rs @@ -219,10 +219,10 @@ fn self_crossing(path: &[Coord], closed: bool) -> Result, Coord> { let n = segs.len(); let minx = |s: &(Coord, Coord)| s.0.x.min(s.1.x); let maxx = |s: &(Coord, Coord)| s.0.x.max(s.1.x); - let mut order: Vec = (0..n).collect(); + let mut order: Vec = (0..n).filter(|&i| segs.get(i).is_some_and(|s| s.0.is_finite() && s.1.is_finite())).collect(); order.sort_by(|a, b| { let (sa, sb) = (segs.get(*a).map_or(0.0, minx), segs.get(*b).map_or(0.0, minx)); - sa.partial_cmp(&sb).unwrap_or(std::cmp::Ordering::Equal) + sa.total_cmp(&sb) }); let mut work = 0usize; for (k, &i) in order.iter().enumerate() { @@ -234,7 +234,7 @@ fn self_crossing(path: &[Coord], closed: bool) -> Result, Coord> { } work += 1; if past_limit(work) { - return Err(path.first().copied().unwrap_or(a.0)); + return Err(path.iter().copied().find(|c| c.is_finite()).unwrap_or(a.0)); } let (lo, hi) = (i.min(j), i.max(j)); // Neighbouring segments share a vertex, as do a ring's first and last. @@ -1683,4 +1683,35 @@ mod tests { // and west of everything: reported. assert_eq!(reported, [1, 2, 3, 4, 5, 6]); } + + #[test] + fn self_intersections_handles_non_finite_coords_without_panicking() { + // Non-monotonic x coordinates mixed with consecutive NaN vertices (so segment minx is NaN) + // trigger driftsort total-order panics under `partial_cmp().unwrap_or(Equal)`. + let mut path = Vec::new(); + for i in 0..80 { + let x = ((i * 37) % 80) as f64 * 0.01; + if i % 5 == 0 { + path.push(Coord::new(f64::NAN, 0.0)); + path.push(Coord::new(f64::NAN, 0.0)); + } else { + path.push(Coord::new(x, i as f64 * 0.01)); + } + } + let mut clean = Dataset::new("l", GeometryType::Polyline, vec![]); + clean.push(Some(Geometry::Line(vec![path.clone()])), vec![]); + assert!(self_intersections(&clean, &[0]).errors.is_empty()); + + // Add a genuine self-crossing among the finite segments. + path.push(Coord::new(f64::NAN, f64::NAN)); + path.push(Coord::new(5.0, 0.0)); + path.push(Coord::new(5.1, 0.1)); + path.push(Coord::new(5.1, 0.0)); + path.push(Coord::new(5.0, 0.1)); + let mut crossing = Dataset::new("l", GeometryType::Polyline, vec![]); + crossing.push(Some(Geometry::Line(vec![path])), vec![]); + let res = self_intersections(&crossing, &[0]); + assert_eq!(res.errors.len(), 1); + assert!((res.errors[0].at.x - 5.05).abs() < 1e-4); + } } diff --git a/crates/geom/src/triangulate.rs b/crates/geom/src/triangulate.rs index b73f242e41..d50bf5d308 100644 --- a/crates/geom/src/triangulate.rs +++ b/crates/geom/src/triangulate.rs @@ -32,6 +32,70 @@ fn crosses(a: (f64, f64), b: (f64, f64), c: (f64, f64), d: (f64, f64)) -> bool { d1 * d2 < 0.0 && d3 * d4 < 0.0 } +/// Whether the ray `cur -> target` leaves strictly into the polygon interior at vertex `cur` +/// (to the left of `prev -> cur -> next`, which holds for both CCW outer rings and CW holes). +fn in_interior_wedge(prev: (f64, f64), cur: (f64, f64), next: (f64, f64), target: (f64, f64)) -> bool { + if target == cur { + return false; + } + let turn = cross(prev, cur, next); + let c1 = cross(prev, cur, target); + let c2 = cross(cur, next, target); + if turn > 0.0 { + c1 > 0.0 && c2 > 0.0 + } else if turn < 0.0 { + c1 > 0.0 || c2 > 0.0 + } else { + let dot = (cur.0 - prev.0) * (next.0 - cur.0) + (cur.1 - prev.1) * (next.1 - cur.1); + if dot > 0.0 { + c1 > 0.0 + } else if dot < 0.0 { + c1 != 0.0 || ((target.0 - cur.0) * (next.0 - cur.0) + (target.1 - cur.1) * (next.1 - cur.1)) < 0.0 + } else { + false + } + } +} + +/// Whether segment `a..b` blocks the open bridge segment `(pm, v)`: by strictly crossing it, by +/// placing a vertex strictly between `pm` and `v`, or by overlapping it collinearly. +fn blocks_bridge(pm: (f64, f64), v: (f64, f64), a: (f64, f64), b: (f64, f64)) -> bool { + if crosses(pm, v, a, b) { + return true; + } + let dx = v.0 - pm.0; + let dy = v.1 - pm.1; + let len2 = dx * dx + dy * dy; + if len2 == 0.0 { + return true; + } + let tol2 = 1e-24 * len2 * len2; + let ca = cross(pm, v, a); + let cb = cross(pm, v, b); + let a_on_line = ca * ca <= tol2; + let b_on_line = cb * cb <= tol2; + if a_on_line && a != pm && a != v { + let ta = (a.0 - pm.0) * dx + (a.1 - pm.1) * dy; + if ta > 0.0 && ta < len2 { + return true; + } + } + if b_on_line && b != pm && b != v { + let tb = (b.0 - pm.0) * dx + (b.1 - pm.1) * dy; + if tb > 0.0 && tb < len2 { + return true; + } + } + if a_on_line && b_on_line { + let ta = (a.0 - pm.0) * dx + (a.1 - pm.1) * dy; + let tb = (b.0 - pm.0) * dx + (b.1 - pm.1) * dy; + if ta.min(tb) < len2 && ta.max(tb) > 0.0 { + return true; + } + } + false +} + /// Triangles (indices into `outer` followed by each hole's vertices, in order) covering the polygon. /// Rings are open (no repeated closing vertex). `None` when the polygon is degenerate or too large. pub fn triangulate(outer: &[(f64, f64)], holes: &[Vec<(f64, f64)>]) -> Option> { @@ -69,29 +133,41 @@ pub fn triangulate_reporting(outer: &[(f64, f64)], holes: &[Vec<(f64, f64)>]) -> // the ring so far that it can see. hole_rings.sort_by(|a, b| { let mx = |r: &Vec| r.iter().map(|&i| pts[i].0).fold(f64::MIN, f64::max); - mx(b).partial_cmp(&mx(a)).unwrap_or(std::cmp::Ordering::Equal) + mx(b).total_cmp(&mx(a)) }); let mut work = 0usize; for (hi, h) in hole_rings.iter().enumerate() { - let (mpos, &m) = h.iter().enumerate().max_by(|a, b| pts[*a.1].0.partial_cmp(&pts[*b.1].0).unwrap_or(std::cmp::Ordering::Equal))?; + let (mpos, &m) = h.iter().enumerate().max_by(|a, b| pts[*a.1].0.total_cmp(&pts[*b.1].0))?; let pm = pts[m]; + let hn = h.len(); + let h_prev = pts[h[(mpos + hn - 1) % hn]]; + let h_next = pts[h[(mpos + 1) % hn]]; let edges_clear = |v: (f64, f64), work: &mut usize| { let ring_ok = (0..ring.len()).all(|k| { *work += 1; - !crosses(pm, v, pts[ring[k]], pts[ring[(k + 1) % ring.len()]]) + !blocks_bridge(pm, v, pts[ring[k]], pts[ring[(k + 1) % ring.len()]]) }); let holes_ok = ring_ok && hole_rings.iter().skip(hi).all(|r| { (0..r.len()).all(|k| { *work += 1; - !crosses(pm, v, pts[r[k]], pts[r[(k + 1) % r.len()]]) + !blocks_bridge(pm, v, pts[r[k]], pts[r[(k + 1) % r.len()]]) }) }); ring_ok && holes_ok }; + let rn = ring.len(); let mut best: Option<(usize, f64)> = None; for (k, &vi) in ring.iter().enumerate() { let v = pts[vi]; + if !in_interior_wedge(h_prev, pm, h_next, v) { + continue; + } + let r_prev = pts[ring[(k + rn - 1) % rn]]; + let r_next = pts[ring[(k + 1) % rn]]; + if !in_interior_wedge(r_prev, v, r_next, pm) { + continue; + } let d = (v.0 - pm.0).powi(2) + (v.1 - pm.1).powi(2); if best.is_none_or(|b| d < b.1) { let clear = edges_clear(v, &mut work); @@ -245,4 +321,33 @@ mod tests { let tr = triangulate(&circle, &circle_holes); assert!(tr.is_some(), "3000-vertex polygon with 8 holes should succeed"); } + + #[test] + fn diamond_hole_bridge_does_not_cut_through_hole_interior() { + // Outer diamond (area 50) with an interior diamond hole (area 4). The closest outer vertex + // to the hole's rightmost vertex (3, 5) is (0, 5), directly across the hole interior and + // through vertex (1, 5); bridging there corrupts the triangulation. + let outer = vec![(0.0, 5.0), (5.0, 0.0), (10.0, 5.0), (5.0, 10.0)]; + let hole = vec![(1.0, 5.0), (2.0, 7.0), (3.0, 5.0), (2.0, 3.0)]; + let all: Vec<(f64, f64)> = outer.iter().chain(&hole).copied().collect(); + let (tris, fanned) = triangulate_reporting(&outer, std::slice::from_ref(&hole)).unwrap(); + assert!(!fanned, "clean diamond with hole should not fall back to fan"); + assert!((area(&all, &tris) - 46.0).abs() < 1e-9, "expected area 46, got {}", area(&all, &tris)); + let hole_center = (2.0, 5.0); + assert!(!tris.iter().any(|t| in_triangle(hole_center, all[t[0]], all[t[1]], all[t[2]])), "no triangle may cover the hole interior"); + + // Two horizontally aligned diamond holes inside a square: bridging the left hole must not + // pass through a vertex of the right hole or its interior. + let sq = vec![(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]; + let h1 = vec![(1.0, 5.0), (2.0, 6.0), (3.0, 5.0), (2.0, 4.0)]; + let h2 = vec![(5.0, 5.0), (6.0, 6.0), (7.0, 5.0), (6.0, 4.0)]; + let holes = vec![h1, h2]; + let all2: Vec<(f64, f64)> = sq.iter().chain(holes.iter().flatten()).copied().collect(); + let (tris2, fanned2) = triangulate_reporting(&sq, &holes).unwrap(); + assert!(!fanned2); + assert!((area(&all2, &tris2) - 96.0).abs() < 1e-9, "expected area 96, got {}", area(&all2, &tris2)); + for pt in [(2.0, 5.0), (6.0, 5.0)] { + assert!(!tris2.iter().any(|t| in_triangle(pt, all2[t[0]], all2[t[1]], all2[t[2]]))); + } + } } diff --git a/crates/render/src/effects.rs b/crates/render/src/effects.rs index 109c2ca80d..b43c5f1db4 100644 --- a/crates/render/src/effects.rs +++ b/crates/render/src/effects.rs @@ -548,7 +548,13 @@ pub(crate) fn extrude_tilted( let mut kept: Vec<(f64, f64)> = Vec::new(); let mut last: Option<(f64, f64)> = None; for c in r { + if !c.is_finite() { + continue; + } let g = cam.ground_px(*c); + if !g.0.is_finite() || !g.1.is_finite() { + continue; + } let s = cam.project_raised(g.0, g.1, 0.0, w, h); let near = match (s, last) { (Some(s), Some(l)) => (s.0 - l.0).hypot(s.1 - l.1) < 0.75, @@ -572,6 +578,10 @@ pub(crate) fn extrude_tilted( continue; } let centroid = rustgis_geom::Coord::new(sum.x / n, sum.y / n); + let depth_y = cam.ground_px(centroid).1; + if !centroid.is_finite() || !depth_y.is_finite() { + continue; + } // At the feature's own scale (Web Mercator stretches the ground toward the poles). let (unit, res) = (m_per_unit(centroid).max(1e-9), cam.res.max(1e-9)); let base = base_within(x.base_metres_at(ds, row, columns) / unit / res, 1e7); @@ -579,10 +589,10 @@ pub(crate) fn extrude_tilted( // Fog on the way to the view's reach, by the middle of the feature. let depth = cam.depth_scale(centroid, h).map_or(1.0, |k| 1.0 / k.max(1e-9)); let t = ((depth - far * 0.5) / (far * 0.5)).clamp(0.0, 1.0); - shapes.push((cam.ground_px(centroid).1, rings, holes, base, up, t * t * (3.0 - 2.0 * t), row)); + shapes.push((depth_y, rings, holes, base, up, t * t * (3.0 - 2.0 * t), row)); } // Far (up the screen) first. - shapes.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal)); + shapes.sort_by(|a, b| a.0.total_cmp(&b.0)); let at = |u: f64, v: f64, up: f64| cam.project_raised(u, v, up, w, h).map(|(x, y)| (x as f32 * ppp, y as f32 * ppp)); let path = |pts: &[(f32, f32)]| { let mut pb = PathBuilder::new(); @@ -758,4 +768,58 @@ mod spool_tests { shapes(&ctx, &ds, &[Some(&geom)], &[true], &Extrusion { height: 10.0, ..Extrusion::default() }, f64::INFINITY, |_| symbol); assert_eq!(flat.first().map(|s| s.3), Some(0.0)); } + + #[test] + fn extrude_tilted_skips_non_finite_vertices_and_depths() { + let symbol = Symbol::default_for(rustgis_data::GeometryType::Polygon, 1); + let mut camera = rustgis_map::Camera::new(rustgis_geom::Coord::new(0.0, 0.0), 1.0); + camera.pitch = 45.0; + let view = View { width: 100.0, height: 100.0, pixels_per_point: 1.0, camera, sky: false }; + let c = rustgis_geom::Coord::new; + let mut geoms = Vec::new(); + // Ascending runs bridged by NaN depths fool driftsort's run detector into treating + // non-monotonic slices as sorted, triggering a merge panic under + // `partial_cmp().unwrap_or(Equal)`. + let mut keys: Vec> = Vec::new(); + for block in 0..8 { + for k in 0..12 { + keys.push(Some(20.0 - (block * 2 + k) as f64 * 0.5)); + } + keys.push(None); + for k in 0..12 { + keys.push(Some(-20.0 + k as f64 * 0.5)); + } + } + for (i, ky) in keys.into_iter().enumerate() { + let y = ky.unwrap_or(0.0); + let x0 = ((i % 7) as f64 - 3.0) * 6.0; + let mut ring = vec![c(x0 - 3.0, y), c(x0 + 3.0, y), c(x0, y + 3.0)]; + if ky.is_none() { + ring.push(c(f64::NAN, f64::NAN)); + } + ring.push(c(x0 - 3.0, y)); + geoms.push(Geometry::Polygon(vec![vec![ring]])); + } + // Also include an all-NaN polygon and a polygon whose vertex sum overflows to infinity. + geoms.push(Geometry::Polygon(vec![vec![vec![c(f64::NAN, f64::NAN), c(f64::NAN, f64::NAN), c(f64::NAN, f64::NAN)]]])); + geoms.push(Geometry::Polygon(vec![vec![vec![c(1e308, 0.0), c(1e308, 1.0), c(1e308, 2.0), c(1e308, 0.0)]]])); + let refs: Vec> = geoms.iter().map(Some).collect(); + let rows = vec![true; geoms.len()]; + let ds = Dataset::new("tilt", rustgis_data::GeometryType::Polygon, vec![]); + let x = Extrusion { height: 10.0, shadows: true, ..Extrusion::default() }; + let mut pm = Pixmap::new(100, 100).unwrap(); + extrude_tilted(&mut pm, &view, &ds, &refs, &rows, &x, |_| 1.0, Rgba::rgb(255, 255, 255), |_| symbol); + assert!(pm.pixels().iter().any(|px| px.alpha() > 0), "valid tilted polygons still draw"); + + // A polygon with 3 valid vertices plus 1 NaN vertex must render identically to the clean + // 3-vertex polygon once the non-finite vertex is skipped. + let clean = Geometry::Polygon(vec![vec![vec![c(-10.0, -10.0), c(10.0, -10.0), c(0.0, 10.0), c(-10.0, -10.0)]]]); + let dirty = + Geometry::Polygon(vec![vec![vec![c(-10.0, -10.0), c(10.0, -10.0), c(0.0, 10.0), c(f64::NAN, f64::NAN), c(-10.0, -10.0)]]]); + let mut pm_clean = Pixmap::new(100, 100).unwrap(); + let mut pm_dirty = Pixmap::new(100, 100).unwrap(); + extrude_tilted(&mut pm_clean, &view, &ds, &[Some(&clean)], &[true], &x, |_| 1.0, Rgba::rgb(255, 255, 255), |_| symbol); + extrude_tilted(&mut pm_dirty, &view, &ds, &[Some(&dirty)], &[true], &x, |_| 1.0, Rgba::rgb(255, 255, 255), |_| symbol); + assert!(pm_dirty.data() == pm_clean.data(), "skipping NaN vertex matches clean polygon"); + } } diff --git a/crates/render/src/gradient_fill.rs b/crates/render/src/gradient_fill.rs index 55d3e48154..a421649a97 100644 --- a/crates/render/src/gradient_fill.rs +++ b/crates/render/src/gradient_fill.rs @@ -478,7 +478,8 @@ fn edt_1d(f: &[f32], out: &mut [f32], v: &mut [usize], z: &mut [f32]) { // The parabola rooted at p, where it crosses the one rooted at q. let cross = |q: usize, p: usize| { let (fq, fp) = (at(f, q), at(f, p)); - ((fq + (q * q) as f32) - (fp + (p * p) as f32)) / (2.0 * (q as f32 - p as f32)) + let (qf, pf) = (q as f64, p as f64); + (((f64::from(fq) + qf * qf) - (f64::from(fp) + pf * pf)) / (2.0 * (qf - pf))) as f32 }; let mut k = 0usize; if let (Some(v0), [z0, z1, ..]) = (v.first_mut(), &mut *z) { @@ -751,4 +752,20 @@ mod tests { blur(&mut s, w, h, 3); assert!(s[3] > 0.0 && s[4] < 1.0, "{s:?}"); } + + #[test] + fn edt_1d_handles_large_indices_without_overflow_or_rounding_loss() { + // Past 65,536, `q * q` overflows 32-bit `usize` on wasm32, and `(q * q) as f32` rounds + // away small `f` differences (ULP >= 256 in f32). + let n = 65_538; + let mut f = vec![1e20f32; n]; + f[65_536] = 0.0; + f[65_537] = 10.0; + let (mut out, mut v, mut z) = (vec![0.0f32; n], vec![0usize; n], vec![0.0f32; n + 1]); + edt_1d(&f, &mut out, &mut v, &mut z); + assert_eq!(out[65_536], 0.0); + assert_eq!(out[65_537], 1.0); + assert_eq!(out[65_535], 1.0); + assert_eq!(out[65_534], 4.0); + } } From cc08e79a12d8be8b5e982dd951d928653d8336f0 Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 25 Nov 2026 09:44:52 -0500 Subject: [PATCH 2/7] Address review feedback - Count valid pixels that overflow the neural network in `neural::classify_on` (exposed via `neural::classify_reporting`) and warn once with the count in `dl.classify`, with both-ways notice tests. - Expose `network::usable_polygon_extent` so `analysis.simulate` counts polygons skipped for empty, zero-area, or non-finite extents and warns once with the count, with both-ways notice tests. - Reject non-finite path coordinates in `workspace::profile` with `"a coordinate is not a number"` instead of reporting `"the line doesn't cross the raster"`, with a regression test. --- crates/analysis/src/network.rs | 24 +++--- crates/analysis/src/neural.rs | 50 ++++++++++-- crates/engine/src/cmd/deeplearning.rs | 27 ++++--- crates/engine/src/cmd/workflows.rs | 16 ++++ crates/engine/src/cmd/workspace.rs | 3 + crates/engine/src/tests.rs | 109 ++++++++++++++++++++++++++ 6 files changed, 202 insertions(+), 27 deletions(-) diff --git a/crates/analysis/src/network.rs b/crates/analysis/src/network.rs index 481cdc0c74..f8f251265c 100644 --- a/crates/analysis/src/network.rs +++ b/crates/analysis/src/network.rs @@ -772,6 +772,19 @@ impl Search { pub const MAX_POINTS: usize = 1_000_000; const MAX_TRIES: usize = 50_000_000; +/// Whether `e` is a finite, positive-area bounding box that [`random_points`] can sample inside. +pub fn usable_polygon_extent(e: rustgis_geom::Extent) -> bool { + !e.is_empty() + && e.min_x.is_finite() + && e.max_x.is_finite() + && e.min_y.is_finite() + && e.max_y.is_finite() + && e.width().is_finite() + && e.height().is_finite() + && e.width() > 0.0 + && e.height() > 0.0 +} + /// Points spread at random (but reproducibly, from `seed`) inside polygons: `per` in each, up to /// [`MAX_POINTS`] in all; thin polygons may get fewer (tries are bounded too). pub fn random_points(ds: &Dataset, rows: &[usize], per: usize, seed: u64) -> Vec<(usize, Coord)> { @@ -792,16 +805,7 @@ pub fn random_points(ds: &Dataset, rows: &[usize], per: usize, seed: u64) -> Vec crate::control::reached(i); let Some(Geometry::Polygon(polys)) = ds.features.get(*r).and_then(|f| f.geometry.as_ref()) else { continue }; let e = ds.features.get(*r).and_then(|f| f.geometry.as_ref()).map(|g| g.extent()).unwrap_or_default(); - if e.is_empty() - || !e.min_x.is_finite() - || !e.max_x.is_finite() - || !e.min_y.is_finite() - || !e.max_y.is_finite() - || !e.width().is_finite() - || !e.height().is_finite() - || e.width() <= 0.0 - || e.height() <= 0.0 - { + if !usable_polygon_extent(e) { continue; } let mut placed = 0; diff --git a/crates/analysis/src/neural.rs b/crates/analysis/src/neural.rs index 8656eeff29..379905f8e8 100644 --- a/crates/analysis/src/neural.rs +++ b/crates/analysis/src/neural.rs @@ -485,15 +485,33 @@ pub fn train( Ok(Trained { model, accuracy, samples: samples.len(), epochs, epochs_asked, fitted: fit.len(), training }) } +/// Result of classifying a raster: 1-based class numbers (`nodata` where a band has no data or +/// where the network overflowed), each pixel's probability of that class, and how many valid +/// pixels overflowed to non-finite probabilities and were left as `nodata`. +#[derive(Clone, Debug, PartialEq)] +pub struct Classified { + pub class: Vec, + pub prob: Vec, + pub overflowed: usize, +} + /// Classifies every pixel: class numbers (1-based, `nodata` where a band has no data) and each /// pixel's probability of that class. Rows go on several threads when the work is large, except in /// the browser, which uses one (#1252). pub fn classify(r: &Raster, model: &Mlp, nodata: f32) -> Result<(Vec, Vec), String> { + let out = classify_on(r, model, nodata, None)?; + Ok((out.class, out.prob)) +} + +/// Like [`classify`], and also counts valid pixels whose values overflowed the network to +/// non-finite probabilities and were left as `nodata`. +pub fn classify_reporting(r: &Raster, model: &Mlp, nodata: f32) -> Result { classify_on(r, model, nodata, None) } -/// [`classify`] on `threads` threads (none: as many as pay off). -fn classify_on(r: &Raster, model: &Mlp, nodata: f32, threads: Option) -> Result<(Vec, Vec), String> { +/// [`classify_reporting`] on `threads` threads (none: as many as pay off). +fn classify_on(r: &Raster, model: &Mlp, nodata: f32, threads: Option) -> Result { + use std::sync::atomic::{AtomicUsize, Ordering}; model.validate()?; // A large model on a large raster is refused rather than run for minutes, unless the run can // be cancelled. @@ -509,6 +527,7 @@ fn classify_on(r: &Raster, model: &Mlp, nodata: f32, threads: Option) -> } let (w, h) = (r.width as usize, r.height as usize); let (mut class, mut prob) = (crate::rasterops::new_band(w, h, nodata)?, crate::rasterops::new_band(w, h, nodata)?); + let overflowed = AtomicUsize::new(0); // In [`crate::parallel::MIN_ROW_WORK`]'s units (about 30 ns each): a weight of a pixel costs // about 1 ns. let work = w.saturating_mul(h).saturating_mul(weights) / 30; @@ -520,6 +539,7 @@ fn classify_on(r: &Raster, model: &Mlp, nodata: f32, threads: Option) -> threads, || (vec![0.0f32; model.bands.len()], crate::control::Pace::default()), |(x, pace): &mut (Vec, crate::control::Pace), row, (class, prob): (&mut [f32], &mut [f32])| { + let mut row_overflowed = 0usize; for (col, (c_out, p_out)) in class.iter_mut().zip(prob.iter_mut()).enumerate() { // A large model on a wide row takes long without a cap: Cancel is looked at // within it. @@ -536,13 +556,20 @@ fn classify_on(r: &Raster, model: &Mlp, nodata: f32, threads: Option) -> None => false, } }); - if ok && let Some((c, p)) = model.predict_checked(x) { - (*c_out, *p_out) = ((c + 1) as f32, p); + if ok { + if let Some((c, p)) = model.predict_checked(x) { + (*c_out, *p_out) = ((c + 1) as f32, p); + } else { + row_overflowed += 1; + } } } + if row_overflowed > 0 { + overflowed.fetch_add(row_overflowed, Ordering::Relaxed); + } }, )?; - Ok((class, prob)) + Ok(Classified { class, prob, overflowed: overflowed.load(Ordering::Relaxed) }) } #[cfg(test)] @@ -612,12 +639,14 @@ mod tests { } let transform = GeoTransform { origin_x: 0.0, origin_y: 45.0, pixel_width: 0.001, pixel_height: -0.001 }; let r = Raster::new("img", w, h, vec![a, b], transform, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); - let (c1, p1) = classify_on(&r, &model, -1.0, Some(1)).unwrap(); + let Classified { class: c1, prob: p1, overflowed } = classify_on(&r, &model, -1.0, Some(1)).unwrap(); + assert_eq!(overflowed, 0); assert!(c1.contains(&1.0) && c1.contains(&2.0) && c1.contains(&-1.0), "both classes and no data"); // A classified pixel has its class's probability; one with no data has none. assert!(c1.iter().zip(&p1).all(|(c, p)| if *c == -1.0 { *p == -1.0 } else { (0.0..=1.0).contains(p) && *p >= 0.5 })); for threads in [2, 7, 16] { - let (c, p) = classify_on(&r, &model, -1.0, Some(threads)).unwrap(); + let Classified { class: c, prob: p, overflowed: ov } = classify_on(&r, &model, -1.0, Some(threads)).unwrap(); + assert_eq!(ov, 0); let bits = |v: &[f32]| v.iter().map(|x| x.to_bits()).collect::>(); assert_eq!((bits(&c), bits(&p)), (bits(&c1), bits(&p1)), "{threads} threads"); } @@ -719,12 +748,17 @@ mod tests { model.validate().unwrap(); let gt = GeoTransform { origin_x: 0.0, origin_y: 1.0, pixel_width: 1.0, pixel_height: -1.0 }; let r = Raster::new("img", 2, 1, vec![vec![1.0, 1.0e38]], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); - let (class, prob) = classify(&r, &model, -1.0).unwrap(); + let classified = classify_reporting(&r, &model, -1.0).unwrap(); + let (class, prob) = (classified.class, classified.prob); + assert_eq!(classified.overflowed, 1, "one valid pixel overflowed the network"); assert_eq!(model.predict_checked(&[1.0e38]), None); assert!(model.predict(&[1.0e38]).1.is_nan()); assert_eq!(class[0], 1.0); assert!(prob[0] > 0.9 && prob[0].is_finite()); assert_eq!(class[1], -1.0, "overflowing pixel stays nodata, got class {} prob {}", class[1], prob[1]); assert_eq!(prob[1], -1.0, "overflowing pixel stays nodata, got prob {}", prob[1]); + + let clean = Raster::new("clean", 2, 1, vec![vec![1.0, -1.0]], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + assert_eq!(classify_reporting(&clean, &model, -1.0).unwrap().overflowed, 0); } } diff --git a/crates/engine/src/cmd/deeplearning.rs b/crates/engine/src/cmd/deeplearning.rs index c73c7e4740..50093e97b9 100644 --- a/crates/engine/src/cmd/deeplearning.rs +++ b/crates/engine/src/cmd/deeplearning.rs @@ -354,7 +354,8 @@ pub(crate) fn classify_work(s: &Session, p: &Value) -> Result= 1.0) { if let Some(c) = counts.get_mut(*v as usize - 1) { @@ -365,18 +366,26 @@ pub(crate) fn classify_work(s: &Session, p: &Value) -> Result = m.model.classes.iter().zip(&counts).enumerate().map(|(i, (c, n))| json!({"value": i + 1, "class": c, "pixels": n})).collect(); let extra = json!({"model": m.name, "accuracy": m.accuracy, "classes": legend}); + let out_name = out.clone(); // Kept once its classes are added. One that was given no name is named then, so it never // replaces a model kept while it trained. - let then: Option = trained.map(|(auto, unread)| { + let then: Option = (trained.is_some() || overflowed > 0).then(|| { Box::new(move |s: &mut Session, v: &mut Value| { - unread.say(s); - let mut m = m; - if let Some(base) = auto { - m.name = free_name(s, &base); - v["model"] = json!(m.name); + if let Some((auto, unread)) = trained { + unread.say(s); + let mut m = m; + if let Some(base) = auto { + m.name = free_name(s, &base); + v["model"] = json!(m.name); + } + m.say_limited(s, v); + v["replaced"] = json!(store(s, m)); + } + if overflowed > 0 { + s.warn(format!( + "{out_name}: {overflowed} pixel(s) overflowed the network during classification and were left as no data" + )); } - m.say_limited(s, v); - v["replaced"] = json!(store(s, m)); }) as super::workflows::Then }); Ok(super::workflows::made_layer(out, layer, Some(extra), then)) diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index c00def6cfd..f4850f92b3 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -2291,6 +2291,16 @@ fn simulate(s: &mut Session, p: &Value) -> CmdResult { && polygons.features.row(r).is_some_and(|f| f.geometry().is_none()) }) .count(); + let unusable = rows + .iter() + .filter(|&&r| { + polygons + .features + .row(r) + .and_then(|f| f.geometry()) + .is_some_and(|g| matches!(g, Geometry::Polygon(_)) && !network::usable_polygon_extent(g.extent())) + }) + .count(); let source = l.name.clone(); let seed = f(p, "seed").map_or(42, |v| v.max(0.0) as u64); let pts: Vec<(usize, Coord)> = match ps(p, "field") { @@ -2337,6 +2347,12 @@ fn simulate(s: &mut Session, p: &Value) -> CmdResult { ds.name )); } + if unusable > 0 { + s.warn(format!( + "{}: {unusable} polygon(s) of {source} have an empty, zero-area or non-finite extent, so no points are simulated in them", + ds.name + )); + } let nid = super::layer::add_dataset(s, ds); Ok(json!({"layer": nid, "points": n})) } diff --git a/crates/engine/src/cmd/workspace.rs b/crates/engine/src/cmd/workspace.rs index 55222935d1..009d0127e6 100644 --- a/crates/engine/src/cmd/workspace.rs +++ b/crates/engine/src/cmd/workspace.rs @@ -541,6 +541,9 @@ fn dem(s: &Session, p: &Value) -> Result CmdResult { + if path.iter().any(|c| !c.is_finite()) { + return Err("a coordinate is not a number".into()); + } let r = dem(s, p)?; let samples = p.get("samples").and_then(Value::as_u64).unwrap_or(200) as usize; let prof = rustgis_analysis::rasterops::profile(&r, 0, path, samples); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a0c70f2c78..5763a337a6 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -61999,3 +61999,112 @@ fn a_transparency_reads_back_without_float_noise() { assert_eq!(crate::cmd::project::percent(33.3), json!(33.3)); assert_eq!(crate::cmd::project::percent(0.0), json!(0.0)); } + +/// Deep learning classification warns with a count when valid pixels overflow the network, and +/// emits no notice for clean input (AGENTS.md > Never silent). +#[test] +fn dl_classify_notifies_when_pixels_overflow_and_not_when_clean() { + use crate::cmd::deeplearning::DlModel; + use rustgis_analysis::neural::{Dense, Mlp}; + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; + use rustgis_map::RasterLayer; + + let mut s = world(); + let gt = GeoTransform { origin_x: 0.0, origin_y: 1.0, pixel_width: 1.0, pixel_height: -1.0 }; + let r_overflow = Raster::new("overflow_img", 2, 1, vec![vec![1.0, 1.0e38]], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + let r_clean = Raster::new("clean_img", 2, 1, vec![vec![1.0, -1.0]], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + crate::cmd::raster::add_raster(&mut s, "overflow_img", RasterLayer::from_path(r_overflow, "overflow_img.tif")).unwrap(); + crate::cmd::raster::add_raster(&mut s, "clean_img", RasterLayer::from_path(r_clean, "clean_img.tif")).unwrap(); + s.project.dl_models.push(DlModel { + name: "m".into(), + model: Mlp { + bands: vec![0], + mean: vec![0.0], + std: vec![1.0], + layers: vec![Dense { inp: 1, out: 2, w: vec![10.0, -10.0], b: vec![0.0, 0.0] }], + classes: vec!["a".into(), "b".into()], + }, + accuracy: 1.0, + epochs: 1, + limited: None, + }); + + let mark = s.notice_mark(); + s.run("dl.classify", &json!({"layer": "overflow_img", "model": "m", "name": "out_ov"})).unwrap(); + let notices = s.notices_since(mark); + assert!(notices.iter().any(|n| n.text.contains("1 pixel(s) overflowed")), "expected overflow notice, got {notices:?}"); + + let mark = s.notice_mark(); + s.run("dl.classify", &json!({"layer": "clean_img", "model": "m", "name": "out_ok"})).unwrap(); + let clean_notices = s.notices_since(mark); + assert!( + !clean_notices.iter().any(|n| n.text.contains("overflowed")), + "clean classification must not emit overflow notice: {clean_notices:?}" + ); +} + +/// `analysis.simulate` warns once with a count when polygons have empty, zero-area or non-finite +/// extents, and emits no notice when all polygons are usable (AGENTS.md > Never silent). +#[test] +fn simulate_notifies_when_polygons_have_unusable_extents_and_not_when_clean() { + use rustgis_data::{Dataset, Geometry, GeometryType}; + use rustgis_geom::Coord; + + let sq = || { + Geometry::Polygon(vec![vec![vec![ + Coord::new(0.0, 0.0), + Coord::new(1.0, 0.0), + Coord::new(1.0, 1.0), + Coord::new(0.0, 1.0), + Coord::new(0.0, 0.0), + ]]]) + }; + + let mut s = world(); + let mut mixed = Dataset::new("mixed_polys", GeometryType::Polygon, vec![]); + mixed.push(Some(sq()), vec![]); + mixed.push(Some(Geometry::Polygon(vec![])), vec![]); + mixed.push(Some(Geometry::Polygon(vec![vec![vec![Coord::new(0.0, 0.0), Coord::new(1.0, 0.0), Coord::new(0.0, 0.0)]]])), vec![]); + let mixed_id = crate::cmd::layer::add_dataset(&mut s, mixed); + + let mut clean = Dataset::new("clean_polys", GeometryType::Polygon, vec![]); + clean.push(Some(sq()), vec![]); + let clean_id = crate::cmd::layer::add_dataset(&mut s, clean); + + let mark = s.notice_mark(); + let res = s.run("analysis.simulate", &json!({"layer": mixed_id, "count": 5, "name": "sim_mixed"})).unwrap(); + assert_eq!(res["points"], 5); + let notices = s.notices_since(mark); + assert!( + notices.iter().any(|n| n.text.contains("2 polygon(s)") && n.text.contains("empty, zero-area or non-finite")), + "expected notice for 2 unusable polygons, got {notices:?}" + ); + + let mark = s.notice_mark(); + let res_clean = s.run("analysis.simulate", &json!({"layer": clean_id, "count": 5, "name": "sim_clean"})).unwrap(); + assert_eq!(res_clean["points"], 5); + let clean_notices = s.notices_since(mark); + assert!(clean_notices.is_empty(), "clean simulate must emit no notice: {clean_notices:?}"); +} + +/// `profile.alongLine` reports a non-finite coordinate directly instead of "the line doesn't cross +/// the raster". +#[test] +fn profile_along_line_reports_non_finite_coordinate() { + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; + use rustgis_data::{Dataset, Geometry, GeometryType}; + use rustgis_geom::Coord; + use rustgis_map::RasterLayer; + + let mut s = world(); + let gt = GeoTransform { origin_x: -10.0, origin_y: 10.0, pixel_width: 1.0, pixel_height: -1.0 }; + let r = Raster::new("dem", 20, 20, vec![vec![50.0; 400]], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + crate::cmd::raster::add_raster(&mut s, "dem", RasterLayer::from_path(r, "dem.tif")).unwrap(); + + let mut lines = Dataset::new("bad_lines", GeometryType::Polyline, vec![]); + lines.push(Some(Geometry::Line(vec![vec![Coord::new(0.0, 0.0), Coord::new(f64::NAN, 1.0)]])), vec![]); + crate::cmd::layer::add_dataset(&mut s, lines); + + let err = s.run("profile.alongLine", &json!({"layer": "dem", "lines": "bad_lines", "row": 0})).unwrap_err(); + assert_eq!(err, "a coordinate is not a number"); +} From 2e30c61f746b56767be99008795e598d068002dd Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 25 Nov 2026 10:05:53 -0500 Subject: [PATCH 3/7] Address review feedback - Reject non-finite intermediate activations before ReLU in `neural::Mlp::probabilities` so hidden-layer NaNs are not replaced by 0.0, with a hidden-layer overflow regression test. - Apply `Raster::wrap_col` in `rasterops::elevation_at` so wrapped profile samples resolve in regional antimeridian and 0..360 rasters, with a 179..183 deg regional raster test. - Filter non-finite input vertices before `to_plane` in `topology::self_intersections` and reflect omitted non-finite segments in `Checked` (`complete: false`, `skipped` feature count), with regression assertions for both NaN and infinite coordinates. - Skip consecutive duplicate coordinates when choosing bridge-wedge neighbors (`distinct_neighbors`) in `geom::triangulate_reporting`, with a repeated-rightmost-vertex hole regression test. --- crates/analysis/src/neural.rs | 32 ++++++++++++++++ crates/analysis/src/rasterops.rs | 12 ++++++ crates/analysis/src/topology.rs | 64 ++++++++++++++++++++++++-------- crates/geom/src/triangulate.rs | 29 ++++++++++++--- 4 files changed, 116 insertions(+), 21 deletions(-) diff --git a/crates/analysis/src/neural.rs b/crates/analysis/src/neural.rs index 379905f8e8..45526652b6 100644 --- a/crates/analysis/src/neural.rs +++ b/crates/analysis/src/neural.rs @@ -89,7 +89,11 @@ impl Mlp { /// Class probabilities for one pixel's band values. pub fn probabilities(&self, x: &[f32]) -> Vec { + let out_len = self.layers.last().map_or(0, |l| l.out); let mut a: Vec = x.iter().zip(self.mean.iter().zip(&self.std)).map(|(v, (m, s))| (v - m) / s).collect(); + if !a.iter().all(|v| v.is_finite()) { + return vec![f32::NAN; out_len]; + } let last = self.layers.len().saturating_sub(1); for (k, l) in self.layers.iter().enumerate() { let mut z = l.b.clone(); @@ -97,6 +101,11 @@ impl Mlp { let row = l.w.get(o * l.inp..(o + 1) * l.inp).unwrap_or(&[]); *zo += row.iter().zip(&a).map(|(w, v)| w * v).sum::(); } + // Reject non-finite activations before ReLU: `f32::NAN.max(0.0)` returns `0.0`, which + // would silently mask a hidden-layer overflow into finite probabilities. + if !z.iter().all(|v| v.is_finite()) { + return vec![f32::NAN; out_len]; + } if k < last { z.iter_mut().for_each(|v| *v = v.max(0.0)); } @@ -760,5 +769,28 @@ mod tests { let clean = Raster::new("clean", 2, 1, vec![vec![1.0, -1.0]], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); assert_eq!(classify_reporting(&clean, &model, -1.0).unwrap().overflowed, 0); + + // A hidden-layer NaN (+inf + -inf) must not be turned into 0.0 by ReLU. + let hidden_model = Mlp { + bands: vec![0, 1], + mean: vec![0.0, 0.0], + std: vec![1.0, 1.0], + layers: vec![ + Dense { inp: 2, out: 1, w: vec![10.0, -5.0], b: vec![0.0] }, + Dense { inp: 1, out: 2, w: vec![1.0, -1.0], b: vec![-1.0, 1.0] }, + ], + classes: vec!["a".into(), "b".into()], + }; + hidden_model.validate().unwrap(); + assert_eq!(hidden_model.predict_checked(&[1.0e38, 1.0e38]), None); + assert!(hidden_model.predict_checked(&[1.0, 1.0]).is_some_and(|(c, p)| c == 0 && p > 0.9)); + let r_hidden = + Raster::new("hidden_img", 2, 1, vec![vec![1.0, 1.0e38], vec![1.0, 1.0e38]], gt, Crs::LonLat, None, ColorHint::Gray, "Float32") + .unwrap(); + let res_hidden = classify_reporting(&r_hidden, &hidden_model, -1.0).unwrap(); + assert_eq!(res_hidden.overflowed, 1); + assert_eq!(res_hidden.class[0], 1.0); + assert_eq!(res_hidden.class[1], -1.0); + assert_eq!(res_hidden.prob[1], -1.0); } } diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index 6a37c32739..4d7da9b82e 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -423,6 +423,7 @@ fn dist_m(a: Coord, b: Coord) -> f64 { pub fn elevation_at(r: &Raster, b: usize, ll: Coord) -> Option { let w = r.transformer().from_lonlat(ll)?; let (x, y) = r.transform.to_pixel(w); + let x = r.wrap_col(x); let (x, y) = (x - 0.5, y - 0.5); let (c0, r0) = (x.floor() as i64, y.floor() as i64); let (fx, fy) = (x - c0 as f64, y - r0 as f64); @@ -3309,5 +3310,16 @@ mod tests { assert!(d.is_finite() && c.is_finite()); assert!(c.x.abs() >= 178.999 && c.x.abs() <= 180.0, "westbound sample swept away: {c:?}"); } + + // Regional raster spanning 179..183 deg: wrapped samples past 180 (e.g. -179.5) must still + // resolve onto the raster's columns via its longitude wrap. + let reg_gt = GeoTransform { origin_x: 179.0, origin_y: 2.0, pixel_width: 1.0, pixel_height: -1.0 }; + let reg = Raster::new("regional", 4, 4, vec![vec![250.0; 16]], reg_gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + let prof_reg = profile(®, 0, &[Coord::new(179.5, 0.0), Coord::new(-177.5, 0.0)], 13); + assert_eq!(prof_reg.len(), 13); + for &(d, c, z) in &prof_reg { + assert!(d.is_finite() && c.is_finite()); + assert_eq!(z, Some(250.0), "regional antimeridian raster missed elevation at {c:?}"); + } } } diff --git a/crates/analysis/src/topology.rs b/crates/analysis/src/topology.rs index f17007fafb..b9ae5bfd5f 100644 --- a/crates/analysis/src/topology.rs +++ b/crates/analysis/src/topology.rs @@ -209,17 +209,19 @@ fn segments_cross(a: (Coord, Coord), b: (Coord, Coord)) -> Option { (t > e && t < 1.0 - e && u > e && u < 1.0 - e).then(|| Coord::new(a.0.x + t * (a.1.x - a.0.x), a.0.y + t * (a.1.y - a.0.y))) } -/// Where a path crosses itself (rings and lines; ring closures are allowed). Segments are swept -/// west to east, so only those overlapping in x are compared. A path too complex to finish -/// within the work budget is reported at its start, to be looked at, rather than passed, and -/// says so (`Err`), so the check is said to be incomplete. A run cancelled past the limit stops -/// with `Err` too, which the caller tells apart by looking at Cancel. -fn self_crossing(path: &[Coord], closed: bool) -> Result, Coord> { +/// Where a path crosses itself (rings and lines; ring closures are allowed), together with +/// whether any non-finite segment had to be omitted. Segments are swept west to east, so only +/// those overlapping in x are compared. A path too complex to finish within the work budget is +/// reported at its start, to be looked at, rather than passed, and says so (`Err`), so the check +/// is said to be incomplete. A run cancelled past the limit stops with `Err` too, which the caller +/// tells apart by looking at Cancel. +fn self_crossing(path: &[Coord], closed: bool) -> Result<(Option, bool), Coord> { let segs: Vec<(Coord, Coord)> = path.windows(2).filter_map(|w| Some((*w.first()?, *w.get(1)?))).collect(); let n = segs.len(); let minx = |s: &(Coord, Coord)| s.0.x.min(s.1.x); let maxx = |s: &(Coord, Coord)| s.0.x.max(s.1.x); let mut order: Vec = (0..n).filter(|&i| segs.get(i).is_some_and(|s| s.0.is_finite() && s.1.is_finite())).collect(); + let omitted = order.len() < n; order.sort_by(|a, b| { let (sa, sb) = (segs.get(*a).map_or(0.0, minx), segs.get(*b).map_or(0.0, minx)); sa.total_cmp(&sb) @@ -242,11 +244,11 @@ fn self_crossing(path: &[Coord], closed: bool) -> Result, Coord> { continue; } if let Some(c) = segments_cross(*a, *b) { - return Ok(Some(c)); + return Ok((Some(c), omitted)); } } } - Ok(None) + Ok((None, omitted)) } /// Lines and polygon rings that cross themselves. @@ -254,10 +256,11 @@ pub fn self_intersections(ds: &Dataset, rows: &[usize]) -> Checked { let mut out = Vec::new(); // A path too complex to finish: reported at its start, and the check said incomplete. let mut limited = false; + let mut skipped = 0usize; crate::control::begin(rows.len()); for (i, r) in rows.iter().enumerate() { if crate::control::cancelled() { - return Checked::partial(out); + return Checked { errors: out, complete: false, skipped }; } crate::control::reached(i); let Some(g) = ds.features.get(*r).and_then(|f| f.geometry.as_ref()) else { continue }; @@ -266,12 +269,18 @@ pub fn self_intersections(ds: &Dataset, rows: &[usize]) -> Checked { Geometry::Polygon(polys) => polys.iter().flatten().map(|r| (r.clone(), true)).collect(), _ => Vec::new(), }; + let mut row_omitted = false; for (p, closed) in paths { - let m: Vec = p.iter().map(|c| to_plane(*c)).collect(); + // Keep non-finite input vertices non-finite before projection: `lonlat_to_plane` + // clamps latitudes to +/-90 and would otherwise turn +/-inf into a finite point. + let m: Vec = p.iter().map(|c| if c.is_finite() { to_plane(*c) } else { Coord::new(f64::NAN, f64::NAN) }).collect(); let found = match self_crossing(&m, closed) { - Ok(c) => c, + Ok((c, omitted)) => { + row_omitted |= omitted; + c + } // Stopped by Cancel, not by the limit: nothing to list (the run is dropped). - Err(_) if crate::control::cancelled() => return Checked::partial(out), + Err(_) if crate::control::cancelled() => return Checked { errors: out, complete: false, skipped }, Err(start) => { limited = true; Some(start) @@ -282,11 +291,14 @@ pub fn self_intersections(ds: &Dataset, rows: &[usize]) -> Checked { break; } } + if row_omitted { + skipped += 1; + } if out.len() >= MAX_ERRORS { - return Checked::partial(out); + return Checked { errors: out, complete: false, skipped }; } } - if limited { Checked::partial(out) } else { Checked::done(out) } + Checked { errors: out, complete: !limited && skipped == 0, skipped } } /// Line ends that touch no other line (within `tol_m` metres). Line parts are indexed on a grid, @@ -1700,7 +1712,27 @@ mod tests { } let mut clean = Dataset::new("l", GeometryType::Polyline, vec![]); clean.push(Some(Geometry::Line(vec![path.clone()])), vec![]); - assert!(self_intersections(&clean, &[0]).errors.is_empty()); + let clean_res = self_intersections(&clean, &[0]); + assert!(clean_res.errors.is_empty()); + assert!(!clean_res.complete, "omitted non-finite segments mark check incomplete"); + assert_eq!(clean_res.skipped, 1); + + // An infinite latitude must be filtered before projection, not clamped to +90 deg into a + // spurious crossing. + let mut inf_ds = Dataset::new("inf", GeometryType::Polyline, vec![]); + inf_ds.push( + Some(Geometry::Line(vec![vec![ + Coord::new(0.0, 0.0), + Coord::new(1.0, f64::INFINITY), + Coord::new(1.0, 0.0), + Coord::new(0.0, 1.0), + ]])), + vec![], + ); + let inf_res = self_intersections(&inf_ds, &[0]); + assert!(inf_res.errors.is_empty(), "infinite vertex must not create a spurious crossing"); + assert!(!inf_res.complete); + assert_eq!(inf_res.skipped, 1); // Add a genuine self-crossing among the finite segments. path.push(Coord::new(f64::NAN, f64::NAN)); @@ -1713,5 +1745,7 @@ mod tests { let res = self_intersections(&crossing, &[0]); assert_eq!(res.errors.len(), 1); assert!((res.errors[0].at.x - 5.05).abs() < 1e-4); + assert!(!res.complete); + assert_eq!(res.skipped, 1); } } diff --git a/crates/geom/src/triangulate.rs b/crates/geom/src/triangulate.rs index d50bf5d308..782fc15b46 100644 --- a/crates/geom/src/triangulate.rs +++ b/crates/geom/src/triangulate.rs @@ -96,6 +96,16 @@ fn blocks_bridge(pm: (f64, f64), v: (f64, f64), a: (f64, f64), b: (f64, f64)) -> false } +/// Nearest vertices before and after `pos` in `ring` whose coordinates differ from `pts[ring[pos]]`, +/// wrapping around the ring. Returns `None` when every vertex in `ring` coincides with `pos`. +fn distinct_neighbors(pts: &[(f64, f64)], ring: &[usize], pos: usize) -> Option<((f64, f64), (f64, f64))> { + let n = ring.len(); + let cur = pts[ring[pos]]; + let prev = (1..n).map(|step| pts[ring[(pos + n - step) % n]]).find(|&p| p != cur)?; + let next = (1..n).map(|step| pts[ring[(pos + step) % n]]).find(|&p| p != cur)?; + Some((prev, next)) +} + /// Triangles (indices into `outer` followed by each hole's vertices, in order) covering the polygon. /// Rings are open (no repeated closing vertex). `None` when the polygon is degenerate or too large. pub fn triangulate(outer: &[(f64, f64)], holes: &[Vec<(f64, f64)>]) -> Option> { @@ -139,9 +149,7 @@ pub fn triangulate_reporting(outer: &[(f64, f64)], holes: &[Vec<(f64, f64)>]) -> for (hi, h) in hole_rings.iter().enumerate() { let (mpos, &m) = h.iter().enumerate().max_by(|a, b| pts[*a.1].0.total_cmp(&pts[*b.1].0))?; let pm = pts[m]; - let hn = h.len(); - let h_prev = pts[h[(mpos + hn - 1) % hn]]; - let h_next = pts[h[(mpos + 1) % hn]]; + let (h_prev, h_next) = distinct_neighbors(&pts, h, mpos)?; let edges_clear = |v: (f64, f64), work: &mut usize| { let ring_ok = (0..ring.len()).all(|k| { *work += 1; @@ -156,15 +164,15 @@ pub fn triangulate_reporting(outer: &[(f64, f64)], holes: &[Vec<(f64, f64)>]) -> }); ring_ok && holes_ok }; - let rn = ring.len(); let mut best: Option<(usize, f64)> = None; for (k, &vi) in ring.iter().enumerate() { let v = pts[vi]; if !in_interior_wedge(h_prev, pm, h_next, v) { continue; } - let r_prev = pts[ring[(k + rn - 1) % rn]]; - let r_next = pts[ring[(k + 1) % rn]]; + let Some((r_prev, r_next)) = distinct_neighbors(&pts, &ring, k) else { + continue; + }; if !in_interior_wedge(r_prev, v, r_next, pm) { continue; } @@ -349,5 +357,14 @@ mod tests { for pt in [(2.0, 5.0), (6.0, 5.0)] { assert!(!tris2.iter().any(|t| in_triangle(pt, all2[t[0]], all2[t[1]], all2[t[2]]))); } + + // Repeated consecutive coordinates at the hole's rightmost vertex must not produce a + // zero-length wedge edge and fail bridging. + let dup_hole = vec![(6.0, 4.0), (8.0, 5.0), (8.0, 5.0), (6.0, 6.0)]; + let all3: Vec<(f64, f64)> = sq.iter().chain(&dup_hole).copied().collect(); + let (tris3, fanned3) = triangulate_reporting(&sq, std::slice::from_ref(&dup_hole)).unwrap(); + assert!(!fanned3, "hole with repeated rightmost vertex should bridge cleanly"); + assert!((area(&all3, &tris3) - 98.0).abs() < 1e-9, "expected area 98, got {}", area(&all3, &tris3)); + assert!(!tris3.iter().any(|t| in_triangle((6.5, 5.0), all3[t[0]], all3[t[1]], all3[t[2]]))); } } From dce3978a296f9c7dd85920f871e2d4e898b405ad Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 28 Nov 2026 21:41:19 -0500 Subject: [PATCH 4/7] Address review: hole bridging, profile longitudes, Silverman copy - triangulate: skip a hole whose vertices all coincide; splice a hole in with a zero-length bridge where its rightmost vertex is on the ring; compute each ring position's distinct neighbors in one pass per hole and test distance before the lookup. - profile: fold leg direction and sample longitude with fold_lon, so longitudes any number of turns apart take the short arc. - silverman_bandwidth: filter points on each pass instead of copying them. --- crates/analysis/src/density.rs | 11 ++-- crates/analysis/src/rasterops.rs | 27 ++++---- crates/geom/src/triangulate.rs | 104 ++++++++++++++++++++++++++----- 3 files changed, 110 insertions(+), 32 deletions(-) diff --git a/crates/analysis/src/density.rs b/crates/analysis/src/density.rs index c6549f7917..4fd4b7da78 100644 --- a/crates/analysis/src/density.rs +++ b/crates/analysis/src/density.rs @@ -75,23 +75,24 @@ pub fn silverman_bandwidth(points: &[(Coord, f64)], extent: &Extent) -> f64 { if span.is_finite() && span > 1e-4 { (span / 30.0).max(1e-4) } else { 1000.0 } }; - let valid: Vec<(Coord, f64)> = points.iter().copied().filter(|(p, w)| p.is_finite() && w.is_finite() && *w > 0.0).collect(); - let n = valid.len(); + // Filtered on each pass rather than collected, so no second copy of the points is held. + let valid = || points.iter().copied().filter(|(p, w)| p.is_finite() && w.is_finite() && *w > 0.0); + let n = valid().count(); if n < 2 { return fallback(); } - let (sum_x, sum_y, sum_w) = valid.iter().fold((0.0, 0.0, 0.0), |(sx, sy, sw), (p, w)| (sx + p.x * w, sy + p.y * w, sw + w)); + let (sum_x, sum_y, sum_w) = valid().fold((0.0, 0.0, 0.0), |(sx, sy, sw), (p, w)| (sx + p.x * w, sy + p.y * w, sw + w)); if sum_w <= 0.0 || !sum_w.is_finite() || !sum_x.is_finite() || !sum_y.is_finite() { return fallback(); } let mean_x = sum_x / sum_w; let mean_y = sum_y / sum_w; - let sum_sq_dist = valid.iter().fold(0.0, |acc, (p, w)| acc + w * ((p.x - mean_x).powi(2) + (p.y - mean_y).powi(2))); + let sum_sq_dist = valid().fold(0.0, |acc, (p, w)| acc + w * ((p.x - mean_x).powi(2) + (p.y - mean_y).powi(2))); let std_dist = (sum_sq_dist / sum_w).sqrt(); - let mut dists: Vec<(f64, f64)> = valid.iter().map(|(p, w)| (((p.x - mean_x).powi(2) + (p.y - mean_y).powi(2)).sqrt(), *w)).collect(); + let mut dists: Vec<(f64, f64)> = valid().map(|(p, w)| (((p.x - mean_x).powi(2) + (p.y - mean_y).powi(2)).sqrt(), w)).collect(); dists.sort_by(|a, b| a.0.total_cmp(&b.0)); let half_w = sum_w * 0.5; diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index 43bd97f849..dc68512739 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -630,6 +630,8 @@ pub fn elevation_at(r: &Raster, b: usize, ll: Coord) -> Option { } /// An elevation profile along a path: (distance from the start in metres, point, elevation). +/// Each leg runs the short way round the globe, so one crossing the antimeridian stays near it, +/// and the sample longitudes are given in -180..180 whatever range the path is given in. pub fn profile(r: &Raster, b: usize, path: &[Coord], samples: usize) -> Vec<(f64, Coord, Option)> { let samples = samples.clamp(2, 10_000); if path.iter().any(|p| !p.is_finite()) { @@ -659,18 +661,8 @@ pub fn profile(r: &Raster, b: usize, path: &[Coord], samples: usize) -> Vec<(f64 let t = if len > 0.0 { ((d - acc) / len).clamp(0.0, 1.0) } else { 0.0 }; let at = match (path.get(li), path.get(li + 1)) { (Some(a), Some(c)) => { - let mut dx = c.x - a.x; - if dx > 180.0 { - dx -= 360.0; - } else if dx < -180.0 { - dx += 360.0; - } - let mut x = a.x + dx * t; - if x > 180.0 { - x -= 360.0; - } else if x < -180.0 { - x += 360.0; - } + // The short way round, however many turns apart the two longitudes are given. + let x = rustgis_geom::fold_lon(a.x + rustgis_geom::fold_lon(c.x - a.x) * t); Coord::new(x, a.y + (c.y - a.y) * t) } _ => path.last().copied().unwrap_or_default(), @@ -4064,5 +4056,16 @@ mod tests { assert!(d.is_finite() && c.is_finite()); assert_eq!(z, Some(250.0), "regional antimeridian raster missed elevation at {c:?}"); } + + // Longitudes given more than 540 degrees apart (359 and -359, i.e. -1 and 1) still run + // the short way, through 0, not round the far side through 180. + let prof_turns = profile(&r, 0, &[Coord::new(359.0, 0.0), Coord::new(-359.0, 0.0)], 11); + assert_eq!(prof_turns.len(), 11); + for &(_, c, z) in &prof_turns { + assert!(c.x.abs() <= 1.0 + 1e-9, "sample left the short arc: {c:?}"); + assert_eq!(z, Some(0.0), "{c:?}"); + } + let mid = prof_turns.get(5).map(|s| s.1.x); + assert!(mid.is_some_and(|x| x.abs() < 1e-9), "{mid:?}"); } } diff --git a/crates/geom/src/triangulate.rs b/crates/geom/src/triangulate.rs index 782fc15b46..e4b3331474 100644 --- a/crates/geom/src/triangulate.rs +++ b/crates/geom/src/triangulate.rs @@ -106,6 +106,39 @@ fn distinct_neighbors(pts: &[(f64, f64)], ring: &[usize], pos: usize) -> Option< Some((prev, next)) } +/// The nearest vertex before and after each position of `ring` that differs from it, as +/// [`distinct_neighbors`] gives them, in one pass round the ring: a vertex repeated in a run +/// shares the neighbors of the run. All `None` when every vertex coincides. +fn ring_neighbors(pts: &[(f64, f64)], ring: &[usize]) -> Vec> { + let n = ring.len(); + let at = |i: usize| pts[ring[i % n]]; + // A position whose predecessor differs from it, to start the walk from. + let Some(s) = (0..n).find(|&i| at(i + n - 1) != at(i)) else { + return vec![None; n]; + }; + let mut prev = vec![(0.0, 0.0); n]; + let mut last = at(s + n - 1); + for step in 0..n { + let i = (s + step) % n; + if step > 0 && at(i + n - 1) != at(i) { + last = at(i + n - 1); + } + prev[i] = last; + } + // The position before `s` has a successor that differs from it; walk back from there. + let e = (s + n - 1) % n; + let mut next = vec![(0.0, 0.0); n]; + let mut last = at(e + 1); + for step in 0..n { + let i = (e + n - step) % n; + if step > 0 && at(i + 1) != at(i) { + last = at(i + 1); + } + next[i] = last; + } + prev.into_iter().zip(next).map(Some).collect() +} + /// Triangles (indices into `outer` followed by each hole's vertices, in order) covering the polygon. /// Rings are open (no repeated closing vertex). `None` when the polygon is degenerate or too large. pub fn triangulate(outer: &[(f64, f64)], holes: &[Vec<(f64, f64)>]) -> Option> { @@ -131,7 +164,8 @@ pub fn triangulate_reporting(outer: &[(f64, f64)], holes: &[Vec<(f64, f64)>]) -> for h in holes { let mut r: Vec = (start..start + h.len()).collect(); start += h.len(); - if h.len() < 3 { + // A hole of fewer than three vertices, or whose vertices all coincide, has no area. + if h.len() < 3 || h.first().is_none_or(|f| h.iter().all(|p| p == f)) { continue; } if area2(h) > 0.0 { @@ -164,20 +198,24 @@ pub fn triangulate_reporting(outer: &[(f64, f64)], holes: &[Vec<(f64, f64)>]) -> }); ring_ok && holes_ok }; - let mut best: Option<(usize, f64)> = None; - for (k, &vi) in ring.iter().enumerate() { - let v = pts[vi]; - if !in_interior_wedge(h_prev, pm, h_next, v) { - continue; - } - let Some((r_prev, r_next)) = distinct_neighbors(&pts, &ring, k) else { - continue; - }; - if !in_interior_wedge(r_prev, v, r_next, pm) { - continue; - } - let d = (v.0 - pm.0).powi(2) + (v.1 - pm.1).powi(2); - if best.is_none_or(|b| d < b.1) { + // A hole touching the ring at its rightmost vertex is spliced in there, with a bridge of + // no length. + let mut best: Option<(usize, f64)> = ring.iter().position(|&vi| pts[vi] == pm).map(|k| (k, 0.0)); + if best.is_none() { + work += ring.len(); + let neighbors = ring_neighbors(&pts, &ring); + for (k, &vi) in ring.iter().enumerate() { + let v = pts[vi]; + let d = (v.0 - pm.0).powi(2) + (v.1 - pm.1).powi(2); + if best.is_some_and(|b| d >= b.1) || !in_interior_wedge(h_prev, pm, h_next, v) { + continue; + } + let Some((r_prev, r_next)) = neighbors.get(k).copied().flatten() else { + continue; + }; + if !in_interior_wedge(r_prev, v, r_next, pm) { + continue; + } let clear = edges_clear(v, &mut work); if work > MAX_WORK { return None; @@ -367,4 +405,40 @@ mod tests { assert!((area(&all3, &tris3) - 98.0).abs() < 1e-9, "expected area 98, got {}", area(&all3, &tris3)); assert!(!tris3.iter().any(|t| in_triangle((6.5, 5.0), all3[t[0]], all3[t[1]], all3[t[2]]))); } + + #[test] + fn a_hole_with_no_area_is_left_out_and_one_touching_the_outer_ring_is_spliced_in() { + let sq = vec![(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]; + // Every vertex of the hole at one point: no area, so the square stays whole. + let dot = vec![(3.0, 3.0); 4]; + let (tris, fanned) = triangulate_reporting(&sq, std::slice::from_ref(&dot)).unwrap(); + let all: Vec<(f64, f64)> = sq.iter().chain(&dot).copied().collect(); + assert!(!fanned); + assert!((area(&all, &tris) - 100.0).abs() < 1e-9, "{}", area(&all, &tris)); + // A hole whose rightmost vertex is the square's corner (10, 10): bridged there with no + // length, and its 1.5 units of area left out. + let touching = vec![(8.0, 9.0), (10.0, 10.0), (9.0, 8.0)]; + let (tris, _) = triangulate_reporting(&sq, std::slice::from_ref(&touching)).unwrap(); + let all: Vec<(f64, f64)> = sq.iter().chain(&touching).copied().collect(); + assert!((area(&all, &tris) - 98.5).abs() < 1e-9, "{}", area(&all, &tris)); + } + + #[test] + fn ring_neighbors_match_distinct_neighbors_and_long_duplicate_runs_stay_bounded() { + let pts = vec![(0.0, 0.0), (1.0, 0.0), (1.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0), (0.0, 0.0)]; + let ring: Vec = (0..pts.len()).collect(); + let all = ring_neighbors(&pts, &ring); + for (k, got) in all.iter().enumerate() { + assert_eq!(*got, distinct_neighbors(&pts, &ring, k), "position {k}"); + } + assert!(ring_neighbors(&[(2.0, 2.0); 3], &[0, 1, 2]).iter().all(Option::is_none)); + // A square whose first corner repeats 2,500 times, with a hole: finishes and covers the + // area between them. + let mut outer = vec![(0.0, 0.0); 2500]; + outer.extend([(10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]); + let hole = vec![(4.0, 4.0), (6.0, 4.0), (6.0, 6.0), (4.0, 6.0)]; + let tris = triangulate(&outer, std::slice::from_ref(&hole)).unwrap(); + let all: Vec<(f64, f64)> = outer.iter().chain(&hole).copied().collect(); + assert!((area(&all, &tris) - 96.0).abs() < 1e-9, "{}", area(&all, &tris)); + } } From fe71348876171283a2c55bd3702120961dd331de Mon Sep 17 00:00:00 2001 From: giswqs Date: Sun, 29 Nov 2026 16:13:55 -0500 Subject: [PATCH 5/7] Splice a hole touching the inside of an outer edge; document the Silverman fallback floor A hole whose rightmost vertex lies on a ring edge (not at a vertex) had no visible bridge under the stricter wedge checks, so triangulation returned None and callers capped the polygon without the hole. Split the edge at that point and splice the hole in with a zero-length bridge. --- crates/analysis/src/density.rs | 7 +++--- crates/geom/src/triangulate.rs | 45 +++++++++++++++++++++++++++++++--- 2 files changed, 46 insertions(+), 6 deletions(-) diff --git a/crates/analysis/src/density.rs b/crates/analysis/src/density.rs index 4fd4b7da78..a13aacfdd1 100644 --- a/crates/analysis/src/density.rs +++ b/crates/analysis/src/density.rs @@ -66,9 +66,10 @@ const DEFAULT_GRID_STEPS: f64 = 250.0; /// h = 0.9 * min(StandardDistance, sqrt(1 / ln(2)) * MedianDistance) * N^(-0.2) /// /// Takes point weights into account for weighted mean center, weighted standard distance, and -/// weighted median distance. Falls back safely and deterministically to extent-based scaling for -/// small samples or identical coordinates (span / 30.0 when extent > 0, or 1000.0 coordinate-space -/// units for single or coincident points). +/// weighted median distance. Only points with finite coordinates and a finite, positive weight +/// count. Falls back safely and deterministically to extent-based scaling for fewer than two such +/// points or identical coordinates (span / 30.0, at least 1e-4, when the span exceeds 1e-4, or +/// 1000.0 coordinate-space units otherwise). pub fn silverman_bandwidth(points: &[(Coord, f64)], extent: &Extent) -> f64 { let fallback = || { let span = extent.width().max(extent.height()); diff --git a/crates/geom/src/triangulate.rs b/crates/geom/src/triangulate.rs index e4b3331474..621a185922 100644 --- a/crates/geom/src/triangulate.rs +++ b/crates/geom/src/triangulate.rs @@ -96,6 +96,19 @@ fn blocks_bridge(pm: (f64, f64), v: (f64, f64), a: (f64, f64), b: (f64, f64)) -> false } +/// Whether `p` lies on segment `a..b` strictly between its ends (within a tolerance relative to +/// the segment's length, as [`blocks_bridge`] takes collinearity). +fn on_edge_interior(p: (f64, f64), a: (f64, f64), b: (f64, f64)) -> bool { + let (dx, dy) = (b.0 - a.0, b.1 - a.1); + let len2 = dx * dx + dy * dy; + if len2 == 0.0 || p == a || p == b { + return false; + } + let c = cross(a, b, p); + let t = (p.0 - a.0) * dx + (p.1 - a.1) * dy; + c * c <= 1e-24 * len2 * len2 && t > 0.0 && t < len2 +} + /// Nearest vertices before and after `pos` in `ring` whose coordinates differ from `pts[ring[pos]]`, /// wrapping around the ring. Returns `None` when every vertex in `ring` coincides with `pos`. fn distinct_neighbors(pts: &[(f64, f64)], ring: &[usize], pos: usize) -> Option<((f64, f64), (f64, f64))> { @@ -184,6 +197,18 @@ pub fn triangulate_reporting(outer: &[(f64, f64)], holes: &[Vec<(f64, f64)>]) -> let (mpos, &m) = h.iter().enumerate().max_by(|a, b| pts[*a.1].0.total_cmp(&pts[*b.1].0))?; let pm = pts[m]; let (h_prev, h_next) = distinct_neighbors(&pts, h, mpos)?; + // A hole touching the ring at its rightmost vertex is spliced in there, with a bridge of + // no length. + let mut best: Option<(usize, f64)> = ring.iter().position(|&vi| pts[vi] == pm).map(|k| (k, 0.0)); + // One touching the inside of a ring edge there is spliced in at that point too: the edge + // is split at it, since no bridge of any length can leave a point on the boundary. + if best.is_none() { + let n = ring.len(); + if let Some(k) = (0..n).find(|&k| on_edge_interior(pm, pts[ring[k]], pts[ring[(k + 1) % n]])) { + ring.insert(k + 1, m); + best = Some((k + 1, 0.0)); + } + } let edges_clear = |v: (f64, f64), work: &mut usize| { let ring_ok = (0..ring.len()).all(|k| { *work += 1; @@ -198,9 +223,6 @@ pub fn triangulate_reporting(outer: &[(f64, f64)], holes: &[Vec<(f64, f64)>]) -> }); ring_ok && holes_ok }; - // A hole touching the ring at its rightmost vertex is spliced in there, with a bridge of - // no length. - let mut best: Option<(usize, f64)> = ring.iter().position(|&vi| pts[vi] == pm).map(|k| (k, 0.0)); if best.is_none() { work += ring.len(); let neighbors = ring_neighbors(&pts, &ring); @@ -315,6 +337,23 @@ mod tests { assert!(!triangulate_reporting(&sq, &[vec![(0.0, 1.0), (2.0, 2.0), (0.0, 3.0)]]).unwrap().1); } + #[test] + fn a_hole_touching_the_inside_of_an_outer_edge_keeps_its_area_out() { + // The hole's rightmost vertex (10, 5) lies on the outer edge (10, 0)..(10, 10), not at a + // vertex: no bridge can leave it, so it is spliced in by splitting that edge. 100 - 2. + let sq = vec![(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]; + let hole = vec![(8.0, 4.0), (10.0, 5.0), (8.0, 6.0)]; + let pts: Vec<(f64, f64)> = sq.iter().chain(&hole).copied().collect(); + let (tris, fanned) = triangulate_reporting(&sq, std::slice::from_ref(&hole)).unwrap(); + assert!(!fanned); + assert!((area(&pts, &tris) - 98.0).abs() < 1e-9, "{}", area(&pts, &tris)); + // Clockwise outer ring too. + let rev: Vec<_> = sq.iter().rev().copied().collect(); + let pts: Vec<(f64, f64)> = rev.iter().chain(&hole).copied().collect(); + let tris = triangulate(&rev, &[hole]).unwrap(); + assert!((area(&pts, &tris) - 98.0).abs() < 1e-9, "{}", area(&pts, &tris)); + } + #[test] fn concave_and_holed_polygons_cover_their_area() { // An L shape (concave): area 3. From de5d17de85db899ae73ad2f62fe97b7fe90877ea Mon Sep 17 00:00:00 2001 From: giswqs Date: Sun, 29 Nov 2026 16:49:50 -0500 Subject: [PATCH 6/7] Fold the simulate polygon-drop notices into one; tidy neural predict analysis.simulate said polygons with no lon/lat place and polygons with an unusable extent in two notices of the same kind; say them in one with the total, naming both reasons when both occur. Document that predict's class means nothing when its probability is NaN, and drop a std check that the clamp above made dead. --- crates/analysis/src/neural.rs | 6 ++++-- crates/engine/src/cmd/workflows.rs | 24 +++++++++++------------- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/crates/analysis/src/neural.rs b/crates/analysis/src/neural.rs index 45526652b6..3ad8b6cd50 100644 --- a/crates/analysis/src/neural.rs +++ b/crates/analysis/src/neural.rs @@ -131,7 +131,9 @@ impl Mlp { Some(best) } - /// The most likely class (0-based) and its probability (`(0, NaN)` when non-finite). + /// The most likely class (0-based) and its probability. When the network overflows the + /// probability is NaN and the class (0) means nothing; [`Mlp::predict_checked`] says so with + /// `None` instead. pub fn predict(&self, x: &[f32]) -> (usize, f32) { self.predict_checked(x).unwrap_or((0, f32::NAN)) } @@ -355,7 +357,7 @@ pub fn train( } let mean: Vec = mean64.iter().map(|m| *m as f32).collect(); let std: Vec = var64.iter().map(|s| ((s / n_samples).sqrt() as f32).max(1e-6)).collect(); - if !mean.iter().chain(&std).all(|v| v.is_finite()) || std.iter().any(|s| *s <= 0.0) { + if !mean.iter().chain(&std).all(|v| v.is_finite()) { return Err("training values are out of range to scale".into()); } // Layers, He-initialised. diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 2d23bff51f..8177a8ff22 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -2560,22 +2560,20 @@ fn simulate(s: &mut Session, p: &Value) -> CmdResult { if let Some(notice) = query_notice { s.notify_text(notice, false); } - if unplaced > 0 { - s.say(rustgis_data::loss::Note::loss( - rustgis_data::loss::LossCode::DroppedFeature, - format!( - "{}: {unplaced} polygon(s) of {source} have a place that can't be given in longitude/latitude, so no points are simulated in them", - ds.name + // One notice for the polygons left without points, whichever the reason (the two are apart: + // an unplaced polygon has no geometry left to measure). + let dropped = unplaced + unusable; + if dropped > 0 { + let why = match (unplaced > 0, unusable > 0) { + (true, false) => "have a place that can't be given in longitude/latitude".to_string(), + (false, true) => "have an empty, zero-area or non-finite extent".to_string(), + _ => format!( + "can't be used ({unplaced} with a place that can't be given in longitude/latitude, {unusable} with an empty, zero-area or non-finite extent)" ), - )); - } - if unusable > 0 { + }; s.say(rustgis_data::loss::Note::loss( rustgis_data::loss::LossCode::DroppedFeature, - format!( - "{}: {unusable} polygon(s) of {source} have an empty, zero-area or non-finite extent, so no points are simulated in them", - ds.name - ), + format!("{}: {dropped} polygon(s) of {source} {why}, so no points are simulated in them", ds.name), )); } let nid = super::layer::add_dataset(s, ds); From f9520ad6c6e8eeb1921c0657c125969eee2e8d1a Mon Sep 17 00:00:00 2001 From: giswqs Date: Sun, 29 Nov 2026 17:20:49 -0500 Subject: [PATCH 7/7] Keep a profile leg's own longitudes when it already runs the short way Folding every sample into -180..180 moved the points a profile returns, so line_of_sight saved a sight line from 190 to 195 degrees at -170 to -165. Only a leg whose ends are more than 180 degrees apart is folded now; the elevation lookup still wraps columns either way. --- crates/analysis/src/rasterops.rs | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index 1c506a5920..aa97b0b4ab 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -617,8 +617,9 @@ pub fn elevation_at(r: &Raster, b: usize, ll: Coord) -> Option { } /// An elevation profile along a path: (distance from the start in metres, point, elevation). -/// Each leg runs the short way round the globe, so one crossing the antimeridian stays near it, -/// and the sample longitudes are given in -180..180 whatever range the path is given in. +/// Each leg runs the short way round the globe, so one crossing the antimeridian stays near it. +/// A leg whose ends are under 180° apart keeps the path's own longitudes (a path given in +/// 0..360 is sampled there); a longer one, which goes round the other way, is given in -180..180. pub fn profile(r: &Raster, b: usize, path: &[Coord], samples: usize) -> Vec<(f64, Coord, Option)> { let samples = samples.clamp(2, 10_000); if path.iter().any(|p| !p.is_finite()) { @@ -648,8 +649,14 @@ pub fn profile(r: &Raster, b: usize, path: &[Coord], samples: usize) -> Vec<(f64 let t = if len > 0.0 { ((d - acc) / len).clamp(0.0, 1.0) } else { 0.0 }; let at = match (path.get(li), path.get(li + 1)) { (Some(a), Some(c)) => { - // The short way round, however many turns apart the two longitudes are given. - let x = rustgis_geom::fold_lon(a.x + rustgis_geom::fold_lon(c.x - a.x) * t); + // A leg already running the short way keeps the path's own longitudes (a sight + // line from 190° to 195° stays there); a longer one goes the short way round, + // however many turns apart its ends are given, in -180..180. + let x = if (c.x - a.x).abs() <= 180.0 { + a.x + (c.x - a.x) * t + } else { + rustgis_geom::fold_lon(a.x + rustgis_geom::fold_lon(c.x - a.x) * t) + }; Coord::new(x, a.y + (c.y - a.y) * t) } _ => path.last().copied().unwrap_or_default(), @@ -4055,6 +4062,17 @@ mod tests { } let mid = prof_turns.get(5).map(|s| s.1.x); assert!(mid.is_some_and(|x| x.abs() < 1e-9), "{mid:?}"); + + // A leg already the short way keeps the path's own longitudes: 190..195 stays there (not + // -170..-165) and still reads the raster, which runs -180..180, at its wrapped columns. + let prof_east = profile(&r, 0, &[Coord::new(178.5, 0.0), Coord::new(181.5, 0.0)], 6); + assert_eq!(prof_east.len(), 6); + for &(_, c, z) in &prof_east { + assert!((178.5..=181.5).contains(&c.x), "sample left the path's frame: {c:?}"); + assert_eq!(z, Some(100.0), "{c:?}"); + } + let prof_frame = profile(&r, 0, &[Coord::new(190.0, 0.0), Coord::new(195.0, 0.0)], 6); + assert!(prof_frame.iter().all(|s| (190.0..=195.0).contains(&s.1.x) && s.2 == Some(0.0)), "{prof_frame:?}"); } /// A DEM in feet sees as far as the same ground in metres: its radius is metres, not feet