PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
Data Structures | Macros | Typedefs | Enumerations | Functions
BC_Handlers.c File Reference
#include "BC_Handlers.h"
#include "expression.h"
#include "Metric.h"
Include dependency graph for BC_Handlers.c:

Go to the source code of this file.

Data Structures

struct  InletPrescribedVelocityData
 Private data of the prescribed-velocity inlet: a compiled source or a PICSLICE file, the values of the source's variables at each face slot this rank owns, and the velocity they last gave. More...
 
struct  OutletConservationData
 Per-face state of the backflow clip; see the section comment above. More...
 
struct  DrivenFluxData
 Private data structure shared by both periodic driven-flux handlers. More...
 

Macros

#define INFLOW_LATTICE_PAD   1048576
 Face cells the synthetic-inflow draw lattice extends beyond each edge; a filter half-width may not exceed it.
 

Typedefs

typedef Cmpnts(* FaceBoundaryVelocityRule) (const BoundaryCondition *self, BCFace face_id, PetscInt i, PetscInt j, PetscInt k, Cmpnts metric, PetscReal sign, Cmpnts interior)
 Cartesian boundary velocity one handler prescribes at one boundary face slot.
 

Enumerations

enum  OutletClipPassMode { OUTLET_CLIP_DECIDE , OUTLET_CLIP_MEASURE , OUTLET_CLIP_WRITE }
 What one OutletClipPass() over the owned outlet elements does. More...
 

Functions

PetscErrorCode Validate_DrivenFlowConfiguration (UserCtx *user)
 Implementation of Validate_DrivenFlowConfiguration().
 
static PetscErrorCode ApplyFaceBoundaryVelocity (BoundaryCondition *self, BCContext *ctx, FaceBoundaryVelocityRule rule)
 Sets a handler's boundary velocity and the face flux it implies on one face.
 
static PetscErrorCode Apply_WallNoSlip (BoundaryCondition *self, BCContext *ctx)
 Apply no-slip velocity values to wall-adjacent cells for this boundary condition.
 
PetscErrorCode Create_WallNoSlip (BoundaryCondition *bc)
 Implementation of Create_WallNoSlip().
 
static Cmpnts WallNoSlipVelocity (const BoundaryCondition *self, BCFace face_id, PetscInt i, PetscInt j, PetscInt k, Cmpnts metric, PetscReal sign, Cmpnts interior)
 The no-slip wall's boundary velocity: the wall's own, which is at rest.
 
static PetscErrorCode Apply_WallFreeSlip (BoundaryCondition *self, BCContext *ctx)
 Apply free-slip boundary values to wall-adjacent cells for this boundary condition.
 
PetscErrorCode Create_WallFreeSlip (BoundaryCondition *bc)
 Implementation of Create_WallFreeSlip().
 
static Cmpnts WallFreeSlipVelocity (const BoundaryCondition *self, BCFace face_id, PetscInt i, PetscInt j, PetscInt k, Cmpnts metric, PetscReal sign, Cmpnts interior)
 The free-slip wall's boundary velocity: the adjacent velocity, less its normal part.
 
static PetscErrorCode Initialize_InletPrescribedVelocity (BoundaryCondition *self, BCContext *ctx)
 Compile the source named by the face's source_id parameter, with its bulk velocity or flow rate if any, record the PICSLICE file named by its source_file parameter, and read the synthetic-fluctuation settings -face_source_<id>_fluct*: the Reynolds-stress sources and the integral length and time scales.
 
static PetscErrorCode PreStep_InletPrescribedVelocity (BoundaryCondition *self, BCContext *ctx, PetscReal *local_inflow_contribution, PetscReal *local_outflow_contribution)
 Refresh the inlet velocity once per step: gather the slots on the first call, then re-evaluate and rescale only what depends on t.
 
static PetscErrorCode Apply_InletVelocity (BoundaryCondition *self, BCContext *ctx)
 Applies the prescribed inlet velocity through the common face-layout path.
 
static PetscErrorCode PostStep_InletFlux (BoundaryCondition *self, BCContext *ctx, PetscReal *local_inflow_contribution, PetscReal *local_outflow_contribution)
 Adds the inlet face's applied flux, the sum of its normal Ucont, to the inflow.
 
static PetscErrorCode Apply_WallMoving (BoundaryCondition *self, BCContext *ctx)
 Applies a moving wall's velocity through the path every prescribed face shares.
 
static PetscErrorCode Destroy_InletPrescribedVelocity (BoundaryCondition *self)
 Release the compiled source and the per-slot arrays.
 
static PetscInt PrescribedSlot (const InletPrescribedVelocityData *data, PetscInt i, PetscInt j, PetscInt k)
 Index of the owned slot (i, j, k) in a prescribed-velocity inlet's per-slot arrays.
 
PetscErrorCode Create_InletPrescribedVelocity (BoundaryCondition *bc)
 Implementation of Create_InletPrescribedVelocity().
 
PetscErrorCode Create_WallMoving (BoundaryCondition *bc)
 Implementation of Create_WallMoving().
 
static PetscErrorCode GetProfileFileExpectedDims (UserCtx *user, BCFace face_id, PetscInt *n1, PetscInt *n2)
 Computes the expected PICSLICE dimensions for an inlet face.
 
static PetscErrorCode OpenPicSlice (InletPrescribedVelocityData *data, PetscInt expected_n1, PetscInt expected_n2)
 Opens a canonical PICSLICE file and reads its header.
 
static PetscErrorCode ReadPicSliceFrame (InletPrescribedVelocityData *data)
 Reads the frame at the file's position into file_values, validating every value: finite, and a normal speed nonnegative.
 
static Cmpnts EvaluateInletCartesianVelocity (const BoundaryCondition *self, BCFace face_id, PetscInt i, PetscInt j, PetscInt k, Cmpnts metric, PetscReal sign, Cmpnts interior)
 Prescribed velocity at one inlet face slot, as a Cartesian vector.
 
static Cmpnts EvaluateMovingWallVelocity (const BoundaryCondition *self, BCFace face_id, PetscInt i, PetscInt j, PetscInt k, Cmpnts metric, PetscReal sign, Cmpnts interior)
 A moving wall's boundary velocity: the source's, with any part along the face removed, since a wall closes its face.
 
static PetscErrorCode PrescribedFaceSums (const InletPrescribedVelocityData *data, UserCtx *user, BCFace face_id, PetscReal local[4])
 This rank's area-weighted sums over the face, physical: the source's normal speed, the staged data's when expressions add to it, the area, and the synthetic fluctuations' inflow (zero without them).
 
static PetscErrorCode PrescribedBulkFactor (InletPrescribedVelocityData *data, UserCtx *user, BCFace face_id, PetscReal physical_time, PetscReal *factor)
 Factor that makes the face's mean normal speed or flow rate equal the target.
 
static PetscErrorCode LoadPrescribedFrame (InletPrescribedVelocityData *data, PetscInt frame, Cmpnts *target)
 Read one frame of the face's PICSLICE into this rank's slots, moving the file there.
 
static PetscErrorCode OpenPrescribedProfile (InletPrescribedVelocityData *data, UserCtx *user, BCFace face_id)
 Open the face's PICSLICE and read a lone frame, as the velocity itself or, under expressions, as what they add to; several frames are read as time reaches them.
 
static PetscErrorCode InterpolatePrescribedFrames (InletPrescribedVelocityData *data, BCFace face_id, PetscReal physical_time)
 Set the staged data at a time: linear between the two frames around it, the first at t = 0.
 
PetscErrorCode LogPrescribedFlowDiagnostics (UserCtx *user)
 Implementation of LogPrescribedFlowDiagnostics().
 
static PetscErrorCode BuildInletFluctuation (InletPrescribedVelocityData *data, UserCtx *user)
 Prepare an inlet's synthetic fluctuations once its slots exist: filter widths from the face's mean spacing, and the Reynolds stresses' Cholesky factor at each slot.
 
static PetscErrorCode StepInletFluctuation (InletPrescribedVelocityData *data, UserCtx *user, BCFace face_id)
 This step's synthetic fluctuation at every owned slot of an inlet.
 
static PetscErrorCode PreStep_OutletConservation (BoundaryCondition *self, BCContext *ctx, PetscReal *local_inflow_contribution, PetscReal *local_outflow_contribution)
 Prepare the outlet-conservation correction before advancing the solver.
 
static PetscErrorCode Apply_OutletConservation (BoundaryCondition *self, BCContext *ctx)
 (Handler Action) Applies mass conservation correction to the outlet face.
 
static PetscErrorCode PostStep_OutletConservation (BoundaryCondition *self, BCContext *ctx, PetscReal *local_inflow_contribution, PetscReal *local_outflow_contribution)
 Update outlet-conservation state after a completed solver step.
 
static PetscErrorCode Destroy_OutletConservation (BoundaryCondition *self)
 Release the outlet-conservation handler's clip state.
 
PetscErrorCode Create_OutletConservation (BoundaryCondition *bc)
 Implementation of Create_OutletConservation().
 
static PetscErrorCode OutletClipPass (UserCtx *user, BCFace face_id, OutletConservationData *data, OutletClipPassMode mode, PetscReal correction, PetscReal psi, PetscReal sums[3])
 One pass over this rank's elements of an outlet face for the backflow clip.
 
static PetscErrorCode OutletConservationClip (UserCtx *user, BCFace face_id, OutletConservationData *data, PetscReal correction, PetscBool *applied)
 Run the backflow clip for one Apply call; see the section comment.
 
PetscErrorCode Create_PeriodicGeometric (BoundaryCondition *bc)
 Implementation of Create_PeriodicGeometric().
 
static PetscErrorCode MeasureDrivenFluxes (UserCtx *user, char direction, PetscReal *boundaryFlux, PetscReal *planarAverageFlux)
 Measure the two volumetric fluxes the driven-flow controller senses.
 
static PetscErrorCode Initialize_PeriodicDrivenConstant (BoundaryCondition *self, BCContext *ctx)
 Initialize constant forcing data for a periodically driven boundary.
 
static PetscErrorCode PreStep_PeriodicDrivenConstant (BoundaryCondition *self, BCContext *ctx, PetscReal *local_inflow_contribution, PetscReal *local_outflow_contribution)
 Prepare constant periodic-driving data before the solver step.
 
static PetscErrorCode Apply_PeriodicDrivenConstant (BoundaryCondition *self, BCContext *ctx)
 Apply the configured constant driving term to the periodic boundary.
 
static PetscErrorCode Destroy_PeriodicDrivenConstant (BoundaryCondition *self)
 Release resources owned by the constant periodic-driving boundary.
 
PetscErrorCode Create_PeriodicDrivenConstant (BoundaryCondition *bc)
 Implementation of Create_PeriodicDrivenConstant().
 
static PetscErrorCode Initialize_PeriodicDrivenInitial (BoundaryCondition *self, BCContext *ctx)
 Initialize forcing data for a periodic boundary driven to its initial flux.
 
static PetscErrorCode PreStep_PeriodicDrivenInitial (BoundaryCondition *self, BCContext *ctx, PetscReal *local_inflow_contribution, PetscReal *local_outflow_contribution)
 Latch the initial-state flux once, then drive to it like a constant target.
 
PetscErrorCode Create_PeriodicDrivenInitial (BoundaryCondition *bc)
 Implementation of Create_PeriodicDrivenInitial().
 

Data Structure Documentation

◆ InletPrescribedVelocityData

struct InletPrescribedVelocityData

Private data of the prescribed-velocity inlet: a compiled source or a PICSLICE file, the values of the source's variables at each face slot this rank owns, and the velocity they last gave.

Definition at line 277 of file BC_Handlers.c.

Collaboration diagram for InletPrescribedVelocityData:
[legend]
Data Fields
PicurvVelocitySource source
char * source_file
Cmpnts * profile
FILE * file
fpos_t first_frame
PetscInt frames
PetscInt components
PetscInt next_frame
PetscInt file_n[2]
PetscReal interval
PetscBool repeat
PetscReal * file_values
Cmpnts * bracket[2]
PetscInt bracket_frame[2]
PicurvSourceFaceSlots slots
Cmpnts * velocity
PetscReal factor
PetscInt evaluated_step
PetscBool built
PetscBool fluctuate
PicurvVelocitySource stress[2]
PetscReal fluct_length[2]
PetscReal fluct_time
PetscInt half[2]
PetscReal * kernel[2]
PetscReal(* lund)[6]
Cmpnts * fluct
PetscBool fluct_started

◆ OutletConservationData

struct OutletConservationData

Per-face state of the backflow clip; see the section comment above.

Definition at line 1401 of file BC_Handlers.c.

Data Fields
PetscInt decisionStep
PetscBool clipRule
PetscInt maskSize
PetscBool * clipped

◆ DrivenFluxData

struct DrivenFluxData

Private data structure shared by both periodic driven-flux handlers.

constant_flux fills targetVolumetricFlux from the bcs file at initialization; initial_flux latches it from the starting field at the first PreStep. Everything downstream of the target is identical, so both handlers reuse this struct and the PreStep/Apply/Destroy implementations below.

Definition at line 2263 of file BC_Handlers.c.

Data Fields
char direction
PetscReal targetVolumetricFlux
PetscBool isMasterController
PetscBool enforceSeamFlux
PetscInt lastBulkCorrectionStep

Macro Definition Documentation

◆ INFLOW_LATTICE_PAD

#define INFLOW_LATTICE_PAD   1048576

Face cells the synthetic-inflow draw lattice extends beyond each edge; a filter half-width may not exceed it.

Definition at line 1102 of file BC_Handlers.c.

Typedef Documentation

◆ FaceBoundaryVelocityRule

typedef Cmpnts(* FaceBoundaryVelocityRule) (const BoundaryCondition *self, BCFace face_id, PetscInt i, PetscInt j, PetscInt k, Cmpnts metric, PetscReal sign, Cmpnts interior)

Cartesian boundary velocity one handler prescribes at one boundary face slot.

Definition at line 97 of file BC_Handlers.c.

Enumeration Type Documentation

◆ OutletClipPassMode

What one OutletClipPass() over the owned outlet elements does.

Enumerator
OUTLET_CLIP_DECIDE 
OUTLET_CLIP_MEASURE 
OUTLET_CLIP_WRITE 

Definition at line 1578 of file BC_Handlers.c.

OutletClipPassMode
What one OutletClipPass() over the owned outlet elements does.
@ OUTLET_CLIP_MEASURE
@ OUTLET_CLIP_WRITE
@ OUTLET_CLIP_DECIDE

Function Documentation

◆ Validate_DrivenFlowConfiguration()

PetscErrorCode Validate_DrivenFlowConfiguration ( UserCtx *  user)

Implementation of Validate_DrivenFlowConfiguration().

(Private) Validates all consistency rules for a driven flow (channel/pipe) setup.

See also
Validate_DrivenFlowConfiguration()

Definition at line 15 of file BC_Handlers.c.

16{
17 PetscFunctionBeginUser;
19
20 // --- CHECK 1: Detect if a driven flow is active. ---
21 PetscBool is_driven_flow_active = PETSC_FALSE;
22 char driven_direction = ' ';
23 const char* first_driven_face_name = "";
24
25 for (int i = 0; i < 6; i++) {
26 BCHandlerType handler_type = user->boundary_faces[i].handler_type;
27 if (handler_type == BC_HANDLER_PERIODIC_DRIVEN_CONSTANT_FLUX ||
29 {
30 is_driven_flow_active = PETSC_TRUE;
31 first_driven_face_name = BCFaceToString((BCFace)i);
32
33 if (i <= 1) driven_direction = 'X';
34 else if (i <= 3) driven_direction = 'Y';
35 else driven_direction = 'Z';
36
37 break; // Exit loop once we've confirmed it's active and found the direction.
38 }
39 }
40
41 // If no driven flow handler is found, validation for this rule set is complete.
42 if (!is_driven_flow_active) {
44 PetscFunctionReturn(0);
45 }
46
47 LOG_ALLOW(GLOBAL, LOG_DEBUG, " - Driven Flow Handler detected on face %s. Applying driven flow validation rules...\n", first_driven_face_name);
48
49 // --- CHECK 2: Ensure no conflicting BCs (Inlet/Outlet/Far-field) are present. ---
50 LOG_ALLOW(GLOBAL, LOG_DEBUG, " - Checking for incompatible Inlet/Outlet/Far-field BCs...\n");
51 for (int i = 0; i < 6; i++) {
52 BCType math_type = user->boundary_faces[i].mathematical_type;
53 if (math_type == INLET || math_type == OUTLET || math_type == FARFIELD) {
54 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT,
55 "Configuration Error: A DRIVEN flow handler is active, which is incompatible with the %s boundary condition found on face %s.",
56 BCTypeToString(math_type), BCFaceToString((BCFace)i));
57 }
58 }
59 LOG_ALLOW(GLOBAL, LOG_DEBUG, " ... No conflicting BC types found. OK.\n");
60
61 // --- CHECK 3: Ensure both ends of the driven direction have identical, valid setups. ---
62 LOG_ALLOW(GLOBAL, LOG_DEBUG, " - Validating symmetry and mathematical types for the '%c' direction...\n", driven_direction);
63
64 PetscInt neg_face_idx = 0, pos_face_idx = 0;
65 if (driven_direction == 'X') {
66 neg_face_idx = BC_FACE_NEG_X; pos_face_idx = BC_FACE_POS_X;
67 } else if (driven_direction == 'Y') {
68 neg_face_idx = BC_FACE_NEG_Y; pos_face_idx = BC_FACE_POS_Y;
69 } else { // 'Z'
70 neg_face_idx = BC_FACE_NEG_Z; pos_face_idx = BC_FACE_POS_Z;
71 }
72
73 BoundaryFaceConfig *neg_face_cfg = &user->boundary_faces[neg_face_idx];
74 BoundaryFaceConfig *pos_face_cfg = &user->boundary_faces[pos_face_idx];
75
76 // Rule 3a: Both faces must be PERIODIC.
77 if (neg_face_cfg->mathematical_type != PERIODIC || pos_face_cfg->mathematical_type != PERIODIC) {
78 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT,
79 "Configuration Error: For a driven flow in the '%c' direction, both the %s and %s faces must be of mathematical_type PERIODIC.",
80 driven_direction, BCFaceToString((BCFace)neg_face_idx), BCFaceToString((BCFace)pos_face_idx));
81 }
82
83 // Rule 3b: Both faces must use the exact same handler type.
84 if (neg_face_cfg->handler_type != pos_face_cfg->handler_type) {
85 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT,
86 "Configuration Error: The DRIVEN handlers on the %s and %s faces of the '%c' direction do not match. Both must be the same type (e.g., both CONSTANT_FLUX).",
87 BCFaceToString((BCFace)neg_face_idx), BCFaceToString((BCFace)pos_face_idx), driven_direction);
88 }
89
90 LOG_ALLOW(GLOBAL, LOG_DEBUG, " ... Symmetry and mathematical types are valid. OK.\n");
91
93 PetscFunctionReturn(0);
94}
#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
const char * BCTypeToString(BCType type)
Returns the canonical log token for a boundary mathematical type.
Definition logging.c:828
@ LOG_DEBUG
Detailed debugging information.
Definition logging.h:32
#define PROFILE_FUNCTION_BEGIN
Marks the beginning of a profiled function: an always-on aggregate timer.
Definition logging.h:1000
BCType
Defines the general mathematical/physical Category of a boundary.
Definition variables.h:316
@ INLET
Definition variables.h:323
@ FARFIELD
Definition variables.h:324
@ OUTLET
Definition variables.h:322
@ PERIODIC
Definition variables.h:325
BoundaryFaceConfig boundary_faces[6]
Definition variables.h:1182
BCHandlerType
Defines the specific computational "strategy" for a boundary handler.
Definition variables.h:343
@ BC_HANDLER_PERIODIC_DRIVEN_INITIAL_FLUX
Definition variables.h:355
@ BC_HANDLER_PERIODIC_DRIVEN_CONSTANT_FLUX
Definition variables.h:354
BCHandlerType handler_type
Definition variables.h:427
BCType mathematical_type
Definition variables.h:426
BCFace
Identifies the six logical faces of a structured computational block.
Definition variables.h:308
@ 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
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:

◆ ApplyFaceBoundaryVelocity()

static PetscErrorCode ApplyFaceBoundaryVelocity ( BoundaryCondition *  self,
BCContext *  ctx,
FaceBoundaryVelocityRule  rule 
)
static

Sets a handler's boundary velocity and the face flux it implies on one face.

Shared by every handler that prescribes a Cartesian velocity at its face: the inlets, the no-slip wall and the free-slip wall. For each boundary slot this rank owns it asks rule for the velocity, stores it as the boundary value, and sets the face flux to its product with the face metric. A rule whose velocity is tangent to the face therefore closes the face. A slot whose fluid side is blanked (nvert > 0.1) belongs to an immersed body, whose own boundary condition applies there, so it is left untouched.

Parameters
selfHandler being applied.
ctxBoundary context naming the face.
ruleVelocity the handler prescribes, given the slot, the face metric, the side (sign, positive on a negative face) and the adjacent interior velocity.
Returns
PetscErrorCode 0 on success.

Definition at line 653 of file BC_Handlers.c.

