PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
les.c
Go to the documentation of this file.
1/**
2 * @file les.c
3 * @brief Implements the Large Eddy Simulation (LES) subgrid-scale closure.
4 *
5 * The closure is built from small kernels that each do one thing, so the physics is
6 * readable at the call sites and testable without a running solve:
7 *
8 * - symmetric-tensor algebra (`SymTensor*`), which knows nothing about turbulence;
9 * - strain rate and filter width, shared by every eddy-viscosity model;
10 * - the Germano identity pieces, `LeonardStress()` and `GermanoModelTensor()`;
11 * - the coefficient averaging, which is `PicurvSpatialRatioAverage()` from the shared
12 * spatial-target module: it turns the local dynamic model into the plane- or
13 * volume-averaged one without a separate code path per mode;
14 * - limiting and eddy-viscosity assembly.
15 *
16 * Two routines drive them. `ComputeSmagorinskyConstant()` runs the Germano-Lilly
17 * procedure for the dynamic model, and `ComputeEddyViscosityLES()` turns whichever
18 * coefficient is in force into the eddy viscosity the momentum equations add to the
19 * molecular one. `LogLESDiagnostics()` reports the coefficient's time history.
20 *
21 * The coefficient stored in `UserCtx::CS` is `C`, the factor multiplying
22 * `Delta^2 |S|`, which is `Cs^2` in the classical notation and is signed when
23 * backscatter is admitted. Conversion to the familiar `Cs` happens only where a
24 * human reads the number.
25 */
26
27#include "les.h"
28#include "statistics_target.h"
29
30// A small constant to prevent division by zero in sensitive calculations.
31static const double LES_EPSILON = 1.0e-12;
32
33/*================================================================================*
34 * INTERNAL (STATIC) FUNCTIONS *
35 *================================================================================*/
36
37/**
38 * @brief Synchronizes the completed Smagorinsky coefficient field.
39 */
40static PetscErrorCode FinalizeSmagorinskyConstantField(UserCtx *user)
41{
42 const FieldId fields[] = {FIELD_ID_CS};
43
44 PetscFunctionBeginUser;
46 PetscCall(SynchronizePeriodicCellFields(user, 1, fields));
47 PetscCall(UpdateLocalGhosts(user, FIELD_ID_CS));
49 PetscFunctionReturn(0);
50}
51
52/**
53 * @brief Resolves the iteration domain the closure computes over.
54 *
55 * Delegates to the shared spatial target so the closure, the statistics pipeline, and
56 * anything else looping over cell-centred data agree on which indices are physical.
57 * The domain excludes PETSc halo storage and the solver's boundary, dummy, and
58 * duplicate-periodic indices; the last of those matters here, because counting a
59 * duplicate plane in a spatial average would weight a real cell twice.
60 *
61 * The plan is resolved for `CS` as a representative cell-centred field. The bounds
62 * depend on the layout and the block's periodicity, not on which field is being
63 * iterated, so the scratch vectors this module allocates share them.
64 */
65static PetscErrorCode LESResolveDomain(UserCtx *user, SpatialTargetPlan *plan)
66{
67 PetscFunctionBeginUser;
71 PetscFunctionReturn(0);
72}
73
74/**
75 * @brief Marks the first cells beside a modelled wall, so the procedure skips them.
76 *
77 * A wall model exists because the grid does not resolve the wall layer, and the first
78 * cell sits inside it, with its wall flux supplied by the model's stress rather than by
79 * a resolved gradient. The Germano identity evaluated there measures an under-resolved
80 * wall layer, not the inertial-range motions the procedure assumes, so the cell is
81 * excluded from both contraction sums; averaging it in biases whatever set it belongs to. Under global averaging that set is the whole
82 * domain; under homogeneous averaging retaining the wall-normal direction it is the wall
83 * plane, whose value would otherwise be entirely imposed.
84 *
85 * A cell left with no data receives a zero coefficient, which is the right answer where
86 * a wall model is already supplying the stress.
87 *
88 * Only meaningful while a wall model is active; a wall-resolved run resolves that layer
89 * and every cell takes part.
90 */
91static PetscErrorCode BuildWallModelExclusionMask(UserCtx *user, Vec inclusion)
92{
93 const DMDALocalInfo info = user->info;
94 const BCFace negative[3] = {BC_FACE_NEG_X, BC_FACE_NEG_Y, BC_FACE_NEG_Z};
95 const BCFace positive[3] = {BC_FACE_POS_X, BC_FACE_POS_Y, BC_FACE_POS_Z};
96 const PetscInt extent[3] = {info.mx, info.my, info.mz};
97 PetscReal ***mask = NULL;
99
100 PetscFunctionBeginUser;
102 PetscCall(VecSet(inclusion, 1.0));
103 PetscCall(LESResolveDomain(user, &plan));
104 PetscCall(DMDAVecGetArray(user->da, inclusion, &mask));
105 for (PetscInt k = plan.start[2]; k < plan.end[2]; k++)
106 for (PetscInt j = plan.start[1]; j < plan.end[1]; j++)
107 for (PetscInt i = plan.start[0]; i < plan.end[0]; i++) {
108 const PetscInt coord[3] = {i, j, k};
109
110 for (PetscInt axis = 0; axis < 3; axis++) {
111 /* Index 1 and extent-2 are the first interior cells beside a modelled wall. */
112 if ((BoundaryFaceHasWallShear(&user->boundary_faces[negative[axis]]) &&
113 coord[axis] == 1) ||
114 (BoundaryFaceHasWallShear(&user->boundary_faces[positive[axis]]) &&
115 coord[axis] == extent[axis] - 2)) {
116 mask[k][j][i] = 0.0;
117 break;
118 }
119 }
120 }
121 PetscCall(DMDAVecRestoreArray(user->da, inclusion, &mask));
123 PetscFunctionReturn(0);
124}
125
126/**
127 * @brief Implementation of \ref SymTensorSelfOuter().
128 * @details Full API contract is documented with the header declaration in
129 * `include/les.h`.
130 * @see SymTensorSelfOuter()
131 */
133{
134 SymTensor t;
135
136 t.xx = v.x * v.x;
137 t.xy = v.x * v.y;
138 t.xz = v.x * v.z;
139 t.yy = v.y * v.y;
140 t.yz = v.y * v.z;
141 t.zz = v.z * v.z;
142 return t;
143}
144
145/**
146 * @brief Implementation of \ref SymTensorCombine().
147 * @details Full API contract is documented with the header declaration in
148 * `include/les.h`.
149 * @see SymTensorCombine()
150 */
151SymTensor SymTensorCombine(PetscReal a, SymTensor x, PetscReal b, SymTensor y)
152{
153 SymTensor t;
154
155 t.xx = a * x.xx + b * y.xx;
156 t.xy = a * x.xy + b * y.xy;
157 t.xz = a * x.xz + b * y.xz;
158 t.yy = a * x.yy + b * y.yy;
159 t.yz = a * x.yz + b * y.yz;
160 t.zz = a * x.zz + b * y.zz;
161 return t;
162}
163
164/**
165 * @brief Implementation of \ref SymTensorTrace().
166 * @details Full API contract is documented with the header declaration in
167 * `include/les.h`.
168 * @see SymTensorTrace()
169 */
171{
172 return t.xx + t.yy + t.zz;
173}
174
175/**
176 * @brief Implementation of \ref SymTensorDeviator().
177 * @details Full API contract is documented with the header declaration in
178 * `include/les.h`.
179 * @see SymTensorDeviator()
180 */
182{
183 const PetscReal isotropic = SymTensorTrace(t) / 3.0;
184
185 t.xx -= isotropic;
186 t.yy -= isotropic;
187 t.zz -= isotropic;
188 return t;
189}
190
191/**
192 * @brief Implementation of \ref SymTensorContract().
193 * @details Full API contract is documented with the header declaration in
194 * `include/les.h`.
195 * @see SymTensorContract()
196 */
198{
199 // The three off-diagonal components each stand for two entries of the full tensor.
200 return a.xx * b.xx + a.yy * b.yy + a.zz * b.zz +
201 2.0 * (a.xy * b.xy + a.xz * b.xz + a.yz * b.yz);
202}
203
204/**
205 * @brief Implementation of \ref SymTensorNormSq().
206 * @details Full API contract is documented with the header declaration in
207 * `include/les.h`.
208 * @see SymTensorNormSq()
209 */
211{
212 return SymTensorContract(t, t);
213}
214
215/*================================================================================*
216 * STRAIN RATE AND FILTER WIDTH *
217 *================================================================================*/
218
219/**
220 * @brief Implementation of \ref StrainRateFromGradients().
221 * @details Full API contract is documented with the header declaration in
222 * `include/les.h`.
223 * @see StrainRateFromGradients()
224 */
225PetscErrorCode StrainRateFromGradients(Cmpnts dudx, Cmpnts dvdx, Cmpnts dwdx,
226 SymTensor *strain, PetscReal *magnitude)
227{
228 SymTensor s;
229
230 PetscFunctionBeginUser;
231
232 s.xx = dudx.x;
233 s.xy = 0.5 * (dudx.y + dvdx.x);
234 s.xz = 0.5 * (dudx.z + dwdx.x);
235 s.yy = dvdx.y;
236 s.yz = 0.5 * (dvdx.z + dwdx.y);
237 s.zz = dwdx.z;
238
239 if (strain) *strain = s;
240 // |S| = sqrt(2 S_ij S_ij), with the off-diagonal doubling handled by the contraction.
241 if (magnitude) *magnitude = PetscSqrtReal(2.0 * SymTensorNormSq(s));
242
243 PetscFunctionReturn(0);
244}
245
246/**
247 * @brief Implementation of \ref ComputeCellFilterWidth().
248 * @details Full API contract is documented with the header declaration in
249 * `include/les.h`.
250 * @see ComputeCellFilterWidth()
251 */
252PetscErrorCode ComputeCellFilterWidth(LESFilterWidthModel model, PetscReal aj,
253 Cmpnts csi, Cmpnts eta, Cmpnts zet, PetscReal *delta)
254{
255 double dx = 0.0, dy = 0.0, dz = 0.0;
256
257 PetscFunctionBeginUser;
258 PetscCheck(delta != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
259 "Filter width destination cannot be NULL.");
260 PetscCheck(aj > 0.0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE,
261 "Cell Jacobian must be positive to define a filter width; received %g.", (double)aj);
262
264 // Cell volume alone: exact for a cube, and increasingly optimistic as the
265 // cell is stretched, because it averages the three extents geometrically.
266 *delta = PetscPowReal(1.0 / aj, 1.0 / 3.0);
267 PetscFunctionReturn(0);
268 }
269
270 // The cell's own extents, not the Cartesian components of its diagonal: a filter
271 // width that changed when the same cell was rotated would hand a bend nine times the
272 // eddy viscosity of an identical cell in a straight section.
273 PetscCall(ComputeCellDirectionalExtents(aj, csi, eta, zet, &dx, &dy, &dz));
274
275 switch (model) {
277 // The largest unresolved scale the cell can carry; conservative on stretched grids.
278 *delta = PetscMax(dx, PetscMax(dy, dz));
279 break;
281 // Scotti, Meneveau & Lilly (1993): the cube root of the extents, multiplied by
282 // f(a1, a2), where a1 and a2 are the two shorter extents over the longest. f is 1
283 // for a cube and grows with the cell's distortion. It assumes the cut-off lies in
284 // the inertial range in every direction, which a very long cell violates.
285 const double longest = PetscMax(dx, PetscMax(dy, dz));
286 const double shortest = PetscMin(dx, PetscMin(dy, dz));
287 const double middle = dx + dy + dz - longest - shortest;
288 const double ln_a1 = log(shortest / longest), ln_a2 = log(middle / longest);
289 const double shape = cosh(sqrt((4.0 / 27.0) *
290 (ln_a1 * ln_a1 - ln_a1 * ln_a2 + ln_a2 * ln_a2)));
291 *delta = PetscPowReal(PetscMax(dx * dy * dz, LES_EPSILON), 1.0 / 3.0) * shape;
292 break;
293 }
295 default:
296 *delta = PetscPowReal(PetscMax(dx * dy * dz, LES_EPSILON), 1.0 / 3.0);
297 break;
298 }
299
300 PetscFunctionReturn(0);
301}
302
303/*================================================================================*
304 * GERMANO IDENTITY KERNELS *
305 *================================================================================*/
306
307/**
308 * @brief Implementation of \ref LeonardStress().
309 * @details Full API contract is documented with the header declaration in
310 * `include/les.h`.
311 * @see LeonardStress()
312 */
313SymTensor LeonardStress(Cmpnts velocity_filtered, SymTensor velocity_product_filtered)
314{
315 // L_ij = (u_i u_j)^ - u^_i u^_j : the stress carried between the two filter widths.
316 return SymTensorCombine(1.0, velocity_product_filtered,
317 -1.0, SymTensorSelfOuter(velocity_filtered));
318}
319
320/**
321 * @brief Implementation of \ref GermanoModelTensor().
322 * @details Full API contract is documented with the header declaration in
323 * `include/les.h`.
324 * @see GermanoModelTensor()
325 */
326SymTensor GermanoModelTensor(PetscReal delta, PetscReal alpha,
327 PetscReal strain_magnitude_filtered,
328 SymTensor strain_filtered,
329 SymTensor strain_product_filtered)
330{
331 // Term one: the model evaluated on the test-filtered strain. Both factors were
332 // filtered separately, then multiplied.
333 const SymTensor test_scale = SymTensorCombine(alpha * strain_magnitude_filtered,
334 strain_filtered, 0.0, strain_filtered);
335
336 // Term two: the grid-scale model formed pointwise and then test-filtered. This is
337 // the filter of a product, and it is not equal to the product of the filtered
338 // factors above. That inequality carries the whole information content of the
339 // dynamic procedure.
340 const SymTensor grid_scale = strain_product_filtered;
341
342 const SymTensor model = SymTensorCombine(-2.0 * delta * delta, test_scale,
343 2.0 * delta * delta, grid_scale);
344
345 // Trace-free, so the Leonard stress's trace cannot enter the contraction through
346 // whatever discrete divergence the velocity field carries.
347 return SymTensorDeviator(model);
348}
349
350/*================================================================================*
351 * COEFFICIENT AVERAGING AND LIMITING *
352 *================================================================================*/
353
354/**
355 * @brief Implementation of \ref ResolveLESAveragingDirections().
356 * @details Full API contract is documented with the header declaration in
357 * `include/les.h`.
358 * @see ResolveLESAveragingDirections()
359 */
360PetscErrorCode ResolveLESAveragingDirections(UserCtx *user, PetscBool direction[3])
361{
362 const LESConfig *config = &user->simCtx->les_config;
363 PetscInt selected = 0;
364 PetscBool periodic[3];
365
366 PetscFunctionBeginUser;
368 PetscCheck(direction != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
369 "Averaging direction destination cannot be NULL.");
370 GetPeriodicAxes(user->simCtx, periodic);
371
372 for (PetscInt axis = 0; axis < 3; axis++) direction[axis] = PETSC_FALSE;
373
374 switch (config->averaging_mode) {
376 // No averaging: the coefficient is whatever the single cell's contractions give.
378 PetscFunctionReturn(0);
379
381 for (PetscInt axis = 0; axis < 3; axis++) direction[axis] = PETSC_TRUE;
383 PetscFunctionReturn(0);
384
386 default:
387 for (PetscInt axis = 0; axis < 3; axis++) {
388 if (config->averaging_direction[axis]) {
389 direction[axis] = PETSC_TRUE;
390 selected++;
391 }
392 }
393 // Naming no direction asks for the periodic axes, which is where the flow is
394 // homogeneous in every case the solver can currently express.
395 if (selected == 0) {
396 for (PetscInt axis = 0; axis < 3; axis++) {
397 if (periodic[axis]) {
398 direction[axis] = PETSC_TRUE;
399 selected++;
400 }
401 }
402 }
403 PetscCheck(selected > 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE,
404 "Homogeneous LES averaging was requested, but this block declares no "
405 "periodic axis and the configuration names no direction. Name the "
406 "homogeneous directions explicitly or select local averaging.");
408 PetscFunctionReturn(0);
409 }
411}
412
413/**
414 * @brief Implementation of \ref ClipModelCoefficient().
415 * @details Full API contract is documented with the header declaration in
416 * `include/les.h`.
417 * @see ClipModelCoefficient()
418 */
419PetscReal ClipModelCoefficient(PetscReal coefficient, const LESConfig *config, PetscBool *limited)
420{
421 PetscReal result = coefficient;
422
423 switch (config->clip_mode) {
424 case LES_CLIP_NONE:
425 // Signed coefficient retained: backscatter survives, and stability is left to
426 // the total-viscosity floor rather than to the coefficient's sign.
427 break;
429 if (result < 0.0) result = 0.0;
430 break;
431 case LES_CLIP_CLAMP:
432 default:
433 if (result < 0.0) result = 0.0;
434 if (result > config->max_cs * config->max_cs) result = config->max_cs * config->max_cs;
435 break;
436 }
437
438 if (limited) *limited = (PetscBool)(result != coefficient);
439 return result;
440}
441
442/**
443 * @brief Implementation of \ref EddyViscosityFromCoefficient().
444 * @details Full API contract is documented with the header declaration in
445 * `include/les.h`.
446 * @see EddyViscosityFromCoefficient()
447 */
448PetscReal EddyViscosityFromCoefficient(PetscReal coefficient, PetscReal delta,
449 PetscReal strain_magnitude,
450 PetscReal molecular_viscosity,
451 PetscReal min_viscosity_ratio)
452{
453 PetscReal nu_t = coefficient * delta * delta * strain_magnitude;
454
455 // A negative eddy viscosity is physical up to the point where it would drive the
456 // total viscosity non-positive and make the momentum operator ill posed.
457 const PetscReal floor = (min_viscosity_ratio - 1.0) * molecular_viscosity;
458
459 if (nu_t < floor) nu_t = floor;
460 return nu_t;
461}
462
463/**
464 * @brief Implementation of \ref WALEEddyViscosity().
465 * @details Full API contract is documented with the header declaration in
466 * `include/les.h`.
467 * @see WALEEddyViscosity()
468 */
469PetscReal WALEEddyViscosity(Cmpnts dudx, Cmpnts dvdx, Cmpnts dwdx,
470 PetscReal delta, PetscReal coefficient)
471{
473 const PetscReal g[3][3] = {{dudx.x, dudx.y, dudx.z},
474 {dvdx.x, dvdx.y, dvdx.z},
475 {dwdx.x, dwdx.y, dwdx.z}};
476 PetscReal g2[3][3], sd[3][3], trace = 0.0, ss = 0.0, sdsd = 0.0, denominator;
477
478 for (PetscInt a = 0; a < 3; ++a)
479 for (PetscInt b = 0; b < 3; ++b) {
480 g2[a][b] = 0.0;
481 for (PetscInt c = 0; c < 3; ++c) g2[a][b] += g[a][c] * g[c][b];
482 }
483 for (PetscInt a = 0; a < 3; ++a) trace += g2[a][a];
484 for (PetscInt a = 0; a < 3; ++a)
485 for (PetscInt b = 0; b < 3; ++b) {
486 const PetscReal s = 0.5 * (g[a][b] + g[b][a]);
487 // Traceless symmetric part of the squared gradient: it vanishes in pure shear,
488 // which is what lets the model switch itself off in a laminar shear layer.
489 sd[a][b] = 0.5 * (g2[a][b] + g2[b][a]) - (a == b ? trace / 3.0 : 0.0);
490 ss += s * s;
491 sdsd += sd[a][b] * sd[a][b];
492 }
493
494 denominator = PetscPowReal(ss, 2.5) + PetscPowReal(sdsd, 1.25);
495 if (denominator <= LES_EPSILON * LES_EPSILON) { PROFILE_HELPER_END; return 0.0; }
497 return coefficient * coefficient * delta * delta * PetscPowReal(sdsd, 1.5) / denominator;
498}
499
500/**
501 * @brief Implementation of \ref VremanEddyViscosity().
502 * @details Full API contract is documented with the header declaration in
503 * `include/les.h`.
504 * @see VremanEddyViscosity()
505 */
506PetscReal VremanEddyViscosity(Cmpnts dudx, Cmpnts dvdx, Cmpnts dwdx,
507 const Cmpnts edges[3], PetscReal coefficient)
508{
510 const Cmpnts gradient[3] = {dudx, dvdx, dwdx};
511 PetscReal beta[3][3] = {{0.0}}, alpha_sq = 0.0, b_beta;
512
513 // Vreman's beta_ij = sum_m Delta_m^2 alpha_mi alpha_mj on a Cartesian grid, where
514 // Delta_m alpha_mi is the change in u_i across the cell in direction m. On a
515 // curvilinear grid that change is edge_m . grad(u_i), so the same sum over the
516 // cell's own directions reproduces the Cartesian form on an aligned grid and does
517 // not depend on the grid's orientation elsewhere.
518 for (PetscInt m = 0; m < 3; ++m) {
519 PetscReal change[3];
520 for (PetscInt a = 0; a < 3; ++a)
521 change[a] = edges[m].x * gradient[a].x + edges[m].y * gradient[a].y + edges[m].z * gradient[a].z;
522 for (PetscInt a = 0; a < 3; ++a)
523 for (PetscInt b = 0; b < 3; ++b) beta[a][b] += change[a] * change[b];
524 }
525 for (PetscInt a = 0; a < 3; ++a)
526 alpha_sq += gradient[a].x * gradient[a].x + gradient[a].y * gradient[a].y + gradient[a].z * gradient[a].z;
527
528 b_beta = beta[0][0] * beta[1][1] - beta[0][1] * beta[0][1]
529 + beta[0][0] * beta[2][2] - beta[0][2] * beta[0][2]
530 + beta[1][1] * beta[2][2] - beta[1][2] * beta[1][2];
531
532 // B_beta is non-negative in exact arithmetic; rounding can leave it a hair below.
533 if (alpha_sq <= LES_EPSILON * LES_EPSILON || b_beta <= 0.0) { PROFILE_HELPER_END; return 0.0; }
535 return coefficient * PetscSqrtReal(b_beta / alpha_sq);
536}
537
538/**
539 * @brief Implementation of \ref SubgridKineticEnergy().
540 * @details Full API contract is documented with the header declaration in
541 * `include/les.h`.
542 * @see SubgridKineticEnergy()
543 */
544PetscReal SubgridKineticEnergy(PetscReal yoshizawa_ci, PetscReal delta, PetscReal strain_magnitude)
545{
546 return 2.0 * yoshizawa_ci * delta * delta * strain_magnitude * strain_magnitude;
547}
548
549/*================================================================================*
550 * DYNAMIC PROCEDURE INTERNALS *
551 *================================================================================*/
552
553/**
554 * @brief Maps a cell index to the index whose strain rate represents it.
555 *
556 * The strain rate must be known one cell beyond the computed range, because the
557 * test-filter stencil reaches there. At an interior index the answer is the index
558 * itself. At the two layout-boundary planes it is not, and for opposite reasons.
559 *
560 * On a periodic axis, index 0 and index `m-1` are duplicates of the last and first
561 * interior cells. A central difference evaluated at index 0 straddles the wrap and
562 * returns nonsense, so the strain is evaluated instead at ghost index `-2`, which
563 * addresses the same physical cell from the interior side. Index `m+1` plays the
564 * same role at the other end. These are the ghost indices the periodic cell
565 * synchronization itself copies from, and the DMDA carries the three ghost layers
566 * they need whenever any axis is periodic.
567 *
568 * On a non-periodic axis the two planes are the solver's boundary layer, where a
569 * central difference would reach outside the domain. The nearest interior cell's
570 * strain is used instead, which is a zeroth-order extrapolation into a layer that
571 * only ever contributes to a filter average.
572 */
573static PetscInt LESStrainSampleIndex(PetscInt index, PetscInt extent, PetscBool periodic)
574{
575 if (index == 0) return periodic ? -2 : 1;
576 if (index == extent - 1) return periodic ? extent + 1 : extent - 2;
577 return index;
578}
579
580/**
581 * @brief Fills the strain-rate scratch fields across the computed range and its halo.
582 */
583static PetscErrorCode ComputeStrainRateField(UserCtx *user, Cmpnts ***ucat,
584 Vec strain_diagonal, Vec strain_offdiagonal,
585 Vec strain_magnitude)
586{
587 DM da = user->da, fda = user->fda;
588 DMDALocalInfo info;
590 PetscBool periodic[3];
591 Cmpnts ***diagonal = NULL, ***offdiagonal = NULL;
592 PetscReal ***magnitude = NULL;
593
594 PetscFunctionBeginUser;
596
597 info = user->info;
598 PetscCall(LESResolveDomain(user, &plan));
599 GetPeriodicAxes(user->simCtx, periodic);
600
601 PetscCall(DMDAVecGetArray(fda, strain_diagonal, &diagonal));
602 PetscCall(DMDAVecGetArray(fda, strain_offdiagonal, &offdiagonal));
603 PetscCall(DMDAVecGetArray(da, strain_magnitude, &magnitude));
604
605 // One cell beyond the computed range in every direction, because that is how far
606 // the 3x3x3 test-filter stencil reaches from the outermost computed cell.
607 for (PetscInt k = plan.start[2] - 1; k <= plan.end[2]; k++)
608 for (PetscInt j = plan.start[1] - 1; j <= plan.end[1]; j++)
609 for (PetscInt i = plan.start[0] - 1; i <= plan.end[0]; i++) {
610 const PetscInt si = LESStrainSampleIndex(i, info.mx, periodic[0]);
611 const PetscInt sj = LESStrainSampleIndex(j, info.my, periodic[1]);
612 const PetscInt sk = LESStrainSampleIndex(k, info.mz, periodic[2]);
613
614 Cmpnts dudx, dvdx, dwdx;
615 SymTensor strain;
616 PetscReal strain_abs;
617
618 PetscCall(ComputeVectorFieldDerivatives(user, si, sj, sk, ucat, &dudx, &dvdx, &dwdx));
619 PetscCall(StrainRateFromGradients(dudx, dvdx, dwdx, &strain, &strain_abs));
620
621 diagonal[k][j][i].x = strain.xx;
622 diagonal[k][j][i].y = strain.yy;
623 diagonal[k][j][i].z = strain.zz;
624 offdiagonal[k][j][i].x = strain.xy;
625 offdiagonal[k][j][i].y = strain.xz;
626 offdiagonal[k][j][i].z = strain.yz;
627 magnitude[k][j][i] = strain_abs;
628 }
629
630 PetscCall(DMDAVecRestoreArray(fda, strain_diagonal, &diagonal));
631 PetscCall(DMDAVecRestoreArray(fda, strain_offdiagonal, &offdiagonal));
632 PetscCall(DMDAVecRestoreArray(da, strain_magnitude, &magnitude));
633
635 PetscFunctionReturn(0);
636}
637
638/**
639 * @brief Rebuilds a symmetric strain tensor from its two scratch storage vectors.
640 */
641static inline SymTensor LESStrainAt(Cmpnts diagonal, Cmpnts offdiagonal)
642{
643 SymTensor s;
644
645 s.xx = diagonal.x;
646 s.yy = diagonal.y;
647 s.zz = diagonal.z;
648 s.xy = offdiagonal.x;
649 s.xz = offdiagonal.y;
650 s.yz = offdiagonal.z;
651 return s;
652}
653
654/*================================================================================*
655 * RUNTIME ENTRY POINTS *
656 *================================================================================*/
657
658/**
659 * @brief Implementation of \ref ComputeSmagorinskyConstant().
660 * @details Full API contract (arguments, ownership, side effects) is documented with
661 * the header declaration in `include/les.h`.
662 * @see ComputeSmagorinskyConstant()
663 */
665{
666 SimCtx *simCtx = user->simCtx;
667 const LESConfig *config = &simCtx->les_config;
668 DM da = user->da, fda = user->fda;
670 PetscBool average_direction[3];
671 PetscReal alpha;
672
673 Vec lStrainDiag, lStrainOff, lStrainAbs, lLM, lMM, lCsq;
674 Vec lWallMask = NULL;
675
676 Cmpnts ***ucat = NULL, ***strain_diag = NULL, ***strain_off = NULL;
677 Cmpnts ***csi = NULL, ***eta = NULL, ***zet = NULL;
678 PetscReal ***strain_abs = NULL, ***nvert = NULL, ***aj = NULL;
679 PetscReal ***lm = NULL, ***mm = NULL, ***csq = NULL, ***cs_out = NULL;
680
681 LESDiagnosticsState diagnostics = {0.0, 0.0, 0.0, 0.0, 0.0, PETSC_TRUE};
682
683 PetscFunctionBeginUser;
685
686 PetscCheck(simCtx->les == DYNAMIC_SMAGORINSKY, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE,
687 "The dynamic procedure runs only for the dynamic Smagorinsky model. The "
688 "constant model prescribes its coefficient from configuration and holds "
689 "no coefficient field.");
690
691 // The dynamic procedure needs a developed field to sample. Starting from rest it
692 // has nothing to measure, so the first steps run with no subgrid dissipation.
693 if (simCtx->step < 2 && simCtx->StartStep == 0) {
694 PetscCall(VecSet(user->CS, 0.0));
695 PetscCall(FinalizeSmagorinskyConstantField(user));
696 user->les_diagnostics = (LESDiagnosticsState){0.0, 0.0, 0.0, 0.0, 0.0, PETSC_FALSE};
698 "Holding the dynamic coefficient at zero for the opening steps (step=%" PetscInt_FMT ").\n",
699 simCtx->step);
701 PetscFunctionReturn(0);
702 }
703
704 PetscCall(LESResolveDomain(user, &plan));
705 PetscCall(ResolveLESAveragingDirections(user, average_direction));
706
707 // alpha is the squared ratio of the two filter widths and sets the relative weight
708 // of the test-scale and grid-scale terms in the model tensor. The widths are the
709 // cube roots of the three directional widths, and the configured ratio applies to
710 // each direction the kernel filters. The box filters all three, so alpha is the
711 // ratio squared. Simpson filters only i and k and leaves j at the grid width, so
712 // its widths differ by ratio^(2/3) and alpha is ratio^(4/3); squaring the ratio
713 // there halved the dynamic coefficient on HOM02 (0.091 against the box's 0.194).
715 alpha = PetscPowReal(config->test_filter_width_ratio, 4.0 / 3.0);
716 } else {
717 alpha = config->test_filter_width_ratio * config->test_filter_width_ratio;
718 }
719
720 PetscCall(VecDuplicate(user->lUcat, &lStrainDiag));
721 PetscCall(VecDuplicate(user->lUcat, &lStrainOff));
722 PetscCall(VecDuplicate(user->lNvert, &lStrainAbs));
723 PetscCall(VecDuplicate(user->lNvert, &lLM));
724 PetscCall(VecDuplicate(user->lNvert, &lMM));
725 PetscCall(VecDuplicate(user->lNvert, &lCsq));
726 PetscCall(VecSet(lStrainDiag, 0.0));
727 PetscCall(VecSet(lStrainOff, 0.0));
728 PetscCall(VecSet(lStrainAbs, 0.0));
729 PetscCall(VecSet(lLM, 0.0));
730 PetscCall(VecSet(lMM, 0.0));
731 PetscCall(VecSet(lCsq, 0.0));
732 /* Beside a modelled wall the first interior cell lies in an unresolved wall layer whose
733 wall flux is the model's stress, so it is kept out of the contraction sums. */
734 if (simCtx->wallfunction) {
735 PetscCall(VecDuplicate(user->lNvert, &lWallMask));
736 PetscCall(BuildWallModelExclusionMask(user, lWallMask));
737 }
738
739 PetscCall(DMDAVecGetArray(fda, user->lUcat, &ucat));
740
741 // --- 1. Strain rate everywhere the filter stencil will look -----------------
742 PetscCall(ComputeStrainRateField(user, ucat, lStrainDiag, lStrainOff, lStrainAbs));
743
744 PetscCall(DMDAVecGetArrayRead(fda, lStrainDiag, &strain_diag));
745 PetscCall(DMDAVecGetArrayRead(fda, lStrainOff, &strain_off));
746 PetscCall(DMDAVecGetArrayRead(da, lStrainAbs, &strain_abs));
747 PetscCall(DMDAVecGetArrayRead(fda, user->lCsi, &csi));
748 PetscCall(DMDAVecGetArrayRead(fda, user->lEta, &eta));
749 PetscCall(DMDAVecGetArrayRead(fda, user->lZet, &zet));
750 PetscCall(DMDAVecGetArrayRead(da, user->lNvert, &nvert));
751 PetscCall(DMDAVecGetArrayRead(da, user->lAj, &aj));
752 PetscCall(DMDAVecGetArray(da, lLM, &lm));
753 PetscCall(DMDAVecGetArray(da, lMM, &mm));
754
755 // --- 2. Germano contractions at every fluid cell ----------------------------
756 for (PetscInt k = plan.start[2]; k < plan.end[2]; k++)
757 for (PetscInt j = plan.start[1]; j < plan.end[1]; j++)
758 for (PetscInt i = plan.start[0]; i < plan.end[0]; i++) {
759 double velocity_x[3][3][3], velocity_y[3][3][3], velocity_z[3][3][3];
760 double strain_abs_stencil[3][3][3], weights[3][3][3];
761 SymTensor strain_stencil[3][3][3], product_stencil[3][3][3], velocity_product[3][3][3];
762 Cmpnts velocity_filtered;
763 SymTensor strain_filtered, product_filtered, velocity_product_filtered;
764 SymTensor leonard, model;
765 PetscReal strain_abs_filtered, delta, volume;
766
767 if (!SpatialTargetPlanMaskAllows(&plan, nvert[k][j][i])) {
768 lm[k][j][i] = 0.0;
769 mm[k][j][i] = 0.0;
770 continue;
771 }
772
773 // --- 2a. Gather the 3x3x3 stencil -------------------------------------
774 for (PetscInt r = -1; r <= 1; r++)
775 for (PetscInt q = -1; q <= 1; q++)
776 for (PetscInt p = -1; p <= 1; p++) {
777 const PetscInt R = r + 1, Q = q + 1, P = p + 1;
778 const PetscInt KK = k + r, JJ = j + q, II = i + p;
779 const SymTensor strain = LESStrainAt(strain_diag[KK][JJ][II], strain_off[KK][JJ][II]);
780 const PetscReal strain_abs_here = strain_abs[KK][JJ][II];
781
782 velocity_x[R][Q][P] = ucat[KK][JJ][II].x;
783 velocity_y[R][Q][P] = ucat[KK][JJ][II].y;
784 velocity_z[R][Q][P] = ucat[KK][JJ][II].z;
785
786 strain_stencil[R][Q][P] = strain;
787 strain_abs_stencil[R][Q][P] = strain_abs_here;
788
789 // The grid-scale model formed pointwise, before any test filtering. Test
790 // filtering this product is the term the model tensor cannot do without,
791 // and it is not the same as multiplying the two filtered factors.
792 product_stencil[R][Q][P] = SymTensorCombine(strain_abs_here, strain, 0.0, strain);
793
794 velocity_product[R][Q][P] = SymTensorSelfOuter(ucat[KK][JJ][II]);
795 weights[R][Q][P] = aj[KK][JJ][II];
796 }
797
798 // --- 2b. Test-filter every quantity the identity needs ----------------
799 velocity_filtered.x = ApplyLESTestFilter(config->test_filter_kernel, velocity_x, weights);
800 velocity_filtered.y = ApplyLESTestFilter(config->test_filter_kernel, velocity_y, weights);
801 velocity_filtered.z = ApplyLESTestFilter(config->test_filter_kernel, velocity_z, weights);
802 strain_abs_filtered = ApplyLESTestFilter(config->test_filter_kernel, strain_abs_stencil, weights);
803 PetscCall(ApplyLESTestFilterSymTensor(config->test_filter_kernel, strain_stencil, weights, &strain_filtered));
804 PetscCall(ApplyLESTestFilterSymTensor(config->test_filter_kernel, product_stencil, weights, &product_filtered));
805 PetscCall(ApplyLESTestFilterSymTensor(config->test_filter_kernel, velocity_product, weights, &velocity_product_filtered));
806
807 // --- 2c. Leonard stress and model tensor -------------------------------
808 leonard = LeonardStress(velocity_filtered, velocity_product_filtered);
809
810 PetscCall(ComputeCellFilterWidth(config->filter_width_model, aj[k][j][i],
811 csi[k][j][i], eta[k][j][i], zet[k][j][i], &delta));
812
813 model = GermanoModelTensor(delta, alpha, strain_abs_filtered, strain_filtered, product_filtered);
814
815 // --- 2d. Lilly's least-squares contraction -----------------------------
816 // Stored pre-multiplied by cell volume. The average that follows is over
817 // volume, not over cell count, so that a refined region does not dominate it
818 // merely by holding more cells; carrying the weight here keeps the shared
819 // averaging kernel free of any weighting policy of its own.
820 volume = 1.0 / aj[k][j][i];
821 lm[k][j][i] = volume * SymTensorContract(leonard, model);
822 mm[k][j][i] = volume * SymTensorNormSq(model);
823 }
824
825 PetscCall(DMDAVecRestoreArrayRead(fda, lStrainDiag, &strain_diag));
826 PetscCall(DMDAVecRestoreArrayRead(fda, lStrainOff, &strain_off));
827 PetscCall(DMDAVecRestoreArray(da, lLM, &lm));
828 PetscCall(DMDAVecRestoreArray(da, lMM, &mm));
829 PetscCall(DMDAVecRestoreArray(fda, user->lUcat, &ucat));
830
831 // --- 3. Average the two contractions, then divide ---------------------------
832 // Both sums are formed before the division. Averaging the pointwise quotients
833 // instead would not be the least-squares coefficient Lilly's closure defines.
834 PetscCall(PicurvSpatialRatioAverage(user, &plan, lLM, lMM, lWallMask, average_direction,
835 PetscObjectComm((PetscObject)da), lCsq, NULL));
836
837 // --- 4. Limit the coefficient and record what limiting cost -----------------
838 PetscCall(DMDAVecGetArrayRead(da, lLM, &lm));
839 PetscCall(DMDAVecGetArrayRead(da, lMM, &mm));
840 PetscCall(DMDAVecGetArrayRead(da, lCsq, &csq));
841 PetscCall(DMDAVecGetArray(da, user->CS, &cs_out));
842
843 for (PetscInt k = plan.start[2]; k < plan.end[2]; k++)
844 for (PetscInt j = plan.start[1]; j < plan.end[1]; j++)
845 for (PetscInt i = plan.start[0]; i < plan.end[0]; i++) {
846 PetscBool limited = PETSC_FALSE;
847 PetscReal weight, raw;
848
849 if (!SpatialTargetPlanMaskAllows(&plan, nvert[k][j][i])) {
850 cs_out[k][j][i] = 0.0;
851 continue;
852 }
853
854 weight = 1.0 / aj[k][j][i];
855 raw = csq[k][j][i];
856
857 cs_out[k][j][i] = ClipModelCoefficient(raw, config, &limited);
858
859 // The two contraction fields already carry the cell volume from the loop
860 // above, so they are summed as they stand rather than weighted twice.
861 diagnostics.contraction_lm += lm[k][j][i];
862 diagnostics.contraction_mm += mm[k][j][i];
863 diagnostics.fluid_volume += weight;
864 if (raw < 0.0) diagnostics.backscatter_volume += weight;
865 if (limited) diagnostics.limited_volume += weight;
866 }
867
868 PetscCall(DMDAVecRestoreArrayRead(da, lLM, &lm));
869 PetscCall(DMDAVecRestoreArrayRead(da, lMM, &mm));
870 PetscCall(DMDAVecRestoreArrayRead(da, lCsq, &csq));
871 PetscCall(DMDAVecRestoreArray(da, user->CS, &cs_out));
872 PetscCall(DMDAVecRestoreArrayRead(fda, user->lCsi, &csi));
873 PetscCall(DMDAVecRestoreArrayRead(fda, user->lEta, &eta));
874 PetscCall(DMDAVecRestoreArrayRead(fda, user->lZet, &zet));
875 PetscCall(DMDAVecRestoreArrayRead(da, user->lNvert, &nvert));
876 PetscCall(DMDAVecRestoreArrayRead(da, user->lAj, &aj));
877
878 PetscCall(VecDestroy(&lStrainDiag));
879 PetscCall(VecDestroy(&lStrainOff));
880 PetscCall(VecDestroy(&lStrainAbs));
881 PetscCall(VecDestroy(&lLM));
882 PetscCall(VecDestroy(&lMM));
883 PetscCall(VecDestroy(&lCsq));
884 if (lWallMask) PetscCall(VecDestroy(&lWallMask));
885
886 user->les_diagnostics = diagnostics;
887 PetscCall(FinalizeSmagorinskyConstantField(user));
888
890 PetscFunctionReturn(0);
891}
892
893/**
894 * @brief Implementation of \ref ComputeEddyViscosityLES().
895 * @details Full API contract (arguments, ownership, side effects) is documented with
896 * the header declaration in `include/les.h`.
897 * @see ComputeEddyViscosityLES()
898 */
899PetscErrorCode ComputeEddyViscosityLES(UserCtx *user)
900{
901 SimCtx *simCtx = user->simCtx;
902 const LESConfig *config = &simCtx->les_config;
903 DM da = user->da, fda = user->fda;
905 const PetscReal molecular_viscosity = 1.0 / simCtx->ren;
906
907 // The constant model's coefficient is a number from the configuration, so it needs
908 // no field, no ghost exchange, and no periodic synchronization.
909 const PetscBool coefficient_is_field = (PetscBool)(simCtx->les == DYNAMIC_SMAGORINSKY);
910 const PetscReal prescribed_coefficient = config->constant_cs * config->constant_cs;
911
912 Cmpnts ***ucat = NULL, ***csi = NULL, ***eta = NULL, ***zet = NULL;
913 PetscReal ***coefficient = NULL, ***nu_t = NULL, ***nvert = NULL, ***aj = NULL;
914
915 PetscFunctionBeginUser;
917
918 PetscCall(LESResolveDomain(user, &plan));
919
920 PetscCall(DMDAVecGetArrayRead(fda, user->lUcat, &ucat));
921 PetscCall(DMDAVecGetArrayRead(fda, user->lCsi, &csi));
922 PetscCall(DMDAVecGetArrayRead(fda, user->lEta, &eta));
923 PetscCall(DMDAVecGetArrayRead(fda, user->lZet, &zet));
924 PetscCall(DMDAVecGetArray(da, user->Nu_t, &nu_t));
925 PetscCall(DMDAVecGetArrayRead(da, user->lNvert, &nvert));
926 PetscCall(DMDAVecGetArrayRead(da, user->lAj, &aj));
927 if (coefficient_is_field) PetscCall(DMDAVecGetArrayRead(da, user->lCs, &coefficient));
928
929 for (PetscInt k = plan.start[2]; k < plan.end[2]; k++)
930 for (PetscInt j = plan.start[1]; j < plan.end[1]; j++)
931 for (PetscInt i = plan.start[0]; i < plan.end[0]; i++) {
932 Cmpnts dudx, dvdx, dwdx;
933 PetscReal strain_magnitude, delta, model_coefficient;
934
935 if (!SpatialTargetPlanMaskAllows(&plan, nvert[k][j][i])) {
936 nu_t[k][j][i] = 0.0;
937 continue;
938 }
939
940 PetscCall(ComputeVectorFieldDerivatives(user, i, j, k, (Cmpnts ***)ucat, &dudx, &dvdx, &dwdx));
941
942 if (simCtx->les == VREMAN) {
943 // Resolved per direction from the cell's own edges; no scalar width enters.
944 Cmpnts edges[3];
945 PetscCall(ComputeCellEdgeVectors(aj[k][j][i], csi[k][j][i], eta[k][j][i], zet[k][j][i], edges));
946 nu_t[k][j][i] = VremanEddyViscosity(dudx, dvdx, dwdx, edges, config->vreman_coefficient);
947 continue;
948 }
949
950 PetscCall(ComputeCellFilterWidth(config->filter_width_model, aj[k][j][i],
951 csi[k][j][i], eta[k][j][i], zet[k][j][i], &delta));
952 if (simCtx->les == WALE) {
953 nu_t[k][j][i] = WALEEddyViscosity(dudx, dvdx, dwdx, delta, config->wale_coefficient);
954 continue;
955 }
956
957 PetscCall(StrainRateFromGradients(dudx, dvdx, dwdx, NULL, &strain_magnitude));
958 model_coefficient = coefficient_is_field ? coefficient[k][j][i] : prescribed_coefficient;
959
960 nu_t[k][j][i] = EddyViscosityFromCoefficient(model_coefficient, delta, strain_magnitude,
961 molecular_viscosity, config->min_viscosity_ratio);
962 }
963
964 if (coefficient_is_field) PetscCall(DMDAVecRestoreArrayRead(da, user->lCs, &coefficient));
965 PetscCall(DMDAVecRestoreArrayRead(fda, user->lUcat, &ucat));
966 PetscCall(DMDAVecRestoreArrayRead(fda, user->lCsi, &csi));
967 PetscCall(DMDAVecRestoreArrayRead(fda, user->lEta, &eta));
968 PetscCall(DMDAVecRestoreArrayRead(fda, user->lZet, &zet));
969 PetscCall(DMDAVecRestoreArray(da, user->Nu_t, &nu_t));
970 PetscCall(DMDAVecRestoreArrayRead(da, user->lNvert, &nvert));
971 PetscCall(DMDAVecRestoreArrayRead(da, user->lAj, &aj));
972
973 {
974 const FieldId periodic_fields[] = {FIELD_ID_NU_T};
975
976 PetscCall(UpdateDummyCells(user, FIELD_ID_NU_T));
977 PetscCall(SynchronizePeriodicCellFields(user, 1, periodic_fields));
978 PetscCall(UpdateLocalGhosts(user, FIELD_ID_NU_T));
979 }
980
982 PetscFunctionReturn(0);
983}
984
985/**
986 * @brief Implementation of \ref LogLESDiagnostics().
987 * @details Full API contract (arguments, ownership, side effects) is documented with
988 * the header declaration in `include/les.h`.
989 * @see LogLESDiagnostics()
990 */
991PetscErrorCode LogLESDiagnostics(UserCtx *user)
992{
993 SimCtx *simCtx = user->simCtx;
994 const LESConfig *config = &simCtx->les_config;
995 DM da = user->da, fda = user->fda;
997 MPI_Comm comm;
998
999 const PetscBool dynamic = (PetscBool)(simCtx->les == DYNAMIC_SMAGORINSKY);
1000 // Vreman and WALE carry no Smagorinsky coefficient, so the coefficient columns are
1001 // written as nan rather than as a number that would read like a measured Cs.
1002 const PetscBool has_coefficient =
1003 (PetscBool)(simCtx->les == DYNAMIC_SMAGORINSKY || simCtx->les == CONSTANT_SMAGORINSKY);
1004
1005 // Index 0..4: fluid volume, coefficient first and second moments, nu_t volume sum,
1006 // subgrid-energy volume sum. Index 5..6: the pre-clip fractions. Reduced together
1007 // so the diagnostic costs one collective rather than seven.
1008 PetscReal local_sum[7] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
1009 PetscReal global_sum[7];
1010 PetscReal local_max[2] = {0.0, 0.0}, global_max[2];
1011 PetscReal local_min_coefficient = PETSC_MAX_REAL, global_min_coefficient;
1012 PetscReal contraction[2], global_contraction[2];
1013
1014 Cmpnts ***ucat = NULL, ***csi = NULL, ***eta = NULL, ***zet = NULL;
1015 PetscReal ***coefficient = NULL, ***nu_t = NULL, ***nvert = NULL, ***aj = NULL;
1016
1017 PetscFunctionBeginUser;
1019
1020 if (!config->diagnostics_enabled) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
1021 if (config->diagnostics_cadence <= 0) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
1022 if (simCtx->step % config->diagnostics_cadence != 0) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
1023
1024 PetscCall(LESResolveDomain(user, &plan));
1025 PetscCall(PetscObjectGetComm((PetscObject)da, &comm));
1026
1027 PetscCall(DMDAVecGetArrayRead(fda, user->lUcat, &ucat));
1028 PetscCall(DMDAVecGetArrayRead(fda, user->lCsi, &csi));
1029 PetscCall(DMDAVecGetArrayRead(fda, user->lEta, &eta));
1030 PetscCall(DMDAVecGetArrayRead(fda, user->lZet, &zet));
1031 PetscCall(DMDAVecGetArrayRead(da, user->lNu_t, &nu_t));
1032 PetscCall(DMDAVecGetArrayRead(da, user->lNvert, &nvert));
1033 PetscCall(DMDAVecGetArrayRead(da, user->lAj, &aj));
1034 if (dynamic) PetscCall(DMDAVecGetArrayRead(da, user->lCs, &coefficient));
1035
1036 for (PetscInt k = plan.start[2]; k < plan.end[2]; k++)
1037 for (PetscInt j = plan.start[1]; j < plan.end[1]; j++)
1038 for (PetscInt i = plan.start[0]; i < plan.end[0]; i++) {
1039 Cmpnts dudx, dvdx, dwdx;
1040 PetscReal strain_magnitude, delta, weight, value;
1041
1042 if (!SpatialTargetPlanMaskAllows(&plan, nvert[k][j][i])) continue;
1043
1044 weight = 1.0 / aj[k][j][i];
1045 value = dynamic ? coefficient[k][j][i]
1046 : config->constant_cs * config->constant_cs;
1047
1048 PetscCall(ComputeVectorFieldDerivatives(user, i, j, k, (Cmpnts ***)ucat, &dudx, &dvdx, &dwdx));
1049 PetscCall(StrainRateFromGradients(dudx, dvdx, dwdx, NULL, &strain_magnitude));
1050 PetscCall(ComputeCellFilterWidth(config->filter_width_model, aj[k][j][i],
1051 csi[k][j][i], eta[k][j][i], zet[k][j][i], &delta));
1052
1053 local_sum[0] += weight;
1054 local_sum[3] += weight * nu_t[k][j][i];
1055 local_sum[4] += weight * SubgridKineticEnergy(config->yoshizawa_ci, delta, strain_magnitude);
1056 local_max[1] = PetscMax(local_max[1], nu_t[k][j][i]);
1057 if (has_coefficient) {
1058 local_sum[1] += weight * value;
1059 local_sum[2] += weight * value * value;
1060 local_max[0] = PetscMax(local_max[0], value);
1061 local_min_coefficient = PetscMin(local_min_coefficient, value);
1062 }
1063 }
1064
1065 if (dynamic) PetscCall(DMDAVecRestoreArrayRead(da, user->lCs, &coefficient));
1066 PetscCall(DMDAVecRestoreArrayRead(fda, user->lUcat, &ucat));
1067 PetscCall(DMDAVecRestoreArrayRead(fda, user->lCsi, &csi));
1068 PetscCall(DMDAVecRestoreArrayRead(fda, user->lEta, &eta));
1069 PetscCall(DMDAVecRestoreArrayRead(fda, user->lZet, &zet));
1070 PetscCall(DMDAVecRestoreArrayRead(da, user->lNu_t, &nu_t));
1071 PetscCall(DMDAVecRestoreArrayRead(da, user->lNvert, &nvert));
1072 PetscCall(DMDAVecRestoreArrayRead(da, user->lAj, &aj));
1073
1074 local_sum[5] = user->les_diagnostics.valid ? user->les_diagnostics.backscatter_volume : 0.0;
1075 local_sum[6] = user->les_diagnostics.valid ? user->les_diagnostics.limited_volume : 0.0;
1076 contraction[0] = user->les_diagnostics.valid ? user->les_diagnostics.contraction_lm : 0.0;
1077 contraction[1] = user->les_diagnostics.valid ? user->les_diagnostics.contraction_mm : 0.0;
1078
1079 PetscCallMPI(MPI_Allreduce(local_sum, global_sum, 7, MPIU_REAL, MPI_SUM, comm));
1080 PetscCallMPI(MPI_Allreduce(local_max, global_max, 2, MPIU_REAL, MPI_MAX, comm));
1081 PetscCallMPI(MPI_Allreduce(&local_min_coefficient, &global_min_coefficient, 1, MPIU_REAL, MPI_MIN, comm));
1082 PetscCallMPI(MPI_Allreduce(contraction, global_contraction, 2, MPIU_REAL, MPI_SUM, comm));
1083
1084 if (simCtx->rank == 0) {
1085 const PetscReal volume = (global_sum[0] > 0.0) ? global_sum[0] : 1.0;
1086 const PetscReal mean = global_sum[1] / volume;
1087 const PetscReal mean_square = global_sum[2] / volume;
1088 const PetscReal variance = PetscMax(mean_square - mean * mean, 0.0);
1089 const PetscReal molecular = 1.0 / simCtx->ren;
1090 const PetscReal effective = (global_contraction[1] > LES_EPSILON)
1091 ? (global_contraction[0] / global_contraction[1]) : 0.0;
1092 FILE *file = NULL;
1093
1094 // Reported as Cs rather than as the stored coefficient, because that is the
1095 // number with a recognised value: near 0.16 for decaying isotropic turbulence.
1096 // A negative average means the box is backscattering on balance, and is written
1097 // as a negative Cs rather than hidden behind a square root.
1098 const PetscReal cs_effective = (effective >= 0.0) ? PetscSqrtReal(effective)
1099 : -PetscSqrtReal(-effective);
1100 const PetscReal cs_mean = (mean >= 0.0) ? PetscSqrtReal(mean) : -PetscSqrtReal(-mean);
1101
1102 PetscCall(PicurvOpenDiagnosticsCsv(simCtx, simCtx->analysis_dir, "les_coefficient.csv",
1103 "step,time,cs_effective,cs_mean,coefficient_mean,"
1104 "coefficient_rms,coefficient_min,coefficient_max,"
1105 "nu_t_mean,nu_t_max,nu_t_over_nu_mean,k_sgs_mean,"
1106 "backscatter_fraction,limited_fraction,physical_time", &file));
1107 PetscReal physical_time = 0.0;
1108 PetscCall(PicurvPhysicalTime(simCtx, simCtx->ti, &physical_time));
1109 fprintf(file,
1110 "%d,%.6e,%.6e,%.6e,%.6e,%.6e,%.6e,%.6e,%.6e,%.6e,%.6e,%.6e,%.6e,%.6e,%.6e\n",
1111 (int)simCtx->step, (double)simCtx->ti,
1112 // cs_effective is the Germano contraction ratio, which only the dynamic
1113 // procedure measures; the constant model's coefficient is cs_mean.
1114 dynamic ? (double)cs_effective : (double)NAN,
1115 has_coefficient ? (double)cs_mean : (double)NAN,
1116 has_coefficient ? (double)mean : (double)NAN,
1117 has_coefficient ? (double)PetscSqrtReal(variance) : (double)NAN,
1118 has_coefficient ? (double)global_min_coefficient : (double)NAN,
1119 has_coefficient ? (double)global_max[0] : (double)NAN,
1120 (double)(global_sum[3] / volume), (double)global_max[1],
1121 (double)(global_sum[3] / volume / molecular),
1122 (double)(global_sum[4] / volume),
1123 (double)(global_sum[5] / volume), (double)(global_sum[6] / volume),
1124 (double)physical_time);
1125 PetscCheck(fclose(file) == 0, PETSC_COMM_SELF, PETSC_ERR_FILE_WRITE,
1126 "Unable to close the LES diagnostics file.");
1127
1129 " LES coefficient: %s=%.4f, nu_t/nu (mean)=%.3e, backscatter=%.1f%%\n",
1130 dynamic ? "Cs_effective" : "Cs_mean",
1131 (double)(dynamic ? cs_effective : cs_mean),
1132 (double)(global_sum[3] / volume / molecular),
1133 (double)(100.0 * global_sum[5] / volume));
1134 }
1135
1137 PetscFunctionReturn(0);
1138}
PetscBool BoundaryFaceHasWallShear(const BoundaryFaceConfig *face)
Reports whether a boundary face is a wall that exerts shear on the flow.
Definition Boundaries.c:9
PetscErrorCode UpdateDummyCells(UserCtx *user, FieldId field_id)
Fills the dummy cells on the non-periodic faces of one cell-centred field.
PetscErrorCode SynchronizePeriodicCellFields(UserCtx *user, PetscInt num_fields, const FieldId field_ids[])
Synchronizes periodic endpoint cells for a list of cell-centered fields.
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 ApplyLESTestFilterSymTensor(LESTestFilterKernel kernel, SymTensor values[3][3][3], double weights[3][3][3], SymTensor *filtered)
Applies the test filter to all six components of a symmetric tensor.
Definition Filter.c:145
PetscErrorCode ComputeCellEdgeVectors(PetscReal ajc, Cmpnts csi, Cmpnts eta, Cmpnts zet, Cmpnts edges[3])
Computes a cell's edge vectors along its three grid directions.
Definition Metric.c:749
PetscErrorCode ComputeCellDirectionalExtents(PetscReal ajc, Cmpnts csi, Cmpnts eta, Cmpnts zet, double *l_xi, double *l_eta, double *l_zeta)
Computes a cell's extent along each of its own grid directions.
Definition Metric.c:717
FieldId
Compile-time identity for a catalogued Eulerian field.
@ FIELD_ID_NU_T
@ FIELD_ID_CS
PetscErrorCode PicurvPhysicalTime(const SimCtx *simCtx, PetscReal solver_time, PetscReal *physical)
Convert a solver time to physical seconds, t * L_ref / U_ref.
Definition io.c:2986
PetscReal SymTensorNormSq(SymTensor t)
Implementation of SymTensorNormSq().
Definition les.c:210
PetscErrorCode ComputeEddyViscosityLES(UserCtx *user)
Implementation of ComputeEddyViscosityLES().
Definition les.c:899
SymTensor SymTensorCombine(PetscReal a, SymTensor x, PetscReal b, SymTensor y)
Implementation of SymTensorCombine().
Definition les.c:151
SymTensor SymTensorSelfOuter(Cmpnts v)
Implementation of SymTensorSelfOuter().
Definition les.c:132
SymTensor SymTensorDeviator(SymTensor t)
Implementation of SymTensorDeviator().
Definition les.c:181
PetscReal SubgridKineticEnergy(PetscReal yoshizawa_ci, PetscReal delta, PetscReal strain_magnitude)
Implementation of SubgridKineticEnergy().
Definition les.c:544
PetscReal SymTensorTrace(SymTensor t)
Implementation of SymTensorTrace().
Definition les.c:170
PetscReal EddyViscosityFromCoefficient(PetscReal coefficient, PetscReal delta, PetscReal strain_magnitude, PetscReal molecular_viscosity, PetscReal min_viscosity_ratio)
Implementation of EddyViscosityFromCoefficient().
Definition les.c:448
SymTensor GermanoModelTensor(PetscReal delta, PetscReal alpha, PetscReal strain_magnitude_filtered, SymTensor strain_filtered, SymTensor strain_product_filtered)
Implementation of GermanoModelTensor().
Definition les.c:326
PetscReal ClipModelCoefficient(PetscReal coefficient, const LESConfig *config, PetscBool *limited)
Implementation of ClipModelCoefficient().
Definition les.c:419
PetscErrorCode ComputeCellFilterWidth(LESFilterWidthModel model, PetscReal aj, Cmpnts csi, Cmpnts eta, Cmpnts zet, PetscReal *delta)
Implementation of ComputeCellFilterWidth().
Definition les.c:252
PetscErrorCode StrainRateFromGradients(Cmpnts dudx, Cmpnts dvdx, Cmpnts dwdx, SymTensor *strain, PetscReal *magnitude)
Implementation of StrainRateFromGradients().
Definition les.c:225
PetscErrorCode ResolveLESAveragingDirections(UserCtx *user, PetscBool direction[3])
Implementation of ResolveLESAveragingDirections().
Definition les.c:360
SymTensor LeonardStress(Cmpnts velocity_filtered, SymTensor velocity_product_filtered)
Implementation of LeonardStress().
Definition les.c:313
PetscReal SymTensorContract(SymTensor a, SymTensor b)
Implementation of SymTensorContract().
Definition les.c:197
static SymTensor LESStrainAt(Cmpnts diagonal, Cmpnts offdiagonal)
Rebuilds a symmetric strain tensor from its two scratch storage vectors.
Definition les.c:641
static PetscErrorCode FinalizeSmagorinskyConstantField(UserCtx *user)
Synchronizes the completed Smagorinsky coefficient field.
Definition les.c:40
PetscErrorCode LogLESDiagnostics(UserCtx *user)
Implementation of LogLESDiagnostics().
Definition les.c:991
static PetscErrorCode ComputeStrainRateField(UserCtx *user, Cmpnts ***ucat, Vec strain_diagonal, Vec strain_offdiagonal, Vec strain_magnitude)
Fills the strain-rate scratch fields across the computed range and its halo.
Definition les.c:583
static PetscInt LESStrainSampleIndex(PetscInt index, PetscInt extent, PetscBool periodic)
Maps a cell index to the index whose strain rate represents it.
Definition les.c:573
PetscErrorCode ComputeSmagorinskyConstant(UserCtx *user)
Implementation of ComputeSmagorinskyConstant().
Definition les.c:664
static const double LES_EPSILON
Definition les.c:31
static PetscErrorCode LESResolveDomain(UserCtx *user, SpatialTargetPlan *plan)
Resolves the iteration domain the closure computes over.
Definition les.c:65
static PetscErrorCode BuildWallModelExclusionMask(UserCtx *user, Vec inclusion)
Marks the first cells beside a modelled wall, so the procedure skips them.
Definition les.c:91
PetscReal WALEEddyViscosity(Cmpnts dudx, Cmpnts dvdx, Cmpnts dwdx, PetscReal delta, PetscReal coefficient)
Implementation of WALEEddyViscosity().
Definition les.c:469
PetscReal VremanEddyViscosity(Cmpnts dudx, Cmpnts dvdx, Cmpnts dwdx, const Cmpnts edges[3], PetscReal coefficient)
Implementation of VremanEddyViscosity().
Definition les.c:506
#define GLOBAL
Scope for global logging across all processes.
Definition logging.h:46
static PetscErrorCode PicurvOpenDiagnosticsCsv(SimCtx *simCtx, const char *dir, const char *filename, const char *header, FILE **file)
Opens a per-step diagnostics CSV: PicurvOpenRunCsv() with the common settings.
Definition logging.h:1197
#define LOG_ALLOW(scope, level, fmt,...)
Logging macro that checks both the log level and whether the calling function is in the allowed-funct...
Definition logging.h:214
#define PROFILE_HELPER_BEGIN
Marks the beginning of a profiled helper: timed only when enabled by name.
Definition logging.h:1014
#define PROFILE_HELPER_END
Alias of PROFILE_FUNCTION_END for a function that began with PROFILE_HELPER_BEGIN.
Definition logging.h:1033
#define PROFILE_FUNCTION_END
Marks the end of a profiled code block.
Definition logging.h:1029
@ LOG_INFO
Informational messages about program execution.
Definition logging.h:31
@ LOG_DEBUG
Detailed debugging information.
Definition logging.h:32
#define PROFILE_FUNCTION_BEGIN
Marks the beginning of a profiled function: an always-on aggregate timer.
Definition logging.h:1000
PetscErrorCode ComputeVectorFieldDerivatives(UserCtx *user, PetscInt i, PetscInt j, PetscInt k, Cmpnts ***field_data, Cmpnts *dudx, Cmpnts *dvdx, Cmpnts *dwdx)
Computes the derivatives of a cell-centered vector field at a specific grid point.
Definition setup.c:3842
PetscErrorCode UpdateLocalGhosts(UserCtx *user, FieldId field_id)
Updates the local vector (including ghost points) from its corresponding global vector.
Definition setup.c:2593
static void GetPeriodicAxes(const SimCtx *simCtx, PetscBool periodic[3])
Which grid axes are periodic.
Definition setup.h:361
Spatial target resolution for the field-statistics pipeline.
PetscBool SpatialTargetPlanMaskAllows(const SpatialTargetPlan *plan, PetscReal nvert_value)
Reports whether a point passes the plan's mask.
@ PICURV_STATISTICS_MASK_FLUID
PetscInt end[3]
Exclusive end per dimension (i, j, k).
PetscInt start[3]
Inclusive start per dimension (i, j, k).
PetscErrorCode SpatialTargetPlanCreate(UserCtx *user, FieldId field_id, PicurvStatisticsMask mask, SpatialTargetPlan *plan)
Resolves the iteration domain for one field on one block.
PetscErrorCode PicurvSpatialRatioAverage(UserCtx *user, const SpatialTargetPlan *plan, Vec numerator, Vec denominator, Vec inclusion, const PetscBool average_direction[3], MPI_Comm comm, Vec ratio, PetscReal *reduced)
Averages two fields over a target domain and divides the results.
Resolved iteration domain for one field on one block.
@ DYNAMIC_SMAGORINSKY
Definition variables.h:586
@ VREMAN
Definition variables.h:587
@ WALE
Definition variables.h:588
@ CONSTANT_SMAGORINSKY
Definition variables.h:585
PetscReal yoshizawa_ci
Yoshizawa constant for the reported SGS kinetic energy.
Definition variables.h:677
PetscMPIInt rank
Definition variables.h:919
BoundaryFaceConfig boundary_faces[6]
Definition variables.h:1182
PetscReal yy
Definition variables.h:162
LESFilterWidthModel filter_width_model
How the grid filter width Delta is derived per cell.
Definition variables.h:669
PetscReal contraction_mm
Volume-weighted sum of M_ij M_ij over fluid cells.
Definition variables.h:691
LESTestFilterKernel test_filter_kernel
Discrete test-filter stencil.
Definition variables.h:670
Vec lNvert
Definition variables.h:1197
LESConfig les_config
Parameters of the LES closure selected by les.
Definition variables.h:1046
SimCtx * simCtx
Back-pointer to the master simulation context.
Definition variables.h:1160
PetscBool valid
Set once a dynamic update has populated this state.
Definition variables.h:695
PetscReal ren
Definition variables.h:965
@ LES_CLIP_CLIP_NEGATIVE
Definition variables.h:654
@ LES_CLIP_CLAMP
Definition variables.h:653
@ LES_CLIP_NONE
Definition variables.h:655
@ LES_TEST_FILTER_SIMPSON_IK
Definition variables.h:628
PetscReal max_cs
Ceiling on Cs under LES_CLIP_CLAMP.
Definition variables.h:675
LESClipMode clip_mode
Admissible range for the coefficient.
Definition variables.h:674
LESDiagnosticsState les_diagnostics
Pre-clipping statistics from the last dynamic update.
Definition variables.h:1260
PetscInt StartStep
Definition variables.h:926
PetscScalar x
Definition variables.h:145
PetscBool averaging_direction[3]
Averaged-over logical directions (xi, eta, zeta).
Definition variables.h:673
PetscReal wale_coefficient
Model constant C_w for WALE (Nicoud & Ducros 1999).
Definition variables.h:668
PetscReal limited_volume
Fluid volume whose coefficient the clip modified.
Definition variables.h:693
PetscReal fluid_volume
Total fluid volume sampled.
Definition variables.h:694
char analysis_dir[PETSC_MAX_PATH_LEN]
Definition variables.h:942
Vec lNu_t
Definition variables.h:1259
PetscReal contraction_lm
Volume-weighted sum of L_ij M_ij over fluid cells.
Definition variables.h:690
PetscScalar z
Definition variables.h:145
PetscInt diagnostics_cadence
Steps between diagnostic rows.
Definition variables.h:679
PetscReal min_viscosity_ratio
Enforce nu + nu_t >= ratio * nu.
Definition variables.h:676
PetscInt wallfunction
Enable wall functions on WALL faces.
Definition variables.h:1042
@ LES_AVERAGING_LOCAL
Definition variables.h:640
@ LES_AVERAGING_GLOBAL
Definition variables.h:642
@ LES_AVERAGING_HOMOGENEOUS
Definition variables.h:641
PetscBool diagnostics_enabled
Append per-step coefficient statistics to the run log directory.
Definition variables.h:678
PetscReal constant_cs
Fixed Cs for CONSTANT_SMAGORINSKY; unused by the dynamic model.
Definition variables.h:666
PetscReal test_filter_width_ratio
Test-to-grid ratio per filtered direction; alpha is its square for the box, ratio^(4/3) for Simpson.
Definition variables.h:671
PetscReal xx
Definition variables.h:162
LESAveragingMode averaging_mode
Averaging set for the Germano contractions.
Definition variables.h:672
PetscInt step
Definition variables.h:924
PetscReal vreman_coefficient
Model constant c for VREMAN (Vreman 2004: 2.5 Cs^2).
Definition variables.h:667
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
PetscReal yz
Definition variables.h:162
PetscReal zz
Definition variables.h:162
PetscReal backscatter_volume
Fluid volume whose raw coefficient was negative.
Definition variables.h:692
PetscReal ti
Definition variables.h:925
LESFilterWidthModel
Selects how a cell's grid filter width is derived from its metrics.
Definition variables.h:614
@ LES_FILTER_WIDTH_SCOTTI
Definition variables.h:618
@ LES_FILTER_WIDTH_GEOMETRIC_MEAN
Definition variables.h:616
@ LES_FILTER_WIDTH_CUBE_ROOT_VOLUME
Definition variables.h:615
@ LES_FILTER_WIDTH_MAX_EDGE
Definition variables.h:617
PetscReal xz
Definition variables.h:162
PetscReal xy
Definition variables.h:162
BCFace
Identifies the six logical faces of a structured computational block.
Definition variables.h:308
@ BC_FACE_NEG_X
Definition variables.h:309
@ BC_FACE_POS_Z
Definition variables.h:311
@ BC_FACE_POS_Y
Definition variables.h:310
@ BC_FACE_NEG_Z
Definition variables.h:311
@ BC_FACE_POS_X
Definition variables.h:309
@ BC_FACE_NEG_Y
Definition variables.h:310
A 3D point or vector with PetscScalar components.
Definition variables.h:144
Every user-selectable parameter of the LES closure.
Definition variables.h:664
Pre-clipping volume statistics captured by one dynamic-coefficient update.
Definition variables.h:689
The master context for the entire simulation.
Definition variables.h:916
A symmetric second-order tensor stored by its six independent components.
Definition variables.h:161
User-defined context containing data specific to a single computational grid level.
Definition variables.h:1157
double nu_t(double yplus)
Computes turbulent eddy viscosity ratio (ν_t / ν)