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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
//! DIMACS minimum-cost-flow format.
//!
//! Implemented from the published format specification of the First DIMACS
//! Implementation Challenge [cite: DIMACS-MCF-FORMAT §7.1]. Needed for
//! benchmark corpora and cross-checking — the standard instance families are
//! all distributed in it.
//!
//! ```text
//! c  comment, ignored
//! p min <nodes> <arcs>          exactly one, before any descriptor
//! n <node> <supply>             positive supplies, negative demands
//! a <tail> <head> <low> <cap> <cost>
//! ```
//!
//! Node ids are 1-based in the file and 0-based in [`Problem`]; the reader
//! converts and the writer converts back, so a round trip is the identity.
//!
//! Two further rules the specification states: all node descriptor lines must
//! precede all arc descriptor lines, and minimum-cost flow instances carry the
//! `.min` suffix. Output (solution) lines are §7.2 of the same document.
//!
//! # Strictness
//!
//! This reader rejects rather than repairs. A truncated arc line, a node id
//! past the declared count, a second problem line, an arc count that disagrees
//! with the header — each is a distinct [`DimacsError`] variant carrying the
//! 1-based line number, because the first thing anyone does with a rejected
//! instance is open it at that line. Silently tolerating a malformed instance
//! would mean benchmarking against a network nobody described.
//!
//! No file IO happens here: the reader takes `&str` and the writer returns
//! `String`, which keeps this crate free of an IO surface and makes the fuzz
//! target trivial to drive.
//!
//! # Bounded allocation
//!
//! The problem line is a *claim* about the file, not evidence about it, and
//! this reader's input is untrusted by construction: benchmark corpora and
//! oracle-comparison files arrive as text from outside. Only the declared node
//! count is acted on before the file has been read — it sizes two per-node
//! arrays — so that is the one number weighed before anything is allocated,
//! against a limit the caller states ([`read_within`], defaulting to
//! [`DEFAULT_READ_LIMIT`]).
//!
//! Arc counts need no such guard, and deliberately do not get one: arcs are
//! appended as their lines are read, so a gigabyte of arcs costs a gigabyte of
//! input. A header over-declaring them is caught after the read, by
//! [`DimacsError::ArcCountMismatch`], which is the more useful report — it
//! says how many arcs the file actually held.

use crate::arith::{Capacity, Cost, Flow, Objective};
use crate::error::DimacsError;
use crate::problem::{Problem, ProblemBuilder};

/// Bytes [`read`] commits per node the problem line declares, before a single
/// descriptor has been seen: one [`Flow`] of supply in the builder, and one
/// flag recording whether that node's supply has already been given.
const BYTES_PER_DECLARED_NODE: u64 = size_of::<Flow>() as u64 + size_of::<bool>() as u64;

/// Memory [`read`] will commit on the strength of a problem line, in bytes.
///
/// 256 MiB, which is a declared node count of about 29.8 million. *Solving* an
/// instance that size would need a further 4 GB even with no arcs at all
/// ([`Problem::memory_estimate`] at the default feature set), so the limit
/// cannot refuse a file this crate could do anything useful with — while a
/// header claiming hundreds of millions of nodes is refused for the 28 bytes
/// of nonsense it was, in the case a fuzzer found in under a minute.
///
/// Use [`read_within`] to set a different one.
pub const DEFAULT_READ_LIMIT: u64 = 256 << 20;

/// Parse a DIMACS min-cost-flow instance, allocating at most
/// [`DEFAULT_READ_LIMIT`] bytes on the strength of its problem line.
///
/// # Errors
///
/// A [`DimacsError`] naming the line and the reason. Structural problems
/// (unbalanced supplies, bounds inverted) surface as
/// [`DimacsError::Build`]. A header declaring more nodes than the limit allows
/// gives [`DimacsError::DeclaredSizeExceedsLimit`]; use [`read_within`] to
/// raise it.
pub fn read(text: &str) -> Result<Problem, DimacsError> {
    read_within(text, DEFAULT_READ_LIMIT)
}

