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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
//! Residual network in CSR form, and the normalisation that produces it.
//!
//! # Layout
//!
//! Arcs are stored grouped by tail in compressed-sparse-row order, so
//! discharging a node walks one contiguous span of `head`/`cap`/`cost`. Each
//! network arc contributes two residual entries — forward and reverse — and
//! `rev[i]` indexes the partner. Pairing by explicit index rather than by the
//! usual `i ^ 1` trick is what allows CSR grouping in the first place: the two
//! partners of an arc sit in different nodes' spans and cannot be adjacent.
//!
//! The `cap` array holds *residual* capacity, so the flow on a network arc is
//! read off its reverse entry: reverse capacity starts at zero and tracks the
//! net units pushed forward. No separate flow array is carried.
//!
//! Each entry also carries `entry_arc` — the normalised arc it belongs to and
//! a forward/backward bit. That map, not a per-arc slot table, is what
//! [`Normalized::reconstruct`] reads the answer out of. The distinction
//! matters under `heur-arc-fixing`, which reorders entries within a span:
//! a slot table would have to be re-pointed on every move and a stale slot
//! would silently misreport the flow of a correct solve, whereas `entry_arc`
//! travels with the entry it describes and cannot dangle.
//!
//! # Arc fixing (`heur-arc-fixing`)
//!
//! Each node's span is partitioned into a live prefix and a dead suffix by
//! `active_end`: entries at indices `first_out[u]..active_end[u]` are live,
//! the rest are **fixed** — proved unable to ever carry flow again
//! (`docs/ALGORITHM.md` §7.4). [`Residual::fix_pair`] retires an entry and its
//! partner by swapping each to the dead end of its own span. The solver scans
//! only live prefixes; [`Normalized::reconstruct`] still walks every entry,
//! because a fixed pair's frozen residual capacities are exactly the flow it
//! must report.
//!
//! # Normalisation
//!
//! [`normalize`] turns the caller's instance into the solver's:
//!
//! * **Lower bounds** are substituted out with `f = l + g`, `g ∈ [0, u−l]`,
//!   moving `l` units of supply from tail to head. The bound comes back in
//!   [`Normalized::reconstruct`].
//! * **Self-loops** carry flow that no conservation constraint sees, so their
//!   optimum is decided directly — `l` when the cost is non-negative, `u` when
//!   it is negative — and they are dropped from the network.
//!
//! Both are invisible to the caller and to [`crate::verify`]: the flow vector
//! that comes back speaks the caller's arcs, and the certifiers re-derive
//! everything from the original [`Problem`].

use crate::arith::{Capacity, Cost, Flow, add, neg, sub};
use crate::error::SolveError;
use crate::problem::Problem;

/// Residual network. Indices are `u32`; see [`crate::problem`] on width.
#[derive(Debug, Clone)]
pub(crate) struct Residual {
    pub(crate) node_count: usize,
    /// Start of each node's arc span; length `node_count + 1`.
    pub(crate) first_out: Vec<u32>,
    /// Head node of each residual entry.
    pub(crate) head: Vec<u32>,
    /// Index of the partner (reverse) entry.
    pub(crate) rev: Vec<u32>,
    /// Residual capacity of each entry.
    pub(crate) cap: Vec<Capacity>,
    /// Cost of each entry; the reverse entry carries the negated cost.
    pub(crate) cost: Vec<Cost>,
    /// Normalised arc of each entry, shifted left one, with the low bit set on
    /// the forward entry. Swapped along with the entry it describes, so it is
    /// correct under any reordering by construction.
    pub(crate) entry_arc: Vec<u32>,
    /// End of each node's live prefix; entries beyond it are fixed. Starts
    /// equal to `first_out[node + 1]` and only ever moves down.
    #[cfg(feature = "heur-arc-fixing")]
    pub(crate) active_end: Vec<u32>,
}

impl Residual {
    /// End of `node`'s live span: entries past it are fixed and provably
    /// unable to carry flow again, so no solver loop needs to look at them.
    /// Without `heur-arc-fixing` this is simply the end of the span.
    #[inline]
    pub(crate) fn live_end(&self, node: usize) -> u32 {
        #[cfg(feature = "heur-arc-fixing")]
        {
            self.active_end[node]
        }
        #[cfg(not(feature = "heur-arc-fixing"))]
        {
            self.first_out[node + 1]
        }
    }

