Skip to content
Closed
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
165 changes: 145 additions & 20 deletions crates/analysis/src/warp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@

use std::collections::HashMap;

use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster, Transformer, max_samples};
use rustgis_data::raster::crs::grid_generation;
use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster, Reprojection, Transformer, max_samples};
use rustgis_geom::Coord;

use crate::georef::Fit;
Expand Down Expand Up @@ -78,7 +79,9 @@ pub struct Options {
pub name: String,
}

/// Map coordinates of the fit, to and from the output's coordinate system.
/// Map coordinates in one coordinate system to another's through longitude/latitude: for the
/// footprints and bounds other commands size a grid by ([`footprint_in`], [`bounds_in`]), and
/// [`Route`] between two systems on one datum.
struct Reproject {
from: Transformer,
to: Transformer,
Expand All @@ -90,25 +93,56 @@ impl Reproject {
Ok(Reproject { from: points.transformer()?, to: out.transformer()?, same: points == out })
}

/// Fit coordinates to output coordinates.
/// Coordinates in the first system to the second's.
fn forward(&self, x: f64, y: f64) -> Option<(f64, f64)> {
if self.same {
return (x.is_finite() && y.is_finite()).then_some((x, y));
}
let c = self.to.from_lonlat(self.from.to_lonlat(Coord::new(x, y))?)?;
Some((c.x, c.y))
}
}