/// Parse a DIMACS min-cost-flow instance, allocating at most `memory_limit`
/// bytes on the strength of its problem line.
///
/// Identical to [`read`] but for the limit, which exists because a node count
/// is acted on before the file that declares it has been read. Everything else
/// the reader allocates is paid for line by line, so `memory_limit` bounds the
/// header's authority and nothing else: it is not a ceiling on the size of the
/// file, nor on the memory a later solve will need — that is
/// [`Problem::memory_estimate`], and it is a separate question with a separate
/// answer.
///
/// # Errors
///
/// As [`read`].
pub fn read_within(text: &str, memory_limit: u64) -> Result<Problem, DimacsError> {
    let mut builder: Option<ProblemBuilder> = None;
    let mut node_count = 0usize;
    let mut declared_arcs = 0usize;
    let mut arcs_seen = 0usize;
    let mut supply_seen: Vec<bool> = Vec::new();

    for (index, raw) in text.lines().enumerate() {
        let line = index + 1;
        let mut fields = raw.split_whitespace();
        let Some(tag) = fields.next() else { continue };
        let Some(tag) = single_char(tag) else {
            return Err(DimacsError::UnknownLineType { line, tag: '?' });
        };

        match tag {
            'c' => {}
            'p' => {
                if builder.is_some() {
                    return Err(DimacsError::DuplicateProblemLine { line });
                }
                let rest: Vec<&str> = fields.collect();
                if rest.len() != 3 {
                    return Err(DimacsError::FieldCount {
                        line,
                        tag,
                        expected: 3,
                        found: rest.len(),
                    });
                }
                if rest[0] != "min" {
                    return Err(DimacsError::UnsupportedProblemType {
                        line,
                        found: rest[0].to_owned(),
                    });
                }
                node_count = count(rest[1], line, 2, "node count")?;
                declared_arcs = count(rest[2], line, 3, "arc count")?;

                // The next two lines are the whole reason this reader has a
                // memory limit: they size two arrays from a number the file
                // has so far only asserted. Saturating, because the assertion
                // is untrusted — a product that wrapped would report a small
                // requirement for a huge instance and admit the very
                // allocation this check exists to refuse.
                let required = (node_count as u64).saturating_mul(BYTES_PER_DECLARED_NODE);
                if required > memory_limit {
                    return Err(DimacsError::DeclaredSizeExceedsLimit {
                        line,
                        node_count,
                        required,
                        limit: memory_limit,
                    });
                }

                supply_seen = vec![false; node_count];
                builder = Some(Problem::builder(node_count));
            }
            'n' => {
                let Some(current) = builder.take() else {
                    return Err(DimacsError::DescriptorBeforeProblem { line, tag });
                };
                let rest: Vec<&str> = fields.collect();
                if rest.len() != 2 {
                    return Err(DimacsError::FieldCount {
                        line,
                        tag,
                        expected: 2,
                        found: rest.len(),
                    });
                }
                let node = node_id(rest[0], line, 1, node_count)?;
                let supply: Flow = integer(rest[1], line, 2)?;
                if supply_seen[node] {
                    return Err(DimacsError::DuplicateSupply { line, node });
                }
                supply_seen[node] = true;
                builder = Some(current.supply(node, supply));
            }
            'a' => {
                let Some(current) = builder.take() else {
                    return Err(DimacsError::DescriptorBeforeProblem { line, tag });
                };
                let rest: Vec<&str> = fields.collect();
                if rest.len() != 5 {
                    return Err(DimacsError::FieldCount {
                        line,
                        tag,
                        expected: 5,
                        found: rest.len(),
                    });
                }
                let tail = node_id(rest[0], line, 1, node_count)?;
                let head = node_id(rest[1], line, 2, node_count)?;
                let lower: Capacity = integer(rest[2], line, 3)?;
                let upper: Capacity = integer(rest[3], line, 4)?;
                let cost: Cost = integer(rest[4], line, 5)?;
                arcs_seen += 1;
                builder = Some(current.arc(tail, head, lower, upper, cost));
            }
            other => return Err(DimacsError::UnknownLineType { line, tag: other }),
        }
    }

    let Some(builder) = builder else {
        return Err(DimacsError::MissingProblemLine);
    };
    if arcs_seen != declared_arcs {
        return Err(DimacsError::ArcCountMismatch {
            declared: declared_arcs,
            found: arcs_seen,
        });
    }
    Ok(builder.build()?)
}

