Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

fix(segment): stop push/relabel looping forever on unreachable nodes (#4869)

LloydNicholson1735c81e67ca
diff --git a/crates/algo/src/segment/maxflow/push_relabel.rs b/crates/algo/src/segment/maxflow/push_relabel.rs
index 914645d4c..1041f9ef5 100644
--- a/crates/algo/src/segment/maxflow/push_relabel.rs
+++ b/crates/algo/src/segment/maxflow/push_relabel.rs
@@ -71,7 +71,10 @@ impl Graph {
let ai = a as usize;
let j = self.head[ai] as usize;
work += 1;
- if self.r_cap[ai] > EPS && self.dist[i] == self.dist[j].saturating_add(1) {
+ // `checked_add`: two nodes a global relabel left unreachable (`u32::MAX`) must
+ // not count as admissible for each other, or float-stranded excess ping-pongs
+ // between them forever.
+ if self.r_cap[ai] > EPS && self.dist[j].checked_add(1) == Some(self.dist[i]) {
let delta = (excess[i] as f32).min(self.r_cap[ai]);
self.r_cap[ai] -= delta;
self.r_cap[ai ^ 1] += delta;
diff --git a/crates/algo/src/segment/maxflow/push_relabel/tests.rs b/crates/algo/src/segment/maxflow/push_relabel/tests.rs
index 6c7141572..ce0c0b862 100644
--- a/crates/algo/src/segment/maxflow/push_relabel/tests.rs
+++ b/crates/algo/src/segment/maxflow/push_relabel/tests.rs
@@ -179,3 +179,28 @@ fn solver_workload_release_comparison() {
}
}
}
+
+#[test]
+fn stranded_excess_terminates_and_matches_bk() {
+ // Source capacities far beyond f32 precision (ulp 32 at 3e8) next to small links: rounding
+ // strands excess on nodes a global relabel finds reachable from neither terminal. Those
+ // nodes (height u32::MAX) used to count as admissible for each other and pushed the excess
+ // back and forth forever (Remove Background never finished on some photos).
+ let mut g = Graph::with_capacity(6, 7);
+ for (i, &(s, t)) in [(33123824.0, 0.0), (347622050.0, 0.0), (0.0, 5539047.5), (76592.22, 0.0), (3514.0022, 0.0), (0.0, 13670.268)].iter().enumerate() {
+ g.add_tweights(i, s, t);
+ }
+ for (i, j, c) in [(0, 1, 0.0), (0, 3, 0.0007301044), (1, 2, 2.803e-42), (1, 4, 8.160078), (2, 5, 3.1224866e-7), (3, 4, 28.512966), (4, 5, 4.099367)] {
+ g.add_edge(i, j, c, c);
+ }
+ let mut bk = g.clone();
+ let checks = std::cell::Cell::new(0);
+ let cancel = || {
+ checks.set(checks.get() + 1);
+ checks.get() > 1000
+ };
+ let flow = g.push_relabel(&cancel).expect("push/relabel did not terminate");
+ let bk_flow = bk.maxflow_bk();
+ assert!((flow - bk_flow).abs() <= 1e-6 * bk_flow, "{flow} vs {bk_flow}");
+ assert_eq!((0..6).map(|i| g.in_source(i)).collect::<Vec<_>>(), (0..6).map(|i| bk.in_source(i)).collect::<Vec<_>>());
+}