PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
Functions
grid.h File Reference

Public interface for grid, solver, and metric setup routines. More...

#include "variables.h"
#include "logging.h"
#include "io.h"
#include "setup.h"
Include dependency graph for grid.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

PetscErrorCode DefineAllGridDimensions (SimCtx *simCtx)
 Orchestrates the parsing and setting of grid dimensions for all blocks.
 
PetscErrorCode InitializeAllGridDMs (SimCtx *simCtx)
 Orchestrates the creation of DMDA objects for every block and multigrid level.
 
PetscErrorCode AssignAllGridCoordinates (SimCtx *simCtx)
 Orchestrates the assignment of physical coordinates to all DMDA objects.
 
PetscErrorCode ValidatePeriodicGeometry (UserCtx *user)
 Validates that configured geometric periodic seams match by translation.
 
PetscErrorCode ComputeLocalBoundingBox (UserCtx *user, BoundingBox *localBBox)
 Computes the local bounding box of the grid on the current process.
 
PetscErrorCode GatherAllBoundingBoxes (UserCtx *user, BoundingBox **allBBoxes)
 Gathers local bounding boxes from all MPI processes to rank 0.
 
PetscErrorCode BroadcastAllBoundingBoxes (UserCtx *user, BoundingBox **bboxlist)
 Broadcasts the bounding box information collected on rank 0 to all other ranks.
 
PetscErrorCode CalculateInletProperties (UserCtx *user)
 Calculates the center and area of the primary INLET face.
 
PetscErrorCode CalculateOutletProperties (UserCtx *user)
 Calculates the center and area of the primary OUTLET face.
 
PetscErrorCode CalculateFaceCenterAndArea (UserCtx *user, BCFace face_id, Cmpnts *face_center, PetscReal *face_area)
 Calculates the geometric center and total area of a specified boundary face.
 
PetscErrorCode CreateCompatibleBlockDM (DM source, PetscInt dof, DM *result)
 Creates a DMDA sharing a block's decomposition at a different degree of freedom.
 
PetscErrorCode BalanceCoarsestOwnership (PetscInt coarse_nodes, PetscInt fine_cells, PetscInt refinements, PetscInt ranks, PetscInt *l)
 Split one axis of the coarsest level so the finest level's owned cells balance.
 

Detailed Description

Public interface for grid, solver, and metric setup routines.

Definition in file grid.h.

Function Documentation

◆ DefineAllGridDimensions()

PetscErrorCode DefineAllGridDimensions ( SimCtx *  simCtx)

Orchestrates the parsing and setting of grid dimensions for all blocks.

This function serves as the high-level entry point for defining the geometric properties of each grid block in the simulation. It iterates through every block defined by simCtx->block_number.

For each block, it performs two key actions:

  1. It explicitly sets the block's index (_this) in the corresponding UserCtx struct for the finest multigrid level. This makes the context "self-aware".
  2. It calls a helper function (ParseAndSetGridInputs) to handle the detailed work of parsing options or files to populate the rest of the geometric properties for that specific block (e.g., IM, Min_X, rx).
Parameters
simCtxThe master SimCtx, which contains the number of blocks and the UserCtx hierarchy to be configured.
Returns
PetscErrorCode 0 on success, or a PETSc error code on failure.

Orchestrates the parsing and setting of grid dimensions for all blocks.

See also
DefineAllGridDimensions()

Definition at line 38 of file grid.c.

39{
40 PetscErrorCode ierr;
41 PetscInt nblk = simCtx->block_number;
42 UserCtx *finest_users;
43
44 PetscFunctionBeginUser;
45
47
48 if (simCtx->usermg.mglevels == 0) {
49 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONGSTATE, "MG levels not set. Cannot get finest_users.");
50 }
51 // Get the UserCtx array for the finest grid level
52 finest_users = simCtx->usermg.mgctx[simCtx->usermg.mglevels - 1].user;
53
54 LOG_ALLOW(GLOBAL, LOG_INFO, "Defining grid dimensions for %" PetscInt_FMT " blocks...\n", nblk);
55
56 // Loop over each block to configure its grid dimensions and geometry.
57 for (PetscInt bi = 0; bi < nblk; bi++) {
58 LOG_ALLOW_SYNC(GLOBAL, LOG_DEBUG, "Rank %d: --- Configuring Geometry for Block %" PetscInt_FMT " ---\n", simCtx->rank, bi);
59
60 // Before calling any helpers, set the block index in the context.
61 // This makes the UserCtx self-aware of which block it represents.
62 LOG_ALLOW(GLOBAL,LOG_DEBUG,"finest_users->_this = %" PetscInt_FMT ", bi = %" PetscInt_FMT "\n",finest_users[bi]._this,bi);
63 //finest_user[bi]._this = bi;
64
65 // Call the helper function for this specific block. It can now derive
66 // all necessary information from the UserCtx pointer it receives.
67 ierr = ParseAndSetGridInputs(&finest_users[bi]); CHKERRQ(ierr);
68 }
69
71
72 PetscFunctionReturn(0);
73}
static PetscErrorCode ParseAndSetGridInputs(UserCtx *user)
Parse grid-generation options and store the resulting geometry settings in the context.
Definition grid.c:12
#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 GLOBAL
Scope for global logging across all processes.
Definition logging.h:46
#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_FUNCTION_END
Marks the end of a profiled code block.
Definition logging.h:1029
@ LOG_INFO
Informational messages about program execution.
Definition logging.h:31
@ LOG_DEBUG
Detailed debugging information.
Definition logging.h:32
#define PROFILE_FUNCTION_BEGIN
Marks the beginning of a profiled function: an always-on aggregate timer.
Definition logging.h:1000
UserCtx * user
Definition variables.h:768
PetscMPIInt rank
Definition variables.h:919
PetscInt block_number
Definition variables.h:1009
UserMG usermg
Definition variables.h:1082
PetscInt mglevels
Definition variables.h:775
MGCtx * mgctx
Definition variables.h:778
User-defined context containing data specific to a single computational grid level.
Definition variables.h:1157
Here is the call graph for this function:
Here is the caller graph for this function:

◆ InitializeAllGridDMs()

PetscErrorCode InitializeAllGridDMs ( SimCtx *  simCtx)

Orchestrates the creation of DMDA objects for every block and multigrid level.

This function systematically builds the entire DMDA hierarchy. It first calculates the dimensions (IM, JM, KM) for all coarse grids based on the finest grid's dimensions and the semi-coarsening flags. It then iterates from the coarsest to the finest level, calling a powerful helper function (InitializeSingleGridDM) to create the DMs for each block, ensuring that finer grids are properly aligned with their coarser parents for multigrid efficiency.

Parameters
simCtxThe master SimCtx, containing the configured UserCtx hierarchy.
Returns
PetscErrorCode 0 on success, or a PETSc error code on failure.

Orchestrates the creation of DMDA objects for every block and multigrid level.

See also
InitializeAllGridDMs()

Definition at line 309 of file grid.c.

