From 6401102f92c199c3bbc927ad9f32070e592281b2 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Mon, 23 Nov 2026 08:52:48 +0100 Subject: [PATCH 1/3] Engine paths in a layer's own system: Calculate Geometry x/y, XY Table To Point, networks, Simulate, annotation, plugin features (#2032 C2e-5) --- crates/analysis/src/lib.rs | 5 + crates/analysis/src/network.rs | 25 +++- crates/analysis/src/tools.rs | 125 +++++++++++++++--- crates/analysis/src/tools/network_analysis.rs | 13 +- crates/engine/src/cmd/imagery.rs | 3 +- crates/engine/src/cmd/labels.rs | 67 ++++++++-- crates/engine/src/cmd/plugins.rs | 23 +++- crates/engine/src/cmd/workflows.rs | 15 ++- crates/engine/src/tests.rs | 8 +- crates/engine/src/tests/held_layers.rs | 68 +++++++++- docs/user-guide/analysis.md | 15 ++- docs/user-guide/cartography.md | 3 + docs/user-guide/data.md | 4 +- 13 files changed, 320 insertions(+), 54 deletions(-) diff --git a/crates/analysis/src/lib.rs b/crates/analysis/src/lib.rs index b68ba78319..e36fd32697 100644 --- a/crates/analysis/src/lib.rs +++ b/crates/analysis/src/lib.rs @@ -299,6 +299,11 @@ const OWN_SYSTEM_TOOLS: &[&str] = &[ "kernelDensity", "zonalStats", "tabulateArea", + // A point's x and y in the system's own unit, areas and lengths still on the ground; networks + // searched on the ground, kept under the layer as it is held (#2032 C2e-5). + "calculateGeometry", + "serviceArea", + "odCostMatrix", ]; impl ToolSpec { diff --git a/crates/analysis/src/network.rs b/crates/analysis/src/network.rs index b6b35599a7..1875197b92 100644 --- a/crates/analysis/src/network.rs +++ b/crates/analysis/src/network.rs @@ -176,13 +176,16 @@ static NETWORK: Mutex> = Mutex::new(None); /// Reuses one bounded graph across calls and workers, without retaining the source features. /// Mutable feature access invalidates the weak allocation identity, including in-place edits. +/// The graph is in longitude/latitude, built from `ds` given there ([`Dataset::in_lonlat`]) when +/// it holds its coordinates in another system, and kept under `ds` as it holds them, so a layer +/// in a projected system isn't converted again while its graph is kept (#2032 C2e-5). fn network_for( cache: &Mutex>, ds: &Dataset, rows: &[usize], cost_field: Option, ) -> Result, String> { - network_keyed(cache, ds, rows, cost_field, || Network::build(ds, rows, cost_field)) + network_keyed(cache, ds, rows, cost_field, || Network::build(&*ds.in_lonlat()?, rows, cost_field)) } /// [`network_for`] kept under `ds`'s rows as it holds them (its system, and the datum grids @@ -1579,6 +1582,26 @@ mod tests { assert!(placed.is_some_and(|p| p.seg == 0), "{placed:?}"); } + /// A network held in a projected system is searched in longitude/latitude, its graph built + /// from it converted there and kept under it as it holds it: a later search over it reuses + /// the graph without converting it again (#2032 C2e-5). + #[test] + fn a_held_networks_graph_is_kept_under_it() { + let cache = Mutex::new(None); + let utm = rustgis_data::raster::Crs::Epsg(32632); + let mut ds = Dataset::new("roads", GeometryType::Polyline, vec![]); + ds.push(Some(Geometry::Line(vec![vec![Coord::new(11.5, 48.7), Coord::new(11.51, 48.7), Coord::new(11.51, 48.71)]])), vec![]); + let lonlat = ds.clone(); + ds.hold_in(utm).unwrap(); + let graph = network_for(&cache, &ds, &[0], None).unwrap(); + let converted = ds.in_lonlat().unwrap(); + let Some(Geometry::Line(parts)) = &converted.features[0].geometry else { panic!("a line") }; + assert_eq!(graph.nodes, parts[0], "the graph is in longitude/latitude"); + let Some(Geometry::Line(given)) = &lonlat.features[0].geometry else { panic!("a line") }; + assert!(graph.nodes.iter().zip(&given[0]).all(|(a, b)| (a.x - b.x).abs() < 1e-9 && (a.y - b.y).abs() < 1e-9)); + assert!(Arc::ptr_eq(&graph, &network_for(&cache, &ds, &[0], None).unwrap()), "kept under the held layer"); + } + /// Repeated pairs reuse topology without retaining endpoint edits; every graph input /// invalidates it, even an attribute/geometry mutation with no other strong feature owner. #[test] diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index b3c5bfb32d..f260d1aafb 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -4211,11 +4211,22 @@ fn xy_table_to_point(inp: &dyn Inputs, p: &Json) -> Result { total += 1; let xy = coordinate(ds.value(r, xi)).zip(coordinate(ds.value(r, yi))); read += usize::from(xy.is_some()); - let pt = xy.and_then(|(x, y)| to.to_lonlat(Coord::new(x, y))).filter(|c| c.is_finite() && c.x.abs() <= 180.0 && c.y.abs() <= 90.0); + // Kept as the table gives it, held in its system, where it has a place in + // longitude/latitude (as a CSV file's points are read); in Web Mercator, one it can hold + // there, within 85.05° (as `Dataset::hold_in` takes it). + let max_lat = if crs == Crs::WebMercator { rustgis_geom::MAX_LAT } else { 90.0 }; + let pt = xy + .map(|(x, y)| Coord::new(x, y)) + .filter(|&c| to.to_lonlat(c).is_some_and(|l| l.is_finite() && l.x.abs() <= 180.0 && l.y.abs() <= max_lat)); placed += usize::from(pt.is_some()); // A row without a usable position stays in the layer's table, without a point. out.push_next(pt.map(Geometry::Point), f.attrs.clone()); } + // Its points are held in their own system, which exports use by default (#2032 C2e-5). + if crs != Crs::LonLat { + out.held_in = crs; + out.crs = Some(crs); + } if placed == 0 { return Err(if read == 0 { format!("{}: no row has numbers in both '{}' and '{}'", ds.name, s(p, "x").trim(), s(p, "y").trim()) @@ -6018,10 +6029,29 @@ fn merc_area_perimeter(mp: &MultiPolygon) -> (f64, f64) { /// [`ground_area_perimeter`]), `length_km` to a line layer, and `point_x`/`point_y` (a label point) /// to any other, updating the layer in place. Polygon measurements and ambiguity counts check /// Cancel between features; measuring one feature's rings is an uninterruptible step. +/// +/// In a layer's own projected system ([`Inputs::work_crs`]) the point's x and y are that system's, +/// in its unit, as the layer holds them; areas and lengths are still measured on the ground, each +/// feature given in longitude/latitude for it (#2032 C2e-5). A feature with a place that can't be +/// given there gets no measures, and is counted in a notice. fn calculate_geometry(inp: &dyn Inputs, p: &Json) -> Result { use geo::{Geodesic, Length}; let ds = input(inp, p, "input")?; let mut out = ds.clone(); + // Each geometry in longitude/latitude for its measures: as it is in a run there. + let to = ds.lonlat_conversion()?; + let unplaced = std::sync::atomic::AtomicUsize::new(0); + fn counted<'a>( + to: &rustgis_data::raster::Reprojection, + g: &'a Geometry, + unplaced: &std::sync::atomic::AtomicUsize, + ) -> Option> { + let g = Dataset::converted_to_lonlat(to, g); + if g.is_none() { + unplaced.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + g + } match ds.geometry_type { GeometryType::Polygon => { let fa = out.ensure_field("area_km2", FieldType::Double); @@ -6035,9 +6065,11 @@ fn calculate_geometry(inp: &dyn Inputs, p: &Json) -> Result |_, _, f| { // Validate every winding, including ones without a full-turn edge, in the // cancellable worker pass. An unavailable area needs no further measurement. - let rings = f.geometry.as_ref().map_or(0, Geometry::ambiguous_area_rings); - let measures = if rings == 0 { f.geometry.as_ref().map_or((0.0, 0.0), ground_area_perimeter) } else { (f64::NAN, 0.0) }; - Ok::<_, String>((measures, rings)) + let Some(g) = f.geometry.as_ref() else { return Ok::<_, String>((Some((0.0, 0.0)), 0)) }; + let Some(g) = counted(&to, g, &unplaced) else { return Ok((None, 0)) }; + let rings = g.ambiguous_area_rings(); + let measures = if rings == 0 { ground_area_perimeter(&g) } else { (f64::NAN, 0.0) }; + Ok((Some(measures), rings)) }, )?; let (rings, features) = measured.iter().fold((0usize, 0usize), |(rings, features), (_, count)| { @@ -6049,12 +6081,13 @@ fn calculate_geometry(inp: &dyn Inputs, p: &Json) -> Result ds.name )); } - for (f, ((a, per), _)) in out.features.iter_mut().zip(measured) { + // (A feature that can't be given in longitude/latitude has no measures: empty.) + for (f, (measures, _)) in out.features.iter_mut().zip(measured) { if let Some(v) = f.attrs.get_mut(fa) { - *v = Value::Float(a / 1e6); + *v = measures.map_or(Value::Null, |(a, _)| Value::Float(a / 1e6)); } if let Some(v) = f.attrs.get_mut(fp) { - *v = Value::Float(per / 1e3); + *v = measures.map_or(Value::Null, |(_, per)| Value::Float(per / 1e3)); } } } @@ -6066,15 +6099,16 @@ fn calculate_geometry(inp: &dyn Inputs, p: &Json) -> Result PARALLEL_FEATURES, || (), |_, _, f| { - Ok::<_, String>(match &f.geometry { - Some(Geometry::Line(parts)) => parts.iter().map(|p| Geodesic.length(&lonlat_line(p))).sum::(), + let Some(g) = f.geometry.as_ref() else { return Ok::<_, String>(Some(0.0)) }; + Ok(counted(&to, g, &unplaced).map(|g| match &*g { + Geometry::Line(parts) => parts.iter().map(|p| Geodesic.length(&lonlat_line(p))).sum::(), _ => 0.0, - }) + })) }, )?; for (f, len) in out.features.iter_mut().zip(lengths) { if let Some(v) = f.attrs.get_mut(fl) { - *v = Value::Float(len / 1e3); + *v = len.map_or(Value::Null, |len| Value::Float(len / 1e3)); } } } @@ -6092,11 +6126,16 @@ fn calculate_geometry(inp: &dyn Inputs, p: &Json) -> Result } } } - Ok(ToolResult { - losses: Vec::new(), - output: Output::Update { layer: ds.name.clone(), dataset: out }, - messages: vec![format!("Calculated geometry attributes for {}", ds.name)], - }) + let mut messages = vec![format!("Calculated geometry attributes for {}", ds.name)]; + let unplaced = unplaced.into_inner(); + if unplaced > 0 { + messages.push(format!( + "Calculate Geometry Attributes: {unplaced} feature(s) of {} have a place in {} that can't be given in longitude/latitude, and weren't measured", + ds.name, + to.source().label() + )); + } + Ok(ToolResult { losses: Vec::new(), output: Output::Update { layer: ds.name.clone(), dataset: out }, messages }) } /// The longest separator CONCATENATE joins values with, in bytes: each value adds one, so a long @@ -10728,6 +10767,40 @@ mod tests { /// Calculate Geometry stores full-precision values (#513): rounding to 0.01 km² gave every /// polygon under half a hectare an area of 0, and lines under 5 m a length of 0. + /// A layer held in a projected system: a polygon is measured on the ground from its places in + /// longitude/latitude, as the same polygon held there is, and one with a place that has none + /// there gets no measures, said in a notice (#2032 C2e-5). + #[test] + fn calculate_geometry_measures_a_held_layer_on_the_ground() { + let (utm, c) = (Crs::Epsg(32632), Coord::new); + let square = + |x: f64, y: f64| Geometry::Polygon(vec![vec![vec![c(x, y), c(x + 0.01, y), c(x + 0.01, y + 0.01), c(x, y + 0.01), c(x, y)]]]); + let mut lonlat = Dataset::new("parcels", GeometryType::Polygon, vec![]); + lonlat.push(Some(square(11.5, 48.7)), vec![]); + let mut held = lonlat.clone(); + held.hold_in(utm).unwrap(); + // Far beyond any place on Earth in UTM. + held.push(Some(Geometry::Polygon(vec![vec![vec![c(1e12, 0.0), c(1e12 + 1.0, 0.0), c(1e12, 1.0), c(1e12, 0.0)]]])), vec![]); + let measured = |ds: Dataset| { + let r = crate::run( + "calculateGeometry", + &Map(HashMap::from([("parcels".to_string(), ds)])), + &serde_json::json!({"input": "parcels"}), + ) + .unwrap(); + let messages = r.messages.clone(); + let out = layer(r); + ((0..out.features.len()).map(|i| (out.value(i, 0).clone(), out.value(i, 1).clone())).collect::>(), messages) + }; + let (expected, said) = measured(lonlat); + assert_eq!(said.len(), 1, "{said:?}"); + let (got, said) = measured(held); + let (Value::Float(a), Value::Float(b)) = (&got[0].0, &expected[0].0) else { panic!("{got:?}") }; + assert!((a - b).abs() < 1e-9 * b, "{a} vs {b}"); + assert_eq!(got[1], (Value::Null, Value::Null), "not measured"); + assert!(said.iter().any(|m| m.contains("1 feature(s) of parcels") && m.contains("weren't measured")), "{said:?}"); + } + #[test] fn calculate_geometry_keeps_small_values() { // A square of about 50 m (0.00045°) at the equator, and one of its sides as a line. @@ -12759,13 +12832,31 @@ mod tests { assert_eq!(points, [Some((-74.08, 4.6)), Some((-75.5, 6.25)), Some((-76.0, 3.0)), None, None, None, None]); assert_eq!(out.value(3, 0), &Value::Text("words".into()), "rows without a point keep their attributes"); - // Another coordinate system, and the output's name. + // Another coordinate system, and the output's name: the points are kept as the table + // gives them, held in it, 10° east on the equator in longitude/latitude. let out = layer(run(serde_json::json!({"input": "metres", "x": "e", "y": "n", "crs": "EPSG:3857", "output": "East"})).unwrap()); assert_eq!(out.name, "East"); + assert_eq!((out.coord_crs(), out.crs), (Crs::WebMercator, Some(Crs::WebMercator))); match out.features.first().and_then(|f| f.geometry.as_ref()) { + Some(Geometry::Point(c)) => assert_eq!((c.x, c.y), (1_113_194.9, 0.0)), + g => panic!("{g:?}"), + } + match out.in_lonlat().unwrap().features.first().and_then(|f| f.geometry.as_ref()) { Some(Geometry::Point(c)) => assert!((c.x - 10.0).abs() < 1e-6 && c.y.abs() < 1e-6, "{c:?}"), g => panic!("{g:?}"), } + // Web Mercator holds no place beyond 85.05°: a row there gets no point. + let mut polar = + Dataset::new("polar", GeometryType::None, vec![Field::new("e", FieldType::Double), Field::new("n", FieldType::Double)]); + polar.push(None, vec![Value::Float(0.0), Value::Float(0.0)]); + polar.push(None, vec![Value::Float(0.0), Value::Float(3.0e7)]); + let m2 = Map(HashMap::from([("polar".to_string(), polar)])); + let r = crate::run("xyTableToPoint", &m2, &serde_json::json!({"input": "polar", "x": "e", "y": "n", "crs": "EPSG:3857"})).unwrap(); + assert!(r.messages.iter().any(|m| m.starts_with("1 of 2 rows")), "{:?}", r.messages); + assert!(layer(r).features[1].geometry.is_none()); + // Points in longitude/latitude are held there, with no system of their own, as before. + let lonlat = layer(run(serde_json::json!({"input": "stops", "x": "lon", "y": "lat", "crs": "EPSG:4326"})).unwrap()); + assert_eq!((lonlat.coord_crs(), lonlat.crs), (Crs::LonLat, None)); // Metres read as longitude/latitude, fields without numbers, and junk parameters. let e = run(serde_json::json!({"input": "metres", "x": "e", "y": "n"})).unwrap_err(); diff --git a/crates/analysis/src/tools/network_analysis.rs b/crates/analysis/src/tools/network_analysis.rs index d54496c7b2..3c921c2108 100644 --- a/crates/analysis/src/tools/network_analysis.rs +++ b/crates/analysis/src/tools/network_analysis.rs @@ -121,6 +121,10 @@ fn place(inp: &dyn Inputs, p: &Json, key: &str, net: &mut Network<'_>, tool: &st Far, } let (graph, snap_m) = (&net.graph, net.snap_m); + // The graph is in longitude/latitude: each point is given there from the system its layer + // holds it in (the one the run works in, [`Inputs::work_crs`]); one that can't be has no + // usable point. + let to = ds.lonlat_conversion()?; crate::control::begin(rows.len()); let got = crate::parallel::try_map( &rows, @@ -137,9 +141,7 @@ fn place(inp: &dyn Inputs, p: &Json, key: &str, net: &mut Network<'_>, tool: &st }, _ => return Ok(Got::NoPoint), }; - if !at.is_finite() || at.y.abs() > 90.0 { - return Ok(Got::NoPoint); - } + let Some(at) = to.point(at).filter(|c| c.is_finite() && c.y.abs() <= 90.0) else { return Ok(Got::NoPoint) }; Ok::<_, String>(graph.place(at, snap_m)?.map_or(Got::Far, |placed| Got::Placed(f.id, placed))) }, )?; @@ -303,7 +305,6 @@ pub(super) fn service_area(inp: &dyn Inputs, p: &Json) -> Result Result Box::new(0..dataset.features.len()), }; // Each vertex converted as `lonlat_extent_of` does it, Cancel looked at every few - // thousand features and vertices. + // thousand features and vertices (in longitude/latitude already, a feature's box is + // taken whole, so there between features only). let to = dataset.lonlat_conversion()?; let (mut e, mut seen, mut unplaced) = (Extent::EMPTY, 0usize, 0usize); let mut cancelled = None; diff --git a/crates/engine/src/cmd/labels.rs b/crates/engine/src/cmd/labels.rs index 78c9018d49..76be067a7d 100644 --- a/crates/engine/src/cmd/labels.rs +++ b/crates/engine/src/cmd/labels.rs @@ -937,10 +937,16 @@ fn convert(s: &mut Session, p: &Value) -> CmdResult { GeometryType::Point, out_fields, ); - // Made in longitude/latitude, then held as the labelled layer is (Dataset::hold_as). + // Made in the labelled layer's own coordinates when it holds them in a projected system, as + // the analysis tools work in it (rustgis_analysis::works_in): a label point found there, as a + // map in that system draws it (#2032 C2e-5). Else made in longitude/latitude, then held as the + // labelled layer is (Dataset::hold_as). let system = (l.dataset.coord_crs(), l.dataset.crs); + let own = rustgis_analysis::works_in(system.0); let mut moved = Vec::new(); let to = l.dataset.lonlat_conversion().map_err(|e| format!("{}: {e}", l.name))?; + // A moved label's place, kept in longitude/latitude, in the layer's own system. + let to_own = if own { Some(rustgis_data::raster::Crs::LonLat.to(system.0).map_err(|e| format!("{}: {e}", l.name))?) } else { None }; // A moved label is drawn where the map puts its place, by the direct operation into the // map's system when there is one (Dataset::shown_through): its annotation is put at the // layer's coordinates the map draws there, given in longitude/latitude through WGS 84 as @@ -949,23 +955,48 @@ fn convert(s: &mut Session, p: &Value) -> CmdResult { Some(_) => Some(l.dataset.shown_from_lonlat().map_err(|e| format!("{}: {e}", l.name))?), None => None, }; - // Those the map's way doesn't reach are put through WGS 84, and said. + // Those the map's way doesn't reach are put through WGS 84, and said; in the layer's own + // system, those WGS 84 can't put there either are left at their feature's label point, and + // said. let astray = std::cell::Cell::new(0usize); - let put_at = |[x, y]: [f64; 2]| { + let unplaced = std::cell::Cell::new(0usize); + let put_at = |[x, y]: [f64; 2], at: Coord| { let c = Coord::new(x, y); - let Some(back) = &shown else { return c }; - back.point(c).and_then(|own| to.point(own)).filter(|l| l.is_finite()).unwrap_or_else(|| { - astray.set(astray.get() + 1); - c - }) + let by_map = shown.as_ref().map(|back| back.point(c).filter(|c| c.is_finite())); + let Some(to_own) = &to_own else { + return match by_map { + None => c, + Some(own) => own.and_then(|own| to.point(own)).filter(|l| l.is_finite()).unwrap_or_else(|| { + astray.set(astray.get() + 1); + c + }), + }; + }; + match by_map { + Some(Some(own)) => own, + by_map => match to_own.point(c).filter(|c| c.is_finite()) { + Some(own) => { + astray.set(astray.get() + usize::from(by_map.is_some())); + own + } + None => { + unplaced.set(unplaced.get() + 1); + at + } + }, + } }; for (row, ft) in l.dataset.features.rows().enumerate() { if rows.get(row) != Some(&true) { continue; } - // In longitude/latitude, as the annotation layer holds its points and moved labels are. + // In the system the annotation layer is made in (above). let Some(g) = ft.geometry() else { continue }; - let g = rustgis_data::Dataset::geometry_to_lonlat_by(&to, g).map_err(|e| format!("{}: feature {}: {e}", l.name, ft.id()))?; + let g = if own { + std::borrow::Cow::Borrowed(g) + } else { + rustgis_data::Dataset::geometry_to_lonlat_by(&to, g).map_err(|e| format!("{}: feature {}: {e}", l.name, ft.id()))? + }; let Some(at) = g.label_point() else { continue }; for (i, class) in matcher.classes_of(&l.dataset, row).filter(|(_, c)| c.visible) { let text = match by_text(i).and_then(|e| e.text_cut(&l.dataset, row)) { @@ -990,7 +1021,7 @@ fn convert(s: &mut Session, p: &Value) -> CmdResult { // A label moved by hand becomes an annotation where it was put, and stays moved there // (its class's offset leaves it). let put = class.moved_to(ft.id()); - let at = put.map_or(at, put_at); + let at = put.map_or(at, |put| put_at(put, at)); let e = exprs.get(i).and_then(Option::as_ref); let number = |v: Option| v.map_or(Attr::Null, |v| Attr::Float(f64::from(v))); if by_size { @@ -1035,6 +1066,12 @@ fn convert(s: &mut Session, p: &Value) -> CmdResult { [("name", ds.name.clone().into()), ("n", astray.get().to_string().into())], ) }); + let unplaced_note = (unplaced.get() > 0).then(|| { + NoticeText::format( + "{name}: {n} moved label(s) that can't be placed in {system} became annotation at their feature's label point", + [("name", ds.name.clone().into()), ("n", unplaced.get().to_string().into()), ("system", system.0.label().into())], + ) + }); let cut_note = (cut > 0).then(|| { format!( "{}: {cut} label text{} cut to {} characters", @@ -1074,7 +1111,11 @@ fn convert(s: &mut Session, p: &Value) -> CmdResult { } let (min_scale, max_scale) = (l.min_scale, l.max_scale); // Before the labelled layer changes, so a cancel leaves it as it was. - super::workflows::hold_as(s, &mut ds, system)?; + if own { + (ds.held_in, ds.crs) = system; + } else { + super::workflows::hold_as(s, &mut ds, system)?; + } if let Some(src) = s.map_mut().layer_mut(id) { src.labels.enabled = false; } @@ -1090,7 +1131,7 @@ fn convert(s: &mut Session, p: &Value) -> CmdResult { if let Some(note) = cut_note { s.notify(note, false); } - for note in [flattened_note, repeated_note, astray_note].into_iter().flatten() { + for note in [flattened_note, repeated_note, astray_note, unplaced_note].into_iter().flatten() { s.notify_text(note, false); } if let Some((_, unread)) = &whole { diff --git a/crates/engine/src/cmd/plugins.rs b/crates/engine/src/cmd/plugins.rs index 13c114babc..adce936bbd 100644 --- a/crates/engine/src/cmd/plugins.rs +++ b/crates/engine/src/cmd/plugins.rs @@ -586,14 +586,16 @@ impl Bridge<'_> { let limit = uint(p, "limit").and_then(|n| usize::try_from(n).ok()).unwrap_or(usize::MAX); let rows: Vec = if b(p, "selected") == Some(true) { l.selection.clone() } else { (0..l.dataset.features.len()).collect() }; // In longitude/latitude, which a response holds unless `crs` asks for another system, - // whatever system the layer holds its coordinates in. + // whatever system the layer holds its coordinates in; as the layer holds them when `crs` + // asks for that one, exactly, with no conversion there and back (#2032 C2e-5). + let own = target.is_some_and(|crs| l.dataset.coord_crs().to(crs).is_ok_and(|to| to.is_identity())); let mut features = rustgis_data::Features::default(); // Made at the first feature with a geometry, once for the layer. let mut conversion = None; for r in rows.iter().take(limit).filter_map(|&i| l.dataset.features.row(i)) { let n = features.len(); features.push_row(r.to_feature()); - let Some(g) = r.geometry() else { continue }; + let Some(g) = r.geometry().filter(|_| !own) else { continue }; let failed = |e: String| format!("{}: feature {}: {e}", l.name, r.id()); let to = match &mut conversion { Some(to) => &*to, @@ -603,8 +605,8 @@ impl Bridge<'_> { features.set_geometry(n, Some(g)); } } - // Its geometry is longitude/latitude (above); `crs` stays the layer's, as the system it - // was read in, which `export_error` reads. + // Its geometry is longitude/latitude, or the layer's own (above); `crs` stays the layer's, + // as the system it was read in, which `export_error` reads. let mut ds = rustgis_data::Dataset { name: l.name.clone(), geometry_type: l.dataset.geometry_type, @@ -615,7 +617,7 @@ impl Bridge<'_> { crs_incomplete: false, zm_dropped: false, windowed: false, - held_in: rustgis_data::raster::Crs::LonLat, + held_in: if own { l.dataset.coord_crs() } else { rustgis_data::raster::Crs::LonLat }, shown_in: None, }; let mut member = None; @@ -643,6 +645,17 @@ impl Bridge<'_> { } let Some(g) = f.geometry.take() else { continue }; let mut ok = true; + if own { + // As the layer holds it: refused only for a missing coordinate, as a + // conversion refuses one. + g.for_each_coord(|c| ok &= c.is_finite()); + if !ok { + failed += 1; + first.get_or_insert(f.id); + } + f.geometry = Some(g); + continue; + } if mercator { g.for_each_coord(|c| ok &= c.y.abs() <= rustgis_geom::MAX_LAT || !c.y.is_finite()); } diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 456b7e43e8..4ce9485f73 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -1962,10 +1962,13 @@ fn simulate(s: &mut Session, p: &Value) -> CmdResult { rustgis_map::rows::Rows::All => (0..l.dataset.features.len()).collect(), rustgis_map::rows::Rows::Subset(rows) => rows, }; - // Placed in longitude/latitude, whatever system the polygons' layer holds its coordinates in, - // then held in that system, as the polygons are. - let polygons = l.dataset.in_lonlat()?; + // Placed in the polygons' own coordinates when their layer holds them in a projected system, + // spread evenly there (#2032 C2e-5), as the analysis tools work in it + // ([`rustgis_analysis::works_in`]); else in longitude/latitude, then held in the layer's + // system, as the polygons are. let system = (l.dataset.coord_crs(), l.dataset.crs); + let own = rustgis_analysis::works_in(system.0); + let polygons = if own { std::borrow::Cow::Borrowed(&l.dataset) } else { l.dataset.in_lonlat()? }; let seed = f(p, "seed").map_or(42, |v| v.max(0.0) as u64); let pts: Vec<(usize, Coord)> = match ps(p, "field") { Some(fname) => { @@ -1995,7 +1998,11 @@ fn simulate(s: &mut Session, p: &Value) -> CmdResult { ds.push(Some(Geometry::Point(*c)), vec![Attr::Int(*r as i64)]); } let n = ds.features.len(); - hold_as(s, &mut ds, system)?; + if own { + (ds.held_in, ds.crs) = system; + } else { + hold_as(s, &mut ds, system)?; + } if let Some(notice) = query_notice { s.notify_text(notice, false); } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e500d55ebb..f83be8901c 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -18926,7 +18926,7 @@ fn plugin_settings_are_erased_by_uninstalling_the_plugin() { fn plugin_host_gives_layer_crs_and_features_in_it() { let mut s = world(); plugin("eng-crs", &["edit"]); - // A layer read in UTM 37N: stored in longitude/latitude, with its own system kept. + // A layer read in UTM 37N, held there. let text = r#"{"type":"FeatureCollection","crs":{"type":"name","properties":{"name":"EPSG:32637"}}, "features":[{"type":"Feature","properties":{},"geometry":{"type":"Point","coordinates":[500000.0,3320000.0]}}]}"#; let (ds, _) = rustgis_data::io::read_geojson(text, "Mine").unwrap(); @@ -18945,11 +18945,13 @@ fn plugin_host_gives_layer_crs_and_features_in_it() { deg["features"][0]["geometry"]["coordinates"][1].as_f64().unwrap(), ); assert!((lon - 39.0).abs() < 1e-6 && (lat - 30.0).abs() < 0.1, "{deg}"); - // "layer": the source's metres, named so host.addLayer reads them back. + // "layer": the source's metres, exactly as the layer holds them (no round trip through + // longitude/latitude), named so host.addLayer reads them back. + assert_eq!(s.map().layer_by_name("Mine").unwrap().dataset.coord_crs().epsg(), 32637); for asked in ["layer", "EPSG:32637", " Layer "] { let m = forward(&mut s, "eng-crs", "host.features", json!({"layer": "Mine", "crs": asked})).unwrap(); let c = &m["features"][0]["geometry"]["coordinates"]; - assert!((c[0].as_f64().unwrap() - 500000.0).abs() < 0.01 && (c[1].as_f64().unwrap() - 3320000.0).abs() < 0.01, "{asked}: {m}"); + assert_eq!((c[0].as_f64().unwrap(), c[1].as_f64().unwrap()), (500000.0, 3320000.0), "{asked}: {m}"); assert_eq!(m["crs"]["properties"]["name"], "EPSG:32637"); assert_eq!(m["features"][0]["row"], 0); } diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index f555191b69..e948a26f80 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -736,6 +736,14 @@ fn a_held_layer_feeds_other_layers_alike() { let (Some(Geometry::Point(p)), Some(Geometry::Point(q))) = (p, q) else { panic!("points") }; assert!((p.x - q.x).abs() < 1e-7 && (p.y - q.y).abs() < 1e-7, "annotation: {p:?} vs {q:?}"); } + // In UTM, the label point is found in the parcels' own coordinates and kept as it is there, + // held in UTM, with no round trip through longitude/latitude (#2032 C2e-5). + let annotation = &ss[1].map().layer_by_name(&nb).unwrap().dataset; + assert_eq!(annotation.coord_crs(), UTM); + let parcels = &ss[1].map().layer_by_name("Parcels").unwrap().dataset; + let points: Vec> = + parcels.features.iter().map(|f| f.geometry.as_ref().and_then(Geometry::label_point).map(Geometry::Point)).collect(); + assert_eq!(annotation.features.iter().map(|f| f.geometry.clone()).collect::>(), points); // Cells off the wells' box's edges (the held layer's is a hair larger: see the extent above). let [a, b] = run_both(&mut ss, "analysis.interpolate", &json!({"layer": "Wells", "field": "n", "cellSize": 0.0015, "crs": "EPSG:4326"})); @@ -754,9 +762,28 @@ fn a_held_layer_feeds_other_layers_alike() { let route = json!({"layer": "Roads", "from": [11.4951, 48.6925], "to": [11.5295, 48.7290], "snapDistance": 100}); let [a, b] = run_both(&mut ss, "analysis.route", &route); assert_close(&lonlat(&ss[0], &made(&ss[0], &a)), &lonlat(&ss[1], &made(&ss[1], &b)), "route"); + // Points simulated in the parcels: spread in each layer's own coordinates (#2032 C2e-5), so + // in UTM they are those spread there, held there, each in its parcel. let [a, b] = run_both(&mut ss, "analysis.simulate", &json!({"layer": "Parcels", "count": 5, "seed": 3})); assert_eq!(a["points"], b["points"]); - assert_close(&lonlat(&ss[0], &made(&ss[0], &a)), &lonlat(&ss[1], &made(&ss[1], &b)), "simulation"); + let parcels = &ss[1].map().layer_by_name("Parcels").unwrap().dataset; + let rows: Vec = (0..parcels.features.len()).collect(); + let spread = rustgis_analysis::network::random_points(parcels, &rows, 5, 3); + let simulated = &ss[1].map().layer(b["layer"].as_u64().unwrap() as u32).unwrap().dataset; + assert_eq!(simulated.coord_crs(), UTM); + let held: Vec<(i64, Coord)> = simulated + .features + .iter() + .map(|f| match (&f.attrs[0], &f.geometry) { + (Cell::Int(r), Some(Geometry::Point(c))) => (*r, *c), + other => panic!("{other:?}"), + }) + .collect(); + assert_eq!(held, spread.iter().map(|&(r, c)| (r as i64, c)).collect::>()); + for (r, c) in held { + let Some(Geometry::Polygon(rings)) = &parcels.features[r as usize].geometry else { panic!("a parcel") }; + assert!(rings.iter().any(|rings| rustgis_data::geometry::polygon_contains(rings, c)), "{c:?} outside parcel {r}"); + } } /// An offline area's edits sync back alike, also when they come back in longitude/latitude (as a @@ -2580,3 +2607,42 @@ fn a_point_its_own_system_cant_give_is_said_as_such() { assert!(said.iter().any(|t| t.contains(&own)), "{said:?}"); assert!(!said.iter().any(|t| t.contains("beyond what")), "{said:?}"); } + +/// Calculate Geometry gives a held point layer's x and y in its own system's unit, as it holds +/// them, and a held polygon's area on the ground; Service Area and OD Cost Matrix search a held +/// network on the ground as one in longitude/latitude (within a millimetre), the service area +/// held in the network's system, and a second search reuses the graph (#2032 C2e-5). +#[test] +fn a_held_layers_points_and_networks_work_in_its_own_system() { + let mut ss = both(); + run_both(&mut ss, "gp.run", &json!({"tool": "calculateGeometry", "params": {"input": "Wells"}})); + let wells = &ss[1].map().layer_by_name("Wells").unwrap().dataset; + let (fx, fy) = (wells.field_index("point_x").unwrap(), wells.field_index("point_y").unwrap()); + for (r, held) in held_coords(&ss[1], "Wells").iter().enumerate() { + assert_eq!((wells.value(r, fx).as_f64(), wells.value(r, fy).as_f64()), (Some(held[0].x), Some(held[0].y)), "well {r}"); + } + assert!(field_numbers(&ss[0], "Wells", "point_x").iter().all(|x| (11.5..11.53).contains(x)), "degrees in longitude/latitude"); + let p = json!({"network": "Roads", "facilities": "Wells", "breaks": "0.5, 1", "snapDistance": 2000}); + let [a, b] = run_both(&mut ss, "gp.run", &json!({"tool": "serviceArea", "params": p})); + assert_eq!(a["messages"], b["messages"]); + assert_eq!(ss[1].map().layer_by_name("Roads_ServiceArea").unwrap().dataset.coord_crs(), UTM); + let [la, lb] = [&ss[0], &ss[1]].map(|s| lonlat(s, "Roads_ServiceArea")); + assert_eq!(la.iter().map(shape).collect::>(), lb.iter().map(shape).collect::>()); + for (g, h) in la.iter().zip(&lb) { + let (mut p, mut q) = (Vec::new(), Vec::new()); + g.as_ref().unwrap().for_each_coord(|c| p.push(c)); + h.as_ref().unwrap().for_each_coord(|c| q.push(c)); + for (p, q) in p.iter().zip(&q) { + assert!(rustgis_geom::wgs84_distance_m(*p, *q) < 1e-3, "{p:?} vs {q:?}"); + } + } + let od = + json!({"tool": "odCostMatrix", "params": {"network": "Roads", "origins": "Wells", "destinations": "Wells", "snapDistance": 2000}}); + run_both(&mut ss, "gp.run", &od); + let costs = |s: &Session| { + let t = &s.project.tables.last().expect("a table").dataset; + let f = t.field_index("cost").unwrap(); + (0..t.features.len()).map(|r| t.value(r, f).as_f64().unwrap()).collect::>() + }; + assert_numbers_close(&costs(&ss[0]), &costs(&ss[1]), 1e-6, "OD costs (km)"); +} diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 64ce1fcef5..2257f96cc7 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -211,7 +211,10 @@ is given; Zonal Statistics and Tabulate Area place their zones on a raster in th are. A surface given another projected system, or a raster in one, gets the points or zones converted straight into it, by the transformation between the two datums where they differ; a raster in longitude/latitude or Web Mercator gets them through WGS 84. Their rasters aren't converted, and -they don't count bent edges. Area, length and perimeter fields stay on the ellipsoid. +they don't count bent edges. Area, length and perimeter fields stay on the ellipsoid. Calculate +Geometry Attributes gives a point's `point_x` and `point_y` in that system's x and y, in its unit, +as the layer holds them. Service Area and OD Cost Matrix still search the network on the ellipsoid, +and the service area's lines are held in the network's system. In the desktop app a tool runs in the background, so the map and the rest of the window stay in use. While it runs, the Tools pane shows its name, a **Cancel** button and, for the tools that @@ -595,7 +598,10 @@ normalized in continuous longitude space, so non-polar regions larger than half keep their full area and small antimeridian crossings stay small. Rings winding around a pole use the smaller polar region in either direction; reversing a ring does not select its global complement. Edges follow the shortest geodesics between vertices. The output fields remain -`area_km2`, `perimeter_km` and `length_km`; point coordinates are unchanged. +`area_km2`, `perimeter_km` and `length_km`; point coordinates are unchanged. A point layer gets +`point_x` and `point_y`: longitude and latitude, or x and y in the projected system the layer is +held in (see above). A feature with a place that can't be given in longitude/latitude isn't +measured, and a notice counts them. A ring through both poles can wind beyond one whole surface and bound no single region. Calculate Geometry Attributes refuses such input, with the numbers of affected rings and features, before changing any fields. The attribute table's Calculate Geometry does the @@ -1226,7 +1232,8 @@ network, as the Network Analysis workflow's route does: lines join where their v line's length is measured on the WGS 84 ellipsoid, and a **Cost Field** multiplies it (a line with no number there costs its length, and one costing 0 or less is closed; each is counted in a notice). Every line can be travelled both ways. The network's selection is honoured, and the graph -is reused while the lines don't change, shared with routes. +is reused while the lines don't change, shared with routes: a network held in a projected system +is converted to longitude/latitude only to build it, not on every run. Points are moved onto the nearest line, at most **Snap Distance** metres (1,000 by default). A feature farther away, with no point, or with several (a multipoint) is left out and counted in a @@ -1579,7 +1586,7 @@ click them on the map: | Geostatistical Wizard | An IDW surface from feature values, using 12 nearest neighbours by default | | Network Analysis | The shortest (or cheapest, by a cost field) route over a line layer | | Neighborhood Explorer | What lies within a distance of a point, with sums of numeric fields | -| Simulation | Random points in polygons (a fixed number, or from a field × rate) | +| Simulation | Random points in polygons (a fixed number, or from a field × rate), spread in the layer's own coordinates when it is held in a projected system, else in longitude/latitude | | Data Engineering | Counts, nulls, distinct values, min, max and mean of every field | | Exploratory Analysis | Histograms and correlations of numeric fields | | Embeddings | The features most like the selected one, by their numeric attributes | diff --git a/docs/user-guide/cartography.md b/docs/user-guide/cartography.md index 82a60e05f7..02e40c4a0e 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -766,6 +766,9 @@ Turn labels on per layer (Labeling › Labels › **Label**), then: - **Convert** (Labeling › Map Labeling, or Layers › right-click › **Convert To Annotation**) turns a layer's labels into an annotation layer: one point per label, carrying its text in a `TEXT` field, which you can then edit, move or delete like any other features. + The annotation layer is held in the labelled layer's system. In a projected system a label's + point is found in its own coordinates, where a map in that system draws it; a moved label that + can't be placed there stays at its feature's label point, and the conversion says how many. A label along a line becomes an upright point at its line's middle vertex (the end of a line of two), which can be some way from where the label was drawn: its angle, curve, repeats and distance from the line are left out, and the conversion says how many, and how many of them diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index 3cd7b79fce..9d867d3716 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -139,7 +139,9 @@ name, which stands for the first table of that name. An id given as a number is a name. The Tools pane and Geocode Addresses send the id of the table picked; a tool's run keeps the table's name beside it (`input_name`). The **XY Table To Point** tool ([Geoprocessing](analysis.md), and a table's right-click menu) makes points of a table already in -the project, from two fields of coordinates and their coordinate system. In a text field a single comma is the decimal separator +the project, from two fields of coordinates and their coordinate system. The points keep the table's +numbers, held in that system, which exports use by default; a row whose numbers have no place in +longitude/latitude gets no point. In a text field a single comma is the decimal separator (`1,234` is 1.234); thousands separators are not read. **Use a polygon's published interior point.** To place TIGER interior points, run **XY Table From 07a7fc9721fde1de9ad5b5624226e7bddb334278 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Mon, 23 Nov 2026 09:48:35 +0100 Subject: [PATCH 2/3] Review: one shared plugin loop, graph built per line, beyond-the-poles unmeasured, unplaced moved labels not kept moved, Cancel before simulated points are kept --- crates/analysis/src/network.rs | 21 +++++++++++++------ crates/analysis/src/tools.rs | 24 ++++++++++++++++------ crates/engine/src/cmd/labels.rs | 24 +++++++++++++--------- crates/engine/src/cmd/plugins.rs | 18 +++++------------ crates/engine/src/cmd/workflows.rs | 3 +++ crates/engine/src/tests/held_layers.rs | 28 ++++++++++++++++++++++++++ docs/user-guide/analysis.md | 4 ++-- xtask/row-uses.txt | 2 +- 8 files changed, 87 insertions(+), 37 deletions(-) diff --git a/crates/analysis/src/network.rs b/crates/analysis/src/network.rs index 1875197b92..17e273f33a 100644 --- a/crates/analysis/src/network.rs +++ b/crates/analysis/src/network.rs @@ -80,8 +80,12 @@ fn cost_overflows(parts: &[Vec], weight: f64, pace: &mut crate::control:: } impl Network { - /// Builds edges in source order, preserving shortest-path tie breaking and arithmetic. + /// Builds edges in source order, preserving shortest-path tie breaking and arithmetic. In + /// longitude/latitude: a layer held in another system has each line given there as it is read + /// (no copy of the layer); the segments of one with a place that has none there are left out, + /// counted as segments with invalid coordinates. fn build(ds: &Dataset, rows: &[usize], cost_field: Option) -> Result { + let to = ds.lonlat_conversion()?; let route_error = |reason, skipped, overflowing| route_error(ds, reason, skipped, overflowing); let mut skipped_segments = 0; let mut overflowing = 0; @@ -101,7 +105,12 @@ impl Network { for (i, r) in rows.iter().enumerate() { crate::control::check()?; crate::control::reached(i); - let Some(Geometry::Line(parts)) = ds.features.get(*r).and_then(|f| f.geometry.as_ref()) else { continue }; + let Some(line @ Geometry::Line(held)) = ds.features.get(*r).and_then(|f| f.geometry.as_ref()) else { continue }; + let Some(line) = Dataset::converted_to_lonlat(&to, line) else { + skipped_segments += held.iter().map(|part| part.len().saturating_sub(1)).sum::(); + continue; + }; + let Geometry::Line(parts) = &*line else { continue }; // A cost multiplies each edge's length; no value means 1, and zero or less closes the // line (impassable). let weight = match cost_field.map(|fi| ds.value(*r, fi).as_f64()) { @@ -176,16 +185,16 @@ static NETWORK: Mutex> = Mutex::new(None); /// Reuses one bounded graph across calls and workers, without retaining the source features. /// Mutable feature access invalidates the weak allocation identity, including in-place edits. -/// The graph is in longitude/latitude, built from `ds` given there ([`Dataset::in_lonlat`]) when -/// it holds its coordinates in another system, and kept under `ds` as it holds them, so a layer -/// in a projected system isn't converted again while its graph is kept (#2032 C2e-5). +/// The graph is in longitude/latitude, each line given there as it is built when `ds` holds its +/// coordinates in another system ([`Network::build`]), and kept under `ds` as it holds them, so a +/// layer in a projected system isn't converted again while its graph is kept (#2032 C2e-5). fn network_for( cache: &Mutex>, ds: &Dataset, rows: &[usize], cost_field: Option, ) -> Result, String> { - network_keyed(cache, ds, rows, cost_field, || Network::build(&*ds.in_lonlat()?, rows, cost_field)) + network_keyed(cache, ds, rows, cost_field, || Network::build(ds, rows, cost_field)) } /// [`network_for`] kept under `ds`'s rows as it holds them (its system, and the datum grids diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index f260d1aafb..0106484dc1 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -6033,7 +6033,7 @@ fn merc_area_perimeter(mp: &MultiPolygon) -> (f64, f64) { /// In a layer's own projected system ([`Inputs::work_crs`]) the point's x and y are that system's, /// in its unit, as the layer holds them; areas and lengths are still measured on the ground, each /// feature given in longitude/latitude for it (#2032 C2e-5). A feature with a place that can't be -/// given there gets no measures, and is counted in a notice. +/// given there, or is given beyond the poles, gets no measures, and is counted in a notice. fn calculate_geometry(inp: &dyn Inputs, p: &Json) -> Result { use geo::{Geodesic, Length}; let ds = input(inp, p, "input")?; @@ -6046,7 +6046,13 @@ fn calculate_geometry(inp: &dyn Inputs, p: &Json) -> Result g: &'a Geometry, unplaced: &std::sync::atomic::AtomicUsize, ) -> Option> { - let g = Dataset::converted_to_lonlat(to, g); + // A place given beyond the poles (a latitude past ±90°) has none either; a missing + // coordinate is measured as it always was. + let g = Dataset::converted_to_lonlat(to, g).filter(|g| { + let mut placed = true; + g.for_each_coord(|c| placed &= !(c.is_finite() && c.y.abs() > 90.0)); + placed + }); if g.is_none() { unplaced.fetch_add(1, std::sync::atomic::Ordering::Relaxed); } @@ -6130,7 +6136,7 @@ fn calculate_geometry(inp: &dyn Inputs, p: &Json) -> Result let unplaced = unplaced.into_inner(); if unplaced > 0 { messages.push(format!( - "Calculate Geometry Attributes: {unplaced} feature(s) of {} have a place in {} that can't be given in longitude/latitude, and weren't measured", + "Calculate Geometry Attributes: {unplaced} feature(s) of {} have a place with no longitude/latitude (beyond the poles, or one {} can't give there), and weren't measured", ds.name, to.source().label() )); @@ -10742,7 +10748,13 @@ mod tests { vec![], ); let inputs = Map(HashMap::from([("invalid".into(), ds)])); - assert!(crate::run("calculateGeometry", &inputs, &serde_json::json!({"input":"invalid"})).is_ok()); + let r = crate::run("calculateGeometry", &inputs, &serde_json::json!({"input":"invalid"})).unwrap(); + // A latitude past 90° has no place: no measures, and a notice; a missing coordinate is + // measured as before, and said nothing of. + let beyond = bad.is_finite(); + assert_eq!(r.messages.iter().any(|m| m.contains("weren't measured")), beyond, "{bad:?}: {:?}", r.messages); + let out = layer(r); + assert_eq!(out.value(0, 0).is_null(), beyond, "{bad:?}"); } } @@ -10765,8 +10777,6 @@ mod tests { assert_eq!(out.features[0].geometry, ds.features[0].geometry); } - /// Calculate Geometry stores full-precision values (#513): rounding to 0.01 km² gave every - /// polygon under half a hectare an area of 0, and lines under 5 m a length of 0. /// A layer held in a projected system: a polygon is measured on the ground from its places in /// longitude/latitude, as the same polygon held there is, and one with a place that has none /// there gets no measures, said in a notice (#2032 C2e-5). @@ -10801,6 +10811,8 @@ mod tests { assert!(said.iter().any(|m| m.contains("1 feature(s) of parcels") && m.contains("weren't measured")), "{said:?}"); } + /// Calculate Geometry stores full-precision values (#513): rounding to 0.01 km² gave every + /// polygon under half a hectare an area of 0, and lines under 5 m a length of 0. #[test] fn calculate_geometry_keeps_small_values() { // A square of about 50 m (0.00045°) at the equator, and one of its sides as a line. diff --git a/crates/engine/src/cmd/labels.rs b/crates/engine/src/cmd/labels.rs index 76be067a7d..0682733669 100644 --- a/crates/engine/src/cmd/labels.rs +++ b/crates/engine/src/cmd/labels.rs @@ -960,28 +960,29 @@ fn convert(s: &mut Session, p: &Value) -> CmdResult { // said. let astray = std::cell::Cell::new(0usize); let unplaced = std::cell::Cell::new(0usize); - let put_at = |[x, y]: [f64; 2], at: Coord| { + // `None` for one left at its feature's label point, which isn't moved there any more. + let put_at = |[x, y]: [f64; 2]| -> Option { let c = Coord::new(x, y); let by_map = shown.as_ref().map(|back| back.point(c).filter(|c| c.is_finite())); let Some(to_own) = &to_own else { - return match by_map { + return Some(match by_map { None => c, Some(own) => own.and_then(|own| to.point(own)).filter(|l| l.is_finite()).unwrap_or_else(|| { astray.set(astray.get() + 1); c }), - }; + }); }; match by_map { - Some(Some(own)) => own, + Some(Some(own)) => Some(own), by_map => match to_own.point(c).filter(|c| c.is_finite()) { Some(own) => { astray.set(astray.get() + usize::from(by_map.is_some())); - own + Some(own) } None => { unplaced.set(unplaced.get() + 1); - at + None } }, } @@ -1020,8 +1021,13 @@ fn convert(s: &mut Session, p: &Value) -> CmdResult { } // A label moved by hand becomes an annotation where it was put, and stays moved there // (its class's offset leaves it). - let put = class.moved_to(ft.id()); - let at = put.map_or(at, |put| put_at(put, at)); + // One that can't be placed in the layer's own system stays at its label point, and + // isn't moved in the annotation's labels either. + let was_moved = class.moved_to(ft.id()).is_some(); + let (put, at) = match class.moved_to(ft.id()).map(|put| (put, put_at(put))) { + Some((put, Some(to))) => (Some(put), to), + Some((_, None)) | None => (None, at), + }; let e = exprs.get(i).and_then(Option::as_ref); let number = |v: Option| v.map_or(Attr::Null, |v| Attr::Float(f64::from(v))); if by_size { @@ -1036,7 +1042,7 @@ fn convert(s: &mut Session, p: &Value) -> CmdResult { attrs.push(number(e.filter(|_| turns).and_then(|e| e.angle(&l.dataset, row)))); } ds.push(Some(Geometry::Point(at)), attrs); - let flat = put.is_none() && along(class, ft.geometry()); + let flat = !was_moved && along(class, ft.geometry()); flattened += usize::from(flat); repeated += usize::from(flat && class.repeat.is_some()); if let (Some(put), Some(new)) = (put, ds.features.last()) { diff --git a/crates/engine/src/cmd/plugins.rs b/crates/engine/src/cmd/plugins.rs index adce936bbd..4ade73bbf7 100644 --- a/crates/engine/src/cmd/plugins.rs +++ b/crates/engine/src/cmd/plugins.rs @@ -645,21 +645,13 @@ impl Bridge<'_> { } let Some(g) = f.geometry.take() else { continue }; let mut ok = true; - if own { - // As the layer holds it: refused only for a missing coordinate, as a - // conversion refuses one. - g.for_each_coord(|c| ok &= c.is_finite()); - if !ok { - failed += 1; - first.get_or_insert(f.id); - } - f.geometry = Some(g); - continue; - } - if mercator { + // As the layer holds it when that is the system asked for: refused only for a + // missing coordinate, as a conversion refuses one. + if mercator && !own { g.for_each_coord(|c| ok &= c.y.abs() <= rustgis_geom::MAX_LAT || !c.y.is_finite()); } - let g = if ok { g.map_coords(&|c| t.from_lonlat(c).unwrap_or(crate::geom::Coord::new(f64::NAN, f64::NAN))) } else { g }; + let g = + if ok && !own { g.map_coords(&|c| t.from_lonlat(c).unwrap_or(crate::geom::Coord::new(f64::NAN, f64::NAN))) } else { g }; g.for_each_coord(|c| ok &= c.is_finite()); if !ok { failed += 1; diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 4ce9485f73..d4a54a8f5b 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -1999,6 +1999,9 @@ fn simulate(s: &mut Session, p: &Value) -> CmdResult { } let n = ds.features.len(); if own { + // A cancel stops the sampling with the points made so far: none of them is added, as the + // conversion below refuses them then. + rustgis_data::progress::check().map_err(|e| e.to_string())?; (ds.held_in, ds.crs) = system; } else { hold_as(s, &mut ds, system)?; diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index e948a26f80..4496fde5d2 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -2646,3 +2646,31 @@ fn a_held_layers_points_and_networks_work_in_its_own_system() { }; assert_numbers_close(&costs(&ss[0]), &costs(&ss[1]), 1e-6, "OD costs (km)"); } + +/// A label moved to a place the layer's own system can't hold (the South Pole, for the NSIDC +/// north polar stereographic system) becomes annotation at its feature's label point, isn't moved there in the +/// annotation's labels, and is said; with every label placed, nothing is said (#2032 C2e-5). +#[test] +fn a_moved_label_the_layers_system_cant_hold_is_said() { + let polar = Crs::Epsg(3413); + for (to, said) in [([11.0, -90.0], true), ([11.51, 48.71], false)] { + let mut s = session(polar); + let l = s.map().layer_by_name("Wells").unwrap(); + let moved = l.dataset.features[1].id; + let label_point = l.dataset.features[1].geometry.clone(); + s.run("labels.enable", &json!({"layer": "Wells", "on": true})).unwrap(); + s.run("labels.move", &json!({"layer": "Wells", "feature": moved, "to": to})).unwrap(); + let mark = s.notice_mark(); + let made = s.run("labels.convert", &json!({"layer": "Wells"})).unwrap(); + let notices: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert_eq!(notices.iter().any(|n| n.contains("can't be placed in")), said, "{to:?}: {notices:?}"); + let a = s.map().layer(made["layer"].as_u64().unwrap() as u32).unwrap(); + assert_eq!(a.dataset.coord_crs(), polar); + if said { + assert_eq!(a.dataset.features[1].geometry, label_point, "at its label point"); + assert!(a.labels.default.moved.is_empty(), "not moved in the annotation"); + } else { + assert_eq!(a.labels.default.moved.len(), 1); + } + } +} diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 2257f96cc7..40db13de1e 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -600,8 +600,8 @@ use the smaller polar region in either direction; reversing a ring does not sele complement. Edges follow the shortest geodesics between vertices. The output fields remain `area_km2`, `perimeter_km` and `length_km`; point coordinates are unchanged. A point layer gets `point_x` and `point_y`: longitude and latitude, or x and y in the projected system the layer is -held in (see above). A feature with a place that can't be given in longitude/latitude isn't -measured, and a notice counts them. +held in (see above). A feature with a place that can't be given in longitude/latitude, or lies +beyond the poles (a latitude past ±90°), isn't measured, and a notice counts them. A ring through both poles can wind beyond one whole surface and bound no single region. Calculate Geometry Attributes refuses such input, with the numbers of affected rings and features, before changing any fields. The attribute table's Calculate Geometry does the diff --git a/xtask/row-uses.txt b/xtask/row-uses.txt index f9278864db..52f6c8cedc 100644 --- a/xtask/row-uses.txt +++ b/xtask/row-uses.txt @@ -4,4 +4,4 @@ # down: new code reads and changes rows through the accessors on `Features` # (crates/data/src/row_access.rs). When a change lowers it, run `cargo xtask rows --update` and # commit this file with it. -count = 782 +count = 781 From 843f16ca24666bce255cda306ceacccfa0a3789e Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Mon, 23 Nov 2026 10:00:30 +0100 Subject: [PATCH 3/3] Review: skip count after the cost check, Cancel before any simulated layer is kept, one moved-label lookup --- crates/analysis/src/network.rs | 16 +++++++++++----- crates/analysis/src/tools.rs | 2 +- crates/engine/src/cmd/labels.rs | 8 ++++---- crates/engine/src/cmd/workflows.rs | 5 ++--- 4 files changed, 18 insertions(+), 13 deletions(-) diff --git a/crates/analysis/src/network.rs b/crates/analysis/src/network.rs index 17e273f33a..1169d9dbb3 100644 --- a/crates/analysis/src/network.rs +++ b/crates/analysis/src/network.rs @@ -106,11 +106,6 @@ impl Network { crate::control::check()?; crate::control::reached(i); let Some(line @ Geometry::Line(held)) = ds.features.get(*r).and_then(|f| f.geometry.as_ref()) else { continue }; - let Some(line) = Dataset::converted_to_lonlat(&to, line) else { - skipped_segments += held.iter().map(|part| part.len().saturating_sub(1)).sum::(); - continue; - }; - let Geometry::Line(parts) = &*line else { continue }; // A cost multiplies each edge's length; no value means 1, and zero or less closes the // line (impassable). let weight = match cost_field.map(|fi| ds.value(*r, fi).as_f64()) { @@ -118,6 +113,11 @@ impl Network { Some(Some(_)) => continue, _ => 1.0, }; + let Some(line) = Dataset::converted_to_lonlat(&to, line) else { + skipped_segments += held.iter().map(|part| part.len().saturating_sub(1)).sum::(); + continue; + }; + let Geometry::Line(parts) = &*line else { continue }; if cost_overflows(parts, weight, &mut pace)? { overflowing += 1; continue; @@ -1609,6 +1609,12 @@ mod tests { let Some(Geometry::Line(given)) = &lonlat.features[0].geometry else { panic!("a line") }; assert!(graph.nodes.iter().zip(&given[0]).all(|(a, b)| (a.x - b.x).abs() < 1e-9 && (a.y - b.y).abs() < 1e-9)); assert!(Arc::ptr_eq(&graph, &network_for(&cache, &ds, &[0], None).unwrap()), "kept under the held layer"); + assert_eq!(graph.skipped_segments, 0); + // A line with a place that has no longitude/latitude (far beyond the Earth in UTM) is left + // out, its segments counted as ones with invalid coordinates; the others are searched. + ds.push(Some(Geometry::Line(vec![vec![Coord::new(1e12, 0.0), Coord::new(1e12 + 1.0, 0.0), Coord::new(1e12 + 2.0, 0.0)]])), vec![]); + let graph = network_for(&cache, &ds, &[0, 1], None).unwrap(); + assert_eq!((graph.skipped_segments, graph.segs.len()), (2, 2)); } /// Repeated pairs reuse topology without retaining endpoint edits; every graph input diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 0106484dc1..b6d72d8e72 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -6136,7 +6136,7 @@ fn calculate_geometry(inp: &dyn Inputs, p: &Json) -> Result let unplaced = unplaced.into_inner(); if unplaced > 0 { messages.push(format!( - "Calculate Geometry Attributes: {unplaced} feature(s) of {} have a place with no longitude/latitude (beyond the poles, or one {} can't give there), and weren't measured", + "Calculate Geometry Attributes: {unplaced} feature(s) of {} have a place with no longitude/latitude (beyond the poles, or not convertible from {}), and weren't measured", ds.name, to.source().label() )); diff --git a/crates/engine/src/cmd/labels.rs b/crates/engine/src/cmd/labels.rs index 0682733669..c55aec500c 100644 --- a/crates/engine/src/cmd/labels.rs +++ b/crates/engine/src/cmd/labels.rs @@ -1023,9 +1023,9 @@ fn convert(s: &mut Session, p: &Value) -> CmdResult { // (its class's offset leaves it). // One that can't be placed in the layer's own system stays at its label point, and // isn't moved in the annotation's labels either. - let was_moved = class.moved_to(ft.id()).is_some(); - let (put, at) = match class.moved_to(ft.id()).map(|put| (put, put_at(put))) { - Some((put, Some(to))) => (Some(put), to), + let moved_to = class.moved_to(ft.id()); + let (put, at) = match moved_to.map(|put| (put, put_at(put))) { + Some((put, Some(placed))) => (Some(put), placed), Some((_, None)) | None => (None, at), }; let e = exprs.get(i).and_then(Option::as_ref); @@ -1042,7 +1042,7 @@ fn convert(s: &mut Session, p: &Value) -> CmdResult { attrs.push(number(e.filter(|_| turns).and_then(|e| e.angle(&l.dataset, row)))); } ds.push(Some(Geometry::Point(at)), attrs); - let flat = !was_moved && along(class, ft.geometry()); + let flat = moved_to.is_none() && along(class, ft.geometry()); flattened += usize::from(flat); repeated += usize::from(flat && class.repeat.is_some()); if let (Some(put), Some(new)) = (put, ds.features.last()) { diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index d4a54a8f5b..3d4ae6a705 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -1998,10 +1998,9 @@ fn simulate(s: &mut Session, p: &Value) -> CmdResult { ds.push(Some(Geometry::Point(*c)), vec![Attr::Int(*r as i64)]); } let n = ds.features.len(); + // A cancel stops the sampling with the points made so far: none of them is added. + rustgis_data::progress::check().map_err(|e| e.to_string())?; if own { - // A cancel stops the sampling with the points made so far: none of them is added, as the - // conversion below refuses them then. - rustgis_data::progress::check().map_err(|e| e.to_string())?; (ds.held_in, ds.crs) = system; } else { hold_as(s, &mut ds, system)?;