Shamrock 2025.10.0
Astrophysical Code
Loading...
Searching...
No Matches
pyRamsesModel.cpp
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
20
22#include "shambase/string.hpp"
25#include "shamcomm/logs.hpp"
32#include <pybind11/functional.h>
33#include <pybind11/numpy.h>
34#include <memory>
35
37
38 namespace {
40 void warn_deprecated_riemann_setter(const char *old_name, const char *mode) {
42 shamcomm::logs::warn_ln(
43 "Ramses",
44 sham::format(
45 ".{}() is deprecated and will be removed at some point, replace it by:\n"
46 " from shamrock.model_ramses import {}\n"
47 " cfg.set_riemann_solver({})",
48 old_name,
49 mode,
50 mode)));
51 }
52 } // namespace
53
54 template<class Tvec, class TgridVec>
55 void add_instance(py::module &m, std::string name_config, std::string name_model) {
56
57 using Tscal = shambase::VecComponent<Tvec>;
58 using Tgridscal = shambase::VecComponent<TgridVec>;
59
60 using T = Model<Tvec, TgridVec>;
61 using TConfig = typename T::Solver::Config;
62 using TAnalysisSodTube = shammodels::basegodunov::modules::AnalysisSodTube<Tvec, TgridVec>;
63 using TCooling = CoolingConfig<Tvec>;
64
65 shamlog_debug_ln("[Py]", "registering class :", name_config, typeid(T).name());
66 shamlog_debug_ln("[Py]", "registering class :", name_model, typeid(T).name());
67
68 py::class_<TConfig> config_cls(m, name_config.c_str());
69
70 shammodels::common::add_json_defs<TConfig>(config_cls);
71
72 config_cls
73 .def(
74 "set_scale_factor",
75 [](TConfig &self, Tscal scale_factor) {
76 self.grid_coord_to_pos_fact = scale_factor;
77 })
78 .def(
79 "set_Csafe",
80 [](TConfig &self, Tscal Csafe) {
81 self.Csafe = Csafe;
82 })
83 .def(
84 "set_eos_gamma",
85 [](TConfig &self, Tscal eos_gamma) {
86 self.set_eos_gamma(eos_gamma);
87 })
88 .def(
89 "set_eos_adiabatic",
90 [](TConfig &self, Tscal gamma) {
91 self.eos_config.set_adiabatic(gamma);
92 })
93 .def(
94 "set_eos_barotropic",
95 [](TConfig &self, Tscal rho_crit, Tscal cs0, Tscal gamma) {
96 self.eos_config.set_barotropic(rho_crit, cs0, gamma);
97 },
98 py::kw_only(),
99 py::arg("rho_crit"),
100 py::arg("cs0"),
101 py::arg("gamma"))
102 .def(
103 "set_eos_reset_barotropic",
104 [](TConfig & /*self*/, py::args /*args*/, py::kwargs /*kwargs*/) {
105 const std::string msg
106 = ".set_eos_reset_barotropic(rho_crit, cs0, gamma_baro, gamma) has been "
107 "removed, as the reset onto the barotrope is an instantaneous cooling "
108 "and not an equation of state. Replace it by:\n"
109 " from shamrock.model_ramses import InstantBarotropic\n"
110 " cfg.set_eos_adiabatic(gamma)\n"
111 " cfg.set_cooling_mode(InstantBarotropic(rho0=rho_crit, "
112 "gamma0=gamma_baro, cs0=cs0))";
113 ON_RANK_0(shamcomm::logs::err_ln("Ramses", msg));
115 },
116 R"==(
117 Removed, raises an error.
118
119 The reset of the internal energy onto a barotrope is now a cooling mode, replace
120 ``cfg.set_eos_reset_barotropic(rho_crit=..., cs0=..., gamma_baro=..., gamma=...)`` by
121 ``cfg.set_eos_adiabatic(gamma)`` and
122 ``cfg.set_cooling_mode(InstantBarotropic(rho0=rho_crit, gamma0=gamma_baro, cs0=cs0))``.
123)==")
124 .def(
125 "set_cooling_mode",
126 [](TConfig &self, const typename TCooling::None &) {
127 self.cooling_config.set_none();
128 },
129 py::arg("mode"),
130 R"==(
131 Disable the cooling (the default).
132
133 Usage
134 -----
135 >>> from shamrock.model_ramses import NoCooling
136 >>> cfg.set_cooling_mode(NoCooling())
137)==")
138 .def(
139 "set_cooling_mode",
140 [](TConfig &self, const typename TCooling::InstantBarotropic &mode) {
141 self.cooling_config.config = mode;
142 },
143 py::arg("mode"),
144 R"==(
145 Set the instantaneous barotropic cooling (RAMSES-like).
146
147 At the end of each timestep, before the CFL condition, the internal energy of every cell is
148 overwritten by :math:`P_{\rm baro}(\rho) / (\gamma - 1)`, with :math:`\gamma` the
149 adiabatic index of the equation of state (``cfg.set_eos_adiabatic``) and
150 :math:`P_{\rm baro}(\rho) = c_{s,0}^2 \rho (1 + (\rho / \rho_0)^{\gamma_0 - 1})`
151 (isothermal below ``rho0``, adiabatic with index ``gamma0`` above).
152
153 Usage
154 -----
155 >>> from shamrock.model_ramses import InstantBarotropic
156 >>> cfg.set_cooling_mode(InstantBarotropic(rho0=1e-13, gamma0=1.4, cs0=0.2))
157)==")
158 .def(
159 "set_riemann_solver",
160 [](TConfig &self, RiemannSolverMode mode) {
161 self.set_riemann_solver(mode);
162 },
163 py::arg("mode"),
164 R"==(
165 Set the gas Riemann solver.
166
167 Parameters
168 ----------
169 mode : RiemannSolverMode
170 One of ``Rusanov``, ``HLL`` (the default), ``HLLC_PVRS``, ``HLLC_Davis`` or
171 ``HLLC_RAMSES``, see
172 :py:class:`RiemannSolverMode`.
173
174 Usage
175 -----
176 >>> from shamrock.model_ramses import HLLC_PVRS
177 >>> cfg.set_riemann_solver(HLLC_PVRS)
178
179 or equivalently
180
181 >>> from shamrock.model_ramses import RiemannSolverMode
182 >>> cfg.set_riemann_solver(RiemannSolverMode.HLLC_PVRS)
183)==")
184 .def(
185 "set_riemann_solver_hll",
186 [](TConfig &self) {
187 warn_deprecated_riemann_setter("set_riemann_solver_hll", "HLL");
188 self.set_riemann_solver(HLL);
189 },
190 R"==(
191 Set the HLL Riemann solver.
192
193 .. deprecated::
194 Use ``cfg.set_riemann_solver(HLL)`` instead (see :py:meth:`set_riemann_solver`).
195)==")
196 .def(
197 "set_riemann_solver_hllc_pvrs",
198 [](TConfig &self) {
199 warn_deprecated_riemann_setter("set_riemann_solver_hllc_pvrs", "HLLC_PVRS");
200 self.set_riemann_solver(HLLC_PVRS);
201 },
202 R"==(
203 Set the HLLC_PVRS Riemann solver.
204
205 .. deprecated::
206 Use ``cfg.set_riemann_solver(HLLC_PVRS)`` instead (see :py:meth:`set_riemann_solver`).
207)==")
208 .def(
209 "set_riemann_solver_hllc",
210 [](TConfig & /*self*/) {
211 const std::string msg
212 = ".set_riemann_solver_hllc() has been removed, as several HLLC variants "
213 "are now available. Select one explicitly:\n"
214 " -> .set_riemann_solver(HLLC_PVRS) : the previous behaviour of "
215 ".set_riemann_solver_hllc()\n"
216 " -> .set_riemann_solver(HLLC_Davis)\n"
217 "with `from shamrock.model_ramses import HLLC_PVRS, HLLC_Davis`";
218 ON_RANK_0(shamcomm::logs::err_ln("Ramses", msg));
220 },
221 R"==(
222 Removed, raises an error.
223
224 It was replaced by ``cfg.set_riemann_solver(HLLC_PVRS)`` (same solver as before) to lift the
225 ambiguity on the HLLC variant; see also ``cfg.set_riemann_solver(HLLC_Davis)`` and
226 :py:meth:`set_riemann_solver`.
227)==")
228 .def(
229 "set_riemann_solver_hllc_davis",
230 [](TConfig &self) {
231 warn_deprecated_riemann_setter("set_riemann_solver_hllc_davis", "HLLC_Davis");
232 self.set_riemann_solver(HLLC_Davis);
233 },
234 R"==(
235 Set the HLLC_Davis Riemann solver.
236
237 .. deprecated::
238 Use ``cfg.set_riemann_solver(HLLC_Davis)`` instead (see :py:meth:`set_riemann_solver`).
239)==")
240 .def(
241 "set_riemann_solver_rusanov",
242 [](TConfig &self) {
243 warn_deprecated_riemann_setter("set_riemann_solver_rusanov", "Rusanov");
244 self.set_riemann_solver(Rusanov);
245 },
246 R"==(
247 Set the Rusanov Riemann solver.
248
249 .. deprecated::
250 Use ``cfg.set_riemann_solver(Rusanov)`` instead (see :py:meth:`set_riemann_solver`).
251)==")
252 .def(
253 "set_slope_lim_none",
254 [](TConfig &self) {
255 self.slope_config = None;
256 })
257 .def(
258 "set_slope_lim_vanleer_f",
259 [](TConfig &self) {
260 self.slope_config = VanLeer_f;
261 })
262 .def(
263 "set_slope_lim_vanleer_std",
264 [](TConfig &self) {
265 self.slope_config = VanLeer_std;
266 })
267 .def(
268 "set_slope_lim_vanleer_sym",
269 [](TConfig &self) {
270 self.slope_config = VanLeer_sym;
271 })
272 .def(
273 "set_slope_lim_minmod",
274 [](TConfig &self) {
275 self.slope_config = Minmod;
276 })
277 .def(
278 "set_scheduler_config",
279 [](TConfig &self, u64 split_crit, u64 merge_crit) {
280 self.scheduler_conf.split_load_value = split_crit;
281 self.scheduler_conf.merge_load_value = merge_crit;
282 },
283 py::kw_only(),
284 py::arg("split_load_value"),
285 py::arg("merge_load_value"))
286 .def(
287 "set_face_time_interpolation",
288 [](TConfig &self, bool face_time_interpolate) {
289 self.face_half_time_interpolation = face_time_interpolate;
290 })
291 .def(
292 "set_boundary_condition",
293 [](TConfig &self, const std::string &axis, const std::string &bc_type) {
294 BCConfig::GhostType ghost_type;
295 if (bc_type == "periodic") {
296 ghost_type = BCConfig::GhostType::Periodic;
297 } else if (bc_type == "reflective") {
298 ghost_type = BCConfig::GhostType::Reflective;
299 } else if (bc_type == "outflow") {
300 ghost_type = BCConfig::GhostType::Outflow;
301 } else {
302 throw std::invalid_argument(
303 "Unsupported boundary condition type: " + bc_type);
304 }
305
306 if (axis == "x") {
307 self.bc_config.set_x(ghost_type);
308 } else if (axis == "y") {
309 self.bc_config.set_y(ghost_type);
310 } else if (axis == "z") {
311 self.bc_config.set_z(ghost_type);
312 } else {
313 throw std::invalid_argument("Unsupported axis: " + axis);
314 }
315 },
316 py::arg("axis"),
317 py::arg("bc_type"))
318 .def(
319 "set_dust_mode_dhll",
320 [](TConfig &self, u32 ndust) {
321 self.dust_config = {DHLL, ndust};
322 })
323 .def(
324 "set_dust_mode_hb",
325 [](TConfig &self, u32 ndust) {
326 self.dust_config = {HB, ndust};
327 })
328 .def(
329 "set_dust_mode_none",
330 [](TConfig &self) {
331 self.dust_config = {NoDust, 0};
332 })
333 .def(
334 "set_alpha_values",
335 [](TConfig &self, f32 alpha_values) {
336 return self.set_alphas_static(alpha_values);
337 })
338 .def(
339 "set_drag_mode_no_drag",
340 [](TConfig &self) {
341 self.drag_config.drag_solver_config = NoDrag;
342 self.drag_config.enable_frictional_heating = false;
343 })
344 .def(
345 "set_drag_mode_irk1",
346 [](TConfig &self, bool frictional_status) {
347 self.drag_config.drag_solver_config = IRK1;
348 self.drag_config.enable_frictional_heating = frictional_status;
349 })
350 .def(
351 "set_drag_mode_irk2",
352 [](TConfig &self, bool frictional_status) {
353 self.drag_config.drag_solver_config = IRK2;
354 self.drag_config.enable_frictional_heating = frictional_status;
355 })
356 .def(
357 "set_drag_mode_expo",
358 [](TConfig &self, bool frictional_status) {
359 self.drag_config.drag_solver_config = EXPO;
360 self.drag_config.enable_frictional_heating = frictional_status;
361 })
362 .def(
363 "set_amr_mode_none",
364 [](TConfig &self) {
365 self.amr_mode.set_refine_none();
366 })
367 .def(
368 "set_amr_mode_density_based",
369 [](TConfig &self, Tscal crit_mass) {
370 self.amr_mode.set_refine_density_based(crit_mass);
371 },
372 py::kw_only(),
373 py::arg("crit_mass"))
374 .def(
375 "set_amr_mode_pseudo_gradient_based",
376 [](TConfig &self, Tscal error_min, Tscal error_max) {
377 self.amr_mode.set_refine_pseudo_gradient_based(error_min, error_max);
378 },
379 py::kw_only(),
380 py::arg("error_min"),
381 py::arg("error_max"))
382 .def(
383 "set_amr_mode_jeans_length_based",
384 [](TConfig &self, u32 N_jeans) {
385 self.amr_mode.set_refine_jeans_length_based(N_jeans);
386 },
387 py::kw_only(),
388 py::arg("N_jeans"),
389 R"==(
390 Refine the blocks where the Jeans length is resolved by less than ``N_jeans`` cells.
391
392 A block is refined if one of its cells has :math:`N_J \Delta x > \lambda_J =
393 \sqrt{\pi c_s^2 / (G \rho)}`, with the sound speed of the equation of state (of the
394 barotrope with the ``InstantBarotropic`` cooling mode) and the gravitational constant of the unit
395 system (``cfg.set_units``). It is derefined if the cells twice larger would still resolve the
396 Jeans length by more than :math:`\sqrt{2} N_J` cells.
397
398 Only implemented in the new AMR (``cfg.set_amr_mode_old(False)``).
399)==")
400 .def(
401 "set_amr_mode_shear_based",
402 [](TConfig &self, Tscal threshold) {
403 self.amr_mode.set_refine_shear_based(threshold);
404 },
405 py::kw_only(),
406 py::arg("Threshold"))
407 .def(
408 "set_amr_mode_old",
409 [](TConfig &self, bool use_old_amr) {
410 self.amr_mode.old_amr = use_old_amr;
411 })
412 .def(
413 "set_first_order_interpolation_mode",
414 [](TConfig &self) {
415 self.amr_interp_mode = FIRST_ORDER;
416 })
417 .def(
418 "set_second_order_interpolation_mode",
419 [](TConfig &self) {
420 self.amr_interp_mode = SECOND_ORDER;
421 })
422 .def(
423 "set_gravity_mode_no_gravity",
424 [](TConfig &self) {
425 self.gravity_config.gravity_mode = NoGravity;
426 })
427 .def(
428 "set_gravity_mode_cg",
429 [](TConfig &self) {
430 self.gravity_config.gravity_mode = CG;
431 },
432 R"==(
433 Enable self-gravity, with the Jacobi preconditioned conjugate gradient Poisson solver.
434
435 Self-gravity is applied as an external force and requires the trapezoidal coupling
436 (``cfg.set_ext_force_coupling(ExtForceCoupling.Trapezoidal)``). The gravitational constant
437 is the one of the unit system (``cfg.set_units``).
438)==")
439 .def(
440 "set_gravity_mode_pcg",
441 [](TConfig &self) {
442 self.gravity_config.gravity_mode = PCG;
443 })
444 .def(
445 "set_gravity_mode_bicgstab",
446 [](TConfig &self) {
447 self.gravity_config.gravity_mode = BICGSTAB;
448 },
449 R"==(
450 Enable self-gravity, with the BiCGSTAB Poisson solver.
451
452 Self-gravity is applied as an external force and requires the trapezoidal coupling
453 (``cfg.set_ext_force_coupling(ExtForceCoupling.Trapezoidal)``). The gravitational constant
454 is the one of the unit system (``cfg.set_units``).
455)==")
456 .def(
457 "set_units",
458 &TConfig::set_units,
459 py::arg("units"),
460 R"==(
461 Set the unit system of the simulation (SI if not set).
462
463 It sets the gravitational constant used by self-gravity.
464)==")
465 .def(
466 "set_self_gravity_Niter_max",
467 [](TConfig &self, u32 Niter) {
468 self.gravity_config.Niter_max = Niter;
469 },
470 py::arg("Niter"),
471 R"==(
472 Set the maximum number of iterations of the self-gravity Poisson solver.
473)==")
474 .def(
475 "set_self_gravity_tol",
476 [](TConfig &self, Tscal tol) {
477 self.gravity_config.tol = tol;
478 },
479 py::arg("tol"),
480 R"==(
481 Set the convergence tolerance of the self-gravity Poisson solver.
482
483 The solver stops when the L2 norm of the residual is below tol relative to the
484 one of the right-hand side.
485)==")
486 .def(
487 "set_self_gravity_happy_breakdown_tol",
488 [](TConfig &self, Tscal tol) {
489 self.gravity_config.tol_hp_bk = tol;
490 },
491 py::arg("tol"),
492 R"==(
493 Set the tolerance of the BiCGSTAB lucky breakdown test.
494
495 BiCGSTAB restarts (shadow residual and search direction reset to the residual)
496 when |<r_k, r'_0>| < tol |r_k| |r'_0|.
497)==")
498 .def(
499 "add_ext_force_constant_gravity",
500 [](TConfig &self, Tvec g) {
501 self.ext_force_config.add_constant_gravity(g);
502 },
503 py::arg("g"))
504 .def(
505 "add_ext_force_point_mass_gravity",
506 [](TConfig &self, Tscal mass, Tvec pos, Tscal epsilon_soft) {
507 self.ext_force_config.add_point_mass_gravity(mass, pos, epsilon_soft);
508 },
509 py::arg("mass"),
510 py::arg("pos"),
511 py::arg("epsilon_soft"),
512 R"==(
513 Add the gravity of a fixed point mass to the external forces:
514 a = -G M (r - pos) / (|r - pos|^2 + epsilon_soft^2)^{3/2}, with G from the unit system.
515 epsilon_soft must be > 0.
516 )==")
517 .def(
518 "set_ext_force_coupling",
519 [](TConfig &self, ExtForceCoupling mode) {
520 self.ext_force_config.set_coupling(mode);
521 },
522 py::arg("mode"),
523 R"==(
524 Set the time quadrature coupling the external forces to the solver.
525
526 Parameters
527 ----------
528 mode : ExtForceCoupling
529 Either ``ExtForceCoupling.Midpoint`` (the default) or ``ExtForceCoupling.Trapezoidal``,
530 as obtained from ``from shamrock.model_ramses import ExtForceCoupling``.
531)==")
532 .def("set_npscal_gas", [](TConfig &self, u32 npscal_gas) {
533 self.npscal_gas_config.npscal_gas = npscal_gas;
534 });
535
536 std::string sod_tube_analysis_name = name_model + "_AnalysisSodTube";
537 py::class_<TAnalysisSodTube>(m, sod_tube_analysis_name.c_str())
538 .def("compute_L2_dist", [](TAnalysisSodTube &self) -> std::tuple<Tscal, Tvec, Tscal> {
539 auto ret = self.compute_L2_dist();
540 return {ret.rho, ret.v, ret.P};
541 });
542
543 py::class_<T>(m, name_model.c_str())
544 .def("init", &T::init)
545 .def("init_scheduler", &T::init_scheduler)
546 .def("make_base_grid", &T::make_base_grid)
547 .def("dump_vtk", &T::dump_vtk)
548 .def("dump", &T::dump)
549 .def("load_from_dump", &T::load_from_dump)
550 .def("evolve_once_override_time", &T::evolve_once_time_expl)
551 .def("evolve_once", &T::evolve_once)
552 .def(
553 "evolve_until",
554 [](T &self, f64 target_time, i32 niter_max) {
555 return self.evolve_until(target_time, niter_max);
556 },
557 py::arg("target_time"),
558 py::kw_only(),
559 py::arg("niter_max") = -1)
560 .def("timestep", &T::timestep)
561 .def("solver_logs_last_rate", &T::solver_logs_last_rate)
562 .def("solver_logs_last_obj_count", &T::solver_logs_last_obj_count)
563 .def(
564 "solver_logs_last_system_metrics",
565 [](T &self) {
566 auto system_metrics = self.solver.solve_logs.get_last_system_metrics();
567 py::dict ret;
568 ret["duration"] = system_metrics.wall_time;
569 if (system_metrics.rank_energy_consummed.has_value()) {
570 ret["rank_energy_consummed"] = system_metrics.rank_energy_consummed.value();
571 }
572 if (system_metrics.gpu_energy_consummed.has_value()) {
573 ret["gpu_energy_consummed"] = system_metrics.gpu_energy_consummed.value();
574 }
575 if (system_metrics.cpu_energy_consummed.has_value()) {
576 ret["cpu_energy_consummed"] = system_metrics.cpu_energy_consummed.value();
577 }
578 if (system_metrics.dram_energy_consummed.has_value()) {
579 ret["dram_energy_consummed"] = system_metrics.dram_energy_consummed.value();
580 }
581 return ret;
582 })
583 .def(
584 "set_field_value_lambda_f64",
585 [](T &self,
586 std::string field_name,
587 const std::function<f64(Tvec, Tvec)> pos_to_val,
588 const i32 offset) {
589 return self.template set_field_value_lambda<f64>(
590 field_name, pos_to_val, offset);
591 },
592 py::arg("field_name"),
593 py::arg("pos_to_val"),
594 py::arg("offset") = 0)
595 .def(
596 "set_field_value_lambda_f64_3",
597 [](T &self,
598 std::string field_name,
599 const std::function<f64_3(Tvec, Tvec)> pos_to_val,
600 const i32 offset) {
601 return self.template set_field_value_lambda<f64_3>(
602 field_name, pos_to_val, offset);
603 },
604 py::arg("field_name"),
605 py::arg("pos_to_val"),
606 py::arg("offset") = 0)
607 .def(
608 "gen_default_config",
609 [](T &self) -> TConfig {
610 return TConfig();
611 })
612 .def(
613 "set_solver_config",
614 [](T &self, TConfig cfg) {
615 if (self.ctx.is_scheduler_initialized()) {
617 "Cannot change solver config after scheduler is initialized");
618 }
619 cfg.check_config();
620 self.solver.solver_config = cfg;
621 })
622 .def(
623 "get_cell_coords",
624 [](T &self, std::pair<TgridVec, TgridVec> block_coord, u32 cell_local_id) {
625 return self.get_cell_coords(block_coord, cell_local_id);
626 })
627 .def(
628 "make_analysis_sodtube",
629 [](T &self,
630 shamphys::SodTube sod,
631 Tvec direction,
632 Tscal time_val,
633 Tscal x_ref,
634 Tscal x_min,
635 Tscal x_max) {
636 return std::make_unique<TAnalysisSodTube>(
637 self.ctx,
638 self.solver.solver_config,
639 self.solver.storage,
640 sod,
641 direction,
642 time_val,
643 x_ref,
644 x_min,
645 x_max);
646 })
647 .def(
648 "add_timestep_callback",
649 [](T &self,
650 std::optional<std::function<void(void)>> step_begin_callback,
651 std::optional<std::function<void(void)>> step_end_callback) {
652 self.solver.timestep_callbacks.push_back(
653 {std::move(step_begin_callback), std::move(step_end_callback)});
654 },
655 py::kw_only(),
656 py::arg("step_begin") = std::nullopt,
657 py::arg("step_end") = std::nullopt)
658 .def(
659 "get_solver_tex",
660 [](T &self) {
661 return shambase::get_check_ref(self.solver.storage.solver_sequence).get_tex();
662 })
663 .def(
664 "get_solver_dot_graph",
665 [](T &self) {
666 return shambase::get_check_ref(self.solver.storage.solver_sequence)
667 .get_dot_graph();
668 })
669 .def(
670 "render_slice",
671 [](T &self, std::string name, std::string field_type, std::vector<Tvec> positions)
672 -> std::variant<std::vector<f64>, std::vector<f64_3>> {
673 if (field_type == "f64") {
674 ramses::modules::GridRender<Tvec, TgridVec, f64> render(
675 self.ctx, self.solver.solver_config, self.solver.storage);
676 return render.compute_slice(name, positions).copy_to_stdvec();
677 }
678
679 if (field_type == "f64_3") {
680 ramses::modules::GridRender<Tvec, TgridVec, f64_3> render(
681 self.ctx, self.solver.solver_config, self.solver.storage);
682 return render.compute_slice(name, positions).copy_to_stdvec();
683 }
684
685 throw shambase::make_except_with_loc<std::runtime_error>("unknown field type");
686 })
687 .def(
688 "get_time",
689 [](T &self) {
690 return self.solver.get_time();
691 })
692 .def(
693 "get_dt",
694 [](T &self) {
695 return self.solver.get_dt();
696 })
697 .def(
698 "set_time",
699 [](T &self, Tscal t) {
700 return self.solver.set_time(t);
701 })
702 .def("set_next_dt", [](T &self, Tscal dt) {
703 return self.solver.set_next_dt(dt);
704 });
705 }
706} // namespace shammodels::basegodunov
707
709 auto &m = root_module;
710
711 py::module mramses = m.def_submodule("model_ramses", "Shamrock Ramses solver");
712
713 std::string base_name = "RamsesModel";
714 using namespace shammodels::basegodunov;
715
716 py::enum_<ExtForceCoupling>(
717 mramses,
718 "ExtForceCoupling",
719 R"==(
720 Time quadrature used to couple the external forces source term to the solver.
721 Both modes are second order in time, and give the same momentum update for a constant
722 acceleration.
723
724 Usage
725 -----
726 >>> from shamrock.model_ramses import ExtForceCoupling
727 >>> cfg.set_ext_force_coupling(ExtForceCoupling.Trapezoidal)
728)==")
729 .value(
730 "Midpoint",
732 R"==(
733 Explicit midpoint rule. This is the default.
734
735 The forces are evaluated once, at :math:`t^{n+1/2}`, from the time centered state (e.g.
736 :math:`\rho^{n+1/2} = \rho^n + \frac{\Delta t}{2} \partial_t \rho`, and the momentum for a
737 velocity dependent force), and applied over the whole time step.
738)==")
739 .value(
740 "Trapezoidal",
742 R"==(
743 Trapezoidal rule (time centred source term, as in RAMSES).
744
745 The forces are evaluated at :math:`t^n` and :math:`t^{n+1}`, each with the state at the same
746 time, and the average of the two source terms is applied over the whole time step:
747 :math:`\Delta (\rho \mathbf{v}) = \Delta t \, \frac{1}{2}
748 (\rho^n \mathbf{a}^n + \rho^{n+1} \mathbf{a}^{n+1})`.
749 A force evaluated at :math:`t^{n+1}` may only depend on the density there (e.g.
750 self-gravity), since it is known before the kick.
751)==");
752
753 py::enum_<RiemannSolverMode>(
754 mramses,
755 "RiemannSolverMode",
756 R"==(
757 Gas Riemann solver of the Ramses solver, to be given to ``cfg.set_riemann_solver``.
758
759 The values are also exported in ``shamrock.model_ramses`` directly.
760
761 Usage
762 -----
763 >>> from shamrock.model_ramses import HLLC_PVRS
764 >>> cfg.set_riemann_solver(HLLC_PVRS)
765)==")
766 .value(
767 "Rusanov",
768 RiemannSolverMode::Rusanov,
769 R"==(
770 Rusanov (local Lax-Friedrichs) flux.
771)==")
772 .value(
773 "HLL",
774 RiemannSolverMode::HLL,
775 R"==(
776 Harten-Lax-van Leer flux. This is the default.
777)==")
778 .value(
779 "HLLC_PVRS",
780 RiemannSolverMode::HLLC_PVRS,
781 R"==(
782 HLLC flux, with wave speeds estimated from the primitive variable Riemann solver (PVRS) star
783 pressure, following Toro (Riemann Solvers and Numerical Methods for Fluid Dynamics,
784 chapter 10).
785)==")
786 .value(
787 "HLLC_Davis",
788 RiemannSolverMode::HLLC_Davis,
789 R"==(
790 HLLC flux, using the Davis (1988) wave speed estimate
791 :math:`s_l = \min(v_l - c_l, v_r - c_r)`, :math:`s_r = \max(v_l + c_l, v_r + c_r)`.
792)==")
793 .value(
794 "HLLC_RAMSES",
795 RiemannSolverMode::HLLC_RAMSES,
796 R"==(
797 HLLC flux, using the wave speed estimate of the RAMSES code (``riemann_hllc`` in
798 ``hydro/godunov_utils.f90``)
799 :math:`s_l = \min(v_l, v_r) - \max(c_l, c_r)`, :math:`s_r = \max(v_l, v_r) + \max(c_l, c_r)`,
800 so that the flux matches the ``hllc`` solver of RAMSES.
801)==")
802 .export_values();
803
804 using Cooling = CoolingConfig<f64_3>;
805 using Tscal = f64;
806
807 py::class_<typename Cooling::None>(
808 mramses,
809 "NoCooling",
810 R"==(
811 No cooling, to be given to ``cfg.set_cooling_mode``.
812
813 Usage
814 -----
815 >>> from shamrock.model_ramses import NoCooling
816 >>> cfg.set_cooling_mode(NoCooling())
817)==")
818 .def(py::init<>())
819 .def("__repr__", [](const typename Cooling::None &) {
820 return std::string("NoCooling()");
821 });
822
823 py::class_<typename Cooling::InstantBarotropic>(
824 mramses,
825 "InstantBarotropic",
826 R"==(
827 Instantaneous barotropic cooling (RAMSES-like), to be given to ``cfg.set_cooling_mode``.
828
829 At the end of each timestep, before the CFL condition, the internal energy of every cell is
830 overwritten by :math:`P_{\rm baro}(\rho) / (\gamma - 1)`, with :math:`\gamma` the
831 adiabatic index of the equation of state and
832 :math:`P_{\rm baro}(\rho) = c_{s,0}^2 \rho (1 + (\rho / \rho_0)^{\gamma_0 - 1})`.
833
834 Parameters
835 ----------
836 rho0 : float
837 Density of the isothermal to adiabatic transition of the barotrope (> 0)
838 gamma0 : float
839 Adiabatic index of the barotrope above ``rho0``
840 cs0 : float
841 Isothermal sound speed of the barotrope below ``rho0`` (> 0)
842
843 Usage
844 -----
845 >>> from shamrock.model_ramses import InstantBarotropic
846 >>> cfg.set_cooling_mode(InstantBarotropic(rho0=1e-13, gamma0=1.4, cs0=0.2))
847)==")
848 .def(
849 py::init([](Tscal rho0, Tscal gamma0, Tscal cs0) {
850 return typename Cooling::InstantBarotropic{rho0, cs0, gamma0};
851 }),
852 py::kw_only(),
853 py::arg("rho0"),
854 py::arg("gamma0"),
855 py::arg("cs0"))
856 .def_readwrite("rho0", &Cooling::InstantBarotropic::rho0)
857 .def_readwrite("gamma0", &Cooling::InstantBarotropic::gamma0)
858 .def_readwrite("cs0", &Cooling::InstantBarotropic::cs0)
859 .def("__repr__", [](const typename Cooling::InstantBarotropic &self) {
860 return sham::format(
861 "InstantBarotropic(rho0={}, gamma0={}, cs0={})", self.rho0, self.gamma0, self.cs0);
862 });
863
864 add_instance<f64_3, i64_3>(
865 mramses, base_name + "_f64_3_i64_3_SolverConfig", base_name + "_f64_3_i64_3_Model");
866
867 using VariantAMRGodunovBind = std::variant<std::unique_ptr<Model<f64_3, i64_3>>>;
868
869 m.def(
870 "get_Model_Ramses",
871 [](ShamrockCtx &ctx,
872 std::string vector_type,
873 std::string grid_repr) -> VariantAMRGodunovBind {
874 VariantAMRGodunovBind ret;
875
876 if (vector_type == "f64_3" && grid_repr == "i64_3") {
877 ret = std::make_unique<Model<f64_3, i64_3>>(ctx);
878 } else {
880 "unknown combination of representation and grid_repr");
881 }
882
883 return ret;
884 },
885 py::kw_only(),
886 py::arg("context"),
887 py::arg("vector_type"),
888 py::arg("grid_repr"));
889}
double f64
Alias for double.
float f32
Alias for float.
std::uint32_t u32
32 bit unsigned integer
std::uint64_t u64
64 bit unsigned integer
std::int32_t i32
32 bit integer
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.
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.
namespace for the basegodunov model
RiemannSolverMode
Gas Riemann solver used by the Ramses (Godunov) model.
@ HB
Huang and Bai. Pressureless Riemann solver by Huang and Bai (2022) in Athena++.
@ DHLL
Dust HLL. This is merely the HLL solver for dust. It's then a Rusanov like.
@ NoDust
No dust, so no Riemann solver is used.
ExtForceCoupling
Time quadrature used to couple the external forces source term to the solver.
Pybind11 include and definitions.
#define ON_PYTHON_INIT
Register a Python module init function using static initialization.
Utilities to convert JSON objects to Python objects and vice versa. TODO: try to convert directly wit...
Cooling of the gas, applied on top of the (adiabatic) equation of state.
Functions related to the MPI communicator.
#define ON_RANK_0(x)
Macro to execute code only on rank 0.
Definition worldInfo.hpp:73