    /// Live residual entry indices leaving `node`.
    #[inline]
    pub(crate) fn out_arcs(&self, node: usize) -> std::ops::Range<usize> {
        self.first_out[node] as usize..self.live_end(node) as usize
    }

    /// Move `delta` units along residual entry `arc`.
    #[inline]
    pub(crate) fn push(&mut self, arc: usize, delta: Capacity) {
        self.cap[arc] -= delta;
        let r = self.rev[arc] as usize;
        self.cap[r] += delta;
    }

    /// Retire `entry` (tail `tail`) and its partner: swap each to the dead end
    /// of its own node's span and shrink both live prefixes.
    ///
    /// The two sit in different spans — self-loops are removed by
    /// normalisation — so the first swap cannot move the partner, and neither
    /// swap can involve both at once. Callers must not hold entry indices
    /// across this call except `first_out`-relative span positions; the solver
    /// only fixes at points immediately followed by a current-arc reset.
    #[cfg(feature = "heur-arc-fixing")]
    pub(crate) fn fix_pair(&mut self, entry: usize, tail: usize) {
        let partner = self.rev[entry] as usize;
        let head = self.head[entry] as usize;
        debug_assert_ne!(tail, head, "self-loops are removed by normalisation");
        self.retire(entry, tail);
        // `partner` still names the same entry: `retire` swaps only inside
        // `tail`'s span, and the partner lives in `head`'s.
        self.retire(partner, head);
    }

    /// Swap `entry` to the last live position of `node`'s span and shrink the
    /// live prefix over it.
    #[cfg(feature = "heur-arc-fixing")]
    fn retire(&mut self, entry: usize, node: usize) {
        let last = self.active_end[node] as usize - 1;
        self.active_end[node] = last as u32;
        if entry == last {
            return;
        }
        self.head.swap(entry, last);
        self.cap.swap(entry, last);
        self.cost.swap(entry, last);
        self.entry_arc.swap(entry, last);
        self.rev.swap(entry, last);
        // Re-point the partners at the entries' new homes. The two movers are
        // never partners of each other — partners sit in different spans.
        let partner_of_entry = self.rev[entry] as usize;
        let partner_of_last = self.rev[last] as usize;
        self.rev[partner_of_entry] = entry as u32;
        self.rev[partner_of_last] = last as u32;
    }
}

/// The caller's instance rewritten in the solver's terms.
#[derive(Debug, Clone)]
pub(crate) struct Normalized {
    pub(crate) res: Residual,
    /// Node excesses: the supplies after lower bounds were substituted out.
    pub(crate) excess: Vec<Flow>,
    /// Original arc index of each normalised arc.
    origin: Vec<u32>,
    /// Lower bound removed from each normalised arc.
    lower: Vec<Capacity>,
    /// Self-loops resolved directly: original arc index and its forced flow.
    forced: Vec<(u32, Flow)>,
    /// Arc count of the original instance.
    original_arcs: usize,
}

