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

Header file for particle location functions using the walking search algorithm. More...

#include <petsc.h>
#include <stdbool.h>
#include <math.h>
#include "variables.h"
#include "logging.h"
#include "setup.h"
Include dependency graph for walkingsearch.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

PetscErrorCode GetCellCharacteristicSize (const Cell *cell, PetscReal *cellSize)
 Estimates a characteristic length of the cell for threshold scaling.
 
PetscErrorCode CalculateDistancesToCellFaces (const Cmpnts p, const Cell *cell, PetscReal *d, const PetscReal threshold, Cmpnts *normals)
 Computes the signed distances from a point to each face of a cubic cell.
 
PetscErrorCode CalculateDistancesToCellFacePlanes (const Cmpnts p, const CellFacePlanes *planes, PetscReal *d, const PetscReal threshold, Cmpnts *normals)
 Signed distances from a point to precomputed cell face planes.
 
PetscErrorCode DeterminePointPosition (PetscReal *d, PetscInt *result)
 Classifies a point based on precomputed face distances.
 
PetscErrorCode InitializeTraversalParameters (UserCtx *user, Particle *particle, PetscInt *idx, PetscInt *idy, PetscInt *idz, PetscInt *traversal_steps)
 Initializes traversal parameters for locating a particle.
 
PetscErrorCode CheckCellWithinLocalGrid (UserCtx *user, PetscInt idx, PetscInt idy, PetscInt idz, PetscBool *is_within)
 Checks if the current cell indices are within the local grid boundaries.
 
PetscErrorCode RetrieveCurrentCell (UserCtx *user, PetscInt idx, PetscInt idy, PetscInt idz, Cell *cell)
 Retrieves the coordinates of the eight vertices of the current cell.
 
PetscErrorCode EvaluateParticlePositionInPlanes (const CellFacePlanes *planes, PetscReal *d, const Cmpnts p, PetscInt *position, const PetscReal threshold)
 Classifies a point against a cell's precomputed face planes.
 
PetscErrorCode FindOwnerOfCell (UserCtx *user, PetscInt i, PetscInt j, PetscInt k, PetscMPIInt *owner_rank)
 Finds the MPI rank that owns a given global cell index.
 
PetscErrorCode ReflectParticleAcrossCellFace (const CellFacePlanes *planes, PetscInt face, Cmpnts *p)
 Mirrors a point about the plane of one face of a cell.
 
PetscErrorCode PlaceParticleInsideCell (const Cell *cell, Cmpnts *p, PetscBool *placed)
 Moves a point to just inside a cell along the segment toward the cell centroid.
 
PetscErrorCode LocateParticleOrFindMigrationTarget (UserCtx *user, const struct FacePlaneArrays *planes, Particle *particle, ParticleLocationStatus *status_out)
 
PetscErrorCode UpdateCellIndicesBasedOnDistances (PetscReal d[NUM_FACES], PetscInt *idx, PetscInt *idy, PetscInt *idz)
 Updates the cell indices based on the signed distances to each face.
 

Detailed Description

Header file for particle location functions using the walking search algorithm.

This file contains declarations of functions that implement the walking search algorithm to locate particles within a computational grid. It includes functions for computing distances to cell faces, determining particle positions relative to cells, and updating traversal parameters.

Definition in file walkingsearch.h.

Function Documentation

◆ GetCellCharacteristicSize()

PetscErrorCode GetCellCharacteristicSize ( const Cell *  cell,
PetscReal *  cellSize 
)

Estimates a characteristic length of the cell for threshold scaling.

For a hexahedral cell with vertices cell->vertices[0..7], we approximate the cell size by some measure—e.g. average edge length or diagonal.

Parameters
[in]cellA pointer to the Cell structure
[out]cellSizeA pointer to a PetscReal where the characteristic size is stored.
Returns
PetscErrorCode 0 on success, non-zero on failure.

Estimates a characteristic length of the cell for threshold scaling.

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

See also
GetCellCharacteristicSize()

Definition at line 30 of file walkingsearch.c.

31{
32 PetscErrorCode ierr = 0;
33 PetscFunctionBeginUser;
35 if (!cell || !cellSize) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
36 "GetCellCharacteristicSize: Null pointer(s).");
37
38 // A simple approach: compute the average of the distances between
39 // all pairs of adjacent vertices that share an edge. That gives
40 // a typical measure of cell dimension. For a uniform grid, you
41 // could do something simpler.
42
43 PetscInt edges[12][2] = {
44 {0,1},{1,2},{2,3},{3,0}, // bottom face edges
45 {4,5},{5,6},{6,7},{7,4}, // top face edges
46 {0,7},{1,6},{2,5},{3,4} // vertical edges
47 };
48
49 PetscReal totalEdgeLen = 0.0;
50 for (PetscInt i=0; i<12; i++) {
51 PetscInt vA = edges[i][0];
52 PetscInt vB = edges[i][1];
53 Cmpnts A = cell->vertices[vA];
54 Cmpnts B = cell->vertices[vB];
55 PetscReal dx = B.x - A.x;
56 PetscReal dy = B.y - A.y;
57 PetscReal dz = B.z - A.z;
58 PetscReal edgeLen = sqrt(dx*dx + dy*dy + dz*dz);
59 totalEdgeLen += edgeLen;
60 }
61
62 // Average edge length
63 *cellSize = totalEdgeLen / 12.0;
64
66 PetscFunctionReturn(ierr);
67}
#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
PetscScalar x
Definition variables.h:145
PetscScalar z
Definition variables.h:145
PetscScalar y
Definition variables.h:145
Cmpnts vertices[8]
Coordinates of the eight vertices of the cell.
Definition variables.h:219
A 3D point or vector with PetscScalar components.
Definition variables.h:144
Here is the caller graph for this function:

