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
105 changes: 92 additions & 13 deletions crates/analysis/src/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ pub struct Route {
pub rows: Vec<usize>,
/// Segments omitted because an endpoint has non-finite coordinates or an invalid latitude.
pub skipped_segments: usize,
/// Lines closed because their cost times a segment's length is past the largest number.
pub overflowing: usize,
}

#[derive(PartialEq)]
Expand Down Expand Up @@ -46,13 +48,43 @@ struct Network {
adj: Vec<Vec<Edge>>,
segs: Vec<Segment>,
skipped_segments: usize,
/// Lines whose cost times a segment's length is past the largest number: closed, as a
/// search would never take an edge of infinite cost.
overflowing: usize,
}

/// Whether a segment of a line in `parts` costs no finite number at `weight` a metre. Segments
/// left out for their coordinates don't count. It looks at Cancel as `build` does, every 4096
/// segments measured.
fn cost_overflows(parts: &[Vec<Coord>], weight: f64, pace: &mut crate::control::Pace) -> Result<bool, String> {
// No segment is longer than half the Earth's circumference: a weight finite at that length
// is finite on every segment, so the segments are measured only past it.
if (weight * 2.1e7).is_finite() {
return Ok(false);
}
for w in parts.iter().flat_map(|part| part.windows(2)) {
if pace.stop(4096) {
return Err(crate::control::Cancelled.into());
}
if let (Some(a), Some(b)) = (w.first(), w.get(1))
&& a.is_finite()
&& b.is_finite()
&& a.y.abs() <= 90.0
&& b.y.abs() <= 90.0
&& !(wgs84_distance_m(*a, *b) * weight).is_finite()
{
return Ok(true);
}
}
Ok(false)
}

