Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion crates/analysis/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
81 changes: 69 additions & 12 deletions crates/analysis/src/neural.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,12 +136,27 @@ pub fn training_samples(
classes: usize,
max_per_class: usize,
) -> Result<(Vec<(Vec<f32>, usize)>, Vec<usize>), 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<Vec<Coord>>, usize, usize)],
classes: usize,
max_per_class: usize,
) -> Result<(Vec<(Vec<f32>, usize)>, Vec<usize>), String> {
let zone = crate::rasterops::ZoneIn::new(r, from)?;
crate::control::begin(polygons.len());
let mut samples: Vec<(Vec<f32>, 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) {
Expand All @@ -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<Coord>], max: usize) -> Vec<Vec<f32>> {
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<Coord>], max: usize) -> Vec<Vec<f32>> {
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 {
Expand Down Expand Up @@ -198,7 +231,7 @@ pub fn polygon_samples(r: &Raster, bands: &[usize], rings: &[Vec<Coord>], 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::<Option<Vec<f32>>>()
{
Expand Down Expand Up @@ -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<Coord> = [(-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]
Expand Down
55 changes: 43 additions & 12 deletions crates/analysis/src/rasterops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1059,16 +1059,34 @@ 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<u32>, Range<u32>) {
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<Coord> {
pub(crate) fn zone(&self, r: &Raster, w: Coord) -> Option<Coord> {
match self {
Self::LonLat => r.transformer().to_lonlat(w),
Self::Own { to_zone, .. } => to_zone.place(w),
}
}

/// A place in the zone's system in the raster's.
fn grid(&self, r: &Raster, c: Coord) -> Option<Coord> {
pub(crate) fn grid(&self, r: &Raster, c: Coord) -> Option<Coord> {
match self {
Self::LonLat => r.transformer().from_lonlat(c),
Self::Own { to_grid, .. } => to_grid.vertex(c),
Expand Down Expand Up @@ -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)?;
Expand Down Expand Up @@ -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<Vec<Coord>>)]) -> Result<Vec<(String, Vec<f64>, 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<Vec<Coord>>)],
) -> Result<Vec<(String, Vec<f64>, 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<f64>, usize)> = Vec::new();
for (key, rings) in polygons {
Expand All @@ -1247,7 +1272,7 @@ pub fn class_means(r: &Raster, bands: &[usize], polygons: &[(String, Vec<Vec<Coo
crate::control::advance(rows);
Ok(())
};
let Some((m, n)) = means_under(r, &ZoneIn::LonLat, bands, &[rings.as_slice()], counted)? else { continue };
let Some((m, n)) = means_under(r, &zone, bands, &[rings.as_slice()], counted)? else { continue };
match classes.iter_mut().find(|c| c.0 == *key) {
Some(c) => {
let total = c.2 + n;
Expand Down Expand Up @@ -1403,6 +1428,12 @@ pub fn transform_polygon_to_lonlat(rings: &[Vec<Coord>], 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<Vec<Coord>>]) -> Result<Vec<Vec<Vec<Coord>>>, 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.
Expand Down Expand Up @@ -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]
Expand Down
6 changes: 3 additions & 3 deletions crates/analysis/src/tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5130,7 +5130,7 @@ pub fn raster_crs(ds: &Dataset, p: &Json, tool: &str) -> Result<(Crs, Option<Str

/// [`raster_crs`] for a run in `work` ([`Inputs::work_crs`]): a layer held in its own projected
/// system makes its grid there unless `p` names another.
fn raster_crs_in(ds: &Dataset, work: Crs, p: &Json, tool: &str) -> Result<(Crs, Option<String>), String> {
pub fn raster_crs_in(ds: &Dataset, work: Crs, p: &Json, tool: &str) -> Result<(Crs, Option<String>), String> {
if work == Crs::LonLat {
raster_crs_of(ds.crs, "was read in", &ds.name, p, tool)
} else {
Expand Down Expand Up @@ -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>), String> {
pub fn points_from(from: Crs, crs: Crs, pts: Vec<(Coord, f64)>) -> Result<(Vec<(Coord, f64)>, Option<String>), String> {
if from == crs {
return Ok((pts, None));
}
Expand Down Expand Up @@ -8295,7 +8295,7 @@ fn zonal_stats_on(inp: &dyn Inputs, p: &Json, threads: Option<usize>) -> 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)?;
Expand Down
2 changes: 1 addition & 1 deletion crates/analysis/src/tools/tabulate_area.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
7 changes: 6 additions & 1 deletion crates/data/src/raster/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
Expand Down
4 changes: 3 additions & 1 deletion crates/engine/src/cmd/deeplearning.rs
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,9 @@ impl Training {
name: String,
) -> Result<DlModel, String> {
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"));
Expand Down
Loading
Loading