-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathamr_program_context.hpp
More file actions
1873 lines (1729 loc) · 87.1 KB
/
Copy pathamr_program_context.hpp
File metadata and controls
1873 lines (1729 loc) · 87.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
/// @file
/// @brief Exact compile-time-ranked execution boundary for generated AMR Programs.
#pragma once
#include <pops/core/foundation/types.hpp>
#include <pops/mesh/execution/for_each.hpp>
#include <pops/mesh/storage/mf_arith.hpp>
#include <pops/numerics/elliptic/interface/field_nullspace.hpp>
#include <pops/numerics/elliptic/linear/generic_krylov.hpp>
#include <pops/numerics/elliptic/linear/solve_outcome.hpp>
#include <pops/numerics/time/amr/levels/amr_subcycling.hpp>
#include <pops/runtime/amr/amr_runtime.hpp>
#include <pops/runtime/amr_system.hpp>
#include <pops/runtime/builders/compiled/generated_amr_system_block.hpp>
#include <pops/runtime/multiblock/evaluation_point.hpp>
#include <pops/runtime/program/clock_schedule.hpp>
#include <pops/runtime/program/prepared_scalar_boundary_session.hpp>
#include <pops/runtime/program/program_runtime_state.hpp>
#include <pops/runtime/system/provider_storage_binding.hpp>
#include <algorithm>
#include <array>
#include <bit>
#include <chrono>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <exception>
#include <functional>
#include <initializer_list>
#include <limits>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <span>
#include <stdexcept>
#include <string>
#include <string_view>
#include <tuple>
#include <type_traits>
#include <utility>
#include <vector>
namespace pops::runtime::program {
template <int Dim>
struct ProgramSpatialSnapshot {
std::string spatial_contract;
std::uint64_t topology_epoch = 0;
std::uint64_t materialization_generation = 0;
bool operator==(const ProgramSpatialSnapshot&) const = default;
};
/// One Program specialization over one immutable native rank.
///
/// The context never decodes a dimension tag and never pads an absent axis. Its active level is a
/// compile-time-ranked `MultiFab<Dim>` selected from the exact `AmrRuntime<Dim>` hierarchy. The
/// retained generated block owns geometry, physical boundaries, same-level/coarse-fine ghost fill,
/// residual assembly and integrated face fluxes. Unsupported provider families fail before a valid
/// cell is changed.
template <int Dim, class MemorySpace = typename Kokkos::DefaultExecutionSpace::memory_space>
class AmrProgramContext {
public:
static_assert(Dim >= 1 && Dim <= 3, "AmrProgramContext only supports dimensions 1, 2, and 3");
static_assert(std::is_same_v<MemorySpace, typename Kokkos::DefaultExecutionSpace::memory_space>,
"AmrProgramContext memory space must match its compiled AmrSystem leaf");
static constexpr int dimension = Dim;
using facade_type = ::pops::AmrSystem<Dim>;
using runtime_type = ::pops::runtime::amr::AmrRuntime<Dim, MemorySpace>;
using hierarchy_type = typename runtime_type::hierarchy_type;
using field_type = typename runtime_type::field_type;
using runtime_state_type = ProgramRuntimeState<Dim>;
using scalar_boundary_session_type = PreparedScalarBoundarySession<Dim>;
using subcycle_plan_type = ::pops::numerics::time::amr::PreparedAmrSubcyclePlan<Dim, MemorySpace>;
using hierarchy_tensor_provider_type = HierarchyTensorSolverProvider<Dim, MemorySpace>;
using hierarchy_tensor_registry_type = HierarchyTensorSolverProviderRegistry<Dim, MemorySpace>;
using hierarchy_tensor_solver_type = PreparedHierarchyTensorSolver<Dim, MemorySpace>;
using hierarchy_tensor_request_type = HierarchyTensorSolverBuildRequest<Dim>;
struct ProgramResourceTopology {
int levels = 0;
std::uint64_t epoch = 0;
std::uint64_t generation = 0;
};
struct FieldStageOverride {
int program_block = -1;
const field_type* state = nullptr;
};
struct RhsGroupRequest {
RhsGroupRequest(int block_value, field_type* state_value, field_type* rhs_value,
int rate_id_value, int flux_only_value)
: block(block_value),
state(state_value),
rhs(rhs_value),
rate_id(rate_id_value),
flux_only(flux_only_value) {}
int block = -1;
field_type* state = nullptr;
field_type* rhs = nullptr;
int rate_id = -1;
int flux_only = 0;
};
struct CouplingStateOverride {
int program_block = -1;
field_type* state = nullptr;
};
struct HierarchyTensorSelection {
int program_block = -1;
int components = 0;
std::string provider_identity;
std::string plan_identity;
std::string operator_contract_identity;
std::vector<std::string> assembly_field_slots;
std::string solution_field_slot;
PreparedProviderOptions options;
std::string exact_contract;
};
class LogicalEvaluationScope {
public:
LogicalEvaluationScope(const AmrProgramContext& owner, int iteration, int count)
: owner_(&owner), prior_dt_(owner.current_dt_), prior_substep_(owner.logical_substep_) {
if (iteration < 0 || count < 1 || iteration >= count || !std::isfinite(prior_dt_) ||
!(prior_dt_ > 0.0))
throw std::invalid_argument("AMR logical evaluation scope is invalid");
owner_->current_dt_ = prior_dt_ / static_cast<double>(count);
owner_->logical_substep_ = iteration;
}
LogicalEvaluationScope(const LogicalEvaluationScope&) = delete;
LogicalEvaluationScope& operator=(const LogicalEvaluationScope&) = delete;
LogicalEvaluationScope(LogicalEvaluationScope&& other) noexcept
: owner_(std::exchange(other.owner_, nullptr)),
prior_dt_(other.prior_dt_),
prior_substep_(other.prior_substep_) {}
~LogicalEvaluationScope() {
if (owner_ != nullptr) {
owner_->current_dt_ = prior_dt_;
owner_->logical_substep_ = prior_substep_;
}
}
Real dt() const { return static_cast<Real>(owner_->current_dt_); }
private:
const AmrProgramContext* owner_ = nullptr;
double prior_dt_ = 0.0;
int prior_substep_ = 0;
};
explicit AmrProgramContext(facade_type* facade)
: facade_(require_facade_(facade)), runtime_(require_runtime_(*facade_)) {
facade_->refresh_prepared_amr_levels();
hierarchy_tensor_solver_registry_ = facade_->hierarchy_tensor_solver_provider_registry();
scalar_boundary_lane_.emplace(ExecutionLane::duplicate_world_collectively(
"pops.program.amr.scalar-boundary.nd" + std::to_string(Dim)));
synchronize_resource_generation_();
}
AmrProgramContext(runtime_type* runtime, facade_type* facade)
: facade_(require_facade_(facade)), runtime_(require_runtime_(runtime)) {
if (facade_->engine() != runtime_)
throw std::invalid_argument("AMR Program facade and runtime do not share one hierarchy");
facade_->refresh_prepared_amr_levels();
hierarchy_tensor_solver_registry_ = facade_->hierarchy_tensor_solver_provider_registry();
scalar_boundary_lane_.emplace(ExecutionLane::duplicate_world_collectively(
"pops.program.amr.scalar-boundary.nd" + std::to_string(Dim)));
synchronize_resource_generation_();
}
/// Spatial-only constructor used by preparation tests. Execution methods require a facade.
explicit AmrProgramContext(runtime_type& runtime) : runtime_(&runtime) {
synchronize_resource_generation_();
}
runtime_type& runtime() const noexcept { return *runtime_; }
hierarchy_type& hierarchy() const noexcept { return runtime_->hierarchy(); }
const ::pops::amr::hierarchy::LevelLayout<Dim>& layout(std::size_t selected) const {
return runtime_->hierarchy().layout(selected);
}
field_type& state(std::size_t selected) const { return runtime_->hierarchy().state(selected); }
::pops::runtime::amr::PreparedTaggerCandidates<Dim> execute_prepared_tagging(
int parent_level) const {
if (facade_ == nullptr)
throw std::logic_error(
"AMR Program tagging execution requires the exact-ranked facade authority");
return facade_->execute_prepared_tagging(parent_level);
}
bool regrid_from_prepared_tagging(int parent_level) const {
if (facade_ == nullptr)
throw std::logic_error(
"AMR Program regrid publication requires the exact-ranked facade authority");
require_history_free_for_topology_change_("prepared tagging regrid");
return facade_->regrid_from_prepared_tagging(parent_level);
}
ProgramSpatialSnapshot<Dim> spatial_snapshot() const {
return {std::string(runtime_->spatial_contract()), runtime_->topology_epoch(),
runtime_->materialization_generation()};
}
void require_live(const ProgramSpatialSnapshot<Dim>& snapshot) const {
if (snapshot.spatial_contract != runtime_->spatial_contract() ||
snapshot.topology_epoch != runtime_->topology_epoch() ||
snapshot.materialization_generation != runtime_->materialization_generation())
throw std::invalid_argument("AMR Program spatial snapshot is stale");
}
subcycle_plan_type prepare_subcycling(
std::span<const int> temporal_substeps,
::pops::numerics::time::amr::AmrSubcyclePreparationBudget budget) const {
return subcycle_plan_type::prepare(*runtime_, temporal_substeps, budget);
}
::pops::amr::regridding::PreparedRegrid<Dim> prepare_regrid(
std::size_t parent_level, ::pops::amr::RefinementRatio<Dim> ratio,
::pops::amr::tagging::ClusterResult<Dim> clustered,
::pops::amr::regridding::RegridPreparationBudget preparation_budget,
const ExecutionLane& lane = ExecutionLane::world()) const {
return runtime_->prepare_regrid(parent_level, ratio, std::move(clustered), preparation_budget,
lane);
}
void publish_regrid(::pops::amr::regridding::PreparedRegrid<Dim> prepared,
std::optional<field_type> child_state) const {
require_history_free_for_topology_change_("regrid");
const int parent_level = prepared.source_level().level;
if (parent_level < 0)
throw std::invalid_argument("AMR Program regrid has no source level");
runtime_->publish_regrid(static_cast<std::size_t>(parent_level), std::move(prepared),
std::move(child_state));
}
PreparedRebalanceDecision<Dim> prepare_rebalance(
std::size_t selected, ResourceEstimates estimates,
parallel::LoadBalancePreparationBudget preparation_budget, const RebalancePolicy& policy,
const ExecutionLane& lane = ExecutionLane::world()) const {
return runtime_->prepare_rebalance(selected, estimates, preparation_budget, policy, lane);
}
PreparedRebalanceDecision<Dim> prepare_rebalance(
std::size_t selected, ResourceEstimates estimates,
parallel::LoadBalancePreparationBudget preparation_budget,
const ExecutionLane& lane = ExecutionLane::world()) const {
return runtime_->prepare_rebalance(selected, estimates, preparation_budget, lane);
}
void apply_rebalance(std::size_t selected, PreparedRebalanceDecision<Dim> decision,
field_type remapped_state) const {
require_history_free_for_topology_change_("rebalance");
runtime_->apply_rebalance(selected, std::move(decision), std::move(remapped_state));
}
template <class Payload, class Axpy>
::pops::amr::reflux::MetricFaceReflux<Payload> reconcile_reflux(
const ::pops::amr::reflux::TransactionalFaceFluxLedger<Dim, Payload>& ledger,
const ::pops::amr::reflux::CoarseFaceRefluxKey<Dim>& key, std::string_view state_identity,
const ::pops::amr::reflux::FaceRefinementMapping<Dim>& mapping,
const ::pops::amr::reflux::MetricRefluxBudget& budget, Axpy&& axpy) const {
return runtime_->reconcile_reflux(ledger, key, state_identity, mapping, budget,
std::forward<Axpy>(axpy));
}
void install(std::function<void(double)> step) const {
require_facade_execution_();
if (!step)
throw std::invalid_argument("AMR Program install requires a non-empty step");
facade_->install_program_step(std::move(step));
}
void install(std::function<void(double)> step, std::shared_ptr<AmrProgramContext> keep_alive,
std::function<void()> hierarchy_refresh = {}) const {
require_facade_execution_();
if (!step || !keep_alive || keep_alive.get() != this)
throw std::invalid_argument("AMR Program install requires its exact owning context");
facade_->install_program_step(
[step = std::move(step), keep_alive = std::move(keep_alive)](double dt) { step(dt); });
if (hierarchy_refresh)
facade_->install_program_hierarchy_refresh(std::move(hierarchy_refresh));
}
void begin_step(double dt) const {
if (!std::isfinite(dt) || !(dt > 0.0))
throw std::invalid_argument("AMR Program step requires a finite positive dt");
current_dt_ = dt;
stage_time_ = ::pops::amr::Rational(0, 1);
logical_substep_ = 0;
}
void configure_primary_clock(const std::string& clock) const {
clock_schedule_.configure_primary_clock(clock);
primary_clock_ = clock;
}
void declare_clock_relation(const std::string& parent, const std::string& child,
int count) const {
clock_schedule_.declare_relation(parent, child, count);
}
void set_stage_time(std::int64_t numerator, std::int64_t denominator) const {
if (denominator <= 0 || numerator < 0 || numerator > denominator)
throw std::invalid_argument("AMR Program stage time is outside [0, 1]");
stage_time_ = ::pops::amr::Rational(numerator, denominator);
}
runtime::multiblock::BoundaryEvaluationPoint boundary_evaluation_point(int stage) const {
require_rate_identity_(stage);
require_facade_execution_();
if (primary_clock_.empty() || !std::isfinite(current_dt_) || !(current_dt_ > 0.0))
throw std::logic_error("AMR Program evaluation point lacks an active clock interval");
return {.clock = primary_clock_,
.tick = static_cast<std::int64_t>(facade_->macro_step()),
.level = active_level_,
.substep = logical_substep_,
.stage = stage,
.stage_fraction = stage_time_,
.dt = current_dt_,
.physical_time = facade_->time() + stage_time_.value() * current_dt_};
}
template <class Body>
void advance_hierarchy(double dt, Body&& body) const {
begin_step(dt);
refresh_resources_();
require_single_level_conservative_route_("advance_hierarchy");
with_program_resource_level(0, [&] { std::forward<Body>(body)(dt); });
}
template <class Body>
void advance_synchronized_hierarchy(double dt, Body&& body) const {
begin_step(dt);
refresh_resources_();
require_single_level_conservative_route_("advance_synchronized_hierarchy");
with_program_resource_level(0, [&] { std::forward<Body>(body)(dt); });
}
[[noreturn]] void prepare_same_level_cell_temporal_execution(std::string, std::int64_t,
int = 0) const {
unavailable_("cell-local AMR temporal provider");
}
[[noreturn]] void advance_same_level_cell_temporal(double) const {
unavailable_("cell-local AMR temporal provider");
}
bool uses_prepared_krylov_fallback() const {
return configured_hierarchy_tensor_solver_().execution_path() ==
HierarchyTensorSolverExecutionPath::PreparedKrylovFallback;
}
int nlev() const { return static_cast<int>(runtime_->hierarchy().num_levels()); }
int level() const noexcept { return active_level_; }
ProgramResourceTopology program_resource_topology() const {
refresh_resources_();
return {nlev(), runtime_->topology_epoch(), runtime_->materialization_generation()};
}
template <class Function>
void for_each_program_resource_level(Function&& function) const {
refresh_resources_();
const int prior = active_level_;
try {
for (int selected = 0; selected < nlev(); ++selected) {
active_level_ = selected;
function(selected);
}
active_level_ = prior;
} catch (...) {
active_level_ = prior;
throw;
}
}
template <class Function>
decltype(auto) with_program_resource_level(int selected, Function&& function) const {
if (selected < 0 || selected >= nlev())
throw std::out_of_range("AMR Program resource level lies outside the live hierarchy");
const int prior = active_level_;
active_level_ = selected;
try {
if constexpr (std::is_void_v<std::invoke_result_t<Function>>) {
std::forward<Function>(function)();
active_level_ = prior;
} else {
decltype(auto) result = std::forward<Function>(function)();
active_level_ = prior;
return result;
}
} catch (...) {
active_level_ = prior;
throw;
}
}
int n_blocks() const {
require_facade_execution_();
return facade_->n_blocks();
}
int sys_block(int program_block) const {
require_facade_execution_();
const auto& map = facade_->program_block_map();
if (program_block < 0 || static_cast<std::size_t>(program_block) >= map.size())
throw std::out_of_range("AMR Program block has no authenticated runtime mapping");
const int selected = map[static_cast<std::size_t>(program_block)];
if (selected < 0 || selected >= facade_->n_blocks())
throw std::runtime_error("AMR Program block mapping targets no runtime block");
return selected;
}
field_type& state(int program_block) const {
if (sys_block(program_block) != 0)
unavailable_("exact-ranked multi-block AMR state provider");
refresh_resources_();
return runtime_->hierarchy().state(static_cast<std::size_t>(active_level_));
}
/// Bind one generated consumer's compact provider view for the active AMR hierarchy level.
/// The program block is authenticated before storage lookup; the qid resolves through that
/// level's sealed plan, so neither generated code nor this context can fall back to ``ctx.aux``.
template <int Count>
[[nodiscard]] ProviderStorageView<Dim, Count> provider_values_view(
std::string_view consumer_qid, int program_block, std::size_t local_fab) const {
static_assert(Count >= 0, "a provider consumer count cannot be negative");
if constexpr (Count == 0) {
(void)consumer_qid;
(void)program_block;
(void)local_fab;
return {};
} else {
const field_type& state_field = state(program_block);
const auto* const groups =
facade_->prepared_amr_provider_storage_groups(active_level_);
const auto& plan = facade_->prepared_amr_auxiliary_consumer_plan(
std::string(consumer_qid), active_level_);
runtime::system::require_pointwise_provider_groups<Dim, Count>(
state_field, groups, &plan, "AmrProgramContext provider values");
return runtime::system::bind_provider_storage_view<Dim, Count>(&plan, groups, local_fab);
}
}
field_type rhs_scratch_like(const field_type& prototype) const {
return make_scratch_(prototype, prototype.ncomp(), prototype.ghosts());
}
field_type scratch_state_like(const field_type& prototype) const {
return make_scratch_(prototype, prototype.ncomp(), prototype.ghosts());
}
field_type& rhs_scratch(std::int64_t value_id, int subslot, const field_type& prototype) const {
return persistent_scratch_(ScratchKind::Rhs, value_id, subslot, prototype, prototype.ncomp(),
prototype.ghosts());
}
field_type& scratch_state(std::int64_t value_id, int subslot, const field_type& prototype) const {
return persistent_scratch_(ScratchKind::State, value_id, subslot, prototype, prototype.ncomp(),
prototype.ghosts());
}
field_type& scalar_scratch(std::int64_t value_id, int subslot, const field_type& prototype,
int ncomp = 1, int ghost_depth = 1) const {
return persistent_scratch_(ScratchKind::Scalar, value_id, subslot, prototype, ncomp,
uniform_ghosts_(ghost_depth));
}
field_type alloc_scalar_field(int ncomp = 1, int ghost_depth = 1) const {
if (ncomp < 1 || ghost_depth < 0)
throw std::invalid_argument("AMR Program scalar allocation has an invalid shape");
const field_type& prototype =
runtime_->hierarchy().state(static_cast<std::size_t>(active_level_));
return make_scratch_(prototype, ncomp, uniform_ghosts_(ghost_depth));
}
void rhs_into(int program_block, field_type& stage_state, field_type& rhs, int rate_id) const {
if (sys_block(program_block) != 0)
unavailable_("exact-ranked multi-block AMR residual provider");
require_rate_identity_(rate_id);
require_same_field_contract_(stage_state, rhs, "AMR Program residual");
const auto& evaluation =
facade_->evaluate_prepared_amr_level_at(boundary_evaluation_point(rate_id), stage_state);
copy_valid_(evaluation.residual, rhs);
count_kernel_();
}
void rhs_group(int group_id, std::initializer_list<RhsGroupRequest> requests) const {
require_rate_identity_(group_id);
std::vector<field_type> candidates;
candidates.reserve(requests.size());
for (const RhsGroupRequest& request : requests) {
if (request.state == nullptr || request.rhs == nullptr || request.rate_id < 0 ||
request.rate_id == group_id || request.flux_only != 0)
throw std::invalid_argument("AMR Program RHS group contains an unsupported request");
candidates.push_back(rhs_scratch_like(*request.rhs));
}
std::size_t index = 0;
for (const RhsGroupRequest& request : requests)
rhs_into(request.block, *request.state, candidates[index++], request.rate_id);
index = 0;
for (const RhsGroupRequest& request : requests)
copy_valid_(candidates[index++], *request.rhs);
}
[[noreturn]] void neg_div_flux_default_into(int, field_type&, field_type&, int) const {
unavailable_("split default-flux AMR provider");
}
[[noreturn]] void source_default_into(int, field_type&, field_type&) const {
unavailable_("split default-source AMR provider");
}
void require_cartesian_generated_operator(int program_block, const std::string& operation) const {
(void)sys_block(program_block);
if (operation.empty())
throw std::invalid_argument("AMR generated operator requires an operation identity");
}
void prepare_generated_state(int program_block, field_type& stage_state, int rate_id) const {
if (sys_block(program_block) != 0)
unavailable_("exact-ranked multi-block AMR state preparation");
require_rate_identity_(rate_id);
facade_->prepare_generated_amr_level_state(boundary_evaluation_point(rate_id), stage_state);
}
void neg_div_named_flux_into(field_type& rhs, const std::array<field_type*, Dim>& fluxes) const {
const Geometry<Dim> geom = geometry();
for (int axis = 0; axis < Dim; ++axis) {
const field_type* flux = fluxes[static_cast<std::size_t>(axis)];
if (flux == nullptr || flux->layout() != rhs.layout() ||
flux->distribution() != rhs.distribution() || flux->local_rank() != rhs.local_rank() ||
flux->local_size() != rhs.local_size() || flux->ncomp() != rhs.ncomp() ||
flux->ghosts()[axis] < 1)
throw std::invalid_argument("AMR named flux differs from its exact residual layout");
}
for (std::size_t local = 0; local < rhs.local_size(); ++local) {
std::array<FieldView<const Real, Dim>, Dim> views{};
for (int axis = 0; axis < Dim; ++axis)
views[static_cast<std::size_t>(axis)] =
std::as_const(*fluxes[static_cast<std::size_t>(axis)]).fab(local).view();
const FieldView<Real, Dim> output = rhs.fab(local).view();
const int components = rhs.ncomp();
for_each_cell(rhs.box(local), [=] POPS_HD(const Index<Dim>& cell) {
for (int component = 0; component < components; ++component) {
Real divergence = Real(0);
for (int axis = 0; axis < Dim; ++axis) {
Index<Dim> lower = cell;
Index<Dim> upper = cell;
--lower[axis];
++upper[axis];
divergence += (views[static_cast<std::size_t>(axis)](upper, component) -
views[static_cast<std::size_t>(axis)](lower, component)) /
(Real(2) * geom.spacing(axis));
}
output(cell, component) = -divergence;
}
});
}
count_kernel_();
}
[[noreturn]] void apply_projection(int, field_type&) const {
unavailable_("generated AMR projection provider");
}
Real max_wave_speed(int program_block, const field_type& stage_state) const {
if (sys_block(program_block) != 0)
unavailable_("exact-ranked multi-block AMR wave-speed provider");
return facade_->prepared_amr_level_maximum_speed(active_level_, stage_state);
}
Real hmin() const {
const Geometry<Dim> geom = geometry();
Real result = geom.spacing(0);
for (int axis = 1; axis < Dim; ++axis)
result = std::min(result, geom.spacing(axis));
return result;
}
RuntimeParams program_params(int program_block) const {
(void)sys_block(program_block);
return facade_->program_params(program_block);
}
void axpy(field_type& destination, Real factor, const field_type& source) const {
require_same_field_contract_(destination, source, "AMR Program axpy");
pops::saxpy(destination, factor, source);
count_kernel_();
}
void axpy(field_type& destination, Real factor, const field_type& source, Real,
std::initializer_list<ExactCoefficientTerm>) const {
axpy(destination, factor, source);
}
void lincomb(field_type& destination, Real left_factor, const field_type& left, Real right_factor,
const field_type& right) const {
require_same_field_contract_(destination, left, "AMR Program linear combination");
require_same_field_contract_(destination, right, "AMR Program linear combination");
pops::lincomb(destination, left_factor, left, right_factor, right);
count_kernel_();
}
void lincomb(field_type& destination, Real left_factor, const field_type& left, Real right_factor,
const field_type& right, Real, std::initializer_list<ExactCoefficientTerm>,
std::initializer_list<ExactCoefficientTerm>) const {
lincomb(destination, left_factor, left, right_factor, right);
}
void commit_many(std::initializer_list<std::pair<field_type*, const field_type*>> commits) const {
std::vector<field_type*> targets;
std::vector<std::optional<field_type>> candidates;
targets.reserve(commits.size());
candidates.reserve(commits.size());
for (const auto& [target, source] : commits) {
if (target == nullptr || source == nullptr ||
std::find(targets.begin(), targets.end(), target) != targets.end())
throw std::invalid_argument("AMR Program commit has null or duplicate storage");
require_same_field_contract_(*target, *source, "AMR Program commit");
targets.push_back(target);
candidates.emplace_back(target == source ? std::nullopt : std::optional<field_type>(*source));
}
std::size_t index = 0;
for (const auto& [target, source] : commits) {
if (target != source)
*target = std::move(*candidates[index]);
++index;
}
}
[[noreturn]] void apply_coupling_operators(Real,
std::initializer_list<CouplingStateOverride>) const {
unavailable_("exact-ranked multi-block AMR coupling provider");
}
Real sum_component(const field_type& field, int component) const {
return pops::reduce_sum(field, component);
}
Real max_component(const field_type& field, int component) const {
return pops::reduce_max(field, component);
}
Real min_component(const field_type& field, int component) const {
return pops::reduce_min(field, component);
}
Real norm2(int, const field_type& field) const { return std::sqrt(pops::dot(field, field, 0)); }
Real norm_inf(int, const field_type& field) const { return pops::reduce_norm_inf(field, 0); }
Real dot(int, const field_type& left, const field_type& right) const {
return pops::dot(left, right, 0);
}
Geometry<Dim> geometry() const {
require_facade_execution_();
return facade_->prepared_amr_level_geometry(active_level_);
}
field_type& assembly_target(field_type& field, std::string_view identity) const {
if (identity.empty())
throw std::invalid_argument("AMR Program assembly target requires an identity");
if (!hierarchy_tensor_selection_)
return field;
hierarchy_tensor_solver_type& solver = configured_hierarchy_tensor_solver_();
if (solver.execution_path() == HierarchyTensorSolverExecutionPath::PreparedKrylovFallback)
return field;
if (std::find(hierarchy_tensor_selection_->assembly_field_slots.begin(),
hierarchy_tensor_selection_->assembly_field_slots.end(),
identity) == hierarchy_tensor_selection_->assembly_field_slots.end())
throw std::invalid_argument("AMR hierarchy assembly used an undeclared provider field slot");
return solver.assembly_target(identity, active_level_);
}
field_type& assembly_source(field_type& field, std::string_view identity) const {
if (identity.empty())
throw std::invalid_argument("AMR Program assembly source requires an identity");
if (!hierarchy_tensor_selection_)
return field;
hierarchy_tensor_solver_type& solver = configured_hierarchy_tensor_solver_();
if (solver.execution_path() == HierarchyTensorSolverExecutionPath::PreparedKrylovFallback)
return field;
if (identity != hierarchy_tensor_selection_->solution_field_slot)
throw std::invalid_argument("AMR hierarchy read used an undeclared provider solution slot");
return solver.solution(active_level_);
}
std::shared_ptr<scalar_boundary_session_type> prepare_mesh_boundary_session(
field_type& prototype, const ExecutionLane& lane) const {
return std::make_shared<scalar_boundary_session_type>(
geometry(), facade_->prepared_amr_boundary_topology(), prototype, lane,
next_boundary_generation_());
}
std::shared_ptr<scalar_boundary_session_type> prepare_block_boundary_session(
int program_block, field_type& prototype,
const runtime::multiblock::BoundaryEvaluationPoint& point, const ExecutionLane& lane) const {
(void)sys_block(program_block);
require_boundary_point_(point, "AMR block scalar boundary");
return prepare_mesh_boundary_session(prototype, lane);
}
void fill_boundary(field_type& field) const {
if (!scalar_boundary_lane_)
throw std::logic_error("AMR Program boundary fill requires an execution facade");
fill_boundary(field, *scalar_boundary_lane_);
}
void fill_boundary(field_type& field, const ExecutionLane& lane) const {
scalar_boundary_session_type session(geometry(), facade_->prepared_amr_boundary_topology(),
field, lane, next_boundary_generation_());
session.fill(field);
}
void laplacian(field_type& output, field_type& input) const {
require_scalar_stencil_(output, input, 1, "AMR Program Laplacian");
fill_boundary(input);
const Geometry<Dim> geom = geometry();
for (std::size_t local = 0; local < output.local_size(); ++local) {
const FieldView<Real, Dim> result = output.fab(local).view();
const FieldView<const Real, Dim> value = std::as_const(input).fab(local).view();
for_each_cell(output.box(local), [=] POPS_HD(const Index<Dim>& cell) {
Real image = Real(0);
for (int axis = 0; axis < Dim; ++axis) {
Index<Dim> lower = cell;
Index<Dim> upper = cell;
--lower[axis];
++upper[axis];
const Real spacing = geom.spacing(axis);
image +=
(value(upper, 0) - Real(2) * value(cell, 0) + value(lower, 0)) / (spacing * spacing);
}
result(cell, 0) = image;
});
}
count_kernel_();
}
void laplacian(field_type& output, field_type& input,
const scalar_boundary_session_type& boundary) const {
boundary.fill(input);
laplacian_without_fill_(output, input, boundary.geometry());
}
void laplacian(field_type& output, field_type& input,
const scalar_boundary_session_type& boundary,
const runtime::multiblock::BoundaryEvaluationPoint& point) const {
require_boundary_point_(point, "AMR Program Laplacian");
laplacian(output, input, boundary);
}
void gradient(field_type& output, field_type& input) const {
require_scalar_stencil_(output, input, Dim, "AMR Program gradient");
fill_boundary(input);
const Geometry<Dim> geom = geometry();
for (std::size_t local = 0; local < output.local_size(); ++local) {
const FieldView<Real, Dim> result = output.fab(local).view();
const FieldView<const Real, Dim> value = std::as_const(input).fab(local).view();
for_each_cell(output.box(local), [=] POPS_HD(const Index<Dim>& cell) {
for (int axis = 0; axis < Dim; ++axis) {
Index<Dim> lower = cell;
Index<Dim> upper = cell;
--lower[axis];
++upper[axis];
result(cell, axis) = (value(upper, 0) - value(lower, 0)) / (Real(2) * geom.spacing(axis));
}
});
}
count_kernel_();
}
void gradient(field_type& output, field_type& input,
const scalar_boundary_session_type& boundary) const {
boundary.fill(input);
gradient_without_fill_(output, input, boundary.geometry());
}
void gradient(field_type& output, field_type& input, const scalar_boundary_session_type& boundary,
const runtime::multiblock::BoundaryEvaluationPoint& point) const {
require_boundary_point_(point, "AMR Program gradient");
gradient(output, input, boundary);
}
void divergence(field_type& output, field_type& flux) const {
if (output.ncomp() != 1 || flux.ncomp() != Dim)
throw std::invalid_argument("AMR Program divergence requires one exact native vector field");
require_same_layout_(output, flux, "AMR Program divergence");
fill_boundary(flux);
const Geometry<Dim> geom = geometry();
for (std::size_t local = 0; local < output.local_size(); ++local) {
const FieldView<Real, Dim> result = output.fab(local).view();
const FieldView<const Real, Dim> vector = std::as_const(flux).fab(local).view();
for_each_cell(output.box(local), [=] POPS_HD(const Index<Dim>& cell) {
Real value = Real(0);
for (int axis = 0; axis < Dim; ++axis) {
Index<Dim> lower = cell;
Index<Dim> upper = cell;
--lower[axis];
++upper[axis];
value += (vector(upper, axis) - vector(lower, axis)) / (Real(2) * geom.spacing(axis));
}
result(cell, 0) = value;
});
}
count_kernel_();
}
void divergence(field_type& output, field_type& flux, const scalar_boundary_session_type&) const {
divergence(output, flux);
}
void divergence(field_type& output, field_type& flux,
const scalar_boundary_session_type& boundary,
const runtime::multiblock::BoundaryEvaluationPoint& point) const {
require_boundary_point_(point, "AMR Program divergence");
divergence(output, flux, boundary);
}
void pack_vector(field_type& output, const std::array<const field_type*, Dim>& components) const {
if (output.ncomp() != Dim)
throw std::invalid_argument("AMR Program vector packing requires Dim output components");
for (const field_type* component : components)
if (component == nullptr || component->ncomp() != 1)
throw std::invalid_argument("AMR Program vector packing requires scalar components");
for (std::size_t local = 0; local < output.local_size(); ++local) {
std::array<FieldView<const Real, Dim>, Dim> values{};
for (int axis = 0; axis < Dim; ++axis) {
require_same_layout_(output, *components[static_cast<std::size_t>(axis)],
"AMR Program vector packing");
values[static_cast<std::size_t>(axis)] =
components[static_cast<std::size_t>(axis)]->fab(local).view();
}
const FieldView<Real, Dim> result = output.fab(local).view();
for_each_cell(output.box(local), [=] POPS_HD(const Index<Dim>& cell) {
for (int axis = 0; axis < Dim; ++axis)
result(cell, axis) = values[static_cast<std::size_t>(axis)](cell, 0);
});
}
count_kernel_();
}
[[noreturn]] void tensor_laplacian(field_type&, field_type&, const field_type&) const {
unavailable_("AMR tensor-elliptic provider");
}
template <class... Arguments>
[[noreturn]] void tensor_laplacian(Arguments&&...) const {
unavailable_("AMR tensor-elliptic provider");
}
/// Copy one exact valid-cell component span without exposing distributed storage to generated
/// code. Aliasing copies select their component direction before the kernel launches, so an
/// overlapping in-place pack cannot overwrite a value that has not yet been read.
void copy_component_span(field_type& destination, int destination_component,
const field_type& source, int source_component,
int component_count) const {
if (component_count <= 0 || destination_component < 0 || source_component < 0 ||
destination_component > destination.ncomp() - component_count ||
source_component > source.ncomp() - component_count)
throw std::invalid_argument("AMR Program component-span copy has an invalid range");
require_same_layout_(destination, source, "AMR Program component-span copy");
for (std::size_t local = 0; local < destination.local_size(); ++local) {
if (destination.global_index(local) != source.global_index(local))
throw std::logic_error(
"AMR Program component-span copy found inconsistent local ownership");
}
if (&destination == &source && destination_component == source_component)
return;
const bool copy_backward = &destination == &source &&
destination_component > source_component &&
destination_component < source_component + component_count;
for (std::size_t local = 0; local < destination.local_size(); ++local) {
const FieldView<Real, Dim> output = destination.fab(local).view();
const FieldView<const Real, Dim> input = std::as_const(source).fab(local).view();
for_each_cell(destination.box(local), [=] POPS_HD(const Index<Dim>& cell) {
if (copy_backward) {
for (int offset = component_count; offset-- > 0;)
output(cell, destination_component + offset) = input(cell, source_component + offset);
} else {
for (int offset = 0; offset < component_count; ++offset)
output(cell, destination_component + offset) = input(cell, source_component + offset);
}
});
}
count_kernel_();
}
/// Register one level-qualified exact-ranked history ring. The generated AMR installer invokes
/// this while constructing each level bundle, so one authored history maps to one immutable
/// layout contract per active level instead of a 2-D or owner-erased global buffer.
void register_history(const std::string& name, int lag, int ncomp, int program_owner,
const std::string& state_identity, const std::string& space_identity,
const std::string& clock_identity,
const std::string& interpolation_identity) const {
if (name.empty() || lag < 1 || program_owner < 0 || state_identity.empty() ||
space_identity.empty() || clock_identity.empty() || interpolation_identity.empty())
throw std::invalid_argument(
"AMR Program history requires complete owner/state/space/clock identities");
if (sys_block(program_owner) != 0)
unavailable_("exact-ranked multi-block AMR history provider");
refresh_resources_();
const field_type& prototype = state(program_owner);
const int components = ncomp < 0 ? prototype.ncomp() : ncomp;
if (components < 1)
throw std::invalid_argument("AMR Program history component count must be positive");
const std::string key = history_key_(name, active_level_);
auto& manager = runtime_state().hist_;
const int depth = lag + 1;
const auto found = manager.histories.find(key);
if (found != manager.histories.end()) {
const field_type& retained = found->second.front();
if (manager.depth.at(key) != depth || manager.owner.at(key) != 0 ||
retained.layout() != prototype.layout() ||
retained.distribution() != prototype.distribution() ||
retained.local_rank() != prototype.local_rank() || retained.ncomp() != components ||
retained.ghosts() != prototype.ghosts() ||
manager.state_identity.at(key) != state_identity ||
manager.space_identity.at(key) != space_identity ||
manager.clock_identity.at(key) != clock_identity ||
manager.interpolation_identity.at(key) != interpolation_identity)
throw std::runtime_error(
"AMR Program history identity changed after exact-ranked registration");
history_levels_.insert_or_assign(key, active_level_);
return;
}
std::vector<field_type> ring;
ring.reserve(static_cast<std::size_t>(depth));
for (int slot = 0; slot < depth; ++slot)
ring.push_back(make_scratch_(prototype, components, prototype.ghosts()));
manager.histories.emplace(key, std::move(ring));
manager.depth[key] = depth;
manager.initialized[key] = false;
manager.fill_count[key] = 0;
manager.store_pending[key] = false;
manager.owner[key] = 0;
manager.state_identity[key] = state_identity;
manager.space_identity[key] = space_identity;
manager.clock_identity[key] = clock_identity;
manager.interpolation_identity[key] = interpolation_identity;
manager.slot_dt[key] = std::vector<Real>(static_cast<std::size_t>(depth), Real(0));
history_levels_.emplace(key, active_level_);
if (history_epoch_ == std::numeric_limits<std::uint64_t>::max()) {
history_epoch_ = runtime_->topology_epoch();
history_generation_ = runtime_->materialization_generation();
}
}
field_type& history(const std::string& name, int lag, int program_owner) const {
require_history_owner_(program_owner);
return history_slot_(name, lag, /*zero_start=*/false, /*components=*/-1);
}
field_type& history(const std::string& name, int lag = 1) const {
return history_slot_(name, lag, /*zero_start=*/false, /*components=*/-1);
}
field_type& history_zero_start(const std::string& name, int lag, int ncomp,
int program_owner) const {
require_history_owner_(program_owner);
return history_slot_(name, lag, /*zero_start=*/true, ncomp);
}
field_type& history_zero_start(const std::string& name, int lag, int ncomp = -1) const {
return history_slot_(name, lag, /*zero_start=*/true, ncomp);
}
void store_history(const std::string& name, const field_type& value, int program_owner) const {
require_history_owner_(program_owner);
store_history_(name, value);
}
void store_history(const std::string& name, const field_type& value) const {
store_history_(name, value);
}
void rotate_histories() const { rotate_histories_(std::nullopt); }
void rotate_histories(const std::string& clock_identity) const {
if (clock_identity.empty())
throw std::invalid_argument("AMR Program history rotation requires a clock identity");
rotate_histories_(clock_identity);
}
void interpolate_history_linear(field_type& output, const std::string& name, int max_lag,
int program_owner, const std::string& source_clock,
const std::string& target_clock, int target_step,
Real target_offset) const {
require_history_owner_(program_owner);
if (max_lag < 1 || !std::isfinite(static_cast<double>(target_offset)))
throw std::invalid_argument("AMR linear history interpolation has an invalid target");
const std::string key = history_key_(name, active_level_);
auto& manager = runtime_state().hist_;
const auto found = manager.histories.find(key);
if (found == manager.histories.end() || manager.depth.at(key) <= max_lag ||
!manager.initialized.at(key))
throw std::runtime_error(
"AMR linear history interpolation requires an initialized retained ring");
require_same_field_contract_(output, found->second.front(), "AMR linear history interpolation");
const double source_ticks = static_cast<double>(clock_schedule_.ticks_per_macro(source_clock));
const double target_ticks = static_cast<double>(clock_schedule_.ticks_per_macro(target_clock));
const double coordinate =
(static_cast<double>(target_step) + static_cast<double>(target_offset)) * source_ticks /
target_ticks;
if (!std::isfinite(coordinate) || coordinate > 0.0 ||
coordinate < -static_cast<double>(max_lag))
throw std::runtime_error(
"AMR linear history interpolation target lies outside retained timestamps");
if (coordinate == 0.0) {
copy_valid_(found->second.front(), output);
count_kernel_();
return;
}