diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 00000000000..1f5cf3415c6 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,31 @@ +name: ctest CI + +on: + pull_request: + branches: + - ternary-lbm + +jobs: + build-and-test: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Install dependencies + run: | + sudo apt-get install -y openmpi-bin libopenmpi-dev + + - name: Configure with tests + run: | + cmake -S cmake -B build -D BUILD_MPI=yes \ + -D PKG_LATBOLTZ=yes \ + -D ENABLE_TESTING=yes + + - name: Build + run: | + cmake --build build -j4 + + - name: Run tests + run: ctest --test-dir build -R 'FixLBMulticomponent:plain' --output-on-failure diff --git a/src/LATBOLTZ/fix_lb_multicomponent.cpp b/src/LATBOLTZ/fix_lb_multicomponent.cpp index 1bd825f0c7e..240db682257 100644 --- a/src/LATBOLTZ/fix_lb_multicomponent.cpp +++ b/src/LATBOLTZ/fix_lb_multicomponent.cpp @@ -67,6 +67,47 @@ void FixLbMulticomponent::end_of_step() dump_xdmf(update->ntimestep); } +void FixLbMulticomponent::get_total_momentum(double &jx, double &jy, double &jz) +{ + double local[3] = {0.0, 0.0, 0.0}; + double global[3] = {0.0, 0.0, 0.0}; + + for (int x = halo_extent[0]; x < subNbx - halo_extent[0]; ++x) + for (int y = halo_extent[1]; y < subNby - halo_extent[1]; ++y) + for (int z = halo_extent[2]; z < subNbz - halo_extent[2]; ++z) + for(int i = 0; i < numvel; ++i){ + local[0] += f_lb[x][y][z][i] * e19[i][0]; + local[1] += f_lb[x][y][z][i] * e19[i][1]; + local[2] += f_lb[x][y][z][i] * e19[i][2]; + } + + MPI_Reduce(local, global, 3, MPI_DOUBLE, MPI_SUM, 0, world); + + if (me == 0){ + jx = global[0]; + jy = global[1]; + jz = global[2]; + } +} + +void FixLbMulticomponent::get_total_mass(double &m) +{ + double local = 0.0; + double global = 0.0; + + for (int x = halo_extent[0]; x < subNbx - halo_extent[0]; ++x) + for (int y = halo_extent[1]; y < subNby - halo_extent[1]; ++y) + for (int z = halo_extent[2]; z < subNbz - halo_extent[2]; ++z) + for(int i = 0; i < numvel; ++i){ + local += f_lb[x][y][z][i]; + } + + MPI_Reduce(&local, &global, 1, MPI_DOUBLE, MPI_SUM, 0, world); + + if (me == 0) + m = global; +} + void FixLbMulticomponent::lb_update() { diff --git a/src/LATBOLTZ/fix_lb_multicomponent.h b/src/LATBOLTZ/fix_lb_multicomponent.h index 75afa7f7de6..809622c2df2 100644 --- a/src/LATBOLTZ/fix_lb_multicomponent.h +++ b/src/LATBOLTZ/fix_lb_multicomponent.h @@ -63,8 +63,12 @@ class FixLbMulticomponent : public FixLbFluid { int setmask() override; void initial_integrate(int) override; void end_of_step() override; + void get_total_momentum(double &, double &, double &); + void get_total_mass(double &); private: + friend class FixLbMulticomponentTestAccess; + double tau_r, tau_p, tau_s; double gamma_p, gamma_s; double kappa1, kappa2, kappa3; diff --git a/src/version.h b/src/version.h index b64909e129c..f4588344634 100644 --- a/src/version.h +++ b/src/version.h @@ -1,2 +1,2 @@ #define LAMMPS_VERSION "27 Dec 2024" -#define LAMMPS_UPDATE "Development @ 4a3bfb5" +#define LAMMPS_UPDATE "Update 10" diff --git a/unittest/CMakeLists.txt b/unittest/CMakeLists.txt index 9819a53e103..eee77c09d5b 100644 --- a/unittest/CMakeLists.txt +++ b/unittest/CMakeLists.txt @@ -98,6 +98,7 @@ add_subdirectory(fortran) add_subdirectory(python) add_subdirectory(tools) add_subdirectory(force-styles) +add_subdirectory(latboltz) # clang-format support for test sources diff --git a/unittest/latboltz/CMakeLists.txt b/unittest/latboltz/CMakeLists.txt new file mode 100644 index 00000000000..0eb1b399332 --- /dev/null +++ b/unittest/latboltz/CMakeLists.txt @@ -0,0 +1,34 @@ +set(FORCE_STYLE_TEST_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../force-styles) +set(TEST_INPUT_FOLDER ${CMAKE_CURRENT_SOURCE_DIR}/tests) + +if (PKG_LATBOLTZ AND BUILD_MPI) + #test for lattice boltzman multicomponent + add_executable(test_fix_lb_multicomponent test_fix_lb_multicomponent.cpp) + + if(NOT BUILD_SHARED_LIBS) + target_compile_definitions(test_fix_lb_multicomponent PRIVATE USING_STATIC_LIBS=1) + endif() + + target_include_directories(test_fix_lb_multicomponent PRIVATE ${FORCE_STYLE_TEST_DIR} + ${LAMMPS_SOURCE_DIR}/LATBOLTZ) + + target_link_libraries(test_fix_lb_multicomponent PRIVATE style_tests) + + file(GLOB LB_FLUID_TESTS LIST_DIRECTORIES false ${TEST_INPUT_FOLDER}/test_lb_multicomponent*.yaml) + foreach(TEST ${LB_FLUID_TESTS}) + add_mpi_test(NAME FixLBMulticomponent:plain NUM_PROCS 2 COMMAND + $ ${TEST} + --gtest_filter=FixLBMulticomponent.plain) + add_mpi_test(NAME FixLBMulticomponent:moments NUM_PROCS 1 COMMAND + $ ${TEST} + --gtest_filter=FixLbMulticomponentTest.*) + add_mpi_test(NAME FixLBMulticomponent:derivatives NUM_PROCS 1 COMMAND + $ ${TEST} + --gtest_filter=FixLbDerivativeTest.*:*/FixLbDerivativePolynomialTest.*) + set_tests_properties(FixLBMulticomponent:plain PROPERTIES PROCESSORS 2 TIMEOUT 120) + set_tests_properties(FixLBMulticomponent:moments PROPERTIES PROCESSORS 1 TIMEOUT 30) + set_tests_properties(FixLBMulticomponent:derivatives PROPERTIES PROCESSORS 1 TIMEOUT 30) + endforeach() +endif() +#set_tests_properties(FixLBMulticomponent:plain PROPERTIES +# PASS_REGULAR_EXPRESSION "Total wall time") diff --git a/unittest/latboltz/README.md b/unittest/latboltz/README.md new file mode 100644 index 00000000000..fdbecec2bf4 --- /dev/null +++ b/unittest/latboltz/README.md @@ -0,0 +1,387 @@ +# Multicomponent lattice-Boltzmann unit tests + +This document describes the implemented moment-reconstruction and +gradient/Laplacian stencil tests. + +| Unit | Status | Function under test | +| --- | --- | --- | +| Local moment reconstruction | Implemented | `FixLbMulticomponent::calc_moments()` | +| Local spatial derivatives | Implemented | `FixLbMulticomponent::calc_gradient_laplacian()` | + +Source: [multicomponent implementation](../../src/LATBOLTZ/fix_lb_multicomponent.cpp), +[test source](test_fix_lb_multicomponent.cpp), and [CTest registration](CMakeLists.txt). + +## 1. Implemented: moment reconstruction + +### Physical meaning and equations + +Each D3Q19 site stores three sets of 19 populations: `f_lb`, `g_lb`, and `k_lb`. +D3Q19 has one rest direction, six axial directions, and twelve face-diagonal +directions. Let $\mathbf{e}_i$ denote direction $i$, for $i=0,\ldots,18$. + +The local density and composition fields are the zeroth moments: + +$$ +\rho = \sum_{i=0}^{18} f_i, \qquad +\phi = \sum_{i=0}^{18} g_i, \qquad +\psi = \sum_{i=0}^{18} k_i. +$$ + +The momentum density is the first moment of the fluid populations. Velocity +is momentum density divided by mass density: + +$$ +\mathbf{j} = \sum_{i=0}^{18} f_i\mathbf{e}_i, \qquad +\mathbf{u} = \frac{\mathbf{j}}{\rho}. +$$ + +The corresponding component densities are + +$$ +\rho_1 = \frac{\rho+\phi-\psi}{2}, \qquad +\rho_2 = \frac{\rho-\phi-\psi}{2}, \qquad +\rho_3 = \psi. +$$ + +These are component densities; divide by total density to obtain component +fractions. `calc_moments()` also stores the bulk pressure +$p_0(\rho,\phi,\psi)$ (Eq. (43) of Semprebon et al.). With +$\kappa_1=\kappa_2=\kappa_3=0$ every free-energy term vanishes and + +$$ +p_0 = c_s^2\rho = \frac{\rho}{3}. +$$ + +The test asserts $\rho$, $\phi$, $\psi$, all three velocity components, and +$p_0$ directly. + +### Controlled input and expected result + +The fixture creates the fix with `kappa1 0 kappa2 0 kappa3 0`, so the pressure +reference is independent of the free-energy expression. At the tested site the +test assigns every population from a table keyed by lattice vector, so the +inputs do not depend on the index order of `e19`. The test asserts that each of +the 19 D3Q19 directions is assigned exactly once. + +| $\mathbf{e}_i$ | $f_i$ | $g_i$ | $k_i$ | +| --- | ---: | ---: | ---: | +| $(0,0,0)$ | 1.30 | 0.10 | 0.20 | +| $(+1,0,0)$ | 0.40 | 0.05 | 0 | +| $(-1,0,0)$ | 0.10 | 0 | 0.03 | +| $(0,+1,0)$ | 0.20 | 0 | 0 | +| $(0,-1,0)$ | 0.50 | $-0.04$ | 0 | +| $(0,0,+1)$ | 0.60 | 0 | 0.05 | +| $(0,0,-1)$ | 0.20 | 0 | 0 | +| $(+1,+1,0)$ | 0.10 | 0.03 | 0 | +| $(-1,-1,0)$ | 0.05 | 0 | 0 | +| $(+1,-1,0)$ | 0.07 | 0 | 0 | +| $(-1,+1,0)$ | 0.03 | 0 | 0.04 | +| $(+1,0,+1)$ | 0.08 | 0 | 0 | +| $(-1,0,-1)$ | 0.02 | 0.14 | 0 | +| $(+1,0,-1)$ | 0.04 | 0 | 0.06 | +| $(-1,0,+1)$ | 0.06 | 0 | 0 | +| $(0,+1,+1)$ | 0.09 | 0 | 0.02 | +| $(0,-1,-1)$ | 0.01 | 0 | 0 | +| $(0,+1,-1)$ | 0.05 | 0 | 0 | +| $(0,-1,+1)$ | 0.10 | 0.02 | 0 | + +The independent, hand-calculated answers follow by grouping rest, axial, and +diagonal contributions. For the density, + +$$ +\rho = \underbrace{1.3}_{\text{rest}} + + \underbrace{(0.4+0.1+0.2+0.5+0.6+0.2)}_{\text{axial}=2.0} + + \underbrace{(0.25+0.20+0.25)}_{\text{diagonal}=0.7} = 4, +$$ + +where the diagonal sums are taken over the $xy$, $xz$, and $yz$ planes. The +composition fields are + +$$ +\phi = 0.10+0.05-0.04+0.03+0.14+0.02 = 0.30, \qquad +\psi = 0.20+0.03+0.05+0.04+0.06+0.02 = 0.40. +$$ + +Each momentum component is the axial difference plus the diagonal +differences in the two planes containing that axis: + +$$ +\begin{aligned} +j_x &= (0.4-0.1) + \underbrace{(0.17-0.08)}_{xy} + \underbrace{(0.12-0.08)}_{xz} = 0.43,\\ +j_y &= (0.2-0.5) + \underbrace{(0.13-0.12)}_{xy} + \underbrace{(0.14-0.11)}_{yz} = -0.26,\\ +j_z &= (0.6-0.2) + \underbrace{(0.14-0.06)}_{xz} + \underbrace{(0.19-0.06)}_{yz} = 0.61, +\end{aligned} +$$ + +so that + +$$ +\mathbf{u} = \mathbf{j}/\rho = (0.1075,\,-0.065,\,0.1525), \qquad +p_0 = 4/3. +$$ + +Why these inputs: + +- Every diagonal is nonzero, so a loop that skips diagonals (e.g. stops at + $i<7$) gives $\rho=3.3$ and fails. +- Opposite populations are unequal on axial and diagonal links, so a sign + error in any `e19` component changes $\mathbf{j}$. +- $g$ and $k$ are spread over rest, axial, and diagonal directions, so summing + only part of the stencil changes $\phi$ or $\psi$. The negative $g$ value + catches clamping or absolute-value errors. +- $\rho\neq1$ exposes a missing division by density; $\phi\neq\psi$ exposes + swapped composition fields. + +These prescribed populations are numerical test inputs and need not be an +equilibrium distribution. + +### Implementation walkthrough + +1. **Access declaration:** `FixLbMulticomponent` declares + `friend class FixLbMulticomponentTestAccess`. No production method is made + public. The helper is defined in the test source in `LAMMPS_NS`. +2. **Fixture setup:** `FixLbMulticomponentTest::SetUp()` constructs LAMMPS, + creates a periodic, atom-free $8\times8\times8$ box with lattice spacing + and timestep equal to one, creates the fix with all $\kappa=0$, and + validates its pointer. +3. **Choose a site:** `interior_site()` returns + `{halo_extent[0], halo_extent[1], halo_extent[2]}`, i.e. local index + $(2,2,2)$: the first owned site, just inside the halo. Its neighbours at + index 1 are allocated halo cells. +4. **Supply inputs:** the test maps the table above onto D3Q19 indices, then + `set_populations()` overwrites all 19 entries of each population family at + that site. This removes dependence on the random mixture initialization at + the tested site. +5. **Execute production code:** `calculate_moments()` calls `calc_moments()` + and returns copies of `density_lb`, `phi_lb`, `psi_lb`, `pressure_lb`, and + `u_lb`. It does not recalculate the expected answer. +6. **Compare:** `ReconstructsDensityCompositionAndVelocity` uses seven + `EXPECT_NEAR` checks with absolute tolerance $10^{-13}$. +7. **Clean up:** `TearDown()` resets the owning `std::unique_ptr`. + LAMMPS destroys its fix and associated resources. + +No timesteps or halo exchanges are required: `calc_moments()` reads only +populations at the selected site. The shared test main initializes MPI; +the test runs with one MPI rank. + +### Coverage and limitations + +This test checks local zeroth and first moments over all 19 directions, +momentum signs on axial and diagonal links, field assignment, division by +density, and the ideal-gas part of the pressure. It does not check the +$\kappa$-dependent pressure terms, collision, streaming, global conservation, +or MPI communication. + +### Mutation check + +To confirm the test can fail, each of the following temporary edits was made +in `calc_moments()`, rebuilt, and run; every one made the test fail. The source +was then restored and both registered tests passed again. + +| Temporary edit | Assertions that failed | +| --- | --- | +| Loop bound `i < numvel` → `i < 7` (skip diagonals) | all seven ($\rho=3.3$) | +| `j[1] += fi * e19[i][1]` → `e19[i][0]` | $u_y$ (0.1075 instead of $-0.065$) | +| Swap the `phi_lb` / `psi_lb` assignments | $\phi$ and $\psi$ | +| Remove `/ rho` from $u_x$ | $u_x$ (0.43 instead of 0.1075) | + +This documents that validation run, not a guarantee about subsequent source +edits. + +## 2. Implemented: gradient and Laplacian + +### Physical relevance + +`calc_equilibrium()` applies `calc_gradient_laplacian()` to $\rho$, $\phi$, +and $\psi$. Their derivatives enter chemical potentials and interfacial +stress terms. A derivative error can change diffusion and interface dynamics +even when total mass remains conserved. + +### Discrete equations used by the code + +For a scalar field $q$ at lattice site $\mathbf{n}$, the implementation uses + +$$ +(\nabla_{\mathrm{LB}}q)_\alpha(\mathbf{n}) += 3\sum_{i=0}^{18} w_i\,q(\mathbf{n}+\mathbf{e}_i)e_{i\alpha}, +\qquad \alpha\in\{x,y,z\}, +$$ + +$$ +\nabla_{\mathrm{LB}}^2q(\mathbf{n}) += 6\sum_{i=0}^{18}w_i +\left[q(\mathbf{n}+\mathbf{e}_i)-q(\mathbf{n})\right]. +$$ + +The D3Q19 weights are + +$$ +w_i = +\begin{cases} +1/3 & \text{rest direction},\\ +1/18 & \text{six axial directions},\\ +1/36 & \text{twelve face-diagonal directions}. +\end{cases} +$$ + +These are derivatives in lattice coordinates: the function contains no +explicit factors of `dx_lb`. For unchanged field units and physical spacing +$h$, physical derivatives are approximated by + +$$ +\nabla_{\mathrm{phys}}q \approx \frac{1}{h}\nabla_{\mathrm{LB}}q, +\qquad +\nabla_{\mathrm{phys}}^2q \approx \frac{1}{h^2}\nabla_{\mathrm{LB}}^2q. +$$ + +The unit tests use $h=1$. Conversion of field units is a separate +concern. + +### Why polynomial fields provide independent answers + +The stencil satisfies + +$$ +\sum_i w_i\mathbf{e}_i=0, \qquad +\sum_i w_i e_{i\alpha}e_{i\beta}=\frac{1}{3}\delta_{\alpha\beta}, +$$ + +where $\delta_{\alpha\beta}$ is one for equal indices and zero otherwise. +Opposite directions also cancel odd-order terms. Expanding a quadratic field +about the tested site therefore gives its exact analytic gradient and +Laplacian, up to floating-point rounding. General smooth fields have +discretization error and should not be required to match continuum derivatives +to roundoff. + +### Test cases + +The test uses local coordinates $(X,Y,Z)$ relative to the chosen site, so the tested +site is $(0,0,0)$, and evaluates each polynomial over its complete stencil neighborhood. + +| Field $q(X,Y,Z)$ | Expected gradient at the site | Expected Laplacian | Purpose | +| --- | --- | ---: | --- | +| $5$ | $(0,0,0)$ | 0 | Constant cancellation | +| $X$, $Y$, $Z$, separately | Corresponding unit vector | 0 | Each derivative direction | +| $5+2X-3Y+4Z$ | $(2,-3,4)$ | 0 | Signs and axis assignment | +| $X^2$, $Y^2$, $Z^2$, separately | $(0,0,0)$ | 2 | Curvature along each axis | +| $X^2+2Y^2+3Z^2$ | $(0,0,0)$ | 12 | Unequal curvature contributions | +| $(X+1)(Y+2)$ | $(2,1,0)$ | 0 | Mixed term in the xy plane | +| $(Y+1)(Z+2)$ | $(0,2,1)$ | 0 | Mixed term in the yz plane | +| $(Z+1)(X+2)$ | $(1,0,2)$ | 0 | Mixed term in the zx plane | + +For example, + +$$ +q=5+2X-3Y+4Z+X^2+2Y^2+3Z^2 +$$ + +has, at the tested site, + +$$ +\nabla q=(2,-3,4), \qquad \nabla^2q=2+4+6=12. +$$ + +This combined case is useful in addition to the isolated cases, which make +failures easier to diagnose. Every case in the table, plus this combined case +(13 polynomials), runs for each of the `rho`, `phi`, and `psi` field/output +triples, giving 39 parameterized tests. + +**Negative control.** For $q=X^3$ the continuum gradient at the origin is +zero, but the second-order stencil gives + +$$ +(\nabla_{\mathrm{LB}}q)_x = 3\sum_i w_i e_{ix}^4 += 3\left(2\cdot\tfrac{1}{18} + 8\cdot\tfrac{1}{36}\right) = 1, +\qquad \nabla_{\mathrm{LB}}^2 q = 6\sum_i w_i e_{ix}^3 = 0. +$$ + +`CubicShowsSecondOrderTruncation` asserts these discrete values. It pins the +known truncation error and documents why only polynomials up to second order +are compared with continuum derivatives. + +### Implementation walkthrough + +1. **Access:** the existing `FixLbMulticomponentTestAccess` friend helper + gains `Field {Rho, Phi, Psi}` and maps it to the same field/output triples + that `calc_equilibrium()` passes: (`density_lb`, `density_gradient`, + `laplace_rho`), (`phi_lb`, `phi_gradient`, `laplace_phi`), and + (`psi_lb`, `psi_gradient`, `laplace_psi`). `calc_gradient_laplacian()` + stays private. +2. **Fixture:** `FixLbDerivativeTest` derives from `FixLbMulticomponentTest` + (same one-rank $8\times8\times8$ box) so the derivative tests get their own + suite name for the CTest filter. +3. **Supply inputs:** `set_scalar_field()` evaluates the polynomial on the + whole $3\times3\times3$ block around `interior_site()` = $(2,2,2)$. D3Q19 + reads only the centre, axial neighbours, and face diagonals; filling the + block keeps setup simple. Neighbours at index 1 are allocated halo cells. +4. **Sentinel outputs:** before the call, `fill_derivatives()` sets every + gradient component and Laplacian on that block to $10^3$. This replaces the + planned "call twice" check: if the function accumulated into its outputs + instead of resetting them, the tested site would be off by $10^3$. +5. **Execute production code:** `calculate_derivatives()` calls + `calc_gradient_laplacian()` with the selected triple and returns copies of + the three gradient components and the Laplacian at the site. +6. **Compare:** `FixLbDerivativePolynomialTest.MatchesAnalyticDerivatives` is + parameterized over (field, polynomial) and checks the four values against + the analytic derivatives with absolute tolerance $10^{-13}$. It also checks + that all 26 neighbours still hold the sentinel, i.e. the function writes + only to the tested site. + +The local polynomials need not be periodic over the whole box because this +test neither exchanges halos nor advances the fluid. Boundary and MPI halo +behaviour require separate tests. Because the helper passes the triple +explicitly, the test does not validate the wiring inside `calc_equilibrium()`; +that needs a separate integration test. + +### Mutation check + +Each of the following temporary edits to `calc_gradient_laplacian()` was +rebuilt and run against the 40 derivative tests; every one made tests fail. +The source was then restored and all three registered tests passed again. + +| Temporary edit | Tests failed (of 40) | +| --- | ---: | +| Gradient factor `3.` → `2.` | 25 | +| Laplacian factor `6.` → `3.` | 15 | +| Gradient uses `e19[i][0]` for every direction | 25 | +| Laplacian output not reset to zero | 39 | +| Gradient outputs not reset to zero | 39 | +| Laplacian without subtracting the centre value | 18 | +| $x$ neighbour taken as `x - e19[i][0]` | 16 | + +The unaffected cases pass as expected; e.g. the Laplacian factor does not +change any case whose Laplacian is zero. This documents that validation run, +not a guarantee about subsequent source edits. + +## 3. Build and run the implemented tests + +From a clean CMake-compatible source tree with an MPI toolchain: + +```sh +cmake -S cmake -B build-latboltz -D BUILD_MPI=ON -D PKG_LATBOLTZ=ON -D ENABLE_TESTING=ON +cmake --build build-latboltz --target test_fix_lb_multicomponent -j 4 +ctest --test-dir build-latboltz -R '^FixLBMulticomponent:moments$' --output-on-failure +ctest --test-dir build-latboltz -R '^FixLBMulticomponent:derivatives$' --output-on-failure +``` + +Run all three registered LATBOLTZ tests with: + +```sh +ctest --test-dir build-latboltz -R '^FixLBMulticomponent:' --output-on-failure +``` + +`FixLBMulticomponent:moments` and `FixLBMulticomponent:derivatives` use one MPI +rank; the `FixLBMulticomponent:plain` conservation test uses two. GoogleTest +filters select the intended tests from their shared executable: + +| CTest name | GoogleTest filter | +| --- | --- | +| `FixLBMulticomponent:plain` | `FixLBMulticomponent.plain` | +| `FixLBMulticomponent:moments` | `FixLbMulticomponentTest.*` | +| `FixLBMulticomponent:derivatives` | `FixLbDerivativeTest.*:*/FixLbDerivativePolynomialTest.*` | + +A filter that matches no test still exits successfully in GoogleTest 1.12, so +after renaming a fixture, run with `-V` and confirm the test count is non-zero. +The executable still receives the existing YAML file because the shared +force-style test main expects it; the unit tests use their C++ tolerances, not +the YAML epsilon. diff --git a/unittest/latboltz/test_fix_lb_multicomponent.cpp b/unittest/latboltz/test_fix_lb_multicomponent.cpp new file mode 100644 index 00000000000..304e6f8faf4 --- /dev/null +++ b/unittest/latboltz/test_fix_lb_multicomponent.cpp @@ -0,0 +1,454 @@ +/* ---------------------------------------------------------------------- + LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator + https://www.lammps.org/, Sandia National Laboratories + Steve Plimpton, sjplimp@sandia.gov + + Copyright (2003) Sandia Corporation. Under the terms of Contract + DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains + certain rights in this software. This software is distributed under + the GNU General Public License. + + See the README file in the top-level LAMMPS directory. +------------------------------------------------------------------------- */ + +/* ---------------------------------------------------------------------- + Contributing authors: Abhin Suresh (University of Delaware) +------------------------------------------------------------------------- */ + +// unit tests for fix style multicomponent fluid dynamics + +#include "test_main.h" +#include "yaml_writer.h" + +#include "gtest/gtest.h" + +#include "input.h" +#include "fix.h" +#include "fix_lb_multicomponent.h" +#include "lammps.h" +#include "modify.h" +#include "latboltz_const.h" + +#include +#include +#include +#include +#include +#include + +using namespace LAMMPS_NS; + +namespace LAMMPS_NS { + +// Keep access to lattice internals local to this test executable. +class FixLbMulticomponentTestAccess { +public: + using Populations = std::array; + struct Site { int x, y, z; }; + struct Moments { double rho, phi, psi, pressure; + std::array velocity; }; + + // return a interior site of subdomain, avoiding halo sites + static Site interior_site(const FixLbMulticomponent &fix){ + return {fix.halo_extent[0], fix.halo_extent[1], fix.halo_extent[2]}; + } + + // Populate fix object f_lb, g_lb, k_lb + static void set_populations(FixLbMulticomponent &fix, Site site, + const Populations &f, const Populations &g, + const Populations &k) + { + for (int i = 0; i < 19; ++i) { + fix.f_lb[site.x][site.y][site.z][i] = f[i]; + fix.g_lb[site.x][site.y][site.z][i] = g[i]; + fix.k_lb[site.x][site.y][site.z][i] = k[i]; + } + } + + // Call the unit calc_moments of the fix object + static Moments calculate_moments(FixLbMulticomponent &fix, Site site) + { + fix.calc_moments(site.x, site.y, site.z); + const auto *u = fix.u_lb[site.x][site.y][site.z]; + return {fix.density_lb[site.x][site.y][site.z], + fix.phi_lb[site.x][site.y][site.z], + fix.psi_lb[site.x][site.y][site.z], + fix.pressure_lb[site.x][site.y][site.z], + {u[0], u[1], u[2]}}; + } + + // Scalar fields passed to calc_gradient_laplacian by calc_equilibrium + enum class Field { Rho, Phi, Psi }; + struct Derivatives { std::array gradient; + double laplacian; }; + // polynomial q(X, Y, Z) in lattice coordinates relative to the tested site + using ScalarFunction = double (*)(double, double, double); + + // Fill the field on the 3x3x3 block around the site, which covers the D3Q19 stencil + static void set_scalar_field(FixLbMulticomponent &fix, Field field, Site site, + ScalarFunction q) + { + double ***values = scalar_field(fix, field); + for (int dx = -1; dx <= 1; ++dx) + for (int dy = -1; dy <= 1; ++dy) + for (int dz = -1; dz <= 1; ++dz) + values[site.x + dx][site.y + dy][site.z + dz] = q(dx, dy, dz); + } + + // Overwrite gradient and laplacian outputs on the 3x3x3 block around the site + static void fill_derivatives(FixLbMulticomponent &fix, Field field, Site site, double value) + { + double ****gradient = gradient_field(fix, field); + double ***laplacian = laplacian_field(fix, field); + for (int dx = -1; dx <= 1; ++dx) + for (int dy = -1; dy <= 1; ++dy) + for (int dz = -1; dz <= 1; ++dz) { + const int x = site.x + dx, y = site.y + dy, z = site.z + dz; + for (int dir = 0; dir < 3; ++dir) gradient[x][y][z][dir] = value; + laplacian[x][y][z] = value; + } + } + + // Return copies of the gradient and laplacian stored at the site + static Derivatives read_derivatives(FixLbMulticomponent &fix, Field field, Site site) + { + const double *g = gradient_field(fix, field)[site.x][site.y][site.z]; + return {{g[0], g[1], g[2]}, laplacian_field(fix, field)[site.x][site.y][site.z]}; + } + + // Call the unit calc_gradient_laplacian with the field/output triple used in calc_equilibrium + static Derivatives calculate_derivatives(FixLbMulticomponent &fix, Field field, Site site) + { + fix.calc_gradient_laplacian(site.x, site.y, site.z, scalar_field(fix, field), + gradient_field(fix, field), laplacian_field(fix, field)); + return read_derivatives(fix, field, site); + } + +private: + static double ***scalar_field(FixLbMulticomponent &fix, Field field) + { + switch (field) { + case Field::Rho: return fix.density_lb; + case Field::Phi: return fix.phi_lb; + default: return fix.psi_lb; + } + } + + static double ****gradient_field(FixLbMulticomponent &fix, Field field) + { + switch (field) { + case Field::Rho: return fix.density_gradient; + case Field::Phi: return fix.phi_gradient; + default: return fix.psi_gradient; + } + } + + static double ***laplacian_field(FixLbMulticomponent &fix, Field field) + { + switch (field) { + case Field::Rho: return fix.laplace_rho; + case Field::Phi: return fix.laplace_phi; + default: return fix.laplace_psi; + } + } +}; + +} // namespace LAMMPS_NS + +class FixLbMulticomponentTest : public ::testing::Test { +protected: + std::unique_ptr lmp; + FixLbMulticomponent *fix = nullptr; + + void SetUp() override{ + const char *args[] = {"FixLbMulticomponentTest", "-log", "none", "-screen", "none", + "-nocite"}; + lmp.reset(new LAMMPS(sizeof(args) / sizeof(args[0]), + const_cast(args), MPI_COMM_WORLD)); + lmp->input->one("boundary p p p"); + lmp->input->one("region fluid block 0 8 0 8 0 8"); + lmp->input->one("create_box 0 fluid"); + lmp->input->one("timestep 1.0"); + // zero kappas reduce the pressure to rho * c_s^2, an independent reference value + lmp->input->one("fix mcmp all lb/multicomponent 1 0.166667 1.0 D3Q19 dx 1 " + "kappa1 0 kappa2 0 kappa3 0 init mixture"); + auto fixes = lmp->modify->get_fix_by_style("lb/multicomponent"); + ASSERT_EQ(fixes.size(), 1); + fix = dynamic_cast(fixes[0]); + ASSERT_NE(fix, nullptr); + } + + void TearDown() override { + lmp.reset(); + } +}; + +// TEST_F(FixtureClassName, TestName) +TEST_F(FixLbMulticomponentTest, ReconstructsDensityCompositionAndVelocity) +{ + using Access = FixLbMulticomponentTestAccess; + Access::Populations f{}, g{}, k{}; + + std::array hits{}; + struct Entry { int ex, ey, ez; double f, g, k; }; + // Hand-chosen populations keyed by lattice vector, independent of the e19 ordering. + // Diagonals are nonzero and opposite pairs are unequal so every direction contributes. + const Entry table[] = { + { 0, 0, 0, 1.30, 0.10, 0.20}, + { 1, 0, 0, 0.40, 0.05, 0.00}, {-1, 0, 0, 0.10, 0.00, 0.03}, + { 0, 1, 0, 0.20, 0.00, 0.00}, { 0,-1, 0, 0.50, -0.04, 0.00}, + { 0, 0, 1, 0.60, 0.00, 0.05}, { 0, 0,-1, 0.20, 0.00, 0.00}, + { 1, 1, 0, 0.10, 0.03, 0.00}, {-1,-1, 0, 0.05, 0.00, 0.00}, + { 1,-1, 0, 0.07, 0.00, 0.00}, {-1, 1, 0, 0.03, 0.00, 0.04}, + { 1, 0, 1, 0.08, 0.00, 0.00}, {-1, 0,-1, 0.02, 0.14, 0.00}, + { 1, 0,-1, 0.04, 0.00, 0.06}, {-1, 0, 1, 0.06, 0.00, 0.00}, + { 0, 1, 1, 0.09, 0.00, 0.02}, { 0,-1,-1, 0.01, 0.00, 0.00}, + { 0, 1,-1, 0.05, 0.00, 0.00}, { 0,-1, 1, 0.10, 0.02, 0.00}, + }; + + for (const auto &t : table) + for (int i = 0; i < 19; ++i) + if (e19[i][0] == t.ex && e19[i][1] == t.ey && e19[i][2] == t.ez) { + f[i] = t.f; + g[i] = t.g; + k[i] = t.k; + ++hits[i]; + } + // every D3Q19 direction must be assigned exactly once + for (int i = 0; i < 19; ++i) ASSERT_EQ(hits[i], 1) << "direction " << i; + + // Get interior lattice site of the subdomain + const auto site = Access::interior_site(*fix); + // Set fix object f_lb, g_lb, k_lb values + Access::set_populations(*fix, site, f, g, k); + // Call the unit fix.calc_moments and returns density, phi, psi, pressure, velocity + const auto calculated = Access::calculate_moments(*fix, site); + + constexpr double tolerance = 1e-13; + // rho = 1.3 (rest) + 2.0 (axial) + 0.7 (diagonal) + EXPECT_NEAR(calculated.rho, 4.0, tolerance); + EXPECT_NEAR(calculated.phi, 0.30, tolerance); + EXPECT_NEAR(calculated.psi, 0.40, tolerance); + // j = (0.3 + 0.13, -0.3 + 0.04, 0.4 + 0.21), u = j / rho + EXPECT_NEAR(calculated.velocity[0], 0.1075, tolerance); + EXPECT_NEAR(calculated.velocity[1], -0.065, tolerance); + EXPECT_NEAR(calculated.velocity[2], 0.1525, tolerance); + // all kappa = 0 in the fixture, so p = rho * c_s^2 + EXPECT_NEAR(calculated.pressure, 4.0 / 3.0, tolerance); +} + +// Tests of calc_gradient_laplacian, kept in their own suites for the CTest filter +class FixLbDerivativeTest : public FixLbMulticomponentTest {}; + +// Quadratic polynomial with its analytic gradient and laplacian at the origin. +// The D3Q19 stencil is exact for polynomials up to second order. +struct PolynomialCase { + const char *name; + FixLbMulticomponentTestAccess::ScalarFunction q; + std::array gradient; + double laplacian; +}; + +void PrintTo(const PolynomialCase &c, std::ostream *os) { *os << c.name; } + +using Field = FixLbMulticomponentTestAccess::Field; + +std::string field_name(Field field) +{ + switch (field) { + case Field::Rho: return "rho"; + case Field::Phi: return "phi"; + default: return "psi"; + } +} + +const PolynomialCase polynomial_cases[] = { + {"Constant", [](double, double, double) { return 5.0; }, {0, 0, 0}, 0}, + {"X", [](double X, double, double) { return X; }, {1, 0, 0}, 0}, + {"Y", [](double, double Y, double) { return Y; }, {0, 1, 0}, 0}, + {"Z", [](double, double, double Z) { return Z; }, {0, 0, 1}, 0}, + {"Linear", [](double X, double Y, double Z) { return 5 + 2 * X - 3 * Y + 4 * Z; }, + {2, -3, 4}, 0}, + {"XX", [](double X, double, double) { return X * X; }, {0, 0, 0}, 2}, + {"YY", [](double, double Y, double) { return Y * Y; }, {0, 0, 0}, 2}, + {"ZZ", [](double, double, double Z) { return Z * Z; }, {0, 0, 0}, 2}, + {"UnequalCurvature", [](double X, double Y, double Z) { return X * X + 2 * Y * Y + 3 * Z * Z; }, + {0, 0, 0}, 12}, + {"MixedXY", [](double X, double Y, double) { return (X + 1) * (Y + 2); }, {2, 1, 0}, 0}, + {"MixedYZ", [](double, double Y, double Z) { return (Y + 1) * (Z + 2); }, {0, 2, 1}, 0}, + {"MixedZX", [](double X, double, double Z) { return (Z + 1) * (X + 2); }, {1, 0, 2}, 0}, + {"Combined", + [](double X, double Y, double Z) { + return 5 + 2 * X - 3 * Y + 4 * Z + X * X + 2 * Y * Y + 3 * Z * Z; + }, + {2, -3, 4}, 12}, +}; + +class FixLbDerivativePolynomialTest + : public FixLbDerivativeTest, + public ::testing::WithParamInterface> {}; + +TEST_P(FixLbDerivativePolynomialTest, MatchesAnalyticDerivatives) +{ + using Access = FixLbMulticomponentTestAccess; + const Field field = std::get<0>(GetParam()); + const PolynomialCase &c = std::get<1>(GetParam()); + const auto site = Access::interior_site(*fix); + + // Sentinel outputs: the site must be overwritten (not accumulated into), + // and its neighbours must be left untouched. + constexpr double sentinel = 1.0e3; + Access::set_scalar_field(*fix, field, site, c.q); + Access::fill_derivatives(*fix, field, site, sentinel); + const auto calculated = Access::calculate_derivatives(*fix, field, site); + + constexpr double tolerance = 1e-13; + EXPECT_NEAR(calculated.gradient[0], c.gradient[0], tolerance); + EXPECT_NEAR(calculated.gradient[1], c.gradient[1], tolerance); + EXPECT_NEAR(calculated.gradient[2], c.gradient[2], tolerance); + EXPECT_NEAR(calculated.laplacian, c.laplacian, tolerance); + + for (int dx = -1; dx <= 1; ++dx) + for (int dy = -1; dy <= 1; ++dy) + for (int dz = -1; dz <= 1; ++dz) { + if (dx == 0 && dy == 0 && dz == 0) continue; + const auto neighbour = Access::read_derivatives( + *fix, field, {site.x + dx, site.y + dy, site.z + dz}); + EXPECT_EQ(neighbour.gradient, (std::array{sentinel, sentinel, sentinel})) + << "neighbour (" << dx << "," << dy << "," << dz << ")"; + EXPECT_EQ(neighbour.laplacian, sentinel) + << "neighbour (" << dx << "," << dy << "," << dz << ")"; + } +} + +INSTANTIATE_TEST_SUITE_P( + Polynomials, FixLbDerivativePolynomialTest, + ::testing::Combine(::testing::Values(Field::Rho, Field::Phi, Field::Psi), + ::testing::ValuesIn(polynomial_cases)), + [](const ::testing::TestParamInfo &info) { + return field_name(std::get<0>(info.param)) + "_" + std::get<1>(info.param).name; + }); + +// Negative control: for q = X^3 the continuum gradient at the origin is zero, but the +// second-order stencil gives 3 * sum_i w_i e_ix^4 = 3 * (2/18 + 8/36) = 1. This pins the +// expected truncation error and shows the analytic cases are not trivially satisfied. +TEST_F(FixLbDerivativeTest, CubicShowsSecondOrderTruncation) +{ + using Access = FixLbMulticomponentTestAccess; + const auto site = Access::interior_site(*fix); + Access::set_scalar_field(*fix, Field::Phi, site, + [](double X, double, double) { return X * X * X; }); + const auto calculated = Access::calculate_derivatives(*fix, Field::Phi, site); + + constexpr double tolerance = 1e-13; + EXPECT_NEAR(calculated.gradient[0], 1.0, tolerance); + EXPECT_NEAR(calculated.gradient[1], 0.0, tolerance); + EXPECT_NEAR(calculated.gradient[2], 0.0, tolerance); + EXPECT_NEAR(calculated.laplacian, 0.0, tolerance); +} + +LAMMPS *init_lammps() +{ + const char *args[] = {"FixLBMulticomponent", "-log", "none", + "-echo", "screen", "-nocite"}; + + char **argv = (char **)args; + int argc = sizeof(args) / sizeof(char *); + + LAMMPS *lmp = new LAMMPS(argc, argv, MPI_COMM_WORLD); + + // utility lambda to improve readability + auto command = [&](const std::string &line){ + lmp->input->one(line); + }; + + command("region fluid block -16 16 -16 16 -3 3"); + command("create_box 0 fluid"); + command("timestep 1.0"); + command("fix mcmp all lb/multicomponent " + "1 0.166667 1.0 D3Q19 dx 1 " + "C1 0.333333 C2 0.333333 C3 0.333334 " + "kappa1 0.01 kappa2 0.02 kappa3 0.05 " + "init mixture"); + + return lmp; +} + +void run_lammps(LAMMPS *lmp) +{ + lmp->input->one("run 100"); +} + +void generate_yaml_file(const char *outfile, const TestConfig &config) +{ + LAMMPS *lmp = init_lammps(); + + YamlWriter writer(outfile); + + write_yaml_header(&writer, &test_config, lmp->version); + + delete lmp; +} +// TEST(TestSuitName, TestName) +TEST(FixLBMulticomponent, plain) +{ + LAMMPS *lmp = init_lammps(); + + // Check for LAMMPS initailization with the fix, else skip the test + if (!lmp) { + std::cerr << "One or more prerequisite styles are not available " + "in this LAMMPS configuration:\n"; + for (auto &prerequisite : test_config.prerequisites) + std::cerr << prerequisite.first << "_style " << prerequisite.second << "\n"; + + GTEST_SKIP(); + } + + int rank; + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + + // get the base-class Fix * matching the style + auto fixes = lmp->modify->get_fix_by_style("lb/multicomponent"); + + ASSERT_EQ(fixes.size(), 1); + ASSERT_NE(fixes[0], nullptr); + + // cast to FixLbMulticomponent * is it exists + auto *fix = dynamic_cast(fixes[0]); + + // verify the cast to FixLbMulticomponent succeeded + ASSERT_NE(fix, nullptr); + + // obtain initial total momentum + double jx0, jy0, jz0, m0; + jx0 = jy0 = jz0 = m0 = 0.0; + fix->get_total_momentum(jx0, jy0, jz0); + fix->get_total_mass(m0); + if (rank == 0){ + std::cout << "Initial P: " << jx0 << " " << jy0 << " " << jz0 << std::endl; + std::cout << "Initial M: " << m0 << std::endl; + EXPECT_NEAR(jx0, 0, 1e-6); + EXPECT_NEAR(jy0, 0, 1e-6); + EXPECT_NEAR(jz0, 0, 1e-6); + } + + // runs lammps time steps invoking fix_lb_multicomponent + run_lammps(lmp); + + // obtain final total momentum + double jx1, jy1, jz1, m1; + jx1 = jy1 = jz1 = m1 = 0.0; + fix->get_total_momentum(jx1, jy1, jz1); + fix->get_total_mass(m1); + + // verify conservation total momentum + if (rank == 0){ + std::cout << "Final P: " << jx1 << " " << jy1 << " " << jz1 << std::endl; + std::cout << "Final M: " << m1 << std::endl; + EXPECT_NEAR(jx1, 0, 1e-6); + EXPECT_NEAR(jy1, 0, 1e-6); + EXPECT_NEAR(jz1, 0, 1e-6); + EXPECT_NEAR(m0, m1, 1e-6); + } + delete lmp; +} diff --git a/unittest/latboltz/tests/test_lb_multicomponent.yaml b/unittest/latboltz/tests/test_lb_multicomponent.yaml new file mode 100644 index 00000000000..3d94a513926 --- /dev/null +++ b/unittest/latboltz/tests/test_lb_multicomponent.yaml @@ -0,0 +1,11 @@ +--- +lammps_version: 27 Dec 2024 +tags: generated +date_generated: Thu Aug 27 14:52:39 2026 +epsilon: 1e-14 +skip_tests: +prerequisites: ! "" +pre_commands: ! "" +post_commands: ! "" +input_file: +...