PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
Enumerations | Functions
Boundaries.h File Reference
#include <petscpf.h>
#include <petscdmswarm.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <petsctime.h>
#include <petscsys.h>
#include <petscdmcomposite.h>
#include <petscsystypes.h>
#include "variables.h"
#include "field_catalog.h"
#include "ParticleSwarm.h"
#include "walkingsearch.h"
#include "grid.h"
#include "logging.h"
#include "io.h"
#include "interpolation.h"
#include "ParticleMotion.h"
#include "BC_Handlers.h"
#include "wallfunction.h"
Include dependency graph for Boundaries.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Enumerations

enum  MomentumRowType { MOM_ROW_PHYSICAL = 0 , MOM_ROW_FIXED_CONDITIONED , MOM_ROW_FIXED_HOMOGENEOUS , MOM_ROW_PERIODIC_DUPLICATE }
 Classification of one staggered momentum row (location + component). More...
 

Functions

PetscErrorCode BoundarySystem_Validate (UserCtx *user)
 (Public) Validates the consistency and compatibility of the parsed boundary condition system.
 
PetscErrorCode BoundaryCondition_Create (BCHandlerType handler_type, BoundaryCondition **new_bc_ptr)
 (Private) Creates and configures a specific BoundaryCondition handler object.
 
PetscErrorCode BoundarySystem_Initialize (UserCtx *user, const char *bcs_filename)
 Initializes the entire boundary system.
 
PetscErrorCode PropagateBoundaryConfigToCoarserLevels (SimCtx *simCtx)
 Propagates boundary condition configuration from finest to all coarser multigrid levels.
 
PetscErrorCode BoundarySystem_ExecuteStep (UserCtx *user)
 Executes one full boundary condition update cycle for a time step.
 
PetscErrorCode BoundarySystem_RefreshUbcs (UserCtx *user)
 (Private) A lightweight execution engine that calls the UpdateUbcs() method on all relevant handlers.
 
PetscErrorCode BoundarySystem_Destroy (UserCtx *user)
 Cleans up and destroys all boundary system resources.
 
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.
 
PetscErrorCode GetBoundaryFaceElements (UserCtx *user, BCFace face_id, BoundaryFaceElements *elements)
 The elements of a boundary face this rank owns, as index ranges.
 
PetscBool BoundaryFaceHasWallShear (const BoundaryFaceConfig *face)
 Reports whether a boundary face is a wall that exerts shear on the flow.
 
static PetscBool BoundaryFaceIsFreeSlipWall (const BoundaryFaceConfig *face)
 Reports whether a boundary face is a free-slip wall: impenetrable, exerting no shear, and a plane across which the flow mirrors.
 
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".
 
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.
 
PetscErrorCode EnforceRHSBoundaryConditions (UserCtx *user)
 Zeroes every momentum RHS row that does not carry an independent unknown.
 
PetscErrorCode SynchronizePeriodicCellFields (UserCtx *user, PetscInt num_fields, const FieldId field_ids[])
 Synchronizes periodic endpoint cells for a list of cell-centered fields.
 
PetscErrorCode SynchronizePeriodicFaceFields (UserCtx *user, char face_direction, PetscInt num_fields, const FieldId field_ids[])
 Synchronizes persistent fields belonging to one face family.
 
PetscErrorCode SynchronizePeriodicStaggeredFields (UserCtx *user, PetscInt num_fields, const FieldId field_ids[])
 Synchronizes persistent component-staggered vector fields.
 
PetscErrorCode PreparePeriodicQuickStencilFields (UserCtx *user, Vec local_vector_field, Vec local_scalar_field)
 Repairs the outer adjacent periodic ghosts used by QUICK cell stencils.
 
PetscErrorCode SynchronizePeriodicLocalStaggeredField (UserCtx *user, Vec local_field)
 Synchronizes one local-only component-staggered periodic work field.
 
PetscErrorCode ApplyMetricsPeriodicBCs (UserCtx *user)
 (Orchestrator) Updates all metric-related fields in the local ghost cell regions for periodic boundaries.
 
PetscErrorCode ApplyPeriodicBCs (UserCtx *user, PetscBool final_cell_update)
 Applies periodic boundary conditions by copying data across domain boundaries for all relevant fields.
 
PetscErrorCode UpdateDummyCells (UserCtx *user, FieldId field_id)
 Fills the dummy cells on the non-periodic faces of one cell-centred field.
 
PetscErrorCode UpdateCornerNodes (UserCtx *user, FieldId field_id)
 Fills the edge and corner dummy cells of one cell-centred field.
 
PetscErrorCode ApplyWallFunction (UserCtx *user)
 Evaluates the selected wall law on every wall-face element and stores the wall stress.
 
PetscErrorCode LogWallModelDiagnostics (UserCtx *user)
 Appends one row of near-wall statistics to <run.analysis.metrics>/wall_model.csv.
 
PetscErrorCode LogBoundaryPressureDiagnostics (UserCtx *user)
 Records each INLET and OUTLET face's area-weighted mean pressure this step.
 
PetscErrorCode FinalizePostProjectionCellFields (UserCtx *user)
 Finalizes cell-centered fields after the projection step.
 
PetscErrorCode FinalizeCellFieldsFromBoundaryValues (UserCtx *user)
 Brings Ucat's and P's dummy cells, periodic endpoints, corners and ghosts in line with their interior values and the boundary values already in Ubcs.
 
PetscErrorCode ApplyBoundaryConditions (UserCtx *user)
 Main boundary-condition orchestrator executed during solver timestepping.
 

Enumeration Type Documentation

◆ MomentumRowType

Classification of one staggered momentum row (location + component).

See also
ClassifyMomentumRow() for the meaning of each member and for the single-source-of-truth contract these values participate in.
Enumerator
MOM_ROW_PHYSICAL 

Independent unknown governed by the momentum equation.

MOM_ROW_FIXED_CONDITIONED 

Strong Dirichlet row; the value comes from ApplyBoundaryConditions().

MOM_ROW_FIXED_HOMOGENEOUS 

Dummy/tangential row carrying no unknown at all.

MOM_ROW_PERIODIC_DUPLICATE 

Duplicate of a wrapped representative row (see ri, rj, rk).

Definition at line 191 of file Boundaries.h.

191 {
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). */
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

Function Documentation

◆ BoundarySystem_Validate()

PetscErrorCode BoundarySystem_Validate ( UserCtx *  user)

(Public) Validates the consistency and compatibility of the parsed boundary condition system.

This function is the main entry point for all boundary condition validation. It should be called from the main setup sequence AFTER the configuration file has been parsed by ParseAllBoundaryConditions but BEFORE any BoundaryCondition handler objects are created.

It acts as a dispatcher, calling specialized private sub-validators for different complex BC setups (like driven flow) to ensure the combination of mathematical_type and handler_type across all six faces is physically and numerically valid. This provides a "fail-fast" mechanism to prevent users from running improperly configured simulations.

Parameters
userThe UserCtx for a single block, containing the populated boundary_faces configuration.
Returns
PetscErrorCode 0 on success, non-zero PETSc error code on failure.

(Public) Validates the consistency and compatibility of the parsed boundary condition system.

See also
BoundarySystem_Validate()

Definition at line 352 of file Boundaries.c.

353{
354 PetscErrorCode ierr;
355 const BCFace neg_faces[3] = {BC_FACE_NEG_X, BC_FACE_NEG_Y, BC_FACE_NEG_Z};
356 const BCFace pos_faces[3] = {BC_FACE_POS_X, BC_FACE_POS_Y, BC_FACE_POS_Z};
357 const char axis_names[3] = {'X', 'Y', 'Z'};
358 DMBoundaryType bx, by, bz;
359 PetscBool dm_periodic[3];
360 PetscFunctionBeginUser;
362
363 LOG_ALLOW(GLOBAL, LOG_INFO, "Validating parsed boundary condition configuration...\n");
364 bx = user->info.bx; by = user->info.by; bz = user->info.bz;
365 dm_periodic[0] = (PetscBool)(bx == DM_BOUNDARY_PERIODIC);
366 dm_periodic[1] = (PetscBool)(by == DM_BOUNDARY_PERIODIC);
367 dm_periodic[2] = (PetscBool)(bz == DM_BOUNDARY_PERIODIC);
368
369 // --- Rule Set 1: Geometric periodic faces must be paired and match the DM topology. ---
370 for (PetscInt axis = 0; axis < 3; axis++) {
371 const PetscBool neg_periodic =
372 user->boundary_faces[neg_faces[axis]].mathematical_type == PERIODIC;
373 const PetscBool pos_periodic =
374 user->boundary_faces[pos_faces[axis]].mathematical_type == PERIODIC;
375
376 PetscCheck(neg_periodic == pos_periodic, PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT,
377 "Configuration Error: Periodic boundaries in the %c direction must be paired; "
378 "%s is %s while %s is %s.",
379 axis_names[axis],
380 BCFaceToString(neg_faces[axis]), neg_periodic ? "PERIODIC" : "not periodic",
381 BCFaceToString(pos_faces[axis]), pos_periodic ? "PERIODIC" : "not periodic");
382 PetscCheck(dm_periodic[axis] == neg_periodic, PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT,
383 "Configuration Error: The %c-direction DM periodic flag (%d) does not match "
384 "the paired boundary configuration (%s).",
385 axis_names[axis], (int)dm_periodic[axis], neg_periodic ? "PERIODIC" : "not periodic");
386 }
387
388 // --- Rule Set 2: Driven Flow Handler Consistency ---
389 // This specialized validator will check all rules related to driven flow handlers.
390 ierr = Validate_DrivenFlowConfiguration(user); CHKERRQ(ierr);
391
392 // --- Rule Set 3: (Future Extension) Overset Interface Consistency ---
393 // ierr = Validate_OversetConfiguration(user); CHKERRQ(ierr);
394
395 LOG_ALLOW(GLOBAL, LOG_INFO, "Boundary configuration is valid.\n");
396
398 PetscFunctionReturn(0);
399}
PetscErrorCode Validate_DrivenFlowConfiguration(UserCtx *user)
(Private) Validates all consistency rules for a driven flow (channel/pipe) setup.
Definition BC_Handlers.c:15
#define GLOBAL
Scope for global logging across all processes.
Definition logging.h:46
const char * BCFaceToString(BCFace face)
Returns the canonical log token for a boundary-face enum value.
Definition logging.c:640
#define LOG_ALLOW(scope, level, fmt,...)
Logging macro that checks both the log level and whether the calling function is in the allowed-funct...
Definition logging.h:214
#define PROFILE_FUNCTION_END
Marks the end of a profiled code block.
Definition logging.h:1029
@ LOG_INFO
Informational messages about program execution.
Definition logging.h:31
#define PROFILE_FUNCTION_BEGIN
Marks the beginning of a profiled function: an always-on aggregate timer.
Definition logging.h:1000
@ PERIODIC
Definition variables.h:325
BoundaryFaceConfig boundary_faces[6]
Definition variables.h:1182
DMDALocalInfo info
Definition variables.h:1169
BCType mathematical_type
Definition variables.h:426
BCFace
Identifies the six logical faces of a structured computational block.
Definition variables.h:308
@ BC_FACE_NEG_X
Definition variables.h:309
@ BC_FACE_POS_Z
Definition variables.h:311
@ BC_FACE_POS_Y
Definition variables.h:310
@ BC_FACE_NEG_Z
Definition variables.h:311
@ BC_FACE_POS_X
Definition variables.h:309
@ BC_FACE_NEG_Y
Definition variables.h:310
Here is the call graph for this function:
Here is the caller graph for this function:

◆ BoundaryCondition_Create()

PetscErrorCode BoundaryCondition_Create ( BCHandlerType  handler_type,
BoundaryCondition **  new_bc_ptr 
)

(Private) Creates and configures a specific BoundaryCondition handler object.

This function acts as a factory. Based on the requested handler_type, it allocates a BoundaryCondition object and populates it with the correct set of function pointers corresponding to that specific behavior.

Parameters
handler_typeThe specific handler to create (e.g., BC_HANDLER_WALL_NOSLIP).
[out]new_bc_ptrA pointer to where the newly created BoundaryCondition object's address will be stored.
Returns
PetscErrorCode 0 on success.

(Private) Creates and configures a specific BoundaryCondition handler object.

See also
BoundaryCondition_Create()

Definition at line 265 of file Boundaries.c.

266{
267 PetscErrorCode ierr;
268 PetscFunctionBeginUser;
270
271 const char* handler_name = BCHandlerTypeToString(handler_type);
272 LOG_ALLOW(LOCAL, LOG_DEBUG, "Factory called for handler type %s. \n", handler_name);
273
274 ierr = PetscMalloc1(1, new_bc_ptr); CHKERRQ(ierr);
275 BoundaryCondition *bc = *new_bc_ptr;
276
277 bc->type = handler_type;
278 bc->priority = -1; // Default priority; can be overridden in specific handlers
279 bc->data = NULL;
280 bc->Initialize = NULL;
281 bc->PreStep = NULL;
282 bc->Apply = NULL;
283 bc->PostStep = NULL;
284 bc->UpdateUbcs = NULL;
285 bc->Destroy = NULL;
286 bc->needs_repeat_pass = PETSC_FALSE; // A handler whose Apply() reads in-pass state sets it
287
288 LOG_ALLOW(LOCAL, LOG_DEBUG, "Allocated generic handler object at address %p.\n", (void*)bc);
289
290 switch (handler_type) {
291
293 LOG_ALLOW(LOCAL, LOG_DEBUG, "Dispatching to Create_OutletConservation().\n");
294 ierr = Create_OutletConservation(bc); CHKERRQ(ierr);
295 break;
296
298 LOG_ALLOW(LOCAL, LOG_DEBUG, "Dispatching to Create_WallNoSlip().\n");
299 ierr = Create_WallNoSlip(bc); CHKERRQ(ierr);
300 break;
301
303 LOG_ALLOW(LOCAL, LOG_DEBUG, "Dispatching to Create_WallFreeSlip().\n");
304 ierr = Create_WallFreeSlip(bc); CHKERRQ(ierr);
305 break;
306
308 LOG_ALLOW(LOCAL, LOG_DEBUG, "Dispatching to Create_WallMoving().\n");
309 ierr = Create_WallMoving(bc); CHKERRQ(ierr);
310 break;
311
313 LOG_ALLOW(LOCAL,LOG_DEBUG,"Dispatching to Create_PeriodicGeometric().\n");
314 ierr = Create_PeriodicGeometric(bc);
315 break;
316
318 LOG_ALLOW(LOCAL,LOG_DEBUG,"Dispatching to Create_PeriodicDrivenConstant().\n");
320 break;
321
323 LOG_ALLOW(LOCAL,LOG_DEBUG,"Dispatching to Create_PeriodicDrivenInitial().\n");
325 break;
326
328 LOG_ALLOW(LOCAL, LOG_DEBUG, "Dispatching to Create_InletPrescribedVelocity().\n");
329 ierr = Create_InletPrescribedVelocity(bc); CHKERRQ(ierr);
330 break;
331 //Add cases for other handlers here in future phases
332
333 default:
334 LOG_ALLOW(GLOBAL, LOG_ERROR, "Handler type (%s) is not recognized or implemented in the factory.\n", handler_name);
335 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_UNKNOWN_TYPE, "Boundary handler type %d (%s) not recognized in factory.\n", handler_type, handler_name);
336 }
337
338 if(bc->priority < 0) {
339 LOG_ALLOW(GLOBAL, LOG_ERROR, "Handler type %d (%s) did not set a valid priority during creation.\n", handler_type, handler_name);
340 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_UNKNOWN_TYPE, "Boundary handler type %d (%s) did not set a valid priority during creation.\n", handler_type, handler_name);
341 }
342
343 LOG_ALLOW(LOCAL, LOG_DEBUG, "Successfully created and configured handler for %s.\n", handler_name);
345 PetscFunctionReturn(0);
346}
PetscErrorCode Create_WallFreeSlip(BoundaryCondition *bc)
Configures a BoundaryCondition object to behave as a free-slip wall.
PetscErrorCode Create_WallMoving(BoundaryCondition *bc)
Creates a wall moving along itself at a velocity source, the prescribed inlet's without its flux.
PetscErrorCode Create_PeriodicGeometric(BoundaryCondition *bc)
Configures a BoundaryCondition object for geometric periodic coupling.
PetscErrorCode Create_PeriodicDrivenInitial(BoundaryCondition *bc)
Configures a BoundaryCondition object for initial-flux periodic driving.
PetscErrorCode Create_PeriodicDrivenConstant(BoundaryCondition *bc)
Configures a BoundaryCondition object for periodic driven-flow forcing.
PetscErrorCode Create_InletPrescribedVelocity(BoundaryCondition *bc)
Configures a BoundaryCondition object as an inlet whose velocity is a configured source: expressions ...
PetscErrorCode Create_WallNoSlip(BoundaryCondition *bc)
Configures a BoundaryCondition object to behave as a no-slip, stationary wall.
PetscErrorCode Create_OutletConservation(BoundaryCondition *bc)
Configures a BoundaryCondition object for conservative outlet treatment.
const char * BCHandlerTypeToString(BCHandlerType handler_type)
Converts a BCHandlerType enum to its string representation.
Definition logging.c:888
#define LOCAL
Logging scope definitions for controlling message output.
Definition logging.h:45
@ LOG_ERROR
Critical errors that may halt the program.
Definition logging.h:29
@ LOG_DEBUG
Detailed debugging information.
Definition logging.h:32
The "virtual table" struct for a boundary condition handler object.
Definition variables.h:389
PetscErrorCode(* PostStep)(BoundaryCondition *self, BCContext *ctx, PetscReal *local_inflow, PetscReal *local_outflow)
Definition variables.h:396
PetscErrorCode(* PreStep)(BoundaryCondition *self, BCContext *ctx, PetscReal *local_inflow, PetscReal *local_outflow)
Definition variables.h:394
BCHandlerType type
Definition variables.h:390
PetscErrorCode(* Destroy)(BoundaryCondition *self)
Definition variables.h:398
PetscErrorCode(* Initialize)(BoundaryCondition *self, BCContext *ctx)
Definition variables.h:393
PetscErrorCode(* UpdateUbcs)(BoundaryCondition *self, BCContext *ctx)
Definition variables.h:397
PetscErrorCode(* Apply)(BoundaryCondition *self, BCContext *ctx)
Definition variables.h:395
PetscBool needs_repeat_pass
Apply() reads state its own boundary pass changes after it runs (the interior Ucat that Contra2Cart r...
Definition variables.h:402
BCPriorityType priority
Definition variables.h:391
@ BC_HANDLER_PERIODIC_GEOMETRIC
Definition variables.h:352
@ BC_HANDLER_PERIODIC_DRIVEN_INITIAL_FLUX
Definition variables.h:355
@ BC_HANDLER_PERIODIC_DRIVEN_CONSTANT_FLUX
Definition variables.h:354
@ BC_HANDLER_WALL_MOVING
Definition variables.h:346
@ BC_HANDLER_INLET_PRESCRIBED_VELOCITY
Definition variables.h:348
@ BC_HANDLER_WALL_NOSLIP
Definition variables.h:345
@ BC_HANDLER_OUTLET_CONSERVATION
Definition variables.h:350
@ BC_HANDLER_WALL_FREE_SLIP
Definition variables.h:347
Here is the call graph for this function:
Here is the caller graph for this function:

◆ BoundarySystem_Initialize()

PetscErrorCode BoundarySystem_Initialize ( UserCtx *  user,
const char *  bcs_filename 
)

Initializes the entire boundary system.

Parameters
[in,out]userFinest-level block context receiving parsed face configuration.
bcs_filenamePath to the generated boundary-condition definition file.
Returns
PetscErrorCode 0 on success.

Initializes the entire boundary system.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/Boundaries.h.

See also
BoundarySystem_Initialize()

Definition at line 412 of file Boundaries.c.

413{
414 PetscErrorCode ierr;
415 PetscFunctionBeginUser;
417
418 LOG_ALLOW(GLOBAL, LOG_INFO, "Starting creation and initialization of all boundary handlers.\n");
419
420 // =========================================================================
421 // Step 0: Clear any existing boundary handlers (if re-initializing).
422 // This ensures no memory leaks if this function is called multiple times.
423 // =========================================================================
424 for (int i = 0; i < 6; i++) {
425 BoundaryFaceConfig *face_cfg = &user->boundary_faces[i];
426 if (face_cfg->handler) {
427 LOG_ALLOW(LOCAL, LOG_DEBUG, "Destroying existing handler on Face %s before re-initialization.\n", BCFaceToString((BCFace)i));
428 if (face_cfg->handler->Destroy) {
429 ierr = face_cfg->handler->Destroy(face_cfg->handler); CHKERRQ(ierr);
430 }
431 ierr = PetscFree(face_cfg->handler); CHKERRQ(ierr);
432 face_cfg->handler = NULL;
433 }
434 }
435 // =========================================================================
436
437 // Step 0.1: Initiate flux sums to zero
438 user->simCtx->FluxInSum = 0.0;
439 user->simCtx->FluxOutSum = 0.0;
440 user->simCtx->FarFluxInSum = 0.0;
441 user->simCtx->FarFluxOutSum = 0.0;
442 // =========================================================================
443
444 // Step 1: Parse the configuration file to determine user intent.
445 // This function, defined in io.c, populates the configuration enums and parameter
446 // lists within the user->boundary_faces array on all MPI ranks.
447 ierr = ParseAllBoundaryConditions(user, bcs_filename); CHKERRQ(ierr);
448 LOG_ALLOW(GLOBAL, LOG_INFO, "Configuration file '%s' parsed successfully.\n", bcs_filename);
449
450 // Step 1.1: Validate the parsed configuration to ensure there are no Boundary Condition conflicts
451 ierr = BoundarySystem_Validate(user); CHKERRQ(ierr);
452
453 // Step 1.2: Resolve each face's particle policy from its particle_policy parameter (remove when absent).
454 for (int i = 0; i < 6; i++) {
455 BoundaryFaceConfig *face_cfg = &user->boundary_faces[i];
456 const char *policy = NULL;
457 PetscBool found;
458 ierr = GetBCParamString(face_cfg->params, "particle_policy", &policy, &found); CHKERRQ(ierr);
459 if (!found || strcasecmp(policy, "remove") == 0) {
461 } else if (strcasecmp(policy, "reflect") == 0 && face_cfg->mathematical_type != PERIODIC) {
463 } else if (strcasecmp(policy, "wrap") == 0 && face_cfg->mathematical_type == PERIODIC) {
465 } else {
466 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONG, "Face %s (%s): particle_policy '%s' is not supported; use 'remove' or '%s'.",
468 (face_cfg->mathematical_type == PERIODIC) ? "wrap" : "reflect");
469 }
470 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Face %s particle policy: %s.\n", BCFaceToString((BCFace)i),
472 }
473
474 // Step 2: Create and Initialize the handler object for each of the 6 faces.
475 for (int i = 0; i < 6; i++) {
476 BoundaryFaceConfig *face_cfg = &user->boundary_faces[i];
477
478 const char *face_name = BCFaceToString(face_cfg->face_id);
479 const char *type_name = BCTypeToString(face_cfg->mathematical_type);
480 const char *handler_name = BCHandlerTypeToString(face_cfg->handler_type);
481
482 LOG_ALLOW(LOCAL, LOG_DEBUG, "Creating handler for Face %s with Type %s and handler '%s'.\n", face_name, type_name,handler_name);
483
484 // Use the private factory to construct the correct handler object based on the parsed type.
485 // The factory returns a pointer to the new handler object, which we store in the config struct.
486 ierr = BoundaryCondition_Create(face_cfg->handler_type, &face_cfg->handler); CHKERRQ(ierr);
487
488 // Step 3: Call the specific Initialize() method for the newly created handler.
489 // This allows the handler to perform its own setup, like reading parameters from the
490 // face_cfg->params list and setting the initial field values on its face.
491 if (face_cfg->handler && face_cfg->handler->Initialize) {
492 LOG_ALLOW(LOCAL, LOG_DEBUG, "Calling Initialize() method for handler %s(%s) on Face %s.\n",type_name,handler_name,face_name);
493
494 // Prepare the context needed by the Initialize() function.
495 BCContext ctx = {
496 .user = user,
497 .face_id = face_cfg->face_id,
498 .global_inflow_sum = &user->simCtx->FluxInSum, // Global flux sums are not relevant during initialization.
499 .global_outflow_sum = &user->simCtx->FluxOutSum,
500 .global_farfield_inflow_sum = &user->simCtx->FarFluxInSum,
501 .global_farfield_outflow_sum = &user->simCtx->FarFluxOutSum
502 };
503
504 ierr = face_cfg->handler->Initialize(face_cfg->handler, &ctx); CHKERRQ(ierr);
505 } else {
506 LOG_ALLOW(LOCAL, LOG_DEBUG, "Handler %s(%s) for Face %s has no Initialize() method, skipping.\n", type_name,handler_name,face_name);
507 }
508 }
509 // =========================================================================
510 // NO SYNCHRONIZATION NEEDED HERE
511 // =========================================================================
512 // Initialize() only reads parameters and allocates memory.
513 // It does NOT modify field values (Ucat, Ucont, Ubcs).
514 // Field values are set by:
515 // 1. Initial conditions (before this function)
516 // 2. Apply() during timestepping (after this function)
517 // The first call to ApplyBoundaryConditions() will handle synchronization.
518 // =========================================================================
519
520 LOG_ALLOW(GLOBAL, LOG_INFO, "All boundary handlers created and initialized successfully.\n");
522 PetscFunctionReturn(0);
523}
PetscErrorCode BoundarySystem_Validate(UserCtx *user)
Implementation of BoundarySystem_Validate().
Definition Boundaries.c:352
PetscErrorCode BoundaryCondition_Create(BCHandlerType handler_type, BoundaryCondition **new_bc_ptr)
Implementation of BoundaryCondition_Create().
Definition Boundaries.c:265
PetscErrorCode ParseAllBoundaryConditions(UserCtx *user, const char *bcs_input_filename)
Parses the boundary conditions file to configure the type, handler, and any associated parameters for...
Definition io.c:911
PetscErrorCode GetBCParamString(BC_Param *params, const char *key, const char **value_out, PetscBool *found)
Searches a BC_Param linked list for a key and returns its value as a string.
Definition io.c:859
const char * ParticleBoundaryPolicyToString(ParticleBoundaryPolicy policy)
Returns the configuration token for a particle boundary policy.
Definition logging.c:850
const char * BCTypeToString(BCType type)
Returns the canonical log token for a boundary mathematical type.
Definition logging.c:828
PetscReal FarFluxInSum
Definition variables.h:1016
PetscReal FarFluxOutSum
Definition variables.h:1016
SimCtx * simCtx
Back-pointer to the master simulation context.
Definition variables.h:1160
PetscReal FluxOutSum
Definition variables.h:1016
@ PARTICLE_BOUNDARY_REMOVE
The particle leaves the domain (EXITED) and is removed.
Definition variables.h:337
@ PARTICLE_BOUNDARY_REFLECT
The particle is mirrored about the face plane and stays.
Definition variables.h:338
@ PARTICLE_BOUNDARY_WRAP
Periodic faces: the particle re-enters through the paired face.
Definition variables.h:339
BCHandlerType handler_type
Definition variables.h:427
UserCtx * user
Definition variables.h:380
PetscReal FluxInSum
Definition variables.h:1016
ParticleBoundaryPolicy particle_policy
What a particle crossing this face becomes (BC param particle_policy).
Definition variables.h:428
BC_Param * params
Definition variables.h:429
BoundaryCondition * handler
Definition variables.h:430
Provides execution context for a boundary condition handler.
Definition variables.h:379
Holds the complete configuration for one of the six boundary faces.
Definition variables.h:424
Here is the call graph for this function:
Here is the caller graph for this function:

◆ PropagateBoundaryConfigToCoarserLevels()

PetscErrorCode PropagateBoundaryConfigToCoarserLevels ( SimCtx *  simCtx)

Propagates boundary condition configuration from finest to all coarser multigrid levels.

Coarser levels need BC type information for geometric operations (e.g., periodic corrections) but do NOT need full handler objects since timestepping only occurs at the finest level. This function copies the boundary_faces configuration down the hierarchy.

Parameters
simCtxThe master SimCtx containing the multigrid hierarchy
Returns
PetscErrorCode 0 on success

Propagates boundary condition configuration from finest to all coarser multigrid levels.

See also
PropagateBoundaryConfigToCoarserLevels()

Definition at line 530 of file Boundaries.c.

531{
532 PetscErrorCode ierr;
533 UserMG *usermg = &simCtx->usermg;
534
535 PetscFunctionBeginUser;
537
538 LOG_ALLOW(GLOBAL, LOG_INFO, "Propagating BC configuration from finest to coarser multigrid levels...\n");
539
540 // Loop from second-finest down to coarsest
541 for (PetscInt level = usermg->mglevels - 2; level >= 0; level--) {
542 for (PetscInt bi = 0; bi < simCtx->block_number; bi++) {
543 UserCtx *user_coarse = &usermg->mgctx[level].user[bi];
544 UserCtx *user_fine = &usermg->mgctx[level + 1].user[bi];
545
546 LOG_ALLOW_SYNC(LOCAL, LOG_DEBUG, "Rank %d: Copying BC config from level %" PetscInt_FMT " to level %" PetscInt_FMT ", block %" PetscInt_FMT "\n",
547 simCtx->rank, level + 1, level, bi);
548
549 // Copy the 6 boundary face configurations
550 for (int face_i = 0; face_i < 6; face_i++) {
551 user_coarse->boundary_faces[face_i].face_id = user_fine->boundary_faces[face_i].face_id;
552 user_coarse->boundary_faces[face_i].mathematical_type = user_fine->boundary_faces[face_i].mathematical_type;
553 user_coarse->boundary_faces[face_i].handler_type = user_fine->boundary_faces[face_i].handler_type;
554 user_coarse->boundary_faces[face_i].particle_policy = user_fine->boundary_faces[face_i].particle_policy;
555
556 // Copy parameter list (deep copy)
557 FreeBC_ParamList(user_coarse->boundary_faces[face_i].params); // Clear any existing
558 user_coarse->boundary_faces[face_i].params = NULL;
559
560 BC_Param **dst_next = &user_coarse->boundary_faces[face_i].params;
561 for (BC_Param *src = user_fine->boundary_faces[face_i].params; src; src = src->next) {
562 BC_Param *new_param;
563 ierr = PetscMalloc1(1, &new_param); CHKERRQ(ierr);
564 ierr = PetscStrallocpy(src->key, &new_param->key); CHKERRQ(ierr);
565 ierr = PetscStrallocpy(src->value, &new_param->value); CHKERRQ(ierr);
566 new_param->next = NULL;
567 *dst_next = new_param;
568 dst_next = &new_param->next;
569 }
570
571 // IMPORTANT: Do NOT create handler objects for coarser levels
572 // Handlers are only needed at finest level for timestepping Apply() calls
573 user_coarse->boundary_faces[face_i].handler = NULL;
574 }
575
576 // Propagate the particle inlet lookup fields to coarse levels as well.
577 user_coarse->inletFaceDefined = user_fine->inletFaceDefined;
578 user_coarse->identifiedInletBCFace = user_fine->identifiedInletBCFace;
579 }
580 }
581
582 LOG_ALLOW(GLOBAL, LOG_INFO, "BC configuration propagation complete.\n");
583
585 PetscFunctionReturn(0);
586}
void FreeBC_ParamList(BC_Param *head)
Frees an entire linked list of boundary-condition parameters.
Definition io.c:719
#define LOG_ALLOW_SYNC(scope, level, fmt,...)
Synchronized logging macro that checks both the log level and whether the calling function is in the ...
Definition logging.h:273
UserCtx * user
Definition variables.h:768
PetscBool inletFaceDefined
Definition variables.h:1183
PetscMPIInt rank
Definition variables.h:919
PetscInt block_number
Definition variables.h:1009
BCFace identifiedInletBCFace
Definition variables.h:1184
struct BC_Param_s * next
Definition variables.h:375
char * key
Definition variables.h:373
UserMG usermg
Definition variables.h:1082
char * value
Definition variables.h:374
PetscInt mglevels
Definition variables.h:775
MGCtx * mgctx
Definition variables.h:778
A node in a linked list for storing key-value parameters from the bcs.dat file.
Definition variables.h:372
User-defined context containing data specific to a single computational grid level.
Definition variables.h:1157
User-level context for managing the entire multigrid hierarchy.
Definition variables.h:774
Here is the call graph for this function:
Here is the caller graph for this function:

◆ BoundarySystem_ExecuteStep()

PetscErrorCode BoundarySystem_ExecuteStep ( UserCtx *  user)

Executes one full boundary condition update cycle for a time step.

Parameters
[in,out]userBlock context whose boundary handlers update target values and fluxes.
Returns
PetscErrorCode 0 on success.

Executes one full boundary condition update cycle for a time step.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/Boundaries.h.

See also
BoundarySystem_ExecuteStep()

Definition at line 600 of file Boundaries.c.

