Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
tpl_mincost_test.cc
Go to the documentation of this file.
1/* Tests for tpl_mincost.H - Advanced minimum cost flow algorithms
2 *
3 * Tests cover:
4 * - Successive Shortest Paths (SSP) algorithm
5 * - Cost Scaling algorithm
6 * - Assignment problem solver
7 * - Transportation problem solver
8 */
9
10#include <array>
11#include <string>
12#include <limits>
13#include <utility>
14#include <vector>
15
16#include <gtest/gtest.h>
17#include <tpl_mincost.H>
18#include <tpl_netcost.H>
19
20using namespace Aleph;
21
22namespace
23{
24 // Network type for tests
26 using Node = TestNet::Node;
27 using Arc = TestNet::Arc;
28
29 // Helper to compute total outgoing flow from source
30 double get_max_flow(const TestNet& net)
31 {
32 double flow = 0;
33 auto source = net.get_source();
34 for (Out_Iterator<TestNet> it(source); it.has_curr(); it.next_ne())
35 flow += it.get_curr()->flow;
36 return flow;
37 }
38
39 // Build a simple path network: s -> a -> t
40 TestNet build_simple_path_network()
41 {
42 TestNet net;
43 auto s = net.insert_node();
44 auto a = net.insert_node();
45 auto t = net.insert_node();
46
47 net.insert_arc(s, a, 10.0, 2.0); // cap=10, cost=2
48 net.insert_arc(a, t, 10.0, 3.0); // cap=10, cost=3
49
50 return net;
51 }
52
53 // Build diamond network with two paths
54 TestNet build_diamond_network()
55 {
56 TestNet net;
57 auto s = net.insert_node();
58 auto a = net.insert_node();
59 auto b = net.insert_node();
60 auto t = net.insert_node();
61
62 // Two paths: s->a->t (expensive) and s->b->t (cheap)
63 net.insert_arc(s, a, 5.0, 10.0); // cap=5, cost=10
64 net.insert_arc(s, b, 5.0, 1.0); // cap=5, cost=1
65 net.insert_arc(a, t, 5.0, 10.0); // cap=5, cost=10
66 net.insert_arc(b, t, 5.0, 1.0); // cap=5, cost=1
67
68 return net;
69 }
70
71 // Build network with cross-connection
72 TestNet build_cross_network()
73 {
74 TestNet net;
75 auto s = net.insert_node();
76 auto a = net.insert_node();
77 auto b = net.insert_node();
78 auto t = net.insert_node();
79
80 net.insert_arc(s, a, 10.0, 5.0); // s->a: cap=10, cost=5
81 net.insert_arc(s, b, 10.0, 2.0); // s->b: cap=10, cost=2
82 net.insert_arc(a, b, 5.0, 0.0); // a->b: cap=5, cost=0 (transfer)
83 net.insert_arc(a, t, 10.0, 3.0); // a->t: cap=10, cost=3
84 net.insert_arc(b, t, 10.0, 1.0); // b->t: cap=10, cost=1
85
86 return net;
87 }
88
89 // Build network with multiple parallel paths
90 TestNet build_parallel_network()
91 {
92 TestNet net;
93 auto s = net.insert_node();
94 auto t = net.insert_node();
95
96 // Three parallel arcs with different costs
97 net.insert_arc(s, t, 5.0, 1.0); // cheap, limited
98 net.insert_arc(s, t, 3.0, 5.0); // medium
99 net.insert_arc(s, t, 2.0, 10.0); // expensive
100
101 return net;
102 }
103}
104
105
106//==============================================================================
107// Successive Shortest Paths (SSP) Tests
108//==============================================================================
109
110TEST(SSPTest, SimplePath)
111{
112 auto net = build_simple_path_network();
113
114 auto [flow, cost] = successive_shortest_paths(net);
115
116 // Max flow = 10, cost = 10*(2+3) = 50
117 EXPECT_DOUBLE_EQ(flow, 10.0);
118 EXPECT_DOUBLE_EQ(cost, 50.0);
119 EXPECT_TRUE(net.check_network());
120}
121
122TEST(SSPTest, DiamondNetwork)
123{
124 auto net = build_diamond_network();
125
126 auto [flow, cost] = successive_shortest_paths(net);
127
128 // Max flow = 10 (5 via each path)
129 // SSP should prefer cheap path: s->b->t costs 1+1=2 per unit
130 // Then use expensive path: s->a->t costs 10+10=20 per unit
131 // Cost = 5*2 + 5*20 = 10 + 100 = 110
132 EXPECT_DOUBLE_EQ(flow, 10.0);
133 EXPECT_DOUBLE_EQ(cost, 110.0);
134 EXPECT_TRUE(net.check_network());
135}
136
137TEST(SSPTest, CrossNetwork)
138{
139 auto net = build_cross_network();
140
141 auto [flow, cost] = successive_shortest_paths(net);
142
143 // Should find path that uses cheap arcs
144 EXPECT_GT(flow, 0.0);
145 EXPECT_GT(cost, 0.0);
146 EXPECT_TRUE(net.check_network());
147}
148
149TEST(SSPTest, ParallelPaths)
150{
151 auto net = build_parallel_network();
152
153 auto [flow, cost] = successive_shortest_paths(net);
154
155 // Max flow = 5 + 3 + 2 = 10
156 // SSP uses cheap arc first (5 units @ cost 1 = 5)
157 // Then medium arc (3 units @ cost 5 = 15)
158 // Then expensive arc (2 units @ cost 10 = 20)
159 // Total cost = 5 + 15 + 20 = 40
160 EXPECT_DOUBLE_EQ(flow, 10.0);
161 EXPECT_DOUBLE_EQ(cost, 40.0);
162 EXPECT_TRUE(net.check_network());
163}
164
165TEST(SSPTest, LargeCosts)
166{
167 TestNet net;
168 auto s = net.insert_node();
169 auto a = net.insert_node();
170 auto t = net.insert_node();
171
172 net.insert_arc(s, a, 5.0, 1000.0);
173 net.insert_arc(a, t, 5.0, 2000.0);
174
175 auto [flow, cost] = successive_shortest_paths(net);
176
177 EXPECT_DOUBLE_EQ(flow, 5.0);
178 EXPECT_DOUBLE_EQ(cost, 15000.0); // 5 * (1000 + 2000)
179}
180
181TEST(SSPTest, SingleArc)
182{
183 TestNet net;
184 auto s = net.insert_node();
185 auto t = net.insert_node();
186 net.insert_arc(s, t, 15.0, 3.0);
187
188 auto [flow, cost] = successive_shortest_paths(net);
189
190 EXPECT_DOUBLE_EQ(flow, 15.0);
191 EXPECT_DOUBLE_EQ(cost, 45.0); // 15 * 3
192}
193
194TEST(SSPTest, ZeroCapacity)
195{
196 TestNet net;
197 auto s = net.insert_node();
198 auto t = net.insert_node();
199 net.insert_arc(s, t, 0.0, 5.0); // Zero capacity
200
201 auto [flow, cost] = successive_shortest_paths(net);
202
203 EXPECT_DOUBLE_EQ(flow, 0.0);
204 EXPECT_DOUBLE_EQ(cost, 0.0);
205}
206
207TEST(SSPTest, FunctorInterface)
208{
209 auto net = build_simple_path_network();
210
212 auto [flow, cost] = ssp(net);
213
214 EXPECT_DOUBLE_EQ(flow, 10.0);
215 EXPECT_DOUBLE_EQ(cost, 50.0);
216}
217
218TEST(SSPTest, CompareWithCycleCanceling)
219{
220 // Build same network twice and compare results
221 auto net_ssp = build_diamond_network();
222 auto net_cc = build_diamond_network();
223
224 auto [flow_ssp, cost_ssp] = successive_shortest_paths(net_ssp);
225 auto [cycles, factor] = max_flow_min_cost_by_cycle_canceling(net_cc);
226 (void)cycles;
227 (void)factor;
228
229 double flow_cc = get_max_flow(net_cc);
230 double cost_cc = net_cc.flow_cost();
231
232 // Both should find the same max flow
233 EXPECT_DOUBLE_EQ(flow_ssp, flow_cc);
234
235 // Costs should be equal (both optimal)
236 EXPECT_NEAR(cost_ssp, cost_cc, 1e-6);
237}
238
239
240//==============================================================================
241// Cost Scaling Tests
242//
243// NOTE: Cost Scaling algorithm is mentioned in the documentation but not yet
244// implemented in tpl_mincost.H. These tests are placeholders for when it gets
245// implemented. For now, we test SSP extensively and compare with Cycle Canceling.
246//==============================================================================
247
248// TODO: Uncomment these tests when cost_scaling_min_cost_flow is implemented
249/*
250TEST(CostScalingTest, SimplePath)
251{
252 auto net = build_simple_path_network();
253
254 auto [flow, cost] = cost_scaling_min_cost_flow(net);
255
256 EXPECT_DOUBLE_EQ(flow, 10.0);
257 EXPECT_DOUBLE_EQ(cost, 50.0);
258 EXPECT_TRUE(net.check_network());
259}
260
261TEST(CostScalingTest, DiamondNetwork)
262{
263 auto net = build_diamond_network();
264
265 auto [flow, cost] = cost_scaling_min_cost_flow(net);
266
267 EXPECT_DOUBLE_EQ(flow, 10.0);
268 EXPECT_DOUBLE_EQ(cost, 110.0);
269 EXPECT_TRUE(net.check_network());
270}
271*/
272
273
274//==============================================================================
275// Algorithm Comparison Tests
276//==============================================================================
277
278TEST(AlgorithmComparisonTest, SSP_vs_CycleCanceling_Diamond)
279{
280 auto net1 = build_diamond_network();
281 auto net2 = build_diamond_network();
282
283 auto [flow_ssp, cost_ssp] = successive_shortest_paths(net1);
285
286 double flow_cc = get_max_flow(net2);
287 double cost_cc = net2.flow_cost();
288
289 // Both should find same max flow
290 EXPECT_DOUBLE_EQ(flow_ssp, flow_cc);
291
292 // Both should find same min cost
293 EXPECT_NEAR(cost_ssp, cost_cc, 1e-6);
294}
295
296TEST(AlgorithmComparisonTest, SSP_vs_CycleCanceling_CrossNetwork)
297{
298 auto net1 = build_cross_network();
299 auto net2 = build_cross_network();
300
301 auto [flow_ssp, cost_ssp] = successive_shortest_paths(net1);
303
304 double flow_cc = get_max_flow(net2);
305 double cost_cc = net2.flow_cost();
306
307 EXPECT_DOUBLE_EQ(flow_ssp, flow_cc);
308 EXPECT_NEAR(cost_ssp, cost_cc, 1e-6);
309}
310
311
312//==============================================================================
313// Performance Comparison Tests
314//==============================================================================
315
316TEST(PerformanceTest, SSP_vs_CycleCanceling_OnLargerNetwork)
317{
318 // Build a grid-like network
319 const int SIZE = 5;
320
321 auto build_grid = []() {
322 TestNet net;
323 std::vector<std::vector<Node*>> nodes(SIZE, std::vector<Node*>(SIZE));
324
325 for (int i = 0; i < SIZE; ++i)
326 for (int j = 0; j < SIZE; ++j)
327 nodes[i][j] = net.insert_node();
328
329 // Add horizontal arcs
330 for (int i = 0; i < SIZE; ++i)
331 for (int j = 0; j < SIZE - 1; ++j)
332 net.insert_arc(nodes[i][j], nodes[i][j+1],
333 10.0 + (i+j) % 5, // capacity
334 1.0 + (i*j) % 3); // cost
335
336 // Add vertical arcs
337 for (int i = 0; i < SIZE - 1; ++i)
338 for (int j = 0; j < SIZE; ++j)
339 net.insert_arc(nodes[i][j], nodes[i+1][j],
340 10.0 + (i+j+1) % 5,
341 1.0 + ((i+1)*j) % 3);
342
343 return net;
344 };
345
346 auto net_ssp = build_grid();
347 auto net_cc = build_grid();
348
349 auto [flow_ssp, cost_ssp] = successive_shortest_paths(net_ssp);
351
352 double flow_cc = get_max_flow(net_cc);
353 double cost_cc = net_cc.flow_cost();
354
355 // Both algorithms should agree
356 EXPECT_DOUBLE_EQ(flow_ssp, flow_cc);
357 EXPECT_NEAR(cost_ssp, cost_cc, 1e-6);
358
359 std::cout << "\nGrid " << SIZE << "x" << SIZE << " results:\n";
360 std::cout << " SSP: Flow=" << flow_ssp << ", Cost=" << cost_ssp << "\n";
361 std::cout << " CC: Flow=" << flow_cc << ", Cost=" << cost_cc << "\n";
362}
363
364
365//==============================================================================
366// Assignment Problem Tests
367//==============================================================================
368
369TEST(AssignmentTest, Basic3x3)
370{
371 std::vector<std::vector<double>> costs = {
372 {10, 5, 13},
373 {3, 9, 18},
374 {10, 6, 12}
375 };
376
377 auto result = solve_assignment(costs);
378
379 EXPECT_TRUE(result.feasible);
380 EXPECT_EQ(result.assignments.size(), 3);
381 EXPECT_DOUBLE_EQ(result.total_cost, 20.0);
382}
383
384TEST(AssignmentTest, Single1x1)
385{
386 std::vector<std::vector<double>> costs = {{42}};
387
388 auto result = solve_assignment(costs);
389
390 EXPECT_TRUE(result.feasible);
391 EXPECT_EQ(result.assignments.size(), 1);
392 EXPECT_DOUBLE_EQ(result.total_cost, 42.0);
393}
394
395TEST(AssignmentTest, Empty)
396{
397 std::vector<std::vector<double>> costs;
398
399 auto result = solve_assignment(costs);
400
401 EXPECT_TRUE(result.feasible);
402 EXPECT_EQ(result.assignments.size(), 0);
403}
404
405TEST(AssignmentTest, Larger5x5)
406{
407 std::vector<std::vector<double>> costs = {
408 {9, 2, 7, 8, 3},
409 {6, 4, 3, 7, 5},
410 {5, 8, 1, 8, 6},
411 {7, 6, 9, 4, 5},
412 {3, 7, 2, 8, 2}
413 };
414
415 auto result = solve_assignment(costs);
416
417 EXPECT_TRUE(result.feasible);
418 EXPECT_EQ(result.assignments.size(), 5);
419 EXPECT_GT(result.total_cost, 0.0);
420}
421
422
423//==============================================================================
424// Transportation Problem Tests
425//==============================================================================
426
427TEST(TransportationTest, Balanced)
428{
429 std::vector<double> supplies = {100, 100};
430 std::vector<double> demands = {100, 100};
431 std::vector<std::vector<double>> costs = {
432 {1, 2},
433 {3, 4}
434 };
435
436 auto result = solve_transportation(supplies, demands, costs);
437
438 EXPECT_TRUE(result.feasible);
439 EXPECT_EQ(result.shipments.size(), 2);
440}
441
442TEST(TransportationTest, Imbalanced)
443{
444 std::vector<double> supplies = {100, 100};
445 std::vector<double> demands = {50, 50};
446
447 std::vector<std::vector<double>> costs = {
448 {1, 2},
449 {3, 4}
450 };
451
452 auto result = solve_transportation(supplies, demands, costs);
453
454 EXPECT_FALSE(result.feasible);
455}
456
457TEST(TransportationTest, Larger3x4)
458{
459 // 3 suppliers, 4 customers
460 std::vector<double> supplies = {50, 60, 40};
461 std::vector<double> demands = {30, 40, 50, 30};
462 std::vector<std::vector<double>> costs = {
463 {2, 3, 1, 4},
464 {3, 2, 4, 1},
465 {1, 4, 2, 3}
466 };
467
468 auto result = solve_transportation(supplies, demands, costs);
469
470 EXPECT_TRUE(result.feasible);
471 EXPECT_EQ(result.shipments.size(), 3);
472
473 // Verify shipments sum correctly
474 double total_shipped = 0;
475 for (size_t i = 0; i < result.shipments.size(); ++i)
476 for (size_t j = 0; j < result.shipments[i].size(); ++j)
477 total_shipped += result.shipments[i][j];
478
479 EXPECT_DOUBLE_EQ(total_shipped, 150.0); // Total supply/demand
480}
481
482// A transportation that is not square, either way: each row of the
483// shipments takes its supply, each column its demand, and the cost is that
484// of the shipments, the least one. The arcs of the network go by rows, so
485// that a mistake in their index would swap shipments
486TEST(TransportationTest, NotSquareKeepsRowsColumnsAndCost)
487{
488 const std::vector<double> supplies = {50, 60, 40};
489 const std::vector<double> demands = {30, 40, 50, 30};
490 const std::vector<std::vector<double>> costs = {{2, 3, 1, 4}, {3, 2, 4, 1}, {1, 4, 2, 3}};
491 std::vector<std::vector<double>> transposed(4, std::vector<double>(3));
492 for (size_t i = 0; i < 3; ++i)
493 for (size_t j = 0; j < 4; ++j)
494 transposed[j][i] = costs[i][j];
495
496 for (bool wide : {true, false})
497 {
498 const auto & sup = wide ? supplies : demands;
499 const auto & dem = wide ? demands : supplies;
500 const auto & cost = wide ? costs : transposed;
501 auto result = solve_transportation(sup, dem, cost);
502
503 ASSERT_TRUE(result.feasible) << (wide ? "3 x 4" : "4 x 3");
504 ASSERT_EQ(result.shipments.size(), sup.size());
505 std::vector<double> column(dem.size(), 0);
506 double total = 0;
507 for (size_t i = 0; i < sup.size(); ++i)
508 {
509 ASSERT_EQ(result.shipments[i].size(), dem.size());
510 double row = 0;
511 for (size_t j = 0; j < dem.size(); ++j)
512 {
513 row += result.shipments[i][j];
514 column[j] += result.shipments[i][j];
515 total += result.shipments[i][j] * cost[i][j];
516 }
517 EXPECT_DOUBLE_EQ(row, sup[i]) << "row " << i;
518 }
519 for (size_t j = 0; j < dem.size(); ++j)
520 EXPECT_DOUBLE_EQ(column[j], dem[j]) << "column " << j;
521 EXPECT_DOUBLE_EQ(result.total_cost, total);
522 EXPECT_DOUBLE_EQ(result.total_cost, 210); // the least, by brute force
523 }
524}
525
526
527// ============================================================================
528// Regression tests for validation and new behavior paths
529// ============================================================================
530
531// --- Negative-cycle detection -------------------------------------------
532
533// The negative-cycle path in ssp_init_potentials fires when Bellman-Ford's
534// extra (n-th) relaxation pass can still reduce some node's distance.
535// That requires a true directed cycle of the residual graph whose arc-costs
536// sum to a negative value, which the source reaches or not.
537//
538// Topology: s --0--> m1 --1--> m2
539// ^ |
540// | -3 |
541// +---------+ (cycle m1→m2→m1, total cost -2)
542// m1 --0--> t
543//
544// s is the unique source (in-degree 0), t is the unique sink (out-degree 0).
545// Bellman-Ford will keep decreasing d[m1] and d[m2] on every pass, and the
546// extra detection pass catches this.
547TEST(NegCycleTest, RejectsNegativeCycle)
548{
549 TestNet net;
550 auto s = net.insert_node();
551 auto m1 = net.insert_node();
552 auto m2 = net.insert_node();
553 auto t = net.insert_node();
554
555 net.insert_arc(s, m1, 10.0, 0.0); // s → m1, cost 0
556 net.insert_arc(m1, m2, 10.0, 1.0); // m1 → m2, cost 1
557 net.insert_arc(m2, m1, 10.0, -3.0); // m2 → m1, cost -3 → cycle cost -2
558 net.insert_arc(m1, t, 10.0, 0.0); // m1 → t, cost 0
559
560 // ssp_init_potentials detects the cycle and returns false;
561 // successive_shortest_paths must propagate that as domain_error.
562 EXPECT_THROW(successive_shortest_paths(net), std::domain_error);
563}
564
565// A network with only non-negative costs must NOT trigger the cycle detector.
566TEST(NegCycleTest, AcceptsNonNegativeCostNetwork)
567{
568 TestNet net;
569 auto s = net.insert_node();
570 auto m1 = net.insert_node();
571 auto t = net.insert_node();
572
573 net.insert_arc(s, m1, 10.0, 2.0);
574 net.insert_arc(m1, t, 10.0, 3.0);
575
576 // No negative cycle — must complete without throwing.
577 EXPECT_NO_THROW(successive_shortest_paths(net));
578}
579
580// Bellman-Ford went from the source, and did not see a negative cycle that
581// the source does not reach: the flow came back of cost 0, while the
582// cheapest maximum flow saturates the cycle, at cost -2
583TEST(NegCycleTest, RejectsANegativeCycleApartFromTheSource)
584{
585 TestNet net;
586 auto s = net.insert_node();
587 auto a = net.insert_node();
588 auto b = net.insert_node();
589 auto t = net.insert_node();
590 auto st = net.insert_arc(s, t, 1.0, 0.0);
591 auto ab = net.insert_arc(a, b, 1.0, -1.0);
592 net.insert_arc(b, a, 1.0, -1.0);
593
594 EXPECT_THROW(successive_shortest_paths(net), std::domain_error);
595 EXPECT_EQ(st->flow, 0.0);
596 EXPECT_EQ(ab->flow, 0.0);
597}
598
599// A source that is the sink, isolated, has no path to augment: the loop took
600// the empty one from it to itself, and did not end
601TEST(SSPTest, ASourceThatIsTheSinkEnds)
602{
603 TestNet net;
604 net.insert_node(); // the source and the sink
605 auto a = net.insert_node();
606 auto b = net.insert_node();
607 auto ab = net.insert_arc(a, b, 1.0, 1.0);
608 auto ba = net.insert_arc(b, a, 1.0, 2.0);
609
610 const auto [flow, cost] = successive_shortest_paths(net);
611 EXPECT_EQ(flow, 0.0);
612 EXPECT_EQ(cost, 0.0);
613
614 // With a circulation of cost 3, whose cancellation is cheaper, the
615 // residual graph has a negative cycle
616 ab->flow = ba->flow = 1.0;
617 EXPECT_THROW(successive_shortest_paths(net), std::domain_error);
618 EXPECT_EQ(ab->flow, 1.0);
619 EXPECT_EQ(ba->flow, 1.0);
620}
621
622// The networks of the cases of decimal costs: u, v, and the capacity and
623// the cost in tenths
624TestNet build_tenths_network(const std::vector<std::array<int, 4>> & spec, int n)
625{
626 TestNet net;
627 std::vector<Node *> nodes;
628 for (int i = 0; i < n; ++i)
629 nodes.push_back(net.insert_node());
630 for (const auto & a : spec)
631 net.insert_arc(nodes[size_t(a[0])], nodes[size_t(a[1])], a[2] / 10.0, a[3] / 10.0);
632 return net;
633}
634
635// With costs in tenths, not exact in binary, a reduced cost of zero came
636// out of the order of -1e-17, and Dijkstra took a distance down by an ulp
637// around a cycle forever: the first run did not end
638TEST(SSPTest, DecimalCostsEnd)
639{
640 // 3 is the source and 5 the sink
641 auto net = build_tenths_network({{2, 1, 17, 5}, {3, 5, 27, 9}, {1, 5, 2, 6}, {0, 2, 37, 9},
642 {2, 4, 23, 6}, {3, 2, 14, 0}, {0, 4, 26, 8}, {3, 0, 2, 6},
643 {4, 5, 37, 7}, {3, 5, 22, 6}}, 6);
644
645 const auto [flow, cost] = successive_shortest_paths(net);
646
647 EXPECT_NEAR(flow, 6.5, 1e-12);
648 EXPECT_NEAR(cost, 5.95, 1e-12); // the exact optimum
649 EXPECT_TRUE(net.check_network());
650}
651
652// The second run starts from the cheapest flow, where the two arcs 2->0 of
653// cost 0.4, one full and one not, make a cycle of cost zero, which the
654// rounding of Bellman-Ford made negative: the second run threw for it
655TEST(SSPTest, ASecondRunOfDecimalCostsFindsNoNegativeCycle)
656{
657 // 1 is the source and 0 the sink
658 auto net = build_tenths_network({{1, 2, 9, 8}, {2, 0, 34, 4}, {1, 2, 24, 0}, {1, 2, 37, 1},
659 {2, 0, 33, 4}}, 3);
660
661 const auto [flow, cost] = successive_shortest_paths(net);
662 EXPECT_NEAR(flow, 6.7, 1e-12);
663 EXPECT_NEAR(cost, 3.53, 1e-12); // the exact optimum
664
665 std::pair<double, double> again;
666 ASSERT_NO_THROW(again = successive_shortest_paths(net));
667 EXPECT_NEAR(again.first, flow, 1e-12);
668 EXPECT_NEAR(again.second, cost, 1e-12);
669}
670
671// Into 2 come 0.1 + 0.8, and out goes their rounded sum, 2.8e-17 less,
672// within the tolerance of check_node(); the network simplex, and the
673// maximum flow before it, returned it from 0->2, which then had residual
674// capacity: with the residual of 1->0, of cost -1, through 2 and 1, a
675// cycle of negative cost, for which successive_shortest_paths(), which
676// starts from the flow that the network has, threw. What a node keeps
677// within its tolerance stays
678TEST(SSPTest, RunsOnTheCheapestFlowOfTheNetworkSimplex)
679{
680 // 0 is the source and 3 the sink
681 auto net = build_tenths_network({{0, 1, 31, 10}, {0, 2, 1, 0}, {1, 2, 8, 0}, {2, 3, 29, 0}}, 4);
683 ASSERT_NEAR(net.flow_value(), 0.9, 1e-12);
684 ASSERT_NEAR(net.flow_cost(), 0.8, 1e-12);
685
686 std::pair<double, double> again;
687 ASSERT_NO_THROW(again = successive_shortest_paths(net));
688 EXPECT_NEAR(again.first, 0.9, 1e-12);
689 EXPECT_NEAR(again.second, 0.8, 1e-12);
690 EXPECT_TRUE(net.check_network());
691}
692
693// The second path, 0->2->3, takes what 2->3 has left, 3.4 - 0.7, and
694// 0.7 + (3.4 - 0.7) came out an ulp above 3.4: 2->3 carried
695// 3.4000000000000004 of 3.3999999999999999, out of its capacity, and the
696// network simplex refused the flow. The arc that bounds a path is filled
697// exactly, and the residues of rounding go back at the end
698TEST(SSPTest, DecimalCapacitiesStayWithinTheArcs)
699{
700 // 0 is the source and 3 the sink
701 auto net = build_tenths_network({{0, 1, 7, 2}, {1, 2, 8, 1}, {0, 2, 27, 8}, {2, 3, 34, 1}}, 4);
702
703 const auto [flow, cost] = successive_shortest_paths(net);
704
705 EXPECT_NEAR(flow, 3.4, 1e-12);
706 EXPECT_NEAR(cost, 2.71, 1e-12); // the exact optimum
707 for (Arc_Iterator<TestNet> it(net); it.has_curr(); it.next_ne())
708 {
709 EXPECT_GE(it.get_curr()->flow, 0);
710 EXPECT_LE(it.get_curr()->flow, it.get_curr()->cap);
711 }
712 EXPECT_TRUE(net.check_network());
713
714 ASSERT_NO_THROW(Network_Simplex<TestNet>(net).run());
715 EXPECT_NEAR(net.flow_value(), 3.4, 1e-12);
716 EXPECT_NEAR(net.flow_cost(), 2.71, 1e-12);
717}
718
719// From the flow through the dearer of two arcs from m to the sink, of costs
720// 1 and 1 - 1e-7, the residual network has a cycle of cost -1e-7, far above
721// the tolerance of the potentials with costs of 1, 4 n^2 epsilons: the
722// flow is not of least cost, and successive_shortest_paths() refuses it,
723// with the flows as they were
724TEST(SSPTest, RefusesACycleOfCost1e7)
725{
726 TestNet net;
727 auto s = net.insert_node(), m = net.insert_node(), t = net.insert_node();
728 Arc * sm = net.insert_arc(s, m, 1, 0);
729 Arc * dear = net.insert_arc(m, t, 1, 1);
730 net.insert_arc(m, t, 1, 1 - 1e-7);
731 sm->flow = dear->flow = 1;
732
733 EXPECT_THROW(successive_shortest_paths(net), std::domain_error);
734 EXPECT_EQ(sm->flow, 1);
735 EXPECT_EQ(dear->flow, 1);
736}
737
738// A path of arcs of infinite capacity from the source to the sink makes
739// the maximum flow infinite, which has no cost to minimize: SSP took that
740// path forever, as the residual of an arc of infinite capacity and flow,
741// inf - inf, is NaN. It throws, with the flows of the entry, also after
742// the path of the cheaper arc, which it takes first
743TEST(SSPTest, RefusesAnInfiniteMaximumFlow)
744{
745 const double inf = std::numeric_limits<double>::infinity();
746 TestNet net;
747 auto s = net.insert_node(), a = net.insert_node(), t = net.insert_node();
748 Arc * cheap = net.insert_arc(s, t, 2.5, 1);
749 Arc * sa = net.insert_arc(s, a, inf, 2);
750 Arc * at = net.insert_arc(a, t, inf, 2);
751 cheap->flow = 1;
752
753 try
754 {
756 ADD_FAILURE() << "successive_shortest_paths() did not throw";
757 }
758 catch (const std::domain_error & e)
759 {
760 EXPECT_NE(std::string(e.what()).find("infinite"), std::string::npos) << e.what();
761 }
762 EXPECT_EQ(cheap->flow, 1);
763 EXPECT_EQ(sa->flow, 0);
764 EXPECT_EQ(at->flow, 0);
765}
766
767// With the arcs that bound the paths filled exactly, and the flows that a
768// path takes next to zero taken to zero, a path took a residue of rounding,
769// of 2.2e-16, and a later one took the flow out of its node to zero: the
770// node kept it, far beyond its tolerance, as it sent nothing. The residues
771// of the paths go back at the end, as those of the maximum flows
772TEST(SSPTest, ReturnsTheResiduesOfItsPaths)
773{
774 // u, v and k for the capacity and the cost, k * 0.1; 0 is the source and
775 // 21 the sink
776 const std::vector<std::array<int, 4>> spec = {
777 {0, 1, 29, 32}, {1, 2, 37, 32}, {3, 4, 34, 5}, {5, 6, 26, 11}, {1, 7, 28, 48},
778 {8, 9, 39, 15}, {10, 11, 39, 44}, {0, 12, 33, 94}, {0, 13, 6, 18}, {9, 14, 20, 6},
779 {1, 15, 34, 14}, {15, 16, 35, 87}, {17, 18, 31, 49}, {12, 6, 8, 77}, {6, 14, 12, 31},
780 {5, 14, 33, 76}, {14, 16, 18, 17}, {16, 19, 27, 21}, {4, 20, 37, 93}, {20, 21, 23, 89},
781 {19, 21, 39, 34}, {1, 8, 12, 24}, {19, 22, 21, 59}, {23, 14, 9, 2}, {3, 7, 20, 5},
782 {13, 9, 25, 51}, {22, 24, 38, 9}, {11, 15, 39, 27}, {24, 21, 24, 95}, {0, 5, 28, 99},
783 {7, 24, 35, 14}, {16, 25, 20, 86}, {25, 17, 1, 14}, {5, 13, 14, 9}, {26, 13, 32, 76},
784 {2, 27, 15, 80}, {28, 10, 12, 37}, {27, 9, 4, 15}, {20, 26, 21, 50}, {13, 28, 7, 91},
785 {13, 3, 20, 40}, {18, 23, 10, 16}};
786 TestNet net;
787 std::vector<Node *> nodes;
788 for (int i = 0; i < 29; ++i)
789 nodes.push_back(net.insert_node());
790 for (const auto & a : spec)
791 net.insert_arc(nodes[size_t(a[0])], nodes[size_t(a[1])], a[2] * 0.1, a[3] * 0.1);
792
793 const auto [flow, cost] = successive_shortest_paths(net);
794
795 EXPECT_NEAR(flow, 6.7, 1e-12);
796 EXPECT_NEAR(cost, 156.22, 1e-9); // the exact optimum
797 EXPECT_TRUE(net.check_network());
798}
799
800// --- Unreachable-node handling (indirect) --------------------------------
801
802// ssp_init_potentials starts the potential of every node at 0, from a
803// virtual node joined to all of them, so that the nodes that the source does
804// not reach have one too: zero-demand nodes in the transshipment wrapper are
805// not connected to the super-source/super-sink.
806// We verify indirectly: a transshipment instance where two nodes carry zero
807// demand must still solve correctly with total_flow == total non-zero supply.
808TEST(SSPTest, ZeroDemandNodesHandledGracefully)
809{
810 // Two supply nodes and two demand nodes balanced at 5 each.
811 // Internally solve_transportation builds a super-source/super-sink network;
812 // ssp_init_potentials must handle any nodes unreachable from super-source
813 // (those with zero demand/supply) without crashing or returning wrong results.
814 std::vector<double> supplies = {5.0, 5.0};
815 std::vector<double> demands = {5.0, 5.0};
816 std::vector<std::vector<double>> costs = {{1.0, 2.0}, {3.0, 1.0}};
817
818 auto result = solve_transportation(supplies, demands, costs);
819 EXPECT_TRUE(result.feasible);
820 EXPECT_DOUBLE_EQ(result.total_cost, 10.0); // optimal: (0,0)=5 + (1,1)=5 → 5+5=10
821}
822
823// --- solve_assignment validation ----------------------------------------
824
825TEST(AssignmentValidationTest, NonSquareMatrixThrows)
826{
827 std::vector<std::vector<double>> bad = {{1, 2, 3}, {4, 5}};
828 EXPECT_THROW(solve_assignment(bad), std::invalid_argument);
829}
830
831TEST(AssignmentValidationTest, EmptyMatrixReturnsFeasible)
832{
833 std::vector<std::vector<double>> empty;
834 auto result = solve_assignment(empty);
835 EXPECT_TRUE(result.feasible);
836}
837
838// --- solve_transportation validation ------------------------------------
839
840TEST(TransportationValidationTest, MismatchedRowsThrows)
841{
842 std::vector<double> supplies = {10, 20};
843 std::vector<double> demands = {30};
844 // costs has 1 row but 2 supply points
845 std::vector<std::vector<double>> costs = {{5}};
846 EXPECT_THROW(solve_transportation(supplies, demands, costs), std::invalid_argument);
847}
848
849TEST(TransportationValidationTest, MismatchedColumnsThrows)
850{
851 std::vector<double> supplies = {10};
852 std::vector<double> demands = {5, 5};
853 // costs[0] has 1 column but 2 demand points
854 std::vector<std::vector<double>> costs = {{3}};
855 EXPECT_THROW(solve_transportation(supplies, demands, costs), std::invalid_argument);
856}
857
858TEST(TransportationValidationTest, NegativeSupplyThrows)
859{
860 std::vector<double> supplies = {-5, 10};
861 std::vector<double> demands = {5};
862 std::vector<std::vector<double>> costs = {{1}, {2}};
863 EXPECT_THROW(solve_transportation(supplies, demands, costs), std::invalid_argument);
864}
865
866TEST(TransportationValidationTest, NegativeDemandThrows)
867{
868 std::vector<double> supplies = {10};
869 std::vector<double> demands = {-5};
870 std::vector<std::vector<double>> costs = {{3}};
871 EXPECT_THROW(solve_transportation(supplies, demands, costs), std::invalid_argument);
872}
873
874// --- Empty-side feasibility ---------------------------------------------
875
876TEST(TransportationValidationTest, EmptySuppliesNonemptyDemandsInfeasible)
877{
878 // m=0, n=1, total_supply=0 != total_demand=5 → infeasible
879 std::vector<double> supplies;
880 std::vector<double> demands = {5};
881 std::vector<std::vector<double>> costs;
882 auto result = solve_transportation(supplies, demands, costs);
883 EXPECT_FALSE(result.feasible);
884}
885
886TEST(TransportationValidationTest, EmptySuppliesZeroDemandFeasible)
887{
888 // m=0, n=1, total_supply=0 == total_demand=0 → feasible
889 std::vector<double> supplies;
890 std::vector<double> demands = {0};
891 std::vector<std::vector<double>> costs;
892 auto result = solve_transportation(supplies, demands, costs);
893 EXPECT_TRUE(result.feasible);
894}
895
896TEST(TransportationValidationTest, BothEmptyFeasible)
897{
898 std::vector<double> supplies;
899 std::vector<double> demands;
900 std::vector<std::vector<double>> costs;
901 auto result = solve_transportation(supplies, demands, costs);
902 EXPECT_TRUE(result.feasible);
903}
904
905int main(int argc, char** argv)
906{
907 ::testing::InitGoogleTest(&argc, argv);
908 return RUN_ALL_TESTS();
909}
910// satisfy CI policy
WeightedDigraph::Node Node
WeightedDigraph::Arc Arc
int main()
size_t row
Definition ca-c-api.h:115
bool has_curr() const noexcept
Return true the iterator has an current arc.
Definition tpl_graph.H:1822
void next_ne() noexcept(shows_ne)
Advances the iterator to the next filtered element, as next() does.
Network Simplex algorithm for minimum cost flow.
Filtered iterator for outcoming arcs of a node.
Definition tpl_graph.H:1942
#define TEST(name)
DynArray< Graph::Node * > nodes
Definition graphpic.C:406
Main namespace for Aleph-w library functions.
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.
size_t max_flow_min_cost_by_network_simplex(Net &net)
Compute maximum flow at minimum cost using Network Simplex.
TransportationResult< Cost_Type > solve_transportation(const std::vector< Cost_Type > &supplies, const std::vector< Cost_Type > &demands, const std::vector< std::vector< Cost_Type > > &costs)
Solve the transportation problem using min-cost flow.
std::pair< typename Net::Flow_Type, typename Net::Flow_Type > successive_shortest_paths(Net &net)
Compute minimum cost maximum flow using Successive Shortest Paths.
AssignmentResult< Cost_Type > solve_assignment(const std::vector< std::vector< Cost_Type > > &costs)
Solve the assignment problem using min-cost flow.
Filtered iterator on all the arcs of a graph.
Definition tpl_graph.H:1200
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
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
Functor wrapper for SSP algorithm.
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
Advanced minimum cost flow algorithms.
TestNet build_tenths_network(const std::vector< std::array< int, 4 > > &spec, int n)
Maximum flow minimum cost network algorithms.