Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
tpl_netcost_test.cc
Go to the documentation of this file.
1
2/*
3 Aleph_w
4
5 Data structures & Algorithms
6 version 2.0.0b
7 https://github.com/lrleon/Aleph-w
8
9 This file is part of Aleph-w library
10
11 Copyright (c) 2002-2026 Leandro Rabindranath Leon
12
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
19
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
22
23 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 SOFTWARE.
30*/
31
32
33
38#include <gtest/gtest.h>
39#include <sstream>
40#include <array>
41#include <cmath>
42#include <limits>
43#include <random>
44#include <stdexcept>
45#include <string>
46#include <vector>
47
48#include <tpl_maxflow.H>
49#include <tpl_netcost.H>
50
51using namespace Aleph;
52
53namespace
54{
55
56// Type aliases for convenience
57using Net = Net_Cost_Graph<>;
58using Node = Net::Node;
59using Arc = Net::Arc;
60
61// =============================================================================
62// NET_COST_ARC TESTS
63// =============================================================================
64
65class NetCostArcTest : public ::testing::Test
66{
67protected:
69};
70
71TEST_F(NetCostArcTest, DefaultConstructor)
72{
73 TestArc arc;
74 EXPECT_EQ(arc.cost, 0.0);
75 EXPECT_EQ(arc.flow, 0.0);
76 EXPECT_EQ(arc.cap, 0.0);
77}
78
79TEST_F(NetCostArcTest, CopyConstructor)
80{
81 TestArc arc1;
82 arc1.cost = 5.5;
83 arc1.flow = 2.0;
84 arc1.cap = 10.0;
85
86 TestArc arc2(arc1);
87 EXPECT_EQ(arc2.cost, 5.5);
88 EXPECT_EQ(arc2.flow, 2.0);
89 EXPECT_EQ(arc2.cap, 10.0);
90}
91
92TEST_F(NetCostArcTest, CopyAssignment)
93{
94 TestArc arc1;
95 arc1.cost = 3.3;
96 arc1.flow = 1.0;
97 arc1.cap = 5.0;
98
99 TestArc arc2;
100 arc2 = arc1;
101 EXPECT_EQ(arc2.cost, 3.3);
102 EXPECT_EQ(arc2.flow, 1.0);
103 EXPECT_EQ(arc2.cap, 5.0);
104}
105
106TEST_F(NetCostArcTest, SelfAssignment)
107{
108 TestArc arc;
109 arc.cost = 7.7;
110 arc.flow = 3.0;
111 arc.cap = 8.0;
112
113 arc = arc;
114 EXPECT_EQ(arc.cost, 7.7);
115 EXPECT_EQ(arc.flow, 3.0);
116 EXPECT_EQ(arc.cap, 8.0);
117}
118
119TEST_F(NetCostArcTest, FlowCost)
120{
121 TestArc arc;
122 arc.cost = 2.5;
123 arc.flow = 4.0;
124 EXPECT_DOUBLE_EQ(arc.flow_cost(), 10.0); // 2.5 * 4.0 = 10.0
125}
126
127TEST_F(NetCostArcTest, FlowCostZeroFlow)
128{
129 TestArc arc;
130 arc.cost = 100.0;
131 arc.flow = 0.0;
132 EXPECT_DOUBLE_EQ(arc.flow_cost(), 0.0);
133}
134
135TEST_F(NetCostArcTest, FlowCostZeroCost)
136{
137 TestArc arc;
138 arc.cost = 0.0;
139 arc.flow = 50.0;
140 EXPECT_DOUBLE_EQ(arc.flow_cost(), 0.0);
141}
142
143TEST_F(NetCostArcTest, FlowCostNegativeCost)
144{
145 TestArc arc;
146 arc.cost = -3.0;
147 arc.flow = 5.0;
148 EXPECT_DOUBLE_EQ(arc.flow_cost(), -15.0);
149}
150
151
152// =============================================================================
153// NET_COST_GRAPH BASIC TESTS
154// =============================================================================
155
156class NetCostGraphTest : public ::testing::Test
157{
158protected:
159 Net net;
160};
161
162TEST_F(NetCostGraphTest, DefaultConstructor)
163{
164 EXPECT_EQ(net.vsize(), 0);
165 EXPECT_EQ(net.esize(), 0);
166}
167
168TEST_F(NetCostGraphTest, InsertNode)
169{
170 auto n = net.insert_node();
171 EXPECT_NE(n, nullptr);
172 EXPECT_EQ(net.vsize(), 1);
173}
174
175TEST_F(NetCostGraphTest, InsertArcWithCost)
176{
177 auto s = net.insert_node();
178 auto t = net.insert_node();
179 auto arc = net.insert_arc(s, t, 10.0, 2.5);
180
181 EXPECT_NE(arc, nullptr);
182 EXPECT_EQ(arc->cap, 10.0);
183 EXPECT_EQ(arc->cost, 2.5);
184 EXPECT_EQ(arc->flow, 0.0);
185}
186
187TEST_F(NetCostGraphTest, GetCostModifiable)
188{
189 auto s = net.insert_node();
190 auto t = net.insert_node();
191 auto arc = net.insert_arc(s, t, 10.0, 5.0);
192
193 net.get_cost(arc) = 7.5;
194 EXPECT_EQ(arc->cost, 7.5);
195}
196
197TEST_F(NetCostGraphTest, GetCostConst)
198{
199 auto s = net.insert_node();
200 auto t = net.insert_node();
201 auto arc = net.insert_arc(s, t, 10.0, 3.0);
202
203 const Net& const_net = net;
204 EXPECT_EQ(const_net.get_cost(arc), 3.0);
205}
206
207TEST_F(NetCostGraphTest, ArcFlowCost)
208{
209 auto s = net.insert_node();
210 auto t = net.insert_node();
211 auto arc = net.insert_arc(s, t, 10.0, 2.0);
212 arc->flow = 5.0;
213
214 EXPECT_DOUBLE_EQ(net.arc_flow_cost(arc), 10.0); // 5.0 * 2.0
215}
216
217TEST_F(NetCostGraphTest, TotalFlowCost)
218{
219 auto s = net.insert_node();
220 auto a = net.insert_node();
221 auto t = net.insert_node();
222
223 auto arc1 = net.insert_arc(s, a, 10.0, 2.0);
224 auto arc2 = net.insert_arc(a, t, 10.0, 3.0);
225
226 arc1->flow = 5.0;
227 arc2->flow = 4.0;
228
229 // Total cost = 5*2 + 4*3 = 10 + 12 = 22
230 EXPECT_DOUBLE_EQ(net.flow_cost(), 22.0);
231}
232
233TEST_F(NetCostGraphTest, TotalFlowCostEmpty)
234{
235 EXPECT_DOUBLE_EQ(net.flow_cost(), 0.0);
236}
237
238
239// =============================================================================
240// NET_COST_GRAPH COPY TESTS
241// =============================================================================
242
243class NetCostGraphCopyTest : public ::testing::Test
244{
245protected:
246 Net net;
247 Node *s, *a, *t;
248 Arc *arc1, *arc2;
249
250 void SetUp() override
251 {
252 s = net.insert_node();
253 a = net.insert_node();
254 t = net.insert_node();
255
256 arc1 = net.insert_arc(s, a, 10.0, 2.0);
257 arc2 = net.insert_arc(a, t, 8.0, 3.0);
258
259 arc1->flow = 5.0;
260 arc2->flow = 4.0;
261 }
262};
263
264TEST_F(NetCostGraphCopyTest, CopyConstructor)
265{
266 Net copy(net);
267
268 EXPECT_EQ(copy.vsize(), net.vsize());
269 EXPECT_EQ(copy.esize(), net.esize());
270 EXPECT_DOUBLE_EQ(copy.flow_cost(), net.flow_cost());
271}
272
273TEST_F(NetCostGraphCopyTest, CopyConstructorPreservesCosts)
274{
275 Net copy(net);
276
277 // Verify that total costs are preserved
278 EXPECT_DOUBLE_EQ(copy.flow_cost(), net.flow_cost());
279}
280
281TEST_F(NetCostGraphCopyTest, CopyAssignment)
282{
283 Net copy;
284 copy = net;
285
286 EXPECT_EQ(copy.vsize(), net.vsize());
287 EXPECT_EQ(copy.esize(), net.esize());
288 EXPECT_DOUBLE_EQ(copy.flow_cost(), net.flow_cost());
289}
290
291TEST_F(NetCostGraphCopyTest, SelfCopyAssignment)
292{
293 auto original_cost = net.flow_cost();
294 net = net;
295 EXPECT_DOUBLE_EQ(net.flow_cost(), original_cost);
296}
297
298
299// =============================================================================
300// RESIDUAL NETWORK TESTS
301// =============================================================================
302
303class ResidualNetTest : public ::testing::Test
304{
305protected:
306 using Rnet = Residual_Net<double>;
307};
308
309TEST_F(ResidualNetTest, CreateResidualArc)
310{
311 Rnet rnet;
312 auto s = rnet.insert_node();
313 auto t = rnet.insert_node();
314
315 auto arc = create_residual_arc(rnet, s, t, 10.0, 3.0, 2.0);
316
317 EXPECT_NE(arc, nullptr);
318 EXPECT_EQ(arc->cap, 10.0);
319 EXPECT_EQ(arc->flow, 3.0);
320 EXPECT_EQ(arc->cost, 2.0);
321 EXPECT_FALSE(arc->is_residual);
322
323 // Check mirror arc
324 EXPECT_NE(arc->img, nullptr);
325 EXPECT_EQ(arc->img->cap, 10.0);
326 EXPECT_EQ(arc->img->flow, 7.0); // cap - flow = 10 - 3
327 EXPECT_EQ(arc->img->cost, -2.0); // Negative cost
328 EXPECT_TRUE(arc->img->is_residual);
329
330 // Check bidirectional link
331 EXPECT_EQ(arc->img->img, arc);
332}
333
334TEST_F(ResidualNetTest, CheckResidualNetConsistency)
335{
336 Rnet rnet;
337 auto s = rnet.insert_node();
338 auto t = rnet.insert_node();
339
340 create_residual_arc(rnet, s, t, 10.0, 3.0, 2.0);
341 create_residual_arc(rnet, s, t, 5.0, 2.0, 1.0);
342
343 EXPECT_TRUE(check_residual_net(rnet));
344}
345
346
347// =============================================================================
348// FILTER TESTS
349// =============================================================================
350
351class FilterTest : public ::testing::Test
352{
353protected:
354 Net net;
355};
356
357TEST_F(FilterTest, ResFiltPositiveResidual)
358{
359 auto s = net.insert_node();
360 auto t = net.insert_node();
361 auto arc = net.insert_arc(s, t, 10.0, 2.0);
362 arc->flow = 5.0; // residual = 5
363
365 EXPECT_TRUE(filter(arc));
366}
367
368TEST_F(FilterTest, ResFiltZeroResidual)
369{
370 auto s = net.insert_node();
371 auto t = net.insert_node();
372 auto arc = net.insert_arc(s, t, 10.0, 2.0);
373 arc->flow = 10.0; // residual = 0
374
376 EXPECT_FALSE(filter(arc));
377}
378
379TEST_F(FilterTest, RcostReturnsArcCost)
380{
381 auto s = net.insert_node();
382 auto t = net.insert_node();
383 auto arc = net.insert_arc(s, t, 10.0, 7.5);
384
385 Rcost<Net> rcost;
386 EXPECT_DOUBLE_EQ(rcost(arc), 7.5);
387}
388
389TEST_F(FilterTest, RcostSetZero)
390{
391 auto s = net.insert_node();
392 auto t = net.insert_node();
393 auto arc = net.insert_arc(s, t, 10.0, 5.0);
394 arc->flow = 3.0;
395
397
398 EXPECT_EQ(arc->cap, std::numeric_limits<double>::max());
399 EXPECT_EQ(arc->flow, 0.0);
400 EXPECT_EQ(arc->cost, 0.0);
401}
402
403
404// =============================================================================
405// OUT_PARS AND IN_PARS TESTS
406// =============================================================================
407
408class FlowParsTest : public ::testing::Test
409{
410protected:
411 Net net;
412 Node *s, *a, *b, *t;
413
414 void SetUp() override
415 {
416 s = net.insert_node();
417 a = net.insert_node();
418 b = net.insert_node();
419 t = net.insert_node();
420 }
421};
422
423TEST_F(FlowParsTest, OutParsMultipleArcs)
424{
425 auto arc1 = net.insert_arc(s, a, 10.0, 2.0);
426 auto arc2 = net.insert_arc(s, b, 5.0, 3.0);
427 arc1->flow = 4.0;
428 arc2->flow = 2.0;
429
430 auto [cap, flow, cost] = net.out_pars(s);
431
432 EXPECT_DOUBLE_EQ(cap, 15.0); // 10 + 5
433 EXPECT_DOUBLE_EQ(flow, 6.0); // 4 + 2
434 EXPECT_DOUBLE_EQ(cost, 5.0); // 2 + 3
435}
436
437TEST_F(FlowParsTest, InParsMultipleArcs)
438{
439 auto arc1 = net.insert_arc(a, t, 10.0, 2.0);
440 auto arc2 = net.insert_arc(b, t, 5.0, 3.0);
441 arc1->flow = 4.0;
442 arc2->flow = 2.0;
443
444 auto [cap, flow, cost] = net.in_pars(t);
445
446 EXPECT_DOUBLE_EQ(cap, 15.0);
447 EXPECT_DOUBLE_EQ(flow, 6.0);
448 EXPECT_DOUBLE_EQ(cost, 5.0);
449}
450
451TEST_F(FlowParsTest, OutParsNoArcs)
452{
453 auto [cap, flow, cost] = net.out_pars(s);
454
455 EXPECT_DOUBLE_EQ(cap, 0.0);
456 EXPECT_DOUBLE_EQ(flow, 0.0);
457 EXPECT_DOUBLE_EQ(cost, 0.0);
458}
459
460
461// =============================================================================
462// EDGE CASE TESTS
463// =============================================================================
464
465class EdgeCaseTest : public ::testing::Test
466{
467};
468
469TEST_F(EdgeCaseTest, EmptyNetwork)
470{
471 Net net;
472 EXPECT_EQ(net.flow_cost(), 0.0);
473}
474
475TEST_F(EdgeCaseTest, SingleNodeNetwork)
476{
477 Net net;
478 net.insert_node();
479
480 EXPECT_EQ(net.vsize(), 1);
481 EXPECT_EQ(net.esize(), 0);
482 EXPECT_EQ(net.flow_cost(), 0.0);
483}
484
485TEST_F(EdgeCaseTest, ZeroCostArcs)
486{
487 Net net;
488 auto s = net.insert_node();
489 auto t = net.insert_node();
490
491 auto arc = net.insert_arc(s, t, 100.0, 0.0);
492 arc->flow = 50.0;
493
494 EXPECT_EQ(net.flow_cost(), 0.0);
495}
496
497TEST_F(EdgeCaseTest, VeryLargeCosts)
498{
499 Net net;
500 auto s = net.insert_node();
501 auto t = net.insert_node();
502
503 double large_cost = 1e10;
504 auto arc = net.insert_arc(s, t, 100.0, large_cost);
505 arc->flow = 5.0;
506
507 EXPECT_DOUBLE_EQ(net.flow_cost(), 5.0 * large_cost);
508}
509
510TEST_F(EdgeCaseTest, IntegerFlowType)
511{
513
514 IntNet net;
515 auto s = net.insert_node();
516 auto t = net.insert_node();
517
518 auto arc = net.insert_arc(s, t, 10, 3);
519 arc->flow = 4;
520
521 EXPECT_EQ(net.flow_cost(), 12); // 4 * 3
522}
523
524
525// =============================================================================
526// FEASIBLE SPANNING TREE TESTS (EXPERIMENTAL)
527// =============================================================================
528
529class FeasibleTreeTest : public ::testing::Test
530{
531protected:
532 Net net;
533};
534
535TEST_F(FeasibleTreeTest, ClassifiesArcsCorrectly)
536{
537 auto s = net.insert_node();
538 auto t = net.insert_node();
539
540 auto empty_arc = net.insert_arc(s, t, 10.0, 1.0);
541 empty_arc->flow = 0.0;
542
543 auto full_arc = net.insert_arc(s, t, 5.0, 2.0);
544 full_arc->flow = 5.0;
545
546 auto partial_arc = net.insert_arc(s, t, 8.0, 3.0);
547 partial_arc->flow = 3.0;
548
549 auto [empty, full, partial] = build_feasible_spanning_tree(net);
550
551 EXPECT_EQ(empty.size(), 1);
552 EXPECT_EQ(full.size(), 1);
553 EXPECT_EQ(partial.size(), 1);
554}
555
556TEST_F(FeasibleTreeTest, GetPartialArcs)
557{
558 auto s = net.insert_node();
559 auto t = net.insert_node();
560
561 auto arc1 = net.insert_arc(s, t, 10.0, 1.0);
562 arc1->flow = 0.0; // empty
563
564 auto arc2 = net.insert_arc(s, t, 10.0, 1.0);
565 arc2->flow = 10.0; // full
566
567 auto arc3 = net.insert_arc(s, t, 10.0, 1.0);
568 arc3->flow = 5.0; // partial
569
570 auto partials = get_partial_arcs(net);
571
572 EXPECT_EQ(partials.size(), 1);
573}
574
575
576// =============================================================================
577// MAX FLOW MIN COST INTEGRATION TESTS
578// =============================================================================
579
580class MaxFlowMinCostIntegrationTest : public ::testing::Test
581{
582protected:
583 // Classic example network from textbooks:
584 //
585 // (cap=4, cost=2)
586 // +--------> a --------+
587 // | | (cap=3, cost=1)
588 // | (cap=2, cost=3) v
589 // s ---+--------> b ------> t
590 // | ^ ^
591 // | | (cap=1, cost=1)
592 // | | |
593 // +--------> c --------+
594 // (cap=2, cost=1) (cap=4, cost=2)
595 //
596 // Optimal max flow = 5, optimal min cost = 14
597 //
598 // Flow assignment for min cost:
599 // s->a: 3, s->b: 0, s->c: 2
600 // a->t: 3
601 // c->b: 1, c->t: 1
602 // b->t: 1
603 //
604 // Cost = 3*2 + 2*1 + 3*1 + 1*1 + 1*2 + 1*3 = 6 + 2 + 3 + 1 + 2 + 3 = 17
605 // Actually, let's use a simpler example with verified solution.
606
607 // Simpler well-known example:
608 //
609 // (cap=3, cost=1)
610 // s --------> a --------> t
611 // | ^ ^
612 // | (cap=2, | (cap=2, | (cap=2, cost=1)
613 // | cost=2) | cost=0) |
614 // +---------> b ----------+
615 //
616 // This network has:
617 // - s->a: cap=3, cost=1
618 // - s->b: cap=2, cost=2
619 // - b->a: cap=2, cost=0
620 // - a->t: cap=3, cost=3
621 // - b->t: cap=2, cost=1
622 //
623 // Max flow = min(3+2, 3+2) = 5, which fills the arcs of s and those
624 // of t and leaves b->a empty: it is the only flow of 5
625 // s->a: 3, a->t: 3 (cost = 3*1 + 3*3 = 12)
626 // s->b: 2, b->t: 2 (cost = 2*2 + 2*1 = 6)
627 // Total cost = 18
628
629 Net build_textbook_network()
630 {
631 Net net;
632
633 auto s = net.insert_node();
634 auto a = net.insert_node();
635 auto b = net.insert_node();
636 auto t = net.insert_node();
637
638 // s->a: cap=3, cost=1
639 net.insert_arc(s, a, 3.0, 1.0);
640 // s->b: cap=2, cost=2
641 net.insert_arc(s, b, 2.0, 2.0);
642 // b->a: cap=2, cost=0 (transfer arc)
643 net.insert_arc(b, a, 2.0, 0.0);
644 // a->t: cap=3, cost=3
645 net.insert_arc(a, t, 3.0, 3.0);
646 // b->t: cap=2, cost=1
647 net.insert_arc(b, t, 2.0, 1.0);
648
649 return net;
650 }
651
652 // Very simple network: single path
653 // s ---(cap=5, cost=3)---> t
654 //
655 // Max flow = 5, cost = 15
656 Net build_single_path_network()
657 {
658 Net net;
659 auto s = net.insert_node();
660 auto t = net.insert_node();
661 net.insert_arc(s, t, 5.0, 3.0);
662 return net;
663 }
664
665 // Two parallel arcs network (multigraph with direct parallel arcs):
666 //
667 // s ===(cap=4, cost=1)===> t (cheap arc)
668 // s ===(cap=3, cost=2)===> t (expensive arc)
669 //
670 // This tests the algorithm's ability to handle multigraphs (parallel arcs
671 // between the same pair of nodes). This was a regression that caused infinite
672 // loops before the fix in tpl_net.H.
673 //
674 // Max flow = 7
675 // Min cost: both arcs are saturated since both go directly to sink
676 // Cost = 4*1 + 3*2 = 10
677 Net build_parallel_paths_network()
678 {
679 Net net;
680 auto s = net.insert_node();
681 auto t = net.insert_node();
682 net.insert_arc(s, t, 4.0, 1.0); // cheap arc
683 net.insert_arc(s, t, 3.0, 2.0); // expensive arc
684 return net;
685 }
686
687 // Diamond network with known optimal solution:
688 //
689 // (cap=3, cost=1)
690 // +--------> a --------+
691 // | | (cap=3, cost=2)
692 // s ---+ +---> t
693 // | |
694 // +--------> b --------+
695 // (cap=3, cost=2) (cap=3, cost=1)
696 //
697 // Max flow = 3 (limited by paths)
698 // Cheapest: 3 units via s->a->t costs 3*(1+2) = 9
699 // vs 3 units via s->b->t costs 3*(2+1) = 9
700 // Both paths have same cost!
701 Net build_diamond_network()
702 {
703 Net net;
704 auto s = net.insert_node();
705 auto a = net.insert_node();
706 auto b = net.insert_node();
707 auto t = net.insert_node();
708
709 net.insert_arc(s, a, 3.0, 1.0); // cheap entry
710 net.insert_arc(s, b, 3.0, 2.0); // expensive entry
711 net.insert_arc(a, t, 3.0, 2.0); // expensive exit
712 net.insert_arc(b, t, 3.0, 1.0); // cheap exit
713
714 return net;
715 }
716
717 // Helper to compute total outgoing flow from source
718 double get_max_flow(const Net& net)
719 {
720 double flow = 0;
721 auto source = net.get_source();
722 for (Out_Iterator<Net> it(source); it.has_curr(); it.next_ne())
723 flow += it.get_curr()->flow;
724 return flow;
725 }
726
727 // Helper to verify flow conservation at intermediate nodes
728 bool verify_flow_conservation(const Net& net)
729 {
730 auto source = net.get_source();
731 auto sink = net.get_sink();
732
733 for (auto p : net.nodes())
734 {
735 if (p == source || p == sink)
736 continue;
737
738 double in_flow = 0, out_flow = 0;
739
740 for (In_Iterator<Net> it(p); it.has_curr(); it.next_ne())
741 in_flow += it.get_curr()->flow;
742
743 for (Out_Iterator<Net> it(p); it.has_curr(); it.next_ne())
744 out_flow += it.get_curr()->flow;
745
746 if (std::abs(in_flow - out_flow) > 1e-9)
747 return false;
748 }
749 return true;
750 }
751
752 // Helper to verify capacity constraints
753 bool verify_capacity_constraints(const Net& net)
754 {
755 for (auto a : net.arcs())
756 {
757 if (a->flow < 0 || a->flow > a->cap)
758 return false;
759 }
760 return true;
761 }
762};
763
764TEST_F(MaxFlowMinCostIntegrationTest, SinglePathNetwork)
765{
766 auto net = build_single_path_network();
767
768 [[maybe_unused]] auto [cycles, factor] = max_flow_min_cost_by_cycle_canceling(net);
769
770 double max_flow = get_max_flow(net);
771 double total_cost = net.flow_cost();
772
773 EXPECT_DOUBLE_EQ(max_flow, 5.0);
774 EXPECT_DOUBLE_EQ(total_cost, 15.0); // 5 * 3
775 EXPECT_TRUE(verify_flow_conservation(net));
776 EXPECT_TRUE(verify_capacity_constraints(net));
777}
778
779TEST_F(MaxFlowMinCostIntegrationTest, ParallelPathsNetwork)
780{
781 auto net = build_parallel_paths_network();
782
783 [[maybe_unused]] auto [cycles, factor] = max_flow_min_cost_by_cycle_canceling(net);
784
785 double max_flow = get_max_flow(net);
786 double total_cost = net.flow_cost();
787
788 EXPECT_DOUBLE_EQ(max_flow, 7.0);
789 // Min cost: use cheap path (cost=1) fully, then expensive (cost=2)
790 // Optimal: 4 units @ cost 1 + 3 units @ cost 2 = 4 + 6 = 10
791 EXPECT_DOUBLE_EQ(total_cost, 10.0);
792 EXPECT_TRUE(verify_flow_conservation(net));
793 EXPECT_TRUE(verify_capacity_constraints(net));
794}
795
796TEST_F(MaxFlowMinCostIntegrationTest, DiamondNetwork)
797{
798 auto net = build_diamond_network();
799
800 [[maybe_unused]] auto [cycles, factor] = max_flow_min_cost_by_cycle_canceling(net);
801
802 double max_flow = get_max_flow(net);
803 double total_cost = net.flow_cost();
804
805 // Max flow through diamond is limited by min-cut
806 // Two paths: s->a->t and s->b->t, each with capacity 3
807 // But can only push 6 total (3 each way)
808 EXPECT_EQ(max_flow, 6.0);
809
810 // Both paths cost the same: 1+2 = 2+1 = 3 per unit
811 // Total cost = 6 * 3 = 18
812 EXPECT_DOUBLE_EQ(total_cost, 18.0);
813 EXPECT_TRUE(verify_flow_conservation(net));
814 EXPECT_TRUE(verify_capacity_constraints(net));
815}
816
817TEST_F(MaxFlowMinCostIntegrationTest, TextbookNetwork)
818{
819 auto net = build_textbook_network();
820
821 [[maybe_unused]] auto [cycles, factor] = max_flow_min_cost_by_cycle_canceling(net);
822
823 double max_flow = get_max_flow(net);
824 double total_cost = net.flow_cost();
825
826 // Verify flow conservation and capacity
827 EXPECT_TRUE(verify_flow_conservation(net));
828 EXPECT_TRUE(verify_capacity_constraints(net));
829
830 // Max flow analysis:
831 // Source capacity: s->a (3) + s->b (2) = 5
832 // Sink capacity: a->t (3) + b->t (2) = 5
833 // The only flow of 5 fills those four arcs and leaves b->a empty
834 EXPECT_DOUBLE_EQ(max_flow, 5.0);
835
836 // 3*1 + 2*2 + 3*3 + 2*1
837 EXPECT_DOUBLE_EQ(total_cost, 18.0);
838
839 // Print actual results for debugging
840 std::cout << "Textbook network: max_flow=" << max_flow
841 << ", total_cost=" << total_cost
842 << ", cycles_cancelled=" << cycles << std::endl;
843}
844
845TEST_F(MaxFlowMinCostIntegrationTest, LargerNetwork)
846{
847 /*
848 * Build a larger network with 6 nodes
849 *
850 * a ----> c
851 * /|\ |\
852 * / | \ | \
853 * / | \ | \
854 * s | \ | t
855 * \ | \ | /
856 * \ | \ | /
857 * \v vv
858 * b ----> d
859 */
860 Net net;
861 auto s = net.insert_node();
862 auto a = net.insert_node();
863 auto b = net.insert_node();
864 auto c = net.insert_node();
865 auto d = net.insert_node();
866 auto t = net.insert_node();
867
868 // From source
869 net.insert_arc(s, a, 4.0, 1.0);
870 net.insert_arc(s, b, 4.0, 2.0);
871
872 // Middle layer
873 net.insert_arc(a, c, 3.0, 2.0);
874 net.insert_arc(a, d, 2.0, 3.0);
875 net.insert_arc(b, c, 2.0, 1.0);
876 net.insert_arc(b, d, 3.0, 2.0);
877
878 // To sink
879 net.insert_arc(c, t, 4.0, 1.0);
880 net.insert_arc(d, t, 4.0, 1.0);
881
882 [[maybe_unused]] auto [cycles, factor] = max_flow_min_cost_by_cycle_canceling(net);
883
884 double max_flow = get_max_flow(net);
885 double total_cost = net.flow_cost();
886
887 EXPECT_TRUE(verify_flow_conservation(net));
888 EXPECT_TRUE(verify_capacity_constraints(net));
889 // The arcs of s carry 8, as those of t, and every flow of 8 costs the
890 // same: 12 through those of s, 16 through the middle and 8 through
891 // those of t
892 EXPECT_DOUBLE_EQ(max_flow, 8.0);
893 EXPECT_DOUBLE_EQ(total_cost, 36.0);
894
895 std::cout << "Larger network: max_flow=" << max_flow
896 << ", total_cost=" << total_cost
897 << ", cycles_cancelled=" << cycles << std::endl;
898}
899
900TEST_F(MaxFlowMinCostIntegrationTest, FunctorInterface)
901{
902 auto net = build_parallel_paths_network();
903
905 [[maybe_unused]] auto [cycles, factor] = algo(net);
906
907 double max_flow = get_max_flow(net);
908 double total_cost = net.flow_cost();
909
910 EXPECT_DOUBLE_EQ(max_flow, 7.0);
911 EXPECT_DOUBLE_EQ(total_cost, 10.0);
912}
913
914// =============================================================================
915// NETWORK SIMPLEX TESTS
916// =============================================================================
917
918class NetworkSimplexTest : public ::testing::Test
919{
920protected:
921 // Very simple network: single path
922 // s ---(cap=5, cost=3)---> t
923 Net build_single_path_network()
924 {
925 Net net;
926 auto s = net.insert_node();
927 auto t = net.insert_node();
928 net.insert_arc(s, t, 5.0, 3.0);
929 return net;
930 }
931
932 // Two parallel arcs network (multigraph):
933 // s ===(cap=4, cost=1)===> t (cheap arc)
934 // s ===(cap=3, cost=2)===> t (expensive arc)
935 Net build_parallel_paths_network()
936 {
937 Net net;
938 auto s = net.insert_node();
939 auto t = net.insert_node();
940 net.insert_arc(s, t, 4.0, 1.0); // cheap arc
941 net.insert_arc(s, t, 3.0, 2.0); // expensive arc
942 return net;
943 }
944
945 // Diamond network:
946 // (cap=3, cost=1)
947 // +--------> a --------+
948 // | | (cap=3, cost=2)
949 // s ---+ +---> t
950 // | |
951 // +--------> b --------+
952 // (cap=3, cost=2) (cap=3, cost=1)
953 Net build_diamond_network()
954 {
955 Net net;
956 auto s = net.insert_node();
957 auto a = net.insert_node();
958 auto b = net.insert_node();
959 auto t = net.insert_node();
960
961 net.insert_arc(s, a, 3.0, 1.0);
962 net.insert_arc(s, b, 3.0, 2.0);
963 net.insert_arc(a, t, 3.0, 2.0);
964 net.insert_arc(b, t, 3.0, 1.0);
965
966 return net;
967 }
968
969 // Textbook network with transfer arc
970 Net build_textbook_network()
971 {
972 Net net;
973 auto s = net.insert_node();
974 auto a = net.insert_node();
975 auto b = net.insert_node();
976 auto t = net.insert_node();
977
978 net.insert_arc(s, a, 3.0, 1.0);
979 net.insert_arc(s, b, 2.0, 2.0);
980 net.insert_arc(b, a, 2.0, 0.0);
981 net.insert_arc(a, t, 3.0, 3.0);
982 net.insert_arc(b, t, 2.0, 1.0);
983
984 return net;
985 }
986
987 // Larger network with 6 nodes
988 Net build_larger_network()
989 {
990 Net net;
991 auto s = net.insert_node();
992 auto a = net.insert_node();
993 auto b = net.insert_node();
994 auto c = net.insert_node();
995 auto d = net.insert_node();
996 auto t = net.insert_node();
997
998 net.insert_arc(s, a, 4.0, 1.0);
999 net.insert_arc(s, b, 4.0, 2.0);
1000 net.insert_arc(a, c, 3.0, 2.0);
1001 net.insert_arc(a, d, 2.0, 3.0);
1002 net.insert_arc(b, c, 2.0, 1.0);
1003 net.insert_arc(b, d, 3.0, 2.0);
1004 net.insert_arc(c, t, 4.0, 1.0);
1005 net.insert_arc(d, t, 4.0, 1.0);
1006
1007 return net;
1008 }
1009
1010 double get_max_flow(const Net& net)
1011 {
1012 double flow = 0;
1013 auto source = net.get_source();
1014 for (Out_Iterator<Net> it(source); it.has_curr(); it.next_ne())
1015 flow += it.get_curr()->flow;
1016 return flow;
1017 }
1018
1019 bool verify_flow_conservation(const Net& net)
1020 {
1021 auto source = net.get_source();
1022 auto sink = net.get_sink();
1023
1024 for (auto p : net.nodes())
1025 {
1026 if (p == source || p == sink)
1027 continue;
1028
1029 double in_flow = 0, out_flow = 0;
1030
1031 for (In_Iterator<Net> it(p); it.has_curr(); it.next_ne())
1032 in_flow += it.get_curr()->flow;
1033
1034 for (Out_Iterator<Net> it(p); it.has_curr(); it.next_ne())
1035 out_flow += it.get_curr()->flow;
1036
1037 if (std::abs(in_flow - out_flow) > 1e-9)
1038 return false;
1039 }
1040 return true;
1041 }
1042
1043 bool verify_capacity_constraints(const Net& net)
1044 {
1045 for (auto a : net.arcs())
1046 {
1047 if (a->flow < 0 || a->flow > a->cap + 1e-9)
1048 return false;
1049 }
1050 return true;
1051 }
1052};
1053
1054TEST_F(NetworkSimplexTest, SinglePathNetwork)
1055{
1056 auto net = build_single_path_network();
1057
1059
1060 double max_flow = get_max_flow(net);
1061 double total_cost = net.flow_cost();
1062
1063 EXPECT_DOUBLE_EQ(max_flow, 5.0);
1064 EXPECT_DOUBLE_EQ(total_cost, 15.0); // 5 * 3
1065 EXPECT_TRUE(verify_flow_conservation(net));
1066 EXPECT_TRUE(verify_capacity_constraints(net));
1067}
1068
1069TEST_F(NetworkSimplexTest, ParallelPathsNetwork)
1070{
1071 auto net = build_parallel_paths_network();
1072
1074
1075 double max_flow = get_max_flow(net);
1076 double total_cost = net.flow_cost();
1077
1078 EXPECT_DOUBLE_EQ(max_flow, 7.0);
1079 EXPECT_DOUBLE_EQ(total_cost, 10.0); // 4*1 + 3*2
1080 EXPECT_TRUE(verify_flow_conservation(net));
1081 EXPECT_TRUE(verify_capacity_constraints(net));
1082}
1083
1084TEST_F(NetworkSimplexTest, DiamondNetwork)
1085{
1086 auto net = build_diamond_network();
1087
1089
1090 double max_flow = get_max_flow(net);
1091 double total_cost = net.flow_cost();
1092
1093 EXPECT_EQ(max_flow, 6.0);
1094 EXPECT_DOUBLE_EQ(total_cost, 18.0); // 6 units * 3 cost per unit
1095 EXPECT_TRUE(verify_flow_conservation(net));
1096 EXPECT_TRUE(verify_capacity_constraints(net));
1097}
1098
1099TEST_F(NetworkSimplexTest, TextbookNetwork)
1100{
1101 auto net = build_textbook_network();
1102
1103 size_t pivots = max_flow_min_cost_by_network_simplex(net);
1104
1105 double max_flow = get_max_flow(net);
1106 double total_cost = net.flow_cost();
1107
1108 EXPECT_TRUE(verify_flow_conservation(net));
1109 EXPECT_TRUE(verify_capacity_constraints(net));
1110 EXPECT_DOUBLE_EQ(max_flow, 5.0);
1111 EXPECT_DOUBLE_EQ(total_cost, 18.0); // the exact optimum
1112
1113 std::cout << "Network Simplex textbook: max_flow=" << max_flow
1114 << ", total_cost=" << total_cost
1115 << ", pivots=" << pivots << std::endl;
1116}
1117
1118TEST_F(NetworkSimplexTest, LargerNetwork)
1119{
1120 auto net = build_larger_network();
1121
1122 size_t pivots = max_flow_min_cost_by_network_simplex(net);
1123
1124 double max_flow = get_max_flow(net);
1125 double total_cost = net.flow_cost();
1126
1127 EXPECT_TRUE(verify_flow_conservation(net));
1128 EXPECT_TRUE(verify_capacity_constraints(net));
1129 EXPECT_DOUBLE_EQ(max_flow, 8.0);
1130 EXPECT_DOUBLE_EQ(total_cost, 36.0); // the exact optimum
1131
1132 std::cout << "Network Simplex larger: max_flow=" << max_flow
1133 << ", total_cost=" << total_cost
1134 << ", pivots=" << pivots << std::endl;
1135}
1136
1137TEST_F(NetworkSimplexTest, FunctorInterface)
1138{
1139 auto net = build_parallel_paths_network();
1140
1142 algo(net);
1143
1144 double max_flow = get_max_flow(net);
1145 double total_cost = net.flow_cost();
1146
1147 EXPECT_DOUBLE_EQ(max_flow, 7.0);
1148 EXPECT_DOUBLE_EQ(total_cost, 10.0);
1149}
1150
1151TEST_F(NetworkSimplexTest, CompareWithCycleCanceling)
1152{
1153 // Build same network twice and compare results
1154 auto net_simplex = build_larger_network();
1155 auto net_cycle = build_larger_network();
1156
1159
1160 double flow_simplex = get_max_flow(net_simplex);
1161 double flow_cycle = get_max_flow(net_cycle);
1162 double cost_simplex = net_simplex.flow_cost();
1163 double cost_cycle = net_cycle.flow_cost();
1164
1165 // Both should find the same max flow
1166 EXPECT_DOUBLE_EQ(flow_simplex, flow_cycle);
1167
1168 // Costs should be equal (or very close) for optimal solution
1169 EXPECT_NEAR(cost_simplex, cost_cycle, 1e-6);
1170}
1171
1172TEST_F(NetworkSimplexTest, EmptyNetwork)
1173{
1174 // A network with nodes but no arcs is not a valid single-source
1175 // single-sink network, so it should throw an exception
1176 Net net;
1177 auto s = net.insert_node();
1178 auto t = net.insert_node();
1179 (void)s; (void)t; // silence unused warnings
1180
1181 EXPECT_THROW(max_flow_min_cost_by_network_simplex(net), std::domain_error);
1182}
1183
1184TEST_F(NetworkSimplexTest, ZeroCostNetwork)
1185{
1186 Net net;
1187 auto s = net.insert_node();
1188 auto t = net.insert_node();
1189 net.insert_arc(s, t, 10.0, 0.0); // zero cost
1190
1192
1193 double max_flow = get_max_flow(net);
1194 double total_cost = net.flow_cost();
1195
1196 EXPECT_DOUBLE_EQ(max_flow, 10.0);
1197 EXPECT_DOUBLE_EQ(total_cost, 0.0);
1198}
1199
1200TEST_F(NetworkSimplexTest, HighCostArcAvoidance)
1201{
1202 // Network where one path is much cheaper
1203 // (cap=5, cost=1)
1204 // s ---------> a ---------> t
1205 // (cap=5, cost=1)
1206 // (cap=5, cost=100)
1207 // s ---------> b ---------> t
1208 // (cap=5, cost=100)
1209 Net net;
1210 auto s = net.insert_node();
1211 auto a = net.insert_node();
1212 auto b = net.insert_node();
1213 auto t = net.insert_node();
1214
1215 net.insert_arc(s, a, 5.0, 1.0);
1216 net.insert_arc(a, t, 5.0, 1.0);
1217 net.insert_arc(s, b, 5.0, 100.0);
1218 net.insert_arc(b, t, 5.0, 100.0);
1219
1221
1222 double max_flow = get_max_flow(net);
1223 double total_cost = net.flow_cost();
1224
1225 // Should route through cheaper path (a) first
1226 EXPECT_DOUBLE_EQ(max_flow, 10.0);
1227 // Min cost: 5 units through a (cost 5*2=10) + 5 units through b (cost 5*200=1000)
1228 EXPECT_DOUBLE_EQ(total_cost, 1010.0);
1229 EXPECT_TRUE(verify_flow_conservation(net));
1230}
1231
1232// =============================================================================
1233// SIMPLEX DATA STRUCTURE TESTS
1234// =============================================================================
1235
1236class SimplexDataStructuresTest : public ::testing::Test
1237{
1238};
1239
1240TEST_F(SimplexDataStructuresTest, SimplexNodeInfoDefaults)
1241{
1243 EXPECT_EQ(info.potential, 0.0);
1244 EXPECT_EQ(info.parent, nullptr);
1245 EXPECT_EQ(info.parent_arc, nullptr);
1246 EXPECT_EQ(info.depth, 0);
1247 EXPECT_EQ(info.mark, 0);
1248 EXPECT_TRUE(info.arc_from_parent); // Default is true
1249}
1250
1251TEST_F(SimplexDataStructuresTest, SimplexArcStateEnum)
1252{
1253 EXPECT_NE(static_cast<int>(Simplex_Arc_State::Lower),
1254 static_cast<int>(Simplex_Arc_State::Upper));
1255 EXPECT_NE(static_cast<int>(Simplex_Arc_State::Lower),
1256 static_cast<int>(Simplex_Arc_State::Tree));
1257 EXPECT_NE(static_cast<int>(Simplex_Arc_State::Upper),
1258 static_cast<int>(Simplex_Arc_State::Tree));
1259}
1260
1261
1262} // close anonymous namespace
1263
1264// =============================================================================
1265// NETWORK SIMPLEX VS PURE SIMPLEX VALIDATION
1266// =============================================================================
1267//
1268// This test validates that Network Simplex produces the same optimal solution
1269// as the pure Simplex method applied to the equivalent LP formulation.
1270//
1271// The min-cost max-flow problem can be formulated as a linear program:
1272//
1273// Variables: x_e for each arc e (flow on arc e)
1274//
1275// Maximize: M * (sum of outflow from source) - sum(cost_e * x_e)
1276// where M is a large constant to prioritize max flow over min cost
1277//
1278// Subject to:
1279// - Capacity: 0 <= x_e <= cap_e for each arc e
1280// - Flow conservation: sum(x entering v) = sum(x leaving v) for each v ≠ s,t
1281//
1282// For Simplex standard form (maximize with <=):
1283// - Upper bound constraints: x_e <= cap_e
1284// - Flow conservation as equality requires two inequalities or slack handling
1285//
1286// =============================================================================
1287
1288#include <Simplex.H>
1289#include <chrono>
1290#include <map>
1291
1292namespace // reopen anonymous namespace
1293{
1294
1296using Node = Net::Node;
1297
1298class NetworkSimplexVsPureSimplexTest : public ::testing::Test
1299{
1300protected:
1301 // Build a simple network and return arc indices for LP formulation
1302 //
1303 // (cap=5, cost=2) (cap=4, cost=3)
1304 // s ----------------> a ----------------> t
1305 // | ^
1306 // | (cap=3, cost=1) | (cap=2, cost=1)
1307 // +-----------------> b -----------------+
1308 // |
1309 // +-------------------> t
1310 // (cap=3, cost=2)
1311 //
1312 // Nodes: s=0, a=1, b=2, t=3
1313 // Arcs (with indices for LP variables):
1314 // 0: s->a (cap=5, cost=2)
1315 // 1: s->b (cap=3, cost=1)
1316 // 2: a->t (cap=4, cost=3)
1317 // 3: b->a (cap=2, cost=1)
1318 // 4: b->t (cap=3, cost=2)
1319 //
1320 struct ArcData
1321 {
1322 int src, tgt;
1323 double cap, cost;
1324 };
1325
1326 std::vector<ArcData> arcs = {
1327 {0, 1, 5.0, 2.0}, // s->a
1328 {0, 2, 3.0, 1.0}, // s->b
1329 {1, 3, 4.0, 3.0}, // a->t
1330 {2, 1, 2.0, 1.0}, // b->a
1331 {2, 3, 3.0, 2.0} // b->t
1332 };
1333
1334 static constexpr int SOURCE = 0;
1335 static constexpr int SINK = 3;
1336 static constexpr int NUM_NODES = 4;
1337
1338 Net build_network()
1339 {
1340 Net net;
1341 std::vector<Node*> nodes(NUM_NODES);
1342
1343 for (int i = 0; i < NUM_NODES; ++i)
1344 nodes[i] = net.insert_node();
1345
1346 for (const auto& a : arcs)
1347 net.insert_arc(nodes[a.src], nodes[a.tgt], a.cap, a.cost);
1348
1349 return net;
1350 }
1351
1352 // Solve using pure Simplex by formulating as LP
1353 // Returns {max_flow, min_cost, time_ms}
1354 std::tuple<double, double, double> solve_with_pure_simplex()
1355 {
1356 // Formulation:
1357 // Variables: x_0, x_1, x_2, x_3, x_4 (flow on each arc)
1358 // x_5 = total flow from source (auxiliary for objective)
1359 //
1360 // Objective: Maximize x_5 * M - (c_0*x_0 + c_1*x_1 + ... + c_4*x_4)
1361 // where M is large (1000) to prioritize max flow
1362 // Rewritten: Maximize M*x_5 - sum(c_i * x_i)
1363 //
1364 // Constraints:
1365 // Capacity: x_i <= cap_i for each arc i (5 constraints)
1366 // Flow conservation at intermediate nodes:
1367 // At a (node 1): x_0 + x_3 = x_2 → x_0 + x_3 - x_2 <= 0 and x_2 - x_0 - x_3 <= 0
1368 // At b (node 2): x_1 = x_3 + x_4 → x_1 - x_3 - x_4 <= 0 and x_3 + x_4 - x_1 <= 0
1369 // Source flow definition: x_5 = x_0 + x_1 → x_0 + x_1 - x_5 <= 0 and x_5 - x_0 - x_1 <= 0
1370 // Non-negativity is implicit in standard form
1371
1372 const size_t NUM_ARCS = arcs.size();
1373 const size_t NUM_VARS = NUM_ARCS + 1; // arc flows + total flow variable
1374 const double M = 1000.0; // Large constant for max flow priority
1375
1376 auto start = std::chrono::high_resolution_clock::now();
1377
1378 Simplex<double> simplex(NUM_VARS);
1379
1380 // Objective function: Maximize M*x_5 - sum(cost_i * x_i)
1381 // Coefficients: [-c_0, -c_1, -c_2, -c_3, -c_4, M]
1382 for (size_t i = 0; i < NUM_ARCS; ++i)
1383 simplex.put_objetive_function_coef(i, -arcs[i].cost);
1384 simplex.put_objetive_function_coef(NUM_ARCS, M); // x_5 coefficient
1385
1386 // Helper lambda to create zero-initialized coefficient vector
1387 auto make_coefs = [NUM_VARS]() {
1388 return std::vector<double>(NUM_VARS + 1, 0.0);
1389 };
1390
1391 // Capacity constraints: x_i <= cap_i
1392 for (size_t i = 0; i < NUM_ARCS; ++i)
1393 {
1394 auto coefs = make_coefs();
1395 coefs[i] = 1.0;
1396 coefs[NUM_VARS] = arcs[i].cap; // RHS
1397 simplex.put_restriction(coefs.data());
1398 }
1399
1400 // Flow conservation at node a (node 1):
1401 // Incoming: x_0 (s->a), x_3 (b->a)
1402 // Outgoing: x_2 (a->t)
1403 // x_0 + x_3 - x_2 <= 0
1404 {
1405 auto coefs = make_coefs();
1406 coefs[0] = 1.0; // x_0: s->a
1407 coefs[3] = 1.0; // x_3: b->a
1408 coefs[2] = -1.0; // x_2: a->t
1409 coefs[NUM_VARS] = 0.0; // RHS
1410 simplex.put_restriction(coefs.data());
1411 }
1412 // x_2 - x_0 - x_3 <= 0
1413 {
1414 auto coefs = make_coefs();
1415 coefs[2] = 1.0; // x_2: a->t
1416 coefs[0] = -1.0; // x_0: s->a
1417 coefs[3] = -1.0; // x_3: b->a
1418 coefs[NUM_VARS] = 0.0; // RHS
1419 simplex.put_restriction(coefs.data());
1420 }
1421
1422 // Flow conservation at node b (node 2):
1423 // Incoming: x_1 (s->b)
1424 // Outgoing: x_3 (b->a), x_4 (b->t)
1425 // x_1 - x_3 - x_4 <= 0
1426 {
1427 auto coefs = make_coefs();
1428 coefs[1] = 1.0; // x_1: s->b
1429 coefs[3] = -1.0; // x_3: b->a
1430 coefs[4] = -1.0; // x_4: b->t
1431 coefs[NUM_VARS] = 0.0; // RHS
1432 simplex.put_restriction(coefs.data());
1433 }
1434 // x_3 + x_4 - x_1 <= 0
1435 {
1436 auto coefs = make_coefs();
1437 coefs[3] = 1.0; // x_3: b->a
1438 coefs[4] = 1.0; // x_4: b->t
1439 coefs[1] = -1.0; // x_1: s->b
1440 coefs[NUM_VARS] = 0.0; // RHS
1441 simplex.put_restriction(coefs.data());
1442 }
1443
1444 // Source flow definition: x_5 = x_0 + x_1
1445 // x_0 + x_1 - x_5 <= 0
1446 {
1447 auto coefs = make_coefs();
1448 coefs[0] = 1.0;
1449 coefs[1] = 1.0;
1450 coefs[NUM_ARCS] = -1.0; // x_5
1451 coefs[NUM_VARS] = 0.0;
1452 simplex.put_restriction(coefs.data());
1453 }
1454 // x_5 - x_0 - x_1 <= 0
1455 {
1456 auto coefs = make_coefs();
1457 coefs[NUM_ARCS] = 1.0; // x_5
1458 coefs[0] = -1.0;
1459 coefs[1] = -1.0;
1460 coefs[NUM_VARS] = 0.0;
1461 simplex.put_restriction(coefs.data());
1462 }
1463
1464 simplex.prepare_linear_program();
1465 auto state = simplex.solve();
1466
1467 auto end = std::chrono::high_resolution_clock::now();
1468 double time_ms = std::chrono::duration<double, std::milli>(end - start).count();
1469
1470 if (state != Simplex<double>::Solved)
1471 return {-1, -1, time_ms};
1472
1473 simplex.load_solution();
1474
1475 double max_flow = simplex.get_solution(NUM_ARCS); // x_5
1476 double total_cost = 0;
1477 for (size_t i = 0; i < NUM_ARCS; ++i)
1478 total_cost += simplex.get_solution(i) * arcs[i].cost;
1479
1480 return {max_flow, total_cost, time_ms};
1481 }
1482
1483 // Solve using Network Simplex
1484 // Returns {max_flow, min_cost, time_ms}
1485 std::tuple<double, double, double> solve_with_network_simplex()
1486 {
1487 auto net = build_network();
1488
1489 auto start = std::chrono::high_resolution_clock::now();
1491 auto end = std::chrono::high_resolution_clock::now();
1492
1493 double time_ms = std::chrono::duration<double, std::milli>(end - start).count();
1494
1495 // Compute max flow
1496 double max_flow = 0;
1497 auto source = net.get_source();
1498 for (Out_Iterator<Net> it(source); it.has_curr(); it.next_ne())
1499 max_flow += it.get_curr()->flow;
1500
1501 return {max_flow, net.flow_cost(), time_ms};
1502 }
1503};
1504
1505TEST_F(NetworkSimplexVsPureSimplexTest, BothMethodsProduceSameOptimalSolution)
1506{
1507 auto [flow_simplex, cost_simplex, time_simplex] = solve_with_pure_simplex();
1508 auto [flow_network, cost_network, time_network] = solve_with_network_simplex();
1509
1510 std::cout << "\n=== Network Simplex vs Pure Simplex Validation ===\n";
1511 std::cout << "Pure Simplex: flow=" << flow_simplex
1512 << ", cost=" << cost_simplex
1513 << ", time=" << time_simplex << " ms\n";
1514 std::cout << "Network Simplex: flow=" << flow_network
1515 << ", cost=" << cost_network
1516 << ", time=" << time_network << " ms\n";
1517
1518 // Both should find the same optimal solution
1519 EXPECT_NEAR(flow_simplex, flow_network, 1e-6)
1520 << "Max flow differs between methods";
1521 EXPECT_NEAR(cost_simplex, cost_network, 1e-6)
1522 << "Min cost differs between methods";
1523
1524 std::cout << "✓ Both methods produce identical optimal solution\n";
1525}
1526
1527TEST_F(NetworkSimplexVsPureSimplexTest, NetworkSimplexIsTypicallyFaster)
1528{
1529 // Run multiple times to get stable measurements
1530 const int RUNS = 10;
1531 double total_simplex_time = 0;
1532 double total_network_time = 0;
1533
1534 for (int i = 0; i < RUNS; ++i)
1535 {
1536 auto [f1, c1, t1] = solve_with_pure_simplex();
1537 auto [f2, c2, t2] = solve_with_network_simplex();
1538 (void)f1; (void)c1; (void)f2; (void)c2;
1539 total_simplex_time += t1;
1540 total_network_time += t2;
1541 }
1542
1543 double avg_simplex = total_simplex_time / RUNS;
1544 double avg_network = total_network_time / RUNS;
1545
1546 std::cout << "\n=== Performance Comparison (" << RUNS << " runs) ===\n";
1547 std::cout << "Avg Pure Simplex time: " << avg_simplex << " ms\n";
1548 std::cout << "Avg Network Simplex time: " << avg_network << " ms\n";
1549
1550 // Network Simplex exploits graph structure and should be competitive or faster
1551 // Note: For very small problems, overhead might make times similar
1552 std::cout << "Speedup factor: " << (avg_simplex / avg_network) << "x\n";
1553}
1554
1555
1556// =============================================================================
1557// LARGER NETWORK TEST FOR PERFORMANCE COMPARISON
1558// =============================================================================
1559
1560class LargeNetworkValidationTest : public ::testing::Test
1561{
1562protected:
1563 // Build a grid-like network with n×n nodes
1564 Net build_grid_network(int n)
1565 {
1566 Net net;
1567 std::vector<std::vector<Node*>> nodes(n, std::vector<Node*>(n));
1568
1569 // Create nodes
1570 for (int i = 0; i < n; ++i)
1571 for (int j = 0; j < n; ++j)
1572 nodes[i][j] = net.insert_node();
1573
1574 // Create arcs: right and down directions
1575 for (int i = 0; i < n; ++i)
1576 {
1577 for (int j = 0; j < n; ++j)
1578 {
1579 // Right arc
1580 if (j + 1 < n)
1581 {
1582 double cap = 10.0 + (i + j) % 5;
1583 double cost = 1.0 + (i * j) % 3;
1584 net.insert_arc(nodes[i][j], nodes[i][j+1], cap, cost);
1585 }
1586 // Down arc
1587 if (i + 1 < n)
1588 {
1589 double cap = 10.0 + (i + j + 1) % 5;
1590 double cost = 1.0 + ((i + 1) * j) % 3;
1591 net.insert_arc(nodes[i][j], nodes[i+1][j], cap, cost);
1592 }
1593 }
1594 }
1595
1596 return net;
1597 }
1598};
1599
1600TEST_F(LargeNetworkValidationTest, CompareAlgorithmsOnLargerNetwork)
1601{
1602 const int GRID_SIZE = 5; // 5x5 grid = 25 nodes, ~40 arcs
1603
1604 auto net1 = build_grid_network(GRID_SIZE);
1605 auto net2 = build_grid_network(GRID_SIZE);
1606
1607 // First check what Ford-Fulkerson produces (before optimization)
1608 auto net_ff = build_grid_network(GRID_SIZE);
1610 double cost_after_ff = net_ff.flow_cost();
1611
1612 // Solve with Network Simplex
1613 auto start_ns = std::chrono::high_resolution_clock::now();
1614 size_t pivots_ns = Aleph::max_flow_min_cost_by_network_simplex(net1);
1615 auto end_ns = std::chrono::high_resolution_clock::now();
1616 double time_ns = std::chrono::duration<double, std::milli>(end_ns - start_ns).count();
1617
1618 // Solve with Cycle Canceling
1619 auto start_cc = std::chrono::high_resolution_clock::now();
1620 auto [cycles_cc, factor_cc] = Aleph::max_flow_min_cost_by_cycle_canceling(net2);
1621 auto end_cc = std::chrono::high_resolution_clock::now();
1622 double time_cc = std::chrono::duration<double, std::milli>(end_cc - start_cc).count();
1623
1624 // Compute flows
1625 auto get_flow = [](const Net& net) {
1626 double flow = 0;
1627 auto source = net.get_source();
1628 for (Out_Iterator<Net> it(source); it.has_curr(); it.next_ne())
1629 flow += it.get_curr()->flow;
1630 return flow;
1631 };
1632
1633 double flow_ns = get_flow(net1);
1634 double flow_cc = get_flow(net2);
1635 double cost_ns = net1.flow_cost();
1636 double cost_cc = net2.flow_cost();
1637
1638 std::cout << "\n=== Grid Network " << GRID_SIZE << "x" << GRID_SIZE
1639 << " (" << net1.vsize() << " nodes, " << net1.esize() << " arcs) ===\n";
1640 std::cout << "Ford-Fulkerson only: cost=" << cost_after_ff << "\n";
1641 std::cout << "Network Simplex: flow=" << flow_ns << ", cost=" << cost_ns
1642 << ", time=" << time_ns << " ms, pivots=" << pivots_ns << "\n";
1643 std::cout << "Cycle Canceling: flow=" << flow_cc << ", cost=" << cost_cc
1644 << ", time=" << time_cc << " ms, cycles=" << cycles_cc << "\n";
1645
1646 // Both should produce the same max flow
1647 EXPECT_NEAR(flow_ns, flow_cc, 1e-6) << "Max flow should be identical";
1648
1649 // Cost comparison - both should find min cost
1650 if (std::abs(cost_ns - cost_cc) > 1e-6)
1651 {
1652 std::cout << "\n⚠ BUG DETECTED: Cost difference = " << std::abs(cost_ns - cost_cc) << "\n";
1653
1654 if (cost_ns > cost_cc)
1655 {
1656 std::cout << " Network Simplex found SUBOPTIMAL solution (pivots=" << pivots_ns << ")\n";
1657 std::cout << " Cost after Ford-Fulkerson: " << cost_after_ff << "\n";
1658 std::cout << " Cost after Network Simplex: " << cost_ns << "\n";
1659 std::cout << " Cost reduction by NS: " << (cost_after_ff - cost_ns) << "\n";
1660 std::cout << " Cost after Cycle Canceling: " << cost_cc << "\n";
1661 std::cout << " Cost reduction by CC: " << (cost_after_ff - cost_cc) << "\n";
1662 std::cout << " => Network Simplex is NOT optimizing correctly!\n";
1663 }
1664 else
1665 {
1666 std::cout << " Cycle Canceling found higher cost (unexpected).\n";
1667 }
1668 }
1669 else
1670 {
1671 std::cout << "✓ Both algorithms produce identical optimal solution\n";
1672 }
1673
1674 // At minimum, verify flow conservation and capacity constraints are satisfied
1675 EXPECT_TRUE(flow_ns > 0) << "Network Simplex should find positive flow";
1676 EXPECT_TRUE(flow_cc > 0) << "Cycle Canceling should find positive flow";
1677}
1678
1679// Performance comparison at different scales
1680// Test Phase I: verify all partial arcs are in tree
1681TEST_F(LargeNetworkValidationTest, PhaseIDiagnostic)
1682{
1683 const int GRID_SIZE = 5;
1684 auto net = build_grid_network(GRID_SIZE);
1685
1687
1688 std::cout << "\n=== Phase I Diagnostic ===\n";
1689
1690 Aleph::Network_Simplex<Net> simplex(net);
1691
1692 // Count partial arcs before Phase I
1693 size_t partial_before = 0;
1694 for (auto a : net.arcs())
1695 if (a->flow > 1e-9 and a->flow < a->cap - 1e-9)
1696 partial_before++;
1697
1698 std::cout << "Partial arcs after FF: " << partial_before << "\n";
1699
1700 // Run the algorithm
1701 size_t pivots = simplex.run();
1702
1703 // Check if valid BFS
1704 bool valid_bfs = simplex.is_valid_basic_solution();
1705 size_t remaining = simplex.count_non_tree_partial_arcs();
1706
1707 std::cout << "Pivots performed: " << pivots << "\n";
1708 std::cout << "Valid BFS: " << (valid_bfs ? "YES" : "NO") << "\n";
1709 std::cout << "Partial arcs not in tree: " << remaining << "\n";
1710 std::cout << "Final cost: " << net.flow_cost() << "\n";
1711
1712 // Print detailed diagnostics
1713 simplex.print_diagnostics();
1714
1715 // Compare with cycle canceling
1716 auto net2 = build_grid_network(GRID_SIZE);
1718 std::cout << "Optimal cost (CC): " << net2.flow_cost() << "\n";
1719
1720 if (not valid_bfs)
1721 std::cout << "WARNING: Phase I failed to establish valid BFS!\n";
1722
1723 if (remaining > 0)
1724 std::cout << "WARNING: " << remaining << " partial arcs still outside tree!\n";
1725
1726 // Check reduced costs of non-tree arcs
1727 std::cout << "\nNon-tree arc analysis:\n";
1728 for (auto a : net.arcs())
1729 {
1730 // We need access to internal state - skip for now
1731 // Check if arc could improve cost
1732 bool at_lower = (a->flow <= 1e-9);
1733 bool at_upper = (a->flow >= a->cap - 1e-9);
1734
1735 if (not at_lower and not at_upper)
1736 continue; // Tree arc (has partial flow)
1737
1738 // For non-tree arcs, compute reduced cost manually
1739 // This requires knowing the potentials - we can't do this easily
1740 // without exposing more internals
1741 }
1742
1743 // Build residual network and check for negative cycles
1744 using Rnet = Aleph::Residual_Net<double>;
1745 Rnet rnet;
1748
1751
1752 auto [cycle, iterations] = BF(rnet).search_negative_cycle(0.4, 10);
1753
1754 if (not cycle.is_empty())
1755 {
1756 std::cout << "NEGATIVE CYCLE FOUND after Network Simplex!\n";
1757 std::cout << " Cycle has " << cycle.size() << " arcs\n";
1758 double cycle_cost = 0;
1759 cycle.for_each_arc([&](auto arc) { cycle_cost += arc->cost; });
1760 std::cout << " Cycle cost: " << cycle_cost << "\n";
1761 }
1762 else
1763 std::cout << "No negative cycles found - this is strange!\n";
1764}
1765
1766// Performance comparison at different scales
1767TEST_F(LargeNetworkValidationTest, PerformanceComparison)
1768{
1769 std::cout << "\n=== Performance Comparison ===\n";
1770 std::cout << std::setw(8) << "Grid" << std::setw(10) << "Nodes"
1771 << std::setw(10) << "Arcs" << std::setw(12) << "NS (ms)"
1772 << std::setw(12) << "CC (ms)" << std::setw(10) << "Winner\n";
1773 std::cout << std::string(62, '-') << "\n";
1774
1775 for (int size = 3; size <= 10; size += 1)
1776 {
1777 auto net1 = build_grid_network(size);
1778 auto net2 = build_grid_network(size);
1779
1780 auto start1 = std::chrono::high_resolution_clock::now();
1782 auto end1 = std::chrono::high_resolution_clock::now();
1783 double time_ns = std::chrono::duration<double, std::milli>(end1 - start1).count();
1784
1785 auto start2 = std::chrono::high_resolution_clock::now();
1787 auto end2 = std::chrono::high_resolution_clock::now();
1788 double time_cc = std::chrono::duration<double, std::milli>(end2 - start2).count();
1789
1790 // Verify same cost
1791 EXPECT_NEAR(net1.flow_cost(), net2.flow_cost(), 1e-6)
1792 << "Different costs for grid " << size << "x" << size;
1793
1794 std::cout << std::setw(5) << size << "x" << size
1795 << std::setw(10) << net1.vsize()
1796 << std::setw(10) << net1.esize()
1797 << std::setw(12) << std::fixed << std::setprecision(3) << time_ns
1798 << std::setw(12) << time_cc
1799 << std::setw(10) << (time_ns < time_cc ? "NS" : "CC") << "\n";
1800 }
1801}
1802
1803
1804
1805// =============================================================================
1806// BUG INVESTIGATION: Network Simplex not finding optimal cost
1807// =============================================================================
1808//
1809// The Network Simplex implementation may have a bug where it fails to optimize
1810// cost after Ford-Fulkerson because:
1811// 1. The BFS-based spanning tree construction doesn't consider current flow
1812// 2. Arc classification (Lower/Upper) doesn't account for arcs with 0 < flow < cap
1813//
1814// This test investigates the issue by examining the internal state.
1815// =============================================================================
1816
1817class NetworkSimplexBugInvestigation : public ::testing::Test
1818{
1819protected:
1820 // Network with a CHOICE: Ford-Fulkerson may pick the expensive path first,
1821 // and Network Simplex should redirect the flow to the cheaper path.
1822 //
1823 // (cap=10, cost=100)
1824 // +-----------------------> t
1825 // |
1826 // s ---+
1827 // |
1828 // +----> a ----> t
1829 // (cap=10, cost=1) (cap=10, cost=1)
1830 //
1831 // Both paths can carry 10 units.
1832 // Sink capacity is unlimited (two arcs arriving at t).
1833 // Ford-Fulkerson might saturate either path first.
1834 // If it saturates expensive path: cost = 10*100 = 1000
1835 // Optimal: cheap path only: cost = 10*(1+1) = 20
1836 //
1837 // BUT: Ford-Fulkerson will actually saturate BOTH paths (total flow = 20).
1838 //
1839 // Let's design a network with LIMITED SINK CAPACITY:
1840 //
1841 // (cap=10, cost=100)
1842 // s ----------------> a --------+
1843 // | (cap=5, cost=0) <- BOTTLENECK
1844 // v
1845 // s ----------------> b -------> t
1846 // (cap=10, cost=1) (cap=5, cost=0) <- BOTTLENECK
1847 //
1848 // Max flow = 10 (limited by sink arcs: 5+5 = 10)
1849 // Ford-Fulkerson may push:
1850 // - 5 units via s->a->t (cost = 5*100 = 500)
1851 // - 5 units via s->b->t (cost = 5*1 = 5)
1852 // - Total: 505
1853 //
1854 // Optimal for 10 units: All via cheap path would need cap 10, but we only have 5.
1855 // So best is still 5 via each, total 505. No improvement possible.
1856 //
1857 // BETTER DESIGN: Cross-edge to allow redistribution
1858 //
1859 // (cap=10, cost=100) (cap=10, cost=0)
1860 // s ----------------> a -----------------> t
1861 // |
1862 // | (cap=10, cost=0) <- CROSS EDGE
1863 // v
1864 // s ----------------> b -----------------> t
1865 // (cap=10, cost=1) (cap=10, cost=0)
1866 //
1867 // Max flow = 20 (both paths saturated)
1868 // If FF routes 10 via s->a->t: cost = 10*100 = 1000
1869 // If FF routes 10 via s->b->t: cost = 10*1 = 10
1870 // Total (if both): 1010
1871 //
1872 // But with cross edge a->b, we can REDIRECT:
1873 // Instead of s->a->t, use s->a->b->t (cross edge has 0 cost)
1874 // s->a: cost 100
1875 // a->b: cost 0
1876 // b->t: cost 0
1877 // Total for this path: 100 per unit
1878 //
1879 // This doesn't help! The cross edge doesn't save cost.
1880 //
1881 /*
1882 * FINAL DESIGN: Force choice between parallel paths with SAME entry
1883 *
1884 * a (cap=5, cost=10)
1885 * / \
1886 * / \
1887 * s ----+ +----> t
1888 * \ /
1889 * \ /
1890 * b (cap=5, cost=1)
1891 */
1892 // Max flow = 10 (through a and b combined)
1893 // If Ford-Fulkerson picks a first: flow_a=5, flow_b=5, cost = 5*10 + 5*1 = 55
1894 // Optimal if we could choose: all 10 via b, but cap is only 5.
1895 // So optimal is still 55. No improvement.
1896 //
1897 // OK let me try a different approach: use LARGER capacity on cheap path
1898 //
1899 // s -----> a -----> t (cap=10, cost=10) + (cap=10, cost=10) = 20 per unit
1900 // \ ^
1901 // \ /
1902 // +--> b ---+ (cap=20, cost=1) + (cap=20, cost=1) = 2 per unit
1903 //
1904 // Max flow = 10 (limited by first layer: s->a has cap 10)
1905 // Wait no, s has two outgoing arcs.
1906 //
1907 // Let me just use the grid from the failing test and inspect what's happening.
1908
1909 Net build_asymmetric_diamond()
1910 {
1911 Net net;
1912 auto s = net.insert_node();
1913 auto a = net.insert_node();
1914 auto b = net.insert_node();
1915 auto t = net.insert_node();
1916
1917 // This creates a situation where FF might not find optimal cost:
1918 //
1919 // (cap=10, cost=10) (cap=5, cost=1)
1920 // s ----------------> a ----------------> t
1921 // (cap=10, cost=1) (cap=15, cost=1)
1922 // s ----------------> b ----------------> t
1923 //
1924 // Max flow: limited by sink capacity = 5 + 15 = 20
1925 // but also by source capacity = 10 + 10 = 20
1926 // So max flow = 20.
1927 //
1928 // If FF saturates s->a->t first (5 units, limited by a->t):
1929 // cost = 5*(10+1) = 55
1930 // Then saturates s->b->t (15 units, limited by b->t):
1931 // cost = 15*(1+1) = 30
1932 // Total flow = 20, cost = 85
1933 //
1934 // But we could push all 10 from s->a through the a->t bottleneck? No, cap is 5.
1935 // Let's push 5 via a and 15 via b:
1936 // 5 * (10+1) + 15 * (1+1) = 55 + 30 = 85
1937 //
1938 // Alternative: Push 0 via a, 20 via b?
1939 // But s->b cap is only 10, and b->t cap is 15. So max via b is 10.
1940 // 10 * (1+1) = 20. Flow = 10.
1941 //
1942 // To get flow = 20, we MUST use path a (at least 5 units because b path caps at 15).
1943 // Actually: s->b = 10, b->t = 15. Via b we can push 10.
1944 // s->a = 10, a->t = 5. Via a we can push 5.
1945 // Total max flow = 15.
1946 //
1947 // Let me recalculate:
1948 // - s->a (10), a->t (5): path capacity = 5
1949 // - s->b (10), b->t (15): path capacity = 10
1950 // Max flow = 5 + 10 = 15
1951 //
1952 // For 15 flow units:
1953 // 5 via a: cost = 5 * (10+1) = 55
1954 // 10 via b: cost = 10 * (1+1) = 20
1955 // Total: 75
1956 //
1957 // Is there an alternative? No, because:
1958 // - a->t limits a-path to 5 units
1959 // - s->b limits b-path to 10 units
1960 // Both paths must be used to their capacity for max flow.
1961 //
1962 // So optimal for max flow = 15 is cost = 75.
1963
1964 net.insert_arc(s, a, 10.0, 10.0); // s->a: expensive
1965 net.insert_arc(a, t, 5.0, 1.0); // a->t: cheap but limited
1966 net.insert_arc(s, b, 10.0, 1.0); // s->b: cheap
1967 net.insert_arc(b, t, 15.0, 1.0); // b->t: cheap and more capacity
1968
1969 return net;
1970 }
1971
1972 double get_flow(const Net& net)
1973 {
1974 double flow = 0;
1975 auto source = net.get_source();
1976 for (Out_Iterator<Net> it(source); it.has_curr(); it.next_ne())
1977 flow += it.get_curr()->flow;
1978 return flow;
1979 }
1980
1981 void print_network_state(const Net& net, const std::string& label)
1982 {
1983 std::cout << "\n--- " << label << " ---\n";
1984 std::cout << "Arcs:\n";
1985 for (auto a : net.arcs())
1986 {
1987 auto src = static_cast<Net::Node*>(a->src_node);
1988 auto tgt = static_cast<Net::Node*>(a->tgt_node);
1989 std::cout << " Arc(" << (void*)src << "->" << (void*)tgt << "): "
1990 << "flow=" << a->flow << "/" << a->cap
1991 << ", cost=" << a->cost
1992 << ", flow_cost=" << (a->flow * a->cost) << "\n";
1993 }
1994 std::cout << "Total flow: " << get_flow(net) << "\n";
1995 std::cout << "Total cost: " << net.flow_cost() << "\n";
1996 }
1997};
1998
1999TEST_F(NetworkSimplexBugInvestigation, DiagnoseNetworkSimplexBug)
2000{
2001 // Run with Network Simplex
2002 auto net_ns = build_asymmetric_diamond();
2003 std::cout << "\n========== NETWORK SIMPLEX BUG INVESTIGATION ==========\n";
2004
2005 // First compute max flow
2007 print_network_state(net_ns, "After Ford-Fulkerson (before Network Simplex)");
2008
2009 // Now run Network Simplex
2010 Aleph::Network_Simplex<Net> simplex(net_ns);
2011 size_t pivots = simplex.run();
2012
2013 print_network_state(net_ns, "After Network Simplex");
2014 std::cout << "Pivots performed: " << pivots << "\n";
2015
2016 // Run with Cycle Canceling for comparison
2017 auto net_cc = build_asymmetric_diamond();
2019 print_network_state(net_cc, "Using Cycle Canceling");
2020
2021 double flow_ns = get_flow(net_ns);
2022 double flow_cc = get_flow(net_cc);
2023 double cost_ns = net_ns.flow_cost();
2024 double cost_cc = net_cc.flow_cost();
2025
2026 std::cout << "\n========== SUMMARY ==========\n";
2027 std::cout << "Network Simplex: flow=" << flow_ns << ", cost=" << cost_ns
2028 << ", pivots=" << pivots << "\n";
2029 std::cout << "Cycle Canceling: flow=" << flow_cc << ", cost=" << cost_cc << "\n";
2030
2031 // For this network:
2032 // - Max flow = 15 (5 via a, 10 via b)
2033 // - Optimal cost = 5*(10+1) + 10*(1+1) = 55 + 20 = 75
2034 double expected_flow = 15.0;
2035 double expected_cost = 75.0;
2036
2037 std::cout << "Expected: flow=" << expected_flow << ", cost=" << expected_cost << "\n";
2038
2039 // Verify both find same flow
2040 EXPECT_NEAR(flow_ns, expected_flow, 1e-6) << "Network Simplex flow";
2041 EXPECT_NEAR(flow_cc, expected_flow, 1e-6) << "Cycle Canceling flow";
2042
2043 // Both should find the same (and optimal) cost
2044 EXPECT_NEAR(cost_ns, expected_cost, 1e-6) << "Network Simplex should find optimal cost";
2045 EXPECT_NEAR(cost_cc, expected_cost, 1e-6) << "Cycle Canceling should find optimal cost";
2046
2047 if (std::abs(cost_ns - cost_cc) > 1e-6)
2048 {
2049 std::cout << "\n⚠️ COST DIFFERENCE: Network Simplex=" << cost_ns
2050 << ", Cycle Canceling=" << cost_cc << "\n";
2051 if (cost_ns > cost_cc)
2052 std::cout << "Network Simplex found suboptimal solution!\n";
2053 else
2054 std::cout << "Cycle Canceling found suboptimal solution!\n";
2055 }
2056 else
2057 {
2058 std::cout << "\n✓ Both algorithms found the same cost\n";
2059 }
2060}
2061
2062TEST_F(NetworkSimplexBugInvestigation, SimpleNetworkOptimization)
2063{
2064 // Use a small diamond to verify basic optimization
2065 auto net = build_asymmetric_diamond();
2066
2067 // First compute max flow
2069 double cost_before = net.flow_cost();
2070
2071 // Create simplex and run
2072 Aleph::Network_Simplex<Net> simplex(net);
2073 size_t pivots = simplex.run();
2074 double cost_after = net.flow_cost();
2075
2076 std::cout << "Simple network: cost_before=" << cost_before
2077 << ", cost_after=" << cost_after
2078 << ", pivots=" << pivots << "\n";
2079
2080 // Verify cost didn't increase
2081 EXPECT_LE(cost_after, cost_before);
2082}
2083
2084//==============================================================================
2085// Network Simplex Statistics Tests
2086//==============================================================================
2087
2088TEST_F(LargeNetworkValidationTest, StatisticsTracking)
2089{
2090 auto net = build_grid_network(5); // 5x5 grid
2091
2093
2094 Aleph::Network_Simplex<Net> simplex(net);
2095 simplex.run();
2096
2097 auto stats = simplex.get_stats();
2098
2099 // Verify statistics are populated
2100 EXPECT_GE(stats.total_pivots, 0u);
2101 EXPECT_GE(stats.phase1_pivots, 0u);
2102 EXPECT_GE(stats.phase2_pivots, 0u);
2103 EXPECT_EQ(stats.total_pivots, stats.phase1_pivots + stats.phase2_pivots);
2104 EXPECT_GE(stats.total_time_ms, 0.0);
2105 EXPECT_GE(stats.phase1_time_ms, 0.0);
2106 EXPECT_GE(stats.phase2_time_ms, 0.0);
2107
2108 // Tree should have n-1 arcs
2109 EXPECT_EQ(stats.tree_arcs, net.vsize() - 1);
2110
2111 std::cout << "Statistics:\n"
2112 << " Total pivots: " << stats.total_pivots << "\n"
2113 << " Phase I: " << stats.phase1_pivots << " (" << stats.phase1_time_ms << " ms)\n"
2114 << " Phase II: " << stats.phase2_pivots << " (" << stats.phase2_time_ms << " ms)\n"
2115 << " Degenerate: " << stats.degenerate_pivots << "\n"
2116 << " Tree arcs: " << stats.tree_arcs << "\n";
2117}
2118
2119TEST_F(LargeNetworkValidationTest, StressTestLargeGrid)
2120{
2121 // Larger grid for stress testing
2122 auto net = build_grid_network(10); // 10x10 grid
2123
2125 double flow = net.flow_value();
2126
2127 Aleph::Network_Simplex<Net> simplex(net);
2128 simplex.run();
2129
2130 auto stats = simplex.get_stats();
2131
2132 // Verify flow is preserved
2133 EXPECT_NEAR(net.flow_value(), flow, 1e-6);
2134
2135 std::cout << "10x10 Grid stats:\n"
2136 << " Nodes: " << net.vsize() << ", Arcs: " << net.esize() << "\n"
2137 << " Pivots: " << stats.total_pivots << "\n"
2138 << " Time: " << stats.total_time_ms << " ms\n";
2139}
2140
2141TEST_F(NetworkSimplexBugInvestigation, DensityStressTest)
2142{
2143 // Create a dense network using the same pattern as other tests
2144 auto net = build_asymmetric_diamond(); // Use existing helper
2145
2147
2148 Aleph::Network_Simplex<Net> simplex(net);
2149 simplex.run();
2150
2151 auto stats = simplex.get_stats();
2152
2153 std::cout << "Dense network:\n"
2154 << " Nodes: " << net.vsize() << ", Arcs: " << net.esize() << "\n"
2155 << " Pivots: " << stats.total_pivots << "\n"
2156 << " Degenerate: " << stats.degenerate_pivots << "\n";
2157
2158 // Verify optimality
2159 EXPECT_TRUE(simplex.verify_tree_integrity());
2160 EXPECT_TRUE(simplex.is_valid_basic_solution());
2161}
2162
2163TEST_F(NetworkSimplexBugInvestigation, NegativeCostsTest)
2164{
2165 // Test with some negative costs using the diamond builder with modified costs
2166 // Build a simple network: s -> a -> b -> t with negative cost on a->b
2167 Net net;
2168
2169 auto s = net.insert_node();
2170 auto a = net.insert_node();
2171 auto b = net.insert_node();
2172 auto t = net.insert_node();
2173
2174 // Network structure allowing negative cost exploitation
2175 auto sa = net.insert_arc(s, a, 10.0, 2.0);
2176 auto sb = net.insert_arc(s, b, 10.0, 3.0);
2177 auto ab = net.insert_arc(a, b, 5.0, -1.0); // Negative cost!
2178 auto at = net.insert_arc(a, t, 10.0, 2.0);
2179 auto bt = net.insert_arc(b, t, 10.0, 1.0);
2180 (void)sa; (void)sb; (void)ab; (void)at; (void)bt; // Suppress unused warnings
2181
2183 double cost_before = net.flow_cost();
2184
2185 Aleph::Network_Simplex<Net> simplex(net);
2186 simplex.run();
2187 double cost_after = net.flow_cost();
2188
2189 std::cout << "Negative costs: before=" << cost_before
2190 << ", after=" << cost_after << "\n";
2191
2192 // Should find lower or equal cost
2193 EXPECT_LE(cost_after, cost_before + 1e-6);
2194}
2195
2196// =============================================================================
2197// NETWORK SIMPLEX WITH FLOATING AND INTEGER FLOWS
2198// =============================================================================
2199
2201
2202// Whether the flow of each arc of net is within [0, cap]
2203template <class N>
2204bool flows_within_capacities(const N & net)
2205{
2206 for (auto a : net.arcs())
2207 if (a->flow < 0 or a->flow > a->cap)
2208 return false;
2209 return true;
2210}
2211
2212// A pivot left an arc an ulp above its capacity; every later cycle through
2213// it then had a negative ratio, so that its pivot failed, and run() ended as
2214// if the flow were optimal, at cost 4 instead of 3.6
2215TEST(NetworkSimplexFloatingTest, APivotKeepsTheFlowsWithinTheCapacities)
2216{
2217 Net net;
2218 auto s = net.insert_node();
2219 auto t = net.insert_node();
2220 auto dear = net.insert_arc(s, t, 0.2, 3.0);
2221 auto a1 = net.insert_arc(s, t, 3.4, 1.0);
2222 auto a2 = net.insert_arc(s, t, 2.3, 1.0);
2223 dear->flow = 0.2;
2224 a1->flow = 2.7;
2225 a2->flow = 0.7;
2226
2227 Network_Simplex<Net> simplex(net);
2228 simplex.run();
2229
2230 EXPECT_TRUE(flows_within_capacities(net));
2231 EXPECT_TRUE(net.check_network());
2232 EXPECT_EQ(dear->flow, 0.0);
2233 EXPECT_NEAR(net.flow_value(), 3.6, 1e-12);
2234 EXPECT_NEAR(net.flow_cost(), 3.6, 1e-12);
2235}
2236
2237// The maximum flow of the paths of a depth-first search, which
2238// Ford-Fulkerson took with a floating flow before it took the shortest
2239// ones: the starting flow of the cases below that it found
2240template <class N>
2241struct Dfs_Maximum_Flow
2242{
2243 typename N::Flow_Type operator () (N & net) const
2244 {
2245 return aumenting_path_maximum_flow<N, Find_Aumenting_Path_DFS>(net);
2246 }
2247};
2248
2249// Capacities in tenths: a pivot left an arc of capacity 2.9 with a flow of
2250// 2.9000000000000004, and run() ended at cost -0.1; the exact problem, of
2251// capacities by ten, has the least cost -8
2252TEST(NetworkSimplexFloatingTest, DecimalCapacitiesReachTheOptimum)
2253{
2254 // u, v, the capacity in tenths and the cost; 0 is the source and 3 the sink
2255 const int spec[][4] = {{1, 4, 9, 2}, {2, 3, 10, 3}, {4, 2, 29, -2}, {2, 4, 22, 0},
2256 {0, 1, 26, 0}, {0, 2, 5, 2}, {0, 1, 7, 1}};
2257 // From the flow of Ford-Fulkerson, and from that of the depth-first
2258 // paths, which the pivots took to the ulp
2259 for (const bool dfs : {false, true})
2260 {
2261 Net net;
2262 std::vector<Net::Node *> nodes;
2263 for (int i = 0; i < 5; ++i)
2264 nodes.push_back(net.insert_node());
2265 for (const auto & a : spec)
2266 net.insert_arc(nodes[size_t(a[0])], nodes[size_t(a[1])], a[2] / 10.0, double(a[3]));
2267
2268 if (dfs)
2269 max_flow_min_cost_by_network_simplex<Net, Dfs_Maximum_Flow>(net);
2270 else
2272
2273 EXPECT_TRUE(flows_within_capacities(net)) << "dfs " << dfs;
2274 EXPECT_TRUE(net.check_network()) << "dfs " << dfs;
2275 EXPECT_NEAR(net.flow_value(), 1.0, 1e-12) << "dfs " << dfs;
2276 EXPECT_NEAR(net.flow_cost(), -0.8, 1e-12) << "dfs " << dfs;
2277 }
2278}
2279
2280// The pivots of a floating flow left a residue of rounding, of 2.8e-17, on a
2281// path that ended in a node, as the arc that leaves the tree takes its
2282// bound exactly: check_network() took it as a loss of the balance of the
2283// node. run() returns the residues at its end, as the maximum flows do. The
2284// capacities are k * 0.1, as the probe that found the case built them; k /
2285// 10.0 rounds them otherwise and does not leave the residue
2286TEST(NetworkSimplexFloatingTest, ResiduesOfRoundingGoBack)
2287{
2288 // u, v, the capacity in tenths and the cost; 1 is the source and 5 the sink
2289 const int spec[][4] = {{2, 5, 4, -1}, {1, 5, 0, -2}, {6, 2, 4, 1}, {0, 4, 2, 4}, {1, 3, 3, -2},
2290 {0, 2, 1, 3}, {3, 0, 4, 3}, {4, 5, 3, 0}, {3, 6, 3, -1}};
2291 Net net;
2292 std::vector<Net::Node *> nodes;
2293 for (int i = 0; i < 7; ++i)
2294 nodes.push_back(net.insert_node());
2295 for (const auto & a : spec)
2296 net.insert_arc(nodes[size_t(a[0])], nodes[size_t(a[1])], a[2] * 0.1, double(a[3]));
2297
2299 Network_Simplex<Net> simplex(net);
2300 simplex.run();
2301
2302 EXPECT_TRUE(flows_within_capacities(net));
2303 EXPECT_TRUE(net.check_network());
2304 EXPECT_NEAR(net.flow_value(), 0.3, 1e-12);
2305 EXPECT_NEAR(net.flow_cost(), -0.9, 1e-12); // the exact optimum
2306}
2307
2308// Ford-Fulkerson, the maximum flow of max_flow_min_cost_by_network_simplex()
2309// and of max_flow_min_cost_by_cycle_canceling() by default, took the paths
2310// of a depth-first search, which took the residues of rounding that
2311// capacities in tenths leave and spread them: on this network of 400 nodes
2312// it did not end. With a floating flow it takes the shortest paths
2313TEST(NetworkSimplexFloatingTest, DecimalCapacitiesEndOnAMidSizeNetwork)
2314{
2315 // n nodes; 0 is the source and n - 1 the sink; every other node has an
2316 // arc from an earlier one and one to a later one; then 10 n arcs at
2317 // random, none into the source nor out of the sink; capacities of 0.1
2318 // to 4 and costs of 1 to 20
2319 auto build = [] (Net & net)
2320 {
2321 const int n = 400;
2322 std::mt19937 gen(1);
2323 std::vector<Net::Node *> nodes;
2324 for (int i = 0; i < n; ++i)
2325 nodes.push_back(net.insert_node());
2326 auto arc = [&] (int a, int b)
2327 {
2328 const double cap = double(1 + gen() % 40) * 0.1;
2329 const double cost = double(1 + gen() % 20);
2330 net.insert_arc(nodes[size_t(a)], nodes[size_t(b)], cap, cost);
2331 };
2332 for (int i = 1; i < n - 1; ++i)
2333 {
2334 arc(int(gen() % unsigned(i)), i);
2335 arc(i, i + 1 + int(gen() % unsigned(n - 1 - i)));
2336 }
2337 for (int k = 0; k < 10 * n; ++k)
2338 {
2339 const int a = int(gen() % unsigned(n - 1));
2340 const int b = 1 + int(gen() % unsigned(n - 1));
2341 if (a != b)
2342 arc(a, b);
2343 }
2344 };
2345
2346 Net simplex, canceling;
2347 build(simplex);
2348 build(canceling);
2351
2352 // With the capacities by ten, the maximum flow is 281 and its least
2353 // cost 8111
2354 for (const Net * net : {&simplex, &canceling})
2355 {
2356 EXPECT_TRUE(flows_within_capacities(*net));
2357 EXPECT_TRUE(net->check_network());
2358 EXPECT_NEAR(net->flow_value(), 28.1, 1e-9);
2359 EXPECT_NEAR(net->flow_cost(), 811.1, 1e-9);
2360 }
2361}
2362
2363// The tolerance of the reduced costs was 1000 epsilons, 2.2e-13: run() did
2364// not lower costs below it, and left the flow on the dearer arc
2365TEST(NetworkSimplexFloatingTest, TinyCostsAreOptimized)
2366{
2367 for (const double unit : {1e-13, std::ldexp(1.0, -44)})
2368 {
2369 Net net;
2370 auto s = net.insert_node();
2371 auto a = net.insert_node();
2372 auto t = net.insert_node();
2373 auto sa = net.insert_arc(s, a, 1.0, 0.0);
2374 auto cheap = net.insert_arc(a, t, 1.0, unit);
2375 auto dear = net.insert_arc(a, t, 1.0, 2 * unit);
2376 sa->flow = 1;
2377 dear->flow = 1;
2378
2379 Network_Simplex<Net> simplex(net);
2380 simplex.run();
2381
2382 EXPECT_EQ(cheap->flow, 1.0) << "unit " << unit;
2383 EXPECT_EQ(dear->flow, 0.0) << "unit " << unit;
2384 EXPECT_DOUBLE_EQ(net.flow_cost(), unit) << "unit " << unit;
2385 }
2386}
2387
2388// So was that of the flows: capacities below it were taken as empty, and the
2389// flow went through the dearer arc
2390TEST(NetworkSimplexFloatingTest, TinyCapacitiesAreOptimized)
2391{
2392 for (const double unit : {1e-12, 1e-13})
2393 {
2394 Net net;
2395 auto s = net.insert_node();
2396 auto a = net.insert_node();
2397 auto t = net.insert_node();
2398 net.insert_arc(s, a, unit, 0.0);
2399 auto cheap = net.insert_arc(a, t, unit, 1.0);
2400 auto dear = net.insert_arc(a, t, unit, 2.0);
2401
2403
2404 EXPECT_EQ(cheap->flow, unit) << "unit " << unit;
2405 EXPECT_EQ(dear->flow, 0.0) << "unit " << unit;
2406 EXPECT_DOUBLE_EQ(net.flow_cost(), unit) << "unit " << unit;
2407 }
2408}
2409
2410// From the zero flow, run() left empty a cycle of cost -2e-13
2411TEST(NetworkSimplexFloatingTest, ATinyNegativeCycleIsSaturated)
2412{
2413 Net net;
2414 auto s = net.insert_node();
2415 auto a = net.insert_node();
2416 auto b = net.insert_node();
2417 auto t = net.insert_node();
2418 net.insert_arc(s, t, 1.0, 0.0);
2419 auto ab = net.insert_arc(a, b, 1.0, -1e-13);
2420 auto ba = net.insert_arc(b, a, 1.0, -1e-13);
2421
2422 Network_Simplex<Net> simplex(net);
2423 simplex.run();
2424
2425 EXPECT_EQ(ab->flow, 1.0);
2426 EXPECT_EQ(ba->flow, 1.0);
2427 EXPECT_DOUBLE_EQ(net.flow_cost(), -2e-13);
2428}
2429
2430// A cycle of negative cost through arcs without capacity has no bound: run()
2431// pushed around it an infinite flow, of cost NaN, or one of max(), and
2432// returned as if it had found the optimum
2433TEST(NetworkSimplexFloatingTest, AnUnboundedProgramThrows)
2434{
2435 for (const double cap : {std::numeric_limits<double>::infinity(),
2436 std::numeric_limits<double>::max()})
2437 {
2438 Net net;
2439 auto s = net.insert_node();
2440 auto a = net.insert_node();
2441 auto b = net.insert_node();
2442 auto t = net.insert_node();
2443 net.insert_arc(s, t, 1.0, 0.0);
2444 net.insert_arc(a, b, cap, -1.0);
2445 net.insert_arc(b, a, cap, 0.0);
2446
2447 EXPECT_THROW(max_flow_min_cost_by_network_simplex(net), std::domain_error)
2448 << "capacity " << cap;
2449 }
2450
2451 LNet net;
2452 auto s = net.insert_node();
2453 auto a = net.insert_node();
2454 auto b = net.insert_node();
2455 auto t = net.insert_node();
2456 net.insert_arc(s, t, 1, 0);
2457 net.insert_arc(a, b, std::numeric_limits<long>::max(), -1);
2458 net.insert_arc(b, a, std::numeric_limits<long>::max(), 0);
2459
2460 EXPECT_THROW(max_flow_min_cost_by_network_simplex(net), std::domain_error);
2461}
2462
2463// The pivots of a floating flow leave residues of rounding, which run()
2464// returns at its end: the domain_error of an unbounded program left before,
2465// after some pivots, and the network kept the residues, so that
2466// check_network() was false after it
2467TEST(NetworkSimplexFloatingTest, AnUnboundedProgramReturnsTheResidues)
2468{
2469 for (const double cap : {std::numeric_limits<double>::infinity(),
2470 std::numeric_limits<double>::max()})
2471 {
2472 // u, v, the capacity and the cost in tenths; 0 is the source and 5
2473 // the sink; 2 and 1 make a cycle of cost -0.1 through two arcs
2474 // without capacity, which no flow bounds
2475 Net net;
2476 std::vector<Net::Node *> nodes;
2477 for (int i = 0; i < 6; ++i)
2478 nodes.push_back(net.insert_node());
2479 const std::vector<std::array<int, 4>> spec = {{0, 2, 35, -6}, {2, 3, 14, 9},
2480 {2, 3, 8, 23}, {4, 5, 37, 0},
2481 {3, 4, 39, 23}, {1, 4, 39, 8}};
2482 for (const auto & a : spec)
2483 net.insert_arc(nodes[size_t(a[0])], nodes[size_t(a[1])], a[2] / 10.0, a[3] / 10.0);
2484 net.insert_arc(nodes[2], nodes[1], cap, -0.3);
2485 net.insert_arc(nodes[1], nodes[2], cap, 0.2);
2486
2488 ASSERT_TRUE(net.check_network()) << "capacity " << cap;
2489 const double value = net.flow_value();
2490
2491 EXPECT_THROW(Network_Simplex<Net>(net).run(), std::domain_error) << "capacity " << cap;
2492 EXPECT_TRUE(net.check_network()) << "capacity " << cap;
2493 EXPECT_TRUE(flows_within_capacities(net)) << "capacity " << cap;
2494 EXPECT_NEAR(net.flow_value(), value, 1e-12) << "capacity " << cap;
2495 }
2496}
2497
2498// Dinic and the capacity scaling left a node that received 5.6e-17 and
2499// sent nothing, a residue of rounding beyond the tolerance of check_node(),
2500// and the network simplex refused their maximum flow as not feasible. They
2501// return the residues at their end, as the augmenting paths
2502TEST(NetworkSimplexFloatingTest, TakesTheMaximumFlowsOfDinicAndOfTheScaling)
2503{
2504 // u, v and k, for a capacity of k * 0.1; the costs are 0; 0 is the
2505 // source and 19 the sink
2506 const int spec[][3] = {{0, 1, 12}, {1, 18, 5}, {1, 2, 8}, {0, 3, 4}, {3, 7, 19},
2507 {0, 5, 0}, {5, 8, 5}, {4, 6, 9}, {7, 11, 8}, {4, 8, 6},
2508 {8, 13, 19}, {0, 10, 11}, {11, 19, 8}, {10, 12, 8}, {12, 18, 8},
2509 {13, 19, 20}, {3, 15, 8}, {15, 18, 15}, {14, 16, 5}, {10, 17, 1},
2510 {17, 19, 14}, {9, 18, 7}, {18, 19, 6}, {10, 16, 13}, {0, 9, 2},
2511 {16, 11, 19}, {3, 4, 8}, {6, 14, 4}, {2, 13, 14}, {9, 7, 20}};
2512 auto build = [&spec] (Net & net)
2513 {
2514 std::vector<Net::Node *> nodes;
2515 for (int i = 0; i < 20; ++i)
2516 nodes.push_back(net.insert_node());
2517 for (const auto & a : spec)
2518 net.insert_arc(nodes[size_t(a[0])], nodes[size_t(a[1])], a[2] * 0.1, 0.0);
2519 };
2520
2521 Net dinic, scaling;
2522 build(dinic);
2523 build(scaling);
2524 dinic_maximum_flow(dinic);
2526 EXPECT_TRUE(dinic.check_network());
2527 EXPECT_TRUE(scaling.check_network());
2528
2529 Net net;
2530 build(net);
2531 ASSERT_NO_THROW((max_flow_min_cost_by_network_simplex<Net, Dinic_Maximum_Flow>(net)));
2532 EXPECT_NEAR(net.flow_value(), 2.7, 1e-12);
2533 EXPECT_TRUE(net.check_network());
2534
2535 Net other;
2536 build(other);
2537 ASSERT_NO_THROW((max_flow_min_cost_by_network_simplex<Net, Capacity_Scaling_Maximum_Flow>(other)));
2538 EXPECT_NEAR(other.flow_value(), 2.7, 1e-12);
2539 EXPECT_TRUE(other.check_network());
2540}
2541
2542// The network of AnInfeasibleFlowThrows: s = 0, a = 1, b = 2, t = 3
2543std::vector<LNet::Arc *> build_infeasible_case(LNet & net)
2544{
2545 std::vector<LNet::Node *> p;
2546 for (int i = 0; i < 4; ++i)
2547 p.push_back(net.insert_node());
2548 return {net.insert_arc(p[0], p[1], 2, 1), net.insert_arc(p[0], p[2], 2, 2),
2549 net.insert_arc(p[1], p[3], 2, 1), net.insert_arc(p[2], p[3], 2, 1),
2550 net.insert_arc(p[1], p[2], 1, -3)};
2551}
2552
2553// run() optimizes the flow that the network has, and did so from flows that
2554// a node did not keep or that broke the bounds of an arc
2555TEST(NetworkSimplexIntegerTest, AnInfeasibleFlowThrows)
2556{
2557 {
2558 LNet net;
2559 auto arcs = build_infeasible_case(net);
2560 arcs[0]->flow = 2; // into a, and nothing out of it
2561 Network_Simplex<LNet> simplex(net);
2562 EXPECT_THROW(simplex.run(), std::domain_error);
2563 }
2564 {
2565 LNet net;
2566 auto arcs = build_infeasible_case(net);
2567 arcs[0]->flow = arcs[2]->flow = 3; // above their capacity 2
2568 Network_Simplex<LNet> simplex(net);
2569 EXPECT_THROW(simplex.run(), std::domain_error);
2570 }
2571 {
2572 LNet net;
2573 auto arcs = build_infeasible_case(net);
2574 arcs[0]->flow = arcs[2]->flow = -1;
2575 Network_Simplex<LNet> simplex(net);
2576 EXPECT_THROW(simplex.run(), std::domain_error);
2577 }
2578}
2579
2580// An infinite flow, on an arc of infinite capacity, is within its bounds
2581TEST(NetworkSimplexFloatingTest, AnInfiniteFlowThrows)
2582{
2583 Net net;
2584 auto s = net.insert_node();
2585 auto t = net.insert_node();
2586 auto st = net.insert_arc(s, t, std::numeric_limits<double>::infinity(), 1.0);
2587 st->flow = std::numeric_limits<double>::infinity();
2588
2589 Network_Simplex<Net> simplex(net);
2590 EXPECT_THROW(simplex.run(), std::domain_error);
2591}
2592
2593// With an integer flow the tolerance was zero, and the predicates compared
2594// with <: is_at_lower_bound() and is_at_upper_bound() were always false
2595TEST(NetworkSimplexIntegerTest, ThePredicatesOfTheBoundsCompareExactly)
2596{
2597 LNet net;
2598 auto s = net.insert_node();
2599 auto a = net.insert_node();
2600 auto t = net.insert_node();
2601 auto sa = net.insert_arc(s, a, 1, 0);
2602 auto cheap = net.insert_arc(a, t, 1, 1);
2603 auto dear = net.insert_arc(a, t, 1, 2);
2604 sa->flow = 1;
2605 dear->flow = 1;
2606
2607 Network_Simplex<LNet> simplex(net);
2608 simplex.run();
2609
2610 ASSERT_EQ(cheap->flow, 1);
2611 ASSERT_EQ(dear->flow, 0);
2612 EXPECT_TRUE(simplex.is_at_upper_bound(sa));
2613 EXPECT_TRUE(simplex.is_at_upper_bound(cheap));
2614 EXPECT_FALSE(simplex.is_at_lower_bound(cheap));
2615 EXPECT_TRUE(simplex.is_at_lower_bound(dear));
2616 EXPECT_FALSE(simplex.is_at_upper_bound(dear));
2617}
2618
2619// And no pivot of an integer flow was counted as degenerate
2620TEST(NetworkSimplexIntegerTest, DegeneratePivotsAreCounted)
2621{
2622 // The maximum flow saturates s->a, s->b, a->t and b->t, and is of least
2623 // cost: no pivot of run() moves flow
2624 LNet net;
2625 auto s = net.insert_node();
2626 auto a = net.insert_node();
2627 auto b = net.insert_node();
2628 auto t = net.insert_node();
2629 net.insert_arc(s, a, 2, 1);
2630 net.insert_arc(s, b, 2, 2);
2631 net.insert_arc(a, t, 2, 1);
2632 net.insert_arc(b, t, 2, 1);
2633 net.insert_arc(a, b, 1, 0);
2635 const long cost = net.flow_cost();
2636
2637 Network_Simplex<LNet> simplex(net);
2638 const size_t pivots = simplex.run();
2639
2640 ASSERT_EQ(net.flow_cost(), cost);
2641 ASSERT_GT(pivots, 0u);
2642 EXPECT_EQ(simplex.get_stats().degenerate_pivots, pivots);
2643}
2644
2645// The diagnostics read the structures that run() makes; before it they
2646// threw "key not found"
2647TEST_F(NetworkSimplexTest, TheDiagnosticsAskForRunFirst)
2648{
2649 auto net = build_diamond_network();
2650 Network_Simplex<Net> simplex(net);
2651
2652 auto expect_run_first = [] (auto diagnostic, const char * name)
2653 {
2654 try
2655 {
2656 diagnostic();
2657 ADD_FAILURE() << name << "() did not throw";
2658 }
2659 catch (const std::domain_error & e)
2660 {
2661 EXPECT_NE(std::string(e.what()).find("run() has not been called"),
2662 std::string::npos) << name << "(): " << e.what();
2663 }
2664 };
2665 expect_run_first([&] { (void) simplex.count_non_tree_partial_arcs(); },
2666 "count_non_tree_partial_arcs");
2667 expect_run_first([&] { (void) simplex.is_valid_basic_solution(); },
2668 "is_valid_basic_solution");
2669 expect_run_first([&] { (void) simplex.verify_tree_reduced_costs(); },
2670 "verify_tree_reduced_costs");
2671 expect_run_first([&] { (void) simplex.verify_tree_integrity(); },
2672 "verify_tree_integrity");
2673 expect_run_first([&] { (void) simplex.force_partial_arcs_into_tree(); },
2674 "force_partial_arcs_into_tree");
2675 expect_run_first([&] { simplex.print_diagnostics(); }, "print_diagnostics");
2676
2677 simplex.run();
2678 EXPECT_TRUE(simplex.is_valid_basic_solution());
2679 EXPECT_TRUE(simplex.verify_tree_integrity());
2680}
2681
2682// A network whose source is its sink, isolated, has a tree for each of its
2683// components, and the statistics expected vsize() - 1 arcs in them
2684TEST(NetworkSimplexIntegerTest, TheStatisticsExpectATreeByComponent)
2685{
2686 LNet net;
2687 net.insert_node(); // the source and the sink
2688 auto a = net.insert_node();
2689 auto b = net.insert_node();
2690 net.insert_arc(a, b, 1, -1);
2691 net.insert_arc(b, a, 1, -1);
2692
2693 Network_Simplex<LNet> simplex(net);
2694 simplex.run();
2695 ASSERT_EQ(net.flow_cost(), -2);
2696
2697 testing::internal::CaptureStdout();
2698 simplex.print_stats();
2699 simplex.print_diagnostics();
2700 const std::string out = testing::internal::GetCapturedStdout();
2701 EXPECT_NE(out.find("Tree arcs: 1 (expected 1)"), std::string::npos) << out;
2702 EXPECT_NE(out.find("Expected tree arcs: 1\n"), std::string::npos) << out;
2703}
2704
2705// set_lower_bound(), get_lower_bound() and residual_lower() are deprecated
2706#if defined(_MSC_VER) && !defined(__clang__)
2707# pragma warning(push)
2708# pragma warning(disable : 4996)
2709#else
2710# pragma GCC diagnostic push
2711# pragma GCC diagnostic ignored "-Wdeprecated-declarations"
2712#endif
2713
2714// The network of the cases of the lower bounds: a->b costs 5, and the
2715// optimum leaves it empty
2716std::vector<LNet::Arc *> build_lower_bound_case(LNet & net)
2717{
2718 auto s = net.insert_node();
2719 auto a = net.insert_node();
2720 auto b = net.insert_node();
2721 auto t = net.insert_node();
2722 std::vector<LNet::Arc *> arcs = {net.insert_arc(s, a, 2, 0), net.insert_arc(s, b, 2, 0),
2723 net.insert_arc(a, t, 2, 0), net.insert_arc(b, t, 2, 0),
2724 net.insert_arc(a, b, 1, 5)};
2726 return arcs;
2727}
2728
2729// set_lower_bound() stored a bound that no part of the algorithm read, and
2730// that the next run() set to 0
2731TEST(NetworkSimplexIntegerTest, ANonzeroLowerBoundThrows)
2732{
2733 LNet net;
2734 auto ab = build_lower_bound_case(net)[4];
2735
2736 Network_Simplex<LNet> simplex(net);
2737 simplex.run();
2738
2739 EXPECT_THROW(simplex.set_lower_bound(ab, 1), std::domain_error);
2740 EXPECT_NO_THROW(simplex.set_lower_bound(ab, 0));
2741 EXPECT_EQ(simplex.get_lower_bound(ab), 0);
2742 simplex.run();
2743 EXPECT_EQ(ab->flow, 0);
2744}
2745
2746// Before run(), the members of the lower bounds threw "key not found"
2747TEST(NetworkSimplexIntegerTest, TheLowerBoundsNeedNoRun)
2748{
2749 LNet net;
2750 auto arcs = build_lower_bound_case(net);
2751 auto sa = arcs[0], ab = arcs[4];
2752
2753 Network_Simplex<LNet> simplex(net);
2754 EXPECT_THROW(simplex.set_lower_bound(ab, 1), std::domain_error);
2755 EXPECT_NO_THROW(simplex.set_lower_bound(ab, 0));
2756 EXPECT_NO_THROW(EXPECT_EQ(simplex.get_lower_bound(ab), 0));
2757 EXPECT_NO_THROW(EXPECT_TRUE(simplex.is_at_lower_bound(ab)));
2758 EXPECT_NO_THROW(EXPECT_FALSE(simplex.is_at_lower_bound(sa)));
2759 EXPECT_NO_THROW(EXPECT_EQ(simplex.residual_lower(sa), sa->flow));
2760}
2761
2762#if defined(_MSC_VER) && !defined(__clang__)
2763# pragma warning(pop)
2764#else
2765# pragma GCC diagnostic pop
2766#endif
2767
2768// =============================================================================
2769// CYCLE CANCELING WITH NEGATIVE COSTS
2770// =============================================================================
2771
2772// The networks of the cases of negative costs, with their least cost: a
2773// negative arc that the cheapest maximum flow, of value 4, takes, at cost
2774// 6 (10 without it), and a cycle of cost -2 apart from the path s->t
2775template <class N>
2776void build_negative_costs_case(N & net, const bool apart)
2777{
2778 auto s = net.insert_node();
2779 auto a = net.insert_node();
2780 auto b = net.insert_node();
2781 auto t = net.insert_node();
2782 if (apart)
2783 {
2784 net.insert_arc(s, t, 1, 0);
2785 net.insert_arc(a, b, 1, -1);
2786 net.insert_arc(b, a, 1, -1);
2787 return;
2788 }
2789 net.insert_arc(s, a, 2, 1);
2790 net.insert_arc(s, b, 2, 1);
2791 net.insert_arc(a, b, 1, -3);
2792 net.insert_arc(a, t, 2, 2);
2793 net.insert_arc(b, t, 3, 1);
2794}
2795
2796// create_residual_arc() asserted that the costs were not negative, which
2797// ended the program in a debug build, though the canceling takes them
2798TEST(CycleCancelingTest, NegativeCostsReachTheOptimum)
2799{
2800 for (const bool apart : {false, true})
2801 {
2802 Net net;
2803 build_negative_costs_case(net, apart);
2805 EXPECT_TRUE(flows_within_capacities(net));
2806 EXPECT_DOUBLE_EQ(net.flow_value(), apart ? 1.0 : 4.0);
2807 EXPECT_DOUBLE_EQ(net.flow_cost(), apart ? -2.0 : 6.0);
2808
2809 LNet lnet;
2810 build_negative_costs_case(lnet, apart);
2811 max_flow_min_cost_by_cycle_canceling<LNet, Edmonds_Karp_Maximum_Flow>(lnet);
2812 EXPECT_TRUE(flows_within_capacities(lnet));
2813 EXPECT_EQ(lnet.flow_value(), apart ? 1 : 4);
2814 EXPECT_EQ(lnet.flow_cost(), apart ? -2 : 6);
2815 }
2816}
2817
2818// A cycle of negative cost through arcs without capacity has no bound: the
2819// canceling pushed around it an infinite flow, of cost NaN, or one of max()
2820TEST(CycleCancelingTest, AnUnboundedProgramThrows)
2821{
2822 for (const double cap : {std::numeric_limits<double>::infinity(),
2823 std::numeric_limits<double>::max()})
2824 {
2825 Net net;
2826 auto s = net.insert_node();
2827 auto a = net.insert_node();
2828 auto b = net.insert_node();
2829 auto t = net.insert_node();
2830 auto st = net.insert_arc(s, t, 1.0, 0.0);
2831 auto ab = net.insert_arc(a, b, cap, -1.0);
2832 auto ba = net.insert_arc(b, a, cap, 0.0);
2833
2834 EXPECT_THROW(max_flow_min_cost_by_cycle_canceling(net), std::domain_error)
2835 << "capacity " << cap;
2836 EXPECT_EQ(st->flow, 1.0); // the maximum flow stays
2837 EXPECT_EQ(ab->flow, 0.0);
2838 EXPECT_EQ(ba->flow, 0.0);
2839 }
2840
2841 LNet net;
2842 auto s = net.insert_node();
2843 auto a = net.insert_node();
2844 auto b = net.insert_node();
2845 auto t = net.insert_node();
2846 net.insert_arc(s, t, 1, 0);
2847 net.insert_arc(a, b, std::numeric_limits<long>::max(), -1);
2848 net.insert_arc(b, a, std::numeric_limits<long>::max(), 0);
2849
2850 EXPECT_THROW(max_flow_min_cost_by_cycle_canceling(net), std::domain_error);
2851}
2852
2853// The network of a case of decimal data: u, v, and the capacity and the
2854// cost in tenths
2855void build_tenths_case(Net & net, int n, const std::vector<std::array<int, 4>> & spec)
2856{
2857 std::vector<Net::Node *> nodes;
2858 for (int i = 0; i < n; ++i)
2859 nodes.push_back(net.insert_node());
2860 for (const auto & a : spec)
2861 net.insert_arc(nodes[size_t(a[0])], nodes[size_t(a[1])], a[2] / 10.0, a[3] / 10.0);
2862}
2863
2864// With costs that are not exact in binary, as tenths, the rounding of the
2865// sums of Bellman-Ford made a cycle of cost zero negative, an arc with a
2866// partial flow and its residual, at c and -c: cancelling it moved no flow,
2867// and the canceling did not end
2868TEST(CycleCancelingTest, DecimalCostsEnd)
2869{
2870 // 1 is the source and 0 the sink; from the flow of Ford-Fulkerson, and
2871 // from that of the depth-first paths, where the case was found
2872 for (const bool dfs : {false, true})
2873 {
2874 Net net;
2875 build_tenths_case(net, 3, {{1, 2, 33, 4}, {2, 2, 20, 6}, {2, 2, 28, 3}, {2, 0, 7, 8},
2876 {2, 2, 9, 9}, {1, 0, 3, 4}, {1, 2, 16, 6}, {2, 2, 15, 1}});
2877
2878 if (dfs)
2879 max_flow_min_cost_by_cycle_canceling<Net, Dfs_Maximum_Flow>(net);
2880 else
2882
2883 EXPECT_TRUE(flows_within_capacities(net)) << "dfs " << dfs;
2884 EXPECT_TRUE(net.check_network()) << "dfs " << dfs;
2885 EXPECT_NEAR(net.flow_value(), 1.0, 1e-12) << "dfs " << dfs;
2886 EXPECT_NEAR(net.flow_cost(), 0.96, 1e-12) << "dfs " << dfs; // the exact optimum
2887 }
2888}
2889
2890// A residue of rounding of a capacity, of an ulp, was the slack of negative
2891// cycles, each of which left such a residue for another: the canceling did
2892// not end
2893TEST(CycleCancelingTest, AResidueOfRoundingIsNoSlack)
2894{
2895 // 4 is the source and 5 the sink; from the flow of Ford-Fulkerson, and
2896 // from that of the depth-first paths, where the case was found
2897 for (const bool dfs : {false, true})
2898 {
2899 Net net;
2900 build_tenths_case(net, 10, {{8, 6, 30, 39}, {8, 7, 11, 57}, {4, 8, 7, 4}, {9, 7, 29, -17},
2901 {0, 2, 25, -28}, {8, 0, 8, 29}, {2, 0, 29, 41}, {7, 3, 8, 24},
2902 {0, 2, 7, 5}, {8, 8, 20, 52}, {0, 9, 4, -15}, {4, 5, 3, 53},
2903 {6, 7, 21, 40}, {4, 9, 11, 18}, {0, 1, 5, 8}, {9, 5, 1, -2},
2904 {9, 1, 12, 19}, {7, 1, 20, 55}, {4, 1, 12, 45}, {4, 8, 2, 22},
2905 {4, 5, 30, 10}, {7, 1, 20, -13}, {6, 1, 7, -17}, {9, 8, 40, 36},
2906 {0, 0, 21, -20}, {0, 5, 20, -15}, {2, 8, 20, -21}, {7, 5, 3, 10},
2907 {1, 5, 30, -27}, {3, 9, 40, 47}});
2908
2909 if (dfs)
2910 max_flow_min_cost_by_cycle_canceling<Net, Dfs_Maximum_Flow>(net);
2911 else
2913
2914 EXPECT_TRUE(flows_within_capacities(net)) << "dfs " << dfs;
2915 EXPECT_TRUE(net.check_network()) << "dfs " << dfs;
2916 EXPECT_NEAR(net.flow_value(), 6.5, 1e-12) << "dfs " << dfs;
2917 EXPECT_NEAR(net.flow_cost(), -3.01, 1e-12) << "dfs " << dfs; // the exact optimum
2918 }
2919}
2920
2921// By rounding, the arc that bounds a cycle went beyond its capacity, or its
2922// mirror below zero, and an arc of the network carried less than nothing
2923TEST(CycleCancelingTest, DecimalFlowsStayWithinTheCapacities)
2924{
2925 // 0 is the source and 1 the sink
2926 Net net;
2927 build_tenths_case(net, 3, {{2, 2, 6, -18}, {0, 2, 2, 50}, {2, 1, 38, 16}, {0, 1, 32, 31},
2928 {0, 1, 4, 0}, {2, 1, 38, 3}, {0, 1, 23, -30}});
2929
2930 max_flow_min_cost_by_cycle_canceling<Net, Edmonds_Karp_Maximum_Flow>(net);
2931
2932 EXPECT_TRUE(flows_within_capacities(net));
2933 EXPECT_TRUE(net.check_network());
2934 EXPECT_NEAR(net.flow_value(), 6.1, 1e-12);
2935 EXPECT_NEAR(net.flow_cost(), 3.0, 1e-12); // the exact optimum
2936}
2937
2938// The flow that the network has, as the maximum flow of the canceling
2939template <class N>
2940struct Given_Maximum_Flow
2941{
2942 typename N::Flow_Type operator () (N & net) const
2943 {
2944 return net.flow_value();
2945 }
2946};
2947
2948// The mirror of an arc without capacity, of capacity infinity or max(), had
2949// the slack cap - (cap - flow), NaN or 0, which the residual filter left
2950// out: the canceling could not take back the flow of a dear path through
2951// that arc, and the cost stayed above the least one
2952TEST(CycleCancelingTest, TheFlowOfAnArcWithoutCapacityGoesBack)
2953{
2954 for (const double cap : {std::numeric_limits<double>::infinity(),
2955 std::numeric_limits<double>::max()})
2956 for (const int units : {1, 2})
2957 for (const bool given : {false, true})
2958 {
2959 // The maximum flow takes the dear arc x, the shortest path; the
2960 // optimum sends one unit through b, at cost 2, and the second
2961 // one, if any, through x, at cost 10
2962 Net net;
2963 auto s = net.insert_node();
2964 auto a = net.insert_node();
2965 auto b = net.insert_node();
2966 auto t = net.insert_node();
2967 auto sa = net.insert_arc(s, a, double(units), 0.0);
2968 auto x = net.insert_arc(a, t, cap, 10.0);
2969 net.insert_arc(a, b, 1.0, 1.0);
2970 net.insert_arc(b, t, 1.0, 1.0);
2971
2972 if (given)
2973 {
2974 sa->flow = x->flow = double(units);
2975 max_flow_min_cost_by_cycle_canceling<Net, Given_Maximum_Flow>(net);
2976 }
2977 else
2979
2980 SCOPED_TRACE("capacity " + std::to_string(cap) + ", units " + std::to_string(units)
2981 + ", given " + std::to_string(given));
2982 EXPECT_TRUE(std::isfinite(x->flow));
2983 EXPECT_TRUE(flows_within_capacities(net));
2984 EXPECT_TRUE(net.check_network());
2985 EXPECT_EQ(x->flow, units - 1.0);
2986 EXPECT_DOUBLE_EQ(net.flow_cost(), 2.0 + 10.0 * (units - 1));
2987 }
2988}
2989
2990// A cycle took what 3->4 had left, and flow + (0.6 - flow) came out an ulp
2991// above 0.6, 0.60000000000000009 of 0.59999999999999998: the arc that
2992// bounds a cycle takes its capacity, exactly
2993TEST(CycleCancelingTest, TheArcThatBoundsACycleStaysWithinItsCapacity)
2994{
2995 // u, v, the capacity and the cost in tenths; 0 is the source and 8 the sink
2996 const std::vector<std::array<int, 4>> spec = {
2997 {0, 1, 33, -8}, {0, 2, 38, 26}, {3, 4, 6, 9}, {4, 5, 29, -2}, {0, 5, 11, 17},
2998 {6, 7, 37, 8}, {7, 8, 4, 15}, {5, 8, 22, -8}, {1, 6, 27, 12}, {6, 3, 17, 22},
2999 {1, 8, 9, -9}, {7, 5, 23, -4}, {0, 6, 3, 5}, {1, 4, 20, 27}, {1, 3, 39, -9},
3000 {1, 7, 15, 28}, {7, 9, 35, 20}, {9, 8, 11, 13}, {2, 8, 37, 10}};
3001 Net net;
3002 std::vector<Net::Node *> nodes;
3003 for (int i = 0; i < 10; ++i)
3004 nodes.push_back(net.insert_node());
3005 for (const auto & a : spec)
3006 net.insert_arc(nodes[size_t(a[0])], nodes[size_t(a[1])], a[2] / 10.0, a[3] / 10.0);
3007
3009
3010 EXPECT_TRUE(flows_within_capacities(net));
3011 EXPECT_TRUE(net.check_network());
3012 EXPECT_NEAR(net.flow_value(), 8.3, 1e-12);
3013 EXPECT_NEAR(net.flow_cost(), 17.67, 1e-12); // the exact optimum
3014}
3015
3016// From m, two arcs to the sink, of costs 1 and 1 - 1e-7, beside an arc
3017// of capacity 1 from the source: the first maximum flow takes the first,
3018// and the second is cheaper by 1e-7, far above the tolerances of the costs
3019// with costs of 1, 4 n^2 epsilons for the canceling and 1000 for the
3020// simplex, so that both take it
3021void build_cheaper_by_1e7(Net & net, Net::Arc *& dear, Net::Arc *& cheap)
3022{
3023 auto s = net.insert_node(), m = net.insert_node(), t = net.insert_node();
3024 net.insert_arc(s, m, 1, 0);
3025 dear = net.insert_arc(m, t, 1, 1);
3026 cheap = net.insert_arc(m, t, 1, 1 - 1e-7);
3027}
3028
3029TEST(CycleCancelingTest, TakesAnImprovementOf1e7)
3030{
3031 Net net;
3032 Net::Arc * dear = nullptr, * cheap = nullptr;
3033 build_cheaper_by_1e7(net, dear, cheap);
3035 EXPECT_EQ(dear->flow, 0);
3036 EXPECT_EQ(cheap->flow, 1);
3037 EXPECT_DOUBLE_EQ(net.flow_cost(), 1 - 1e-7);
3038}
3039
3040TEST(NetworkSimplexFloatingTest, TakesAnImprovementOf1e7)
3041{
3042 Net net;
3043 Net::Arc * dear = nullptr, * cheap = nullptr;
3044 build_cheaper_by_1e7(net, dear, cheap);
3046 EXPECT_EQ(dear->flow, 0);
3047 EXPECT_EQ(cheap->flow, 1);
3048 EXPECT_DOUBLE_EQ(net.flow_cost(), 1 - 1e-7);
3049}
3050
3051// A path of arcs of infinite capacity from the source to the sink makes
3052// the maximum flow infinite, which has no cost to minimize: the network
3053// simplex took it as a flow that is not feasible, and the cycle canceling
3054// returned it with an infinite cost. Both throw that the maximum flow is
3055// infinite, and the network keeps it
3056TEST(InfiniteMaximumFlowTest, TheSimplexAndTheCancelingRefuseIt)
3057{
3058 const double inf = std::numeric_limits<double>::infinity();
3059 for (int algo = 0; algo < 2; ++algo)
3060 {
3061 Net net;
3062 auto s = net.insert_node(), a = net.insert_node(), t = net.insert_node();
3063 net.insert_arc(s, a, inf, 1);
3064 net.insert_arc(a, t, inf, 1);
3065 net.insert_arc(s, t, 2.5, 3);
3066 const char * name = algo == 0 ? "network simplex" : "cycle canceling";
3067 try
3068 {
3069 if (algo == 0)
3071 else
3073 ADD_FAILURE() << name << " did not throw";
3074 }
3075 catch (const std::domain_error & e)
3076 {
3077 EXPECT_NE(std::string(e.what()).find("infinite"), std::string::npos)
3078 << name << ": " << e.what();
3079 }
3080 EXPECT_EQ(net.flow_value(), inf) << name;
3081 }
3082}
3083
3084// The network of the maximum flows of an arc of infinite capacity: s -> a
3085// of infinity and a -> t of 2.5, s -> b of 1.5 and b -> t of infinity,
3086// whose maximum flow, 4, costs 2.5 * 2 + 1.5 * 4 = 11
3087template <template <class> class Max_Flow>
3088void expect_the_cost_of_a_finite_flow_through_infinite_arcs(const char * name)
3089{
3090 const double inf = std::numeric_limits<double>::infinity();
3091 for (int algo = 0; algo < 2; ++algo)
3092 {
3093 Net net;
3094 auto s = net.insert_node(), a = net.insert_node(), b = net.insert_node(),
3095 t = net.insert_node();
3096 net.insert_arc(s, a, inf, 1);
3097 net.insert_arc(a, t, 2.5, 1);
3098 net.insert_arc(s, b, 1.5, 2);
3099 net.insert_arc(b, t, inf, 2);
3100 if (algo == 0)
3101 EXPECT_NO_THROW((max_flow_min_cost_by_network_simplex<Net, Max_Flow>(net))) << name;
3102 else
3103 EXPECT_NO_THROW((max_flow_min_cost_by_cycle_canceling<Net, Max_Flow>(net))) << name;
3104 EXPECT_EQ(net.flow_value(), 4.0) << name << (algo == 0 ? " and the simplex" : " and the canceling");
3105 EXPECT_EQ(net.flow_cost(), 11.0) << name << (algo == 0 ? " and the simplex" : " and the canceling");
3106 }
3107}
3108
3109// An arc of infinite capacity on a network whose maximum flow is finite
3110// does not make it infinite: the simplex and the canceling take it from
3111// each maximum flow, also from those of the preflows, which came out
3112// infinite there
3113TEST(InfiniteMaximumFlowTest, AnInfiniteArcOfAFiniteMaximumFlowIsTaken)
3114{
3115 expect_the_cost_of_a_finite_flow_through_infinite_arcs<Ford_Fulkerson_Maximum_Flow>("ford_fulkerson");
3116 expect_the_cost_of_a_finite_flow_through_infinite_arcs<Edmonds_Karp_Maximum_Flow>("edmonds_karp");
3117 expect_the_cost_of_a_finite_flow_through_infinite_arcs<Dinic_Maximum_Flow>("dinic");
3118 expect_the_cost_of_a_finite_flow_through_infinite_arcs<Capacity_Scaling_Maximum_Flow>("capacity_scaling");
3119 expect_the_cost_of_a_finite_flow_through_infinite_arcs<Fifo_Preflow_Maximum_Flow>("fifo_preflow");
3120 expect_the_cost_of_a_finite_flow_through_infinite_arcs<Heap_Preflow_Maximum_Flow>("heap_preflow");
3121 expect_the_cost_of_a_finite_flow_through_infinite_arcs<Random_Preflow_Maximum_Flow>("random_preflow");
3122 expect_the_cost_of_a_finite_flow_through_infinite_arcs<HLPP_Maximum_Flow>("hlpp");
3123}
3124
3125
3126} // anonymous namespace
3127
3128int main(int argc, char **argv)
3129{
3130 ::testing::InitGoogleTest(&argc, argv);
3131 return RUN_ALL_TESTS();
3132}
Simplex algorithm for linear programming.
TEST_F(AdaptiveHuffmanWithoutMemory, ALostByteLeavesTheDecoderFailed)
WeightedDigraph::Node Node
WeightedDigraph::Arc Arc
int main()
size_t size_t int32_t value
Definition ca-c-api.h:116
size_t size_t int32_t * out
Definition ca-c-api.h:120
Bellman-Ford algorithm for shortest paths with negative weights.
bool has_curr() const noexcept
Return true the iterator has an current arc.
Definition tpl_graph.H:1822
Generic key-value map implemented on top of a binary search tree.
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
Network Simplex algorithm for minimum cost flow.
Filtered iterator for outcoming arcs of a node.
Definition tpl_graph.H:1942
Linear program solver using the Simplex method.
Definition Simplex.H:279
constexpr size_t vsize() const noexcept
See get_num_nodes().
Definition graph-dry.H:984
size_t esize() const noexcept
Return the total of arcs of graph.
Definition graph-dry.H:1078
#define TEST(name)
DynArray< Graph::Node * > nodes
Definition graphpic.C:406
DynArray< Graph::Arc * > arcs
Definition graphpic.C:408
Container< T > arcs_map(GT &g, Op transformation, SA sa=SA())
Map the filtered arcs of a graph to a transformed type.
Definition tpl_graph.H:1507
Net build_grid_network(int rows, int cols, FlowType base_cap=10.0)
Build a grid network for stress testing.
void build(Tree_Node< Key > *troot, Convert &&convert, typename GT::Node *groot, Args &&... args)
DFSResult< typename Domain::Distance > dfs(Domain &domain, typename Domain::State &state, SearchPath< typename Domain::Move > &path, const typename Domain::Distance g, const typename Domain::Distance threshold, const size_t depth, IDAStarResult< Solution, typename Domain::Distance > &result, OnSolution &on_solution)
Core recursive DFS used by IDA* for a single threshold pass.
Cost_Type cycle_cost(const Indexed_Graph< GT, Cost_Type > &ig, const Array< size_t > &arcs, const char *context)
Total cost of the arcs arcs (indices into ig.arcs).
Main namespace for Aleph-w library functions.
DynList< typename Net::Arc * > get_partial_arcs(const Net &net)
Get arcs with partial flow (0 < flow < cap).
Residual_Net< typenameNet::Flow_Type >::Node * build_residual_net(const Net &net, Residual_Net< typename Net::Flow_Type > &rnet, DynMapTree< void *, void * > &arcs)
Build a residual network from a flow network.
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
Container2< typename Container1::Item_Type > filter(Container1 &container, Operation &operation)
Filter elements that satisfy operation.
Net::Flow_Type dinic_maximum_flow(Net &net)
Compute maximum flow using Dinic's algorithm.
Itor2 copy(Itor1 sourceBeg, const Itor1 &sourceEnd, Itor2 destBeg)
Copy elements from one range to another.
Definition ahAlgo.H:584
Net::Flow_Type capacity_scaling_maximum_flow(Net &net)
Compute maximum flow using capacity scaling.
std::tuple< size_t, double > max_flow_min_cost_by_cycle_canceling(Net &net, double it_factor=0.4, size_t step=10)
Compute maximum flow at minimum cost using cycle canceling.
void create_residual_arc(const Net &net, PP_Res_Net< Net > &rnet, typename Net::Arc *a)
Create residual arcs for a in the residual network.
Definition tpl_net.H:2152
and
Check uniqueness with explicit hash + equality functors.
size_t max_flow_min_cost_by_network_simplex(Net &net)
Compute maximum flow at minimum cost using Network Simplex.
bool check_residual_net(const Res_Net &net)
Verify residual network consistency.
Feasible_Tree< Net > build_feasible_spanning_tree(const Net &net)
Build feasible spanning tree classification.
long long max_flow(const Spec &s, int src, int snk)
The maximum flow from src to snk, by Edmonds-Karp on the matrix of the capacities w (loops carry noth...
Filtered iterator on all the arcs of a graph.
Definition tpl_graph.H:1200
Functor wrapper for edmonds_karp_maximum_flow().
Definition tpl_net.H:2347
Functor wrapper for ford_fulkerson_maximum_flow().
Definition tpl_net.H:2320
Arc information for multi-commodity flow.
Flow_Type cost(size_t k) const
Get cost for commodity k.
Flow_Type flow(size_t k) const
Get flow for commodity k.
Functor wrapper for maximum flow minimum cost algorithm.
Functor wrapper for Network Simplex algorithm.
Arc type for maximum flow minimum cost networks.
Definition tpl_netcost.H:96
Capacitated flow network with costs associated to arcs.
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
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
Flow_Type flow_value() const
Return the total flow value of the network: the flow out of its sources, which a valid flow also take...
Definition tpl_net.H:1139
NodeT Node
Node type.
Definition tpl_net.H:325
Cost distance functor for Bellman-Ford on residual networks.
static void set_zero(typename Net::Arc *a) noexcept
Reset arc to zero state.
Arc filter for residual networks.
Node information for Network Simplex algorithm.
void * parent
Parent node in the spanning tree (nullptr for root).
bool arc_from_parent
True if parent_arc is oriented from parent towards this node.
long depth
Depth in the spanning tree (root has depth 0).
long mark
Mark used for LCA computation.
void * parent_arc
Arc connecting this node to its parent.
Ftype potential
Node potential (dual variable pi).
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
static int * k
Advanced maximum flow algorithms.
void verify_flow_conservation(const Net &net)
Maximum flow minimum cost network algorithms.