NeoN
A framework for CFD software
Loading...
Searching...
No Matches
boundaryData.hpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2024 - 2026 NeoN authors
2//
3// SPDX-License-Identifier: MIT
4
5#pragma once
6
11
12#include <vector>
13#include <utility>
14#include <cstdio>
15#include <algorithm>
16
17#ifdef NF_WITH_MPI_SUPPORT
18#include <mpi.h>
19#include <optional>
24#endif
25
26namespace NeoN
27{
28
29
41template<typename ValueType>
43{
44
45public:
46
47 using BoundaryDataType = ValueType;
48
50 {
51 // commBuffers_ backs the memory of any in-flight MPI_Isend/MPI_Irecv calls.
52 // Destroying them while operations are pending is undefined behaviour, so
53 // drain all outstanding requests before the storage is freed.
54 waitAll();
55 }
56
62 : exec_(rhs.exec_), value_(rhs.value_), refValue_(rhs.refValue_),
63 valueFraction_(rhs.valueFraction_), refGrad_(rhs.refGrad_),
64 boundaryTypes_(rhs.boundaryTypes_), offset_(rhs.offset_), nBoundaries_(rhs.nBoundaries_),
65 nBoundaryFaces_(rhs.nBoundaryFaces_)
66 {}
67
77 : exec_((rhs.waitAll(), rhs.exec_)), value_(std::move(rhs.value_)),
78 refValue_(std::move(rhs.refValue_)), valueFraction_(std::move(rhs.valueFraction_)),
79 refGrad_(std::move(rhs.refGrad_)), boundaryTypes_(std::move(rhs.boundaryTypes_)),
80 offset_(std::move(rhs.offset_)), nBoundaries_(rhs.nBoundaries_),
81 nBoundaryFaces_(rhs.nBoundaryFaces_)
82 {}
83
84
90 : exec_(rhs.exec_), value_(exec, rhs.value_), refValue_(exec, rhs.refValue_),
91 valueFraction_(exec, rhs.valueFraction_), refGrad_(exec, rhs.refGrad_),
92 boundaryTypes_(exec, rhs.boundaryTypes_), offset_(SerialExecutor {}, rhs.offset_),
93 nBoundaries_(rhs.nBoundaries_), nBoundaryFaces_(rhs.nBoundaryFaces_)
94 {}
95
96
104 : exec_(exec), value_(exec, nBoundaryFaces, ValueType {}),
105 refValue_(exec, nBoundaryFaces, ValueType {}),
106 valueFraction_(exec, nBoundaryFaces, scalar(0)),
107 refGrad_(exec, nBoundaryFaces, ValueType {}), boundaryTypes_(exec, nBoundaryTypes),
108 offset_(SerialExecutor {}, nBoundaryTypes + 1), nBoundaries_(nBoundaryTypes),
109 nBoundaryFaces_(nBoundaryFaces)
110 {}
111
118 BoundaryData(const Executor& exec, const std::vector<localIdx>& offsets)
119 : BoundaryData(exec, offsets.back(), static_cast<localIdx>(offsets.size() - 1))
120 {
121 offset_ = Vector(SerialExecutor {}, offsets);
122 }
123
124
127 {
128 waitAll();
129 return value_;
130 }
131
139 {
140 waitAll();
141 return value_;
142 }
143
145 const Vector<ValueType>& refValue() const { return refValue_; }
146
151 Vector<ValueType>& refValue() { return refValue_; }
152
154 const Vector<scalar>& valueFraction() const { return valueFraction_; }
155
160 Vector<scalar>& valueFraction() { return valueFraction_; }
161
163 const Vector<ValueType>& refGrad() const { return refGrad_; }
164
169 Vector<ValueType>& refGrad() { return refGrad_; }
170
175 const Vector<int>& boundaryTypes() const { return boundaryTypes_; }
176
181 const Vector<localIdx>& offset() const { return offset_; }
182
187 sizeType nBoundaries() const { return nBoundaries_; }
188
193 sizeType nBoundaryFaces() const { return nBoundaryFaces_; }
194
200 {
201 return offset_.data()[patchId + 1] - offset_.data()[patchId];
202 }
203
204 const Executor& exec() { return exec_; }
205
207 {
208
209 // TODO maybe dont overwrite nBoundaries and nBoundaryFaces
210 // but use them for a sanity check
211 nBoundaries_ = rhs.nBoundaries_;
212 nBoundaryFaces_ = rhs.nBoundaryFaces_;
213
214 value_ = rhs.value_;
215 refValue_ = rhs.refValue_;
216 valueFraction_ = rhs.valueFraction_;
217 refGrad_ = rhs.refGrad_;
218 boundaryTypes_ = rhs.boundaryTypes_;
219 offset_ = rhs.offset_;
220 return *this;
221 }
222
223 // Non-const rvalue: with `const BoundaryData&&` the std::move calls below bound to the Vector
224 // copy assignments, so a move assignment copied every boundary vector.
226 {
227 // finish pending halo exchanges: ours would write into the replaced vectors, rhs's
228 // would refer to the moved buffers
229 waitAll();
230 rhs.waitAll();
231
232 // TODO maybe dont overwrite nBoundaries and nBoundaryFaces
233 // but use them for a sanity check
234 nBoundaries_ = rhs.nBoundaries_;
235 nBoundaryFaces_ = rhs.nBoundaryFaces_;
236
237 value_ = std::move(rhs.value_);
238 refValue_ = std::move(rhs.refValue_);
239 valueFraction_ = std::move(rhs.valueFraction_);
240 refGrad_ = std::move(rhs.refGrad_);
241 boundaryTypes_ = std::move(rhs.boundaryTypes_);
242 offset_ = std::move(rhs.offset_);
243 return *this;
244 }
245
246#ifdef NF_WITH_MPI_SUPPORT
247 void communicate(std::pair<localIdx, localIdx> range, int neighborRank)
248 {
249 const auto [rangeStart, rangeEnd] = range;
251 rangeEnd > rangeStart, "range ending index must be larger than range starting index"
252 );
253 const localIdx patchSize = rangeEnd - rangeStart;
254
255 mpi::Environment mpiEnv;
256 CommBuffer buf;
257 buf.rangeStart = rangeStart;
258 buf.patchSize = patchSize;
259
260 const auto byteCount =
261 static_cast<mpi_label_t>(patchSize) * static_cast<mpi_label_t>(sizeof(ValueType));
262 const auto neighborRankLabel = static_cast<mpi_label_t>(neighborRank);
263
264 // Deterministic, symmetric tag for the processor patch shared by (myRank, neighborRank).
265 // A unique tag per unordered rank pair, identical on both sides, makes each isend/irecv
266 // match its true partner regardless of posting order. min*P+max is symmetric so both
267 // ranks of the pair compute the same tag.
268 const auto nProcs = static_cast<mpi_label_t>(mpiEnv.sizeRank());
269 const auto myRankLabel = static_cast<mpi_label_t>(mpiEnv.rank());
270 const mpi_label_t pairTag = std::min(myRankLabel, neighborRankLabel) * nProcs
271 + std::max(myRankLabel, neighborRankLabel);
272
273 const bool useGpuPath = mpiEnv.gpuAwareMpi() && std::holds_alternative<GPUExecutor>(exec_);
274
275 MPI_Request sendReq, recvReq;
276 if (useGpuPath)
277 {
278 buf.deviceRecvBuf = Vector<ValueType>(exec_, patchSize, ValueType {});
279 // The zero-fill above is an asynchronous kernel and MPI does not order against it:
280 // without a fence it can overwrite halo data that already arrived through irecv.
281 fence(exec_);
282 mpi::isend<char>(
283 reinterpret_cast<const char*>(value_.data() + rangeStart),
284 byteCount,
285 neighborRankLabel,
286 pairTag,
287 mpiEnv.comm(),
288 &sendReq
289 );
290 mpi::irecv<char>(
291 reinterpret_cast<char*>(buf.deviceRecvBuf->data()),
292 byteCount,
293 neighborRankLabel,
294 pairTag,
295 mpiEnv.comm(),
296 &recvReq
297 );
298 }
299 else
300 {
301 auto valH = value_.copyToHost();
302 buf.sendBuf.resize(static_cast<sizeType>(patchSize));
303 buf.recvBuf.resize(static_cast<sizeType>(patchSize));
304 for (localIdx k = 0; k < patchSize; k++)
305 buf.sendBuf[static_cast<sizeType>(k)] = valH.view()[rangeStart + k];
306 mpi::isend<char>(
307 reinterpret_cast<const char*>(buf.sendBuf.data()),
308 byteCount,
309 neighborRankLabel,
310 pairTag,
311 mpiEnv.comm(),
312 &sendReq
313 );
314 mpi::irecv<char>(
315 reinterpret_cast<char*>(buf.recvBuf.data()),
316 byteCount,
317 neighborRankLabel,
318 pairTag,
319 mpiEnv.comm(),
320 &recvReq
321 );
322 }
323 communicating_ = true;
324 requests_.push_back(sendReq);
325 requests_.push_back(recvReq);
326 commBuffers_.push_back(std::move(buf));
327 }
328
329 bool isComplete() const
330 {
331 if (requests_.empty() || !communicating_) return true;
332 for (auto& req : requests_)
333 {
334 if (!mpi::test(&req)) return false;
335 }
336 communicating_ = false;
337 return true;
338 }
339
340
341#endif
342
343 void waitAll() const
344 {
345#ifdef NF_WITH_MPI_SUPPORT
346 if (requests_.empty() || !communicating_) return;
347 while (!isComplete())
348 {
349 }
350 mpi::Environment mpiEnv;
351 const bool useGpuPath = mpiEnv.gpuAwareMpi() && std::holds_alternative<GPUExecutor>(exec_);
352 if (useGpuPath)
353 {
354 for (const auto& buf : commBuffers_)
355 {
356 auto srcView = buf.deviceRecvBuf->view();
357 auto dstView = value_.view();
358 const localIdx start = buf.rangeStart;
360 exec_,
361 {0, buf.patchSize},
362 KOKKOS_LAMBDA(const localIdx k) { dstView[start + k] = srcView[k]; }
363 );
364 }
365 // The copy kernels read deviceRecvBuf, which commBuffers_.clear() below frees; with a
366 // memory pool a later irecv could reuse that memory while they still run.
367 fence(exec_);
368 }
369 else if (std::holds_alternative<GPUExecutor>(exec_))
370 {
371 // GPU executor but not GPU-aware MPI: data was staged through host buffers.
372 // Copy received host data back to the device in-place (via copy-assign, not
373 // move-assign) so that value_.data() stays the same pointer and any View
374 // obtained from value() before the exchange remains valid.
375 auto valH = value_.copyToHost();
376 for (const auto& buf : commBuffers_)
377 {
378 for (localIdx k = 0; k < buf.patchSize; k++)
379 valH.view()[buf.rangeStart + k] = buf.recvBuf[static_cast<sizeType>(k)];
380 }
381 Vector<ValueType> backToDevice = valH.copyToExecutor(exec_);
382 value_ = backToDevice; // operator=(const Vector&): setContainer dispatches async kernel
383 // Fence before backToDevice goes out of scope: the setContainer kernel reads from
384 // backToDevice.data_; freeing it while the kernel runs is a GPU page fault.
385 fence(exec_);
386 }
387 else
388 {
389 // SerialExecutor or CPUExecutor: value_ lives in host-accessible memory;
390 // write received data directly without any intermediate allocation.
391 for (const auto& buf : commBuffers_)
392 {
393 ValueType* dst = value_.data() + buf.rangeStart;
394 for (localIdx k = 0; k < buf.patchSize; k++)
395 dst[k] = buf.recvBuf[static_cast<sizeType>(k)];
396 }
397 }
398 requests_.clear();
399 communicating_ = false;
400 commBuffers_.clear();
401#endif
402 }
403
408 std::pair<localIdx, localIdx> range(localIdx patchId) const
409 {
410 return {offset_.data()[patchId], offset_.data()[patchId + 1]};
411 }
412
413private:
414
416 friend struct NoWaitAccess;
417
431 Vector<ValueType>& valueNoWait() { return value_; }
432
433 Executor exec_;
434 mutable Vector<ValueType> value_;
436 Vector<ValueType> refValue_;
438 valueFraction_;
439 Vector<ValueType> refGrad_;
440 Vector<int> boundaryTypes_;
441 Vector<localIdx> offset_;
442 sizeType nBoundaries_;
443 sizeType nBoundaryFaces_;
444
445#ifdef NF_WITH_MPI_SUPPORT
446 struct CommBuffer
447 {
448 std::vector<ValueType> sendBuf; // host staging, used when !gpuAwareMpi
449 std::vector<ValueType> recvBuf; // host staging, used when !gpuAwareMpi
450 std::optional<Vector<ValueType>> deviceRecvBuf; // device buffer, used when gpuAwareMpi
451 localIdx rangeStart;
452 sizeType patchSize;
453 };
454 mutable std::vector<MPI_Request>
455 requests_;
456 mutable std::vector<CommBuffer>
457 commBuffers_;
458 mutable bool communicating_ = false;
459#endif
460};
461
471{
472 template<typename ValueType>
474 {
475 return in.valueNoWait();
476 }
477};
478
479}
Represents the boundary fields for a computational domain.
std::pair< localIdx, localIdx > range(localIdx patchId) const
Get the range for a given patchId.
Vector< ValueType > & refValue()
Get the view storing the Dirichlet boundary values.
ValueType BoundaryDataType
sizeType nBoundaryFaces() const
Get the number of boundary faces.
const Vector< ValueType > & refValue() const
Get the view storing the Dirichlet boundary values.
const Vector< ValueType > & value() const
Get the view storing the computed values from the boundary condition.
BoundaryData(BoundaryData< ValueType > &&rhs)
Move constructor.
const Vector< int > & boundaryTypes() const
Get the view storing the boundary types.
Vector< scalar > & valueFraction()
Get the view storing the fraction of the boundary value.
BoundaryData(const Executor &exec, const BoundaryData< ValueType > &rhs)
Copy constructor.
friend struct NoWaitAccess
Grants NoWaitAccess (and only it) access to valueNoWait().
const Vector< localIdx > & offset() const
Get the view storing the offsets of each boundary.
const Executor & exec()
sizeType nBoundaries() const
Get the number of boundaries.
const Vector< scalar > & valueFraction() const
Get the view storing the fraction of the boundary value.
BoundaryData(const Executor &exec, sizeType nBoundaryFaces, localIdx nBoundaryTypes)
constructor with default initialized Vectors from sizes.
BoundaryData(const Executor &exec, const std::vector< localIdx > &offsets)
constructor from a given offsets vector @warn all members except offsets are default constructed
Vector< ValueType > & value()
Get the view storing the computed values from the boundary condition.
const Vector< ValueType > & refGrad() const
Get the view storing the Neumann boundary values.
Vector< ValueType > & refGrad()
Get the view storing the Neumann boundary values.
BoundaryData(const BoundaryData< ValueType > &rhs)
Copy constructor.
sizeType nBoundaryFaces(localIdx patchId) const
Get the number of boundary faces for this patch.
BoundaryData< ValueType > & operator=(BoundaryData< ValueType > &&rhs)
BoundaryData< ValueType > & operator=(const BoundaryData< ValueType > &rhs)
Reference executor for serial CPU execution.
An executor-aware contiguous container for numerical data with vector-style arithmetic semantics.
Definition vector.hpp:40
Vector< ValueType > copyToExecutor(Executor dstExec) const
Creates a copy of the Vector on the specified executor.
Integer types used throughout NeoN.
Definition array.hpp:18
std::variant< SerialExecutor, CPUExecutor, GPUExecutor > Executor
Definition executor.hpp:21
void fence(const Executor &exec)
Definition executor.hpp:24
int mpi_label_t
Definition label.hpp:57
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)
void validateInput(bool condition, std::string_view message, const std::source_location location=std::source_location::current())
int32_t localIdx
Definition label.hpp:50
Passkey granting non-draining access to BoundaryData's value storage.
static Vector< ValueType > & value(BoundaryData< ValueType > &in)