◆ CalculateDistancesToCellFaces()

PetscErrorCode CalculateDistancesToCellFaces ( const Cmpnts  p,
const Cell *  cell,
PetscReal *  d,
const PetscReal  threshold,
Cmpnts *  normals 
)

Computes the signed distances from a point to each face of a cubic cell.

This function calculates the signed distances from a specified point p to each of the six faces of a cubic cell. The cell is defined by its eight vertices, and the distances are stored in the memory location pointed to by d.

Parameters
[in]pThe target point in 3D space.
[in]cellPointer to a Cell structure that defines the cubic cell via its vertices.
[out]dA pointer to an array of six PetscReal values where the computed signed distances will be stored.
[in]thresholdA PetscReal value that specifies the minimum distance below which a computed distance is considered to be zero.
[out]normalsOptional, may be NULL: an array of six Cmpnts receiving each face plane's unit outward normal, in the same order as d.
Returns
PetscErrorCode Returns 0 on success, non-zero on failure.

Computes the signed distances from a point to each face of a cubic cell.

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

See also
CalculateDistancesToCellFaces()

Definition at line 113 of file walkingsearch.c.

114{
115 PetscErrorCode ierr;
116 PetscFunctionBeginUser;
118
119 // Validate that the 'cell' pointer is not NULL to prevent dereferencing a null pointer.
120 if (cell == NULL) {
121 LOG_ALLOW(LOCAL,LOG_ERROR, "'cell' is NULL.\n");
122 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "'cell' is NULL.");
123 }
124
125 // Validate that the 'd' pointer is not NULL to ensure there is memory allocated for distance storage.
126 if (d == NULL) {
127 LOG_ALLOW(LOCAL,LOG_ERROR, "'d' is NULL.\n");
128 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "'d' is NULL.");
129 }
130
131 CellFacePlanes planes;
132 MetricBuildCellFacePlanes(cell, &planes);
133 ierr = CalculateDistancesToCellFacePlanes(p, &planes, d, threshold, normals); CHKERRQ(ierr);
134
135 LOG_ALLOW(LOCAL, LOG_DEBUG, "Populated d: "
136 "d[LEFT=%d]=%.3e, d[RIGHT=%d]=%.3e, d[BOTTOM=%d]=%.3e, "
137 "d[TOP=%d]=%.3e, d[FRONT=%d]=%.3e, d[BACK=%d]=%.3e\n",
138 LEFT, d[LEFT], RIGHT, d[RIGHT], BOTTOM, d[BOTTOM],
139 TOP, d[TOP], FRONT, d[FRONT], BACK, d[BACK]);
140 LOG_ALLOW(LOCAL, LOG_DEBUG, "Raw d: "
141 "[%.3e, %.3e, %.3e, %.3e, %.3e, %.3e]\n",
142 d[0], d[1], d[2], d[3], d[4], d[5]);
143
145 PetscFunctionReturn(0); // Indicate successful execution of the function.
146}
void MetricBuildCellFacePlanes(const Cell *cell, CellFacePlanes *planes)
Builds the six face planes of a hexahedron, as the particle search tests them.
Definition Metric.c:108
#define LOCAL
Logging scope definitions for controlling message output.
Definition logging.h:45
#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
@ LOG_ERROR
Critical errors that may halt the program.
Definition logging.h:29
@ LOG_DEBUG
Detailed debugging information.
Definition logging.h:32
@ TOP
Definition variables.h:197
@ FRONT
Definition variables.h:197
@ BOTTOM
Definition variables.h:197
@ BACK
Definition variables.h:197
@ LEFT
Definition variables.h:197
@ RIGHT
Definition variables.h:197
The six face planes of one hexahedron, indexed by Face, and its characteristic size.
Definition variables.h:229
PetscErrorCode CalculateDistancesToCellFacePlanes(const Cmpnts p, const CellFacePlanes *planes, PetscReal *d, const PetscReal threshold, Cmpnts *normals)
Implementation of CalculateDistancesToCellFacePlanes().
Here is the call graph for this function:
Here is the caller graph for this function:

◆ CalculateDistancesToCellFacePlanes()

PetscErrorCode CalculateDistancesToCellFacePlanes ( const Cmpnts  p,
const CellFacePlanes *  planes,
PetscReal *  d,
const PetscReal  threshold,
Cmpnts *  normals 
)

Signed distances from a point to precomputed cell face planes.

Parameters
[in]pThe target point.
[in]planesFace planes from MetricBuildCellFacePlanes().
[out]dSix signed distances, positive inside, indexed by Face; below threshold set to 0.
[in]thresholdAbsolute distance below which a distance is zero.
[out]normalsOptional, may be NULL: each face's unit outward normal, in the order of d.
Returns
PetscErrorCode 0 on success, or PETSC_ERR_USER for a degenerate face; faces are checked in BACK, FRONT, BOTTOM, TOP, LEFT, RIGHT order and the first degenerate one is reported.

Signed distances from a point to precomputed cell face planes.

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

See also
CalculateDistancesToCellFacePlanes()

Definition at line 88 of file walkingsearch.c.

