-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
2276 lines (2070 loc) · 71.9 KB
/
Copy pathmain.cpp
File metadata and controls
2276 lines (2070 loc) · 71.9 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 <algorithm>
#include <atomic>
#include <chrono>
#include <cmath>
#include <csignal>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <functional>
#include <iostream>
#include <limits>
#include <memory>
#include <numeric>
#include <optional>
#include <random>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#if defined(__unix__) || defined(__APPLE__)
#include <sys/resource.h>
#endif
struct SolverParameters {
uint64_t seed = 42;
size_t default_max_generations = 1'000'000'000ULL;
size_t swap_stagnation_threshold = 1'000;
double swap_probability = 0.1;
size_t perturbation_stagnation_threshold = 5'000;
double perturbation_probability = 0.1;
size_t interrupted_fitness_penalty = std::numeric_limits<size_t>::max();
size_t initial_best_fitness = std::numeric_limits<size_t>::max();
double output_reserve_seconds = 4.0;
size_t component_cache_memory_mib = 256;
};
volatile std::sig_atomic_t running = 1;
void signal_handler(int) { running = 0; }
std::chrono::steady_clock::time_point internal_deadline{};
bool internal_deadline_enabled = false;
bool internal_deadline_reached = false;
void configure_internal_deadline(
std::chrono::steady_clock::time_point process_start, double timeout_seconds,
double reserve_seconds) {
if (timeout_seconds <= 0.0) {
internal_deadline_enabled = false;
return;
}
const double effective_reserve =
std::min(reserve_seconds, timeout_seconds * 0.20);
const double usable_seconds =
std::max(0.0, timeout_seconds - effective_reserve);
internal_deadline =
process_start +
std::chrono::duration_cast<std::chrono::steady_clock::duration>(
std::chrono::duration<double>(usable_seconds));
internal_deadline_enabled = true;
}
inline bool check_internal_deadline_now() {
if (!internal_deadline_enabled || internal_deadline_reached) {
return !internal_deadline_reached;
}
if (std::chrono::steady_clock::now() >= internal_deadline) {
internal_deadline_reached = true;
running = 0;
return false;
}
return true;
}
inline bool keep_running() {
if (running == 0) {
return false;
}
// Avoid reading the clock on every inner-loop check.
static uint32_t checks = 0;
if (internal_deadline_enabled && ((++checks & 0x3ffU) == 0U)) {
return check_internal_deadline_now();
}
return true;
}
class ExactComponentCompatibilityCache {
public:
struct Value {
bool structures_match = false;
uint32_t canonicalization_calls = 0;
const size_t* lcas = nullptr;
};
ExactComponentCompatibilityCache(size_t memory_mib, size_t tree_count)
: tree_count_(tree_count),
budget_bytes_(static_cast<uint64_t>(memory_mib) * 1024ULL * 1024ULL) {
if (memory_mib == 0) {
throw std::runtime_error("component_cache_memory_mib must be positive");
}
if (tree_count_ != 2) {
throw std::runtime_error(
"component cache requires exactly two input trees");
}
constexpr uint64_t kExpectedLabelsPerSlot = 8;
const uint64_t expected_payload_values =
kExpectedLabelsPerSlot + static_cast<uint64_t>(tree_count_);
const uint64_t bytes_per_planned_slot =
sizeof(Slot) + expected_payload_values * sizeof(size_t);
uint64_t raw_capacity = budget_bytes_ / bytes_per_planned_slot;
if (raw_capacity < 16) {
throw std::runtime_error("component cache memory budget is too small");
}
slot_capacity_ = 1;
while (slot_capacity_ <= raw_capacity / 2) {
slot_capacity_ *= 2;
}
const uint64_t slot_bytes =
static_cast<uint64_t>(slot_capacity_) * sizeof(Slot);
if (slot_bytes >= budget_bytes_) {
throw std::runtime_error(
"component cache memory budget cannot hold payload storage");
}
payload_capacity_ =
static_cast<size_t>((budget_bytes_ - slot_bytes) / sizeof(size_t));
max_entries_ = std::max<size_t>(1, slot_capacity_ * 7 / 10);
slots_ = std::make_unique<Slot[]>(slot_capacity_);
payload_ = std::make_unique<size_t[]>(payload_capacity_);
}
std::optional<Value> lookup(const std::vector<size_t>& labels) const {
const uint64_t hash = hash_labels(labels);
size_t index = static_cast<size_t>(hash) & (slot_capacity_ - 1);
for (size_t probe = 0; probe < slot_capacity_; ++probe) {
const Slot& slot = slots_[index];
if (slot.hash == 0) {
return std::nullopt;
}
if (slot.hash == hash) {
if (equals(slot, labels)) {
return Value{slot.structures_match != 0, slot.canonicalization_calls,
payload_.get() + slot.payload_offset + slot.label_count};
}
}
index = (index + 1) & (slot_capacity_ - 1);
}
return std::nullopt;
}
void insert(const std::vector<size_t>& labels,
const std::vector<size_t>& lcas, Value value) {
if (lcas.size() != tree_count_) {
throw std::runtime_error(
"component cache received an invalid LCA vector");
}
const size_t required_values = labels.size() + tree_count_;
if (entries_ >= max_entries_ ||
required_values > payload_capacity_ - used_payload_values_) {
return;
}
if (labels.size() > std::numeric_limits<uint32_t>::max() ||
used_payload_values_ > std::numeric_limits<uint32_t>::max()) {
return;
}
const uint64_t hash = hash_labels(labels);
size_t index = static_cast<size_t>(hash) & (slot_capacity_ - 1);
for (size_t probe = 0; probe < slot_capacity_; ++probe) {
Slot& slot = slots_[index];
if (slot.hash == 0) {
const uint32_t offset = static_cast<uint32_t>(used_payload_values_);
std::copy(labels.begin(), labels.end(),
payload_.get() + used_payload_values_);
used_payload_values_ += labels.size();
std::copy(lcas.begin(), lcas.end(),
payload_.get() + used_payload_values_);
used_payload_values_ += lcas.size();
slot.hash = hash;
slot.payload_offset = offset;
slot.label_count = static_cast<uint32_t>(labels.size());
slot.canonicalization_calls = value.canonicalization_calls;
if (value.structures_match) {
slot.structures_match = 1U;
} else {
slot.structures_match = 0U;
}
++entries_;
return;
}
if (slot.hash == hash && equals(slot, labels)) {
return;
}
index = (index + 1) & (slot_capacity_ - 1);
}
}
private:
struct Slot {
uint64_t hash = 0;
uint32_t payload_offset = 0;
uint32_t label_count = 0;
uint32_t canonicalization_calls = 0;
uint8_t structures_match = 0;
std::array<uint8_t, 3> padding{};
};
static uint64_t mix64(uint64_t value) {
value ^= value >> 30;
value *= 0xbf58476d1ce4e5b9ULL;
value ^= value >> 27;
value *= 0x94d049bb133111ebULL;
value ^= value >> 31;
return value;
}
static uint64_t hash_labels(const std::vector<size_t>& labels) {
uint64_t hash = mix64(labels.size() + 0x9e3779b97f4a7c15ULL);
for (size_t label : labels) {
hash = mix64(hash ^
mix64(static_cast<uint64_t>(label) + 0x9e3779b97f4a7c15ULL));
}
if (hash == 0) {
return 1;
}
return hash;
}
bool equals(const Slot& slot, const std::vector<size_t>& labels) const {
if (slot.label_count != labels.size()) {
return false;
}
return std::equal(labels.begin(), labels.end(),
payload_.get() + slot.payload_offset);
}
size_t tree_count_ = 0;
uint64_t budget_bytes_ = 0;
size_t slot_capacity_ = 0;
size_t payload_capacity_ = 0;
size_t max_entries_ = 0;
size_t entries_ = 0;
size_t used_payload_values_ = 0;
std::unique_ptr<Slot[]> slots_;
std::unique_ptr<size_t[]> payload_;
};
struct CanonicalKey {
enum class Kind : uint8_t { Leaf, Branch };
Kind kind = Kind::Leaf;
size_t first = 0;
size_t second = 0;
bool operator==(const CanonicalKey&) const = default;
};
struct CanonicalKeyHash {
size_t operator()(const CanonicalKey& key) const {
size_t hash = static_cast<size_t>(key.kind);
hash ^= key.first + 0x9e3779b97f4a7c15ULL + (hash << 6) + (hash >> 2);
hash ^= key.second + 0x9e3779b97f4a7c15ULL + (hash << 6) + (hash >> 2);
return hash;
}
};
class StructuralInterner {
public:
explicit StructuralInterner(size_t reserve_hint = 0) {
if (reserve_hint > 0) {
ids_.reserve(reserve_hint);
}
}
size_t leaf(size_t label) {
return intern({CanonicalKey::Kind::Leaf, label, 0});
}
size_t branch(size_t left, size_t right) {
if (left > right) {
std::swap(left, right);
}
return intern({CanonicalKey::Kind::Branch, left, right});
}
private:
size_t intern(const CanonicalKey& key) {
auto [iterator, inserted] = ids_.try_emplace(key, next_id_);
if (inserted) {
++next_id_;
}
return iterator->second;
}
std::unordered_map<CanonicalKey, size_t, CanonicalKeyHash> ids_;
size_t next_id_ = 1; // 0 denotes an empty restricted subtree.
};
struct Node {
std::optional<size_t> label;
std::vector<size_t> children;
std::optional<size_t> parent;
std::optional<size_t> edge_idx;
};
class Tree {
public:
std::vector<Node> nodes;
size_t root = 0;
size_t n_edges = 0;
size_t max_leaf_label = 0;
std::unordered_map<size_t, size_t> leaf_to_idx;
std::vector<size_t> leaf_index_by_label;
std::vector<size_t> depths;
std::vector<std::vector<size_t>> up;
std::vector<size_t> subtree_leaf_counts;
std::vector<size_t> preorder_index;
std::vector<size_t> subtree_preorder_end;
size_t get_subtree_leaf_count(size_t node_idx) const {
return subtree_leaf_counts[node_idx];
}
// Parse Newick iteratively and ignore branch lengths and internal
// annotations.
static Tree parse_newick(std::string text) {
auto trim = [](std::string& value) {
const size_t first = value.find_first_not_of(" \t\n\r");
if (first == std::string::npos) {
value.clear();
return;
}
const size_t last = value.find_last_not_of(" \t\n\r");
value = value.substr(first, last - first + 1);
};
trim(text);
if (!text.empty() && text.back() == ';') {
text.pop_back();
}
trim(text);
if (text.empty()) {
throw std::runtime_error("Empty Newick tree");
}
std::vector<Node> parsed_nodes;
std::vector<size_t> parent_stack;
std::optional<size_t> parsed_root;
auto attach = [&](size_t node_index) {
if (parent_stack.empty()) {
if (parsed_root.has_value()) {
throw std::runtime_error("Multiple roots in Newick tree");
}
parsed_root = node_index;
} else {
const size_t parent = parent_stack.back();
parsed_nodes[parent].children.push_back(node_index);
parsed_nodes[node_index].parent = parent;
}
};
size_t i = 0;
while (i < text.size()) {
if (!keep_running()) {
break;
}
const char current = text[i];
if (current == ' ' || current == '\t' || current == '\n' ||
current == '\r' || current == ',') {
++i;
continue;
}
if (current == '(') {
const size_t index = parsed_nodes.size();
parsed_nodes.push_back({std::nullopt, {}, std::nullopt, std::nullopt});
attach(index);
parent_stack.push_back(index);
++i;
continue;
}
if (current == ')') {
if (parent_stack.empty()) {
throw std::runtime_error("Unmatched ')' in Newick tree");
}
parent_stack.pop_back();
++i;
// Ignore an optional internal-node annotation or branch length.
while (i < text.size() && text[i] != ',' && text[i] != ')' &&
text[i] != ';') {
++i;
}
continue;
}
if (current == ';') {
++i;
continue;
}
const size_t label_start = i;
while (i < text.size() && text[i] != ':' && text[i] != ',' &&
text[i] != ')' && text[i] != '(' && text[i] != ';' &&
text[i] != ' ' && text[i] != '\t' && text[i] != '\n' &&
text[i] != '\r') {
++i;
}
if (i == label_start) {
throw std::runtime_error("Malformed leaf token in Newick tree");
}
const std::string label_text = text.substr(label_start, i - label_start);
size_t consumed = 0;
const size_t label = std::stoull(label_text, &consumed);
if (consumed != label_text.size()) {
throw std::runtime_error("Non-numeric leaf label: " + label_text);
}
const size_t leaf_index = parsed_nodes.size();
parsed_nodes.push_back({label, {}, std::nullopt, std::nullopt});
attach(leaf_index);
while (i < text.size() && (text[i] == ' ' || text[i] == '\t' ||
text[i] == '\n' || text[i] == '\r')) {
++i;
}
if (i < text.size() && text[i] == ':') {
++i;
while (i < text.size() && text[i] != ',' && text[i] != ')' &&
text[i] != ';') {
++i;
}
}
}
if (!keep_running() && !parsed_root.has_value()) {
throw std::runtime_error("Interrupted before a tree could be parsed");
}
if (!parent_stack.empty()) {
throw std::runtime_error("Unclosed '(' in Newick tree");
}
if (!parsed_root.has_value()) {
throw std::runtime_error("Newick tree contains no root");
}
Tree tree;
tree.nodes = std::move(parsed_nodes);
tree.root = *parsed_root;
tree.n_edges = tree.assign_edge_indices();
tree.precompute();
return tree;
}
size_t assign_edge_indices() {
if (nodes.empty() || root >= nodes.size()) {
throw std::runtime_error("Invalid tree root");
}
for (auto& node : nodes) {
node.parent.reset();
node.edge_idx.reset();
}
size_t edge_index = 0;
std::vector<size_t> stack = {root};
std::vector<uint8_t> seen(nodes.size(), 0);
seen[root] = 1;
while (!stack.empty()) {
const size_t node_index = stack.back();
stack.pop_back();
if (node_index != root) {
nodes[node_index].edge_idx = edge_index++;
}
for (auto iterator = nodes[node_index].children.rbegin();
iterator != nodes[node_index].children.rend(); ++iterator) {
const size_t child = *iterator;
if (child >= nodes.size()) {
throw std::runtime_error("Tree contains an invalid child index");
}
if (seen[child]) {
throw std::runtime_error("Tree is cyclic or has multiple parents");
}
seen[child] = 1;
nodes[child].parent = node_index;
stack.push_back(child);
}
}
if (std::count(seen.begin(), seen.end(), uint8_t{1}) !=
static_cast<std::ptrdiff_t>(nodes.size())) {
throw std::runtime_error("Tree contains unreachable nodes");
}
nodes[root].parent.reset();
nodes[root].edge_idx.reset();
return edge_index;
}
void precompute() {
const size_t node_count = nodes.size();
if (node_count == 0) {
throw std::runtime_error("Cannot precompute empty tree");
}
leaf_to_idx.clear();
max_leaf_label = 0;
for (size_t i = 0; i < node_count; ++i) {
if (!nodes[i].label.has_value()) {
continue;
}
const size_t label = *nodes[i].label;
if (label == 0) {
throw std::runtime_error("Leaf labels must be positive");
}
if (!leaf_to_idx.emplace(label, i).second) {
throw std::runtime_error("Duplicate leaf label: " +
std::to_string(label));
}
max_leaf_label = std::max(max_leaf_label, label);
}
const size_t missing = std::numeric_limits<size_t>::max();
leaf_index_by_label.assign(max_leaf_label + 1, missing);
for (const auto& [label, node_index] : leaf_to_idx) {
leaf_index_by_label[label] = node_index;
}
depths.assign(node_count, 0);
size_t log_n = 1;
while (log_n < std::numeric_limits<size_t>::digits &&
(size_t{1} << log_n) <= node_count) {
++log_n;
}
up.assign(node_count, std::vector<size_t>(log_n, root));
std::vector<size_t> stack = {root};
std::vector<size_t> preorder;
preorder.reserve(node_count);
while (!stack.empty()) {
const size_t node_index = stack.back();
stack.pop_back();
preorder.push_back(node_index);
for (auto iterator = nodes[node_index].children.rbegin();
iterator != nodes[node_index].children.rend(); ++iterator) {
const size_t child = *iterator;
depths[child] = depths[node_index] + 1;
up[child][0] = node_index;
for (size_t level = 1; level < log_n; ++level) {
up[child][level] = up[up[child][level - 1]][level - 1];
}
stack.push_back(child);
}
}
preorder_index.assign(node_count, 0);
for (size_t position = 0; position < preorder.size(); ++position) {
preorder_index[preorder[position]] = position;
}
subtree_leaf_counts.assign(node_count, 0);
std::vector<size_t> subtree_node_counts(node_count, 1);
for (auto iterator = preorder.rbegin(); iterator != preorder.rend();
++iterator) {
const size_t node_index = *iterator;
if (nodes[node_index].label.has_value()) {
subtree_leaf_counts[node_index] = 1;
} else {
size_t leaf_count = 0;
size_t node_total = 1;
for (size_t child : nodes[node_index].children) {
leaf_count += subtree_leaf_counts[child];
node_total += subtree_node_counts[child];
}
subtree_leaf_counts[node_index] = leaf_count;
subtree_node_counts[node_index] = node_total;
}
}
subtree_preorder_end.assign(node_count, 0);
for (size_t node_index = 0; node_index < node_count; ++node_index) {
subtree_preorder_end[node_index] =
preorder_index[node_index] + subtree_node_counts[node_index];
}
}
bool is_ancestor(size_t ancestor, size_t descendant) const {
return preorder_index[ancestor] <= preorder_index[descendant] &&
preorder_index[descendant] < subtree_preorder_end[ancestor];
}
// Compute exact full-subtree canonical IDs for reduction checks.
std::vector<size_t> full_canonical_ids(StructuralInterner& interner) const {
std::vector<size_t> order(nodes.size());
std::iota(order.begin(), order.end(), 0);
std::sort(order.begin(), order.end(), [&](size_t lhs, size_t rhs) {
return preorder_index[lhs] > preorder_index[rhs];
});
std::vector<size_t> ids(nodes.size(), 0);
for (size_t node_index : order) {
const Node& node = nodes[node_index];
if (node.label.has_value()) {
ids[node_index] = interner.leaf(*node.label);
continue;
}
if (node.children.size() != 2) {
throw std::runtime_error("Full canonicalization requires binary trees");
}
ids[node_index] =
interner.branch(ids[node.children[0]], ids[node.children[1]]);
}
return ids;
}
std::vector<size_t> get_subtree_leaf_labels(size_t node_index) const {
std::vector<size_t> labels;
labels.reserve(get_subtree_leaf_count(node_index));
std::vector<size_t> stack = {node_index};
while (!stack.empty()) {
const size_t current = stack.back();
stack.pop_back();
const Node& node = nodes[current];
if (node.label.has_value()) {
labels.push_back(*node.label);
} else {
for (auto iterator = node.children.rbegin();
iterator != node.children.rend(); ++iterator) {
stack.push_back(*iterator);
}
}
}
return labels;
}
size_t get_lca(size_t first, size_t second) const {
if (depths[first] < depths[second]) {
std::swap(first, second);
}
size_t difference = depths[first] - depths[second];
const size_t log_n = up[0].size();
for (size_t level = 0; level < log_n; ++level) {
if ((difference >> level) & 1U) {
first = up[first][level];
}
}
if (first == second) {
return first;
}
for (size_t level = log_n; level-- > 0;) {
if (up[first][level] != up[second][level]) {
first = up[first][level];
second = up[second][level];
}
}
return up[first][0];
}
size_t get_lca_of_set(const std::vector<size_t>& leaves) const {
if (leaves.empty()) {
throw std::runtime_error("LCA of empty leaf set");
}
size_t current = find_leaf_idx(leaves.front());
for (size_t i = 1; i < leaves.size(); ++i) {
current = get_lca(current, find_leaf_idx(leaves[i]));
}
return current;
}
size_t find_leaf_idx(size_t label) const {
const size_t missing = std::numeric_limits<size_t>::max();
if (label >= leaf_index_by_label.size() ||
leaf_index_by_label[label] == missing) {
throw std::runtime_error("Leaf missing: " + std::to_string(label));
}
return leaf_index_by_label[label];
}
static Tree compact(std::vector<Node> source_nodes, size_t source_root) {
if (source_root >= source_nodes.size()) {
throw std::runtime_error("Invalid compact root");
}
std::vector<size_t> order;
std::vector<size_t> stack = {source_root};
while (!stack.empty()) {
const size_t old_index = stack.back();
stack.pop_back();
order.push_back(old_index);
for (auto iterator = source_nodes[old_index].children.rbegin();
iterator != source_nodes[old_index].children.rend(); ++iterator) {
stack.push_back(*iterator);
}
}
std::vector<size_t> old_to_new(source_nodes.size(),
std::numeric_limits<size_t>::max());
std::vector<Node> compact_nodes;
compact_nodes.reserve(order.size());
for (size_t old_index : order) {
old_to_new[old_index] = compact_nodes.size();
Node copy = source_nodes[old_index];
copy.parent.reset();
copy.edge_idx.reset();
compact_nodes.push_back(std::move(copy));
}
for (Node& node : compact_nodes) {
for (size_t& child : node.children) {
if (child >= old_to_new.size() ||
old_to_new[child] == std::numeric_limits<size_t>::max()) {
throw std::runtime_error("Compaction retained an unreachable child");
}
child = old_to_new[child];
}
}
Tree tree;
tree.nodes = std::move(compact_nodes);
tree.root = 0;
tree.n_edges = tree.assign_edge_indices();
tree.precompute();
return tree;
}
Tree prune_and_compact(const std::vector<size_t>& to_remove) const {
std::vector<uint8_t> removed(nodes.size(), 0);
for (size_t label : to_remove) {
auto iterator = leaf_to_idx.find(label);
if (iterator != leaf_to_idx.end()) {
removed[iterator->second] = 1;
}
}
std::vector<size_t> preorder;
std::vector<size_t> stack = {root};
while (!stack.empty()) {
const size_t node_index = stack.back();
stack.pop_back();
preorder.push_back(node_index);
for (size_t child : nodes[node_index].children) {
stack.push_back(child);
}
}
std::vector<std::optional<size_t>> mapped(nodes.size());
std::vector<Node> new_nodes;
new_nodes.reserve(nodes.size());
for (auto iterator = preorder.rbegin(); iterator != preorder.rend();
++iterator) {
const size_t old_index = *iterator;
const Node& old_node = nodes[old_index];
if (old_node.label.has_value()) {
if (removed[old_index]) {
continue;
}
const size_t new_index = new_nodes.size();
new_nodes.push_back({*old_node.label, {}, std::nullopt, std::nullopt});
mapped[old_index] = new_index;
continue;
}
std::vector<size_t> kept_children;
kept_children.reserve(old_node.children.size());
for (size_t old_child : old_node.children) {
if (mapped[old_child].has_value()) {
kept_children.push_back(*mapped[old_child]);
}
}
if (kept_children.empty()) {
continue;
}
if (kept_children.size() == 1) {
mapped[old_index] = kept_children.front();
continue;
}
const size_t new_index = new_nodes.size();
new_nodes.push_back(
{std::nullopt, kept_children, std::nullopt, std::nullopt});
mapped[old_index] = new_index;
}
if (!mapped[root].has_value()) {
throw std::runtime_error("Tree empty after pruning");
}
Tree tree;
tree.nodes = std::move(new_nodes);
tree.root = *mapped[root];
tree.n_edges = tree.assign_edge_indices();
tree.precompute();
return tree;
}
void fill_leaf_components(
const std::vector<uint8_t>& bits, std::vector<size_t>& component_map,
std::vector<std::pair<size_t, size_t>>& stack) const {
if (component_map.size() < max_leaf_label + 1) {
component_map.resize(max_leaf_label + 1);
}
stack.clear();
stack.emplace_back(root, 0);
size_t next_component = 1;
while (!stack.empty()) {
const auto [node_index, component] = stack.back();
stack.pop_back();
const Node& node = nodes[node_index];
if (node.label.has_value()) {
component_map[*node.label] = component;
continue;
}
for (size_t child : node.children) {
const std::optional<size_t> edge = nodes[child].edge_idx;
const bool is_cut = edge.has_value() && bits[*edge] != 0;
size_t child_component = component;
if (is_cut) {
child_component = next_component;
++next_component;
}
stack.emplace_back(child, child_component);
}
}
}
std::vector<size_t> get_leaf_components(
const std::vector<uint8_t>& bits) const {
std::vector<size_t> component_map(max_leaf_label + 1, 0);
std::vector<std::pair<size_t, size_t>> stack;
stack.reserve(nodes.size());
fill_leaf_components(bits, component_map, stack);
return component_map;
}
};
// Reusable storage for exact induced-tree canonicalization.
struct InducedCanonicalScratch {
std::vector<size_t> selected_nodes;
std::vector<size_t> virtual_nodes;
std::vector<size_t> parent_index;
std::vector<size_t> first_child;
std::vector<size_t> second_child;
std::vector<uint8_t> child_count;
std::vector<size_t> canonical_ids;
std::vector<size_t> stack;
};
struct InducedCanonicalResult {
size_t canonical_id = 0;
size_t lca_node = 0;
};
InducedCanonicalResult canonical_induced_component_id(
const Tree& tree, const std::vector<size_t>& leaf_labels,
StructuralInterner& interner, InducedCanonicalScratch& scratch) {
if (leaf_labels.empty()) {
throw std::runtime_error("Cannot canonicalize an empty component");
}
if (leaf_labels.size() == 1) {
const size_t leaf_node = tree.find_leaf_idx(leaf_labels.front());
return {interner.leaf(leaf_labels.front()), leaf_node};
}
scratch.selected_nodes.clear();
scratch.selected_nodes.reserve(leaf_labels.size());
for (size_t label : leaf_labels) {
scratch.selected_nodes.push_back(tree.find_leaf_idx(label));
}
auto by_preorder = [&](size_t lhs, size_t rhs) {
return tree.preorder_index[lhs] < tree.preorder_index[rhs];
};
std::sort(scratch.selected_nodes.begin(), scratch.selected_nodes.end(),
by_preorder);
if (std::adjacent_find(scratch.selected_nodes.begin(),
scratch.selected_nodes.end()) !=
scratch.selected_nodes.end()) {
throw std::runtime_error("Component contains duplicate leaf labels");
}
scratch.virtual_nodes.assign(scratch.selected_nodes.begin(),
scratch.selected_nodes.end());
scratch.virtual_nodes.reserve(scratch.selected_nodes.size() * 2);
for (size_t i = 1; i < scratch.selected_nodes.size(); ++i) {
scratch.virtual_nodes.push_back(
tree.get_lca(scratch.selected_nodes[i - 1], scratch.selected_nodes[i]));
}
std::sort(scratch.virtual_nodes.begin(), scratch.virtual_nodes.end(),
by_preorder);
scratch.virtual_nodes.erase(
std::unique(scratch.virtual_nodes.begin(), scratch.virtual_nodes.end()),
scratch.virtual_nodes.end());
const size_t node_count = scratch.virtual_nodes.size();
const size_t none = std::numeric_limits<size_t>::max();
scratch.parent_index.assign(node_count, none);
scratch.first_child.assign(node_count, none);
scratch.second_child.assign(node_count, none);
scratch.child_count.assign(node_count, 0);
scratch.canonical_ids.assign(node_count, 0);
scratch.stack.clear();
scratch.stack.reserve(node_count);
size_t root_index = none;
for (size_t index = 0; index < node_count; ++index) {
const size_t node = scratch.virtual_nodes[index];
while (
!scratch.stack.empty() &&
!tree.is_ancestor(scratch.virtual_nodes[scratch.stack.back()], node)) {
scratch.stack.pop_back();
}
if (scratch.stack.empty()) {
if (root_index != none) {
throw std::runtime_error(
"Virtual canonicalization produced multiple roots");
}
root_index = index;
} else {
const size_t parent = scratch.stack.back();
scratch.parent_index[index] = parent;
if (scratch.child_count[parent] == 0) {
scratch.first_child[parent] = index;
} else if (scratch.child_count[parent] == 1) {
scratch.second_child[parent] = index;
} else {
throw std::runtime_error("Restricted component is not binary");
}
++scratch.child_count[parent];
}
scratch.stack.push_back(index);
}
if (root_index == none) {
throw std::runtime_error("Virtual canonicalization produced no root");
}
for (size_t index = node_count; index-- > 0;) {
const Node& node = tree.nodes[scratch.virtual_nodes[index]];
if (node.label.has_value()) {
scratch.canonical_ids[index] = interner.leaf(*node.label);
continue;
}
const uint8_t count = scratch.child_count[index];
if (count == 0) {
throw std::runtime_error(
"Virtual canonicalization contains an empty internal node");
}
if (count == 1) {
scratch.canonical_ids[index] =
scratch.canonical_ids[scratch.first_child[index]];
continue;
}
scratch.canonical_ids[index] =
interner.branch(scratch.canonical_ids[scratch.first_child[index]],
scratch.canonical_ids[scratch.second_child[index]]);
}
return {scratch.canonical_ids[root_index], scratch.virtual_nodes[root_index]};
}
struct ComponentRecord {
size_t component_id = 0;
std::vector<size_t> leaves;
std::vector<size_t> lcas;
bool structures_match = true;
};
// Epoch-stamped owner arrays for repeated penalty evaluations.
struct StampedOwnerScratch {
std::vector<size_t> owner;
std::vector<uint64_t> stamp;
uint64_t epoch = 0;
void begin(size_t node_count) {
if (owner.size() != node_count) {
owner.assign(node_count, 0);
stamp.assign(node_count, 0);
epoch = 1;
return;
}
++epoch;
if (epoch == 0) {
std::fill(stamp.begin(), stamp.end(), 0);
epoch = 1;
}
}
bool conflict_or_claim(size_t node, size_t component_id) {
if (stamp[node] != epoch) {
stamp[node] = epoch;
owner[node] = component_id;
return false;
}
return owner[node] != component_id;