Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
archeap_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
38#include <gtest/gtest.h>
39
40#include <algorithm>
41#include <limits>
42#include <map>
43#include <memory>
44#include <random>
45#include <stdexcept>
46#include <unordered_map>
47#include <utility>
48#include <vector>
49
50#if defined(__unix__) || defined(__APPLE__)
51#include <pthread.h>
52#endif
53
54#include <tpl_graph.H>
55#include <archeap.H>
56
57using namespace Aleph;
58
59namespace
60{
62 using Node = Graph::Node;
63 using Arc = Graph::Arc;
64
65 std::vector<Node *> make_nodes(Graph &g, int n)
66 {
67 std::vector<Node *> nodes;
68 nodes.reserve(n);
69 for (int i = 0; i < n; ++i)
70 nodes.push_back(g.insert_node(i));
71 return nodes;
72 }
73
74 struct ArcWeightDist
75 {
76 int operator()(Arc *a) const noexcept
77 {
78 return a->get_info();
79 }
80 };
81
83 using HeapNode = typename BinHeapType::Node;
84
85 struct MapAccess
86 {
87 std::unordered_map<Node *, HeapNode *> *map = nullptr;
88
89 MapAccess() = default;
90
91 explicit MapAccess(std::unordered_map<Node *, HeapNode *> &m) noexcept
92 : map(&m)
93 { }
94
95 HeapNode *& operator()(Node *p)
96 {
97 return (*map)[p];
98 }
99 };
100
102} // namespace
103
104TEST(ArcHeapBasic, SingleArcInsertAndExtract)
105{
106 Graph g;
107 auto nodes = make_nodes(g, 2);
108 Arc *a = g.insert_arc(nodes[0], nodes[1], 5);
109
110 std::unordered_map<Node *, HeapNode *> mapping;
111 MapAccess access(mapping);
112 TestArcHeap heap(ArcWeightDist{}, access);
113
114 heap.put_arc(a, nodes[1]);
115
116 ASSERT_EQ(mapping.size(), 1U);
117 ASSERT_NE(mapping[nodes[1]], nullptr);
118
119 Arc *min_arc = heap.get_min_arc();
120 EXPECT_EQ(min_arc, a);
121 EXPECT_EQ(mapping[nodes[1]], nullptr);
122}
123
124TEST(ArcHeapBasic, KeepsBestOfParallelArcs)
125{
126 Graph g;
127 auto nodes = make_nodes(g, 2);
128 Arc *a1 = g.insert_arc(nodes[0], nodes[1], 10);
129 Arc *a2 = g.insert_arc(nodes[0], nodes[1], 3);
130
131 std::unordered_map<Node *, HeapNode *> mapping;
132 MapAccess access(mapping);
133 TestArcHeap heap(ArcWeightDist{}, access);
134
135 heap.put_arc(a1, nodes[1]);
136 heap.put_arc(a2, nodes[1]);
137
138 Arc *min_arc = heap.get_min_arc();
139 EXPECT_EQ(min_arc, a2);
140 EXPECT_EQ(mapping[nodes[1]], nullptr);
141}
142
143TEST(ArcHeapBasic, IgnoresWorseArcForSameTarget)
144{
145 Graph g;
146 auto nodes = make_nodes(g, 2);
147 Arc *a1 = g.insert_arc(nodes[0], nodes[1], 2);
148 Arc *a2 = g.insert_arc(nodes[0], nodes[1], 7);
149
150 std::unordered_map<Node *, HeapNode *> mapping;
151 MapAccess access(mapping);
152 TestArcHeap heap(ArcWeightDist{}, access);
153
154 heap.put_arc(a1, nodes[1]);
155 heap.put_arc(a2, nodes[1]);
156
157 Arc *min_arc = heap.get_min_arc();
158 EXPECT_EQ(min_arc, a1);
159 EXPECT_EQ(mapping[nodes[1]], nullptr);
160}
161
162TEST(ArcHeapBasic, ExtractsArcsInIncreasingDistanceAcrossTargets)
163{
164 Graph g;
165 auto nodes = make_nodes(g, 4);
166 Arc *a1 = g.insert_arc(nodes[0], nodes[1], 5);
167 Arc *a2 = g.insert_arc(nodes[0], nodes[2], 1);
168 Arc *a3 = g.insert_arc(nodes[0], nodes[3], 3);
169
170 std::unordered_map<Node *, HeapNode *> mapping;
171 MapAccess access(mapping);
172 TestArcHeap heap(ArcWeightDist{}, access);
173
174 heap.put_arc(a1, nodes[1]);
175 heap.put_arc(a2, nodes[2]);
176 heap.put_arc(a3, nodes[3]);
177
178 std::vector<int> extracted;
179 extracted.reserve(3);
180 extracted.push_back(heap.get_min_arc()->get_info());
181 extracted.push_back(heap.get_min_arc()->get_info());
182 extracted.push_back(heap.get_min_arc()->get_info());
183
184 EXPECT_EQ(extracted.size(), 3U);
185 EXPECT_TRUE(std::is_sorted(extracted.begin(), extracted.end()));
186}
187
188TEST(ArcHeapBasic, ClearsMappingForAllTargets)
189{
190 Graph g;
191 auto nodes = make_nodes(g, 4);
192 Arc *a1 = g.insert_arc(nodes[0], nodes[1], 4);
193 Arc *a2 = g.insert_arc(nodes[0], nodes[2], 2);
194 Arc *a3 = g.insert_arc(nodes[0], nodes[3], 6);
195
196 std::unordered_map<Node *, HeapNode *> mapping;
197 MapAccess access(mapping);
198 TestArcHeap heap(ArcWeightDist{}, access);
199
200 heap.put_arc(a1, nodes[1]);
201 heap.put_arc(a2, nodes[2]);
202 heap.put_arc(a3, nodes[3]);
203
204 EXPECT_EQ(mapping.size(), 3U);
205 EXPECT_NE(mapping[nodes[1]], nullptr);
206 EXPECT_NE(mapping[nodes[2]], nullptr);
207 EXPECT_NE(mapping[nodes[3]], nullptr);
208
209 (void)heap.get_min_arc();
210 (void)heap.get_min_arc();
211 (void)heap.get_min_arc();
212
213 EXPECT_EQ(mapping[nodes[1]], nullptr);
214 EXPECT_EQ(mapping[nodes[2]], nullptr);
215 EXPECT_EQ(mapping[nodes[3]], nullptr);
216}
217
218TEST(ArcHeapRandom, ExtractsNonDecreasingByDistance)
219{
220 std::mt19937 rng(123456);
221 std::uniform_int_distribution<int> node_count(2, 8);
222 std::uniform_int_distribution<int> weight_dist(0, 100);
223
224 for (int iter = 0; iter < 100; ++iter)
225 {
226 Graph g;
227 const int n = node_count(rng);
228 auto nodes = make_nodes(g, n);
229
230 std::unordered_map<Node *, HeapNode *> mapping;
231 MapAccess access(mapping);
232 TestArcHeap heap(ArcWeightDist{}, access);
233
234 std::vector<int> weights;
235 for (int i = 1; i < n; ++i)
236 {
237 const int w = weight_dist(rng);
238 Arc *a = g.insert_arc(nodes[0], nodes[i], w);
239 heap.put_arc(a, nodes[i]);
240 weights.push_back(w);
241 }
242
243 if (weights.empty())
244 continue;
245
246 std::vector<int> extracted;
247 extracted.reserve(weights.size());
248 for (size_t i = 0; i < weights.size(); ++i)
249 extracted.push_back(heap.get_min_arc()->get_info());
250
251 EXPECT_TRUE(std::is_sorted(extracted.begin(), extracted.end()));
252 }
253}
254
255namespace
256{
257 // The weight of an arc, or its negation when `negated` is set: a
258 // default-constructed instance orders the arcs the other way.
259 struct SignedWeightDist
260 {
261 bool negated = false;
262
263 int operator()(Arc *a) const noexcept
264 {
265 return negated ? -a->get_info() : a->get_info();
266 }
267 };
268
269 // The weight of an arc times a factor, with no default constructor.
270 struct FactorDist
271 {
272 int factor;
273
274 explicit FactorDist(int f) noexcept : factor(f) { }
275
276 int operator()(Arc *a) const noexcept
277 {
278 return factor * a->get_info();
279 }
280 };
281} // namespace
282
283// The heap ordered the arcs with a default-constructed distance; only the
284// choice between two arcs with the same target used the given one.
285TEST(ArcHeapDistance, OrdersByTheGivenDistance)
286{
287 Graph g;
288 auto nodes = make_nodes(g, 4);
289 Arc *a1 = g.insert_arc(nodes[0], nodes[1], 5);
290 Arc *a2 = g.insert_arc(nodes[0], nodes[2], 1);
291 Arc *a3 = g.insert_arc(nodes[0], nodes[3], 3);
292
293 std::unordered_map<Node *, HeapNode *> mapping;
294 MapAccess access(mapping);
295 ArcHeap<Graph, SignedWeightDist, MapAccess> heap(SignedWeightDist{true},
296 access);
297
298 heap.put_arc(a1, nodes[1]);
299 heap.put_arc(a2, nodes[2]);
300 heap.put_arc(a3, nodes[3]);
301
302 EXPECT_EQ(heap.get_min_arc(), a1);
303 EXPECT_EQ(heap.get_min_arc(), a3);
304 EXPECT_EQ(heap.get_min_arc(), a2);
305}
306
307// Building that default comparator required a default constructor.
308TEST(ArcHeapDistance, TakesADistanceWithoutADefaultConstructor)
309{
310 Graph g;
311 auto nodes = make_nodes(g, 3);
312 Arc *a1 = g.insert_arc(nodes[0], nodes[1], 4);
313 Arc *a2 = g.insert_arc(nodes[0], nodes[2], 2);
314
315 std::unordered_map<Node *, HeapNode *> mapping;
316 MapAccess access(mapping);
318
319 heap.put_arc(a1, nodes[1]);
320 heap.put_arc(a2, nodes[2]);
321
322 EXPECT_EQ(heap.get_min_arc(), a2);
323 EXPECT_EQ(heap.get_min_arc(), a1);
324}
325
326namespace
327{
328 // The weight of an arc; counts its calls, and the call number fail_at
329 // throws (0 for none).
330 struct FailingDist
331 {
332 long *calls = nullptr;
333 long fail_at = 0;
334
335 int operator()(Arc *a) const
336 {
337 if (calls != nullptr and ++*calls == fail_at)
338 throw std::runtime_error("arc weight not available");
339 return a->get_info();
340 }
341 };
342} // namespace
343
344// Comparing with the given distance, the heap called it in functions that
345// were noexcept, so a distance that threw there ended the program.
346TEST(ArcHeapDistance, WhatTheDistanceThrowsReachesTheCaller)
347{
348 Graph g;
349 auto nodes = make_nodes(g, 6);
350 std::vector<std::pair<Arc *, Node *>> puts;
351 for (int i = 1; i < 6; ++i)
352 puts.emplace_back(g.insert_arc(nodes[0], nodes[i], 10 * i), nodes[i]);
353 for (int i = 1; i < 6; i += 2) // lighter arcs that replace others
354 puts.emplace_back(g.insert_arc(nodes[0], nodes[i], 10 * i - 7), nodes[i]);
355
356 // Puts the arcs in a heap and takes them out, with a distance that fails
357 // at its call fail_at
358 auto put_and_take = [&](long &calls, long fail_at)
359 {
360 std::unordered_map<Node *, HeapNode *> mapping;
361 ArcHeap<Graph, FailingDist, MapAccess> heap(FailingDist{&calls, fail_at},
362 MapAccess(mapping));
363 std::vector<int> weights;
364 for (auto [arc, tgt] : puts)
365 heap.put_arc(arc, tgt);
366 while (not heap.is_empty())
367 weights.push_back(heap.get_min_arc()->get_info());
368 return weights;
369 };
370
371 long calls = 0;
372 EXPECT_EQ(put_and_take(calls, 0), (std::vector<int>{3, 20, 23, 40, 43}));
373
374 for (long k = 1; k <= calls; ++k)
375 {
376 long count = 0;
377 EXPECT_THROW(put_and_take(count, k), std::runtime_error) << "call " << k;
378 }
379}
380
381namespace
382{
383 // Keeps the handles of either heap as void *
384 struct VoidMapAccess
385 {
386 std::unordered_map<Node *, void *> *map = nullptr;
387
388 void *& operator()(Node *p) { return (*map)[p]; }
389 };
390
391 struct BinaryArcHeap
392 {
394 };
395
396 struct FibonacciArcHeap
397 {
399 };
400
401 template <class Kind>
402 struct ArcHeapLifecycle : public ::testing::Test
403 {
404 using Heap = typename Kind::Heap;
405
406 Graph g;
407 std::vector<Node *> nodes = make_nodes(g, 6);
408 std::vector<Arc *> arcs; // arcs[i - 1] goes from nodes[0] to nodes[i]
409
410 ArcHeapLifecycle()
411 {
412 for (int i = 1; i < 6; ++i)
413 arcs.push_back(g.insert_arc(nodes[0], nodes[i], 10 * i));
414 }
415
416 void put_all(Heap & heap)
417 {
418 for (int i = 1; i < 6; ++i)
419 heap.put_arc(arcs[i - 1], nodes[i]);
420 }
421
422 static std::vector<int> take_all(Heap & heap)
423 {
424 std::vector<int> weights;
425 while (not heap.is_empty())
426 weights.push_back(heap.get_min_arc()->get_info());
427 return weights;
428 }
429
430 static bool all_null(const std::unordered_map<Node *, void *> & handles)
431 {
432 return std::all_of(handles.begin(), handles.end(),
433 [](const auto & entry) { return entry.second == nullptr; });
434 }
435 };
436
437 using ArcHeapKinds = ::testing::Types<BinaryArcHeap, FibonacciArcHeap>;
438} // namespace
439
440TYPED_TEST_SUITE(ArcHeapLifecycle, ArcHeapKinds);
441
442// clear() deleted the heap nodes but left their handles, so putting an arc
443// to the same target again used a freed node.
444TYPED_TEST(ArcHeapLifecycle, ClearNullsTheHandles)
445{
446 std::unordered_map<Node *, void *> handles;
447 typename TestFixture::Heap heap(ArcWeightDist{}, VoidMapAccess{&handles});
448
449 this->put_all(heap);
450 heap.clear();
451 EXPECT_TRUE(heap.is_empty());
452 EXPECT_TRUE(this->all_null(handles));
453
454 heap.clear(); // twice
455 EXPECT_TRUE(heap.is_empty());
456
457 this->put_all(heap);
458 EXPECT_EQ(this->take_all(heap), (std::vector<int>{10, 20, 30, 40, 50}));
459 EXPECT_TRUE(this->all_null(handles));
460}
461
462// The destructor empties the heap in the same way, while the storage of the
463// handles is still alive.
464TYPED_TEST(ArcHeapLifecycle, DestroyingAFullHeapNullsTheHandles)
465{
466 std::unordered_map<Node *, void *> handles;
467 {
468 typename TestFixture::Heap heap(ArcWeightDist{}, VoidMapAccess{&handles});
469 this->put_all(heap);
470 }
471 EXPECT_TRUE(this->all_null(handles));
472}
473
474// The move constructor of ArcHeap moved its base, which pointed to the
475// header of the source, so the new heap broke once the source was gone.
476TYPED_TEST(ArcHeapLifecycle, MoveConstructionOutlivesTheSource)
477{
478 using Heap = typename TestFixture::Heap;
479 std::unordered_map<Node *, void *> handles;
480 std::unique_ptr<Heap> moved;
481 {
482 Heap source(ArcWeightDist{}, VoidMapAccess{&handles});
483 this->put_all(source);
484 moved = std::make_unique<Heap>(std::move(source));
485 EXPECT_TRUE(source.is_empty());
486 }
487
488 EXPECT_EQ(this->take_all(*moved), (std::vector<int>{10, 20, 30, 40, 50}));
489 EXPECT_TRUE(this->all_null(handles));
490}
491
492// The move assignment of ArcHeap did not compile, and that of
493// ArcFibonacciHeap left the handles of the arcs that the target held.
494TYPED_TEST(ArcHeapLifecycle, MoveAssignmentEmptiesTheTarget)
495{
496 using Heap = typename TestFixture::Heap;
497 std::unordered_map<Node *, void *> target_handles, source_handles;
498 Heap target(ArcWeightDist{}, VoidMapAccess{&target_handles});
499 target.put_arc(this->arcs[0], this->nodes[1]);
500 target.put_arc(this->arcs[1], this->nodes[2]);
501 {
502 Heap source(ArcWeightDist{}, VoidMapAccess{&source_handles});
503 this->put_all(source);
504 target = std::move(source);
505 EXPECT_TRUE(source.is_empty());
506 }
507
508 EXPECT_TRUE(this->all_null(target_handles));
509 EXPECT_EQ(this->take_all(target), (std::vector<int>{10, 20, 30, 40, 50}));
510 EXPECT_TRUE(this->all_null(source_handles));
511}
512
513namespace
514{
515 // Either heap of arcs, with the distance Dist
516 struct BinaryArcHeapOf
517 {
518 template <class Dist>
520 };
521
522 struct FibonacciArcHeapOf
523 {
524 template <class Dist>
526 };
527
528 template <class Kind>
529 struct ArcHeapWithDistance : public ::testing::Test
530 {
531 template <class Dist>
532 using Heap = typename Kind::template Heap<Dist>;
533
534 Graph g;
535 std::vector<Node *> nodes = make_nodes(g, 8);
536 };
537
538 using ArcHeapsOf = ::testing::Types<BinaryArcHeapOf, FibonacciArcHeapOf>;
539
540 // The calls of a distance, and the one that throws (0 for none)
541 struct Distance_Calls
542 {
543 long calls = 0;
544 long fail_at = 0;
545 };
546
547 // The weight of an arc; counts its calls in calls, which the copies of
548 // the distance share
549 struct Shared_Failing_Dist
550 {
551 Distance_Calls *calls = nullptr;
552
553 int operator()(Arc *a) const
554 {
555 if (calls != nullptr and ++calls->calls == calls->fail_at)
556 throw std::runtime_error("arc weight not available");
557 return a->get_info();
558 }
559 };
560} // namespace
561
562TYPED_TEST_SUITE(ArcHeapWithDistance, ArcHeapsOf);
563
564// get_distance() gave a copy that the heap did not use: changing it changed
565// neither the order of the arcs nor the choice between two arcs to the same
566// node
567TYPED_TEST(ArcHeapWithDistance, GetDistanceGivesTheDistanceThatOrders)
568{
569 using Heap = typename TestFixture::template Heap<SignedWeightDist>;
570 auto & nodes = this->nodes;
571 Arc *a1 = this->g.insert_arc(nodes[0], nodes[1], 1);
572 Arc *a2 = this->g.insert_arc(nodes[0], nodes[2], 2);
573 Arc *a3 = this->g.insert_arc(nodes[0], nodes[3], 3);
574 Arc *a4 = this->g.insert_arc(nodes[0], nodes[3], 4); // parallel to a3
575
576 std::unordered_map<Node *, void *> handles;
577 Heap heap(SignedWeightDist{false}, VoidMapAccess{&handles});
578 EXPECT_FALSE(heap.get_distance().negated);
579 heap.get_distance().negated = true; // the heaviest arcs first
580
581 heap.put_arc(a1, nodes[1]);
582 heap.put_arc(a2, nodes[2]);
583 heap.put_arc(a3, nodes[3]);
584 heap.put_arc(a4, nodes[3]); // replaces a3, which is lighter
585
586 Heap moved(std::move(heap)); // with its distance
587 EXPECT_TRUE(moved.get_distance().negated);
588 EXPECT_EQ(moved.get_min_arc(), a4);
589 EXPECT_EQ(moved.get_min_arc(), a2);
590 EXPECT_EQ(moved.get_min_arc(), a1);
591 EXPECT_TRUE(moved.is_empty());
592
593 Heap assigned(SignedWeightDist{false}, VoidMapAccess{&handles});
594 assigned = std::move(moved);
595 EXPECT_TRUE(assigned.get_distance().negated);
596}
597
598// If the distance throws, each arc in the heap has its handle, and each
599// handle that is set is that of an arc in the heap. ArcFibonacciHeap lost
600// the node that it was taking out and could leave the others out of the
601// heap, and it kept the node of a new arc whose handle was not set.
602TYPED_TEST(ArcHeapWithDistance, WhatTheDistanceThrowsLeavesEachArcWithItsHandle)
603{
604 using Heap = typename TestFixture::template Heap<Shared_Failing_Dist>;
605 auto & nodes = this->nodes;
606 std::vector<std::pair<Arc *, Node *>> puts;
607 for (int i = 1; i < 8; ++i)
608 puts.emplace_back(this->g.insert_arc(nodes[0], nodes[i], 10 * i), nodes[i]);
609 for (int i = 1; i < 8; i += 2) // lighter arcs that replace others
610 puts.emplace_back(this->g.insert_arc(nodes[0], nodes[i], 10 * i - 7),
611 nodes[i]);
612
613 // Puts the arcs in a heap and takes them out, with a distance that
614 // fails at the call calls.fail_at
615 auto put_and_take = [&puts](Distance_Calls & calls)
616 {
617 std::unordered_map<Node *, void *> handles;
618 Heap heap(Shared_Failing_Dist{&calls}, VoidMapAccess{&handles});
619 try
620 {
621 std::vector<int> weights;
622 for (auto [arc, tgt] : puts)
623 heap.put_arc(arc, tgt);
624 while (not heap.is_empty())
625 weights.push_back(heap.get_min_arc()->get_info());
626 return weights;
627 }
628 catch (...)
629 {
630 calls.fail_at = 0;
631 const auto set = std::count_if(handles.begin(), handles.end(),
632 [](const auto & entry)
633 { return entry.second != nullptr; });
634 long taken = 0;
635 while (not heap.is_empty())
636 {
637 (void) heap.get_min_arc();
638 ++taken;
639 }
640 EXPECT_EQ(taken, long(set));
641 EXPECT_TRUE(std::all_of(handles.begin(), handles.end(),
642 [](const auto & entry)
643 { return entry.second == nullptr; }));
644 throw;
645 }
646 };
647
648 Distance_Calls calls;
649 EXPECT_EQ(put_and_take(calls),
650 (std::vector<int>{3, 20, 23, 40, 43, 60, 63}));
651
652 for (long k = 1; k <= calls.calls; ++k)
653 {
654 Distance_Calls failing;
655 failing.fail_at = k;
656 EXPECT_THROW(put_and_take(failing), std::runtime_error) << "call " << k;
657 }
658}
659
660// If the distance throws, the heap is as it was before the call: it has the
661// arcs that it had, one for each of their targets, and they come out in
662// order afterwards. ArcHeap could be left out of order, with the new arc
663// in it, or without the arc that it was taking out; ArcFibonacciHeap,
664// without that arc, or with the new arc in a node under a heavier one
665TYPED_TEST(ArcHeapWithDistance, WhatTheDistanceThrowsLeavesTheHeapAsItWas)
666{
667 using Heap = typename TestFixture::template Heap<Shared_Failing_Dist>;
668 auto & nodes = this->nodes;
669 std::vector<std::pair<Arc *, Node *>> puts;
670 for (int round = 0; round < 3; ++round) // lighter and lighter arcs to each target
671 for (int i = 1; i < 8; ++i)
672 puts.emplace_back(this->g.insert_arc(nodes[0], nodes[i], 100 - 30*round + 3*((i*5) % 7)), nodes[i]);
673
674 // Puts the arcs in a heap, taking the minimum out after every third one,
675 // with a distance that fails at the call calls.fail_at. Returns whether
676 // it failed, and leaves in in_steps the calls of those steps
677 long in_steps = 0;
678 auto put_and_take = [&puts, &in_steps](Distance_Calls & calls)
679 {
680 std::unordered_map<Node *, void *> handles;
681 Heap heap(Shared_Failing_Dist{&calls}, VoidMapAccess{&handles});
682 std::map<Node *, Arc *> in_heap; // the arc of each target
683 // The arcs of the heap, as they come out, are those of in_heap by weight
684 auto check = [&heap, &in_heap, &handles]
685 {
686 std::vector<int> expected;
687 for (const auto & entry : in_heap)
688 expected.push_back(entry.second->get_info());
689 std::sort(expected.begin(), expected.end());
690 const auto set = std::count_if(handles.begin(), handles.end(),
691 [](const auto & entry) { return entry.second != nullptr; });
692 EXPECT_EQ(static_cast<size_t>(set), in_heap.size());
693 std::vector<int> out;
694 while (not heap.is_empty())
695 out.push_back(heap.get_min_arc()->get_info());
696 EXPECT_EQ(out, expected);
697 };
698 try
699 {
700 size_t step = 0;
701 for (auto [arc, tgt] : puts)
702 {
703 heap.put_arc(arc, tgt);
704 const auto it = in_heap.find(tgt);
705 if (it == in_heap.end() or not (it->second->get_info() < arc->get_info()))
706 in_heap[tgt] = arc;
707 if (++step % 3 != 0)
708 continue;
709 int least = std::numeric_limits<int>::max(); // of the arcs that are in
710 for (const auto & entry : in_heap)
711 least = std::min(least, entry.second->get_info());
712 Arc *min = heap.get_min_arc();
713 EXPECT_EQ(min->get_info(), least);
714 const auto of_min = std::find_if(in_heap.begin(), in_heap.end(),
715 [min](const auto & entry) { return entry.second == min; });
716 EXPECT_NE(of_min, in_heap.end());
717 if (of_min != in_heap.end())
718 in_heap.erase(of_min);
719 }
720 }
721 catch (const std::runtime_error &)
722 {
723 calls.fail_at = 0;
724 check();
725 return true;
726 }
727 calls.fail_at = 0; // none of the calls of the steps failed
728 in_steps = calls.calls;
729 check();
730 return false;
731 };
732
733 Distance_Calls calls;
734 EXPECT_FALSE(put_and_take(calls));
735 const long steps_calls = in_steps;
736 EXPECT_GT(steps_calls, 40);
737
738 for (long k = 1; k <= steps_calls; ++k)
739 {
740 Distance_Calls failing;
741 failing.fail_at = k;
742 EXPECT_TRUE(put_and_take(failing)) << "call " << k;
743 }
744}
745
746namespace
747{
748 using FibonacciHeapOfArcs =
750 using FibonacciNode = FibonacciHeapOfArcs::handle_type;
751
752 // Runs f, which must not throw, in a thread with a stack of 256 KiB, which
753 // a recursion as deep as the trees of these tests are high overflows.
754 // Without POSIX threads, it runs f in this thread.
755 template <class F>
756 void run_with_small_stack(F f)
757 {
758#if defined(__unix__) || defined(__APPLE__)
759 pthread_attr_t attr;
760 ASSERT_EQ(pthread_attr_init(&attr), 0);
761 ASSERT_EQ(pthread_attr_setstacksize(&attr, 256 * 1024), 0);
762 auto start = [](void *arg) -> void *
763 {
764 (*static_cast<F *>(arg))();
765 return nullptr;
766 };
767 pthread_t thread;
768 const int created = pthread_create(&thread, &attr, start, &f);
769 pthread_attr_destroy(&attr);
770 ASSERT_EQ(created, 0);
771 ASSERT_EQ(pthread_join(thread, nullptr), 0);
772#else
773 f();
774#endif
775 }
776
777 // A graph whose arcs go from a hub to other nodes, and the handles that a
778 // Fibonacci heap of its arcs keeps for the nodes
779 struct HubGraph
780 {
781 Graph g;
782 Node *hub = g.insert_node(0);
783 std::unordered_map<Node *, void *> handles;
784
785 bool all_null() const
786 {
787 return std::all_of(handles.begin(), handles.end(),
788 [](const auto & entry) { return entry.second == nullptr; });
789 }
790
791 FibonacciNode handle(Node *p) { return static_cast<FibonacciNode>(handles[p]); }
792 };
793
794 // Puts in heap, which must be empty, a single tree that is a chain of n
795 // heap nodes (CLRS, exercise 19.4-1), and returns the node whose handle is
796 // its root. Each round puts the arcs a < b < c below the root and takes a,
797 // so that b takes c and the chain as children; then it puts a lighter arc
798 // to the node of c, which cuts c, and takes it, so that b ends on top.
799 Node * build_chain(HubGraph & hg, FibonacciHeapOfArcs & heap, int n)
800 {
801 int key = 4 * n;
802 Node *top = hg.g.insert_node(1);
803 heap.put_arc(hg.g.insert_arc(hg.hub, top, key), top);
804
805 Node *node_a = hg.g.insert_node(2), *node_c = hg.g.insert_node(3);
806 Arc *a = hg.g.insert_arc(hg.hub, node_a, 0);
807 Arc *c = hg.g.insert_arc(hg.hub, node_c, 0);
808 Arc *lighter_c = hg.g.insert_arc(hg.hub, node_c, 0);
809 for (int i = 1; i < n; ++i)
810 {
811 Node *node_b = hg.g.insert_node(4);
812 a->get_info() = key - 3;
813 c->get_info() = key - 1;
814 lighter_c->get_info() = key - 4;
815 heap.put_arc(a, node_a);
816 heap.put_arc(hg.g.insert_arc(hg.hub, node_b, key - 2), node_b);
817 heap.put_arc(c, node_c);
818 (void) heap.get_min_arc(); // a
819 heap.put_arc(lighter_c, node_c);
820 (void) heap.get_min_arc(); // lighter_c
821 top = node_b;
822 key -= 2;
823 }
824 return top;
825 }
826
827 // The number of heap nodes from the handle of top down by child
828 size_t height_of_chain(HubGraph & hg, Node *top)
829 {
830 size_t height = 0;
831 for (auto p = hg.handle(top); p != nullptr; p = p->child)
832 ++height;
833 return height;
834 }
835}
836
837// ArcFibonacciHeap cleared the handles recursively, so a tree as high as the
838// heap is large overflowed the stack.
839TEST(ArcFibonacciHeapDepth, ClearNullsTheHandlesOfATreeAsHighAsTheHeap)
840{
841 constexpr int n = 50000;
842 HubGraph hg;
843 FibonacciHeapOfArcs heap(ArcWeightDist{}, VoidMapAccess{&hg.handles});
844 Node *top = build_chain(hg, heap, n);
845 ASSERT_EQ(height_of_chain(hg, top), size_t(n));
846
847 run_with_small_stack([&heap] { heap.clear(); });
848 EXPECT_TRUE(heap.is_empty());
849 EXPECT_TRUE(hg.all_null());
850}
851
852TEST(ArcFibonacciHeapDepth, DestroyingATreeAsHighAsTheHeapNullsTheHandles)
853{
854 constexpr int n = 50000;
855 HubGraph hg;
856 auto heap = std::make_unique<FibonacciHeapOfArcs>(ArcWeightDist{},
857 VoidMapAccess{&hg.handles});
858 Node *top = build_chain(hg, *heap, n);
859 ASSERT_EQ(height_of_chain(hg, top), size_t(n));
860
861 run_with_small_stack([&heap] { heap.reset(); });
862 EXPECT_TRUE(hg.all_null());
863}
864
865// The handles of trees of several children and levels are cleared too.
866TEST(ArcFibonacciHeapDepth, ClearNullsTheHandlesOfBushyTrees)
867{
868 HubGraph hg;
869 const std::vector<Node *> targets = make_nodes(hg.g, 300);
870 FibonacciHeapOfArcs heap(ArcWeightDist{}, VoidMapAccess{&hg.handles});
871 std::mt19937 gen(141);
872 auto put_arcs = [&](int count)
873 {
874 for (int i = 0; i < count; ++i)
875 {
876 Node *p = targets[gen() % targets.size()];
877 heap.put_arc(hg.g.insert_arc(hg.hub, p, int(gen() % 100000)), p);
878 }
879 };
880 put_arcs(1000);
881 for (int i = 0; i < 60; ++i) // links the roots in trees
882 (void) heap.get_min_arc();
883 put_arcs(1000); // lighter arcs cut heap nodes
884 for (int i = 0; i < 20; ++i)
885 (void) heap.get_min_arc();
886
887 size_t degree = 0, depth = 0;
888 for (Node *p : targets)
889 if (auto q = hg.handle(p); q != nullptr)
890 {
891 degree = std::max(degree, q->degree);
892 size_t d = 0;
893 for (; q->parent != nullptr; q = q->parent)
894 ++d;
895 depth = std::max(depth, d);
896 }
897 ASSERT_GE(degree, 3u);
898 ASSERT_GE(depth, 3u);
899
900 heap.clear();
901 EXPECT_TRUE(heap.is_empty());
902 EXPECT_TRUE(hg.all_null());
903}
Arc heap for graph algorithms.
TYPED_TEST_SUITE(ArcHeapLifecycle, ArcHeapKinds)
TYPED_TEST(ArcHeapLifecycle, ClearNullsTheHandles)
WeightedDigraph::Node Node
WeightedDigraph::Arc Arc
long double w
Definition btreepic.C:153
size_t size_t int32_t * out
Definition ca-c-api.h:120
virtual Node * insert_node(Node *node) noexcept
Insertion of a node already allocated.
Definition tpl_graph.H:535
Node Node
The graph type.
Definition tpl_graph.H:443
Arc Arc
The node class type.
Definition tpl_graph.H:444
Arc * insert_arc(Node *src_node, Node *tgt_node, void *a)
Definition tpl_graph.H:618
Minimal std::expected-style result type for C++20.
void put_arc(typename GT::Arc *arc, typename GT::Node *tgt)
Insert or update an arc associated with a target node, keeping the smallest-distance arc per node in ...
Definition archeap.H:131
GT::Arc * get_min_arc()
Extract the arc with minimum distance from the heap and clear its node-to-heap mapping.
Definition archeap.H:171
ArcInfo & get_info() noexcept
Return a modifiable reference to the arc data.
Definition graph-dry.H:854
#define TEST(name)
static mt19937 rng
__gmp_expr< typename __gmp_resolve_expr< T, V >::value_type, __gmp_binary_expr< __gmp_expr< T, U >, __gmp_expr< V, W >, __gmp_min_function > > min(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4189
DynArray< Graph::Node * > nodes
Definition graphpic.C:406
DynArray< Graph::Arc * > arcs
Definition graphpic.C:408
Main namespace for Aleph-w library functions.
and
Check uniqueness with explicit hash + equality functors.
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
Definition ahAlgo.H:127
bool run_with_small_stack(F &&f, size_t kb=256)
Runs f in a thread whose stack has kb KiB, and returns false if the thread could not run; without POS...
Node heap without virtual destructor.
Arc of graph implemented with double-linked adjacency lists.
Definition tpl_graph.H:231
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
bool check(GT &g)
Node * access(Node *list, size_t n)
Definition test-splice.C:59
static int * k
Generic graph and digraph implementations.