655{
656 UserCtx *user = ctx->user;
657 BCFace face_id = ctx->face_id;
658 PetscBool can_service;
659 DMDALocalInfo *info = &user->info;
660 Cmpnts ***ubcs, ***ucont, ***csi, ***eta, ***zet, ***ucat;
661 PetscReal ***nvert;
662
663 PetscFunctionBeginUser;
665
666 PetscCall(CanRankServiceFace(info, user->IM, user->JM, user->KM, face_id, &can_service));
667 if (!can_service) { PROFILE_HELPER_END; PetscFunctionReturn(0); }
668
669 PetscCall(DMDAVecGetArray(user->fda, user->Bcs.Ubcs, &ubcs));
670 PetscCall(DMDAVecGetArray(user->fda, user->Ucont, &ucont));
671 PetscCall(DMDAVecGetArrayRead(user->fda, user->lCsi, (const Cmpnts***)&csi));
672 PetscCall(DMDAVecGetArrayRead(user->fda, user->lEta, (const Cmpnts***)&eta));
673 PetscCall(DMDAVecGetArrayRead(user->fda, user->lZet, (const Cmpnts***)&zet));
674 PetscCall(DMDAVecGetArrayRead(user->da, user->lNvert, (const PetscReal***)&nvert));
675 PetscCall(DMDAVecGetArrayRead(user->fda, user->lUcat, (const Cmpnts***)&ucat));
676
677 const PetscInt xs = info->xs, xe = info->xs + info->xm;
678 const PetscInt ys = info->ys, ye = info->ys + info->ym;
679 const PetscInt zs = info->zs, ze = info->zs + info->zm;
680 const PetscInt mx = info->mx, my = info->my, mz = info->mz;
681 PetscInt lxs = xs, lxe = xe, lys = ys, lye = ye, lzs = zs, lze = ze;
682 if (xs == 0) lxs++;
683 if (xe == mx) lxe--;
684 if (ys == 0) lys++;
685 if (ye == my) lye--;
686 if (zs == 0) lzs++;
687 if (ze == mz) lze--;
688
689 switch (face_id) {
690 case BC_FACE_NEG_X:
691 case BC_FACE_POS_X: {
692 const PetscReal sign = (face_id == BC_FACE_NEG_X) ? 1.0 : -1.0;
693 const PetscInt i = (face_id == BC_FACE_NEG_X) ? xs : mx - 2;
694 const PetscInt ib = i + (sign < 0);
695 for (PetscInt k = lzs; k < lze; k++) {
696 for (PetscInt j = lys; j < lye; j++) {
697 if ((sign > 0 && nvert[k][j][i + 1] > 0.1) ||
698 (sign < 0 && nvert[k][j][i] > 0.1)) continue;
699 const Cmpnts metric = csi[k][j][i];
700 const Cmpnts velocity = rule(self, face_id, i, j, k, metric, sign,
701 (sign > 0) ? ucat[k][j][i + 1] : ucat[k][j][i]);
702 ubcs[k][j][ib] = velocity;
703 ucont[k][j][i].x = velocity.x * metric.x + velocity.y * metric.y + velocity.z * metric.z;
704 }
705 }
706 } break;
707 case BC_FACE_NEG_Y:
708 case BC_FACE_POS_Y: {
709 const PetscReal sign = (face_id == BC_FACE_NEG_Y) ? 1.0 : -1.0;
710 const PetscInt j = (face_id == BC_FACE_NEG_Y) ? ys : my - 2;
711 const PetscInt jb = j + (sign < 0);
712 for (PetscInt k = lzs; k < lze; k++) {
713 for (PetscInt i = lxs; i < lxe; i++) {
714 if ((sign > 0 && nvert[k][j + 1][i] > 0.1) ||
715 (sign < 0 && nvert[k][j][i] > 0.1)) continue;
716 const Cmpnts metric = eta[k][j][i];
717 const Cmpnts velocity = rule(self, face_id, i, j, k, metric, sign,
718 (sign > 0) ? ucat[k][j + 1][i] : ucat[k][j][i]);
719 ubcs[k][jb][i] = velocity;
720 ucont[k][j][i].y = velocity.x * metric.x + velocity.y * metric.y + velocity.z * metric.z;
721 }
722 }
723 } break;
724 case BC_FACE_NEG_Z:
725 case BC_FACE_POS_Z: {
726 const PetscReal sign = (face_id == BC_FACE_NEG_Z) ? 1.0 : -1.0;
727 const PetscInt k = (face_id == BC_FACE_NEG_Z) ? zs : mz - 2;
728 const PetscInt kb = k + (sign < 0);
729 for (PetscInt j = lys; j < lye; j++) {
730 for (PetscInt i = lxs; i < lxe; i++) {
731 if ((sign > 0 && nvert[k + 1][j][i] > 0.1) ||
732 (sign < 0 && nvert[k][j][i] > 0.1)) continue;
733 const Cmpnts metric = zet[k][j][i];
734 const Cmpnts velocity = rule(self, face_id, i, j, k, metric, sign,
735 (sign > 0) ? ucat[k + 1][j][i] : ucat[k][j][i]);
736 ubcs[kb][j][i] = velocity;
737 ucont[k][j][i].z = velocity.x * metric.x + velocity.y * metric.y + velocity.z * metric.z;
738 }
739 }
740 } break;
741 }
742
743 PetscCall(DMDAVecRestoreArray(user->fda, user->Bcs.Ubcs, &ubcs));
744 PetscCall(DMDAVecRestoreArray(user->fda, user->Ucont, &ucont));
745 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lCsi, (const Cmpnts***)&csi));
746 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lEta, (const Cmpnts***)&eta));
747 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lZet, (const Cmpnts***)&zet));
748 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lUcat, (const Cmpnts***)&ucat));
749 PetscCall(DMDAVecRestoreArrayRead(user->da, user->lNvert, (const PetscReal***)&nvert));
751 PetscFunctionReturn(0);
752}
PetscErrorCode CanRankServiceFace(const DMDALocalInfo *info, PetscInt IM_nodes_global, PetscInt JM_nodes_global, PetscInt KM_nodes_global, BCFace face_id, PetscBool *can_service_out)
Determines if the current MPI rank owns any part of a specified global face.
Definition Boundaries.c:22
#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
Vec lNvert
Definition variables.h:1197
PetscInt KM
Definition variables.h:1171
BCFace face_id
Definition variables.h:381
Vec Ucont
Definition variables.h:1197
Vec Ubcs
Physical Cartesian velocity at boundary faces. Full 3D array but only boundary-face entries are meani...
Definition variables.h:172
PetscScalar x
Definition variables.h:145
UserCtx * user
Definition variables.h:380
PetscScalar z
Definition variables.h:145
PetscInt JM
Definition variables.h:1171
DMDALocalInfo info
Definition variables.h:1169
Vec lUcat
Definition variables.h:1197
PetscScalar y
Definition variables.h:145
PetscInt IM
Definition variables.h:1171
A 3D point or vector with PetscScalar components.
Definition variables.h:144
User-defined context containing data specific to a single computational grid level.
Definition variables.h:1157
Here is the call graph for this function:
Here is the caller graph for this function:

◆ Apply_WallNoSlip()

static PetscErrorCode Apply_WallNoSlip ( BoundaryCondition *  self,
BCContext *  ctx 
)
static

Apply no-slip velocity values to wall-adjacent cells for this boundary condition.

A zero boundary velocity also closes the face, since its flux is the velocity's product with the face metric.

Definition at line 166 of file BC_Handlers.c.

167{
168 PetscFunctionBeginUser;
170 LOG_ALLOW(LOCAL, LOG_DEBUG, "Apply_WallNoSlip: Applying to Face %d (%s).\n",
171 ctx->face_id, BCFaceToString(ctx->face_id));
172 PetscCall(ApplyFaceBoundaryVelocity(self, ctx, WallNoSlipVelocity));
174 PetscFunctionReturn(0);
175}
static PetscErrorCode ApplyFaceBoundaryVelocity(BoundaryCondition *self, BCContext *ctx, FaceBoundaryVelocityRule rule)
Sets a handler's boundary velocity and the face flux it implies on one face.
static Cmpnts WallNoSlipVelocity(const BoundaryCondition *self, BCFace face_id, PetscInt i, PetscInt j, PetscInt k, Cmpnts metric, PetscReal sign, Cmpnts interior)
The no-slip wall's boundary velocity: the wall's own, which is at rest.
#define LOCAL
Logging scope definitions for controlling message output.
Definition logging.h:45
Here is the call graph for this function:
Here is the caller graph for this function:

◆ Create_WallNoSlip()

PetscErrorCode Create_WallNoSlip ( BoundaryCondition *  bc)

Implementation of Create_WallNoSlip().

Configures a BoundaryCondition object to behave as a no-slip, stationary wall.

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

See also
Create_WallNoSlip()

Definition at line 123 of file BC_Handlers.c.

124{
125 PetscFunctionBeginUser;
127
128 PetscCheck(bc, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "BoundaryCondition is NULL");
129
130 // ✅ Set priority
132
133 // Assign function pointers
134 bc->Initialize = NULL;
135 bc->PreStep = NULL;
137 bc->PostStep = NULL;
138 bc->UpdateUbcs = NULL;
139 bc->Destroy = NULL;
140
141 // No private data needed for this simple handler
142 bc->data = NULL;
143
145 PetscFunctionReturn(0);
146}
static PetscErrorCode Apply_WallNoSlip(BoundaryCondition *self, BCContext *ctx)
Apply no-slip velocity values to wall-adjacent cells for this boundary condition.
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
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
BCPriorityType priority
Definition variables.h:391
@ BC_PRIORITY_WALL
Definition variables.h:363
Here is the call graph for this function:
Here is the caller graph for this function:

◆ WallNoSlipVelocity()

static Cmpnts WallNoSlipVelocity ( const BoundaryCondition *  self,
BCFace  face_id,
PetscInt  i,
PetscInt  j,
PetscInt  k,
Cmpnts  metric,
PetscReal  sign,
Cmpnts  interior 
)
static

The no-slip wall's boundary velocity: the wall's own, which is at rest.

Definition at line 151 of file BC_Handlers.c.

154{
155 const Cmpnts rest = {0.0, 0.0, 0.0};
156
157 (void)self; (void)face_id; (void)i; (void)j; (void)k; (void)metric; (void)sign; (void)interior;
158 return rest;
159}
Here is the caller graph for this function:

◆ Apply_WallFreeSlip()

static PetscErrorCode Apply_WallFreeSlip ( BoundaryCondition *  self,
BCContext *  ctx 
)
static

Apply free-slip boundary values to wall-adjacent cells for this boundary condition.

Definition at line 237 of file BC_Handlers.c.

238{
239 PetscFunctionBeginUser;
241 PetscCall(ApplyFaceBoundaryVelocity(self, ctx, WallFreeSlipVelocity));
243 PetscFunctionReturn(0);
244}
static Cmpnts WallFreeSlipVelocity(const BoundaryCondition *self, BCFace face_id, PetscInt i, PetscInt j, PetscInt k, Cmpnts metric, PetscReal sign, Cmpnts interior)
The free-slip wall's boundary velocity: the adjacent velocity, less its normal part.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ Create_WallFreeSlip()

PetscErrorCode Create_WallFreeSlip ( BoundaryCondition *  bc)

Implementation of Create_WallFreeSlip().

Configures a BoundaryCondition object to behave as a free-slip wall.

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

See also
Create_WallFreeSlip()

Definition at line 197 of file BC_Handlers.c.

198{
199 PetscFunctionBeginUser;
201 PetscCheck(bc, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "BoundaryCondition is NULL");
203 bc->Initialize = NULL;
204 bc->PreStep = NULL;
206 bc->PostStep = NULL;
207 /* The boundary value follows the adjacent velocity, so it is refreshed whenever
208 * the velocity is: on every boundary pass and after each projection. */
210 bc->needs_repeat_pass = PETSC_TRUE; // Copies the adjacent Ucat, which the pass refreshes after it
211 bc->Destroy = NULL;
212 bc->data = NULL;
214 PetscFunctionReturn(0);
215}
static PetscErrorCode Apply_WallFreeSlip(BoundaryCondition *self, BCContext *ctx)
Apply free-slip boundary values to wall-adjacent cells for this boundary condition.
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
Here is the call graph for this function:
Here is the caller graph for this function:

◆ WallFreeSlipVelocity()

static Cmpnts WallFreeSlipVelocity ( const BoundaryCondition *  self,
BCFace  face_id,
PetscInt  i,
PetscInt  j,
PetscInt  k,
Cmpnts  metric,
PetscReal  sign,
Cmpnts  interior 
)
inlinestatic

The free-slip wall's boundary velocity: the adjacent velocity, less its normal part.

Removing the component along the face metric leaves a velocity tangent to the face, so the face flux vanishes; placing it as the boundary value makes the dummy cell the mirror image of the interior one, reversing the normal velocity and keeping the tangential one, which is zero normal gradient. On a curvilinear grid the metric is the face's own normal, so the construction holds there too.

Definition at line 226 of file BC_Handlers.c.

229{
230 (void)self; (void)face_id; (void)i; (void)j; (void)k; (void)sign;
231 return RemoveFaceNormalComponent(interior, metric);
232}
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
Here is the call graph for this function:
Here is the caller graph for this function:

◆ Initialize_InletPrescribedVelocity()

static PetscErrorCode Initialize_InletPrescribedVelocity ( BoundaryCondition *  self,
BCContext *  ctx 
)
static

Compile the source named by the face's source_id parameter, with its bulk velocity or flow rate if any, record the PICSLICE file named by its source_file parameter, and read the synthetic-fluctuation settings -face_source_<id>_fluct*: the Reynolds-stress sources and the integral length and time scales.

Definition at line 797 of file BC_Handlers.c.

798{
800 UserCtx *user = ctx->user;
801 PetscReal id = -1.0;
802 PetscBool found = PETSC_FALSE;
803 const char *source_file = NULL;
804 char prefix[64];
805
806 PetscFunctionBeginUser;
808 PetscCall(GetBCParamReal(user->boundary_faces[ctx->face_id].params, "source_id", &id, &found));
809 PetscCheck(found && id >= 0.0, PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT,
810 "Face %s: the prescribed_velocity inlet needs a source_id parameter.", BCFaceToString(ctx->face_id));
811 PetscCall(GetBCParamString(user->boundary_faces[ctx->face_id].params, "source_file", &source_file, &found));
812 if (found && source_file && source_file[0] != '\0') {
813 PetscCall(PetscStrallocpy(source_file, &data->source_file));
814 }
815 PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "face_source_%d", (int)id));
816 PetscCall(PicurvVelocitySourceCreate(prefix, PETSC_TRUE, (PetscBool)(data->source_file != NULL), PETSC_TRUE, &data->source));
817 PetscCheck(!data->source_file || data->source.frame == PICURV_SOURCE_FRAME_NORMAL ||
818 data->source.frame == PICURV_SOURCE_FRAME_CARTESIAN, PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT,
819 "Face %s: a profile file and the expressions added to it are in the normal or cartesian frame.",
820 BCFaceToString(ctx->face_id));
821 PetscCall(GetBCParamBool(user->boundary_faces[ctx->face_id].params, "source_repeat", &data->repeat, &found));
822 data->factor = 1.0;
823 data->evaluated_step = -1;
824 {
825 char option[96], stress_prefix[96];
826 PetscInt count = 2;
827 PetscCall(PetscSNPrintf(option, sizeof(option), "-%s_fluct", prefix));
828 PetscCall(PetscOptionsGetBool(NULL, NULL, option, &data->fluctuate, NULL));
829 if (data->fluctuate) {
830 PetscCheck(user->InflowFluctuation, PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONGSTATE,
831 "Face %s adds fluctuations, but -inflow_fluctuations did not allocate their state.",
832 BCFaceToString(ctx->face_id));
833 for (PetscInt g = 0; g < 2; ++g) {
834 PetscCall(PetscSNPrintf(stress_prefix, sizeof(stress_prefix), "%s_fluct_stress_%d", prefix, (int)g));
835 PetscCall(PicurvVelocitySourceCreate(stress_prefix, PETSC_TRUE, PETSC_FALSE, PETSC_FALSE, &data->stress[g]));
836 /* Three stress components, as read: no frame turns them, and no bulk velocity or
837 flow rate scales them. */
838 PetscCheck(data->stress[g].frame == PICURV_SOURCE_FRAME_CARTESIAN && !data->stress[g].bulk,
839 PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT,
840 "Face %s: the Reynolds stresses -%s_* must be in the cartesian frame, with no bulk_velocity or flow_rate.",
841 BCFaceToString(ctx->face_id), stress_prefix);
842 }
843 PetscCall(PetscSNPrintf(option, sizeof(option), "-%s_fluct_length", prefix));
844 PetscCall(PetscOptionsGetRealArray(NULL, NULL, option, data->fluct_length, &count, &found));
845 PetscCheck(found && count == 2 && data->fluct_length[0] > 0.0 && data->fluct_length[1] > 0.0,
846 PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT, "%s needs two positive length scales.", option);
847 PetscCall(PetscSNPrintf(option, sizeof(option), "-%s_fluct_time", prefix));
848 PetscCall(PetscOptionsGetReal(NULL, NULL, option, &data->fluct_time, &found));
849 PetscCheck(found && data->fluct_time > 0.0, PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT,
850 "%s needs a positive time scale.", option);
851 }
852 }
853 if (data->source_file) {
854 LOG_ALLOW(GLOBAL, LOG_INFO, "Face %s: prescribed velocity from %s%s.\n",
855 BCFaceToString(ctx->face_id), data->source_file, data->source.bulk ? ", rescaled to a target" : "");
856 } else {
857 LOG_ALLOW(GLOBAL, LOG_INFO, "Face %s: prescribed velocity from -face_source_%d (%s frame%s%s).\n",
858 BCFaceToString(ctx->face_id), (int)id,
859 data->source.frame == PICURV_SOURCE_FRAME_NORMAL ? "normal" :
860 data->source.frame == PICURV_SOURCE_FRAME_CURVILINEAR ? "curvilinear" : "cartesian",
861 data->source.time_dependent ? ", time-dependent" : "", data->source.bulk ? ", bulk velocity" : "");
862 }
863 if (data->fluctuate) {
864 LOG_ALLOW(GLOBAL, LOG_INFO, "Face %s: synthetic fluctuations, integral lengths %g and %g, time %g (solver units).\n",
865 BCFaceToString(ctx->face_id), (double)data->fluct_length[0], (double)data->fluct_length[1],
866 (double)data->fluct_time);
867 }
869 PetscFunctionReturn(0);
870}
Private data of the prescribed-velocity inlet: a compiled source or a PICSLICE file,...
PetscErrorCode PicurvVelocitySourceCreate(const char *prefix, PetscBool on_face, PetscBool has_data, PetscBool allow_draws, PicurvVelocitySource *source)
Read and compile a velocity source from the options database.
Definition expression.c:872
@ PICURV_SOURCE_FRAME_NORMAL
One value: the speed into the domain through a face.
Definition expression.h:178
@ PICURV_SOURCE_FRAME_CARTESIAN
Three values: x, y, z velocity components.
Definition expression.h:176
@ PICURV_SOURCE_FRAME_CURVILINEAR
Three values along the unit xi, eta, zeta grid-line directions.
Definition expression.h:177
PetscErrorCode GetBCParamReal(BC_Param *params, const char *key, PetscReal *value_out, PetscBool *found)
Searches a BC_Param linked list for a key and returns its value as a double.
Definition io.c:819
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
PetscErrorCode GetBCParamBool(BC_Param *params, const char *key, PetscBool *value_out, PetscBool *found)
Searches a BC_Param linked list for a key and returns its value as a bool.
Definition io.c:836
@ LOG_INFO
Informational messages about program execution.
Definition logging.h:31
Vec InflowFluctuation
Definition variables.h:1194
BC_Param * params
Definition variables.h:429
Here is the call graph for this function:
Here is the caller graph for this function:

◆ PreStep_InletPrescribedVelocity()

static PetscErrorCode PreStep_InletPrescribedVelocity ( BoundaryCondition *  self,
BCContext *  ctx,
PetscReal *  in,
PetscReal *  out 
)
static

Refresh the inlet velocity once per step: gather the slots on the first call, then re-evaluate and rescale only what depends on t.

Definition at line 1266 of file BC_Handlers.c.