impl Normalized {
    /// Forward arcs as `(tail, head, capacity)`.
    ///
    /// Capacities here are *residual*, so this is only the arc list of the
    /// original network while the flow is still zero — which is exactly when
    /// the feasibility pre-check runs, and nowhere else. Order is entry order,
    /// which the max-flow value does not depend on.
    pub(crate) fn forward_arcs(&self) -> impl Iterator<Item = (u32, u32, Capacity)> + '_ {
        self.res
            .entry_arc
            .iter()
            .enumerate()
            .filter(|&(_, &tag)| tag & 1 == 1)
            .map(move |(i, _)| {
                let tail = self.res.head[self.res.rev[i] as usize];
                (tail, self.res.head[i], self.res.cap[i])
            })
    }

    /// Rebuild the caller's flow vector, one entry per original arc, with
    /// lower bounds added back and resolved self-loops filled in.
    ///
    /// Walks every entry — fixed ones included, since a fixed pair's frozen
    /// residual capacities *are* the flow it reports — and reads each arc's
    /// flow off its backward entry, whose residual capacity is exactly the net
    /// units pushed forward. Keying by the entry's own `entry_arc` tag rather
    /// than by an arc-indexed slot table means reorderings cannot dangle it.
    pub(crate) fn reconstruct(&self) -> Vec<Flow> {
        let mut flows = vec![0; self.original_arcs];
        for (i, &tag) in self.res.entry_arc.iter().enumerate() {
            if tag & 1 == 0 {
                let j = (tag >> 1) as usize;
                flows[self.origin[j] as usize] = self.lower[j] + self.res.cap[i];
            }
        }
        for &(arc, flow) in &self.forced {
            flows[arc as usize] = flow;
        }
        flows
    }

    /// Forward residual entry of normalised arc `j`. Test-only: product code
    /// never addresses an entry by arc — that is what `entry_arc` is for.
    #[cfg(test)]
    pub(crate) fn forward_entry_of(&self, j: usize) -> usize {
        let tag = (j as u32) << 1 | 1;
        self.res
            .entry_arc
            .iter()
            .position(|&t| t == tag)
            .expect("normalised arc has a forward entry")
    }
}

/// Rewrite `problem` into a residual network with zero lower bounds and no
/// self-loops.
pub(crate) fn normalize(problem: &Problem) -> Result<Normalized, SolveError> {
    let node_count = problem.node_count();
    let mut excess = problem.supplies().to_vec();

    let mut tails: Vec<u32> = Vec::with_capacity(problem.arc_count());
    let mut heads: Vec<u32> = Vec::with_capacity(problem.arc_count());
    let mut caps: Vec<Capacity> = Vec::with_capacity(problem.arc_count());
    let mut costs: Vec<Cost> = Vec::with_capacity(problem.arc_count());
    let mut origin: Vec<u32> = Vec::with_capacity(problem.arc_count());
    let mut lower: Vec<Capacity> = Vec::with_capacity(problem.arc_count());
    let mut forced: Vec<(u32, Flow)> = Vec::new();

    for (k, arc) in problem.arcs().iter().enumerate() {
        let index = u32::try_from(k).map_err(|_| SolveError::InvariantViolated {
            what: "arc index exceeds u32 after a successful build",
        })?;

        if arc.tail == arc.head {
            // A self-loop is unconstrained by conservation, so its optimum is
            // an endpoint of its bound interval.
            let flow = if arc.cost >= 0 { arc.lower } else { arc.upper };
            forced.push((index, flow));
            continue;
        }

        // f = lower + g. The forced `lower` units leave the tail and arrive at
        // the head whatever `g` turns out to be.
        excess[arc.tail] = sub(
            excess[arc.tail],
            arc.lower,
            "supply after lower-bound substitution",
        )?;
        excess[arc.head] = add(
            excess[arc.head],
            arc.lower,
            "supply after lower-bound substitution",
        )?;

        tails.push(u32::try_from(arc.tail).unwrap_or(u32::MAX));
        heads.push(u32::try_from(arc.head).unwrap_or(u32::MAX));
        caps.push(sub(
            arc.upper,
            arc.lower,
            "arc capacity after lower-bound substitution",
        )?);
        costs.push(arc.cost);
        origin.push(index);
        lower.push(arc.lower);
    }

    let res = build_csr(node_count, &tails, &heads, &caps, &costs)?;

    Ok(Normalized {
        res,
        excess,
        origin,
        lower,
        forced,
        original_arcs: problem.arc_count(),
    })
}

