ESPResSo
Extensible Simulation Package for Research on Soft Matter Systems
Loading...
Searching...
No Matches
EKSpecies.cpp
Go to the documentation of this file.
1/*
2 * Copyright (C) 2021-2026 The ESPResSo project
3 *
4 * This file is part of ESPResSo.
5 *
6 * ESPResSo is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * ESPResSo is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 */
19#include <config/config.hpp>
20
21#ifdef ESPRESSO_WALBERLA
22
23#include "EKSpecies.hpp"
26#include "errorhandling.hpp"
27
29
33
34#include <boost/mpi.hpp>
35#include <boost/mpi/collectives/all_reduce.hpp>
36#include <boost/mpi/collectives/broadcast.hpp>
37
38#include <algorithm>
39#include <cassert>
40#include <filesystem>
41#include <functional>
42#include <memory>
43#include <optional>
44#include <sstream>
45#include <stdexcept>
46#include <string>
47#include <vector>
48
50
51std::unordered_map<std::string, int> const EKVTKHandle::obs_map = {
52 {"density", static_cast<int>(EKOutputVTK::density)},
53 {"flux", static_cast<int>(EKOutputVTK::flux)},
54};
55
57 VariantMap const &parameters) {
58 if (method == "update_flux_boundary_from_shape") {
61 std::ranges::for_each(values, [this](double &v) { v *= m_conv_flux; });
62
63 m_instance->update_flux_boundary_from_shape(
64 get_value<std::vector<int>>(parameters, "raster"), values);
65 return {};
66 }
67 if (method == "update_density_boundary_from_shape") {
69 std::ranges::for_each(values, [this](double &v) { v *= m_conv_density; });
70 m_instance->update_density_boundary_from_shape(
71 get_value<std::vector<int>>(parameters, "raster"), values);
72 return {};
73 }
74 if (method == "clear_flux_boundaries") {
75 m_instance->clear_flux_boundaries();
76 return {};
77 }
78 if (method == "clear_density_boundaries") {
79 m_instance->clear_density_boundaries();
80 return {};
81 }
82 if (method == "save_checkpoint") {
83 auto const path = get_value<std::filesystem::path>(parameters, "path");
84 auto const mode = get_value<int>(parameters, "mode");
85 save_checkpoint(path, mode);
86 return {};
87 }
88 if (method == "load_checkpoint") {
89 auto const path = get_value<std::filesystem::path>(parameters, "path");
90 auto const mode = get_value<int>(parameters, "mode");
91 load_checkpoint(path, mode);
92 return {};
93 }
95}
96
98 auto const diffusion = get_value<double>(params, "diffusion");
99 auto const ext_efield = get_value<Utils::Vector3d>(params, "ext_efield");
100 auto const density = get_value<double>(params, "density");
101 auto const kT = get_value<double>(params, "kT");
102 auto const gpu = get_value_or(params, "gpu", false);
105 auto const ek_density = density * m_conv_density;
106 auto const ek_kT = kT * m_conv_energy;
107 auto *make_new_instance = &::walberla::new_ek_walberla_cpu;
108 if (gpu) {
109 std::vector<std::string> required_features;
110 required_features.emplace_back("CUDA");
112#ifdef ESPRESSO_CUDA
113 make_new_instance = &::walberla::new_ek_walberla_gpu;
114#endif
115 }
116 m_instance = make_new_instance(
117 m_lattice->lattice(), ek_diffusion, ek_kT,
118 get_value<double>(params, "valency"), ek_ext_efield, ek_density,
119 get_value<bool>(params, "advection"),
120 get_value<bool>(params, "friction_coupling"),
121 get_value_or<bool>(params, "single_precision", gpu),
122 get_value_or<bool>(params, "thermalized", false),
123 static_cast<uint>(get_value_or<int>(params, "seed", 0)));
124 m_instance->ghost_communication();
125}
126
130 get_value_or<decltype(m_vtk_writers)>(params, "vtk_writers", {});
131 auto const agrid = get_value<double>(m_lattice->get_parameter("agrid"));
132 auto const density = get_value<double>(params, "density");
133 auto const kT = get_value<double>(params, "kT");
134 auto const tau = m_tau = get_value<double>(params, "tau");
135 auto const seed = get_value_or<int>(params, "seed", 0);
136 context()->parallel_try_catch([&]() {
137 if (get_value<bool>(params, "thermalized") and
138 not params.contains("seed")) {
139 throw std::invalid_argument(
140 "Parameter 'seed' is required for thermalized EKSpecies");
141 }
142 if (seed < 0) {
143 throw std::domain_error("Parameter 'seed' must be >= 0");
144 }
145 if (tau <= 0.) {
146 throw std::domain_error("Parameter 'tau' must be > 0");
147 }
148 if (kT < 0.) {
149 throw std::domain_error("Parameter 'kT' must be >= 0");
150 }
151 if (density < 0.) {
152 throw std::domain_error("Parameter 'density' must be >= 0");
153 }
154 m_conv_energy = Utils::int_pow<2>(tau) / Utils::int_pow<2>(agrid);
155 m_conv_diffusion = tau / Utils::int_pow<2>(agrid);
156 m_conv_ext_efield = Utils::int_pow<2>(tau) / agrid;
157 m_conv_density = Utils::int_pow<3>(agrid);
158 m_conv_flux = tau * Utils::int_pow<2>(agrid);
160 make_instance(params);
162 for (auto &vtk : m_vtk_writers) {
163 vtk->attach_to_lattice(m_instance, get_lattice_to_md_units_conversion());
164 }
165 });
166}
167
168void EKSpecies::load_checkpoint(std::filesystem::path const &path, int mode) {
169 auto &ek_obj = *m_instance;
170
171 auto const read_metadata = [&ek_obj](CheckpointFile &cpfile) {
172 auto const expected_grid_size = ek_obj.get_lattice().get_grid_dimensions();
176 std::stringstream message;
177 message << "grid dimensions mismatch, read [" << read_grid_size << "], "
178 << "expected [" << expected_grid_size << "].";
179 throw std::runtime_error(message.str());
180 }
181 };
182
183 auto const read_data = [&ek_obj](CheckpointFile &cpfile) {
184 auto const grid_size = ek_obj.get_lattice().get_grid_dimensions();
185 auto const i_max = grid_size[0];
186 auto const j_max = grid_size[1];
187 auto const k_max = grid_size[2];
189 for (int i = 0; i < i_max; i++) {
190 for (int j = 0; j < j_max; j++) {
191 for (int k = 0; k < k_max; k++) {
192 auto const ind = Utils::Vector3i{{i, j, k}};
193 cpfile.read(cpnode.density);
194 cpfile.read(cpnode.is_boundary_density);
195 if (cpnode.is_boundary_density) {
196 cpfile.read(cpnode.density_boundary);
197 }
198 cpfile.read(cpnode.is_boundary_flux);
199 if (cpnode.is_boundary_flux) {
200 cpfile.read(cpnode.flux_boundary);
201 }
202 ek_obj.set_node_density(ind, cpnode.density);
203 if (cpnode.is_boundary_density) {
204 ek_obj.set_node_density_boundary(ind, cpnode.density_boundary);
205 }
206 if (cpnode.is_boundary_flux) {
207 ek_obj.set_node_flux_boundary(ind, cpnode.flux_boundary);
208 }
209 }
210 }
211 }
212 };
213
214 auto const on_success = [&ek_obj]() { ek_obj.ghost_communication(); };
215
217 on_success);
218}
219
220void EKSpecies::save_checkpoint(std::filesystem::path const &path, int mode) {
221 auto &ek_obj = *m_instance;
222
223 auto const write_metadata = [&ek_obj,
224 mode](std::shared_ptr<CheckpointFile> cpfile_ptr,
225 Context const &context) {
226 auto const grid_size = ek_obj.get_lattice().get_grid_dimensions();
227 if (context.is_head_node()) {
228 cpfile_ptr->write(grid_size);
230 }
231 };
232
233 auto const on_failure = [](std::shared_ptr<CheckpointFile> const &,
234 Context const &context) {
235 if (context.is_head_node()) {
236 auto failure = true;
237 boost::mpi::broadcast(context.get_comm(), failure, 0);
238 }
239 };
240
241 auto const write_data = [&ek_obj,
242 mode](std::shared_ptr<CheckpointFile> cpfile_ptr,
243 Context const &context) {
244 auto const get_node_checkpoint =
245 [&](Utils::Vector3i const &ind) -> std::optional<EKWalberlaNodeState> {
246 auto const density = ek_obj.get_node_density(ind);
247 auto const is_b_d = ek_obj.get_node_is_density_boundary(ind);
248 auto const dens_b = ek_obj.get_node_density_at_boundary(ind);
249 auto const is_b_f = ek_obj.get_node_is_flux_boundary(ind);
250 auto const flux_b = ek_obj.get_node_flux_at_boundary(ind);
252 ((*is_b_d) ? dens_b.has_value() : true) and
253 ((*is_b_f) ? flux_b.has_value() : true)) {
256 cpnode.is_boundary_density = *is_b_d;
257 if (*is_b_d) {
258 cpnode.density_boundary = *dens_b;
259 }
260 cpnode.is_boundary_flux = *is_b_f;
261 if (*is_b_f) {
262 cpnode.flux_boundary = *flux_b;
263 }
264 return cpnode;
265 }
266 return std::nullopt;
267 };
268
269 auto failure = false;
270 auto const &comm = context.get_comm();
271 auto const is_head_node = context.is_head_node();
272 auto const unit_test_mode = (mode != static_cast<int>(CptMode::ascii)) and
273 (mode != static_cast<int>(CptMode::binary));
274 auto const grid_size = ek_obj.get_lattice().get_grid_dimensions();
275 auto const i_max = grid_size[0];
276 auto const j_max = grid_size[1];
277 auto const k_max = grid_size[2];
279 for (int i = 0; i < i_max; i++) {
280 for (int j = 0; j < j_max; j++) {
281 for (int k = 0; k < k_max; k++) {
282 auto const ind = Utils::Vector3i{{i, j, k}};
283 auto const result = get_node_checkpoint(ind);
284 if (!unit_test_mode) {
285 assert(1 == boost::mpi::all_reduce(comm, static_cast<int>(!!result),
286 std::plus<>()) &&
287 "Incorrect number of return values");
288 }
289 if (is_head_node) {
290 if (result) {
291 cpnode = *result;
292 } else {
293 comm.recv(boost::mpi::any_source, 42, cpnode);
294 }
295 auto &cpfile = *cpfile_ptr;
296 cpfile.write(cpnode.density);
297 cpfile.write(cpnode.is_boundary_density);
298 if (cpnode.is_boundary_density) {
299 cpfile.write(cpnode.density_boundary);
300 }
301 cpfile.write(cpnode.is_boundary_flux);
302 if (cpnode.is_boundary_flux) {
303 cpfile.write(cpnode.flux_boundary);
304 }
305 boost::mpi::broadcast(comm, failure, 0);
306 } else {
307 if (result) {
308 comm.send(0, 42, *result);
309 }
310 boost::mpi::broadcast(comm, failure, 0);
311 if (failure) {
312 return;
313 }
314 }
315 }
316 }
317 }
318 };
319
322}
323
324} // namespace ScriptInterface::walberla
325
326#endif // ESPRESSO_WALBERLA
virtual void parallel_try_catch(std::function< void()> const &cb) const =0
virtual bool is_head_node() const =0
virtual boost::mpi::communicator const & get_comm() const =0
Context * context() const
Responsible context.
void flux_boundary_ghost_layer_size_sanity_check() const
::LatticeModel::units_map get_lattice_to_md_units_conversion() const override
std::optional< ResourceObserver > m_mpi_cart_comm_observer
Definition EKSpecies.hpp:67
void make_instance(VariantMap const &params) override
Definition EKSpecies.cpp:97
Variant do_call_method(std::string const &method, VariantMap const &parameters) override
Definition EKSpecies.cpp:56
void do_construct(VariantMap const &params) override
Variant do_call_method(std::string const &method_name, VariantMap const &params) override
cudaStream_t stream[1]
CUDA streams for parallel computing on CPU and GPU.
This file contains the errorhandling code for severe errors, like a broken bond or illegal parameter ...
void check_features(std::vector< std::string > const &features)
Definition CodeInfo.cpp:74
void save_checkpoint_common(Context const &context, std::string const classname, std::filesystem::path const &path, int mode, F1 const write_metadata, F2 const write_data, F3 const on_failure)
void unit_test_handle(int mode)
Inject code for unit tests.
void load_checkpoint_common(Context const &context, std::string const classname, std::filesystem::path const &path, int mode, F1 const read_metadata, F2 const read_data, F3 const on_success)
T get_value(Variant const &v)
Extract value of specific type T from a Variant.
std::unordered_map< std::string, Variant > VariantMap
Definition Variant.hpp:133
T get_value_or(VariantMap const &vals, std::string const &name, T const &default_)
Get a value from a VariantMap by name, or return a default value if it does not exist.
std::shared_ptr< EKinWalberlaBase > new_ek_walberla_cpu(std::shared_ptr< LatticeWalberla > const &lattice, double diffusion, double kT, double valency, Utils::Vector3d ext_efield, double density, bool advection, bool friction_coupling, bool single_precision, bool thermalized, unsigned int seed)
std::shared_ptr< EKinWalberlaBase > new_ek_walberla_gpu(std::shared_ptr< LatticeWalberla > const &lattice, double diffusion, double kT, double valency, Utils::Vector3d ext_efield, double density, bool advection, bool friction_coupling, bool single_precision, bool thermalized, unsigned int seed)
ResourceObserver get_mpi_cart_comm_observer()
Get an observer on waLBerla's MPI Cartesian communicator status.
Checkpoint data for a EK node.
Recursive variant implementation.
Definition Variant.hpp:84