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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion crates/data/src/export/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -375,9 +375,11 @@ fn a_layer_without_a_declared_type_takes_its_first_geometrys() {
points.push_next(Some(Geometry::Point(Coord::new(i as f64, 2.0))), vec![Value::Int(i)]);
}
let layer = Dataset::new("points", GeometryType::None, points.fields.clone());
write_chunks_in(&Runs::new(&points, 2), &layer, &d.join("points.csv"), Crs::LonLat, 1).unwrap();
let e = write_chunks_in(&Runs::new(&points, 2), &layer, &d.join("points.csv"), Crs::LonLat, 1).unwrap();
let text = std::fs::read_to_string(d.join("points.csv")).unwrap();
assert!(text.starts_with("longitude,latitude,n"), "{text}");
// The export says so, for the notice of the system its columns are in (`share.exportLayer`).
assert!(e.csv.points);
}

/// Rows a source couldn't read are counted, so an export can say how many it left out; a clean
Expand Down
34 changes: 25 additions & 9 deletions crates/data/src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4577,6 +4577,12 @@ pub struct CsvLosses {
impl CsvLosses {
/// The losses of `features` in a layer of type `gt`; a streamed export adds up its chunks'.
pub fn of(features: &[crate::Feature], gt: GeometryType, fields: &[Field]) -> Result<Self> {
Self::of_placed(features, gt, fields, &|c| Some(c))
}

/// As [`CsvLosses::of`], for features whose points are written where `place` puts them (in
/// another system): only the points are converted, not the features.
fn of_placed(features: &[crate::Feature], gt: GeometryType, fields: &[Field], place: &dyn Fn(Coord) -> Option<Coord>) -> Result<Self> {
let mut out = Self { points: gt == GeometryType::Point, guarded: vec![0; fields.len()], ..Self::default() };
for feature in features {
crate::progress::check()?;
Expand All @@ -4585,7 +4591,7 @@ impl CsvLosses {
}
let geometry = feature.geometry.as_ref();
let point = if out.points { geometry.and_then(Geometry::label_point) } else { None };
if out.points && !point.is_some_and(usable_degree_point) {
if out.points && !point.and_then(place).is_some_and(usable_degree_point) {
out.unusable_points += 1;
}
let Some(g) = geometry else { continue };
Expand Down Expand Up @@ -4651,8 +4657,15 @@ impl CsvLosses {
let [x, y] = csv_projected_names(fields);
let target: String = target.chars().map(dbf_notice_char).collect();
return (x != "x" && x != "easting" || y != "y" && y != "northing").then(|| {
// The names that moved the columns: each axis's two, when both are taken.
let names: Vec<String> = [(x != "x" && x != "easting", ["x", "easting"]), (y != "y" && y != "northing", ["y", "northing"])]
.into_iter()
.filter(|(moved, _)| *moved)
.flat_map(|(_, names)| names.map(|n| format!("'{n}'")))
.collect();
format!(
"{target}: the fields have the names 'x', 'y', 'easting' and 'northing', so the coordinates are in columns '{}' and '{}'; pick those columns when adding the file back",
"{target}: the fields have the names {}, so the coordinates are in columns '{}' and '{}'; pick those columns when adding the file back",
names.join(" and ").replacen(" and ", ", ", names.len().saturating_sub(2)),
dbf_notice_name(&x),
dbf_notice_name(&y)
)
Expand Down Expand Up @@ -4982,15 +4995,18 @@ pub fn export_losses_notes(ds: &Dataset, ext: &str, name_field: Option<usize>, t
pub fn export_losses_notes_in(ds: &Dataset, ext: &str, name_field: Option<usize>, target: &str, crs: Crs) -> Result<Vec<String>> {
let mut notes = match ext {
"csv" => {
// Of the coordinates the file is written in: longitude/latitude, or another system's.
let ds = if crs == Crs::LonLat {
ds.in_lonlat().map_err(DataError::of_conversion)?
} else if crs == ds.coord_crs() {
std::borrow::Cow::Borrowed(ds)
// Of the coordinates the file is written in: longitude/latitude, or another
// geographic system's, whose points alone are converted to be checked (no copy of the

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The comment says a projected system's coordinates "aren't checked as such", but the projected branch (else at line 5007) still calls CsvLosses::of on the native coordinates, so they are checked as degrees. The result is never read for a projected target: coordinates_note_in returns before using unusable_points when !crs.is_geographic(), and notes() doesn't read it either. So the pass is wasted work and the comment misstates what happens. Suggest rewording the comment to say the count is not used for projected targets, or skipping the degree check on that path.

Category: quality

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Left for the release quality pass.

// layer); a projected system's aren't degrees, so aren't checked as such.
let losses = if crs == Crs::LonLat {
let ds = ds.in_lonlat().map_err(DataError::of_conversion)?;
CsvLosses::of(&ds.features, ds.geometry_type, &ds.fields)?
} else if crs.is_geographic() && crs != ds.coord_crs() {
let to = ds.coord_crs().to(crs).map_err(DataError::Format)?;
CsvLosses::of_placed(&ds.features, ds.geometry_type, &ds.fields, &|c| to.point(c))?
} else {
std::borrow::Cow::Owned(project(ds, crs)?)
CsvLosses::of(&ds.features, ds.geometry_type, &ds.fields)?
};
let losses = CsvLosses::of(&ds.features, ds.geometry_type, &ds.fields)?;
let mut notes = losses.notes(&ds.fields, target);
notes.extend(losses.coordinates_note_in(&ds.fields, target, crs));
notes
Expand Down
15 changes: 14 additions & 1 deletion crates/data/src/source/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3239,7 +3239,20 @@ fn a_csv_export_takes_x_and_y_in_a_system_asked_for() {
}
assert!(crate::io::to_csv_in(&every, lv95).unwrap().starts_with("x_1,y_1,"));
let notes = crate::io::export_losses_notes_in(&every, "csv", None, "xy.csv", lv95).unwrap();
assert!(notes.iter().any(|n| n.contains("'x_1' and 'y_1'")), "{notes:?}");
assert!(notes.iter().any(|n| n.contains("'x', 'easting', 'y' and 'northing'") && n.contains("'x_1' and 'y_1'")), "{notes:?}");
// Each axis on its own: 'x' and 'easting' taken move only the x column, and only those two
// names are said.
let mut one =
Dataset::new("one", GeometryType::Point, vec![Field::new("x", FieldType::Integer), Field::new("easting", FieldType::Integer)]);
one.push(Some(Geometry::Point(Coord::new(2_600_000.0, 1_200_000.0))), vec![Value::Int(1), Value::Int(2)]);
one.crs = Some(lv95);
one.held_in = lv95;
assert!(crate::io::to_csv_in(&one, lv95).unwrap().starts_with("x_1,y,x,easting\n"));
let notes = crate::io::export_losses_notes_in(&one, "csv", None, "one.csv", lv95).unwrap();
assert!(
notes.iter().any(|n| n.contains("the names 'x' and 'easting', so") && n.contains("'x_1' and 'y'") && !n.contains("northing")),
"{notes:?}"
);
// Into a geographic system other than WGS 84: longitude and latitude columns, and no note
// of unusable positions, which are counted on the coordinates written.
// Fields named x and y are a pair reading could take instead, which a note names when rows
Expand Down
19 changes: 14 additions & 5 deletions crates/engine/src/cmd/publish.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,11 +62,20 @@ pub(crate) fn publish_work(s: &Session, p: &Value) -> Result<super::exports::Wor
let (synced, path, dataset, instance, name) =
(synced.clone(), path.to_string(), l.dataset.clone(), l.instance_id(), l.name.clone());
Ok(Box::new(move || {
// Both kinds of digest, before anything is written: the record the publish makes may
// keep the other kind (an older release's record kept no native one), and Cancel must
// not leave a written file without its record.
let (lonlat_rows, native_rows) = rustgis_data::sync::digests(&dataset).map_err(|e| e.to_string())?;
let of_kind = |native: bool| if native { native_rows } else { Some(lonlat_rows) };
// The digests the record needs, before anything is written, so Cancel can't leave a
// written file without its record. A layer held in its own system is hashed as held
// (no conversion), and in longitude/latitude too only when its record is of that kind
// (an older release's kept no native one), in the same pass. A record of a kind not
// hashed here (a held layer read back in longitude/latitude) differs, so the layer
// takes what was read back: refreshed, never out of step.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The later comment (lines 128-129, which is outside this diff hunk) says the new record's digest is "hashed above", but in this else branch (a layer held in its own system, with a native record) only the native digest is computed. If published.native is None (the file reads back in longitude/latitude), of_kind(false) is None, so held is always Some and the layer is refreshed to the read-back, changing its held_in, where before the digests could match and it kept its system. I think this is unreachable in practice (GeoJSON sources aren't projected at read, and shapefile publishes read back in the file's system), so this is mainly a comment fix. Suggest saying that the comparison is skipped in this branch and why the refresh is safe.

Category: quality

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Left for the release quality pass.

let err = |e: rustgis_data::DataError| e.to_string();
let (lonlat_rows, native_rows) = if synced.native.is_none() || dataset.coord_crs() == rustgis_data::raster::Crs::LonLat {
let (rows, native) = rustgis_data::sync::digests(&dataset).map_err(err)?;
(Some(rows), native)
} else {
(None, Some(rustgis_data::sync::native_digest(&dataset).map_err(err)?))
};
let of_kind = |native: bool| if native { native_rows } else { lonlat_rows };
let rows = of_kind(synced.native.is_some());
let features = dataset.features.len();
if rows == Some(synced.digest()) {
Expand Down
7 changes: 6 additions & 1 deletion crates/engine/src/cmd/share.rs
Original file line number Diff line number Diff line change
Expand Up @@ -713,11 +713,15 @@ fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option<Crs>, gpkg: Gpk
return Err(format!("{path}: {e}"));
}
let parquet = matches!(ext.as_str(), "parquet" | "geoparquet");
// Whether a CSV has coordinate columns: a streamed layer that declares no type takes its
// first geometry's, which the chunks written say.
let mut csv_points = ds.geometry_type == rustgis_data::GeometryType::Point;
let (written, left_out, skipped, table, unfit, null_numbers, moved, format_notes, dates) = match &chunks {
Some((src, layer)) => {
let (e, table) = rustgis_data::export::write_source_filtered(src.as_ref(), layer, Path::new(&path), crs, &gpkg, query)
.map_err(|e| e.to_string())?;
query_report = e.query;
csv_points |= e.csv.points;
// Counted as the chunks were written, as the layer holds none of them.
let unfit = rustgis_data::source::parquet::unfit_note(&layer.fields, &e.unfit, path);
let moved = rustgis_data::web_mercator_moved_note(path, &layer.name, e.beyond_web_mercator);
Expand Down Expand Up @@ -774,7 +778,8 @@ fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option<Crs>, gpkg: Gpk
if asked.is_none() {
notes.extend(rustgis_data::io::default_export_note(ds, path));
}
notes.extend(rustgis_data::io::csv_system_note(path, ds.geometry_type, crs));
let csv_type = if csv_points { rustgis_data::GeometryType::Point } else { ds.geometry_type };
notes.extend(rustgis_data::io::csv_system_note(path, csv_type, crs));
notes.extend(moved);
// A Shapefile (`.shp`, or zipped to `.zip`) cuts field names to dBase's.
let shapefile = matches!(ext.as_str(), "shp" | "zip");
Expand Down
8 changes: 4 additions & 4 deletions docs/user-guide/data-formats.md
Original file line number Diff line number Diff line change
Expand Up @@ -722,10 +722,10 @@ coordinates for degrees. A layer made in RustGIS defaults to WGS 84.
another, such as `{"layer": "Parcels", "path": "parcels.gpkg", "crs": "EPSG:4647"}`. GeoJSON, KML
and GPX are always written in WGS 84. CSV is written in WGS 84 (`longitude` and `latitude`) unless
a `"crs"` is given: a point layer's coordinates are then written in that system, in `longitude`
and `latitude` columns for a geographic one, and for a projected one in `x` and `y`, or `easting`
and `northing` when fields have the names `x` or `y`, or `x_1` and `y_1` when fields have all
four. A notice says which system it is, since a CSV file can't; give the same system when adding
the file back.
and `latitude` columns for a geographic one, and for a projected one in an x and a y column. Each
takes the first name no field has: `x`, then `easting`, then `x_1`, `x_2` and so on, and `y`, then
`northing`, then `y_1` and so on. A notice says which system it is, since a CSV file can't; give
the same system when adding the file back.

RustGIS keeps x and y only. When a source has Z or M values (heights or measures), adding it says
they were dropped, and exporting or converting the layer (or exporting a standalone table that
Expand Down
Loading