601{
602 PetscErrorCode ierr;
603 PetscFunctionBeginUser;
605
606 LOG_ALLOW(LOCAL, LOG_DEBUG, "Starting.\n");
607
608 // =========================================================================
609 // PRIORITY 0: INLETS
610 // =========================================================================
611
612 PetscReal local_inflow_pre = 0.0;
613 PetscReal local_inflow_post = 0.0;
614 PetscReal global_inflow_pre = 0.0;
615 PetscReal global_inflow_post = 0.0;
616 PetscInt num_handlers[3] = {0,0,0};
617
618 LOG_ALLOW(LOCAL, LOG_TRACE, " (INLETS): Begin.\n");
619
620 // Phase 1: PreStep - Preparation (e.g., calculate profiles, read files)
621 for (int i = 0; i < 6; i++) {
622 BoundaryCondition *handler = user->boundary_faces[i].handler;
623 if (!handler || handler->priority != BC_PRIORITY_INLET) continue;
624 if (!handler->PreStep) continue;
625
626 num_handlers[0]++;
627 BCContext ctx = {
628 .user = user,
629 .face_id = (BCFace)i,
630 .global_inflow_sum = NULL,
631 .global_outflow_sum = NULL,
632 .global_farfield_inflow_sum = &user->simCtx->FarFluxInSum,
633 .global_farfield_outflow_sum = &user->simCtx->FarFluxOutSum
634 };
635
636 LOG_ALLOW(LOCAL, LOG_TRACE, " PreStep: Face %d (%s)\n", i, BCFaceToString((BCFace)i));
637 ierr = handler->PreStep(handler, &ctx, &local_inflow_pre, NULL); CHKERRQ(ierr);
638 }
639
640 // Optional: Global communication for PreStep (for debugging)
641 if (local_inflow_pre != 0.0) {
642 ierr = MPI_Allreduce(&local_inflow_pre, &global_inflow_pre, 1, MPIU_REAL,
643 MPI_SUM, PETSC_COMM_WORLD); CHKERRQ(ierr);
644 LOG_ALLOW(GLOBAL, LOG_TRACE, " PreStep predicted flux: %.6e\n", global_inflow_pre);
645 }
646
647 // Phase 2: Apply - Set boundary conditions
648 for (int i = 0; i < 6; i++) {
649 BoundaryCondition *handler = user->boundary_faces[i].handler;
650 if (!handler || handler->priority != BC_PRIORITY_INLET) continue;
651 if(!handler->Apply) continue; // For example Periodic BCs
652
653 num_handlers[1]++;
654
655 BCContext ctx = {
656 .user = user,
657 .face_id = (BCFace)i,
658 .global_inflow_sum = NULL,
659 .global_outflow_sum = NULL,
660 .global_farfield_inflow_sum = &user->simCtx->FarFluxInSum,
661 .global_farfield_outflow_sum = &user->simCtx->FarFluxOutSum
662 };
663
664 LOG_ALLOW(LOCAL, LOG_TRACE, " Apply: Face %d (%s)\n", i, BCFaceToString((BCFace)i));
665 ierr = handler->Apply(handler, &ctx); CHKERRQ(ierr);
666 }
667
668 // Phase 3: PostStep - Measure actual flux
669 for (int i = 0; i < 6; i++) {
670 BoundaryCondition *handler = user->boundary_faces[i].handler;
671 if (!handler || handler->priority != BC_PRIORITY_INLET) continue;
672 if (!handler->PostStep) continue;
673
674 num_handlers[2]++;
675
676 BCContext ctx = {
677 .user = user,
678 .face_id = (BCFace)i,
679 .global_inflow_sum = NULL,
680 .global_outflow_sum = NULL,
681 .global_farfield_inflow_sum = &user->simCtx->FarFluxInSum,
682 .global_farfield_outflow_sum = &user->simCtx->FarFluxOutSum
683 };
684
685 LOG_ALLOW(LOCAL, LOG_TRACE, " PostStep: Face %d (%s)\n", i, BCFaceToString((BCFace)i));
686 ierr = handler->PostStep(handler, &ctx, &local_inflow_post, NULL); CHKERRQ(ierr);
687 }
688
689 // Phase 4: Global communication - Sum flux for other priorities to use
690 ierr = MPI_Allreduce(&local_inflow_post, &global_inflow_post, 1, MPIU_REAL,
691 MPI_SUM, PETSC_COMM_WORLD); CHKERRQ(ierr);
692
693 // Store for next priority levels
694 user->simCtx->FluxInSum = global_inflow_post;
695
697 " (INLETS): %" PetscInt_FMT " Prestep(s), %" PetscInt_FMT " Application(s), %" PetscInt_FMT " Poststep(s), FluxInSum = %.6e\n",
698 num_handlers[0],num_handlers[1],num_handlers[2], global_inflow_post);
699
700 // =========================================================================
701 // PRIORITY 1: FARFIELD
702 // =========================================================================
703
704 PetscReal local_farfield_in_pre = 0.0;
705 PetscReal local_farfield_out_pre = 0.0;
706 PetscReal local_farfield_in_post = 0.0;
707 PetscReal local_farfield_out_post = 0.0;
708 PetscReal global_farfield_in_pre = 0.0;
709 PetscReal global_farfield_out_pre = 0.0;
710 PetscReal global_farfield_in_post = 0.0;
711 PetscReal global_farfield_out_post = 0.0;
712 memset(num_handlers,0,sizeof(num_handlers));
713
714 LOG_ALLOW(LOCAL, LOG_TRACE, " (FARFIELD): Begin.\n");
715
716 // Phase 1: PreStep - Analyze flow direction, measure initial flux
717 for (int i = 0; i < 6; i++) {
718 BoundaryCondition *handler = user->boundary_faces[i].handler;
719 if (!handler || handler->priority != BC_PRIORITY_FARFIELD) continue;
720 if (!handler->PreStep) continue;
721
722 num_handlers[0]++;
723 BCContext ctx = {
724 .user = user,
725 .face_id = (BCFace)i,
726 .global_inflow_sum = &user->simCtx->FluxInSum, // Available from Priority 0
727 .global_outflow_sum = NULL,
728 .global_farfield_inflow_sum = &user->simCtx->FarFluxInSum,
729 .global_farfield_outflow_sum = &user->simCtx->FarFluxOutSum
730 };
731
732 LOG_ALLOW(LOCAL, LOG_TRACE, " PreStep: Face %d (%s)\n", i, BCFaceToString((BCFace)i));
733 ierr = handler->PreStep(handler, &ctx, &local_farfield_in_pre, &local_farfield_out_pre);
734 CHKERRQ(ierr);
735 }
736
737 // Phase 2: Global communication (optional, for debugging)
738 if (local_farfield_in_pre != 0.0 || local_farfield_out_pre != 0.0) {
739 ierr = MPI_Allreduce(&local_farfield_in_pre, &global_farfield_in_pre, 1, MPIU_REAL,
740 MPI_SUM, PETSC_COMM_WORLD); CHKERRQ(ierr);
741 ierr = MPI_Allreduce(&local_farfield_out_pre, &global_farfield_out_pre, 1, MPIU_REAL,
742 MPI_SUM, PETSC_COMM_WORLD); CHKERRQ(ierr);
743
745 " Farfield pre-analysis: In=%.6e, Out=%.6e\n",
746 global_farfield_in_pre, global_farfield_out_pre);
747 }
748
749 // Phase 3: Apply - Set farfield boundary conditions
750 for (int i = 0; i < 6; i++) {
751 BoundaryCondition *handler = user->boundary_faces[i].handler;
752 if (!handler || handler->priority != BC_PRIORITY_FARFIELD) continue;
753 if(!handler->Apply) continue; // For example Periodic BCs
754
755 num_handlers[1]++;
756
757 BCContext ctx = {
758 .user = user,
759 .face_id = (BCFace)i,
760 .global_inflow_sum = &user->simCtx->FluxInSum,
761 .global_outflow_sum = NULL,
762 .global_farfield_inflow_sum = &user->simCtx->FarFluxInSum,
763 .global_farfield_outflow_sum = &user->simCtx->FarFluxOutSum
764 };
765
766 LOG_ALLOW(LOCAL, LOG_TRACE, " Apply: Face %d (%s)\n", i, BCFaceToString((BCFace)i));
767 ierr = handler->Apply(handler, &ctx); CHKERRQ(ierr);
768 }
769
770 // Phase 4: PostStep - Measure actual farfield fluxes
771 for (int i = 0; i < 6; i++) {
772 BoundaryCondition *handler = user->boundary_faces[i].handler;
773 if (!handler || handler->priority != BC_PRIORITY_FARFIELD) continue;
774 if (!handler->PostStep) continue;
775
776 num_handlers[2]++;
777
778 BCContext ctx = {
779 .user = user,
780 .face_id = (BCFace)i,
781 .global_inflow_sum = &user->simCtx->FluxInSum,
782 .global_outflow_sum = NULL,
783 .global_farfield_inflow_sum = &user->simCtx->FarFluxInSum,
784 .global_farfield_outflow_sum = &user->simCtx->FarFluxOutSum
785 };
786
787 LOG_ALLOW(LOCAL, LOG_TRACE, " PostStep: Face %d (%s)\n", i, BCFaceToString((BCFace)i));
788 ierr = handler->PostStep(handler, &ctx, &local_farfield_in_post, &local_farfield_out_post);
789 CHKERRQ(ierr);
790 }
791
792 // Phase 5: Global communication - Store for outlet priority
793 if (num_handlers > 0) {
794 ierr = MPI_Allreduce(&local_farfield_in_post, &global_farfield_in_post, 1, MPIU_REAL,
795 MPI_SUM, PETSC_COMM_WORLD); CHKERRQ(ierr);
796 ierr = MPI_Allreduce(&local_farfield_out_post, &global_farfield_out_post, 1, MPIU_REAL,
797 MPI_SUM, PETSC_COMM_WORLD); CHKERRQ(ierr);
798
799 // Store for outlet handlers to use
800 user->simCtx->FarFluxInSum = global_farfield_in_post;
801 user->simCtx->FarFluxOutSum = global_farfield_out_post;
802
804 " (FARFIELD): %" PetscInt_FMT " Prestep(s), %" PetscInt_FMT " Application(s), %" PetscInt_FMT " Poststep(s) , InFlux=%.6e, OutFlux=%.6e\n",
805 num_handlers[0],num_handlers[1],num_handlers[2], global_farfield_in_post, global_farfield_out_post);
806 } else {
807 // No farfield handlers - zero out the fluxes
808 user->simCtx->FarFluxInSum = 0.0;
809 user->simCtx->FarFluxOutSum = 0.0;
810 }
811
812
813 // =========================================================================
814 // PRIORITY 2: WALLS
815 // =========================================================================
816
817 memset(num_handlers,0,sizeof(num_handlers));
818
819 LOG_ALLOW(LOCAL, LOG_TRACE, " (WALLS): Begin.\n");
820
821 // Phase 1: PreStep - Preparation (usually no-op for walls)
822 for (int i = 0; i < 6; i++) {
823 BoundaryCondition *handler = user->boundary_faces[i].handler;
824 if (!handler || handler->priority != BC_PRIORITY_WALL) continue;
825 if (!handler->PreStep) continue;
826
827 num_handlers[0]++;
828 BCContext ctx = {
829 .user = user,
830 .face_id = (BCFace)i,
831 .global_inflow_sum = &user->simCtx->FluxInSum,
832 .global_outflow_sum = NULL,
833 .global_farfield_inflow_sum = &user->simCtx->FarFluxInSum,
834 .global_farfield_outflow_sum = &user->simCtx->FarFluxOutSum
835 };
836
837 LOG_ALLOW(LOCAL, LOG_TRACE, " PreStep: Face %d (%s)\n", i, BCFaceToString((BCFace)i));
838 ierr = handler->PreStep(handler, &ctx, NULL, NULL); CHKERRQ(ierr);
839 }
840
841 // No global communication needed for walls
842
843 // Phase 2: Apply - Set boundary conditions
844 for (int i = 0; i < 6; i++) {
845 BoundaryCondition *handler = user->boundary_faces[i].handler;
846 if (!handler || handler->priority != BC_PRIORITY_WALL) continue;
847 if(!handler->Apply) continue; // For example Periodic BCs
848
849 num_handlers[1]++;
850
851 BCContext ctx = {
852 .user = user,
853 .face_id = (BCFace)i,
854 .global_inflow_sum = &user->simCtx->FluxInSum,
855 .global_outflow_sum = NULL,
856 .global_farfield_inflow_sum = &user->simCtx->FarFluxInSum,
857 .global_farfield_outflow_sum = &user->simCtx->FarFluxOutSum
858 };
859
860 LOG_ALLOW(LOCAL, LOG_TRACE, " Apply: Face %d (%s)\n", i, BCFaceToString((BCFace)i));
861 ierr = handler->Apply(handler, &ctx); CHKERRQ(ierr);
862 }
863
864 // Phase 3: PostStep - Post-application processing (usually no-op for walls)
865 for (int i = 0; i < 6; i++) {
866 BoundaryCondition *handler = user->boundary_faces[i].handler;
867 if (!handler || handler->priority != BC_PRIORITY_WALL) continue;
868 if (!handler->PostStep) continue;
869
870 num_handlers[2]++;
871
872 BCContext ctx = {
873 .user = user,
874 .face_id = (BCFace)i,
875 .global_inflow_sum = &user->simCtx->FluxInSum,
876 .global_outflow_sum = NULL,
877 .global_farfield_inflow_sum = &user->simCtx->FarFluxInSum,
878 .global_farfield_outflow_sum = &user->simCtx->FarFluxOutSum
879 };
880
881 LOG_ALLOW(LOCAL, LOG_TRACE, " PostStep: Face %d (%s)\n", i, BCFaceToString((BCFace)i));
882 ierr = handler->PostStep(handler, &ctx, NULL, NULL); CHKERRQ(ierr);
883 }
884
885 // No global communication needed for walls
886
887 LOG_ALLOW(GLOBAL, LOG_INFO, " (WALLS): %" PetscInt_FMT " Prestep(s), %" PetscInt_FMT " Application(s), %" PetscInt_FMT " Poststep(s) applied.\n",
888 num_handlers[0],num_handlers[1],num_handlers[2]);
889
890
891 // =========================================================================
892 // PRIORITY 3: OUTLETS
893 // =========================================================================
894
895 PetscReal local_outflow_pre = 0.0;
896 PetscReal local_outflow_post = 0.0;
897 PetscReal global_outflow_pre = 0.0;
898 PetscReal global_outflow_post = 0.0;
899 memset(num_handlers,0,sizeof(num_handlers));
900
901 LOG_ALLOW(LOCAL, LOG_TRACE, " (OUTLETS): Begin.\n");
902
903 // Phase 1: PreStep - Measure uncorrected outflow (from ucat)
904 for (int i = 0; i < 6; i++) {
905 BoundaryCondition *handler = user->boundary_faces[i].handler;
906 if (!handler || handler->priority != BC_PRIORITY_OUTLET) continue;
907 if (!handler->PreStep) continue;
908
909 num_handlers[0]++;
910 BCContext ctx = {
911 .user = user,
912 .face_id = (BCFace)i,
913 .global_inflow_sum = &user->simCtx->FluxInSum, // From Priority 0
914 .global_outflow_sum = NULL,
915 .global_farfield_inflow_sum = &user->simCtx->FarFluxInSum,
916 .global_farfield_outflow_sum = &user->simCtx->FarFluxOutSum
917 };
918
919 LOG_ALLOW(LOCAL, LOG_TRACE, " PreStep: Face %d (%s)\n", i, BCFaceToString((BCFace)i));
920 ierr = handler->PreStep(handler, &ctx, NULL, &local_outflow_pre); CHKERRQ(ierr);
921 }
922
923 // Phase 2: Global communication - Get uncorrected outflow sum
924 ierr = MPI_Allreduce(&local_outflow_pre, &global_outflow_pre, 1, MPIU_REAL,
925 MPI_SUM, PETSC_COMM_WORLD); CHKERRQ(ierr);
926
927 // Calculate total inflow (inlet + farfield inflow)
928 PetscReal total_inflow = user->simCtx->FluxInSum + user->simCtx->FarFluxInSum;
929
931 " Uncorrected outflow: %.6e, Total inflow: %.6e (Inlet: %.6e + Farfield: %.6e)\n",
932 global_outflow_pre, total_inflow, user->simCtx->FluxInSum,
933 user->simCtx->FarFluxInSum);
934
935 // Phase 3: Apply - Set corrected boundary conditions
936 for (int i = 0; i < 6; i++) {
937 BoundaryCondition *handler = user->boundary_faces[i].handler;
938 if (!handler || handler->priority != BC_PRIORITY_OUTLET) continue;
939 if(!handler->Apply) continue; // For example Periodic BCs
940
941 num_handlers[1]++;
942
943 BCContext ctx = {
944 .user = user,
945 .face_id = (BCFace)i,
946 .global_inflow_sum = &user->simCtx->FluxInSum, // From Priority 0
947 .global_outflow_sum = &global_outflow_pre, // From PreStep above
948 .global_farfield_inflow_sum = &user->simCtx->FarFluxInSum,
949 .global_farfield_outflow_sum = &user->simCtx->FarFluxOutSum
950 };
951
952 LOG_ALLOW(LOCAL, LOG_TRACE, " Apply: Face %d (%s)\n", i, BCFaceToString((BCFace)i));
953 ierr = handler->Apply(handler, &ctx); CHKERRQ(ierr);
954 }
955
956 // Phase 4: PostStep - Measure corrected outflow (verification)
957 for (int i = 0; i < 6; i++) {
958 BoundaryCondition *handler = user->boundary_faces[i].handler;
959 if (!handler || handler->priority != BC_PRIORITY_OUTLET) continue;
960 if (!handler->PostStep) continue;
961
962 num_handlers[2]++;
963
964 BCContext ctx = {
965 .user = user,
966 .face_id = (BCFace)i,
967 .global_inflow_sum = &user->simCtx->FluxInSum,
968 .global_outflow_sum = &global_outflow_pre,
969 .global_farfield_inflow_sum = &user->simCtx->FarFluxInSum,
970 .global_farfield_outflow_sum = &user->simCtx->FarFluxOutSum
971 };
972
973 LOG_ALLOW(LOCAL, LOG_TRACE, " PostStep: Face %d (%s)\n", i, BCFaceToString((BCFace)i));
974 ierr = handler->PostStep(handler, &ctx, NULL, &local_outflow_post); CHKERRQ(ierr);
975 }
976
977 // Phase 5: Global communication - Verify conservation
978 ierr = MPI_Allreduce(&local_outflow_post, &global_outflow_post, 1, MPIU_REAL,
979 MPI_SUM, PETSC_COMM_WORLD); CHKERRQ(ierr);
980
981 // Store for global reporting.
982 user->simCtx->FluxOutSum = global_outflow_post;
983
984 // Conservation check (compare total outflow vs total inflow)
985 PetscReal total_outflow = global_outflow_post + user->simCtx->FarFluxOutSum;
986 PetscReal flux_error = PetscAbsReal(total_outflow - total_inflow);
987 PetscReal relative_error = (total_inflow > 1e-16) ?
988 flux_error / total_inflow : flux_error;
989
991 " (OUTLETS): %" PetscInt_FMT " Prestep(s), %" PetscInt_FMT " Application(s), %" PetscInt_FMT " Poststep(s), FluxOutSum = %.6e\n",
992 num_handlers[0],num_handlers[1],num_handlers[2], global_outflow_post);
994 " Conservation: Total In=%.6e, Total Out=%.6e, Error=%.3e (%.2e)%%)\n",
995 total_inflow, total_outflow, flux_error, relative_error * 100.0);
996
997 if (relative_error > 1e-6) {
999 " WARNING: Large mass conservation error (%.2e%%)!\n",
1000 relative_error * 100.0);
1001 }
1002
1003
1004 LOG_ALLOW(LOCAL, LOG_VERBOSE, "Complete.\n");
1005
1007 PetscFunctionReturn(0);
1008}
@ LOG_TRACE
Very fine-grained tracing information for in-depth debugging.
Definition logging.h:33
@ LOG_WARNING
Non-critical issues that warrant attention.
Definition logging.h:30
@ LOG_VERBOSE
Extremely detailed logs, typically for development use only.
Definition logging.h:34
@ BC_PRIORITY_OUTLET
Definition variables.h:364
@ BC_PRIORITY_FARFIELD
Definition variables.h:362
@ BC_PRIORITY_WALL
Definition variables.h:363
@ BC_PRIORITY_INLET
Definition variables.h:361
Here is the call graph for this function:
Here is the caller graph for this function:

◆ BoundarySystem_RefreshUbcs()

PetscErrorCode BoundarySystem_RefreshUbcs ( UserCtx *  user)

(Private) A lightweight execution engine that calls the UpdateUbcs() method on all relevant handlers.

This function's sole purpose is to re-evaluate the target boundary values (ubcs) for flow-dependent boundary conditions (e.g., Symmetry, Outlets) after the interior velocity field has changed, such as after the projection step.

It operates based on a "pull" model: it iterates through all boundary handlers and executes their UpdateUbcs method only if the handler has provided one. This makes the system extensible, as new flow-dependent handlers can be added without changing this engine. Handlers for fixed boundary conditions (e.g., a wall with a constant velocity) will have their UpdateUbcs pointer set to NULL and will be skipped automatically.

Note
This function is a critical part of the post-projection refresh. It intentionally does NOT modify ucont and does NOT perform flux balancing.
Parameters
userThe main UserCtx struct.
Returns
PetscErrorCode 0 on success.

(Private) A lightweight execution engine that calls the UpdateUbcs() method on all relevant handlers.

See also
BoundarySystem_RefreshUbcs()

Definition at line 1020 of file Boundaries.c.

1021{
1022 PetscErrorCode ierr;
1023 PetscFunctionBeginUser;
1025
1026 LOG_ALLOW(GLOBAL, LOG_TRACE, "Refreshing `ubcs` targets for flow-dependent boundaries...\n");
1027
1028 // Loop through all 6 faces of the domain
1029 for (int i = 0; i < 6; i++) {
1030 BoundaryCondition *handler = user->boundary_faces[i].handler;
1031
1032 // THE FILTER:
1033 // This is the core logic. We only act if a handler exists for the face
1034 // AND that handler has explicitly implemented the `UpdateUbcs` method.
1035 if (handler && handler->UpdateUbcs) {
1036
1037 const char *face_name = BCFaceToString((BCFace)i);
1038 LOG_ALLOW(LOCAL, LOG_TRACE, " Calling UpdateUbcs() for handler on Face %s.\n", face_name);
1039
1040 // Prepare the context. For this refresh step, we don't need to pass flux sums.
1041 BCContext ctx = {
1042 .user = user,
1043 .face_id = (BCFace)i,
1044 .global_inflow_sum = NULL,
1045 .global_outflow_sum = NULL,
1046 .global_farfield_inflow_sum = NULL,
1047 .global_farfield_outflow_sum = NULL
1048 };
1049
1050 // Call the handler's specific UpdateUbcs function pointer.
1051 ierr = handler->UpdateUbcs(handler, &ctx); CHKERRQ(ierr);
1052 }
1053 }
1054
1056 PetscFunctionReturn(0);
1057}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ BoundarySystem_Destroy()

PetscErrorCode BoundarySystem_Destroy ( UserCtx *  user)

Cleans up and destroys all boundary system resources.

Parameters
[in,out]userBlock context whose boundary handlers and temporary state are released.
Returns
PetscErrorCode 0 on success.

Cleans up and destroys all boundary system resources.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/Boundaries.h.

See also
BoundarySystem_Destroy()

Definition at line 1070 of file Boundaries.c.

1071{
1072 PetscErrorCode ierr;
1073 PetscFunctionBeginUser;
1075
1076
1077
1078 LOG_ALLOW(GLOBAL, LOG_INFO, "Starting destruction of all boundary handlers. \n");
1079
1080 for (int i = 0; i < 6; i++) {
1081 BoundaryFaceConfig *face_cfg = &user->boundary_faces[i];
1082 const char *face_name = BCFaceToString(face_cfg->face_id);
1083
1084 // --- Step 1: Free the parameter linked list associated with this face ---
1085 if (face_cfg->params) {
1086 LOG_ALLOW(LOCAL, LOG_DEBUG, " Freeing parameter list for Face %d (%s). \n", i, face_name);
1087 FreeBC_ParamList(face_cfg->params);
1088 face_cfg->params = NULL; // Good practice to nullify dangling pointers
1089 }
1090
1091 // --- Step 2: Destroy the handler object itself ---
1092 if (face_cfg->handler) {
1093 const char *handler_name = BCHandlerTypeToString(face_cfg->handler->type);
1094 LOG_ALLOW(LOCAL, LOG_DEBUG, " Destroying handler '%s' on Face %d (%s).\n", handler_name, i, face_name);
1095
1096 // Call the handler's specific cleanup function first, if it exists.
1097 // This will free any memory stored in the handler's private `data` pointer.
1098 if (face_cfg->handler->Destroy) {
1099 ierr = face_cfg->handler->Destroy(face_cfg->handler); CHKERRQ(ierr);
1100 }
1101
1102 // Finally, free the generic BoundaryCondition object itself.
1103 ierr = PetscFree(face_cfg->handler); CHKERRQ(ierr);
1104 face_cfg->handler = NULL;
1105 }
1106 }
1107
1108 LOG_ALLOW(GLOBAL, LOG_INFO, "Destruction complete.\n");
1110 PetscFunctionReturn(0);
1111}
#define PROFILE_HELPER_BEGIN
Marks the beginning of a profiled helper: timed only when enabled by name.
Definition logging.h:1014
#define PROFILE_HELPER_END
Alias of PROFILE_FUNCTION_END for a function that began with PROFILE_HELPER_BEGIN.
Definition logging.h:1033
Here is the call graph for this function:
Here is the caller graph for this function:

◆ CanRankServiceFace()

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.

This function is a general utility for parallel boundary operations. It checks if the local domain of the current MPI rank is adjacent to a specified global boundary face. A rank "services" a face if it owns the cells adjacent to that global boundary and has a non-zero extent (i.e., owns at least one cell) in the tangential dimensions of that face.

Parameters
infoPointer to the DMDALocalInfo for the current rank's DA.
IM_nodes_globalGlobal number of nodes in the I-direction (e.g., user->IM + 1 if user->IM is cell count).
JM_nodes_globalGlobal number of nodes in the J-direction.
KM_nodes_globalGlobal number of nodes in the K-direction.
face_idThe specific global face (e.g., BC_FACE_NEG_Z) to check.
[out]can_service_outPointer to a PetscBool; set to PETSC_TRUE if the rank services the face, PETSC_FALSE otherwise.
Returns
PetscErrorCode 0 on success.

Determines if the current MPI rank owns any part of a specified global face.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/Boundaries.h.

See also
CanRankServiceFace()

Definition at line 22 of file Boundaries.c.

