NeoN
A framework for CFD software
Loading...
Searching...
No Matches
solver.hpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2023 - 2026 NeoN authors
2//
3// SPDX-License-Identifier: MIT
4
5#pragma once
6
7#include <memory>
8#include <utility>
9#include <concepts>
10#include <optional>
11
12#include "NeoN/fields/field.hpp"
15#include "NeoN/core/logging.hpp"
16#include "NeoN/core/input.hpp"
21
24#ifdef NF_WITH_MPI_SUPPORT
26#endif
27
28
29namespace NeoN::dsl
30{
31
32namespace detail
33{
34template<typename VectorType, typename IndexType>
38 VectorType& solution,
39 scalar t,
40 scalar dt,
41 const Dictionary& fvSchemes,
42 const Dictionary& fvSolution,
44)
45{
46 auto optExp = optimize(exp);
47 optExp.read(fvSchemes);
48 optExp.assemble(t, dt, ls, ps);
49
50 // TODO move that to expression explicit operation or
51 // into functor ?
52 // subtract the explicit source term from the rhs
53 auto expTmp = optExp.explicitOperation(solution.mesh().nCells());
54 auto [vol, expSource, rhs] = views(solution.mesh().cellVolumes(), expTmp, ls.rhs());
56 solution.exec(),
57 {0, rhs.size()},
58 NEON_LAMBDA(const localIdx i) { rhs[i] -= expSource[i] * vol[i]; }
59 );
60
61 auto solver = la::Solver(solution.exec(), fvSolution);
62 fence(solution.exec());
63
64 // Do some sanity checks before trying to solve
65 NF_ASSERT(ls.exec() == solution.exec(), "Executors are not the same");
66 return solver.solve(ls, solution.internalVector());
67}
68
69template<typename VectorType, typename IndexType>
72 VectorType& solution,
73 scalar t,
74 scalar dt,
75 const Dictionary& fvSolution,
77)
78{
79 auto ls = exp.assemble(solution.mesh(), t, dt, ps);
80
81 auto solver = la::Solver(solution.exec(), fvSolution);
82 fence(solution.exec());
83 return solver.solve(ls, solution.internalVector());
84}
85}
86
87/* @brief solve an expression
88 *
89 * @param exp - Expression which is to be solved/updated.
90 * @param solution - Solution field, where the solution will be 'written to'.
91 * @param t - the time at the start of the time step.
92 * @param dt - time step for the temporal integration
93 * @param fvSchemes - Dictionary containing spatial operator and time integration properties
94 * @param fvSolution - Dictionary containing linear solver properties
95 * @param p - A chainable functor that performs manipulations on the assembled system
96 */
97template<typename VectorType, typename IndexType>
98std::optional<la::SolverStats> solve(
100 VectorType& solution,
101 scalar t,
102 scalar dt,
103 const Dictionary& fvSchemes,
104 const Dictionary& fvSolution,
106)
107{
108 if (exp.temporalOperators().size() == 0 && exp.spatialOperators().size() == 0)
109 {
110 NF_ERROR_EXIT("No temporal or implicit terms to solve.");
111 }
112 exp.read(fvSchemes);
113 auto integrator = timeIntegration::TimeIntegration<VectorType>(
114 fvSchemes.subDict("timeIntegration"), fvSolution
115 );
116
117 if (exp.temporalOperators().size() > 0 && integrator.explicitIntegration())
118 {
119 // integrate equations in time
120 integrator.solve(exp, solution, t, dt);
121 return std::nullopt; // no linear solve was performed, so no stats to return
122 }
123 else
124 {
125 return detail::iterativeSolveImpl(exp, solution, t, dt, fvSolution, p);
126 }
127}
128
129// ---------------------------------------------------------------------------
130// Matrix under-relaxation (post-assembly fused kernel)
131// ---------------------------------------------------------------------------
132
134KOKKOS_INLINE_FUNCTION scalar copySign(const scalar mag, const scalar s)
135{
136 return (s >= 0) ? mag : -mag;
137}
138
140KOKKOS_INLINE_FUNCTION scalar componentCopySign(const scalar mag, const scalar s)
141{
142 return copySign(mag, s);
143}
144
146KOKKOS_INLINE_FUNCTION Vec3 componentCopySign(const Vec3& mag, const Vec3& s)
147{
148 return Vec3(copySign(mag[0], s[0]), copySign(mag[1], s[1]), copySign(mag[2], s[2]));
149}
150
152KOKKOS_INLINE_FUNCTION scalar componentMag(const scalar value) { return Kokkos::abs(value); }
153
156KOKKOS_INLINE_FUNCTION Vec3 componentMag(const Vec3& value)
157{
158 return Vec3(Kokkos::abs(value[0]), Kokkos::abs(value[1]), Kokkos::abs(value[2]));
159}
160
162KOKKOS_INLINE_FUNCTION scalar componentMax(const scalar lhs, const scalar rhs)
163{
164 return Kokkos::max(lhs, rhs);
165}
166
168KOKKOS_INLINE_FUNCTION Vec3 componentMax(const Vec3& lhs, const Vec3& rhs)
169{
170 return Vec3(
171 Kokkos::max(lhs[0], rhs[0]), Kokkos::max(lhs[1], rhs[1]), Kokkos::max(lhs[2], rhs[2])
172 );
173}
174
175/* @brief Apply equation (matrix) under-relaxation to an assembled LinearSystem.
176 *
177 * NeoN bakes boundary contributions permanently into the CSR diagonal at assembly time,
178 * so the augmented diagonal `D_aug = matrix.values[diagIdx(cell)]` already contains the
179 * boundary diagonal. This kernel relaxes the augmented diagonal DIRECTLY. Per cell:
180 *
181 * D_aug : matrix.values[diagIdx(cell)] (augmented, boundary-baked)
182 * D_dom : max(mag(D_aug), sumMagOffDiag[cell]) (dominance clamp on the augmented diag)
183 * D_relaxed : componentCopySign(D_dom / alpha, sign) (sign: the system's convention, taken
184 * from the summed diagonal; OpenFOAM's D = max(|D|, sumOff) for a positive system)
185 * write : matrix.values[diagIdx(cell)] = D_relaxed
186 * source : rhs[cell] += (D_relaxed - D_aug) * psi_prev[cell]
187 *
188 * The source correction makes the relaxed system share the fixed point of the
189 * unrelaxed system (the correction cancels at the converged solution). `psi_prev`
190 * is the field value at solve entry (`solution.internalVector()` — no separate snapshot).
191 * The negative-diagonal sign convention is preserved componentwise via `componentCopySign`
192 * so `rAU`/`HbyA` stay correct for alpha < 1.
193 *
194 * @param ls The assembled LinearSystem (mutated in place on the augmented diagonal).
195 * @param solution The solution VolumeField — supplies psi_prev (internalVector).
196 * @param alpha The under-relaxation factor. alpha <= 0 or alpha == 1 is a bitwise no-op.
197 */
198// Overload set is templated on the FULL LinearSystem parameter pack (mirroring
199// removeBoundaryContributions, linearSystem.hpp) rather than LinearSystem<ElementType>.
200// This matters because the real momentum system assembled by
201// the DSL is the SEGREGATED vector-solve form — a SCALAR matrix (MatrixValueType == scalar) with
202// a Vec3 RHS (RHSValueType == Vec3) — not LinearSystem<Vec3>. The diagonal/off-diagonal/boundary
203// algebra therefore runs in MatrixValueType (scalar here), while the source correction and field
204// read run in RHSValueType (Vec3 here); the cross term (dRelaxed - dAug) * field is
205// MatrixValueType * RHSValueType (scalar * Vec3 = Vec3), which the existing operator* already
206// supports. The synthetic NeoN unit tests use createEmptyLinearSystem<Vec3>(mesh) where
207// MatrixValueType == RHSValueType == Vec3, so both forms are now exercised.
208template<
209 typename VectorType,
210 typename MatrixValueType,
211 typename RHSValueType,
212 typename SystemMatrixType,
213 typename BoundaryMatrixType>
216 const VectorType& solution,
217 scalar alpha
218)
219{
220 // alpha<=0 guard: bitwise no-op. MUST be first so neither
221 // matrix.values nor rhs is touched when no relaxation is requested.
222 if (alpha <= 0.0 || alpha == 1.0)
223 {
224 return;
225 }
226
227 const scalar invAlpha = 1.0 / alpha;
228
229 auto lsView = ls.view();
230 auto& matrix = lsView.matrix;
231 auto& rhs = lsView.rhs;
232 const auto ma = ls.faceToMatrixAddress()->view(ls.matrix().sparsity()->rowOffs().view());
233 const auto [rowOffs, colIdxs] = views(ls.matrix().rowOffs(), ls.matrix().colIdxs());
234 const auto field = solution.internalVector().view();
235
236 const localIdx nCells = field.size();
237
238 // The system's sign convention, per component. OpenFOAM assembles with a positive central
239 // coefficient and fvMatrix::relax() makes every relaxed diagonal positive
240 // (D = max(|D|, sumOff)), so a row whose diagonal came out negative -- convection-dominated
241 // and not diagonally dominant, e.g. a bounded-convection cell with more outflow than inflow --
242 // is relaxed as a positive one. NeoN also relaxes systems assembled with the opposite overall
243 // sign, so the sign is taken from the summed diagonal rather than assumed, and every relaxed
244 // row gets it; copying each row's own sign would keep such a negative row negative. The sum
245 // is taken over all ranks, so the sign does not depend on the decomposition.
246 auto globalSum = [&](scalar& sum)
247 {
248#ifdef NF_WITH_MPI_SUPPORT
249 if (solution.mesh().boundaryMesh().isDistributed())
250 {
251 mpi::allReduce(sum, mpi::ReduceOp::Sum, ls.commPattern().env.comm());
252 }
253#else
254 (void)sum;
255#endif
256 };
257 auto convention = one<MatrixValueType>();
258 if constexpr (std::is_same_v<MatrixValueType, scalar>)
259 {
260 scalar sumDiag = 0;
262 ls.exec(),
263 {0, nCells},
264 NEON_LAMBDA(const localIdx celli, scalar& sum) {
265 sum += matrix.values[ma.diagIdx(celli)];
266 },
267 sumDiag
268 );
269 globalSum(sumDiag);
270 convention = sumDiag >= 0 ? scalar(1) : scalar(-1);
271 }
272 else
273 {
274 for (int cmpt = 0; cmpt < 3; ++cmpt)
275 {
276 scalar sumDiag = 0;
278 ls.exec(),
279 {0, nCells},
280 NEON_LAMBDA(const localIdx celli, scalar& sum) {
281 sum += matrix.values[ma.diagIdx(celli)][cmpt];
282 },
283 sumDiag
284 );
285 globalSum(sumDiag);
286 convention[cmpt] = sumDiag >= 0 ? scalar(1) : scalar(-1);
287 }
288 }
289
290 // FUSED single-pass relaxation: compute the off-diagonal magnitude sum inline and apply
291 // the dominance clamp + diagonal boost + source correction in ONE kernel, eliminating the
292 // per-call O(nCells) `sumOff` scratch allocation. Each cell needs only its OWN row's
293 // off-diagonal sum — no cross-cell dependency — and relaxation only ever writes a cell's own
294 // diagonal (matrix.values[diagIdx]) and rhs[celli]. The row walk skips the diagonal
295 // (colIdxs[idx] != celli), and a cell's diagonal write never aliases another cell's
296 // off-diagonal storage.
297 //
298 // componentCopySign gives the relaxed diagonal the system's sign so rAU = V/diag stays correct
299 // for alpha < 1 under either convention.
300 // The source correction rhs += (dRelaxed - dAug)*psi_prev makes the relaxed system share
301 // the unrelaxed fixed point. Off-diagonal sum + diagonal algebra are in MatrixValueType;
302 // the source-correction cross term (dRelaxed - dAug)*field is MatrixValueType * RHSValueType
303 // (scalar * Vec3 in the segregated momentum form).
305 ls.exec(),
306 {0, nCells},
307 NEON_LAMBDA(const localIdx celli) {
308 // Off-diagonal magnitude sum — cell-based CSR row gather, NO atomics (perf lever).
309 auto sumOff = zero<MatrixValueType>();
310 for (localIdx idx = rowOffs[celli]; idx < rowOffs[celli + 1]; ++idx)
311 {
312 if (colIdxs[idx] != celli)
313 {
314 sumOff = sumOff + componentMag(matrix.values[idx]);
315 }
316 }
317 const auto diagIdx = ma.diagIdx(celli);
318 const auto dAug = matrix.values[diagIdx]; // augmented, boundary-baked
319 const auto dDom = componentMax(componentMag(dAug), sumOff); // dominance clamp
320 // scale whole augmented diag by 1/alpha
321 const auto dRelaxed = componentCopySign(dDom * invAlpha, convention);
322 matrix.values[diagIdx] = dRelaxed;
323 rhs[celli] = rhs[celli] + (dRelaxed - dAug) * field[celli]; // source corr
324 },
325 "applyMatrixRelaxation"
326 );
327}
328
329// ---------------------------------------------------------------------------
330// Field (explicit) under-relaxation
331// ---------------------------------------------------------------------------
332
333/* @brief Apply explicit field under-relaxation to a solution field's internal vector.
334 *
335 * Blends the internal field toward the previous outer-iteration value:
336 *
337 * psi[c] = prev[c] + alpha * (psi[c] - prev[c])
338 *
339 * `prev` is the caller-owned previous-iteration snapshot (e.g. from
340 * `fieldRelaxationSnapshot`, taken at the top of the outer corrector).
341 *
342 * Only the internal vector is blended; the caller is responsible for calling
343 * `solution.correctBoundaryConditions()` afterwards so boundary values are
344 * re-derived from the boundary conditions.
345 *
346 * `alpha <= 0` or `alpha == 1` is a bitwise no-op (the early return touches nothing).
347 * This is REQUIRED so the final outer iteration (`alpha == 1`) and an unset
348 * factor leave the field byte-for-byte unchanged, side-stepping the `alpha == 1` ULP
349 * round-trip trap of `prev + 1*(cur - prev)`.
350 *
351 * @param solution The solution VolumeField — its internal vector is blended in place.
352 * @param previous The previous-iteration snapshot of the internal vector (deep copy).
353 * @param alpha The under-relaxation factor. alpha <= 0 or alpha == 1 is a bitwise no-op.
354 */
355template<typename VectorType>
357 VectorType& solution, const Vector<typename VectorType::ElementType>& previous, scalar alpha
358)
359{
360 // Bitwise no-op guard: MUST be first so the internal vector is not touched when no
361 // relaxation is requested (final iteration / unset factor, alpha==1 ULP trap).
362 if (alpha <= 0.0 || alpha == 1.0)
363 {
364 return;
365 }
366
367 NF_ASSERT(solution.size() == previous.size(), "applyFieldRelaxation: field/prev size mismatch");
368
369 auto [current, prev] = views(solution.internalVector(), previous);
371 solution.exec(),
372 {0, solution.size()},
373 NEON_LAMBDA(const localIdx celli) {
374 current[celli] = prev[celli] + alpha * (current[celli] - prev[celli]);
375 },
376 "applyFieldRelaxation"
377 );
378}
379
380/* @brief Snapshot a field's internal vector for use as the `previous` arg to
381 * `applyFieldRelaxation` (caller-owned prevIter primitive).
382 *
383 * Returns an independent on-executor deep copy of `field.internalVector()` via the
384 * `Vector` copy constructor — subsequent mutation of `field` does not affect the
385 * returned snapshot. Do NOT hand-roll a `parallelFor` copy; the copy ctor already
386 * performs an executor-correct deep copy.
387 */
388template<typename VectorType>
389[[nodiscard]] auto fieldRelaxationSnapshot(const VectorType& field)
390{
391 return Vector<typename VectorType::ElementType>(field.internalVector());
392}
393
394} // namespace dsl
A class representing a dictionary that stores key-value pairs.
Dictionary & subDict(const std::string &key)
Retrieves a sub-dictionary associated with the given key.
A class for the representation of a 3D Vec3.
Definition vec3.hpp:24
An executor-aware contiguous container for numerical data with vector-style arithmetic semantics.
Definition vector.hpp:40
sizeType size() const
Returns the number of elements in the Vector.
Definition vector.hpp:332
const std::vector< TemporalOperator< ValueType > > & temporalOperators() const
void read(const Dictionary &input)
const std::vector< SpatialOperator< ValueType > > & spatialOperators() const
A class representing a linear system of equations.
Vector< RHSValueType > & rhs()
std::shared_ptr< const FaceToMatrixAddress > faceToMatrixAddress() const
LinearSystemView< RHSValueType, MatrixView< MatrixValueType, SparsityView< typename SystemMatrixType::MatrixSparsityType::SparsityIndexType > > > view() &&=delete
const Executor & exec() const
SystemMatrixType & matrix()
#define NF_ERROR_EXIT(message)
Macro for printing an error message and aborting the program.
Definition error.hpp:90
#define NF_ASSERT(condition, message)
Macro for asserting a condition and printing an error message if the condition is false.
Definition error.hpp:118
la::SolverStats iterativeSolveImpl(Expression< typename VectorType::ElementType > &exp, la::LinearSystem< typename VectorType::ElementType > &ls, VectorType &solution, scalar t, scalar dt, const Dictionary &fvSchemes, const Dictionary &fvSolution, std::vector< const PostAssemblyBase< typename VectorType::ElementType, IndexType > * > ps={})
Definition solver.hpp:35
void applyFieldRelaxation(VectorType &solution, const Vector< typename VectorType::ElementType > &previous, scalar alpha)
Definition solver.hpp:356
KOKKOS_INLINE_FUNCTION scalar componentMag(const scalar value)
Componentwise magnitude (scalar overload).
Definition solver.hpp:152
KOKKOS_INLINE_FUNCTION scalar componentMax(const scalar lhs, const scalar rhs)
Componentwise max (scalar overload).
Definition solver.hpp:162
KOKKOS_INLINE_FUNCTION scalar copySign(const scalar mag, const scalar s)
Returns |mag| carrying the sign of s (scalar overload).
Definition solver.hpp:134
auto fieldRelaxationSnapshot(const VectorType &field)
Definition solver.hpp:389
void applyMatrixRelaxation(la::LinearSystem< MatrixValueType, RHSValueType, SystemMatrixType, BoundaryMatrixType > &ls, const VectorType &solution, scalar alpha)
Definition solver.hpp:214
ExpressionType optimize(const ExpressionType &in)
Apply the default optimizer pipeline to an expression.
std::optional< la::SolverStats > solve(Expression< typename VectorType::ElementType, IndexType > &exp, VectorType &solution, scalar t, scalar dt, const Dictionary &fvSchemes, const Dictionary &fvSolution, std::vector< const PostAssemblyBase< typename VectorType::ElementType, IndexType > * > p={})
Definition solver.hpp:98
KOKKOS_INLINE_FUNCTION scalar componentCopySign(const scalar mag, const scalar s)
Componentwise sign-copy (scalar overload).
Definition solver.hpp:140
void fence(const Executor &exec)
Definition executor.hpp:24
KOKKOS_INLINE_FUNCTION T zero()
KOKKOS_INLINE_FUNCTION scalar mag(const scalar &s)
Definition scalar.hpp:23
KOKKOS_INLINE_FUNCTION T one()
float scalar
Definition scalar.hpp:17
void parallelFor(const ExecutorType &, std::pair< localIdx, localIdx > range, const Kernel &kernel, std::string name)
int32_t localIdx
Definition label.hpp:50
auto views(Types &... args)
Unpacks all views of the passed classes.
Definition view.hpp:108
void parallelReduce(const Executor &exec, std::pair< localIdx, localIdx > range, const Kernel &kernel, T &value)
#define NEON_LAMBDA