38#include <gtest/gtest.h>
65class NetCostArcTest :
public ::testing::Test
71TEST_F(NetCostArcTest, DefaultConstructor)
74 EXPECT_EQ(arc.
cost, 0.0);
75 EXPECT_EQ(arc.
flow, 0.0);
76 EXPECT_EQ(arc.cap, 0.0);
79TEST_F(NetCostArcTest, CopyConstructor)
87 EXPECT_EQ(arc2.cost, 5.5);
88 EXPECT_EQ(arc2.flow, 2.0);
89 EXPECT_EQ(arc2.cap, 10.0);
92TEST_F(NetCostArcTest, CopyAssignment)
101 EXPECT_EQ(arc2.
cost, 3.3);
102 EXPECT_EQ(arc2.
flow, 1.0);
103 EXPECT_EQ(arc2.cap, 5.0);
106TEST_F(NetCostArcTest, SelfAssignment)
114 EXPECT_EQ(arc.
cost, 7.7);
115 EXPECT_EQ(arc.
flow, 3.0);
116 EXPECT_EQ(arc.cap, 8.0);
119TEST_F(NetCostArcTest, FlowCost)
124 EXPECT_DOUBLE_EQ(arc.flow_cost(), 10.0);
127TEST_F(NetCostArcTest, FlowCostZeroFlow)
132 EXPECT_DOUBLE_EQ(arc.flow_cost(), 0.0);
135TEST_F(NetCostArcTest, FlowCostZeroCost)
140 EXPECT_DOUBLE_EQ(arc.flow_cost(), 0.0);
143TEST_F(NetCostArcTest, FlowCostNegativeCost)
148 EXPECT_DOUBLE_EQ(arc.flow_cost(), -15.0);
156class NetCostGraphTest :
public ::testing::Test
162TEST_F(NetCostGraphTest, DefaultConstructor)
164 EXPECT_EQ(net.vsize(), 0);
165 EXPECT_EQ(net.esize(), 0);
168TEST_F(NetCostGraphTest, InsertNode)
170 auto n = net.insert_node();
171 EXPECT_NE(n,
nullptr);
172 EXPECT_EQ(net.vsize(), 1);
175TEST_F(NetCostGraphTest, InsertArcWithCost)
177 auto s = net.insert_node();
178 auto t = net.insert_node();
179 auto arc = net.insert_arc(s, t, 10.0, 2.5);
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);
187TEST_F(NetCostGraphTest, GetCostModifiable)
189 auto s = net.insert_node();
190 auto t = net.insert_node();
191 auto arc = net.insert_arc(s, t, 10.0, 5.0);
193 net.get_cost(arc) = 7.5;
194 EXPECT_EQ(arc->cost, 7.5);
197TEST_F(NetCostGraphTest, GetCostConst)
199 auto s = net.insert_node();
200 auto t = net.insert_node();
201 auto arc = net.insert_arc(s, t, 10.0, 3.0);
203 const Net& const_net = net;
204 EXPECT_EQ(const_net.get_cost(arc), 3.0);
207TEST_F(NetCostGraphTest, ArcFlowCost)
209 auto s = net.insert_node();
210 auto t = net.insert_node();
211 auto arc = net.insert_arc(s, t, 10.0, 2.0);
214 EXPECT_DOUBLE_EQ(net.arc_flow_cost(arc), 10.0);
217TEST_F(NetCostGraphTest, TotalFlowCost)
219 auto s = net.insert_node();
220 auto a = net.insert_node();
221 auto t = net.insert_node();
223 auto arc1 = net.insert_arc(s, a, 10.0, 2.0);
224 auto arc2 = net.insert_arc(a, t, 10.0, 3.0);
230 EXPECT_DOUBLE_EQ(net.flow_cost(), 22.0);
233TEST_F(NetCostGraphTest, TotalFlowCostEmpty)
235 EXPECT_DOUBLE_EQ(net.flow_cost(), 0.0);
243class NetCostGraphCopyTest :
public ::testing::Test
250 void SetUp()
override
264TEST_F(NetCostGraphCopyTest, CopyConstructor)
270 EXPECT_DOUBLE_EQ(
copy.flow_cost(), net.flow_cost());
273TEST_F(NetCostGraphCopyTest, CopyConstructorPreservesCosts)
278 EXPECT_DOUBLE_EQ(
copy.flow_cost(), net.flow_cost());
281TEST_F(NetCostGraphCopyTest, CopyAssignment)
288 EXPECT_DOUBLE_EQ(
copy.flow_cost(), net.flow_cost());
291TEST_F(NetCostGraphCopyTest, SelfCopyAssignment)
293 auto original_cost = net.flow_cost();
295 EXPECT_DOUBLE_EQ(net.flow_cost(), original_cost);
303class ResidualNetTest :
public ::testing::Test
309TEST_F(ResidualNetTest, CreateResidualArc)
313 auto t = rnet.insert_node();
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);
324 EXPECT_NE(arc->img,
nullptr);
325 EXPECT_EQ(arc->img->cap, 10.0);
326 EXPECT_EQ(arc->img->flow, 7.0);
327 EXPECT_EQ(arc->img->cost, -2.0);
328 EXPECT_TRUE(arc->img->is_residual);
331 EXPECT_EQ(arc->img->img, arc);
334TEST_F(ResidualNetTest, CheckResidualNetConsistency)
337 auto s = rnet.insert_node();
338 auto t = rnet.insert_node();
351class FilterTest :
public ::testing::Test
357TEST_F(FilterTest, ResFiltPositiveResidual)
368TEST_F(FilterTest, ResFiltZeroResidual)
376 EXPECT_FALSE(
filter(arc));
379TEST_F(FilterTest, RcostReturnsArcCost)
386 EXPECT_DOUBLE_EQ(rcost(arc), 7.5);
389TEST_F(FilterTest, RcostSetZero)
398 EXPECT_EQ(arc->cap, std::numeric_limits<double>::max());
399 EXPECT_EQ(arc->flow, 0.0);
400 EXPECT_EQ(arc->cost, 0.0);
408class FlowParsTest :
public ::testing::Test
414 void SetUp()
override
423TEST_F(FlowParsTest, OutParsMultipleArcs)
430 auto [cap, flow, cost] = net.out_pars(s);
432 EXPECT_DOUBLE_EQ(cap, 15.0);
433 EXPECT_DOUBLE_EQ(flow, 6.0);
434 EXPECT_DOUBLE_EQ(cost, 5.0);
437TEST_F(FlowParsTest, InParsMultipleArcs)
444 auto [cap, flow, cost] = net.in_pars(t);
446 EXPECT_DOUBLE_EQ(cap, 15.0);
447 EXPECT_DOUBLE_EQ(flow, 6.0);
448 EXPECT_DOUBLE_EQ(cost, 5.0);
451TEST_F(FlowParsTest, OutParsNoArcs)
453 auto [cap, flow, cost] = net.out_pars(s);
455 EXPECT_DOUBLE_EQ(cap, 0.0);
456 EXPECT_DOUBLE_EQ(flow, 0.0);
457 EXPECT_DOUBLE_EQ(cost, 0.0);
472 EXPECT_EQ(net.flow_cost(), 0.0);
480 EXPECT_EQ(net.
vsize(), 1);
481 EXPECT_EQ(net.
esize(), 0);
482 EXPECT_EQ(net.flow_cost(), 0.0);
494 EXPECT_EQ(net.flow_cost(), 0.0);
503 double large_cost = 1e10;
504 auto arc = net.
insert_arc(s, t, 100.0, large_cost);
507 EXPECT_DOUBLE_EQ(net.flow_cost(), 5.0 * large_cost);
521 EXPECT_EQ(net.flow_cost(), 12);
529class FeasibleTreeTest :
public ::testing::Test
535TEST_F(FeasibleTreeTest, ClassifiesArcsCorrectly)
540 auto empty_arc = net.
insert_arc(s, t, 10.0, 1.0);
541 empty_arc->flow = 0.0;
543 auto full_arc = net.
insert_arc(s, t, 5.0, 2.0);
544 full_arc->flow = 5.0;
546 auto partial_arc = net.
insert_arc(s, t, 8.0, 3.0);
547 partial_arc->flow = 3.0;
551 EXPECT_EQ(empty.size(), 1);
552 EXPECT_EQ(full.size(), 1);
553 EXPECT_EQ(partial.size(), 1);
556TEST_F(FeasibleTreeTest, GetPartialArcs)
572 EXPECT_EQ(partials.size(), 1);
580class MaxFlowMinCostIntegrationTest :
public ::testing::Test
629 Net build_textbook_network()
656 Net build_single_path_network()
677 Net build_parallel_paths_network()
701 Net build_diamond_network()
718 double get_max_flow(
const Net& net)
723 flow += it.get_curr()->flow;
733 for (
auto p : net.
nodes())
735 if (p == source || p == sink)
738 double in_flow = 0, out_flow = 0;
741 in_flow += it.get_curr()->flow;
744 out_flow += it.get_curr()->flow;
746 if (std::abs(in_flow - out_flow) > 1e-9)
753 bool verify_capacity_constraints(
const Net& net)
755 for (
auto a : net.
arcs())
757 if (a->flow < 0 || a->flow > a->cap)
764TEST_F(MaxFlowMinCostIntegrationTest, SinglePathNetwork)
766 auto net = build_single_path_network();
770 double max_flow = get_max_flow(net);
771 double total_cost = net.flow_cost();
773 EXPECT_DOUBLE_EQ(max_flow, 5.0);
774 EXPECT_DOUBLE_EQ(total_cost, 15.0);
776 EXPECT_TRUE(verify_capacity_constraints(net));
779TEST_F(MaxFlowMinCostIntegrationTest, ParallelPathsNetwork)
781 auto net = build_parallel_paths_network();
785 double max_flow = get_max_flow(net);
786 double total_cost = net.flow_cost();
788 EXPECT_DOUBLE_EQ(max_flow, 7.0);
791 EXPECT_DOUBLE_EQ(total_cost, 10.0);
793 EXPECT_TRUE(verify_capacity_constraints(net));
796TEST_F(MaxFlowMinCostIntegrationTest, DiamondNetwork)
798 auto net = build_diamond_network();
802 double max_flow = get_max_flow(net);
803 double total_cost = net.flow_cost();
808 EXPECT_EQ(max_flow, 6.0);
812 EXPECT_DOUBLE_EQ(total_cost, 18.0);
814 EXPECT_TRUE(verify_capacity_constraints(net));
817TEST_F(MaxFlowMinCostIntegrationTest, TextbookNetwork)
819 auto net = build_textbook_network();
823 double max_flow = get_max_flow(net);
824 double total_cost = net.flow_cost();
828 EXPECT_TRUE(verify_capacity_constraints(net));
834 EXPECT_DOUBLE_EQ(max_flow, 5.0);
837 EXPECT_DOUBLE_EQ(total_cost, 18.0);
840 std::cout <<
"Textbook network: max_flow=" <<
max_flow
841 <<
", total_cost=" << total_cost
842 <<
", cycles_cancelled=" << cycles << std::endl;
845TEST_F(MaxFlowMinCostIntegrationTest, LargerNetwork)
884 double max_flow = get_max_flow(net);
885 double total_cost = net.flow_cost();
888 EXPECT_TRUE(verify_capacity_constraints(net));
892 EXPECT_DOUBLE_EQ(max_flow, 8.0);
893 EXPECT_DOUBLE_EQ(total_cost, 36.0);
895 std::cout <<
"Larger network: max_flow=" <<
max_flow
896 <<
", total_cost=" << total_cost
897 <<
", cycles_cancelled=" << cycles << std::endl;
900TEST_F(MaxFlowMinCostIntegrationTest, FunctorInterface)
902 auto net = build_parallel_paths_network();
905 [[maybe_unused]]
auto [cycles, factor] = algo(net);
907 double max_flow = get_max_flow(net);
908 double total_cost = net.flow_cost();
910 EXPECT_DOUBLE_EQ(max_flow, 7.0);
911 EXPECT_DOUBLE_EQ(total_cost, 10.0);
918class NetworkSimplexTest :
public ::testing::Test
923 Net build_single_path_network()
935 Net build_parallel_paths_network()
953 Net build_diamond_network()
970 Net build_textbook_network()
988 Net build_larger_network()
1010 double get_max_flow(
const Net& net)
1015 flow += it.get_curr()->flow;
1024 for (
auto p : net.
nodes())
1026 if (p == source || p == sink)
1029 double in_flow = 0, out_flow = 0;
1032 in_flow += it.get_curr()->flow;
1035 out_flow += it.get_curr()->flow;
1037 if (std::abs(in_flow - out_flow) > 1e-9)
1043 bool verify_capacity_constraints(
const Net& net)
1045 for (
auto a : net.
arcs())
1047 if (a->flow < 0 || a->flow > a->cap + 1e-9)
1054TEST_F(NetworkSimplexTest, SinglePathNetwork)
1056 auto net = build_single_path_network();
1060 double max_flow = get_max_flow(net);
1061 double total_cost = net.flow_cost();
1063 EXPECT_DOUBLE_EQ(max_flow, 5.0);
1064 EXPECT_DOUBLE_EQ(total_cost, 15.0);
1066 EXPECT_TRUE(verify_capacity_constraints(net));
1069TEST_F(NetworkSimplexTest, ParallelPathsNetwork)
1071 auto net = build_parallel_paths_network();
1075 double max_flow = get_max_flow(net);
1076 double total_cost = net.flow_cost();
1078 EXPECT_DOUBLE_EQ(max_flow, 7.0);
1079 EXPECT_DOUBLE_EQ(total_cost, 10.0);
1081 EXPECT_TRUE(verify_capacity_constraints(net));
1084TEST_F(NetworkSimplexTest, DiamondNetwork)
1086 auto net = build_diamond_network();
1090 double max_flow = get_max_flow(net);
1091 double total_cost = net.flow_cost();
1093 EXPECT_EQ(max_flow, 6.0);
1094 EXPECT_DOUBLE_EQ(total_cost, 18.0);
1096 EXPECT_TRUE(verify_capacity_constraints(net));
1099TEST_F(NetworkSimplexTest, TextbookNetwork)
1101 auto net = build_textbook_network();
1105 double max_flow = get_max_flow(net);
1106 double total_cost = net.flow_cost();
1109 EXPECT_TRUE(verify_capacity_constraints(net));
1110 EXPECT_DOUBLE_EQ(max_flow, 5.0);
1111 EXPECT_DOUBLE_EQ(total_cost, 18.0);
1113 std::cout <<
"Network Simplex textbook: max_flow=" <<
max_flow
1114 <<
", total_cost=" << total_cost
1115 <<
", pivots=" << pivots << std::endl;
1118TEST_F(NetworkSimplexTest, LargerNetwork)
1120 auto net = build_larger_network();
1124 double max_flow = get_max_flow(net);
1125 double total_cost = net.flow_cost();
1128 EXPECT_TRUE(verify_capacity_constraints(net));
1129 EXPECT_DOUBLE_EQ(max_flow, 8.0);
1130 EXPECT_DOUBLE_EQ(total_cost, 36.0);
1132 std::cout <<
"Network Simplex larger: max_flow=" <<
max_flow
1133 <<
", total_cost=" << total_cost
1134 <<
", pivots=" << pivots << std::endl;
1137TEST_F(NetworkSimplexTest, FunctorInterface)
1139 auto net = build_parallel_paths_network();
1144 double max_flow = get_max_flow(net);
1145 double total_cost = net.flow_cost();
1147 EXPECT_DOUBLE_EQ(max_flow, 7.0);
1148 EXPECT_DOUBLE_EQ(total_cost, 10.0);
1151TEST_F(NetworkSimplexTest, CompareWithCycleCanceling)
1154 auto net_simplex = build_larger_network();
1155 auto net_cycle = build_larger_network();
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();
1166 EXPECT_DOUBLE_EQ(flow_simplex, flow_cycle);
1169 EXPECT_NEAR(cost_simplex, cost_cycle, 1e-6);
1172TEST_F(NetworkSimplexTest, EmptyNetwork)
1184TEST_F(NetworkSimplexTest, ZeroCostNetwork)
1193 double max_flow = get_max_flow(net);
1194 double total_cost = net.flow_cost();
1196 EXPECT_DOUBLE_EQ(max_flow, 10.0);
1197 EXPECT_DOUBLE_EQ(total_cost, 0.0);
1200TEST_F(NetworkSimplexTest, HighCostArcAvoidance)
1222 double max_flow = get_max_flow(net);
1223 double total_cost = net.flow_cost();
1226 EXPECT_DOUBLE_EQ(max_flow, 10.0);
1228 EXPECT_DOUBLE_EQ(total_cost, 1010.0);
1236class SimplexDataStructuresTest :
public ::testing::Test
1240TEST_F(SimplexDataStructuresTest, SimplexNodeInfoDefaults)
1244 EXPECT_EQ(info.
parent,
nullptr);
1246 EXPECT_EQ(info.
depth, 0);
1247 EXPECT_EQ(info.
mark, 0);
1251TEST_F(SimplexDataStructuresTest, SimplexArcStateEnum)
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));
1298class NetworkSimplexVsPureSimplexTest :
public ::testing::Test
1326 std::vector<ArcData>
arcs = {
1334 static constexpr int SOURCE = 0;
1335 static constexpr int SINK = 3;
1336 static constexpr int NUM_NODES = 4;
1341 std::vector<Node*>
nodes(NUM_NODES);
1343 for (
int i = 0; i < NUM_NODES; ++i)
1346 for (
const auto& a :
arcs)
1347 net.insert_arc(
nodes[a.src],
nodes[a.tgt], a.cap, a.cost);
1354 std::tuple<double, double, double> solve_with_pure_simplex()
1372 const size_t NUM_ARCS =
arcs.size();
1373 const size_t NUM_VARS = NUM_ARCS + 1;
1374 const double M = 1000.0;
1376 auto start = std::chrono::high_resolution_clock::now();
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);
1387 auto make_coefs = [NUM_VARS]() {
1388 return std::vector<double>(NUM_VARS + 1, 0.0);
1392 for (
size_t i = 0; i < NUM_ARCS; ++i)
1394 auto coefs = make_coefs();
1396 coefs[NUM_VARS] =
arcs[i].cap;
1397 simplex.put_restriction(coefs.data());
1405 auto coefs = make_coefs();
1409 coefs[NUM_VARS] = 0.0;
1410 simplex.put_restriction(coefs.data());
1414 auto coefs = make_coefs();
1418 coefs[NUM_VARS] = 0.0;
1419 simplex.put_restriction(coefs.data());
1427 auto coefs = make_coefs();
1431 coefs[NUM_VARS] = 0.0;
1432 simplex.put_restriction(coefs.data());
1436 auto coefs = make_coefs();
1440 coefs[NUM_VARS] = 0.0;
1441 simplex.put_restriction(coefs.data());
1447 auto coefs = make_coefs();
1450 coefs[NUM_ARCS] = -1.0;
1451 coefs[NUM_VARS] = 0.0;
1452 simplex.put_restriction(coefs.data());
1456 auto coefs = make_coefs();
1457 coefs[NUM_ARCS] = 1.0;
1460 coefs[NUM_VARS] = 0.0;
1461 simplex.put_restriction(coefs.data());
1464 simplex.prepare_linear_program();
1465 auto state = simplex.solve();
1467 auto end = std::chrono::high_resolution_clock::now();
1468 double time_ms = std::chrono::duration<double, std::milli>(end - start).count();
1471 return {-1, -1, time_ms};
1473 simplex.load_solution();
1475 double max_flow = simplex.get_solution(NUM_ARCS);
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;
1480 return {
max_flow, total_cost, time_ms};
1485 std::tuple<double, double, double> solve_with_network_simplex()
1487 auto net = build_network();
1489 auto start = std::chrono::high_resolution_clock::now();
1491 auto end = std::chrono::high_resolution_clock::now();
1493 double time_ms = std::chrono::duration<double, std::milli>(end - start).count();
1501 return {
max_flow, net.flow_cost(), time_ms};
1505TEST_F(NetworkSimplexVsPureSimplexTest, BothMethodsProduceSameOptimalSolution)
1507 auto [flow_simplex, cost_simplex, time_simplex] = solve_with_pure_simplex();
1508 auto [flow_network, cost_network, time_network] = solve_with_network_simplex();
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";
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";
1524 std::cout <<
"✓ Both methods produce identical optimal solution\n";
1527TEST_F(NetworkSimplexVsPureSimplexTest, NetworkSimplexIsTypicallyFaster)
1530 const int RUNS = 10;
1531 double total_simplex_time = 0;
1532 double total_network_time = 0;
1534 for (
int i = 0; i < RUNS; ++i)
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;
1543 double avg_simplex = total_simplex_time / RUNS;
1544 double avg_network = total_network_time / RUNS;
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";
1552 std::cout <<
"Speedup factor: " << (avg_simplex / avg_network) <<
"x\n";
1560class LargeNetworkValidationTest :
public ::testing::Test
1567 std::vector<std::vector<Node*>>
nodes(n, std::vector<Node*>(n));
1570 for (
int i = 0; i < n; ++i)
1571 for (
int j = 0; j < n; ++j)
1575 for (
int i = 0; i < n; ++i)
1577 for (
int j = 0; j < n; ++j)
1582 double cap = 10.0 + (i + j) % 5;
1583 double cost = 1.0 + (i * j) % 3;
1589 double cap = 10.0 + (i + j + 1) % 5;
1590 double cost = 1.0 + ((i + 1) * j) % 3;
1600TEST_F(LargeNetworkValidationTest, CompareAlgorithmsOnLargerNetwork)
1602 const int GRID_SIZE = 5;
1610 double cost_after_ff = net_ff.flow_cost();
1613 auto start_ns = std::chrono::high_resolution_clock::now();
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();
1619 auto start_cc = std::chrono::high_resolution_clock::now();
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();
1625 auto get_flow = [](
const Net& net) {
1629 flow += it.get_curr()->flow;
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();
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";
1647 EXPECT_NEAR(flow_ns, flow_cc, 1e-6) <<
"Max flow should be identical";
1650 if (std::abs(cost_ns - cost_cc) > 1e-6)
1652 std::cout <<
"\n⚠ BUG DETECTED: Cost difference = " << std::abs(cost_ns - cost_cc) <<
"\n";
1654 if (cost_ns > cost_cc)
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";
1666 std::cout <<
" Cycle Canceling found higher cost (unexpected).\n";
1671 std::cout <<
"✓ Both algorithms produce identical optimal solution\n";
1675 EXPECT_TRUE(flow_ns > 0) <<
"Network Simplex should find positive flow";
1676 EXPECT_TRUE(flow_cc > 0) <<
"Cycle Canceling should find positive flow";
1681TEST_F(LargeNetworkValidationTest, PhaseIDiagnostic)
1683 const int GRID_SIZE = 5;
1688 std::cout <<
"\n=== Phase I Diagnostic ===\n";
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)
1698 std::cout <<
"Partial arcs after FF: " << partial_before <<
"\n";
1701 size_t pivots = simplex.run();
1704 bool valid_bfs = simplex.is_valid_basic_solution();
1705 size_t remaining = simplex.count_non_tree_partial_arcs();
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";
1713 simplex.print_diagnostics();
1718 std::cout <<
"Optimal cost (CC): " << net2.flow_cost() <<
"\n";
1721 std::cout <<
"WARNING: Phase I failed to establish valid BFS!\n";
1724 std::cout <<
"WARNING: " << remaining <<
" partial arcs still outside tree!\n";
1727 std::cout <<
"\nNon-tree arc analysis:\n";
1728 for (
auto a : net.
arcs())
1732 bool at_lower = (a->flow <= 1e-9);
1733 bool at_upper = (a->flow >= a->cap - 1e-9);
1735 if (not at_lower
and not at_upper)
1752 auto [cycle, iterations] = BF(rnet).search_negative_cycle(0.4, 10);
1754 if (not cycle.is_empty())
1756 std::cout <<
"NEGATIVE CYCLE FOUND after Network Simplex!\n";
1757 std::cout <<
" Cycle has " << cycle.size() <<
" arcs\n";
1759 cycle.for_each_arc([&](
auto arc) {
cycle_cost += arc->cost; });
1760 std::cout <<
" Cycle cost: " <<
cycle_cost <<
"\n";
1763 std::cout <<
"No negative cycles found - this is strange!\n";
1767TEST_F(LargeNetworkValidationTest, PerformanceComparison)
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";
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();
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();
1791 EXPECT_NEAR(net1.flow_cost(), net2.flow_cost(), 1e-6)
1792 <<
"Different costs for grid " <<
size <<
"x" <<
size;
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";
1817class NetworkSimplexBugInvestigation :
public ::testing::Test
1909 Net build_asymmetric_diamond()
1972 double get_flow(
const Net& net)
1977 flow += it.get_curr()->flow;
1981 void print_network_state(
const Net& net,
const std::string& label)
1983 std::cout <<
"\n--- " << label <<
" ---\n";
1984 std::cout <<
"Arcs:\n";
1985 for (
auto a : net.
arcs())
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";
1994 std::cout <<
"Total flow: " << get_flow(net) <<
"\n";
1995 std::cout <<
"Total cost: " << net.flow_cost() <<
"\n";
1999TEST_F(NetworkSimplexBugInvestigation, DiagnoseNetworkSimplexBug)
2002 auto net_ns = build_asymmetric_diamond();
2003 std::cout <<
"\n========== NETWORK SIMPLEX BUG INVESTIGATION ==========\n";
2007 print_network_state(net_ns,
"After Ford-Fulkerson (before Network Simplex)");
2011 size_t pivots = simplex.run();
2013 print_network_state(net_ns,
"After Network Simplex");
2014 std::cout <<
"Pivots performed: " << pivots <<
"\n";
2017 auto net_cc = build_asymmetric_diamond();
2019 print_network_state(net_cc,
"Using Cycle Canceling");
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();
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";
2034 double expected_flow = 15.0;
2035 double expected_cost = 75.0;
2037 std::cout <<
"Expected: flow=" << expected_flow <<
", cost=" << expected_cost <<
"\n";
2040 EXPECT_NEAR(flow_ns, expected_flow, 1e-6) <<
"Network Simplex flow";
2041 EXPECT_NEAR(flow_cc, expected_flow, 1e-6) <<
"Cycle Canceling flow";
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";
2047 if (std::abs(cost_ns - cost_cc) > 1e-6)
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";
2054 std::cout <<
"Cycle Canceling found suboptimal solution!\n";
2058 std::cout <<
"\n✓ Both algorithms found the same cost\n";
2062TEST_F(NetworkSimplexBugInvestigation, SimpleNetworkOptimization)
2065 auto net = build_asymmetric_diamond();
2069 double cost_before = net.flow_cost();
2073 size_t pivots = simplex.run();
2074 double cost_after = net.flow_cost();
2076 std::cout <<
"Simple network: cost_before=" << cost_before
2077 <<
", cost_after=" << cost_after
2078 <<
", pivots=" << pivots <<
"\n";
2081 EXPECT_LE(cost_after, cost_before);
2088TEST_F(LargeNetworkValidationTest, StatisticsTracking)
2097 auto stats = simplex.get_stats();
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);
2109 EXPECT_EQ(stats.tree_arcs, net.
vsize() - 1);
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";
2119TEST_F(LargeNetworkValidationTest, StressTestLargeGrid)
2130 auto stats = simplex.get_stats();
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";
2141TEST_F(NetworkSimplexBugInvestigation, DensityStressTest)
2144 auto net = build_asymmetric_diamond();
2151 auto stats = simplex.get_stats();
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";
2159 EXPECT_TRUE(simplex.verify_tree_integrity());
2160 EXPECT_TRUE(simplex.is_valid_basic_solution());
2163TEST_F(NetworkSimplexBugInvestigation, NegativeCostsTest)
2180 (void)sa; (void)sb; (void)ab; (void)at; (void)bt;
2183 double cost_before = net.flow_cost();
2187 double cost_after = net.flow_cost();
2189 std::cout <<
"Negative costs: before=" << cost_before
2190 <<
", after=" << cost_after <<
"\n";
2193 EXPECT_LE(cost_after, cost_before + 1e-6);
2204bool flows_within_capacities(
const N & net)
2206 for (
auto a : net.
arcs())
2207 if (a->flow < 0 or a->flow > a->cap)
2215TEST(NetworkSimplexFloatingTest, APivotKeepsTheFlowsWithinTheCapacities)
2230 EXPECT_TRUE(flows_within_capacities(net));
2232 EXPECT_EQ(dear->flow, 0.0);
2234 EXPECT_NEAR(net.flow_cost(), 3.6, 1e-12);
2241struct Dfs_Maximum_Flow
2243 typename N::Flow_Type operator () (
N & net)
const
2245 return aumenting_path_maximum_flow<N, Find_Aumenting_Path_DFS>(net);
2252TEST(NetworkSimplexFloatingTest, DecimalCapacitiesReachTheOptimum)
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}};
2259 for (
const bool dfs : {
false,
true})
2262 std::vector<Net::Node *>
nodes;
2263 for (
int i = 0; i < 5; ++i)
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]));
2269 max_flow_min_cost_by_network_simplex<Net, Dfs_Maximum_Flow>(net);
2273 EXPECT_TRUE(flows_within_capacities(net)) <<
"dfs " <<
dfs;
2276 EXPECT_NEAR(net.flow_cost(), -0.8, 1e-12) <<
"dfs " <<
dfs;
2286TEST(NetworkSimplexFloatingTest, ResiduesOfRoundingGoBack)
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}};
2292 std::vector<Net::Node *>
nodes;
2293 for (
int i = 0; i < 7; ++i)
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]));
2302 EXPECT_TRUE(flows_within_capacities(net));
2305 EXPECT_NEAR(net.flow_cost(), -0.9, 1e-12);
2313TEST(NetworkSimplexFloatingTest, DecimalCapacitiesEndOnAMidSizeNetwork)
2322 std::mt19937 gen(1);
2323 std::vector<Net::Node *>
nodes;
2324 for (
int i = 0; i < n; ++i)
2326 auto arc = [&] (
int a,
int b)
2328 const double cap = double(1 + gen() % 40) * 0.1;
2329 const double cost = double(1 + gen() % 20);
2332 for (
int i = 1; i < n - 1; ++i)
2334 arc(
int(gen() %
unsigned(i)), i);
2335 arc(i, i + 1 +
int(gen() %
unsigned(n - 1 - i)));
2337 for (
int k = 0;
k < 10 * n; ++
k)
2339 const int a = int(gen() %
unsigned(n - 1));
2340 const int b = 1 + int(gen() %
unsigned(n - 1));
2346 Net simplex, canceling;
2354 for (
const Net * net : {&simplex, &canceling})
2356 EXPECT_TRUE(flows_within_capacities(*net));
2359 EXPECT_NEAR(net->flow_cost(), 811.1, 1e-9);
2365TEST(NetworkSimplexFloatingTest, TinyCostsAreOptimized)
2367 for (
const double unit : {1e-13, std::ldexp(1.0, -44)})
2374 auto cheap = net.
insert_arc(a, t, 1.0, unit);
2375 auto dear = net.
insert_arc(a, t, 1.0, 2 * unit);
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;
2390TEST(NetworkSimplexFloatingTest, TinyCapacitiesAreOptimized)
2392 for (
const double unit : {1e-12, 1e-13})
2399 auto cheap = net.
insert_arc(a, t, unit, 1.0);
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;
2411TEST(NetworkSimplexFloatingTest, ATinyNegativeCycleIsSaturated)
2425 EXPECT_EQ(ab->flow, 1.0);
2426 EXPECT_EQ(ba->flow, 1.0);
2427 EXPECT_DOUBLE_EQ(net.flow_cost(), -2e-13);
2433TEST(NetworkSimplexFloatingTest, AnUnboundedProgramThrows)
2435 for (
const double cap : {std::numeric_limits<double>::infinity(),
2436 std::numeric_limits<double>::max()})
2448 <<
"capacity " << cap;
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);
2467TEST(NetworkSimplexFloatingTest, AnUnboundedProgramReturnsTheResidues)
2469 for (
const double cap : {std::numeric_limits<double>::infinity(),
2470 std::numeric_limits<double>::max()})
2476 std::vector<Net::Node *>
nodes;
2477 for (
int i = 0; i < 6; ++i)
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);
2493 EXPECT_TRUE(flows_within_capacities(net)) <<
"capacity " << cap;
2502TEST(NetworkSimplexFloatingTest, TakesTheMaximumFlowsOfDinicAndOfTheScaling)
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}};
2514 std::vector<Net::Node *>
nodes;
2515 for (
int i = 0; i < 20; ++i)
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);
2531 ASSERT_NO_THROW((max_flow_min_cost_by_network_simplex<Net, Dinic_Maximum_Flow>(net)));
2537 ASSERT_NO_THROW((max_flow_min_cost_by_network_simplex<Net, Capacity_Scaling_Maximum_Flow>(other)));
2543std::vector<LNet::Arc *> build_infeasible_case(LNet & net)
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)};
2555TEST(NetworkSimplexIntegerTest, AnInfeasibleFlowThrows)
2559 auto arcs = build_infeasible_case(net);
2562 EXPECT_THROW(simplex.run(), std::domain_error);
2566 auto arcs = build_infeasible_case(net);
2569 EXPECT_THROW(simplex.run(), std::domain_error);
2573 auto arcs = build_infeasible_case(net);
2574 arcs[0]->flow =
arcs[2]->flow = -1;
2576 EXPECT_THROW(simplex.run(), std::domain_error);
2581TEST(NetworkSimplexFloatingTest, AnInfiniteFlowThrows)
2586 auto st = net.
insert_arc(s, t, std::numeric_limits<double>::infinity(), 1.0);
2587 st->flow = std::numeric_limits<double>::infinity();
2590 EXPECT_THROW(simplex.run(), std::domain_error);
2595TEST(NetworkSimplexIntegerTest, ThePredicatesOfTheBoundsCompareExactly)
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);
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));
2620TEST(NetworkSimplexIntegerTest, DegeneratePivotsAreCounted)
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();
2638 const size_t pivots = simplex.run();
2640 ASSERT_EQ(net.flow_cost(), cost);
2641 ASSERT_GT(pivots, 0u);
2642 EXPECT_EQ(simplex.get_stats().degenerate_pivots, pivots);
2647TEST_F(NetworkSimplexTest, TheDiagnosticsAskForRunFirst)
2649 auto net = build_diamond_network();
2652 auto expect_run_first = [] (
auto diagnostic,
const char * name)
2657 ADD_FAILURE() << name <<
"() did not throw";
2659 catch (
const std::domain_error & e)
2661 EXPECT_NE(std::string(e.what()).find(
"run() has not been called"),
2662 std::string::npos) << name <<
"(): " << e.what();
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");
2678 EXPECT_TRUE(simplex.is_valid_basic_solution());
2679 EXPECT_TRUE(simplex.verify_tree_integrity());
2684TEST(NetworkSimplexIntegerTest, TheStatisticsExpectATreeByComponent)
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);
2695 ASSERT_EQ(net.flow_cost(), -2);
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;
2706#if defined(_MSC_VER) && !defined(__clang__)
2707# pragma warning(push)
2708# pragma warning(disable : 4996)
2710# pragma GCC diagnostic push
2711# pragma GCC diagnostic ignored "-Wdeprecated-declarations"
2716std::vector<LNet::Arc *> build_lower_bound_case(LNet & net)
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)};
2731TEST(NetworkSimplexIntegerTest, ANonzeroLowerBoundThrows)
2734 auto ab = build_lower_bound_case(net)[4];
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);
2743 EXPECT_EQ(ab->flow, 0);
2747TEST(NetworkSimplexIntegerTest, TheLowerBoundsNeedNoRun)
2750 auto arcs = build_lower_bound_case(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));
2762#if defined(_MSC_VER) && !defined(__clang__)
2763# pragma warning(pop)
2765# pragma GCC diagnostic pop
2776void build_negative_costs_case(
N & net,
const bool apart)
2778 auto s = net.insert_node();
2779 auto a = net.insert_node();
2780 auto b = net.insert_node();
2781 auto t = net.insert_node();
2784 net.insert_arc(s, t, 1, 0);
2785 net.insert_arc(a, b, 1, -1);
2786 net.insert_arc(b, a, 1, -1);
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);
2798TEST(CycleCancelingTest, NegativeCostsReachTheOptimum)
2800 for (
const bool apart : {
false,
true})
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);
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);
2820TEST(CycleCancelingTest, AnUnboundedProgramThrows)
2822 for (
const double cap : {std::numeric_limits<double>::infinity(),
2823 std::numeric_limits<double>::max()})
2835 <<
"capacity " << cap;
2836 EXPECT_EQ(st->flow, 1.0);
2837 EXPECT_EQ(ab->flow, 0.0);
2838 EXPECT_EQ(ba->flow, 0.0);
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);
2855void build_tenths_case(
Net & net,
int n,
const std::vector<std::array<int, 4>> & spec)
2857 std::vector<Net::Node *>
nodes;
2858 for (
int i = 0; i < n; ++i)
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);
2868TEST(CycleCancelingTest, DecimalCostsEnd)
2872 for (
const bool dfs : {
false,
true})
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}});
2879 max_flow_min_cost_by_cycle_canceling<Net, Dfs_Maximum_Flow>(net);
2883 EXPECT_TRUE(flows_within_capacities(net)) <<
"dfs " <<
dfs;
2886 EXPECT_NEAR(net.flow_cost(), 0.96, 1e-12) <<
"dfs " <<
dfs;
2893TEST(CycleCancelingTest, AResidueOfRoundingIsNoSlack)
2897 for (
const bool dfs : {
false,
true})
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}});
2910 max_flow_min_cost_by_cycle_canceling<Net, Dfs_Maximum_Flow>(net);
2914 EXPECT_TRUE(flows_within_capacities(net)) <<
"dfs " <<
dfs;
2917 EXPECT_NEAR(net.flow_cost(), -3.01, 1e-12) <<
"dfs " <<
dfs;
2923TEST(CycleCancelingTest, DecimalFlowsStayWithinTheCapacities)
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}});
2930 max_flow_min_cost_by_cycle_canceling<Net, Edmonds_Karp_Maximum_Flow>(net);
2932 EXPECT_TRUE(flows_within_capacities(net));
2935 EXPECT_NEAR(net.flow_cost(), 3.0, 1e-12);
2940struct Given_Maximum_Flow
2942 typename N::Flow_Type operator () (
N & net)
const
2944 return net.flow_value();
2952TEST(CycleCancelingTest, TheFlowOfAnArcWithoutCapacityGoesBack)
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})
2967 auto sa = net.
insert_arc(s, a,
double(units), 0.0);
2974 sa->flow = x->flow = double(units);
2975 max_flow_min_cost_by_cycle_canceling<Net, Given_Maximum_Flow>(net);
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));
2985 EXPECT_EQ(x->flow, units - 1.0);
2986 EXPECT_DOUBLE_EQ(net.flow_cost(), 2.0 + 10.0 * (units - 1));
2993TEST(CycleCancelingTest, TheArcThatBoundsACycleStaysWithinItsCapacity)
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}};
3002 std::vector<Net::Node *>
nodes;
3003 for (
int i = 0; i < 10; ++i)
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);
3010 EXPECT_TRUE(flows_within_capacities(net));
3013 EXPECT_NEAR(net.flow_cost(), 17.67, 1e-12);
3029TEST(CycleCancelingTest, TakesAnImprovementOf1e7)
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);
3040TEST(NetworkSimplexFloatingTest, TakesAnImprovementOf1e7)
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);
3056TEST(InfiniteMaximumFlowTest, TheSimplexAndTheCancelingRefuseIt)
3058 const double inf = std::numeric_limits<double>::infinity();
3059 for (
int algo = 0; algo < 2; ++algo)
3066 const char * name = algo == 0 ?
"network simplex" :
"cycle canceling";
3073 ADD_FAILURE() << name <<
" did not throw";
3075 catch (
const std::domain_error & e)
3077 EXPECT_NE(std::string(e.what()).find(
"infinite"), std::string::npos)
3078 << name <<
": " << e.what();
3087template <
template <
class>
class Max_Flow>
3088void expect_the_cost_of_a_finite_flow_through_infinite_arcs(
const char * name)
3090 const double inf = std::numeric_limits<double>::infinity();
3091 for (
int algo = 0; algo < 2; ++algo)
3101 EXPECT_NO_THROW((max_flow_min_cost_by_network_simplex<Net, Max_Flow>(net))) << name;
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");
3113TEST(InfiniteMaximumFlowTest, AnInfiniteArcOfAFiniteMaximumFlowIsTaken)
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");
3130 ::testing::InitGoogleTest(&argc, argv);
3131 return RUN_ALL_TESTS();
Simplex algorithm for linear programming.
TEST_F(AdaptiveHuffmanWithoutMemory, ALostByteLeavesTheDecoderFailed)
WeightedDigraph::Node Node
size_t size_t int32_t value
size_t size_t int32_t * out
Bellman-Ford algorithm for shortest paths with negative weights.
bool has_curr() const noexcept
Return true the iterator has an current arc.
Generic key-value map implemented on top of a binary search tree.
Filtered iterator for incoming arcs of a node.
Number Theoretic Transform over Z / MOD Z.
Node * insert_node(Node *p) override
Network Simplex algorithm for minimum cost flow.
Filtered iterator for outcoming arcs of a node.
Linear program solver using the Simplex method.
constexpr size_t vsize() const noexcept
See get_num_nodes().
size_t esize() const noexcept
Return the total of arcs of graph.
DynArray< Graph::Node * > nodes
DynArray< Graph::Arc * > arcs
Container< T > arcs_map(GT &g, Op transformation, SA sa=SA())
Map the filtered arcs of a graph to a transformed type.
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.
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.
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.
Functor wrapper for edmonds_karp_maximum_flow().
Functor wrapper for ford_fulkerson_maximum_flow().
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.
Capacitated flow network with costs associated to arcs.
Flow network implemented with adjacency lists.
Node * insert_node(const Node_Type &node_info)
Insert a new node by copying node_info.
bool check_network() const
Validate flow-conservation and capacity constraints.
Node * get_source() const
Return an arbitrary source node.
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.
Node * get_sink() const
Return an arbitrary sink node.
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...
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)
Advanced maximum flow algorithms.
void verify_flow_conservation(const Net &net)
Maximum flow minimum cost network algorithms.