diff --git a/crates/analysis/src/lib.rs b/crates/analysis/src/lib.rs index 1e3d5fd4e0..b68ba78319 100644 --- a/crates/analysis/src/lib.rs +++ b/crates/analysis/src/lib.rs @@ -49,12 +49,28 @@ pub use parallel::scratch_budget; pub use parameters::StatisticList; pub use tools::{ SimplifyNotes, TOOLS, find_field_case_insensitive, holds_coordinates, in_its_units, layer_raster_crs, max_buffer_bytes, min_pad, - param_applies, past_pole, points_in, projected_crs, raster_crs, simplify_geometry, zonal_bands, + param_applies, past_pole, points_from, points_in, projected_crs, raster_crs, raster_crs_in, simplify_geometry, zonal_bands, }; use rustgis_data::Dataset; use serde_json::Value; +/// Whether a tool that works in its first input's own system ([`ToolSpec::works_in_own_system`]), +/// and the Geostatistical Wizard, works in `crs`: a projected system, whose coordinates are a +/// plane's. Longitude/latitude, Web Mercator and the other world projections (whose plane has the +/// antimeridian as a seam and the poles as lines, +/// [`rustgis_data::raster::Crs::is_world_projection`]), and other geographic or geocentric +/// systems, keep the longitude/latitude path, whose plane and geodesics their coordinates need. So +/// does a system whose conversion can't be made or gives no parameters, whose unit and axes +/// ([`rustgis_data::raster::Crs::unit_and_axes`]) aren't known. +pub fn works_in(crs: rustgis_data::raster::Crs) -> bool { + crs != rustgis_data::raster::Crs::LonLat + && !crs.is_world_projection() + && !crs.is_geographic() + && !crs.is_geocentric() + && crs.transformer().is_ok_and(|t| t.params().is_some()) +} + /// Parameter kinds, which the Tools pane turns into widgets. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ParamKind { diff --git a/crates/analysis/src/neural.rs b/crates/analysis/src/neural.rs index fc6a278cb3..74488112b3 100644 --- a/crates/analysis/src/neural.rs +++ b/crates/analysis/src/neural.rs @@ -136,12 +136,27 @@ pub fn training_samples( classes: usize, max_per_class: usize, ) -> Result<(Vec<(Vec, usize)>, Vec), String> { + training_samples_in(r, rustgis_data::raster::Crs::LonLat, bands, polygons, classes, max_per_class) +} + +/// [`training_samples`] of polygons whose rings are in `from`: longitude/latitude, or the system +/// their layer holds its coordinates in, a pixel's centre tested there (none of it converted +/// when that is the raster's own). +pub fn training_samples_in( + r: &Raster, + from: rustgis_data::raster::Crs, + bands: &[usize], + polygons: &[(Vec>, usize, usize)], + classes: usize, + max_per_class: usize, +) -> Result<(Vec<(Vec, usize)>, Vec), String> { + let zone = crate::rasterops::ZoneIn::new(r, from)?; crate::control::begin(polygons.len()); let mut samples: Vec<(Vec, usize)> = Vec::new(); let mut per_class = vec![0usize; classes]; for (rings, ci, share) in polygons { let room = max_per_class.saturating_sub(per_class.get(*ci).copied().unwrap_or(0)).min(*share); - let got = polygon_samples(r, bands, rings, room); + let got = samples_under(r, &zone, bands, rings, room); // Stopped part of the way through the polygon: what it got isn't its share. crate::control::check()?; if let Some(n) = per_class.get_mut(*ci) { @@ -159,18 +174,36 @@ pub fn training_samples( /// stops between rows, with the pixels found so far. If an outline vertex can't be placed, /// search the whole raster instead of bounding the polygon by only its surviving vertices. pub fn polygon_samples(r: &Raster, bands: &[usize], rings: &[Vec], max: usize) -> Vec> { + samples_under(r, &crate::rasterops::ZoneIn::LonLat, bands, rings, max) +} + +/// [`polygon_samples`] of rings in the zone's system (`zone`), each pixel's centre tested in that +/// system. +fn samples_under(r: &Raster, zone: &crate::rasterops::ZoneIn, bands: &[usize], rings: &[Vec], max: usize) -> Vec> { let mut out = Vec::new(); - let tr = r.transformer(); - // The pixel window under the outline (its vertices, projected into the raster). + // The pixel window under the outline: in longitude/latitude its vertices projected into the + // raster (the whole raster when one can't be); in a system of its own the zone's conservative + // window over the outline's box ([`crate::rasterops::ZoneIn::window`]: its sides and inside + // sampled, the whole raster when it holds a pole), since a straight side there can bow on the + // raster's grid past the vertices' places. let (mut c0, mut r0, mut c1, mut r1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); - for v in rings.iter().flatten().take(1_000_000) { - let Some(w) = tr.from_lonlat(*v) else { - (c0, r0, c1, r1) = (0.0, 0.0, f64::from(r.width), f64::from(r.height)); - break; - }; - let (c, rw) = r.transform.to_pixel(w); - if c.is_finite() && rw.is_finite() { - (c0, r0, c1, r1) = (c0.min(c), r0.min(rw), c1.max(c), r1.max(rw)); + if matches!(zone, crate::rasterops::ZoneIn::LonLat) { + for v in rings.iter().flatten().take(1_000_000) { + let Some(w) = zone.grid(r, *v) else { + (c0, r0, c1, r1) = (0.0, 0.0, f64::from(r.width), f64::from(r.height)); + break; + }; + let (c, rw) = r.transform.to_pixel(w); + if c.is_finite() && rw.is_finite() { + (c0, r0, c1, r1) = (c0.min(c), r0.min(rw), c1.max(c), r1.max(rw)); + } + } + } else { + let mut e = rustgis_geom::Extent::EMPTY; + rings.iter().flatten().for_each(|c| e.expand(*c)); + let (cols, rows) = zone.window(r, &e); + if !cols.is_empty() && !rows.is_empty() { + (c0, r0, c1, r1) = (f64::from(cols.start), f64::from(rows.start), f64::from(cols.end), f64::from(rows.end)); } } if c0 > c1 || max == 0 { @@ -198,7 +231,7 @@ pub fn polygon_samples(r: &Raster, bands: &[usize], rings: &[Vec], max: u break 'scan; } let w = r.transform.to_world(col as f64 + 0.5, row as f64 + 0.5); - if let Some(ll) = tr.to_lonlat(w) + if let Some(ll) = zone.zone(r, w) && rustgis_data::geometry::polygon_contains(rings, ll) && let Some(v) = bands.iter().map(|b| r.value(*b, col, row)).collect::>>() { @@ -500,6 +533,30 @@ mod tests { assert_eq!(polygon_samples(&r, &[0], &[ring], 10), [vec![42.0]]); } + /// A training polygon held in its own system is sampled wherever its pixels are, even where its + /// straight sides bow on the raster's grid past its corners: a rectangle 2000 km by 100 km in + /// polar stereographic north (EPSG:3413), over a small raster in degrees at its middle, which + /// lies north of all four corners there. + #[test] + fn a_held_polygon_is_sampled_between_its_corners() { + use rustgis_data::raster::{ColorHint, Crs, GeoTransform}; + let polar = Crs::Epsg(3413); + let t = polar.transformer().unwrap(); + let mid = t.to_lonlat(Coord::new(0.0, -950_000.0)).unwrap(); + let corners: Vec = [(-1e6, -1e6), (1e6, -1e6), (1e6, -0.9e6), (-1e6, -0.9e6)] + .iter() + .map(|(x, y)| t.to_lonlat(Coord::new(*x, *y)).unwrap()) + .collect(); + assert!(corners.iter().all(|c| c.y < mid.y - 0.05), "{corners:?} {mid:?}"); + let (w, h) = (40u32, 40u32); + let gt = GeoTransform { origin_x: mid.x - 0.02, origin_y: mid.y + 0.02, pixel_width: 0.001, pixel_height: -0.001 }; + let r = Raster::new("mid", w, h, vec![vec![7.0; (w * h) as usize]], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + let ring = + vec![Coord::new(-1e6, -1e6), Coord::new(1e6, -1e6), Coord::new(1e6, -0.9e6), Coord::new(-1e6, -0.9e6), Coord::new(-1e6, -1e6)]; + let zone = crate::rasterops::ZoneIn::new(&r, polar).unwrap(); + assert_eq!(samples_under(&r, &zone, &[0], &[ring], 10_000).len(), (w * h) as usize); + } + /// Rows classified on several threads give the same classes and probabilities, bit for bit, /// as one thread (#1252), no-data pixels included. #[test] diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index 43e529f967..4be519e3fe 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -1059,8 +1059,26 @@ impl ZoneIn { }) } + /// Whether the zone's box `e` holds a pole its system holds, in a system other than the + /// raster's: the outline bounds nothing there (on a Web Mercator raster it lands south of the + /// cells near the pole), so the whole raster is read. + pub(crate) fn holds_a_pole(&self, e: &Extent) -> bool { + matches!(self, Self::Own { to_zone, .. } if to_zone.poles().iter().any(|p| e.contains(*p))) + } + + /// The columns and rows of `r` whose cell centres can fall in the zone's box `e`: the whole + /// raster when the box holds a pole ([`ZoneIn::holds_a_pole`]), else [`zone_window`], with its + /// interior samples for a zone in a system of its own. + pub(crate) fn window(&self, r: &Raster, e: &Extent) -> (Range, Range) { + match self { + _ if self.holds_a_pole(e) => (0..r.width, 0..r.height), + Self::Own { .. } => zone_window(r, e, true, |c| self.grid(r, c)), + Self::LonLat => zone_window(r, e, false, |c| self.grid(r, c)), + } + } + /// A place in the raster's system in the zone's. - fn zone(&self, r: &Raster, w: Coord) -> Option { + pub(crate) fn zone(&self, r: &Raster, w: Coord) -> Option { match self { Self::LonLat => r.transformer().to_lonlat(w), Self::Own { to_zone, .. } => to_zone.place(w), @@ -1068,7 +1086,7 @@ impl ZoneIn { } /// A place in the zone's system in the raster's. - fn grid(&self, r: &Raster, c: Coord) -> Option { + pub(crate) fn grid(&self, r: &Raster, c: Coord) -> Option { match self { Self::LonLat => r.transformer().from_lonlat(c), Self::Own { to_grid, .. } => to_grid.vertex(c), @@ -1123,13 +1141,7 @@ fn means_under( let mut n = 0usize; for (k, e) in boxes.iter().enumerate() { let earlier = index.as_ref().filter(|ix| ix.any_candidate(e, |j| j < k && boxes[j].intersects(e))); - // A pole inside the zone's box, in a system other than the raster's: the outline bounds - // nothing there (on a Web Mercator raster it lands south of the cells near the pole). - let (cols, rows) = match zone { - ZoneIn::Own { to_zone, .. } if to_zone.poles().iter().any(|p| e.contains(*p)) => (0..r.width, 0..r.height), - ZoneIn::Own { .. } => zone_window(r, e, true, |c| zone.grid(r, c)), - ZoneIn::LonLat => zone_window(r, e, false, |c| zone.grid(r, c)), - }; + let (cols, rows) = zone.window(r, e); each_rows((r.height - (rows.end - rows.start)) as usize)?; for row in rows { each_rows(1)?; @@ -1239,6 +1251,19 @@ fn zone_window(r: &Raster, e: &Extent, interior: bool, to_grid: impl Fn(Coord) - /// under its polygons left out. Each polygon's rows count toward the run's progress, and a /// cancelled run stops (#1291). pub fn class_means(r: &Raster, bands: &[usize], polygons: &[(String, Vec>)]) -> Result, usize)>, String> { + class_means_in(r, Crs::LonLat, bands, polygons) +} + +/// [`class_means`] of training polygons whose rings are in `from`: longitude/latitude, or the +/// system their layer holds its coordinates in, a cell's centre tested there ([`ZoneIn`]: none of +/// it converted when that is the raster's own). +pub fn class_means_in( + r: &Raster, + from: Crs, + bands: &[usize], + polygons: &[(String, Vec>)], +) -> Result, usize)>, String> { + let zone = ZoneIn::new(r, from)?; crate::control::begin(polygons.len().saturating_mul(r.height as usize)); let mut classes: Vec<(String, Vec, usize)> = Vec::new(); for (key, rings) in polygons { @@ -1247,7 +1272,7 @@ pub fn class_means(r: &Raster, bands: &[usize], polygons: &[(String, Vec { let total = c.2 + n; @@ -1403,6 +1428,12 @@ pub fn transform_polygon_to_lonlat(rings: &[Vec], tr: Option<&Transformer Ok(out_rings) } +/// The polygon parts of a (multi-)polygon feature, checked and taken apart into rings, in the +/// system they are in: [`transform_feature_polygons_to_lonlat`] with no transformer. +pub fn validated_polygon_parts(polys: &[Vec>]) -> Result>>, PolygonTransformError> { + transform_feature_polygons_to_lonlat(polys, None) +} + /// Transforms and validates all polygon parts of a (multi-)polygon feature to WGS 84 lon/lat coordinates. /// With no transformer (`tr` `None`), it only checks the parts and takes them apart into rings, /// in whatever system they are in. @@ -3134,14 +3165,14 @@ mod tests { // Multipart features let multi_valid = vec![vec![ext.clone(), hole1.clone()], vec![sq(20.0, 20.0, 30.0, 30.0)]]; - let multi_res = transform_feature_polygons_to_lonlat(&multi_valid, None).unwrap(); + let multi_res = validated_polygon_parts(&multi_valid).unwrap(); assert_eq!(multi_res.len(), 2); assert_eq!(multi_res[0].len(), 2); assert_eq!(multi_res[1].len(), 1); // Multipart with failing part let multi_bad = vec![vec![ext.clone()], vec![vec![Coord::new(1.0, 1.0)]]]; - assert!(transform_feature_polygons_to_lonlat(&multi_bad, None).is_err()); + assert!(validated_polygon_parts(&multi_bad).is_err()); } #[test] diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 6a8caba26d..644fd8a0cf 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -5130,7 +5130,7 @@ pub fn raster_crs(ds: &Dataset, p: &Json, tool: &str) -> Result<(Crs, Option Result<(Crs, Option), String> { +pub fn raster_crs_in(ds: &Dataset, work: Crs, p: &Json, tool: &str) -> Result<(Crs, Option), String> { if work == Crs::LonLat { raster_crs_of(ds.crs, "was read in", &ds.name, p, tool) } else { @@ -5196,7 +5196,7 @@ pub fn points_in(crs: Crs, pts: Vec<(Coord, f64)>) -> Result<(Vec<(Coord, f64)>, /// [`points_in`] for points in `from`, a run's own system ([`Inputs::work_crs`]): as they are /// when the grid is in it too, else through [`ToGrid`]. -fn points_from(from: Crs, crs: Crs, pts: Vec<(Coord, f64)>) -> Result<(Vec<(Coord, f64)>, Option), String> { +pub fn points_from(from: Crs, crs: Crs, pts: Vec<(Coord, f64)>) -> Result<(Vec<(Coord, f64)>, Option), String> { if from == crs { return Ok((pts, None)); } @@ -8295,7 +8295,7 @@ fn zonal_stats_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Result< Ok::<_, String>(match &f.geometry { Some(Geometry::Polygon(polys)) if !polys.is_empty() => { // Checked and taken apart into rings, in the run's system as they are. - match crate::rasterops::transform_feature_polygons_to_lonlat(polys, None) { + match crate::rasterops::validated_polygon_parts(polys) { Ok(rings) => { let mut failed_parts = Vec::new(); let st = crate::rasterops::zonal_statistics_from(r, to, &bands, &rings, &mut failed_parts)?; diff --git a/crates/analysis/src/tools/tabulate_area.rs b/crates/analysis/src/tools/tabulate_area.rs index 64ecd2150b..1289cd46eb 100644 --- a/crates/analysis/src/tools/tabulate_area.rs +++ b/crates/analysis/src/tools/tabulate_area.rs @@ -178,7 +178,7 @@ fn summarize( crate::control::check()?; let shape = zones.features.get(row).and_then(|f| f.geometry.as_ref()); let valid = match shape { - Some(Geometry::Polygon(p)) => crate::rasterops::transform_feature_polygons_to_lonlat(p, None).ok(), + Some(Geometry::Polygon(p)) => crate::rasterops::validated_polygon_parts(p).ok(), _ => None, }; match valid { diff --git a/crates/data/src/raster/mod.rs b/crates/data/src/raster/mod.rs index a8a1299d23..a5de7c420d 100644 --- a/crates/data/src/raster/mod.rs +++ b/crates/data/src/raster/mod.rs @@ -1267,7 +1267,12 @@ impl Raster { /// The pixel under a longitude/latitude point. pub fn pixel_at(&self, lonlat: Coord) -> Option<(i64, i64)> { - let (c, r) = self.transform.to_pixel(self.transformer.from_lonlat(lonlat)?); + self.pixel_at_world(self.transformer.from_lonlat(lonlat)?) + } + + /// The pixel under a place in the raster's own system. + pub fn pixel_at_world(&self, w: Coord) -> Option<(i64, i64)> { + let (c, r) = self.transform.to_pixel(w); let (c, r) = (self.wrap_col(c).floor(), r.floor()); (c >= 0.0 && r >= 0.0 && c < self.width as f64 && r < self.height as f64).then_some((c as i64, r as i64)) } diff --git a/crates/engine/src/cmd/deeplearning.rs b/crates/engine/src/cmd/deeplearning.rs index 0bbcbdc4f6..6e368969cd 100644 --- a/crates/engine/src/cmd/deeplearning.rs +++ b/crates/engine/src/cmd/deeplearning.rs @@ -219,7 +219,9 @@ impl Training { name: String, ) -> Result { let (classes, polygons) = training_polygons(ds, field)?; - let (samples, per_class) = neural::training_samples(raster, bands, &polygons, classes.len(), MAX_SAMPLES_PER_CLASS)?; + // Sampled in the system the polygons are held in. + let (samples, per_class) = + neural::training_samples_in(raster, ds.coord_crs(), bands, &polygons, classes.len(), MAX_SAMPLES_PER_CLASS)?; // Every class needs pixels of its own (its polygons may miss the raster or cover no data). if let Some((c, _)) = classes.iter().zip(&per_class).find(|(_, n)| **n < 5) { return Err(format!("the class '{c}' has fewer than 5 pixels with data under its polygons")); diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index 9354ee0025..1427c9e7b0 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -143,31 +143,54 @@ pub(crate) fn apply_with>(s: &mut Session, id: u32, changes: } let elevation = s.map().editing.settings.elevation.clone(); // Elevation from a surface: sampled before the layer is borrowed mutably. - let z_of = |s: &Session, g: &Geometry| -> Option { + let new_rows: Vec = + if new_defaults { changes.iter().filter(|c| c.before.is_none()).filter_map(|c| c.row).collect() } else { Vec::new() }; + // The surface is read at the label point of the shape as the layer holds it, placed on the + // surface's grid by the direct operation between the two systems (none of it when they are + // one), made once for all the new features (a conversion that can't be made refuses only a + // feature with a place to read). A label point the surface's system can't give refuses the + // edit rather than leave the feature without its `z`; one off the surface, or over no data, + // gets none. + let (layer_name, layer_crs) = s.map().layer(id).map(|l| (l.name.clone(), l.dataset.coord_crs())).ok_or("no such layer")?; + let to_surface = match &elevation { + Elevation::Surface(name) if !new_rows.is_empty() => { + match surface_layer(s, name).and_then(|l| l.raster.as_ref()?.data.as_ref()).map(|r| r.crs) { + Some(crs) if crs != layer_crs => Some(layer_crs.to(crs).map_err(|e| format!("{layer_name}: {e}"))), + _ => None, + } + } + _ => None, + }; + let z_of = |s: &Session, g: &Geometry| -> Result, String> { match &elevation { - Elevation::None => None, - Elevation::Constant(z) => Some(*z), + Elevation::None => Ok(None), + Elevation::Constant(z) => Ok(Some(*z)), Elevation::Surface(name) => { - let c = g.label_point()?; - let r = surface_layer(s, name)?.raster.as_ref()?.data.as_ref()?; - let (col, row) = r.pixel_at(c)?; - r.value(0, col, row).map(f64::from) + let Some(c) = g.label_point() else { return Ok(None) }; + let Some(r) = surface_layer(s, name).and_then(|l| l.raster.as_ref()?.data.as_ref()) else { return Ok(None) }; + let w = match &to_surface { + Some(Err(e)) => return Err(e.clone()), + Some(Ok(to)) => to.point(c).ok_or_else(|| { + format!( + "{layer_name}: this feature's place in {} can't be given in the system of the surface {name}, {}", + layer_crs.label(), + r.crs.label() + ) + })?, + None => c, + }; + Ok(r.pixel_at_world(w).and_then(|(col, row)| r.value(0, col, row)).map(f64::from)) } } }; - let new_rows: Vec = - if new_defaults { changes.iter().filter(|c| c.before.is_none()).filter_map(|c| c.row).collect() } else { Vec::new() }; - // Sampled from a surface at each place in longitude/latitude, from the layer's own coordinates: - // a place that can't be converted refuses the edit rather than leave the feature without its - // `z`. Without a surface, the place isn't converted. Done before anything below changes the - // session, so a refusal leaves it as it was. + // Sampled from a surface at each place in the layer's own coordinates (see `z_of`). Done before + // anything below changes the session, so a refusal leaves it as it was. let mut zs: Vec<(usize, Option)> = Vec::with_capacity(new_rows.len()); for r in &new_rows { - let stored = s.map().layer(id).and_then(|l| Some((l, l.dataset.features.get(*r)?.geometry.as_ref()?))); - let z = match (stored, &elevation) { - (None, _) => None, - (Some((l, g)), Elevation::Surface(_)) => z_of(s, l.dataset.geometry_to_lonlat(g)?.as_ref()), - (Some((_, g)), _) => z_of(s, g), + let stored = s.map().layer(id).and_then(|l| l.dataset.features.get(*r)?.geometry.as_ref()); + let z = match stored { + Some(g) => z_of(s, g)?, + None => None, }; zs.push((*r, z)); } diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index f56a1f5f0a..e7f528467b 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -1521,21 +1521,9 @@ fn streamed_inputs( Ok((full, said)) } -/// Whether a tool that works in its first input's own system ([`ToolSpec::works_in_own_system`]) -/// works in `crs`: a projected system, whose coordinates are a plane's. Longitude/latitude, Web -/// Mercator and the other world projections (whose plane has the antimeridian as a seam and the -/// poles as lines, [`Crs::is_world_projection`]), and other geographic or geocentric systems, keep -/// the longitude/latitude path, whose plane and geodesics their coordinates need. So does a system -/// whose conversion can't be made or gives no parameters, whose unit and axes -/// ([`Crs::unit_and_axes`]) aren't known. -/// -/// [`ToolSpec::works_in_own_system`]: rustgis_analysis::ToolSpec::works_in_own_system +/// Whether a run works in `crs`: [`rustgis_analysis::works_in`]. fn works_in(crs: Crs) -> bool { - crs != Crs::LonLat - && !crs.is_world_projection() - && !crs.is_geographic() - && !crs.is_geocentric() - && crs.transformer().is_ok_and(|t| t.params().is_some()) + rustgis_analysis::works_in(crs) } /// The system a run works in: its first input's own ([`Dataset::coord_crs`]) when the tool works diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 7bd2f0ab02..7039e1ab51 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -503,7 +503,7 @@ fn rasterize(s: &mut Session, p: &Value) -> CmdResult { for row in rows { let Some(feature) = ds.features.get(row) else { continue }; let parts = match &feature.geometry { - Some(Geometry::Polygon(polys)) => rasterops::transform_feature_polygons_to_lonlat(polys, None).ok(), + Some(Geometry::Polygon(polys)) => rasterops::validated_polygon_parts(polys).ok(), _ => None, }; let Some(parts) = parts else { @@ -566,16 +566,21 @@ fn rasterize(s: &mut Session, p: &Value) -> CmdResult { if shapes.is_empty() { return Err(format!("{ln} has no polygons with a value to burn")); } - // By default, the system the layer holds its coordinates in (else the one it was read in) and + // By default, the projected system the layer holds its coordinates in (else the one it was read in) and // the polygons' bounds. let held_bounds = shapes.iter().flat_map(|s| s.parts.iter().flatten().flatten()).fold(Extent::EMPTY, |mut e, c| { e.expand(*c); e }); - let crs = if held == Crs::LonLat { ds.crs.unwrap_or(Crs::LonLat) } else { held }; + // A projected system the layer holds it in: a geographic or geocentric one (an ECEF layer) has + // no plane for a grid, so it takes the one the layer was read in. Web Mercator and the world + // projections are planes a grid is laid on, unlike the analysis plane `works_in` excludes them + // from. + let projected = held != Crs::LonLat && !held.is_geographic() && !held.is_geocentric(); + let crs = if projected { held } else { ds.crs.unwrap_or(Crs::LonLat) }; let mut unsized_by = 0usize; let grid = grid_param(s, p, crs, |crs| { - if crs == held && held != Crs::LonLat { + if crs == held && projected { return Ok(([held_bounds.min_x, held_bounds.min_y, held_bounds.max_x, held_bounds.max_y], None)); } // Otherwise the bounds of the polygons' box in longitude/latitude, as before. A place the @@ -1182,8 +1187,8 @@ pub(crate) fn supervised_work(s: &Session, p: &Value) -> Result Result match rasterops::transform_feature_polygons_to_lonlat(polys, None) { + Some(Geometry::Polygon(polys)) => match rasterops::validated_polygon_parts(polys) { Ok(transformed) => { polygons.extend(transformed); } diff --git a/crates/engine/src/cmd/whole.rs b/crates/engine/src/cmd/whole.rs index 6a6c2503a6..97aa0dd617 100644 --- a/crates/engine/src/cmd/whole.rs +++ b/crates/engine/src/cmd/whole.rs @@ -56,20 +56,17 @@ impl Whole { Whole { name: l.name.clone(), rows } } - /// Every feature in longitude/latitude, whatever system the layer holds its coordinates in - /// (its work reads places there), with the fields the layer lists (so a field's index in the - /// layer is its index here), and the rows of its source that couldn't be read. A source read - /// a chunk at a time looks at Cancel between chunks; one read at once (a GeoJSON file, a - /// database table) is a single step that doesn't, as for Load All Features. + /// Every feature in the system the layer holds its coordinates in ([`Dataset::coord_crs`]: its + /// work tests places there, none of them converted), with the fields the layer lists (so a + /// field's index in the layer is its index here), and the rows of its source that couldn't be + /// read. A source read a chunk at a time looks at Cancel between chunks; one read at once (a + /// GeoJSON file, a database table) is a single step that doesn't, as for Load All Features. pub(crate) fn read(self) -> Result<(Dataset, Unread), String> { let Whole { name, rows } = self; - let (mut ds, unread) = match rows { + let (ds, unread) = match rows { Rows::Held(ds) => (ds, Unreadable::default()), Rows::Source(l) => l.load_all_counted().map_err(|e| format!("{name}: {e}"))?, }; - if ds.coord_crs() != rustgis_data::raster::Crs::LonLat { - ds = ds.in_lonlat()?.into_owned(); - } Ok((ds, Unread::of(name, unread))) } } diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index ff19400f8a..da1cae86bc 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -1651,15 +1651,18 @@ fn interpolate_work(s: &Session, p: &Value) -> Result { // Features without a place or a number are left out, and said (by kind, with a count). let (mut no_point, mut no_value) = (0usize, 0usize); let mut pts: Vec<(Coord, f64)> = Vec::with_capacity(ds.features.len()); - // Each place in longitude/latitude, whatever system the layer holds its coordinates in; one - // that can't be given there has no place. A point is converted alone; any other shape is - // converted first, so its label point (a polygon's centroid) is the one it has in - // longitude/latitude, not the one in the layer's own system. A shape with a place that can't - // be converted gives its label point in its own system, converted, as long as that converts. - let to = ds.lonlat_conversion()?; - let place = |g: &Geometry| match g { - Geometry::Point(c) => to.point(*c), - g => match Dataset::converted_to_lonlat(&to, g) { + // The run's system: the layer's own projected one it holds its coordinates in, as the + // interpolation tools take it (`rustgis_analysis::works_in`), its places taken as they are; else + // longitude/latitude, each place given there (one that can't be has no place). There a point + // is converted alone; any other shape is converted first, so its label point (a polygon's + // centroid) is the one it has in longitude/latitude. A shape with a place that can't be + // converted gives its label point in its own system, converted, as long as that converts. + let work = Some(ds.coord_crs()).filter(|c| rustgis_analysis::works_in(*c)).unwrap_or(Crs::LonLat); + let to = if work == Crs::LonLat { Some(ds.lonlat_conversion()?) } else { None }; + let place = |g: &Geometry| match (&to, g) { + (None, g) => g.label_point(), + (Some(to), Geometry::Point(c)) => to.point(*c), + (Some(to), g) => match Dataset::converted_to_lonlat(to, g) { Some(g) => g.label_point(), None => g.label_point().and_then(|c| to.point(c)), }, @@ -1676,14 +1679,14 @@ fn interpolate_work(s: &Session, p: &Value) -> Result { pts.push((c, v)); } let (layer_name, field_name) = (ds.name.clone(), field.to_string()); - // The system: the one given, else the environment's, else the projected one the layer was read - // in, else degrees. + // The system: the one given, else the environment's, else the projected one the layer holds its + // coordinates in, else the one it was read in, else degrees. let env = &s.project.gp_env; // An empty `crs` is none given, as `null` is: the environment's system still applies. let given = p.get("crs").is_some_and(|v| !v.is_null() && v.as_str().is_none_or(|t| !t.trim().is_empty())); let (crs, crs_note) = match env.projected { Some(g) if !given => (g.crs, None), - _ => rustgis_analysis::raster_crs(ds, p, "Geostatistical Wizard")?, + _ => rustgis_analysis::raster_crs_in(ds, work, p, "Geostatistical Wizard")?, }; let crs_note = rustgis_analysis::in_its_units(p, crs, crs_note, &Extent::EMPTY, &[], &["cellSize"]); let env_extent = env.extent; @@ -1713,7 +1716,7 @@ fn interpolate_work(s: &Session, p: &Value) -> Result { let neighbors = p.get("neighbors").and_then(Value::as_u64).unwrap_or(12).max(1) as usize; Ok(Box::new(move || { // Off the window's thread: the points, and the grid they set, in the system. - let (pts, beyond_note) = rustgis_analysis::points_in(crs, pts)?; + let (pts, beyond_note) = rustgis_analysis::points_from(work, crs, pts)?; let e = match env_extent { Some(e) if crs == Crs::LonLat => e, Some(e) => { diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index 50ed50048c..d40385ba00 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -737,7 +737,8 @@ fn a_held_layer_feeds_other_layers_alike() { assert!((p.x - q.x).abs() < 1e-7 && (p.y - q.y).abs() < 1e-7, "annotation: {p:?} vs {q:?}"); } // 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})); + let [a, b] = + run_both(&mut ss, "analysis.interpolate", &json!({"layer": "Wells", "field": "n", "cellSize": 0.0015, "crs": "EPSG:4326"})); let grid = |s: &Session, v: &Value| s.map().layer(v["layer"].as_u64().unwrap() as u32).unwrap().raster.as_ref().unwrap().data.clone().unwrap(); let (ga, gb) = (grid(&ss[0], &a), grid(&ss[1], &b)); @@ -2157,6 +2158,97 @@ fn datum_pair() -> Session { s } +/// The Geostatistical Wizard makes a held layer's surface in the system it holds its coordinates +/// in, from them as they are: points 1500 km east of UTM 32N's central meridian, where a round trip +/// through longitude/latitude doesn't come back to the same bits, give a grid whose corner is +/// their own bounds, padded. +#[test] +fn the_geostatistical_wizard_works_in_the_held_system() { + let at: Vec = + (0..9).map(|i| Coord::new(2_000_003.7 + f64::from(i % 3) * 100.0, 5_400_001.3 + f64::from(i / 3) * 100.0)).collect(); + let mut s = Session::new(Project::default()); + add_in(&mut s, "Wells", GeometryType::Point, at.iter().map(|c| Geometry::Point(*c)).collect(), UTM); + s.run("analysis.interpolate", &json!({"layer": "Wells", "field": "v", "cellSize": 10, "name": "Surface"})).unwrap(); + let g = grid_of(&s, "Surface"); + let mut e = rustgis_geom::Extent::EMPTY; + at.iter().for_each(|c| e.expand(*c)); + let e = e.padded(0.05, rustgis_analysis::min_pad(UTM)); + assert_eq!(g.crs, UTM); + assert_eq!((g.transform.origin_x, g.transform.origin_y), (e.min_x, e.max_y)); +} + +/// A new feature's elevation from a surface whose system can't give its place refuses the edit, +/// rather than leave the feature without its `z`: the North Pole held in polar stereographic north, +/// over a surface in Antarctic polar stereographic (EPSG:3031), whose plane has no place for it. +#[test] +fn elevation_from_a_surface_that_cant_hold_the_place_refuses_the_edit() { + use rustgis_data::raster::{ColorHint, GeoTransform, Raster}; + let mut s = Session::new(Project::default()); + let gt = GeoTransform { origin_x: -1000.0, origin_y: 1000.0, pixel_width: 100.0, pixel_height: -100.0 }; + let r = Raster::new("south", 20, 20, vec![vec![1.0; 400]], gt, Crs::Epsg(3031), None, ColorHint::Gray, "Float32").unwrap(); + s.map_mut().add_raster("south", rustgis_map::raster::RasterLayer::from_path(r, "south.tif")); + add_in(&mut s, "Pins", GeometryType::Point, Vec::new(), POLAR); + s.run("edit.enable", &json!({"on": true})).unwrap(); + s.run("edit.elevation", &json!({"mode": "surface", "surface": "south"})).unwrap(); + let e = s.run("edit.addFeature", &json!({"layer": "Pins", "geometry": {"type": "Point", "coordinates": [0.0, 90.0]}})).unwrap_err(); + assert!(e.contains("can't be given in the system of the surface south"), "{e}"); + assert!(s.map().layer_by_name("Pins").unwrap().dataset.features.is_empty()); +} + +/// Training polygons held in another system than the raster's reach it by the direct operation: +/// two 3 m squares of two classes held in Gauss-Krüger zone 3 (DHDN) train the same supervised +/// classification and the same deep learning model over a raster of 10 cm cells in UTM 32N +/// (ETRS89) as the squares converted there by [`Crs::to`], where the way through WGS 84 is 0.44 m +/// off. +#[test] +fn training_polygons_reach_a_raster_by_the_direct_operation() { + let mut s = datum_pair(); + let (cx, cy) = (3_500_000.0, 5_400_000.0); + let square = |dx: f64| -> Vec { + [(-1.5, -1.5), (1.5, -1.5), (1.5, 1.5), (-1.5, 1.5), (-1.5, -1.5)].iter().map(|(x, y)| Coord::new(cx + dx + x, cy + y)).collect() + }; + let to = GK3.to(ETRS_UTM).unwrap(); + let held = [square(-2.0), square(2.0)]; + let there: Vec> = held.iter().map(|r| r.iter().map(|c| to.point(*c).unwrap()).collect()).collect(); + add_in(&mut s, "Training", GeometryType::Polygon, held.into_iter().map(|r| Geometry::Polygon(vec![vec![r]])).collect(), GK3); + add_in(&mut s, "TrainingThere", GeometryType::Polygon, there.into_iter().map(|r| Geometry::Polygon(vec![vec![r]])).collect(), ETRS_UTM); + let mut got = Vec::new(); + for training in ["Training", "TrainingThere"] { + let p = json!({"layer": "grid", "training": training, "classField": "v", "name": format!("{training} classes")}); + let classified = s.run("raster.classifySupervised", &p).unwrap(); + let dl = json!({"layer": "grid", "training": training, "classField": "v", "epochs": 5, "name": format!("{training} dl")}); + let learnt = s.run("dl.classify", &dl).unwrap(); + got.push((classified["classes"].clone(), raster_cells(&s, &classified), learnt["classes"].clone(), raster_cells(&s, &learnt))); + } + // 30 × 30 cells a class. + assert_eq!(got[0].0[0]["pixels"], 900, "{:?}", got[0].0); + assert_eq!(got[0], got[1]); +} + +/// A new feature's elevation from a surface is read where the layer holds it, placed on the +/// surface by the direct operation: a point held in Gauss-Krüger zone 3 (DHDN) added over a +/// surface of 10 cm cells in UTM 32N (ETRS89) takes the cell its place converted by [`Crs::to`] +/// lands on, not the one 0.44 m off that the way through WGS 84 gives. +#[test] +fn elevation_is_read_from_a_surface_by_the_direct_operation() { + let mut s = datum_pair(); + add_in(&mut s, "Pins", GeometryType::Point, Vec::new(), GK3); + s.run("edit.enable", &json!({"on": true})).unwrap(); + s.run("edit.elevation", &json!({"mode": "surface", "surface": "grid"})).unwrap(); + let at = Coord::new(3_500_000.0, 5_400_000.0); + let lonlat = GK3.to(Crs::LonLat).unwrap().point(at).unwrap(); + s.run("edit.addFeature", &json!({"layer": "Pins", "geometry": {"type": "Point", "coordinates": [lonlat.x, lonlat.y]}})).unwrap(); + let l = s.map().layer_by_name("Pins").unwrap(); + let Some(Geometry::Point(p)) = l.dataset.features[0].geometry.clone() else { panic!("a point") }; + let z = l.dataset.field_index("z").map(|i| l.dataset.value(0, i).as_f64()).unwrap_or_else(|| panic!("no z")); + let grid = grid_of(&s, "grid"); + let value = |w: Coord| grid.pixel_at_world(w).and_then(|(c, r)| grid.value(0, c, r)).map(f64::from); + let direct = value(GK3.to(ETRS_UTM).unwrap().point(p).unwrap()); + let via = value(ETRS_UTM.transformer().unwrap().from_lonlat(GK3.transformer().unwrap().to_lonlat(p).unwrap()).unwrap()); + assert_ne!(direct, via, "the two ways land on one cell"); + assert_eq!(z, direct); +} + /// Zonal Statistics and Tabulate Area place zones held in another system than the raster's by the /// direct operation between the two: a square held in Gauss-Krüger zone 3 on DHDN covers the cells /// of a raster in UTM 32N on ETRS89 that the same square converted there by [`Crs::to`] covers, diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index e6cb7f3808..6d5de24b21 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -15,6 +15,9 @@ pub struct Pick { pub points: Vec, } +/// A layer's systems: the one it holds its coordinates in, and the one it was read in. +type LayerSystems = (rustgis_engine::data::raster::Crs, Option); + /// The Workflows pane's inputs and results. #[derive(Default)] pub struct Workflow { @@ -64,14 +67,17 @@ pub struct Workflow { pub spectral: crate::spectralui::Spectral, pub selected_only: Option, /// The projected coordinate system the Geostatistical Wizard's surface is made in; empty: the - /// environment's, else the projected one the layer was read in, else degrees. + /// environment's, else the projected one the layer holds its coordinates in, else the one it + /// was read in, else degrees. pub crs: String, /// The system the Wizard's surface was last to be made in (its own, else the environment's): /// when it changes, the cell size typed for it is cleared. pub wizard_system: String, - /// The system the Wizard's layer was read in, and the one its surface is made in from it - /// ([`rustgis_engine::analysis::layer_raster_crs`]), kept so it is worked out once. - pub layer_system: Option<(rustgis_engine::data::raster::Crs, Option)>, + /// The systems the Wizard's layer holds its coordinates in and was read in, and the one its + /// surface is made in from them (the held one when projected, + /// [`rustgis_engine::analysis::works_in`], else the read-in one, + /// [`rustgis_engine::analysis::layer_raster_crs`]), kept so it is worked out once. + pub layer_system: Option<(LayerSystems, Option)>, /// The coordinate system typed for a new ortho or reality workspace; empty: the images' /// projected system, else degrees. pub workspace_crs: String, @@ -906,15 +912,17 @@ pub fn workflows(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { heading(ui, "Interpolate a surface from points (IDW)"); combo(ui, "wf_i", "Layer", &mut app.workflow.layer, &points); combo(ui, "wf_if", "Field", &mut app.workflow.field, &numeric); - // Empty: the environment's system, else the projected one the layer was read in, else - // degrees; the hint shows which. - let read_in = app.session.map().layer_by_name(&app.workflow.layer).and_then(|l| l.dataset.crs); - // The run's choice; kept for the layer's system, so a projection isn't built every frame. - let layer_crs = match (read_in, app.workflow.layer_system) { + // Empty: the environment's system, else the projected one the layer holds its + // coordinates in, else the one it was read in, else degrees; the hint shows which. + let systems = app.session.map().layer_by_name(&app.workflow.layer).map(|l| (l.dataset.coord_crs(), l.dataset.crs)); + // The run's choice; kept for the layer's systems, so a projection isn't built every + // frame. + let layer_crs = match (systems, app.workflow.layer_system) { (Some(c), Some((seen, chosen))) if seen == c => chosen, - (Some(c), _) => { - let chosen = rustgis_engine::analysis::layer_raster_crs(Some(c)).and_then(Result::ok); - app.workflow.layer_system = Some((c, chosen)); + (Some((held, read_in)), _) => { + let from = if rustgis_engine::analysis::works_in(held) { Some(held) } else { read_in }; + let chosen = rustgis_engine::analysis::layer_raster_crs(from).and_then(Result::ok); + app.workflow.layer_system = Some(((held, read_in), chosen)); chosen } (None, _) => None, diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 3aca7bee80..bf2ff77153 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -2088,7 +2088,9 @@ The Imagery tab's groups open their tools in the Workflows pane. The tab belongs yet and no cap on its work: each polygon fills the cells it covers, so many large polygons on a fine grid take time in proportion. - **Classification Wizard** (unsupervised k-means) and **Classification Tools** (minimum distance - from training polygons). + from training polygons). Training polygons held in a coordinate system of their own are read as + they are: a pixel's centre is converted into their system to be tested, straight by the + transformation between the two datums where they differ, as for Deep Learning Tools. - **Mensuration**: distances along the surface, heights between two points, areas, and volumes above or below a base height, with a list of results. @@ -2354,8 +2356,9 @@ the wrong field. ## Deep learning and hosted imagery **Imagery › Deep Learning Tools** trains a neural network (a multilayer perceptron) on the pixels -under training polygons and classifies every pixel, adding a class raster with a confidence band -and reporting the accuracy on held-back pixels. Run from its pane in the desktop app, it trains +under training polygons (tested in the system their layer holds them in, as for Classification +Tools) and classifies every pixel, adding a class raster with a confidence band and reporting the +accuracy on held-back pixels. Run from its pane in the desktop app, it trains on every sampled pixel for all the epochs asked, however long that takes, and can be cancelled; elsewhere it keeps to a few seconds of work (see the limits above). Trained models stay in the project; **Publish › Share As › Deep Learning** saves one as a package to apply in other projects. **Imagery › Create diff --git a/docs/user-guide/editing.md b/docs/user-guide/editing.md index 9cd0fda6e3..663b15e688 100644 --- a/docs/user-guide/editing.md +++ b/docs/user-guide/editing.md @@ -146,7 +146,9 @@ you edit the value or choose units; click **Apply elevation** to apply the new i - **Settings**: **Show Vertices** marks the vertices of the selected features even when Edit Vertices isn't on (`edit.settings={"showVertices": true}`). - **Elevation**: new features get a `z` attribute, constant or sampled from a raster surface at - the feature's label point; this is not a change to its geometry's coordinates. + the feature's label point, as the layer holds it, placed on the surface by the transformation + between the two systems; this is not a change to its geometry's coordinates. An edit whose + label point the surface's system can't give is refused. - **Ground to grid**: a scale factor and rotation applied to entered distances and directions (Move, and `edit.traverse`, which draws a line or polygon from distances and bearings). - **Topology**: rules (must not overlap, must not have gaps, must not self-intersect, must not