PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
BC_Handlers.c
Go to the documentation of this file.
1#include "BC_Handlers.h" // The header that declares this file's "constructor" functions
2#include "expression.h"
3#include "Metric.h"
4
5
6//================================================================================
7// VALIDATORS
8//================================================================================
9
10
11/**
12 * @brief Implementation of \ref Validate_DrivenFlowConfiguration().
13 * @see Validate_DrivenFlowConfiguration()
14 */
16{
17 PetscFunctionBeginUser;
19
20 // --- CHECK 1: Detect if a driven flow is active. ---
21 PetscBool is_driven_flow_active = PETSC_FALSE;
22 char driven_direction = ' ';
23 const char* first_driven_face_name = "";
24
25 for (int i = 0; i < 6; i++) {
26 BCHandlerType handler_type = user->boundary_faces[i].handler_type;
27 if (handler_type == BC_HANDLER_PERIODIC_DRIVEN_CONSTANT_FLUX ||
29 {
30 is_driven_flow_active = PETSC_TRUE;
31 first_driven_face_name = BCFaceToString((BCFace)i);
32
33 if (i <= 1) driven_direction = 'X';
34 else if (i <= 3) driven_direction = 'Y';
35 else driven_direction = 'Z';
36
37 break; // Exit loop once we've confirmed it's active and found the direction.
38 }
39 }
40
41 // If no driven flow handler is found, validation for this rule set is complete.
42 if (!is_driven_flow_active) {
44 PetscFunctionReturn(0);
45 }
46
47 LOG_ALLOW(GLOBAL, LOG_DEBUG, " - Driven Flow Handler detected on face %s. Applying driven flow validation rules...\n", first_driven_face_name);
48
49 // --- CHECK 2: Ensure no conflicting BCs (Inlet/Outlet/Far-field) are present. ---
50 LOG_ALLOW(GLOBAL, LOG_DEBUG, " - Checking for incompatible Inlet/Outlet/Far-field BCs...\n");
51 for (int i = 0; i < 6; i++) {
52 BCType math_type = user->boundary_faces[i].mathematical_type;
53 if (math_type == INLET || math_type == OUTLET || math_type == FARFIELD) {
54 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT,
55 "Configuration Error: A DRIVEN flow handler is active, which is incompatible with the %s boundary condition found on face %s.",
56 BCTypeToString(math_type), BCFaceToString((BCFace)i));
57 }
58 }
59 LOG_ALLOW(GLOBAL, LOG_DEBUG, " ... No conflicting BC types found. OK.\n");
60
61 // --- CHECK 3: Ensure both ends of the driven direction have identical, valid setups. ---
62 LOG_ALLOW(GLOBAL, LOG_DEBUG, " - Validating symmetry and mathematical types for the '%c' direction...\n", driven_direction);
63
64 PetscInt neg_face_idx = 0, pos_face_idx = 0;
65 if (driven_direction == 'X') {
66 neg_face_idx = BC_FACE_NEG_X; pos_face_idx = BC_FACE_POS_X;
67 } else if (driven_direction == 'Y') {
68 neg_face_idx = BC_FACE_NEG_Y; pos_face_idx = BC_FACE_POS_Y;
69 } else { // 'Z'
70 neg_face_idx = BC_FACE_NEG_Z; pos_face_idx = BC_FACE_POS_Z;
71 }
72
73 BoundaryFaceConfig *neg_face_cfg = &user->boundary_faces[neg_face_idx];
74 BoundaryFaceConfig *pos_face_cfg = &user->boundary_faces[pos_face_idx];
75
76 // Rule 3a: Both faces must be PERIODIC.
77 if (neg_face_cfg->mathematical_type != PERIODIC || pos_face_cfg->mathematical_type != PERIODIC) {
78 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT,
79 "Configuration Error: For a driven flow in the '%c' direction, both the %s and %s faces must be of mathematical_type PERIODIC.",
80 driven_direction, BCFaceToString((BCFace)neg_face_idx), BCFaceToString((BCFace)pos_face_idx));
81 }
82
83 // Rule 3b: Both faces must use the exact same handler type.
84 if (neg_face_cfg->handler_type != pos_face_cfg->handler_type) {
85 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT,
86 "Configuration Error: The DRIVEN handlers on the %s and %s faces of the '%c' direction do not match. Both must be the same type (e.g., both CONSTANT_FLUX).",
87 BCFaceToString((BCFace)neg_face_idx), BCFaceToString((BCFace)pos_face_idx), driven_direction);
88 }
89
90 LOG_ALLOW(GLOBAL, LOG_DEBUG, " ... Symmetry and mathematical types are valid. OK.\n");
91
93 PetscFunctionReturn(0);
94}
95
96/** @brief Cartesian boundary velocity one handler prescribes at one boundary face slot. */
98 PetscInt i, PetscInt j, PetscInt k,
99 Cmpnts metric, PetscReal sign, Cmpnts interior);
100
101static PetscErrorCode ApplyFaceBoundaryVelocity(BoundaryCondition *self, BCContext *ctx,
103
104//================================================================================
105//
106// HANDLER IMPLEMENTATION: NO-SLIP WALL
107// (Corresponds to BC_HANDLER_WALL_NOSLIP)
108//
109// This handler implements a stationary, impenetrable wall where the fluid
110// velocity is zero (no-slip condition).
111//
112//================================================================================
113
114// --- FORWARD DECLARATIONS ---
115static PetscErrorCode Apply_WallNoSlip(BoundaryCondition *self, BCContext *ctx);
116
117/**
118 * @brief Implementation of \ref Create_WallNoSlip().
119 * @details Full API contract (arguments, ownership, side effects) is documented with
120 * the header declaration in `include/BC_Handlers.h`.
121 * @see Create_WallNoSlip()
122 */
124{
125 PetscFunctionBeginUser;
127
128 PetscCheck(bc, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "BoundaryCondition is NULL");
129
130 // ✅ Set priority
132
133 // Assign function pointers
134 bc->Initialize = NULL;
135 bc->PreStep = NULL;
137 bc->PostStep = NULL;
138 bc->UpdateUbcs = NULL;
139 bc->Destroy = NULL;
140
141 // No private data needed for this simple handler
142 bc->data = NULL;
143
145 PetscFunctionReturn(0);
146}
147
148/**
149 * @brief The no-slip wall's boundary velocity: the wall's own, which is at rest.
150 */
152 PetscInt i, PetscInt j, PetscInt k,
153 Cmpnts metric, PetscReal sign, Cmpnts interior)
154{
155 const Cmpnts rest = {0.0, 0.0, 0.0};
156
157 (void)self; (void)face_id; (void)i; (void)j; (void)k; (void)metric; (void)sign; (void)interior;
158 return rest;
159}
160
161/**
162 * @brief Apply no-slip velocity values to wall-adjacent cells for this boundary condition.
163 * @details A zero boundary velocity also closes the face, since its flux is the
164 * velocity's product with the face metric.
165 */
166static PetscErrorCode Apply_WallNoSlip(BoundaryCondition *self, BCContext *ctx)
167{
168 PetscFunctionBeginUser;
170 LOG_ALLOW(LOCAL, LOG_DEBUG, "Apply_WallNoSlip: Applying to Face %d (%s).\n",
171 ctx->face_id, BCFaceToString(ctx->face_id));
172 PetscCall(ApplyFaceBoundaryVelocity(self, ctx, WallNoSlipVelocity));
174 PetscFunctionReturn(0);
175}
176
177//================================================================================
178//
179// HANDLER IMPLEMENTATION: FREE-SLIP WALL
180// (Corresponds to BC_HANDLER_WALL_FREE_SLIP)
181//
182// An impenetrable wall that exerts no shear: the normal velocity vanishes and the
183// tangential velocity has zero normal gradient. It is also a plane of symmetry,
184// the same condition read as the mirror image of the flow beyond it, which is why
185// PICurv offers no separate symmetry boundary type.
186//
187//================================================================================
188
189static PetscErrorCode Apply_WallFreeSlip(BoundaryCondition *self, BCContext *ctx);
190
191/**
192 * @brief Implementation of \ref Create_WallFreeSlip().
193 * @details Full API contract (arguments, ownership, side effects) is documented with
194 * the header declaration in `include/BC_Handlers.h`.
195 * @see Create_WallFreeSlip()
196 */
198{
199 PetscFunctionBeginUser;
201 PetscCheck(bc, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "BoundaryCondition is NULL");
203 bc->Initialize = NULL;
204 bc->PreStep = NULL;
206 bc->PostStep = NULL;
207 /* The boundary value follows the adjacent velocity, so it is refreshed whenever
208 * the velocity is: on every boundary pass and after each projection. */
210 bc->needs_repeat_pass = PETSC_TRUE; // Copies the adjacent Ucat, which the pass refreshes after it
211 bc->Destroy = NULL;
212 bc->data = NULL;
214 PetscFunctionReturn(0);
215}
216
217
218/**
219 * @brief The free-slip wall's boundary velocity: the adjacent velocity, less its normal part.
220 * @details Removing the component along the face metric leaves a velocity tangent to the
221 * face, so the face flux vanishes; placing it as the boundary value makes the
222 * dummy cell the mirror image of the interior one, reversing the normal velocity
223 * and keeping the tangential one, which is zero normal gradient. On a curvilinear
224 * grid the metric is the face's own normal, so the construction holds there too.
225 */
226static inline Cmpnts WallFreeSlipVelocity(const BoundaryCondition *self, BCFace face_id,
227 PetscInt i, PetscInt j, PetscInt k,
228 Cmpnts metric, PetscReal sign, Cmpnts interior)
229{
230 (void)self; (void)face_id; (void)i; (void)j; (void)k; (void)sign;
231 return RemoveFaceNormalComponent(interior, metric);
232}
233
234/**
235 * @brief Apply free-slip boundary values to wall-adjacent cells for this boundary condition.
236 */
237static PetscErrorCode Apply_WallFreeSlip(BoundaryCondition *self, BCContext *ctx)
238{
239 PetscFunctionBeginUser;
241 PetscCall(ApplyFaceBoundaryVelocity(self, ctx, WallFreeSlipVelocity));
243 PetscFunctionReturn(0);
244}
245
246//================================================================================
247//
248// HANDLER IMPLEMENTATION: PRESCRIBED VELOCITY INLET
249// (Corresponds to BC_HANDLER_INLET_PRESCRIBED_VELOCITY)
250//
251// The velocity is a configured source (expression.h) evaluated at the centre of every
252// inlet face slot, a PICSLICE file of one value per slot (a normal speed, or a Cartesian
253// velocity), in one frame or a recording of frames interpolated in time, or such a file with
254// expressions in its frame added to it. It is optionally rescaled so the face's mean normal
255// speed or flow rate follows a target, the expressions alone when they add to a file, and
256// synthetic fluctuations may be added after the rescaling. The slots are gathered at the
257// first boundary pass, once the metrics exist; the velocity is re-evaluated once per step
258// when it depends on t, and the rescaling is recomputed once per step when the source, the
259// file or the target depends on t.
260//
261//================================================================================
262
263static PetscErrorCode Initialize_InletPrescribedVelocity(BoundaryCondition *self, BCContext *ctx);
264static PetscErrorCode PreStep_InletPrescribedVelocity(BoundaryCondition *self, BCContext *ctx,
265 PetscReal *in, PetscReal *out);
266static PetscErrorCode Apply_InletVelocity(BoundaryCondition *self, BCContext *ctx);
267static PetscErrorCode PostStep_InletFlux(BoundaryCondition *self, BCContext *ctx,
268 PetscReal *in, PetscReal *out);
269static PetscErrorCode Apply_WallMoving(BoundaryCondition *self, BCContext *ctx);
270static PetscErrorCode Destroy_InletPrescribedVelocity(BoundaryCondition *self);
271
272/**
273 * @brief Private data of the prescribed-velocity inlet: a compiled source or a PICSLICE file,
274 * the values of the source's variables at each face slot this rank owns, and the
275 * velocity they last gave.
276 */
277typedef struct {
278 PicurvVelocitySource source; /* Normal frame with no expressions for a file alone. */
279 char *source_file; /* Staged PICSLICE of solver-unit velocities, or NULL. */
280 Cmpnts *profile; /* The file's velocity per slot when expressions add to it, or NULL. */
281 FILE *file; /* The open PICSLICE, while later frames remain to be read. */
282 fpos_t first_frame; /* Where the file's values begin. */
283 PetscInt frames; /* Frames in the file; more than one varies in time. */
284 PetscInt components; /* 1, a normal speed, or 3, a Cartesian velocity. */
285 PetscInt next_frame; /* The frame the file's position is at. */
286 PetscInt file_n[2]; /* The file's slice dimensions. */
287 PetscReal interval; /* Time between frames [s]. */
288 PetscBool repeat; /* Past the last frame, return to the first. */
289 PetscReal *file_values; /* One frame as the file stores it. */
290 Cmpnts *bracket[2]; /* This rank's slots of the frames around the step's time. */
291 PetscInt bracket_frame[2]; /* Which frames those are, or -1. */
292 PicurvSourceFaceSlots slots; /* What the source reads at each owned slot; t is refreshed. */
293 Cmpnts *velocity; /* Solver-unit velocity per slot, the speed in x for the normal frame. */
294 PetscReal factor; /* Bulk-velocity rescaling of `velocity`. */
295 PetscInt evaluated_step; /* Step the cache was last refreshed for. */
296 PetscBool built;
297 /* Synthetic fluctuations (digital filter, Xie & Castro 2008), added after `factor`. */
298 PetscBool fluctuate;
299 PicurvVelocitySource stress[2]; /* Reynolds stresses [m^2/s^2]: (uu, vv, ww), then (uv, uw, vw). */
300 PetscReal fluct_length[2]; /* Integral lengths along the tangential axes, solver units. */
301 PetscReal fluct_time; /* Integral time, solver units. */
302 PetscInt half[2]; /* Filter half-widths along the tangential axes, in cells. */
303 PetscReal *kernel[2]; /* Filter weights, 2 half + 1 per axis, unit sum of squares. */
304 PetscReal (*lund)[6]; /* Per slot, the stresses' Cholesky factor in solver units: a11 a21 a22 a31 a32 a33. */
305 Cmpnts *fluct; /* Per slot, this step's fluctuation in solver units. */
306 PetscBool fluct_started; /* The filter has a previous state to continue from. */
308
309/** @brief Index of the owned slot (i, j, k) in a prescribed-velocity inlet's per-slot arrays. */
310static inline PetscInt PrescribedSlot(const InletPrescribedVelocityData *data, PetscInt i, PetscInt j, PetscInt k)
311{
312 const PetscInt idx[3] = {i, j, k};
313 const PicurvSourceFaceSlots *slots = &data->slots;
314 return (idx[slots->elements.a] - slots->elements.lo[0]) + slots->elements.n[0] * (idx[slots->elements.b] - slots->elements.lo[1]);
315}
316
317/**
318 * @brief Implementation of \ref Create_InletPrescribedVelocity().
319 * @details Full API contract (arguments, ownership, side effects) is documented with
320 * the header declaration in `include/BC_Handlers.h`.
321 * @see Create_InletPrescribedVelocity()
322 */
324{
325 InletPrescribedVelocityData *data = NULL;
326
327 PetscFunctionBeginUser;
329 PetscCheck(bc, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "BoundaryCondition is NULL");
330 PetscCall(PetscNew(&data));
331 bc->data = (void*)data;
337 bc->UpdateUbcs = NULL;
340 PetscFunctionReturn(0);
341}
342
343/**
344 * @brief Implementation of \ref Create_WallMoving().
345 * @see Create_WallMoving()
346 */
348{
349 PetscFunctionBeginUser;
351 PetscCall(Create_InletPrescribedVelocity(bc));
354 bc->PostStep = NULL;
356 PetscFunctionReturn(0);
357}
358
359/**
360 * @brief Adds the inlet face's applied flux, the sum of its normal Ucont, to the inflow.
361 */
362static PetscErrorCode PostStep_InletFlux(BoundaryCondition *self, BCContext *ctx,
363 PetscReal *local_inflow_contribution,
364 PetscReal *local_outflow_contribution)
365{
366 PetscErrorCode ierr;
367 UserCtx* user = ctx->user;
368 BCFace face_id = ctx->face_id;
369 PetscBool can_service;
370
371 (void)self;
372 (void)local_outflow_contribution;
373
374 PetscFunctionBeginUser;
376
377 DMDALocalInfo *info = &user->info;
378 Cmpnts ***ucont;
379
380 PetscInt IM_nodes_global, JM_nodes_global,KM_nodes_global;
381
382 IM_nodes_global = user->IM;
383 JM_nodes_global = user->JM;
384 KM_nodes_global = user->KM;
385
386 ierr = CanRankServiceFace(info,IM_nodes_global,JM_nodes_global,KM_nodes_global,face_id,&can_service); CHKERRQ(ierr);
387
388
389 if (!can_service) { PROFILE_HELPER_END; PetscFunctionReturn(0); }
390
391 ierr = DMDAVecGetArrayRead(user->fda, user->Ucont, (const Cmpnts***)&ucont); CHKERRQ(ierr);
392
393 PetscReal local_flux = 0.0;
394
395 PetscInt xs = info->xs, xe = info->xs + info->xm;
396 PetscInt ys = info->ys, ye = info->ys + info->ym;
397 PetscInt zs = info->zs, ze = info->zs + info->zm;
398 PetscInt mx = info->mx, my = info->my, mz = info->mz;
399
400 PetscInt lxs = xs, lxe = xe, lys = ys, lye = ye, lzs = zs, lze = ze;
401 if (xs == 0) lxs = xs + 1;
402 if (xe == mx) lxe = xe - 1;
403 if (ys == 0) lys = ys + 1;
404 if (ye == my) lye = ye - 1;
405 if (zs == 0) lzs = zs + 1;
406 if (ze == mz) lze = ze - 1;
407
408 // Sum ucont components
409 switch (face_id) {
410 case BC_FACE_NEG_X:
411 case BC_FACE_POS_X: {
412 PetscInt i = (face_id == BC_FACE_NEG_X) ? xs : mx - 2;
413 for (PetscInt k = lzs; k < lze; k++) {
414 for (PetscInt j = lys; j < lye; j++) {
415 local_flux += ucont[k][j][i].x;
416 }
417 }
418 } break;
419
420 case BC_FACE_NEG_Y:
421 case BC_FACE_POS_Y: {
422 PetscInt j = (face_id == BC_FACE_NEG_Y) ? ys : my - 2;
423 for (PetscInt k = lzs; k < lze; k++) {
424 for (PetscInt i = lxs; i < lxe; i++) {
425 local_flux += ucont[k][j][i].y;
426 }
427 }
428 } break;
429
430 case BC_FACE_NEG_Z:
431 case BC_FACE_POS_Z: {
432 PetscInt k = (face_id == BC_FACE_NEG_Z) ? zs : mz - 2;
433 for (PetscInt j = lys; j < lye; j++) {
434 for (PetscInt i = lxs; i < lxe; i++) {
435 local_flux += ucont[k][j][i].z;
436 }
437 }
438 } break;
439 }
440
441 ierr = DMDAVecRestoreArrayRead(user->fda, user->Ucont, (const Cmpnts***)&ucont); CHKERRQ(ierr);
442
443 *local_inflow_contribution += local_flux;
444
445 LOG_ALLOW(LOCAL, LOG_DEBUG, "PostStep_InletFlux: Face %d, flux = %.6e\n",
446 face_id, local_flux);
447
449 PetscFunctionReturn(0);
450}
451
452/**
453 * @brief Computes the expected PICSLICE dimensions for an inlet face.
454 *
455 * @param user User context containing global grid node counts.
456 * @param face_id Boundary face whose tangential profile dimensions are requested.
457 * @param[out] n1 First PICSLICE dimension in handler storage order.
458 * @param[out] n2 Second PICSLICE dimension in handler storage order.
459 * @return PetscErrorCode 0 on success, or a PETSc error for unsupported faces or invalid dimensions.
460 */
461static PetscErrorCode GetProfileFileExpectedDims(UserCtx *user, BCFace face_id,
462 PetscInt *n1, PetscInt *n2)
463{
464 PetscFunctionBeginUser;
466 switch (face_id) {
467 case BC_FACE_NEG_X:
468 case BC_FACE_POS_X:
469 *n1 = user->KM - 1;
470 *n2 = user->JM - 1;
471 break;
472 case BC_FACE_NEG_Y:
473 case BC_FACE_POS_Y:
474 *n1 = user->KM - 1;
475 *n2 = user->IM - 1;
476 break;
477 case BC_FACE_NEG_Z:
478 case BC_FACE_POS_Z:
479 *n1 = user->JM - 1;
480 *n2 = user->IM - 1;
481 break;
482 default:
483 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE,
484 "Unsupported face id %d for inlet profile dimensions.", face_id);
485 }
486 if (*n1 <= 0 || *n2 <= 0) {
487 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG,
488 "Invalid inlet profile dimensions (%" PetscInt_FMT ", %" PetscInt_FMT ") for grid (%" PetscInt_FMT ", %" PetscInt_FMT ", %" PetscInt_FMT ").",
489 *n1, *n2, user->IM, user->JM, user->KM);
490 }
492 PetscFunctionReturn(0);
493}
494
495/**
496 * @brief Opens a canonical PICSLICE file and reads its header.
497 *
498 * @details The file holds magic token `PICSLICE`, a frame count, then a line with the slice
499 * dimensions, optionally the components per slot (1, a normal speed, the default, or 3,
500 * a Cartesian velocity) and, with several frames, the time between them. Frames follow.
501 *
502 * @param data Handler data; `file`, `first_frame`, `frames`, `components`, `interval` and
503 * `file_n` are set.
504 * @param expected_n1 Expected first slice dimension.
505 * @param expected_n2 Expected second slice dimension.
506 * @return PetscErrorCode 0 on success, or a PETSc file/validation error on malformed input.
507 */
508static PetscErrorCode OpenPicSlice(InletPrescribedVelocityData *data, PetscInt expected_n1, PetscInt expected_n2)
509{
510 const char *source_file = data->source_file;
511 FILE *fd = NULL;
512 char magic[32] = {0}, line[256] = {0};
513 PetscInt frame_count = 0, n1 = 0, n2 = 0;
514 PetscInt components = 1;
515 double interval = 0.0;
516
517 PetscFunctionBeginUser;
519 fd = fopen(source_file, "r");
520 if (!fd) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_OPEN,
521 "Cannot open PICSLICE inlet profile file: %s", source_file);
522
523 if (fscanf(fd, "%31s", magic) != 1 || strcmp(magic, "PICSLICE") != 0) {
524 fclose(fd);
525 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_READ,
526 "PICSLICE inlet profile file %s must begin with PICSLICE header.", source_file);
527 }
528 if (fscanf(fd, "%" PetscInt_FMT " ", &frame_count) != 1) {
529 fclose(fd);
530 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_READ,
531 "PICSLICE inlet profile file %s missing frame count.", source_file);
532 }
533 if (!fgets(line, sizeof(line), fd) ||
534 sscanf(line, "%" PetscInt_FMT " %" PetscInt_FMT " %" PetscInt_FMT " %le", &n1, &n2, &components, &interval) < 2) {
535 fclose(fd);
536 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_READ,
537 "PICSLICE inlet profile file %s missing slice dimensions.", source_file);
538 }
539 if (n1 != expected_n1 || n2 != expected_n2) {
540 fclose(fd);
541 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_UNEXPECTED,
542 "PICSLICE inlet profile dimensions mismatch for %s: expected (%" PetscInt_FMT ", %" PetscInt_FMT "), found (%" PetscInt_FMT ", %" PetscInt_FMT ").",
543 source_file, expected_n1, expected_n2, n1, n2);
544 }
545 if (frame_count < 1 || (components != 1 && components != 3) || (frame_count > 1 && !(interval > 0.0))) {
546 fclose(fd);
547 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_UNEXPECTED,
548 "PICSLICE inlet profile file %s has %" PetscInt_FMT " frames of %" PetscInt_FMT " components, %g apart; "
549 "it needs at least one frame, 1 or 3 components, and a positive interval between several frames.",
550 source_file, frame_count, components, interval);
551 }
552 if (fgetpos(fd, &data->first_frame) != 0) {
553 fclose(fd);
554 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_READ, "Cannot record a position in %s.", source_file);
555 }
556 data->file = fd;
557 data->frames = frame_count;
558 data->components = components;
559 data->interval = interval;
560 data->file_n[0] = n1;
561 data->file_n[1] = n2;
563 PetscFunctionReturn(0);
564}
565
566/**
567 * @brief Reads the frame at the file's position into `file_values`, validating every value: finite,
568 * and a normal speed nonnegative. After the last frame the file must end.
569 * @param data Handler data with an open file.
570 * @return PetscErrorCode 0 on success, or a PETSc file/validation error on malformed input.
571 */
573{
574 const PetscInt count = data->file_n[0] * data->file_n[1] * data->components;
575
576 PetscFunctionBeginUser;
578 for (PetscInt idx = 0; idx < count; idx++) {
579 PetscReal value = 0.0;
580 if (fscanf(data->file, "%le", &value) != 1) {
581 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_READ,
582 "PICSLICE inlet profile file %s ended early in frame %" PetscInt_FMT ": expected %" PetscInt_FMT " values.",
583 data->source_file, data->next_frame, count);
584 }
585 if (PetscIsInfOrNanReal(value) || (data->components == 1 && value < 0.0)) {
586 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_UNEXPECTED,
587 "PICSLICE inlet profile file %s contains invalid speed %.6e at flat index %" PetscInt_FMT ".",
588 data->source_file, (double)value, idx);
589 }
590 data->file_values[idx] = value;
591 }
592 data->next_frame++;
593 if (data->next_frame == data->frames) {
594 char extra[64];
595 if (fscanf(data->file, "%63s", extra) == 1) {
596 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_UNEXPECTED,
597 "PICSLICE inlet profile file %s has extra token after %" PetscInt_FMT " frames of %" PetscInt_FMT " values: %s",
598 data->source_file, data->frames, count, extra);
599 }
600 }
602 PetscFunctionReturn(0);
603}
604
605/**
606 * @brief Prescribed velocity at one inlet face slot, as a Cartesian vector.
607 * @details A normal-frame source stores its speed in `.x`; it is lifted onto the signed unit
608 * face normal. Other frames store the Cartesian velocity. Both carry the bulk factor.
609 */
611 BCFace face_id,
612 PetscInt i, PetscInt j, PetscInt k,
613 Cmpnts metric, PetscReal sign, Cmpnts interior)
614{
615 (void)interior;
617 Cmpnts velocity = {0.0, 0.0, 0.0};
618 if (!data->built) return velocity;
619 const Cmpnts v = data->velocity[PrescribedSlot(data, i, j, k)];
620 const Cmpnts staged = data->profile ? data->profile[PrescribedSlot(data, i, j, k)] : velocity;
621 /* Fluctuations follow the bulk factor, which rescales only the mean. */
622 const Cmpnts fluct = data->fluct ? data->fluct[PrescribedSlot(data, i, j, k)] : velocity;
624 velocity.x = data->factor * v.x + staged.x + fluct.x;
625 velocity.y = data->factor * v.y + staged.y + fluct.y;
626 velocity.z = data->factor * v.z + staged.z + fluct.z;
627 return velocity;
628 }
629 const PetscReal area = sqrt(metric.x * metric.x + metric.y * metric.y + metric.z * metric.z);
630 if (area <= 0.0) return velocity;
631 const PetscReal speed = data->factor * v.x + staged.x;
632 velocity.x = sign * speed * metric.x / area + fluct.x;
633 velocity.y = sign * speed * metric.y / area + fluct.y;
634 velocity.z = sign * speed * metric.z / area + fluct.z;
635 return velocity;
636}
637
638/**
639 * @brief Sets a handler's boundary velocity and the face flux it implies on one face.
640 * @details Shared by every handler that prescribes a Cartesian velocity at its face: the
641 * inlets, the no-slip wall and the free-slip wall. For each boundary slot this
642 * rank owns it asks @p rule for the velocity, stores it as the boundary value,
643 * and sets the face flux to its product with the face metric. A rule whose
644 * velocity is tangent to the face therefore closes the face. A slot whose fluid
645 * side is blanked (`nvert > 0.1`) belongs to an immersed body, whose own boundary
646 * condition applies there, so it is left untouched.
647 * @param self Handler being applied.
648 * @param ctx Boundary context naming the face.
649 * @param rule Velocity the handler prescribes, given the slot, the face metric, the
650 * side (`sign`, positive on a negative face) and the adjacent interior velocity.
651 * @return PetscErrorCode 0 on success.
652 */
653static PetscErrorCode ApplyFaceBoundaryVelocity(BoundaryCondition *self, BCContext *ctx,
655{
656 UserCtx *user = ctx->user;
657 BCFace face_id = ctx->face_id;
658 PetscBool can_service;
659 DMDALocalInfo *info = &user->info;
660 Cmpnts ***ubcs, ***ucont, ***csi, ***eta, ***zet, ***ucat;
661 PetscReal ***nvert;
662
663 PetscFunctionBeginUser;
665
666 PetscCall(CanRankServiceFace(info, user->IM, user->JM, user->KM, face_id, &can_service));
667 if (!can_service) { PROFILE_HELPER_END; PetscFunctionReturn(0); }
668
669 PetscCall(DMDAVecGetArray(user->fda, user->Bcs.Ubcs, &ubcs));
670 PetscCall(DMDAVecGetArray(user->fda, user->Ucont, &ucont));
671 PetscCall(DMDAVecGetArrayRead(user->fda, user->lCsi, (const Cmpnts***)&csi));
672 PetscCall(DMDAVecGetArrayRead(user->fda, user->lEta, (const Cmpnts***)&eta));
673 PetscCall(DMDAVecGetArrayRead(user->fda, user->lZet, (const Cmpnts***)&zet));
674 PetscCall(DMDAVecGetArrayRead(user->da, user->lNvert, (const PetscReal***)&nvert));
675 PetscCall(DMDAVecGetArrayRead(user->fda, user->lUcat, (const Cmpnts***)&ucat));
676
677 const PetscInt xs = info->xs, xe = info->xs + info->xm;
678 const PetscInt ys = info->ys, ye = info->ys + info->ym;
679 const PetscInt zs = info->zs, ze = info->zs + info->zm;
680 const PetscInt mx = info->mx, my = info->my, mz = info->mz;
681 PetscInt lxs = xs, lxe = xe, lys = ys, lye = ye, lzs = zs, lze = ze;
682 if (xs == 0) lxs++;
683 if (xe == mx) lxe--;
684 if (ys == 0) lys++;
685 if (ye == my) lye--;
686 if (zs == 0) lzs++;
687 if (ze == mz) lze--;
688
689 switch (face_id) {
690 case BC_FACE_NEG_X:
691 case BC_FACE_POS_X: {
692 const PetscReal sign = (face_id == BC_FACE_NEG_X) ? 1.0 : -1.0;
693 const PetscInt i = (face_id == BC_FACE_NEG_X) ? xs : mx - 2;
694 const PetscInt ib = i + (sign < 0);
695 for (PetscInt k = lzs; k < lze; k++) {
696 for (PetscInt j = lys; j < lye; j++) {
697 if ((sign > 0 && nvert[k][j][i + 1] > 0.1) ||
698 (sign < 0 && nvert[k][j][i] > 0.1)) continue;
699 const Cmpnts metric = csi[k][j][i];
700 const Cmpnts velocity = rule(self, face_id, i, j, k, metric, sign,
701 (sign > 0) ? ucat[k][j][i + 1] : ucat[k][j][i]);
702 ubcs[k][j][ib] = velocity;
703 ucont[k][j][i].x = velocity.x * metric.x + velocity.y * metric.y + velocity.z * metric.z;
704 }
705 }
706 } break;
707 case BC_FACE_NEG_Y:
708 case BC_FACE_POS_Y: {
709 const PetscReal sign = (face_id == BC_FACE_NEG_Y) ? 1.0 : -1.0;
710 const PetscInt j = (face_id == BC_FACE_NEG_Y) ? ys : my - 2;
711 const PetscInt jb = j + (sign < 0);
712 for (PetscInt k = lzs; k < lze; k++) {
713 for (PetscInt i = lxs; i < lxe; i++) {
714 if ((sign > 0 && nvert[k][j + 1][i] > 0.1) ||
715 (sign < 0 && nvert[k][j][i] > 0.1)) continue;
716 const Cmpnts metric = eta[k][j][i];
717 const Cmpnts velocity = rule(self, face_id, i, j, k, metric, sign,
718 (sign > 0) ? ucat[k][j + 1][i] : ucat[k][j][i]);
719 ubcs[k][jb][i] = velocity;
720 ucont[k][j][i].y = velocity.x * metric.x + velocity.y * metric.y + velocity.z * metric.z;
721 }
722 }
723 } break;
724 case BC_FACE_NEG_Z:
725 case BC_FACE_POS_Z: {
726 const PetscReal sign = (face_id == BC_FACE_NEG_Z) ? 1.0 : -1.0;
727 const PetscInt k = (face_id == BC_FACE_NEG_Z) ? zs : mz - 2;
728 const PetscInt kb = k + (sign < 0);
729 for (PetscInt j = lys; j < lye; j++) {
730 for (PetscInt i = lxs; i < lxe; i++) {
731 if ((sign > 0 && nvert[k + 1][j][i] > 0.1) ||
732 (sign < 0 && nvert[k][j][i] > 0.1)) continue;
733 const Cmpnts metric = zet[k][j][i];
734 const Cmpnts velocity = rule(self, face_id, i, j, k, metric, sign,
735 (sign > 0) ? ucat[k + 1][j][i] : ucat[k][j][i]);
736 ubcs[kb][j][i] = velocity;
737 ucont[k][j][i].z = velocity.x * metric.x + velocity.y * metric.y + velocity.z * metric.z;
738 }
739 }
740 } break;
741 }
742
743 PetscCall(DMDAVecRestoreArray(user->fda, user->Bcs.Ubcs, &ubcs));
744 PetscCall(DMDAVecRestoreArray(user->fda, user->Ucont, &ucont));
745 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lCsi, (const Cmpnts***)&csi));
746 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lEta, (const Cmpnts***)&eta));
747 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lZet, (const Cmpnts***)&zet));
748 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lUcat, (const Cmpnts***)&ucat));
749 PetscCall(DMDAVecRestoreArrayRead(user->da, user->lNvert, (const PetscReal***)&nvert));
751 PetscFunctionReturn(0);
752}
753
754/**
755 * @brief A moving wall's boundary velocity: the source's, with any part along the face removed, since
756 * a wall closes its face. PreStep refuses a source with more than a rounding of the
757 * surface's facets through it.
758 */
759static inline Cmpnts EvaluateMovingWallVelocity(const BoundaryCondition *self, BCFace face_id, PetscInt i, PetscInt j, PetscInt k,
760 Cmpnts metric, PetscReal sign, Cmpnts interior)
761{
762 return RemoveFaceNormalComponent(EvaluateInletCartesianVelocity(self, face_id, i, j, k, metric, sign, interior), metric);
763}
764
765/** @brief Applies a moving wall's velocity through the path every prescribed face shares. */
766static PetscErrorCode Apply_WallMoving(BoundaryCondition *self, BCContext *ctx)
767{
768 PetscFunctionBeginUser;
772 PetscFunctionReturn(0);
773}
774
775/**
776 * @brief Applies the prescribed inlet velocity through the common face-layout path.
777 *
778 * @details Ownership clipping, immersed-cell exclusion, metric projection, `Ubcs` placement,
779 * and the normal staggered `Ucont` write are `ApplyFaceBoundaryVelocity()`'s, shared
780 * with the walls.
781 */
782static PetscErrorCode Apply_InletVelocity(BoundaryCondition *self, BCContext *ctx)
783{
784 PetscFunctionBeginUser;
788 PetscFunctionReturn(0);
789}
790
791/**
792 * @brief Compile the source named by the face's `source_id` parameter, with its bulk velocity or
793 * flow rate if any, record the PICSLICE file named by its `source_file` parameter, and read
794 * the synthetic-fluctuation settings `-face_source_<id>_fluct*`: the Reynolds-stress sources
795 * and the integral length and time scales.
796 */
798{
800 UserCtx *user = ctx->user;
801 PetscReal id = -1.0;
802 PetscBool found = PETSC_FALSE;
803 const char *source_file = NULL;
804 char prefix[64];
805
806 PetscFunctionBeginUser;
808 PetscCall(GetBCParamReal(user->boundary_faces[ctx->face_id].params, "source_id", &id, &found));
809 PetscCheck(found && id >= 0.0, PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT,
810 "Face %s: the prescribed_velocity inlet needs a source_id parameter.", BCFaceToString(ctx->face_id));
811 PetscCall(GetBCParamString(user->boundary_faces[ctx->face_id].params, "source_file", &source_file, &found));
812 if (found && source_file && source_file[0] != '\0') {
813 PetscCall(PetscStrallocpy(source_file, &data->source_file));
814 }
815 PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "face_source_%d", (int)id));
816 PetscCall(PicurvVelocitySourceCreate(prefix, PETSC_TRUE, (PetscBool)(data->source_file != NULL), PETSC_TRUE, &data->source));
817 PetscCheck(!data->source_file || data->source.frame == PICURV_SOURCE_FRAME_NORMAL ||
818 data->source.frame == PICURV_SOURCE_FRAME_CARTESIAN, PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT,
819 "Face %s: a profile file and the expressions added to it are in the normal or cartesian frame.",
820 BCFaceToString(ctx->face_id));
821 PetscCall(GetBCParamBool(user->boundary_faces[ctx->face_id].params, "source_repeat", &data->repeat, &found));
822 data->factor = 1.0;
823 data->evaluated_step = -1;
824 {
825 char option[96], stress_prefix[96];
826 PetscInt count = 2;
827 PetscCall(PetscSNPrintf(option, sizeof(option), "-%s_fluct", prefix));
828 PetscCall(PetscOptionsGetBool(NULL, NULL, option, &data->fluctuate, NULL));
829 if (data->fluctuate) {
830 PetscCheck(user->InflowFluctuation, PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONGSTATE,
831 "Face %s adds fluctuations, but -inflow_fluctuations did not allocate their state.",
832 BCFaceToString(ctx->face_id));
833 for (PetscInt g = 0; g < 2; ++g) {
834 PetscCall(PetscSNPrintf(stress_prefix, sizeof(stress_prefix), "%s_fluct_stress_%d", prefix, (int)g));
835 PetscCall(PicurvVelocitySourceCreate(stress_prefix, PETSC_TRUE, PETSC_FALSE, PETSC_FALSE, &data->stress[g]));
836 /* Three stress components, as read: no frame turns them, and no bulk velocity or
837 flow rate scales them. */
838 PetscCheck(data->stress[g].frame == PICURV_SOURCE_FRAME_CARTESIAN && !data->stress[g].bulk,
839 PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT,
840 "Face %s: the Reynolds stresses -%s_* must be in the cartesian frame, with no bulk_velocity or flow_rate.",
841 BCFaceToString(ctx->face_id), stress_prefix);
842 }
843 PetscCall(PetscSNPrintf(option, sizeof(option), "-%s_fluct_length", prefix));
844 PetscCall(PetscOptionsGetRealArray(NULL, NULL, option, data->fluct_length, &count, &found));
845 PetscCheck(found && count == 2 && data->fluct_length[0] > 0.0 && data->fluct_length[1] > 0.0,
846 PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT, "%s needs two positive length scales.", option);
847 PetscCall(PetscSNPrintf(option, sizeof(option), "-%s_fluct_time", prefix));
848 PetscCall(PetscOptionsGetReal(NULL, NULL, option, &data->fluct_time, &found));
849 PetscCheck(found && data->fluct_time > 0.0, PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT,
850 "%s needs a positive time scale.", option);
851 }
852 }
853 if (data->source_file) {
854 LOG_ALLOW(GLOBAL, LOG_INFO, "Face %s: prescribed velocity from %s%s.\n",
855 BCFaceToString(ctx->face_id), data->source_file, data->source.bulk ? ", rescaled to a target" : "");
856 } else {
857 LOG_ALLOW(GLOBAL, LOG_INFO, "Face %s: prescribed velocity from -face_source_%d (%s frame%s%s).\n",
858 BCFaceToString(ctx->face_id), (int)id,
859 data->source.frame == PICURV_SOURCE_FRAME_NORMAL ? "normal" :
860 data->source.frame == PICURV_SOURCE_FRAME_CURVILINEAR ? "curvilinear" : "cartesian",
861 data->source.time_dependent ? ", time-dependent" : "", data->source.bulk ? ", bulk velocity" : "");
862 }
863 if (data->fluctuate) {
864 LOG_ALLOW(GLOBAL, LOG_INFO, "Face %s: synthetic fluctuations, integral lengths %g and %g, time %g (solver units).\n",
865 BCFaceToString(ctx->face_id), (double)data->fluct_length[0], (double)data->fluct_length[1],
866 (double)data->fluct_time);
867 }
869 PetscFunctionReturn(0);
870}
871
872/**
873 * @brief This rank's area-weighted sums over the face, physical: the source's normal speed, the
874 * staged data's when expressions add to it, the area, and the synthetic fluctuations'
875 * inflow (zero without them). Slots blanked by an immersed body are excluded, as in Apply.
876 * The first three are what the bulk rescaling reads; the fluctuations are added after it.
877 */
878static PetscErrorCode PrescribedFaceSums(const InletPrescribedVelocityData *data, UserCtx *user, BCFace face_id, PetscReal local[4])
879{
880 const PicurvSourceFaceSlots *slots = &data->slots;
881 const PetscInt normal = slots->elements.normal, a = slots->elements.a, b = slots->elements.b;
882 const PetscBool negative = (PetscBool)((PetscInt)face_id % 2 == 0);
883 const PetscReal sign = negative ? 1.0 : -1.0, U_ref = user->simCtx->scaling.U_ref;
884 const PetscReal L_ref = user->simCtx->scaling.L_ref;
885
886 PetscFunctionBeginUser;
888 local[0] = local[1] = local[2] = local[3] = 0.0;
889 if (slots->elements.n[0] * slots->elements.n[1] > 0) {
890 const PetscInt slot = slots->elements.layer;
891 const PetscInt cell = negative ? slot + 1 : slot;
892 const Cmpnts ***metric_arr;
893 const PetscReal ***nvert;
894 Vec metric_vec = (normal == 0) ? user->lCsi : (normal == 1) ? user->lEta : user->lZet;
895 PetscCall(DMDAVecGetArrayRead(user->fda, metric_vec, &metric_arr));
896 PetscCall(DMDAVecGetArrayRead(user->da, user->lNvert, &nvert));
897 for (PetscInt q = 0; q < slots->elements.n[1]; ++q)
898 for (PetscInt p = 0; p < slots->elements.n[0]; ++p) {
899 PetscInt s_idx[3], c_idx[3];
900 s_idx[normal] = slot; s_idx[a] = slots->elements.lo[0] + p; s_idx[b] = slots->elements.lo[1] + q;
901 c_idx[normal] = cell; c_idx[a] = s_idx[a]; c_idx[b] = s_idx[b];
902 if (nvert[c_idx[2]][c_idx[1]][c_idx[0]] > 0.1) continue;
903 const Cmpnts m = metric_arr[s_idx[2]][s_idx[1]][s_idx[0]];
904 const Cmpnts v = data->velocity[p + slots->elements.n[0] * q];
905 const PetscReal area = PetscSqrtReal(m.x * m.x + m.y * m.y + m.z * m.z);
906 const PetscReal physical = U_ref * L_ref * L_ref;
907 local[0] += physical * ((data->source.frame == PICURV_SOURCE_FRAME_NORMAL)
908 ? v.x * area : sign * (v.x * m.x + v.y * m.y + v.z * m.z));
909 if (data->profile) {
910 const Cmpnts staged = data->profile[p + slots->elements.n[0] * q];
911 local[1] += physical * ((data->source.frame == PICURV_SOURCE_FRAME_NORMAL)
912 ? staged.x * area : sign * (staged.x * m.x + staged.y * m.y + staged.z * m.z));
913 }
914 local[2] += L_ref * L_ref * area;
915 /* Fluctuations are Cartesian in every frame (Apply adds them to the velocity). */
916 if (data->fluct) {
917 const Cmpnts f = data->fluct[p + slots->elements.n[0] * q];
918 local[3] += physical * sign * (f.x * m.x + f.y * m.y + f.z * m.z);
919 }
920 }
921 PetscCall(DMDAVecRestoreArrayRead(user->da, user->lNvert, &nvert));
922 PetscCall(DMDAVecRestoreArrayRead(user->fda, metric_vec, &metric_arr));
923 }
925 PetscFunctionReturn(0);
926}
927
928/**
929 * @brief Factor that makes the face's mean normal speed or flow rate equal the target. Collective.
930 */
931static PetscErrorCode PrescribedBulkFactor(InletPrescribedVelocityData *data, UserCtx *user, BCFace face_id,
932 PetscReal physical_time, PetscReal *factor)
933{
934 PetscReal local[4];
935 char where[32];
936
937 PetscFunctionBeginUser;
939 PetscCall(PrescribedFaceSums(data, user, face_id, local));
940 PetscCall(PetscSNPrintf(where, sizeof(where), "Face %s", BCFaceToString(face_id)));
941 PetscCall(PicurvVelocitySourceBulkFactor(&data->source, physical_time, local, where, factor));
943 PetscFunctionReturn(0);
944}
945
946/**
947 * @brief Read one frame of the face's PICSLICE into this rank's slots, moving the file there.
948 * Every rank reads the file, so a malformed one fails on all of them.
949 * @param data Handler data with an open file.
950 * @param frame Frame to read.
951 * @param target Velocity per owned slot; a normal speed goes in `x`.
952 */
953static PetscErrorCode LoadPrescribedFrame(InletPrescribedVelocityData *data, PetscInt frame, Cmpnts *target)
954{
955 const PicurvSourceFaceSlots *slots = &data->slots;
956 const PetscInt n2 = data->file_n[1], components = data->components;
957
958 PetscFunctionBeginUser;
960 if (frame < data->next_frame) {
961 PetscCheck(fsetpos(data->file, &data->first_frame) == 0, PETSC_COMM_SELF, PETSC_ERR_FILE_READ,
962 "Cannot return to the first frame of %s.", data->source_file);
963 data->next_frame = 0;
964 }
965 while (data->next_frame <= frame) PetscCall(ReadPicSliceFrame(data));
966 /* A PICSLICE row runs along the face's first tangential axis; rows step along the second. */
967 for (PetscInt q = 0; q < slots->elements.n[1]; ++q)
968 for (PetscInt p = 0; p < slots->elements.n[0]; ++p) {
969 const PetscReal *value = &data->file_values[components * ((slots->elements.lo[1] + q - 1) * n2 + (slots->elements.lo[0] + p - 1))];
970 Cmpnts *v = &target[p + slots->elements.n[0] * q];
971 v->x = value[0];
972 v->y = (components == 3) ? value[1] : 0.0;
973 v->z = (components == 3) ? value[2] : 0.0;
974 }
976 PetscFunctionReturn(0);
977}
978
979/**
980 * @brief Open the face's PICSLICE and read a lone frame, as the velocity itself or, under
981 * expressions, as what they add to; several frames are read as time reaches them.
982 */
983static PetscErrorCode OpenPrescribedProfile(InletPrescribedVelocityData *data, UserCtx *user, BCFace face_id)
984{
985 const PetscInt n_slots = data->slots.elements.n[0] * data->slots.elements.n[1];
986 const PetscBool normal = (PetscBool)(data->source.frame == PICURV_SOURCE_FRAME_NORMAL);
987 PetscInt n1 = 0, n2 = 0;
988
989 PetscFunctionBeginUser;
991 PetscCall(GetProfileFileExpectedDims(user, face_id, &n1, &n2));
992 PetscCall(OpenPicSlice(data, n1, n2));
993 PetscCheck(data->components == (normal ? 1 : 3), PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT,
994 "Face %s: %s holds %" PetscInt_FMT " component(s) per slot, but the source is in the %s frame.",
995 BCFaceToString(face_id), data->source_file, data->components, normal ? "normal" : "cartesian");
996 if (data->source.count > 0) PetscCall(PetscCalloc1(n_slots, &data->profile));
997 PetscCall(PetscMalloc1(n1 * n2 * data->components, &data->file_values));
998 if (data->frames == 1) {
999 PetscCall(LoadPrescribedFrame(data, 0, data->profile ? data->profile : data->velocity));
1000 PetscCheck(fclose(data->file) == 0, PETSC_COMM_SELF, PETSC_ERR_FILE_READ, "Cannot close %s.", data->source_file);
1001 data->file = NULL;
1002 } else {
1003 /* Two allocations: the brackets swap as time advances, so neither stays the first of a pair. */
1004 PetscCall(PetscMalloc1(n_slots, &data->bracket[0]));
1005 PetscCall(PetscMalloc1(n_slots, &data->bracket[1]));
1006 data->bracket_frame[0] = data->bracket_frame[1] = -1;
1007 }
1008 LOG_ALLOW(GLOBAL, LOG_INFO, "Face %s: PICSLICE %s, %" PetscInt_FMT " x %" PetscInt_FMT ", %" PetscInt_FMT " component(s), %" PetscInt_FMT " frame(s).\n",
1009 BCFaceToString(face_id), data->source_file, n1, n2, data->components, data->frames);
1011 PetscFunctionReturn(0);
1012}
1013
1014/**
1015 * @brief Set the staged data at a time: linear between the two frames around it, the first at t = 0.
1016 */
1017static PetscErrorCode InterpolatePrescribedFrames(InletPrescribedVelocityData *data, BCFace face_id, PetscReal physical_time)
1018{
1019 const PetscInt n_slots = data->slots.elements.n[0] * data->slots.elements.n[1];
1020 const PetscReal position = physical_time / data->interval;
1021 PetscInt frame[2] = {(PetscInt)PetscFloorReal(position), 0};
1022 PetscReal weight = position - PetscFloorReal(position);
1023 Cmpnts *out = data->profile ? data->profile : data->velocity;
1024
1025 PetscFunctionBeginUser;
1027 if (data->repeat) {
1028 frame[0] = frame[0] % data->frames;
1029 frame[1] = (frame[0] + 1) % data->frames;
1030 } else {
1031 /* A time step landing on the last frame may round just past it. */
1032 if (frame[0] == data->frames - 1 && weight < 1.0e-9) { frame[0] = data->frames - 2; weight = 1.0; }
1033 PetscCheck(frame[0] < data->frames - 1 && frame[0] >= 0, PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT,
1034 "Face %s: time %g is past the %" PetscInt_FMT " frames of %s, %g s apart. Set repeat: true to loop them.",
1035 BCFaceToString(face_id), (double)physical_time, data->frames, data->source_file, (double)data->interval);
1036 frame[1] = frame[0] + 1;
1037 }
1038 for (PetscInt f = 0; f < 2; ++f) {
1039 if (data->bracket_frame[f] == frame[f]) continue;
1040 if (data->bracket_frame[1 - f] == frame[f]) {
1041 /* The later frame of the last interval is the earlier one of this. */
1042 Cmpnts *kept = data->bracket[1 - f];
1043 data->bracket[1 - f] = data->bracket[f];
1044 data->bracket[f] = kept;
1045 data->bracket_frame[1 - f] = data->bracket_frame[f];
1046 data->bracket_frame[f] = frame[f];
1047 continue;
1048 }
1049 PetscCall(LoadPrescribedFrame(data, frame[f], data->bracket[f]));
1050 data->bracket_frame[f] = frame[f];
1051 }
1052 for (PetscInt s = 0; s < n_slots; ++s) {
1053 out[s].x = (1.0 - weight) * data->bracket[0][s].x + weight * data->bracket[1][s].x;
1054 out[s].y = (1.0 - weight) * data->bracket[0][s].y + weight * data->bracket[1][s].y;
1055 out[s].z = (1.0 - weight) * data->bracket[0][s].z + weight * data->bracket[1][s].z;
1056 }
1058 PetscFunctionReturn(0);
1059}
1060
1061/**
1062 * @brief Implementation of \ref LogPrescribedFlowDiagnostics().
1063 * @see LogPrescribedFlowDiagnostics()
1064 */
1066{
1067 SimCtx *simCtx = user->simCtx;
1068
1069 PetscFunctionBeginUser;
1071 for (PetscInt face = 0; face < 6; ++face) {
1072 const BoundaryCondition *handler = user->boundary_faces[face].handler;
1073 PetscReal local[4], global[4], physical_time, flow_rate;
1074 FILE *file = NULL;
1075
1076 if (!handler || user->boundary_faces[face].handler_type != BC_HANDLER_INLET_PRESCRIBED_VELOCITY) continue;
1077 const InletPrescribedVelocityData *data = (const InletPrescribedVelocityData*)handler->data;
1078 if (!data->built) continue;
1079 PetscCall(PrescribedFaceSums(data, user, (BCFace)face, local));
1080 PetscCallMPI(MPI_Allreduce(local, global, 4, MPIU_REAL, MPI_SUM, PETSC_COMM_WORLD));
1081 if (simCtx->rank != 0 || user->_this != 0) continue;
1082 PetscCall(PicurvPhysicalTime(simCtx, simCtx->ti, &physical_time));
1083 flow_rate = data->factor * global[0] + global[1];
1084 PetscCall(PicurvOpenDiagnosticsCsv(simCtx, simCtx->analysis_dir, "inlet_flow.csv",
1085 "step,physical_time,face,area,flow_rate,mean_normal_speed,bulk_factor,"
1086 "fluctuation_flow_rate,applied_flow_rate",
1087 &file));
1088 /* flow_rate is the rescaled profile's, the one a bulk target controls; the synthetic
1089 fluctuations are added after the rescaling, so the flux the face actually admits is
1090 their sum. */
1091 fprintf(file, "%d,%.10e,%s,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e\n", (int)simCtx->step, (double)physical_time,
1092 BCFaceToString((BCFace)face), (double)global[2], (double)flow_rate,
1093 (double)(global[2] > 0.0 ? flow_rate / global[2] : 0.0), (double)data->factor,
1094 (double)global[3], (double)(flow_rate + global[3]));
1095 PetscCheck(fclose(file) == 0, PETSC_COMM_SELF, PETSC_ERR_FILE_WRITE, "Unable to close the inlet-flow diagnostics file.");
1096 }
1098 PetscFunctionReturn(0);
1099}
1100
1101/** Face cells the synthetic-inflow draw lattice extends beyond each edge; a filter half-width may not exceed it. */
1102#define INFLOW_LATTICE_PAD 1048576
1103
1104/**
1105 * @brief Prepare an inlet's synthetic fluctuations once its slots exist: filter widths from the
1106 * face's mean spacing, and the Reynolds stresses' Cholesky factor at each slot.
1107 * @details Collective over the block. The integral length L along a tangential axis spans
1108 * n = L / h cells, h the face's cell width along it: the mean of its widest and
1109 * narrowest cell there. The filter weights are
1110 * exp(-pi |k| / n) for |k| <= 2n, scaled to a unit sum of squares (Xie & Castro 2008),
1111 * so filtered unit-variance noise keeps unit variance. Every rank and every
1112 * decomposition uses the same h, so the kernel is bitwise the same.
1113 */
1115{
1116 PicurvSourceFaceSlots *slots = &data->slots;
1117 const PetscInt count = slots->elements.n[0] * slots->elements.n[1];
1118 const PetscInt tangential[2] = {slots->elements.a, slots->elements.b};
1119 const PetscReal U2 = user->simCtx->scaling.U_ref * user->simCtx->scaling.U_ref;
1120 /* Widest and narrowest cell along each axis, as {max0, max1, -min0, -min1}. Each width comes
1121 from its own cell's metrics and a maximum is exact in any order, so every decomposition
1122 builds the same kernel; a line length is summed across the ranks it crosses, and is not. */
1123 PetscReal extent[4] = {0.0, 0.0, -PETSC_MAX_REAL, -PETSC_MAX_REAL};
1124
1125 PetscFunctionBeginUser;
1127 for (PetscInt s = 0; s < count; ++s) {
1128 for (PetscInt d = 0; d < 2; ++d) {
1129 const Cmpnts e = data->slots.edges[s][tangential[d]];
1130 const PetscReal width = PetscSqrtReal(e.x * e.x + e.y * e.y + e.z * e.z);
1131 extent[d] = PetscMax(extent[d], width);
1132 extent[2 + d] = PetscMax(extent[2 + d], -width);
1133 }
1134 }
1135 PetscCallMPI(MPI_Allreduce(MPI_IN_PLACE, extent, 4, MPIU_REAL, MPI_MAX, PETSC_COMM_WORLD));
1136 for (PetscInt d = 0; d < 2; ++d) {
1137 const PetscReal h = 0.5 * (extent[d] - extent[2 + d]);
1138 const PetscReal n = data->fluct_length[d] / h;
1139 PetscReal norm = 0.0;
1140 data->half[d] = PetscMax(1, (PetscInt)PetscCeilReal(2.0 * n));
1141 PetscCheck(data->half[d] <= INFLOW_LATTICE_PAD, PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT,
1142 "An inlet's fluctuation length spans %g cells, beyond the %d its draws can reach.",
1143 (double)n, INFLOW_LATTICE_PAD / 2);
1144 PetscCall(PetscMalloc1(2 * data->half[d] + 1, &data->kernel[d]));
1145 for (PetscInt k = -data->half[d]; k <= data->half[d]; ++k) {
1146 data->kernel[d][k + data->half[d]] = PetscExpReal(-PETSC_PI * PetscAbsReal((PetscReal)k) / n);
1147 norm += data->kernel[d][k + data->half[d]] * data->kernel[d][k + data->half[d]];
1148 }
1149 for (PetscInt k = 0; k <= 2 * data->half[d]; ++k) data->kernel[d][k] /= PetscSqrtReal(norm);
1150 }
1151 PetscCall(PetscMalloc2(count, &data->lund, count, &data->fluct));
1152 for (PetscInt s = 0; s < count; ++s) {
1153 Cmpnts diag, cross;
1154 PetscCall(PicurvVelocitySourceEvaluate(&data->stress[0], data->slots.values[s], NULL, data->slots.edges[s], &diag));
1155 PetscCall(PicurvVelocitySourceEvaluate(&data->stress[1], data->slots.values[s], NULL, data->slots.edges[s], &cross));
1156 /* Lund, Wu & Squires (1998): u' = A psi with A A^T = R. A stress tensor that is not
1157 positive definite, such as zero at a wall, leaves the rows it cannot fill at zero. */
1158 PetscReal *a = data->lund[s];
1159 a[0] = PetscSqrtReal(PetscMax(diag.x / U2, 0.0));
1160 a[1] = (a[0] > 0.0) ? cross.x / U2 / a[0] : 0.0;
1161 a[2] = PetscSqrtReal(PetscMax(diag.y / U2 - a[1] * a[1], 0.0));
1162 a[3] = (a[0] > 0.0) ? cross.y / U2 / a[0] : 0.0;
1163 a[4] = (a[2] > 0.0) ? (cross.z / U2 - a[1] * a[3]) / a[2] : 0.0;
1164 a[5] = PetscSqrtReal(PetscMax(diag.z / U2 - a[3] * a[3] - a[4] * a[4], 0.0));
1165 data->fluct[s].x = data->fluct[s].y = data->fluct[s].z = 0.0;
1166 }
1168 PetscFunctionReturn(0);
1169}
1170
1171/**
1172 * @brief This step's synthetic fluctuation at every owned slot of an inlet.
1173 * @details Keyed unit normals on the owned face cells and a halo of the filter's half-width are
1174 * filtered along each tangential axis; a draw is a pure function of the seed, block,
1175 * component, face cell and step, so a rank computes its halo itself and the result does
1176 * not depend on the decomposition. A periodic tangential axis wraps the halo. The time
1177 * filter psi <- psi exp(-pi dt / 2T) + filtered sqrt(1 - exp(-pi dt / T)) keeps unit
1178 * variance; its state lives in the inlet's dummy plane of `InflowFluctuation`, which a
1179 * checkpoint carries, and starts from the filtered noise when there is none. A restored
1180 * state belongs to the restart step already, so the first pass after it only reads it.
1181 */
1182static PetscErrorCode StepInletFluctuation(InletPrescribedVelocityData *data, UserCtx *user, BCFace face_id)
1183{
1184 SimCtx *simCtx = user->simCtx;
1185 const PicurvSourceFaceSlots *slots = &data->slots;
1186 const PetscInt n0 = slots->elements.n[0], n1 = slots->elements.n[1], h0 = data->half[0], h1 = data->half[1];
1187 const PetscInt w0 = n0 + 2 * h0, w1 = n1 + 2 * h1;
1188 const PetscInt nodes[3] = {user->info.mx, user->info.my, user->info.mz};
1189 const PetscInt cells[2] = {nodes[slots->elements.a] - 2, nodes[slots->elements.b] - 2};
1190 PetscBool axes_periodic[3];
1191 GetPeriodicAxes(simCtx, axes_periodic);
1192 const PetscBool periodic[2] = {axes_periodic[slots->elements.a], axes_periodic[slots->elements.b]};
1193 const PetscBool negative = (PetscBool)((PetscInt)face_id % 2 == 0);
1194 const PetscReal decay = PetscExpReal(-PETSC_PI * simCtx->dt / (2.0 * data->fluct_time));
1195 const PetscReal gain = PetscSqrtReal(1.0 - decay * decay);
1196 const PetscBool fresh = (PetscBool)(!data->fluct_started && !simCtx->inflowFluctuationsRestored);
1197 /* A restored state is already this step's: the checkpoint was written after its update. */
1198 const PetscBool restored = (PetscBool)(!data->fluct_started && simCtx->inflowFluctuationsRestored);
1199 PetscReal *noise = NULL, *rows = NULL, *psi = NULL;
1200 Cmpnts ***state = NULL;
1201
1202 PetscFunctionBeginUser;
1204 if (n0 * n1 > 0) {
1205 PetscCall(PetscMalloc3(w0 * w1, &noise, n0 * w1, &rows, 3 * n0 * n1, &psi));
1206 for (PetscInt c = 0; c < 3 && !restored; ++c) {
1207 for (PetscInt qq = 0; qq < w1; ++qq) {
1208 for (PetscInt pp = 0; pp < w0; ++pp) {
1209 PetscInt g[2] = {slots->elements.lo[0] - 1 - h0 + pp, slots->elements.lo[1] - 1 - h1 + qq};
1210 for (PetscInt d = 0; d < 2; ++d) if (periodic[d]) g[d] = ((g[d] % cells[d]) + cells[d]) % cells[d];
1211 /* A face cell, or one of its halo beyond a closed edge, on a lattice padded by a fixed
1212 width, so a draw does not depend on the filter's half-widths. */
1213 const PetscInt64 id = ((PetscInt64)face_id * (cells[1] + 2 * INFLOW_LATTICE_PAD) + (g[1] + INFLOW_LATTICE_PAD))
1214 * (cells[0] + 2 * INFLOW_LATTICE_PAD) + (g[0] + INFLOW_LATTICE_PAD);
1215 noise[pp + w0 * qq] = PicurvNormalFromHash(PicurvDrawHash((PetscInt64)simCtx->sourceRandomSeed,
1217 (uint64_t)(3 * user->_this + c), id,
1218 (PetscInt64)simCtx->step));
1219 }
1220 }
1221 for (PetscInt qq = 0; qq < w1; ++qq) {
1222 for (PetscInt p = 0; p < n0; ++p) {
1223 PetscReal sum = 0.0;
1224 for (PetscInt k = 0; k <= 2 * h0; ++k) sum += data->kernel[0][k] * noise[(p + k) + w0 * qq];
1225 rows[p + n0 * qq] = sum;
1226 }
1227 }
1228 for (PetscInt q = 0; q < n1; ++q) {
1229 for (PetscInt p = 0; p < n0; ++p) {
1230 PetscReal sum = 0.0;
1231 for (PetscInt k = 0; k <= 2 * h1; ++k) sum += data->kernel[1][k] * rows[p + n0 * (q + k)];
1232 psi[3 * (p + n0 * q) + c] = sum;
1233 }
1234 }
1235 }
1236 PetscCall(DMDAVecGetArray(user->fda, user->InflowFluctuation, &state));
1237 for (PetscInt q = 0; q < n1; ++q) {
1238 for (PetscInt p = 0; p < n0; ++p) {
1239 const PetscInt s = p + n0 * q;
1240 PetscInt idx[3];
1241 idx[slots->elements.normal] = negative ? 0 : nodes[slots->elements.normal] - 1;
1242 idx[slots->elements.a] = slots->elements.lo[0] + p;
1243 idx[slots->elements.b] = slots->elements.lo[1] + q;
1244 Cmpnts *st = &state[idx[2]][idx[1]][idx[0]];
1245 const PetscReal *f = &psi[3 * s];
1246 if (fresh) { st->x = f[0]; st->y = f[1]; st->z = f[2]; }
1247 else if (!restored) { st->x = decay * st->x + gain * f[0]; st->y = decay * st->y + gain * f[1]; st->z = decay * st->z + gain * f[2]; }
1248 const PetscReal *a = data->lund[s];
1249 data->fluct[s].x = a[0] * st->x;
1250 data->fluct[s].y = a[1] * st->x + a[2] * st->y;
1251 data->fluct[s].z = a[3] * st->x + a[4] * st->y + a[5] * st->z;
1252 }
1253 }
1254 PetscCall(DMDAVecRestoreArray(user->fda, user->InflowFluctuation, &state));
1255 PetscCall(PetscFree3(noise, rows, psi));
1256 }
1257 data->fluct_started = PETSC_TRUE;
1259 PetscFunctionReturn(0);
1260}
1261
1262/**
1263 * @brief Refresh the inlet velocity once per step: gather the slots on the first call, then
1264 * re-evaluate and rescale only what depends on t.
1265 */
1267 PetscReal *local_inflow_contribution,
1268 PetscReal *local_outflow_contribution)
1269{
1271 UserCtx *user = ctx->user;
1272 SimCtx *simCtx = user->simCtx;
1273 PetscReal physical_time;
1274
1275 (void)local_inflow_contribution;
1276 (void)local_outflow_contribution;
1277 PetscFunctionBeginUser;
1279 /* Boundary passes repeat within a step (every stage and residual); the velocity is
1280 defined at the step's time, so it is refreshed once. */
1281 if (data->built && data->evaluated_step == simCtx->step) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
1282 const PetscBool first = (PetscBool)!data->built;
1283 if (first) {
1284 Vec fraction, length;
1285 PetscCall(DMCreateGlobalVector(user->fda, &fraction));
1286 PetscCall(DMCreateGlobalVector(user->fda, &length));
1287 PetscCall(ComputeGridLineFractions(user, fraction, length));
1288 PetscCall(PicurvSourceFaceSlotsCreate(user, ctx->face_id, fraction, length, &data->slots));
1289 PetscCall(VecDestroy(&fraction));
1290 PetscCall(VecDestroy(&length));
1291 PetscCall(PetscMalloc1(data->slots.elements.n[0] * data->slots.elements.n[1], &data->velocity));
1292 if (data->source_file) PetscCall(OpenPrescribedProfile(data, user, ctx->face_id));
1293 if (data->fluctuate) PetscCall(BuildInletFluctuation(data, user));
1294 }
1295 const PetscBool frames_vary = (PetscBool)(data->frames > 1);
1296 const PetscBool evaluate = (PetscBool)(first || data->source.time_dependent);
1297 const PetscBool rescale = (PetscBool)(data->source.bulk && (evaluate || frames_vary || data->source.bulk_time_dependent));
1298 PetscCall(PicurvPhysicalTime(simCtx, simCtx->ti, &physical_time));
1299 if (frames_vary) PetscCall(InterpolatePrescribedFrames(data, ctx->face_id, physical_time));
1300 if (evaluate && data->source.count > 0) {
1301 const PetscReal U_ref = simCtx->scaling.U_ref;
1302 const PetscInt nodes[3] = {user->info.mx, user->info.my, user->info.mz};
1303 for (PetscInt s = 0; s < data->slots.elements.n[0] * data->slots.elements.n[1]; ++s) {
1304 const PetscInt p = s % data->slots.elements.n[0], q = s / data->slots.elements.n[0];
1305 const PicurvExpressionDrawKey key = PicurvFaceDrawKey((PetscInt64)simCtx->sourceRandomSeed, user->_this, nodes, ctx->face_id,
1306 data->slots.elements.lo[0] + p - 1, data->slots.elements.lo[1] + q - 1,
1307 (PetscInt64)simCtx->step);
1308 Cmpnts v;
1309 data->slots.values[s][PICURV_SOURCE_VAR_T] = physical_time;
1310 PetscCall(PicurvVelocitySourceEvaluate(&data->source, data->slots.values[s], &key, data->slots.edges[s], &v));
1311 data->velocity[s].x = v.x / U_ref;
1312 data->velocity[s].y = v.y / U_ref;
1313 data->velocity[s].z = v.z / U_ref;
1315 const Cmpnts m = data->slots.edges[s][data->slots.elements.normal];
1316 const PetscReal speed2 = v.x * v.x + v.y * v.y + v.z * v.z;
1317 const PetscReal through = v.x * m.x + v.y * m.y + v.z * m.z;
1318 PetscCheck(through * through <= 2.5e-3 * speed2 * (m.x * m.x + m.y * m.y + m.z * m.z), PETSC_COMM_SELF, PETSC_ERR_USER_INPUT,
1319 "Face %s: a moving wall's velocity must lie along the wall; (%g, %g, %g) passes through it at (%g, %g, %g).",
1320 BCFaceToString(ctx->face_id), (double)v.x, (double)v.y, (double)v.z,
1321 (double)data->slots.values[s][PICURV_SOURCE_VAR_X], (double)data->slots.values[s][PICURV_SOURCE_VAR_Y],
1322 (double)data->slots.values[s][PICURV_SOURCE_VAR_Z]);
1323 }
1324 }
1325 }
1326 data->built = PETSC_TRUE;
1327 if (rescale) PetscCall(PrescribedBulkFactor(data, user, ctx->face_id, physical_time, &data->factor));
1328 if (data->fluctuate) PetscCall(StepInletFluctuation(data, user, ctx->face_id));
1329 data->evaluated_step = simCtx->step;
1331 PetscFunctionReturn(0);
1332}
1333
1334/** @brief Release the compiled source and the per-slot arrays. */
1336{
1337 PetscFunctionBeginUser;
1339 if (self && self->data) {
1341 PetscCall(PicurvVelocitySourceDestroy(&data->source));
1342 PetscCall(PetscFree(data->source_file));
1343 if (data->file) PetscCheck(fclose(data->file) == 0, PETSC_COMM_SELF, PETSC_ERR_FILE_READ, "Cannot close a PICSLICE file.");
1344 PetscCall(PetscFree(data->profile));
1345 PetscCall(PetscFree(data->file_values));
1346 PetscCall(PetscFree(data->bracket[0]));
1347 PetscCall(PetscFree(data->bracket[1]));
1348 if (data->built) PetscCall(PicurvSourceFaceSlotsDestroy(&data->slots));
1349 PetscCall(PetscFree(data->velocity));
1350 if (data->fluctuate) {
1351 PetscCall(PicurvVelocitySourceDestroy(&data->stress[0]));
1352 PetscCall(PicurvVelocitySourceDestroy(&data->stress[1]));
1353 PetscCall(PetscFree(data->kernel[0]));
1354 PetscCall(PetscFree(data->kernel[1]));
1355 PetscCall(PetscFree2(data->lund, data->fluct));
1356 }
1357 PetscCall(PetscFree(self->data));
1358 }
1360 PetscFunctionReturn(0);
1361}
1362
1363//================================================================================
1364//
1365// HANDLER IMPLEMENTATION: OUTLET WITH MASS CONSERVATION
1366// (Corresponds to BC_HANDLER_OUTLET_CONSERVATION)
1367//
1368// This handler ensures that the total flux leaving through outlet boundaries
1369// balances the total flux entering through inlet and far-field boundaries.
1370//
1371// Workflow:
1372// 1. PreStep: Measures the *uncorrected* flux based on interior velocities.
1373// 2. Apply: Calculates a global correction factor based on the flux imbalance
1374// and applies it to the contravariant velocity (ucont) on the outlet face.
1375// 3. PostStep: Measures the *corrected* flux for verification and logging.
1376//
1377// Backflow clip. The uniform correction adds the same velocity c to every face,
1378// so it can leave a face with flux into the domain. Once per time step, at the
1379// step's first Apply, the handler asks whether F + c*A points into the domain on
1380// any face of this outlet (F the zero-gradient flux, signed along +xi like every
1381// face flux, so outward is F > 0 on a positive face and F < 0 on a negative one;
1382// A the face area). If not, the uniform rule
1383// runs unchanged. If so, the faces whose F points into the domain are clipped to
1384// zero flux (and zero normal velocity in Ubcs), and the rest are scaled by one factor
1385// psi so that this face carries the same total as the uniform rule would. The
1386// rule and the clipped set are frozen for the rest of the step so the residual
1387// stays smooth inside a Newton solve; psi is re-measured on every call, as c is,
1388// so the total stays exact.
1389//
1390//================================================================================
1391
1392// --- 1. FORWARD DECLARATIONS ---
1393static PetscErrorCode PreStep_OutletConservation(BoundaryCondition *self, BCContext *ctx,
1394 PetscReal *local_inflow_contribution, PetscReal *local_outflow_contribution);
1395static PetscErrorCode Apply_OutletConservation(BoundaryCondition *self, BCContext *ctx);
1396static PetscErrorCode PostStep_OutletConservation(BoundaryCondition *self, BCContext *ctx,
1397 PetscReal *in, PetscReal *out);
1398static PetscErrorCode Destroy_OutletConservation(BoundaryCondition *self);
1399
1400/** Per-face state of the backflow clip; see the section comment above. */
1401typedef struct {
1402 PetscInt decisionStep; /* Step at which the rule and clipped set were chosen (-1 = never). */
1403 PetscBool clipRule; /* PETSC_TRUE: clip reversed faces and scale the rest, this step. */
1404 PetscInt maskSize; /* Owned face elements covered by clipped[]. */
1405 PetscBool *clipped; /* Frozen clipped set, indexed q*n[0] + p over the owned elements. */
1407
1408/**
1409 * @brief Implementation of \ref Create_OutletConservation().
1410 * @details Full API contract (arguments, ownership, side effects) is documented with
1411 * the header declaration in `include/BC_Handlers.h`.
1412 * @see Create_OutletConservation()
1413 */
1415{
1416 PetscFunctionBeginUser;
1418
1419 PetscCheck(bc, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "BoundaryCondition is NULL");
1420
1421 // This handler has the highest priority to ensure it runs after
1422 // all inflow fluxes have been calculated.
1424
1425 // Assign function pointers
1426 bc->Initialize = NULL; // No initialization needed
1430 bc->UpdateUbcs = NULL;
1431 bc->needs_repeat_pass = PETSC_TRUE; // Reads the adjacent Ucat and the inlets' flux
1433
1434 OutletConservationData *data = NULL;
1435 PetscCall(PetscNew(&data));
1436 data->decisionStep = -1;
1437 bc->data = (void*)data;
1438
1440 PetscFunctionReturn(0);
1441}
1442
1443/**
1444 * @brief Prepare the outlet-conservation correction before advancing the solver.
1445 */
1447 PetscReal *local_inflow_contribution, PetscReal *local_outflow_contribution)
1448{
1449 PetscErrorCode ierr;
1450 UserCtx* user = ctx->user;
1451 BCFace face_id = ctx->face_id;
1452 DMDALocalInfo* info = &user->info;
1453 PetscBool can_service;
1454
1455 // Suppress unused parameter warnings for clarity.
1456 (void)self;
1457 (void)local_inflow_contribution;
1458
1459 PetscFunctionBeginUser;
1461
1462 // Step 1: Use the robust utility function to determine if this MPI rank owns a computable
1463 // portion of the specified boundary face. If not, there is no work to do, so we exit immediately.
1464 const PetscInt IM_nodes_global = user->IM;
1465 const PetscInt JM_nodes_global = user->JM;
1466 const PetscInt KM_nodes_global = user->KM;
1467 ierr = CanRankServiceFace(info, IM_nodes_global, JM_nodes_global, KM_nodes_global, face_id, &can_service); CHKERRQ(ierr);
1468
1469 if (!can_service) {
1471 PetscFunctionReturn(0);
1472 }
1473
1474 // Step 2: Get read-only access to the necessary PETSc arrays.
1475 // We use the local versions (`lUcat`, `lNvert`) which include ghost cell data,
1476 // ensuring we have the correct interior values adjacent to the boundary.
1477 Cmpnts ***ucat, ***csi, ***eta, ***zet;
1478 PetscReal ***nvert;
1479 ierr = DMDAVecGetArrayRead(user->fda, user->lUcat, (const Cmpnts***)&ucat); CHKERRQ(ierr);
1480 ierr = DMDAVecGetArrayRead(user->da, user->lNvert, (const PetscReal***)&nvert); CHKERRQ(ierr);
1481 ierr = DMDAVecGetArrayRead(user->fda, user->lCsi, (const Cmpnts***)&csi); CHKERRQ(ierr);
1482 ierr = DMDAVecGetArrayRead(user->fda, user->lEta, (const Cmpnts***)&eta); CHKERRQ(ierr);
1483 ierr = DMDAVecGetArrayRead(user->fda, user->lZet, (const Cmpnts***)&zet); CHKERRQ(ierr);
1484
1485 PetscReal local_flux_out = 0.0;
1486 const PetscInt xs=info->xs, xe=info->xs+info->xm;
1487 const PetscInt ys=info->ys, ye=info->ys+info->ym;
1488 const PetscInt zs=info->zs, ze=info->zs+info->zm;
1489 const PetscInt mx=info->mx, my=info->my, mz=info->mz;
1490
1491 // Step 3: Replicate the legacy shrunk loop bounds to exclude corners and edges.
1492 PetscInt lxs = xs; if (xs == 0) lxs = xs + 1;
1493 PetscInt lxe = xe; if (xe == mx) lxe = xe - 1;
1494 PetscInt lys = ys; if (ys == 0) lys = ys + 1;
1495 PetscInt lye = ye; if (ye == my) lye = ye - 1;
1496 PetscInt lzs = zs; if (zs == 0) lzs = zs + 1;
1497 PetscInt lze = ze; if (ze == mz) lze = ze - 1;
1498
1499 // Step 4: Loop over the specified face using the corrected bounds and indexing to calculate flux.
1500 switch (face_id) {
1501 case BC_FACE_NEG_X: {
1502 const PetscInt i_cell = xs + 1; // Index for first interior cell-centered data
1503 const PetscInt i_face = xs; // Index for the -X face of that cell
1504 for (int k=lzs; k<lze; k++) for (int j=lys; j<lye; j++) {
1505 if (nvert[k][j][i_cell] < 0.1) {
1506 local_flux_out += (ucat[k][j][i_cell].x * csi[k][j][i_face].x + ucat[k][j][i_cell].y * csi[k][j][i_face].y + ucat[k][j][i_cell].z * csi[k][j][i_face].z);
1507 }
1508 }
1509 break;
1510 }
1511 case BC_FACE_POS_X: {
1512 const PetscInt i_cell = xe - 2; // Index for last interior cell-centered data
1513 const PetscInt i_face = xe - 2; // Index for the +X face of that cell
1514 for (int k=lzs; k<lze; k++) for (int j=lys; j<lye; j++) {
1515 if (nvert[k][j][i_cell] < 0.1) {
1516 local_flux_out += (ucat[k][j][i_cell].x * csi[k][j][i_face].x + ucat[k][j][i_cell].y * csi[k][j][i_face].y + ucat[k][j][i_cell].z * csi[k][j][i_face].z);
1517 }
1518 }
1519 break;
1520 }
1521 case BC_FACE_NEG_Y: {
1522 const PetscInt j_cell = ys + 1;
1523 const PetscInt j_face = ys;
1524 for (int k=lzs; k<lze; k++) for (int i=lxs; i<lxe; i++) {
1525 if (nvert[k][j_cell][i] < 0.1) {
1526 local_flux_out += (ucat[k][j_cell][i].x * eta[k][j_face][i].x + ucat[k][j_cell][i].y * eta[k][j_face][i].y + ucat[k][j_cell][i].z * eta[k][j_face][i].z);
1527 }
1528 }
1529 break;
1530 }
1531 case BC_FACE_POS_Y: {
1532 const PetscInt j_cell = ye - 2;
1533 const PetscInt j_face = ye - 2;
1534 for (int k=lzs; k<lze; k++) for (int i=lxs; i<lxe; i++) {
1535 if (nvert[k][j_cell][i] < 0.1) {
1536 local_flux_out += (ucat[k][j_cell][i].x * eta[k][j_face][i].x + ucat[k][j_cell][i].y * eta[k][j_face][i].y + ucat[k][j_cell][i].z * eta[k][j_face][i].z);
1537 }
1538 }
1539 break;
1540 }
1541 case BC_FACE_NEG_Z: {
1542 const PetscInt k_cell = zs + 1;
1543 const PetscInt k_face = zs;
1544 for (int j=lys; j<lye; j++) for (int i=lxs; i<lxe; i++) {
1545 if (nvert[k_cell][j][i] < 0.1) {
1546 local_flux_out += (ucat[k_cell][j][i].x * zet[k_face][j][i].x + ucat[k_cell][j][i].y * zet[k_face][j][i].y + ucat[k_cell][j][i].z * zet[k_face][j][i].z);
1547 }
1548 }
1549 break;
1550 }
1551 case BC_FACE_POS_Z: {
1552 const PetscInt k_cell = ze - 2;
1553 const PetscInt k_face = ze - 2;
1554 for (int j=lys; j<lye; j++) for (int i=lxs; i<lxe; i++) {
1555 if (nvert[k_cell][j][i] < 0.1) {
1556 local_flux_out += (ucat[k_cell][j][i].x * zet[k_face][j][i].x + ucat[k_cell][j][i].y * zet[k_face][j][i].y + ucat[k_cell][j][i].z * zet[k_face][j][i].z);
1557 }
1558 }
1559 break;
1560 }
1561 }
1562
1563 // Step 5: Restore the PETSc arrays.
1564 ierr = DMDAVecRestoreArrayRead(user->fda, user->lUcat, (const Cmpnts***)&ucat); CHKERRQ(ierr);
1565 ierr = DMDAVecRestoreArrayRead(user->da, user->lNvert, (const PetscReal***)&nvert); CHKERRQ(ierr);
1566 ierr = DMDAVecRestoreArrayRead(user->fda, user->lCsi, (const Cmpnts***)&csi); CHKERRQ(ierr);
1567 ierr = DMDAVecRestoreArrayRead(user->fda, user->lEta, (const Cmpnts***)&eta); CHKERRQ(ierr);
1568 ierr = DMDAVecRestoreArrayRead(user->fda, user->lZet, (const Cmpnts***)&zet); CHKERRQ(ierr);
1569
1570 // Step 6: Add this face's calculated flux to the accumulator for this rank.
1571 *local_outflow_contribution += local_flux_out;
1572
1574 PetscFunctionReturn(0);
1575}
1576
1577/** What one OutletClipPass() over the owned outlet elements does. */
1579
1580/**
1581 * @brief One pass over this rank's elements of an outlet face for the backflow clip.
1582 *
1583 * Every fluid element's zero-gradient flux is F = Ucat(cell) . S, the flux the uniform rule
1584 * starts from. The pass is local; the caller reduces @p sums.
1585 * - DECIDE freezes the clipped set {F points into the domain} into @p data and returns
1586 * sums[0] = the number of elements where F + correction*A points into the domain and
1587 * sums[1] = the number clipped. Fluxes are signed along +xi, so outward is +F on a positive
1588 * face and -F on a negative one.
1589 * - MEASURE returns sums[0] = sum F, sums[1] = sum A and sums[2] = sum F over unclipped elements.
1590 * - WRITE sets the outlet flux: zero on clipped elements, whose Ubcs loses its normal component,
1591 * and psi*F elsewhere, with Ubcs = Ucat as in the uniform rule.
1592 */
1593static PetscErrorCode OutletClipPass(UserCtx *user, BCFace face_id, OutletConservationData *data,
1594 OutletClipPassMode mode, PetscReal correction, PetscReal psi,
1595 PetscReal sums[3])
1596{
1597 const PetscBool negative = (PetscBool)((PetscInt)face_id % 2 == 0);
1598 const PetscReal outward = negative ? -1.0 : 1.0;
1600 Cmpnts ***ucat, ***metric, ***ubcs = NULL, ***ucont = NULL;
1601 PetscReal ***nvert;
1602
1603 PetscFunctionBeginUser;
1605 sums[0] = sums[1] = sums[2] = 0.0;
1606 PetscCall(GetBoundaryFaceElements(user, face_id, &e));
1607 const PetscInt count = e.n[0] * e.n[1];
1608 if (mode == OUTLET_CLIP_DECIDE && count != data->maskSize) {
1609 PetscCall(PetscFree(data->clipped));
1610 if (count > 0) PetscCall(PetscCalloc1(count, &data->clipped));
1611 data->maskSize = count;
1612 }
1613 if (count == 0) { PROFILE_HELPER_END; PetscFunctionReturn(PETSC_SUCCESS); }
1614
1615 const Vec lmetric = (e.normal == 0) ? user->lCsi : (e.normal == 1) ? user->lEta : user->lZet;
1616 const PetscInt cell = negative ? e.layer + 1 : e.layer;
1617 const PetscInt dummy = negative ? e.layer : e.layer + 1;
1618
1619 PetscCall(DMDAVecGetArrayRead(user->fda, user->lUcat, (const Cmpnts***)&ucat));
1620 PetscCall(DMDAVecGetArrayRead(user->fda, lmetric, (const Cmpnts***)&metric));
1621 PetscCall(DMDAVecGetArrayRead(user->da, user->lNvert, (const PetscReal***)&nvert));
1622 if (mode == OUTLET_CLIP_WRITE) {
1623 PetscCall(DMDAVecGetArray(user->fda, user->Bcs.Ubcs, &ubcs));
1624 PetscCall(DMDAVecGetArray(user->fda, user->Ucont, &ucont));
1625 }
1626 for (PetscInt q = 0; q < e.n[1]; q++)
1627 for (PetscInt p = 0; p < e.n[0]; p++) {
1628 PetscInt c[3], f[3], d[3];
1629
1630 c[e.normal] = cell; c[e.a] = e.lo[0] + p; c[e.b] = e.lo[1] + q;
1631 if (nvert[c[2]][c[1]][c[0]] >= 0.1) continue;
1632 f[0] = d[0] = c[0]; f[1] = d[1] = c[1]; f[2] = d[2] = c[2];
1633 f[e.normal] = e.layer;
1634 d[e.normal] = dummy;
1635
1636 const PetscInt idx = q * e.n[0] + p;
1637 const Cmpnts S = metric[f[2]][f[1]][f[0]];
1638 const Cmpnts u = ucat[c[2]][c[1]][c[0]];
1639 const PetscReal flux = u.x * S.x + u.y * S.y + u.z * S.z;
1640 const PetscReal area = PetscSqrtReal(S.x * S.x + S.y * S.y + S.z * S.z);
1641
1642 switch (mode) {
1643 case OUTLET_CLIP_DECIDE:
1644 data->clipped[idx] = (PetscBool)(outward * flux < 0.0);
1645 if (outward * (flux + correction * area) < 0.0) sums[0] += 1.0;
1646 if (data->clipped[idx]) sums[1] += 1.0;
1647 break;
1649 sums[0] += flux;
1650 sums[1] += area;
1651 if (!data->clipped[idx]) sums[2] += flux;
1652 break;
1653 case OUTLET_CLIP_WRITE: {
1654 Cmpnts *face_flux = &ucont[f[2]][f[1]][f[0]];
1655 PetscReal *normal_flux = (e.normal == 0) ? &face_flux->x : (e.normal == 1) ? &face_flux->y : &face_flux->z;
1656
1657 if (data->clipped[idx]) {
1658 *normal_flux = 0.0;
1659 ubcs[d[2]][d[1]][d[0]] = RemoveFaceNormalComponent(u, S);
1660 } else {
1661 *normal_flux = psi * flux;
1662 ubcs[d[2]][d[1]][d[0]] = u;
1663 }
1664 break;
1665 }
1666 }
1667 }
1668 if (mode == OUTLET_CLIP_WRITE) {
1669 PetscCall(DMDAVecRestoreArray(user->fda, user->Bcs.Ubcs, &ubcs));
1670 PetscCall(DMDAVecRestoreArray(user->fda, user->Ucont, &ucont));
1671 }
1672 PetscCall(DMDAVecRestoreArrayRead(user->da, user->lNvert, (const PetscReal***)&nvert));
1673 PetscCall(DMDAVecRestoreArrayRead(user->fda, lmetric, (const Cmpnts***)&metric));
1674 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lUcat, (const Cmpnts***)&ucat));
1676 PetscFunctionReturn(PETSC_SUCCESS);
1677}
1678
1679/**
1680 * @brief Run the backflow clip for one Apply call; see the section comment.
1681 *
1682 * Collective: every rank calls it, whether or not it serves the face. Sets @p applied when the
1683 * clip rule wrote this face's fluxes; otherwise the caller applies the uniform rule unchanged.
1684 */
1685static PetscErrorCode OutletConservationClip(UserCtx *user, BCFace face_id, OutletConservationData *data,
1686 PetscReal correction, PetscBool *applied)
1687{
1688 SimCtx *simCtx = user->simCtx;
1689 const PetscReal outward = ((PetscInt)face_id % 2 == 0) ? -1.0 : 1.0;
1690 PetscReal local[3], global[3];
1691 PetscBool decided_now = PETSC_FALSE;
1692 PetscReal reversed = 0.0, clipped = 0.0;
1693
1694 PetscFunctionBeginUser;
1696 *applied = PETSC_FALSE;
1697 if (data->decisionStep != simCtx->step) {
1698 PetscCall(OutletClipPass(user, face_id, data, OUTLET_CLIP_DECIDE, correction, 0.0, local));
1699 PetscCallMPI(MPI_Allreduce(local, global, 2, MPIU_REAL, MPI_SUM, PETSC_COMM_WORLD));
1700 data->clipRule = (PetscBool)(global[0] > 0.5);
1701 data->decisionStep = simCtx->step;
1702 decided_now = PETSC_TRUE;
1703 reversed = global[0];
1704 clipped = global[1];
1705 }
1706 if (!data->clipRule) { PROFILE_HELPER_END; PetscFunctionReturn(PETSC_SUCCESS); }
1707
1708 PetscCall(OutletClipPass(user, face_id, data, OUTLET_CLIP_MEASURE, correction, 0.0, local));
1709 PetscCallMPI(MPI_Allreduce(local, global, 3, MPIU_REAL, MPI_SUM, PETSC_COMM_WORLD));
1710 /* The total the uniform rule would give this face: the clip only redistributes it. */
1711 const PetscReal target = global[0] + correction * global[1];
1712 if (!(outward * global[2] > 0.0 && outward * target > 0.0)) {
1714 "Outlet %s, step %" PetscInt_FMT ": nothing left to scale (unclipped flux %.4e, target %.4e); "
1715 "using the uniform correction for this pass.\n",
1716 BCFaceToString(face_id), simCtx->step, global[2], target);
1718 PetscFunctionReturn(PETSC_SUCCESS);
1719 }
1720 const PetscReal psi = target / global[2];
1721 PetscCall(OutletClipPass(user, face_id, data, OUTLET_CLIP_WRITE, correction, psi, local));
1722 if (decided_now) {
1724 "Outlet %s, step %" PetscInt_FMT ": uniform correction would leave %.0f faces reversed; "
1725 "clipped %.0f reversed faces, scaled the rest by psi = %.6f.\n",
1726 BCFaceToString(face_id), simCtx->step, reversed, clipped, psi);
1727 }
1728 *applied = PETSC_TRUE;
1730 PetscFunctionReturn(PETSC_SUCCESS);
1731}
1732
1733/**
1734 * @brief (Handler Action) Applies mass conservation correction to the outlet face.
1735 *
1736 * This function calculates a global correction factor based on the total inflow and outflow fluxes
1737 * and applies it to the contravariant velocity (`ucont`) on the outlet face to ensure mass conservation.
1738 */
1739static PetscErrorCode Apply_OutletConservation(BoundaryCondition *self, BCContext *ctx)
1740{
1741 PetscErrorCode ierr;
1742 UserCtx* user = ctx->user;
1743 BCFace face_id = ctx->face_id;
1744 DMDALocalInfo* info = &user->info;
1745 PetscBool can_service;
1746 PetscBool clip_applied = PETSC_FALSE;
1747
1748 PetscFunctionBeginUser;
1750
1751 // --- STEP 1: Calculate the correction factor using pre-calculated area ---
1752 PetscReal total_inflow = *ctx->global_inflow_sum + *ctx->global_farfield_inflow_sum;
1753 PetscReal flux_imbalance = total_inflow - *ctx->global_outflow_sum;
1754
1755 // Directly use the pre-calculated area from the simulation context.
1756 PetscReal velocity_correction = (PetscAbsReal(user->simCtx->AreaOutSum) > 1e-12)
1757 ? flux_imbalance / user->simCtx->AreaOutSum
1758 : 0.0;
1759
1760 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Outlet Correction on Face %d: Imbalance=%.4e, Pre-calc Area=%.4e, V_corr=%.4e\n",
1761 face_id, flux_imbalance, user->simCtx->AreaOutSum, velocity_correction);
1762
1763 // Backflow clip (collective, so before the can_service exit). When it applies, it has
1764 // written this face; otherwise the uniform rule below runs unchanged.
1765 ierr = OutletConservationClip(user, face_id, (OutletConservationData*)self->data,
1766 velocity_correction, &clip_applied); CHKERRQ(ierr);
1767 if (clip_applied) {
1769 PetscFunctionReturn(0);
1770 }
1771
1772 const PetscInt IM_nodes_global = user->IM;
1773 const PetscInt JM_nodes_global = user->JM;
1774 const PetscInt KM_nodes_global = user->KM;
1775 ierr = CanRankServiceFace(info, IM_nodes_global, JM_nodes_global, KM_nodes_global, face_id, &can_service); CHKERRQ(ierr);
1776
1777 if (!can_service) {
1779 PetscFunctionReturn(0);
1780 }
1781
1782 // --- STEP 2: Apply the correction to ucont on the outlet face ---
1783
1784 // Get read/write access to necessary arrays
1785
1786 Cmpnts ***ubcs, ***ucont, ***csi, ***eta, ***zet, ***ucat;
1787 PetscReal ***nvert;
1788 ierr = DMDAVecGetArray(user->fda, user->Bcs.Ubcs, &ubcs); CHKERRQ(ierr);
1789 ierr = DMDAVecGetArray(user->fda, user->Ucont, &ucont); CHKERRQ(ierr);
1790 ierr = DMDAVecGetArrayRead(user->fda,user->lUcat, (const Cmpnts***)&ucat); CHKERRQ(ierr);
1791 ierr = DMDAVecGetArrayRead(user->fda, user->lCsi, (const Cmpnts***)&csi); CHKERRQ(ierr);
1792 ierr = DMDAVecGetArrayRead(user->fda, user->lEta, (const Cmpnts***)&eta); CHKERRQ(ierr);
1793 ierr = DMDAVecGetArrayRead(user->fda, user->lZet, (const Cmpnts***)&zet); CHKERRQ(ierr);
1794 ierr = DMDAVecGetArrayRead(user->da, user->lNvert, (const PetscReal***)&nvert); CHKERRQ(ierr);
1795
1796 // Get local grid bounds to exclude corners/edges
1797 PetscInt xs = info->xs, xe = info->xs + info->xm;
1798 PetscInt ys = info->ys, ye = info->ys + info->ym;
1799 PetscInt zs = info->zs, ze = info->zs + info->zm;
1800 PetscInt mx = info->mx, my = info->my, mz = info->mz;
1801 PetscInt lxs = xs, lxe = xe, lys = ys, lye = ye, lzs = zs, lze = ze;
1802
1803 if (xs == 0) lxs = xs + 1;
1804 if (xe == mx) lxe = xe - 1;
1805 if (ys == 0) lys = ys + 1;
1806 if (ye == my) lye = ye - 1;
1807 if (zs == 0) lzs = zs + 1;
1808 if (ze == mz) lze = ze - 1;
1809
1810 // Loop over faces and apply correction
1811 switch(face_id){
1812 case BC_FACE_NEG_X:{
1813 const PetscInt i_cell = xs + 1;
1814 const PetscInt i_face = xs;
1815 const PetscInt i_dummy = xs;
1816 for (PetscInt k = lzs; k < lze; k++) {
1817 for (PetscInt j = lys; j < lye; j++) {
1818 if (nvert[k][j][i_cell] < 0.1) {
1819 // Set ubcs
1820 ubcs[k][j][i_dummy] = ucat[k][j][i_cell];
1821
1822 // Calculate Local uncorrected original flux
1823 PetscReal Uncorrected_local_flux = (ubcs[k][j][i_dummy].x * csi[k][j][i_face].x) + (ubcs[k][j][i_dummy].y * csi[k][j][i_face].y) + (ubcs[k][j][i_dummy].z * csi[k][j][i_face].z);
1824
1825 PetscReal Cell_Area = sqrt((csi[k][j][i_face].x*csi[k][j][i_face].x) + (csi[k][j][i_face].y*csi[k][j][i_face].y) + (csi[k][j][i_face].z*csi[k][j][i_face].z));
1826
1827 PetscReal Correction_flux = velocity_correction*Cell_Area;
1828
1829 ucont[k][j][i_face].x = Uncorrected_local_flux + Correction_flux;
1830 }
1831 }
1832 }
1833 break;
1834 }
1835 case BC_FACE_POS_X:{
1836 const PetscInt i_cell = xe - 2;
1837 const PetscInt i_face = xe - 2;
1838 const PetscInt i_dummy = xe - 1;
1839 for(PetscInt k = lzs; k < lze; k++) for (PetscInt j = lys; j < lye; j++){
1840 if(nvert[k][j][i_cell]<0.1){
1841 // Set ubcs
1842 ubcs[k][j][i_dummy] = ucat[k][j][i_cell];
1843
1844 // Calculate Local uncorrected original flux
1845 PetscReal Uncorrected_local_flux = (ubcs[k][j][i_dummy].x * csi[k][j][i_face].x) + (ubcs[k][j][i_dummy].y * csi[k][j][i_face].y) + (ubcs[k][j][i_dummy].z * csi[k][j][i_face].z);
1846
1847 PetscReal Cell_Area = sqrt((csi[k][j][i_face].x*csi[k][j][i_face].x) + (csi[k][j][i_face].y*csi[k][j][i_face].y) + (csi[k][j][i_face].z*csi[k][j][i_face].z));
1848
1849 PetscReal Correction_flux = velocity_correction*Cell_Area;
1850
1851 ucont[k][j][i_face].x = Uncorrected_local_flux + Correction_flux;
1852 }
1853 }
1854 break;
1855 }
1856 case BC_FACE_NEG_Y:{
1857 const PetscInt j_cell = ys + 1;
1858 const PetscInt j_face = ys;
1859 const PetscInt j_dummy = ys;
1860 for(PetscInt k = lzs; k < lze; k++) for (PetscInt i = lxs; i < lxe; i++){
1861 if(nvert[k][j_cell][i]<0.1){
1862 // Set ubcs
1863 ubcs[k][j_dummy][i] = ucat[k][j_cell][i];
1864
1865 // Calculate Local uncorrected original flux
1866 PetscReal Uncorrected_local_flux = (ubcs[k][j_dummy][i].x*eta[k][j_face][i].x) + (ubcs[k][j_dummy][i].y*eta[k][j_face][i].y) + (ubcs[k][j_dummy][i].z*eta[k][j_face][i].z);
1867
1868 PetscReal Cell_Area = sqrt((eta[k][j_face][i].x*eta[k][j_face][i].x)+(eta[k][j_face][i].y*eta[k][j_face][i].y)+(eta[k][j_face][i].z*eta[k][j_face][i].z));
1869
1870 PetscReal Correction_flux = velocity_correction*Cell_Area;
1871
1872 ucont[k][j_face][i].y = Uncorrected_local_flux + Correction_flux;
1873 }
1874 }
1875 break;
1876 }
1877 case BC_FACE_POS_Y:{
1878 const PetscInt j_cell = ye - 2;
1879 const PetscInt j_face = ye - 2;
1880 const PetscInt j_dummy = ye - 1;
1881 for(PetscInt k = lzs; k < lze; k++) for (PetscInt i = lxs; i < lxe; i++){
1882 if(nvert[k][j_cell][i]<0.1){
1883 // Set ubcs
1884 ubcs[k][j_dummy][i] = ucat[k][j_cell][i];
1885
1886 // Calculate Local uncorrected original flux
1887 PetscReal Uncorrected_local_flux = (ubcs[k][j_dummy][i].x*eta[k][j_face][i].x) + (ubcs[k][j_dummy][i].y*eta[k][j_face][i].y) + (ubcs[k][j_dummy][i].z*eta[k][j_face][i].z);
1888
1889 PetscReal Cell_Area = sqrt((eta[k][j_face][i].x*eta[k][j_face][i].x)+(eta[k][j_face][i].y*eta[k][j_face][i].y)+(eta[k][j_face][i].z*eta[k][j_face][i].z));
1890
1891 PetscReal Correction_flux = velocity_correction*Cell_Area;
1892
1893 ucont[k][j_face][i].y = Uncorrected_local_flux + Correction_flux;
1894 }
1895 }
1896 break;
1897 }
1898 case BC_FACE_NEG_Z:{
1899 const PetscInt k_cell = zs + 1;
1900 const PetscInt k_face = zs;
1901 const PetscInt k_dummy = zs;
1902 for(PetscInt j = lys; j < lye; j++) for (PetscInt i = lxs; i < lxe; i++){
1903 if(nvert[k_cell][j][i]<0.1){
1904 // Set ubcs
1905 ubcs[k_dummy][j][i] = ucat[k_cell][j][i];
1906
1907 // Calculate Local uncorrected original flux
1908 PetscReal Uncorrected_local_flux = ((ubcs[k_dummy][j][i].x*zet[k_face][j][i].x) + (ubcs[k_dummy][j][i].y*zet[k_face][j][i].y) + (ubcs[k_dummy][j][i].z*zet[k_face][j][i].z));
1909
1910 PetscReal Cell_Area = sqrt((zet[k_face][j][i].x*zet[k_face][j][i].x)+(zet[k_face][j][i].y*zet[k_face][j][i].y)+(zet[k_face][j][i].z*zet[k_face][j][i].z));
1911
1912 PetscReal Correction_flux = velocity_correction*Cell_Area;
1913
1914 ucont[k_face][j][i].z = Uncorrected_local_flux + Correction_flux;
1915 }
1916 }
1917 break;
1918 }
1919 case BC_FACE_POS_Z:{
1920 const PetscInt k_cell = ze - 2;
1921 const PetscInt k_face = ze - 2;
1922 const PetscInt k_dummy = ze - 1;
1923 for(PetscInt j = lys; j < lye; j++) for (PetscInt i = lxs; i < lxe; i++){
1924 if(nvert[k_cell][j][i]<0.1){
1925 // Set ubcs
1926 ubcs[k_dummy][j][i] = ucat[k_cell][j][i];
1927
1928 // Calculate Local uncorrected original flux
1929 PetscReal Uncorrected_local_flux = ((ubcs[k_dummy][j][i].x*zet[k_face][j][i].x) + (ubcs[k_dummy][j][i].y*zet[k_face][j][i].y) + (ubcs[k_dummy][j][i].z*zet[k_face][j][i].z));
1930
1931 PetscReal Cell_Area = sqrt((zet[k_face][j][i].x*zet[k_face][j][i].x)+(zet[k_face][j][i].y*zet[k_face][j][i].y)+(zet[k_face][j][i].z*zet[k_face][j][i].z));
1932
1933 PetscReal Correction_flux = velocity_correction*Cell_Area;
1934
1935 ucont[k_face][j][i].z = Uncorrected_local_flux + Correction_flux;
1936 }
1937 }
1938 break;
1939 }
1940 }
1941
1942 // Restore all arrays
1943 ierr = DMDAVecRestoreArray(user->fda, user->Bcs.Ubcs, &ubcs); CHKERRQ(ierr);
1944 ierr = DMDAVecRestoreArray(user->fda, user->Ucont, &ucont); CHKERRQ(ierr);
1945 ierr = DMDAVecRestoreArrayRead(user->fda,user->lUcat, (const Cmpnts***)&ucat); CHKERRQ(ierr);
1946 ierr = DMDAVecRestoreArrayRead(user->fda, user->lCsi, (const Cmpnts***)&csi); CHKERRQ(ierr);
1947 ierr = DMDAVecRestoreArrayRead(user->fda, user->lEta, (const Cmpnts***)&eta); CHKERRQ(ierr);
1948 ierr = DMDAVecRestoreArrayRead(user->fda, user->lZet, (const Cmpnts***)&zet); CHKERRQ(ierr);
1949 ierr = DMDAVecRestoreArrayRead(user->da, user->lNvert, (const PetscReal***)&nvert); CHKERRQ(ierr);
1950
1952 PetscFunctionReturn(0);
1953}
1954
1955/**
1956 * @brief Update outlet-conservation state after a completed solver step.
1957 */
1959 PetscReal *local_inflow_contribution,
1960 PetscReal *local_outflow_contribution)
1961{
1962 PetscErrorCode ierr;
1963 UserCtx* user = ctx->user;
1964 BCFace face_id = ctx->face_id;
1965 DMDALocalInfo* info = &user->info;
1966 PetscBool can_service;
1967
1968 (void)self;
1969 (void)local_inflow_contribution;
1970
1971 PetscFunctionBeginUser;
1973 const PetscInt IM_nodes_global = user->IM;
1974 const PetscInt JM_nodes_global = user->JM;
1975 const PetscInt KM_nodes_global = user->KM;
1976 ierr = CanRankServiceFace(info, IM_nodes_global, JM_nodes_global, KM_nodes_global, face_id, &can_service); CHKERRQ(ierr);
1977
1978 if (!can_service) { PROFILE_HELPER_END; PetscFunctionReturn(0); }
1979
1980 // Get arrays (need both ucont and nvert)
1981 Cmpnts ***ucont;
1982 PetscReal ***nvert; // ✅ ADD nvert
1983
1984 ierr = DMDAVecGetArrayRead(user->fda, user->Ucont, (const Cmpnts***)&ucont); CHKERRQ(ierr);
1985 ierr = DMDAVecGetArrayRead(user->da, user->lNvert, (const PetscReal***)&nvert); CHKERRQ(ierr); // ✅ ADD
1986
1987 PetscReal local_flux = 0.0;
1988
1989 PetscInt xs = info->xs, xe = info->xs + info->xm;
1990 PetscInt ys = info->ys, ye = info->ys + info->ym;
1991 PetscInt zs = info->zs, ze = info->zs + info->zm;
1992 PetscInt mx = info->mx, my = info->my, mz = info->mz;
1993
1994 PetscInt lxs = xs, lxe = xe, lys = ys, lye = ye, lzs = zs, lze = ze;
1995 if (xs == 0) lxs = xs + 1;
1996 if (xe == mx) lxe = xe - 1;
1997 if (ys == 0) lys = ys + 1;
1998 if (ye == my) lye = ye - 1;
1999 if (zs == 0) lzs = zs + 1;
2000 if (ze == mz) lze = ze - 1;
2001
2002 // Sum ucont components, skipping solid cells (same indices as PreStep)
2003 switch (face_id) {
2004 case BC_FACE_NEG_X: {
2005 const PetscInt i_cell = xs + 1; // ✅ Match PreStep
2006 const PetscInt i_face = xs;
2007 for (PetscInt k = lzs; k < lze; k++) {
2008 for (PetscInt j = lys; j < lye; j++) {
2009 if (nvert[k][j][i_cell] < 0.1) { // ✅ Skip solid cells
2010 local_flux += ucont[k][j][i_face].x;
2011 }
2012 }
2013 }
2014 } break;
2015
2016 case BC_FACE_POS_X: {
2017 const PetscInt i_cell = xe - 2; // ✅ Match PreStep
2018 const PetscInt i_face = xe - 2;
2019 for (PetscInt k = lzs; k < lze; k++) {
2020 for (PetscInt j = lys; j < lye; j++) {
2021 if (nvert[k][j][i_cell] < 0.1) { // ✅ Skip solid cells
2022 local_flux += ucont[k][j][i_face].x;
2023 }
2024 }
2025 }
2026 } break;
2027
2028 case BC_FACE_NEG_Y: {
2029 const PetscInt j_cell = ys + 1; // ✅ Match PreStep
2030 const PetscInt j_face = ys;
2031 for (PetscInt k = lzs; k < lze; k++) {
2032 for (PetscInt i = lxs; i < lxe; i++) {
2033 if (nvert[k][j_cell][i] < 0.1) { // ✅ Skip solid cells
2034 local_flux += ucont[k][j_face][i].y;
2035 }
2036 }
2037 }
2038 } break;
2039
2040 case BC_FACE_POS_Y: {
2041 const PetscInt j_cell = ye - 2; // ✅ Match PreStep
2042 const PetscInt j_face = ye - 2;
2043 for (PetscInt k = lzs; k < lze; k++) {
2044 for (PetscInt i = lxs; i < lxe; i++) {
2045 if (nvert[k][j_cell][i] < 0.1) { // ✅ Skip solid cells
2046 local_flux += ucont[k][j_face][i].y;
2047 }
2048 }
2049 }
2050 } break;
2051
2052 case BC_FACE_NEG_Z: {
2053 const PetscInt k_cell = zs + 1; // ✅ Match PreStep
2054 const PetscInt k_face = zs;
2055 for (PetscInt j = lys; j < lye; j++) {
2056 for (PetscInt i = lxs; i < lxe; i++) {
2057 if (nvert[k_cell][j][i] < 0.1) { // ✅ Skip solid cells
2058 local_flux += ucont[k_face][j][i].z;
2059 }
2060 }
2061 }
2062 } break;
2063
2064 case BC_FACE_POS_Z: {
2065 const PetscInt k_cell = ze - 2; // ✅ Match PreStep
2066 const PetscInt k_face = ze - 2;
2067 for (PetscInt j = lys; j < lye; j++) {
2068 for (PetscInt i = lxs; i < lxe; i++) {
2069 if (nvert[k_cell][j][i] < 0.1) { // ✅ Skip solid cells
2070 local_flux += ucont[k_face][j][i].z;
2071 }
2072 }
2073 }
2074 } break;
2075 }
2076
2077 // Restore arrays
2078 ierr = DMDAVecRestoreArrayRead(user->fda, user->Ucont, (const Cmpnts***)&ucont); CHKERRQ(ierr);
2079 ierr = DMDAVecRestoreArrayRead(user->da, user->lNvert, (const PetscReal***)&nvert); CHKERRQ(ierr); // ✅ ADD
2080
2081 // Add to accumulator
2082 *local_outflow_contribution += local_flux;
2083
2084 LOG_ALLOW(LOCAL, LOG_DEBUG, "PostStep_OutletConservation: Face %d, corrected flux = %.6e\n",
2085 face_id, local_flux);
2086
2088 PetscFunctionReturn(0);
2089}
2090
2091/**
2092 * @brief Release the outlet-conservation handler's clip state.
2093 */
2095{
2096 PetscFunctionBeginUser;
2098 if (self && self->data) {
2100 PetscCall(PetscFree(data->clipped));
2101 PetscCall(PetscFree(self->data));
2102 }
2104 PetscFunctionReturn(PETSC_SUCCESS);
2105}
2106
2107
2108/**
2109 * @brief Implementation of \ref Create_PeriodicGeometric().
2110 * @details Full API contract (arguments, ownership, side effects) is documented with
2111 * the header declaration in `include/BC_Handlers.h`.
2112 * @see Create_PeriodicGeometric()
2113 */
2114
2116 PetscFunctionBeginUser;
2118
2119 PetscCheck(bc, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "BoundaryCondition is NULL");
2121
2122 // Assign function pointers
2123 bc->Initialize = NULL; // No initialization needed
2124 bc->PreStep = NULL;
2125 bc->Apply = NULL;
2126 bc->PostStep = NULL;
2127 bc->UpdateUbcs = NULL;
2128 bc->Destroy = NULL; // No private data to destroy
2129
2130 bc->data = NULL;
2131
2133 PetscFunctionReturn(0);
2134}
2135
2136
2137/**
2138 * @brief Measure the two volumetric fluxes the driven-flow controller senses.
2139 *
2140 * Both periodic driven handlers steer on the same pair of measurements, so they
2141 * are taken here in a single sweep of `lUcont`:
2142 *
2143 * - `*boundaryFlux` is the flux through the single periodic boundary plane.
2144 * It is fast and responsive but noisy, and drives the boundary trim.
2145 * - `*planarAverageFlux` is the flux averaged over every cross-sectional plane
2146 * in the driven direction. It is stable and inertial, and drives the
2147 * momentum source. It is also the quantity `initial_flux` latches at t=0.
2148 *
2149 * @param[in] user Block context supplying `lUcont`, `lNvert` and `info`.
2150 * @param[in] direction Driven direction, 'X', 'Y' or 'Z'.
2151 * @param[out] boundaryFlux Globally reduced flux through the boundary plane.
2152 * @param[out] planarAverageFlux Globally reduced plane-averaged flux.
2153 * @return PetscErrorCode 0 on success.
2154 */
2155static PetscErrorCode MeasureDrivenFluxes(UserCtx *user, char direction,
2156 PetscReal *boundaryFlux,
2157 PetscReal *planarAverageFlux)
2158{
2159 PetscErrorCode ierr;
2160 DMDALocalInfo info = user->info;
2161 PetscInt i, j, k;
2162
2163 PetscFunctionBeginUser;
2165
2166 // --- Get read-only access to necessary field data ---
2167 Cmpnts ***ucont;
2168 PetscReal ***nvert;
2169 ierr = DMDAVecGetArrayRead(user->fda, user->lUcont, (const Cmpnts***)&ucont); CHKERRQ(ierr);
2170 ierr = DMDAVecGetArrayRead(user->da, user->lNvert, (const PetscReal***)&nvert); CHKERRQ(ierr);
2171
2172 // --- Define local loop bounds ---
2173 PetscInt lo[3], hi[3];
2174 GetOwnedInteriorCellBounds(&info, lo, hi);
2175 PetscInt lxs = lo[0], lys = lo[1], lzs = lo[2], lxe = hi[0], lye = hi[1], lze = hi[2];
2176
2177 // --- Initialize local accumulators ---
2178 PetscReal localCurrentBoundaryFlux = 0.0;
2179 PetscReal localAveragePlanarVolumetricFluxTerm = 0.0;
2180
2181 // --- Measure local contributions to the two flux types, generalized by direction ---
2182 switch (direction) {
2183 case 'X':
2184 if (info.xs == 0) { // Only the rank on the negative face contributes to boundary flux
2185 i = 0;
2186 for (k = lzs; k < lze; k++) for (j = lys; j < lye; j++) {
2187 if (nvert[k][j][i + 1] < 0.1) localCurrentBoundaryFlux += ucont[k][j][i].x;
2188 }
2189 }
2190 for (i = info.xs; i < lxe; i++) {
2191 for (k = lzs; k < lze; k++) for (j = lys; j < lye; j++) {
2192 if (nvert[k][j][i + 1] < 0.1) localAveragePlanarVolumetricFluxTerm += ucont[k][j][i].x / (PetscReal)(info.mx - 1);
2193 }
2194 }
2195 break;
2196 case 'Y':
2197 if (info.ys == 0) {
2198 j = 0;
2199 for (k = lzs; k < lze; k++) for (i = lxs; i < lxe; i++) {
2200 if (nvert[k][j + 1][i] < 0.1) localCurrentBoundaryFlux += ucont[k][j][i].y;
2201 }
2202 }
2203 for (j = info.ys; j < lye; j++) {
2204 for (k = lzs; k < lze; k++) for (i = lxs; i < lxe; i++) {
2205 if (nvert[k][j + 1][i] < 0.1) localAveragePlanarVolumetricFluxTerm += ucont[k][j][i].y / (PetscReal)(info.my - 1);
2206 }
2207 }
2208 break;
2209 case 'Z':
2210 if (info.zs == 0) {
2211 k = 0;
2212 for (j = lys; j < lye; j++) for (i = lxs; i < lxe; i++) {
2213 if (nvert[k + 1][j][i] < 0.1) localCurrentBoundaryFlux += ucont[k][j][i].z;
2214 }
2215 }
2216 for (k = info.zs; k < lze; k++) {
2217 for (j = lys; j < lye; j++) for (i = lxs; i < lxe; i++) {
2218 if (nvert[k + 1][j][i] < 0.1) localAveragePlanarVolumetricFluxTerm += ucont[k][j][i].z / (PetscReal)(info.mz - 1);
2219 }
2220 }
2221 break;
2222 default:
2223 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG,
2224 "MeasureDrivenFluxes received an unknown driven direction '%c'.", direction);
2225 }
2226
2227 // --- Release array access as soon as possible ---
2228 ierr = DMDAVecRestoreArrayRead(user->fda, user->lUcont, (const Cmpnts***)&ucont); CHKERRQ(ierr);
2229 ierr = DMDAVecRestoreArrayRead(user->da, user->lNvert, (const PetscReal***)&nvert); CHKERRQ(ierr);
2230
2231 // --- Perform global reductions to get the final flux values ---
2232 ierr = MPI_Allreduce(&localCurrentBoundaryFlux, boundaryFlux, 1, MPI_DOUBLE, MPI_SUM, PETSC_COMM_WORLD); CHKERRQ(ierr);
2233 ierr = MPI_Allreduce(&localAveragePlanarVolumetricFluxTerm, planarAverageFlux, 1, MPI_DOUBLE, MPI_SUM, PETSC_COMM_WORLD); CHKERRQ(ierr);
2234
2236 PetscFunctionReturn(0);
2237}
2238
2239// ===============================================================================
2240//
2241// HANDLER IMPLEMENTATION: PERIODIC DRIVEN CONSTANT FLUX
2242// (Corresponds to BC_HANDLER_PERIODIC_DRIVEN_CONSTANT_FLUX)
2243//
2244// ===============================================================================
2245
2246// --- 1. FORWARD DECLARATIONS & PRIVATE DATA ---
2247
2248// Forward declarations for the static functions that implement this handler's behavior.
2249static PetscErrorCode Initialize_PeriodicDrivenConstant(BoundaryCondition *self, BCContext *ctx);
2250static PetscErrorCode PreStep_PeriodicDrivenConstant(BoundaryCondition *self, BCContext *ctx, PetscReal *in, PetscReal *out);
2251static PetscErrorCode Apply_PeriodicDrivenConstant(BoundaryCondition *self, BCContext *ctx);
2252static PetscErrorCode Destroy_PeriodicDrivenConstant(BoundaryCondition *self);
2253
2254/**
2255 * @brief Private data structure shared by both periodic driven-flux handlers.
2256 *
2257 * `constant_flux` fills `targetVolumetricFlux` from the bcs file at
2258 * initialization; `initial_flux` latches it from the starting field at the
2259 * first PreStep. Everything downstream of the target is identical, so both
2260 * handlers reuse this struct and the PreStep/Apply/Destroy implementations
2261 * below.
2262 */
2263typedef struct {
2264 char direction; // 'X', 'Y', or 'Z', determined at initialization.
2265 PetscReal targetVolumetricFlux; // The target flux this controller drives to.
2266 PetscBool isMasterController; // Flag: PETSC_TRUE only for the handler on the negative face.
2267 PetscBool enforceSeamFlux; // Flag: PETSC_TRUE to add the seam-flux correction into Ucont.
2268 PetscInt lastBulkCorrectionStep; // Physical step at which the momentum source was last set (-1 = never).
2270
2271
2272// --- 2. HANDLER CONSTRUCTOR ---
2273
2274/**
2275 * @brief Implementation of \ref Create_PeriodicDrivenConstant().
2276 * @see Create_PeriodicDrivenConstant()
2277 */
2279{
2280 PetscErrorCode ierr;
2281 PetscFunctionBeginUser;
2283
2284 PetscCheck(bc, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "BoundaryCondition is NULL");
2285
2286 // --- Allocate the private data structure ---
2287 DrivenFluxData *data = NULL;
2288 ierr = PetscNew(&data); CHKERRQ(ierr);
2289 // Initialize fields to safe default values
2290 data->direction = ' ';
2291 data->targetVolumetricFlux = 0.0;
2292 data->isMasterController = PETSC_FALSE;
2293 data->enforceSeamFlux = PETSC_FALSE;
2294 data->lastBulkCorrectionStep = -1;
2295
2296 // Attach the private data to the generic handler object
2297 bc->data = (void*)data;
2298
2299 // --- Configure the handler's properties and methods ---
2300
2301 // Set priority: Using BC_PRIORITY_INLET ensures this handler's PreStep runs
2302 // before other handlers (like outlets) that might depend on its calculations.
2303 // It is the caller's responsibility that there are no Inlets called along with driven periodic to avoid clash.
2305
2306 // Assign the function pointers to the implementations in this file.
2310 bc->PostStep = NULL; // This handler has no action after the main solver step.
2311 bc->UpdateUbcs = NULL; // The boundary value is not flow-dependent (it's periodic).
2313
2315 PetscFunctionReturn(0);
2316}
2317
2318/**
2319 * @brief Initialize constant forcing data for a periodically driven boundary.
2320 */
2322{
2323 PetscErrorCode ierr;
2324 DrivenFluxData *data = (DrivenFluxData*)self->data;
2325 BCFace face_id = ctx->face_id;
2326 UserCtx* user = ctx->user;
2327
2328 PetscFunctionBeginUser;
2330
2331 LOG_ALLOW(LOCAL, LOG_DEBUG, "Initializing PERIODIC_DRIVEN_CONSTANT_FLUX handler on Face %s...\n", BCFaceToString(face_id));
2332
2333 // --- 1. Validation: Ensure the mathematical type is PERIODIC ---
2334 if (user->boundary_faces[face_id].mathematical_type != PERIODIC) {
2335 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT,
2336 "Configuration Error: Handler PERIODIC_DRIVEN_CONSTANT_FLUX on Face %s must be applied to a face with mathematical_type PERIODIC.",
2337 BCFaceToString(face_id));
2338 }
2339
2340 // --- 2. Role Assignment: Determine direction and master status ---
2341 data->isMasterController = PETSC_FALSE;
2342 switch (face_id) {
2343 case BC_FACE_NEG_X: data->direction = 'X'; data->isMasterController = PETSC_TRUE; break;
2344 case BC_FACE_POS_X: data->direction = 'X'; break;
2345 case BC_FACE_NEG_Y: data->direction = 'Y'; data->isMasterController = PETSC_TRUE; break;
2346 case BC_FACE_POS_Y: data->direction = 'Y'; break;
2347 case BC_FACE_NEG_Z: data->direction = 'Z'; data->isMasterController = PETSC_TRUE; break;
2348 case BC_FACE_POS_Z: data->direction = 'Z'; break;
2349 }
2350
2351 // --- 3. Parameter Parsing (Master Controller only) ---
2352 if (data->isMasterController) {
2353 PetscBool found;
2354
2355 // Attempt to read the 'target_flux' parameter from the bcs.run file.
2356 ierr = GetBCParamReal(user->boundary_faces[face_id].params, "target_flux",
2357 &data->targetVolumetricFlux, &found); CHKERRQ(ierr);
2358
2359 // If the required parameter is not found, halt with an informative error.
2360 if (!found) {
2361 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT,
2362 "Configuration Error: Handler PERIODIC_DRIVEN_CONSTANT_FLUX on Face %s requires a 'target_flux' parameter in the bcs file (e.g., target_flux=10.0).",
2363 BCFaceToString(face_id));
2364 }
2365
2366 LOG_ALLOW(GLOBAL, LOG_INFO, "Driven Flow (Dir %c): Constant target volumetric flux set to %le.\n",
2367 data->direction, data->targetVolumetricFlux);
2368
2369 // Store the target flux in the simulation context, where the driven-flow
2370 // controller and its diagnostics read it.
2372 // The target is fixed for the run from here on; see the flag's comment in
2373 // variables.h for how initial_flux uses the same latch.
2374 user->simCtx->drivenFluxTargetLatched = PETSC_TRUE;
2375 }
2376
2377 PetscBool trimfound;
2378 // Optional seam-flux enforcement; accepts the deprecated `apply_trim` spelling.
2379 ierr = GetDrivenSeamFluxFlag(user->boundary_faces[face_id].params,
2380 &data->enforceSeamFlux, &trimfound); CHKERRQ(ierr);
2381
2382 if(!trimfound) LOG_ALLOW(GLOBAL,LOG_DEBUG,"Seam-flux enforcement not specified, defaults to %s.\n",data->enforceSeamFlux? "True":"False");
2383 // Enforcing the seam flux adds a trim re-measured every pass, so the pass must repeat.
2384 self->needs_repeat_pass = data->enforceSeamFlux;
2385
2387 PetscFunctionReturn(0);
2388}
2389
2390/**
2391 * @brief Prepare constant periodic-driving data before the solver step.
2392 */
2394 PetscReal *local_inflow_contribution,
2395 PetscReal *local_outflow_contribution)
2396{
2397 PetscErrorCode ierr;
2398 DrivenFluxData *data = (DrivenFluxData*)self->data;
2399 UserCtx* user = ctx->user;
2400 SimCtx* simCtx = user->simCtx;
2401
2402 PetscFunctionBeginUser;
2404
2405 // --- Master Check: Only the handler on the negative face performs calculations ---
2406 if (!data->isMasterController) {
2408 PetscFunctionReturn(0);
2409 }
2410
2411 // The controller senses two fluxes; see MeasureDrivenFluxes() for what each
2412 // one is for and why the controller needs both.
2413 char direction = data->direction;
2414 PetscReal globalCurrentBoundaryFlux, globalAveragePlanarVolumetricFlux;
2415 ierr = MeasureDrivenFluxes(user, direction, &globalCurrentBoundaryFlux,
2416 &globalAveragePlanarVolumetricFlux); CHKERRQ(ierr);
2417
2418 // --- Get cross-sectional area using the dedicated geometry function ---
2419 Cmpnts ignored_center;
2420 PetscReal globalBoundaryArea;
2421 BCFace neg_face_id = (direction == 'X') ? BC_FACE_NEG_X : (direction == 'Y') ? BC_FACE_NEG_Y : BC_FACE_NEG_Z;
2422 ierr = CalculateFaceCenterAndArea(user, neg_face_id, &ignored_center, &globalBoundaryArea); CHKERRQ(ierr);
2423
2424 // --- Calculate the two correction terms ---
2425 //
2426 // These are refreshed on DIFFERENT cadences, and the difference matters.
2427 //
2428 // ApplyBoundaryConditions() runs BoundarySystem_ExecuteStep() -- and hence
2429 // this PreStep -- three times per call, and it is itself called once per
2430 // Jameson RK stage under the Picard solver and once per residual evaluation
2431 // under Newton-Krylov. So "per PreStep" is emphatically not "per timestep".
2432 //
2433 // - bulkVelocityCorrection scales the momentum source in ComputeRHS. Both
2434 // momentum solvers are built on it being FROZEN across a timestep: the
2435 // Picard shadow-Jacobian estimate treats the body force as a constant
2436 // forcing with zero velocity Jacobian, and the Newton solve needs a
2437 // source that does not drift between residual evaluations. It is
2438 // therefore computed once per physical step, from the field at the start
2439 // of that step, and held.
2440 //
2441 // - boundaryVelocityCorrection is the tactical trim applied to the
2442 // boundary fluxes in Apply(). It is deliberately re-measured on every
2443 // pass: Apply() accumulates it into Ucont, and re-measuring is what makes
2444 // that accumulation self-limiting as the seam converges. Freezing it
2445 // would make repeated Apply() calls add the same trim over and over.
2446 if (globalBoundaryArea > 1.0e-12) {
2447 if (data->lastBulkCorrectionStep != simCtx->step) {
2448 simCtx->bulkVelocityCorrection = (data->targetVolumetricFlux - globalAveragePlanarVolumetricFlux) / globalBoundaryArea;
2449 simCtx->drivenFluxMeasured = globalAveragePlanarVolumetricFlux;
2450 simCtx->drivenFluxArea = globalBoundaryArea;
2451 data->lastBulkCorrectionStep = simCtx->step;
2452 }
2453 simCtx->boundaryVelocityCorrection = (data->targetVolumetricFlux - globalCurrentBoundaryFlux) / globalBoundaryArea;
2454 } else {
2455 simCtx->bulkVelocityCorrection = 0.0;
2456 simCtx->boundaryVelocityCorrection = 0.0;
2457 data->lastBulkCorrectionStep = simCtx->step;
2458 }
2459
2460 LOG_ALLOW(GLOBAL, LOG_INFO, "Driven Flow Controller Update (Dir %c):\n", data->direction);
2461 LOG_ALLOW(GLOBAL, LOG_INFO, " - Target Volumetric Flux: %.6e\n", data->targetVolumetricFlux);
2462 LOG_ALLOW(GLOBAL, LOG_INFO, " - Avg Planar Volumetric Flux (Stable): %.6e\n", globalAveragePlanarVolumetricFlux);
2463 LOG_ALLOW(GLOBAL, LOG_INFO, " - Boundary Flux (Fast): %.6e\n", globalCurrentBoundaryFlux);
2464 LOG_ALLOW(GLOBAL, LOG_INFO, " - Bulk Velocity Correction: %.6e (For Momentum Source)\n", simCtx->bulkVelocityCorrection);
2465 LOG_ALLOW(GLOBAL, LOG_INFO, " - Boundary Velocity Correction: %.6e (For Boundary Trim)\n", simCtx->boundaryVelocityCorrection);
2466
2467 // Suppress unused parameter warnings for this handler
2468 (void)local_inflow_contribution;
2469 (void)local_outflow_contribution;
2470
2472 PetscFunctionReturn(0);
2473}
2474
2475/**
2476 * @brief Apply the configured constant driving term to the periodic boundary.
2477 */
2479{
2480 PetscErrorCode ierr;
2481 DrivenFluxData *data = (DrivenFluxData*)self->data;
2482 UserCtx* user = ctx->user;
2483 BCFace face_id = ctx->face_id;
2484 PetscBool can_service;
2485
2486 PetscFunctionBeginUser;
2488
2489 // Check if this rank owns part of this boundary face
2490 ierr = CanRankServiceFace(&user->info, user->IM, user->JM, user->KM, face_id, &can_service); CHKERRQ(ierr);
2491 if (!can_service) {
2493 PetscFunctionReturn(0);
2494 }
2495
2496 // If the correction is negligible, no work is needed.
2497 if (PetscAbsReal(user->simCtx->boundaryVelocityCorrection) < 1e-12) {
2499 PetscFunctionReturn(0);
2500 }
2501
2502 LOG_ALLOW(LOCAL, LOG_TRACE, "Apply_PeriodicDrivenConstant: Applying boundary trim on Face %s...\n", BCFaceToString(face_id));
2503
2504 // --- Get read/write access to necessary arrays ---
2505 DMDALocalInfo info = user->info;
2506 Cmpnts ***ucont, ***uch, ***csi, ***eta, ***zet;
2507 PetscReal ***nvert;
2508
2509 ierr = DMDAVecGetArray(user->fda, user->Ucont, &ucont); CHKERRQ(ierr);
2510 ierr = DMDAVecGetArray(user->fda, user->Bcs.Uch, &uch); CHKERRQ(ierr);
2511 ierr = DMDAVecGetArrayRead(user->fda, user->lCsi, (const Cmpnts***)&csi); CHKERRQ(ierr);
2512 ierr = DMDAVecGetArrayRead(user->fda, user->lEta, (const Cmpnts***)&eta); CHKERRQ(ierr);
2513 ierr = DMDAVecGetArrayRead(user->fda, user->lZet, (const Cmpnts***)&zet); CHKERRQ(ierr);
2514 ierr = DMDAVecGetArrayRead(user->da, user->lNvert, (const PetscReal***)&nvert); CHKERRQ(ierr);
2515
2516 PetscInt lo[3], hi[3];
2517 GetOwnedInteriorCellBounds(&info, lo, hi);
2518 PetscInt lxs = lo[0], lys = lo[1], lzs = lo[2], lxe = hi[0], lye = hi[1], lze = hi[2];
2519
2520 // --- Apply correction to the appropriate face and velocity component ---
2521 switch (face_id) {
2522 case BC_FACE_NEG_X: case BC_FACE_POS_X: {
2523 PetscInt i_face = (face_id == BC_FACE_NEG_X) ? info.xs : info.mx - 2;
2524 PetscInt i_nvert = (face_id == BC_FACE_NEG_X) ? info.xs + 1 : info.mx - 2;
2525
2526 for (PetscInt k = lzs; k < lze; k++) for (PetscInt j = lys; j < lye; j++) {
2527 if (nvert[k][j][i_nvert] < 0.1) {
2528 PetscReal faceArea = sqrt(csi[k][j][i_face].x*csi[k][j][i_face].x + csi[k][j][i_face].y*csi[k][j][i_face].y + csi[k][j][i_face].z*csi[k][j][i_face].z);
2529 PetscReal fluxTrim = user->simCtx->boundaryVelocityCorrection * faceArea;
2530 if(data->enforceSeamFlux) ucont[k][j][i_face].x += fluxTrim;
2531 uch[k][j][i_face].x = fluxTrim; // Store correction for diagnostics
2532 }
2533 }
2534 } break;
2535
2536 case BC_FACE_NEG_Y: case BC_FACE_POS_Y: {
2537 PetscInt j_face = (face_id == BC_FACE_NEG_Y) ? info.ys : info.my - 2;
2538 PetscInt j_nvert = (face_id == BC_FACE_NEG_Y) ? info.ys + 1 : info.my - 2;
2539
2540 for (PetscInt k = lzs; k < lze; k++) for (PetscInt i = lxs; i < lxe; i++) {
2541 if (nvert[k][j_nvert][i] < 0.1) {
2542 PetscReal faceArea = sqrt(eta[k][j_face][i].x*eta[k][j_face][i].x + eta[k][j_face][i].y*eta[k][j_face][i].y + eta[k][j_face][i].z*eta[k][j_face][i].z);
2543 PetscReal fluxTrim = user->simCtx->boundaryVelocityCorrection * faceArea;
2544 if(data->enforceSeamFlux) ucont[k][j_face][i].y += fluxTrim;
2545 uch[k][j_face][i].y = fluxTrim;
2546 }
2547 }
2548 } break;
2549
2550 case BC_FACE_NEG_Z: case BC_FACE_POS_Z: {
2551 PetscInt k_face = (face_id == BC_FACE_NEG_Z) ? info.zs : info.mz - 2;
2552 PetscInt k_nvert = (face_id == BC_FACE_NEG_Z) ? info.zs + 1 : info.mz - 2;
2553
2554 for (PetscInt j = lys; j < lye; j++) for (PetscInt i = lxs; i < lxe; i++) {
2555 if (nvert[k_nvert][j][i] < 0.1) {
2556 PetscReal faceArea = sqrt(zet[k_face][j][i].x*zet[k_face][j][i].x + zet[k_face][j][i].y*zet[k_face][j][i].y + zet[k_face][j][i].z*zet[k_face][j][i].z);
2557 PetscReal fluxTrim = user->simCtx->boundaryVelocityCorrection * faceArea;
2558 if(data->enforceSeamFlux) ucont[k_face][j][i].z += fluxTrim;
2559 uch[k_face][j][i].z = fluxTrim;
2560 }
2561 }
2562 } break;
2563 }
2564
2565 // --- Restore arrays ---
2566 ierr = DMDAVecRestoreArray(user->fda, user->Ucont, &ucont); CHKERRQ(ierr);
2567 ierr = DMDAVecRestoreArray(user->fda, user->Bcs.Uch, &uch); CHKERRQ(ierr);
2568 ierr = DMDAVecRestoreArrayRead(user->fda, user->lCsi, (const Cmpnts***)&csi); CHKERRQ(ierr);
2569 ierr = DMDAVecRestoreArrayRead(user->fda, user->lEta, (const Cmpnts***)&eta); CHKERRQ(ierr);
2570 ierr = DMDAVecRestoreArrayRead(user->fda, user->lZet, (const Cmpnts***)&zet); CHKERRQ(ierr);
2571 ierr = DMDAVecRestoreArrayRead(user->da, user->lNvert, (const PetscReal***)&nvert); CHKERRQ(ierr);
2572
2574 PetscFunctionReturn(0);
2575}
2576
2577/**
2578 * @brief Release resources owned by the constant periodic-driving boundary.
2579 */
2581{
2582 PetscFunctionBeginUser;
2584
2585 // Check that the handler object and its private data pointer are valid before trying to free.
2586 if (self && self->data) {
2587 // The private data was allocated with PetscNew(), so it must be freed with PetscFree().
2588 PetscFree(self->data);
2589
2590 // It is good practice to nullify the pointer after freeing to prevent
2591 // any accidental use of the dangling pointer (use-after-free).
2592 self->data = NULL;
2593
2594 LOG_ALLOW(LOCAL, LOG_TRACE, "Destroy_PeriodicDrivenConstant: Private data freed successfully.\n");
2595 }
2596
2598 PetscFunctionReturn(0);
2599}
2600
2601
2602// ===============================================================================
2603//
2604// HANDLER IMPLEMENTATION: PERIODIC DRIVEN INITIAL FLUX
2605// (Corresponds to BC_HANDLER_PERIODIC_DRIVEN_INITIAL_FLUX)
2606//
2607// Identical to the CONSTANT_FLUX handler except for where the target comes
2608// from: this one measures the volumetric flux of the field the run starts
2609// with and then holds it, so it takes no `target_flux` parameter. Once the
2610// target is latched the two handlers behave the same, so PreStep delegates
2611// to the constant implementation and Apply/Destroy are shared outright.
2612//
2613// ===============================================================================
2614
2615// --- 1. FORWARD DECLARATIONS ---
2616
2617static PetscErrorCode Initialize_PeriodicDrivenInitial(BoundaryCondition *self, BCContext *ctx);
2618static PetscErrorCode PreStep_PeriodicDrivenInitial(BoundaryCondition *self, BCContext *ctx, PetscReal *in, PetscReal *out);
2619
2620// --- 2. HANDLER CONSTRUCTOR ---
2621
2622/**
2623 * @brief Implementation of \ref Create_PeriodicDrivenInitial().
2624 * @see Create_PeriodicDrivenInitial()
2625 */
2627{
2628 PetscErrorCode ierr;
2629 PetscFunctionBeginUser;
2631
2632 PetscCheck(bc, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "BoundaryCondition is NULL");
2633
2634 // --- Allocate the private data structure ---
2635 DrivenFluxData *data = NULL;
2636 ierr = PetscNew(&data); CHKERRQ(ierr);
2637 // Initialize fields to safe default values
2638 data->direction = ' ';
2639 data->targetVolumetricFlux = 0.0;
2640 data->isMasterController = PETSC_FALSE;
2641 data->enforceSeamFlux = PETSC_FALSE;
2642 data->lastBulkCorrectionStep = -1;
2643
2644 // Attach the private data to the generic handler object
2645 bc->data = (void*)data;
2646
2647 // --- Configure the handler's properties and methods ---
2648
2649 // Same priority reasoning as the constant-flux handler: PreStep must run
2650 // before any handler that depends on the controller's corrections.
2652
2655 bc->Apply = Apply_PeriodicDrivenConstant; // Boundary trim is target-agnostic.
2656 bc->PostStep = NULL; // This handler has no action after the main solver step.
2657 bc->UpdateUbcs = NULL; // The boundary value is not flow-dependent (it's periodic).
2658 bc->Destroy = Destroy_PeriodicDrivenConstant; // Same private data layout.
2659
2661 PetscFunctionReturn(0);
2662}
2663
2664/**
2665 * @brief Initialize forcing data for a periodic boundary driven to its initial flux.
2666 *
2667 * @note The target itself is NOT measured here. Boundary handlers are
2668 * initialized before `InitializeEulerianState()` runs, so at this point
2669 * `Ucont` still holds zeros. The measurement is deferred to the first
2670 * PreStep, by which time either the initial condition has been applied or
2671 * the restart target has been restored from the checkpoint manifest.
2672 */
2674{
2675 PetscErrorCode ierr;
2676 DrivenFluxData *data = (DrivenFluxData*)self->data;
2677 BCFace face_id = ctx->face_id;
2678 UserCtx* user = ctx->user;
2679
2680 PetscFunctionBeginUser;
2682
2683 LOG_ALLOW(LOCAL, LOG_DEBUG, "Initializing PERIODIC_DRIVEN_INITIAL_FLUX handler on Face %s...\n", BCFaceToString(face_id));
2684
2685 // --- 1. Validation: Ensure the mathematical type is PERIODIC ---
2686 if (user->boundary_faces[face_id].mathematical_type != PERIODIC) {
2687 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT,
2688 "Configuration Error: Handler PERIODIC_DRIVEN_INITIAL_FLUX on Face %s must be applied to a face with mathematical_type PERIODIC.",
2689 BCFaceToString(face_id));
2690 }
2691
2692 // --- 2. Role Assignment: Determine direction and master status ---
2693 data->isMasterController = PETSC_FALSE;
2694 switch (face_id) {
2695 case BC_FACE_NEG_X: data->direction = 'X'; data->isMasterController = PETSC_TRUE; break;
2696 case BC_FACE_POS_X: data->direction = 'X'; break;
2697 case BC_FACE_NEG_Y: data->direction = 'Y'; data->isMasterController = PETSC_TRUE; break;
2698 case BC_FACE_POS_Y: data->direction = 'Y'; break;
2699 case BC_FACE_NEG_Z: data->direction = 'Z'; data->isMasterController = PETSC_TRUE; break;
2700 case BC_FACE_POS_Z: data->direction = 'Z'; break;
2701 }
2702
2703 // --- 3. Parameter Parsing (Master Controller only) ---
2704 if (data->isMasterController) {
2705 PetscReal unused_flux;
2706 PetscBool found;
2707
2708 // This handler derives its own target, so an explicit one is a config error
2709 // rather than something to silently ignore. Users who want to prescribe the
2710 // flux should select the `constant_flux` handler instead.
2711 ierr = GetBCParamReal(user->boundary_faces[face_id].params, "target_flux",
2712 &unused_flux, &found); CHKERRQ(ierr);
2713 if (found) {
2714 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT,
2715 "Configuration Error: Handler PERIODIC_DRIVEN_INITIAL_FLUX on Face %s takes no 'target_flux' parameter; "
2716 "it measures the flux of the initial condition and holds that. Use handler 'constant_flux' to prescribe a target.",
2717 BCFaceToString(face_id));
2718 }
2719
2720 LOG_ALLOW(GLOBAL, LOG_INFO, "Driven Flow (Dir %c): target volumetric flux will be latched from the initial state.\n",
2721 data->direction);
2722 }
2723
2724 PetscBool trimfound;
2725 // Optional seam-flux enforcement; accepts the deprecated `apply_trim` spelling.
2726 ierr = GetDrivenSeamFluxFlag(user->boundary_faces[face_id].params,
2727 &data->enforceSeamFlux, &trimfound); CHKERRQ(ierr);
2728
2729 if(!trimfound) LOG_ALLOW(GLOBAL,LOG_DEBUG,"Seam-flux enforcement not specified, defaults to %s.\n",data->enforceSeamFlux? "True":"False");
2730 // Enforcing the seam flux adds a trim re-measured every pass, so the pass must repeat.
2731 self->needs_repeat_pass = data->enforceSeamFlux;
2732
2734 PetscFunctionReturn(0);
2735}
2736
2737/**
2738 * @brief Latch the initial-state flux once, then drive to it like a constant target.
2739 *
2740 * @details The latch is one-shot and guarded by `simCtx->drivenFluxTargetLatched`:
2741 * - Fresh start: the flag is false and `Ucont` now holds the initial
2742 * condition, so the plane-averaged flux is measured and stored.
2743 * - Restart: `ReadSimulationFields()` restored both the target and the
2744 * flag from the checkpoint manifest, so the original target survives
2745 * instead of being re-measured from a drifted field.
2746 */
2748 PetscReal *local_inflow_contribution,
2749 PetscReal *local_outflow_contribution)
2750{
2751 PetscErrorCode ierr;
2752 DrivenFluxData *data = (DrivenFluxData*)self->data;
2753 SimCtx* simCtx = ctx->user->simCtx;
2754
2755 PetscFunctionBeginUser;
2757
2758 if (data->isMasterController) {
2759 if (!simCtx->drivenFluxTargetLatched) {
2760 PetscReal boundaryFlux, planarAverageFlux;
2761
2762 /* Boundary handlers are also exercised once during setup, from
2763 * FinalizeBlockState(), and at that point the initial condition has
2764 * been written to Ucont but not yet scattered into the ghosted
2765 * lUcont that MeasureDrivenFluxes() reads. Latching there would
2766 * record a target of zero. Setup runs with step == StartStep, so
2767 * wait for the first PreStep of the first real timestep: by then
2768 * lUcont holds the initial condition (or, on a restart, the state
2769 * the restored target already describes). Do no work at all until
2770 * then, so no bogus correction is derived from a zero target. */
2771 if (simCtx->step <= simCtx->StartStep) {
2772 simCtx->bulkVelocityCorrection = 0.0;
2773 simCtx->boundaryVelocityCorrection = 0.0;
2775 PetscFunctionReturn(0);
2776 }
2777
2778 ierr = MeasureDrivenFluxes(ctx->user, data->direction,
2779 &boundaryFlux, &planarAverageFlux); CHKERRQ(ierr);
2780
2781 simCtx->targetVolumetricFlux = planarAverageFlux;
2782 simCtx->drivenFluxTargetLatched = PETSC_TRUE;
2783
2785 "Driven Flow (Dir %c): latched initial volumetric flux %.6e as the target.\n",
2786 data->direction, planarAverageFlux);
2787 }
2788 // Keep the handler's copy in step with the authoritative value in SimCtx,
2789 // which is also where a restart deposits the restored target.
2791 }
2792
2793 ierr = PreStep_PeriodicDrivenConstant(self, ctx,
2794 local_inflow_contribution,
2795 local_outflow_contribution); CHKERRQ(ierr);
2796
2798 PetscFunctionReturn(0);
2799}
static Cmpnts EvaluateMovingWallVelocity(const BoundaryCondition *self, BCFace face_id, PetscInt i, PetscInt j, PetscInt k, Cmpnts metric, PetscReal sign, Cmpnts interior)
A moving wall's boundary velocity: the source's, with any part along the face removed,...
PetscBool enforceSeamFlux
static PetscInt PrescribedSlot(const InletPrescribedVelocityData *data, PetscInt i, PetscInt j, PetscInt k)
Index of the owned slot (i, j, k) in a prescribed-velocity inlet's per-slot arrays.
static PetscErrorCode Destroy_OutletConservation(BoundaryCondition *self)
Release the outlet-conservation handler's clip state.
static PetscErrorCode Apply_InletVelocity(BoundaryCondition *self, BCContext *ctx)
Applies the prescribed inlet velocity through the common face-layout path.
static PetscErrorCode Apply_WallNoSlip(BoundaryCondition *self, BCContext *ctx)
Apply no-slip velocity values to wall-adjacent cells for this boundary condition.
static PetscErrorCode OpenPrescribedProfile(InletPrescribedVelocityData *data, UserCtx *user, BCFace face_id)
Open the face's PICSLICE and read a lone frame, as the velocity itself or, under expressions,...
static PetscErrorCode ApplyFaceBoundaryVelocity(BoundaryCondition *self, BCContext *ctx, FaceBoundaryVelocityRule rule)
Sets a handler's boundary velocity and the face flux it implies on one face.
PetscBool isMasterController
static PetscErrorCode GetProfileFileExpectedDims(UserCtx *user, BCFace face_id, PetscInt *n1, PetscInt *n2)
Computes the expected PICSLICE dimensions for an inlet face.
PetscErrorCode Create_WallFreeSlip(BoundaryCondition *bc)
Implementation of Create_WallFreeSlip().
static PetscErrorCode Apply_WallFreeSlip(BoundaryCondition *self, BCContext *ctx)
Apply free-slip boundary values to wall-adjacent cells for this boundary condition.
static PetscErrorCode LoadPrescribedFrame(InletPrescribedVelocityData *data, PetscInt frame, Cmpnts *target)
Read one frame of the face's PICSLICE into this rank's slots, moving the file there.
static PetscErrorCode Apply_WallMoving(BoundaryCondition *self, BCContext *ctx)
Applies a moving wall's velocity through the path every prescribed face shares.
PicurvVelocitySource stress[2]
PetscErrorCode Create_WallMoving(BoundaryCondition *bc)
Implementation of Create_WallMoving().
PetscInt lastBulkCorrectionStep
static PetscErrorCode Apply_OutletConservation(BoundaryCondition *self, BCContext *ctx)
(Handler Action) Applies mass conservation correction to the outlet face.
PicurvSourceFaceSlots slots
PicurvVelocitySource source
static PetscErrorCode Initialize_InletPrescribedVelocity(BoundaryCondition *self, BCContext *ctx)
Compile the source named by the face's source_id parameter, with its bulk velocity or flow rate if an...
static PetscErrorCode PrescribedFaceSums(const InletPrescribedVelocityData *data, UserCtx *user, BCFace face_id, PetscReal local[4])
This rank's area-weighted sums over the face, physical: the source's normal speed,...
static PetscErrorCode Apply_PeriodicDrivenConstant(BoundaryCondition *self, BCContext *ctx)
Apply the configured constant driving term to the periodic boundary.
static PetscErrorCode StepInletFluctuation(InletPrescribedVelocityData *data, UserCtx *user, BCFace face_id)
This step's synthetic fluctuation at every owned slot of an inlet.
OutletClipPassMode
What one OutletClipPass() over the owned outlet elements does.
@ OUTLET_CLIP_MEASURE
@ OUTLET_CLIP_WRITE
@ OUTLET_CLIP_DECIDE
static Cmpnts EvaluateInletCartesianVelocity(const BoundaryCondition *self, BCFace face_id, PetscInt i, PetscInt j, PetscInt k, Cmpnts metric, PetscReal sign, Cmpnts interior)
Prescribed velocity at one inlet face slot, as a Cartesian vector.
static PetscErrorCode Initialize_PeriodicDrivenConstant(BoundaryCondition *self, BCContext *ctx)
Initialize constant forcing data for a periodically driven boundary.
PetscErrorCode Create_PeriodicGeometric(BoundaryCondition *bc)
Implementation of Create_PeriodicGeometric().
PetscErrorCode Validate_DrivenFlowConfiguration(UserCtx *user)
Implementation of Validate_DrivenFlowConfiguration().
Definition BC_Handlers.c:15
static PetscErrorCode InterpolatePrescribedFrames(InletPrescribedVelocityData *data, BCFace face_id, PetscReal physical_time)
Set the staged data at a time: linear between the two frames around it, the first at t = 0.
Cmpnts(* FaceBoundaryVelocityRule)(const BoundaryCondition *self, BCFace face_id, PetscInt i, PetscInt j, PetscInt k, Cmpnts metric, PetscReal sign, Cmpnts interior)
Cartesian boundary velocity one handler prescribes at one boundary face slot.
Definition BC_Handlers.c:97
#define INFLOW_LATTICE_PAD
Face cells the synthetic-inflow draw lattice extends beyond each edge; a filter half-width may not ex...
static PetscErrorCode PostStep_InletFlux(BoundaryCondition *self, BCContext *ctx, PetscReal *in, PetscReal *out)
Adds the inlet face's applied flux, the sum of its normal Ucont, to the inflow.
static PetscErrorCode Initialize_PeriodicDrivenInitial(BoundaryCondition *self, BCContext *ctx)
Initialize forcing data for a periodic boundary driven to its initial flux.
PetscErrorCode Create_PeriodicDrivenInitial(BoundaryCondition *bc)
Implementation of Create_PeriodicDrivenInitial().
static PetscErrorCode Destroy_PeriodicDrivenConstant(BoundaryCondition *self)
Release resources owned by the constant periodic-driving boundary.
PetscErrorCode Create_PeriodicDrivenConstant(BoundaryCondition *bc)
Implementation of Create_PeriodicDrivenConstant().
static PetscErrorCode ReadPicSliceFrame(InletPrescribedVelocityData *data)
Reads the frame at the file's position into file_values, validating every value: finite,...
static PetscErrorCode OpenPicSlice(InletPrescribedVelocityData *data, PetscInt expected_n1, PetscInt expected_n2)
Opens a canonical PICSLICE file and reads its header.
PetscErrorCode Create_InletPrescribedVelocity(BoundaryCondition *bc)
Implementation of Create_InletPrescribedVelocity().
static PetscErrorCode MeasureDrivenFluxes(UserCtx *user, char direction, PetscReal *boundaryFlux, PetscReal *planarAverageFlux)
Measure the two volumetric fluxes the driven-flow controller senses.
static PetscErrorCode Destroy_InletPrescribedVelocity(BoundaryCondition *self)
Release the compiled source and the per-slot arrays.
PetscErrorCode LogPrescribedFlowDiagnostics(UserCtx *user)
Implementation of LogPrescribedFlowDiagnostics().
static Cmpnts WallNoSlipVelocity(const BoundaryCondition *self, BCFace face_id, PetscInt i, PetscInt j, PetscInt k, Cmpnts metric, PetscReal sign, Cmpnts interior)
The no-slip wall's boundary velocity: the wall's own, which is at rest.
static PetscErrorCode PostStep_OutletConservation(BoundaryCondition *self, BCContext *ctx, PetscReal *in, PetscReal *out)
Update outlet-conservation state after a completed solver step.
static PetscErrorCode OutletClipPass(UserCtx *user, BCFace face_id, OutletConservationData *data, OutletClipPassMode mode, PetscReal correction, PetscReal psi, PetscReal sums[3])
One pass over this rank's elements of an outlet face for the backflow clip.
static Cmpnts WallFreeSlipVelocity(const BoundaryCondition *self, BCFace face_id, PetscInt i, PetscInt j, PetscInt k, Cmpnts metric, PetscReal sign, Cmpnts interior)
The free-slip wall's boundary velocity: the adjacent velocity, less its normal part.
static PetscErrorCode BuildInletFluctuation(InletPrescribedVelocityData *data, UserCtx *user)
Prepare an inlet's synthetic fluctuations once its slots exist: filter widths from the face's mean sp...
PetscErrorCode Create_WallNoSlip(BoundaryCondition *bc)
Implementation of Create_WallNoSlip().
static PetscErrorCode PrescribedBulkFactor(InletPrescribedVelocityData *data, UserCtx *user, BCFace face_id, PetscReal physical_time, PetscReal *factor)
Factor that makes the face's mean normal speed or flow rate equal the target.
static PetscErrorCode PreStep_PeriodicDrivenConstant(BoundaryCondition *self, BCContext *ctx, PetscReal *in, PetscReal *out)
Prepare constant periodic-driving data before the solver step.
static PetscErrorCode PreStep_OutletConservation(BoundaryCondition *self, BCContext *ctx, PetscReal *local_inflow_contribution, PetscReal *local_outflow_contribution)
Prepare the outlet-conservation correction before advancing the solver.
PetscErrorCode Create_OutletConservation(BoundaryCondition *bc)
Implementation of Create_OutletConservation().
static PetscErrorCode PreStep_InletPrescribedVelocity(BoundaryCondition *self, BCContext *ctx, PetscReal *in, PetscReal *out)
Refresh the inlet velocity once per step: gather the slots on the first call, then re-evaluate and re...
static PetscErrorCode PreStep_PeriodicDrivenInitial(BoundaryCondition *self, BCContext *ctx, PetscReal *in, PetscReal *out)
Latch the initial-state flux once, then drive to it like a constant target.
PetscReal targetVolumetricFlux
static PetscErrorCode OutletConservationClip(UserCtx *user, BCFace face_id, OutletConservationData *data, PetscReal correction, PetscBool *applied)
Run the backflow clip for one Apply call; see the section comment.
Private data structure shared by both periodic driven-flux handlers.
Private data of the prescribed-velocity inlet: a compiled source or a PICSLICE file,...
Per-face state of the backflow clip; see the section comment above.
PetscErrorCode GetBoundaryFaceElements(UserCtx *user, BCFace face_id, BoundaryFaceElements *elements)
The elements of a boundary face this rank owns, as index ranges.
Definition Boundaries.c:105
PetscErrorCode CanRankServiceFace(const DMDALocalInfo *info, PetscInt IM_nodes_global, PetscInt JM_nodes_global, PetscInt KM_nodes_global, BCFace face_id, PetscBool *can_service_out)
Determines if the current MPI rank owns any part of a specified global face.
Definition Boundaries.c:22
static Cmpnts RemoveFaceNormalComponent(Cmpnts velocity, Cmpnts metric)
velocity less its component along the face metric metric, which leaves it tangent to the face.
Definition Metric.h:99
PetscErrorCode ComputeGridLineFractions(UserCtx *user, Vec fraction, Vec length)
Arc-length position of every owned cell centre along its three grid lines.
Definition Metric.c:1362
The expression language shared by every configured field, the keyed hashes its random draws and other...
PetscReal PicurvNormalFromHash(uint64_t hash)
A standard normal deviate from a hash: the first of PicurvNormalPairFromHash()'s pair.
Definition expression.c:655
BoundaryFaceElements elements
The owned face elements the slots are.
Definition expression.h:317
PicurvExpression * bulk
Target mean speed [m/s] in t, or NULL.
Definition expression.h:192
uint64_t PicurvDrawHash(PetscInt64 seed, PicurvDrawSpace space, uint64_t stream, PetscInt64 id, PetscInt64 salt)
Hash that keys a draw: a pure function of its arguments, so a draw does not depend on the rank that m...
Definition expression.c:610
PetscBool bulk_time_dependent
Definition expression.h:193
PetscErrorCode PicurvVelocitySourceEvaluate(const PicurvVelocitySource *source, const PetscReal *values, const PicurvExpressionDrawKey *key, const Cmpnts edges[3], Cmpnts *value)
Evaluate a source at one point.
Definition expression.c:993
@ PICURV_DRAW_SPACE_INFLOW
Synthetic inflow noise: stream per block and component, salt the step.
Definition expression.h:37
PetscErrorCode PicurvVelocitySourceCreate(const char *prefix, PetscBool on_face, PetscBool has_data, PetscBool allow_draws, PicurvVelocitySource *source)
Read and compile a velocity source from the options database.
Definition expression.c:872
@ PICURV_SOURCE_VAR_T
Physical time [s].
Definition expression.h:162
@ PICURV_SOURCE_VAR_Y
Physical y [m].
Definition expression.h:160
@ PICURV_SOURCE_VAR_X
Physical x of the point [m].
Definition expression.h:159
@ PICURV_SOURCE_VAR_Z
Physical z [m].
Definition expression.h:161
PetscErrorCode PicurvVelocitySourceDestroy(PicurvVelocitySource *source)
Free a source's compiled expressions and bulk velocity.
static PicurvExpressionDrawKey PicurvFaceDrawKey(PetscInt64 seed, PetscInt block, const PetscInt nodes[3], BCFace face, PetscInt p, PetscInt q, PetscInt64 step)
Draw key of a boundary face cell at one step, the key of a face source's draws.
Definition expression.h:307
PetscErrorCode PicurvVelocitySourceBulkFactor(const PicurvVelocitySource *source, PetscReal physical_time, const PetscReal local[3], const char *where, PetscReal *factor)
Factor on a source's expressions that makes a target's whole mean equal its bulk velocity.
Definition expression.c:947
PetscBool time_dependent
Some component reads t or draws, so a face re-evaluates it each step.
Definition expression.h:191
PetscErrorCode PicurvSourceFaceSlotsCreate(UserCtx *user, BCFace face_id, Vec fraction, Vec length, PicurvSourceFaceSlots *slots)
Gather each owned slot of a boundary face: face-centre position, the grid-line fractions and lengths ...
PetscReal(* values)[PICURV_SOURCE_VAR_COUNT]
Variables per slot; t is the caller's.
Definition expression.h:318
PicurvSourceFrame frame
Definition expression.h:188
PetscErrorCode PicurvSourceFaceSlotsDestroy(PicurvSourceFaceSlots *slots)
Release what PicurvSourceFaceSlotsCreate() allocated.
Cmpnts(* edges)[3]
Directions per slot, for the curvilinear frame.
Definition expression.h:319
@ PICURV_SOURCE_FRAME_NORMAL
One value: the speed into the domain through a face.
Definition expression.h:178
@ PICURV_SOURCE_FRAME_CARTESIAN
Three values: x, y, z velocity components.
Definition expression.h:176
@ PICURV_SOURCE_FRAME_CURVILINEAR
Three values along the unit xi, eta, zeta grid-line directions.
Definition expression.h:177
PetscInt count
1 for the normal frame, otherwise 3; 0 for staged data alone.
Definition expression.h:189
What a random draw is keyed on, besides its stream.
Definition expression.h:85
What a source reads at each boundary-face slot this rank owns, gathered once.
Definition expression.h:316
A prescribed velocity, for any target: one compiled expression per value, the frame they are in,...
Definition expression.h:187
PetscErrorCode CalculateFaceCenterAndArea(UserCtx *user, BCFace face_id, Cmpnts *face_center, PetscReal *face_area)
Calculates the geometric center and total area of a specified boundary face.
Definition grid.c:1211
PetscErrorCode GetBCParamReal(BC_Param *params, const char *key, PetscReal *value_out, PetscBool *found)
Searches a BC_Param linked list for a key and returns its value as a double.
Definition io.c:819
PetscErrorCode GetDrivenSeamFluxFlag(BC_Param *params, PetscBool *value_out, PetscBool *found)
Read the driven-flow seam-flux flag, accepting its deprecated apply_trim spelling.
Definition io.c:888
PetscErrorCode GetBCParamString(BC_Param *params, const char *key, const char **value_out, PetscBool *found)
Searches a BC_Param linked list for a key and returns its value as a string.
Definition io.c:859
PetscErrorCode GetBCParamBool(BC_Param *params, const char *key, PetscBool *value_out, PetscBool *found)
Searches a BC_Param linked list for a key and returns its value as a bool.
Definition io.c:836
PetscErrorCode PicurvPhysicalTime(const SimCtx *simCtx, PetscReal solver_time, PetscReal *physical)
Convert a solver time to physical seconds, t * L_ref / U_ref.
Definition io.c:2986
#define LOCAL
Logging scope definitions for controlling message output.
Definition logging.h:45
#define GLOBAL
Scope for global logging across all processes.
Definition logging.h:46
const char * BCFaceToString(BCFace face)
Returns the canonical log token for a boundary-face enum value.
Definition logging.c:640
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
const char * BCTypeToString(BCType type)
Returns the canonical log token for a boundary mathematical type.
Definition logging.c:828
@ LOG_TRACE
Very fine-grained tracing information for in-depth debugging.
Definition logging.h:33
@ LOG_INFO
Informational messages about program execution.
Definition logging.h:31
@ LOG_WARNING
Non-critical issues that warrant attention.
Definition logging.h:30
@ LOG_DEBUG
Detailed debugging information.
Definition logging.h:32
#define PROFILE_FUNCTION_BEGIN
Marks the beginning of a profiled function: an always-on aggregate timer.
Definition logging.h:1000
static void GetOwnedInteriorCellBounds(const DMDALocalInfo *info, PetscInt lo[3], PetscInt hi[3])
Index bounds of the interior cells this rank owns in the solver's cell-centred layout: the owned rang...
Definition setup.h:378
static void GetPeriodicAxes(const SimCtx *simCtx, PetscBool periodic[3])
Which grid axes are periodic.
Definition setup.h:361
The "virtual table" struct for a boundary condition handler object.
Definition variables.h:389
PetscErrorCode(* PostStep)(BoundaryCondition *self, BCContext *ctx, PetscReal *local_inflow, PetscReal *local_outflow)
Definition variables.h:396
PetscErrorCode(* PreStep)(BoundaryCondition *self, BCContext *ctx, PetscReal *local_inflow, PetscReal *local_outflow)
Definition variables.h:394
PetscErrorCode(* Destroy)(BoundaryCondition *self)
Definition variables.h:398
PetscErrorCode(* Initialize)(BoundaryCondition *self, BCContext *ctx)
Definition variables.h:393
PetscErrorCode(* UpdateUbcs)(BoundaryCondition *self, BCContext *ctx)
Definition variables.h:397
PetscErrorCode(* Apply)(BoundaryCondition *self, BCContext *ctx)
Definition variables.h:395
PetscBool needs_repeat_pass
Apply() reads state its own boundary pass changes after it runs (the interior Ucat that Contra2Cart r...
Definition variables.h:402
BCPriorityType priority
Definition variables.h:391
const PetscReal * global_outflow_sum
Definition variables.h:385
BCType
Defines the general mathematical/physical Category of a boundary.
Definition variables.h:316
@ INLET
Definition variables.h:323
@ FARFIELD
Definition variables.h:324
@ OUTLET
Definition variables.h:322
@ PERIODIC
Definition variables.h:325
PetscMPIInt rank
Definition variables.h:919
BoundaryFaceConfig boundary_faces[6]
Definition variables.h:1182
PetscReal targetVolumetricFlux
Definition variables.h:1024
Vec lNvert
Definition variables.h:1197
SimCtx * simCtx
Back-pointer to the master simulation context.
Definition variables.h:1160
PetscReal boundaryVelocityCorrection
Definition variables.h:1031
PetscInt KM
Definition variables.h:1171
PetscBool inflowFluctuationsRestored
That state was read from the restart checkpoint.
Definition variables.h:1044
PetscReal L_ref
Definition variables.h:898
Vec InflowFluctuation
Definition variables.h:1194
BCHandlerType
Defines the specific computational "strategy" for a boundary handler.
Definition variables.h:343
@ BC_HANDLER_PERIODIC_DRIVEN_INITIAL_FLUX
Definition variables.h:355
@ BC_HANDLER_PERIODIC_DRIVEN_CONSTANT_FLUX
Definition variables.h:354
@ BC_HANDLER_WALL_MOVING
Definition variables.h:346
@ BC_HANDLER_INLET_PRESCRIBED_VELOCITY
Definition variables.h:348
BCHandlerType handler_type
Definition variables.h:427
PetscInt layer
Index along the normal of the face's metric and flux.
Definition variables.h:418
PetscInt normal
Logical axis of the face normal.
Definition variables.h:416
PetscBool drivenFluxTargetLatched
Definition variables.h:1029
PetscInt _this
Definition variables.h:1175
PetscReal dt
Definition variables.h:933
PetscReal bulkVelocityCorrection
Definition variables.h:1030
BCFace face_id
Definition variables.h:381
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
PetscScalar x
Definition variables.h:145
UserCtx * user
Definition variables.h:380
const PetscReal * global_inflow_sum
Definition variables.h:382
char analysis_dir[PETSC_MAX_PATH_LEN]
Definition variables.h:942
BC_Param * params
Definition variables.h:429
PetscScalar z
Definition variables.h:145
ScalingCtx scaling
Definition variables.h:1003
PetscInt JM
Definition variables.h:1171
PetscReal drivenFluxMeasured
Definition variables.h:1035
const PetscReal * global_farfield_inflow_sum
Definition variables.h:383
PetscInt n[2]
Owned elements along a and b; 0 when this rank does not serve the face.
Definition variables.h:420
PetscInt sourceRandomSeed
Seed of the draws in velocity and pressure sources (-source_random_seed).
Definition variables.h:1051
Vec lUcont
Definition variables.h:1197
PetscInt step
Definition variables.h:924
PetscReal AreaOutSum
Definition variables.h:1036
PetscReal drivenFluxArea
Definition variables.h:1035
DMDALocalInfo info
Definition variables.h:1169
@ BC_PRIORITY_OUTLET
Definition variables.h:364
@ BC_PRIORITY_WALL
Definition variables.h:363
@ BC_PRIORITY_INLET
Definition variables.h:361
Vec lUcat
Definition variables.h:1197
PetscScalar y
Definition variables.h:145
PetscInt IM
Definition variables.h:1171
BCType mathematical_type
Definition variables.h:426
PetscReal ti
Definition variables.h:925
PetscReal U_ref
Definition variables.h:899
PetscInt lo[2]
First owned indices along a and b.
Definition variables.h:419
PetscInt b
The two tangential axes, a < b.
Definition variables.h:417
Vec Uch
Characteristic velocity for boundary conditions.
Definition variables.h:173
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
BoundaryCondition * handler
Definition variables.h:430
Provides execution context for a boundary condition handler.
Definition variables.h:379
Holds the complete configuration for one of the six boundary faces.
Definition variables.h:424
The elements of one boundary face that this rank owns: one per interior cell beside the face,...
Definition variables.h:415
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