90{
91 // Faces are evaluated in this order, so a degenerate face is reported in it.
92 static const int order[NUM_FACES] = {BACK, FRONT, BOTTOM, TOP, LEFT, RIGHT};
93
94 PetscFunctionBeginUser;
95 for (int n = 0; n < NUM_FACES; ++n) {
96 const FacePlane *plane = &planes->face[order[n]];
97 if (((PetscInt)planes->degenerate >> order[n]) & 1) {
98 LOG_ALLOW(LOCAL, LOG_ERROR, "Degenerate plane detected on face %d (normal magnitude below 1e-12).\n", order[n]);
99 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_USER, "Degenerate plane detected (normal vector is near zero).");
100 }
101 d[order[n]] = FacePlaneDistance(plane, p, threshold);
102 if (normals) normals[order[n]] = plane->normal;
103 }
104 PetscFunctionReturn(0);
105}
Cmpnts normal
Unit outward normal of (v2 - v1) x (v4 - v1); unnormalised when degenerate.
Definition variables.h:224
PetscInt degenerate
Bit f set when face f's normal magnitude is below 1e-12.
Definition variables.h:231
@ NUM_FACES
Definition variables.h:197
FacePlane face[NUM_FACES]
Face planes in LEFT..BACK order.
Definition variables.h:230
One cell face as the particle search tests against it: a plane through the vertex mean.
Definition variables.h:223
static PetscReal FacePlaneDistance(const FacePlane *plane, const Cmpnts p, const PetscReal threshold)
Signed distance from p to a face plane, positive on the cell side, zeroed below threshold.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ DeterminePointPosition()

PetscErrorCode DeterminePointPosition ( PetscReal *  d,
PetscInt *  result 
)

Classifies a point based on precomputed face distances.

Given an array of six distances d[NUM_FACES] from the point to each face of a hexahedral cell, this function determines: 0 => inside 1 => on a single face 2 => on an edge (2 faces = 0) 3 => on a corner (3+ faces = 0) -1 => outside

Parameters
[in]dArray of six face distances.
[out]resultPointer to an integer classification: {0,1,2,3,-1}.
Returns
PetscErrorCode Returns 0 on success, non-zero on failure.

Classifies a point based on precomputed face distances.

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

See also
DeterminePointPosition()

Definition at line 154 of file walkingsearch.c.

155{
156
157 PetscFunctionBeginUser;
159 // Validate input pointers
160 if (d == NULL) {
161 LOG_ALLOW(LOCAL,LOG_ERROR, "'d' is NULL.\n");
162 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Input parameter 'd' is NULL.");
163 }
164 if (result == NULL) {
165 LOG_ALLOW(LOCAL,LOG_ERROR, "'result' is NULL.\n");
166 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Output parameter 'result' is NULL.");
167 }
168
169 // Initialize flags
170 PetscBool isInside = PETSC_TRUE;
171 PetscBool isOnBoundary = PETSC_FALSE;
172 PetscInt IntersectionCount = 0; // Counts the number of intersections of the point with various planes of the cell.
173
174 // Analyze distances to determine position
175 for(int i = 0; i < NUM_FACES; i++) {
176 if(d[i] < 0.0) {
177 isInside = PETSC_FALSE; // Point is outside in at least one direction
178 }
179 if(d[i] == 0.0) {
180 isOnBoundary = PETSC_TRUE; // Point is exactly at least one face
181 IntersectionCount++;
182 }
183 }
184
185 // Set the result based on flags
186 if(isInside && isOnBoundary) {
187 if(IntersectionCount == 1){
188 *result = 1; // on face
189 }
190 else if(IntersectionCount == 2){
191 *result = 2; // on edge
192 }
193 else if(IntersectionCount >= 3){
194 *result = 3; // on corner
195 }
196 }
197 else if(isInside) {
198 *result = 0; // Inside the cell
199 }
200 else {
201 *result = -1; // Outside the cell
202 }
203
205 PetscFunctionReturn(0); // Indicate successful execution
206}
Here is the caller graph for this function:

◆ InitializeTraversalParameters()

PetscErrorCode InitializeTraversalParameters ( UserCtx *  user,
Particle *  particle,
PetscInt *  idx,
PetscInt *  idy,
PetscInt *  idz,
PetscInt *  traversal_steps 
)

Initializes traversal parameters for locating a particle.

This function sets the initial cell indices based on the local grid boundaries and initializes the traversal step counter.

Parameters
[in]userPointer to the user-defined context containing grid information.
[in]particlePointer to the Particle structure containing its location.
[out]idxPointer to store the initial i-index of the cell.
[out]idyPointer to store the initial j-index of the cell.
[out]idzPointer to store the initial k-index of the cell.
[out]traversal_stepsPointer to store the initial traversal step count.
Returns
PetscErrorCode Returns 0 on success, non-zero on failure.

Initializes traversal parameters for locating a particle.

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

See also
InitializeTraversalParameters()

Definition at line 214 of file walkingsearch.c.

