ESPResSo
Extensible Simulation Package for Research on Soft Matter Systems
Loading...
Searching...
No Matches
LBFluid.cpp
Go to the documentation of this file.
1/*
2 * Copyright (C) 2021-2023 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 "LBFluid.hpp"
26
27#include "core/BoxGeometry.hpp"
32
35
41
42#include <utils/Vector.hpp>
43#include <utils/matrix.hpp>
45
46#include <boost/mpi.hpp>
47#include <boost/mpi/collectives/all_reduce.hpp>
48#include <boost/mpi/collectives/broadcast.hpp>
49
50#include <algorithm>
51#include <cassert>
52#include <cstddef>
53#include <filesystem>
54#include <functional>
55#include <memory>
56#include <optional>
57#include <sstream>
58#include <stdexcept>
59#include <string>
60#include <unordered_map>
61#include <vector>
62
64
65std::unordered_map<std::string, int> const LBVTKHandle::obs_map = {
66 {"density", static_cast<int>(OutputVTK::density)},
67 {"velocity_vector", static_cast<int>(OutputVTK::velocity_vector)},
68 {"pressure_tensor", static_cast<int>(OutputVTK::pressure_tensor)},
69};
70
71Variant LBFluid::do_call_method(std::string const &name,
72 VariantMap const &params) {
73 if (name == "activate") {
74 auto &system = get_system();
79 m_is_active = true;
80 return {};
81 }
82 if (name == "deactivate") {
83 get_system().lb.reset();
84 m_is_active = false;
85 return {};
86 }
87 if (not name.starts_with("get_")) {
90 }
91 if (name == "add_force_at_pos") {
92 auto const &box_geo = *get_system().box_geo;
93 auto const pos = get_value<Utils::Vector3d>(params, "pos");
94 auto const f = get_value<Utils::Vector3d>(params, "force");
95 auto const folded_pos = box_geo.folded_position(pos);
96 m_instance->add_force_at_pos(folded_pos * m_conv_dist, f * m_conv_force);
97 return {};
98 }
99 if (name == "get_interpolated_velocity") {
100 auto const pos = get_value<Utils::Vector3d>(params, "pos");
101 return get_interpolated_velocity(pos);
102 }
103 if (name == "get_boundary_force_from_shape") {
104 return get_boundary_force_from_shape(
105 get_value<std::vector<int>>(params, "raster"));
106 }
107 if (name == "get_boundary_force") {
108 return get_boundary_force();
109 }
110 if (name == "get_pressure_tensor") {
111 return get_average_pressure_tensor();
112 }
113 if (name == "load_checkpoint") {
114 auto const path = get_value<std::filesystem::path>(params, "path");
115 auto const mode = get_value<int>(params, "mode");
116 load_checkpoint(path, mode);
117 return {};
118 }
119 if (name == "save_checkpoint") {
120 auto const path = get_value<std::filesystem::path>(params, "path");
121 auto const mode = get_value<int>(params, "mode");
122 save_checkpoint(path, mode);
123 return {};
124 }
125 if (name == "clear_boundaries") {
126 m_instance->clear_boundaries();
128 return {};
129 }
130 if (name == "add_boundary_from_shape") {
131 m_instance->update_boundary_from_shape(
132 get_value<std::vector<int>>(params, "raster"),
133 get_value<std::vector<double>>(params, "values"));
134 return {};
135 }
136 if (name == "get_lattice_speed") {
137 return 1. / m_conv_speed;
138 }
139
140 return Base::do_call_method(name, params);
141}
142
144 auto const visc = get_value<double>(params, "kinematic_viscosity");
145 auto const dens = get_value<double>(params, "density");
146 auto const gpu = get_value_or(params, "gpu", false);
147 auto const precision = get_value_or(params, "single_precision", gpu);
148 auto const lb_lattice = m_lattice->lattice();
149 auto const lb_visc = m_conv_visc * visc;
150 auto const lb_dens = m_conv_dens * dens;
151 auto *make_new_instance = &new_lb_walberla_cpu;
152 if (gpu) {
153 std::vector<std::string> required_features;
154 required_features.emplace_back("CUDA");
156#ifdef ESPRESSO_CUDA
158 m_lattice->get_parameter("blocks_per_mpi_rank"));
159 if (blocks_per_mpi_rank != Utils::Vector3i{{1, 1, 1}}) {
160 throw std::runtime_error(
161 "Using more than one block per MPI rank is not supported for GPU LB");
162 }
163 make_new_instance = &new_lb_walberla_gpu;
164#endif
165 }
166 m_instance = make_new_instance(lb_lattice, lb_visc, lb_dens, precision);
167}
168
172 get_value_or<decltype(m_vtk_writers)>(params, "vtk_writers", {});
173 auto const tau = get_value<double>(params, "tau");
174 auto const agrid = get_value<double>(m_lattice->get_parameter("agrid"));
175 auto const visc = get_value<double>(params, "kinematic_viscosity");
176 auto const dens = get_value<double>(params, "density");
177 auto const kT = get_value<double>(params, "kT");
178 auto const ext_f = get_value<Utils::Vector3d>(params, "ext_force_density");
179 m_lb_params = std::make_shared<::LB::LBWalberlaParams>(agrid, tau);
180 m_is_active = false;
181 auto const seed = get_value<int>(params, "seed");
182 context()->parallel_try_catch([&]() {
183 if (tau <= 0.) {
184 throw std::domain_error("Parameter 'tau' must be > 0");
185 }
186 m_conv_dist = 1. / agrid;
187 m_conv_visc = Utils::int_pow<1>(tau) / Utils::int_pow<2>(agrid);
188 m_conv_energy = Utils::int_pow<2>(tau) / Utils::int_pow<2>(agrid);
189 m_conv_dens = Utils::int_pow<3>(agrid);
190 m_conv_speed = Utils::int_pow<1>(tau) / Utils::int_pow<1>(agrid);
191 m_conv_press = Utils::int_pow<2>(tau) * Utils::int_pow<1>(agrid);
192 m_conv_force = Utils::int_pow<2>(tau) / Utils::int_pow<1>(agrid);
193 m_conv_force_dens = Utils::int_pow<2>(tau) * Utils::int_pow<2>(agrid);
194 auto const lb_visc = m_conv_visc * visc;
195 auto const lb_dens = m_conv_dens * dens;
196 auto const lb_kT = m_conv_energy * kT;
197 auto const lb_ext_f = m_conv_force_dens * ext_f;
198 if (seed < 0) {
199 throw std::domain_error("Parameter 'seed' must be >= 0");
200 }
201 if (lb_kT < 0.) {
202 throw std::domain_error("Parameter 'kT' must be >= 0");
203 }
204 if (lb_dens <= 0.) {
205 throw std::domain_error("Parameter 'density' must be > 0");
206 }
207 if (lb_visc < 0.) {
208 throw std::domain_error("Parameter 'kinematic_viscosity' must be >= 0");
209 }
210 make_instance(params);
212 m_instance->set_collision_model(lb_kT, seed);
213 m_instance->set_external_force(lb_ext_f);
214 m_instance->ghost_communication();
215 for (auto &vtk : m_vtk_writers) {
216 vtk->attach_to_lattice(m_instance, get_lattice_to_md_units_conversion());
217 }
218 });
219}
220
222LBFluid::get_boundary_force_from_shape(std::vector<int> const &raster) const {
223 auto const local =
224 m_instance->get_boundary_force_from_shape(raster) / m_conv_force;
225 return mpi_reduce_sum(context()->get_comm(), local);
226}
227
228Variant LBFluid::get_boundary_force() const {
229 auto const local = m_instance->get_boundary_force() / m_conv_force;
230 return mpi_reduce_sum(context()->get_comm(), local);
231}
232
233std::vector<Variant> LBFluid::get_average_pressure_tensor() const {
234 auto const local = m_instance->get_pressure_tensor() / m_conv_press;
235 auto const tensor_flat = mpi_reduce_sum(context()->get_comm(), local);
237 std::ranges::copy(tensor_flat, tensor.m_data.begin());
238 return std::vector<Variant>{tensor.row<0>().as_vector(),
239 tensor.row<1>().as_vector(),
240 tensor.row<2>().as_vector()};
241}
242
243Variant LBFluid::get_interpolated_velocity(Utils::Vector3d const &pos) const {
244 auto const &box_geo = *get_system().box_geo;
245 auto const lb_pos = box_geo.folded_position(pos) * m_conv_dist;
246 auto const result = m_instance->get_velocity_at_pos(lb_pos);
247 return Utils::Mpi::reduce_optional(context()->get_comm(), result) /
249}
250
251void LBFluid::load_checkpoint(std::filesystem::path const &path, int mode) {
252 auto &lb_obj = *m_instance;
253
254 auto const read_metadata = [&lb_obj](CheckpointFile &cpfile) {
255 auto const expected_grid_size = lb_obj.get_lattice().get_grid_dimensions();
256 auto const expected_pop_size = lb_obj.stencil_size();
258 std::size_t read_pop_size;
260 cpfile.read(read_pop_size);
262 std::stringstream message;
263 message << "grid dimensions mismatch, read [" << read_grid_size << "], "
264 << "expected [" << expected_grid_size << "].";
265 throw std::runtime_error(message.str());
266 }
268 throw std::runtime_error("population size mismatch, read " +
269 std::to_string(read_pop_size) + ", expected " +
270 std::to_string(expected_pop_size) + ".");
271 }
272 };
273
274 auto const read_data = [&lb_obj](CheckpointFile &cpfile) {
275 auto const grid_size = lb_obj.get_lattice().get_grid_dimensions();
276 auto const i_max = grid_size[0];
277 auto const j_max = grid_size[1];
278 auto const k_max = grid_size[2];
280 cpnode.populations.resize(lb_obj.stencil_size());
281 for (int i = 0; i < i_max; i++) {
282 for (int j = 0; j < j_max; j++) {
283 for (int k = 0; k < k_max; k++) {
284 auto const ind = Utils::Vector3i{{i, j, k}};
285 cpfile.read(cpnode.populations);
286 cpfile.read(cpnode.last_applied_force);
287 cpfile.read(cpnode.is_boundary);
288 if (cpnode.is_boundary) {
289 cpfile.read(cpnode.slip_velocity);
290 }
291 lb_obj.set_node_population(ind, cpnode.populations);
292 lb_obj.set_node_last_applied_force(ind, cpnode.last_applied_force);
293 if (cpnode.is_boundary) {
294 lb_obj.set_node_velocity_at_boundary(ind, cpnode.slip_velocity);
295 }
296 }
297 }
298 }
299 };
300
301 auto const on_success = [&lb_obj]() {
302 lb_obj.ghost_communication();
303 lb_obj.reallocate_ubb_field();
304 };
305
307 on_success);
308}
309
310void LBFluid::save_checkpoint(std::filesystem::path const &path, int mode) {
311 auto &lb_obj = *m_instance;
312
313 auto const write_metadata = [&lb_obj,
314 mode](std::shared_ptr<CheckpointFile> cpfile_ptr,
315 Context const &context) {
316 auto const grid_size = lb_obj.get_lattice().get_grid_dimensions();
317 auto const pop_size = lb_obj.stencil_size();
318 if (context.is_head_node()) {
319 cpfile_ptr->write(grid_size);
320 cpfile_ptr->write(pop_size);
322 }
323 };
324
325 auto const on_failure = [](std::shared_ptr<CheckpointFile> const &,
326 Context const &context) {
327 if (context.is_head_node()) {
328 auto failure = true;
329 boost::mpi::broadcast(context.get_comm(), failure, 0);
330 }
331 };
332
333 auto const write_data = [&lb_obj,
334 mode](std::shared_ptr<CheckpointFile> cpfile_ptr,
335 Context const &context) {
336 auto const get_node_checkpoint =
337 [&](Utils::Vector3i const &ind) -> std::optional<LBWalberlaNodeState> {
338 auto const pop = lb_obj.get_node_population(ind);
339 auto const laf = lb_obj.get_node_last_applied_force(ind);
340 auto const lbb = lb_obj.get_node_is_boundary(ind);
341 auto const vbb = lb_obj.get_node_velocity_at_boundary(ind);
342 if (pop and laf and lbb and ((*lbb) ? vbb.has_value() : true)) {
345 cpnode.last_applied_force = *laf;
346 cpnode.is_boundary = *lbb;
347 if (*lbb) {
348 cpnode.slip_velocity = *vbb;
349 }
350 return {cpnode};
351 }
352 return std::nullopt;
353 };
354
355 auto failure = false;
356 auto const &comm = context.get_comm();
357 auto const is_head_node = context.is_head_node();
358 auto const unit_test_mode = (mode != static_cast<int>(CptMode::ascii)) and
359 (mode != static_cast<int>(CptMode::binary));
360 auto const grid_size = lb_obj.get_lattice().get_grid_dimensions();
361 auto const i_max = grid_size[0];
362 auto const j_max = grid_size[1];
363 auto const k_max = grid_size[2];
365 for (int i = 0; i < i_max; i++) {
366 for (int j = 0; j < j_max; j++) {
367 for (int k = 0; k < k_max; k++) {
368 auto const ind = Utils::Vector3i{{i, j, k}};
369 auto const result = get_node_checkpoint(ind);
370 if (!unit_test_mode) {
371 assert(1 == boost::mpi::all_reduce(comm, static_cast<int>(!!result),
372 std::plus<>()) &&
373 "Incorrect number of return values");
374 }
375 if (is_head_node) {
376 if (result) {
377 cpnode = *result;
378 } else {
379 comm.recv(boost::mpi::any_source, 42, cpnode);
380 }
381 auto &cpfile = *cpfile_ptr;
382 cpfile.write(cpnode.populations);
383 cpfile.write(cpnode.last_applied_force);
384 cpfile.write(cpnode.is_boundary);
385 if (cpnode.is_boundary) {
386 cpfile.write(cpnode.slip_velocity);
387 }
388 boost::mpi::broadcast(comm, failure, 0);
389 } else {
390 if (result) {
391 comm.send(0, 42, *result);
392 }
393 boost::mpi::broadcast(comm, failure, 0);
394 if (failure) {
395 return;
396 }
397 }
398 }
399 }
400 }
401 };
402
405}
406
407} // namespace ScriptInterface::walberla
408
409#endif // ESPRESSO_WALBERLA
Vector implementation and trait types for boost qvm interoperability.
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.
std::string_view name() const
std::optional< ResourceObserver > m_mpi_cart_comm_observer
Definition LBFluid.hpp:74
void do_construct(VariantMap const &params) override
Definition LBFluid.cpp:169
void make_instance(VariantMap const &params) override
Definition LBFluid.cpp:143
::LatticeModel::units_map get_lattice_to_md_units_conversion() const override
Definition LBFluid.hpp:152
Variant do_call_method(std::string const &name, VariantMap const &params) override
Definition LBFluid.cpp:71
std::shared_ptr<::LB::LBWalberlaParams > m_lb_params
Definition LBFluid.hpp:73
Variant do_call_method(std::string const &method_name, VariantMap const &params) override
void on_lb_boundary_conditions_change()
Called when the LB boundary conditions change (geometry, slip velocity, or both).
std::shared_ptr< BoxGeometry > box_geo
std::shared_ptr< LBWalberlaBase > new_lb_walberla_cpu(std::shared_ptr< LatticeWalberla > const &lattice, double viscosity, double density, bool single_precision)
std::shared_ptr< LBWalberlaBase > new_lb_walberla_gpu(std::shared_ptr< LatticeWalberla > const &lattice, double viscosity, double density, bool single_precision)
Matrix implementation and trait types for boost qvm interoperability.
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 lb_throw_if_expired(std::optional< ResourceObserver > const &mpi_obs)
Definition LBFluid.hpp:63
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.
T mpi_reduce_sum(boost::mpi::communicator const &comm, T const &result)
Reduce object by sum on the head node.
make_recursive_variant< ObjectRef > Variant
Possible types for parameters.
Definition Variant.hpp:131
System & get_system()
T reduce_optional(boost::mpi::communicator const &comm, std::optional< T > const &result)
Reduce an optional on the head node.
ResourceObserver get_mpi_cart_comm_observer()
Get an observer on waLBerla's MPI Cartesian communicator status.
Checkpoint data for a LB node.
std::vector< double > populations
void update_collision_model()
void reset()
Remove the LB solver.
Definition lb/Solver.cpp:67
Recursive variant implementation.
Definition Variant.hpp:84
Matrix representation with static size.
Definition matrix.hpp:65