Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
tpl_ca_graph_automaton.H
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 version 2.0.0b
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
73#ifndef TPL_CA_GRAPH_AUTOMATON_H
74#define TPL_CA_GRAPH_AUTOMATON_H
75
76#include <array>
77#include <cstddef>
78#include <functional>
79#include <span>
80#include <type_traits>
81#include <utility>
82
83#include <ah-errors.H>
84#include <tpl_array.H>
85
86#include <ca-traits.H>
87#include <tpl_ca_concepts.H>
88
89namespace Aleph {
90namespace CA {
91
106template <typename T>
108{
109 static_assert(CellState<T>, "Graph_Lattice requires a CellState type");
110
111public:
112 using state_type = T;
114 using extents_type = std::array<ca_size_t, 1>;
115
117 static constexpr std::size_t rank = 1;
118
119private:
123
124public:
126 Graph_Lattice() = default;
127
139 explicit Graph_Lattice(const Array<Array<std::size_t>> &adjacency,
140 const T &init = T{})
141 : num_nodes_(static_cast<ca_size_t>(adjacency.size()))
143 , adjacency_(num_nodes_, Array<std::size_t>{})
144 {
145 for (ca_size_t i = 0; i < num_nodes_; ++i)
146 {
147 const auto &row = adjacency[i];
148 Array<std::size_t> r(row.size(), std::size_t{0});
149 for (std::size_t k = 0; k < row.size(); ++k)
150 {
152 << "Graph_Lattice: neighbour id " << row[k] << " of node " << i
153 << " is out of range [0, " << num_nodes_ << ")";
154 r[k] = row[k];
155 }
156 adjacency_[i] = std::move(r);
157 }
158 }
159
163 Graph_Lattice(const Graph_Lattice &other) = default;
164
174 Graph_Lattice(Graph_Lattice &&other) noexcept
175 : num_nodes_(std::exchange(other.num_nodes_, 0)), cells_(std::move(other.cells_)),
176 adjacency_(std::move(other.adjacency_))
177 {}
178
184 Graph_Lattice &operator=(const Graph_Lattice &other) = default;
185
192 {
193 swap(other);
194 return *this;
195 }
196
197 // -------------------------------------------------------------
198 // LatticeLike surface.
199 // -------------------------------------------------------------
200
201 [[nodiscard]] static constexpr std::size_t dimension() noexcept { return rank; }
202
203 [[nodiscard]] ca_size_t size() const noexcept { return num_nodes_; }
204
205 [[nodiscard]] ca_size_t size(std::size_t d) const
206 {
208 << "Graph_Lattice::size: axis " << d << " out of range";
209 return num_nodes_;
210 }
211
212 [[nodiscard]] extents_type extents() const noexcept
213 {
214 return extents_type{num_nodes_};
215 }
216
217 [[nodiscard]] T at(const coord_type &c) const
218 {
219 ah_out_of_range_error_if(c[0] < 0 or static_cast<ca_size_t>(c[0]) >= num_nodes_)
220 << "Graph_Lattice::at: id " << c[0] << " out of [0, " << num_nodes_ << ")";
221 return cells_[static_cast<ca_size_t>(c[0])];
222 }
223
224 void set(const coord_type &c, const T &v)
225 {
226 ah_out_of_range_error_if(c[0] < 0 or static_cast<ca_size_t>(c[0]) >= num_nodes_)
227 << "Graph_Lattice::set: id " << c[0] << " out of [0, " << num_nodes_ << ")";
228 cells_[static_cast<ca_size_t>(c[0])] = v;
229 }
230
234 [[nodiscard]] T at_safe(const coord_type &c) const
235 {
236 if (c[0] < 0 or static_cast<ca_size_t>(c[0]) >= num_nodes_)
237 return T{};
238 return cells_[static_cast<ca_size_t>(c[0])];
239 }
240
241 // -------------------------------------------------------------
242 // Graph-specific accessors.
243 // -------------------------------------------------------------
244
246 [[nodiscard]] T at_node(std::size_t n) const
247 {
249 << "Graph_Lattice::at_node: id " << n << " out of [0, " << num_nodes_ << ")";
250 return cells_[n];
251 }
252
254 void set_node(std::size_t n, const T &v)
255 {
257 << "Graph_Lattice::set_node: id " << n << " out of [0, " << num_nodes_ << ")";
258 cells_[n] = v;
259 }
260
262 [[nodiscard]] std::size_t degree(std::size_t n) const
263 {
265 << "Graph_Lattice::degree: id " << n << " out of [0, " << num_nodes_ << ")";
266 return adjacency_[n].size();
267 }
268
270 [[nodiscard]] const Array<std::size_t> &neighbours(std::size_t n) const
271 {
273 << "Graph_Lattice::neighbours: id " << n << " out of [0, " << num_nodes_ << ")";
274 return adjacency_[n];
275 }
276
278 [[nodiscard]] std::size_t max_degree() const noexcept
279 {
280 std::size_t m = 0;
281 for (ca_size_t i = 0; i < num_nodes_; ++i)
282 if (adjacency_[i].size() > m)
283 m = adjacency_[i].size();
284 return m;
285 }
286
288 void fill(const T &value)
289 {
290 for (ca_size_t i = 0; i < num_nodes_; ++i)
291 cells_[i] = value;
292 }
293
295 void swap(Graph_Lattice &other) noexcept
296 {
297 using std::swap;
298 swap(num_nodes_, other.num_nodes_);
299 cells_.swap(other.cells_);
300 adjacency_.swap(other.adjacency_);
301 }
302};
303
305template <typename T>
306inline void swap(Graph_Lattice<T> &a, Graph_Lattice<T> &b) noexcept
307{
308 a.swap(b);
309}
310
311// -----------------------------------------------------------------------
312// Synchronous engine for graph CAs.
313// -----------------------------------------------------------------------
314
330template <typename R, typename T>
332and (requires(const R &r, const T &s, Neighbor_View<T> v) {
333 { r(s, v) } -> std::convertible_to<T>;
334 }
335 or requires(const R &r, const T &s, Neighbor_View<T> v,
336 const Cell_Context<1> &ctx) {
337 { r(s, v, ctx) } -> std::convertible_to<T>;
338 });
339
357template <typename Lattice, typename Rule>
359{
360public:
363
364private:
366 "Graph_Synchronous_Engine requires a GraphRuleLike rule");
367
370 Rule rule_;
372 std::function<void(std::size_t, const Lattice &)> pre_hook_;
373 std::function<void(std::size_t, const Lattice &)> post_hook_;
374 std::size_t step_count_ = 0;
375
376public:
388 : cur_buf_(std::move(initial)), nxt_buf_(cur_buf_), rule_(std::move(r))
389 {
390 nbuf_.reserve(cur_buf_.max_degree());
391 }
392
398
409 std::is_nothrow_move_constructible_v<Lattice> and std::is_nothrow_move_constructible_v<Rule>)
410 : cur_buf_(std::move(other.cur_buf_)), nxt_buf_(std::move(other.nxt_buf_)),
411 rule_(std::move(other.rule_)), nbuf_(std::move(other.nbuf_)),
412 pre_hook_(std::exchange(other.pre_hook_, nullptr)),
413 post_hook_(std::exchange(other.post_hook_, nullptr)),
414 step_count_(std::exchange(other.step_count_, 0))
415 {}
416
423
430 noexcept(swap(other)))
431 requires std::swappable<Rule>
432 {
433 swap(other);
434 return *this;
435 }
436
448 void swap(Graph_Synchronous_Engine &other) noexcept(
449 noexcept(cur_buf_.swap(other.cur_buf_)) and std::is_nothrow_swappable_v<Rule>)
450 requires std::swappable<Rule>
451 {
452 // The swap of Rule that the specification evaluates: found by its
453 // arguments, else std::swap(). When it or that of a lattice may throw,
454 // the rules go first, and all go in a sequence that is all or none: one
455 // that throws leaves no lattice with the rule of the other. When none
456 // may, the order cannot be seen, and the rules go after the lattices,
457 // as they always did: a rule with members, even Game_Of_Life_Rule,
458 // would reorder the code if it went first
459 using std::swap;
460 if constexpr (not std::is_nothrow_swappable_v<Rule> or not noexcept(cur_buf_.swap(other.cur_buf_)))
461 swap_all_or_none(other);
462 else
463 {
464 cur_buf_.swap(other.cur_buf_);
465 nxt_buf_.swap(other.nxt_buf_);
466 swap(rule_, other.rule_);
467 }
468 nbuf_.swap(other.nbuf_);
469 pre_hook_.swap(other.pre_hook_);
470 post_hook_.swap(other.post_hook_);
471 swap(step_count_, other.step_count_);
472 }
473
474private:
475 // The rules and the lattices, with the swap of Rule that the
476 // specification of swap() evaluates, all or none: if one throws, those
477 // before it are exchanged back
479 {
480 using std::swap;
481 int done = 0;
482 try
483 {
484 swap(rule_, other.rule_);
485 ++done;
486 cur_buf_.swap(other.cur_buf_);
487 ++done;
488 nxt_buf_.swap(other.nxt_buf_);
489 }
490 catch (...)
491 {
492 if (done > 1)
493 cur_buf_.swap(other.cur_buf_);
494 if (done > 0)
495 swap(rule_, other.rule_);
496 throw;
497 }
498 }
499
500public:
502 [[nodiscard]] const Lattice &frame() const noexcept { return cur_buf_; }
503
505 [[nodiscard]] std::size_t steps_run() const noexcept { return step_count_; }
506
508 template <typename F>
509 void on_pre_step(F &&f)
510 {
511 pre_hook_ = std::forward<F>(f);
512 }
513
515 template <typename F>
516 void on_post_step(F &&f)
517 {
518 post_hook_ = std::forward<F>(f);
519 }
520
528 void step()
529 {
530 if (pre_hook_)
532
533 const ca_size_t n = cur_buf_.size();
534 for (ca_size_t node = 0; node < n; ++node)
535 {
536 const auto &neigh_ids = cur_buf_.neighbours(node);
537 const std::size_t deg = neigh_ids.size();
538 // Aleph::Array has no `resize(n)`; grow by appending value-
539 // initialised cells until capacity is reached. Size only
540 // grows monotonically (max_degree is bounded), so this is
541 // amortised O(1) per node.
542 while (nbuf_.size() < deg)
544
545 for (std::size_t k = 0; k < deg; ++k)
546 nbuf_[k] = cur_buf_.at_node(neigh_ids[k]);
547
548 const state_type *const view_ptr = deg > 0 ? &nbuf_[0] : nullptr;
549 const Neighbor_View<state_type> view(view_ptr, deg);
550 const Cell_Context<1> ctx{step_count_, {static_cast<ca_index_t>(node)}};
551 nxt_buf_.set_node(node,
552 apply_rule(rule_, cur_buf_.at_node(node), view, ctx));
553 }
554
556 ++step_count_;
557
558 if (post_hook_)
560 }
561
565 void run(const std::size_t steps)
566 {
567 for (std::size_t i = 0; i < steps; ++i)
568 step();
569 }
570};
571
572// -----------------------------------------------------------------------
573// Graph builders for common test patterns.
574// -----------------------------------------------------------------------
575
591 std::size_t rows, std::size_t cols, bool periodic = false)
592{
594 auto idx = [cols](std::size_t i, std::size_t j) { return i * cols + j; };
595 for (std::size_t i = 0; i < rows; ++i)
596 for (std::size_t j = 0; j < cols; ++j)
597 {
598 auto &row = adj[idx(i, j)];
599 // North
600 if (i > 0)
601 row.append(idx(i - 1, j));
602 else if (periodic)
603 row.append(idx(rows - 1, j));
604 // South
605 if (i + 1 < rows)
606 row.append(idx(i + 1, j));
607 else if (periodic)
608 row.append(idx(0, j));
609 // West
610 if (j > 0)
611 row.append(idx(i, j - 1));
612 else if (periodic)
613 row.append(idx(i, cols - 1));
614 // East
615 if (j + 1 < cols)
616 row.append(idx(i, j + 1));
617 else if (periodic)
618 row.append(idx(i, 0));
619 }
620 return adj;
621}
622
634 std::size_t n, bool cycle = false)
635{
637 for (std::size_t i = 0; i < n; ++i)
638 {
639 if (i > 0)
640 adj[i].append(i - 1);
641 else if (cycle and n > 1)
642 adj[i].append(n - 1);
643 if (i + 1 < n)
644 adj[i].append(i + 1);
645 else if (cycle and n > 1)
646 adj[i].append(0);
647 }
648 return adj;
649}
650
651} // namespace CA
652} // namespace Aleph
653
654#endif // TPL_CA_GRAPH_AUTOMATON_H
Exception handling system with formatted messages for Aleph-w.
#define ah_out_of_range_error_if(C)
Throws std::out_of_range if condition holds.
Definition ah-errors.H:727
size_t steps
Definition ca-c-api.h:126
size_t size_t int32_t value
Definition ca-c-api.h:116
size_t row
Definition ca-c-api.h:115
size_t * rows
Definition ca-c-api.h:112
size_t cols
Definition ca-c-api.h:105
Common typedefs and tag types for the Cellular Automata module.
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
void swap(Array &s) noexcept
Swap this with s
Definition tpl_array.H:313
T & append(const T &data)
Append a copy of data
Definition tpl_array.H:331
void reserve(size_t cap)
Reserves cap cells into the array.
Definition tpl_array.H:402
Graph lattice: one cell per node + precomputed adjacency.
Graph_Lattice & operator=(Graph_Lattice &&other) noexcept
Exchange this lattice with another, which is left with the previous nodes of this one.
std::size_t degree(std::size_t n) const
Degree of node n.
Graph_Lattice()=default
Construct an empty graph lattice (0 nodes).
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.
ca_size_t size(std::size_t d) const
extents_type extents() const noexcept
Graph_Lattice(const Array< Array< std::size_t > > &adjacency, const T &init=T{})
Build a graph lattice from an adjacency list.
void set_node(std::size_t n, const T &v)
Direct write at node id n.
std::array< ca_size_t, 1 > extents_type
T at(const coord_type &c) const
static constexpr std::size_t dimension() noexcept
void swap(Graph_Lattice &other) noexcept
O(1) swap with another graph lattice of the same type.
static constexpr std::size_t rank
Rank-1 lattice: node id is the only axis.
std::size_t max_degree() const noexcept
Maximum degree across the graph (computed in O(N)).
T at_safe(const coord_type &c) const
Boundary-aware read.
void fill(const T &value)
Set every cell to value.
Graph_Lattice(Graph_Lattice &&other) noexcept
Take the cells and the adjacency of another lattice, which is left with no nodes.
Graph_Lattice(const Graph_Lattice &other)=default
Copy another lattice: its cells and its adjacency.
Array< Array< std::size_t > > adjacency_
Graph_Lattice & operator=(const Graph_Lattice &other)=default
Copy another lattice into this one: its cells and its adjacency.
Synchronous double-buffered engine for graph CAs.
Graph_Synchronous_Engine(Graph_Synchronous_Engine &&other) noexcept(std::is_nothrow_move_constructible_v< Lattice > and std::is_nothrow_move_constructible_v< Rule >)
Take the simulation of another engine, which is left with empty lattices, no hooks and no steps run.
void step()
Apply the rule to every node once and swap buffers.
Array< state_type > nbuf_
Aleph::Array reused across cells.
void on_post_step(F &&f)
Register a hook fired after every step().
void run(const std::size_t steps)
Run several synchronous steps.
void swap_all_or_none(Graph_Synchronous_Engine &other)
Graph_Synchronous_Engine(Lattice initial, Rule r)
Build an engine on top of an existing graph lattice.
Graph_Synchronous_Engine(const Graph_Synchronous_Engine &other)=default
Copy another engine: its lattices, its rule, its hooks and its count of steps.
std::function< void(std::size_t, const Lattice &)> pre_hook_
Graph_Synchronous_Engine & operator=(Graph_Synchronous_Engine &&other) noexcept(noexcept(swap(other)))
Exchange this engine with another, which is left with the previous simulation of this one.
void swap(Graph_Synchronous_Engine &other) noexcept(noexcept(cur_buf_.swap(other.cur_buf_)) and std::is_nothrow_swappable_v< Rule >)
Exchange in O(1) the simulation of this engine and another.
const Lattice & frame() const noexcept
Graph_Synchronous_Engine & operator=(const Graph_Synchronous_Engine &other)=default
Copy another engine into this one: its lattices, its rule, its hooks and its count of steps.
void on_pre_step(F &&f)
Register a hook fired before every step().
typename Lattice::state_type state_type
std::function< void(std::size_t, const Lattice &)> post_hook_
Lattice that adds boundary-aware access on top of a storage.
typename Storage::state_type state_type
void swap(Lattice &other) noexcept(noexcept(store_.swap(other.store_)))
O(1) swap.
ca_size_t size() const noexcept
constexpr size_t size() const noexcept
Returns the number of entries in the table.
Definition hashDry.H:954
A type usable as the value stored inside a cell.
Concept satisfied by graph rules.
@ R
Recovered (and immune).
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
Array< Array< std::size_t > > make_grid_graph_adjacency(std::size_t rows, std::size_t cols, bool periodic=false)
Build the adjacency of a 2D 4-neighbour grid graph.
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 swap(Bit_Cell_Storage< N > &a, Bit_Cell_Storage< N > &b) noexcept
Free-function swap so the storage plays nicely with std::swap.
std::size_t ca_size_t
Unsigned size component used for extents and counts.
Definition ca-traits.H:63
State apply_rule(const Rule &r, const State &s, Neighbor_View< State > v, const Cell_Context< Rank > &ctx)
Invoke a rule, optionally forwarding the per-cell context.
Main namespace for Aleph-w library functions.
std::decay_t< typename HeadC::Item_Type > T
Definition ah-zip.H:152
and
Check uniqueness with explicit hash + equality functors.
static std::atomic< bool > init
Definition hash-fct.C:54
STL namespace.
Per-cell context handed to rules that need to know "where" and "when" they are firing.
Definition ca-traits.H:106
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
static int * k
Gsl_Compatible_Rng r
Dynamic array container with automatic resizing.
C++20 concepts for the Cellular Automata module.