215{
216 PetscErrorCode ierr;
217 const DMDALocalInfo *info;
218
219 PetscFunctionBeginUser;
221
222 // Validate input pointers
223 if (user == NULL || particle == NULL || idx == NULL || idy == NULL || idz == NULL || traversal_steps == NULL) {
224 LOG_ALLOW(LOCAL,LOG_ERROR, "One or more input pointers are NULL.\n");
225 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "One or more input pointers are NULL.");
226 }
227
228 // Grid information stored at setup (the decomposition never changes), for the fallback start.
229 info = &user->info;
230
231 // --- Check if the particle has a valid previous cell ID ---
232 // Assuming particle->cell stores the *global* indices
233 if (particle->cell[0] >= 0 && particle->cell[1] >= 0 && particle->cell[2] >= 0) {
234
235 // It sees a valid cell ID exists.
236 // Before using it, it explicitly checks if this cell is accessible.
237 PetscBool is_handoff_cell_valid;
238 ierr = CheckCellWithinLocalGrid(user, particle->cell[0], particle->cell[1], particle->cell[2], &is_handoff_cell_valid); CHKERRQ(ierr);
239
240 if (is_handoff_cell_valid) {
241 // FAST PATH: The check passed. The cell is safe. Use it.
242 *idx = particle->cell[0];
243 *idy = particle->cell[1];
244 *idz = particle->cell[2];
245
246 } else {
247 // SAFE FALLBACK: The check failed! The handoff cell is NOT safe.
248 // Discard the unsafe handoff cell and revert to starting at the
249 // guaranteed-safe local corner.
250 *idx = info->xs;
251 *idy = info->ys;
252 *idz = info->zs;
253 }
254 } else {
255 // No valid previous cell ID (e.g., -1,-1,-1 or first time).
256 // Sample the 6 face centers + volume center (7 total candidates) and start from the closest.
257
258 Cmpnts ***cent;
259
260 // Get local cell center array (lCent)
261 // For cell (i,j,k), the center is at cent[k+1][j+1][i+1]
262 ierr = DMDAVecGetArrayRead(user->fda, user->lCent, &cent); CHKERRQ(ierr);
263
264 // Define 7 strategic sampling points: 6 face centers + 1 volume center
265 PetscInt candidates[7][3];
266 const char* candidate_names[7] = {"X-min face", "X-max face", "Y-min face",
267 "Y-max face", "Z-min face", "Z-max face", "Volume center"};
268
269 // Calculate middle indices for each dimension
270 PetscInt mid_i = info->xs + (info->xm - 1) / 2;
271 PetscInt mid_j = info->ys + (info->ym - 1) / 2;
272 PetscInt mid_k = info->zs + (info->zm - 1) / 2;
273 PetscInt max_i = info->xs + info->xm - 2;
274 PetscInt max_j = info->ys + info->ym - 2;
275 PetscInt max_k = info->zs + info->zm - 2;
276
277 // Clamp max indices to ensure valid cells
278 if (max_i < info->xs) max_i = info->xs;
279 if (max_j < info->ys) max_j = info->ys;
280 if (max_k < info->zs) max_k = info->zs;
281
282 // X-min face center (i=min, j=mid, k=mid)
283 candidates[0][0] = info->xs; candidates[0][1] = mid_j; candidates[0][2] = mid_k;
284 // X-max face center (i=max, j=mid, k=mid)
285 candidates[1][0] = max_i; candidates[1][1] = mid_j; candidates[1][2] = mid_k;
286 // Y-min face center (i=mid, j=min, k=mid)
287 candidates[2][0] = mid_i; candidates[2][1] = info->ys; candidates[2][2] = mid_k;
288 // Y-max face center (i=mid, j=max, k=mid)
289 candidates[3][0] = mid_i; candidates[3][1] = max_j; candidates[3][2] = mid_k;
290 // Z-min face center (i=mid, j=mid, k=min)
291 candidates[4][0] = mid_i; candidates[4][1] = mid_j; candidates[4][2] = info->zs;
292 // Z-max face center (i=mid, j=mid, k=max)
293 candidates[5][0] = mid_i; candidates[5][1] = mid_j; candidates[5][2] = max_k;
294 // Volume center (i=mid, j=mid, k=mid)
295 candidates[6][0] = mid_i; candidates[6][1] = mid_j; candidates[6][2] = mid_k;
296
297 // Find the closest candidate cell
298 PetscReal min_distance = PETSC_MAX_REAL;
299 PetscInt best_candidate = 6; // Default to volume center
300
301 for (PetscInt i = 0; i < 7; i++) {
302 PetscInt ci = candidates[i][0];
303 PetscInt cj = candidates[i][1];
304 PetscInt ck = candidates[i][2];
305
306 // Get cell center coordinates: cent[k+1][j+1][i+1] for cell (i,j,k)
307 Cmpnts cell_center = cent[ck+1][cj+1][ci+1];
308
309 // Calculate Euclidean distance from particle to cell center
310 PetscReal dx = particle->loc.x - cell_center.x;
311 PetscReal dy = particle->loc.y - cell_center.y;
312 PetscReal dz = particle->loc.z - cell_center.z;
313 PetscReal distance = sqrt(dx*dx + dy*dy + dz*dz);
314
315 if (distance < min_distance) {
316 min_distance = distance;
317 best_candidate = i;
318 *idx = ci;
319 *idy = cj;
320 *idz = ck;
321 }
322 }
323
324 // Restore array
325 ierr = DMDAVecRestoreArrayRead(user->fda, user->lCent, &cent); CHKERRQ(ierr);
326
327 LOG_PARTICLE(user->simCtx, particle->PID, "locate",
328 "no prior cell: walk starts at the %s seed cell (%" PetscInt_FMT ",%" PetscInt_FMT ",%" PetscInt_FMT "), %.3e from the particle\n",
329 candidate_names[best_candidate], *idx, *idy, *idz, min_distance);
330 }
331
332 // Initialize traversal step counter
333 *traversal_steps = 0;
334
336 PetscFunctionReturn(0);
337}
#define LOG_PARTICLE(simCtx, pid, stage, fmt,...)
Reports one particle at one stage of a step: the consolidated per-particle line.
Definition logging.h:355
Vec lCent
Definition variables.h:1244
PetscInt cell[3]
Definition variables.h:238
SimCtx * simCtx
Back-pointer to the master simulation context.
Definition variables.h:1160
Cmpnts loc
Definition variables.h:239
DMDALocalInfo info
Definition variables.h:1169
PetscInt64 PID
Definition variables.h:237
PetscErrorCode CheckCellWithinLocalGrid(UserCtx *user, PetscInt idx, PetscInt idy, PetscInt idz, PetscBool *is_within)
Implementation of CheckCellWithinLocalGrid().
Here is the call graph for this function:
Here is the caller graph for this function:

