Shamrock 2025.10.0
Astrophysical Code
Loading...
Searching...
No Matches
Model.hpp
Go to the documentation of this file.
1// -------------------------------------------------------//
2//
3// SHAMROCK code for hydrodynamics
4// Copyright (c) 2021-2026 Timothée David--Cléris <tim.shamrock@proton.me>
5// SPDX-License-Identifier: CeCILL Free Software License Agreement v2.1
6// Shamrock is licensed under the CeCILL 2.1 License, see LICENSE for more information
7//
8// -------------------------------------------------------//
9
10#pragma once
11
20
22#include "shambase/memory.hpp"
23#include "shambackends/vec.hpp"
31
33
34 template<class Tvec, class TgridVec>
35 class Model {
36 public:
37 using Tscal = shambase::VecComponent<Tvec>;
38 static constexpr u32 dim = shambase::VectorProperties<Tvec>::dimension;
39 ShamrockCtx &ctx;
40
41 using Solver = Solver<Tvec, TgridVec>;
42 Solver solver;
43
44 Model(ShamrockCtx &ctx) : ctx(ctx), solver(ctx) {};
45
49
51 void init();
52
55 inline void init_scheduler(u32 crit_split, u32 crit_merge) {
56 solver.solver_config.scheduler_conf.split_load_value = crit_split;
57 solver.solver_config.scheduler_conf.merge_load_value = crit_merge;
58 init();
59 }
60
61 inline f64 solver_logs_last_rate() { return solver.solve_logs.get_last_rate(); }
62 inline u64 solver_logs_last_obj_count() { return solver.solve_logs.get_last_obj_count(); }
63 inline shamsys::SystemMetrics solver_logs_last_system_metrics() {
64 return solver.solve_logs.get_last_system_metrics();
65 }
66
67 void make_base_grid(TgridVec bmin, TgridVec cell_size, u32_3 cell_count);
68
69 void dump_vtk(std::string filename);
70
71 template<class T>
72 inline void set_field_value_lambda(
73 std::string field_name,
74 const std::function<T(Tvec, Tvec)> pos_to_val,
75 const i32 offset) {
76
77 StackEntry stack_loc{};
78
79 using Block = typename Solver::Config::AMRBlock;
80
81 PatchScheduler &sched = shambase::get_check_ref(ctx.sched);
82 sched.patch_data.for_each_patchdata([&](u64 patch_id,
83 shamrock::patch::PatchDataLayer &pdat) {
84 sham::DeviceBuffer<TgridVec> &buf_cell_min = pdat.get_field_buf_ref<TgridVec>(0);
85 sham::DeviceBuffer<TgridVec> &buf_cell_max = pdat.get_field_buf_ref<TgridVec>(1);
86
87 PatchDataField<T> &f
88 = pdat.template get_field<T>(sched.pdl_old().get_field_idx<T>(field_name));
89
90 auto acc = f.get_buf().copy_to_stdvec();
91
92 auto f_nvar = f.get_nvar() / Block::block_size;
93
94 auto cell_min = buf_cell_min.copy_to_stdvec();
95 auto cell_max = buf_cell_max.copy_to_stdvec();
96
97 Tscal scale_factor = solver.solver_config.grid_coord_to_pos_fact;
98 for (u32 i = 0; i < pdat.get_obj_cnt(); i++) {
99 Tvec block_min = cell_min[i].template convert<Tscal>() * scale_factor;
100 Tvec block_max = cell_max[i].template convert<Tscal>() * scale_factor;
101 Tvec delta_cell = (block_max - block_min) / Block::side_size;
102
103 Block::for_each_cell_in_block(delta_cell, [&](u32 lid, Tvec delta) {
104 Tvec bmin = block_min + delta;
105 acc[(i * Block::block_size + lid) * f_nvar + offset]
106 = pos_to_val(bmin, bmin + delta_cell);
107 });
108 }
109
110 f.get_buf().copy_from_stdvec(acc);
111 });
112 }
113
114 inline std::pair<Tvec, Tvec> get_cell_coords(
115 std::pair<TgridVec, TgridVec> block_coords, u32 lid) {
116 using Block = typename Solver::Config::AMRBlock;
117 auto tmp = Block::utils_get_cell_coords(block_coords, lid);
118 tmp.first *= solver.solver_config.grid_coord_to_pos_fact;
119 tmp.second *= solver.solver_config.grid_coord_to_pos_fact;
120 return tmp;
121 }
122
123 inline f64 evolve_once_time_expl(f64 t_curr, f64 dt_input) {
124 return solver.evolve_once_time_expl(t_curr, dt_input);
125 }
126
127 inline void timestep() { solver.evolve_once(); }
128
129 inline void evolve_once() {
130 solver.evolve_once();
131 solver.print_timestep_logs();
132 }
133
134 inline bool evolve_until(Tscal target_time, i32 niter_max) {
135 return solver.evolve_until(target_time, niter_max);
136 }
137
141
142 inline void dump(std::string fname) {
143 if (shamcomm::world_rank() == 0) {
144 logger::info_ln("Godunov", "Dumping state to", fname);
145 }
146
147 nlohmann::json metadata;
148 metadata["solver_config"] = solver.solver_config;
149
151 fname, metadata.dump(4), shambase::get_check_ref(ctx.sched));
152 }
153
159 inline void load_from_dump(std::string fname) {
160 if (shamcomm::world_rank() == 0) {
161 logger::info_ln("Godunov", "Loading state from dump", fname);
162 }
163
164 // Load the context state and recover user metadata
165 std::string metadata_user{};
166 shamrock::load_shamrock_dump(fname, metadata_user, ctx);
167
168 nlohmann::json j = nlohmann::json::parse(metadata_user);
169 j.at("solver_config").get_to(solver.solver_config);
170
171 // modules::GhostZones gz(ctx, solver.solver_config, storage);
172 // gz.build_ghost_cache();
173
174 PatchScheduler &sched = shambase::get_check_ref(ctx.sched);
175
176 // Migrate old dumps that stored time/dt in solver_config.time_state (before PR #1932)
177 auto sync_names = sched.synchronized_data.get_edge_names();
178
179 // Checking for time is equivalent to dumps written after this migration
180 bool had_time_edge
181 = std::find(sync_names.begin(), sync_names.end(), "time") != sync_names.end();
182
183 // create time/dt synchronization edges if not present
184 solver.ensure_time_state_edges();
185
186 if (!had_time_edge) {
187 if (j.at("solver_config").contains("time_state")) {
188 ON_RANK_0(
190 "Godunov",
191 "Migrated time/dt from solver_config.time_state into scheduler "
192 "edges"));
193 const auto &ts = j.at("solver_config").at("time_state");
194 solver.set_time(ts.at("time").get<Tscal>());
195 solver.set_next_dt(ts.at("dt").get<Tscal>());
196 } else {
198 "this should never happen: dump has neither time edges nor "
199 "solver_config.time_state");
200 }
201 }
202
203 shamlog_debug_ln("Sys", "build local scheduler tables");
204 sched.owned_patch_id = sched.patch_list.build_local();
207 sched.update_local_load_value([&](shamrock::patch::Patch p) {
208 return sched.patch_data.owned_data.get(p.id_patch).get_obj_cnt();
209 });
210 }
211 };
212
213} // namespace shammodels::basegodunov
double f64
Alias for double.
std::uint32_t u32
32 bit unsigned integer
std::uint64_t u64
64 bit unsigned integer
std::int32_t i32
32 bit integer
The MPI scheduler.
SchedulerPatchData patch_data
handle the data of the patches of the scheduler
SynchronizedData synchronized_data
data that is synchroneous across all ranks
SchedulerPatchList patch_list
handle the list of the patches of the scheduler
std::unordered_set< u64 > owned_patch_id
(owned_patch_id = patch_list.build_local())
std::unordered_set< u64 > build_local()
select owned patches owned by the node to rebuild local
void build_local_idx_map()
recompute id_patch_to_local_idx
void build_global_idx_map()
recompute id_patch_to_global_idx
std::vector< T > copy_to_stdvec() const
Copy the content of the buffer to a std::vector.
void init_scheduler(u32 crit_split, u32 crit_merge)
Definition Model.hpp:55
void init()
Initialise the model and all the related data structures (patch scheduler in particular).
Definition Model.cpp:27
void load_from_dump(std::string fname)
Load the state of the Godunov model from a dump file.
Definition Model.hpp:159
u32 get_field_idx(const std::string &field_name) const
Get the field id if matching name & type.
u32 get_obj_cnt() const
get the number of objects (particles) stored in this layer
shambase::DistributedData< PatchData > owned_data
map container for patchdata owned by the current node (layout : id_patch,data)
std::vector< std::string > get_edge_names() const
Returns edge registration keys in lexicographic order (deterministic).
T & get_check_ref(const std::unique_ptr< T > &ptr, SourceLocation loc=SourceLocation())
Takes a std::unique_ptr and returns a reference to the object it holds. It throws a std::runtime_erro...
Definition memory.hpp:112
ExcptTypes make_except_with_loc(std::string message, SourceLocation loc=SourceLocation{})
Create an exception with a message and a location.
i32 world_rank()
Gives the rank of the current process in the MPI communicator.
Definition worldInfo.cpp:41
namespace for the basegodunov model
void load_shamrock_dump(std::string fname, std::string &metadata_user, ShamrockCtx &ctx)
Load a Shamrock dump file and restore the state of the patches and retreive user metadata.
void write_shamrock_dump(std::string fname, std::string metadata_user, PatchScheduler &sched)
Write a Shamrock dump file containing the current state of the patches and user supplied metadata.
void info_ln(std::string module_name, Types... var2)
Prints a log message with multiple arguments followed by a newline.
Definition logs.hpp:132
void warn_ln(std::string module_name, Types... var2)
Prints a log message with multiple arguments followed by a newline.
Definition logs.hpp:132
shambase::details::BasicStackEntry StackEntry
Alias for shambase::details::BasicStackEntry.
Patch object that contain generic patch information.
Definition Patch.hpp:33
#define ON_RANK_0(x)
Macro to execute code only on rank 0.
Definition worldInfo.hpp:73