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
58 changes: 48 additions & 10 deletions crates/data/src/gml.rs
Original file line number Diff line number Diff line change
Expand Up @@ -539,17 +539,22 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result<Vec<(Dataset, ReadReport)>>
continue;
}
let s = g.attribute("srsName").or_else(|| g.descendants().find_map(|d| d.attribute("srsName")));
// A system RustGIS doesn't know is said only for a geometry read in it.
let mut unknown = None;
if let Some(s) = s {
match srs(s) {
Some(found) => {
file_srs.get_or_insert(found);
}
None => unknown_srs = Some(s.to_string()),
None => unknown = Some(s.to_string()),
}
}
let (dims, lost) = (Cell::new(false), Cell::new(0));
match geometry(&g, &dims, &lost) {
Some(gm) => {
if unknown.is_some() {
unknown_srs = unknown;
}
zm = dims.get();
rings_lost += lost.get();
geom = Some(gm);
Expand Down Expand Up @@ -730,7 +735,11 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result<Vec<(Dataset, ReadReport)>>
rep.skipped = kind.skipped;

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 new notice says these features are kept without their geometry, but rep.skipped = kind.skipped on the line above still counts those same rows as skipped in the report. A caller that reads ReadReport::skipped will see the features as left out while the notice says they were kept. This line predates the PR, so I can't tell from the diff whether any caller reads it. I did not trace the consumers. The new test checks the notice and features.len(), but not rep.skipped.

Confidence: low to medium. If skipped means "rows left out", the count should be zero here, or the field should be documented as "geometry not read".

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Right that skipped here counts rows kept without their geometry, as it did before this PR; the reading corpus and other callers compare it, so changing what it means is a change of its own. Left for the release quality pass, with the field's doc comment.

if kind.skipped > 0 {
let what = if kind.skipped == 1 { "feature" } else { "features" };
rep.messages.push(format!("{}: {} {what} had geometry that couldn't be read", ds.name, kind.skipped));
// Kept, without the geometry.
rep.messages.push(crate::loss::Note::loss(
crate::loss::LossCode::DroppedGeometry,
format!("{}: {} {what} had geometry that couldn't be read", ds.name, kind.skipped),
));
}
if unplaced > 0 {
let what = if unplaced == 1 { "feature has" } else { "features have" };
Expand Down Expand Up @@ -799,9 +808,9 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result<Vec<(Dataset, ReadReport)>>
}
if unread > 0 {
let what = if unread == 1 { "property" } else { "properties" };
rep.messages.push(format!(
"{}: {unread} {what} not read: nested records, other GML values or further shapes ({unread_names})",
ds.name
rep.messages.push(crate::loss::Note::loss(
crate::loss::LossCode::DroppedValue,
format!("{}: {unread} {what} not read: nested records, other GML values or further shapes ({unread_names})", ds.name),
));
}
if kind.repeated > 0 {
Expand Down Expand Up @@ -990,7 +999,10 @@ mod tests {
// Its height is dropped, and said; so is the nested `member` property, not an attribute.
assert!(ds.zm_dropped && rep.messages.iter().any(|m| m.contains("Z or M values")), "{:?}", rep.messages);
assert!(
rep.messages.iter().any(|m| m == "n: 1 property not read: nested records, other GML values or further shapes (member)"),
rep.messages
.iter()
.any(|m| m.as_str() == "n: 1 property not read: nested records, other GML values or further shapes (member)"
&& m.loss == Some(crate::loss::LossCode::DroppedValue)),
"{:?}",
rep.messages
);
Expand Down Expand Up @@ -1123,9 +1135,8 @@ mod tests {
// The first shape is the one kept; the second is said as not read.
assert_eq!(ds.features[0].geometry, Some(Geometry::Point(Coord::new(10.0, 48.0))));
assert!(
rep.messages
.iter()
.any(|m| m == "t parks: 3 properties not read: nested records, other GML values or further shapes (owner, built, entrance)"),
rep.messages.iter().any(|m| m.as_str()
== "t parks: 3 properties not read: nested records, other GML values or further shapes (owner, built, entrance)"),
"{:?}",
rep.messages
);
Expand All @@ -1140,7 +1151,9 @@ mod tests {
let (ds, rep) = &layers[0];
assert_eq!((ds.features.len(), rep.skipped), (1, 0), "{:?}", rep.messages);
assert!(
rep.messages.iter().any(|m| m == "d: 4 properties not read: nested records, other GML values or further shapes (a, b, c, …)"),
rep.messages
.iter()
.any(|m| m.as_str() == "d: 4 properties not read: nested records, other GML values or further shapes (a, b, c, …)"),
"{:?}",
rep.messages
);
Expand Down Expand Up @@ -1424,6 +1437,31 @@ mod tests {
assert!(!said(&lossy[0], "couldn't be read") && said(&lossy[1], "t parks: 1 feature had geometry that couldn't be read"));
let clean = read("t.gml", two("<gml:Point><gml:pos>10 49</gml:pos></gml:Point>").as_bytes()).unwrap();
assert!(clean.iter().all(|l| l.1.skipped == 0 && !said(l, "couldn't be read")));
// The feature is kept, without its geometry.
assert_eq!(lossy[1].0.features.len(), 1);
let note = lossy[1].1.messages.iter().find(|m| m.contains("couldn't be read")).unwrap();
assert_eq!(note.loss, Some(crate::loss::LossCode::DroppedGeometry));
}

/// A system RustGIS doesn't know is said, as assumed, only for a geometry read in it: one that
/// names it and can't be read places nothing there.
#[test]
fn an_unknown_system_is_said_only_for_a_geometry_read_in_it() {
let member = |g: &str| doc(&format!("<wfs:member><app:roads><app:g>{g}</app:g></app:roads></wfs:member>"));
let unknown = |layers: &[(Dataset, ReadReport)]| {
layers
.iter()
.flat_map(|l| l.1.messages.iter())
.filter(|m| m.contains("unknown coordinate system"))
.map(|m| m.loss)
.collect::<Vec<_>>()
};
let read_in_it =
read("t.gml", member(r#"<gml:Point srsName="urn:x-unknown:99"><gml:pos>10 48</gml:pos></gml:Point>"#).as_bytes()).unwrap();
assert_eq!(unknown(&read_in_it), [Some(crate::loss::LossCode::AssumedCrs)]);
let failed =
read("t.gml", member(r#"<gml:Point srsName="urn:x-unknown:99"><gml:pos>bad</gml:pos></gml:Point>"#).as_bytes()).unwrap();
assert!(unknown(&failed).is_empty(), "{:?}", failed[0].1.messages);
}

/// #1620: unread property names come in document order, and a `gml:description` value is no shape.
Expand Down
53 changes: 48 additions & 5 deletions crates/data/src/gpx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,8 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result<Vec<(Dataset, ReadReport)>>
}
let mut skipped = 0usize;
let mut short_segments = 0usize;
// Route points without usable coordinates: vertices left out of their route, not features.
let mut route_points = 0usize;
let point_fields = |extra: &[(&str, FieldType)]| {
let mut f: Vec<Field> = extra.iter().map(|(n, t)| Field::new(*n, *t)).collect();
f.extend(["name", "ele", "time", "desc", "cmt", "sym", "type"].iter().map(|n| Field::new(*n, FieldType::Text)));
Expand Down Expand Up @@ -110,17 +112,19 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result<Vec<(Dataset, ReadReport)>>
};
let mut routes = Dataset::new(format!("{name} routes"), GeometryType::Polyline, line_fields());
for r in children(&gpx, "rte") {
let mut pts = Vec::new();
let (mut pts, mut unplaced) = (Vec::new(), 0usize);
for p in children(&r, "rtept") {
match coord(&p) {
Some(c) => pts.push(c),
None => skipped += 1,
None => unplaced += 1,
}
}
let n = pts.len();
if n >= 2 {
routes.push_next(Some(Geometry::Line(vec![pts])), line_attrs(&r, n));
route_points += unplaced;
} else {
// Left out whole, said with the routes; its points aren't also a kept route's loss.
skipped += 1;
}
}
Expand Down Expand Up @@ -196,11 +200,29 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result<Vec<(Dataset, ReadReport)>>
} else {
("segments", "were left out of tracks; their points remain in track points")
};
report.messages.push(format!("{name}: {short_segments} GPX track {segment} with fewer than two usable points {action}"));
report.messages.push(crate::loss::Note::loss(
crate::loss::LossCode::DroppedGeometry,
format!("{name}: {short_segments} GPX track {segment} with fewer than two usable points {action}"),
));
}
if route_points > 0 {
let what = if route_points == 1 {
"point without usable coordinates was left out of its route"
} else {
"points without usable coordinates were left out of their routes"
};
report
.messages
.push(crate::loss::Note::loss(crate::loss::LossCode::DroppedGeometry, format!("{name}: {route_points} GPX route {what}")));
}
report.skipped = skipped;
if skipped > 0 {
report.messages.push(format!("{name}: {skipped} points, routes or tracks without usable geometry were skipped"));
let what = if skipped == 1 {
"point, route or track without usable geometry was skipped"
} else {
"points, routes or tracks without usable geometry were skipped"
};
report.messages.push(crate::loss::Note::loss(crate::loss::LossCode::DroppedFeature, format!("{name}: {skipped} {what}")));
}
}
if out.is_empty() {
Expand All @@ -224,9 +246,10 @@ mod tests {
assert_eq!(layers[1].0.features[2].geometry, Some(Geometry::Point(Coord::new(6.0, 5.0))));
assert_eq!(layers[1].0.value(2, 1), &Value::Int(2));
assert_eq!(
layers[0].1.messages,
layers[0].1.messages.texts().collect::<Vec<_>>(),
["a: 1 GPX track segment with fewer than two usable points was left out of tracks; its point remains in track points"]
);
assert_eq!(layers[0].1.messages[0].loss, Some(crate::loss::LossCode::DroppedGeometry));
assert!(layers[1].1.messages.is_empty());
let clean =
read("a.gpx", br#"<gpx><trk><trkseg><trkpt lat="1" lon="2"/><trkpt lat="3" lon="4"/></trkseg><trkseg/></trk></gpx>"#).unwrap();
Expand All @@ -245,6 +268,26 @@ mod tests {
</trk>
</gpx>"#;

/// A route point without usable coordinates is left out of a route that is kept: its geometry
/// lost a vertex, said apart from the points, routes and tracks left out whole.
#[test]
fn a_route_point_without_coordinates_is_a_vertex_left_out() {
let xml = br#"<gpx><rte><name>kept</name><rtept lat="1" lon="1"/><rtept lat="x" lon="1"/><rtept lat="2" lon="2"/></rte><wpt lat="91" lon="2"/></gpx>"#;
let layers = read("a.gpx", xml).unwrap();
let (routes, _) = layers.iter().find(|(d, _)| d.name == "a routes").unwrap();
assert_eq!(routes.features.len(), 1);
let report = &layers[0].1;
assert_eq!(report.skipped, 1, "only the waypoint off the globe is a feature left out");
let said: Vec<_> = report.messages.iter().map(|m| (m.as_str(), m.loss)).collect();
assert_eq!(
said,
[
("a: 1 GPX route point without usable coordinates was left out of its route", Some(crate::loss::LossCode::DroppedGeometry)),
("a: 1 point, route or track without usable geometry was skipped", Some(crate::loss::LossCode::DroppedFeature)),
]
);
}

#[test]
fn splits_into_layers() {
let layers = read("run.gpx", GPX.as_bytes()).unwrap();
Expand Down
60 changes: 47 additions & 13 deletions crates/data/src/kml.rs
Original file line number Diff line number Diff line change
Expand Up @@ -355,20 +355,23 @@ impl GeometryLosses {

/// Emits one counted notice per kind, only for nonzero totals.
fn report(&self, name: &str, report: &mut ReadReport) {
for (count, one, many) in [
(self.unreadable.get(), "unreadable KML coordinate tuple", "unreadable KML coordinate tuples"),
(self.holes, "unreadable KML polygon hole", "unreadable KML polygon holes"),
use crate::loss::LossCode::{DroppedGeometry, DroppedRing};
// Each is a part left out of a kept placemark's geometry.
for (count, one, many, code) in [
(self.unreadable.get(), "unreadable KML coordinate tuple", "unreadable KML coordinate tuples", DroppedGeometry),
(self.holes, "unreadable KML polygon hole", "unreadable KML polygon holes", DroppedRing),
(
self.short_lines,
"KML line part with fewer than two usable coordinates",
"KML line parts with fewer than two usable coordinates",
DroppedGeometry,
),
(self.excess_points, "excess KML Point coordinate tuple", "excess KML Point coordinate tuples"),
(self.polygons, "KML polygon without a usable outer ring", "KML polygons without a usable outer ring"),
(self.excess_points, "excess KML Point coordinate tuple", "excess KML Point coordinate tuples", DroppedGeometry),
(self.polygons, "KML polygon without a usable outer ring", "KML polygons without a usable outer ring", DroppedGeometry),
] {
if count > 0 {
let (subject, verb) = if count == 1 { (one, "was") } else { (many, "were") };
report.messages.push(format!("{name}: {count} {subject} {verb} left out"));
report.messages.push(crate::loss::Note::loss(code, format!("{name}: {count} {subject} {verb} left out")));
}
}
}
Expand Down Expand Up @@ -583,7 +586,9 @@ impl Reader {
for g in pm.children().filter(|c| c.is_element()) {
geometry(&g, &mut parts, 0);
}
self.geometry_losses.add(&parts.losses);
// A placemark left out whole is said as one; only a kept one's parts left out are its
// geometry's loss.
let losses = std::mem::take(&mut parts.losses);
let mut data = Vec::new();
let mut seen = HashSet::new();
let mut duplicates = 0usize;
Expand Down Expand Up @@ -646,6 +651,9 @@ impl Reader {
if !parts.polygons.is_empty() {
push(Geometry::Polygon(parts.polygons), &parts.zm[2], &mut self.rows);
}
if any {
self.geometry_losses.add(&losses);
}
if !any {
self.skipped += 1;
} else if duplicates > 0 {
Expand Down Expand Up @@ -733,9 +741,12 @@ impl Reader {
));
}
if self.duplicate_entries > 0 {
report.messages.push(format!(
"{name}: {} repeated ExtendedData entries in {} placemarks were left out",
self.duplicate_entries, self.duplicate_placemarks
report.messages.push(crate::loss::Note::loss(
crate::loss::LossCode::DroppedValue,
format!(
"{name}: {} repeated ExtendedData entries in {} placemarks were left out",
self.duplicate_entries, self.duplicate_placemarks
),
));
}
if self.dropped_keys > 0 {
Expand Down Expand Up @@ -800,13 +811,16 @@ mod tests {
assert_eq!(layers[0].dataset.features[0].attrs[0], Value::Text("kept".into()));
assert!(!layers[0].dataset.zm_dropped, "discarded rings do not set a retained point's altitude flag");
assert_eq!(
layers[0].report.messages,
layers[0].report.messages.texts().collect::<Vec<_>>(),
[
"a: 2 unreadable KML coordinate tuples were left out",
"a: 1 unreadable KML polygon hole was left out",
"a: 2 KML polygons without a usable outer ring were left out"
]
);
use crate::loss::LossCode::{DroppedGeometry, DroppedRing};
let codes: Vec<_> = layers[0].report.messages.iter().map(|m| m.loss).collect();
assert_eq!(codes, [Some(DroppedGeometry), Some(DroppedRing), Some(DroppedGeometry)]);
for clean in [
"<Polygon/>",
"<Polygon><outerBoundaryIs><LinearRing><coordinates> </coordinates></LinearRing></outerBoundaryIs><innerBoundaryIs/><innerBoundaryIs><LinearRing><coordinates> </coordinates></LinearRing></innerBoundaryIs></Polygon>",
Expand All @@ -830,7 +844,7 @@ mod tests {
);
assert!(layers.iter().all(|l| !l.dataset.zm_dropped && l.dataset.features[0].attrs[0] == Value::Text("kept".into())));
assert_eq!(
layers[0].report.messages,
layers[0].report.messages.texts().collect::<Vec<_>>(),
[
"a: 2 unreadable KML coordinate tuples were left out",
"a: 2 KML line parts with fewer than two usable coordinates were left out"
Expand All @@ -852,6 +866,19 @@ mod tests {
}
}

/// A placemark left out whole is said once, as one: the parts of it that couldn't be read
/// aren't also a kept placemark's geometry loss.
#[test]
fn a_placemark_left_out_whole_is_said_once() {
let layers = read(
"a.kml",
br#"<kml><Placemark><LineString><coordinates>x,y 1,2</coordinates></LineString></Placemark><Placemark><Point><coordinates>1,2</coordinates></Point></Placemark></kml>"#,
)
.unwrap();
let said: Vec<_> = layers.iter().flat_map(|l| l.report.messages.iter().map(|m| (m.as_str(), m.loss))).collect();
assert_eq!(said, [("a: 1 placemarks without a geometry RustGIS draws were skipped", Some(crate::loss::LossCode::DroppedFeature))]);
}

#[test]
fn xml_loss_partial_geometry_losses_are_counted() {
let xml = br#"<kml><Placemark><name>kept</name><MultiGeometry>
Expand Down Expand Up @@ -890,6 +917,9 @@ mod tests {
"a: 2 excess KML Point coordinate tuples were left out"
]
);
use crate::loss::LossCode::{DroppedGeometry, DroppedRing};
let codes: Vec<_> = layers.iter().flat_map(|l| l.report.messages.iter().map(|m| m.loss)).collect();
assert_eq!(codes, [Some(DroppedGeometry), Some(DroppedRing), Some(DroppedGeometry), Some(DroppedGeometry)]);
}
let clean = read("a.kml", br#"<kml><Placemark><MultiGeometry><Point><coordinates>1,2</coordinates></Point><LineString/><LineString><coordinates> </coordinates></LineString><Polygon><outerBoundaryIs><LinearRing><coordinates>0,0 4,0 4,4 0,0</coordinates></LinearRing></outerBoundaryIs><innerBoundaryIs/><innerBoundaryIs><LinearRing><coordinates> </coordinates></LinearRing></innerBoundaryIs></Polygon></MultiGeometry></Placemark></kml>"#).unwrap();
assert!(clean[0].report.messages.is_empty());
Expand Down Expand Up @@ -949,7 +979,11 @@ mod tests {
let layers = read("duplicates.kml", xml.as_bytes()).unwrap();
assert_eq!(layers.len(), 2);
let messages: Vec<_> = layers.iter().flat_map(|l| &l.report.messages).collect();
assert_eq!(messages, ["duplicates: 4 repeated ExtendedData entries in 2 placemarks were left out"]);
assert_eq!(
messages.iter().map(|m| m.as_str()).collect::<Vec<_>>(),
["duplicates: 4 repeated ExtendedData entries in 2 placemarks were left out"]
);
assert_eq!(messages[0].loss, Some(crate::loss::LossCode::DroppedValue));
for layer in &layers {
let ds = &layer.dataset;
assert_eq!(ds.value(0, ds.field_index("n").unwrap()), &Value::Int(0));
Expand Down
Loading
Loading