eo-mcf 0.1.0

Exact minimum-cost-flow solver (cost-scaling push-relabel) with independent optimality certification.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
//! Independent reference implementations, for validation only.
//!
//! Nothing here is used by [`solve`](crate::solve). These exist so that the
//! solver can be checked against something that is not the solver, and — for
//! [`brute_force`] — against something that is not an algorithm at all.
//!
//! | Oracle | Depends on |
//! |---|---|
//! | [`brute_force`] — enumerate every integral flow, keep the cheapest feasible one | nothing |
//! | [`successive_shortest_paths`] — a different exact algorithm for the same problem | nothing |
//! | [`max_flow_value`] — max flow, for "zero costs ⇒ maximum flow" | nothing |
//!
//! The point of [`successive_shortest_paths`] is triangulation: it shares no
//! idea with cost scaling beyond the problem statement — it augments along
//! shortest paths and maintains primal feasibility throughout, where cost
//! scaling maintains ε-optimality over a pseudoflow and only becomes feasible
//! at the end. Two implementations that agree by accident would have to be
//! wrong in the same way, and these two have no way to be.
//!
//! These are written for clarity over speed and are sized for validation
//! instances, not production ones.

use crate::arith::{Capacity, Cost, Flow, Objective, Overflow};
use crate::problem::Problem;

/// Ceiling on the search space [`brute_force`] will enumerate.
pub const BRUTE_FORCE_LIMIT: u128 = 1 << 20;

/// An oracle could not answer.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum OracleError {
    /// The instance is beyond exhaustive enumeration.
    #[error("instance has {combinations} candidate flows, above the brute-force limit of {limit}")]
    TooLarge {
        /// Size of the search space.
        combinations: u128,
        /// The ceiling.
        limit: u128,
    },
    /// Successive shortest paths did not finish within its bound.
    #[error("successive shortest paths did not converge within {augmentations} augmentations")]
    DidNotConverge {
        /// The bound that was reached.
        augmentations: u64,
    },
    /// An intermediate quantity left integer range.
    #[error(transparent)]
    Overflow(#[from] Overflow),
}

/// The optimal cost by exhaustive enumeration, or `None` if no feasible
/// flow exists.
///
/// Enumerates every point of `∏ₖ [lowerₖ, upperₖ]`, keeps the feasible ones
/// and takes the cheapest. This is the only oracle in the crate that depends
/// on no algorithm whatsoever: if it disagrees with the solver, the solver is
/// wrong.
///
/// # Errors
///
/// [`OracleError::TooLarge`] when the search space exceeds
/// [`BRUTE_FORCE_LIMIT`].
pub fn brute_force(problem: &Problem) -> Result<Option<Objective>, OracleError> {
    let mut radices: Vec<u64> = Vec::with_capacity(problem.arc_count());
    let mut combinations: u128 = 1;
    for arc in problem.arcs() {
        let span = arc
            .upper
            .checked_sub(arc.lower)
            .and_then(|s| s.checked_add(1))
            .ok_or_else(|| Overflow::new("brute-force arc span"))?;
        let span = u64::try_from(span).map_err(|_| Overflow::new("brute-force arc span"))?;
        radices.push(span);
        combinations = combinations.saturating_mul(u128::from(span));
        if combinations > BRUTE_FORCE_LIMIT {
            return Err(OracleError::TooLarge {
                combinations,
                limit: BRUTE_FORCE_LIMIT,
            });
        }
    }

    let mut digits = vec![0u64; problem.arc_count()];
    let mut flows = vec![0 as Flow; problem.arc_count()];
    let mut best: Option<Objective> = None;

    'candidates: loop {
        for (index, arc) in problem.arcs().iter().enumerate() {
            flows[index] = arc.lower + digits[index] as Flow;
        }
        if let Some(cost) = feasible_cost(problem, &flows) {
            best = Some(best.map_or(cost, |b: Objective| b.min(cost)));
        }

        // Odometer step over the mixed-radix counter.
        let mut position = 0;
        loop {
            if position == digits.len() {
                break 'candidates;
            }
            digits[position] += 1;
            if digits[position] < radices[position] {
                break;
            }
            digits[position] = 0;
            position += 1;
        }
        if digits.is_empty() {
            break;
        }
    }

    Ok(best)
}