◆ CheckCellWithinLocalGrid()

PetscErrorCode CheckCellWithinLocalGrid ( UserCtx *  user,
PetscInt  idx,
PetscInt  idy,
PetscInt  idz,
PetscBool *  is_within 
)

Checks if the current cell indices are within the local grid boundaries.

Parameters
[in]userPointer to the user-defined context containing grid information.
[in]idxThe i-index of the current cell.
[in]idyThe j-index of the current cell.
[in]idzThe k-index of the current cell.
[out]is_withinPointer to a PetscBool that will be set to PETSC_TRUE if within bounds, else PETSC_FALSE.
Returns
PetscErrorCode Returns 0 on success, non-zero on failure.

Checks if the current cell indices are within the local grid boundaries.

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

See also
CheckCellWithinLocalGrid()

Definition at line 346 of file walkingsearch.c.

347{
348 const DMDALocalInfo *info_nodes; // Node decomposition, shared by user->da and user->fda
349
350 PetscFunctionBeginUser; // Assuming this is part of your PETSc style
352
353 // Validate inputs
354 if (user == NULL || is_within == NULL) {
355 LOG_ALLOW(LOCAL, LOG_ERROR, "Input pointer is NULL.\n");
356 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Input pointer is NULL in CheckCellWithinLocalGrid.");
357 }
358
359 // Ghosted node ranges stored at grid setup; user->fda is built compatible with user->da, so
360 // they are its ranges too.
361 info_nodes = &user->info;
362
363 // Determine the range of GLOBAL CELL INDICES that are covered by this rank's ghosted NODAL region.
364 // A cell C(i,j,k) has origin node N(i,j,k).
365 // The ghosted nodal region starts at global node index info_nodes->gxs and has info_nodes->gxm nodes.
366
367 // Global starting index of the first cell whose origin node is within the ghosted nodal region.
368 PetscInt gxs_cell_global_start = info_nodes->gxs;
369 PetscInt gys_cell_global_start = info_nodes->gys;
370 PetscInt gzs_cell_global_start = info_nodes->gzs;
371
372 // Number of cells that can be formed starting from nodes within the ghosted nodal region.
373 // If there are N ghosted nodes (info_nodes->gxm), they can be origins for N-1 cells.
374 PetscInt gxm_cell_local_count = (info_nodes->gxm > 0) ? info_nodes->gxm - 1 : 0;
375 PetscInt gym_cell_local_count = (info_nodes->gym > 0) ? info_nodes->gym - 1 : 0;
376 PetscInt gzm_cell_local_count = (info_nodes->gzm > 0) ? info_nodes->gzm - 1 : 0;
377
378 // Global exclusive end index for cells whose origins are in the ghosted nodal region.
379 PetscInt gxe_cell_global_end_exclusive = gxs_cell_global_start + gxm_cell_local_count;
380 PetscInt gye_cell_global_end_exclusive = gys_cell_global_start + gym_cell_local_count;
381 PetscInt gze_cell_global_end_exclusive = gzs_cell_global_start + gzm_cell_local_count;
382
383 // Check if the given global cell index (idx, idy, idz) falls within this range.
384 // This means the origin node of cell (idx,idy,idz) is within the rank's accessible ghosted node region,
385 // and that node can indeed serve as a cell origin (i.e., it's not the very last node in the ghosted region).
386 if (idx >= gxs_cell_global_start && idx < gxe_cell_global_end_exclusive &&
387 idy >= gys_cell_global_start && idy < gye_cell_global_end_exclusive &&
388 idz >= gzs_cell_global_start && idz < gze_cell_global_end_exclusive) {
389 *is_within = PETSC_TRUE;
390 } else {
391 *is_within = PETSC_FALSE;
392 }
393
395 PetscFunctionReturn(0);
396}
Here is the caller graph for this function:

◆ RetrieveCurrentCell()

PetscErrorCode RetrieveCurrentCell ( UserCtx *  user,
PetscInt  idx,
PetscInt  idy,
PetscInt  idz,
Cell *  cell 
)

Retrieves the coordinates of the eight vertices of the current cell.

Vertices 0 to 7 are the nodes (i,j,k), (i+1,j,k), (i+1,j+1,k), (i,j+1,k), (i,j+1,k+1), (i+1,j+1,k+1), (i+1,j,k+1) and (i,j,k+1) of cell (i,j,k) = (idx,idy,idz), the order MetricBuildCellFacePlanes() reads.

Parameters
[in]userPointer to the user-defined context containing grid information.
[in]idxThe i-index of the current cell.
[in]idyThe j-index of the current cell.
[in]idzThe k-index of the current cell.
[out]cellPointer to a Cell structure to store the cell's vertices.
Returns
PetscErrorCode Returns 0 on success, non-zero on failure.

Retrieves the coordinates of the eight vertices of the current cell.

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

See also
RetrieveCurrentCell()

Definition at line 404 of file walkingsearch.c.