/// Render `problem` in DIMACS min-cost-flow format.
///
/// `read(&write(&p))` reproduces `p` exactly, including arc order — for any
/// `p` within [`read`]'s node limit. A network built directly at a size beyond
/// it round-trips through [`read_within`] instead; the writer itself imposes
/// no limit, since a `Problem` that already exists has already been paid for.
#[must_use]
pub fn write(problem: &Problem) -> String {
    use std::fmt::Write as _;

    let mut out = String::new();
    let _ = writeln!(out, "c min-cost flow instance written by eo-mcf");
    let _ = writeln!(
        out,
        "p min {} {}",
        problem.node_count(),
        problem.arc_count()
    );
    for (node, &supply) in problem.supplies().iter().enumerate() {
        if supply != 0 {
            let _ = writeln!(out, "n {} {supply}", node + 1);
        }
    }
    for arc in problem.arcs() {
        let _ = writeln!(
            out,
            "a {} {} {} {} {}",
            arc.tail + 1,
            arc.head + 1,
            arc.lower,
            arc.upper,
            arc.cost
        );
    }
    out
}

/// Render a solution in the DIMACS solution convention: an `s` line with the
/// total cost, then one `f` line per arc carrying flow.
///
/// The `s` line is the part that carries meaning across implementations: the
/// optimal *cost* is unique even though the optimal *flow* is not.
#[must_use]
pub fn write_solution(problem: &Problem, flows: &[Flow], objective: Objective) -> String {
    use std::fmt::Write as _;

    let mut out = String::new();
    let _ = writeln!(out, "s {objective}");
    for (arc, &flow) in problem.arcs().iter().zip(flows) {
        if flow != 0 {
            let _ = writeln!(out, "f {} {} {flow}", arc.tail + 1, arc.head + 1);
        }
    }
    out
}

fn single_char(field: &str) -> Option<char> {
    let mut chars = field.chars();
    let first = chars.next()?;
    chars.next().is_none().then_some(first)
}

fn integer(text: &str, line: usize, field: usize) -> Result<i64, DimacsError> {
    text.parse::<i64>().map_err(|_| DimacsError::BadInteger {
        line,
        field,
        text: text.to_owned(),
    })
}

fn count(text: &str, line: usize, field: usize, what: &'static str) -> Result<usize, DimacsError> {
    let value = integer(text, line, field)?;
    usize::try_from(value).map_err(|_| DimacsError::BadCount { line, what, value })
}