24{
25 PetscErrorCode ierr;
26 PetscMPIInt rank_for_logging;
27 PetscFunctionBeginUser;
28
30
31 rank_for_logging = PetscGlobalRank;
32
33 *can_service_out = PETSC_FALSE; // Default to no service
34
35 // Get the range of cells owned by this rank
36 PetscInt owned_start_cell_i, num_owned_cells_on_rank_i;
37 PetscInt owned_start_cell_j, num_owned_cells_on_rank_j;
38 PetscInt owned_start_cell_k, num_owned_cells_on_rank_k;
39 ierr = GetOwnedCellRange(info, 0, &owned_start_cell_i, &num_owned_cells_on_rank_i); CHKERRQ(ierr);
40 ierr = GetOwnedCellRange(info, 1, &owned_start_cell_j, &num_owned_cells_on_rank_j); CHKERRQ(ierr);
41 ierr = GetOwnedCellRange(info, 2, &owned_start_cell_k, &num_owned_cells_on_rank_k); CHKERRQ(ierr);
42
43 // Determine the global index of the last cell (0-indexed) in each direction.
44 PetscInt last_global_cell_idx_i = (IM_nodes_global > 1) ? (IM_nodes_global - 2) : -1;
45 PetscInt last_global_cell_idx_j = (JM_nodes_global > 1) ? (JM_nodes_global - 2) : -1;
46 PetscInt last_global_cell_idx_k = (KM_nodes_global > 1) ? (KM_nodes_global - 2) : -1;
47
48 switch (face_id) {
49 case BC_FACE_NEG_X:
50 if (info->xs == 0 && num_owned_cells_on_rank_i > 0 &&
51 num_owned_cells_on_rank_j > 0 && num_owned_cells_on_rank_k > 0) {
52 *can_service_out = PETSC_TRUE;
53 }
54 break;
55 case BC_FACE_POS_X:
56 if (last_global_cell_idx_i >= 0 &&
57 (owned_start_cell_i + num_owned_cells_on_rank_i - 1) == last_global_cell_idx_i &&
58 num_owned_cells_on_rank_j > 0 && num_owned_cells_on_rank_k > 0) {
59 *can_service_out = PETSC_TRUE;
60 }
61 break;
62 case BC_FACE_NEG_Y:
63 if (info->ys == 0 && num_owned_cells_on_rank_j > 0 &&
64 num_owned_cells_on_rank_i > 0 && num_owned_cells_on_rank_k > 0) {
65 *can_service_out = PETSC_TRUE;
66 }
67 break;
68 case BC_FACE_POS_Y:
69 if (last_global_cell_idx_j >= 0 &&
70 (owned_start_cell_j + num_owned_cells_on_rank_j - 1) == last_global_cell_idx_j &&
71 num_owned_cells_on_rank_i > 0 && num_owned_cells_on_rank_k > 0) {
72 *can_service_out = PETSC_TRUE;
73 }
74 break;
75 case BC_FACE_NEG_Z:
76 if (info->zs == 0 && num_owned_cells_on_rank_k > 0 &&
77 num_owned_cells_on_rank_i > 0 && num_owned_cells_on_rank_j > 0) {
78 *can_service_out = PETSC_TRUE;
79 }
80 break;
81 case BC_FACE_POS_Z:
82 if (last_global_cell_idx_k >= 0 &&
83 (owned_start_cell_k + num_owned_cells_on_rank_k - 1) == last_global_cell_idx_k &&
84 num_owned_cells_on_rank_i > 0 && num_owned_cells_on_rank_j > 0) {
85 *can_service_out = PETSC_TRUE;
86 }
87 break;
88 default:
89 LOG_ALLOW(LOCAL, LOG_WARNING, "Rank %d: Unknown face enum %d. \n", rank_for_logging, face_id);
90 break;
91 }
92
93 LOG_ALLOW(LOCAL, LOG_DEBUG, "Rank %d check for face %s: Result=%s. \n",
94 rank_for_logging, BCFaceToString((BCFace)face_id), (*can_service_out ? "TRUE" : "FALSE"));
95
97
98 PetscFunctionReturn(0);
99}
PetscErrorCode GetOwnedCellRange(const DMDALocalInfo *info_nodes, PetscInt dim, PetscInt *xs_cell_global_out, PetscInt *xm_cell_local_out)
Determines the global starting index and number of CELLS owned by the current processor in a specifie...
Definition setup.c:3021
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GetBoundaryFaceElements()

PetscErrorCode GetBoundaryFaceElements ( UserCtx *  user,
BCFace  face_id,
BoundaryFaceElements *  elements 
)

The elements of a boundary face this rank owns, as index ranges.

Purely local: it reads the block's decomposition through CanRankServiceFace() and GetOwnedInteriorCellBounds(), allocates nothing and communicates nothing, so a per-pass loop over a face's elements may call it freely. Edge and corner elements of the face are those of the interior cells beside it; the dummy rows of the other faces are not included.

Parameters
[in]userBlock context.
[in]face_idFace.
[out]elementsAxes, the face's metric/flux layer, and the owned tangential ranges; n is zero along both axes when this rank does not serve the face.
Returns
PetscErrorCode 0 on success.

The elements of a boundary face this rank owns, as index ranges.

See also
GetBoundaryFaceElements()

Definition at line 105 of file Boundaries.c.

106{
107 const DMDALocalInfo *info = &user->info;
108 const PetscInt nodes[3] = {info->mx, info->my, info->mz};
109 const PetscBool negative = (PetscBool)((PetscInt)face_id % 2 == 0);
110 PetscBool can_service = PETSC_FALSE;
111 PetscInt lo[3], hi[3];
112
113 PetscFunctionBeginUser;
115 elements->normal = (PetscInt)face_id / 2;
116 elements->a = (elements->normal == 0) ? 1 : 0;
117 elements->b = (elements->normal == 2) ? 1 : 2;
118 elements->layer = negative ? 0 : nodes[elements->normal] - 2;
119 PetscCall(CanRankServiceFace(info, user->IM, user->JM, user->KM, face_id, &can_service));
120 GetOwnedInteriorCellBounds(info, lo, hi);
121 elements->lo[0] = lo[elements->a];
122 elements->lo[1] = lo[elements->b];
123 elements->n[0] = can_service ? hi[elements->a] - lo[elements->a] : 0;
124 elements->n[1] = can_service ? hi[elements->b] - lo[elements->b] : 0;
126 PetscFunctionReturn(PETSC_SUCCESS);
127}
PetscErrorCode CanRankServiceFace(const DMDALocalInfo *info, PetscInt IM_nodes_global, PetscInt JM_nodes_global, PetscInt KM_nodes_global, BCFace face_id, PetscBool *can_service_out)
Implementation of CanRankServiceFace().
Definition Boundaries.c:22
static void GetOwnedInteriorCellBounds(const DMDALocalInfo *info, PetscInt lo[3], PetscInt hi[3])
Index bounds of the interior cells this rank owns in the solver's cell-centred layout: the owned rang...
Definition setup.h:378
PetscInt KM
Definition variables.h:1171
PetscInt layer
Index along the normal of the face's metric and flux.
Definition variables.h:418
PetscInt normal
Logical axis of the face normal.
Definition variables.h:416
PetscInt JM
Definition variables.h:1171
PetscInt n[2]
Owned elements along a and b; 0 when this rank does not serve the face.
Definition variables.h:420
PetscInt IM
Definition variables.h:1171
PetscInt lo[2]
First owned indices along a and b.
Definition variables.h:419
PetscInt b
The two tangential axes, a < b.
Definition variables.h:417
Here is the call graph for this function:
Here is the caller graph for this function:

◆ BoundaryFaceHasWallShear()

PetscBool BoundaryFaceHasWallShear ( const BoundaryFaceConfig *  face)

Reports whether a boundary face is a wall that exerts shear on the flow.

Every WALL face is impenetrable, and code that needs only that tests the type. A free-slip wall exerts no shear, so the wall model, its eddy viscosity on the wall face, and the cells it writes belong only to the walls this reports: a free-slip face uses the interior face average there instead, as a symmetry plane does.

Parameters
faceBoundary face configuration.
Returns
PETSC_TRUE for a WALL face whose handler is not free-slip.

Reports whether a boundary face is a wall that exerts shear on the flow.

See also
BoundaryFaceHasWallShear()

Definition at line 9 of file Boundaries.c.

