diff --git a/crates/data/src/loss.rs b/crates/data/src/loss.rs index 62a4a050f4..f35f46d754 100644 --- a/crates/data/src/loss.rs +++ b/crates/data/src/loss.rs @@ -107,6 +107,12 @@ loss_codes! { "A coordinate system's name or definition could not be written with the data, so the file holds the coordinates without it.", "Keep the source file's coordinate system definition with the export, or export in WGS 84, which every format can name." ), + DroppedEpoch => ( + "dropped.epoch", + Dropped, + "The date the coordinates are valid at (the coordinate epoch) was not kept, so positions are read as if the coordinate system did not change over time.", + "Keep the source file where the epoch matters, or convert the coordinates to a system that does not move with the ground before adding them." + ), DroppedFeature => ( "dropped.feature", Dropped, @@ -176,7 +182,7 @@ loss_codes! { ApproximatedCurve => ( "approximated.curve", Approximated, - "Curves, circles or rotated boxes were drawn or written as straight segments.", + "Curves, circles, rotated boxes or edges that follow the Earth's curve were read, drawn or written as straight segments.", "Keep the source file where exact curves matter: RustGIS draws curves as straight segments." ), AssumedNullMarker => ( diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index 3e338ca9d3..4d5c455842 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -818,6 +818,10 @@ pub type Queried = (Vec, Batch); fn query_now(file: &std::sync::Arc, columns: &[String], req: &Request) -> Result { let cols: Vec<&str> = columns.iter().map(String::as_str).collect(); let src = parquet::ParquetSource::open_remote(file.clone(), &url_name(file.url()))?.with_columns(&cols).exact(); + // A caller takes the rows' places for longitude/latitude, and has no notices. + if let Some(why) = src.refusal() { + return Err(DataError::Format(format!("GeoParquet: {why}"))); + } let batch = src.read(req)?; Ok((src.info().fields.clone(), batch)) } diff --git a/crates/data/src/source/parquet.rs b/crates/data/src/source/parquet.rs index 6631e6945f..a2ad50e138 100644 --- a/crates/data/src/source/parquet.rs +++ b/crates/data/src/source/parquet.rs @@ -11,6 +11,8 @@ //! chunks of the rows the read takes, each set fetched in one round. Files without a covering are //! downloaded whole instead. +mod declared; + use super::remote::{self, Remote}; use super::{Batch, FeatureSource, Reproject, Request, Sampler, SourceInfo, clamp_limit}; use crate::raster::Crs; @@ -38,6 +40,12 @@ const MAX_GROUP_ROWS: usize = if cfg!(target_arch = "wasm32") { 1 << 21 } else { /// Conservative decoded-column budget for one group scanned without native view bounds. const MAX_SCAN_BYTES: u64 = if cfg!(target_arch = "wasm32") { 64 << 20 } else { 256 << 20 }; +/// The largest geometry, encoded, decoded to look at a file's coordinates as it opens. +const PEEK_BYTES: usize = 1 << 20; + +/// The notice of a file whose first geometries couldn't be looked at for Z or M values. +const UNTOLD_ZM: &str = "couldn't tell whether it has Z or M values, which RustGIS doesn't keep"; + /// The least [`max_decoded_bytes`] allows, and its limit in the browser. const DECODED_FLOOR: usize = if cfg!(target_arch = "wasm32") { 128 << 20 } else { 512 << 20 }; /// The most [`max_decoded_bytes`] allows, however much the computer has. @@ -119,6 +127,9 @@ pub struct ParquetSource { reproject: Reproject, /// The file, when it is read by its web address. remote: Option>, + /// What opening it said of its geometry column: the first of `info.notes`, of which there are + /// this many. + declared_notes: usize, /// Every row group meeting a read's extent is read (a catalog's index), never a sample of them. exact: bool, /// The most rows read from one row group: `MAX_GROUP_ROWS`, lowered by tests. @@ -211,6 +222,24 @@ impl ParquetSource { self } + /// Why its rows can't be read by place as longitude/latitude without a word, for a reader that + /// gives no notices: something its geometry column declares isn't kept or is only assumed, or + /// its system is another one. + pub(super) fn refusal(&self) -> Option { + use crate::loss::LossCode::{ApproximatedCurve, AssumedCrs, DroppedZm}; + let lost = self.info.notes.iter().filter(|n| matches!(n.loss, Some(AssumedCrs | DroppedZm)) || **n == UNTOLD_ZM); + // Curved edges are looked at in the rows an exact read takes. + let declared = self.info.notes.iter().take(self.declared_notes).filter(|n| n.loss != Some(ApproximatedCurve)); + if let Some(note) = declared.chain(lost).next() { + return Some(note.as_str().to_string()); + } + if self.info.extent.beyond_lonlat() { + return Some("its coordinates are not longitude/latitude".to_string()); + } + let other = self.reproject.t.is_some(); + other.then(|| format!("its coordinates are in {}, not WGS 84 longitude/latitude", self.reproject.label())) + } + /// Reads take every row group an extent meets (a catalog's index, whose matches are all /// wanted), not a sample spread over the file; an extent needing more than one read may fetch /// is an error. @@ -241,61 +270,22 @@ fn remote_reader(file: &Arc) -> Result> { } impl ParquetSource { - /// Opens a GeoParquet from its `geo` metadata: geometry column, types, bbox and coordinate - /// system, noting Z or M values (which reading drops). + /// Opens a GeoParquet from its geometry column's native type and its `geo` metadata (column, + /// types, bbox and coordinate system), noting Z or M values (which reading drops). fn new(reader: Arc, name: &str, remote: Option>) -> Result { let md = reader.metadata(); validate_chunks(md)?; let schema = md.file_metadata().schema_descr(); - let kv = md.file_metadata().key_value_metadata(); - let geo: Option = kv - .and_then(|kv| kv.iter().find(|k| k.key == "geo")) - .and_then(|k| k.value.as_deref()) - .and_then(|v| serde_json::from_str(v).ok()); + let column = declared::Column::find(md)?; + let (primary, geom_col) = (column.name.clone(), column.leaf); // Top-level leaf columns by name (nested ones are left out of the fields). let top = |i: usize| -> Option { let c = schema.column(i); (c.path().parts().len() == 1 && c.max_rep_level() == 0).then(|| c.name().to_string()) }; - let leaf_named = |n: &str| (0..schema.num_columns()).find(|&i| top(i).as_deref() == Some(n)); - // The geometry column: the metadata's primary column, else a binary column with a usual name. - let primary = geo.as_ref().and_then(|g| g.get("primary_column")).and_then(|v| v.as_str()).map(str::to_string).or_else(|| { - ["geometry", "geom", "wkb_geometry", "the_geom", "wkb"] - .into_iter() - .find(|n| leaf_named(n).is_some_and(|i| schema.column(i).physical_type() == Physical::BYTE_ARRAY)) - .map(str::to_string) - }); - let Some(primary) = primary else { - return Err(DataError::Format("not a GeoParquet file: no geometry column".into())); - }; - let col_meta = geo.as_ref().and_then(|g| g.get("columns")).and_then(|c| c.get(&primary)); - let encoding = col_meta.and_then(|c| c.get("encoding")).and_then(|v| v.as_str()).unwrap_or("WKB"); - if !encoding.eq_ignore_ascii_case("wkb") { - return Err(DataError::Unsupported(format!("GeoParquet geometry encoding '{encoding}' (only WKB is read)"))); - } - let geom_col = leaf_named(&primary).ok_or_else(|| DataError::Format(format!("no column '{primary}'")))?; - if schema.column(geom_col).physical_type() != Physical::BYTE_ARRAY { - return Err(DataError::Format(format!("geometry column '{primary}' is not binary"))); - } - let mut notes = crate::loss::Notes::new(); - let crs = col_meta.and_then(|c| c.get("crs")); - let code = crs_code(crs); - // Another body's system is said, or refused when its coordinates aren't longitude/latitude. - let other_body = crs.filter(|_| code.is_none()).and_then(crate::raster::planetary::projjson); - if let Some(crate::raster::planetary::Declared::Refused(e)) = &other_body { - return Err(DataError::Format(format!("its coordinate system: {e}"))); - } - if let Some(crate::raster::planetary::Declared::LonLat { note, .. }) = &other_body { - notes.push(format!("its coordinate system: {note}")); - } else if code.is_none() && crs.is_some_and(|c| !c.is_null() && !is_crs84(c)) { - // A coordinate system given without an EPSG code (and not OGC:CRS84) can't be converted. - notes.push(crate::loss::Note::loss( - crate::loss::LossCode::AssumedCrs, - "its coordinate system has no EPSG code; read as longitude/latitude", - )); - } - let reproject = Reproject::from_epsg(code, &mut notes); - let covering = find_covering(md, col_meta, &primary); + let reproject = column.reproject.clone(); + let col_meta = column.meta(); + let covering = find_covering(md, col_meta, &primary, column.plain_bbox); let declared_covering = col_meta.and_then(|c| c.get("covering")).and_then(|c| c.get("bbox")).is_some(); let mut fields = Vec::new(); @@ -322,7 +312,7 @@ impl ParquetSource { parts => parts.first().cloned(), }) .collect(); - let geometries = geo.as_ref().and_then(|g| g.get("columns")).and_then(|c| c.as_object()); + let geometries = column.columns().and_then(|c| c.as_object()); let left_out: Vec<(String, String)> = schema .root_schema() .get_fields() @@ -361,7 +351,9 @@ impl ParquetSource { .collect(); let has_zm = |v: &&str| v.ends_with(" Z") || v.ends_with(" M") || v.ends_with(" ZM"); let all_zm = !types.is_empty() && types.iter().all(has_zm); - let zm = types.iter().any(has_zm) || col_meta.and_then(|c| c.get("bbox")).and_then(|b| b.as_array()).is_some_and(|b| b.len() == 6); + let zm = types.iter().any(has_zm) + || column.native_zm(md) + || col_meta.and_then(|c| c.get("bbox")).and_then(|b| b.as_array()).is_some_and(|b| b.len() == 6); let count = u64::try_from(md.file_metadata().num_rows()).ok(); let mut info = SourceInfo { name: name.to_string(), @@ -372,7 +364,7 @@ impl ParquetSource { count, crs: reproject.label(), indexed: covering.is_some(), - notes, + notes: column.notes.clone(), zm_dropped: false, }; info.note_columns( @@ -394,6 +386,7 @@ impl ParquetSource { declared_covering, reproject, remote, + declared_notes: column.notes.iter().count(), exact: false, group_rows: MAX_GROUP_ROWS, scan_bytes: MAX_SCAN_BYTES, @@ -405,21 +398,56 @@ impl ParquetSource { match src.peek_zm() { Some(true) => src.info.drop_zm(None), Some(false) => {} - None => src.info.notes.push("couldn't tell whether it has Z or M values, which RustGIS doesn't keep"), + None => src.info.notes.push(UNTOLD_ZM), } } if src.info.geometry_type == GeometryType::None { src.info.geometry_type = super::peek_kind(&src); } + let assumed = |n: &crate::loss::Note| n.loss == Some(crate::loss::LossCode::AssumedCrs); + let in_assumed = column.notes.iter().any(assumed); + if src.reproject.t.is_none() { + // Nothing of a file read by its address is fetched only to word a notice. + let known = Some(src.info.extent).filter(|e| !e.is_empty() || src.remote.is_some()).or_else(|| src.peek_extent()); + let known = known.unwrap_or(Extent::EMPTY); + if column.unknown_crs { + src.info.notes.push(declared::unknown_note(&known)); + } else if known.beyond_lonlat() && !in_assumed { + src.info.notes.push(column.beyond_note()); + } else if known.beyond_lonlat() { + let notes = std::mem::take(&mut src.info.notes); + for note in notes.iter().cloned() { + let out_of_place = + |text| format!("{text}, though its coordinates aren't: load the layer and give its system with Define Projection"); + src.info.notes.push(if assumed(¬e) { note.map_text(out_of_place) } else { note }); + } + } + } Ok(src) } /// Whether any of the first 16 geometries has Z or M values; `None` when they can't be read - /// here (a remote file's first row group not fetched yet). + /// here. fn peek_zm(&self) -> Option { + Some(self.peek()?.iter().any(|b| wkb::has_zm(b))) + } + + /// The box of the first 16 geometries' coordinates, as the file holds them, without those too + /// large to decode for it; `None` when they can't be read here. + fn peek_extent(&self) -> Option { + let mut extent = Extent::EMPTY; + for g in self.peek()?.iter().filter(|b| b.len() <= PEEK_BYTES).filter_map(|b| wkb::decode(b)) { + extent = extent.union(&g.extent()); + } + Some(extent) + } + + /// The first 16 geometries, encoded; `None` when they can't be read here (a remote file's first + /// row group not fetched yet). + fn peek(&self) -> Option>> { let md = self.reader.metadata(); if md.num_row_groups() == 0 { - return Some(false); + return Some(Vec::new()); } if let Some(file) = &self.remote && !want_chunks(file, md, &[0], &[self.geom_col]).ok()? @@ -429,7 +457,7 @@ impl ParquetSource { let rows = usize::try_from(md.row_group(0).num_rows()).unwrap_or(0).min(16); let rg = self.reader.get_row_group(0).ok()?; let geoms = read_bytes(rg.as_ref(), self.geom_col, &vec![true; rows], &Budget::new(self.decoded_limit(), 0)).ok()?; - Some(geoms.iter().filter_map(|b| b.as_deref()).any(wkb::has_zm)) + Some(geoms.into_iter().flatten().collect()) } } @@ -541,6 +569,17 @@ impl ParquetSource { return Err(DataError::Format(format!("GeoParquet: row group {g} has covering columns shorter than its rows"))); } let v = |k: usize, r: usize| cols.get(k).and_then(|c| c.get(r).copied().flatten()); + // A catalog's reader has no notice that boxes read as longitude/latitude aren't (the + // statistics, where there are some, say it as the file opens). + if self.exact && self.reproject.t.is_none() { + let beyond = |r: usize| match [v(0, r), v(1, r), v(2, r), v(3, r)] { + [Some(x0), Some(y0), Some(x1), Some(y1)] => Extent::new(x0, y0, x1, y1).beyond_lonlat(), + _ => false, + }; + if (0..n).any(beyond) { + return Err(DataError::Format(format!("GeoParquet: row group {g} has coordinates that are not longitude/latitude"))); + } + } Ok((0..n) .map(|r| { let [Some(min_x), Some(min_y), Some(max_x), Some(max_y)] = [v(0, r), v(1, r), v(2, r), v(3, r)] else { @@ -625,6 +664,15 @@ impl FeatureSource for ParquetSource { _ => true, }) .collect(); + // A catalog's reader takes the rows for all of them, so a group is read whole or refused. + if self.exact { + for &g in &groups { + let rows = whole_group(g, md.row_group(g).num_rows(), self.group_rows)?; + if rows_in(g) != rows { + return Err(DataError::Format(format!("GeoParquet: row group {g} has columns shorter than its rows"))); + } + } + } // Read by address: no more row groups than a read may fetch (an evenly spread part of them, // a sample), and the covering's chunks of those asked for together. // A row group wholly inside the extent with no null boxes: every row matches, @@ -770,6 +818,26 @@ impl FeatureSource for ParquetSource { let rg = self.reader.get_row_group(g).map_err(err)?; let budget = Budget::new(*decoded, g); let geoms = read_bytes(rg.as_ref(), self.geom_col, take, &budget)?; + // A catalog's reader gives no notices, so a value dropped from a row is refused. + if self.exact && geoms.iter().flatten().any(|b| wkb::has_zm(b)) { + return Err(DataError::Format(format!("GeoParquet: row group {g} has Z or M values, which RustGIS doesn't keep"))); + } + if self.exact { + let curved = self.info.notes.iter().find(|n| n.loss == Some(crate::loss::LossCode::ApproximatedCurve)); + for geometry in geoms.iter().flatten().filter_map(|b| wkb::decode(b)) { + if self.reproject.t.is_none() && geometry.extent().beyond_lonlat() { + return Err(DataError::Format(format!( + "GeoParquet: row group {g} has coordinates that are not longitude/latitude" + ))); + } + // Before the extent is tested, which a straight edge may miss and a curved one meet. + if let Some(note) = curved + && !matches!(geometry, crate::Geometry::Point(_) | crate::Geometry::MultiPoint(_)) + { + return Err(DataError::Format(format!("GeoParquet: {}", note.as_str()))); + } + } + } let base = starts.get(g).copied().unwrap_or(0); let wanted = take.iter().filter(|&&t| t).count(); if late { @@ -1610,8 +1678,11 @@ fn is_crs84(crs: &serde_json::Value) -> bool { let id = crs.get("id"); let authority = id.and_then(|i| i.get("authority")).and_then(|a| a.as_str()).unwrap_or(""); let code = id.and_then(|i| i.get("code")).map(|c| c.to_string().trim_matches('"').to_string()).unwrap_or_default(); + // A name alone says it only of a system that can be longitude/latitude. + let kind = crs.get("type").and_then(|t| t.as_str()); (authority.eq_ignore_ascii_case("OGC") && code.eq_ignore_ascii_case("CRS84")) - || crs.get("name").and_then(|n| n.as_str()).is_some_and(|n| n.contains("CRS84")) + || matches!(kind, None | Some("GeographicCRS" | "GeodeticCRS")) + && crs.get("name").and_then(|n| n.as_str()).is_some_and(|n| n.contains("CRS84")) } /// The EPSG code of a GeoParquet `crs` (PROJJSON); absent means OGC:CRS84 (longitude/latitude). @@ -1622,17 +1693,25 @@ fn crs_code(crs: Option<&serde_json::Value>) -> Option { } let id = crs.get("id")?; let authority = id.get("authority").and_then(|a| a.as_str()).unwrap_or(""); + // The longitude/latitude of NAD 83 and NAD 27. + if let (true, Some(code)) = (authority.eq_ignore_ascii_case("OGC"), id.get("code").and_then(|c| c.as_str())) { + return match code.to_ascii_uppercase().as_str() { + "CRS83" => Some(4269), + "CRS27" => Some(4267), + _ => None, + }; + } let code = id.get("code").and_then(|c| c.as_u64().or_else(|| c.as_str().and_then(|s| s.parse().ok())))?; match authority.to_ascii_uppercase().as_str() { - "EPSG" => u32::try_from(code).ok(), + "EPSG" => u32::try_from(code).ok().filter(|c| *c != 0), // OGC:CRS84 is longitude/latitude. _ => None, } } /// The bbox covering's leaf columns: the declared `covering.bbox`, else a `_bbox` or -/// `bbox` struct. -fn find_covering(md: &ParquetMetaData, col_meta: Option<&serde_json::Value>, primary: &str) -> Option<[usize; 4]> { +/// (when `plain`, so that it is this column's) `bbox` struct. +fn find_covering(md: &ParquetMetaData, col_meta: Option<&serde_json::Value>, primary: &str, plain: bool) -> Option<[usize; 4]> { let schema = md.file_metadata().schema_descr(); let leaf = |path: &[&str]| -> Option { let want = path.join("."); @@ -1645,7 +1724,8 @@ fn find_covering(md: &ParquetMetaData, col_meta: Option<&serde_json::Value>, pri .map(|k| b.get(*k).and_then(|p| p.as_array()).map(|p| p.iter().filter_map(|s| s.as_str().map(str::to_string)).collect())) .collect::>>>()?, None => { - let base = [format!("{primary}_bbox"), "bbox".to_string()].into_iter().find(|b| leaf(&[b.as_str(), "xmin"]).is_some())?; + let plain = plain.then(|| "bbox".to_string()); + let base = [format!("{primary}_bbox")].into_iter().chain(plain).find(|b| leaf(&[b.as_str(), "xmin"]).is_some())?; ["xmin", "ymin", "xmax", "ymax"].iter().map(|k| vec![base.clone(), (*k).to_string()]).collect() } }; @@ -2193,8 +2273,20 @@ const MAX_DIMS: usize = 8192; /// The most vector values one read keeps (in all; 4 bytes each). const MAX_VECTOR_VALUES: usize = if cfg!(target_arch = "wasm32") { 8 << 20 } else { 32 << 20 }; +/// The rows of row group `g`, refused when they are more than the `cap` read from one, for a read +/// that can't say it left some out. +fn whole_group(g: usize, rows: i64, cap: usize) -> Result { + usize::try_from(rows) + .ok() + .filter(|rows| *rows <= cap) + .ok_or_else(|| DataError::Format(format!("GeoParquet: row group {g} has {rows} rows, more than the {cap} read from one"))) +} + /// Reads the points of a GeoParquet in `extent` (longitude/latitude) with the vectors of a list -/// column (`column`, such as `embedding`), from a file by its web address. The geometry of every +/// column (`column`, such as `embedding`), from a file by its web address, in longitude/latitude. +/// A file whose geometry column's declaration gives a notice is refused, and so is one with Z or M +/// values, with points that have no place in longitude/latitude or with other geometries, which +/// would be lost without a word. The geometry of every /// row group is read (it has no bbox covering), then the vectors of those holding points in the /// extent: at most `max_groups` of them and `max_points` points, or an error saying how many the /// extent needs. Fails with [`remote::NEED`] until the bytes it needs are fetched (run it with @@ -2204,8 +2296,17 @@ pub fn read_vectors(file: &Arc, extent: &Extent, column: &str, max_group let md = reader.metadata(); let schema = md.file_metadata().schema_descr(); let leaf = |pred: &dyn Fn(&ColumnDescPtr) -> bool| (0..schema.num_columns()).find(|&i| pred(&schema.column(i))); - let geom = leaf(&|c| c.path().string() == "geometry" && c.physical_type() == Physical::BYTE_ARRAY) - .ok_or_else(|| DataError::Format("GeoParquet: no geometry column".into()))?; + let geometry = declared::Column::find(md)?; + // A caller gets points alone, so what can't be read without a word is refused. Edges are no + // matter to points. + let said = |n: &&crate::loss::Note| n.loss != Some(crate::loss::LossCode::ApproximatedCurve); + if let Some(note) = geometry.notes.iter().find(said).map(|n| n.as_str()) { + return Err(DataError::Format(format!("GeoParquet: {note}"))); + } + if geometry.unknown_crs { + return Err(DataError::Format("GeoParquet: the file says its coordinate system is unknown".into())); + } + let (geom, to_lonlat) = (geometry.leaf, geometry.reproject.t.as_ref()); let prefix = format!("{column}."); let vec_col = leaf(&|c| { c.path().string().starts_with(&prefix) && c.max_rep_level() == 1 && matches!(c.physical_type(), Physical::FLOAT | Physical::DOUBLE) @@ -2223,16 +2324,39 @@ pub fn read_vectors(file: &Arc, extent: &Extent, column: &str, max_group let mut found: Vec<(usize, Vec<(usize, (f64, f64))>)> = Vec::new(); let mut total = 0usize; let mut hit = 0usize; + let (mut zm, mut unplaced, mut others) = (0usize, 0usize, 0usize); for &g in &groups { let rg = reader.get_row_group(g).map_err(err)?; - let rows = usize::try_from(rg.metadata().num_rows()).unwrap_or(0).min(MAX_GROUP_ROWS); + let rows = whole_group(g, rg.metadata().num_rows(), MAX_GROUP_ROWS)?; let geoms = read_bytes(rg.as_ref(), geom, &vec![true; rows], &Budget::new(*decoded, g))?; + if geoms.len() != rows { + return Err(DataError::Format(format!("GeoParquet: row group {g} has columns shorter than its rows"))); + } let inside: Vec<(usize, (f64, f64))> = geoms .iter() .enumerate() .filter_map(|(r, b)| match b.as_deref().and_then(wkb::decode) { - Some(crate::Geometry::Point(c)) if extent.contains(c) => Some((r, (c.x, c.y))), - _ => None, + Some(crate::Geometry::Point(c)) => { + zm += usize::from(b.as_deref().is_some_and(wkb::has_zm)); + let Some(c) = to_lonlat + .map_or(Some(c), |t| t.to_lonlat(c)) + .filter(|c| c.is_finite() && !Extent::new(c.x, c.y, c.x, c.y).beyond_lonlat()) + else { + unplaced += 1; + return None; + }; + extent.contains(c).then_some((r, (c.x, c.y))) + } + // One that can't be read is as lost as one with no place. + None if b.is_some() => { + unplaced += 1; + None + } + Some(_) => { + others += 1; + None + } + None => None, }) .collect(); if !inside.is_empty() { @@ -2244,6 +2368,15 @@ pub fn read_vectors(file: &Arc, extent: &Extent, column: &str, max_group } } } + if unplaced > 0 { + return Err(DataError::Format(format!("GeoParquet: {unplaced} of its rows have no place in longitude/latitude that can be read"))); + } + if others > 0 { + return Err(DataError::Format(format!("GeoParquet: {others} of its geometries aren't single points, which aren't read here"))); + } + if zm > 0 { + return Err(DataError::Format(format!("GeoParquet: {zm} of its points have Z or M values, which RustGIS doesn't keep"))); + } if hit > max_groups || total > max_points { return Err(DataError::Format(format!("the area holds {total} points in {hit} row groups, more than are read at once: zoom in"))); } @@ -2847,6 +2980,14 @@ mod tests { .get_next_page() } + #[test] + fn a_group_past_the_cap_is_refused_not_cut() { + assert_eq!(whole_group(0, 40, 40).unwrap(), 40); + for rows in [41, i64::MAX, -1] { + assert!(whole_group(3, rows, 40).unwrap_err().to_string().contains("row group 3"), "{rows}"); + } + } + /// A page can't hold more than the column chunk it belongs to says it does, nor more than the /// read allows; a footer without a size leaves the read's limit. #[test] diff --git a/crates/data/src/source/parquet/declared.rs b/crates/data/src/source/parquet/declared.rs new file mode 100644 index 0000000000..adbb1371da --- /dev/null +++ b/crates/data/src/source/parquet/declared.rs @@ -0,0 +1,897 @@ +//! What a Parquet file declares about its geometry: the column holding it, its coordinate system, +//! its edges and its epoch. From the column's native type (`GEOMETRY` or `GEOGRAPHY`), which is the +//! source of truth when there is one, and from the `geo` metadata of GeoParquet +//! (, +//! ). + +use super::{DataError, ParquetMetaData, Physical, Reproject, Result, crs_code, is_crs84}; +use crate::loss::{LossCode, Note, Notes}; +use crate::raster::Crs; +use crate::raster::planetary::{self, Declared}; +use crate::raster::wkt::clip; +use parquet::basic::LogicalType; +use serde_json::{Value, json}; + +/// The names taken for a geometry column's when nothing says which column it is. +const USUAL_NAMES: [&str; 5] = ["geometry", "geom", "wkb_geometry", "the_geom", "wkb"]; + +/// The metadata's major versions read: before 1.0, 1.x and 2.x. +const MAJOR_VERSIONS: std::ops::RangeInclusive = 0..=2; + +/// The longest authority, or code, of a native type's `authority:code`. +const MAX_NAME: usize = 64; + +/// The longest PROJJSON, in bytes, read to compare two definitions by their parameters. +const MAX_DEFINITION: usize = 64 << 10; + +/// A column's native type. +struct Native { + /// Its `crs` as written; absent means OGC:CRS84. + crs: Option, + /// A `GEOGRAPHY`'s edges; `None` for a `GEOMETRY`, whose edges are straight. + edges: Option, +} + +/// The geometry column of a file and what the file declares about it. +pub(super) struct Column { + pub name: String, + /// Its leaf column index. + pub leaf: usize, + /// The `geo` metadata, when the file has some that can be read. + geo: Option, + native: Option, + /// The coordinate system, resolved. + pub reproject: Reproject, + /// What was assumed, dropped or left unused. The columns left out aren't among them. + pub notes: Notes, + /// A `bbox` struct that nothing declares is this column's: the metadata names the column, or + /// it has a usual name and no other is before it, or it is the only geometry column. + pub plain_bbox: bool, + /// The file says that its coordinate system is unknown ([`unknown_note`]). + pub unknown_crs: bool, +} + +impl Column { + /// Finds the geometry column and its coordinate system. The column is the `geo` metadata's + /// primary one, else one with a native type (one of the usual names first, else the first in + /// the file, saying which when there are several), else a binary one with a usual name. + pub(super) fn find(md: &ParquetMetaData) -> Result { + let schema = md.file_metadata().schema_descr(); + let mut notes = Notes::new(); + let geo_text = key(md, "geo"); + let geo = geo_text.and_then(|v| serde_json::from_str::(v).ok()).filter(Value::is_object); + if let Some(geo) = &geo { + check_version(geo)?; + } + // The top-level columns, which may hold the geometry, with their leaf index. + let columns: Vec<(usize, &str)> = (0..schema.num_columns()) + .filter_map(|i| { + let c = schema.columns().get(i)?; + (c.path().parts().len() == 1 && c.max_rep_level() == 0).then(|| (i, c.name())) + }) + .collect(); + let binary = |i: usize| schema.column(i).physical_type() == Physical::BYTE_ARRAY; + let (leaf, name, plain_bbox) = match geo.as_ref().and_then(|g| g.get("primary_column")).and_then(Value::as_str) { + Some(primary) => { + let (leaf, name) = columns + .iter() + .copied() + .find(|(_, c)| *c == primary) + .ok_or_else(|| DataError::Format(format!("no column '{primary}'")))?; + (leaf, name, true) + } + None => { + let natives: Vec<(usize, &str)> = + columns.iter().copied().filter(|&(i, _)| binary(i) && native(schema.column(i).logical_type_ref()).is_some()).collect(); + let named: Vec<(usize, &str)> = columns.iter().copied().filter(|&(i, _)| binary(i)).collect(); + let found = usual(&natives) + .or_else(|| natives.first().copied()) + .or_else(|| usual(&named)) + .ok_or_else(|| DataError::Format("not a GeoParquet file: no geometry column".into()))?; + if natives.len() > 1 { + notes.push(format!( + "it has {} geometry columns and nothing says which is the main one: '{}' is read", + natives.len(), + clip(found.1) + )); + } + let plain_bbox = usual(&named).map_or(natives.len() == 1, |usual| usual == found); + (found.0, found.1, plain_bbox) + } + }; + let native = native(schema.column(leaf).logical_type_ref()); + let name = name.to_string(); + let mut column = + Column { name, leaf, geo, native, reproject: Reproject { crs: Crs::LonLat, t: None }, notes, plain_bbox, unknown_crs: false }; + let encoding = column.meta().and_then(|c| c.get("encoding")).and_then(Value::as_str).unwrap_or("WKB"); + if !encoding.eq_ignore_ascii_case("wkb") { + return Err(DataError::Unsupported(format!("GeoParquet geometry encoding '{}' (only WKB is read)", clip(encoding)))); + } + if !binary(leaf) { + return Err(DataError::Format(format!("geometry column '{}' is not binary", column.name))); + } + let unread_geo = geo_text.is_some() && column.geo.is_none(); + let crs = column.crs(md); + column.reproject = match crs { + // Without the type, the system is only in the metadata that can't be read. + Said::Default if unread_geo && column.native.is_none() => { + column.notes.push(Note::loss( + LossCode::AssumedCrs, + "its 'geo' metadata can't be read, so its coordinate system isn't known; read as longitude/latitude", + )); + Reproject::from_crs(Crs::LonLat, &mut column.notes) + } + crs => column.resolve(crs)?, + }; + if unread_geo && column.native.is_some() { + column.notes.push("its 'geo' metadata can't be read, so only its geometry column's own type is used"); + } + // An empty file loses nothing. + if md.file_metadata().num_rows() != 0 { + column.note_epoch(); + column.note_edges(md); + } + Ok(column) + } + + /// Whether every row group's statistics list its geometries' types, all of them points. + fn native_points(&self, md: &ParquetMetaData) -> bool { + // 1 is a point and 4 a multipoint. + self.native_types(md).all(|t| t.is_some_and(|t| t.iter().all(|t| matches!(t % 1000, 1 | 4)))) + } + + /// Whether the statistics of any row group list a type with Z or M values. + pub(super) fn native_zm(&self, md: &ParquetMetaData) -> bool { + self.native_types(md).flatten().flatten().any(|t| matches!(t / 1000, 1..=3)) + } + + /// The ISO WKB codes (thousands for Z and M) of the types in each row group, by its statistics; + /// `None` for one whose statistics don't say. + fn native_types<'a>(&'a self, md: &'a ParquetMetaData) -> impl Iterator>> { + md.row_groups().iter().map(|g| { + let types = g.columns().get(self.leaf).and_then(|c| c.geo_statistics()).and_then(|s| s.geospatial_types()); + types.filter(|t| !t.is_empty()) + }) + } + + /// The notice for coordinates read as longitude/latitude that aren't, as a Shapefile's: the + /// file says they are, or it says nothing (no native type and no `geo` metadata). + pub(super) fn beyond_note(&self) -> Note { + let text = "coordinates are not longitude/latitude; RustGIS reads them as WGS 84 and they may draw out of place: load the layer and give its system with Define Projection"; + if self.native.is_some() || self.meta().is_some() { Note::plain(text) } else { Note::loss(LossCode::AssumedCrs, text) } + } + + /// The `geo` metadata's entry for this column. + pub(super) fn meta(&self) -> Option<&Value> { + self.columns().and_then(|c| c.get(&self.name)) + } + + /// The `geo` metadata's columns. + pub(super) fn columns(&self) -> Option<&Value> { + self.geo.as_ref()?.get("columns") + } + + /// The coordinate system declared: the native type's when it has one, else the `geo` + /// metadata's. A system the type only names, which the metadata gives in full, is read from the + /// metadata; a type naming one RustGIS can't resolve is too. Says when they disagree. + fn crs(&mut self, md: &ParquetMetaData) -> Said { + let geo = self.meta().map(|meta| match meta.get("crs") { + None => Said::Default, + Some(Value::Null) => Said::Unknown, + Some(v) => Said::System(v.clone()), + }); + let Some(native) = &self.native else { return geo.unwrap_or(Said::Default) }; + let native = Said::native(native.crs.as_deref(), md); + let Some(geo) = geo else { return native }; + // A type that only names a system leaves its definition to the metadata. + let only_named = match &native { + Said::Unresolved(_) => true, + Said::System(v) => v.as_object().is_some_and(|o| o.len() == 1), + Said::Default | Said::Unknown => false, + }; + if native.same(&geo) { + let from_geo = native.usable().is_none() && (only_named || geo.usable().is_some()); + return if from_geo { geo } else { native }; + } + if matches!((&native, &geo), (Said::Unresolved(_), Said::System(_) | Said::Unknown)) { + self.notes.push(format!( + "its geometry column's type gives the coordinate system {}, which RustGIS can't read, and its 'geo' metadata {}: the metadata's is used", + native.name(), + geo.name() + )); + return geo; + } + let differ = if native.identity() == Identity::None || geo.identity() == Identity::None { + "coordinate systems that can't be told to be the same" + } else { + "different coordinate systems" + }; + self.notes.push(format!( + "its geometry column's type and its 'geo' metadata give {differ} ({} and {}): the type's is used", + native.name(), + geo.name() + )); + native + } + + /// How coordinates in the declared system are placed. Another body's system is said, or + /// refused when its coordinates aren't longitude/latitude. + fn resolve(&mut self, said: Said) -> Result { + let notes = &mut self.notes; + let crs = match said { + Said::Default => return Ok(Reproject::from_crs(Crs::LonLat, notes)), + Said::Unknown => { + // Said once its coordinates can be looked at ([`unknown_note`]). + self.unknown_crs = true; + return Ok(Reproject::from_crs(Crs::LonLat, notes)); + } + Said::Unresolved(text) => { + notes.push(Note::loss( + LossCode::AssumedCrs, + format!("its geometry column's coordinate system '{text}' isn't one RustGIS can read; read as longitude/latitude"), + )); + return Ok(Reproject::from_crs(Crs::LonLat, notes)); + } + Said::System(v) => v, + }; + let code = crs_code(Some(&crs)); + if code.is_none() { + match planetary::projjson(&crs) { + Some(Declared::Refused(e)) => return Err(DataError::Format(format!("its coordinate system: {e}"))), + Some(Declared::LonLat { note, .. }) => { + notes.push(format!("its coordinate system: {note}")); + return Ok(Reproject::from_crs(Crs::LonLat, notes)); + } + None => {} + } + if let Some(esri) = esri(&crs) { + if esri.is_planetary() { + let system = esri.label(); + if !esri.is_geographic() { + let why = planetary::refused(&system, planetary::PROJECTED); + return Err(DataError::Format(format!("its coordinate system: {why}"))); + } + notes.push(format!("its coordinate system: {}", planetary::read_note(&system))); + } + return Ok(Reproject::from_crs(esri, notes)); + } + if !is_crs84(&crs) { + // A coordinate system given without an EPSG code (and not OGC:CRS84) can't be converted. + notes.push(Note::loss(LossCode::AssumedCrs, "its coordinate system has no EPSG code; read as longitude/latitude")); + } + } + Ok(Reproject::from_epsg(code, notes)) + } + + /// Says that the coordinates' epoch isn't kept. + fn note_epoch(&mut self) { + let epoch = match self.meta().and_then(|m| m.get("epoch")) { + None | Some(Value::Null) => return, + Some(v) => clip(&v.to_string()), + }; + self.notes.push(Note::loss( + LossCode::DroppedEpoch, + format!("its coordinate epoch ({epoch}) isn't kept: positions are read as if the system didn't change over time"), + )); + } + + /// Says that edges other than straight lines are read as straight lines. Points have none. + fn note_edges(&mut self, md: &ParquetMetaData) { + let meta = self.meta(); + let edges = match self.native.as_ref().and_then(|n| n.edges.clone()) { + Some(edges) => edges, + None => match meta.and_then(|m| m.get("edges")) { + None | Some(Value::Null) => return, + Some(Value::String(s)) if s.eq_ignore_ascii_case("planar") => return, + Some(Value::String(s)) => clip(s), + Some(v) => clip(&v.to_string()), + }, + }; + let mut types = meta.and_then(|m| m.get("geometry_types")).and_then(Value::as_array).into_iter().flatten().peekable(); + let points = + types.peek().is_some() && types.all(|t| t.as_str().and_then(super::geometry_type_name) == Some(crate::GeometryType::Point)); + if !points && !self.native_points(md) { + self.notes.push(Note::loss( + LossCode::ApproximatedCurve, + format!("its edges follow the Earth's curve ({edges}) and are read as straight lines between their vertices"), + )); + } + } +} + +/// The notice for a file that declares its system unknown, which says so when its coordinates +/// (`extent`, as the file holds them, empty when none are known) can't be degrees. +pub(super) fn unknown_note(extent: &rustgis_geom::Extent) -> Note { + let what = if extent.beyond_lonlat() { + "the file says its coordinate system is unknown, and its coordinates are not longitude/latitude; RustGIS reads them as WGS 84 and they may draw out of place: load the layer and give its system with Define Projection" + } else if extent.is_empty() { + "the file says its coordinate system is unknown; read as longitude/latitude, though its coordinates couldn't be checked: if they aren't, load the layer and give its system with Define Projection" + } else { + "the file says its coordinate system is unknown; read as longitude/latitude" + }; + Note::loss(LossCode::AssumedCrs, what) +} + +/// A coordinate system as a file declares it. +#[derive(PartialEq)] +enum Said { + /// None given: OGC:CRS84. + Default, + /// Declared unknown: `crs: null` or `srid:0`. + Unknown, + /// PROJJSON, or its `id` alone for a system given by authority and code. + System(Value), + /// A native type's text that isn't any form RustGIS reads, or names nothing in the file. + Unresolved(String), +} + +/// A system's identity, to compare two declarations of it by. +#[derive(PartialEq)] +enum Identity { + LonLat, + Unknown, + Epsg(u32), + /// Another authority's code. + Code(String), + /// Without a code, or not read. + None, +} + +impl Said { + /// The system of a native type's `crs`: inline PROJJSON, `authority:code`, `srid:` (an + /// EPSG code) or `projjson:`, a key of the file's metadata. + fn native(text: Option<&str>, md: &ParquetMetaData) -> Said { + let Some(text) = text.map(str::trim) else { return Said::Default }; + let unresolved = || Said::Unresolved(clip(text)); + let definition = |v: &str| match serde_json::from_str::(v) { + // An object that defines no system, by its type, says nothing. Without a type, its code + // names one. + Ok(v) if v.get("type").map_or(id(&v).is_some(), |t| t.as_str().is_some_and(|t| t.ends_with("CRS"))) => Said::System(v), + _ => unresolved(), + }; + if text.starts_with('{') { + return definition(text); + } + let Some((authority, code)) = text.split_once(':').map(|(a, c)| (a.trim(), c.trim())) else { return unresolved() }; + if authority.eq_ignore_ascii_case("projjson") { + return key(md, code).map_or_else(unresolved, definition); + } + if authority.eq_ignore_ascii_case("srid") { + return match code.parse::() { + Ok(0) => Said::Unknown, + Ok(n) => Said::System(json!({"id": {"authority": "EPSG", "code": n}})), + Err(_) => unresolved(), + }; + } + let name = + |s: &str| !s.is_empty() && s.len() <= MAX_NAME && s.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.')); + if name(authority) && name(code) { + return Said::System(json!({"id": {"authority": authority, "code": code}})); + } + unresolved() + } + + fn identity(&self) -> Identity { + let v = match self { + Said::Default => return Identity::LonLat, + Said::Unknown => return Identity::Unknown, + Said::Unresolved(_) => return Identity::None, + Said::System(v) => v, + }; + match crs_code(Some(v)) { + Some(4326) => Identity::LonLat, + Some(code) => Identity::Epsg(code), + None if is_crs84(v) => Identity::LonLat, + None => id(v).map_or(Identity::None, |(a, c)| Identity::Code(format!("{a}:{c}").to_ascii_uppercase())), + } + } + + /// Whether `other` declares the same system, in whatever form. A definition without a code is + /// told by its name and its parameters. + fn same(&self, other: &Said) -> bool { + let (a, b) = (self.identity(), other.identity()); + if self == other { + return true; + } + if a != Identity::None && b != Identity::None { + return a == b; + } + match (self.definition(), other.definition()) { + (Some(a), Some(b)) => a == b, + _ => false, + } + } + + /// The name and the parameters (as a PROJ definition) of the system, by its own definition or + /// its EPSG code's. `None` when there is none or it can't be read. + fn definition(&self) -> Option<(String, String)> { + let system = match self { + Said::System(v) if v.get("type").is_some() => { + let text = v.to_string(); + if text.len() > MAX_DEFINITION { + return None; + } + terrio_crs::SpatialRef::from_projjson(&text).ok()? + } + _ => match self.identity() { + Identity::LonLat => terrio_crs::SpatialRef::from_epsg(4326).ok()?, + Identity::Epsg(code) => terrio_crs::SpatialRef::from_epsg(code).ok()?, + Identity::Unknown | Identity::Code(_) | Identity::None => return None, + }, + }; + Some((system.name()?.to_ascii_lowercase(), system.to_proj4()?)) + } + + /// The system RustGIS reads it in, `None` for one it can't use. + fn usable(&self) -> Option { + match self { + Said::System(v) => match crs_code(Some(v)) { + Some(code) => Crs::from_epsg(code), + None if is_crs84(v) => Some(Crs::LonLat), + None => esri(v), + }, + Said::Default => Some(Crs::LonLat), + Said::Unknown | Said::Unresolved(_) => None, + } + } + + /// The system as a notice names it. + fn name(&self) -> String { + match self { + Said::Default => "OGC:CRS84, the default".into(), + Said::Unknown => "unknown".into(), + Said::Unresolved(text) => format!("'{text}'"), + Said::System(v) => match (id(v), v.get("name").and_then(Value::as_str)) { + (Some((a, c)), _) => clip(&format!("{a}:{c}")), + (None, Some(name)) => clip(name), + (None, None) => "one with no code".into(), + }, + } + } +} + +/// The column with the first of the usual names, among columns with their leaf index. +fn usual<'a>(among: &[(usize, &'a str)]) -> Option<(usize, &'a str)> { + USUAL_NAMES.iter().find_map(|n| among.iter().copied().find(|(_, c)| c == n)) +} + +/// A native geometry type's declaration, `None` for any other type. +fn native(ty: Option<&LogicalType>) -> Option { + match ty? { + LogicalType::Geometry(g) => Some(Native { crs: g.crs.clone(), edges: None }), + LogicalType::Geography(g) => Some(Native { + crs: g.crs.clone(), + edges: Some(g.algorithm.unwrap_or_default().to_string().trim_start_matches('_').to_ascii_lowercase()), + }), + _ => None, + } +} + +/// The value of a key of the file's metadata. +fn key<'a>(md: &'a ParquetMetaData, key: &str) -> Option<&'a str> { + md.file_metadata().key_value_metadata()?.iter().find(|k| k.key == key)?.value.as_deref() +} + +/// Refuses `geo` metadata of a major version RustGIS doesn't know, whose fields may mean +/// something else. One without a version is read. +fn check_version(geo: &Value) -> Result<()> { + let (version, text) = match geo.get("version") { + None | Some(Value::Null) => return Ok(()), + Some(Value::String(s)) => (s.clone(), true), + Some(v) => (v.to_string(), false), + }; + let major = version.split('.').next().and_then(|m| m.trim().parse::().ok()); + if text && major.is_some_and(|m| MAJOR_VERSIONS.contains(&m)) { + return Ok(()); + } + Err(DataError::Unsupported(format!("GeoParquet version {} (versions up to 2.x are read)", clip(&version)))) +} + +/// A PROJJSON definition's authority and code. +fn id(crs: &Value) -> Option<(&str, String)> { + let id = crs.get("id")?; + let code = match id.get("code")? { + Value::String(s) => s.clone(), + Value::Number(n) => n.to_string(), + _ => return None, + }; + Some((id.get("authority")?.as_str()?, code)) +} + +/// The system of an `ESRI` code. +fn esri(crs: &Value) -> Option { + let (authority, code) = id(crs)?; + if !authority.eq_ignore_ascii_case("ESRI") { + return None; + } + crate::raster::crs::esri_crs(code.trim().parse().ok()?) +} + +#[cfg(test)] +mod tests { + use super::super::{ParquetSource, projjson}; + use super::*; + use crate::Geometry; + use crate::source::{FeatureSource, Request}; + use parquet::basic::{EdgeInterpolationAlgorithm as Edges, Repetition}; + use parquet::data_type::ByteArrayType; + use parquet::file::metadata::KeyValue; + use parquet::file::properties::WriterProperties; + use parquet::file::writer::SerializedFileWriter; + use rustgis_geom::Coord; + use std::sync::Arc; + + const UTM: Coord = Coord::new(222146.7, 3893937.8); + const DEGREES: Coord = Coord::new(-90.0, 35.0); + + /// A Parquet file of binary columns, each with a logical type and one row, a point at `at`, and + /// the file's metadata. + fn file(columns: &[(&str, Option)], at: Coord, metadata: &[(&str, String)]) -> Vec { + file_of(columns, at, metadata, false) + } + + /// As [`file`], of a line from `at` when `line`. + fn file_of(columns: &[(&str, Option)], at: Coord, metadata: &[(&str, String)], line: bool) -> Vec { + let fields = columns + .iter() + .map(|(name, ty)| { + let ty = parquet::schema::types::Type::primitive_type_builder(name, Physical::BYTE_ARRAY) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(ty.clone()); + Arc::new(ty.build().unwrap()) + }) + .collect(); + let schema = Arc::new(parquet::schema::types::Type::group_type_builder("schema").with_fields(fields).build().unwrap()); + let kv = metadata.iter().map(|(k, v)| KeyValue::new(k.to_string(), v.clone())).collect(); + let props = Arc::new(WriterProperties::builder().set_key_value_metadata(Some(kv)).build()); + let end = Coord::new(at.x + 1.0, at.y + 1.0); + let geometry = if line { Geometry::Line(vec![vec![at, end]]) } else { Geometry::Point(at) }; + let mut writer = SerializedFileWriter::new(Vec::new(), schema, props).unwrap(); + let mut group = writer.next_row_group().unwrap(); + while let Some(mut column) = group.next_column().unwrap() { + let wkb = crate::wkb::encode(&geometry); + column.typed::().write_batch(&[wkb.into()], None, None).unwrap(); + column.close().unwrap(); + } + group.close().unwrap(); + writer.into_inner().unwrap() + } + + fn geometry(crs: Option<&str>) -> Option { + Some(LogicalType::geometry(crs.map(str::to_string))) + } + + /// `geo` metadata with the column's `more` members beside its encoding and types. + fn geo(version: &str, more: Value) -> (&'static str, String) { + let mut column = json!({"encoding": "WKB", "geometry_types": ["LineString"]}); + column.as_object_mut().unwrap().extend(more.as_object().unwrap().clone()); + ("geo", json!({"version": version, "primary_column": "geometry", "columns": {"geometry": column}}).to_string()) + } + + fn open(columns: &[(&str, Option)], at: Coord, metadata: &[(&str, String)]) -> ParquetSource { + ParquetSource::open_bytes(file(columns, at, metadata), "t").unwrap() + } + + /// The notes, each with its loss code. + fn notes(s: &ParquetSource) -> Vec<(Option, String)> { + s.info().notes.iter().map(|n| (n.loss, n.text.clone())).collect() + } + + fn utm16() -> Value { + projjson(Crs::from_epsg(26916).unwrap()).unwrap() + } + + #[test] + fn the_native_type_gives_the_system_in_every_form() { + let inline = utm16().to_string(); + let key = ("my_crs", inline.clone()); + for (crs, at, epsg) in [ + (None, DEGREES, 4326), + (Some("OGC:CRS84"), DEGREES, 4326), + (Some("EPSG:4326"), DEGREES, 4326), + (Some("srid:4326"), DEGREES, 4326), + (Some("OGC:CRS83"), DEGREES, 4269), + (Some("ogc:crs27"), DEGREES, 4267), + (Some(inline.as_str()), UTM, 26916), + (Some("EPSG:26916"), UTM, 26916), + (Some("epsg:26916"), UTM, 26916), + (Some("srid:26916"), UTM, 26916), + (Some("projjson:my_crs"), UTM, 26916), + (Some("ESRI:102033"), Coord::new(0.0, 0.0), 0), + ] { + for name in ["geometry", "shape"] { + let s = open(&[(name, geometry(crs))], at, std::slice::from_ref(&key)); + let expected = if epsg == 0 { crate::raster::crs::esri_crs(102033).unwrap() } else { Crs::from_epsg(epsg).unwrap() }; + assert_eq!(s.coord_crs(), expected, "{crs:?}"); + assert_eq!(s.info().coordinate_system().unwrap_or(Crs::LonLat), expected, "{crs:?}: as the layer keeps it"); + assert_eq!(notes(&s), [], "{crs:?}"); + let batch = s.read(&Request { extent: None, limit: 10, own: None }).unwrap(); + assert_eq!(batch.features[0].geometry, Some(Geometry::Point(at))); + } + } + } + + #[test] + fn an_unresolvable_native_system_is_assumed_with_a_notice() { + let long = format!("EPSG:{}", "9".repeat(100_000)); + let deep = format!("{{\"a\":{}", "[".repeat(100_000)); + for crs in [ + "", + "nonsense", + "projjson:missing", + "projjson:bad", + "srid:x", + "srid:-1", + "srid:99999999999", + "{not json", + "EPSG:0", + "EPSG:", + ":1", + "EPSG:4979999", + "IGNF:ATI", + "é:é", + &long, + &deep, + ] { + let s = open(&[("geometry", geometry(Some(crs)))], DEGREES, &[("bad", "[1]".into())]); + assert_eq!(s.coord_crs(), Crs::LonLat); + let said = notes(&s); + assert_eq!(said.len(), 1, "{said:?}"); + assert_eq!(said[0].0, Some(LossCode::AssumedCrs), "{said:?}"); + assert!(said[0].1.len() < 400, "a file's text is clipped"); + } + } + + #[test] + fn another_bodys_native_system_is_refused_or_said() { + let e = ParquetSource::open_bytes(file(&[("geometry", geometry(Some("IAU_2015:49910")))], UTM, &[]), "t").err().unwrap(); + assert!(e.to_string().contains("another body"), "{e}"); + let s = open(&[("geometry", geometry(Some("IAU_2015:49900")))], DEGREES, &[]); + assert!(notes(&s)[0].1.contains("another body"), "{:?}", notes(&s)); + } + + #[test] + fn an_unknown_system_is_said_and_whether_it_can_be_degrees() { + for (columns, metadata) in [ + ([("geometry", geometry(Some("srid:0")))], vec![]), + ([("geometry", None)], vec![geo("2.0.0", json!({"crs": null}))]), + ([("geometry", geometry(Some("srid:0")))], vec![geo("2.0.0", json!({"crs": null}))]), + ] { + let degrees = notes(&open(&columns, DEGREES, &metadata)); + assert_eq!(degrees.len(), 1, "{degrees:?}"); + assert_eq!(degrees[0].0, Some(LossCode::AssumedCrs)); + assert_eq!(degrees[0].1, "the file says its coordinate system is unknown; read as longitude/latitude"); + let metres = notes(&open(&columns, UTM, &metadata)); + assert_eq!(metres.len(), 1, "{metres:?}"); + assert_eq!(metres[0].0, Some(LossCode::AssumedCrs)); + assert!(metres[0].1.contains("are not longitude/latitude") && metres[0].1.contains("Define Projection"), "{metres:?}"); + } + } + + /// An undeclared `bbox` struct belongs to a usual column, not to another one read in its place. + #[test] + fn a_plain_bbox_is_only_the_columns_it_can_belong_to() { + use parquet::file::reader::{FileReader, SerializedFileReader}; + let native = || geometry(None); + for (columns, metadata, plain) in [ + (vec![("geometry", None)], vec![], true), + (vec![("shape", native())], vec![], true), + (vec![("a", native()), ("geometry", native())], vec![], true), + (vec![("geometry", None), ("shape", native())], vec![], false), + (vec![("a", native()), ("b", native())], vec![], false), + (vec![("geometry", None), ("shape", native())], vec![geo("1.0.0", json!({}))], true), + ] { + let reader = SerializedFileReader::new(bytes::Bytes::from(file(&columns, DEGREES, &metadata))).unwrap(); + assert_eq!(Column::find(reader.metadata()).unwrap().plain_bbox, plain, "{columns:?}"); + } + } + + /// Coordinates that can't be degrees in a file that says they are, or that says nothing. + #[test] + fn coordinates_beyond_degrees_are_said() { + for (ty, metadata, loss) in [ + (None, vec![], Some(LossCode::AssumedCrs)), + (geometry(None), vec![], None), + (geometry(Some("OGC:CRS84")), vec![], None), + (None, vec![geo("1.1.0", json!({}))], None), + ] { + let all = notes(&open(&[("geometry", ty.clone())], UTM, &metadata)); + assert!(all.len() == 1 && all[0].0 == loss && all[0].1.contains("Define Projection"), "{ty:?}: {all:?}"); + assert_eq!(notes(&open(&[("geometry", ty)], DEGREES, &metadata)), []); + } + } + + #[test] + fn an_unknown_system_unchecked_says_so() { + let note = super::unknown_note(&rustgis_geom::Extent::EMPTY); + assert_eq!(note.loss, Some(LossCode::AssumedCrs)); + assert!(note.contains("couldn't be checked") && note.contains("Define Projection"), "{note:?}"); + } + + #[test] + fn the_native_type_wins_over_the_metadata_with_a_notice() { + let crs84 = json!({"type": "GeographicCRS", "name": "WGS 84 longitude-latitude", "id": {"authority": "OGC", "code": "CRS84"}}); + let wgs84 = json!({"type": "GeographicCRS", "name": "WGS 84", "id": {"authority": "EPSG", "code": 4326}}); + let mut no_code = utm16(); + no_code.as_object_mut().unwrap().remove("id"); + // Its name on another system: a false easting of 400 km. + let mut moved = no_code.clone(); + let parameters = moved.pointer_mut("/conversion/parameters").and_then(Value::as_array_mut).unwrap(); + parameters.iter_mut().find(|p| p["name"] == "False easting").unwrap()["value"] = json!(400000.0); + // The same system in another form says nothing. + for (native, meta) in [ + (None, json!({})), + (None, json!({"crs": crs84})), + (Some("EPSG:4326"), json!({"crs": crs84})), + (Some("OGC:CRS84"), json!({"crs": wgs84})), + (Some("OGC:CRS84"), json!({})), + (Some("EPSG:26916"), json!({"crs": utm16()})), + (Some("EPSG:26916"), json!({"crs": no_code})), + (Some(no_code.to_string().as_str()), json!({"crs": utm16()})), + (Some("srid:26916"), json!({"crs": utm16()})), + (Some(utm16().to_string().as_str()), json!({"crs": utm16()})), + ] { + let s = open(&[("geometry", geometry(native))], DEGREES, &[geo("2.0.0", meta.clone())]); + assert_eq!(notes(&s), [], "{native:?} and {meta}"); + assert_eq!(s.coord_crs() == Crs::LonLat, !meta.to_string().contains("UTM"), "{native:?} and {meta}"); + } + // Different ones: the type's, and both are named. + for (native, meta, epsg, said) in [ + (Some("EPSG:26916"), json!({}), 26916, "EPSG:26916 and OGC:CRS84"), + (Some("EPSG:26916"), json!({"crs": crs84}), 26916, "EPSG:26916 and OGC:CRS84"), + (Some("EPSG:26916"), json!({"crs": null}), 26916, "EPSG:26916 and unknown"), + (Some("EPSG:32616"), json!({"crs": utm16()}), 32616, "EPSG:32616 and EPSG:26916"), + (Some("EPSG:26916"), json!({"crs": moved}), 26916, "EPSG:26916 and NAD83 / UTM zone 16N"), + (None, json!({"crs": utm16()}), 4326, "OGC:CRS84, the default and EPSG:26916"), + ] { + let s = open(&[("geometry", geometry(native))], DEGREES, &[geo("2.0.0", meta.clone())]); + assert_eq!(s.coord_crs(), Crs::from_epsg(epsg).unwrap()); + let all = notes(&s); + assert!(all.len() == 1 && all[0].0.is_none() && all[0].1.contains(said) && all[0].1.contains("the type's is used"), "{all:?}"); + } + // A type that names no system leaves it to the metadata. + let s = open(&[("geometry", geometry(Some("projjson:missing")))], UTM, &[geo("2.0.0", json!({"crs": utm16()}))]); + assert_eq!(s.coord_crs(), Crs::from_epsg(26916).unwrap()); + assert!(notes(&s).len() == 1 && notes(&s)[0].1.contains("the metadata's is used"), "{:?}", notes(&s)); + for empty in ["{}", "projjson:empty", r#"{"type":"Ellipsoid"}"#] { + let metadata = [geo("2.0.0", json!({"crs": utm16()})), ("empty", "{}".to_string())]; + let s = open(&[("geometry", geometry(Some(empty)))], UTM, &metadata); + assert_eq!(s.coord_crs(), Crs::from_epsg(26916).unwrap(), "{empty}"); + assert!(notes(&s).len() == 1 && notes(&s)[0].1.contains("the metadata's is used"), "{:?}", notes(&s)); + } + // A projected definition's name doesn't make it longitude/latitude. + let mut named = no_code.clone(); + named["name"] = json!("CRS84 / local grid"); + let all = notes(&open(&[("geometry", geometry(Some(&named.to_string())))], DEGREES, &[])); + assert!(all.len() == 1 && all[0].0 == Some(LossCode::AssumedCrs), "{all:?}"); + // So does one whose definition has no code, which is then assumed. + let s = open(&[("geometry", geometry(Some("projjson:missing")))], DEGREES, &[geo("2.0.0", json!({"crs": no_code}))]); + let all = notes(&s); + assert!(all.len() == 2 && all[0].1.contains("the metadata's is used") && all[1].0 == Some(LossCode::AssumedCrs), "{all:?}"); + // And the metadata's unknown. + let s = open(&[("geometry", geometry(Some("projjson:missing")))], UTM, &[geo("2.0.0", json!({"crs": null}))]); + let all = notes(&s); + assert!(all.len() == 2 && all[0].1.contains("the metadata's is used") && all[1].1.contains("Define Projection"), "{all:?}"); + // Another body's system isn't taken for the Earth's by a definition that can't be compared. + let bytes = file(&[("geometry", geometry(Some("IAU_2015:49910")))], UTM, &[geo("2.0.0", json!({"crs": no_code}))]); + assert!(ParquetSource::open_bytes(bytes, "t").err().unwrap().to_string().contains("another body")); + // Coordinates that can't be degrees say the way out when their system is assumed. + for (at, said) in [(UTM, true), (DEGREES, false)] { + let all = notes(&open(&[("geometry", geometry(Some("IGNF:ATI")))], at, &[])); + assert!(all.len() == 1 && all[0].0 == Some(LossCode::AssumedCrs) && all[0].1.contains("Define Projection") == said, "{all:?}"); + } + // One that names another system, though RustGIS can't use it, doesn't. + for crs in ["IGNF:ATI", "EPSG:4979999"] { + let s = open(&[("geometry", geometry(Some(crs)))], DEGREES, &[geo("2.0.0", json!({"crs": utm16()}))]); + let all = notes(&s); + assert_eq!(s.coord_crs(), Crs::LonLat); + assert!(all.len() == 2 && all[0].1.contains("the type's is used") && all[1].0 == Some(LossCode::AssumedCrs), "{all:?}"); + } + // A file without the type is read by its metadata, as before. + let s = open(&[("geometry", None)], UTM, &[geo("1.1.0", json!({"crs": utm16()}))]); + assert_eq!((s.coord_crs(), notes(&s)), (Crs::from_epsg(26916).unwrap(), vec![])); + } + + #[test] + fn the_geometry_column_is_the_primary_then_a_native_then_a_usual_name() { + let utm = || geometry(Some("EPSG:26916")); + let left = |n: &str, kind: &str| format!("1 column of a type RustGIS has no field for was left out: {n} ({kind})"); + // A native type over a usual name without one. + let s = open(&[("geom", None), ("shape", utm())], UTM, &[]); + assert_eq!(s.coord_crs(), Crs::from_epsg(26916).unwrap()); + assert_eq!(notes(&s), [(None, left("geom", "binary"))]); + // Several: a usual name, else the first, saying which. + for (names, read, other) in [(["a", "geom"], "geom", "a"), (["b", "a"], "b", "a")] { + let columns = names.map(|n| (n, if n == read { utm() } else { geometry(None) })); + let s = open(&columns, UTM, &[]); + assert_eq!(s.coord_crs(), Crs::from_epsg(26916).unwrap(), "{names:?}"); + let which = format!("it has 2 geometry columns and nothing says which is the main one: '{read}' is read"); + assert_eq!(notes(&s), [(None, which), (None, left(other, "geometry"))]); + } + // The metadata's primary column, whatever the others are. + let s = open(&[("a", utm()), ("geometry", None)], DEGREES, &[geo("1.0.0", json!({}))]); + assert_eq!((s.coord_crs(), notes(&s)), (Crs::LonLat, vec![(None, left("a", "geometry"))])); + // A usual name alone, and none. + assert_eq!(notes(&open(&[("the_geom", None)], DEGREES, &[])), []); + assert!(ParquetSource::open_bytes(file(&[("shape", None)], DEGREES, &[]), "t").is_err()); + } + + #[test] + fn curved_edges_are_said_unless_the_layer_is_points() { + let open = |columns: &[(&str, Option)], at, metadata: &[(&str, String)]| { + ParquetSource::open_bytes(file_of(columns, at, metadata, true), "t").unwrap() + }; + let geography = |e| Some(LogicalType::geography(Some("OGC:CRS84".into()), e)); + for (ty, name) in [ + (geography(None), "spherical"), + (geography(Some(Edges::SPHERICAL)), "spherical"), + (geography(Some(Edges::VINCENTY)), "vincenty"), + (geography(Some(Edges::THOMAS)), "thomas"), + (geography(Some(Edges::ANDOYER)), "andoyer"), + (geography(Some(Edges::KARNEY)), "karney"), + ] { + let s = open(&[("geog", ty.clone())], DEGREES, &[]); + let said = notes(&s); + assert_eq!(s.coord_crs(), Crs::LonLat); + assert!(said.len() == 1 && said[0].0 == Some(LossCode::ApproximatedCurve) && said[0].1.contains(name), "{said:?}"); + } + for edges in ["spherical", "vincenty", "thomas", "andoyer", "karney"] { + let said = notes(&open(&[("geometry", None)], DEGREES, &[geo("2.0.0", json!({"edges": edges}))])); + assert!(said.len() == 1 && said[0].0 == Some(LossCode::ApproximatedCurve) && said[0].1.contains(edges), "{said:?}"); + let open = super::tests::open; + let points = json!({"edges": edges, "geometry_types": ["Point", "MultiPoint"]}); + assert_eq!(notes(&open(&[("geometry", None)], DEGREES, &[geo("2.0.0", points)])), []); + } + assert_eq!(notes(&open(&[("geometry", None)], DEGREES, &[geo("2.0.0", json!({"edges": "planar"}))])), []); + } + + /// The statistics of every row group say that a geography holds points alone. + #[test] + fn a_geography_of_points_by_its_statistics_has_no_edges() { + use parquet::file::reader::{FileReader, SerializedFileReader}; + let ty = Some(LogicalType::geography(None, None)); + let bytes = bytes::Bytes::from(file(&[("geog", ty)], DEGREES, &[])); + let md = SerializedFileReader::new(bytes).unwrap().metadata().clone(); + for (types, said) in [(None, 1), (Some(vec![]), 1), (Some(vec![1, 3004]), 0), (Some(vec![1001]), 0), (Some(vec![1, 2]), 1)] { + let group = md.row_group(0).clone(); + let stats = parquet::geospatial::statistics::GeospatialStatistics::new(None, types.clone()); + let chunk = group.column(0).clone().into_builder().set_geo_statistics(Box::new(stats)).build().unwrap(); + let group = group.into_builder().set_column_metadata(vec![chunk]).build().unwrap(); + let md = ParquetMetaData::new(md.file_metadata().clone(), vec![group]); + let column = Column::find(&md).unwrap(); + assert_eq!(column.notes.iter().count(), said, "{types:?}"); + assert_eq!(column.native_zm(&md), types.is_some_and(|t| t.iter().any(|t| *t > 1000))); + } + } + + #[test] + fn an_epoch_is_said() { + let said = notes(&open(&[("geometry", None)], DEGREES, &[geo("2.0.0", json!({"epoch": 2021.5}))])); + assert!(said.len() == 1 && said[0].0 == Some(LossCode::DroppedEpoch) && said[0].1.contains("2021.5"), "{said:?}"); + assert_eq!(notes(&open(&[("geometry", None)], DEGREES, &[geo("2.0.0", json!({"epoch": null}))])), []); + } + + #[test] + fn unknown_major_versions_are_refused() { + for version in ["0.1.0", "0.4.0", "1.0.0-beta.1", "1.0.0", "1.1.0", "1.9.0", "2.0.0", "2.3.1", "2.0.0-dev"] { + assert_eq!(notes(&open(&[("geometry", None)], DEGREES, &[geo(version, json!({}))])), [], "{version}"); + } + let number = ("geo", r#"{"version":2.5,"primary_column":"geometry","columns":{"geometry":{"encoding":"WKB"}}}"#.to_string()); + assert!(ParquetSource::open_bytes(file(&[("geometry", None)], DEGREES, &[number]), "t").is_err()); + for version in ["3.0.0", "10.0.0", "", "two", "-1.0"] { + let e = ParquetSource::open_bytes(file(&[("geometry", geometry(None))], DEGREES, &[geo(version, json!({}))]), "t").err(); + assert!(e.is_some_and(|e| e.to_string().contains("GeoParquet version")), "{version}"); + } + } + + #[test] + fn metadata_that_cant_be_read_is_said() { + for bad in ["{", "[1]", "null"] { + let said = notes(&open(&[("geometry", None)], DEGREES, &[("geo", bad.into())])); + assert!(said.len() == 1 && said[0].0 == Some(LossCode::AssumedCrs), "{said:?}"); + let s = open(&[("geometry", geometry(Some("EPSG:26916")))], UTM, &[("geo", bad.into())]); + assert_eq!(s.coord_crs(), Crs::from_epsg(26916).unwrap()); + assert!(notes(&s).len() == 1 && notes(&s)[0].0.is_none(), "{:?}", notes(&s)); + } + } +} diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index d9b4cd2e0f..b46579c1aa 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -3528,17 +3528,26 @@ fn a_csv_export_takes_x_and_y_in_a_system_asked_for() { } /// A catalog index as AlphaEarth's is (a `bbox` struct, a nested `assets.data.href`), and patch -/// embeddings as Earth Index's are (a fixed-size list of floats a point), in row groups of 50. -fn write_index_and_vectors() -> Vec { +/// embeddings as Earth Index's are (a fixed-size list of floats a point), in row groups of 50, with +/// `geo` metadata. +fn write_index_and_vectors(geo: &str, native: Option<::parquet::basic::LogicalType>) -> Vec { + write_index_and_vectors_with(geo, native, |_| {}) +} + +/// As [`write_index_and_vectors`], with the first point's WKB changed. +fn write_index_and_vectors_with(geo: &str, native: Option<::parquet::basic::LogicalType>, first: impl FnOnce(&mut Vec)) -> Vec { use arrow_array::builder::{FixedSizeListBuilder, Float32Builder}; use arrow_array::{BinaryArray, Float64Array, RecordBatch, StringArray, StructArray}; use arrow_schema::{DataType, Field as AField, Fields, Schema}; let pts = points(); - let wkbs: Vec> = pts.iter().map(|(c, ..)| wkb::encode(&Geometry::Point(*c))).collect(); + let mut wkbs: Vec> = pts.iter().map(|(c, ..)| wkb::encode(&Geometry::Point(*c))).collect(); + first(&mut wkbs[0]); let bbox_fields: Fields = ["xmin", "ymin", "xmax", "ymax"].map(|n| Arc::new(AField::new(n, DataType::Float64, false))).into_iter().collect(); - let coord = - |f: fn(&Coord) -> f64| Arc::new(Float64Array::from(pts.iter().map(|(c, ..)| f(c)).collect::>())) as arrow_array::ArrayRef; + let coord = |f: fn(&Coord) -> f64| { + Arc::new(Float64Array::from(pts.iter().map(|(c, ..)| f(c) * if geo.contains("metres") { 1e5 } else { 1.0 }).collect::>())) + as arrow_array::ArrayRef + }; let bbox = StructArray::new(bbox_fields.clone(), vec![coord(|c| c.x), coord(|c| c.y), coord(|c| c.x), coord(|c| c.y)], None); let href = Arc::new(StringArray::from(pts.iter().map(|p| format!("s3://bucket/{}.tiff", p.1)).collect::>())) as arrow_array::ArrayRef; @@ -3566,13 +3575,32 @@ fn write_index_and_vectors() -> Vec { Arc::new(assets), Arc::new(emb), ]; - let geo = r#"{"version":"1.0.0","primary_column":"geometry","columns":{"geometry":{"encoding":"WKB","geometry_types":["Point"]}}}"#; let props = ::parquet::file::properties::WriterProperties::builder() .set_max_row_group_row_count(Some(50)) + .set_statistics_enabled(if geo.contains("no-statistics") { + ::parquet::file::properties::EnabledStatistics::None + } else { + ::parquet::file::properties::EnabledStatistics::Chunk + }) .set_key_value_metadata(Some(vec![::parquet::file::metadata::KeyValue::new("geo".to_string(), geo.to_string())])) .build(); let mut out = Vec::new(); - let mut w = ::parquet::arrow::ArrowWriter::try_new(&mut out, schema.clone(), Some(props)).unwrap(); + // The arrow writer gives a geometry column no native type, so it is put in the schema. + let parquet_schema = ::parquet::arrow::ArrowSchemaConverter::new().convert(&schema).unwrap(); + let fields = parquet_schema.root_schema().get_fields().iter().map(|f| match native.clone().filter(|_| f.name() == "geometry") { + Some(ty) => Arc::new( + ::parquet::schema::types::Type::primitive_type_builder("geometry", ::parquet::basic::Type::BYTE_ARRAY) + .with_repetition(::parquet::basic::Repetition::REQUIRED) + .with_logical_type(Some(ty)) + .build() + .unwrap(), + ), + None => f.clone(), + }); + let root = ::parquet::schema::types::Type::group_type_builder("schema").with_fields(fields.collect()).build().unwrap(); + let described = ::parquet::schema::types::SchemaDescriptor::new(Arc::new(root)); + let options = ::parquet::arrow::arrow_writer::ArrowWriterOptions::new().with_properties(props).with_parquet_schema(described); + let mut w = ::parquet::arrow::ArrowWriter::try_new_with_options(&mut out, schema.clone(), options).unwrap(); w.write(&RecordBatch::try_new(schema, cols).unwrap()).unwrap(); w.close().unwrap(); out @@ -3580,7 +3608,10 @@ fn write_index_and_vectors() -> Vec { #[test] fn nested_columns_and_vectors_by_address() { - let bytes = write_index_and_vectors(); + let bytes = write_index_and_vectors( + r#"{"version":"1.0.0","primary_column":"geometry","columns":{"geometry":{"encoding":"WKB","geometry_types":["Point"]}}}"#, + None, + ); let url = "https://test.example/index.parquet"; remote::testing::serve(url, bytes.clone()); let e = Extent::new(10.0, 10.0, 40.0, 30.0); @@ -3614,6 +3645,121 @@ fn nested_columns_and_vectors_by_address() { } } +/// Points and rows found by place are in the file's own system, and refused when the file doesn't +/// say it. +#[test] +fn vectors_and_index_rows_by_address_keep_to_the_files_system() { + let geo = |crs: &str| { + format!( + r#"{{"version":"2.0.0","primary_column":"geometry","columns":{{"geometry":{{"encoding":"WKB","geometry_types":["Point"],"crs":{crs}}}}}}}"# + ) + }; + // Degrees' numbers as metres: all of them within a few metres of 0, 0. + let mercator = "https://test.example/mercator.parquet"; + remote::testing::serve(mercator, write_index_and_vectors(&geo(r#"{"id":{"authority":"EPSG","code":3857}}"#), None)); + let near = Extent::new(-0.01, -0.01, 0.01, 0.01); + let v = vectors_url_blocking(mercator, near, "embedding".into(), (100, 10_000)).unwrap(); + assert_eq!(v.points.len(), points().len()); + assert!(v.points.iter().all(|(x, y)| near.contains(Coord::new(*x, *y)))); + let far = Extent::new(10.0, 10.0, 40.0, 30.0); + assert!(vectors_url_blocking(mercator, far, "embedding".into(), (100, 10_000)).unwrap().points.is_empty()); + let refused = query_url_blocking(mercator, vec![], Request { extent: Some(near), limit: 10, own: None }).unwrap_err().to_string(); + assert!(refused.contains("not WGS 84 longitude/latitude"), "{refused}"); + for (name, more, why) in [ + ("nad27", r#"{"id":{"authority":"OGC","code":"CRS27"}}"#, "not WGS 84"), + ("zm", r#"{"id":{"authority":"EPSG","code":4326}},"bbox":[0,0,0,1,1,1]"#, "Z"), + ] { + let url = format!("https://test.example/{name}.parquet"); + remote::testing::serve(&url, write_index_and_vectors(&geo(more), None)); + let refused = query_url_blocking(&url, vec![], Request { extent: Some(far), limit: 10, own: None }).unwrap_err().to_string(); + assert!(refused.contains(why), "{refused}"); + } + let dated = "https://test.example/dated.parquet"; + remote::testing::serve(dated, write_index_and_vectors(&geo(r#"{"id":{"authority":"EPSG","code":4326}},"epoch":2021.5"#), None)); + let refused = query_url_blocking(dated, vec![], Request { extent: Some(far), limit: 10, own: None }).unwrap_err().to_string(); + assert!(refused.contains("epoch"), "{refused}"); + let unknown = "https://test.example/unknown.parquet"; + remote::testing::serve(unknown, write_index_and_vectors(&geo("null"), None)); + // Geography points have no edges to approximate, and a native type gives the system. + let native = |crs: &str| Some(::parquet::basic::LogicalType::geography(Some(crs.into()), None)); + let geography = "https://test.example/geography.parquet"; + remote::testing::serve(geography, write_index_and_vectors("{}", native("OGC:CRS84"))); + assert_eq!(vectors_url_blocking(geography, far, "embedding".into(), (100, 10_000)).unwrap().points.len(), in_box(&far)); + let native_mercator = "https://test.example/native-mercator.parquet"; + remote::testing::serve( + native_mercator, + write_index_and_vectors("{}", Some(::parquet::basic::LogicalType::geometry(Some("EPSG:3857".into())))), + ); + assert_eq!(vectors_url_blocking(native_mercator, near, "embedding".into(), (100, 10_000)).unwrap().points.len(), points().len()); + // A point with a height, and one with no place, are refused rather than lost without a word. + let wgs84 = geo(r#"{"id":{"authority":"EPSG","code":4326}}"#); + let height = "https://test.example/height.parquet"; + let with_z = |b: &mut Vec| { + // The ISO code of a Point Z, and its Z after x and y. + b[1..5].copy_from_slice(&1001u32.to_le_bytes()); + b.extend(5f64.to_le_bytes()); + }; + remote::testing::serve(height, write_index_and_vectors_with(&wgs84, None, with_z)); + let refused = vectors_url_blocking(height, far, "embedding".into(), (100, 10_000)).err().unwrap().to_string(); + assert!(refused.contains("1 of its points have Z or M values"), "{refused}"); + let refused = query_url_blocking(height, vec![], Request { extent: None, limit: 1000, own: None }).unwrap_err().to_string(); + assert!(refused.contains("Z or M"), "{refused}"); + // Points of a geography have no edges to say anything of; a line has. + assert_eq!( + query_url_blocking(geography, vec![], Request { extent: Some(far), limit: 1000, own: None }).unwrap().1.features.len(), + in_box(&far) + ); + let curved = "https://test.example/curved.parquet"; + let line = |b: &mut Vec| *b = wkb::encode(&Geometry::Line(vec![vec![Coord::new(0.0, 0.0), Coord::new(1.0, 1.0)]])); + remote::testing::serve(curved, write_index_and_vectors_with("{}", native("OGC:CRS84"), line)); + let refused = query_url_blocking(curved, vec![], Request { extent: None, limit: 1000, own: None }).unwrap_err().to_string(); + assert!(refused.contains("straight lines"), "{refused}"); + let refused = vectors_url_blocking(curved, far, "embedding".into(), (100, 10_000)).err().unwrap().to_string(); + assert!(refused.contains("1 of its geometries aren't single points"), "{refused}"); + let lost = "https://test.example/lost.parquet"; + let nowhere = |b: &mut Vec| b[5..13].copy_from_slice(&f64::INFINITY.to_le_bytes()); + // Boxes in metres with no statistics to say so as the file opens, and the same in degrees. + for (writer, refused) in [("no-statistics metres", true), ("no-statistics", false)] { + let url = format!("https://test.example/{}.parquet", writer.replace(' ', "-")); + let more = format!(r#"{{"id":{{"authority":"EPSG","code":4326}}}},"writer":"{writer}""#); + remote::testing::serve(&url, write_index_and_vectors(&geo(&more), None)); + let read = query_url_blocking(&url, vec![], Request { extent: Some(far), limit: 1000, own: None }); + match refused { + true => assert!(read.unwrap_err().to_string().contains("not longitude/latitude")), + false => assert_eq!(read.unwrap().1.features.len(), in_box(&far)), + } + } + let east = "https://test.example/one-point-in-metres.parquet"; + let beyond = |b: &mut Vec| b[5..13].copy_from_slice(&500_000f64.to_le_bytes()); + remote::testing::serve(east, write_index_and_vectors_with(&geo(r#"{"id":{"authority":"EPSG","code":4326}}"#), None, beyond)); + let refused = query_url_blocking(east, vec![], Request { extent: None, limit: 1000, own: None }).unwrap_err().to_string(); + assert!(refused.contains("not longitude/latitude"), "{refused}"); + // A box beyond degrees in a file that says it is in degrees. + let metres = "https://test.example/metres.parquet"; + let bounded = geo(r#"{"id":{"authority":"EPSG","code":4326}},"bbox":[222146,3893937,222147,3893938]"#); + remote::testing::serve(metres, write_index_and_vectors(&bounded, None)); + let refused = query_url_blocking(metres, vec![], Request { extent: Some(far), limit: 10, own: None }).unwrap_err().to_string(); + assert!(refused.contains("not longitude/latitude"), "{refused}"); + let polar = "https://test.example/beyond-the-pole.parquet"; + let beyond = |b: &mut Vec| b[13..21].copy_from_slice(&95f64.to_le_bytes()); + remote::testing::serve(polar, write_index_and_vectors_with(&wgs84, None, beyond)); + let east = "https://test.example/beyond-the-edge.parquet"; + let beyond = |b: &mut Vec| b[5..13].copy_from_slice(&500_000f64.to_le_bytes()); + remote::testing::serve(east, write_index_and_vectors_with(&wgs84, None, beyond)); + let refused = vectors_url_blocking(east, far, "embedding".into(), (100, 10_000)).err().unwrap().to_string(); + assert!(refused.contains("1 of its rows have no place"), "{refused}"); + let refused = vectors_url_blocking(polar, far, "embedding".into(), (100, 10_000)).err().unwrap().to_string(); + assert!(refused.contains("1 of its rows have no place"), "{refused}"); + let utm = geo(r#"{"id":{"authority":"EPSG","code":32616}}"#); + remote::testing::serve(lost, write_index_and_vectors_with(&utm, None, nowhere)); + let refused = vectors_url_blocking(lost, far, "embedding".into(), (100, 10_000)).err().unwrap().to_string(); + assert!(refused.contains("1 of its rows have no place"), "{refused}"); + let refused = vectors_url_blocking(unknown, far, "embedding".into(), (100, 10_000)).err().unwrap().to_string(); + assert!(refused.contains("coordinate system is unknown"), "{refused}"); + let refused = query_url_blocking(unknown, vec![], Request { extent: Some(far), limit: 10, own: None }).unwrap_err().to_string(); + assert!(refused.contains("coordinate system is unknown"), "{refused}"); +} + #[test] fn shapefile_complete_chunks_keep_all_rows_order_attributes_and_budget() { let dir = tempfile::tempdir().unwrap(); @@ -3827,6 +3973,10 @@ fn geopackage_flatgeobuf_and_geoparquet_visit_what_a_whole_read_gives() { let error = capped.visit_chunks(None, 4096, &mut |_| Ok(())).unwrap_err().to_string(); assert!(error.contains("row group 0 has 50 rows, more than the 40"), "{error}"); // A capped row group outside the extent is passed over, not refused. + // A catalog's read refuses the group, whichever of its rows would match. + let exact = parquet::ParquetSource::open_path(&pq, "grid").unwrap().with_group_rows(40).exact(); + let world = Request { extent: Some(Extent::new(-180.0, -90.0, 180.0, 90.0)), limit: 1000, own: None }; + assert!(exact.read(&world).unwrap_err().to_string().contains("more than the 40 read from one")); let capped = parquet::ParquetSource::open_path(&pq, "grid").unwrap().with_group_rows(40); assert!(visit_all(&capped, Some(Extent::new(178.0, 0.0, 179.0, 1.0)), 4096).0.is_empty()); // A GeoPackage put in place of the one added is refused, not read as the layer. diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index c9be0e8a53..1baf4a0abc 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -39,7 +39,7 @@ export names its feature. | Geotagged photos | `.jpg`, `.jpeg` | Add Data (several at once in the web app), drop them, upload, or `layer.addPhotos` with `"paths"` or a `"folder"` | JPEGs with a GPS position in their EXIF become points in the **Photos** layer (photos added one at a time join it): each with its `name`, `file`, `time` (when it was taken), `altitude`, `direction` (where the camera faced), `camera` and a `thumbnail` of at most 160 pixels, kept with the feature so the project needs no other file. Identify shows the thumbnail. Photos without a position are named in a notice and left out; a layer holds up to 2,000 photos. A JPEG is always read as a photo unless `layer.addData` or `layer.addDataBytes` is given `"as": "scan"` (a phone photo of a paper map, say: see [Scans with no coordinates](#rasters)). | | LiDAR point clouds | `.las`, `.laz` (COPC too) | Add Data, drop the file, upload, or From URL… | LAS 1.0–1.4 (point formats 0–10) and LAZ, on desktop and web: points with `z`, `intensity`, `classification`, `return` and colour (`red`, `green`, `blue`), coloured by ASPRS class or elevation. An evenly spread sample is read once, at most 2 million points (500,000 in the web app); views use that sample, not the COPC spatial index. LAZ decompression reads at most the first 400 million points (40 million on the web), with a notice when capped. Held in the system of the file's WKT or GeoTIFF-key record, as the file holds its points; without one, coordinates are kept as longitude/latitude, with a notice when they aren't. Points with no place in longitude/latitude are kept and counted ([below](#places-with-no-longitudelatitude)); points with a coordinate that isn't a number are left out and counted. A local project keeps the path; uploads keep the file bytes. Remote files download whole. | | GeoPackage | `.gpkg` | Add Data, or upload in the web app | Local files and browser uploads add every feature table, up to 32 (with the rest counted in `skippedCount` and up to 100 named in `skipped`); `"layer"` picks one, and `info.fileLayers` lists them. Desktop byte uploads and downloads add the first table unless `"layer"` names another. Large local tables use their R-tree. Rows with no geometry (NULL or empty) are kept, with their attributes, in whole reads and exports; a read of an extent leaves them out, as they have no location. A table is read in its coordinate system: by its EPSG code, or, for a system without one (or with a code RustGIS doesn't know), by the WKT definition the file gives it (the WKT2 of GeoPackage 1.2's `definition_12_063` first, as the specification says, else `definition`). The definition also comes before the code when it gives another datum transformation than the code's, or describes another body's system. This holds on the desktop and in the web app alike (an azimuthal equidistant system opens on the desktop only, and the web app says so). Browser tables are scanned, testing each geometry header's envelope first; UTF-16 databases aren't read there. Raster tile tables aren't imported. A `BLOB` column other than the geometry is left out, with a notice counting such columns and naming the first 12. `DATE` and `DATETIME` columns are read as dates and date-times (ISO 8601 text, as GeoPackage stores them); a value that isn't one is empty and counted in a notice. | -| GeoParquet | `.parquet`, `.geoparquet` | Add Data, or upload in the web app | WKB geometry, with the CRS from the file's `geo` metadata. A binary geometry column is required; plain non-spatial Parquet tables and GeoArrow-native geometry encodings aren't read by this importer. Row groups are pruned by the bbox covering. Whole reads and exports retain rows with null geometry and their attributes; extent-filtered reads exclude them because they have no location. Snappy, gzip, LZ4 and zstd compression are read, in the browser too; Brotli isn't. Text, whole-number, floating-point and true/false columns become fields, as do decimals stored as 32- or 64-bit integers (up to 18 digits), read as floating-point numbers. Columns annotated as DATE are read as dates, TIMESTAMP ones as date-times, and TIME ones as text (a time of day such as `00:00:00.000000000Z`); integers with no such annotation, whatever they hold (such as milliseconds since 1970), are read as the whole numbers they are. Other columns are left out: decimals stored as bytes (how many writers store every decimal), binary, lists, maps, structs, INT96 timestamps and further geometry columns. A notice gives how many were left out and names the first 12, each with its kind; another counts date values that couldn't be read (left empty) and date-times rounded to the microsecond, naming the first fields. A row group whose text (times of day read as text too) and geometry values, for the rows a read takes, decode to more than the decoded-column budget (512 MiB at least on the desktop, up to a quarter of the computer's memory and at most 3 GiB; 128 MiB in the browser) is refused with a message naming the group and the column: rewrite the file with smaller row groups. Only the rows a read takes count for text, so a view or a sample of such a file still reads (a view tested on its geometry still charges the geometry of every candidate row, and the text only of the rows it keeps), unless a page does not fit: a WKB geometry or text byte-array page of more than the budget is refused (numeric pages have no page limit), and so is a DELTA_BYTE_ARRAY or DELTA_LENGTH_BYTE_ARRAY page whose length arrays (4 bytes a value, 8 for DELTA_BYTE_ARRAY) are more than the budget has left when it is fetched, even when a sample would take one short value from it. Where the values fit the budget one by one, a refusal that names the row group's budget is met by rewriting the file with smaller row groups only when each row's values fit the budget together (otherwise reduce or split that row's values), and one that names a page by rewriting it with smaller pages or another encoding for the text column (PLAIN or dictionary). A single WKB geometry (or text value) larger than the budget by itself is not: smaller row groups or pages can't split it, so simplify the geometry or split it into several features before writing the file. | +| GeoParquet | `.parquet`, `.geoparquet` | Add Data, or upload in the web app | GeoParquet 1.x and 2.x (and earlier drafts) and Parquet files with a native `GEOMETRY` or `GEOGRAPHY` column; another major version is refused. WKB geometry, from the `geo` metadata's primary column, else a column with a native type (a notice says which when there are several), else a binary column with a usual name. The coordinate system is the native type's when the column has one: PROJJSON, `authority:code` (EPSG, ESRI, OGC), `srid:` or `projjson:`; else the `geo` metadata's. None given means longitude/latitude (OGC:CRS84). When the two differ the type's is used and a notice gives both, except that when the type's can't be read at all the metadata's is. A file that says its system is unknown (`"crs": null` or `srid:0`), or gives one RustGIS can't use, is read as longitude/latitude with a notice; when the coordinates can't be degrees, load the layer and use [Define Projection](#define-projection). Edges that follow the Earth's curve are read as straight lines, and a coordinate epoch isn't kept; a notice says each. A binary geometry column is required; plain non-spatial Parquet tables and GeoArrow-native geometry encodings aren't read by this importer. Row groups are pruned by the bbox covering. Whole reads and exports retain rows with null geometry and their attributes; extent-filtered reads exclude them because they have no location. Snappy, gzip, LZ4 and zstd compression are read, in the browser too; Brotli isn't. Text, whole-number, floating-point and true/false columns become fields, as do decimals stored as 32- or 64-bit integers (up to 18 digits), read as floating-point numbers. Columns annotated as DATE are read as dates, TIMESTAMP ones as date-times, and TIME ones as text (a time of day such as `00:00:00.000000000Z`); integers with no such annotation, whatever they hold (such as milliseconds since 1970), are read as the whole numbers they are. Other columns are left out: decimals stored as bytes (how many writers store every decimal), binary, lists, maps, structs, INT96 timestamps and further geometry columns. A notice gives how many were left out and names the first 12, each with its kind; another counts date values that couldn't be read (left empty) and date-times rounded to the microsecond, naming the first fields. A row group whose text (times of day read as text too) and geometry values, for the rows a read takes, decode to more than the decoded-column budget (512 MiB at least on the desktop, up to a quarter of the computer's memory and at most 3 GiB; 128 MiB in the browser) is refused with a message naming the group and the column: rewrite the file with smaller row groups. Only the rows a read takes count for text, so a view or a sample of such a file still reads (a view tested on its geometry still charges the geometry of every candidate row, and the text only of the rows it keeps), unless a page does not fit: a WKB geometry or text byte-array page of more than the budget is refused (numeric pages have no page limit), and so is a DELTA_BYTE_ARRAY or DELTA_LENGTH_BYTE_ARRAY page whose length arrays (4 bytes a value, 8 for DELTA_BYTE_ARRAY) are more than the budget has left when it is fetched, even when a sample would take one short value from it. Where the values fit the budget one by one, a refusal that names the row group's budget is met by rewriting the file with smaller row groups only when each row's values fit the budget together (otherwise reduce or split that row's values), and one that names a page by rewriting it with smaller pages or another encoding for the text column (PLAIN or dictionary). A single WKB geometry (or text value) larger than the budget by itself is not: smaller row groups or pages can't split it, so simplify the geometry or split it into several features before writing the file. | | FlatGeobuf | `.fgb` | Add Data, or upload | Read in place by its packed R-tree. Binary columns are left out, with a notice counting them and naming the first 12. Coordinates use the header's EPSG code, else its WKT, as a GeoPackage's system does: the WKT comes first when it gives another datum transformation than the code's, or another body's system, and a grid shift it gives beside the code isn't applied, with a notice. Another organization's code (an `ESRI` one, say) or a negative code without a WKT is read as longitude/latitude, with a notice. Another body's IAU code without a WKT is read with a notice, or refused when its coordinates are projected; with a WKT, the WKT is read (see coordinate systems of other bodies, below). | | Esri File Geodatabase | `.gdb` folder (desktop) | In Add Data pick a `.gdbtable` file inside it; or double-click the `.gdb` in the Browser, or drop the folder | The native reader loads up to 512 feature classes and tables, up to 2 GiB per table. Feature classes become layers and non-spatial tables standalone tables; dates are text. Coordinates use the EPSG/Esri code, else WKT; the WKT comes first when it gives another datum transformation than an EPSG code's, or another body's system. An Esri-only code still comes first, as ArcGIS keeps transformations apart from the system, with a notice when the WKT gives another one; a grid shift the WKT gives isn't applied, with a notice. `"layer"` picks one; `info.fileLayers` lists them. Binary fields, and geometry fields after the first, are left out, with a notice (by the table's name) counting them and naming the first 12. Multipatches become footprints with `z_min`, `z_max` and `height`; large or wall-only ones may use a convex hull. Curves become straight segments between their ends. Unreadable tables (compressed storage, raster fields or unsupported row indexes) are tried through GDAL when installed; otherwise they are named in a notice. | | Standalone tables | CSV, or any layer without geometry | Add Data | Listed under the map in Layers; join or relate them to layers. | diff --git a/docs/user-guide/loss-codes.md b/docs/user-guide/loss-codes.md index 76a65b6ed2..530cee975d 100644 --- a/docs/user-guide/loss-codes.md +++ b/docs/user-guide/loss-codes.md @@ -80,6 +80,14 @@ A coordinate system's name or definition could not be written with the data, so **What to do:** Keep the source file's coordinate system definition with the export, or export in WGS 84, which every format can name. +### `dropped.epoch` { #dropped.epoch } + +The date the coordinates are valid at (the coordinate epoch) was not kept, so positions are read as if the coordinate system did not change over time. + +**Where you see it:** adding a GeoParquet file that gives an epoch. Reading one for a catalog search or as embeddings is refused instead. + +**What to do:** Keep the source file where the epoch matters, or convert the coordinates to a system that does not move with the ground before adding them. + ### `dropped.feature` { #dropped.feature } Whole features, rows or items were left out because they could not be read or are not supported. @@ -178,9 +186,9 @@ A datum RustGIS does not shift was treated as WGS 84, so places may be a little ### `approximated.curve` { #approximated.curve } -Curves, circles or rotated boxes were drawn or written as straight segments. +Curves, circles, rotated boxes or edges that follow the Earth's curve were read, drawn or written as straight segments. -**Where you see it:** reading GML or File Geodatabase data; the Buffer tool; exporting circles and rotated boxes drawn in the session. +**Where you see it:** reading GML or File Geodatabase data, or a GeoParquet file with curved edges; the Buffer tool; exporting circles and rotated boxes drawn in the session. **What to do:** Keep the source file where exact curves matter: RustGIS draws curves as straight segments. @@ -202,7 +210,7 @@ data. The file does not say which coordinate system its coordinates are in, or says one RustGIS cannot use, so RustGIS read them as longitude and latitude (WGS 84). -**Where you see it:** reading a Shapefile with an unusable .prj file, GeoPackage, PostGIS or SQL Server data, Zarr stores and point-cloud files. +**Where you see it:** reading a Shapefile with an unusable .prj file, GeoPackage, GeoParquet, PostGIS or SQL Server data, Zarr stores and point-cloud files. **What to do:** Give the coordinate system the coordinates are in ("crs" when adding the data, or Define Projection).