405{
406 PetscErrorCode ierr;
407 Vec Coor;
408 const PetscScalar *coor_flat;
409 PetscInt gxs, gys, gzs, gxm, gym;
410
411 PetscFunctionBeginUser;
413
414 // Validate input pointers
415 if (user == NULL || cell == NULL) {
416 LOG_ALLOW(LOCAL,LOG_ERROR, "One or more input pointers are NULL.\n");
417 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "One or more input pointers are NULL.");
418 }
419
420 // Called once per walk step per particle, so read the ghosted local coordinates as a flat
421 // array: DMDAVecGetArrayRead would rebuild a pointer array over the whole local grid on
422 // every call. The indices are ghosted global node indices, as for that 3D view.
423 Coor = user->lCoor;
424 gxs = user->info.gxs; gys = user->info.gys; gzs = user->info.gzs; // fda shares da's decomposition
425 gxm = user->info.gxm; gym = user->info.gym;
426 ierr = VecGetArrayRead(Coor, &coor_flat); CHKERRQ(ierr);
427 {
428 const Cmpnts *coor = (const Cmpnts *)coor_flat;
429#define PICURV_NODE(i, j, k) coor[(((k) - gzs) * gym + ((j) - gys)) * gxm + ((i) - gxs)]
430 // Vertex numbering documented with RetrieveCurrentCell() in walkingsearch.h.
431 cell->vertices[0] = PICURV_NODE(idx, idy, idz);
432 cell->vertices[1] = PICURV_NODE(idx + 1, idy, idz);
433 cell->vertices[2] = PICURV_NODE(idx + 1, idy + 1, idz);
434 cell->vertices[3] = PICURV_NODE(idx, idy + 1, idz);
435 cell->vertices[4] = PICURV_NODE(idx, idy + 1, idz + 1);
436 cell->vertices[5] = PICURV_NODE(idx + 1, idy + 1, idz + 1);
437 cell->vertices[6] = PICURV_NODE(idx + 1, idy, idz + 1);
438 cell->vertices[7] = PICURV_NODE(idx, idy, idz + 1);
439#undef PICURV_NODE
440 }
441 ierr = VecRestoreArrayRead(Coor, &coor_flat); CHKERRQ(ierr);
442
444 PetscFunctionReturn(0);
445}
Vec lCoor
Definition variables.h:1243
#define PICURV_NODE(i, j, k)
Here is the caller graph for this function:

◆ EvaluateParticlePositionInPlanes()

PetscErrorCode EvaluateParticlePositionInPlanes ( const CellFacePlanes *  planes,
PetscReal *  d,
const Cmpnts  p,
PetscInt *  position,
const PetscReal  threshold 
)

Classifies a point against a cell's precomputed face planes.

Computes the signed distances to the six face planes, zeroing those below threshold * planes->size, then classifies them with DeterminePointPosition().

Parameters
[in]planesFace planes with size set, e.g. from MetricGatherCellFacePlanes().
[out]dSix signed face distances, thresholded at threshold * planes->size.
[in]pThe particle position.
[out]position0 inside, 1 to 3 on a face, edge or corner, -1 outside.
[in]thresholdBase threshold, scaled by the cell size.
Returns
PetscErrorCode 0 on success, or PETSC_ERR_USER for a degenerate face.

Classifies a point against a cell's precomputed face planes.

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

See also
EvaluateParticlePositionInPlanes()

Definition at line 453 of file walkingsearch.c.

455{
456 PetscErrorCode ierr;
457
458 PetscFunctionBeginUser;
460 // Scale the base threshold by the cell size (threshold 1e-6 in a 0.01 cell is 1e-8).
461 ierr = CalculateDistancesToCellFacePlanes(p, planes, d, threshold * planes->size, NULL); CHKERRQ(ierr);
462 // 0 inside, 1 (2 or 3) on a face (edge or corner), -1 outside.
463 ierr = DeterminePointPosition(d, position); CHKERRQ(ierr);
465 PetscFunctionReturn(0);
466}
PetscReal size
Mean edge length (GetCellCharacteristicSize()); 0 where unused.
Definition variables.h:232
PetscErrorCode DeterminePointPosition(PetscReal *d, PetscInt *result)
Implementation of DeterminePointPosition().
Here is the call graph for this function:
Here is the caller graph for this function:

◆ FindOwnerOfCell()

PetscErrorCode FindOwnerOfCell ( UserCtx *  user,
PetscInt  i,
PetscInt  j,
PetscInt  k,
PetscMPIInt *  owner_rank 
)

Finds the MPI rank that owns a given global cell index.

The DMDA decomposition is a tensor product of per-axis ranges, with rank i + m (j + n k) on process grid m x n x p, so the owner is found by a binary search of the range starts along each axis in the pre-computed decomposition map (user->RankCellInfoMap): O(log m + log n + log p), not O(ranks). It is the definitive method for resolving cell ownership in the "Walk and Handoff" migration algorithm.

If the provided indices are outside the range of any rank (e.g., negative or beyond the global domain), the function will not find an owner and owner_rank will be set to -1.

Parameters
[in]userPointer to the UserCtx structure, which must contain the initialized RankCellInfoMap and num_ranks.
[in]iGlobal i-index of the cell to find.
[in]jGlobal j-index of the cell to find.
[in]kGlobal k-index of the cell to find.
[out]owner_rankPointer to a PetscMPIInt where the resulting owner rank will be stored. It is set to -1 if no owner is found.
Returns
PetscErrorCode 0 on success, or a non-zero PETSc error code on failure.

Finds the MPI rank that owns a given global cell index.

See also
FindOwnerOfCell()

Definition at line 538 of file walkingsearch.c.

