PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
Boundaries.h
Go to the documentation of this file.
1#ifndef BOUNDARIES_H
2#define BOUNDARIES_H
3
4#include <petscpf.h>
5#include <petscdmswarm.h>
6#include <stdlib.h>
7#include <time.h>
8#include <math.h>
9#include <petsctime.h>
10#include <petscsys.h>
11#include <petscdmcomposite.h>
12#include <petscsystypes.h>
13
14// Include additional headers
15#include "variables.h" // Shared type definitions
16#include "field_catalog.h" // Typed Eulerian field identities
17#include "ParticleSwarm.h" // Particle swarm functions
18#include "walkingsearch.h" // Particle location functions
19#include "grid.h" // Grid functions
20#include "logging.h" // Logging macros
21#include "io.h" // Data Input and Output functions
22#include "interpolation.h" // Interpolation routines
23#include "ParticleMotion.h" // Functions related to motion of particles
24#include "BC_Handlers.h" // Boundary Handlers
25#include "wallfunction.h" // wall functions for LES
26//================================================================================
27//
28// PUBLIC SYSTEM-LEVEL FUNCTIONS
29//
30// These are the main entry points for interacting with the boundary system.
31//
32//================================================================================
33
34/**
35 * @brief (Public) Validates the consistency and compatibility of the parsed boundary condition system.
36 *
37 * This function is the main entry point for all boundary condition validation. It should be
38 * called from the main setup sequence AFTER the configuration file has been parsed by
39 * `ParseAllBoundaryConditions` but BEFORE any `BoundaryCondition` handler objects are created.
40 *
41 * It acts as a dispatcher, calling specialized private sub-validators for different complex
42 * BC setups (like driven flow) to ensure the combination of `mathematical_type` and `handler_type`
43 * across all six faces is physically and numerically valid. This provides a "fail-fast"
44 * mechanism to prevent users from running improperly configured simulations.
45 *
46 * @param user The UserCtx for a single block, containing the populated `boundary_faces` configuration.
47 * @return PetscErrorCode 0 on success, non-zero PETSc error code on failure.
48 */
49PetscErrorCode BoundarySystem_Validate(UserCtx *user);
50
51/**
52 * @brief (Private) Creates and configures a specific BoundaryCondition handler object.
53 *
54 * This function acts as a factory. Based on the requested handler_type, it allocates
55 * a BoundaryCondition object and populates it with the correct set of function
56 * pointers corresponding to that specific behavior.
57 *
58 * @param handler_type The specific handler to create (e.g., BC_HANDLER_WALL_NOSLIP).
59 * @param[out] new_bc_ptr A pointer to where the newly created BoundaryCondition
60 * object's address will be stored.
61 * @return PetscErrorCode 0 on success.
62 */
63
64PetscErrorCode BoundaryCondition_Create(BCHandlerType handler_type, BoundaryCondition **new_bc_ptr);
65
66/**
67 * @brief Initializes the entire boundary system.
68 *
69 * @param[in,out] user Finest-level block context receiving parsed face configuration.
70 * @param bcs_filename Path to the generated boundary-condition definition file.
71 * @return PetscErrorCode 0 on success.
72 */
73PetscErrorCode BoundarySystem_Initialize(UserCtx *user, const char *bcs_filename);
74
75/**
76 * @brief Propagates boundary condition configuration from finest to all coarser multigrid levels.
77 *
78 * Coarser levels need BC type information for geometric operations (e.g., periodic corrections)
79 * but do NOT need full handler objects since timestepping only occurs at the finest level.
80 * This function copies the boundary_faces configuration down the hierarchy.
81 *
82 * @param simCtx The master SimCtx containing the multigrid hierarchy
83 * @return PetscErrorCode 0 on success
84 */
86
87/**
88 * @brief Executes one full boundary condition update cycle for a time step.
89 *
90 * @param[in,out] user Block context whose boundary handlers update target values and fluxes.
91 * @return PetscErrorCode 0 on success.
92 */
93PetscErrorCode BoundarySystem_ExecuteStep(UserCtx *user);
94
95/**
96 * @brief (Private) A lightweight execution engine that calls the UpdateUbcs() method on all relevant handlers.
97 *
98 * This function's sole purpose is to re-evaluate the target boundary values (`ubcs`) for
99 * flow-dependent boundary conditions (e.g., Symmetry, Outlets) after the interior
100 * velocity field has changed, such as after the projection step.
101 *
102 * It operates based on a "pull" model: it iterates through all boundary handlers and
103 * executes their `UpdateUbcs` method only if the handler has provided one. This makes the
104 * system extensible, as new flow-dependent handlers can be added without changing this
105 * engine. Handlers for fixed boundary conditions (e.g., a wall with a constant velocity)
106 * will have their `UpdateUbcs` pointer set to `NULL` and will be skipped automatically.
107 *
108 * @note This function is a critical part of the post-projection refresh. It intentionally
109 * does NOT modify `ucont` and does NOT perform flux balancing.
110 *
111 * @param user The main UserCtx struct.
112 * @return PetscErrorCode 0 on success.
113 */
114PetscErrorCode BoundarySystem_RefreshUbcs(UserCtx *user);
115
116/**
117 * @brief Cleans up and destroys all boundary system resources.
118 *
119 * @param[in,out] user Block context whose boundary handlers and temporary state are released.
120 * @return PetscErrorCode 0 on success.
121 */
122PetscErrorCode BoundarySystem_Destroy(UserCtx *user);
123
124/**
125 * @brief Determines if the current MPI rank owns any part of a specified global face.
126 *
127 * This function is a general utility for parallel boundary operations. It checks if the
128 * local domain of the current MPI rank is adjacent to a specified global boundary face.
129 * A rank "services" a face if it owns the cells adjacent to that global boundary and has
130 * a non-zero extent (i.e., owns at least one cell) in the tangential dimensions of that face.
131 *
132 * @param info Pointer to the DMDALocalInfo for the current rank's DA.
133 * @param IM_nodes_global Global number of nodes in the I-direction (e.g., user->IM + 1 if user->IM is cell count).
134 * @param JM_nodes_global Global number of nodes in the J-direction.
135 * @param KM_nodes_global Global number of nodes in the K-direction.
136 * @param face_id The specific global face (e.g., BC_FACE_NEG_Z) to check.
137 * @param[out] can_service_out Pointer to a PetscBool; set to PETSC_TRUE if the rank
138 * services the face, PETSC_FALSE otherwise.
139 * @return PetscErrorCode 0 on success.
140 */
141PetscErrorCode CanRankServiceFace(const DMDALocalInfo *info, PetscInt IM_nodes_global, PetscInt JM_nodes_global, PetscInt KM_nodes_global,
142 BCFace face_id, PetscBool *can_service_out);
143
144/**
145 * @brief The elements of a boundary face this rank owns, as index ranges.
146 *
147 * Purely local: it reads the block's decomposition through CanRankServiceFace() and
148 * GetOwnedInteriorCellBounds(), allocates nothing and communicates nothing, so a per-pass loop
149 * over a face's elements may call it freely. Edge and corner elements of the face are those of
150 * the interior cells beside it; the dummy rows of the other faces are not included.
151 *
152 * @param[in] user Block context.
153 * @param[in] face_id Face.
154 * @param[out] elements Axes, the face's metric/flux layer, and the owned tangential ranges;
155 * `n` is zero along both axes when this rank does not serve the face.
156 * @return PetscErrorCode 0 on success.
157 */
158PetscErrorCode GetBoundaryFaceElements(UserCtx *user, BCFace face_id, BoundaryFaceElements *elements);
159
160/**
161 * @brief Reports whether a boundary face is a wall that exerts shear on the flow.
162 *
163 * Every WALL face is impenetrable, and code that needs only that tests the type. A
164 * free-slip wall exerts no shear, so the wall model, its eddy viscosity on the wall
165 * face, and the cells it writes belong only to the walls this reports: a free-slip
166 * face uses the interior face average there instead, as a symmetry plane does.
167 *
168 * @param face Boundary face configuration.
169 * @return PETSC_TRUE for a WALL face whose handler is not free-slip.
170 */
171PetscBool BoundaryFaceHasWallShear(const BoundaryFaceConfig *face);
172
173/**
174 * @brief Reports whether a boundary face is a free-slip wall: impenetrable, exerting no shear,
175 * and a plane across which the flow mirrors.
176 *
177 * @param face Boundary face configuration.
178 * @return PETSC_TRUE for a WALL face whose handler is free-slip.
179 */
180static inline PetscBool BoundaryFaceIsFreeSlipWall(const BoundaryFaceConfig *face)
181{
182 return (PetscBool)(face->mathematical_type == WALL && face->handler_type == BC_HANDLER_WALL_FREE_SLIP);
183}
184
185/**
186 * @brief Classification of one staggered momentum row (location + component).
187 *
188 * @see ClassifyMomentumRow() for the meaning of each member and for the
189 * single-source-of-truth contract these values participate in.
190 */
191typedef enum {
192 MOM_ROW_PHYSICAL = 0, /**< Independent unknown governed by the momentum equation. */
193 MOM_ROW_FIXED_CONDITIONED, /**< Strong Dirichlet row; the value comes from ApplyBoundaryConditions(). */
194 MOM_ROW_FIXED_HOMOGENEOUS, /**< Dummy/tangential row carrying no unknown at all. */
195 MOM_ROW_PERIODIC_DUPLICATE /**< Duplicate of a wrapped representative row (see @p ri, @p rj, @p rk). */
197
198/**
199 * @brief Single source of truth for "which staggered momentum rows are unknowns".
200 *
201 * Every consumer of the momentum system must agree on which rows the solver is
202 * responsible for, and every consumer must derive that answer from this function
203 * rather than restating the index arithmetic locally. Three independent
204 * restatements previously disagreed, and the disagreement was silent: the
205 * residual assembly skipped the periodic duplicate column at index 0 while
206 * nothing zeroed it, so `ComputeTotalResidual()`'s BDF term accumulated there
207 * without bound and the reported residual norm stopped describing the state.
208 *
209 * The classification depends only on @p user->info, the configured boundary
210 * types, and the queried index; it reads no field data and performs no
211 * communication, so it is safe to call inside assembly loops.
212 *
213 * Periodicity of an axis is taken from that axis's NEGATIVE face, matching
214 * `ComputeRHS()` and `TransferPeriodicStaggeredFieldByDirection()`. A periodic
215 * axis is expected to carry PERIODIC on both of its faces.
216 *
217 * Callers act on the classification differently, and both actions are correct:
218 * - residual/pseudo-time consumers (`EnforceRHSBoundaryConditions()`) zero
219 * every non-physical row, because the value there is imposed immediately
220 * afterwards by the boundary sweep or the periodic synchronisation;
221 * - the matrix-free Newton path substitutes an explicit equation instead
222 * (`F = X - U_conditioned`, `F = X`, `F = X_dup - X_rep`), because a zeroed
223 * row would leave a zero Jacobian row.
224 *
225 * @param[in] user Block context supplying `info` and `boundary_faces`.
226 * @param[in] i Location index along xi.
227 * @param[in] j Location index along eta.
228 * @param[in] k Location index along zeta.
229 * @param[in] component Staggered component of the row (0 = xi, 1 = eta, 2 = zeta).
230 * @param[out] ri Representative xi index; equals @p i unless the row wraps.
231 * @param[out] rj Representative eta index; equals @p j unless the row wraps.
232 * @param[out] rk Representative zeta index; equals @p k unless the row wraps.
233 * @return The row classification. Only #MOM_ROW_PHYSICAL denotes an unknown.
234 */
235MomentumRowType ClassifyMomentumRow(UserCtx *user, PetscInt i, PetscInt j, PetscInt k,
236 PetscInt component, PetscInt *ri, PetscInt *rj, PetscInt *rk);
237
238/**
239 * @brief Reports whether a momentum row is masked out by the solid-cell field.
240 *
241 * `ComputeRHS()` zeroes the residual at a solid cell and at the staggered rows whose
242 * downstream neighbour is solid, so those rows carry no equation. A solver that only
243 * marches on the residual needs nothing more: a zero residual means no update. A solver
244 * that assembles a matrix and solves `F(X) = 0` does, because such a row has a zero
245 * Jacobian row and a zero column, leaving the unknown undetermined. Those rows must be
246 * constrained like any other row that carries no unknown.
247 *
248 * The condition mirrors the residual's own masking exactly. If one changes, so must the
249 * other, or the assembled operator stops matching the residual it preconditions.
250 *
251 * @param[in] nvert Ghosted solid-cell field, or NULL to apply no masking.
252 * @param[in] i Location index along xi.
253 * @param[in] j Location index along eta.
254 * @param[in] k Location index along zeta.
255 * @param[in] component Staggered component of the row (0 = xi, 1 = eta, 2 = zeta).
256 * @return `PETSC_TRUE` when the row is masked and therefore carries no unknown.
257 */
258PetscBool MomentumRowIsSolidMasked(const PetscReal ***nvert, PetscInt i, PetscInt j,
259 PetscInt k, PetscInt component);
260
261/**
262 * @brief Zeroes every momentum RHS row that does not carry an independent unknown.
263 *
264 * The set of such rows is not restated here: each owned location and component is
265 * asked of ClassifyMomentumRow(), and anything other than #MOM_ROW_PHYSICAL is
266 * zeroed. That covers, without enumerating them,
267 *
268 * - strong Dirichlet rows on non-periodic faces, so the time-stepping scheme
269 * cannot alter the values `ApplyBoundaryConditions()` has just set;
270 * - dummy layers at the far index of every axis, which hold no unknown; and
271 * - periodic duplicate columns, whose value the next
272 * `SynchronizePeriodicStaggeredFields()` copies from the wrapped master.
273 *
274 * The last case is the one that must not be skipped. `ComputeRHS()` leaves the
275 * transverse components of a periodic duplicate column untouched, so a row left
276 * unzeroed here retains its previous contents while `ComputeTotalResidual()`
277 * adds the BDF term on top of them on every call. The residual norm then grows
278 * by |dU|/dt per evaluation regardless of the state, and no pseudo-time
279 * iteration can reduce it.
280 *
281 * Call immediately after the RHS vector is fully assembled (spatial + temporal
282 * terms) and before it is used in a time-stepping update.
283 *
284 * @param user The UserCtx for the specific block being computed.
285 * @return PetscErrorCode 0 on success.
286 */
287PetscErrorCode EnforceRHSBoundaryConditions(UserCtx *user);
288
289/**
290 * @brief Synchronizes periodic endpoint cells for a list of cell-centered fields.
291 *
292 * The fields are first communicated from global to local storage. Each periodic
293 * direction is then transferred in i-j-k order, with an intermediate ghost
294 * refresh after every active direction so periodic edges and corners inherit the
295 * values established by earlier directions. Only global duplicate planes in active
296 * periodic directions are repaired; non-periodic directions are untouched. The
297 * routine is a no-op, including no local refresh, when every direction is
298 * nonperiodic. During active periodic synchronization it internally refreshes the
299 * local vectors, but it is not a general replacement for `UpdateLocalGhosts()`.
300 *
301 * Supported fields are selected by
302 * `FIELD_CAPABILITY_PERIODIC_CELL_SYNC` in the field catalog.
303 *
304 * @param user The main UserCtx struct.
305 * @param num_fields The number of entries in `field_ids`.
306 * @param field_ids The cell-centered fields to synchronize.
307 * @return PetscErrorCode 0 on success.
308 */
309PetscErrorCode SynchronizePeriodicCellFields(UserCtx *user, PetscInt num_fields, const FieldId field_ids[]);
310
311/**
312 * @brief Synchronizes persistent fields belonging to one face family.
313 *
314 * The function performs deterministic I/J/K directional passes with an
315 * intermediate ghost refresh after each active periodic direction. It updates
316 * persistent global seam/dummy values only; face-specific local stencil repair
317 * remains a separate operation.
318 *
319 * @param user The main UserCtx struct.
320 * @param face_direction Face family shared by every field (`'i'`, `'j'`, or `'k'`).
321 * @param[in] num_fields Count of registered face fields.
322 * @param field_ids Registered persistent face-field identities.
323 * @return PetscErrorCode 0 on success.
324 */
325PetscErrorCode SynchronizePeriodicFaceFields(UserCtx *user, char face_direction, PetscInt num_fields, const FieldId field_ids[]);
326
327/**
328 * @brief Synchronizes persistent component-staggered vector fields.
329 *
330 * The function performs deterministic I/J/K endpoint transfers with an
331 * intermediate ghost refresh after every active periodic direction. Currently
332 * `Ucont` is the only registered component-staggered field.
333 *
334 * @param user The main UserCtx struct.
335 * @param num_fields Number of entries in `field_ids`.
336 * @param field_ids Registered component-staggered field identities.
337 * @return PetscErrorCode 0 on success.
338 */
339PetscErrorCode SynchronizePeriodicStaggeredFields(UserCtx *user, PetscInt num_fields,
340 const FieldId field_ids[]);
341
342/**
343 * @brief Repairs the outer adjacent periodic ghosts used by QUICK cell stencils.
344 *
345 * The supplied local vectors must already contain a current PETSc periodic
346 * ghost exchange. The vector and scalar fields are repaired two logical cells
347 * across each active periodic seam so QUICK's `i-1/i+2` equivalents are valid.
348 *
349 * @param user Main block context containing periodic boundary metadata.
350 * @param local_vector_field Ghosted three-component cell-centered field.
351 * @param local_scalar_field Ghosted scalar cell-centered field.
352 * @return PetscErrorCode 0 on success.
353 */
354PetscErrorCode PreparePeriodicQuickStencilFields(UserCtx *user, Vec local_vector_field,
355 Vec local_scalar_field);
356
357/**
358 * @brief Synchronizes one local-only component-staggered periodic work field.
359 *
360 * This helper communicates locally computed owned entries, establishes the
361 * normal-component periodic endpoint values, and communicates once more.
362 *
363 * @param user Main block context containing periodic boundary metadata.
364 * @param local_field Ghosted local component-staggered vector.
365 * @return PetscErrorCode 0 on success.
366 */
367PetscErrorCode SynchronizePeriodicLocalStaggeredField(UserCtx *user, Vec local_field);
368
369/**
370 * @brief (Orchestrator) Updates all metric-related fields in the local ghost cell regions for periodic boundaries.
371 *
372 * This function synchronizes cell-centered `Aj` and the persistent I/J/K metric
373 * face families through the canonical MPI-safe synchronizers.
374 *
375 * @param user The main UserCtx struct.
376 * @return PetscErrorCode 0 on success.
377 */
378PetscErrorCode ApplyMetricsPeriodicBCs(UserCtx *user);
379
380/**
381 * @brief Applies periodic boundary conditions by copying data across domain boundaries for all relevant fields.
382 *
383 * This is the canonical periodic orchestrator for geometric consistency. It updates
384 * `Ucat`, `P`, and `Nvert` through the generic cell synchronizer and updates
385 * staggered `Ucont` through the component-staggered synchronizer.
386 *
387 * Future extension rule: add new periodic variables by extending the existing field
388 * string dispatchers and invoking them from this orchestrator.
389 *
390 * @param user The main UserCtx struct.
391 * @param final_cell_update PETSC_FALSE leaves the cell fields' last ghost update to the
392 * caller, which must update `Ucat`, `P` and `Nvert` before anything reads their
393 * local vectors; PETSC_TRUE leaves them current.
394 * @return PetscErrorCode 0 on success.
395 */
396PetscErrorCode ApplyPeriodicBCs(UserCtx *user, PetscBool final_cell_update);
397
398/**
399 * @brief Fills the dummy cells on the non-periodic faces of one cell-centred field.
400 *
401 * A cell-centred field stores cell `c` at index `c+1`; index 0 and the last index
402 * along each axis are dummy cells outside the domain. Stencils and node averages that
403 * reach across a boundary read them, so their value is the field's boundary condition:
404 *
405 * | Field | Dummy value | Condition it encodes |
406 * |--------|------------------------------|----------------------|
407 * | `Ucat` | `2 Ubcs - interior` | face average equals the handler's boundary velocity |
408 * | `P` | the adjacent interior cell | zero normal gradient |
409 * | `Psi` | the adjacent interior cell | zero normal gradient (no scalar flux) |
410 *
411 * Any other field is refused: its condition must be chosen for the quantity before its
412 * dummy cells are filled (see @ref p60_stats_boundary_sec for why no default serves
413 * every quantity).
414 *
415 * **Pressure.** Zero gradient is the condition the pressure solve already implies on
416 * every non-periodic face: the Poisson operator drops each boundary face's term, the
417 * dummy rows are identities with a zero right-hand side, and the projection corrects
418 * interior faces only. Nothing in the solve reads these values; filling them makes
419 * `P_nodal` and near-wall pressure gradients (the Cabot wall model) consistent with that
420 * condition, instead of averaging in a dummy value that stays at its initial zero. A
421 * pressure boundary condition (a far field, or a pressure outlet) will set its dummy
422 * value here as well, but that alone changes nothing the solve sees; see
423 * @ref p57_pressure_bc_sec for what has to change with it.
424 *
425 * **Eddy viscosity.** Mirrored, zero gradient, across a free-slip wall only. The flow
426 * mirrors there, so the face value the viscous flux averages must be the interior one,
427 * as on the corresponding interior face of the full, unmirrored domain. A wall that
428 * exerts shear replaces the face value outright (the wall model's, or zero), and the
429 * eddy viscosity's dummy cells on every other face are not written here.
430 *
431 * Periodic faces are skipped: the periodic synchronizers own them. Only the flat part
432 * of each face is written (shrunken loop ranges); edges and corners are filled
433 * afterwards by `UpdateCornerNodes` from these values.
434 *
435 * @param user Block context supplying the layout, face types, and `Ubcs`.
436 * @param field_id Cell-centred field to fill: `FIELD_ID_UCAT`, `FIELD_ID_P`, `FIELD_ID_PSI`,
437 * or `FIELD_ID_NU_T`.
438 * @return Zero on success; `PETSC_ERR_ARG_WRONG` for a field that is not cell-centred,
439 * `PETSC_ERR_SUP` for one with no boundary rule.
440 */
441PetscErrorCode UpdateDummyCells(UserCtx *user, FieldId field_id);
442
443/**
444 * @brief Fills the edge and corner dummy cells of one cell-centred field.
445 *
446 * Call after the face dummy cells are final, both periodic (the periodic
447 * synchronizers) and non-periodic (`UpdateDummyCells`). Each edge dummy cell becomes the
448 * mean of its two face-adjacent dummy cells; the edges along the Z faces are done
449 * first, so the corners the remaining edges pass through are filled from finished
450 * edges. Across a free-slip wall the flow is the mirror image of the flow inside, so an
451 * edge cell beside one is instead the mirror image of its neighbour across that wall:
452 * a scalar copied, a velocity with its component along the wall's metric reversed.
453 * That keeps a free-slip wall exactly a plane of symmetry up to its edges.
454 *
455 * @param user Block context supplying the layout.
456 * @param field_id Cell-centred field whose edges and corners are filled.
457 * @return Zero on success; `PETSC_ERR_ARG_WRONG` for a field that is not cell-centred.
458 */
459PetscErrorCode UpdateCornerNodes(UserCtx *user, FieldId field_id);
460
461/**
462 * @brief Evaluates the selected wall law on every wall-face element and stores the wall stress.
463 *
464 * For each element of a face whose boundary exerts shear (no-slip or moving wall; free-slip
465 * exerts none), the law is evaluated from the resolved velocity of the reference cell - the
466 * second cell from the wall - relative to the wall's velocity, at that cell's wall distance,
467 * and gives a friction velocity u_tau. The kinematic wall shear stress u_tau^2, directed
468 * against the reference cell's wall-parallel motion, is written to `Wall_Stress` in the
469 * face's own dummy cell, oriented as that face's viscous flux per unit area;
470 * `ComputeViscous()` applies it on the wall face in place of a gradient flux. The wall-normal
471 * flux through the face is set to zero.
472 *
473 * The resolved velocity is never modified, so the momentum equation, the subgrid closure,
474 * the dummy cells and every other boundary condition read the same near-wall velocity. A
475 * cell beside two walls has one element on each, with its own reference cell and stress.
476 * `Friction_Velocity` holds, per first cell, the RMS of u_tau over its wall faces, and
477 * @ref LogWallModelDiagnostics reduces per-element statistics.
478 *
479 * Distances come from the cell Jacobians and the wall-face area: half the first cell's
480 * thickness, and the first cell's full thickness plus half the second's. A rank must own at
481 * least three nodes normal to each wall it serves, so the reference cell is in its block;
482 * a layout that violates this is refused.
483 *
484 * Cabot may return a negative friction velocity when an adverse pressure gradient reverses
485 * its wall-layer balance; the stress then acts along the reference flow.
486 *
487 * @param user Block context whose Ucat is the current pass's reconstruction.
488 * @return PetscErrorCode 0 on success; `PETSC_ERR_ARG_OUTOFRANGE` for a layout that does not
489 * reach the reference cell; `PETSC_ERR_FP` for a non-finite friction velocity.
490 */
491PetscErrorCode ApplyWallFunction(UserCtx *user);
492
493/**
494 * @brief Appends one row of near-wall statistics to `<run.analysis.metrics>/wall_model.csv`.
495 *
496 * Reduces the state @ref ApplyWallFunction accumulated over the wall faces this rank owns
497 * and writes the run-wide row from rank 0. `y+` is the column that matters: it says
498 * whether the first cell sits where the selected law is valid, and no stored field can
499 * answer that after the fact.
500 *
501 * A no-op when no wall model is active. When a wall model is active but no cell was
502 * corrected - wall functions enabled on a case with no WALL face - it warns and writes
503 * nothing rather than emitting a row of zeros.
504 *
505 * Collective on the block's communicator; call it on every rank, once per step, after
506 * @ref ApplyWallFunction.
507 *
508 * @param[in] user Block context whose wall-model pass has already run this step.
509 * @return PetscErrorCode 0 on success.
510 */
511PetscErrorCode LogWallModelDiagnostics(UserCtx *user);
512
513/**
514 * @brief Records each INLET and OUTLET face's area-weighted mean pressure this step.
515 *
516 * Appends one row per such face to `<analysis_dir>/boundary_pressure.csv`: the step, the
517 * physical time, the face, its type, its open area, and the mean of the pressure in the
518 * first interior cells beside it, weighted by their face areas, in physical units. Edge and
519 * corner cells and cells blanked by an immersed body are left out, as in the outlet's flux
520 * sum. Pressure carries an arbitrary constant, so the difference between two faces' rows is
521 * the meaningful quantity: the pressure drop across the domain, the observable for a duct's
522 * friction factor and for the transient that enforces a change in an inflow-outflow
523 * domain's flow rate. A no-op when the block has no INLET or OUTLET face; in a multi-block
524 * run only the first block's faces are recorded, as in `inlet_flow.csv`.
525 *
526 * Collective on PETSC_COMM_WORLD; call it on every rank, once per step, after the projection.
527 *
528 * @param[in] user Block context whose pressure is current for this step.
529 * @return PetscErrorCode 0 on success.
530 */
531PetscErrorCode LogBoundaryPressureDiagnostics(UserCtx *user);
532
533/**
534 * @brief Finalizes cell-centered fields after the projection step.
535 *
536 * This function completes the cell-centered state derived from the final,
537 * divergence-free `Ucont` produced by `Projection`. It fills non-periodic
538 * `Ucat` dummy faces, synchronizes periodic `Ucat` and `P` endpoints, resolves
539 * edges and corners, and refreshes the corresponding local vectors.
540 *
541 * This function is fundamentally different from `ApplyBoundaryConditions`: it
542 * does NOT modify `Ucont`, reapply wall functions, or rerun the full physical
543 * boundary-condition workflow.
544 *
545 * WORKFLOW:
546 * 1. Refreshes local `Ucat` and any flow-dependent `Ubcs` targets.
547 * 2. Fills non-periodic dummy faces and establishes periodic cell endpoints.
548 * 3. Resolves edges/corners, restores exact periodic relationships, and refreshes
549 * local `Ucat` and `P`.
550 *
551 * @param user The main UserCtx struct, containing all simulation state.
552 * @return PetscErrorCode 0 on success.
553 */
554PetscErrorCode FinalizePostProjectionCellFields(UserCtx *user);
555
556/**
557 * @brief Brings Ucat's and P's dummy cells, periodic endpoints, corners and ghosts in line with
558 * their interior values and the boundary values already in `Ubcs`.
559 * @details The part of FinalizePostProjectionCellFields() that does not ask the handlers to
560 * refresh `Ubcs`, for a caller that sets the boundary values itself. Collective.
561 * @param[in,out] user Block whose global Ucat, P and `Ubcs` are current.
562 * @return PetscErrorCode 0 on success.
563 */
565
566/**
567 * @brief Main boundary-condition orchestrator executed during solver timestepping.
568 *
569 * This routine performs the full BC workflow for the current block, including
570 * dynamic boundary refresh, periodic transfer, dummy/corner updates, and optional
571 * wall-function corrections in the same order expected by the runtime solver.
572 * It may iterate boundary updates to enforce coupled boundary dependencies.
573 *
574 * @param user The main UserCtx struct containing field vectors and boundary system state.
575 * @return PetscErrorCode 0 on success.
576 */
577PetscErrorCode ApplyBoundaryConditions(UserCtx *user);
578
579#endif // BOUNDARIES_H
PetscErrorCode FinalizeCellFieldsFromBoundaryValues(UserCtx *user)
Brings Ucat's and P's dummy cells, periodic endpoints, corners and ghosts in line with their interior...
PetscErrorCode PreparePeriodicQuickStencilFields(UserCtx *user, Vec local_vector_field, Vec local_scalar_field)
Repairs the outer adjacent periodic ghosts used by QUICK cell stencils.
MomentumRowType
Classification of one staggered momentum row (location + component).
Definition Boundaries.h:191
@ MOM_ROW_FIXED_HOMOGENEOUS
Dummy/tangential row carrying no unknown at all.
Definition Boundaries.h:194
@ MOM_ROW_PHYSICAL
Independent unknown governed by the momentum equation.
Definition Boundaries.h:192
@ MOM_ROW_PERIODIC_DUPLICATE
Duplicate of a wrapped representative row (see ri, rj, rk).
Definition Boundaries.h:195
@ MOM_ROW_FIXED_CONDITIONED
Strong Dirichlet row; the value comes from ApplyBoundaryConditions().
Definition Boundaries.h:193
PetscErrorCode BoundarySystem_Initialize(UserCtx *user, const char *bcs_filename)
Initializes the entire boundary system.
Definition Boundaries.c:412
PetscErrorCode ApplyWallFunction(UserCtx *user)
Evaluates the selected wall law on every wall-face element and stores the wall stress.
MomentumRowType ClassifyMomentumRow(UserCtx *user, PetscInt i, PetscInt j, PetscInt k, PetscInt component, PetscInt *ri, PetscInt *rj, PetscInt *rk)
Single source of truth for "which staggered momentum rows are unknowns".
Definition Boundaries.c:139
PetscErrorCode PropagateBoundaryConfigToCoarserLevels(SimCtx *simCtx)
Propagates boundary condition configuration from finest to all coarser multigrid levels.
Definition Boundaries.c:530
PetscBool BoundaryFaceHasWallShear(const BoundaryFaceConfig *face)
Reports whether a boundary face is a wall that exerts shear on the flow.
Definition Boundaries.c:9
PetscErrorCode ApplyMetricsPeriodicBCs(UserCtx *user)
(Orchestrator) Updates all metric-related fields in the local ghost cell regions for periodic boundar...
PetscErrorCode EnforceRHSBoundaryConditions(UserCtx *user)
Zeroes every momentum RHS row that does not carry an independent unknown.
Definition Boundaries.c:224
PetscErrorCode UpdateDummyCells(UserCtx *user, FieldId field_id)
Fills the dummy cells on the non-periodic faces of one cell-centred field.
PetscErrorCode LogWallModelDiagnostics(UserCtx *user)
Appends one row of near-wall statistics to <run.analysis.metrics>/wall_model.csv.
PetscErrorCode BoundarySystem_RefreshUbcs(UserCtx *user)
(Private) A lightweight execution engine that calls the UpdateUbcs() method on all relevant handlers.
PetscErrorCode SynchronizePeriodicLocalStaggeredField(UserCtx *user, Vec local_field)
Synchronizes one local-only component-staggered periodic work field.
PetscBool MomentumRowIsSolidMasked(const PetscReal ***nvert, PetscInt i, PetscInt j, PetscInt k, PetscInt component)
Reports whether a momentum row is masked out by the solid-cell field.
Definition Boundaries.c:193
PetscErrorCode BoundarySystem_Validate(UserCtx *user)
(Public) Validates the consistency and compatibility of the parsed boundary condition system.
Definition Boundaries.c:352
static PetscBool BoundaryFaceIsFreeSlipWall(const BoundaryFaceConfig *face)
Reports whether a boundary face is a free-slip wall: impenetrable, exerting no shear,...
Definition Boundaries.h:180
PetscErrorCode LogBoundaryPressureDiagnostics(UserCtx *user)
Records each INLET and OUTLET face's area-weighted mean pressure this step.
PetscErrorCode GetBoundaryFaceElements(UserCtx *user, BCFace face_id, BoundaryFaceElements *elements)
The elements of a boundary face this rank owns, as index ranges.
Definition Boundaries.c:105
PetscErrorCode BoundaryCondition_Create(BCHandlerType handler_type, BoundaryCondition **new_bc_ptr)
(Private) Creates and configures a specific BoundaryCondition handler object.
Definition Boundaries.c:265
PetscErrorCode SynchronizePeriodicStaggeredFields(UserCtx *user, PetscInt num_fields, const FieldId field_ids[])
Synchronizes persistent component-staggered vector fields.
PetscErrorCode ApplyBoundaryConditions(UserCtx *user)
Main boundary-condition orchestrator executed during solver timestepping.
PetscErrorCode FinalizePostProjectionCellFields(UserCtx *user)
Finalizes cell-centered fields after the projection step.
PetscErrorCode UpdateCornerNodes(UserCtx *user, FieldId field_id)
Fills the edge and corner dummy cells of one cell-centred field.
PetscErrorCode CanRankServiceFace(const DMDALocalInfo *info, PetscInt IM_nodes_global, PetscInt JM_nodes_global, PetscInt KM_nodes_global, BCFace face_id, PetscBool *can_service_out)
Determines if the current MPI rank owns any part of a specified global face.
Definition Boundaries.c:22
PetscErrorCode BoundarySystem_ExecuteStep(UserCtx *user)
Executes one full boundary condition update cycle for a time step.
Definition Boundaries.c:600
PetscErrorCode SynchronizePeriodicFaceFields(UserCtx *user, char face_direction, PetscInt num_fields, const FieldId field_ids[])
Synchronizes persistent fields belonging to one face family.
PetscErrorCode BoundarySystem_Destroy(UserCtx *user)
Cleans up and destroys all boundary system resources.
PetscErrorCode SynchronizePeriodicCellFields(UserCtx *user, PetscInt num_fields, const FieldId field_ids[])
Synchronizes periodic endpoint cells for a list of cell-centered fields.
PetscErrorCode ApplyPeriodicBCs(UserCtx *user, PetscBool final_cell_update)
Applies periodic boundary conditions by copying data across domain boundaries for all relevant fields...
Header file for Particle Motion and migration related functions.
Header file for Particle Swarm management functions.
Authoritative identities and storage metadata for persistent Eulerian fields.
FieldId
Compile-time identity for a catalogued Eulerian field.
Public interface for grid, solver, and metric setup routines.
Public interface for data input/output routines.
Logging utilities and macros for PETSc-based applications.
The "virtual table" struct for a boundary condition handler object.
Definition variables.h:389
Main header file for a complex fluid dynamics solver.
@ WALL
Definition variables.h:319
BCHandlerType
Defines the specific computational "strategy" for a boundary handler.
Definition variables.h:343
@ BC_HANDLER_WALL_FREE_SLIP
Definition variables.h:347
BCHandlerType handler_type
Definition variables.h:427
BCType mathematical_type
Definition variables.h:426
BCFace
Identifies the six logical faces of a structured computational block.
Definition variables.h:308
Holds the complete configuration for one of the six boundary faces.
Definition variables.h:424
The elements of one boundary face that this rank owns: one per interior cell beside the face,...
Definition variables.h:415
The master context for the entire simulation.
Definition variables.h:916
User-defined context containing data specific to a single computational grid level.
Definition variables.h:1157
Header file for particle location functions using the walking search algorithm.