Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
tpl_net_test.cc
Go to the documentation of this file.
1
2/*
3 Aleph_w
4
5 Data structures & Algorithms
6 version 2.0.0b
7 https://github.com/lrleon/Aleph-w
8
9 This file is part of Aleph-w library
10
11 Copyright (c) 2002-2026 Leandro Rabindranath Leon
12
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
19
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
22
23 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 SOFTWARE.
30*/
31
32
33
38#include <gtest/gtest.h>
39
40#include <cmath>
41#include <limits>
42#include <random>
43#include <set>
44#include <vector>
45
46#include <tpl_dynDlist.H>
47#include <tpl_maxflow.H>
48#include <tpl_net.H>
49#include <tpl_net_sup_dem.H>
50#include <tpl_netcapgraph.H>
51#include <tpl_netcost.H>
52
53using namespace Aleph;
54
55namespace
56{
58
59 struct SimpleNet
60 {
61 Net::Node *s = nullptr;
62 Net::Node *a = nullptr;
63 Net::Node *b = nullptr;
64 Net::Node *t = nullptr;
65 Net::Arc *sa = nullptr;
66 Net::Arc *sb = nullptr;
67 Net::Arc *ab = nullptr;
68 Net::Arc *at = nullptr;
69 Net::Arc *bt = nullptr;
70 };
71
72 SimpleNet build_simple_net(Net &net)
73 {
74 SimpleNet sn;
75 sn.s = net.insert_node(0);
76 sn.a = net.insert_node(1);
77 sn.b = net.insert_node(2);
78 sn.t = net.insert_node(3);
79
80 sn.sa = net.insert_arc(sn.s, sn.a, 3, 0);
81 sn.sb = net.insert_arc(sn.s, sn.b, 2, 0);
82 sn.ab = net.insert_arc(sn.a, sn.b, 1, 0);
83 sn.at = net.insert_arc(sn.a, sn.t, 2, 0);
84 sn.bt = net.insert_arc(sn.b, sn.t, 3, 0);
85
86 return sn;
87 }
88
89 struct SingleArcNet
90 {
91 Net::Node *s = nullptr;
92 Net::Node *t = nullptr;
93 Net::Arc *st = nullptr;
94 };
95
96 SingleArcNet build_single_arc(Net &net, int cap, int flow = 0)
97 {
98 SingleArcNet sn;
99 sn.s = net.insert_node(0);
100 sn.t = net.insert_node(1);
101 sn.st = net.insert_arc(sn.s, sn.t, cap, flow);
102 return sn;
103 }
104}
105
106TEST(NetGraphBasics, SourcesSinksUpdateOnArcOperations)
107{
108 Net net;
109 auto s = net.insert_node(1);
110 auto t = net.insert_node(2);
111
112 EXPECT_TRUE(net.is_source(s));
113 EXPECT_TRUE(net.is_sink(s));
114 EXPECT_TRUE(net.is_source(t));
115 EXPECT_TRUE(net.is_sink(t));
116
117 auto arc = net.insert_arc(s, t, 5, 0);
118
119 EXPECT_TRUE(net.is_source(s));
120 EXPECT_FALSE(net.is_sink(s));
121 EXPECT_FALSE(net.is_source(t));
122 EXPECT_TRUE(net.is_sink(t));
123
124 net.remove_arc(arc);
125
126 EXPECT_TRUE(net.is_source(s));
127 EXPECT_TRUE(net.is_sink(s));
128 EXPECT_TRUE(net.is_source(t));
129 EXPECT_TRUE(net.is_sink(t));
130}
131
132TEST(NetGraphBasics, DisconnectConnectArcUpdatesSets)
133{
134 Net net;
135 auto s = net.insert_node(1);
136 auto t = net.insert_node(2);
137 auto arc = net.insert_arc(s, t, 5, 0);
138
139 net.disconnect_arc(arc);
140 EXPECT_EQ(net.get_num_arcs(), 0U);
141 EXPECT_TRUE(net.is_source(t));
142 EXPECT_TRUE(net.is_sink(s));
143
144 net.connect_arc(arc);
145 EXPECT_EQ(net.get_num_arcs(), 1U);
146 EXPECT_FALSE(net.is_source(t));
147 EXPECT_FALSE(net.is_sink(s));
148}
149
150TEST(NetGraphSuperNodes, MakeAndUnmakeSuperSource)
151{
152 Net net;
153 auto s1 = net.insert_node(1);
154 auto s2 = net.insert_node(2);
155 auto t1 = net.insert_node(3);
156 auto t2 = net.insert_node(4);
157
158 net.insert_arc(s1, t1, 5, 0);
159 net.insert_arc(s2, t2, 7, 0);
160
161 EXPECT_EQ(net.get_src_nodes().size(), 2U);
162 EXPECT_EQ(net.get_sink_nodes().size(), 2U);
163
164 const auto before_nodes = net.get_num_nodes();
165 net.make_super_source();
166
167 EXPECT_EQ(net.get_src_nodes().size(), 1U);
168 EXPECT_EQ(net.get_num_nodes(), before_nodes + 1);
169
170 auto super_source = net.get_source();
171 EXPECT_EQ(net.get_out_degree(super_source), 2U);
172
173 bool has_self = false;
174 for (Node_Arc_Iterator<Net> it(super_source); it.has_curr(); it.next_ne())
175 {
176 if (it.get_tgt_node_ne() == super_source)
177 has_self = true;
178 }
179 EXPECT_FALSE(has_self);
180
182 EXPECT_EQ(net.get_num_nodes(), before_nodes);
183 EXPECT_EQ(net.get_src_nodes().size(), 2U);
184}
185
186TEST(NetGraphSuperNodes, MakeAndUnmakeSuperSink)
187{
188 Net net;
189 auto s1 = net.insert_node(1);
190 auto s2 = net.insert_node(2);
191 auto t1 = net.insert_node(3);
192 auto t2 = net.insert_node(4);
193
194 net.insert_arc(s1, t1, 5, 0);
195 net.insert_arc(s2, t2, 7, 0);
196
197 EXPECT_EQ(net.get_sink_nodes().size(), 2U);
198
199 const auto before_nodes = net.get_num_nodes();
200 net.make_super_sink();
201
202 EXPECT_EQ(net.get_sink_nodes().size(), 1U);
203 EXPECT_EQ(net.get_num_nodes(), before_nodes + 1);
204
205 auto super_sink = net.get_sink();
206 EXPECT_EQ(net.get_in_degree(super_sink), 2U);
207
208 bool has_self = false;
209 for (Node_Arc_Iterator<Net> it(super_sink); it.has_curr(); it.next_ne())
210 {
211 if (it.get_tgt_node_ne() == super_sink)
212 has_self = true;
213 }
214 EXPECT_FALSE(has_self);
215
216 net.unmake_super_sink();
217 EXPECT_EQ(net.get_num_nodes(), before_nodes);
218 EXPECT_EQ(net.get_sink_nodes().size(), 2U);
219}
220
221TEST(NetGraphFlowAlgorithms, FordFulkersonAndEdmondsKarp)
222{
223 Net net1;
224 build_simple_net(net1);
225 EXPECT_EQ(ford_fulkerson_maximum_flow(net1), 5);
226 EXPECT_TRUE(net1.check_network());
227 EXPECT_EQ(net1.flow_value(), 5);
228
229 Net net2;
230 build_simple_net(net2);
231 EXPECT_EQ(edmonds_karp_maximum_flow(net2), 5);
232 EXPECT_TRUE(net2.check_network());
233 EXPECT_EQ(net2.flow_value(), 5);
234}
235
236TEST(NetGraphFlowAlgorithms, PreflowVariants)
237{
238 Net net1;
239 build_simple_net(net1);
240 EXPECT_EQ(fifo_preflow_maximum_flow(net1), 5);
241 EXPECT_TRUE(net1.check_network());
242
243 Net net2;
244 build_simple_net(net2);
245 EXPECT_EQ(heap_preflow_maximum_flow(net2), 5);
246 EXPECT_TRUE(net2.check_network());
247
248 Net net3;
249 build_simple_net(net3);
250 EXPECT_EQ(random_preflow_maximum_flow(net3), 5);
251 EXPECT_TRUE(net3.check_network());
252}
253
254namespace
255{
256 // Four nodes after the source, each with an arc to each of four before
257 // the sink, all of capacity 1: every perfect matching between them is a
258 // maximum flow, so that the order of the pushes chooses one
259 void build_matching_net(Net & net)
260 {
261 auto s = net.insert_node(0);
262 auto t = net.insert_node(1);
263 std::vector<Net::Node *> left, right;
264 for (int i = 0; i < 4; ++i)
265 left.push_back(net.insert_node(10 + i));
266 for (int i = 0; i < 4; ++i)
267 right.push_back(net.insert_node(20 + i));
268 for (auto * l : left)
269 net.insert_arc(s, l, 1, 0);
270 for (auto * l : left)
271 for (auto * r : right)
272 net.insert_arc(l, r, 1, 0);
273 for (auto * r : right)
274 net.insert_arc(r, t, 1, 0);
275 }
276
277 std::vector<int> arc_flows(Net & net)
278 {
279 std::vector<int> flows;
280 for (Arc_Iterator<Net> it(net); it.has_curr(); it.next_ne())
281 flows.push_back(it.get_curr_ne()->flow);
282 return flows;
283 }
284} // namespace
285
286// The random preflow took its seed from the time, so that its runs could
287// not be repeated: with a seed, two runs on equal networks push the same
288// flows
289TEST(NetGraphFlowAlgorithms, RandomPreflowWithASeedRepeatsItsPushes)
290{
291 std::set<std::vector<int>> seen;
292 for (unsigned long seed : {7ul, 8ul, 9ul, 10ul, 11ul, 12ul, 13ul, 14ul})
293 {
294 Net net1, net2;
295 build_matching_net(net1);
296 build_matching_net(net2);
297 EXPECT_EQ(random_preflow_maximum_flow(net1, seed), 4);
298 EXPECT_EQ(random_preflow_maximum_flow(net2, seed), 4);
299 EXPECT_TRUE(net1.check_network());
300 const auto flows = arc_flows(net1);
301 EXPECT_EQ(flows, arc_flows(net2)) << "seed " << seed;
302 seen.insert(flows);
303 }
304 EXPECT_GT(seen.size(), 1u); // the seed chooses among the maximum flows
305}
306
307TEST(NetGraphAugmentingPaths, IncreaseFlowOnPath)
308{
309 Net net;
310 auto nodes = build_single_arc(net, 4);
311
312 auto path = find_aumenting_path_dfs(net, 0);
313 auto slack = increase_flow(net, path);
314
315 EXPECT_EQ(slack, 4);
316 EXPECT_EQ(nodes.st->flow, 4);
317}
318
319TEST(NetGraphAugmentingPaths, SemiPathAndIncreaseFlow)
320{
321 Net net;
322 auto nodes = build_single_arc(net, 4);
323
325 DynList<Parc<Net>> semi_path;
326 auto slack = finder.semi_path(nodes.s, nodes.t, semi_path, 0);
327
328 EXPECT_EQ(slack, 4);
329 EXPECT_FALSE(semi_path.is_empty());
330
331 increase_flow(net, semi_path, slack);
332 EXPECT_EQ(nodes.st->flow, 4);
333}
334
335TEST(NetGraphResidualHelpers, RemainingFlowAndFilter)
336{
337 Net net;
338 auto nodes = build_single_arc(net, 10, 3);
339
340 EXPECT_FALSE(is_residual<Net>(nodes.s, nodes.st));
341 EXPECT_TRUE(is_residual<Net>(nodes.t, nodes.st));
342 EXPECT_EQ(remaining_flow<Net>(nodes.s, nodes.st), 7);
343 EXPECT_EQ(remaining_flow<Net>(nodes.t, nodes.st), 3);
344
345 Net_Filt<Net> from_src(nodes.s);
346 Net_Filt<Net> from_tgt(nodes.t);
347 EXPECT_TRUE(from_src(nodes.st));
348 EXPECT_TRUE(from_tgt(nodes.st));
349
350 nodes.st->flow = nodes.st->cap;
351 EXPECT_FALSE(from_src(nodes.st));
352
353 nodes.st->flow = 0;
354 EXPECT_FALSE(from_tgt(nodes.st));
355}
356
357TEST(NetGraphResidualNet, UpdateFlowFromResidual)
358{
359 Net net;
360 build_single_arc(net, 10, 4);
361
362 auto residual = preflow_create_residual_net(net);
363 auto &rnet = std::get<0>(residual);
364 using Rnet = PP_Res_Net<Net>;
365
366 Net::Arc *original = nullptr;
367 for (typename Rnet::Arc_Iterator it(rnet); it.has_curr(); it.next_ne())
368 {
369 auto arc = it.get_curr();
370 if (arc->img != nullptr)
371 {
372 original = arc->img;
373 arc->flow = 7;
374 break;
375 }
376 }
377
378 ASSERT_NE(original, nullptr);
379 update_flow(rnet);
380 EXPECT_EQ(original->flow, 7);
381}
382
383TEST(NetGraphMinCut, ComputesCutCapacity)
384{
385 Net net;
386 auto nodes = build_simple_net(net);
387
392
393 auto value = min_cut<Net, Edmonds_Karp_Maximum_Flow>(net, vs, vt, cuts, cutt);
394 EXPECT_EQ(value, 5);
395 EXPECT_TRUE(vs.contains(nodes.s));
396 EXPECT_TRUE(vt.contains(nodes.t));
397
398 int cut_cap = 0;
399 for (typename DynList<Net::Arc *>::Iterator it(cuts); it.has_curr(); it.next_ne())
400 cut_cap += it.get_curr()->cap;
401
402 EXPECT_EQ(cut_cap, value);
403}
404
405// insert_arc() checked the flow after the arc was in the network, with the
406// sources and the sinks updated, so an arc with more flow than capacity was
407// left in it
408TEST(NetGraphBasics, AnArcWithMoreFlowThanCapacityIsNotInserted)
409{
410 Net net;
411 auto s = net.insert_node(1);
412 auto t = net.insert_node(2);
413
414 EXPECT_THROW(net.insert_arc(s, t, 2, 3), std::overflow_error);
415 EXPECT_THROW(net.insert_arc(s, t, 2, -1), std::overflow_error);
416 EXPECT_EQ(net.get_num_arcs(), 0u);
417 EXPECT_TRUE(net.is_sink(s));
418 EXPECT_TRUE(net.is_source(t));
419
420 auto arc = net.insert_arc(s, t, 2, 2);
421 EXPECT_EQ(net.get_num_arcs(), 1u);
422 EXPECT_EQ(arc->flow, 2);
423 EXPECT_FALSE(net.is_sink(s));
424 EXPECT_FALSE(net.is_source(t));
425}
426
427// The copy constructor inserts the arcs with two arguments, and the
428// overload that took them was disabled for an arithmetic arc info, so a
429// network with one did not compile its copy
430TEST(NetGraphBasics, CopiesANetworkWithAnArithmeticArcInfo)
431{
433 Info_Net net;
434 auto s = net.insert_node(1);
435 auto a = net.insert_node(2);
436 auto t = net.insert_node(3);
437 net.insert_arc(s, a, 5.0, 2.0, 7);
438 net.insert_arc(a, t, 4.0, 1.5, 8);
439
440 Info_Net copy(net);
441 ASSERT_EQ(copy.get_num_nodes(), 3u);
442 ASSERT_EQ(copy.get_num_arcs(), 2u);
443 EXPECT_TRUE(copy.is_single_source());
444 EXPECT_TRUE(copy.is_single_sink());
445 double cap = 0, flow = 0;
446 int info = 0;
447 for (Info_Net::Arc_Iterator it(copy); it.has_curr(); it.next_ne())
448 {
449 cap += it.get_curr()->cap;
450 flow += it.get_curr()->flow;
451 info += it.get_curr()->get_info();
452 }
453 EXPECT_EQ(cap, 9.0);
454 EXPECT_EQ(flow, 3.5);
455 EXPECT_EQ(info, 15);
456
457 Info_Net assigned;
458 assigned = net;
459 EXPECT_EQ(assigned.get_num_arcs(), 2u);
460
461 auto zero = copy.insert_arc(copy.get_first_node(), copy.get_first_node());
462 EXPECT_EQ(zero->cap, 0.0);
463 EXPECT_EQ(zero->get_info(), 0);
464}
465
466// The search kept in each node the node it came from, and the path took,
467// of the arcs between both, the first one with some slack: with parallel
468// arcs, one with less slack than asked for
469TEST(NetGraphAugmentingPaths, ASemiPathHasTheSlackItWasAskedFor)
470{
471 for (bool light_first : {true, false})
472 {
473 SCOPED_TRACE(light_first ? "light arc first" : "heavy arc first");
474 Net net;
475 auto s = net.insert_node(0);
476 auto a = net.insert_node(1);
477 auto t = net.insert_node(2);
478 if (light_first)
479 net.insert_arc(s, a, 1, 0);
480 auto heavy = net.insert_arc(s, a, 5, 0);
481 if (not light_first)
482 net.insert_arc(s, a, 1, 0);
483 net.insert_arc(a, t, 4, 0);
484
485 DynList<Parc<Net>> path;
486 const auto slack =
487 Find_Aumenting_Path_BFS<Net>(net).semi_path(s, t, path, 3);
488 EXPECT_EQ(slack, 4);
489 ASSERT_EQ(path.size(), 2u);
490 EXPECT_EQ(get<0>(path.get_first()), heavy);
491
493 EXPECT_EQ(nodes.size(), 3u);
494 }
495}
496
497namespace
498{
500
501 // A random network with a path from the node 0 to the last one, so that
502 // it has one source and one sink, and capacities that are random reals,
503 // or tenths, whose sums round
504 Double_Net random_double_network(unsigned seed)
505 {
506 std::mt19937 gen(seed);
507 std::uniform_real_distribution<double> real(0.01, 10.0);
508 Double_Net net;
509 std::vector<Double_Net::Node *> v;
510 const int n = 4 + int(gen() % 20);
511 for (int i = 0; i < n; ++i)
512 v.push_back(net.insert_node(i));
513 auto cap = [&]() { return seed % 2 ? real(gen) : 0.1 * double(1 + gen() % 9); };
514 for (int i = 0; i + 1 < n; ++i)
515 net.insert_arc(v[i], v[i + 1], cap(), 0.0);
516 for (int k = 0, m = int(gen() % 80); k < m; ++k)
517 {
518 const int a = int(gen() % (n - 1)), b = 1 + int(gen() % (n - 1));
519 if (a < b)
520 net.insert_arc(v[a], v[b], cap(), 0.0);
521 }
522 return net;
523 }
524
525 // Every flow is between zero and the capacity of its arc
526 bool flows_within_capacities(Double_Net & net)
527 {
528 for (Double_Net::Arc_Iterator it(net); it.has_curr(); it.next_ne())
529 if (auto a = it.get_curr(); a->flow < 0 or a->flow > a->cap)
530 return false;
531 return true;
532 }
533}
534
535// With a floating type of flow, an augmentation could leave a flow above
536// the capacity of its arc, below zero, or next to zero on an arc of a node
537// without other flow, by rounding: the checks of the network then failed,
538// and so did its assertion in increase_flow(), in a build that has them
539TEST(NetGraphAugmentingPaths, FloatingFlowsStayWithinTheirCapacities)
540{
541 for (unsigned seed = 0; seed < 300; ++seed)
542 {
543 SCOPED_TRACE(seed);
544 Double_Net ff_net = random_double_network(seed);
545 Double_Net ek_net = random_double_network(seed);
546 Double_Net dinic_net = random_double_network(seed);
547 ASSERT_TRUE(ff_net.is_single_source() and ff_net.is_single_sink());
548
549 const double ff = ford_fulkerson_maximum_flow(ff_net);
550 const double ek = edmonds_karp_maximum_flow(ek_net);
551 const double dinic = dinic_maximum_flow(dinic_net);
552
553 EXPECT_NEAR(ff, dinic, 1e-9 * std::max(1.0, dinic));
554 EXPECT_NEAR(ek, dinic, 1e-9 * std::max(1.0, dinic));
555 EXPECT_TRUE(flows_within_capacities(ff_net));
556 EXPECT_TRUE(flows_within_capacities(ek_net));
557 EXPECT_TRUE(ff_net.check_network());
558 EXPECT_TRUE(ek_net.check_network());
559 }
560}
561
562// A path of arcs of infinite capacity carries an infinite flow, which its
563// nodes take in and send out: equal flows balance, also infinite ones,
564// whose difference, inf - inf, is NaN, which check_node() and the
565// comparison of the totals took as an imbalance, so that check_network()
566// was false and flow_value() failed its assertion. An infinite flow into
567// a node that sends 2.5 does not balance, which the tolerance of an
568// infinite flow, infinite too, took as balanced
569TEST(NetGraphInfiniteFlows, EqualInfiniteFlowsBalanceAndUnequalOnesDoNot)
570{
571 const double inf = std::numeric_limits<double>::infinity();
572 Double_Net net;
573 auto s = net.insert_node(0);
574 auto a = net.insert_node(1);
575 auto t = net.insert_node(2);
576 auto sa = net.insert_arc(s, a, inf);
577 auto at = net.insert_arc(a, t, inf);
578 auto st = net.insert_arc(s, t, 2.5);
579 sa->flow = inf;
580 at->flow = inf;
581 st->flow = 2.5;
582 EXPECT_TRUE(net.check_node(a));
583 EXPECT_TRUE(net.check_network());
584 EXPECT_EQ(net.flow_value(), inf);
585
586 at->flow = 2.5; // a receives inf and sends 2.5
587 EXPECT_FALSE(net.check_node(a));
588 EXPECT_FALSE(net.check_network());
589}
590
591// Ford-Fulkerson and Edmonds-Karp take a path of arcs of infinite capacity
592// and return the infinite maximum flow, which check_network() takes; with
593// assertions, they aborted, as check_network() was false
594TEST(NetGraphInfiniteFlows, TheAugmentingPathsReturnAnInfiniteMaximumFlow)
595{
596 const double inf = std::numeric_limits<double>::infinity();
597 for (int algo = 0; algo < 2; ++algo)
598 {
599 Double_Net net;
600 auto s = net.insert_node(0);
601 auto a = net.insert_node(1);
602 auto t = net.insert_node(2);
603 net.insert_arc(s, a, inf);
604 net.insert_arc(a, t, inf);
605 net.insert_arc(s, t, 2.5);
606 const double value = algo == 0 ? ford_fulkerson_maximum_flow(net)
608 EXPECT_EQ(value, inf) << (algo == 0 ? "ford_fulkerson" : "edmonds_karp");
609 EXPECT_TRUE(net.check_network()) << (algo == 0 ? "ford_fulkerson" : "edmonds_karp");
610 }
611}
612
613// =============================================================================
614// What Net_Graph tells a network derived from it
615// =============================================================================
616
617namespace
618{
619 // A network that counts the calls to swapped() and the arcs that are
620 // disconnected from it
621 struct Told_Net : Net
622 {
623 int swaps = 0;
624 int disconnections = 0;
625
626 void swapped() noexcept override { ++swaps; }
627
628 void disconnect_arc(Arc *arc) override
629 {
630 ++disconnections;
632 }
633 };
634}
635
636// swap(), the move and the assignments of Net_Graph, through a reference to
637// it, tell once each network whose nodes and arcs they exchange
638TEST(NetGraphDerived, ASwapTellsItsTwoNetworks)
639{
640 Told_Net one, two;
641 build_single_arc(one, 5);
642 Net &base = one;
643
644 base.swap(two);
645 EXPECT_EQ(one.swaps, 1);
646 EXPECT_EQ(two.swaps, 1);
647 EXPECT_EQ(two.get_num_arcs(), 1U);
648
649 base = std::move(static_cast<Net &>(two)); // a swap
650 EXPECT_EQ(one.swaps, 2);
651 EXPECT_EQ(two.swaps, 2);
652 EXPECT_EQ(one.get_num_arcs(), 1U);
653
654 Net plain;
655 base = plain; // a copy of plain, and a swap with it
656 EXPECT_EQ(one.swaps, 3);
657 EXPECT_EQ(two.swaps, 2);
658
659 Net taken(std::move(base)); // it tells the network that it empties
660 EXPECT_EQ(one.swaps, 4);
661}
662
663// a network swapped with itself keeps its nodes and its arcs: nothing to
664// tell
665TEST(NetGraphDerived, ASwapWithItselfTellsNothing)
666{
667 Told_Net net;
668 build_single_arc(net, 5);
669 Net &base = net;
670
671 base.swap(base);
672 EXPECT_EQ(net.swaps, 0);
673 EXPECT_EQ(net.get_num_nodes(), 2U);
674 EXPECT_EQ(net.get_num_arcs(), 1U);
675}
676
677// disconnect_arc() is virtual, as remove_arc()
678TEST(NetGraphDerived, ADisconnectionThroughTheBaseIsThatOfTheDerivedNetwork)
679{
680 Told_Net net;
681 auto sn = build_single_arc(net, 5);
682 Net &base = net;
683
684 base.disconnect_arc(sn.st);
685 EXPECT_EQ(net.disconnections, 1);
686 EXPECT_EQ(net.get_num_arcs(), 0U);
687
688 base.connect_arc(sn.st);
689 EXPECT_EQ(net.get_num_arcs(), 1U);
690}
691
692// =============================================================================
693// Every network derived from Net_Graph, once its nodes and arcs changed
694// through a reference to the base
695// =============================================================================
696//
697// A network may keep something for its nodes and its arcs: Net_Graph its
698// super nodes and its sets of sources and of sinks, Net_Cap_Graph an
699// auxiliary network that points to them, Net_Sup_Dem_Graph its two super
700// nodes, and Net_Cost_Graph nothing, since the costs are in the arcs.
701// Whatever changes the nodes and the arcs through a reference to Net_Graph
702// must leave the network either with what it keeps or knowing that it lost
703// it: the use of what it keeps says so, and touches no node nor arc that
704// the network no longer has, which the sanitizers see. A network derived
705// from Net_Graph that is not in Derived_Networks is not checked here: add
706// it, with its Kept_By.
707
708namespace
709{
710 // For a network derived from Net_Graph: fill() gives it nodes, arcs and
711 // what it keeps for them; use() uses all that it keeps and returns
712 // whether the network had it; apart says whether it stays when the nodes
713 // and the arcs go to another network
714 template <class N>
715 struct Kept_By;
716
717 // its super source, over two sources
718 template <>
719 struct Kept_By<Net_Graph<>>
720 {
721 static constexpr bool apart = false;
722
723 static void fill(Net_Graph<> &net)
724 {
725 auto a = net.insert_node();
726 auto b = net.insert_node();
727 auto c = net.insert_node();
728 net.insert_arc(a, c, 1.0, 0.0);
729 net.insert_arc(b, c, 1.0, 0.0);
730 net.make_super_source();
731 }
732
733 static bool use(Net_Graph<> &net)
734 {
735 if (not net.with_super_source)
736 return false;
738 return true;
739 }
740 };
741
742 // its auxiliary network, whose arcs point to its nodes and arcs
743 template <>
744 struct Kept_By<Net_Cap_Graph<>>
745 {
746 static constexpr bool apart = true;
747
748 static void fill(Net_Cap_Graph<> &net)
749 {
750 auto a = net.insert_node(10.0);
751 auto b = net.insert_node(5.0);
752 auto c = net.insert_node(10.0);
753 net.insert_arc(a, b, 8.0, 0.0);
754 net.insert_arc(b, c, 8.0, 0.0);
755 net.compute_aux_net();
756 }
757
758 static bool use(Net_Cap_Graph<> &net)
759 {
760 if (not net.has_aux_net())
761 return false;
762 bool used = true;
763 try
764 {
765 net.update();
766 }
767 catch (const std::domain_error &)
768 {
769 used = false;
770 }
771 net.free_aux_net();
772 return used;
773 }
774 };
775
776 // its super source and its super sink, which are nodes of it
777 template <>
778 struct Kept_By<Net_Sup_Dem_Graph<>>
779 {
780 static constexpr bool apart = true;
781
782 static void fill(Net_Sup_Dem_Graph<> &net)
783 {
784 auto s = net.insert_node(10.0);
785 auto t = net.insert_node(-10.0);
786 net.insert_arc(s, t, 20.0, 0.0);
787 net.compute_aux_net();
788 }
789
790 static bool use(Net_Sup_Dem_Graph<> &net)
791 {
792 if (not net.exist_aux_net())
793 return false;
794 (void) net.is_feasible();
795 DynDlist<Net_Sup_Dem_Graph<>::Node *> supplies, demands;
796 net.non_feasible_nodes(supplies, demands);
797 net.free_aux_net();
798 return true;
799 }
800 };
801
802 // nothing: the costs go with the arcs
803 template <>
804 struct Kept_By<Net_Cost_Graph<>>
805 {
806 static constexpr bool apart = false;
807
808 static void fill(Net_Cost_Graph<> &net)
809 {
810 auto a = net.insert_node();
811 auto b = net.insert_node();
812 net.insert_arc(a, b, 5.0, 2.0);
813 }
814
815 static bool use(Net_Cost_Graph<> &net)
816 {
817 (void) net.flow_cost();
818 return true;
819 }
820 };
821
822 // Whether the numbers of nodes and of arcs of net are those that its
823 // iterators see, and its sources and its sinks are nodes of it
824 template <class B>
825 bool sound(const B &net)
826 {
827 size_t nodes = 0, arcs = 0;
828 for (typename B::Node_Iterator it(net); it.has_curr(); it.next_ne())
829 ++nodes;
830 for (typename B::Arc_Iterator it(net); it.has_curr(); it.next_ne())
831 ++arcs;
832 if (nodes != net.get_num_nodes() or arcs != net.get_num_arcs())
833 return false;
834 auto is_node = [&net] (typename B::Node *p)
835 {
836 for (typename B::Node_Iterator it(net); it.has_curr(); it.next_ne())
837 if (it.get_curr() == p)
838 return true;
839 return false;
840 };
841 for (auto it = net.get_src_nodes().get_it(); it.has_curr(); it.next_ne())
842 if (not is_node(it.get_curr()))
843 return false;
844 for (auto it = net.get_sink_nodes().get_it(); it.has_curr(); it.next_ne())
845 if (not is_node(it.get_curr()))
846 return false;
847 return true;
848 }
849
850 // three nodes in a chain, with nothing kept for them
851 template <class B>
852 void fill_chain(B &net)
853 {
854 auto x = net.insert_node();
855 auto y = net.insert_node();
856 auto z = net.insert_node();
857 net.insert_arc(x, y, 1.0, 0.0);
858 net.insert_arc(y, z, 1.0, 0.0);
859 }
860
861 template <class N>
862 class NetDerivedChanged : public ::testing::Test
863 {};
864
865 using Derived_Networks = ::testing::Types<Net_Graph<>, Net_Cap_Graph<>, Net_Sup_Dem_Graph<>, Net_Cost_Graph<>>;
866}
867
868TYPED_TEST_SUITE(NetDerivedChanged, Derived_Networks);
869
870// The ways that take all the nodes and the arcs of the network to another
871// one, or free them: the assignments, the swap() and the move of Net_Graph
872TYPED_TEST(NetDerivedChanged, ItKnowsThatItsNodesWentThroughTheBase)
873{
874 using N = TypeParam;
876 using K = Kept_By<N>;
877 const char *const ways[] = {"a copy assignment", "a move assignment", "a swap()", "a move construction",
878 "a swap() with another one that keeps the same"};
879 // with the other network alive when what the network keeps is used, and
880 // gone, which frees the nodes that it took
881 for (const bool gone : {false, true})
882 for (int way = 0; way < 5; ++way)
883 {
884 SCOPED_TRACE(std::string(ways[way]) + (gone ? ", and the other network gone" : ""));
885 N net;
886 K::fill(net);
887 B &base = net;
888 auto plain = std::make_unique<B>();
889 fill_chain(*plain);
890 auto other = std::make_unique<N>();
891 K::fill(*other);
892 if (way == 0)
893 base = *plain;
894 else if (way == 1)
895 base = std::move(*plain);
896 else if (way == 2)
897 base.swap(*plain);
898 else if (way == 3)
899 *plain = B(std::move(base));
900 else
901 base.swap(static_cast<B &>(*other));
902 if (gone)
903 {
904 plain.reset();
905 other.reset();
906 }
907
908 const bool used = K::use(net);
909 if (K::apart)
910 {
911 EXPECT_FALSE(used); // what it kept was for the nodes that went
912 }
913 EXPECT_TRUE(sound(base));
914 if (not gone)
915 {
916 if (way == 4)
917 {
918 const bool other_used = K::use(*other);
919 if (K::apart)
920 {
921 EXPECT_FALSE(other_used);
922 }
923 }
924 EXPECT_TRUE(sound(*plain));
925 EXPECT_TRUE(sound(static_cast<B &>(*other)));
926 }
927 }
928}
929
930// The ways that take some of them, or none: what the network keeps is used
931// then, or refused, and nothing that is gone is touched
932TYPED_TEST(NetDerivedChanged, ItUsesNothingThatIsGoneAfterAChangeThroughTheBase)
933{
934 using N = TypeParam;
936 using K = Kept_By<N>;
937 const char *const ways[] = {"nothing", "a swap() with itself", "an assignment to itself", "a move to itself",
938 "remove_node() of its first node", "remove_arc() of its first arc",
939 "an arc disconnected and freed", "clear_graph()", "copy_graph() into it"};
940 for (int way = 0; way < 9; ++way)
941 {
942 SCOPED_TRACE(ways[way]);
943 N net;
944 K::fill(net);
945 B &base = net;
946 B &same = net;
947 B plain;
948 fill_chain(plain);
949 if (way == 1)
950 base.swap(same);
951 else if (way == 2)
952 base = static_cast<const B &>(same);
953 else if (way == 3)
954 base = std::move(same);
955 else if (way == 4)
956 base.remove_node(base.get_first_node());
957 else if (way == 5)
958 base.remove_arc(base.get_first_arc());
959 else if (way == 6)
960 {
961 auto a = base.get_first_arc();
962 base.disconnect_arc(a);
963 delete a;
964 }
965 else if (way == 7)
966 clear_graph(base);
967 else if (way == 8)
968 copy_graph(base, plain);
969
970 const bool used = K::use(net);
971 if (way < 4)
972 {
973 EXPECT_TRUE(used); // the network is the one that it was
974 }
975 EXPECT_TRUE(sound(base));
976 EXPECT_TRUE(sound(plain));
977 }
978}
WeightedDigraph::Arc Arc
size_t size_t int32_t value
Definition ca-c-api.h:116
Generic directed graph (digraph) wrapper template.
Definition graph-dry.H:4377
Dynamic doubly linked list with O(1) size and bidirectional access.
Iterator on the items of list.
Definition htlist.H:1614
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
T & get_first()
Return the first item of the list.
Definition htlist.H:1548
size_t size() const noexcept
Return the number of items of the list, in constant time.
Definition htlist.H:1264
Dynamic set backed by balanced binary search trees with automatic memory management.
const size_t & size() const
Returns the cardinality of the set.
bool contains(const Key &key) const
Checks if a key exists in the set.
void next_ne() noexcept(shows_ne)
Advances the iterator to the next filtered element, as next() does.
Augmenting-path search over a directed network.
Definition tpl_net.H:1822
Net::Flow_Type semi_path(typename Net::Node *start, typename Net::Node *end, DynList< Parc< Net > > &semi_path, const typename Net::Flow_Type &min_slack=0)
Fill semi_path and return the slack value.
Definition tpl_net.H:1982
bool has_curr() const noexcept
Definition htlist.H:969
constexpr bool is_empty() const noexcept
Definition htlist.H:434
Number Theoretic Transform over Z / MOD Z.
Definition ntt.H:115
Capacitated network with node capacity constraints.
bool has_aux_net() const noexcept
Check if auxiliary network has been computed.
void free_aux_net()
Free the auxiliary network.
void update()
Update flow values from auxiliary network to this network.
Node * insert_node(Node *p) override
Aux_Net * compute_aux_net()
Compute the equivalent arc-capacitated auxiliary network.
Network graph with supply and demand nodes.
void non_feasible_nodes(DynDlist< Node * > &supply_list, DynDlist< Node * > &demand_list)
Get lists of nodes with unsatisfied supply/demand.
bool exist_aux_net() const noexcept
Check if the auxiliary network has been computed.
void free_aux_net()
Free the auxiliary network structures.
bool is_feasible() const
Check if the current flow is feasible.
Net_Sup_Dem_Graph * compute_aux_net()
Compute the auxiliary capacitated network.
Node * insert_node(const Node_Type &node_info, const Flow_Type &supply)
Insert a node with info and supply/demand value.
Path on a graph.
Definition tpl_graph.H:3832
constexpr size_t get_num_nodes() const noexcept
Return the total of nodes of graph.
Definition graph-dry.H:975
constexpr size_t get_num_arcs() const noexcept
Return the number of arcs of the graph.
Definition graph-dry.H:1064
#define TEST(name)
DynArray< Graph::Node * > nodes
Definition graphpic.C:406
DynArray< Graph::Arc * > arcs
Definition graphpic.C:408
void clear_graph(GT &g)
Clean a graph: all its nodes and arcs are removed and freed.
Definition tpl_graph.H:4776
void copy_graph(GT &gtgt, const GT &gsrc, bool cookie_map=false)
Explicit copy of graph.
Definition tpl_graph.H:4794
static mpfr_t y
Definition mpfr_mul_d.c:3
Main namespace for Aleph-w library functions.
Net::Flow_Type edmonds_karp_maximum_flow(Net &net)
Maximize flow using the Edmonds-Karp algorithm.
Definition tpl_net.H:2336
Net::Flow_Type random_preflow_maximum_flow(Net &net)
Preflow-push maximum flow using a random active-node queue.
Definition tpl_net.H:2738
Path< Net > find_aumenting_path_dfs(const Net &net, const typename Net::Flow_Type &min_slack)
Find an augmenting path using DFS.
Definition tpl_net.H:2027
Net::Flow_Type dinic_maximum_flow(Net &net)
Compute maximum flow using Dinic's algorithm.
Net::Flow_Type heap_preflow_maximum_flow(Net &net)
Preflow-push maximum flow using a height-ordered heap.
Definition tpl_net.H:2706
Itor2 copy(Itor1 sourceBeg, const Itor1 &sourceEnd, Itor2 destBeg)
Copy elements from one range to another.
Definition ahAlgo.H:584
void fill(Itor beg, const Itor &end, const T &value)
Fill a range with a value.
Definition ahAlgo.H:707
Net::Flow_Type increase_flow(Net &net, const Path< Net > &path)
Increase flow along an augmenting path.
Definition tpl_net.H:1714
std::tuple< PP_Res_Net< Net >, typename PP_Res_Net< Net >::Node *, typename PP_Res_Net< Net >::Node * > preflow_create_residual_net(Net &net)
Build the residual network for preflow-push algorithms.
Definition tpl_net.H:2195
and
Check uniqueness with explicit hash + equality functors.
Net::Flow_Type fifo_preflow_maximum_flow(Net &net)
Preflow-push maximum flow using a FIFO queue of active nodes.
Definition tpl_net.H:2668
Net::Flow_Type ford_fulkerson_maximum_flow(Net &net)
Maximize flow using the Ford-Fulkerson algorithm.
Definition tpl_net.H:2306
void update_flow(const Rnet &rnet)
Propagate residual arc flows back to their original arcs.
Definition tpl_net.H:2223
Net_Sup_Dem_Graph< SimpleNode, SimpleArc > SimpleNet
Filtered iterator on all the arcs of a graph.
Definition tpl_graph.H:1200
Arc of a flow network implemented with adjacency lists.
Definition tpl_net.H:160
Capacitated flow network with costs associated to arcs.
Flow_Type flow_cost() const
Compute the total cost of flow circulating through the network.
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.
Arc filter for residual traversal in flow networks.
Definition tpl_net.H:224
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
const DynSetTree< Node * > & get_sink_nodes() const noexcept
Return the set of sink nodes.
Definition tpl_net.H:595
bool check_network() const
Validate flow-conservation and capacity constraints.
Definition tpl_net.H:1116
const DynSetTree< Node * > & get_src_nodes() const noexcept
Return the set of source nodes.
Definition tpl_net.H:589
Arc * connect_arc(Arc *arc)
Connect a previously disconnected arc.
Definition tpl_net.H:832
void remove_arc(Arc *arc) override
Remove arc arc from the network.
Definition tpl_net.H:906
virtual void disconnect_arc(Arc *arc)
Disconnect arc arc from the graph without deleting it.
Definition tpl_net.H:921
void make_super_source()
Convert a multi-source network into a single super-source network.
Definition tpl_net.H:603
void make_super_sink()
Convert a multi-sink network into a single super-sink network.
Definition tpl_net.H:656
size_t get_out_degree(Node *p) const noexcept
Return the out-degree of p (number of outgoing arcs).
Definition tpl_net.H:393
bool is_source(Node *node) const noexcept
Return true if node is a source.
Definition tpl_net.H:417
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
bool with_super_source
True if the network has a super-source.
Definition tpl_net.H:1150
ArcT Arc
Arc type.
Definition tpl_net.H:322
virtual void swapped() noexcept
What swap() calls on each of its two networks, once their nodes and arcs are exchanged: nothing,...
Definition tpl_net.H:1023
void unmake_super_sink()
Restore a super-sink network to its original multi-sink form, by removing the super sink that make_su...
Definition tpl_net.H:688
Node * get_sink() const
Return an arbitrary sink node.
Definition tpl_net.H:739
bool is_sink(Node *node) const noexcept
Return true if node is a sink.
Definition tpl_net.H:423
Flow_Type flow_value() const
Return the total flow value of the network: the flow out of its sources, which a valid flow also take...
Definition tpl_net.H:1139
NodeT Node
Node type.
Definition tpl_net.H:325
void unmake_super_source()
Restore a super-source network to its original multi-source form, by removing the super source that m...
Definition tpl_net.H:640
size_t get_in_degree(Node *p) const noexcept
Return the in-degree of p (number of incoming arcs).
Definition tpl_net.H:387
void swap(Net_Graph &other) noexcept
Swap contents with another network.
Definition tpl_net.H:1032
Filtered iterator of adjacent arcs of a node.
Definition tpl_graph.H:1155
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
ValueArg< size_t > seed
Definition testHash.C:53
static int * k
Gsl_Compatible_Rng r
Dynamic doubly linked list implementation.
Advanced maximum flow algorithms.
Network flow graph structures.
Supply-demand network flow algorithms.
TYPED_TEST(NetDerivedChanged, ItKnowsThatItsNodesWentThroughTheBase)
TYPED_TEST_SUITE(NetDerivedChanged, Derived_Networks)
Network flow graph with capacities.
Maximum flow minimum cost network algorithms.
DynList< int > l