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
28
30#include "shambackends/math.hpp"
33#include "shambackends/vec.hpp"
42#include "shammodels/sph/config/BCConfig.hpp" // Reuse boundary conditions from SPH
51#include <nlohmann/json.hpp>
54#include <variant>
55#include <vector>
56
57namespace shammodels::gsph {
58
65 template<class Tvec, template<class> class SPHKernel>
66 struct SolverConfig;
67
73 template<class Tscal>
74 struct CFLConfig {
75 Tscal cfl_cour = 0.3;
76 Tscal cfl_force = 0.25;
77 };
78
80 struct DensityBased {};
82 u32 max_neigh_count = 500;
83 };
84
85 using mode = std::variant<DensityBased, DensityBasedNeighLim>;
86
87 mode config = DensityBased{};
88
89 void set_density_based() { config = DensityBased{}; }
90 void set_density_based_neigh_lim(u32 max_neigh_count) {
91 config = DensityBasedNeighLim{max_neigh_count};
92 }
93
94 bool is_density_based_neigh_lim() const {
95 return std::holds_alternative<DensityBasedNeighLim>(config);
96 }
97 };
98
99} // namespace shammodels::gsph
100
101template<class Tvec, template<class> class SPHKernel>
103
104 using Tscal = shambase::VecComponent<Tvec>;
105 static constexpr u32 dim = shambase::VectorProperties<Tvec>::dimension;
106 using Kernel = SPHKernel<Tscal>;
107 using u_morton = u32;
108
110
111 static constexpr Tscal Rkern = Kernel::Rkern;
112
113 Tscal gpart_mass{0};
114
116
117 PatchSchedulerConfig scheduler_conf = {};
118
120 // Units Config
122
123 std::optional<shamunits::UnitSystem<Tscal>> unit_sys = {};
124
125 inline void set_units(shamunits::UnitSystem<Tscal> new_sys) { unit_sys = new_sys; }
126
127 inline Tscal get_constant_G() const {
128 if (!unit_sys) {
129 ON_RANK_0(logger::warn_ln("gsph::Config", "the unit system is not set"));
130 return shamunits::UnitSystem<Tscal>{}.template get<shamunits::constants::G>();
131 } else {
132 return unit_sys->template get<shamunits::constants::G>();
133 }
134 }
135
137 // Units Config (END)
139
141 // Riemann Solver Config
143
144 using RiemannConfig = RiemannConfig<Tvec>;
145 RiemannConfig riemann_config;
146
147 inline void set_riemann_iterative(Tscal tol = Tscal{1e-6}, u32 max_iter = 20) {
148 riemann_config.set_iterative(tol, max_iter);
149 }
150
151 inline void set_riemann_hllc() { riemann_config.set_hllc(); }
152
153 inline void set_riemann_exact(Tscal tol = Tscal{1e-8}, u32 max_iter = 100) {
154 riemann_config.set_exact(tol, max_iter);
155 }
156
158 // Riemann Solver Config (END)
160
162 // Reconstruction Config
164
165 using ReconstructConfig = ReconstructConfig<Tvec>;
166 ReconstructConfig reconstruct_config;
167
168 inline void set_reconstruct_piecewise_constant() {
169 reconstruct_config.set_piecewise_constant();
170 }
171
172 inline void set_reconstruct_muscl(
174 reconstruct_config.set_muscl(limiter);
175 }
176
177 inline bool requires_gradients() const { return reconstruct_config.requires_gradients(); }
178
180 // Reconstruction Config (END)
182
184 // Force Formulation Config
186
187 using ForceFormulationConfig = ForceFormulationConfig<Tvec>;
188 ForceFormulationConfig force_formulation_config;
189
190 inline void set_force_cha_whitworth() { force_formulation_config.set_cha_whitworth(); }
191
192 inline void set_force_inutsuka_v2() { force_formulation_config.set_inutsuka_v2(); }
193
194 inline bool is_force_inutsuka_v2() const { return force_formulation_config.is_inutsuka_v2(); }
195
197 // Force Formulation Config (END)
199
201 // EOS Config
203
204 using EOSConfig = shammodels::EOSConfig<Tvec>;
205 EOSConfig eos_config;
206
207 inline bool is_eos_adiabatic() const {
208 using T = typename EOSConfig::Adiabatic;
209 return bool(std::get_if<T>(&eos_config.config));
210 }
211
212 inline bool is_eos_isothermal() const {
213 using T = typename EOSConfig::Isothermal;
214 return bool(std::get_if<T>(&eos_config.config));
215 }
216
222 inline Tscal get_eos_gamma() const {
223 using Adiabatic = typename EOSConfig::Adiabatic;
224 using Polytropic = typename EOSConfig::Polytropic;
225 if (const auto *eos = std::get_if<Adiabatic>(&eos_config.config)) {
226 return eos->gamma;
227 } else if (const auto *eos = std::get_if<Polytropic>(&eos_config.config)) {
228 return eos->gamma;
229 }
230 return Tscal{1.4}; // Default for non-gamma EOS types
231 }
232
233 inline void set_eos_adiabatic(Tscal gamma) { eos_config.set_adiabatic(gamma); }
234
235 inline void set_eos_isothermal(Tscal cs) { eos_config.set_isothermal(cs); }
236
238 // EOS Config (END)
240
242 // Boundary Config
244
245 using BCConfig = shammodels::sph::BCConfig<Tvec>; // Reuse from SPH
246 BCConfig boundary_config;
247
248 inline void set_boundary_free() { boundary_config.set_free(); }
249 inline void set_boundary_periodic() { boundary_config.set_periodic(); }
250
261 inline void set_boundary_shearing_periodic(i32_3 shear_base, i32_3 shear_dir, Tscal speed) {
262 boundary_config.set_shearing_periodic(shear_base, shear_dir, speed);
263 }
264
266 // Boundary Config (END)
268
270 // External Force Config
272
274 ExtForceConfig ext_force_config{};
275
276 inline void add_ext_force_point_mass(
277 Tscal central_mass, Tscal Racc, Tvec central_pos = Tvec{}) {
278 ext_force_config.add_point_mass(central_mass, Racc, central_pos);
279 }
280
282 // External Force Config (END)
284
286 // Tree config
288
289 u32 tree_reduction_level = 3;
290
295
296 inline void set_tree_reduction_level(u32 level) { tree_reduction_level = level; }
297
300 neigh_cache_strategy = strategy;
301 }
302
307 inline void set_two_stage_search(bool enable) {
308 ON_RANK_0(shamlog_warn_ln(
309 "GSPH::SolverConfig",
310 "set_two_stage_search() is deprecated,\n"
311 " -> use set_neigh_cache_strategy(NeighCacheStrategy.TwoStage) or\n"
312 " set_neigh_cache_strategy(NeighCacheStrategy.SingleStage) instead"););
314 }
315
317 // Tree config (END)
319
321 // Solver behavior config
323
330 Tscal epsilon_h = 1e-6;
333
334 SmoothingLengthConfig smoothing_length_config;
335
336 inline void set_smoothing_length_density_based() {
337 smoothing_length_config.set_density_based();
338 }
339 inline void set_smoothing_length_density_based_neigh_lim(u32 max_neigh_count) {
340 smoothing_length_config.set_density_based_neigh_lim(max_neigh_count);
341 }
342
343 bool enable_particle_reordering = false;
344 inline void set_enable_particle_reordering(bool enable) { enable_particle_reordering = enable; }
345 u64 particle_reordering_step_freq = 1000;
346 inline void set_particle_reordering_step_freq(u64 freq) {
347 if (freq == 0) {
349 "particle_reordering_step_freq cannot be zero");
350 }
351 particle_reordering_step_freq = freq;
352 }
353
354 bool save_dt_to_fields = false;
355 inline void set_save_dt_to_fields(bool enable) { save_dt_to_fields = enable; }
356 inline bool should_save_dt_to_fields() const { return save_dt_to_fields; }
357
358 bool show_ghost_zone_graph = false;
359 inline void set_show_ghost_zone_graph(bool enable) { show_ghost_zone_graph = enable; }
360
362 // Solver behavior config (END)
364
365 inline bool has_field_uint() const { return is_eos_adiabatic(); }
366
367 inline void print_status() {
368 if (shamcomm::world_rank() != 0) {
369 return;
370 }
371 logger::raw_ln("----- GSPH Solver configuration -----");
372 logger::raw_ln("gpart_mass =", gpart_mass);
373 riemann_config.print_status();
374 reconstruct_config.print_status();
375 force_formulation_config.print_status();
376 eos_config.print_status();
377 logger::raw_ln("--------------------------------------");
378 }
379
380 inline void check_config() const {
381 // Validate configuration (gpart_mass checked later at runtime)
382 // Only check gamma for adiabatic EOS types
383 if (is_eos_adiabatic() && get_eos_gamma() <= 1) {
384 shambase::throw_with_loc<std::runtime_error>("gamma must be > 1 for adiabatic gas");
385 }
386
387 // InutsukaV2 is only wired into update_derivs_iterative()/update_derivs_exact();
388 // update_derivs_hllc() would silently fall back to ChaWhitworth otherwise.
389 if (force_formulation_config.is_inutsuka_v2() && riemann_config.is_hllc()) {
391 "InutsukaV2 force formulation is not yet supported with the HLLC Riemann "
392 "solver. Use set_riemann_iterative() or set_riemann_exact() instead.");
393 }
394 }
395
396 inline void check_config_runtime() const {
397 // Validate configuration for runtime (called before simulation starts)
398 if (gpart_mass <= 0) {
400 "gpart_mass must be positive. Call set_particle_mass() before evolving.");
401 }
402 check_config();
403 }
404
405 void set_layout(shamrock::patch::PatchDataLayerLayout &pdl);
406 void set_ghost_layout(shamrock::patch::PatchDataLayerLayout &ghost_layout);
407};
408
409namespace shammodels::gsph {
410
411 template<class Tscal>
412 inline void to_json(nlohmann::json &j, const CFLConfig<Tscal> &p) {
413 j = nlohmann::json{
414 {"cfl_cour", p.cfl_cour},
415 {"cfl_force", p.cfl_force},
416 };
417 }
418
419 template<class Tscal>
420 inline void from_json(const nlohmann::json &j, CFLConfig<Tscal> &p) {
421 j.at("cfl_cour").get_to(p.cfl_cour);
422 j.at("cfl_force").get_to(p.cfl_force);
423 }
424
425 // JSON serialization for SmoothingLengthConfig
426 inline void to_json(nlohmann::json &j, const SmoothingLengthConfig &p) {
428 = std::get_if<SmoothingLengthConfig::DensityBased>(&p.config)) {
429 j = {
430 {"type", "density_based"},
431 };
432
433 } else if (
435 = std::get_if<SmoothingLengthConfig::DensityBasedNeighLim>(&p.config)) {
436
437 j = {
438 {"type", "density_based_neigh_lim"},
439 {"max_neigh_count", conf->max_neigh_count},
440 };
441 } else {
443 }
444 }
445
446 inline void from_json(const nlohmann::json &j, SmoothingLengthConfig &p) {
447 if (j.at("type").get<std::string>() == "density_based") {
449 } else if (j.at("type").get<std::string>() == "density_based_neigh_lim") {
450 p.config
451 = SmoothingLengthConfig::DensityBasedNeighLim{j.at("max_neigh_count").get<u32>()};
452 } else {
454 }
455 }
456
457 template<class Tvec, template<class> class SPHKernel>
458 inline void to_json(nlohmann::json &j, const SolverConfig<Tvec, SPHKernel> &p) {
460 using Tkernel = typename T::Kernel;
461
462 std::string kernel_id = shambase::get_type_name<Tkernel>();
463 std::string type_id = shambase::get_type_name<Tvec>();
464
465 j = nlohmann::json{
466 {"solver_type", "gsph"},
467 {"kernel_id", kernel_id},
468 {"type_id", type_id},
469 {"scheduler_config", p.scheduler_conf},
470 {"gpart_mass", p.gpart_mass},
471 {"cfl_config", p.cfl_config},
472 {"unit_sys", p.unit_sys},
473 {"riemann_config", p.riemann_config},
474 {"reconstruct_config", p.reconstruct_config},
475 {"force_formulation_config", p.force_formulation_config},
476 {"eos_config", p.eos_config},
477 {"boundary_config", p.boundary_config},
478 {"tree_reduction_level", p.tree_reduction_level},
479 {shammodels::neigh_cache_strategy_json_key, p.neigh_cache_strategy},
480 {"htol_up_coarse_cycle", p.htol_up_coarse_cycle},
481 {"htol_up_fine_cycle", p.htol_up_fine_cycle},
482 {"epsilon_h", p.epsilon_h},
483 {"h_iter_per_subcycles", p.h_iter_per_subcycles},
484 {"h_max_subcycles_count", p.h_max_subcycles_count},
485 {"combined_dtdiv_divcurlv_compute", p.combined_dtdiv_divcurlv_compute},
486 {"enable_particle_reordering", p.enable_particle_reordering},
487 {"particle_reordering_step_freq", p.particle_reordering_step_freq},
488 {"set_save_dt_to_fields", p.save_dt_to_fields},
489 {"show_ghost_zone_graph", p.show_ghost_zone_graph},
490 };
491 }
492
493 template<class Tvec, template<class> class SPHKernel>
494 inline void from_json(const nlohmann::json &j, SolverConfig<Tvec, SPHKernel> &p) {
496 using Tkernel = typename T::Kernel;
497
498 std::string kernel_id = j.at("kernel_id").get<std::string>();
499 if (kernel_id != shambase::get_type_name<Tkernel>()) {
501 "Invalid kernel type: expected " + shambase::get_type_name<Tkernel>() + " but got "
502 + kernel_id);
503 }
504
505 std::string type_id = j.at("type_id").get<std::string>();
506 if (type_id != shambase::get_type_name<Tvec>()) {
508 "Invalid vector type: expected " + shambase::get_type_name<Tvec>() + " but got "
509 + type_id);
510 }
511
512 bool has_used_defaults = false;
513 bool has_updated_config = false;
514
515 auto _get_to_if_contains = [&](const std::string &key, auto &value) {
516 shamrock::get_to_if_contains(j, key, value, has_used_defaults);
517 };
518
519 _get_to_if_contains("scheduler_config", p.scheduler_conf);
520 _get_to_if_contains("gpart_mass", p.gpart_mass);
521 _get_to_if_contains("cfl_config", p.cfl_config);
522 _get_to_if_contains("unit_sys", p.unit_sys);
523 _get_to_if_contains("riemann_config", p.riemann_config);
524 _get_to_if_contains("reconstruct_config", p.reconstruct_config);
525 _get_to_if_contains("force_formulation_config", p.force_formulation_config);
526 _get_to_if_contains("eos_config", p.eos_config);
527 _get_to_if_contains("boundary_config", p.boundary_config);
528 _get_to_if_contains("tree_reduction_level", p.tree_reduction_level);
529 // Reads the new enum key, falling back on the legacy `use_two_stage_search` boolean
531 j, p.neigh_cache_strategy, "GSPH::SolverConfig", has_used_defaults, has_updated_config);
532 _get_to_if_contains("htol_up_coarse_cycle", p.htol_up_coarse_cycle);
533 _get_to_if_contains("htol_up_fine_cycle", p.htol_up_fine_cycle);
534 _get_to_if_contains("epsilon_h", p.epsilon_h);
535 _get_to_if_contains("h_iter_per_subcycles", p.h_iter_per_subcycles);
536 _get_to_if_contains("h_max_subcycles_count", p.h_max_subcycles_count);
537
538 if (has_used_defaults || has_updated_config) {
539 if (shamcomm::world_rank() == 0) {
540 logger::info_ln(
541 "GSPH::SolverConfig",
542 shamrock::log_json_changes(p, j, has_used_defaults, has_updated_config));
543 }
544 }
545 }
546
547} // namespace shammodels::gsph
Configuration for the GSPH momentum equation formulation.
Header file describing a Node Instance.
MPI scheduler.
Configuration for reconstruction methods in GSPH.
Configuration for Riemann solvers in GSPH.
A unit system: the values of the seven SI base units in code units.
std::uint32_t u32
32 bit unsigned integer
std::uint64_t u64
64 bit unsigned integer
A Compressed Leaf Bounding Volume Hierarchy (CLBVH) for neighborhood queries.
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).
Neighbour cache build strategy 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.
void throw_unimplemented(SourceLocation loc=SourceLocation{})
Throw a std::runtime_error saying that the function is unimplemented.
i32 world_rank()
Gives the rank of the current process in the MPI communicator.
Definition worldInfo.cpp:41
constexpr const char * neigh_cache_strategy_json_key
Json key holding the neighbour cache strategy.
void get_to_neigh_cache_strategy(const nlohmann::json &j, NeighCacheStrategy &value, const std::string &log_ctx, bool &has_used_defaults, bool &has_updated_config)
Deserialize the neighbour cache strategy, falling back on the legacy boolean key.
NeighCacheStrategy neigh_cache_strategy_from_two_stage_search(bool use_two_stage_search)
Map the legacy use_two_stage_search boolean onto the strategy enum.
NeighCacheStrategy
Strategy used to build the neighbour cache out of the tree traversal.
@ TwoStage
Two stage neighbours search (see shamrock paper).
void get_to_if_contains(const nlohmann::json &j, const std::string &key, T &value, bool &has_used_defaults)
std::string log_json_changes(const nlohmann::json &j_current, const nlohmann::json &j, bool has_used_defaults, bool has_updated_config)
Shown the changes between two JSON objects to log config changes.
Contains traits and utilities for backend related types.
void warn_ln(std::string module_name, Types... var2)
Prints a log message with multiple arguments followed by a newline.
Definition logs.hpp:132
sph kernels
shamphys::EOS_Config_Polytropic< Tscal > Polytropic
Polytropic equation of state configuration.
Definition EOSConfig.hpp:55
shamphys::EOS_Config_Isothermal< Tscal > Isothermal
Isothermal equation of state configuration.
Definition EOSConfig.hpp:58
shamphys::EOS_Config_Adiabatic< Tscal > Adiabatic
Adiabatic equation of state configuration.
Definition EOSConfig.hpp:52
The configuration for the CFL condition in GSPH.
Tscal cfl_force
CFL condition for the force.
Tscal cfl_cour
CFL condition for the courant factor.
Limiter
Slope limiter types for MUSCL reconstruction.
The configuration for a GSPH solver.
u32 h_iter_per_subcycles
Maximum number of iterations per subcycle.
void set_neigh_cache_strategy(NeighCacheStrategy strategy)
Setter for the neighbours cache strategy.
void set_boundary_shearing_periodic(i32_3 shear_base, i32_3 shear_dir, Tscal speed)
Set shearing periodic boundary conditions.
NeighCacheStrategy neigh_cache_strategy
Tscal get_eos_gamma() const
Get the adiabatic index (gamma) from the EOS config.
Tscal gpart_mass
The mass of each gas particle (must be set before use).
u32 h_max_subcycles_count
Maximum number of subcycles before solver crash.
Tscal htol_up_fine_cycle
Maximum factor of the smoothing length evolution per subcycles.
void set_two_stage_search(bool enable)
Setter for the two stage search.
CFLConfig< Tscal > cfl_config
CFL configuration.
Tscal epsilon_h
Convergence criteria for the smoothing length.
Boundary conditions configuration.
Definition BCConfig.hpp:40
void set_free()
Set the boundary condition to free boundaries.
Definition BCConfig.hpp:98
Functions related to the MPI communicator.
#define ON_RANK_0(x)
Macro to execute code only on rank 0.
Definition worldInfo.hpp:73