fn node_id(text: &str, line: usize, field: usize, node_count: usize) -> Result<usize, DimacsError> {
    let value = integer(text, line, field)?;
    if value < 1 || value > node_count as i64 {
        return Err(DimacsError::NodeOutOfRange {
            line,
            node: value,
            node_count,
        });
    }
    Ok(value as usize - 1)
}

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

    const SAMPLE: &str = "\
c a four-node instance
p min 4 5
n 1 4
n 4 -4
a 1 2 0 3 1
a 2 4 0 3 1
a 1 3 0 4 3
a 3 4 0 4 3
a 2 3 0 1 0
";

    #[test]
    fn reads_a_well_formed_instance() {
        let problem = read(SAMPLE).unwrap();
        assert_eq!(problem.node_count(), 4);
        assert_eq!(problem.arc_count(), 5);
        assert_eq!(problem.supplies(), &[4, 0, 0, -4]);
        assert_eq!(problem.arcs()[0].tail, 0);
        assert_eq!(problem.arcs()[0].head, 1);
        assert_eq!(problem.arcs()[4].cost, 0);
    }

    #[test]
    fn round_trips() {
        let problem = read(SAMPLE).unwrap();
        assert_eq!(read(&write(&problem)), Ok(problem));
    }

    #[test]
    fn round_trips_lower_bounds_and_negative_costs() {
        let problem = Problem::builder(3)
            .supply(0, 5)
            .supply(2, -5)
            .arc(0, 1, 2, 6, -3)
            .arc(1, 2, 0, 9, 4)
            .build()
            .unwrap();
        assert_eq!(read(&write(&problem)), Ok(problem));
    }

    #[test]
    fn rejects_a_missing_problem_line() {
        assert_eq!(
            read("c nothing here\n"),
            Err(DimacsError::MissingProblemLine)
        );
    }

    #[test]
    fn rejects_a_second_problem_line() {
        assert_eq!(
            read("p min 2 0\np min 3 0\n"),
            Err(DimacsError::DuplicateProblemLine { line: 2 })
        );
    }

    #[test]
    fn rejects_a_descriptor_before_the_problem_line() {
        assert_eq!(
            read("n 1 5\np min 2 0\n"),
            Err(DimacsError::DescriptorBeforeProblem { line: 1, tag: 'n' })
        );
    }

    #[test]
    fn rejects_an_unknown_tag() {
        assert_eq!(
            read("p min 2 0\nx 1 2\n"),
            Err(DimacsError::UnknownLineType { line: 2, tag: 'x' })
        );
    }

    #[test]
    fn rejects_a_short_arc_line() {
        assert_eq!(
            read("p min 2 1\na 1 2 0 5\n"),
            Err(DimacsError::FieldCount {
                line: 2,
                tag: 'a',
                expected: 5,
                found: 4
            })
        );
    }

    #[test]
    fn rejects_a_non_integer_field() {
        assert_eq!(
            read("p min 2 1\na 1 2 0 five 1\n"),
            Err(DimacsError::BadInteger {
                line: 2,
                field: 4,
                text: "five".to_owned()
            })
        );
    }

    #[test]
    fn rejects_a_node_id_out_of_range() {
        assert_eq!(
            read("p min 2 1\na 1 7 0 5 1\n"),
            Err(DimacsError::NodeOutOfRange {
                line: 2,
                node: 7,
                node_count: 2
            })
        );
        assert_eq!(
            read("p min 2 1\na 0 1 0 5 1\n"),
            Err(DimacsError::NodeOutOfRange {
                line: 2,
                node: 0,
                node_count: 2
            })
        );
    }

    #[test]
    fn rejects_a_duplicate_supply() {
        assert_eq!(
            read("p min 2 0\nn 1 3\nn 1 -3\n"),
            Err(DimacsError::DuplicateSupply { line: 3, node: 0 })
        );
    }

    #[test]
    fn rejects_an_arc_count_that_disagrees_with_the_header() {
        assert_eq!(
            read("p min 2 3\na 1 2 0 5 1\n"),
            Err(DimacsError::ArcCountMismatch {
                declared: 3,
                found: 1
            })
        );
    }

    /// The input libFuzzer minimised out of the fuzz smoke campaign, byte for
    /// byte: 28 bytes, vertical tabs for separators, declaring 666 million
    /// nodes and 666 billion arcs. The reader sized two arrays from that node
    /// count on the header's word alone and ran the process out of memory.
    const FUZZ_OOM: &str = "p\u{b}min\u{b}666663165\u{b}666663165193";

    #[test]
    fn rejects_the_fuzzers_out_of_memory_header() {
        assert_eq!(FUZZ_OOM.len(), 28, "not the input that was minimised");
        let error = read(FUZZ_OOM).expect_err("28 bytes must not buy 6 GB");
        assert!(
            matches!(
                error,
                DimacsError::DeclaredSizeExceedsLimit {
                    line: 1,
                    node_count: 666_663_165,
                    limit: DEFAULT_READ_LIMIT,
                    ..
                }
            ),
            "refused for the wrong reason: {error}"
        );
    }

    #[test]
    fn rejects_an_unaffordable_node_count_with_no_arcs_at_all() {
        // The arc count in the fuzzer's input is a red herring: arcs are
        // appended as they are read and cost nothing to declare. Eighteen
        // bytes with no arc lines at all still ask for 6 GB, and the guard
        // has to be on the node count to catch it.
        let error = read("p min 666663165 0\n").expect_err("18 bytes must not buy 6 GB");
        assert!(
            matches!(error, DimacsError::DeclaredSizeExceedsLimit { .. }),
            "refused for the wrong reason: {error}"
        );
    }

    #[test]
    fn still_reads_a_large_but_affordable_instance() {
        // The guard against tuning the limit into a false positive. A million
        // isolated nodes is a legal instance, costs 9 MB to hold, and must
        // still parse.
        let problem = read("p min 1000000 0\n").unwrap();
        assert_eq!(problem.node_count(), 1_000_000);
        assert_eq!(problem.arc_count(), 0);
    }

    #[test]
    fn the_read_limit_binds_and_belongs_to_the_caller() {
        // Refusing the four-node SAMPLE at a limit of zero proves the
        // parameter is live rather than decorative, and `u64::MAX` is the
        // documented way to opt out of it entirely.
        assert!(matches!(
            read_within(SAMPLE, 0),
            Err(DimacsError::DeclaredSizeExceedsLimit {
                node_count: 4,
                limit: 0,
                ..
            })
        ));
        assert!(read_within(SAMPLE, DEFAULT_READ_LIMIT).is_ok());
        assert_eq!(read_within(SAMPLE, u64::MAX), read(SAMPLE));
    }

    #[test]
    fn the_limit_is_exact_at_the_boundary_and_raising_it_admits_the_instance() {
        // 1 000 nodes at 9 bytes each. Testing the boundary rather than an
        // order of magnitude either side is what distinguishes a limit from a
        // vibe, and it proves the raise direction too — the same instance the
        // tighter limit refuses is read by the looser one, at a size a test
        // can actually afford to allocate.
        const TEXT: &str = "p min 1000 0\n";
        let required = 1000 * BYTES_PER_DECLARED_NODE;
        assert_eq!(required, 9000);

        assert!(matches!(
            read_within(TEXT, required - 1),
            Err(DimacsError::DeclaredSizeExceedsLimit {
                required: 9000,
                limit: 8999,
                ..
            })
        ));
        let problem = read_within(TEXT, required).expect("the limit is a ceiling, not a barrier");
        assert_eq!(problem.node_count(), 1000);
    }

    #[test]
    fn an_over_declared_arc_count_is_still_reported_as_a_mismatch() {
        // Not as a size refusal. The file is tiny and the arc count is a
        // lie; saying "declares 3 000 000, holds 1" is the report that helps,
        // and a second guard on arcs would have replaced it with a worse one.
        assert_eq!(
            read("p min 2 3000000\na 1 2 0 5 1\n"),
            Err(DimacsError::ArcCountMismatch {
                declared: 3_000_000,
                found: 1
            })
        );
    }

    #[test]
    fn rejects_an_unsupported_problem_type() {
        assert_eq!(
            read("p max 2 1\n"),
            Err(DimacsError::UnsupportedProblemType {
                line: 1,
                found: "max".to_owned()
            })
        );
    }

    #[test]
    fn rejects_a_negative_declared_count() {
        assert_eq!(
            read("p min -2 0\n"),
            Err(DimacsError::BadCount {
                line: 1,
                what: "node count",
                value: -2
            })
        );
    }

    #[test]
    fn surfaces_structural_problems_from_the_builder() {
        assert_eq!(
            read("p min 2 0\nn 1 5\n"),
            Err(DimacsError::Build(BuildError::UnbalancedSupply {
                total: 5
            }))
        );
    }

    #[test]
    fn tolerates_blank_lines_and_odd_whitespace() {
        let problem = read("\np min 2 1\n\n   a   1   2   0  5  1  \n").unwrap();
        assert_eq!(problem.arc_count(), 1);
    }

    #[test]
    fn writes_a_solution_in_the_conventional_shape() {
        let problem = read(SAMPLE).unwrap();
        let rendered = write_solution(&problem, &[3, 3, 1, 1, 0], 12);
        assert!(rendered.starts_with("s 12\n"));
        assert!(rendered.contains("f 1 2 3\n"));
        assert!(!rendered.contains("f 2 3"), "zero-flow arcs are omitted");
    }
}