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
34
38
39#include <utils/Vector.hpp>
40#include <utils/matrix.hpp>
42
43#include <boost/mpi.hpp>
44#include <boost/mpi/collectives/all_reduce.hpp>
45#include <boost/mpi/collectives/broadcast.hpp>
46
47#include <algorithm>
48#include <cassert>
49#include <cstddef>
50#include <filesystem>
51#include <functional>
52#include <memory>
53#include <optional>
54#include <sstream>
55#include <stdexcept>
56#include <string>
57#include <unordered_map>
58#include <vector>
59
61
62std::unordered_map<std::string, int> const LBVTKHandle::obs_map = {
63 {"density", static_cast<int>(OutputVTK::density)},
64 {"velocity_vector", static_cast<int>(OutputVTK::velocity_vector)},
65 {"pressure_tensor", static_cast<int>(OutputVTK::pressure_tensor)},
66};
67
68Variant LBFluid::do_call_method(std::string const &name,
69 VariantMap const &params) {
70 if (name == "activate") {
71 context()->parallel_try_catch([this]() {
73 });
74 m_is_active = true;
75 return {};
76 }
77 if (name == "deactivate") {
78 if (m_is_active) {
80 m_is_active = false;
81 }
82 return {};
83 }
84 if (name == "add_force_at_pos") {
85 auto const &box_geo = *::System::get_system().box_geo;
86 auto const pos = get_value<Utils::Vector3d>(params, "pos");
87 auto const f = get_value<Utils::Vector3d>(params, "force");
88 auto const folded_pos = box_geo.folded_position(pos);
89 m_instance->add_force_at_pos(folded_pos * m_conv_dist, f * m_conv_force);
90 return {};
91 }
92 if (name == "get_interpolated_velocity") {
93 auto const pos = get_value<Utils::Vector3d>(params, "pos");
94 return get_interpolated_velocity(pos);
95 }
96 if (name == "get_boundary_force_from_shape") {
97 return get_boundary_force_from_shape(
98 get_value<std::vector<int>>(params, "raster"));
99 }
100 if (name == "get_boundary_force") {
101 return get_boundary_force();
102 }
103 if (name == "get_pressure_tensor") {
104 return get_average_pressure_tensor();
105 }
106 if (name == "load_checkpoint") {
107 auto const path = get_value<std::filesystem::path>(params, "path");
108 auto const mode = get_value<int>(params, "mode");
109 load_checkpoint(path, mode);
110 return {};
111 }
112 if (name == "save_checkpoint") {
113 auto const path = get_value<std::filesystem::path>(params, "path");
114 auto const mode = get_value<int>(params, "mode");
115 save_checkpoint(path, mode);
116 return {};
117 }
118 if (name == "clear_boundaries") {
119 m_instance->clear_boundaries();
121 return {};
122 }
123 if (name == "add_boundary_from_shape") {
124 m_instance->update_boundary_from_shape(
125 get_value<std::vector<int>>(params, "raster"),
126 get_value<std::vector<double>>(params, "values"));
127 return {};
128 }
129 if (name == "get_lattice_speed") {
130 return 1. / m_conv_speed;
131 }
132
134}
135
137 auto const visc = get_value<double>(params, "kinematic_viscosity");
138 auto const dens = get_value<double>(params, "density");
139 auto const precision = get_value<bool>(params, "single_precision");
140 auto const lb_lattice = m_lattice->lattice();
141 auto const lb_visc = m_conv_visc * visc;
142 auto const lb_dens = m_conv_dens * dens;
144}
145
146#ifdef ESPRESSO_CUDA
148 auto const visc = get_value<double>(params, "kinematic_viscosity");
149 auto const dens = get_value<double>(params, "density");
150 auto const precision = get_value<bool>(params, "single_precision");
152 m_lattice->get_parameter("blocks_per_mpi_rank"));
153 if (blocks_per_mpi_rank != Utils::Vector3i{{1, 1, 1}}) {
154 throw std::runtime_error(
155 "Using more than one block per MPI rank is not supported for GPU LB");
156 }
157 auto const lb_lattice = m_lattice->lattice();
158 auto const lb_visc = m_conv_visc * visc;
159 auto const lb_dens = m_conv_dens * dens;
161}
162#endif // ESPRESSO_CUDA
163
168 auto const tau = get_value<double>(params, "tau");
169 auto const agrid = get_value<double>(m_lattice->get_parameter("agrid"));
170 auto const visc = get_value<double>(params, "kinematic_viscosity");
171 auto const dens = get_value<double>(params, "density");
172 auto const kT = get_value<double>(params, "kT");
173 auto const ext_f = get_value<Utils::Vector3d>(params, "ext_force_density");
174 m_lb_params = std::make_shared<::LB::LBWalberlaParams>(agrid, tau);
175 m_is_active = false;
176 auto const seed = get_value<int>(params, "seed");
177 context()->parallel_try_catch([&]() {
178 if (tau <= 0.) {
179 throw std::domain_error("Parameter 'tau' must be > 0");
180 }
181 m_conv_dist = 1. / agrid;
182 m_conv_visc = Utils::int_pow<1>(tau) / Utils::int_pow<2>(agrid);
183 m_conv_energy = Utils::int_pow<2>(tau) / Utils::int_pow<2>(agrid);
184 m_conv_dens = Utils::int_pow<3>(agrid);
185 m_conv_speed = Utils::int_pow<1>(tau) / Utils::int_pow<1>(agrid);
186 m_conv_press = Utils::int_pow<2>(tau) * Utils::int_pow<1>(agrid);
187 m_conv_force = Utils::int_pow<2>(tau) / Utils::int_pow<1>(agrid);
188 m_conv_force_dens = Utils::int_pow<2>(tau) * Utils::int_pow<2>(agrid);
189 auto const lb_visc = m_conv_visc * visc;
190 auto const lb_dens = m_conv_dens * dens;
191 auto const lb_kT = m_conv_energy * kT;
192 auto const lb_ext_f = m_conv_force_dens * ext_f;
193 if (seed < 0) {
194 throw std::domain_error("Parameter 'seed' must be >= 0");
195 }
196 if (lb_kT < 0.) {
197 throw std::domain_error("Parameter 'kT' must be >= 0");
198 }
199 if (lb_dens <= 0.) {
200 throw std::domain_error("Parameter 'density' must be > 0");
201 }
202 if (lb_visc < 0.) {
203 throw std::domain_error("Parameter 'kinematic_viscosity' must be >= 0");
204 }
207 static_cast<unsigned int>(seed));
208 m_instance->set_external_force(lb_ext_f);
209 m_instance->ghost_communication();
210 for (auto &vtk : m_vtk_writers) {
211 vtk->attach_to_lattice(m_instance, get_lattice_to_md_units_conversion());
212 }
213 });
214}
215
217LBFluid::get_boundary_force_from_shape(std::vector<int> const &raster) const {
218 auto const local =
219 m_instance->get_boundary_force_from_shape(raster) / m_conv_force;
220 return mpi_reduce_sum(context()->get_comm(), local);
221}
222
223Variant LBFluid::get_boundary_force() const {
224 auto const local = m_instance->get_boundary_force() / m_conv_force;
225 return mpi_reduce_sum(context()->get_comm(), local);
226}
227
228std::vector<Variant> LBFluid::get_average_pressure_tensor() const {
229 auto const local = m_instance->get_pressure_tensor() / m_conv_press;
230 auto const tensor_flat = mpi_reduce_sum(context()->get_comm(), local);
232 std::ranges::copy(tensor_flat, tensor.m_data.begin());
233 return std::vector<Variant>{tensor.row<0>().as_vector(),
234 tensor.row<1>().as_vector(),
235 tensor.row<2>().as_vector()};
236}
237
238Variant LBFluid::get_interpolated_velocity(Utils::Vector3d const &pos) const {
239 auto const &box_geo = *::System::get_system().box_geo;
240 auto const lb_pos = box_geo.folded_position(pos) * m_conv_dist;
241 auto const result = m_instance->get_velocity_at_pos(lb_pos);
242 return Utils::Mpi::reduce_optional(context()->get_comm(), result) /
244}
245
246void LBFluid::load_checkpoint(std::filesystem::path const &path, int mode) {
247 auto &lb_obj = *m_instance;
248
249 auto const read_metadata = [&lb_obj](CheckpointFile &cpfile) {
250 auto const expected_grid_size = lb_obj.get_lattice().get_grid_dimensions();
251 auto const expected_pop_size = lb_obj.stencil_size();
253 std::size_t read_pop_size;
255 cpfile.read(read_pop_size);
257 std::stringstream message;
258 message << "grid dimensions mismatch, read [" << read_grid_size << "], "
259 << "expected [" << expected_grid_size << "].";
260 throw std::runtime_error(message.str());
261 }
263 throw std::runtime_error("population size mismatch, read " +
264 std::to_string(read_pop_size) + ", expected " +
265 std::to_string(expected_pop_size) + ".");
266 }
267 };
268
269 auto const read_data = [&lb_obj](CheckpointFile &cpfile) {
270 auto const grid_size = lb_obj.get_lattice().get_grid_dimensions();
271 auto const i_max = grid_size[0];
272 auto const j_max = grid_size[1];
273 auto const k_max = grid_size[2];
275 cpnode.populations.resize(lb_obj.stencil_size());
276 for (int i = 0; i < i_max; i++) {
277 for (int j = 0; j < j_max; j++) {
278 for (int k = 0; k < k_max; k++) {
279 auto const ind = Utils::Vector3i{{i, j, k}};
280 cpfile.read(cpnode.populations);
281 cpfile.read(cpnode.last_applied_force);
282 cpfile.read(cpnode.is_boundary);
283 if (cpnode.is_boundary) {
284 cpfile.read(cpnode.slip_velocity);
285 }
286 lb_obj.set_node_population(ind, cpnode.populations);
287 lb_obj.set_node_last_applied_force(ind, cpnode.last_applied_force);
288 if (cpnode.is_boundary) {
289 lb_obj.set_node_velocity_at_boundary(ind, cpnode.slip_velocity);
290 }
291 }
292 }
293 }
294 };
295
296 auto const on_success = [&lb_obj]() {
297 lb_obj.ghost_communication();
298 lb_obj.reallocate_ubb_field();
299 };
300
302 on_success);
303}
304
305void LBFluid::save_checkpoint(std::filesystem::path const &path, int mode) {
306 auto &lb_obj = *m_instance;
307
308 auto const write_metadata = [&lb_obj,
309 mode](std::shared_ptr<CheckpointFile> cpfile_ptr,
310 Context const &context) {
311 auto const grid_size = lb_obj.get_lattice().get_grid_dimensions();
312 auto const pop_size = lb_obj.stencil_size();
313 if (context.is_head_node()) {
314 cpfile_ptr->write(grid_size);
315 cpfile_ptr->write(pop_size);
317 }
318 };
319
320 auto const on_failure = [](std::shared_ptr<CheckpointFile> const &,
321 Context const &context) {
322 if (context.is_head_node()) {
323 auto failure = true;
324 boost::mpi::broadcast(context.get_comm(), failure, 0);
325 }
326 };
327
328 auto const write_data = [&lb_obj,
329 mode](std::shared_ptr<CheckpointFile> cpfile_ptr,
330 Context const &context) {
331 auto const get_node_checkpoint =
332 [&](Utils::Vector3i const &ind) -> std::optional<LBWalberlaNodeState> {
333 auto const pop = lb_obj.get_node_population(ind);
334 auto const laf = lb_obj.get_node_last_applied_force(ind);
335 auto const lbb = lb_obj.get_node_is_boundary(ind);
336 auto const vbb = lb_obj.get_node_velocity_at_boundary(ind);
337 if (pop and laf and lbb and ((*lbb) ? vbb.has_value() : true)) {
340 cpnode.last_applied_force = *laf;
341 cpnode.is_boundary = *lbb;
342 if (*lbb) {
343 cpnode.slip_velocity = *vbb;
344 }
345 return {cpnode};
346 }
347 return std::nullopt;
348 };
349
350 auto failure = false;
351 auto const &comm = context.get_comm();
352 auto const is_head_node = context.is_head_node();
353 auto const unit_test_mode = (mode != static_cast<int>(CptMode::ascii)) and
354 (mode != static_cast<int>(CptMode::binary));
355 auto const grid_size = lb_obj.get_lattice().get_grid_dimensions();
356 auto const i_max = grid_size[0];
357 auto const j_max = grid_size[1];
358 auto const k_max = grid_size[2];
360 for (int i = 0; i < i_max; i++) {
361 for (int j = 0; j < j_max; j++) {
362 for (int k = 0; k < k_max; k++) {
363 auto const ind = Utils::Vector3i{{i, j, k}};
364 auto const result = get_node_checkpoint(ind);
365 if (!unit_test_mode) {
366 assert(1 == boost::mpi::all_reduce(comm, static_cast<int>(!!result),
367 std::plus<>()) &&
368 "Incorrect number of return values");
369 }
370 if (is_head_node) {
371 if (result) {
372 cpnode = *result;
373 } else {
374 comm.recv(boost::mpi::any_source, 42, cpnode);
375 }
376 auto &cpfile = *cpfile_ptr;
377 cpfile.write(cpnode.populations);
378 cpfile.write(cpnode.last_applied_force);
379 cpfile.write(cpnode.is_boundary);
380 if (cpnode.is_boundary) {
381 cpfile.write(cpnode.slip_velocity);
382 }
383 boost::mpi::broadcast(comm, failure, 0);
384 } else {
385 if (result) {
386 comm.send(0, 42, *result);
387 }
388 boost::mpi::broadcast(comm, failure, 0);
389 if (failure) {
390 return;
391 }
392 }
393 }
394 }
395 }
396 };
397
400}
401
402} // namespace ScriptInterface::walberla
403
404#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
void make_instance(VariantMap const &params) override
Definition LBFluid.cpp:136
void make_instance(VariantMap const &params) override
Definition LBFluid.cpp:147
void do_construct(VariantMap const &params) override
Definition LBFluid.cpp:164
::LatticeModel::units_map get_lattice_to_md_units_conversion() const override
Definition LBFluid.hpp:133
Variant do_call_method(std::string const &name, VariantMap const &params) override
Definition LBFluid.cpp:68
std::shared_ptr<::LB::LBWalberlaParams > m_lb_params
Definition LBFluid.hpp:60
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 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 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.
static FUNC_PREFIX double *RESTRICT const double *RESTRICT int64_t const int64_t const int64_t const int64_t const int64_t const int64_t const int64_t const int64_t const int64_t const int64_t const int64_t const int64_t const int64_t const int64_t const int64_t const double grid_size
static SteepestDescentParameters params
Currently active steepest descent instance.
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
void set(Args... args)
Set the LB solver.
Recursive variant implementation.
Definition Variant.hpp:84
Matrix representation with static size.
Definition matrix.hpp:65