Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
tpl_ca_engine.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
55#ifndef TPL_CA_ENGINE_H
56#define TPL_CA_ENGINE_H
57
58#include <array>
59#include <concepts>
60#include <cstddef>
61#include <functional>
62#include <span>
63#include <type_traits>
64#include <utility>
65
66#include <ca-traits.H>
67#include <tpl_ca_concepts.H>
68#include <tpl_ca_neighborhood.H>
69
70namespace Aleph {
71namespace CA {
72
73namespace ca_engine_detail {
75template <typename O>
76struct is_tile : std::false_type
77{
78};
79
80template <std::size_t W, std::size_t H>
81struct is_tile<Tile<W, H>> : std::true_type
82{
83};
84
85template <typename O>
86inline constexpr bool is_tile_v = is_tile<O>::value;
87
89template <typename Coord, typename F>
90inline void iterate_1d(ca_size_t n0, F &&f)
91{
92 Coord c{};
93 for (ca_index_t i = 0; i < static_cast<ca_index_t>(n0); ++i)
94 {
95 c[0] = i;
96 f(c);
97 }
98}
99
101template <typename Coord, typename F>
103{
104 Coord c{};
105 for (ca_index_t i = 0; i < static_cast<ca_index_t>(n0); ++i)
106 for (ca_index_t j = 0; j < static_cast<ca_index_t>(n1); ++j)
107 {
108 c[0] = i;
109 c[1] = j;
110 f(c);
111 }
112}
113
115template <typename Coord, typename F>
117{
118 Coord c{};
119 for (ca_index_t j = 0; j < static_cast<ca_index_t>(n1); ++j)
120 for (ca_index_t i = 0; i < static_cast<ca_index_t>(n0); ++i)
121 {
122 c[0] = i;
123 c[1] = j;
124 f(c);
125 }
126}
127
130template <std::size_t W, std::size_t H, typename Coord, typename F>
131inline void iterate_2d_tile(const ca_size_t n0, const ca_size_t n1, F &&f)
132{
133 Coord c{};
134 for (ca_size_t ti = 0; ti < n0; ti += H)
135 for (ca_size_t tj = 0; tj < n1; tj += W)
136 {
137 const ca_size_t i_end = ti + H < n0 ? ti + H : n0;
138 const ca_size_t j_end = tj + W < n1 ? tj + W : n1;
139 for (ca_size_t i = ti; i < i_end; ++i)
140 for (ca_size_t j = tj; j < j_end; ++j)
141 {
142 c[0] = static_cast<ca_index_t>(i);
143 c[1] = static_cast<ca_index_t>(j);
144 f(c);
145 }
146 }
147}
148
150template <typename Coord, typename F>
151inline void iterate_3d_row_major(const ca_size_t n0, const ca_size_t n1, const ca_size_t n2, F &&f)
152{
153 Coord c{};
154 for (ca_index_t i = 0; i < static_cast<ca_index_t>(n0); ++i)
155 for (ca_index_t j = 0; j < static_cast<ca_index_t>(n1); ++j)
156 for (ca_index_t k = 0; k < static_cast<ca_index_t>(n2); ++k)
157 {
158 c[0] = i;
159 c[1] = j;
160 c[2] = k;
161 f(c);
162 }
163}
164} // namespace ca_engine_detail
165
182template <typename Lattice, typename Rule, typename Neighborhood, typename Order = RowMajor>
184{
185 static_assert(LatticeLike<Lattice>, "Synchronous_Engine requires a LatticeLike lattice");
186 static_assert(NeighborhoodLike<Neighborhood>,
187 "Synchronous_Engine requires a NeighborhoodLike neighborhood");
188 static_assert(RuleLike<Rule, Lattice>, "Synchronous_Engine requires a RuleLike rule");
189 static_assert(Neighborhood::rank_v == Lattice::rank, "Neighborhood rank must match lattice rank");
190
191public:
195 using rule_type = Rule;
197 using neighborhood_type = Neighborhood;
199 using order_type = Order;
200
207
209 static constexpr std::size_t rank = Lattice::rank;
211 static constexpr std::size_t neighbour_count = Neighborhood::size_v;
212
214 using hook_type = std::function<void(std::size_t, const Lattice &)>;
215
216private:
219 Rule rule_;
220 Neighborhood nh_;
223 std::size_t step_count_ = 0;
224
225public:
240 Synchronous_Engine(Lattice initial, Rule r, Neighborhood n)
241 : cur_buf_(std::move(initial)), nxt_buf_(cur_buf_.extents()), rule_(std::move(r)), nh_(std::move(n))
242 {}
243
258 requires std::default_initializable<Neighborhood>
259 : Synchronous_Engine(std::move(initial), std::move(r), Neighborhood{})
260 {}
261
266 Synchronous_Engine(const Synchronous_Engine &other) = default;
267
278 std::is_nothrow_move_constructible_v<Lattice> and std::is_nothrow_move_constructible_v<Rule>
279 and std::is_nothrow_move_constructible_v<Neighborhood>)
280 : cur_buf_(std::move(other.cur_buf_)), nxt_buf_(std::move(other.nxt_buf_)),
281 rule_(std::move(other.rule_)), nh_(std::move(other.nh_)),
282 pre_hook_(std::exchange(other.pre_hook_, nullptr)),
283 post_hook_(std::exchange(other.post_hook_, nullptr)),
284 step_count_(std::exchange(other.step_count_, 0))
285 {}
286
293
299 Synchronous_Engine &operator=(Synchronous_Engine &&other) noexcept(noexcept(swap(other)))
300 requires (std::swappable<Rule> and std::swappable<Neighborhood>)
301 {
302 swap(other);
303 return *this;
304 }
305
318 void swap(Synchronous_Engine &other) noexcept(
319 noexcept(cur_buf_.swap(other.cur_buf_)) and std::is_nothrow_swappable_v<Rule>
320 and std::is_nothrow_swappable_v<Neighborhood>)
321 requires (std::swappable<Rule> and std::swappable<Neighborhood>)
322 {
323 // When a swap may throw, that of a rule, a neighborhood or a lattice,
324 // the rules and the neighborhoods go first, and all go in a sequence
325 // that is all or none: one that throws leaves no lattice with the rule
326 // of the other. When none may, the order cannot be seen, and the rules
327 // and the neighborhoods go after the lattices, as they always did: a
328 // rule with members, even Game_Of_Life_Rule, would reorder the code if
329 // it went first
330 constexpr bool may_throw =
331 not std::is_nothrow_swappable_v<Rule> or not std::is_nothrow_swappable_v<Neighborhood>
332 or not noexcept(cur_buf_.swap(other.cur_buf_));
333 using std::swap;
334 if constexpr (may_throw)
335 swap_all_or_none(other);
336 else
337 {
338 cur_buf_.swap(other.cur_buf_);
339 nxt_buf_.swap(other.nxt_buf_);
340 swap(rule_, other.rule_);
341 swap(nh_, other.nh_);
342 }
343 pre_hook_.swap(other.pre_hook_);
344 post_hook_.swap(other.post_hook_);
345 swap(step_count_, other.step_count_);
346 }
347
348private:
349 // The rules, the neighborhoods and the lattices, with the swaps that the
350 // specification of swap() evaluates (found by their arguments, else
351 // std::swap()), all or none: if one throws, those before it are
352 // exchanged back
354 {
355 using std::swap;
356 int done = 0;
357 try
358 {
359 swap(rule_, other.rule_);
360 ++done;
361 swap(nh_, other.nh_);
362 ++done;
363 cur_buf_.swap(other.cur_buf_);
364 ++done;
365 nxt_buf_.swap(other.nxt_buf_);
366 }
367 catch (...)
368 {
369 if (done > 2)
370 cur_buf_.swap(other.cur_buf_);
371 if (done > 1)
372 swap(nh_, other.nh_);
373 if (done > 0)
374 swap(rule_, other.rule_);
375 throw;
376 }
377 }
378
379public:
380
385 [[nodiscard]] const Lattice &frame() const noexcept
386 {
387 return cur_buf_;
388 }
389
394 [[nodiscard]] std::size_t steps_run() const noexcept
395 {
396 return step_count_;
397 }
398
403 [[nodiscard]] const extents_type &extents() const noexcept
404 {
405 return cur_buf_.extents();
406 }
407
411 [[nodiscard]] const Rule &rule() const noexcept
412 {
413 return rule_;
414 }
415
420 [[nodiscard]] Rule &rule() noexcept
421 {
422 return rule_;
423 }
424
433 [[nodiscard]] Lattice &write_lattice() noexcept
434 {
435 return cur_buf_;
436 }
437
445 void set_step_count(const std::size_t s) noexcept
446 {
447 step_count_ = s;
448 }
449
454 template <typename F>
455 void on_pre_step(F &&f)
456 {
457 pre_hook_ = std::forward<F>(f);
458 }
459
465 template <typename F>
466 void on_post_step(F &&f)
467 {
468 post_hook_ = std::forward<F>(f);
469 }
470
482 void step()
483 {
484 using namespace ca_engine_detail;
485
486 // Refresh the ghost layer, if the lattice has one. This is what
487 // allows Phase 4 lattices to keep the boundary logic out of the
488 // inner loop: by the time `gather_neighbors` runs, every cell
489 // inside the halo already carries the correct policy value.
490 if constexpr (HasRefreshHalo<Lattice>)
491 cur_buf_.refresh_halo();
492
493 if (pre_hook_)
495
496 // Stack buffer for the gathered neighbour values. Size is fixed
497 // by the neighbourhood at compile time, so no heap involvement.
498 std::array<state_type, neighbour_count> nbuf{};
499
500 auto compute_one = [&](const coord_type &c)
501 {
502 const std::size_t neigh_sz = std::min(nh_.size(), nbuf.size());
503 gather_neighbors(nh_, cur_buf_, c, std::span<state_type>(nbuf.data(), neigh_sz));
504 const Cell_Context<rank> ctx{step_count_, c};
505 nxt_buf_.set(c,
507 cur_buf_.at(c),
508 Neighbor_View<state_type>(nbuf.data(), neigh_sz),
509 ctx));
510 };
511
512 if constexpr (rank == 1)
513 {
514 iterate_1d<coord_type>(cur_buf_.size(0), compute_one);
515 }
516 else if constexpr (rank == 2)
517 {
518 if constexpr (is_tile_v<Order>)
519 iterate_2d_tile<Order::width, Order::height, coord_type>(cur_buf_.size(0),
520 cur_buf_.size(1),
521 compute_one);
522 else if constexpr (std::is_same_v<Order, ColumnMajor>)
523 iterate_2d_column_major<coord_type>(cur_buf_.size(0), cur_buf_.size(1), compute_one);
524 else
525 iterate_2d_row_major<coord_type>(cur_buf_.size(0), cur_buf_.size(1), compute_one);
526 }
527 else if constexpr (rank == 3)
528 {
529 iterate_3d_row_major<coord_type>(cur_buf_.size(0), cur_buf_.size(1), cur_buf_.size(2), compute_one);
530 }
531 else
532 static_assert(rank <= 3, "Synchronous_Engine currently supports rank <= 3");
533
535 ++step_count_;
536
537 if (post_hook_)
539 }
540
551 void run(const std::size_t steps)
552 {
553 for (std::size_t i = 0; i < steps; ++i)
554 step();
555 }
556};
557
558} // namespace CA
559} // namespace Aleph
560
561#endif // TPL_CA_ENGINE_H
size_t steps
Definition ca-c-api.h:126
Common typedefs and tag types for the Cellular Automata module.
Lattice that adds boundary-aware access on top of a storage.
void set(const coord_type &c, const state_type &v)
Strict write: throws if c is out of range.
typename Storage::state_type state_type
typename Storage::extents_type extents_type
const extents_type & extents() const noexcept
void swap(Lattice &other) noexcept(noexcept(store_.swap(other.store_)))
O(1) swap.
typename Storage::coord_type coord_type
static constexpr std::size_t rank
ca_size_t size() const noexcept
state_type at(const coord_type &c) const
Strict access: throws if c is out of range.
Synchronous double-buffered engine.
const extents_type & extents() const noexcept
Return the frame extents.
static constexpr std::size_t rank
Lattice dimension.
static constexpr std::size_t neighbour_count
Number of neighbours.
void run(const std::size_t steps)
Run several synchronous steps.
std::function< void(std::size_t, const Lattice &)> hook_type
Hook signature: (step_index_just_completed, frame).
Synchronous_Engine & operator=(Synchronous_Engine &&other) noexcept(noexcept(swap(other)))
Exchange this engine with another, which is left with the previous simulation of this one.
typename Lattice::extents_type extents_type
Extents type.
const Rule & rule() const noexcept
Read-only access to the rule (used by checkpointing).
Rule & rule() noexcept
Mutable access to the rule (used by checkpointing to restore the master RNG seed of stochastic rules)...
Lattice & write_lattice() noexcept
Mutable access to the current lattice buffer.
void on_post_step(F &&f)
Register a hook fired after every step().
std::size_t steps_run() const noexcept
Return the number of completed steps.
Neighborhood neighborhood_type
Neighborhood type.
typename Lattice::coord_type coord_type
Coordinate type.
void step()
Apply the rule to every cell once and swap buffers.
Synchronous_Engine(Lattice initial, Rule r, Neighborhood n)
Build an engine on top of an existing initial lattice.
Synchronous_Engine & operator=(const Synchronous_Engine &other)=default
Copy another engine into this one: its lattices, its rule, its neighborhood, its hooks and its count ...
void on_pre_step(F &&f)
Register a hook fired before every step().
Order order_type
Iteration order.
const Lattice & frame() const noexcept
Return the current frame.
void swap(Synchronous_Engine &other) noexcept(noexcept(cur_buf_.swap(other.cur_buf_)) and std::is_nothrow_swappable_v< Rule > and std::is_nothrow_swappable_v< Neighborhood >)
Exchange in O(1) the simulation of this engine and another.
Synchronous_Engine(Lattice initial, Rule r)
Build an engine with a default-constructed neighbourhood.
Synchronous_Engine(const Synchronous_Engine &other)=default
Copy another engine: its lattices, its rule, its neighborhood, its hooks and its count of steps.
typename Lattice::state_type state_type
Cell state type.
void set_step_count(const std::size_t s) noexcept
Override the completed-step counter.
Synchronous_Engine(Synchronous_Engine &&other) noexcept(std::is_nothrow_move_constructible_v< Lattice > and std::is_nothrow_move_constructible_v< Rule > and std::is_nothrow_move_constructible_v< Neighborhood >)
Take the simulation of another engine, which is left with empty lattices, no hooks and no steps run.
void swap_all_or_none(Synchronous_Engine &other)
Shape (per-axis sizes) of an mdspan, mixing compile-time and run-time extents.
Definition ah-mdspan.H:303
A coordinate type with N integral components.
Detect whether a lattice exposes a refresh_halo() method (the hallmark of a Ghost_Lattice or any othe...
Storage + topology that carries the cell values.
Connectivity pattern around a coordinate.
Local transition function (any supported signature).
void iterate_3d_row_major(const ca_size_t n0, const ca_size_t n1, const ca_size_t n2, F &&f)
3D row-major iteration.
void iterate_1d(ca_size_t n0, F &&f)
1D row-major iteration callback f(coord).
void iterate_2d_column_major(ca_size_t n0, ca_size_t n1, F &&f)
2D column-major iteration.
void iterate_2d_tile(const ca_size_t n0, const ca_size_t n1, F &&f)
2D tiled iteration with tile size H along axis 0 and W along axis 1.
void iterate_2d_row_major(ca_size_t n0, ca_size_t n1, F &&f)
2D row-major iteration.
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
void gather_neighbors(const Nbh &nh, const L &lat, const typename L::coord_type &center, std::span< T > out)
Populate out[0..nh.size()) with neighbour values of center.
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.
and
Check uniqueness with explicit hash + equality functors.
STL namespace.
Per-cell context handed to rules that need to know "where" and "when" they are firing.
Definition ca-traits.H:106
Iterate a 2D lattice in W x H tiles.
Definition ca-traits.H:200
Detect whether O is a Tile<W, H> instantiation.
static int * k
Gsl_Compatible_Rng r
C++20 concepts for the Cellular Automata module.
Neighborhoods catalogue for Aleph::CA.