ESPResSo
Extensible Simulation Package for Research on Soft Matter Systems
Loading...
Searching...
No Matches
LBWalberlaImpl.hpp
Go to the documentation of this file.
1/*
2 * Copyright (C) 2019-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
20#pragma once
21
22/**
23 * @file
24 * @ref walberla::LBWalberlaImpl implements the interface of the LB
25 * waLBerla bridge using sweeps generated by lbmpy
26 * (see <tt>maintainer/walberla_kernels</tt>).
27 */
28
29#include <blockforest/Initialization.h>
30#include <blockforest/StructuredBlockForest.h>
31#include <domain_decomposition/BlockDataID.h>
32#include <domain_decomposition/IBlock.h>
33#include <field/AddToStorage.h>
34#include <field/vtk/FlagFieldCellFilter.h>
35#include <field/vtk/VTKWriter.h>
36#include <stencil/D3Q19.h>
37#include <stencil/D3Q27.h>
38#include <waLBerlaDefinitions.h>
39#if defined(__CUDACC__) and defined(WALBERLA_BUILD_WITH_CUDA)
40#include <gpu/AddGPUFieldToStorage.h>
41#endif
42
43#include "../BoundaryHandling.hpp"
44#include "../BoundaryPackInfo.hpp"
45#include "../utils/boundary.hpp"
46#include "../utils/types_conversion.hpp"
48#include "ResetForce.hpp"
49#include "lb_fields.hpp"
50#include "lb_kernels.hpp"
51#if defined(__CUDACC__) and defined(WALBERLA_BUILD_WITH_CUDA)
52#include "lb_fields.cuh"
53#include "lb_kernels.cuh"
54#endif
55
63
64#include <utils/Vector.hpp>
65
66#include <array>
67#include <bitset>
68#include <cstddef>
69#include <cstdint>
70#include <functional>
71#include <initializer_list>
72#include <limits>
73#include <memory>
74#include <optional>
75#include <ranges>
76#include <stdexcept>
77#include <string>
78#include <type_traits>
79#include <utility>
80#include <variant>
81#include <vector>
82
83namespace walberla {
84
85/** @brief Class that runs and controls the LB on waLBerla. */
86template <typename FloatType, lbmpy::Arch Architecture>
88#if not defined(WALBERLA_BUILD_WITH_CUDA)
89 static_assert(Architecture != lbmpy::Arch::GPU,
90 "waLBerla was compiled without CUDA support");
91#endif
92protected:
93 // ---- Types & Constants ----
94
95 using Kernels = detail::KernelTrait<FloatType, Architecture>;
97 typename Kernels::DynamicUBB>;
99 std::variant<typename Kernels::StreamCollisionModelThermalized,
101
102public:
103 /** @brief Stencil for collision and streaming operations. */
104 using Stencil = stencil::D3Q19;
105 /** @brief Stencil for ghost communication (includes domain corners). */
106 using StencilFull = stencil::D3Q27;
107 /** @brief Lattice model (e.g. blockforest). */
109
110protected:
111 // "underlying" field types (`GPUField` has no f-size info at compile time)
114
115public:
119#if defined(__CUDACC__) and defined(WALBERLA_BUILD_WITH_CUDA)
120 using GPUField = gpu::GPUField<FloatType>;
121#endif
122
123 struct GhostComm {
124 /** @brief Ghost communication operations. */
125 enum GhostCommFlags : unsigned {
126 PDF, ///< PDFs communication
127 VEL, ///< velocities communication
128 LAF, ///< last applied forces communication
129 UBB, ///< boundaries communication
130 SIZE
131 };
132 };
133
134protected:
135 /**
136 * @brief Full communicator.
137 * We use the D3Q27 directions to update cells along the diagonals during
138 * a full ghost communication. This is needed to properly update the corners
139 * of the ghost layer when setting cell velocities or populations.
140 */
142 FieldTrait<FloatType, Stencil,
145 FieldTrait<FloatType, Stencil,
147 /**
148 * @brief Regular communicator.
149 * We use the same directions as the stencil during integration.
150 */
152 FieldTrait<FloatType, Stencil,
154 template <class Field>
155 using PackInfo =
157
158protected:
159 // ---- Member Variables ----
160
161 // Physical parameters
162 FloatType m_viscosity; /// kinematic viscosity
163 FloatType m_density;
164 FloatType m_kT;
165 unsigned int m_seed;
166 double m_zc_to_md; // zero-centered conversion factor to MD units
167 double m_zc_to_lb; // zero-centered conversion factor to LB units
168
169 // lattice
170 std::shared_ptr<LatticeWalberla> m_lattice;
171
172 // Block data access handles
176
179
182
183 /** Flag for boundary cells. */
184 FlagUID const Boundary_flag{"boundary"};
185 bool m_has_boundaries{false};
186
187 // boundaries
188 std::shared_ptr<BoundaryModel> m_boundary;
189
190 // communicators
191 std::shared_ptr<BoundaryFullCommunicator> m_boundary_communicator;
192 std::shared_ptr<RegularFullCommunicator> m_full_communicator;
193 std::shared_ptr<RegularFullCommunicator> m_pdf_communicator;
194 std::shared_ptr<RegularFullCommunicator> m_vel_communicator;
195 std::shared_ptr<RegularFullCommunicator> m_laf_communicator;
196 std::shared_ptr<PDFStreamingCommunicator> m_pdf_streaming_communicator;
197 std::bitset<GhostComm::SIZE> m_pending_ghost_comm;
199
200 // collision sweep
201 std::shared_ptr<CollisionModel> m_collision_model;
202
203 // force reset sweep + external force handling
204 std::shared_ptr<ResetForce<PdfField, VectorField>> m_reset_force;
205
206 // velocity update sweep
207 std::shared_ptr<typename Kernels::UpdateVelFromPDF>
209
210 // Lees-Edwards boundary interpolation
211 std::shared_ptr<LeesEdwardsPack> m_lees_edwards_callbacks;
212 std::shared_ptr<InterpolateAndShiftAtBoundary<_PdfField, FloatType>>
214 std::shared_ptr<InterpolateAndShiftAtBoundary<_VectorField, FloatType>>
216 std::shared_ptr<InterpolateAndShiftAtBoundary<_VectorField, FloatType>>
218
219public:
220 template <typename T> FloatType FloatType_c(T t) const {
221 return numeric_cast<FloatType>(t);
222 }
223
224 [[nodiscard]] std::size_t stencil_size() const noexcept override {
225 return static_cast<std::size_t>(Stencil::Size);
226 }
227
229 return std::is_same_v<FloatType, double>;
230 }
231
232 [[nodiscard]] bool is_gpu() const noexcept override {
234 }
235
236public:
237 LBWalberlaImpl(std::shared_ptr<LatticeWalberla> lattice, double viscosity,
238 double density)
240 m_kT(FloatType{0}), m_seed(0u), m_zc_to_md(density),
241 m_zc_to_lb(1. / density), m_lattice(std::move(lattice)),
243
244 auto const &blocks = m_lattice->get_blocks();
245 auto const n_ghost_layers = m_lattice->get_ghost_layers();
246 if (n_ghost_layers == 0u)
247 throw std::runtime_error("At least one ghost layer must be used");
248
249 // Initialize and register fields (must use the "underlying" types)
256
257 // Initialize and register pdf field with zero centered density
260 for (auto &block : *blocks) {
262 }
263
264 // Initialize and register flag field (fluid/boundary)
265 m_flag_field_id = field::addFlagFieldToStorage<FlagField>(
266 blocks, "flag field", n_ghost_layers);
267 // Initialize boundary sweep
268 reset_boundary_handling(m_lattice->get_blocks());
269
270 // Set up the communication and register fields
273
275
276 // Instantiate the sweep responsible for force double buffering and
277 // external forces
278 m_reset_force = std::make_shared<ResetForce<PdfField, VectorField>>(
280
281 // Instantiate velocity update sweep
283 std::make_shared<typename Kernels::UpdateVelFromPDF>(
285 }
286
287 ~LBWalberlaImpl() override = default;
288
289 // ---- Integration (Core LB Algorithm) ----
290
291 void integrate() override {
292 integrate_pull_scheme();
294 }
295
296protected:
297 void integrate_vtk_writers() override {
298 for (auto const &vtk_handle : m_vtk_auto | std::views::values) {
299 if (vtk_handle->enabled) {
300 vtk::writeFiles(vtk_handle->ptr)();
301 vtk_handle->execution_count++;
302 }
303 }
304 }
305
306private:
307 /**
308 * @brief One LB time step using the pull scheme.
309 * Sequence: reset forces, stream-collide, communicate PDFs,
310 * apply Lees-Edwards interpolation (if active), handle boundaries,
311 * update velocity field from PDFs.
312 */
313 void integrate_pull_scheme() {
315 auto const &blocks = get_lattice().get_blocks();
316 // Reset force fields
317 integrate_reset_force(blocks);
318 // LB stream collide
319 integrate_stream_collide(blocks);
320 // Mark pending ghost layer updates
321 // As pdf and laf are communicated directly afterwards, they are not set
324 m_pdf_streaming_communicator->communicate();
325 if (has_lees_edwards_bc()) {
326 apply_lees_edwards_pdf_interpolation(blocks);
327 apply_lees_edwards_last_applied_force_interpolation(blocks);
328 }
329 // Handle boundaries
330 if (m_has_boundaries) {
331 integrate_boundaries(blocks);
332 }
333 // Update velocities from pdfs
334 integrate_update_velocities_from_pdf(blocks);
335
336 if (has_lees_edwards_bc()) {
337 apply_lees_edwards_vel_interpolation_and_shift(blocks);
338 }
339 }
340
341 void integrate_stream_collide(std::shared_ptr<BlockStorage> const &blocks) {
343 for (auto &block : *blocks) {
344 auto const block_variant = std::variant<IBlock *>(&block);
345 std::visit(m_run_stream_collide_sweep, cm_variant, block_variant);
346 }
347 if (auto *cm =
348 std::get_if<typename Kernels::StreamCollisionModelThermalized>(
349 &cm_variant)) {
350 cm->setTime_step(cm->getTime_step() + 1u);
351 }
352 }
353
354 void integrate_reset_force(std::shared_ptr<BlockStorage> const &blocks) {
355 for (auto &block : *blocks)
356 (*m_reset_force)(&block);
357 }
358
359 void integrate_boundaries(std::shared_ptr<BlockStorage> const &blocks) {
360 for (auto &block : *blocks)
361 (*m_boundary)(&block);
362 }
363
364 void integrate_update_velocities_from_pdf(
365 std::shared_ptr<BlockStorage> const &blocks) {
366 for (auto &block : *blocks)
368 }
369
370private:
371 // ---- Collision Model ----
372
373 /**
374 * @brief Visitor for dispatching stream-collide sweeps.
375 * Handles both thermalized and Lees-Edwards collision models
376 * via @c std::visit on the @ref CollisionModel variant.
377 */
378 class StreamCollideSweepVisitor {
379 public:
380 using StructuredBlockStorage = LatticeWalberla::Lattice_T;
381
382 void operator()(typename Kernels::StreamCollisionModelThermalized &cm,
383 IBlock *b) {
384 cm.configure(m_storage, b);
385 cm(b);
386 }
387
388 void operator()(typename Kernels::StreamCollisionModelLeesEdwards &cm,
389 IBlock *b) {
390 cm.setV_s(static_cast<decltype(cm.getV_s())>(
391 m_lees_edwards_callbacks->get_shear_velocity()));
392 cm(b);
393 }
394
395 StreamCollideSweepVisitor() = default;
396 StreamCollideSweepVisitor(std::shared_ptr<StructuredBlockStorage> storage) {
397 m_storage = std::move(storage);
398 }
399 StreamCollideSweepVisitor(std::shared_ptr<StructuredBlockStorage> storage,
400 std::shared_ptr<LeesEdwardsPack> callbacks) {
401 m_storage = std::move(storage);
402 m_lees_edwards_callbacks = std::move(callbacks);
403 }
404
405 private:
406 std::shared_ptr<StructuredBlockStorage> m_storage{};
407 std::shared_ptr<LeesEdwardsPack> m_lees_edwards_callbacks{};
408 };
409 StreamCollideSweepVisitor m_run_stream_collide_sweep{};
410
411 /** @brief Relaxation rate omega from kinematic viscosity: 2/(6*nu+1). */
412 FloatType shear_mode_relaxation_rate() const;
413 /**
414 * @brief Odd-mode relaxation rate for the magic parameter relation.
415 * Ensures optimal bounce-back wall location for the two-relaxation-time
416 * model. Default magic number is 3/16.
417 */
418 FloatType odd_mode_relaxation_rate(
419 FloatType shear_relaxation,
420 FloatType magic_number = FloatType{3} / FloatType{16}) const;
421
422public:
423 void set_collision_model(double kT, unsigned int seed) override;
425 std::unique_ptr<LeesEdwardsPack> &&lees_edwards_pack) override;
426 void check_lebc(unsigned int shear_direction,
427 unsigned int shear_plane_normal) const override;
428
429public:
430 // ---- Ghost Communication ----
431
432 /**
433 * @brief Perform all pending ghost layer updates.
434 * Uses a lazy scheme: ghost communications are only executed when
435 * they have been marked as pending by a preceding write operation.
436 */
446
447 void ghost_communication_pdf() override {
450 m_pdf_communicator->communicate();
451 if (has_lees_edwards_bc()) {
452 auto const &blocks = get_lattice().get_blocks();
453 apply_lees_edwards_pdf_interpolation(blocks);
454 }
456 }
457 }
458
459 void ghost_communication_vel() override {
462 m_vel_communicator->communicate();
463 if (has_lees_edwards_bc()) {
464 auto const &blocks = get_lattice().get_blocks();
465 apply_lees_edwards_vel_interpolation_and_shift(blocks);
466 }
468 }
469 }
470
471 void ghost_communication_laf() override {
474 m_laf_communicator->communicate();
475 if (has_lees_edwards_bc()) {
476 auto const &blocks = get_lattice().get_blocks();
477 apply_lees_edwards_last_applied_force_interpolation(blocks);
478 }
480 }
481 }
482
490
491 /** @brief Communicate all fields at once using the D3Q27 stencil. */
502
503private:
504 // ---- Lees-Edwards Boundary Conditions ----
505
506 auto has_lees_edwards_bc() const {
507 return std::holds_alternative<
508 typename Kernels::StreamCollisionModelLeesEdwards>(*m_collision_model);
509 }
510
511 void apply_lees_edwards_pdf_interpolation(
512 std::shared_ptr<BlockStorage> const &blocks) {
513 for (auto &block : *blocks)
515 }
516
517 void apply_lees_edwards_vel_interpolation_and_shift(
518 std::shared_ptr<BlockStorage> const &blocks) {
519 for (auto &block : *blocks)
521 }
522
523 void apply_lees_edwards_last_applied_force_interpolation(
524 std::shared_ptr<BlockStorage> const &blocks) {
525 for (auto &block : *blocks)
527 }
528
529public:
531 auto const &blocks = get_lattice().get_blocks();
532 apply_lees_edwards_pdf_interpolation(blocks);
533 apply_lees_edwards_vel_interpolation_and_shift(blocks);
534 apply_lees_edwards_last_applied_force_interpolation(blocks);
535 }
536
537public:
538 // ---- Node & Slice Accessors (by quantity) ----
539
540 // Velocity
541 std::optional<Utils::Vector3d>
543 bool consider_ghosts = false) const override;
544 bool set_node_velocity(Utils::Vector3i const &node,
545 Utils::Vector3d const &v) override;
546 std::vector<double>
548 Utils::Vector3i const &upper_corner) const override;
551 std::vector<double> const &velocity) override;
552
553 // Density
554 std::optional<double>
556 bool consider_ghosts = false) const override;
557 bool set_node_density(Utils::Vector3i const &node, double density) override;
558 std::vector<double>
560 Utils::Vector3i const &upper_corner) const override;
563 std::vector<double> const &density) override;
564
565 // Population
566 std::optional<std::vector<double>>
568 bool consider_ghosts = false) const override;
569 bool set_node_population(Utils::Vector3i const &node,
570 std::vector<double> const &population) override;
571 std::vector<double>
573 Utils::Vector3i const &upper_corner) const override;
576 std::vector<double> const &population) override;
577
578 // Force
579 std::optional<Utils::Vector3d>
580 get_node_force_to_be_applied(Utils::Vector3i const &node) const override;
581 std::optional<Utils::Vector3d>
583 bool consider_ghosts = false) const override;
585 Utils::Vector3d const &force) override;
586 std::vector<double> get_slice_last_applied_force(
588 Utils::Vector3i const &upper_corner) const override;
591 std::vector<double> const &force) override;
592
593 // Pressure tensor
594 std::optional<Utils::VectorXd<9>>
595 get_node_pressure_tensor(Utils::Vector3i const &node) const override;
596 std::vector<double>
598 Utils::Vector3i const &upper_corner) const override;
599
600private:
601 // ---- Interpolation (position-based access) ----
602
603 /** @brief Return a B-spline interpolation kernel for force distribution. */
604 auto make_force_interpolation_kernel() const;
605 /** @brief Return a B-spline interpolation kernel for velocity readout. */
606 auto make_velocity_interpolation_kernel() const;
607 /** @brief Return a B-spline interpolation kernel for density readout. */
608 auto make_density_interpolation_kernel() const;
609
610public:
611 std::function<bool(Utils::Vector3d const &)>
613 bool add_force_at_pos(Utils::Vector3d const &pos,
614 Utils::Vector3d const &force) override;
615 void add_forces_at_pos(std::vector<Utils::Vector3d> const &pos,
616 std::vector<Utils::Vector3d> const &forces) override;
617 std::optional<Utils::Vector3d>
619 bool consider_points_in_halo = false) const override;
620 std::vector<Utils::Vector3d>
621 get_velocities_at_pos(std::vector<Utils::Vector3d> const &pos) override;
622 std::optional<double>
624 bool consider_points_in_halo = false) const override;
625 std::vector<double>
626 get_densities_at_pos(std::vector<Utils::Vector3d> const &pos) override;
627
628public:
629 // ---- Boundary Handling ----
630
631 void reset_boundary_handling(std::shared_ptr<BlockStorage> const &blocks) {
632 auto const [lc, uc] = m_lattice->get_local_grid_range(true);
633 m_boundary =
634 std::make_shared<BoundaryModel>(blocks, m_pdf_field_id, m_flag_field_id,
635 CellInterval{to_cell(lc), to_cell(uc)});
636 }
637
638 void on_boundary_add();
639 void clear_boundaries() override;
640 void reallocate_ubb_field() override;
641 void
642 update_boundary_from_shape(std::vector<int> const &raster_flat,
643 std::vector<double> const &data_flat) override;
644 std::optional<Utils::Vector3d>
646 bool consider_ghosts = false) const override;
648 Utils::Vector3d const &velocity) override;
649 std::vector<std::optional<Utils::Vector3d>> get_slice_velocity_at_boundary(
651 Utils::Vector3i const &upper_corner) const override;
654 std::vector<std::optional<Utils::Vector3d>> const &velocity) override;
655 std::optional<Utils::Vector3d>
656 get_node_boundary_force(Utils::Vector3i const &node) const override;
657 bool remove_node_from_boundary(Utils::Vector3i const &node) override;
658 std::optional<bool>
660 bool consider_ghosts = false) const override;
661 std::vector<bool>
663 Utils::Vector3i const &upper_corner) const override;
665 std::vector<int> const &raster_flat) const override;
666 [[nodiscard]] Utils::Vector3d get_boundary_force() const override;
667
668private:
669 [[nodiscard]] Utils::Vector3i flat_index_to_node(int index) const;
670 [[nodiscard]] Utils::Vector3i get_neighbor_node(Utils::Vector3i const &node,
671 int dir) const;
672
673public:
674 // ---- Global Reductions & Physical Parameters ----
675
676 // Global pressure tensor
678 Matrix3<FloatType> tensor(FloatType{0});
679 for (auto const &block : *get_lattice().get_blocks()) {
682 }
683 auto const &grid_size = get_lattice().get_grid_dimensions();
686 return to_vector9d(tensor) * (1. / static_cast<double>(number_of_nodes));
687 }
688
689 // Global momentum
701
702 // Global external force
703 void set_external_force(Utils::Vector3d const &ext_force) override {
704 m_reset_force->set_ext_force(zero_centered_to_lb(ext_force));
705 }
706
708 return zero_centered_to_md(m_reset_force->get_ext_force());
709 }
710
711 void set_viscosity(double viscosity) override {
712 m_viscosity = FloatType_c(viscosity);
713 }
714
715 [[nodiscard]] double get_viscosity() const noexcept override {
716 return static_cast<double>(m_viscosity);
717 }
718
719 [[nodiscard]] double get_density() const noexcept override {
720 return static_cast<double>(m_density);
721 }
722
723 [[nodiscard]] double get_kT() const noexcept override {
724 return static_cast<double>(m_kT);
725 }
726
727 [[nodiscard]] unsigned int get_seed() const noexcept override {
728 return m_seed;
729 }
730
731 [[nodiscard]] std::optional<uint64_t> get_rng_state() const override {
732 auto const cm =
733 std::get_if<typename Kernels::StreamCollisionModelThermalized>(
735 if (!cm or m_kT == 0.) {
736 return std::nullopt;
737 }
738 return {static_cast<uint64_t>(cm->getTime_step())};
739 }
740
741 void set_rng_state(uint64_t counter) override {
742 auto const cm =
743 std::get_if<typename Kernels::StreamCollisionModelThermalized>(
745 if (!cm or m_kT == 0.) {
746 throw std::runtime_error("This LB instance is unthermalized");
747 }
748 assert(counter <=
749 static_cast<uint32_t>(std::numeric_limits<uint_t>::max()));
750 cm->setTime_step(static_cast<uint32_t>(counter));
751 }
752
754 return *m_lattice;
755 }
756
757 [[nodiscard]] std::size_t get_velocity_field_id() const noexcept override {
758 return m_velocity_field_id;
759 }
760
761 [[nodiscard]] std::size_t get_force_field_id() const noexcept override {
763 }
764
765 /**
766 * @brief Correction factor for off-diagonal pressure tensor elements.
767 * Compensates for the viscosity-dependent error in the non-equilibrium
768 * stress: factor = nu / (nu + 1/6).
769 */
771 return m_viscosity / (m_viscosity + FloatType{1} / FloatType{6});
772 }
773
776 for (auto const i : {1u, 2u, 3u, 5u, 6u, 7u}) {
777 tensor[i] *= revert_factor;
778 }
779 }
780
781 void pressure_tensor_correction(std::span<FloatType, 9ul> tensor) const {
783 for (auto const i : {1u, 2u, 3u, 5u, 6u, 7u}) {
784 tensor[i] *= revert_factor;
785 }
786 }
787
788protected:
789 /**
790 * @brief Scale data by a conversion factor (in-place).
791 * Used for zero-centered density representation: LB internally stores
792 * density fluctuations around zero, while the user interface uses
793 * absolute densities. The conversion factors @ref m_zc_to_md and
794 * @ref m_zc_to_lb translate between these representations.
795 */
796 template <typename T>
797 void zero_centered_transform_impl(T &data, auto const factor) const {
798 if constexpr (std::is_arithmetic_v<T>) {
799 static_assert(std::is_floating_point_v<T>);
800 data *= static_cast<T>(factor);
801 } else {
802 auto const coef = static_cast<typename T::value_type>(factor);
803 std::transform(std::begin(data), std::end(data), std::begin(data),
804 [coef](auto value) { return value * coef; });
805 }
806 }
807
808 void zero_centered_to_lb_in_place(auto &data) const {
810 }
811
812 void zero_centered_to_md_in_place(auto &data) const {
814 }
815
816 auto zero_centered_to_lb(auto const &data) const {
817 auto transformed_data = data;
819 return transformed_data;
820 }
821
822 auto zero_centered_to_md(auto const &data) const {
823 auto transformed_data = data;
825 return transformed_data;
826 }
827
828public:
829 // ---- File I/O ----
830
831 void register_vtk_field_filters(walberla::vtk::VTKOutput &vtk_obj) override {
832 field::FlagFieldCellFilter<FlagField> fluid_filter(m_flag_field_id);
834 vtk_obj.addCellExclusionFilter(fluid_filter);
835 }
836
837 void register_vtk_field_writers(walberla::vtk::VTKOutput &vtk_obj,
839 int flag_observables) override;
840
841protected:
842 // ---- Private Infrastructure Helpers ----
843
844 /**
845 * @brief Convenience function to add a field with a custom allocator.
846 *
847 * When vectorization is off, let waLBerla decide which memory allocator
848 * to use. When vectorization is on, the aligned memory allocator is
849 * required, otherwise <tt>cpu_vectorize_info["assume_aligned"]</tt> will
850 * trigger assertions. That is because for single-precision kernels the
851 * waLBerla heuristic in <tt>src/field/allocation/FieldAllocator.h</tt>
852 * will fall back to @c StdFieldAlloc, yet @c AllocateAligned is needed
853 * for intrinsics to work.
854 */
855 template <typename Field> auto add_to_storage(std::string const tag) {
856 auto const &blocks = m_lattice->get_blocks();
857 auto const n_ghost_layers = m_lattice->get_ghost_layers();
858#if defined(__CUDACC__) and defined(WALBERLA_BUILD_WITH_CUDA)
859 if constexpr (Architecture == lbmpy::Arch::GPU) {
860 auto field_id = gpu::addGPUFieldToStorage<GPUField>(
861 blocks, tag, Field::F_SIZE, field::fzyx, n_ghost_layers);
862 if constexpr (std::is_same_v<Field, _VectorField>) {
863 for (auto &block : *blocks) {
864 auto field = block.template getData<GPUField>(field_id);
866 }
867 } else if constexpr (std::is_same_v<Field, _PdfField>) {
868 for (auto &block : *blocks) {
869 auto field = block.template getData<GPUField>(field_id);
871 field, std::array<FloatType, Stencil::Size>{});
872 }
873 }
874 return field_id;
875 }
876#endif
877 {
878#ifdef ESPRESSO_BUILD_WITH_AVX_KERNELS
879 constexpr auto alignment = field::SIMDAlignment();
880 using value_type = Field::value_type;
881 using Allocator = field::AllocateAligned<value_type, alignment>;
882 auto const allocator = std::make_shared<Allocator>();
883 auto const empty_set = Set<SUID>::emptySet();
884 return field::addToStorage<Field>(
885 blocks, tag, field::internal::defaultSize, FloatType{0}, field::fzyx,
886 n_ghost_layers, false, {}, empty_set, empty_set, allocator);
887#else // ESPRESSO_BUILD_WITH_AVX_KERNELS
888 return field::addToStorage<Field>(blocks, tag, FloatType{0}, field::fzyx,
890#endif // ESPRESSO_BUILD_WITH_AVX_KERNELS
891 }
892 }
893
894 /**
895 * @brief Set up D3Q27 communicators for full ghost layer updates.
896 * Creates per-field communicators (PDF, velocity, last-applied force)
897 * as well as a combined communicator and the boundary communicator.
898 */
900 auto const &blocks = m_lattice->get_blocks();
901
902 m_full_communicator = std::make_shared<RegularFullCommunicator>(blocks);
903 m_full_communicator->addPackInfo(
904 std::make_shared<PackInfo<PdfField>>(m_pdf_field_id));
905 m_full_communicator->addPackInfo(
907 m_full_communicator->addPackInfo(
908 std::make_shared<PackInfo<VectorField>>(m_velocity_field_id));
909
910 m_pdf_communicator = std::make_shared<RegularFullCommunicator>(blocks);
911 m_vel_communicator = std::make_shared<RegularFullCommunicator>(blocks);
912 m_laf_communicator = std::make_shared<RegularFullCommunicator>(blocks);
913 m_pdf_communicator->addPackInfo(
914 std::make_shared<PackInfo<PdfField>>(m_pdf_field_id));
915 m_vel_communicator->addPackInfo(
916 std::make_shared<PackInfo<VectorField>>(m_velocity_field_id));
917 m_laf_communicator->addPackInfo(
919
921 std::make_shared<BoundaryFullCommunicator>(blocks);
922 m_boundary_communicator->addPackInfo(
925 auto boundary_packinfo = std::make_shared<
930 }
931
932 /**
933 * @brief Set up the communicator used during integration.
934 * Uses optimized streaming pack info when neither boundaries nor
935 * Lees-Edwards boundary conditions are active; falls back to the
936 * generic pack info otherwise.
937 */
939 auto const setup = [this]<typename PackInfoPdf, typename PackInfoVec>() {
940 auto const &blocks = m_lattice->get_blocks();
942 std::make_shared<PDFStreamingCommunicator>(blocks);
943 m_pdf_streaming_communicator->addPackInfo(
944 std::make_shared<PackInfoPdf>(m_pdf_field_id));
945 m_pdf_streaming_communicator->addPackInfo(
946 std::make_shared<PackInfoVec>(m_last_applied_force_field_id));
947 };
949 using PackInfoPdf = FieldTrait::PackInfoStreamingPdf;
950 using PackInfoVec = FieldTrait::PackInfoStreamingVec;
951 if (m_has_boundaries or (m_collision_model and has_lees_edwards_bc())) {
952 setup.template operator()<PackInfo<PdfField>, PackInfoVec>();
953 } else {
954 setup.template operator()<PackInfoPdf, PackInfoVec>();
955 }
956 }
957};
958
959} // namespace walberla
960
961// Out-of-class template method definitions
965#include "LBNodeAccess.impl.hpp"
966#include "LBSliceAccess.impl.hpp"
967#include "LBVTK.impl.hpp"
Out-of-class boundary access definitions for walberla::LBWalberlaImpl.
Out-of-class collision model setup definitions for walberla::LBWalberlaImpl.
Out-of-class position-based interpolation definitions for walberla::LBWalberlaImpl.
Out-of-class node access definitions for walberla::LBWalberlaImpl.
Out-of-class slice access definitions for walberla::LBWalberlaImpl.
Out-of-class VTK writer registration definition for walberla::LBWalberlaImpl.
LBWalberlaBase provides the public interface of the LB waLBerla bridge.
Vector implementation and trait types for boost qvm interoperability.
Interface of a lattice-based fluid model.
std::map< std::string, std::shared_ptr< VTKHandle > > m_vtk_auto
VTK writers that are executed automatically.
std::unordered_map< std::string, double > units_map
Class that runs and controls the BlockForest in waLBerla.
walberla::blockforest::StructuredBlockForest Lattice_T
Boundary class optimized for sparse data.
field::FlagField< uint8_t > FlagField
Class that runs and controls the LB on waLBerla.
void add_forces_at_pos(std::vector< Utils::Vector3d > const &pos, std::vector< Utils::Vector3d > const &forces) override
Distribute forces to the lattice at given positions.
std::shared_ptr< typename Kernels::UpdateVelFromPDF > m_update_velocities_from_pdf
std::vector< double > get_slice_last_applied_force(Utils::Vector3i const &lower_corner, Utils::Vector3i const &upper_corner) const override
std::variant< typename Kernels::StreamCollisionModelThermalized, typename Kernels::StreamCollisionModelLeesEdwards > CollisionModel
void zero_centered_transform_impl(T &data, auto const factor) const
Scale data by a conversion factor (in-place).
void reset_boundary_handling(std::shared_ptr< BlockStorage > const &blocks)
std::shared_ptr< RegularFullCommunicator > m_pdf_communicator
std::vector< std::optional< Utils::Vector3d > > get_slice_velocity_at_boundary(Utils::Vector3i const &lower_corner, Utils::Vector3i const &upper_corner) const override
std::optional< Utils::Vector3d > get_node_last_applied_force(Utils::Vector3i const &node, bool consider_ghosts=false) const override
stencil::D3Q19 Stencil
Stencil for collision and streaming operations.
std::optional< Utils::Vector3d > get_node_velocity_at_boundary(Utils::Vector3i const &node, bool consider_ghosts=false) const override
void ghost_communication() override
Perform all pending ghost layer updates.
void pressure_tensor_correction(Matrix3< FloatType > &tensor) const
std::optional< Utils::Vector3d > get_node_velocity(Utils::Vector3i const &node, bool consider_ghosts=false) const override
FieldTrait< FloatType, Stencil, Architecture >::template RegularCommScheme< Stencil > PDFStreamingCommunicator
Regular communicator.
Utils::Vector3d get_boundary_force_from_shape(std::vector< int > const &raster_flat) const override
Total force exerted by the fluid on a subset of boundary nodes.
std::shared_ptr< RegularFullCommunicator > m_full_communicator
std::size_t get_force_field_id() const noexcept override
std::shared_ptr< CollisionModel > m_collision_model
void set_slice_velocity(Utils::Vector3i const &lower_corner, Utils::Vector3i const &upper_corner, std::vector< double > const &velocity) override
unsigned int get_seed() const noexcept override
void integrate_vtk_writers() override
void pressure_tensor_correction(std::span< FloatType, 9ul > tensor) const
BoundaryModel::FlagField FlagField
bool remove_node_from_boundary(Utils::Vector3i const &node) override
std::optional< Utils::Vector3d > get_node_boundary_force(Utils::Vector3i const &node) const override
std::optional< double > get_density_at_pos(Utils::Vector3d const &pos, bool consider_points_in_halo=false) const override
void zero_centered_to_md_in_place(auto &data) const
FieldTrait< FloatType, Stencil >::VectorField _VectorField
void set_slice_velocity_at_boundary(Utils::Vector3i const &lower_corner, Utils::Vector3i const &upper_corner, std::vector< std::optional< Utils::Vector3d > > const &velocity) override
std::vector< double > get_slice_population(Utils::Vector3i const &lower_corner, Utils::Vector3i const &upper_corner) const override
void set_rng_state(uint64_t counter) override
std::vector< double > get_slice_velocity(Utils::Vector3i const &lower_corner, Utils::Vector3i const &upper_corner) const override
Utils::Vector3d get_boundary_force() const override
std::shared_ptr< LatticeWalberla > m_lattice
std::shared_ptr< LeesEdwardsPack > m_lees_edwards_callbacks
LBWalberlaImpl(std::shared_ptr< LatticeWalberla > lattice, double viscosity, double density)
bool set_node_last_applied_force(Utils::Vector3i const &node, Utils::Vector3d const &force) override
std::function< bool(Utils::Vector3d const &)> make_lattice_position_checker(bool consider_points_in_halo) const override
FieldTrait< FloatType, Stencil >::PdfField _PdfField
std::shared_ptr< InterpolateAndShiftAtBoundary< _VectorField, FloatType > > m_lees_edwards_vel_interpol_sweep
std::vector< bool > get_slice_is_boundary(Utils::Vector3i const &lower_corner, Utils::Vector3i const &upper_corner) const override
std::vector< double > get_slice_density(Utils::Vector3i const &lower_corner, Utils::Vector3i const &upper_corner) const override
bool is_double_precision() const noexcept override
void update_boundary_from_shape(std::vector< int > const &raster_flat, std::vector< double > const &data_flat) override
Set boundary conditions from a rasterized shape.
std::shared_ptr< BoundaryModel > m_boundary
FieldTrait< FloatType, Stencil, Architecture >::PdfField PdfField
std::vector< double > get_slice_pressure_tensor(Utils::Vector3i const &lower_corner, Utils::Vector3i const &upper_corner) const override
FieldTrait< FloatType, Stencil, Architecture >::template PackInfo< Field > PackInfo
bool set_node_density(Utils::Vector3i const &node, double density) override
void set_collision_model(double kT, unsigned int seed) override
Set up the thermalized collision model.
std::vector< Utils::Vector3d > get_velocities_at_pos(std::vector< Utils::Vector3d > const &pos) override
Interpolate velocities at given positions (batch version).
void ghost_communication_laf() override
std::optional< bool > get_node_is_boundary(Utils::Vector3i const &node, bool consider_ghosts=false) const override
std::shared_ptr< ResetForce< PdfField, VectorField > > m_reset_force
void setup_streaming_communicator()
Set up the communicator used during integration.
FlagUID const Boundary_flag
Flag for boundary cells.
~LBWalberlaImpl() override=default
std::optional< uint64_t > get_rng_state() const override
std::optional< std::vector< double > > get_node_population(Utils::Vector3i const &node, bool consider_ghosts=false) const override
FloatType m_density
kinematic viscosity
double get_viscosity() const noexcept override
double get_kT() const noexcept override
Utils::Vector3d get_momentum() const override
void set_viscosity(double viscosity) override
void on_boundary_add()
Lazily enable boundary mode on first boundary addition.
std::shared_ptr< BoundaryFullCommunicator > m_boundary_communicator
std::size_t stencil_size() const noexcept override
auto add_to_storage(std::string const tag)
Convenience function to add a field with a custom allocator.
void ghost_communication_full()
Communicate all fields at once using the D3Q27 stencil.
auto zero_centered_to_lb(auto const &data) const
FieldTrait< FloatType, Stencil, Architecture >::template BoundaryCommScheme< stencil::D3Q27 > BoundaryFullCommunicator
bool set_node_velocity_at_boundary(Utils::Vector3i const &node, Utils::Vector3d const &velocity) override
stencil::D3Q27 StencilFull
Stencil for ghost communication (includes domain corners).
void register_vtk_field_writers(walberla::vtk::VTKOutput &vtk_obj, LatticeModel::units_map const &units, int flag_observables) override
std::optional< double > get_node_density(Utils::Vector3i const &node, bool consider_ghosts=false) const override
void check_lebc(unsigned int shear_direction, unsigned int shear_plane_normal) const override
Verify that MD and LB Lees-Edwards parameters are consistent.
void set_slice_density(Utils::Vector3i const &lower_corner, Utils::Vector3i const &upper_corner, std::vector< double > const &density) override
void ghost_communication_vel() override
Utils::Vector3d get_external_force() const noexcept override
FloatType FloatType_c(T t) const
std::shared_ptr< RegularFullCommunicator > m_laf_communicator
std::size_t get_velocity_field_id() const noexcept override
Utils::VectorXd< 9 > get_pressure_tensor() const override
ResourceObserver m_mpi_cart_comm_observer
FieldTrait< FloatType, Stencil, Architecture >::template RegularCommScheme< stencil::D3Q27 > RegularFullCommunicator
Full communicator.
std::shared_ptr< InterpolateAndShiftAtBoundary< _PdfField, FloatType > > m_lees_edwards_pdf_interpol_sweep
void set_external_force(Utils::Vector3d const &ext_force) override
void setup_full_communicator()
Set up D3Q27 communicators for full ghost layer updates.
std::optional< Utils::Vector3d > get_velocity_at_pos(Utils::Vector3d const &pos, bool consider_points_in_halo=false) const override
FieldTrait< FloatType, Stencil, Architecture >::VectorField VectorField
void set_slice_last_applied_force(Utils::Vector3i const &lower_corner, Utils::Vector3i const &upper_corner, std::vector< double > const &force) override
LatticeWalberla::Lattice_T BlockStorage
Lattice model (e.g.
std::shared_ptr< RegularFullCommunicator > m_vel_communicator
std::bitset< GhostComm::SIZE > m_pending_ghost_comm
LatticeWalberla const & get_lattice() const noexcept override
auto zero_centered_to_md(auto const &data) const
void set_slice_population(Utils::Vector3i const &lower_corner, Utils::Vector3i const &upper_corner, std::vector< double > const &population) override
double get_density() const noexcept override
void ghost_communication_pdf() override
void register_vtk_field_filters(walberla::vtk::VTKOutput &vtk_obj) override
std::optional< Utils::Vector3d > get_node_force_to_be_applied(Utils::Vector3i const &node) const override
std::vector< double > get_densities_at_pos(std::vector< Utils::Vector3d > const &pos) override
void zero_centered_to_lb_in_place(auto &data) const
bool set_node_velocity(Utils::Vector3i const &node, Utils::Vector3d const &v) override
bool set_node_population(Utils::Vector3i const &node, std::vector< double > const &population) override
bool is_gpu() const noexcept override
FloatType pressure_tensor_correction_factor() const
Correction factor for off-diagonal pressure tensor elements.
std::shared_ptr< PDFStreamingCommunicator > m_pdf_streaming_communicator
detail::KernelTrait< FloatType, Architecture > Kernels
BlockDataID m_last_applied_force_field_id
std::optional< Utils::VectorXd< 9 > > get_node_pressure_tensor(Utils::Vector3i const &node) const override
std::shared_ptr< InterpolateAndShiftAtBoundary< _VectorField, FloatType > > m_lees_edwards_last_applied_force_interpol_sweep
bool add_force_at_pos(Utils::Vector3d const &pos, Utils::Vector3d const &force) override
void setup_boundary_handle(std::shared_ptr< LatticeWalberla > lattice, std::shared_ptr< Boundary_T > boundary)
cudaStream_t stream[1]
CUDA streams for parallel computing on CPU and GPU.
static double * block(double *p, std::size_t index, std::size_t size)
Definition elc.cpp:169
T product(Vector< T, N > const &v)
Definition Vector.hpp:373
STL namespace.
auto reduce(GhostLayerField< double, uint_t{19u}> const *pdf_field, GhostLayerField< double, uint_t{3u}> const *force_field, double const density)
void initialize(GhostLayerField< double, uint_t{19u}> *pdf_field, std::array< double, 19u > const &pop)
auto reduce(GhostLayerField< double, uint_t{19u}> const *pdf_field, double const density)
void initialize(GhostLayerField< double, uint_t{3u}> *vec_field, Vector3< double > const &vec)
\file PackInfoPdfDoublePrecision.cpp \author pystencils
auto to_vector3d(Vector3< T > const &v) noexcept
Cell to_cell(signed_integral_vector auto const &xyz)
ResourceObserver get_mpi_cart_comm_observer()
Get an observer on waLBerla's MPI Cartesian communicator status.
auto to_vector9d(Matrix3< T > const &m) noexcept
static Utils::Vector3d velocity(Particle const &p_ref, Particle const &p_vs)
Velocity of the virtual site.
Definition relative.cpp:65
Observer to monitor the lifetime of a shared resource.
detail::KernelTrait< FT, AT >::PackInfoVec PackInfoStreamingVec
Definition lb_fields.hpp:37
field::GhostLayerField< FT, PdfStencil::Size > PdfField
Definition lb_fields.hpp:33
field::GhostLayerField< FT, uint_t{3u}> VectorField
Definition lb_fields.hpp:34
detail::KernelTrait< FT, AT >::PackInfoPdf PackInfoStreamingPdf
Definition lb_fields.hpp:36
GhostCommFlags
Ghost communication operations.
@ LAF
last applied forces communication