Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
tpl_maxflow_test.cc
Go to the documentation of this file.
1/* Tests for tpl_maxflow.H - Advanced maximum flow algorithms
2 *
3 * Tests cover:
4 * - Dinic's algorithm
5 * - Capacity scaling
6 * - Flow decomposition
7 * - HLPP (Highest Label Preflow-Push)
8 * - Flow statistics
9 */
10
11#include <gtest/gtest.h>
12#include <tpl_maxflow.H>
13#include <tpl_net.H>
14#include <array>
15#include <chrono>
16#include <limits>
17#include <random>
18#include <set>
19#include <stdexcept>
20#include <vector>
21
22using namespace Aleph;
23
24namespace
25{
26 // Network type for tests
28 using Node = TestNet::Node;
29 using Arc = TestNet::Arc;
30
31 // Build a simple linear network: s -> a -> b -> t
32 // Returns the source node
33 Node* build_linear_network(TestNet& net)
34 {
35 auto s = net.insert_node(0);
36 auto a = net.insert_node(1);
37 auto b = net.insert_node(2);
38 auto t = net.insert_node(3);
39
40 net.insert_arc(s, a, 10); // cap=10
41 net.insert_arc(a, b, 5); // cap=5 (bottleneck)
42 net.insert_arc(b, t, 10); // cap=10
43
44 return s;
45 }
46
47 // Build a diamond network: s -> a,b -> t
48 Node* build_diamond_network(TestNet& net)
49 {
50 auto s = net.insert_node(0);
51 auto a = net.insert_node(1);
52 auto b = net.insert_node(2);
53 auto t = net.insert_node(3);
54
55 net.insert_arc(s, a, 10); // cap=10
56 net.insert_arc(s, b, 10); // cap=10
57 net.insert_arc(a, t, 10); // cap=10
58 net.insert_arc(b, t, 10); // cap=10
59
60 return s;
61 }
62
63 // Build a complex network with multiple paths
64 Node* build_complex_network(TestNet& net)
65 {
66 auto s = net.insert_node(0);
67 auto a = net.insert_node(1);
68 auto b = net.insert_node(2);
69 auto c = net.insert_node(3);
70 auto d = net.insert_node(4);
71 auto t = net.insert_node(5);
72
73 net.insert_arc(s, a, 16);
74 net.insert_arc(s, b, 13);
75 net.insert_arc(a, b, 10);
76 net.insert_arc(a, c, 12);
77 net.insert_arc(b, a, 4);
78 net.insert_arc(b, d, 14);
79 net.insert_arc(c, b, 9);
80 net.insert_arc(c, t, 20);
81 net.insert_arc(d, c, 7);
82 net.insert_arc(d, t, 4);
83
84 return s;
85 }
86
87 // Build a grid network with directed arcs (flow only goes right and down)
88 // This ensures single source (top-left) and single sink (bottom-right)
89 Node* build_grid_network(TestNet& net, int rows, int cols, double capacity)
90 {
91 std::vector<std::vector<Node*>> nodes(rows, std::vector<Node*>(cols));
92 int id = 0;
93
94 // Create nodes
95 for (int i = 0; i < rows; ++i)
96 for (int j = 0; j < cols; ++j)
97 nodes[i][j] = net.insert_node(id++);
98
99 // Create horizontal arcs (left to right only)
100 for (int i = 0; i < rows; ++i)
101 for (int j = 0; j < cols - 1; ++j)
102 net.insert_arc(nodes[i][j], nodes[i][j+1], capacity);
103
104 // Create vertical arcs (top to bottom only)
105 for (int i = 0; i < rows - 1; ++i)
106 for (int j = 0; j < cols; ++j)
107 net.insert_arc(nodes[i][j], nodes[i+1][j], capacity);
108
109 return nodes[0][0];
110 }
111
112 [[maybe_unused]] void reset_flow(TestNet& net)
113 {
114 for (Arc_Iterator<TestNet> it(net); it.has_curr(); it.next_ne())
115 it.get_curr()->flow = 0;
116 }
117}
118
119
120//==============================================================================
121// Dinic's Algorithm Tests
122//==============================================================================
123
124TEST(DinicTest, LinearNetwork)
125{
126 TestNet net;
127 build_linear_network(net);
128
129 const auto flow = dinic_maximum_flow(net);
130
131 EXPECT_DOUBLE_EQ(flow, 5.0); // Bottleneck is middle arc
132 EXPECT_TRUE(net.check_network());
133}
134
135TEST(DinicTest, DiamondNetwork)
136{
137 TestNet net;
138 build_diamond_network(net);
139
140 const auto flow = dinic_maximum_flow(net);
141 (void)flow;
142
143 EXPECT_DOUBLE_EQ(flow, 20.0); // Both paths can carry 10
144 EXPECT_TRUE(net.check_network());
145}
146
147TEST(DinicTest, ComplexNetwork)
148{
149 TestNet net;
150 build_complex_network(net);
151
152 auto flow = dinic_maximum_flow(net);
153
154 // Known max flow for this network is 23
155 EXPECT_DOUBLE_EQ(flow, 23.0);
156 EXPECT_TRUE(net.check_network());
157}
158
159TEST(DinicTest, ZeroCapacity)
160{
161 // Test with zero capacity arc - should give zero flow
162 TestNet net;
163 auto s = net.insert_node(0);
164 auto t = net.insert_node(1);
165
166 net.insert_arc(s, t, 0); // Zero capacity
167
168 auto flow = dinic_maximum_flow(net);
169 EXPECT_DOUBLE_EQ(flow, 0.0);
170}
171
172TEST(DinicTest, SingleArc)
173{
174 TestNet net;
175 auto s = net.insert_node(0);
176 auto t = net.insert_node(1);
177 net.insert_arc(s, t, 42);
178
179 auto flow = dinic_maximum_flow(net);
180 EXPECT_DOUBLE_EQ(flow, 42.0);
181}
182
183
184//==============================================================================
185// Capacity Scaling Tests
186//==============================================================================
187
188TEST(CapacityScalingTest, LinearNetwork)
189{
190 TestNet net;
191 build_linear_network(net);
192
193 auto flow = capacity_scaling_maximum_flow(net);
194
195 EXPECT_DOUBLE_EQ(flow, 5.0);
196 EXPECT_TRUE(net.check_network());
197}
198
199TEST(CapacityScalingTest, DiamondNetwork)
200{
201 TestNet net;
202 build_diamond_network(net);
203
204 auto flow = capacity_scaling_maximum_flow(net);
205
206 EXPECT_DOUBLE_EQ(flow, 20.0);
207 EXPECT_TRUE(net.check_network());
208}
209
210TEST(CapacityScalingTest, ComplexNetwork)
211{
212 TestNet net;
213 build_complex_network(net);
214
215 auto flow = capacity_scaling_maximum_flow(net);
216
217 EXPECT_DOUBLE_EQ(flow, 23.0);
218 EXPECT_TRUE(net.check_network());
219}
220
221TEST(CapacityScalingTest, LargeCapacities)
222{
223 TestNet net;
224 auto s = net.insert_node(0);
225 auto a = net.insert_node(1);
226 auto t = net.insert_node(2);
227
228 net.insert_arc(s, a, 1000000);
229 net.insert_arc(a, t, 1000000);
230
231 auto flow = capacity_scaling_maximum_flow(net);
232 EXPECT_DOUBLE_EQ(flow, 1000000.0);
233}
234
235
236//==============================================================================
237// HLPP Tests
238//==============================================================================
239
240TEST(HLPPTest, LinearNetwork)
241{
242 TestNet net;
243 build_linear_network(net);
244
245 auto flow = hlpp_maximum_flow(net);
246
247 EXPECT_DOUBLE_EQ(flow, 5.0);
248 EXPECT_TRUE(net.check_network());
249}
250
251TEST(HLPPTest, DiamondNetwork)
252{
253 TestNet net;
254 build_diamond_network(net);
255
256 auto flow = hlpp_maximum_flow(net);
257
258 EXPECT_DOUBLE_EQ(flow, 20.0);
259 EXPECT_TRUE(net.check_network());
260}
261
262TEST(HLPPTest, ComplexNetwork)
263{
264 TestNet net;
265 build_complex_network(net);
266
267 auto flow = hlpp_maximum_flow(net);
268
269 EXPECT_DOUBLE_EQ(flow, 23.0);
270 EXPECT_TRUE(net.check_network());
271}
272
273
274//==============================================================================
275// Flow Decomposition Tests
276//==============================================================================
277
278TEST(FlowDecompositionTest, LinearFlow)
279{
280 TestNet net;
281 build_linear_network(net);
283
284 auto decomp = decompose_flow(net);
285
286 EXPECT_EQ(decomp.num_paths(), 1);
287 EXPECT_DOUBLE_EQ(decomp.total_flow(), 5.0);
288}
289
290TEST(FlowDecompositionTest, DiamondFlow)
291{
292 TestNet net;
293 build_diamond_network(net);
295
296 auto decomp = decompose_flow(net);
297
298 // Should decompose into 2 paths (through a and through b)
299 EXPECT_EQ(decomp.num_paths(), 2);
300 EXPECT_DOUBLE_EQ(decomp.total_flow(), 20.0);
301}
302
303TEST(FlowDecompositionTest, ComplexFlow)
304{
305 TestNet net;
306 build_complex_network(net);
308
309 auto decomp = decompose_flow(net);
310
311 // Total flow should match
312 EXPECT_DOUBLE_EQ(decomp.total_flow(), 23.0);
313 // Should have multiple paths
314 EXPECT_GT(decomp.num_paths(), 1);
315}
316
317TEST(FlowDecompositionTest, ZeroFlow)
318{
319 // Build a network with a path but zero flow
320 TestNet net;
321 auto s = net.insert_node(0);
322 auto a = net.insert_node(1);
323 auto t = net.insert_node(2);
324
325 net.insert_arc(s, a, 10);
326 net.insert_arc(a, t, 10);
327 // Don't run max-flow, so all arcs have 0 flow
328
329 auto decomp = decompose_flow(net);
330
331 EXPECT_EQ(decomp.num_paths(), 0);
332 EXPECT_DOUBLE_EQ(decomp.total_flow(), 0.0);
333}
334
335TEST(FlowDecompositionTest, CycleDetection)
336{
337 // Build a network with a cycle: s -> a -> b -> a (cycle a-b-a) -> t
338 TestNet net;
339 auto s = net.insert_node(0);
340 auto a = net.insert_node(1);
341 auto b = net.insert_node(2);
342 auto t = net.insert_node(3);
343
344 // Main path s -> a -> t
345 auto arc_sa = net.insert_arc(s, a, 10);
346 auto arc_at = net.insert_arc(a, t, 10);
347
348 // Cycle a -> b -> a
349 auto arc_ab = net.insert_arc(a, b, 5);
350 auto arc_ba = net.insert_arc(b, a, 5);
351
352 // Manually set flow to create a cycle
353 // Flow goes s -> a -> t (5 units)
354 // And circulates a -> b -> a (5 units)
355 arc_sa->flow = 5;
356 arc_at->flow = 5;
357 arc_ab->flow = 5;
358 arc_ba->flow = 5;
359
360 // Verify manual flow setup is valid (conservation holds)
361 // Node a: in=5(s)+5(b)=10, out=5(t)+5(b)=10. OK.
362 // Node b: in=5(a), out=5(a). OK.
363
364 auto decomp = decompose_flow(net);
365
366 // Should have 1 path (s->a->t) and 1 cycle (a->b->a)
367 EXPECT_EQ(decomp.num_paths(), 1);
368 EXPECT_EQ(decomp.num_cycles(), 1);
369
370 EXPECT_DOUBLE_EQ(decomp.total_flow(), 5.0); // Only path flow counts towards total s-t flow
371
372 // Verify cycle details
373 const auto& cycle = decomp.cycles.get_first();
374 EXPECT_DOUBLE_EQ(cycle.flow, 5.0);
375
376 // Verify path details
377 const auto& path = decomp.paths.get_first();
378 EXPECT_DOUBLE_EQ(path.flow, 5.0);
379}
380
381
382//==============================================================================
383// Flow Statistics Tests
384//==============================================================================
385
386TEST(FlowStatisticsTest, BeforeFlow)
387{
388 TestNet net;
389 build_diamond_network(net);
390
391 auto stats = compute_flow_statistics(net);
392
393 EXPECT_DOUBLE_EQ(stats.total_capacity, 40.0);
394 EXPECT_EQ(stats.num_empty_arcs, 4);
395 EXPECT_EQ(stats.num_saturated_arcs, 0);
396 EXPECT_EQ(stats.num_partial_arcs, 0);
397}
398
399TEST(FlowStatisticsTest, AfterFlow)
400{
401 TestNet net;
402 build_diamond_network(net);
404
405 auto stats = compute_flow_statistics(net);
406
407 EXPECT_DOUBLE_EQ(stats.total_flow, 20.0);
408 EXPECT_DOUBLE_EQ(stats.utilization, 0.5); // 20/40
409}
410
411
412//==============================================================================
413// Min-Cut Validation Tests (Max-Flow Min-Cut Theorem)
414//==============================================================================
415
416// Helper function to compute min-cut capacity by BFS from source
417template <class Net>
419{
420 using Node = typename Net::Node;
421 using Arc = typename Net::Arc;
422
423 auto source = net.get_source();
424 (void)net.get_sink();
425
426 // Find reachable nodes from source via residual network
427 std::set<Node*> reachable;
429
430 reachable.insert(source);
431 q.put(source);
432
433 while (!q.is_empty())
434 {
435 Node* u = q.front();
436 q.get();
437
438 // Explore all adjacent arcs
439 for (typename Net::Node_Arc_Iterator it(u); it.has_curr(); it.next_ne())
440 {
441 Arc* arc = it.get_curr();
442 Node* v = net.get_connected_node(arc, u);
443
444 if (reachable.count(v) > 0)
445 continue; // Already visited
446
447 // Check if there is residual capacity
448 bool forward = (net.get_src_node(arc) == u);
449 double residual = forward ? (arc->cap - arc->flow) : arc->flow;
450
451 if (residual > 1e-9) // Has residual capacity
452 {
453 reachable.insert(v);
454 q.put(v);
455 }
456 }
457 }
458
459 // Compute cut capacity: sum of capacities of arcs from reachable to non-reachable
460 double cut_capacity = 0.0;
461
462 for (auto u : reachable)
463 {
464 for (Out_Iterator<Net> it(u); it.has_curr(); it.next_ne())
465 {
466 Arc* arc = it.get_curr();
467 Node* v = net.get_tgt_node(arc);
468
469 if (reachable.count(v) == 0) // Arc crosses the cut
470 cut_capacity += arc->cap;
471 }
472 }
473
474 return cut_capacity;
475}
476
477// Helper to verify max-flow = min-cut
478template <class Net>
479bool verify_max_flow_min_cut(Net& net, double max_flow)
480{
481 double min_cut = compute_min_cut_capacity(net);
482 return std::abs(max_flow - min_cut) < 1e-6;
483}
484
485TEST(MinCutTest, LinearNetwork)
486{
487 TestNet net;
488 build_linear_network(net);
489
490 auto flow = dinic_maximum_flow(net);
491
492 // Verify max-flow = min-cut theorem
493 EXPECT_TRUE(verify_max_flow_min_cut(net, flow));
494
495 // The min-cut should be at the bottleneck (middle arc with cap=5)
496 double min_cut = compute_min_cut_capacity(net);
497 EXPECT_DOUBLE_EQ(min_cut, 5.0);
498}
499
500TEST(MinCutTest, DiamondNetwork)
501{
502 TestNet net;
503 build_diamond_network(net);
504
505 auto flow = dinic_maximum_flow(net);
506
507 EXPECT_TRUE(verify_max_flow_min_cut(net, flow));
508
509 double min_cut = compute_min_cut_capacity(net);
510 EXPECT_DOUBLE_EQ(min_cut, 20.0);
511}
512
513TEST(MinCutTest, ComplexNetwork)
514{
515 TestNet net;
516 build_complex_network(net);
517
518 auto flow = dinic_maximum_flow(net);
519
520 EXPECT_TRUE(verify_max_flow_min_cut(net, flow));
521
522 double min_cut = compute_min_cut_capacity(net);
523 EXPECT_DOUBLE_EQ(min_cut, 23.0);
524}
525
526TEST(MinCutTest, GridNetwork)
527{
528 TestNet net;
529 build_grid_network(net, 5, 5, 10);
530
531 auto flow = edmonds_karp_maximum_flow(net);
532
533 EXPECT_TRUE(verify_max_flow_min_cut(net, flow));
534}
535
536TEST(MinCutTest, SingleBottleneck)
537{
538 // Build network where min-cut is obvious
539 TestNet net;
540 auto s = net.insert_node(0);
541 auto a = net.insert_node(1);
542 auto b = net.insert_node(2);
543 auto t = net.insert_node(3);
544
545 // Wide source side, narrow bottleneck, wide sink side
546 net.insert_arc(s, a, 100);
547 net.insert_arc(s, b, 100);
548 net.insert_arc(a, t, 5); // Bottleneck
549 net.insert_arc(b, t, 5); // Bottleneck
550
551 auto flow = dinic_maximum_flow(net);
552
553 EXPECT_DOUBLE_EQ(flow, 10.0);
554 EXPECT_TRUE(verify_max_flow_min_cut(net, flow));
555
556 double min_cut = compute_min_cut_capacity(net);
557 EXPECT_DOUBLE_EQ(min_cut, 10.0);
558}
559
560TEST(MinCutTest, ParallelArcs)
561{
562 TestNet net;
563 auto s = net.insert_node(0);
564 auto t = net.insert_node(1);
565
566 // Three parallel arcs
567 net.insert_arc(s, t, 10);
568 net.insert_arc(s, t, 20);
569 net.insert_arc(s, t, 30);
570
571 auto flow = dinic_maximum_flow(net);
572
573 EXPECT_DOUBLE_EQ(flow, 60.0);
574 EXPECT_TRUE(verify_max_flow_min_cut(net, flow));
575
576 double min_cut = compute_min_cut_capacity(net);
577 EXPECT_DOUBLE_EQ(min_cut, 60.0);
578}
579
580TEST(MinCutTest, AllAlgorithmsGiveSameMinCut)
581{
582 // Build 4 identical networks
583 TestNet net1, net2, net3, net4;
584 build_complex_network(net1);
585 build_complex_network(net2);
586 build_complex_network(net3);
587 build_complex_network(net4);
588
589 auto flow_ff = ford_fulkerson_maximum_flow(net1);
590 auto flow_ek = edmonds_karp_maximum_flow(net2);
591 auto flow_dinic = dinic_maximum_flow(net3);
592 auto flow_cs = capacity_scaling_maximum_flow(net4);
593
594 // All should satisfy max-flow = min-cut
595 EXPECT_TRUE(verify_max_flow_min_cut(net1, flow_ff));
596 EXPECT_TRUE(verify_max_flow_min_cut(net2, flow_ek));
597 EXPECT_TRUE(verify_max_flow_min_cut(net3, flow_dinic));
598 EXPECT_TRUE(verify_max_flow_min_cut(net4, flow_cs));
599
600 // All min-cuts should be equal
601 double cut1 = compute_min_cut_capacity(net1);
602 double cut2 = compute_min_cut_capacity(net2);
603 double cut3 = compute_min_cut_capacity(net3);
604 double cut4 = compute_min_cut_capacity(net4);
605
606 EXPECT_DOUBLE_EQ(cut1, cut2);
607 EXPECT_DOUBLE_EQ(cut2, cut3);
608 EXPECT_DOUBLE_EQ(cut3, cut4);
609}
610
611TEST(MinCutTest, VerifyCutPartition)
612{
613 // Verify that the cut actually partitions the graph correctly
614 TestNet net;
615 build_diamond_network(net);
616
617 const auto flow = dinic_maximum_flow(net);
618 (void)flow;
619
620 auto source = net.get_source();
621 auto sink = net.get_sink();
622
623 // Find reachable set from source
624 std::set<Node*> S_side; // Source side of cut
626
627 S_side.insert(source);
628 q.put(source);
629
630 while (!q.is_empty())
631 {
632 Node* u = q.front();
633 q.get();
634
635 for (typename TestNet::Node_Arc_Iterator it(u); it.has_curr(); it.next_ne())
636 {
637 Arc* arc = it.get_curr();
638 Node* v = net.get_connected_node(arc, u);
639
640 if (S_side.count(v) > 0)
641 continue;
642
643 bool forward = (net.get_src_node(arc) == u);
644 double residual = forward ? (arc->cap - arc->flow) : arc->flow;
645
646 if (residual > 1e-9)
647 {
648 S_side.insert(v);
649 q.put(v);
650 }
651 }
652 }
653
654 // Source should be in S, sink should not be in S
655 EXPECT_TRUE(S_side.count(source) > 0);
656 EXPECT_FALSE(S_side.count(sink) > 0);
657
658 // Verify all arcs crossing the cut are saturated (forward) or empty (backward)
659 for (auto u : S_side)
660 {
661 for (Out_Iterator<TestNet> it(u); it.has_curr(); it.next_ne())
662 {
663 Arc* arc = it.get_curr();
664 Node* v = net.get_tgt_node(arc);
665
666 if (S_side.count(v) == 0) // Arc crosses the cut
667 {
668 // Forward arc crossing cut should be saturated
669 EXPECT_NEAR(arc->flow, arc->cap, 1e-6);
670 }
671 }
672
673 for (In_Iterator<TestNet> it(u); it.has_curr(); it.next_ne())
674 {
675 Arc* arc = it.get_curr();
676 Node* v = net.get_src_node(arc);
677
678 if (S_side.count(v) == 0) // Arc crosses the cut (backward)
679 {
680 // Backward arc crossing cut should have zero flow
681 EXPECT_NEAR(arc->flow, 0.0, 1e-6);
682 }
683 }
684 }
685}
686
687
688//==============================================================================
689// Algorithm Comparison Tests
690//==============================================================================
691
692TEST(AlgorithmComparisonTest, AllAlgorithmsAgree)
693{
694 // Build 4 identical networks
695 TestNet net1, net2, net3, net4;
696 build_complex_network(net1);
697 build_complex_network(net2);
698 build_complex_network(net3);
699 build_complex_network(net4);
700
701 auto flow_ff = ford_fulkerson_maximum_flow(net1);
702 auto flow_ek = edmonds_karp_maximum_flow(net2);
703 auto flow_dinic = dinic_maximum_flow(net3);
704 auto flow_cs = capacity_scaling_maximum_flow(net4);
705
706 EXPECT_DOUBLE_EQ(flow_ff, flow_ek);
707 EXPECT_DOUBLE_EQ(flow_ek, flow_dinic);
708 EXPECT_DOUBLE_EQ(flow_dinic, flow_cs);
709}
710
711TEST(AlgorithmComparisonTest, GridNetwork)
712{
713 const int size = 5;
714
715 TestNet net1, net2, net3;
716 build_grid_network(net1, size, size, 10);
717 build_grid_network(net2, size, size, 10);
718 build_grid_network(net3, size, size, 10);
719
720 auto flow_ek = edmonds_karp_maximum_flow(net1);
721 auto flow_dinic = dinic_maximum_flow(net2);
722 auto flow_cs = capacity_scaling_maximum_flow(net3);
723
724 EXPECT_DOUBLE_EQ(flow_ek, flow_dinic);
725 EXPECT_DOUBLE_EQ(flow_dinic, flow_cs);
726}
727
728
729//==============================================================================
730// Edge Cases
731//==============================================================================
732
733TEST(EdgeCasesTest, ParallelArcs)
734{
735 TestNet net;
736 auto s = net.insert_node(0);
737 auto t = net.insert_node(1);
738
739 // Multiple arcs between same nodes
740 net.insert_arc(s, t, 10);
741 net.insert_arc(s, t, 20);
742 net.insert_arc(s, t, 30);
743
744 auto flow = dinic_maximum_flow(net);
745 EXPECT_DOUBLE_EQ(flow, 60.0); // Sum of capacities
746}
747
748TEST(EdgeCasesTest, SourceBottleneck)
749{
750 TestNet net;
751 auto s = net.insert_node(0);
752 auto a = net.insert_node(1);
753 auto t = net.insert_node(2);
754
755 net.insert_arc(s, a, 5); // Bottleneck at source
756 net.insert_arc(a, t, 100);
757
758 auto flow = dinic_maximum_flow(net);
759 EXPECT_DOUBLE_EQ(flow, 5.0);
760}
761
762TEST(EdgeCasesTest, SinkBottleneck)
763{
764 TestNet net;
765 auto s = net.insert_node(0);
766 auto a = net.insert_node(1);
767 auto t = net.insert_node(2);
768
769 net.insert_arc(s, a, 100);
770 net.insert_arc(a, t, 5); // Bottleneck at sink
771
772 auto flow = dinic_maximum_flow(net);
773 EXPECT_DOUBLE_EQ(flow, 5.0);
774}
775
776
777//==============================================================================
778// Functor Tests
779//==============================================================================
780
781TEST(FunctorTest, DinicFunctor)
782{
783 TestNet net;
784 build_diamond_network(net);
785
787 auto flow = algo(net);
788 EXPECT_DOUBLE_EQ(flow, 20.0);
789}
790
791TEST(FunctorTest, CapacityScalingFunctor)
792{
793 TestNet net;
794 build_diamond_network(net);
795
797 auto flow = algo(net);
798 EXPECT_DOUBLE_EQ(flow, 20.0);
799}
800
801TEST(FunctorTest, HLPPFunctor)
802{
803 TestNet net;
804 build_diamond_network(net);
805
807 auto flow = algo(net);
808 EXPECT_DOUBLE_EQ(flow, 20.0);
809}
810
811TEST(FunctorTest, DecomposeFunctor)
812{
813 TestNet net;
814 build_diamond_network(net);
816
817 Decompose_Flow<TestNet> decomposer;
818 auto decomp = decomposer(net);
819
820 EXPECT_DOUBLE_EQ(decomp.total_flow(), 20.0);
821}
822
823
824//==============================================================================
825// Performance Benchmark
826//==============================================================================
827
828TEST(PerformanceTest, Benchmark)
829{
830 const int grid_size = 10;
831 std::cout << "\n=== Max Flow Performance Benchmark (Grid "
832 << grid_size << "x" << grid_size << ") ===\n";
833
834 auto benchmark = [&](const std::string& name, auto algo) {
835 TestNet net;
836 build_grid_network(net, grid_size, grid_size, 100);
837
838 auto start = std::chrono::high_resolution_clock::now();
839 auto flow = algo(net);
840 auto end = std::chrono::high_resolution_clock::now();
841 double ms = std::chrono::duration<double, std::milli>(end - start).count();
842
843 std::cout << name << ": " << ms << " ms, flow=" << flow << "\n";
844 return flow;
845 };
846
847 auto flow_ek = benchmark("Edmonds-Karp ", [](TestNet& n) {
849 });
850
851 auto flow_dinic = benchmark("Dinic ", [](TestNet& n) {
852 return dinic_maximum_flow(n);
853 });
854
855 auto flow_cs = benchmark("Capacity Scaling", [](TestNet& n) {
857 });
858
859 // All should give same result
860 EXPECT_DOUBLE_EQ(flow_ek, flow_dinic);
861 EXPECT_DOUBLE_EQ(flow_dinic, flow_cs);
862}
863
864
865// =============================================================================
866// Regression Tests
867// =============================================================================
868
869TEST(RegressionTest, HLPPDisconnectedNodeRelabel)
870{
871 // This test covers a bug where HLPP could set height[u] = 2*n+1
872 // when relabeling a node with no residual neighbors, causing
873 // out-of-bounds access to buckets[2*n+1].
874 //
875 // Network structure that can trigger this:
876 // s -> a -> t (bottleneck at a->t)
877 // If 'a' has excess but all outgoing arcs are saturated and
878 // all incoming arcs have no reverse capacity, relabel would
879 // set height[a] = min_height+1 where min_height could be 2*n.
880
881 TestNet net;
882 auto s = net.insert_node(0); // source (inferred)
883 auto a = net.insert_node(1); // intermediate
884 auto t = net.insert_node(2); // sink (inferred)
885
886 // Create a very small capacity to sink, so 'a' can get excess
887 net.insert_arc(s, a, 100.0); // large capacity
888 net.insert_arc(a, t, 1.0); // small capacity (bottleneck)
889
890 // Run HLPP - should not crash or access out of bounds
891 double flow = hlpp_maximum_flow(net);
892
893 // The max flow is limited by the bottleneck
894 EXPECT_DOUBLE_EQ(flow, 1.0);
895
896 // Verify the flow is valid (conservation at intermediate node)
897 double flow_in_a = 0, flow_out_a = 0;
898 for (typename TestNet::Node_Arc_Iterator it(a); it.has_curr(); it.next_ne())
899 {
900 auto arc = it.get_curr();
901 if (net.get_tgt_node(arc) == a)
902 flow_in_a += arc->flow;
903 else
904 flow_out_a += arc->flow;
905 }
906 EXPECT_DOUBLE_EQ(flow_in_a, flow_out_a);
907}
908
909
910//==============================================================================
911// Bug-hunting tests: Anti-parallel arcs
912//==============================================================================
913
914// Helper: build network with anti-parallel arcs (A->B and B->A)
915// This stresses backward-edge residual logic because there are REAL
916// reverse arcs in addition to the virtual backward edges.
917//
918// s --20--> a --10--> t
919// | ^
920// 7 | | 5
921// v |
922// b --8--> t
923//
924// Plus anti-parallel: a->b(7), b->a(5)
925// Max flow should be 20 (limited by s->a), with paths:
926// s->a->t: 10, s->a->b->t: 7, and s->a flow via b->a back to a->t: up to 5
928{
929 auto s = net.insert_node(0);
930 auto a = net.insert_node(1);
931 auto b = net.insert_node(2);
932 auto t = net.insert_node(3);
933
934 net.insert_arc(s, a, 20);
935 net.insert_arc(a, t, 10);
936 net.insert_arc(a, b, 7); // Forward a->b
937 net.insert_arc(b, a, 5); // Anti-parallel b->a
938 net.insert_arc(b, t, 8);
939
940 return s;
941}
942
943TEST(AntiParallelTest, AllAlgorithmsAgreeOnAntiParallel)
944{
945 // All algorithms must give the same result on anti-parallel arcs
946 TestNet net1, net2, net3, net4, net5;
952
953 auto flow_ff = ford_fulkerson_maximum_flow(net1);
954 auto flow_ek = edmonds_karp_maximum_flow(net2);
955 auto flow_dinic = dinic_maximum_flow(net3);
956 auto flow_cs = capacity_scaling_maximum_flow(net4);
957 auto flow_hlpp = hlpp_maximum_flow(net5);
958
959 // Max flow is 18: s->a(20), a->t(10), a->b(7), b->t(8) => 10+8=18
960 // (limited by outgoing capacity from a: 10+7=17? no, b->a adds 5 more to a)
961 // Actually just verify they all agree and conservation holds
962 EXPECT_DOUBLE_EQ(flow_ff, flow_ek);
963 EXPECT_DOUBLE_EQ(flow_ek, flow_dinic);
964 EXPECT_DOUBLE_EQ(flow_dinic, flow_cs);
965 EXPECT_DOUBLE_EQ(flow_cs, flow_hlpp);
966
967 EXPECT_TRUE(net1.check_network());
968 EXPECT_TRUE(net2.check_network());
969 EXPECT_TRUE(net3.check_network());
970 EXPECT_TRUE(net4.check_network());
971 EXPECT_TRUE(net5.check_network());
972
973 // Verify min-cut theorem for all
974 EXPECT_TRUE(verify_max_flow_min_cut(net1, flow_ff));
975 EXPECT_TRUE(verify_max_flow_min_cut(net3, flow_dinic));
976 EXPECT_TRUE(verify_max_flow_min_cut(net5, flow_hlpp));
977}
978
979TEST(AntiParallelTest, PureAntiParallel)
980{
981 // s -> a -> t AND s -> b -> a (with b->a anti-parallel to a->b implicit)
982 // But also a -> b exists
983 TestNet net;
984 auto s = net.insert_node(0);
985 auto a = net.insert_node(1);
986 auto b = net.insert_node(2);
987 auto t = net.insert_node(3);
988
989 net.insert_arc(s, a, 10);
990 net.insert_arc(s, b, 10);
991 net.insert_arc(a, b, 5); // a->b
992 net.insert_arc(b, a, 5); // b->a (anti-parallel)
993 net.insert_arc(a, t, 15);
994 net.insert_arc(b, t, 15);
995
996 auto flow = dinic_maximum_flow(net);
997 EXPECT_DOUBLE_EQ(flow, 20.0); // Both s->a and s->b push 10 each
998 EXPECT_TRUE(net.check_network());
999}
1000
1001
1002//==============================================================================
1003// Bug-hunting tests: Capacity Scaling with fractional capacities
1004//==============================================================================
1005
1006TEST(CapacityScalingTest, FractionalCapacities)
1007{
1008 // Capacity scaling now scales down to the minimum positive capacity,
1009 // so fractional capacities are handled correctly.
1010 auto build_net = [](TestNet& net) {
1011 auto s = net.insert_node(0);
1012 auto t = net.insert_node(1);
1013 net.insert_arc(s, t, 0.5);
1014 };
1015
1016 TestNet net_cs, net_dinic;
1017 build_net(net_cs);
1018 build_net(net_dinic);
1019
1020 auto flow_cs = capacity_scaling_maximum_flow(net_cs);
1021 auto flow_dinic = dinic_maximum_flow(net_dinic);
1022
1023 EXPECT_DOUBLE_EQ(flow_dinic, 0.5);
1024 EXPECT_DOUBLE_EQ(flow_cs, 0.5); // Now correctly finds fractional flow
1025}
1026
1027TEST(CapacityScalingTest, MixedIntegerFractional)
1028{
1029 // Network where integer-capacity paths exist but fractional adds more
1030 // Must use separate networks since algorithms modify flow in-place
1031
1032 auto build_net = [](TestNet& net) {
1033 auto s = net.insert_node(0);
1034 auto a = net.insert_node(1);
1035 auto b = net.insert_node(2);
1036 auto t = net.insert_node(3);
1037 net.insert_arc(s, a, 10);
1038 net.insert_arc(s, b, 0.7); // Fractional
1039 net.insert_arc(a, t, 10);
1040 net.insert_arc(b, t, 0.7); // Fractional
1041 };
1042
1043 TestNet net_cs, net_dinic;
1044 build_net(net_cs);
1045 build_net(net_dinic);
1046
1047 auto flow_cs = capacity_scaling_maximum_flow(net_cs);
1048 auto flow_dinic = dinic_maximum_flow(net_dinic);
1049
1050 // Both should find the full flow: 10 + 0.7 = 10.7
1051 EXPECT_DOUBLE_EQ(flow_dinic, 10.7);
1052 EXPECT_DOUBLE_EQ(flow_cs, 10.7);
1053}
1054
1055
1056//==============================================================================
1057// Bug-hunting tests: HLPP stress with conservation verification
1058//==============================================================================
1059
1060// Explicit conservation check at every intermediate node
1061template <class Net>
1063{
1064 for (Node_Iterator<Net> it(net); it.has_curr(); it.next_ne())
1065 {
1066 auto p = it.get_curr();
1067 if (net.is_source(p) or net.is_sink(p))
1068 continue;
1069
1070 double in_flow = 0, out_flow = 0;
1071 for (typename Net::Node_Arc_Iterator ait(p); ait.has_curr(); ait.next_ne())
1072 {
1073 auto arc = ait.get_curr();
1074 if (net.get_tgt_node(arc) == p)
1075 in_flow += arc->flow;
1076 else if (net.get_src_node(arc) == p)
1077 out_flow += arc->flow;
1078 }
1079
1080 EXPECT_NEAR(in_flow, out_flow, 1e-6)
1081 << "Conservation violated at node with in=" << in_flow
1082 << " out=" << out_flow;
1083 }
1084}
1085
1086TEST(HLPPStressTest, LadderNetwork)
1087{
1088 // Ladder graph: two parallel chains connected by rungs
1089 // Forces many relabeling operations
1090 //
1091 // s -> a0 -> a1 -> a2 -> ... -> aN -> t
1092 // | | | |
1093 // v v v v
1094 // s -> b0 -> b1 -> b2 -> ... -> bN -> t
1095 //
1096 const int N = 15;
1097 TestNet net;
1098 auto s = net.insert_node(0);
1099 auto t = net.insert_node(1);
1100
1101 auto chain_a = Array<Node *>::create(N);
1102 auto chain_b = Array<Node *>::create(N);
1103 for (int i = 0; i < N; ++i)
1104 {
1105 chain_a[i] = net.insert_node(10 + i);
1106 chain_b[i] = net.insert_node(30 + i);
1107 }
1108
1109 // Connect source to first nodes
1110 net.insert_arc(s, chain_a[0], 100);
1111 net.insert_arc(s, chain_b[0], 100);
1112
1113 // Chains
1114 for (int i = 0; i < N - 1; ++i)
1115 {
1116 net.insert_arc(chain_a[i], chain_a[i+1], 50);
1117 net.insert_arc(chain_b[i], chain_b[i+1], 50);
1118 }
1119
1120 // Rungs (cross connections)
1121 for (int i = 0; i < N; ++i)
1122 {
1123 net.insert_arc(chain_a[i], chain_b[i], 10);
1124 net.insert_arc(chain_b[i], chain_a[i], 10); // Anti-parallel rungs
1125 }
1126
1127 // Connect last nodes to sink
1128 net.insert_arc(chain_a[N-1], t, 100);
1129 net.insert_arc(chain_b[N-1], t, 100);
1130
1131 // Build identical networks (can't copy Net_Graph, so rebuild)
1132 auto build_ladder = [&](TestNet& n) {
1133 auto s2 = n.insert_node(0);
1134 auto t2 = n.insert_node(1);
1135 auto ca = Array<Node *>::create(N);
1136 auto cb = Array<Node *>::create(N);
1137 for (int i = 0; i < N; ++i)
1138 {
1139 ca[i] = n.insert_node(10 + i);
1140 cb[i] = n.insert_node(30 + i);
1141 }
1142 n.insert_arc(s2, ca[0], 100);
1143 n.insert_arc(s2, cb[0], 100);
1144 for (int i = 0; i < N - 1; ++i)
1145 {
1146 n.insert_arc(ca[i], ca[i+1], 50);
1147 n.insert_arc(cb[i], cb[i+1], 50);
1148 }
1149 for (int i = 0; i < N; ++i)
1150 {
1151 n.insert_arc(ca[i], cb[i], 10);
1152 n.insert_arc(cb[i], ca[i], 10);
1153 }
1154 n.insert_arc(ca[N-1], t2, 100);
1155 n.insert_arc(cb[N-1], t2, 100);
1156 };
1157
1158 TestNet net2, net3;
1159 build_ladder(net2);
1160 build_ladder(net3);
1161
1162 auto flow_dinic = dinic_maximum_flow(net);
1163 auto flow_hlpp = hlpp_maximum_flow(net2);
1164 auto flow_ek = edmonds_karp_maximum_flow(net3);
1165
1166 EXPECT_DOUBLE_EQ(flow_dinic, flow_hlpp);
1167 EXPECT_DOUBLE_EQ(flow_dinic, flow_ek);
1168
1169 // Explicit conservation check
1170 EXPECT_TRUE(net.check_network());
1171 EXPECT_TRUE(net2.check_network());
1172 verify_flow_conservation<TestNet>(net);
1173 verify_flow_conservation<TestNet>(net2);
1174}
1175
1176TEST(HLPPStressTest, HighExcessBottleneck)
1177{
1178 // Graph designed to create large excess at intermediate nodes
1179 // s pushes 1000 to a, but a can only drain 1 to t
1180 // HLPP must push 999 back to s
1181 TestNet net;
1182 auto s = net.insert_node(0);
1183 auto a = net.insert_node(1);
1184 auto b = net.insert_node(2);
1185 auto c = net.insert_node(3);
1186 auto t = net.insert_node(4);
1187
1188 net.insert_arc(s, a, 1000);
1189 net.insert_arc(s, b, 1000);
1190 net.insert_arc(a, c, 1); // Tiny bottleneck
1191 net.insert_arc(b, c, 1); // Tiny bottleneck
1192 net.insert_arc(c, t, 2);
1193 net.insert_arc(a, b, 500); // Cross connection
1194 net.insert_arc(b, a, 500); // Anti-parallel
1195
1196 auto flow = hlpp_maximum_flow(net);
1197
1198 EXPECT_DOUBLE_EQ(flow, 2.0);
1199 EXPECT_TRUE(net.check_network());
1200 verify_flow_conservation<TestNet>(net);
1201}
1202
1203
1204//==============================================================================
1205// Bug-hunting tests: Flow decomposition consistency
1206//==============================================================================
1207
1208TEST(FlowDecompositionTest, ArcFlowConsistency)
1209{
1210 // After decomposition, for each arc:
1211 // sum of (path.flow for paths using that arc) == arc.flow
1212 TestNet net;
1213 build_complex_network(net);
1214 dinic_maximum_flow(net);
1215
1216 // Save original flows
1217 DynMapTree<Arc*, double> original_flow;
1218 for (Arc_Iterator<TestNet> it(net); it.has_curr(); it.next_ne())
1219 {
1220 auto arc = it.get_curr();
1221 original_flow[arc] = arc->flow;
1222 }
1223
1224 auto decomp = decompose_flow(net);
1225
1226 // Rebuild flow from decomposition
1227 DynMapTree<Arc*, double> reconstructed_flow;
1228 for (Arc_Iterator<TestNet> it(net); it.has_curr(); it.next_ne())
1229 reconstructed_flow[it.get_curr()] = 0.0;
1230
1231 for (auto path_it = decomp.paths.get_it(); path_it.has_curr(); path_it.next_ne())
1232 {
1233 const auto& path = path_it.get_curr();
1234 for (auto arc_it = path.arcs.get_it(); arc_it.has_curr(); arc_it.next_ne())
1235 reconstructed_flow[arc_it.get_curr()] += path.flow;
1236 }
1237
1238 for (auto cycle_it = decomp.cycles.get_it(); cycle_it.has_curr(); cycle_it.next_ne())
1239 {
1240 const auto& cycle = cycle_it.get_curr();
1241 for (auto arc_it = cycle.arcs.get_it(); arc_it.has_curr(); arc_it.next_ne())
1242 reconstructed_flow[arc_it.get_curr()] += cycle.flow;
1243 }
1244
1245 // Every arc's flow should be fully accounted for
1246 for (Arc_Iterator<TestNet> it(net); it.has_curr(); it.next_ne())
1247 {
1248 auto arc = it.get_curr();
1249 EXPECT_NEAR(reconstructed_flow[arc], original_flow[arc], 1e-6)
1250 << "Arc flow mismatch: reconstructed=" << reconstructed_flow[arc]
1251 << " original=" << original_flow[arc];
1252 }
1253}
1254
1255TEST(FlowDecompositionTest, Phase2CycleClosingNode)
1256{
1257 // Create a flow with a cycle NOT reachable from source (Phase 2 territory)
1258 // After fixing the Phase-2 bug, cycle.nodes should include the closing node
1259 TestNet net;
1260 auto s = net.insert_node(0);
1261 auto a = net.insert_node(1);
1262 auto b = net.insert_node(2);
1263 auto c = net.insert_node(3);
1264 auto t = net.insert_node(4);
1265
1266 // Main path s->a->t
1267 auto arc_sa = net.insert_arc(s, a, 10);
1268 auto arc_at = net.insert_arc(a, t, 10);
1269
1270 // Isolated cycle b->c->b (not connected to source outflow)
1271 auto arc_bc = net.insert_arc(b, c, 5);
1272 auto arc_cb = net.insert_arc(c, b, 5);
1273
1274 // Dummy arcs to keep b,c in the network but no flow from source to them
1275 net.insert_arc(s, b, 0); // zero capacity
1276 net.insert_arc(c, t, 0); // zero capacity
1277
1278 // Set up flow manually: path s->a->t with flow 5, cycle b->c->b with flow 3
1279 arc_sa->flow = 5;
1280 arc_at->flow = 5;
1281 arc_bc->flow = 3;
1282 arc_cb->flow = 3;
1283
1284 auto decomp = decompose_flow(net);
1285
1286 EXPECT_EQ(decomp.num_paths(), 1);
1287 EXPECT_DOUBLE_EQ(decomp.total_flow(), 5.0);
1288
1289 // Should find the b->c->b cycle in Phase 2
1290 EXPECT_GE(decomp.num_cycles(), 1);
1291
1292 if (decomp.num_cycles() >= 1)
1293 {
1294 const auto& cycle = decomp.cycles.get_first();
1295 EXPECT_DOUBLE_EQ(cycle.flow, 3.0);
1296
1297 // Verify closing node: cycle.nodes should have one more element than
1298 // cycle.arcs, and first node == last node
1299 size_t n_nodes = 0, n_arcs = 0;
1300 for (auto it = cycle.nodes.get_it(); it.has_curr(); it.next_ne())
1301 ++n_nodes;
1302 for (auto it = cycle.arcs.get_it(); it.has_curr(); it.next_ne())
1303 ++n_arcs;
1304
1305 EXPECT_EQ(n_nodes, n_arcs + 1)
1306 << "Cycle should have nodes.size() == arcs.size() + 1 (closing node)";
1307
1308 // First and last node should be the same (cycle is closed)
1309 auto first_node = cycle.nodes.get_first();
1310 auto last_node = cycle.nodes.get_last();
1311 EXPECT_EQ(first_node, last_node)
1312 << "Cycle first and last node should be the same";
1313 }
1314}
1315
1316TEST(FlowDecompositionTest, Phase1CycleClosingNode)
1317{
1318 // Also verify Phase-1 cycles have proper format for symmetry
1319 TestNet net;
1320 auto s = net.insert_node(0);
1321 auto a = net.insert_node(1);
1322 auto b = net.insert_node(2);
1323 auto t = net.insert_node(3);
1324
1325 auto arc_sa = net.insert_arc(s, a, 10);
1326 auto arc_at = net.insert_arc(a, t, 10);
1327 auto arc_ab = net.insert_arc(a, b, 5);
1328 auto arc_ba = net.insert_arc(b, a, 5);
1329
1330 // Flow: s->a->t(5), cycle a->b->a(5)
1331 arc_sa->flow = 5;
1332 arc_at->flow = 5;
1333 arc_ab->flow = 5;
1334 arc_ba->flow = 5;
1335
1336 auto decomp = decompose_flow(net);
1337
1338 EXPECT_EQ(decomp.num_paths(), 1);
1339 EXPECT_GE(decomp.num_cycles(), 1);
1340
1341 if (decomp.num_cycles() >= 1)
1342 {
1343 const auto& cycle = decomp.cycles.get_first();
1344
1345 size_t n_nodes = 0, n_arcs = 0;
1346 for (auto it = cycle.nodes.get_it(); it.has_curr(); it.next_ne())
1347 ++n_nodes;
1348 for (auto it = cycle.arcs.get_it(); it.has_curr(); it.next_ne())
1349 ++n_arcs;
1350
1351 EXPECT_EQ(n_nodes, n_arcs + 1)
1352 << "Phase-1 cycle should also have nodes.size() == arcs.size() + 1";
1353
1354 auto first_node = cycle.nodes.get_first();
1355 auto last_node = cycle.nodes.get_last();
1356 EXPECT_EQ(first_node, last_node)
1357 << "Phase-1 cycle first and last node should be the same";
1358 }
1359}
1360
1361
1362//==============================================================================
1363// Bug-hunting tests: Disconnected sink
1364//==============================================================================
1365
1366TEST(DisconnectedTest, ZeroCapacityBottleneck)
1367{
1368 // Single-source/single-sink network where all paths have zero capacity
1369 // This is the closest to "disconnected" that Net_Graph allows
1370 TestNet net;
1371 auto s = net.insert_node(0);
1372 auto a = net.insert_node(1);
1373 auto t = net.insert_node(2);
1374
1375 net.insert_arc(s, a, 0); // Zero capacity bottleneck
1376 net.insert_arc(a, t, 10);
1377
1378 auto flow = dinic_maximum_flow(net);
1379 EXPECT_DOUBLE_EQ(flow, 0.0);
1380}
1381
1382TEST(DisconnectedTest, InvalidNetworkThrows)
1383{
1384 // A truly disconnected network violates single source/sink
1385 // (Net_Graph determines source/sink by in/out-degree)
1386 // Algorithms should throw domain_error
1387 TestNet net;
1388 auto s = net.insert_node(0);
1389 auto a = net.insert_node(1);
1390 auto b = net.insert_node(2); // Another "source" (no incoming arcs)
1391 auto t = net.insert_node(3);
1392
1393 net.insert_arc(s, a, 10);
1394 net.insert_arc(b, t, 10);
1395
1396 EXPECT_THROW(dinic_maximum_flow(net), std::exception);
1397 EXPECT_THROW(capacity_scaling_maximum_flow(net), std::exception);
1398 EXPECT_THROW(hlpp_maximum_flow(net), std::exception);
1399}
1400
1401
1402//==============================================================================
1403// Bug-hunting tests: Dinic with deep level graph
1404//==============================================================================
1405
1406TEST(DinicStressTest, LongChain)
1407{
1408 // s -> n1 -> n2 -> ... -> n50 -> t
1409 // Forces 1 BFS phase with 51 levels
1410 const int chain_len = 50;
1411 TestNet net;
1412 auto s = net.insert_node(0);
1413 auto t = net.insert_node(1);
1414
1415 auto prev = s;
1416 for (int i = 0; i < chain_len; ++i)
1417 {
1418 auto curr = net.insert_node(10 + i);
1419 net.insert_arc(prev, curr, 100);
1420 prev = curr;
1421 }
1422 net.insert_arc(prev, t, 100);
1423
1424 auto flow = dinic_maximum_flow(net);
1425 EXPECT_DOUBLE_EQ(flow, 100.0);
1426 EXPECT_TRUE(net.check_network());
1427}
1428
1429TEST(DinicStressTest, WideParallel)
1430{
1431 // s -> {a1, a2, ..., a100} -> t, all with cap 1
1432 // Many parallel paths
1433 const int width = 100;
1434 TestNet net;
1435 auto s = net.insert_node(0);
1436 auto t = net.insert_node(1);
1437
1438 for (int i = 0; i < width; ++i)
1439 {
1440 auto mid = net.insert_node(10 + i);
1441 net.insert_arc(s, mid, 1);
1442 net.insert_arc(mid, t, 1);
1443 }
1444
1445 // Build a second identical network for HLPP
1446 TestNet net2;
1447 auto s2 = net2.insert_node(0);
1448 auto t2 = net2.insert_node(1);
1449 for (int i = 0; i < width; ++i)
1450 {
1451 auto mid = net2.insert_node(10 + i);
1452 net2.insert_arc(s2, mid, 1);
1453 net2.insert_arc(mid, t2, 1);
1454 }
1455
1456 auto flow_dinic = dinic_maximum_flow(net);
1457 auto flow_hlpp = hlpp_maximum_flow(net2);
1458
1459 EXPECT_DOUBLE_EQ(flow_dinic, static_cast<double>(width));
1460 EXPECT_DOUBLE_EQ(flow_hlpp, static_cast<double>(width));
1461 EXPECT_TRUE(net.check_network());
1462 EXPECT_TRUE(net2.check_network());
1463}
1464
1465
1466//==============================================================================
1467// Randomized stress tests: all algorithms must agree on random graphs
1468//==============================================================================
1469
1470namespace
1471{
1472 // Integer flow network type
1474
1475 // Build a random network with n nodes, m arcs, max_cap capacity
1476 template <class NetT>
1477 void build_random_network(NetT & net, int n, int m, int max_cap,
1478 unsigned seed)
1479 {
1481 << "build_random_network requires n >= 3";
1482
1483 using NodeT = typename NetT::Node;
1484 std::mt19937 rng(seed);
1485 std::uniform_int_distribution<int> node_dist(0, n - 1);
1486 std::uniform_int_distribution<int> cap_dist(1, max_cap);
1487
1488 std::vector<NodeT *> nodes(n);
1489 for (int i = 0; i < n; ++i)
1490 nodes[i] = net.insert_node(i);
1491
1492 // Ensure source (0) has outgoing and sink (n-1) has incoming
1493 net.insert_arc(nodes[0], nodes[1], cap_dist(rng));
1494 net.insert_arc(nodes[n - 2], nodes[n - 1], cap_dist(rng));
1495
1496 for (int i = 0; i < m - 2; ++i)
1497 {
1498 int u = node_dist(rng);
1499 int v = node_dist(rng);
1500 if (u == v) v = (u + 1 < n) ? (u + 1) : 0;
1501 // Avoid creating additional sources/sinks
1502 if (v == 0) v = 1; // don't point to source
1503 if (u == n - 1) u = n - 2; // don't leave from sink
1504 if (u < 0) u = 0;
1505 if (u == v) continue;
1506 net.insert_arc(nodes[u], nodes[v], cap_dist(rng));
1507 }
1508 }
1509
1510 // Build identical random networks (since copy doesn't work)
1511 template <class NetT>
1512 void build_n_random_networks(std::vector<NetT> & nets,
1513 int count, int n, int m,
1514 int max_cap, unsigned seed)
1515 {
1516 nets.resize(count);
1517 for (int i = 0; i < count; ++i)
1518 build_random_network(nets[i], n, m, max_cap, seed);
1519 }
1520}
1521
1522TEST(RandomStressTest, SmallRandomGraphs)
1523{
1524 // Run 30 random small graphs, compare all 5 algorithms
1525 for (unsigned seed = 100; seed < 130; ++seed)
1526 {
1527 std::vector<TestNet> nets;
1528 build_n_random_networks(nets, 5, 8, 15, 100, seed);
1529
1530 if (not (nets[0].is_single_source() and nets[0].is_single_sink()))
1531 continue; // skip invalid graphs
1532
1533 auto f_ek = edmonds_karp_maximum_flow(nets[0]);
1534 auto f_dinic = dinic_maximum_flow(nets[1]);
1535 auto f_cs = capacity_scaling_maximum_flow(nets[2]);
1536 auto f_hlpp = hlpp_maximum_flow(nets[3]);
1537
1538 EXPECT_DOUBLE_EQ(f_ek, f_dinic)
1539 << "EK vs Dinic disagree at seed=" << seed;
1540 EXPECT_DOUBLE_EQ(f_ek, f_cs)
1541 << "EK vs CapScale disagree at seed=" << seed;
1542 EXPECT_DOUBLE_EQ(f_ek, f_hlpp)
1543 << "EK vs HLPP disagree at seed=" << seed;
1544
1545 EXPECT_TRUE(nets[0].check_network()) << "EK invalid at seed=" << seed;
1546 EXPECT_TRUE(nets[1].check_network()) << "Dinic invalid at seed=" << seed;
1547 EXPECT_TRUE(nets[2].check_network()) << "CapScale invalid at seed=" << seed;
1548 EXPECT_TRUE(nets[3].check_network()) << "HLPP invalid at seed=" << seed;
1549 }
1550}
1551
1552TEST(RandomStressTest, MediumRandomGraphs)
1553{
1554 // 10 medium random graphs, 50 nodes, 150 arcs
1555 for (unsigned seed = 200; seed < 210; ++seed)
1556 {
1557 std::vector<TestNet> nets;
1558 build_n_random_networks(nets, 4, 50, 150, 1000, seed);
1559
1560 if (not (nets[0].is_single_source() and nets[0].is_single_sink()))
1561 continue;
1562
1563 auto f_ek = edmonds_karp_maximum_flow(nets[0]);
1564 auto f_dinic = dinic_maximum_flow(nets[1]);
1565 auto f_hlpp = hlpp_maximum_flow(nets[2]);
1566
1567 EXPECT_DOUBLE_EQ(f_ek, f_dinic)
1568 << "EK vs Dinic disagree at seed=" << seed;
1569 EXPECT_DOUBLE_EQ(f_ek, f_hlpp)
1570 << "EK vs HLPP disagree at seed=" << seed;
1571
1572 verify_flow_conservation<TestNet>(nets[0]);
1573 verify_flow_conservation<TestNet>(nets[1]);
1574 verify_flow_conservation<TestNet>(nets[2]);
1575 }
1576}
1577
1578
1579//==============================================================================
1580// Integer Flow_Type tests
1581//==============================================================================
1582
1583TEST(IntegerFlowTest, AllAlgorithmsAgree)
1584{
1585 // Diamond network with integer capacities
1586 IntNet net1, net2, net3, net4;
1587
1588 auto build_int_diamond = [](IntNet & net) {
1589 auto s = net.insert_node(0);
1590 auto a = net.insert_node(1);
1591 auto b = net.insert_node(2);
1592 auto t = net.insert_node(3);
1593 net.insert_arc(s, a, 10);
1594 net.insert_arc(s, b, 10);
1595 net.insert_arc(a, t, 10);
1596 net.insert_arc(b, t, 10);
1597 };
1598
1599 build_int_diamond(net1);
1600 build_int_diamond(net2);
1601 build_int_diamond(net3);
1602 build_int_diamond(net4);
1603
1604 auto f_ek = edmonds_karp_maximum_flow(net1);
1605 auto f_dinic = dinic_maximum_flow(net2);
1606 auto f_cs = capacity_scaling_maximum_flow(net3);
1607 auto f_hlpp = hlpp_maximum_flow(net4);
1608
1609 EXPECT_EQ(f_ek, 20);
1610 EXPECT_EQ(f_dinic, 20);
1611 EXPECT_EQ(f_cs, 20);
1612 EXPECT_EQ(f_hlpp, 20);
1613
1614 EXPECT_TRUE(net1.check_network());
1615 EXPECT_TRUE(net2.check_network());
1616 EXPECT_TRUE(net4.check_network());
1617}
1618
1619TEST(IntegerFlowTest, ComplexIntegerNetwork)
1620{
1621 IntNet net1, net2, net3;
1622
1623 auto build = [](IntNet & net) {
1624 auto s = net.insert_node(0);
1625 auto a = net.insert_node(1);
1626 auto b = net.insert_node(2);
1627 auto c = net.insert_node(3);
1628 auto d = net.insert_node(4);
1629 auto t = net.insert_node(5);
1630
1631 net.insert_arc(s, a, 16);
1632 net.insert_arc(s, c, 13);
1633 net.insert_arc(a, b, 12);
1634 net.insert_arc(a, c, 10);
1635 net.insert_arc(b, t, 20);
1636 net.insert_arc(c, d, 14);
1637 net.insert_arc(d, b, 7);
1638 net.insert_arc(d, t, 4);
1639 };
1640
1641 build(net1);
1642 build(net2);
1643 build(net3);
1644
1645 auto f_dinic = dinic_maximum_flow(net1);
1646 auto f_cs = capacity_scaling_maximum_flow(net2);
1647 auto f_hlpp = hlpp_maximum_flow(net3);
1648
1649 EXPECT_EQ(f_dinic, 23);
1650 EXPECT_EQ(f_cs, 23);
1651 EXPECT_EQ(f_hlpp, 23);
1652
1653 EXPECT_TRUE(net1.check_network());
1654 EXPECT_TRUE(net3.check_network());
1655}
1656
1657TEST(IntegerFlowTest, RandomIntegerGraphs)
1658{
1659 // Random integer graphs, all algorithms must agree
1660 for (unsigned seed = 300; seed < 320; ++seed)
1661 {
1662 std::vector<IntNet> nets;
1663 build_n_random_networks(nets, 4, 12, 25, 50, seed);
1664
1665 if (not (nets[0].is_single_source() and nets[0].is_single_sink()))
1666 continue;
1667
1668 auto f_ek = edmonds_karp_maximum_flow(nets[0]);
1669 auto f_dinic = dinic_maximum_flow(nets[1]);
1670 auto f_cs = capacity_scaling_maximum_flow(nets[2]);
1671 auto f_hlpp = hlpp_maximum_flow(nets[3]);
1672
1673 EXPECT_EQ(f_ek, f_dinic)
1674 << "EK vs Dinic disagree at seed=" << seed;
1675 EXPECT_EQ(f_ek, f_cs)
1676 << "EK vs CapScale disagree at seed=" << seed;
1677 EXPECT_EQ(f_ek, f_hlpp)
1678 << "EK vs HLPP disagree at seed=" << seed;
1679
1680 EXPECT_TRUE(nets[0].check_network()) << "seed=" << seed;
1681 EXPECT_TRUE(nets[1].check_network()) << "seed=" << seed;
1682 EXPECT_TRUE(nets[2].check_network()) << "seed=" << seed;
1683 EXPECT_TRUE(nets[3].check_network()) << "seed=" << seed;
1684 }
1685}
1686
1687TEST(IntegerFlowTest, MinCutVerification)
1688{
1689 // Verify max-flow = min-cut for integer networks
1690 IntNet net1, net2;
1691
1692 auto build = [](IntNet & net) {
1693 auto s = net.insert_node(0);
1694 auto a = net.insert_node(1);
1695 auto b = net.insert_node(2);
1696 auto c = net.insert_node(3);
1697 auto t = net.insert_node(4);
1698
1699 net.insert_arc(s, a, 3);
1700 net.insert_arc(s, b, 2);
1701 net.insert_arc(a, b, 1);
1702 net.insert_arc(a, c, 3);
1703 net.insert_arc(b, c, 1);
1704 net.insert_arc(c, t, 4);
1705 };
1706
1707 build(net1);
1708 build(net2);
1709
1710 auto flow = dinic_maximum_flow(net1);
1711 EXPECT_EQ(flow, 4);
1712
1713 // Verify min-cut via HLPP reachability
1714 hlpp_maximum_flow(net2);
1715
1716 // After HLPP, the min cut separates nodes reachable from source
1717 // in the residual graph from those not reachable.
1718 // The min-cut capacity should equal the max-flow.
1719 int cut_cap = 0;
1720 for (Arc_Iterator<IntNet> it(net2); it.has_curr(); it.next_ne())
1721 {
1722 auto arc = it.get_curr();
1723 // Arc crosses cut if src is source-side and tgt is sink-side
1724 // Check via residual: source-side nodes can reach source via
1725 // residual arcs, sink-side nodes cannot
1726 if (arc->flow == arc->cap) // saturated arcs are candidates
1727 cut_cap += arc->cap;
1728 }
1729 // Total saturated capacity >= max flow (some saturated arcs may not be cut arcs)
1730 EXPECT_GE(cut_cap, flow);
1731}
1732
1733// Ford-Fulkerson took a path through what rounding left of the capacity
1734// of an arc, whose flows summed to a little less than it, and augmented
1735// by that residue: the small flows that it spread broke the balance of
1736// the nodes, so that its assertion failed in a debug build, and
1737// check_network() after it in a release one
1738TEST(FordFulkersonTest, DecimalCapacitiesKeepTheBalance)
1739{
1740 // u, v and the capacity in tenths; 4 is the source and 2 the sink
1741 const int spec[][3] = {{1, 3, 20}, {3, 5, 20}, {5, 2, 30}, {4, 3, 20},
1742 {0, 2, 29}, {4, 0, 2}, {0, 1, 1}, {5, 0, 10},
1743 {4, 0, 27}, {0, 1, 19}, {4, 5, 10}};
1744 auto build = [&spec] (TestNet & net)
1745 {
1746 std::vector<Node *> nodes;
1747 for (int i = 0; i < 6; ++i)
1748 nodes.push_back(net.insert_node(i));
1749 for (const auto & a : spec)
1750 net.insert_arc(nodes[size_t(a[0])], nodes[size_t(a[1])], a[2] / 10.0);
1751 };
1752
1753 // ff and ek, and the depth-first paths, which Ford-Fulkerson took with
1754 // a floating flow before it took the shortest ones, and where the case
1755 // was found
1756 TestNet ff, ek, dfs;
1757 build(ff);
1758 build(ek);
1759 build(dfs);
1760 const double ff_value = Ford_Fulkerson_Maximum_Flow<TestNet>()(ff);
1761 const double ek_value = Edmonds_Karp_Maximum_Flow<TestNet>()(ek);
1762 const double dfs_value = aumenting_path_maximum_flow<TestNet, Find_Aumenting_Path_DFS>(dfs);
1763
1764 EXPECT_TRUE(ff.check_network());
1765 EXPECT_TRUE(ek.check_network());
1766 EXPECT_TRUE(dfs.check_network());
1767 // The arcs out of the source, 2 + 0.2 + 2.7 + 1, are saturated
1768 EXPECT_NEAR(ff_value, 5.9, 1e-12);
1769 EXPECT_NEAR(ek_value, 5.9, 1e-12);
1770 EXPECT_NEAR(dfs_value, 5.9, 1e-12);
1771}
1772
1773// A slack that rounding left on an arc of capacity 2, of 0.09999999999999964
1774// for 0.1, filled arcs of capacity 0.1 and left them a residue of 3.6e-16,
1775// which a path took; later paths took the flows of a node to zero, but that
1776// residue, and the node lost its balance. The residues go back at the end,
1777// as those of the preflows
1778TEST(FordFulkersonTest, ResiduesOfLargerArcsKeepTheBalance)
1779{
1780 // u, v and the capacity in tenths; 1 is the source and 14 the sink
1781 const int spec[][3] = {{0, 18, 0}, {7, 10, 3}, {20, 4, 7}, {7, 16, 0}, {19, 16, 1},
1782 {16, 17, 2}, {4, 3, 7}, {10, 4, 3}, {18, 0, 0}, {9, 6, 2},
1783 {11, 20, 6}, {5, 14, 20}, {6, 20, 1}, {12, 13, 0}, {2, 14, 10},
1784 {3, 14, 8}, {15, 19, 1}, {3, 15, 2}, {4, 20, 0}, {1, 20, 0},
1785 {5, 7, 3}, {6, 12, 5}, {12, 19, 0}, {1, 6, 16}, {17, 3, 1},
1786 {16, 5, 11}, {16, 13, 1}, {2, 14, 1}, {6, 8, 10}, {17, 8, 5},
1787 {16, 6, 9}, {3, 17, 5}, {12, 11, 7}, {19, 20, 1}, {1, 5, 9},
1788 {11, 19, 1}, {1, 16, 14}, {16, 12, 7}, {15, 9, 2}, {8, 2, 11},
1789 {13, 9, 1}};
1790 auto build = [&spec] (TestNet & net)
1791 {
1792 std::vector<Node *> nodes;
1793 for (int i = 0; i < 21; ++i)
1794 nodes.push_back(net.insert_node(i));
1795 for (const auto & a : spec)
1796 net.insert_arc(nodes[size_t(a[0])], nodes[size_t(a[1])], a[2] / 10.0);
1797 };
1798
1799 // ff and ek, and the depth-first paths, which Ford-Fulkerson took with
1800 // a floating flow before it took the shortest ones, and where the case
1801 // was found
1802 TestNet ff, ek, dfs;
1803 build(ff);
1804 build(ek);
1805 build(dfs);
1806 ASSERT_EQ(ff.get_source()->get_info(), 1);
1807 ASSERT_EQ(ff.get_sink()->get_info(), 14);
1808 const double ff_value = Ford_Fulkerson_Maximum_Flow<TestNet>()(ff);
1809 const double ek_value = Edmonds_Karp_Maximum_Flow<TestNet>()(ek);
1810 const double dfs_value = aumenting_path_maximum_flow<TestNet, Find_Aumenting_Path_DFS>(dfs);
1811
1812 EXPECT_TRUE(ff.check_network());
1813 EXPECT_TRUE(ek.check_network());
1814 EXPECT_TRUE(dfs.check_network());
1815 EXPECT_NEAR(ff_value, ek_value, 1e-12);
1816 EXPECT_NEAR(dfs_value, ek_value, 1e-12);
1817}
1818
1819// The paths of a depth-first search took the residues of rounding that
1820// capacities in tenths leave, of an ulp, and spread them, so that the flows
1821// left the multiples of 0.1 and the slacks of the paths went down to 1e-17:
1822// Ford-Fulkerson did not end on this network of 400 nodes. With a floating
1823// flow it takes the shortest paths, as Edmonds-Karp
1824TEST(FordFulkersonTest, DecimalCapacitiesEndOnAMidSizeNetwork)
1825{
1826 // n nodes; 0 is the source and n - 1 the sink; every other node has an
1827 // arc from an earlier one and one to a later one; then 10 n arcs at
1828 // random, none into the source nor out of the sink
1829 const int n = 400;
1830 TestNet net;
1831 std::mt19937 gen(1);
1832 std::vector<Node *> nodes;
1833 for (int i = 0; i < n; ++i)
1834 nodes.push_back(net.insert_node(i));
1835 auto arc = [&] (int a, int b)
1836 {
1837 const double cap = double(1 + gen() % 40) * 0.1;
1838 net.insert_arc(nodes[size_t(a)], nodes[size_t(b)], cap);
1839 };
1840 for (int i = 1; i < n - 1; ++i)
1841 {
1842 arc(int(gen() % unsigned(i)), i);
1843 arc(i, i + 1 + int(gen() % unsigned(n - 1 - i)));
1844 }
1845 for (int k = 0; k < 10 * n; ++k)
1846 {
1847 const int a = int(gen() % unsigned(n - 1));
1848 const int b = 1 + int(gen() % unsigned(n - 1));
1849 if (a != b)
1850 arc(a, b);
1851 }
1852
1853 const double value = Ford_Fulkerson_Maximum_Flow<TestNet>()(net);
1854
1855 EXPECT_TRUE(net.check_network());
1856 EXPECT_NEAR(value, 33.6, 1e-9); // 336 with the capacities by ten
1857}
1858
1859namespace
1860{
1861 // Whether a path of arcs of positive residual capacity, exactly, goes
1862 // from the source to the sink of net
1863 bool residual_path_to_sink(TestNet & net)
1864 {
1865 std::set<Node *> seen = {net.get_source()};
1866 std::vector<Node *> queue = {net.get_source()};
1867 for (size_t k = 0; k < queue.size(); ++k)
1868 for (TestNet::Node_Arc_Iterator it(queue[k]); it.has_curr(); it.next_ne())
1869 {
1870 Arc * a = it.get_curr();
1871 Node * v = nullptr;
1872 if (net.get_src_node(a) == queue[k] and a->cap - a->flow > 0)
1873 v = net.get_tgt_node(a);
1874 else if (net.get_tgt_node(a) == queue[k] and a->flow > 0)
1875 v = net.get_src_node(a);
1876 if (v != nullptr and seen.insert(v).second)
1877 queue.push_back(v);
1878 }
1879 return seen.count(net.get_sink()) > 0;
1880 }
1881
1882 // A network of capacities in tenths: arcs {u, v, tenths}, with the
1883 // nodes 0 to n - 1
1884 void build_tenths(TestNet & net, int n, const std::vector<std::array<int, 3>> & arcs)
1885 {
1886 std::vector<Node *> nodes;
1887 for (int i = 0; i < n; ++i)
1888 nodes.push_back(net.insert_node(i));
1889 for (const auto & a : arcs)
1890 net.insert_arc(nodes[size_t(a[0])], nodes[size_t(a[1])], a[2] / 10.0);
1891 }
1892
1893 // The cut that min_cut() gives with Maxflow on the network of n nodes
1894 // and arcs in tenths: the source with its side and the sink with its,
1895 // every arc from the side of the source to that of the sink full, every
1896 // one back empty, a capacity of the cut that is the value of the flow,
1897 // no path of residual capacity left, and a second return of the residues
1898 // of rounding that changes nothing
1899 template <template <class> class Maxflow>
1900 void expect_a_minimum_cut(int n, const std::vector<std::array<int, 3>> & arcs,
1901 double value, const char * name)
1902 {
1903 SCOPED_TRACE(name);
1904 TestNet net;
1905 build_tenths(net, n, arcs);
1906 DynSetTree<Node *> vs, vt;
1907 DynList<Arc *> cuts, cutt;
1908 EXPECT_NEAR((min_cut<TestNet, Maxflow>(net, vs, vt, cuts, cutt)), value, 1e-12);
1909 EXPECT_TRUE(vs.contains(net.get_source()));
1910 EXPECT_TRUE(vt.contains(net.get_sink()));
1911 double capacity = 0;
1912 for (Arc_Iterator<TestNet> it(net); it.has_curr(); it.next_ne())
1913 {
1914 Arc * a = it.get_curr();
1915 const bool from = vs.contains(net.get_src_node(a)), to = vs.contains(net.get_tgt_node(a));
1916 if (from and not to)
1917 {
1918 capacity += a->cap;
1919 EXPECT_EQ(a->flow, a->cap);
1920 }
1921 else if (to and not from)
1922 EXPECT_EQ(a->flow, 0);
1923 }
1924 EXPECT_NEAR(capacity, value, 1e-12);
1925 EXPECT_FALSE(residual_path_to_sink(net));
1926 EXPECT_TRUE(net.check_network());
1927
1928 std::vector<double> flows;
1929 for (Arc_Iterator<TestNet> it(net); it.has_curr(); it.next_ne())
1930 flows.push_back(it.get_curr()->flow);
1931 net_detail::return_dust(net, net.get_source(), net.get_sink());
1932 size_t i = 0;
1933 for (Arc_Iterator<TestNet> it(net); it.has_curr(); it.next_ne(), ++i)
1934 EXPECT_EQ(it.get_curr()->flow, flows[i]);
1935 }
1936
1937 template <template <class> class Maxflow>
1938 void expect_minimum_cuts_of_tenths(const char * name)
1939 {
1940 // Into node 2 come 0.1 + 0.8, and out goes their rounded sum, 2.8e-17
1941 // less, well within the tolerance of check_node(); the return of the
1942 // residues of the paths took it from 0->2, which then had residual
1943 // capacity, and min_cut() put the sink with the source, with no arc
1944 // in the cut. The cut is {0->2, 1->2}
1945 expect_a_minimum_cut<Maxflow>(4, {{0, 1, 31}, {0, 2, 1}, {1, 2, 8}, {2, 3, 29}}, 0.9, name);
1946
1947 // Likewise for node 4, with 1.3 + 1.5, where the return of the
1948 // residues of the preflows took it from 0->1 or 0->3, the cut, in
1949 // 7.5.0 too
1950 expect_a_minimum_cut<Maxflow>(6, {{0, 1, 13}, {1, 2, 25}, {0, 3, 15}, {2, 4, 25},
1951 {4, 5, 30}, {3, 4, 19}}, 2.8, name);
1952 }
1953
1954 template <class Net>
1955 struct DFS_Augmenting_Paths
1956 {
1957 typename Net::Flow_Type operator () (Net & net) const
1958 {
1959 return aumenting_path_maximum_flow<Net, Find_Aumenting_Path_DFS>(net);
1960 }
1961 };
1962}
1963
1964// The residues of rounding that a node keeps within the tolerance of
1965// check_node() stay where they are: returning them lowered by an ulp an
1966// arc that the flow saturates, of the minimum cut, so that the flow was
1967// no longer maximal
1968TEST(MinCutTest, AFloatingFlowKeepsTheArcsOfTheCutFull)
1969{
1970 expect_minimum_cuts_of_tenths<Ford_Fulkerson_Maximum_Flow>("ford_fulkerson");
1971 expect_minimum_cuts_of_tenths<Edmonds_Karp_Maximum_Flow>("edmonds_karp");
1972 expect_minimum_cuts_of_tenths<DFS_Augmenting_Paths>("depth-first paths");
1973 expect_minimum_cuts_of_tenths<Heap_Preflow_Maximum_Flow>("heap_preflow");
1974 expect_minimum_cuts_of_tenths<Fifo_Preflow_Maximum_Flow>("fifo_preflow");
1975 expect_minimum_cuts_of_tenths<Random_Preflow_Maximum_Flow>("random_preflow");
1976 expect_minimum_cuts_of_tenths<HLPP_Maximum_Flow>("hlpp");
1977 expect_minimum_cuts_of_tenths<Dinic_Maximum_Flow>("dinic");
1978 expect_minimum_cuts_of_tenths<Capacity_Scaling_Maximum_Flow>("capacity_scaling");
1979}
1980
1981// The return of the residues keeps what a node keeps or lacks within the
1982// tolerance of check_node(), also when another node has dust to return:
1983// 2 receives 0.1 + 0.8 and sends 0.9, 2.8e-17 less, and 5 sends 0.1 + 0.6
1984// and receives 0.7, 2.8e-17 less, both within their tolerance; 4 receives
1985// 5.6e-17 and sends nothing, far beyond its own. Only that dust goes back
1986TEST(ReturnDustTest, KeepsTheResiduesWithinTheToleranceBesideDust)
1987{
1988 TestNet net;
1989 std::vector<Node *> n;
1990 for (int i = 0; i < 8; ++i)
1991 n.push_back(net.insert_node(i));
1992 // 0 is the source and 3 the sink
1993 auto arc = [&] (int u, int v, double cap, double flow)
1994 {
1995 Arc * a = net.insert_arc(n[size_t(u)], n[size_t(v)], cap);
1996 a->flow = flow;
1997 return a;
1998 };
1999 Arc * kept[] = {arc(0, 1, 3.1, 0.8), arc(0, 2, 0.1, 0.1), arc(1, 2, 0.8, 0.8),
2000 arc(2, 3, 2.9, 0.9), arc(0, 5, 0.7, 0.7), arc(5, 6, 0.1, 0.1),
2001 arc(5, 7, 0.6, 0.6), arc(6, 3, 3.2, 0.1), arc(7, 3, 0.7, 0.6)};
2002 Arc * dust = arc(0, 4, 1, 5.5511151231257827e-17);
2003 arc(4, 3, 1, 0);
2004 ASSERT_TRUE(net.is_single_source() and net.is_single_sink());
2005 ASSERT_FALSE(net.check_node(n[4]));
2006 std::vector<double> flows;
2007 for (Arc * a : kept)
2008 flows.push_back(a->flow);
2009
2010 net_detail::return_dust(net, n[0], n[3]);
2011
2012 for (size_t i = 0; i < flows.size(); ++i)
2013 EXPECT_EQ(kept[i]->flow, flows[i]) << "arc " << i;
2014 EXPECT_EQ(dust->flow, 0);
2015 EXPECT_TRUE(net.check_network());
2016}
2017
2018// The last pass: when nothing reaches the sink, the dust that leaves the
2019// source goes back from the arcs of the source with the least flow first,
2020// and when nothing leaves the source, that which reaches the sink from
2021// the arcs of the sink. Of 5d and d through two arcs of the end, with 4d
2022// back through a third, the 2d of dust take the d of the smaller arc and
2023// then a d of the larger: in the other order, the larger would give both.
2024// A large circulation through a, b and c keeps their imbalances within
2025// their tolerances, so that only the end has dust
2026TEST(ReturnDustTest, ReturnsTheDustOfAnEndFromItsSmallestFlowsFirst)
2027{
2028 const double d = 0x1p-40;
2029 for (bool at_source : {true, false})
2030 {
2031 TestNet net;
2032 Node * s = net.insert_node(0), * a = net.insert_node(1), * b = net.insert_node(2),
2033 * c = net.insert_node(3), * t = net.insert_node(4);
2034 net.insert_arc(a, c, 2e6)->flow = 1e6;
2035 net.insert_arc(c, a, 2e6)->flow = 1e6;
2036 net.insert_arc(b, c, 2e6)->flow = 1e6;
2037 net.insert_arc(c, b, 2e6)->flow = 1e6;
2038 Arc * big, * small, * back;
2039 if (at_source)
2040 {
2041 big = net.insert_arc(s, a, 1.0);
2042 small = net.insert_arc(s, b, 1.0);
2043 back = net.insert_arc(c, s, 1.0);
2044 net.insert_arc(a, t, 1.0); // which takes nothing
2045 }
2046 else
2047 {
2048 big = net.insert_arc(a, t, 1.0);
2049 small = net.insert_arc(b, t, 1.0);
2050 back = net.insert_arc(t, c, 1.0);
2051 net.insert_arc(s, a, 1.0); // which gives nothing
2052 }
2053 big->flow = 5 * d;
2054 small->flow = d;
2055 back->flow = 4 * d;
2056
2057 net_detail::return_dust(net, s, t);
2058
2059 const char * end = at_source ? "source" : "sink";
2060 EXPECT_EQ(big->flow, 4 * d) << end;
2061 EXPECT_EQ(small->flow, 0) << end;
2062 EXPECT_EQ(back->flow, 4 * d) << end;
2063 }
2064}
2065
2066namespace
2067{
2068 // A maximum flow of the library, with its name
2069 struct Named_Maximum_Flow
2070 {
2071 const char * name;
2072 double (*run)(TestNet &);
2073 };
2074
2075 // Those that take augmenting paths or blocking flows
2076 const Named_Maximum_Flow path_maximum_flows[] = {
2077 {"ford_fulkerson", [] (TestNet & net) { return ford_fulkerson_maximum_flow(net); }},
2078 {"edmonds_karp", [] (TestNet & net) { return edmonds_karp_maximum_flow(net); }},
2079 {"dinic", [] (TestNet & net) { return dinic_maximum_flow(net); }},
2080 {"capacity_scaling", [] (TestNet & net) { return capacity_scaling_maximum_flow(net); }}};
2081
2082 // And the preflows
2083 const Named_Maximum_Flow preflow_maximum_flows[] = {
2084 {"fifo_preflow", [] (TestNet & net) { return fifo_preflow_maximum_flow(net); }},
2085 {"heap_preflow", [] (TestNet & net) { return heap_preflow_maximum_flow(net); }},
2086 {"random_preflow", [] (TestNet & net) { return random_preflow_maximum_flow(net); }},
2087 {"hlpp", [] (TestNet & net) { return hlpp_maximum_flow(net); }}};
2088} // anonymous namespace
2089
2090// A network of arcs of infinite capacity alone: its maximum flow is
2091// infinite. The capacity scaling takes its first delta from the largest
2092// finite capacity, and that there is none is no reason to return 0
2093TEST(InfiniteCapacityTest, ArcsOfInfiniteCapacityAloneGiveAnInfiniteMaximumFlow)
2094{
2095 const double inf = std::numeric_limits<double>::infinity();
2096 auto check = [inf] (const Named_Maximum_Flow & f)
2097 {
2098 TestNet net;
2099 auto s = net.insert_node(0);
2100 auto a = net.insert_node(1);
2101 auto t = net.insert_node(2);
2102 net.insert_arc(s, a, inf);
2103 net.insert_arc(a, t, inf);
2104 EXPECT_EQ(f.run(net), inf) << f.name;
2105 EXPECT_TRUE(net.check_network()) << f.name;
2106 };
2107 for (const auto & f : path_maximum_flows)
2108 check(f);
2109 for (const auto & f : preflow_maximum_flows)
2110 check(f);
2111}
2112
2113// An arc of infinite capacity, which the notes of the cost tolerances give
2114// to an arc without a bound, takes flow as any other: s -> a of capacity
2115// infinity and a -> t of 2.5, s -> b of 1.5 and b -> t of infinity. The
2116// capacity scaling doubled its first delta up to the largest capacity, and
2117// with an infinite one it did not end, also on this network, whose maximum
2118// flow is 4; the preflows filled s -> a with infinity, which a could not
2119// send back, and gave an infinite flow
2120TEST(InfiniteCapacityTest, AFinitePathThroughAnInfiniteArcCarriesItsBottleneck)
2121{
2122 const double inf = std::numeric_limits<double>::infinity();
2123 auto check = [inf] (const Named_Maximum_Flow & f)
2124 {
2125 TestNet net;
2126 auto s = net.insert_node(0);
2127 auto a = net.insert_node(1);
2128 auto b = net.insert_node(2);
2129 auto t = net.insert_node(3);
2130 net.insert_arc(s, a, inf);
2131 net.insert_arc(a, t, 2.5);
2132 net.insert_arc(s, b, 1.5);
2133 net.insert_arc(b, t, inf);
2134 EXPECT_EQ(f.run(net), 4.0) << f.name;
2135 EXPECT_TRUE(net.check_network()) << f.name;
2136 };
2137 // s -> a of infinity, a -> t of 1, a -> b of 5 and b -> t of infinity:
2138 // with an arc of infinite capacity into the sink, the arcs into it do
2139 // not bound the flow out of s -> a, 6, and the sum of the finite
2140 // capacities does
2141 auto check_bound = [inf] (const Named_Maximum_Flow & f)
2142 {
2143 TestNet net;
2144 auto s = net.insert_node(0);
2145 auto a = net.insert_node(1);
2146 auto b = net.insert_node(2);
2147 auto t = net.insert_node(3);
2148 net.insert_arc(s, a, inf);
2149 net.insert_arc(a, t, 1.0);
2150 net.insert_arc(a, b, 5.0);
2151 net.insert_arc(b, t, inf);
2152 EXPECT_EQ(f.run(net), 6.0) << f.name;
2153 EXPECT_TRUE(net.check_network()) << f.name;
2154 };
2155 for (const auto & f : path_maximum_flows)
2156 {
2157 check(f);
2158 check_bound(f);
2159 }
2160 for (const auto & f : preflow_maximum_flows)
2161 {
2162 check(f);
2163 check_bound(f);
2164 }
2165}
2166
2167// A path from the source to the sink of arcs of infinite capacity makes
2168// the maximum flow infinite, which every maximum flow returns. Dinic took
2169// the same path forever, as the residual of an arc of infinite capacity
2170// and flow, inf - inf, is NaN, which it compared as residual <= 0; and
2171// the capacity scaling did not end. A capacity of max() is finite, and
2172// so is the flow, max()
2173TEST(InfiniteCapacityTest, APathOfInfiniteArcsMakesTheMaximumFlowInfinite)
2174{
2175 auto check = [] (const Named_Maximum_Flow & f, double cap)
2176 {
2177 TestNet net;
2178 auto s = net.insert_node(0);
2179 auto a = net.insert_node(1);
2180 auto t = net.insert_node(2);
2181 net.insert_arc(s, a, cap);
2182 net.insert_arc(a, t, cap);
2183 net.insert_arc(s, t, 2.5);
2184 EXPECT_EQ(f.run(net), cap) << f.name << " with a capacity of " << cap;
2185 };
2186 for (const double cap : {std::numeric_limits<double>::infinity(),
2187 std::numeric_limits<double>::max()})
2188 {
2189 for (const auto & f : path_maximum_flows)
2190 check(f, cap);
2191 for (const auto & f : preflow_maximum_flows)
2192 check(f, cap);
2193 }
2194}
2195
2196// A path of arcs of infinite capacity beside an arc of infinite capacity
2197// that leads where only finite arcs go on: the maximum flow is infinite,
2198// which every maximum flow returns with a flow that every node keeps
2199TEST(InfiniteCapacityTest, AnInfinitePathBesideAnInfiniteArcToAFinitePart)
2200{
2201 const double inf = std::numeric_limits<double>::infinity();
2202 auto check = [inf] (const Named_Maximum_Flow & f)
2203 {
2204 TestNet net;
2205 auto s = net.insert_node(0);
2206 auto a = net.insert_node(1);
2207 auto b = net.insert_node(2);
2208 auto t = net.insert_node(3);
2209 net.insert_arc(s, b, inf); // b sends on only 1.5
2210 net.insert_arc(b, t, 1.5);
2211 net.insert_arc(s, a, inf);
2212 net.insert_arc(a, t, inf);
2213 EXPECT_EQ(f.run(net), inf) << f.name;
2214 EXPECT_TRUE(net.check_network()) << f.name;
2215 };
2216 for (const auto & f : path_maximum_flows)
2217 check(f);
2218 for (const auto & f : preflow_maximum_flows)
2219 check(f);
2220}
2221
2222// Dinic and HLPP keep the cookies that the caller left in the nodes, also
2223// with an arc of infinite capacity out of the source: on s -> a of
2224// infinity and a -> t of 2.5, and on a path of arcs of infinite capacity.
2225// HLPP searched for such a path, whose search writes in the cookies,
2226// before saving them, and the nodes lost theirs
2227TEST(InfiniteCapacityTest, DinicAndHlppKeepTheCookiesOfTheNodes)
2228{
2229 const double inf = std::numeric_limits<double>::infinity();
2230 const Named_Maximum_Flow keepers[] = {
2231 {"dinic", [] (TestNet & net) { return dinic_maximum_flow(net); }},
2232 {"hlpp", [] (TestNet & net) { return hlpp_maximum_flow(net); }}};
2233 for (const auto & f : keepers)
2234 for (const double cap : {2.5, inf})
2235 {
2236 TestNet net;
2237 auto s = net.insert_node(0);
2238 auto a = net.insert_node(1);
2239 auto t = net.insert_node(2);
2240 net.insert_arc(s, a, inf);
2241 net.insert_arc(a, t, cap);
2242 int tags[3] = {0, 1, 2};
2243 NODE_COOKIE(s) = &tags[0];
2244 NODE_COOKIE(a) = &tags[1];
2245 NODE_COOKIE(t) = &tags[2];
2246 EXPECT_EQ(f.run(net), cap) << f.name << " with a -> t of " << cap;
2247 EXPECT_EQ(NODE_COOKIE(s), static_cast<void *>(&tags[0]))
2248 << f.name << " with a -> t of " << cap;
2249 EXPECT_EQ(NODE_COOKIE(a), static_cast<void *>(&tags[1]))
2250 << f.name << " with a -> t of " << cap;
2251 EXPECT_EQ(NODE_COOKIE(t), static_cast<void *>(&tags[2]))
2252 << f.name << " with a -> t of " << cap;
2253 }
2254}
2255
2256
2257int main(int argc, char** argv)
2258{
2259 ::testing::InitGoogleTest(&argc, argv);
2260 return RUN_ALL_TESTS();
2261}
#define ah_invalid_argument_if(C)
Throws std::invalid_argument if condition holds.
Definition ah-errors.H:787
WeightedDigraph::Node Node
WeightedDigraph::Arc Arc
int main()
size_t size_t int32_t value
Definition ca-c-api.h:116
size_t * rows
Definition ca-c-api.h:112
size_t cols
Definition ca-c-api.h:105
Iterator over the arcs of a node.
Definition tpl_agraph.H:354
bool has_curr() const noexcept
Return true if the iterator is on an arc.
Definition tpl_agraph.H:387
static Array create(const size_t n)
Create an array with n logical elements.
Definition tpl_array.H:245
bool has_curr() const noexcept
Return true the iterator has an current arc.
Definition tpl_graph.H:1822
Dynamic queue of elements of generic type T based on single linked list.
T & put(const T &data)
The type of element.
T get()
Remove the oldest item of the queue.
T & front()
Return a modifiable reference to the oldest item in the queue.
T & insert(const T &data)
bool is_empty() const noexcept
Return true if this is empty.
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
Generic key-value map implemented on top of a binary search tree.
Dynamic set backed by balanced binary search trees with automatic memory management.
bool contains(const Key &key) const
Checks if a key exists in the set.
void next_ne() noexcept(shows_ne)
Advances the iterator to the next filtered element, as next() does.
Filtered iterator for incoming arcs of a node.
Definition tpl_graph.H:2045
Number Theoretic Transform over Z / MOD Z.
Definition ntt.H:115
Node * insert_node(Node *p) override
Filtered iterator on the nodes of a graph.
Definition tpl_graph.H:1287
Filtered iterator for outcoming arcs of a node.
Definition tpl_graph.H:1942
Node * get_src_node(Arc *arc) const noexcept
Return the source node of arc (only for directed graphs)
Definition graph-dry.H:1017
Node * get_connected_node(Arc *arc, Node *node) const noexcept
Return the adjacent node to node through arc.
Definition graph-dry.H:1058
Node * get_tgt_node(Arc *arc) const noexcept
Return the target node of arc (only for directed graphs)
Definition graph-dry.H:1023
#define TEST(name)
static mt19937 rng
#define N
Definition fib.C:294
DynArray< Graph::Node * > nodes
Definition graphpic.C:406
DynArray< Graph::Arc * > arcs
Definition graphpic.C:408
#define NODE_COOKIE(p)
Return the node cookie
Net build_grid_network(int rows, int cols, FlowType base_cap=10.0)
Build a grid network for stress testing.
void return_dust(Net &net, typename Net::Node *source, typename Net::Node *sink)
Returns the dust of a floating flow that a preflow algorithm left in net, from source to sink: what e...
Definition tpl_net.H:1410
Main namespace for Aleph-w library functions.
FlowStatistics< typename Net::Flow_Type > compute_flow_statistics(const Net &net)
Compute statistics about the current flow in a network.
Net::Flow_Type edmonds_karp_maximum_flow(Net &net)
Maximize flow using the Edmonds-Karp algorithm.
Definition tpl_net.H:2336
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
Net::Flow_Type random_preflow_maximum_flow(Net &net)
Preflow-push maximum flow using a random active-node queue.
Definition tpl_net.H:2738
Net::Flow_Type dinic_maximum_flow(Net &net)
Compute maximum flow using Dinic's algorithm.
Net::Flow_Type heap_preflow_maximum_flow(Net &net)
Preflow-push maximum flow using a height-ordered heap.
Definition tpl_net.H:2706
FlowDecomposition< Net > decompose_flow(const Net &net)
Decompose network flow into paths and cycles.
Net::Flow_Type capacity_scaling_maximum_flow(Net &net)
Compute maximum flow using capacity scaling.
Net::Flow_Type hlpp_maximum_flow(Net &net)
Compute maximum flow using Highest-Label Preflow-Push.
and
Check uniqueness with explicit hash + equality functors.
Net::Flow_Type fifo_preflow_maximum_flow(Net &net)
Preflow-push maximum flow using a FIFO queue of active nodes.
Definition tpl_net.H:2668
Net::Flow_Type ford_fulkerson_maximum_flow(Net &net)
Maximize flow using the Ford-Fulkerson algorithm.
Definition tpl_net.H:2306
Net::Flow_Type min_cut(Net &net, DynSetTree< typename Net::Node * > &vs, DynSetTree< typename Net::Node * > &vt, DynList< typename Net::Arc * > &cuts, DynList< typename Net::Arc * > &cutt)
Compute max flow and the corresponding minimum cut.
Definition tpl_net.H:2790
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
Definition ahAlgo.H:127
Filtered iterator on all the arcs of a graph.
Definition tpl_graph.H:1200
Functor wrapper for capacity scaling.
Functor wrapper for flow decomposition.
Functor wrapper for Dinic's algorithm.
Functor wrapper for edmonds_karp_maximum_flow().
Definition tpl_net.H:2347
Functor wrapper for ford_fulkerson_maximum_flow().
Definition tpl_net.H:2320
Functor wrapper for HLPP.
Arc of a flow network implemented with adjacency lists.
Definition tpl_net.H:160
Flow network implemented with adjacency lists.
Definition tpl_net.H:311
Node * insert_node(const Node_Type &node_info)
Insert a new node by copying node_info.
Definition tpl_net.H:750
bool check_network() const
Validate flow-conservation and capacity constraints.
Definition tpl_net.H:1116
constexpr bool is_single_source() const noexcept
Return true if the network has a single source.
Definition tpl_net.H:429
bool is_source(Node *node) const noexcept
Return true if node is a source.
Definition tpl_net.H:417
Node * get_source() const
Return an arbitrary source node.
Definition tpl_net.H:733
Arc * insert_arc(Node *src_node, Node *tgt_node, const Flow_Type &cap, const Flow_Type &flow, const typename Arc::Arc_Type &arc_info=Arc_Type())
Insert a capacitated arc with an initial flow.
Definition tpl_net.H:799
ArcT Arc
Arc type.
Definition tpl_net.H:322
Node * get_sink() const
Return an arbitrary sink node.
Definition tpl_net.H:739
bool is_sink(Node *node) const noexcept
Return true if node is a sink.
Definition tpl_net.H:423
typename Arc::Flow_Type Flow_Type
Capacity/flow numeric type.
Definition tpl_net.H:328
constexpr bool is_single_sink() const noexcept
Return true if the network has a single sink.
Definition tpl_net.H:435
NodeT Node
Node type.
Definition tpl_net.H:325
bool check_node(Node *node) const noexcept
Return true if node satisfies flow conservation constraints.
Definition tpl_net.H:468
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
bool check(GT &g)
ValueArg< size_t > seed
Definition testHash.C:53
static int * k
Advanced maximum flow algorithms.
void verify_flow_conservation(const Net &net)
Node * build_antiparallel_network(TestNet &net)
bool verify_max_flow_min_cut(Net &net, double max_flow)
double compute_min_cut_capacity(Net &net)
Network flow graph structures.
Treap< int >::Node * last_node
Definition writeTreap.C:60