310{
311 PetscErrorCode ierr;
312 UserMG *usermg = &simCtx->usermg;
313 MGCtx *mgctx = usermg->mgctx;
314 PetscInt nblk = simCtx->block_number;
315
316 PetscFunctionBeginUser;
317
319
320 LOG_ALLOW(GLOBAL,LOG_INFO, "Pre-scanning BCs to identify domain periodicity.\n");
321 ierr = DeterminePeriodicity(simCtx); CHKERRQ(ierr);
322
323 LOG_ALLOW(GLOBAL, LOG_INFO, "Creating DMDA objects for all levels and blocks...\n");
324
325 // --- Part 1: Calculate Coarse Grid Dimensions & VALIDATE ---
326 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Calculating and validating coarse grid dimensions...\n");
327 for (PetscInt level = usermg->mglevels - 2; level >= 0; level--) {
328 for (PetscInt bi = 0; bi < nblk; bi++) {
329 UserCtx *user_coarse = &mgctx[level].user[bi];
330 UserCtx *user_fine = &mgctx[level + 1].user[bi];
331
332 user_coarse->IM = user_fine->isc ? user_fine->IM : (user_fine->IM + 1) / 2;
333 user_coarse->JM = user_fine->jsc ? user_fine->JM : (user_fine->JM + 1) / 2;
334 user_coarse->KM = user_fine->ksc ? user_fine->KM : (user_fine->KM + 1) / 2;
335
336 LOG_ALLOW_SYNC(LOCAL, LOG_TRACE, "Rank %d: Block %" PetscInt_FMT ", Level %" PetscInt_FMT " dims calculated: %" PetscInt_FMT " x %" PetscInt_FMT " x %" PetscInt_FMT "\n",
337 simCtx->rank, bi, level, user_coarse->IM, user_coarse->JM, user_coarse->KM);
338
339 // Validation check from legacy MGDACreate to ensure coarsening is possible
340 PetscInt check_i = user_coarse->IM * (2 - user_coarse->isc) - (user_fine->IM + 1 - user_coarse->isc);
341 PetscInt check_j = user_coarse->JM * (2 - user_coarse->jsc) - (user_fine->JM + 1 - user_coarse->jsc);
342 PetscInt check_k = user_coarse->KM * (2 - user_coarse->ksc) - (user_fine->KM + 1 - user_coarse->ksc);
343
344 if (check_i + check_j + check_k != 0) {
345 // SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONG,
346 // "Grid at level %d, block %d cannot be coarsened from %dx%dx%d to %dx%dx%d with the given semi-coarsening flags. Check grid dimensions.",
347 // level, bi, user_fine->IM, user_fine->JM, user_fine->KM, user_coarse->IM, user_coarse->JM, user_coarse->KM);
348 LOG(GLOBAL,LOG_WARNING,"WARNING: Grid at level %" PetscInt_FMT ", block %" PetscInt_FMT " can't be consistently coarsened further.\n", level, bi);
349 }
350 }
351 }
352
353 // --- Part 2: Create DMs from Coarse to Fine for each Block ---
354 for (PetscInt bi = 0; bi < nblk; bi++) {
355 LOG_ALLOW(GLOBAL, LOG_DEBUG, "--- Creating DMs for Block %" PetscInt_FMT " ---\n", bi);
356
357 // Create the coarsest level DM first (passing NULL for the coarse_user)
358 ierr = InitializeSingleGridDM(&mgctx[0].user[bi], NULL); CHKERRQ(ierr);
359
360 // Create finer level DMs, passing the next-coarser context for alignment
361 for (PetscInt level = 1; level < usermg->mglevels; level++) {
362 ierr = InitializeSingleGridDM(&mgctx[level].user[bi], &mgctx[level-1].user[bi]); CHKERRQ(ierr);
363 }
364 }
365
366 // --- Optional: View the finest DM for debugging verification ---
367 if (get_log_level() >= LOG_DEBUG) {
368 LOG_ALLOW(GLOBAL, LOG_INFO, "--- Viewing Finest DMDA (Level %" PetscInt_FMT ", Block 0) ---\n", usermg->mglevels - 1);
369 ierr = DMView(mgctx[usermg->mglevels - 1].user[0].da, PETSC_VIEWER_STDOUT_WORLD); CHKERRQ(ierr);
370 }
371
372 LOG_ALLOW(GLOBAL, LOG_INFO, "DMDA object creation complete.\n");
373
375
376 PetscFunctionReturn(0);
377}
static PetscErrorCode InitializeSingleGridDM(UserCtx *user, UserCtx *coarse_user)
Create and configure one PETSc DMDA for a multigrid level.
Definition grid.c:158
PetscErrorCode DeterminePeriodicity(SimCtx *simCtx)
Scans all block-specific boundary condition files to determine a globally consistent periodicity for ...
Definition io.c:1096
#define LOCAL
Logging scope definitions for controlling message output.
Definition logging.h:45
#define LOG(scope, level, fmt,...)
Logging macro for PETSc-based applications with scope control.
Definition logging.h:86
@ LOG_TRACE
Very fine-grained tracing information for in-depth debugging.
Definition logging.h:33
@ LOG_WARNING
Non-critical issues that warrant attention.
Definition logging.h:30
static LogLevel get_log_level(void)
Retrieves the current logging level from the environment variable LOG_LEVEL.
Definition logging.h:496
PetscInt isc
Definition variables.h:1175
PetscInt ksc
Definition variables.h:1175
PetscInt KM
Definition variables.h:1171
PetscInt jsc
Definition variables.h:1175
PetscInt JM
Definition variables.h:1171
PetscInt IM
Definition variables.h:1171
Context for Multigrid operations.
Definition variables.h:767
User-level context for managing the entire multigrid hierarchy.
Definition variables.h:774
Here is the call graph for this function:
Here is the caller graph for this function:

◆ AssignAllGridCoordinates()

PetscErrorCode AssignAllGridCoordinates ( SimCtx *  simCtx)

Orchestrates the assignment of physical coordinates to all DMDA objects.

This function manages the entire process of populating the coordinate vectors for every DMDA across all multigrid levels and blocks. It follows a two-part strategy that is essential for multigrid methods:

  1. Populate Finest Level: It first loops through each block and calls a helper (SetFinestLevelCoordinates) to set the physical coordinates for the highest-resolution grid (the finest multigrid level).
  2. Restrict to Coarser Levels: It then iterates downwards from the finest level, calling a helper (RestrictCoordinates) to copy the coordinate values from the fine grid nodes to their corresponding parent nodes on the coarser grids. This ensures all levels represent the exact same geometry.
Parameters
simCtxThe master SimCtx, containing the configured UserCtx hierarchy.
Returns
PetscErrorCode 0 on success, or a PETSc error code on failure.

Orchestrates the assignment of physical coordinates to all DMDA objects.

See also
AssignAllGridCoordinates()

Definition at line 389 of file grid.c.

390{
391 PetscErrorCode ierr;
392 UserMG *usermg = &simCtx->usermg;
393 PetscInt nblk = simCtx->block_number;
394
395 PetscFunctionBeginUser;
396
398
399 LOG_ALLOW(GLOBAL, LOG_INFO, "Assigning physical coordinates to all grid DMs...\n");
400
401 // --- Part 1: Populate the Finest Grid Level ---
402 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Setting coordinates for the finest grid level (%" PetscInt_FMT ")...\n", usermg->mglevels - 1);
403 for (PetscInt bi = 0; bi < nblk; bi++) {
404 UserCtx *fine_user = &usermg->mgctx[usermg->mglevels - 1].user[bi];
405 ierr = SetFinestLevelCoordinates(fine_user); CHKERRQ(ierr);
406 LOG_ALLOW(GLOBAL,LOG_TRACE,"The Finest level coordinates for block %" PetscInt_FMT " have been set.\n",bi);
407 if(get_log_level() >= LOG_VERBOSE && is_function_allowed(__func__)==true){
408 ierr = LOG_FIELD_MIN_MAX(fine_user, FIELD_ID_COORDINATES);
409 }
410 }
411 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Finest level coordinates have been set for all blocks.\n");
412
413 // --- Part 2: Restrict Coordinates to Coarser Levels ---
414 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Restricting coordinates to coarser grid levels...\n");
415 for (PetscInt level = usermg->mglevels - 2; level >= 0; level--) {
416 for (PetscInt bi = 0; bi < nblk; bi++) {
417 UserCtx *coarse_user = &usermg->mgctx[level].user[bi];
418 UserCtx *fine_user = &usermg->mgctx[level + 1].user[bi];
419 ierr = RestrictCoordinates(coarse_user, fine_user); CHKERRQ(ierr);
420
421 LOG_ALLOW(GLOBAL,LOG_TRACE,"Coordinates restricted to block %" PetscInt_FMT " level %" PetscInt_FMT ".\n",bi,level);
422 if(get_log_level() >= LOG_VERBOSE && is_function_allowed(__func__)==true) {
423 ierr = LOG_FIELD_MIN_MAX(coarse_user, FIELD_ID_COORDINATES);
424 }
425 }
426 }
427
428 LOG_ALLOW(GLOBAL, LOG_INFO, "Physical coordinates assigned to all grid levels and blocks.\n");
429
431
432 PetscFunctionReturn(0);
433}
@ FIELD_ID_COORDINATES
static PetscErrorCode RestrictCoordinates(UserCtx *coarse_user, UserCtx *fine_user)
Restrict finest-grid coordinates onto each coarser multigrid level.
Definition grid.c:796
static PetscErrorCode SetFinestLevelCoordinates(UserCtx *user)
Attach the generated physical coordinates to the finest-level DMDA.
Definition grid.c:585
PetscErrorCode LOG_FIELD_MIN_MAX(UserCtx *user, FieldId field_id)
Computes and logs the local and global min/max values of a 3-component vector field.
Definition logging.c:2501
PetscBool is_function_allowed(const char *functionName)
Checks if a given function is in the allow-list.
Definition logging.c:207
@ LOG_VERBOSE
Extremely detailed logs, typically for development use only.
Definition logging.h:34
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ValidatePeriodicGeometry()

PetscErrorCode ValidatePeriodicGeometry ( UserCtx *  user)

Validates that configured geometric periodic seams match by translation.

Each active periodic direction is checked independently using the physical nodal coordinates. On success, the constant seam translation is stored in the UserCtx.

Parameters
userGrid/block context with assigned coordinates and boundary configuration.
Returns
PetscErrorCode 0 on success, or a user-input error for unsupported geometry.

Validates that configured geometric periodic seams match by translation.

Full API contract is documented with the header declaration in include/grid.h.

Definition at line 450 of file grid.c.

