Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
tpl_ca_hashlife.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
70#ifndef TPL_CA_HASHLIFE_H
71#define TPL_CA_HASHLIFE_H
72
73#include <algorithm>
74#include <bit>
75#include <cctype>
76#include <cstdint>
77#include <deque>
78#include <istream>
79#include <limits>
80#include <optional>
81#include <ostream>
82#include <sstream>
83#include <string>
84#include <unordered_map>
85#include <utility>
86
87#include <ah-errors.H>
88#include <tpl_array.H>
89#include <tpl_sort_utils.H>
90
91namespace Aleph {
92namespace CA {
93
108{
109 std::uint16_t birth_mask;
110 std::uint16_t survival_mask;
111
113 [[nodiscard]] constexpr bool apply(const bool current, const std::uint8_t n) const noexcept
114 {
115 return current ? (((survival_mask >> n) & 1u) != 0) : (((birth_mask >> n) & 1u) != 0);
116 }
117
118 [[nodiscard]] constexpr bool operator==(const Outer_Totalistic_Binary_Rule &) const noexcept
119 = default;
120};
121
124 static_cast<std::uint16_t>(1u << 3), static_cast<std::uint16_t>((1u << 2) | (1u << 3))};
125
128 static_cast<std::uint16_t>((1u << 3) | (1u << 6)),
129 static_cast<std::uint16_t>((1u << 2) | (1u << 3))};
130
133 static_cast<std::uint16_t>((1u << 3) | (1u << 6) | (1u << 7) | (1u << 8)),
134 static_cast<std::uint16_t>((1u << 3) | (1u << 4) | (1u << 6) | (1u << 7) | (1u << 8))};
135
137inline constexpr Outer_Totalistic_Binary_Rule Seeds{static_cast<std::uint16_t>(1u << 2),
138 std::uint16_t{0}};
139
145[[nodiscard]] inline std::string format_rule(const Outer_Totalistic_Binary_Rule &r)
146{
147 std::string s;
148 s.reserve(20);
149 s.push_back('B');
150 for (int i = 0; i <= 8; ++i)
151 if (((r.birth_mask >> i) & 1u) != 0)
152 s.push_back(static_cast<char>('0' + i));
153 s.push_back('/');
154 s.push_back('S');
155 for (int i = 0; i <= 8; ++i)
156 if (((r.survival_mask >> i) & 1u) != 0)
157 s.push_back(static_cast<char>('0' + i));
158 return s;
159}
160
168[[nodiscard]] inline std::optional<Outer_Totalistic_Binary_Rule> parse_rule(const std::string &s)
169{
170 std::uint16_t birth = 0, survival = 0;
171 std::size_t i = 0;
172 while (i < s.size() and std::isspace(static_cast<unsigned char>(s[i])))
173 ++i;
174 if (i < s.size() and (s[i] == 'B' or s[i] == 'b'))
175 {
176 ++i;
177 while (i < s.size() and std::isdigit(static_cast<unsigned char>(s[i])))
178 {
179 birth |= static_cast<std::uint16_t>(1u << (s[i] - '0'));
180 ++i;
181 }
182 if (i < s.size() and s[i] == '/')
183 ++i;
184 if (i < s.size() and (s[i] == 'S' or s[i] == 's'))
185 ++i;
186 while (i < s.size() and std::isdigit(static_cast<unsigned char>(s[i])))
187 {
188 survival |= static_cast<std::uint16_t>(1u << (s[i] - '0'));
189 ++i;
190 }
191 }
192 else
193 {
194 while (i < s.size() and std::isdigit(static_cast<unsigned char>(s[i])))
195 {
196 survival |= static_cast<std::uint16_t>(1u << (s[i] - '0'));
197 ++i;
198 }
199 if (i >= s.size() or s[i] != '/')
200 return std::nullopt;
201 ++i;
202 while (i < s.size() and std::isdigit(static_cast<unsigned char>(s[i])))
203 {
204 birth |= static_cast<std::uint16_t>(1u << (s[i] - '0'));
205 ++i;
206 }
207 }
208 return Outer_Totalistic_Binary_Rule{birth, survival};
209}
210
211namespace ca_hashlife_detail {
212
215struct Node
216{
217 std::uint8_t level;
218 std::uint8_t bits;
219 std::uint64_t population;
225};
226
229{
230 std::uint8_t level;
231 std::uint8_t bits;
236
237 [[nodiscard]] bool operator==(const Node_Key &o) const noexcept
238 {
239 return level == o.level and bits == o.bits and nw == o.nw and ne == o.ne and sw == o.sw
240 and se == o.se;
241 }
242};
243
245{
246 [[nodiscard]] std::size_t operator()(const Node_Key &k) const noexcept
247 {
248 auto mix = [](std::size_t a, std::size_t b) noexcept -> std::size_t
249 {
250 return a ^ (b + 0x9e3779b97f4a7c15ULL + (a << 6) + (a >> 2));
251 };
252 std::size_t h = (static_cast<std::size_t>(k.level) << 8) | k.bits;
253 h = mix(h, reinterpret_cast<std::uintptr_t>(k.nw));
254 h = mix(h, reinterpret_cast<std::uintptr_t>(k.ne));
255 h = mix(h, reinterpret_cast<std::uintptr_t>(k.sw));
256 h = mix(h, reinterpret_cast<std::uintptr_t>(k.se));
257 return h;
258 }
259};
260
261} // namespace ca_hashlife_detail
262
301{
302public:
305
307 struct BBox
308 {
309 std::int64_t x_min;
310 std::int64_t y_min;
311 std::int64_t x_max;
312 std::int64_t y_max;
313
315 [[nodiscard]] bool is_empty() const noexcept
316 {
317 return x_min > x_max;
318 }
319
321 [[nodiscard]] std::int64_t width() const noexcept
322 {
323 return is_empty() ? std::int64_t{0} : (x_max - x_min + 1);
324 }
325
327 [[nodiscard]] std::int64_t height() const noexcept
328 {
329 return is_empty() ? std::int64_t{0} : (y_max - y_min + 1);
330 }
331 };
332
334 struct Stats
335 {
336 std::size_t canonical_nodes;
337 std::size_t result_hits;
338 std::size_t result_misses;
340 std::uint8_t root_level;
341 };
342
350 explicit Hashlife_Engine(Rule rule = Conway_Life, std::size_t cache_capacity = std::size_t{1} << 22)
352 {
354 << "Hashlife_Engine: cache_capacity (" << cache_capacity_ << ") below minimum 1024";
356 }
357
365
368
383 {
384 swap(other);
385 }
386
393 {
394 swap(other);
395 return *this;
396 }
397
402 void swap(Hashlife_Engine &other) noexcept
403 {
404 using std::swap;
405 swap(rule_, other.rule_);
406 swap(cache_capacity_, other.cache_capacity_);
407 pool_.swap(other.pool_);
408 table_.swap(other.table_);
409 empty_by_level_.swap(other.empty_by_level_);
410 swap(root_, other.root_);
411 swap(generation_, other.generation_);
412 swap(result_hits_, other.result_hits_);
413 swap(result_misses_, other.result_misses_);
414 swap(result_cache_clears_, other.result_cache_clears_);
415 }
416
418 void set_rule(const Rule &r)
419 {
420 if (r == rule_)
421 return;
422 rule_ = r;
424 }
425
427 [[nodiscard]] Rule rule() const noexcept
428 {
429 return rule_;
430 }
431
441 void set_alive(const std::int64_t x, const std::int64_t y, const bool alive = true)
442 {
443 while (true)
444 {
445 const std::int64_t half = std::int64_t{1} << (root_->level - 1);
446 if (x >= -half and x < half and y >= -half and y < half)
447 break;
448 root_ = expand(root_);
449 }
450 const std::int64_t half = std::int64_t{1} << (root_->level - 1);
451 root_ = set_in_node(root_, x + half, y + half, alive);
452 }
453
456 [[nodiscard]] bool alive_at(const std::int64_t x, const std::int64_t y) const
457 {
458 const std::int64_t half = std::int64_t{1} << (root_->level - 1);
459 if (x < -half or x >= half or y < -half or y >= half)
460 return false;
461 return get_in_node(root_, x + half, y + half);
462 }
463
476 std::uint64_t advance(const unsigned k)
477 {
478 ah_domain_error_if(k > 62) << "Hashlife_Engine::advance: k=" << k << " exceeds 62";
479 const std::uint8_t min_level =
480 std::max<std::uint8_t>(static_cast<std::uint8_t>(k + 2), 4);
481 while (root_->level < min_level)
482 root_ = expand(root_);
483 while (not is_centered_well(root_))
484 root_ = expand(root_);
485
486 const std::uint8_t L = root_->level;
487 Node *const new_root = evolve(root_);
488 const std::uint64_t steps = std::uint64_t{1} << (L - 2);
489 generation_ += static_cast<std::int64_t>(steps);
490 root_ = new_root;
491
492 if (table_.size() > cache_capacity_)
494 return steps;
495 }
496
506 std::uint64_t run(std::uint64_t generations)
507 {
508 std::uint64_t advanced = 0;
509 while (generations > 0)
510 {
511 const unsigned k = static_cast<unsigned>(63 - std::countl_zero(generations));
512 const std::uint64_t step = advance(k);
513 advanced += step;
514 if (step >= generations)
515 break;
516 generations -= step;
517 }
518 return advanced;
519 }
520
522 [[nodiscard]] std::uint64_t population() const noexcept
523 {
524 return root_->population;
525 }
526
528 [[nodiscard]] std::int64_t generation() const noexcept
529 {
530 return generation_;
531 }
532
534 [[nodiscard]] BBox bbox() const
535 {
536 BBox bb{std::numeric_limits<std::int64_t>::max(), std::numeric_limits<std::int64_t>::max(),
537 std::numeric_limits<std::int64_t>::min(), std::numeric_limits<std::int64_t>::min()};
538 if (root_->population == 0)
539 return bb;
540 const std::int64_t half = std::int64_t{1} << (root_->level - 1);
541 visit_alive(root_, -half, -half, [&bb](std::int64_t x, std::int64_t y) noexcept
542 {
543 if (x < bb.x_min)
544 bb.x_min = x;
545 if (x > bb.x_max)
546 bb.x_max = x;
547 if (y < bb.y_min)
548 bb.y_min = y;
549 if (y > bb.y_max)
550 bb.y_max = y;
551 });
552 return bb;
553 }
554
556 void clear()
557 {
558 generation_ = 0;
560 }
561
563 [[nodiscard]] Stats stats() const noexcept
564 {
566 }
567
569 [[nodiscard]] std::size_t cache_capacity() const noexcept
570 {
571 return cache_capacity_;
572 }
573
581 template <typename F>
582 void for_each_alive(F &&f) const
583 {
584 if (root_->population == 0)
585 return;
586 const std::int64_t half = std::int64_t{1} << (root_->level - 1);
587 visit_alive(root_, -half, -half, std::forward<F>(f));
588 }
589
590 // ------------------------------------------------------------------
591 // RLE (Run-Length-Encoded) Conway-format I/O.
592 // ------------------------------------------------------------------
593
602 void load_rle(std::istream &in)
603 {
604 std::string line;
605 bool header_seen = false;
606 std::int64_t origin_x = 0;
607 std::int64_t origin_y = 0;
608 std::int64_t cur_x = 0;
609 std::int64_t cur_y = 0;
610 std::int64_t run = 0;
611 bool ended = false;
612
613 while (not ended and std::getline(in, line))
614 {
615 if (line.empty() or line[0] == '#')
616 continue;
617 if (not header_seen)
618 {
619 const std::int64_t x_size = parse_header_value(line, 'x');
620 const std::int64_t y_size = parse_header_value(line, 'y');
621 if (auto rule_opt = parse_rule_field(line); rule_opt)
622 rule_ = *rule_opt;
623 origin_x = -(x_size / 2);
624 origin_y = -(y_size / 2);
625 cur_x = origin_x;
626 cur_y = origin_y;
627 header_seen = true;
628 continue;
629 }
630 for (const char c : line)
631 {
632 if (std::isdigit(static_cast<unsigned char>(c)))
633 run = run * 10 + (c - '0');
634 else if (c == 'b' or c == '.')
635 {
636 cur_x += (run == 0 ? 1 : run);
637 run = 0;
638 }
639 else if (c == 'o' or c == 'A')
640 {
641 const std::int64_t r = (run == 0 ? 1 : run);
642 for (std::int64_t i = 0; i < r; ++i)
643 set_alive(cur_x + i, cur_y, true);
644 cur_x += r;
645 run = 0;
646 }
647 else if (c == '$')
648 {
649 cur_y += (run == 0 ? 1 : run);
650 cur_x = origin_x;
651 run = 0;
652 }
653 else if (c == '!')
654 {
655 ended = true;
656 break;
657 }
658 }
659 }
660 }
661
663 void load_rle_string(const std::string &s)
664 {
665 std::istringstream iss(s);
666 load_rle(iss);
667 }
668
677 void save_rle(std::ostream &out, const std::string &comment = {}) const
678 {
679 if (not comment.empty())
680 {
681 std::istringstream cs(comment);
682 std::string l;
683 while (std::getline(cs, l))
684 out << "#C " << l << '\n';
685 }
686 const BBox bb = bbox();
687 if (bb.is_empty())
688 {
689 out << "x = 0, y = 0, rule = " << format_rule(rule_) << "\n!\n";
690 return;
691 }
692
693 // Collect alive cells sorted by (y, x).
695 cells.reserve(static_cast<std::size_t>(root_->population));
696 for_each_alive([&cells](std::int64_t x, std::int64_t y)
697 {
698 cells.append(std::pair{y, x});
699 });
700 if (cells.size() > 1)
701 quicksort(&cells.base(), 0, static_cast<long>(cells.size()) - 1);
702
703 out << "x = " << bb.width() << ", y = " << bb.height() << ", rule = " << format_rule(rule_)
704 << '\n';
705
706 std::ostringstream body;
707 auto emit_run = [&body](const std::int64_t n, const char glyph)
708 {
709 if (n <= 0)
710 return;
711 if (n != 1)
712 body << n;
713 body << glyph;
714 };
715
716 std::int64_t prev_y = bb.y_min;
717 std::int64_t cur_x = bb.x_min;
718 std::size_t i = 0;
719 while (i < cells.size())
720 {
721 const std::int64_t y = cells(i).first;
722 const std::int64_t x = cells(i).second;
723 if (y != prev_y)
724 {
725 emit_run(y - prev_y, '$');
726 prev_y = y;
727 cur_x = bb.x_min;
728 }
729 if (x > cur_x)
730 {
731 emit_run(x - cur_x, 'b');
732 cur_x = x;
733 }
734 std::int64_t alive_run = 0;
735 std::size_t j = i;
736 while (j < cells.size() and cells(j).first == y and cells(j).second == cur_x + alive_run)
737 {
738 ++alive_run;
739 ++j;
740 }
741 emit_run(alive_run, 'o');
742 cur_x += alive_run;
743 i = j;
744 }
745 body << "!\n";
746
747 // Wrap body at ~70 columns, never breaking inside a `<digits><glyph>` token.
748 const std::string body_str = body.str();
749 std::size_t pos = 0;
750 while (pos < body_str.size())
751 {
752 std::size_t end = std::min<std::size_t>(pos + 70, body_str.size());
753 while (end < body_str.size() and std::isdigit(static_cast<unsigned char>(body_str[end])))
754 ++end;
755 if (end < body_str.size() and (body_str[end] == 'b' or body_str[end] == 'o'))
756 ++end;
757 out << body_str.substr(pos, end - pos) << '\n';
758 pos = end;
759 }
760 }
761
763 [[nodiscard]] std::string save_rle_string(const std::string &comment = {}) const
764 {
765 std::ostringstream oss;
766 save_rle(oss, comment);
767 return oss.str();
768 }
769
770private:
773
774 static constexpr std::uint8_t initial_level_ = 3;
775
777 std::size_t cache_capacity_;
778
779 std::deque<Node> pool_;
780 std::unordered_map<Node_Key, Node *, ca_hashlife_detail::Node_Key_Hash> table_;
782
783 Node *root_ = nullptr;
784 std::int64_t generation_ = 0;
785
786 mutable std::size_t result_hits_ = 0;
787 mutable std::size_t result_misses_ = 0;
788 std::size_t result_cache_clears_ = 0;
789
790 // -------------------- Canonical node creation --------------------
791
792 Node *make_leaf(const std::uint8_t bits)
793 {
794 const Node_Key key{1, bits, nullptr, nullptr, nullptr, nullptr};
795 if (auto it = table_.find(key); it != table_.end())
796 return it->second;
797 Node n{};
798 n.level = 1;
799 n.bits = bits;
800 n.population = static_cast<std::uint64_t>(std::popcount(bits));
801 pool_.push_back(n);
802 Node *const p = &pool_.back();
803 table_.emplace(key, p);
804 return p;
805 }
806
807 Node *make_node(Node *nw, Node *ne, Node *sw, Node *se)
808 {
809 const Node_Key key{static_cast<std::uint8_t>(nw->level + 1), 0, nw, ne, sw, se};
810 if (auto it = table_.find(key); it != table_.end())
811 return it->second;
812 Node n{};
813 n.level = key.level;
814 n.bits = 0;
815 n.population = nw->population + ne->population + sw->population + se->population;
816 n.nw = nw;
817 n.ne = ne;
818 n.sw = sw;
819 n.se = se;
820 pool_.push_back(n);
821 Node *const p = &pool_.back();
822 table_.emplace(key, p);
823 return p;
824 }
825
826 Node *empty_node(const std::uint8_t level)
827 {
828 while (empty_by_level_.size() <= level)
829 {
830 const std::uint8_t L = static_cast<std::uint8_t>(empty_by_level_.size());
831 if (L == 0)
832 {
833 empty_by_level_.append(nullptr);
834 continue;
835 }
836 Node *n = (L == 1) ? make_leaf(0)
838 empty_by_level_[L - 1], empty_by_level_[L - 1]);
840 }
841 return empty_by_level_[level];
842 }
843
845 {
846 for (auto &n : pool_)
847 n.result = nullptr;
848 result_hits_ = 0;
849 result_misses_ = 0;
851 }
852
853 // -------------------- Geometry helpers --------------------
854
855 Node *expand(const Node *n)
856 {
857 const std::uint8_t L = n->level;
858 if (L == 1)
859 {
860 Node *nw = make_leaf(static_cast<std::uint8_t>((n->bits & 1u) ? (1u << 3) : 0u));
861 Node *ne = make_leaf(static_cast<std::uint8_t>((n->bits & 2u) ? (1u << 2) : 0u));
862 Node *sw = make_leaf(static_cast<std::uint8_t>((n->bits & 4u) ? (1u << 1) : 0u));
863 Node *se = make_leaf(static_cast<std::uint8_t>((n->bits & 8u) ? (1u << 0) : 0u));
864 return make_node(nw, ne, sw, se);
865 }
866 Node *const e = empty_node(static_cast<std::uint8_t>(L - 1));
867 Node *new_nw = make_node(e, e, e, n->nw);
868 Node *new_ne = make_node(e, e, n->ne, e);
869 Node *new_sw = make_node(e, n->sw, e, e);
870 Node *new_se = make_node(n->se, e, e, e);
871 return make_node(new_nw, new_ne, new_sw, new_se);
872 }
873
881 [[nodiscard]] static bool is_centered_well(const Node *n) noexcept
882 {
883 if (n->level < 4)
884 return false;
885 const std::uint64_t central =
886 n->nw->se->se->population
887 + n->ne->sw->sw->population
888 + n->sw->ne->ne->population
889 + n->se->nw->nw->population;
890 return central == n->population;
891 }
892
894 {
895 return make_node(w->ne, e->nw, w->se, e->sw);
896 }
897
899 {
900 return make_node(n->sw, n->se, s->nw, s->ne);
901 }
902
903 Node *center_of_4(Node *nw, Node *ne, Node *sw, Node *se)
904 {
905 return make_node(nw->se, ne->sw, sw->ne, se->nw);
906 }
907
908 // -------------------- Evolution --------------------
909
911 {
912 const std::uint8_t a = n->nw->bits;
913 const std::uint8_t b = n->ne->bits;
914 const std::uint8_t c = n->sw->bits;
915 const std::uint8_t d = n->se->bits;
916
917 // Pack 4x4 cells row-major into a 16-bit bitmap, bit `(r*4 + c)`.
918 std::uint16_t g = 0;
919 g |= static_cast<std::uint16_t>((a & 0x3u)) << 0; // row 0 cols 0-1
920 g |= static_cast<std::uint16_t>((b & 0x3u)) << 2; // row 0 cols 2-3
921 g |= static_cast<std::uint16_t>((a >> 2) & 0x3u) << 4; // row 1 cols 0-1
922 g |= static_cast<std::uint16_t>((b >> 2) & 0x3u) << 6; // row 1 cols 2-3
923 g |= static_cast<std::uint16_t>((c & 0x3u)) << 8; // row 2 cols 0-1
924 g |= static_cast<std::uint16_t>((d & 0x3u)) << 10; // row 2 cols 2-3
925 g |= static_cast<std::uint16_t>((c >> 2) & 0x3u) << 12; // row 3 cols 0-1
926 g |= static_cast<std::uint16_t>((d >> 2) & 0x3u) << 14; // row 3 cols 2-3
927
928 auto get = [g](const int r, const int c) noexcept -> bool
929 {
930 return ((g >> (r * 4 + c)) & 1u) != 0;
931 };
932 auto count = [&get](const int r, const int c) noexcept -> std::uint8_t
933 {
934 return static_cast<std::uint8_t>(get(r - 1, c - 1) + get(r - 1, c) + get(r - 1, c + 1)
935 + get(r, c - 1) + get(r, c + 1) + get(r + 1, c - 1)
936 + get(r + 1, c) + get(r + 1, c + 1));
937 };
938
939 std::uint8_t result = 0;
940 if (rule_.apply(get(1, 1), count(1, 1)))
941 result |= 1u << 0;
942 if (rule_.apply(get(1, 2), count(1, 2)))
943 result |= 1u << 1;
944 if (rule_.apply(get(2, 1), count(2, 1)))
945 result |= 1u << 2;
946 if (rule_.apply(get(2, 2), count(2, 2)))
947 result |= 1u << 3;
948 return make_leaf(result);
949 }
950
952 {
953 if (n->result != nullptr)
954 {
955 ++result_hits_;
956 return n->result;
957 }
959 Node *result = nullptr;
960 if (n->level == 2)
961 {
962 result = evolve_level_2(n);
963 }
964 else
965 {
966 Node *const nw = n->nw;
967 Node *const ne = n->ne;
968 Node *const sw = n->sw;
969 Node *const se = n->se;
970
971 Node *n00 = nw;
972 Node *n01 = horizontal_centered(nw, ne);
973 Node *n02 = ne;
974 Node *n10 = vertical_centered(nw, sw);
975 Node *n11 = center_of_4(nw, ne, sw, se);
976 Node *n12 = vertical_centered(ne, se);
977 Node *n20 = sw;
978 Node *n21 = horizontal_centered(sw, se);
979 Node *n22 = se;
980
981 Node *r00 = evolve(n00);
982 Node *r01 = evolve(n01);
983 Node *r02 = evolve(n02);
984 Node *r10 = evolve(n10);
985 Node *r11 = evolve(n11);
986 Node *r12 = evolve(n12);
987 Node *r20 = evolve(n20);
988 Node *r21 = evolve(n21);
989 Node *r22 = evolve(n22);
990
991 Node *m_nw = make_node(r00, r01, r10, r11);
992 Node *m_ne = make_node(r01, r02, r11, r12);
993 Node *m_sw = make_node(r10, r11, r20, r21);
994 Node *m_se = make_node(r11, r12, r21, r22);
995
996 Node *q_nw = evolve(m_nw);
997 Node *q_ne = evolve(m_ne);
998 Node *q_sw = evolve(m_sw);
999 Node *q_se = evolve(m_se);
1000
1001 result = make_node(q_nw, q_ne, q_sw, q_se);
1002 }
1003 n->result = result;
1004 return result;
1005 }
1006
1007 // -------------------- Cell-level set / get / iterate --------------------
1008
1009 Node *set_in_node(const Node *n, const std::int64_t x, const std::int64_t y, const bool alive)
1010 {
1011 if (n->level == 1)
1012 {
1013 const int bit_idx = static_cast<int>(y) * 2 + static_cast<int>(x);
1014 std::uint8_t new_bits = n->bits;
1015 if (alive)
1016 new_bits |= static_cast<std::uint8_t>(1u << bit_idx);
1017 else
1018 new_bits &= static_cast<std::uint8_t>(~(1u << bit_idx));
1019 return make_leaf(new_bits);
1020 }
1021 const std::int64_t half = std::int64_t{1} << (n->level - 1);
1022 Node *nw = n->nw;
1023 Node *ne = n->ne;
1024 Node *sw = n->sw;
1025 Node *se = n->se;
1026 if (y < half)
1027 {
1028 if (x < half)
1029 nw = set_in_node(nw, x, y, alive);
1030 else
1031 ne = set_in_node(ne, x - half, y, alive);
1032 }
1033 else
1034 {
1035 if (x < half)
1036 sw = set_in_node(sw, x, y - half, alive);
1037 else
1038 se = set_in_node(se, x - half, y - half, alive);
1039 }
1040 return make_node(nw, ne, sw, se);
1041 }
1042
1043 [[nodiscard]] static bool get_in_node(const Node *n, const std::int64_t x, const std::int64_t y) noexcept
1044 {
1045 if (n->level == 1)
1046 {
1047 const int bit_idx = static_cast<int>(y) * 2 + static_cast<int>(x);
1048 return ((n->bits >> bit_idx) & 1u) != 0;
1049 }
1050 const std::int64_t half = std::int64_t{1} << (n->level - 1);
1051 if (y < half)
1052 return (x < half) ? get_in_node(n->nw, x, y) : get_in_node(n->ne, x - half, y);
1053 return (x < half) ? get_in_node(n->sw, x, y - half) : get_in_node(n->se, x - half, y - half);
1054 }
1055
1056 template <typename F>
1057 void visit_alive(Node *n, std::int64_t x, std::int64_t y, F &&f) const
1058 {
1059 if (n->population == 0)
1060 return;
1061 if (n->level == 1)
1062 {
1063 if (n->bits & 0x1u)
1064 f(x, y);
1065 if (n->bits & 0x2u)
1066 f(x + 1, y);
1067 if (n->bits & 0x4u)
1068 f(x, y + 1);
1069 if (n->bits & 0x8u)
1070 f(x + 1, y + 1);
1071 return;
1072 }
1073 const std::int64_t half = std::int64_t{1} << (n->level - 1);
1074 visit_alive(n->nw, x, y, f);
1075 visit_alive(n->ne, x + half, y, f);
1076 visit_alive(n->sw, x, y + half, f);
1077 visit_alive(n->se, x + half, y + half, f);
1078 }
1079
1080 // -------------------- RLE header parsing --------------------
1081
1082 static std::int64_t parse_header_value(const std::string &line, const char key)
1083 {
1084 auto pos = line.find(key);
1085 if (pos == std::string::npos)
1086 return 0;
1087 pos = line.find('=', pos);
1088 if (pos == std::string::npos)
1089 return 0;
1090 ++pos;
1091 while (pos < line.size() and std::isspace(static_cast<unsigned char>(line[pos])))
1092 ++pos;
1093 bool neg = false;
1094 if (pos < line.size() and line[pos] == '-')
1095 {
1096 neg = true;
1097 ++pos;
1098 }
1099 std::int64_t v = 0;
1100 while (pos < line.size() and std::isdigit(static_cast<unsigned char>(line[pos])))
1101 {
1102 v = v * 10 + (line[pos] - '0');
1103 ++pos;
1104 }
1105 return neg ? -v : v;
1106 }
1107
1108 static std::optional<Outer_Totalistic_Binary_Rule> parse_rule_field(const std::string &line)
1109 {
1110 auto pos = line.find("rule");
1111 if (pos == std::string::npos)
1112 pos = line.find("Rule");
1113 if (pos == std::string::npos)
1114 return std::nullopt;
1115 pos = line.find('=', pos);
1116 if (pos == std::string::npos)
1117 return std::nullopt;
1118 ++pos;
1119 while (pos < line.size() and std::isspace(static_cast<unsigned char>(line[pos])))
1120 ++pos;
1121 std::string token;
1122 while (pos < line.size() and not std::isspace(static_cast<unsigned char>(line[pos]))
1123 and line[pos] != ',')
1124 {
1125 token.push_back(line[pos]);
1126 ++pos;
1127 }
1128 if (token.empty())
1129 return std::nullopt;
1130 return parse_rule(token);
1131 }
1132};
1133
1134} // namespace CA
1135} // namespace Aleph
1136
1137#endif // TPL_CA_HASHLIFE_H
Exception handling system with formatted messages for Aleph-w.
#define ah_domain_error_if(C)
Throws std::domain_error if condition holds.
Definition ah-errors.H:670
long double h
Definition btreepic.C:154
long double w
Definition btreepic.C:153
size_t steps
Definition ca-c-api.h:126
size_t size_t int32_t * out
Definition ca-c-api.h:120
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
T & base()
Return a reference to the first element of array.
Definition tpl_array.H:408
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
Hashlife engine for outer-totalistic binary cellular automata.
Rule rule() const noexcept
Current rule.
void swap(Hashlife_Engine &other) noexcept
Exchange in O(1) the universe, the rule and the caches of this engine and another.
Hashlife_Engine & operator=(const Hashlife_Engine &)=delete
Copying is disabled, as in the copy constructor.
void load_rle_string(const std::string &s)
Convenience overload that reads the pattern from a string.
BBox bbox() const
Tight bounding box of the alive cells (empty if population() == 0).
std::size_t cache_capacity() const noexcept
Maximum allowed canonical-node count before the result cache is dropped.
Hashlife_Engine & operator=(Hashlife_Engine &&other) noexcept
Exchange this engine with another, which is left with the previous universe of this one.
Hashlife_Engine(Rule rule=Conway_Life, std::size_t cache_capacity=std::size_t{1}<< 22)
Build an engine with the given rule and result-cache capacity.
static constexpr std::uint8_t initial_level_
8 × 8 starting universe
static bool is_centered_well(const Node *n) noexcept
Standard Hashlife "centered well" predicate: every quadrant of n has its population concentrated in t...
void set_rule(const Rule &r)
Replace the rule. Invalidates the result cache.
static std::optional< Outer_Totalistic_Binary_Rule > parse_rule_field(const std::string &line)
Node * set_in_node(const Node *n, const std::int64_t x, const std::int64_t y, const bool alive)
Node * vertical_centered(Node *n, Node *s)
static bool get_in_node(const Node *n, const std::int64_t x, const std::int64_t y) noexcept
void save_rle(std::ostream &out, const std::string &comment={}) const
Write the alive cells in RLE format.
std::uint64_t run(std::uint64_t generations)
Advance by exactly generations steps.
void for_each_alive(F &&f) const
Iterate over all alive cells, calling f(x, y) for each.
Hashlife_Engine(Hashlife_Engine &&other)
Take the universe and the caches of another engine, which is left with an empty universe of the same ...
Stats stats() const noexcept
Diagnostic counters and current root level.
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).
std::uint64_t advance(const unsigned k)
Advance the universe by 2^k generations.
Node * expand(const Node *n)
void visit_alive(Node *n, std::int64_t x, std::int64_t y, F &&f) const
Node * empty_node(const std::uint8_t level)
Node * horizontal_centered(Node *w, Node *e)
std::unordered_map< Node_Key, Node *, ca_hashlife_detail::Node_Key_Hash > table_
static std::int64_t parse_header_value(const std::string &line, const char key)
std::string save_rle_string(const std::string &comment={}) const
Convenience overload returning the RLE serialisation as a string.
Node * make_node(Node *nw, Node *ne, Node *sw, Node *se)
Hashlife_Engine(const Hashlife_Engine &)=delete
Copying is disabled.
Array< Node * > empty_by_level_
Aleph::Array of canonical empties per level.
void clear()
Reset the universe to empty (preserves rule, capacity and node cache).
Node * make_leaf(const std::uint8_t bits)
void load_rle(std::istream &in)
Load an RLE pattern from in (centred at the origin).
std::int64_t generation() const noexcept
Number of generations elapsed since construction (or the last clear).
bool alive_at(const std::int64_t x, const std::int64_t y) const
Read the cell at world coordinates (x, y).
std::uint64_t population() const noexcept
Number of alive cells.
Node * center_of_4(Node *nw, Node *ne, Node *sw, Node *se)
static mpfr_t y
Definition mpfr_mul_d.c:3
std::optional< Outer_Totalistic_Binary_Rule > parse_rule(const std::string &s)
Parse a B.../S... (or Wolfram S/B) rule string.
std::string format_rule(const Outer_Totalistic_Binary_Rule &r)
Format a rule as a Conway-style Bxxx/Sxxx string.
constexpr Outer_Totalistic_Binary_Rule Conway_Life
Conway's Game of Life: B3/S23.
constexpr Outer_Totalistic_Binary_Rule HighLife
Nathan Thompson's HighLife: B36/S23 (replicators).
constexpr Outer_Totalistic_Binary_Rule Day_And_Night
Bays' Day & Night: B3678/S34678 (self-complementary).
constexpr Outer_Totalistic_Binary_Rule Seeds
Seeds: B2/S (every live cell dies, two neighbours produce a birth).
Main namespace for Aleph-w library functions.
constexpr Bit_Column bits(const unsigned n)
Column of n bits without sign: the integers of [0, 2^n - 1].
and
Check uniqueness with explicit hash + equality functors.
void quicksort(T *a, const long l, const long r, const Compare &cmp=Compare())
Sort an array using iterative quicksort with optimizations.
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
Definition ahAlgo.H:127
Inclusive bounding box (returned by bbox).
std::int64_t height() const noexcept
Height of the box (0 if empty).
bool is_empty() const noexcept
True iff there are no alive cells.
std::int64_t width() const noexcept
Width of the box (0 if empty).
Diagnostics returned by stats.
std::size_t result_cache_clears
times the result cache was invalidated
std::size_t result_misses
misses on the per-node result cache
std::size_t result_hits
hits on the per-node result cache
std::size_t canonical_nodes
number of distinct canonical nodes
std::uint8_t root_level
current universe level (side 2^level)
Outer-totalistic binary rule encoded as two 9-bit bitmasks.
std::uint16_t birth_mask
bit i ⇒ dead cell with i live neighbours becomes alive
constexpr bool apply(const bool current, const std::uint8_t n) const noexcept
True iff a cell with current state and n live neighbours is alive next.
constexpr bool operator==(const Outer_Totalistic_Binary_Rule &) const noexcept=default
std::uint16_t survival_mask
bit i ⇒ live cell with i live neighbours stays alive
std::size_t operator()(const Node_Key &k) const noexcept
Hash key used to canonicalise nodes via std::unordered_map.
bool operator==(const Node_Key &o) const noexcept
Node * result
memoised next-generation result (level level - 1)
std::uint8_t level
1 ⇒ 2x2 leaf; k ⇒ 2^k × 2^k node
std::uint64_t population
number of alive cells covered by this node
std::uint8_t bits
for level-1 leaves: NW NE SW SE bits
static int * k
Gsl_Compatible_Rng r
Dynamic array container with automatic resizing.
Comprehensive sorting algorithms and search utilities for Aleph-w.
DynList< int > l