539{
540 PetscFunctionBeginUser;
541
543
544 // --- 1. Input Validation ---
545 if (!user || !user->RankCellInfoMap) {
546 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "UserCtx or RankCellInfoMap is not initialized in FindOwnerOfCell.");
547 }
548 if (!owner_rank) {
549 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Output pointer owner_rank is NULL in FindOwnerOfCell.");
550 }
551
552 // --- 2. Binary Search of the Range Starts Along Each Axis ---
553 // Rank i + m (j + n k) owns process-grid slot (i, j, k); the axis-a starts are those of the
554 // ranks one stride apart from rank 0. Starts are node starts and strictly increase.
555 const PetscInt *procs = user->RankCellInfoProcs;
556 const PetscInt cell[3] = {i, j, k};
557 const PetscInt stride[3] = {1, procs[0], procs[0] * procs[1]};
558 const RankCellInfo *map = user->RankCellInfoMap;
559 PetscInt slot[3];
560 *owner_rank = -1;
561 for (PetscInt a = 0; a < 3; ++a) {
562 PetscInt lo = 0, hi = procs[a] - 1; // Last slot whose start is <= cell[a]
563 while (lo < hi) {
564 const PetscInt mid = (lo + hi + 1) / 2;
565 const RankCellInfo *info = &map[mid * stride[a]];
566 if (((a == 0) ? info->xs_cell : (a == 1) ? info->ys_cell : info->zs_cell) <= cell[a]) lo = mid;
567 else hi = mid - 1;
568 }
569 slot[a] = lo;
570 }
571 const PetscInt r = slot[0] + procs[0] * (slot[1] + procs[1] * slot[2]);
572 const RankCellInfo *info = &map[r];
573 // A rank owns a cell if the cell's index is within its start (inclusive)
574 // and end (exclusive) range for all three dimensions.
575 if ((i >= info->xs_cell && i < info->xs_cell + info->xm_cell) &&
576 (j >= info->ys_cell && j < info->ys_cell + info->ym_cell) &&
577 (k >= info->zs_cell && k < info->zs_cell + info->zm_cell)) *owner_rank = (PetscMPIInt)r;
578
580 PetscFunctionReturn(0);
581}
PetscInt xs_cell
Definition variables.h:264
PetscInt RankCellInfoProcs[3]
DMDA process grid (m, n, p) of RankCellInfoMap: rank i + m (j + n k).
Definition variables.h:1275
RankCellInfo * RankCellInfoMap
Definition variables.h:1274
A lean struct to hold the global cell ownership range for a single MPI rank.
Definition variables.h:263
Here is the caller graph for this function:

◆ ReflectParticleAcrossCellFace()

PetscErrorCode ReflectParticleAcrossCellFace ( const CellFacePlanes *  planes,
PetscInt  face,
Cmpnts *  p 
)

Mirrors a point about the plane of one face of a cell.

The plane is the one the walking search tested the point against, so a point outside the face by |d| ends inside it by |d|: p' = p + 2 d n, with d < 0 outside. Only the position changes.

Parameters
[in]planesThe cell's face planes (MetricGatherCellFacePlanes() or MetricBuildCellFacePlanes()).
[in]faceThe face index (LEFT, RIGHT, BOTTOM, TOP, FRONT or BACK).
[in,out]pThe point to mirror.
Returns
PetscErrorCode 0 on success, or a non-zero PETSc error code (including a degenerate face).

Mirrors a point about the plane of one face of a cell.

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

See also
ReflectParticleAcrossCellFace()

Definition at line 589 of file walkingsearch.c.

590{
591 PetscErrorCode ierr;
592 PetscReal d[NUM_FACES];
593 Cmpnts n[NUM_FACES];
594
595 PetscFunctionBeginUser;
597 if (!planes || !p) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Planes and point must not be NULL.");
598 if (face < 0 || face >= NUM_FACES) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Face %" PetscInt_FMT " is not a cell face.", face);
599
600 // Mirror about the face plane: d < 0 outside and n points outward, so p + 2 d n is the image.
601 ierr = CalculateDistancesToCellFacePlanes(*p, planes, d, 0.0, n); CHKERRQ(ierr);
602 LOG_ALLOW(LOCAL, LOG_VERBOSE, "Mirror about face %" PetscInt_FMT ": d = %.6e, n = (%.6e, %.6e, %.6e).\n", face, d[face], n[face].x, n[face].y, n[face].z);
603 p->x += 2.0 * d[face] * n[face].x;
604 p->y += 2.0 * d[face] * n[face].y;
605 p->z += 2.0 * d[face] * n[face].z;
606
608 PetscFunctionReturn(0);
609}
@ 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:

◆ PlaceParticleInsideCell()

PetscErrorCode PlaceParticleInsideCell ( const Cell *  cell,
Cmpnts *  p,
PetscBool *  placed 
)

Moves a point to just inside a cell along the segment toward the cell centroid.

The terminal action when reflections reach their cap. Plane distances are linear along the segment, so the entry parameter is the largest d_p / (d_p - d_c) over the faces the point is outside of; the point is placed a relative 1e-6 of the remaining segment beyond it.

Parameters
[in]cellThe cell to place the point in.
[in,out]pThe point; unchanged when it cannot be placed.
[out]placedPETSC_FALSE when the centroid is not inside every face plane the point is outside of (a cell warped that far), in which case p is unchanged.
Returns
PetscErrorCode 0 on success, or a non-zero PETSc error code on failure.

Moves a point to just inside a cell along the segment toward the cell centroid.

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

See also
PlaceParticleInsideCell()

Definition at line 617 of file walkingsearch.c.

