-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiskforge.cpp
More file actions
2020 lines (1901 loc) · 86.1 KB
/
Copy pathdiskforge.cpp
File metadata and controls
2020 lines (1901 loc) · 86.1 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 <array>
#include <atomic>
#include <bit>
#include <chrono>
#include <cfenv>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <limits>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <system_error>
#include <utility>
#include <vector>
#include "diskforge/app.hpp"
#include "diskforge/cell_list.hpp"
#include "diskforge/cli.hpp"
#include "diskforge/foundation.hpp"
#include "diskforge/initialization.hpp"
#include "diskforge/manifest.hpp"
#include "diskforge/overlap.hpp"
#include "diskforge/reference_overlap.hpp"
#include "diskforge/validation.hpp"
#ifdef _OPENMP
#include <omp.h>
#endif
#include <unistd.h>
namespace diskforge {
using Clock = std::chrono::steady_clock;
struct Counters {
std::uint64_t compression_steps = 0;
std::uint64_t overlap_particle_scans = 0;
std::uint64_t representatives = 0;
std::uint64_t neighbor_lists = 0;
std::uint64_t neighbor_visits = 0;
std::uint64_t move_trials = 0;
std::uint64_t accepted_moves = 0;
std::uint64_t distance_checks = 0;
std::uint64_t discovery_distance_checks = 0;
std::uint64_t relaxation_distance_checks = 0;
std::uint64_t scheduler_distance_checks = 0;
std::uint64_t candidate_point_queries = 0;
std::uint64_t event_candidate_pairs = 0;
std::uint64_t event_events_scheduled = 0;
std::uint64_t event_initial_events = 0;
std::uint64_t event_local_events = 0;
std::uint64_t event_rebuild_events = 0;
std::uint64_t event_valid_events = 0;
std::uint64_t event_stale_events = 0;
std::uint64_t event_generation_bumps = 0;
std::uint64_t event_dirty_particles = 0;
std::uint64_t event_local_refreshes = 0;
std::uint64_t event_rebuilds = 0;
std::uint64_t event_rebuild_dropped_events = 0;
std::uint64_t event_peak_queued = 0;
std::uint64_t event_queued_end = 0;
std::uint64_t sqrt_calls = 0;
std::uint64_t temporary_vectors = 0;
std::uint64_t cell_removals = 0;
std::uint64_t cell_additions = 0;
std::uint64_t radius_writes = 0;
std::uint64_t anchor_writes = 0;
std::uint64_t rng_draws = 0;
bool operator==(const Counters&) const = default;
};
struct SimulationState {
std::vector<Point> points;
std::vector<Point> anchors;
std::vector<double> legacy_radii;
double radius;
double box;
PeriodicCellList cells;
SimulationState(const InitialConfiguration& initial, double final_radius)
: points(initial.points),
anchors(initial.points),
legacy_radii(initial.points.size(), initial.radius),
radius(initial.radius),
box(initial.box),
cells(initial.box, 2.0 * final_radius, initial.points.size()) {
if (!(radius <= final_radius)) [[unlikely]] {
throw std::logic_error(
"initial radius exceeds the requested final radius");
}
for (std::size_t particle = 0; particle < points.size(); ++particle) {
cells.add(static_cast<int>(particle), points[particle]);
}
}
};
struct Workspace {
static constexpr std::size_t kCandidateNeighborhoods = 9;
std::vector<int> representatives;
std::vector<int> neighbors;
std::vector<int> dirty_particles;
std::vector<unsigned char> dirty_flags;
std::vector<unsigned char> overlap_flags;
std::array<int, kCandidateNeighborhoods> candidate_cells{};
std::array<std::vector<int>, kCandidateNeighborhoods>
candidate_neighbors;
std::vector<int> uncached_candidate_neighbors;
std::size_t candidate_neighborhood_count = 0;
explicit Workspace(std::size_t particle_count)
: dirty_flags(particle_count, 0), overlap_flags(particle_count, 0) {
representatives.reserve(particle_count);
neighbors.reserve(particle_count);
dirty_particles.reserve(particle_count);
}
void mark_dirty(int particle) {
const std::size_t index = static_cast<std::size_t>(particle);
if (dirty_flags[index] == 0) {
dirty_flags[index] = 1;
dirty_particles.push_back(particle);
}
}
void write_dirty_anchors(SimulationState& state, Counters& counters) {
for (const int particle : dirty_particles) {
const std::size_t index = static_cast<std::size_t>(particle);
state.anchors[index] = state.points[index];
++counters.anchor_writes;
}
}
void clear_dirty() {
for (const int particle : dirty_particles) {
dirty_flags[static_cast<std::size_t>(particle)] = 0;
}
dirty_particles.clear();
}
void update_dirty_anchors(SimulationState& state, Counters& counters) {
write_dirty_anchors(state, counters);
clear_dirty();
}
void clear_candidate_neighborhoods() {
candidate_neighborhood_count = 0;
}
const std::vector<int>& candidate_neighborhood(
const PeriodicCellList& cells, int cell) {
for (std::size_t index = 0;
index < candidate_neighborhood_count; ++index) {
if (candidate_cells[index] == cell) {
return candidate_neighbors[index];
}
}
if (candidate_neighborhood_count >= candidate_cells.size()) [[unlikely]] {
// Exact boundary rounding can expose more than the mathematical
// 3x3 set. Preserve correctness with an uncached query rather than
// turning the optimization's common-case bound into a failure.
cells.gather_cell_neighbors(cell, uncached_candidate_neighbors);
return uncached_candidate_neighbors;
}
const std::size_t index = candidate_neighborhood_count++;
candidate_cells[index] = cell;
cells.gather_cell_neighbors(cell, candidate_neighbors[index]);
return candidate_neighbors[index];
}
};
bool has_overlap_legacy(const SimulationState& state,
int particle,
Counters& counters,
std::uint64_t& phase_distance_checks) {
const std::vector<int> neighbors = state.cells.neighbors_allocating(particle);
++counters.temporary_vectors;
for (const int neighbor : neighbors) {
if (neighbor == particle) {
continue;
}
++counters.distance_checks;
++phase_distance_checks;
++counters.sqrt_calls;
const double distance =
std::sqrt(squared_distance(state.points[static_cast<std::size_t>(particle)],
state.points[static_cast<std::size_t>(neighbor)], state.box));
if (distance <
state.legacy_radii[static_cast<std::size_t>(particle)] +
state.legacy_radii[static_cast<std::size_t>(neighbor)]) {
return true;
}
}
return false;
}
bool has_overlap_at_point_fast(const SimulationState& state,
const Point& candidate,
const std::vector<int>& neighbors,
StrictOverlapCutoff cutoff,
Counters& counters) {
for (const int neighbor : neighbors) {
++counters.distance_checks;
++counters.relaxation_distance_checks;
if (strict_overlap_from_squared(
squared_distance(candidate, state.points[static_cast<std::size_t>(neighbor)],
state.box),
cutoff)) {
return true;
}
}
return false;
}
void discover_overlaps_legacy(const SimulationState& state,
Workspace& workspace,
Counters& counters) {
workspace.representatives.clear();
for (std::size_t particle = 0; particle < state.points.size(); ++particle) {
++counters.overlap_particle_scans;
if (has_overlap_legacy(state, static_cast<int>(particle), counters,
counters.discovery_distance_checks)) {
workspace.representatives.push_back(static_cast<int>(particle));
}
}
counters.representatives += workspace.representatives.size();
}
void discover_overlaps_fast(const SimulationState& state,
Workspace& workspace,
StrictOverlapCutoff cutoff,
Counters& counters) {
workspace.representatives.clear();
std::fill(workspace.overlap_flags.begin(), workspace.overlap_flags.end(), 0);
std::uint64_t distance_checks = 0;
for (std::size_t cell = 0; cell < state.cells.cell_count(); ++cell) {
state.cells.for_each_unordered_neighbor_pair_owned_by_cell(
static_cast<int>(cell), [&](int particle, int neighbor) {
++distance_checks;
if (strict_overlap_from_squared(
squared_distance(
state.points[static_cast<std::size_t>(particle)],
state.points[static_cast<std::size_t>(neighbor)],
state.box),
cutoff)) [[unlikely]] {
workspace.overlap_flags[
static_cast<std::size_t>(particle)] = 1;
workspace.overlap_flags[static_cast<std::size_t>(neighbor)] = 1;
}
});
}
counters.overlap_particle_scans += state.points.size();
counters.distance_checks += distance_checks;
counters.discovery_distance_checks += distance_checks;
for (std::size_t particle = 0; particle < workspace.overlap_flags.size(); ++particle) {
if (workspace.overlap_flags[particle] != 0) {
workspace.representatives.push_back(static_cast<int>(particle));
}
}
counters.representatives += workspace.representatives.size();
}
int discover_overlaps_omp(const SimulationState& state,
Workspace& workspace,
StrictOverlapCutoff cutoff,
Counters& counters,
int requested_threads) {
workspace.representatives.clear();
std::fill(workspace.overlap_flags.begin(), workspace.overlap_flags.end(), 0);
std::uint64_t distance_checks = 0;
int threads_used = 1;
#ifdef _OPENMP
static const int runtime_default_team_size = omp_get_max_threads();
const int previous_dynamic = omp_get_dynamic();
const int team_size =
requested_threads > 0 ? requested_threads : runtime_default_team_size;
omp_set_dynamic(0);
#pragma omp parallel num_threads(team_size) reduction(+ : distance_checks)
{
#pragma omp single
{ threads_used = omp_get_num_threads(); }
#pragma omp for schedule(static)
for (std::ptrdiff_t cell = 0;
cell < static_cast<std::ptrdiff_t>(state.cells.cell_count()); ++cell) {
state.cells.for_each_unordered_neighbor_pair_owned_by_cell(
static_cast<int>(cell), [&](int particle, int neighbor) {
++distance_checks;
if (strict_overlap_from_squared(
squared_distance(
state.points[static_cast<std::size_t>(particle)],
state.points[static_cast<std::size_t>(neighbor)],
state.box),
cutoff)) [[unlikely]] {
std::atomic_ref<unsigned char>(
workspace.overlap_flags[
static_cast<std::size_t>(particle)])
.store(1, std::memory_order_relaxed);
std::atomic_ref<unsigned char>(
workspace.overlap_flags[
static_cast<std::size_t>(neighbor)])
.store(1, std::memory_order_relaxed);
}
});
}
}
omp_set_dynamic(previous_dynamic);
#else
(void)requested_threads;
for (std::size_t cell = 0; cell < state.cells.cell_count(); ++cell) {
state.cells.for_each_unordered_neighbor_pair_owned_by_cell(
static_cast<int>(cell), [&](int particle, int neighbor) {
++distance_checks;
if (strict_overlap_from_squared(
squared_distance(
state.points[static_cast<std::size_t>(particle)],
state.points[static_cast<std::size_t>(neighbor)],
state.box),
cutoff)) [[unlikely]] {
workspace.overlap_flags[
static_cast<std::size_t>(particle)] = 1;
workspace.overlap_flags[static_cast<std::size_t>(neighbor)] = 1;
}
});
}
#endif
counters.overlap_particle_scans += state.points.size();
counters.distance_checks += distance_checks;
counters.discovery_distance_checks += distance_checks;
// Serial compaction is the reproducibility boundary: output is always index ordered.
for (std::size_t particle = 0; particle < workspace.overlap_flags.size(); ++particle) {
if (workspace.overlap_flags[particle] != 0) {
workspace.representatives.push_back(static_cast<int>(particle));
}
}
counters.representatives += workspace.representatives.size();
return threads_used;
}
void relocate_until_clear_legacy(SimulationState& state,
int particle,
ReproducibleRng& rng,
const Parameters& parameters,
Counters& counters) {
const std::size_t index = static_cast<std::size_t>(particle);
const double displacement_extent = 2.0 * state.radius;
for (std::size_t trial = 0; trial < parameters.max_trials_per_move; ++trial) {
++counters.move_trials;
state.cells.remove(particle);
++counters.cell_removals;
const Point displacement =
rng.symmetric_pair(displacement_extent);
state.points[index] = wrap_point(
{state.anchors[index].x + displacement.x,
state.anchors[index].y + displacement.y},
state.box);
counters.rng_draws += 2;
state.cells.add(particle, state.points[index]);
++counters.cell_additions;
if (!has_overlap_legacy(state, particle, counters,
counters.relaxation_distance_checks)) {
++counters.accepted_moves;
return;
}
}
throw std::runtime_error("relocation trial limit exhausted for particle " +
std::to_string(particle));
}
void relocate_until_clear_fast(SimulationState& state,
int particle,
ReproducibleRng& rng,
const Parameters& parameters,
Workspace& workspace,
StrictOverlapCutoff cutoff,
Counters& counters) {
const std::size_t index = static_cast<std::size_t>(particle);
const double displacement_extent = 2.0 * state.radius;
const Point previous_position = state.points[index];
state.cells.remove(particle);
++counters.cell_removals;
workspace.clear_candidate_neighborhoods();
for (std::size_t trial = 0; trial < parameters.max_trials_per_move; ++trial) {
++counters.move_trials;
const Point displacement =
rng.symmetric_pair(displacement_extent);
const Point candidate = wrap_point(
{state.anchors[index].x + displacement.x,
state.anchors[index].y + displacement.y},
state.box);
counters.rng_draws += 2;
++counters.candidate_point_queries;
const int candidate_cell = state.cells.cell_for_point(candidate);
const std::vector<int>& candidate_neighbors =
workspace.candidate_neighborhood(state.cells, candidate_cell);
if (!has_overlap_at_point_fast(
state, candidate, candidate_neighbors, cutoff, counters)) {
state.points[index] = candidate;
state.cells.add(particle, candidate);
++counters.cell_additions;
++counters.accepted_moves;
return;
}
}
state.points[index] = previous_position;
state.cells.add(particle, previous_position);
++counters.cell_additions;
throw std::runtime_error("relocation trial limit exhausted for particle " +
std::to_string(particle));
}
void relax_representatives(SimulationState& state,
Workspace& workspace,
ReproducibleRng& rng,
const Parameters& parameters,
Engine engine,
StrictOverlapCutoff cutoff,
Counters& counters) {
for (const int representative : workspace.representatives) {
if (engine == Engine::scan_legacy) {
std::vector<int> neighbors = state.cells.neighbors_allocating(representative);
++counters.temporary_vectors;
++counters.neighbor_lists;
counters.neighbor_visits += neighbors.size();
for (const int particle : neighbors) {
relocate_until_clear_legacy(state, particle, rng, parameters, counters);
}
} else {
state.cells.gather_neighbors(representative, workspace.neighbors);
++counters.neighbor_lists;
counters.neighbor_visits += workspace.neighbors.size();
for (const int particle : workspace.neighbors) {
workspace.mark_dirty(particle);
relocate_until_clear_fast(
state, particle, rng, parameters, workspace, cutoff,
counters);
}
}
}
}
enum class StepVerification {
none,
discovery,
discovery_and_clear,
};
struct RunControls {
StepVerification verification = StepVerification::none;
bool force_event_rebuilds = false;
};
struct VerificationStats {
std::uint64_t discovery_scans = 0;
std::uint64_t post_relaxation_scans = 0;
std::uint64_t pairs_checked = 0;
};
struct RunResult {
Engine engine = Engine::scan_fast;
std::vector<Point> points;
double radius = 0.0;
double box = 0.0;
double seconds = 0.0;
double setup_seconds = 0.0;
double discovery_seconds = 0.0;
double relaxation_seconds = 0.0;
double scheduler_seconds = 0.0;
int threads_used = 1;
Counters counters;
OracleResult oracle;
VerificationStats verification;
std::uint64_t state_checksum = 0;
};
enum class EventScheduleOrigin {
initial,
local,
rebuild,
};
struct PairEvent {
std::uint32_t a = 0;
std::uint32_t b = 0;
std::uint64_t scheduled_after_step = 0;
};
static_assert(sizeof(PairEvent) == 16);
std::size_t first_strict_event_step(const std::vector<double>& diameters,
double distance,
std::size_t current_step) {
if (current_step + 1U >= diameters.size()) {
return diameters.size();
}
const auto search_begin =
diameters.begin() + static_cast<std::ptrdiff_t>(current_step + 1U);
const auto event_position =
std::upper_bound(search_begin, diameters.end(), distance);
return static_cast<std::size_t>(event_position - diameters.begin());
}
class EventCalendar {
public:
EventCalendar(const SimulationState& state,
const Parameters& parameters,
Counters& counters)
: radii_(build_radii(state.radius, parameters)),
diameters_(radii_.size()),
events_at_step_(radii_.size()),
last_dirty_step_(state.points.size(), 0),
endpoint_bits_((state.points.size() + 63U) / 64U, 0) {
const double final_diameter = 2.0 * parameters.final_radius;
if (state.cells.cell_size() < final_diameter) {
throw std::logic_error(
"event scheduler requires cell width at least the final diameter");
}
std::transform(radii_.begin(), radii_.end(), diameters_.begin(),
[](double radius) { return radius + radius; });
enumerate_all_pairs(state, 0, EventScheduleOrigin::initial, counters);
live_count_at_last_rebuild_ = queued_events_;
counters.event_queued_end = queued_events_;
}
std::size_t step_count() const {
return radii_.size() - 1U;
}
double radius_at(std::size_t step) const {
return radii_.at(step);
}
void discover_representatives(const SimulationState& state,
std::size_t step,
Workspace& workspace,
StrictOverlapCutoff cutoff,
Counters& counters) {
if (step == 0 || step >= events_at_step_.size()) {
throw std::out_of_range("event calendar step is out of range");
}
std::vector<PairEvent> bucket =
std::move(events_at_step_[step]);
if (queued_events_ < bucket.size()) {
throw std::logic_error("event queue accounting underflow");
}
queued_events_ -= bucket.size();
for (const PairEvent& event : bucket) {
const std::size_t a = event.a;
const std::size_t b = event.b;
if (last_dirty_step_[a] > event.scheduled_after_step ||
last_dirty_step_[b] > event.scheduled_after_step) {
++stale_since_rebuild_;
++counters.event_stale_events;
continue;
}
#ifndef NDEBUG
if (!strict_overlap_from_squared(
squared_distance(state.points[a], state.points[b], state.box),
cutoff)) {
throw std::logic_error("live event is not overlapping at its scheduled step");
}
#else
(void)cutoff;
#endif
endpoint_bits_[a / 64U] |= 1ULL << (a % 64U);
endpoint_bits_[b / 64U] |= 1ULL << (b % 64U);
++valid_since_rebuild_;
++counters.event_valid_events;
}
workspace.representatives.clear();
for (std::size_t block_index = 0; block_index < endpoint_bits_.size(); ++block_index) {
std::uint64_t block =
std::exchange(endpoint_bits_[block_index], 0);
while (block != 0) {
const unsigned offset = std::countr_zero(block);
const std::size_t particle = block_index * 64U + offset;
if (particle < state.points.size()) {
workspace.representatives.push_back(static_cast<int>(particle));
}
block &= block - 1U;
}
}
counters.representatives += workspace.representatives.size();
counters.event_queued_end = queued_events_;
}
void finish_step(SimulationState& state,
std::size_t step,
Workspace& workspace,
Counters& counters,
bool force_rebuild) {
const std::size_t dirty_count = workspace.dirty_particles.size();
counters.event_dirty_particles += dirty_count;
for (const int particle : workspace.dirty_particles) {
last_dirty_step_[static_cast<std::size_t>(particle)] = step;
++counters.event_generation_bumps;
}
workspace.write_dirty_anchors(state, counters);
if (step < step_count()) {
const bool rebuild =
force_rebuild || dirty_count > state.points.size() / 3U ||
queued_events_ >
std::max(4ULL * static_cast<std::uint64_t>(state.points.size()),
3ULL * live_count_at_last_rebuild_) ||
stale_since_rebuild_ >
std::max(static_cast<std::uint64_t>(state.points.size()),
std::uint64_t{2} * valid_since_rebuild_);
if (rebuild) {
rebuild_future(state, step, counters);
} else if (dirty_count != 0) {
++counters.event_local_refreshes;
enumerate_dirty_pairs(state, step, workspace, counters);
}
}
workspace.clear_dirty();
counters.event_queued_end = queued_events_;
}
private:
static std::vector<double> build_radii(double initial_radius,
const Parameters& parameters) {
std::vector<double> radii;
radii.reserve(std::min<std::size_t>(parameters.max_compression_steps, 4095U) + 1U);
radii.push_back(initial_radius);
while (radii.back() < parameters.final_radius) {
if (radii.size() - 1U >= parameters.max_compression_steps) {
throw std::runtime_error("compression step limit exhausted");
}
radii.push_back(next_compression_radius(radii.back(), parameters));
}
return radii;
}
void schedule_pair(const SimulationState& state,
int first,
int second,
std::size_t current_step,
EventScheduleOrigin origin,
Counters& counters) {
if (first == second || current_step >= step_count()) {
return;
}
const int a = std::min(first, second);
const int b = std::max(first, second);
++counters.event_candidate_pairs;
++counters.distance_checks;
++counters.scheduler_distance_checks;
const double distance =
std::sqrt(squared_distance(state.points[static_cast<std::size_t>(a)],
state.points[static_cast<std::size_t>(b)], state.box));
++counters.sqrt_calls;
const std::size_t event_step =
first_strict_event_step(diameters_, distance, current_step);
if (event_step == diameters_.size()) {
return;
}
events_at_step_[event_step].push_back(
{static_cast<std::uint32_t>(a), static_cast<std::uint32_t>(b),
static_cast<std::uint64_t>(current_step)});
++queued_events_;
++counters.event_events_scheduled;
switch (origin) {
case EventScheduleOrigin::initial:
++counters.event_initial_events;
break;
case EventScheduleOrigin::local:
++counters.event_local_events;
break;
case EventScheduleOrigin::rebuild:
++counters.event_rebuild_events;
break;
}
counters.event_peak_queued = std::max(counters.event_peak_queued, queued_events_);
}
void enumerate_all_pairs(const SimulationState& state,
std::size_t current_step,
EventScheduleOrigin origin,
Counters& counters) {
for (std::size_t particle = 0; particle < state.points.size(); ++particle) {
state.cells.for_each_neighbor_until(static_cast<int>(particle), [&](int neighbor) {
if (neighbor > static_cast<int>(particle)) {
schedule_pair(state, static_cast<int>(particle), neighbor, current_step,
origin, counters);
}
return true;
});
}
}
void enumerate_dirty_pairs(const SimulationState& state,
std::size_t current_step,
const Workspace& workspace,
Counters& counters) {
for (const int particle : workspace.dirty_particles) {
state.cells.for_each_neighbor_until(particle, [&](int neighbor) {
if (neighbor == particle) {
return true;
}
if (workspace.dirty_flags[static_cast<std::size_t>(neighbor)] != 0 &&
neighbor < particle) {
return true;
}
schedule_pair(state, particle, neighbor, current_step,
EventScheduleOrigin::local, counters);
return true;
});
}
}
void rebuild_future(const SimulationState& state,
std::size_t current_step,
Counters& counters) {
++counters.event_rebuilds;
counters.event_rebuild_dropped_events += queued_events_;
for (std::size_t step = current_step + 1U; step < events_at_step_.size(); ++step) {
events_at_step_[step].clear();
}
queued_events_ = 0;
enumerate_all_pairs(state, current_step, EventScheduleOrigin::rebuild, counters);
live_count_at_last_rebuild_ = queued_events_;
stale_since_rebuild_ = 0;
valid_since_rebuild_ = 0;
}
std::vector<double> radii_;
std::vector<double> diameters_;
std::vector<std::vector<PairEvent>> events_at_step_;
std::vector<std::uint64_t> last_dirty_step_;
std::vector<std::uint64_t> endpoint_bits_;
std::uint64_t queued_events_ = 0;
std::uint64_t live_count_at_last_rebuild_ = 0;
std::uint64_t stale_since_rebuild_ = 0;
std::uint64_t valid_since_rebuild_ = 0;
};
void verify_discovery_with_reference(const SimulationState& state,
const std::vector<int>& representatives,
std::size_t step,
Engine engine,
VerificationStats& stats) {
const ReferenceOverlapScan reference =
scan_overlaps_reference(state.points, state.radius, state.box);
++stats.discovery_scans;
stats.pairs_checked += reference.pairs_checked;
if (reference.representatives != representatives) {
throw std::logic_error(
std::string(engine_name(engine)) +
"/independent-reference representative mismatch at compression step " +
std::to_string(step));
}
}
void verify_clear_with_reference(const SimulationState& state,
std::size_t step,
Engine engine,
VerificationStats& stats) {
const ReferenceOverlapScan reference =
scan_overlaps_reference(state.points, state.radius, state.box);
++stats.post_relaxation_scans;
stats.pairs_checked += reference.pairs_checked;
if (reference.overlapping_pairs != 0) {
throw std::logic_error(
std::string(engine_name(engine)) +
"/independent-reference found overlaps after relaxation at compression step " +
std::to_string(step));
}
}
void validate_final_state_fast(const SimulationState& state) {
if (!(state.radius > 0.0) || !std::isfinite(state.radius) ||
!(state.box > 0.0) || !std::isfinite(state.box) ||
state.radius + state.radius > state.box) {
throw std::logic_error(
"final state violates finite periodic geometry invariants");
}
if (!state.cells.validate(state.points)) {
throw std::logic_error(
"final state violates cell-list membership invariants");
}
const StrictOverlapCutoff cutoff =
make_strict_overlap_cutoff(state.radius + state.radius);
std::uint64_t distance_checks = 0;
for (std::size_t particle = 0; particle < state.points.size(); ++particle) {
if (has_strict_overlap(
state.points, state.cells, static_cast<int>(particle),
cutoff, state.box, distance_checks)) {
throw std::logic_error(
"final state contains an overlap under the source predicate");
}
}
}
RunResult run_engine(const InitialConfiguration& initial,
const Parameters& parameters,
Engine engine,
RunControls controls = {}) {
const auto start = Clock::now();
SimulationState state(initial, parameters.final_radius);
ReproducibleRng rng = initial.rng_after_initialization;
Workspace workspace(state.points.size());
Counters counters;
VerificationStats verification_stats;
StepVerification verification = controls.verification;
#ifndef NDEBUG
if (verification == StepVerification::none && state.points.size() <= 128U) {
verification = StepVerification::discovery_and_clear;
}
#endif
const double setup_seconds =
std::chrono::duration<double>(Clock::now() - start).count();
int threads_used = 1;
double discovery_seconds = 0.0;
double relaxation_seconds = 0.0;
double scheduler_seconds = 0.0;
if (engine == Engine::event) {
const auto scheduler_start = Clock::now();
EventCalendar calendar(state, parameters, counters);
scheduler_seconds +=
std::chrono::duration<double>(Clock::now() - scheduler_start).count();
for (std::size_t step = 1; step <= calendar.step_count(); ++step) {
state.radius = calendar.radius_at(step);
++counters.compression_steps;
const auto discovery_start = Clock::now();
const StrictOverlapCutoff cutoff =
make_strict_overlap_cutoff(
state.radius + state.radius, &counters.sqrt_calls);
calendar.discover_representatives(
state, step, workspace, cutoff, counters);
discovery_seconds +=
std::chrono::duration<double>(Clock::now() - discovery_start).count();
if (verification != StepVerification::none) [[unlikely]] {
verify_discovery_with_reference(
state, workspace.representatives, step, engine, verification_stats);
}
const auto relaxation_start = Clock::now();
relax_representatives(
state, workspace, rng, parameters, engine, cutoff, counters);
relaxation_seconds +=
std::chrono::duration<double>(Clock::now() - relaxation_start).count();
if (verification == StepVerification::discovery_and_clear) [[unlikely]] {
verify_clear_with_reference(state, step, engine, verification_stats);
}
const auto refresh_start = Clock::now();
calendar.finish_step(
state, step, workspace, counters, controls.force_event_rebuilds);
scheduler_seconds +=
std::chrono::duration<double>(Clock::now() - refresh_start).count();
#ifndef NDEBUG
if (!state.cells.validate(state.points)) {
throw std::logic_error("cell-list invariant failed during compression");
}
#endif
}
} else {
while (state.radius < parameters.final_radius) {
if (counters.compression_steps >= parameters.max_compression_steps) {
throw std::runtime_error("compression step limit exhausted");
}
state.radius =
next_compression_radius(state.radius, parameters);
++counters.compression_steps;
const auto discovery_start = Clock::now();
StrictOverlapCutoff cutoff;
if (engine == Engine::scan_legacy) {
std::fill(state.legacy_radii.begin(), state.legacy_radii.end(), state.radius);
counters.radius_writes += state.legacy_radii.size();
discover_overlaps_legacy(state, workspace, counters);
} else {
cutoff = make_strict_overlap_cutoff(
state.radius + state.radius, &counters.sqrt_calls);
if (engine == Engine::scan_fast) {
discover_overlaps_fast(
state, workspace, cutoff, counters);
} else {
threads_used = discover_overlaps_omp(
state, workspace, cutoff, counters,
parameters.threads);
}
}
discovery_seconds +=
std::chrono::duration<double>(Clock::now() - discovery_start).count();
if (verification != StepVerification::none) [[unlikely]] {
verify_discovery_with_reference(
state, workspace.representatives,
static_cast<std::size_t>(counters.compression_steps), engine,
verification_stats);
}
const auto relaxation_start = Clock::now();
relax_representatives(
state, workspace, rng, parameters, engine, cutoff, counters);
if (engine == Engine::scan_legacy) {
state.anchors = state.points;
counters.anchor_writes += state.anchors.size();
} else {
workspace.update_dirty_anchors(state, counters);
}
relaxation_seconds +=
std::chrono::duration<double>(Clock::now() - relaxation_start).count();
if (verification == StepVerification::discovery_and_clear) [[unlikely]] {
verify_clear_with_reference(
state, static_cast<std::size_t>(counters.compression_steps), engine,
verification_stats);
}
#ifndef NDEBUG
if (!state.cells.validate(state.points)) {
throw std::logic_error("cell-list invariant failed during compression");
}
#endif
}
}
const auto compression_end = Clock::now();
validate_final_state_fast(state);
RunResult result;
result.engine = engine;
result.seconds =
std::chrono::duration<double>(compression_end - start).count();
result.setup_seconds = setup_seconds;
result.discovery_seconds = discovery_seconds;
result.relaxation_seconds = relaxation_seconds;
result.scheduler_seconds = scheduler_seconds;
result.points = std::move(state.points);
result.radius = state.radius;
result.box = state.box;
result.threads_used = threads_used;
result.counters = counters;
result.verification = verification_stats;
if (!parameters.skip_oracle) {
result.oracle = final_oracle(
result.points, result.radius, result.box,
parameters.oracle_threads);
}
result.state_checksum = checksum(result.points, result.radius, result.box);
return result;
}
double maximum_coordinate_difference(const RunResult& lhs, const RunResult& rhs) {
if (lhs.points.size() != rhs.points.size()) {
return std::numeric_limits<double>::infinity();
}
double maximum = 0.0;
for (std::size_t particle = 0; particle < lhs.points.size(); ++particle) {
maximum = std::max(maximum, std::fabs(lhs.points[particle].x - rhs.points[particle].x));
maximum = std::max(maximum, std::fabs(lhs.points[particle].y - rhs.points[particle].y));
}
return maximum;
}
bool positions_bitwise_equal(const RunResult& lhs, const RunResult& rhs) {
if (lhs.points.size() != rhs.points.size() ||
std::bit_cast<std::uint64_t>(lhs.radius) !=
std::bit_cast<std::uint64_t>(rhs.radius) ||
std::bit_cast<std::uint64_t>(lhs.box) !=
std::bit_cast<std::uint64_t>(rhs.box)) {
return false;
}
for (std::size_t particle = 0; particle < lhs.points.size(); ++particle) {
if (std::bit_cast<std::uint64_t>(lhs.points[particle].x) !=
std::bit_cast<std::uint64_t>(rhs.points[particle].x) ||
std::bit_cast<std::uint64_t>(lhs.points[particle].y) !=
std::bit_cast<std::uint64_t>(rhs.points[particle].y)) {
return false;
}
}
return true;
}
std::string render_configuration(const RunResult& result,