451{
452 const BCFace neg_faces[3] = {BC_FACE_NEG_X, BC_FACE_NEG_Y, BC_FACE_NEG_Z};
453 const BCFace pos_faces[3] = {BC_FACE_POS_X, BC_FACE_POS_Y, BC_FACE_POS_Z};
454 const char axis_names[3] = {'X', 'Y', 'Z'};
455 const Cmpnts ***coor = NULL;
456 Vec lcoor = NULL;
457 DMDALocalInfo info;
458
459 PetscFunctionBeginUser;
461 info = user->info;
462 lcoor = user->lCoor;
463 PetscCheck(lcoor != NULL, PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONGSTATE,
464 "Cannot validate periodic geometry before local coordinates are assigned.");
465 for (PetscInt axis = 0; axis < 3; axis++) {
466 const PetscBool neg_periodic =
467 user->boundary_faces[neg_faces[axis]].mathematical_type == PERIODIC;
468 const PetscBool pos_periodic =
469 user->boundary_faces[pos_faces[axis]].mathematical_type == PERIODIC;
470 PetscReal local_min[3] = {PETSC_MAX_REAL, PETSC_MAX_REAL, PETSC_MAX_REAL};
471 PetscReal local_max[3] = {-PETSC_MAX_REAL, -PETSC_MAX_REAL, -PETSC_MAX_REAL};
472 PetscReal global_min[3], global_max[3];
473 PetscInt local_count = 0, global_count = 0;
474
475 user->periodic_translation_valid[axis] = PETSC_FALSE;
476 user->periodic_translation[axis] = (Cmpnts){0.0, 0.0, 0.0};
477 if (!neg_periodic && !pos_periodic) continue;
478
479 PetscCheck(neg_periodic && pos_periodic, PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT,
480 "Periodic geometry in the %c direction requires paired negative and positive faces.",
481 axis_names[axis]);
482 const PetscInt axis_size = axis == 0 ? info.mx : (axis == 1 ? info.my : info.mz);
483 PetscCheck(axis_size >= 5, PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT,
484 "%c-periodic geometry on block %" PetscInt_FMT " level %" PetscInt_FMT " requires at least four physical "
485 "nodes in that direction; found %" PetscInt_FMT ".",
486 axis_names[axis], user->_this, user->thislevel, axis_size - 1);
487
488 PetscCall(DMDAVecGetArrayRead(user->fda, lcoor, &coor));
489 if (axis == 0 && info.xs == 0) {
490 for (PetscInt k = PetscMax(info.zs, 0); k < PetscMin(info.zs + info.zm, info.mz - 1); k++) {
491 for (PetscInt j = PetscMax(info.ys, 0); j < PetscMin(info.ys + info.ym, info.my - 1); j++) {
492 const Cmpnts delta = {
493 coor[k][j][-2].x - coor[k][j][0].x,
494 coor[k][j][-2].y - coor[k][j][0].y,
495 coor[k][j][-2].z - coor[k][j][0].z
496 };
497 for (PetscInt c = 0; c < 3; c++) {
498 local_min[c] = PetscMin(local_min[c], CoordinateComponent(delta, c));
499 local_max[c] = PetscMax(local_max[c], CoordinateComponent(delta, c));
500 }
501 local_count++;
502 }
503 }
504 } else if (axis == 1 && info.ys == 0) {
505 for (PetscInt k = PetscMax(info.zs, 0); k < PetscMin(info.zs + info.zm, info.mz - 1); k++) {
506 for (PetscInt i = PetscMax(info.xs, 0); i < PetscMin(info.xs + info.xm, info.mx - 1); i++) {
507 const Cmpnts delta = {
508 coor[k][-2][i].x - coor[k][0][i].x,
509 coor[k][-2][i].y - coor[k][0][i].y,
510 coor[k][-2][i].z - coor[k][0][i].z
511 };
512 for (PetscInt c = 0; c < 3; c++) {
513 local_min[c] = PetscMin(local_min[c], CoordinateComponent(delta, c));
514 local_max[c] = PetscMax(local_max[c], CoordinateComponent(delta, c));
515 }
516 local_count++;
517 }
518 }
519 } else if (axis == 2 && info.zs == 0) {
520 for (PetscInt j = PetscMax(info.ys, 0); j < PetscMin(info.ys + info.ym, info.my - 1); j++) {
521 for (PetscInt i = PetscMax(info.xs, 0); i < PetscMin(info.xs + info.xm, info.mx - 1); i++) {
522 const Cmpnts delta = {
523 coor[-2][j][i].x - coor[0][j][i].x,
524 coor[-2][j][i].y - coor[0][j][i].y,
525 coor[-2][j][i].z - coor[0][j][i].z
526 };
527 for (PetscInt c = 0; c < 3; c++) {
528 local_min[c] = PetscMin(local_min[c], CoordinateComponent(delta, c));
529 local_max[c] = PetscMax(local_max[c], CoordinateComponent(delta, c));
530 }
531 local_count++;
532 }
533 }
534 }
535 PetscCall(DMDAVecRestoreArrayRead(user->fda, lcoor, &coor));
536
537 PetscCallMPI(MPI_Allreduce(local_min, global_min, 3, MPIU_REAL, MPI_MIN, PETSC_COMM_WORLD));
538 PetscCallMPI(MPI_Allreduce(local_max, global_max, 3, MPIU_REAL, MPI_MAX, PETSC_COMM_WORLD));
539 PetscCallMPI(MPI_Allreduce(&local_count, &global_count, 1, MPIU_INT, MPI_SUM, PETSC_COMM_WORLD));
540 PetscCheck(global_count > 0, PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONGSTATE,
541 "No physical seam nodes were available to validate %c-periodic geometry.",
542 axis_names[axis]);
543
544 PetscReal translation[3];
545 PetscReal scale = 1.0;
546 PetscReal max_mismatch = 0.0;
547 for (PetscInt c = 0; c < 3; c++) {
548 translation[c] = 0.5 * (global_min[c] + global_max[c]);
549 scale = PetscMax(scale, PetscAbsReal(translation[c]));
550 max_mismatch = PetscMax(max_mismatch, global_max[c] - global_min[c]);
551 }
552 const PetscReal tolerance = 1.0e-9 * scale + 100.0 * PETSC_MACHINE_EPSILON;
553 const PetscReal magnitude = PetscSqrtReal(
554 PetscSqr(translation[0]) + PetscSqr(translation[1]) + PetscSqr(translation[2]));
555
556 PetscCheck(max_mismatch <= tolerance, PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT,
557 "Unsupported %c-periodic geometry on block %" PetscInt_FMT " level %" PetscInt_FMT ": opposite physical "
558 "surfaces are not related by one constant translation. Maximum component "
559 "mismatch is %.12e (tolerance %.12e).",
560 axis_names[axis], user->_this, user->thislevel,
561 (double)max_mismatch, (double)tolerance);
562 PetscCheck(magnitude > tolerance, PETSC_COMM_WORLD, PETSC_ERR_USER_INPUT,
563 "Unsupported %c-periodic geometry on block %" PetscInt_FMT " level %" PetscInt_FMT ": seam translation "
564 "magnitude %.12e is zero or too small.",
565 axis_names[axis], user->_this, user->thislevel, (double)magnitude);
566
567 user->periodic_translation[axis] =
568 (Cmpnts){translation[0], translation[1], translation[2]};
569 user->periodic_translation_valid[axis] = PETSC_TRUE;
571 "Validated %c-periodic geometry for block %" PetscInt_FMT " level %" PetscInt_FMT " with translation "
572 "(%.12e, %.12e, %.12e).\n",
573 axis_names[axis], user->_this, user->thislevel,
574 (double)translation[0], (double)translation[1], (double)translation[2]);
575 }
576
578 PetscFunctionReturn(0);
579}
static PetscReal CoordinateComponent(Cmpnts value, PetscInt component)
Returns one Cartesian component from a coordinate/vector value.
Definition grid.c:438
@ PERIODIC
Definition variables.h:325
BoundaryFaceConfig boundary_faces[6]
Definition variables.h:1182
PetscInt _this
Definition variables.h:1175
PetscScalar x
Definition variables.h:145
PetscInt thislevel
Definition variables.h:1269
PetscScalar z
Definition variables.h:145
Vec lCoor
Definition variables.h:1243
DMDALocalInfo info
Definition variables.h:1169
PetscScalar y
Definition variables.h:145
Cmpnts periodic_translation[3]
Definition variables.h:1178
PetscBool periodic_translation_valid[3]
Definition variables.h:1179
BCType mathematical_type
Definition variables.h:426
BCFace
Identifies the six logical faces of a structured computational block.
Definition variables.h:308
@ BC_FACE_NEG_X
Definition variables.h:309
@ BC_FACE_POS_Z
Definition variables.h:311
@ BC_FACE_POS_Y
Definition variables.h:310
@ BC_FACE_NEG_Z
Definition variables.h:311
@ BC_FACE_POS_X
Definition variables.h:309
@ BC_FACE_NEG_Y
Definition variables.h:310
A 3D point or vector with PetscScalar components.
Definition variables.h:144
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ComputeLocalBoundingBox()

PetscErrorCode ComputeLocalBoundingBox ( UserCtx *  user,
BoundingBox *  localBBox 
)

Computes the local bounding box of the grid on the current process.

This function calculates the minimum and maximum coordinates of the local grid points owned by the current MPI process and stores the computed bounding box in the provided structure.

Parameters
[in]userPointer to the user-defined context containing grid information.
[out]localBBoxPointer to the BoundingBox structure to store the computed bounding box.
Returns
PetscErrorCode Returns 0 on success, non-zero on failure.

Computes the local bounding box of the grid on the current process.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/grid.h.

See also
ComputeLocalBoundingBox()

Definition at line 869 of file grid.c.

870{
871 PetscErrorCode ierr;
872 PetscInt i, j, k;
873 PetscMPIInt rank;
874 PetscInt xs, ys, zs, xe, ye, ze;
875 DMDALocalInfo info;
876 Vec coordinates;
877 Cmpnts ***coordArray;
878 Cmpnts minCoords, maxCoords;
879
880 PetscFunctionBeginUser;
881
883
884 // Start of function execution
885 LOG_ALLOW(GLOBAL, LOG_INFO, "Entering the function.\n");
886
887 // Validate input Pointers
888 if (!user) {
889 LOG_ALLOW(LOCAL, LOG_ERROR, "Input 'user' Pointer is NULL.\n");
891 return PETSC_ERR_ARG_NULL;
892 }
893 if (!localBBox) {
894 LOG_ALLOW(LOCAL, LOG_ERROR, "Output 'localBBox' Pointer is NULL.\n");
896 return PETSC_ERR_ARG_NULL;
897 }
898
899 // Get MPI rank
900 rank = PetscGlobalRank;
901
902 // Get the local coordinates vector from the DMDA
903 coordinates = user->lCoor;
904
905 if (!coordinates) {
906 LOG_ALLOW(LOCAL, LOG_ERROR, "Coordinates vector is NULL.\n");
908 return PETSC_ERR_ARG_NULL;
909 }
910
911 // Access the coordinate array for reading
912 ierr = DMDAVecGetArrayRead(user->fda, coordinates, &coordArray);
913 if (ierr) {
914 LOG_ALLOW(LOCAL, LOG_ERROR, "Error accessing coordinate array.\n");
916 return ierr;
917 }
918
919 // Get the local grid information (indices and sizes)
920 info = user->info;
921 if (ierr) {
922 LOG_ALLOW(LOCAL, LOG_ERROR, "Error getting DMDA local info.\n");
924 return ierr;
925 }
926
927
928 xs = info.gxs; xe = xs + info.gxm;
929 ys = info.gys; ye = ys + info.gym;
930 zs = info.gzs; ze = zs + info.gzm;
931
932 /*
933 xs = info.xs; xe = xs + info.xm;
934 ys = info.ys; ye = ys + info.ym;
935 zs = info.zs; ze = zs + info.zm;
936 */
937
938 // Initialize min and max coordinates with extreme values
939 minCoords.x = minCoords.y = minCoords.z = PETSC_MAX_REAL;
940 maxCoords.x = maxCoords.y = maxCoords.z = PETSC_MIN_REAL;
941
942 LOG_ALLOW(LOCAL, LOG_TRACE, "[Rank %d] Grid indices (Including Ghosts): xs=%" PetscInt_FMT ", xe=%" PetscInt_FMT ", ys=%" PetscInt_FMT ", ye=%" PetscInt_FMT ", zs=%" PetscInt_FMT ", ze=%" PetscInt_FMT ".\n",rank, xs, xe, ys, ye, zs, ze);
943
944 // Iterate over the local grid to find min and max coordinates
945 for (k = zs; k < ze; k++) {
946 for (j = ys; j < ye; j++) {
947 for (i = xs; i < xe; i++) {
948 // Only consider nodes within the physical domain.
949 if(i < user->IM && j < user->JM && k < user->KM){
950 Cmpnts coord = coordArray[k][j][i];
951
952 // Update min and max coordinates
953 if (coord.x < minCoords.x) minCoords.x = coord.x;
954 if (coord.y < minCoords.y) minCoords.y = coord.y;
955 if (coord.z < minCoords.z) minCoords.z = coord.z;
956
957 if (coord.x > maxCoords.x) maxCoords.x = coord.x;
958 if (coord.y > maxCoords.y) maxCoords.y = coord.y;
959 if (coord.z > maxCoords.z) maxCoords.z = coord.z;
960 }
961 }
962 }
963 }
964
965
966 // Add tolerance to bboxes.
967 minCoords.x = minCoords.x - BBOX_TOLERANCE;
968 minCoords.y = minCoords.y - BBOX_TOLERANCE;
969 minCoords.z = minCoords.z - BBOX_TOLERANCE;
970
971 maxCoords.x = maxCoords.x + BBOX_TOLERANCE;
972 maxCoords.y = maxCoords.y + BBOX_TOLERANCE;
973 maxCoords.z = maxCoords.z + BBOX_TOLERANCE;
974
975 LOG_ALLOW(LOCAL,LOG_DEBUG," Tolerance added to the limits: %.8e .\n",(PetscReal)BBOX_TOLERANCE);
976
977 // Log the computed min and max coordinates
978 LOG_ALLOW(LOCAL, LOG_INFO,"[Rank %d] Bounding Box Ranges = X[%.6f, %.6f], Y[%.6f,%.6f], Z[%.6f, %.6f].\n",rank,minCoords.x, maxCoords.x,minCoords.y, maxCoords.y, minCoords.z, maxCoords.z);
979
980
981
982 // Restore the coordinate array
983 ierr = DMDAVecRestoreArrayRead(user->fda, coordinates, &coordArray);
984 if (ierr) {
985 LOG_ALLOW(LOCAL, LOG_ERROR, "Error restoring coordinate array.\n");
987 return ierr;
988 }
989
990 // Set the local bounding box
991 localBBox->min_coords = minCoords;
992 localBBox->max_coords = maxCoords;
993
994 // Update the bounding box inside the UserCtx for consistency
995 user->bbox = *localBBox;
996
997 LOG_ALLOW(GLOBAL, LOG_INFO, "Exiting the function successfully.\n");
998
1000
1001 PetscFunctionReturn(0);
1002}
#define BBOX_TOLERANCE
Definition grid.c:7
@ LOG_ERROR
Critical errors that may halt the program.
Definition logging.h:29
Cmpnts max_coords
Maximum x, y, z coordinates of the bounding box.
Definition variables.h:214
Cmpnts min_coords
Minimum x, y, z coordinates of the bounding box.
Definition variables.h:213
BoundingBox bbox
Definition variables.h:1173
Here is the caller graph for this function:

◆ GatherAllBoundingBoxes()

PetscErrorCode GatherAllBoundingBoxes ( UserCtx *  user,
BoundingBox **  allBBoxes 
)

Gathers local bounding boxes from all MPI processes to rank 0.

This function computes the local bounding box on each process, then collects all local bounding boxes on the root process (rank 0) using MPI. The result is stored in an array of BoundingBox structures on rank 0.

Parameters
[in]userPointer to the user-defined context containing grid information.
[out]allBBoxesPointer to a pointer where the array of gathered bounding boxes will be stored on rank 0. The caller on rank 0 must free this array.
Returns
PetscErrorCode Returns 0 on success, non-zero on failure.

Gathers local bounding boxes from all MPI processes to rank 0.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/grid.h.

See also
GatherAllBoundingBoxes()

Definition at line 1011 of file grid.c.

1012{
1013 PetscErrorCode ierr;
1014 PetscMPIInt rank, size;
1015 BoundingBox *bboxArray = NULL;
1016 BoundingBox localBBox;
1017
1018 PetscFunctionBeginUser;
1019
1021
1022 /* Validate */
1023 if (!user || !allBBoxes) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
1024 "GatherAllBoundingBoxes: NULL pointer");
1025
1026 rank = PetscGlobalRank;
1027 size = PetscGlobalSize;
1028
1029 /* Compute local bbox */
1030 ierr = ComputeLocalBoundingBox(user, &localBBox); CHKERRQ(ierr);
1031
1032 /* Ensure everyone is synchronized before the gather */
1033 MPI_Barrier(PETSC_COMM_WORLD);
1035 "Rank %d: about to MPI_Gather(localBBox)\n", rank);
1036
1037 /* Allocate on root */
1038 if (rank == 0) {
1039 bboxArray = (BoundingBox*)malloc(size * sizeof(BoundingBox));
1040 if (!bboxArray) SETERRABORT(PETSC_COMM_WORLD, PETSC_ERR_MEM,
1041 "GatherAllBoundingBoxes: malloc failed");
1042 }
1043
1044 /* Collective: every rank must call */
1045 ierr = MPI_Gather(&localBBox, sizeof(BoundingBox), MPI_BYTE,
1046 bboxArray, sizeof(BoundingBox), MPI_BYTE,
1047 0, PETSC_COMM_WORLD);
1048 CHKERRMPI(ierr);
1049
1050 MPI_Barrier(PETSC_COMM_WORLD);
1052 "Rank %d: completed MPI_Gather(localBBox)\n", rank);
1053
1054 /* Return result */
1055 if (rank == 0) {
1056 *allBBoxes = bboxArray;
1057 } else {
1058 *allBBoxes = NULL;
1059 }
1060
1062
1063 PetscFunctionReturn(0);
1064}
PetscErrorCode ComputeLocalBoundingBox(UserCtx *user, BoundingBox *localBBox)
Implementation of ComputeLocalBoundingBox().
Definition grid.c:869
Defines a 3D axis-aligned bounding box.
Definition variables.h:212
Here is the call graph for this function:
Here is the caller graph for this function:

◆ BroadcastAllBoundingBoxes()

PetscErrorCode BroadcastAllBoundingBoxes ( UserCtx *  user,
BoundingBox **  bboxlist 
)

Broadcasts the bounding box information collected on rank 0 to all other ranks.

This function assumes that GatherAllBoundingBoxes() was previously called, so bboxlist is allocated and populated on rank 0. All other ranks will allocate memory for bboxlist, and this function will use MPI_Bcast to distribute the bounding box data to them.

Parameters
[in]userPointer to the UserCtx structure. (Currently unused in this function, but kept for consistency.)
[in,out]bboxlistPointer to the array of BoundingBoxes. On rank 0, this should point to a valid array of size 'size' (where size is the number of MPI ranks). On non-root ranks, this function will allocate memory for bboxlist.
Returns
PetscErrorCode Returns 0 on success, non-zero on MPI or PETSc-related errors.

Broadcasts the bounding box information collected on rank 0 to all other ranks.

See also
BroadcastAllBoundingBoxes()

Definition at line 1071 of file grid.c.

1072{
1073 PetscErrorCode ierr;
1074 (void)user;
1075 PetscMPIInt rank, size;
1076
1077 PetscFunctionBeginUser;
1078
1080
1081 if (!bboxlist) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
1082 "BroadcastAllBoundingBoxes: NULL pointer");
1083
1084 rank = user->simCtx->rank;
1085 size = user->simCtx->size;
1086
1087 /* Non-root ranks must allocate before the Bcast */
1088 if (rank != 0) {
1089 *bboxlist = (BoundingBox*)malloc(size * sizeof(BoundingBox));
1090 if (!*bboxlist) SETERRABORT(PETSC_COMM_WORLD, PETSC_ERR_MEM,
1091 "BroadcastAllBoundingBoxes: malloc failed");
1092 }
1093
1094 MPI_Barrier(PETSC_COMM_WORLD);
1096 "Rank %d: about to MPI_Bcast(%d boxes)\n", rank, size);
1097
1098 /* Collective: every rank must call */
1099 ierr = MPI_Bcast(*bboxlist, size * sizeof(BoundingBox), MPI_BYTE,
1100 0, PETSC_COMM_WORLD);
1101 CHKERRMPI(ierr);
1102
1103 MPI_Barrier(PETSC_COMM_WORLD);
1105 "Rank %d: completed MPI_Bcast(%d boxes)\n", rank, size);
1106
1107
1109
1110 PetscFunctionReturn(0);
1111}
SimCtx * simCtx
Back-pointer to the master simulation context.
Definition variables.h:1160
PetscMPIInt size
Definition variables.h:920
Here is the caller graph for this function:

◆ CalculateInletProperties()

PetscErrorCode CalculateInletProperties ( UserCtx *  user)

Calculates the center and area of the primary INLET face.

This function identifies the primary INLET face from the boundary face configurations, computes its geometric center and total area using a generic utility function, and stores these results in the simulation context.

Parameters
userPointer to the UserCtx containing boundary face information.
Returns
PetscErrorCode

Calculates the center and area of the primary INLET face.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/grid.h.

See also
CalculateInletProperties()

Definition at line 1119 of file grid.c.

1120{
1121 PetscErrorCode ierr;
1122 BCFace inlet_face_id = -1;
1123 PetscBool inlet_found = PETSC_FALSE;
1124
1125 PetscFunctionBeginUser;
1127
1128 // 1. Identify the primary inlet face from the configuration
1129 for (int i = 0; i < 6; i++) {
1130 if (user->boundary_faces[i].mathematical_type == INLET) {
1131 inlet_face_id = user->boundary_faces[i].face_id;
1132 inlet_found = PETSC_TRUE;
1133 break; // Use the first inlet found
1134 }
1135 }
1136
1137 if (!inlet_found) {
1138 LOG_ALLOW(GLOBAL, LOG_INFO, "No INLET face found. Skipping inlet center calculation.\n");
1140 PetscFunctionReturn(0);
1141 }
1142
1143 Cmpnts inlet_center;
1144 PetscReal inlet_area;
1145
1146 // 2. Call the generic utility to compute the center and area of any face.
1147 ierr = CalculateFaceCenterAndArea(user,inlet_face_id,&inlet_center,&inlet_area); CHKERRQ(ierr);
1148
1149 // 3. Store results in the SimCtx
1150 user->simCtx->CMx_c = inlet_center.x;
1151 user->simCtx->CMy_c = inlet_center.y;
1152 user->simCtx->CMz_c = inlet_center.z;
1153 user->simCtx->AreaInSum = inlet_area;
1154
1156 "Rank[%d] Inlet Center: (%.6f, %.6f, %.6f), Area: %.6f\n",
1157 user->simCtx->rank, inlet_center.x, inlet_center.y, inlet_center.z, inlet_area);
1158
1160 PetscFunctionReturn(0);
1161
1162}
PetscErrorCode CalculateFaceCenterAndArea(UserCtx *user, BCFace face_id, Cmpnts *face_center, PetscReal *face_area)
Implementation of CalculateFaceCenterAndArea().
Definition grid.c:1211
@ INLET
Definition variables.h:323
PetscReal CMy_c
Definition variables.h:1001
PetscReal CMz_c
Definition variables.h:1001
PetscReal AreaInSum
Definition variables.h:1036
PetscReal CMx_c
Definition variables.h:1001
Here is the call graph for this function:
Here is the caller graph for this function:

◆ CalculateOutletProperties()

PetscErrorCode CalculateOutletProperties ( UserCtx *  user)

Calculates the center and area of the primary OUTLET face.

This function identifies the primary OUTLET face from the boundary face configurations, computes its geometric center and total area using a generic utility function, and stores these results in the simulation context.

Parameters
userPointer to the UserCtx containing boundary face information.
Returns
PetscErrorCode

Calculates the center and area of the primary OUTLET face.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/grid.h.

See also
CalculateOutletProperties()

Definition at line 1170 of file grid.c.

1171{
1172 PetscErrorCode ierr;
1173 BCFace outlet_face_id = -1;
1174 PetscBool outlet_found = PETSC_FALSE;
1175 PetscFunctionBeginUser;
1177 // 1. Identify the primary outlet face from the configuration
1178 for (int i = 0; i < 6; i++) {
1179 if (user->boundary_faces[i].mathematical_type == OUTLET) {
1180 outlet_face_id = user->boundary_faces[i].face_id;
1181 outlet_found = PETSC_TRUE;
1182 break; // Use the first outlet found
1183 }
1184 }
1185 if (!outlet_found) {
1186 LOG_ALLOW(GLOBAL, LOG_INFO, "No OUTLET face found. Skipping outlet center calculation.\n");
1188 PetscFunctionReturn(0);
1189 }
1190 PetscReal outlet_area;
1191 Cmpnts outlet_center;
1192 // 2. Call the generic utility to compute the center and area of any face
1193 ierr = CalculateFaceCenterAndArea(user,outlet_face_id,&outlet_center,&outlet_area); CHKERRQ(ierr);
1194 // 3. Store results in the SimCtx
1195 user->simCtx->AreaOutSum = outlet_area;
1196
1198 "Outlet Center: (%.6f, %.6f, %.6f), Area: %.6f\n",
1199 outlet_center.x, outlet_center.y, outlet_center.z, outlet_area);
1200
1202 PetscFunctionReturn(0);
1203}
@ OUTLET
Definition variables.h:322
PetscReal AreaOutSum
Definition variables.h:1036
Here is the call graph for this function:
Here is the caller graph for this function:

◆ CalculateFaceCenterAndArea()

PetscErrorCode CalculateFaceCenterAndArea ( UserCtx *  user,
BCFace  face_id,
Cmpnts *  face_center,
PetscReal *  face_area 
)

Calculates the geometric center and total area of a specified boundary face.

This function computes two key properties of a boundary face in the computational domain:

  1. Geometric Center: The average (x,y,z) position of all physical nodes on the face
  2. Total Area: The sum of face area vector magnitudes from all non-solid cells adjacent to the face

Indexing Architecture

The solver uses different indexing conventions for different field types:

Node-Centered Fields (Coordinates):

  • Direct indexing: Node n stored at coor[n]
  • For mx=26: Physical nodes [0-24], Dummy at [25]
  • For mz=98: Physical nodes [0-96], Dummy at [97]

Face-Centered Fields (Metrics: csi, eta, zet):

  • Direct indexing: Face n stored at csi/eta/zet[n]
  • For mx=26: Physical faces [0-24], Dummy at [25]
  • For mz=98: Physical faces [0-96], Dummy at [97]
  • Face at index k bounds cells k-1 and k

Cell-Centered Fields (nvert):

  • Shifted indexing: Physical cell c stored at nvert[c+1]
  • For mx=26 (25 cells): Cell 0→nvert[1], Cell 23→nvert[24]
  • For mz=98 (96 cells): Cell 0→nvert[1], Cell 95→nvert[96]
  • nvert[0] and nvert[mx-1] are ghost values

Face-to-Index Mapping

Example for a domain with mx=26, my=26, mz=98:

Face ID Node Index Face Metric Adjacent Cell (shifted) Physical Extent
BC_FACE_NEG_X i=0 csi[k][j][0] nvert[k][j][1] (Cell 0) j∈[0,24], k∈[0,96]
BC_FACE_POS_X i=24 csi[k][j][24] nvert[k][j][24] (Cell 23) j∈[0,24], k∈[0,96]
BC_FACE_NEG_Y j=0 eta[k][0][i] nvert[k][1][i] (Cell 0) i∈[0,24], k∈[0,96]
BC_FACE_POS_Y j=24 eta[k][24][i] nvert[k][24][i] (Cell 23) i∈[0,24], k∈[0,96]
BC_FACE_NEG_Z k=0 zet[0][j][i] nvert[1][j][i] (Cell 0) i∈[0,24], j∈[0,24]
BC_FACE_POS_Z k=96 zet[96][j][i] nvert[96][j][i] (Cell 95) i∈[0,24], j∈[0,24]

Algorithm

The function performs two separate computations with different loop bounds:

1. Center Calculation (uses ALL physical nodes):

  • Loop over all physical nodes on the face (excluding dummy indices)
  • Accumulate coordinate sums: Σx, Σy, Σz
  • Count number of nodes
  • Average: center = (Σx/n, Σy/n, Σz/n)

2. Area Calculation (uses INTERIOR cells only):

  • Loop over interior cell range to avoid accessing ghost values in nvert
  • For each face adjacent to a fluid cell (nvert < 0.1):
    • Compute area magnitude: |csi/eta/zet| = √(x² + y² + z²)
    • Accumulate to total area

Loop Bound Details

Why different bounds for center vs. area?

For BC_FACE_NEG_X at i=0 with my=26, mz=98:

Center calculation (coordinates):

  • j ∈ [ys, j_max): Includes j=[0,24] (25 nodes), excludes dummy at j=25
  • k ∈ [zs, k_max): Includes k=[0,96] (97 nodes), excludes dummy at k=97
  • Total: 25 × 97 = 2,425 nodes

Area calculation (nvert checks):

  • j ∈ [lys, lye): j=[1,24] (24 values), excludes boundaries
  • k ∈ [lzs, lze): k=[1,96] (96 values), excludes boundaries
  • Why restricted?
    • At j=0: nvert[k][0][1] is ghost (no cell at j=-1)
    • At j=25: nvert[k][25][1] is ghost (no cell at j=24, index 25 is dummy)
    • At k=0: nvert[0][j][1] is ghost (no cell at k=-1)
    • At k=97: nvert[97][j][1] is ghost (no cell at k=96, index 97 is dummy)
  • Total: 24 × 96 = 2,304 interior cells adjacent to face

Area Calculation Formulas

Face area contributions are computed from metric tensor magnitudes:

  • i-faces (±Xi): Area = |csi| = √(csi_x² + csi_y² + csi_z²)
  • j-faces (±Eta): Area = |eta| = √(eta_x² + eta_y² + eta_z²)
  • k-faces (±Zeta): Area = |zet| = √(zet_x² + zet_y² + zet_z²)
