Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
tpl_netcost.H
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
48# ifndef TPL_NETCOST_H
49# define TPL_NETCOST_H
50
51# include <ah-graph-concepts.H>
52
53# include <limits>
54# include <chrono>
55# include <tpl_net.H>
56# include <tpl_dynMapTree.H>
57# include <tpl_find_path.H>
58# include <tpl_cut_nodes.H>
59# include <Bellman_Ford.H>
60# include <tpl_dfs_stack.H> // ALEPH_FLATTEN
61# include <generate_graph.H>
62# include <ah-errors.H>
63
64namespace Aleph
65{
73 template <typename Node_Info = Empty_Class>
75
76
94 template <typename Arc_Info = Empty_Class, typename F_Type = double>
95 struct Net_Cost_Arc : public Net_Arc<Arc_Info, F_Type>
96 {
98 using Base::Base;
99
101 using Flow_Type = F_Type;
102
105
107 Net_Cost_Arc() = default;
108
111 : Base(a), cost(a.cost)
112 { /* empty */
113 }
114
117 {
118 if (&a == this)
119 return *this;
121 cost = a.cost;
122 return *this;
123 }
124
126 Flow_Type flow_cost() const noexcept { return this->flow * cost; }
127 };
128
129
147 template <class NodeT = Net_Cost_Node<Empty_Class>,
148 class ArcT = Net_Cost_Arc<Empty_Class, double>>
149 struct Net_Cost_Graph : public Net_Graph<NodeT, ArcT>
150 {
152
155
158
160 using Arc = ArcT;
161
163 using Node = NodeT;
164
166 using Flow_Type = typename Arc::Flow_Type;
167
169 using Node_Type = typename Node::Node_Type;
170
172 using Arc_Type = typename Arc::Arc_Type;
173
175 Net_Cost_Graph() = default;
176
185 {
186 zip(this->arcs(), net.arcs()).for_each([](const auto & p)
187 {
188 auto atgt = p.first;
189 auto asrc = p.second;
190 atgt->cost = asrc->cost;
191 });
192 }
193
196
199 {
200 if (this == &net)
201 return *this;
202 Net_Cost_Graph tmp(net); // copy construct (copies capacity, flow, and cost)
203 tmp.get_cookie() = this->get_cookie(); // the network keeps its cookie
204 this->swap(tmp); // swap with copy
205 return *this;
206 }
207
210
216 Flow_Type &get_cost(Arc *a) noexcept { return a->cost; }
217
223 Flow_Type get_cost(Arc *a) const noexcept { return a->cost; }
224
230 static Flow_Type arc_flow_cost(Arc *a) noexcept { return a->flow_cost(); }
231
243 virtual Arc * insert_arc(Node *src_node, Node *tgt_node,
244 const Flow_Type & cap, const Flow_Type & __cost)
245 {
246 Arc *a = Net::insert_arc(src_node, tgt_node, cap, 0, Arc_Type());
247 a->cost = __cost;
248 return a;
249 }
250
261 template <typename... Args>
262 Arc * emplace_arc(Node *src_node, Node *tgt_node,
263 const Flow_Type & cap, const Flow_Type & __cost,
264 Args &&... args)
265 {
266 auto a = Net::insert_arc(src_node, tgt_node, cap, 0,
267 Arc_Type(std::forward<Args>(args)...));
268 a->cost = __cost;
269 return a;
270 }
271
281 virtual Arc * insert_arc(Node *src_node, Node *tgt_node)
282 {
283 Arc *a = Net::insert_arc(src_node, tgt_node, Arc_Type());
284 a->cost = 0;
285 return a;
286 }
287
295 {
296 Flow_Type total = 0;
297 for (Arc_Iterator<Net_MFMC> it(*this); it.has_curr(); it.next_ne())
298 {
299 Arc *a = it.get_curr();
300 total += a->flow_cost();
301 }
302 return total;
303 }
304
311 auto out_pars(Node *p)
312 {
313 Flow_Type cap_sum = 0, flow_sum = 0, cost_sum = 0;
314 for (_Out_Iterator<Net> it(p); it.has_curr(); it.next_ne())
315 {
316 Arc *a = it.get_curr();
317 cap_sum += a->cap;
318 flow_sum += a->flow;
319 cost_sum += a->cost;
320 }
321 return std::make_tuple(cap_sum, flow_sum, cost_sum);
322 }
323
330 auto in_pars(Node *p)
331 {
332 Flow_Type cap_sum = 0, flow_sum = 0, cost_sum = 0;
333 for (_In_Iterator<Net> it(p); it.has_curr(); it.next_ne())
334 {
335 Arc *a = it.get_curr();
336 cap_sum += a->cap;
337 flow_sum += a->flow;
338 cost_sum += a->cost;
339 }
340 return std::make_tuple(cap_sum, flow_sum, cost_sum);
341 }
342 };
343
344
352 template <class Net>
353 struct Res_Filt
354 {
356 Res_Filt(typename Net::Node *) noexcept {}
357
359 Res_Filt() noexcept = default;
360
366 bool operator ()(typename Net::Arc *a) const noexcept
367 {
368 return a->cap > a->flow;
369 }
370 };
371
372
373 namespace net_detail
374 {
379 template <class Arc>
380 inline auto residual_room(const Arc *a) noexcept
381 {
382 return a->is_residual ? a->img->flow : a->cap - a->flow;
383 }
384 } // namespace net_detail
385
399 template <class Net>
401 {
403 typename Net::Flow_Type tol{0};
404
406 Res_Filt_With_Tolerance(typename Net::Node *) noexcept {}
407
409 Res_Filt_With_Tolerance() noexcept = default;
410
412 explicit Res_Filt_With_Tolerance(const typename Net::Flow_Type & t) noexcept : tol(t) {}
413
420 bool operator ()(typename Net::Arc *a) const noexcept
421 {
422 return net_detail::residual_room(a) > tol;
423 }
424 };
425
426
435 template <class Net>
436 struct Rcost
437 {
438 Rcost() noexcept = default;
439
440 using Distance_Type = typename Net::Flow_Type;
441
447 typename Net::Flow_Type operator ()(typename Net::Arc *a) const noexcept
448 {
449 return a->cost;
450 }
451
458 static void set_zero(typename Net::Arc *a) noexcept
459 {
460 a->cap = std::numeric_limits<Distance_Type>::max();
461 a->flow = 0;
462 a->cost = 0;
463 }
464 };
465
466
478 template <class Net>
479 struct Rcost_With_Tolerance : public Rcost<Net>
480 {
482 typename Net::Flow_Type tol{0};
483
484 Rcost_With_Tolerance() noexcept = default;
485
487 explicit Rcost_With_Tolerance(const typename Net::Flow_Type & t) noexcept : tol(t) {}
488
490 typename Net::Flow_Type tolerance() const noexcept { return tol; }
491 };
492
493
494 namespace net_detail
495 {
497 template <typename Flow_Type>
498 inline bool without_capacity(const Flow_Type & cap) noexcept
499 {
500 return not (cap < std::numeric_limits<Flow_Type>::max());
501 }
502
515 template <class Net>
516 void refuse_infinite_maximum_flow(const Net & net, const char * algorithm)
517 {
518 using Flow_Type = typename Net::Flow_Type;
519 if constexpr (std::numeric_limits<Flow_Type>::has_infinity)
520 ah_domain_error_if(net.flow_value() == std::numeric_limits<Flow_Type>::infinity())
521 << algorithm << ": the maximum flow is infinite, through a path of arcs of "
522 << "infinite capacity from the source to the sink";
523 else
524 {
525 (void) net;
526 (void) algorithm;
527 }
528 }
529 } // namespace net_detail
530
531
540 template <typename Ftype>
541 struct Res_Arc : public Net_Cost_Arc<Empty_Class, Ftype>
542 {
544 using Base::Base;
545
547 bool is_residual = false;
548
550 Res_Arc *img = nullptr;
551 };
552
553
559 template <typename Ftype>
561
562
581 template <class Res_Net>
582 typename Res_Net::Arc *
583 create_residual_arc(Res_Net & residual_net,
584 typename Res_Net::Node *src,
585 typename Res_Net::Node *tgt,
586 const typename Res_Net::Flow_Type cap,
587 const typename Res_Net::Flow_Type flow,
588 const typename Res_Net::Flow_Type cost)
589 {
590 assert(flow <= cap);
591
592 auto arc = residual_net.insert_arc(src, tgt, cap, cost);
593 auto rarc = residual_net.insert_arc(tgt, src, cap, -cost);
594
595 arc->is_residual = false;
596 arc->flow = flow;
597 arc->img = rarc;
598
599 rarc->is_residual = true;
600 rarc->img = arc;
601 rarc->flow = arc->cap - arc->flow;
602
603 assert(arc->cap == cap and arc->flow == flow and arc->cost == cost);
604 assert(rarc->cap == cap and rarc->flow == cap - flow and rarc->cost == -cost);
605
606 return arc;
607 }
608
609
625 template <class Net>
630 {
632 << "Network is not single source and single sink";
633
635
636 // Copy nodes from net to residual network
637 for (typename Net::Node_Iterator it(net); it.has_curr(); it.next_ne())
638 {
639 auto p = it.get_curr();
640 auto q = rnet.insert_node();
641 map_nodes<Net, Rnet>(p, q);
642 }
643
644 // Create residual arcs and build mapping
645 for (typename Net::Arc_Iterator it(net); it.has_curr(); it.next_ne())
646 {
647 auto ga = it.get_curr();
648 auto gsrc = static_cast<typename Net::Node *>(ga->src_node);
649 auto gtgt = static_cast<typename Net::Node *>(ga->tgt_node);
650
651 auto rsrc = mapped_node<Net, Rnet>(gsrc);
652 auto rtgt = mapped_node<Net, Rnet>(gtgt);
653 auto ra = create_residual_arc(rnet, rsrc, rtgt,
654 ga->cap, ga->flow, ga->cost);
655 arcs.insert(ga, ra);
656 }
657
658 assert(check_residual_net(rnet));
659
660 return static_cast<typename Rnet::Node *>(NODE_COOKIE(net.get_source()));
661 }
662
663
673 template <class Res_Net>
674 bool check_residual_net(const Res_Net & net)
675 {
676 return net.all_arcs([](typename Res_Net::Arc *a)
677 {
678 return a->img != nullptr and a->img->img == a;
679 });
680 }
681
682
698 template <class Res_Net>
699 void cancel_cycle(const Res_Net &, const Path<Res_Net> & path)
700 {
701 ah_domain_error_if(path.is_empty() or not path.is_cycle())
702 << "Path is empty or not a cycle";
703
704 using Ftype = typename Res_Net::Flow_Type;
705
706 // Determine minimum slack (bottleneck capacity) of the cycle; a cycle
707 // that only arcs without capacity make has none, and its flow would
708 // grow without bound: by infinity, of cost NaN, or by max()
709 Ftype slack = std::numeric_limits<Ftype>::max();
710 bool bounded = false;
711 path.for_each_arc([&slack, &bounded](typename Res_Net::Arc *a)
712 {
713 Ftype room;
714 if constexpr (std::is_floating_point_v<Ftype>)
716 else
717 room = a->cap - a->flow;
718 assert(room > 0);
719 slack = std::min(slack, room);
720 bounded = bounded or a->is_residual
721 or not net_detail::without_capacity(a->cap);
722 });
723 ah_domain_error_if(not bounded)
724 << "cancel_cycle(): the cycle has no bound: its arcs have no capacity";
725
726 // Cancel the cycle by augmenting flow. With a floating slack, an arc
727 // takes it within its capacity, and its capacity, exactly, if the slack
728 // covers what it has left, and its mirror takes the rest: by rounding,
729 // the arc that bounds the cycle went beyond, or the mirror below zero,
730 // and an arc of the network carried more than its capacity, or less
731 // than nothing. A mirror takes the slack from the flow of its image,
732 // which the slack does not exceed, as it is what the mirror has left:
733 // the flow goes to zero, exactly, if the mirror bounds the cycle.
734 // cap - flow lost that flow for an arc of capacity infinity or max()
735 path.for_each_arc([slack](typename Res_Net::Arc *a)
736 {
737 auto img = a->img;
738 assert(img->img == a);
739 assert(a->cap == img->cap);
740 if constexpr (std::is_floating_point_v<Ftype>)
741 {
742 if (a->is_residual)
743 {
744 img->flow -= slack;
745 a->flow = a->cap - img->flow;
746 }
747 else
748 {
749 a->flow = a->cap - a->flow <= slack
750 ? a->cap : std::min(a->flow + slack, a->cap);
751 img->flow = a->cap - a->flow;
752 }
753 }
754 else
755 {
756 a->flow += slack;
757 img->flow -= slack;
758 }
759 });
760 }
761
762
772 template <class Net>
774 {
776 arcs.for_each([](std::pair<void *, void *> p)
777 {
778 auto net_arc = static_cast<typename Net::Arc *>(p.first);
779 auto res_arc = static_cast<typename Rnet::Arc *>(p.second);
780 net_arc->flow = res_arc->flow;
781 });
782 }
783
784
861 template <FlowNetwork Net,
862 template <class> class Max_Flow_Algo = Ford_Fulkerson_Maximum_Flow>
863 std::tuple<size_t, double>
865 double it_factor = 0.4,
866 size_t step = 10)
867 {
868 Max_Flow_Algo<Net>()(net); // First compute maximum flow
869 net_detail::refuse_infinite_maximum_flow(net, "max_flow_min_cost_by_cycle_canceling()");
870
871 using Ftype = typename Net::Flow_Type;
872 using Rnet = Residual_Net<Ftype>;
873 constexpr bool floating = std::is_floating_point_v<Ftype>;
874 using Cost = std::conditional_t<floating, Rcost_With_Tolerance<Rnet>, Rcost<Rnet>>;
875 using Filt = std::conditional_t<floating, Res_Filt_With_Tolerance<Rnet>, Res_Filt<Rnet>>;
877
878 // Build residual network
879 Rnet rnet;
881 typename Rnet::Node *source = build_residual_net(net, rnet, arcs_map);
882
883 // With a floating flow, a relaxation must improve a distance by more
884 // than 4 n^2 epsilons of the largest cost, as a distance is a sum of
885 // up to n - 1 costs; and an arc has residual capacity if it has more
886 // than 1000 epsilons of the largest finite capacity or flow left, the
887 // tolerance of Network_Simplex
888 Cost cost;
889 Filt filt;
890 if constexpr (floating)
891 {
892 Ftype largest_cost{0}, largest_flow{0};
893 for (typename Net::Arc_Iterator it(net); it.has_curr(); it.next_ne())
894 {
895 auto a = it.get_curr();
896 if (const Ftype c = std::abs(a->cost); c < std::numeric_limits<Ftype>::max())
897 largest_cost = std::max(largest_cost, c);
898 if (not net_detail::without_capacity(a->cap))
899 largest_flow = std::max(largest_flow, std::abs(a->cap));
900 if (std::isfinite(a->flow))
901 largest_flow = std::max(largest_flow, std::abs(a->flow));
902 }
903 const Ftype n = Ftype(net.vsize()), e = std::numeric_limits<Ftype>::epsilon();
904 cost = Cost(4 * n * n * e * largest_cost);
905 filt = Filt(1000 * e * largest_flow);
906 }
907
908 size_t count = 0;
909 bool found_cycle = true;
910
911 // Main loop: find and cancel negative cycles
912 while (found_cycle)
913 {
914 // Search for negative cycle from source
915 auto [cycle, iterations] =
916 BF(rnet, cost, filt).search_negative_cycle(source, it_factor, step);
917
918 if (cycle.is_empty())
919 {
920 // No cycle found from source, try global search
921 auto [global_cycle, global_iter] =
922 BF(rnet, cost, filt).search_negative_cycle(it_factor, step);
923
924 if (global_cycle.is_empty())
925 found_cycle = false;
926 else
927 {
928 cancel_cycle(rnet, global_cycle);
929 ++count;
930 }
931 }
932 else
933 { // Update iteration factor based on when cycle was found
934 it_factor = static_cast<double>(iterations) / net.vsize();
935 cancel_cycle(rnet, cycle);
936 ++count;
937 }
938 }
939
940 // Transfer results back to original network
941 residual_to_net<Net>(arcs_map);
942
943 // The residues of rounding that the cycles leave go back, as those of
944 // the maximum flows: a slack of the arcs of larger flows left them on
945 // arcs of smaller ones, and a node of such residues lost its balance
947
948 return std::make_tuple(count, it_factor);
949 }
950
951
962 template <FlowNetwork Net,
963 template <class> class Max_Flow_Algo = Ford_Fulkerson_Maximum_Flow>
965 {
973 std::tuple<size_t, double> operator ()(Net & net,
974 const double it_factor = 0.4,
975 const size_t step = 10)
976 {
977 return max_flow_min_cost_by_cycle_canceling<Net, Max_Flow_Algo>
978 (net, it_factor, step);
979 }
980 };
981
982
993 template <class Net>
994 void print_net_cost(const Net & net, std::ostream & out)
995 {
996 long i = 0;
997 net.nodes().for_each([&i](typename Net::Node *p)
998 {
999 NODE_COUNTER(p) = i++;
1000 });
1001
1002 struct Show_Node
1003 {
1004 void operator ()(const Net &, typename Net::Node *p, std::ostream & o)
1005 {
1006 o << "label = \"(" << p->get_info() << "," << NODE_COUNTER(p) << ")\"";
1007 }
1008 };
1009
1010 struct Show_Arc
1011 {
1012 void operator ()(const Net &, typename Net::Arc *a, std::ostream & o)
1013 {
1014 o << "label = \"" << a->flow << "/" << a->cap << "/" << a->cost << "\"";
1015 }
1016 };
1017
1019 }
1020
1021
1031 template <class Net>
1033 std::ostream & out)
1034 {
1036
1037 long i = 0;
1038 net.nodes().for_each([&i](typename Rnet::Node *p)
1039 {
1040 NODE_COUNTER(p) = i++;
1041 });
1042
1043 struct Show_Node
1044 {
1045 void operator ()(const Rnet &, typename Rnet::Node *p, std::ostream & o)
1046 {
1047 o << "label = \"" << NODE_COUNTER(p) << "\"";
1048 }
1049 };
1050
1051 struct Show_Arc
1052 {
1053 void operator ()(const Rnet &, typename Rnet::Arc *a, std::ostream & o)
1054 {
1055 o << "label = \"" << a->flow << "/" << a->cap << "/" << a->cost << "\"";
1056 if (a->is_residual)
1057 o << " color = red";
1058 }
1059 };
1060
1062 Res_Filt<Rnet>>().digraph(net, out);
1063 }
1064
1065
1066 // =========================================================================
1067 // Network Simplex Algorithm Implementation
1068 // =========================================================================
1069
1080 template <class Net>
1081 using Feasible_Tree = std::tuple<DynList<typename Net::Arc *>,
1084
1085
1095 template <class Net>
1097 {
1098 using Arc = typename Net::Arc;
1099 DynList<Arc *> empty, full, partial;
1100
1101 for (typename Net::Arc_Iterator it(net); it.has_curr(); it.next_ne())
1102 {
1103 if (auto a = it.get_curr(); a->flow == 0)
1104 empty.append(a);
1105 else if (a->flow == a->cap)
1106 full.append(a);
1107 else
1108 partial.append(a);
1109 }
1110
1111 return std::make_tuple(std::move(empty), std::move(full), std::move(partial));
1112 }
1113
1114
1122 template <class Net>
1124 {
1126 for (typename Net::Arc_Iterator it(net); it.has_curr(); it.next_ne())
1127 if (auto a = it.get_curr(); a->flow > 0 and a->flow < a->cap)
1128 ret.append(a);
1129 return ret;
1130 }
1131
1132
1142 template <typename Ftype>
1144 {
1146 Ftype potential = 0;
1147
1149 void *parent = nullptr;
1150
1152 void *parent_arc = nullptr;
1153
1155 long depth = 0;
1156
1158 bool arc_from_parent = true;
1159
1161 long mark = 0;
1162 };
1163
1164
1170 enum class Simplex_Arc_State : unsigned char
1171 {
1172 Lower,
1173 Upper,
1174 Tree
1175 };
1176
1177
1183 template <typename Ftype>
1194
1195
1202 {
1203 size_t total_pivots = 0;
1204 size_t phase1_pivots = 0;
1205 size_t phase2_pivots = 0;
1207 size_t tree_arcs = 0;
1208 double phase1_time_ms = 0.0;
1209 double phase2_time_ms = 0.0;
1210 double total_time_ms = 0.0;
1212 size_t forced_into_tree = 0;
1213
1214 void reset() noexcept
1215 {
1216 total_pivots = 0;
1217 phase1_pivots = 0;
1218 phase2_pivots = 0;
1220 tree_arcs = 0;
1221 phase1_time_ms = 0.0;
1222 phase2_time_ms = 0.0;
1223 total_time_ms = 0.0;
1225 forced_into_tree = 0;
1226 }
1227 };
1228
1229
1288 template <FlowNetwork Net>
1290 {
1291 public:
1292 using Node = typename Net::Node;
1293 using Arc = typename Net::Arc;
1294 using Flow_Type = typename Net::Flow_Type;
1297
1298 private:
1304 Node *root = nullptr;
1305 size_t num_pivots = 0;
1306 long lca_mark = 0; // Counter for LCA marking
1308
1309 static constexpr Flow_Type Inf = std::numeric_limits<Flow_Type>::max();
1310
1311 // The tolerances of the comparisons of a floating flow, relative to the
1312 // data of the network: of the flows, 1000 epsilons of the largest
1313 // finite capacity or flow, and of the reduced costs, 1000 epsilons of
1314 // the largest cost. An absolute tolerance of 1000 epsilons left
1315 // unoptimized the costs and the capacities below 2.2e-13. An integer
1316 // flow compares exactly.
1319
1320 bool ran = false; // whether run() made the structures of the arcs
1321 bool unbounded = false; // whether the last cycle had no bound
1322
1327 static void move_flow(Arc *a, const Flow_Type d, const bool up) noexcept
1328 {
1329 if (up)
1330 a->flow += d;
1331 else
1332 a->flow -= d;
1333
1334 if constexpr (std::is_floating_point_v<Flow_Type>)
1335 {
1336 if (a->flow > a->cap)
1337 a->flow = a->cap;
1338 else if (a->flow < Flow_Type{0})
1339 a->flow = Flow_Type{0};
1340 }
1341 }
1342
1344 static bool without_capacity(const Arc *a) noexcept
1345 {
1346 return net_detail::without_capacity(a->cap);
1347 }
1348
1351 {
1352 if constexpr (std::is_floating_point_v<Flow_Type>)
1353 {
1354 Flow_Type largest_flow = 0, largest_cost = 0;
1355 for (typename Net::Arc_Iterator it(net); it.has_curr(); it.next_ne())
1356 {
1357 auto a = it.get_curr();
1358 if (not without_capacity(a))
1359 largest_flow = std::max(largest_flow, std::abs(a->cap));
1360 if (std::isfinite(a->flow))
1361 largest_flow = std::max(largest_flow, std::abs(a->flow));
1362 if (std::isfinite(a->cost))
1363 largest_cost = std::max(largest_cost, std::abs(a->cost));
1364 }
1365 const Flow_Type e = std::numeric_limits<Flow_Type>::epsilon() * 1000;
1366 flow_tol = e * largest_flow;
1367 cost_tol = e * largest_cost;
1368 }
1369 }
1370
1373 void ensure_ran(const char *member) const
1374 {
1375 ah_domain_error_if(not ran)
1376 << "Network_Simplex::" << member << "(): run() has not been called";
1377 }
1378
1384 bool feasible_flow() const
1385 {
1386 for (typename Net::Arc_Iterator it(net); it.has_curr(); it.next_ne())
1387 {
1388 auto a = it.get_curr();
1389 if (not a->check_arc())
1390 return false;
1391 if constexpr (std::is_floating_point_v<Flow_Type>)
1392 if (not std::isfinite(a->flow))
1393 return false;
1394 }
1395
1396 const auto source = net.get_source(), sink = net.get_sink();
1397 for (typename Net::Node_Iterator it(net); it.has_curr(); it.next_ne())
1398 {
1399 auto p = it.get_curr();
1400 if (p == source or p == sink)
1401 continue;
1402 const auto in = net.get_in_flow(p), out = net.get_out_flow(p);
1403 if (not (std::abs(in - out) <= Net::node_tolerance(in, out)))
1404 return false;
1405 }
1406 return true;
1407 }
1408
1412 size_t expected_tree_arcs() const
1413 {
1414 if (not ran)
1415 return 0;
1416
1417 size_t roots = 0;
1418 for (typename Net::Node_Iterator it(net); it.has_curr(); it.next_ne())
1419 if (ninfo(it.get_curr()).depth == 0)
1420 ++roots;
1421 return net.vsize() - roots;
1422 }
1423
1425 Node_Info &ninfo(Node *p) { return node_info(node_to_idx.find(p)); }
1426
1428 const Node_Info &ninfo(Node *p) const { return node_info(node_to_idx.find(p)); }
1429
1431 Arc_Info &ainfo(Arc *a) { return arc_info(arc_to_idx.find(a)); }
1432
1434 const Arc_Info &ainfo(Arc *a) const { return arc_info(arc_to_idx.find(a)); }
1435
1437 Node *parent(Node *p) const { return static_cast<Node *>(ninfo(p).parent); }
1438
1440 Arc *parent_arc(Node *p) const { return static_cast<Arc *>(ninfo(p).parent_arc); }
1441
1443 long depth(Node *p) const { return ninfo(p).depth; }
1444
1446 Flow_Type potential(Node *p) const { return ninfo(p).potential; }
1447
1453 {
1454 auto src = static_cast<Node *>(a->src_node);
1455 auto tgt = static_cast<Node *>(a->tgt_node);
1456 return a->cost - ninfo(src).potential + ninfo(tgt).potential;
1457 }
1458
1461 {
1462 node_info.cut(0);
1463 arc_info.cut(0);
1464 node_to_idx.empty();
1465 arc_to_idx.empty();
1466
1467 // Map nodes to indices
1468 size_t idx = 0;
1469 for (typename Net::Node_Iterator it(net); it.has_curr(); it.next_ne())
1470 {
1471 auto p = it.get_curr();
1472 node_to_idx.insert(p, idx);
1473 node_info.touch(idx) = Node_Info{};
1474 ++idx;
1475 }
1476
1477 // Map arcs to indices - DO NOT classify yet, let build_spanning_tree handle it
1478 idx = 0;
1479 for (typename Net::Arc_Iterator it(net); it.has_curr(); it.next_ne())
1480 {
1481 auto a = it.get_curr();
1482 arc_to_idx.insert(a, idx);
1483 arc_info.touch(idx) = Arc_Info{};
1484 // Initially mark all arcs as Lower; build_spanning_tree will fix this
1485 arc_info(idx).state = Simplex_Arc_State::Lower;
1486 ++idx;
1487 }
1488 }
1489
1491 bool is_partial_flow(Arc *a) const
1492 {
1493 return a->flow > flow_tol and a->flow < a->cap - flow_tol;
1494 }
1495
1507 {
1508 root = net.get_source();
1509
1510 // Reset all nodes
1511 for (typename Net::Node_Iterator it(net); it.has_curr(); it.next_ne())
1512 {
1513 auto p = it.get_curr();
1514 auto &ni = ninfo(p);
1515 ni.parent = nullptr;
1516 ni.parent_arc = nullptr;
1517 ni.depth = -1;
1518 ni.potential = 0;
1519 ni.mark = 0;
1520 }
1521
1522 // Reset all arcs to Lower
1523 for (typename Net::Arc_Iterator it(net); it.has_curr(); it.next_ne())
1524 ainfo(it.get_curr()).state = Simplex_Arc_State::Lower;
1525
1526 const size_t total_nodes = net.vsize();
1528 queue.put(root);
1529 ninfo(root).depth = 0;
1530 ninfo(root).potential = 0;
1531
1532 size_t nodes_in_tree = 1;
1533
1534 // Helper to add a node to tree via an arc
1535 auto add_to_tree = [&](Node *p, Arc *a, Node *other) -> bool {
1536 if (ninfo(other).depth >= 0)
1537 return false; // Already in tree
1538
1539 const auto &pi = ninfo(p);
1540 auto &oi = ninfo(other);
1541 oi.parent = p;
1542 oi.parent_arc = a;
1543 oi.depth = pi.depth + 1;
1544
1545 auto src = static_cast<Node *>(a->src_node);
1546 if (src == p)
1547 {
1548 oi.arc_from_parent = true;
1549 oi.potential = pi.potential - a->cost;
1550 }
1551 else
1552 {
1553 oi.arc_from_parent = false;
1554 oi.potential = pi.potential + a->cost;
1555 }
1556
1557 ainfo(a).state = Simplex_Arc_State::Tree;
1558 ++nodes_in_tree;
1559 queue.put(other);
1560 return true;
1561 };
1562
1563 // Build tree with multiple priority passes, from the nodes in queue
1564 auto grow = [&]
1565 {
1566 while (not queue.is_empty() and nodes_in_tree < total_nodes)
1567 {
1568 auto p = queue.get();
1569
1570 // Collect all candidate arcs with priorities
1571 struct ArcPriority {
1572 Arc* arc;
1573 Node* other;
1574 int priority; // 0 = partial flow, 1 = with flow, 2 = no flow
1575 };
1576 DynList<ArcPriority> candidates;
1577
1578 for (Node_Arc_Iterator<Net> it(p); it.has_curr(); it.next_ne())
1579 {
1580 auto a = it.get_curr();
1581 auto other = net.get_connected_node(a, p);
1582 if (ninfo(other).depth >= 0)
1583 continue; // Already in tree
1584
1585 int prio;
1586 if (is_partial_flow(a))
1587 prio = 0; // Highest priority
1588 else if (a->flow > flow_tol)
1589 prio = 1; // Medium priority
1590 else
1591 prio = 2; // Lowest priority
1592
1593 candidates.append(ArcPriority{a, other, prio});
1594 }
1595
1596 // Sort by priority (partial flow first)
1597 // Since DynList doesn't have sort, process in order
1598 for (int target_prio = 0; target_prio <= 2; ++target_prio)
1599 {
1600 for (auto& ap : candidates)
1601 {
1602 if (ap.priority == target_prio)
1603 add_to_tree(p, ap.arc, ap.other);
1604 }
1605 }
1606 }
1607
1608 };
1609 grow();
1610
1611 // The nodes that the tree from the source does not reach, as those
1612 // of a flow apart from it, get trees of their own: else a cycle
1613 // through them would have no common ancestor
1614 for (typename Net::Node_Iterator it(net);
1615 it.has_curr() and nodes_in_tree < total_nodes; it.next_ne())
1616 if (auto r = it.get_curr(); ninfo(r).depth < 0)
1617 {
1618 ninfo(r).depth = 0;
1619 ninfo(r).potential = 0;
1620 ++nodes_in_tree;
1621 queue.put(r);
1622 grow();
1623 }
1624
1625 // Classify remaining non-tree arcs
1626 for (typename Net::Arc_Iterator it(net); it.has_curr(); it.next_ne())
1627 {
1628 auto a = it.get_curr();
1629 if (ainfo(a).state == Simplex_Arc_State::Tree)
1630 continue;
1631
1632 if (a->flow <= flow_tol)
1633 ainfo(a).state = Simplex_Arc_State::Lower;
1634 else if (a->flow >= a->cap - flow_tol)
1635 ainfo(a).state = Simplex_Arc_State::Upper;
1636 else
1637 {
1638 // Partial flow arc NOT in tree - classify based on reduced cost
1639 auto rc = reduced_cost(a);
1640 ainfo(a).state = (rc < -cost_tol) ?
1641 Simplex_Arc_State::Upper : Simplex_Arc_State::Lower;
1642 }
1643 }
1644 }
1645
1663 {
1664 Arc *best = nullptr;
1665 Flow_Type best_violation = cost_tol; // Threshold to avoid tiny violations
1666 bool best_is_increase = true;
1667
1668 for (typename Net::Arc_Iterator it(net); it.has_curr(); it.next_ne())
1669 {
1670 auto a = it.get_curr();
1671 auto &ai = ainfo(a);
1672
1673 if (ai.state == Simplex_Arc_State::Tree)
1674 continue;
1675
1676 if (ai.skip) // Skip arcs that failed in this round
1677 continue;
1678
1679 const auto rc = reduced_cost(a);
1680 const bool can_increase = (a->flow < a->cap - flow_tol);
1681 const bool can_decrease = (a->flow > flow_tol);
1682
1683 // Check FORWARD direction: increase flow (rc < 0 is good)
1684 if (can_increase and rc < -best_violation)
1685 {
1686 best_violation = -rc;
1687 best = a;
1688 best_is_increase = true;
1689 }
1690
1691 // Check BACKWARD direction: decrease flow (rc > 0 is good)
1692 // This is equivalent to using the "reverse arc" in residual network
1693 if (can_decrease and rc > best_violation)
1694 {
1695 best_violation = rc;
1696 best = a;
1697 best_is_increase = false;
1698 }
1699 }
1700
1701 // Update state based on direction
1702 if (best != nullptr)
1703 {
1704 ainfo(best).state = best_is_increase ?
1705 Simplex_Arc_State::Lower : Simplex_Arc_State::Upper;
1706 }
1707
1708 return best;
1709 }
1710
1720 {
1721 ++lca_mark; // Use new mark
1722
1723 // Mark path from u to root
1724 Node *p = u;
1725 while (p != nullptr)
1726 {
1727 ninfo(p).mark = lca_mark;
1728 p = parent(p);
1729 }
1730
1731 // Walk from v towards root until we hit a marked node
1732 p = v;
1733 while (p != nullptr and ninfo(p).mark != lca_mark)
1734 p = parent(p);
1735
1736 return p;
1737 }
1738
1757 Arc *&leaving, bool &leaving_goes_lower)
1758 {
1759 auto u = static_cast<Node *>(entering->src_node);
1760 auto v = static_cast<Node *>(entering->tgt_node);
1761 Node *lca = find_lca(u, v);
1762
1763 assert(lca != nullptr);
1764
1765 // Determine if we're increasing or decreasing flow on entering arc
1766 const bool increase_on_entering = (ainfo(entering).state == Simplex_Arc_State::Lower);
1767
1768 // Initialize with entering arc's slack
1769 if (increase_on_entering)
1770 delta = entering->cap - entering->flow;
1771 else
1772 delta = entering->flow;
1773
1774 leaving = entering;
1775 leaving_goes_lower = increase_on_entering;
1776
1777 // Walk from u to lca
1778 // Direction: lca → ... → u (following tree direction)
1779 // If increase_on_entering, flow increases in arcs pointing towards u
1780 Node *p = u;
1781 while (p != lca)
1782 {
1783 Arc *pa = parent_arc(p);
1784 bool from_parent = ninfo(p).arc_from_parent;
1785 // from_parent=true means arc goes parent→child (towards u)
1786 // So flow increases when both are true or both are false
1787 bool flow_increases = (increase_on_entering == from_parent);
1788
1789 Flow_Type slack;
1790 bool goes_lower;
1791
1792 if (flow_increases)
1793 {
1794 slack = pa->cap - pa->flow;
1795 goes_lower = false;
1796 }
1797 else
1798 {
1799 slack = pa->flow;
1800 goes_lower = true;
1801 }
1802
1803 // Prefer arc that goes to lower bound in case of tie (Bland's rule variant)
1804 if (slack < delta or (slack == delta and goes_lower and not leaving_goes_lower))
1805 {
1806 delta = slack;
1807 leaving = pa;
1808 leaving_goes_lower = goes_lower;
1809 }
1810
1811 p = parent(p);
1812 }
1813
1814 // Walk from v to lca
1815 // Direction: v → ... → lca (against tree direction)
1816 // If increase_on_entering, flow decreases in arcs pointing towards v
1817 p = v;
1818 while (p != lca)
1819 {
1820 Arc *pa = parent_arc(p);
1821 bool from_parent = ninfo(p).arc_from_parent;
1822 // from_parent=true means arc goes parent→child (towards v)
1823 // Since we go against tree direction, flow decreases when from_parent=true
1824 bool flow_increases = (increase_on_entering != from_parent);
1825
1826 Flow_Type slack;
1827 bool goes_lower;
1828
1829 if (flow_increases)
1830 {
1831 slack = pa->cap - pa->flow;
1832 goes_lower = false;
1833 }
1834 else
1835 {
1836 slack = pa->flow;
1837 goes_lower = true;
1838 }
1839
1840 if (slack < delta or (slack == delta and goes_lower and not leaving_goes_lower))
1841 {
1842 delta = slack;
1843 leaving = pa;
1844 leaving_goes_lower = goes_lower;
1845 }
1846
1847 p = parent(p);
1848 }
1849
1850 // Whether the leaving arc goes to its capacity: the entering arc
1851 // that leaves goes to the bound to which it moves, which
1852 // leaving_goes_lower does not tell for it
1853 const bool to_cap = leaving == entering ? increase_on_entering : not leaving_goes_lower;
1854
1855 // A cycle that no arc bounds, of arcs without capacity, has no
1856 // pivot; in Phase II, where it lowers the cost, the program is
1857 // unbounded, and run() throws
1858 unbounded = to_cap and without_capacity(leaving);
1859 if (unbounded)
1860 return false;
1861
1862 // Allow degenerate pivots (delta=0) if we found a valid leaving arc
1863 // This restructures the tree without changing flow, potentially enabling
1864 // future pivots that were previously blocked.
1865 if (delta >= 0 and leaving != nullptr)
1866 {
1867 // Update entering arc
1868 move_flow(entering, delta, increase_on_entering);
1869
1870 // Update u-side (same logic as above)
1871 p = u;
1872 while (p != lca)
1873 {
1874 Arc *pa = parent_arc(p);
1875 bool from_parent = ninfo(p).arc_from_parent;
1876 move_flow(pa, delta, increase_on_entering == from_parent);
1877 p = parent(p);
1878 }
1879
1880 // Update v-side (same logic as above)
1881 p = v;
1882 while (p != lca)
1883 {
1884 Arc *pa = parent_arc(p);
1885 bool from_parent = ninfo(p).arc_from_parent;
1886 move_flow(pa, delta, increase_on_entering != from_parent);
1887 p = parent(p);
1888 }
1889
1890 // The leaving arc reaches its bound, exactly
1891 if constexpr (std::is_floating_point_v<Flow_Type>)
1892 leaving->flow = to_cap ? leaving->cap : Flow_Type{0};
1893
1894 return true; // Successful pivot (including degenerate with delta=0)
1895 }
1896
1897 return false; // Failed - no valid cycle found
1898 }
1899
1909 ALEPH_FLATTEN void pivot_tree(Arc *entering, Arc *leaving, bool leaving_goes_lower)
1910 {
1911 // Handle degenerate pivot where entering = leaving
1912 if (entering == leaving)
1913 {
1914 auto &ai = ainfo(entering);
1915 ai.state = leaving_goes_lower ?
1916 Simplex_Arc_State::Lower : Simplex_Arc_State::Upper;
1917 return;
1918 }
1919
1920 // Set leaving arc state
1921 ainfo(leaving).state = leaving_goes_lower ?
1922 Simplex_Arc_State::Lower : Simplex_Arc_State::Upper;
1923
1924 // Set entering arc as tree arc
1925 ainfo(entering).state = Simplex_Arc_State::Tree;
1926
1927 // Find which end of leaving arc becomes the new subtree root
1928 // One of the endpoints must have leaving as its parent_arc
1929 auto leaving_src = static_cast<Node *>(leaving->src_node);
1930 auto leaving_tgt = static_cast<Node *>(leaving->tgt_node);
1931
1932 Node *subtree_root;
1933 bool src_has_leaving = (parent_arc(leaving_src) == leaving);
1934 bool tgt_has_leaving = (parent_arc(leaving_tgt) == leaving);
1935
1936 if (not src_has_leaving and not tgt_has_leaving)
1937 return; // Invalid pivot
1938
1939 if (src_has_leaving)
1940 subtree_root = leaving_src;
1941 else
1942 subtree_root = leaving_tgt;
1943
1944 auto entering_src = static_cast<Node *>(entering->src_node);
1945 auto entering_tgt = static_cast<Node *>(entering->tgt_node);
1946
1947 // Determine which end of entering arc is in the subtree
1948 Node *in_subtree, *out_subtree;
1949 {
1950 Node *p = entering_src;
1951 bool src_in = false;
1952 while (p != nullptr)
1953 {
1954 if (p == subtree_root)
1955 {
1956 src_in = true;
1957 break;
1958 }
1959 p = parent(p);
1960 }
1961
1962 if (src_in)
1963 {
1964 in_subtree = entering_src;
1965 out_subtree = entering_tgt;
1966 }
1967 else
1968 {
1969 in_subtree = entering_tgt;
1970 out_subtree = entering_src;
1971 }
1972 }
1973
1974 // Reverse path from subtree_root to in_subtree
1975 DynList<Node *> path;
1976 Node *p = in_subtree;
1977 while (p != subtree_root and p != nullptr)
1978 {
1979 path.insert(p); // Prepend
1980 p = parent(p);
1981 }
1982 if (p == subtree_root)
1983 path.insert(subtree_root);
1984 else
1985 return; // in_subtree not descendant of subtree_root
1986
1987 // Reverse parent relationships along the path
1988 // Path is: [subtree_root, X, Y, ..., in_subtree] (built by prepending)
1989 //
1990 // Original tree (parent pointers):
1991 // in_subtree --> Y --> X --> subtree_root --> (via leaving to rest of tree)
1992 // (each node's parent is to its right)
1993 //
1994 // After reversal (parent pointers):
1995 // subtree_root --> X --> Y --> in_subtree --> out_subtree --> ...
1996 // (each node's parent is to its right, but in_subtree connects via entering)
1997 //
1998 // For each pair (curr, next) in [subtree_root, X, Y, ...]:
1999 // - Original: next.parent = curr, so parent_arc(next) = arc between them
2000 // - New: curr.parent = next, using the same arc
2001 for (auto it = path.get_it(); it.has_curr(); )
2002 {
2003 Node *curr = it.get_curr();
2004 it.next();
2005
2006 if (not it.has_curr())
2007 break;
2008
2009 Node *next = it.get_curr();
2010
2011 // Original: next was child of curr, so parent_arc(next) = arc between curr and next
2012 Arc *arc_between = parent_arc(next);
2013 auto &curr_info = ninfo(curr);
2014 curr_info.parent = next;
2015 curr_info.parent_arc = arc_between;
2016
2017 auto arc_src = static_cast<Node *>(arc_between->src_node);
2018 curr_info.arc_from_parent = (arc_src == next);
2019 }
2020
2021 // Link in_subtree to out_subtree via entering arc
2022 auto &sub_info = ninfo(in_subtree);
2023 sub_info.parent = out_subtree;
2024 sub_info.parent_arc = entering;
2025 sub_info.arc_from_parent = (static_cast<Node *>(entering->src_node) == out_subtree);
2026
2027 // Update depths and potentials using BFS from in_subtree
2029 queue.put(in_subtree);
2030
2031 auto &out_info = ninfo(out_subtree);
2032 sub_info.depth = out_info.depth + 1;
2033 if (sub_info.arc_from_parent)
2034 sub_info.potential = out_info.potential - entering->cost;
2035 else
2036 sub_info.potential = out_info.potential + entering->cost;
2037
2038 while (not queue.is_empty())
2039 {
2040 Node *curr = queue.get();
2041 const auto &curr_info = ninfo(curr);
2042
2043 // Find children of curr (nodes whose parent is curr)
2044 for (typename Net::Node_Iterator nit(net); nit.has_curr(); nit.next_ne())
2045 {
2046 Node *child = nit.get_curr();
2047 if (child == curr)
2048 continue;
2049
2050 if (parent(child) != curr)
2051 continue;
2052
2053 auto &ci = ninfo(child);
2054 ci.depth = curr_info.depth + 1;
2055
2056 Arc *pa = parent_arc(child);
2057 if (ci.arc_from_parent)
2058 ci.potential = curr_info.potential - pa->cost;
2059 else
2060 ci.potential = curr_info.potential + pa->cost;
2061
2062 queue.put(child);
2063 }
2064 }
2065 }
2066
2067 public:
2072 explicit Network_Simplex(Net &network) : net(network) {}
2073
2086 [[deprecated("Network_Simplex supports no lower bound but 0: it goes in 8.0.0")]]
2087 void set_lower_bound([[maybe_unused]] Arc *a, Flow_Type lower_bound)
2088 {
2090 << "Network_Simplex::set_lower_bound(): no lower bound but 0 is supported";
2091 }
2092
2100 [[deprecated("Network_Simplex supports no lower bound but 0: it goes in 8.0.0")]]
2101 [[nodiscard]] Flow_Type get_lower_bound([[maybe_unused]] Arc *a) const
2102 {
2103 return Flow_Type{0};
2104 }
2105
2114 [[nodiscard]] bool is_at_lower_bound(Arc *a) const
2115 {
2116 return std::abs(a->flow) <= flow_tol;
2117 }
2118
2127 [[nodiscard]] bool is_at_upper_bound(Arc *a) const
2128 {
2129 return std::abs(a->flow - a->cap) <= flow_tol;
2130 }
2131
2137 [[nodiscard]] Flow_Type residual_capacity(Arc *a) const
2138 {
2139 return a->cap - a->flow;
2140 }
2141
2150 [[deprecated("every lower bound of Network_Simplex is 0: use the flow; it goes in 8.0.0")]]
2151 [[nodiscard]] Flow_Type residual_lower(Arc *a) const
2152 {
2153 return a->flow;
2154 }
2155
2156
2157 public:
2185 size_t run([[maybe_unused]] Flow_Type unused = 0)
2186 {
2187 ah_domain_error_if(not (net.is_single_source() and net.is_single_sink()))
2188 << "Network is not single source and single sink";
2189 ah_domain_error_if(not feasible_flow())
2190 << "Network_Simplex::run(): the flow of the network is not feasible";
2191
2192 stats.reset();
2193 auto total_start = std::chrono::high_resolution_clock::now();
2194
2195 set_tolerances();
2196 init_structures();
2198 ran = true;
2199
2200 // Count initial partial-flow arcs
2201 stats.initial_partial_arcs = count_non_tree_partial_arcs();
2202
2203 // PHASE I: Establish valid basic feasible solution
2204 auto phase1_start = std::chrono::high_resolution_clock::now();
2205 size_t phase1_pivots = force_partial_arcs_into_tree();
2206 auto phase1_end = std::chrono::high_resolution_clock::now();
2207 stats.phase1_time_ms = std::chrono::duration<double, std::milli>(
2208 phase1_end - phase1_start).count();
2209 stats.phase1_pivots = phase1_pivots;
2210 stats.forced_into_tree = phase1_pivots;
2211
2212 // PHASE II: Optimize cost using standard Network Simplex
2213 auto phase2_start = std::chrono::high_resolution_clock::now();
2214 num_pivots = phase1_pivots;
2215 size_t failed_attempts = 0;
2216 const size_t max_pivots = net.vsize() * net.esize() * 10 + 1000;
2217 const size_t max_failures = net.esize() + 1;
2218
2219 bool optimal = false;
2220 while (num_pivots < max_pivots and failed_attempts < max_failures)
2221 {
2222 Arc *entering = find_entering_arc();
2223
2224 if (entering == nullptr)
2225 {
2226 // Without an arc that failed its pivot, which no arc takes
2227 optimal = failed_attempts == 0;
2228 break;
2229 }
2230
2231 Flow_Type delta;
2232 Arc *leaving;
2233 bool leaving_goes_lower;
2234
2235 bool success = augment_and_find_leaving(entering, delta, leaving, leaving_goes_lower);
2236
2237 // The residues of rounding of the pivots made go back before
2238 // the exception, as at the end: they stayed in the nodes
2239 if (unbounded)
2240 {
2241 net_detail::return_dust(net, net.get_source(), net.get_sink());
2243 << "Network_Simplex::run(): the program is unbounded: a cycle of "
2244 << "negative cost through arcs without capacity";
2245 }
2246
2247 if (success)
2248 {
2249 if (delta <= flow_tol) // zero, for an integer flow
2250 ++stats.degenerate_pivots;
2251
2252 pivot_tree(entering, leaving, leaving_goes_lower);
2253 ++num_pivots;
2254 failed_attempts = 0;
2255
2256 // Reset skip flags after successful pivot
2257 for (typename Net::Arc_Iterator ait(net); ait.has_curr(); ait.next_ne())
2258 ainfo(ait.get_curr()).skip = false;
2259 }
2260 else
2261 {
2262 ainfo(entering).skip = true;
2263 ++failed_attempts;
2264 }
2265 }
2266
2267 // The pivots of a floating flow leave residues of rounding, as the
2268 // arc that leaves the tree takes its bound exactly: dust that ends
2269 // in a node, which check_node() takes as a loss of its balance
2270 net_detail::return_dust(net, net.get_source(), net.get_sink());
2271
2272 auto phase2_end = std::chrono::high_resolution_clock::now();
2273 stats.phase2_time_ms = std::chrono::duration<double, std::milli>(
2274 phase2_end - phase2_start).count();
2275 stats.phase2_pivots = num_pivots - phase1_pivots;
2276
2277 auto total_end = std::chrono::high_resolution_clock::now();
2278 stats.total_time_ms = std::chrono::duration<double, std::milli>(
2279 total_end - total_start).count();
2280 stats.total_pivots = num_pivots;
2281
2282 // Count tree arcs
2283 stats.tree_arcs = 0;
2284 for (typename Net::Arc_Iterator it(net); it.has_curr(); it.next_ne())
2285 if (ainfo(it.get_curr()).state == Simplex_Arc_State::Tree)
2286 ++stats.tree_arcs;
2287
2288 // The bounds of the pivots ended the loop without the optimum, which
2289 // it hid
2290 ah_runtime_error_if(not optimal)
2291 << "Network_Simplex::run(): the cost is not optimal after "
2292 << num_pivots << " pivots";
2293
2294 return num_pivots;
2295 }
2296
2298 [[nodiscard]] size_t get_num_pivots() const { return num_pivots; }
2299
2301 [[nodiscard]] const NetworkSimplexStats & get_stats() const noexcept { return stats; }
2302
2304 void print_stats() const
2305 {
2306 std::cout << "=== Network Simplex Statistics ===\n"
2307 << "Total pivots: " << stats.total_pivots << "\n"
2308 << " Phase I pivots: " << stats.phase1_pivots << "\n"
2309 << " Phase II pivots: " << stats.phase2_pivots << "\n"
2310 << " Degenerate pivots: " << stats.degenerate_pivots << "\n"
2311 << "Tree arcs: " << stats.tree_arcs << " (expected " << expected_tree_arcs() << ")\n"
2312 << "Initial partial-flow arcs: " << stats.initial_partial_arcs << "\n"
2313 << "Arcs forced into tree: " << stats.forced_into_tree << "\n"
2314 << "Timing:\n"
2315 << " Phase I: " << stats.phase1_time_ms << " ms\n"
2316 << " Phase II: " << stats.phase2_time_ms << " ms\n"
2317 << " Total: " << stats.total_time_ms << " ms\n";
2318 }
2319
2333 {
2334 ensure_ran("force_partial_arcs_into_tree");
2335 size_t forced_pivots = 0;
2336 bool made_progress = true;
2337
2338 while (made_progress)
2339 {
2340 made_progress = false;
2341
2342 // Find a non-tree arc with partial flow
2343 for (typename Net::Arc_Iterator it(net); it.has_curr(); it.next_ne())
2344 {
2345 auto a = it.get_curr();
2346 if (ainfo(a).state == Simplex_Arc_State::Tree)
2347 continue;
2348
2349 if (not is_partial_flow(a))
2350 continue;
2351
2352 // Found a partial-flow arc not in tree - force it in
2353 // Mark it as Lower (to increase flow direction)
2354 ainfo(a).state = Simplex_Arc_State::Lower;
2355
2356 Flow_Type delta;
2357 Arc *leaving;
2358 bool leaving_goes_lower;
2359
2360 // Try to find a valid cycle and leaving arc
2361 bool success = augment_and_find_leaving(a, delta, leaving, leaving_goes_lower);
2362
2363 if (success and leaving != nullptr and leaving != a)
2364 {
2365 // Verify leaving arc is in tree
2366 if (ainfo(leaving).state != Simplex_Arc_State::Tree)
2367 {
2368 ainfo(a).state = Simplex_Arc_State::Lower;
2369 continue;
2370 }
2371
2372 pivot_tree(a, leaving, leaving_goes_lower);
2373 ++forced_pivots;
2374 made_progress = true;
2375 break;
2376 }
2377 else
2378 {
2379 // Try the other direction (Upper = decrease flow)
2380 ainfo(a).state = Simplex_Arc_State::Upper;
2381 success = augment_and_find_leaving(a, delta, leaving, leaving_goes_lower);
2382
2383 if (success and leaving != nullptr and leaving != a)
2384 {
2385 pivot_tree(a, leaving, leaving_goes_lower);
2386 ++forced_pivots;
2387 made_progress = true;
2388 break;
2389 }
2390 else
2391 {
2392 // Cannot add this arc - restore to appropriate bound
2393 if (a->flow <= flow_tol)
2394 ainfo(a).state = Simplex_Arc_State::Lower;
2395 else if (a->flow >= a->cap - flow_tol)
2396 ainfo(a).state = Simplex_Arc_State::Upper;
2397 else
2398 ainfo(a).state = Simplex_Arc_State::Lower; // Should not happen
2399 }
2400 }
2401 }
2402 }
2403
2404 return forced_pivots;
2405 }
2406
2416 {
2417 ensure_ran("is_valid_basic_solution");
2418 for (typename Net::Arc_Iterator it(net); it.has_curr(); it.next_ne())
2419 {
2420 auto a = it.get_curr();
2421 if (ainfo(a).state == Simplex_Arc_State::Tree)
2422 continue;
2423
2424 // Non-tree arc must be at bounds
2425 if (is_partial_flow(a))
2426 return false;
2427 }
2428 return true;
2429 }
2430
2433 {
2434 ensure_ran("count_non_tree_partial_arcs");
2435 size_t count = 0;
2436 for (typename Net::Arc_Iterator it(net); it.has_curr(); it.next_ne())
2437 {
2438 auto a = it.get_curr();
2439 if (ainfo(a).state != Simplex_Arc_State::Tree and is_partial_flow(a))
2440 ++count;
2441 }
2442 return count;
2443 }
2444
2453 {
2454 ensure_ran("verify_tree_reduced_costs");
2455 for (typename Net::Arc_Iterator it(net); it.has_curr(); it.next_ne())
2456 {
2457 auto a = it.get_curr();
2458 if (ainfo(a).state != Simplex_Arc_State::Tree)
2459 continue;
2460
2461 auto rc = reduced_cost(a);
2462 if (std::abs(rc) > 100 * cost_tol) // Allow small tolerance
2463 return false;
2464 }
2465 return true;
2466 }
2467
2472 [[nodiscard]] bool verify_tree_integrity() const
2473 {
2474 ensure_ran("verify_tree_integrity");
2475 for (typename Net::Node_Iterator it(net); it.has_curr(); it.next_ne())
2476 {
2477 auto p = it.get_curr();
2478 if (p == root or ninfo(p).depth == 0)
2479 continue; // a root of the trees
2480
2481 auto pa = parent_arc(p);
2482 if (pa == nullptr)
2483 return false;
2484
2485 if (ainfo(pa).state != Simplex_Arc_State::Tree)
2486 return false;
2487 }
2488 return true;
2489 }
2490
2493 {
2494 ensure_ran("print_diagnostics");
2495 std::cout << "\n=== Network Simplex Diagnostics ===\n";
2496
2497 // Count arc types
2498 size_t tree_arcs = 0, lower_arcs = 0, upper_arcs = 0;
2499 for (typename Net::Arc_Iterator it(net); it.has_curr(); it.next_ne())
2500 {
2501 switch (ainfo(it.get_curr()).state)
2502 {
2503 case Simplex_Arc_State::Tree: ++tree_arcs; break;
2504 case Simplex_Arc_State::Lower: ++lower_arcs; break;
2505 case Simplex_Arc_State::Upper: ++upper_arcs; break;
2506 }
2507 }
2508
2509 std::cout << "Arcs: Tree=" << tree_arcs << " Lower=" << lower_arcs
2510 << " Upper=" << upper_arcs << " Total=" << net.esize() << "\n";
2511 std::cout << "Expected tree arcs: " << expected_tree_arcs() << "\n";
2512
2513 // Verify tree reduced costs
2514 bool tree_rc_ok = verify_tree_reduced_costs();
2515 std::cout << "Tree arcs rc=0: " << (tree_rc_ok ? "YES" : "NO") << "\n";
2516
2517 // Check for optimality violations
2518 size_t violations = 0;
2519 for (typename Net::Arc_Iterator it(net); it.has_curr(); it.next_ne())
2520 {
2521 auto a = it.get_curr();
2522 auto state = ainfo(a).state;
2523 auto rc = reduced_cost(a);
2524
2525 if (state == Simplex_Arc_State::Lower)
2526 {
2527 // Lower: flow=0, can increase. Optimal if rc >= 0
2528 if (rc < -cost_tol and a->flow < a->cap - flow_tol)
2529 {
2530 ++violations;
2531 std::cout << " VIOLATION: Lower arc with rc=" << rc
2532 << " flow=" << a->flow << "/" << a->cap << "\n";
2533 }
2534 }
2535 else if (state == Simplex_Arc_State::Upper)
2536 {
2537 // Upper: flow=cap, can decrease. Optimal if rc <= 0
2538 if (rc > cost_tol and a->flow > flow_tol)
2539 {
2540 ++violations;
2541 std::cout << " VIOLATION: Upper arc with rc=" << rc
2542 << " flow=" << a->flow << "/" << a->cap << "\n";
2543 }
2544 }
2545 }
2546
2547 std::cout << "Optimality violations: " << violations << "\n";
2548 std::cout << "==================================\n";
2549 }
2550 };
2551
2552
2599 template <FlowNetwork Net,
2600 template <class> class Max_Flow_Algo = Ford_Fulkerson_Maximum_Flow>
2602 {
2603 Max_Flow_Algo<Net>()(net); // First compute maximum flow
2604 net_detail::refuse_infinite_maximum_flow(net, "max_flow_min_cost_by_network_simplex()");
2605 Network_Simplex<Net> simplex(net);
2606 return simplex.run();
2607 }
2608
2609
2618 template <FlowNetwork Net,
2619 template <class> class Max_Flow_Algo = Ford_Fulkerson_Maximum_Flow>
2621 {
2627 size_t operator ()(Net & net)
2628 {
2629 return max_flow_min_cost_by_network_simplex<Net, Max_Flow_Algo>(net);
2630 }
2631 };
2632
2633} // end namespace Aleph
2634
2635# endif // TPL_NETCOST_H
Bellman-Ford algorithm for single-source shortest paths.
Exception handling system with formatted messages for Aleph-w.
#define ah_domain_error()
Throws std::domain_error unconditionally.
Definition ah-errors.H:702
#define ah_domain_error_if(C)
Throws std::domain_error if condition holds.
Definition ah-errors.H:670
#define ah_runtime_error_if(C)
Throws std::runtime_error if condition holds.
Definition ah-errors.H:415
C++20 concepts for the protocol shared by graph algorithms.
WeightedDigraph::Arc Arc
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
Dynamic queue of elements of generic type T based on single linked list.
T & put(const T &data)
The type of element.
T get()
Remove the oldest item of the queue.
bool is_empty() const noexcept
Return true if this is empty.
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
T & append(const T &item)
Definition htlist.H:1362
T & insert(const T &item)
Definition htlist.H:1308
Generic key-value map implemented on top of a binary search tree.
void next_ne() noexcept(shows_ne)
Advances the iterator to the next filtered element, as next() does.
Network Simplex algorithm for minimum cost flow.
Flow_Type residual_lower(Arc *a) const
Get residual lower (room to decrease flow).
const Arc_Info & ainfo(Arc *a) const
Get arc info const reference.
Arc * parent_arc(Node *p) const
Get parent arc.
static void move_flow(Arc *a, const Flow_Type d, const bool up) noexcept
Add d to the flow of a, if up, or take it away.
Arc * find_entering_arc()
Find entering arc using most negative reduced cost.
size_t get_num_pivots() const
Return number of pivots performed in last run.
bool augment_and_find_leaving(Arc *entering, Flow_Type &delta, Arc *&leaving, bool &leaving_goes_lower)
Augment flow around the cycle and find leaving arc.
bool feasible_flow() const
Whether the flow of the network is feasible: finite and within the bounds of each arc,...
void pivot_tree(Arc *entering, Arc *leaving, bool leaving_goes_lower)
Update tree structure after pivot.
size_t run(Flow_Type unused=0)
Execute Network Simplex algorithm.
DynArray< Arc_Info > arc_info
Network_Simplex(Net &network)
Construct Network Simplex solver.
typename Net::Flow_Type Flow_Type
void set_lower_bound(Arc *a, Flow_Type lower_bound)
Set lower bound for an arc.
const Node_Info & ninfo(Node *p) const
Get node info const reference.
bool verify_tree_integrity() const
Verify tree integrity - all parent_arcs should be Tree arcs.
DynMapTree< Arc *, size_t > arc_to_idx
void build_spanning_tree()
Build initial spanning tree from source.
void init_structures()
Initialize data structures.
size_t expected_tree_arcs() const
The arcs of the trees of a basic solution, one by node but the root of the tree of each component of ...
Node * find_lca(Node *u, Node *v)
Find the lowest common ancestor of two nodes.
Flow_Type residual_capacity(Arc *a) const
Get residual capacity (room to increase flow).
DynArray< Node_Info > node_info
bool is_partial_flow(Arc *a) const
Check if arc has partial flow (strictly between bounds).
Flow_Type reduced_cost(Arc *a) const
Compute reduced cost of an arc.
size_t count_non_tree_partial_arcs() const
Count arcs with partial flow not in tree.
static constexpr Flow_Type Inf
Flow_Type get_lower_bound(Arc *a) const
Get lower bound for an arc.
void set_tolerances()
Compute the tolerances from the capacities, flows and costs.
bool is_at_lower_bound(Arc *a) const
Check if arc flow is at lower bound, 0.
long depth(Node *p) const
Get depth.
NetworkSimplexStats stats
DynMapTree< Node *, size_t > node_to_idx
void print_stats() const
Print execution statistics to stdout.
typename Net::Node Node
bool is_valid_basic_solution() const
Check if current solution is a valid basic feasible solution.
bool is_at_upper_bound(Arc *a) const
Check if arc flow is at upper bound (capacity).
void ensure_ran(const char *member) const
Throw domain_error, naming member, if run() has not made the structures of the arcs that it reads.
size_t force_partial_arcs_into_tree()
Phase I: Force all partial-flow arcs into the spanning tree.
void print_diagnostics() const
Print diagnostic information about current state.
Node * parent(Node *p) const
Get parent node.
Arc_Info & ainfo(Arc *a)
Get arc info reference.
Node_Info & ninfo(Node *p)
Get node info reference.
const NetworkSimplexStats & get_stats() const noexcept
Return execution statistics from last run.
Flow_Type potential(Node *p) const
Get potential.
static bool without_capacity(const Arc *a) noexcept
Whether an arc has no capacity: its capacity is infinite or max().
typename Net::Arc Arc
bool verify_tree_reduced_costs() const
Verify that tree arcs have zero reduced cost.
Path on a graph.
Definition tpl_graph.H:3832
bool is_cycle() const
Return true if this is a cycle; throws if path is empty.
Definition tpl_graph.H:4351
bool is_empty() const noexcept
Return true if the path is empty.
Definition tpl_graph.H:3993
void for_each_arc(Operation op=Operation()) const
Execute an operation on each arc of path.
Definition tpl_graph.H:4540
Container< Arc * > arcs() const
Return a container with all the arcs of the graph.
Definition graph-dry.H:3080
void *& get_cookie() noexcept
Return a modifiable reference to graph's cookie.
Definition graph-dry.H:931
constexpr size_t vsize() const noexcept
See get_num_nodes().
Definition graph-dry.H:984
Container< Node * > nodes() const
Return a container with all the nodes of the graph.
Definition graph-dry.H:3062
auto get_it()
Return a properly initialized iterator positioned at the first item on the container.
Definition ah-dry.H:663
QuadTree - Hierarchical spatial index for 2D points.
Definition quadtree.H:126
Graph visualization and output generation utilities.
__gmp_expr< T, __gmp_binary_expr< __gmp_expr< T, U >, unsigned long int, __gmp_root_function > > root(const __gmp_expr< T, U > &expr, unsigned long int l)
Definition gmpfrxx.h:4138
DynArray< Graph::Arc * > arcs
Definition graphpic.C:408
GT build_spanning_tree(const DynArray< typename GT::Arc * > &arcs)
Build a graph from a list of arcs (typically a spanning tree).
#define NODE_COUNTER(p)
Get the counter of a node.
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
#define NODE_COOKIE(p)
Return the node cookie
#define ALEPH_FLATTEN
[[gnu::flatten]], or nothing where it would only make the compilation slower.
Net_Graph< Net_Node< string >, Net_Arc< Empty_Class, FlowType > > Net
double Flow_Type
void refuse_infinite_maximum_flow(const Net &net, const char *algorithm)
Refuse an infinite maximum flow before minimizing its cost.
void return_dust(Net &net, typename Net::Node *source, typename Net::Node *sink)
Returns the dust of a floating flow that a preflow algorithm left in net, from source to sink: what e...
Definition tpl_net.H:1410
auto residual_room(const Arc *a) noexcept
What a residual arc of a floating flow has left: if it is a mirror, the flow of its image,...
bool without_capacity(const Flow_Type &cap) noexcept
Whether an arc of capacity cap has none: infinite, or max()
Main namespace for Aleph-w library functions.
Itor lower_bound(Itor beg, Itor end, const T &value)
Find lower bound in a sorted range.
Definition ahAlgo.H:1190
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.
void cancel_cycle(const Res_Net &, const Path< Res_Net > &path)
Cancel a negative cycle by augmenting flow.
DynList< std::pair< typename Container1::Item_Type, typename Container2::Item_Type > > zip(const Container1 &a, const Container2 &b)
Zip two containers into a list of pairs.
void residual_to_net(const DynMapTree< void *, void * > &arcs)
Transfer flow values from residual network back to original.
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.
Simplex_Arc_State
Arc state in Network Simplex.
@ Upper
Non-basic arc at upper bound (flow = cap).
@ Lower
Non-basic arc at lower bound (flow = 0).
std::tuple< DynList< typename Net::Arc * >, DynList< typename Net::Arc * >, DynList< typename Net::Arc * > > Feasible_Tree
Feasible spanning tree classification.
void print_net_cost(const Net &net, std::ostream &out)
Output a flow network to Graphviz format.
bool check_residual_net(const Res_Net &net)
Verify residual network consistency.
void next()
Advance all underlying iterators (bounds-checked).
Definition ah-zip.H:236
void print_residual_net(const Residual_Net< typename Net::Flow_Type > &net, std::ostream &out)
Output a residual network to Graphviz format.
Feasible_Tree< Net > build_feasible_spanning_tree(const Net &net)
Build feasible spanning tree classification.
Net::Flow_Type reduced_cost(const Net &net, typename Net::Arc *arc, bool forward)
Compute reduced cost of an arc.
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
Definition ahAlgo.H:127
Iterator over arcs of a graph.
Definition tpl_agraph.H:334
Functor wrapper for ford_fulkerson_maximum_flow().
Definition tpl_net.H:2320
Functor wrapper for maximum flow minimum cost algorithm.
std::tuple< size_t, double > operator()(Net &net, const double it_factor=0.4, const size_t step=10)
Execute the algorithm.
Functor wrapper for Network Simplex algorithm.
size_t operator()(Net &net)
Execute the algorithm.
Arc of a flow network implemented with adjacency lists.
Definition tpl_net.H:160
Flow_Type cap
Capacity value.
Definition tpl_net.H:169
Net_Arc & operator=(const Net_Arc &arc)
Copy assignment.
Definition tpl_net.H:197
Flow_Type flow
Flow value.
Definition tpl_net.H:172
Arc type for maximum flow minimum cost networks.
Definition tpl_netcost.H:96
Flow_Type cost
Cost per unit of flow (negative for residual arcs).
Flow_Type flow_cost() const noexcept
Return the cost of the current flow through this arc.
Net_Cost_Arc(const Net_Cost_Arc &a)
Copy constructor.
Net_Cost_Arc & operator=(const Net_Cost_Arc &a)
Copy assignment operator.
Net_Cost_Arc()=default
Default constructor.
F_Type Flow_Type
Type representing flow, capacity, and cost values.
Capacitated flow network with costs associated to arcs.
typename Arc::Arc_Type Arc_Type
Type of attribute stored in an arc.
Flow_Type flow_cost() const
Compute the total cost of flow circulating through the network.
Flow_Type get_cost(Arc *a) const noexcept
Return the cost of an arc (const version).
typename Node::Node_Type Node_Type
Type of attribute stored in a node.
auto in_pars(Node *p)
Compute incoming flow parameters for a node.
Net_Cost_Graph & operator=(const Net_Cost_Graph &net)
Copy assignment operator (uses copy-and-swap idiom).
typename Arc::Flow_Type Flow_Type
Type representing capacity, flow, and cost values.
Net_Cost_Graph(Net_Cost_Graph &&)=default
Move constructor.
auto out_pars(Node *p)
Compute outgoing flow parameters for a node.
NodeT Node
Node type.
Net_Cost_Graph()=default
Default constructor.
virtual Arc * insert_arc(Node *src_node, Node *tgt_node)
Insert arc (internal use only).
Net_Cost_Graph(const Net_Cost_Graph &net)
Copy constructor.
Flow_Type & get_cost(Arc *a) noexcept
Return a modifiable reference to the cost of an arc.
Arc * emplace_arc(Node *src_node, Node *tgt_node, const Flow_Type &cap, const Flow_Type &__cost, Args &&... args)
Create and insert an arc with arc info using perfect forwarding.
virtual Arc * insert_arc(Node *src_node, Node *tgt_node, const Flow_Type &cap, const Flow_Type &__cost)
Create and insert an arc in a flow network with costs.
static Flow_Type arc_flow_cost(Arc *a) noexcept
Compute the cost of the flow through an arc.
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
static Flow_Type node_tolerance(const Flow_Type &in, const Flow_Type &out) noexcept
The tolerance of rounding of the flow of a node whose flows into and out of it are in and out.
Definition tpl_net.H:453
constexpr bool is_single_source() const noexcept
Return true if the network has a single source.
Definition tpl_net.H:429
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
typename Arc::Flow_Type Flow_Type
Capacity/flow numeric type.
Definition tpl_net.H:328
constexpr bool is_single_sink() const noexcept
Return true if the network has a single sink.
Definition tpl_net.H:435
NodeT Node
Node type.
Definition tpl_net.H:325
void swap(Net_Graph &other) noexcept
Swap contents with another network.
Definition tpl_net.H:1032
Execution statistics for Network Simplex algorithm.
double phase1_time_ms
Phase I elapsed time in milliseconds.
size_t tree_arcs
Number of arcs in spanning tree.
size_t degenerate_pivots
Pivots with zero flow change.
size_t total_pivots
Total pivot operations.
size_t initial_partial_arcs
Arcs with partial flow before Phase I.
size_t phase1_pivots
Pivots in Phase I (feasibility)
size_t phase2_pivots
Pivots in Phase II (optimization)
size_t forced_into_tree
Arcs forced into tree in Phase I.
double total_time_ms
Total elapsed time in milliseconds.
double phase2_time_ms
Phase II elapsed time in milliseconds.
Filtered iterator of adjacent arcs of a node.
Definition tpl_graph.H:1155
Cost of a residual arc, with a tolerance for the relaxations of Bellman-Ford (see the parameter Dista...
Net::Flow_Type tolerance() const noexcept
Return the tolerance.
Rcost_With_Tolerance() noexcept=default
Net::Flow_Type tol
A relaxation must improve a distance by more than it.
Cost distance functor for Bellman-Ford on residual networks.
Rcost() noexcept=default
static void set_zero(typename Net::Arc *a) noexcept
Reset arc to zero state.
typename Net::Flow_Type Distance_Type
Residual arc type with mirror pointer.
Res_Arc * img
Pointer to the mirror arc in the opposite direction.
bool is_residual
True if this is a residual (backward) arc.
Arc filter for the residual networks of a floating flow, which the cycle canceling takes: an arc has ...
Net::Flow_Type tol
An arc with no more than it left has no residual capacity.
bool operator()(typename Net::Arc *a) const noexcept
Check if arc has residual capacity beyond the tolerance.
Res_Filt_With_Tolerance() noexcept=default
Default constructor.
Res_Filt_With_Tolerance(typename Net::Node *) noexcept
Constructor (node parameter ignored).
Arc filter for residual networks.
Res_Filt() noexcept=default
Default constructor.
Res_Filt(typename Net::Node *) noexcept
Constructor (node parameter ignored).
Arc information for Network Simplex algorithm.
bool skip
Skip this arc temporarily (failed pivot, will retry later).
Simplex_Arc_State state
Arc state (Lower, Upper, or Tree).
Ftype lower_bound
Lower bound on flow: always 0, as Network_Simplex supports no other.
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).
Functor class for generating Graphviz DOT specifications.
void digraph(const GT &g, std::ostream &out, const Node_Attr &node_attr=Node_Attr(), const Arc_Attr &arc_attr=Arc_Attr(), const std::string &rankdir="LR")
Gsl_Compatible_Rng r
Articulation points (cut nodes), bridges, and biconnected components.
Stack of the frames of a depth-first search that does not recurse.
Dynamic key-value map based on balanced binary search trees.
Path finding algorithms in graphs.
Network flow graph structures.