/// Cost of `flows` if it conserves flow at every node, else `None`.
fn feasible_cost(problem: &Problem, flows: &[Flow]) -> Option<Objective> {
    let mut net = vec![0 as Objective; problem.node_count()];
    for (arc, &flow) in problem.arcs().iter().zip(flows) {
        net[arc.tail] += Objective::from(flow);
        net[arc.head] -= Objective::from(flow);
    }
    for (&balance, &supply) in net.iter().zip(problem.supplies()) {
        if balance != Objective::from(supply) {
            return None;
        }
    }
    problem.objective(flows).ok()
}

/// An optimal flow by successive shortest paths, or `None` if the
/// instance is infeasible.
///
/// Negative-cost arcs are saturated up front, which removes every negative
/// residual cycle and makes shortest-path augmentation valid. Shortest paths
/// are found by Bellman–Ford, bounded by node count, so the oracle terminates
/// on any input.
///
/// # Errors
///
/// [`OracleError::DidNotConverge`] if the augmentation bound is reached;
/// [`OracleError::Overflow`] on integer range.
pub fn successive_shortest_paths(
    problem: &Problem,
) -> Result<Option<(Vec<Flow>, Objective)>, OracleError> {
    let node_count = problem.node_count();
    let source = node_count;
    let sink = node_count + 1;
    let mut graph = Graph::new(node_count + 2);
    let mut excess: Vec<i128> = problem.supplies().iter().map(|&b| i128::from(b)).collect();
    let mut flows = vec![0 as Flow; problem.arc_count()];
    // How to read each arc's flow back: (edge index, base, sign).
    let mut readback: Vec<Option<(usize, Flow, Flow)>> = vec![None; problem.arc_count()];

    for (index, arc) in problem.arcs().iter().enumerate() {
        if arc.tail == arc.head {
            flows[index] = if arc.cost >= 0 { arc.lower } else { arc.upper };
            continue;
        }
        excess[arc.tail] -= i128::from(arc.lower);
        excess[arc.head] += i128::from(arc.lower);
        let span = arc
            .upper
            .checked_sub(arc.lower)
            .ok_or_else(|| Overflow::new("oracle arc span"))?;

        if arc.cost < 0 {
            // Saturate, then allow the flow to be given back along a
            // positive-cost reverse edge.
            excess[arc.tail] -= i128::from(span);
            excess[arc.head] += i128::from(span);
            let edge = graph.add(arc.head, arc.tail, span, -arc.cost);
            flows[index] = arc.upper;
            readback[index] = Some((edge, arc.upper, -1));
        } else {
            let edge = graph.add(arc.tail, arc.head, span, arc.cost);
            flows[index] = arc.lower;
            readback[index] = Some((edge, arc.lower, 1));
        }
    }

    let mut required: i128 = 0;
    for (node, &value) in excess.iter().enumerate() {
        if value > 0 {
            let capacity = Capacity::try_from(value).map_err(|_| Overflow::new("oracle supply"))?;
            graph.add(source, node, capacity, 0);
            required += value;
        } else if value < 0 {
            let capacity =
                Capacity::try_from(-value).map_err(|_| Overflow::new("oracle demand"))?;
            graph.add(node, sink, capacity, 0);
        }
    }

    let bound = (graph.cap.len() as u64)
        .saturating_mul(4)
        .saturating_add(1024);
    let mut routed: i128 = 0;
    let mut augmentations = 0u64;

    while routed < required {
        let Some(path) = graph.shortest_path(source, sink) else {
            break;
        };
        let Some(bottleneck) = path.iter().map(|&e| graph.cap[e]).min() else {
            break;
        };
        if bottleneck <= 0 {
            break;
        }
        for &edge in &path {
            graph.cap[edge] -= bottleneck;
            graph.cap[edge ^ 1] += bottleneck;
        }
        routed += i128::from(bottleneck);
        augmentations += 1;
        if augmentations > bound {
            return Err(OracleError::DidNotConverge {
                augmentations: bound,
            });
        }
    }

    if routed != required {
        return Ok(None);
    }

    for (index, entry) in readback.iter().enumerate() {
        if let &Some((edge, base, sign)) = entry {
            // The partner edge accumulates exactly the units pushed.
            flows[index] = base + sign * graph.cap[edge ^ 1];
        }
    }
    let objective = problem.objective(&flows)?;
    Ok(Some((flows, objective)))
}