impl Network {
/// Builds edges in source order, preserving shortest-path tie breaking and arithmetic.
fn build(ds: &Dataset, rows: &[usize], cost_field: Option<usize>) -> Result<Self, String> {
let route_error = |reason, skipped| route_error(ds, reason, skipped);
let route_error = |reason, skipped, overflowing| route_error(ds, reason, skipped, overflowing);
let mut skipped_segments = 0;
let mut overflowing = 0;
let mut ids: HashMap<(i64, i64), usize> = HashMap::new();
let mut nodes: Vec<Coord> = Vec::new();
let mut adj: Vec<Vec<Edge>> = Vec::new();
Expand All @@ -77,6 +109,10 @@ impl Network {
Some(Some(_)) => continue,
Comment thread
giswqs marked this conversation as resolved.
Resolved
_ => 1.0,
};
if cost_overflows(parts, weight, &mut pace)? {
overflowing += 1;
continue;
}
for part in parts {
for w in part.windows(2) {
if pace.stop(4096) {
Expand All @@ -100,16 +136,16 @@ impl Network {
segs.push((ia, ib, weight, *r));
// Checked per segment, so one huge feature can't grow the network unbounded.
if segs.len() > 10_000_000 || nodes.len() > 5_000_000 {
return Err(route_error("the network is too large".into(), skipped_segments));
return Err(route_error("the network is too large".into(), skipped_segments, overflowing));
}
}
}
}
if segs.is_empty() && skipped_segments > 0 {
return Err(route_error("no usable network remains".into(), skipped_segments));
return Err(route_error("no usable network remains".into(), skipped_segments, overflowing));
}
crate::control::finish();
Ok(Self { nodes, adj, segs, skipped_segments })
Ok(Self { nodes, adj, segs, skipped_segments, overflowing })
}

/// Heap storage retained by the cache, including spare capacity in every adjacency list.
Expand Down Expand Up @@ -179,13 +215,20 @@ fn network_keyed(
Ok(graph)
}

/// Preserve clean-network errors; failed partial routes must still disclose omissions.
fn route_error(ds: &Dataset, reason: String, skipped_segments: usize) -> String {
if skipped_segments == 0 {
reason
} else {
format!("{reason}; {skipped_segments} segments with invalid coordinates were omitted from '{}'", ds.name)
/// Preserve clean-network errors; failed partial routes must still disclose omissions: segments
/// with invalid coordinates and lines closed for a cost past the largest number.
fn route_error(ds: &Dataset, reason: String, skipped_segments: usize, overflowing: usize) -> String {
let mut said = reason;
if skipped_segments > 0 {
said.push_str(&format!("; {skipped_segments} segments with invalid coordinates were omitted from '{}'", ds.name));
}
if overflowing > 0 {
said.push_str(&format!(
"; {overflowing} line(s) of '{}' cost so much that a segment's cost is past the largest number, and were closed",
ds.name
));
}
said
}

/// The shortest route between two points over the lines of `rows`, joining where vertices
Expand Down Expand Up @@ -332,7 +375,7 @@ fn route_on(graph: &Network, ds: &Dataset, from: Coord, to: Coord, snap_m: f64)
let mut adj = graph.adj.clone();
let segs = &graph.segs;
let skipped_segments = graph.skipped_segments;
let route_error = |reason, skipped| route_error(ds, reason, skipped);
let route_error = |reason, skipped| route_error(ds, reason, skipped, graph.overflowing);
let nearest = |p: Coord, nodes: &[Coord]| nearest_segment(segs, nodes, p, None);
// Each end becomes a node on its segment, joined to the segment's two ends.
let attach = |p: Coord, nodes: &mut Vec<Coord>, adj: &mut Vec<Vec<Edge>>| -> Result<(usize, usize, f64), String> {
Expand Down Expand Up @@ -383,6 +426,7 @@ fn route_on(graph: &Network, ds: &Dataset, from: Coord, to: Coord, snap_m: f64)
let mut dist = vec![f64::INFINITY; n];
let mut prev: Vec<Option<(usize, f64, usize)>> = vec![None; n];
let mut heap = BinaryHeap::new();
let mut summed_past = false;
if let Some(d) = dist.get_mut(s) {
*d = 0.0;
}
Expand All @@ -405,6 +449,9 @@ fn route_on(graph: &Network, ds: &Dataset, from: Coord, to: Coord, snap_m: f64)
return Err(crate::control::Cancelled.into());
}
let nd = d + c;
// Each edge's cost is finite, but a path's sum of them can pass the largest number:
// never taken, and said if the route then has none.
summed_past |= c.is_finite() && !nd.is_finite();
if nd < dist.get(v).copied().unwrap_or(f64::INFINITY) {
if let Some(x) = dist.get_mut(v) {
*x = nd;
Expand All @@ -418,7 +465,14 @@ fn route_on(graph: &Network, ds: &Dataset, from: Coord, to: Coord, snap_m: f64)
}
let cost = dist.get(t).copied().unwrap_or(f64::INFINITY);
if !cost.is_finite() {
return Err(route_error("the two points aren't connected by the network".into(), skipped_segments));
// A sum past the largest number seen anywhere in the search may or may not be on the
// way to the target: both are said.
let why = if summed_past {
"the two points aren't joined by a route whose costs stay within the largest number: the costs along the network add up past it, or they aren't connected (give the lines smaller costs)"
} else {
"the two points aren't connected by the network"
};
return Err(route_error(why.into(), skipped_segments));
}
let mut path = Vec::new();
let mut length = 0.0;
Expand All @@ -438,7 +492,7 @@ fn route_on(graph: &Network, ds: &Dataset, from: Coord, to: Coord, snap_m: f64)
used.reverse();
used.dedup();
crate::control::finish();
Ok(Route { path, length_m: length, cost, rows: used, skipped_segments })
Ok(Route { path, length_m: length, cost, rows: used, skipped_segments, overflowing: graph.overflowing })
Comment thread
giswqs marked this conversation as resolved.
Resolved
}

// ---------------------------------------------------------------------------------------------
Expand Down Expand Up @@ -489,6 +543,12 @@ impl Graph {
self.0.skipped_segments
}

/// Lines left out of the network as their cost times a segment's length is past the largest
/// number.
pub(crate) fn overflowing(&self) -> usize {
self.0.overflowing
}

/// Segment `i`, in the order the lines and their vertices were read; None past the last.
pub(crate) fn segment(&self, i: usize) -> Option<SegmentInfo> {
let &(a, b, weight, row) = self.0.segs.get(i)?;
Expand Down Expand Up @@ -1515,6 +1575,25 @@ mod tests {
let cheap =
shortest_route(&ds, &rows, Coord::new(0.0, 0.0), Coord::new(1.0, 1.0), Some(0), 1000.0).unwrap_or_else(|e| panic!("{e}"));
assert_eq!(cheap.rows, vec![0, 1], "by cost the two sides win");
assert_eq!((short.overflowing, cheap.overflowing), (0, 0));
// A cost whose segments' costs overflow closes its line, and the route says so.
let mut huge = Dataset::new("roads", GeometryType::Polyline, vec![Field::new("cost", FieldType::Double)]);
huge.push(l((0.0, 0.0), (1.0, 0.0)), vec![Value::Float(1.0)]);
huge.push(l((1.0, 0.0), (1.0, 1.0)), vec![Value::Float(1.0)]);
huge.push(l((0.0, 0.0), (1.0, 1.0)), vec![Value::Float(1e306)]);
let around =
shortest_route(&huge, &rows, Coord::new(0.0, 0.0), Coord::new(1.0, 1.0), Some(0), 1000.0).unwrap_or_else(|e| panic!("{e}"));
assert_eq!((around.rows, around.overflowing), (vec![0, 1], 1));
// Each edge finite, their sum past the largest number: said, not "not connected".
let mut summed = Dataset::new("roads", GeometryType::Polyline, vec![Field::new("cost", FieldType::Double)]);
let two = vec![Coord::new(0.0, 0.0), Coord::new(0.00001, 0.0), Coord::new(0.00002, 0.0)];
summed.push(Some(Geometry::Line(vec![two])), vec![Value::Float(1e308)]);
let e = shortest_route(&summed, &[0], Coord::new(0.0, 0.0), Coord::new(0.00002, 0.0), Some(0), 1000.0).unwrap_err();
assert!(e.contains("add up past it"), "{e}");
// The same beside a target on a line of its own: either may be why, so both are said.
summed.push(Some(Geometry::Line(vec![vec![Coord::new(1.0, 1.0), Coord::new(1.001, 1.0)]])), vec![Value::Float(1.0)]);
let e = shortest_route(&summed, &[0, 1], Coord::new(0.0, 0.0), Coord::new(1.001, 1.0), Some(0), 1000.0).unwrap_err();
assert!(e.contains("add up past it, or they aren't connected"), "{e}");
assert!(shortest_route(&ds, &rows, Coord::new(5.0, 5.0), Coord::new(1.0, 1.0), None, 1000.0).is_err());
let mut poly = Dataset::new("p", GeometryType::Polygon, vec![]);
poly.push(
Expand Down
20 changes: 13 additions & 7 deletions crates/analysis/src/tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1957,9 +1957,9 @@ impl MaskCache {
/// coordinates while the masks are unioned, then twice the largest input feature's, a list of
/// the masks (or the index's references to them), and the larger of the largest mask and the
/// largest size of the masks one feature meets, together (found for each batch first, standing
/// for their union); the threads are as many as half the scratch
/// memory work may take holds of that, and their recent unions of several masks share
/// `cache_bytes` (by default the other half of [`crate::parallel::scratch_budget`]).
/// for their union); as many threads run as fit, at that much work each, in half the scratch
/// budget, and their recent unions of several masks share `cache_bytes` (by default the other
/// half of [`crate::parallel::scratch_budget`]).
fn clip_on(inp: &dyn Inputs, p: &Json, threads: Option<usize>, cache_bytes: Option<usize>) -> Result<ToolResult, String> {
let ds = input(inp, p, "input")?;
let clip_ds = input(inp, p, "clip")?;
Expand Down Expand Up @@ -4936,8 +4936,8 @@ fn merge_coincident(mut points: Vec<(Coord, f64)>) -> Result<Vec<(Coord, f64)>,
Ok(kept.into_iter().map(|(c, sum, count)| (c, sum / count as f64)).collect())
}

/// The cell [`merge_coincident`] files a coordinate `v` under: below 2^24, which 4e-9 of the
/// axis, numbered from zero (under 2^53, an i64 exactly); from 2^24 on, the coordinate's own bits,
/// The cell [`merge_coincident`] files a coordinate `v` under: below 2^24, the index of its
/// 4e-9-wide cell, numbered from zero (under 2^53, an i64 exactly); from 2^24 on, the coordinate's own bits,
/// whose magnitude (an exponent of 24 or more) is past 2^60, beyond every number below.
fn coincident_cell(v: f64) -> i64 {
const CELL: f64 = 4e-9;
Expand Down Expand Up @@ -6620,7 +6620,13 @@ fn tabulate_intersection(inp: &dyn Inputs, p: &Json) -> Result<ToolResult, Strin
let mut row = zone.key.clone();
row.extend(class.key.iter().cloned());
if let Some(message) = rustgis_data::ambiguous_area_message(std::iter::once(covered)) {
return Err(format!("Tabulate Intersection: {message}"));
let zone_key: Vec<String> = zone.key.iter().map(ToString::to_string).collect();
let class_key: Vec<String> = class.key.iter().map(ToString::to_string).collect();
return Err(format!(
"Tabulate Intersection: in zone '{}' and class '{}': {message}",
zone_key.join(", "),
class_key.join(", ")
));
}
row.push(Value::Float(ground_area_perimeter(covered).0 / area_divisor));
let covered_area = map_area_m2(covered);
Expand Down Expand Up @@ -11527,7 +11533,7 @@ mod tests {
let far = [16_777_216.0, -16_777_216.0, 1.0e11, -1.0e11, 1.0e300, -1.0e300, f64::MAX, -f64::MAX];
let near = [16_777_215.999_999_998, -16_777_215.999_999_998, 0.0, -0.0];
for f in far {
assert_eq!(coincident_cell(f), coincident_cell(f));
assert_ne!(coincident_cell(f), coincident_cell(-f), "{f}");
for n in near {
assert!(coincident_cell(f).abs_diff(coincident_cell(n)) > 1, "{f} {n}");
}
Expand Down
32 changes: 31 additions & 1 deletion crates/analysis/src/tools/network_analysis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,14 @@ fn network<'a>(inp: &'a dyn Inputs, p: &Json, tool: &str) -> Result<Network<'a>,
}
}
let graph = Graph::of(ds, &rows, cost_field)?;
if graph.overflowing() > 0 {
let field = cost_field.and_then(|fi| ds.fields.get(fi)).map_or("", |f| f.name.as_str());
notes.push(format!(
"{tool}: {} line(s) of '{}' cost so much in {field} that a segment's cost is past the largest number, and are closed",
graph.overflowing(),
ds.name
));
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
if graph.skipped_segments() > 0 {
notes.push(format!(
"{tool}: {} segment(s) of '{}' with invalid coordinates were left out of the network",
Expand All @@ -88,7 +96,9 @@ fn network<'a>(inp: &'a dyn Inputs, p: &Json, tool: &str) -> Result<Network<'a>,
));
}
if graph.segments() == 0 {
return Err(format!("'{}' has no lines to search", ds.name));
// What left no lines is said with it: the notes would be lost with the run.
let why = if notes.is_empty() { String::new() } else { format!(" ({})", notes.join("; ")) };
return Err(format!("'{}' has no lines to search{why}", ds.name));
}
Ok(Network { ds, graph, unit_m, snap_m, notes })
}
Expand Down Expand Up @@ -699,6 +709,26 @@ mod tests {
"{:?}",
r.messages
);
assert!(!r.messages.iter().any(|m| m.contains("past the largest number")), "{:?}", r.messages);
// A cost so large its segments' costs overflow closes the line too, counted apart.
let mut huge = roads();
huge.features[3].attrs[0] = Value::Float(1e306);
let inputs = map(vec![huge, points("shops", &[Some(c(0.005, 0.0))])]);
let r = service_area(&inputs, &json!({"network": "roads", "facilities": "shops", "breaks": "5", "costField": "cost"})).unwrap();
assert!(
r.messages.iter().any(|m| m
.contains("1 line(s) of 'roads' cost so much in cost that a segment's cost is past the largest number, and are closed")),
"{:?}",
r.messages
);
// Every line closed so: the refusal says why.
let mut all = roads();
for f in all.features.iter_mut() {
f.attrs[0] = Value::Float(1e306);
}
let inputs = map(vec![all, points("shops", &[Some(c(0.005, 0.0))])]);
let e = service_area(&inputs, &json!({"network": "roads", "facilities": "shops", "breaks": "5", "costField": "cost"})).unwrap_err();
assert!(e.contains("has no lines to search") && e.contains("4 line(s) of 'roads' cost so much"), "{e}");
}

/// A point just across ±180° from a line is moved onto it, about 110 m away, not left out as
Expand Down
16 changes: 3 additions & 13 deletions crates/data/src/export.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,18 +103,8 @@ pub fn write_source_in(src: &dyn FeatureSource, layer: &Dataset, path: &Path, cr
}

/// As [`write_source_in`], a GeoPackage's table placed as `gpkg` says (see
/// [`crate::io::write_path_to`]): also returns the table written.
pub fn write_source_to(
src: &dyn FeatureSource,
layer: &Dataset,
path: &Path,
crs: Crs,
gpkg: &GpkgTable,
) -> Result<(Exported, Option<GpkgWritten>)> {
write_chunks_to(src, layer, path, crs, gpkg, CHUNK_BYTES, None)
}

/// As [`write_source_to`], applying the layer's query before projecting or serializing each chunk.
/// [`crate::io::write_path_to`]), applying the layer's query before projecting or serializing each
/// chunk: also returns the table written.
pub fn write_source_filtered(
src: &dyn FeatureSource,
layer: &Dataset,
Expand All @@ -134,7 +124,7 @@ fn write_chunks_in(src: &dyn FeatureSource, layer: &Dataset, path: &Path, crs: C
write_chunks_to(src, layer, path, crs, &GpkgTable::default(), bytes, None).map(|(e, _)| e)
}

/// [`write_source_to`], `bytes` of features a chunk.
/// [`write_source_filtered`], `bytes` of features a chunk.
fn write_chunks_to(
src: &dyn FeatureSource,
layer: &Dataset,
Expand Down
Loading
Loading