Skip to content
Merged
86 changes: 57 additions & 29 deletions crates/analysis/src/density.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,41 +66,35 @@ const DEFAULT_GRID_STEPS: f64 = 250.0;
/// h = 0.9 * min(StandardDistance, sqrt(1 / ln(2)) * MedianDistance) * N^(-0.2)
///
/// Takes point weights into account for weighted mean center, weighted standard distance, and
/// weighted median distance. Falls back safely and deterministically to extent-based scaling for
/// small samples or identical coordinates (span / 30.0 when extent > 0, or 1000.0 coordinate-space
/// units for single or coincident points).
/// weighted median distance. Only points with finite coordinates and a finite, positive weight
/// count. Falls back safely and deterministically to extent-based scaling for fewer than two such
/// points or identical coordinates (span / 30.0, at least 1e-4, when the span exceeds 1e-4, or
/// 1000.0 coordinate-space units otherwise).
pub fn silverman_bandwidth(points: &[(Coord, f64)], extent: &Extent) -> f64 {
let n = points.len();
if n < 2 {
let fallback = || {
let span = extent.width().max(extent.height());
return if span > 1e-4 { span / 30.0 } else { 1000.0 };
if span.is_finite() && span > 1e-4 { (span / 30.0).max(1e-4) } else { 1000.0 }
Comment thread
giswqs marked this conversation as resolved.
Resolved
};

// Filtered on each pass rather than collected, so no second copy of the points is held.
let valid = || points.iter().copied().filter(|(p, w)| p.is_finite() && w.is_finite() && *w > 0.0);
let n = valid().count();
if n < 2 {
return fallback();
}

let (sum_x, sum_y, sum_w) = points.iter().fold((0.0, 0.0, 0.0), |(sx, sy, sw), (p, w)| {
let weight = if w.is_finite() && *w > 0.0 { *w } else { 1.0 };
(sx + p.x * weight, sy + p.y * weight, sw + weight)
});
if sum_w <= 0.0 || !sum_w.is_finite() {
let span = extent.width().max(extent.height());
return if span.is_finite() && span > 1e-4 { (span / 30.0).max(1e-4) } else { 1000.0 };
let (sum_x, sum_y, sum_w) = valid().fold((0.0, 0.0, 0.0), |(sx, sy, sw), (p, w)| (sx + p.x * w, sy + p.y * w, sw + w));
if sum_w <= 0.0 || !sum_w.is_finite() || !sum_x.is_finite() || !sum_y.is_finite() {
return fallback();
}
let mean_x = sum_x / sum_w;
let mean_y = sum_y / sum_w;

let sum_sq_dist = points.iter().fold(0.0, |acc, (p, w)| {
let weight = if w.is_finite() && *w > 0.0 { *w } else { 1.0 };
acc + weight * ((p.x - mean_x).powi(2) + (p.y - mean_y).powi(2))
});
let sum_sq_dist = valid().fold(0.0, |acc, (p, w)| acc + w * ((p.x - mean_x).powi(2) + (p.y - mean_y).powi(2)));
let std_dist = (sum_sq_dist / sum_w).sqrt();

let mut dists: Vec<(f64, f64)> = points
.iter()
.map(|(p, w)| {
let weight = if w.is_finite() && *w > 0.0 { *w } else { 1.0 };
(((p.x - mean_x).powi(2) + (p.y - mean_y).powi(2)).sqrt(), weight)
})
.collect();
dists.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));
let mut dists: Vec<(f64, f64)> = valid().map(|(p, w)| (((p.x - mean_x).powi(2) + (p.y - mean_y).powi(2)).sqrt(), w)).collect();
dists.sort_by(|a, b| a.0.total_cmp(&b.0));

let half_w = sum_w * 0.5;
let mut cum_w = 0.0;
Expand All @@ -117,17 +111,15 @@ pub fn silverman_bandwidth(points: &[(Coord, f64)], extent: &Extent) -> f64 {
let a = (1.0 / 2.0f64.ln()).sqrt();
let term = std_dist.min(a * median_dist);

if term > 1e-6 {
if term.is_finite() && term > 1e-6 {
let n_factor = (n as f64).powf(-0.2);
let h = 0.9 * term * n_factor;
if h.is_finite() && h > 1e-4 {
return h;
}
}

// Fallback: fraction of extent or fixed distance
let span = extent.width().max(extent.height());
if span.is_finite() && span > 1e-4 { (span / 30.0).max(1e-4) } else { 1000.0 }
fallback()
}

/// Automatically calculates cell size so the grid spans approximately 250 cells across its maximum dimension.
Expand Down Expand Up @@ -705,4 +697,40 @@ mod tests {
assert_eq!(e, crate::control::CANCELLED, "{threads}");
}
}

#[test]
fn silverman_bandwidth_matches_valid_points_and_handles_non_finite() {
let base = vec![
(Coord::new(0.0, 0.0), 1.0),
(Coord::new(100.0, 0.0), 2.0),
(Coord::new(0.0, 100.0), 1.5),
(Coord::new(100.0, 100.0), 1.0),
(Coord::new(50.0, 50.0), 3.0),
];
let ext = Extent::new(0.0, 0.0, 100.0, 100.0);
let h_base = silverman_bandwidth(&base, &ext);

let mut noisy = base.clone();
for i in 0..30 {
match i % 5 {
0 => noisy.push((Coord::new(f64::NAN, 10.0), 1.0)),
1 => noisy.push((Coord::new(f64::INFINITY, 10.0), 1.0)),
2 => noisy.push((Coord::new(25.0, 25.0), 0.0)),
3 => noisy.push((Coord::new(75.0, 75.0), -2.0)),
_ => noisy.push((Coord::new(50.0, 50.0), f64::NAN)),
}
}
let h_noisy = silverman_bandwidth(&noisy, &ext);
assert_eq!(h_noisy, h_base, "invalid and non-positive points must not change bandwidth");

// Fewer than 2 valid points falls back to extent scaling.
let one_valid = vec![
(Coord::new(50.0, 50.0), 1.0),
(Coord::new(0.0, 0.0), 0.0),
(Coord::new(100.0, 100.0), -1.0),
(Coord::new(f64::NAN, 0.0), 1.0),
];
let h_one = silverman_bandwidth(&one_valid, &ext);
assert!((h_one - 100.0 / 30.0).abs() < 1e-12, "got {h_one}");
}
}
63 changes: 62 additions & 1 deletion crates/analysis/src/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -845,6 +845,19 @@ impl Search {
pub const MAX_POINTS: usize = 1_000_000;
const MAX_TRIES: usize = 50_000_000;

/// Whether `e` is a finite, positive-area bounding box that [`random_points`] can sample inside.
pub fn usable_polygon_extent(e: rustgis_geom::Extent) -> bool {
!e.is_empty()
&& e.min_x.is_finite()
&& e.max_x.is_finite()
&& e.min_y.is_finite()
&& e.max_y.is_finite()
&& e.width().is_finite()
&& e.height().is_finite()
&& e.width() > 0.0
&& e.height() > 0.0
}

/// Points spread at random (but reproducibly, from `seed`) inside polygons: `per` in each, up to
/// [`MAX_POINTS`] in all; thin polygons may get fewer (tries are bounded too).
pub fn random_points(ds: &Dataset, rows: &[usize], per: usize, seed: u64) -> Vec<(usize, Coord)> {
Expand All @@ -858,17 +871,23 @@ pub fn random_points(ds: &Dataset, rows: &[usize], per: usize, seed: u64) -> Vec
};
let mut out = Vec::new();
crate::control::begin(rows.len());
for (i, r) in rows.iter().enumerate() {
'rows: for (i, r) in rows.iter().enumerate() {
if crate::control::cancelled() {
break;
}
crate::control::reached(i);
let Some(Geometry::Polygon(polys)) = ds.features.get(*r).and_then(|f| f.geometry.as_ref()) else { continue };
let e = ds.features.get(*r).and_then(|f| f.geometry.as_ref()).map(|g| g.extent()).unwrap_or_default();
if !usable_polygon_extent(e) {
continue;
}
let mut placed = 0;
let mut tries = 0usize;
while placed < per && tries < per.saturating_mul(200) && budget > 0 && out.len() < MAX_POINTS {
tries += 1;
if tries & 1023 == 0 && crate::control::cancelled() {
break 'rows;
}
budget -= 1;
let c = Coord::new(e.min_x + rnd() * e.width(), e.min_y + rnd() * e.height());
if polys.iter().any(|rings| rustgis_data::geometry::polygon_contains(rings, c)) {
Expand Down Expand Up @@ -2030,6 +2049,48 @@ mod tests {
assert!(empty_err.contains("the layer has no lines"), "{empty_err}");
}

#[test]
fn random_points_skips_empty_extents_and_checks_cancel_inside_loop() {
// 1,000 empty polygons (each would burn 250 * 200 = 50,000 tries = 50,000,000 total)
// followed by one valid unit square: the empty polygons must not exhaust the try budget.
let mut ds = Dataset::new("p", GeometryType::Polygon, vec![]);
for _ in 0..1000 {
ds.push(Some(Geometry::Polygon(vec![])), vec![]);
}
ds.push(
Some(Geometry::Polygon(vec![vec![vec![
Coord::new(0.0, 0.0),
Coord::new(1.0, 0.0),
Coord::new(1.0, 1.0),
Coord::new(0.0, 1.0),
Coord::new(0.0, 0.0),
]]])),
vec![],
);
let rows: Vec<usize> = (0..ds.features.len()).collect();
let pts = random_points(&ds, &rows, 250, 7);
assert_eq!(pts.len(), 250);
assert!(pts.iter().all(|(r, _)| *r == 1000));

// A very thin diagonal sliver polygon forces many rejection tries; cancellation must be
// observed inside the rejection loop rather than only between features.
let mut sliver = Dataset::new("sliver", GeometryType::Polygon, vec![]);
sliver.push(
Some(Geometry::Polygon(vec![vec![vec![
Coord::new(0.0, 0.0),
Coord::new(1.0, 1.0),
Coord::new(1.0, 1.0 - 1e-6),
Coord::new(0.0, 0.0),
]]])),
vec![],
);
let ctrl = crate::control::Control::cancelled_at_look(2);
let _installed = crate::control::install(Some(ctrl.clone()));
let got = random_points(&sliver, &[0], 10_000, 7);
assert!(ctrl.looked() >= 2, "expected cancel check inside rejection loop, looked {}", ctrl.looked());
assert!(got.len() < 10_000);
}

#[test]
fn route_overlay_handles_empty_far_same_segment_and_endpoint_snaps() {
let cache = Mutex::new(None);
Expand Down
Loading
Loading