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
6 changes: 6 additions & 0 deletions crates/analysis/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,12 @@ const OWN_SYSTEM_TOOLS: &[&str] = &[
"simplify",
"pointsAlongLines",
"near",
// Grids and zones on rasters, from the system's own coordinates (#2032 C2e-4).
"idwInterpolation",
"kriging",
"kernelDensity",
"zonalStats",
"tabulateArea",
];

impl ToolSpec {
Expand Down
55 changes: 44 additions & 11 deletions crates/analysis/src/rasterops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1290,6 +1290,8 @@ pub fn transform_polygon_to_lonlat(rings: &[Vec<Coord>], tr: Option<&Transformer
}

/// 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.
pub fn transform_feature_polygons_to_lonlat(
polys: &[Vec<Vec<Coord>>],
tr: Option<&Transformer>,
Expand Down Expand Up @@ -1389,8 +1391,26 @@ pub fn parse_bands_str(s: &str, total_bands: usize) -> Result<Vec<usize>, String
Ok(out)
}

/// How polygons' places reach a grid's coordinate system: from longitude/latitude through its
/// transformer, or from a run's own system ([`crate::tools::ToGrid`]: as they are when the grid is
/// in it too).
#[derive(Clone, Copy)]
pub(crate) enum ToWorld<'a> {
LonLat(&'a Transformer),
Own(&'a crate::tools::ToGrid),
}

impl ToWorld<'_> {
fn world(&self, c: Coord) -> Option<Coord> {
match self {
Self::LonLat(tr) => tr.from_lonlat(c),
Self::Own(to) => to.vertex(c),
}
}
}

/// Projects a complete ring to the raster grid without dropping failed vertices.
fn project_ring(tr: &Transformer, t: &GeoTransform, ring: &[Coord]) -> Option<Vec<(f64, f64)>> {
fn project_ring(tr: ToWorld<'_>, t: &GeoTransform, ring: &[Coord]) -> Option<Vec<(f64, f64)>> {
if ring.len() < 3 {
return None;
}
Expand All @@ -1399,7 +1419,7 @@ fn project_ring(tr: &Transformer, t: &GeoTransform, ring: &[Coord]) -> Option<Ve
if !c.is_finite() {
return None;
}
let pt = t.to_pixel(tr.from_lonlat(c)?);
let pt = t.to_pixel(tr.world(c)?);
(pt.0.is_finite() && pt.1.is_finite()).then_some(pt)
})
.collect()
Expand All @@ -1424,13 +1444,13 @@ pub fn polygon_mask_with_failures(
polygons: &[Vec<Vec<Coord>>],
failed_parts: &mut Vec<usize>,
) -> Result<Option<(Range<u32>, Range<u32>, Vec<bool>)>, String> {
polygon_mask_on(r.transformer(), &r.transform, (r.width, r.height), polygons, failed_parts)
polygon_mask_on(ToWorld::LonLat(r.transformer()), &r.transform, (r.width, r.height), polygons, failed_parts)
}

/// [`polygon_mask_with_failures`] on a grid of `size` (columns, rows) cells placed by `t` in the
/// coordinate system of `tr`, with no raster on it yet.
pub(crate) fn polygon_mask_on(
tr: &Transformer,
tr: ToWorld<'_>,
t: &GeoTransform,
size: (u32, u32),
polygons: &[Vec<Vec<Coord>>],
Expand Down Expand Up @@ -1465,8 +1485,8 @@ pub(crate) fn polygon_mask_on(
Ok(Some((cols, rows, trimmed)))
}

/// Polygons (each an exterior ring and its holes, in longitude/latitude) projected to a grid's
/// pixels, with the window of the grid around them.
/// Polygons (each an exterior ring and its holes, their places reaching the grid's system by a
/// [`ToWorld`]) projected to a grid's pixels, with the window of the grid around them.
pub(crate) struct Placed {
parts: Vec<Vec<Vec<(f64, f64)>>>,
width: u32,
Expand All @@ -1487,7 +1507,7 @@ impl Placed {
/// `None` when no polygon can be placed or none reaches the grid of `size` (columns, rows).
/// The zero-based indices of the rejected parts are appended to `failed_parts`.
pub(crate) fn new(
tr: &Transformer,
tr: ToWorld<'_>,
t: &GeoTransform,
size: (u32, u32),
polygons: &[Vec<Vec<Coord>>],
Expand Down Expand Up @@ -1682,6 +1702,17 @@ pub(crate) fn zonal_statistics_with_failures(
bands: &[usize],
polygons: &[Vec<Vec<Coord>>],
failed_parts: &mut Vec<usize>,
) -> Result<Vec<ZoneStats>, String> {
zonal_statistics_from(r, ToWorld::LonLat(r.transformer()), bands, polygons, failed_parts)
}

/// [`zonal_statistics_with_failures`] for polygons whose places reach the raster's system by `to`.
pub(crate) fn zonal_statistics_from(
r: &Raster,
to: ToWorld<'_>,
bands: &[usize],
polygons: &[Vec<Vec<Coord>>],
failed_parts: &mut Vec<usize>,
) -> Result<Vec<ZoneStats>, String> {
r.require_coordinates()?;
for &b in bands {
Expand All @@ -1693,7 +1724,7 @@ pub(crate) fn zonal_statistics_with_failures(
return Ok(Vec::new());
}

let Some((cols, rows, mask)) = polygon_mask_with_failures(r, polygons, failed_parts)? else {
let Some((cols, rows, mask)) = polygon_mask_on(to, &r.transform, (r.width, r.height), polygons, failed_parts)? else {
return Ok(vec![ZoneStats::default(); bands.len()]);
};

Expand Down Expand Up @@ -2586,9 +2617,11 @@ mod tests {
}
polygons.push(rings);
}
let found = polygon_mask_on(&tr, &t, (width, height), &polygons, &mut Vec::new()).unwrap();
let parts: Vec<Vec<Vec<(f64, f64)>>> =
polygons.iter().map(|rings| rings.iter().map(|ring| project_ring(&tr, &t, ring).unwrap()).collect()).collect();
let found = polygon_mask_on(ToWorld::LonLat(&tr), &t, (width, height), &polygons, &mut Vec::new()).unwrap();
let parts: Vec<Vec<Vec<(f64, f64)>>> = polygons
.iter()
.map(|rings| rings.iter().map(|ring| project_ring(ToWorld::LonLat(&tr), &t, ring).unwrap()).collect())
.collect();
let want = plain(&parts, width, height);
let mut got = vec![false; want.len()];
if let Some((cols, rows, mask)) = found {
Expand Down
124 changes: 102 additions & 22 deletions crates/analysis/src/tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -901,7 +901,7 @@ pub static TOOLS: &[ToolSpec] = &[
kind: K::Text,
required: false,
default: "",
help: "A projected coordinate system (e.g. EPSG:32618) to make the raster in, its units for the extent and pixel size; when empty, the one the layer was read in if projected, else degrees; EPSG:4326 for degrees.",
help: "A projected coordinate system (e.g. EPSG:32618) to make the raster in, its units for the extent and pixel size; when empty, the projected one the layer is held in, or else was read in, else degrees; EPSG:4326 for degrees.",
},
P { name: "output", label: "Output Name", kind: K::Text, required: false, default: "", help: "" },
],
Expand Down Expand Up @@ -1067,7 +1067,7 @@ pub static TOOLS: &[ToolSpec] = &[
kind: K::Text,
required: false,
default: "",
help: "A projected coordinate system (e.g. EPSG:32618) to make the raster in, its units for the extent, pixel size and range; when empty, the one the layer was read in if projected, else degrees; EPSG:4326 for degrees.",
help: "A projected coordinate system (e.g. EPSG:32618) to make the raster in, its units for the extent, pixel size and range; when empty, the projected one the layer is held in, or else was read in, else degrees; EPSG:4326 for degrees.",
},
P { name: "output", label: "Output Name", kind: K::Text, required: false, default: "", help: "" },
],
Expand Down Expand Up @@ -1317,7 +1317,7 @@ pub static TOOLS: &[ToolSpec] = &[
kind: K::Text,
required: false,
default: "",
help: "Projected coordinate system (e.g. EPSG:32618); defaults to the layer's CRS when projected, or required when the layer has none or is in degrees.",
help: "Projected coordinate system (e.g. EPSG:32618); defaults to the projected system the layer is held in, or else was read in; required when the layer has none or is in degrees.",
},
P { name: "output", label: "Output Name", kind: K::Text, required: false, default: "", help: "Output raster layer name." },
],
Expand Down Expand Up @@ -4761,8 +4761,8 @@ fn idw_interpolation(inp: &dyn Inputs, p: &Json) -> Result<ToolResult, String> {
}
});
}
let (crs, crs_note) = raster_crs(ds, p, "IDW Interpolation")?;
let (pts, beyond_note) = points_in(crs, pts)?;
let (crs, crs_note) = raster_crs_in(ds, inp.work_crs(), p, "IDW Interpolation")?;
let (pts, beyond_note) = points_from(inp.work_crs(), crs, pts)?;
let extent = match s(p, "extent").trim() {
"" => {
let mut e = Extent::EMPTY;
Expand Down Expand Up @@ -4854,8 +4854,8 @@ fn kriging_interpolation(inp: &dyn Inputs, p: &Json) -> Result<ToolResult, Strin
}
}
}
let (crs, crs_note) = raster_crs(ds, p, "Ordinary Kriging")?;
let (raw_pts, beyond_note) = points_in(crs, raw_pts)?;
let (crs, crs_note) = raster_crs_in(ds, inp.work_crs(), p, "Ordinary Kriging")?;
let (raw_pts, beyond_note) = points_from(inp.work_crs(), crs, raw_pts)?;
// Points at the same place as one, so the kriging matrix isn't singular.
let pts = merge_coincident(raw_pts)?;
if pts.len() < 2 {
Expand Down Expand Up @@ -5051,26 +5051,39 @@ pub fn layer_raster_crs(crs: Option<Crs>) -> Option<Result<Crs, String>> {
/// run used where that could surprise: the system it took from the layer, or the compatibility note
/// on the one given.
pub fn raster_crs(ds: &Dataset, p: &Json, tool: &str) -> Result<(Crs, Option<String>), String> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doc is now stale (the line above it, 5050, says "as Kernel Density uses"). In a run in a layer's own projected system, Kernel Density, IDW and Kriging (through raster_crs_in) take the system the layer is held in, not the one it was read in. The read-in default described here is only what the Geostatistical Wizard and the longitude/latitude path still use. Suggest naming that explicitly, e.g. "the projected system ds was read in, as the Geostatistical Wizard uses; the interpolations and Kernel Density use the one it is held in (see raster_crs_in)".

Category: quality

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in #2686 (ecb1e5b): raster_crs's doc now says the read-in default is for the Geostatistical Wizard and runs in longitude/latitude, and that the interpolations and Kernel Density take the held system through raster_crs_in in a run in a layer's own projected system.

raster_crs_of(ds.crs, "was read in", &ds.name, p, tool)
}

/// [`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> {
if work == Crs::LonLat {
raster_crs_of(ds.crs, "was read in", &ds.name, p, tool)
} else {
raster_crs_of(Some(work), "is held in", &ds.name, p, tool)
}
}

/// [`raster_crs`] for a layer named `name` that `how` ("was read in", "is held in") `layer_crs`.
fn raster_crs_of(layer_crs: Option<Crs>, how: &str, name: &str, p: &Json, tool: &str) -> Result<(Crs, Option<String>), String> {
if p.get("crs").is_some_and(|v| !v.is_null() && !v.is_string()) {
return Err("crs must be text".into());
}
match s(p, "crs").trim() {
"" => Ok(match layer_raster_crs(ds.crs) {
"" => Ok(match layer_raster_crs(layer_crs) {
// A system that can't hold a raster's cells (geocentric), or one this version can't
// project to: degrees, as before, and said why.
Some(Err(why)) => (
Crs::LonLat,
Some(format!(
"{tool}: made in degrees of longitude and latitude, though {} was read in {why}; give a projected crs to make it in metres or feet",
ds.name
"{tool}: made in degrees of longitude and latitude, though {name} {how} {why}; give a projected crs to make it in metres or feet"
)),
),
Some(Ok(c)) => (
c,
Some(format!(
"{tool}: made in {}, the coordinate system {} was read in, with its units for the extent and sizes; set crs to EPSG:4326 to make it in degrees",
c.label(),
ds.name
"{tool}: made in {}, the coordinate system {name} {how}, with its units for the extent and sizes; set crs to EPSG:4326 to make it in degrees",
c.label()
)),
),
None => (Crs::LonLat, None),
Expand Down Expand Up @@ -5104,10 +5117,16 @@ pub fn projected_crs(text: &str) -> Result<(Crs, Option<String>), String> {
/// can't hold them (see [`in_projected`]). A point costs a projection and its round trip: Cancel is
/// looked at every [`LOOK_EVERY`] points.
pub fn points_in(crs: Crs, pts: Vec<(Coord, f64)>) -> Result<(Vec<(Coord, f64)>, Option<String>), String> {
if crs == Crs::LonLat {
points_from(Crs::LonLat, crs, pts)
}

/// [`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> {
if from == crs {
return Ok((pts, None));
}
let to = crs.transformer()?;
let to = ToGrid::new(from, crs)?;
let n = pts.len();
// (In the points' own storage, as a filtered collect of the same kind reuses it.)
let kept: Vec<(Coord, f64)> = pts
Expand All @@ -5119,7 +5138,7 @@ pub fn points_in(crs: Crs, pts: Vec<(Coord, f64)>) -> Result<(Vec<(Coord, f64)>,
{
return Some(Err(cancelled));
}
in_projected(crs, &to, c).map(|c| Ok((c, v)))
to.place(c).map(|c| Ok((c, v)))
})
.collect::<Result<_, crate::control::Cancelled>>()?;
let beyond = n - kept.len();
Expand Down Expand Up @@ -5149,6 +5168,59 @@ fn in_projected(crs: Crs, to: &Transformer, c: Coord) -> Option<Coord> {
held.then(|| to.from_lonlat(c)).flatten().filter(|p| p.is_finite() && to.to_lonlat(*p).is_some_and(|back| (back.y - c.y).abs() < 1e-4))
}

/// Places in a run's own system converted to a grid's system `crs`, as [`in_projected`] takes
/// them from longitude/latitude: a place `crs` can't hold is `None`. From longitude/latitude, that
/// conversion; from the grid's own system, the place as it is; from another, through
/// longitude/latitude for the check, then the direct operation between the two where it lands
/// near that ([`Reprojection::point_near`]), so a datum pair takes its best operation.
///
/// [`Reprojection::point_near`]: rustgis_data::raster::Reprojection::point_near
pub(crate) struct ToGrid {
crs: Crs,
same: bool,
/// The run's system's transformer, `None` from longitude/latitude.
from: Option<Transformer>,
to: Transformer,
direct: Option<rustgis_data::raster::Reprojection>,
}

impl ToGrid {
pub(crate) fn new(from: Crs, crs: Crs) -> Result<Self, String> {
let same = from == crs;
let unproject = if same || from == Crs::LonLat { None } else { Some(from.transformer()?) };
let direct = if unproject.is_some() { Some(from.to(crs)?) } else { None };
Ok(Self { crs, same, from: unproject, to: crs.transformer()?, direct })
}

pub(crate) fn place(&self, c: Coord) -> Option<Coord> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Performance, low confidence. For a place in another projected system, each call now makes several PROJ transforms: to_lonlat, from_lonlat, the round-trip check inside in_projected, and point_near's direct operation. Before, Zonal Statistics copied the polygons to lon/lat once (one transform per vertex) and then projected each vertex once. So for zones on a raster in another system, the per-vertex cost may roughly double, while same-system runs get cheaper. Could you measure a large zone layer (tens of thousands of vertices, or one with millions) on that path with cargo xtask memory or a timing run, and say the result in the PR?

Category: performance

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not measured. Counting transforms per vertex:

  • Same system (the usual case, a raster or grid in the layer's own system): none, where before there were two, one to longitude/latitude for the copy and one onto the grid.
  • Zones in another projected system: the inverse, the raster's forward and the direct operation, so three, against two before. The whole longitude/latitude copy of the layer is gone. The direct operation is what makes a datum pair land 0.44 m nearer (zones_reach_a_raster_by_the_direct_operation).
  • Points in another projected system: as before, the inverse, the forward and in_projected's round trip, plus the direct operation.

So only a run on a raster in another datum pays one more transform per vertex, and that is the cost of the right operation. The PR body's Memory section says this is reasoned, not measured.

if self.same {
return c.is_finite().then_some(c);
}
let lonlat = match &self.from {
Some(t) => t.to_lonlat(c)?,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low confidence, quality. t.to_lonlat(c)? fails when the run's own system can't turn a place into longitude/latitude. That is not the grid's system refusing the place, but points_from counts it in the same beyond bucket, so the note reads "N point(s) beyond what can hold were left out". That attributes the loss to the wrong system. Before this PR the run's coordinates were never inverted here, so this is a new misattribution. Rare in practice (it needs a finite place the source projection can't invert), so a separate count or wording for the source-side failure would be enough.

Category: quality

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in #2686 (ecb1e5b), since this PR was approved and merging. ToGrid::try_place says which system failed. A point the run's own system can't give in longitude/latitude is now counted apart: "N point(s) that can't give in longitude/latitude were left out". Points the grid can't hold keep the "beyond what can hold" note. Tested in a_point_its_own_system_cant_give_is_said_as_such.

None => c,
};
let via = in_projected(self.crs, &self.to, lonlat)?;
Some(self.direct.as_ref().map_or(via, |d| d.point_near(c, via)))
}

/// A polygon's vertex in the grid's system, as the grid's transformer takes a place in
/// longitude/latitude, with no check: Web Mercator takes a latitude past 85.05° as 85.05°, so a
/// zone reaching past it keeps its part below, as zones in longitude/latitude always did. Then
/// the direct operation's coordinates where it lands near that, as [`ToGrid::place`].
pub(crate) fn vertex(&self, c: Coord) -> Option<Coord> {
if self.same {
return c.is_finite().then_some(c);
}
let lonlat = match &self.from {
Some(t) => t.to_lonlat(c)?,
None => c,
};
let via = self.to.from_lonlat(lonlat).filter(|p| p.is_finite())?;
Some(self.direct.as_ref().map_or(via, |d| d.point_near(c, via)))
}
}

/// The note on a system an interpolation took from the layer (`p`'s `crs` empty), naming the values
/// among `keys` that `p` gives, read in its units: a script written when these tools worked in
/// degrees is told, not answered in metres without a word (#1743). An `extent` that holds none of
Expand Down Expand Up @@ -5236,9 +5308,11 @@ fn kernel_density_tool(inp: &dyn Inputs, p: &Json) -> Result<ToolResult, String>
}

let crs_text = s(p, "crs").trim();
// The system the layer is held in, in a run in its own; else the one it was read in.
let layer_crs = if inp.work_crs() == Crs::LonLat { ds.crs } else { Some(inp.work_crs()) };
let (crs, crs_note) = if !crs_text.is_empty() {
crs_with_compatibility_note(crs_text)?
} else if let Some(c) = ds.crs {
} else if let Some(c) = layer_crs {
(c, None)
} else {
return Err(format!(
Expand All @@ -5260,7 +5334,9 @@ fn kernel_density_tool(inp: &dyn Inputs, p: &Json) -> Result<ToolResult, String>
));
}

let transformer = crs.transformer()?;
// From the layer's own system when it is held in one (straight through when that is the
// grid's), else from longitude/latitude.
let to_grid = ToGrid::new(inp.work_crs(), crs)?;

if p.get("field").is_some_and(|v| !v.is_null() && !v.is_string()) {
return Err("field must be text".into());
Expand Down Expand Up @@ -5288,7 +5364,7 @@ fn kernel_density_tool(inp: &dyn Inputs, p: &Json) -> Result<ToolResult, String>
// feature with none is counted in `skipped`).
let (mut non_finite, mut non_finite_features) = (0usize, 0usize);
let project = |c: Coord, beyond: &mut usize| {
let p = in_projected(crs, &transformer, c);
let p = to_grid.place(c);
*beyond += usize::from(p.is_none());
p
};
Expand Down Expand Up @@ -8011,6 +8087,10 @@ fn zonal_stats_on(inp: &dyn Inputs, p: &Json, threads: Option<usize>) -> Result<
// bounds the threads too.
let mask_bytes = (r.width as usize).saturating_mul(r.height as usize).saturating_mul(2);
let threads = threads.unwrap_or_else(|| crate::parallel::threads_for_scratch(target_rows.len(), PARALLEL_FEATURES, mask_bytes));
// The polygons are in the run's system: their own projected one, converted to the raster's
// (none of it when that is the raster's too), else longitude/latitude.
let own = (inp.work_crs() != Crs::LonLat).then(|| ToGrid::new(inp.work_crs(), r.crs)).transpose()?;
let to = own.as_ref().map_or(crate::rasterops::ToWorld::LonLat(r.transformer()), crate::rasterops::ToWorld::Own);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
crate::control::begin(target_rows.len());
// A feature's statistics by band, whether its geometry was read, its parts that couldn't be
// projected and what went wrong.
Expand All @@ -8023,11 +8103,11 @@ fn zonal_stats_on(inp: &dyn Inputs, p: &Json, threads: Option<usize>) -> Result<
let Some(f) = poly_ds.features.get(r_idx) else { return Ok((none(), false, 0, None)) };
Ok::<_, String>(match &f.geometry {
Some(Geometry::Polygon(polys)) if !polys.is_empty() => {
// Dataset geometry is already lon/lat; crs records the source system.
// Checked and taken apart into rings, in the run's system as they are.
match crate::rasterops::transform_feature_polygons_to_lonlat(polys, None) {
Ok(polys_lonlat) => {
Ok(rings) => {
let mut failed_parts = Vec::new();
let st = crate::rasterops::zonal_statistics_with_failures(r, &bands, &polys_lonlat, &mut failed_parts)?;
let st = crate::rasterops::zonal_statistics_from(r, to, &bands, &rings, &mut failed_parts)?;
let detail = (!failed_parts.is_empty())
.then(|| format!("feature {}: raster projection failed for polygon part(s) {failed_parts:?}", f.id));
(st, true, failed_parts.len(), detail)
Expand Down
Loading
Loading