/// Build the CSR residual network.
fn build_csr(
    node_count: usize,
    tails: &[u32],
    heads: &[u32],
    caps: &[Capacity],
    costs: &[Cost],
) -> Result<Residual, SolveError> {
    let entries = tails.len() * 2;
    let mut first_out = vec![0u32; node_count + 1];

    // Out-degree of each node counts both directions: an arc u→v puts a
    // forward entry in u's span and a reverse entry in v's.
    for (&u, &v) in tails.iter().zip(heads) {
        first_out[u as usize + 1] += 1;
        first_out[v as usize + 1] += 1;
    }
    for i in 0..node_count {
        first_out[i + 1] += first_out[i];
    }

    let mut head = vec![0u32; entries];
    let mut rev = vec![0u32; entries];
    let mut cap = vec![0 as Capacity; entries];
    let mut cost = vec![0 as Cost; entries];
    let mut entry_arc = vec![0u32; entries];

    // Cursor per node, advanced as entries are placed into its span.
    let mut cursor: Vec<u32> = first_out[..node_count].to_vec();

    for k in 0..tails.len() {
        let (u, v) = (tails[k] as usize, heads[k] as usize);
        let forward = cursor[u];
        cursor[u] += 1;
        let backward = cursor[v];
        cursor[v] += 1;

        // Normalised arc indices fit u32 shifted one left: the residual entry
        // index 2k+1 fits u32 by MAX_ARCS, and k << 1 < 2k + 1.
        let tag = (u32::try_from(k).map_err(|_| SolveError::InvariantViolated {
            what: "normalised arc index exceeds u32 after a successful build",
        })?) << 1;

        let (fi, bi) = (forward as usize, backward as usize);
        head[fi] = heads[k];
        cap[fi] = caps[k];
        cost[fi] = costs[k];
        rev[fi] = backward;
        entry_arc[fi] = tag | 1;

        head[bi] = tails[k];
        cap[bi] = 0;
        cost[bi] = neg(costs[k], "reverse arc cost")?;
        rev[bi] = forward;
        entry_arc[bi] = tag;
    }

    Ok(Residual {
        node_count,
        #[cfg(feature = "heur-arc-fixing")]
        active_end: first_out[1..].to_vec(),
        first_out,
        head,
        rev,
        cap,
        cost,
        entry_arc,
    })
}

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

    #[test]
    fn csr_spans_partition_the_entries_and_pair_correctly() {
        let p = Problem::builder(3)
            .supply(0, 1)
            .supply(2, -1)
            .edge(0, 1, 4, 7)
            .edge(1, 2, 5, -2)
            .build()
            .unwrap();
        let norm = normalize(&p).unwrap();
        let res = &norm.res;

        assert_eq!(res.first_out.len(), 4);
        assert_eq!(*res.first_out.last().unwrap() as usize, res.head.len());
        assert_eq!(res.head.len(), 4);

        for i in 0..res.head.len() {
            let partner = res.rev[i] as usize;
            assert_eq!(res.rev[partner] as usize, i, "rev must be an involution");
            assert_eq!(
                res.cost[partner], -res.cost[i],
                "partner carries the negated cost"
            );
        }
        // Each node's span really does contain arcs leaving that node.
        for u in 0..res.node_count {
            for a in res.out_arcs(u) {
                let v = res.head[a] as usize;
                assert_eq!(res.head[res.rev[a] as usize] as usize, u);
                assert_ne!(u, v);
            }
        }
    }

    #[test]
    fn lower_bounds_move_supply_and_come_back_on_reconstruct() {
        // One arc 0→1 forced to carry at least 3 of its 5 units.
        let p = Problem::builder(2)
            .supply(0, 4)
            .supply(1, -4)
            .arc(0, 1, 3, 5, 1)
            .build()
            .unwrap();
        let mut norm = normalize(&p).unwrap();

        // 3 units are pre-routed, so only 1 remains to be pushed.
        assert_eq!(norm.excess, vec![1, -1]);
        let forward = norm.forward_entry_of(0);
        assert_eq!(norm.res.cap[forward], 2, "residual span is upper − lower");

        // Push the remaining unit and check the caller sees 3 + 1.
        norm.res.push(forward, 1);
        assert_eq!(norm.reconstruct(), vec![4]);
    }

    /// Every entry names its arc, forward and backward entries pair up, and
    /// the tags survive whatever order the CSR build placed things in.
    #[test]
    fn entry_arc_tags_are_a_partner_respecting_bijection() {
        let p = Problem::builder(4)
            .supply(0, 2)
            .supply(3, -2)
            .edge(0, 1, 4, 7)
            .edge(1, 3, 5, -2)
            .edge(0, 2, 3, 1)
            .edge(2, 3, 3, 1)
            .edge(1, 2, 2, 0) // parallel structure and a zero cost
            .build()
            .unwrap();
        let norm = normalize(&p).unwrap();
        let res = &norm.res;

        let mut seen = [0u32; 5];
        for i in 0..res.head.len() {
            let tag = res.entry_arc[i];
            let partner = res.rev[i] as usize;
            assert_eq!(
                res.entry_arc[partner],
                tag ^ 1,
                "partners describe the same arc from opposite ends"
            );
            seen[(tag >> 1) as usize] += 1;
        }
        assert!(seen.iter().all(|&count| count == 2), "one pair per arc");
    }

    #[cfg(feature = "heur-arc-fixing")]
    #[test]
    fn fix_pair_retires_both_entries_and_preserves_every_invariant() {
        let p = Problem::builder(4)
            .supply(0, 2)
            .supply(3, -2)
            .edge(0, 1, 4, 7)
            .edge(0, 2, 3, 1)
            .edge(0, 3, 5, 9)
            .edge(1, 3, 4, 2)
            .edge(2, 3, 3, 1)
            .build()
            .unwrap();
        let mut norm = normalize(&p).unwrap();

        // Route one unit along 0→2→3 so reconstruct has something to report,
        // then fix arc 1 (0→2) and arc 3 (1→3).
        let via = norm.forward_entry_of(1);
        norm.res.push(via, 1);
        let via = norm.forward_entry_of(4);
        norm.res.push(via, 1);

        for arc in [1usize, 3] {
            let entry = norm.forward_entry_of(arc);
            let tail = norm.res.head[norm.res.rev[entry] as usize] as usize;
            norm.res.fix_pair(entry, tail);
        }

        let res = &norm.res;
        for node in 0..res.node_count {
            assert!(res.active_end[node] >= res.first_out[node]);
            assert!(res.active_end[node] <= res.first_out[node + 1]);
        }
        // Fixed pairs sit outside every live span; live entries sit inside.
        let live: Vec<bool> = (0..res.node_count)
            .flat_map(|u| {
                (res.first_out[u]..res.first_out[u + 1]).map(move |i| i < res.active_end[u])
            })
            .collect();
        let mut dead_arcs: Vec<u32> = (0..res.head.len())
            .filter(|&i| !live[i])
            .map(|i| res.entry_arc[i] >> 1)
            .collect();
        dead_arcs.sort_unstable();
        assert_eq!(dead_arcs, [1, 1, 3, 3], "exactly the fixed pairs died");

        // The swaps must leave rev an involution onto the same arc…
        for i in 0..res.head.len() {
            let partner = res.rev[i] as usize;
            assert_eq!(res.rev[partner] as usize, i, "rev is an involution");
            assert_eq!(res.entry_arc[partner], res.entry_arc[i] ^ 1);
            assert_eq!(res.cost[partner], -res.cost[i]);
        }
        // …and the flow readout must be exactly what was pushed, fixed arcs
        // included: a stale mapping here is the silent failure the ticket
        // calls highest-risk.
        assert_eq!(norm.reconstruct(), vec![0, 1, 0, 0, 1]);
    }

    #[test]
    fn self_loops_are_resolved_and_removed() {
        let p = Problem::builder(2)
            .supply(0, 1)
            .supply(1, -1)
            .arc(0, 0, 2, 9, 5) // non-negative cost → sits at its lower bound
            .arc(1, 1, 2, 9, -5) // negative cost → saturates
            .edge(0, 1, 1, 0)
            .build()
            .unwrap();
        let norm = normalize(&p).unwrap();
        assert_eq!(norm.res.head.len(), 2, "only the real arc survives");
        let flows = norm.reconstruct();
        assert_eq!(flows[0], 2);
        assert_eq!(flows[1], 9);
    }

    #[test]
    fn reverse_cost_negation_overflow_is_an_error_not_a_wrap() {
        let p = Problem::builder(2)
            .supply(0, 0)
            .edge(0, 1, 1, i64::MIN)
            .build()
            .unwrap();
        assert!(matches!(normalize(&p), Err(SolveError::Overflow(_))));
    }
}