1269{
1271 UserCtx *user = ctx->user;
1272 SimCtx *simCtx = user->simCtx;
1273 PetscReal physical_time;
1274
1275 (void)local_inflow_contribution;
1276 (void)local_outflow_contribution;
1277 PetscFunctionBeginUser;
1279 /* Boundary passes repeat within a step (every stage and residual); the velocity is
1280 defined at the step's time, so it is refreshed once. */
1281 if (data->built && data->evaluated_step == simCtx->step) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
1282 const PetscBool first = (PetscBool)!data->built;
1283 if (first) {
1284 Vec fraction, length;
1285 PetscCall(DMCreateGlobalVector(user->fda, &fraction));
1286 PetscCall(DMCreateGlobalVector(user->fda, &length));
1287 PetscCall(ComputeGridLineFractions(user, fraction, length));
1288 PetscCall(PicurvSourceFaceSlotsCreate(user, ctx->face_id, fraction, length, &data->slots));
1289 PetscCall(VecDestroy(&fraction));
1290 PetscCall(VecDestroy(&length));
1291 PetscCall(PetscMalloc1(data->slots.elements.n[0] * data->slots.elements.n[1], &data->velocity));
1292 if (data->source_file) PetscCall(OpenPrescribedProfile(data, user, ctx->face_id));
1293 if (data->fluctuate) PetscCall(BuildInletFluctuation(data, user));
1294 }
1295 const PetscBool frames_vary = (PetscBool)(data->frames > 1);
1296 const PetscBool evaluate = (PetscBool)(first || data->source.time_dependent);
1297 const PetscBool rescale = (PetscBool)(data->source.bulk && (evaluate || frames_vary || data->source.bulk_time_dependent));
1298 PetscCall(PicurvPhysicalTime(simCtx, simCtx->ti, &physical_time));
1299 if (frames_vary) PetscCall(InterpolatePrescribedFrames(data, ctx->face_id, physical_time));
1300 if (evaluate && data->source.count > 0) {
1301 const PetscReal U_ref = simCtx->scaling.U_ref;
1302 const PetscInt nodes[3] = {user->info.mx, user->info.my, user->info.mz};
1303 for (PetscInt s = 0; s < data->slots.elements.n[0] * data->slots.elements.n[1]; ++s) {
1304 const PetscInt p = s % data->slots.elements.n[0], q = s / data->slots.elements.n[0];
1305 const PicurvExpressionDrawKey key = PicurvFaceDrawKey((PetscInt64)simCtx->sourceRandomSeed, user->_this, nodes, ctx->face_id,
1306 data->slots.elements.lo[0] + p - 1, data->slots.elements.lo[1] + q - 1,
1307 (PetscInt64)simCtx->step);
1308 Cmpnts v;
1309 data->slots.values[s][PICURV_SOURCE_VAR_T] = physical_time;
1310 PetscCall(PicurvVelocitySourceEvaluate(&data->source, data->slots.values[s], &key, data->slots.edges[s], &v));
1311 data->velocity[s].x = v.x / U_ref;
1312 data->velocity[s].y = v.y / U_ref;
1313 data->velocity[s].z = v.z / U_ref;
1315 const Cmpnts m = data->slots.edges[s][data->slots.elements.normal];
1316 const PetscReal speed2 = v.x * v.x + v.y * v.y + v.z * v.z;
1317 const PetscReal through = v.x * m.x + v.y * m.y + v.z * m.z;
1318 PetscCheck(through * through <= 2.5e-3 * speed2 * (m.x * m.x + m.y * m.y + m.z * m.z), PETSC_COMM_SELF, PETSC_ERR_USER_INPUT,
1319 "Face %s: a moving wall's velocity must lie along the wall; (%g, %g, %g) passes through it at (%g, %g, %g).",
1320 BCFaceToString(ctx->face_id), (double)v.x, (double)v.y, (double)v.z,
1321 (double)data->slots.values[s][PICURV_SOURCE_VAR_X], (double)data->slots.values[s][PICURV_SOURCE_VAR_Y],
1322 (double)data->slots.values[s][PICURV_SOURCE_VAR_Z]);
1323 }
1324 }
1325 }
1326 data->built = PETSC_TRUE;
1327 if (rescale) PetscCall(PrescribedBulkFactor(data, user, ctx->face_id, physical_time, &data->factor));
1328 if (data->fluctuate) PetscCall(StepInletFluctuation(data, user, ctx->face_id));
1329 data->evaluated_step = simCtx->step;
1331 PetscFunctionReturn(0);
1332}
static PetscErrorCode OpenPrescribedProfile(InletPrescribedVelocityData *data, UserCtx *user, BCFace face_id)
Open the face's PICSLICE and read a lone frame, as the velocity itself or, under expressions,...
static PetscErrorCode StepInletFluctuation(InletPrescribedVelocityData *data, UserCtx *user, BCFace face_id)
This step's synthetic fluctuation at every owned slot of an inlet.
static PetscErrorCode InterpolatePrescribedFrames(InletPrescribedVelocityData *data, BCFace face_id, PetscReal physical_time)
Set the staged data at a time: linear between the two frames around it, the first at t = 0.
static PetscErrorCode BuildInletFluctuation(InletPrescribedVelocityData *data, UserCtx *user)
Prepare an inlet's synthetic fluctuations once its slots exist: filter widths from the face's mean sp...
static PetscErrorCode PrescribedBulkFactor(InletPrescribedVelocityData *data, UserCtx *user, BCFace face_id, PetscReal physical_time, PetscReal *factor)
Factor that makes the face's mean normal speed or flow rate equal the target.
PetscErrorCode ComputeGridLineFractions(UserCtx *user, Vec fraction, Vec length)
Arc-length position of every owned cell centre along its three grid lines.
Definition Metric.c:1362
PetscErrorCode PicurvVelocitySourceEvaluate(const PicurvVelocitySource *source, const PetscReal *values, const PicurvExpressionDrawKey *key, const Cmpnts edges[3], Cmpnts *value)
Evaluate a source at one point.
Definition expression.c:993
@ PICURV_SOURCE_VAR_T
Physical time [s].
Definition expression.h:162
@ PICURV_SOURCE_VAR_Y
Physical y [m].
Definition expression.h:160
@ PICURV_SOURCE_VAR_X
Physical x of the point [m].
Definition expression.h:159
@ PICURV_SOURCE_VAR_Z
Physical z [m].
Definition expression.h:161
static PicurvExpressionDrawKey PicurvFaceDrawKey(PetscInt64 seed, PetscInt block, const PetscInt nodes[3], BCFace face, PetscInt p, PetscInt q, PetscInt64 step)
Draw key of a boundary face cell at one step, the key of a face source's draws.
Definition expression.h:307
PetscErrorCode PicurvSourceFaceSlotsCreate(UserCtx *user, BCFace face_id, Vec fraction, Vec length, PicurvSourceFaceSlots *slots)
Gather each owned slot of a boundary face: face-centre position, the grid-line fractions and lengths ...
What a random draw is keyed on, besides its stream.
Definition expression.h:85
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
dict evaluate(list surfaces, set published)
Classify every surface as current, suspect, or an integrity failure.
SimCtx * simCtx
Back-pointer to the master simulation context.
Definition variables.h:1160
@ BC_HANDLER_WALL_MOVING
Definition variables.h:346
PetscInt _this
Definition variables.h:1175
ScalingCtx scaling
Definition variables.h:1003
PetscInt sourceRandomSeed
Seed of the draws in velocity and pressure sources (-source_random_seed).
Definition variables.h:1051
PetscInt step
Definition variables.h:924
PetscReal ti
Definition variables.h:925
PetscReal U_ref
Definition variables.h:899
The master context for the entire simulation.
Definition variables.h:916
Here is the call graph for this function:
Here is the caller graph for this function:

◆ Apply_InletVelocity()

static PetscErrorCode Apply_InletVelocity ( BoundaryCondition *  self,
BCContext *  ctx 
)
static

Applies the prescribed inlet velocity through the common face-layout path.

Ownership clipping, immersed-cell exclusion, metric projection, Ubcs placement, and the normal staggered Ucont write are ApplyFaceBoundaryVelocity()'s, shared with the walls.

Definition at line 782 of file BC_Handlers.c.

783{
784 PetscFunctionBeginUser;
788 PetscFunctionReturn(0);
789}
static Cmpnts EvaluateInletCartesianVelocity(const BoundaryCondition *self, BCFace face_id, PetscInt i, PetscInt j, PetscInt k, Cmpnts metric, PetscReal sign, Cmpnts interior)
Prescribed velocity at one inlet face slot, as a Cartesian vector.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ PostStep_InletFlux()

static PetscErrorCode PostStep_InletFlux ( BoundaryCondition *  self,
BCContext *  ctx,
PetscReal *  in,
PetscReal *  out 
)
static

Adds the inlet face's applied flux, the sum of its normal Ucont, to the inflow.

Definition at line 362 of file BC_Handlers.c.

365{
366 PetscErrorCode ierr;
367 UserCtx* user = ctx->user;
368 BCFace face_id = ctx->face_id;
369 PetscBool can_service;
370
371 (void)self;
372 (void)local_outflow_contribution;
373
374 PetscFunctionBeginUser;
376
377 DMDALocalInfo *info = &user->info;
378 Cmpnts ***ucont;
379
380 PetscInt IM_nodes_global, JM_nodes_global,KM_nodes_global;
381
382 IM_nodes_global = user->IM;
383 JM_nodes_global = user->JM;
384 KM_nodes_global = user->KM;
385
386 ierr = CanRankServiceFace(info,IM_nodes_global,JM_nodes_global,KM_nodes_global,face_id,&can_service); CHKERRQ(ierr);
387
388
389 if (!can_service) { PROFILE_HELPER_END; PetscFunctionReturn(0); }
390
391 ierr = DMDAVecGetArrayRead(user->fda, user->Ucont, (const Cmpnts***)&ucont); CHKERRQ(ierr);
392
393 PetscReal local_flux = 0.0;
394
395 PetscInt xs = info->xs, xe = info->xs + info->xm;
396 PetscInt ys = info->ys, ye = info->ys + info->ym;
397 PetscInt zs = info->zs, ze = info->zs + info->zm;
398 PetscInt mx = info->mx, my = info->my, mz = info->mz;
399
400 PetscInt lxs = xs, lxe = xe, lys = ys, lye = ye, lzs = zs, lze = ze;
401 if (xs == 0) lxs = xs + 1;
402 if (xe == mx) lxe = xe - 1;
403 if (ys == 0) lys = ys + 1;
404 if (ye == my) lye = ye - 1;
405 if (zs == 0) lzs = zs + 1;
406 if (ze == mz) lze = ze - 1;
407
408 // Sum ucont components
409 switch (face_id) {
410 case BC_FACE_NEG_X:
411 case BC_FACE_POS_X: {
412 PetscInt i = (face_id == BC_FACE_NEG_X) ? xs : mx - 2;
413 for (PetscInt k = lzs; k < lze; k++) {
414 for (PetscInt j = lys; j < lye; j++) {
415 local_flux += ucont[k][j][i].x;
416 }
417 }
418 } break;
419
420 case BC_FACE_NEG_Y:
421 case BC_FACE_POS_Y: {
422 PetscInt j = (face_id == BC_FACE_NEG_Y) ? ys : my - 2;
423 for (PetscInt k = lzs; k < lze; k++) {
424 for (PetscInt i = lxs; i < lxe; i++) {
425 local_flux += ucont[k][j][i].y;
426 }
427 }
428 } break;
429
430 case BC_FACE_NEG_Z:
431 case BC_FACE_POS_Z: {
432 PetscInt k = (face_id == BC_FACE_NEG_Z) ? zs : mz - 2;
433 for (PetscInt j = lys; j < lye; j++) {
434 for (PetscInt i = lxs; i < lxe; i++) {
435 local_flux += ucont[k][j][i].z;
436 }
437 }
438 } break;
439 }
440
441 ierr = DMDAVecRestoreArrayRead(user->fda, user->Ucont, (const Cmpnts***)&ucont); CHKERRQ(ierr);
442
443 *local_inflow_contribution += local_flux;
444
445 LOG_ALLOW(LOCAL, LOG_DEBUG, "PostStep_InletFlux: Face %d, flux = %.6e\n",
446 face_id, local_flux);
447
449 PetscFunctionReturn(0);
450}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ Apply_WallMoving()

static PetscErrorCode Apply_WallMoving ( BoundaryCondition *  self,
BCContext *  ctx 
)
static

Applies a moving wall's velocity through the path every prescribed face shares.

Definition at line 766 of file BC_Handlers.c.

767{
768 PetscFunctionBeginUser;
772 PetscFunctionReturn(0);
773}
static Cmpnts EvaluateMovingWallVelocity(const BoundaryCondition *self, BCFace face_id, PetscInt i, PetscInt j, PetscInt k, Cmpnts metric, PetscReal sign, Cmpnts interior)
A moving wall's boundary velocity: the source's, with any part along the face removed,...
Here is the call graph for this function:
Here is the caller graph for this function:

◆ Destroy_InletPrescribedVelocity()

static PetscErrorCode Destroy_InletPrescribedVelocity ( BoundaryCondition *  self)
static

Release the compiled source and the per-slot arrays.

Definition at line 1335 of file BC_Handlers.c.

1336{
1337 PetscFunctionBeginUser;
1339 if (self && self->data) {
1341 PetscCall(PicurvVelocitySourceDestroy(&data->source));
1342 PetscCall(PetscFree(data->source_file));
1343 if (data->file) PetscCheck(fclose(data->file) == 0, PETSC_COMM_SELF, PETSC_ERR_FILE_READ, "Cannot close a PICSLICE file.");
1344 PetscCall(PetscFree(data->profile));
1345 PetscCall(PetscFree(data->file_values));
1346 PetscCall(PetscFree(data->bracket[0]));
1347 PetscCall(PetscFree(data->bracket[1]));
1348 if (data->built) PetscCall(PicurvSourceFaceSlotsDestroy(&data->slots));
1349 PetscCall(PetscFree(data->velocity));
1350 if (data->fluctuate) {
1351 PetscCall(PicurvVelocitySourceDestroy(&data->stress[0]));
1352 PetscCall(PicurvVelocitySourceDestroy(&data->stress[1]));
1353 PetscCall(PetscFree(data->kernel[0]));
1354 PetscCall(PetscFree(data->kernel[1]));
1355 PetscCall(PetscFree2(data->lund, data->fluct));
1356 }
1357 PetscCall(PetscFree(self->data));
1358 }
1360 PetscFunctionReturn(0);
1361}
PetscErrorCode PicurvVelocitySourceDestroy(PicurvVelocitySource *source)
Free a source's compiled expressions and bulk velocity.
PetscErrorCode PicurvSourceFaceSlotsDestroy(PicurvSourceFaceSlots *slots)
Release what PicurvSourceFaceSlotsCreate() allocated.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ PrescribedSlot()

static PetscInt PrescribedSlot ( const InletPrescribedVelocityData *  data,
PetscInt  i,
PetscInt  j,
PetscInt  k 
)
inlinestatic

Index of the owned slot (i, j, k) in a prescribed-velocity inlet's per-slot arrays.

Definition at line 310 of file BC_Handlers.c.

311{
312 const PetscInt idx[3] = {i, j, k};
313 const PicurvSourceFaceSlots *slots = &data->slots;
314 return (idx[slots->elements.a] - slots->elements.lo[0]) + slots->elements.n[0] * (idx[slots->elements.b] - slots->elements.lo[1]);
315}
PicurvSourceFaceSlots slots
BoundaryFaceElements elements
The owned face elements the slots are.
Definition expression.h:317
What a source reads at each boundary-face slot this rank owns, gathered once.
Definition expression.h:316
PetscInt n[2]
Owned elements along a and b; 0 when this rank does not serve the face.
Definition variables.h:420
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 caller graph for this function:

◆ Create_InletPrescribedVelocity()

PetscErrorCode Create_InletPrescribedVelocity ( BoundaryCondition *  bc)

Implementation of Create_InletPrescribedVelocity().

Configures a BoundaryCondition object as an inlet whose velocity is a configured source: expressions over position, time and grid-line fractions, in the Cartesian, curvilinear or face-normal frame, a PICSLICE file, or a file with expressions added to it, optionally rescaled to a bulk velocity or flow rate, with optional synthetic fluctuations.

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

See also
Create_InletPrescribedVelocity()

Definition at line 323 of file BC_Handlers.c.

324{
325 InletPrescribedVelocityData *data = NULL;
326
327 PetscFunctionBeginUser;
329 PetscCheck(bc, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "BoundaryCondition is NULL");
330 PetscCall(PetscNew(&data));
331 bc->data = (void*)data;
337 bc->UpdateUbcs = NULL;
340 PetscFunctionReturn(0);
341}
static PetscErrorCode Apply_InletVelocity(BoundaryCondition *self, BCContext *ctx)
Applies the prescribed inlet velocity through the common face-layout path.
static PetscErrorCode Initialize_InletPrescribedVelocity(BoundaryCondition *self, BCContext *ctx)
Compile the source named by the face's source_id parameter, with its bulk velocity or flow rate if an...
static PetscErrorCode PostStep_InletFlux(BoundaryCondition *self, BCContext *ctx, PetscReal *in, PetscReal *out)
Adds the inlet face's applied flux, the sum of its normal Ucont, to the inflow.
static PetscErrorCode Destroy_InletPrescribedVelocity(BoundaryCondition *self)
Release the compiled source and the per-slot arrays.
static PetscErrorCode PreStep_InletPrescribedVelocity(BoundaryCondition *self, BCContext *ctx, PetscReal *in, PetscReal *out)
Refresh the inlet velocity once per step: gather the slots on the first call, then re-evaluate and re...
@ BC_PRIORITY_INLET
Definition variables.h:361
Here is the call graph for this function:
Here is the caller graph for this function:

◆ Create_WallMoving()

PetscErrorCode Create_WallMoving ( BoundaryCondition *  bc)

Implementation of Create_WallMoving().

Creates a wall moving along itself at a velocity source, the prescribed inlet's without its flux.

See also
Create_WallMoving()

Definition at line 347 of file BC_Handlers.c.

348{
349 PetscFunctionBeginUser;
351 PetscCall(Create_InletPrescribedVelocity(bc));
354 bc->PostStep = NULL;
356 PetscFunctionReturn(0);
357}
static PetscErrorCode Apply_WallMoving(BoundaryCondition *self, BCContext *ctx)
Applies a moving wall's velocity through the path every prescribed face shares.
PetscErrorCode Create_InletPrescribedVelocity(BoundaryCondition *bc)
Implementation of Create_InletPrescribedVelocity().
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GetProfileFileExpectedDims()

static PetscErrorCode GetProfileFileExpectedDims ( UserCtx *  user,
BCFace  face_id,
PetscInt *  n1,
PetscInt *  n2 
)
static

Computes the expected PICSLICE dimensions for an inlet face.

Parameters
userUser context containing global grid node counts.
face_idBoundary face whose tangential profile dimensions are requested.
[out]n1First PICSLICE dimension in handler storage order.
[out]n2Second PICSLICE dimension in handler storage order.
Returns
PetscErrorCode 0 on success, or a PETSc error for unsupported faces or invalid dimensions.

Definition at line 461 of file BC_Handlers.c.

463{
464 PetscFunctionBeginUser;
466 switch (face_id) {
467 case BC_FACE_NEG_X:
468 case BC_FACE_POS_X:
469 *n1 = user->KM - 1;
470 *n2 = user->JM - 1;
471 break;
472 case BC_FACE_NEG_Y:
473 case BC_FACE_POS_Y:
474 *n1 = user->KM - 1;
475 *n2 = user->IM - 1;
476 break;
477 case BC_FACE_NEG_Z:
478 case BC_FACE_POS_Z:
479 *n1 = user->JM - 1;
480 *n2 = user->IM - 1;
481 break;
482 default:
483 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE,
484 "Unsupported face id %d for inlet profile dimensions.", face_id);
485 }
486 if (*n1 <= 0 || *n2 <= 0) {
487 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG,
488 "Invalid inlet profile dimensions (%" PetscInt_FMT ", %" PetscInt_FMT ") for grid (%" PetscInt_FMT ", %" PetscInt_FMT ", %" PetscInt_FMT ").",
489 *n1, *n2, user->IM, user->JM, user->KM);
490 }
492 PetscFunctionReturn(0);
493}
Here is the caller graph for this function:

◆ OpenPicSlice()

static PetscErrorCode OpenPicSlice ( InletPrescribedVelocityData *  data,
PetscInt  expected_n1,
PetscInt  expected_n2 
)
static

Opens a canonical PICSLICE file and reads its header.

The file holds magic token PICSLICE, a frame count, then a line with the slice dimensions, optionally the components per slot (1, a normal speed, the default, or 3, a Cartesian velocity) and, with several frames, the time between them. Frames follow.

Parameters
dataHandler data; file, first_frame, frames, components, interval and file_n are set.
expected_n1Expected first slice dimension.
expected_n2Expected second slice dimension.
Returns
PetscErrorCode 0 on success, or a PETSc file/validation error on malformed input.

Definition at line 508 of file BC_Handlers.c.

509{
510 const char *source_file = data->source_file;
511 FILE *fd = NULL;
512 char magic[32] = {0}, line[256] = {0};
513 PetscInt frame_count = 0, n1 = 0, n2 = 0;
514 PetscInt components = 1;
515 double interval = 0.0;
516
517 PetscFunctionBeginUser;
519 fd = fopen(source_file, "r");
520 if (!fd) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_OPEN,
521 "Cannot open PICSLICE inlet profile file: %s", source_file);
522
523 if (fscanf(fd, "%31s", magic) != 1 || strcmp(magic, "PICSLICE") != 0) {
524 fclose(fd);
525 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_READ,
526 "PICSLICE inlet profile file %s must begin with PICSLICE header.", source_file);
527 }
528 if (fscanf(fd, "%" PetscInt_FMT " ", &frame_count) != 1) {
529 fclose(fd);
530 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_READ,
531 "PICSLICE inlet profile file %s missing frame count.", source_file);
532 }
533 if (!fgets(line, sizeof(line), fd) ||
534 sscanf(line, "%" PetscInt_FMT " %" PetscInt_FMT " %" PetscInt_FMT " %le", &n1, &n2, &components, &interval) < 2) {
535 fclose(fd);
536 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_READ,
537 "PICSLICE inlet profile file %s missing slice dimensions.", source_file);
538 }
539 if (n1 != expected_n1 || n2 != expected_n2) {
540 fclose(fd);
541 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_UNEXPECTED,
542 "PICSLICE inlet profile dimensions mismatch for %s: expected (%" PetscInt_FMT ", %" PetscInt_FMT "), found (%" PetscInt_FMT ", %" PetscInt_FMT ").",
543 source_file, expected_n1, expected_n2, n1, n2);
544 }
545 if (frame_count < 1 || (components != 1 && components != 3) || (frame_count > 1 && !(interval > 0.0))) {
546 fclose(fd);
547 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_UNEXPECTED,
548 "PICSLICE inlet profile file %s has %" PetscInt_FMT " frames of %" PetscInt_FMT " components, %g apart; "
549 "it needs at least one frame, 1 or 3 components, and a positive interval between several frames.",
550 source_file, frame_count, components, interval);
551 }
552 if (fgetpos(fd, &data->first_frame) != 0) {
553 fclose(fd);
554 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_READ, "Cannot record a position in %s.", source_file);
555 }
556 data->file = fd;
557 data->frames = frame_count;
558 data->components = components;
559 data->interval = interval;
560 data->file_n[0] = n1;
561 data->file_n[1] = n2;
563 PetscFunctionReturn(0);
564}
Here is the caller graph for this function:

◆ ReadPicSliceFrame()

static PetscErrorCode ReadPicSliceFrame ( InletPrescribedVelocityData *  data)
static

Reads the frame at the file's position into file_values, validating every value: finite, and a normal speed nonnegative.

After the last frame the file must end.

Parameters
dataHandler data with an open file.
Returns
PetscErrorCode 0 on success, or a PETSc file/validation error on malformed input.

Definition at line 572 of file BC_Handlers.c.

