PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
BodyForces.c
Go to the documentation of this file.
1#include "BodyForces.h"
2#include "io.h"
3
4
5//////////////////////////////////////////////
6// DRIVEN CHANNEL FLOW FORCE(EQUIVALENT) TERM
7/////////////////////////////////////////////
8
9/**
10 * @brief The axis a driven periodic handler drives, or ' ' when none is configured.
11 * @param[in] user Block whose boundary faces are inspected.
12 * @return 'X', 'Y', 'Z', or ' '.
13 */
14static char DrivenFlowDirection(const UserCtx *user)
15{
17 for (int i = 0; i < 6; i++) {
18 const BCHandlerType handler_type = user->boundary_faces[i].handler_type;
19 if (handler_type == BC_HANDLER_PERIODIC_DRIVEN_CONSTANT_FLUX ||
21 switch (user->boundary_faces[i].face_id) {
22 case BC_FACE_NEG_X: case BC_FACE_POS_X: PROFILE_HELPER_END; return 'X';
23 case BC_FACE_NEG_Y: case BC_FACE_POS_Y: PROFILE_HELPER_END; return 'Y';
24 case BC_FACE_NEG_Z: case BC_FACE_POS_Z: PROFILE_HELPER_END; return 'Z';
25 }
27 return ' ';
28 }
29 }
31 return ' ';
32}
33
34/**
35 * @brief Internal helper implementation: `ComputeDrivenChannelFlowSource()`.
36 * @details Local to this translation unit.
37 */
38PetscErrorCode ComputeDrivenChannelFlowSource(UserCtx *user, Vec Rct)
39{
40 PetscErrorCode ierr;
41 SimCtx *simCtx = user->simCtx;
42 PetscFunctionBeginUser;
44
45 // --- Step 1: Discover if and where a driven flow is active ---
46 const char drivenDirection = DrivenFlowDirection(user); // ' ' when none is configured
47
48 // --- Step 2: Early exit if no driven flow is configured ---
49 if (drivenDirection == ' ') {
51 PetscFunctionReturn(0);
52 }
53
54 // --- Step 3: Get the control signal and exit if no correction is needed ---
55 PetscReal bulkVelocityCorrection = simCtx->bulkVelocityCorrection;
56 if (PetscAbsReal(bulkVelocityCorrection) < 1.0e-12) {
58 PetscFunctionReturn(0);
59 }
60
61 LOG_ALLOW(LOCAL, LOG_DEBUG, "Rank %d, Block %" PetscInt_FMT ": Applying driven flow momentum source in '%c' direction.\n",
62 simCtx->rank, user->_this, drivenDirection);
63 LOG_ALLOW(LOCAL, LOG_DEBUG, " - Received Bulk Velocity Correction: %le\n", bulkVelocityCorrection);
64
65 // --- Step 4: Setup for calculation ---
66 DMDALocalInfo info = user->info;
67 PetscInt i, j, k;
68 PetscInt lo[3], hi[3];
69 GetOwnedInteriorCellBounds(&info, lo, hi);
70 PetscInt lxs = lo[0], lys = lo[1], lzs = lo[2], lxe = hi[0], lye = hi[1], lze = hi[2];
71
72 Cmpnts ***rct, ***csi, ***eta, ***zet;
73 PetscReal ***nvert;
74 ierr = DMDAVecGetArray(user->fda, Rct, &rct); CHKERRQ(ierr);
75 ierr = DMDAVecGetArrayRead(user->fda, user->lCsi, (const Cmpnts***)&csi); CHKERRQ(ierr);
76 ierr = DMDAVecGetArrayRead(user->fda, user->lEta, (const Cmpnts***)&eta); CHKERRQ(ierr);
77 ierr = DMDAVecGetArrayRead(user->fda, user->lZet, (const Cmpnts***)&zet); CHKERRQ(ierr);
78 ierr = DMDAVecGetArrayRead(user->da, user->lNvert, (const PetscReal***)&nvert); CHKERRQ(ierr);
79
80 // Calculate the driving force magnitude for the current timestep, smoothed
81 // with the value from the previous step for stability.
82 //
83 // ONCE PER PHYSICAL STEP, NOT ONCE PER CALL. This function runs from
84 // ComputeRHS, which executes once per Jameson RK stage under the Picard
85 // solver and once per residual evaluation under Newton-Krylov. The smoothing
86 // below carries state in simCtx across calls, so advancing it every call
87 // would walk the applied force toward its target within a single timestep
88 // (0.5, then 0.75, then 0.875 ... of the way there). The force would then
89 // depend on how many residual evaluations preceded it - history dependence
90 // that MomentumNewtonKrylov_FormResidual() explicitly forbids, and that
91 // breaks the constant-forcing assumption behind the Picard shadow-Jacobian
92 // estimate. Resolve it once for the step and reuse it thereafter.
93 const PetscReal forceScalingFactor = simCtx->forceScalingFactor;
94 PetscReal drivingForceMagnitude;
95
96 if (simCtx->drivingForceStep != simCtx->step) {
97 const PetscReal targetForce = (bulkVelocityCorrection / simCtx->dt / 1.0 * COEF_TIME_ACCURACY); // replaced simCtx->st with 1.0.
98 drivingForceMagnitude = (simCtx->drivingForceMagnitude * 0.5) + (targetForce * 0.5);
99 simCtx->drivingForceMagnitude = drivingForceMagnitude;
100 simCtx->drivingForceStep = simCtx->step;
101 } else {
102 drivingForceMagnitude = simCtx->drivingForceMagnitude;
103 }
104
105 LOG_ALLOW(GLOBAL, LOG_DEBUG, " - Previous driving force: %le\n", simCtx->drivingForceMagnitude);
106 LOG_ALLOW(GLOBAL, LOG_DEBUG, " - New smoothed driving force: %le\n", drivingForceMagnitude);
107 LOG_ALLOW(GLOBAL, LOG_DEBUG, " - Force scaling factor: %f\n", simCtx->forceScalingFactor);
108
109 PetscBool hasLoggedApplication = PETSC_FALSE; // Flag to log details only once per rank.
110 // --- Step 5: Apply the momentum source to the correct RHS component ---
111 for (k = lzs; k < lze; k++) {
112 for (j = lys; j < lye; j++) {
113 for (i = lxs; i < lxe; i++) {
114 if (nvert[k][j][i] < 0.1) { // Apply only to fluid cells
115 PetscReal faceArea = 0.0;
116 PetscReal momentumSource = 0.0;
117
118 switch (drivenDirection) {
119 case 'X':
120 faceArea = sqrt(csi[k][j][i].x * csi[k][j][i].x + csi[k][j][i].y * csi[k][j][i].y + csi[k][j][i].z * csi[k][j][i].z);
121 momentumSource = drivingForceMagnitude * forceScalingFactor * faceArea;
122 rct[k][j][i].x += momentumSource;
123
124 // Log details for the very first point where force is applied on this rank.
125 if (!hasLoggedApplication) {
126 LOG_ALLOW(LOCAL, LOG_DEBUG,"Body Force %le added at (%" PetscInt_FMT ",%" PetscInt_FMT ",%" PetscInt_FMT ")\n",momentumSource, k, j, i);
127 hasLoggedApplication = PETSC_TRUE;
128 }
129 break;
130 case 'Y':
131 faceArea = sqrt(eta[k][j][i].x * eta[k][j][i].x + eta[k][j][i].y * eta[k][j][i].y + eta[k][j][i].z * eta[k][j][i].z);
132 momentumSource = drivingForceMagnitude * forceScalingFactor * faceArea;
133 rct[k][j][i].y += momentumSource;
134
135 // Log details for the very first point where force is applied on this rank.
136 if (!hasLoggedApplication) {
137 LOG_ALLOW(LOCAL, LOG_DEBUG,"Body Force %le added at (%" PetscInt_FMT ",%" PetscInt_FMT ",%" PetscInt_FMT ")\n",momentumSource, k, j, i);
138 hasLoggedApplication = PETSC_TRUE;
139 }
140 break;
141 case 'Z':
142 faceArea = sqrt(zet[k][j][i].x * zet[k][j][i].x + zet[k][j][i].y * zet[k][j][i].y + zet[k][j][i].z * zet[k][j][i].z);
143 momentumSource = drivingForceMagnitude * forceScalingFactor * faceArea;
144 rct[k][j][i].z += momentumSource;
145
146 // Log details for the very first point where force is applied on this rank.
147 if (!hasLoggedApplication) {
148 LOG_ALLOW(LOCAL, LOG_DEBUG,"Body Force %le added at (%" PetscInt_FMT ",%" PetscInt_FMT ",%" PetscInt_FMT ")\n",momentumSource, k, j, i);
149 hasLoggedApplication = PETSC_TRUE;
150 }
151 break;
152 }
153 }
154 }
155 }
156 }
157
158 // --- Step 6: Restore arrays ---
159 ierr = DMDAVecRestoreArray(user->fda, Rct, &rct); CHKERRQ(ierr);
160 ierr = DMDAVecRestoreArrayRead(user->fda, user->lCsi, (const Cmpnts***)&csi); CHKERRQ(ierr);
161 ierr = DMDAVecRestoreArrayRead(user->fda, user->lEta, (const Cmpnts***)&eta); CHKERRQ(ierr);
162 ierr = DMDAVecRestoreArrayRead(user->fda, user->lZet, (const Cmpnts***)&zet); CHKERRQ(ierr);
163 ierr = DMDAVecRestoreArrayRead(user->da, user->lNvert, (const PetscReal***)&nvert); CHKERRQ(ierr);
164
166 PetscFunctionReturn(0);
167}
168
169/**
170 * @brief Implementation of \ref LogDrivenFlowDiagnostics().
171 * @details Full API contract is documented with the header declaration in
172 * `include/BodyForces.h`.
173 */
175{
176 SimCtx *simCtx = user->simCtx;
177 const char direction = DrivenFlowDirection(user);
178 FILE *file = NULL;
179
180 PetscFunctionBeginUser;
182
183 /* The controller state is global: every rank holds the same values, set from the
184 controller's collective reductions, so rank 0 reports it once per step. */
185 if (direction == ' ' || user->_this != 0 || simCtx->rank != 0) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
186
187 /* What the momentum equation actually received this step. The source is resolved
188 once per step and skipped entirely when the correction is negligible, in which
189 case the smoothed magnitude is stale and nothing was applied. */
190 const PetscBool applied = (PetscBool)(simCtx->drivingForceStep == simCtx->step &&
191 PetscAbsReal(simCtx->bulkVelocityCorrection) >= 1.0e-12);
192 const PetscReal acceleration = applied ? simCtx->drivingForceMagnitude * simCtx->forceScalingFactor : 0.0;
193 const PetscReal area = simCtx->drivenFluxArea;
194 const PetscReal bulk_velocity = (area > 0.0) ? simCtx->drivenFluxMeasured / area : 0.0;
195 PetscReal physical_time = 0.0;
196
197 PetscCall(PicurvPhysicalTime(simCtx, simCtx->ti, &physical_time));
198 PetscCall(PicurvOpenDiagnosticsCsv(simCtx, simCtx->analysis_dir, "driven_flow.csv",
199 "step,time,direction,target_flux,measured_flux,cross_section_area,"
200 "bulk_velocity,bulk_velocity_correction,driving_acceleration,physical_time",
201 &file));
202 fprintf(file, "%d,%.6e,%c,%.10e,%.10e,%.10e,%.10e,%.6e,%.10e,%.6e\n",
203 (int)simCtx->step, (double)simCtx->ti, direction,
204 (double)simCtx->targetVolumetricFlux, (double)simCtx->drivenFluxMeasured, (double)area,
205 (double)bulk_velocity, (double)simCtx->bulkVelocityCorrection, (double)acceleration,
206 (double)physical_time);
207 PetscCheck(fclose(file) == 0, PETSC_COMM_SELF, PETSC_ERR_FILE_WRITE,
208 "Unable to close the driven-flow diagnostics file.");
210 PetscFunctionReturn(0);
211}
PetscErrorCode LogDrivenFlowDiagnostics(UserCtx *user)
Implementation of LogDrivenFlowDiagnostics().
Definition BodyForces.c:174
PetscErrorCode ComputeDrivenChannelFlowSource(UserCtx *user, Vec Rct)
Internal helper implementation: ComputeDrivenChannelFlowSource().
Definition BodyForces.c:38
static char DrivenFlowDirection(const UserCtx *user)
The axis a driven periodic handler drives, or ' ' when none is configured.
Definition BodyForces.c:14
Momentum source terms added to the contravariant RHS.
Public interface for data input/output routines.
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
#define LOCAL
Logging scope definitions for controlling message output.
Definition logging.h:45
#define GLOBAL
Scope for global logging across all processes.
Definition logging.h:46
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
#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_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
#define PROFILE_FUNCTION_END
Marks the end of a profiled code block.
Definition logging.h:1029
@ 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
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
PetscMPIInt rank
Definition variables.h:919
BoundaryFaceConfig boundary_faces[6]
Definition variables.h:1182
PetscReal targetVolumetricFlux
Definition variables.h:1024
Vec lNvert
Definition variables.h:1197
PetscReal forceScalingFactor
Definition variables.h:1018
SimCtx * simCtx
Back-pointer to the master simulation context.
Definition variables.h:1160
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
PetscInt _this
Definition variables.h:1175
PetscReal dt
Definition variables.h:933
PetscReal bulkVelocityCorrection
Definition variables.h:1030
PetscScalar x
Definition variables.h:145
char analysis_dir[PETSC_MAX_PATH_LEN]
Definition variables.h:942
PetscScalar z
Definition variables.h:145
PetscInt drivingForceStep
Definition variables.h:1023
PetscReal drivenFluxMeasured
Definition variables.h:1035
PetscInt step
Definition variables.h:924
PetscReal drivenFluxArea
Definition variables.h:1035
DMDALocalInfo info
Definition variables.h:1169
PetscScalar y
Definition variables.h:145
PetscReal ti
Definition variables.h:925
#define COEF_TIME_ACCURACY
Coefficient controlling the temporal accuracy scheme (e.g., 1.5 for 2nd Order Backward Difference).
Definition variables.h:96
PetscReal drivingForceMagnitude
Definition variables.h:1018
@ 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
A 3D point or vector with PetscScalar components.
Definition variables.h:144
The master context for the entire simulation.
Definition variables.h:916
User-defined context containing data specific to a single computational grid level.
Definition variables.h:1157