Parameters
[in]userPointer to UserCtx containing grid info, DMs, and field vectors
[in]face_idEnum identifying which boundary face to analyze (BC_FACE_NEG_X, etc.)
[out]face_centerPointer to Cmpnts structure to store computed geometric center (x,y,z)
[out]face_areaPointer to PetscReal to store computed total face area
Returns
PetscErrorCode Returns 0 on success, non-zero PETSc error code on failure
Note
This function uses MPI_Allreduce, so it must be called collectively by all ranks
Only ranks that own the specified boundary face contribute to the calculation
Center calculation includes ALL physical nodes on the face
Area calculation ONLY includes faces adjacent to fluid cells (nvert < 0.1)
Dummy/unused indices (e.g., k=97, j=25 for standard test case) are excluded
Warning
Assumes grid and field arrays have been properly initialized
Incorrect face_id values will result in zero contribution from all ranks
See also
CanRankServiceFace() for determining rank ownership of boundary faces
BCFace enum for valid face_id values
LOG_FIELD_ANATOMY() for debugging field indexing
Example Usage:
Cmpnts inlet_center;
PetscReal inlet_area;
ierr = CalculateFaceCenterAndArea(user, BC_FACE_NEG_Z, &inlet_center, &inlet_area);
PetscPrintf(PETSC_COMM_WORLD, "Inlet center: (%.4f, %.4f, %.4f), Area: %.6f\n",
inlet_center.x, inlet_center.y, inlet_center.z, inlet_area);
PetscErrorCode CalculateFaceCenterAndArea(UserCtx *user, BCFace face_id, Cmpnts *face_center, PetscReal *face_area)
Calculates the geometric center and total area of a specified boundary face.
Definition grid.c:1211

Calculates the geometric center and total area of a specified boundary face.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/grid.h.

See also
CalculateFaceCenterAndArea()

< Local sum of (x,y,z) coordinates

< Local sum of face area magnitudes

< Local count of nodes

< Global sum of coordinates

< Global sum of areas

< Global count of nodes

< i-range: [xs, xe)

< j-range: [ys, ye)

< k-range: [zs, ze)

< Physical domain size in i (exclude dummy)

< Physical domain size in j (exclude dummy)

< Physical domain size in k (exclude dummy)

< Start at 1 if on -Xi boundary

< End at mx-1 if on +Xi boundary

< Start at 1 if on -Eta boundary

< End at my-1 if on +Eta boundary

< Start at 1 if on -Zeta boundary

< End at mz-1 if on +Zeta boundary

< Exclude dummy at i=mx-1 (e.g., i=25)

< Exclude dummy at j=my-1 (e.g., j=25)

< Exclude dummy at k=mz-1 (e.g., k=97)

< Local ghosted coordinate vector

< Nodal coordinates [k][j][i]

< Face metric tensors [k][j][i]

< Cell blanking field [k][j][i] (shifted +1)

Definition at line 1211 of file grid.c.