/// Maximum flow between two nodes, for the "all costs zero" property.
///
/// **Edmonds–Karp, written here rather than delegated to the crate's internal
/// `maxflow` module.** The solver settles feasibility with its own Dinic
/// implementation, so an oracle that called the same code would compare the
/// solver against one of the solver's own components: a defect in that
/// component would make both sides agree and the property would pass while
/// being wrong. Everywhere else this crate is careful about independence —
/// the two optimality proofs share no code, the certifiers refuse the
/// solver's prices — and
/// this closes the one place it leaked.
///
/// Shortest augmenting paths by BFS: `O(n·m²)`, slower than the solver's
/// blocking-flow search and deliberately so. An oracle is judged on being
/// obviously right, not on being fast.
#[must_use]
pub fn max_flow_value(
    node_count: usize,
    edges: &[(u32, u32, Capacity)],
    source: usize,
    sink: usize,
) -> i128 {
    if source == sink || source >= node_count || sink >= node_count {
        return 0;
    }

    // Adjacency lists with `e ^ 1` pairing — not the solver's CSR layout.
    let mut adjacency: Vec<Vec<usize>> = vec![Vec::new(); node_count];
    let mut to: Vec<usize> = Vec::with_capacity(edges.len() * 2);
    let mut residual: Vec<Capacity> = Vec::with_capacity(edges.len() * 2);
    for &(tail, head, capacity) in edges {
        adjacency[tail as usize].push(to.len());
        to.push(head as usize);
        residual.push(capacity.max(0));
        adjacency[head as usize].push(to.len());
        to.push(tail as usize);
        residual.push(0);
    }

    let mut total: i128 = 0;
    loop {
        // BFS for a shortest augmenting path, recording the arc reached by.
        let mut arrived: Vec<Option<usize>> = vec![None; node_count];
        let mut seen = vec![false; node_count];
        seen[source] = true;
        let mut queue = std::collections::VecDeque::new();
        queue.push_back(source);
        while let Some(node) = queue.pop_front() {
            if node == sink {
                break;
            }
            for &edge in &adjacency[node] {
                let next = to[edge];
                if residual[edge] > 0 && !seen[next] {
                    seen[next] = true;
                    arrived[next] = Some(edge);
                    queue.push_back(next);
                }
            }
        }
        if !seen[sink] {
            return total;
        }

        // Bottleneck, then augment.
        let mut bottleneck = Capacity::MAX;
        let mut node = sink;
        while let Some(edge) = arrived[node] {
            bottleneck = bottleneck.min(residual[edge]);
            node = to[edge ^ 1];
        }
        if bottleneck <= 0 {
            return total;
        }
        let mut node = sink;
        while let Some(edge) = arrived[node] {
            residual[edge] -= bottleneck;
            residual[edge ^ 1] += bottleneck;
            node = to[edge ^ 1];
        }
        total += i128::from(bottleneck);
    }
}

/// Adjacency-list flow network with paired edges at `e` and `e ^ 1`.
///
/// Deliberately unlike the solver's CSR layout: this is a cross-check, and a
/// cross-check that shares a data structure shares its bugs.
struct Graph {
    adjacency: Vec<Vec<usize>>,
    to: Vec<usize>,
    cap: Vec<Capacity>,
    cost: Vec<Cost>,
}

impl Graph {
    fn new(node_count: usize) -> Self {
        Self {
            adjacency: vec![Vec::new(); node_count],
            to: Vec::new(),
            cap: Vec::new(),
            cost: Vec::new(),
        }
    }

    fn add(&mut self, from: usize, to: usize, capacity: Capacity, cost: Cost) -> usize {
        let edge = self.to.len();
        self.adjacency[from].push(edge);
        self.to.push(to);
        self.cap.push(capacity);
        self.cost.push(cost);

        self.adjacency[to].push(edge + 1);
        self.to.push(from);
        self.cap.push(0);
        self.cost.push(-cost);
        edge
    }

    /// Cheapest residual path, as edge indices. Bellman–Ford: residual reverse
    /// edges carry negative costs even though no negative cycle exists.
    fn shortest_path(&self, source: usize, sink: usize) -> Option<Vec<usize>> {
        let node_count = self.adjacency.len();
        let mut distance = vec![i128::MAX; node_count];
        let mut incoming: Vec<Option<usize>> = vec![None; node_count];
        distance[source] = 0;

        for _ in 0..node_count {
            let mut changed = false;
            for u in 0..node_count {
                if distance[u] == i128::MAX {
                    continue;
                }
                for &edge in &self.adjacency[u] {
                    if self.cap[edge] <= 0 {
                        continue;
                    }
                    let v = self.to[edge];
                    let candidate = distance[u] + i128::from(self.cost[edge]);
                    if candidate < distance[v] {
                        distance[v] = candidate;
                        incoming[v] = Some(edge);
                        changed = true;
                    }
                }
            }
            if !changed {
                break;
            }
        }

        if distance[sink] == i128::MAX {
            return None;
        }
        let mut path = Vec::new();
        let mut node = sink;
        while node != source {
            let edge = incoming[node]?;
            path.push(edge);
            node = self.to[edge ^ 1];
        }
        path.reverse();
        Some(path)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn brute_force_finds_the_cheap_route() {
        let problem = Problem::builder(4)
            .supply(0, 1)
            .supply(3, -1)
            .edge(0, 1, 1, 1)
            .edge(1, 3, 1, 1)
            .edge(0, 2, 1, 5)
            .edge(2, 3, 1, 5)
            .build()
            .unwrap();
        assert_eq!(brute_force(&problem), Ok(Some(2)));
    }

    #[test]
    fn brute_force_reports_infeasibility_as_none() {
        let problem = Problem::builder(2)
            .supply(0, 5)
            .supply(1, -5)
            .edge(0, 1, 2, 1)
            .build()
            .unwrap();
        assert_eq!(brute_force(&problem), Ok(None));
    }

    #[test]
    fn brute_force_refuses_an_instance_it_cannot_enumerate() {
        let problem = Problem::builder(2)
            .supply(0, 0)
            .edge(0, 1, 1_000_000, 1)
            .edge(1, 0, 1_000_000, 1)
            .build()
            .unwrap();
        assert!(matches!(
            brute_force(&problem),
            Err(OracleError::TooLarge { .. })
        ));
    }

    #[test]
    fn successive_shortest_paths_agrees_with_brute_force() {
        let problem = Problem::builder(4)
            .supply(0, 2)
            .supply(3, -2)
            .edge(0, 1, 1, 1)
            .edge(1, 3, 2, 1)
            .edge(0, 2, 2, 2)
            .edge(2, 3, 1, 1)
            .build()
            .unwrap();
        let (_, objective) = successive_shortest_paths(&problem).unwrap().unwrap();
        assert_eq!(Some(objective), brute_force(&problem).unwrap());
    }

    #[test]
    fn successive_shortest_paths_handles_negative_costs() {
        // A negative arc worth saturating even though the flow must come back.
        let problem = Problem::builder(3)
            .supply(0, 1)
            .supply(2, -1)
            .edge(0, 1, 3, -4)
            .edge(1, 2, 3, 1)
            .edge(0, 2, 3, 1)
            .build()
            .unwrap();
        let (flows, objective) = successive_shortest_paths(&problem).unwrap().unwrap();
        assert_eq!(Some(objective), brute_force(&problem).unwrap());
        assert_eq!(crate::verify::certify_feasibility(&problem, &flows), Ok(()));
    }

    #[test]
    fn successive_shortest_paths_reports_infeasibility() {
        let problem = Problem::builder(2)
            .supply(0, 5)
            .supply(1, -5)
            .edge(0, 1, 2, 1)
            .build()
            .unwrap();
        assert_eq!(successive_shortest_paths(&problem), Ok(None));
    }

    #[test]
    fn successive_shortest_paths_respects_lower_bounds() {
        let problem = Problem::builder(3)
            .supply(0, 2)
            .supply(2, -2)
            .arc(0, 1, 1, 2, 7) // must carry at least one unit, expensively
            .arc(1, 2, 0, 2, 0)
            .arc(0, 2, 0, 2, 1)
            .build()
            .unwrap();
        let (flows, objective) = successive_shortest_paths(&problem).unwrap().unwrap();
        assert!(flows[0] >= 1);
        assert_eq!(Some(objective), brute_force(&problem).unwrap());
    }

    #[test]
    fn max_flow_value_matches_the_obvious_bottleneck() {
        assert_eq!(max_flow_value(3, &[(0, 1, 4), (1, 2, 2)], 0, 2), 2);
    }
}