618{
619 PetscErrorCode ierr;
620 PetscReal dp[NUM_FACES], dc[NUM_FACES];
621 Cmpnts c = {0.0, 0.0, 0.0};
622 PetscReal t = 0.0;
623
624 PetscFunctionBeginUser;
626 if (!cell || !p || !placed) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Cell, point and output flag must not be NULL.");
627 *placed = PETSC_FALSE;
628 for (int v = 0; v < 8; ++v) {
629 c.x += cell->vertices[v].x / 8.0;
630 c.y += cell->vertices[v].y / 8.0;
631 c.z += cell->vertices[v].z / 8.0;
632 }
633 ierr = CalculateDistancesToCellFaces(*p, cell, dp, 0.0, NULL); CHKERRQ(ierr);
634 ierr = CalculateDistancesToCellFaces(c, cell, dc, 0.0, NULL); CHKERRQ(ierr);
635
636 // Plane distance is linear along p + s (c - p); the segment enters the cell at the largest
637 // crossing parameter over the faces p is outside of. It needs the centroid inside every plane.
638 for (PetscInt f = 0; f < NUM_FACES; ++f) {
639 if (dp[f] >= 0.0) continue;
640 if (dc[f] <= 0.0) {
641 LOG_ALLOW(LOCAL, LOG_DEBUG, "Cell centroid is not inside face %" PetscInt_FMT "'s plane (d = %.3e); cannot place the particle.\n", f, dc[f]);
643 PetscFunctionReturn(0);
644 }
645 t = PetscMax(t, dp[f] / (dp[f] - dc[f]));
646 }
647 t += 1.0e-6 * (1.0 - t); // Just inside, not on, the entry face
648 LOG_ALLOW(LOCAL, LOG_VERBOSE, "Placing particle at segment parameter %.6e toward the cell centroid.\n", t);
649 p->x += t * (c.x - p->x);
650 p->y += t * (c.y - p->y);
651 p->z += t * (c.z - p->z);
652 *placed = PETSC_TRUE;
653
655 PetscFunctionReturn(0);
656}
PetscErrorCode CalculateDistancesToCellFaces(const Cmpnts p, const Cell *cell, PetscReal *d, const PetscReal threshold, Cmpnts *normals)
Implementation of CalculateDistancesToCellFaces().
Here is the call graph for this function:
Here is the caller graph for this function:

◆ LocateParticleOrFindMigrationTarget()

PetscErrorCode LocateParticleOrFindMigrationTarget ( UserCtx *  user,
const struct FacePlaneArrays *  planes,
Particle *  particle,
ParticleLocationStatus *  status_out 
)
Here is the caller graph for this function:

◆ UpdateCellIndicesBasedOnDistances()

PetscErrorCode UpdateCellIndicesBasedOnDistances ( PetscReal  d[NUM_FACES],
PetscInt *  idx,
PetscInt *  idy,
PetscInt *  idz 
)

Updates the cell indices based on the signed distances to each face.

This function modifies the cell indices (idx, idy, idz) to move towards the direction where the particle is likely to be located, based on positive distances indicating that the particle is outside in that particular direction.

Parameters
[in]dAn array of six PetscReal values representing the signed distances to each face:
  • d[LEFT]: Left Face
  • d[RIGHT]: Right Face
  • d[BOTTOM]: Bottom Face
  • d[TOP]: Top Face
  • d[FRONT]: Front Face
  • d[BACK]: Back Face
[out]idxPointer to the i-index of the cell to be updated.
[out]idyPointer to the j-index of the cell to be updated.
[out]idzPointer to the k-index of the cell to be updated.
Returns
PetscErrorCode Returns 0 on success, non-zero on failure.

Updates the cell indices based on the signed distances to each face.

See also
UpdateCellIndicesBasedOnDistances()

Definition at line 472 of file walkingsearch.c.

473{
474
475 PetscFunctionBeginUser;
477 /*
478 PetscInt cxm,cxs; // maximum & minimum cell ID in x
479 PetscInt cym,cys; // maximum & minimum cell ID in y
480 PetscInt czm,czs; // maximum & minimum cell ID in z
481
482 cxs = info->xs; cxm = cxs + info->xm - 2;
483 cys = info->ys; cym = cys + info->ym - 2;
484 czs = info->zs; czm = czs + info->zm - 2;
485 */
486
487 // Validate input pointers
488 if (d == NULL) {
489 LOG_ALLOW(LOCAL,LOG_ERROR, "'d' is NULL.\n");
490 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Input array 'd' is NULL.");
491 }
492 if (idx == NULL || idy == NULL || idz == NULL) {
493 LOG_ALLOW(LOCAL,LOG_ERROR, "One or more index pointers are NULL.\n");
494 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "One or more index pointers are NULL.");
495 }
496
497 // Update k-direction based on FRONT and BACK distances
498 if (d[FRONT] < 0.0) {
499 (*idz) += 1;
500 }
501 else if(d[BACK] < 0.0){
502 (*idz) -= 1;
503 }
504
505 // Update i-direction based on LEFT and RIGHT distances
506 if (d[LEFT] < 0.0) {
507 (*idx) -= 1;
508 }
509 else if (d[RIGHT] < 0.0) {
510 (*idx) += 1;
511 }
512
513 // Update j-direction based on BOTTOM and TOP distances
514 if (d[BOTTOM] < 0.0) {
515 (*idy) -= 1;
516 }
517 else if (d[TOP] < 0.0) {
518 (*idy) += 1;
519 }
520
521 /*
522 // The 'cell' corners you can reference go from [xs .. xs+xm-1], but
523 // to form a valid cell in x, you need (idx+1) in range, so max is (xs+xm-2).
524 *idx = PetscMax(cxs, PetscMin(*idx, cxm));
525 *idy = PetscMax(cys, PetscMin(*idy, cym));
526 *idz = PetscMax(czs, PetscMin(*idz, czm));
527 */
528
530 PetscFunctionReturn(0); // Indicate successful execution
531}
Here is the caller graph for this function: