Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
ca-observer.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
75#ifndef CA_OBSERVER_H
76#define CA_OBSERVER_H
77
78#include <concepts>
79#include <cstddef>
80#include <cstdint>
81#include <functional>
82#include <optional>
83#include <tuple>
84#include <utility>
85
86#include <ah-errors.H>
87#include <tpl_array.H>
88
89#include <ca-metrics.H>
90#include <ca-traits.H>
91#include <tpl_ca_concepts.H>
92
93namespace Aleph {
94namespace CA {
95
107template <typename O, typename Lattice>
108concept ObserverLike = requires(O &o, std::size_t s, const Lattice &f) {
109 o.on_step_begin(s, f);
110 o.on_step_end(s, f);
111};
112
113// ---------------------------------------------------------------------------
114// Composite observer.
115// ---------------------------------------------------------------------------
116
127template <typename... Observers>
129{
130 std::tuple<Observers...> obs_;
131
132public:
148 explicit Composite_Observer(Observers... observers) : obs_(std::forward<Observers>(observers)...)
149 {}
150
156 template <std::size_t I>
157 [[nodiscard]] const auto &get() const noexcept
158 {
159 return std::get<I>(obs_);
160 }
161
167 template <std::size_t I>
168 [[nodiscard]] auto &get() noexcept
169 {
170 return std::get<I>(obs_);
171 }
172
177 [[nodiscard]] static constexpr std::size_t size() noexcept
178 {
179 return sizeof...(Observers);
180 }
181
191 template <typename Lattice>
192 void on_step_begin(std::size_t step, const Lattice &frame)
193 {
194 std::apply([&](auto &...o)
195 {
196 (o.on_step_begin(step, frame), ...);
197 }, obs_);
198 }
199
209 template <typename Lattice>
210 void on_step_end(std::size_t step, const Lattice &frame)
211 {
212 std::apply([&](auto &...o)
213 {
214 (o.on_step_end(step, frame), ...);
215 }, obs_);
216 }
217};
218
233template <typename... Observers>
234[[nodiscard]] inline auto make_composite_observer(Observers &&...observers)
235{
236 return Composite_Observer<Observers...>(std::forward<Observers>(observers)...);
237}
238
239// ---------------------------------------------------------------------------
240// Engine plumbing.
241// ---------------------------------------------------------------------------
242
261template <typename Engine, typename Observer>
262inline void attach_observer(Engine &engine, Observer &observer)
263{
264 using Lat = typename Engine::lattice_type;
265 engine.on_pre_step([&observer](std::size_t step, const Lat &frame)
266 {
267 observer.on_step_begin(step, frame);
268 });
269 engine.on_post_step([&observer](std::size_t step, const Lat &frame)
270 {
271 observer.on_step_end(step, frame);
272 });
273}
274
291template <typename Engine, typename Observer>
292inline void attach_observer_graph(Engine &engine, Observer &observer)
293{
294 engine.on_pre_step([&observer](std::size_t step, const auto &frame)
295 {
296 observer.on_step_begin(step, frame);
297 });
298 engine.on_post_step([&observer](std::size_t step, const auto &frame)
299 {
300 observer.on_step_end(step, frame);
301 });
302}
303
304// ---------------------------------------------------------------------------
305// Density observer.
306// ---------------------------------------------------------------------------
307
327template <typename State>
329{
333 bool seeded_ = false;
334
335public:
339 Density_Observer() = default;
340
345 explicit Density_Observer(State s) : tracked_state_(std::move(s)) {}
346
351 Density_Observer(const Density_Observer &other) = default;
352
362 Density_Observer(Density_Observer &&other) noexcept(std::is_nothrow_copy_constructible_v<State>)
363 : tracked_state_(other.tracked_state_), counts_(std::move(other.counts_)),
364 totals_(std::move(other.totals_)), seeded_(std::exchange(other.seeded_, false))
365 {}
366
374
381 std::is_nothrow_swappable_v<State>)
382 {
383 swap(other);
384 return *this;
385 }
386
391 void swap(Density_Observer &other) noexcept(std::is_nothrow_swappable_v<State>)
392 {
393 using std::swap;
394 swap(tracked_state_, other.tracked_state_);
395 counts_.swap(other.counts_);
396 totals_.swap(other.totals_);
397 swap(seeded_, other.seeded_);
398 }
399
404 [[nodiscard]] const Array<ca_size_t> &counts() const noexcept
405 {
406 return counts_;
407 }
408
413 [[nodiscard]] const Array<ca_size_t> &totals() const noexcept
414 {
415 return totals_;
416 }
417
423 [[nodiscard]] double density_at(const std::size_t i) const
424 {
426 << "Density_Observer: index " << i << " out of range";
427 return totals_[i] == 0 ? 0.0 : static_cast<double>(counts_[i]) / static_cast<double>(totals_[i]);
428 }
429
434 [[nodiscard]] std::size_t size() const noexcept
435 {
436 return counts_.size();
437 }
438
445 void reset() noexcept
446 {
447 counts_.clear();
448 totals_.clear();
449 seeded_ = false;
450 }
451
458 template <typename Lattice>
459 void on_step_begin(const std::size_t step, const Lattice &frame)
460 {
461 if (step == 0 and not seeded_)
462 {
464 totals_.append(total_cells(frame));
465 seeded_ = true;
466 }
467 }
468
475 template <typename Lattice>
476 void on_step_end(const std::size_t step, const Lattice &frame)
477 {
478 (void) step;
480 totals_.append(total_cells(frame));
481 }
482};
483
484// ---------------------------------------------------------------------------
485// Activity observer.
486// ---------------------------------------------------------------------------
487
510template <typename Lattice>
512{
513 std::optional<Lattice> prev_;
515
516public:
520 Activity_Observer() = default;
521
526 [[nodiscard]] const Array<ca_size_t> &activity() const noexcept
527 {
528 return activity_;
529 }
530
535 [[nodiscard]] std::size_t size() const noexcept
536 {
537 return activity_.size();
538 }
539
546 void reset() noexcept
547 {
548 prev_.reset();
550 }
551
557 void on_step_begin(std::size_t step, const Lattice &frame)
558 {
559 (void) step;
560 prev_.emplace(frame);
561 }
562
568 void on_step_end(const std::size_t step, const Lattice &frame)
569 {
570 (void) step;
571 if (prev_.has_value())
573 else
574 activity_.append(0);
575 }
576};
577
578// ---------------------------------------------------------------------------
579// Entropy observer.
580// ---------------------------------------------------------------------------
581
600template <std::size_t MaxState>
602{
604 bool seeded_ = false;
605
606public:
610 Entropy_Observer() = default;
611
616 Entropy_Observer(const Entropy_Observer &other) = default;
617
627 : entropy_(std::move(other.entropy_)), seeded_(std::exchange(other.seeded_, false))
628 {}
629
636
643 {
644 swap(other);
645 return *this;
646 }
647
651 void swap(Entropy_Observer &other) noexcept
652 {
653 entropy_.swap(other.entropy_);
654 std::swap(seeded_, other.seeded_);
655 }
656
661 [[nodiscard]] const Array<double> &entropy() const noexcept
662 {
663 return entropy_;
664 }
665
670 [[nodiscard]] std::size_t size() const noexcept
671 {
672 return entropy_.size();
673 }
674
681 void reset() noexcept
682 {
683 entropy_.clear();
684 seeded_ = false;
685 }
686
693 template <typename Lattice>
694 void on_step_begin(const std::size_t step, const Lattice &frame)
695 {
696 if (step == 0 and not seeded_)
697 {
698 entropy_.append(shannon_entropy(frame, MaxState));
699 seeded_ = true;
700 }
701 }
702
709 template <typename Lattice>
710 void on_step_end(const std::size_t step, const Lattice &frame)
711 {
712 (void) step;
713 entropy_.append(shannon_entropy(frame, MaxState));
714 }
715};
716
717// ---------------------------------------------------------------------------
718// Stationary detector.
719// ---------------------------------------------------------------------------
720
750{
751 std::size_t max_cycle_length_ = 0;
754 std::optional<std::size_t> cycle_length_;
755 std::optional<std::size_t> cycle_start_;
756
757 // A full window drops its oldest entry and keeps the new one in its
758 // place: close_gap() moves the others one place down, in both buffers,
759 // which then keep their size and do not allocate. remove_first() also
760 // shrinks a buffer that holds a quarter of its capacity or less, as
761 // those of a small window do, and a bad_alloc there would leave each
762 // hash with the step of another one. A window that is not full grows:
763 // the room for the new entry comes first, in both buffers, so that a
764 // bad_alloc leaves them as they were and the appends do not allocate
765 void push(const std::uint64_t h, const std::size_t step)
766 {
767 // size > max, not size >= max + 1: with max = SIZE_MAX the sum wraps
768 // to 0, and the first push would drop from an empty buffer
770 {
771 const std::size_t n = hashes_.size();
772 Aleph::close_gap(&hashes_(0), n, 0);
773 Aleph::close_gap(&steps_(0), n, 0);
774 hashes_(n - 1) = h;
775 steps_(n - 1) = step;
776 return;
777 }
778
780 steps_.reserve(steps_.size() + 1);
782 steps_.append(step);
783 }
784
785 // Whether a frame seen length steps before is within the steps that a
786 // full window spans, max_cycle_length_ + 1: that sum wraps to 0 with
787 // SIZE_MAX, so the last one is checked as length - 1. A length of 0, as
788 // a step given twice makes, stays within them
789 [[nodiscard]] bool spans_a_full_window_at_most(const std::size_t length) const noexcept
790 {
791 return length <= max_cycle_length_ or length - 1 == max_cycle_length_;
792 }
793
794public:
799
806 explicit Stationary_Detector(std::size_t max_cycle_length) : max_cycle_length_(max_cycle_length)
807 {}
808
813 [[nodiscard]] bool cycle_detected() const noexcept
814 {
815 return cycle_length_.has_value();
816 }
817
822 [[nodiscard]] std::optional<std::size_t> cycle_length() const noexcept
823 {
824 return cycle_length_;
825 }
826
831 [[nodiscard]] std::optional<std::size_t> cycle_start() const noexcept
832 {
833 return cycle_start_;
834 }
835
840 [[nodiscard]] std::size_t buffered_hashes() const noexcept
841 {
842 return hashes_.size();
843 }
844
851 void reset() noexcept
852 {
853 hashes_.clear();
854 steps_.clear();
855 cycle_length_.reset();
856 cycle_start_.reset();
857 }
858
865 template <typename Lattice>
866 void on_step_begin(const std::size_t step, const Lattice &frame)
867 {
868 if (max_cycle_length_ == 0)
870 if (step == 0 and hashes_.is_empty())
871 push(frame_hash(frame), step);
872 }
873
887 template <typename Lattice>
888 void on_step_end(std::size_t step, const Lattice &frame)
889 {
890 if (max_cycle_length_ == 0)
892 const std::uint64_t h = frame_hash(frame);
893
894 if (not cycle_length_.has_value())
895 for (std::size_t i = 0; i < hashes_.size(); ++i)
896 if (hashes_[i] == h and spans_a_full_window_at_most(step - steps_[i]))
897 {
898 cycle_start_ = steps_[i];
899 cycle_length_ = step - steps_[i];
900 break;
901 }
902 push(h, step);
903 }
904};
905
906// ---------------------------------------------------------------------------
907// Sampling observer.
908// ---------------------------------------------------------------------------
909
932template <typename Lattice>
934{
935 std::size_t period_ = 1;
938
939public:
943 Sampling_Observer() = default;
944
949 explicit Sampling_Observer(const std::size_t period) : period_(period) {}
950
955 [[nodiscard]] const Array<Lattice> &snapshots() const noexcept
956 {
957 return snapshots_;
958 }
959
964 [[nodiscard]] const Array<std::size_t> &step_indices() const noexcept
965 {
966 return step_indices_;
967 }
968
973 [[nodiscard]] std::size_t size() const noexcept
974 {
975 return snapshots_.size();
976 }
977
984 void reset() noexcept
985 {
986 snapshots_.clear();
988 }
989
995 void on_step_begin(const std::size_t step, const Lattice &frame)
996 {
997 if (period_ != 0 and step == 0 and snapshots_.is_empty())
998 {
999 snapshots_.append(frame);
1001 }
1002 }
1003
1009 void on_step_end(const std::size_t step, const Lattice &frame)
1010 {
1011 if (period_ == 0)
1012 return;
1013 if (step % period_ == 0)
1014 {
1015 snapshots_.append(frame);
1016 step_indices_.append(step);
1017 }
1018 }
1019};
1020
1021} // namespace CA
1022} // namespace Aleph
1023
1024#endif // CA_OBSERVER_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
long double h
Definition btreepic.C:154
Free metric helpers for cellular automata frames.
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 clear() noexcept
Empties the container.
Definition tpl_array.H:435
constexpr bool is_empty() const noexcept
Checks if the container is empty.
Definition tpl_array.H:444
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
Records the number of cells that changed across each step.
void on_step_begin(std::size_t step, const Lattice &frame)
Capture the frame before a step.
std::optional< Lattice > prev_
Activity_Observer()=default
Construct an empty activity observer.
const Array< ca_size_t > & activity() const noexcept
Return the activity time series.
void on_step_end(const std::size_t step, const Lattice &frame)
Record changed cells after a step.
Array< ca_size_t > activity_
void reset() noexcept
Clear the previous frame and activity samples.
std::size_t size() const noexcept
Return the number of recorded steps.
Variadic adaptor that fan-outs notifications to many observers.
std::tuple< Observers... > obs_
static constexpr std::size_t size() noexcept
Return the number of child observers.
void on_step_end(std::size_t step, const Lattice &frame)
Forward a step-end event to every child observer.
Composite_Observer(Observers... observers)
Build the composite from child observers.
auto & get() noexcept
Return mutable access to a child observer.
const auto & get() const noexcept
Return read-only access to a 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.
Density_Observer & operator=(Density_Observer &&other) noexcept(std::is_nothrow_swappable_v< State >)
Exchange this observer with another, which is left with the previous samples of this one.
Density_Observer(State s)
Construct an observer tracking a specific state.
Density_Observer(Density_Observer &&other) noexcept(std::is_nothrow_copy_constructible_v< State >)
Take the samples of another observer, which is left with none, tracking the same state.
Density_Observer(const Density_Observer &other)=default
Copy another observer: the state that it counts, the counts of each step, their totals,...
Array< ca_size_t > counts_
double density_at(const std::size_t i) const
Return density at a recorded sample.
void swap(Density_Observer &other) noexcept(std::is_nothrow_swappable_v< State >)
Exchange in O(1) the tracked state and the samples of this observer and another.
const Array< ca_size_t > & counts() const noexcept
Return the count time series.
const Array< ca_size_t > & totals() const noexcept
Return the total-cell time series.
Density_Observer()=default
Construct an observer that tracks State{}.
Density_Observer & operator=(const Density_Observer &other)=default
Copy another observer into this one: the state that it counts, the counts of each step,...
Array< ca_size_t > totals_
void reset() noexcept
Clear all recorded samples.
std::size_t size() const noexcept
Return the number of recorded samples.
void on_step_begin(const std::size_t step, const Lattice &frame)
Record the initial frame before step zero.
void on_step_end(const std::size_t step, const Lattice &frame)
Record the frame after a completed step.
Records the Shannon entropy of the state distribution.
Entropy_Observer(Entropy_Observer &&other) noexcept
Take the samples of another observer, which is left with none.
std::size_t size() const noexcept
Return the number of entropy samples.
void on_step_end(const std::size_t step, const Lattice &frame)
Record entropy after a completed step.
void swap(Entropy_Observer &other) noexcept
Exchange in O(1) the samples of this observer and another.
void on_step_begin(const std::size_t step, const Lattice &frame)
Record entropy of the initial frame.
Entropy_Observer()=default
Construct an empty entropy observer.
Entropy_Observer & operator=(const Entropy_Observer &other)=default
Copy another observer into this one: the entropy of each step, and whether it has seen a frame.
Entropy_Observer(const Entropy_Observer &other)=default
Copy another observer: the entropy of each step, and whether it has seen a frame.
Entropy_Observer & operator=(Entropy_Observer &&other) noexcept
Exchange this observer with another, which is left with the previous samples of this one.
void reset() noexcept
Clear all entropy samples.
const Array< double > & entropy() const noexcept
Return the entropy time series.
Lattice that adds boundary-aware access on top of a storage.
Snapshots the lattice every period steps.
Sampling_Observer()=default
Construct an observer that snapshots every step.
std::size_t size() const noexcept
Return the number of stored snapshots.
const Array< std::size_t > & step_indices() const noexcept
Return step indices for collected snapshots.
Array< Lattice > snapshots_
Array< std::size_t > step_indices_
const Array< Lattice > & snapshots() const noexcept
Return collected snapshots.
void reset() noexcept
Clear all snapshots and step indices.
void on_step_begin(const std::size_t step, const Lattice &frame)
Capture the initial frame when sampling is enabled.
void on_step_end(const std::size_t step, const Lattice &frame)
Capture the completed frame at period boundaries.
Sampling_Observer(const std::size_t period)
Construct an observer with an explicit sampling period.
Detects fixed points and short cycles via frame hashing.
std::optional< std::size_t > cycle_start_
std::size_t buffered_hashes() const noexcept
Return the number of buffered hashes.
Stationary_Detector()=default
Construct a detector with the default 16-frame window.
void reset() noexcept
Clear buffered hashes and detected-cycle state.
std::optional< std::size_t > cycle_start() const noexcept
Return the cycle start step.
Array< std::size_t > steps_
Array< std::uint64_t > hashes_
bool cycle_detected() const noexcept
Return whether a cycle has been detected.
bool spans_a_full_window_at_most(const std::size_t length) const noexcept
std::optional< std::size_t > cycle_length() const noexcept
Return the detected cycle length.
std::optional< std::size_t > cycle_length_
void on_step_end(std::size_t step, const Lattice &frame)
Check the completed frame against the recent hash window.
void on_step_begin(const std::size_t step, const Lattice &frame)
Seed the detector with the initial frame hash.
void push(const std::uint64_t h, const std::size_t step)
Stationary_Detector(std::size_t max_cycle_length)
Construct a detector with an explicit window size.
Concept satisfied by any cellular-automaton observer.
void attach_observer(Engine &engine, Observer &observer)
Plug an observer into an engine's pre/post-step hooks.
double shannon_entropy(const Lattice &lat, std::size_t max_state)
Shannon entropy in nats of the [0, max_state) distribution.
Definition ca-metrics.H:276
void attach_observer_graph(Engine &engine, Observer &observer)
Attach an observer to engines without a lattice_type alias.
ca_size_t total_cells(const Lattice &lat) noexcept
Definition ca-metrics.H:204
std::uint64_t frame_hash(const Lattice &lat)
Deterministic 64-bit FNV-1a hash of the lattice cells.
Definition ca-metrics.H:311
ca_size_t count_state(const Lattice &lat, const typename Lattice::state_type &s)
Definition ca-metrics.H:175
auto make_composite_observer(Observers &&...observers)
Build a Composite_Observer with deduced ownership semantics.
ca_size_t cell_diff_count(const Lattice &a, const Lattice &b)
Definition ca-metrics.H:386
Main namespace for Aleph-w library functions.
and
Check uniqueness with explicit hash + equality functors.
void close_gap(T *ptr, size_t n, size_t pos, size_t num_entries=1)
Close a gap in an array by shifting elements left.
STL namespace.
void on_step_end(std::size_t, const Lattice &)
Definition test_format.cc:7
static mt19937 engine
Dynamic array container with automatic resizing.
C++20 concepts for the Cellular Automata module.