PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
Data Structures | Macros | Enumerations | Functions
momentumsolvers.h File Reference
#include "variables.h"
#include "logging.h"
#include "rhs.h"
#include "Boundaries.h"
Include dependency graph for momentumsolvers.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  MomStabilityReport
 Diagnostic report produced by ComputeMomentumStabilityEstimate(). More...
 

Macros

#define MomentumSolver_DualTime_Picard_RK4   MomentumSolver_DualTime_Picard_JamesonRK
 

Enumerations

enum  MomStabCandidate { MOM_STAB_CAND_B = 0 , MOM_STAB_CAND_C = 1 , MOM_STAB_CAND_D = 2 }
 Convective-estimate candidate selector. More...
 
enum  MomStabLimiter { MOM_STAB_LIMITER_TIME = 0 , MOM_STAB_LIMITER_CONVECTION = 1 , MOM_STAB_LIMITER_VISCOSITY = 2 }
 Dominant stiffness contributor at the controlling cell. More...
 

Functions

PetscErrorCode MomentumSolver_Explicit_RungeKutta4 (UserCtx *user, IBMNodes *ibm, FSInfo *fsi)
 Advances the momentum equations using an explicit 4th-order Runge-Kutta scheme.
 
PetscErrorCode MomentumSolver_NewtonKrylov (UserCtx *user, IBMNodes *ibm, FSInfo *fsi)
 Solves one physical momentum step with matrix-free Newton–Krylov.
 
PetscErrorCode MomentumSolver_NewtonKrylov_Destroy (UserCtx *user)
 Releases the Newton–Krylov solve context MomentumSolver_NewtonKrylov() keeps for the run.
 
PetscErrorCode MomentumSolver_DualTime_Picard_JamesonRK (UserCtx *user, IBMNodes *ibm, FSInfo *fsi)
 Solves the momentum equations using dual-time Picard iteration with Jameson RK smoothing.
 
PetscBool MomentumUsesBDF2 (SimCtx *simCtx)
 Returns whether the current physical step uses the BDF2 discretization.
 
PetscReal MomentumBDFCoefficient (SimCtx *simCtx)
 Returns the BDF physical-time coefficient a0 for the current step.
 
PetscErrorCode ComputeTotalResidual (UserCtx *user)
 Computes the shared spatial-plus-BDF momentum residual in user->Rhs.
 
PetscErrorCode ComputeMomentumStabilityEstimate (UserCtx *user, PetscInt block_number, PetscReal dt, MomStabCandidate candidate, MomStabilityReport *rep)
 Compute the momentum pseudo-time stability estimate (shadow/diagnostic).
 
PetscInt MomCellActiveRows (PetscReal ***nvert, PetscInt k, PetscInt j, PetscInt i, PetscInt mx, PetscInt my, PetscInt mz, PetscBool np_x1, PetscBool np_y1, PetscBool np_z1, PetscInt twoD)
 Active staggered-momentum row mask for a cell (exposed for unit testing).
 

Data Structure Documentation

◆ MomStabilityReport

struct MomStabilityReport

Diagnostic report produced by ComputeMomentumStabilityEstimate().

This is a PRACTICAL CONSERVATIVE STABILITY ESTIMATE (operator-scaled pseudo-time estimate), not a proven spectral radius. All lambda_* are global maxima in [1/s].

Definition at line 185 of file momentumsolvers.h.

Data Fields
PetscReal lambda
PetscReal lambda_t
PetscReal lambda_c
PetscReal lambda_v
PetscReal lambda_B
PetscReal lambda_C
PetscReal lambda_D
PetscInt ci
PetscInt cj
PetscInt ck
PetscInt cblock
PetscInt cclass
PetscInt one_sided
PetscInt active_cells
PetscBool estimate_incomplete
MomStabLimiter limiter

Macro Definition Documentation

◆ MomentumSolver_DualTime_Picard_RK4

#define MomentumSolver_DualTime_Picard_RK4   MomentumSolver_DualTime_Picard_JamesonRK

Enumeration Type Documentation

◆ MomStabCandidate

Convective-estimate candidate selector.

See ComputeMomentumStabilityEstimate().

B: six-face transport scale (f_c * Aj * sum|U_f| / 2). C: B + frozen-advector discrete-divergence diagonal term. D: C + nonlinear velocity-gradient row-norm term (lambda_grad_u).

Enumerator
MOM_STAB_CAND_B 
MOM_STAB_CAND_C 
MOM_STAB_CAND_D 

Definition at line 164 of file momentumsolvers.h.

164 {
165 MOM_STAB_CAND_B = 0,
166 MOM_STAB_CAND_C = 1,
MomStabCandidate
Convective-estimate candidate selector.
@ MOM_STAB_CAND_B
@ MOM_STAB_CAND_C
@ MOM_STAB_CAND_D

◆ MomStabLimiter

Dominant stiffness contributor at the controlling cell.

Enumerator
MOM_STAB_LIMITER_TIME 
MOM_STAB_LIMITER_CONVECTION 
MOM_STAB_LIMITER_VISCOSITY 

Definition at line 173 of file momentumsolvers.h.

173 {
MomStabLimiter
Dominant stiffness contributor at the controlling cell.
@ MOM_STAB_LIMITER_CONVECTION
@ MOM_STAB_LIMITER_VISCOSITY
@ MOM_STAB_LIMITER_TIME

Function Documentation

◆ MomentumSolver_Explicit_RungeKutta4()

PetscErrorCode MomentumSolver_Explicit_RungeKutta4 ( UserCtx *  user,
IBMNodes *  ibm,
FSInfo *  fsi 
)
extern

Advances the momentum equations using an explicit 4th-order Runge-Kutta scheme.

Parameters
userArray of UserCtx structs for all blocks.
ibm(Optional) Pointer to IBM data. Pass NULL if disabled.
fsi(Optional) Pointer to FSI data. Pass NULL if disabled.
Returns
PetscErrorCode 0 on success.
Note
Testing status: The explicit RK path remains on the near-term backlog for direct positive-path bespoke coverage; today it is weaker than the dual-time path in the test surface.

Advances the momentum equations using an explicit 4th-order Runge-Kutta scheme.

See also
MomentumSolver_Explicit_RungeKutta4()

Definition at line 97 of file momentumsolvers.c.

98{
99 PetscErrorCode ierr;
100 (void)fsi;
101 // --- Context Acquisition ---
102 // Get the master simulation context from the first block's UserCtx.
103 // This is the bridge to access all former global variables.
104 SimCtx *simCtx = user[0].simCtx;
105 PetscReal dt = simCtx->dt;
106 //PetscReal st = simCtx->st;
107 PetscInt istage;
108 PetscReal alfa[] = {0.25, 1.0/3.0, 0.5, 1.0};
109
110 PetscFunctionBeginUser;
111
113
114 LOG_ALLOW(GLOBAL, LOG_INFO, "Executing explicit momentum solver (Runge-Kutta) for %" PetscInt_FMT " block(s).\n",simCtx->block_number);
115
116 // --- 1. Pre-Loop Initialization (Legacy Logic) ---
117 // This block prepares boundary conditions and allocates the RHS vector for all blocks
118 // before the main RK loop begins. This logic is preserved from the original code.
119 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Preparing all blocks for Runge-Kutta solve...\n");
120 for (PetscInt bi = 0; bi < simCtx->block_number; bi++) {
121
122 ierr = ApplyBoundaryConditions(&user[bi]); CHKERRQ(ierr);
123
124 /*
125 // Immersed boundary interpolation (if enabled)
126 if (simCtx->immersed) {
127 LOG_ALLOW(LOCAL, LOG_DEBUG, " Performing pre-RK IBM interpolation for block %d.\n", bi);
128 for (PetscInt ibi = 0; ibi < simCtx->NumberOfBodies; ibi++) {
129 // The 'ibm' and 'fsi' pointers are passed directly from FlowSolver
130 ierr = ibm_interpolation_advanced(&user[bi], &ibm[ibi], ibi, 1); CHKERRQ(ierr);
131 }
132 }
133 */
134
135 // Allocate the persistent RHS vector for this block's context
136 ierr = VecDuplicate(user[bi].Ucont, &user[bi].Rhs); CHKERRQ(ierr);
137 }
138 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Pre-loop initialization complete.\n");
139
140 // --- 2. Main Runge-Kutta Loop ---
141 // The legacy code had an outer `pseudot` loop that only ran once. We preserve it.
142 for (PetscInt pseudot = 0; pseudot < 1; pseudot++) {
143 // Loop over each block to perform the RK stages
144 for (PetscInt bi = 0; bi < simCtx->block_number; bi++) {
145 for (istage = 0; istage < 4; istage++) {
146 LOG_ALLOW(LOCAL, LOG_DEBUG, " Block %" PetscInt_FMT ", RK Stage %" PetscInt_FMT " (alpha=%.4f)...\n", bi, istage, alfa[istage]);
147
148 // a. Calculate the Right-Hand Side (RHS) of the momentum equation.
149 ierr = ComputeRHS(&user[bi], user[bi].Rhs); CHKERRQ(ierr);
150
151 // b. Advance Ucont to the next intermediate stage using the RK coefficient.
152 // Ucont_new = Ucont_old + alpha * dt * RHS
153 ierr = VecWAXPY(user[bi].Ucont, alfa[istage] * dt, user[bi].Rhs, user[bi].Ucont_o); CHKERRQ(ierr);
154
155 // c. Synchronize periodic endpoints and local ghosts for the new intermediate Ucont.
156 const FieldId staggered_fields[] = {FIELD_ID_UCONT};
157 ierr = SynchronizePeriodicStaggeredFields(&user[bi], 1, staggered_fields); CHKERRQ(ierr);
158
159 // d. Re-apply boundary conditions for the new intermediate velocity.
160 // This is crucial for the stability and accuracy of the multi-stage scheme.
161 ierr = ApplyBoundaryConditions(&user[bi]); CHKERRQ(ierr);
162
163 } // End of RK stages for one block
164
165 /* Nothing limits dt on this path, so an unstable step only showed up later,
166 as a non-finite Poisson solve blamed on the multigrid depth. Name the
167 actual cause where it arises. */
168 {
169 /* Divergence usually overflows the Poisson right-hand side before the
170 velocity itself stops being finite, so a jump no flow can make in one
171 step is treated the same as a non-finite value. */
172 PetscReal ucont_max = 0.0, ucont_start = 0.0;
173 ierr = VecNorm(user[bi].Ucont, NORM_INFINITY, &ucont_max); CHKERRQ(ierr);
174 ierr = VecNorm(user[bi].Ucont_o, NORM_INFINITY, &ucont_start); CHKERRQ(ierr);
175 PetscCheck(!PetscIsInfOrNanReal(ucont_max) && ucont_max <= 1.0e10 * (1.0 + ucont_start),
176 PETSC_COMM_WORLD, PETSC_ERR_FP,
177 "Explicit RK4 diverged on block %" PetscInt_FMT
178 " at step %" PetscInt_FMT " with dt = %g: the step exceeds the explicit "
179 "stability limit. RK4 needs roughly dt < 2.8 / (4 nu (1/dx^2 + 1/dy^2 + 1/dz^2)) "
180 "for viscosity and a convective CFL of order 1. Reduce dt, or use "
181 "'Dual Time Picard Jameson RK', which has no such limit.",
182 bi, simCtx->step, (double)dt);
183 }
184
185 /*
186 // Final IBM Interpolation for the block (if enabled)
187 if (simCtx->immersed) {
188 LOG_ALLOW(LOCAL, LOG_DEBUG, " Performing post-RK IBM interpolation for block %d.\n", bi);
189 for (PetscInt ibi = 0; ibi < simCtx->NumberOfBodies; ibi++) {
190 ierr = ibm_interpolation_advanced(&user[bi], &ibm[ibi], ibi, 1); CHKERRQ(ierr);
191 }
192 }
193 */
194
195 } // End loop over blocks
196
197 // --- 3. Inter-Block Communication (Legacy Logic) ---
198 // This is called after all blocks have completed their RK stages.
199 if (simCtx->block_number > 1) {
200 // LOG_ALLOW(GLOBAL, LOG_DEBUG, "Updating multi-block interfaces after RK stages.\n");
201 // ierr = Block_Interface_U(user); CHKERRQ(ierr);
202 }
203
204 } // End of pseudo-time loop
205
206 // --- 4. Cleanup ---
207 // Destroy the RHS vectors that were created at the start of this function.
208 for (PetscInt bi = 0; bi < simCtx->block_number; bi++) {
209 ierr = VecDestroy(&user[bi].Rhs); CHKERRQ(ierr);
210 }
211
212 LOG_ALLOW(GLOBAL, LOG_INFO, "Runge-Kutta solve completed for all blocks.\n");
213
215
216 PetscFunctionReturn(0);
217}
PetscErrorCode SynchronizePeriodicStaggeredFields(UserCtx *user, PetscInt num_fields, const FieldId field_ids[])
Synchronizes persistent component-staggered vector fields.
PetscErrorCode ApplyBoundaryConditions(UserCtx *user)
Main boundary-condition orchestrator executed during solver timestepping.
FieldId
Compile-time identity for a catalogued Eulerian field.
@ FIELD_ID_UCONT
#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
#define LOG_ALLOW(scope, level, fmt,...)
Logging macro that checks both the log level and whether the calling function is in the allowed-funct...
Definition logging.h:214
#define PROFILE_FUNCTION_END
Marks the end of a profiled code block.
Definition logging.h:1029
@ LOG_INFO
Informational messages about program execution.
Definition logging.h:31
@ 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
PetscErrorCode ComputeRHS(UserCtx *user, Vec Rhs)
Computes the Right-Hand Side (RHS) of the momentum equations.
Definition rhs.c:616
PetscInt block_number
Definition variables.h:1009
SimCtx * simCtx
Back-pointer to the master simulation context.
Definition variables.h:1160
PetscReal dt
Definition variables.h:933
PetscInt step
Definition variables.h:924
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:

◆ MomentumSolver_NewtonKrylov()

PetscErrorCode MomentumSolver_NewtonKrylov ( UserCtx *  user,
IBMNodes *  ibm,
FSInfo *  fsi 
)

Solves one physical momentum step with matrix-free Newton–Krylov.

The Jacobian operator is the finite-difference, matrix-free operator of the complete deterministic residual. With no mathematical preconditioner its matrix is also passed to PETSc's preconditioning slot and PCNONE is derived. The optional provisional frozen-momentum, point-block model approximates same-cell frozen coupling, owns a separate matrix, and derives a block-Jacobi PETSc backend. It does not relax the version-one physics or boundary-condition restrictions. The PETSc solver objects are built on the first call and kept for the run in UserCtx::momentumNewtonKrylov (MomentumSolver_NewtonKrylov_Destroy() releases them), with UserCtx::Rhs; a step that fails releases both, so the next call builds afresh. Rows removed by legacy boundary residual enforcement are made explicit: conditioned normal rows use X-Uconditioned, untouched dummy/tangential rows use X, and periodic duplicates use Xdup-Xrepresentative. Unsupported masked, interface, and component-disabled rows are rejected before setup.

Parameters
userSingle-block momentum context.
ibmMust be NULL; immersed boundaries are not supported in version one.
fsiMust be NULL; moving-body coupling is not supported in version one.
Returns
0 when the step is committed: on SNES convergence, or when SNES fails but the residual at its iterate is finite and no larger than at entry (then simCtx->mom_last_converged is false). PETSC_ERR_CONV_FAILED after rollback when that residual is non-finite or grew.

Definition at line 1303 of file momentum_newton_krylov.c.

1304{
1305 PetscErrorCode ierr = PETSC_SUCCESS, cleanup_ierr;
1306 SimCtx *simCtx;
1307 SNES snes = NULL;
1308 Vec solution = NULL, entry_backup = NULL;
1309 MomentumNewtonKrylovContext *ctx = NULL;
1310 PetscBool restore_entry = PETSC_FALSE;
1311 PetscBool solve_started = PETSC_FALSE;
1312 PetscBool committed = PETSC_FALSE;
1313 PetscBool converged = PETSC_FALSE;
1314 SNESConvergedReason reason = SNES_CONVERGED_ITERATING;
1315 PetscInt nonlinear_its = 0, function_evals = 0, linear_its = 0;
1316 PetscReal final_norm = PETSC_MAX_REAL;
1317 const FieldId staggered_fields[] = {FIELD_ID_UCONT};
1318
1319 PetscFunctionBeginUser;
1321 PetscCall(MomentumNewtonKrylov_Validate(user));
1322 PetscCheck(ibm == NULL && fsi == NULL, PETSC_COMM_WORLD, PETSC_ERR_SUP,
1323 "Newton Krylov version one does not accept IBM or FSI objects.");
1324 simCtx = user->simCtx;
1325
1326 /* Rhs is kept for the run and zeroed for each step. */
1327 if (!user->Rhs) { ierr = VecDuplicate(user->Ucont, &user->Rhs); if (ierr) goto cleanup; }
1328 ierr = VecZeroEntries(user->Rhs); if (ierr) goto cleanup;
1329
1330 ierr = SynchronizePeriodicStaggeredFields(user, 1, staggered_fields); if (ierr) goto cleanup;
1331 ierr = ApplyBoundaryConditions(user); if (ierr) goto cleanup;
1332 if (!user->momentumNewtonKrylov) { ierr = MomentumNewtonKrylov_Build(user); if (ierr) goto cleanup; }
1333 ctx = user->momentumNewtonKrylov;
1334 ctx->have_initial_norm = PETSC_FALSE;
1335 ctx->initial_norm = 0.0;
1336 snes = ctx->snes;
1337 /* The residual and Jacobian callbacks live on fda's DMSNES, which every SNES on fda shares;
1338 registering them before each solve keeps another solver on fda from leaving its own in place. */
1339 ierr = SNESSetFunction(snes, NULL, MomentumNewtonKrylov_FormResidual, ctx); if (ierr) goto cleanup;
1340 ierr = MomentumNewtonJacobian_Register(snes, &ctx->jacobian,
1341 &ctx->preconditioning_engine, ctx); if (ierr) goto cleanup;
1342 solution = ctx->solution;
1343 entry_backup = ctx->entry_backup;
1344 ierr = VecCopy(user->Ucont, entry_backup); if (ierr) goto cleanup;
1345 restore_entry = PETSC_TRUE;
1346 ierr = VecCopy(user->Ucont, solution); if (ierr) goto cleanup;
1347
1349 "Newton Krylov Jacobian: finite_difference / matrix_free; "
1350 "Preconditioner: %s; PETSc Jacobian matrix type: MATMFFD; "
1351 "PETSc PC type: %s.\n",
1353 "none" : "frozen_momentum_jacobian / point_block",
1354 ctx->preconditioning_engine.petsc_pc_type);
1355
1357 solve_started = PETSC_TRUE;
1358 ierr = SNESSolve(snes, NULL, solution);
1359 if (ierr) goto cleanup;
1360 ierr = SNESGetConvergedReason(snes, &reason); if (ierr) goto cleanup;
1361 ierr = SNESGetIterationNumber(snes, &nonlinear_its); if (ierr) goto cleanup;
1362 ierr = SNESGetNumberFunctionEvals(snes, &function_evals); if (ierr) goto cleanup;
1363 ierr = SNESGetLinearSolveIterations(snes, &linear_its); if (ierr) goto cleanup;
1364 ierr = SNESGetFunctionNorm(snes, &final_norm); if (ierr) goto cleanup;
1365
1366 /* Failure policy, shared with the dual-time solver: a solve SNES did not declare
1367 converged still commits its iterate when the residual there is finite and no larger
1368 than at entry, and the step is reported as not converged. Only a non-finite or
1369 grown residual rolls the step back and stops the run. */
1370 if (reason > 0) {
1371 committed = PETSC_TRUE;
1372 converged = PETSC_TRUE;
1373 } else {
1374 PetscReal held_residual = 0.0, held_residual_2 = 0.0, held_reference = 0.0;
1375 ierr = MomentumNewtonKrylov_AssessIterate(ctx, solution, &held_residual, &held_residual_2,
1376 &held_reference, &converged); if (ierr) goto cleanup;
1377 committed = (PetscBool)(!PetscIsInfOrNanReal(held_residual_2) && ctx->have_initial_norm &&
1378 held_residual_2 <= ctx->initial_norm);
1379 if (!committed) converged = PETSC_FALSE;
1380 if (converged) {
1382 "Newton Krylov step %" PetscInt_FMT ": SNES reported %s, but |R|_inf = %.3e is within "
1383 "residual_absolute_tol (%.1e) x a0|U|/dt = %.3e; the step is committed as converged.\n",
1384 simCtx->step, SNESConvergedReasons[reason], (double)held_residual,
1385 (double)simCtx->mom_resid_atol, (double)held_reference);
1386 } else if (committed) {
1388 "Newton Krylov step %" PetscInt_FMT ": SNES reported %s with |R|_inf = %.3e, above "
1389 "residual_absolute_tol (%.1e) x a0|U|/dt = %.3e; |R|_2 = %.3e is no larger than %.3e at "
1390 "entry, so the step continues from the SNES iterate, not converged.\n",
1391 simCtx->step, SNESConvergedReasons[reason], (double)held_residual,
1392 (double)simCtx->mom_resid_atol, (double)held_reference,
1393 (double)held_residual_2, (double)ctx->initial_norm);
1394 } else {
1395 if (ctx->have_initial_norm) {
1397 "Newton Krylov step %" PetscInt_FMT ": SNES reported %s and |R|_2 at its iterate is "
1398 "%.3e against %.3e at entry; the step is rolled back.\n",
1399 simCtx->step, SNESConvergedReasons[reason], (double)held_residual_2,
1400 (double)ctx->initial_norm);
1401 } else {
1403 "Newton Krylov step %" PetscInt_FMT ": SNES reported %s before an entry residual norm "
1404 "was available (|R|_2 at its iterate is %.3e); the step is rolled back.\n",
1405 simCtx->step, SNESConvergedReasons[reason], (double)held_residual_2);
1406 }
1407 }
1408 }
1409
1410 ierr = VecCopy(committed ? solution : entry_backup, user->Ucont); if (ierr) goto cleanup;
1411 simCtx->mom_last_converged = converged;
1412 ierr = SynchronizePeriodicStaggeredFields(user, 1, staggered_fields); if (ierr) goto cleanup;
1413 ierr = ApplyBoundaryConditions(user); if (ierr) goto cleanup;
1414 restore_entry = PETSC_FALSE;
1415
1417 "Newton Krylov momentum solve: reason=%s (%" PetscInt_FMT "), Newton iterations=%" PetscInt_FMT ", residual evaluations=%" PetscInt_FMT ", Krylov iterations=%" PetscInt_FMT ", final norm=%.6e, state=%s.\n",
1418 SNESConvergedReasons[reason], (PetscInt)reason, nonlinear_its, function_evals,
1419 linear_its, (double)final_norm,
1420 !committed ? "rolled back" : converged ? "committed" : "committed, not converged");
1421 if (!committed) ierr = PETSC_ERR_CONV_FAILED;
1422
1423cleanup:
1424 /* A PETSc solve error can bypass the normal statistics path. Query whatever
1425 SNES retained without replacing the primary error so a failed attempt is
1426 still represented in the structured log. */
1427 if (solve_started && snes) {
1428 (void)SNESGetConvergedReason(snes, &reason);
1429 (void)SNESGetIterationNumber(snes, &nonlinear_its);
1430 (void)SNESGetNumberFunctionEvals(snes, &function_evals);
1431 (void)SNESGetLinearSolveIterations(snes, &linear_its);
1432 (void)SNESGetFunctionNorm(snes, &final_norm);
1433 }
1434 if (restore_entry && entry_backup) {
1435 cleanup_ierr = VecCopy(entry_backup, user->Ucont);
1436 if (!ierr) ierr = cleanup_ierr;
1437 cleanup_ierr = SynchronizePeriodicStaggeredFields(user, 1, staggered_fields);
1438 if (!ierr) ierr = cleanup_ierr;
1439 cleanup_ierr = ApplyBoundaryConditions(user);
1440 if (!ierr) ierr = cleanup_ierr;
1441 simCtx->mom_last_converged = PETSC_FALSE;
1442 committed = PETSC_FALSE;
1443 }
1444 if (ctx && ctx->history_file) {
1445 (void)fclose(ctx->history_file);
1446 ctx->history_file = NULL;
1447 }
1448 if (ctx && ctx->linear_history_file) {
1449 (void)fclose(ctx->linear_history_file);
1450 ctx->linear_history_file = NULL;
1451 }
1452 if (solve_started) {
1453 MomentumNewtonKrylov_WriteSummary(ctx, reason, nonlinear_its, function_evals,
1454 linear_its, final_norm, committed);
1455 }
1456 /* A failed step, or a failed first build, releases what the solver holds, so the next call
1457 starts afresh; a committed step keeps it for the next. */
1458 if (ierr) {
1459 cleanup_ierr = VecDestroy(&user->Rhs); if (!ierr) ierr = cleanup_ierr;
1460 cleanup_ierr = MomentumSolver_NewtonKrylov_Destroy(user); if (!ierr) ierr = cleanup_ierr;
1461 }
1463 PetscFunctionReturn(ierr);
1464}
#define LOG(scope, level, fmt,...)
Logging macro for PETSc-based applications with scope control.
Definition logging.h:86
@ LOG_ERROR
Critical errors that may halt the program.
Definition logging.h:29
@ LOG_WARNING
Non-critical issues that warrant attention.
Definition logging.h:30
static PetscErrorCode MomentumNewtonJacobian_Register(SNES snes, MomentumNewtonJacobian *jacobian, MomentumPreconditionerEngine *engine, MomentumNewtonKrylovContext *ctx)
Registers the application orchestration callback and both SNES matrices.
static PetscErrorCode MomentumNewtonKrylov_AssessIterate(MomentumNewtonKrylovContext *ctx, Vec solution, PetscReal *residual, PetscReal *residual_2, PetscReal *reference, PetscBool *satisfied)
Measure the residual at the iterate a failed SNES solve holds, for the failure policy in MomentumSolv...
MomentumPreconditionerDescription description
static void MomentumNewtonKrylov_WriteSummary(const MomentumNewtonKrylovContext *ctx, SNESConvergedReason reason, PetscInt nonlinear_its, PetscInt function_evals, PetscInt linear_its, PetscReal final_norm, PetscBool committed)
Appends one rank-zero structured Newton result for a physical step.
static void MomentumNewtonKrylov_OpenHistory(MomentumNewtonKrylovContext *ctx)
Opens the optional rank-zero Newton iteration-history files (per Newton and per Krylov iteration).
static PetscErrorCode MomentumNewtonKrylov_Build(UserCtx *user)
Builds the solve context MomentumSolver_NewtonKrylov() keeps for the run.
static PetscErrorCode MomentumNewtonKrylov_Validate(UserCtx *user)
Rejects configurations outside the audited version-one feature set.
MomentumPreconditionerEngine preconditioning_engine
static PetscErrorCode MomentumNewtonKrylov_FormResidual(SNES snes, Vec X, Vec F, void *ctx)
Adapts a PETSc trial vector to the existing momentum residual path.
@ MOM_NK_PC_MODEL_NONE
#define MomentumSolver_NewtonKrylov_Destroy
PetscBool mom_last_converged
Definition variables.h:971
Vec Ucont
Definition variables.h:1197
struct MomentumNewtonKrylovContext * momentumNewtonKrylov
Definition variables.h:1235
PetscReal mom_resid_atol
Definition variables.h:960
Here is the call graph for this function:

◆ MomentumSolver_NewtonKrylov_Destroy()

PetscErrorCode MomentumSolver_NewtonKrylov_Destroy ( UserCtx *  user)

Releases the Newton–Krylov solve context MomentumSolver_NewtonKrylov() keeps for the run.

Parameters
userBlock context; a no-op when it holds no solve context.
Returns
PetscErrorCode 0 on success.

Releases the Newton–Krylov solve context MomentumSolver_NewtonKrylov() keeps for the run.

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

See also
MomentumSolver_NewtonKrylov_Destroy()

Definition at line 1239 of file momentum_newton_krylov.c.

1240{
1242
1243 PetscFunctionBeginUser;
1245 if (ctx) {
1246 PetscCall(VecDestroy(&ctx->entry_backup));
1247 PetscCall(VecDestroy(&ctx->solution));
1249 PetscCall(MomentumNewtonJacobian_Destroy(&ctx->jacobian));
1250 PetscCall(SNESDestroy(&ctx->snes));
1251 PetscCall(PetscFree(user->momentumNewtonKrylov));
1252 }
1254 PetscFunctionReturn(PETSC_SUCCESS);
1255}
static PetscErrorCode MomentumNewtonJacobian_Destroy(MomentumNewtonJacobian *jacobian)
Destroys a partially or fully created Jacobian operator.
static PetscErrorCode MomentumPreconditionerEngine_Destroy(MomentumPreconditionerEngine *engine)
Destroys only a separately owned preconditioning matrix.
Here is the call graph for this function:

◆ MomentumSolver_DualTime_Picard_JamesonRK()

PetscErrorCode MomentumSolver_DualTime_Picard_JamesonRK ( UserCtx *  user,
IBMNodes *  ibm,
FSInfo *  fsi 
)

Solves the momentum equations using dual-time Picard iteration with Jameson RK smoothing.


GLOSSARY & THEORETICAL BASIS

  1. METHODOLOGY: Dual-Time Stepping (Pseudo-Time Integration) We aim to solve the implicit BDF equation: R_spatial(U) + dU/dt_physical = 0. We do this by introducing a fictitious "Pseudo-Time" (tau) and iterating to steady state: dU/d(tau) = - [ R_spatial(U) + BDF_Terms(U) ] When dU/d(tau) -> 0, the physical time step is satisfied.
  2. ALGORITHM: Fixed-Point Iteration with Explicit Runge-Kutta This is technically a Fixed-Point iteration on the operator: U_new = U_old + pseudo_dtau * alfa_stage * Total_Residual(U_old) where pseudo_dtau = pseudo_cfl / lambda_max is the spectral-radius-based pseudo-time step (lambda_max = global max convective spectral radius). This makes pseudo_cfl a true dimensionless Courant number, independent of the physical time step dt. We use a 4-Stage Explicit RK scheme (Jameson-Schmidt-Turkel coeffs) to smooth errors.
  3. STABILITY: Adaptive Pseudo-CFL Trial Acceptance and Rollback If a pseudo-time trial causes excessive residual growth, the solver restores the

previous accepted state, reduces the global pseudo-CFL, and retries.

VARIABLE MAPPING

– Physics Variables (Legacy Names Kept) – ti : Physical Time Step Index. dt : Physical Time Step size (Delta t). st : Pseudo-Time Step size (Delta tau). alfa : Runge-Kutta stage coefficients {1/4, 1/3, 1/2, 1}. – Convergence & Solver Control (Renamed) – pseudo_iter : Counter for the inner dual-time loop. pseudo_dtau : Adaptive pseudo-time step [physical time], = pseudo_cfl / lambda_max. lambda_max : Global max convective spectral radius [1/s] from the current field. delta_sol_norm : The L_inf norm of the change in solution (dU).

resid_norm : The L_inf norm of the Total Residual (RHS).

Parameters
userPrimary UserCtx input for the operation.
ibmOptional immersed-boundary state; NULL when IBM is disabled.
fsiOptional fluid-structure state; NULL when FSI is disabled.
Returns
PetscErrorCode 0 on success.
Note
Testing status: This solver is covered primarily through runtime smoke and orchestration tests. A smaller direct invariant-style positive-path harness remains part of the next-gap backlog.

Solves the momentum equations using dual-time Picard iteration with Jameson RK smoothing.

See also
MomentumSolver_DualTime_Picard_JamesonRK()

Definition at line 804 of file momentumsolvers.c.

805{
806 (void)ibm;
807 (void)fsi;
808 // --- CONTEXT ACQUISITION BLOCK ---
809 SimCtx *simCtx = user[0].simCtx;
810 const PetscInt block_number = simCtx->block_number;
811
812 // Legacy Names (Physics/Time) - Kept for brevity in formulas
813 const PetscInt ti = simCtx->step;
814 const PetscReal dt = simCtx->dt; // Physical Time Step
815 /* cfl: initial pseudo-CFL Courant number (dimensionless, flow-independent since Phase 3).
816 * Actual dtau = cfl / lambda_max, computed after the spectral radius estimate below. */
817 const PetscReal cfl = simCtx->pseudo_cfl;
818 const PetscReal alfa[] = {0.25, 1.0/3.0, 0.5, 1.0}; // Jameson RK smoothing coefficients
819
820 // State flags
821 PetscBool force_restart = PETSC_FALSE;
822
823 // Renamed Solver Parameters
824 const PetscInt max_pseudo_steps = simCtx->mom_max_pseudo_steps; // Max Dual-Time Iterations
825 const PetscReal tol_abs_delta = simCtx->mom_atol; // Stop if |dU| < tol
826 const PetscReal tol_rtol_delta = simCtx->mom_rtol; // Stop if |dU|/|dU0| < tol
827 // --- END CONTEXT ACQUISITION BLOCK ---
828
829 PetscErrorCode ierr;
830 PetscMPIInt rank;
831 PetscInt istage, pseudo_iter;
832 PetscInt accepted_iter = 0, rejected_iter = 0, recovery_streak = 0;
833 PetscReal ts, te, cput;
834
835 // --- Global Convergence Metrics ---
836 PetscReal global_norm_delta = 10.0;
837 PetscReal global_rel_delta = 1.0;
838 PetscReal global_norm_resid = 1.0;
839 PetscReal global_rel_resid = 1.0;
840 PetscReal smoothed_trial_ratio = 1.0; /* EMA-smoothed ratio; initialized neutral */
841
842 // --- Spectral-radius-based pseudo-time step ---
843 /* lambda_max: global maximum spectral radius [1/s], computed once per physical timestep.
844 * pseudo_dtau[bi]: physical pseudo-time step dtau = pseudo_cfl / lambda_max [time].
845 * Unlike the old scheme (dtau = pseudo_cfl * dt), this is independent of dt and makes
846 * pseudo_cfl a true Courant number. (2.83 is only the scalar imaginary-axis RK limit,
847 * not a generally-stable value for the actual operator -- to be characterized in A4.)
848 * dtau_min / dtau_max: per-timestep bounds derived from simCtx->min/max_pseudo_cfl. */
849 PetscReal lambda_max = 0.0;
850 /* cfl_cap: dimensionless memory of where trials have failed. Without it the controller
851 * re-discovers the stability limit every physical step -- measured on the laminar
852 * channel it climbed 1.36 -> 2.00, rejected, recovered, and climbed straight back, with
853 * 28.8% of all trials spent above the limit. Carried in CFL (not dtau) so it stays
854 * meaningful as lambda_max evolves; see the rejection and growth paths below. */
855 PetscReal cfl_cap = simCtx->max_pseudo_cfl;
856 /* resid_ref: reference scale for the residual [same units as R], recomputed each
857 * physical step. See the assembly below for why the absolute residual tolerance is
858 * measured against this rather than being a raw dimensional bound. */
859 PetscReal resid_ref = 0.0;
860 PetscReal dtau_min, dtau_max;
861
862 // --- Local Metric Arrays (Per Block) ---
863 PetscReal *delta_sol_norm_init, *delta_sol_norm_prev, *delta_sol_norm_curr, *delta_sol_rel_curr;
864 PetscReal *resid_norm_init, *resid_norm_prev, *resid_norm_curr, *resid_rel_curr;
865 PetscReal *pseudo_dtau; /* per-block pseudo-time step dtau [physical time, NOT dtau/dt] */
866 PetscReal *trial_ratio_log; /* per-block step-to-step residual ratio (for diagnostics) */
867 PetscReal last_accepted_resid; /* last accepted |R|, for final summary */
868
869 PetscFunctionBeginUser;
871 rank = user->simCtx->rank;
872 LOG_ALLOW(GLOBAL, LOG_INFO, "Executing Dual-Time Momentum Solver for %" PetscInt_FMT " block(s).\n", block_number);
873
874 // --- Allocate metric arrays ---
875 ierr = PetscMalloc2(block_number, &delta_sol_norm_init, block_number, &delta_sol_norm_prev); CHKERRQ(ierr);
876 ierr = PetscMalloc2(block_number, &delta_sol_norm_curr, block_number, &delta_sol_rel_curr); CHKERRQ(ierr);
877 ierr = PetscMalloc2(block_number, &resid_norm_init, block_number, &resid_norm_prev); CHKERRQ(ierr);
878 ierr = PetscMalloc2(block_number, &resid_norm_curr, block_number, &pseudo_dtau); CHKERRQ(ierr);
879 ierr = PetscMalloc1(block_number, &resid_rel_curr); CHKERRQ(ierr);
880 ierr = PetscMalloc1(block_number, &trial_ratio_log); CHKERRQ(ierr);
881 last_accepted_resid = 0.0;
882
883 ierr = PetscTime(&ts); CHKERRQ(ierr);
884
885 // --- 1. Pre-Loop Initialization ---
886
887 if (block_number > 1) {
888 // ierr = Block_Interface_U(user); CHKERRQ(ierr);
889 }
890
891 for (PetscInt bi = 0; bi < block_number; bi++) {
892 ierr = ApplyBoundaryConditions(&user[bi]); CHKERRQ(ierr);
893
894 // Immersed boundary interpolation (if enabled)
895
896 // Workspace, allocated on the first step and kept for the run. pRhs is the backup of Rhs
897 // at the last accepted pseudo-state; Rhs is zeroed for each step, and the others are
898 // overwritten before they are read.
899 if (!user[bi].Rhs) { ierr = VecDuplicate(user[bi].Ucont, &user[bi].Rhs); CHKERRQ(ierr); }
900 if (!user[bi].pRhs) { ierr = VecDuplicate(user[bi].Ucont, &user[bi].pRhs); CHKERRQ(ierr); }
901 if (!user[bi].dUcont) { ierr = VecDuplicate(user[bi].Ucont, &user[bi].dUcont); CHKERRQ(ierr); }
902 if (!user[bi].pUcont) { ierr = VecDuplicate(user[bi].Ucont, &user[bi].pUcont); CHKERRQ(ierr); }
903 ierr = VecZeroEntries(user[bi].Rhs); CHKERRQ(ierr);
904
905 // Initialize Backup (pUcont) with current state
906 ierr = VecCopy(user[bi].Ucont, user[bi].pUcont); CHKERRQ(ierr);
907
908 // --- Calculate Initial Total Residual (Spatial + Temporal) ---
909 ierr = ComputeTotalResidual(&user[bi]); CHKERRQ(ierr);
910
911 // Backup Rhs with current state
912 ierr = VecCopy(user[bi].Rhs, user[bi].pRhs); CHKERRQ(ierr);
913
914 // Compute Initial Norms
915 ierr = VecNorm(user[bi].Rhs, NORM_INFINITY, &resid_norm_init[bi]); CHKERRQ(ierr);
916
917 /* Reference scale for the absolute residual test (see its use below). VecNorm is
918 * collective, so this is already global; take the max across blocks. */
919 {
920 PetscReal ucont_inf;
921 ierr = VecNorm(user[bi].Ucont, NORM_INFINITY, &ucont_inf); CHKERRQ(ierr);
922 resid_ref = PetscMax(resid_ref, MomentumBDFCoefficient(simCtx) * ucont_inf / dt);
923 }
924
925 // Initialize history for backtracking logic
926 resid_norm_prev[bi] = resid_norm_init[bi]; /* meaningful ratio on first iteration */
927 delta_sol_norm_prev[bi] = 1000.0;
928 /* pseudo_dtau[bi] is set after ComputeGlobalSpectralRadiusEstimate below. */
929
930 LOG_ALLOW(GLOBAL,LOG_INFO," Block %" PetscInt_FMT " | Max RHS = %.6f | initial pseudo-CFL = %.4f .\n", bi, resid_norm_init[bi], cfl);
931 }
932
933 /* --- Spectral Radius Estimate (computed once per physical timestep) ---
934 * lambda_max [1/s] is the global maximum of (face_flux_sum * inverse_cell_volume)
935 * over all owned cells across all MPI ranks. See ComputeGlobalSpectralRadiusEstimate().
936 *
937 * dtau = pseudo_cfl / lambda_max (pseudo_cfl is now a true Courant number)
938 * dtau_min/max are derived from the user-specified min/max_pseudo_cfl bounds.
939 *
940 * The BDF2 lower bound inside the helper ensures lambda_max >= 1.5/dt, so dtau
941 * remains finite even when the velocity field is zero (startup / stagnant ICs). */
942 ierr = ComputeGlobalSpectralRadiusEstimate(user, block_number, dt, &lambda_max); CHKERRQ(ierr);
943 dtau_min = simCtx->min_pseudo_cfl / lambda_max;
944 dtau_max = simCtx->max_pseudo_cfl / lambda_max;
945
946 /* Initialise per-block pseudo-time step from the warm-start CFL (carried from last timestep). */
947 for (PetscInt bi = 0; bi < block_number; bi++) {
948 pseudo_dtau[bi] = cfl / lambda_max; /* dtau [physical time], NOT a fraction of dt */
949 }
950
951 /* --- SHADOW MODE: new operator-scaled stability estimate (diagnostic only) ---
952 * Computes the Workstream-A estimate alongside the legacy one and logs a compact
953 * comparison. The legacy estimate above continues to drive production dtau; the
954 * shadow estimate changes nothing. Enable with -mom_stability_shadow. */
955 {
956 PetscBool shadow = PETSC_FALSE;
957 ierr = PetscOptionsGetBool(NULL, NULL, "-mom_stability_shadow", &shadow, NULL); CHKERRQ(ierr);
958 if (shadow) {
960 ierr = ComputeMomentumStabilityEstimate(user, block_number, dt, MOM_STAB_CAND_C, &rep); CHKERRQ(ierr);
961 const char *lim = (rep.limiter==MOM_STAB_LIMITER_TIME) ? "time"
962 : (rep.limiter==MOM_STAB_LIMITER_CONVECTION) ? "convection" : "viscosity";
963 /* Detailed shadow comparison at DEBUG only (gated by level + function allowlist);
964 never printed unconditionally. Enable in tests via the logging controls. */
966 "Momentum scale [shadow]: legacy_dtau=%.4e new_dtau=%.4e ratio=%.4f limiter=%s | "
967 "lambda_legacy=%.4e lambda_new=%.4e (B=%.4e C=%.4e D=%.4e) | "
968 "lt=%.4e lc=%.4e lv=%.4e | cell=(%d,%d,%d) blk=%d class=%d onesided=%d\n",
969 cfl / lambda_max, cfl / rep.lambda, rep.lambda / lambda_max, lim,
970 lambda_max, rep.lambda, rep.lambda_B, rep.lambda_C, rep.lambda_D,
971 rep.lambda_t, rep.lambda_c, rep.lambda_v,
972 (int)rep.ci, (int)rep.cj, (int)rep.ck, (int)rep.cblock, (int)rep.cclass, (int)rep.one_sided);
973 }
974 }
975
977 "Dual-time solver: lambda_max=%.4e [1/s] resid_ref=%.4e dtau_init=%.4e dtau range [%.4e, %.4e] "
978 "CFL range [%.4f, %.4f] rejection_threshold=%.3f (EMA alpha=%.2f) "
979 "growth=%.3f reduction=%.3f max_accepted=%" PetscInt_FMT ".\n",
980 lambda_max, resid_ref, cfl / lambda_max, dtau_min, dtau_max,
981 simCtx->min_pseudo_cfl, simCtx->max_pseudo_cfl,
983 simCtx->mom_ratio_ema_alpha,
985 max_pseudo_steps);
986
987 // --- 2. Main Pseudo-Time Iteration Loop ---
988 pseudo_iter = 0;
989 PetscBool residual_convergence_enabled =
990 (PetscBool)(simCtx->mom_resid_atol > 0.0 || simCtx->mom_resid_rtol > 0.0);
991 PetscBool converged = PETSC_FALSE;
992 PetscBool last_trial_nonfinite = PETSC_FALSE;
993 /* Rejected iterations no longer consume the accepted-iteration budget.
994 A hard cap of 3x max_pseudo_steps guards against infinite rejection loops. */
995 const PetscInt max_total_attempts = max_pseudo_steps * 3;
996 while (!converged && accepted_iter < max_pseudo_steps && pseudo_iter < max_total_attempts)
997 {
998 pseudo_iter++;
999 force_restart = PETSC_FALSE;
1000
1001 // Every attempt starts from the last globally accepted state.
1002 for (PetscInt bi = 0; bi < block_number; bi++) {
1003 ierr = VecCopy(user[bi].pUcont, user[bi].Ucont); CHKERRQ(ierr);
1004 ierr = VecCopy(user[bi].pRhs, user[bi].Rhs); CHKERRQ(ierr);
1005 const FieldId staggered_fields[] = {FIELD_ID_UCONT};
1006 ierr = SynchronizePeriodicStaggeredFields(&user[bi], 1, staggered_fields); CHKERRQ(ierr);
1007 ierr = ApplyBoundaryConditions(&user[bi]); CHKERRQ(ierr);
1008 }
1009
1010 for (PetscInt bi = 0; bi < block_number; bi++) {
1011
1012 // === 4-Stage Jameson RK Smoothing Loop ===
1013 for (istage = 0; istage < 4; istage++) {
1014
1015 LOG_ALLOW(GLOBAL,LOG_TRACE," Pseudo-Iter: %" PetscInt_FMT " | RK-Stage: %" PetscInt_FMT "\n", pseudo_iter, istage);
1016
1017 /* RK Update: U_new = U_old + (dtau * alpha) * Residual
1018 * pseudo_dtau[bi] IS dtau [physical time] — no further multiplication by dt.
1019 * (In the old scheme dtau = pseudo_cfl * dt; here dtau = pseudo_cfl / lambda_max.) */
1020 ierr = VecWAXPY(user[bi].Ucont,
1021 pseudo_dtau[bi] * alfa[istage],
1022 user[bi].Rhs,
1023 user[bi].pUcont); CHKERRQ(ierr);
1024
1025 // Sync Ghosts & Re-apply BCs for intermediate stage
1026 const FieldId staggered_fields[] = {FIELD_ID_UCONT};
1027 ierr = SynchronizePeriodicStaggeredFields(&user[bi], 1, staggered_fields); CHKERRQ(ierr);
1028
1029 ierr = ApplyBoundaryConditions(&user[bi]); CHKERRQ(ierr);
1030
1031 // --- Re-calculate Total Residual for next stage ---
1032 ierr = ComputeTotalResidual(&user[bi]); CHKERRQ(ierr);
1033
1034 } // End RK Stages
1035
1036 // Immersed boundary interpolation (if enabled)
1037
1038 // === Convergence Metrics Calculation ===
1039
1040 // Calculate dU = U_current - U_backup
1041 ierr = VecWAXPY(user[bi].dUcont, -1.0, user[bi].pUcont, user[bi].Ucont); CHKERRQ(ierr);
1042
1043 // Compute Infinity Norms
1044 ierr = VecNorm(user[bi].dUcont, NORM_INFINITY, &delta_sol_norm_curr[bi]); CHKERRQ(ierr);
1045 ierr = VecNorm(user[bi].Rhs, NORM_INFINITY, &resid_norm_curr[bi]); CHKERRQ(ierr);
1046
1047 // Normalize relative metrics
1048 if (pseudo_iter == 1) {
1049 delta_sol_norm_init[bi] = delta_sol_norm_curr[bi];
1050 delta_sol_rel_curr[bi] = 1.0;
1051 resid_rel_curr[bi] = 1.0;
1052 // resid_norm_init[bi] set correctly before the loop — do not overwrite
1053 } else {
1054 if (delta_sol_norm_init[bi] > 1.0e-10)
1055 delta_sol_rel_curr[bi] = delta_sol_norm_curr[bi] / delta_sol_norm_init[bi];
1056 else
1057 delta_sol_rel_curr[bi] = 0.0;
1058
1059 if(resid_norm_init[bi] > 1.0e-10)
1060 resid_rel_curr[bi] = resid_norm_curr[bi] / resid_norm_init[bi];
1061 else
1062 resid_rel_curr[bi] = 0.0;
1063 }
1064
1065 /* Pre-compute per-block step-to-step trial ratio for later file logging. */
1066 {
1067 const PetscReal resid_floor_log = 1.0e-30;
1068 if (resid_norm_prev[bi] > resid_floor_log)
1069 trial_ratio_log[bi] = resid_norm_curr[bi] / resid_norm_prev[bi];
1070 else if (resid_norm_curr[bi] <= resid_floor_log)
1071 trial_ratio_log[bi] = 0.0;
1072 else
1073 trial_ratio_log[bi] = PETSC_MAX_REAL;
1074 }
1075 } // End loop over blocks
1076
1077 // --- Update Global Convergence Criteria ---
1078 global_norm_delta = -1.0e20;
1079 global_rel_delta = -1.0e20;
1080 global_norm_resid = -1.0e20;
1081 global_rel_resid = -1.0e20;
1082
1083 for (PetscInt bi = 0; bi < block_number; bi++) {
1084 global_norm_delta = PetscMax(delta_sol_norm_curr[bi], global_norm_delta);
1085 global_rel_delta = PetscMax(delta_sol_rel_curr[bi], global_rel_delta);
1086 global_norm_resid = PetscMax(resid_norm_curr[bi], global_norm_resid);
1087 global_rel_resid = PetscMax(resid_rel_curr[bi], global_rel_resid);
1088 }
1089 ierr = PetscTime(&te); CHKERRQ(ierr);
1090 cput = te - ts;
1091 LOG_ALLOW(GLOBAL, LOG_INFO, " Pseudo-Iter(k) %" PetscInt_FMT ": |dUk|=%e, |dUk|/|dU0| = %e, |Rk|/|R0| = %e, CPU=%.2fs\n",
1092 pseudo_iter, global_norm_delta, global_rel_delta, global_rel_resid, cput);
1093
1094 // === Adaptive Pseudo-CFL Trial Acceptance and Rollback ===
1095 const PetscReal resid_floor = 1.0e-30;
1096 PetscReal global_trial_ratio = 0.0;
1097 PetscBool global_nonfinite = PETSC_FALSE;
1098 for (PetscInt bi = 0; bi < block_number; bi++) {
1099 PetscReal ratio;
1100 if (resid_norm_prev[bi] > resid_floor) {
1101 ratio = resid_norm_curr[bi] / resid_norm_prev[bi];
1102 } else if (resid_norm_curr[bi] <= resid_floor) {
1103 ratio = 0.0;
1104 } else {
1105 ratio = PETSC_MAX_REAL;
1106 }
1107 global_trial_ratio = PetscMax(global_trial_ratio, ratio);
1108 global_nonfinite = (PetscBool)(global_nonfinite ||
1109 PetscIsInfOrNanReal(delta_sol_norm_curr[bi]) ||
1110 PetscIsInfOrNanReal(resid_norm_curr[bi]) ||
1111 PetscIsInfOrNanReal(ratio));
1112 }
1113
1114 PetscReal reduced_trial_ratio;
1115 PetscMPIInt local_nonfinite = global_nonfinite ? 1 : 0;
1116 PetscMPIInt reduced_nonfinite = 0;
1117 ierr = MPI_Allreduce(&global_trial_ratio, &reduced_trial_ratio, 1, MPIU_REAL, MPI_MAX, PETSC_COMM_WORLD); CHKERRQ(ierr);
1118 ierr = MPI_Allreduce(&local_nonfinite, &reduced_nonfinite, 1, MPI_INT, MPI_LOR, PETSC_COMM_WORLD); CHKERRQ(ierr);
1119 global_trial_ratio = reduced_trial_ratio;
1120 global_nonfinite = reduced_nonfinite ? PETSC_TRUE : PETSC_FALSE;
1121 last_trial_nonfinite = global_nonfinite;
1122
1123 /* EMA-smooth the trial ratio to tolerate occasional non-monotonic residual bumps.
1124 Non-finite trials bypass smoothing and always trigger rollback.
1125
1126 The smoothed value is only a CANDIDATE until the trial is accepted. A rejected
1127 trial is rolled back -- its state never happened -- so letting its ratio persist
1128 into the next decision is a state leak, and a costly one: measured on the laminar
1129 channel, a diverging trial at cfl 2.0 (raw ratio 3.97) pushed the EMA to 1.61, and
1130 the *next* trial at cfl 1.5 was rejected too despite a raw ratio of 0.994, i.e.
1131 despite the residual actually decreasing. That false rejection cost four discarded
1132 ComputeRHS calls and drove dtau down to cfl 1.125, below the measured optimum.
1133 The dtau reduction on the rejection path already carries the information; the EMA
1134 does not need to carry it as well. */
1135 PetscReal trial_smoothed = smoothed_trial_ratio;
1136 if (!global_nonfinite) {
1137 trial_smoothed = simCtx->mom_ratio_ema_alpha * global_trial_ratio
1138 + (1.0 - simCtx->mom_ratio_ema_alpha) * smoothed_trial_ratio;
1139 }
1141 " [k=%" PetscInt_FMT "] raw_ratio=%.4e smoothed_ratio=%.4e (threshold=%.3f) | "
1142 "|R_prev|=%.6e | |R_curr|=%.6e | CFL=%.6f\n",
1143 pseudo_iter, global_trial_ratio, trial_smoothed,
1145 resid_norm_prev[0], resid_norm_curr[0], pseudo_dtau[0]);
1146
1147 if (simCtx->no_pseudo_cfl_backtrack) {
1148 /* Diagnostic mode: commit every finite trial; only non-finite triggers rollback. */
1149 force_restart = global_nonfinite;
1150 } else {
1151 force_restart = (PetscBool)(global_nonfinite ||
1153 }
1154
1155 if (force_restart) {
1156 /* old_dtau: dtau used for this (rejected) trial [physical time].
1157 * next_dtau: reduced dtau for the retry, clamped to dtau_min.
1158 * Both are physical-time values; the effective CFL = dtau * lambda_max. */
1159 PetscReal old_dtau = pseudo_dtau[0];
1160 PetscReal next_dtau = PetscMax(dtau_min, old_dtau * simCtx->pseudo_cfl_reduction_factor);
1161 /* This CFL failed: never grow back to it. MOM_CFL_CAP_SAFETY keeps the ceiling
1162 * off the edge, where the smoother damps worst even when it is still stable. */
1163 cfl_cap = PetscMax(simCtx->min_pseudo_cfl,
1164 PetscMin(cfl_cap, old_dtau * lambda_max * MOM_CFL_CAP_SAFETY));
1165 rejected_iter++;
1166 recovery_streak = 0;
1167 for (PetscInt bi = 0; bi < block_number; bi++) {
1168 ierr = VecCopy(user[bi].pUcont, user[bi].Ucont); CHKERRQ(ierr);
1169 ierr = VecCopy(user[bi].pRhs, user[bi].Rhs); CHKERRQ(ierr);
1170 const FieldId staggered_fields[] = {FIELD_ID_UCONT};
1171 ierr = SynchronizePeriodicStaggeredFields(&user[bi], 1, staggered_fields); CHKERRQ(ierr);
1172 ierr = ApplyBoundaryConditions(&user[bi]); CHKERRQ(ierr);
1173 pseudo_dtau[bi] = next_dtau;
1174 }
1175 /* A rejected trial is the controller working; the momentum history file records it. */
1177 " Trial %" PetscInt_FMT " REJECTED (raw_ratio=%.4e, smoothed=%.4e, nonfinite=%d); "
1178 "dtau %.4e -> %.4e (cfl_eff %.4f -> %.4f)%s\n",
1179 pseudo_iter, global_trial_ratio, trial_smoothed, (int)global_nonfinite,
1180 old_dtau, next_dtau, old_dtau * lambda_max, next_dtau * lambda_max,
1181 (old_dtau == next_dtau) ? " [AT FLOOR — no dtau reduction]" : "");
1182 /* Log rejected trial to file before rolling back. */
1183 if (!rank) {
1184 ierr = AppendPicardHistoryRows(simCtx, block_number, pseudo_iter, old_dtau, next_dtau, lambda_max,
1185 delta_sol_norm_curr, delta_sol_rel_curr, resid_norm_curr, resid_rel_curr,
1186 trial_ratio_log, trial_smoothed, "rejected"); CHKERRQ(ierr);
1187 }
1188 if (old_dtau <= dtau_min) {
1189 if (global_nonfinite) {
1190 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_CONV_FAILED,
1191 "Momentum solver produced a non-finite trial at minimum pseudo-CFL.");
1192 }
1193 /* Finite rejection at the dtau floor: reducing further is impossible.
1194 Break instead of retrying bit-identically until max_pseudo_steps. */
1196 " Trial %" PetscInt_FMT " REJECTED (ratio=%.4e) at minimum dtau (%.4e, cfl_eff=%.4f) "
1197 "with no further reduction possible; breaking retry loop.\n",
1198 pseudo_iter, global_trial_ratio, old_dtau, old_dtau * lambda_max);
1199 break;
1200 }
1201 continue;
1202 }
1203
1204 accepted_iter++;
1205 smoothed_trial_ratio = trial_smoothed; /* commit only for a trial that survives */
1206 last_trial_nonfinite = PETSC_FALSE;
1207 last_accepted_resid = resid_norm_curr[0]; /* track for final summary */
1208 for (PetscInt bi = 0; bi < block_number; bi++) {
1209 ierr = VecCopy(user[bi].Ucont, user[bi].pUcont); CHKERRQ(ierr);
1210 ierr = VecCopy(user[bi].Rhs, user[bi].pRhs); CHKERRQ(ierr);
1211 resid_norm_prev[bi] = resid_norm_curr[bi];
1212 delta_sol_norm_prev[bi] = delta_sol_norm_curr[bi];
1213 }
1214
1215 /* old_dtau: dtau used for this (accepted) trial.
1216 * next_dtau: dtau for the next trial, grown/reduced based on convergence rate.
1217 * Bounds (dtau_min, dtau_max) are derived from simCtx->min/max_pseudo_cfl / lambda_max. */
1218 PetscReal old_dtau = pseudo_dtau[0]; /* save before any update */
1219 PetscReal next_dtau = old_dtau;
1220 if (global_trial_ratio < 0.90) {
1221 /* Residual decreasing fast: grow dtau to accelerate convergence. */
1222 next_dtau *= simCtx->pseudo_cfl_growth_factor;
1223 recovery_streak = 0;
1224 } else if (global_trial_ratio <= 1.0) {
1225 /* Residual barely decreasing: grow only after 3 clean consecutive trials. */
1226 recovery_streak++;
1227 if (recovery_streak >= 3) {
1228 next_dtau *= simCtx->pseudo_cfl_growth_factor;
1229 recovery_streak = 0;
1230 }
1231 } else {
1232 /* Accepted but residual slightly grew (within EMA noise allowance): reduce dtau. */
1233 next_dtau *= simCtx->pseudo_cfl_reduction_factor;
1234 recovery_streak = 0;
1235 }
1236 /* Relax the cap slowly on healthy trials: a single rejection caused by a transient
1237 * must not hold the step down for the rest of the run, but recovery has to be slow
1238 * enough that the controller does not simply walk back into the wall. */
1239 cfl_cap = PetscMin(simCtx->max_pseudo_cfl, cfl_cap * MOM_CFL_CAP_RELAX);
1240 next_dtau = PetscMin(next_dtau, dtau_max);
1241 next_dtau = PetscMin(next_dtau, cfl_cap / lambda_max);
1242 next_dtau = PetscMax(next_dtau, dtau_min);
1243 for (PetscInt bi = 0; bi < block_number; bi++) pseudo_dtau[bi] = next_dtau;
1244
1246 " Trial %" PetscInt_FMT " ACCEPTED (raw_ratio=%.4e, smoothed=%.4e); |dU|=%.6e | "
1247 "dtau %.4e -> %.4e (cfl_eff %.4f -> %.4f)\n",
1248 pseudo_iter, global_trial_ratio, trial_smoothed, global_norm_delta,
1249 old_dtau, next_dtau, old_dtau * lambda_max, next_dtau * lambda_max);
1250
1251 /* --- Post-decision file logging (one row per accepted trial) --- */
1252 if (!rank) {
1253 ierr = AppendPicardHistoryRows(simCtx, block_number, pseudo_iter, old_dtau, next_dtau, lambda_max,
1254 delta_sol_norm_curr, delta_sol_rel_curr, resid_norm_curr, resid_rel_curr,
1255 trial_ratio_log, trial_smoothed, "accepted"); CHKERRQ(ierr);
1256 }
1257
1258 /* --- Convergence decision ---
1259 *
1260 * The residual is what states that the momentum equations are satisfied at the
1261 * current state; the update norm measures progress, not correctness. The two
1262 * residual tests therefore carry different weight and are structured differently.
1263 *
1264 * converged = residual_abs_pass || (residual_rel_pass && update_pass)
1265 *
1266 * ABSOLUTE branch, sufficient on its own. |R| <= mom_resid_atol * resid_ref says
1267 * the equations are satisfied to the configured level outright, so it needs no
1268 * corroboration -- this is what an absolute tolerance means, and how PETSc's SNES
1269 * and KSP already behave. Requiring the update guard alongside it made the floor
1270 * unable to fire: measured on the laminar channel at step 793, |R| dropped below
1271 * the floor at pseudo-iteration 8 and the step still ran to 20, because
1272 * |dU|/|dU0| had not yet reached its own tolerance.
1273 *
1274 * RELATIVE branch, weaker evidence, paired with the update guard. A 1000x
1275 * reduction of |R0| says the iteration made progress from wherever it started,
1276 * not that the result is small; |R0| itself collapses as a run approaches steady
1277 * state. The guard stays mandatory here.
1278 *
1279 * The update norm is never sufficient by itself in either branch. |dU| ~ dtau*|R|,
1280 * so it goes small whenever dtau goes small -- observed as |dU| falling only ~10%
1281 * over 100 pseudo-iterations of a completely frozen iteration. An ABSOLUTE bound
1282 * on it (mom_atol) is the disguised, step-size-dependent residual bound
1283 * |R| <= mom_atol/dtau, which tightens as the controller succeeds in growing dtau;
1284 * it duplicates the residual test while pulling against it and takes no part here.
1285 *
1286 * With no residual criterion configured at all -- both residual tolerances set
1287 * non-positive, an explicit opt-out since the defaults now enable them -- the
1288 * update norms are the only information available and the legacy test is retained
1289 * unchanged.
1290 */
1291 if (residual_convergence_enabled) {
1292 const PetscBool residual_abs_pass = (PetscBool)(
1293 simCtx->mom_resid_atol > 0.0 && resid_ref > 0.0 &&
1294 global_norm_resid <= simCtx->mom_resid_atol * resid_ref);
1295 const PetscBool residual_rel_pass = (PetscBool)(
1296 simCtx->mom_resid_rtol > 0.0 && global_rel_resid <= simCtx->mom_resid_rtol);
1297 const PetscBool update_pass = (PetscBool)(
1298 tol_rtol_delta <= 0.0 || global_rel_delta <= tol_rtol_delta);
1299 converged = (PetscBool)(residual_abs_pass || (residual_rel_pass && update_pass));
1300 } else {
1301 converged = (PetscBool)(global_norm_delta <= tol_abs_delta &&
1302 global_rel_delta <= tol_rtol_delta);
1303 }
1304
1305 if (block_number > 1) {
1306 // ierr = Block_Interface_U(user); CHKERRQ(ierr);
1307 }
1308 } // End while loop
1309
1310 if (last_trial_nonfinite) {
1311 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_CONV_FAILED,
1312 "Momentum solver exhausted its attempt limit while recovering from a non-finite trial.");
1313 }
1314
1315 /* Convert the final dtau back to a CFL number for the warm-start of the next physical timestep.
1316 * simCtx->pseudo_cfl stores a dimensionless Courant number (dtau * lambda_max); the next
1317 * timestep's lambda_max may differ as the flow evolves, so storing the CFL number (not dtau)
1318 * ensures the warm-start adapts correctly to the new spectral radius. */
1319 PetscReal next_dtau_start = pseudo_dtau[0];
1320 PetscReal next_cfl_warmstart = next_dtau_start * lambda_max; /* CFL = dtau * lambda_max */
1321
1322 if (!rank) {
1324 " Step %" PetscInt_FMT " finished: dtau=%.4e cfl_eff=%.4f lambda_max=%.4e [1/s]. "
1325 "Next step warm-starts at cfl=%.4f.\n",
1326 simCtx->step, next_dtau_start, next_cfl_warmstart, lambda_max, next_cfl_warmstart);
1327 }
1328
1329 /* Store the CFL number (not dtau) so it remains meaningful across physical timesteps. */
1330 simCtx->pseudo_cfl = next_cfl_warmstart;
1331 simCtx->mom_last_lambda_max = lambda_max;
1332
1333 /* Expose the last accepted finite state. On converged or floor-break exits pUcont==Ucont
1334 already (VecCopy would be an identity), but ghosts may have gone stale; always re-sync
1335 and re-apply BCs. Only restore the solution vector itself when nothing was ever accepted. */
1336 if (accepted_iter == 0) {
1337 for (PetscInt bi = 0; bi < block_number; bi++) {
1338 ierr = VecCopy(user[bi].pUcont, user[bi].Ucont); CHKERRQ(ierr);
1339 ierr = VecCopy(user[bi].pRhs, user[bi].Rhs); CHKERRQ(ierr);
1340 }
1341 }
1342 for (PetscInt bi = 0; bi < block_number; bi++) {
1343 const FieldId staggered_fields[] = {FIELD_ID_UCONT};
1344 ierr = SynchronizePeriodicStaggeredFields(&user[bi], 1, staggered_fields); CHKERRQ(ierr);
1345 ierr = ApplyBoundaryConditions(&user[bi]); CHKERRQ(ierr);
1346 }
1347
1348 simCtx->mom_last_converged = converged;
1349 if (!converged) {
1350 PetscPrintf(PETSC_COMM_WORLD,
1351 "[WARNING] Momentum solver step %d: reached %" PetscInt_FMT " total attempts (%" PetscInt_FMT " accepted, %" PetscInt_FMT " rejected) "
1352 "without convergence; continuing from last accepted finite state.\n",
1353 (int)ti, pseudo_iter, accepted_iter, rejected_iter);
1354 }
1355 if (accepted_iter == 0) {
1356 PetscPrintf(PETSC_COMM_WORLD,
1357 "[WARNING] Momentum solver step %d: no pseudo-time trials were accepted; "
1358 "retaining physical-step entry state.\n", (int)ti);
1359 }
1361 "Momentum solver finished: %" PetscInt_FMT " attempts (%" PetscInt_FMT " accepted, %" PetscInt_FMT " rejected) of %" PetscInt_FMT " max accepted / %" PetscInt_FMT " hard cap, "
1362 "converged=%s, last accepted |R|=%.6e, last accepted |dU|=%.6e, "
1363 "next_dtau=%.4e (cfl=%.4f).\n",
1364 pseudo_iter, accepted_iter, rejected_iter, max_pseudo_steps, max_total_attempts,
1365 converged ? "yes" : "no",
1366 (accepted_iter > 0) ? last_accepted_resid : resid_norm_init[0],
1367 (accepted_iter > 0) ? delta_sol_norm_prev[0] : 0.0,
1368 next_dtau_start, next_cfl_warmstart);
1369
1370 // --- Final Cleanup ---
1371
1372 ierr = PetscFree2(delta_sol_norm_init, delta_sol_norm_prev);CHKERRQ(ierr);
1373 ierr = PetscFree2(delta_sol_norm_curr, delta_sol_rel_curr);CHKERRQ(ierr);
1374 ierr = PetscFree2(resid_norm_init, resid_norm_prev);CHKERRQ(ierr);
1375 ierr = PetscFree2(resid_norm_curr, pseudo_dtau); CHKERRQ(ierr);
1376 ierr = PetscFree(resid_rel_curr); CHKERRQ(ierr);
1377 ierr = PetscFree(trial_ratio_log); CHKERRQ(ierr);
1378
1380 PetscFunctionReturn(0);
1381}
@ LOG_TRACE
Very fine-grained tracing information for in-depth debugging.
Definition logging.h:33
static PetscErrorCode AppendPicardHistoryRows(SimCtx *simCtx, PetscInt block_number, PetscInt pseudo_iter, PetscReal dtau, PetscReal dtau_after, PetscReal lambda_max, const PetscReal *delta, const PetscReal *delta_rel, const PetscReal *resid, const PetscReal *resid_rel, const PetscReal *trial_ratio, PetscReal smoothed_ratio, const char *status)
Appends one pseudo-iteration's row per block to the Picard momentum history CSVs.
PetscReal MomentumBDFCoefficient(SimCtx *simCtx)
Returns a0 in {1.0, 1.5} for the current physical step.
#define MOM_CFL_CAP_SAFETY
static PetscErrorCode ComputeGlobalSpectralRadiusEstimate(UserCtx *user, PetscInt block_number, PetscReal dt, PetscReal *lambda_max_out)
Compute a conservative global pseudo-time spectral radius estimate.
PetscErrorCode ComputeTotalResidual(UserCtx *user)
Shared implementation of ComputeTotalResidual().
PetscErrorCode ComputeMomentumStabilityEstimate(UserCtx *user, PetscInt block_number, PetscReal dt, MomStabCandidate candidate, MomStabilityReport *rep)
Practical conservative momentum pseudo-time stability estimate (shadow).
#define MOM_CFL_CAP_RELAX
MomStabLimiter limiter
Diagnostic report produced by ComputeMomentumStabilityEstimate().
PetscMPIInt rank
Definition variables.h:919
PetscReal mom_rtol
Definition variables.h:960
PetscReal mom_last_lambda_max
Definition variables.h:974
PetscReal pseudo_cfl_reduction_factor
Definition variables.h:966
PetscReal min_pseudo_cfl
Definition variables.h:967
PetscReal mom_atol
Definition variables.h:960
PetscBool no_pseudo_cfl_backtrack
Definition variables.h:969
PetscReal max_pseudo_cfl
Definition variables.h:967
PetscReal mom_dt_jameson_residual_norm_noise_allowance_factor
Definition variables.h:968
PetscReal pseudo_cfl_growth_factor
Definition variables.h:966
PetscReal mom_resid_rtol
Definition variables.h:960
PetscInt mom_max_pseudo_steps
Definition variables.h:959
PetscReal mom_ratio_ema_alpha
Definition variables.h:970
PetscReal pseudo_cfl
Definition variables.h:965
Here is the call graph for this function:
Here is the caller graph for this function:

◆ MomentumUsesBDF2()

PetscBool MomentumUsesBDF2 ( SimCtx *  simCtx)

Returns whether the current physical step uses the BDF2 discretization.

Single source of truth for the BDF1/BDF2 selection. The predicate is identical to the one historically inlined in ComputeTotalResidual(): BDF2 when COEF_TIME_ACCURACY > 1.1 AND step != StartStep AND step != 1, otherwise BDF1 (startup step and the first step after a restart).

Parameters
simCtxMaster simulation context (reads step, StartStep).
Returns
PETSC_TRUE for BDF2, PETSC_FALSE for BDF1.

Returns whether the current physical step uses the BDF2 discretization.

See header.

The run loop increments step before invoking the momentum solve. Therefore, BDF1 applies at a fresh start until two physical states exist. A committed checkpoint restores Ucont_rm1, so a restarted solve can retain BDF2 on its first advanced step.

Definition at line 22 of file momentumsolvers.c.

23{
25 const PetscInt ti = simCtx->step;
26 const PetscInt tistart = simCtx->StartStep;
27 const PetscBool bdf2 = (PetscBool)(COEF_TIME_ACCURACY > 1.1 && ti != 1 &&
28 (simCtx->restartHistoryAvailable || ti > tistart + 1));
30 return bdf2;
31}
#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
PetscInt StartStep
Definition variables.h:926
PetscBool restartHistoryAvailable
Definition variables.h:947
#define COEF_TIME_ACCURACY
Coefficient controlling the temporal accuracy scheme (e.g., 1.5 for 2nd Order Backward Difference).
Definition variables.h:96
Here is the caller graph for this function:

◆ MomentumBDFCoefficient()

PetscReal MomentumBDFCoefficient ( SimCtx *  simCtx)

Returns the BDF physical-time coefficient a0 for the current step.

a0 = 1.5 (== COEF_TIME_ACCURACY) for BDF2, a0 = 1.0 for BDF1. Used both as the leading coefficient of the physical-time term in the residual and as the additive temporal contribution lambda_t = a0/dt in the momentum stability estimate, keeping the two numerically consistent.

Parameters
simCtxMaster simulation context.
Returns
a0 in {1.0, 1.5}.

Returns the BDF physical-time coefficient a0 for the current step.

See header.

Definition at line 36 of file momentumsolvers.c.

37{
39 const PetscReal a0 = MomentumUsesBDF2(simCtx) ? COEF_TIME_ACCURACY : 1.0;
41 return a0;
42}
PetscBool MomentumUsesBDF2(SimCtx *simCtx)
Single source of truth for the BDF1/BDF2 selection.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ComputeTotalResidual()

PetscErrorCode ComputeTotalResidual ( UserCtx *  user)

Computes the shared spatial-plus-BDF momentum residual in user->Rhs.

Parameters
userBlock context with an allocated Rhs vector.
Returns
PetscErrorCode 0 on success.

Computes the shared spatial-plus-BDF momentum residual in user->Rhs.

Definition at line 48 of file momentumsolvers.c.

49{
50 PetscErrorCode ierr;
51 SimCtx *simCtx = user->simCtx;
52
53 // Extract Time Parameters from Context.
54 // BDF step selection now lives in MomentumUsesBDF2() (shared with the stability estimate).
55 const PetscReal dt = simCtx->dt;
56
57 PetscFunctionBeginUser;
59 // 1. Calculate Spatial Terms (stored in user->Rhs)
60 // Rhs = -Div(Flux) + Viscous + Source
61 ierr = ComputeRHS(user, user->Rhs); CHKERRQ(ierr);
62
63 // 2. Add Physical Time Derivative Terms (BDF Discretization)
64 // The equation solved is: dU/dtau = RHS_Spatial + RHS_Temporal
65
66 /* BDF order + leading coefficient from the shared helpers (single source of truth,
67 shared with the momentum stability estimate). a0 = 1.5 (==COEF_TIME_ACCURACY) for
68 BDF2, 1.0 for BDF1; using a0 for the current-state term keeps the residual
69 numerically identical to the historical inlined coefficients. */
70 const PetscBool use_bdf2 = MomentumUsesBDF2(simCtx);
71 const PetscReal a0 = MomentumBDFCoefficient(simCtx);
72 if (use_bdf2) {
73 // --- BDF2 (Second Order Backward Difference) ---
74 // (a0*U^{n} - 2.0*U^{n-1} + 0.5*U^{n-2}) / dt = RHS_Spatial(U^{n})
75 ierr = VecAXPY(user->Rhs, -a0/dt, user->Ucont); CHKERRQ(ierr);
76 ierr = VecAXPY(user->Rhs, +2.0/dt, user->Ucont_o); CHKERRQ(ierr);
77 ierr = VecAXPY(user->Rhs, -0.5/dt, user->Ucont_rm1); CHKERRQ(ierr);
78 } else {
79 // --- BDF1 (First Order / Euler Implicit) ---
80 // (a0*U^{n} - U^{n-1}) / dt = RHS_Spatial(U^{n}), with a0 = 1.0
81 ierr = VecAXPY(user->Rhs, -a0/dt, user->Ucont); CHKERRQ(ierr);
82 ierr = VecAXPY(user->Rhs, +1.0/dt, user->Ucont_o); CHKERRQ(ierr);
83 }
84
85 // 3. Enforce Boundary Conditions on the Residual
86 ierr = EnforceRHSBoundaryConditions(user); CHKERRQ(ierr);
87
89 PetscFunctionReturn(0);
90}
PetscErrorCode EnforceRHSBoundaryConditions(UserCtx *user)
Zeroes every momentum RHS row that does not carry an independent unknown.
Definition Boundaries.c:224
Vec Ucont_o
Definition variables.h:1204
Vec Ucont_rm1
Definition variables.h:1207
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ComputeMomentumStabilityEstimate()

PetscErrorCode ComputeMomentumStabilityEstimate ( UserCtx *  user,
PetscInt  block_number,
PetscReal  dt,
MomStabCandidate  candidate,
MomStabilityReport *  rep 
)

Compute the momentum pseudo-time stability estimate (shadow/diagnostic).

Conservative, operator-scaled estimate: lambda = max_cell (a0/dt + lambda_c + lambda_nu), over active, non-solid cells, blocks, and MPI ranks, where lambda_c already includes the per-direction QUICK scheme factors. Read-only; performs no halo exchange, but does perform global scalar collectives (see implementation). This is a PRACTICAL CONSERVATIVE estimate, not a proven spectral radius. See the Workstream-A design.

Call-site preconditions (NOT enforced internally): lUcont, lUcat, lNu_t, lNvert must be fresh; lAj, face Jacobians and face metrics are static after grid init.

Parameters
[in]userArray of UserCtx (one per block).
[in]block_numberNumber of blocks.
[in]dtPhysical time step.
[in]candidateConvective candidate driving rep->lambda (B, C or D).
[out]repFilled diagnostic report (global maxima + breakdown).
Returns
PetscErrorCode 0 on success.

Compute the momentum pseudo-time stability estimate (shadow/diagnostic).

See header.

Operator-scaled estimate lambda = max_cell (a0/dt + lambda_c + lambda_nu) over active, non-solid interior cells, blocks and MPI ranks (lambda_c already carries the per-direction QUICK scheme factors – it is NOT multiplied by f_c again here). Read-only; no halo exchange, 5 global scalar collectives. NOT a proven spectral radius. Drives nothing in shadow mode.

Definition at line 423 of file momentumsolvers.c.

426{
427 PetscErrorCode ierr;
428 PetscMPIInt rank;
429 PetscFunctionBeginUser;
431
432 /* ---- input validation (no silent fallback) ---- */
433 PetscCheck(user != NULL, PETSC_COMM_WORLD, PETSC_ERR_ARG_NULL, "user is NULL");
434 PetscCheck(rep != NULL, PETSC_COMM_WORLD, PETSC_ERR_ARG_NULL, "rep is NULL");
435 PetscCheck(block_number > 0, PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE, "block_number must be > 0");
436 PetscCheck(candidate >= MOM_STAB_CAND_B && candidate <= MOM_STAB_CAND_D,
437 PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE, "unsupported stability candidate enum");
438 PetscCheck(PetscIsNormalReal(dt) && dt > 0.0, PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE,
439 "dt must be finite and positive");
440
441 SimCtx *simCtx = user[0].simCtx;
442 PetscCheck(simCtx != NULL, PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONGSTATE, "user[0].simCtx is NULL");
443 const PetscReal a0 = MomentumBDFCoefficient(simCtx);
444 const PetscBool centered = (PetscBool)(simCtx->les || simCtx->central);
445 const PetscBool has_nut = (PetscBool)(simCtx->les != NO_LES_MODEL);
446 const PetscBool inviscid = (PetscBool)simCtx->invicid;
447 PetscCheck(inviscid || (PetscIsNormalReal(simCtx->ren) && simCtx->ren > 0.0),
448 PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE, "Reynolds number must be finite and positive when viscous");
449 const PetscReal lambda_t = a0 / dt;
450 const PetscReal nu_mol = inviscid ? 0.0 : 1.0 / simCtx->ren;
451 const PetscInt twoD = simCtx->TwoD;
452
453 /* Shadow-mode completeness flag. The estimate does NOT cover the Clark nonlinear stress
454 Jacobian (not verified sign-definite).
455 Body forces in the supported configs read a per-timestep-frozen scalar
456 (simCtx->bulkVelocityCorrection) inside ComputeRHS, so within a pseudo-solve they are a
457 constant forcing with ZERO velocity Jacobian (consistent with the frozen-pressure
458 treatment) -- they do not make the estimate incomplete. */
459 rep->estimate_incomplete = (PetscBool)(simCtx->les_gradient_model);
460
461 rank = user->simCtx->rank;
462
463 /* Per-candidate local maxima; selected candidate also tracks the controlling cell. */
464 PetscReal locmaxB = 0.0, locmaxC = 0.0, locmaxD = 0.0, sel_max = 0.0;
465 PetscReal sel_lc = 0.0, sel_lv = 0.0;
466 PetscInt sel_ci = -1, sel_cj = -1, sel_ck = -1, sel_blk = -1, sel_class = 0, sel_os = 0;
467 PetscInt local_active = 0;
468
469 for (PetscInt bi = 0; bi < block_number; bi++) {
470 UserCtx *u = &user[bi];
471 DMDALocalInfo info = u->info;
472 const PetscInt mx = info.mx, my = info.my, mz = info.mz;
473 const PetscInt xs = info.xs, xe = xs + info.xm;
474 const PetscInt ys = info.ys, ye = ys + info.ym;
475 const PetscInt zs = info.zs, ze = zs + info.zm;
476 /* Interior range == where ComputeRHS evaluates the residual; boundary faces
477 (0 and m-1) are RHS-masked, so excluding them implements active-row masking
478 for the normal boundary rows. The last physical face (m-2) stays IN with the
479 full cell estimate (its tangential rows remain active). */
480 const PetscInt lxs = (xs==0)?xs+1:xs, lxe = (xe==mx)?xe-1:xe;
481 const PetscInt lys = (ys==0)?ys+1:ys, lye = (ye==my)?ye-1:ye;
482 const PetscInt lzs = (zs==0)?zs+1:zs, lze = (ze==mz)?ze-1:ze;
483
484 /* Non-periodic boundary flags (QUICK stencil is degraded near these). */
485 const PetscBool npx0 = (PetscBool)(u->boundary_faces[BC_FACE_NEG_X].mathematical_type != PERIODIC);
486 const PetscBool npx1 = (PetscBool)(u->boundary_faces[BC_FACE_POS_X].mathematical_type != PERIODIC);
487 const PetscBool npy0 = (PetscBool)(u->boundary_faces[BC_FACE_NEG_Y].mathematical_type != PERIODIC);
488 const PetscBool npy1 = (PetscBool)(u->boundary_faces[BC_FACE_POS_Y].mathematical_type != PERIODIC);
489 const PetscBool npz0 = (PetscBool)(u->boundary_faces[BC_FACE_NEG_Z].mathematical_type != PERIODIC);
490 const PetscBool npz1 = (PetscBool)(u->boundary_faces[BC_FACE_POS_Z].mathematical_type != PERIODIC);
491 const PetscBool wxn = BoundaryFaceHasWallShear(&u->boundary_faces[BC_FACE_NEG_X]);
492 const PetscBool wxp = BoundaryFaceHasWallShear(&u->boundary_faces[BC_FACE_POS_X]);
493 const PetscBool wyn = BoundaryFaceHasWallShear(&u->boundary_faces[BC_FACE_NEG_Y]);
494 const PetscBool wyp = BoundaryFaceHasWallShear(&u->boundary_faces[BC_FACE_POS_Y]);
495 const PetscBool wzn = BoundaryFaceHasWallShear(&u->boundary_faces[BC_FACE_NEG_Z]);
496 const PetscBool wzp = BoundaryFaceHasWallShear(&u->boundary_faces[BC_FACE_POS_Z]);
497
498 Cmpnts ***ucont, ***ucat = NULL;
499 Cmpnts ***icsi, ***ieta, ***izet, ***jcsi, ***jeta, ***jzet, ***kcsi, ***keta, ***kzet;
500 Cmpnts ***csi = NULL, ***eta = NULL, ***zet = NULL;
501 PetscReal ***aj, ***iaj, ***jaj, ***kaj, ***nvert, ***nut = NULL;
502
503 ierr = DMDAVecGetArrayRead(u->fda, u->lUcont, &ucont); CHKERRQ(ierr);
504 ierr = DMDAVecGetArrayRead(u->da, u->lAj, &aj); CHKERRQ(ierr);
505 ierr = DMDAVecGetArrayRead(u->da, u->lIAj, &iaj); CHKERRQ(ierr);
506 ierr = DMDAVecGetArrayRead(u->da, u->lJAj, &jaj); CHKERRQ(ierr);
507 ierr = DMDAVecGetArrayRead(u->da, u->lKAj, &kaj); CHKERRQ(ierr);
508 ierr = DMDAVecGetArrayRead(u->fda, u->lICsi, &icsi); CHKERRQ(ierr);
509 ierr = DMDAVecGetArrayRead(u->fda, u->lIEta, &ieta); CHKERRQ(ierr);
510 ierr = DMDAVecGetArrayRead(u->fda, u->lIZet, &izet); CHKERRQ(ierr);
511 ierr = DMDAVecGetArrayRead(u->fda, u->lJCsi, &jcsi); CHKERRQ(ierr);
512 ierr = DMDAVecGetArrayRead(u->fda, u->lJEta, &jeta); CHKERRQ(ierr);
513 ierr = DMDAVecGetArrayRead(u->fda, u->lJZet, &jzet); CHKERRQ(ierr);
514 ierr = DMDAVecGetArrayRead(u->fda, u->lKCsi, &kcsi); CHKERRQ(ierr);
515 ierr = DMDAVecGetArrayRead(u->fda, u->lKEta, &keta); CHKERRQ(ierr);
516 ierr = DMDAVecGetArrayRead(u->fda, u->lKZet, &kzet); CHKERRQ(ierr);
517 ierr = DMDAVecGetArrayRead(u->da, u->lNvert, &nvert); CHKERRQ(ierr);
518 if (has_nut) { ierr = DMDAVecGetArrayRead(u->da, u->lNu_t, &nut); CHKERRQ(ierr); }
519 /* Cartesian velocity + cell metrics: always read so candidate D's gradient term
520 (and hence rep->lambda_D) is meaningful regardless of the selected candidate.
521 Precondition: lUcat fresh (Contra2Cart has run in the preceding residual eval). */
522 ierr = DMDAVecGetArrayRead(u->fda, u->lUcat, &ucat); CHKERRQ(ierr);
523 ierr = DMDAVecGetArrayRead(u->fda, u->lCsi, &csi); CHKERRQ(ierr);
524 ierr = DMDAVecGetArrayRead(u->fda, u->lEta, &eta); CHKERRQ(ierr);
525 ierr = DMDAVecGetArrayRead(u->fda, u->lZet, &zet); CHKERRQ(ierr);
526
527 /* Error flag for the cell loop: on a bad metric/estimate we record the location and
528 jump to block_cleanup so EVERY acquired array is restored before the error returns. */
529 PetscErrorCode cell_err = 0;
530 PetscInt be_i = -1, be_j = -1, be_k = -1;
531 const char *be_what = NULL;
532
533 for (PetscInt k = lzs; k < lze; k++) {
534 for (PetscInt j = lys; j < lye; j++) {
535 for (PetscInt i = lxs; i < lxe; i++) {
536 /* ---- active-row mask: skip only locations with no active unknown ---- */
537 const PetscInt rows = MomCellActiveRows(nvert, k, j, i, mx, my, mz,
538 npx1, npy1, npz1, twoD);
539 if (rows == 0) continue;
540 local_active++;
541 const PetscReal Ajc = aj[k][j][i];
542 if (!(PetscIsNormalReal(Ajc) && Ajc > 0.0)) {
543 cell_err = PETSC_ERR_FP; be_i = i; be_j = j; be_k = k;
544 be_what = "non-finite/non-positive cell inverse-Jacobian";
545 goto block_cleanup;
546 }
547
548 /* ---- directional QUICK modification (per direction; both faces; 2nd neighbour) ---- */
549 const PetscBool mod_x = MomQuickDirModified(nvert, k, j, i, i, mx, npx0, npx1,
550 info.gxs, info.gxs+info.gxm, 'i');
551 const PetscBool mod_y = MomQuickDirModified(nvert, k, j, i, j, my, npy0, npy1,
552 info.gys, info.gys+info.gym, 'j');
553 const PetscBool mod_z = MomQuickDirModified(nvert, k, j, i, k, mz, npz0, npz1,
554 info.gzs, info.gzs+info.gzm, 'k');
555
556 /* ---- classify cell: interior / physical-boundary / IB-adjacent ---- */
557 const PetscBool bnd = (PetscBool)((npx0 && i<=1) || (npx1 && i>=mx-2) ||
558 (npy0 && j<=1) || (npy1 && j>=my-2) ||
559 (npz0 && k<=1) || (npz1 && k>=mz-2));
560 const PetscBool ib = MomCellHasSolidNeighbor(nvert, k, j, i);
561 const PetscInt cls = ib ? 2 : (bnd ? 1 : 0);
562
563 /* ---- convective: six contravariant face fluxes, DIRECTIONAL QUICK factors ---- */
564 const PetscReal Uxp = ucont[k][j][i].x, Uxm = ucont[k][j][i-1].x;
565 const PetscReal Uyp = ucont[k][j][i].y, Uym = ucont[k][j-1][i].y;
566 const PetscReal Uzp = ucont[k][j][i].z, Uzm = ucont[k-1][j][i].z;
567 const PetscReal divU = PetscAbsReal((Uxp-Uxm)+(Uyp-Uym)+(Uzp-Uzm));
568 const PetscReal fx = centered ? 1.0 : (mod_x ? 2.5 : (4.0/3.0));
569 const PetscReal fy = centered ? 1.0 : (mod_y ? 2.5 : (4.0/3.0));
570 const PetscReal fz = centered ? 1.0 : (mod_z ? 2.5 : (4.0/3.0));
571
572 /* per-direction transport scale; C's divergence term stays unscaled by f_d. */
573 const PetscReal lcB = 0.5 * Ajc * (
574 fx * (PetscAbsReal(Uxp)+PetscAbsReal(Uxm))
575 + fy * (PetscAbsReal(Uyp)+PetscAbsReal(Uym))
576 + fz * (PetscAbsReal(Uzp)+PetscAbsReal(Uzm)) );
577 const PetscReal lcC = lcB + 0.5 * Ajc * divU;
578 /* lambda_grad_u = max_i sum_j |du_i/dx_j| from fresh Cartesian velocity
579 (the nonlinear zero-order Jacobian term delta_u . grad u).
580 Physical gradient: d/dx_dir = Ajc*(Csi.dir d/dxi + Eta.dir d/deta + Zet.dir d/dzeta). */
581 const Cmpnts duc = { 0.5*(ucat[k][j][i+1].x-ucat[k][j][i-1].x),
582 0.5*(ucat[k][j][i+1].y-ucat[k][j][i-1].y),
583 0.5*(ucat[k][j][i+1].z-ucat[k][j][i-1].z) };
584 const Cmpnts due = { 0.5*(ucat[k][j+1][i].x-ucat[k][j-1][i].x),
585 0.5*(ucat[k][j+1][i].y-ucat[k][j-1][i].y),
586 0.5*(ucat[k][j+1][i].z-ucat[k][j-1][i].z) };
587 const Cmpnts duz = { 0.5*(ucat[k+1][j][i].x-ucat[k-1][j][i].x),
588 0.5*(ucat[k+1][j][i].y-ucat[k-1][j][i].y),
589 0.5*(ucat[k+1][j][i].z-ucat[k-1][j][i].z) };
590 const Cmpnts C = csi[k][j][i], E = eta[k][j][i], Z = zet[k][j][i];
591 #define MOM_ROW(cmp) ( \
592 PetscAbsReal(Ajc*(C.x*duc.cmp + E.x*due.cmp + Z.x*duz.cmp)) + \
593 PetscAbsReal(Ajc*(C.y*duc.cmp + E.y*due.cmp + Z.y*duz.cmp)) + \
594 PetscAbsReal(Ajc*(C.z*duc.cmp + E.z*due.cmp + Z.z*duz.cmp)) )
595 const PetscReal lgrad = PetscMax(MOM_ROW(x), PetscMax(MOM_ROW(y), MOM_ROW(z)));
596 #undef MOM_ROW
597 const PetscReal lcD = lcC + lgrad;
598
599 /* ---- viscous: six faces, face Jacobians, full metric rows ---- */
600 PetscReal lv = 0.0;
601 if (!inviscid) {
602 /* xi+ (i), xi- (i-1) */
603 for (PetscInt s = 0; s < 2; s++) {
604 const PetscInt fi = (s==0) ? i : i-1;
605 if (!(PetscIsNormalReal(iaj[k][j][fi]) && iaj[k][j][fi] > 0.0)) {
606 cell_err = PETSC_ERR_FP; be_i=i; be_j=j; be_k=k;
607 be_what = "non-finite/non-positive xi-face inverse-Jacobian"; goto block_cleanup; }
608 PetscReal nuf = nu_mol;
609 if (has_nut) {
610 PetscReal nt = 0.5*(nut[k][j][fi] + nut[k][j][fi+1]);
611 if ((wxn && fi==0) || (wxp && fi==mx-2)) nt = 0.0;
612 nuf += nt;
613 }
614 lv += PetscAbsReal(nuf) * Ajc * iaj[k][j][fi]
615 * MomFaceGabs(icsi[k][j][fi], ieta[k][j][fi], izet[k][j][fi]);
616 }
617 /* eta+ (j), eta- (j-1) */
618 for (PetscInt s = 0; s < 2; s++) {
619 const PetscInt fj = (s==0) ? j : j-1;
620 if (!(PetscIsNormalReal(jaj[k][fj][i]) && jaj[k][fj][i] > 0.0)) {
621 cell_err = PETSC_ERR_FP; be_i=i; be_j=j; be_k=k;
622 be_what = "non-finite/non-positive eta-face inverse-Jacobian"; goto block_cleanup; }
623 PetscReal nuf = nu_mol;
624 if (has_nut) {
625 PetscReal nt = 0.5*(nut[k][fj][i] + nut[k][fj+1][i]);
626 if ((wyn && fj==0) || (wyp && fj==my-2)) nt = 0.0;
627 nuf += nt;
628 }
629 /* eta-face normal is the eta metric (jeta) -> pass as N. */
630 lv += PetscAbsReal(nuf) * Ajc * jaj[k][fj][i]
631 * MomFaceGabs(jeta[k][fj][i], jcsi[k][fj][i], jzet[k][fj][i]);
632 }
633 /* zeta+ (k), zeta- (k-1) */
634 for (PetscInt s = 0; s < 2; s++) {
635 const PetscInt fk = (s==0) ? k : k-1;
636 if (!(PetscIsNormalReal(kaj[fk][j][i]) && kaj[fk][j][i] > 0.0)) {
637 cell_err = PETSC_ERR_FP; be_i=i; be_j=j; be_k=k;
638 be_what = "non-finite/non-positive zeta-face inverse-Jacobian"; goto block_cleanup; }
639 PetscReal nuf = nu_mol;
640 if (has_nut) {
641 PetscReal nt = 0.5*(nut[fk][j][i] + nut[fk+1][j][i]);
642 if ((wzn && fk==0) || (wzp && fk==mz-2)) nt = 0.0;
643 nuf += nt;
644 }
645 /* zeta-face normal is the zeta metric (kzet) -> pass as N. */
646 lv += PetscAbsReal(nuf) * Ajc * kaj[fk][j][i]
647 * MomFaceGabs(kzet[fk][j][i], kcsi[fk][j][i], keta[fk][j][i]);
648 }
649 lv *= 4.0; /* 2 (two-face row-sum) x 2 (longitudinal full-stress) */
650 }
651
652 /* one-sided viscous cross-derivative branch near a solid: conservative x2,
653 applied ONCE per cell, after a complete 3x3x3 solid-band check. */
654 PetscInt one_sided = 0;
655 if (!inviscid && MomCellUsesOneSidedViscousStencil(nvert, k, j, i)) {
656 one_sided = 1;
657 lv *= 2.0;
658 }
659
660 /* ---- candidate totals and running maxima ---- */
661 const PetscReal lB = lambda_t + lcB + lv;
662 const PetscReal lC = lambda_t + lcC + lv;
663 const PetscReal lD = lambda_t + lcD + lv;
664 if (PetscIsInfOrNanReal(lD)) {
665 cell_err = PETSC_ERR_FP; be_i=i; be_j=j; be_k=k;
666 be_what = "non-finite stability estimate"; goto block_cleanup;
667 }
668 locmaxB = PetscMax(locmaxB, lB);
669 locmaxC = PetscMax(locmaxC, lC);
670 locmaxD = PetscMax(locmaxD, lD);
671
672 const PetscReal lsel = (candidate==MOM_STAB_CAND_B)?lB:(candidate==MOM_STAB_CAND_C)?lC:lD;
673 const PetscReal lcsel = (candidate==MOM_STAB_CAND_B)?lcB:(candidate==MOM_STAB_CAND_C)?lcC:lcD;
674 if (lsel > sel_max) {
675 sel_max = lsel; sel_lc = lcsel; sel_lv = lv;
676 sel_ci = i; sel_cj = j; sel_ck = k; sel_blk = bi;
677 sel_class = cls; sel_os = one_sided;
678 }
679 }
680 }
681 }
682
683 /* Single cleanup point: reached on normal completion AND on any cell-loop error.
684 Every successful GetArrayRead above has exactly one matching restore here. */
685 block_cleanup:
686 ierr = DMDAVecRestoreArrayRead(u->fda, u->lUcont, &ucont); CHKERRQ(ierr);
687 ierr = DMDAVecRestoreArrayRead(u->da, u->lAj, &aj); CHKERRQ(ierr);
688 ierr = DMDAVecRestoreArrayRead(u->da, u->lIAj, &iaj); CHKERRQ(ierr);
689 ierr = DMDAVecRestoreArrayRead(u->da, u->lJAj, &jaj); CHKERRQ(ierr);
690 ierr = DMDAVecRestoreArrayRead(u->da, u->lKAj, &kaj); CHKERRQ(ierr);
691 ierr = DMDAVecRestoreArrayRead(u->fda, u->lICsi, &icsi); CHKERRQ(ierr);
692 ierr = DMDAVecRestoreArrayRead(u->fda, u->lIEta, &ieta); CHKERRQ(ierr);
693 ierr = DMDAVecRestoreArrayRead(u->fda, u->lIZet, &izet); CHKERRQ(ierr);
694 ierr = DMDAVecRestoreArrayRead(u->fda, u->lJCsi, &jcsi); CHKERRQ(ierr);
695 ierr = DMDAVecRestoreArrayRead(u->fda, u->lJEta, &jeta); CHKERRQ(ierr);
696 ierr = DMDAVecRestoreArrayRead(u->fda, u->lJZet, &jzet); CHKERRQ(ierr);
697 ierr = DMDAVecRestoreArrayRead(u->fda, u->lKCsi, &kcsi); CHKERRQ(ierr);
698 ierr = DMDAVecRestoreArrayRead(u->fda, u->lKEta, &keta); CHKERRQ(ierr);
699 ierr = DMDAVecRestoreArrayRead(u->fda, u->lKZet, &kzet); CHKERRQ(ierr);
700 ierr = DMDAVecRestoreArrayRead(u->da, u->lNvert, &nvert); CHKERRQ(ierr);
701 if (has_nut) { ierr = DMDAVecRestoreArrayRead(u->da, u->lNu_t, &nut); CHKERRQ(ierr); }
702 ierr = DMDAVecRestoreArrayRead(u->fda, u->lUcat, &ucat); CHKERRQ(ierr);
703 ierr = DMDAVecRestoreArrayRead(u->fda, u->lCsi, &csi); CHKERRQ(ierr);
704 ierr = DMDAVecRestoreArrayRead(u->fda, u->lEta, &eta); CHKERRQ(ierr);
705 ierr = DMDAVecRestoreArrayRead(u->fda, u->lZet, &zet); CHKERRQ(ierr);
706
707 /* Now that this block's arrays are restored, surface any cell-loop error. */
708 PetscCheck(cell_err == 0, PETSC_COMM_SELF, cell_err, "%s at (%" PetscInt_FMT
709 ",%" PetscInt_FMT ",%" PetscInt_FMT ")", be_what ? be_what : "error", be_i, be_j, be_k);
710 }
711
712 /* ---- global reductions (no ghost/halo exchange; scalar collectives only) ----
713 5 collectives total: one 3-element MAX (B/C/D), one SUM (active-cell count),
714 one MIN (portable owner selection), and two broadcasts (the controlling-cell
715 real breakdown and integer indices). */
716 PetscReal loc3[3] = { locmaxB, locmaxC, locmaxD }, glo3[3];
717 ierr = MPI_Allreduce(loc3, glo3, 3, MPIU_REAL, MPI_MAX, PETSC_COMM_WORLD); CHKERRQ(ierr);
718
719 PetscInt global_active = 0;
720 ierr = MPI_Allreduce(&local_active, &global_active, 1, MPIU_INT, MPI_SUM, PETSC_COMM_WORLD); CHKERRQ(ierr);
721
722 /* The selected candidate's global max equals glo3[candidate] (no extra reduction).
723 Portable owner pick: lowest rank whose local sel_max equals the global max. */
724 const PetscReal sel_global = glo3[(int)candidate];
725 PetscMPIInt nproc, claim, owner;
726 nproc = user->simCtx->size;
727 claim = (sel_max == sel_global) ? rank : nproc;
728 ierr = MPI_Allreduce(&claim, &owner, 1, MPI_INT, MPI_MIN, PETSC_COMM_WORLD); CHKERRQ(ierr);
729 if (owner == nproc) owner = 0; /* no active cell anywhere: deterministic fallback owner */
730
731 PetscReal dbuf[2] = { sel_lc, sel_lv };
732 PetscInt ibuf[6] = { sel_ci, sel_cj, sel_ck, sel_blk, sel_class, sel_os };
733 ierr = MPI_Bcast(dbuf, 2, MPIU_REAL, owner, PETSC_COMM_WORLD); CHKERRQ(ierr);
734 ierr = MPI_Bcast(ibuf, 6, MPIU_INT, owner, PETSC_COMM_WORLD); CHKERRQ(ierr);
735
736 rep->lambda_t = lambda_t;
737 rep->lambda_c = dbuf[0];
738 rep->lambda_v = dbuf[1];
739 rep->lambda = sel_global;
740 rep->lambda_B = glo3[0]; rep->lambda_C = glo3[1]; rep->lambda_D = glo3[2];
741 rep->ci = ibuf[0]; rep->cj = ibuf[1]; rep->ck = ibuf[2];
742 rep->cblock = ibuf[3]; rep->cclass = ibuf[4]; rep->one_sided = ibuf[5];
743 rep->active_cells = global_active;
744
745 /* Only a genuinely empty active set (all cells masked) may fall back to the temporal
746 term alone. A non-finite or non-positive estimate with active cells is a hard error. */
747 if (global_active == 0) {
748 rep->lambda = lambda_t;
749 } else {
750 PetscCheck(PetscIsNormalReal(rep->lambda) && rep->lambda > 0.0, PETSC_COMM_WORLD, PETSC_ERR_FP,
751 "momentum stability estimate is non-finite or non-positive with %" PetscInt_FMT
752 " active cells", global_active);
753 }
754
755 /* Dominant limiter at the controlling cell. */
756 if (rep->lambda_t >= rep->lambda_c && rep->lambda_t >= rep->lambda_v) rep->limiter = MOM_STAB_LIMITER_TIME;
757 else if (rep->lambda_c >= rep->lambda_v) rep->limiter = MOM_STAB_LIMITER_CONVECTION;
759
761 PetscFunctionReturn(0);
762}
PetscBool BoundaryFaceHasWallShear(const BoundaryFaceConfig *face)
Reports whether a boundary face is a wall that exerts shear on the flow.
Definition Boundaries.c:9
#define MOM_ROW(cmp)
static PetscBool MomQuickDirModified(PetscReal ***nvert, PetscInt a, PetscInt b, PetscInt c, PetscInt idx, PetscInt m, PetscBool np0, PetscBool np1, PetscInt g0, PetscInt g1, char dir)
static PetscBool MomCellHasSolidNeighbor(PetscReal ***nvert, PetscInt k, PetscInt j, PetscInt i)
static PetscReal MomFaceGabs(Cmpnts N, Cmpnts A, Cmpnts B)
PetscInt MomCellActiveRows(PetscReal ***nvert, PetscInt k, PetscInt j, PetscInt i, PetscInt mx, PetscInt my, PetscInt mz, PetscBool np_x1, PetscBool np_y1, PetscBool np_z1, PetscInt twoD)
Active staggered-momentum row mask for a cell (exposed for unit testing).
static PetscBool MomCellUsesOneSidedViscousStencil(PetscReal ***nvert, PetscInt k, PetscInt j, PetscInt i)
PetscBool estimate_incomplete
@ NO_LES_MODEL
Definition variables.h:584
@ PERIODIC
Definition variables.h:325
PetscInt TwoD
Definition variables.h:951
BoundaryFaceConfig boundary_faces[6]
Definition variables.h:1182
Vec lIEta
Definition variables.h:1254
Vec lIZet
Definition variables.h:1254
Vec lNvert
Definition variables.h:1197
PetscReal ren
Definition variables.h:965
Vec lKEta
Definition variables.h:1256
Vec lJCsi
Definition variables.h:1255
PetscScalar x
Definition variables.h:145
PetscInt invicid
Definition variables.h:951
Vec lKZet
Definition variables.h:1256
Vec lNu_t
Definition variables.h:1259
Vec lJEta
Definition variables.h:1255
PetscInt les_gradient_model
Add the Clark gradient (tensor-diffusivity) term to the viscous flux.
Definition variables.h:1045
PetscScalar z
Definition variables.h:145
Vec lKCsi
Definition variables.h:1256
PetscInt central
Definition variables.h:963
Vec lJZet
Definition variables.h:1255
Vec lUcont
Definition variables.h:1197
Vec lICsi
Definition variables.h:1254
DMDALocalInfo info
Definition variables.h:1169
Vec lUcat
Definition variables.h:1197
PetscScalar y
Definition variables.h:145
PetscMPIInt size
Definition variables.h:920
PetscInt les
Active LES closure; an LESModelType value.
Definition variables.h:1041
BCType mathematical_type
Definition variables.h:426
@ 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
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:

◆ MomCellActiveRows()

PetscInt MomCellActiveRows ( PetscReal ***  nvert,
PetscInt  k,
PetscInt  j,
PetscInt  i,
PetscInt  mx,
PetscInt  my,
PetscInt  mz,
PetscBool  np_x1,
PetscBool  np_y1,
PetscBool  np_z1,
PetscInt  twoD 
)

Active staggered-momentum row mask for a cell (exposed for unit testing).

Returns a 3-bit mask (xi=1, eta=2, zeta=4). A solid cell yields 0 (all inactive); a positive solid neighbour or a positive non-periodic physical face clears the corresponding normal row; TwoD (1/2/3) clears the homogeneous direction's row.

Parameters
nvertLocal nvert array (ghosted).
kCell k index.
jCell j index.
iCell i index.
mxGlobal x dimension.
myGlobal y dimension.
mzGlobal z dimension.
np_x1True if the positive-x face is non-periodic.
np_y1True if the positive-y face is non-periodic.
np_z1True if the positive-z face is non-periodic.
twoDTwoD homogeneous-direction selector (0 none, 1 xi, 2 eta, 3 zeta).
Returns
3-bit active-row mask (0 when the location carries no active unknown).

Definition at line 395 of file momentumsolvers.c.

398{
400 if (nvert[k][j][i] > POISSON_SOLID_THRESHOLD) { PROFILE_HELPER_END; return 0; } /* solid cell: all rows inactive */
401 PetscInt bits = 0x7;
402 if (nvert[k][j][i+1] > POISSON_SOLID_THRESHOLD) bits &= ~0x1; /* positive xi neighbour solid */
403 if (nvert[k][j+1][i] > POISSON_SOLID_THRESHOLD) bits &= ~0x2; /* positive eta neighbour solid */
404 if (nvert[k+1][j][i] > POISSON_SOLID_THRESHOLD) bits &= ~0x4; /* positive zeta neighbour solid */
405 if (np_x1 && i == mx-2) bits &= ~0x1; /* positive non-periodic xi face */
406 if (np_y1 && j == my-2) bits &= ~0x2;
407 if (np_z1 && k == mz-2) bits &= ~0x4;
408 if (twoD == 1) bits &= ~0x1; /* TwoD homogeneous direction: xi */
409 else if (twoD == 2) bits &= ~0x2; /* eta */
410 else if (twoD == 3) bits &= ~0x4; /* zeta */
412 return bits;
413}
#define POISSON_SOLID_THRESHOLD
Cells whose nvert exceeds this value are solid.
Definition poisson.h:29
Here is the caller graph for this function: