PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
test_momentum_newton_boundary_fixedpoint.c
Go to the documentation of this file.
1/**
2 * @file test_momentum_newton_boundary_fixedpoint.c
3 * @brief Opt-in integration regression for the Newton--Krylov deterministic
4 * Cartesian-seed correction on the production-sized straight duct.
5 *
6 * The diagnostic phase established that the production Newton--Krylov residual
7 * must reconstruct Ucat/lUcat from the current SNES trial vector X before the
8 * first boundary sweep (see src/momentum_newton_krylov.c). That correction is
9 * now in production. This file locks the resulting guarantees in place using the
10 * *actual production* residual callback (included via a privately renamed copy of
11 * the production translation unit) -- it deliberately does NOT keep a duplicate
12 * test-local seeded callback, so it exercises exactly what ships:
13 *
14 * 1. residual purity at the reproduced physical step-2 state (immediate and
15 * after real PETSc MFFD products);
16 * 2. a complete production step-2 solve from the true projected step-1 state
17 * using PETSc's default classical Gram--Schmidt;
18 * 3. boundary-map compatibility: the converged three-pass solution also zeros
19 * the 24-pass outlet residual;
20 * 4. clean pressure projection of the converged momentum state.
21 *
22 * The heavy fixture keeps this target out of `make check`; the cheap
23 * seed-removal detector lives in unit-newton-krylov (default suite). Central
24 * checks run on one and four MPI ranks.
25 */
26
27#include "test_support.h"
28#include "initialcondition.h"
29#include "runloop.h"
30#include "solvers.h"
31
32#define MomentumSolver_NewtonKrylov MomentumSolver_NewtonKrylov_BoundaryFixedpointPrivateCopy
33#define MomentumSolver_NewtonKrylov_Destroy MomentumSolver_NewtonKrylov_Destroy_BoundaryFixedpointPrivateCopy
34#include "../../src/momentum_newton_krylov.c"
35#undef MomentumSolver_NewtonKrylov
36#undef MomentumSolver_NewtonKrylov_Destroy
37
38/* ======================================================================== */
39/* Persistent-state snapshot machinery (solve-entry restore). */
40/* ======================================================================== */
41
42#define FP_FIELD_COUNT 16
43#define FP_SCALAR_COUNT 9
44
45typedef struct {
46 Vec value[FP_FIELD_COUNT];
47 PetscReal scalar[FP_SCALAR_COUNT];
49
50/** @brief Collects the persistent vectors observed by the residual/boundary path. */
51static void FpGetVectors(UserCtx *user, Vec field[FP_FIELD_COUNT])
52{
53 field[0] = user->Ucont; field[1] = user->lUcont;
54 field[2] = user->Ucat; field[3] = user->lUcat;
55 field[4] = user->P; field[5] = user->lP;
56 field[6] = user->Bcs.Ubcs; field[7] = user->Bcs.Uch;
57 field[8] = user->Rhs;
58 field[9] = user->Ucont_o; field[10] = user->lUcont_o;
59 field[11] = user->Ucont_rm1; field[12] = user->lUcont_rm1;
60 field[13] = user->Ucat_o; field[14] = user->P_o;
61 field[15] = user->CellVectorAtCorner;
62}
63
64/** @brief Collects the persistent scalar diagnostics maintained by boundary processing. */
65static void FpGetScalars(UserCtx *user, PetscReal scalar[FP_SCALAR_COUNT])
66{
67 SimCtx *s = user->simCtx;
68 scalar[0] = s->FluxInSum; scalar[1] = s->FluxOutSum;
69 scalar[2] = s->FarFluxInSum; scalar[3] = s->FarFluxOutSum;
70 scalar[4] = s->Fluxsum; scalar[5] = s->AreaInSum;
71 scalar[6] = s->AreaOutSum; scalar[7] = s->bulkVelocityCorrection;
72 scalar[8] = s->boundaryVelocityCorrection;
73}
74
75/** @brief Deep-copies the audited persistent state into a test-owned snapshot. */
76static PetscErrorCode FpCapture(UserCtx *user, FpSnapshot *snap)
77{
78 Vec field[FP_FIELD_COUNT];
79 PetscFunctionBeginUser;
80 memset(snap, 0, sizeof(*snap));
81 FpGetVectors(user, field);
82 for (PetscInt i = 0; i < FP_FIELD_COUNT; ++i) {
83 if (field[i]) {
84 PetscCall(VecDuplicate(field[i], &snap->value[i]));
85 PetscCall(VecCopy(field[i], snap->value[i]));
86 }
87 }
88 FpGetScalars(user, snap->scalar);
89 PetscFunctionReturn(PETSC_SUCCESS);
90}
91
92/** @brief Restores a previously captured persistent-state snapshot. */
93static PetscErrorCode FpRestore(UserCtx *user, const FpSnapshot *snap)
94{
95 Vec field[FP_FIELD_COUNT];
96 SimCtx *s = user->simCtx;
97 PetscFunctionBeginUser;
98 FpGetVectors(user, field);
99 for (PetscInt i = 0; i < FP_FIELD_COUNT; ++i)
100 if (field[i] && snap->value[i]) PetscCall(VecCopy(snap->value[i], field[i]));
101 s->FluxInSum = snap->scalar[0]; s->FluxOutSum = snap->scalar[1];
102 s->FarFluxInSum = snap->scalar[2]; s->FarFluxOutSum = snap->scalar[3];
103 s->Fluxsum = snap->scalar[4]; s->AreaInSum = snap->scalar[5];
104 s->AreaOutSum = snap->scalar[6]; s->bulkVelocityCorrection = snap->scalar[7];
106 PetscFunctionReturn(PETSC_SUCCESS);
107}
108
109/** @brief Releases all vectors owned by one persistent-state snapshot. */
110static PetscErrorCode FpDestroy(FpSnapshot *snap)
111{
112 PetscFunctionBeginUser;
113 for (PetscInt i = 0; i < FP_FIELD_COUNT; ++i) PetscCall(VecDestroy(&snap->value[i]));
114 PetscFunctionReturn(PETSC_SUCCESS);
115}
116
117/* ======================================================================== */
118/* Collective norm helpers. */
119/* ======================================================================== */
120
121/** @brief Computes collective global difference norms for global or rank-local vectors. */
122static PetscErrorCode CollectiveDifference(Vec a, Vec b, PetscReal *norm_inf, PetscReal *norm_2)
123{
124 Vec delta = NULL;
125 MPI_Comm comm;
126 PetscMPIInt comm_size, world_size;
127 PetscReal local_inf, local_2;
128 PetscFunctionBeginUser;
129 PetscCall(VecDuplicate(a, &delta));
130 PetscCall(VecWAXPY(delta, -1.0, a, b));
131 PetscCall(VecNorm(delta, NORM_INFINITY, &local_inf));
132 PetscCall(VecNorm(delta, NORM_2, &local_2));
133 comm = PetscObjectComm((PetscObject)a);
134 PetscCallMPI(MPI_Comm_size(comm, &comm_size));
135 PetscCallMPI(MPI_Comm_size(PETSC_COMM_WORLD, &world_size));
136 if (comm_size == 1 && world_size > 1) {
137 PetscReal square = local_2 * local_2;
138 PetscCallMPI(MPI_Allreduce(&local_inf, norm_inf, 1, MPIU_REAL, MPI_MAX, PETSC_COMM_WORLD));
139 PetscCallMPI(MPI_Allreduce(&square, norm_2, 1, MPIU_REAL, MPI_SUM, PETSC_COMM_WORLD));
140 *norm_2 = PetscSqrtReal(*norm_2);
141 } else {
142 *norm_inf = local_inf;
143 *norm_2 = local_2;
144 }
145 PetscCall(VecDestroy(&delta));
146 PetscFunctionReturn(PETSC_SUCCESS);
147}
148
149/** @brief Finds the MPI rank containing the largest local entry difference. */
150static PetscErrorCode DifferenceMaxRank(Vec a, Vec b, PetscMPIInt *max_rank)
151{
152 const PetscScalar *aa = NULL, *bb = NULL;
153 PetscInt nlocal;
154 PetscReal local_max = 0.0, *all_max = NULL;
155 PetscMPIInt size;
156 PetscFunctionBeginUser;
157 PetscCall(VecGetLocalSize(a, &nlocal));
158 PetscCall(VecGetArrayRead(a, &aa)); PetscCall(VecGetArrayRead(b, &bb));
159 for (PetscInt i = 0; i < nlocal; ++i) local_max = PetscMax(local_max, PetscAbsScalar(bb[i] - aa[i]));
160 PetscCall(VecRestoreArrayRead(b, &bb)); PetscCall(VecRestoreArrayRead(a, &aa));
161 PetscCallMPI(MPI_Comm_size(PETSC_COMM_WORLD, &size));
162 PetscCall(PetscMalloc1(size, &all_max));
163 PetscCallMPI(MPI_Allgather(&local_max, 1, MPIU_REAL, all_max, 1, MPIU_REAL, PETSC_COMM_WORLD));
164 *max_rank = 0;
165 for (PetscMPIInt r = 1; r < size; ++r) if (all_max[r] > all_max[*max_rank]) *max_rank = r;
166 PetscCall(PetscFree(all_max));
167 PetscFunctionReturn(PETSC_SUCCESS);
168}
169
170/* ======================================================================== */
171/* Deterministic Cartesian seed and an N-pass residual for compatibility. */
172/* ======================================================================== */
173
174/**
175 * @brief Reconstructs Ucat/lUcat deterministically from X, mirroring the seed
176 * now performed by the production callback.
177 *
178 * Used only by the N-pass compatibility residual (Experiment 3), which needs a
179 * boundary-pass count other than the production default of one call (three
180 * passes). For a single call it reproduces the production callback exactly.
181 */
182static PetscErrorCode SeedCartesianFromX(UserCtx *user, Vec X)
183{
184 const FieldId staggered[] = {FIELD_ID_UCONT};
185 const FieldId cell[] = {FIELD_ID_UCAT};
186 PetscFunctionBeginUser;
187 PetscCall(VecCopy(X, user->Ucont));
188 PetscCall(SynchronizePeriodicStaggeredFields(user, 1, staggered));
189 PetscCall(Contra2Cart(user));
190 PetscCall(SynchronizePeriodicCellFields(user, 1, cell));
191 PetscCall(UpdateLocalGhosts(user, FIELD_ID_UCAT));
192 PetscFunctionReturn(PETSC_SUCCESS);
193}
194
195/**
196 * @brief Deterministic residual at X using an explicit number of boundary-condition
197 * calls (each three internal passes), for the boundary-map compatibility test.
198 */
199static PetscErrorCode ResidualNCalls(MomentumNewtonKrylovContext *ctx, Vec X,
200 PetscInt boundary_calls, Vec F)
201{
202 UserCtx *user = ctx->user;
203 PetscFunctionBeginUser;
204 PetscCall(SeedCartesianFromX(user, X));
205 for (PetscInt i = 0; i < boundary_calls; ++i) PetscCall(ApplyBoundaryConditions(user));
206 PetscCall(ComputeTotalResidual(user));
207 PetscCall(VecCopy(user->Rhs, F));
208 PetscCall(VecScale(F, -1.0));
209 PetscCall(MomentumNewtonKrylov_ApplyConstraints(ctx, X, F));
210 PetscFunctionReturn(PETSC_SUCCESS);
211}
212
213/* ======================================================================== */
214/* Newton solve configuration and monitor. */
215/* ======================================================================== */
216
217/** @brief Installs the production Newton, line-search, and GMRES options. */
218static PetscErrorCode ConfigureNewtonOptions(void)
219{
220 PetscFunctionBeginUser;
221 PetscCall(PetscOptionsSetValue(NULL, "-mom_nk_snes_type", "newtonls"));
222 PetscCall(PetscOptionsSetValue(NULL, "-mom_nk_snes_atol", "1e-10"));
223 PetscCall(PetscOptionsSetValue(NULL, "-mom_nk_snes_rtol", "1e-8"));
224 PetscCall(PetscOptionsSetValue(NULL, "-mom_nk_snes_stol", "1e-12"));
225 PetscCall(PetscOptionsSetValue(NULL, "-mom_nk_snes_max_it", "25"));
226 PetscCall(PetscOptionsSetValue(NULL, "-mom_nk_snes_linesearch_type", "bt"));
227 PetscCall(PetscOptionsSetValue(NULL, "-mom_nk_ksp_type", "gmres"));
228 PetscCall(PetscOptionsSetValue(NULL, "-mom_nk_ksp_atol", "1e-10"));
229 PetscCall(PetscOptionsSetValue(NULL, "-mom_nk_ksp_rtol", "1e-6"));
230 PetscCall(PetscOptionsSetValue(NULL, "-mom_nk_ksp_max_it", "400"));
231 PetscCall(PetscOptionsSetValue(NULL, "-mom_nk_ksp_gmres_restart", "80"));
232 PetscCall(PetscOptionsSetValue(NULL, "-mom_nk_pc_type", "none"));
233 PetscFunctionReturn(PETSC_SUCCESS);
234}
235
236typedef struct { const char *label; PetscReal *initial_norm; } SolveMonitorCtx;
237
238/** @brief Records per-Newton nonlinear norm, KSP iterations/reason, and accepted lambda. */
239static PetscErrorCode SolveMonitor(SNES snes, PetscInt it, PetscReal norm, void *vctx)
240{
241 SolveMonitorCtx *m = (SolveMonitorCtx *)vctx;
242 SNESLineSearch ls = NULL;
243 KSP ksp = NULL;
244 KSPConvergedReason kr = KSP_CONVERGED_ITERATING;
245 PetscReal lambda = -1.0;
246 PetscInt cum_ksp = 0, step_ksp = 0;
247 PetscFunctionBeginUser;
248 if (it == 0 && m->initial_norm) *m->initial_norm = norm;
249 PetscCall(SNESGetLinearSolveIterations(snes, &cum_ksp));
250 PetscCall(SNESGetKSP(snes, &ksp));
251 PetscCall(KSPGetConvergedReason(ksp, &kr));
252 PetscCall(KSPGetIterationNumber(ksp, &step_ksp));
253 PetscCall(SNESGetLineSearch(snes, &ls));
254 if (it > 0) PetscCall(SNESLineSearchGetLambda(ls, &lambda));
255 PetscCall(PetscPrintf(PETSC_COMM_WORLD,
256 "FULLSOLVE %s newton=%d nonlinear_norm=% .16e last_ksp_its=%d cumulative_ksp_its=%d "
257 "last_ksp_reason=%d accepted_lambda=% .6e\n",
258 m->label, (int)it, (double)norm, (int)step_ksp, (int)cum_ksp, (int)kr, (double)lambda));
259 PetscFunctionReturn(PETSC_SUCCESS);
260}
261
262typedef struct {
263 SNESConvergedReason reason;
264 PetscInt its, fevals, ksp_total;
265 PetscReal initial_norm, final_norm;
266 PetscBool converged;
269
270/**
271 * @brief Creates a test-owned matrix-free SNES driven by the *production* residual callback.
272 * @param[in] user Test context supplying the velocity DMDA.
273 * @param[in] pctx Production-compatible residual context borrowed by the SNES.
274 * @param[in] use_mgs When false (production default), leaves GMRES orthogonalization at
275 * PETSc's default classical Gram--Schmidt -- the path the production solver uses.
276 * @param[out] snes Created nonlinear solver.
277 * @param[out] J Created matrix-free Jacobian operator.
278 * @param[out] ksp Borrowed linear solver configured by the created SNES.
279 * @return PetscErrorCode 0 on success.
280 */
282 PetscBool use_mgs, SNES *snes, Mat *J, KSP *ksp)
283{
284 PC pc = NULL;
285 PetscFunctionBeginUser;
286 PetscCall(SNESCreate(PETSC_COMM_WORLD, snes));
287 PetscCall(SNESSetOptionsPrefix(*snes, "mom_nk_"));
288 PetscCall(SNESSetType(*snes, SNESNEWTONLS));
289 PetscCall(SNESSetDM(*snes, user->fda));
290 PetscCall(SNESSetFunction(*snes, NULL, MomentumNewtonKrylov_FormResidual, pctx));
291 PetscCall(MatCreateSNESMF(*snes, J));
292 PetscCall(SNESSetJacobian(*snes, *J, *J, MatMFFDComputeJacobian, NULL));
293 PetscCall(SNESGetKSP(*snes, ksp));
294 PetscCall(KSPSetType(*ksp, KSPGMRES));
295 if (use_mgs) PetscCall(KSPGMRESSetOrthogonalization(*ksp, KSPGMRESModifiedGramSchmidtOrthogonalization));
296 PetscCall(KSPGMRESSetRestart(*ksp, 80));
297 PetscCall(KSPGetPC(*ksp, &pc));
298 PetscCall(PCSetType(pc, PCNONE));
299 PetscCall(SNESSetFromOptions(*snes));
300 PetscFunctionReturn(PETSC_SUCCESS);
301}
302
303/** @brief Runs one complete production-callback step-2 solve from the restored entry state. */
304static PetscErrorCode RunProductionFullSolve(UserCtx *user, const FpSnapshot *entry, Vec X0,
305 PetscBool use_mgs, const char *label, SolveResult *res)
306{
307 MomentumNewtonKrylovContext pctx = {.user = user}; /* Every other member starts zeroed */
308 SNES snes = NULL; Mat J = NULL; KSP ksp = NULL; Vec solution = NULL;
310 PetscFunctionBeginUser;
311 memset(res, 0, sizeof(*res));
312 res->initial_norm = -1.0;
313 PetscCall(FpRestore(user, entry));
314 PetscCall(VecDuplicate(X0, &solution)); PetscCall(VecCopy(X0, solution));
315 PetscCall(CreateProductionSNES(user, &pctx, use_mgs, &snes, &J, &ksp));
316 m.label = label; m.initial_norm = &res->initial_norm;
317 PetscCall(SNESMonitorSet(snes, SolveMonitor, &m, NULL));
318 PetscCall(SNESSolve(snes, NULL, solution));
319 PetscCall(SNESGetConvergedReason(snes, &res->reason));
320 PetscCall(SNESGetIterationNumber(snes, &res->its));
321 PetscCall(SNESGetNumberFunctionEvals(snes, &res->fevals));
322 PetscCall(SNESGetLinearSolveIterations(snes, &res->ksp_total));
323 PetscCall(SNESGetFunctionNorm(snes, &res->final_norm));
324 res->converged = (PetscBool)(res->reason > 0);
325 PetscCall(VecDuplicate(solution, &res->Xfinal)); PetscCall(VecCopy(solution, res->Xfinal));
326 PetscCall(PetscPrintf(PETSC_COMM_WORLD,
327 "FULLSOLVE_SUMMARY %s reason=%s (%d) newton=%d fevals=%d ksp_total=%d orthogonalization=%s "
328 "initial_norm=% .16e final_norm=% .16e -> %s\n",
329 label, SNESConvergedReasons[res->reason], (int)res->reason, (int)res->its, (int)res->fevals,
330 (int)res->ksp_total, use_mgs ? "modified-GS" : "classical-GS(default)",
331 (double)res->initial_norm, (double)res->final_norm, res->converged ? "CONVERGED" : "FAILED"));
332 PetscCall(VecDestroy(&solution)); PetscCall(MatDestroy(&J)); PetscCall(SNESDestroy(&snes));
333 PetscFunctionReturn(PETSC_SUCCESS);
334}
335
336/** @brief Stops SNES immediately after its first accepted Newton correction. */
337static PetscErrorCode StopAfterOne(SNES snes, PetscInt it, PetscReal xnorm, PetscReal gnorm,
338 PetscReal fnorm, SNESConvergedReason *reason, void *vctx)
339{
340 PetscReal *norms = (PetscReal *)vctx;
341 PetscFunctionBeginUser;
342 (void)snes; (void)xnorm; (void)gnorm;
343 if (it == 0) norms[0] = fnorm;
344 if (it == 1) norms[1] = fnorm;
345 *reason = it >= 1 ? SNES_CONVERGED_ITS : SNES_CONVERGED_ITERATING;
346 PetscFunctionReturn(PETSC_SUCCESS);
347}
348
349/* ======================================================================== */
350/* The regression itself. */
351/* ======================================================================== */
352
353/**
354 * @brief Builds the production-sized duct, advances the true physical step 1, and
355 * exercises purity, full-solve convergence, boundary-map compatibility, and
356 * projection using the production Newton--Krylov callback and solver.
357 */
358static PetscErrorCode TestNewtonKrylovProductionRegression(void)
359{
360 SimCtx *simCtx = NULL;
361 UserCtx *user = NULL;
362 char tmpdir[PETSC_MAX_PATH_LEN] = "";
363 FpSnapshot entry = {0};
365 Vec X0 = NULL, X1 = NULL, Xfinal = NULL;
366 Vec F0 = NULL, F1 = NULL, Fafter = NULL, v = NULL, jv = NULL;
367 Vec F3 = NULL, F24 = NULL;
368 SolveResult res_cgs = {0};
369 PetscReal norms[2] = {0.0, 0.0};
370 PetscReal imm_inf = 0.0, imm_2 = 0.0, mffd_inf = 0.0, mffd_2 = 0.0;
371 PetscReal f3_2 = 0.0, f24_2 = 0.0, f24_inf = 0.0, f24m3_inf = 0.0, f24m3_2 = 0.0;
372 PetscReal max_div = -1.0;
373 const FieldId fields[] = {FIELD_ID_UCONT};
374 const FieldId stag[] = {FIELD_ID_UCONT}; const FieldId cell[] = {FIELD_ID_UCAT};
375 const PetscReal purity_inf_tol = 1e-13, purity_2_tol = 1e-12;
376 const PetscReal compat_tol = 1e-8, div_tol = 1e-6;
377 PetscMPIInt world, mffd_rank = 0;
378 PetscErrorCode prod_ierr;
379
380 PetscFunctionBeginUser;
381 PetscCallMPI(MPI_Comm_size(PETSC_COMM_WORLD, &world));
382 PetscCall(PetscPrintf(PETSC_COMM_WORLD,
383 "\n########## NEWTON-KRYLOV PRODUCTION REGRESSION (ranks=%d) ##########\n", (int)world));
384 PetscCall(PicurvBuildMomentumPurityRuntimeContext(NULL, &simCtx, &user, tmpdir, sizeof(tmpdir)));
385 PetscCall(InitializeEulerianState(simCtx));
386 PetscCall(ConfigureNewtonOptions());
387
388 /* Complete physical step 1 (momentum + Poisson + projection + finalization)
389 * through the real run path, advance histories, then enter step 2. */
390 simCtx->step = 1; simCtx->ti = simCtx->dt;
391 PetscCall(FlowSolver(simCtx));
392 PetscCall(UpdateSolverHistoryVectors(user, PETSC_FALSE));
393 simCtx->step = 2; simCtx->ti = 2.0 * simCtx->dt;
394
395 PetscCall(VecDuplicate(user->Ucont, &user->Rhs));
396 pctx.user = user; pctx.history_file = NULL; pctx.have_initial_norm = PETSC_FALSE; pctx.initial_norm = 0.0;
397
398 /* Canonicalize the entry exactly as production MomentumSolver_NewtonKrylov does. */
399 PetscCall(SynchronizePeriodicStaggeredFields(user, 1, fields));
400 PetscCall(ApplyBoundaryConditions(user));
401 PetscCall(FpCapture(user, &entry));
402 PetscCall(VecDuplicate(user->Ucont, &X0)); PetscCall(VecCopy(user->Ucont, X0));
403
404 /* -------- 4.1 residual purity at the step-2 / Newton-1 state -------- */
405 PetscCall(PetscPrintf(PETSC_COMM_WORLD, "\n===== 4.1 production-callback residual purity =====\n"));
406 { /* Reach the accepted Newton-1 state X1 with the production callback + default CGS. */
407 SNES snes = NULL; Mat J = NULL; KSP ksp = NULL;
408 PetscCall(VecDuplicate(X0, &X1)); PetscCall(VecCopy(X0, X1));
409 PetscCall(CreateProductionSNES(user, &pctx, PETSC_FALSE, &snes, &J, &ksp));
410 PetscCall(SNESSetConvergenceTest(snes, StopAfterOne, norms, NULL));
411 PetscCall(SNESSolve(snes, NULL, X1));
412 PetscCall(MatDestroy(&J)); PetscCall(SNESDestroy(&snes));
413 }
414 PetscCall(VecDuplicate(X1, &F0)); PetscCall(VecDuplicate(X1, &F1));
415 PetscCall(VecDuplicate(X1, &Fafter)); PetscCall(VecDuplicate(X1, &v)); PetscCall(VecDuplicate(X1, &jv));
416
417 /* Immediate repeatability with hidden state poisoned between the two calls. */
418 PetscCall(MomentumNewtonKrylov_FormResidual(NULL, X1, F0, &pctx));
419 simCtx->FluxInSum = 1234.0; simCtx->FluxOutSum = -4321.0;
420 simCtx->FarFluxInSum = 77.0; simCtx->FarFluxOutSum = -88.0;
421 PetscCall(VecSet(user->Ucat, 7.0)); PetscCall(VecSet(user->lUcat, 7.0));
422 PetscCall(MomentumNewtonKrylov_FormResidual(NULL, X1, F1, &pctx));
423 PetscCall(CollectiveDifference(F0, F1, &imm_inf, &imm_2));
424 PetscCall(PetscPrintf(PETSC_COMM_WORLD,
425 "PURITY immediate inf=% .3e l2=% .3e (tol inf=%.0e l2=%.0e)\n",
426 (double)imm_inf, (double)imm_2, (double)purity_inf_tol, (double)purity_2_tol));
427
428 /* Post-MFFD repeatability: real PETSc MFFD products, then reevaluate. */
429 {
430 SNES snes = NULL; Mat J = NULL; KSP ksp = NULL;
431 PetscInt lo, hi; PetscScalar *a = NULL; PetscReal vn;
432 PetscCall(VecGetOwnershipRange(v, &lo, &hi));
433 PetscCall(VecGetArray(v, &a));
434 for (PetscInt i = lo; i < hi; ++i) a[i - lo] = PetscSinReal(0.17 * (PetscReal)(i + 1));
435 PetscCall(VecRestoreArray(v, &a));
436 PetscCall(VecNorm(v, NORM_2, &vn)); PetscCall(VecScale(v, 1.0 / vn));
437 PetscCall(CreateProductionSNES(user, &pctx, PETSC_FALSE, &snes, &J, &ksp));
438 PetscCall(MatMFFDSetBase(J, X1, F0));
439 for (PetscInt i = 0; i < 40; ++i) PetscCall(MatMult(J, v, jv));
440 PetscCall(MomentumNewtonKrylov_FormResidual(NULL, X1, Fafter, &pctx));
441 PetscCall(CollectiveDifference(F0, Fafter, &mffd_inf, &mffd_2));
442 PetscCall(DifferenceMaxRank(F0, Fafter, &mffd_rank));
443 PetscCall(MatDestroy(&J)); PetscCall(SNESDestroy(&snes));
444 }
445 PetscCall(PetscPrintf(PETSC_COMM_WORLD,
446 "PURITY post_mffd inf=% .3e l2=% .3e max_rank=%d\n",
447 (double)mffd_inf, (double)mffd_2, (int)mffd_rank));
448
449 /* -------- 4.2 full step-2 solve with default classical Gram-Schmidt -------- */
450 PetscCall(PetscPrintf(PETSC_COMM_WORLD, "\n===== 4.2 full production step-2 solve (default classical GS) =====\n"));
451 PetscCall(RunProductionFullSolve(user, &entry, X0, PETSC_FALSE, "CGS-default", &res_cgs));
452
453 /* Also drive the ACTUAL production solver wrapper (default GS) and take X_final
454 * from it. The wrapper allocates user->Rhs when it is unallocated and keeps it on a
455 * committed step; a failed step releases it. */
456 PetscCall(FpRestore(user, &entry));
457 PetscCall(VecDestroy(&user->Rhs));
458 prod_ierr = MomentumSolver_NewtonKrylov_BoundaryFixedpointPrivateCopy(user, NULL, NULL);
459 if (!user->Rhs) PetscCall(VecDuplicate(user->Ucont, &user->Rhs));
460 PetscCall(VecDuplicate(user->Ucont, &Xfinal)); PetscCall(VecCopy(user->Ucont, Xfinal));
461 PetscCall(PetscPrintf(PETSC_COMM_WORLD,
462 "PROD_SOLVER ierr=%d mom_last_converged=%d\n",
463 (int)prod_ierr, (int)simCtx->mom_last_converged));
464 {
465 PetscReal dinf, d2; PetscMPIInt r;
466 PetscCall(CollectiveDifference(res_cgs.Xfinal, Xfinal, &dinf, &d2));
467 PetscCall(DifferenceMaxRank(res_cgs.Xfinal, Xfinal, &r));
468 PetscCall(PetscPrintf(PETSC_COMM_WORLD,
469 "PROD_SOLVER test_snes_vs_wrapper inf=% .3e l2=% .3e max_rank=%d\n",
470 (double)dinf, (double)d2, (int)r));
471 }
472
473 /* -------- 4.3 boundary-map compatibility at the converged solution -------- */
474 PetscCall(PetscPrintf(PETSC_COMM_WORLD, "\n===== 4.3 boundary-map compatibility (3 vs 24 passes) =====\n"));
475 PetscCall(VecDuplicate(Xfinal, &F3)); PetscCall(VecDuplicate(Xfinal, &F24));
476 PetscCall(FpRestore(user, &entry));
477 PetscCall(ResidualNCalls(&pctx, Xfinal, 1, F3)); /* 3 passes == production callback */
478 PetscCall(VecNorm(F3, NORM_2, &f3_2));
479 PetscCall(FpRestore(user, &entry));
480 PetscCall(ResidualNCalls(&pctx, Xfinal, 8, F24)); /* 24 passes */
481 PetscCall(VecNorm(F24, NORM_2, &f24_2));
482 PetscCall(VecNorm(F24, NORM_INFINITY, &f24_inf));
483 PetscCall(CollectiveDifference(F3, F24, &f24m3_inf, &f24m3_2));
484 PetscCall(PetscPrintf(PETSC_COMM_WORLD,
485 "COMPAT F3_l2=% .6e F24_l2=% .6e F24_inf=% .6e F24_minus_F3_l2=% .6e (tol %.0e)\n",
486 (double)f3_2, (double)f24_2, (double)f24_inf, (double)f24m3_2, (double)compat_tol));
487
488 /* -------- 4.4 projection compatibility -------- */
489 PetscCall(PetscPrintf(PETSC_COMM_WORLD, "\n===== 4.4 projection compatibility =====\n"));
490 PetscCall(FpRestore(user, &entry));
491 PetscCall(VecCopy(Xfinal, user->Ucont));
492 PetscCall(SynchronizePeriodicStaggeredFields(user, 1, stag));
493 PetscCall(Contra2Cart(user));
494 PetscCall(SynchronizePeriodicCellFields(user, 1, cell));
495 PetscCall(UpdateLocalGhosts(user, FIELD_ID_UCAT));
496 PetscCall(ApplyBoundaryConditions(user));
497 PetscCall(PoissonSolver_Multigrid(&simCtx->usermg));
498 PetscCall(UpdatePressure(user));
499 PetscCall(ProjectVelocity(user));
500 PetscCall(UpdateLocalGhosts(user, FIELD_ID_P));
501 PetscCall(ComputeDivergence(user));
502 max_div = simCtx->MaxDiv;
503 PetscCall(PetscPrintf(PETSC_COMM_WORLD,
504 "PROJECTION max_divergence=% .6e net_divergence_sum=% .6e (tol %.0e)\n",
505 (double)max_div, (double)simCtx->poissonSourceImbalance, (double)div_tol));
506
507 /* -------- consolidated verdicts (printed before assertions) -------- */
508 PetscCall(PetscPrintf(PETSC_COMM_WORLD, "\nREGRESSION_VERDICTS (ranks=%d)\n", (int)world));
509 PetscCall(PetscPrintf(PETSC_COMM_WORLD, " PRODUCTION_PURITY: %s\n",
510 (imm_inf <= purity_inf_tol && imm_2 <= purity_2_tol &&
511 mffd_inf <= purity_inf_tol && mffd_2 <= purity_2_tol) ? "PASS" : "FAIL"));
512 PetscCall(PetscPrintf(PETSC_COMM_WORLD, " FULL_STEP2_DEFAULT_GS: %s\n",
513 res_cgs.converged ? "PASS" : "FAIL"));
514 PetscCall(PetscPrintf(PETSC_COMM_WORLD, " PRODUCTION_SOLVER_WRAPPER: %s\n",
515 (prod_ierr == 0 && simCtx->mom_last_converged) ? "PASS" : "FAIL"));
516 PetscCall(PetscPrintf(PETSC_COMM_WORLD, " THREE_PASS_24_PASS_COMPATIBLE: %s\n",
517 (f24_2 <= compat_tol) ? "PASS" : "FAIL"));
518 PetscCall(PetscPrintf(PETSC_COMM_WORLD, " PROJECTION_DIVERGENCE_FREE: %s\n",
519 (max_div <= div_tol) ? "PASS" : "FAIL"));
520
521 /* -------- assertions -------- */
522 PetscCheck(imm_inf <= purity_inf_tol && imm_2 <= purity_2_tol, PETSC_COMM_WORLD, PETSC_ERR_PLIB,
523 "production residual not immediately repeatable (inf=%g l2=%g)", (double)imm_inf, (double)imm_2);
524 PetscCheck(mffd_inf <= purity_inf_tol && mffd_2 <= purity_2_tol, PETSC_COMM_WORLD, PETSC_ERR_PLIB,
525 "production residual changed after MFFD products (inf=%g l2=%g)", (double)mffd_inf, (double)mffd_2);
526 PetscCheck(res_cgs.converged, PETSC_COMM_WORLD, PETSC_ERR_PLIB,
527 "full step-2 solve (default GS) did not converge (reason=%d)", (int)res_cgs.reason);
528 PetscCheck(res_cgs.reason != SNES_DIVERGED_LINE_SEARCH && res_cgs.reason != SNES_DIVERGED_LINEAR_SOLVE,
529 PETSC_COMM_WORLD, PETSC_ERR_PLIB, "full step-2 solve diverged via line search or linear solve (reason=%d)",
530 (int)res_cgs.reason);
531 PetscCheck(prod_ierr == 0 && simCtx->mom_last_converged, PETSC_COMM_WORLD, PETSC_ERR_PLIB,
532 "production Newton-Krylov solver wrapper did not converge (ierr=%d)", (int)prod_ierr);
533 PetscCheck(f24_2 <= compat_tol, PETSC_COMM_WORLD, PETSC_ERR_PLIB,
534 "converged three-pass solution does not satisfy the 24-pass residual (||F24||2=%g)", (double)f24_2);
535 PetscCheck(max_div <= div_tol, PETSC_COMM_WORLD, PETSC_ERR_PLIB,
536 "projection of the converged momentum state is not divergence free (max_div=%g)", (double)max_div);
537
538 PetscCall(VecDestroy(&F24)); PetscCall(VecDestroy(&F3));
539 PetscCall(VecDestroy(&Xfinal)); PetscCall(VecDestroy(&res_cgs.Xfinal));
540 PetscCall(VecDestroy(&jv)); PetscCall(VecDestroy(&v));
541 PetscCall(VecDestroy(&Fafter)); PetscCall(VecDestroy(&F1)); PetscCall(VecDestroy(&F0));
542 PetscCall(VecDestroy(&X1)); PetscCall(VecDestroy(&X0));
543 PetscCall(FpDestroy(&entry));
544 PetscCall(VecDestroy(&user->Rhs));
545 PetscCall(PicurvDestroyRuntimeContext(&simCtx));
546 PetscCall(PicurvRemoveTempDir(tmpdir));
547 PetscFunctionReturn(PETSC_SUCCESS);
548}
549
550/** @brief Runs the opt-in Newton--Krylov production regression executable. */
551int main(int argc, char **argv)
552{
553 PetscErrorCode ierr;
554 const PicurvTestCase cases[] = {
555 {"newton-krylov-production-regression", TestNewtonKrylovProductionRegression}
556 };
557
558 ierr = PetscInitialize(&argc, &argv, NULL, "PICurv Newton-Krylov production regression");
559 if (ierr) return (int)ierr;
560 ierr = PicurvRunTests("unit-momentum-newton-boundary-fixedpoint", cases, 1);
561 if (PetscFinalize()) return 1;
562 return (int)ierr;
563}
PetscErrorCode SynchronizePeriodicStaggeredFields(UserCtx *user, PetscInt num_fields, const FieldId field_ids[])
Synchronizes persistent component-staggered vector fields.
PetscErrorCode ApplyBoundaryConditions(UserCtx *user)
Main boundary-condition orchestrator executed during solver timestepping.
PetscErrorCode SynchronizePeriodicCellFields(UserCtx *user, PetscInt num_fields, const FieldId field_ids[])
Synchronizes periodic endpoint cells for a list of cell-centered fields.
FieldId
Compile-time identity for a catalogued Eulerian field.
@ FIELD_ID_UCAT
@ FIELD_ID_UCONT
@ FIELD_ID_P
PetscErrorCode InitializeEulerianState(SimCtx *simCtx)
High-level orchestrator to set the complete initial state of the Eulerian solver.
static PetscErrorCode MomentumNewtonKrylov_ApplyConstraints(MomentumNewtonKrylovContext *ctx, Vec X, Vec F)
Replaces every non-independent residual row with an explicit equation.
static PetscErrorCode MomentumNewtonKrylov_FormResidual(SNES snes, Vec X, Vec F, void *ctx)
Adapts a PETSc trial vector to the existing momentum residual path.
PetscErrorCode ComputeTotalResidual(UserCtx *user)
Computes the shared spatial-plus-BDF momentum residual in user->Rhs.
PetscErrorCode UpdatePressure(UserCtx *user)
Adds the pressure correction to the pressure, P += Phi, and refreshes both fields' periodic images an...
Definition poisson.c:405
PetscErrorCode ProjectVelocity(UserCtx *user)
Corrects the contravariant flux with the gradient of Phi.
Definition poisson.c:425
PetscErrorCode PoissonSolver_Multigrid(UserMG *usermg)
Solves the pressure-correction equation for every block with geometric multigrid.
Definition poisson.c:922
PetscErrorCode UpdateSolverHistoryVectors(UserCtx *user, PetscBool preserve_previous_state)
Copies the current time step's solution fields into history vectors (e.g., U(t_n) -> U_o,...
Definition runloop.c:376
PetscErrorCode Contra2Cart(UserCtx *user)
Reconstructs Cartesian velocity (Ucat) at cell centers from contravariant velocity (Ucont) defined on...
Definition setup.c:3313
PetscErrorCode ComputeDivergence(UserCtx *user)
Computes the discrete divergence of the contravariant velocity field.
Definition setup.c:3599
PetscErrorCode UpdateLocalGhosts(UserCtx *user, FieldId field_id)
Updates the local vector (including ghost points) from its corresponding global vector.
Definition setup.c:2593
PetscErrorCode FlowSolver(SimCtx *simCtx)
Orchestrates a single time step of the Eulerian fluid solver.
Definition solvers.c:9
static PetscErrorCode StopAfterOne(SNES snes, PetscInt it, PetscReal xnorm, PetscReal gnorm, PetscReal fnorm, SNESConvergedReason *reason, void *vctx)
Stops SNES immediately after its first accepted Newton correction.
static PetscErrorCode FpDestroy(FpSnapshot *snap)
Releases all vectors owned by one persistent-state snapshot.
static PetscErrorCode FpCapture(UserCtx *user, FpSnapshot *snap)
Deep-copies the audited persistent state into a test-owned snapshot.
int main(int argc, char **argv)
Runs the opt-in Newton–Krylov production regression executable.
static void FpGetScalars(UserCtx *user, PetscReal scalar[9])
Collects the persistent scalar diagnostics maintained by boundary processing.
static void FpGetVectors(UserCtx *user, Vec field[16])
Collects the persistent vectors observed by the residual/boundary path.
static PetscErrorCode CollectiveDifference(Vec a, Vec b, PetscReal *norm_inf, PetscReal *norm_2)
Computes collective global difference norms for global or rank-local vectors.
static PetscErrorCode ConfigureNewtonOptions(void)
Installs the production Newton, line-search, and GMRES options.
static PetscErrorCode TestNewtonKrylovProductionRegression(void)
Builds the production-sized duct, advances the true physical step 1, and exercises purity,...
static PetscErrorCode CreateProductionSNES(UserCtx *user, MomentumNewtonKrylovContext *pctx, PetscBool use_mgs, SNES *snes, Mat *J, KSP *ksp)
Creates a test-owned matrix-free SNES driven by the production residual callback.
static PetscErrorCode SolveMonitor(SNES snes, PetscInt it, PetscReal norm, void *vctx)
Records per-Newton nonlinear norm, KSP iterations/reason, and accepted lambda.
static PetscErrorCode FpRestore(UserCtx *user, const FpSnapshot *snap)
Restores a previously captured persistent-state snapshot.
static PetscErrorCode SeedCartesianFromX(UserCtx *user, Vec X)
Reconstructs Ucat/lUcat deterministically from X, mirroring the seed now performed by the production ...
static PetscErrorCode DifferenceMaxRank(Vec a, Vec b, PetscMPIInt *max_rank)
Finds the MPI rank containing the largest local entry difference.
static PetscErrorCode RunProductionFullSolve(UserCtx *user, const FpSnapshot *entry, Vec X0, PetscBool use_mgs, const char *label, SolveResult *res)
Runs one complete production-callback step-2 solve from the restored entry state.
static PetscErrorCode ResidualNCalls(MomentumNewtonKrylovContext *ctx, Vec X, PetscInt boundary_calls, Vec F)
Deterministic residual at X using an explicit number of boundary-condition calls (each three internal...
PetscErrorCode PicurvBuildMomentumPurityRuntimeContext(const char *bcs_contents, SimCtx **simCtx_out, UserCtx **user_out, char *tmpdir, size_t tmpdir_len)
Builds the production-sized straight-duct fixture used only by the opt-in Newton residual-purity diag...
PetscErrorCode PicurvDestroyRuntimeContext(SimCtx **simCtx_ptr)
Finalizes and frees a runtime context built by PicurvBuildTinyRuntimeContext.
PetscErrorCode PicurvRunTests(const char *suite_name, const PicurvTestCase *cases, size_t case_count)
Runs a named C test suite and prints pass/fail progress markers.
PetscErrorCode PicurvRemoveTempDir(const char *path)
Recursively removes a temporary directory created by PicurvMakeTempDir.
Shared declarations for the PICurv C test fixture and assertion layer.
Named test case descriptor consumed by PicurvRunTests.
PetscReal FarFluxInSum
Definition variables.h:1016
PetscReal FarFluxOutSum
Definition variables.h:1016
SimCtx * simCtx
Back-pointer to the master simulation context.
Definition variables.h:1160
PetscReal FluxOutSum
Definition variables.h:1016
PetscReal boundaryVelocityCorrection
Definition variables.h:1031
UserMG usermg
Definition variables.h:1082
PetscBool mom_last_converged
Definition variables.h:971
Vec lUcont_rm1
Definition variables.h:1207
PetscReal poissonSourceImbalance
Definition variables.h:1095
PetscReal dt
Definition variables.h:933
PetscReal bulkVelocityCorrection
Definition variables.h:1030
Vec Ucont
Definition variables.h:1197
Vec Ubcs
Physical Cartesian velocity at boundary faces. Full 3D array but only boundary-face entries are meani...
Definition variables.h:172
PetscReal MaxDiv
Definition variables.h:1096
Vec lUcont_o
Definition variables.h:1204
Vec CellVectorAtCorner
Definition variables.h:1213
Vec Ucat_o
Definition variables.h:1204
PetscReal FluxInSum
Definition variables.h:1016
Vec Ucont_o
Definition variables.h:1204
PetscReal Fluxsum
Definition variables.h:1016
Vec Ucont_rm1
Definition variables.h:1207
Vec lUcont
Definition variables.h:1197
PetscInt step
Definition variables.h:924
PetscReal AreaOutSum
Definition variables.h:1036
Vec lUcat
Definition variables.h:1197
PetscReal ti
Definition variables.h:925
PetscReal AreaInSum
Definition variables.h:1036
Vec Uch
Characteristic velocity for boundary conditions.
Definition variables.h:173
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