1213{
1214 PetscErrorCode ierr;
1215 DMDALocalInfo info;
1216
1217 // ========================================================================
1218 // Local accumulators for this rank's contribution
1219 // ========================================================================
1220 PetscReal local_sum[3] = {0.0, 0.0, 0.0}; ///< Local sum of (x,y,z) coordinates
1221 PetscReal localAreaSum = 0.0; ///< Local sum of face area magnitudes
1222 PetscCount local_n_points = 0; ///< Local count of nodes
1223
1224 // ========================================================================
1225 // Global accumulators after MPI reduction
1226 // ========================================================================
1227 PetscReal global_sum[3] = {0.0, 0.0, 0.0}; ///< Global sum of coordinates
1228 PetscReal globalAreaSum = 0.0; ///< Global sum of areas
1229 PetscCount global_n_points = 0; ///< Global count of nodes
1230
1231 // ========================================================================
1232 // Grid information and array pointers
1233 // ========================================================================
1234 info = user->info;
1235
1236 // Rank's owned range in global indices
1237 PetscInt xs = info.xs, xe = info.xs + info.xm; ///< i-range: [xs, xe)
1238 PetscInt ys = info.ys, ye = info.ys + info.ym; ///< j-range: [ys, ye)
1239 PetscInt zs = info.zs, ze = info.zs + info.zm; ///< k-range: [zs, ze)
1240
1241 // Global domain dimensions (total allocated, includes dummy at end)
1242 PetscInt mx = info.mx, my = info.my, mz = info.mz;
1243 PetscInt IM = user->IM; ///< Physical domain size in i (exclude dummy)
1244 PetscInt JM = user->JM; ///< Physical domain size in j (exclude dummy)
1245 PetscInt KM = user->KM; ///< Physical domain size in k (exclude dummy)
1246
1247 // ========================================================================
1248 // Interior loop bounds (adjusted to avoid ghost/boundary cells)
1249 // These are used for nvert checks where we need valid cell indices
1250 // ========================================================================
1251 PetscInt lxs = xs; if(xs == 0) lxs = xs + 1; ///< Start at 1 if on -Xi boundary
1252 PetscInt lxe = xe; if(xe == mx) lxe = xe - 1; ///< End at mx-1 if on +Xi boundary
1253 PetscInt lys = ys; if(ys == 0) lys = ys + 1; ///< Start at 1 if on -Eta boundary
1254 PetscInt lye = ye; if(ye == my) lye = ye - 1; ///< End at my-1 if on +Eta boundary
1255 PetscInt lzs = zs; if(zs == 0) lzs = zs + 1; ///< Start at 1 if on -Zeta boundary
1256 PetscInt lze = ze; if(ze == mz) lze = ze - 1; ///< End at mz-1 if on +Zeta boundary
1257
1258 // ========================================================================
1259 // Physical node bounds (exclude dummy indices at mx-1, my-1, mz-1)
1260 // These are used for coordinate loops where we want ALL physical nodes
1261 // ========================================================================
1262 PetscInt i_max = (xe == mx) ? mx - 1 : xe; ///< Exclude dummy at i=mx-1 (e.g., i=25)
1263 PetscInt j_max = (ye == my) ? my - 1 : ye; ///< Exclude dummy at j=my-1 (e.g., j=25)
1264 PetscInt k_max = (ze == mz) ? mz - 1 : ze; ///< Exclude dummy at k=mz-1 (e.g., k=97)
1265
1266 // ========================================================================
1267 // Array pointers for field access
1268 // ========================================================================
1269 Vec lCoor; ///< Local ghosted coordinate vector
1270 Cmpnts ***coor; ///< Nodal coordinates [k][j][i]
1271 Cmpnts ***csi, ***eta, ***zet; ///< Face metric tensors [k][j][i]
1272 PetscReal ***nvert; ///< Cell blanking field [k][j][i] (shifted +1)
1273
1274 PetscFunctionBeginUser;
1276
1277 // ========================================================================
1278 // Step 1: Check if this rank owns the specified boundary face
1279 // ========================================================================
1280 PetscBool owns_face = PETSC_FALSE;
1281 ierr = CanRankServiceFace(&info,IM,JM,KM,face_id,&owns_face); CHKERRQ(ierr);
1282 if(owns_face){
1283 // ========================================================================
1284 // Step 2: Get read-only array access for all required fields
1285 // ========================================================================
1286 lCoor = user->lCoor;
1287 ierr = DMDAVecGetArrayRead(user->fda, lCoor, &coor); CHKERRQ(ierr);
1288 ierr = DMDAVecGetArrayRead(user->da, user->lNvert, &nvert); CHKERRQ(ierr);
1289 ierr = DMDAVecGetArrayRead(user->fda, user->lCsi, &csi); CHKERRQ(ierr);
1290 ierr = DMDAVecGetArrayRead(user->fda, user->lEta, &eta); CHKERRQ(ierr);
1291 ierr = DMDAVecGetArrayRead(user->fda, user->lZet, &zet); CHKERRQ(ierr);
1292
1293 // ========================================================================
1294 // Step 3: Loop over the specified face and accumulate center and area
1295 // ========================================================================
1296 switch (face_id) {
1297
1298 // ====================================================================
1299 // BC_FACE_NEG_X: Face at i=0 (bottom boundary in i-direction)
1300 // ====================================================================
1301 case BC_FACE_NEG_X:
1302 if (xs == 0) {
1303 PetscInt i = 0; // Face is at node index i=0
1304
1305 // ---- Part 1: Center calculation (ALL physical nodes) ----
1306 // Loop over ALL physical nodes on this face
1307 // For my=26, mz=98: j∈[0,24], k∈[0,96] → 25×97 = 2,425 nodes
1308 for (PetscInt k = zs; k < k_max; k++) {
1309 for (PetscInt j = ys; j < j_max; j++) {
1310 // Accumulate coordinates at node [k][j][0]
1311 local_sum[0] += coor[k][j][i].x;
1312 local_sum[1] += coor[k][j][i].y;
1313 local_sum[2] += coor[k][j][i].z;
1314 local_n_points++;
1315 }
1316 }
1317
1318 // ---- Part 2: Area calculation (INTERIOR cells only) ----
1319 // Loop over interior range where nvert checks are valid
1320 // For my=26, mz=98: j∈[1,24], k∈[1,96] → 24×96 = 2,304 cells
1321 for (PetscInt k = lzs; k < lze; k++) {
1322 for (PetscInt j = lys; j < lye; j++) {
1323 // Check if adjacent cell is fluid
1324 // nvert[k][j][i+1] = nvert[k][j][1] checks Cell 0
1325 // (Physical Cell 0 in j-k plane, stored at shifted index [1])
1326 if (nvert[k][j][i+1] < 0.1) {
1327 // Cell is fluid - add face area contribution
1328 // Face area = magnitude of csi metric at [k][j][0]
1329 localAreaSum += sqrt(csi[k][j][i].x * csi[k][j][i].x +
1330 csi[k][j][i].y * csi[k][j][i].y +
1331 csi[k][j][i].z * csi[k][j][i].z);
1332 }
1333 }
1334 }
1335 }
1336 break;
1337
1338 // ====================================================================
1339 // BC_FACE_POS_X: Face at i=IM-1 (top boundary in i-direction)
1340 // ====================================================================
1341 case BC_FACE_POS_X:
1342 if (xe == mx) {
1343 PetscInt i = mx - 2; // Last physical node (e.g., i=24 for mx=26)
1344
1345 // ---- Part 1: Center calculation (ALL physical nodes) ----
1346 for (PetscInt k = zs; k < k_max; k++) {
1347 for (PetscInt j = ys; j < j_max; j++) {
1348 local_sum[0] += coor[k][j][i].x;
1349 local_sum[1] += coor[k][j][i].y;
1350 local_sum[2] += coor[k][j][i].z;
1351 local_n_points++;
1352 }
1353 }
1354
1355 // ---- Part 2: Area calculation (INTERIOR cells only) ----
1356 for (PetscInt k = lzs; k < lze; k++) {
1357 for (PetscInt j = lys; j < lye; j++) {
1358 // Check if adjacent cell is fluid
1359 // nvert[k][j][i] = nvert[k][j][24] checks last cell (Cell 23)
1360 // (Physical Cell 23, stored at shifted index [24])
1361 if (nvert[k][j][i] < 0.1) {
1362 // Face area = magnitude of csi metric at [k][j][24]
1363 localAreaSum += sqrt(csi[k][j][i].x * csi[k][j][i].x +
1364 csi[k][j][i].y * csi[k][j][i].y +
1365 csi[k][j][i].z * csi[k][j][i].z);
1366 }
1367 }
1368 }
1369 }
1370 break;
1371
1372 // ====================================================================
1373 // BC_FACE_NEG_Y: Face at j=0 (bottom boundary in j-direction)
1374 // ====================================================================
1375 case BC_FACE_NEG_Y:
1376 if (ys == 0) {
1377 PetscInt j = 0; // Face is at node index j=0
1378
1379 // ---- Part 1: Center calculation (ALL physical nodes) ----
1380 // For mx=26, mz=98: i∈[0,24], k∈[0,96] → 25×97 = 2,425 nodes
1381 for (PetscInt k = zs; k < k_max; k++) {
1382 for (PetscInt i = xs; i < i_max; i++) {
1383 local_sum[0] += coor[k][j][i].x;
1384 local_sum[1] += coor[k][j][i].y;
1385 local_sum[2] += coor[k][j][i].z;
1386 local_n_points++;
1387 }
1388 }
1389
1390 // ---- Part 2: Area calculation (INTERIOR cells only) ----
1391 // For mx=26, mz=98: i∈[1,24], k∈[1,96] → 24×96 = 2,304 cells
1392 for (PetscInt k = lzs; k < lze; k++) {
1393 for (PetscInt i = lxs; i < lxe; i++) {
1394 // nvert[k][j+1][i] = nvert[k][1][i] checks Cell 0
1395 if (nvert[k][j+1][i] < 0.1) {
1396 // Face area = magnitude of eta metric at [k][0][i]
1397 localAreaSum += sqrt(eta[k][j][i].x * eta[k][j][i].x +
1398 eta[k][j][i].y * eta[k][j][i].y +
1399 eta[k][j][i].z * eta[k][j][i].z);
1400 }
1401 }
1402 }
1403 }
1404 break;
1405
1406 // ====================================================================
1407 // BC_FACE_POS_Y: Face at j=JM-1 (top boundary in j-direction)
1408 // ====================================================================
1409 case BC_FACE_POS_Y:
1410 if (ye == my) {
1411 PetscInt j = my - 2; // Last physical node (e.g., j=24 for my=26)
1412
1413 // ---- Part 1: Center calculation (ALL physical nodes) ----
1414 for (PetscInt k = zs; k < k_max; k++) {
1415 for (PetscInt i = xs; i < i_max; i++) {
1416 local_sum[0] += coor[k][j][i].x;
1417 local_sum[1] += coor[k][j][i].y;
1418 local_sum[2] += coor[k][j][i].z;
1419 local_n_points++;
1420 }
1421 }
1422
1423 // ---- Part 2: Area calculation (INTERIOR cells only) ----
1424 for (PetscInt k = lzs; k < lze; k++) {
1425 for (PetscInt i = lxs; i < lxe; i++) {
1426 // nvert[k][j][i] = nvert[k][24][i] checks last cell (Cell 23)
1427 if (nvert[k][j][i] < 0.1) {
1428 // Face area = magnitude of eta metric at [k][24][i]
1429 localAreaSum += sqrt(eta[k][j][i].x * eta[k][j][i].x +
1430 eta[k][j][i].y * eta[k][j][i].y +
1431 eta[k][j][i].z * eta[k][j][i].z);
1432 }
1433 }
1434 }
1435 }
1436 break;
1437
1438 // ====================================================================
1439 // BC_FACE_NEG_Z: Face at k=0 (inlet, bottom boundary in k-direction)
1440 // ====================================================================
1441 case BC_FACE_NEG_Z:
1442 if (zs == 0) {
1443 PetscInt k = 0; // Face is at node index k=0
1444
1445 // ---- Part 1: Center calculation (ALL physical nodes) ----
1446 // For mx=26, my=26: i∈[0,24], j∈[0,24] → 25×25 = 625 nodes
1447 for (PetscInt j = ys; j < j_max; j++) {
1448 for (PetscInt i = xs; i < i_max; i++) {
1449 local_sum[0] += coor[k][j][i].x;
1450 local_sum[1] += coor[k][j][i].y;
1451 local_sum[2] += coor[k][j][i].z;
1452 local_n_points++;
1453 }
1454 }
1455
1456 // ---- Part 2: Area calculation (INTERIOR cells only) ----
1457 // For mx=26, my=26: i∈[1,24], j∈[1,24] → 24×24 = 576 cells
1458 for (PetscInt j = lys; j < lye; j++) {
1459 for (PetscInt i = lxs; i < lxe; i++) {
1460 // nvert[k+1][j][i] = nvert[1][j][i] checks Cell 0
1461 // (Physical Cell 0 in i-j plane, stored at shifted index [1])
1462 if (nvert[k+1][j][i] < 0.1) {
1463 // Face area = magnitude of zet metric at [0][j][i]
1464 localAreaSum += sqrt(zet[k][j][i].x * zet[k][j][i].x +
1465 zet[k][j][i].y * zet[k][j][i].y +
1466 zet[k][j][i].z * zet[k][j][i].z);
1467 }
1468 }
1469 }
1470 }
1471 break;
1472
1473 // ====================================================================
1474 // BC_FACE_POS_Z: Face at k=KM-1 (outlet, top boundary in k-direction)
1475 // ====================================================================
1476 case BC_FACE_POS_Z:
1477 if (ze == mz) {
1478 PetscInt k = mz - 2; // Last physical node (e.g., k=96 for mz=98)
1479
1480 // ---- Part 1: Center calculation (ALL physical nodes) ----
1481 // For mx=26, my=26: i∈[0,24], j∈[0,24] → 25×25 = 625 nodes
1482 for (PetscInt j = ys; j < j_max; j++) {
1483 for (PetscInt i = xs; i < i_max; i++) {
1484 local_sum[0] += coor[k][j][i].x;
1485 local_sum[1] += coor[k][j][i].y;
1486 local_sum[2] += coor[k][j][i].z;
1487 local_n_points++;
1488 }
1489 }
1490
1491 // ---- Part 2: Area calculation (INTERIOR cells only) ----
1492 // For mx=26, my=26: i∈[1,24], j∈[1,24] → 24×24 = 576 cells
1493 for (PetscInt j = lys; j < lye; j++) {
1494 for (PetscInt i = lxs; i < lxe; i++) {
1495 // nvert[k][j][i] = nvert[96][j][i] checks last cell (Cell 95)
1496 // (Physical Cell 95, stored at shifted index [96])
1497 if (nvert[k][j][i] < 0.1) {
1498 // Face area = magnitude of zet metric at [96][j][i]
1499 localAreaSum += sqrt(zet[k][j][i].x * zet[k][j][i].x +
1500 zet[k][j][i].y * zet[k][j][i].y +
1501 zet[k][j][i].z * zet[k][j][i].z);
1502 }
1503 }
1504 }
1505 }
1506 break;
1507
1508 default:
1509 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE,
1510 "Unknown face_id %d in CalculateFaceCenterAndArea", face_id);
1511 }
1512
1513 // ========================================================================
1514 // Step 4: Restore array access (release pointers)
1515 // ========================================================================
1516 ierr = DMDAVecRestoreArrayRead(user->fda, lCoor, &coor); CHKERRQ(ierr);
1517 ierr = DMDAVecRestoreArrayRead(user->da, user->lNvert, &nvert); CHKERRQ(ierr);
1518 ierr = DMDAVecRestoreArrayRead(user->fda, user->lCsi, &csi); CHKERRQ(ierr);
1519 ierr = DMDAVecRestoreArrayRead(user->fda, user->lEta, &eta); CHKERRQ(ierr);
1520 ierr = DMDAVecRestoreArrayRead(user->fda, user->lZet, &zet); CHKERRQ(ierr);
1521 }
1522 // ========================================================================
1523 // Step 5: Perform MPI reductions to get global sums
1524 // ========================================================================
1525 // Sum coordinate contributions from all ranks
1526 ierr = MPI_Allreduce(local_sum, global_sum, 3, MPI_DOUBLE, MPI_SUM,
1527 PETSC_COMM_WORLD); CHKERRQ(ierr);
1528
1529 // Sum node counts from all ranks
1530 ierr = MPI_Allreduce(&local_n_points, &global_n_points, 1, MPI_COUNT, MPI_SUM,
1531 PETSC_COMM_WORLD); CHKERRQ(ierr);
1532
1533 // Sum area contributions from all ranks
1534 ierr = MPI_Allreduce(&localAreaSum, &globalAreaSum, 1, MPI_DOUBLE, MPI_SUM,
1535 PETSC_COMM_WORLD); CHKERRQ(ierr);
1536
1537 // ========================================================================
1538 // Step 6: Calculate geometric center by averaging coordinates
1539 // ========================================================================
1540 if (global_n_points > 0) {
1541 face_center->x = global_sum[0] / global_n_points;
1542 face_center->y = global_sum[1] / global_n_points;
1543 face_center->z = global_sum[2] / global_n_points;
1545 "Calculated center for Face %s: (x=%.4f, y=%.4f, z=%.4f) from %lld nodes\n",
1546 BCFaceToString(face_id),
1547 face_center->x, face_center->y, face_center->z,
1548 (long long)global_n_points);
1549 } else {
1550 // No nodes found - this should not happen for a valid face
1552 "WARNING: Face %s identified but no grid points found. Center not calculated.\n",
1553 BCFaceToString(face_id));
1554 face_center->x = face_center->y = face_center->z = 0.0;
1555 }
1556
1557 // ========================================================================
1558 // Step 7: Return computed total area
1559 // ========================================================================
1560 *face_area = globalAreaSum;
1562 "Calculated area for Face %s: Area=%.6f\n",
1563 BCFaceToString(face_id), *face_area);
1564
1566 PetscFunctionReturn(0);
1567}
PetscErrorCode CanRankServiceFace(const DMDALocalInfo *info, PetscInt IM_nodes_global, PetscInt JM_nodes_global, PetscInt KM_nodes_global, BCFace face_id, PetscBool *can_service_out)
Determines if the current MPI rank owns any part of a specified global face.
Definition Boundaries.c:22
const char * BCFaceToString(BCFace face)
Returns the canonical log token for a boundary-face enum value.
Definition logging.c:640
Vec lNvert
Definition variables.h:1197
Here is the call graph for this function:
Here is the caller graph for this function:

◆ CreateCompatibleBlockDM()

PetscErrorCode CreateCompatibleBlockDM ( DM  source,
PetscInt  dof,
DM *  result 
)

Creates a DMDA sharing a block's decomposition at a different degree of freedom.

Fields whose component count is neither one nor three still have to live on the same index space as the block, so a pointwise loop can read da and write them at the same (i,j,k). Copying the source DM's sizes, boundary types, stencil, and — critically — its explicit per-rank ownership ranges makes the decomposition identical rather than merely similar. Letting PETSc re-decide the split would be free to disagree, and the loop would misalign silently.

Parameters
[in]sourceExisting block DMDA whose decomposition is mirrored.
[in]dofDegrees of freedom the new DM carries; must be positive.
[out]resultCreated DM; the caller owns it and must destroy it.
Returns
Zero on success, or a PETSc error for a null argument or non-positive dof.

Creates a DMDA sharing a block's decomposition at a different degree of freedom.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/grid.h.

See also
CreateCompatibleBlockDM()

Definition at line 81 of file grid.c.

82{
83 PetscErrorCode ierr;
84 PetscInt dim = 0, M = 0, N = 0, P = 0, m = 0, n = 0, p = 0, source_dof = 0, stencil_width = 0;
85 DMBoundaryType bx = DM_BOUNDARY_NONE, by = DM_BOUNDARY_NONE, bz = DM_BOUNDARY_NONE;
86 DMDAStencilType stencil_type = DMDA_STENCIL_BOX;
87 const PetscInt *lx = NULL, *ly = NULL, *lz = NULL;
88
89 PetscFunctionBeginUser;
91 PetscCheck(source != NULL && result != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
92 "Source DM and output pointer are required.");
93 PetscCheck(dof > 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE,
94 "A compatible DM needs a positive degree of freedom, got %" PetscInt_FMT ".", dof);
95
96 ierr = DMDAGetInfo(source, &dim, &M, &N, &P, &m, &n, &p, &source_dof, &stencil_width,
97 &bx, &by, &bz, &stencil_type); CHKERRQ(ierr);
98 ierr = DMDAGetOwnershipRanges(source, &lx, &ly, &lz); CHKERRQ(ierr);
99 {
100 char object[96];
101 ierr = PetscSNPrintf(object, sizeof(object), "A %" PetscInt_FMT "x%" PetscInt_FMT "x%" PetscInt_FMT
102 " grid field of %" PetscInt_FMT " components", M, N, P, dof); CHKERRQ(ierr);
103 ierr = PicurvCheckPetscIntRange(PetscObjectComm((PetscObject)source), (PetscInt64)M * N * P * dof, object); CHKERRQ(ierr);
104 }
105 ierr = DMDACreate3d(PetscObjectComm((PetscObject)source), bx, by, bz, stencil_type,
106 M, N, P, m, n, p, dof, stencil_width, lx, ly, lz, result); CHKERRQ(ierr);
107 ierr = DMSetUp(*result); CHKERRQ(ierr);
109 "Created a dof-%d DM mirroring the block decomposition (%dx%dx%d ranks).\n",
110 (int)dof, (int)m, (int)n, (int)p);
112 PetscFunctionReturn(0);
113}
PetscErrorCode PicurvCheckPetscIntRange(MPI_Comm comm, PetscInt64 entries, const char *object)
Refuse a PETSc object whose global size this build's PetscInt cannot index.
Definition setup.c:102
Here is the call graph for this function:
Here is the caller graph for this function:

◆ BalanceCoarsestOwnership()

PetscErrorCode BalanceCoarsestOwnership ( PetscInt  coarse_nodes,
PetscInt  fine_cells,
PetscInt  refinements,
PetscInt  ranks,
PetscInt *  l 
)

Split one axis of the coarsest level so the finest level's owned cells balance.

The finer levels inherit their ownership by refinement (InitializeSingleGridDM): each refinement maps a coarse rank boundary at node c to 2c - 1, so a boundary at coarsest node c lands at finest node 2^R (c - 1) + 1. Refining PETSc's default coarsest split compounds its remainder, e.g. 128 cells on 4 ranks at 3 levels own 33/36/32/27 cells. A rank owns the cells whose lower-corner node it owns, and the last node is padding. Every rank keeps at least PETSc's floor width, so every stencil-width check on the default split still holds, and the spare points go where they minimise the largest finest-level share, by dynamic programming over (rank, spare points used so far): O(ranks x spare^2) once per axis at setup. A rank may take several: unrefined, 128 cells on 4 ranks split 32/32/32/34 nodes, 32 cells each. The share counted is the particles' (GetOwnedCellRange); cell-centred Eulerian storage puts cell c at node c + 1, so it differs by one cell at each end and is not balanced with it (GitHub #21).

Parameters
[in]coarse_nodesCoarsest-level DA points on the axis.
[in]fine_cellsFinest-level physical cells on the axis.
[in]refinementsRefinements of the axis between the coarsest and finest levels.
[in]ranksRanks on the axis.
[out]lCoarsest-level DA points owned by each rank on the axis.
Returns
PetscErrorCode 0 on success, or a PETSc allocation error.

Split one axis of the coarsest level so the finest level's owned cells balance.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/grid.h.

See also
BalanceCoarsestOwnership()

Definition at line 121 of file grid.c.

123{
124 const PetscInt width = coarse_nodes / ranks, extras = coarse_nodes % ranks, cols = extras + 1;
125 PetscInt *worst = NULL; // [r * cols + e]: least largest share over ranks 0..r using e spare points
126 PetscInt *wide = NULL; // [r * cols + e]: how many spare points rank r takes on that optimum
127
128 PetscFunctionBeginUser;
130 PetscCall(PetscMalloc2(ranks * cols, &worst, ranks * cols, &wide));
131 #define PICURV_FINE_NODE(c) ((c) == 0 ? 0 : (refinements ? (((c) - 1) << refinements) + 1 : (c)))
132 for (PetscInt r = 0; r < ranks; ++r) {
133 for (PetscInt e = 0; e < cols; ++e) {
134 worst[r * cols + e] = PETSC_MAX_INT;
135 for (PetscInt w = 0; w <= e; ++w) {
136 const PetscInt before = e - w;
137 if (r == 0 ? before != 0 : worst[(r - 1) * cols + before] == PETSC_MAX_INT) continue;
138 const PetscInt start = PICURV_FINE_NODE(r * width + before);
139 const PetscInt end = (r == ranks - 1) ? fine_cells : PICURV_FINE_NODE((r + 1) * width + e);
140 const PetscInt share = PetscMax(end - start, r ? worst[(r - 1) * cols + before] : 0);
141 if (share < worst[r * cols + e]) { worst[r * cols + e] = share; wide[r * cols + e] = w; }
142 }
143 }
144 }
145 #undef PICURV_FINE_NODE
146 for (PetscInt r = ranks - 1, e = extras; r >= 0; --r) {
147 l[r] = width + wide[r * cols + e];
148 e -= wide[r * cols + e];
149 }
150 PetscCall(PetscFree2(worst, wide));
152 PetscFunctionReturn(0);
153}
#define PICURV_FINE_NODE(c)
Here is the caller graph for this function: