Shamrock 2025.10.0
Astrophysical Code
Loading...
Searching...
No Matches
pySPHModel.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
17
20#include "shambase/memory.hpp"
23#include "shamcomm/logs.hpp"
42#include "shamphys/SodTube.hpp"
45#include <experimental/mdspan>
46#include <pybind11/cast.h>
47#include <pybind11/numpy.h>
48#include <pybind11/pytypes.h>
49#include <memory>
50#include <optional>
51#include <random>
52#include <utility>
53
54template<class Tvec, template<class> class SPHKernel>
55void add_instance(py::module &m, std::string name_config, std::string name_model) {
56 using namespace shammodels::sph;
57
58 using Tscal = shambase::VecComponent<Tvec>;
59
60 using T = Model<Tvec, SPHKernel>;
61
65 using TConfig = typename T::Solver::Config;
66
67 using custom_getter_t
68 = std::function<pybind11::array_t<f64>(size_t, shamrock::PatchDataLazyGetter &)>;
69
70 shamlog_debug_ln("[Py]", "registering class :", name_config, typeid(T).name());
71 shamlog_debug_ln("[Py]", "registering class :", name_model, typeid(T).name());
72
73 py::class_<TConfig> config_cls(m, name_config.c_str());
74
75 shammodels::common::add_json_defs<TConfig>(config_cls);
76
77 config_cls.def("print_status", &TConfig::print_status)
78 .def("set_particle_tracking", &TConfig::set_particle_tracking)
79 .def(
80 "set_scheduler_config",
81 [](TConfig &self, u64 split_crit, u64 merge_crit) {
82 self.scheduler_conf.split_load_value = split_crit;
83 self.scheduler_conf.merge_load_value = merge_crit;
84 },
85 py::kw_only(),
86 py::arg("split_load_value"),
87 py::arg("merge_load_value"))
88 .def("set_tree_reduction_level", &TConfig::set_tree_reduction_level)
89 .def(
90 "set_neigh_cache_strategy",
91 &TConfig::set_neigh_cache_strategy,
92 R"==(
93 Set the strategy used to build the neighbours cache.
94
95 Parameters
96 ----------
97 strategy : NeighCacheStrategy
98 Either ``NeighCacheStrategy.SingleStage`` or ``NeighCacheStrategy.TwoStage``
99 (the default), as obtained from ``from shamrock import NeighCacheStrategy``.
100)==")
101 .def(
102 "set_two_stage_search",
103 &TConfig::set_two_stage_search,
104 R"==(
105 Set the neighbours cache strategy from a boolean.
106
107 .. deprecated::
108 Use :py:meth:`set_neigh_cache_strategy` instead.
109)==")
110 .def("set_show_neigh_stats", &TConfig::set_show_neigh_stats)
111 .def(
112 "set_max_neigh_cache_size",
113 [](TConfig &self, const py::object &max_neigh_cache_size) {
114 ON_RANK_0(shamlog_warn_ln(
115 "SPH",
116 ".set_max_neigh_cache_size() is deprecated,\n"
117 " -> calling this is a no-op,\n"
118 " -> you can remove the call to that function"););
119 })
120 .def("set_filter_empty_patch_gz", &TConfig::set_filter_empty_patch_gz)
121 .def("set_smoothing_length_density_based", &TConfig::set_smoothing_length_density_based)
122 .def(
123 "set_smoothing_length_density_based_neigh_lim",
124 &TConfig::set_smoothing_length_density_based_neigh_lim)
125 .def(
126 "set_smoothing_length_density_based_bisecting_nr",
127 &TConfig::set_smoothing_length_density_based_bisecting_nr)
128 .def("set_enable_particle_reordering", &TConfig::set_enable_particle_reordering)
129 .def("set_particle_reordering_step_freq", &TConfig::set_particle_reordering_step_freq)
130 .def("set_show_ghost_zone_graph", &TConfig::set_show_ghost_zone_graph)
131 .def("set_show_ghost_stats", &TConfig::set_show_ghost_stats)
132 .def("use_luminosity", &TConfig::use_luminosity)
133 .def("compute_GW", &TConfig::use_GW)
134 .def("set_save_dt_to_fields", &TConfig::set_save_dt_to_fields)
135 .def("should_save_dt_to_fields", &TConfig::should_save_dt_to_fields)
136 .def("set_eos_isothermal", &TConfig::set_eos_isothermal)
137 .def("set_eos_adiabatic", &TConfig::set_eos_adiabatic)
138 .def("set_eos_polytropic", &TConfig::set_eos_polytropic)
139 .def("set_eos_locally_isothermal", &TConfig::set_eos_locally_isothermal)
140 .def(
141 "set_eos_locally_isothermalLP07",
142 [](TConfig &self, Tscal cs0, Tscal q, Tscal r0) {
143 self.set_eos_locally_isothermalLP07(cs0, q, r0);
144 },
145 py::kw_only(),
146 py::arg("cs0"),
147 py::arg("q"),
148 py::arg("r0"))
149 .def(
150 "set_eos_locally_isothermalFA2014",
151 [](TConfig &self, Tscal h_over_r) {
152 self.set_eos_locally_isothermalFA2014(h_over_r);
153 },
154 py::kw_only(),
155 py::arg("h_over_r"))
156 .def(
157 "set_eos_locally_isothermalFA2014_extended",
158 [](TConfig &self, Tscal cs0, Tscal q, Tscal r0, u32 n_sinks) {
159 self.set_eos_locally_isothermalFA2014_extended(cs0, q, r0, n_sinks);
160 },
161 py::kw_only(),
162 py::arg("cs0"),
163 py::arg("q"),
164 py::arg("r0"),
165 py::arg("n_sinks"))
166 .def(
167 "set_eos_fermi",
168 [](TConfig &self, Tscal mu_e) {
169 self.set_eos_fermi(mu_e);
170 },
171 py::kw_only(),
172 py::arg("mu_e"))
173 .def(
174 "set_eos_barotropic",
175 [](TConfig &self, Tscal cs0, Tscal rho0, Tscal gamma0) {
176 self.set_eos_barotropic(cs0, rho0, gamma0);
177 },
178 py::kw_only(),
179 py::arg("cs0"),
180 py::arg("rho0"),
181 py::arg("gamma0") = Tscal{5.0 / 3.0})
182 .def("set_artif_viscosity_None", &TConfig::set_artif_viscosity_None)
183 .def(
184 "set_artif_viscosity_Constant",
185 [](TConfig &self, Tscal alpha_u, Tscal alpha_AV, Tscal beta_AV) {
186 self.set_artif_viscosity_Constant({alpha_u, alpha_AV, beta_AV});
187 },
188 py::kw_only(),
189 py::arg("alpha_u"),
190 py::arg("alpha_AV"),
191 py::arg("beta_AV"))
192 .def(
193 "set_artif_viscosity_VaryingMM97",
194 [](TConfig &self,
195 Tscal alpha_min,
196 Tscal alpha_max,
197 Tscal sigma_decay,
198 Tscal alpha_u,
199 Tscal beta_AV) {
200 self.set_artif_viscosity_VaryingMM97(
201 {alpha_min, alpha_max, sigma_decay, alpha_u, beta_AV});
202 },
203 py::kw_only(),
204 py::arg("alpha_min"),
205 py::arg("alpha_max"),
206 py::arg("sigma_decay"),
207 py::arg("alpha_u"),
208 py::arg("beta_AV"))
209 .def(
210 "set_artif_viscosity_VaryingCD10",
211 [](TConfig &self,
212 Tscal alpha_min,
213 Tscal alpha_max,
214 Tscal sigma_decay,
215 Tscal alpha_u,
216 Tscal beta_AV) {
217 self.set_artif_viscosity_VaryingCD10(
218 {alpha_min, alpha_max, sigma_decay, alpha_u, beta_AV});
219 },
220 py::kw_only(),
221 py::arg("alpha_min"),
222 py::arg("alpha_max"),
223 py::arg("sigma_decay"),
224 py::arg("alpha_u"),
225 py::arg("beta_AV"))
226 .def(
227 "set_artif_viscosity_ConstantDisc",
228 [](TConfig &self, Tscal alpha_AV, Tscal alpha_u, Tscal beta_AV) {
229 self.set_artif_viscosity_ConstantDisc({alpha_AV, alpha_u, beta_AV});
230 },
231 py::kw_only(),
232 py::arg("alpha_AV"),
233 py::arg("alpha_u"),
234 py::arg("beta_AV"))
235 .def(
236 "set_IdealMHD",
237 [](TConfig &self, Tscal sigma_mhd, Tscal alpha_B) {
238 self.set_ideal_mhd({sigma_mhd, alpha_B});
239 },
240 py::kw_only(),
241 py::arg("sigma_mhd"),
242 py::arg("alpha_B") = 1.0)
243 .def(
244 "set_NonIdealMHD",
245 [](TConfig &self, Tscal sigma_mhd, Tscal etaO, Tscal etaH, Tscal etaAD, Tscal alpha_B) {
246 self.set_non_ideal_mhd({sigma_mhd, alpha_B, etaO, etaH, etaAD});
247 },
248 py::kw_only(),
249 py::arg("sigma_mhd"),
250 py::arg("etaO"),
251 py::arg("etaH"),
252 py::arg("etaAD"),
253 py::arg("alpha_B") = 1.0)
254 .def(
255 "set_self_gravity_none",
256 [](TConfig &self) {
257 self.self_grav_config.set_none();
258 })
259 .def(
260 "set_self_gravity_direct",
261 [](TConfig &self, bool reference_mode = false) {
262 self.self_grav_config.set_direct(reference_mode);
263 },
264 py::kw_only(),
265 py::arg("reference_mode") = false)
266 .def(
267 "set_self_gravity_mm",
268 [](TConfig &self, u32 mm_order, f64 opening_angle, u32 reduction_level) {
269 self.self_grav_config.set_mm(mm_order, opening_angle, reduction_level);
270 },
271 py::kw_only(),
272 py::arg("order"),
273 py::arg("opening_angle"),
274 py::arg("reduction_level") = 3)
275 .def(
276 "set_self_gravity_fmm",
277 [](TConfig &self, u32 order, f64 opening_angle, u32 reduction_level) {
278 self.self_grav_config.set_fmm(order, opening_angle, reduction_level);
279 },
280 py::kw_only(),
281 py::arg("order"),
282 py::arg("opening_angle"),
283 py::arg("reduction_level") = 3)
284 .def(
285 "set_self_gravity_sfmm",
286 [](TConfig &self,
287 u32 sfmm_order,
288 f64 opening_angle,
289 bool leaf_lowering,
290 u32 reduction_level) {
291 self.self_grav_config.set_sfmm(
292 sfmm_order, opening_angle, leaf_lowering, reduction_level);
293 },
294 py::kw_only(),
295 py::arg("order"),
296 py::arg("opening_angle"),
297 py::arg("leaf_lowering") = true,
298 py::arg("reduction_level") = 3)
299 .def(
300 "set_softening_plummer",
301 [](TConfig &self, f64 epsilon) {
302 self.self_grav_config.set_softening_plummer(epsilon);
303 },
304 py::kw_only(),
305 py::arg("epsilon"))
306 .def(
307 "set_softening_none",
308 [](TConfig &self) {
309 self.self_grav_config.set_softening_none();
310 })
311 .def("set_boundary_free", &TConfig::set_boundary_free)
312 .def("set_boundary_periodic", &TConfig::set_boundary_periodic)
313 .def("set_boundary_shearing_periodic", &TConfig::set_boundary_shearing_periodic)
314 .def(
315 "set_dust_mode_none",
316 [](TConfig &self) {
317 self.dust_config.set_none();
318 })
319 .def(
320 "set_dust_mode_monofluid_tva",
321 [](TConfig &self,
322 u32 nvar,
323 bool pure_diffusion_mode,
324 Tscal C_1_fluid,
325 Tscal C_drift,
326 Tscal cfl_density_threshold,
327 bool ensure_s_j_positivity,
328 bool smooth_s_positivity_limiter,
329 bool dust_corrected_av,
330 std::optional<Tscal> clamp_dust_frac,
331 bool pair_gate_s_positivity_limiter) {
332 self.dust_config.set_monofluid_tva(
333 nvar,
334 pure_diffusion_mode,
335 C_1_fluid,
336 C_drift,
337 cfl_density_threshold,
338 ensure_s_j_positivity,
339 smooth_s_positivity_limiter,
340 dust_corrected_av,
341 clamp_dust_frac,
342 pair_gate_s_positivity_limiter);
343 },
344 py::kw_only(),
345 py::arg("nvar"),
346 py::arg("pure_diffusion_mode") = false,
347 py::arg("C_1_fluid") = 0.1,
348 py::arg("C_drift") = 1.0,
349 py::arg("cfl_density_threshold") = shambase::get_epsilon<Tscal>(),
350 py::arg("ensure_s_j_positivity") = true,
351 py::arg("smooth_s_positivity_limiter") = false,
352 py::arg("dust_corrected_av") = false,
353 py::arg("clamp_dust_frac") = std::nullopt,
354 py::arg("pair_gate_s_positivity_limiter") = false)
355 .def(
356 "set_dust_mode_monofluid_complete",
357 [](TConfig &self, u32 ndust) {
358 self.dust_config.set_monofluid_complete(ndust);
359 },
360 py::kw_only(),
361 py::arg("ndust"))
362 .def(
363 "set_dust_drag_constant",
364 [](TConfig &self, std::vector<Tscal> ts) {
365 self.dust_config.set_drag_constant({.stopping_times = std::move(ts)});
366 })
367 .def(
368 "set_dust_drag_epstein",
369 [](TConfig &self,
370 Tscal gamma,
371 std::vector<Tscal> grain_sizes,
372 std::vector<Tscal> grain_densities) {
373 self.dust_config.set_drag_epstein(
374 {.gamma = gamma,
375 .grains_sizes = std::move(grain_sizes),
376 .grains_densities = std::move(grain_densities)});
377 },
378 py::arg("gamma"),
379 py::arg("grain_sizes"),
380 py::arg("grain_densities"))
381 .def(
382 "set_dust_evol_coala_coag",
383 [](TConfig &self,
384 Tscal rhodust_eps,
385 Tscal vfrag_threshold,
386 std::vector<Tscal> massgrid,
387 py::array_t<Tscal> tabflux_coag,
388 Tscal tau_frac) {
389 if (massgrid.size() == 0) {
391 "massgrid must not be empty");
392 }
393
394 u32 nbins = massgrid.size() - 1;
395
396 // tabflux_coag is a 3D array of shape (nbins ** 3)
397
398 // assert rank is 3
399 if (tabflux_coag.ndim() != 3) {
401 "tabflux_coag must be a 3D array, got ndim="
402 + std::to_string(tabflux_coag.ndim()));
403 }
404
405 // assert shape is (nbins, nbins, nbins)
406 if (tabflux_coag.shape(0) != nbins || tabflux_coag.shape(1) != nbins
407 || tabflux_coag.shape(2) != nbins) {
409 "tabflux_coag must be a 3D array of shape (nbins, nbins, nbins) with "
410 "nbins="
411 + std::to_string(nbins) + " (massgrid.size() - 1), got shape ("
412 + std::to_string(tabflux_coag.shape(0)) + ", "
413 + std::to_string(tabflux_coag.shape(1)) + ", "
414 + std::to_string(tabflux_coag.shape(2)) + ")");
415 }
416
417 std::vector<Tscal> tabflux_coag_vec(nbins * nbins * nbins);
418
419 using mdspan_rank_3 = std::mdspan<Tscal, std::dextents<u32, 3>>;
420 mdspan_rank_3 tabflux_coag_mdspan(tabflux_coag_vec.data(), nbins, nbins, nbins);
421
422 for (u32 i = 0; i < nbins; i++) {
423 for (u32 j = 0; j < nbins; j++) {
424 for (u32 k = 0; k < nbins; k++) {
425 tabflux_coag_mdspan(i, j, k) = tabflux_coag.mutable_at(i, j, k);
426 }
427 }
428 }
429
430 self.dust_config.set_dust_evol_coala(
431 {.rhodust_eps = rhodust_eps,
432 .tau_frac = tau_frac,
433 .vfrag_threshold = vfrag_threshold,
434 .massgrid = massgrid,
435 .tabflux_coag = tabflux_coag_vec});
436 },
437 py::arg("rhodust_eps"),
438 py::arg("vfrag_threshold"),
439 py::arg("massgrid"),
440 py::arg("tabflux_coag"),
441 py::arg("tau_frac") = Tscal(10),
442 R"pbdoc(
443 Enable the COALA dust coagulation source term.
444
445 Args:
446 rhodust_eps: Dust density floor.
447 vfrag_threshold: Fragmentation velocity threshold, must be positive.
448 In this coagulation-only mode, a pair of dust bins whose
449 differential velocity ``|dv_ij|`` exceeds this value gets
450 ``dv_ij = 0``. This is a crude stand-in for fragmentation
451 ("poor man" fragmentation), not a fragmentation model. Pass
452 ``math.inf`` to disable it.
453 massgrid: Dust mass grid bin edges, of size ``nbins + 1``.
454 tabflux_coag: Tabulated coagulation flux, of shape
455 ``(nbins, nbins, nbins)``.
456 tau_frac: The source term on ``s_j`` is integrated implicitly over
457 ``dt_eff = max(dt, tau_frac * rhodust_eps / |S|)``, that is over at
458 least the time needed to move ``tau_frac * rhodust_eps``. This bounds
459 the rate of an empty bin when ``dt`` is null or tiny (e.g. right after
460 a dust injection). Must be positive.
461 )pbdoc")
462 .def(
463 "set_dust_ballabio_ts_limiter",
464 [](TConfig &self, bool enabled) {
465 self.dust_config.ballabio_ts_limiter = enabled;
466 },
467 py::arg("enabled"))
468 .def(
469 "add_ext_force_point_mass",
470 [](TConfig &self, Tscal central_mass, Tscal Racc, Tvec central_pos) {
471 self.add_ext_force_point_mass(central_mass, Racc, central_pos);
472 },
473 py::arg("central_mass"),
474 py::arg("Racc"),
475 py::kw_only(),
476 py::arg("central_pos") = Tvec{0, 0, 0})
477 .def("add_ext_force_paczynski_wiita", &TConfig::add_ext_force_paczynski_wiita)
478 .def(
479 "add_ext_force_lense_thirring",
480 [](TConfig &self,
481 Tscal central_mass,
482 Tscal Racc,
483 Tscal a_spin,
484 Tvec dir_spin,
485 Tvec central_pos) {
486 self.add_ext_force_lense_thirring(
487 central_mass, Racc, a_spin, dir_spin, central_pos);
488 },
489 py::kw_only(),
490 py::arg("central_mass"),
491 py::arg("Racc"),
492 py::arg("a_spin"),
493 py::arg("dir_spin"),
494 py::arg("central_pos") = Tvec{0, 0, 0})
495 .def(
496 "add_ext_force_shearing_box",
497 [](TConfig &self, Tscal Omega_0, Tscal eta, Tscal q) {
498 self.add_ext_force_shearing_box(Omega_0, eta, q);
499 },
500 py::kw_only(),
501 py::arg("Omega_0"),
502 py::arg("eta"),
503 py::arg("q"))
504 .def(
505 "add_ext_force_velocity_dissipation",
506 [](TConfig &self, Tscal eta) {
507 self.ext_force_config.add_velocity_dissipation(eta);
508 },
509 py::kw_only(),
510 py::arg("eta"))
511 .def(
512 "add_ext_force_vertical_disc_potential",
513 [](TConfig &self, Tscal central_mass, Tscal R0) {
514 self.ext_force_config.add_vertical_disc_potential(central_mass, R0);
515 },
516 py::kw_only(),
517 py::arg("central_mass"),
518 py::arg("R0"))
519 .def("set_units", &TConfig::set_units)
520 .def(
521 "get_units",
522 [](TConfig &self) {
523 return self.unit_sys;
524 })
525 .def(
526 "set_cfl_cour",
527 [](TConfig &self, Tscal cfl_cour) {
528 self.cfl_config.cfl_cour = cfl_cour;
529 })
530 .def(
531 "set_cfl_force",
532 [](TConfig &self, Tscal cfl_force) {
533 self.cfl_config.cfl_force = cfl_force;
534 })
535 .def(
536 "set_eta_sink",
537 [](TConfig &self, Tscal eta_sink) {
538 self.cfl_config.eta_sink = eta_sink;
539 })
540 .def("set_cfl_mult_stiffness", &TConfig::set_cfl_mult_stiffness)
541 .def(
542 "set_show_cfl_detail",
543 [](TConfig &self, bool show_cfl_detail) {
544 self.show_cfl_detail = show_cfl_detail;
545 },
546 py::arg("show_cfl_detail"))
547 .def(
548 "set_particle_mass",
549 [](TConfig &self, Tscal gpart_mass) {
550 self.gpart_mass = gpart_mass;
551 })
552 .def(
553 "add_kill_sphere",
554 [](TConfig &self, const Tvec &center, Tscal radius) {
555 self.particle_killing.add_kill_sphere(center, radius);
556 },
557 py::kw_only(),
558 py::arg("center"),
559 py::arg("radius"));
560
561 std::string sod_tube_analysis_name = name_model + "_AnalysisSodTube";
562 py::class_<TAnalysisSodTube>(m, sod_tube_analysis_name.c_str())
563 .def("compute_L2_dist", [](TAnalysisSodTube &self) -> std::tuple<Tscal, Tvec, Tscal> {
564 auto ret = self.compute_L2_dist();
565 return {ret.rho, ret.v, ret.P};
566 });
567
568 std::string disc_analysis_name = name_model + "_AnalysisDisc";
569 py::class_<TAnalysisDisc>(m, disc_analysis_name.c_str())
570 .def(
571 "collect_data",
572 [](TAnalysisDisc &self, Tscal Rmin, Tscal Rmax, u32 Nbin, ShamrockCtx &ctx) {
573 auto anal = self.compute_analysis(Rmin, Rmax, Nbin, ctx);
574 py::dict dic_out;
575
576 auto radius = anal.radius.copy_to_stdvec();
577 auto counter = anal.counter.copy_to_stdvec();
578 auto Sigma = anal.Sigma.copy_to_stdvec();
579 auto lx = anal.lx.copy_to_stdvec();
580 auto ly = anal.ly.copy_to_stdvec();
581 auto lz = anal.lz.copy_to_stdvec();
582 auto tilt = anal.tilt.copy_to_stdvec();
583 auto twist = anal.twist.copy_to_stdvec();
584 auto psi = anal.psi.copy_to_stdvec();
585 auto Hsq = anal.Hsq.copy_to_stdvec();
586
587 dic_out["radius"] = radius;
588 dic_out["counter"] = counter;
589 dic_out["Sigma"] = Sigma;
590 dic_out["lx"] = lx;
591 dic_out["ly"] = ly;
592 dic_out["lz"] = lz;
593 dic_out["tilt"] = tilt;
594 dic_out["twist"] = twist;
595 dic_out["psi"] = psi;
596 dic_out["Hsq"] = Hsq;
597
598 return dic_out;
599 });
600
601 std::string setup_name = name_model + "_SPHSetup";
602 py::class_<TSPHSetup>(m, setup_name.c_str())
603 .def(
604 "make_generator_lattice_hcp",
605 [](TSPHSetup &self,
606 Tscal dr,
607 Tvec box_min,
608 Tvec box_max,
609 bool discontinuous,
610 Tscal init_h_factor) {
611 return self.make_generator_lattice_hcp(
612 dr, {box_min, box_max}, discontinuous, init_h_factor);
613 },
614 py::arg("dr"),
615 py::arg("box_min"),
616 py::arg("box_max"),
617 py::arg("discontinuous") = true,
619 R"==(
620 Generate particles on a HCP lattice of parameter dr (neighbours are 2 dr apart)
621
622 The initial smoothing length is set to init_h_factor * dr. The default 2^(5/6)
623 is the equilibrium smoothing length for hfact = 1 (the smallest hfact of all
624 the SPH kernels), so the initial guess never exceeds the equilibrium value.
625)==")
626 .def(
627 "make_generator_lattice_fcc",
628 [](TSPHSetup &self,
629 Tscal dr,
630 Tvec box_min,
631 Tvec box_max,
632 bool discontinuous,
633 Tscal init_h_factor) {
634 return self.make_generator_lattice_fcc(
635 dr, {box_min, box_max}, discontinuous, init_h_factor);
636 },
637 py::arg("dr"),
638 py::arg("box_min"),
639 py::arg("box_max"),
640 py::arg("discontinuous") = true,
642 R"==(
643 Generate particles on a true FCC lattice (ABC stacking of close-packed layers along z)
644 of parameter dr (neighbours are 2 dr apart)
645
646 The number of layers along z must be a multiple of 3, the number of rows along y even
647
648 The initial smoothing length is set to init_h_factor * dr. The default 2^(5/6)
649 is the equilibrium smoothing length for hfact = 1 (the smallest hfact of all
650 the SPH kernels), so the initial guess never exceeds the equilibrium value.
651)==")
652 .def(
653 "make_generator_lattice_cubic",
654 [](TSPHSetup &self, Tscal dr, Tvec box_min, Tvec box_max) {
655 return self.make_generator_lattice_cubic(dr, {box_min, box_max});
656 })
657 .def(
658 "make_generator_disc_mc",
659 [](TSPHSetup &self,
660 Tscal part_mass,
661 Tscal disc_mass,
662 Tscal r_in,
663 Tscal r_out,
664 std::function<Tscal(Tscal)> sigma_profile,
665 std::function<Tscal(Tscal)> H_profile,
666 std::function<Tscal(Tscal)> rot_profile,
667 std::function<Tscal(Tscal)> cs_profile,
668 std::function<Tvec(Tvec)> velocity_field,
669 std::function<Tscal(Tvec)> cs_field,
670 u64 random_seed,
671 Tscal init_h_factor) {
672 auto build_vel_lambda = [&]() -> std::function<Tvec(Tvec)> {
673 if (!velocity_field && !rot_profile) {
675 "make_generator_disc_mc: either velocity_field or rot_profile must be "
676 "provided, you must provide one of them");
677 }
678
679 if (velocity_field && rot_profile) {
681 "make_generator_disc_mc: either velocity_field or rot_profile must be "
682 "provided, you cannot provide both");
683 }
684
685 if (velocity_field) {
686 return std::move(velocity_field);
687 }
688 return [vth_r = std::move(rot_profile)](Tvec pos) {
689 pos[2] = 0; // to get the cylindrical radius
690 Tscal r = sycl::length(pos);
691
692 auto etheta = sycl::vec<Tscal, 3>{-pos.y(), pos.x(), 0};
693 etheta /= sycl::length(etheta);
694
695 return vth_r(r) * etheta;
696 };
697 };
698
699 auto build_cs_lambda = [&]() -> std::function<Tscal(Tvec)> {
700 bool need_cs = self.solver_config.is_eos_locally_isothermal();
701
702 if (!need_cs) {
703 if (cs_field) {
704 if (shamcomm::world_rank() == 0) {
706 "SPHSetup",
707 "make_generator_disc_mc: with the current EOS, cs_field is "
708 "ignored");
709 }
710 }
711 if (cs_profile) {
712 if (shamcomm::world_rank() == 0) {
714 "SPHSetup",
715 "make_generator_disc_mc: with the current EOS, cs_profile is "
716 "ignored");
717 }
718 }
719 return std::function<Tscal(Tvec)>{};
720 }
721
722 if (!cs_field && !cs_profile) {
724 "make_generator_disc_mc: either cs_field or cs_profile must be "
725 "provided, you must provide one of them");
726 }
727
728 if (cs_field && cs_profile) {
730 "make_generator_disc_mc: either cs_field or cs_profile must be "
731 "provided, you cannot provide both");
732 }
733
734 if (cs_field) {
735 return std::move(cs_field);
736 }
737
738 return [cs_r = std::move(cs_profile)](Tvec pos) {
739 pos[2] = 0; // to get the cylindrical radius
740 Tscal r = sycl::length(pos);
741 return cs_r(r);
742 };
743 };
744
745 return self.make_generator_disc_mc(
746 part_mass,
747 disc_mass,
748 r_in,
749 r_out,
750 std::move(sigma_profile),
751 std::move(H_profile),
752 build_vel_lambda(),
753 build_cs_lambda(),
754 std::mt19937_64(random_seed),
755 init_h_factor);
756 },
757 py::kw_only(),
758 py::arg("part_mass"),
759 py::arg("disc_mass"),
760 py::arg("r_in"),
761 py::arg("r_out"),
762 py::arg("sigma_profile"),
763 py::arg("H_profile"),
764 py::arg("rot_profile") = std::function<Tscal(Tscal)>{},
765 py::arg("cs_profile") = std::function<Tscal(Tscal)>{},
766 py::arg("velocity_field") = std::function<Tvec(Tvec)>{},
767 py::arg("cs_field") = std::function<Tscal(Tvec)>{},
768 py::arg("random_seed"),
769 py::arg("init_h_factor") = 0.8,
770 R"pbdoc(
771 Create a Monte Carlo disc particle generator.
772
773 Particles are sampled in cylindrical coordinates: the radius is drawn
774 with rejection sampling from ``sigma_profile``, the azimuth is uniform,
775 and the vertical coordinate follows a Gaussian with scale ``H_profile(r)``.
776 The initial density is extrapolated from the surface density profile, and
777 smoothing lengths are set from that density.
778
779 Args:
780 part_mass: Mass of each SPH particle.
781 disc_mass: Total disc mass. The particle count is ``disc_mass / part_mass``.
782 r_in: Inner disc radius.
783 r_out: Outer disc radius.
784 sigma_profile: Surface density profile ``sigma(r)``.
785 H_profile: Disc scale height profile ``H(r)``.
786 rot_profile: Azimuthal speed profile ``v_theta(r)``. The velocity is
787 projected along the cylindrical azimuthal direction at each
788 particle position. Mutually exclusive with ``velocity_field``.
789 cs_profile: Sound speed profile ``c_s(r)``. Evaluated at the cylindrical
790 radius of each particle. Required when the solver uses a locally
791 isothermal EOS. Mutually exclusive with ``cs_field``.
792 velocity_field: Velocity profile ``v(x, y, z)``. Mutually exclusive
793 with ``rot_profile``.
794 cs_field: Sound speed profile ``c_s(x, y, z)``. Required when the solver
795 uses a locally isothermal EOS. Mutually exclusive with ``cs_profile``.
796 random_seed: Seed for the Monte Carlo sampler.
797 init_h_factor: Multiplier applied to the smoothing length inferred from
798 the generated density. Defaults to ``0.8``.
799
800 Notes:
801 Exactly one of ``velocity_field`` or ``rot_profile`` must be provided.
802
803 If the solver uses a locally isothermal EOS, exactly one of ``cs_field``
804 or ``cs_profile`` must be provided. Otherwise both sound-speed profiles
805 are ignored and a warning is emitted if either is supplied.
806
807 Returns:
808 A setup node to pass to :py:meth:`apply_setup`.
809 )pbdoc")
810 .def(
811 "make_generator_from_context",
812 [](TSPHSetup &self, ShamrockCtx &context_other) {
813 return self.make_generator_from_context(context_other);
814 })
815 .def(
816 "make_combiner_add",
817 [](TSPHSetup &self,
820 return self.make_combiner_add(parent1, parent2);
821 })
822 .def(
823 "make_modifier_warp_disc",
824 [](TSPHSetup &self,
826 Tscal Rwarp,
827 Tscal Hwarp,
828 Tscal inclination,
829 Tscal posangle) {
830 return self.make_modifier_warp_disc(parent, Rwarp, Hwarp, inclination, posangle);
831 },
832 py::kw_only(),
833 py::arg("parent"),
834 py::arg("Rwarp"),
835 py::arg("Hwarp"),
836 py::arg("inclination"),
837 py::arg("posangle") = 0.)
838 .def(
839 "make_modifier_custom_warp",
840 [](TSPHSetup &self,
842 std::function<Tscal(Tscal)> inc_profile,
843 std::function<Tscal(Tscal)> psi_profile,
844 std::function<Tvec(Tscal)> k_profile) {
845 return self.make_modifier_custom_warp(parent, inc_profile, psi_profile, k_profile);
846 },
847 py::kw_only(),
848 py::arg("parent"),
849 py::arg("inc_profile"),
850 py::arg("psi_profile"),
851 py::arg("k_profile"))
852 .def(
853 "make_modifier_offset",
854 [](TSPHSetup &self,
856 Tvec offset_postion,
857 Tvec offset_velocity) {
858 return self.make_modifier_add_offset(parent, offset_postion, offset_velocity);
859 },
860 py::kw_only(),
861 py::arg("parent"),
862 py::arg("offset_position"),
863 py::arg("offset_velocity"))
864 .def(
865 "make_modifier_filter",
866 [](TSPHSetup &self,
868 std::function<bool(Tvec)> filter) {
869 return self.make_modifier_filter(parent, filter);
870 },
871 py::kw_only(),
872 py::arg("parent"),
873 py::arg("filter"))
874 .def(
875 "make_modifier_split_part",
876 [](TSPHSetup &self,
878 u64 n_split,
879 u64 seed,
880 Tscal h_scaling) {
881 return self.make_modifier_split_part(parent, n_split, seed, h_scaling);
882 },
883 py::kw_only(),
884 py::arg("parent"),
885 py::arg("n_split"),
886 py::arg("seed"),
887 py::arg("h_scaling") = 0.6)
888 .def(
889 "apply_setup",
890 [](TSPHSetup &self,
892 bool part_reordering,
893 std::optional<u32> gen_step,
894 std::optional<u32> insert_step,
895 std::optional<u64> msg_count_limit,
896 std::optional<u64> msg_size_limit,
897 std::optional<u64> max_msg_size,
898 bool do_setup_log,
899 bool use_new_setup,
900 bool speculative_balancing) {
901 if (use_new_setup) {
902 return self.apply_setup_new(
903 setup,
904 part_reordering,
905 gen_step,
906 insert_step,
907 msg_count_limit,
908 msg_size_limit,
909 max_msg_size,
910 do_setup_log,
911 speculative_balancing);
912 } else {
913 if (bool(gen_step)) {
914 ON_RANK_0(
916 "SPHSetup", "gen_step is ignored when using old setup"));
917 }
918 if (bool(msg_count_limit)) {
919 ON_RANK_0(
921 "SPHSetup", "msg_count_limit is ignored when using old setup"));
922 }
923 if (bool(msg_size_limit)) {
924 ON_RANK_0(
926 "SPHSetup", "msg_size_limit is ignored when using old setup"));
927 }
928 if (bool(max_msg_size)) {
929 ON_RANK_0(
931 "SPHSetup", "max_msg_size is ignored when using old setup"));
932 }
933 if (bool(do_setup_log)) {
934 ON_RANK_0(
936 "SPHSetup", "do_setup_log is ignored when using old setup"));
937 }
938 return self.apply_setup(setup, part_reordering, insert_step);
939 }
940 },
941 py::arg("setup"),
942 py::kw_only(),
943 py::arg("part_reordering") = true,
944 py::arg("gen_step") = std::nullopt,
945 py::arg("insert_step") = std::nullopt,
946 py::arg("msg_count_limit") = std::nullopt,
947 py::arg("rank_comm_size_limit") = std::nullopt,
948 py::arg("max_msg_size") = std::nullopt,
949 py::arg("do_setup_log") = false,
950 py::arg("use_new_setup") = true,
951 py::arg("speculative_balancing") = false);
952
953 py::class_<T>(m, name_model.c_str())
954 .def(py::init([](ShamrockCtx &ctx) {
955 return std::make_unique<T>(ctx);
956 }))
957 .def("init", &T::init)
958 .def("init_scheduler", &T::init_scheduler)
959
960 .def(
961 "evolve_once_override_time",
962 &T::evolve_once_time_expl,
963 py::arg("t_curr"),
964 py::arg("dt_input"))
965 .def("evolve_once", &T::evolve_once)
966 .def(
967 "evolve_until",
968 [](T &self, f64 target_time, i32 niter_max, f64 max_walltime) {
969 return self.evolve_until(target_time, niter_max, max_walltime);
970 },
971 py::arg("target_time"),
972 py::kw_only(),
973 py::arg("niter_max") = -1,
974 py::arg("max_walltime") = -1)
975 .def("timestep", &T::timestep)
976 .def("set_cfl_cour", &T::set_cfl_cour, py::arg("cfl_cour"))
977 .def("set_cfl_force", &T::set_cfl_force, py::arg("cfl_force"))
978 .def("set_eta_sink", &T::set_eta_sink, py::arg("eta_sink"))
979 .def("set_particle_mass", &T::set_particle_mass, py::arg("gpart_mass"))
980 .def("get_particle_mass", &T::get_particle_mass)
981 .def("rho_h", &T::rho_h)
982 .def("get_hfact", &T::get_hfact)
983 .def(
984 "get_solver_tex",
985 [](T &self) {
986 return shambase::get_check_ref(self.solver.storage.solver_sequence).get_tex();
987 })
988 .def(
989 "get_solver_dot_graph",
990 [](T &self) {
991 return shambase::get_check_ref(self.solver.storage.solver_sequence).get_dot_graph();
992 })
993 .def(
994 "get_box_dim_fcc_3d",
995 [](T &self, f64 dr, u32 xcnt, u32 ycnt, u32 zcnt) {
996 return self.get_box_dim_fcc_3d(dr, xcnt, ycnt, zcnt);
997 })
998 .def(
999 "get_box_dim_true_fcc_3d",
1000 [](T &self, f64 dr, u32 xcnt, u32 ycnt, u32 zcnt) {
1001 return self.get_box_dim_true_fcc_3d(dr, xcnt, ycnt, zcnt);
1002 },
1003 py::arg("dr"),
1004 py::arg("xcnt"),
1005 py::arg("ycnt"),
1006 py::arg("zcnt"),
1007 R"==(
1008 Get the dimensions of a periodic box holding a true FCC lattice of xcnt * ycnt * zcnt
1009 (see setup.make_generator_lattice_fcc). Unlike get_box_dim_fcc_3d (which actually
1010 describes a HCP lattice and is kept for backward compatibility), this throws if the box
1011 cannot be periodic: xcnt must be >= 2, ycnt even and zcnt a multiple of 3.
1012)==")
1013 .def(
1014 "get_ideal_fcc_box",
1015 [](T &self, f64 dr, f64_3 box_min, f64_3 box_max) {
1016 ON_RANK_0(
1018 "SPH",
1019 "The python function get_ideal_fcc_box is deprecated in the SPH model and "
1020 "will be removed at some point, replace it by "
1021 "shamrock.math.get_ideal_hcp_box"));
1022 return shammath::LatticeHCP<f64_3>::get_ideal_hcp_box(dr, {box_min, box_max});
1023 })
1024 .def(
1025 "get_ideal_hcp_box",
1026 [](T &self, f64 dr, f64_3 box_min, f64_3 box_max) {
1027 ON_RANK_0(
1029 "SPH",
1030 "The python function get_ideal_hcp_box is deprecated in the SPH model and "
1031 "will be removed at some point, replace it by "
1032 "shamrock.math.get_ideal_hcp_box"));
1033 return shammath::LatticeHCP<f64_3>::get_ideal_hcp_box(dr, {box_min, box_max});
1034 })
1035 .def(
1036 "resize_simulation_box",
1037 [](T &self, f64_3 box_min, f64_3 box_max) {
1038 return self.resize_simulation_box({box_min, box_max});
1039 })
1040 .def(
1041 "push_particle",
1042 [](T &self, std::vector<f64_3> pos, std::vector<f64> hpart, std::vector<f64> upart) {
1043 return self.push_particle(pos, hpart, upart);
1044 })
1045 .def(
1046 "push_particle_mhd",
1047 [](T &self,
1048 std::vector<f64_3> pos,
1049 std::vector<f64> hpart,
1050 std::vector<f64> upart,
1051 std::vector<f64_3> B_on_rho,
1052 std::vector<f64> psi_on_ch) {
1053 return self.push_particle_mhd(pos, hpart, upart, B_on_rho, psi_on_ch);
1054 })
1055 .def(
1056 "add_cube_fcc_3d",
1057 [](T &self, f64 dr, f64_3 box_min, f64_3 box_max) {
1058 return self.add_cube_fcc_3d(dr, {box_min, box_max});
1059 })
1060 .def(
1061 "add_cube_hcp_3d",
1062 [](T &self, f64 dr, f64_3 box_min, f64_3 box_max) {
1063 return self.add_cube_hcp_3d(dr, {box_min, box_max});
1064 })
1065 .def(
1066 "add_cube_hcp_3d_v2",
1067 [](T &self, f64 dr, f64_3 box_min, f64_3 box_max) {
1068 return self.add_cube_hcp_3d_v2(dr, {box_min, box_max});
1069 })
1070 .def(
1071 "add_disc_3d_keplerian",
1072 [](T &self,
1073 Tvec center,
1074 u32 Npart,
1075 Tscal p,
1076 Tscal rho_0,
1077 Tscal m,
1078 Tscal r_in,
1079 Tscal r_out,
1080 Tscal q,
1081 Tscal cmass) {
1082 return self.add_cube_disc_3d(center, Npart, p, rho_0, m, r_in, r_out, q, cmass);
1083 })
1084 .def(
1085 "add_disc_3d",
1086 [](T &self,
1087 Tvec center,
1088 Tscal central_mass,
1089 u32 Npart,
1090 Tscal r_in,
1091 Tscal r_out,
1092 Tscal disc_mass,
1093 Tscal p,
1094 Tscal H_r_in,
1095 Tscal q) {
1096 return self.add_disc_3d(
1097 center, central_mass, Npart, r_in, r_out, disc_mass, p, H_r_in, q);
1098 })
1099 .def(
1100 "add_big_disc_3d",
1101 [](T &self,
1102 Tvec center,
1103 Tscal central_mass,
1104 u32 Npart,
1105 Tscal r_in,
1106 Tscal r_out,
1107 Tscal disc_mass,
1108 Tscal p,
1109 Tscal H_r_in,
1110 Tscal q,
1111 u16 seed) {
1112 self.add_big_disc_3d(
1113 center,
1114 central_mass,
1115 Npart,
1116 r_in,
1117 r_out,
1118 disc_mass,
1119 p,
1120 H_r_in,
1121 q,
1122 std::mt19937{seed});
1123 return disc_mass / Npart;
1124 })
1125 .def("get_total_part_count", &T::get_total_part_count)
1126 .def("total_mass_to_part_mass", &T::total_mass_to_part_mass)
1127 .def(
1128 "set_value_in_a_box",
1129 [](T &self,
1130 const std::string &field_name,
1131 const std::string &field_type,
1132 const pybind11::object &value,
1133 f64_3 box_min,
1134 f64_3 box_max,
1135 u32 ivar) {
1136 if (field_type == "f64") {
1137 f64 val = value.cast<f64>();
1138 self.set_value_in_a_box(field_name, val, {box_min, box_max}, ivar);
1139 } else if (field_type == "f64_3") {
1140 f64_3 val = value.cast<f64_3>();
1141 self.set_value_in_a_box(field_name, val, {box_min, box_max}, ivar);
1142 } else {
1144 "unknown field type");
1145 }
1146 },
1147 py::arg("field_name"),
1148 py::arg("field_type"),
1149 py::arg("value"),
1150 py::arg("box_min"),
1151 py::arg("box_max"),
1152 py::kw_only(),
1153 py::arg("ivar") = 0)
1154 .def(
1155 "set_value_in_sphere",
1156 [](T &self,
1157 const std::string &field_name,
1158 const std::string &field_type,
1159 const pybind11::object &value,
1160 f64_3 center,
1161 f64 radius) {
1162 if (field_type == "f64") {
1163 f64 val = value.cast<f64>();
1164 self.set_value_in_sphere(field_name, val, center, radius);
1165 } else if (field_type == "f64_3") {
1166 f64_3 val = value.cast<f64_3>();
1167 self.set_value_in_sphere(field_name, val, center, radius);
1168 } else {
1170 "unknown field type");
1171 }
1172 })
1173 .def(
1174 "set_field_value_lambda_f64",
1175 [](T &self,
1176 std::string field_name,
1177 const std::function<f64(Tvec)> pos_to_val,
1178 const u32 offset) {
1179 return self.template set_field_value_lambda<f64>(
1180 std::move(field_name), pos_to_val, offset);
1181 },
1182 py::arg("field_name"),
1183 py::arg("pos_to_val"),
1184 py::arg("offset") = 0)
1185 .def(
1186 "set_field_value_lambda_f64_3",
1187 [](T &self,
1188 std::string field_name,
1189 const std::function<f64_3(Tvec)> pos_to_val,
1190 const u32 offset) {
1191 return self.template set_field_value_lambda<f64_3>(
1192 std::move(field_name), pos_to_val, offset);
1193 },
1194 py::arg("field_name"),
1195 py::arg("pos_to_val"),
1196 py::arg("offset") = 0)
1197 .def("overwrite_field_value_f64", &T::template overwrite_field_value<f64>)
1198 .def("overwrite_field_value_f64_3", &T::template overwrite_field_value<f64_3>)
1199 .def("remap_positions", &T::remap_positions)
1200 //.def("set_field_value_lambda_f64_3",[](T&self,std::string field_name, const
1201 // std::function<f64_3 (Tscal, Tscal , Tscal)> pos_to_val){
1202 // self.template set_field_value_lambda<f64_3>(field_name, [=](Tvec v){
1203 // return pos_to_val(v.x(), v.y(),v.z());
1204 // });
1205 //})
1206 .def(
1207 "add_kernel_value",
1208 [](T &self,
1209 const std::string &field_name,
1210 const std::string &field_type,
1211 const pybind11::object &value,
1212 f64_3 center,
1213 f64 h_ker) {
1214 if (field_type == "f64") {
1215 f64 val = value.cast<f64>();
1216 self.add_kernel_value(field_name, val, center, h_ker);
1217 } else if (field_type == "f64_3") {
1218 f64_3 val = value.cast<f64_3>();
1219 self.add_kernel_value(field_name, val, center, h_ker);
1220 } else {
1222 "unknown field type");
1223 }
1224 })
1225 .def(
1226 "get_sum",
1227 [](T &self, const std::string &field_name, const std::string &field_type) {
1228 if (field_type == "f64") {
1229 return py::cast(self.template get_sum<f64>(field_name));
1230 } else if (field_type == "f64_3") {
1231 return py::cast(self.template get_sum<f64_3>(field_name));
1232 } else {
1234 "unknown field type");
1235 }
1236 })
1237 .def(
1238 "get_closest_part_to",
1239 [](T &self, f64_3 pos) -> f64_3 {
1240 return self.get_closest_part_to(pos);
1241 })
1242 .def(
1243 "gen_default_config",
1244 [](T &self) {
1245 return typename T::Solver::Config{};
1246 })
1247 .def(
1248 "get_current_config",
1249 [](T &self) {
1250 return self.solver.solver_config;
1251 })
1252 .def("set_solver_config", &T::set_solver_config)
1253 .def("add_sink", &T::add_sink)
1254 .def(
1255 "get_sinks",
1256 [](T &self) {
1257 py::list list_out;
1258
1259 auto &sync = shambase::get_check_ref(self.ctx.sched).synchronized_data;
1260 auto edges = get_sink_edges<Tvec>(sync);
1261 for (auto &sink : to_sink_particles(edges)) {
1262 py::dict sink_dic;
1263 sink_dic["pos"] = sink.pos;
1264 sink_dic["velocity"] = sink.velocity;
1265 sink_dic["sph_acceleration"] = sink.sph_acceleration;
1266 sink_dic["ext_acceleration"] = sink.ext_acceleration;
1267 sink_dic["mass"] = sink.mass;
1268 sink_dic["angular_momentum"] = sink.angular_momentum;
1269 sink_dic["accretion_radius"] = sink.accretion_radius;
1270 list_out.append(sink_dic);
1271 }
1272
1273 // only present with dust, flattened as [i_sink * ndust + j_dust]
1274 if (has_sink_accreted_dust_mass(sync)) {
1275 auto &dust_mass = get_sink_accreted_dust_mass<Tvec>(sync);
1276 size_t nsink = list_out.size();
1277 size_t ndust = (nsink == 0) ? 0 : dust_mass.size() / nsink;
1278 for (size_t i = 0; i < nsink; i++) {
1279 auto begin = dust_mass.begin() + i * ndust;
1280 list_out[i]["accreted_dust_mass"]
1281 = std::vector<Tscal>(begin, begin + ndust);
1282 }
1283 }
1284
1285 return list_out;
1286 })
1287 .def(
1288 "get_units",
1289 [](T &self) {
1290 return self.solver.solver_config.unit_sys;
1291 })
1292 .def(
1293 "render_slice",
1294 [](T &self,
1295 const std::string &name,
1296 const std::string &field_type,
1297 const std::vector<Tvec> &positions,
1298 const std::optional<custom_getter_t> &custom_getter)
1299 -> std::variant<std::vector<f64>, std::vector<f64_3>> {
1300 if (custom_getter.has_value()) {
1301 if (!(name == "custom" && field_type == "f64")) {
1303 "custom_getter only available for name=custom and field_type=f64");
1304 }
1305 }
1306
1307 if (field_type == "f64") {
1309 self.ctx, self.solver.solver_config, self.solver.storage);
1310 return render.compute_slice(name, positions, custom_getter).copy_to_stdvec();
1311 }
1312
1313 if (field_type == "f64_3") {
1315 self.ctx, self.solver.solver_config, self.solver.storage);
1316 return render.compute_slice(name, positions, std::nullopt).copy_to_stdvec();
1317 }
1318
1319 throw shambase::make_except_with_loc<std::runtime_error>("unknown field type");
1320 },
1321 py::arg("name"),
1322 py::arg("field_type"),
1323 py::arg("positions"),
1324 py::arg("custom_getter") = std::nullopt)
1325 .def(
1326 "render_slice",
1327 [](T &self,
1329 const std::vector<Tvec> &positions) -> std::vector<f64> {
1331 self.ctx, self.solver.solver_config, self.solver.storage);
1332 return render.compute_slice(field, positions).copy_to_stdvec();
1333 },
1334 py::arg("field"),
1335 py::arg("positions"))
1336 .def(
1337 "render_slice",
1338 [](T &self,
1340 const std::vector<Tvec> &positions) -> std::vector<f64_3> {
1342 self.ctx, self.solver.solver_config, self.solver.storage);
1343 return render.compute_slice(field, positions).copy_to_stdvec();
1344 },
1345 py::arg("field"),
1346 py::arg("positions"))
1347 .def(
1348 "render_column_integ",
1349 [](T &self,
1350 const std::string &name,
1351 const std::string &field_type,
1352 const std::vector<shammath::Ray<Tvec>> &rays,
1353 const std::optional<custom_getter_t> &custom_getter)
1354 -> std::variant<std::vector<f64>, std::vector<f64_3>> {
1355 if (custom_getter.has_value()) {
1356 if (!(name == "custom" && field_type == "f64")) {
1358 "custom_getter only available for name=custom and field_type=f64");
1359 }
1360 }
1361
1362 if (field_type == "f64") {
1364 self.ctx, self.solver.solver_config, self.solver.storage);
1365 return render.compute_column_integ(name, rays, custom_getter).copy_to_stdvec();
1366 }
1367
1368 if (field_type == "f64_3") {
1370 self.ctx, self.solver.solver_config, self.solver.storage);
1371 return render.compute_column_integ(name, rays, std::nullopt).copy_to_stdvec();
1372 }
1373
1374 throw shambase::make_except_with_loc<std::runtime_error>("unknown field type");
1375 },
1376 py::arg("name"),
1377 py::arg("field_type"),
1378 py::arg("rays"),
1379 py::arg("custom_getter") = std::nullopt)
1380 .def(
1381 "render_column_integ",
1382 [](T &self,
1384 const std::vector<shammath::Ray<Tvec>> &rays) -> std::vector<f64> {
1386 self.ctx, self.solver.solver_config, self.solver.storage);
1387 return render.compute_column_integ(field, rays).copy_to_stdvec();
1388 },
1389 py::arg("field"),
1390 py::arg("rays"))
1391 .def(
1392 "render_column_integ",
1393 [](T &self,
1395 const std::vector<shammath::Ray<Tvec>> &rays) -> std::vector<f64_3> {
1397 self.ctx, self.solver.solver_config, self.solver.storage);
1398 return render.compute_column_integ(field, rays).copy_to_stdvec();
1399 },
1400 py::arg("field"),
1401 py::arg("rays"))
1402 .def(
1403 "compute_field",
1404 [](T &self,
1405 const std::string &name,
1406 const std::string &field_type,
1407 const std::optional<custom_getter_t> &custom_getter)
1408 -> std::variant<
1411 if (custom_getter.has_value()) {
1412 if (!(name == "custom" && field_type == "f64")) {
1414 "custom_getter only available for name=custom and field_type=f64");
1415 }
1416 }
1417
1418 if (field_type == "f64") {
1420 self.ctx, self.solver.solver_config, self.solver.storage);
1421 return render_field_getter.build_field(name, custom_getter);
1422 }
1423
1424 if (field_type == "f64_3") {
1426 self.ctx, self.solver.solver_config, self.solver.storage);
1427 return render_field_getter.build_field(name, custom_getter);
1428 }
1429
1430 throw shambase::make_except_with_loc<std::runtime_error>("unknown field type");
1431 },
1432 py::arg("name"),
1433 py::arg("field_type"),
1434 py::arg("custom_getter") = std::nullopt)
1435 .def(
1436 "render_azymuthal_integ",
1437 [](T &self,
1438 const std::string &name,
1439 const std::string &field_type,
1440 const std::vector<shammath::RingRay<Tvec>> &ring_rays,
1441 const std::optional<custom_getter_t> &custom_getter)
1442 -> std::variant<std::vector<f64>, std::vector<f64_3>> {
1443 if (custom_getter.has_value()) {
1444 if (!(name == "custom" && field_type == "f64")) {
1446 "custom_getter only available for name=custom and field_type=f64");
1447 }
1448 }
1449
1450 if (field_type == "f64") {
1452 self.ctx, self.solver.solver_config, self.solver.storage);
1453 return render.compute_azymuthal_integ(name, ring_rays, custom_getter)
1454 .copy_to_stdvec();
1455 }
1456
1457 if (field_type == "f64_3") {
1459 self.ctx, self.solver.solver_config, self.solver.storage);
1460 return render.compute_azymuthal_integ(name, ring_rays, std::nullopt)
1461 .copy_to_stdvec();
1462 }
1463
1464 throw shambase::make_except_with_loc<std::runtime_error>("unknown field type");
1465 },
1466 py::arg("name"),
1467 py::arg("field_type"),
1468 py::arg("ring_rays"),
1469 py::arg("custom_getter") = std::nullopt)
1470 .def(
1471 "render_azymuthal_integ",
1472 [](T &self,
1474 const std::vector<shammath::RingRay<Tvec>> &ring_rays) -> std::vector<f64> {
1476 self.ctx, self.solver.solver_config, self.solver.storage);
1477 return render.compute_azymuthal_integ(field, ring_rays).copy_to_stdvec();
1478 },
1479 py::arg("field"),
1480 py::arg("ring_rays"))
1481 .def(
1482 "render_azymuthal_integ",
1483 [](T &self,
1485 const std::vector<shammath::RingRay<Tvec>> &ring_rays) -> std::vector<f64_3> {
1487 self.ctx, self.solver.solver_config, self.solver.storage);
1488 return render.compute_azymuthal_integ(field, ring_rays).copy_to_stdvec();
1489 },
1490 py::arg("field"),
1491 py::arg("ring_rays"))
1492 .def(
1493 "render_cartesian_slice",
1494 [](T &self,
1495 const std::string &name,
1496 const std::string &field_type,
1497 Tvec center,
1498 Tvec delta_x,
1499 Tvec delta_y,
1500 u32 nx,
1501 u32 ny,
1502 const std::optional<custom_getter_t> &custom_getter)
1503 -> std::variant<py::array_t<Tscal>> {
1504 if (custom_getter.has_value()) {
1505 if (!(name == "custom" && field_type == "f64")) {
1507 "custom_getter only available for name=custom and field_type=f64");
1508 }
1509 }
1510
1511 if (field_type == "f64") {
1512 py::array_t<Tscal> ret({ny, nx});
1513
1515 self.ctx, self.solver.solver_config, self.solver.storage);
1516
1517 std::vector<f64> slice
1518 = render
1519 .compute_slice(name, center, delta_x, delta_y, nx, ny, custom_getter)
1520 .copy_to_stdvec();
1521
1522 for (u32 iy = 0; iy < ny; iy++) {
1523 for (u32 ix = 0; ix < nx; ix++) {
1524 ret.mutable_at(iy, ix) = slice[ix + nx * iy];
1525 }
1526 }
1527
1528 return ret;
1529 }
1530
1531 if (field_type == "f64_3") {
1532 py::array_t<Tscal> ret({ny, nx, 3_u32});
1533
1535 self.ctx, self.solver.solver_config, self.solver.storage);
1536
1537 std::vector<f64_3> slice
1538 = render.compute_slice(name, center, delta_x, delta_y, nx, ny, std::nullopt)
1539 .copy_to_stdvec();
1540
1541 for (u32 iy = 0; iy < ny; iy++) {
1542 for (u32 ix = 0; ix < nx; ix++) {
1543 ret.mutable_at(iy, ix, 0) = slice[ix + nx * iy][0];
1544 ret.mutable_at(iy, ix, 1) = slice[ix + nx * iy][1];
1545 ret.mutable_at(iy, ix, 2) = slice[ix + nx * iy][2];
1546 }
1547 }
1548
1549 return ret;
1550 }
1551
1553 return py::array_t<Tscal>({nx, ny});
1554 },
1555 py::arg("name"),
1556 py::arg("field_type"),
1557 py::arg("center"),
1558 py::arg("delta_x"),
1559 py::arg("delta_y"),
1560 py::arg("nx"),
1561 py::arg("ny"),
1562 py::arg("custom_getter") = std::nullopt)
1563 .def(
1564 "render_cartesian_slice",
1565 [](T &self,
1567 Tvec center,
1568 Tvec delta_x,
1569 Tvec delta_y,
1570 u32 nx,
1571 u32 ny) -> py::array_t<Tscal> {
1572 py::array_t<Tscal> ret({ny, nx});
1573
1575 self.ctx, self.solver.solver_config, self.solver.storage);
1576
1577 std::vector<f64> slice
1578 = render.compute_slice(field, center, delta_x, delta_y, nx, ny)
1579 .copy_to_stdvec();
1580
1581 for (u32 iy = 0; iy < ny; iy++) {
1582 for (u32 ix = 0; ix < nx; ix++) {
1583 ret.mutable_at(iy, ix) = slice[ix + nx * iy];
1584 }
1585 }
1586
1587 return ret;
1588 },
1589 py::arg("field"),
1590 py::arg("center"),
1591 py::arg("delta_x"),
1592 py::arg("delta_y"),
1593 py::arg("nx"),
1594 py::arg("ny"))
1595 .def(
1596 "render_cartesian_slice",
1597 [](T &self,
1599 Tvec center,
1600 Tvec delta_x,
1601 Tvec delta_y,
1602 u32 nx,
1603 u32 ny) -> py::array_t<Tscal> {
1604 py::array_t<Tscal> ret({ny, nx, 3_u32});
1605
1607 self.ctx, self.solver.solver_config, self.solver.storage);
1608
1609 std::vector<f64_3> slice
1610 = render.compute_slice(field, center, delta_x, delta_y, nx, ny)
1611 .copy_to_stdvec();
1612
1613 for (u32 iy = 0; iy < ny; iy++) {
1614 for (u32 ix = 0; ix < nx; ix++) {
1615 ret.mutable_at(iy, ix, 0) = slice[ix + nx * iy][0];
1616 ret.mutable_at(iy, ix, 1) = slice[ix + nx * iy][1];
1617 ret.mutable_at(iy, ix, 2) = slice[ix + nx * iy][2];
1618 }
1619 }
1620
1621 return ret;
1622 },
1623 py::arg("field"),
1624 py::arg("center"),
1625 py::arg("delta_x"),
1626 py::arg("delta_y"),
1627 py::arg("nx"),
1628 py::arg("ny"))
1629 .def(
1630 "render_cartesian_column_integ",
1631 [](T &self,
1632 const std::string &name,
1633 const std::string &field_type,
1634 Tvec center,
1635 Tvec delta_x,
1636 Tvec delta_y,
1637 u32 nx,
1638 u32 ny,
1639 const std::optional<custom_getter_t> &custom_getter)
1640 -> std::variant<py::array_t<Tscal>> {
1641 if (custom_getter.has_value()) {
1642 if (!(name == "custom" && field_type == "f64")) {
1644 "custom_getter only available for name=custom and field_type=f64");
1645 }
1646 }
1647
1648 if (field_type == "f64") {
1649 py::array_t<Tscal> ret({ny, nx});
1650
1652 self.ctx, self.solver.solver_config, self.solver.storage);
1653
1654 std::vector<f64> slice
1655 = render
1656 .compute_column_integ(
1657 name, center, delta_x, delta_y, nx, ny, custom_getter)
1658 .copy_to_stdvec();
1659
1660 for (u32 iy = 0; iy < ny; iy++) {
1661 for (u32 ix = 0; ix < nx; ix++) {
1662 ret.mutable_at(iy, ix) = slice[ix + nx * iy];
1663 }
1664 }
1665
1666 return ret;
1667 }
1668
1669 if (field_type == "f64_3") {
1670 py::array_t<Tscal> ret({ny, nx, 3_u32});
1671
1673 self.ctx, self.solver.solver_config, self.solver.storage);
1674
1675 std::vector<f64_3> slice
1676 = render
1677 .compute_column_integ(
1678 name, center, delta_x, delta_y, nx, ny, std::nullopt)
1679 .copy_to_stdvec();
1680
1681 for (u32 iy = 0; iy < ny; iy++) {
1682 for (u32 ix = 0; ix < nx; ix++) {
1683 ret.mutable_at(iy, ix, 0) = slice[ix + nx * iy][0];
1684 ret.mutable_at(iy, ix, 1) = slice[ix + nx * iy][1];
1685 ret.mutable_at(iy, ix, 2) = slice[ix + nx * iy][2];
1686 }
1687 }
1688
1689 return ret;
1690 }
1691
1693 return py::array_t<Tscal>({nx, ny});
1694 },
1695 py::arg("name"),
1696 py::arg("field_type"),
1697 py::arg("center"),
1698 py::arg("delta_x"),
1699 py::arg("delta_y"),
1700 py::arg("nx"),
1701 py::arg("ny"),
1702 py::arg("custom_getter") = std::nullopt)
1703 .def(
1704 "render_cartesian_column_integ",
1705 [](T &self,
1707 Tvec center,
1708 Tvec delta_x,
1709 Tvec delta_y,
1710 u32 nx,
1711 u32 ny) -> py::array_t<Tscal> {
1712 py::array_t<Tscal> ret({ny, nx});
1713
1715 self.ctx, self.solver.solver_config, self.solver.storage);
1716
1717 std::vector<f64> slice
1718 = render.compute_column_integ(field, center, delta_x, delta_y, nx, ny)
1719 .copy_to_stdvec();
1720
1721 for (u32 iy = 0; iy < ny; iy++) {
1722 for (u32 ix = 0; ix < nx; ix++) {
1723 ret.mutable_at(iy, ix) = slice[ix + nx * iy];
1724 }
1725 }
1726
1727 return ret;
1728 },
1729 py::arg("field"),
1730 py::arg("center"),
1731 py::arg("delta_x"),
1732 py::arg("delta_y"),
1733 py::arg("nx"),
1734 py::arg("ny"))
1735 .def(
1736 "render_cartesian_column_integ",
1737 [](T &self,
1739 Tvec center,
1740 Tvec delta_x,
1741 Tvec delta_y,
1742 u32 nx,
1743 u32 ny) -> py::array_t<Tscal> {
1744 py::array_t<Tscal> ret({ny, nx, 3_u32});
1745
1747 self.ctx, self.solver.solver_config, self.solver.storage);
1748
1749 std::vector<f64_3> slice
1750 = render.compute_column_integ(field, center, delta_x, delta_y, nx, ny)
1751 .copy_to_stdvec();
1752
1753 for (u32 iy = 0; iy < ny; iy++) {
1754 for (u32 ix = 0; ix < nx; ix++) {
1755 ret.mutable_at(iy, ix, 0) = slice[ix + nx * iy][0];
1756 ret.mutable_at(iy, ix, 1) = slice[ix + nx * iy][1];
1757 ret.mutable_at(iy, ix, 2) = slice[ix + nx * iy][2];
1758 }
1759 }
1760
1761 return ret;
1762 },
1763 py::arg("field"),
1764 py::arg("center"),
1765 py::arg("delta_x"),
1766 py::arg("delta_y"),
1767 py::arg("nx"),
1768 py::arg("ny"))
1769 .def(
1770 "gen_config_from_phantom_dump",
1771 [](T &self, PhantomDump &dump, bool bypass_error) {
1772 return self.gen_config_from_phantom_dump(dump, bypass_error);
1773 },
1774 py::arg("dump"),
1775 py::arg("bypass_error") = false,
1776 R"==(
1777 This function generate a shamrock sph solver config from a phantom dump
1778
1779 Parameters
1780 ----------
1781 PhantomDump dump
1782 bypass_error = false (default) bypass any error in the config
1783)==")
1784 .def(
1785 "init_from_phantom_dump",
1786 [](T &self, PhantomDump &dump, Tscal hpart_fact_load) {
1787 self.init_from_phantom_dump(dump, hpart_fact_load);
1788 },
1789 py::arg("dump"),
1790 py::arg("hpart_fact_load") = 1.0)
1791 .def(
1792 "make_phantom_dump",
1793 [](T &self) {
1794 return self.make_phantom_dump();
1795 })
1796 .def("do_vtk_dump", &T::do_vtk_dump)
1797 .def("set_debug_dump", &T::set_debug_dump)
1798 .def("solver_logs_last_rate", &T::solver_logs_last_rate)
1799 .def("solver_logs_last_obj_count", &T::solver_logs_last_obj_count)
1800 .def(
1801 "solver_logs_last_system_metrics",
1802 [&](T &self) {
1803 auto system_metrics = self.solver.solve_logs.get_last_system_metrics();
1804 py::dict ret;
1805 ret["duration"] = system_metrics.wall_time;
1806 if (system_metrics.rank_energy_consummed.has_value()) {
1807 ret["rank_energy_consummed"] = system_metrics.rank_energy_consummed.value();
1808 }
1809 if (system_metrics.gpu_energy_consummed.has_value()) {
1810 ret["gpu_energy_consummed"] = system_metrics.gpu_energy_consummed.value();
1811 }
1812 if (system_metrics.cpu_energy_consummed.has_value()) {
1813 ret["cpu_energy_consummed"] = system_metrics.cpu_energy_consummed.value();
1814 }
1815 if (system_metrics.dram_energy_consummed.has_value()) {
1816 ret["dram_energy_consummed"] = system_metrics.dram_energy_consummed.value();
1817 }
1818 return ret;
1819 })
1820 .def("solver_logs_cumulated_step_time", &T::solver_logs_cumulated_step_time)
1821 .def("solver_logs_reset_cumulated_step_time", &T::solver_logs_reset_cumulated_step_time)
1822 .def("solver_logs_step_count", &T::solver_logs_step_count)
1823 .def("solver_logs_reset_step_count", &T::solver_logs_reset_step_count)
1824 .def(
1825 "get_time",
1826 [](T &self) {
1827 return self.get_time();
1828 })
1829 .def(
1830 "get_dt",
1831 [](T &self) {
1832 return self.get_dt_sph();
1833 })
1834 .def(
1835 "get_last_cfl_dts",
1836 [](T &self) {
1837 py::dict ret;
1838 for (auto &[name, value] : self.solver.get_last_cfl_dts()) {
1839 ret[py::str(name)] = value;
1840 }
1841 return ret;
1842 },
1843 R"==(
1844 Get the last CFL timesteps stored in the synchronized edges.
1845
1846 Returns a dict keyed by synchronized edge name:
1847
1848 - ``"cfl_dt"``: the global CFL timestep of the last step (min over all CFL conditions).
1849 - ``"cfl_dt_<type>"`` (e.g. ``"cfl_dt_courant"``, ``"cfl_dt_force"``,
1850 ``"cfl_dt_sink_sink"``): the CFL timestep of each condition enabled in the solver
1851 config, only present when ``show_cfl_detail`` is enabled.
1852
1853 All values are 0 before the first step. A condition that was not evaluated during the
1854 last step (e.g. ``"cfl_dt_sink_sink"`` with no sinks) keeps its previous value.
1855)==")
1856 .def(
1857 "set_time",
1858 [](T &self, Tscal t) {
1859 return self.set_time(t);
1860 })
1861 .def(
1862 "set_next_dt",
1863 [](T &self, Tscal dt) {
1864 return self.set_next_dt(dt);
1865 })
1866 .def(
1867 "set_dt",
1868 [](T &self, f64 dt) {
1869 self.set_next_dt(dt);
1870 })
1871 .def(
1872 "set_cfl_multipler",
1873 [](T &self, Tscal lambda) {
1874 return self.set_cfl_multipler(lambda);
1875 },
1876 py::arg("lambda"))
1877 .def(
1878 "set_cfl_mult_stiffness",
1879 [](T &self, Tscal cstiff) {
1880 return self.solver.solver_config.set_cfl_mult_stiffness(cstiff);
1881 },
1882 py::arg("cstiff"))
1883 .def(
1884 "change_htolerance",
1885 [](T &self, Tscal in) {
1886 ON_RANK_0(shamlog_warn_ln(
1887 "SPH",
1888 ".change_htolerance(val) is deprecated,\n"
1889 " -> calling this is replaced internally by "
1890 ".change_htolerances(coarse=val, fine=min(val, 1.1))\n"
1891 " see: "
1892 "https://shamrock-code.github.io/Shamrock/sphinx/user_guide/sph/"
1893 "smoothing_length_tolerance.html"););
1894 self.change_htolerances(in, std::min(in, (Tscal) 1.1));
1895 })
1896 .def(
1897 "change_htolerances",
1898 [](T &self, Tscal coarse, Tscal fine) {
1899 self.change_htolerances(coarse, fine);
1900 },
1901 py::kw_only(),
1902 py::arg("coarse"),
1903 py::arg("fine"))
1904 .def(
1905 "make_analysis_sodtube",
1906 [](T &self,
1908 Tvec direction,
1909 Tscal time_val,
1910 Tscal x_ref,
1911 Tscal x_min,
1912 Tscal x_max) {
1913 return std::make_unique<TAnalysisSodTube>(
1914 self.ctx,
1915 self.solver.solver_config,
1916 self.solver.storage,
1917 sod,
1918 direction,
1919 time_val,
1920 x_ref,
1921 x_min,
1922 x_max);
1923 },
1924 py::arg("sod"),
1925 py::arg("direction"),
1926 py::arg("time_val"),
1927 py::arg("x_ref"),
1928 py::arg("x_min"),
1929 py::arg("x_max"))
1930 .def(
1931 "make_analysis_disc",
1932 [](T &self) {
1933 return std::make_unique<TAnalysisDisc>(
1934 self.ctx, self.solver.solver_config, self.solver.storage);
1935 })
1936 .def("load_from_dump", &T::load_from_dump)
1937 .def("dump", &T::dump)
1938 .def("get_setup", &T::get_setup)
1939 .def(
1940 "get_patch_transform",
1941 [](T &self) {
1942 PatchScheduler &sched = shambase::get_check_ref(self.ctx.sched);
1943 return sched.get_patch_transform<Tvec>();
1944 })
1945 .def("apply_momentum_offset", &T::apply_momentum_offset)
1946 .def("apply_position_offset", &T::apply_position_offset)
1947 .def(
1948 "add_timestep_callback",
1949 [](T &self,
1950 std::optional<std::function<void(void)>> step_begin_callback,
1951 std::optional<std::function<void(void)>> step_end_callback) {
1952 self.solver.timestep_callbacks.push_back(
1953 {std::move(step_begin_callback), std::move(step_end_callback)});
1954 },
1955 py::kw_only(),
1956 py::arg("step_begin") = std::nullopt,
1957 py::arg("step_end") = std::nullopt);
1958}
1959
1960template<class Tvec, template<class> class SPHKernel>
1961void add_analysisBarycenter_instance(py::module &m, const std::string &name_model) {
1962 using namespace shammodels::sph;
1963
1964 using Tscal = shambase::VecComponent<Tvec>;
1965
1966 using T = Model<Tvec, SPHKernel>;
1967
1968 py::class_<modules::AnalysisBarycenter<Tvec, SPHKernel>>(m, name_model.c_str())
1969 .def(py::init([](T &model) {
1970 return std::make_unique<modules::AnalysisBarycenter<Tvec, SPHKernel>>(model);
1971 }))
1972 .def("get_barycenter", [](modules::AnalysisBarycenter<Tvec, SPHKernel> &self) {
1973 auto result = self.get_barycenter();
1974 return py::make_tuple(result.barycenter, result.mass_disc);
1975 });
1976}
1977
1978template<class Tvec, template<class> class SPHKernel>
1979void add_analysisEnergyKinetic_instance(py::module &m, const std::string &name_model) {
1980 using namespace shammodels::sph;
1981
1982 using Tscal = shambase::VecComponent<Tvec>;
1983 using T = Model<Tvec, SPHKernel>;
1984
1985 py::class_<modules::AnalysisEnergyKinetic<Tvec, SPHKernel>>(m, name_model.c_str())
1986 .def(py::init([](T &model) {
1987 return std::make_unique<modules::AnalysisEnergyKinetic<Tvec, SPHKernel>>(model);
1988 }))
1989 .def("get_kinetic_energy", [](modules::AnalysisEnergyKinetic<Tvec, SPHKernel> &self) {
1990 return self.get_kinetic_energy();
1991 });
1992}
1993
1994template<class Tvec, template<class> class SPHKernel>
1995void add_analysisEnergyPotential_instance(py::module &m, const std::string &name_model) {
1996 using namespace shammodels::sph;
1997
1998 using Tscal = shambase::VecComponent<Tvec>;
1999 using T = Model<Tvec, SPHKernel>;
2000
2001 py::class_<modules::AnalysisEnergyPotential<Tvec, SPHKernel>>(m, name_model.c_str())
2002 .def(py::init([](T &model) {
2003 return std::make_unique<modules::AnalysisEnergyPotential<Tvec, SPHKernel>>(model);
2004 }))
2005 .def("get_potential_energy", [](modules::AnalysisEnergyPotential<Tvec, SPHKernel> &self) {
2006 return self.get_potential_energy();
2007 });
2008}
2009
2010template<class Tvec, template<class> class SPHKernel>
2011void add_analysisTotalMomentum_instance(py::module &m, const std::string &name_model) {
2012 using namespace shammodels::sph;
2013
2014 using Tscal = shambase::VecComponent<Tvec>;
2015 using T = Model<Tvec, SPHKernel>;
2016
2017 py::class_<modules::AnalysisTotalMomentum<Tvec, SPHKernel>>(m, name_model.c_str())
2018 .def(py::init([](T &model) {
2019 return std::make_unique<modules::AnalysisTotalMomentum<Tvec, SPHKernel>>(model);
2020 }))
2021 .def("get_total_momentum", [](modules::AnalysisTotalMomentum<Tvec, SPHKernel> &self) {
2022 return self.get_total_momentum();
2023 });
2024}
2025
2026template<class Tvec, template<class> class SPHKernel>
2027void add_analysisAngularMomentum_instance(py::module &m, const std::string &name_model) {
2028 using namespace shammodels::sph;
2029
2030 using Tscal = shambase::VecComponent<Tvec>;
2031 using T = Model<Tvec, SPHKernel>;
2032
2033 py::class_<modules::AnalysisAngularMomentum<Tvec, SPHKernel>>(m, name_model.c_str())
2034 .def(py::init([](T &model) {
2035 return std::make_unique<modules::AnalysisAngularMomentum<Tvec, SPHKernel>>(model);
2036 }))
2037 .def("get_angular_momentum", [](modules::AnalysisAngularMomentum<Tvec, SPHKernel> &self) {
2038 return self.get_angular_momentum();
2039 });
2040}
2041
2042template<class Tvec, template<class> class SPHKernel>
2043void add_analysisDustMass_instance(py::module &m, const std::string &name_model) {
2044 using namespace shammodels::sph;
2045
2046 using Tscal = shambase::VecComponent<Tvec>;
2047 using T = Model<Tvec, SPHKernel>;
2048
2049 py::class_<modules::AnalysisDustMass<Tvec, SPHKernel>>(m, name_model.c_str())
2050 .def(py::init([](T &model) {
2051 return std::make_unique<modules::AnalysisDustMass<Tvec, SPHKernel>>(model);
2052 }))
2053 .def("get_dust_mass", [](modules::AnalysisDustMass<Tvec, SPHKernel> &self) {
2054 return self.get_dust_mass();
2055 });
2056}
2057
2058using namespace shammodels::sph;
2059
2060template<class Analysis, typename Tvec, template<class> class SPHKernel>
2061auto analysis_impl(shammodels::sph::Model<Tvec, SPHKernel> &model) -> Analysis {
2062 return Analysis(model);
2063}
2064
2065template<template<class, template<class> class> class Analysis>
2066void register_analysis_impl_for_each_kernel(py::module &msph, const char *name_class) {
2067 using namespace shammodels::sph;
2068
2069 using SPHModel_f64_3_M4 = shammodels::sph::Model<f64_3, shammath::M4>;
2070 using SPHModel_f64_3_M6 = shammodels::sph::Model<f64_3, shammath::M6>;
2071 using SPHModel_f64_3_M8 = shammodels::sph::Model<f64_3, shammath::M8>;
2072
2073 using SPHModel_f64_3_C2 = shammodels::sph::Model<f64_3, shammath::C2>;
2074 using SPHModel_f64_3_C4 = shammodels::sph::Model<f64_3, shammath::C4>;
2075 using SPHModel_f64_3_C6 = shammodels::sph::Model<f64_3, shammath::C6>;
2076
2077 msph.def(
2078 name_class,
2079 [](SPHModel_f64_3_M4 &model) {
2080 return analysis_impl<Analysis<f64_3, shammath::M4>>(model);
2081 },
2082 py::kw_only(),
2083 py::arg("model"));
2084
2085 msph.def(
2086 name_class,
2087 [](SPHModel_f64_3_M6 &model) {
2088 return analysis_impl<Analysis<f64_3, shammath::M6>>(model);
2089 },
2090 py::kw_only(),
2091 py::arg("model"));
2092
2093 msph.def(
2094 name_class,
2095 [](SPHModel_f64_3_M8 &model) {
2096 return analysis_impl<Analysis<f64_3, shammath::M8>>(model);
2097 },
2098 py::kw_only(),
2099 py::arg("model"));
2100
2101 msph.def(
2102 name_class,
2103 [](SPHModel_f64_3_C2 &model) {
2104 return analysis_impl<Analysis<f64_3, shammath::C2>>(model);
2105 },
2106 py::kw_only(),
2107 py::arg("model"));
2108
2109 msph.def(
2110 name_class,
2111 [](SPHModel_f64_3_C4 &model) {
2112 return analysis_impl<Analysis<f64_3, shammath::C4>>(model);
2113 },
2114 py::kw_only(),
2115 py::arg("model"));
2116
2117 msph.def(
2118 name_class,
2119 [](SPHModel_f64_3_C6 &model) {
2120 return analysis_impl<Analysis<f64_3, shammath::C6>>(model);
2121 },
2122 py::kw_only(),
2123 py::arg("model"));
2124}
2125
2127 auto &m = root_module;
2128
2129 py::module msph = m.def_submodule("model_sph", "Shamrock sph solver");
2130
2131 py::class_<shamrock::PatchDataLazyGetter>(m, "PatchDataLazyGetter")
2132 .def("__getitem__", &shamrock::PatchDataLazyGetter::get_item);
2133
2134 py::class_<EvolveUntilResults>(m, "EvolveUntilResults")
2135 .def_readwrite("reach_target_time", &EvolveUntilResults::reach_target_time)
2136 .def_readwrite("reach_niter_max", &EvolveUntilResults::reach_niter_max)
2137 .def_readwrite("reach_max_walltime", &EvolveUntilResults::reach_max_walltime)
2138 .def_readwrite("iter_count", &EvolveUntilResults::iter_count)
2139 .def("__repr__", [](const EvolveUntilResults &self) {
2140 return sham::format(
2141 "EvolveUntilResults(reach_target_time={}, reach_niter_max={}, "
2142 "reach_max_walltime={}, iter_count={})",
2143 self.reach_target_time,
2144 self.reach_niter_max,
2145 self.reach_max_walltime,
2146 self.iter_count);
2147 });
2148
2149 using namespace shammodels::sph;
2150
2151 add_instance<f64_3, shammath::M4>(msph, "SPHModel_f64_3_M4_SolverConfig", "SPHModel_f64_3_M4");
2152 add_instance<f64_3, shammath::M6>(msph, "SPHModel_f64_3_M6_SolverConfig", "SPHModel_f64_3_M6");
2153 add_instance<f64_3, shammath::M8>(msph, "SPHModel_f64_3_M8_SolverConfig", "SPHModel_f64_3_M8");
2154
2155 add_instance<f64_3, shammath::C2>(msph, "SPHModel_f64_3_C2_SolverConfig", "SPHModel_f64_3_C2");
2156 add_instance<f64_3, shammath::C4>(msph, "SPHModel_f64_3_C4_SolverConfig", "SPHModel_f64_3_C4");
2157 add_instance<f64_3, shammath::C6>(msph, "SPHModel_f64_3_C6_SolverConfig", "SPHModel_f64_3_C6");
2158
2159 using VariantSPHModelBind = std::variant<
2160 std::unique_ptr<Model<f64_3, shammath::M4>>,
2161 std::unique_ptr<Model<f64_3, shammath::M6>>,
2162 std::unique_ptr<Model<f64_3, shammath::M8>>,
2163 std::unique_ptr<Model<f64_3, shammath::C2>>,
2164 std::unique_ptr<Model<f64_3, shammath::C4>>,
2165 std::unique_ptr<Model<f64_3, shammath::C6>>>;
2166
2167 m.def(
2168 "get_Model_SPH",
2169 [](ShamrockCtx &ctx,
2170 const std::string &vector_type,
2171 const std::string &kernel) -> VariantSPHModelBind {
2172 VariantSPHModelBind ret;
2173
2174 if (vector_type == "f64_3" && kernel == "M4") {
2175 ret = std::make_unique<Model<f64_3, shammath::M4>>(ctx);
2176 } else if (vector_type == "f64_3" && kernel == "M6") {
2177 ret = std::make_unique<Model<f64_3, shammath::M6>>(ctx);
2178 } else if (vector_type == "f64_3" && kernel == "M8") {
2179 ret = std::make_unique<Model<f64_3, shammath::M8>>(ctx);
2180 } else if (vector_type == "f64_3" && kernel == "C2") {
2181 ret = std::make_unique<Model<f64_3, shammath::C2>>(ctx);
2182 } else if (vector_type == "f64_3" && kernel == "C4") {
2183 ret = std::make_unique<Model<f64_3, shammath::C4>>(ctx);
2184 } else if (vector_type == "f64_3" && kernel == "C6") {
2185 ret = std::make_unique<Model<f64_3, shammath::C6>>(ctx);
2186 } else {
2188 "unknown combination of representation and kernel");
2189 }
2190
2191 return ret;
2192 },
2193 py::kw_only(),
2194 py::arg("context"),
2195 py::arg("vector_type"),
2196 py::arg("sph_kernel"));
2197
2198 py::class_<
2200 std::shared_ptr<shammodels::sph::modules::ISPHSetupNode>>(msph, "ISPHSetupNode")
2201 .def("get_dot", [](std::shared_ptr<shammodels::sph::modules::ISPHSetupNode> &self) {
2202 return self->get_dot();
2203 });
2204
2205 py::class_<shammodels::sph::TimestepLog>(msph, "TimestepLog")
2206 .def(py::init<>())
2207 .def_readwrite("rank", &shammodels::sph::TimestepLog::rank)
2208 .def_readwrite("rate", &shammodels::sph::TimestepLog::rate)
2209 .def_readwrite("npart", &shammodels::sph::TimestepLog::npart)
2210 .def_readwrite("tcompute", &shammodels::sph::TimestepLog::tcompute)
2211 .def("rate_sum", &shammodels::sph::TimestepLog::rate_sum)
2212 .def("npart_sum", &shammodels::sph::TimestepLog::npart_sum);
2213
2214 add_analysisBarycenter_instance<f64_3, shammath::M4>(msph, "AnalysisBarycenter_f64_3_M4");
2215 add_analysisBarycenter_instance<f64_3, shammath::M6>(msph, "AnalysisBarycenter_f64_3_M6");
2216 add_analysisBarycenter_instance<f64_3, shammath::M8>(msph, "AnalysisBarycenter_f64_3_M8");
2217
2218 add_analysisBarycenter_instance<f64_3, shammath::C2>(msph, "AnalysisBarycenter_f64_3_C2");
2219 add_analysisBarycenter_instance<f64_3, shammath::C4>(msph, "AnalysisBarycenter_f64_3_C4");
2220 add_analysisBarycenter_instance<f64_3, shammath::C6>(msph, "AnalysisBarycenter_f64_3_C6");
2221
2222 add_analysisEnergyKinetic_instance<f64_3, shammath::M4>(msph, "AnalysisEnergyKinetic_f64_3_M4");
2223 add_analysisEnergyKinetic_instance<f64_3, shammath::M6>(msph, "AnalysisEnergyKinetic_f64_3_M6");
2224 add_analysisEnergyKinetic_instance<f64_3, shammath::M8>(msph, "AnalysisEnergyKinetic_f64_3_M8");
2225
2226 add_analysisEnergyKinetic_instance<f64_3, shammath::C2>(msph, "AnalysisEnergyKinetic_f64_3_C2");
2227 add_analysisEnergyKinetic_instance<f64_3, shammath::C4>(msph, "AnalysisEnergyKinetic_f64_3_C4");
2228 add_analysisEnergyKinetic_instance<f64_3, shammath::C6>(msph, "AnalysisEnergyKinetic_f64_3_C6");
2229
2230 add_analysisEnergyPotential_instance<f64_3, shammath::M4>(
2231 msph, "AnalysisEnergyPotential_f64_3_M4");
2232 add_analysisEnergyPotential_instance<f64_3, shammath::M6>(
2233 msph, "AnalysisEnergyPotential_f64_3_M6");
2234 add_analysisEnergyPotential_instance<f64_3, shammath::M8>(
2235 msph, "AnalysisEnergyPotential_f64_3_M8");
2236
2237 add_analysisEnergyPotential_instance<f64_3, shammath::C2>(
2238 msph, "AnalysisEnergyPotential_f64_3_C2");
2239 add_analysisEnergyPotential_instance<f64_3, shammath::C4>(
2240 msph, "AnalysisEnergyPotential_f64_3_C4");
2241 add_analysisEnergyPotential_instance<f64_3, shammath::C6>(
2242 msph, "AnalysisEnergyPotential_f64_3_C6");
2243
2244 add_analysisTotalMomentum_instance<f64_3, shammath::M4>(msph, "AnalysisTotalMomentum_f64_3_M4");
2245 add_analysisTotalMomentum_instance<f64_3, shammath::M6>(msph, "AnalysisTotalMomentum_f64_3_M6");
2246 add_analysisTotalMomentum_instance<f64_3, shammath::M8>(msph, "AnalysisTotalMomentum_f64_3_M8");
2247
2248 add_analysisTotalMomentum_instance<f64_3, shammath::C2>(msph, "AnalysisTotalMomentum_f64_3_C2");
2249 add_analysisTotalMomentum_instance<f64_3, shammath::C4>(msph, "AnalysisTotalMomentum_f64_3_C4");
2250 add_analysisTotalMomentum_instance<f64_3, shammath::C6>(msph, "AnalysisTotalMomentum_f64_3_C6");
2251
2252 add_analysisAngularMomentum_instance<f64_3, shammath::M4>(
2253 msph, "AnalysisAngularMomentum_f64_3_M4");
2254 add_analysisAngularMomentum_instance<f64_3, shammath::M6>(
2255 msph, "AnalysisAngularMomentum_f64_3_M6");
2256 add_analysisAngularMomentum_instance<f64_3, shammath::M8>(
2257 msph, "AnalysisAngularMomentum_f64_3_M8");
2258
2259 add_analysisAngularMomentum_instance<f64_3, shammath::C2>(
2260 msph, "AnalysisAngularMomentum_f64_3_C2");
2261 add_analysisAngularMomentum_instance<f64_3, shammath::C4>(
2262 msph, "AnalysisAngularMomentum_f64_3_C4");
2263 add_analysisAngularMomentum_instance<f64_3, shammath::C6>(
2264 msph, "AnalysisAngularMomentum_f64_3_C6");
2265
2266 register_analysis_impl_for_each_kernel<modules::AnalysisBarycenter>(msph, "analysisBarycenter");
2267 register_analysis_impl_for_each_kernel<modules::AnalysisEnergyKinetic>(
2268 msph, "analysisEnergyKinetic");
2269 register_analysis_impl_for_each_kernel<modules::AnalysisEnergyPotential>(
2270 msph, "analysisEnergyPotential");
2271 register_analysis_impl_for_each_kernel<modules::AnalysisTotalMomentum>(
2272 msph, "analysisTotalMomentum");
2273 register_analysis_impl_for_each_kernel<modules::AnalysisAngularMomentum>(
2274 msph, "analysisAngularMomentum");
2275
2276 add_analysisDustMass_instance<f64_3, shammath::M4>(msph, "AnalysisDustMass_f64_3_M4");
2277 add_analysisDustMass_instance<f64_3, shammath::M6>(msph, "AnalysisDustMass_f64_3_M6");
2278 add_analysisDustMass_instance<f64_3, shammath::M8>(msph, "AnalysisDustMass_f64_3_M8");
2279
2280 add_analysisDustMass_instance<f64_3, shammath::C2>(msph, "AnalysisDustMass_f64_3_C2");
2281 add_analysisDustMass_instance<f64_3, shammath::C4>(msph, "AnalysisDustMass_f64_3_C4");
2282 add_analysisDustMass_instance<f64_3, shammath::C6>(msph, "AnalysisDustMass_f64_3_C6");
2283
2284 register_analysis_impl_for_each_kernel<modules::AnalysisDustMass>(msph, "analysisDustMass");
2285}
AnalysisAngularMomentum class.
AnalysisBarycenter class with one method AnalysisBarycenter.get_barycenter().
AnalysisDustMass class.
AnalysisEnergyKinetic class with one method AnalysisEnergyKinetic.get_kinetic_energy().
AnalysisEnergyPotential class with one method AnalysisEnergyPotential.get_potential_energy().
AnalysisTotalMomentum class with one method AnalysisTotalMomentum.get_total_momentum().
Compute the gravitational wave quadrupole. Based on Toscani et. al. 2021.
MPI scheduler.
double f64
Alias for double.
std::uint32_t u32
32 bit unsigned integer
std::uint64_t u64
64 bit unsigned integer
std::uint16_t u16
16 bit unsigned integer
std::int32_t i32
32 bit integer
The MPI scheduler.
The shamrock SPH model.
Definition Model.hpp:56
This class is an interface that all SPH setup nodes must implement. It describe an operation associat...
Lazily fetches a single named field of a patch as a numpy array, on demand.
constexpr Unit k
Boltzmann constant.
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.
i32 world_rank()
Gives the rank of the current process in the MPI communicator.
Definition worldInfo.cpp:41
std::shared_ptr< ISPHSetupNode > SetupNodePtr
Alias for a shared pointer to an ISPHSetupNode.
namespace for the sph model
std::vector< SinkParticle< Tvec > > to_sink_particles(const SinkEdges< Tvec > &e)
Build an AoS sink list from the current SoA edges (Python API / dump helpers).
SinkEdges< Tvec > get_sink_edges(shamrock::solvergraph::SolverGraphSerializable &sync)
Fetch mutable references to the sink SoA synchronized edges.
bool has_sink_accreted_dust_mass(shamrock::solvergraph::SolverGraphSerializable &sync)
Whether the per species accreted dust mass sink edge is registered.
Pybind11 include and definitions.
#define ON_PYTHON_INIT
Register a Python module init function using static initialization.
void warn_ln(std::string module_name, Types... var2)
Prints a log message with multiple arguments followed by a newline.
Definition logs.hpp:132
Utilities to convert JSON objects to Python objects and vice versa. TODO: try to convert directly wit...
Helpers to access SPH sink particles stored as SoA synchronized data edges.
sph kernels
Ray representation for intersection testing.
Definition AABB.hpp:34
Ring ray representation for intersection testing.
Definition AABB.hpp:67
Class representing a Phantom dump file.
Functions related to the MPI communicator.
#define ON_RANK_0(x)
Macro to execute code only on rank 0.
Definition worldInfo.hpp:73