573{
574 const PetscInt count = data->file_n[0] * data->file_n[1] * data->components;
575
576 PetscFunctionBeginUser;
578 for (PetscInt idx = 0; idx < count; idx++) {
579 PetscReal value = 0.0;
580 if (fscanf(data->file, "%le", &value) != 1) {
581 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_READ,
582 "PICSLICE inlet profile file %s ended early in frame %" PetscInt_FMT ": expected %" PetscInt_FMT " values.",
583 data->source_file, data->next_frame, count);
584 }
585 if (PetscIsInfOrNanReal(value) || (data->components == 1 && value < 0.0)) {
586 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_UNEXPECTED,
587 "PICSLICE inlet profile file %s contains invalid speed %.6e at flat index %" PetscInt_FMT ".",
588 data->source_file, (double)value, idx);
589 }
590 data->file_values[idx] = value;
591 }
592 data->next_frame++;
593 if (data->next_frame == data->frames) {
594 char extra[64];
595 if (fscanf(data->file, "%63s", extra) == 1) {
596 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_UNEXPECTED,
597 "PICSLICE inlet profile file %s has extra token after %" PetscInt_FMT " frames of %" PetscInt_FMT " values: %s",
598 data->source_file, data->frames, count, extra);
599 }
600 }
602 PetscFunctionReturn(0);
603}
Here is the caller graph for this function:

◆ EvaluateInletCartesianVelocity()

static Cmpnts EvaluateInletCartesianVelocity ( const BoundaryCondition *  self,
BCFace  face_id,
PetscInt  i,
PetscInt  j,
PetscInt  k,
Cmpnts  metric,
PetscReal  sign,
Cmpnts  interior 
)
inlinestatic

Prescribed velocity at one inlet face slot, as a Cartesian vector.

A normal-frame source stores its speed in .x; it is lifted onto the signed unit face normal. Other frames store the Cartesian velocity. Both carry the bulk factor.

Definition at line 610 of file BC_Handlers.c.

614{
615 (void)interior;
617 Cmpnts velocity = {0.0, 0.0, 0.0};
618 if (!data->built) return velocity;
619 const Cmpnts v = data->velocity[PrescribedSlot(data, i, j, k)];
620 const Cmpnts staged = data->profile ? data->profile[PrescribedSlot(data, i, j, k)] : velocity;
621 /* Fluctuations follow the bulk factor, which rescales only the mean. */
622 const Cmpnts fluct = data->fluct ? data->fluct[PrescribedSlot(data, i, j, k)] : velocity;
623 if (data->source.frame != PICURV_SOURCE_FRAME_NORMAL) {
624 velocity.x = data->factor * v.x + staged.x + fluct.x;
625 velocity.y = data->factor * v.y + staged.y + fluct.y;
626 velocity.z = data->factor * v.z + staged.z + fluct.z;
627 return velocity;
628 }
629 const PetscReal area = sqrt(metric.x * metric.x + metric.y * metric.y + metric.z * metric.z);
630 if (area <= 0.0) return velocity;
631 const PetscReal speed = data->factor * v.x + staged.x;
632 velocity.x = sign * speed * metric.x / area + fluct.x;
633 velocity.y = sign * speed * metric.y / area + fluct.y;
634 velocity.z = sign * speed * metric.z / area + fluct.z;
635 return velocity;
636}
static PetscInt PrescribedSlot(const InletPrescribedVelocityData *data, PetscInt i, PetscInt j, PetscInt k)
Index of the owned slot (i, j, k) in a prescribed-velocity inlet's per-slot arrays.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ EvaluateMovingWallVelocity()

static Cmpnts EvaluateMovingWallVelocity ( const BoundaryCondition *  self,
BCFace  face_id,
PetscInt  i,
PetscInt  j,
PetscInt  k,
Cmpnts  metric,
PetscReal  sign,
Cmpnts  interior 
)
inlinestatic

A moving wall's boundary velocity: the source's, with any part along the face removed, since a wall closes its face.

PreStep refuses a source with more than a rounding of the surface's facets through it.

Definition at line 759 of file BC_Handlers.c.

761{
762 return RemoveFaceNormalComponent(EvaluateInletCartesianVelocity(self, face_id, i, j, k, metric, sign, interior), metric);
763}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ PrescribedFaceSums()

static PetscErrorCode PrescribedFaceSums ( const InletPrescribedVelocityData *  data,
UserCtx *  user,
BCFace  face_id,
PetscReal  local[4] 
)
static

This rank's area-weighted sums over the face, physical: the source's normal speed, the staged data's when expressions add to it, the area, and the synthetic fluctuations' inflow (zero without them).

Slots blanked by an immersed body are excluded, as in Apply. The first three are what the bulk rescaling reads; the fluctuations are added after it.

Definition at line 878 of file BC_Handlers.c.

879{
880 const PicurvSourceFaceSlots *slots = &data->slots;
881 const PetscInt normal = slots->elements.normal, a = slots->elements.a, b = slots->elements.b;
882 const PetscBool negative = (PetscBool)((PetscInt)face_id % 2 == 0);
883 const PetscReal sign = negative ? 1.0 : -1.0, U_ref = user->simCtx->scaling.U_ref;
884 const PetscReal L_ref = user->simCtx->scaling.L_ref;
885
886 PetscFunctionBeginUser;
888 local[0] = local[1] = local[2] = local[3] = 0.0;
889 if (slots->elements.n[0] * slots->elements.n[1] > 0) {
890 const PetscInt slot = slots->elements.layer;
891 const PetscInt cell = negative ? slot + 1 : slot;
892 const Cmpnts ***metric_arr;
893 const PetscReal ***nvert;
894 Vec metric_vec = (normal == 0) ? user->lCsi : (normal == 1) ? user->lEta : user->lZet;
895 PetscCall(DMDAVecGetArrayRead(user->fda, metric_vec, &metric_arr));
896 PetscCall(DMDAVecGetArrayRead(user->da, user->lNvert, &nvert));
897 for (PetscInt q = 0; q < slots->elements.n[1]; ++q)
898 for (PetscInt p = 0; p < slots->elements.n[0]; ++p) {
899 PetscInt s_idx[3], c_idx[3];
900 s_idx[normal] = slot; s_idx[a] = slots->elements.lo[0] + p; s_idx[b] = slots->elements.lo[1] + q;
901 c_idx[normal] = cell; c_idx[a] = s_idx[a]; c_idx[b] = s_idx[b];
902 if (nvert[c_idx[2]][c_idx[1]][c_idx[0]] > 0.1) continue;
903 const Cmpnts m = metric_arr[s_idx[2]][s_idx[1]][s_idx[0]];
904 const Cmpnts v = data->velocity[p + slots->elements.n[0] * q];
905 const PetscReal area = PetscSqrtReal(m.x * m.x + m.y * m.y + m.z * m.z);
906 const PetscReal physical = U_ref * L_ref * L_ref;
907 local[0] += physical * ((data->source.frame == PICURV_SOURCE_FRAME_NORMAL)
908 ? v.x * area : sign * (v.x * m.x + v.y * m.y + v.z * m.z));
909 if (data->profile) {
910 const Cmpnts staged = data->profile[p + slots->elements.n[0] * q];
911 local[1] += physical * ((data->source.frame == PICURV_SOURCE_FRAME_NORMAL)
912 ? staged.x * area : sign * (staged.x * m.x + staged.y * m.y + staged.z * m.z));
913 }
914 local[2] += L_ref * L_ref * area;
915 /* Fluctuations are Cartesian in every frame (Apply adds them to the velocity). */
916 if (data->fluct) {
917 const Cmpnts f = data->fluct[p + slots->elements.n[0] * q];
918 local[3] += physical * sign * (f.x * m.x + f.y * m.y + f.z * m.z);
919 }
920 }
921 PetscCall(DMDAVecRestoreArrayRead(user->da, user->lNvert, &nvert));
922 PetscCall(DMDAVecRestoreArrayRead(user->fda, metric_vec, &metric_arr));
923 }
925 PetscFunctionReturn(0);
926}
PicurvVelocitySource source
PicurvSourceFrame frame
Definition expression.h:188
PetscReal L_ref
Definition variables.h:898
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
Here is the caller graph for this function:

◆ PrescribedBulkFactor()

static PetscErrorCode PrescribedBulkFactor ( InletPrescribedVelocityData *  data,
UserCtx *  user,
BCFace  face_id,
PetscReal  physical_time,
PetscReal *  factor 
)
static

Factor that makes the face's mean normal speed or flow rate equal the target.

Collective.

Definition at line 931 of file BC_Handlers.c.

933{
934 PetscReal local[4];
935 char where[32];
936
937 PetscFunctionBeginUser;
939 PetscCall(PrescribedFaceSums(data, user, face_id, local));
940 PetscCall(PetscSNPrintf(where, sizeof(where), "Face %s", BCFaceToString(face_id)));
941 PetscCall(PicurvVelocitySourceBulkFactor(&data->source, physical_time, local, where, factor));
943 PetscFunctionReturn(0);
944}
static PetscErrorCode PrescribedFaceSums(const InletPrescribedVelocityData *data, UserCtx *user, BCFace face_id, PetscReal local[4])
This rank's area-weighted sums over the face, physical: the source's normal speed,...
PetscErrorCode PicurvVelocitySourceBulkFactor(const PicurvVelocitySource *source, PetscReal physical_time, const PetscReal local[3], const char *where, PetscReal *factor)
Factor on a source's expressions that makes a target's whole mean equal its bulk velocity.
Definition expression.c:947
Here is the call graph for this function:
Here is the caller graph for this function:

◆ LoadPrescribedFrame()

static PetscErrorCode LoadPrescribedFrame ( InletPrescribedVelocityData *  data,
PetscInt  frame,
Cmpnts *  target 
)
static

Read one frame of the face's PICSLICE into this rank's slots, moving the file there.

Every rank reads the file, so a malformed one fails on all of them.

Parameters
dataHandler data with an open file.
frameFrame to read.
targetVelocity per owned slot; a normal speed goes in x.

Definition at line 953 of file BC_Handlers.c.

954{
955 const PicurvSourceFaceSlots *slots = &data->slots;
956 const PetscInt n2 = data->file_n[1], components = data->components;
957
958 PetscFunctionBeginUser;
960 if (frame < data->next_frame) {
961 PetscCheck(fsetpos(data->file, &data->first_frame) == 0, PETSC_COMM_SELF, PETSC_ERR_FILE_READ,
962 "Cannot return to the first frame of %s.", data->source_file);
963 data->next_frame = 0;
964 }
965 while (data->next_frame <= frame) PetscCall(ReadPicSliceFrame(data));
966 /* A PICSLICE row runs along the face's first tangential axis; rows step along the second. */
967 for (PetscInt q = 0; q < slots->elements.n[1]; ++q)
968 for (PetscInt p = 0; p < slots->elements.n[0]; ++p) {
969 const PetscReal *value = &data->file_values[components * ((slots->elements.lo[1] + q - 1) * n2 + (slots->elements.lo[0] + p - 1))];
970 Cmpnts *v = &target[p + slots->elements.n[0] * q];
971 v->x = value[0];
972 v->y = (components == 3) ? value[1] : 0.0;
973 v->z = (components == 3) ? value[2] : 0.0;
974 }
976 PetscFunctionReturn(0);
977}
static PetscErrorCode ReadPicSliceFrame(InletPrescribedVelocityData *data)
Reads the frame at the file's position into file_values, validating every value: finite,...
Here is the call graph for this function:
Here is the caller graph for this function:

◆ OpenPrescribedProfile()

static PetscErrorCode OpenPrescribedProfile ( InletPrescribedVelocityData *  data,
UserCtx *  user,
BCFace  face_id 
)
static

Open the face's PICSLICE and read a lone frame, as the velocity itself or, under expressions, as what they add to; several frames are read as time reaches them.

Definition at line 983 of file BC_Handlers.c.

984{
985 const PetscInt n_slots = data->slots.elements.n[0] * data->slots.elements.n[1];
986 const PetscBool normal = (PetscBool)(data->source.frame == PICURV_SOURCE_FRAME_NORMAL);
987 PetscInt n1 = 0, n2 = 0;
988
989 PetscFunctionBeginUser;
991 PetscCall(GetProfileFileExpectedDims(user, face_id, &n1, &n2));
992 PetscCall(OpenPicSlice(data, n1, n2));
993 PetscCheck(data->components == (normal ? 1 : 3), PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT,
994 "Face %s: %s holds %" PetscInt_FMT " component(s) per slot, but the source is in the %s frame.",
995 BCFaceToString(face_id), data->source_file, data->components, normal ? "normal" : "cartesian");
996 if (data->source.count > 0) PetscCall(PetscCalloc1(n_slots, &data->profile));
997 PetscCall(PetscMalloc1(n1 * n2 * data->components, &data->file_values));
998 if (data->frames == 1) {
999 PetscCall(LoadPrescribedFrame(data, 0, data->profile ? data->profile : data->velocity));
1000 PetscCheck(fclose(data->file) == 0, PETSC_COMM_SELF, PETSC_ERR_FILE_READ, "Cannot close %s.", data->source_file);
1001 data->file = NULL;
1002 } else {
1003 /* Two allocations: the brackets swap as time advances, so neither stays the first of a pair. */
1004 PetscCall(PetscMalloc1(n_slots, &data->bracket[0]));
1005 PetscCall(PetscMalloc1(n_slots, &data->bracket[1]));
1006 data->bracket_frame[0] = data->bracket_frame[1] = -1;
1007 }
1008 LOG_ALLOW(GLOBAL, LOG_INFO, "Face %s: PICSLICE %s, %" PetscInt_FMT " x %" PetscInt_FMT ", %" PetscInt_FMT " component(s), %" PetscInt_FMT " frame(s).\n",
1009 BCFaceToString(face_id), data->source_file, n1, n2, data->components, data->frames);
1011 PetscFunctionReturn(0);
1012}
static PetscErrorCode GetProfileFileExpectedDims(UserCtx *user, BCFace face_id, PetscInt *n1, PetscInt *n2)
Computes the expected PICSLICE dimensions for an inlet face.
static PetscErrorCode LoadPrescribedFrame(InletPrescribedVelocityData *data, PetscInt frame, Cmpnts *target)
Read one frame of the face's PICSLICE into this rank's slots, moving the file there.
static PetscErrorCode OpenPicSlice(InletPrescribedVelocityData *data, PetscInt expected_n1, PetscInt expected_n2)
Opens a canonical PICSLICE file and reads its header.
PetscInt count
1 for the normal frame, otherwise 3; 0 for staged data alone.
Definition expression.h:189
Here is the call graph for this function:
Here is the caller graph for this function:

◆ InterpolatePrescribedFrames()

static PetscErrorCode InterpolatePrescribedFrames ( InletPrescribedVelocityData *  data,
BCFace  face_id,
PetscReal  physical_time 
)
static

Set the staged data at a time: linear between the two frames around it, the first at t = 0.

Definition at line 1017 of file BC_Handlers.c.

1018{
1019 const PetscInt n_slots = data->slots.elements.n[0] * data->slots.elements.n[1];
1020 const PetscReal position = physical_time / data->interval;
1021 PetscInt frame[2] = {(PetscInt)PetscFloorReal(position), 0};
1022 PetscReal weight = position - PetscFloorReal(position);
1023 Cmpnts *out = data->profile ? data->profile : data->velocity;
1024
1025 PetscFunctionBeginUser;
1027 if (data->repeat) {
1028 frame[0] = frame[0] % data->frames;
1029 frame[1] = (frame[0] + 1) % data->frames;
1030 } else {
1031 /* A time step landing on the last frame may round just past it. */
1032 if (frame[0] == data->frames - 1 && weight < 1.0e-9) { frame[0] = data->frames - 2; weight = 1.0; }
1033 PetscCheck(frame[0] < data->frames - 1 && frame[0] >= 0, PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT,
1034 "Face %s: time %g is past the %" PetscInt_FMT " frames of %s, %g s apart. Set repeat: true to loop them.",
1035 BCFaceToString(face_id), (double)physical_time, data->frames, data->source_file, (double)data->interval);
1036 frame[1] = frame[0] + 1;
1037 }
1038 for (PetscInt f = 0; f < 2; ++f) {
1039 if (data->bracket_frame[f] == frame[f]) continue;
1040 if (data->bracket_frame[1 - f] == frame[f]) {
1041 /* The later frame of the last interval is the earlier one of this. */
1042 Cmpnts *kept = data->bracket[1 - f];
1043 data->bracket[1 - f] = data->bracket[f];
1044 data->bracket[f] = kept;
1045 data->bracket_frame[1 - f] = data->bracket_frame[f];
1046 data->bracket_frame[f] = frame[f];
1047 continue;
1048 }
1049 PetscCall(LoadPrescribedFrame(data, frame[f], data->bracket[f]));
1050 data->bracket_frame[f] = frame[f];
1051 }
1052 for (PetscInt s = 0; s < n_slots; ++s) {
1053 out[s].x = (1.0 - weight) * data->bracket[0][s].x + weight * data->bracket[1][s].x;
1054 out[s].y = (1.0 - weight) * data->bracket[0][s].y + weight * data->bracket[1][s].y;
1055 out[s].z = (1.0 - weight) * data->bracket[0][s].z + weight * data->bracket[1][s].z;
1056 }
1058 PetscFunctionReturn(0);
1059}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ LogPrescribedFlowDiagnostics()

PetscErrorCode LogPrescribedFlowDiagnostics ( UserCtx *  user)

Implementation of LogPrescribedFlowDiagnostics().

Appends each prescribed-velocity inlet's flow rate and mean normal speed this step to inlet_flow.csv.

See also
LogPrescribedFlowDiagnostics()

Definition at line 1065 of file BC_Handlers.c.

1066{
1067 SimCtx *simCtx = user->simCtx;
1068
1069 PetscFunctionBeginUser;
1071 for (PetscInt face = 0; face < 6; ++face) {
1072 const BoundaryCondition *handler = user->boundary_faces[face].handler;
1073 PetscReal local[4], global[4], physical_time, flow_rate;
1074 FILE *file = NULL;
1075
1076 if (!handler || user->boundary_faces[face].handler_type != BC_HANDLER_INLET_PRESCRIBED_VELOCITY) continue;
1077 const InletPrescribedVelocityData *data = (const InletPrescribedVelocityData*)handler->data;
1078 if (!data->built) continue;
1079 PetscCall(PrescribedFaceSums(data, user, (BCFace)face, local));
1080 PetscCallMPI(MPI_Allreduce(local, global, 4, MPIU_REAL, MPI_SUM, PETSC_COMM_WORLD));
1081 if (simCtx->rank != 0 || user->_this != 0) continue;
1082 PetscCall(PicurvPhysicalTime(simCtx, simCtx->ti, &physical_time));
1083 flow_rate = data->factor * global[0] + global[1];
1084 PetscCall(PicurvOpenDiagnosticsCsv(simCtx, simCtx->analysis_dir, "inlet_flow.csv",
1085 "step,physical_time,face,area,flow_rate,mean_normal_speed,bulk_factor,"
1086 "fluctuation_flow_rate,applied_flow_rate",
1087 &file));
1088 /* flow_rate is the rescaled profile's, the one a bulk target controls; the synthetic
1089 fluctuations are added after the rescaling, so the flux the face actually admits is
1090 their sum. */
1091 fprintf(file, "%d,%.10e,%s,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e\n", (int)simCtx->step, (double)physical_time,
1092 BCFaceToString((BCFace)face), (double)global[2], (double)flow_rate,
1093 (double)(global[2] > 0.0 ? flow_rate / global[2] : 0.0), (double)data->factor,
1094 (double)global[3], (double)(flow_rate + global[3]));
1095 PetscCheck(fclose(file) == 0, PETSC_COMM_SELF, PETSC_ERR_FILE_WRITE, "Unable to close the inlet-flow diagnostics file.");
1096 }
1098 PetscFunctionReturn(0);
1099}
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
The "virtual table" struct for a boundary condition handler object.
Definition variables.h:389
PetscMPIInt rank
Definition variables.h:919
@ BC_HANDLER_INLET_PRESCRIBED_VELOCITY
Definition variables.h:348
char analysis_dir[PETSC_MAX_PATH_LEN]
Definition variables.h:942
BoundaryCondition * handler
Definition variables.h:430
Here is the call graph for this function:
Here is the caller graph for this function:

◆ BuildInletFluctuation()

static PetscErrorCode BuildInletFluctuation ( InletPrescribedVelocityData *  data,
UserCtx *  user 
)
static

Prepare an inlet's synthetic fluctuations once its slots exist: filter widths from the face's mean spacing, and the Reynolds stresses' Cholesky factor at each slot.

Collective over the block. The integral length L along a tangential axis spans n = L / h cells, h the face's cell width along it: the mean of its widest and narrowest cell there. The filter weights are exp(-pi |k| / n) for |k| <= 2n, scaled to a unit sum of squares (Xie & Castro 2008), so filtered unit-variance noise keeps unit variance. Every rank and every decomposition uses the same h, so the kernel is bitwise the same.

Definition at line 1114 of file BC_Handlers.c.

1115{
1116 PicurvSourceFaceSlots *slots = &data->slots;
1117 const PetscInt count = slots->elements.n[0] * slots->elements.n[1];
1118 const PetscInt tangential[2] = {slots->elements.a, slots->elements.b};
1119 const PetscReal U2 = user->simCtx->scaling.U_ref * user->simCtx->scaling.U_ref;
1120 /* Widest and narrowest cell along each axis, as {max0, max1, -min0, -min1}. Each width comes
1121 from its own cell's metrics and a maximum is exact in any order, so every decomposition
1122 builds the same kernel; a line length is summed across the ranks it crosses, and is not. */
1123 PetscReal extent[4] = {0.0, 0.0, -PETSC_MAX_REAL, -PETSC_MAX_REAL};
1124
1125 PetscFunctionBeginUser;
1127 for (PetscInt s = 0; s < count; ++s) {
1128 for (PetscInt d = 0; d < 2; ++d) {
1129 const Cmpnts e = data->slots.edges[s][tangential[d]];
1130 const PetscReal width = PetscSqrtReal(e.x * e.x + e.y * e.y + e.z * e.z);
1131 extent[d] = PetscMax(extent[d], width);
1132 extent[2 + d] = PetscMax(extent[2 + d], -width);
1133 }
1134 }
1135 PetscCallMPI(MPI_Allreduce(MPI_IN_PLACE, extent, 4, MPIU_REAL, MPI_MAX, PETSC_COMM_WORLD));
1136 for (PetscInt d = 0; d < 2; ++d) {
1137 const PetscReal h = 0.5 * (extent[d] - extent[2 + d]);
1138 const PetscReal n = data->fluct_length[d] / h;
1139 PetscReal norm = 0.0;
1140 data->half[d] = PetscMax(1, (PetscInt)PetscCeilReal(2.0 * n));
1141 PetscCheck(data->half[d] <= INFLOW_LATTICE_PAD, PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT,
1142 "An inlet's fluctuation length spans %g cells, beyond the %d its draws can reach.",
1143 (double)n, INFLOW_LATTICE_PAD / 2);
1144 PetscCall(PetscMalloc1(2 * data->half[d] + 1, &data->kernel[d]));
1145 for (PetscInt k = -data->half[d]; k <= data->half[d]; ++k) {
1146 data->kernel[d][k + data->half[d]] = PetscExpReal(-PETSC_PI * PetscAbsReal((PetscReal)k) / n);
1147 norm += data->kernel[d][k + data->half[d]] * data->kernel[d][k + data->half[d]];
1148 }
1149 for (PetscInt k = 0; k <= 2 * data->half[d]; ++k) data->kernel[d][k] /= PetscSqrtReal(norm);
1150 }
1151 PetscCall(PetscMalloc2(count, &data->lund, count, &data->fluct));
1152 for (PetscInt s = 0; s < count; ++s) {
1153 Cmpnts diag, cross;
1154 PetscCall(PicurvVelocitySourceEvaluate(&data->stress[0], data->slots.values[s], NULL, data->slots.edges[s], &diag));
1155 PetscCall(PicurvVelocitySourceEvaluate(&data->stress[1], data->slots.values[s], NULL, data->slots.edges[s], &cross));
1156 /* Lund, Wu & Squires (1998): u' = A psi with A A^T = R. A stress tensor that is not
1157 positive definite, such as zero at a wall, leaves the rows it cannot fill at zero. */
1158 PetscReal *a = data->lund[s];
1159 a[0] = PetscSqrtReal(PetscMax(diag.x / U2, 0.0));
1160 a[1] = (a[0] > 0.0) ? cross.x / U2 / a[0] : 0.0;
1161 a[2] = PetscSqrtReal(PetscMax(diag.y / U2 - a[1] * a[1], 0.0));
1162 a[3] = (a[0] > 0.0) ? cross.y / U2 / a[0] : 0.0;
1163 a[4] = (a[2] > 0.0) ? (cross.z / U2 - a[1] * a[3]) / a[2] : 0.0;
1164 a[5] = PetscSqrtReal(PetscMax(diag.z / U2 - a[3] * a[3] - a[4] * a[4], 0.0));
1165 data->fluct[s].x = data->fluct[s].y = data->fluct[s].z = 0.0;
1166 }
1168 PetscFunctionReturn(0);
1169}
PicurvVelocitySource stress[2]
#define INFLOW_LATTICE_PAD
Face cells the synthetic-inflow draw lattice extends beyond each edge; a filter half-width may not ex...
PetscReal(* values)[PICURV_SOURCE_VAR_COUNT]
Variables per slot; t is the caller's.
Definition expression.h:318
Cmpnts(* edges)[3]
Directions per slot, for the curvilinear frame.
Definition expression.h:319
Here is the call graph for this function:
Here is the caller graph for this function:

◆ StepInletFluctuation()

static PetscErrorCode StepInletFluctuation ( InletPrescribedVelocityData *  data,
UserCtx *  user,
BCFace  face_id 
)
static

This step's synthetic fluctuation at every owned slot of an inlet.

Keyed unit normals on the owned face cells and a halo of the filter's half-width are filtered along each tangential axis; a draw is a pure function of the seed, block, component, face cell and step, so a rank computes its halo itself and the result does not depend on the decomposition. A periodic tangential axis wraps the halo. The time filter psi <- psi exp(-pi dt / 2T) + filtered sqrt(1 - exp(-pi dt / T)) keeps unit variance; its state lives in the inlet's dummy plane of InflowFluctuation, which a checkpoint carries, and starts from the filtered noise when there is none. A restored state belongs to the restart step already, so the first pass after it only reads it.

Definition at line 1182 of file BC_Handlers.c.

1183{
1184 SimCtx *simCtx = user->simCtx;
1185 const PicurvSourceFaceSlots *slots = &data->slots;
1186 const PetscInt n0 = slots->elements.n[0], n1 = slots->elements.n[1], h0 = data->half[0], h1 = data->half[1];
1187 const PetscInt w0 = n0 + 2 * h0, w1 = n1 + 2 * h1;
1188 const PetscInt nodes[3] = {user->info.mx, user->info.my, user->info.mz};
1189 const PetscInt cells[2] = {nodes[slots->elements.a] - 2, nodes[slots->elements.b] - 2};
1190 PetscBool axes_periodic[3];
1191 GetPeriodicAxes(simCtx, axes_periodic);
1192 const PetscBool periodic[2] = {axes_periodic[slots->elements.a], axes_periodic[slots->elements.b]};
1193 const PetscBool negative = (PetscBool)((PetscInt)face_id % 2 == 0);
1194 const PetscReal decay = PetscExpReal(-PETSC_PI * simCtx->dt / (2.0 * data->fluct_time));
1195 const PetscReal gain = PetscSqrtReal(1.0 - decay * decay);
1196 const PetscBool fresh = (PetscBool)(!data->fluct_started && !simCtx->inflowFluctuationsRestored);
1197 /* A restored state is already this step's: the checkpoint was written after its update. */
1198 const PetscBool restored = (PetscBool)(!data->fluct_started && simCtx->inflowFluctuationsRestored);
1199 PetscReal *noise = NULL, *rows = NULL, *psi = NULL;
1200 Cmpnts ***state = NULL;
1201
1202 PetscFunctionBeginUser;
1204 if (n0 * n1 > 0) {
1205 PetscCall(PetscMalloc3(w0 * w1, &noise, n0 * w1, &rows, 3 * n0 * n1, &psi));
1206 for (PetscInt c = 0; c < 3 && !restored; ++c) {
1207 for (PetscInt qq = 0; qq < w1; ++qq) {
1208 for (PetscInt pp = 0; pp < w0; ++pp) {
1209 PetscInt g[2] = {slots->elements.lo[0] - 1 - h0 + pp, slots->elements.lo[1] - 1 - h1 + qq};
1210 for (PetscInt d = 0; d < 2; ++d) if (periodic[d]) g[d] = ((g[d] % cells[d]) + cells[d]) % cells[d];
1211 /* A face cell, or one of its halo beyond a closed edge, on a lattice padded by a fixed
1212 width, so a draw does not depend on the filter's half-widths. */
1213 const PetscInt64 id = ((PetscInt64)face_id * (cells[1] + 2 * INFLOW_LATTICE_PAD) + (g[1] + INFLOW_LATTICE_PAD))
1214 * (cells[0] + 2 * INFLOW_LATTICE_PAD) + (g[0] + INFLOW_LATTICE_PAD);
1215 noise[pp + w0 * qq] = PicurvNormalFromHash(PicurvDrawHash((PetscInt64)simCtx->sourceRandomSeed,
1217 (uint64_t)(3 * user->_this + c), id,
1218 (PetscInt64)simCtx->step));
1219 }
1220 }
1221 for (PetscInt qq = 0; qq < w1; ++qq) {
1222 for (PetscInt p = 0; p < n0; ++p) {
1223 PetscReal sum = 0.0;
1224 for (PetscInt k = 0; k <= 2 * h0; ++k) sum += data->kernel[0][k] * noise[(p + k) + w0 * qq];
1225 rows[p + n0 * qq] = sum;
1226 }
1227 }
1228 for (PetscInt q = 0; q < n1; ++q) {
1229 for (PetscInt p = 0; p < n0; ++p) {
1230 PetscReal sum = 0.0;
1231 for (PetscInt k = 0; k <= 2 * h1; ++k) sum += data->kernel[1][k] * rows[p + n0 * (q + k)];
1232 psi[3 * (p + n0 * q) + c] = sum;
1233 }
1234 }
1235 }
1236 PetscCall(DMDAVecGetArray(user->fda, user->InflowFluctuation, &state));
1237 for (PetscInt q = 0; q < n1; ++q) {
1238 for (PetscInt p = 0; p < n0; ++p) {
1239 const PetscInt s = p + n0 * q;
1240 PetscInt idx[3];
1241 idx[slots->elements.normal] = negative ? 0 : nodes[slots->elements.normal] - 1;
1242 idx[slots->elements.a] = slots->elements.lo[0] + p;
1243 idx[slots->elements.b] = slots->elements.lo[1] + q;
1244 Cmpnts *st = &state[idx[2]][idx[1]][idx[0]];
1245 const PetscReal *f = &psi[3 * s];
1246 if (fresh) { st->x = f[0]; st->y = f[1]; st->z = f[2]; }
1247 else if (!restored) { st->x = decay * st->x + gain * f[0]; st->y = decay * st->y + gain * f[1]; st->z = decay * st->z + gain * f[2]; }
1248 const PetscReal *a = data->lund[s];
1249 data->fluct[s].x = a[0] * st->x;
1250 data->fluct[s].y = a[1] * st->x + a[2] * st->y;
1251 data->fluct[s].z = a[3] * st->x + a[4] * st->y + a[5] * st->z;
1252 }
1253 }
1254 PetscCall(DMDAVecRestoreArray(user->fda, user->InflowFluctuation, &state));
1255 PetscCall(PetscFree3(noise, rows, psi));
1256 }
1257 data->fluct_started = PETSC_TRUE;
1259 PetscFunctionReturn(0);
1260}
PetscReal PicurvNormalFromHash(uint64_t hash)
A standard normal deviate from a hash: the first of PicurvNormalPairFromHash()'s pair.
Definition expression.c:655
uint64_t PicurvDrawHash(PetscInt64 seed, PicurvDrawSpace space, uint64_t stream, PetscInt64 id, PetscInt64 salt)
Hash that keys a draw: a pure function of its arguments, so a draw does not depend on the rank that m...
Definition expression.c:610
@ PICURV_DRAW_SPACE_INFLOW
Synthetic inflow noise: stream per block and component, salt the step.
Definition expression.h:37
static void GetPeriodicAxes(const SimCtx *simCtx, PetscBool periodic[3])
Which grid axes are periodic.
Definition setup.h:361
PetscBool inflowFluctuationsRestored
That state was read from the restart checkpoint.
Definition variables.h:1044
PetscReal dt
Definition variables.h:933
Here is the call graph for this function:
Here is the caller graph for this function:

◆ PreStep_OutletConservation()

static PetscErrorCode PreStep_OutletConservation ( BoundaryCondition *  self,
BCContext *  ctx,
PetscReal *  local_inflow_contribution,
PetscReal *  local_outflow_contribution 
)
static

Prepare the outlet-conservation correction before advancing the solver.

Definition at line 1446 of file BC_Handlers.c.

1448{
1449 PetscErrorCode ierr;
1450 UserCtx* user = ctx->user;
1451 BCFace face_id = ctx->face_id;
1452 DMDALocalInfo* info = &user->info;
1453 PetscBool can_service;
1454
1455 // Suppress unused parameter warnings for clarity.
1456 (void)self;
1457 (void)local_inflow_contribution;
1458
1459 PetscFunctionBeginUser;
1461
1462 // Step 1: Use the robust utility function to determine if this MPI rank owns a computable
1463 // portion of the specified boundary face. If not, there is no work to do, so we exit immediately.
1464 const PetscInt IM_nodes_global = user->IM;
1465 const PetscInt JM_nodes_global = user->JM;
1466 const PetscInt KM_nodes_global = user->KM;
1467 ierr = CanRankServiceFace(info, IM_nodes_global, JM_nodes_global, KM_nodes_global, face_id, &can_service); CHKERRQ(ierr);
1468
1469 if (!can_service) {
1471 PetscFunctionReturn(0);
1472 }
1473
1474 // Step 2: Get read-only access to the necessary PETSc arrays.
1475 // We use the local versions (`lUcat`, `lNvert`) which include ghost cell data,
1476 // ensuring we have the correct interior values adjacent to the boundary.
1477 Cmpnts ***ucat, ***csi, ***eta, ***zet;
1478 PetscReal ***nvert;
1479 ierr = DMDAVecGetArrayRead(user->fda, user->lUcat, (const Cmpnts***)&ucat); CHKERRQ(ierr);
1480 ierr = DMDAVecGetArrayRead(user->da, user->lNvert, (const PetscReal***)&nvert); CHKERRQ(ierr);
1481 ierr = DMDAVecGetArrayRead(user->fda, user->lCsi, (const Cmpnts***)&csi); CHKERRQ(ierr);
1482 ierr = DMDAVecGetArrayRead(user->fda, user->lEta, (const Cmpnts***)&eta); CHKERRQ(ierr);
1483 ierr = DMDAVecGetArrayRead(user->fda, user->lZet, (const Cmpnts***)&zet); CHKERRQ(ierr);
1484
1485 PetscReal local_flux_out = 0.0;
1486 const PetscInt xs=info->xs, xe=info->xs+info->xm;
1487 const PetscInt ys=info->ys, ye=info->ys+info->ym;
1488 const PetscInt zs=info->zs, ze=info->zs+info->zm;
1489 const PetscInt mx=info->mx, my=info->my, mz=info->mz;
1490
1491 // Step 3: Replicate the legacy shrunk loop bounds to exclude corners and edges.
1492 PetscInt lxs = xs; if (xs == 0) lxs = xs + 1;
1493 PetscInt lxe = xe; if (xe == mx) lxe = xe - 1;
1494 PetscInt lys = ys; if (ys == 0) lys = ys + 1;
1495 PetscInt lye = ye; if (ye == my) lye = ye - 1;
1496 PetscInt lzs = zs; if (zs == 0) lzs = zs + 1;
1497 PetscInt lze = ze; if (ze == mz) lze = ze - 1;
1498
1499 // Step 4: Loop over the specified face using the corrected bounds and indexing to calculate flux.
1500 switch (face_id) {
1501 case BC_FACE_NEG_X: {
1502 const PetscInt i_cell = xs + 1; // Index for first interior cell-centered data
1503 const PetscInt i_face = xs; // Index for the -X face of that cell
1504 for (int k=lzs; k<lze; k++) for (int j=lys; j<lye; j++) {
1505 if (nvert[k][j][i_cell] < 0.1) {
1506 local_flux_out += (ucat[k][j][i_cell].x * csi[k][j][i_face].x + ucat[k][j][i_cell].y * csi[k][j][i_face].y + ucat[k][j][i_cell].z * csi[k][j][i_face].z);
1507 }
1508 }
1509 break;
1510 }
1511 case BC_FACE_POS_X: {
1512 const PetscInt i_cell = xe - 2; // Index for last interior cell-centered data
1513 const PetscInt i_face = xe - 2; // Index for the +X face of that cell
1514 for (int k=lzs; k<lze; k++) for (int j=lys; j<lye; j++) {
1515 if (nvert[k][j][i_cell] < 0.1) {
1516 local_flux_out += (ucat[k][j][i_cell].x * csi[k][j][i_face].x + ucat[k][j][i_cell].y * csi[k][j][i_face].y + ucat[k][j][i_cell].z * csi[k][j][i_face].z);
1517 }
1518 }
1519 break;
1520 }
1521 case BC_FACE_NEG_Y: {
1522 const PetscInt j_cell = ys + 1;
1523 const PetscInt j_face = ys;
1524 for (int k=lzs; k<lze; k++) for (int i=lxs; i<lxe; i++) {
1525 if (nvert[k][j_cell][i] < 0.1) {
1526 local_flux_out += (ucat[k][j_cell][i].x * eta[k][j_face][i].x + ucat[k][j_cell][i].y * eta[k][j_face][i].y + ucat[k][j_cell][i].z * eta[k][j_face][i].z);
1527 }
1528 }
1529 break;
1530 }
1531 case BC_FACE_POS_Y: {
1532 const PetscInt j_cell = ye - 2;
1533 const PetscInt j_face = ye - 2;
1534 for (int k=lzs; k<lze; k++) for (int i=lxs; i<lxe; i++) {
1535 if (nvert[k][j_cell][i] < 0.1) {
1536 local_flux_out += (ucat[k][j_cell][i].x * eta[k][j_face][i].x + ucat[k][j_cell][i].y * eta[k][j_face][i].y + ucat[k][j_cell][i].z * eta[k][j_face][i].z);
1537 }
1538 }
1539 break;
1540 }
1541 case BC_FACE_NEG_Z: {
1542 const PetscInt k_cell = zs + 1;
1543 const PetscInt k_face = zs;
1544 for (int j=lys; j<lye; j++) for (int i=lxs; i<lxe; i++) {
1545 if (nvert[k_cell][j][i] < 0.1) {
1546 local_flux_out += (ucat[k_cell][j][i].x * zet[k_face][j][i].x + ucat[k_cell][j][i].y * zet[k_face][j][i].y + ucat[k_cell][j][i].z * zet[k_face][j][i].z);
1547 }
1548 }
1549 break;
1550 }
1551 case BC_FACE_POS_Z: {
1552 const PetscInt k_cell = ze - 2;
1553 const PetscInt k_face = ze - 2;
1554 for (int j=lys; j<lye; j++) for (int i=lxs; i<lxe; i++) {
1555 if (nvert[k_cell][j][i] < 0.1) {
1556 local_flux_out += (ucat[k_cell][j][i].x * zet[k_face][j][i].x + ucat[k_cell][j][i].y * zet[k_face][j][i].y + ucat[k_cell][j][i].z * zet[k_face][j][i].z);
1557 }
1558 }
1559 break;
1560 }
1561 }
1562
1563 // Step 5: Restore the PETSc arrays.
1564 ierr = DMDAVecRestoreArrayRead(user->fda, user->lUcat, (const Cmpnts***)&ucat); CHKERRQ(ierr);
1565 ierr = DMDAVecRestoreArrayRead(user->da, user->lNvert, (const PetscReal***)&nvert); CHKERRQ(ierr);
1566 ierr = DMDAVecRestoreArrayRead(user->fda, user->lCsi, (const Cmpnts***)&csi); CHKERRQ(ierr);
1567 ierr = DMDAVecRestoreArrayRead(user->fda, user->lEta, (const Cmpnts***)&eta); CHKERRQ(ierr);
1568 ierr = DMDAVecRestoreArrayRead(user->fda, user->lZet, (const Cmpnts***)&zet); CHKERRQ(ierr);
1569
1570 // Step 6: Add this face's calculated flux to the accumulator for this rank.
1571 *local_outflow_contribution += local_flux_out;
1572
1574 PetscFunctionReturn(0);
1575}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ Apply_OutletConservation()

static PetscErrorCode Apply_OutletConservation ( BoundaryCondition *  self,
BCContext *  ctx 
)
static

(Handler Action) Applies mass conservation correction to the outlet face.

This function calculates a global correction factor based on the total inflow and outflow fluxes and applies it to the contravariant velocity (ucont) on the outlet face to ensure mass conservation.

Definition at line 1739 of file BC_Handlers.c.

1740{
1741 PetscErrorCode ierr;
1742 UserCtx* user = ctx->user;
1743 BCFace face_id = ctx->face_id;
1744 DMDALocalInfo* info = &user->info;
1745 PetscBool can_service;
1746 PetscBool clip_applied = PETSC_FALSE;
1747
1748 PetscFunctionBeginUser;
1750
1751 // --- STEP 1: Calculate the correction factor using pre-calculated area ---
1752 PetscReal total_inflow = *ctx->global_inflow_sum + *ctx->global_farfield_inflow_sum;
1753 PetscReal flux_imbalance = total_inflow - *ctx->global_outflow_sum;
1754
1755 // Directly use the pre-calculated area from the simulation context.
1756 PetscReal velocity_correction = (PetscAbsReal(user->simCtx->AreaOutSum) > 1e-12)
1757 ? flux_imbalance / user->simCtx->AreaOutSum
1758 : 0.0;
1759
1760 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Outlet Correction on Face %d: Imbalance=%.4e, Pre-calc Area=%.4e, V_corr=%.4e\n",
1761 face_id, flux_imbalance, user->simCtx->AreaOutSum, velocity_correction);
1762
1763 // Backflow clip (collective, so before the can_service exit). When it applies, it has
1764 // written this face; otherwise the uniform rule below runs unchanged.
1765 ierr = OutletConservationClip(user, face_id, (OutletConservationData*)self->data,
1766 velocity_correction, &clip_applied); CHKERRQ(ierr);
1767 if (clip_applied) {
1769 PetscFunctionReturn(0);
1770 }
1771
1772 const PetscInt IM_nodes_global = user->IM;
1773 const PetscInt JM_nodes_global = user->JM;
1774 const PetscInt KM_nodes_global = user->KM;
1775 ierr = CanRankServiceFace(info, IM_nodes_global, JM_nodes_global, KM_nodes_global, face_id, &can_service); CHKERRQ(ierr);
1776
1777 if (!can_service) {
1779 PetscFunctionReturn(0);
1780 }
1781
1782 // --- STEP 2: Apply the correction to ucont on the outlet face ---
1783
1784 // Get read/write access to necessary arrays
1785
1786 Cmpnts ***ubcs, ***ucont, ***csi, ***eta, ***zet, ***ucat;
1787 PetscReal ***nvert;
1788 ierr = DMDAVecGetArray(user->fda, user->Bcs.Ubcs, &ubcs); CHKERRQ(ierr);
1789 ierr = DMDAVecGetArray(user->fda, user->Ucont, &ucont); CHKERRQ(ierr);
1790 ierr = DMDAVecGetArrayRead(user->fda,user->lUcat, (const Cmpnts***)&ucat); CHKERRQ(ierr);
1791 ierr = DMDAVecGetArrayRead(user->fda, user->lCsi, (const Cmpnts***)&csi); CHKERRQ(ierr);
1792 ierr = DMDAVecGetArrayRead(user->fda, user->lEta, (const Cmpnts***)&eta); CHKERRQ(ierr);
1793 ierr = DMDAVecGetArrayRead(user->fda, user->lZet, (const Cmpnts***)&zet); CHKERRQ(ierr);
1794 ierr = DMDAVecGetArrayRead(user->da, user->lNvert, (const PetscReal***)&nvert); CHKERRQ(ierr);
1795
1796 // Get local grid bounds to exclude corners/edges
1797 PetscInt xs = info->xs, xe = info->xs + info->xm;
1798 PetscInt ys = info->ys, ye = info->ys + info->ym;
1799 PetscInt zs = info->zs, ze = info->zs + info->zm;
1800 PetscInt mx = info->mx, my = info->my, mz = info->mz;
1801 PetscInt lxs = xs, lxe = xe, lys = ys, lye = ye, lzs = zs, lze = ze;
1802
1803 if (xs == 0) lxs = xs + 1;
1804 if (xe == mx) lxe = xe - 1;
1805 if (ys == 0) lys = ys + 1;
1806 if (ye == my) lye = ye - 1;
1807 if (zs == 0) lzs = zs + 1;
1808 if (ze == mz) lze = ze - 1;
1809
1810 // Loop over faces and apply correction
1811 switch(face_id){
1812 case BC_FACE_NEG_X:{
1813 const PetscInt i_cell = xs + 1;
1814 const PetscInt i_face = xs;
1815 const PetscInt i_dummy = xs;
1816 for (PetscInt k = lzs; k < lze; k++) {
1817 for (PetscInt j = lys; j < lye; j++) {
1818 if (nvert[k][j][i_cell] < 0.1) {
1819 // Set ubcs
1820 ubcs[k][j][i_dummy] = ucat[k][j][i_cell];
1821
1822 // Calculate Local uncorrected original flux
1823 PetscReal Uncorrected_local_flux = (ubcs[k][j][i_dummy].x * csi[k][j][i_face].x) + (ubcs[k][j][i_dummy].y * csi[k][j][i_face].y) + (ubcs[k][j][i_dummy].z * csi[k][j][i_face].z);
1824
1825 PetscReal Cell_Area = sqrt((csi[k][j][i_face].x*csi[k][j][i_face].x) + (csi[k][j][i_face].y*csi[k][j][i_face].y) + (csi[k][j][i_face].z*csi[k][j][i_face].z));
1826
1827 PetscReal Correction_flux = velocity_correction*Cell_Area;
1828
1829 ucont[k][j][i_face].x = Uncorrected_local_flux + Correction_flux;
1830 }
1831 }
1832 }
1833 break;
1834 }
1835 case BC_FACE_POS_X:{
1836 const PetscInt i_cell = xe - 2;
1837 const PetscInt i_face = xe - 2;
1838 const PetscInt i_dummy = xe - 1;
1839 for(PetscInt k = lzs; k < lze; k++) for (PetscInt j = lys; j < lye; j++){
1840 if(nvert[k][j][i_cell]<0.1){
1841 // Set ubcs
1842 ubcs[k][j][i_dummy] = ucat[k][j][i_cell];
1843
1844 // Calculate Local uncorrected original flux
1845 PetscReal Uncorrected_local_flux = (ubcs[k][j][i_dummy].x * csi[k][j][i_face].x) + (ubcs[k][j][i_dummy].y * csi[k][j][i_face].y) + (ubcs[k][j][i_dummy].z * csi[k][j][i_face].z);
1846
1847 PetscReal Cell_Area = sqrt((csi[k][j][i_face].x*csi[k][j][i_face].x) + (csi[k][j][i_face].y*csi[k][j][i_face].y) + (csi[k][j][i_face].z*csi[k][j][i_face].z));
1848
1849 PetscReal Correction_flux = velocity_correction*Cell_Area;
1850
1851 ucont[k][j][i_face].x = Uncorrected_local_flux + Correction_flux;
1852 }
1853 }
1854 break;
1855 }
1856 case BC_FACE_NEG_Y:{
1857 const PetscInt j_cell = ys + 1;
1858 const PetscInt j_face = ys;
1859 const PetscInt j_dummy = ys;
1860 for(PetscInt k = lzs; k < lze; k++) for (PetscInt i = lxs; i < lxe; i++){
1861 if(nvert[k][j_cell][i]<0.1){
1862 // Set ubcs
1863 ubcs[k][j_dummy][i] = ucat[k][j_cell][i];
1864
1865 // Calculate Local uncorrected original flux
1866 PetscReal Uncorrected_local_flux = (ubcs[k][j_dummy][i].x*eta[k][j_face][i].x) + (ubcs[k][j_dummy][i].y*eta[k][j_face][i].y) + (ubcs[k][j_dummy][i].z*eta[k][j_face][i].z);
1867
1868 PetscReal Cell_Area = sqrt((eta[k][j_face][i].x*eta[k][j_face][i].x)+(eta[k][j_face][i].y*eta[k][j_face][i].y)+(eta[k][j_face][i].z*eta[k][j_face][i].z));
1869
1870 PetscReal Correction_flux = velocity_correction*Cell_Area;
1871
1872 ucont[k][j_face][i].y = Uncorrected_local_flux + Correction_flux;
1873 }
1874 }
1875 break;
1876 }
1877 case BC_FACE_POS_Y:{
1878 const PetscInt j_cell = ye - 2;
1879 const PetscInt j_face = ye - 2;
1880 const PetscInt j_dummy = ye - 1;
1881 for(PetscInt k = lzs; k < lze; k++) for (PetscInt i = lxs; i < lxe; i++){
1882 if(nvert[k][j_cell][i]<0.1){
1883 // Set ubcs
1884 ubcs[k][j_dummy][i] = ucat[k][j_cell][i];
1885
1886 // Calculate Local uncorrected original flux
1887 PetscReal Uncorrected_local_flux = (ubcs[k][j_dummy][i].x*eta[k][j_face][i].x) + (ubcs[k][j_dummy][i].y*eta[k][j_face][i].y) + (ubcs[k][j_dummy][i].z*eta[k][j_face][i].z);
1888
1889 PetscReal Cell_Area = sqrt((eta[k][j_face][i].x*eta[k][j_face][i].x)+(eta[k][j_face][i].y*eta[k][j_face][i].y)+(eta[k][j_face][i].z*eta[k][j_face][i].z));
1890
1891 PetscReal Correction_flux = velocity_correction*Cell_Area;
1892
1893 ucont[k][j_face][i].y = Uncorrected_local_flux + Correction_flux;
1894 }
1895 }
1896 break;
1897 }
1898 case BC_FACE_NEG_Z:{
1899 const PetscInt k_cell = zs + 1;
1900 const PetscInt k_face = zs;
1901 const PetscInt k_dummy = zs;
1902 for(PetscInt j = lys; j < lye; j++) for (PetscInt i = lxs; i < lxe; i++){
1903 if(nvert[k_cell][j][i]<0.1){
1904 // Set ubcs
1905 ubcs[k_dummy][j][i] = ucat[k_cell][j][i];
1906
1907 // Calculate Local uncorrected original flux
1908 PetscReal Uncorrected_local_flux = ((ubcs[k_dummy][j][i].x*zet[k_face][j][i].x) + (ubcs[k_dummy][j][i].y*zet[k_face][j][i].y) + (ubcs[k_dummy][j][i].z*zet[k_face][j][i].z));
1909
1910 PetscReal Cell_Area = sqrt((zet[k_face][j][i].x*zet[k_face][j][i].x)+(zet[k_face][j][i].y*zet[k_face][j][i].y)+(zet[k_face][j][i].z*zet[k_face][j][i].z));
1911
1912 PetscReal Correction_flux = velocity_correction*Cell_Area;
1913
1914 ucont[k_face][j][i].z = Uncorrected_local_flux + Correction_flux;
1915 }
1916 }
1917 break;
1918 }
1919 case BC_FACE_POS_Z:{
1920 const PetscInt k_cell = ze - 2;
1921 const PetscInt k_face = ze - 2;
1922 const PetscInt k_dummy = ze - 1;
1923 for(PetscInt j = lys; j < lye; j++) for (PetscInt i = lxs; i < lxe; i++){
1924 if(nvert[k_cell][j][i]<0.1){
1925 // Set ubcs
1926 ubcs[k_dummy][j][i] = ucat[k_cell][j][i];
1927
1928 // Calculate Local uncorrected original flux
1929 PetscReal Uncorrected_local_flux = ((ubcs[k_dummy][j][i].x*zet[k_face][j][i].x) + (ubcs[k_dummy][j][i].y*zet[k_face][j][i].y) + (ubcs[k_dummy][j][i].z*zet[k_face][j][i].z));
1930
1931 PetscReal Cell_Area = sqrt((zet[k_face][j][i].x*zet[k_face][j][i].x)+(zet[k_face][j][i].y*zet[k_face][j][i].y)+(zet[k_face][j][i].z*zet[k_face][j][i].z));
1932
1933 PetscReal Correction_flux = velocity_correction*Cell_Area;
1934
1935 ucont[k_face][j][i].z = Uncorrected_local_flux + Correction_flux;
1936 }
1937 }
1938 break;
1939 }
1940 }
1941
1942 // Restore all arrays
1943 ierr = DMDAVecRestoreArray(user->fda, user->Bcs.Ubcs, &ubcs); CHKERRQ(ierr);
1944 ierr = DMDAVecRestoreArray(user->fda, user->Ucont, &ucont); CHKERRQ(ierr);
1945 ierr = DMDAVecRestoreArrayRead(user->fda,user->lUcat, (const Cmpnts***)&ucat); CHKERRQ(ierr);
1946 ierr = DMDAVecRestoreArrayRead(user->fda, user->lCsi, (const Cmpnts***)&csi); CHKERRQ(ierr);
1947 ierr = DMDAVecRestoreArrayRead(user->fda, user->lEta, (const Cmpnts***)&eta); CHKERRQ(ierr);
1948 ierr = DMDAVecRestoreArrayRead(user->fda, user->lZet, (const Cmpnts***)&zet); CHKERRQ(ierr);
1949 ierr = DMDAVecRestoreArrayRead(user->da, user->lNvert, (const PetscReal***)&nvert); CHKERRQ(ierr);
1950
1952 PetscFunctionReturn(0);
1953}
static PetscErrorCode OutletConservationClip(UserCtx *user, BCFace face_id, OutletConservationData *data, PetscReal correction, PetscBool *applied)
Run the backflow clip for one Apply call; see the section comment.
Per-face state of the backflow clip; see the section comment above.
const PetscReal * global_outflow_sum
Definition variables.h:385
const PetscReal * global_inflow_sum
Definition variables.h:382
const PetscReal * global_farfield_inflow_sum
Definition variables.h:383
PetscReal AreaOutSum
Definition variables.h:1036
Here is the call graph for this function:
Here is the caller graph for this function:

◆ PostStep_OutletConservation()

static PetscErrorCode PostStep_OutletConservation ( BoundaryCondition *  self,
BCContext *  ctx,
PetscReal *  in,
PetscReal *  out 
)
static

Update outlet-conservation state after a completed solver step.

Definition at line 1958 of file BC_Handlers.c.

1961{
1962 PetscErrorCode ierr;
1963 UserCtx* user = ctx->user;
1964 BCFace face_id = ctx->face_id;
1965 DMDALocalInfo* info = &user->info;
1966 PetscBool can_service;
1967
1968 (void)self;
1969 (void)local_inflow_contribution;
1970
1971 PetscFunctionBeginUser;
1973 const PetscInt IM_nodes_global = user->IM;
1974 const PetscInt JM_nodes_global = user->JM;
1975 const PetscInt KM_nodes_global = user->KM;
1976 ierr = CanRankServiceFace(info, IM_nodes_global, JM_nodes_global, KM_nodes_global, face_id, &can_service); CHKERRQ(ierr);
1977
1978 if (!can_service) { PROFILE_HELPER_END; PetscFunctionReturn(0); }
1979
1980 // Get arrays (need both ucont and nvert)
1981 Cmpnts ***ucont;
1982 PetscReal ***nvert; // ✅ ADD nvert
1983
1984 ierr = DMDAVecGetArrayRead(user->fda, user->Ucont, (const Cmpnts***)&ucont); CHKERRQ(ierr);
1985 ierr = DMDAVecGetArrayRead(user->da, user->lNvert, (const PetscReal***)&nvert); CHKERRQ(ierr); // ✅ ADD
1986
1987 PetscReal local_flux = 0.0;
1988
1989 PetscInt xs = info->xs, xe = info->xs + info->xm;
1990 PetscInt ys = info->ys, ye = info->ys + info->ym;
1991 PetscInt zs = info->zs, ze = info->zs + info->zm;
1992 PetscInt mx = info->mx, my = info->my, mz = info->mz;
1993
1994 PetscInt lxs = xs, lxe = xe, lys = ys, lye = ye, lzs = zs, lze = ze;
1995 if (xs == 0) lxs = xs + 1;
1996 if (xe == mx) lxe = xe - 1;
1997 if (ys == 0) lys = ys + 1;
1998 if (ye == my) lye = ye - 1;
1999 if (zs == 0) lzs = zs + 1;
2000 if (ze == mz) lze = ze - 1;
2001
2002 // Sum ucont components, skipping solid cells (same indices as PreStep)
2003 switch (face_id) {
2004 case BC_FACE_NEG_X: {
2005 const PetscInt i_cell = xs + 1; // ✅ Match PreStep
2006 const PetscInt i_face = xs;
2007 for (PetscInt k = lzs; k < lze; k++) {
2008 for (PetscInt j = lys; j < lye; j++) {
2009 if (nvert[k][j][i_cell] < 0.1) { // ✅ Skip solid cells
2010 local_flux += ucont[k][j][i_face].x;
2011 }
2012 }
2013 }
2014 } break;
2015
2016 case BC_FACE_POS_X: {
2017 const PetscInt i_cell = xe - 2; // ✅ Match PreStep
2018 const PetscInt i_face = xe - 2;
2019 for (PetscInt k = lzs; k < lze; k++) {
2020 for (PetscInt j = lys; j < lye; j++) {
2021 if (nvert[k][j][i_cell] < 0.1) { // ✅ Skip solid cells
2022 local_flux += ucont[k][j][i_face].x;
2023 }
2024 }
2025 }
2026 } break;
2027
2028 case BC_FACE_NEG_Y: {
2029 const PetscInt j_cell = ys + 1; // ✅ Match PreStep
2030 const PetscInt j_face = ys;
2031 for (PetscInt k = lzs; k < lze; k++) {
2032 for (PetscInt i = lxs; i < lxe; i++) {
2033 if (nvert[k][j_cell][i] < 0.1) { // ✅ Skip solid cells
2034 local_flux += ucont[k][j_face][i].y;
2035 }
2036 }
2037 }
2038 } break;
2039
2040 case BC_FACE_POS_Y: {
2041 const PetscInt j_cell = ye - 2; // ✅ Match PreStep
2042 const PetscInt j_face = ye - 2;
2043 for (PetscInt k = lzs; k < lze; k++) {
2044 for (PetscInt i = lxs; i < lxe; i++) {
2045 if (nvert[k][j_cell][i] < 0.1) { // ✅ Skip solid cells
2046 local_flux += ucont[k][j_face][i].y;
2047 }
2048 }
2049 }
2050 } break;
2051
2052 case BC_FACE_NEG_Z: {
2053 const PetscInt k_cell = zs + 1; // ✅ Match PreStep
2054 const PetscInt k_face = zs;
2055 for (PetscInt j = lys; j < lye; j++) {
2056 for (PetscInt i = lxs; i < lxe; i++) {
2057 if (nvert[k_cell][j][i] < 0.1) { // ✅ Skip solid cells
2058 local_flux += ucont[k_face][j][i].z;
2059 }
2060 }
2061 }
2062 } break;
2063
2064 case BC_FACE_POS_Z: {
2065 const PetscInt k_cell = ze - 2; // ✅ Match PreStep
2066 const PetscInt k_face = ze - 2;
2067 for (PetscInt j = lys; j < lye; j++) {
2068 for (PetscInt i = lxs; i < lxe; i++) {
2069 if (nvert[k_cell][j][i] < 0.1) { // ✅ Skip solid cells
2070 local_flux += ucont[k_face][j][i].z;
2071 }
2072 }
2073 }
2074 } break;
2075 }
2076
2077 // Restore arrays
2078 ierr = DMDAVecRestoreArrayRead(user->fda, user->Ucont, (const Cmpnts***)&ucont); CHKERRQ(ierr);
2079 ierr = DMDAVecRestoreArrayRead(user->da, user->lNvert, (const PetscReal***)&nvert); CHKERRQ(ierr); // ✅ ADD
2080
2081 // Add to accumulator
2082 *local_outflow_contribution += local_flux;
2083
2084 LOG_ALLOW(LOCAL, LOG_DEBUG, "PostStep_OutletConservation: Face %d, corrected flux = %.6e\n",
2085 face_id, local_flux);
2086
2088 PetscFunctionReturn(0);
2089}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ Destroy_OutletConservation()

static PetscErrorCode Destroy_OutletConservation ( BoundaryCondition *  self)
static

Release the outlet-conservation handler's clip state.

Definition at line 2094 of file BC_Handlers.c.

2095{
2096 PetscFunctionBeginUser;
2098 if (self && self->data) {
2100 PetscCall(PetscFree(data->clipped));
2101 PetscCall(PetscFree(self->data));
2102 }
2104 PetscFunctionReturn(PETSC_SUCCESS);
2105}
Here is the caller graph for this function:

◆ Create_OutletConservation()

PetscErrorCode Create_OutletConservation ( BoundaryCondition *  bc)

Implementation of Create_OutletConservation().

Configures a BoundaryCondition object for conservative outlet treatment.

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

See also
Create_OutletConservation()

Definition at line 1414 of file BC_Handlers.c.

1415{
1416 PetscFunctionBeginUser;
1418
1419 PetscCheck(bc, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "BoundaryCondition is NULL");
1420
1421 // This handler has the highest priority to ensure it runs after
1422 // all inflow fluxes have been calculated.
1424
1425 // Assign function pointers
1426 bc->Initialize = NULL; // No initialization needed
1430 bc->UpdateUbcs = NULL;
1431 bc->needs_repeat_pass = PETSC_TRUE; // Reads the adjacent Ucat and the inlets' flux
1433
1434 OutletConservationData *data = NULL;
1435 PetscCall(PetscNew(&data));
1436 data->decisionStep = -1;
1437 bc->data = (void*)data;
1438
1440 PetscFunctionReturn(0);
1441}
static PetscErrorCode Destroy_OutletConservation(BoundaryCondition *self)
Release the outlet-conservation handler's clip state.
static PetscErrorCode Apply_OutletConservation(BoundaryCondition *self, BCContext *ctx)
(Handler Action) Applies mass conservation correction to the outlet face.
static PetscErrorCode PostStep_OutletConservation(BoundaryCondition *self, BCContext *ctx, PetscReal *in, PetscReal *out)
Update outlet-conservation state after a completed solver step.
static PetscErrorCode PreStep_OutletConservation(BoundaryCondition *self, BCContext *ctx, PetscReal *local_inflow_contribution, PetscReal *local_outflow_contribution)
Prepare the outlet-conservation correction before advancing the solver.
@ BC_PRIORITY_OUTLET
Definition variables.h:364
Here is the call graph for this function:
Here is the caller graph for this function:

◆ OutletClipPass()

static PetscErrorCode OutletClipPass ( UserCtx *  user,
BCFace  face_id,
OutletConservationData *  data,
OutletClipPassMode  mode,
PetscReal  correction,
PetscReal  psi,
PetscReal  sums[3] 
)
static

One pass over this rank's elements of an outlet face for the backflow clip.

Every fluid element's zero-gradient flux is F = Ucat(cell) . S, the flux the uniform rule starts from. The pass is local; the caller reduces sums.

  • DECIDE freezes the clipped set {F points into the domain} into data and returns sums[0] = the number of elements where F + correction*A points into the domain and sums[1] = the number clipped. Fluxes are signed along +xi, so outward is +F on a positive face and -F on a negative one.
  • MEASURE returns sums[0] = sum F, sums[1] = sum A and sums[2] = sum F over unclipped elements.
  • WRITE sets the outlet flux: zero on clipped elements, whose Ubcs loses its normal component, and psi*F elsewhere, with Ubcs = Ucat as in the uniform rule.

Definition at line 1593 of file BC_Handlers.c.

1596{
1597 const PetscBool negative = (PetscBool)((PetscInt)face_id % 2 == 0);
1598 const PetscReal outward = negative ? -1.0 : 1.0;
1600 Cmpnts ***ucat, ***metric, ***ubcs = NULL, ***ucont = NULL;
1601 PetscReal ***nvert;
1602
1603 PetscFunctionBeginUser;
1605 sums[0] = sums[1] = sums[2] = 0.0;
1606 PetscCall(GetBoundaryFaceElements(user, face_id, &e));
1607 const PetscInt count = e.n[0] * e.n[1];
1608 if (mode == OUTLET_CLIP_DECIDE && count != data->maskSize) {
1609 PetscCall(PetscFree(data->clipped));
1610 if (count > 0) PetscCall(PetscCalloc1(count, &data->clipped));
1611 data->maskSize = count;
1612 }
1613 if (count == 0) { PROFILE_HELPER_END; PetscFunctionReturn(PETSC_SUCCESS); }
1614
1615 const Vec lmetric = (e.normal == 0) ? user->lCsi : (e.normal == 1) ? user->lEta : user->lZet;
1616 const PetscInt cell = negative ? e.layer + 1 : e.layer;
1617 const PetscInt dummy = negative ? e.layer : e.layer + 1;
1618
1619 PetscCall(DMDAVecGetArrayRead(user->fda, user->lUcat, (const Cmpnts***)&ucat));
1620 PetscCall(DMDAVecGetArrayRead(user->fda, lmetric, (const Cmpnts***)&metric));
1621 PetscCall(DMDAVecGetArrayRead(user->da, user->lNvert, (const PetscReal***)&nvert));
1622 if (mode == OUTLET_CLIP_WRITE) {
1623 PetscCall(DMDAVecGetArray(user->fda, user->Bcs.Ubcs, &ubcs));
1624 PetscCall(DMDAVecGetArray(user->fda, user->Ucont, &ucont));
1625 }
1626 for (PetscInt q = 0; q < e.n[1]; q++)
1627 for (PetscInt p = 0; p < e.n[0]; p++) {
1628 PetscInt c[3], f[3], d[3];
1629
1630 c[e.normal] = cell; c[e.a] = e.lo[0] + p; c[e.b] = e.lo[1] + q;
1631 if (nvert[c[2]][c[1]][c[0]] >= 0.1) continue;
1632 f[0] = d[0] = c[0]; f[1] = d[1] = c[1]; f[2] = d[2] = c[2];
1633 f[e.normal] = e.layer;
1634 d[e.normal] = dummy;
1635
1636 const PetscInt idx = q * e.n[0] + p;
1637 const Cmpnts S = metric[f[2]][f[1]][f[0]];
1638 const Cmpnts u = ucat[c[2]][c[1]][c[0]];
1639 const PetscReal flux = u.x * S.x + u.y * S.y + u.z * S.z;
1640 const PetscReal area = PetscSqrtReal(S.x * S.x + S.y * S.y + S.z * S.z);
1641
1642 switch (mode) {
1643 case OUTLET_CLIP_DECIDE:
1644 data->clipped[idx] = (PetscBool)(outward * flux < 0.0);
1645 if (outward * (flux + correction * area) < 0.0) sums[0] += 1.0;
1646 if (data->clipped[idx]) sums[1] += 1.0;
1647 break;
1649 sums[0] += flux;
1650 sums[1] += area;
1651 if (!data->clipped[idx]) sums[2] += flux;
1652 break;
1653 case OUTLET_CLIP_WRITE: {
1654 Cmpnts *face_flux = &ucont[f[2]][f[1]][f[0]];
1655 PetscReal *normal_flux = (e.normal == 0) ? &face_flux->x : (e.normal == 1) ? &face_flux->y : &face_flux->z;
1656
1657 if (data->clipped[idx]) {
1658 *normal_flux = 0.0;
1659 ubcs[d[2]][d[1]][d[0]] = RemoveFaceNormalComponent(u, S);
1660 } else {
1661 *normal_flux = psi * flux;
1662 ubcs[d[2]][d[1]][d[0]] = u;
1663 }
1664 break;
1665 }
1666 }
1667 }
1668 if (mode == OUTLET_CLIP_WRITE) {
1669 PetscCall(DMDAVecRestoreArray(user->fda, user->Bcs.Ubcs, &ubcs));
1670 PetscCall(DMDAVecRestoreArray(user->fda, user->Ucont, &ucont));
1671 }
1672 PetscCall(DMDAVecRestoreArrayRead(user->da, user->lNvert, (const PetscReal***)&nvert));
1673 PetscCall(DMDAVecRestoreArrayRead(user->fda, lmetric, (const Cmpnts***)&metric));
1674 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lUcat, (const Cmpnts***)&ucat));
1676 PetscFunctionReturn(PETSC_SUCCESS);
1677}
PetscErrorCode GetBoundaryFaceElements(UserCtx *user, BCFace face_id, BoundaryFaceElements *elements)
The elements of a boundary face this rank owns, as index ranges.
Definition Boundaries.c:105
The elements of one boundary face that this rank owns: one per interior cell beside the face,...
Definition variables.h:415
Here is the call graph for this function:
Here is the caller graph for this function:

◆ OutletConservationClip()

static PetscErrorCode OutletConservationClip ( UserCtx *  user,
BCFace  face_id,
OutletConservationData *  data,
PetscReal  correction,
PetscBool *  applied 
)
static

Run the backflow clip for one Apply call; see the section comment.

Collective: every rank calls it, whether or not it serves the face. Sets applied when the clip rule wrote this face's fluxes; otherwise the caller applies the uniform rule unchanged.

Definition at line 1685 of file BC_Handlers.c.

1687{
1688 SimCtx *simCtx = user->simCtx;
1689 const PetscReal outward = ((PetscInt)face_id % 2 == 0) ? -1.0 : 1.0;
1690 PetscReal local[3], global[3];
1691 PetscBool decided_now = PETSC_FALSE;
1692 PetscReal reversed = 0.0, clipped = 0.0;
1693
1694 PetscFunctionBeginUser;
1696 *applied = PETSC_FALSE;
1697 if (data->decisionStep != simCtx->step) {
1698 PetscCall(OutletClipPass(user, face_id, data, OUTLET_CLIP_DECIDE, correction, 0.0, local));
1699 PetscCallMPI(MPI_Allreduce(local, global, 2, MPIU_REAL, MPI_SUM, PETSC_COMM_WORLD));
1700 data->clipRule = (PetscBool)(global[0] > 0.5);
1701 data->decisionStep = simCtx->step;
1702 decided_now = PETSC_TRUE;
1703 reversed = global[0];
1704 clipped = global[1];
1705 }
1706 if (!data->clipRule) { PROFILE_HELPER_END; PetscFunctionReturn(PETSC_SUCCESS); }
1707
1708 PetscCall(OutletClipPass(user, face_id, data, OUTLET_CLIP_MEASURE, correction, 0.0, local));
1709 PetscCallMPI(MPI_Allreduce(local, global, 3, MPIU_REAL, MPI_SUM, PETSC_COMM_WORLD));
1710 /* The total the uniform rule would give this face: the clip only redistributes it. */
1711 const PetscReal target = global[0] + correction * global[1];
1712 if (!(outward * global[2] > 0.0 && outward * target > 0.0)) {
1714 "Outlet %s, step %" PetscInt_FMT ": nothing left to scale (unclipped flux %.4e, target %.4e); "
1715 "using the uniform correction for this pass.\n",
1716 BCFaceToString(face_id), simCtx->step, global[2], target);
1718 PetscFunctionReturn(PETSC_SUCCESS);
1719 }
1720 const PetscReal psi = target / global[2];
1721 PetscCall(OutletClipPass(user, face_id, data, OUTLET_CLIP_WRITE, correction, psi, local));
1722 if (decided_now) {
1724 "Outlet %s, step %" PetscInt_FMT ": uniform correction would leave %.0f faces reversed; "
1725 "clipped %.0f reversed faces, scaled the rest by psi = %.6f.\n",
1726 BCFaceToString(face_id), simCtx->step, reversed, clipped, psi);
1727 }
1728 *applied = PETSC_TRUE;
1730 PetscFunctionReturn(PETSC_SUCCESS);
1731}
static PetscErrorCode OutletClipPass(UserCtx *user, BCFace face_id, OutletConservationData *data, OutletClipPassMode mode, PetscReal correction, PetscReal psi, PetscReal sums[3])
One pass over this rank's elements of an outlet face for the backflow clip.
@ LOG_WARNING
Non-critical issues that warrant attention.
Definition logging.h:30
Here is the call graph for this function:
Here is the caller graph for this function:

◆ Create_PeriodicGeometric()

PetscErrorCode Create_PeriodicGeometric ( BoundaryCondition *  bc)

Implementation of Create_PeriodicGeometric().

Configures a BoundaryCondition object for geometric periodic coupling.

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

See also
Create_PeriodicGeometric()

Definition at line 2115 of file BC_Handlers.c.

2115 {
2116 PetscFunctionBeginUser;
2118
2119 PetscCheck(bc, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "BoundaryCondition is NULL");
2121
2122 // Assign function pointers
2123 bc->Initialize = NULL; // No initialization needed
2124 bc->PreStep = NULL;
2125 bc->Apply = NULL;
2126 bc->PostStep = NULL;
2127 bc->UpdateUbcs = NULL;
2128 bc->Destroy = NULL; // No private data to destroy
2129
2130 bc->data = NULL;
2131
2133 PetscFunctionReturn(0);
2134}
Here is the caller graph for this function:

◆ MeasureDrivenFluxes()

static PetscErrorCode MeasureDrivenFluxes ( UserCtx *  user,
char  direction,
PetscReal *  boundaryFlux,
PetscReal *  planarAverageFlux 
)
static

Measure the two volumetric fluxes the driven-flow controller senses.

Both periodic driven handlers steer on the same pair of measurements, so they are taken here in a single sweep of lUcont:

  • *boundaryFlux is the flux through the single periodic boundary plane. It is fast and responsive but noisy, and drives the boundary trim.
  • *planarAverageFlux is the flux averaged over every cross-sectional plane in the driven direction. It is stable and inertial, and drives the momentum source. It is also the quantity initial_flux latches at t=0.
Parameters
[in]userBlock context supplying lUcont, lNvert and info.
[in]directionDriven direction, 'X', 'Y' or 'Z'.
[out]boundaryFluxGlobally reduced flux through the boundary plane.
[out]planarAverageFluxGlobally reduced plane-averaged flux.
Returns
PetscErrorCode 0 on success.

Definition at line 2155 of file BC_Handlers.c.

2158{
2159 PetscErrorCode ierr;
2160 DMDALocalInfo info = user->info;
2161 PetscInt i, j, k;
2162
2163 PetscFunctionBeginUser;
2165
2166 // --- Get read-only access to necessary field data ---
2167 Cmpnts ***ucont;
2168 PetscReal ***nvert;
2169 ierr = DMDAVecGetArrayRead(user->fda, user->lUcont, (const Cmpnts***)&ucont); CHKERRQ(ierr);
2170 ierr = DMDAVecGetArrayRead(user->da, user->lNvert, (const PetscReal***)&nvert); CHKERRQ(ierr);
2171
2172 // --- Define local loop bounds ---
2173 PetscInt lo[3], hi[3];
2174 GetOwnedInteriorCellBounds(&info, lo, hi);
2175 PetscInt lxs = lo[0], lys = lo[1], lzs = lo[2], lxe = hi[0], lye = hi[1], lze = hi[2];
2176
2177 // --- Initialize local accumulators ---
2178 PetscReal localCurrentBoundaryFlux = 0.0;
2179 PetscReal localAveragePlanarVolumetricFluxTerm = 0.0;
2180
2181 // --- Measure local contributions to the two flux types, generalized by direction ---
2182 switch (direction) {
2183 case 'X':
2184 if (info.xs == 0) { // Only the rank on the negative face contributes to boundary flux
2185 i = 0;
2186 for (k = lzs; k < lze; k++) for (j = lys; j < lye; j++) {
2187 if (nvert[k][j][i + 1] < 0.1) localCurrentBoundaryFlux += ucont[k][j][i].x;
2188 }
2189 }
2190 for (i = info.xs; i < lxe; i++) {
2191 for (k = lzs; k < lze; k++) for (j = lys; j < lye; j++) {
2192 if (nvert[k][j][i + 1] < 0.1) localAveragePlanarVolumetricFluxTerm += ucont[k][j][i].x / (PetscReal)(info.mx - 1);
2193 }
2194 }
2195 break;
2196 case 'Y':
2197 if (info.ys == 0) {
2198 j = 0;
2199 for (k = lzs; k < lze; k++) for (i = lxs; i < lxe; i++) {
2200 if (nvert[k][j + 1][i] < 0.1) localCurrentBoundaryFlux += ucont[k][j][i].y;
2201 }
2202 }
2203 for (j = info.ys; j < lye; j++) {
2204 for (k = lzs; k < lze; k++) for (i = lxs; i < lxe; i++) {
2205 if (nvert[k][j + 1][i] < 0.1) localAveragePlanarVolumetricFluxTerm += ucont[k][j][i].y / (PetscReal)(info.my - 1);
2206 }
2207 }
2208 break;
2209 case 'Z':
2210 if (info.zs == 0) {
2211 k = 0;
2212 for (j = lys; j < lye; j++) for (i = lxs; i < lxe; i++) {
2213 if (nvert[k + 1][j][i] < 0.1) localCurrentBoundaryFlux += ucont[k][j][i].z;
2214 }
2215 }
2216 for (k = info.zs; k < lze; k++) {
2217 for (j = lys; j < lye; j++) for (i = lxs; i < lxe; i++) {
2218 if (nvert[k + 1][j][i] < 0.1) localAveragePlanarVolumetricFluxTerm += ucont[k][j][i].z / (PetscReal)(info.mz - 1);
2219 }
2220 }
2221 break;
2222 default:
2223 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG,
2224 "MeasureDrivenFluxes received an unknown driven direction '%c'.", direction);
2225 }
2226
2227 // --- Release array access as soon as possible ---
2228 ierr = DMDAVecRestoreArrayRead(user->fda, user->lUcont, (const Cmpnts***)&ucont); CHKERRQ(ierr);
2229 ierr = DMDAVecRestoreArrayRead(user->da, user->lNvert, (const PetscReal***)&nvert); CHKERRQ(ierr);
2230
2231 // --- Perform global reductions to get the final flux values ---
2232 ierr = MPI_Allreduce(&localCurrentBoundaryFlux, boundaryFlux, 1, MPI_DOUBLE, MPI_SUM, PETSC_COMM_WORLD); CHKERRQ(ierr);
2233 ierr = MPI_Allreduce(&localAveragePlanarVolumetricFluxTerm, planarAverageFlux, 1, MPI_DOUBLE, MPI_SUM, PETSC_COMM_WORLD); CHKERRQ(ierr);
2234
2236 PetscFunctionReturn(0);
2237}
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
Vec lUcont
Definition variables.h:1197
Here is the call graph for this function:
Here is the caller graph for this function:

◆ Initialize_PeriodicDrivenConstant()

static PetscErrorCode Initialize_PeriodicDrivenConstant ( BoundaryCondition *  self,
BCContext *  ctx 
)
static

Initialize constant forcing data for a periodically driven boundary.

Definition at line 2321 of file BC_Handlers.c.

2322{
2323 PetscErrorCode ierr;
2324 DrivenFluxData *data = (DrivenFluxData*)self->data;
2325 BCFace face_id = ctx->face_id;
2326 UserCtx* user = ctx->user;
2327
2328 PetscFunctionBeginUser;
2330
2331 LOG_ALLOW(LOCAL, LOG_DEBUG, "Initializing PERIODIC_DRIVEN_CONSTANT_FLUX handler on Face %s...\n", BCFaceToString(face_id));
2332
2333 // --- 1. Validation: Ensure the mathematical type is PERIODIC ---
2334 if (user->boundary_faces[face_id].mathematical_type != PERIODIC) {
2335 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT,
2336 "Configuration Error: Handler PERIODIC_DRIVEN_CONSTANT_FLUX on Face %s must be applied to a face with mathematical_type PERIODIC.",
2337 BCFaceToString(face_id));
2338 }
2339
2340 // --- 2. Role Assignment: Determine direction and master status ---
2341 data->isMasterController = PETSC_FALSE;
2342 switch (face_id) {
2343 case BC_FACE_NEG_X: data->direction = 'X'; data->isMasterController = PETSC_TRUE; break;
2344 case BC_FACE_POS_X: data->direction = 'X'; break;
2345 case BC_FACE_NEG_Y: data->direction = 'Y'; data->isMasterController = PETSC_TRUE; break;
2346 case BC_FACE_POS_Y: data->direction = 'Y'; break;
2347 case BC_FACE_NEG_Z: data->direction = 'Z'; data->isMasterController = PETSC_TRUE; break;
2348 case BC_FACE_POS_Z: data->direction = 'Z'; break;
2349 }
2350
2351 // --- 3. Parameter Parsing (Master Controller only) ---
2352 if (data->isMasterController) {
2353 PetscBool found;
2354
2355 // Attempt to read the 'target_flux' parameter from the bcs.run file.
2356 ierr = GetBCParamReal(user->boundary_faces[face_id].params, "target_flux",
2357 &data->targetVolumetricFlux, &found); CHKERRQ(ierr);
2358
2359 // If the required parameter is not found, halt with an informative error.
2360 if (!found) {
2361 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT,
2362 "Configuration Error: Handler PERIODIC_DRIVEN_CONSTANT_FLUX on Face %s requires a 'target_flux' parameter in the bcs file (e.g., target_flux=10.0).",
2363 BCFaceToString(face_id));
2364 }
2365
2366 LOG_ALLOW(GLOBAL, LOG_INFO, "Driven Flow (Dir %c): Constant target volumetric flux set to %le.\n",
2367 data->direction, data->targetVolumetricFlux);
2368
2369 // Store the target flux in the simulation context, where the driven-flow
2370 // controller and its diagnostics read it.
2371 user->simCtx->targetVolumetricFlux = data->targetVolumetricFlux;
2372 // The target is fixed for the run from here on; see the flag's comment in
2373 // variables.h for how initial_flux uses the same latch.
2374 user->simCtx->drivenFluxTargetLatched = PETSC_TRUE;
2375 }
2376
2377 PetscBool trimfound;
2378 // Optional seam-flux enforcement; accepts the deprecated `apply_trim` spelling.
2379 ierr = GetDrivenSeamFluxFlag(user->boundary_faces[face_id].params,
2380 &data->enforceSeamFlux, &trimfound); CHKERRQ(ierr);
2381
2382 if(!trimfound) LOG_ALLOW(GLOBAL,LOG_DEBUG,"Seam-flux enforcement not specified, defaults to %s.\n",data->enforceSeamFlux? "True":"False");
2383 // Enforcing the seam flux adds a trim re-measured every pass, so the pass must repeat.
2384 self->needs_repeat_pass = data->enforceSeamFlux;
2385
2387 PetscFunctionReturn(0);
2388}
Private data structure shared by both periodic driven-flux handlers.
PetscErrorCode GetDrivenSeamFluxFlag(BC_Param *params, PetscBool *value_out, PetscBool *found)
Read the driven-flow seam-flux flag, accepting its deprecated apply_trim spelling.
Definition io.c:888
PetscReal targetVolumetricFlux
Definition variables.h:1024
PetscBool drivenFluxTargetLatched
Definition variables.h:1029
Here is the call graph for this function:
Here is the caller graph for this function:

◆ PreStep_PeriodicDrivenConstant()

static PetscErrorCode PreStep_PeriodicDrivenConstant ( BoundaryCondition *  self,
BCContext *  ctx,
PetscReal *  in,
PetscReal *  out 
)
static

Prepare constant periodic-driving data before the solver step.

Definition at line 2393 of file BC_Handlers.c.

2396{
2397 PetscErrorCode ierr;
2398 DrivenFluxData *data = (DrivenFluxData*)self->data;
2399 UserCtx* user = ctx->user;
2400 SimCtx* simCtx = user->simCtx;
2401
2402 PetscFunctionBeginUser;
2404
2405 // --- Master Check: Only the handler on the negative face performs calculations ---
2406 if (!data->isMasterController) {
2408 PetscFunctionReturn(0);
2409 }
2410
2411 // The controller senses two fluxes; see MeasureDrivenFluxes() for what each
2412 // one is for and why the controller needs both.
2413 char direction = data->direction;
2414 PetscReal globalCurrentBoundaryFlux, globalAveragePlanarVolumetricFlux;
2415 ierr = MeasureDrivenFluxes(user, direction, &globalCurrentBoundaryFlux,
2416 &globalAveragePlanarVolumetricFlux); CHKERRQ(ierr);
2417
2418 // --- Get cross-sectional area using the dedicated geometry function ---
2419 Cmpnts ignored_center;
2420 PetscReal globalBoundaryArea;
2421 BCFace neg_face_id = (direction == 'X') ? BC_FACE_NEG_X : (direction == 'Y') ? BC_FACE_NEG_Y : BC_FACE_NEG_Z;
2422 ierr = CalculateFaceCenterAndArea(user, neg_face_id, &ignored_center, &globalBoundaryArea); CHKERRQ(ierr);
2423
2424 // --- Calculate the two correction terms ---
2425 //
2426 // These are refreshed on DIFFERENT cadences, and the difference matters.
2427 //
2428 // ApplyBoundaryConditions() runs BoundarySystem_ExecuteStep() -- and hence
2429 // this PreStep -- three times per call, and it is itself called once per
2430 // Jameson RK stage under the Picard solver and once per residual evaluation
2431 // under Newton-Krylov. So "per PreStep" is emphatically not "per timestep".
2432 //
2433 // - bulkVelocityCorrection scales the momentum source in ComputeRHS. Both
2434 // momentum solvers are built on it being FROZEN across a timestep: the
2435 // Picard shadow-Jacobian estimate treats the body force as a constant
2436 // forcing with zero velocity Jacobian, and the Newton solve needs a
2437 // source that does not drift between residual evaluations. It is
2438 // therefore computed once per physical step, from the field at the start
2439 // of that step, and held.
2440 //
2441 // - boundaryVelocityCorrection is the tactical trim applied to the
2442 // boundary fluxes in Apply(). It is deliberately re-measured on every
2443 // pass: Apply() accumulates it into Ucont, and re-measuring is what makes
2444 // that accumulation self-limiting as the seam converges. Freezing it
2445 // would make repeated Apply() calls add the same trim over and over.
2446 if (globalBoundaryArea > 1.0e-12) {
2447 if (data->lastBulkCorrectionStep != simCtx->step) {
2448 simCtx->bulkVelocityCorrection = (data->targetVolumetricFlux - globalAveragePlanarVolumetricFlux) / globalBoundaryArea;
2449 simCtx->drivenFluxMeasured = globalAveragePlanarVolumetricFlux;
2450 simCtx->drivenFluxArea = globalBoundaryArea;
2451 data->lastBulkCorrectionStep = simCtx->step;
2452 }
2453 simCtx->boundaryVelocityCorrection = (data->targetVolumetricFlux - globalCurrentBoundaryFlux) / globalBoundaryArea;
2454 } else {
2455 simCtx->bulkVelocityCorrection = 0.0;
2456 simCtx->boundaryVelocityCorrection = 0.0;
2457 data->lastBulkCorrectionStep = simCtx->step;
2458 }
2459
2460 LOG_ALLOW(GLOBAL, LOG_INFO, "Driven Flow Controller Update (Dir %c):\n", data->direction);
2461 LOG_ALLOW(GLOBAL, LOG_INFO, " - Target Volumetric Flux: %.6e\n", data->targetVolumetricFlux);
2462 LOG_ALLOW(GLOBAL, LOG_INFO, " - Avg Planar Volumetric Flux (Stable): %.6e\n", globalAveragePlanarVolumetricFlux);
2463 LOG_ALLOW(GLOBAL, LOG_INFO, " - Boundary Flux (Fast): %.6e\n", globalCurrentBoundaryFlux);
2464 LOG_ALLOW(GLOBAL, LOG_INFO, " - Bulk Velocity Correction: %.6e (For Momentum Source)\n", simCtx->bulkVelocityCorrection);
2465 LOG_ALLOW(GLOBAL, LOG_INFO, " - Boundary Velocity Correction: %.6e (For Boundary Trim)\n", simCtx->boundaryVelocityCorrection);
2466
2467 // Suppress unused parameter warnings for this handler
2468 (void)local_inflow_contribution;
2469 (void)local_outflow_contribution;
2470
2472 PetscFunctionReturn(0);
2473}
static PetscErrorCode MeasureDrivenFluxes(UserCtx *user, char direction, PetscReal *boundaryFlux, PetscReal *planarAverageFlux)
Measure the two volumetric fluxes the driven-flow controller senses.
PetscErrorCode CalculateFaceCenterAndArea(UserCtx *user, BCFace face_id, Cmpnts *face_center, PetscReal *face_area)
Calculates the geometric center and total area of a specified boundary face.
Definition grid.c:1211
PetscReal boundaryVelocityCorrection
Definition variables.h:1031
PetscReal bulkVelocityCorrection
Definition variables.h:1030
PetscReal drivenFluxMeasured
Definition variables.h:1035
PetscReal drivenFluxArea
Definition variables.h:1035
Here is the call graph for this function:
Here is the caller graph for this function:

◆ Apply_PeriodicDrivenConstant()

static PetscErrorCode Apply_PeriodicDrivenConstant ( BoundaryCondition *  self,
BCContext *  ctx 
)
static

Apply the configured constant driving term to the periodic boundary.

Definition at line 2478 of file BC_Handlers.c.

2479{
2480 PetscErrorCode ierr;
2481 DrivenFluxData *data = (DrivenFluxData*)self->data;
2482 UserCtx* user = ctx->user;
2483 BCFace face_id = ctx->face_id;
2484 PetscBool can_service;
2485
2486 PetscFunctionBeginUser;
2488
2489 // Check if this rank owns part of this boundary face
2490 ierr = CanRankServiceFace(&user->info, user->IM, user->JM, user->KM, face_id, &can_service); CHKERRQ(ierr);
2491 if (!can_service) {
2493 PetscFunctionReturn(0);
2494 }
2495
2496 // If the correction is negligible, no work is needed.
2497 if (PetscAbsReal(user->simCtx->boundaryVelocityCorrection) < 1e-12) {
2499 PetscFunctionReturn(0);
2500 }
2501
2502 LOG_ALLOW(LOCAL, LOG_TRACE, "Apply_PeriodicDrivenConstant: Applying boundary trim on Face %s...\n", BCFaceToString(face_id));
2503
2504 // --- Get read/write access to necessary arrays ---
2505 DMDALocalInfo info = user->info;
2506 Cmpnts ***ucont, ***uch, ***csi, ***eta, ***zet;
2507 PetscReal ***nvert;
2508
2509 ierr = DMDAVecGetArray(user->fda, user->Ucont, &ucont); CHKERRQ(ierr);
2510 ierr = DMDAVecGetArray(user->fda, user->Bcs.Uch, &uch); CHKERRQ(ierr);
2511 ierr = DMDAVecGetArrayRead(user->fda, user->lCsi, (const Cmpnts***)&csi); CHKERRQ(ierr);
2512 ierr = DMDAVecGetArrayRead(user->fda, user->lEta, (const Cmpnts***)&eta); CHKERRQ(ierr);
2513 ierr = DMDAVecGetArrayRead(user->fda, user->lZet, (const Cmpnts***)&zet); CHKERRQ(ierr);
2514 ierr = DMDAVecGetArrayRead(user->da, user->lNvert, (const PetscReal***)&nvert); CHKERRQ(ierr);
2515
2516 PetscInt lo[3], hi[3];
2517 GetOwnedInteriorCellBounds(&info, lo, hi);
2518 PetscInt lxs = lo[0], lys = lo[1], lzs = lo[2], lxe = hi[0], lye = hi[1], lze = hi[2];
2519
2520 // --- Apply correction to the appropriate face and velocity component ---
2521 switch (face_id) {
2522 case BC_FACE_NEG_X: case BC_FACE_POS_X: {
2523 PetscInt i_face = (face_id == BC_FACE_NEG_X) ? info.xs : info.mx - 2;
2524 PetscInt i_nvert = (face_id == BC_FACE_NEG_X) ? info.xs + 1 : info.mx - 2;
2525
2526 for (PetscInt k = lzs; k < lze; k++) for (PetscInt j = lys; j < lye; j++) {
2527 if (nvert[k][j][i_nvert] < 0.1) {
2528 PetscReal faceArea = sqrt(csi[k][j][i_face].x*csi[k][j][i_face].x + csi[k][j][i_face].y*csi[k][j][i_face].y + csi[k][j][i_face].z*csi[k][j][i_face].z);
2529 PetscReal fluxTrim = user->simCtx->boundaryVelocityCorrection * faceArea;
2530 if(data->enforceSeamFlux) ucont[k][j][i_face].x += fluxTrim;
2531 uch[k][j][i_face].x = fluxTrim; // Store correction for diagnostics
2532 }
2533 }
2534 } break;
2535
2536 case BC_FACE_NEG_Y: case BC_FACE_POS_Y: {
2537 PetscInt j_face = (face_id == BC_FACE_NEG_Y) ? info.ys : info.my - 2;
2538 PetscInt j_nvert = (face_id == BC_FACE_NEG_Y) ? info.ys + 1 : info.my - 2;
2539
2540 for (PetscInt k = lzs; k < lze; k++) for (PetscInt i = lxs; i < lxe; i++) {
2541 if (nvert[k][j_nvert][i] < 0.1) {
2542 PetscReal faceArea = sqrt(eta[k][j_face][i].x*eta[k][j_face][i].x + eta[k][j_face][i].y*eta[k][j_face][i].y + eta[k][j_face][i].z*eta[k][j_face][i].z);
2543 PetscReal fluxTrim = user->simCtx->boundaryVelocityCorrection * faceArea;
2544 if(data->enforceSeamFlux) ucont[k][j_face][i].y += fluxTrim;
2545 uch[k][j_face][i].y = fluxTrim;
2546 }
2547 }
2548 } break;
2549
2550 case BC_FACE_NEG_Z: case BC_FACE_POS_Z: {
2551 PetscInt k_face = (face_id == BC_FACE_NEG_Z) ? info.zs : info.mz - 2;
2552 PetscInt k_nvert = (face_id == BC_FACE_NEG_Z) ? info.zs + 1 : info.mz - 2;
2553
2554 for (PetscInt j = lys; j < lye; j++) for (PetscInt i = lxs; i < lxe; i++) {
2555 if (nvert[k_nvert][j][i] < 0.1) {
2556 PetscReal faceArea = sqrt(zet[k_face][j][i].x*zet[k_face][j][i].x + zet[k_face][j][i].y*zet[k_face][j][i].y + zet[k_face][j][i].z*zet[k_face][j][i].z);
2557 PetscReal fluxTrim = user->simCtx->boundaryVelocityCorrection * faceArea;
2558 if(data->enforceSeamFlux) ucont[k_face][j][i].z += fluxTrim;
2559 uch[k_face][j][i].z = fluxTrim;
2560 }
2561 }
2562 } break;
2563 }
2564
2565 // --- Restore arrays ---
2566 ierr = DMDAVecRestoreArray(user->fda, user->Ucont, &ucont); CHKERRQ(ierr);
2567 ierr = DMDAVecRestoreArray(user->fda, user->Bcs.Uch, &uch); CHKERRQ(ierr);
2568 ierr = DMDAVecRestoreArrayRead(user->fda, user->lCsi, (const Cmpnts***)&csi); CHKERRQ(ierr);
2569 ierr = DMDAVecRestoreArrayRead(user->fda, user->lEta, (const Cmpnts***)&eta); CHKERRQ(ierr);
2570 ierr = DMDAVecRestoreArrayRead(user->fda, user->lZet, (const Cmpnts***)&zet); CHKERRQ(ierr);
2571 ierr = DMDAVecRestoreArrayRead(user->da, user->lNvert, (const PetscReal***)&nvert); CHKERRQ(ierr);
2572
2574 PetscFunctionReturn(0);
2575}
@ LOG_TRACE
Very fine-grained tracing information for in-depth debugging.
Definition logging.h:33
Vec Uch
Characteristic velocity for boundary conditions.
Definition variables.h:173
Here is the call graph for this function:
Here is the caller graph for this function:

◆ Destroy_PeriodicDrivenConstant()

static PetscErrorCode Destroy_PeriodicDrivenConstant ( BoundaryCondition *  self)
static

Release resources owned by the constant periodic-driving boundary.

Definition at line 2580 of file BC_Handlers.c.

2581{
2582 PetscFunctionBeginUser;
2584
2585 // Check that the handler object and its private data pointer are valid before trying to free.
2586 if (self && self->data) {
2587 // The private data was allocated with PetscNew(), so it must be freed with PetscFree().
2588 PetscFree(self->data);
2589
2590 // It is good practice to nullify the pointer after freeing to prevent
2591 // any accidental use of the dangling pointer (use-after-free).
2592 self->data = NULL;
2593
2594 LOG_ALLOW(LOCAL, LOG_TRACE, "Destroy_PeriodicDrivenConstant: Private data freed successfully.\n");
2595 }
2596
2598 PetscFunctionReturn(0);
2599}
Here is the caller graph for this function:

◆ Create_PeriodicDrivenConstant()

PetscErrorCode Create_PeriodicDrivenConstant ( BoundaryCondition *  bc)

Implementation of Create_PeriodicDrivenConstant().

Configures a BoundaryCondition object for periodic driven-flow forcing.

See also
Create_PeriodicDrivenConstant()

Definition at line 2278 of file BC_Handlers.c.

2279{
2280 PetscErrorCode ierr;
2281 PetscFunctionBeginUser;
2283
2284 PetscCheck(bc, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "BoundaryCondition is NULL");
2285
2286 // --- Allocate the private data structure ---
2287 DrivenFluxData *data = NULL;
2288 ierr = PetscNew(&data); CHKERRQ(ierr);
2289 // Initialize fields to safe default values
2290 data->direction = ' ';
2291 data->targetVolumetricFlux = 0.0;
2292 data->isMasterController = PETSC_FALSE;
2293 data->enforceSeamFlux = PETSC_FALSE;
2294 data->lastBulkCorrectionStep = -1;
2295
2296 // Attach the private data to the generic handler object
2297 bc->data = (void*)data;
2298
2299 // --- Configure the handler's properties and methods ---
2300
2301 // Set priority: Using BC_PRIORITY_INLET ensures this handler's PreStep runs
2302 // before other handlers (like outlets) that might depend on its calculations.
2303 // It is the caller's responsibility that there are no Inlets called along with driven periodic to avoid clash.
2305
2306 // Assign the function pointers to the implementations in this file.
2310 bc->PostStep = NULL; // This handler has no action after the main solver step.
2311 bc->UpdateUbcs = NULL; // The boundary value is not flow-dependent (it's periodic).
2313
2315 PetscFunctionReturn(0);
2316}
PetscBool enforceSeamFlux
PetscBool isMasterController
PetscInt lastBulkCorrectionStep
static PetscErrorCode Apply_PeriodicDrivenConstant(BoundaryCondition *self, BCContext *ctx)
Apply the configured constant driving term to the periodic boundary.
static PetscErrorCode Initialize_PeriodicDrivenConstant(BoundaryCondition *self, BCContext *ctx)
Initialize constant forcing data for a periodically driven boundary.
static PetscErrorCode Destroy_PeriodicDrivenConstant(BoundaryCondition *self)
Release resources owned by the constant periodic-driving boundary.
static PetscErrorCode PreStep_PeriodicDrivenConstant(BoundaryCondition *self, BCContext *ctx, PetscReal *in, PetscReal *out)
Prepare constant periodic-driving data before the solver step.
PetscReal targetVolumetricFlux
Here is the call graph for this function:
Here is the caller graph for this function:

◆ Initialize_PeriodicDrivenInitial()

static PetscErrorCode Initialize_PeriodicDrivenInitial ( BoundaryCondition *  self,
BCContext *  ctx 
)
static

Initialize forcing data for a periodic boundary driven to its initial flux.

Note
The target itself is NOT measured here. Boundary handlers are initialized before InitializeEulerianState() runs, so at this point Ucont still holds zeros. The measurement is deferred to the first PreStep, by which time either the initial condition has been applied or the restart target has been restored from the checkpoint manifest.

Definition at line 2673 of file BC_Handlers.c.

2674{
2675 PetscErrorCode ierr;
2676 DrivenFluxData *data = (DrivenFluxData*)self->data;
2677 BCFace face_id = ctx->face_id;
2678 UserCtx* user = ctx->user;
2679
2680 PetscFunctionBeginUser;
2682
2683 LOG_ALLOW(LOCAL, LOG_DEBUG, "Initializing PERIODIC_DRIVEN_INITIAL_FLUX handler on Face %s...\n", BCFaceToString(face_id));
2684
2685 // --- 1. Validation: Ensure the mathematical type is PERIODIC ---
2686 if (user->boundary_faces[face_id].mathematical_type != PERIODIC) {
2687 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT,
2688 "Configuration Error: Handler PERIODIC_DRIVEN_INITIAL_FLUX on Face %s must be applied to a face with mathematical_type PERIODIC.",
2689 BCFaceToString(face_id));
2690 }
2691
2692 // --- 2. Role Assignment: Determine direction and master status ---
2693 data->isMasterController = PETSC_FALSE;
2694 switch (face_id) {
2695 case BC_FACE_NEG_X: data->direction = 'X'; data->isMasterController = PETSC_TRUE; break;
2696 case BC_FACE_POS_X: data->direction = 'X'; break;
2697 case BC_FACE_NEG_Y: data->direction = 'Y'; data->isMasterController = PETSC_TRUE; break;
2698 case BC_FACE_POS_Y: data->direction = 'Y'; break;
2699 case BC_FACE_NEG_Z: data->direction = 'Z'; data->isMasterController = PETSC_TRUE; break;
2700 case BC_FACE_POS_Z: data->direction = 'Z'; break;
2701 }
2702
2703 // --- 3. Parameter Parsing (Master Controller only) ---
2704 if (data->isMasterController) {
2705 PetscReal unused_flux;
2706 PetscBool found;
2707
2708 // This handler derives its own target, so an explicit one is a config error
2709 // rather than something to silently ignore. Users who want to prescribe the
2710 // flux should select the `constant_flux` handler instead.
2711 ierr = GetBCParamReal(user->boundary_faces[face_id].params, "target_flux",
2712 &unused_flux, &found); CHKERRQ(ierr);
2713 if (found) {
2714 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT,
2715 "Configuration Error: Handler PERIODIC_DRIVEN_INITIAL_FLUX on Face %s takes no 'target_flux' parameter; "
2716 "it measures the flux of the initial condition and holds that. Use handler 'constant_flux' to prescribe a target.",
2717 BCFaceToString(face_id));
2718 }
2719
2720 LOG_ALLOW(GLOBAL, LOG_INFO, "Driven Flow (Dir %c): target volumetric flux will be latched from the initial state.\n",
2721 data->direction);
2722 }
2723
2724 PetscBool trimfound;
2725 // Optional seam-flux enforcement; accepts the deprecated `apply_trim` spelling.
2726 ierr = GetDrivenSeamFluxFlag(user->boundary_faces[face_id].params,
2727 &data->enforceSeamFlux, &trimfound); CHKERRQ(ierr);
2728
2729 if(!trimfound) LOG_ALLOW(GLOBAL,LOG_DEBUG,"Seam-flux enforcement not specified, defaults to %s.\n",data->enforceSeamFlux? "True":"False");
2730 // Enforcing the seam flux adds a trim re-measured every pass, so the pass must repeat.
2731 self->needs_repeat_pass = data->enforceSeamFlux;
2732
2734 PetscFunctionReturn(0);
2735}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ PreStep_PeriodicDrivenInitial()

static PetscErrorCode PreStep_PeriodicDrivenInitial ( BoundaryCondition *  self,
BCContext *  ctx,
PetscReal *  local_inflow_contribution,
PetscReal *  local_outflow_contribution 
)
static

Latch the initial-state flux once, then drive to it like a constant target.

The latch is one-shot and guarded by simCtx->drivenFluxTargetLatched:

  • Fresh start: the flag is false and Ucont now holds the initial condition, so the plane-averaged flux is measured and stored.
  • Restart: ReadSimulationFields() restored both the target and the flag from the checkpoint manifest, so the original target survives instead of being re-measured from a drifted field.

Definition at line 2747 of file BC_Handlers.c.

2750{
2751 PetscErrorCode ierr;
2752 DrivenFluxData *data = (DrivenFluxData*)self->data;
2753 SimCtx* simCtx = ctx->user->simCtx;
2754
2755 PetscFunctionBeginUser;
2757
2758 if (data->isMasterController) {
2759 if (!simCtx->drivenFluxTargetLatched) {
2760 PetscReal boundaryFlux, planarAverageFlux;
2761
2762 /* Boundary handlers are also exercised once during setup, from
2763 * FinalizeBlockState(), and at that point the initial condition has
2764 * been written to Ucont but not yet scattered into the ghosted
2765 * lUcont that MeasureDrivenFluxes() reads. Latching there would
2766 * record a target of zero. Setup runs with step == StartStep, so
2767 * wait for the first PreStep of the first real timestep: by then
2768 * lUcont holds the initial condition (or, on a restart, the state
2769 * the restored target already describes). Do no work at all until
2770 * then, so no bogus correction is derived from a zero target. */
2771 if (simCtx->step <= simCtx->StartStep) {
2772 simCtx->bulkVelocityCorrection = 0.0;
2773 simCtx->boundaryVelocityCorrection = 0.0;
2775 PetscFunctionReturn(0);
2776 }
2777
2778 ierr = MeasureDrivenFluxes(ctx->user, data->direction,
2779 &boundaryFlux, &planarAverageFlux); CHKERRQ(ierr);
2780
2781 simCtx->targetVolumetricFlux = planarAverageFlux;
2782 simCtx->drivenFluxTargetLatched = PETSC_TRUE;
2783
2785 "Driven Flow (Dir %c): latched initial volumetric flux %.6e as the target.\n",
2786 data->direction, planarAverageFlux);
2787 }
2788 // Keep the handler's copy in step with the authoritative value in SimCtx,
2789 // which is also where a restart deposits the restored target.
2790 data->targetVolumetricFlux = simCtx->targetVolumetricFlux;
2791 }
2792
2793 ierr = PreStep_PeriodicDrivenConstant(self, ctx,
2794 local_inflow_contribution,
2795 local_outflow_contribution); CHKERRQ(ierr);
2796
2798 PetscFunctionReturn(0);
2799}
PetscInt StartStep
Definition variables.h:926
Here is the call graph for this function:
Here is the caller graph for this function:

◆ Create_PeriodicDrivenInitial()

PetscErrorCode Create_PeriodicDrivenInitial ( BoundaryCondition *  bc)

Implementation of Create_PeriodicDrivenInitial().

Configures a BoundaryCondition object for initial-flux periodic driving.

See also
Create_PeriodicDrivenInitial()

Definition at line 2626 of file BC_Handlers.c.

2627{
2628 PetscErrorCode ierr;
2629 PetscFunctionBeginUser;
2631
2632 PetscCheck(bc, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "BoundaryCondition is NULL");
2633
2634 // --- Allocate the private data structure ---
2635 DrivenFluxData *data = NULL;
2636 ierr = PetscNew(&data); CHKERRQ(ierr);
2637 // Initialize fields to safe default values
2638 data->direction = ' ';
2639 data->targetVolumetricFlux = 0.0;
2640 data->isMasterController = PETSC_FALSE;
2641 data->enforceSeamFlux = PETSC_FALSE;
2642 data->lastBulkCorrectionStep = -1;
2643
2644 // Attach the private data to the generic handler object
2645 bc->data = (void*)data;
2646
2647 // --- Configure the handler's properties and methods ---
2648
2649 // Same priority reasoning as the constant-flux handler: PreStep must run
2650 // before any handler that depends on the controller's corrections.
2652
2655 bc->Apply = Apply_PeriodicDrivenConstant; // Boundary trim is target-agnostic.
2656 bc->PostStep = NULL; // This handler has no action after the main solver step.
2657 bc->UpdateUbcs = NULL; // The boundary value is not flow-dependent (it's periodic).
2658 bc->Destroy = Destroy_PeriodicDrivenConstant; // Same private data layout.
2659
2661 PetscFunctionReturn(0);
2662}
static PetscErrorCode Initialize_PeriodicDrivenInitial(BoundaryCondition *self, BCContext *ctx)
Initialize forcing data for a periodic boundary driven to its initial flux.
static PetscErrorCode PreStep_PeriodicDrivenInitial(BoundaryCondition *self, BCContext *ctx, PetscReal *in, PetscReal *out)
Latch the initial-state flux once, then drive to it like a constant target.
Here is the call graph for this function:
Here is the caller graph for this function: