Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
ca_observer_test.cc
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
51#include <cstdint>
52#include <limits>
53#include <random>
54#include <vector>
55
56#include <gtest/gtest.h>
57
58#include <ca-engine-utils.H>
59#include <ca-metrics.H>
60#include <ca-observer.H>
61#include <ca-traits.H>
62#include <tpl_ca_engine.H>
63#include <tpl_ca_lattice.H>
64#include <tpl_ca_neighborhood.H>
65#include <tpl_ca_rule.H>
66#include <tpl_ca_storage.H>
67
68using namespace Aleph;
69using namespace Aleph::CA;
70
71namespace {
72
75
76L make_blinker(ca_size_t rows = 5, ca_size_t cols = 5)
77{
78 L seed({rows, cols}, 0);
79 // Horizontal three-in-a-row at row 2.
80 seed.set({2, 1}, 1);
81 seed.set({2, 2}, 1);
82 seed.set({2, 3}, 1);
83 return seed;
84}
85
86L make_block(ca_size_t rows = 4, ca_size_t cols = 4)
87{
88 L seed({rows, cols}, 0);
89 seed.set({1, 1}, 1);
90 seed.set({1, 2}, 1);
91 seed.set({2, 1}, 1);
92 seed.set({2, 2}, 1);
93 return seed;
94}
95
96L make_random(ca_size_t rows, ca_size_t cols, std::uint32_t seed, double density)
97{
98 L lat({rows, cols}, 0);
99 std::mt19937 rng(seed);
100 std::bernoulli_distribution flip(density);
101 for (ca_size_t i = 0; i < rows; ++i)
102 for (ca_size_t j = 0; j < cols; ++j)
103 lat.set({static_cast<ca_index_t>(i), static_cast<ca_index_t>(j)},
104 flip(rng) ? 1 : 0);
105 return lat;
106}
107
108} // namespace
109
110// ---------------------------------------------------------------------------
111// Concept conformance.
112// ---------------------------------------------------------------------------
113
114static_assert(ObserverLike<Density_Observer<int>, L>);
115static_assert(ObserverLike<Activity_Observer<L>, L>);
116static_assert(ObserverLike<Entropy_Observer<2>, L>);
117static_assert(ObserverLike<Stationary_Detector, L>);
118static_assert(ObserverLike<Sampling_Observer<L>, L>);
119
120// ---------------------------------------------------------------------------
121// Composite observer.
122// ---------------------------------------------------------------------------
123
124namespace {
125
126struct Counting_Observer
127{
128 std::size_t begins = 0;
129 std::size_t ends = 0;
130
131 template <typename Frame>
132 void on_step_begin(std::size_t, const Frame &)
133 {
134 ++begins;
135 }
136
137 template <typename Frame>
138 void on_step_end(std::size_t, const Frame &)
139 {
140 ++ends;
141 }
142};
143
144} // namespace
145
146TEST(CAComposite, FansOutBothCallbacksToEveryChild)
147{
148 Counting_Observer a;
149 Counting_Observer b;
151 L frame({2, 2}, 0);
152 comp.on_step_begin(0, frame);
153 comp.on_step_end(1, frame);
154 comp.on_step_begin(1, frame);
155 EXPECT_EQ(a.begins, 2u);
156 EXPECT_EQ(a.ends, 1u);
157 EXPECT_EQ(b.begins, 2u);
158 EXPECT_EQ(b.ends, 1u);
159}
160
161TEST(CAComposite, FactoryPreservesLvalueObserverReferences)
162{
163 Counting_Observer a;
164 Counting_Observer b;
165 auto comp = make_composite_observer(a, b);
166 L frame({2, 2}, 0);
167
168 comp.on_step_begin(0, frame);
169 comp.on_step_end(1, frame);
170 comp.on_step_begin(1, frame);
171
172 EXPECT_EQ(a.begins, 2u);
173 EXPECT_EQ(a.ends, 1u);
174 EXPECT_EQ(b.begins, 2u);
175 EXPECT_EQ(b.ends, 1u);
176}
177
178// ---------------------------------------------------------------------------
179// Activity observer: blinker -> 4 changes per step.
180// ---------------------------------------------------------------------------
181
182TEST(CAActivityObserver, BlinkerReportsFourChangesPerStep)
183{
184 L seed = make_blinker();
185 Engine eng(seed, make_game_of_life_rule(), Moore<2, 1>{});
187 attach_observer(eng, act);
188 eng.run(6);
189
190 ASSERT_EQ(act.activity().size(), 6u);
191 for (auto a : act.activity())
192 EXPECT_EQ(a, 4u);
193}
194
195TEST(CAActivityObserver, BlockIsStillSoActivityIsZero)
196{
197 L seed = make_block();
198 Engine eng(seed, make_game_of_life_rule(), Moore<2, 1>{});
200 attach_observer(eng, act);
201 eng.run(5);
202
203 ASSERT_EQ(act.activity().size(), 5u);
204 for (auto a : act.activity())
205 EXPECT_EQ(a, 0u);
206}
207
208// ---------------------------------------------------------------------------
209// Density observer.
210// ---------------------------------------------------------------------------
211
212TEST(CADensityObserver, InitialFrameIsCapturedAndStepsAccumulate)
213{
214 L seed = make_blinker();
215 Engine eng(seed, make_game_of_life_rule(), Moore<2, 1>{});
216 Density_Observer<int> dens(1);
217 attach_observer(eng, dens);
218 eng.run(4);
219
220 // 1 initial sample + 4 post-step samples.
221 ASSERT_EQ(dens.size(), 5u);
222 // Blinker keeps three alive cells in every frame.
223 for (std::size_t i = 0; i < dens.size(); ++i)
224 EXPECT_EQ(dens.counts()[i], 3u);
225}
226
227TEST(CADensityObserver, GoLRandomDensityLandsInExpectedBand)
228{
229 // Random 64x64 GoL with a fixed seed; classic literature places
230 // long-run alive density around ~0.03-0.05 for the toroidal case
231 // after enough steps to dissipate transients.
232 L seed = make_random(64, 64, /*seed=*/0xCAFEu, /*density=*/0.4);
233 Engine eng(seed, make_game_of_life_rule(), Moore<2, 1>{});
234 Density_Observer<int> dens(1);
235 attach_observer(eng, dens);
236 eng.run(500);
237
238 // Average the last 200 samples.
239 double sum = 0.0;
240 std::size_t cnt = 0;
241 for (std::size_t i = dens.size() - 200; i < dens.size(); ++i)
242 {
243 sum += dens.density_at(i);
244 ++cnt;
245 }
246 const double avg = sum / static_cast<double>(cnt);
247 // Generous band so the test is robust across builds; the spec
248 // band is 0.03-0.05 but we widen to 0.005-0.20 to keep the test
249 // resistant to seed sensitivity.
250 EXPECT_GT(avg, 0.005);
251 EXPECT_LT(avg, 0.20);
252}
253
254// ---------------------------------------------------------------------------
255// Stationary detector.
256// ---------------------------------------------------------------------------
257
258TEST(CAStationaryDetector, BlinkerYieldsCycleLengthTwo)
259{
260 L seed = make_blinker();
261 Engine eng(seed, make_game_of_life_rule(), Moore<2, 1>{});
262 Stationary_Detector det(8);
263 attach_observer(eng, det);
264 eng.run(10);
265
266 ASSERT_TRUE(det.cycle_detected());
267 EXPECT_EQ(*det.cycle_length(), 2u);
268}
269
270TEST(CAStationaryDetector, BlockYieldsCycleLengthOne)
271{
272 L seed = make_block();
273 Engine eng(seed, make_game_of_life_rule(), Moore<2, 1>{});
274 Stationary_Detector det(4);
275 attach_observer(eng, det);
276 eng.run(5);
277
278 ASSERT_TRUE(det.cycle_detected());
279 EXPECT_EQ(*det.cycle_length(), 1u);
280}
281
282TEST(CAStationaryDetector, NoCycleDetectedWhenWindowIsTooSmall)
283{
284 // A glider on a large enough toroidal grid takes 32 steps to
285 // return; with a window of 4 we should not detect anything.
286 L seed({16, 16}, 0);
287 seed.set({0, 1}, 1); seed.set({1, 2}, 1);
288 seed.set({2, 0}, 1); seed.set({2, 1}, 1); seed.set({2, 2}, 1);
289
290 Engine eng(seed, make_game_of_life_rule(), Moore<2, 1>{});
291 Stationary_Detector det(4);
292 attach_observer(eng, det);
293 eng.run(20);
294
295 EXPECT_FALSE(det.cycle_detected());
296}
297
298TEST(CAStationaryDetector, TheWindowKeepsOneFrameMoreThanTheCycleLength)
299{
300 L seed = make_blinker();
301 Engine eng(seed, make_game_of_life_rule(), Moore<2, 1>{});
302 Stationary_Detector det(4);
303 attach_observer(eng, det);
304 eng.run(10);
305
306 ASSERT_TRUE(det.cycle_detected());
307 EXPECT_EQ(*det.cycle_length(), 2u);
308 EXPECT_EQ(det.buffered_hashes(), 5u);
309}
310
311// A window of SIZE_MAX, the natural way to ask for no limit: the check of
312// the window computed SIZE_MAX + 1, which wraps to 0, and the first step
313// removed from an empty buffer inside noexcept: the program ended.
314TEST(CAStationaryDetector, AWindowOfSizeMaxKeepsEveryFrame)
315{
316 L seed = make_blinker();
317 Engine eng(seed, make_game_of_life_rule(), Moore<2, 1>{});
318 Stationary_Detector det(std::numeric_limits<std::size_t>::max());
319 attach_observer(eng, det);
320 eng.run(10);
321
322 ASSERT_TRUE(det.cycle_detected());
323 EXPECT_EQ(*det.cycle_length(), 2u);
324 EXPECT_EQ(det.buffered_hashes(), 11u); // the initial frame and ten steps
325}
326
327// ---------------------------------------------------------------------------
328// Sampling observer.
329// ---------------------------------------------------------------------------
330
331TEST(CASamplingObserver, SnapshotsAtConfiguredPeriod)
332{
333 L seed = make_blinker();
334 Engine eng(seed, make_game_of_life_rule(), Moore<2, 1>{});
335 Sampling_Observer<L> samp(/*period=*/3);
336 attach_observer(eng, samp);
337 eng.run(9);
338
339 // initial + steps {3, 6, 9} = 4 snapshots.
340 ASSERT_EQ(samp.size(), 4u);
341 EXPECT_EQ(samp.step_indices(),
342 (Array<std::size_t>{0, 3, 6, 9}));
343}
344
345TEST(CASamplingObserver, ZeroPeriodDisablesSampling)
346{
347 L seed = make_blinker();
348 Engine eng(seed, make_game_of_life_rule(), Moore<2, 1>{});
349 Sampling_Observer<L> samp(0);
350 attach_observer(eng, samp);
351 eng.run(5);
352
353 EXPECT_EQ(samp.size(), 0u);
354}
355
356// ---------------------------------------------------------------------------
357// Entropy observer.
358// ---------------------------------------------------------------------------
359
360TEST(CAEntropyObserver, EntropyZeroForEmptyAndConstantFrames)
361{
362 L seed({4, 4}, 0);
363 Engine eng(seed, make_game_of_life_rule(), Moore<2, 1>{});
365 attach_observer(eng, ent);
366 eng.run(3);
367
368 ASSERT_EQ(ent.size(), 4u);
369 for (double e : ent.entropy())
370 EXPECT_DOUBLE_EQ(e, 0.0);
371}
372
373TEST(CAEntropyObserver, EntropyPositiveOnRandomFrame)
374{
375 L seed = make_random(16, 16, /*seed=*/42u, /*density=*/0.5);
376 Engine eng(seed, make_game_of_life_rule(), Moore<2, 1>{});
378 attach_observer(eng, ent);
379 eng.run(1); // step 1 runs => on_step_begin captures the initial frame
380 ASSERT_GE(ent.size(), 1u);
381 EXPECT_GT(ent.entropy()[0], 0.0);
382}
383
384// ---------------------------------------------------------------------------
385// Composite-of-real-observers.
386// ---------------------------------------------------------------------------
387
388TEST(CAComposite, MultipleObserversObserveTheSameRun)
389{
390 L seed = make_blinker();
391 Engine eng(seed, make_game_of_life_rule(), Moore<2, 1>{});
392
393 Density_Observer<int> dens(1);
395 Stationary_Detector det(8);
396
399 comp(dens, act, det);
400
401 attach_observer(eng, comp);
402 eng.run(6);
403
404 EXPECT_EQ(dens.size(), 7u);
405 EXPECT_EQ(act.size(), 6u);
406 EXPECT_TRUE(det.cycle_detected());
407 EXPECT_EQ(*det.cycle_length(), 2u);
408}
size_t * rows
Definition ca-c-api.h:112
size_t cols
Definition ca-c-api.h:105
Convenience builders for the Phase 3 synchronous engine.
Free metric helpers for cellular automata frames.
Phase-7 observability layer for cellular automata engines.
Common typedefs and tag types for the Cellular Automata module.
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
Records the number of cells that changed across each step.
std::size_t size() const noexcept
Return the number of recorded steps.
Variadic adaptor that fan-outs notifications to many observers.
void on_step_end(std::size_t step, const Lattice &frame)
Forward a step-end event to every child observer.
void on_step_begin(std::size_t step, const Lattice &frame)
Forward a step-begin event to every child observer.
Records the count of cells in tracked_state per step.
Records the Shannon entropy of the state distribution.
Lattice that adds boundary-aware access on top of a storage.
Moore (Chebyshev) neighborhood of radius R in N dimensions.
Snapshots the lattice every period steps.
Detects fixed points and short cycles via frame hashing.
bool cycle_detected() const noexcept
Return whether a cycle has been detected.
std::optional< std::size_t > cycle_length() const noexcept
Return the detected cycle length.
Synchronous double-buffered engine.
#define TEST(name)
static mt19937 rng
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.
double density(const Lattice &lat, const typename Lattice::state_type &s)
Definition ca-metrics.H:212
auto make_composite_observer(Observers &&...observers)
Build a Composite_Observer with deduced ownership semantics.
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.
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
The lattice wraps around on every axis.
Definition ca-traits.H:124
ValueArg< size_t > seed
Definition testHash.C:53
Synchronous double-buffered engine for cellular automata.
Cellular automata lattice with pluggable boundary policies.
Neighborhoods catalogue for Aleph::CA.
Rule mechanisms for Aleph::CA.
Dense, contiguous storage for cellular automata cells (1D/2D/3D).