Skip to content

Commit 649a73d

Browse files
Mavrick-Fclaude
andcommitted
fix(analysis): snap across ±180°, keep negative ids, limit matrices by their rows (#2344)
- A point just across the antimeridian from a segment is projected on the segment's side, so it snaps to it instead of being left out. - facility_fid, origin_fid and destination_fid keep ids stored wrapped (a GeoPackage's negative ones), as the vertex tools do. - OD Cost Matrix is limited by the rows it makes, not by origins times destinations, so a sparse matrix isn't refused before it runs. - Pairs that aren't connected are counted before Destinations to Find keeps the cheapest, so the notice appears with a count set too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent dadeacf commit 649a73d

2 files changed

Lines changed: 50 additions & 12 deletions

File tree

‎crates/analysis/src/network.rs‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -228,9 +228,12 @@ fn nearest_segment(segs: &[Segment], nodes: &[Coord], p: Coord, within: Option<f
228228
{
229229
return None;
230230
}
231+
// The point's longitude on the segment's side of ±180°: unchanged within 180° of its
232+
// middle, so only segments near the antimeridian see a point just across it.
233+
let px = p.x + 360.0 * ((0.5 * (a.x + b.x) - p.x) / 360.0).round();
231234
let (dx, dy) = ((b.x - a.x) * k, b.y - a.y);
232235
let len2 = dx * dx + dy * dy;
233-
let t = if len2 > 0.0 { (((p.x - a.x) * k * dx + (p.y - a.y) * dy) / len2).clamp(0.0, 1.0) } else { 0.0 };
236+
let t = if len2 > 0.0 { (((px - a.x) * k * dx + (p.y - a.y) * dy) / len2).clamp(0.0, 1.0) } else { 0.0 };
234237
let q = Coord::new(a.x + t * (b.x - a.x), a.y + t * (b.y - a.y));
235238
Some((i, t, q, haversine_m(q, p)))
236239
})

‎crates/analysis/src/tools/network_analysis.rs‎

Lines changed: 46 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -285,7 +285,7 @@ pub(super) fn service_area(inp: &dyn Inputs, p: &Json) -> Result<ToolResult, Str
285285
let Some(f) = ds.features.get(row) else { continue };
286286
reached.insert(facility);
287287
let mut attrs: Vec<Value> = (0..ds.fields.len()).map(|i| f.attrs.get(i).cloned().unwrap_or(Value::Null)).collect();
288-
let fid = facilities.get(facility).map_or(Value::Null, |(id, _)| i64::try_from(*id).map_or(Value::Null, Value::Int));
288+
let fid = facilities.get(facility).map_or(Value::Null, |(id, _)| Value::Int(id.cast_signed()));
289289
let from = if band == 0 { 0.0 } else { breaks.get(band - 1).copied().unwrap_or(0.0) };
290290
attrs.extend([fid, Value::Float(from), Value::Float(breaks.get(band).copied().unwrap_or(0.0))]);
291291
out.push(Some(Geometry::Line(lines)), attrs);
@@ -329,12 +329,6 @@ pub(super) fn od_cost_matrix_on(inp: &dyn Inputs, p: &Json, threads: Option<usiz
329329
let origins = place(inp, p, "origins", &mut net, TOOL)?;
330330
let destinations = place(inp, p, "destinations", &mut net, TOOL)?;
331331
let per_origin = count.map_or(destinations.len(), |n| n.min(destinations.len()));
332-
if cutoff.is_none() && origins.len().saturating_mul(per_origin) > MAX_PAIRS {
333-
return Err(format!(
334-
"{TOOL}: {} origins by {per_origin} destinations is more than {MAX_PAIRS} rows; set a Cutoff or Destinations to Find",
335-
origins.len()
336-
));
337-
}
338332
let (graph, unit_m) = (&net.graph, net.unit_m);
339333
let limit = cutoff.map_or(f64::INFINITY, |c| c * unit_m);
340334
// The destinations at each end of their segments, and on each segment: a search visits only
@@ -388,14 +382,16 @@ pub(super) fn od_cost_matrix_on(inp: &dyn Inputs, p: &Json, threads: Option<usiz
388382
(cost.is_finite() && cost <= limit).then_some((j, cost, length))
389383
})
390384
.collect();
385+
// Counted before the cheapest few are kept: those beyond them are reached.
386+
let unreached = destinations.len() - row.len();
391387
row.sort_by(|a, b| a.1.total_cmp(&b.1).then(a.0.cmp(&b.0)));
392388
row.truncate(per_origin);
393389
if rows.fetch_add(row.len(), Ordering::Relaxed).saturating_add(row.len()) > MAX_PAIRS {
394390
return Err(format!(
395391
"{TOOL}: the matrix would hold more than {MAX_PAIRS} rows; set a lower Cutoff or Destinations to Find"
396392
));
397393
}
398-
Ok(row)
394+
Ok((row, unreached))
399395
},
400396
)?;
401397
crate::control::finish();
@@ -406,11 +402,12 @@ pub(super) fn od_cost_matrix_on(inp: &dyn Inputs, p: &Json, threads: Option<usiz
406402
GeometryType::None,
407403
fields.into_iter().chain(["cost", "length"].map(|n| Field::new(n, FieldType::Double))).collect(),
408404
);
409-
let id = |v: u64| i64::try_from(v).map_or(Value::Null, Value::Int);
405+
// Ids stored wrapped (a GeoPackage's negative ones) read back as they were written.
406+
let id = |v: u64| Value::Int(v.cast_signed());
410407
let mut unreached = 0usize;
411-
for ((oid, _), row) in origins.iter().zip(&found) {
408+
for ((oid, _), (row, missed)) in origins.iter().zip(&found) {
412409
crate::control::check()?;
413-
unreached += per_origin - row.len();
410+
unreached += missed;
414411
for (rank, &(j, cost, length)) in row.iter().enumerate() {
415412
let did = destinations.get(j).map_or(Value::Null, |(d, _)| id(*d));
416413
out.push(None, vec![id(*oid), did, Value::Int(rank as i64 + 1), Value::Float(cost / unit_m), Value::Float(length / unit_m)]);
@@ -630,6 +627,44 @@ mod tests {
630627
);
631628
}
632629

630+
/// A point just across ±180° from a line is moved onto it, about 110 m away, not left out as
631+
/// if it were the whole Earth's width away.
632+
#[test]
633+
fn a_point_across_the_antimeridian_snaps_to_the_line_beside_it() {
634+
let mut lines = Dataset::new("roads", GeometryType::Polyline, vec![]);
635+
lines.push(Some(Geometry::Line(vec![vec![c(-180.0, 0.0), c(-179.99, 0.0)]])), vec![]);
636+
let inputs = map(vec![lines, points("shops", &[Some(c(179.999, 0.0))])]);
637+
let r = service_area(&inputs, &json!({"network": "roads", "facilities": "shops", "breaks": "0.5"})).unwrap();
638+
assert_eq!(r.messages.len(), 1, "{:?}", r.messages);
639+
assert!(!dataset(&r).features.is_empty());
640+
}
641+
642+
/// Ids stored wrapped, as a GeoPackage's negative ones are, are written back as they were;
643+
/// and an origin that reaches one destination but not another says so even when only the
644+
/// nearest is kept.
645+
#[test]
646+
fn od_rows_keep_negative_ids_and_count_pairs_past_the_kept_ones() {
647+
let mut from = points("from", &[Some(c(0.0, 0.0))]);
648+
from.features[0].id = (-2i64).cast_unsigned();
649+
let to = points("to", &[Some(c(0.01, 0.0)), Some(c(1.005, 1.0))]);
650+
let inputs = map(vec![roads(), from, to]);
651+
let r = od_cost_matrix(&inputs, &json!({"network": "roads", "origins": "from", "destinations": "to", "count": 1})).unwrap();
652+
let out = dataset(&r);
653+
assert_eq!(out.features.len(), 1);
654+
assert_eq!(field(out, &out.features[0], "origin_fid"), -2.0);
655+
assert!(r.messages.iter().any(|m| m.contains("1 origin–destination pair(s) aren't connected")), "{:?}", r.messages);
656+
let r = service_area(
657+
&map(vec![roads(), {
658+
let mut shops = points("shops", &[Some(c(0.005, 0.0))]);
659+
shops.features[0].id = (-7i64).cast_unsigned();
660+
shops
661+
}]),
662+
&json!({"network": "roads", "facilities": "shops", "breaks": "1"}),
663+
)
664+
.unwrap();
665+
assert!(dataset(&r).features.iter().all(|f| field(dataset(&r), f, "facility_fid") == -7.0));
666+
}
667+
633668
/// Every origin's row the same, bit for bit, on one thread or several.
634669
#[test]
635670
fn od_cost_matrix_is_the_same_on_any_thread_count() {

0 commit comments

Comments
 (0)