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
14 changes: 12 additions & 2 deletions crates/data/src/export.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,11 @@ fn write_chunks_as(
GeometryType::None => first_kind(src, 1 << 20)?,
t => t,
};
let t = if crs == Crs::LonLat { None } else { Some(Crs::LonLat.to(crs).map_err(DataError::Format)?) };
// From the system the source gives its features in.
let held = src.coord_crs();
let t = if crs == held { None } else { Some(held.to(crs).map_err(DataError::Format)?) };
// The longitude/latitude of a place, for the count of those Web Mercator can't hold.
let to_lonlat = if held == Crs::LonLat { None } else { Some(held.to(Crs::LonLat).map_err(DataError::Format)?) };
let mut total = 0usize;
let mut filtered = 0usize;
let mut skipped = 0usize;
Expand Down Expand Up @@ -277,7 +281,13 @@ fn write_chunks_as(
// leave out only features without geometry.
if crs == Crs::WebMercator {
for g in chunk.iter().filter_map(|f| f.geometry.as_ref()) {
g.for_each_coord(|c| beyond_web_mercator += usize::from(c.x.is_finite() && c.y.abs() > rustgis_geom::MAX_LAT));
g.for_each_coord(|c| {
let c = match &to_lonlat {
Some(t) => t.point(c).unwrap_or(rustgis_geom::Coord::new(f64::NAN, f64::NAN)),
None => c,
};
beyond_web_mercator += usize::from(c.x.is_finite() && c.y.abs() > rustgis_geom::MAX_LAT)
});
}
}
if let Some(t) = &t {
Expand Down
36 changes: 36 additions & 0 deletions crates/data/src/export/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ struct Runs {
chunks: bool,
/// Rows it reports as unreadable, as a GeoPackage's bad rows are.
unreadable: usize,
/// The system it gives its features in.
held: Crs,
}

impl Runs {
Expand All @@ -77,6 +79,7 @@ impl Runs {
passes: Default::default(),
chunks: true,
unreadable: 0,
held: Crs::LonLat,
}
}
}
Expand All @@ -85,6 +88,9 @@ impl FeatureSource for Runs {
fn info(&self) -> &SourceInfo {
&self.info
}
fn coord_crs(&self) -> Crs {
self.held
}
fn read(&self, _: &Request) -> Result<Batch> {
Ok(Batch {
features: self.features.clone(),
Expand Down Expand Up @@ -655,3 +661,33 @@ fn a_mixed_layer_added_to_a_geopackage_keeps_every_kind() {
assert_eq!(rows, 300);
}
}

/// A source that gives its features in its own system (UTM 32N here; every source gives
/// longitude/latitude until #2032 C2) is exported a chunk at a time from it: a GeoJSON in
/// longitude/latitude, a GeoPackage in its own system and one in Web Mercator, which counts places
/// past where Web Mercator ends by their latitude (a square's 5 vertices at 86° N), not by the
/// source's northings.
#[test]
fn a_streamed_export_is_written_from_the_system_its_source_gives() {
let d = folder("held");
let mut lonlat = squares();
let ring = vec![Coord::new(9.0, 86.0), Coord::new(9.5, 86.0), Coord::new(9.5, 86.5), Coord::new(9.0, 86.5), Coord::new(9.0, 86.0)];
lonlat.push_next(Some(Geometry::Polygon(vec![vec![ring]])), vec![Value::Null, Value::Int(-2), Value::Null, Value::Null]);
let utm = Crs::Epsg(32632);
let ds = crate::io::project(&lonlat, utm).unwrap();
let layer = Dataset::new(ds.name.clone(), ds.geometry_type, ds.fields.clone());
let src = Runs { held: utm, ..Runs::new(&ds, 10) };
let first = |ds: &Dataset| match &ds.features[0].geometry {
Some(Geometry::Polygon(p)) => p[0][0][0],
g => panic!("{g:?}"),
};
let want = first(&lonlat);
for (name, crs, beyond) in [("out.geojson", Crs::LonLat, 0), ("own.gpkg", utm, 0), ("merc.gpkg", Crs::WebMercator, 5)] {
let e = write_source_in(&src, &layer, &d.join(name), crs).unwrap();
assert_eq!(e.written, 302, "{name}");
// Northings in the millions: only the square at 86° N is past 85.05°.
assert_eq!(e.beyond_web_mercator, beyond, "{name}");
let p = first(&read_back(&d.join(name)));
assert!((p.x - want.x).abs() < 1e-7 && (p.y - want.y).abs() < 1e-7, "{name}: {p:?} {want:?}");
}
}
107 changes: 94 additions & 13 deletions crates/data/src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -617,14 +617,17 @@ pub fn default_export_note(ds: &Dataset, path: &str) -> Option<String> {
})
}

/// The dataset (in longitude/latitude, as every dataset is) in `crs`'s coordinates. Fails on a
/// coordinate the system can't hold, naming its feature.
/// The dataset in `crs`'s coordinates, from the system it holds them in ([`Dataset::coord_crs`]:
/// longitude/latitude, as every dataset's are today), by the direct operation between the two
/// ([`Crs::to`]). A copy as it is when it holds them in `crs`. Fails on a coordinate the system
/// can't hold, naming its feature.
pub fn project(ds: &Dataset, crs: Crs) -> Result<Dataset> {

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.

Latent: the copy project returns still reports longitude/latitude. project returns a dataset whose coordinates are in crs, but Dataset::coord_crs() is hard-coded to LonLat in production, so the copy answers coord_crs() wrongly. Every helper keyed on coord_crs() (in_lonlat, lonlat_conversion, in_file, shapefile_geometry_notes, the extent helpers) would convert it a second time if it were passed one. I checked the write paths in this PR: projected_bytes and the format writers don't call those helpers on the projected copy, so nothing is broken today.

The test hook hides the problem. HeldIn makes every dataset on the thread report the held system, including the output of project, so the new tests can't tell a correctly labelled copy from a mislabelled one.

Suggested fix: say in the doc that the output's system is not recorded until C2 and must not be fed back into coordinate-dependent helpers, and add a test that asserts that. Confidence: medium that this is a trap for C2; low that it causes a bug in this PR.

if crs == Crs::LonLat {
let from = ds.coord_crs();
if crs == from {
return Ok(ds.clone());
}
let mut out = ds.clone();
let to = Crs::LonLat.to(crs).map_err(DataError::Format)?;
let to = from.to(crs).map_err(DataError::Format)?;
project_features(&mut out.features, &to)?;
Ok(out)
}
Expand Down Expand Up @@ -708,9 +711,12 @@ pub fn write_bytes_in(ds: &Dataset, ext: &str, crs: Crs) -> Result<(Vec<u8>, usi
return Err(DataError::Unsupported(format!(".{ext} in {} (it holds longitude/latitude only)", crs.label())));
}
check_projected(&ext, crs)?;
return projected_bytes(&project(ds, crs)?, &ext, crs);
}
projected_bytes(ds, &ext, crs)
// From the system the dataset holds its coordinates in: as they are when that is `crs`.
if crs == ds.coord_crs() {
return projected_bytes(ds, &ext, crs);
}
projected_bytes(&project(ds, crs)?, &ext, crs)
}

/// [`write_bytes_in`] for a dataset already in `crs`'s coordinates.
Expand Down Expand Up @@ -790,11 +796,15 @@ pub fn write_path_in(ds: &Dataset, path: &Path, crs: Crs) -> Result<usize> {
/// also returns the table written.
pub fn write_path_to(ds: &Dataset, path: &Path, crs: Crs, gpkg: &GpkgTable) -> Result<(usize, Option<GpkgWritten>)> {
let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase();
if crs != Crs::LonLat && PROJECTED_FORMATS.contains(&ext.as_str()) {
check_projected(&ext, crs)?;
}
let projected;
let ds = if crs == Crs::LonLat || !PROJECTED_FORMATS.contains(&ext.as_str()) {
// From the system the dataset holds its coordinates in ([`project`]): as they are when that
// is `crs`, and when `crs` is one the format can't hold, which is refused below.
let ds = if crs == ds.coord_crs() || (crs != Crs::LonLat && !PROJECTED_FORMATS.contains(&ext.as_str())) {
ds
} else {
check_projected(&ext, crs)?;
projected = project(ds, crs)?;
&projected
};
Expand Down Expand Up @@ -4310,6 +4320,8 @@ impl std::ops::AddAssign for CsvLosses {
pub fn export_losses_notes(ds: &Dataset, ext: &str, name_field: Option<usize>, target: &str) -> Result<Vec<String>> {
Ok(match ext {
"csv" => {
// Of the longitude/latitude the file is written in.
let ds = ds.in_lonlat().map_err(DataError::Format)?;

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.

Memory: this clones the whole layer once it is held in another system. in_lonlat() borrows the layer while it is held in longitude/latitude, which is every layer today, so there is no cost yet. Once C2 lands, every CSV notes call on a projected layer will allocate a full longitude/latitude copy of it.

AGENTS.md ("Size for real data") asks that a change which stores or copies layer data give its size as a multiple of the layer, as cargo xtask memory measures. The PR body says "one more copy" but gives no measured multiple.

Suggested fix: either state the multiple in the PR body, or compute the CSV losses per feature or per chunk with a borrowed conversion so that no second layer is held. Confidence: medium that it matters once C2 lands; no current impact.

let losses = CsvLosses::of(&ds.features, ds.geometry_type, &ds.fields)?;
let mut notes = losses.notes(&ds.fields, target);
notes.extend(losses.coordinates_note(&ds.fields, target));
Expand Down Expand Up @@ -4486,13 +4498,16 @@ fn shapefile_geometry_losses(g: Option<&Geometry>, gt: GeometryType, drawable: f
/// What an export to a Shapefile in `crs` says it leaves out of the geometry it writes, one
/// notice per kind with a count, or none: vertices with a missing (NaN) or infinite coordinate,
/// and the line parts or polygon rings without enough vertices to draw. Features left out whole
/// are [`left_out_note`]'s. In another system than longitude/latitude, the export writes the
/// projected copy and refuses a coordinate that doesn't project to a finite one ([`project`]), so
/// every vertex it writes is drawable (an infinite latitude in Web Mercator is written at
/// 85.05°), and only parts too short to draw are left out. `target` names what was written; line
/// are [`left_out_note`]'s. In another system than the one the layer holds its coordinates in
/// ([`Dataset::coord_crs`], longitude/latitude today), the export writes the projected copy and
/// refuses a coordinate that doesn't project to a finite one ([`project`]), so every vertex it
/// writes is drawable (an infinite latitude in Web Mercator is written at 85.05°), and only parts
/// too short to draw are left out. `target` names what was written; line
/// breaks and other control characters in it show as spaces.
pub fn shapefile_geometry_notes(ds: &Dataset, target: &str, crs: Crs) -> Vec<String> {
let drawable: fn(&Coord) -> bool = if crs == Crs::LonLat { |c| c.x.is_finite() && c.y.is_finite() } else { |_| true };
// Written as held when `crs` is the system the layer holds its coordinates in; otherwise a
// converted copy, which refused every vertex that isn't a place.
let drawable: fn(&Coord) -> bool = if crs == ds.coord_crs() { |c| c.x.is_finite() && c.y.is_finite() } else { |_| true };
let (mut vertices, mut parts) = (0usize, 0usize);
for f in &ds.features {
let Some((v, p)) = shapefile_geometry_losses(f.geometry.as_ref(), ds.geometry_type, drawable) else { continue };
Expand Down Expand Up @@ -7868,4 +7883,70 @@ mod tests {
assert_eq!(read_back.fields[1].ty, FieldType::Integer);
assert_eq!(read_back.features[0].attrs[1], Value::Int(1));
}

/// A layer held in its own system (UTM 32N here; every layer's is longitude/latitude until
/// #2032 C2) is written from it: in longitude/latitude for a format that holds only those, in
/// another system by the direct operation between the two, and in its own as it is.
#[test]
fn a_layer_is_written_from_the_system_it_holds() {
let (utm, etrs) = (Crs::Epsg(32632), Crs::Epsg(25832));
let lonlat = Coord::new(9.0, 48.7);
let at = utm.transformer().unwrap().from_lonlat(lonlat).unwrap();
let mut ds = Dataset::new("held", GeometryType::Point, vec![]);
ds.push(Some(Geometry::Point(at)), vec![]);
let _held = crate::tests::HeldIn::new(utm);
assert_eq!(ds.coord_crs(), utm);
// GeoJSON: longitude/latitude.
let (bytes, _) = write_bytes_in(&ds, "geojson", Crs::LonLat).unwrap();
let read = read_bytes("held.geojson", &bytes).unwrap().0;
let Some(Geometry::Point(p)) = read.features[0].geometry.clone() else { panic!("a point") };
assert!((p.x - lonlat.x).abs() < 1e-9 && (p.y - lonlat.y).abs() < 1e-9, "{p:?}");
// Its own system: the coordinates as they are.
let same = project(&ds, utm).unwrap();
assert_eq!(same.features[0].geometry, ds.features[0].geometry);
// Another: by the direct operation from it.
let other = project(&ds, etrs).unwrap();
let want = utm.to(etrs).unwrap().point(at).unwrap();
assert_eq!(other.features[0].geometry, Some(Geometry::Point(want)));
// A file written whole, in the layer's own system, and in longitude/latitude.
let d = std::env::temp_dir().join(format!("rustgis-held-writes-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
write_path_in(&ds, &d.join("own.fgb"), utm).unwrap();
write_path_in(&ds, &d.join("lonlat.csv"), Crs::LonLat).unwrap();
for name in ["own.fgb", "lonlat.csv"] {
let read = read_path(&d.join(name)).unwrap().0;
let Some(Geometry::Point(p)) = read.features[0].geometry.clone() else { panic!("{name}: a point") };
assert!((p.x - lonlat.x).abs() < 1e-9 && (p.y - lonlat.y).abs() < 1e-9, "{name}: {p:?}");
}
let _ = std::fs::remove_dir_all(&d);
}

/// The notes of an export of a layer held in its own system (UTM 32N here) are those of what
/// is written: a CSV's of the longitude/latitude it writes (as for the same layer held in
/// them), and a Shapefile's vertices left out only when it is written as held.
#[test]
fn an_exports_notes_are_of_what_it_writes() {
let utm = Crs::Epsg(32632);
// With x and y fields, which a CSV reader could take for the position: a point the file
// can't give a longitude/latitude would be said.
let fields = vec![Field::new("x", FieldType::Double), Field::new("y", FieldType::Double)];
let mut lonlat = Dataset::new("held", GeometryType::Point, fields);
for (lon, lat) in [(9.0, 48.7), (10.0, 50.0)] {
lonlat.push(Some(Geometry::Point(Coord::new(lon, lat))), vec![Value::Float(1.0), Value::Float(2.0)]);
}
let want = export_losses_notes(&lonlat, "csv", None, "out.csv").unwrap();
let held = project(&lonlat, utm).unwrap();
let _held = crate::tests::HeldIn::new(utm);
assert_eq!(export_losses_notes(&held, "csv", None, "out.csv").unwrap(), want);
// A line with a missing coordinate: its vertex is left out of a Shapefile written as
// held, and noted; in any other system the export's conversion refuses the line instead
// (`project`), so there is nothing to note.
let mut line = Dataset::new("line", GeometryType::Polyline, vec![]);
let parts = vec![vec![Coord::new(500_000.0, 5_400_000.0), Coord::new(f64::NAN, 5_400_100.0), Coord::new(500_100.0, 5_400_200.0)]];
line.push(Some(Geometry::Line(parts)), vec![]);
let own = shapefile_geometry_notes(&line, "out.shp", utm);
assert!(own.iter().any(|n| n.contains("1 vertex with a missing or infinite coordinate")), "{own:?}");
assert!(shapefile_geometry_notes(&line, "out.shp", Crs::Epsg(25832)).is_empty());
}
}
62 changes: 61 additions & 1 deletion crates/data/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -439,6 +439,10 @@ impl Dataset {
/// a layer whose conversion fails (`Layer::projected_in`) and doesn't say so yet: before this
/// returns another system, that needs a notice, as AGENTS.md's "Never silent" asks.
pub fn coord_crs(&self) -> raster::Crs {
#[cfg(test)]
if let Some(held) = tests::held_in() {
return held;
}
raster::Crs::LonLat
}

Expand Down Expand Up @@ -748,7 +752,19 @@ fn web_mercator_note(layers: &[(&Dataset, rustgis_geom::Extent)], target: &str)
.filter_map(|(ds, e)| {
let mut moved = 0usize;
if !ds.windowed {
let mut count = |c: Coord| moved += usize::from(c.x.is_finite() && c.y.abs() > MAX_LAT);
// By latitude, from the system the layer holds its coordinates in: none counted
// when that can't be converted (its export can't be written either).
let to = match ds.lonlat_conversion() {
Ok(t) => (!t.is_identity()).then_some(t),
Err(_) => return None,
};
let mut count = |c: Coord| {
let c = match &to {
Some(t) => t.point(c).unwrap_or(Coord::new(f64::NAN, f64::NAN)),
None => c,
};
moved += usize::from(c.x.is_finite() && c.y.abs() > MAX_LAT)
};
for g in ds.features.iter().filter_map(|f| f.geometry.as_ref()) {
if shapefile {
crate::io::shapefile_vertices(g, ds.geometry_type, &mut count);
Expand Down Expand Up @@ -1133,6 +1149,50 @@ fn convert_keeping_missing(to: &raster::Reprojection, g: &Geometry, held: &HeldP
mod tests {
use super::*;

thread_local! {
/// The system this thread's tests hold every dataset's coordinates in ([`HeldIn`]).
static HELD_IN: std::cell::Cell<Option<raster::Crs>> = const { std::cell::Cell::new(None) };
}

/// What [`Dataset::coord_crs`] says on this thread while a [`HeldIn`] is alive: what a dataset
/// that keeps the coordinates it was read in (#2032 C2) will say, for the paths that convert
/// from it to be tried before it does.
pub(crate) fn held_in() -> Option<raster::Crs> {
HELD_IN.try_with(std::cell::Cell::get).ok().flatten()
}

/// Every dataset on this thread is taken to hold its coordinates in a system until dropped,
/// on the thread that made it (it can't be sent to another).
pub(crate) struct HeldIn(Option<raster::Crs>, std::marker::PhantomData<*const ()>);

impl HeldIn {
pub(crate) fn new(crs: raster::Crs) -> HeldIn {
HeldIn(HELD_IN.with(|h| h.replace(Some(crs))), std::marker::PhantomData)
}
}

impl Drop for HeldIn {
fn drop(&mut self) {
let _ = HELD_IN.try_with(|h| h.set(self.0));
}
}

/// An export in Web Mercator counts the places past where it ends by their latitude, from the
/// system the layer holds its coordinates in (UTM 32N here): one at 86° N, not every northing.
#[test]
fn web_mercators_end_is_counted_by_latitude() {
let utm = raster::Crs::Epsg(32632);
let t = utm.transformer().unwrap();
let mut ds = Dataset::new("held", GeometryType::Point, vec![]);
for lat in [48.7, 86.0] {
ds.push(Some(Geometry::Point(t.from_lonlat(Coord::new(9.0, lat)).unwrap())), vec![]);
}
let _held = HeldIn::new(utm);
let note = web_mercator_note(&[(&ds, ds.extent())], "out.gpkg").unwrap_or_default();
assert_eq!(note, web_mercator_said(&[("held", Some(1))], "out.gpkg").unwrap_or_default());
assert!(!note.is_empty());
}

/// Analysis and measurement read a longitude/latitude dataset as it is: no copy, and the
/// measure and the area check of the geometry itself.
#[test]
Expand Down
Loading
Loading