/// Output coordinates to fit coordinates.
fn back(&self, x: f64, y: f64) -> Option<(f64, f64)> {
if self.same {
return (x.is_finite() && y.is_finite()).then_some((x, y));
/// Map coordinates in one coordinate system to another's as Project Raster and Georeference
/// place them. Between two datums, by the transformation between them ([`Crs::to`]) rather than
/// each datum's shift to WGS 84 and back; it falls back to WGS 84 where the datums have no
/// transformation between them or it can't place a point. Between two systems on one datum,
/// through longitude/latitude as before, so such a grid is sized and sampled as it always was:
/// the direct operation's rounding differs, which can move a grid's edge across a cell.
enum Route {
Direct(Reprojection),
Lonlat(Reproject),
}

impl Route {
/// The route from `from` to `to`: direct when [`Crs::to`] shifts datum between them. Fails as
/// either system's transformer does.
fn new(from: Crs, to: Crs) -> Result<Route, String> {
let re = from.to(to)?;

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.

Crs::to builds a DirectPair for every pair of two non-WGS 84 systems (crates/data/src/raster/reproject.rs, DirectPair::new), and DirectPair::new calls wait_for_grids and note_used before it returns. So Route::new does that work even when it then picks Route::Lonlat for a one-datum pair, and the PR text says "Only the operations each step uses are built". For a one-datum projection that is new work versus main: a possible wait on grid downloads, and the pair is noted as used. The output is unchanged, but the "as before" claim in the PR and in the Route doc is not exact. Consider deciding shifts_datum before building the direct pair, or saying in the PR that the pair is still built and noted.

Category: performance

if re.shifts_datum() { Ok(Route::Direct(re)) } else { Reproject::new(from, to).map(Route::Lonlat) }
}

/// The place `(x, y)` in the second system, as an `(x, y)` pair.
fn point(&self, x: f64, y: f64) -> Option<(f64, f64)> {
match self {
Route::Direct(re) => re.point(Coord::new(x, y)).map(|c| (c.x, c.y)),
Route::Lonlat(re) => re.forward(x, y),
}
let c = self.from.from_lonlat(self.to.to_lonlat(Coord::new(x, y))?)?;
Some((c.x, c.y))
}
}

/// Runs `f`, refusing its result when datum grids arrived meanwhile ([`grid_generation`]): its
/// conversions, built again for them, may then have placed one raster by two transformations.
/// Nothing is kept from a refused run.
pub fn on_unchanged_grids<T>(what: &str, f: impl FnOnce() -> Result<T, String>) -> Result<T, 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.

The refusal branch (datum grids arrived while … ran) has no test. The PR explains why: bumping the process-wide generation in the shared test binary would make other projection tests refuse. A test that stays on this function could still cover it: pass a closure that changes the generation (through a test hook, or by a grid folder change under a lock the other projection tests also take), then check that it returns Err and that a closure with no change returns Ok. Without this, the "Test both ways" rule for refusals is only covered by the description.

Category: quality

let generation = grid_generation();
let out = f()?;
if grid_generation() != generation {
return Err(format!("datum grids arrived while {what} ran, so its cells may be placed by two transformations: run it again"));
}
Ok(out)
}

/// Reads pixels at fractional image positions.
struct Sampler<'a> {
r: &'a Raster,
Expand Down Expand Up @@ -218,15 +252,22 @@ impl Sampler<'_> {
/// `r` (in the full image's pixels, when `r` is an overview of it) and whose map coordinates are
/// in `o.points_crs`. The grid covers the warped image's footprint. A colour or grey byte raster
/// with neither alpha nor no-data gets an alpha band (0–255), so the cells outside the image are
/// see-through. Geographic output cells are square in degrees.
/// see-through. Geographic output cells are square in degrees. Map coordinates go between
/// `o.points_crs` and `o.crs` as [`Route`] takes them. Refused when datum grids arrive while it
/// runs ([`on_unchanged_grids`]).
pub fn warp(r: &Raster, fit: &Fit, o: &Options) -> Result<Raster, String> {
let re = Reproject::new(o.points_crs, o.crs)?;
on_unchanged_grids("the warp", || warp_now(r, fit, o))
}

/// [`warp`], whatever grids arrive.
fn warp_now(r: &Raster, fit: &Fit, o: &Options) -> Result<Raster, String> {
let (forward, back) = (Route::new(o.points_crs, o.crs)?, Route::new(o.crs, o.points_crs)?);
let (w, h) = (f64::from(r.width), f64::from(r.height));
// An overview's pixels are bigger than the full image's, which the fit is in; a grid of
// posts read at a step also starts before the file's corner (each cell centered on its post).
let (sx, sy) = r.file_pixels();
let (ox, oy) = r.file_origin();
let place = |c: f64, row: f64| fit.to_map(c * sx + ox, row * sy + oy).and_then(|(x, y)| re.forward(x, y));
let place = |c: f64, row: f64| fit.to_map(c * sx + ox, row * sy + oy).and_then(|(x, y)| forward.point(x, y));

let [min_x, min_y, max_x, max_y] = footprint(w, h, &place).ok_or("the image's edge can't be placed in the output coordinate system")?;
if o.crs.is_geographic() && max_x - min_x > 180.0 {
Expand Down Expand Up @@ -275,7 +316,7 @@ pub fn warp(r: &Raster, fit: &Fit, o: &Options) -> Result<Raster, String> {
let g = Grid { crs: o.crs, min_x, max_y, cell_x: cell, cell_y: cell, width: ow as usize, height: oh as usize };
// The image position of an output coordinate.
let source = |x: f64, y: f64| -> Option<(f64, f64)> {
let (px, py) = re.back(x, y)?;
let (px, py) = back.point(x, y)?;
let (c, row) = fit.to_pixel(px, py)?;
let (c, row) = ((c - ox) / sx, (row - oy) / sy);
(c.is_finite() && row.is_finite()).then_some((c, row))
Expand Down Expand Up @@ -387,14 +428,29 @@ impl Grid {
}
}

/// The bounds in `crs` of `r`'s footprint, and about the size of its pixel there.
/// The bounds in `crs` of `r`'s footprint, and about the size of its pixel there, through
/// longitude/latitude.
pub fn footprint_in(r: &Raster, crs: Crs) -> Result<([f64; 4], f64), String> {
r.require_coordinates()?;
let re = Reproject::new(r.crs, crs)?;
footprint_by(r, crs, &|x, y| re.forward(x, y))
}

/// [`footprint_in`] placed as [`project`] places `r`'s pixels ([`Route`]), so a grid sized by it
/// holds what `project` samples. Between two systems on one datum, [`footprint_in`].
pub fn projected_footprint(r: &Raster, crs: Crs) -> Result<([f64; 4], f64), String> {
r.require_coordinates()?;
let re = Route::new(r.crs, crs)?;
footprint_by(r, crs, &|x, y| re.point(x, y))
}

/// The bounds and pixel size of [`footprint_in`], `r`'s map coordinates converted to `crs` by
/// `to`.
fn footprint_by(r: &Raster, crs: Crs, to: &dyn Fn(f64, f64) -> Option<(f64, f64)>) -> Result<([f64; 4], f64), String> {
let t = r.transform;
let place = |c: f64, row: f64| {
let p = t.to_world(c, row);
re.forward(p.x, p.y)
to(p.x, p.y)
};
let (w, h) = (f64::from(r.width), f64::from(r.height));
let bounds = footprint(w, h, &place).ok_or_else(|| format!("{} can't be placed in {}", r.name, crs.label()))?;
Expand Down Expand Up @@ -452,9 +508,9 @@ impl Method {
}
}

/// Projects `r` onto the grid `g`, through longitude/latitude when their coordinate systems
/// differ: each cell sampled at its centre, or (average, mode) taken from every pixel of `r`
/// whose centre falls in it. A cell no pixel centre falls in (a grid finer than the raster) takes
/// Projects `r` onto the grid `g`, its coordinates converted as [`Route`] takes them when their
/// systems differ (size the grid with [`projected_footprint`]): each cell sampled at its centre,
/// or (average, mode) taken from every pixel of `r` whose centre falls in it. A cell no pixel centre falls in (a grid finer than the raster) takes
/// the pixel under its centre. Outside cells use 0 in every band when alpha is present or
/// added; otherwise they use explicit no-data. Without either, they use NaN for floating-point
/// data, RGB data with more than three bands, or when any band has class names, else 0.
Expand All @@ -478,10 +534,10 @@ fn project_on(threads: Option<usize>, r: &Raster, g: &Grid, method: Method, name
g.width, g.height, out_bands
));
}
let re = Reproject::new(r.crs, g.crs)?;
let back = Route::new(g.crs, r.crs)?;
let t = r.transform;
let source = |x: f64, y: f64| -> Option<(f64, f64)> {
let (px, py) = re.back(x, y)?;
let (px, py) = back.point(x, y)?;
let (c, row) = t.to_pixel(Coord::new(px, py));
(c.is_finite() && row.is_finite()).then_some((c, row))
};
Expand Down Expand Up @@ -1629,6 +1685,75 @@ mod tests {
}
}

/// Between two datums each cell is sampled where the direct operation puts it (DHDN to ETRS89's
/// transformation), not where each datum's shift to WGS 84 and back does, about 0.44 m away
/// here; on one thread and on several alike.
#[test]
fn a_projection_between_datums_takes_their_transformation() {
// 40 × 40 pixels of 1 m in Gauss-Krüger zone 3 on DHDN, its bands the column and row of a
// place, so bilinear sampling gives back where a cell was sampled.
let (gk3, utm32) = (Crs::from_epsg(31467).unwrap(), Crs::from_epsg(25832).unwrap());
let gt = GeoTransform { origin_x: 3_500_000.0, origin_y: 5_400_040.0, pixel_width: 1.0, pixel_height: -1.0 };
let (col, row): (Vec<f32>, Vec<f32>) = (0..1600).map(|i| ((i % 40) as f32 + 0.5, (i / 40) as f32 + 0.5)).unzip();
let r = Raster::new("t", 40, 40, vec![col, row], gt, gk3, None, ColorHint::Gray, "Float32").unwrap();
let (bounds, _) = projected_footprint(&r, utm32).unwrap();
// Sized on the same route: the corners where the direct operation puts them, not where
// the way through WGS 84 does.
let corners = |to: &dyn Fn(Coord) -> Coord| {
let c: Vec<Coord> = [(0.0, 0.0), (40.0, 0.0), (0.0, 40.0), (40.0, 40.0)].iter().map(|&(i, j)| to(gt.to_world(i, j))).collect();
let (xs, ys) = (c.iter().map(|c| c.x), c.iter().map(|c| c.y));
[
xs.clone().fold(f64::MAX, f64::min),
ys.clone().fold(f64::MAX, f64::min),
xs.fold(f64::MIN, f64::max),
ys.fold(f64::MIN, f64::max),
]
};
let forward = gk3.to(utm32).unwrap();
let sized = corners(&|c| forward.point(c).unwrap());
assert!(bounds.iter().zip(sized).all(|(a, b)| (a - b).abs() < 1e-6), "{bounds:?} against {sized:?}");
let (from, to) = (gk3.transformer().unwrap(), utm32.transformer().unwrap());
let via = corners(&|c| to.from_lonlat(from.to_lonlat(c).unwrap()).unwrap());
assert!(bounds.iter().zip(via).any(|(a, b)| (a - b).abs() > 0.2), "{bounds:?} through WGS 84 is {via:?}");
let g = Grid::snapped(utm32, bounds, (1.0, 1.0), (0.0, 0.0)).unwrap();
let out = project_on(Some(1), &r, &g, Method::Sample(Resampling::Bilinear), "p".into()).unwrap();
let many = project_on(Some(4), &r, &g, Method::Sample(Resampling::Bilinear), "p".into()).unwrap();
let bits = |r: &Raster| r.bands.iter().map(|b| b.data.iter().map(|v| v.to_bits()).collect::<Vec<_>>()).collect::<Vec<_>>();
assert_eq!(bits(&out), bits(&many));
let (direct, back) = (utm32.to(gk3).unwrap(), (utm32.transformer().unwrap(), gk3.transformer().unwrap()));
let pixel = |p: Coord| (p.x - gt.origin_x, gt.origin_y - p.y);
let mut checked = 0;
for j in 0..g.height {
for i in 0..g.width {
let at = Coord::new(g.min_x + (i as f64 + 0.5) * g.cell_x, g.max_y - (j as f64 + 0.5) * g.cell_y);
let want = pixel(direct.point(at).unwrap());
// Away from the edge, where bilinear sampling is linear.
if !(1.0..39.0).contains(&want.0) || !(1.0..39.0).contains(&want.1) {
continue;
}
let got = (f64::from(out.bands[0].data[j * g.width + i]), f64::from(out.bands[1].data[j * g.width + i]));
assert!((got.0 - want.0).abs().max((got.1 - want.1).abs()) < 1e-3, "cell {i}, {j}: {got:?} against {want:?}");
let via = pixel(back.1.from_lonlat(back.0.to_lonlat(at).unwrap()).unwrap());
assert!((via.0 - want.0).hypot(via.1 - want.1) > 0.4, "cell {i}, {j}: {via:?} through WGS 84");
checked += 1;
}
}
assert!(checked > 1000, "{checked} cells checked");
}

/// Between two systems on one datum (UTM 16N and World Mercator, both WGS 84), the grid is
/// sized as it always was, through longitude/latitude: the direct operation's rounding put the
/// east edge across a snapped cell boundary, one column short.
#[test]
fn a_projection_on_one_datum_is_sized_as_before() {
let (utm16, mercator) = (Crs::from_epsg(32616).unwrap(), Crs::from_epsg(3395).unwrap());
let gt = GeoTransform { origin_x: 500_000.0, origin_y: 30.0, pixel_width: 1.0, pixel_height: -1.0 };
let r = Raster::new("t", 40, 30, vec![vec![1.0; 1200]], gt, utm16, None, ColorHint::Gray, "Float32").unwrap();
let (bounds, _) = projected_footprint(&r, mercator).unwrap();
let g = Grid::snapped(mercator, bounds, (1.0, 1.0), (-9_684_795.699_014_802, 0.0)).unwrap();
assert_eq!((g.width, g.height, g.min_x, g.max_y), (42, 31, -9_684_796.699_014_802, 31.0), "{bounds:?}");
}

/// A raster projected to another system and back keeps its values in place, within a cell.
#[test]
fn a_projection_and_back_keeps_values_in_place() {
Expand Down
14 changes: 13 additions & 1 deletion crates/data/src/raster/crs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1092,6 +1092,9 @@ pub(crate) struct DirectOperation {
missing: Vec<MissingGrid>,
/// Its pair's key ([`pair_key`]), what its notes are kept under.
key: String,
/// Whether it changes datum: false between two systems on one datum, where it runs no
/// transformation (at the middle of the source's area of use, which no grid changes).
shifts: bool,
}

// What it noted and the session hasn't asked for yet is the pair's as it goes (built again when
Expand Down Expand Up @@ -1171,6 +1174,12 @@ impl DirectPair {
Some(DirectPair { source, target, from: from.clone(), to: to.clone(), first, built_for, again })
}

/// Whether it changes datum ([`DirectOperation`]'s `shifts`), as first built: grids change
/// which transformation it takes, not whether it takes one.
pub(crate) fn shifts_datum(&self) -> bool {
self.first.shifts
}

/// [`DirectOperation::point`], by the operation built for the grids there are now: as first
/// built until grids arrive (one atomic load), then as built again (a read lock).
pub(crate) fn point(&self, c: Coord, via: Coord) -> Option<Coord> {
Expand Down Expand Up @@ -1267,14 +1276,17 @@ fn build_direct(
};
let at = [source, target].into_iter().find_map(|crs| area_of_use(crs).and_then(|c| from.from_lonlat(c)));
let grids = at.and_then(|c| op.best_operation_grids_at(c.x, c.y, 0.0).ok()).unwrap_or_default();
// No operation there only between two systems on one datum; a place it can't convert, or none
// known, counts as a shift.
let shifts = at.is_none_or(|c| !matches!(op.operation_at(c.x, c.y, 0.0), Ok(None)));

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.

shifts is true when at is None. at is None when neither system has a known area of use (area_of_use returns None for Crs::Custom without a geographic code, and for a place that can't be converted). In that case a one-datum pair, for example two custom proj4 systems on WGS 84, takes the direct route in Route::new. Its sampling and sizing then differ from main's by rounding, which is the case the PR says it keeps unchanged ("byte-identical" for one datum). The doc on DirectOperation::shifts also says the check is at the source's area of use, but the code falls back to the target's. Confidence on the output change is low (about 35%), since it needs two systems without area of use. A check at a point both systems can convert, or a clear default for None, would settle it.

Category: bug

if grids.iter().any(|g| !g.available && !g.optional) {
let mut needs = needs_grid().lock().unwrap_or_else(|e| e.into_inner());
if !needs.iter().any(|d| d == key) {
needs.push(key.to_string());
}
}
let missing = grids.into_iter().filter(downloadable).filter_map(|g| Some(MissingGrid { url: g.url?, name: g.name })).collect();
Some(std::sync::Arc::new(DirectOperation { op, turn, slack, missing, key: key.to_string() }))
Some(std::sync::Arc::new(DirectOperation { op, turn, slack, missing, key: key.to_string(), shifts }))
}

/// The datum grids the direct operation from `source` to `target` needs where the source's data
Expand Down
10 changes: 10 additions & 0 deletions crates/data/src/raster/reproject.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,16 @@ impl Reprojection {
self.direct.is_some()
}

/// Whether it takes a transformation between two datums where it can: the direct operation,
/// between systems on different datums. Between two systems on one datum it converts as the
/// way through WGS 84 does, but for rounding.
pub fn shifts_datum(&self) -> bool {
match &self.through {
Some(through) => through.0.shifts_datum() || through.1.shifts_datum(),
None => self.direct.as_ref().is_some_and(|d| d.shifts_datum()),
}
}

/// A place in the target system, or `None` where the source system has no such place or the
/// target can't hold it. Each system's transformer judges what it is given, as a call of its
/// own did: Web Mercator takes a latitude past 85.05° (an infinite one too) as 85.05°, where
Expand Down
9 changes: 7 additions & 2 deletions crates/engine/src/cmd/imagery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -518,10 +518,15 @@ fn project_raster(s: &mut Session, p: &Value) -> CmdResult {
None | Some(Value::Null) => warp::Method::Sample(warp::Resampling::Nearest),
Some(v) => v.as_str().and_then(warp::Method::parse).ok_or("resampling is nearest, bilinear, cubic, average or mode")?,
};
let grid = grid_param(s, p, r.crs, |crs| warp::footprint_in(&r, crs).map(|(bounds, pixel)| (bounds, Some(pixel))))?;
let path = tif_path(p)?;
let out_name = name(p, format!("{} projected", r.name))?;
let out = warp::project(&r, &grid, method, out_name.clone())?;
// Sized and sampled for the same datum grids: refused, before anything is kept, when one
// arrives between.
let (grid, out) = warp::on_unchanged_grids("Project Raster", || {
let grid = grid_param(s, p, r.crs, |crs| warp::projected_footprint(&r, crs).map(|(bounds, pixel)| (bounds, Some(pixel))))?;
let out = warp::project(&r, &grid, method, out_name.clone())?;
Ok((grid, out))
})?;
let used = method.used_on(&r);
report_resampled_classes(s, &r, &out, used.id());
let mut info = json!({
Expand Down
Loading
Loading