Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
moved_from_engines_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
38#include "moved_from.H"
39
40#include <ca-observer.H>
42#include <concurrency_utils.H>
43#include <parse-csv.H>
44#include <thread_pool.H>
45#include <tpl_ca_async_engine.H>
46#include <tpl_ca_bit_storage.H>
47#include <tpl_ca_engine.H>
50#include <tpl_ca_hashlife.H>
51#include <tpl_ca_lattice.H>
55#include <tpl_ca_neighborhood.H>
57#include <tpl_ca_rule.H>
58#include <tpl_ca_storage.H>
59
60#include <array>
61#include <cstdint>
62#include <filesystem>
63#include <fstream>
64#include <memory>
65#include <sstream>
66#include <string>
67#include <system_error>
68#include <thread>
69#include <tuple>
70#include <type_traits>
71#include <utility>
72
73#if defined(_WIN32)
74# include <process.h>
75#else
76# include <unistd.h>
77#endif
78
79using namespace Aleph;
80using namespace Aleph::CA;
81
82namespace
83{
84 using Extents = std::array<ca_size_t, 2>;
85
86 // About n cells: one row for the smallest objects, ten rows otherwise
87 Extents extents_of(const size_t n)
88 {
89 const ca_size_t rows = n < 10 ? 1 : 10;
90 return {rows, n / rows};
91 }
92
93 // Calls f(c) with every coordinate of a lattice of extents e
94 template <typename F>
95 void for_each_cell(const Extents & e, F && f)
96 {
97 for (ca_size_t i = 0; i < e[0]; ++i)
98 for (ca_size_t j = 0; j < e[1]; ++j)
99 f(Coord_Vec<2>{static_cast<ca_index_t>(i), static_cast<ca_index_t>(j)});
100 }
101
106
113
114 using Random_Life
116
117 using Tiles = Tile_Cache<int, 4>;
118 using Density = Density_Observer<int>;
119 using Entropy = Entropy_Observer<2>;
120
121 using Locked = Synchronized<long>::LockedPtr;
122 using Const_Locked = Synchronized<long>::ConstLockedPtr;
123 using Read_Locked = RwSynchronized<long>::ReadLockedPtr;
124 using Write_Locked = RwSynchronized<long>::WriteLockedPtr;
125
126 // A lattice of about n cells, with a blinker where it fits
127 Grid life_grid(const size_t n)
128 {
129 Grid g(extents_of(n), 0);
130 if (g.size(1) >= 3)
131 for (ca_index_t j = 0; j < 3; ++j)
132 g.set({0, j}, 1);
133 return g;
134 }
135
136 // What a user does with a rectangular engine: step it, read its frame and
137 // run it
138 template <class Engine>
139 void use_engine(Engine & e)
140 {
141 const size_t steps = e.steps_run();
142 e.step();
143 EXPECT_EQ(e.steps_run(), steps + 1);
144 size_t alive = 0;
145 for_each_cell(e.frame().extents(), [&e, &alive](const Coord_Vec<2> & c)
146 {
147 if (e.frame().at(c) != 0)
148 ++alive;
149 });
150 EXPECT_LE(alive, e.frame().size());
151 e.run(2);
152 EXPECT_EQ(e.steps_run(), steps + 3);
153 }
154
155 // The cells, the live cells and the steps of a rectangular engine
156 template <class Engine>
157 std::tuple<size_t, size_t, size_t> engine_print(const Engine & e)
158 {
159 size_t alive = 0;
160 for_each_cell(e.frame().extents(), [&e, &alive](const Coord_Vec<2> & c)
161 {
162 if (e.frame().at(c) != 0)
163 ++alive;
164 });
165 return {e.frame().size(), alive, e.steps_run()};
166 }
167
168 // Runs an engine for some steps from step 0 with the observer attached,
169 // as a user does
170 template <class Observer>
171 void observe_run(Observer & o, const size_t steps)
172 {
173 Life e(life_grid(100), make_game_of_life_rule(), Moore<2, 1>{});
174 attach_observer(e, o);
175 e.run(steps);
176 }
177
178 // Extents of about n cells, in whole tiles
179 Extents tile_extents_of(const size_t n)
180 {
181 ca_size_t side = Tiles::tile_side;
182 while (side * side < n)
183 side += Tiles::tile_side;
184 return {side, side};
185 }
186
187 // Calls f(r, c) with every cell of a cache of extents e, tile by tile
188 template <typename F>
189 void for_each_tiled_cell(const Extents & e, F && f)
190 {
191 constexpr ca_size_t side = Tiles::tile_side;
192 for (ca_size_t r0 = 0; r0 < e[0]; r0 += side)
193 for (ca_size_t c0 = 0; c0 < e[1]; c0 += side)
194 for (ca_size_t r = r0; r < r0 + side; ++r)
195 for (ca_size_t c = c0; c < c0 + side; ++c)
196 f(r, c);
197 }
198
199 ThreadPool & small_pool()
200 {
201 static ThreadPool pool(2);
202 return pool;
203 }
204
205 // A new value, with its own mutex, for each guard that a test makes: a
206 // test can hold two guards, and since it takes them in the order of the
207 // values, ThreadSanitizer sees no inversion of the order of the locks
208 Synchronized<long> & sync_slot()
209 {
210 static Synchronized<long> slots[32];
211 static size_t next = 0;
212 return slots[next++ % 32];
213 }
214
215 RwSynchronized<long> & rw_slot()
216 {
217 static RwSynchronized<long> slots[32];
218 static size_t next = 0;
219 return slots[next++ % 32];
220 }
221
222 // Each test runs in its own process, maybe beside others: the names of
223 // the files carry the process
224 long long process_id() noexcept
225 {
226#if defined(_WIN32)
227 return static_cast<long long>(_getpid());
228#else
229 return static_cast<long long>(getpid());
230#endif
231 }
232
233 // The files and directories that the tests write, all of them in the
234 // temporary directory; they are removed when the program ends, once
235 // every object has closed them
236 struct Temp_Paths
237 {
239
240 ~Temp_Paths()
241 {
242 for (size_t i = 0; i < paths.size(); ++i)
243 {
244 std::error_code ec;
245 std::filesystem::remove_all(paths(i), ec);
246 }
247 }
248 };
249
250 // A new path in the temporary directory, unique to the process and to
251 // the call
252 std::filesystem::path temp_path(const std::string & kind)
253 {
254 static Temp_Paths temps;
255 const std::string name = "aleph_moved_from_" + kind + "_" + std::to_string(process_id())
256 + "_" + std::to_string(temps.paths.size());
257 const std::filesystem::path path = std::filesystem::temp_directory_path() / name;
258 temps.paths.append(path);
259 return path;
260 }
261
262 // A file whose header gives its number of rows, followed by n rows of
263 // three fields
264 std::string write_csv(const size_t n)
265 {
266 const std::string path = temp_path("csv").string();
267 std::ofstream out(path);
268 out << "rows," << n << "\n";
269 for (size_t i = 0; i < n; ++i)
270 out << i << ",b" << i << ",c" << i << "\n";
271 return path;
272 }
273
274 // A rule that, like a lambda, can be moved but not assigned
275 struct Fixed_Rule
276 {
277 Fixed_Rule() = default;
278 Fixed_Rule(const Fixed_Rule &) = default;
279 Fixed_Rule(Fixed_Rule &&) = default;
280 Fixed_Rule & operator = (const Fixed_Rule &) = delete;
281
282 template <typename State>
283 State operator()(const State & s, Neighbor_View<State>) const { return s; }
284 };
285}
286
287// The moves of the storages, the lattices and the guards do not throw, and
288// those of the engines do not throw when the moves of their parts do not
289static_assert(std::is_nothrow_move_constructible_v<Dense_Cell_Storage<int, 2>>);
290static_assert(std::is_nothrow_move_assignable_v<Dense_Cell_Storage<int, 2>>);
291static_assert(std::is_nothrow_move_constructible_v<Bit_Cell_Storage<2>>);
292static_assert(std::is_nothrow_move_assignable_v<Ghost_Grid>);
293static_assert(std::is_nothrow_move_assignable_v<Field_Grid>);
294static_assert(std::is_nothrow_move_constructible_v<Graph_Lattice<int>>);
295static_assert(std::is_nothrow_move_constructible_v<Life>);
296static_assert(std::is_nothrow_move_assignable_v<Life>);
297static_assert(std::is_nothrow_move_assignable_v<Async_Life>);
298static_assert(std::is_nothrow_move_assignable_v<Parallel_Life>);
299static_assert(std::is_nothrow_move_assignable_v<Field_Life>);
300static_assert(std::is_nothrow_move_assignable_v<Graph_Life>);
301static_assert(std::is_nothrow_move_assignable_v<Random_Life>);
302static_assert(std::is_nothrow_move_assignable_v<Hashlife_Engine>);
303static_assert(std::is_nothrow_move_assignable_v<Tiles>);
304static_assert(std::is_nothrow_move_constructible_v<Density>);
305static_assert(std::is_nothrow_move_assignable_v<Entropy>);
306static_assert(std::is_nothrow_move_assignable_v<Locked>);
307static_assert(std::is_nothrow_move_constructible_v<Read_Locked>);
308
309// The copies are kept, except those of Hashlife_Engine and Tile_Cache, which
310// shared the nodes and the tiles of the original
311static_assert(std::is_copy_constructible_v<Dense_Cell_Storage<int, 2>>);
312static_assert(std::is_copy_assignable_v<Life>);
313static_assert(std::is_copy_constructible_v<Density>);
314static_assert(not std::is_copy_constructible_v<Hashlife_Engine>);
315static_assert(not std::is_copy_constructible_v<Tiles>);
316
317// An engine whose rule cannot be assigned is moved, but not assigned, as
318// with the implicit moves
319static_assert(std::is_move_constructible_v<Synchronous_Engine<Grid, Fixed_Rule, Moore<2, 1>>>);
320static_assert(not std::is_move_assignable_v<Synchronous_Engine<Grid, Fixed_Rule, Moore<2, 1>>>);
321
322template <> struct Moved_From_Case<Dense_Cell_Storage<int, 2>>
323{
324 static Dense_Cell_Storage<int, 2> make(const size_t n)
325 {
326 return Dense_Cell_Storage<int, 2>(extents_of(n), 1);
327 }
329 {
330 return s.size() == 0 and s.size(0) == 0 and s.data() == nullptr;
331 }
332 static std::tuple<ca_size_t, ca_size_t, long> fingerprint(const Dense_Cell_Storage<int, 2> & s)
333 {
334 long sum = 0;
335 for_each_cell(s.extents(), [&s, &sum](const Coord_Vec<2> & c) { sum += s.at(c); });
336 return {s.size(0), s.size(1), sum};
337 }
339 {
340 for_each_cell(s.extents(), [&s](const Coord_Vec<2> & c) { s.set(c, s.at(c) + 1); });
341 s.fill(7);
342 for_each_cell(s.extents(), [&s](const Coord_Vec<2> & c) { EXPECT_EQ(s.at(c), 7); });
343 EXPECT_EQ(s.view().extent(0), s.size(0));
344 }
345};
346
347template <> struct Moved_From_Case<Bit_Cell_Storage<2>>
348{
349 static Bit_Cell_Storage<2> make(const size_t n)
350 {
351 return Bit_Cell_Storage<2>(extents_of(n), true);
352 }
353 static bool is_empty(const Bit_Cell_Storage<2> & s) { return s.size() == 0 and s.size(0) == 0; }
354 static std::tuple<ca_size_t, ca_size_t, size_t> fingerprint(const Bit_Cell_Storage<2> & s)
355 {
356 size_t set = 0;
357 for_each_cell(s.extents(), [&s, &set](const Coord_Vec<2> & c)
358 {
359 if (s.at(c))
360 ++set;
361 });
362 return {s.size(0), s.size(1), set};
363 }
364 static void use(Bit_Cell_Storage<2> & s)
365 {
366 for_each_cell(s.extents(), [&s](const Coord_Vec<2> & c) { s.set(c, not s.at(c)); });
367 s.fill(true);
368 for_each_cell(s.extents(), [&s](const Coord_Vec<2> & c) { EXPECT_TRUE(s.at(c)); });
369 }
370};
371
372template <> struct Moved_From_Case<Ghost_Grid>
373{
374 static Ghost_Grid make(const size_t n)
375 {
376 Ghost_Grid g(extents_of(n), 0);
377 g.set({0, 0}, 1);
378 g.refresh_halo();
379 return g;
380 }
381 static bool is_empty(const Ghost_Grid & g)
382 {
383 return g.size() == 0 and g.size(0) == 0 and g.store_extents()[0] == 0;
384 }
385 static std::tuple<ca_size_t, ca_size_t, long> fingerprint(const Ghost_Grid & g)
386 {
387 long sum = 0;
388 for_each_cell(g.extents(), [&g, &sum](const Coord_Vec<2> & c) { sum += g.at(c); });
389 return {g.size(0), g.size(1), sum};
390 }
391 static void use(Ghost_Grid & g)
392 {
393 for_each_cell(g.extents(), [&g](const Coord_Vec<2> & c) { g.set(c, g.at(c) + 1); });
394 g.refresh_halo();
395 for_each_cell(g.extents(), [&g](const Coord_Vec<2> & c) { EXPECT_EQ(g.at_safe(c), g.at(c)); });
396 (void) g.at_safe({-1, -1});
397 g.fill(3);
398 }
399};
400
401template <> struct Moved_From_Case<Field_Grid>
402{
403 static Field_Grid make(const size_t n) { return Field_Grid(extents_of(n), std::tuple{1, 2}); }
404 static bool is_empty(const Field_Grid & m)
405 {
406 return m.size() == 0 and m.size(0) == 0 and m.field<0>().size() == 0;
407 }
408 static std::tuple<ca_size_t, ca_size_t, long, long> fingerprint(const Field_Grid & m)
409 {
410 long first = 0;
411 long second = 0;
412 for_each_cell(m.extents(), [&m, &first, &second](const Coord_Vec<2> & c)
413 {
414 first += m.at<0>(c);
415 second += m.at<1>(c);
416 });
417 return {m.size(0), m.size(1), first, second};
418 }
419 static void use(Field_Grid & m)
420 {
421 for_each_cell(m.extents(), [&m](const Coord_Vec<2> & c)
422 {
423 m.set<0>(c, m.at<0>(c) + 1);
424 m.set_cell(c, m.at_cell(c));
425 });
426 m.fill(std::tuple{3, 4});
427 for_each_cell(m.extents(), [&m](const Coord_Vec<2> & c) { EXPECT_EQ(m.at<1>(c), 4); });
428 }
429};
430
431template <> struct Moved_From_Case<Graph_Lattice<int>>
432{
433 static Graph_Lattice<int> make(const size_t n)
434 {
436 }
437 static bool is_empty(const Graph_Lattice<int> & g)
438 {
439 return g.size() == 0 and g.max_degree() == 0;
440 }
441 static std::tuple<size_t, long, size_t> fingerprint(const Graph_Lattice<int> & g)
442 {
443 long sum = 0;
444 size_t degrees = 0;
445 for (size_t i = 0; i < g.size(); ++i)
446 {
447 sum += g.at_node(i);
448 degrees += g.degree(i);
449 }
450 return {g.size(), sum, degrees};
451 }
452 static void use(Graph_Lattice<int> & g)
453 {
454 for (size_t i = 0; i < g.size(); ++i)
455 {
456 g.set_node(i, g.at_node(i) + 1);
457 for (size_t k = 0; k < g.degree(i); ++k)
458 (void) g.at_node(g.neighbours(i)[k]);
459 const Coord_Vec<1> c{static_cast<ca_index_t>(i)};
460 g.set(c, g.at(c));
461 }
462 g.fill(2);
463 (void) g.max_degree();
464 }
465};
466
467template <> struct Moved_From_Case<Life>
468{
469 static Life make(const size_t n)
470 {
471 Life e(life_grid(n), make_game_of_life_rule(), Moore<2, 1>{});
472 e.step();
473 return e;
474 }
475 static bool is_empty(const Life & e) { return e.frame().size() == 0 and e.steps_run() == 0; }
476 static auto fingerprint(const Life & e) { return engine_print(e); }
477 static void use(Life & e) { use_engine(e); }
478};
479
480template <> struct Moved_From_Case<Async_Life>
481{
482 static Async_Life make(const size_t n)
483 {
484 Async_Life e(life_grid(n), make_game_of_life_rule(), Moore<2, 1>{});
485 e.step();
486 return e;
487 }
488 static bool is_empty(const Async_Life & e)
489 {
490 return e.frame().size() == 0 and e.steps_run() == 0 and e.step_count() == 0;
491 }
492 static auto fingerprint(const Async_Life & e) { return engine_print(e); }
493 static void use(Async_Life & e) { use_engine(e); }
494};
495
496template <> struct Moved_From_Case<Parallel_Life>
497{
498 static Parallel_Life make(const size_t n)
499 {
501 cfg.pool = &small_pool();
502 cfg.num_partitions = 2;
503 cfg.min_parallel_cells = 0;
504 Parallel_Life e(life_grid(n), make_game_of_life_rule(), Moore<2, 1>{}, cfg);
505 e.step();
506 return e;
507 }
508 static bool is_empty(const Parallel_Life & e)
509 {
510 return e.frame().size() == 0 and e.steps_run() == 0 and e.config().pool == &small_pool();
511 }
512 static auto fingerprint(const Parallel_Life & e) { return engine_print(e); }
513 static void use(Parallel_Life & e) { use_engine(e); }
514};
515
516template <> struct Moved_From_Case<Field_Life>
517{
518 static Field_Life make(const size_t n)
519 {
520 Two_Fields lat(extents_of(n), std::tuple{0, 7});
521 if (lat.size(1) >= 3)
522 for (ca_index_t j = 0; j < 3; ++j)
523 lat.set<0>({0, j}, 1);
525 Moore<2, 1>{});
526 e.step();
527 return e;
528 }
529 static bool is_empty(const Field_Life & e)
530 {
531 return e.frame().size() == 0 and e.steps_run() == 0;
532 }
533 static std::tuple<size_t, size_t, size_t> fingerprint(const Field_Life & e)
534 {
535 size_t alive = 0;
536 for_each_cell(e.frame().extents(), [&e, &alive](const Coord_Vec<2> & c)
537 {
538 if (e.frame().at<0>(c) != 0)
539 ++alive;
540 });
541 return {e.frame().size(), alive, e.steps_run()};
542 }
543 static void use(Field_Life & e)
544 {
545 const size_t steps = e.steps_run();
546 e.step();
547 EXPECT_EQ(e.steps_run(), steps + 1);
548 for_each_cell(e.frame().extents(), [&e](const Coord_Vec<2> & c)
549 {
550 EXPECT_EQ(e.frame().at<1>(c), 7);
551 });
552 e.run(2);
553 EXPECT_EQ(e.steps_run(), steps + 3);
554 }
555};
556
557template <> struct Moved_From_Case<Graph_Life>
558{
559 static Graph_Life make(const size_t n)
560 {
562 for (size_t i = 0; i < n; i += 3)
563 g.set_node(i, 1);
564 Graph_Life e(std::move(g), make_game_of_life_rule());
565 e.step();
566 return e;
567 }
568 static bool is_empty(const Graph_Life & e)
569 {
570 return e.frame().size() == 0 and e.steps_run() == 0;
571 }
572 static std::tuple<size_t, size_t, size_t> fingerprint(const Graph_Life & e)
573 {
574 size_t alive = 0;
575 for (size_t i = 0; i < e.frame().size(); ++i)
576 if (e.frame().at_node(i) != 0)
577 ++alive;
578 return {e.frame().size(), alive, e.steps_run()};
579 }
580 static void use(Graph_Life & e)
581 {
582 const size_t steps = e.steps_run();
583 e.step();
584 EXPECT_EQ(e.steps_run(), steps + 1);
585 for (size_t i = 0; i < e.frame().size(); ++i)
586 EXPECT_LE(e.frame().at_node(i), 1);
587 e.run(2);
588 EXPECT_EQ(e.steps_run(), steps + 3);
589 }
590};
591
593{
594 static Hashlife_Engine make(const size_t n)
595 {
597 for (size_t i = 0; i < n; ++i)
598 h.set_alive(static_cast<std::int64_t>(i % 40), static_cast<std::int64_t>(i / 40));
599 return h;
600 }
601 static bool is_empty(const Hashlife_Engine & h)
602 {
603 return h.population() == 0 and h.generation() == 0 and h.bbox().is_empty();
604 }
605 static std::pair<std::uint64_t, std::int64_t> fingerprint(const Hashlife_Engine & h)
606 {
607 return {h.population(), h.generation()};
608 }
609 static void use(Hashlife_Engine & h)
610 {
611 h.set_alive(-5, 7);
612 EXPECT_TRUE(h.alive_at(-5, 7));
613 std::uint64_t seen = 0;
614 h.for_each_alive([&seen](std::int64_t, std::int64_t) { ++seen; });
615 EXPECT_EQ(seen, h.population());
616 EXPECT_FALSE(h.save_rle_string().empty());
617 (void) h.run(1);
618 h.clear();
619 EXPECT_EQ(h.population(), 0u);
620 }
621};
622
623template <> struct Moved_From_Case<Locked>
624{
625 static Locked make(const size_t n)
626 {
627 Locked g = sync_slot().lock();
628 *g = static_cast<long>(n);
629 return g;
630 }
631 static bool is_empty(Locked & g) { return g.operator->() == nullptr; }
632 // The value that the guard gives; its operator-> is not const
633 static const long * fingerprint(const Locked & g)
634 {
635 return const_cast<Locked &>(g).operator->();
636 }
637 static void use(Locked & g)
638 {
639 if (long * v = g.operator->())
640 {
641 ++*v;
642 EXPECT_EQ(g.get(), *v);
643 }
644 }
645};
646
647template <> struct Moved_From_Case<Const_Locked>
648{
649 static Const_Locked make(const size_t n)
650 {
651 Synchronized<long> & s = sync_slot();
652 s.with_lock([n](long & v) { v = static_cast<long>(n); });
653 return std::as_const(s).lock();
654 }
655 static bool is_empty(const Const_Locked & g) { return g.operator->() == nullptr; }
656 static const long * fingerprint(const Const_Locked & g) { return g.operator->(); }
657 static void use(Const_Locked & g)
658 {
659 if (const long * v = g.operator->())
660 {
661 EXPECT_EQ(*g, *v);
662 }
663 }
664};
665
666template <> struct Moved_From_Case<Read_Locked>
667{
668 static Read_Locked make(const size_t n)
669 {
670 RwSynchronized<long> & s = rw_slot();
671 s.with_write_lock([n](long & v) { v = static_cast<long>(n); });
672 return s.read();
673 }
674 static bool is_empty(const Read_Locked & g) { return g.operator->() == nullptr; }
675 static const long * fingerprint(const Read_Locked & g) { return g.operator->(); }
676 static void use(Read_Locked & g)
677 {
678 if (const long * v = g.operator->())
679 {
680 EXPECT_EQ(g.get(), *v);
681 }
682 }
683};
684
685template <> struct Moved_From_Case<Write_Locked>
686{
687 static Write_Locked make(const size_t n)
688 {
689 Write_Locked g = rw_slot().write();
690 *g = static_cast<long>(n);
691 return g;
692 }
693 static bool is_empty(Write_Locked & g) { return g.operator->() == nullptr; }
694 // The value that the guard gives; its operator-> is not const
695 static const long * fingerprint(const Write_Locked & g)
696 {
697 return const_cast<Write_Locked &>(g).operator->();
698 }
699 static void use(Write_Locked & g)
700 {
701 if (long * v = g.operator->())
702 {
703 *v += 2;
704 EXPECT_EQ(*g, *v);
705 }
706 }
707};
708
709template <> struct Moved_From_Case<CsvReader>
710{
711 static CsvReader make(const size_t n)
712 {
714 r.read_header();
715 return r;
716 }
717 static bool is_empty(const CsvReader & r)
718 {
719 return not r.has_next() and r.rows_read() == 0 and not r.has_header()
720 and r.header().size() == 0;
721 }
722 // The header of a reader of make() names its file; the rows read say
723 // where the reader is
724 static std::tuple<bool, std::string, size_t> fingerprint(const CsvReader & r)
725 {
726 return {r.has_header(), r.header().size() > 1 ? r.header()[1] : std::string(),
727 r.rows_read()};
728 }
729 static void use(CsvReader & r)
730 {
731 // The header of a reader of make() gives its rows; an empty one has none
732 const size_t expected = r.has_header() ? std::stoul(r.header()[1]) : 0;
733 r.reset();
734 size_t rows = 0;
735 while (r.has_next())
736 {
737 EXPECT_EQ(r.next().size(), 3u);
738 ++rows;
739 }
740 EXPECT_EQ(rows, expected);
741 EXPECT_EQ(r.rows_read(), rows);
742 }
743};
744
745template <> struct Moved_From_Case<Random_Life>
746{
747 static Random_Life make(const size_t n)
748 {
749 Random_Life e(life_grid(n), make_game_of_life_rule(), Moore<2, 1>{},
751 e.step();
752 return e;
753 }
754 static bool is_empty(const Random_Life & e)
755 {
756 return e.frame().size() == 0 and e.steps_run() == 0;
757 }
758 static auto fingerprint(const Random_Life & e) { return engine_print(e); }
759 static void use(Random_Life & e) { use_engine(e); }
760};
761
762template <> struct Moved_From_Case<Tiles>
763{
764 static Tiles make(const size_t n)
765 {
766 Tiles t(tile_extents_of(n), temp_path("tiles"), 4);
767 for_each_tiled_cell(t.extents(), [&t](const ca_size_t r, const ca_size_t c)
768 {
769 t.set(r, c, static_cast<int>((r + c) % 3));
770 });
771 return t;
772 }
773 static bool is_empty(const Tiles & t)
774 {
775 return t.extents()[0] == 0 and t.extents()[1] == 0 and t.tiles_rows() == 0
776 and t.resident() == 0 and t.stats().misses == 0;
777 }
778 // The content is out of reach of a const cache; its activity is not
779 static std::tuple<ca_size_t, ca_size_t, size_t, std::uint64_t, std::uint64_t>
780 fingerprint(const Tiles & t)
781 {
782 return {t.extents()[0], t.extents()[1], t.resident(), t.stats().misses, t.stats().writes};
783 }
784 static void use(Tiles & t)
785 {
786 for_each_tiled_cell(t.extents(), [&t](const ca_size_t r, const ca_size_t c)
787 {
788 const int v = t.at(r, c);
789 t.set(r, c, v + 1);
790 EXPECT_EQ(t.at(r, c), v + 1);
791 });
792 t.flush();
793 EXPECT_LE(t.resident(), t.capacity());
794 }
795};
796
797template <> struct Moved_From_Case<Density>
798{
799 static Density make(const size_t n)
800 {
801 Density o(1);
802 observe_run(o, n);
803 return o;
804 }
805 static bool is_empty(const Density & o) { return o.size() == 0 and o.totals().size() == 0; }
806 static std::tuple<size_t, size_t, size_t> fingerprint(const Density & o)
807 {
808 size_t counts = 0;
809 size_t totals = 0;
810 for (size_t i = 0; i < o.size(); ++i)
811 {
812 counts += o.counts()[i];
813 totals += o.totals()[i];
814 }
815 return {o.size(), counts, totals};
816 }
817 static void use(Density & o)
818 {
819 const size_t before = o.size();
820 observe_run(o, 3);
821 // An observer with no samples records the initial frame of the run too
822 EXPECT_EQ(o.size(), before + 3 + (before == 0 ? 1 : 0));
823 for (size_t i = 0; i < o.size(); ++i)
824 EXPECT_LE(o.density_at(i), 1.0);
825 }
826};
827
828template <> struct Moved_From_Case<Entropy>
829{
830 static Entropy make(const size_t n)
831 {
832 Entropy o;
833 observe_run(o, n);
834 return o;
835 }
836 static bool is_empty(const Entropy & o) { return o.size() == 0; }
837 static std::pair<size_t, double> fingerprint(const Entropy & o)
838 {
839 double sum = 0;
840 for (size_t i = 0; i < o.size(); ++i)
841 sum += o.entropy()[i];
842 return {o.size(), sum};
843 }
844 static void use(Entropy & o)
845 {
846 const size_t before = o.size();
847 observe_run(o, 3);
848 // An observer with no samples records the initial frame of the run too
849 EXPECT_EQ(o.size(), before + 3 + (before == 0 ? 1 : 0));
850 for (size_t i = 0; i < o.size(); ++i)
851 EXPECT_GE(o.entropy()[i], 0.0);
852 }
853};
854
855using Engines = ::testing::Types<Dense_Cell_Storage<int, 2>, Bit_Cell_Storage<2>, Ghost_Grid,
856 Field_Grid, Graph_Lattice<int>, Life, Async_Life, Parallel_Life,
857 Field_Life, Graph_Life, Hashlife_Engine, Locked, Const_Locked,
858 Read_Locked, Write_Locked, CsvReader, Random_Life, Tiles,
859 Density, Entropy>;
861
862// A move assignment exchanges the simulations of two engines, with their
863// steps
864template <class Engine>
866{
867 Engine a = Moved_From_Case<Engine>::make(100); // one step
868 Engine b = Moved_From_Case<Engine>::make(1000);
869 b.run(4);
870 a = std::move(b);
871 EXPECT_EQ(a.steps_run(), 5u);
872 EXPECT_EQ(a.frame().size(), 1000u);
873 EXPECT_EQ(b.steps_run(), 1u);
874 EXPECT_EQ(b.frame().size(), 100u);
875}
876
877TEST(MovedFromEngines, AnAssignmentExchangesTheSteps)
878{
879 expect_exchanged_steps<Life>();
880 expect_exchanged_steps<Async_Life>();
881 expect_exchanged_steps<Random_Life>();
882 expect_exchanged_steps<Parallel_Life>();
883 expect_exchanged_steps<Field_Life>();
884 expect_exchanged_steps<Graph_Life>();
885}
886
887// An engine on an empty lattice, with a scheme that picks a fixed number of
888// cells at random, steps without picking any, as the moved-from one does
889TEST(MovedFromEngines, AnEmptyRandomEngineSteps)
890{
891 Random_Life e(Grid(), make_game_of_life_rule(), Moore<2, 1>{},
893 EXPECT_NO_THROW(e.run(3));
894 EXPECT_EQ(e.steps_run(), 3u);
895 EXPECT_EQ(e.frame().size(), 0u);
896}
897
898// A moved-from cache has no cells: it reads and writes no tile, in no
899// directory
900TEST(MovedFromTileCache, TheMovedFromCacheTouchesNoFile)
901{
902 Tiles src({8, 8}, temp_path("tiles"), 2);
903 src.set(1, 1, 5);
904 Tiles dst(std::move(src));
905 EXPECT_THROW(src.set(5, 5, 7), std::out_of_range);
906 EXPECT_THROW((void) src.at(0, 0), std::out_of_range);
907 src.flush();
908 EXPECT_EQ(src.stats().writes, 0u);
909 EXPECT_EQ(dst.at(1, 1), 5);
910}
911
912// A moved-from engine keeps no hook of the simulation that it gave
913TEST(MovedFromEngines, TheHooksGoWithTheSimulation)
914{
915 size_t fired = 0;
916 Life src(life_grid(100), make_game_of_life_rule(), Moore<2, 1>{});
917 src.on_post_step([&fired](size_t, const Grid &) { ++fired; });
918 Life dst(std::move(src));
919 src.step();
920 EXPECT_EQ(fired, 0u);
921 dst.step();
922 EXPECT_EQ(fired, 1u);
923}
924
925// The lock goes with the moved guard, while another thread writes the value
926// under the lock; the moved-from guard gives no access, and the guard that
927// takes another one by assignment releases its own lock
928TEST(MovedFromGuards, TheLockGoesWithTheGuard)
929{
932 std::thread other([&s]
933 {
934 for (int i = 0; i < 1000; ++i)
935 ++*s.lock();
936 });
937 for (int i = 0; i < 1000; ++i)
938 {
939 Locked g = s.lock();
940 Locked taken = std::move(g);
941 EXPECT_EQ(g.operator->(), nullptr);
942 ++*taken;
943 Locked last = t.lock();
944 last = std::move(taken);
945 EXPECT_EQ(taken.operator->(), nullptr);
946 ++*last;
947 }
948 other.join();
949 EXPECT_EQ(*s.lock(), 3000);
950 EXPECT_EQ(*t.lock(), 0);
951}
952
953// The reader that takes a file reads it also after the moved-from reader is
954// destroyed
955TEST(MovedFromCsvReader, TheFileGoesWithTheReader)
956{
957 auto src = std::make_unique<CsvReader>(write_csv(5));
958 CsvReader dst(std::move(*src));
959 src.reset();
960 ASSERT_TRUE(dst.has_next());
961 EXPECT_EQ(dst.read_header()[1], "5");
962 size_t rows = 0;
963 while (dst.has_next())
964 {
965 EXPECT_EQ(dst.next().size(), 3u);
966 ++rows;
967 }
968 EXPECT_EQ(rows, 5u);
969}
970
971// A reader of a stream that it does not own gives the stream to the reader
972// that takes it, and reads nothing afterwards
973TEST(MovedFromCsvReader, AReaderOfAStreamGivesTheStream)
974{
975 std::istringstream in("a,b\n1,2\n3,4\n");
976 CsvReader src(in);
977 CsvReader dst(std::move(src));
978 EXPECT_FALSE(src.has_next());
979 EXPECT_EQ(dst.read_header().size(), 2u);
980 size_t rows = 0;
981 while (dst.has_next())
982 {
983 EXPECT_EQ(dst.next().size(), 2u);
984 ++rows;
985 }
986 EXPECT_EQ(rows, 2u);
987 src.reset();
988 EXPECT_FALSE(src.has_next());
989}
long double h
Definition btreepic.C:154
size_t steps
Definition ca-c-api.h:126
size_t size_t int32_t * out
Definition ca-c-api.h:120
size_t * rows
Definition ca-c-api.h:112
Phase-7 observability layer for cellular automata engines.
Phase 15 tile-based out-of-core storage for Aleph::CA.
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
constexpr size_t size() const noexcept
Return the number of elements stored in the stack.
Definition tpl_array.H:450
Update-scheme aware engine.
Bit-packed row-major storage for N-dimensional binary CAs.
void fill(const bool value)
Set every cell to value.
const extents_type & extents() const noexcept
Return the full extents array.
ca_size_t size() const noexcept
Row-major dense storage for N-dimensional cellular automata.
ca_size_t size() const noexcept
void fill(const T &value)
Set every cell to value.
view_type view() noexcept
Return a mutable Aleph::mdspan view of this storage.
const extents_type & extents() const noexcept
Records the count of cells in tracked_state per step.
Records the Shannon entropy of the state distribution.
Adaptor: apply a mono-field rule to field I, leave the other fields unchanged.
Lattice with Halo ghost layers around the user-visible cells.
Graph lattice: one cell per node + precomputed adjacency.
std::size_t degree(std::size_t n) const
Degree of node n.
void set(const coord_type &c, const T &v)
ca_size_t size() const noexcept
T at_node(std::size_t n) const
Direct read at node id n.
const Array< std::size_t > & neighbours(std::size_t n) const
Neighbour ids of node n in the order supplied at construction.
void set_node(std::size_t n, const T &v)
Direct write at node id n.
T at(const coord_type &c) const
std::size_t max_degree() const noexcept
Maximum degree across the graph (computed in O(N)).
void fill(const T &value)
Set every cell to value.
Synchronous double-buffered engine for graph CAs.
Hashlife engine for outer-totalistic binary cellular automata.
void set_alive(const std::int64_t x, const std::int64_t y, const bool alive=true)
Set or clear the cell at world coordinates (x, y).
Lattice that adds boundary-aware access on top of a storage.
Moore (Chebyshev) neighborhood of radius R in N dimensions.
Synchronous double-buffered engine for multi-field lattices.
Multi-field lattice with selectable storage layout.
Rule whose next state depends on (current, alive_count).
Definition tpl_ca_rule.H:99
Parallel synchronous double-buffered engine.
Synchronous double-buffered engine.
Out-of-core 2D tile cache with LRU eviction.
Lazy CSV reader for large files.
Definition parse-csv.H:712
Array< std::string > next()
Read the next row as Array.
Definition parse-csv.H:799
void reset()
Reset to beginning (only works for file-based readers).
Definition parse-csv.H:832
Array< std::string > read_header()
Read and store the header row.
Definition parse-csv.H:785
bool has_next() const
Check if more rows are available.
Definition parse-csv.H:793
std::uint32_t next() noexcept
Definition ah-random.H:203
RAII guard for shared (read-only) access.
RAII guard for exclusive (write) access.
Read/write-lock protected shared object wrapper.
ReadLockedPtr read() const
Acquire a shared lock and return a guard.
decltype(auto) with_write_lock(F &&f)
Execute a callback with exclusive (write) access.
RAII guard for read-only access to the synchronized value.
RAII guard for exclusive access to the synchronized value.
Mutex-protected shared object wrapper.
decltype(auto) with_lock(F &&f)
Execute a callback with exclusive access to the value.
LockedPtr lock()
Acquire an exclusive lock and return a guard.
A reusable thread pool for efficient parallel task execution.
Minimal std::expected-style result type for C++20.
constexpr index_type extent(rank_type r) const noexcept
Run-time size of axis r.
Definition ah-mdspan.H:678
The typed suite of the moved-from tests.
Definition moved_from.H:115
constexpr size_t size() const noexcept
Returns the number of entries in the table.
Definition hashDry.H:954
Modern synchronization helpers for channels, shared state, and small producer-consumer queues.
#define TEST(name)
The pattern test of the moved-from objects.
void expect_exchanged_steps()
::testing::Types< Dense_Cell_Storage< int, 2 >, Bit_Cell_Storage< 2 >, Ghost_Grid, Field_Grid, Graph_Lattice< int >, Life, Async_Life, Parallel_Life, Field_Life, Graph_Life, Hashlife_Engine, Locked, Const_Locked, Read_Locked, Write_Locked, CsvReader, Random_Life, Tiles, Density, Entropy > Engines
INSTANTIATE_TYPED_TEST_SUITE_P(Engines, MovedFrom, Engines)
void attach_observer(Engine &engine, Observer &observer)
Plug an observer into an engine's pre/post-step hooks.
constexpr Game_Of_Life_Rule make_game_of_life_rule() noexcept
Build the canonical Game of Life rule.
std::span< const T > Neighbor_View
Read-only view over a contiguous range of neighbour values.
Definition ca-traits.H:90
std::ptrdiff_t ca_index_t
Signed coordinate component used by lattices and neighborhoods.
Definition ca-traits.H:60
std::array< ca_index_t, N > Coord_Vec
Default coordinate vector.
Definition ca-traits.H:69
void for_each_cell(const Lattice &lat, F &&f)
Visit every cell of a lattice in canonical row-major order.
Definition ca-metrics.H:133
Array< Array< std::size_t > > make_path_graph_adjacency(std::size_t n, bool cycle=false)
Build the adjacency of a path graph with n nodes.
void write_csv(std::ostream &out, const Lattice &frame, const CSV_Options &opts={})
Write a numeric CSV snapshot.
Definition ca-io.H:1276
std::size_t ca_size_t
Unsigned size component used for extents and counts.
Definition ca-traits.H:63
Main namespace for Aleph-w library functions.
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
and
Check uniqueness with explicit hash + equality functors.
void next()
Advance all underlying iterators (bounds-checked).
Definition ah-zip.H:236
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
Comprehensive CSV (Comma-Separated Values) parsing and manipulation utilities.
Configuration for Parallel_Synchronous_Engine.
std::size_t num_partitions
Number of partitions per step.
ThreadPool * pool
Thread pool to schedule on. nullptr means Aleph::default_pool().
std::size_t min_parallel_cells
Workloads with fewer cells than this are executed sequentially without touching the pool.
Pick one cell at random per sub-step, update it in place.
The lattice wraps around on every axis.
Definition ca-traits.H:124
static Async_Life make(const size_t n)
static auto fingerprint(const Async_Life &e)
static bool is_empty(const Async_Life &e)
static bool is_empty(const Bit_Cell_Storage< 2 > &s)
static Bit_Cell_Storage< 2 > make(const size_t n)
static void use(Bit_Cell_Storage< 2 > &s)
static std::tuple< ca_size_t, ca_size_t, size_t > fingerprint(const Bit_Cell_Storage< 2 > &s)
static Const_Locked make(const size_t n)
static const long * fingerprint(const Const_Locked &g)
static bool is_empty(const Const_Locked &g)
static CsvReader make(const size_t n)
static std::tuple< bool, std::string, size_t > fingerprint(const CsvReader &r)
static bool is_empty(const CsvReader &r)
static bool is_empty(const Dense_Cell_Storage< int, 2 > &s)
static void use(Dense_Cell_Storage< int, 2 > &s)
static std::tuple< ca_size_t, ca_size_t, long > fingerprint(const Dense_Cell_Storage< int, 2 > &s)
static Dense_Cell_Storage< int, 2 > make(const size_t n)
static Density make(const size_t n)
static std::tuple< size_t, size_t, size_t > fingerprint(const Density &o)
static bool is_empty(const Density &o)
static std::pair< size_t, double > fingerprint(const Entropy &o)
static Entropy make(const size_t n)
static bool is_empty(const Entropy &o)
static std::tuple< ca_size_t, ca_size_t, long, long > fingerprint(const Field_Grid &m)
static bool is_empty(const Field_Grid &m)
static Field_Grid make(const size_t n)
static Field_Life make(const size_t n)
static bool is_empty(const Field_Life &e)
static std::tuple< size_t, size_t, size_t > fingerprint(const Field_Life &e)
static bool is_empty(const Ghost_Grid &g)
static Ghost_Grid make(const size_t n)
static std::tuple< ca_size_t, ca_size_t, long > fingerprint(const Ghost_Grid &g)
static Graph_Lattice< int > make(const size_t n)
static std::tuple< size_t, long, size_t > fingerprint(const Graph_Lattice< int > &g)
static bool is_empty(const Graph_Lattice< int > &g)
static void use(Graph_Lattice< int > &g)
static Graph_Life make(const size_t n)
static std::tuple< size_t, size_t, size_t > fingerprint(const Graph_Life &e)
static bool is_empty(const Graph_Life &e)
static Hashlife_Engine make(const size_t n)
static std::pair< std::uint64_t, std::int64_t > fingerprint(const Hashlife_Engine &h)
static bool is_empty(const Hashlife_Engine &h)
static void use(Hashlife_Engine &h)
static auto fingerprint(const Life &e)
static bool is_empty(const Life &e)
static Life make(const size_t n)
static const long * fingerprint(const Locked &g)
static Locked make(const size_t n)
static Parallel_Life make(const size_t n)
static bool is_empty(const Parallel_Life &e)
static auto fingerprint(const Parallel_Life &e)
static bool is_empty(const Random_Life &e)
static Random_Life make(const size_t n)
static auto fingerprint(const Random_Life &e)
static Read_Locked make(const size_t n)
static const long * fingerprint(const Read_Locked &g)
static bool is_empty(const Read_Locked &g)
static bool is_empty(const Tiles &t)
static std::tuple< ca_size_t, ca_size_t, size_t, std::uint64_t, std::uint64_t > fingerprint(const Tiles &t)
static Tiles make(const size_t n)
static bool is_empty(Write_Locked &g)
static const long * fingerprint(const Write_Locked &g)
static Write_Locked make(const size_t n)
How the moved-from tests build, check and use objects of a class.
Definition moved_from.H:92
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
static int * k
Gsl_Compatible_Rng r
A modern, efficient thread pool for parallel task execution.
Phase 13 update-scheme aware engine.
Bit-packed dense storage for boolean cellular automata.
Synchronous double-buffered engine for cellular automata.
Ghost-layer lattice for high-performance boundary handling.
CA whose underlying topology is an arbitrary undirected graph.
Hashlife engine for outer-totalistic binary cellular automata.
Cellular automata lattice with pluggable boundary policies.
Phase 14 synchronous double-buffered engine for multi-field cellular automata.
Phase 14 multi-field cellular automata lattice (AoS / SoA).
Phase 14 multi-field local rules for Aleph::CA.
Neighborhoods catalogue for Aleph::CA.
Parallel synchronous engine for cellular automata (Phase 5).
Rule mechanisms for Aleph::CA.
Dense, contiguous storage for cellular automata cells (1D/2D/3D).