Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
bounded_cycle_index_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
39# include <gtest/gtest.h>
40
41# include <algorithm>
42# include <cmath>
43# include <cstdint>
44# include <functional>
45# include <limits>
46# include <map>
47# include <random>
48# include <set>
49# include <stdexcept>
50# include <type_traits>
51# include <utility>
52# include <vector>
53
54# include <gmpxx.h>
55
56# include <Bounded_Cycle_Index.H>
57# include <tpl_agraph.H>
58# include <tpl_const_graph_view.H>
59# include <tpl_graph.H>
60# include <tpl_sgraph.H>
61
62using namespace Aleph;
63
64namespace
65{
69
70 using Ends = std::vector<std::pair<size_t, size_t>>;
71 using Cycle = std::vector<size_t>;
72
73 const double Infinity = std::numeric_limits<double>::infinity();
74
75 // A digraph of n nodes with an arc for each pair of ends, whose
76 // information is its place in `ends`; the arcs are inserted in that
77 // order or in the reverse one
78 template <class GT>
79 struct Built
80 {
81 GT g;
82 std::vector<typename GT::Node *> nodes;
83 std::vector<typename GT::Arc *> arcs; // by its place in `ends`
84
85 Built(const size_t n, const Ends & ends, const bool reversed = false)
86 : arcs(ends.size())
87 {
88 for (size_t i = 0; i < n; ++i)
89 nodes.push_back(g.insert_node(int(i)));
90 for (size_t i = 0; i < ends.size(); ++i)
91 {
92 const size_t id = reversed ? ends.size() - 1 - i : i;
93 arcs[id] = g.insert_arc(nodes[ends[id].first], nodes[ends[id].second], int(id));
94 }
95 }
96 };
97
98 // The order of the information of the arcs
99 struct By_Info
100 {
101 template <class Arc>
102 bool operator () (const Arc *a, const Arc *b) const
103 {
104 return a->get_info() < b->get_info();
105 }
106 };
107
108 // The catalog of a digraph, found apart from the index: the arcs are
109 // numbered with a stable sort, and the cycles come from walking the
110 // simple paths from each node, each one rotated to its least arc
111 template <class GT>
112 struct Oracle
113 {
114 using Arc = typename GT::Arc;
115
116 std::vector<Arc *> arcs; // by number
117 std::map<const void *, size_t> number; // of each arc
118 std::vector<Cycle> cycles; // by length, then lexicographically
119 std::vector<std::vector<size_t>> of_arc; // by arc, the positions of its cycles
120
121 template <class Less>
122 Oracle(const GT & g, const std::set<size_t> & lengths, Less less)
123 {
124 for (typename GT::Arc_Iterator it(g); it.has_curr(); it.next_ne())
125 arcs.push_back(it.get_curr_ne());
126 std::stable_sort(arcs.begin(), arcs.end(), less);
127 std::vector<const void *> source(arcs.size()), target(arcs.size());
128 std::map<const void *, std::vector<size_t>> out;
129 for (size_t a = 0; a < arcs.size(); ++a)
130 {
131 number[arcs[a]] = a;
132 source[a] = g.get_src_node(arcs[a]);
133 target[a] = g.get_tgt_node(arcs[a]);
134 out[source[a]].push_back(a);
135 }
136
137 const size_t longest = lengths.empty() ? 0 : *lengths.rbegin();
138 std::set<Cycle> found;
139 for (typename GT::Node_Iterator it(g); it.has_curr(); it.next_ne())
140 {
141 const void *start = it.get_curr_ne();
142 Cycle path;
143 std::set<const void *> on_path = {start};
144 const std::function<void(const void *)> walk = [&] (const void *node)
145 {
146 for (const size_t a : out[node])
147 if (target[a] == start)
148 {
149 if (lengths.count(path.size() + 1) == 0)
150 continue;
151 Cycle cycle = path;
152 cycle.push_back(a);
153 std::rotate(cycle.begin(), std::min_element(cycle.begin(), cycle.end()),
154 cycle.end());
155 found.insert(cycle);
156 }
157 else if (path.size() + 2 <= longest and on_path.count(target[a]) == 0)
158 {
159 path.push_back(a);
160 on_path.insert(target[a]);
161 walk(target[a]);
162 on_path.erase(target[a]);
163 path.pop_back();
164 }
165 };
166 walk(start);
167 }
168 cycles.assign(found.begin(), found.end());
169 std::sort(cycles.begin(), cycles.end(), [] (const Cycle & a, const Cycle & b)
170 {
171 return a.size() != b.size() ? a.size() < b.size() : a < b;
172 });
173 of_arc.resize(arcs.size());
174 for (size_t position = 0; position < cycles.size(); ++position)
175 for (const size_t a : cycles[position])
176 of_arc[a].push_back(position);
177 }
178 };
179
180 template <class Span>
181 std::vector<size_t> as_vector(const Span & items)
182 {
183 return std::vector<size_t>(items.begin(), items.end());
184 }
185
186 // The index has the numbers, the cycles and the cycles of each arc of
187 // the oracle
188 template <class GT>
189 void expect_the_catalog(const Bounded_Cycle_Index<GT> & index, const Oracle<GT> & oracle)
190 {
191 ASSERT_EQ(index.num_arcs(), oracle.arcs.size());
192 for (size_t a = 0; a < oracle.arcs.size(); ++a)
193 {
194 ASSERT_EQ(index.arc(a), oracle.arcs[a]) << "arc " << a;
195 ASSERT_EQ(index.arc_number(oracle.arcs[a]), a);
196 }
197 ASSERT_EQ(index.num_cycles(), oracle.cycles.size());
198 size_t by_length[Bounded_Cycle_Index<GT>::Max_Length + 2] = {};
199 for (size_t position = 0; position < oracle.cycles.size(); ++position)
200 {
201 ASSERT_EQ(as_vector(index.cycle_arcs(position)), oracle.cycles[position])
202 << "position " << position;
203 ASSERT_EQ(index.length(position), oracle.cycles[position].size());
204 ++by_length[oracle.cycles[position].size()];
205 }
206 size_t up_to = 0;
207 for (size_t k = 1; k <= Bounded_Cycle_Index<GT>::Max_Length; ++k)
208 {
209 EXPECT_EQ(index.num_cycles(k), by_length[k]) << "length " << k;
210 up_to += by_length[k];
211 EXPECT_EQ(index.num_cycles_up_to(k), up_to) << "length " << k;
212 }
213 for (size_t a = 0; a < oracle.arcs.size(); ++a)
214 ASSERT_EQ(as_vector(index.cycles_of(a)), oracle.of_arc[a]) << "arc " << a;
215 }
216
217 // What a query hands: the positions with their sums, in the order of
218 // the calls
219 using Handed = std::vector<std::pair<size_t, double>>;
220
221 // The cycles of an arc whose length is at most max_length and whose
222 // sum is below the bound, from the catalog and weight_sum()
223 template <class GT>
224 Handed below_of(const Bounded_Cycle_Index<GT> & index, const size_t arc,
225 const double bound, const size_t max_length)
226 {
227 Handed ret;
228 for (const size_t position : index.cycles_of(arc))
229 if (index.length(position) <= max_length and index.weight_sum(position) < bound)
230 ret.emplace_back(position, index.weight_sum(position));
231 return ret;
232 }
233
234 // Random ends of m arcs among n nodes: loops and parallel arcs come out
235 Ends random_ends(std::mt19937 & rng, const size_t n, const size_t m)
236 {
237 std::uniform_int_distribution<size_t> node(0, n - 1);
238 Ends ends;
239 for (size_t i = 0; i < m; ++i)
240 {
241 const size_t source = node(rng); // the order of the two draws is fixed
242 ends.emplace_back(source, node(rng));
243 }
244 return ends;
245 }
246
247 // The complete digraph of n nodes
248 // All that an index answers, to compare two of them: its arcs with
249 // their weights, their stamps and their cycles, its cycles with their
250 // sums, its counts and its clock, and what a query of all its arcs hands
251 template <class GT>
252 struct Answers
253 {
254 std::vector<const void *> arcs;
255 std::vector<double> weights;
256 std::vector<uint64_t> stamps;
257 std::vector<std::vector<size_t>> of_arc;
258 std::vector<Cycle> cycles;
259 std::vector<double> sums;
260 std::vector<uint64_t> counts;
261 Handed handed;
262 size_t seen = 0;
263
264 explicit Answers(Bounded_Cycle_Index<GT> & index)
265 {
267 for (size_t a = 0; a < index.num_arcs(); ++a)
268 {
269 arcs.push_back(index.arc(a));
270 weights.push_back(index.weight(a));
271 stamps.push_back(index.stamp(a));
272 of_arc.push_back(as_vector(index.cycles_of(a)));
273 all.append(a);
274 }
275 for (size_t position = 0; position < index.num_cycles(); ++position)
276 {
277 cycles.push_back(as_vector(index.cycle_arcs(position)));
278 sums.push_back(index.weight_sum(position));
279 }
280 for (size_t k = 0; k <= Bounded_Cycle_Index<GT>::Max_Length + 1; ++k)
281 {
282 counts.push_back(index.num_cycles(k));
283 counts.push_back(index.num_cycles_up_to(k));
284 counts.push_back(index.has_length(k));
285 }
286 counts.push_back(index.longest_length());
287 counts.push_back(index.clock());
289 [this] (size_t p, double s) { handed.emplace_back(p, s); });
290 }
291
292 bool operator == (const Answers &) const = default;
293 };
294
295 // The index has no arcs and no cycles, and answers so to every query
296 template <class GT>
297 void expect_no_arcs_and_no_cycles(Bounded_Cycle_Index<GT> & index,
298 const typename GT::Arc *arc)
299 {
300 EXPECT_EQ(index.num_arcs(), 0u);
301 EXPECT_EQ(index.num_cycles(), 0u);
302 for (size_t k = 0; k <= Bounded_Cycle_Index<GT>::Max_Length + 1; ++k)
303 {
304 EXPECT_EQ(index.num_cycles(k), 0u) << "length " << k;
305 EXPECT_EQ(index.num_cycles_up_to(k), 0u) << "length " << k;
306 EXPECT_FALSE(index.has_length(k)) << "length " << k;
307 }
308 EXPECT_EQ(index.longest_length(), 0u);
309 EXPECT_EQ(index.clock(), 0u);
310 EXPECT_THROW((void) index.arc_number(arc), std::domain_error);
311 EXPECT_THROW((void) index.arc(0), std::out_of_range);
312 EXPECT_THROW((void) index.weight(0), std::out_of_range);
313 EXPECT_THROW((void) index.stamp(0), std::out_of_range);
314 EXPECT_THROW((void) index.cycles_of(0), std::out_of_range);
315 EXPECT_THROW((void) index.cycle_arcs(0), std::out_of_range);
316 EXPECT_THROW((void) index.weight_sum(0), std::out_of_range);
317 EXPECT_THROW((void) index.length(0), std::out_of_range);
318 EXPECT_THROW((void) index.is_stale(0, 0), std::out_of_range);
319 EXPECT_THROW(index.set_weight(0, 1), std::out_of_range);
320 EXPECT_THROW(index.touch(0), std::out_of_range);
321 size_t handed = 0;
322 const auto count = [&handed] (size_t, double) { ++handed; };
323 EXPECT_THROW(index.update(0, 1, Infinity, 8, count), std::out_of_range);
324 EXPECT_THROW(index.for_each_cycle_below({0}, Infinity, 8, count), std::out_of_range);
325 EXPECT_EQ(index.for_each_cycle_below(Array<size_t>(), Infinity, 8, count), 0u);
326 EXPECT_EQ(index.for_each_cycle_below(Infinity, 8, count), 0u);
327 EXPECT_EQ(handed, 0u);
328 }
329
330 Ends complete_ends(const size_t n)
331 {
332 Ends ends;
333 for (size_t i = 0; i < n; ++i)
334 for (size_t j = 0; j < n; ++j)
335 if (i != j)
336 ends.emplace_back(i, j);
337 return ends;
338 }
339
340 size_t falling(const size_t n, const size_t k) // n (n - 1) ... (n - k + 1)
341 {
342 size_t ret = 1;
343 for (size_t i = 0; i < k; ++i)
344 ret *= n - i;
345 return ret;
346 }
347
348 template <class GT>
349 class BoundedCycleIndexOn : public ::testing::Test {};
350
351 using Digraph_Types = ::testing::Types<List_Type, Sparse_Type, Array_Type>;
352 TYPED_TEST_SUITE(BoundedCycleIndexOn, Digraph_Types);
353}
354
355// The catalog of random multigraphs, with loops and parallel arcs, is that
356// of a search made apart, for several sets of lengths and orders of the
357// arcs, on each type of digraph and through a view
358TYPED_TEST(BoundedCycleIndexOn, HasTheCatalogOfASearchMadeApart)
359{
360 using GT = TypeParam;
361 using View = Const_Graph_View<GT>;
362 const std::vector<std::set<size_t>> sets =
363 {{3}, {1, 2, 3}, {2, 3, 4}, {3, 4, 5, 6}, {2, 4}, {1, 2, 3, 4, 5, 6, 7, 8}, {8}, {1}};
364 std::mt19937 rng(20261113);
365 size_t compared = 0, with_loops = 0, with_parallel = 0;
366 for (size_t round = 0; round < 600; ++round)
367 {
368 const size_t n = 1 + rng() % 7;
369 const Ends ends = random_ends(rng, n, rng() % 26);
370 const Built<GT> built(n, ends, round % 2 == 1);
371 const auto & lengths = sets[round % sets.size()];
372 const Array<size_t> array_of_lengths(lengths.begin(), lengths.end());
373 const auto by_info_down = [] (const typename GT::Arc *a, const typename GT::Arc *b)
374 {
375 return a->get_info() > b->get_info();
376 };
377 const auto by_parity = [] (const typename GT::Arc *a, const typename GT::Arc *b)
378 {
379 return a->get_info() % 2 < b->get_info() % 2; // many arcs are not told apart
380 };
381
382 const Bounded_Cycle_Index<GT> in_list_order(built.g, array_of_lengths);
383 expect_the_catalog(in_list_order, Oracle<GT>(built.g, lengths, Arc_List_Order()));
384 const Bounded_Cycle_Index<GT> by_info(built.g, array_of_lengths, By_Info());
385 expect_the_catalog(by_info, Oracle<GT>(built.g, lengths, By_Info()));
386 const Bounded_Cycle_Index<GT> down(built.g, array_of_lengths, by_info_down);
387 expect_the_catalog(down, Oracle<GT>(built.g, lengths, by_info_down));
388 const Bounded_Cycle_Index<GT> parity(built.g, array_of_lengths, by_parity);
389 expect_the_catalog(parity, Oracle<GT>(built.g, lengths, by_parity));
390
391 const View view(built.g);
392 const Bounded_Cycle_Index<View> through_view(view, array_of_lengths, By_Info());
393 expect_the_catalog(through_view, Oracle<View>(view, lengths, By_Info()));
394 ASSERT_EQ(through_view.num_cycles(), by_info.num_cycles());
395 for (size_t position = 0; position < by_info.num_cycles(); ++position)
396 ASSERT_EQ(as_vector(through_view.cycle_arcs(position)),
397 as_vector(by_info.cycle_arcs(position)));
398
399 compared += by_info.num_cycles();
400 std::set<std::pair<size_t, size_t>> seen;
401 bool loop = false, parallel = false;
402 for (const auto & e : ends)
403 {
404 loop = loop or e.first == e.second;
405 parallel = parallel or not seen.insert(e).second;
406 }
407 with_loops += loop;
408 with_parallel += parallel;
409 if (::testing::Test::HasFatalFailure())
410 return;
411 }
412 EXPECT_GT(compared, 3000u); // the rounds do have cycles, loops and parallel arcs
413 EXPECT_GT(with_loops, 300u);
414 EXPECT_GT(with_parallel, 300u);
415}
416
417// With an order of the arcs that tells them all apart, the catalog does
418// not depend on the order in which the arcs were inserted
419TYPED_TEST(BoundedCycleIndexOn, DoesNotDependOnTheOrderOfInsertion)
420{
421 using GT = TypeParam;
422 std::mt19937 rng(7);
423 for (size_t round = 0; round < 40; ++round)
424 {
425 const size_t n = 2 + rng() % 5;
426 const Ends ends = random_ends(rng, n, 4 + rng() % 12);
427 const Built<GT> forward(n, ends), backward(n, ends, true);
428 const Bounded_Cycle_Index<GT> a(forward.g, {1, 2, 3, 4, 5}, By_Info());
429 const Bounded_Cycle_Index<GT> b(backward.g, {1, 2, 3, 4, 5}, By_Info());
430 ASSERT_EQ(a.num_cycles(), b.num_cycles());
431 for (size_t arc = 0; arc < a.num_arcs(); ++arc)
432 ASSERT_EQ(a.arc(arc)->get_info(), b.arc(arc)->get_info());
433 for (size_t position = 0; position < a.num_cycles(); ++position)
434 ASSERT_EQ(as_vector(a.cycle_arcs(position)), as_vector(b.cycle_arcs(position)));
435 }
436}
437
438// The complete digraph of n nodes has C(n, k) (k - 1)! cycles of length
439// k: n (n - 1) ... (n - k + 1) / k
440TEST(BoundedCycleIndex, CountsTheCyclesOfACompleteDigraph)
441{
442 for (size_t n = 1; n <= 8; ++n)
443 {
444 const Built<List_Type> built(n, complete_ends(n));
445 const Bounded_Cycle_Index index(built.g, {1, 2, 3, 4, 5, 6, 7, 8});
446 EXPECT_EQ(index.num_cycles(1), 0u);
447 size_t total = 0;
448 for (size_t k = 2; k <= 8; ++k)
449 {
450 const size_t expected = k > n ? 0 : falling(n, k) / k;
451 EXPECT_EQ(index.num_cycles(k), expected) << n << " nodes, length " << k;
452 total += expected;
453 }
454 EXPECT_EQ(index.num_cycles(), total);
455 EXPECT_EQ(index.num_cycles(0), 0u);
456 EXPECT_EQ(index.num_cycles(9), 0u);
457 EXPECT_EQ(index.num_cycles_up_to(100), total);
458 EXPECT_EQ(index.num_cycles_up_to(0), 0u);
459 }
460}
461
462// Each cycle starts with its least arc, the cycles go by length and then
463// lexicographically, and those up to a length are the catalog of the
464// smaller set, position by position
465TEST(BoundedCycleIndex, OrdersTheCatalogAndKeepsThePrefixes)
466{
467 std::mt19937 rng(11);
468 for (size_t round = 0; round < 30; ++round)
469 {
470 const size_t n = 3 + rng() % 4;
471 const Built<List_Type> built(n, random_ends(rng, n, 8 + rng() % 12));
472 const Bounded_Cycle_Index whole(built.g, {1, 2, 3, 4, 5, 6});
473 for (size_t position = 0; position < whole.num_cycles(); ++position)
474 {
475 const auto arcs = as_vector(whole.cycle_arcs(position));
476 EXPECT_EQ(*std::min_element(arcs.begin(), arcs.end()), arcs.front());
477 EXPECT_EQ(std::set<size_t>(arcs.begin(), arcs.end()).size(), arcs.size());
478 if (position == 0)
479 continue;
480 const auto before = as_vector(whole.cycle_arcs(position - 1));
481 EXPECT_TRUE(before.size() < arcs.size() or
482 (before.size() == arcs.size() and before < arcs));
483 }
484 for (size_t m = 1; m <= 6; ++m)
485 {
486 Array<size_t> lengths;
487 for (size_t k = 1; k <= m; ++k)
488 lengths.append(k);
489 const Bounded_Cycle_Index<List_Type> prefix(built.g, lengths);
490 ASSERT_EQ(prefix.num_cycles(), whole.num_cycles_up_to(m));
491 EXPECT_EQ(prefix.longest_length(), m);
492 for (size_t position = 0; position < prefix.num_cycles(); ++position)
493 ASSERT_EQ(as_vector(prefix.cycle_arcs(position)),
494 as_vector(whole.cycle_arcs(position)));
495 }
496 const Bounded_Cycle_Index some(built.g, {2, 5});
497 EXPECT_EQ(some.num_cycles(), whole.num_cycles(2) + whole.num_cycles(5));
498 EXPECT_TRUE(some.has_length(2) and some.has_length(5));
499 EXPECT_FALSE(some.has_length(3) or some.has_length(0) or some.has_length(9));
500 }
501}
502
503// Parallel arcs give different cycles, a loop is a cycle of one arc and
504// is in no longer cycle, and the two senses of a cycle are two cycles
505TEST(BoundedCycleIndex, TellsParallelArcsLoopsAndSensesApart)
506{
507 // 0 -> 1 twice, 1 -> 0, a loop at 1, and the triangle 0 1 2 both ways
508 const Built<List_Type> built(3, {{0, 1}, {0, 1}, {1, 0}, {1, 1}, {1, 2}, {2, 0}, {2, 1}, {0, 2}});
509 const Bounded_Cycle_Index index(built.g, {1, 2, 3});
510 EXPECT_EQ(index.num_cycles(1), 1u);
511 EXPECT_EQ(as_vector(index.cycle_arcs(0)), Cycle({3}));
512 // of two arcs: 0 2, 1 2, 4 6 (1 -> 2 -> 1) and 5 7 (2 -> 0 -> 2)
513 EXPECT_EQ(index.num_cycles(2), 4u);
514 EXPECT_EQ(as_vector(index.cycle_arcs(1)), Cycle({0, 2}));
515 EXPECT_EQ(as_vector(index.cycle_arcs(2)), Cycle({1, 2}));
516 // of three: 0 -> 1 -> 2 -> 0 with each parallel arc, and 0 -> 2 -> 1 -> 0
517 EXPECT_EQ(index.num_cycles(3), 3u);
518 EXPECT_EQ(as_vector(index.cycle_arcs(5)), Cycle({0, 4, 5}));
519 EXPECT_EQ(as_vector(index.cycle_arcs(6)), Cycle({1, 4, 5}));
520 EXPECT_EQ(as_vector(index.cycle_arcs(7)), Cycle({2, 7, 6}));
521 EXPECT_EQ(as_vector(index.cycles_of(3)), std::vector<size_t>({0})); // the loop
522}
523
524// The arcs take their numbers in the order given and, where it does not
525// tell them apart, in that of the iterator; an arc of another graph has
526// no number
527TEST(BoundedCycleIndex, NumbersTheArcsInTheOrderGiven)
528{
529 const Built<List_Type> built(3, {{0, 1}, {1, 2}, {2, 0}, {0, 2}});
530 const Built<List_Type> other(2, {{0, 1}});
531 const auto down = [] (const List_Type::Arc *a, const List_Type::Arc *b)
532 {
533 return a->get_info() > b->get_info();
534 };
535 const Bounded_Cycle_Index index(built.g, {3}, down);
536 ASSERT_EQ(index.num_arcs(), 4u);
537 for (size_t number = 0; number < 4; ++number)
538 {
539 EXPECT_EQ(index.arc(number)->get_info(), int(3 - number));
540 EXPECT_EQ(index.arc_number(index.arc(number)), number);
541 }
542 EXPECT_THROW((void) index.arc(4), std::out_of_range);
543 EXPECT_THROW((void) index.arc_number(other.arcs[0]), std::domain_error);
544 EXPECT_THROW((void) index.arc_number(nullptr), std::domain_error);
545
546 const Bounded_Cycle_Index in_list_order(built.g, {3});
547 size_t number = 0;
548 for (List_Type::Arc_Iterator it(built.g); it.has_curr(); it.next_ne(), ++number)
549 EXPECT_EQ(in_list_order.arc(number), it.get_curr_ne());
550}
551
552// Until an arc is given a weight it cannot be used: no cycle through it
553// is below a bound, not even an infinite one
554TEST(BoundedCycleIndex, StartsWithArcsThatCannotBeUsed)
555{
556 const Built<List_Type> built(4, complete_ends(4));
557 Bounded_Cycle_Index index(built.g, {2, 3, 4});
558 size_t handed = 0;
559 const auto count = [&handed] (size_t, double) { ++handed; };
560 for (size_t a = 0; a < index.num_arcs(); ++a)
561 EXPECT_EQ(index.weight(a), Infinity);
562 EXPECT_EQ(index.for_each_cycle_below(Infinity, 8, count), index.num_cycles());
563 EXPECT_EQ(handed, 0u);
564 for (size_t position = 0; position < index.num_cycles(); ++position)
565 EXPECT_EQ(index.weight_sum(position), Infinity);
566
567 // all but one arc: only the cycles without it are below
568 for (size_t a = 1; a < index.num_arcs(); ++a)
569 index.set_weight(a, 1);
570 index.for_each_cycle_below(Infinity, 8, count);
571 EXPECT_EQ(handed, index.num_cycles() - index.cycles_of(0).size());
572 handed = 0;
573 EXPECT_EQ(index.update(0, 1, Infinity, 8, count), index.cycles_of(0).size());
574 EXPECT_EQ(handed, index.cycles_of(0).size());
575 handed = 0;
576 index.update(0, Infinity, Infinity, 8, count); // and it can be taken out again
577 EXPECT_EQ(handed, 0u);
578}
579
580// update() hands the cycles of its arc below the bound and up to the
581// length, by ascending position, each with the sum of weight_sum(), which
582// is that of the weights added in the order of the cycle
583TYPED_TEST(BoundedCycleIndexOn, UpdateHandsTheCyclesBelowTheBound)
584{
585 using GT = TypeParam;
586 std::mt19937 rng(20261114);
587 std::uniform_real_distribution<double> weight(-3, 3);
588 size_t handed_in_all = 0, looked_at = 0;
589 for (size_t round = 0; round < 60; ++round)
590 {
591 const size_t n = 2 + rng() % 5;
592 const Built<GT> built(n, random_ends(rng, n, 6 + rng() % 14));
593 Bounded_Cycle_Index<GT> index(built.g, {1, 2, 3, 4, 5, 6});
594 std::vector<double> weights(index.num_arcs());
595 for (size_t a = 0; a < index.num_arcs(); ++a)
596 index.set_weight(a, weights[a] = rng() % 9 == 0 ? Infinity : weight(rng));
597 for (size_t step = 0; step < 40; ++step)
598 {
599 const size_t arc = rng() % index.num_arcs();
600 const double w = rng() % 11 == 0 ? Infinity : weight(rng);
601 const double bound = weight(rng);
602 const size_t max_length = rng() % 10;
603 weights[arc] = w;
604 Handed handed;
605 const size_t seen = index.update(arc, w, bound, max_length, [&] (size_t p, double s)
606 {
607 handed.emplace_back(p, s);
608 });
609 ASSERT_EQ(index.weight(arc), w);
610 ASSERT_EQ(handed, below_of(index, arc, bound, max_length));
611 size_t expected_seen = 0;
612 for (const size_t position : index.cycles_of(arc))
613 expected_seen += index.length(position) <= max_length;
614 ASSERT_EQ(seen, expected_seen);
615 for (const auto & [position, sum] : handed)
616 {
617 const auto arcs = index.cycle_arcs(position);
618 double expected = weights[arcs[0]];
619 for (size_t j = 1; j < arcs.size(); ++j)
620 expected += weights[arcs[j]];
621 ASSERT_EQ(sum, expected); // the same number: the weights in the order of the cycle
622 }
623 handed_in_all += handed.size();
624 looked_at += seen;
625 }
626 }
627 EXPECT_GT(handed_in_all, 500u);
628 EXPECT_GT(looked_at, handed_in_all);
629}
630
631// The sum of a cycle is the same number whichever of its arcs changed
632TEST(BoundedCycleIndex, HandsTheSameSumWhicheverArcChanged)
633{
634 const Built<List_Type> built(4, {{0, 1}, {1, 2}, {2, 3}, {3, 0}});
635 Bounded_Cycle_Index index(built.g, {4});
636 const double weights[] = {0.1, 1e16, -1e16, 0.3}; // the order of the sum matters
637 for (size_t a = 0; a < 4; ++a)
638 index.set_weight(a, weights[a]);
639 const double sum = ((0.1 + 1e16) - 1e16) + 0.3;
640 EXPECT_EQ(index.weight_sum(0), sum);
641 for (size_t a = 0; a < 4; ++a)
642 {
643 Handed handed;
644 index.update(a, weights[a], Infinity, 4, [&] (size_t p, double s)
645 {
646 handed.emplace_back(p, s);
647 });
648 ASSERT_EQ(handed, Handed({{0, sum}})) << "arc " << a;
649 }
650}
651
652// A change of several arcs is seen whole, and each cycle once: also the
653// cycle of two arcs that has both, and with an arc given twice
654TYPED_TEST(BoundedCycleIndexOn, HandsOnceEachCycleOfSeveralArcs)
655{
656 using GT = TypeParam;
657 std::mt19937 rng(42);
658 std::uniform_real_distribution<double> weight(-2, 2);
659 size_t shared = 0;
660 for (size_t round = 0; round < 80; ++round)
661 {
662 const size_t n = 2 + rng() % 4;
663 const Built<GT> built(n, random_ends(rng, n, 5 + rng() % 12));
664 Bounded_Cycle_Index<GT> index(built.g, {1, 2, 3, 4, 5});
665 for (size_t a = 0; a < index.num_arcs(); ++a)
666 index.set_weight(a, weight(rng));
667 for (size_t step = 0; step < 12; ++step)
668 {
670 for (size_t i = 0, m = rng() % 5; i < m; ++i)
671 arcs.append(rng() % index.num_arcs()); // some come twice
672 for (size_t i = 0; i < arcs.size(); ++i)
673 index.set_weight(arcs(i), weight(rng));
674 const double bound = weight(rng);
675 const size_t max_length = 1 + rng() % 6;
676
677 std::set<size_t> expected;
678 size_t expected_seen = 0, memberships = 0;
679 std::set<size_t> of_any;
680 for (size_t i = 0; i < arcs.size(); ++i)
681 for (const size_t position : index.cycles_of(arcs(i)))
682 if (index.length(position) <= max_length)
683 {
684 ++memberships;
685 if (not of_any.insert(position).second)
686 continue;
687 ++expected_seen;
688 if (index.weight_sum(position) < bound)
689 expected.insert(position);
690 }
691 shared += memberships - expected_seen;
692
693 Handed handed;
694 const size_t seen =
695 index.for_each_cycle_below(arcs, bound, max_length, [&] (size_t p, double s)
696 {
697 handed.emplace_back(p, s);
698 });
699 ASSERT_EQ(seen, expected_seen);
700 std::set<size_t> positions;
701 for (const auto & [position, sum] : handed)
702 {
703 ASSERT_TRUE(positions.insert(position).second) << "handed twice";
704 ASSERT_EQ(sum, index.weight_sum(position));
705 }
706 ASSERT_EQ(positions, expected);
707
708 // and nothing is left marked: the same call gives the same
709 size_t again = 0;
710 index.for_each_cycle_below(arcs, bound, max_length,
711 [&again] (size_t, double) { ++again; });
712 ASSERT_EQ(again, handed.size());
713 }
714 }
715 EXPECT_GT(shared, 200u); // the cycles with several of the arcs did come out
716
717 // the two arcs of a cycle of length 2, as the two arcs of a market
718 const Built<GT> pair(2, {{0, 1}, {1, 0}});
719 Bounded_Cycle_Index<GT> index(pair.g, {2});
720 index.set_weight(0, -1);
721 index.set_weight(1, -1);
722 Handed handed;
723 EXPECT_EQ(index.for_each_cycle_below({0, 1, 0}, 0, 2, [&] (size_t p, double s)
724 {
725 handed.emplace_back(p, s);
726 }), 1u);
727 EXPECT_EQ(handed, Handed({{0, -2.0}}));
728}
729
730// for_each_cycle_below() on the whole catalog hands what weight_sum() says
731TEST(BoundedCycleIndex, WalksTheWholeCatalog)
732{
733 std::mt19937 rng(3);
734 std::uniform_real_distribution<double> weight(-1, 1);
735 const Built<List_Type> built(6, complete_ends(6));
736 Bounded_Cycle_Index index(built.g, {2, 3, 4, 5});
737 for (size_t a = 0; a < index.num_arcs(); ++a)
738 index.set_weight(a, weight(rng));
739 const auto & constant = index;
740 for (size_t max_length = 0; max_length <= 9; ++max_length)
741 {
742 Handed handed, expected;
743 const size_t seen = constant.for_each_cycle_below(-0.5, max_length, [&] (size_t p, double s)
744 {
745 handed.emplace_back(p, s);
746 });
747 EXPECT_EQ(seen, index.num_cycles_up_to(max_length));
748 for (size_t position = 0; position < index.num_cycles_up_to(max_length); ++position)
749 if (index.weight_sum(position) < -0.5)
750 expected.emplace_back(position, index.weight_sum(position));
751 EXPECT_EQ(handed, expected);
752 EXPECT_FALSE(max_length >= 2 and handed.empty());
753 }
754}
755
756// An arc that is in no cycle, a digraph of one arc, a digraph without
757// cycles and a digraph without arcs give empty ranges, and their arcs can
758// be changed
759TEST(BoundedCycleIndex, GivesEmptyRanges)
760{
761 size_t handed = 0;
762 const auto count = [&handed] (size_t, double) { ++handed; };
763 {
764 const Built<List_Type> one_arc(2, {{0, 1}});
765 Bounded_Cycle_Index index(one_arc.g, {3});
766 EXPECT_EQ(index.num_cycles(), 0u);
767 EXPECT_TRUE(index.cycles_of(0).empty());
768 EXPECT_EQ(index.update(0, -1, Infinity, 8, count), 0u);
769 EXPECT_EQ(index.for_each_cycle_below({0}, Infinity, 8, count), 0u);
770 EXPECT_EQ(index.for_each_cycle_below(Infinity, 8, count), 0u);
771 EXPECT_EQ(index.weight(0), -1);
772 EXPECT_THROW((void) index.length(0), std::out_of_range);
773 EXPECT_THROW((void) index.cycle_arcs(0), std::out_of_range);
774 EXPECT_THROW((void) index.weight_sum(0), std::out_of_range);
775 EXPECT_THROW((void) index.is_stale(0, 0), std::out_of_range);
776 }
777 {
778 // a triangle, and an arc that leaves it: in no cycle
779 const Built<List_Type> with_tail(4, {{0, 1}, {1, 2}, {2, 0}, {2, 3}});
780 Bounded_Cycle_Index index(with_tail.g, {2, 3, 4});
781 EXPECT_EQ(index.num_cycles(), 1u);
782 EXPECT_TRUE(index.cycles_of(3).empty());
783 EXPECT_EQ(index.update(3, -1, Infinity, 8, count), 0u);
784 // the triangle is of length 3: none of its arcs has cycles of 2 or 4
785 for (size_t a = 0; a < 3; ++a)
786 EXPECT_EQ(index.update(a, -1, Infinity, 2, count), 0u);
787 EXPECT_EQ(handed, 0u);
788 EXPECT_EQ(index.update(0, -1, Infinity, 3, count), 1u);
789 EXPECT_EQ(handed, 1u);
790 }
791 {
792 const Built<List_Type> acyclic(5, {{0, 1}, {1, 2}, {0, 2}, {2, 3}, {3, 4}, {0, 4}});
793 Bounded_Cycle_Index index(acyclic.g, {1, 2, 3, 4, 5, 6, 7, 8});
794 EXPECT_EQ(index.num_cycles(), 0u);
795 for (size_t a = 0; a < index.num_arcs(); ++a)
796 {
797 EXPECT_TRUE(index.cycles_of(a).empty());
798 EXPECT_EQ(index.update(a, -1, Infinity, 8, count), 0u);
799 }
800 }
801 {
802 const Built<List_Type> no_arcs(3, {});
803 Bounded_Cycle_Index index(no_arcs.g, {1, 2, 3});
804 EXPECT_EQ(index.num_arcs(), 0u);
805 EXPECT_EQ(index.num_cycles(), 0u);
806 EXPECT_THROW((void) index.cycles_of(0), std::out_of_range);
807 EXPECT_THROW(index.update(0, 1, 0, 3, count), std::out_of_range);
808 EXPECT_EQ(index.for_each_cycle_below(Array<size_t>(), 0, 3, count), 0u);
809 EXPECT_EQ(index.for_each_cycle_below(0, 3, count), 0u);
810 List_Type empty;
811 Bounded_Cycle_Index of_empty(empty, {1});
812 EXPECT_EQ(of_empty.num_arcs(), 0u);
813 }
814 EXPECT_EQ(handed, 1u);
815}
816
817// What is not a weight, a bound, an arc or a position is rejected, and
818// the index keeps what it had
819TEST(BoundedCycleIndex, RejectsWhatIsNotValid)
820{
821 const double nan = std::numeric_limits<double>::quiet_NaN();
822 const Built<List_Type> built(3, {{0, 1}, {1, 2}, {2, 0}});
823 Bounded_Cycle_Index index(built.g, {3});
824 for (size_t a = 0; a < 3; ++a)
825 index.set_weight(a, 1);
826 size_t handed = 0;
827 const auto count = [&handed] (size_t, double) { ++handed; };
828 const uint64_t clock = index.clock();
829
830 EXPECT_THROW(index.set_weight(0, nan), std::domain_error);
831 EXPECT_THROW(index.set_weight(0, -Infinity), std::domain_error);
832 EXPECT_THROW(index.set_weight(3, 1), std::out_of_range);
833 EXPECT_THROW(index.update(0, nan, 10, 3, count), std::domain_error);
834 EXPECT_THROW(index.update(0, -Infinity, 10, 3, count), std::domain_error);
835 EXPECT_THROW(index.update(0, 2, nan, 3, count), std::domain_error);
836 EXPECT_THROW(index.update(3, 2, 10, 3, count), std::out_of_range);
837 EXPECT_THROW(index.for_each_cycle_below(nan, 3, count), std::domain_error);
838 EXPECT_THROW(index.for_each_cycle_below({0}, nan, 3, count), std::domain_error);
839 EXPECT_THROW(index.for_each_cycle_below({0, 3}, 10, 3, count), std::out_of_range);
840 EXPECT_THROW((void) index.weight(3), std::out_of_range);
841 EXPECT_THROW((void) index.stamp(3), std::out_of_range);
842 EXPECT_THROW(index.touch(3), std::out_of_range);
843 EXPECT_THROW((void) index.cycles_of(3), std::out_of_range);
844 EXPECT_THROW((void) index.length(1), std::out_of_range);
845
846 EXPECT_EQ(handed, 0u);
847 EXPECT_EQ(index.clock(), clock);
848 for (size_t a = 0; a < 3; ++a)
849 EXPECT_EQ(index.weight(a), 1);
850 EXPECT_EQ(index.for_each_cycle_below({0, 1, 2}, 10, 3, count), 1u); // no mark was left
851 EXPECT_EQ(handed, 1u);
852 EXPECT_EQ(index.update(0, Infinity, 10, 3, count), 1u); // plus infinity is a weight
853 EXPECT_EQ(handed, 1u);
854}
855
856// The lengths, the kind of graph and the number of cycles have limits
857TEST(BoundedCycleIndex, HasLimits)
858{
859 const Built<List_Type> built(5, complete_ends(5));
860 EXPECT_THROW(Bounded_Cycle_Index(built.g, {0}), std::domain_error);
861 EXPECT_THROW(Bounded_Cycle_Index(built.g, {3, 9}), std::domain_error);
862 EXPECT_THROW(Bounded_Cycle_Index(built.g, std::initializer_list<size_t>()), std::domain_error);
863 EXPECT_THROW(Bounded_Cycle_Index<List_Type>(built.g, Array<size_t>()), std::domain_error);
864 EXPECT_THROW(Bounded_Cycle_Index<List_Type>(built.g, Array<size_t>({2, 12})), std::domain_error);
865
866 // 10 cycles of length 2 and 20 of length 3
867 EXPECT_NO_THROW(Bounded_Cycle_Index(built.g, {2, 3}, Arc_List_Order(), 30));
868 EXPECT_THROW(Bounded_Cycle_Index(built.g, {2, 3}, Arc_List_Order(), 29), std::length_error);
869 EXPECT_THROW(Bounded_Cycle_Index(built.g, {2, 3}, Arc_List_Order(), 0), std::length_error);
870 EXPECT_NO_THROW(Bounded_Cycle_Index(built.g, {1}, Arc_List_Order(), 0)); // it has no loops
871
872 using Undirected = List_Graph<Graph_Node<int>, Graph_Arc<int>>;
873 Undirected g;
874 auto p = g.insert_node(0), q = g.insert_node(1);
875 g.insert_arc(p, q, 0);
876 EXPECT_THROW(Bounded_Cycle_Index<Undirected>(g, {2}), std::domain_error);
877}
878
879// With more arcs than fit in 16 bits the index keeps the numbers of the
880// arcs of each cycle in 32, and answers the same
881TEST(BoundedCycleIndex, HoldsMoreArcsThanFitIn16Bits)
882{
883 const size_t chain = 70000; // a path: its arcs are in no cycle
884 Ends ends;
885 for (size_t i = 0; i < chain; ++i)
886 ends.emplace_back(i, i + 1);
887 const size_t base = chain + 1; // then a complete digraph of 4 nodes
888 for (size_t i = 0; i < 4; ++i)
889 for (size_t j = 0; j < 4; ++j)
890 if (i != j)
891 ends.emplace_back(base + i, base + j);
892 const Built<List_Type> built(base + 4, ends);
893 Bounded_Cycle_Index index(built.g, {2, 3, 4});
894 ASSERT_EQ(index.num_arcs(), chain + 12);
895 EXPECT_EQ(index.num_cycles(2), 6u);
896 EXPECT_EQ(index.num_cycles(3), 8u);
897 EXPECT_EQ(index.num_cycles(4), 6u);
898 expect_the_catalog(index, Oracle<List_Type>(built.g, {2, 3, 4}, Arc_List_Order()));
899
900 std::mt19937 rng(5);
901 std::uniform_real_distribution<double> weight(-1, 1);
902 for (size_t a = chain; a < chain + 12; ++a)
903 index.set_weight(a, weight(rng));
904 size_t handed_in_all = 0;
905 for (size_t step = 0; step < 200; ++step)
906 {
907 const size_t arc = chain + rng() % 12;
908 const double w = weight(rng), bound = weight(rng);
909 Handed handed;
910 index.update(arc, w, bound, 4, [&] (size_t p, double s) { handed.emplace_back(p, s); });
911 ASSERT_EQ(handed, below_of(index, arc, bound, 4));
912 handed_in_all += handed.size();
913 }
914 EXPECT_GT(handed_in_all, 100u);
915 EXPECT_TRUE(index.cycles_of(0).empty());
916 EXPECT_EQ(index.update(chain - 1, -5, Infinity, 4, [] (size_t, double) {}), 0u);
917 Handed once;
918 index.for_each_cycle_below({chain, chain + 3, chain + 1}, Infinity, 4,
919 [&] (size_t p, double s) { once.emplace_back(p, s); });
920 std::set<size_t> positions;
921 for (const auto & [position, sum] : once)
922 EXPECT_TRUE(positions.insert(position).second);
923}
924
925// If the function throws, the weight is changed, the index is whole and
926// no mark is left
927TEST(BoundedCycleIndex, StaysWholeWhenTheFunctionThrows)
928{
929 const Built<List_Type> built(4, complete_ends(4));
930 Bounded_Cycle_Index index(built.g, {2, 3, 4});
931 for (size_t a = 0; a < index.num_arcs(); ++a)
932 index.set_weight(a, 1);
933 size_t calls = 0;
934 const auto third_throws = [&calls] (size_t, double)
935 {
936 if (++calls == 3)
937 throw std::runtime_error("the third one");
938 };
939 EXPECT_THROW(index.update(0, -7, Infinity, 4, third_throws), std::runtime_error);
940 EXPECT_EQ(calls, 3u);
941 EXPECT_EQ(index.weight(0), -7);
942
943 calls = 0;
944 EXPECT_THROW(index.for_each_cycle_below({1, 2, 3}, Infinity, 4, third_throws),
945 std::runtime_error);
946 calls = 0;
947 EXPECT_THROW(index.for_each_cycle_below(Infinity, 4, third_throws), std::runtime_error);
948
949 // afterwards each query hands all that it must
950 size_t handed = 0;
951 const auto count = [&handed] (size_t, double) { ++handed; };
952 std::set<size_t> of_any;
953 for (const size_t a : {1, 2, 3})
954 for (const size_t position : index.cycles_of(a))
955 of_any.insert(position);
956 EXPECT_EQ(index.for_each_cycle_below({1, 2, 3}, Infinity, 4, count), of_any.size());
957 EXPECT_EQ(handed, of_any.size());
958 handed = 0;
959 EXPECT_EQ(index.update(0, -7, Infinity, 4, count), index.cycles_of(0).size());
960 EXPECT_EQ(handed, index.cycles_of(0).size());
961}
962
963// Each write of an arc takes the next value of the clock, and a cycle is
964// stale if one of its arcs was written after the moment given
965TEST(BoundedCycleIndex, StampsTheWritesOfEachArc)
966{
967 // two triangles that share the arc 0 -> 1
968 const Built<List_Type> built(4, {{0, 1}, {1, 2}, {2, 0}, {1, 3}, {3, 0}});
969 Bounded_Cycle_Index index(built.g, {3});
970 ASSERT_EQ(index.num_cycles(), 2u); // 0 1 2 and 0 3 4
971 EXPECT_EQ(index.clock(), 0u);
972 for (size_t a = 0; a < 5; ++a)
973 EXPECT_EQ(index.stamp(a), 0u);
974 EXPECT_FALSE(index.is_stale(0, 0));
975
976 for (size_t a = 0; a < 5; ++a)
977 index.set_weight(a, 1);
978 EXPECT_EQ(index.clock(), 5u);
979 EXPECT_EQ(index.stamp(3), 4u);
980 const uint64_t computed_at = index.clock();
981 EXPECT_FALSE(index.is_stale(0, computed_at));
982 EXPECT_FALSE(index.is_stale(1, computed_at));
983
984 index.update(4, 2, 0, 3, [] (size_t, double) {}); // of the second triangle
985 EXPECT_EQ(index.stamp(4), 6u);
986 EXPECT_FALSE(index.is_stale(0, computed_at));
987 EXPECT_TRUE(index.is_stale(1, computed_at));
988 EXPECT_FALSE(index.is_stale(1, index.clock()));
989
990 index.touch(0); // of both, and its weight is the same
991 EXPECT_EQ(index.weight(0), 1);
992 EXPECT_EQ(index.stamp(0), 7u);
993 EXPECT_TRUE(index.is_stale(0, computed_at));
994 EXPECT_TRUE(index.is_stale(1, 6));
995 index.set_weight(0, 1); // the same weight is a write too
996 EXPECT_EQ(index.clock(), 8u);
997}
998
999// swap() exchanges two indexes, also of different sets of lengths and of
1000// different graphs, and a copy does not share with its original
1001TEST(BoundedCycleIndex, SwapsAndCopies)
1002{
1003 const Built<List_Type> built(5, complete_ends(5));
1004 const Built<List_Type> other(3, {{0, 1}, {1, 2}, {2, 0}});
1005 Bounded_Cycle_Index small(built.g, {3});
1006 Bounded_Cycle_Index large(built.g, {3, 4, 5});
1007 Bounded_Cycle_Index triangle(other.g, {3});
1008 static_assert(noexcept(small.swap(large)));
1009 small.set_weight(0, 0.5);
1010 large.set_weight(0, 0.25);
1011 const size_t in_small = small.num_cycles(), in_large = large.num_cycles();
1012
1013 small.swap(large);
1014 EXPECT_EQ(small.num_cycles(), in_large);
1015 EXPECT_EQ(large.num_cycles(), in_small);
1016 EXPECT_EQ(small.longest_length(), 5u);
1017 EXPECT_EQ(large.longest_length(), 3u);
1018 EXPECT_EQ(small.weight(0), 0.25);
1019 EXPECT_EQ(large.weight(0), 0.5);
1020 EXPECT_EQ(small.clock(), 1u);
1021 expect_the_catalog(small, Oracle<List_Type>(built.g, {3, 4, 5}, Arc_List_Order()));
1022 expect_the_catalog(large, Oracle<List_Type>(built.g, {3}, Arc_List_Order()));
1023
1024 small.swap(triangle);
1025 EXPECT_EQ(small.num_arcs(), 3u);
1026 EXPECT_EQ(triangle.num_arcs(), 20u);
1027 EXPECT_EQ(small.arc_number(other.arcs[1]), 1u);
1028 EXPECT_THROW((void) small.arc_number(built.arcs[0]), std::domain_error);
1029 expect_the_catalog(triangle, Oracle<List_Type>(built.g, {3, 4, 5}, Arc_List_Order()));
1030 EXPECT_EQ(small.clock(), 0u);
1031 EXPECT_EQ(triangle.clock(), 1u);
1032 EXPECT_EQ(triangle.stamp(0), 1u);
1033
1034 // each one answers with what it has now
1035 for (Bounded_Cycle_Index<List_Type> *index : {&small, &triangle})
1036 {
1037 for (size_t a = 0; a < index->num_arcs(); ++a)
1038 index->set_weight(a, a % 3 == 0 ? -1.0 : 0.25);
1039 const size_t last = index->num_arcs() - 1;
1040 Handed handed;
1041 const auto keep = [&handed] (size_t p, double s) { handed.emplace_back(p, s); };
1042 index->update(last, -0.5, 0, 8, keep);
1043 EXPECT_EQ(handed, below_of(*index, last, 0, 8));
1044 EXPECT_FALSE(handed.empty());
1045 handed.clear();
1046 const size_t seen = index->for_each_cycle_below({0, last}, 0, 8, keep);
1047 std::set<size_t> of_any;
1048 for (const size_t a : {size_t(0), last})
1049 for (const size_t position : index->cycles_of(a))
1050 of_any.insert(position);
1051 EXPECT_EQ(seen, of_any.size());
1052 size_t below = 0;
1053 for (const size_t position : of_any)
1054 below += index->weight_sum(position) < 0;
1055 EXPECT_EQ(handed.size(), below);
1056 }
1057
1058 Bounded_Cycle_Index copy = triangle;
1059 copy.set_weight(0, 9);
1060 EXPECT_EQ(triangle.weight(0), -1);
1061 EXPECT_EQ(copy.weight(0), 9);
1062 EXPECT_EQ(copy.clock(), triangle.clock() + 1);
1063 expect_the_catalog(copy, Oracle<List_Type>(built.g, {3, 4, 5}, Arc_List_Order()));
1064 Bounded_Cycle_Index moved = std::move(copy);
1065 EXPECT_EQ(moved.weight(0), 9);
1066 expect_the_catalog(moved, Oracle<List_Type>(built.g, {3, 4, 5}, Arc_List_Order()));
1067}
1068
1069// A copy made by the function that receives the cycles, while some arcs
1070// are marked, is in no query: it hands every cycle that it is asked for.
1071// So does an index that is assigned there.
1072TEST(BoundedCycleIndex, StartsACopyMadeInsideAQueryWithoutMarks)
1073{
1074 // two cycles of two arcs, apart: the arcs 0 and 1, and the arcs 2 and 3
1075 const Built<List_Type> built(4, {{0, 1}, {1, 0}, {2, 3}, {3, 2}});
1076 const Built<List_Type> other(3, {{0, 1}, {1, 2}, {2, 0}});
1077 Bounded_Cycle_Index index(built.g, {2});
1078 ASSERT_EQ(index.num_cycles(), 2u);
1079 for (size_t a = 0; a < 4; ++a)
1080 index.set_weight(a, -1);
1081
1082 std::vector<Bounded_Cycle_Index<List_Type>> copies;
1083 Bounded_Cycle_Index assigned(other.g, {3});
1084 size_t calls = 0;
1085 index.for_each_cycle_below({0, 2}, 0, 2, [&] (size_t, double)
1086 {
1087 if (++calls == 2) // the cycle of the arc 2: the arc 0 is marked
1088 {
1089 copies.push_back(index);
1090 assigned = index;
1091 }
1092 });
1093 ASSERT_EQ(calls, 2u);
1094 ASSERT_EQ(copies.size(), 1u);
1095
1096 // the arc 1 after another arc: its cycle goes through the arc 0
1097 for (Bounded_Cycle_Index<List_Type> *each : {&copies[0], &assigned, &index})
1098 {
1099 size_t handed = 0;
1100 EXPECT_EQ(each->for_each_cycle_below({2, 1}, 0, 2, [&handed] (size_t, double) { ++handed; }),
1101 2u);
1102 EXPECT_EQ(handed, 2u);
1103 }
1104 EXPECT_EQ(Answers(copies[0]), Answers(index));
1105 EXPECT_EQ(Answers(assigned), Answers(index));
1106}
1107
1108// An index that is moved from, by construction or by assignment, is left
1109// without arcs and without cycles; it answers every query, and it can
1110// be copied, exchanged and given an index again
1111TEST(BoundedCycleIndex, LeavesAnIndexThatIsMovedFromWithoutArcsAndCycles)
1112{
1113 static_assert(std::is_nothrow_move_constructible_v<Bounded_Cycle_Index<List_Type>>);
1114 static_assert(std::is_nothrow_move_assignable_v<Bounded_Cycle_Index<List_Type>>);
1115 const Built<List_Type> built(4, complete_ends(4));
1116 const Built<List_Type> other(3, {{0, 1}, {1, 2}, {2, 0}});
1117 Bounded_Cycle_Index index(built.g, {2, 3});
1118 for (size_t a = 0; a < index.num_arcs(); ++a)
1119 index.set_weight(a, a % 2 == 0 ? -1.0 : 0.5);
1120 Bounded_Cycle_Index copy = index;
1121 const Answers before(copy);
1122 ASSERT_GT(before.cycles.size(), 0u);
1123 ASSERT_GT(before.handed.size(), 0u);
1124
1125 Bounded_Cycle_Index taken(std::move(index));
1126 EXPECT_EQ(Answers(taken), before);
1127 expect_no_arcs_and_no_cycles(index, built.arcs[0]);
1128
1129 Bounded_Cycle_Index triangle(other.g, {3});
1130 triangle.set_weight(0, 0.125);
1131 triangle = std::move(taken); // what the triangle had is freed
1132 EXPECT_EQ(Answers(triangle), before);
1133 expect_no_arcs_and_no_cycles(taken, built.arcs[0]);
1134
1135 // a copy of one without arcs has none either, and so is what is
1136 // exchanged with it
1137 Bounded_Cycle_Index of_none = index;
1138 expect_no_arcs_and_no_cycles(of_none, built.arcs[0]);
1139 of_none.swap(triangle);
1140 EXPECT_EQ(Answers(of_none), before);
1141 expect_no_arcs_and_no_cycles(triangle, built.arcs[0]);
1142
1143 // and each of them takes an index again, by copy and by move
1144 index = copy;
1145 EXPECT_EQ(Answers(index), before);
1146 taken = std::move(index);
1147 EXPECT_EQ(Answers(taken), before);
1148 expect_no_arcs_and_no_cycles(index, built.arcs[0]);
1149 taken.set_weight(0, 7);
1150 EXPECT_EQ(copy.weight(0), -1);
1151}
1152
1153// An index that is assigned to itself, by copy or by move, keeps all
1154// that it had
1155TEST(BoundedCycleIndex, KeepsWhatItHadWhenItIsAssignedToItself)
1156{
1157 const Built<List_Type> built(4, complete_ends(4));
1158 Bounded_Cycle_Index index(built.g, {2, 3, 4});
1159 for (size_t a = 0; a < index.num_arcs(); ++a)
1160 index.set_weight(a, a % 3 == 0 ? -2.0 : 0.25);
1161 const Answers before(index);
1162 Bounded_Cycle_Index<List_Type> & same = index;
1163 index = same;
1164 EXPECT_EQ(Answers(index), before);
1165 index = std::move(same);
1166 EXPECT_EQ(Answers(index), before);
1167 index.swap(same);
1168 EXPECT_EQ(Answers(index), before);
1169}
1170
1171// If the function throws when an arc was already looked at, the mark of
1172// that arc is cleared: the next query hands the cycles of that arc
1173TEST(BoundedCycleIndex, ClearsTheMarkOfAnArcWhenTheFunctionThrowsAfterIt)
1174{
1175 const Built<List_Type> built(4, complete_ends(4));
1176 Bounded_Cycle_Index index(built.g, {2, 3, 4});
1177 for (size_t a = 0; a < index.num_arcs(); ++a)
1178 index.set_weight(a, 1);
1179 // the arcs 1 and 2 leave the same node: no cycle has both
1180 const size_t of_first = index.cycles_of(1).size();
1181 ASSERT_GT(of_first, 0u);
1182 size_t calls = 0;
1183 const auto throws_at_the_second_arc = [&calls, of_first] (size_t, double)
1184 {
1185 if (++calls == of_first + 1)
1186 throw std::runtime_error("the first cycle of the second arc");
1187 };
1188 EXPECT_THROW(index.for_each_cycle_below({1, 2}, Infinity, 4, throws_at_the_second_arc),
1189 std::runtime_error);
1190 EXPECT_EQ(calls, of_first + 1);
1191
1192 size_t handed = 0;
1193 const auto count = [&handed] (size_t, double) { ++handed; };
1194 const size_t of_both = of_first + index.cycles_of(2).size();
1195 EXPECT_EQ(index.for_each_cycle_below({2, 1}, Infinity, 4, count), of_both);
1196 EXPECT_EQ(handed, of_both);
1197}
1198
1199// The additions that widen the bound are rounded as well: a bound that is
1200// rounded down to the sum of a cycle loses it, and one that is rounded up
1201// after each addition does not
1202TEST(BoundedCycleIndex, NeedsTheBoundRoundedUp)
1203{
1204 // a loop that weighs exactly 1, below an exact threshold of 1 + 2^-54
1205 // that the caller has as 1, within 2^-54
1206 const Built<List_Type> built(1, {{0, 0}});
1207 Bounded_Cycle_Index index(built.g, {1});
1208 const double approximate = 1, its_error = 0x1p-54;
1209 const double of_the_sum = Bounded_Cycle_Index<List_Type>::sum_error_bound(1, 1);
1210 EXPECT_EQ(of_the_sum, 0);
1211 size_t handed = 0;
1212 const auto count = [&handed] (size_t, double) { ++handed; };
1213
1214 const double rounded_down = approximate + of_the_sum + its_error;
1215 EXPECT_EQ(rounded_down, 1);
1216 index.update(0, 1, rounded_down, 1, count);
1217 EXPECT_EQ(handed, 0u);
1218
1219 double bound = std::nextafter(approximate + of_the_sum, Infinity);
1220 bound = std::nextafter(bound + its_error, Infinity);
1221 index.update(0, 1, bound, 1, count);
1222 EXPECT_EQ(handed, 1u);
1223}
1224
1225// With only the loops asked for, the index has each loop of a multigraph
1226// and no other cycle, also among many parallel arcs
1227TEST(BoundedCycleIndex, HasOnlyTheLoopsWhenOnlyTheyAreAskedFor)
1228{
1229 Ends ends;
1230 for (size_t i = 0; i < 300; ++i)
1231 {
1232 ends.emplace_back(0, 1);
1233 ends.emplace_back(1, 2);
1234 if (i % 100 == 0)
1235 ends.emplace_back(i / 100, i / 100); // a loop at the nodes 0, 1 and 2
1236 }
1237 ends.emplace_back(2, 0); // closes cycles of three arcs, which are not asked for
1238 const Built<List_Type> built(3, ends);
1239 Bounded_Cycle_Index index(built.g, {1});
1240 expect_the_catalog(index, Oracle<List_Type>(built.g, {1}, Arc_List_Order()));
1241 EXPECT_EQ(index.num_cycles(), 3u);
1242 for (size_t position = 0; position < index.num_cycles(); ++position)
1243 {
1244 const size_t loop = index.cycle_arcs(position)[0];
1245 EXPECT_EQ(built.g.get_src_node(index.arc(loop)), built.g.get_tgt_node(index.arc(loop)));
1246 EXPECT_EQ(as_vector(index.cycles_of(loop)), std::vector<size_t>{position});
1247 }
1248}
1249
1250// The sum that the index computes is within sum_error_bound() of the
1251// exact sum of the weights, taken with rationals; and with the bound
1252// widened by it, no cycle whose exact sum is below a threshold is lost
1253TEST(BoundedCycleIndex, BoundsTheErrorOfTheSum)
1254{
1255 using Index = Bounded_Cycle_Index<List_Type>;
1256 EXPECT_EQ(Index::sum_error_bound(0, 100), 0);
1257 EXPECT_EQ(Index::sum_error_bound(1, 100), 0);
1258 EXPECT_GT(Index::sum_error_bound(2, 100), 0);
1259 static_assert(Index::sum_error_bound(6, 64) < 4e-13); // the figure of the report
1260 static_assert(Index::sum_error_bound(6, 64) > 2e-13);
1261
1262 std::mt19937_64 rng(20261115);
1263 size_t inexact = 0, kept_by_the_margin = 0;
1264 for (size_t k = 2; k <= 8; ++k)
1265 {
1266 Ends ring;
1267 for (size_t i = 0; i < k; ++i)
1268 ring.emplace_back(i, (i + 1) % k);
1269 const Built<List_Type> built(k, ring);
1270 Index index(built.g, {k});
1271 ASSERT_EQ(index.num_cycles(), 1u);
1272 for (size_t round = 0; round < 4000; ++round)
1273 {
1274 // weights of very different magnitudes, some of them cancelling
1275 const double scale = std::ldexp(1.0, int(rng() % 60));
1276 double largest = 0;
1277 mpq_class exact = 0;
1278 double previous = 0;
1279 for (size_t a = 0; a < k; ++a)
1280 {
1281 // two statements: the order of the arguments of a call is
1282 // not fixed, and each compiler would draw other weights
1283 const double fraction = double(int64_t(rng() >> 11)) / 9007199254740992.0 - 0.5;
1284 double w = std::ldexp(fraction, int(rng() % 60));
1285 if (a % 3 == 2)
1286 w = -previous * (1 + std::ldexp(1.0, -30 - int(rng() % 20)));
1287 w = std::fmin(std::fmax(w, -scale), scale);
1288 index.set_weight(a, previous = w);
1289 largest = std::fmax(largest, std::fabs(w));
1290 exact += mpq_class(w);
1291 }
1292 const double sum = index.weight_sum(0);
1293 const double error_bound = Index::sum_error_bound(k, largest);
1294 const mpq_class error = abs(mpq_class(sum) - exact);
1295 // not ASSERT_LE: it would print the rationals, and with libc++
1296 // the inserters of the library of GMP do not link
1297 ASSERT_TRUE(error <= mpq_class(error_bound)) << "length " << k << ", sum " << sum;
1298 inexact += error != 0;
1299
1300 // a threshold just above the exact sum: the cycle is below it
1301 const mpq_class threshold =
1302 exact + abs(exact) / mpz_class("1000000000000000000") +
1303 1 / mpq_class(std::ldexp(1.0, 200));
1304 const double t = threshold.get_d(); // truncated towards zero
1305 const double t_error = std::fabs(t) * 0x1p-52 + 0x1p-1000;
1306 size_t handed = 0;
1307 index.for_each_cycle_below(t + t_error + error_bound, k,
1308 [&handed] (size_t, double) { ++handed; });
1309 ASSERT_EQ(handed, 1u) << "a cycle below the threshold was lost";
1310 handed = 0;
1311 index.for_each_cycle_below(t, k, [&handed] (size_t, double) { ++handed; });
1312 kept_by_the_margin += handed == 0;
1313 }
1314 }
1315 EXPECT_GT(inexact, 5000u); // the sums did round
1316 EXPECT_GT(kept_by_the_margin, 500u); // and without the margin cycles are lost
1317}
Index of the simple cycles of bounded length of a digraph, with a weight for each arc and a filter by...
TYPED_TEST_SUITE(ArcHeapLifecycle, ArcHeapKinds)
WeightedDigraph::Arc Arc
TYPED_TEST(BoundedCycleIndexOn, HasTheCatalogOfASearchMadeApart)
long double w
Definition btreepic.C:153
size_t size_t int32_t * out
Definition ca-c-api.h:120
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
T & append(const T &data)
Append a copy of data
Definition tpl_array.H:331
Index of the simple cycles of bounded length of a digraph.
uint64_t clock() const noexcept
The number of writes of a weight so far: each set_weight(), update() and touch() adds one.
static constexpr double sum_error_bound(const size_t k, const double max_abs_weight) noexcept
A bound of the rounding error of the sum of the weights of a cycle.
void swap(Bounded_Cycle_Index &other) noexcept
Exchange two indexes in constant time, without failing: how to replace an index by another built apar...
size_t arc_number(const Arc *a) const
The number of an arc of the graph, in O(1) expected.
size_t length(const size_t position) const
The length of a cycle.
uint64_t stamp(const size_t arc) const
The value of clock() when an arc was last written.
bool has_length(const size_t length) const noexcept
Return true if length is one of the lengths of the index.
std::span< const uint32_t > cycles_of(const size_t arc) const
The cycles that go through an arc, by their positions, in ascending order.
double weight(const size_t arc) const
The weight of an arc.
double weight_sum(const size_t position) const
The weight of a cycle: the sum of the weights of its arcs, in the order of its canonical rotation.
size_t for_each_cycle_below(const Array< size_t > &arcs, const double bound, const size_t max_length, Op &&op)
Hand the cycles through any of some arcs whose weight is below a bound, each cycle once.
size_t num_arcs() const noexcept
The number of arcs of the graph when the index was built.
std::span< const uint32_t > cycle_arcs(const size_t position) const
The arcs of a cycle, by their numbers, in its canonical rotation: from the arc of least number,...
void touch(const size_t arc)
Mark an arc as written without changing its weight, for what the caller keeps of its cycles and depen...
bool is_stale(const size_t position, const uint64_t computed_at) const
Return true if an arc of a cycle was written after a moment: what was computed of the cycle then is o...
size_t num_cycles_up_to(const size_t max_length) const noexcept
The number of cycles whose length is at most max_length: the size of the prefix of the catalog that t...
size_t num_cycles() const noexcept
The number of cycles of the catalog.
void set_weight(const size_t arc, const double w)
Change the weight of an arc, without looking at its cycles.
Arc * arc(const size_t number) const
The arc with a number.
size_t update(const size_t arc, const double w, const double bound, const size_t max_length, Op &&op)
Change the weight of an arc and hand the cycles through it whose weight is below a bound.
size_t longest_length() const noexcept
The longest length of the set of the index.
Strict read-only view of a graph.
Generic directed graph (digraph) wrapper template.
Definition graph-dry.H:4377
Arc for graphs implemented with simple adjacency lists.
Definition tpl_sgraph.H:197
virtual Node * insert_node(Node *node) noexcept
Insertion of a node already allocated.
Definition tpl_graph.H:535
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.
ArcInfo & get_info() noexcept
Return a modifiable reference to the arc data.
Definition graph-dry.H:854
Node * get_src_node(Arc *arc) const noexcept
Return the source node of arc (only for directed graphs)
Definition graph-dry.H:1017
Node * get_tgt_node(Arc *arc) const noexcept
Return the target node of arc (only for directed graphs)
Definition graph-dry.H:1023
#define TEST(name)
static mt19937 rng
static Tree_Node< int > * chain(size_t n)
__gmp_expr< T, __gmp_unary_expr< __gmp_expr< T, U >, __gmp_abs_function > > abs(const __gmp_expr< T, U > &expr)
Definition gmpfrxx.h:4129
__gmp_expr< mpz_t, mpz_t > mpz_class
Definition gmpfrxx.h:2068
__gmp_expr< mpq_t, mpq_t > mpq_class
Definition gmpfrxx.h:2270
DynArray< Graph::Node * > nodes
Definition graphpic.C:406
DynArray< Graph::Arc * > arcs
Definition graphpic.C:408
Main namespace for Aleph-w library functions.
void each(const size_t start, const size_t end, Op &op)
Execute an operation repeatedly over a range of indices.
bool operator==(const DynList< T > &l1, const DynList< T > &l2)
Equality operator for DynList.
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
Itor2 copy(Itor1 sourceBeg, const Itor1 &sourceEnd, Itor2 destBeg)
Copy elements from one range to another.
Definition ahAlgo.H:584
bool all(Container &container, Operation &operation)
Return true if all elements satisfy a predicate.
static void prefix(Node *root, DynList< Node * > &acc)
@ Cycle
Graph has an Eulerian cycle.
and
Check uniqueness with explicit hash + equality functors.
std::pair< First, Second > pair
Alias to std::pair kept for backwards compatibility.
Definition ahPair.H:89
void error(const char *file, int line, const char *format,...)
Print an error message with file and line info.
Definition ahDefs.C:100
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
Definition ahAlgo.H:127
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
Spec reversed(const Spec &s)
The spec with each arc reversed; the arcs keep their numbers.
The order of the arc iterator of the graph, as a comparison for Bounded_Cycle_Index: it tells no arc ...
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)
static int * k
Array-based graph implementation.
Strict read-only access to a graph: Const_Graph_View and the read-only iterators on the nodes,...
Generic graph and digraph implementations.
Simple graph implementation with adjacency lists.