10{
11 return (PetscBool)(face != NULL && face->mathematical_type == WALL &&
13}
@ WALL
Definition variables.h:319
Here is the caller graph for this function:

◆ BoundaryFaceIsFreeSlipWall()

static PetscBool BoundaryFaceIsFreeSlipWall ( const BoundaryFaceConfig *  face)
inlinestatic

Reports whether a boundary face is a free-slip wall: impenetrable, exerting no shear, and a plane across which the flow mirrors.

Parameters
faceBoundary face configuration.
Returns
PETSC_TRUE for a WALL face whose handler is free-slip.

Definition at line 180 of file Boundaries.h.

181{
182 return (PetscBool)(face->mathematical_type == WALL && face->handler_type == BC_HANDLER_WALL_FREE_SLIP);
183}
Here is the caller graph for this function:

◆ ClassifyMomentumRow()

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".

Every consumer of the momentum system must agree on which rows the solver is responsible for, and every consumer must derive that answer from this function rather than restating the index arithmetic locally. Three independent restatements previously disagreed, and the disagreement was silent: the residual assembly skipped the periodic duplicate column at index 0 while nothing zeroed it, so ComputeTotalResidual()'s BDF term accumulated there without bound and the reported residual norm stopped describing the state.

The classification depends only on user->info, the configured boundary types, and the queried index; it reads no field data and performs no communication, so it is safe to call inside assembly loops.

Periodicity of an axis is taken from that axis's NEGATIVE face, matching ComputeRHS() and TransferPeriodicStaggeredFieldByDirection(). A periodic axis is expected to carry PERIODIC on both of its faces.

Callers act on the classification differently, and both actions are correct:

  • residual/pseudo-time consumers (EnforceRHSBoundaryConditions()) zero every non-physical row, because the value there is imposed immediately afterwards by the boundary sweep or the periodic synchronisation;
  • the matrix-free Newton path substitutes an explicit equation instead (F = X - U_conditioned, F = X, F = X_dup - X_rep), because a zeroed row would leave a zero Jacobian row.
Parameters
[in]userBlock context supplying info and boundary_faces.
[in]iLocation index along xi.
[in]jLocation index along eta.
[in]kLocation index along zeta.
[in]componentStaggered component of the row (0 = xi, 1 = eta, 2 = zeta).
[out]riRepresentative xi index; equals i unless the row wraps.
[out]rjRepresentative eta index; equals j unless the row wraps.
[out]rkRepresentative zeta index; equals k unless the row wraps.
Returns
The row classification. Only MOM_ROW_PHYSICAL denotes an unknown.

Single source of truth for "which staggered momentum rows are unknowns".

Pure index/boundary-type arithmetic: no field reads, no communication. Precedence matters. A conditioned row is reported first because its explicit Dirichlet value is more specific than the homogeneous fallback, and a periodic duplicate is reported before the homogeneous case because the Newton path needs its representative index to build F = X_dup - X_rep.

Definition at line 139 of file Boundaries.c.

141{
142 const PetscInt mx = user->info.mx, my = user->info.my, mz = user->info.mz;
143 const PetscInt coord[3] = {i, j, k};
144 const PetscInt size[3] = {mx, my, mz};
145 PetscBool periodic[3], periodic_duplicate = PETSC_FALSE;
146 PetscBool residual_zeroed = PETSC_FALSE, conditioned = PETSC_FALSE;
147
148 *ri = i; *rj = j; *rk = k;
149 GetPeriodicAxes(user->simCtx, periodic);
150 for (PetscInt axis = 0; axis < 3; ++axis) {
151 if (periodic[axis] && coord[axis] == 0) {
152 periodic_duplicate = PETSC_TRUE;
153 if (axis == 0) *ri = -2;
154 else if (axis == 1) *rj = -2;
155 else *rk = -2;
156 }
157 if (periodic[axis] && coord[axis] == size[axis] - 1) {
158 periodic_duplicate = PETSC_TRUE;
159 if (axis == 0) *ri = mx + 1;
160 else if (axis == 1) *rj = my + 1;
161 else *rk = mz + 1;
162 }
163
164 if (!periodic[axis] && coord[axis] == 0) residual_zeroed = PETSC_TRUE;
165 if (coord[axis] == size[axis] - 1) residual_zeroed = PETSC_TRUE;
166 if (!periodic[axis] && coord[axis] == size[axis] - 2 && component == axis)
167 residual_zeroed = PETSC_TRUE;
168 }
169
170 if (!periodic[component] &&
171 (coord[component] == 0 || coord[component] == size[component] - 2)) {
172 PetscBool tangential_interior = PETSC_TRUE;
173 for (PetscInt axis = 0; axis < 3; ++axis) {
174 if (axis == component) continue;
175 if (coord[axis] < 1 || coord[axis] > size[axis] - 2)
176 tangential_interior = PETSC_FALSE;
177 }
178 conditioned = tangential_interior;
179 }
180
181 if (conditioned) return MOM_ROW_FIXED_CONDITIONED;
182 if (periodic_duplicate) return MOM_ROW_PERIODIC_DUPLICATE;
183 if (residual_zeroed) return MOM_ROW_FIXED_HOMOGENEOUS;
184 return MOM_ROW_PHYSICAL;
185}
static void GetPeriodicAxes(const SimCtx *simCtx, PetscBool periodic[3])
Which grid axes are periodic.
Definition setup.h:361
Here is the call graph for this function:
Here is the caller graph for this function:

◆ MomentumRowIsSolidMasked()

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.

ComputeRHS() zeroes the residual at a solid cell and at the staggered rows whose downstream neighbour is solid, so those rows carry no equation. A solver that only marches on the residual needs nothing more: a zero residual means no update. A solver that assembles a matrix and solves F(X) = 0 does, because such a row has a zero Jacobian row and a zero column, leaving the unknown undetermined. Those rows must be constrained like any other row that carries no unknown.

The condition mirrors the residual's own masking exactly. If one changes, so must the other, or the assembled operator stops matching the residual it preconditions.

Parameters
[in]nvertGhosted solid-cell field, or NULL to apply no masking.
[in]iLocation index along xi.
[in]jLocation index along eta.
[in]kLocation index along zeta.
[in]componentStaggered component of the row (0 = xi, 1 = eta, 2 = zeta).
Returns
PETSC_TRUE when the row is masked and therefore carries no unknown.

Reports whether a momentum row is masked out by the solid-cell field.

Full API contract is documented with the header declaration in include/Boundaries.h.

See also
MomentumRowIsSolidMasked()

Definition at line 193 of file Boundaries.c.

195{
197 /* PICURV_SOLID_THRESHOLD mirrors the 0.1 fluid test ComputeRHS() applies. */
198 const PetscReal threshold = 0.1;
199
200 if (nvert == NULL) { PROFILE_HELPER_END; return PETSC_FALSE; }
201 /* A solid cell carries no momentum equation in any component. */
202 if (nvert[k][j][i] > threshold) { PROFILE_HELPER_END; return PETSC_TRUE; }
203 /* A staggered row also loses its equation when the cell it points into is solid. */
204 switch (component) {
205 case 0: PROFILE_HELPER_END; return (PetscBool)(nvert[k][j][i + 1] > threshold);
206 case 1: PROFILE_HELPER_END; return (PetscBool)(nvert[k][j + 1][i] > threshold);
207 case 2: PROFILE_HELPER_END; return (PetscBool)(nvert[k + 1][j][i] > threshold);
208 default: PROFILE_HELPER_END; return PETSC_FALSE;
209 }
211}
Here is the caller graph for this function:

◆ EnforceRHSBoundaryConditions()

PetscErrorCode EnforceRHSBoundaryConditions ( UserCtx *  user)

Zeroes every momentum RHS row that does not carry an independent unknown.

The set of such rows is not restated here: each owned location and component is asked of ClassifyMomentumRow(), and anything other than MOM_ROW_PHYSICAL is zeroed. That covers, without enumerating them,

  • strong Dirichlet rows on non-periodic faces, so the time-stepping scheme cannot alter the values ApplyBoundaryConditions() has just set;
  • dummy layers at the far index of every axis, which hold no unknown; and
  • periodic duplicate columns, whose value the next SynchronizePeriodicStaggeredFields() copies from the wrapped master.

The last case is the one that must not be skipped. ComputeRHS() leaves the transverse components of a periodic duplicate column untouched, so a row left unzeroed here retains its previous contents while ComputeTotalResidual() adds the BDF term on top of them on every call. The residual norm then grows by |dU|/dt per evaluation regardless of the state, and no pseudo-time iteration can reduce it.

Call immediately after the RHS vector is fully assembled (spatial + temporal terms) and before it is used in a time-stepping update.

Parameters
userThe UserCtx for the specific block being computed.
Returns
PetscErrorCode 0 on success.

Zeroes every momentum RHS row that does not carry an independent unknown.

The sweep is deliberately expressed over every owned location rather than over the six boundary slabs: restating "which indices can be non-physical" here is exactly the duplication that let the periodic duplicate column go unzeroed. ClassifyMomentumRow() is a handful of integer comparisons and the walk is a single pass with no stencil access, which is negligible next to the several ghosted stencil passes ComputeRHS() has already made over the same range. MomentumNewtonKrylov_ApplyConstraints() walks the same range the same way.

Definition at line 224 of file Boundaries.c.

225{
226 PetscErrorCode ierr;
227 DMDALocalInfo info = user->info;
228 Cmpnts ***rhs;
229
230 PetscFunctionBeginUser;
232
233 // Get a writable pointer to the local data of the global RHS vector.
234 ierr = DMDAVecGetArray(user->fda, user->Rhs, &rhs); CHKERRQ(ierr);
235
236 for (PetscInt k = info.zs; k < info.zs + info.zm; k++) {
237 for (PetscInt j = info.ys; j < info.ys + info.ym; j++) {
238 for (PetscInt i = info.xs; i < info.xs + info.xm; i++) {
239 PetscScalar *row = &rhs[k][j][i].x; /* .x/.y/.z are contiguous */
240 for (PetscInt component = 0; component < 3; component++) {
241 PetscInt ri, rj, rk;
242 if (ClassifyMomentumRow(user, i, j, k, component, &ri, &rj, &rk) != MOM_ROW_PHYSICAL)
243 row[component] = 0.0;
244 }
245 }
246 }
247 }
248
249 // --- Release the pointer to the local data ---
250 ierr = DMDAVecRestoreArray(user->fda, user->Rhs, &rhs); CHKERRQ(ierr);
251
252 LOG_ALLOW(LOCAL, LOG_TRACE, "Rank %d, Block %" PetscInt_FMT ": Finished enforcing RHS boundary conditions.\n",
253 user->simCtx->rank, user->_this);
254
256
257 PetscFunctionReturn(0);
258}
MomentumRowType ClassifyMomentumRow(UserCtx *user, PetscInt i, PetscInt j, PetscInt k, PetscInt component, PetscInt *ri, PetscInt *rj, PetscInt *rk)
Implementation of ClassifyMomentumRow().
Definition Boundaries.c:139
PetscInt _this
Definition variables.h:1175
PetscScalar x
Definition variables.h:145
A 3D point or vector with PetscScalar components.
Definition variables.h:144
Here is the call graph for this function:
Here is the caller graph for this function:

◆ SynchronizePeriodicCellFields()

PetscErrorCode SynchronizePeriodicCellFields ( UserCtx *  user,
PetscInt  num_fields,
const FieldId  field_ids[] 
)

Synchronizes periodic endpoint cells for a list of cell-centered fields.

The fields are first communicated from global to local storage. Each periodic direction is then transferred in i-j-k order, with an intermediate ghost refresh after every active direction so periodic edges and corners inherit the values established by earlier directions. Only global duplicate planes in active periodic directions are repaired; non-periodic directions are untouched. The routine is a no-op, including no local refresh, when every direction is nonperiodic. During active periodic synchronization it internally refreshes the local vectors, but it is not a general replacement for UpdateLocalGhosts().

Supported fields are selected by FIELD_CAPABILITY_PERIODIC_CELL_SYNC in the field catalog.

Parameters
userThe main UserCtx struct.
num_fieldsThe number of entries in field_ids.
field_idsThe cell-centered fields to synchronize.
Returns
PetscErrorCode 0 on success.

Synchronizes periodic endpoint cells for a list of cell-centered fields.

Full API contract is documented with the header declaration in include/Boundaries.h.

Definition at line 1474 of file Boundaries.c.

1475{
1476 PetscErrorCode ierr;
1477
1478 PetscFunctionBeginUser;
1480 ierr = SynchronizePeriodicCellFieldsFrom(user, num_fields, field_ids, PETSC_FALSE, PETSC_TRUE); CHKERRQ(ierr);
1482 PetscFunctionReturn(0);
1483}
static PetscErrorCode SynchronizePeriodicCellFieldsFrom(UserCtx *user, PetscInt num_fields, const FieldId field_ids[], PetscBool locals_current, PetscBool final_update)
Body of SynchronizePeriodicCellFields(), optionally without its first or last ghost update.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ SynchronizePeriodicFaceFields()

PetscErrorCode SynchronizePeriodicFaceFields ( UserCtx *  user,
char  face_direction,
PetscInt  num_fields,
const FieldId  field_ids[] 
)

Synchronizes persistent fields belonging to one face family.

The function performs deterministic I/J/K directional passes with an intermediate ghost refresh after each active periodic direction. It updates persistent global seam/dummy values only; face-specific local stencil repair remains a separate operation.

Parameters
userThe main UserCtx struct.
face_directionFace family shared by every field (‘'i’,'j', or'k'`).
[in]num_fieldsCount of registered face fields.
field_idsRegistered persistent face-field identities.
Returns
PetscErrorCode 0 on success.

Definition at line 1658 of file Boundaries.c.

1660{
1661 PetscErrorCode ierr;
1662 const char periodic_directions[3] = {'i', 'j', 'k'};
1663 const BCFace negative_faces[3] = {BC_FACE_NEG_X, BC_FACE_NEG_Y, BC_FACE_NEG_Z};
1664 const BCFace positive_faces[3] = {BC_FACE_POS_X, BC_FACE_POS_Y, BC_FACE_POS_Z};
1665
1666 PetscFunctionBeginUser;
1668 PetscCheck(num_fields >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE,
1669 "Number of face fields cannot be negative.");
1670 if (num_fields == 0) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
1671 PetscCheck(field_ids != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
1672 "Face field-ID array cannot be NULL.");
1673
1674 for (PetscInt field = 0; field < num_fields; field++) {
1675 DM dm;
1676 Vec global_vec, local_vec;
1677 PetscInt dof;
1678 PetscBool is_coordinate;
1679 PetscCall(GetPersistentFaceField(user, field_ids[field], face_direction,
1680 &dm, &global_vec, &local_vec, &dof));
1681 ierr = UpdateLocalGhosts(user, field_ids[field]); CHKERRQ(ierr);
1682 ierr = IsFaceCenterCoordinateField(field_ids[field], &is_coordinate); CHKERRQ(ierr);
1683 if (is_coordinate) {
1684 ierr = TranslatePeriodicFaceCenterGhosts(user, local_vec); CHKERRQ(ierr);
1685 }
1686 }
1687
1688 for (PetscInt direction = 0; direction < 3; direction++) {
1689 const PetscBool active =
1690 user->boundary_faces[negative_faces[direction]].mathematical_type == PERIODIC ||
1691 user->boundary_faces[positive_faces[direction]].mathematical_type == PERIODIC;
1692 if (!active) continue;
1693
1694 for (PetscInt field = 0; field < num_fields; field++) {
1695 ierr = TransferPeriodicFaceFieldByDirection(user, field_ids[field], face_direction,
1696 periodic_directions[direction]); CHKERRQ(ierr);
1697 }
1698 for (PetscInt field = 0; field < num_fields; field++) {
1699 DM dm;
1700 Vec global_vec, local_vec;
1701 PetscInt dof;
1702 PetscBool is_coordinate;
1703 ierr = UpdateLocalGhosts(user, field_ids[field]); CHKERRQ(ierr);
1704 ierr = IsFaceCenterCoordinateField(field_ids[field], &is_coordinate); CHKERRQ(ierr);
1705 if (is_coordinate) {
1706 PetscCall(GetPersistentFaceField(user, field_ids[field], face_direction,
1707 &dm, &global_vec, &local_vec, &dof));
1708 ierr = TranslatePeriodicFaceCenterGhosts(user, local_vec); CHKERRQ(ierr);
1709 }
1710 }
1711 }
1712
1714 PetscFunctionReturn(0);
1715}
static PetscErrorCode GetPersistentFaceField(UserCtx *user, FieldId field_id, char face_direction, DM *dm, Vec *global_vec, Vec *local_vec, PetscInt *dof)
Resolves one registered persistent single-face-family field.
static PetscErrorCode TranslatePeriodicFaceCenterGhosts(UserCtx *user, Vec local_vec)
Applies geometric translations to wrapped face-center ghost coordinates.
static PetscErrorCode IsFaceCenterCoordinateField(FieldId field_id, PetscBool *is_coordinate)
Returns whether a registered face field stores physical coordinates.
static PetscErrorCode TransferPeriodicFaceFieldByDirection(UserCtx *user, FieldId field_id, char face_direction, char periodic_direction)
Transfers one registered face-family field along one periodic axis.
PetscErrorCode UpdateLocalGhosts(UserCtx *user, FieldId field_id)
Updates the local vector (including ghost points) from its corresponding global vector.
Definition setup.c:2593
Here is the call graph for this function:
Here is the caller graph for this function:

◆ SynchronizePeriodicStaggeredFields()

PetscErrorCode SynchronizePeriodicStaggeredFields ( UserCtx *  user,
PetscInt  num_fields,
const FieldId  field_ids[] 
)

Synchronizes persistent component-staggered vector fields.

The function performs deterministic I/J/K endpoint transfers with an intermediate ghost refresh after every active periodic direction. Currently Ucont is the only registered component-staggered field.

Parameters
userThe main UserCtx struct.
num_fieldsNumber of entries in field_ids.
field_idsRegistered component-staggered field identities.
Returns
PetscErrorCode 0 on success.

Synchronizes persistent component-staggered vector fields.

Definition at line 1850 of file Boundaries.c.

1852{
1853 PetscErrorCode ierr;
1854
1855 PetscFunctionBeginUser;
1857 ierr = SynchronizePeriodicStaggeredFieldsFrom(user, num_fields, field_ids, PETSC_FALSE); CHKERRQ(ierr);
1859 PetscFunctionReturn(0);
1860}
static PetscErrorCode SynchronizePeriodicStaggeredFieldsFrom(UserCtx *user, PetscInt num_fields, const FieldId field_ids[], PetscBool locals_current)
Body of SynchronizePeriodicStaggeredFields(), optionally without its leading ghost update.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ PreparePeriodicQuickStencilFields()

PetscErrorCode PreparePeriodicQuickStencilFields ( UserCtx *  user,
Vec  local_vector_field,
Vec  local_scalar_field 
)

Repairs the outer adjacent periodic ghosts used by QUICK cell stencils.

The supplied local vectors must already contain a current PETSc periodic ghost exchange. The vector and scalar fields are repaired two logical cells across each active periodic seam so QUICK's i-1/i+2 equivalents are valid.

Parameters
userMain block context containing periodic boundary metadata.
local_vector_fieldGhosted three-component cell-centered field.
local_scalar_fieldGhosted scalar cell-centered field.
Returns
PetscErrorCode 0 on success.

Repairs the outer adjacent periodic ghosts used by QUICK cell stencils.

Definition at line 1865 of file Boundaries.c.

1867{
1868 DMDALocalInfo info = user->info;
1869 Cmpnts ***vector_array;
1870 PetscReal ***scalar_array;
1871 const PetscInt xs = info.xs, xe = info.xs + info.xm;
1872 const PetscInt ys = info.ys, ye = info.ys + info.ym;
1873 const PetscInt zs = info.zs, ze = info.zs + info.zm;
1874 const PetscInt gxs = info.gxs, gxe = info.gxs + info.gxm;
1875 const PetscInt gys = info.gys, gye = info.gys + info.gym;
1876 const PetscInt gzs = info.gzs, gze = info.gzs + info.gzm;
1877
1878 PetscFunctionBeginUser;
1880 PetscCheck(local_vector_field && local_scalar_field, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
1881 "QUICK stencil repair requires both local vector and scalar fields.");
1882 PetscCall(DMDAVecGetArray(user->fda, local_vector_field, &vector_array));
1883 PetscCall(DMDAVecGetArray(user->da, local_scalar_field, &scalar_array));
1884
1885 if (user->boundary_faces[BC_FACE_NEG_X].mathematical_type == PERIODIC && xs == 0) {
1886 for (PetscInt k = gzs; k < gze; k++) for (PetscInt j = gys; j < gye; j++) {
1887 vector_array[k][j][-1] = vector_array[k][j][-3];
1888 scalar_array[k][j][-1] = scalar_array[k][j][-3];
1889 }
1890 }
1891 if (user->boundary_faces[BC_FACE_POS_X].mathematical_type == PERIODIC && xe == info.mx) {
1892 for (PetscInt k = gzs; k < gze; k++) for (PetscInt j = gys; j < gye; j++) {
1893 vector_array[k][j][info.mx] = vector_array[k][j][info.mx + 2];
1894 scalar_array[k][j][info.mx] = scalar_array[k][j][info.mx + 2];
1895 }
1896 }
1897 if (user->boundary_faces[BC_FACE_NEG_Y].mathematical_type == PERIODIC && ys == 0) {
1898 for (PetscInt k = gzs; k < gze; k++) for (PetscInt i = gxs; i < gxe; i++) {
1899 vector_array[k][-1][i] = vector_array[k][-3][i];
1900 scalar_array[k][-1][i] = scalar_array[k][-3][i];
1901 }
1902 }
1903 if (user->boundary_faces[BC_FACE_POS_Y].mathematical_type == PERIODIC && ye == info.my) {
1904 for (PetscInt k = gzs; k < gze; k++) for (PetscInt i = gxs; i < gxe; i++) {
1905 vector_array[k][info.my][i] = vector_array[k][info.my + 2][i];
1906 scalar_array[k][info.my][i] = scalar_array[k][info.my + 2][i];
1907 }
1908 }
1909 if (user->boundary_faces[BC_FACE_NEG_Z].mathematical_type == PERIODIC && zs == 0) {
1910 for (PetscInt j = gys; j < gye; j++) for (PetscInt i = gxs; i < gxe; i++) {
1911 vector_array[-1][j][i] = vector_array[-3][j][i];
1912 scalar_array[-1][j][i] = scalar_array[-3][j][i];
1913 }
1914 }
1915 if (user->boundary_faces[BC_FACE_POS_Z].mathematical_type == PERIODIC && ze == info.mz) {
1916 for (PetscInt j = gys; j < gye; j++) for (PetscInt i = gxs; i < gxe; i++) {
1917 vector_array[info.mz][j][i] = vector_array[info.mz + 2][j][i];
1918 scalar_array[info.mz][j][i] = scalar_array[info.mz + 2][j][i];
1919 }
1920 }
1921
1922 PetscCall(DMDAVecRestoreArray(user->da, local_scalar_field, &scalar_array));
1923 PetscCall(DMDAVecRestoreArray(user->fda, local_vector_field, &vector_array));
1925 PetscFunctionReturn(0);
1926}
Here is the caller graph for this function:

◆ SynchronizePeriodicLocalStaggeredField()

PetscErrorCode SynchronizePeriodicLocalStaggeredField ( UserCtx *  user,
Vec  local_field 
)

Synchronizes one local-only component-staggered periodic work field.

This helper communicates locally computed owned entries, establishes the normal-component periodic endpoint values, and communicates once more.

Parameters
userMain block context containing periodic boundary metadata.
local_fieldGhosted local component-staggered vector.
Returns
PetscErrorCode 0 on success.

Synchronizes one local-only component-staggered periodic work field.

Definition at line 1931 of file Boundaries.c.

1932{
1933 DMDALocalInfo info = user->info;
1934 Cmpnts ***array;
1935 const PetscInt xs = info.xs, xe = info.xs + info.xm;
1936 const PetscInt ys = info.ys, ye = info.ys + info.ym;
1937 const PetscInt zs = info.zs, ze = info.zs + info.zm;
1938
1939 PetscFunctionBeginUser;
1941 PetscCheck(local_field, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
1942 "Local staggered field cannot be NULL.");
1943 PetscCall(DMLocalToLocalBegin(user->fda, local_field, INSERT_VALUES, local_field));
1944 PetscCall(DMLocalToLocalEnd(user->fda, local_field, INSERT_VALUES, local_field));
1945 PetscCall(DMDAVecGetArray(user->fda, local_field, &array));
1946
1947 if (user->boundary_faces[BC_FACE_NEG_X].mathematical_type == PERIODIC && xs == 0)
1948 for (PetscInt k = zs; k < ze; k++) for (PetscInt j = ys; j < ye; j++) array[k][j][0].x = array[k][j][-2].x;
1949 if (user->boundary_faces[BC_FACE_POS_X].mathematical_type == PERIODIC && xe == info.mx)
1950 for (PetscInt k = zs; k < ze; k++) for (PetscInt j = ys; j < ye; j++) array[k][j][info.mx - 1].x = array[k][j][info.mx + 1].x;
1951 if (user->boundary_faces[BC_FACE_NEG_Y].mathematical_type == PERIODIC && ys == 0)
1952 for (PetscInt k = zs; k < ze; k++) for (PetscInt i = xs; i < xe; i++) array[k][0][i].y = array[k][-2][i].y;
1953 if (user->boundary_faces[BC_FACE_POS_Y].mathematical_type == PERIODIC && ye == info.my)
1954 for (PetscInt k = zs; k < ze; k++) for (PetscInt i = xs; i < xe; i++) array[k][info.my - 1][i].y = array[k][info.my + 1][i].y;
1955 if (user->boundary_faces[BC_FACE_NEG_Z].mathematical_type == PERIODIC && zs == 0)
1956 for (PetscInt j = ys; j < ye; j++) for (PetscInt i = xs; i < xe; i++) array[0][j][i].z = array[-2][j][i].z;
1957 if (user->boundary_faces[BC_FACE_POS_Z].mathematical_type == PERIODIC && ze == info.mz)
1958 for (PetscInt j = ys; j < ye; j++) for (PetscInt i = xs; i < xe; i++) array[info.mz - 1][j][i].z = array[info.mz + 1][j][i].z;
1959
1960 PetscCall(DMDAVecRestoreArray(user->fda, local_field, &array));
1961 PetscCall(DMLocalToLocalBegin(user->fda, local_field, INSERT_VALUES, local_field));
1962 PetscCall(DMLocalToLocalEnd(user->fda, local_field, INSERT_VALUES, local_field));
1964 PetscFunctionReturn(0);
1965}
Here is the caller graph for this function:

◆ ApplyMetricsPeriodicBCs()

PetscErrorCode ApplyMetricsPeriodicBCs ( UserCtx *  user)

(Orchestrator) Updates all metric-related fields in the local ghost cell regions for periodic boundaries.

This function synchronizes cell-centered Aj and the persistent I/J/K metric face families through the canonical MPI-safe synchronizers.

Parameters
userThe main UserCtx struct.
Returns
PetscErrorCode 0 on success.

(Orchestrator) Updates all metric-related fields in the local ghost cell regions for periodic boundaries.

See also
ApplyMetricsPeriodicBCs()

Definition at line 1971 of file Boundaries.c.

1972{
1973 PetscErrorCode ierr;
1974 PetscFunctionBeginUser;
1976
1977 const FieldId cell_fields[] = {FIELD_ID_AJ};
1978 const FieldId i_face_fields[] = {FIELD_ID_CENTX, FIELD_ID_CSI, FIELD_ID_ICSI,
1980 const FieldId j_face_fields[] = {FIELD_ID_CENTY, FIELD_ID_ETA, FIELD_ID_JCSI,
1982 const FieldId k_face_fields[] = {FIELD_ID_CENTZ, FIELD_ID_ZET, FIELD_ID_KCSI,
1984
1985 ierr = SynchronizePeriodicCellFields(user, 1, cell_fields); CHKERRQ(ierr);
1986 ierr = SynchronizePeriodicFaceFields(user, 'i', 6, i_face_fields); CHKERRQ(ierr);
1987 ierr = SynchronizePeriodicFaceFields(user, 'j', 6, j_face_fields); CHKERRQ(ierr);
1988 ierr = SynchronizePeriodicFaceFields(user, 'k', 6, k_face_fields); CHKERRQ(ierr);
1989
1991 PetscFunctionReturn(0);
1992}
PetscErrorCode SynchronizePeriodicFaceFields(UserCtx *user, char face_direction, PetscInt num_fields, const FieldId field_ids[])
Synchronizes persistent fields belonging to one face family.
PetscErrorCode SynchronizePeriodicCellFields(UserCtx *user, PetscInt num_fields, const FieldId field_ids[])
Implementation of SynchronizePeriodicCellFields().
FieldId
Compile-time identity for a catalogued Eulerian field.
@ FIELD_ID_JETA
@ FIELD_ID_CENTZ
@ FIELD_ID_CSI
@ FIELD_ID_IAJ
@ FIELD_ID_KETA
@ FIELD_ID_JAJ
@ FIELD_ID_KAJ
@ FIELD_ID_AJ
@ FIELD_ID_CENTY
@ FIELD_ID_KZET
@ FIELD_ID_IETA
@ FIELD_ID_ICSI
@ FIELD_ID_ETA
@ FIELD_ID_JCSI
@ FIELD_ID_JZET
@ FIELD_ID_IZET
@ FIELD_ID_ZET
@ FIELD_ID_KCSI
@ FIELD_ID_CENTX
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ApplyPeriodicBCs()

PetscErrorCode ApplyPeriodicBCs ( UserCtx *  user,
PetscBool  final_cell_update 
)

Applies periodic boundary conditions by copying data across domain boundaries for all relevant fields.

This is the canonical periodic orchestrator for geometric consistency. It updates Ucat, P, and Nvert through the generic cell synchronizer and updates staggered Ucont through the component-staggered synchronizer.

Future extension rule: add new periodic variables by extending the existing field string dispatchers and invoking them from this orchestrator.

Parameters
userThe main UserCtx struct.
final_cell_updatePETSC_FALSE leaves the cell fields' last ghost update to the caller, which must update Ucat, P and Nvert before anything reads their local vectors; PETSC_TRUE leaves them current.
Returns
PetscErrorCode 0 on success.

Applies periodic boundary conditions by copying data across domain boundaries for all relevant fields.

See also
ApplyPeriodicBCs()

Definition at line 1998 of file Boundaries.c.

1999{
2000 PetscErrorCode ierr;
2001 PetscBool periodic[3], is_any_periodic;
2002
2003 PetscFunctionBeginUser;
2004
2006
2007 GetPeriodicAxes(user->simCtx, periodic);
2008 is_any_periodic = (PetscBool)(periodic[0] || periodic[1] || periodic[2]);
2009
2010 if (!is_any_periodic) {
2011 LOG_ALLOW(GLOBAL,LOG_TRACE, "No periodic boundaries defined; skipping ApplyPeriodicBCs.\n");
2013 PetscFunctionReturn(0);
2014 }
2015
2016 LOG_ALLOW(GLOBAL, LOG_TRACE, "Applying periodic boundary conditions for all fields.\n");
2017
2018 // STEP 1: Synchronize periodic cell-centered fields in deterministic direction order.
2019 const FieldId cell_fields[] = {FIELD_ID_UCAT, FIELD_ID_P, FIELD_ID_NVERT};
2020 ierr = SynchronizePeriodicCellFieldsFrom(user, 3, cell_fields, PETSC_FALSE, final_cell_update); CHKERRQ(ierr);
2021
2022 // STEP 2: Synchronize persistent staggered endpoints and repair local
2023 // component-normal ghosts through UpdateLocalGhosts().
2024 const FieldId staggered_fields[] = {FIELD_ID_UCONT};
2025 ierr = SynchronizePeriodicStaggeredFields(user, 1, staggered_fields); CHKERRQ(ierr);
2026
2028 PetscFunctionReturn(0);
2029}
PetscErrorCode SynchronizePeriodicStaggeredFields(UserCtx *user, PetscInt num_fields, const FieldId field_ids[])
Implementation of SynchronizePeriodicStaggeredFields().
@ FIELD_ID_NVERT
@ FIELD_ID_UCAT
@ FIELD_ID_UCONT
@ FIELD_ID_P
Here is the call graph for this function:
Here is the caller graph for this function:

◆ UpdateDummyCells()

PetscErrorCode UpdateDummyCells ( UserCtx *  user,
FieldId  field_id 
)

Fills the dummy cells on the non-periodic faces of one cell-centred field.

A cell-centred field stores cell c at index c+1; index 0 and the last index along each axis are dummy cells outside the domain. Stencils and node averages that reach across a boundary read them, so their value is the field's boundary condition:

Field Dummy value Condition it encodes
Ucat 2 Ubcs - interior face average equals the handler's boundary velocity
P the adjacent interior cell zero normal gradient
Psi the adjacent interior cell zero normal gradient (no scalar flux)

Any other field is refused: its condition must be chosen for the quantity before its dummy cells are filled (see 11. Derived Statistics At Non-Periodic Boundaries for why no default serves every quantity).

Pressure. Zero gradient is the condition the pressure solve already implies on every non-periodic face: the Poisson operator drops each boundary face's term, the dummy rows are identities with a zero right-hand side, and the projection corrects interior faces only. Nothing in the solve reads these values; filling them makes P_nodal and near-wall pressure gradients (the Cabot wall model) consistent with that condition, instead of averaging in a dummy value that stays at its initial zero. A pressure boundary condition (a far field, or a pressure outlet) will set its dummy value here as well, but that alone changes nothing the solve sees; see 6b. Pressure Boundary Conditions for what has to change with it.

Eddy viscosity. Mirrored, zero gradient, across a free-slip wall only. The flow mirrors there, so the face value the viscous flux averages must be the interior one, as on the corresponding interior face of the full, unmirrored domain. A wall that exerts shear replaces the face value outright (the wall model's, or zero), and the eddy viscosity's dummy cells on every other face are not written here.

Periodic faces are skipped: the periodic synchronizers own them. Only the flat part of each face is written (shrunken loop ranges); edges and corners are filled afterwards by UpdateCornerNodes from these values.

Parameters
userBlock context supplying the layout, face types, and Ubcs.
field_idCell-centred field to fill: FIELD_ID_UCAT, FIELD_ID_P, FIELD_ID_PSI, or FIELD_ID_NU_T.
Returns
Zero on success; PETSC_ERR_ARG_WRONG for a field that is not cell-centred, PETSC_ERR_SUP for one with no boundary rule.

Fills the dummy cells on the non-periodic faces of one cell-centred field.

Full API contract is documented with the header declaration in include/Boundaries.h.

See also
UpdateDummyCells()

Definition at line 2037 of file Boundaries.c.

2038{
2039 DMDALocalInfo info = user->info;
2040 PetscInt xs = info.xs, xe = info.xs + info.xm;
2041 PetscInt ys = info.ys, ye = info.ys + info.ym;
2042 PetscInt zs = info.zs, ze = info.zs + info.zm;
2043 PetscInt mx = info.mx, my = info.my, mz = info.mz;
2044 FieldView view;
2045 PetscScalar ****field = NULL, ****ubcs = NULL;
2046 PetscInt dof;
2047 PetscBool from_boundary_value, fills[6];
2048
2049 // --- Calculate shrunken loop ranges to avoid edges and corners ---
2050 PetscInt lxs = (xs == 0) ? xs + 1 : xs, lxe = (xe == mx) ? xe - 1 : xe;
2051 PetscInt lys = (ys == 0) ? ys + 1 : ys, lye = (ye == my) ? ye - 1 : ye;
2052 PetscInt lzs = (zs == 0) ? zs + 1 : zs, lze = (ze == mz) ? ze - 1 : ze;
2053
2054 PetscFunctionBeginUser;
2056 PetscCall(FieldGetView(user, field_id, &view));
2057 PetscCheck(view.descriptor->layout == FIELD_LAYOUT_CELL_CENTERED, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG,
2058 "UpdateDummyCells fills cell-centred fields; '%s' is not one.", view.descriptor->canonical_name);
2059 /* The dummy value is the quantity's boundary condition. Velocity takes the
2060 * boundary value the handlers set, placed so the face average equals it. Pressure
2061 * and the particle scalar take the adjacent cell's value: zero normal gradient. The
2062 * eddy viscosity mirrors only across a free-slip wall, where the flow mirrors and the
2063 * face average must equal the interior value; a wall that exerts shear replaces it on
2064 * the face, and no other face's eddy-viscosity dummy cells are written here. */
2065 PetscCheck(field_id == FIELD_ID_UCAT || field_id == FIELD_ID_P || field_id == FIELD_ID_PSI ||
2066 field_id == FIELD_ID_NU_T,
2067 PETSC_COMM_SELF, PETSC_ERR_SUP,
2068 "UpdateDummyCells has no boundary rule for '%s'; one must be chosen for the quantity "
2069 "before its dummy cells are filled.", view.descriptor->canonical_name);
2070 from_boundary_value = (PetscBool)(field_id == FIELD_ID_UCAT);
2071 for (PetscInt face = 0; face < 6; ++face) {
2072 const BoundaryFaceConfig *config = &user->boundary_faces[face];
2073
2074 fills[face] = (field_id == FIELD_ID_NU_T)
2076 : (PetscBool)(config->mathematical_type != PERIODIC);
2077 }
2078 dof = view.descriptor->dof;
2079
2080 PetscCall(DMDAVecGetArrayDOF(view.dm, view.global_vec, &field));
2081 if (from_boundary_value) PetscCall(DMDAVecGetArrayDOF(user->fda, user->Bcs.Ubcs, &ubcs));
2082
2083 // -X Face
2084 if (fills[BC_FACE_NEG_X] && xs == 0) {
2085 for (PetscInt k = lzs; k < lze; k++) for (PetscInt j = lys; j < lye; j++) for (PetscInt c = 0; c < dof; c++)
2086 field[k][j][xs][c] = from_boundary_value ? 2.0 * ubcs[k][j][xs][c] - field[k][j][xs + 1][c]
2087 : field[k][j][xs + 1][c];
2088 }
2089 // +X Face
2090 if (fills[BC_FACE_POS_X] && xe == mx) {
2091 for (PetscInt k = lzs; k < lze; k++) for (PetscInt j = lys; j < lye; j++) for (PetscInt c = 0; c < dof; c++)
2092 field[k][j][xe-1][c] = from_boundary_value ? 2.0 * ubcs[k][j][xe-1][c] - field[k][j][xe - 2][c]
2093 : field[k][j][xe - 2][c];
2094 }
2095 // -Y Face
2096 if (fills[BC_FACE_NEG_Y] && ys == 0) {
2097 for (PetscInt k = lzs; k < lze; k++) for (PetscInt i = lxs; i < lxe; i++) for (PetscInt c = 0; c < dof; c++)
2098 field[k][ys][i][c] = from_boundary_value ? 2.0 * ubcs[k][ys][i][c] - field[k][ys + 1][i][c]
2099 : field[k][ys + 1][i][c];
2100 }
2101 // +Y Face
2102 if (fills[BC_FACE_POS_Y] && ye == my) {
2103 for (PetscInt k = lzs; k < lze; k++) for (PetscInt i = lxs; i < lxe; i++) for (PetscInt c = 0; c < dof; c++)
2104 field[k][ye-1][i][c] = from_boundary_value ? 2.0 * ubcs[k][ye-1][i][c] - field[k][ye-2][i][c]
2105 : field[k][ye-2][i][c];
2106 }
2107 // -Z Face
2108 if (fills[BC_FACE_NEG_Z] && zs == 0) {
2109 for (PetscInt j = lys; j < lye; j++) for (PetscInt i = lxs; i < lxe; i++) for (PetscInt c = 0; c < dof; c++)
2110 field[zs][j][i][c] = from_boundary_value ? 2.0 * ubcs[zs][j][i][c] - field[zs + 1][j][i][c]
2111 : field[zs + 1][j][i][c];
2112 }
2113 // +Z Face
2114 if (fills[BC_FACE_POS_Z] && ze == mz) {
2115 for (PetscInt j = lys; j < lye; j++) for (PetscInt i = lxs; i < lxe; i++) for (PetscInt c = 0; c < dof; c++)
2116 field[ze-1][j][i][c] = from_boundary_value ? 2.0 * ubcs[ze-1][j][i][c] - field[ze-2][j][i][c]
2117 : field[ze-2][j][i][c];
2118 }
2119
2120 if (from_boundary_value) PetscCall(DMDAVecRestoreArrayDOF(user->fda, user->Bcs.Ubcs, &ubcs));
2121 PetscCall(DMDAVecRestoreArrayDOF(view.dm, view.global_vec, &field));
2123 PetscFunctionReturn(0);
2124}
static PetscBool BoundaryFaceIsFreeSlipWall(const BoundaryFaceConfig *face)
Reports whether a boundary face is a free-slip wall: impenetrable, exerting no shear,...
Definition Boundaries.h:180
FieldLayout layout
const FieldDescriptor * descriptor
PetscErrorCode FieldGetView(UserCtx *user, FieldId field_id, FieldView *view)
Resolve the existing DM and global/local vectors for one field.
@ FIELD_LAYOUT_CELL_CENTERED
const char * canonical_name
@ FIELD_ID_PSI
@ FIELD_ID_NU_T
Non-owning runtime objects resolved for one field and UserCtx.
Vec Ubcs
Physical Cartesian velocity at boundary faces. Full 3D array but only boundary-face entries are meani...
Definition variables.h:172
Here is the call graph for this function:
Here is the caller graph for this function:

◆ UpdateCornerNodes()

PetscErrorCode UpdateCornerNodes ( UserCtx *  user,
FieldId  field_id 
)

Fills the edge and corner dummy cells of one cell-centred field.

Call after the face dummy cells are final, both periodic (the periodic synchronizers) and non-periodic (UpdateDummyCells). Each edge dummy cell becomes the mean of its two face-adjacent dummy cells; the edges along the Z faces are done first, so the corners the remaining edges pass through are filled from finished edges. Across a free-slip wall the flow is the mirror image of the flow inside, so an edge cell beside one is instead the mirror image of its neighbour across that wall: a scalar copied, a velocity with its component along the wall's metric reversed. That keeps a free-slip wall exactly a plane of symmetry up to its edges.

Parameters
userBlock context supplying the layout.
field_idCell-centred field whose edges and corners are filled.
Returns
Zero on success; PETSC_ERR_ARG_WRONG for a field that is not cell-centred.

Fills the edge and corner dummy cells of one cell-centred field.

Full API contract is documented with the header declaration in include/Boundaries.h.

See also
UpdateCornerNodes()

Definition at line 2183 of file Boundaries.c.

2184{
2185 DMDALocalInfo info = user->info;
2186 PetscInt xs = info.xs, xe = info.xs + info.xm;
2187 PetscInt ys = info.ys, ye = info.ys + info.ym;
2188 PetscInt zs = info.zs, ze = info.zs + info.zm;
2189 PetscInt mx = info.mx, my = info.my, mz = info.mz;
2190 FieldView view;
2191 PetscScalar ****f = NULL;
2192 PetscInt dof;
2193 PetscBool free_slip[6], any_free_slip = PETSC_FALSE;
2194 Cmpnts ***metric[3] = {NULL, NULL, NULL};
2195
2196 PetscFunctionBeginUser;
2198 PetscCall(FieldGetView(user, field_id, &view));
2199 PetscCheck(view.descriptor->layout == FIELD_LAYOUT_CELL_CENTERED, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG,
2200 "UpdateCornerNodes fills cell-centred fields; '%s' is not one.", view.descriptor->canonical_name);
2201 dof = view.descriptor->dof;
2202 for (PetscInt face = 0; face < 6; ++face) {
2203 const BoundaryFaceConfig *config = &user->boundary_faces[face];
2204
2205 free_slip[face] = BoundaryFaceIsFreeSlipWall(config);
2206 any_free_slip = (PetscBool)(any_free_slip || free_slip[face]);
2207 }
2208 PetscCall(DMDAVecGetArrayDOF(view.dm, view.global_vec, &f));
2209 /* A velocity mirrors along the wall's own normal, which only a free-slip edge needs. */
2210 if (any_free_slip && dof == 3) {
2211 PetscCall(DMDAVecGetArrayRead(user->fda, user->lCsi, (const Cmpnts ***)&metric[0]));
2212 PetscCall(DMDAVecGetArrayRead(user->fda, user->lEta, (const Cmpnts ***)&metric[1]));
2213 PetscCall(DMDAVecGetArrayRead(user->fda, user->lZet, (const Cmpnts ***)&metric[2]));
2214 }
2215
2216#define EDGE_FILL(tk, tj, ti, ak, aj, ai, bk, bj, bi) \
2217 FillEdgeCell(f, dof, free_slip, metric, tk, tj, ti, ak, aj, ai, bk, bj, bi)
2218
2219 // --- Update Edges and Corners ---
2220 // The order of these blocks ensures that corners (where 3 faces meet) are
2221 // computed using data from edges (where 2 faces meet), which are computed first.
2222 // Edges connected to the -Z face (k=zs)
2223 if (zs == 0) {
2224 if (xs == 0) for (PetscInt j = ys; j < ye; j++) { EDGE_FILL(zs, j, xs, zs+1, j, xs, zs, j, xs+1); }
2225 if (xe == mx) for (PetscInt j = ys; j < ye; j++) { EDGE_FILL(zs, j, mx-1, zs+1, j, mx-1, zs, j, mx-2); }
2226 if (ys == 0) for (PetscInt i = xs; i < xe; i++) { EDGE_FILL(zs, ys, i, zs+1, ys, i, zs, ys+1, i); }
2227 if (ye == my) for (PetscInt i = xs; i < xe; i++) { EDGE_FILL(zs, my-1, i, zs+1, my-1, i, zs, my-2, i); }
2228 }
2229 // Edges connected to the +Z face (k=ze-1)
2230 if (ze == mz) {
2231 if (xs == 0) for (PetscInt j = ys; j < ye; j++) { EDGE_FILL(mz-1, j, xs, mz-2, j, xs, mz-1, j, xs+1); }
2232 if (xe == mx) for (PetscInt j = ys; j < ye; j++) { EDGE_FILL(mz-1, j, mx-1, mz-2, j, mx-1, mz-1, j, mx-2); }
2233 if (ys == 0) for (PetscInt i = xs; i < xe; i++) { EDGE_FILL(mz-1, ys, i, mz-2, ys, i, mz-1, ys+1, i); }
2234 if (ye == my) for (PetscInt i = xs; i < xe; i++) { EDGE_FILL(mz-1, my-1, i, mz-2, my-1, i, mz-1, my-2, i); }
2235 }
2236 // Remaining edges on the XY plane (that are not on Z faces)
2237 if (ys == 0) {
2238 if (xs == 0) for (PetscInt k = zs; k < ze; k++) { EDGE_FILL(k, ys, xs, k, ys+1, xs, k, ys, xs+1); }
2239 if (xe == mx) for (PetscInt k = zs; k < ze; k++) { EDGE_FILL(k, ys, mx-1, k, ys+1, mx-1, k, ys, mx-2); }
2240 }
2241 if (ye == my) {
2242 if (xs == 0) for (PetscInt k = zs; k < ze; k++) { EDGE_FILL(k, my-1, xs, k, my-2, xs, k, my-1, xs+1); }
2243 if (xe == mx) for (PetscInt k = zs; k < ze; k++) { EDGE_FILL(k, my-1, mx-1, k, my-2, mx-1, k, my-1, mx-2); }
2244 }
2245#undef EDGE_FILL
2246
2247 if (any_free_slip && dof == 3) {
2248 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lZet, (const Cmpnts ***)&metric[2]));
2249 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lEta, (const Cmpnts ***)&metric[1]));
2250 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lCsi, (const Cmpnts ***)&metric[0]));
2251 }
2252 PetscCall(DMDAVecRestoreArrayDOF(view.dm, view.global_vec, &f));
2254 PetscFunctionReturn(0);
2255}
#define EDGE_FILL(tk, tj, ti, ak, aj, ai, bk, bj, bi)
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ApplyWallFunction()

