PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
test_solver_kernels.c
Go to the documentation of this file.
1/**
2 * @file test_solver_kernels.c
3 * @brief C unit tests for solver-side analytical and LES helper kernels.
4 */
5
6#include "test_support.h"
8
10#include "BodyForces.h"
11#include "Filter.h"
12#include "les.h"
13#include "solvers.h"
14#include "momentumsolvers.h"
15/**
16 * @brief Tests LES test-filter helper paths for representative cases.
17 */
18
19static PetscErrorCode TestLESTestFilterPaths(void)
20{
21 double values[3][3][3];
22 double weights[3][3][3];
23
24 PetscFunctionBeginUser;
25 for (PetscInt k = 0; k < 3; ++k) {
26 for (PetscInt j = 0; j < 3; ++j) {
27 for (PetscInt i = 0; i < 3; ++i) {
28 values[k][j][i] = 2.0;
29 weights[k][j][i] = 1.0;
30 }
31 }
32 }
33
34 PetscCall(PicurvAssertRealNear(2.0, ApplyLESTestFilter(LES_TEST_FILTER_SIMPSON_IK, values, weights), 1.0e-12,
35 "Simpson-rule filter should preserve a constant field"));
36
37 PetscCall(PicurvAssertRealNear(2.0, ApplyLESTestFilter(LES_TEST_FILTER_VOLUME_WEIGHTED_BOX, values, weights), 1.0e-12,
38 "box filter should preserve a constant field"));
39
40 for (PetscInt k = 0; k < 3; ++k) {
41 for (PetscInt j = 0; j < 3; ++j) {
42 for (PetscInt i = 0; i < 3; ++i) {
43 weights[k][j][i] = 0.0;
44 }
45 }
46 }
47 PetscCall(PicurvAssertRealNear(0.0, ApplyLESTestFilter(LES_TEST_FILTER_VOLUME_WEIGHTED_BOX, values, weights), 1.0e-12,
48 "box filter should return zero when all weights are zero"));
49 PetscFunctionReturn(0);
50}
51/**
52 * @brief Tests analytical scalar verification helper routines.
53 */
54
55static PetscErrorCode TestAnalyticalScalarVerificationHelpers(void)
56{
57 Cmpnts point;
58 SimCtx *simCtx = NULL;
59 UserCtx *user = NULL;
60 Vec target = NULL;
61 PetscReal value = 0.0;
62 PetscReal ***target_arr = NULL;
63 PetscReal *positions = NULL;
64 PetscReal *psi = NULL;
65
66 PetscFunctionBeginUser;
67 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
68 PetscCall(PicurvCreateSwarmPair(user, 2, "ske"));
69
70 PetscCall(VerificationFieldCompile("2.5", &simCtx->verificationScalar));
71 point.x = 0.2; point.y = 0.3; point.z = 0.4;
72 PetscCall(VerificationFieldEvaluate(simCtx, &simCtx->verificationScalar, point, 0.0, &value));
73 PetscCall(PicurvAssertRealNear(2.5, value, 1.0e-12,
74 "constant scalar profile should evaluate to the configured value"));
75
76 PetscCall(DMSwarmGetField(user->swarm, "position", NULL, NULL, (void **)&positions));
77 positions[0] = 0.1; positions[1] = 0.2; positions[2] = 0.3;
78 positions[3] = 0.8; positions[4] = 0.6; positions[5] = 0.4;
79 PetscCall(DMSwarmRestoreField(user->swarm, "position", NULL, NULL, (void **)&positions));
80
82 PetscCall(DMSwarmGetField(user->swarm, "Psi", NULL, NULL, (void **)&psi));
83 PetscCall(PicurvAssertRealNear(2.5, psi[0], 1.0e-12,
84 "SetVerificationScalarOnParticles should overwrite the first particle scalar"));
85 PetscCall(PicurvAssertRealNear(2.5, psi[1], 1.0e-12,
86 "SetVerificationScalarOnParticles should overwrite the second particle scalar"));
87 PetscCall(DMSwarmRestoreField(user->swarm, "Psi", NULL, NULL, (void **)&psi));
88
89 PetscCall(VerificationFieldCompile("1.0 + 2.0*x", &simCtx->verificationScalar));
90 point.x = 0.25; point.y = 0.0; point.z = 0.0;
91 PetscCall(VerificationFieldEvaluate(simCtx, &simCtx->verificationScalar, point, 0.0, &value));
92 PetscCall(PicurvAssertRealNear(1.5, value, 1.0e-12,
93 "linear-x scalar profile should evaluate phi0 + slope_x * x"));
94
95 PetscCall(VecDuplicate(user->Psi, &target));
96 PetscCall(SetVerificationScalarAtCellCenters(user, target));
97 PetscCall(DMDAVecGetArrayRead(user->da, target, &target_arr));
98 PetscCall(PicurvAssertRealNear(1.25, target_arr[1][1][1], 1.0e-12,
99 "cell-center scalar fill should use the physical x center coordinate"));
100 PetscCall(DMDAVecRestoreArrayRead(user->da, target, &target_arr));
101 PetscCall(VecDestroy(&target));
102
103 PetscCall(VerificationFieldCompile("3.0*sin(pi*x)*sin(pi*y)*sin(pi*z)", &simCtx->verificationScalar));
104 point.x = 0.5; point.y = 0.5; point.z = 0.5;
105 PetscCall(VerificationFieldEvaluate(simCtx, &simCtx->verificationScalar, point, 0.0, &value));
106 PetscCall(PicurvAssertRealNear(3.0, value, 1.0e-12,
107 "sin-product scalar profile should peak at pi/2 in each coordinate"));
108
109 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
110 PetscFunctionReturn(0);
111}
112/**
113 * @brief Selects an analytical field: the options a case's source becomes.
114 */
115static PetscErrorCode UseAnalyticalSource(SimCtx *simCtx, const char *u, const char *v, const char *w, const char *pressure)
116{
117 PetscFunctionBeginUser;
118 PetscCall(AnalyticalFieldDestroy(simCtx));
119 PetscCall(PetscOptionsSetValue(NULL, "-ic_source_frame", "cartesian"));
120 PetscCall(PetscOptionsSetValue(NULL, "-ic_source_expr_0", u));
121 PetscCall(PetscOptionsSetValue(NULL, "-ic_source_expr_1", v));
122 PetscCall(PetscOptionsSetValue(NULL, "-ic_source_expr_2", w));
123 PetscCall(PetscOptionsClearValue(NULL, "-ic_source_pressure"));
124 if (pressure) PetscCall(PetscOptionsSetValue(NULL, "-ic_source_pressure", pressure));
125 PetscFunctionReturn(0);
126}
127
128/**
129 * @brief Tests that the field is the source: zero, then uniform with its face fluxes and boundary
130 * values, and that a source without `t` is evaluated once.
131 */
133{
134 SimCtx *simCtx = NULL;
135 UserCtx *user = NULL;
136 Cmpnts ***ucat = NULL, ***ucont = NULL, ***ubcs = NULL;
137
138 PetscFunctionBeginUser;
139 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
140 PetscCall(PicurvPopulateIdentityMetrics(user));
141 PetscCall(VecSet(user->Ucat, 3.0));
142 PetscCall(VecSet(user->P, 5.0));
143 PetscCall(VecSet(user->Bcs.Ubcs, 7.0));
144
145 PetscCall(UseAnalyticalSource(simCtx, "0", "0", "0", NULL));
146 PetscCall(AnalyticalSolutionEngine(simCtx));
147 PetscCall(PicurvAssertVecConstant(user->Ucat, 0.0, 1.0e-12, "a zero source should zero the velocity"));
148 PetscCall(PicurvAssertVecConstant(user->P, 0.0, 1.0e-12, "a source without pressure should zero the pressure"));
149 PetscCall(DMDAVecGetArrayRead(user->fda, user->Bcs.Ubcs, &ubcs));
150 PetscCall(PicurvAssertRealNear(0.0, ubcs[0][1][1].z, 1.0e-12, "a zero source should zero the boundary values"));
151 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->Bcs.Ubcs, &ubcs));
153 "a uniform field has no interpolation error to measure"));
154
155 PetscCall(UseAnalyticalSource(simCtx, "1.25", "-0.5", "0.75", NULL));
156 PetscCall(AnalyticalSolutionEngine(simCtx));
157 PetscCall(DMDAVecGetArrayRead(user->fda, user->Ucat, &ucat));
158 PetscCall(DMDAVecGetArrayRead(user->fda, user->Ucont, &ucont));
159 PetscCall(DMDAVecGetArrayRead(user->fda, user->Bcs.Ubcs, &ubcs));
160 PetscCall(PicurvAssertRealNear(1.25, ucat[1][1][1].x, 1.0e-12, "the source should set the interior x velocity"));
161 PetscCall(PicurvAssertRealNear(-0.5, ucat[1][1][1].y, 1.0e-12, "the source should set the interior y velocity"));
162 PetscCall(PicurvAssertRealNear(0.75, ucat[1][1][1].z, 1.0e-12, "the source should set the interior z velocity"));
163 PetscCall(PicurvAssertRealNear(1.25, ucont[1][1][1].x, 1.0e-12, "the source should set the xi flux"));
164 PetscCall(PicurvAssertRealNear(-0.5, ucont[1][1][1].y, 1.0e-12, "the source should set the eta flux"));
165 PetscCall(PicurvAssertRealNear(0.75, ucont[1][1][1].z, 1.0e-12, "the source should set the zeta flux"));
166 PetscCall(PicurvAssertRealNear(0.75, ucont[0][1][1].z, 1.0e-12, "the source should set the boundary face's flux"));
167 PetscCall(PicurvAssertRealNear(1.25, ubcs[0][1][1].x, 1.0e-12, "the source should set the boundary x velocity"));
168 PetscCall(PicurvAssertRealNear(0.75, ubcs[0][1][1].z, 1.0e-12, "the source should set the boundary z velocity"));
169 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->Bcs.Ubcs, &ubcs));
170 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->Ucont, &ucont));
171 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->Ucat, &ucat));
172
173 /* Nothing reads t, so a later step finds the fields as it left them. */
174 PetscCall(VecSet(user->P, 9.0));
175 PetscCall(AnalyticalSolutionEngine(simCtx));
176 PetscCall(PicurvAssertVecConstant(user->P, 9.0, 1.0e-12, "a source without t should be evaluated once"));
177
178 /* A bulk velocity scales the expressions on this target too. */
179 PetscCall(UseAnalyticalSource(simCtx, "0", "0", "3", NULL));
180 PetscCall(PetscOptionsSetValue(NULL, "-ic_source_bulk_velocity", "2"));
181 PetscCall(AnalyticalSolutionEngine(simCtx));
182 PetscCall(PetscOptionsClearValue(NULL, "-ic_source_bulk_velocity"));
183 PetscCall(DMDAVecGetArrayRead(user->fda, user->Ucat, &ucat));
184 PetscCall(PicurvAssertRealNear(2.0, ucat[1][1][1].z, 1.0e-12, "the source should reach its bulk velocity"));
185 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->Ucat, &ucat));
186
187 PetscCall(AnalyticalFieldDestroy(simCtx));
188 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
189 PetscFunctionReturn(0);
190}
191/**
192 * @brief Tests exact Taylor-Green samples on selected Eulerian interior and boundary points.
193 */
195{
196 SimCtx *simCtx = NULL;
197 UserCtx *user = NULL;
198 Cmpnts ***cent = NULL;
199 Cmpnts ***cent_x = NULL;
200 Cmpnts ***cent_y = NULL;
201 Cmpnts ***cent_z = NULL;
202 Cmpnts ***ucat = NULL;
203 Cmpnts ***ubcs = NULL;
204 PetscReal ***p = NULL;
205 const PetscReal vel_decay = PetscExpReal(-0.5);
206
207 PetscFunctionBeginUser;
208 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
209 PetscCall(PicurvPopulateIdentityMetrics(user));
210 simCtx->ti = 0.5;
211 PetscCall(UseAnalyticalSource(simCtx, "sin(x)*cos(y)*cos(z)*exp(-2*0.5*t)", "(-cos(x)*sin(y)*cos(z)*exp(-2*0.5*t))", "0",
212 "0.25*(cos(2*x) + cos(2*y))*exp(-4*0.5*t)"));
213
214 PetscCall(DMDAVecGetArray(user->fda, user->Cent, &cent));
215 PetscCall(DMDAVecGetArray(user->fda, user->lCentx, &cent_x));
216 PetscCall(DMDAVecGetArray(user->fda, user->lCenty, &cent_y));
217 PetscCall(DMDAVecGetArray(user->fda, user->lCentz, &cent_z));
218 for (PetscInt k = user->info.zs; k < user->info.zs + user->info.zm; ++k) {
219 for (PetscInt j = user->info.ys; j < user->info.ys + user->info.ym; ++j) {
220 for (PetscInt i = user->info.xs; i < user->info.xs + user->info.xm; ++i) {
221 cent[k][j][i].x = 0.0;
222 cent[k][j][i].y = 0.0;
223 cent[k][j][i].z = 0.0;
224 cent_x[k][j][i] = cent[k][j][i];
225 cent_y[k][j][i] = cent[k][j][i];
226 cent_z[k][j][i] = cent[k][j][i];
227 }
228 }
229 }
230 cent[1][1][1].x = 0.5 * PETSC_PI;
231 cent[1][1][1].y = 0.0;
232 cent[1][1][1].z = 0.0;
233 cent[1][2][1].x = 0.0;
234 cent[1][2][1].y = 0.5 * PETSC_PI;
235 cent[1][2][1].z = 0.0;
236 cent_z[0][1][1].x = 0.5 * PETSC_PI;
237 cent_z[0][1][1].y = 0.0;
238 cent_z[0][1][1].z = 0.0;
239 PetscCall(DMDAVecRestoreArray(user->fda, user->lCentz, &cent_z));
240 PetscCall(DMDAVecRestoreArray(user->fda, user->lCenty, &cent_y));
241 PetscCall(DMDAVecRestoreArray(user->fda, user->lCentx, &cent_x));
242 PetscCall(DMDAVecRestoreArray(user->fda, user->Cent, &cent));
243
244 PetscCall(AnalyticalSolutionEngine(simCtx));
245
246 PetscCall(DMDAVecGetArrayRead(user->fda, user->Ucat, &ucat));
247 PetscCall(DMDAVecGetArrayRead(user->fda, user->Bcs.Ubcs, &ubcs));
248 PetscCall(DMDAVecGetArrayRead(user->da, user->P, &p));
249 PetscCall(PicurvAssertRealNear(vel_decay, ucat[1][1][1].x, 1.0e-12, "TGV sample should set the expected interior x velocity"));
250 PetscCall(PicurvAssertRealNear(0.0, ucat[1][1][1].y, 1.0e-12, "TGV sample should keep the paired interior y velocity at zero"));
251 PetscCall(PicurvAssertRealNear(-vel_decay, ucat[1][2][1].y, 1.0e-12, "TGV sample should set the expected interior y velocity"));
252 PetscCall(PicurvAssertRealNear(0.0, p[1][1][1], 1.0e-12, "Chosen TGV sample should produce zero pressure"));
253 PetscCall(PicurvAssertRealNear(vel_decay, ubcs[0][1][1].x, 1.0e-12, "TGV sample should set the expected boundary x velocity"));
254 PetscCall(PicurvAssertRealNear(0.0, ubcs[0][1][1].y, 1.0e-12, "TGV boundary sample should keep the paired y velocity at zero"));
255 PetscCall(DMDAVecRestoreArrayRead(user->da, user->P, &p));
256 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->Bcs.Ubcs, &ubcs));
257 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->Ucat, &ucat));
258
259 PetscCall(AnalyticalFieldDestroy(simCtx));
260 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
261 PetscFunctionReturn(0);
262}
263/**
264 * @brief Tests that a boundary value is the source at its own face's centre on both sides: a + face's
265 * value lives in the dummy layer, one past the layer of its flux and centre.
266 */
268{
269 SimCtx *simCtx = NULL;
270 UserCtx *user = NULL;
271 Cmpnts ***cent_x = NULL, ***ubcs = NULL, ***ucat = NULL;
272
273 PetscFunctionBeginUser;
274 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
275 PetscCall(PicurvPopulateIdentityMetrics(user));
276 const PetscInt mx = user->info.mx;
277 PetscCall(UseAnalyticalSource(simCtx, "x", "0", "0", NULL));
278 PetscCall(DMDAVecGetArray(user->fda, user->lCentx, &cent_x));
279 cent_x[1][1][0].x = 0.25;
280 cent_x[1][1][mx - 2].x = 2.0;
281 cent_x[1][1][mx - 1].x = -7.0; /* The dummy layer has no face centre. */
282 PetscCall(DMDAVecRestoreArray(user->fda, user->lCentx, &cent_x));
283
284 PetscCall(AnalyticalSolutionEngine(simCtx));
285
286 PetscCall(DMDAVecGetArrayRead(user->fda, user->Bcs.Ubcs, &ubcs));
287 PetscCall(DMDAVecGetArrayRead(user->fda, user->Ucat, &ucat));
288 PetscCall(PicurvAssertRealNear(0.25, ubcs[1][1][0].x, 1.0e-12, "the - face's value should be the source at its centre"));
289 PetscCall(PicurvAssertRealNear(2.0, ubcs[1][1][mx - 1].x, 1.0e-12, "the + face's value should be the source at its centre"));
290 PetscCall(PicurvAssertRealNear(2.0, 0.5 * (ucat[1][1][mx - 1].x + ucat[1][1][mx - 2].x), 1.0e-12,
291 "the dummy and last cell should average to the + face's value"));
292 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->Ucat, &ucat));
293 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->Bcs.Ubcs, &ubcs));
294 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
295 PetscFunctionReturn(0);
296}
297
298/**
299 * @brief Tests the source evaluated at particle positions, and the fields it cannot be evaluated for.
300 */
302{
303 SimCtx *simCtx = NULL;
304 UserCtx *user = NULL;
305 Vec tempVec = NULL;
306 PetscReal *data = NULL;
307 PetscErrorCode ierr_uniform;
308 const PetscReal vel_decay = PetscExpReal(-0.5);
309
310 PetscFunctionBeginUser;
311 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
312 PetscCall(PicurvPopulateIdentityMetrics(user));
313 simCtx->ti = 0.5;
314 PetscCall(UseAnalyticalSource(simCtx, "sin(x)*cos(y)*cos(z)*exp(-2*0.5*t)", "(-cos(x)*sin(y)*cos(z)*exp(-2*0.5*t))", "0", NULL));
315 PetscCall(AnalyticalSolutionEngine(simCtx));
317 "a source in x, y, z and t can be compared at particles"));
318
319 PetscCall(VecCreateSeq(PETSC_COMM_SELF, 6, &tempVec));
320 PetscCall(VecGetArray(tempVec, &data));
321 data[0] = 0.5 * PETSC_PI; data[1] = 0.0; data[2] = 0.0;
322 data[3] = 0.0; data[4] = 0.5 * PETSC_PI; data[5] = 0.0;
323 PetscCall(VecRestoreArray(tempVec, &data));
324 PetscCall(SetAnalyticalSolutionForParticles(tempVec, simCtx));
325 PetscCall(VecGetArray(tempVec, &data));
326 PetscCall(PicurvAssertRealNear(vel_decay, data[0], 1.0e-12, "the x velocity at x=pi/2"));
327 PetscCall(PicurvAssertRealNear(0.0, data[1], 1.0e-12, "the y velocity at x=pi/2"));
328 PetscCall(PicurvAssertRealNear(0.0, data[3], 1.0e-12, "the x velocity at y=pi/2"));
329 PetscCall(PicurvAssertRealNear(-vel_decay, data[4], 1.0e-12, "the y velocity at y=pi/2"));
330 PetscCall(VecRestoreArray(tempVec, &data));
331
332 PetscCall(UseAnalyticalSource(simCtx, "1", "0", "4*eta*(1-eta)", NULL));
333 PetscCall(AnalyticalSolutionEngine(simCtx));
335 "a source in grid-line fractions cannot be evaluated at a point"));
336 PetscCall(PetscPushErrorHandler(PetscIgnoreErrorHandler, NULL));
337 ierr_uniform = SetAnalyticalSolutionForParticles(tempVec, simCtx);
338 PetscCall(PetscPopErrorHandler());
339 PetscCall(PicurvAssertBool((PetscBool)(ierr_uniform != 0), "evaluating such a source at particles should fail"));
340
341 PetscCall(VecDestroy(&tempVec));
342 PetscCall(AnalyticalFieldDestroy(simCtx));
343 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
344 PetscFunctionReturn(0);
345}
346/**
347 * @brief Tests deterministic LES eddy-viscosity computation on a linear velocity field.
348 */
349
351{
352 SimCtx *simCtx = NULL;
353 UserCtx *user = NULL;
354 Cmpnts ***ucat = NULL;
355 PetscReal ***nu_t = NULL;
356 /* CS stores the coefficient C that multiplies Delta^2 |S|, so C = 0.25 is the
357 Cs = 0.5 of the classical form. With Aj = 1 the filter width is 1, and the
358 linear field below gives |S| = sqrt(2). */
359 const PetscReal coefficient = 0.25;
360 const PetscReal expected_nu_t = 0.25 * PetscSqrtReal(2.0);
361
362 PetscFunctionBeginUser;
363 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 5, 5, 5));
364 simCtx->les = DYNAMIC_SMAGORINSKY;
365 PetscCall(DMCreateGlobalVector(user->da, &user->Nu_t));
366 PetscCall(DMCreateLocalVector(user->da, &user->lNu_t));
367 PetscCall(DMCreateGlobalVector(user->da, &user->CS));
368 PetscCall(DMCreateLocalVector(user->da, &user->lCs));
369
370 PetscCall(VecSet(user->Aj, 1.0));
371 PetscCall(VecSet(user->Nu_t, 0.0));
372 PetscCall(VecSet(user->CS, coefficient));
373 PetscCall(DMDAVecGetArray(user->fda, user->Ucat, &ucat));
374 for (PetscInt k = user->info.zs; k < user->info.zs + user->info.zm; ++k) {
375 for (PetscInt j = user->info.ys; j < user->info.ys + user->info.ym; ++j) {
376 for (PetscInt i = user->info.xs; i < user->info.xs + user->info.xm; ++i) {
377 ucat[k][j][i].x = (PetscReal)i;
378 ucat[k][j][i].y = 0.0;
379 ucat[k][j][i].z = 0.0;
380 }
381 }
382 }
383 PetscCall(DMDAVecRestoreArray(user->fda, user->Ucat, &ucat));
384 PetscCall(DMGlobalToLocalBegin(user->fda, user->Ucat, INSERT_VALUES, user->lUcat));
385 PetscCall(DMGlobalToLocalEnd(user->fda, user->Ucat, INSERT_VALUES, user->lUcat));
386 PetscCall(DMGlobalToLocalBegin(user->da, user->Aj, INSERT_VALUES, user->lAj));
387 PetscCall(DMGlobalToLocalEnd(user->da, user->Aj, INSERT_VALUES, user->lAj));
388 PetscCall(DMGlobalToLocalBegin(user->da, user->CS, INSERT_VALUES, user->lCs));
389 PetscCall(DMGlobalToLocalEnd(user->da, user->CS, INSERT_VALUES, user->lCs));
390
391 PetscCall(ComputeEddyViscosityLES(user));
392 PetscCall(DMDAVecGetArrayRead(user->da, user->Nu_t, &nu_t));
393 PetscCall(PicurvAssertRealNear(expected_nu_t, nu_t[2][2][2], 1.0e-6,
394 "linear velocity field should yield deterministic LES eddy viscosity"));
395 PetscCall(PicurvAssertRealNear(0.0, nu_t[0][2][2], 1.0e-12,
396 "boundary cells should remain untouched by the interior LES loop"));
397 PetscCall(DMDAVecRestoreArrayRead(user->da, user->Nu_t, &nu_t));
398
399 PetscCall(VecDestroy(&user->CS));
400 PetscCall(VecDestroy(&user->lCs));
401 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
402 PetscFunctionReturn(0);
403}
404/**
405 * @brief Tests FlowSolver guardrails for unsupported momentum solver selections.
406 */
407
409{
410 SimCtx *simCtx = NULL;
411 UserCtx *user = NULL;
412 PetscErrorCode ierr_flow = 0;
413
414 PetscFunctionBeginUser;
415 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
416 simCtx->mom_solver_type = (MomentumSolverType)999;
417
418 PetscCall(PetscPushErrorHandler(PetscIgnoreErrorHandler, NULL));
419 ierr_flow = FlowSolver(simCtx);
420 PetscCall(PetscPopErrorHandler());
421 PetscCall(PicurvAssertBool((PetscBool)(ierr_flow != 0),
422 "FlowSolver should reject unsupported momentum solver selectors"));
423
424 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
425 PetscFunctionReturn(0);
426}
427/**
428 * @brief Tests driven-channel flow source-term evaluation.
429 */
430
431static PetscErrorCode TestDrivenChannelFlowSource(void)
432{
433 SimCtx *simCtx = NULL;
434 UserCtx *user = NULL;
435 Vec rct = NULL;
436 Cmpnts ***rct_arr = NULL;
437 Cmpnts ***l_csi = NULL;
438 Cmpnts ***l_eta = NULL;
439 Cmpnts ***l_zet = NULL;
440
441 PetscFunctionBeginUser;
442 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
443 PetscCall(VecDuplicate(user->Ucont, &rct));
444 PetscCall(VecZeroEntries(rct));
445
452 simCtx->bulkVelocityCorrection = 2.0;
453 simCtx->dt = 1.0;
454 simCtx->forceScalingFactor = 1.0;
455 simCtx->drivingForceMagnitude = 0.0;
456 PetscCall(VecSet(user->Nvert, 0.0));
457 PetscCall(DMGlobalToLocalBegin(user->da, user->Nvert, INSERT_VALUES, user->lNvert));
458 PetscCall(DMGlobalToLocalEnd(user->da, user->Nvert, INSERT_VALUES, user->lNvert));
459 PetscCall(DMDAVecGetArray(user->fda, user->lCsi, &l_csi));
460 PetscCall(DMDAVecGetArray(user->fda, user->lEta, &l_eta));
461 PetscCall(DMDAVecGetArray(user->fda, user->lZet, &l_zet));
462 l_csi[1][1][1].x = 1.0; l_csi[1][1][1].y = 0.0; l_csi[1][1][1].z = 0.0;
463 l_eta[1][1][1].x = 0.0; l_eta[1][1][1].y = 1.0; l_eta[1][1][1].z = 0.0;
464 l_zet[1][1][1].x = 0.0; l_zet[1][1][1].y = 0.0; l_zet[1][1][1].z = 1.0;
465 PetscCall(DMDAVecRestoreArray(user->fda, user->lZet, &l_zet));
466 PetscCall(DMDAVecRestoreArray(user->fda, user->lEta, &l_eta));
467 PetscCall(DMDAVecRestoreArray(user->fda, user->lCsi, &l_csi));
468
469 PetscCall(ComputeDrivenChannelFlowSource(user, rct));
470 PetscCall(DMDAVecGetArrayRead(user->fda, rct, &rct_arr));
471 PetscCall(PicurvAssertRealNear(1.5, simCtx->drivingForceMagnitude, 1.0e-12,
472 "driven flow source should update the controller magnitude"));
473 PetscCall(PicurvAssertRealNear(0.0, rct_arr[1][1][1].y, 1.0e-12,
474 "driven flow source should leave the y component unchanged"));
475 PetscCall(PicurvAssertRealNear(0.0, rct_arr[1][1][1].z, 1.0e-12,
476 "driven flow source should leave the z component unchanged"));
477 PetscCall(DMDAVecRestoreArrayRead(user->fda, rct, &rct_arr));
478
479 PetscCall(VecDestroy(&rct));
480 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
481 PetscFunctionReturn(0);
482}
483/* ===================================================================== *
484 * Stage A3: momentum pseudo-time stability estimate (shadow) tests *
485 * Unit Cartesian grid via identity metrics: Csi=(1,0,0), aj=1, so the *
486 * analytic targets are exact (lambda_t=a0/dt, viscous=4*6*nu=24nu, *
487 * centered conv reduces to sum|U_f|, QUICK interior=4/3, boundary=2.5).*
488 * ===================================================================== */
489
490/**
491 * @brief Fills a local Cmpnts vector (ghosts included) with a uniform vector value.
492 * @param fda Vector DM owning lvec.
493 * @param lvec Local Cmpnts vector to fill.
494 * @param x,y,z Uniform component values.
495 * @return PetscErrorCode 0 on success.
496 */
497static PetscErrorCode MomFillLocalCmpnts(DM fda, Vec lvec, PetscReal x, PetscReal y, PetscReal z)
498{
499 Cmpnts ***a;
500 PetscInt gxs, gys, gzs, gxm, gym, gzm;
501 PetscFunctionBeginUser;
502 PetscCall(DMDAGetGhostCorners(fda, &gxs, &gys, &gzs, &gxm, &gym, &gzm));
503 PetscCall(DMDAVecGetArray(fda, lvec, &a));
504 for (PetscInt k = gzs; k < gzs+gzm; ++k)
505 for (PetscInt j = gys; j < gys+gym; ++j)
506 for (PetscInt i = gxs; i < gxs+gxm; ++i) { a[k][j][i].x = x; a[k][j][i].y = y; a[k][j][i].z = z; }
507 PetscCall(DMDAVecRestoreArray(fda, lvec, &a));
508 PetscFunctionReturn(0);
509}
510
511/**
512 * @brief Fills a local scalar vector (ghosts included) with a uniform value.
513 * @param da Scalar DM owning lvec.
514 * @param lvec Local scalar vector to fill.
515 * @param v Uniform value.
516 * @return PetscErrorCode 0 on success.
517 */
518static PetscErrorCode MomFillLocalScalar(DM da, Vec lvec, PetscReal v)
519{
520 PetscReal ***a;
521 PetscInt gxs, gys, gzs, gxm, gym, gzm;
522 PetscFunctionBeginUser;
523 PetscCall(DMDAGetGhostCorners(da, &gxs, &gys, &gzs, &gxm, &gym, &gzm));
524 PetscCall(DMDAVecGetArray(da, lvec, &a));
525 for (PetscInt k = gzs; k < gzs+gzm; ++k)
526 for (PetscInt j = gys; j < gys+gym; ++j)
527 for (PetscInt i = gxs; i < gxs+gxm; ++i) a[k][j][i] = v;
528 PetscCall(DMDAVecRestoreArray(da, lvec, &a));
529 PetscFunctionReturn(0);
530}
531
532/**
533 * @brief Sets a single local-scalar cell value (e.g. to mark one nvert solid).
534 * @param da Scalar DM owning lvec.
535 * @param lvec Local scalar vector.
536 * @param ci,cj,ck Cell indices to set.
537 * @param v Value to assign.
538 * @return PetscErrorCode 0 on success.
539 */
540static PetscErrorCode MomSetLocalScalarCell(DM da, Vec lvec, PetscInt ci, PetscInt cj, PetscInt ck, PetscReal v)
541{
542 PetscReal ***a;
543 PetscInt gxs, gys, gzs, gxm, gym, gzm;
544 PetscFunctionBeginUser;
545 PetscCall(DMDAGetGhostCorners(da, &gxs, &gys, &gzs, &gxm, &gym, &gzm));
546 PetscCall(DMDAVecGetArray(da, lvec, &a));
547 /* MPI-safe: only write if (ci,cj,ck) is within this rank's ghost-inclusive range. */
548 if (ci >= gxs && ci < gxs+gxm && cj >= gys && cj < gys+gym && ck >= gzs && ck < gzs+gzm)
549 a[ck][cj][ci] = v;
550 PetscCall(DMDAVecRestoreArray(da, lvec, &a));
551 PetscFunctionReturn(0);
552}
553
554/* 1. Shared BDF coefficient: old/current-only state falls back to BDF1, while
555 * a committed checkpoint with restored Ucont_rm1 retains BDF2 immediately. */
556static PetscErrorCode TestMomentumBDFCoefficient(void)
557{
558 SimCtx *simCtx = NULL; UserCtx *user = NULL;
559 PetscFunctionBeginUser;
560 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 6, 6, 6));
561 simCtx->StartStep = 0; simCtx->step = 1;
562 PetscCall(PicurvAssertRealNear(1.0, MomentumBDFCoefficient(simCtx), 1e-12, "a0 BDF1 on cold-start step 1"));
563 PetscCall(PicurvAssertBool((PetscBool)(!MomentumUsesBDF2(simCtx)), "step 1 is BDF1"));
564 simCtx->step = 5;
565 PetscCall(PicurvAssertRealNear(1.5, MomentumBDFCoefficient(simCtx), 1e-12, "a0 BDF2 on interior step"));
566 PetscCall(PicurvAssertBool(MomentumUsesBDF2(simCtx), "step 5 (StartStep 0) is BDF2"));
567 simCtx->StartStep = 5; simCtx->step = 5;
568 PetscCall(PicurvAssertRealNear(1.0, MomentumBDFCoefficient(simCtx), 1e-12, "a0 BDF1 at restart setup step"));
569 simCtx->step = 6;
570 PetscCall(PicurvAssertRealNear(1.0, MomentumBDFCoefficient(simCtx), 1e-12, "a0 BDF1 on first restart solve (ti==StartStep+1)"));
571 simCtx->step = 7;
572 PetscCall(PicurvAssertRealNear(1.5, MomentumBDFCoefficient(simCtx), 1e-12, "a0 BDF2 after first restart solve"));
573 simCtx->restartHistoryAvailable = PETSC_TRUE;
574 simCtx->step = 5;
575 PetscCall(PicurvAssertRealNear(1.5, MomentumBDFCoefficient(simCtx), 1e-12,
576 "restored history enables BDF2 at restart setup"));
577 simCtx->step = 6;
578 PetscCall(PicurvAssertRealNear(1.5, MomentumBDFCoefficient(simCtx), 1e-12,
579 "restored history enables BDF2 on first restart solve"));
580 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
581 PetscFunctionReturn(0);
582}
583
584/* Common setup with explicit per-direction DMDA periodicity. Periodic directions get real
585 wrapped ghosts (so the conservative QUICK rule sees the full stencil) and PERIODIC BC;
586 non-periodic directions get `bc`. Identity metrics; caller tweaks flags/fields. */
587static PetscErrorCode MomMakeUnitGridP(SimCtx **simCtx, UserCtx **user, PetscInt n,
588 PetscBool px, PetscBool py, PetscBool pz, BCType bc)
589{
590 PetscFunctionBeginUser;
591 PetscCall(PicurvCreateMinimalContextsWithPeriodicity(simCtx, user, n, n, n, px, py, pz));
592 (*user)->boundary_faces[BC_FACE_NEG_X].mathematical_type = px ? PERIODIC : bc;
593 (*user)->boundary_faces[BC_FACE_POS_X].mathematical_type = px ? PERIODIC : bc;
594 (*user)->boundary_faces[BC_FACE_NEG_Y].mathematical_type = py ? PERIODIC : bc;
595 (*user)->boundary_faces[BC_FACE_POS_Y].mathematical_type = py ? PERIODIC : bc;
596 (*user)->boundary_faces[BC_FACE_NEG_Z].mathematical_type = pz ? PERIODIC : bc;
597 (*user)->boundary_faces[BC_FACE_POS_Z].mathematical_type = pz ? PERIODIC : bc;
598 (*simCtx)->dt = 0.1; (*simCtx)->step = 1; (*simCtx)->StartStep = 0; /* a0=1 -> lambda_t=10 */
599 (*simCtx)->ren = 1.0; (*simCtx)->les = 0;
600 (*simCtx)->central = 0; (*simCtx)->invicid = 0; (*simCtx)->block_number = 1;
601 (*simCtx)->TwoD = 0; (*simCtx)->les_gradient_model = 0;
602 /* The minimal fixture does not allocate lNu_t (LES off by default); create a
603 zeroed one so the estimator can read it when a test enables LES. */
604 if (!(*user)->lNu_t) PetscCall(DMCreateLocalVector((*user)->da, &(*user)->lNu_t));
605 PetscCall(MomFillLocalCmpnts((*user)->fda, (*user)->lUcont, 0.0, 0.0, 0.0));
606 PetscCall(MomFillLocalCmpnts((*user)->fda, (*user)->lUcat, 0.0, 0.0, 0.0));
607 PetscCall(MomFillLocalScalar((*user)->da, (*user)->lNvert, 0.0));
608 PetscCall(MomFillLocalScalar((*user)->da, (*user)->lNu_t, 0.0));
609 PetscFunctionReturn(0);
610}
611
612/* Convenience: all-periodic (bc==PERIODIC) or all-non-periodic with the given BC. */
613static PetscErrorCode MomMakeUnitGrid(SimCtx **simCtx, UserCtx **user, PetscInt n, BCType bc)
614{
615 const PetscBool p = (PetscBool)(bc == PERIODIC);
616 PetscFunctionBeginUser;
617 PetscCall(MomMakeUnitGridP(simCtx, user, n, p, p, p, bc));
618 PetscFunctionReturn(0);
619}
620
621/* 2. Centered convection: f_c=1, and Aj*U^xi = u/dx scaling (identity grid -> lambda_c = sum|u|). */
623{
624 SimCtx *simCtx = NULL; UserCtx *user = NULL; MomStabilityReport rep;
625 PetscFunctionBeginUser;
626 PetscCall(MomMakeUnitGrid(&simCtx, &user, 8, PERIODIC));
627 simCtx->central = 1; simCtx->invicid = 1;
628 PetscCall(MomFillLocalCmpnts(user->fda, user->lUcont, 2.0, 0.0, 0.0));
629 PetscCall(ComputeMomentumStabilityEstimate(user, 1, simCtx->dt, MOM_STAB_CAND_C, &rep));
630 PetscCall(PicurvAssertRealNear(10.0, rep.lambda_t, 1e-9, "lambda_t = a0/dt"));
631 PetscCall(PicurvAssertRealNear(2.0, rep.lambda_c, 1e-9, "centered conv f_c=1 (Aj*U^xi scaling)"));
632 PetscCall(PicurvAssertRealNear(0.0, rep.lambda_v, 1e-9, "inviscid: no viscous term"));
633 PetscCall(PicurvAssertRealNear(12.0, rep.lambda, 1e-9, "total lambda"));
634 PetscCall(PicurvAssertIntEqual(0, (PetscInt)rep.cclass, "interior cell class"));
635 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
636 PetscFunctionReturn(0);
637}
638
639/* 3. Interior QUICK convective factor = 4/3. */
640static PetscErrorCode TestMomentumStabilityQuickInterior(void)
641{
642 SimCtx *simCtx = NULL; UserCtx *user = NULL; MomStabilityReport rep;
643 PetscFunctionBeginUser;
644 PetscCall(MomMakeUnitGrid(&simCtx, &user, 8, PERIODIC));
645 simCtx->central = 0; simCtx->invicid = 1; /* QUICK branch */
646 PetscCall(MomFillLocalCmpnts(user->fda, user->lUcont, 3.0, 0.0, 0.0));
647 PetscCall(ComputeMomentumStabilityEstimate(user, 1, simCtx->dt, MOM_STAB_CAND_C, &rep));
648 PetscCall(PicurvAssertRealNear(4.0, rep.lambda_c, 1e-9, "QUICK interior f_c=4/3 (4/3*3=4)"));
649 PetscCall(PicurvAssertIntEqual(0, (PetscInt)rep.cclass, "interior cell class"));
650 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
651 PetscFunctionReturn(0);
652}
653
654/* 4. Boundary/IB-modified QUICK convective factor = 2.5 (conservative branch class). */
655static PetscErrorCode TestMomentumStabilityQuickBoundary(void)
656{
657 SimCtx *simCtx = NULL; UserCtx *user = NULL; MomStabilityReport rep;
658 PetscFunctionBeginUser;
659 PetscCall(MomMakeUnitGrid(&simCtx, &user, 8, INLET)); /* non-periodic -> boundary band active */
660 simCtx->central = 0; simCtx->invicid = 1;
661 PetscCall(MomFillLocalCmpnts(user->fda, user->lUcont, 8.0, 0.0, 0.0));
662 PetscCall(ComputeMomentumStabilityEstimate(user, 1, simCtx->dt, MOM_STAB_CAND_C, &rep));
663 PetscCall(PicurvAssertRealNear(20.0, rep.lambda_c, 1e-9, "boundary QUICK f_c=2.5 (2.5*8=20)"));
664 PetscCall(PicurvAssertIntEqual(1, (PetscInt)rep.cclass, "physical-boundary cell class"));
665 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
666 PetscFunctionReturn(0);
667}
668
669/* 5. Viscous longitudinal full-stress factor: 4*6*nu = 24nu (= 8nu*(1/dx^2+1/dy^2+1/dz^2)). */
671{
672 SimCtx *simCtx = NULL; UserCtx *user = NULL; MomStabilityReport rep;
673 PetscFunctionBeginUser;
674 PetscCall(MomMakeUnitGrid(&simCtx, &user, 8, PERIODIC));
675 simCtx->invicid = 0; simCtx->ren = 1.0; /* nu = 1, no convection */
676 PetscCall(ComputeMomentumStabilityEstimate(user, 1, simCtx->dt, MOM_STAB_CAND_C, &rep));
677 PetscCall(PicurvAssertRealNear(24.0, rep.lambda_v, 1e-9, "viscous = 4*6*nu = 24nu (factor-8 longitudinal)"));
678 PetscCall(PicurvAssertRealNear(34.0, rep.lambda, 1e-9, "total lambda_t+lambda_v"));
679 PetscCall(PicurvAssertIntEqual((PetscInt)MOM_STAB_LIMITER_VISCOSITY, (PetscInt)rep.limiter, "viscosity-limited"));
680 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
681 PetscFunctionReturn(0);
682}
683
684/* 6. Viscous estimate scales linearly with molecular viscosity (1/Re). */
686{
687 SimCtx *simCtx = NULL; UserCtx *user = NULL; MomStabilityReport rep;
688 PetscFunctionBeginUser;
689 PetscCall(MomMakeUnitGrid(&simCtx, &user, 8, PERIODIC));
690 simCtx->invicid = 0; simCtx->ren = 4.0; /* nu = 0.25 -> 24*0.25 = 6 */
691 PetscCall(ComputeMomentumStabilityEstimate(user, 1, simCtx->dt, MOM_STAB_CAND_C, &rep));
692 PetscCall(PicurvAssertRealNear(6.0, rep.lambda_v, 1e-9, "viscous scales with nu=1/Re"));
693 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
694 PetscFunctionReturn(0);
695}
696
697/* 7. LES eddy viscosity adds into nu_eff,f (face average): nu_eff = 1/Re + nu_t. */
698static PetscErrorCode TestMomentumStabilityLESEddyViscosity(void)
699{
700 SimCtx *simCtx = NULL; UserCtx *user = NULL; MomStabilityReport rep;
701 PetscFunctionBeginUser;
702 PetscCall(MomMakeUnitGrid(&simCtx, &user, 8, PERIODIC));
703 simCtx->invicid = 0; simCtx->ren = 1.0; simCtx->les = 1; /* nu_eff = 1 + nu_t */
704 PetscCall(MomFillLocalScalar(user->da, user->lNu_t, 1.0)); /* nu_t = 1 -> nu_eff = 2 -> 24*2 = 48 */
705 PetscCall(ComputeMomentumStabilityEstimate(user, 1, simCtx->dt, MOM_STAB_CAND_C, &rep));
706 PetscCall(PicurvAssertRealNear(48.0, rep.lambda_v, 1e-9, "LES nu_t adds: 4*6*(1+1) = 48"));
707 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
708 PetscFunctionReturn(0);
709}
710
711/* 8. One-sided viscous branch near a solid: conservative x2 applied once per cell. */
712static PetscErrorCode TestMomentumStabilityOneSidedViscous(void)
713{
714 SimCtx *simCtx = NULL; UserCtx *user = NULL; MomStabilityReport rep;
715 PetscFunctionBeginUser;
716 PetscCall(MomMakeUnitGrid(&simCtx, &user, 8, PERIODIC));
717 simCtx->invicid = 0; simCtx->ren = 1.0;
718 /* Mark one interior cell solid; its fluid cross-neighbours get the one-sided x2 (24 -> 48). */
719 PetscCall(MomSetLocalScalarCell(user->da, user->lNvert, 4, 5, 4, 1.0));
720 PetscCall(ComputeMomentumStabilityEstimate(user, 1, simCtx->dt, MOM_STAB_CAND_C, &rep));
721 PetscCall(PicurvAssertRealNear(48.0, rep.lambda_v, 1e-9, "one-sided viscous x2 (24 -> 48)"));
722 PetscCall(PicurvAssertIntEqual(1, (PetscInt)rep.one_sided, "one-sided multiplier flagged"));
723 PetscCall(PicurvAssertIntEqual(2, (PetscInt)rep.cclass, "IB-adjacent cell class"));
724 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
725 PetscFunctionReturn(0);
726}
727
728/* 9. Read-only: the estimator must not mutate any solver field. */
729static PetscErrorCode TestMomentumStabilityReadOnly(void)
730{
731 SimCtx *simCtx = NULL; UserCtx *user = NULL; MomStabilityReport rep;
732 PetscReal n_ucont_0, n_ucat_0, n_nvert_0, n_ucont_1, n_ucat_1, n_nvert_1;
733 PetscFunctionBeginUser;
734 PetscCall(MomMakeUnitGrid(&simCtx, &user, 8, PERIODIC));
735 simCtx->invicid = 0; simCtx->ren = 2.0;
736 PetscCall(MomFillLocalCmpnts(user->fda, user->lUcont, 1.5, -0.7, 0.3));
737 PetscCall(MomFillLocalCmpnts(user->fda, user->lUcat, 0.9, 0.4, -0.2));
738 PetscCall(VecNorm(user->lUcont, NORM_2, &n_ucont_0));
739 PetscCall(VecNorm(user->lUcat, NORM_2, &n_ucat_0));
740 PetscCall(VecNorm(user->lNvert, NORM_2, &n_nvert_0));
741 PetscCall(ComputeMomentumStabilityEstimate(user, 1, simCtx->dt, MOM_STAB_CAND_D, &rep));
742 PetscCall(VecNorm(user->lUcont, NORM_2, &n_ucont_1));
743 PetscCall(VecNorm(user->lUcat, NORM_2, &n_ucat_1));
744 PetscCall(VecNorm(user->lNvert, NORM_2, &n_nvert_1));
745 PetscCall(PicurvAssertRealNear(n_ucont_0, n_ucont_1, 1e-14, "lUcont unchanged by estimator"));
746 PetscCall(PicurvAssertRealNear(n_ucat_0, n_ucat_1, 1e-14, "lUcat unchanged by estimator"));
747 PetscCall(PicurvAssertRealNear(n_nvert_0, n_nvert_1, 1e-14, "lNvert unchanged by estimator"));
748 PetscCall(PicurvAssertBool((PetscBool)(rep.lambda > 0.0), "estimate finite and positive"));
749 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
750 PetscFunctionReturn(0);
751}
752
753/**
754 * @brief Sets uniform Cartesian metrics for spacing (dx,dy,dz) on all cell and face arrays.
755 * @param user Test user context.
756 * @param dx,dy,dz Cartesian cell spacings.
757 * @return PetscErrorCode 0 on success.
758 */
759static PetscErrorCode MomSetCartesianMetrics(UserCtx *user, PetscReal dx, PetscReal dy, PetscReal dz)
760{
761 const PetscReal sx = dy*dz, sy = dx*dz, sz = dx*dy, aj = 1.0/(dx*dy*dz);
762 Vec csiv[] = {user->lCsi, user->lICsi, user->lJCsi, user->lKCsi};
763 Vec etav[] = {user->lEta, user->lIEta, user->lJEta, user->lKEta};
764 Vec zetv[] = {user->lZet, user->lIZet, user->lJZet, user->lKZet};
765 Vec ajv[] = {user->lAj, user->lIAj, user->lJAj, user->lKAj};
766 PetscFunctionBeginUser;
767 for (int t = 0; t < 4; ++t) {
768 PetscCall(MomFillLocalCmpnts(user->fda, csiv[t], sx, 0, 0));
769 PetscCall(MomFillLocalCmpnts(user->fda, etav[t], 0, sy, 0));
770 PetscCall(MomFillLocalCmpnts(user->fda, zetv[t], 0, 0, sz));
771 PetscCall(MomFillLocalScalar(user->da, ajv[t], aj));
772 }
773 PetscFunctionReturn(0);
774}
775
776/**
777 * @brief Fills lUcont.x as a linear ramp slope*i (nonzero discrete contravariant divergence).
778 * @param fda Vector DM.
779 * @param lvec Local Cmpnts vector.
780 * @param slope Ramp slope.
781 * @return PetscErrorCode 0 on success.
782 */
783static PetscErrorCode MomFillUcontXRamp(DM fda, Vec lvec, PetscReal slope)
784{
785 Cmpnts ***a;
786 PetscInt gxs, gys, gzs, gxm, gym, gzm;
787 PetscFunctionBeginUser;
788 PetscCall(DMDAGetGhostCorners(fda, &gxs, &gys, &gzs, &gxm, &gym, &gzm));
789 PetscCall(DMDAVecGetArray(fda, lvec, &a));
790 for (PetscInt k = gzs; k < gzs+gzm; ++k)
791 for (PetscInt j = gys; j < gys+gym; ++j)
792 for (PetscInt i = gxs; i < gxs+gxm; ++i) { a[k][j][i].x = slope*i; a[k][j][i].y = 0; a[k][j][i].z = 0; }
793 PetscCall(DMDAVecRestoreArray(fda, lvec, &a));
794 PetscFunctionReturn(0);
795}
796
797/**
798 * @brief Fills lUcat as a linear shear u=(gamma*j,0,0) so |grad u|_inf = gamma.
799 * @param fda Vector DM.
800 * @param lvec Local Cmpnts vector.
801 * @param gamma Shear rate.
802 * @return PetscErrorCode 0 on success.
803 */
804static PetscErrorCode MomFillUcatShearY(DM fda, Vec lvec, PetscReal gamma)
805{
806 Cmpnts ***a;
807 PetscInt gxs, gys, gzs, gxm, gym, gzm;
808 PetscFunctionBeginUser;
809 PetscCall(DMDAGetGhostCorners(fda, &gxs, &gys, &gzs, &gxm, &gym, &gzm));
810 PetscCall(DMDAVecGetArray(fda, lvec, &a));
811 for (PetscInt k = gzs; k < gzs+gzm; ++k)
812 for (PetscInt j = gys; j < gys+gym; ++j)
813 for (PetscInt i = gxs; i < gxs+gxm; ++i) { a[k][j][i].x = gamma*j; a[k][j][i].y = 0; a[k][j][i].z = 0; }
814 PetscCall(DMDAVecRestoreArray(fda, lvec, &a));
815 PetscFunctionReturn(0);
816}
817
818/* A3.5-1. Anisotropic Cartesian viscous: detects metric-normal argument-order mistakes
819 * that the identity-metric test cannot. Target = 8nu*(1/dx^2+1/dy^2+1/dz^2). */
821{
822 SimCtx *simCtx = NULL; UserCtx *user = NULL; MomStabilityReport rep;
823 PetscFunctionBeginUser;
824 PetscCall(MomMakeUnitGrid(&simCtx, &user, 8, PERIODIC));
825 simCtx->invicid = 0; simCtx->ren = 1.0;
826 PetscCall(MomSetCartesianMetrics(user, 1.0, 2.0, 4.0)); /* 8*(1 + 1/4 + 1/16) = 10.5 */
827 PetscCall(ComputeMomentumStabilityEstimate(user, 1, simCtx->dt, MOM_STAB_CAND_C, &rep));
828 PetscCall(PicurvAssertRealNear(10.5, rep.lambda_v, 1e-9, "anisotropic viscous = 8nu*sum(1/d^2)"));
829 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
830 PetscFunctionReturn(0);
831}
832
833/* A3.5-2. Directional QUICK: only the boundary-modified direction gets 2.5; others stay 4/3. */
834static PetscErrorCode TestMomentumStabilityDirectionalQuick(void)
835{
836 SimCtx *simCtx = NULL; UserCtx *user = NULL; MomStabilityReport rep;
837 PetscFunctionBeginUser;
838 PetscCall(MomMakeUnitGridP(&simCtx, &user, 8, PETSC_FALSE, PETSC_TRUE, PETSC_TRUE, INLET)); /* x non-periodic */
839 simCtx->central = 0; simCtx->invicid = 1;
840 PetscCall(MomFillLocalCmpnts(user->fda, user->lUcont, 3.0, 3.0, 3.0));
841 PetscCall(ComputeMomentumStabilityEstimate(user, 1, simCtx->dt, MOM_STAB_CAND_C, &rep));
842 /* boundary cell: 0.5*(2.5*6 + (4/3)*6 + (4/3)*6) = 15.5 ; NOT 22.5 (all-2.5). */
843 PetscCall(PicurvAssertRealNear(15.5, rep.lambda_c, 1e-9, "only x-direction modified to 2.5"));
844 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
845 PetscFunctionReturn(0);
846}
847
848/* A3.5-3. One-sided viscous trigger by x-, y-, z-neighbor and applied only once for multiples. */
850{
851 SimCtx *simCtx = NULL; UserCtx *user = NULL; MomStabilityReport rep;
852 const PetscInt offs[3][3] = {{1,0,0},{0,1,0},{0,0,1}}; /* x,y,z neighbors of (4,4,4) */
853 PetscFunctionBeginUser;
854 for (int d = 0; d < 3; ++d) {
855 PetscCall(MomMakeUnitGrid(&simCtx, &user, 8, PERIODIC));
856 simCtx->invicid = 0; simCtx->ren = 1.0;
857 PetscCall(MomSetLocalScalarCell(user->da, user->lNvert,
858 4+offs[d][0], 4+offs[d][1], 4+offs[d][2], 1.0));
859 PetscCall(ComputeMomentumStabilityEstimate(user, 1, simCtx->dt, MOM_STAB_CAND_C, &rep));
860 PetscCall(PicurvAssertRealNear(48.0, rep.lambda_v, 1e-9, "single-direction one-sided x2"));
861 PetscCall(PicurvAssertIntEqual(1, (PetscInt)rep.one_sided, "one-sided flagged"));
862 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
863 }
864 /* multiple solid neighbors still apply x2 only once (48, not 96). */
865 PetscCall(MomMakeUnitGrid(&simCtx, &user, 8, PERIODIC));
866 simCtx->invicid = 0; simCtx->ren = 1.0;
867 PetscCall(MomSetLocalScalarCell(user->da, user->lNvert, 5, 4, 4, 1.0));
868 PetscCall(MomSetLocalScalarCell(user->da, user->lNvert, 4, 5, 4, 1.0));
869 PetscCall(ComputeMomentumStabilityEstimate(user, 1, simCtx->dt, MOM_STAB_CAND_C, &rep));
870 PetscCall(PicurvAssertRealNear(48.0, rep.lambda_v, 1e-9, "multiple triggers -> x2 once (not 96)"));
871 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
872 PetscFunctionReturn(0);
873}
874
875/* A3.5-4. Active-row mask: a cell with an inactive normal row but active tangential rows is
876 * retained with the full estimate; a fully-inactive location is excluded. */
877static PetscErrorCode TestMomentumStabilityActiveRowMask(void)
878{
879 SimCtx *simCtx = NULL; UserCtx *user = NULL; MomStabilityReport rep;
880 PetscFunctionBeginUser;
881 /* Positive non-periodic x face (i=mx-2) disables the xi row only; cell stays active. */
882 PetscCall(MomMakeUnitGrid(&simCtx, &user, 8, INLET));
883 simCtx->central = 1; simCtx->invicid = 1;
884 PetscCall(MomFillLocalCmpnts(user->fda, user->lUcont, 2.0, 2.0, 2.0));
885 PetscCall(ComputeMomentumStabilityEstimate(user, 1, simCtx->dt, MOM_STAB_CAND_C, &rep));
886 PetscCall(PicurvAssertBool((PetscBool)(rep.active_cells > 0), "boundary cells remain active"));
887 PetscCall(PicurvAssertBool((PetscBool)(rep.lambda > rep.lambda_t), "tangential rows retained"));
888 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
889 /* All cells solid -> zero active -> estimate falls back to lambda_t only. */
890 PetscCall(MomMakeUnitGrid(&simCtx, &user, 8, PERIODIC));
891 simCtx->invicid = 1;
892 PetscCall(MomFillLocalScalar(user->da, user->lNvert, 1.0)); /* every cell solid */
893 PetscCall(ComputeMomentumStabilityEstimate(user, 1, simCtx->dt, MOM_STAB_CAND_C, &rep));
894 PetscCall(PicurvAssertIntEqual(0, rep.active_cells, "all solid -> zero active cells"));
895 PetscCall(PicurvAssertRealNear(rep.lambda_t, rep.lambda, 1e-12, "empty active set -> lambda_t only"));
896 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
897 PetscFunctionReturn(0);
898}
899
900/* A3.5-5. Explicit input validation: invalid block_number and a non-finite metric both error. */
901static PetscErrorCode TestMomentumStabilityValidation(void)
902{
903 SimCtx *simCtx = NULL; UserCtx *user = NULL; MomStabilityReport rep;
904 PetscErrorCode e1 = 0, e2 = 0;
905 PetscFunctionBeginUser;
906 PetscCall(MomMakeUnitGrid(&simCtx, &user, 8, PERIODIC));
907 simCtx->invicid = 0; simCtx->ren = 1.0;
908
909 PetscCall(PetscPushErrorHandler(PetscIgnoreErrorHandler, NULL));
910 e1 = ComputeMomentumStabilityEstimate(user, 0, simCtx->dt, MOM_STAB_CAND_C, &rep); /* block_number=0 */
911 PetscCall(PetscPopErrorHandler());
912 PetscCall(PicurvAssertBool((PetscBool)(e1 != 0), "block_number<=0 rejected"));
913
914 PetscCall(MomSetLocalScalarCell(user->da, user->lAj, 4, 4, 4, PETSC_INFINITY)); /* bad metric */
915 PetscCall(PetscPushErrorHandler(PetscIgnoreErrorHandler, NULL));
916 e2 = ComputeMomentumStabilityEstimate(user, 1, simCtx->dt, MOM_STAB_CAND_C, &rep);
917 PetscCall(PetscPopErrorHandler());
918 PetscCall(PicurvAssertBool((PetscBool)(e2 != 0), "non-finite inverse-Jacobian rejected"));
919
920 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
921 PetscFunctionReturn(0);
922}
923
924/* A3.5-6a. Candidate C exceeds B by the discrete-divergence term when div(Ucont) != 0. */
926{
927 SimCtx *simCtx = NULL; UserCtx *user = NULL; MomStabilityReport rep;
928 PetscFunctionBeginUser;
929 PetscCall(MomMakeUnitGrid(&simCtx, &user, 8, PERIODIC));
930 simCtx->central = 1; simCtx->invicid = 1; /* f_c=1 isolates the div term */
931 PetscCall(MomFillUcontXRamp(user->fda, user->lUcont, 2.0)); /* div = slope = 2 */
932 PetscCall(ComputeMomentumStabilityEstimate(user, 1, simCtx->dt, MOM_STAB_CAND_C, &rep));
933 /* C - B = 0.5*Aj*|div| = 0.5*2 = 1.0 at the (shared) controlling cell. */
934 PetscCall(PicurvAssertRealNear(1.0, rep.lambda_C - rep.lambda_B, 1e-9, "C-B = divergence term"));
935 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
936 PetscFunctionReturn(0);
937}
938
939/* A3.5-6b. Candidate D adds |grad u|_inf on a linear shear, and equals C for uniform velocity. */
940static PetscErrorCode TestMomentumStabilityCandidateDShear(void)
941{
942 SimCtx *simCtx = NULL; UserCtx *user = NULL; MomStabilityReport rep;
943 PetscFunctionBeginUser;
944 PetscCall(MomMakeUnitGrid(&simCtx, &user, 8, PERIODIC));
945 simCtx->central = 1; simCtx->invicid = 1;
946 PetscCall(MomFillUcatShearY(user->fda, user->lUcat, 2.0)); /* |grad u|_inf = gamma = 2 */
947 PetscCall(ComputeMomentumStabilityEstimate(user, 1, simCtx->dt, MOM_STAB_CAND_D, &rep));
948 PetscCall(PicurvAssertRealNear(2.0, rep.lambda_D - rep.lambda_C, 1e-9, "D-C = |grad u| on shear"));
949 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
950
951 PetscCall(MomMakeUnitGrid(&simCtx, &user, 8, PERIODIC));
952 simCtx->central = 1; simCtx->invicid = 1;
953 PetscCall(MomFillLocalCmpnts(user->fda, user->lUcat, 0.7, -0.3, 0.5)); /* uniform velocity */
954 PetscCall(ComputeMomentumStabilityEstimate(user, 1, simCtx->dt, MOM_STAB_CAND_D, &rep));
955 PetscCall(PicurvAssertRealNear(rep.lambda_C, rep.lambda_D, 1e-12, "D == C for uniform velocity"));
956 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
957 PetscFunctionReturn(0);
958}
959
960/* A3.5-6c. Wall faces suppress eddy viscosity exactly as in ComputeViscous(). */
961static PetscErrorCode TestMomentumStabilityWallSuppression(void)
962{
963 SimCtx *simCtx = NULL; UserCtx *user = NULL; MomStabilityReport rep;
964 PetscFunctionBeginUser;
965 /* n=3 -> DMDA mx=4 -> interior cells {1,2}; every interior cell touches 3 wall faces
966 (no wall-free interior cell exists, so the global max reflects suppression). */
967 PetscCall(MomMakeUnitGrid(&simCtx, &user, 3, WALL));
968 simCtx->invicid = 0; simCtx->ren = 1.0; simCtx->les = 1;
969 PetscCall(MomFillLocalScalar(user->da, user->lNu_t, 1.0));
970 PetscCall(ComputeMomentumStabilityEstimate(user, 1, simCtx->dt, MOM_STAB_CAND_C, &rep));
971 /* 3 wall faces (nu_t suppressed, nu_eff=1) + 3 interior faces (nu_eff=2): 4*(3*1+3*2)=36. */
972 PetscCall(PicurvAssertRealNear(36.0, rep.lambda_v, 1e-9, "wall-face eddy viscosity suppressed"));
973 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
974 PetscFunctionReturn(0);
975}
976
977/* A3.5-7. Strengthened read-only: exact per-vector equality (not just norms). */
978static PetscErrorCode TestMomentumStabilityReadOnlyExact(void)
979{
980 SimCtx *simCtx = NULL; UserCtx *user = NULL; MomStabilityReport rep;
981 Vec ucont0, ucat0, nvert0, nut0, aj0;
982 PetscBool eq;
983 PetscFunctionBeginUser;
984 PetscCall(MomMakeUnitGrid(&simCtx, &user, 8, PERIODIC));
985 simCtx->invicid = 0; simCtx->ren = 2.0; simCtx->les = 1;
986 PetscCall(MomFillLocalCmpnts(user->fda, user->lUcont, 1.5, -0.7, 0.3));
987 PetscCall(MomFillUcatShearY(user->fda, user->lUcat, 1.1));
988 PetscCall(MomFillLocalScalar(user->da, user->lNu_t, 0.4));
989 PetscCall(VecDuplicate(user->lUcont, &ucont0)); PetscCall(VecCopy(user->lUcont, ucont0));
990 PetscCall(VecDuplicate(user->lUcat, &ucat0)); PetscCall(VecCopy(user->lUcat, ucat0));
991 PetscCall(VecDuplicate(user->lNvert, &nvert0)); PetscCall(VecCopy(user->lNvert, nvert0));
992 PetscCall(VecDuplicate(user->lNu_t, &nut0)); PetscCall(VecCopy(user->lNu_t, nut0));
993 PetscCall(VecDuplicate(user->lAj, &aj0)); PetscCall(VecCopy(user->lAj, aj0));
994 PetscCall(ComputeMomentumStabilityEstimate(user, 1, simCtx->dt, MOM_STAB_CAND_D, &rep));
995 PetscCall(VecEqual(user->lUcont, ucont0, &eq)); PetscCall(PicurvAssertBool(eq, "lUcont bit-identical"));
996 PetscCall(VecEqual(user->lUcat, ucat0, &eq)); PetscCall(PicurvAssertBool(eq, "lUcat bit-identical"));
997 PetscCall(VecEqual(user->lNvert, nvert0, &eq)); PetscCall(PicurvAssertBool(eq, "lNvert bit-identical"));
998 PetscCall(VecEqual(user->lNu_t, nut0, &eq)); PetscCall(PicurvAssertBool(eq, "lNu_t bit-identical"));
999 PetscCall(VecEqual(user->lAj, aj0, &eq)); PetscCall(PicurvAssertBool(eq, "lAj bit-identical"));
1000 PetscCall(VecDestroy(&ucont0)); PetscCall(VecDestroy(&ucat0)); PetscCall(VecDestroy(&nvert0));
1001 PetscCall(VecDestroy(&nut0)); PetscCall(VecDestroy(&aj0));
1002 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
1003 PetscFunctionReturn(0);
1004}
1005
1006/* A3.6-1. Active-row mask helper: TwoD 1/2/3 disable the right row; full mask otherwise;
1007 * skip (0) only when all three rows are inactive. Tested directly on a fixture nvert. */
1008static PetscErrorCode TestMomentumActiveRowsHelper(void)
1009{
1010 SimCtx *simCtx = NULL; UserCtx *user = NULL;
1011 PetscReal ***nvert;
1012 const PetscInt mx = 9, my = 9, mz = 9;
1013 PetscFunctionBeginUser;
1014 PetscCall(MomMakeUnitGrid(&simCtx, &user, 8, PERIODIC)); /* mx=9; all fluid */
1015 PetscCall(DMDAVecGetArray(user->da, user->lNvert, &nvert));
1016 /* fully periodic interior cell (4,4,4): all rows active regardless of TwoD value below. */
1017 PetscCall(PicurvAssertIntEqual(0x7, MomCellActiveRows(nvert,4,4,4,mx,my,mz,PETSC_FALSE,PETSC_FALSE,PETSC_FALSE,0), "all rows active (periodic interior)"));
1018 PetscCall(PicurvAssertIntEqual(0x6, MomCellActiveRows(nvert,4,4,4,mx,my,mz,PETSC_FALSE,PETSC_FALSE,PETSC_FALSE,1), "TwoD=1 clears xi row"));
1019 PetscCall(PicurvAssertIntEqual(0x5, MomCellActiveRows(nvert,4,4,4,mx,my,mz,PETSC_FALSE,PETSC_FALSE,PETSC_FALSE,2), "TwoD=2 clears eta row"));
1020 PetscCall(PicurvAssertIntEqual(0x3, MomCellActiveRows(nvert,4,4,4,mx,my,mz,PETSC_FALSE,PETSC_FALSE,PETSC_FALSE,3), "TwoD=3 clears zeta row"));
1021 /* positive non-periodic faces clear the corresponding normal rows. */
1022 PetscCall(PicurvAssertIntEqual(0x6, MomCellActiveRows(nvert,4,4,mx-2,mx,my,mz,PETSC_TRUE,PETSC_FALSE,PETSC_FALSE,0), "pos non-periodic xi face clears xi row"));
1023 /* a location is skipped only when all three rows are inactive (here: solid cell). */
1024 PetscCall(MomSetLocalScalarCell(user->da, user->lNvert, 4, 4, 4, 1.0));
1025 PetscCall(DMDAVecRestoreArray(user->da, user->lNvert, &nvert));
1026 PetscCall(DMDAVecGetArray(user->da, user->lNvert, &nvert));
1027 PetscCall(PicurvAssertIntEqual(0, MomCellActiveRows(nvert,4,4,4,mx,my,mz,PETSC_FALSE,PETSC_FALSE,PETSC_FALSE,0), "solid cell -> all rows inactive"));
1028 PetscCall(DMDAVecRestoreArray(user->da, user->lNvert, &nvert));
1029 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
1030 PetscFunctionReturn(0);
1031}
1032
1033/* A3.6-2. Error path restores arrays and the estimator is reusable after the metric is repaired. */
1034static PetscErrorCode TestMomentumStabilityErrorReentry(void)
1035{
1036 SimCtx *simCtx = NULL; UserCtx *user = NULL; MomStabilityReport rep;
1037 PetscErrorCode e_bad = 0; PetscBool eq;
1038 Vec aj_good;
1039 PetscFunctionBeginUser;
1040 PetscCall(MomMakeUnitGrid(&simCtx, &user, 8, PERIODIC));
1041 simCtx->invicid = 0; simCtx->ren = 1.0;
1042 PetscCall(VecDuplicate(user->lAj, &aj_good)); PetscCall(VecCopy(user->lAj, aj_good));
1043
1044 PetscCall(MomSetLocalScalarCell(user->da, user->lAj, 4, 4, 4, PETSC_INFINITY));
1045 PetscCall(PetscPushErrorHandler(PetscIgnoreErrorHandler, NULL));
1046 e_bad = ComputeMomentumStabilityEstimate(user, 1, simCtx->dt, MOM_STAB_CAND_C, &rep);
1047 PetscCall(PetscPopErrorHandler());
1048 PetscCall(PicurvAssertBool((PetscBool)(e_bad != 0), "bad metric triggers error"));
1049
1050 /* Arrays must have been restored: lAj is still writable/usable -> repair it. */
1051 PetscCall(VecCopy(aj_good, user->lAj));
1052 PetscCall(VecEqual(user->lAj, aj_good, &eq));
1053 PetscCall(PicurvAssertBool(eq, "lAj usable after error (arrays were restored)"));
1054
1055 /* Re-entry must now succeed on the repaired state. */
1056 PetscCall(ComputeMomentumStabilityEstimate(user, 1, simCtx->dt, MOM_STAB_CAND_C, &rep));
1057 PetscCall(PicurvAssertRealNear(24.0, rep.lambda_v, 1e-9, "estimator reusable after repair"));
1058 PetscCall(VecDestroy(&aj_good));
1059 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
1060 PetscFunctionReturn(0);
1061}
1062
1063/* A3.6-3. Residual-level BDF combination: the shared helpers produce the exact BDF1/BDF2
1064 * temporal vector combination used by ComputeTotalResidual (a0 from the helper). */
1065static PetscErrorCode TestMomentumBDFResidualCombination(void)
1066{
1067 SimCtx *simCtx = NULL; UserCtx *user = NULL;
1068 Vec Rhs, ref; PetscReal dt, nrm;
1069 PetscFunctionBeginUser;
1070 PetscCall(MomMakeUnitGrid(&simCtx, &user, 6, PERIODIC));
1071 dt = simCtx->dt;
1072 PetscCall(VecSet(user->Ucont, 2.0)); /* U^{n} */
1073 PetscCall(VecSet(user->Ucont_o, 1.0)); /* U^{n-1} */
1074 PetscCall(VecSet(user->Ucont_rm1, 0.5)); /* U^{n-2} */
1075 PetscCall(VecDuplicate(user->Ucont, &Rhs));
1076 PetscCall(VecDuplicate(user->Ucont, &ref));
1077
1078 /* ---- BDF2 (step != 1, step != StartStep) ---- */
1079 simCtx->StartStep = 0; simCtx->step = 5;
1080 PetscCall(PicurvAssertBool(MomentumUsesBDF2(simCtx), "step5 uses BDF2"));
1081 {
1082 const PetscReal a0 = MomentumBDFCoefficient(simCtx); /* == 1.5 */
1083 PetscCall(VecSet(Rhs, 3.0)); /* mock R_spatial */
1084 PetscCall(VecAXPY(Rhs, -a0/dt, user->Ucont));
1085 PetscCall(VecAXPY(Rhs, +2.0/dt, user->Ucont_o));
1086 PetscCall(VecAXPY(Rhs, -0.5/dt, user->Ucont_rm1));
1087 /* independent reference: 3 + (-1.5*2 + 2*1 - 0.5*0.5)/dt = 3 + (-3+2-0.25)/0.1 = 3 - 12.5 = -9.5 */
1088 PetscCall(VecSet(ref, -9.5));
1089 PetscCall(VecAXPY(ref, -1.0, Rhs)); PetscCall(VecNorm(ref, NORM_INFINITY, &nrm));
1090 PetscCall(PicurvAssertRealNear(0.0, nrm, 1e-9, "BDF2 temporal vector combination"));
1091 }
1092 /* ---- BDF1 (step == 1) ---- */
1093 simCtx->StartStep = 0; simCtx->step = 1;
1094 PetscCall(PicurvAssertBool((PetscBool)(!MomentumUsesBDF2(simCtx)), "step1 uses BDF1"));
1095 {
1096 const PetscReal a0 = MomentumBDFCoefficient(simCtx); /* == 1.0 */
1097 PetscCall(VecSet(Rhs, 3.0));
1098 PetscCall(VecAXPY(Rhs, -a0/dt, user->Ucont));
1099 PetscCall(VecAXPY(Rhs, +1.0/dt, user->Ucont_o));
1100 /* reference: 3 + (-1*2 + 1*1)/0.1 = 3 + (-1)/0.1 = 3 - 10 = -7.0 */
1101 PetscCall(VecSet(ref, -7.0));
1102 PetscCall(VecAXPY(ref, -1.0, Rhs)); PetscCall(VecNorm(ref, NORM_INFINITY, &nrm));
1103 PetscCall(PicurvAssertRealNear(0.0, nrm, 1e-9, "BDF1 temporal vector combination"));
1104 }
1105 PetscCall(VecDestroy(&Rhs)); PetscCall(VecDestroy(&ref));
1106 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
1107 PetscFunctionReturn(0);
1108}
1109
1110/**
1111 * @brief Runs the unit-solver PETSc test binary.
1112 */
1113
1114int main(int argc, char **argv)
1115{
1116 PetscErrorCode ierr;
1117 const PicurvTestCase cases[] = {
1118 {"les-filter-paths", TestLESTestFilterPaths},
1119 {"analytical-scalar-verification-helpers", TestAnalyticalScalarVerificationHelpers},
1120 {"analytical-solution-engine-follows-its-source", TestAnalyticalSolutionEngineFollowsItsSource},
1121 {"analytical-solution-engine-taylor-green-samples", TestAnalyticalSolutionEngineTaylorGreenSamples},
1122 {"analytical-boundary-values-are-at-face-centres", TestAnalyticalBoundaryValuesAreAtFaceCentres},
1123 {"analytical-solution-for-particles-evaluates-the-source", TestAnalyticalSolutionForParticlesEvaluatesTheSource},
1124 {"compute-eddy-viscosity-les-deterministic-field", TestComputeEddyViscosityLESDeterministicField},
1125 {"flow-solver-rejects-unsupported-momentum-solver-type", TestFlowSolverRejectsUnsupportedMomentumSolverType},
1126 {"driven-channel-flow-source", TestDrivenChannelFlowSource},
1127 {"momentum-bdf-coefficient", TestMomentumBDFCoefficient},
1128 {"momentum-stability-centered-convection", TestMomentumStabilityCenteredConvection},
1129 {"momentum-stability-quick-interior", TestMomentumStabilityQuickInterior},
1130 {"momentum-stability-quick-boundary", TestMomentumStabilityQuickBoundary},
1131 {"momentum-stability-viscous-cartesian-factor8-estimate", TestMomentumStabilityViscousLongitudinal},
1132 {"momentum-stability-viscous-scales-with-nu", TestMomentumStabilityViscousScalesWithNu},
1133 {"momentum-stability-les-eddy-viscosity", TestMomentumStabilityLESEddyViscosity},
1134 {"momentum-stability-one-sided-viscous", TestMomentumStabilityOneSidedViscous},
1135 {"momentum-stability-read-only", TestMomentumStabilityReadOnly},
1136 {"momentum-stability-anisotropic-viscous", TestMomentumStabilityAnisotropicViscous},
1137 {"momentum-stability-directional-quick", TestMomentumStabilityDirectionalQuick},
1138 {"momentum-stability-one-sided-directions", TestMomentumStabilityOneSidedDirections},
1139 {"momentum-stability-active-row-mask", TestMomentumStabilityActiveRowMask},
1140 {"momentum-stability-validation", TestMomentumStabilityValidation},
1141 {"momentum-stability-candidate-bc-divergence", TestMomentumStabilityCandidateBCDivergence},
1142 {"momentum-stability-candidate-d-shear", TestMomentumStabilityCandidateDShear},
1143 {"momentum-stability-wall-suppression", TestMomentumStabilityWallSuppression},
1144 {"momentum-stability-read-only-exact", TestMomentumStabilityReadOnlyExact},
1145 {"momentum-active-rows-helper", TestMomentumActiveRowsHelper},
1146 {"momentum-stability-error-reentry", TestMomentumStabilityErrorReentry},
1147 {"momentum-bdf-residual-combination", TestMomentumBDFResidualCombination},
1148 };
1149
1150 ierr = PetscInitialize(&argc, &argv, NULL, "PICurv solver utility tests");
1151 if (ierr) {
1152 return (int)ierr;
1153 }
1154
1155 ierr = PicurvRunTests("unit-solver", cases, sizeof(cases) / sizeof(cases[0]));
1156 if (ierr) {
1157 PetscFinalize();
1158 return (int)ierr;
1159 }
1160
1161 ierr = PetscFinalize();
1162 return (int)ierr;
1163}
PetscErrorCode AnalyticalFieldDestroy(SimCtx *simCtx)
Release what AnalyticalSolutionEngine() keeps from step to step, if anything.
PetscErrorCode AnalyticalSolutionEngine(SimCtx *simCtx)
Sets the Eulerian fields from the case's source (-ic_source_*) at the step's time.
PetscBool AnalyticalFieldSupportsInterpolationError(const SimCtx *simCtx)
Reports whether the analytical field can be compared with interpolated particle velocities.
PetscErrorCode SetAnalyticalSolutionForParticles(Vec tempVec, SimCtx *simCtx)
Evaluates the analytical velocity at particle positions.
Momentum source terms added to the contravariant RHS.
PetscErrorCode ComputeDrivenChannelFlowSource(UserCtx *user, Vec Rct)
Applies a momentum source term to drive flow in a periodic channel or pipe.
Definition BodyForces.c:38
double ApplyLESTestFilter(LESTestFilterKernel kernel, double values[3][3][3], double weights[3][3][3])
Applies a numerical "test filter" to a 3x3x3 stencil of data points.
Definition Filter.c:123
PetscErrorCode ComputeEddyViscosityLES(UserCtx *user)
Computes the turbulent eddy viscosity for one block.
Definition les.c:899
@ MOM_STAB_LIMITER_VISCOSITY
MomStabLimiter limiter
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.
@ MOM_STAB_CAND_C
@ MOM_STAB_CAND_D
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).
PetscErrorCode ComputeMomentumStabilityEstimate(UserCtx *user, PetscInt block_number, PetscReal dt, MomStabCandidate candidate, MomStabilityReport *rep)
Compute the momentum pseudo-time stability estimate (shadow/diagnostic).
Diagnostic report produced by ComputeMomentumStabilityEstimate().
@ PARTICLE_FIELD_ID_PSI
PetscErrorCode FlowSolver(SimCtx *simCtx)
Orchestrates a single time step of the Eulerian fluid solver.
Definition solvers.c:9
static PetscErrorCode TestAnalyticalSolutionEngineTaylorGreenSamples(void)
Tests exact Taylor-Green samples on selected Eulerian interior and boundary points.
static PetscErrorCode TestMomentumStabilityWallSuppression(void)
static PetscErrorCode TestAnalyticalBoundaryValuesAreAtFaceCentres(void)
Tests that a boundary value is the source at its own face's centre on both sides: a + face's value li...
static PetscErrorCode MomSetLocalScalarCell(DM da, Vec lvec, PetscInt ci, PetscInt cj, PetscInt ck, PetscReal v)
Sets a single local-scalar cell value (e.g.
static PetscErrorCode TestMomentumActiveRowsHelper(void)
static PetscErrorCode TestComputeEddyViscosityLESDeterministicField(void)
Tests deterministic LES eddy-viscosity computation on a linear velocity field.
static PetscErrorCode TestFlowSolverRejectsUnsupportedMomentumSolverType(void)
Tests FlowSolver guardrails for unsupported momentum solver selections.
static PetscErrorCode TestMomentumStabilityOneSidedDirections(void)
int main(int argc, char **argv)
Runs the unit-solver PETSc test binary.
static PetscErrorCode UseAnalyticalSource(SimCtx *simCtx, const char *u, const char *v, const char *w, const char *pressure)
Selects an analytical field: the options a case's source becomes.
static PetscErrorCode TestMomentumStabilityReadOnly(void)
static PetscErrorCode TestMomentumStabilityOneSidedViscous(void)
static PetscErrorCode MomSetCartesianMetrics(UserCtx *user, PetscReal dx, PetscReal dy, PetscReal dz)
Sets uniform Cartesian metrics for spacing (dx,dy,dz) on all cell and face arrays.
static PetscErrorCode TestAnalyticalScalarVerificationHelpers(void)
Tests analytical scalar verification helper routines.
static PetscErrorCode TestMomentumStabilityReadOnlyExact(void)
static PetscErrorCode TestAnalyticalSolutionEngineFollowsItsSource(void)
Tests that the field is the source: zero, then uniform with its face fluxes and boundary values,...
static PetscErrorCode TestMomentumStabilityErrorReentry(void)
static PetscErrorCode TestMomentumStabilityActiveRowMask(void)
static PetscErrorCode TestMomentumStabilityCandidateDShear(void)
static PetscErrorCode TestMomentumStabilityViscousLongitudinal(void)
static PetscErrorCode MomMakeUnitGrid(SimCtx **simCtx, UserCtx **user, PetscInt n, BCType bc)
static PetscErrorCode TestMomentumStabilityCandidateBCDivergence(void)
static PetscErrorCode TestDrivenChannelFlowSource(void)
Tests driven-channel flow source-term evaluation.
static PetscErrorCode MomFillLocalCmpnts(DM fda, Vec lvec, PetscReal x, PetscReal y, PetscReal z)
Fills a local Cmpnts vector (ghosts included) with a uniform vector value.
static PetscErrorCode TestMomentumStabilityViscousScalesWithNu(void)
static PetscErrorCode TestMomentumStabilityAnisotropicViscous(void)
static PetscErrorCode TestAnalyticalSolutionForParticlesEvaluatesTheSource(void)
Tests the source evaluated at particle positions, and the fields it cannot be evaluated for.
static PetscErrorCode TestMomentumBDFCoefficient(void)
static PetscErrorCode TestMomentumStabilityCenteredConvection(void)
static PetscErrorCode TestMomentumStabilityDirectionalQuick(void)
static PetscErrorCode MomMakeUnitGridP(SimCtx **simCtx, UserCtx **user, PetscInt n, PetscBool px, PetscBool py, PetscBool pz, BCType bc)
static PetscErrorCode TestMomentumBDFResidualCombination(void)
static PetscErrorCode MomFillLocalScalar(DM da, Vec lvec, PetscReal v)
Fills a local scalar vector (ghosts included) with a uniform value.
static PetscErrorCode TestLESTestFilterPaths(void)
Tests LES test-filter helper paths for representative cases.
static PetscErrorCode MomFillUcatShearY(DM fda, Vec lvec, PetscReal gamma)
Fills lUcat as a linear shear u=(gamma*j,0,0) so |grad u|_inf = gamma.
static PetscErrorCode TestMomentumStabilityQuickBoundary(void)
static PetscErrorCode TestMomentumStabilityLESEddyViscosity(void)
static PetscErrorCode TestMomentumStabilityQuickInterior(void)
static PetscErrorCode MomFillUcontXRamp(DM fda, Vec lvec, PetscReal slope)
Fills lUcont.x as a linear ramp slope*i (nonzero discrete contravariant divergence).
static PetscErrorCode TestMomentumStabilityValidation(void)
PetscErrorCode PicurvCreateMinimalContexts(SimCtx **simCtx_out, UserCtx **user_out, PetscInt mx, PetscInt my, PetscInt mz)
Builds minimal SimCtx and UserCtx fixtures for C unit tests.
PetscErrorCode PicurvAssertRealNear(PetscReal expected, PetscReal actual, PetscReal tol, const char *context)
Asserts that two real values agree within tolerance.
PetscErrorCode PicurvDestroyMinimalContexts(SimCtx **simCtx_ptr, UserCtx **user_ptr)
Destroys minimal SimCtx/UserCtx fixtures and all owned PETSc objects.
PetscErrorCode PicurvCreateMinimalContextsWithPeriodicity(SimCtx **simCtx_out, UserCtx **user_out, PetscInt mx, PetscInt my, PetscInt mz, PetscBool x_periodic, PetscBool y_periodic, PetscBool z_periodic)
Builds minimal SimCtx and UserCtx fixtures for C unit tests with configurable periodicity.
PetscErrorCode PicurvCreateSwarmPair(UserCtx *user, PetscInt nlocal, const char *post_field_name)
Creates matched solver and post-processing swarms for tests.
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 PicurvAssertVecConstant(Vec vec, PetscScalar expected, PetscReal tol, const char *context)
Asserts that a PETSc vector is spatially constant within tolerance.
PetscErrorCode PicurvAssertIntEqual(PetscInt expected, PetscInt actual, const char *context)
Asserts that two integer values are equal.
PetscErrorCode PicurvPopulateIdentityMetrics(UserCtx *user)
Populates identity metric vectors on the minimal grid fixture.
PetscErrorCode PicurvAssertBool(PetscBool value, const char *context)
Asserts that one boolean condition is true.
Shared declarations for the PICurv C test fixture and assertion layer.
Named test case descriptor consumed by PicurvRunTests.
@ DYNAMIC_SMAGORINSKY
Definition variables.h:586
BCType
Defines the general mathematical/physical Category of a boundary.
Definition variables.h:316
@ INLET
Definition variables.h:323
@ PERIODIC
Definition variables.h:325
@ WALL
Definition variables.h:319
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 forceScalingFactor
Definition variables.h:1018
@ BC_HANDLER_PERIODIC_DRIVEN_CONSTANT_FLUX
Definition variables.h:354
PetscReal ren
Definition variables.h:965
BCHandlerType handler_type
Definition variables.h:427
Vec lKEta
Definition variables.h:1256
PetscReal dt
Definition variables.h:933
PetscReal bulkVelocityCorrection
Definition variables.h:1030
@ LES_TEST_FILTER_SIMPSON_IK
Definition variables.h:628
@ LES_TEST_FILTER_VOLUME_WEIGHTED_BOX
Definition variables.h:627
Vec lJCsi
Definition variables.h:1255
Vec Ucont
Definition variables.h:1197
PetscInt StartStep
Definition variables.h:926
Vec Ubcs
Physical Cartesian velocity at boundary faces. Full 3D array but only boundary-face entries are meani...
Definition variables.h:172
MomentumSolverType
Enumerator to identify the implemented momentum solver strategies.
Definition variables.h:729
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
PetscScalar z
Definition variables.h:145
Vec lKCsi
Definition variables.h:1256
Vec Ucont_o
Definition variables.h:1204
Vec lCenty
Definition variables.h:1253
PetscInt central
Definition variables.h:963
Vec lJZet
Definition variables.h:1255
Vec lCentx
Definition variables.h:1253
Vec Ucont_rm1
Definition variables.h:1207
Vec lUcont
Definition variables.h:1197
PetscInt step
Definition variables.h:924
Vec lICsi
Definition variables.h:1254
DMDALocalInfo info
Definition variables.h:1169
Vec lUcat
Definition variables.h:1197
PetscScalar y
Definition variables.h:145
PetscInt les
Active LES closure; an LESModelType value.
Definition variables.h:1041
Vec Nvert
Definition variables.h:1197
BCType mathematical_type
Definition variables.h:426
Vec lCentz
Definition variables.h:1253
PetscBool restartHistoryAvailable
Definition variables.h:947
PetscReal ti
Definition variables.h:925
MomentumSolverType mom_solver_type
Definition variables.h:958
VerificationFieldConfig verificationScalar
Definition variables.h:997
PetscReal drivingForceMagnitude
Definition variables.h:1018
@ BC_FACE_NEG_X
Definition variables.h:309
@ BC_FACE_POS_Z
Definition variables.h:311
@ BC_FACE_POS_Y
Definition variables.h:310
@ BC_FACE_NEG_Z
Definition variables.h:311
@ BC_FACE_POS_X
Definition variables.h:309
@ BC_FACE_NEG_Y
Definition variables.h:310
A 3D point or vector with PetscScalar components.
Definition variables.h:144
The master context for the entire simulation.
Definition variables.h:916
User-defined context containing data specific to a single computational grid level.
Definition variables.h:1157
PetscErrorCode VerificationFieldCompile(const char *text, VerificationFieldConfig *field)
Compiles a verification field's expression, in physical x, y, z and t, and enables the field.
PetscErrorCode SetVerificationScalarOnParticles(UserCtx *user, ParticleFieldId particle_field_id)
Writes the configured verification scalar profile onto a particle swarm scalar field.
PetscErrorCode VerificationFieldEvaluate(const SimCtx *simCtx, const VerificationFieldConfig *field, Cmpnts point, PetscReal solver_time, PetscReal *value)
Evaluates a verification field at a point.
PetscErrorCode SetVerificationScalarAtCellCenters(UserCtx *user, Vec targetVec)
Writes the configured verification scalar profile at physical cell centers into a scalar Vec.
double nu_t(double yplus)
Computes turbulent eddy viscosity ratio (ν_t / ν)