BioCMAMC-ST
simulation.hpp
1#ifndef __SIMULATIONS_UNIT_HPP__
2#define __SIMULATIONS_UNIT_HPP__
3
4#include "simulation/kernels/model_kernel.hpp"
5#include <Kokkos_Core.hpp>
6#include <Kokkos_ScatterView.hpp>
7#include <biocma_cst_config.hpp>
8#include <cassert>
9#include <cma_utils/iteration_state.hpp>
10#include <common/common.hpp>
11#include <common/logger.hpp>
12#include <cstddef>
13#include <cstdint>
14#include <mc/domain.hpp>
15#include <mc/events.hpp>
16#include <mc/prng/prng.hpp>
17#include <mc/unit.hpp>
18#include <memory>
19#include <optional>
20#include <simulation/alias.hpp>
21#include <simulation/feed_descriptor.hpp>
22#include <simulation/kernels/kernels.hpp>
23#include <simulation/mass_transfer.hpp>
24#include <simulation/probe.hpp>
25#include <simulation/scalar_initializer.hpp>
26
27// TODO Clean
28static constexpr size_t trigger_const_particle_number = 1e6;
29static constexpr bool f_reaction = true; // FIXME
30
31namespace CmaUtils
32{
34} // namespace CmaUtils
35
41namespace Simulation
42{
43
45 {
46 std::size_t n_species{};
47 std::size_t n_compartment{};
48
49 template <class Archive> void serialize(Archive& archive)
50 {
51 archive(n_species, n_compartment);
52 }
53 };
54
55 class ScalarSimulation;
56
58 {
59 public:
60 SimulationUnit(std::unique_ptr<MC::MonteCarloUnit>&& _unit,
61 const ScalarInitializer& scalar_init,
62 std::optional<Feed::SimulationFeed> _feed = std::nullopt);
63
65
66 SimulationUnit(SimulationUnit&& other) noexcept;
67 SimulationUnit(const SimulationUnit& other) = delete;
70
71 std::unique_ptr<MC::MonteCarloUnit> mc_unit; // NOLINT
72
73 [[nodiscard]] const Simulation::Feed::SimulationFeed& get_feed() const;
75
76 // std::span<double> getContributionData_mut();
77
78 // Setters
79 void setProbes(ProbeAutogeneratedBuffer&& _probes);
81 void setLogger(std::shared_ptr<IO::Logger>);
82
83 // Getters
84 [[nodiscard]] double& get_start_time_mut();
85 [[nodiscard]] double& get_end_time_mut();
86 [[nodiscard]] const CmaUtils::IterationState& getState() const;
87 [[nodiscard]] Dimensions getDimensions() const noexcept;
88 [[nodiscard]] std::span<double> getCliqData() const;
89 [[nodiscard]] std::optional<std::span<const double>> getCgasData() const;
90 [[nodiscard]] std::span<const double> getContributionData() const;
91 [[nodiscard]] bool two_phase_flow() const;
92 [[nodiscard]] std::optional<std::span<const double>> getMTRData() const;
93 [[nodiscard]] std::size_t dead_counter() const;
94 std::span<double> getContributionData_mut();
95
96 // Simulation methods
97
98 void cycleProcess(auto&& container, double d_t, auto& _functors);
99 void step(double d_t) const;
100 void reduceContribs(std::span<const double> data, size_t n_rank) const;
101
102 //[[deprecated("perf:not useful")]] void
103 // reduceContribs_per_rank(std::span<const double> data) const;
104 //
105 void clearContribution() const noexcept;
106 auto init_functor(double d_t, auto&& container);
107 void update_feed(double t, double d_t, bool update_scalar = true) noexcept;
108 void update(CmaUtils::IterationState&& new_state);
109
110 // Memory management
111 void clear_mc();
112 void reset();
114
115 template <typename Space, ModelType Model>
116 KernelInline::Functors<Space, Model>
117 init_functors(MC::ParticlesContainer<Model> container);
118
119 private:
120 void setVolumes() const;
121 void setLiquidFlow(CmaUtils::PreCalculatedHydroState* _flows_l);
122 void setGasFlow(CmaUtils::PreCalculatedHydroState* _flows_g);
123
124 [[nodiscard]] MC::KernelConcentrationType getkernel_concentration() const;
125
126 MC::ContributionView contribs_scatter;
128
129 // Attributes
132 // ProbeAutogeneratedBuffer probes;
133 Simulation::Feed::SimulationFeed feed;
134
135 CmaUtils::IterationState state;
139 0.; // Not used within calculation, only for export purposes
140 double end_time{}; // Not used within calculation, only for export purposes
141
142 void scatter_contribute();
144 // Bounce methods to pimpl
148 [[nodiscard]] kernelContribution get_kernel_contribution() const;
149
150 void post_init_concentration(const ScalarInitializer& scalar_init);
151 void post_init_concentration_functor(const ScalarInitializer& scalar_init);
152 void post_init_concentration_file(const ScalarInitializer& scalar_init);
153
154 std::shared_ptr<ScalarSimulation> liquid_scalar;
155 std::shared_ptr<ScalarSimulation> gas_scalar;
157 mt_model; // TODO add default null value (no model)
159
160 std::shared_ptr<IO::Logger> logger;
161
162 template <typename Space, ModelType Model>
163 void post_cycle(
165 std::size_t n_particle,
168 reducer_type);
169
170 template <ModelType Model>
172 double d_t,
173 auto& functors);
174 };
175
176 template <ModelType Model>
178 double d_t,
179 auto& functors)
180 {
181 this->contribs_scatter.reset();
182 this->move_info.cumulative_probability = get_kernel_cumulative_proba();
183 this->move_info.diag_transition = get_kernel_diagonal();
184 this->move_info.neighbors = mc_unit->domain.getNeighbors();
185
186 //TODO map through flowmap and find max flow, then true if max>0
187 bool enable_move = move_info.liquid_volume.size() > 1;
188 bool enable_leave = move_info.leaving_flow.size() != 0;
189
190 // FIXME: cycle_kernel: need to update container because we change:
191 // n_used_element counter which is size_t outside of kernel. As functor owns
192 // a copy of container this counter is not update between iterations.
193 // 1. Use n_used_element as a reference counter type
194 // 2. Manually update counter in update function (dirty way)
195
196 functors.cycle_kernel.update(d_t, container);
197
198 // TODO: Why need to update all views (where did we lost the refcount ? )
199 functors.move_kernel.update(d_t,
200 container.n_particles(),
201 this->move_info,
202 container.position,
203 container.status,
204 container.ages,
205 enable_move,
206 enable_leave);
207 }
208
209 template <typename Space, ModelType Model>
212 {
213 auto local_rng = mc_unit->rng;
214 auto events = mc_unit->events;
215 auto reaction_functor =
217 local_rng.random_pool,
220 events);
221 auto move_functor =
222 Simulation ::KernelInline ::MoveFunctor(container.position,
223 container.status,
224 move_info,
225 local_rng.random_pool,
226 events,
227 probes[ProbeType ::LeavingTime],
228 container.ages);
229
230 return KernelInline::Functors<Space, Model>(std::move(reaction_functor),
231 std::move(move_functor));
232 }
233
234 void
235 SimulationUnit::cycleProcess(auto&& container, double d_t, auto& functors)
236 {
237
238 PROFILE_SECTION("cycleProcess")
239
240 using cycle_functor_type = decltype(functors.cycle_kernel);
241 using CurrentModel =
242 typename std::remove_reference<decltype(container)>::type::UsedModel;
243 const size_t n_particle = container.n_particles();
244 if (n_particle == 0)
245 {
246 return;
247 }
248
249 pre_cycle(container, d_t, functors);
250
251 if (functors.move_kernel.need_launch())
252 {
253 constexpr bool is_reduce = true;
254 const auto _policy =
255 MC::get_policy(functors.move_kernel, n_particle, is_reduce);
256 Kokkos ::parallel_reduce(
257 "cycle_move", _policy, functors.move_kernel, functors.move_reducer);
258 }
259
260 if (f_reaction)
261 {
262 constexpr bool is_reduce = true;
263 const auto _policy =
265 functors.cycle_kernel, n_particle, is_reduce);
266 const auto scatter_policy =
268 functors.cycle_kernel, n_particle, false);
269
270 Kokkos::parallel_reduce(
271 "cycle_model",
272 _policy,
273 functors.cycle_kernel,
274 KernelInline::CycleReducer<ComputeSpace>(functors.cycle_reducer));
275 Kokkos::fence(); // TODO needed ?
276 Kokkos::parallel_for(
277 "cycle_scatter", scatter_policy, functors.cycle_kernel);
278 }
279
281 container, n_particle, functors.move_reducer, functors.cycle_reducer);
282 }
283
284 template <typename Space, ModelType Model>
287 std::size_t n_particle,
290 reducer_type)
291 {
292 const auto threshold = std::max(
294 static_cast<uint64_t>(static_cast<double>(n_particle) *
295 AutoGenerated::dead_particle_ratio_threshold));
296
297 Kokkos::fence();
298
299 this->scatter_contribute();
300
301 const auto host_red =
302 Kokkos::create_mirror_view_and_copy(HostSpace(), reducer_type)();
303
304 const auto host_out_counter =
305 Kokkos::create_mirror_view_and_copy(HostSpace(), out_total)();
306
308 host_out_counter, host_red.dead_total, threshold);
309
310 container.merge_buffer();
311
312 if (host_red.waiting_allocation_particle != 0)
313 {
314 if (logger)
315 {
316 logger->alert("Simulation",
317 "Overflow of particle not implemented yet (ignore "
318 "_waiting_allocation_particle)");
319 }
320 }
321
323 }
324
325} // namespace Simulation
326
327#endif //__SIMULATIONS_UNIT_HPP__
Structure to store hydrodynamic properties from a compartment mesh.
Definition cache_hydro_state.hpp:56
Main owning object for Monte-Carlo particles.
Definition particles_container.hpp:155
KOKKOS_INLINE_FUNCTION std::size_t n_particles() const
Gets the number of particles in the container.
Definition particles_container.hpp:267
std::size_t update_and_clean_dead(std::size_t out, std::size_t dead, std::size_t threshold)
Definition particles_container.hpp:329
void merge_buffer()
Definition particles_container.hpp:359
MC::ParticlePositions position
Definition particles_container.hpp:184
ParticleAges ages
Definition particles_container.hpp:187
MC::ParticleStatus status
Definition particles_container.hpp:185
Definition feed_descriptor.hpp:108
Definition model_kernel.hpp:37
Definition mass_transfer.hpp:54
ProbeAutogeneratedBuffer & get_probes()
Definition simulation.getset.cpp:152
const Simulation::Feed::SimulationFeed & get_feed() const
Definition simulation.getset.cpp:69
auto init_functor(double d_t, auto &&container)
MassTransfer::MassTransferModel mt_model
Definition simulation.hpp:157
double & get_start_time_mut()
Definition simulation.getset.cpp:60
SimulationUnit & operator=(const SimulationUnit &rhs)=delete
void clear_mc()
Definition simulation.cpp:159
Simulation::Feed::SimulationFeed feed
Definition simulation.hpp:133
double starting_time
Definition simulation.hpp:138
std::span< const double > getContributionData() const
Definition simulation.getset.cpp:115
SimulationUnit(std::unique_ptr< MC::MonteCarloUnit > &&_unit, const ScalarInitializer &scalar_init, std::optional< Feed::SimulationFeed > _feed=std::nullopt)
Definition simulation.cpp:51
std::span< double > getCliqData() const
Definition simulation.getset.cpp:125
void setLogger(std::shared_ptr< IO::Logger >)
Definition simulation.getset.cpp:74
std::span< double > getContributionData_mut()
Definition simulation.getset.cpp:120
MC::KernelConcentrationType getkernel_concentration() const
Definition simulation.getset.cpp:110
bool const_number_simulation
Definition simulation.hpp:136
void post_init_concentration_file(const ScalarInitializer &scalar_init)
Definition simulation.cpp:125
void post_init_compartments()
Definition simulation.cpp:237
MapProbes probes
Definition simulation.hpp:127
void setLiquidFlow(CmaUtils::PreCalculatedHydroState *_flows_l)
uint64_t minimum_dead_particle_removal
Definition simulation.hpp:131
KernelInline::MoveInfo< ComputeSpace > move_info
Definition simulation.hpp:158
std::unique_ptr< MC::MonteCarloUnit > mc_unit
Definition simulation.hpp:71
void setGasFlow(CmaUtils::PreCalculatedHydroState *_flows_g)
void reduceContribs(std::span< const double > data, size_t n_rank) const
Definition simulation.model.cpp:31
void update_feed(double t, double d_t, bool update_scalar=true) noexcept
Definition simulation.model.cpp:55
void cycleProcess(auto &&container, double d_t, auto &_functors)
Definition simulation.hpp:235
Dimensions getDimensions() const noexcept
Definition simulation.getset.cpp:140
DiagonalView< ComputeSpace > get_kernel_diagonal() const
Definition simulation.getset.cpp:50
void setProbes(ProbeAutogeneratedBuffer &&_probes)
Definition simulation.getset.cpp:88
bool two_phase_flow() const
Definition simulation.getset.cpp:45
SimulationUnit(const SimulationUnit &other)=delete
std::shared_ptr< ScalarSimulation > gas_scalar
Definition simulation.hpp:155
void setMtrModel(MassTransfer::Type::MtrTypeVariant &&variant)
Definition simulation.getset.cpp:79
std::optional< std::span< const double > > getMTRData() const
Definition simulation.getset.cpp:147
double & get_end_time_mut()
Definition simulation.getset.cpp:64
double end_time
Definition simulation.hpp:140
kernelContribution get_kernel_contribution() const
Definition simulation.getset.cpp:55
void reset()
Definition simulation.cpp:164
SimulationUnit(SimulationUnit &&other) noexcept
KernelInline::Functors< Space, Model > init_functors(MC::ParticlesContainer< Model > container)
Definition simulation.hpp:211
SimulationUnit & operator=(SimulationUnit &&rhs)=delete
CmaUtils::IterationState state
Definition simulation.hpp:135
bool is_two_phase_flow
Definition simulation.hpp:137
std::size_t internal_counter_dead
Definition simulation.hpp:130
std::size_t dead_counter() const
Definition simulation.getset.cpp:40
std::optional< std::span< const double > > getCgasData() const
Definition simulation.getset.cpp:131
void set_kernel_contribs_to_host()
Definition simulation.getset.cpp:104
CumulativeProbabilityView< ComputeSpace > get_kernel_cumulative_proba() const
Definition simulation.getset.cpp:94
void post_cycle(MC::ParticlesContainer< Model > &container, std::size_t n_particle, KernelInline::Functors< Space, Model >::move_reducer_view_type out_total, KernelInline::Functors< Space, Model >::cycle_reducer_view_type reducer_type)
Definition simulation.hpp:285
std::shared_ptr< ScalarSimulation > liquid_scalar
Definition simulation.hpp:154
void post_init_concentration_functor(const ScalarInitializer &scalar_init)
Definition simulation.cpp:171
void post_init_concentration(const ScalarInitializer &scalar_init)
Definition simulation.cpp:201
void update(CmaUtils::IterationState &&new_state)
Definition simulation.cpp:83
void pre_cycle(MC::ParticlesContainer< Model > &container, double d_t, auto &functors)
Definition simulation.hpp:177
const CmaUtils::IterationState & getState() const
Definition simulation.getset.cpp:157
void scatter_contribute()
Definition simulation.cpp:90
std::shared_ptr< IO::Logger > logger
Definition simulation.hpp:160
void setVolumes() const
Definition simulation.cpp:97
void clearContribution() const noexcept
Definition simulation.model.cpp:44
void step(double d_t) const
Definition simulation.model.cpp:165
MC::ContributionView contribs_scatter
Definition simulation.hpp:126
Model type.
Definition traits.hpp:147
Namespace to handle algorithms and structures related to reading compartment mesh.
Definition host_specific.hpp:18
Namespace that contains classes and structures related to Monte Carlo (MC) simulations.
Definition alias.hpp:11
Kokkos::TeamPolicy< ComputeSpace, Tag > get_policy(FunctorType &f, std::size_t range, bool reduce=false)
Definition unit.hpp:39
Definition feed_descriptor.hpp:33
Definition kernels.hpp:8
std::variant< FlowmapTurbulence, FixedKla, FlowmapKla > MtrTypeVariant
Definition mass_transfer.hpp:39
Namespace that contains classes and structures related to simulation handling.
Definition host_specific.hpp:13
Kokkos::View< double *, Kokkos::LayoutLeft, ExecSpace, Kokkos::MemoryTraits< Kokkos::RandomAccess > > DiagonalView
Definition alias.hpp:14
Probes< AutoGenerated::probe_buffer_size > ProbeAutogeneratedBuffer
Definition probe.hpp:61
Kokkos::View< const double **, Kokkos::LayoutRight, Space, Kokkos::MemoryTraits< Kokkos::RandomAccess > > CumulativeProbabilityView
Definition alias.hpp:20
std::unordered_map< ProbeType, ProbeAutogeneratedBuffer > MapProbes
Definition probe.hpp:63
Structure to store information about the reactor state during simulation.
Definition iteration_state.hpp:25
Definition simulation.hpp:45
std::size_t n_species
Definition simulation.hpp:46
std::size_t n_compartment
Definition simulation.hpp:47
void serialize(Archive &archive)
Definition simulation.hpp:49
Definition model_kernel.hpp:100
Definition kernels.hpp:11
Kokkos::View< std::size_t, Space > move_reducer_view_type
Definition kernels.hpp:16
KernelInline::CycleReducer< Space >::result_view_type cycle_reducer_view_type
Definition kernels.hpp:14
Definition move_kernel.hpp:28
Definition scalar_initializer.hpp:28