Repository navigation
Expand file tree
/
Copy pathStomp.cpp
More file actions
1177 lines (964 loc) · 39.4 KB
/
Copy pathStomp.cpp
File metadata and controls
1177 lines (964 loc) · 39.4 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 <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <filesystem>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <limits>
#include <functional>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include "../Component.hpp"
#include "../ComponentTemplate.hpp"
#include "ComponentDatabase.hpp"
#include "TemplateCache.hpp"
#include "CLI11/include/CLI/CLI.hpp"
template<typename T>
class ThreadSafeQueue {
private:
std::priority_queue<T, std::vector<T>, std::greater<T>> queue_;
mutable std::mutex mutex_;
std::condition_variable condition_;
std::atomic<int> waiting_threads_{0};
std::atomic<int> active_threads_{0};
std::atomic<bool> shutdown_{false};
public:
void push(const T& item) {
std::lock_guard<std::mutex> lock(mutex_);
if (shutdown_) return;
queue_.push(item);
condition_.notify_one();
}
bool pop(T& item) {
std::unique_lock<std::mutex> lock(mutex_);
while (true) {
if (shutdown_) {
return false;
}
if (!queue_.empty()) {
item = queue_.top();
queue_.pop();
return true;
}
// Queue is empty, increment waiting threads
++waiting_threads_;
// Check if all threads are waiting (meaning no one is actively processing)
if (waiting_threads_ == active_threads_) {
// All threads are waiting and queue is empty - time to shutdown
shutdown_ = true;
--waiting_threads_;
condition_.notify_all();
return false;
}
// Wait for either new items or shutdown
condition_.wait(lock, [this] {
return !queue_.empty() || shutdown_;
});
--waiting_threads_;
}
}
void register_thread() {
++active_threads_;
}
void unregister_thread() {
--active_threads_;
}
bool empty() const {
std::lock_guard<std::mutex> lock(mutex_);
return queue_.empty();
}
size_t size() const {
std::lock_guard<std::mutex> lock(mutex_);
return queue_.size();
}
int waiting_threads() const {
return waiting_threads_.load();
}
int active_threads() const {
return active_threads_.load();
}
void shutdown() {
std::lock_guard<std::mutex> lock(mutex_);
shutdown_ = true;
condition_.notify_all();
}
};
class TransferSynthesis {
public:
// Structure to hold a synthesis result
struct SynthesisResult {
Component component;
std::string precursorApgcode;
std::string targetApgcode;
bool valid; // Unused?
SynthesisResult() : valid(false) {}
SynthesisResult(const Component& comp, const std::string& precursor, const std::string& target)
: component(comp), precursorApgcode(precursor), targetApgcode(target), valid(true) {}
};
static std::vector<std::string> ReadTargetFile(const std::string& filename);
static std::vector<std::string> GetMostExpensiveTargets(
const std::unordered_map<std::string, SearchResult>& dijkstraResults,
int countPerClass, int minPopulation, int maxPopulation, int specificPopulation,
bool includePseudo, bool verbose);
// Filter target objects, optionally skipping those with existing synthesis paths
static std::vector<std::string> FilterTargetObjects(
const std::vector<std::string>& objects,
const std::unordered_map<std::string, SearchResult>& minPaths,
bool skipExisting = false);
// Check if a synthesis result is promising (filters out hopeless cases like distant blocks/tubs)
static bool IsSparse(const LifeState &state);
static bool IsSparse(const LifeState &state, const std::vector<LifeState> &components);
static bool IsPromising(const SynthesisResult& synthesis);
// Find all possible synthesis steps for a given pattern
static std::vector<SynthesisResult> FindSynthesisSteps(
const LifeState &targetPattern,
const std::vector<ComponentTemplate> &templates,
const std::unordered_map<std::string, SearchResult> &minPaths);
static void RunSynthesis(
const std::vector<std::string> &transferComponentFiles,
const std::vector<std::string> &objects,
const std::unordered_map<std::string, SearchResult> &minPaths,
int maxDepth = 1,
int maxPrecursorPop = 30,
bool skipExisting = false,
bool acceptFirst = false,
int numThreads = 1,
unsigned minTemplateOccurrences = 1,
bool outputVisitedApgcodes = false,
const std::string& cacheDir = "./template_cache",
bool useCache = true,
const std::unordered_map<std::string, std::vector<std::tuple<unsigned, std::string, std::string>>>& reverseLookup = {});
private:
using QueueEntry = std::tuple<int, int, std::string>; // population, depth, apgcode
// Context object to reduce parameter passing
struct SearchContext {
ComponentDatabase& miniDb;
ThreadSafeQueue<QueueEntry>& searchQueue;
std::unordered_set<std::string>& processed;
std::unordered_set<std::string>& allVisitedApgcodes;
const std::vector<ComponentTemplate>& templates;
const std::unordered_map<std::string, SearchResult>& minPaths;
const std::unordered_map<std::string, std::vector<std::tuple<unsigned, std::string, std::string>>>& reverseLookup;
// Configuration
int maxDepth;
int maxPrecursorPop;
bool outputVisitedApgcodes;
bool acceptFirst;
// Shared counters
std::atomic<int>& processCount;
// Synchronization
std::mutex& processedMutex;
std::mutex& miniDbMutex;
std::mutex& visitedApgcodesMutex;
std::mutex& cerrMutex;
std::atomic<bool>& shouldStop;
};
// Worker thread function for processing search queue entries
static void ProcessSearchQueue(SearchContext& ctx);
// Process a single synthesis result
static void ProcessSynthesis(
SynthesisResult& synthesis,
SearchContext& ctx,
int depth);
// Add database precursors to search queue
static void AddDatabasePrecursors(
const std::string& currentApgcode,
SearchContext& ctx,
int depth);
};
std::vector<TransferSynthesis::SynthesisResult> TransferSynthesis::FindSynthesisSteps(
const LifeState& targetPattern,
const std::vector<ComponentTemplate>& templates,
const std::unordered_map<std::string, SearchResult>& minPaths) {
std::vector<SynthesisResult> results;
std::string targetApgcode = targetPattern.EncodeApgcode();
NeighbourCount stateCount(targetPattern);
for (const ComponentTemplate& templ : templates) {
LifeState matches = templ.MatchReverse(targetPattern, stateCount);
for (auto [x, y] : matches.OnCells()) {
try {
LifeState transformedBase = templ.base.Moved(x, y);
LifeState transformedOut = templ.out.Moved(x, y);
Component resultComp;
resultComp.base = (targetPattern & ~transformedOut) | transformedBase;
resultComp.gliderSet = templ.gliderSet.Moved({x, y});
resultComp.out = targetPattern;
resultComp.ShiftToFitTorus();
if (!resultComp.SanityCheck()) continue;
std::string precursorApgcode = resultComp.base.EncodeApgcode();
results.emplace_back(resultComp, precursorApgcode, targetApgcode);
} catch (const std::exception&) {
continue;
}
}
}
return results;
}
std::vector<std::string> TransferSynthesis::FilterTargetObjects(
const std::vector<std::string>& objects,
const std::unordered_map<std::string, SearchResult>& minPaths,
bool skipExisting) {
// Filter objects to only xs patterns
std::vector<std::string> xsObjects;
for (const auto& obj : objects) {
if (obj.substr(0, 2) == "xs") {
xsObjects.push_back(obj);
}
}
// If skipExisting is enabled, filter out objects that already have complete synthesis paths
if (skipExisting) {
std::vector<std::string> filteredObjects;
for (const auto& obj : xsObjects) {
if (minPaths.find(obj) == minPaths.end()) {
filteredObjects.push_back(obj); // Keep only objects without synthesis paths
}
}
size_t originalCount = xsObjects.size();
xsObjects = std::move(filteredObjects);
std::cerr << "Filtered from " << originalCount << " to " << xsObjects.size()
<< " objects without complete synthesis paths" << std::endl;
}
return xsObjects;
}
bool TransferSynthesis::IsSparse(const LifeState &state) {
return IsSparse(state, state.StillComponents());
}
bool TransferSynthesis::IsSparse(const LifeState &state, const std::vector<LifeState> &components) {
// Single component is not sparse
if (components.size() <= 1) {
return false;
}
// // Bounding box strategy: check if components are too distant
// auto originalBounds = state.XYBounds();
// int originalWidth = originalBounds[2] - originalBounds[0];
// int originalHeight = originalBounds[3] - originalBounds[1];
// int originalArea = originalWidth * originalHeight;
// // Density check: if pattern is too sparse overall, likely not promising
// int population = state.GetPop();
// double density = (double)population / originalArea;
// if (density < 0.05) {
// return true;
// }
LifeState largest;
unsigned largest_pop = 0;
for (const auto &component : components) {
unsigned pop = component.GetPop();
if (pop > largest_pop) {
largest = component;
largest_pop = pop;
}
}
LifeState nearby = state.ComponentContaining(
state & largest.Convolve(
LifeState::ConstantParse("7o$7o$7o$7o$7o$7o$7o!", -3, -3)),
LifeState::ConstantParse("5o$5o$5o$5o$5o!", -2, -2));
if (!(state & ~nearby).IsEmpty())
return true;
// ALSO OLD
// auto newBounds = largest.XYBounds();
// int newWidth = newBounds[2] - newBounds[0];
// int newHeight = newBounds[3] - newBounds[1];
// int newArea = newWidth * newHeight;
// double areaShrinkage = 1.0 - (double)newArea / originalArea;
// if (areaShrinkage > 0.3) {
// return true;
// }
// OLD
// for (const auto& component : components) {
// LifeState remaining = state & ~component;
// if (remaining.IsEmpty()) continue;
// auto newBounds = remaining.XYBounds();
// int newWidth = newBounds[2] - newBounds[0];
// int newHeight = newBounds[3] - newBounds[1];
// int newArea = newWidth * newHeight;
// double areaShrinkage = 1.0 - (double)newArea / originalArea;
// if (areaShrinkage > 0.4) {
// return true;
// }
// }
return false;
}
bool TransferSynthesis::IsPromising(const SynthesisResult& synthesis) {
// // Filter out patterns with very small components (blocks, etc.)
// for (const auto& component : components) {
// if (component.GetPop() <= 4) {
// std::cerr << "Unpromising small component " << synthesis.precursorApgcode << std::endl;
// return false;
// }
// }
// Pure additions are always fine:
if ((synthesis.component.base & ~synthesis.component.out).IsEmpty()) {
return true;
}
auto base_components = synthesis.component.base.StillComponents();
auto out_components = synthesis.component.out.StillComponents();
if (IsSparse(synthesis.component.base, base_components) &&
IsSparse(synthesis.component.out, out_components)) {
// std::cerr << "Unpromising density " << synthesis.precursorApgcode << std::endl;
return false;
}
LifeState base_largest;
unsigned base_largest_pop = 0;
for (const auto &component : base_components) {
unsigned pop = component.GetPop();
if (pop > base_largest_pop) {
base_largest = component;
base_largest_pop = pop;
}
}
// Steps that interact with the largest component without touching
// any smaller ones are not promising
if (base_components.size() > 1 && !((synthesis.component.base ^ synthesis.component.out) & synthesis.component.base.ZOI()).IsEmpty()) {
LifeState smaller_components = synthesis.component.base & ~base_largest;
if ((smaller_components & ~synthesis.component.out).IsEmpty())
return false;
}
// Steps that just shove a small still life around are not promising
LifeState nearbyDiff = (synthesis.component.base ^ synthesis.component.out) & base_largest.ZOI();
if(nearbyDiff.IsEmpty()) {
LifeState before = synthesis.component.base & ~base_largest.ZOI();
LifeState after = synthesis.component.out & ~base_largest.ZOI();
// bool beforeSmall = !before.IsEmpty() && before.GetPop() <= 8 && before.Stepped() == before;
// bool afterSmall = !after.IsEmpty() && after.GetPop() <= 8 && after.Stepped() == after;
bool beforeSmall = before.Stepped() == before;
bool afterSmall = after.Stepped() == after;
if (beforeSmall && afterSmall)
return false;
}
return true;
}
void TransferSynthesis::RunSynthesis(
const std::vector<std::string> &transferComponentFiles,
const std::vector<std::string> &objects,
const std::unordered_map<std::string, SearchResult> &minPaths,
int maxDepth,
int maxPrecursorPop,
bool skipExisting,
bool acceptFirst,
int numThreads,
unsigned minTemplateOccurrences,
bool outputVisitedApgcodes,
const std::string& cacheDir,
bool useCache,
const std::unordered_map<std::string, std::vector<std::tuple<unsigned, std::string, std::string>>>& reverseLookup) {
// Load component templates using cache
TemplateCache templateCache;
std::vector<ComponentTemplate> templates = templateCache.LoadTemplates(
transferComponentFiles, true, minTemplateOccurrences, cacheDir, useCache);
// Build mini synthesis database using ComponentDatabase
ComponentDatabase miniDb;
// std::unordered_set<std::string> processed;
int successCount = 0;
int improvedCount = 0;
int targetIndex = 0;
for (const auto& target : objects) {
targetIndex++;
// Determine target cost based on existing synthesis
unsigned targetCost = std::numeric_limits<unsigned>::max();
bool hasExisting = false;
auto it = minPaths.find(target);
if (it != minPaths.end()) {
targetCost = it->second.cost;
hasExisting = true;
}
std::cerr << "[" << targetIndex << "/" << objects.size() << "] Searching for " << target;
if (hasExisting) {
std::cerr << " (trying to beat cost " << targetCost << ")";
} else {
std::cerr << " (new synthesis)";
}
std::cerr << std::endl;
// Build mini database for multi-step synthesis
miniDb.db.clear();
std::unordered_set<std::string> processed;
// Thread-safe queue for multithreaded processing
ThreadSafeQueue<QueueEntry> searchQueue;
// Mutexes for shared data structures
std::mutex processedMutex;
std::mutex miniDbMutex;
std::mutex cerrMutex;
std::atomic<bool> shouldStop{false};
// Collection for all queue apgcodes (if enabled)
std::unordered_set<std::string> allVisitedApgcodes;
std::mutex visitedApgcodesMutex;
// Get population of target
int targetPop = 0;
try {
LifeState targetPattern = LifeState::DecodeApgcode(target);
targetPop = targetPattern.GetPop();
} catch (const std::exception&) {
continue;
}
searchQueue.push({targetPop, 0, target});
{
std::lock_guard<std::mutex> lock(cerrMutex);
std::cerr << " Starting search with " << numThreads << " threads" << std::endl;
}
std::atomic<int> processCount{0};
SearchContext ctx = {
.miniDb = miniDb,
.searchQueue = searchQueue,
.processed = processed,
.allVisitedApgcodes = allVisitedApgcodes,
.templates = templates,
.minPaths = minPaths,
.reverseLookup = reverseLookup,
.maxDepth = maxDepth,
.maxPrecursorPop = maxPrecursorPop,
.outputVisitedApgcodes = outputVisitedApgcodes,
.acceptFirst = acceptFirst,
.processCount = processCount,
.processedMutex = processedMutex,
.miniDbMutex = miniDbMutex,
.visitedApgcodesMutex = visitedApgcodesMutex,
.cerrMutex = cerrMutex,
.shouldStop = shouldStop
};
// Create worker threads
std::vector<std::thread> workers;
for (int i = 0; i < numThreads; ++i) {
workers.emplace_back(ProcessSearchQueue, std::ref(ctx));
}
// Wait for all workers to complete
for (auto& worker : workers) {
worker.join();
}
auto results = miniDb.Dijkstra();
unsigned foundCost = std::numeric_limits<unsigned>::max();
auto targetIt = results.find(target);
if (targetIt != results.end()) {
foundCost = targetIt->second.cost;
if (foundCost < targetCost) {
// Output the synthesis components by following the path
std::string current = target;
std::vector<std::string> synthesisPath;
while (!current.empty()) {
auto resultIt = results.find(current);
if (resultIt == results.end() || resultIt->second.predecessor.empty()) break;
if (!resultIt->second.componentLine.empty())
synthesisPath.push_back(resultIt->second.componentLine);
current = resultIt->second.predecessor;
}
// Output components in synthesis order
for (auto it = synthesisPath.rbegin(); it != synthesisPath.rend(); ++it) {
std::cout << *it << std::endl;
}
}
}
if (foundCost != std::numeric_limits<unsigned>::max()) {
successCount++;
if (hasExisting && foundCost < targetCost) {
improvedCount++;
std::cerr << " ✓ Improved: cost " << targetCost << " → " << foundCost << std::endl;
} else if (!hasExisting) {
std::cerr << " ✓ New synthesis: cost " << foundCost << std::endl;
} else {
std::cerr << " = No improvement (cost " << targetCost << ")" << std::endl;
}
} else {
std::cerr << " ✗ No synthesis found" << std::endl;
}
if (outputVisitedApgcodes) {
std::cerr << "Queue apgcodes for " << target << ":" << std::endl;
for (const auto& apgcode : allVisitedApgcodes) {
std::cout << apgcode << std::endl;
}
}
}
std::cerr << "Synthesis complete: " << successCount << "/" << objects.size()
<< " targets synthesised";
if (improvedCount > 0) {
std::cerr << " (" << improvedCount << " improved)";
}
std::cerr << std::endl;
}
void TransferSynthesis::ProcessSearchQueue(SearchContext& ctx) {
ctx.searchQueue.register_thread();
QueueEntry entry;
while (ctx.searchQueue.pop(entry)) {
if (ctx.shouldStop.load()) {
break;
}
auto [population, depth, currentApgcode] = entry;
// Collect apgcode if output is enabled
if (ctx.outputVisitedApgcodes) {
std::lock_guard<std::mutex> lock(ctx.visitedApgcodesMutex);
ctx.allVisitedApgcodes.insert(currentApgcode);
}
// Check if already processed
{
std::lock_guard<std::mutex> lock(ctx.processedMutex);
if (ctx.processed.find(currentApgcode) != ctx.processed.end()) {
continue;
}
ctx.processed.insert(currentApgcode);
}
// Check database for early termination (non-max-depth patterns)
auto it = ctx.minPaths.find(currentApgcode);
if (it != ctx.minPaths.end()) {
// Add to mini database as a seed
{
std::lock_guard<std::mutex> lock(ctx.miniDbMutex);
ctx.miniDb.db[""].emplace_back(it->second.cost, currentApgcode, ">>" + currentApgcode);
}
// if (it->second.cost + depth <= targetCost)
{
std::lock_guard<std::mutex> lock(ctx.cerrMutex);
std::string indent(2 + depth, ' ');
std::cerr << indent << "Found in database: " << currentApgcode << " (cost " << it->second.cost << ")" << std::endl;
}
// If accept-first is enabled and we found a synthesis, stop searching
if (ctx.acceptFirst) {
{
std::lock_guard<std::mutex> lock(ctx.cerrMutex);
std::cerr << " Accept-first: stopping search early" << std::endl;
}
ctx.shouldStop.store(true);
ctx.searchQueue.shutdown();
break;
}
}
// Verbose output for interesting cases
int currentCount = ++ctx.processCount;
if (depth < 2 || currentCount % 50 == 0) {
std::lock_guard<std::mutex> lock(ctx.cerrMutex);
std::string indent(2 + depth, ' ');
std::cerr << indent << "Processing depth " << depth << ", pop " << population
<< ", queue size " << ctx.searchQueue.size() << ": " << currentApgcode << std::endl;
}
if (depth == ctx.maxDepth)
continue;
try {
LifeState targetPattern = LifeState::DecodeApgcode(currentApgcode);
auto orientations = targetPattern.SymmetryOrbit();
for (const LifeState& pattern : orientations) {
auto syntheses = FindSynthesisSteps(pattern, ctx.templates, ctx.minPaths);
for (auto& synthesis : syntheses) {
ProcessSynthesis(synthesis, ctx, depth);
if (ctx.shouldStop.load()) {
break;
}
}
}
// if (depth <= 1)
// AddDatabasePrecursors(currentApgcode, ctx, depth);
} catch (const std::exception&) {
continue;
}
if (ctx.shouldStop.load()) {
break;
}
}
ctx.searchQueue.unregister_thread();
}
void TransferSynthesis::ProcessSynthesis(
SynthesisResult& synthesis,
SearchContext& ctx,
int depth) {
int maxPop = depth == ctx.maxDepth - 1 ? std::numeric_limits<int>::max() : ctx.maxPrecursorPop;
if (synthesis.component.base.GetPop() > maxPop) {
auto components = synthesis.component.base.StillComponents();
unsigned largest_pop = 0;
for (const auto &component : components) {
unsigned pop = component.GetPop();
if (pop > largest_pop) {
largest_pop = pop;
}
}
if(largest_pop > maxPop)
return;
return;
}
// Filter out unpromising synthesis results
if (depth + 1 < ctx.maxDepth && !IsPromising(synthesis)) {
return;
}
synthesis.component.ShiftToFitTorus();
// Add synthesis to mini database
{
std::lock_guard<std::mutex> lock(ctx.miniDbMutex);
ctx.miniDb.db[synthesis.precursorApgcode].emplace_back(
synthesis.component.Cost(),
synthesis.targetApgcode,
synthesis.component.Realise().RLE()
);
}
// If we're at max depth, do database lookup immediately
if (depth + 1 >= ctx.maxDepth) {
if (ctx.outputVisitedApgcodes) {
std::lock_guard<std::mutex> lock(ctx.visitedApgcodesMutex);
ctx.allVisitedApgcodes.insert(synthesis.precursorApgcode);
}
auto dbIt = ctx.minPaths.find(synthesis.precursorApgcode);
if (dbIt != ctx.minPaths.end()) {
{
std::lock_guard<std::mutex> lock(ctx.processedMutex);
if (ctx.processed.find(synthesis.precursorApgcode) != ctx.processed.end()) {
return;
}
ctx.processed.insert(synthesis.precursorApgcode);
}
{
std::lock_guard<std::mutex> lock(ctx.miniDbMutex);
ctx.miniDb.db[""].emplace_back(dbIt->second.cost, synthesis.precursorApgcode, "");
}
{
std::lock_guard<std::mutex> lock(ctx.cerrMutex);
std::string indent(2 + (depth + 1), ' ');
std::cerr << indent << "Found at max depth: " << synthesis.precursorApgcode
<< " (cost " << dbIt->second.cost << ")" << std::endl;
}
// If accept-first is enabled and we found a synthesis, stop searching
if (ctx.acceptFirst) {
{
std::lock_guard<std::mutex> lock(ctx.cerrMutex);
std::cerr << " Accept-first: stopping search early" << std::endl;
}
ctx.shouldStop.store(true);
ctx.searchQueue.shutdown();
}
}
} else {
// Get precursor population for priority queue
int precursorPop = synthesis.component.base.GetPop();
ctx.searchQueue.push({precursorPop, depth + 1, synthesis.precursorApgcode});
}
}
void TransferSynthesis::AddDatabasePrecursors(
const std::string& currentApgcode,
SearchContext& ctx,
int depth) {
auto reverseIt = ctx.reverseLookup.find(currentApgcode);
if (reverseIt != ctx.reverseLookup.end()) {
for (const auto& [cost, precursorApgcode, compLine] : reverseIt->second) {
try {
auto [inData, gliderData, outData] = Component::SplitSJKLine(compLine);
{
std::lock_guard<std::mutex> lock(ctx.miniDbMutex);
ctx.miniDb.db[precursorApgcode].emplace_back(cost, currentApgcode, "");
}
LifeState precursorPattern = LifeState::DecodeApgcode(precursorApgcode);
int precursorPop = precursorPattern.GetPop();
ctx.searchQueue.push({precursorPop, depth + 1, precursorApgcode});
} catch (const std::exception&) {
continue;
}
}
}
}
std::vector<std::string> TransferSynthesis::ReadTargetFile(const std::string& filename) {
std::vector<std::string> targets;
std::ifstream file(filename);
if (!file.is_open()) {
throw std::runtime_error("Could not open target file: " + filename);
}
std::string line;
while (std::getline(file, line)) {
// Remove comments and trim
size_t commentPos = line.find('#');
if (commentPos != std::string::npos) {
line = line.substr(0, commentPos);
}
// Trim whitespace
line.erase(line.find_last_not_of(" \t\r\n") + 1);
line.erase(0, line.find_first_not_of(" \t\r\n"));
if (!line.empty()) {
targets.push_back(line);
}
}
return targets;
}
std::vector<std::string> TransferSynthesis::GetMostExpensiveTargets(const std::unordered_map<std::string, SearchResult>& dijkstraResults, int countPerClass, int minPopulation, int maxPopulation, int specificPopulation, bool includePseudo, bool verbose) {
// Group patterns by population, tracking their Dijkstra cost
std::unordered_map<int, std::vector<std::pair<unsigned, std::string>>> byPopulation;
for (const auto& [apgcode, searchResult] : dijkstraResults) {
if (apgcode.empty() || apgcode.substr(0, 2) != "xs") continue;
// Extract population from apgcode (e.g., "xs19_..." -> 19)
size_t underscorePos = apgcode.find('_');
if (underscorePos == std::string::npos) continue;
std::string populationStr = apgcode.substr(2, underscorePos - 2);
int population;
try {
population = std::stoi(populationStr);
} catch (const std::exception&) {
continue;
}
// Filter by population based on mode
if (specificPopulation >= 0) {
// Specific population mode: only include exact match
if (population != specificPopulation) continue;
} else {
// Range mode: skip populations outside the range
if (population < minPopulation || population > maxPopulation) continue;
}
// Filter pseudo still lifes unless explicitly included
if (!includePseudo) {
try {
LifeState pattern = LifeState::DecodeApgcode(apgcode);
if (pattern.IsPseudoStillLife()) {
continue; // Skip pseudo still lifes
}
} catch (const std::exception&) {
// If we can't decode, assume it's not pseudo and include it
}
}
// Use Dijkstra cost (optimal synthesis cost)
unsigned cost = static_cast<unsigned>(searchResult.cost);
if (cost != std::numeric_limits<unsigned>::max()) {
byPopulation[population].emplace_back(cost, apgcode);
}
}
std::vector<std::string> result;
// For each population class, sort by cost (descending) and take top N
for (auto& [population, patterns] : byPopulation) {
if (verbose) {
std::cerr << "Population " << population << ": " << patterns.size() << " patterns" << std::endl;
}
// Sort by cost (descending - most expensive first)
std::sort(patterns.begin(), patterns.end(), [](const auto& a, const auto& b) {
return a.first > b.first;
});
// Take top countPerClass
int count = std::min(countPerClass, static_cast<int>(patterns.size()));
for (int i = 0; i < count; i++) {
result.push_back(patterns[i].second);
}
if (verbose) {
std::cerr << "Selected " << count << " most expensive patterns from population " << population;
if (count > 0) {
std::cerr << " (costs " << patterns[count-1].first << " to " << patterns[0].first << ")";
}
std::cerr << std::endl;
}
}
if (verbose) {
std::string pseudoNote = includePseudo ? "" : ", excluding pseudo still lifes";
if (specificPopulation >= 0) {
std::cerr << "Total selected: " << result.size() << " patterns (population = " << specificPopulation << pseudoNote << ")" << std::endl;
} else {
std::cerr << "Total selected: " << result.size() << " patterns (populations " << minPopulation << "-" << maxPopulation << pseudoNote << ")" << std::endl;
}
}
return result;
}
int main(int argc, char* argv[]) {
CLI::App app{"Stomp: synthesis transfer tool"};
// Basic arguments
std::string componentsPath;
app.add_option("components_path", componentsPath, "Directory or file containing .sjk files for component templates")
->required();
// Options
bool verbose = false;
app.add_flag("-v,--verbose", verbose, "Enable verbose output");
// Cost database option
std::string costPath;
auto cost_opt = app.add_option("--cost-db", costPath,
"Directory or file containing cost database (defaults to components_path)");
// Skip existing option
bool skipExisting = false;
app.add_flag("--skip-existing", skipExisting,
"Skip targets that already have complete synthesis paths");
// Search options
int maxDepth = 1;
app.add_option("--max-depth", maxDepth, "Maximum search depth (1 = single-step synthesis, >1 = multi-step)")
->default_val(1);
int maxPrecursorPop = 30;
app.add_option("--max-precursor-pop", maxPrecursorPop, "Maximum population of precursor patterns")
->default_val(30);
int numThreads = 1;
app.add_option("--threads", numThreads, "Number of worker threads for parallel processing")
->default_val(1);
unsigned minTemplateOccurrences = 1;
app.add_option("--min-template-occurrences", minTemplateOccurrences, "Minimum times a template must occur to be used")
->default_val(1);
bool outputVisitedApgcodes = false;
app.add_flag("--output-visited-apgcodes", outputVisitedApgcodes, "Output all apgcodes that were ever processed in the search queue");
// Template caching options
std::string cacheDir = "./template_cache";
app.add_option("--cache-dir", cacheDir, "Directory for template cache")
->default_val("./template_cache");
bool noCache = false;
app.add_flag("--no-cache", noCache, "Disable template caching");
bool clearCache = false;
app.add_flag("--clear-cache", clearCache, "Clear template cache and exit");
// Mutually exclusive target selection
auto target_group = app.add_option_group("target_selection", "Target selection (exactly one required)");
std::string targetFile;
target_group->add_option("--target-file", targetFile,
"File containing target apgcodes (one per line)");
std::string singleTarget;
target_group->add_option("--target", singleTarget,
"Single target apgcode to synthesize");
int expensiveCount = 1000;
auto expensive_opt = target_group->add_option("--most-expensive", expensiveCount,
"Target the N most expensive syntheses of each population class")
->default_val(1000);
// Population selection for most-expensive mode
int minPopulation = 0;
auto min_pop_opt = app.add_option("--min-population", minPopulation,
"Minimum population to consider (only with --most-expensive)")
->default_val(0);
int maxPopulation = 60;
auto max_pop_opt = app.add_option("--max-population", maxPopulation,
"Maximum population to consider (only with --most-expensive)")
->default_val(60);
int specificPopulation = -1;
auto specific_pop_opt = app.add_option("--population", specificPopulation,
"Target specific population only (only with --most-expensive)");
// Population options need --most-expensive and are mutually exclusive with --population
min_pop_opt->needs(expensive_opt);
max_pop_opt->needs(expensive_opt);
specific_pop_opt->needs(expensive_opt);
max_pop_opt->excludes(specific_pop_opt);
min_pop_opt->excludes(specific_pop_opt);