73 template <
typename Node_Info = Empty_Class>
94 template <
typename Arc_Info = Empty_Class,
typename F_Type =
double>
147 template <
class NodeT = Net_Cost_Node<Empty_Class>,
148 class ArcT = Net_Cost_Arc<Empty_Class,
double>>
186 zip(this->
arcs(), net.
arcs()).for_each([](
const auto & p)
189 auto asrc = p.second;
190 atgt->cost = asrc->cost;
261 template <
typename... Args>
267 Arc_Type(std::forward<Args>(args)...));
299 Arc *a = it.get_curr();
313 Flow_Type cap_sum = 0, flow_sum = 0, cost_sum = 0;
316 Arc *a = it.get_curr();
321 return std::make_tuple(cap_sum, flow_sum, cost_sum);
332 Flow_Type cap_sum = 0, flow_sum = 0, cost_sum = 0;
335 Arc *a = it.get_curr();
340 return std::make_tuple(cap_sum, flow_sum, cost_sum);
366 bool operator ()(typename
Net::
Arc *a) const noexcept
368 return a->cap > a->flow;
382 return a->is_residual ? a->img->flow : a->cap - a->flow;
460 a->cap = std::numeric_limits<Distance_Type>::max();
497 template <
typename Flow_Type>
500 return not (cap < std::numeric_limits<Flow_Type>::max());
519 if constexpr (std::numeric_limits<Flow_Type>::has_infinity)
521 << algorithm <<
": the maximum flow is infinite, through a path of arcs of "
522 <<
"infinite capacity from the source to the sink";
540 template <
typename Ftype>
559 template <
typename Ftype>
581 template <
class Res_Net>
582 typename Res_Net::Arc *
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)
592 auto arc = residual_net.insert_arc(src, tgt, cap, cost);
593 auto rarc = residual_net.insert_arc(tgt, src, cap, -cost);
595 arc->is_residual =
false;
599 rarc->is_residual =
true;
601 rarc->flow = arc->cap - arc->flow;
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);
632 <<
"Network is not single source and single sink";
639 auto p = it.get_curr();
641 map_nodes<Net, Rnet>(p, q);
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);
651 auto rsrc = mapped_node<Net, Rnet>(gsrc);
652 auto rtgt = mapped_node<Net, Rnet>(gtgt);
654 ga->cap, ga->flow, ga->cost);
673 template <
class Res_Net>
676 return net.all_arcs([](
typename Res_Net::Arc *a)
678 return a->img !=
nullptr and a->img->img == a;
698 template <
class Res_Net>
702 <<
"Path is empty or not a cycle";
704 using Ftype =
typename Res_Net::Flow_Type;
709 Ftype slack = std::numeric_limits<Ftype>::max();
710 bool bounded =
false;
711 path.
for_each_arc([&slack, &bounded](
typename Res_Net::Arc *a)
714 if constexpr (std::is_floating_point_v<Ftype>)
717 room = a->cap - a->flow;
719 slack = std::min(slack, room);
720 bounded = bounded or a->is_residual
724 <<
"cancel_cycle(): the cycle has no bound: its arcs have no capacity";
738 assert(img->img == a);
739 assert(a->cap == img->cap);
740 if constexpr (std::is_floating_point_v<Ftype>)
745 a->flow = a->cap - img->flow;
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;
776 arcs.for_each([](std::pair<void *, void *> p)
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;
861 template <FlowNetwork
Net,
863 std::tuple<size_t, double>
865 double it_factor = 0.4,
868 Max_Flow_Algo<Net>()(net);
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>>;
890 if constexpr (floating)
892 Ftype largest_cost{0}, largest_flow{0};
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);
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));
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);
909 bool found_cycle =
true;
915 auto [cycle, iterations] =
916 BF(rnet, cost, filt).search_negative_cycle(source, it_factor, step);
918 if (cycle.is_empty())
921 auto [global_cycle, global_iter] =
922 BF(rnet, cost, filt).search_negative_cycle(it_factor, step);
924 if (global_cycle.is_empty())
934 it_factor =
static_cast<double>(iterations) / net.
vsize();
948 return std::make_tuple(
count, it_factor);
962 template <FlowNetwork
Net,
974 const double it_factor = 0.4,
975 const size_t step = 10)
977 return max_flow_min_cost_by_cycle_canceling<Net, Max_Flow_Algo>
978 (net, it_factor, step);
1004 void operator ()(
const Net &,
typename Net::Node *p, std::ostream & o)
1006 o <<
"label = \"(" << p->get_info() <<
"," <<
NODE_COUNTER(p) <<
")\"";
1012 void operator ()(
const Net &,
typename Net::Arc *a, std::ostream & o)
1014 o <<
"label = \"" << a->flow <<
"/" << a->cap <<
"/" << a->cost <<
"\"";
1031 template <
class Net>
1038 net.
nodes().for_each([&i](
typename Rnet::Node *p)
1045 void operator ()(
const Rnet &,
typename Rnet::Node *p, std::ostream & o)
1053 void operator ()(
const Rnet &,
typename Rnet::Arc *a, std::ostream & o)
1055 o <<
"label = \"" << a->flow <<
"/" << a->cap <<
"/" << a->cost <<
"\"";
1057 o <<
" color = red";
1080 template <
class Net>
1095 template <
class Net>
1103 if (
auto a = it.get_curr(); a->flow == 0)
1105 else if (a->flow == a->cap)
1111 return std::make_tuple(std::move(empty), std::move(full), std::move(partial));
1122 template <
class Net>
1127 if (
auto a = it.get_curr(); a->flow > 0
and a->flow < a->cap)
1142 template <
typename Ftype>
1183 template <
typename Ftype>
1288 template <FlowNetwork Net>
1334 if constexpr (std::is_floating_point_v<Flow_Type>)
1336 if (a->flow > a->cap)
1352 if constexpr (std::is_floating_point_v<Flow_Type>)
1354 Flow_Type largest_flow = 0, largest_cost = 0;
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));
1365 const Flow_Type e = std::numeric_limits<Flow_Type>::epsilon() * 1000;
1366 flow_tol = e * largest_flow;
1367 cost_tol = e * largest_cost;
1376 <<
"Network_Simplex::" << member <<
"(): run() has not been called";
1388 auto a = it.get_curr();
1389 if (not a->check_arc())
1391 if constexpr (std::is_floating_point_v<Flow_Type>)
1392 if (not std::isfinite(a->flow))
1396 const auto source = net.get_source(), sink = net.get_sink();
1399 auto p = it.get_curr();
1400 if (p == source or p == sink)
1402 const auto in = net.get_in_flow(p),
out = net.get_out_flow(p);
1419 if (ninfo(it.get_curr()).depth == 0)
1421 return net.vsize() - roots;
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;
1464 node_to_idx.empty();
1471 auto p = it.get_curr();
1472 node_to_idx.insert(p, idx);
1481 auto a = it.get_curr();
1482 arc_to_idx.insert(a, idx);
1485 arc_info(idx).
state = Simplex_Arc_State::Lower;
1493 return a->flow > flow_tol
and a->flow < a->cap - flow_tol;
1508 root = net.get_source();
1513 auto p = it.get_curr();
1514 auto &ni = ninfo(p);
1515 ni.parent =
nullptr;
1516 ni.parent_arc =
nullptr;
1524 ainfo(it.get_curr()).state = Simplex_Arc_State::Lower;
1526 const size_t total_nodes = net.vsize();
1529 ninfo(
root).depth = 0;
1530 ninfo(
root).potential = 0;
1532 size_t nodes_in_tree = 1;
1535 auto add_to_tree = [&](
Node *p,
Arc *a,
Node *other) ->
bool {
1536 if (ninfo(other).depth >= 0)
1539 const auto &pi = ninfo(p);
1540 auto &oi = ninfo(other);
1543 oi.depth = pi.depth + 1;
1545 auto src =
static_cast<Node *
>(a->src_node);
1548 oi.arc_from_parent =
true;
1549 oi.potential = pi.potential - a->cost;
1553 oi.arc_from_parent =
false;
1554 oi.potential = pi.potential + a->cost;
1557 ainfo(a).state = Simplex_Arc_State::Tree;
1566 while (not queue.
is_empty()
and nodes_in_tree < total_nodes)
1568 auto p = queue.
get();
1571 struct ArcPriority {
1580 auto a = it.get_curr();
1581 auto other = net.get_connected_node(a, p);
1582 if (ninfo(other).depth >= 0)
1586 if (is_partial_flow(a))
1588 else if (a->flow > flow_tol)
1593 candidates.
append(ArcPriority{a, other, prio});
1598 for (
int target_prio = 0; target_prio <= 2; ++target_prio)
1600 for (
auto& ap : candidates)
1602 if (ap.priority == target_prio)
1603 add_to_tree(p, ap.arc, ap.other);
1615 it.has_curr()
and nodes_in_tree < total_nodes; it.next_ne())
1616 if (
auto r = it.get_curr(); ninfo(
r).depth < 0)
1619 ninfo(
r).potential = 0;
1628 auto a = it.get_curr();
1629 if (ainfo(a).state == Simplex_Arc_State::Tree)
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;
1640 ainfo(a).state = (rc < -cost_tol) ?
1641 Simplex_Arc_State::Upper : Simplex_Arc_State::Lower;
1664 Arc *best =
nullptr;
1666 bool best_is_increase =
true;
1670 auto a = it.get_curr();
1671 auto &ai = ainfo(a);
1673 if (ai.state == Simplex_Arc_State::Tree)
1680 const bool can_increase = (a->flow < a->cap - flow_tol);
1681 const bool can_decrease = (a->flow > flow_tol);
1684 if (can_increase
and rc < -best_violation)
1686 best_violation = -rc;
1688 best_is_increase =
true;
1693 if (can_decrease
and rc > best_violation)
1695 best_violation = rc;
1697 best_is_increase =
false;
1702 if (best !=
nullptr)
1704 ainfo(best).state = best_is_increase ?
1705 Simplex_Arc_State::Lower : Simplex_Arc_State::Upper;
1725 while (p !=
nullptr)
1727 ninfo(p).mark = lca_mark;
1733 while (p !=
nullptr and ninfo(p).mark != lca_mark)
1757 Arc *&leaving,
bool &leaving_goes_lower)
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);
1763 assert(lca !=
nullptr);
1766 const bool increase_on_entering = (ainfo(entering).state == Simplex_Arc_State::Lower);
1769 if (increase_on_entering)
1770 delta = entering->cap - entering->flow;
1772 delta = entering->flow;
1775 leaving_goes_lower = increase_on_entering;
1783 Arc *pa = parent_arc(p);
1784 bool from_parent = ninfo(p).arc_from_parent;
1787 bool flow_increases = (increase_on_entering == from_parent);
1794 slack = pa->cap - pa->flow;
1804 if (slack < delta or (slack == delta
and goes_lower
and not leaving_goes_lower))
1808 leaving_goes_lower = goes_lower;
1820 Arc *pa = parent_arc(p);
1821 bool from_parent = ninfo(p).arc_from_parent;
1824 bool flow_increases = (increase_on_entering != from_parent);
1831 slack = pa->cap - pa->flow;
1840 if (slack < delta or (slack == delta
and goes_lower
and not leaving_goes_lower))
1844 leaving_goes_lower = goes_lower;
1853 const bool to_cap = leaving == entering ? increase_on_entering : not leaving_goes_lower;
1858 unbounded = to_cap
and without_capacity(leaving);
1865 if (delta >= 0
and leaving !=
nullptr)
1868 move_flow(entering, delta, increase_on_entering);
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);
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);
1891 if constexpr (std::is_floating_point_v<Flow_Type>)
1892 leaving->flow = to_cap ? leaving->cap :
Flow_Type{0};
1912 if (entering == leaving)
1914 auto &ai = ainfo(entering);
1915 ai.state = leaving_goes_lower ?
1916 Simplex_Arc_State::Lower : Simplex_Arc_State::Upper;
1921 ainfo(leaving).state = leaving_goes_lower ?
1922 Simplex_Arc_State::Lower : Simplex_Arc_State::Upper;
1925 ainfo(entering).state = Simplex_Arc_State::Tree;
1929 auto leaving_src =
static_cast<Node *
>(leaving->src_node);
1930 auto leaving_tgt =
static_cast<Node *
>(leaving->tgt_node);
1933 bool src_has_leaving = (parent_arc(leaving_src) == leaving);
1934 bool tgt_has_leaving = (parent_arc(leaving_tgt) == leaving);
1936 if (not src_has_leaving
and not tgt_has_leaving)
1939 if (src_has_leaving)
1940 subtree_root = leaving_src;
1942 subtree_root = leaving_tgt;
1944 auto entering_src =
static_cast<Node *
>(entering->src_node);
1945 auto entering_tgt =
static_cast<Node *
>(entering->tgt_node);
1948 Node *in_subtree, *out_subtree;
1950 Node *p = entering_src;
1951 bool src_in =
false;
1952 while (p !=
nullptr)
1954 if (p == subtree_root)
1964 in_subtree = entering_src;
1965 out_subtree = entering_tgt;
1969 in_subtree = entering_tgt;
1970 out_subtree = entering_src;
1976 Node *p = in_subtree;
1977 while (p != subtree_root
and p !=
nullptr)
1982 if (p == subtree_root)
1983 path.
insert(subtree_root);
2001 for (
auto it = path.
get_it(); it.has_curr(); )
2003 Node *curr = it.get_curr();
2006 if (not it.has_curr())
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;
2017 auto arc_src =
static_cast<Node *
>(arc_between->src_node);
2018 curr_info.arc_from_parent = (arc_src ==
next);
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);
2029 queue.
put(in_subtree);
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;
2036 sub_info.potential = out_info.potential + entering->cost;
2041 const auto &curr_info = ninfo(curr);
2046 Node *child = nit.get_curr();
2050 if (parent(child) != curr)
2053 auto &ci = ninfo(child);
2054 ci.depth = curr_info.depth + 1;
2056 Arc *pa = parent_arc(child);
2057 if (ci.arc_from_parent)
2058 ci.potential = curr_info.potential - pa->cost;
2060 ci.potential = curr_info.potential + pa->cost;
2086 [[deprecated(
"Network_Simplex supports no lower bound but 0: it goes in 8.0.0")]]
2090 <<
"Network_Simplex::set_lower_bound(): no lower bound but 0 is supported";
2100 [[deprecated(
"Network_Simplex supports no lower bound but 0: it goes in 8.0.0")]]
2116 return std::abs(a->flow) <= flow_tol;
2129 return std::abs(a->flow - a->cap) <= flow_tol;
2139 return a->cap - a->flow;
2150 [[deprecated(
"every lower bound of Network_Simplex is 0: use the flow; it goes in 8.0.0")]]
2188 <<
"Network is not single source and single sink";
2190 <<
"Network_Simplex::run(): the flow of the network is not feasible";
2193 auto total_start = std::chrono::high_resolution_clock::now();
2201 stats.initial_partial_arcs = count_non_tree_partial_arcs();
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;
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;
2219 bool optimal =
false;
2220 while (num_pivots < max_pivots
and failed_attempts < max_failures)
2222 Arc *entering = find_entering_arc();
2224 if (entering ==
nullptr)
2227 optimal = failed_attempts == 0;
2233 bool leaving_goes_lower;
2235 bool success = augment_and_find_leaving(entering, delta, leaving, leaving_goes_lower);
2243 <<
"Network_Simplex::run(): the program is unbounded: a cycle of "
2244 <<
"negative cost through arcs without capacity";
2249 if (delta <= flow_tol)
2250 ++stats.degenerate_pivots;
2252 pivot_tree(entering, leaving, leaving_goes_lower);
2254 failed_attempts = 0;
2258 ainfo(ait.get_curr()).skip =
false;
2262 ainfo(entering).skip =
true;
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;
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;
2283 stats.tree_arcs = 0;
2285 if (ainfo(it.get_curr()).state == Simplex_Arc_State::Tree)
2291 <<
"Network_Simplex::run(): the cost is not optimal after "
2292 << num_pivots <<
" pivots";
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"
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";
2334 ensure_ran(
"force_partial_arcs_into_tree");
2335 size_t forced_pivots = 0;
2336 bool made_progress =
true;
2338 while (made_progress)
2340 made_progress =
false;
2345 auto a = it.get_curr();
2346 if (ainfo(a).state == Simplex_Arc_State::Tree)
2349 if (not is_partial_flow(a))
2354 ainfo(a).state = Simplex_Arc_State::Lower;
2358 bool leaving_goes_lower;
2361 bool success = augment_and_find_leaving(a, delta, leaving, leaving_goes_lower);
2363 if (success
and leaving !=
nullptr and leaving != a)
2366 if (ainfo(leaving).state != Simplex_Arc_State::Tree)
2368 ainfo(a).state = Simplex_Arc_State::Lower;
2372 pivot_tree(a, leaving, leaving_goes_lower);
2374 made_progress =
true;
2380 ainfo(a).state = Simplex_Arc_State::Upper;
2381 success = augment_and_find_leaving(a, delta, leaving, leaving_goes_lower);
2383 if (success
and leaving !=
nullptr and leaving != a)
2385 pivot_tree(a, leaving, leaving_goes_lower);
2387 made_progress =
true;
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;
2398 ainfo(a).state = Simplex_Arc_State::Lower;
2404 return forced_pivots;
2417 ensure_ran(
"is_valid_basic_solution");
2420 auto a = it.get_curr();
2421 if (ainfo(a).state == Simplex_Arc_State::Tree)
2425 if (is_partial_flow(a))
2434 ensure_ran(
"count_non_tree_partial_arcs");
2438 auto a = it.get_curr();
2439 if (ainfo(a).state != Simplex_Arc_State::Tree
and is_partial_flow(a))
2454 ensure_ran(
"verify_tree_reduced_costs");
2457 auto a = it.get_curr();
2458 if (ainfo(a).state != Simplex_Arc_State::Tree)
2462 if (std::abs(rc) > 100 * cost_tol)
2474 ensure_ran(
"verify_tree_integrity");
2477 auto p = it.get_curr();
2478 if (p ==
root or ninfo(p).depth == 0)
2481 auto pa = parent_arc(p);
2485 if (ainfo(pa).state != Simplex_Arc_State::Tree)
2494 ensure_ran(
"print_diagnostics");
2495 std::cout <<
"\n=== Network Simplex Diagnostics ===\n";
2498 size_t tree_arcs = 0, lower_arcs = 0, upper_arcs = 0;
2501 switch (ainfo(it.get_curr()).state)
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;
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";
2514 bool tree_rc_ok = verify_tree_reduced_costs();
2515 std::cout <<
"Tree arcs rc=0: " << (tree_rc_ok ?
"YES" :
"NO") <<
"\n";
2518 size_t violations = 0;
2521 auto a = it.get_curr();
2522 auto state = ainfo(a).state;
2525 if (state == Simplex_Arc_State::Lower)
2528 if (rc < -cost_tol and a->flow < a->cap - flow_tol)
2531 std::cout <<
" VIOLATION: Lower arc with rc=" << rc
2532 <<
" flow=" << a->flow <<
"/" << a->cap <<
"\n";
2535 else if (state == Simplex_Arc_State::Upper)
2538 if (rc > cost_tol
and a->flow > flow_tol)
2541 std::cout <<
" VIOLATION: Upper arc with rc=" << rc
2542 <<
" flow=" << a->flow <<
"/" << a->cap <<
"\n";
2547 std::cout <<
"Optimality violations: " << violations <<
"\n";
2548 std::cout <<
"==================================\n";
2599 template <FlowNetwork
Net,
2603 Max_Flow_Algo<Net>()(net);
2606 return simplex.
run();
2618 template <FlowNetwork
Net,
2629 return max_flow_min_cost_by_network_simplex<Net, Max_Flow_Algo>(net);
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.
#define ah_domain_error_if(C)
Throws std::domain_error if condition holds.
#define ah_runtime_error_if(C)
Throws std::runtime_error if condition holds.
C++20 concepts for the protocol shared by graph algorithms.
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.
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).
T & append(const T &item)
T & insert(const T &item)
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.
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().
bool verify_tree_reduced_costs() const
Verify that tree arcs have zero reduced cost.
bool is_cycle() const
Return true if this is a cycle; throws if path is empty.
bool is_empty() const noexcept
Return true if the path is empty.
void for_each_arc(Operation op=Operation()) const
Execute an operation on each arc of path.
Container< Arc * > arcs() const
Return a container with all the arcs of the graph.
void *& get_cookie() noexcept
Return a modifiable reference to graph's cookie.
constexpr size_t vsize() const noexcept
See get_num_nodes().
Container< Node * > nodes() const
Return a container with all the nodes of the graph.
auto get_it()
Return a properly initialized iterator positioned at the first item on the container.
QuadTree - Hierarchical spatial index for 2D points.
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)
DynArray< Graph::Arc * > arcs
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.
#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
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...
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.
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.
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).
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.
Iterator over arcs of a graph.
Functor wrapper for ford_fulkerson_maximum_flow().
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.
Flow_Type cap
Capacity value.
Net_Arc & operator=(const Net_Arc &arc)
Copy assignment.
Flow_Type flow
Flow value.
Arc type for maximum flow minimum cost networks.
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.
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.
Node * insert_node(const Node_Type &node_info)
Insert a new node by copying node_info.
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.
constexpr bool is_single_source() const noexcept
Return true if the network has a single source.
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...
typename Arc::Flow_Type Flow_Type
Capacity/flow numeric type.
constexpr bool is_single_sink() const noexcept
Return true if the network has a single sink.
void swap(Net_Graph &other) noexcept
Swap contents with another network.
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.
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.
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")
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.