NeoN
A framework for CFD software
Loading...
Searching...
No Matches
expression.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 <algorithm>
8#include <vector>
9
10#include "NeoN/core/error.hpp"
14#include "NeoN/fields/field.hpp"
21#ifdef NF_WITH_MPI_SUPPORT
23#endif
24
27
28namespace NeoN::dsl
29{
30
31template<typename VectorType, typename IndexType>
33{
34 virtual ~PostAssemblyBase() = default;
35 virtual void
37 const {};
38
48};
49
65template<typename ValueType, typename IndexType = localIdx>
66class SetReference : public PostAssemblyBase<ValueType, IndexType>
67{
68public:
69
70 SetReference(localIdx refCell, ValueType refValue) : refCell_(refCell), refValue_(refValue) {}
71
73 ) const override
74 {
75#ifdef NF_WITH_MPI_SUPPORT
76 // For distributed systems, only the rank owning refCell applies the constraint.
77 // For non-distributed systems (each rank holds a full copy), every rank applies it.
78 if (!ls.commPattern().sendCounts.empty())
79 {
80 mpi::Environment mpiEnv;
81 if (mpiEnv.isInitialized() && mpiEnv.rank() != 0) return;
82 }
83#endif
84 auto lsView = ls.view();
85 const auto ma = ls.faceToMatrixAddress()->view(ls.matrix().sparsity()->rowOffs().view());
86 auto refVal = refValue_;
87 auto refCell = refCell_;
89 ls.exec(),
90 {refCell, refCell + 1},
91 NEON_LAMBDA(const localIdx celli) {
92 auto dIdx = ma.diagIdx(celli);
93 auto diagVal = lsView.matrix.values[dIdx];
94 lsView.rhs[celli] += diagVal * refVal;
95 lsView.matrix.values[dIdx] += diagVal;
96 },
97 "SetReference"
98 );
99 }
100
105 scalar,
106 ValueType,
108 la::COOMatrix<scalar, IndexType>>& ls) const override
109 {
110#ifdef NF_WITH_MPI_SUPPORT
111 // For distributed systems, only the rank owning refCell applies the constraint.
112 // For non-distributed systems (each rank holds a full copy), every rank applies it.
113 if (!ls.commPattern().sendCounts.empty())
114 {
115 mpi::Environment mpiEnv;
116 if (mpiEnv.isInitialized() && mpiEnv.rank() != 0) return;
117 }
118#endif
119 auto lsView = ls.view();
120 const auto ma = ls.faceToMatrixAddress()->view(ls.matrix().sparsity()->rowOffs().view());
121 auto refVal = refValue_;
122 auto refCell = refCell_;
124 ls.exec(),
125 {refCell, refCell + 1},
126 NEON_LAMBDA(const localIdx celli) {
127 auto dIdx = ma.diagIdx(celli);
128 auto diagVal = lsView.matrix.values[dIdx];
129 lsView.rhs[celli] += diagVal * refVal;
130 lsView.matrix.values[dIdx] += diagVal;
131 },
132 "SetReference"
133 );
134 }
135
136private:
137
138 localIdx refCell_;
139 ValueType refValue_;
140};
141
142
173template<typename ValueType, typename IndexType = localIdx>
174class FixedValueConstraints : public PostAssemblyBase<ValueType, IndexType>
175{
176 static_assert(
177 std::is_same_v<ValueType, scalar>,
178 "FixedValueConstraints only supports scalar fields. "
179 "For non-scalar fields implement applyScalarMatrix()."
180 );
181
182public:
183
185 : mask_(mask), values_(values), nCells_(nCells)
186 {}
187
189 ) const override
190 {
191 auto lsView = ls.view();
192 const auto rowOffs = ls.matrix().sparsity()->rowOffs().view();
193 const auto colIdxs = ls.matrix().sparsity()->colIdxs().view();
194 auto matrixValues = lsView.matrix.values;
195 auto rhs = lsView.rhs;
196 auto mask = mask_;
197 auto vals = values_;
198 // Sweep EVERY row (not only the pinned ones): a pinned row drops its off-diagonals, while
199 // a NON-pinned row that couples into a pinned column relocates that term to its own source
200 // and zeros it (OpenFOAM's column cut). Parallelising over rows means each row owns its own
201 // rhs entry and its own off-diagonal slots, so no atomics are needed.
203 ls.exec(),
204 {0, nCells_},
205 NEON_LAMBDA(const localIdx row) {
206 const bool rowPinned = mask[row] != scalar(0);
207 ValueType diagVal = zero<ValueType>();
208 for (auto o = rowOffs[row]; o < rowOffs[row + 1]; ++o)
209 {
210 const auto col = colIdxs[o];
211 if (col == row)
212 {
213 diagVal = matrixValues[o];
214 continue;
215 }
216 if (rowPinned)
217 {
218 // pinned cell's own row: decouple it entirely
219 matrixValues[o] = zero<ValueType>();
220 }
221 else if (mask[col] != scalar(0))
222 {
223 // neighbour row coupling INTO a pinned cell: move the term to this row's
224 // source as a constant, then drop the coefficient (OF setValues column cut)
225 rhs[row] -= matrixValues[o] * vals[col];
226 matrixValues[o] = zero<ValueType>();
227 }
228 }
229 if (rowPinned)
230 {
231 // row now reads A[c,c]*x_c = A[c,c]*value[c] => x_c = value[c]
232 rhs[row] = diagVal * vals[row];
233 }
234 },
235 "FixedValueConstraints"
236 );
237 // Zero offDiagonalMatrix entries for pinned rows so that proc-boundary
238 // couplings do not contribute to the residual of constrained cells.
239 auto& offDiag = ls.offDiagonalMatrix();
240 const localIdx nnz = offDiag.nNonZeros();
241 if (nnz > 0)
242 {
243 const auto offRowIdxs = offDiag.sparsity()->rowIdxs().view();
244 auto offValues = offDiag.values().view();
246 ls.exec(),
247 {0, nnz},
248 NEON_LAMBDA(const localIdx i) {
249 if (mask[offRowIdxs[i]] != scalar(0)) offValues[i] = zero<ValueType>();
250 },
251 "FixedValueConstraints::offDiag"
252 );
253 }
254 }
255
256private:
257
258 View<const scalar> mask_;
259 View<const ValueType> values_;
260 localIdx nCells_;
261};
262
263
264template<typename ValueType, typename IndexType = localIdx>
266{
267public:
268
269 using ExpressionValueType = ValueType;
270
271 Expression(const Executor& exec) : exec_(exec), temporalOperators_(), spatialOperators_() {}
272
274 : exec_(exp.exec_), temporalOperators_(exp.temporalOperators_),
275 spatialOperators_(exp.spatialOperators_)
276 {}
277
279 : exec_(oper.exec()), temporalOperators_(), spatialOperators_()
280 {
281 spatialOperators_.push_back(oper);
282 }
283
285 {
286 if (this == &exp)
287 {
288 return *this;
289 }
290 NF_ASSERT(exec_ == exp.exec_, "Executors are not the same");
291 temporalOperators_ = exp.temporalOperators_;
292 spatialOperators_ = exp.spatialOperators_;
293 return *this;
294 }
295
296
298 : exec_(oper.exec()), temporalOperators_(), spatialOperators_()
299 {
300 temporalOperators_.push_back(oper);
301 }
302
303 /* @brief dispatch read call to operator */
304 void read(const Dictionary& input)
305 {
306 for (auto& op : temporalOperators_)
307 {
308 op.read(input);
309 }
310 for (auto& op : spatialOperators_)
311 {
312 op.read(input);
313 }
314 }
315
316 /* @brief perform all explicit operation and accumulate the result */
318 {
319 Vector<ValueType> source(exec_, nCells, zero<ValueType>());
320 // accumulate in place and return the local: returning explicitOperation(source) would
321 // copy-construct the result from the reference (allocation + full device copy)
322 accumulateExplicitOperation(source);
323 return source;
324 }
325
326 /* @brief perform all explicit operation and accumulate the result */
328 {
329 accumulateExplicitOperation(source);
330 return source;
331 }
332
334 {
335 for (auto& op : temporalOperators_)
336 {
337 if (op.getType() == Operator::Type::Explicit)
338 {
339 op.explicitOperation(source, t, dt);
340 }
341 }
342 return source;
343 }
344
346 template<typename AssemblyType = ValueType>
348 {
349 for (auto& op : spatialOperators_)
350 {
351 if (op.getType() == Operator::Type::Implicit)
352 {
353 op.implicitOperation(ls);
354 }
355 }
356 }
357
361 template<typename AssemblyType = ValueType>
364 ) const
365 {
366 for (auto& op : temporalOperators_)
367 {
368 if (op.getType() == Operator::Type::Implicit)
369 {
370 op.implicitOperation(ls, t, dt);
371 }
372 }
373 }
374
375 /*@brief subtract explicit source terms from the linear system rhs, scaled by cell volumes */
376 template<typename AssemblyType = ValueType>
379 ) const
380 {
381 auto expTmp = explicitOperation(mesh.nCells());
382 auto [vol, expSource, rhs] = views(mesh.cellVolumes(), expTmp, ls.rhs());
384 ls.exec(),
385 {0, static_cast<localIdx>(rhs.size())},
386 NEON_LAMBDA(const localIdx i) { rhs[i] -= expSource[i] * vol[i]; }
387 );
388 }
389
395 template<typename AssemblyType = ValueType>
397 const UnstructuredMesh& mesh,
398 scalar t,
399 scalar dt,
400 std::vector<const PostAssemblyBase<ValueType, IndexType>*> ps = {}
401 ) const
402 {
404 assemble<AssemblyType>(t, dt, ls, mesh, ps);
405 return ls;
406 }
407
412 template<typename AssemblyType = ValueType>
414 scalar t,
415 scalar dt,
417 const UnstructuredMesh& mesh,
418 std::vector<const PostAssemblyBase<ValueType, IndexType>*> ps = {}
419 ) const
420 {
421 assemble<AssemblyType>(t, dt, ls, ps);
422 assembleExplicitSource(ls, mesh);
423 }
424
425 /* @brief assemble into a given linear system (implicit operators only, no explicit sources)
426 *
427 * @param ps post-assembly functors applied to the system after assembly
428 */
429 template<typename AssemblyType = ValueType>
431 scalar t,
432 scalar dt,
434 std::vector<const PostAssemblyBase<ValueType, IndexType>*> ps = {}
435 ) const
436 {
437 assembleSpatialOperator(ls); // add spatial operator
438 assembleTemporalOperator(ls, t, dt); // add temporal operators
439
440 // Post-assembly functors apply on the same-type form via operator(); the segregated
441 // scalar-matrix / ValueType-rhs form dispatches to applyScalarMatrix instead.
442 if constexpr (std::is_same_v<AssemblyType, ValueType>)
443 {
444 for (const auto* p : ps)
445 {
446 (*p)(ls);
447 }
448 }
449 else if constexpr (std::is_same_v<AssemblyType, scalar>)
450 {
451 for (const auto* p : ps)
452 {
453 p->applyScalarMatrix(ls);
454 }
455 }
456 }
457
458 void addOperator(const SpatialOperator<ValueType>& oper) { spatialOperators_.push_back(oper); }
459
461 {
462 temporalOperators_.push_back(oper);
463 }
464
465 void addExpression(const Expression& equation)
466 {
467 for (auto& op : equation.temporalOperators_)
468 {
469 temporalOperators_.push_back(op);
470 }
471 for (auto& op : equation.spatialOperators_)
472 {
473 spatialOperators_.push_back(op);
474 }
475 }
476
478 template<typename OperatorType, Operator::Type Type>
479 bool hasOperatorOfType(const std::string& name) const
480 {
481 auto opType = Type;
482 auto matchNameAndType = [name, opType](const auto& op)
483 { return op.getName() == name && op.getType() == opType; };
484 if constexpr (std::is_same_v<OperatorType, SpatialOperator<ValueType>>)
485 {
486 return std::ranges::any_of(spatialOperators_, matchNameAndType);
487 }
488 else if constexpr (std::is_same_v<OperatorType, TemporalOperator<ValueType>>)
489 {
490 return std::ranges::any_of(temporalOperators_, matchNameAndType);
491 }
492 return false;
493 }
494
496 template<Operator::Type Type>
497 bool hasOperator(const std::string& name) const
498 {
501 }
502
504 template<typename OperatorType, Operator::Type Type>
505 OperatorType& getOperator(const std::string& name)
506 {
508 {
509 throw std::runtime_error {"No operator with given name and type found"};
510 }
511 auto opType = Type;
512 auto matchNameAndType = [name, opType](const auto& op)
513 { return op.getName() == name && op.getType() == opType; };
514 if constexpr (std::is_same_v<OperatorType, SpatialOperator<ValueType>>)
515 {
516 return *std::ranges::find_if(spatialOperators_, matchNameAndType);
517 }
518 else if constexpr (std::is_same_v<OperatorType, TemporalOperator<ValueType>>)
519 {
520 return *std::ranges::find_if(temporalOperators_, matchNameAndType);
521 }
522 throw std::runtime_error {"Unknown operator type"};
523 // should never be reached, shut up compiler warning
524 return spatialOperators_[0];
525 }
526
528 template<Operator::Type Type>
529 void dropOperator(const std::string& name)
530 {
532 {
533 throw std::runtime_error {"No operator with given name and type found"};
534 }
535 auto opType = Type;
536 auto matchNameAndType = [name, opType](const auto& op)
537 { return op.getName() == name && op.getType() == opType; };
539 {
540 std::erase_if(spatialOperators_, matchNameAndType);
541 }
542 else
543 {
544 std::erase_if(temporalOperators_, matchNameAndType);
545 }
546 }
547
548 /* @brief getter for the total number of terms in the equation */
550 {
551 return static_cast<localIdx>(temporalOperators_.size() + spatialOperators_.size());
552 }
553
554 // getters
555 const std::vector<TemporalOperator<ValueType>>& temporalOperators() const
556 {
557 return temporalOperators_;
558 }
559
560 const std::vector<SpatialOperator<ValueType>>& spatialOperators() const
561 {
562 return spatialOperators_;
563 }
564
565 std::vector<TemporalOperator<ValueType>>& temporalOperators() { return temporalOperators_; }
566
567 std::vector<SpatialOperator<ValueType>>& spatialOperators() { return spatialOperators_; }
568
569 const Executor& exec() const { return exec_; }
570
571private:
572
573 /* @brief add all explicit spatial operations to source in place */
574 void accumulateExplicitOperation(Vector<ValueType>& source) const
575 {
576 for (auto& op : spatialOperators_)
577 {
578 if (op.getType() == Operator::Type::Explicit)
579 {
580 op.explicitOperation(source);
581 }
582 }
583 }
584
585 const Executor exec_;
586
587 std::vector<TemporalOperator<ValueType>> temporalOperators_;
588
589 std::vector<SpatialOperator<ValueType>> spatialOperators_;
590};
591
592template<typename ValueType>
593[[nodiscard]] inline Expression<ValueType>
595{
596 lhs.addExpression(rhs);
597 return lhs;
598}
599
600template<typename ValueType>
601[[nodiscard]] inline Expression<ValueType>
603{
604 lhs.addOperator(rhs);
605 return lhs;
606}
607
608template<typename leftOperator, typename rightOperator>
609[[nodiscard]] inline Expression<typename leftOperator::VectorValueType>
610operator+(leftOperator lhs, rightOperator rhs)
611{
612 using ValueType = typename leftOperator::VectorValueType;
613 Expression<ValueType> expr(lhs.exec());
614 expr.addOperator(lhs);
615 expr.addOperator(rhs);
616 return expr;
617}
618
619template<typename ValueType>
620[[nodiscard]] inline Expression<ValueType> operator*(scalar scale, const Expression<ValueType>& es)
621{
622 Expression<ValueType> expr(es.exec());
623 for (const auto& oper : es.temporalOperators())
624 {
625 expr.addOperator(scale * oper);
626 }
627 for (const auto& oper : es.spatialOperators())
628 {
629 expr.addOperator(scale * oper);
630 }
631 return expr;
632}
633
634
635template<typename ValueType>
636[[nodiscard]] inline Expression<ValueType>
638{
639 lhs.addExpression(-1.0 * rhs);
640 return lhs;
641}
642
643template<typename ValueType>
644[[nodiscard]] inline Expression<ValueType>
646{
647 lhs.addOperator(-1.0 * rhs);
648 return lhs;
649}
650
651template<typename leftOperator, typename rightOperator>
652[[nodiscard]] inline Expression<typename leftOperator::VectorValueType>
653operator-(leftOperator lhs, rightOperator rhs)
654{
655 using ValueType = typename leftOperator::VectorValueType;
656 Expression<ValueType> expr(lhs.exec());
657 expr.addOperator(lhs);
658 expr.addOperator(Coeff(-1) * rhs);
659 return expr;
660}
661
662
663} // namespace dsl
A class representing a dictionary that stores key-value pairs.
Represents an unstructured mesh in NeoN.
const scalarVector & cellVolumes() const
Get the field of cell volumes in the mesh.
sizeType nCells() const
Get the number of cells in the mesh.
An executor-aware contiguous container for numerical data with vector-style arithmetic semantics.
Definition vector.hpp:40
A class that represents a coefficient for the NeoN dsl.
Definition coeff.hpp:24
Expression & operator=(const Expression &exp)
void assemble(scalar t, scalar dt, la::LinearSystem< AssemblyType, ValueType > &ls, std::vector< const PostAssemblyBase< ValueType, IndexType > * > ps={}) const
la::LinearSystem< AssemblyType, ValueType > assemble(const UnstructuredMesh &mesh, scalar t, scalar dt, std::vector< const PostAssemblyBase< ValueType, IndexType > * > ps={}) const
construct a linear system and force assembly including explicit source terms
std::vector< TemporalOperator< ValueType > > & temporalOperators()
Expression(const SpatialOperator< ValueType > &oper)
void assembleTemporalOperator(la::LinearSystem< AssemblyType, ValueType > &ls, scalar t, scalar dt) const
compute matrix coefficients based on all temporal operators assemble directly into linear system
Vector< ValueType > explicitOperation(Vector< ValueType > &source) const
Expression(const TemporalOperator< ValueType > &oper)
std::vector< SpatialOperator< ValueType > > & spatialOperators()
Expression(const Expression &exp)
bool hasOperatorOfType(const std::string &name) const
returns operator of given type and name exists
const std::vector< TemporalOperator< ValueType > > & temporalOperators() const
void dropOperator(const std::string &name)
removes operator of given name
void assembleSpatialOperator(la::LinearSystem< AssemblyType, ValueType > &ls) const
compute matrix coefficients based on all spatial operators
void read(const Dictionary &input)
void addOperator(const TemporalOperator< ValueType > &oper)
localIdx size() const
void assemble(scalar t, scalar dt, la::LinearSystem< AssemblyType, ValueType > &ls, const UnstructuredMesh &mesh, std::vector< const PostAssemblyBase< ValueType, IndexType > * > ps={}) const
assemble into a given linear system including explicit source terms
OperatorType & getOperator(const std::string &name)
returns operator of given type and name
bool hasOperator(const std::string &name) const
returns whether the expression contains an operator with a given name
void addExpression(const Expression &equation)
void assembleExplicitSource(la::LinearSystem< AssemblyType, ValueType > &ls, const UnstructuredMesh &mesh) const
Vector< ValueType > explicitOperation(Vector< ValueType > &source, scalar t, scalar dt) const
void addOperator(const SpatialOperator< ValueType > &oper)
const Executor & exec() const
const std::vector< SpatialOperator< ValueType > > & spatialOperators() const
Vector< ValueType > explicitOperation(sizeType nCells) const
ValueType ExpressionValueType
Expression(const Executor &exec)
void operator()(la::LinearSystem< ValueType, ValueType, la::CSRMatrix< ValueType, IndexType > > &ls) const override
FixedValueConstraints(View< const scalar > mask, View< const ValueType > values, localIdx nCells)
SetReference(localIdx refCell, ValueType refValue)
void applyScalarMatrix(la::LinearSystem< scalar, ValueType, la::CSRMatrix< scalar, IndexType >, la::COOMatrix< scalar, IndexType > > &ls) const override
Segregated scalar-matrix / ValueType-rhs form. The scalar diagonal scales the ValueType reference val...
void operator()(la::LinearSystem< ValueType, ValueType, la::CSRMatrix< ValueType, IndexType > > &ls) const override
A class representing a linear system of equations.
Vector< RHSValueType > & rhs()
const Executor & exec() const
#define NF_ASSERT(condition, message)
Macro for asserting a condition and printing an error message if the condition is false.
Definition error.hpp:118
Expression< ValueType > operator+(Expression< ValueType > lhs, const Expression< ValueType > &rhs)
Coeff operator*(const Coeff &lhs, const Coeff &rhs)
Definition coeff.hpp:61
Expression< ValueType > operator-(Expression< ValueType > lhs, const Expression< ValueType > &rhs)
Matrix< ValueType, la::CooSparsityPattern< IndexType > > COOMatrix
Definition matrix.hpp:264
Matrix< ValueType, la::CsrSparsityPattern< IndexType > > CSRMatrix
Definition matrix.hpp:261
LinearSystem< ValueType, RHSValueType, SystemMatrixType, BoundaryMatrixType > createEmptyLinearSystem(const UnstructuredMesh &mesh, std::shared_ptr< MeshIterationStrategy > strategy=std::make_shared< FaceBasedIterator >())
std::variant< SerialExecutor, CPUExecutor, GPUExecutor > Executor
Definition executor.hpp:21
KOKKOS_INLINE_FUNCTION T zero()
float scalar
Definition scalar.hpp:17
std::size_t sizeType
Definition label.hpp:56
void parallelFor(const ExecutorType &, std::pair< localIdx, localIdx > range, const Kernel &kernel, std::string name)
const std::string & name(const NeoN::Document &doc)
Retrieves the name of a Document.
int32_t localIdx
Definition label.hpp:50
auto views(Types &... args)
Unpacks all views of the passed classes.
Definition view.hpp:108
#define NEON_LAMBDA
virtual void operator()(la::LinearSystem< VectorType, VectorType, la::CSRMatrix< VectorType, IndexType > > &) const
virtual ~PostAssemblyBase()=default
virtual void applyScalarMatrix(la::LinearSystem< scalar, VectorType, la::CSRMatrix< scalar, IndexType >, la::COOMatrix< scalar, IndexType > > &) const
Apply to the segregated scalar-matrix / VectorType-rhs form (a scalar coefficient matrix with a Vecto...