-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathBarrister.cpp
More file actions
1222 lines (971 loc) · 38.7 KB
/
Barrister.cpp
File metadata and controls
1222 lines (971 loc) · 38.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <cassert>
#include <cmath>
#include <stack>
#include <map>
#include <set>
#include <algorithm>
#include "toml/toml.hpp"
#include "Bits.hpp"
#include "LifeAPI.h"
#include "LifeStableState.hpp"
#include "LifeUnknownState.hpp"
#include "RotorDescription.hpp"
#include "Params.hpp"
#include "Parsing.hpp"
// Idea:
//
// * Calculate the frontier
// * Go through it a single cell at a time
// * For each cell, determine which of the cases (ON to OFF, OFF to
// ON, STABLE to STABLE) are allowed. If there is only one then set it
// and remove the cell from the frontier
// * If we set any cell of the frontier, then propagate stable and
// start over
// * Once there are only true choices left, branch on a cell in the
// frontier (earliest first?)
// After branching, we will likely get some new frontier cells, and
// some previous frontier cells might become settable. Maybe we should
// check the existing frontier cells for any settable ones quickly,
// before doing a full recalculation. (Maybe only if we have made the
// new cell active instead of stable)
// It might also be useful to calculate the "semi-frontier" while
// calculating the frontier, and using that information somehow when
// choosing which cell to branch on. Perhaps something like: branch on
// the frontier cell whose ZOI (over all generations) touches the most
// semi-frontier cells
// The UnknownStep could be made more intelligent by handling unknown
// active cells in the neighbourhood. E.g., if we are a DEAD6 cell
// then we will stay dead.
// It may not be worth the cost: if there is an unknown active cell
// then the current cell is likely to be swamped in the next
// generation or two
const unsigned maxFrontierGens = 6;
const unsigned maxBranchFastCount = 1;
const unsigned maxCalculateRounds = 1;
const unsigned maxCellActiveWindowGens = 0;
const unsigned maxCellActiveStreakGens = 0;
struct Solution {
LifeState state;
LifeState completed;
LifeStableState stable;
LifeStableState interactionStable;
LifeState stator;
unsigned interactionGen;
unsigned recoveryGen;
CompletionResult completionResult;
bool operator==(const Solution&) const = default; // I don't really know why I need to say this
// Doesn't have to be fast
auto operator<=>(const Solution &other) const {
if (auto c = interactionGen <=> other.interactionGen; c != 0) return c;
if (auto c = stable.state.GetPop() <=> other.stable.state.GetPop(); c != 0) return c;
if (auto c = recoveryGen <=> other.recoveryGen; c != 0) return c;
return stable.state.GetHash() <=> other.stable.state.GetHash();
}
};
Transition AllowedTransitions(bool state, bool unknownstable, bool stablestate,
bool forcedInactive, bool forcedUnchanging, bool inzoi, Transition unperturbed) {
auto result = Transition::ANY & ~Transition::STABLE_TO_STABLE;
// If current state is known, remove options with the wrong previous state
if (!unknownstable && state)
result &= Transition::ON_TO_OFF | Transition::ON_TO_ON;
if (!unknownstable && !state)
result &= Transition::OFF_TO_OFF | Transition::OFF_TO_ON;
if (forcedInactive && inzoi) {
if (unknownstable)
result &= ~(Transition::OFF_TO_ON | Transition::ON_TO_OFF);
if (!unknownstable && stablestate)
result &= ~(Transition::OFF_TO_OFF | Transition::ON_TO_OFF);
if (!unknownstable && !stablestate)
result &= ~(Transition::OFF_TO_ON | Transition::ON_TO_ON);
}
if (forcedInactive && !inzoi) {
result &= unperturbed | Transition::OFF_TO_OFF | Transition::ON_TO_ON;
}
if (forcedUnchanging && inzoi)
result &= Transition::OFF_TO_OFF | Transition::ON_TO_ON;
return result;
}
struct FrontierGeneration {
LifeUnknownState state;
LifeUnknownState next;
LifeState frontierCells;
LifeState active;
LifeState changes;
LifeState forcedInactive;
LifeState forcedUnchanging;
unsigned gen;
void SetTransition(std::pair<int, int> cell, Transition transition) {
state.SetTransitionPrev(cell, transition);
next.SetTransitionResult(cell, transition);
}
std::string RLE() const {
LifeHistoryState history(next.state, next.unknown & ~next.unknownStable,
next.unknownStable, LifeState());
return history.RLEWHeader();
}
Transition AllowedTransitions(const LifeStableState &stable,
std::pair<int, int> cell) const {
auto allowedTransitions = ::AllowedTransitions(
state.state.Get(cell), stable.unknown.Get(cell), stable.state.Get(cell),
forcedInactive.Get(cell), forcedUnchanging.Get(cell),
stable.dead0.Get(cell), state.UnperturbedTransitionFor(cell));
return allowedTransitions;
}
};
class SearchState {
public:
LifeStableState stable;
FrontierGeneration frontier;
LifeState everActive;
LifeCountdown<maxCellActiveWindowGens> activeTimer;
LifeCountdown<maxCellActiveStreakGens> streakTimer;
LifeStableState lastTest;
unsigned timeSincePropagate;
unsigned currentGen;
bool hasInteracted;
unsigned interactionStart;
unsigned recoveredTime;
SearchParams *params;
std::vector<Solution> *allSolutions;
std::set<std::string> *seenRotors;
LifeStableState *stableAtInteraction;
SearchState(SearchParams &inparams, std::vector<Solution> &outsolutions, std::set<std::string> &outrotors, LifeStableState &stableAtInteraction);
SearchState(const SearchState &) = default;
SearchState &operator=(const SearchState &) = default;
LifeState ForcedInactiveCells(
const FrontierGeneration &gen, const LifeState &everActive,
const LifeCountdown<maxCellActiveWindowGens> &activeTimer,
const LifeCountdown<maxCellActiveStreakGens> &streakTimer) const;
LifeState ForcedUnchangingCells(
const FrontierGeneration &gen, const LifeState &everActive,
const LifeCountdown<maxCellActiveWindowGens> &activeTimer,
const LifeCountdown<maxCellActiveStreakGens> &streakTimer) const;
bool UpdateActive(FrontierGeneration &generation,
LifeCountdown<maxCellActiveWindowGens> &activeTimer,
LifeCountdown<maxCellActiveStreakGens> &streakTimer);
std::pair<bool, bool> SetForced(FrontierGeneration &generation);
std::pair<bool, bool> TestActive(FrontierGeneration &generation);
std::tuple<bool, bool> PopulateFrontier();
bool UpdateFrontierStrip(unsigned column);
bool CalculateFrontier();
bool RefineFrontier();
std::pair<bool, bool> TryAdvance();
StableOptions OptionsFor(const LifeUnknownState &state,
std::pair<int, int> cell,
Transition transition) const;
std::pair<unsigned, std::pair<int, int>> ChooseBranchCell() const;
void SearchStep();
void RecordOscillator();
void RecordSolution();
void PrintSolution(const Solution &solution);
void SanityCheck();
};
LifeState SearchState::ForcedInactiveCells(
const FrontierGeneration &gen,
const LifeState &everActive,
const LifeCountdown<maxCellActiveWindowGens> &activeTimer,
const LifeCountdown<maxCellActiveStreakGens> &streakTimer) const {
if (gen.gen < params->minFirstActiveGen) {
return ~LifeState();
}
auto activePop = gen.active.GetPop();
if (hasInteracted && !params->reportOscillators && gen.gen > interactionStart + params->maxActiveWindowGens)
return ~LifeState();
if (params->maxActiveCells != -1 && activePop > (unsigned)params->maxActiveCells)
return ~LifeState();
LifeState result;
if (params->maxActiveCells != -1 && activePop == (unsigned)params->maxActiveCells)
result |= ~gen.active; // Or maybe just return
if (params->activeBounds.first != -1 && activePop > 0) {
result |= ~gen.active.BufferAround(params->activeBounds);
}
if (params->maxEverActiveCells != -1 && everActive.GetPop() == (unsigned)params->maxEverActiveCells) {
result |= ~everActive; // Or maybe just return
}
if (params->everActiveBounds.first != -1) {
result |= ~everActive.BufferAround(params->everActiveBounds);
}
if (params->maxComponentActiveCells != -1 && activePop > (unsigned)params->maxComponentActiveCells) {
for (auto &c : gen.active.Components()) {
auto componentPop = c.GetPop();
if(componentPop > (unsigned)params->maxComponentActiveCells)
return ~LifeState();
if(componentPop == (unsigned)params->maxComponentActiveCells)
result |= ~gen.active & c.BigZOI();
}
}
if (params->maxComponentEverActiveCells != -1 && everActive.GetPop() > (unsigned)params->maxComponentEverActiveCells) {
for (auto &c : everActive.Components()) {
auto componentPop = c.GetPop();
if(componentPop > (unsigned)params->maxComponentEverActiveCells)
return ~LifeState();
if(componentPop == (unsigned)params->maxComponentEverActiveCells)
result |= ~c & c.BigZOI();
}
}
if (params->componentEverActiveBounds.first != -1) {
for (auto &c : everActive.Components()) {
auto wh = c.WidthHeight();
if (wh.first > params->componentEverActiveBounds.first ||
wh.second > params->componentEverActiveBounds.second)
return ~LifeState();
result |= ~c.BufferAround(params->componentEverActiveBounds) & c.BigZOI();
}
}
if (params->maxCellActiveWindowGens != -1 &&
hasInteracted &&
gen.gen > interactionStart + (unsigned)params->maxCellActiveWindowGens)
result |= activeTimer.finished;
if (params->maxCellActiveStreakGens != -1 &&
hasInteracted &&
gen.gen > interactionStart + (unsigned)params->maxCellActiveStreakGens)
result |= streakTimer.finished;
if (params->maxCellStationaryDistance != -1) {
LifeState unchanging = ~(gen.changes | (gen.next.unknown & ~gen.next.unknownStable));
result |= unchanging.MatchLive(LifeState::NZOIAround({0, 0}, params->maxCellStationaryDistance));
}
return result;
}
LifeState SearchState::ForcedUnchangingCells(
const FrontierGeneration &gen,
const LifeState &everActive,
const LifeCountdown<maxCellActiveWindowGens> &activeTimer,
const LifeCountdown<maxCellActiveStreakGens> &streakTimer)
const {
LifeState result;
if (params->maxChanges != -1) {
unsigned changesPop = gen.changes.GetPop();
if (changesPop > (unsigned)params->maxChanges)
return ~LifeState();
if (changesPop == (unsigned)params->maxChanges) {
result |= ~gen.changes;
}
}
if (params->maxComponentChanges != -1) {
for (auto &c : gen.changes.Components()) {
unsigned changesPop = c.GetPop();
if (changesPop > (unsigned)params->maxComponentChanges)
return ~LifeState();
if (changesPop == (unsigned)params->maxComponentChanges) {
result |= ~gen.changes & c.BigZOI();
}
}
}
if (params->changesBounds.first != -1) {
result |= ~gen.changes.BufferAround(params->changesBounds);
}
if (params->componentChangesBounds.first != -1) {
for (auto &c : gen.changes.Components()) {
auto wh = c.WidthHeight();
if (wh.first > params->componentChangesBounds.first ||
wh.second > params->componentChangesBounds.second)
return ~LifeState();
result |= ~c.BufferAround(params->componentChangesBounds) & c.BigZOI();
}
}
if (params->hasStator)
result |= params->stator;
return result;
}
StableOptions OptionsFor(bool currentstate, bool nextstate, unsigned currenton,
unsigned unknown, unsigned stableon) {
// The possible current count for the neighbourhood, as a bitfield
unsigned currentmask = (1 << 9) - 1;
currentmask &= ((1 << (unknown + 1)) - 1) << currenton;
if (!currentstate && !nextstate) currentmask &= 0b111110111;
if (!currentstate && nextstate) currentmask &= 0b000001000;
if ( currentstate && !nextstate) currentmask &= 0b111110011;
if ( currentstate && nextstate) currentmask &= 0b000001100;
// The possible stable count for the neighbourhood, as a bitfield
unsigned stablemask = (currentmask >> currenton) << stableon;
StableOptions result = StableOptions::IMPOSSIBLE;
if ((1 << 2) & stablemask) result |= StableOptions::LIVE2;
if ((1 << 3) & stablemask) result |= StableOptions::LIVE3;
if ((1 << 0) & stablemask) result |= StableOptions::DEAD0;
if ((1 << 1) & stablemask) result |= StableOptions::DEAD1;
if ((1 << 2) & stablemask) result |= StableOptions::DEAD2;
if ((1 << 4) & stablemask) result |= StableOptions::DEAD4;
if ((1 << 5) & stablemask) result |= StableOptions::DEAD5;
if ((1 << 6) & stablemask) result |= StableOptions::DEAD6;
return result;
}
StableOptions SearchState::OptionsFor(const LifeUnknownState &state,
std::pair<int, int> cell,
Transition transition) const {
unsigned currenton = state.state.CountNeighbours(cell);
unsigned unknown = state.unknown.CountNeighbours(cell);
unsigned stableon = stable.state.CountNeighbours(cell);
StableOptions options;
switch (transition) {
case Transition::OFF_TO_OFF:
options = ::OptionsFor(false, false, currenton, unknown, stableon);
if (state.unknownStable.Get(cell))
options &= StableOptions::DEAD;
break;
case Transition::OFF_TO_ON:
options = ::OptionsFor(false, true, currenton, unknown, stableon);
if (state.unknownStable.Get(cell))
options &= StableOptions::DEAD;
break;
case Transition::ON_TO_OFF:
options = ::OptionsFor(true, false, currenton, unknown, stableon);
if (state.unknownStable.Get(cell))
options &= StableOptions::LIVE;
break;
case Transition::ON_TO_ON:
options = ::OptionsFor(true, true, currenton, unknown, stableon);
if (state.unknownStable.Get(cell))
options &= StableOptions::LIVE;
break;
case Transition::STABLE_TO_STABLE:
options = (::OptionsFor(false, false, currenton, unknown, stableon) & StableOptions::DEAD) |
(::OptionsFor(true, true, currenton, unknown, stableon) & StableOptions::LIVE);
break;
default:
options = StableOptions::IMPOSSIBLE;
}
return options;
}
bool SearchState::UpdateActive(FrontierGeneration &generation,
LifeCountdown<maxCellActiveWindowGens> &activeTimer,
LifeCountdown<maxCellActiveStreakGens> &streakTimer) {
generation.active = generation.next.ActiveComparedTo(stable) & stable.dead0 & ~params->exempt;
generation.changes = generation.next.ChangesComparedTo(generation.state) & stable.dead0 & ~params->exempt;
everActive |= generation.active;
generation.forcedInactive =
ForcedInactiveCells(generation, everActive, activeTimer, streakTimer) &
~params->exempt;
if (!(generation.active & generation.forcedInactive).IsEmpty())
return false;
generation.forcedUnchanging =
ForcedUnchangingCells(generation, everActive, activeTimer, streakTimer) &
~params->exempt;
if (!(generation.changes & generation.forcedUnchanging).IsEmpty())
return false;
return true;
}
std::pair<bool, bool> SearchState::SetForced(FrontierGeneration &generation) {
bool anyChanges = false;
LifeState remainingCells = generation.frontierCells;
for (auto cell = remainingCells.FirstOn(); cell != std::make_pair(-1, -1);
remainingCells.Erase(cell), cell = remainingCells.FirstOn()) {
stable.SynchroniseStateKnown(cell);
generation.state.TransferStable(stable, cell);
generation.next.TransferStable(stable, cell);
auto allowedTransitions = generation.AllowedTransitions(stable, cell);
if (allowedTransitions == Transition::IMPOSSIBLE) {
return {false, false};
}
auto startingOptions = stable.GetOptions(cell);
auto possibleOptions = StableOptions::IMPOSSIBLE;
// See which options and transitions can be actually realised
auto remainingTransitions = allowedTransitions;
for (auto transition = TransitionHighest(remainingTransitions);
remainingTransitions != Transition::IMPOSSIBLE;
remainingTransitions &= ~transition, transition = TransitionHighest(remainingTransitions)) {
auto transitionOptions = startingOptions & OptionsFor(generation.state, cell, transition);
possibleOptions |= transitionOptions;
if (transitionOptions == StableOptions::IMPOSSIBLE)
allowedTransitions &= ~transition;
}
auto newOptions = possibleOptions & startingOptions;
if (newOptions == StableOptions::IMPOSSIBLE)
return {false, false};
stable.RestrictOptions(cell, newOptions);
stable.SynchroniseStateKnown(cell);
bool alreadyFixed = startingOptions == newOptions;
if (!alreadyFixed) {
anyChanges = true;
}
allowedTransitions = TransitionSimplify(allowedTransitions);
// Force the transition to occur if it is the only one allowed
if (TransitionIsSingleton(allowedTransitions)) {
auto transition = allowedTransitions;
generation.SetTransition(cell, transition);
generation.frontierCells.Erase(cell);
if (generation.state.TransitionIsActive(cell, transition)) {
everActive.Set(cell);
}
// stable.SanityCheck();
// generation.prev.SanityCheck(stable);
// generation.state.SanityCheck(stable);
}
}
return {true, anyChanges};
}
std::tuple<bool, bool> SearchState::PopulateFrontier() {
bool anyChanges = false;
frontier.state.TransferStable(stable);
LifeUnknownState lookahead = frontier.state;
unsigned gen = currentGen;
auto lookaheadActiveTimer = activeTimer;
auto lookaheadStreakTimer = streakTimer;
for (unsigned i = 0; i < maxFrontierGens; i++) {
gen++;
FrontierGeneration generation;
generation.state = lookahead;
generation.next = lookahead.StepMaintaining(stable);
generation.gen = gen;
bool updateresult = UpdateActive(generation, lookaheadActiveTimer, lookaheadStreakTimer);
if (!updateresult)
return {false, false};
if (params->maxCellActiveWindowGens != -1) {
lookaheadActiveTimer.Start(generation.active);
lookaheadActiveTimer.Tick();
}
if (params->maxCellActiveStreakGens != -1) {
lookaheadStreakTimer.Reset(~generation.active);
lookaheadStreakTimer.Start(generation.active);
lookaheadStreakTimer.Tick();
}
LifeState prevUnknownActive = generation.state.unknown & ~generation.state.unknownStable;
LifeState becomeUnknown = (generation.next.unknown & ~generation.next.unknownStable) & ~prevUnknownActive;
generation.frontierCells = becomeUnknown & ~prevUnknownActive.ZOI();
if (i == 0)
frontier = generation;
auto [result, someForced] = SetForced(generation);
if (!result)
return {false, false};
anyChanges = anyChanges || someForced;
bool isInert = ((generation.state.state ^ generation.next.state) &
~generation.state.unknown & ~generation.next.unknown)
.IsEmpty() ||
(stable.dead0 & ~params->exempt & ~generation.next.unknown).IsEmpty();
if (isInert)
break;
lookahead = generation.next;
}
return {true, anyChanges};
}
bool SearchState::UpdateFrontierStrip(unsigned column) {
stable.SynchroniseStateKnown();
frontier.state.TransferStable(stable);
auto stripState = frontier.state.state.GetStrip<4>(column);
auto stripUnknown = frontier.state.unknown.GetStrip<4>(column);
auto stripUnknownStable = frontier.state.unknownStable.GetStrip<4>(column);
std::tie(stripState, stripUnknown, stripUnknownStable) = frontier.state.StepMaintainingStrip(stable, column);
frontier.next.state.SetStrip<4>(column, stripState);
frontier.next.unknown.SetStrip<4>(column, stripUnknown);
frontier.next.unknownStable.SetStrip<4>(column, stripUnknownStable);
bool updateresult = UpdateActive(frontier, activeTimer, streakTimer);
if (!updateresult)
return false;
return true;
}
std::pair<bool, bool> SearchState::TryAdvance() {
bool didAdvance = false;
bool done = false;
while (!done) {
if (!(frontier.next.unknown & ~frontier.next.unknownStable).IsEmpty())
break;
didAdvance = true;
frontier.state = frontier.next;
frontier.next = frontier.next.StepMaintaining(stable);
currentGen += 1;
LifeState active = frontier.state.ActiveComparedTo(stable) & stable.dead0 & ~params->exempt;
everActive |= active;
if (params->maxCellActiveWindowGens != -1) {
activeTimer.Start(active);
activeTimer.Tick();
}
if (params->maxCellActiveStreakGens != -1) {
streakTimer.Reset(~active);
streakTimer.Start(active);
streakTimer.Tick();
}
if (hasInteracted) {
bool isRecovered = active.IsEmpty();
if (isRecovered)
recoveredTime++;
else
recoveredTime = 0;
if (isRecovered && recoveredTime == params->minStableInterval) {
if(!params->reportOscillators)
RecordSolution();
if(!params->continueAfterSuccess)
return {false, false};
}
if (currentGen > interactionStart + params->maxActiveWindowGens) {
if (params->reportOscillators)
RecordOscillator();
return {false, false};
}
} else {
if (currentGen >= params->maxFirstActiveGen)
return {false, false};
}
}
return {true, didAdvance};
}
bool SearchState::CalculateFrontier() {
unsigned rounds = 0;
bool anyChanges = true;
while (anyChanges) {
anyChanges = false;
rounds++;
if (rounds > maxCalculateRounds)
break;
auto [consistent, someChanges] = PopulateFrontier();
if (!consistent) {
return false;
}
anyChanges = anyChanges || someChanges;
// This is more important now than in old Barrister: we otherwise
// spend a fair bit of time searching uncompletable parts of the
// search space
LifeState toTest = stable.Vulnerable() & stable.Differences(lastTest).ZOI();
lastTest = stable;
auto propagateResult = stable.TestUnknowns(toTest);
if (!propagateResult.consistent) {
return false;
}
anyChanges = anyChanges || propagateResult.changed;
propagateResult = stable.Propagate();
if (!propagateResult.consistent) {
return false;
}
anyChanges = anyChanges || propagateResult.changed;
stable.SanityCheck();
}
if (params->hasForbidden) {
for(auto &f : params->forbiddens) {
bool allKnown = (f.mask & stable.unknown).IsEmpty();
if (!allKnown)
continue;
bool matches = ((stable.state ^ f.state) & f.mask).IsEmpty();
if (allKnown && matches)
return false;
}
}
frontier.state.TransferStable(stable);
frontier.next.TransferStable(stable);
auto [consistent, didAdvance] = TryAdvance();
if (!consistent)
return false;
if (didAdvance) {
// We have to start over
[[clang::musttail]]
return CalculateFrontier();
}
return true;
}
bool SearchState::RefineFrontier() {
stable.SynchroniseStateKnown();
frontier.state.TransferStable(stable);
frontier.next.TransferStable(stable);
bool updateresult = UpdateActive(frontier, activeTimer, streakTimer);
if (!updateresult) {
return false;
}
auto [consistent, changed] = SetForced(frontier);
if (!consistent) {
return false;
}
return true;
}
std::pair<unsigned, std::pair<int, int>> SearchState::ChooseBranchCell() const {
// unsigned stopGen = std::min(frontier.size, maxBranchingGens);
// Prefer unknown stable cells?
// Prefer lower numbers of possible transitions?
// Prefer cells where all options are active?
// for (unsigned i = 0; i < generations.size(); i++) {
// std::pair<int, int> branchCell = generations[i].frontierCells.FirstOn();
// if (branchCell.first != -1) {
// auto allowedTransitions = ::AllowedTransitions(generations[i], stable, branchCell);
// if ((allowedTransitions & Transition::STABLE_TO_STABLE) != Transition::STABLE_TO_STABLE)
// // if(TransitionCount(allowedTransitions) <= 3)
// return {i, branchCell};
// }
// }
// for (unsigned i = frontier.start; i < frontier.start + stopGen; i++) {
// auto &g = frontier.generations[i];
// auto branchCell = g.frontierCells.FirstOn();
// if (branchCell.first != -1)
// return {i, branchCell};
// }
LifeState remainingCells = frontier.frontierCells;
for (auto cell = remainingCells.FirstOn(); cell != std::make_pair(-1, -1);
remainingCells.Erase(cell), cell = remainingCells.FirstOn()) {
auto allowedTransitions = frontier.AllowedTransitions(stable, cell);
if(TransitionCount(allowedTransitions) <= 2)
return {0, cell};
}
auto branchCell = frontier.frontierCells.FirstOn();
if (branchCell.first != -1)
return {0, branchCell};
return {0, {-1, -1}};
}
void SearchState::SearchStep() {
#ifdef DEBUG
if (params->hasOracle) {
if (!stable.CompatibleWith(params->oracle))
return;
}
#endif
if(frontier.frontierCells.IsEmpty() || timeSincePropagate >= maxBranchFastCount){
bool consistent = CalculateFrontier();
if (!consistent)
return;
timeSincePropagate = 0;
stable.SanityCheck();
// SanityCheck();
} else {
timeSincePropagate++;
bool consistent = RefineFrontier();
if (!consistent)
return;
if (frontier.frontierCells.IsEmpty()) {
bool consistent = CalculateFrontier();
if (!consistent)
return;
timeSincePropagate = 0;
}
}
auto [i, branchCell] = ChooseBranchCell();
assert(branchCell.first != -1);
stable.SynchroniseStateKnown(branchCell);
frontier.state.TransferStable(stable, branchCell);
auto allowedTransitions = frontier.AllowedTransitions(stable, branchCell);
allowedTransitions = TransitionSimplify(allowedTransitions);
// The cell should not still be in the frontier in this case
assert(allowedTransitions != Transition::IMPOSSIBLE);
assert(!TransitionIsSingleton(allowedTransitions));
// Loop over the possible transitions
for (auto transition = TransitionHighest(allowedTransitions);
!TransitionIsSingleton(allowedTransitions);
allowedTransitions &= ~transition, transition = TransitionHighest(allowedTransitions)) {
auto newoptions = stable.GetOptions(branchCell) & OptionsFor(frontier.state, branchCell, transition);
if (newoptions == StableOptions::IMPOSSIBLE)
continue;
SearchState newSearch = *this;
newSearch.stable.RestrictOptions(branchCell, newoptions);
newSearch.stable.SynchroniseStateKnown(branchCell);
auto propagateResult = newSearch.stable.PropagateStrip(branchCell.first);
if (!propagateResult.consistent)
continue;
newSearch.frontier.frontierCells.Erase(branchCell);
newSearch.frontier.SetTransition(branchCell, transition);
if (frontier.state.TransitionIsPerturbation(branchCell, transition)) {
if(transition == Transition::OFF_TO_ON || transition == Transition::ON_TO_OFF)
newSearch.everActive.Set(branchCell);
if (!hasInteracted) {
newSearch.hasInteracted = true;
newSearch.interactionStart = currentGen;
*stableAtInteraction = stable;
}
}
newSearch.SearchStep();
}
// TODO: move body to a function, make sure it becomes a tail call correctly
{
auto transition = allowedTransitions;
auto newoptions = stable.GetOptions(branchCell) & OptionsFor(frontier.state, branchCell, transition);
if (newoptions == StableOptions::IMPOSSIBLE)
return;
SearchState &newSearch = *this;
newSearch.stable.RestrictOptions(branchCell, newoptions);
newSearch.stable.SynchroniseStateKnown(branchCell);
auto propagateResult = newSearch.stable.PropagateStrip(branchCell.first);
if (!propagateResult.consistent)
return;
newSearch.frontier.frontierCells.Erase(branchCell);
newSearch.frontier.SetTransition(branchCell, transition);
if (frontier.state.TransitionIsPerturbation(branchCell, transition)) {
if(transition == Transition::OFF_TO_ON || transition == Transition::ON_TO_OFF)
newSearch.everActive.Set(branchCell);
if (!hasInteracted) {
newSearch.hasInteracted = true;
newSearch.interactionStart = currentGen;
*stableAtInteraction = stable;
}
}
[[clang::musttail]]
return newSearch.SearchStep();
}
}
SearchState::SearchState(SearchParams &inparams,
std::vector<Solution> &outsolutions,
std::set<std::string> &outrotors,
LifeStableState &inStableAtInteraction)
: currentGen{0}, hasInteracted{false}, interactionStart{0} {
params = &inparams;
allSolutions = &outsolutions;
seenRotors = &outrotors;
stableAtInteraction = &inStableAtInteraction;
stable = inparams.stable;
frontier.state = inparams.startingState;
frontier.next = frontier.state.StepMaintaining(stable);
timeSincePropagate = 0;
everActive = LifeState();
activeTimer = LifeCountdown<maxCellActiveWindowGens>(params->maxCellActiveWindowGens);
streakTimer = LifeCountdown<maxCellActiveStreakGens>(params->maxCellActiveStreakGens);
TryAdvance();
}
void SearchState::PrintSolution(const Solution &solution) {
std::cout << "Winner:" << std::endl;
std::cout << "x = 0, y = 0, rule = LifeBellman" << std::endl;
LifeState state = params->startingState.state | solution.stable.state;
LifeState marked = solution.stable.unknown | solution.stable.state;
LifeState startingOff = (params->stable.state & ~params->startingState.state);
state &= ~startingOff;
marked &= ~startingOff;
std::cout << LifeBellmanRLEFor(state, marked) << std::endl;
switch (solution.completionResult) {
case CompletionResult::COMPLETED:
std::cout << "Completed:" << std::endl;
std::cout << solution.state.RLE() << std::endl;
break;
case CompletionResult::INCONSISTENT:
std::cout << "Completion Failed: Inconsistent" << std::endl;
std::cout << LifeState().RLE() << std::endl;
break;
case CompletionResult::TIMEOUT:
std::cout << "Completion Failed: Timeout" << std::endl;
std::cout << LifeState().RLE() << std::endl;
break;
}
}
void SearchState::RecordOscillator() {
unsigned period = DeterminePeriod(frontier.state, stable);
if (period >= params->reportOscillatorsMinPeriod) {
std::cout << "Oscillating! Period: " << period << std::endl;
if(!(everActive.ZOI() & stable.unknown).IsEmpty()) {
auto [result, completed] = stable.CompleteStable(
params->stabiliseResultsTimeout, params->minimiseResults);
if(!completed.IsEmpty()) {
stable.SetOn(completed);
stable.SetOff(~completed);
frontier.state.TransferStable(stable);
}
}
for(auto &r : GetSeparatedRotorDesc(frontier.state, stable, period)) {
auto rotorDesc = r.ToString();
if (seenRotors->contains(rotorDesc))
std::cout << "Known Rotor: " << rotorDesc << std::endl;
else {
seenRotors->insert(rotorDesc);
std::cout << "New Rotor: " << rotorDesc << std::endl;
RecordSolution();
}
}
}
}
void SearchState::RecordSolution() {
Solution solution;
solution.stable = stable;
solution.interactionStable = *stableAtInteraction;
solution.interactionGen = interactionStart;
solution.recoveryGen = currentGen - params->minStableInterval + 1;
if (params->stabiliseResults) {
std::tie(solution.completionResult, solution.completed) = stable.CompleteStable(params->stabiliseResultsTimeout, params->minimiseResults);
}
LifeState startingActive = params->startingState.state & ~params->stable.state;
LifeState startingStableOff = params->stable.state & ~params->startingState.state;
solution.state = (stable.state | startingActive | solution.completed) & ~startingStableOff;
allSolutions->push_back(solution);
if (!params->metasearch)
PrintSolution(solution);
}
void SearchState::SanityCheck() {
#ifdef DEBUG
frontier.state.SanityCheck(stable);
assert((stable.state & stable.unknown).IsEmpty());
LifeStableState copy = stable;
auto result = copy.Propagate();
assert(result.consistent);
assert(copy == stable); // The stable state should be fully propagated
LifeStableState copycopy = copy;
copycopy.Propagate();
assert(copycopy == copy);
LifeUnknownState startingStable = {stable.state, stable.unknown, stable.unknown};
LifeUnknownState steppedStable = startingStable.StepMaintaining(stable);
assert(startingStable == steppedStable);
#endif
}
void PrintSummary(std::vector<Solution> &pats, std::ostream &out) {
out << "x = 0, y = 0, rule = B3/S23" << std::endl;
for (unsigned i = 0; i < pats.size(); i += 8) {
std::vector<Solution> rowSolutions = std::vector<Solution>(pats.begin() + i, pats.begin() + std::min((unsigned)pats.size(), i + 8));