Shamrock 2025.10.0
Astrophysical Code
Loading...
Searching...
No Matches
SolverConfig.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
23
26#include "shambase/string.hpp"
27#include "shambackends/vec.hpp"
28#include "shamcomm/logs.hpp"
42#include <nlohmann/json.hpp>
47#include <stdexcept>
48#include <variant>
49
51
55 struct DragConfig {
56 DragSolverMode drag_solver_config = NoDrag;
57 std::vector<f64> alphas;
58 bool enable_frictional_heating
59 = false; // 0 to turn off and 1 when all dissipation is deposited to the gas
60 };
61
62 struct DustConfig {
63 DustRiemannSolverMode dust_riemann_config = NoDust;
64 u32 ndust = 0;
65
66 inline bool is_dust_on() {
67 if (dust_riemann_config != NoDust) {
68
69 if (ndust == 0) {
71 "Dust is on with ndust == 0");
72 }
73 return true;
74 }
75 return false;
76 }
77 };
78
82 u32 npscal_gas = 0;
83
84 inline bool is_gas_passive_scalar_on() { return npscal_gas > 0; }
85 };
86
87 template<class Tvec>
89 using Tscal = shambase::VecComponent<Tvec>;
90 GravityMode gravity_mode = NoGravity;
92 Tscal tol = 1e-6;
94 Tscal tol_hp_bk = 1e-6;
97 inline Tscal get_tolerance() { return tol; }
98 inline bool is_gravity_on() { return gravity_mode != NoGravity; }
99 };
100
101 template<class Tvec, class TgridVec>
102 struct AMRMode {
103
104 using Tscal = shambase::VecComponent<Tvec>;
105
106 struct None {};
107
109 Tscal crit_mass;
110 };
111
113 Tscal error_min;
114 Tscal error_max;
115 };
116
128 u32 N_J = 4;
129 };
130
131 struct ShearBased {
132 Tscal threshold;
133 };
134
135 using mode
136 = std::variant<None, DensityBased, PseudoGradientBased, JeansLengthBased, ShearBased>;
137
138 mode config = None{};
139
140 bool old_amr = true;
141
142 void set_refine_none() { config = None{}; }
143 void set_refine_density_based(Tscal crit_mass) { config = DensityBased{crit_mass}; }
144 void set_refine_pseudo_gradient_based(Tscal error_min, Tscal error_max) {
145 config = PseudoGradientBased{error_min, error_max};
146 }
147
148 void set_refine_jeans_length_based(u32 N_J) { config = JeansLengthBased{N_J}; }
149
150 void set_refine_shear_based(Tscal thresh) { config = ShearBased{thresh}; }
151
152 bool need_level_zero_compute() { return !old_amr; }
153 bool need_amr_level_compute() { return !old_amr; }
154 };
155
162 template<class Tvec>
163 struct EOSConfig {
164 using Tscal = shambase::VecComponent<Tvec>;
165
167 struct Adiabatic {
168 Tscal gamma = 5. / 3.;
169
170 inline shammath::FluidStateAdiabatic<Tvec> get_spec() const {
171 return shammath::FluidStateAdiabatic<Tvec>{.m_gamma = gamma};
172 }
173 };
174
176 struct Barotropic {
177 Tscal rho_crit;
178 Tscal cs0;
179 Tscal gamma = 5. / 3.;
180
181 inline shammath::FluidStateBarotropic<Tvec> get_spec() const {
182 return shammath::FluidStateBarotropic<Tvec>(rho_crit, cs0, gamma);
183 }
184 };
185
186 using Variant = std::variant<Adiabatic, Barotropic>;
187
188 Variant config = Adiabatic{};
189
190 inline void set_adiabatic(Tscal gamma) { config = Adiabatic{gamma}; }
191 inline void set_barotropic(Tscal rho_crit, Tscal cs0, Tscal gamma) {
192 config = Barotropic{rho_crit, cs0, gamma};
193 }
194
196 inline bool is_hydro_adiabatic() const { return std::holds_alternative<Adiabatic>(config); }
197 };
198
199 struct BCConfig {
200 enum class GhostType { Periodic = 0, Reflective = 1, Outflow = 2 };
201
202 GhostType ghost_type_x = GhostType::Periodic;
203 GhostType ghost_type_y = GhostType::Periodic;
204 GhostType ghost_type_z = GhostType::Periodic;
205
206 GhostType get_x() const { return ghost_type_x; }
207 GhostType get_y() const { return ghost_type_y; }
208 GhostType get_z() const { return ghost_type_z; }
209
210 void set_x(GhostType ghost_type) { ghost_type_x = ghost_type; }
211 void set_y(GhostType ghost_type) { ghost_type_y = ghost_type; }
212 void set_z(GhostType ghost_type) { ghost_type_z = ghost_type; }
213 };
214
215 template<class Tvec, class TgridVec>
216 struct SolverConfig;
217
218}; // namespace shammodels::basegodunov
219
220template<class Tvec, class TgridVec>
222
223 using Tscal = shambase::VecComponent<Tvec>;
224
225 Tscal grid_coord_to_pos_fact = 1;
226
227 static constexpr u32 NsideBlockPow = 1;
229
232
234 inline void set_eos_gamma(Tscal gamma) { eos_config.set_adiabatic(gamma); }
235
237 inline Tscal get_eos_gamma() const {
238 using Adiabatic = typename EOSConfig<Tvec>::Adiabatic;
239 if (const Adiabatic *cfg = std::get_if<Adiabatic>(&eos_config.config)) {
240 return cfg->gamma;
241 }
243 "The Ramses solver only supports an adiabatic hydro step (Adiabatic equation of "
244 "state) for now");
245 return {};
246 }
247
250
251 inline bool is_cooling_on() const { return cooling_config.is_cooling_on(); }
252
253 RiemannSolverMode riemann_config = HLL;
254 SlopeMode slope_config = VanLeer_sym;
255 bool face_half_time_interpolation = true;
256 AMRInterpMode amr_interp_mode = FIRST_ORDER;
257
259 inline void set_riemann_solver(RiemannSolverMode mode) { riemann_config = mode; }
260
261 inline bool should_compute_rho_mean() { return is_gravity_on() && is_boundary_periodic(); }
262
264 // Dust config
266
267 DustConfig dust_config{};
268 DragConfig drag_config{};
269
270 inline bool is_dust_on() { return dust_config.is_dust_on(); }
271 // get alpha values from user
272 // alphas is the dust collision rate (the inverse of the stopping time)
273 inline void set_alphas_static(f32 alpha_values) {
274 StackEntry stack_lock{};
275 drag_config.alphas.push_back(alpha_values);
276 }
277
279 // Dust config (END)
281
282 BCConfig bc_config{};
283
285 // Gas passive scalars config
287
288 PassiveScalarGasConfig npscal_gas_config{};
289
290 inline bool is_gas_passive_scalar_on() { return npscal_gas_config.is_gas_passive_scalar_on(); }
292 // Gas passive scalars config (END)
294
296 // Gravity config
300 if (!unit_sys) {
301 ON_RANK_0(logger::warn_ln("amr::Config", "the unit system is not set"));
303 } else {
304 return *unit_sys;
305 }
306 }
307 inline Tscal get_constant_G() { return get_unit_sys().template get<shamunits::constants::G>(); }
308 inline Tscal get_constant_4piG() {
309 return get_unit_sys().template get<4 * shamunits::pi<double> * shamunits::constants::G>();
310 }
311 inline bool is_boundary_periodic() { return true; }
312 GravityConfig<Tvec> gravity_config{};
313 inline Tscal get_grav_tol() { return gravity_config.get_tolerance(); }
314 inline Tscal get_happy_bk_grav_tol() { return gravity_config.tol_hp_bk; }
315 inline bool is_gravity_on() { return gravity_config.is_gravity_on(); }
316 inline bool is_coordinate_field_required() { return ext_force_config.is_coordinates_needed(); }
317
319 // Gravity config (END)
321
323 // External forces config
325
326 using ExtForceConfig = shammodels::basegodunov::ExtForceConfig<Tvec>;
327
329 ExtForceConfig ext_force_config{};
330
331 inline bool has_ext_forces() { return ext_force_config.has_ext_forces(); }
332
334 // External forces config (END)
336
339
341 // Units Config
343
345 std::optional<shamunits::UnitSystem<Tscal>> unit_sys = {};
346
348 inline void set_units(shamunits::UnitSystem<Tscal> new_sys) { unit_sys = new_sys; }
350 // Units Config (END)
352
353 PatchSchedulerConfig scheduler_conf = {};
354
356 // CFL Configuration (config)
358
359 Tscal Csafe = 0.9;
360
362 // CFL Configuration (END)
364
365 inline void check_config() {
366 if (grid_coord_to_pos_fact <= 0) {
368 sham::format("grid_coord_to_pos_fact must be > 0, got {}", grid_coord_to_pos_fact));
369 }
370
371 if (is_dust_on()) {
372 ON_RANK_0(logger::warn_ln("Ramses::SolverConfig", "Dust is experimental"));
373 }
374
375 if (is_gravity_on()) {
376 if (gravity_config.gravity_mode != CG && gravity_config.gravity_mode != BICGSTAB) {
378 "self-gravity: only the cg and bicgstab Poisson solvers are implemented, got "
379 "gravity mode {}",
380 nlohmann::json(gravity_config.gravity_mode).dump()));
381 }
382
383 // self-gravity is applied through the external forces, its acceleration at t^{n+1}
384 // only depending on the density at t^{n+1} (see Solver::init_solver_graph)
387 "self-gravity requires the trapezoidal coupling of the external forces");
388 }
389
390 // Combinations that were not validated with this self-gravity scheme (only gas
391 // self-gravity was). The external forces path would apply the self-gravity
392 // acceleration to the dust as well, and the drag integrator is not coupled to it.
393 if (is_dust_on()) {
395 "self-gravity with dust is not supported yet");
396 }
397 if (drag_config.drag_solver_config != NoDrag) {
399 "self-gravity with drag is not supported yet");
400 }
401
402 ON_RANK_0(logger::warn_ln("Ramses::SolverConfig", "Self gravity is experimental"));
403 u32 mode = gravity_config.gravity_mode;
404
406 sham::format(
407 "self gravity mode is not enabled but gravity mode is set to {} (> 0 whith 0 "
408 "== "
409 "NoGravity mode)",
410 mode));
411 }
412
413 using EOSAdiabatic = typename EOSConfig<Tvec>::Adiabatic;
414 if (const EOSAdiabatic *cfg = std::get_if<EOSAdiabatic>(&eos_config.config)) {
415 if (!(cfg->gamma > 1.0)) {
417 sham::format("Gamma must be > 1, currently Gamma = {}", cfg->gamma));
418 }
419 } else {
421 "The barotropic equation of state is not supported by the Ramses solver yet");
422 }
423
424 cooling_config.check_config();
425
426 if (is_gas_passive_scalar_on()) {
427 ON_RANK_0(logger::warn_ln("Ramses::SolverConfig", "Passive scalars are experimental"));
429 sham::format(
430 "gas passive scalars mode is not enabled but gas passive scalars mode is set "
431 "to {}"
432 "> 0",
433 npscal_gas_config.npscal_gas));
434 }
435
436 if (!amr_mode.old_amr) {
437 shamrock::experimental_feature_check("new AMR is experimental");
438 }
439
440 using AMRNone = typename AMRMode<Tvec, TgridVec>::None;
441 using AMRDensityBased = typename AMRMode<Tvec, TgridVec>::DensityBased;
442 if (amr_mode.old_amr
443 && !(
444 std::holds_alternative<AMRNone>(amr_mode.config)
445 || std::holds_alternative<AMRDensityBased>(amr_mode.config))) {
447 "the old AMR only implements the None and DensityBased refinement criteria, the "
448 "selected one is only implemented in the new AMR (cfg.set_amr_mode_old(False))");
449 }
450
451 using AMRJeansLengthBased = typename AMRMode<Tvec, TgridVec>::JeansLengthBased;
452 if (const AMRJeansLengthBased *cfg = std::get_if<AMRJeansLengthBased>(&amr_mode.config)) {
453 if (cfg->N_J == 0) {
455 }
456 }
457 }
458
459 void set_layout(shamrock::patch::PatchDataLayerLayout &pdl);
460};
461
462namespace shammodels::basegodunov {
463
464 inline void to_json(nlohmann::json &j, const BCConfig::GhostType &e) {
465 switch (e) {
466 case BCConfig::GhostType::Periodic : j = "periodic"; break;
467 case BCConfig::GhostType::Reflective: j = "reflective"; break;
468 case BCConfig::GhostType::Outflow : j = "outflow"; break;
469 default:
471 "Invalid BCConfig::GhostType value: " + std::to_string(static_cast<int>(e)));
472 }
473 }
474
475 inline void from_json(const nlohmann::json &j, BCConfig::GhostType &e) {
476 const std::string type = j.get<std::string>();
477 if (type == "periodic") {
478 e = BCConfig::GhostType::Periodic;
479 } else if (type == "reflective") {
480 e = BCConfig::GhostType::Reflective;
481 } else if (type == "outflow") {
482 e = BCConfig::GhostType::Outflow;
483 } else {
485 "Invalid BCConfig::GhostType value: " + type);
486 }
487 }
488
489 inline void to_json(nlohmann::json &j, const BCConfig &p) {
490 j = nlohmann::json{
491 {"ghost_type_x", p.ghost_type_x},
492 {"ghost_type_y", p.ghost_type_y},
493 {"ghost_type_z", p.ghost_type_z}};
494 }
495
496 inline void from_json(const nlohmann::json &j, BCConfig &p) {
497 j.at("ghost_type_x").get_to(p.ghost_type_x);
498 j.at("ghost_type_y").get_to(p.ghost_type_y);
499 j.at("ghost_type_z").get_to(p.ghost_type_z);
500 }
501
502 inline void to_json(nlohmann::json &j, const DragConfig &p) {
503 j = nlohmann::json{
504 {"drag_solver", p.drag_solver_config},
505 {"alphas", p.alphas},
506 {"enable_frictional_heating", p.enable_frictional_heating}};
507 }
508
509 inline void from_json(const nlohmann::json &j, DragConfig &p) {
510 j.at("drag_solver").get_to(p.drag_solver_config);
511 j.at("alphas").get_to(p.alphas);
512 j.at("enable_frictional_heating").get_to(p.enable_frictional_heating);
513 }
514
515 template<class Tvec, class TgridVec>
516 inline void amr_config_to_json(nlohmann::json &j, const AMRMode<Tvec, TgridVec> &p) {
517 using AMR = AMRMode<Tvec, TgridVec>;
518
519 if (std::holds_alternative<typename AMR::None>(p.config)) {
520 j = {{"type", "none"}};
521 } else if (const auto *cfg = std::get_if<typename AMR::DensityBased>(&p.config)) {
522 j = {{"type", "density_based"}, {"crit_mass", cfg->crit_mass}};
523 } else if (const auto *cfg = std::get_if<typename AMR::PseudoGradientBased>(&p.config)) {
524 j
525 = {{"type", "pseudo_gradient_based"},
526 {"error_min", cfg->error_min},
527 {"error_max", cfg->error_max}};
528 } else if (const auto *cfg = std::get_if<typename AMR::JeansLengthBased>(&p.config)) {
529 j = {{"type", "jeans_length_based"}, {"N_J", cfg->N_J}};
530 } else if (const auto *cfg = std::get_if<typename AMR::ShearBased>(&p.config)) {
531 j = {{"type", "shear_based"}, {"threshold", cfg->threshold}};
532 } else {
534 }
535 }
536
537 template<class Tvec, class TgridVec>
538 inline void amr_config_from_json(const nlohmann::json &j, AMRMode<Tvec, TgridVec> &p) {
539 using Tscal = shambase::VecComponent<Tvec>;
540
541 const std::string type = j.at("type").get<std::string>();
542 if (type == "none") {
543 p.set_refine_none();
544 } else if (type == "density_based") {
545 p.set_refine_density_based(j.at("crit_mass").get<Tscal>());
546 } else if (type == "pseudo_gradient_based") {
547 p.set_refine_pseudo_gradient_based(
548 j.at("error_min").get<Tscal>(), j.at("error_max").get<Tscal>());
549 } else if (type == "jeans_length_based") {
550 p.set_refine_jeans_length_based(j.at("N_J").get<u32>());
551 } else if (type == "shear_based") {
552 p.set_refine_shear_based(j.at("threshold").get<Tscal>());
553 } else {
554 shambase::throw_with_loc<std::runtime_error>("Invalid AMR mode type: " + type);
555 }
556 }
557
558 template<class Tvec>
559 inline void to_json(nlohmann::json &j, const EOSConfig<Tvec> &p) {
560 using EOS = EOSConfig<Tvec>;
561
562 std::visit(
564 [&](const typename EOS::Adiabatic &cfg) {
565 j = {{"type", "adiabatic"}, {"gamma", cfg.gamma}};
566 },
567 [&](const typename EOS::Barotropic &cfg) {
568 j
569 = {{"type", "barotropic"},
570 {"rho_crit", cfg.rho_crit},
571 {"cs0", cfg.cs0},
572 {"gamma", cfg.gamma}};
573 },
574 },
575 p.config);
576 }
577
578 template<class Tvec>
579 inline void from_json(const nlohmann::json &j, EOSConfig<Tvec> &p) {
580 using Tscal = shambase::VecComponent<Tvec>;
581
582 const std::string type = j.at("type").get<std::string>();
583 if (type == "adiabatic") {
584 p.set_adiabatic(j.at("gamma").get<Tscal>());
585 } else if (type == "barotropic") {
586 p.set_barotropic(
587 j.at("rho_crit").get<Tscal>(),
588 j.at("cs0").get<Tscal>(),
589 j.at("gamma").get<Tscal>());
590 } else if (type == "reset_barotropic") {
591 // legacy EOS, now an adiabatic EOS + CoolingConfig::InstantBarotropic, only
592 // converted when deserializing a whole SolverConfig
594 "The reset_barotropic EOS was replaced by an adiabatic EOS with the "
595 "instant_barotropic cooling, it can only be converted when deserializing a "
596 "SolverConfig");
597 } else {
598 shambase::throw_with_loc<std::runtime_error>("Invalid EOS type: " + type);
599 }
600 }
601
602 template<class Tvec, class TgridVec>
603 inline void to_json(nlohmann::json &j, const AMRMode<Tvec, TgridVec> &p) {
604 nlohmann::json config_j;
605 amr_config_to_json(config_j, p);
606 j = nlohmann::json{{"old_amr", p.old_amr}, {"config", config_j}};
607 }
608
609 template<class Tvec, class TgridVec>
610 inline void from_json(const nlohmann::json &j, AMRMode<Tvec, TgridVec> &p) {
611 j.at("old_amr").get_to(p.old_amr);
612 amr_config_from_json(j.at("config"), p);
613 }
614
621 template<class Tvec, class TgridVec>
622 void to_json(nlohmann::json &j, const SolverConfig<Tvec, TgridVec> &p);
629 template<class Tvec, class TgridVec>
630 void from_json(const nlohmann::json &j, SolverConfig<Tvec, TgridVec> &p);
631
632} // namespace shammodels::basegodunov
utility to manipulate AMR blocks
Physical constants in a unit system, plus a few dimensionless numbers.
Cooling config of the Ramses solver + json serialization/deserialization.
MPI scheduler.
A unit system: the values of the seven SI base units in code units.
float f32
Alias for float.
std::uint32_t u32
32 bit unsigned integer
FluidStateSpec implementation for a barotropic equation of state that is isothermal below a threshold...
A unit system, defined by the SI value of its base units.
The table of physical constants: each constant is a Unit (its SI value and dimension).
AMR (refinement) prolongation mode enum + json serialization/deserialization.
Drag solver mode enum + json serialization/deserialization.
Dust Riemann solver mode enum + json serialization/deserialization.
Gravity mode enum + json serialization/deserialization.
Riemann solver mode enum + json serialization/deserialization.
Slope mode enum + json serialization/deserialization.
This header file contains utility functions related to exception handling in the code.
void throw_with_loc(std::string message, SourceLocation loc=SourceLocation{})
Throw an exception and append the source location to it.
overloaded(Ts...) -> overloaded< Ts... >
Deduction guide so overloaded{lambda1, lambda2, ...} deduces Ts... from the lambdas.
ExcptTypes make_except_with_loc(std::string message, SourceLocation loc=SourceLocation{})
Create an exception with a message and a location.
void throw_unimplemented(SourceLocation loc=SourceLocation{})
Throw a std::runtime_error saying that the function is unimplemented.
namespace for the basegodunov model
RiemannSolverMode
Gas Riemann solver used by the Ramses (Godunov) model.
DustRiemannSolverMode
Dust Riemann solver mode enum.
@ NoDust
No dust, so no Riemann solver is used.
SlopeMode
Slope limiter modes.
void experimental_feature_check(const std::string &message, SourceLocation loc=SourceLocation{})
Check if experimental features are enabled, if not throw with the given message.
External forces config of the Ramses solver + json serialization/deserialization.
Gas and dust conservative/primitive states and axis-transform helpers shared by every gas and dust Ri...
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.
FluidStateSpec implementation for an ideal (adiabatic) gas equation of state.
shamphys::EOS_Config_Adiabatic< Tscal > Adiabatic
Adiabatic equation of state configuration.
Definition EOSConfig.hpp:52
utility class to handle AMR blocks
Definition AMRBlock.hpp:35
Refine the blocks where the Jeans length is resolved by less than N_J cells.
Cooling of the gas, applied on top of the (adiabatic) equation of state.
alphas is the dust collision rate (the inverse of the stopping time)
Ideal gas equation of state, see shammath::FluidStateAdiabatic.
Isothermal below rho_crit and adiabatic above, see shammath::FluidStateBarotropic.
Equation of state of the gas, each alternative maps to a shammath FluidStateSpec.
bool is_hydro_adiabatic() const
True if the hydro step is the adiabatic one.
Tscal tol
Convergence tolerance of the Poisson solver.
u32 Niter_max
Maximum number of iterations of the Poisson solver.
Tscal tol_hp_bk
Tolerance of the BiCGSTAB lucky breakdown test (restarts the solver below it).
Npscal_gas is the number of gas passive scalars.
void set_eos_gamma(Tscal gamma)
Set an adiabatic equation of state (kept for backward compatibility).
ExtForceConfig ext_force_config
External forces applied to the gas.
AMRMode< Tvec, TgridVec > amr_mode
AMR refinement mode.
shamunits::UnitSystem< Tscal > get_unit_sys()
The unit system of the config, or the default one (SI) if it is not set.
Tscal get_eos_gamma() const
Adiabatic index of the hydro step, throws if the hydro step is not adiabatic.
std::optional< shamunits::UnitSystem< Tscal > > unit_sys
The unit system of the simulation.
EOSConfig< Tvec > eos_config
Equation of state of the gas.
CoolingConfig< Tvec > cooling_config
Cooling of the gas.
void set_riemann_solver(RiemannSolverMode mode)
Set the gas Riemann solver.
void set_units(shamunits::UnitSystem< Tscal > new_sys)
Set the unit system of the simulation.
#define ON_RANK_0(x)
Macro to execute code only on rank 0.
Definition worldInfo.hpp:73