PetscErrorCode ApplyWallFunction ( UserCtx *  user)

Evaluates the selected wall law on every wall-face element and stores the wall stress.

For each element of a face whose boundary exerts shear (no-slip or moving wall; free-slip exerts none), the law is evaluated from the resolved velocity of the reference cell - the second cell from the wall - relative to the wall's velocity, at that cell's wall distance, and gives a friction velocity u_tau. The kinematic wall shear stress u_tau^2, directed against the reference cell's wall-parallel motion, is written to Wall_Stress in the face's own dummy cell, oriented as that face's viscous flux per unit area; ComputeViscous() applies it on the wall face in place of a gradient flux. The wall-normal flux through the face is set to zero.

The resolved velocity is never modified, so the momentum equation, the subgrid closure, the dummy cells and every other boundary condition read the same near-wall velocity. A cell beside two walls has one element on each, with its own reference cell and stress. Friction_Velocity holds, per first cell, the RMS of u_tau over its wall faces, and LogWallModelDiagnostics reduces per-element statistics.

Distances come from the cell Jacobians and the wall-face area: half the first cell's thickness, and the first cell's full thickness plus half the second's. A rank must own at least three nodes normal to each wall it serves, so the reference cell is in its block; a layout that violates this is refused.

Cabot may return a negative friction velocity when an adverse pressure gradient reverses its wall-layer balance; the stress then acts along the reference flow.

Parameters
userBlock context whose Ucat is the current pass's reconstruction.
Returns
PetscErrorCode 0 on success; PETSC_ERR_ARG_OUTOFRANGE for a layout that does not reach the reference cell; PETSC_ERR_FP for a non-finite friction velocity.

Evaluates the selected wall law on every wall-face element and stores the wall stress.

See also
ApplyWallFunction()

Definition at line 2314 of file Boundaries.c.

2315{
2316 SimCtx *simCtx = user->simCtx;
2317 const DMDALocalInfo *info = &user->info;
2318 const PetscInt start[3] = {info->xs, info->ys, info->zs};
2319 const PetscInt end[3] = {info->xs + info->xm, info->ys + info->ym, info->zs + info->zm};
2320 const PetscInt size[3] = {info->mx, info->my, info->mz};
2321 const PetscReal molecular = 1.0 / simCtx->ren;
2322 const PetscReal roughness_height = simCtx->wall_roughness_height;
2323 const Cmpnts ***ucat, ***ubcs, ***metric[3];
2324 const PetscReal ***nvert, ***aj, ***pressure;
2325 Cmpnts ***ucont, ***stress;
2326 PetscReal ***friction_velocity;
2327 PetscInt wall_faces_at[3][2];
2328
2329 PetscFunctionBeginUser;
2331 if (!simCtx->wallfunction) { PROFILE_HELPER_END; PetscFunctionReturn(0); }
2332
2333 /* One pass, one sample set: the state describes this pass and nothing earlier. Faces the
2334 model does not reach must not keep a stale stress, and the friction velocity is
2335 accumulated per cell below, so both start from zero. */
2336 PetscCall(PetscMemzero(&user->wall_diagnostics, sizeof(user->wall_diagnostics)));
2337 PetscCall(VecSet(user->Wall_Stress, 0.0));
2338 PetscCall(VecSet(user->Friction_Velocity, 0.0));
2339
2340 /* The resolved velocity this pass's Contra2Cart wrote, read from the global view: the
2341 model reads it and never writes it. */
2342 PetscCall(DMDAVecGetArrayRead(user->fda, user->Ucat, (void *)&ucat));
2343 PetscCall(DMDAVecGetArrayRead(user->fda, user->Bcs.Ubcs, (void *)&ubcs));
2344 PetscCall(DMDAVecGetArray(user->fda, user->Ucont, &ucont));
2345 PetscCall(DMDAVecGetArrayRead(user->fda, user->lCsi, (void *)&metric[0]));
2346 PetscCall(DMDAVecGetArrayRead(user->fda, user->lEta, (void *)&metric[1]));
2347 PetscCall(DMDAVecGetArrayRead(user->fda, user->lZet, (void *)&metric[2]));
2348 PetscCall(DMDAVecGetArrayRead(user->da, user->lNvert, (void *)&nvert));
2349 PetscCall(DMDAVecGetArrayRead(user->da, user->lAj, (void *)&aj));
2350 /* Cabot reads the previous projection's pressure gradient; the other laws ignore it. */
2351 PetscCall(DMDAVecGetArrayRead(user->da, user->lP, (void *)&pressure));
2352 PetscCall(DMDAVecGetArray(user->fda, user->Wall_Stress, &stress));
2353 PetscCall(DMDAVecGetArray(user->da, user->Friction_Velocity, &friction_velocity));
2354
2355 for (PetscInt axis = 0; axis < 3; axis++) {
2356 wall_faces_at[axis][0] = BoundaryFaceHasWallShear(&user->boundary_faces[2 * axis]) ? 1 : 0;
2357 wall_faces_at[axis][1] = BoundaryFaceHasWallShear(&user->boundary_faces[2 * axis + 1]) ? 1 : 0;
2358 }
2359
2360 /* Every wall face element is one sample of the law. A cell beside two walls, along an
2361 edge of the domain, has two such elements, each with its own reference cell, normal
2362 and stress, so the two walls never write into one another's input. */
2363 for (PetscInt face = 0; face < 6; face++) {
2364 const PetscInt axis = face / 2;
2365 const PetscBool negative = (PetscBool)(face % 2 == 0);
2366 const PetscReal side = negative ? 1.0 : -1.0;
2367 BoundaryFaceElements elements;
2368
2369 if (!wall_faces_at[axis][negative ? 0 : 1]) continue;
2370 PetscCall(GetBoundaryFaceElements(user, (BCFace)face, &elements));
2371 if (elements.n[0] * elements.n[1] == 0) continue;
2372
2373 const PetscInt face_at = elements.layer;
2374 const PetscInt cell = negative ? face_at + 1 : face_at;
2375 const PetscInt reference = negative ? face_at + 2 : face_at - 1;
2376 const PetscInt dummy = negative ? face_at : face_at + 1;
2377 /* The reference cell is read from the owned block. A rank holding fewer than three
2378 nodes normal to a wall would read outside it, so that layout is refused. */
2379 PetscCheck(reference >= start[axis] && reference < end[axis], PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE,
2380 "Wall model on face %s: this rank owns indices %" PetscInt_FMT "-%" PetscInt_FMT
2381 " normal to the wall, which does not reach the reference cell %" PetscInt_FMT
2382 ". Use a layout with at least three nodes per rank normal to every wall.",
2383 BCFaceToString((BCFace)face), start[axis], end[axis] - 1, reference);
2384
2385 for (PetscInt q = 0; q < elements.n[1]; q++)
2386 for (PetscInt p = 0; p < elements.n[0]; p++) {
2387 PetscInt c[3];
2388
2389 c[axis] = cell; c[elements.a] = elements.lo[0] + p; c[elements.b] = elements.lo[1] + q;
2390 const PetscInt i = c[0], j = c[1], k = c[2];
2391 PetscInt c_ref[3] = {i, j, k}, c_dummy[3] = {i, j, k}, c_face[3] = {i, j, k};
2392 PetscReal signed_u_tau = 0.0, u_tau;
2393
2394 if (nvert[k][j][i] > 0.1) continue;
2395 c_ref[axis] = reference;
2396 c_dummy[axis] = dummy;
2397 c_face[axis] = face_at;
2398
2399 const Cmpnts area_vector = metric[axis][c_face[2]][c_face[1]][c_face[0]];
2400 const PetscReal area = PetscSqrtReal(area_vector.x * area_vector.x + area_vector.y * area_vector.y +
2401 area_vector.z * area_vector.z);
2402 /* The first and reference cell-centre distances from the wall, from each cell's
2403 volume over the wall area. */
2404 const PetscReal distance_boundary = 0.5 / aj[k][j][i] / area;
2405 const PetscReal distance_reference = 2.0 * distance_boundary +
2406 0.5 / aj[c_ref[2]][c_ref[1]][c_ref[0]] / area;
2407 const Cmpnts velocity_wall = ubcs[c_dummy[2]][c_dummy[1]][c_dummy[0]];
2408 const Cmpnts velocity_reference = ucat[c_ref[2]][c_ref[1]][c_ref[0]];
2409 const Cmpnts relative_reference = {velocity_reference.x - velocity_wall.x,
2410 velocity_reference.y - velocity_wall.y,
2411 velocity_reference.z - velocity_wall.z};
2412 const Cmpnts tangent = RemoveFaceNormalComponent(relative_reference, area_vector);
2413 const PetscReal tangent_speed = PetscSqrtReal(tangent.x * tangent.x + tangent.y * tangent.y +
2414 tangent.z * tangent.z);
2415
2416 PetscCall(WallModelFrictionVelocity(user, pressure, i, j, k, roughness_height, distance_reference,
2417 tangent, tangent_speed, &signed_u_tau));
2418 u_tau = PetscAbsReal(signed_u_tau);
2419
2420 /* The stress opposes the reference cell's motion relative to the wall, along its
2421 wall-parallel direction. Stored in the face's dummy cell, which no other wall
2422 face uses, already oriented as the viscous flux through that face, so the
2423 flux is the stored value times the face area (ComputeViscous). */
2424 if (tangent_speed > 1.0e-12) {
2425 const PetscReal scale = side * signed_u_tau * u_tau / tangent_speed;
2426 stress[c_dummy[2]][c_dummy[1]][c_dummy[0]].x = scale * tangent.x;
2427 stress[c_dummy[2]][c_dummy[1]][c_dummy[0]].y = scale * tangent.y;
2428 stress[c_dummy[2]][c_dummy[1]][c_dummy[0]].z = scale * tangent.z;
2429 }
2430 /* The wall is impermeable whatever the law. */
2431 if (axis == 0) ucont[c_face[2]][c_face[1]][c_face[0]].x = 0.0;
2432 else if (axis == 1) ucont[c_face[2]][c_face[1]][c_face[0]].y = 0.0;
2433 else ucont[c_face[2]][c_face[1]][c_face[0]].z = 0.0;
2434
2435 /* The cell's friction velocity is the RMS over its wall faces; the sum of
2436 squares is accumulated here and reduced once every face has been visited. */
2437 friction_velocity[k][j][i] += u_tau * u_tau;
2438
2439 {
2440 WallModelDiagnosticsState *diagnostics = &user->wall_diagnostics;
2441 const PetscReal y_plus = u_tau * distance_boundary / molecular;
2442 const Cmpnts first = ucat[k][j][i];
2443 const Cmpnts relative_first = {first.x - velocity_wall.x, first.y - velocity_wall.y,
2444 first.z - velocity_wall.z};
2445 const Cmpnts first_tangent = RemoveFaceNormalComponent(relative_first, area_vector);
2446 const PetscReal first_speed = PetscSqrtReal(first_tangent.x * first_tangent.x +
2447 first_tangent.y * first_tangent.y +
2448 first_tangent.z * first_tangent.z);
2449 /* The eddy viscosity a gradient closure would need on this face to carry
2450 the stress across the resolved first cell: nu_eq = u_tau^2 y / |U_1|,
2451 less the molecular part. A diagnostic only; the stress itself is applied. */
2452 if (first_speed > 1.0e-10) {
2453 diagnostics->wall_viscosity_sum += PetscMax(u_tau * u_tau * distance_boundary / first_speed - molecular, 0.0);
2454 }
2455 if (diagnostics->cells == 0) {
2456 diagnostics->friction_velocity_min = u_tau;
2457 } else {
2458 diagnostics->friction_velocity_min = PetscMin(diagnostics->friction_velocity_min, u_tau);
2459 }
2460 if (diagnostics->cells == 0 || u_tau > diagnostics->friction_velocity_max) {
2461 diagnostics->friction_velocity_max = u_tau;
2462 diagnostics->friction_velocity_max_at[0] = face;
2463 diagnostics->friction_velocity_max_at[1] = i;
2464 diagnostics->friction_velocity_max_at[2] = j;
2465 diagnostics->friction_velocity_max_at[3] = k;
2466 }
2467 if (diagnostics->cells == 0 || y_plus > diagnostics->y_plus_max) {
2468 diagnostics->y_plus_max = y_plus;
2469 diagnostics->y_plus_max_at[0] = face;
2470 diagnostics->y_plus_max_at[1] = i;
2471 diagnostics->y_plus_max_at[2] = j;
2472 diagnostics->y_plus_max_at[3] = k;
2473 }
2474 diagnostics->friction_velocity_sum += u_tau;
2475 diagnostics->friction_velocity_sq += u_tau * u_tau;
2476 diagnostics->wall_distance_sum += distance_boundary;
2477 diagnostics->y_plus_sum += y_plus;
2478 diagnostics->cells += 1;
2479 }
2480 }
2481 }
2482
2483 /* Friction velocity per first cell: the RMS over the wall faces it touches. Only the
2484 wall-face elements are visited, and an edge cell is finalized once, by the first of its
2485 wall faces in face order, so the cost stays with the wall layers. */
2486 for (PetscInt face = 0; face < 6; face++) {
2487 const PetscInt axis = face / 2;
2488 BoundaryFaceElements elements;
2489
2490 if (!wall_faces_at[axis][face % 2]) continue;
2491 PetscCall(GetBoundaryFaceElements(user, (BCFace)face, &elements));
2492 for (PetscInt q = 0; q < elements.n[1]; q++)
2493 for (PetscInt p = 0; p < elements.n[0]; p++) {
2494 PetscInt c[3];
2495 PetscInt faces = 0, first_face = -1;
2496
2497 c[axis] = (face % 2 == 0) ? elements.layer + 1 : elements.layer;
2498 c[elements.a] = elements.lo[0] + p;
2499 c[elements.b] = elements.lo[1] + q;
2500 const PetscInt i = c[0], j = c[1], k = c[2];
2501
2502 if (friction_velocity[k][j][i] <= 0.0) continue;
2503 for (PetscInt other = 0; other < 6; other++) {
2504 const PetscInt other_axis = other / 2;
2505 const PetscInt beside = (other % 2 == 0) ? 1 : size[other_axis] - 2;
2506 if (wall_faces_at[other_axis][other % 2] && c[other_axis] == beside) {
2507 faces++;
2508 if (first_face < 0) first_face = other;
2509 }
2510 }
2511 if (first_face != face) continue;
2512 friction_velocity[k][j][i] = PetscSqrtReal(friction_velocity[k][j][i] / (PetscReal)faces);
2513 }
2514 }
2515
2516 PetscCall(DMDAVecRestoreArray(user->da, user->Friction_Velocity, &friction_velocity));
2517 PetscCall(DMDAVecRestoreArray(user->fda, user->Wall_Stress, &stress));
2518 PetscCall(DMDAVecRestoreArrayRead(user->da, user->lP, (void *)&pressure));
2519 PetscCall(DMDAVecRestoreArrayRead(user->da, user->lAj, (void *)&aj));
2520 PetscCall(DMDAVecRestoreArrayRead(user->da, user->lNvert, (void *)&nvert));
2521 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lZet, (void *)&metric[2]));
2522 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lEta, (void *)&metric[1]));
2523 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lCsi, (void *)&metric[0]));
2524 PetscCall(DMDAVecRestoreArray(user->fda, user->Ucont, &ucont));
2525 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->Bcs.Ubcs, (void *)&ubcs));
2526 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->Ucat, (void *)&ucat));
2527
2528 /* Refresh the ghosted images here so that every caller sees consistent fields rather
2529 than each remembering to do it. */
2530 PetscCall(UpdateLocalGhosts(user, FIELD_ID_U_TAU));
2531 PetscCall(UpdateLocalGhosts(user, FIELD_ID_WALL_STRESS));
2533 PetscFunctionReturn(PETSC_SUCCESS);
2534}
PetscBool BoundaryFaceHasWallShear(const BoundaryFaceConfig *face)
Implementation of BoundaryFaceHasWallShear().
Definition Boundaries.c:9
static PetscErrorCode WallModelFrictionVelocity(UserCtx *user, const PetscReal ***pressure, PetscInt i, PetscInt j, PetscInt k, PetscReal roughness_height, PetscReal distance_reference, Cmpnts tangent, PetscReal tangent_speed, PetscReal *friction_velocity)
The signed friction velocity the configured wall law gives for one wall-face element.
PetscErrorCode GetBoundaryFaceElements(UserCtx *user, BCFace face_id, BoundaryFaceElements *elements)
Implementation of GetBoundaryFaceElements().
Definition Boundaries.c:105
static Cmpnts RemoveFaceNormalComponent(Cmpnts velocity, Cmpnts metric)
velocity less its component along the face metric metric, which leaves it tangent to the face.
Definition Metric.h:99
@ FIELD_ID_U_TAU
@ FIELD_ID_WALL_STRESS
Vec Wall_Stress
Definition variables.h:1193
PetscReal wall_viscosity_sum
Sum of the equivalent eddy viscosity u_tau^2 y/|U_1| - nu (diagnostic only).
Definition variables.h:717
Vec lNvert
Definition variables.h:1197
PetscReal friction_velocity_sq
Sum of u_tau^2, for the RMS.
Definition variables.h:709
PetscReal ren
Definition variables.h:965
Vec Ucont
Definition variables.h:1197
PetscInt friction_velocity_max_at[4]
Wall face (BCFace) and global cell i, j, k of friction_velocity_max.
Definition variables.h:715
PetscReal wall_distance_sum
Sum of the first-cell wall distance.
Definition variables.h:712
PetscReal friction_velocity_min
Smallest u_tau this rank corrected.
Definition variables.h:710
PetscReal friction_velocity_max
Largest u_tau this rank corrected.
Definition variables.h:711
PetscReal y_plus_sum
Sum of u_tau * y / nu over corrected cells.
Definition variables.h:713
PetscReal wall_roughness_height
Definition variables.h:1004
PetscReal friction_velocity_sum
Sum of u_tau over corrected cells.
Definition variables.h:708
PetscScalar z
Definition variables.h:145
PetscInt wallfunction
Enable wall functions on WALL faces.
Definition variables.h:1042
PetscInt y_plus_max_at[4]
Wall face (BCFace) and global cell i, j, k of y_plus_max.
Definition variables.h:716
PetscInt cells
Number of cells this rank corrected.
Definition variables.h:718
Vec Friction_Velocity
Definition variables.h:1189
PetscReal y_plus_max
Largest first-cell y+ this rank corrected.
Definition variables.h:714
PetscScalar y
Definition variables.h:145
WallModelDiagnosticsState wall_diagnostics
Near-wall statistics from the last wall-model pass.
Definition variables.h:1261
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
Near-wall statistics captured by one wall-model pass.
Definition variables.h:707
Here is the call graph for this function:
Here is the caller graph for this function:

◆ LogWallModelDiagnostics()

PetscErrorCode LogWallModelDiagnostics ( UserCtx *  user)

Appends one row of near-wall statistics to <run.analysis.metrics>/wall_model.csv.

Reduces the state ApplyWallFunction accumulated over the wall faces this rank owns and writes the run-wide row from rank 0. y+ is the column that matters: it says whether the first cell sits where the selected law is valid, and no stored field can answer that after the fact.

A no-op when no wall model is active. When a wall model is active but no cell was corrected - wall functions enabled on a case with no WALL face - it warns and writes nothing rather than emitting a row of zeros.

Collective on the block's communicator; call it on every rank, once per step, after ApplyWallFunction.

Parameters
[in]userBlock context whose wall-model pass has already run this step.
Returns
PetscErrorCode 0 on success.

Appends one row of near-wall statistics to <run.analysis.metrics>/wall_model.csv.

Full API contract is documented with the header declaration in include/Boundaries.h.

Definition at line 2541 of file Boundaries.c.

2542{
2543 SimCtx *simCtx = user->simCtx;
2544 const WallModelDiagnosticsState *state = &user->wall_diagnostics;
2545 MPI_Comm comm;
2546
2547 /* Index 0..3: cell count, u_tau sum, u_tau^2 sum, y+ sum. Index 4..5: wall-distance
2548 and wall-viscosity sums. One collective rather than six. */
2549 PetscReal local_sum[6], global_sum[6];
2550 PetscReal global_max[2];
2551 PetscReal local_min, global_min;
2552 /* Index 0: u_tau, 1: y+. MAXLOC carries the owning rank with each maximum, and that
2553 rank alone contributes the face and cell, so the sum below is its location. The
2554 lowest rank wins a tie, so the record is the same at any layout that ties. */
2555 struct { double value; int rank; } local_max[2], owner_max[2];
2556 PetscInt local_at[8], global_at[8];
2557
2558 PetscFunctionBeginUser;
2560
2561 if (!simCtx->wallfunction) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
2562
2563 PetscCall(PetscObjectGetComm((PetscObject)user->da, &comm));
2564
2565 local_sum[0] = (PetscReal)state->cells;
2566 local_sum[1] = state->friction_velocity_sum;
2567 local_sum[2] = state->friction_velocity_sq;
2568 local_sum[3] = state->y_plus_sum;
2569 local_sum[4] = state->wall_distance_sum;
2570 local_sum[5] = state->wall_viscosity_sum;
2571 /* Both are non-negative, so a rank with no wall cell offers -1 and can never own them. */
2572 local_max[0].value = (state->cells > 0) ? (double)state->friction_velocity_max : -1.0;
2573 local_max[1].value = (state->cells > 0) ? (double)state->y_plus_max : -1.0;
2574 local_max[0].rank = local_max[1].rank = (int)simCtx->rank;
2575 /* A rank that owns no wall face must not win the minimum with a zero it never
2576 measured, so it contributes the identity instead. */
2577 local_min = (state->cells > 0) ? state->friction_velocity_min : PETSC_MAX_REAL;
2578
2579 PetscCallMPI(MPI_Allreduce(local_sum, global_sum, 6, MPIU_REAL, MPI_SUM, comm));
2580 PetscCallMPI(MPI_Allreduce(local_max, owner_max, 2, MPI_DOUBLE_INT, MPI_MAXLOC, comm));
2581 PetscCallMPI(MPI_Allreduce(&local_min, &global_min, 1, MPIU_REAL, MPI_MIN, comm));
2582 global_max[0] = (PetscReal)owner_max[0].value;
2583 global_max[1] = (PetscReal)owner_max[1].value;
2584 for (PetscInt n = 0; n < 4; n++) {
2585 local_at[n] = (owner_max[0].rank == (int)simCtx->rank) ? state->friction_velocity_max_at[n] : 0;
2586 local_at[4 + n] = (owner_max[1].rank == (int)simCtx->rank) ? state->y_plus_max_at[n] : 0;
2587 }
2588 PetscCallMPI(MPI_Allreduce(local_at, global_at, 8, MPIU_INT, MPI_SUM, comm));
2589
2590 if (simCtx->rank == 0) {
2591 const PetscReal cells = global_sum[0];
2592 FILE *file = NULL;
2593 PetscReal mean, mean_square, variance;
2594
2595 /* No wall face anywhere is a configuration fact, not a data point: a run with
2596 wall functions enabled and no WALL boundary would otherwise emit a row of
2597 zeros that reads like a converged answer. */
2598 if (cells <= 0.0) {
2600 "Wall model is enabled but no WALL face was reached this step; "
2601 "no diagnostics written.\n");
2603 PetscFunctionReturn(0);
2604 }
2605
2606 mean = global_sum[1] / cells;
2607 mean_square = global_sum[2] / cells;
2608 variance = PetscMax(mean_square - mean * mean, 0.0);
2609
2610 PetscCall(PicurvOpenDiagnosticsCsv(simCtx, simCtx->analysis_dir, "wall_model.csv",
2611 "step,time,wall_cells,u_tau_mean,u_tau_rms,"
2612 "u_tau_min,u_tau_max,y_plus_mean,y_plus_max,"
2613 "wall_distance_mean,nu_wall_over_nu_mean,physical_time,"
2614 "u_tau_max_face,u_tau_max_i,u_tau_max_j,u_tau_max_k,"
2615 "y_plus_max_face,y_plus_max_i,y_plus_max_j,y_plus_max_k", &file));
2616 PetscReal physical_time = 0.0;
2617 PetscCall(PicurvPhysicalTime(simCtx, simCtx->ti, &physical_time));
2618 fprintf(file,
2619 "%d,%.6e,%d,%.6e,%.6e,%.6e,%.6e,%.6e,%.6e,%.6e,%.6e,%.6e,%s,%d,%d,%d,%s,%d,%d,%d\n",
2620 (int)simCtx->step, (double)simCtx->ti, (int)cells,
2621 (double)mean, (double)PetscSqrtReal(variance),
2622 (double)global_min, (double)global_max[0],
2623 (double)(global_sum[3] / cells), (double)global_max[1],
2624 (double)(global_sum[4] / cells),
2625 (double)(global_sum[5] / cells * simCtx->ren), (double)physical_time,
2626 BCFaceToString((BCFace)global_at[0]), (int)global_at[1], (int)global_at[2], (int)global_at[3],
2627 BCFaceToString((BCFace)global_at[4]), (int)global_at[5], (int)global_at[6], (int)global_at[7]);
2628 PetscCheck(fclose(file) == 0, PETSC_COMM_SELF, PETSC_ERR_FILE_WRITE,
2629 "Unable to close the wall-model diagnostics file.");
2630
2632 " Wall model (%s): u_tau=%.4e (max %.4e on %s at %d,%d,%d), y+ (mean)=%.2f, "
2633 "y+ (max)=%.2f over %d cell(s)\n",
2635 (double)mean, (double)global_max[0], BCFaceToString((BCFace)global_at[0]),
2636 (int)global_at[1], (int)global_at[2], (int)global_at[3],
2637 (double)(global_sum[3] / cells), (double)global_max[1], (int)cells);
2638 }
2639
2640 /* Whether the first cell sits where the selected law is valid is a property of the
2641 mesh, not of the configuration, so it cannot be settled before the grid exists.
2642 It is checked here instead, and a run that stays outside the range is stopped
2643 rather than left to spend its walltime producing a wall stress the law cannot
2644 support. */
2645 {
2646 /* Consecutive samples tolerated outside the range. A startup transient or a
2647 brief excursion is not worth ending a run over; a mesh that is simply wrong
2648 never comes back. */
2649 const PetscInt PICURV_WALL_YPLUS_GRACE_SAMPLES = 10;
2650 const PetscReal y_plus_mean = (global_sum[0] > 0.0) ? global_sum[3] / global_sum[0] : 0.0;
2651 PetscReal lower = 0.0, upper = 300.0;
2652 const char *range_reason = NULL;
2653
2654 switch ((WallFunctionModel)simCtx->wallfunction) {
2656 /* Below 30 the first cell is under the logarithmic region; above 300 it is
2657 in the wake region, where the inverse still returns a friction velocity
2658 from the logarithmic branch but the flow no longer follows it. */
2659 lower = 30.0;
2660 upper = 300.0;
2661 range_reason = "the logarithmic region the law describes";
2662 break;
2664 /* The two-layer form has a valid branch below its edge, 8.3^(7/6) = 11.81, so
2665 only the upper end is a limit. */
2666 lower = 0.0;
2667 upper = 300.0;
2668 range_reason = "the region the power law describes";
2669 break;
2670 default:
2671 /* Cabot integrates across the wall layer, so it has no lower bound worth
2672 asserting; a first cell far outside the layer leaves its ODE nothing to
2673 integrate over. */
2674 lower = 0.0;
2675 upper = 1000.0;
2676 range_reason = "the wall layer the model integrates over";
2677 break;
2678 }
2679
2680 if (global_sum[0] > 0.0 && (y_plus_mean < lower || y_plus_mean > upper)) {
2681 user->wall_yplus_excursions += 1;
2683 "Wall model (%s): first-cell y+ is %.2f, outside %s (%.0f to %.0f). "
2684 "The stress it reports is not one the law supports here. Sample %d "
2685 "of %d before this run is stopped.\n",
2687 (double)y_plus_mean, range_reason, (double)lower, (double)upper,
2688 (int)user->wall_yplus_excursions,
2689 (int)PICURV_WALL_YPLUS_GRACE_SAMPLES);
2690
2691 PetscCheck(user->wall_yplus_excursions < PICURV_WALL_YPLUS_GRACE_SAMPLES,
2692 PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE,
2693 "Wall model (%s): first-cell y+ has been outside %s (%.0f to %.0f) "
2694 "for %d consecutive samples, most recently %.2f. Refine or coarsen "
2695 "the wall-normal spacing so the first cell lands in range, or "
2696 "resolve the wall and disable the wall function. Stopping now "
2697 "rather than spending the run producing a stress the law cannot "
2698 "support.",
2700 range_reason, (double)lower, (double)upper,
2701 (int)user->wall_yplus_excursions, (double)y_plus_mean);
2702 } else {
2703 /* Consecutive, so a sample back in range clears the count. */
2704 user->wall_yplus_excursions = 0;
2705 }
2706
2707 /* The stop above reads the mean, which a local excursion - a corner, a separation,
2708 an outlet - cannot move. The maximum is reported once, with where it is, so such a
2709 site is visible without stopping a run whose wall is otherwise in range. */
2710 if (global_sum[0] > 0.0 && global_max[1] > upper && !user->wall_yplus_max_reported) {
2711 user->wall_yplus_max_reported = PETSC_TRUE;
2713 "Wall model (%s): first-cell y+ reaches %.2f on face %s at cell (%d, %d, %d), above %s "
2714 "(up to %.0f), although the wall-face mean %.2f is in range. Reported once; "
2715 "wall_model.csv tracks the maximum and its location every step.\n",
2717 (double)global_max[1], BCFaceToString((BCFace)global_at[4]), (int)global_at[5],
2718 (int)global_at[6], (int)global_at[7], range_reason, (double)upper, (double)y_plus_mean);
2719 }
2720 }
2721
2723 PetscFunctionReturn(0);
2724}
PetscErrorCode PicurvPhysicalTime(const SimCtx *simCtx, PetscReal solver_time, PetscReal *physical)
Convert a solver time to physical seconds, t * L_ref / U_ref.
Definition io.c:2986
static PetscErrorCode PicurvOpenDiagnosticsCsv(SimCtx *simCtx, const char *dir, const char *filename, const char *header, FILE **file)
Opens a per-step diagnostics CSV: PicurvOpenRunCsv() with the common settings.
Definition logging.h:1197
const char * WallFunctionModelToString(WallFunctionModel model)
Returns the user-facing name of a wall-function model.
Definition logging.c:786
PetscInt wall_yplus_excursions
Consecutive diagnostic samples with the first cell outside the selected law's valid y+ range.
Definition variables.h:1262
WallFunctionModel
Selects the wall model applied on WALL faces.
Definition variables.h:600
@ WALL_FUNCTION_LOG_LAW
Definition variables.h:602
@ WALL_FUNCTION_WERNER
Definition variables.h:603
char analysis_dir[PETSC_MAX_PATH_LEN]
Definition variables.h:942
PetscInt step
Definition variables.h:924
PetscBool wall_yplus_max_reported
The local y+ maximum has already been reported above the law's range.
Definition variables.h:1263
PetscReal ti
Definition variables.h:925
Here is the call graph for this function:
Here is the caller graph for this function:

◆ LogBoundaryPressureDiagnostics()

PetscErrorCode LogBoundaryPressureDiagnostics ( UserCtx *  user)

Records each INLET and OUTLET face's area-weighted mean pressure this step.

Appends one row per such face to <analysis_dir>/boundary_pressure.csv: the step, the physical time, the face, its type, its open area, and the mean of the pressure in the first interior cells beside it, weighted by their face areas, in physical units. Edge and corner cells and cells blanked by an immersed body are left out, as in the outlet's flux sum. Pressure carries an arbitrary constant, so the difference between two faces' rows is the meaningful quantity: the pressure drop across the domain, the observable for a duct's friction factor and for the transient that enforces a change in an inflow-outflow domain's flow rate. A no-op when the block has no INLET or OUTLET face; in a multi-block run only the first block's faces are recorded, as in inlet_flow.csv.

Collective on PETSC_COMM_WORLD; call it on every rank, once per step, after the projection.

Parameters
[in]userBlock context whose pressure is current for this step.
Returns
PetscErrorCode 0 on success.

Records each INLET and OUTLET face's area-weighted mean pressure this step.

See also
LogBoundaryPressureDiagnostics()

Definition at line 2730 of file Boundaries.c.

2731{
2732 SimCtx *simCtx = user->simCtx;
2733 /* Per face: the area-weighted pressure sum and the open area. One collective for all six. */
2734 PetscReal local[12] = {0.0}, global[12];
2735 PetscBool selected[6] = {PETSC_FALSE};
2736 PetscInt n_selected = 0;
2737
2738 PetscFunctionBeginUser;
2740 for (PetscInt face = 0; face < 6; face++) {
2741 const BCType type = user->boundary_faces[face].mathematical_type;
2742 selected[face] = (PetscBool)(type == INLET || type == OUTLET);
2743 n_selected += selected[face] ? 1 : 0;
2744 }
2745 if (n_selected == 0) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
2746
2747 {
2748 const PetscReal ***pressure, ***nvert;
2749 const Cmpnts ***metric[3];
2750
2751 PetscCall(DMDAVecGetArrayRead(user->da, user->P, (void *)&pressure));
2752 PetscCall(DMDAVecGetArrayRead(user->da, user->lNvert, (void *)&nvert));
2753 PetscCall(DMDAVecGetArrayRead(user->fda, user->lCsi, (void *)&metric[0]));
2754 PetscCall(DMDAVecGetArrayRead(user->fda, user->lEta, (void *)&metric[1]));
2755 PetscCall(DMDAVecGetArrayRead(user->fda, user->lZet, (void *)&metric[2]));
2756 for (PetscInt face = 0; face < 6; face++) {
2757 BoundaryFaceElements elements;
2758
2759 if (!selected[face]) continue;
2760 /* The first interior cell beside each owned face element, and the face's own metric. */
2761 PetscCall(GetBoundaryFaceElements(user, (BCFace)face, &elements));
2762 const PetscInt axis = elements.normal;
2763 const PetscInt cell = (face % 2 == 0) ? elements.layer + 1 : elements.layer;
2764 for (PetscInt q = 0; q < elements.n[1]; q++)
2765 for (PetscInt p = 0; p < elements.n[0]; p++) {
2766 PetscInt c[3], f[3];
2767 c[axis] = cell; c[elements.a] = elements.lo[0] + p; c[elements.b] = elements.lo[1] + q;
2768 const PetscInt i = c[0], j = c[1], k = c[2];
2769 if (nvert[k][j][i] > 0.1) continue;
2770 f[0] = i; f[1] = j; f[2] = k;
2771 f[axis] = elements.layer;
2772 const Cmpnts m = metric[axis][f[2]][f[1]][f[0]];
2773 const PetscReal area = PetscSqrtReal(m.x * m.x + m.y * m.y + m.z * m.z);
2774 local[2 * face] += pressure[k][j][i] * area;
2775 local[2 * face + 1] += area;
2776 }
2777 }
2778 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lZet, (void *)&metric[2]));
2779 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lEta, (void *)&metric[1]));
2780 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lCsi, (void *)&metric[0]));
2781 PetscCall(DMDAVecRestoreArrayRead(user->da, user->lNvert, (void *)&nvert));
2782 PetscCall(DMDAVecRestoreArrayRead(user->da, user->P, (void *)&pressure));
2783 }
2784 PetscCallMPI(MPI_Allreduce(local, global, 12, MPIU_REAL, MPI_SUM, PETSC_COMM_WORLD));
2785
2786 /* One record per run, as the inlet-flow record keeps: the first block's faces. */
2787 if (simCtx->rank == 0 && user->_this == 0) {
2788 const PetscReal L_ref = simCtx->scaling.L_ref, P_ref = simCtx->scaling.P_ref;
2789 PetscReal physical_time = 0.0;
2790 FILE *file = NULL;
2791
2792 PetscCall(PicurvPhysicalTime(simCtx, simCtx->ti, &physical_time));
2793 PetscCall(PicurvOpenDiagnosticsCsv(simCtx, simCtx->analysis_dir, "boundary_pressure.csv",
2794 "step,physical_time,face,type,area,mean_pressure", &file));
2795 for (PetscInt face = 0; face < 6; face++) {
2796 if (!selected[face] || global[2 * face + 1] <= 0.0) continue;
2797 fprintf(file, "%d,%.10e,%s,%s,%.10e,%.10e\n", (int)simCtx->step, (double)physical_time,
2799 (double)(global[2 * face + 1] * L_ref * L_ref),
2800 (double)(global[2 * face] / global[2 * face + 1] * P_ref));
2801 }
2802 PetscCheck(fclose(file) == 0, PETSC_COMM_SELF, PETSC_ERR_FILE_WRITE,
2803 "Unable to close the boundary-pressure diagnostics file.");
2804 }
2806 PetscFunctionReturn(0);
2807}
BCType
Defines the general mathematical/physical Category of a boundary.
Definition variables.h:316
@ INLET
Definition variables.h:323
@ OUTLET
Definition variables.h:322
PetscReal L_ref
Definition variables.h:898
ScalingCtx scaling
Definition variables.h:1003
PetscReal P_ref
Definition variables.h:901
Here is the call graph for this function:
Here is the caller graph for this function:

◆ FinalizePostProjectionCellFields()

PetscErrorCode FinalizePostProjectionCellFields ( UserCtx *  user)

Finalizes cell-centered fields after the projection step.

This function completes the cell-centered state derived from the final, divergence-free Ucont produced by Projection. It fills non-periodic Ucat dummy faces, synchronizes periodic Ucat and P endpoints, resolves edges and corners, and refreshes the corresponding local vectors.

This function is fundamentally different from ApplyBoundaryConditions: it does NOT modify Ucont, reapply wall functions, or rerun the full physical boundary-condition workflow.

WORKFLOW:

  1. Refreshes local Ucat and any flow-dependent Ubcs targets.
  2. Fills non-periodic dummy faces and establishes periodic cell endpoints.
  3. Resolves edges/corners, restores exact periodic relationships, and refreshes local Ucat and P.
Parameters
userThe main UserCtx struct, containing all simulation state.
Returns
PetscErrorCode 0 on success.

Finalizes cell-centered fields after the projection step.

Full API contract is documented with the header declaration in include/Boundaries.h.

Definition at line 2814 of file Boundaries.c.

2815{
2816 PetscErrorCode ierr;
2817
2818 PetscFunctionBeginUser;
2820
2821 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Finalizing post-projection cell-centered fields.\n");
2822
2823 // Ensure flow-dependent Ubcs handlers see the newly reconstructed Ucat.
2824 ierr = UpdateLocalGhosts(user, FIELD_ID_UCAT); CHKERRQ(ierr);
2825 ierr = BoundarySystem_RefreshUbcs(user); CHKERRQ(ierr);
2826 ierr = FinalizeCellFieldsFromBoundaryValues(user); CHKERRQ(ierr);
2827
2828 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Post-projection cell-centered fields finalized.\n");
2830 PetscFunctionReturn(0);
2831}
PetscErrorCode FinalizeCellFieldsFromBoundaryValues(UserCtx *user)
Implementation of FinalizeCellFieldsFromBoundaryValues().
PetscErrorCode BoundarySystem_RefreshUbcs(UserCtx *user)
Implementation of BoundarySystem_RefreshUbcs().
Here is the call graph for this function:
Here is the caller graph for this function:

◆ FinalizeCellFieldsFromBoundaryValues()

PetscErrorCode FinalizeCellFieldsFromBoundaryValues ( UserCtx *  user)

Brings Ucat's and P's dummy cells, periodic endpoints, corners and ghosts in line with their interior values and the boundary values already in Ubcs.

The part of FinalizePostProjectionCellFields() that does not ask the handlers to refresh Ubcs, for a caller that sets the boundary values itself. Collective.

Parameters
[in,out]userBlock whose global Ucat, P and Ubcs are current.
Returns
PetscErrorCode 0 on success.

Brings Ucat's and P's dummy cells, periodic endpoints, corners and ghosts in line with their interior values and the boundary values already in Ubcs.

See also
FinalizeCellFieldsFromBoundaryValues()

Definition at line 2837 of file Boundaries.c.

2838{
2839 PetscErrorCode ierr;
2840 const FieldId cell_fields[] = {FIELD_ID_UCAT, FIELD_ID_P};
2841
2842 PetscFunctionBeginUser;
2844
2845 // Establish flat non-periodic faces and periodic endpoints before corners.
2846 ierr = UpdateDummyCells(user, FIELD_ID_UCAT); CHKERRQ(ierr);
2847 ierr = UpdateDummyCells(user, FIELD_ID_P); CHKERRQ(ierr);
2848 ierr = SynchronizePeriodicCellFields(user, 2, cell_fields); CHKERRQ(ierr);
2849
2850 // Corner averaging can overwrite periodic endpoints, so restore them after.
2851 ierr = UpdateCornerNodes(user, FIELD_ID_UCAT); CHKERRQ(ierr);
2852 ierr = UpdateCornerNodes(user, FIELD_ID_P); CHKERRQ(ierr);
2853 ierr = SynchronizePeriodicCellFields(user, 2, cell_fields); CHKERRQ(ierr);
2854
2855 // With a periodic axis that synchronisation ends with the local vectors current: it
2856 // updates them after the corner writes, and each direction's plane refresh restores what
2857 // its transfer changed. With none it does nothing, so they are updated here.
2858 {
2859 PetscBool periodic[3];
2860 GetPeriodicAxes(user->simCtx, periodic);
2861 if (!periodic[0] && !periodic[1] && !periodic[2]) {
2862 ierr = UpdateLocalGhosts(user, FIELD_ID_UCAT); CHKERRQ(ierr);
2863 ierr = UpdateLocalGhosts(user, FIELD_ID_P); CHKERRQ(ierr);
2864 } else {
2865 ierr = VerifyLocalGhostsCurrent(user, FIELD_ID_UCAT, "after the periodic synchronisation"); CHKERRQ(ierr);
2866 ierr = VerifyLocalGhostsCurrent(user, FIELD_ID_P, "after the periodic synchronisation"); CHKERRQ(ierr);
2867 }
2868 }
2869
2871 PetscFunctionReturn(0);
2872}
PetscErrorCode UpdateDummyCells(UserCtx *user, FieldId field_id)
Implementation of UpdateDummyCells().
static PetscErrorCode VerifyLocalGhostsCurrent(UserCtx *user, FieldId field_id, const char *where)
Requires a field's local vector to equal a full ghost update, when -picurv_verify_ghost_updates is se...
PetscErrorCode UpdateCornerNodes(UserCtx *user, FieldId field_id)
Implementation of UpdateCornerNodes().
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ApplyBoundaryConditions()

PetscErrorCode ApplyBoundaryConditions ( UserCtx *  user)

Main boundary-condition orchestrator executed during solver timestepping.

This routine performs the full BC workflow for the current block, including dynamic boundary refresh, periodic transfer, dummy/corner updates, and optional wall-function corrections in the same order expected by the runtime solver. It may iterate boundary updates to enforce coupled boundary dependencies.

Parameters
userThe main UserCtx struct containing field vectors and boundary system state.
Returns
PetscErrorCode 0 on success.

Main boundary-condition orchestrator executed during solver timestepping.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/Boundaries.h.

See also
ApplyBoundaryConditions()

Definition at line 2992 of file Boundaries.c.

2993{
2994 PetscErrorCode ierr;
2995 const FieldId staggered_fields[] = {FIELD_ID_UCONT};
2996 PetscBool periodic[3], any_periodic;
2997 PetscInt passes = user->simCtx->wallfunction ? 3 : 1;
2998 PetscFunctionBeginUser;
3000
3001 LOG_ALLOW(GLOBAL,LOG_TRACE,"Boundary Condition Application begins.\n");
3002
3003 GetPeriodicAxes(user->simCtx, periodic);
3004 any_periodic = (PetscBool)(periodic[0] || periodic[1] || periodic[2]);
3005 for (int face = 0; face < 6; face++) {
3006 if (user->boundary_faces[face].handler && user->boundary_faces[face].handler->needs_repeat_pass) passes = 3;
3007 }
3008 // STEP 1: The boundary passes. Three let information propagate between coupled boundaries,
3009 // like an inlet and a conserving outlet, or a free-slip wall and the interior velocity it
3010 // copies. Without such a face (needs_repeat_pass) and without a wall function, the first
3011 // pass leaves every field final, and verify mode checks that the skipped passes agree.
3012 for (PetscInt iter = 0; iter < passes; iter++) {
3013 ierr = ApplyBoundaryPass(user, any_periodic); CHKERRQ(ierr);
3014 }
3015 if (passes == 1) {
3016 ierr = VerifySinglePassIsFinal(user, any_periodic); CHKERRQ(ierr);
3017 }
3018
3019 // STEP 2: Final staggered periodic synchronization. The last pass already left Ucat, P
3020 // and Ucont's local vectors current with their global ones, so only the transfers run: a
3021 // ghost update depends only on its global vector, and one that repeats an update with no
3022 // write to that vector since changes nothing.
3023 ierr = SynchronizePeriodicStaggeredFieldsFrom(user, 1, staggered_fields, PETSC_TRUE); CHKERRQ(ierr);
3024 ierr = VerifyBoundaryPassFinite(user); CHKERRQ(ierr);
3025
3027 PetscFunctionReturn(0);
3028}
static PetscErrorCode VerifySinglePassIsFinal(UserCtx *user, PetscBool any_periodic)
In verify mode, checks that the passes a single-pass call skipped would change nothing.
static PetscErrorCode VerifyBoundaryPassFinite(UserCtx *user)
Requires the boundary pass's fields to be finite, when -picurv_verify_ghost_updates is set.
static PetscErrorCode ApplyBoundaryPass(UserCtx *user, PetscBool any_periodic)
One boundary pass: the handlers, Contra2Cart, the wall function, the dummy, periodic and corner updat...
Here is the call graph for this function:
Here is the caller graph for this function: