PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
Boundaries.c
Go to the documentation of this file.
1#include "Boundaries.h" // The main header for our project
2#include <string.h> // For strcasecmp
3#include <ctype.h> // For isspace
4
5/**
6 * @brief Implementation of \ref BoundaryFaceHasWallShear().
7 * @see BoundaryFaceHasWallShear()
8 */
10{
11 return (PetscBool)(face != NULL && face->mathematical_type == WALL &&
13}
14
15
16/**
17 * @brief Implementation of \ref CanRankServiceFace().
18 * @details Full API contract (arguments, ownership, side effects) is documented with
19 * the header declaration in `include/Boundaries.h`.
20 * @see CanRankServiceFace()
21 */
22PetscErrorCode CanRankServiceFace(const DMDALocalInfo *info, PetscInt IM_nodes_global, PetscInt JM_nodes_global, PetscInt KM_nodes_global,
23 BCFace face_id, PetscBool *can_service_out)
24{
25 PetscErrorCode ierr;
26 PetscMPIInt rank_for_logging;
27 PetscFunctionBeginUser;
28
30
31 rank_for_logging = PetscGlobalRank;
32
33 *can_service_out = PETSC_FALSE; // Default to no service
34
35 // Get the range of cells owned by this rank
36 PetscInt owned_start_cell_i, num_owned_cells_on_rank_i;
37 PetscInt owned_start_cell_j, num_owned_cells_on_rank_j;
38 PetscInt owned_start_cell_k, num_owned_cells_on_rank_k;
39 ierr = GetOwnedCellRange(info, 0, &owned_start_cell_i, &num_owned_cells_on_rank_i); CHKERRQ(ierr);
40 ierr = GetOwnedCellRange(info, 1, &owned_start_cell_j, &num_owned_cells_on_rank_j); CHKERRQ(ierr);
41 ierr = GetOwnedCellRange(info, 2, &owned_start_cell_k, &num_owned_cells_on_rank_k); CHKERRQ(ierr);
42
43 // Determine the global index of the last cell (0-indexed) in each direction.
44 PetscInt last_global_cell_idx_i = (IM_nodes_global > 1) ? (IM_nodes_global - 2) : -1;
45 PetscInt last_global_cell_idx_j = (JM_nodes_global > 1) ? (JM_nodes_global - 2) : -1;
46 PetscInt last_global_cell_idx_k = (KM_nodes_global > 1) ? (KM_nodes_global - 2) : -1;
47
48 switch (face_id) {
49 case BC_FACE_NEG_X:
50 if (info->xs == 0 && num_owned_cells_on_rank_i > 0 &&
51 num_owned_cells_on_rank_j > 0 && num_owned_cells_on_rank_k > 0) {
52 *can_service_out = PETSC_TRUE;
53 }
54 break;
55 case BC_FACE_POS_X:
56 if (last_global_cell_idx_i >= 0 &&
57 (owned_start_cell_i + num_owned_cells_on_rank_i - 1) == last_global_cell_idx_i &&
58 num_owned_cells_on_rank_j > 0 && num_owned_cells_on_rank_k > 0) {
59 *can_service_out = PETSC_TRUE;
60 }
61 break;
62 case BC_FACE_NEG_Y:
63 if (info->ys == 0 && num_owned_cells_on_rank_j > 0 &&
64 num_owned_cells_on_rank_i > 0 && num_owned_cells_on_rank_k > 0) {
65 *can_service_out = PETSC_TRUE;
66 }
67 break;
68 case BC_FACE_POS_Y:
69 if (last_global_cell_idx_j >= 0 &&
70 (owned_start_cell_j + num_owned_cells_on_rank_j - 1) == last_global_cell_idx_j &&
71 num_owned_cells_on_rank_i > 0 && num_owned_cells_on_rank_k > 0) {
72 *can_service_out = PETSC_TRUE;
73 }
74 break;
75 case BC_FACE_NEG_Z:
76 if (info->zs == 0 && num_owned_cells_on_rank_k > 0 &&
77 num_owned_cells_on_rank_i > 0 && num_owned_cells_on_rank_j > 0) {
78 *can_service_out = PETSC_TRUE;
79 }
80 break;
81 case BC_FACE_POS_Z:
82 if (last_global_cell_idx_k >= 0 &&
83 (owned_start_cell_k + num_owned_cells_on_rank_k - 1) == last_global_cell_idx_k &&
84 num_owned_cells_on_rank_i > 0 && num_owned_cells_on_rank_j > 0) {
85 *can_service_out = PETSC_TRUE;
86 }
87 break;
88 default:
89 LOG_ALLOW(LOCAL, LOG_WARNING, "Rank %d: Unknown face enum %d. \n", rank_for_logging, face_id);
90 break;
91 }
92
93 LOG_ALLOW(LOCAL, LOG_DEBUG, "Rank %d check for face %s: Result=%s. \n",
94 rank_for_logging, BCFaceToString((BCFace)face_id), (*can_service_out ? "TRUE" : "FALSE"));
95
97
98 PetscFunctionReturn(0);
99}
100
101/**
102 * @brief Implementation of \ref GetBoundaryFaceElements().
103 * @see GetBoundaryFaceElements()
104 */
105PetscErrorCode GetBoundaryFaceElements(UserCtx *user, BCFace face_id, BoundaryFaceElements *elements)
106{
107 const DMDALocalInfo *info = &user->info;
108 const PetscInt nodes[3] = {info->mx, info->my, info->mz};
109 const PetscBool negative = (PetscBool)((PetscInt)face_id % 2 == 0);
110 PetscBool can_service = PETSC_FALSE;
111 PetscInt lo[3], hi[3];
112
113 PetscFunctionBeginUser;
115 elements->normal = (PetscInt)face_id / 2;
116 elements->a = (elements->normal == 0) ? 1 : 0;
117 elements->b = (elements->normal == 2) ? 1 : 2;
118 elements->layer = negative ? 0 : nodes[elements->normal] - 2;
119 PetscCall(CanRankServiceFace(info, user->IM, user->JM, user->KM, face_id, &can_service));
120 GetOwnedInteriorCellBounds(info, lo, hi);
121 elements->lo[0] = lo[elements->a];
122 elements->lo[1] = lo[elements->b];
123 elements->n[0] = can_service ? hi[elements->a] - lo[elements->a] : 0;
124 elements->n[1] = can_service ? hi[elements->b] - lo[elements->b] : 0;
126 PetscFunctionReturn(PETSC_SUCCESS);
127}
128
129
130/**
131 * @brief Implementation of \ref ClassifyMomentumRow().
132 *
133 * Pure index/boundary-type arithmetic: no field reads, no communication.
134 * Precedence matters. A conditioned row is reported first because its explicit
135 * Dirichlet value is more specific than the homogeneous fallback, and a periodic
136 * duplicate is reported before the homogeneous case because the Newton path needs
137 * its representative index to build `F = X_dup - X_rep`.
138 */
139MomentumRowType ClassifyMomentumRow(UserCtx *user, PetscInt i, PetscInt j, PetscInt k,
140 PetscInt component, PetscInt *ri, PetscInt *rj, PetscInt *rk)
141{
142 const PetscInt mx = user->info.mx, my = user->info.my, mz = user->info.mz;
143 const PetscInt coord[3] = {i, j, k};
144 const PetscInt size[3] = {mx, my, mz};
145 PetscBool periodic[3], periodic_duplicate = PETSC_FALSE;
146 PetscBool residual_zeroed = PETSC_FALSE, conditioned = PETSC_FALSE;
147
148 *ri = i; *rj = j; *rk = k;
149 GetPeriodicAxes(user->simCtx, periodic);
150 for (PetscInt axis = 0; axis < 3; ++axis) {
151 if (periodic[axis] && coord[axis] == 0) {
152 periodic_duplicate = PETSC_TRUE;
153 if (axis == 0) *ri = -2;
154 else if (axis == 1) *rj = -2;
155 else *rk = -2;
156 }
157 if (periodic[axis] && coord[axis] == size[axis] - 1) {
158 periodic_duplicate = PETSC_TRUE;
159 if (axis == 0) *ri = mx + 1;
160 else if (axis == 1) *rj = my + 1;
161 else *rk = mz + 1;
162 }
163
164 if (!periodic[axis] && coord[axis] == 0) residual_zeroed = PETSC_TRUE;
165 if (coord[axis] == size[axis] - 1) residual_zeroed = PETSC_TRUE;
166 if (!periodic[axis] && coord[axis] == size[axis] - 2 && component == axis)
167 residual_zeroed = PETSC_TRUE;
168 }
169
170 if (!periodic[component] &&
171 (coord[component] == 0 || coord[component] == size[component] - 2)) {
172 PetscBool tangential_interior = PETSC_TRUE;
173 for (PetscInt axis = 0; axis < 3; ++axis) {
174 if (axis == component) continue;
175 if (coord[axis] < 1 || coord[axis] > size[axis] - 2)
176 tangential_interior = PETSC_FALSE;
177 }
178 conditioned = tangential_interior;
179 }
180
181 if (conditioned) return MOM_ROW_FIXED_CONDITIONED;
182 if (periodic_duplicate) return MOM_ROW_PERIODIC_DUPLICATE;
183 if (residual_zeroed) return MOM_ROW_FIXED_HOMOGENEOUS;
184 return MOM_ROW_PHYSICAL;
185}
186
187/**
188 * @brief Implementation of \ref MomentumRowIsSolidMasked().
189 * @details Full API contract is documented with the header declaration in
190 * `include/Boundaries.h`.
191 * @see MomentumRowIsSolidMasked()
192 */
193PetscBool MomentumRowIsSolidMasked(const PetscReal ***nvert, PetscInt i, PetscInt j,
194 PetscInt k, PetscInt component)
195{
197 /* PICURV_SOLID_THRESHOLD mirrors the 0.1 fluid test ComputeRHS() applies. */
198 const PetscReal threshold = 0.1;
199
200 if (nvert == NULL) { PROFILE_HELPER_END; return PETSC_FALSE; }
201 /* A solid cell carries no momentum equation in any component. */
202 if (nvert[k][j][i] > threshold) { PROFILE_HELPER_END; return PETSC_TRUE; }
203 /* A staggered row also loses its equation when the cell it points into is solid. */
204 switch (component) {
205 case 0: PROFILE_HELPER_END; return (PetscBool)(nvert[k][j][i + 1] > threshold);
206 case 1: PROFILE_HELPER_END; return (PetscBool)(nvert[k][j + 1][i] > threshold);
207 case 2: PROFILE_HELPER_END; return (PetscBool)(nvert[k + 1][j][i] > threshold);
208 default: PROFILE_HELPER_END; return PETSC_FALSE;
209 }
211}
212
213/**
214 * @brief Implementation of \ref EnforceRHSBoundaryConditions().
215 *
216 * The sweep is deliberately expressed over every owned location rather than over
217 * the six boundary slabs: restating "which indices can be non-physical" here is
218 * exactly the duplication that let the periodic duplicate column go unzeroed.
219 * ClassifyMomentumRow() is a handful of integer comparisons and the walk is a
220 * single pass with no stencil access, which is negligible next to the several
221 * ghosted stencil passes ComputeRHS() has already made over the same range.
222 * MomentumNewtonKrylov_ApplyConstraints() walks the same range the same way.
223 */
225{
226 PetscErrorCode ierr;
227 DMDALocalInfo info = user->info;
228 Cmpnts ***rhs;
229
230 PetscFunctionBeginUser;
232
233 // Get a writable pointer to the local data of the global RHS vector.
234 ierr = DMDAVecGetArray(user->fda, user->Rhs, &rhs); CHKERRQ(ierr);
235
236 for (PetscInt k = info.zs; k < info.zs + info.zm; k++) {
237 for (PetscInt j = info.ys; j < info.ys + info.ym; j++) {
238 for (PetscInt i = info.xs; i < info.xs + info.xm; i++) {
239 PetscScalar *row = &rhs[k][j][i].x; /* .x/.y/.z are contiguous */
240 for (PetscInt component = 0; component < 3; component++) {
241 PetscInt ri, rj, rk;
242 if (ClassifyMomentumRow(user, i, j, k, component, &ri, &rj, &rk) != MOM_ROW_PHYSICAL)
243 row[component] = 0.0;
244 }
245 }
246 }
247 }
248
249 // --- Release the pointer to the local data ---
250 ierr = DMDAVecRestoreArray(user->fda, user->Rhs, &rhs); CHKERRQ(ierr);
251
252 LOG_ALLOW(LOCAL, LOG_TRACE, "Rank %d, Block %" PetscInt_FMT ": Finished enforcing RHS boundary conditions.\n",
253 user->simCtx->rank, user->_this);
254
256
257 PetscFunctionReturn(0);
258}
259
260/**
261 * @brief Implementation of \ref BoundaryCondition_Create().
262 * @see BoundaryCondition_Create()
263 */
264
265PetscErrorCode BoundaryCondition_Create(BCHandlerType handler_type, BoundaryCondition **new_bc_ptr)
266{
267 PetscErrorCode ierr;
268 PetscFunctionBeginUser;
270
271 const char* handler_name = BCHandlerTypeToString(handler_type);
272 LOG_ALLOW(LOCAL, LOG_DEBUG, "Factory called for handler type %s. \n", handler_name);
273
274 ierr = PetscMalloc1(1, new_bc_ptr); CHKERRQ(ierr);
275 BoundaryCondition *bc = *new_bc_ptr;
276
277 bc->type = handler_type;
278 bc->priority = -1; // Default priority; can be overridden in specific handlers
279 bc->data = NULL;
280 bc->Initialize = NULL;
281 bc->PreStep = NULL;
282 bc->Apply = NULL;
283 bc->PostStep = NULL;
284 bc->UpdateUbcs = NULL;
285 bc->Destroy = NULL;
286 bc->needs_repeat_pass = PETSC_FALSE; // A handler whose Apply() reads in-pass state sets it
287
288 LOG_ALLOW(LOCAL, LOG_DEBUG, "Allocated generic handler object at address %p.\n", (void*)bc);
289
290 switch (handler_type) {
291
293 LOG_ALLOW(LOCAL, LOG_DEBUG, "Dispatching to Create_OutletConservation().\n");
294 ierr = Create_OutletConservation(bc); CHKERRQ(ierr);
295 break;
296
298 LOG_ALLOW(LOCAL, LOG_DEBUG, "Dispatching to Create_WallNoSlip().\n");
299 ierr = Create_WallNoSlip(bc); CHKERRQ(ierr);
300 break;
301
303 LOG_ALLOW(LOCAL, LOG_DEBUG, "Dispatching to Create_WallFreeSlip().\n");
304 ierr = Create_WallFreeSlip(bc); CHKERRQ(ierr);
305 break;
306
308 LOG_ALLOW(LOCAL, LOG_DEBUG, "Dispatching to Create_WallMoving().\n");
309 ierr = Create_WallMoving(bc); CHKERRQ(ierr);
310 break;
311
313 LOG_ALLOW(LOCAL,LOG_DEBUG,"Dispatching to Create_PeriodicGeometric().\n");
314 ierr = Create_PeriodicGeometric(bc);
315 break;
316
318 LOG_ALLOW(LOCAL,LOG_DEBUG,"Dispatching to Create_PeriodicDrivenConstant().\n");
320 break;
321
323 LOG_ALLOW(LOCAL,LOG_DEBUG,"Dispatching to Create_PeriodicDrivenInitial().\n");
325 break;
326
328 LOG_ALLOW(LOCAL, LOG_DEBUG, "Dispatching to Create_InletPrescribedVelocity().\n");
329 ierr = Create_InletPrescribedVelocity(bc); CHKERRQ(ierr);
330 break;
331 //Add cases for other handlers here in future phases
332
333 default:
334 LOG_ALLOW(GLOBAL, LOG_ERROR, "Handler type (%s) is not recognized or implemented in the factory.\n", handler_name);
335 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_UNKNOWN_TYPE, "Boundary handler type %d (%s) not recognized in factory.\n", handler_type, handler_name);
336 }
337
338 if(bc->priority < 0) {
339 LOG_ALLOW(GLOBAL, LOG_ERROR, "Handler type %d (%s) did not set a valid priority during creation.\n", handler_type, handler_name);
340 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_UNKNOWN_TYPE, "Boundary handler type %d (%s) did not set a valid priority during creation.\n", handler_type, handler_name);
341 }
342
343 LOG_ALLOW(LOCAL, LOG_DEBUG, "Successfully created and configured handler for %s.\n", handler_name);
345 PetscFunctionReturn(0);
346}
347
348/**
349 * @brief Implementation of \ref BoundarySystem_Validate().
350 * @see BoundarySystem_Validate()
351 */
352PetscErrorCode BoundarySystem_Validate(UserCtx *user)
353{
354 PetscErrorCode ierr;
355 const BCFace neg_faces[3] = {BC_FACE_NEG_X, BC_FACE_NEG_Y, BC_FACE_NEG_Z};
356 const BCFace pos_faces[3] = {BC_FACE_POS_X, BC_FACE_POS_Y, BC_FACE_POS_Z};
357 const char axis_names[3] = {'X', 'Y', 'Z'};
358 DMBoundaryType bx, by, bz;
359 PetscBool dm_periodic[3];
360 PetscFunctionBeginUser;
362
363 LOG_ALLOW(GLOBAL, LOG_INFO, "Validating parsed boundary condition configuration...\n");
364 bx = user->info.bx; by = user->info.by; bz = user->info.bz;
365 dm_periodic[0] = (PetscBool)(bx == DM_BOUNDARY_PERIODIC);
366 dm_periodic[1] = (PetscBool)(by == DM_BOUNDARY_PERIODIC);
367 dm_periodic[2] = (PetscBool)(bz == DM_BOUNDARY_PERIODIC);
368
369 // --- Rule Set 1: Geometric periodic faces must be paired and match the DM topology. ---
370 for (PetscInt axis = 0; axis < 3; axis++) {
371 const PetscBool neg_periodic =
372 user->boundary_faces[neg_faces[axis]].mathematical_type == PERIODIC;
373 const PetscBool pos_periodic =
374 user->boundary_faces[pos_faces[axis]].mathematical_type == PERIODIC;
375
376 PetscCheck(neg_periodic == pos_periodic, PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT,
377 "Configuration Error: Periodic boundaries in the %c direction must be paired; "
378 "%s is %s while %s is %s.",
379 axis_names[axis],
380 BCFaceToString(neg_faces[axis]), neg_periodic ? "PERIODIC" : "not periodic",
381 BCFaceToString(pos_faces[axis]), pos_periodic ? "PERIODIC" : "not periodic");
382 PetscCheck(dm_periodic[axis] == neg_periodic, PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT,
383 "Configuration Error: The %c-direction DM periodic flag (%d) does not match "
384 "the paired boundary configuration (%s).",
385 axis_names[axis], (int)dm_periodic[axis], neg_periodic ? "PERIODIC" : "not periodic");
386 }
387
388 // --- Rule Set 2: Driven Flow Handler Consistency ---
389 // This specialized validator will check all rules related to driven flow handlers.
390 ierr = Validate_DrivenFlowConfiguration(user); CHKERRQ(ierr);
391
392 // --- Rule Set 3: (Future Extension) Overset Interface Consistency ---
393 // ierr = Validate_OversetConfiguration(user); CHKERRQ(ierr);
394
395 LOG_ALLOW(GLOBAL, LOG_INFO, "Boundary configuration is valid.\n");
396
398 PetscFunctionReturn(0);
399}
400
401//================================================================================
402//
403// PUBLIC MASTER SETUP FUNCTION
404//
405//================================================================================
406/**
407 * @brief Implementation of \ref BoundarySystem_Initialize().
408 * @details Full API contract (arguments, ownership, side effects) is documented with
409 * the header declaration in `include/Boundaries.h`.
410 * @see BoundarySystem_Initialize()
411 */
412PetscErrorCode BoundarySystem_Initialize(UserCtx *user, const char *bcs_filename)
413{
414 PetscErrorCode ierr;
415 PetscFunctionBeginUser;
417
418 LOG_ALLOW(GLOBAL, LOG_INFO, "Starting creation and initialization of all boundary handlers.\n");
419
420 // =========================================================================
421 // Step 0: Clear any existing boundary handlers (if re-initializing).
422 // This ensures no memory leaks if this function is called multiple times.
423 // =========================================================================
424 for (int i = 0; i < 6; i++) {
425 BoundaryFaceConfig *face_cfg = &user->boundary_faces[i];
426 if (face_cfg->handler) {
427 LOG_ALLOW(LOCAL, LOG_DEBUG, "Destroying existing handler on Face %s before re-initialization.\n", BCFaceToString((BCFace)i));
428 if (face_cfg->handler->Destroy) {
429 ierr = face_cfg->handler->Destroy(face_cfg->handler); CHKERRQ(ierr);
430 }
431 ierr = PetscFree(face_cfg->handler); CHKERRQ(ierr);
432 face_cfg->handler = NULL;
433 }
434 }
435 // =========================================================================
436
437 // Step 0.1: Initiate flux sums to zero
438 user->simCtx->FluxInSum = 0.0;
439 user->simCtx->FluxOutSum = 0.0;
440 user->simCtx->FarFluxInSum = 0.0;
441 user->simCtx->FarFluxOutSum = 0.0;
442 // =========================================================================
443
444 // Step 1: Parse the configuration file to determine user intent.
445 // This function, defined in io.c, populates the configuration enums and parameter
446 // lists within the user->boundary_faces array on all MPI ranks.
447 ierr = ParseAllBoundaryConditions(user, bcs_filename); CHKERRQ(ierr);
448 LOG_ALLOW(GLOBAL, LOG_INFO, "Configuration file '%s' parsed successfully.\n", bcs_filename);
449
450 // Step 1.1: Validate the parsed configuration to ensure there are no Boundary Condition conflicts
451 ierr = BoundarySystem_Validate(user); CHKERRQ(ierr);
452
453 // Step 1.2: Resolve each face's particle policy from its particle_policy parameter (remove when absent).
454 for (int i = 0; i < 6; i++) {
455 BoundaryFaceConfig *face_cfg = &user->boundary_faces[i];
456 const char *policy = NULL;
457 PetscBool found;
458 ierr = GetBCParamString(face_cfg->params, "particle_policy", &policy, &found); CHKERRQ(ierr);
459 if (!found || strcasecmp(policy, "remove") == 0) {
461 } else if (strcasecmp(policy, "reflect") == 0 && face_cfg->mathematical_type != PERIODIC) {
463 } else if (strcasecmp(policy, "wrap") == 0 && face_cfg->mathematical_type == PERIODIC) {
465 } else {
466 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONG, "Face %s (%s): particle_policy '%s' is not supported; use 'remove' or '%s'.",
468 (face_cfg->mathematical_type == PERIODIC) ? "wrap" : "reflect");
469 }
470 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Face %s particle policy: %s.\n", BCFaceToString((BCFace)i),
472 }
473
474 // Step 2: Create and Initialize the handler object for each of the 6 faces.
475 for (int i = 0; i < 6; i++) {
476 BoundaryFaceConfig *face_cfg = &user->boundary_faces[i];
477
478 const char *face_name = BCFaceToString(face_cfg->face_id);
479 const char *type_name = BCTypeToString(face_cfg->mathematical_type);
480 const char *handler_name = BCHandlerTypeToString(face_cfg->handler_type);
481
482 LOG_ALLOW(LOCAL, LOG_DEBUG, "Creating handler for Face %s with Type %s and handler '%s'.\n", face_name, type_name,handler_name);
483
484 // Use the private factory to construct the correct handler object based on the parsed type.
485 // The factory returns a pointer to the new handler object, which we store in the config struct.
486 ierr = BoundaryCondition_Create(face_cfg->handler_type, &face_cfg->handler); CHKERRQ(ierr);
487
488 // Step 3: Call the specific Initialize() method for the newly created handler.
489 // This allows the handler to perform its own setup, like reading parameters from the
490 // face_cfg->params list and setting the initial field values on its face.
491 if (face_cfg->handler && face_cfg->handler->Initialize) {
492 LOG_ALLOW(LOCAL, LOG_DEBUG, "Calling Initialize() method for handler %s(%s) on Face %s.\n",type_name,handler_name,face_name);
493
494 // Prepare the context needed by the Initialize() function.
495 BCContext ctx = {
496 .user = user,
497 .face_id = face_cfg->face_id,
498 .global_inflow_sum = &user->simCtx->FluxInSum, // Global flux sums are not relevant during initialization.
499 .global_outflow_sum = &user->simCtx->FluxOutSum,
500 .global_farfield_inflow_sum = &user->simCtx->FarFluxInSum,
501 .global_farfield_outflow_sum = &user->simCtx->FarFluxOutSum
502 };
503
504 ierr = face_cfg->handler->Initialize(face_cfg->handler, &ctx); CHKERRQ(ierr);
505 } else {
506 LOG_ALLOW(LOCAL, LOG_DEBUG, "Handler %s(%s) for Face %s has no Initialize() method, skipping.\n", type_name,handler_name,face_name);
507 }
508 }
509 // =========================================================================
510 // NO SYNCHRONIZATION NEEDED HERE
511 // =========================================================================
512 // Initialize() only reads parameters and allocates memory.
513 // It does NOT modify field values (Ucat, Ucont, Ubcs).
514 // Field values are set by:
515 // 1. Initial conditions (before this function)
516 // 2. Apply() during timestepping (after this function)
517 // The first call to ApplyBoundaryConditions() will handle synchronization.
518 // =========================================================================
519
520 LOG_ALLOW(GLOBAL, LOG_INFO, "All boundary handlers created and initialized successfully.\n");
522 PetscFunctionReturn(0);
523}
524
525
526/**
527 * @brief Implementation of \ref PropagateBoundaryConfigToCoarserLevels().
528 * @see PropagateBoundaryConfigToCoarserLevels()
529 */
531{
532 PetscErrorCode ierr;
533 UserMG *usermg = &simCtx->usermg;
534
535 PetscFunctionBeginUser;
537
538 LOG_ALLOW(GLOBAL, LOG_INFO, "Propagating BC configuration from finest to coarser multigrid levels...\n");
539
540 // Loop from second-finest down to coarsest
541 for (PetscInt level = usermg->mglevels - 2; level >= 0; level--) {
542 for (PetscInt bi = 0; bi < simCtx->block_number; bi++) {
543 UserCtx *user_coarse = &usermg->mgctx[level].user[bi];
544 UserCtx *user_fine = &usermg->mgctx[level + 1].user[bi];
545
546 LOG_ALLOW_SYNC(LOCAL, LOG_DEBUG, "Rank %d: Copying BC config from level %" PetscInt_FMT " to level %" PetscInt_FMT ", block %" PetscInt_FMT "\n",
547 simCtx->rank, level + 1, level, bi);
548
549 // Copy the 6 boundary face configurations
550 for (int face_i = 0; face_i < 6; face_i++) {
551 user_coarse->boundary_faces[face_i].face_id = user_fine->boundary_faces[face_i].face_id;
552 user_coarse->boundary_faces[face_i].mathematical_type = user_fine->boundary_faces[face_i].mathematical_type;
553 user_coarse->boundary_faces[face_i].handler_type = user_fine->boundary_faces[face_i].handler_type;
554 user_coarse->boundary_faces[face_i].particle_policy = user_fine->boundary_faces[face_i].particle_policy;
555
556 // Copy parameter list (deep copy)
557 FreeBC_ParamList(user_coarse->boundary_faces[face_i].params); // Clear any existing
558 user_coarse->boundary_faces[face_i].params = NULL;
559
560 BC_Param **dst_next = &user_coarse->boundary_faces[face_i].params;
561 for (BC_Param *src = user_fine->boundary_faces[face_i].params; src; src = src->next) {
562 BC_Param *new_param;
563 ierr = PetscMalloc1(1, &new_param); CHKERRQ(ierr);
564 ierr = PetscStrallocpy(src->key, &new_param->key); CHKERRQ(ierr);
565 ierr = PetscStrallocpy(src->value, &new_param->value); CHKERRQ(ierr);
566 new_param->next = NULL;
567 *dst_next = new_param;
568 dst_next = &new_param->next;
569 }
570
571 // IMPORTANT: Do NOT create handler objects for coarser levels
572 // Handlers are only needed at finest level for timestepping Apply() calls
573 user_coarse->boundary_faces[face_i].handler = NULL;
574 }
575
576 // Propagate the particle inlet lookup fields to coarse levels as well.
577 user_coarse->inletFaceDefined = user_fine->inletFaceDefined;
578 user_coarse->identifiedInletBCFace = user_fine->identifiedInletBCFace;
579 }
580 }
581
582 LOG_ALLOW(GLOBAL, LOG_INFO, "BC configuration propagation complete.\n");
583
585 PetscFunctionReturn(0);
586}
587
588//================================================================================
589//
590// PUBLIC MASTER TIME-STEP FUNCTION
591//
592//================================================================================
593
594/**
595 * @brief Implementation of \ref BoundarySystem_ExecuteStep().
596 * @details Full API contract (arguments, ownership, side effects) is documented with
597 * the header declaration in `include/Boundaries.h`.
598 * @see BoundarySystem_ExecuteStep()
599 */
601{
602 PetscErrorCode ierr;
603 PetscFunctionBeginUser;
605
606 LOG_ALLOW(LOCAL, LOG_DEBUG, "Starting.\n");
607
608 // =========================================================================
609 // PRIORITY 0: INLETS
610 // =========================================================================
611
612 PetscReal local_inflow_pre = 0.0;
613 PetscReal local_inflow_post = 0.0;
614 PetscReal global_inflow_pre = 0.0;
615 PetscReal global_inflow_post = 0.0;
616 PetscInt num_handlers[3] = {0,0,0};
617
618 LOG_ALLOW(LOCAL, LOG_TRACE, " (INLETS): Begin.\n");
619
620 // Phase 1: PreStep - Preparation (e.g., calculate profiles, read files)
621 for (int i = 0; i < 6; i++) {
622 BoundaryCondition *handler = user->boundary_faces[i].handler;
623 if (!handler || handler->priority != BC_PRIORITY_INLET) continue;
624 if (!handler->PreStep) continue;
625
626 num_handlers[0]++;
627 BCContext ctx = {
628 .user = user,
629 .face_id = (BCFace)i,
630 .global_inflow_sum = NULL,
631 .global_outflow_sum = NULL,
632 .global_farfield_inflow_sum = &user->simCtx->FarFluxInSum,
633 .global_farfield_outflow_sum = &user->simCtx->FarFluxOutSum
634 };
635
636 LOG_ALLOW(LOCAL, LOG_TRACE, " PreStep: Face %d (%s)\n", i, BCFaceToString((BCFace)i));
637 ierr = handler->PreStep(handler, &ctx, &local_inflow_pre, NULL); CHKERRQ(ierr);
638 }
639
640 // Optional: Global communication for PreStep (for debugging)
641 if (local_inflow_pre != 0.0) {
642 ierr = MPI_Allreduce(&local_inflow_pre, &global_inflow_pre, 1, MPIU_REAL,
643 MPI_SUM, PETSC_COMM_WORLD); CHKERRQ(ierr);
644 LOG_ALLOW(GLOBAL, LOG_TRACE, " PreStep predicted flux: %.6e\n", global_inflow_pre);
645 }
646
647 // Phase 2: Apply - Set boundary conditions
648 for (int i = 0; i < 6; i++) {
649 BoundaryCondition *handler = user->boundary_faces[i].handler;
650 if (!handler || handler->priority != BC_PRIORITY_INLET) continue;
651 if(!handler->Apply) continue; // For example Periodic BCs
652
653 num_handlers[1]++;
654
655 BCContext ctx = {
656 .user = user,
657 .face_id = (BCFace)i,
658 .global_inflow_sum = NULL,
659 .global_outflow_sum = NULL,
660 .global_farfield_inflow_sum = &user->simCtx->FarFluxInSum,
661 .global_farfield_outflow_sum = &user->simCtx->FarFluxOutSum
662 };
663
664 LOG_ALLOW(LOCAL, LOG_TRACE, " Apply: Face %d (%s)\n", i, BCFaceToString((BCFace)i));
665 ierr = handler->Apply(handler, &ctx); CHKERRQ(ierr);
666 }
667
668 // Phase 3: PostStep - Measure actual flux
669 for (int i = 0; i < 6; i++) {
670 BoundaryCondition *handler = user->boundary_faces[i].handler;
671 if (!handler || handler->priority != BC_PRIORITY_INLET) continue;
672 if (!handler->PostStep) continue;
673
674 num_handlers[2]++;
675
676 BCContext ctx = {
677 .user = user,
678 .face_id = (BCFace)i,
679 .global_inflow_sum = NULL,
680 .global_outflow_sum = NULL,
681 .global_farfield_inflow_sum = &user->simCtx->FarFluxInSum,
682 .global_farfield_outflow_sum = &user->simCtx->FarFluxOutSum
683 };
684
685 LOG_ALLOW(LOCAL, LOG_TRACE, " PostStep: Face %d (%s)\n", i, BCFaceToString((BCFace)i));
686 ierr = handler->PostStep(handler, &ctx, &local_inflow_post, NULL); CHKERRQ(ierr);
687 }
688
689 // Phase 4: Global communication - Sum flux for other priorities to use
690 ierr = MPI_Allreduce(&local_inflow_post, &global_inflow_post, 1, MPIU_REAL,
691 MPI_SUM, PETSC_COMM_WORLD); CHKERRQ(ierr);
692
693 // Store for next priority levels
694 user->simCtx->FluxInSum = global_inflow_post;
695
697 " (INLETS): %" PetscInt_FMT " Prestep(s), %" PetscInt_FMT " Application(s), %" PetscInt_FMT " Poststep(s), FluxInSum = %.6e\n",
698 num_handlers[0],num_handlers[1],num_handlers[2], global_inflow_post);
699
700 // =========================================================================
701 // PRIORITY 1: FARFIELD
702 // =========================================================================
703
704 PetscReal local_farfield_in_pre = 0.0;
705 PetscReal local_farfield_out_pre = 0.0;
706 PetscReal local_farfield_in_post = 0.0;
707 PetscReal local_farfield_out_post = 0.0;
708 PetscReal global_farfield_in_pre = 0.0;
709 PetscReal global_farfield_out_pre = 0.0;
710 PetscReal global_farfield_in_post = 0.0;
711 PetscReal global_farfield_out_post = 0.0;
712 memset(num_handlers,0,sizeof(num_handlers));
713
714 LOG_ALLOW(LOCAL, LOG_TRACE, " (FARFIELD): Begin.\n");
715
716 // Phase 1: PreStep - Analyze flow direction, measure initial flux
717 for (int i = 0; i < 6; i++) {
718 BoundaryCondition *handler = user->boundary_faces[i].handler;
719 if (!handler || handler->priority != BC_PRIORITY_FARFIELD) continue;
720 if (!handler->PreStep) continue;
721
722 num_handlers[0]++;
723 BCContext ctx = {
724 .user = user,
725 .face_id = (BCFace)i,
726 .global_inflow_sum = &user->simCtx->FluxInSum, // Available from Priority 0
727 .global_outflow_sum = NULL,
728 .global_farfield_inflow_sum = &user->simCtx->FarFluxInSum,
729 .global_farfield_outflow_sum = &user->simCtx->FarFluxOutSum
730 };
731
732 LOG_ALLOW(LOCAL, LOG_TRACE, " PreStep: Face %d (%s)\n", i, BCFaceToString((BCFace)i));
733 ierr = handler->PreStep(handler, &ctx, &local_farfield_in_pre, &local_farfield_out_pre);
734 CHKERRQ(ierr);
735 }
736
737 // Phase 2: Global communication (optional, for debugging)
738 if (local_farfield_in_pre != 0.0 || local_farfield_out_pre != 0.0) {
739 ierr = MPI_Allreduce(&local_farfield_in_pre, &global_farfield_in_pre, 1, MPIU_REAL,
740 MPI_SUM, PETSC_COMM_WORLD); CHKERRQ(ierr);
741 ierr = MPI_Allreduce(&local_farfield_out_pre, &global_farfield_out_pre, 1, MPIU_REAL,
742 MPI_SUM, PETSC_COMM_WORLD); CHKERRQ(ierr);
743
745 " Farfield pre-analysis: In=%.6e, Out=%.6e\n",
746 global_farfield_in_pre, global_farfield_out_pre);
747 }
748
749 // Phase 3: Apply - Set farfield boundary conditions
750 for (int i = 0; i < 6; i++) {
751 BoundaryCondition *handler = user->boundary_faces[i].handler;
752 if (!handler || handler->priority != BC_PRIORITY_FARFIELD) continue;
753 if(!handler->Apply) continue; // For example Periodic BCs
754
755 num_handlers[1]++;
756
757 BCContext ctx = {
758 .user = user,
759 .face_id = (BCFace)i,
760 .global_inflow_sum = &user->simCtx->FluxInSum,
761 .global_outflow_sum = NULL,
762 .global_farfield_inflow_sum = &user->simCtx->FarFluxInSum,
763 .global_farfield_outflow_sum = &user->simCtx->FarFluxOutSum
764 };
765
766 LOG_ALLOW(LOCAL, LOG_TRACE, " Apply: Face %d (%s)\n", i, BCFaceToString((BCFace)i));
767 ierr = handler->Apply(handler, &ctx); CHKERRQ(ierr);
768 }
769
770 // Phase 4: PostStep - Measure actual farfield fluxes
771 for (int i = 0; i < 6; i++) {
772 BoundaryCondition *handler = user->boundary_faces[i].handler;
773 if (!handler || handler->priority != BC_PRIORITY_FARFIELD) continue;
774 if (!handler->PostStep) continue;
775
776 num_handlers[2]++;
777
778 BCContext ctx = {
779 .user = user,
780 .face_id = (BCFace)i,
781 .global_inflow_sum = &user->simCtx->FluxInSum,
782 .global_outflow_sum = NULL,
783 .global_farfield_inflow_sum = &user->simCtx->FarFluxInSum,
784 .global_farfield_outflow_sum = &user->simCtx->FarFluxOutSum
785 };
786
787 LOG_ALLOW(LOCAL, LOG_TRACE, " PostStep: Face %d (%s)\n", i, BCFaceToString((BCFace)i));
788 ierr = handler->PostStep(handler, &ctx, &local_farfield_in_post, &local_farfield_out_post);
789 CHKERRQ(ierr);
790 }
791
792 // Phase 5: Global communication - Store for outlet priority
793 if (num_handlers > 0) {
794 ierr = MPI_Allreduce(&local_farfield_in_post, &global_farfield_in_post, 1, MPIU_REAL,
795 MPI_SUM, PETSC_COMM_WORLD); CHKERRQ(ierr);
796 ierr = MPI_Allreduce(&local_farfield_out_post, &global_farfield_out_post, 1, MPIU_REAL,
797 MPI_SUM, PETSC_COMM_WORLD); CHKERRQ(ierr);
798
799 // Store for outlet handlers to use
800 user->simCtx->FarFluxInSum = global_farfield_in_post;
801 user->simCtx->FarFluxOutSum = global_farfield_out_post;
802
804 " (FARFIELD): %" PetscInt_FMT " Prestep(s), %" PetscInt_FMT " Application(s), %" PetscInt_FMT " Poststep(s) , InFlux=%.6e, OutFlux=%.6e\n",
805 num_handlers[0],num_handlers[1],num_handlers[2], global_farfield_in_post, global_farfield_out_post);
806 } else {
807 // No farfield handlers - zero out the fluxes
808 user->simCtx->FarFluxInSum = 0.0;
809 user->simCtx->FarFluxOutSum = 0.0;
810 }
811
812
813 // =========================================================================
814 // PRIORITY 2: WALLS
815 // =========================================================================
816
817 memset(num_handlers,0,sizeof(num_handlers));
818
819 LOG_ALLOW(LOCAL, LOG_TRACE, " (WALLS): Begin.\n");
820
821 // Phase 1: PreStep - Preparation (usually no-op for walls)
822 for (int i = 0; i < 6; i++) {
823 BoundaryCondition *handler = user->boundary_faces[i].handler;
824 if (!handler || handler->priority != BC_PRIORITY_WALL) continue;
825 if (!handler->PreStep) continue;
826
827 num_handlers[0]++;
828 BCContext ctx = {
829 .user = user,
830 .face_id = (BCFace)i,
831 .global_inflow_sum = &user->simCtx->FluxInSum,
832 .global_outflow_sum = NULL,
833 .global_farfield_inflow_sum = &user->simCtx->FarFluxInSum,
834 .global_farfield_outflow_sum = &user->simCtx->FarFluxOutSum
835 };
836
837 LOG_ALLOW(LOCAL, LOG_TRACE, " PreStep: Face %d (%s)\n", i, BCFaceToString((BCFace)i));
838 ierr = handler->PreStep(handler, &ctx, NULL, NULL); CHKERRQ(ierr);
839 }
840
841 // No global communication needed for walls
842
843 // Phase 2: Apply - Set boundary conditions
844 for (int i = 0; i < 6; i++) {
845 BoundaryCondition *handler = user->boundary_faces[i].handler;
846 if (!handler || handler->priority != BC_PRIORITY_WALL) continue;
847 if(!handler->Apply) continue; // For example Periodic BCs
848
849 num_handlers[1]++;
850
851 BCContext ctx = {
852 .user = user,
853 .face_id = (BCFace)i,
854 .global_inflow_sum = &user->simCtx->FluxInSum,
855 .global_outflow_sum = NULL,
856 .global_farfield_inflow_sum = &user->simCtx->FarFluxInSum,
857 .global_farfield_outflow_sum = &user->simCtx->FarFluxOutSum
858 };
859
860 LOG_ALLOW(LOCAL, LOG_TRACE, " Apply: Face %d (%s)\n", i, BCFaceToString((BCFace)i));
861 ierr = handler->Apply(handler, &ctx); CHKERRQ(ierr);
862 }
863
864 // Phase 3: PostStep - Post-application processing (usually no-op for walls)
865 for (int i = 0; i < 6; i++) {
866 BoundaryCondition *handler = user->boundary_faces[i].handler;
867 if (!handler || handler->priority != BC_PRIORITY_WALL) continue;
868 if (!handler->PostStep) continue;
869
870 num_handlers[2]++;
871
872 BCContext ctx = {
873 .user = user,
874 .face_id = (BCFace)i,
875 .global_inflow_sum = &user->simCtx->FluxInSum,
876 .global_outflow_sum = NULL,
877 .global_farfield_inflow_sum = &user->simCtx->FarFluxInSum,
878 .global_farfield_outflow_sum = &user->simCtx->FarFluxOutSum
879 };
880
881 LOG_ALLOW(LOCAL, LOG_TRACE, " PostStep: Face %d (%s)\n", i, BCFaceToString((BCFace)i));
882 ierr = handler->PostStep(handler, &ctx, NULL, NULL); CHKERRQ(ierr);
883 }
884
885 // No global communication needed for walls
886
887 LOG_ALLOW(GLOBAL, LOG_INFO, " (WALLS): %" PetscInt_FMT " Prestep(s), %" PetscInt_FMT " Application(s), %" PetscInt_FMT " Poststep(s) applied.\n",
888 num_handlers[0],num_handlers[1],num_handlers[2]);
889
890
891 // =========================================================================
892 // PRIORITY 3: OUTLETS
893 // =========================================================================
894
895 PetscReal local_outflow_pre = 0.0;
896 PetscReal local_outflow_post = 0.0;
897 PetscReal global_outflow_pre = 0.0;
898 PetscReal global_outflow_post = 0.0;
899 memset(num_handlers,0,sizeof(num_handlers));
900
901 LOG_ALLOW(LOCAL, LOG_TRACE, " (OUTLETS): Begin.\n");
902
903 // Phase 1: PreStep - Measure uncorrected outflow (from ucat)
904 for (int i = 0; i < 6; i++) {
905 BoundaryCondition *handler = user->boundary_faces[i].handler;
906 if (!handler || handler->priority != BC_PRIORITY_OUTLET) continue;
907 if (!handler->PreStep) continue;
908
909 num_handlers[0]++;
910 BCContext ctx = {
911 .user = user,
912 .face_id = (BCFace)i,
913 .global_inflow_sum = &user->simCtx->FluxInSum, // From Priority 0
914 .global_outflow_sum = NULL,
915 .global_farfield_inflow_sum = &user->simCtx->FarFluxInSum,
916 .global_farfield_outflow_sum = &user->simCtx->FarFluxOutSum
917 };
918
919 LOG_ALLOW(LOCAL, LOG_TRACE, " PreStep: Face %d (%s)\n", i, BCFaceToString((BCFace)i));
920 ierr = handler->PreStep(handler, &ctx, NULL, &local_outflow_pre); CHKERRQ(ierr);
921 }
922
923 // Phase 2: Global communication - Get uncorrected outflow sum
924 ierr = MPI_Allreduce(&local_outflow_pre, &global_outflow_pre, 1, MPIU_REAL,
925 MPI_SUM, PETSC_COMM_WORLD); CHKERRQ(ierr);
926
927 // Calculate total inflow (inlet + farfield inflow)
928 PetscReal total_inflow = user->simCtx->FluxInSum + user->simCtx->FarFluxInSum;
929
931 " Uncorrected outflow: %.6e, Total inflow: %.6e (Inlet: %.6e + Farfield: %.6e)\n",
932 global_outflow_pre, total_inflow, user->simCtx->FluxInSum,
933 user->simCtx->FarFluxInSum);
934
935 // Phase 3: Apply - Set corrected boundary conditions
936 for (int i = 0; i < 6; i++) {
937 BoundaryCondition *handler = user->boundary_faces[i].handler;
938 if (!handler || handler->priority != BC_PRIORITY_OUTLET) continue;
939 if(!handler->Apply) continue; // For example Periodic BCs
940
941 num_handlers[1]++;
942
943 BCContext ctx = {
944 .user = user,
945 .face_id = (BCFace)i,
946 .global_inflow_sum = &user->simCtx->FluxInSum, // From Priority 0
947 .global_outflow_sum = &global_outflow_pre, // From PreStep above
948 .global_farfield_inflow_sum = &user->simCtx->FarFluxInSum,
949 .global_farfield_outflow_sum = &user->simCtx->FarFluxOutSum
950 };
951
952 LOG_ALLOW(LOCAL, LOG_TRACE, " Apply: Face %d (%s)\n", i, BCFaceToString((BCFace)i));
953 ierr = handler->Apply(handler, &ctx); CHKERRQ(ierr);
954 }
955
956 // Phase 4: PostStep - Measure corrected outflow (verification)
957 for (int i = 0; i < 6; i++) {
958 BoundaryCondition *handler = user->boundary_faces[i].handler;
959 if (!handler || handler->priority != BC_PRIORITY_OUTLET) continue;
960 if (!handler->PostStep) continue;
961
962 num_handlers[2]++;
963
964 BCContext ctx = {
965 .user = user,
966 .face_id = (BCFace)i,
967 .global_inflow_sum = &user->simCtx->FluxInSum,
968 .global_outflow_sum = &global_outflow_pre,
969 .global_farfield_inflow_sum = &user->simCtx->FarFluxInSum,
970 .global_farfield_outflow_sum = &user->simCtx->FarFluxOutSum
971 };
972
973 LOG_ALLOW(LOCAL, LOG_TRACE, " PostStep: Face %d (%s)\n", i, BCFaceToString((BCFace)i));
974 ierr = handler->PostStep(handler, &ctx, NULL, &local_outflow_post); CHKERRQ(ierr);
975 }
976
977 // Phase 5: Global communication - Verify conservation
978 ierr = MPI_Allreduce(&local_outflow_post, &global_outflow_post, 1, MPIU_REAL,
979 MPI_SUM, PETSC_COMM_WORLD); CHKERRQ(ierr);
980
981 // Store for global reporting.
982 user->simCtx->FluxOutSum = global_outflow_post;
983
984 // Conservation check (compare total outflow vs total inflow)
985 PetscReal total_outflow = global_outflow_post + user->simCtx->FarFluxOutSum;
986 PetscReal flux_error = PetscAbsReal(total_outflow - total_inflow);
987 PetscReal relative_error = (total_inflow > 1e-16) ?
988 flux_error / total_inflow : flux_error;
989
991 " (OUTLETS): %" PetscInt_FMT " Prestep(s), %" PetscInt_FMT " Application(s), %" PetscInt_FMT " Poststep(s), FluxOutSum = %.6e\n",
992 num_handlers[0],num_handlers[1],num_handlers[2], global_outflow_post);
994 " Conservation: Total In=%.6e, Total Out=%.6e, Error=%.3e (%.2e)%%)\n",
995 total_inflow, total_outflow, flux_error, relative_error * 100.0);
996
997 if (relative_error > 1e-6) {
999 " WARNING: Large mass conservation error (%.2e%%)!\n",
1000 relative_error * 100.0);
1001 }
1002
1003
1004 LOG_ALLOW(LOCAL, LOG_VERBOSE, "Complete.\n");
1005
1007 PetscFunctionReturn(0);
1008}
1009
1010// =============================================================================
1011//
1012// PRIVATE "LIGHT" EXECUTION ENGINE
1013//
1014// =============================================================================
1015
1016/**
1017 * @brief Implementation of \ref BoundarySystem_RefreshUbcs().
1018 * @see BoundarySystem_RefreshUbcs()
1019 */
1021{
1022 PetscErrorCode ierr;
1023 PetscFunctionBeginUser;
1025
1026 LOG_ALLOW(GLOBAL, LOG_TRACE, "Refreshing `ubcs` targets for flow-dependent boundaries...\n");
1027
1028 // Loop through all 6 faces of the domain
1029 for (int i = 0; i < 6; i++) {
1030 BoundaryCondition *handler = user->boundary_faces[i].handler;
1031
1032 // THE FILTER:
1033 // This is the core logic. We only act if a handler exists for the face
1034 // AND that handler has explicitly implemented the `UpdateUbcs` method.
1035 if (handler && handler->UpdateUbcs) {
1036
1037 const char *face_name = BCFaceToString((BCFace)i);
1038 LOG_ALLOW(LOCAL, LOG_TRACE, " Calling UpdateUbcs() for handler on Face %s.\n", face_name);
1039
1040 // Prepare the context. For this refresh step, we don't need to pass flux sums.
1041 BCContext ctx = {
1042 .user = user,
1043 .face_id = (BCFace)i,
1044 .global_inflow_sum = NULL,
1045 .global_outflow_sum = NULL,
1046 .global_farfield_inflow_sum = NULL,
1047 .global_farfield_outflow_sum = NULL
1048 };
1049
1050 // Call the handler's specific UpdateUbcs function pointer.
1051 ierr = handler->UpdateUbcs(handler, &ctx); CHKERRQ(ierr);
1052 }
1053 }
1054
1056 PetscFunctionReturn(0);
1057}
1058
1059//================================================================================
1060//
1061// PUBLIC MASTER CLEANUP FUNCTION
1062//
1063//================================================================================
1064/**
1065 * @brief Implementation of \ref BoundarySystem_Destroy().
1066 * @details Full API contract (arguments, ownership, side effects) is documented with
1067 * the header declaration in `include/Boundaries.h`.
1068 * @see BoundarySystem_Destroy()
1069 */
1070PetscErrorCode BoundarySystem_Destroy(UserCtx *user)
1071{
1072 PetscErrorCode ierr;
1073 PetscFunctionBeginUser;
1075
1076
1077
1078 LOG_ALLOW(GLOBAL, LOG_INFO, "Starting destruction of all boundary handlers. \n");
1079
1080 for (int i = 0; i < 6; i++) {
1081 BoundaryFaceConfig *face_cfg = &user->boundary_faces[i];
1082 const char *face_name = BCFaceToString(face_cfg->face_id);
1083
1084 // --- Step 1: Free the parameter linked list associated with this face ---
1085 if (face_cfg->params) {
1086 LOG_ALLOW(LOCAL, LOG_DEBUG, " Freeing parameter list for Face %d (%s). \n", i, face_name);
1087 FreeBC_ParamList(face_cfg->params);
1088 face_cfg->params = NULL; // Good practice to nullify dangling pointers
1089 }
1090
1091 // --- Step 2: Destroy the handler object itself ---
1092 if (face_cfg->handler) {
1093 const char *handler_name = BCHandlerTypeToString(face_cfg->handler->type);
1094 LOG_ALLOW(LOCAL, LOG_DEBUG, " Destroying handler '%s' on Face %d (%s).\n", handler_name, i, face_name);
1095
1096 // Call the handler's specific cleanup function first, if it exists.
1097 // This will free any memory stored in the handler's private `data` pointer.
1098 if (face_cfg->handler->Destroy) {
1099 ierr = face_cfg->handler->Destroy(face_cfg->handler); CHKERRQ(ierr);
1100 }
1101
1102 // Finally, free the generic BoundaryCondition object itself.
1103 ierr = PetscFree(face_cfg->handler); CHKERRQ(ierr);
1104 face_cfg->handler = NULL;
1105 }
1106 }
1107
1108 LOG_ALLOW(GLOBAL, LOG_INFO, "Destruction complete.\n");
1110 PetscFunctionReturn(0);
1111}
1112
1113/**
1114 * @brief Copies one cell field's wrapped local values onto the owned periodic duplicate plane.
1115 * @details Handles scalar and three-component storage for one selected logical axis.
1116 */
1117static PetscErrorCode TransferPeriodicFieldByDirection(UserCtx *user, FieldId field_id, char direction)
1118{
1119 PetscErrorCode ierr;
1120 DMDALocalInfo info = user->info;
1121 PetscInt xs = info.xs, xe = info.xs + info.xm;
1122 PetscInt ys = info.ys, ye = info.ys + info.ym;
1123 PetscInt zs = info.zs, ze = info.zs + info.zm;
1124 PetscInt mx = info.mx, my = info.my, mz = info.mz;
1125
1126 FieldView field_view;
1127 DM dm;
1128 Vec global_vec;
1129 Vec local_vec;
1130 PetscInt dof;
1131
1132 PetscFunctionBeginUser;
1134 PetscCall(FieldGetView(user, field_id, &field_view));
1135 PetscCheck((field_view.descriptor->capabilities & FIELD_CAPABILITY_PERIODIC_CELL_SYNC) != 0u,
1136 PETSC_COMM_SELF, PETSC_ERR_SUP,
1137 "Field '%s' is not registered for periodic cell synchronization.",
1138 field_view.descriptor->canonical_name);
1139 dm = field_view.dm;
1140 global_vec = field_view.global_vec;
1141 local_vec = field_view.local_vec;
1142 dof = field_view.descriptor->dof;
1143
1144 // --- Execute the copy logic based on DoF and Direction ---
1145 if (dof == 1) { // --- Handle SCALAR fields (PetscReal) ---
1146 PetscReal ***g_array, ***l_array;
1147 ierr = DMDAVecGetArray(dm, global_vec, &g_array); CHKERRQ(ierr);
1148 ierr = DMDAVecGetArrayRead(dm, local_vec, (void*)&l_array); CHKERRQ(ierr); // Use Read for safety
1149
1150 switch (direction) {
1151 case 'i':
1152 if (user->boundary_faces[BC_FACE_NEG_X].mathematical_type == PERIODIC && xs == 0) for (PetscInt k=zs; k<ze; k++) for (PetscInt j=ys; j<ye; j++) g_array[k][j][xs] = l_array[k][j][xs-2];
1153 if (user->boundary_faces[BC_FACE_POS_X].mathematical_type == PERIODIC && xe == mx) for (PetscInt k=zs; k<ze; k++) for (PetscInt j=ys; j<ye; j++) g_array[k][j][xe-1] = l_array[k][j][xe+1];
1154 break;
1155 case 'j':
1156 if (user->boundary_faces[BC_FACE_NEG_Y].mathematical_type == PERIODIC && ys == 0) for (PetscInt k=zs; k<ze; k++) for (PetscInt i=xs; i<xe; i++) g_array[k][ys][i] = l_array[k][ys-2][i];
1157 if (user->boundary_faces[BC_FACE_POS_Y].mathematical_type == PERIODIC && ye == my) for (PetscInt k=zs; k<ze; k++) for (PetscInt i=xs; i<xe; i++) g_array[k][ye-1][i] = l_array[k][ye+1][i];
1158 break;
1159 case 'k':
1160 if (user->boundary_faces[BC_FACE_NEG_Z].mathematical_type == PERIODIC && zs == 0) for (PetscInt j=ys; j<ye; j++) for (PetscInt i=xs; i<xe; i++) g_array[zs][j][i] = l_array[zs-2][j][i];
1161 if (user->boundary_faces[BC_FACE_POS_Z].mathematical_type == PERIODIC && ze == mz) for (PetscInt j=ys; j<ye; j++) for (PetscInt i=xs; i<xe; i++) g_array[ze-1][j][i] = l_array[ze+1][j][i];
1162 break;
1163 default: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid direction '%c'", direction);
1164 }
1165 ierr = DMDAVecRestoreArray(dm, global_vec, &g_array); CHKERRQ(ierr);
1166 ierr = DMDAVecRestoreArrayRead(dm, local_vec, (void*)&l_array); CHKERRQ(ierr);
1167
1168 } else if (dof == 3) { // --- Handle VECTOR fields (Cmpnts) ---
1169 Cmpnts ***g_array, ***l_array;
1170 ierr = DMDAVecGetArray(dm, global_vec, &g_array); CHKERRQ(ierr);
1171 ierr = DMDAVecGetArrayRead(dm, local_vec, (void*)&l_array); CHKERRQ(ierr);
1172
1173 switch (direction) {
1174 case 'i':
1175 if (user->boundary_faces[BC_FACE_NEG_X].mathematical_type == PERIODIC && xs == 0) for (PetscInt k=zs; k<ze; k++) for (PetscInt j=ys; j<ye; j++) g_array[k][j][xs] = l_array[k][j][xs-2];
1176 if (user->boundary_faces[BC_FACE_POS_X].mathematical_type == PERIODIC && xe == mx) for (PetscInt k=zs; k<ze; k++) for (PetscInt j=ys; j<ye; j++) g_array[k][j][xe-1] = l_array[k][j][xe+1];
1177 break;
1178 case 'j':
1179 if (user->boundary_faces[BC_FACE_NEG_Y].mathematical_type == PERIODIC && ys == 0) for (PetscInt k=zs; k<ze; k++) for (PetscInt i=xs; i<xe; i++) g_array[k][ys][i] = l_array[k][ys-2][i];
1180 if (user->boundary_faces[BC_FACE_POS_Y].mathematical_type == PERIODIC && ye == my) for (PetscInt k=zs; k<ze; k++) for (PetscInt i=xs; i<xe; i++) g_array[k][ye-1][i] = l_array[k][ye+1][i];
1181 break;
1182 case 'k':
1183 if (user->boundary_faces[BC_FACE_NEG_Z].mathematical_type == PERIODIC && zs == 0) for (PetscInt j=ys; j<ye; j++) for (PetscInt i=xs; i<xe; i++) g_array[zs][j][i] = l_array[zs-2][j][i];
1184 if (user->boundary_faces[BC_FACE_POS_Z].mathematical_type == PERIODIC && ze == mz) for (PetscInt j=ys; j<ye; j++) for (PetscInt i=xs; i<xe; i++) g_array[ze-1][j][i] = l_array[ze+1][j][i];
1185 break;
1186 default: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid direction '%c'", direction);
1187 }
1188 ierr = DMDAVecRestoreArray(dm, global_vec, &g_array); CHKERRQ(ierr);
1189 ierr = DMDAVecRestoreArrayRead(dm, local_vec, (void*)&l_array); CHKERRQ(ierr);
1190 }
1191
1193 PetscFunctionReturn(0);
1194}
1195
1196/**
1197 * @brief Requires a field's local vector to equal a full ghost update, when -picurv_verify_ghost_updates is set.
1198 * @details Rebuilds the update UpdateLocalGhosts() would make (scatter, then periodic repair)
1199 * into a scratch vector and compares every local entry bitwise. The periodic
1200 * synchronizers call it where they rely on an update they did not perform: a caller's
1201 * locals_current claim and every plane-only refresh.
1202 * @param[in] user Block context owning the field.
1203 * @param[in] field_id Field whose local vector is checked.
1204 * @param[in] where Short description of the claim, for the error message.
1205 * @return 0 when the check is off or passes; an error naming the field otherwise.
1206 */
1207static PetscErrorCode VerifyLocalGhostsCurrent(UserCtx *user, FieldId field_id, const char *where)
1208{
1209 FieldView view;
1210 Vec full;
1211 const PetscScalar *expected, *actual;
1212 PetscInt n;
1213 PetscInt64 differing = 0, total = 0;
1214
1215 PetscFunctionBeginUser;
1217 if (!user->simCtx->verifyGhostUpdates) { PROFILE_HELPER_END; PetscFunctionReturn(0); }
1218 PetscCall(FieldGetView(user, field_id, &view));
1219 PetscCall(VecDuplicate(view.local_vec, &full));
1220 PetscCall(DMGlobalToLocalBegin(view.dm, view.global_vec, INSERT_VALUES, full));
1221 PetscCall(DMGlobalToLocalEnd(view.dm, view.global_vec, INSERT_VALUES, full));
1222 PetscCall(RepairPeriodicFieldGhosts(user, &view, full));
1223 PetscCall(VecGetLocalSize(full, &n));
1224 PetscCall(VecGetArrayRead(full, &expected));
1225 PetscCall(VecGetArrayRead(view.local_vec, &actual));
1226 for (PetscInt entry = 0; entry < n; entry++) {
1227 if (memcmp(&expected[entry], &actual[entry], sizeof(PetscScalar))) differing++;
1228 }
1229 PetscCall(VecRestoreArrayRead(view.local_vec, &actual));
1230 PetscCall(VecRestoreArrayRead(full, &expected));
1231 PetscCall(VecDestroy(&full));
1232 PetscCallMPI(MPI_Allreduce(&differing, &total, 1, MPIU_INT64, MPI_SUM, PetscObjectComm((PetscObject)view.dm)));
1233 PetscCheck(total == 0, PetscObjectComm((PetscObject)view.dm), PETSC_ERR_PLIB,
1234 "Ghost-update verification failed for '%s' %s: %" PetscInt64_FMT " local entries differ from a full update.",
1235 view.descriptor->canonical_name, where, total);
1237 PetscFunctionReturn(0);
1238}
1239
1240/**
1241 * @brief Requires the boundary pass's fields to be finite, when -picurv_verify_ghost_updates is set.
1242 * @details The companion of PoisonStaleLocalGhosts(): a stale local vector it filled with NaN
1243 * and something then read would leave non-finite values in these fields.
1244 * @param[in] user Block context after ApplyBoundaryConditions().
1245 * @return 0 when the check is off or passes; an error naming the field otherwise.
1246 */
1247static PetscErrorCode VerifyBoundaryPassFinite(UserCtx *user)
1248{
1249 const FieldId fields[] = {FIELD_ID_UCAT, FIELD_ID_P, FIELD_ID_UCONT};
1250
1251 PetscFunctionBeginUser;
1253 if (!user->simCtx->verifyGhostUpdates) { PROFILE_HELPER_END; PetscFunctionReturn(0); }
1254 for (size_t f = 0; f < sizeof(fields) / sizeof(fields[0]); f++) {
1255 FieldView view;
1256 PetscReal global_norm, local_norm;
1257 PetscCall(FieldGetView(user, fields[f], &view));
1258 PetscCall(VecNorm(view.global_vec, NORM_1, &global_norm));
1259 PetscCall(VecNorm(view.local_vec, NORM_1, &local_norm));
1260 PetscCheck(PetscIsNormalReal(global_norm) || global_norm == 0.0, PetscObjectComm((PetscObject)view.dm), PETSC_ERR_PLIB,
1261 "Ghost-update verification failed: '%s' is not finite after the boundary pass; a stale local vector was read.",
1263 PetscCheck(PetscIsNormalReal(local_norm) || local_norm == 0.0, PetscObjectComm((PetscObject)view.dm), PETSC_ERR_PLIB,
1264 "Ghost-update verification failed: local '%s' is not finite after the boundary pass; a stale local vector was left.",
1266 }
1268 PetscFunctionReturn(0);
1269}
1270
1271/**
1272 * @brief Fills a field's local vector with NaN, when -picurv_verify_ghost_updates is set.
1273 * @details Marks a local vector the boundary pass leaves out of date because a later full
1274 * UpdateLocalGhosts() rewrites all of it before any read. If anything reads it in
1275 * between, the NaN reaches the solution and the run's output.
1276 * @param[in] user Block context owning the field.
1277 * @param[in] field_id Field whose local vector is left stale.
1278 * @return 0 on success.
1279 */
1280static PetscErrorCode PoisonStaleLocalGhosts(UserCtx *user, FieldId field_id)
1281{
1282 FieldView view;
1283
1284 PetscFunctionBeginUser;
1286 if (!user->simCtx->verifyGhostUpdates) { PROFILE_HELPER_END; PetscFunctionReturn(0); }
1287 PetscCall(FieldGetView(user, field_id, &view));
1288 PetscCall(VecSet(view.local_vec, (PetscScalar)NAN));
1290 PetscFunctionReturn(0);
1291}
1292
1293/**
1294 * @brief The scatter that refreshes only the local entries mirroring a DM's two end planes in one direction.
1295 * @details A periodic transfer in direction d writes only the global planes 0 and M_d-1. The
1296 * scatter is the DMDA's global-to-local scatter restricted to the leaves whose periodic
1297 * (wrapped) index along d is one of those planes: the owners' copies and every ghost
1298 * copy, including those across the seam. Built on first use, collectively since every
1299 * rank synchronizes the same DMs, and kept on the DM, which owns it.
1300 * @param[in] dm DMDA of the field being synchronized.
1301 * @param[in] direction 'i', 'j' or 'k'.
1302 * @param[out] plane The scatter, or NULL when the DM is not periodic along direction.
1303 * @return 0 on success.
1304 */
1305static PetscErrorCode GetPeriodicPlaneScatter(DM dm, char direction, VecScatter *plane)
1306{
1307 const PetscInt axis = direction - 'i';
1308 char key[] = "PICurvPeriodicPlaneScatter_?";
1309 PetscObject cached = NULL;
1310 DMBoundaryType boundary[3];
1311 PetscInt size[3], dof, gs[3], gm[3], nleaves, maxleaf, nselected = 0, *selected = NULL;
1312 const PetscInt *ilocal;
1313 VecScatter gtol, embedded;
1314 PetscBool per_point;
1315
1316 PetscFunctionBeginUser;
1318 PetscCheck(axis >= 0 && axis < 3, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid direction '%c'", direction);
1319 *plane = NULL;
1320 PetscCall(DMDAGetInfo(dm, NULL, &size[0], &size[1], &size[2], NULL, NULL, NULL, &dof, NULL,
1321 &boundary[0], &boundary[1], &boundary[2], NULL));
1322 if (boundary[axis] != DM_BOUNDARY_PERIODIC) { PROFILE_HELPER_END; PetscFunctionReturn(0); }
1323 key[sizeof(key) - 2] = direction;
1324 PetscCall(PetscObjectQuery((PetscObject)dm, key, &cached));
1325 if (cached) { *plane = (VecScatter)cached; PROFILE_HELPER_END; PetscFunctionReturn(0); }
1326
1327 PetscCall(DMDAGetGhostCorners(dm, &gs[0], &gs[1], &gs[2], &gm[0], &gm[1], &gm[2]));
1328 PetscCall(DMDAGetScatter(dm, &gtol, NULL));
1329 PetscCall(PetscSFGetGraph(gtol, NULL, &nleaves, &ilocal, NULL));
1330 PetscCall(PetscSFGetLeafRange(gtol, NULL, &maxleaf));
1331 /* Leaves index whole points when the scatter moves dof-sized blocks, single entries otherwise. */
1332 per_point = (PetscBool)(dof == 1 || maxleaf < gm[0] * gm[1] * gm[2]);
1333 PetscCall(PetscMalloc1(nleaves, &selected));
1334 for (PetscInt edge = 0; edge < nleaves; edge++) {
1335 const PetscInt leaf = ilocal ? ilocal[edge] : edge;
1336 const PetscInt point = per_point ? leaf : leaf / dof;
1337 const PetscInt index[3] = {gs[0] + point % gm[0], gs[1] + (point / gm[0]) % gm[1], gs[2] + point / (gm[0] * gm[1])};
1338 const PetscInt wrapped = ((index[axis] % size[axis]) + size[axis]) % size[axis];
1339 if (wrapped == 0 || wrapped == size[axis] - 1) selected[nselected++] = edge;
1340 }
1341 PetscCall(PetscSFCreateEmbeddedLeafSF(gtol, nselected, selected, &embedded));
1342 PetscCall(PetscFree(selected));
1343 PetscCall(PetscObjectCompose((PetscObject)dm, key, (PetscObject)embedded));
1344 PetscCall(PetscSFDestroy(&embedded));
1345 PetscCall(PetscObjectQuery((PetscObject)dm, key, &cached));
1346 *plane = (VecScatter)cached;
1348 PetscFunctionReturn(0);
1349}
1350
1351/**
1352 * @brief Brings a field's local vector up to date after a periodic transfer along one direction.
1353 * @details Precondition: the local vector was the ghost update of the global vector before the
1354 * transfer. The transfer wrote only the end planes along direction, so rescattering the
1355 * entries that mirror those planes and reapplying the periodic repair leaves exactly what
1356 * UpdateLocalGhosts() would. Static so that only the periodic synchronizers below, which
1357 * establish the precondition, can call it; -picurv_verify_ghost_updates checks each call.
1358 * @param[in,out] user Block context owning the field.
1359 * @param[in] field_id Field just transferred.
1360 * @param[in] direction Direction of that transfer.
1361 * @return 0 on success.
1362 */
1363static PetscErrorCode RefreshPeriodicPlaneGhosts(UserCtx *user, FieldId field_id, char direction)
1364{
1365 FieldView view;
1366 VecScatter plane;
1367
1368 PetscFunctionBeginUser;
1370 PetscCall(FieldGetView(user, field_id, &view));
1371 PetscCall(GetPeriodicPlaneScatter(view.dm, direction, &plane));
1372 if (!plane) {
1373 PetscCall(UpdateLocalGhosts(user, field_id));
1374 } else {
1375 PetscCall(VecScatterBegin(plane, view.global_vec, view.local_vec, INSERT_VALUES, SCATTER_FORWARD));
1376 PetscCall(VecScatterEnd(plane, view.global_vec, view.local_vec, INSERT_VALUES, SCATTER_FORWARD));
1377 PetscCall(RepairPeriodicFieldGhosts(user, &view, view.local_vec));
1378 }
1379 PetscCall(VerifyLocalGhostsCurrent(user, field_id, "after a plane-only refresh"));
1381 PetscFunctionReturn(0);
1382}
1383
1384/**
1385 * @brief Body of SynchronizePeriodicCellFields(), optionally without its first or last ghost update.
1386 * @details UpdateLocalGhosts() rebuilds the whole local vector from the global one, so it is
1387 * an exact no-op on a field whose global vector has not been written since its last
1388 * update. A caller that knows this from its own call sequence passes locals_current
1389 * and skips that leading exchange. A caller that updates every listed field again
1390 * before anything reads its local vector passes final_update = PETSC_FALSE and skips
1391 * the update after the last direction's transfers, leaving the local vectors stale
1392 * until then. The transfers themselves always run.
1393 * @param[in,out] user Block context owning the fields.
1394 * @param[in] num_fields Number of cell fields to synchronize.
1395 * @param[in] field_ids Field identifiers.
1396 * @param[in] locals_current PETSC_TRUE when every listed field's local vector is already
1397 * the ghost update of its current global vector.
1398 * @param[in] final_update PETSC_FALSE to leave the last direction's update to the caller.
1399 * @return 0 on success.
1400 */
1401static PetscErrorCode SynchronizePeriodicCellFieldsFrom(UserCtx *user, PetscInt num_fields,
1402 const FieldId field_ids[],
1403 PetscBool locals_current,
1404 PetscBool final_update)
1405{
1406 PetscErrorCode ierr;
1407 PetscBool periodic_i;
1408 PetscBool periodic_j;
1409 PetscBool periodic_k;
1410
1411 PetscFunctionBeginUser;
1413
1414 PetscCheck(num_fields >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE,
1415 "Number of cell fields cannot be negative.");
1416 if (num_fields == 0) { PROFILE_HELPER_END; PetscFunctionReturn(0); }
1417 PetscCheck(field_ids != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
1418 "Cell field-ID array cannot be NULL.");
1419
1420 {
1421 PetscBool periodic[3];
1422 GetPeriodicAxes(user->simCtx, periodic);
1423 periodic_i = periodic[0]; periodic_j = periodic[1]; periodic_k = periodic[2];
1424 }
1425
1426 if (!periodic_i && !periodic_j && !periodic_k) { PROFILE_HELPER_END; PetscFunctionReturn(0); }
1427
1428 for (PetscInt field = 0; field < num_fields; field++) {
1429 if (locals_current) { ierr = VerifyLocalGhostsCurrent(user, field_ids[field], "claimed current by the caller"); CHKERRQ(ierr); }
1430 else { ierr = UpdateLocalGhosts(user, field_ids[field]); CHKERRQ(ierr); }
1431 }
1432
1433 /* Each transfer writes only the end planes of its direction, and the local vectors are
1434 * current before it, so a plane-only refresh restores exactly a full update. */
1435 if (periodic_i) {
1436 for (PetscInt field = 0; field < num_fields; field++) {
1437 ierr = TransferPeriodicFieldByDirection(user, field_ids[field], 'i'); CHKERRQ(ierr);
1438 }
1439 for (PetscInt field = 0; (final_update || periodic_j || periodic_k) && field < num_fields; field++) {
1440 ierr = RefreshPeriodicPlaneGhosts(user, field_ids[field], 'i'); CHKERRQ(ierr);
1441 }
1442 }
1443
1444 if (periodic_j) {
1445 for (PetscInt field = 0; field < num_fields; field++) {
1446 ierr = TransferPeriodicFieldByDirection(user, field_ids[field], 'j'); CHKERRQ(ierr);
1447 }
1448 for (PetscInt field = 0; (final_update || periodic_k) && field < num_fields; field++) {
1449 ierr = RefreshPeriodicPlaneGhosts(user, field_ids[field], 'j'); CHKERRQ(ierr);
1450 }
1451 }
1452
1453 if (periodic_k) {
1454 for (PetscInt field = 0; field < num_fields; field++) {
1455 ierr = TransferPeriodicFieldByDirection(user, field_ids[field], 'k'); CHKERRQ(ierr);
1456 }
1457 for (PetscInt field = 0; final_update && field < num_fields; field++) {
1458 ierr = RefreshPeriodicPlaneGhosts(user, field_ids[field], 'k'); CHKERRQ(ierr);
1459 }
1460 }
1461 for (PetscInt field = 0; !final_update && field < num_fields; field++) {
1462 ierr = PoisonStaleLocalGhosts(user, field_ids[field]); CHKERRQ(ierr);
1463 }
1464
1466 PetscFunctionReturn(0);
1467}
1468
1469/**
1470 * @brief Implementation of \ref SynchronizePeriodicCellFields().
1471 * @details Full API contract is documented with the header declaration in
1472 * `include/Boundaries.h`.
1473 */
1474PetscErrorCode SynchronizePeriodicCellFields(UserCtx *user, PetscInt num_fields, const FieldId field_ids[])
1475{
1476 PetscErrorCode ierr;
1477
1478 PetscFunctionBeginUser;
1480 ierr = SynchronizePeriodicCellFieldsFrom(user, num_fields, field_ids, PETSC_FALSE, PETSC_TRUE); CHKERRQ(ierr);
1482 PetscFunctionReturn(0);
1483}
1484
1485/**
1486 * @brief Resolves one registered persistent single-face-family field.
1487 */
1488static PetscErrorCode GetPersistentFaceField(UserCtx *user, FieldId field_id,
1489 char face_direction, DM *dm,
1490 Vec *global_vec, Vec *local_vec,
1491 PetscInt *dof)
1492{
1493 FieldView field_view;
1494 FieldLayout expected_layout;
1495
1496 PetscFunctionBeginUser;
1498 PetscCheck(face_direction == 'i' || face_direction == 'j' || face_direction == 'k',
1499 PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG,
1500 "Invalid face direction '%c'; expected 'i', 'j', or 'k'.", face_direction);
1501
1502 expected_layout = face_direction == 'i' ? FIELD_LAYOUT_I_FACE :
1503 (face_direction == 'j' ? FIELD_LAYOUT_J_FACE : FIELD_LAYOUT_K_FACE);
1504 PetscCall(FieldGetView(user, field_id, &field_view));
1505 PetscCheck((field_view.descriptor->capabilities & FIELD_CAPABILITY_PERIODIC_FACE_SYNC) != 0u &&
1506 field_view.descriptor->layout == expected_layout,
1507 PETSC_COMM_SELF, PETSC_ERR_SUP,
1508 "Field '%s' is not registered for %c-face periodic synchronization.",
1509 field_view.descriptor->canonical_name, face_direction);
1510
1511 *dm = field_view.dm;
1512 *global_vec = field_view.global_vec;
1513 *local_vec = field_view.local_vec;
1514 *dof = field_view.descriptor->dof;
1516 PetscFunctionReturn(0);
1517}
1518
1519/**
1520 * @brief Returns whether a registered face field stores physical coordinates.
1521 */
1522static PetscErrorCode IsFaceCenterCoordinateField(FieldId field_id, PetscBool *is_coordinate)
1523{
1524 const FieldDescriptor *descriptor = NULL;
1525
1526 PetscFunctionBeginUser;
1528 PetscCheck(is_coordinate != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
1529 "Face-coordinate result cannot be NULL.");
1530 PetscCall(FieldGetDescriptor(field_id, &descriptor));
1531 *is_coordinate = (PetscBool)((descriptor->capabilities & FIELD_CAPABILITY_PERIODIC_GEOMETRY_SHIFT) != 0u);
1533 PetscFunctionReturn(0);
1534}
1535
1536/**
1537 * @brief Applies geometric translations to wrapped face-center ghost coordinates.
1538 */
1539static PetscErrorCode TranslatePeriodicFaceCenterGhosts(UserCtx *user, Vec local_vec)
1540{
1541 DMDALocalInfo info;
1542 Cmpnts ***array;
1543 PetscBool periodic[3];
1544
1545 PetscFunctionBeginUser;
1547 info = user->info;
1548 PetscCall(DMDAVecGetArray(user->fda, local_vec, &array));
1549
1550 GetPeriodicAxes(user->simCtx, periodic);
1551 for (PetscInt axis = 0; axis < 3; axis++) {
1552 const PetscBool active = periodic[axis];
1553 Cmpnts translation;
1554
1555 if (!active) continue;
1556 PetscCheck(user->periodic_translation_valid[axis], PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE,
1557 "Periodic face-center synchronization requires validated %c-direction geometry.",
1558 "XYZ"[axis]);
1559 translation = user->periodic_translation[axis];
1560
1561 for (PetscInt k = info.gzs; k < info.gzs + info.gzm; k++) {
1562 for (PetscInt j = info.gys; j < info.gys + info.gym; j++) {
1563 for (PetscInt i = info.gxs; i < info.gxs + info.gxm; i++) {
1564 PetscReal scale = 0.0;
1565 const PetscInt index = axis == 0 ? i : (axis == 1 ? j : k);
1566 const PetscInt size = axis == 0 ? info.mx : (axis == 1 ? info.my : info.mz);
1567 if (index < 0) scale = -1.0;
1568 else if (index >= size) scale = 1.0;
1569 if (scale == 0.0) continue;
1570 array[k][j][i].x += scale * translation.x;
1571 array[k][j][i].y += scale * translation.y;
1572 array[k][j][i].z += scale * translation.z;
1573 }
1574 }
1575 }
1576 }
1577
1578 PetscCall(DMDAVecRestoreArray(user->fda, local_vec, &array));
1580 PetscFunctionReturn(0);
1581}
1582
1583/** @brief Transfers one registered face-family field along one periodic axis. */
1584static PetscErrorCode TransferPeriodicFaceFieldByDirection(UserCtx *user, FieldId field_id,
1585 char face_direction, char periodic_direction)
1586{
1587 PetscErrorCode ierr;
1588 DMDALocalInfo info = user->info;
1589 PetscInt xs = info.xs, xe = info.xs + info.xm;
1590 PetscInt ys = info.ys, ye = info.ys + info.ym;
1591 PetscInt zs = info.zs, ze = info.zs + info.zm;
1592 PetscInt mx = info.mx, my = info.my, mz = info.mz;
1593 DM dm;
1594 Vec global_vec, local_vec;
1595 PetscInt dof;
1596
1597 PetscFunctionBeginUser;
1599 PetscCheck(periodic_direction == 'i' || periodic_direction == 'j' || periodic_direction == 'k',
1600 PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG,
1601 "Invalid periodic direction '%c'; expected 'i', 'j', or 'k'.", periodic_direction);
1602 PetscCall(GetPersistentFaceField(user, field_id, face_direction, &dm, &global_vec, &local_vec, &dof));
1603
1604 if (dof == 1) {
1605 PetscReal ***global_array, ***local_array;
1606 ierr = DMDAVecGetArray(dm, global_vec, &global_array); CHKERRQ(ierr);
1607 ierr = DMDAVecGetArrayRead(dm, local_vec, &local_array); CHKERRQ(ierr);
1608
1609 if (periodic_direction == 'i') {
1610 if (user->boundary_faces[BC_FACE_NEG_X].mathematical_type == PERIODIC && xs == 0)
1611 for (PetscInt k=zs; k<ze; k++) for (PetscInt j=ys; j<ye; j++) global_array[k][j][0] = local_array[k][j][-2];
1612 if (user->boundary_faces[BC_FACE_POS_X].mathematical_type == PERIODIC && xe == mx)
1613 for (PetscInt k=zs; k<ze; k++) for (PetscInt j=ys; j<ye; j++) global_array[k][j][mx-1] = local_array[k][j][mx+1];
1614 } else if (periodic_direction == 'j') {
1615 if (user->boundary_faces[BC_FACE_NEG_Y].mathematical_type == PERIODIC && ys == 0)
1616 for (PetscInt k=zs; k<ze; k++) for (PetscInt i=xs; i<xe; i++) global_array[k][0][i] = local_array[k][-2][i];
1617 if (user->boundary_faces[BC_FACE_POS_Y].mathematical_type == PERIODIC && ye == my)
1618 for (PetscInt k=zs; k<ze; k++) for (PetscInt i=xs; i<xe; i++) global_array[k][my-1][i] = local_array[k][my+1][i];
1619 } else {
1620 if (user->boundary_faces[BC_FACE_NEG_Z].mathematical_type == PERIODIC && zs == 0)
1621 for (PetscInt j=ys; j<ye; j++) for (PetscInt i=xs; i<xe; i++) global_array[0][j][i] = local_array[-2][j][i];
1622 if (user->boundary_faces[BC_FACE_POS_Z].mathematical_type == PERIODIC && ze == mz)
1623 for (PetscInt j=ys; j<ye; j++) for (PetscInt i=xs; i<xe; i++) global_array[mz-1][j][i] = local_array[mz+1][j][i];
1624 }
1625 ierr = DMDAVecRestoreArrayRead(dm, local_vec, &local_array); CHKERRQ(ierr);
1626 ierr = DMDAVecRestoreArray(dm, global_vec, &global_array); CHKERRQ(ierr);
1627 } else {
1628 Cmpnts ***global_array, ***local_array;
1629 ierr = DMDAVecGetArray(dm, global_vec, &global_array); CHKERRQ(ierr);
1630 ierr = DMDAVecGetArrayRead(dm, local_vec, &local_array); CHKERRQ(ierr);
1631
1632 if (periodic_direction == 'i') {
1633 if (user->boundary_faces[BC_FACE_NEG_X].mathematical_type == PERIODIC && xs == 0)
1634 for (PetscInt k=zs; k<ze; k++) for (PetscInt j=ys; j<ye; j++) global_array[k][j][0] = local_array[k][j][-2];
1635 if (user->boundary_faces[BC_FACE_POS_X].mathematical_type == PERIODIC && xe == mx)
1636 for (PetscInt k=zs; k<ze; k++) for (PetscInt j=ys; j<ye; j++) global_array[k][j][mx-1] = local_array[k][j][mx+1];
1637 } else if (periodic_direction == 'j') {
1638 if (user->boundary_faces[BC_FACE_NEG_Y].mathematical_type == PERIODIC && ys == 0)
1639 for (PetscInt k=zs; k<ze; k++) for (PetscInt i=xs; i<xe; i++) global_array[k][0][i] = local_array[k][-2][i];
1640 if (user->boundary_faces[BC_FACE_POS_Y].mathematical_type == PERIODIC && ye == my)
1641 for (PetscInt k=zs; k<ze; k++) for (PetscInt i=xs; i<xe; i++) global_array[k][my-1][i] = local_array[k][my+1][i];
1642 } else {
1643 if (user->boundary_faces[BC_FACE_NEG_Z].mathematical_type == PERIODIC && zs == 0)
1644 for (PetscInt j=ys; j<ye; j++) for (PetscInt i=xs; i<xe; i++) global_array[0][j][i] = local_array[-2][j][i];
1645 if (user->boundary_faces[BC_FACE_POS_Z].mathematical_type == PERIODIC && ze == mz)
1646 for (PetscInt j=ys; j<ye; j++) for (PetscInt i=xs; i<xe; i++) global_array[mz-1][j][i] = local_array[mz+1][j][i];
1647 }
1648 ierr = DMDAVecRestoreArrayRead(dm, local_vec, &local_array); CHKERRQ(ierr);
1649 ierr = DMDAVecRestoreArray(dm, global_vec, &global_array); CHKERRQ(ierr);
1650 }
1651
1653 PetscFunctionReturn(0);
1654}
1655
1656// Implements SynchronizePeriodicFaceFields(); the public header owns the
1657// rendered API contract.
1658PetscErrorCode SynchronizePeriodicFaceFields(UserCtx *user, char face_direction,
1659 PetscInt num_fields, const FieldId field_ids[])
1660{
1661 PetscErrorCode ierr;
1662 const char periodic_directions[3] = {'i', 'j', 'k'};
1663 const BCFace negative_faces[3] = {BC_FACE_NEG_X, BC_FACE_NEG_Y, BC_FACE_NEG_Z};
1664 const BCFace positive_faces[3] = {BC_FACE_POS_X, BC_FACE_POS_Y, BC_FACE_POS_Z};
1665
1666 PetscFunctionBeginUser;
1668 PetscCheck(num_fields >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE,
1669 "Number of face fields cannot be negative.");
1670 if (num_fields == 0) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
1671 PetscCheck(field_ids != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
1672 "Face field-ID array cannot be NULL.");
1673
1674 for (PetscInt field = 0; field < num_fields; field++) {
1675 DM dm;
1676 Vec global_vec, local_vec;
1677 PetscInt dof;
1678 PetscBool is_coordinate;
1679 PetscCall(GetPersistentFaceField(user, field_ids[field], face_direction,
1680 &dm, &global_vec, &local_vec, &dof));
1681 ierr = UpdateLocalGhosts(user, field_ids[field]); CHKERRQ(ierr);
1682 ierr = IsFaceCenterCoordinateField(field_ids[field], &is_coordinate); CHKERRQ(ierr);
1683 if (is_coordinate) {
1684 ierr = TranslatePeriodicFaceCenterGhosts(user, local_vec); CHKERRQ(ierr);
1685 }
1686 }
1687
1688 for (PetscInt direction = 0; direction < 3; direction++) {
1689 const PetscBool active =
1690 user->boundary_faces[negative_faces[direction]].mathematical_type == PERIODIC ||
1691 user->boundary_faces[positive_faces[direction]].mathematical_type == PERIODIC;
1692 if (!active) continue;
1693
1694 for (PetscInt field = 0; field < num_fields; field++) {
1695 ierr = TransferPeriodicFaceFieldByDirection(user, field_ids[field], face_direction,
1696 periodic_directions[direction]); CHKERRQ(ierr);
1697 }
1698 for (PetscInt field = 0; field < num_fields; field++) {
1699 DM dm;
1700 Vec global_vec, local_vec;
1701 PetscInt dof;
1702 PetscBool is_coordinate;
1703 ierr = UpdateLocalGhosts(user, field_ids[field]); CHKERRQ(ierr);
1704 ierr = IsFaceCenterCoordinateField(field_ids[field], &is_coordinate); CHKERRQ(ierr);
1705 if (is_coordinate) {
1706 PetscCall(GetPersistentFaceField(user, field_ids[field], face_direction,
1707 &dm, &global_vec, &local_vec, &dof));
1708 ierr = TranslatePeriodicFaceCenterGhosts(user, local_vec); CHKERRQ(ierr);
1709 }
1710 }
1711 }
1712
1714 PetscFunctionReturn(0);
1715}
1716
1717/**
1718 * @brief Resolves one registered persistent component-staggered field.
1719 */
1720static PetscErrorCode GetPersistentStaggeredField(UserCtx *user, FieldId field_id,
1721 DM *dm, Vec *global_vec, Vec *local_vec)
1722{
1723 FieldView field_view;
1724
1725 PetscFunctionBeginUser;
1727 PetscCall(FieldGetView(user, field_id, &field_view));
1728 PetscCheck((field_view.descriptor->capabilities & FIELD_CAPABILITY_PERIODIC_STAGGERED_SYNC) != 0u &&
1730 PETSC_COMM_SELF, PETSC_ERR_SUP,
1731 "Field '%s' is not registered for component-staggered periodic synchronization.",
1732 field_view.descriptor->canonical_name);
1733 *dm = field_view.dm;
1734 *global_vec = field_view.global_vec;
1735 *local_vec = field_view.local_vec;
1737 PetscFunctionReturn(0);
1738}
1739
1740/**
1741 * @brief Transfers one component-staggered field along one periodic axis.
1742 */
1743static PetscErrorCode TransferPeriodicStaggeredFieldByDirection(UserCtx *user, FieldId field_id,
1744 char periodic_direction)
1745{
1746 PetscErrorCode ierr;
1747 DMDALocalInfo info = user->info;
1748 PetscInt xs = info.xs, xe = info.xs + info.xm;
1749 PetscInt ys = info.ys, ye = info.ys + info.ym;
1750 PetscInt zs = info.zs, ze = info.zs + info.zm;
1751 PetscInt mx = info.mx, my = info.my, mz = info.mz;
1752 DM dm;
1753 Vec global_vec, local_vec;
1754 Cmpnts ***global_array, ***local_array;
1755
1756 PetscFunctionBeginUser;
1758 PetscCheck(periodic_direction == 'i' || periodic_direction == 'j' || periodic_direction == 'k',
1759 PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG,
1760 "Invalid periodic direction '%c'; expected 'i', 'j', or 'k'.", periodic_direction);
1761 PetscCall(GetPersistentStaggeredField(user, field_id, &dm, &global_vec, &local_vec));
1762
1763 ierr = DMDAVecGetArray(dm, global_vec, &global_array); CHKERRQ(ierr);
1764 ierr = DMDAVecGetArrayRead(dm, local_vec, &local_array); CHKERRQ(ierr);
1765
1766 if (periodic_direction == 'i') {
1767 if (user->boundary_faces[BC_FACE_NEG_X].mathematical_type == PERIODIC && xs == 0)
1768 for (PetscInt k=zs; k<ze; k++) for (PetscInt j=ys; j<ye; j++) global_array[k][j][0] = local_array[k][j][-2];
1769 if (user->boundary_faces[BC_FACE_POS_X].mathematical_type == PERIODIC && xe == mx)
1770 for (PetscInt k=zs; k<ze; k++) for (PetscInt j=ys; j<ye; j++) global_array[k][j][mx-1] = local_array[k][j][mx+1];
1771 } else if (periodic_direction == 'j') {
1772 if (user->boundary_faces[BC_FACE_NEG_Y].mathematical_type == PERIODIC && ys == 0)
1773 for (PetscInt k=zs; k<ze; k++) for (PetscInt i=xs; i<xe; i++) global_array[k][0][i] = local_array[k][-2][i];
1774 if (user->boundary_faces[BC_FACE_POS_Y].mathematical_type == PERIODIC && ye == my)
1775 for (PetscInt k=zs; k<ze; k++) for (PetscInt i=xs; i<xe; i++) global_array[k][my-1][i] = local_array[k][my+1][i];
1776 } else {
1777 if (user->boundary_faces[BC_FACE_NEG_Z].mathematical_type == PERIODIC && zs == 0)
1778 for (PetscInt j=ys; j<ye; j++) for (PetscInt i=xs; i<xe; i++) global_array[0][j][i] = local_array[-2][j][i];
1779 if (user->boundary_faces[BC_FACE_POS_Z].mathematical_type == PERIODIC && ze == mz)
1780 for (PetscInt j=ys; j<ye; j++) for (PetscInt i=xs; i<xe; i++) global_array[mz-1][j][i] = local_array[mz+1][j][i];
1781 }
1782
1783 ierr = DMDAVecRestoreArrayRead(dm, local_vec, &local_array); CHKERRQ(ierr);
1784 ierr = DMDAVecRestoreArray(dm, global_vec, &global_array); CHKERRQ(ierr);
1786 PetscFunctionReturn(0);
1787}
1788
1789/**
1790 * @brief Body of SynchronizePeriodicStaggeredFields(), optionally without its leading ghost update.
1791 * @details As for SynchronizePeriodicCellFieldsFrom(): locals_current skips only the leading
1792 * UpdateLocalGhosts(), an exact no-op when no global vector was written since its
1793 * last update; the per-direction transfers and their updates always run.
1794 * @param[in,out] user Block context owning the fields.
1795 * @param[in] num_fields Number of staggered fields to synchronize.
1796 * @param[in] field_ids Field identifiers.
1797 * @param[in] locals_current PETSC_TRUE when every listed field's local vector is already
1798 * the ghost update of its current global vector.
1799 * @return 0 on success.
1800 */
1801static PetscErrorCode SynchronizePeriodicStaggeredFieldsFrom(UserCtx *user, PetscInt num_fields,
1802 const FieldId field_ids[],
1803 PetscBool locals_current)
1804{
1805 PetscErrorCode ierr;
1806 const char periodic_directions[3] = {'i', 'j', 'k'};
1807 const BCFace negative_faces[3] = {BC_FACE_NEG_X, BC_FACE_NEG_Y, BC_FACE_NEG_Z};
1808 const BCFace positive_faces[3] = {BC_FACE_POS_X, BC_FACE_POS_Y, BC_FACE_POS_Z};
1809
1810 PetscFunctionBeginUser;
1812 PetscCheck(num_fields >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE,
1813 "Number of staggered fields cannot be negative.");
1814 if (num_fields == 0) { PROFILE_HELPER_END; PetscFunctionReturn(0); }
1815 PetscCheck(field_ids != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
1816 "Staggered field-ID array cannot be NULL.");
1817
1818 for (PetscInt field = 0; field < num_fields; field++) {
1819 DM dm;
1820 Vec global_vec, local_vec;
1821 PetscCall(GetPersistentStaggeredField(user, field_ids[field], &dm, &global_vec, &local_vec));
1822 if (locals_current) { ierr = VerifyLocalGhostsCurrent(user, field_ids[field], "claimed current by the caller"); CHKERRQ(ierr); }
1823 else { ierr = UpdateLocalGhosts(user, field_ids[field]); CHKERRQ(ierr); }
1824 }
1825
1826 for (PetscInt direction = 0; direction < 3; direction++) {
1827 const PetscBool active =
1828 user->boundary_faces[negative_faces[direction]].mathematical_type == PERIODIC ||
1829 user->boundary_faces[positive_faces[direction]].mathematical_type == PERIODIC;
1830 if (!active) continue;
1831
1832 for (PetscInt field = 0; field < num_fields; field++) {
1833 ierr = TransferPeriodicStaggeredFieldByDirection(user, field_ids[field],
1834 periodic_directions[direction]); CHKERRQ(ierr);
1835 }
1836 /* As in SynchronizePeriodicCellFieldsFrom(): the transfer wrote only this direction's
1837 * end planes into current local vectors, so a plane-only refresh suffices. */
1838 for (PetscInt field = 0; field < num_fields; field++) {
1839 ierr = RefreshPeriodicPlaneGhosts(user, field_ids[field], periodic_directions[direction]); CHKERRQ(ierr);
1840 }
1841 }
1842
1844 PetscFunctionReturn(0);
1845}
1846
1847/**
1848 * @brief Implementation of \ref SynchronizePeriodicStaggeredFields().
1849 */
1850PetscErrorCode SynchronizePeriodicStaggeredFields(UserCtx *user, PetscInt num_fields,
1851 const FieldId field_ids[])
1852{
1853 PetscErrorCode ierr;
1854
1855 PetscFunctionBeginUser;
1857 ierr = SynchronizePeriodicStaggeredFieldsFrom(user, num_fields, field_ids, PETSC_FALSE); CHKERRQ(ierr);
1859 PetscFunctionReturn(0);
1860}
1861
1862/**
1863 * @brief Implementation of \ref PreparePeriodicQuickStencilFields().
1864 */
1865PetscErrorCode PreparePeriodicQuickStencilFields(UserCtx *user, Vec local_vector_field,
1866 Vec local_scalar_field)
1867{
1868 DMDALocalInfo info = user->info;
1869 Cmpnts ***vector_array;
1870 PetscReal ***scalar_array;
1871 const PetscInt xs = info.xs, xe = info.xs + info.xm;
1872 const PetscInt ys = info.ys, ye = info.ys + info.ym;
1873 const PetscInt zs = info.zs, ze = info.zs + info.zm;
1874 const PetscInt gxs = info.gxs, gxe = info.gxs + info.gxm;
1875 const PetscInt gys = info.gys, gye = info.gys + info.gym;
1876 const PetscInt gzs = info.gzs, gze = info.gzs + info.gzm;
1877
1878 PetscFunctionBeginUser;
1880 PetscCheck(local_vector_field && local_scalar_field, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
1881 "QUICK stencil repair requires both local vector and scalar fields.");
1882 PetscCall(DMDAVecGetArray(user->fda, local_vector_field, &vector_array));
1883 PetscCall(DMDAVecGetArray(user->da, local_scalar_field, &scalar_array));
1884
1885 if (user->boundary_faces[BC_FACE_NEG_X].mathematical_type == PERIODIC && xs == 0) {
1886 for (PetscInt k = gzs; k < gze; k++) for (PetscInt j = gys; j < gye; j++) {
1887 vector_array[k][j][-1] = vector_array[k][j][-3];
1888 scalar_array[k][j][-1] = scalar_array[k][j][-3];
1889 }
1890 }
1891 if (user->boundary_faces[BC_FACE_POS_X].mathematical_type == PERIODIC && xe == info.mx) {
1892 for (PetscInt k = gzs; k < gze; k++) for (PetscInt j = gys; j < gye; j++) {
1893 vector_array[k][j][info.mx] = vector_array[k][j][info.mx + 2];
1894 scalar_array[k][j][info.mx] = scalar_array[k][j][info.mx + 2];
1895 }
1896 }
1897 if (user->boundary_faces[BC_FACE_NEG_Y].mathematical_type == PERIODIC && ys == 0) {
1898 for (PetscInt k = gzs; k < gze; k++) for (PetscInt i = gxs; i < gxe; i++) {
1899 vector_array[k][-1][i] = vector_array[k][-3][i];
1900 scalar_array[k][-1][i] = scalar_array[k][-3][i];
1901 }
1902 }
1903 if (user->boundary_faces[BC_FACE_POS_Y].mathematical_type == PERIODIC && ye == info.my) {
1904 for (PetscInt k = gzs; k < gze; k++) for (PetscInt i = gxs; i < gxe; i++) {
1905 vector_array[k][info.my][i] = vector_array[k][info.my + 2][i];
1906 scalar_array[k][info.my][i] = scalar_array[k][info.my + 2][i];
1907 }
1908 }
1909 if (user->boundary_faces[BC_FACE_NEG_Z].mathematical_type == PERIODIC && zs == 0) {
1910 for (PetscInt j = gys; j < gye; j++) for (PetscInt i = gxs; i < gxe; i++) {
1911 vector_array[-1][j][i] = vector_array[-3][j][i];
1912 scalar_array[-1][j][i] = scalar_array[-3][j][i];
1913 }
1914 }
1915 if (user->boundary_faces[BC_FACE_POS_Z].mathematical_type == PERIODIC && ze == info.mz) {
1916 for (PetscInt j = gys; j < gye; j++) for (PetscInt i = gxs; i < gxe; i++) {
1917 vector_array[info.mz][j][i] = vector_array[info.mz + 2][j][i];
1918 scalar_array[info.mz][j][i] = scalar_array[info.mz + 2][j][i];
1919 }
1920 }
1921
1922 PetscCall(DMDAVecRestoreArray(user->da, local_scalar_field, &scalar_array));
1923 PetscCall(DMDAVecRestoreArray(user->fda, local_vector_field, &vector_array));
1925 PetscFunctionReturn(0);
1926}
1927
1928/**
1929 * @brief Implementation of \ref SynchronizePeriodicLocalStaggeredField().
1930 */
1931PetscErrorCode SynchronizePeriodicLocalStaggeredField(UserCtx *user, Vec local_field)
1932{
1933 DMDALocalInfo info = user->info;
1934 Cmpnts ***array;
1935 const PetscInt xs = info.xs, xe = info.xs + info.xm;
1936 const PetscInt ys = info.ys, ye = info.ys + info.ym;
1937 const PetscInt zs = info.zs, ze = info.zs + info.zm;
1938
1939 PetscFunctionBeginUser;
1941 PetscCheck(local_field, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
1942 "Local staggered field cannot be NULL.");
1943 PetscCall(DMLocalToLocalBegin(user->fda, local_field, INSERT_VALUES, local_field));
1944 PetscCall(DMLocalToLocalEnd(user->fda, local_field, INSERT_VALUES, local_field));
1945 PetscCall(DMDAVecGetArray(user->fda, local_field, &array));
1946
1947 if (user->boundary_faces[BC_FACE_NEG_X].mathematical_type == PERIODIC && xs == 0)
1948 for (PetscInt k = zs; k < ze; k++) for (PetscInt j = ys; j < ye; j++) array[k][j][0].x = array[k][j][-2].x;
1949 if (user->boundary_faces[BC_FACE_POS_X].mathematical_type == PERIODIC && xe == info.mx)
1950 for (PetscInt k = zs; k < ze; k++) for (PetscInt j = ys; j < ye; j++) array[k][j][info.mx - 1].x = array[k][j][info.mx + 1].x;
1951 if (user->boundary_faces[BC_FACE_NEG_Y].mathematical_type == PERIODIC && ys == 0)
1952 for (PetscInt k = zs; k < ze; k++) for (PetscInt i = xs; i < xe; i++) array[k][0][i].y = array[k][-2][i].y;
1953 if (user->boundary_faces[BC_FACE_POS_Y].mathematical_type == PERIODIC && ye == info.my)
1954 for (PetscInt k = zs; k < ze; k++) for (PetscInt i = xs; i < xe; i++) array[k][info.my - 1][i].y = array[k][info.my + 1][i].y;
1955 if (user->boundary_faces[BC_FACE_NEG_Z].mathematical_type == PERIODIC && zs == 0)
1956 for (PetscInt j = ys; j < ye; j++) for (PetscInt i = xs; i < xe; i++) array[0][j][i].z = array[-2][j][i].z;
1957 if (user->boundary_faces[BC_FACE_POS_Z].mathematical_type == PERIODIC && ze == info.mz)
1958 for (PetscInt j = ys; j < ye; j++) for (PetscInt i = xs; i < xe; i++) array[info.mz - 1][j][i].z = array[info.mz + 1][j][i].z;
1959
1960 PetscCall(DMDAVecRestoreArray(user->fda, local_field, &array));
1961 PetscCall(DMLocalToLocalBegin(user->fda, local_field, INSERT_VALUES, local_field));
1962 PetscCall(DMLocalToLocalEnd(user->fda, local_field, INSERT_VALUES, local_field));
1964 PetscFunctionReturn(0);
1965}
1966
1967/**
1968 * @brief Implementation of \ref ApplyMetricsPeriodicBCs().
1969 * @see ApplyMetricsPeriodicBCs()
1970 */
1972{
1973 PetscErrorCode ierr;
1974 PetscFunctionBeginUser;
1976
1977 const FieldId cell_fields[] = {FIELD_ID_AJ};
1978 const FieldId i_face_fields[] = {FIELD_ID_CENTX, FIELD_ID_CSI, FIELD_ID_ICSI,
1980 const FieldId j_face_fields[] = {FIELD_ID_CENTY, FIELD_ID_ETA, FIELD_ID_JCSI,
1982 const FieldId k_face_fields[] = {FIELD_ID_CENTZ, FIELD_ID_ZET, FIELD_ID_KCSI,
1984
1985 ierr = SynchronizePeriodicCellFields(user, 1, cell_fields); CHKERRQ(ierr);
1986 ierr = SynchronizePeriodicFaceFields(user, 'i', 6, i_face_fields); CHKERRQ(ierr);
1987 ierr = SynchronizePeriodicFaceFields(user, 'j', 6, j_face_fields); CHKERRQ(ierr);
1988 ierr = SynchronizePeriodicFaceFields(user, 'k', 6, k_face_fields); CHKERRQ(ierr);
1989
1991 PetscFunctionReturn(0);
1992}
1993
1994/**
1995 * @brief Implementation of \ref ApplyPeriodicBCs().
1996 * @see ApplyPeriodicBCs()
1997 */
1998PetscErrorCode ApplyPeriodicBCs(UserCtx *user, PetscBool final_cell_update)
1999{
2000 PetscErrorCode ierr;
2001 PetscBool periodic[3], is_any_periodic;
2002
2003 PetscFunctionBeginUser;
2004
2006
2007 GetPeriodicAxes(user->simCtx, periodic);
2008 is_any_periodic = (PetscBool)(periodic[0] || periodic[1] || periodic[2]);
2009
2010 if (!is_any_periodic) {
2011 LOG_ALLOW(GLOBAL,LOG_TRACE, "No periodic boundaries defined; skipping ApplyPeriodicBCs.\n");
2013 PetscFunctionReturn(0);
2014 }
2015
2016 LOG_ALLOW(GLOBAL, LOG_TRACE, "Applying periodic boundary conditions for all fields.\n");
2017
2018 // STEP 1: Synchronize periodic cell-centered fields in deterministic direction order.
2019 const FieldId cell_fields[] = {FIELD_ID_UCAT, FIELD_ID_P, FIELD_ID_NVERT};
2020 ierr = SynchronizePeriodicCellFieldsFrom(user, 3, cell_fields, PETSC_FALSE, final_cell_update); CHKERRQ(ierr);
2021
2022 // STEP 2: Synchronize persistent staggered endpoints and repair local
2023 // component-normal ghosts through UpdateLocalGhosts().
2024 const FieldId staggered_fields[] = {FIELD_ID_UCONT};
2025 ierr = SynchronizePeriodicStaggeredFields(user, 1, staggered_fields); CHKERRQ(ierr);
2026
2028 PetscFunctionReturn(0);
2029}
2030
2031/**
2032 * @brief Implementation of \ref UpdateDummyCells().
2033 * @details Full API contract is documented with the header declaration in
2034 * `include/Boundaries.h`.
2035 * @see UpdateDummyCells()
2036 */
2037PetscErrorCode UpdateDummyCells(UserCtx *user, FieldId field_id)
2038{
2039 DMDALocalInfo info = user->info;
2040 PetscInt xs = info.xs, xe = info.xs + info.xm;
2041 PetscInt ys = info.ys, ye = info.ys + info.ym;
2042 PetscInt zs = info.zs, ze = info.zs + info.zm;
2043 PetscInt mx = info.mx, my = info.my, mz = info.mz;
2044 FieldView view;
2045 PetscScalar ****field = NULL, ****ubcs = NULL;
2046 PetscInt dof;
2047 PetscBool from_boundary_value, fills[6];
2048
2049 // --- Calculate shrunken loop ranges to avoid edges and corners ---
2050 PetscInt lxs = (xs == 0) ? xs + 1 : xs, lxe = (xe == mx) ? xe - 1 : xe;
2051 PetscInt lys = (ys == 0) ? ys + 1 : ys, lye = (ye == my) ? ye - 1 : ye;
2052 PetscInt lzs = (zs == 0) ? zs + 1 : zs, lze = (ze == mz) ? ze - 1 : ze;
2053
2054 PetscFunctionBeginUser;
2056 PetscCall(FieldGetView(user, field_id, &view));
2057 PetscCheck(view.descriptor->layout == FIELD_LAYOUT_CELL_CENTERED, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG,
2058 "UpdateDummyCells fills cell-centred fields; '%s' is not one.", view.descriptor->canonical_name);
2059 /* The dummy value is the quantity's boundary condition. Velocity takes the
2060 * boundary value the handlers set, placed so the face average equals it. Pressure
2061 * and the particle scalar take the adjacent cell's value: zero normal gradient. The
2062 * eddy viscosity mirrors only across a free-slip wall, where the flow mirrors and the
2063 * face average must equal the interior value; a wall that exerts shear replaces it on
2064 * the face, and no other face's eddy-viscosity dummy cells are written here. */
2065 PetscCheck(field_id == FIELD_ID_UCAT || field_id == FIELD_ID_P || field_id == FIELD_ID_PSI ||
2066 field_id == FIELD_ID_NU_T,
2067 PETSC_COMM_SELF, PETSC_ERR_SUP,
2068 "UpdateDummyCells has no boundary rule for '%s'; one must be chosen for the quantity "
2069 "before its dummy cells are filled.", view.descriptor->canonical_name);
2070 from_boundary_value = (PetscBool)(field_id == FIELD_ID_UCAT);
2071 for (PetscInt face = 0; face < 6; ++face) {
2072 const BoundaryFaceConfig *config = &user->boundary_faces[face];
2073
2074 fills[face] = (field_id == FIELD_ID_NU_T)
2076 : (PetscBool)(config->mathematical_type != PERIODIC);
2077 }
2078 dof = view.descriptor->dof;
2079
2080 PetscCall(DMDAVecGetArrayDOF(view.dm, view.global_vec, &field));
2081 if (from_boundary_value) PetscCall(DMDAVecGetArrayDOF(user->fda, user->Bcs.Ubcs, &ubcs));
2082
2083 // -X Face
2084 if (fills[BC_FACE_NEG_X] && xs == 0) {
2085 for (PetscInt k = lzs; k < lze; k++) for (PetscInt j = lys; j < lye; j++) for (PetscInt c = 0; c < dof; c++)
2086 field[k][j][xs][c] = from_boundary_value ? 2.0 * ubcs[k][j][xs][c] - field[k][j][xs + 1][c]
2087 : field[k][j][xs + 1][c];
2088 }
2089 // +X Face
2090 if (fills[BC_FACE_POS_X] && xe == mx) {
2091 for (PetscInt k = lzs; k < lze; k++) for (PetscInt j = lys; j < lye; j++) for (PetscInt c = 0; c < dof; c++)
2092 field[k][j][xe-1][c] = from_boundary_value ? 2.0 * ubcs[k][j][xe-1][c] - field[k][j][xe - 2][c]
2093 : field[k][j][xe - 2][c];
2094 }
2095 // -Y Face
2096 if (fills[BC_FACE_NEG_Y] && ys == 0) {
2097 for (PetscInt k = lzs; k < lze; k++) for (PetscInt i = lxs; i < lxe; i++) for (PetscInt c = 0; c < dof; c++)
2098 field[k][ys][i][c] = from_boundary_value ? 2.0 * ubcs[k][ys][i][c] - field[k][ys + 1][i][c]
2099 : field[k][ys + 1][i][c];
2100 }
2101 // +Y Face
2102 if (fills[BC_FACE_POS_Y] && ye == my) {
2103 for (PetscInt k = lzs; k < lze; k++) for (PetscInt i = lxs; i < lxe; i++) for (PetscInt c = 0; c < dof; c++)
2104 field[k][ye-1][i][c] = from_boundary_value ? 2.0 * ubcs[k][ye-1][i][c] - field[k][ye-2][i][c]
2105 : field[k][ye-2][i][c];
2106 }
2107 // -Z Face
2108 if (fills[BC_FACE_NEG_Z] && zs == 0) {
2109 for (PetscInt j = lys; j < lye; j++) for (PetscInt i = lxs; i < lxe; i++) for (PetscInt c = 0; c < dof; c++)
2110 field[zs][j][i][c] = from_boundary_value ? 2.0 * ubcs[zs][j][i][c] - field[zs + 1][j][i][c]
2111 : field[zs + 1][j][i][c];
2112 }
2113 // +Z Face
2114 if (fills[BC_FACE_POS_Z] && ze == mz) {
2115 for (PetscInt j = lys; j < lye; j++) for (PetscInt i = lxs; i < lxe; i++) for (PetscInt c = 0; c < dof; c++)
2116 field[ze-1][j][i][c] = from_boundary_value ? 2.0 * ubcs[ze-1][j][i][c] - field[ze-2][j][i][c]
2117 : field[ze-2][j][i][c];
2118 }
2119
2120 if (from_boundary_value) PetscCall(DMDAVecRestoreArrayDOF(user->fda, user->Bcs.Ubcs, &ubcs));
2121 PetscCall(DMDAVecRestoreArrayDOF(view.dm, view.global_vec, &field));
2123 PetscFunctionReturn(0);
2124}
2125
2126/**
2127 * @brief Internal helper: the face separating an edge dummy cell from one neighbour.
2128 * @details Local to this translation unit. The two cells differ in exactly one index,
2129 * and the target's own value of it says which side of the domain the face is on.
2130 */
2131static BCFace EdgeSeparatingFace(PetscInt tk, PetscInt tj, PetscInt ti,
2132 PetscInt nk, PetscInt nj, PetscInt ni)
2133{
2134 if (nk != tk) return (tk == 0) ? BC_FACE_NEG_Z : BC_FACE_POS_Z;
2135 if (nj != tj) return (tj == 0) ? BC_FACE_NEG_Y : BC_FACE_POS_Y;
2136 (void)ni;
2137 return (ti == 0) ? BC_FACE_NEG_X : BC_FACE_POS_X;
2138}
2139
2140/**
2141 * @brief Internal helper: fills one edge dummy cell from its two face-adjacent dummy cells.
2142 * @details Local to this translation unit. Across a free-slip wall the flow is the mirror
2143 * image of the flow inside, so the edge cell is the mirror image of the neighbour
2144 * on the other side of that wall: a scalar is copied, and a velocity has its
2145 * component along the wall's metric reversed. Elsewhere the edge cell is the mean
2146 * of the two neighbours.
2147 */
2148static void FillEdgeCell(PetscScalar ****f, PetscInt dof, const PetscBool free_slip[6],
2149 Cmpnts ***const metric[3],
2150 PetscInt tk, PetscInt tj, PetscInt ti,
2151 PetscInt ak, PetscInt aj, PetscInt ai,
2152 PetscInt bk, PetscInt bj, PetscInt bi)
2153{
2154 const BCFace face_a = EdgeSeparatingFace(tk, tj, ti, ak, aj, ai);
2155 const BCFace face_b = EdgeSeparatingFace(tk, tj, ti, bk, bj, bi);
2156 PetscInt sk = ak, sj = aj, si = ai;
2157 BCFace mirror = face_a;
2158
2159 if (!free_slip[face_a] && !free_slip[face_b]) {
2160 for (PetscInt c = 0; c < dof; c++) f[tk][tj][ti][c] = 0.5 * (f[ak][aj][ai][c] + f[bk][bj][bi][c]);
2161 return;
2162 }
2163 if (!free_slip[face_a]) { sk = bk; sj = bj; si = bi; mirror = face_b; }
2164 for (PetscInt c = 0; c < dof; c++) f[tk][tj][ti][c] = f[sk][sj][si][c];
2165 if (dof == 3) {
2166 const Cmpnts n = metric[mirror / 2][sk][sj][si];
2167 const PetscReal area_sq = n.x * n.x + n.y * n.y + n.z * n.z;
2168 const PetscReal normal = (area_sq > 0.0)
2169 ? (f[sk][sj][si][0] * n.x + f[sk][sj][si][1] * n.y + f[sk][sj][si][2] * n.z) / area_sq : 0.0;
2170
2171 f[tk][tj][ti][0] -= 2.0 * normal * n.x;
2172 f[tk][tj][ti][1] -= 2.0 * normal * n.y;
2173 f[tk][tj][ti][2] -= 2.0 * normal * n.z;
2174 }
2175}
2176
2177/**
2178 * @brief Implementation of \ref UpdateCornerNodes().
2179 * @details Full API contract is documented with the header declaration in
2180 * `include/Boundaries.h`.
2181 * @see UpdateCornerNodes()
2182 */
2183PetscErrorCode UpdateCornerNodes(UserCtx *user, FieldId field_id)
2184{
2185 DMDALocalInfo info = user->info;
2186 PetscInt xs = info.xs, xe = info.xs + info.xm;
2187 PetscInt ys = info.ys, ye = info.ys + info.ym;
2188 PetscInt zs = info.zs, ze = info.zs + info.zm;
2189 PetscInt mx = info.mx, my = info.my, mz = info.mz;
2190 FieldView view;
2191 PetscScalar ****f = NULL;
2192 PetscInt dof;
2193 PetscBool free_slip[6], any_free_slip = PETSC_FALSE;
2194 Cmpnts ***metric[3] = {NULL, NULL, NULL};
2195
2196 PetscFunctionBeginUser;
2198 PetscCall(FieldGetView(user, field_id, &view));
2199 PetscCheck(view.descriptor->layout == FIELD_LAYOUT_CELL_CENTERED, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG,
2200 "UpdateCornerNodes fills cell-centred fields; '%s' is not one.", view.descriptor->canonical_name);
2201 dof = view.descriptor->dof;
2202 for (PetscInt face = 0; face < 6; ++face) {
2203 const BoundaryFaceConfig *config = &user->boundary_faces[face];
2204
2205 free_slip[face] = BoundaryFaceIsFreeSlipWall(config);
2206 any_free_slip = (PetscBool)(any_free_slip || free_slip[face]);
2207 }
2208 PetscCall(DMDAVecGetArrayDOF(view.dm, view.global_vec, &f));
2209 /* A velocity mirrors along the wall's own normal, which only a free-slip edge needs. */
2210 if (any_free_slip && dof == 3) {
2211 PetscCall(DMDAVecGetArrayRead(user->fda, user->lCsi, (const Cmpnts ***)&metric[0]));
2212 PetscCall(DMDAVecGetArrayRead(user->fda, user->lEta, (const Cmpnts ***)&metric[1]));
2213 PetscCall(DMDAVecGetArrayRead(user->fda, user->lZet, (const Cmpnts ***)&metric[2]));
2214 }
2215
2216#define EDGE_FILL(tk, tj, ti, ak, aj, ai, bk, bj, bi) \
2217 FillEdgeCell(f, dof, free_slip, metric, tk, tj, ti, ak, aj, ai, bk, bj, bi)
2218
2219 // --- Update Edges and Corners ---
2220 // The order of these blocks ensures that corners (where 3 faces meet) are
2221 // computed using data from edges (where 2 faces meet), which are computed first.
2222 // Edges connected to the -Z face (k=zs)
2223 if (zs == 0) {
2224 if (xs == 0) for (PetscInt j = ys; j < ye; j++) { EDGE_FILL(zs, j, xs, zs+1, j, xs, zs, j, xs+1); }
2225 if (xe == mx) for (PetscInt j = ys; j < ye; j++) { EDGE_FILL(zs, j, mx-1, zs+1, j, mx-1, zs, j, mx-2); }
2226 if (ys == 0) for (PetscInt i = xs; i < xe; i++) { EDGE_FILL(zs, ys, i, zs+1, ys, i, zs, ys+1, i); }
2227 if (ye == my) for (PetscInt i = xs; i < xe; i++) { EDGE_FILL(zs, my-1, i, zs+1, my-1, i, zs, my-2, i); }
2228 }
2229 // Edges connected to the +Z face (k=ze-1)
2230 if (ze == mz) {
2231 if (xs == 0) for (PetscInt j = ys; j < ye; j++) { EDGE_FILL(mz-1, j, xs, mz-2, j, xs, mz-1, j, xs+1); }
2232 if (xe == mx) for (PetscInt j = ys; j < ye; j++) { EDGE_FILL(mz-1, j, mx-1, mz-2, j, mx-1, mz-1, j, mx-2); }
2233 if (ys == 0) for (PetscInt i = xs; i < xe; i++) { EDGE_FILL(mz-1, ys, i, mz-2, ys, i, mz-1, ys+1, i); }
2234 if (ye == my) for (PetscInt i = xs; i < xe; i++) { EDGE_FILL(mz-1, my-1, i, mz-2, my-1, i, mz-1, my-2, i); }
2235 }
2236 // Remaining edges on the XY plane (that are not on Z faces)
2237 if (ys == 0) {
2238 if (xs == 0) for (PetscInt k = zs; k < ze; k++) { EDGE_FILL(k, ys, xs, k, ys+1, xs, k, ys, xs+1); }
2239 if (xe == mx) for (PetscInt k = zs; k < ze; k++) { EDGE_FILL(k, ys, mx-1, k, ys+1, mx-1, k, ys, mx-2); }
2240 }
2241 if (ye == my) {
2242 if (xs == 0) for (PetscInt k = zs; k < ze; k++) { EDGE_FILL(k, my-1, xs, k, my-2, xs, k, my-1, xs+1); }
2243 if (xe == mx) for (PetscInt k = zs; k < ze; k++) { EDGE_FILL(k, my-1, mx-1, k, my-2, mx-1, k, my-1, mx-2); }
2244 }
2245#undef EDGE_FILL
2246
2247 if (any_free_slip && dof == 3) {
2248 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lZet, (const Cmpnts ***)&metric[2]));
2249 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lEta, (const Cmpnts ***)&metric[1]));
2250 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lCsi, (const Cmpnts ***)&metric[0]));
2251 }
2252 PetscCall(DMDAVecRestoreArrayDOF(view.dm, view.global_vec, &f));
2254 PetscFunctionReturn(0);
2255}
2256
2257/**
2258 * @brief The signed friction velocity the configured wall law gives for one wall-face element.
2259 *
2260 * Each law is inverted at the reference cell's wall distance for the wall-parallel speed of
2261 * that cell relative to the wall, which the caller has already projected. Cabot's departure
2262 * from an equilibrium profile is driven by the wall-parallel pressure gradient, taken from the
2263 * resolved pressure at the first cell along the same direction; the pressure is the previous
2264 * projection's, the same lag every other explicit use of it carries. Its momentum balance
2265 * gives a signed stress, so the sign is returned on the friction velocity: negative when an
2266 * adverse gradient reverses the stress. The other two laws are always positive.
2267 */
2268static PetscErrorCode WallModelFrictionVelocity(UserCtx *user, const PetscReal ***pressure,
2269 PetscInt i, PetscInt j, PetscInt k,
2270 PetscReal roughness_height, PetscReal distance_reference,
2271 Cmpnts tangent, PetscReal tangent_speed,
2272 PetscReal *friction_velocity)
2273{
2274 const PetscReal kinematic_viscosity = 1.0 / user->simCtx->ren;
2275
2276 PetscFunctionBeginUser;
2278 switch ((WallFunctionModel)user->simCtx->wallfunction) {
2280 *friction_velocity = find_utau_Werner(kinematic_viscosity, tangent_speed, distance_reference, 0.0);
2281 break;
2282 case WALL_FUNCTION_CABOT: {
2283 Cmpnts gradient = {0.0, 0.0, 0.0};
2284 PetscReal gradient_along = 0.0, u_tau = 0.0, stress = 0.0, stress_normal = 0.0;
2285
2286 if (pressure) PetscCall(ComputeScalarFieldDerivatives(user, i, j, k, (PetscReal ***)pressure, &gradient));
2287 if (tangent_speed > 1.0e-10) {
2288 gradient_along = (gradient.x * tangent.x + gradient.y * tangent.y + gradient.z * tangent.z) / tangent_speed;
2289 }
2290 find_utau_Cabot(kinematic_viscosity, tangent_speed, distance_reference, 0.01, gradient_along, 0.0,
2291 &u_tau, &stress, &stress_normal);
2292 *friction_velocity = (stress < 0.0) ? -u_tau : u_tau;
2293 break;
2294 }
2296 default:
2297 *friction_velocity = find_utau_hydset(kinematic_viscosity, tangent_speed, distance_reference, 0.001,
2298 roughness_height);
2299 break;
2300 }
2301 /* A non-finite value stops the run here rather than entering the stress. */
2302 PetscCheck(PetscIsInfOrNanReal(*friction_velocity) == PETSC_FALSE, PETSC_COMM_SELF, PETSC_ERR_FP,
2303 "Wall model (%s) returned a non-finite friction velocity at cell (%" PetscInt_FMT ", %" PetscInt_FMT
2304 ", %" PetscInt_FMT ").",
2307 PetscFunctionReturn(PETSC_SUCCESS);
2308}
2309
2310/**
2311 * @brief Implementation of \ref ApplyWallFunction().
2312 * @see ApplyWallFunction()
2313 */
2314PetscErrorCode ApplyWallFunction(UserCtx *user)
2315{
2316 SimCtx *simCtx = user->simCtx;
2317 const DMDALocalInfo *info = &user->info;
2318 const PetscInt start[3] = {info->xs, info->ys, info->zs};
2319 const PetscInt end[3] = {info->xs + info->xm, info->ys + info->ym, info->zs + info->zm};
2320 const PetscInt size[3] = {info->mx, info->my, info->mz};
2321 const PetscReal molecular = 1.0 / simCtx->ren;
2322 const PetscReal roughness_height = simCtx->wall_roughness_height;
2323 const Cmpnts ***ucat, ***ubcs, ***metric[3];
2324 const PetscReal ***nvert, ***aj, ***pressure;
2325 Cmpnts ***ucont, ***stress;
2326 PetscReal ***friction_velocity;
2327 PetscInt wall_faces_at[3][2];
2328
2329 PetscFunctionBeginUser;
2331 if (!simCtx->wallfunction) { PROFILE_HELPER_END; PetscFunctionReturn(0); }
2332
2333 /* One pass, one sample set: the state describes this pass and nothing earlier. Faces the
2334 model does not reach must not keep a stale stress, and the friction velocity is
2335 accumulated per cell below, so both start from zero. */
2336 PetscCall(PetscMemzero(&user->wall_diagnostics, sizeof(user->wall_diagnostics)));
2337 PetscCall(VecSet(user->Wall_Stress, 0.0));
2338 PetscCall(VecSet(user->Friction_Velocity, 0.0));
2339
2340 /* The resolved velocity this pass's Contra2Cart wrote, read from the global view: the
2341 model reads it and never writes it. */
2342 PetscCall(DMDAVecGetArrayRead(user->fda, user->Ucat, (void *)&ucat));
2343 PetscCall(DMDAVecGetArrayRead(user->fda, user->Bcs.Ubcs, (void *)&ubcs));
2344 PetscCall(DMDAVecGetArray(user->fda, user->Ucont, &ucont));
2345 PetscCall(DMDAVecGetArrayRead(user->fda, user->lCsi, (void *)&metric[0]));
2346 PetscCall(DMDAVecGetArrayRead(user->fda, user->lEta, (void *)&metric[1]));
2347 PetscCall(DMDAVecGetArrayRead(user->fda, user->lZet, (void *)&metric[2]));
2348 PetscCall(DMDAVecGetArrayRead(user->da, user->lNvert, (void *)&nvert));
2349 PetscCall(DMDAVecGetArrayRead(user->da, user->lAj, (void *)&aj));
2350 /* Cabot reads the previous projection's pressure gradient; the other laws ignore it. */
2351 PetscCall(DMDAVecGetArrayRead(user->da, user->lP, (void *)&pressure));
2352 PetscCall(DMDAVecGetArray(user->fda, user->Wall_Stress, &stress));
2353 PetscCall(DMDAVecGetArray(user->da, user->Friction_Velocity, &friction_velocity));
2354
2355 for (PetscInt axis = 0; axis < 3; axis++) {
2356 wall_faces_at[axis][0] = BoundaryFaceHasWallShear(&user->boundary_faces[2 * axis]) ? 1 : 0;
2357 wall_faces_at[axis][1] = BoundaryFaceHasWallShear(&user->boundary_faces[2 * axis + 1]) ? 1 : 0;
2358 }
2359
2360 /* Every wall face element is one sample of the law. A cell beside two walls, along an
2361 edge of the domain, has two such elements, each with its own reference cell, normal
2362 and stress, so the two walls never write into one another's input. */
2363 for (PetscInt face = 0; face < 6; face++) {
2364 const PetscInt axis = face / 2;
2365 const PetscBool negative = (PetscBool)(face % 2 == 0);
2366 const PetscReal side = negative ? 1.0 : -1.0;
2367 BoundaryFaceElements elements;
2368
2369 if (!wall_faces_at[axis][negative ? 0 : 1]) continue;
2370 PetscCall(GetBoundaryFaceElements(user, (BCFace)face, &elements));
2371 if (elements.n[0] * elements.n[1] == 0) continue;
2372
2373 const PetscInt face_at = elements.layer;
2374 const PetscInt cell = negative ? face_at + 1 : face_at;
2375 const PetscInt reference = negative ? face_at + 2 : face_at - 1;
2376 const PetscInt dummy = negative ? face_at : face_at + 1;
2377 /* The reference cell is read from the owned block. A rank holding fewer than three
2378 nodes normal to a wall would read outside it, so that layout is refused. */
2379 PetscCheck(reference >= start[axis] && reference < end[axis], PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE,
2380 "Wall model on face %s: this rank owns indices %" PetscInt_FMT "-%" PetscInt_FMT
2381 " normal to the wall, which does not reach the reference cell %" PetscInt_FMT
2382 ". Use a layout with at least three nodes per rank normal to every wall.",
2383 BCFaceToString((BCFace)face), start[axis], end[axis] - 1, reference);
2384
2385 for (PetscInt q = 0; q < elements.n[1]; q++)
2386 for (PetscInt p = 0; p < elements.n[0]; p++) {
2387 PetscInt c[3];
2388
2389 c[axis] = cell; c[elements.a] = elements.lo[0] + p; c[elements.b] = elements.lo[1] + q;
2390 const PetscInt i = c[0], j = c[1], k = c[2];
2391 PetscInt c_ref[3] = {i, j, k}, c_dummy[3] = {i, j, k}, c_face[3] = {i, j, k};
2392 PetscReal signed_u_tau = 0.0, u_tau;
2393
2394 if (nvert[k][j][i] > 0.1) continue;
2395 c_ref[axis] = reference;
2396 c_dummy[axis] = dummy;
2397 c_face[axis] = face_at;
2398
2399 const Cmpnts area_vector = metric[axis][c_face[2]][c_face[1]][c_face[0]];
2400 const PetscReal area = PetscSqrtReal(area_vector.x * area_vector.x + area_vector.y * area_vector.y +
2401 area_vector.z * area_vector.z);
2402 /* The first and reference cell-centre distances from the wall, from each cell's
2403 volume over the wall area. */
2404 const PetscReal distance_boundary = 0.5 / aj[k][j][i] / area;
2405 const PetscReal distance_reference = 2.0 * distance_boundary +
2406 0.5 / aj[c_ref[2]][c_ref[1]][c_ref[0]] / area;
2407 const Cmpnts velocity_wall = ubcs[c_dummy[2]][c_dummy[1]][c_dummy[0]];
2408 const Cmpnts velocity_reference = ucat[c_ref[2]][c_ref[1]][c_ref[0]];
2409 const Cmpnts relative_reference = {velocity_reference.x - velocity_wall.x,
2410 velocity_reference.y - velocity_wall.y,
2411 velocity_reference.z - velocity_wall.z};
2412 const Cmpnts tangent = RemoveFaceNormalComponent(relative_reference, area_vector);
2413 const PetscReal tangent_speed = PetscSqrtReal(tangent.x * tangent.x + tangent.y * tangent.y +
2414 tangent.z * tangent.z);
2415
2416 PetscCall(WallModelFrictionVelocity(user, pressure, i, j, k, roughness_height, distance_reference,
2417 tangent, tangent_speed, &signed_u_tau));
2418 u_tau = PetscAbsReal(signed_u_tau);
2419
2420 /* The stress opposes the reference cell's motion relative to the wall, along its
2421 wall-parallel direction. Stored in the face's dummy cell, which no other wall
2422 face uses, already oriented as the viscous flux through that face, so the
2423 flux is the stored value times the face area (ComputeViscous). */
2424 if (tangent_speed > 1.0e-12) {
2425 const PetscReal scale = side * signed_u_tau * u_tau / tangent_speed;
2426 stress[c_dummy[2]][c_dummy[1]][c_dummy[0]].x = scale * tangent.x;
2427 stress[c_dummy[2]][c_dummy[1]][c_dummy[0]].y = scale * tangent.y;
2428 stress[c_dummy[2]][c_dummy[1]][c_dummy[0]].z = scale * tangent.z;
2429 }
2430 /* The wall is impermeable whatever the law. */
2431 if (axis == 0) ucont[c_face[2]][c_face[1]][c_face[0]].x = 0.0;
2432 else if (axis == 1) ucont[c_face[2]][c_face[1]][c_face[0]].y = 0.0;
2433 else ucont[c_face[2]][c_face[1]][c_face[0]].z = 0.0;
2434
2435 /* The cell's friction velocity is the RMS over its wall faces; the sum of
2436 squares is accumulated here and reduced once every face has been visited. */
2437 friction_velocity[k][j][i] += u_tau * u_tau;
2438
2439 {
2440 WallModelDiagnosticsState *diagnostics = &user->wall_diagnostics;
2441 const PetscReal y_plus = u_tau * distance_boundary / molecular;
2442 const Cmpnts first = ucat[k][j][i];
2443 const Cmpnts relative_first = {first.x - velocity_wall.x, first.y - velocity_wall.y,
2444 first.z - velocity_wall.z};
2445 const Cmpnts first_tangent = RemoveFaceNormalComponent(relative_first, area_vector);
2446 const PetscReal first_speed = PetscSqrtReal(first_tangent.x * first_tangent.x +
2447 first_tangent.y * first_tangent.y +
2448 first_tangent.z * first_tangent.z);
2449 /* The eddy viscosity a gradient closure would need on this face to carry
2450 the stress across the resolved first cell: nu_eq = u_tau^2 y / |U_1|,
2451 less the molecular part. A diagnostic only; the stress itself is applied. */
2452 if (first_speed > 1.0e-10) {
2453 diagnostics->wall_viscosity_sum += PetscMax(u_tau * u_tau * distance_boundary / first_speed - molecular, 0.0);
2454 }
2455 if (diagnostics->cells == 0) {
2456 diagnostics->friction_velocity_min = u_tau;
2457 } else {
2458 diagnostics->friction_velocity_min = PetscMin(diagnostics->friction_velocity_min, u_tau);
2459 }
2460 if (diagnostics->cells == 0 || u_tau > diagnostics->friction_velocity_max) {
2461 diagnostics->friction_velocity_max = u_tau;
2462 diagnostics->friction_velocity_max_at[0] = face;
2463 diagnostics->friction_velocity_max_at[1] = i;
2464 diagnostics->friction_velocity_max_at[2] = j;
2465 diagnostics->friction_velocity_max_at[3] = k;
2466 }
2467 if (diagnostics->cells == 0 || y_plus > diagnostics->y_plus_max) {
2468 diagnostics->y_plus_max = y_plus;
2469 diagnostics->y_plus_max_at[0] = face;
2470 diagnostics->y_plus_max_at[1] = i;
2471 diagnostics->y_plus_max_at[2] = j;
2472 diagnostics->y_plus_max_at[3] = k;
2473 }
2474 diagnostics->friction_velocity_sum += u_tau;
2475 diagnostics->friction_velocity_sq += u_tau * u_tau;
2476 diagnostics->wall_distance_sum += distance_boundary;
2477 diagnostics->y_plus_sum += y_plus;
2478 diagnostics->cells += 1;
2479 }
2480 }
2481 }
2482
2483 /* Friction velocity per first cell: the RMS over the wall faces it touches. Only the
2484 wall-face elements are visited, and an edge cell is finalized once, by the first of its
2485 wall faces in face order, so the cost stays with the wall layers. */
2486 for (PetscInt face = 0; face < 6; face++) {
2487 const PetscInt axis = face / 2;
2488 BoundaryFaceElements elements;
2489
2490 if (!wall_faces_at[axis][face % 2]) continue;
2491 PetscCall(GetBoundaryFaceElements(user, (BCFace)face, &elements));
2492 for (PetscInt q = 0; q < elements.n[1]; q++)
2493 for (PetscInt p = 0; p < elements.n[0]; p++) {
2494 PetscInt c[3];
2495 PetscInt faces = 0, first_face = -1;
2496
2497 c[axis] = (face % 2 == 0) ? elements.layer + 1 : elements.layer;
2498 c[elements.a] = elements.lo[0] + p;
2499 c[elements.b] = elements.lo[1] + q;
2500 const PetscInt i = c[0], j = c[1], k = c[2];
2501
2502 if (friction_velocity[k][j][i] <= 0.0) continue;
2503 for (PetscInt other = 0; other < 6; other++) {
2504 const PetscInt other_axis = other / 2;
2505 const PetscInt beside = (other % 2 == 0) ? 1 : size[other_axis] - 2;
2506 if (wall_faces_at[other_axis][other % 2] && c[other_axis] == beside) {
2507 faces++;
2508 if (first_face < 0) first_face = other;
2509 }
2510 }
2511 if (first_face != face) continue;
2512 friction_velocity[k][j][i] = PetscSqrtReal(friction_velocity[k][j][i] / (PetscReal)faces);
2513 }
2514 }
2515
2516 PetscCall(DMDAVecRestoreArray(user->da, user->Friction_Velocity, &friction_velocity));
2517 PetscCall(DMDAVecRestoreArray(user->fda, user->Wall_Stress, &stress));
2518 PetscCall(DMDAVecRestoreArrayRead(user->da, user->lP, (void *)&pressure));
2519 PetscCall(DMDAVecRestoreArrayRead(user->da, user->lAj, (void *)&aj));
2520 PetscCall(DMDAVecRestoreArrayRead(user->da, user->lNvert, (void *)&nvert));
2521 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lZet, (void *)&metric[2]));
2522 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lEta, (void *)&metric[1]));
2523 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lCsi, (void *)&metric[0]));
2524 PetscCall(DMDAVecRestoreArray(user->fda, user->Ucont, &ucont));
2525 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->Bcs.Ubcs, (void *)&ubcs));
2526 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->Ucat, (void *)&ucat));
2527
2528 /* Refresh the ghosted images here so that every caller sees consistent fields rather
2529 than each remembering to do it. */
2530 PetscCall(UpdateLocalGhosts(user, FIELD_ID_U_TAU));
2531 PetscCall(UpdateLocalGhosts(user, FIELD_ID_WALL_STRESS));
2533 PetscFunctionReturn(PETSC_SUCCESS);
2534}
2535
2536/**
2537 * @brief Implementation of \ref LogWallModelDiagnostics().
2538 * @details Full API contract is documented with the header declaration in
2539 * `include/Boundaries.h`.
2540 */
2542{
2543 SimCtx *simCtx = user->simCtx;
2544 const WallModelDiagnosticsState *state = &user->wall_diagnostics;
2545 MPI_Comm comm;
2546
2547 /* Index 0..3: cell count, u_tau sum, u_tau^2 sum, y+ sum. Index 4..5: wall-distance
2548 and wall-viscosity sums. One collective rather than six. */
2549 PetscReal local_sum[6], global_sum[6];
2550 PetscReal global_max[2];
2551 PetscReal local_min, global_min;
2552 /* Index 0: u_tau, 1: y+. MAXLOC carries the owning rank with each maximum, and that
2553 rank alone contributes the face and cell, so the sum below is its location. The
2554 lowest rank wins a tie, so the record is the same at any layout that ties. */
2555 struct { double value; int rank; } local_max[2], owner_max[2];
2556 PetscInt local_at[8], global_at[8];
2557
2558 PetscFunctionBeginUser;
2560
2561 if (!simCtx->wallfunction) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
2562
2563 PetscCall(PetscObjectGetComm((PetscObject)user->da, &comm));
2564
2565 local_sum[0] = (PetscReal)state->cells;
2566 local_sum[1] = state->friction_velocity_sum;
2567 local_sum[2] = state->friction_velocity_sq;
2568 local_sum[3] = state->y_plus_sum;
2569 local_sum[4] = state->wall_distance_sum;
2570 local_sum[5] = state->wall_viscosity_sum;
2571 /* Both are non-negative, so a rank with no wall cell offers -1 and can never own them. */
2572 local_max[0].value = (state->cells > 0) ? (double)state->friction_velocity_max : -1.0;
2573 local_max[1].value = (state->cells > 0) ? (double)state->y_plus_max : -1.0;
2574 local_max[0].rank = local_max[1].rank = (int)simCtx->rank;
2575 /* A rank that owns no wall face must not win the minimum with a zero it never
2576 measured, so it contributes the identity instead. */
2577 local_min = (state->cells > 0) ? state->friction_velocity_min : PETSC_MAX_REAL;
2578
2579 PetscCallMPI(MPI_Allreduce(local_sum, global_sum, 6, MPIU_REAL, MPI_SUM, comm));
2580 PetscCallMPI(MPI_Allreduce(local_max, owner_max, 2, MPI_DOUBLE_INT, MPI_MAXLOC, comm));
2581 PetscCallMPI(MPI_Allreduce(&local_min, &global_min, 1, MPIU_REAL, MPI_MIN, comm));
2582 global_max[0] = (PetscReal)owner_max[0].value;
2583 global_max[1] = (PetscReal)owner_max[1].value;
2584 for (PetscInt n = 0; n < 4; n++) {
2585 local_at[n] = (owner_max[0].rank == (int)simCtx->rank) ? state->friction_velocity_max_at[n] : 0;
2586 local_at[4 + n] = (owner_max[1].rank == (int)simCtx->rank) ? state->y_plus_max_at[n] : 0;
2587 }
2588 PetscCallMPI(MPI_Allreduce(local_at, global_at, 8, MPIU_INT, MPI_SUM, comm));
2589
2590 if (simCtx->rank == 0) {
2591 const PetscReal cells = global_sum[0];
2592 FILE *file = NULL;
2593 PetscReal mean, mean_square, variance;
2594
2595 /* No wall face anywhere is a configuration fact, not a data point: a run with
2596 wall functions enabled and no WALL boundary would otherwise emit a row of
2597 zeros that reads like a converged answer. */
2598 if (cells <= 0.0) {
2600 "Wall model is enabled but no WALL face was reached this step; "
2601 "no diagnostics written.\n");
2603 PetscFunctionReturn(0);
2604 }
2605
2606 mean = global_sum[1] / cells;
2607 mean_square = global_sum[2] / cells;
2608 variance = PetscMax(mean_square - mean * mean, 0.0);
2609
2610 PetscCall(PicurvOpenDiagnosticsCsv(simCtx, simCtx->analysis_dir, "wall_model.csv",
2611 "step,time,wall_cells,u_tau_mean,u_tau_rms,"
2612 "u_tau_min,u_tau_max,y_plus_mean,y_plus_max,"
2613 "wall_distance_mean,nu_wall_over_nu_mean,physical_time,"
2614 "u_tau_max_face,u_tau_max_i,u_tau_max_j,u_tau_max_k,"
2615 "y_plus_max_face,y_plus_max_i,y_plus_max_j,y_plus_max_k", &file));
2616 PetscReal physical_time = 0.0;
2617 PetscCall(PicurvPhysicalTime(simCtx, simCtx->ti, &physical_time));
2618 fprintf(file,
2619 "%d,%.6e,%d,%.6e,%.6e,%.6e,%.6e,%.6e,%.6e,%.6e,%.6e,%.6e,%s,%d,%d,%d,%s,%d,%d,%d\n",
2620 (int)simCtx->step, (double)simCtx->ti, (int)cells,
2621 (double)mean, (double)PetscSqrtReal(variance),
2622 (double)global_min, (double)global_max[0],
2623 (double)(global_sum[3] / cells), (double)global_max[1],
2624 (double)(global_sum[4] / cells),
2625 (double)(global_sum[5] / cells * simCtx->ren), (double)physical_time,
2626 BCFaceToString((BCFace)global_at[0]), (int)global_at[1], (int)global_at[2], (int)global_at[3],
2627 BCFaceToString((BCFace)global_at[4]), (int)global_at[5], (int)global_at[6], (int)global_at[7]);
2628 PetscCheck(fclose(file) == 0, PETSC_COMM_SELF, PETSC_ERR_FILE_WRITE,
2629 "Unable to close the wall-model diagnostics file.");
2630
2632 " Wall model (%s): u_tau=%.4e (max %.4e on %s at %d,%d,%d), y+ (mean)=%.2f, "
2633 "y+ (max)=%.2f over %d cell(s)\n",
2635 (double)mean, (double)global_max[0], BCFaceToString((BCFace)global_at[0]),
2636 (int)global_at[1], (int)global_at[2], (int)global_at[3],
2637 (double)(global_sum[3] / cells), (double)global_max[1], (int)cells);
2638 }
2639
2640 /* Whether the first cell sits where the selected law is valid is a property of the
2641 mesh, not of the configuration, so it cannot be settled before the grid exists.
2642 It is checked here instead, and a run that stays outside the range is stopped
2643 rather than left to spend its walltime producing a wall stress the law cannot
2644 support. */
2645 {
2646 /* Consecutive samples tolerated outside the range. A startup transient or a
2647 brief excursion is not worth ending a run over; a mesh that is simply wrong
2648 never comes back. */
2649 const PetscInt PICURV_WALL_YPLUS_GRACE_SAMPLES = 10;
2650 const PetscReal y_plus_mean = (global_sum[0] > 0.0) ? global_sum[3] / global_sum[0] : 0.0;
2651 PetscReal lower = 0.0, upper = 300.0;
2652 const char *range_reason = NULL;
2653
2654 switch ((WallFunctionModel)simCtx->wallfunction) {
2656 /* Below 30 the first cell is under the logarithmic region; above 300 it is
2657 in the wake region, where the inverse still returns a friction velocity
2658 from the logarithmic branch but the flow no longer follows it. */
2659 lower = 30.0;
2660 upper = 300.0;
2661 range_reason = "the logarithmic region the law describes";
2662 break;
2664 /* The two-layer form has a valid branch below its edge, 8.3^(7/6) = 11.81, so
2665 only the upper end is a limit. */
2666 lower = 0.0;
2667 upper = 300.0;
2668 range_reason = "the region the power law describes";
2669 break;
2670 default:
2671 /* Cabot integrates across the wall layer, so it has no lower bound worth
2672 asserting; a first cell far outside the layer leaves its ODE nothing to
2673 integrate over. */
2674 lower = 0.0;
2675 upper = 1000.0;
2676 range_reason = "the wall layer the model integrates over";
2677 break;
2678 }
2679
2680 if (global_sum[0] > 0.0 && (y_plus_mean < lower || y_plus_mean > upper)) {
2681 user->wall_yplus_excursions += 1;
2683 "Wall model (%s): first-cell y+ is %.2f, outside %s (%.0f to %.0f). "
2684 "The stress it reports is not one the law supports here. Sample %d "
2685 "of %d before this run is stopped.\n",
2687 (double)y_plus_mean, range_reason, (double)lower, (double)upper,
2688 (int)user->wall_yplus_excursions,
2689 (int)PICURV_WALL_YPLUS_GRACE_SAMPLES);
2690
2691 PetscCheck(user->wall_yplus_excursions < PICURV_WALL_YPLUS_GRACE_SAMPLES,
2692 PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE,
2693 "Wall model (%s): first-cell y+ has been outside %s (%.0f to %.0f) "
2694 "for %d consecutive samples, most recently %.2f. Refine or coarsen "
2695 "the wall-normal spacing so the first cell lands in range, or "
2696 "resolve the wall and disable the wall function. Stopping now "
2697 "rather than spending the run producing a stress the law cannot "
2698 "support.",
2700 range_reason, (double)lower, (double)upper,
2701 (int)user->wall_yplus_excursions, (double)y_plus_mean);
2702 } else {
2703 /* Consecutive, so a sample back in range clears the count. */
2704 user->wall_yplus_excursions = 0;
2705 }
2706
2707 /* The stop above reads the mean, which a local excursion - a corner, a separation,
2708 an outlet - cannot move. The maximum is reported once, with where it is, so such a
2709 site is visible without stopping a run whose wall is otherwise in range. */
2710 if (global_sum[0] > 0.0 && global_max[1] > upper && !user->wall_yplus_max_reported) {
2711 user->wall_yplus_max_reported = PETSC_TRUE;
2713 "Wall model (%s): first-cell y+ reaches %.2f on face %s at cell (%d, %d, %d), above %s "
2714 "(up to %.0f), although the wall-face mean %.2f is in range. Reported once; "
2715 "wall_model.csv tracks the maximum and its location every step.\n",
2717 (double)global_max[1], BCFaceToString((BCFace)global_at[4]), (int)global_at[5],
2718 (int)global_at[6], (int)global_at[7], range_reason, (double)upper, (double)y_plus_mean);
2719 }
2720 }
2721
2723 PetscFunctionReturn(0);
2724}
2725
2726/**
2727 * @brief Implementation of \ref LogBoundaryPressureDiagnostics().
2728 * @see LogBoundaryPressureDiagnostics()
2729 */
2731{
2732 SimCtx *simCtx = user->simCtx;
2733 /* Per face: the area-weighted pressure sum and the open area. One collective for all six. */
2734 PetscReal local[12] = {0.0}, global[12];
2735 PetscBool selected[6] = {PETSC_FALSE};
2736 PetscInt n_selected = 0;
2737
2738 PetscFunctionBeginUser;
2740 for (PetscInt face = 0; face < 6; face++) {
2741 const BCType type = user->boundary_faces[face].mathematical_type;
2742 selected[face] = (PetscBool)(type == INLET || type == OUTLET);
2743 n_selected += selected[face] ? 1 : 0;
2744 }
2745 if (n_selected == 0) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
2746
2747 {
2748 const PetscReal ***pressure, ***nvert;
2749 const Cmpnts ***metric[3];
2750
2751 PetscCall(DMDAVecGetArrayRead(user->da, user->P, (void *)&pressure));
2752 PetscCall(DMDAVecGetArrayRead(user->da, user->lNvert, (void *)&nvert));
2753 PetscCall(DMDAVecGetArrayRead(user->fda, user->lCsi, (void *)&metric[0]));
2754 PetscCall(DMDAVecGetArrayRead(user->fda, user->lEta, (void *)&metric[1]));
2755 PetscCall(DMDAVecGetArrayRead(user->fda, user->lZet, (void *)&metric[2]));
2756 for (PetscInt face = 0; face < 6; face++) {
2757 BoundaryFaceElements elements;
2758
2759 if (!selected[face]) continue;
2760 /* The first interior cell beside each owned face element, and the face's own metric. */
2761 PetscCall(GetBoundaryFaceElements(user, (BCFace)face, &elements));
2762 const PetscInt axis = elements.normal;
2763 const PetscInt cell = (face % 2 == 0) ? elements.layer + 1 : elements.layer;
2764 for (PetscInt q = 0; q < elements.n[1]; q++)
2765 for (PetscInt p = 0; p < elements.n[0]; p++) {
2766 PetscInt c[3], f[3];
2767 c[axis] = cell; c[elements.a] = elements.lo[0] + p; c[elements.b] = elements.lo[1] + q;
2768 const PetscInt i = c[0], j = c[1], k = c[2];
2769 if (nvert[k][j][i] > 0.1) continue;
2770 f[0] = i; f[1] = j; f[2] = k;
2771 f[axis] = elements.layer;
2772 const Cmpnts m = metric[axis][f[2]][f[1]][f[0]];
2773 const PetscReal area = PetscSqrtReal(m.x * m.x + m.y * m.y + m.z * m.z);
2774 local[2 * face] += pressure[k][j][i] * area;
2775 local[2 * face + 1] += area;
2776 }
2777 }
2778 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lZet, (void *)&metric[2]));
2779 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lEta, (void *)&metric[1]));
2780 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lCsi, (void *)&metric[0]));
2781 PetscCall(DMDAVecRestoreArrayRead(user->da, user->lNvert, (void *)&nvert));
2782 PetscCall(DMDAVecRestoreArrayRead(user->da, user->P, (void *)&pressure));
2783 }
2784 PetscCallMPI(MPI_Allreduce(local, global, 12, MPIU_REAL, MPI_SUM, PETSC_COMM_WORLD));
2785
2786 /* One record per run, as the inlet-flow record keeps: the first block's faces. */
2787 if (simCtx->rank == 0 && user->_this == 0) {
2788 const PetscReal L_ref = simCtx->scaling.L_ref, P_ref = simCtx->scaling.P_ref;
2789 PetscReal physical_time = 0.0;
2790 FILE *file = NULL;
2791
2792 PetscCall(PicurvPhysicalTime(simCtx, simCtx->ti, &physical_time));
2793 PetscCall(PicurvOpenDiagnosticsCsv(simCtx, simCtx->analysis_dir, "boundary_pressure.csv",
2794 "step,physical_time,face,type,area,mean_pressure", &file));
2795 for (PetscInt face = 0; face < 6; face++) {
2796 if (!selected[face] || global[2 * face + 1] <= 0.0) continue;
2797 fprintf(file, "%d,%.10e,%s,%s,%.10e,%.10e\n", (int)simCtx->step, (double)physical_time,
2799 (double)(global[2 * face + 1] * L_ref * L_ref),
2800 (double)(global[2 * face] / global[2 * face + 1] * P_ref));
2801 }
2802 PetscCheck(fclose(file) == 0, PETSC_COMM_SELF, PETSC_ERR_FILE_WRITE,
2803 "Unable to close the boundary-pressure diagnostics file.");
2804 }
2806 PetscFunctionReturn(0);
2807}
2808
2809/**
2810 * @brief Implementation of \ref FinalizePostProjectionCellFields().
2811 * @details Full API contract is documented with the header declaration in
2812 * `include/Boundaries.h`.
2813 */
2815{
2816 PetscErrorCode ierr;
2817
2818 PetscFunctionBeginUser;
2820
2821 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Finalizing post-projection cell-centered fields.\n");
2822
2823 // Ensure flow-dependent Ubcs handlers see the newly reconstructed Ucat.
2824 ierr = UpdateLocalGhosts(user, FIELD_ID_UCAT); CHKERRQ(ierr);
2825 ierr = BoundarySystem_RefreshUbcs(user); CHKERRQ(ierr);
2826 ierr = FinalizeCellFieldsFromBoundaryValues(user); CHKERRQ(ierr);
2827
2828 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Post-projection cell-centered fields finalized.\n");
2830 PetscFunctionReturn(0);
2831}
2832
2833/**
2834 * @brief Implementation of \ref FinalizeCellFieldsFromBoundaryValues().
2835 * @see FinalizeCellFieldsFromBoundaryValues()
2836 */
2838{
2839 PetscErrorCode ierr;
2840 const FieldId cell_fields[] = {FIELD_ID_UCAT, FIELD_ID_P};
2841
2842 PetscFunctionBeginUser;
2844
2845 // Establish flat non-periodic faces and periodic endpoints before corners.
2846 ierr = UpdateDummyCells(user, FIELD_ID_UCAT); CHKERRQ(ierr);
2847 ierr = UpdateDummyCells(user, FIELD_ID_P); CHKERRQ(ierr);
2848 ierr = SynchronizePeriodicCellFields(user, 2, cell_fields); CHKERRQ(ierr);
2849
2850 // Corner averaging can overwrite periodic endpoints, so restore them after.
2851 ierr = UpdateCornerNodes(user, FIELD_ID_UCAT); CHKERRQ(ierr);
2852 ierr = UpdateCornerNodes(user, FIELD_ID_P); CHKERRQ(ierr);
2853 ierr = SynchronizePeriodicCellFields(user, 2, cell_fields); CHKERRQ(ierr);
2854
2855 // With a periodic axis that synchronisation ends with the local vectors current: it
2856 // updates them after the corner writes, and each direction's plane refresh restores what
2857 // its transfer changed. With none it does nothing, so they are updated here.
2858 {
2859 PetscBool periodic[3];
2860 GetPeriodicAxes(user->simCtx, periodic);
2861 if (!periodic[0] && !periodic[1] && !periodic[2]) {
2862 ierr = UpdateLocalGhosts(user, FIELD_ID_UCAT); CHKERRQ(ierr);
2863 ierr = UpdateLocalGhosts(user, FIELD_ID_P); CHKERRQ(ierr);
2864 } else {
2865 ierr = VerifyLocalGhostsCurrent(user, FIELD_ID_UCAT, "after the periodic synchronisation"); CHKERRQ(ierr);
2866 ierr = VerifyLocalGhostsCurrent(user, FIELD_ID_P, "after the periodic synchronisation"); CHKERRQ(ierr);
2867 }
2868 }
2869
2871 PetscFunctionReturn(0);
2872}
2873
2874/**
2875 * @brief One boundary pass: the handlers, Contra2Cart, the wall function, the dummy, periodic
2876 * and corner updates, and the ghost synchronisations that leave the fields consistent.
2877 * @details Local to this translation unit; ApplyBoundaryConditions() decides how many to run.
2878 */
2879static PetscErrorCode ApplyBoundaryPass(UserCtx *user, PetscBool any_periodic)
2880{
2881 PetscErrorCode ierr;
2882 const FieldId staggered_fields[] = {FIELD_ID_UCONT};
2883
2884 PetscFunctionBeginUser;
2886 // (a) Execute the boundary system. This phase calculates fluxes across
2887 // the domain and then applies the physical logic for each non-periodic
2888 // handler, setting the `ubcs` (boundary value) array.
2889 ierr = BoundarySystem_ExecuteStep(user); CHKERRQ(ierr);
2890
2891 LOG_ALLOW(GLOBAL,LOG_VERBOSE,"Boundary Condition Setup Executed.\n");
2892
2893 // (b) Synchronize the updated ghost cells across all processors to ensure
2894 // all ucont values are current before updating the dummy cells.
2895 ierr = SynchronizePeriodicStaggeredFields(user, 1, staggered_fields); CHKERRQ(ierr);
2896
2897 // (c) Convert updated Contravariant velocities to Cartesian velocities.
2898 ierr = Contra2Cart(user); CHKERRQ(ierr);
2899
2900 // (d) Ucat's ghosts are not updated here: the wall function, the dummy and corner
2901 // updates read only global Ucat, and (g) or (i) updates it before any local read.
2902 ierr = PoisonStaleLocalGhosts(user, FIELD_ID_UCAT); CHKERRQ(ierr);
2903
2904 // (e) If a wall model is enabled, compute the wall shear stress on every wall face from
2905 // the velocity just reconstructed. It writes the stress and zeroes the wall-face
2906 // flux; the resolved velocity is not changed.
2907 if(user->simCtx->wallfunction){
2908 ierr = ApplyWallFunction(user); CHKERRQ(ierr);
2909
2910 LOG_ALLOW(GLOBAL,LOG_VERBOSE,"Wall Function Applied at Walls.\n");
2911 }
2912
2913 // (f) Update the first layer of ghost cells for non-periodic faces using
2914 // the newly computed `ubcs` values.
2915 ierr = UpdateDummyCells(user, FIELD_ID_UCAT); CHKERRQ(ierr);
2916 ierr = UpdateDummyCells(user, FIELD_ID_P); CHKERRQ(ierr);
2917
2918 LOG_ALLOW(GLOBAL,LOG_VERBOSE,"Dummy Cells/Ghost Cells Updated.\n");
2919
2920 // (g) Handle all periodic boundaries. This is a parallel direct copy
2921 // that sets the absolute constraints for the rest of the solve.
2922 // There is a Ghost update happening inside this function. Its last cell-field update
2923 // is left to (j): (h) and the staggered transfers do not read local Ucat, P or Nvert.
2924 ierr = ApplyPeriodicBCs(user, PETSC_FALSE); CHKERRQ(ierr);
2925
2926 // (h) Update the corner and edge ghost nodes. This routine calculates
2927 // values for corners/edges by averaging their neighbors, which have been
2928 // finalized in the steps above (both periodic and non-periodic).
2929 ierr = UpdateCornerNodes(user, FIELD_ID_UCAT); CHKERRQ(ierr);
2930 ierr = UpdateCornerNodes(user, FIELD_ID_P); CHKERRQ(ierr);
2931
2932 // (i) Synchronize the updated edge and corner cells across all processors to ensure
2933 // consistency before the next iteration or finalization.
2934 // Ucont was last written before (g)'s synchronization, or, with no periodic
2935 // face, before (b)'s update unless the wall function wrote it since. With a
2936 // periodic face, (j) updates P and Ucat first, so they are not updated here.
2937 if (!any_periodic) {
2938 ierr = UpdateLocalGhosts(user, FIELD_ID_P); CHKERRQ(ierr);
2939 ierr = UpdateLocalGhosts(user, FIELD_ID_UCAT); CHKERRQ(ierr);
2940 }
2941 ierr = SynchronizePeriodicStaggeredFieldsFrom(user, 1, staggered_fields,
2942 (PetscBool)(any_periodic || !user->simCtx->wallfunction)); CHKERRQ(ierr);
2943
2944 // (j) Ensure All the corners are synchronized with a well defined protocol in case of Periodic boundary conditions
2945 // To avoid race conditions.
2946 // Its leading update also completes (g)'s, which was left to it.
2947 const FieldId all_fields[] = {FIELD_ID_UCAT, FIELD_ID_P, FIELD_ID_NVERT};
2948 ierr = SynchronizePeriodicCellFieldsFrom(user, 3, all_fields, PETSC_FALSE, PETSC_TRUE); CHKERRQ(ierr);
2949
2951 PetscFunctionReturn(0);
2952}
2953
2954/**
2955 * @brief In verify mode, checks that the passes a single-pass call skipped would change nothing.
2956 * @details Runs the two passes the coupled path would add and requires Ucont, Ucat, P and the
2957 * boundary values to be bitwise what the first pass left. A mismatch means a handler
2958 * that reads in-pass state does not set `needs_repeat_pass`. Local to this
2959 * translation unit.
2960 */
2961static PetscErrorCode VerifySinglePassIsFinal(UserCtx *user, PetscBool any_periodic)
2962{
2963 Vec fields[4] = {user->Ucont, user->Ucat, user->P, user->Bcs.Ubcs}, saved[4];
2964 const char *names[4] = {"Ucont", "Ucat", "P", "Ubcs"};
2965
2966 PetscFunctionBeginUser;
2968 if (!user->simCtx->verifyGhostUpdates) { PROFILE_HELPER_END; PetscFunctionReturn(0); }
2969 for (int f = 0; f < 4; ++f) {
2970 PetscCall(VecDuplicate(fields[f], &saved[f]));
2971 PetscCall(VecCopy(fields[f], saved[f]));
2972 }
2973 for (int pass = 1; pass < 3; ++pass) PetscCall(ApplyBoundaryPass(user, any_periodic));
2974 for (int f = 0; f < 4; ++f) {
2975 PetscBool equal;
2976 PetscCall(VecEqual(fields[f], saved[f], &equal));
2977 PetscCheck(equal, PETSC_COMM_WORLD, PETSC_ERR_PLIB,
2978 "A further boundary pass changed %s after a single-pass call: some face's handler reads "
2979 "state the pass changes but does not set needs_repeat_pass.", names[f]);
2980 PetscCall(VecDestroy(&saved[f]));
2981 }
2983 PetscFunctionReturn(0);
2984}
2985
2986/**
2987 * @brief Implementation of \ref ApplyBoundaryConditions().
2988 * @details Full API contract (arguments, ownership, side effects) is documented with
2989 * the header declaration in `include/Boundaries.h`.
2990 * @see ApplyBoundaryConditions()
2991 */
2993{
2994 PetscErrorCode ierr;
2995 const FieldId staggered_fields[] = {FIELD_ID_UCONT};
2996 PetscBool periodic[3], any_periodic;
2997 PetscInt passes = user->simCtx->wallfunction ? 3 : 1;
2998 PetscFunctionBeginUser;
3000
3001 LOG_ALLOW(GLOBAL,LOG_TRACE,"Boundary Condition Application begins.\n");
3002
3003 GetPeriodicAxes(user->simCtx, periodic);
3004 any_periodic = (PetscBool)(periodic[0] || periodic[1] || periodic[2]);
3005 for (int face = 0; face < 6; face++) {
3006 if (user->boundary_faces[face].handler && user->boundary_faces[face].handler->needs_repeat_pass) passes = 3;
3007 }
3008 // STEP 1: The boundary passes. Three let information propagate between coupled boundaries,
3009 // like an inlet and a conserving outlet, or a free-slip wall and the interior velocity it
3010 // copies. Without such a face (needs_repeat_pass) and without a wall function, the first
3011 // pass leaves every field final, and verify mode checks that the skipped passes agree.
3012 for (PetscInt iter = 0; iter < passes; iter++) {
3013 ierr = ApplyBoundaryPass(user, any_periodic); CHKERRQ(ierr);
3014 }
3015 if (passes == 1) {
3016 ierr = VerifySinglePassIsFinal(user, any_periodic); CHKERRQ(ierr);
3017 }
3018
3019 // STEP 2: Final staggered periodic synchronization. The last pass already left Ucat, P
3020 // and Ucont's local vectors current with their global ones, so only the transfers run: a
3021 // ghost update depends only on its global vector, and one that repeats an update with no
3022 // write to that vector since changes nothing.
3023 ierr = SynchronizePeriodicStaggeredFieldsFrom(user, 1, staggered_fields, PETSC_TRUE); CHKERRQ(ierr);
3024 ierr = VerifyBoundaryPassFinite(user); CHKERRQ(ierr);
3025
3027 PetscFunctionReturn(0);
3028}
PetscErrorCode Create_WallFreeSlip(BoundaryCondition *bc)
Configures a BoundaryCondition object to behave as a free-slip wall.
PetscErrorCode Create_WallMoving(BoundaryCondition *bc)
Creates a wall moving along itself at a velocity source, the prescribed inlet's without its flux.
PetscErrorCode Create_PeriodicGeometric(BoundaryCondition *bc)
Configures a BoundaryCondition object for geometric periodic coupling.
PetscErrorCode Validate_DrivenFlowConfiguration(UserCtx *user)
(Private) Validates all consistency rules for a driven flow (channel/pipe) setup.
Definition BC_Handlers.c:15
PetscErrorCode Create_PeriodicDrivenInitial(BoundaryCondition *bc)
Configures a BoundaryCondition object for initial-flux periodic driving.
PetscErrorCode Create_PeriodicDrivenConstant(BoundaryCondition *bc)
Configures a BoundaryCondition object for periodic driven-flow forcing.
PetscErrorCode Create_InletPrescribedVelocity(BoundaryCondition *bc)
Configures a BoundaryCondition object as an inlet whose velocity is a configured source: expressions ...
PetscErrorCode Create_WallNoSlip(BoundaryCondition *bc)
Configures a BoundaryCondition object to behave as a no-slip, stationary wall.
PetscErrorCode Create_OutletConservation(BoundaryCondition *bc)
Configures a BoundaryCondition object for conservative outlet treatment.
static void FillEdgeCell(PetscScalar ****f, PetscInt dof, const PetscBool free_slip[6], Cmpnts ***const metric[3], PetscInt tk, PetscInt tj, PetscInt ti, PetscInt ak, PetscInt aj, PetscInt ai, PetscInt bk, PetscInt bj, PetscInt bi)
Internal helper: fills one edge dummy cell from its two face-adjacent dummy cells.
PetscErrorCode FinalizeCellFieldsFromBoundaryValues(UserCtx *user)
Implementation of FinalizeCellFieldsFromBoundaryValues().
PetscErrorCode PreparePeriodicQuickStencilFields(UserCtx *user, Vec local_vector_field, Vec local_scalar_field)
Implementation of PreparePeriodicQuickStencilFields().
PetscErrorCode BoundarySystem_Initialize(UserCtx *user, const char *bcs_filename)
Implementation of BoundarySystem_Initialize().
Definition Boundaries.c:412
static PetscErrorCode VerifySinglePassIsFinal(UserCtx *user, PetscBool any_periodic)
In verify mode, checks that the passes a single-pass call skipped would change nothing.
static PetscErrorCode TransferPeriodicFieldByDirection(UserCtx *user, FieldId field_id, char direction)
Copies one cell field's wrapped local values onto the owned periodic duplicate plane.
static BCFace EdgeSeparatingFace(PetscInt tk, PetscInt tj, PetscInt ti, PetscInt nk, PetscInt nj, PetscInt ni)
Internal helper: the face separating an edge dummy cell from one neighbour.
PetscErrorCode ApplyWallFunction(UserCtx *user)
Implementation of ApplyWallFunction().
static PetscErrorCode GetPersistentFaceField(UserCtx *user, FieldId field_id, char face_direction, DM *dm, Vec *global_vec, Vec *local_vec, PetscInt *dof)
Resolves one registered persistent single-face-family field.
static PetscErrorCode RefreshPeriodicPlaneGhosts(UserCtx *user, FieldId field_id, char direction)
Brings a field's local vector up to date after a periodic transfer along one direction.
static PetscErrorCode PoisonStaleLocalGhosts(UserCtx *user, FieldId field_id)
Fills a field's local vector with NaN, when -picurv_verify_ghost_updates is set.
MomentumRowType ClassifyMomentumRow(UserCtx *user, PetscInt i, PetscInt j, PetscInt k, PetscInt component, PetscInt *ri, PetscInt *rj, PetscInt *rk)
Implementation of ClassifyMomentumRow().
Definition Boundaries.c:139
PetscErrorCode PropagateBoundaryConfigToCoarserLevels(SimCtx *simCtx)
Implementation of PropagateBoundaryConfigToCoarserLevels().
Definition Boundaries.c:530
PetscBool BoundaryFaceHasWallShear(const BoundaryFaceConfig *face)
Implementation of BoundaryFaceHasWallShear().
Definition Boundaries.c:9
static PetscErrorCode GetPersistentStaggeredField(UserCtx *user, FieldId field_id, DM *dm, Vec *global_vec, Vec *local_vec)
Resolves one registered persistent component-staggered field.
PetscErrorCode ApplyMetricsPeriodicBCs(UserCtx *user)
Implementation of ApplyMetricsPeriodicBCs().
PetscErrorCode EnforceRHSBoundaryConditions(UserCtx *user)
Implementation of EnforceRHSBoundaryConditions().
Definition Boundaries.c:224
PetscErrorCode UpdateDummyCells(UserCtx *user, FieldId field_id)
Implementation of UpdateDummyCells().
static PetscErrorCode VerifyLocalGhostsCurrent(UserCtx *user, FieldId field_id, const char *where)
Requires a field's local vector to equal a full ghost update, when -picurv_verify_ghost_updates is se...
static PetscErrorCode VerifyBoundaryPassFinite(UserCtx *user)
Requires the boundary pass's fields to be finite, when -picurv_verify_ghost_updates is set.
PetscErrorCode LogWallModelDiagnostics(UserCtx *user)
Implementation of LogWallModelDiagnostics().
static PetscErrorCode WallModelFrictionVelocity(UserCtx *user, const PetscReal ***pressure, PetscInt i, PetscInt j, PetscInt k, PetscReal roughness_height, PetscReal distance_reference, Cmpnts tangent, PetscReal tangent_speed, PetscReal *friction_velocity)
The signed friction velocity the configured wall law gives for one wall-face element.
static PetscErrorCode TransferPeriodicStaggeredFieldByDirection(UserCtx *user, FieldId field_id, char periodic_direction)
Transfers one component-staggered field along one periodic axis.
PetscErrorCode BoundarySystem_RefreshUbcs(UserCtx *user)
Implementation of BoundarySystem_RefreshUbcs().
#define EDGE_FILL(tk, tj, ti, ak, aj, ai, bk, bj, bi)
PetscErrorCode SynchronizePeriodicLocalStaggeredField(UserCtx *user, Vec local_field)
Implementation of SynchronizePeriodicLocalStaggeredField().
PetscBool MomentumRowIsSolidMasked(const PetscReal ***nvert, PetscInt i, PetscInt j, PetscInt k, PetscInt component)
Implementation of MomentumRowIsSolidMasked().
Definition Boundaries.c:193
static PetscErrorCode TranslatePeriodicFaceCenterGhosts(UserCtx *user, Vec local_vec)
Applies geometric translations to wrapped face-center ghost coordinates.
PetscErrorCode BoundarySystem_Validate(UserCtx *user)
Implementation of BoundarySystem_Validate().
Definition Boundaries.c:352
PetscErrorCode LogBoundaryPressureDiagnostics(UserCtx *user)
Implementation of LogBoundaryPressureDiagnostics().
PetscErrorCode GetBoundaryFaceElements(UserCtx *user, BCFace face_id, BoundaryFaceElements *elements)
Implementation of GetBoundaryFaceElements().
Definition Boundaries.c:105
PetscErrorCode BoundaryCondition_Create(BCHandlerType handler_type, BoundaryCondition **new_bc_ptr)
Implementation of BoundaryCondition_Create().
Definition Boundaries.c:265
static PetscErrorCode IsFaceCenterCoordinateField(FieldId field_id, PetscBool *is_coordinate)
Returns whether a registered face field stores physical coordinates.
PetscErrorCode SynchronizePeriodicStaggeredFields(UserCtx *user, PetscInt num_fields, const FieldId field_ids[])
Implementation of SynchronizePeriodicStaggeredFields().
static PetscErrorCode SynchronizePeriodicCellFieldsFrom(UserCtx *user, PetscInt num_fields, const FieldId field_ids[], PetscBool locals_current, PetscBool final_update)
Body of SynchronizePeriodicCellFields(), optionally without its first or last ghost update.
PetscErrorCode ApplyBoundaryConditions(UserCtx *user)
Implementation of ApplyBoundaryConditions().
PetscErrorCode FinalizePostProjectionCellFields(UserCtx *user)
Implementation of FinalizePostProjectionCellFields().
PetscErrorCode UpdateCornerNodes(UserCtx *user, FieldId field_id)
Implementation of UpdateCornerNodes().
static PetscErrorCode TransferPeriodicFaceFieldByDirection(UserCtx *user, FieldId field_id, char face_direction, char periodic_direction)
Transfers one registered face-family field along one periodic axis.
PetscErrorCode CanRankServiceFace(const DMDALocalInfo *info, PetscInt IM_nodes_global, PetscInt JM_nodes_global, PetscInt KM_nodes_global, BCFace face_id, PetscBool *can_service_out)
Implementation of CanRankServiceFace().
Definition Boundaries.c:22
PetscErrorCode BoundarySystem_ExecuteStep(UserCtx *user)
Implementation of BoundarySystem_ExecuteStep().
Definition Boundaries.c:600
PetscErrorCode SynchronizePeriodicFaceFields(UserCtx *user, char face_direction, PetscInt num_fields, const FieldId field_ids[])
Synchronizes persistent fields belonging to one face family.
static PetscErrorCode GetPeriodicPlaneScatter(DM dm, char direction, VecScatter *plane)
The scatter that refreshes only the local entries mirroring a DM's two end planes in one direction.
static PetscErrorCode SynchronizePeriodicStaggeredFieldsFrom(UserCtx *user, PetscInt num_fields, const FieldId field_ids[], PetscBool locals_current)
Body of SynchronizePeriodicStaggeredFields(), optionally without its leading ghost update.
PetscErrorCode BoundarySystem_Destroy(UserCtx *user)
Implementation of BoundarySystem_Destroy().
PetscErrorCode SynchronizePeriodicCellFields(UserCtx *user, PetscInt num_fields, const FieldId field_ids[])
Implementation of SynchronizePeriodicCellFields().
static PetscErrorCode ApplyBoundaryPass(UserCtx *user, PetscBool any_periodic)
One boundary pass: the handlers, Contra2Cart, the wall function, the dummy, periodic and corner updat...
PetscErrorCode ApplyPeriodicBCs(UserCtx *user, PetscBool final_cell_update)
Implementation of ApplyPeriodicBCs().
MomentumRowType
Classification of one staggered momentum row (location + component).
Definition Boundaries.h:191
@ MOM_ROW_FIXED_HOMOGENEOUS
Dummy/tangential row carrying no unknown at all.
Definition Boundaries.h:194
@ MOM_ROW_PHYSICAL
Independent unknown governed by the momentum equation.
Definition Boundaries.h:192
@ MOM_ROW_PERIODIC_DUPLICATE
Duplicate of a wrapped representative row (see ri, rj, rk).
Definition Boundaries.h:195
@ MOM_ROW_FIXED_CONDITIONED
Strong Dirichlet row; the value comes from ApplyBoundaryConditions().
Definition Boundaries.h:193
static PetscBool BoundaryFaceIsFreeSlipWall(const BoundaryFaceConfig *face)
Reports whether a boundary face is a free-slip wall: impenetrable, exerting no shear,...
Definition Boundaries.h:180
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
FieldLayout layout
@ FIELD_CAPABILITY_PERIODIC_GEOMETRY_SHIFT
@ FIELD_CAPABILITY_PERIODIC_CELL_SYNC
@ FIELD_CAPABILITY_PERIODIC_FACE_SYNC
@ FIELD_CAPABILITY_PERIODIC_STAGGERED_SYNC
unsigned int capabilities
const FieldDescriptor * descriptor
PetscErrorCode FieldGetView(UserCtx *user, FieldId field_id, FieldView *view)
Resolve the existing DM and global/local vectors for one field.
FieldLayout
Logical storage topology of a field.
@ FIELD_LAYOUT_K_FACE
@ FIELD_LAYOUT_I_FACE
@ FIELD_LAYOUT_CELL_CENTERED
@ FIELD_LAYOUT_COMPONENT_STAGGERED
@ FIELD_LAYOUT_J_FACE
const char * canonical_name
PetscErrorCode FieldGetDescriptor(FieldId field_id, const FieldDescriptor **descriptor)
Return immutable metadata for a valid field identifier.
FieldId
Compile-time identity for a catalogued Eulerian field.
@ FIELD_ID_PSI
@ FIELD_ID_JETA
@ FIELD_ID_CENTZ
@ FIELD_ID_CSI
@ FIELD_ID_IAJ
@ FIELD_ID_NVERT
@ FIELD_ID_UCAT
@ FIELD_ID_KETA
@ FIELD_ID_JAJ
@ FIELD_ID_KAJ
@ FIELD_ID_AJ
@ FIELD_ID_NU_T
@ FIELD_ID_CENTY
@ FIELD_ID_KZET
@ FIELD_ID_IETA
@ FIELD_ID_UCONT
@ FIELD_ID_U_TAU
@ FIELD_ID_ICSI
@ FIELD_ID_ETA
@ FIELD_ID_WALL_STRESS
@ FIELD_ID_JCSI
@ FIELD_ID_JZET
@ FIELD_ID_P
@ FIELD_ID_IZET
@ FIELD_ID_ZET
@ FIELD_ID_KCSI
@ FIELD_ID_CENTX
Immutable metadata for one field identity.
Non-owning runtime objects resolved for one field and UserCtx.
PetscErrorCode ParseAllBoundaryConditions(UserCtx *user, const char *bcs_input_filename)
Parses the boundary conditions file to configure the type, handler, and any associated parameters for...
Definition io.c:911
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
void FreeBC_ParamList(BC_Param *head)
Frees an entire linked list of boundary-condition parameters.
Definition io.c:719
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
const char * BCHandlerTypeToString(BCHandlerType handler_type)
Converts a BCHandlerType enum to its string representation.
Definition logging.c:888
#define LOG_ALLOW_SYNC(scope, level, fmt,...)
Synchronized logging macro that checks both the log level and whether the calling function is in the ...
Definition logging.h:273
#define LOCAL
Logging scope definitions for controlling message output.
Definition logging.h:45
const char * ParticleBoundaryPolicyToString(ParticleBoundaryPolicy policy)
Returns the configuration token for a particle boundary policy.
Definition logging.c:850
#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 * WallFunctionModelToString(WallFunctionModel model)
Returns the user-facing name of a wall-function model.
Definition logging.c:786
const char * BCTypeToString(BCType type)
Returns the canonical log token for a boundary mathematical type.
Definition logging.c:828
@ LOG_ERROR
Critical errors that may halt the program.
Definition logging.h:29
@ 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
@ LOG_VERBOSE
Extremely detailed logs, typically for development use only.
Definition logging.h:34
#define PROFILE_FUNCTION_BEGIN
Marks the beginning of a profiled function: an always-on aggregate timer.
Definition logging.h:1000
PetscErrorCode GetOwnedCellRange(const DMDALocalInfo *info_nodes, PetscInt dim, PetscInt *xs_cell_global_out, PetscInt *xm_cell_local_out)
Determines the global starting index and number of CELLS owned by the current processor in a specifie...
Definition setup.c:3021
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
PetscErrorCode Contra2Cart(UserCtx *user)
Reconstructs Cartesian velocity (Ucat) at cell centers from contravariant velocity (Ucont) defined on...
Definition setup.c:3313
PetscErrorCode ComputeScalarFieldDerivatives(UserCtx *user, PetscInt i, PetscInt j, PetscInt k, PetscReal ***field_data, Cmpnts *grad)
Computes the gradient of a cell-centered SCALAR field at a specific grid point.
Definition setup.c:3799
PetscErrorCode UpdateLocalGhosts(UserCtx *user, FieldId field_id)
Updates the local vector (including ghost points) from its corresponding global vector.
Definition setup.c:2593
static void GetPeriodicAxes(const SimCtx *simCtx, PetscBool periodic[3])
Which grid axes are periodic.
Definition setup.h:361
PetscErrorCode RepairPeriodicFieldGhosts(UserCtx *user, const FieldView *view, Vec local_vec)
Applies a catalogued field's periodic normal-face ghost repair to a local vector.
Definition setup.c:2556
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
BCHandlerType type
Definition variables.h:390
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
Vec Wall_Stress
Definition variables.h:1193
PetscReal FarFluxInSum
Definition variables.h:1016
BCType
Defines the general mathematical/physical Category of a boundary.
Definition variables.h:316
@ INLET
Definition variables.h:323
@ OUTLET
Definition variables.h:322
@ PERIODIC
Definition variables.h:325
@ WALL
Definition variables.h:319
UserCtx * user
Definition variables.h:768
PetscReal FarFluxOutSum
Definition variables.h:1016
PetscBool inletFaceDefined
Definition variables.h:1183
PetscReal wall_viscosity_sum
Sum of the equivalent eddy viscosity u_tau^2 y/|U_1| - nu (diagnostic only).
Definition variables.h:717
PetscMPIInt rank
Definition variables.h:919
PetscBool verifyGhostUpdates
-picurv_verify_ghost_updates: test-only cross-checks of skipped or partial ghost updates,...
Definition variables.h:1108
BoundaryFaceConfig boundary_faces[6]
Definition variables.h:1182
PetscInt block_number
Definition variables.h:1009
BCFace identifiedInletBCFace
Definition variables.h:1184
Vec lNvert
Definition variables.h:1197
SimCtx * simCtx
Back-pointer to the master simulation context.
Definition variables.h:1160
PetscReal FluxOutSum
Definition variables.h:1016
struct BC_Param_s * next
Definition variables.h:375
char * key
Definition variables.h:373
PetscInt KM
Definition variables.h:1171
UserMG usermg
Definition variables.h:1082
@ PARTICLE_BOUNDARY_REMOVE
The particle leaves the domain (EXITED) and is removed.
Definition variables.h:337
@ PARTICLE_BOUNDARY_REFLECT
The particle is mirrored about the face plane and stays.
Definition variables.h:338
@ PARTICLE_BOUNDARY_WRAP
Periodic faces: the particle re-enters through the paired face.
Definition variables.h:339
PetscReal L_ref
Definition variables.h:898
PetscInt wall_yplus_excursions
Consecutive diagnostic samples with the first cell outside the selected law's valid y+ range.
Definition variables.h:1262
BCHandlerType
Defines the specific computational "strategy" for a boundary handler.
Definition variables.h:343
@ BC_HANDLER_PERIODIC_GEOMETRIC
Definition variables.h:352
@ 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
@ BC_HANDLER_WALL_NOSLIP
Definition variables.h:345
@ BC_HANDLER_OUTLET_CONSERVATION
Definition variables.h:350
@ BC_HANDLER_WALL_FREE_SLIP
Definition variables.h:347
PetscReal friction_velocity_sq
Sum of u_tau^2, for the RMS.
Definition variables.h:709
PetscReal ren
Definition variables.h:965
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
PetscInt _this
Definition variables.h:1175
WallFunctionModel
Selects the wall model applied on WALL faces.
Definition variables.h:600
@ WALL_FUNCTION_CABOT
Definition variables.h:604
@ WALL_FUNCTION_LOG_LAW
Definition variables.h:602
@ WALL_FUNCTION_WERNER
Definition variables.h:603
char * value
Definition variables.h:374
Vec Ucont
Definition variables.h:1197
Vec Ubcs
Physical Cartesian velocity at boundary faces. Full 3D array but only boundary-face entries are meani...
Definition variables.h:172
PetscInt friction_velocity_max_at[4]
Wall face (BCFace) and global cell i, j, k of friction_velocity_max.
Definition variables.h:715
PetscScalar x
Definition variables.h:145
PetscReal wall_distance_sum
Sum of the first-cell wall distance.
Definition variables.h:712
UserCtx * user
Definition variables.h:380
PetscReal friction_velocity_min
Smallest u_tau this rank corrected.
Definition variables.h:710
char analysis_dir[PETSC_MAX_PATH_LEN]
Definition variables.h:942
PetscReal FluxInSum
Definition variables.h:1016
PetscReal friction_velocity_max
Largest u_tau this rank corrected.
Definition variables.h:711
ParticleBoundaryPolicy particle_policy
What a particle crossing this face becomes (BC param particle_policy).
Definition variables.h:428
BC_Param * params
Definition variables.h:429
PetscReal y_plus_sum
Sum of u_tau * y / nu over corrected cells.
Definition variables.h:713
PetscReal wall_roughness_height
Definition variables.h:1004
PetscReal friction_velocity_sum
Sum of u_tau over corrected cells.
Definition variables.h:708
PetscScalar z
Definition variables.h:145
ScalingCtx scaling
Definition variables.h:1003
PetscInt JM
Definition variables.h:1171
PetscInt wallfunction
Enable wall functions on WALL faces.
Definition variables.h:1042
PetscInt y_plus_max_at[4]
Wall face (BCFace) and global cell i, j, k of y_plus_max.
Definition variables.h:716
PetscInt mglevels
Definition variables.h:775
PetscInt cells
Number of cells this rank corrected.
Definition variables.h:718
Vec Friction_Velocity
Definition variables.h:1189
PetscInt n[2]
Owned elements along a and b; 0 when this rank does not serve the face.
Definition variables.h:420
PetscReal y_plus_max
Largest first-cell y+ this rank corrected.
Definition variables.h:714
PetscInt step
Definition variables.h:924
DMDALocalInfo info
Definition variables.h:1169
@ BC_PRIORITY_OUTLET
Definition variables.h:364
@ BC_PRIORITY_FARFIELD
Definition variables.h:362
@ BC_PRIORITY_WALL
Definition variables.h:363
@ BC_PRIORITY_INLET
Definition variables.h:361
PetscScalar y
Definition variables.h:145
PetscInt IM
Definition variables.h:1171
Cmpnts periodic_translation[3]
Definition variables.h:1178
MGCtx * mgctx
Definition variables.h:778
PetscBool periodic_translation_valid[3]
Definition variables.h:1179
BCType mathematical_type
Definition variables.h:426
PetscReal P_ref
Definition variables.h:901
PetscBool wall_yplus_max_reported
The local y+ maximum has already been reported above the law's range.
Definition variables.h:1263
PetscReal ti
Definition variables.h:925
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
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
WallModelDiagnosticsState wall_diagnostics
Near-wall statistics from the last wall-model pass.
Definition variables.h:1261
BoundaryCondition * handler
Definition variables.h:430
Provides execution context for a boundary condition handler.
Definition variables.h:379
A node in a linked list for storing key-value parameters from the bcs.dat file.
Definition variables.h:372
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
User-level context for managing the entire multigrid hierarchy.
Definition variables.h:774
Near-wall statistics captured by one wall-model pass.
Definition variables.h:707
double find_utau_hydset(double kinematic_viscosity, double known_velocity, double wall_distance, double initial_guess, double roughness_height)
Solves for friction velocity using Newton-Raphson iteration.
void find_utau_Cabot(double kinematic_viscosity, double velocity, double wall_distance, double initial_guess, double pressure_gradient_tangent, double pressure_gradient_normal, double *friction_velocity, double *wall_shear_velocity, double *wall_shear_normal)
Solves for friction velocity using Cabot wall function.
double find_utau_Werner(double kinematic_viscosity, double velocity, double wall_distance, double initial_guess)
Friction velocity from a point velocity, inverting u_Werner() exactly.