PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
Macros | Functions | Variables
walkingsearch.c File Reference
#include "walkingsearch.h"
#include "Metric.h"
#include "logging.h"
#include <petsc.h>
#include <stdbool.h>
#include <math.h>
Include dependency graph for walkingsearch.c:

Go to the source code of this file.

Macros

#define MAX_TRAVERSAL   1000
 
#define DISTANCE_THRESHOLD   1e-11
 
#define REPEAT_COUNT_THRESHOLD   5
 
#define BLOCKED_WALK_GUARD_CELLS   3.0
 
#define REFLECTION_CAP   4
 
#define PICURV_NODE(i, j, k)   coor[(((k) - gzs) * gym + ((j) - gys)) * gxm + ((i) - gxs)]
 

Functions

PetscErrorCode GetCellCharacteristicSize (const Cell *cell, PetscReal *cellSize)
 Implementation of GetCellCharacteristicSize().
 
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.
 
PetscErrorCode CalculateDistancesToCellFacePlanes (const Cmpnts p, const CellFacePlanes *planes, PetscReal *d, const PetscReal threshold, Cmpnts *normals)
 Implementation of CalculateDistancesToCellFacePlanes().
 
PetscErrorCode CalculateDistancesToCellFaces (const Cmpnts p, const Cell *cell, PetscReal *d, const PetscReal threshold, Cmpnts *normals)
 Implementation of CalculateDistancesToCellFaces().
 
PetscErrorCode DeterminePointPosition (PetscReal *d, PetscInt *result)
 Implementation of DeterminePointPosition().
 
PetscErrorCode InitializeTraversalParameters (UserCtx *user, Particle *particle, PetscInt *idx, PetscInt *idy, PetscInt *idz, PetscInt *traversal_steps)
 Implementation of InitializeTraversalParameters().
 
PetscErrorCode CheckCellWithinLocalGrid (UserCtx *user, PetscInt idx, PetscInt idy, PetscInt idz, PetscBool *is_within)
 Implementation of CheckCellWithinLocalGrid().
 
PetscErrorCode RetrieveCurrentCell (UserCtx *user, PetscInt idx, PetscInt idy, PetscInt idz, Cell *cell)
 Implementation of RetrieveCurrentCell().
 
PetscErrorCode EvaluateParticlePositionInPlanes (const CellFacePlanes *planes, PetscReal *d, const Cmpnts p, PetscInt *position, const PetscReal threshold)
 Implementation of EvaluateParticlePositionInPlanes().
 
PetscErrorCode UpdateCellIndicesBasedOnDistances (PetscReal d[NUM_FACES], PetscInt *idx, PetscInt *idy, PetscInt *idz)
 Implementation of UpdateCellIndicesBasedOnDistances().
 
PetscErrorCode FindOwnerOfCell (UserCtx *user, PetscInt i, PetscInt j, PetscInt k, PetscMPIInt *owner_rank)
 Implementation of FindOwnerOfCell().
 
PetscErrorCode ReflectParticleAcrossCellFace (const CellFacePlanes *planes, PetscInt face, Cmpnts *p)
 Implementation of ReflectParticleAcrossCellFace().
 
PetscErrorCode PlaceParticleInsideCell (const Cell *cell, Cmpnts *p, PetscBool *placed)
 Implementation of PlaceParticleInsideCell().
 
static void ResetStuckDetection (PetscInt *repeated, PetscInt *prev_i, PetscInt *prev_j, PetscInt *prev_k)
 Forget the cell the stuck-walk detector compared against, after the particle moved without the walk stepping (a wrap, a reflection or the reflection fallback).
 
PetscErrorCode LocateParticleOrFindMigrationTarget (UserCtx *user, const FacePlaneArrays *planes, Particle *particle, ParticleLocationStatus *status_out)
 Implementation of LocateParticleOrFindMigrationTarget().
 

Variables

static const BCFace kCellFaceDomainFace [NUM_FACES]
 

Macro Definition Documentation

◆ MAX_TRAVERSAL

#define MAX_TRAVERSAL   1000

Definition at line 11 of file walkingsearch.c.

◆ DISTANCE_THRESHOLD

#define DISTANCE_THRESHOLD   1e-11

Definition at line 12 of file walkingsearch.c.

◆ REPEAT_COUNT_THRESHOLD

#define REPEAT_COUNT_THRESHOLD   5

Definition at line 13 of file walkingsearch.c.

◆ BLOCKED_WALK_GUARD_CELLS

#define BLOCKED_WALK_GUARD_CELLS   3.0

Definition at line 16 of file walkingsearch.c.

◆ REFLECTION_CAP

#define REFLECTION_CAP   4

Definition at line 18 of file walkingsearch.c.

◆ PICURV_NODE

#define PICURV_NODE (   i,
  j,
  k 
)    coor[(((k) - gzs) * gym + ((j) - gys)) * gxm + ((i) - gxs)]

Function Documentation

◆ GetCellCharacteristicSize()

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

Implementation of GetCellCharacteristicSize().

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:

◆ FacePlaneDistance()

static PetscReal FacePlaneDistance ( const FacePlane *  plane,
const Cmpnts  p,
const PetscReal  threshold 
)
inlinestatic

Signed distance from p to a face plane, positive on the cell side, zeroed below threshold.

Definition at line 73 of file walkingsearch.c.

74{
75 const PetscReal vec_p_to_fc_x = plane->centroid.x - p.x;
76 const PetscReal vec_p_to_fc_y = plane->centroid.y - p.y;
77 const PetscReal vec_p_to_fc_z = plane->centroid.z - p.z;
78 const PetscReal d = vec_p_to_fc_x * plane->normal.x + vec_p_to_fc_y * plane->normal.y + vec_p_to_fc_z * plane->normal.z;
79 return (fabs(d) < threshold) ? 0.0 : d;
80}
Cmpnts normal
Unit outward normal of (v2 - v1) x (v4 - v1); unnormalised when degenerate.
Definition variables.h:224
Cmpnts centroid
Mean of the face's four vertices.
Definition variables.h:225
Here is the caller graph for this function:

◆ CalculateDistancesToCellFacePlanes()

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

Implementation of CalculateDistancesToCellFacePlanes().

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}
#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
PetscInt degenerate
Bit f set when face f's normal magnitude is below 1e-12.
Definition variables.h:231
@ 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
@ NUM_FACES
Definition variables.h:197
@ RIGHT
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:

◆ CalculateDistancesToCellFaces()

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

Implementation of CalculateDistancesToCellFaces().

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
@ LOG_DEBUG
Detailed debugging information.
Definition logging.h:32
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:

◆ DeterminePointPosition()

PetscErrorCode DeterminePointPosition ( PetscReal *  d,
PetscInt *  result 
)

Implementation of DeterminePointPosition().

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 
)

Implementation of InitializeTraversalParameters().

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 
)

Implementation of CheckCellWithinLocalGrid().

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 
)

Implementation of RetrieveCurrentCell().

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 
)

Implementation of EvaluateParticlePositionInPlanes().

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:

◆ UpdateCellIndicesBasedOnDistances()

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

Implementation of UpdateCellIndicesBasedOnDistances().

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:

◆ FindOwnerOfCell()

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

Implementation of FindOwnerOfCell().

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 
)

Implementation of ReflectParticleAcrossCellFace().

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 
)

Implementation of PlaceParticleInsideCell().

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:

◆ ResetStuckDetection()

static void ResetStuckDetection ( PetscInt *  repeated,
PetscInt *  prev_i,
PetscInt *  prev_j,
PetscInt *  prev_k 
)
inlinestatic

Forget the cell the stuck-walk detector compared against, after the particle moved without the walk stepping (a wrap, a reflection or the reflection fallback).

Definition at line 663 of file walkingsearch.c.

664{
665 *repeated = 0;
666 *prev_i = PETSC_MIN_INT; *prev_j = PETSC_MIN_INT; *prev_k = PETSC_MIN_INT;
667}
Here is the caller graph for this function:

◆ LocateParticleOrFindMigrationTarget()

PetscErrorCode LocateParticleOrFindMigrationTarget ( UserCtx *  user,
const FacePlaneArrays *  planes,
Particle *  particle,
ParticleLocationStatus *  status_out 
)

Implementation of LocateParticleOrFindMigrationTarget().

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

See also
LocateParticleOrFindMigrationTarget()

Definition at line 675 of file walkingsearch.c.

679{
680 PetscErrorCode ierr;
681 PetscMPIInt rank;
682
683 // --- Search State Variables ---
684 PetscInt idx, idy, idz; // Current search cell global indices
685 PetscInt traversal_steps; // Counter to prevent infinite loops
686 PetscBool search_concluded = PETSC_FALSE; // Flag to terminate the main while loop
687 PetscBool exited = PETSC_FALSE; // Concluded beyond a domain-boundary face
688 PetscBool blocked = PETSC_FALSE; // Concluded beyond the guard: retry from scratch
689
690 // --- Oscillation/Stuck Loop Detection Variables ---
691 PetscInt repeatedIndexCount = 0;
692 PetscInt prevIdx = PETSC_MIN_INT, prevIdy = PETSC_MIN_INT, prevIdz = PETSC_MIN_INT;
693 PetscInt last_position_result = -999;
694 PetscInt reflections = 0;
695
696 PetscFunctionBeginUser;
698 rank = user->simCtx->rank;
702 }
703
704 // Only a pass-1 walk from the previous-step cell relies on the particle having moved a short
705 // distance; that is the walk a non-convex boundary can block. Every other walk is final.
706 const PetscBool guard_blocked_walk = (PetscBool)(particle->cell[0] >= 0 && user->simCtx->searchMetrics.currentSettlementPass <= 1);
707
708 // --- 1. Initialize the Search ---
709 FacePlaneArrays own_arrays;
710 const FacePlaneArrays *plane_arrays = planes;
711 if (!planes) {
712 ierr = MetricGetFacePlaneArrays(user, PETSC_FALSE, &own_arrays); CHKERRQ(ierr);
713 plane_arrays = &own_arrays;
714 }
715 PetscCheck(!plane_arrays->dual, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "The walk needs the primal face planes, not the dual ones.");
716 ierr = InitializeTraversalParameters(user, particle, &idx, &idy, &idz, &traversal_steps); CHKERRQ(ierr);
717 const PetscInt start_cell[3] = {idx, idy, idz};
718
719 // --- 2. Main Walking Search Loop ---
720 while (!search_concluded && traversal_steps < MAX_TRAVERSAL) {
721 traversal_steps++;
722
723 // --- 2a. GLOBAL Domain Boundary Check ---
724 // Instead of failing when the walk reaches a domain boundary, clamp the indices
725 // to the boundary and continue searching. This allows the search to explore other
726 // directions that might lead to the particle.
727 PetscBool hit_boundary = PETSC_FALSE;
728 if (idx < 0) {
729 idx = 0;
730 hit_boundary = PETSC_TRUE;
732 }
733 if (idx >= (user->IM - 1)) {
734 idx = user->IM - 2;
735 hit_boundary = PETSC_TRUE;
737 }
738 if (idy < 0) {
739 idy = 0;
740 hit_boundary = PETSC_TRUE;
742 }
743 if (idy >= (user->JM - 1)) {
744 idy = user->JM - 2;
745 hit_boundary = PETSC_TRUE;
747 }
748 if (idz < 0) {
749 idz = 0;
750 hit_boundary = PETSC_TRUE;
752 }
753 if (idz >= (user->KM - 1)) {
754 idz = user->KM - 2;
755 hit_boundary = PETSC_TRUE;
757 }
758
759 if (hit_boundary) {
760 LOG_PARTICLE(user->simCtx, particle->PID, "locate", "walk clamped to boundary cell (%" PetscInt_FMT ",%" PetscInt_FMT ",%" PetscInt_FMT ")\n",
761 idx, idy, idz);
762 }
763
764 // --- 2b. LOCAL GHOST REGION CHECK (PREVENTS SEGV) ---
765 // Before trying to access cell data, check if we have it.
766 PetscBool is_cell_local;
767 ierr = CheckCellWithinLocalGrid(user, idx, idy, idz, &is_cell_local); CHKERRQ(ierr);
768 if (!is_cell_local) {
769 // We have walked outside the local rank's ghost region.
770 // This definitively means the particle belongs to another rank.
771 // Conclude the search here; the current (idx,idy,idz) is the handoff cell.
772 LOG_PARTICLE(user->simCtx, particle->PID, "locate", "walk left this rank's ghost region at cell (%" PetscInt_FMT ",%" PetscInt_FMT ",%" PetscInt_FMT "): handoff\n",
773 idx, idy, idz);
774 search_concluded = PETSC_TRUE;
775 continue; // Skip the rest of the loop; proceed to finalization.
776 }
777
778 // --- 2c. Stuck Loop Detection & Enhanced Tie-Breaker ---
779 if (idx == prevIdx && idy == prevIdy && idz == prevIdz) {
780 repeatedIndexCount++;
781 if (repeatedIndexCount > REPEAT_COUNT_THRESHOLD) {
782 // Only apply tie-breaker if we are stuck for the right reason (on a boundary)
783 if (last_position_result >= 1) {
785 // Counted in search_metrics.csv (tie_break_count); a tie-break is a normal outcome.
786 LOG_PARTICLE(user->simCtx, particle->PID, "locate", "stuck on the boundary of cell (%" PetscInt_FMT ",%" PetscInt_FMT ",%" PetscInt_FMT ") for %" PetscInt_FMT " steps: tie-break accepts it\n",
787 idx, idy, idz, repeatedIndexCount);
788
789 // Re-evaluate at the stuck cell to get definitive weights
790 PetscReal final_d[NUM_FACES];
791 PetscInt final_position; // Dummy variable
792
793 CellFacePlanes final_planes;
794 MetricGatherCellFacePlanes(plane_arrays, &user->info, idx, idy, idz, &final_planes);
795 ierr = EvaluateParticlePositionInPlanes(&final_planes, final_d, particle->loc, &final_position, DISTANCE_THRESHOLD);
796
797 if (ierr == 0) { // If evaluation succeeded
798 ierr = UpdateParticleWeights(final_d, particle); CHKERRQ(ierr);
799 search_concluded = PETSC_TRUE; // Conclude search, accepting this cell.
800 } else { // Evaluation failed (e.g., degenerate cell)
801 LOG_ALLOW(LOCAL, LOG_ERROR, "[PID %lld]: Tie-breaker failed during final evaluation at cell (%" PetscInt_FMT ",%" PetscInt_FMT ",%" PetscInt_FMT "). Search fails.\n",
802 (long long)particle->PID, idx, idy, idz);
803 idx = -1; // Invalidate result
804 search_concluded = PETSC_TRUE;
805 }
806 } else { // Stuck for the wrong reason (not on a boundary)
807 LOG_ALLOW(LOCAL, LOG_ERROR, "[PID %lld]: Search is stuck at cell (%" PetscInt_FMT ",%" PetscInt_FMT ",%" PetscInt_FMT ") but not on a boundary. This indicates a logic error. Failing search.\n",
808 (long long)particle->PID, idx, idy, idz);
809 idx = -1; // Invalidate result
810 search_concluded = PETSC_TRUE;
811 }
812 if(search_concluded) continue;
813 }
814 } else {
815 repeatedIndexCount = 0;
816 }
817 prevIdx = idx; prevIdy = idy; prevIdz = idz;
818
819 // --- 2d. Geometric Evaluation ---
820 CellFacePlanes current_planes_storage;
821 MetricGatherCellFacePlanes(plane_arrays, &user->info, idx, idy, idz, &current_planes_storage);
822 const CellFacePlanes *current_planes = &current_planes_storage;
823 PetscReal distances[NUM_FACES];
824 PetscInt position_in_cell;
825
826 ierr = EvaluateParticlePositionInPlanes(current_planes, distances, particle->loc, &position_in_cell, DISTANCE_THRESHOLD); CHKERRQ(ierr);
827 last_position_result = position_in_cell;
828 LOG_PARTICLE(user->simCtx, particle->PID, "locate",
829 "walk step %" PetscInt_FMT " cell (%" PetscInt_FMT ",%" PetscInt_FMT ",%" PetscInt_FMT ") at (%.6e, %.6e, %.6e): position %" PetscInt_FMT " (0 inside, >0 on a face/edge/corner, -1 outside), d L %.3e R %.3e B %.3e T %.3e F %.3e K %.3e\n",
830 traversal_steps, idx, idy, idz, particle->loc.x, particle->loc.y, particle->loc.z, position_in_cell,
831 distances[LEFT], distances[RIGHT], distances[BOTTOM], distances[TOP], distances[FRONT], distances[BACK]);
832
833 // --- 2e. Decision Making ---
834 if (position_in_cell >= 0) { // Particle is INSIDE or ON THE BOUNDARY
835 search_concluded = PETSC_TRUE;
836 ierr = UpdateParticleWeights(distances, particle); CHKERRQ(ierr);
837 } else { // Particle is OUTSIDE
838 // Faces of this cell that lie on the domain boundary, in LEFT, RIGHT, BOTTOM, TOP, FRONT, BACK order.
839 const PetscBool on_domain_face[NUM_FACES] = {idx == 0, idx == user->IM - 2, idy == 0, idy == user->JM - 2,
840 idz == user->KM - 2, idz == 0};
841 PetscInt crossed = -1; // Most negative face, when every negative face lies on the domain boundary
842 for (PetscInt f = 0; f < NUM_FACES; ++f) {
843 if (distances[f] >= 0.0) continue;
844 if (!on_domain_face[f]) { crossed = -1; break; }
845 if (crossed < 0 || distances[f] < distances[crossed]) crossed = f;
846 }
847
848 if (crossed < 0) { // Outside an interior face: keep walking (along the boundary if clamped).
849 ierr = UpdateCellIndicesBasedOnDistances(distances, &idx, &idy, &idz); CHKERRQ(ierr);
850 } else {
851 PetscReal cell_size;
852 PetscBool reflect = PETSC_TRUE; // Every crossed face reflects particles
853 PetscBool wrap = PETSC_FALSE; // Some crossed face is periodic
854 for (PetscInt f = 0; f < NUM_FACES; ++f) {
855 if (distances[f] >= 0.0) continue;
857 if (policy != PARTICLE_BOUNDARY_REFLECT) reflect = PETSC_FALSE;
858 if (policy == PARTICLE_BOUNDARY_WRAP) wrap = PETSC_TRUE;
859 }
860 cell_size = current_planes->size;
861 if (wrap) {
862 // Re-enter through the paired face of every crossed periodic face at once: shift by
863 // each seam translation and move to the cell at the other end of that axis, so an
864 // edge or corner crossing is one handoff when the new cell is not local.
865 for (PetscInt f = 0; f < NUM_FACES; ++f) {
866 const BCFace face = kCellFaceDomainFace[f];
867 if (distances[f] >= 0.0 || user->boundary_faces[face].particle_policy != PARTICLE_BOUNDARY_WRAP) continue;
868 const PetscInt axis = (PetscInt)face / 2;
869 const PetscReal sign = ((PetscInt)face % 2 == 0) ? 1.0 : -1.0; // Beyond the min face: +T
870 const Cmpnts T = user->periodic_translation[axis];
871 PetscCheck(user->periodic_translation_valid[axis], PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE,
872 "Particle wrap on axis %d needs the validated seam translation.", (int)axis);
873 particle->loc.x += sign * T.x;
874 particle->loc.y += sign * T.y;
875 particle->loc.z += sign * T.z;
876 if (axis == 0) idx = (sign > 0.0) ? user->IM - 2 : 0;
877 if (axis == 1) idy = (sign > 0.0) ? user->JM - 2 : 0;
878 if (axis == 2) idz = (sign > 0.0) ? user->KM - 2 : 0;
880 LOG_PARTICLE(user->simCtx, particle->PID, "locate", "wrapped through %s to (%.6e, %.6e, %.6e), cell (%" PetscInt_FMT ",%" PetscInt_FMT ",%" PetscInt_FMT ")\n",
881 BCFaceToString(face), particle->loc.x, particle->loc.y, particle->loc.z, idx, idy, idz);
882 }
883 ResetStuckDetection(&repeatedIndexCount, &prevIdx, &prevIdy, &prevIdz);
884 } else if (guard_blocked_walk && -distances[crossed] > BLOCKED_WALK_GUARD_CELLS * cell_size) {
885 blocked = PETSC_TRUE;
886 search_concluded = PETSC_TRUE;
887 LOG_PARTICLE(user->simCtx, particle->PID, "locate", "%.3e beyond boundary face %" PetscInt_FMT " of cell (%" PetscInt_FMT ",%" PetscInt_FMT ",%" PetscInt_FMT "), above the %.1f-cell guard: walk treated as blocked\n",
888 -distances[crossed], crossed, idx, idy, idz, BLOCKED_WALK_GUARD_CELLS);
889 } else if (!reflect) {
890 exited = PETSC_TRUE;
891 search_concluded = PETSC_TRUE;
892 LOG_PARTICLE(user->simCtx, particle->PID, "locate", "left the domain through boundary face %" PetscInt_FMT " of cell (%" PetscInt_FMT ",%" PetscInt_FMT ",%" PetscInt_FMT "), %.3e beyond it\n",
893 crossed, idx, idy, idz, -distances[crossed]);
894 } else if (reflections < REFLECTION_CAP) {
895 // Mirror about the most-crossed face and evaluate this cell again; an edge or
896 // corner crossing reflects about the next face on the following iteration.
897 ierr = ReflectParticleAcrossCellFace(current_planes, crossed, &particle->loc); CHKERRQ(ierr);
898 reflections++;
900 ResetStuckDetection(&repeatedIndexCount, &prevIdx, &prevIdy, &prevIdz);
901 LOG_PARTICLE(user->simCtx, particle->PID, "locate", "reflected about boundary face %" PetscInt_FMT " of cell (%" PetscInt_FMT ",%" PetscInt_FMT ",%" PetscInt_FMT ") to (%.6e, %.6e, %.6e)\n",
902 crossed, idx, idy, idz, particle->loc.x, particle->loc.y, particle->loc.z);
903 } else {
904 PetscBool placed;
905 Cell current_cell; // The fallback needs the vertices; it runs once per capped walk
906 ierr = RetrieveCurrentCell(user, idx, idy, idz, &current_cell); CHKERRQ(ierr);
907 ierr = PlaceParticleInsideCell(&current_cell, &particle->loc, &placed); CHKERRQ(ierr);
908 if (placed) {
910 ResetStuckDetection(&repeatedIndexCount, &prevIdx, &prevIdy, &prevIdz);
911 LOG_PARTICLE(user->simCtx, particle->PID, "locate", "reflection cap %d reached: placed just inside cell (%" PetscInt_FMT ",%" PetscInt_FMT ",%" PetscInt_FMT ")\n",
912 REFLECTION_CAP, idx, idy, idz);
913 } else {
914 idx = -1; // Search failure: the cell cannot hold the fallback (warped beyond its centroid)
915 search_concluded = PETSC_TRUE;
916 }
917 }
918 }
919 }
920 }
921
922 user->simCtx->searchMetrics.traversalStepsSum += traversal_steps;
924 traversal_steps);
925
926 // --- 3. Finalize and Determine Actionable Status ---
927 if (blocked) {
928 // Hand the particle back as unlocated; the orchestrator searches it again from scratch.
930 *status_out = NEEDS_LOCATION;
931 particle->cell[0] = -1; particle->cell[1] = -1; particle->cell[2] = -1;
932 } else if (exited) {
933 *status_out = EXITED;
934 particle->cell[0] = -1; particle->cell[1] = -1; particle->cell[2] = -1;
935 } else if (idx == -1 || (!search_concluded && traversal_steps >= MAX_TRAVERSAL)) {
936 if (idx != -1) {
938 LOG_ALLOW(LOCAL, LOG_ERROR, "[PID %lld]: Search FAILED, exceeded MAX_TRAVERSAL limit of %d.\n",
939 (long long)particle->PID, MAX_TRAVERSAL);
940 }
941 *status_out = LOST;
942 particle->cell[0] = -1; particle->cell[1] = -1; particle->cell[2] = -1;
943 } else {
944 // Search succeeded in finding a candidate cell, now determine its owner.
945 PetscMPIInt owner_rank;
946 ierr = FindOwnerOfCell(user, idx, idy, idz, &owner_rank); CHKERRQ(ierr);
947
948 // Always update the particle's cell index. It's a good guess for the receiving rank.
949 particle->cell[0] = idx; particle->cell[1] = idy; particle->cell[2] = idz;
950
951 if (owner_rank == rank) {
952 *status_out = ACTIVE_AND_LOCATED;
953 } else if (owner_rank != -1) {
954 // Particle belongs to another rank. Return the direct, actionable status.
955 *status_out = MIGRATING_OUT;
956 particle->destination_rank = owner_rank;
957 } else { // Found a valid index, but no owner in the map.
958 *status_out = LOST;
959 particle->cell[0] = -1; particle->cell[1] = -1; particle->cell[2] = -1;
960 }
961 }
962
963 // --- 4. Report the Final Outcome: the particle's consolidated locate line ---
964 LOG_PARTICLE(user->simCtx, particle->PID, "locate",
965 "%s from cell (%" PetscInt_FMT ",%" PetscInt_FMT ",%" PetscInt_FMT ") to (%" PetscInt_FMT ",%" PetscInt_FMT ",%" PetscInt_FMT ") in %" PetscInt_FMT " step(s), %" PetscInt_FMT " reflection(s) | weights (%.6f, %.6f, %.6f) | at (%.6e, %.6e, %.6e) | destination rank %d\n",
966 ParticleLocationStatusToString(*status_out), start_cell[0], start_cell[1], start_cell[2],
967 particle->cell[0], particle->cell[1], particle->cell[2], traversal_steps, reflections,
968 particle->weights.x, particle->weights.y, particle->weights.z,
969 particle->loc.x, particle->loc.y, particle->loc.z, (int)particle->destination_rank);
970 if (!planes) { ierr = MetricRestoreFacePlaneArrays(user, &own_arrays); CHKERRQ(ierr); }
971
973 PetscFunctionReturn(0);
974}
PetscErrorCode MetricRestoreFacePlaneArrays(UserCtx *user, FacePlaneArrays *arrays)
Closes arrays opened by MetricGetFacePlaneArrays().
Definition Metric.c:401
void MetricGatherCellFacePlanes(const FacePlaneArrays *arrays, const DMDALocalInfo *info, PetscInt i, PetscInt j, PetscInt k, CellFacePlanes *planes)
Assembles one cell's six outward face planes from the shared per-face planes.
Definition Metric.c:421
PetscErrorCode MetricGetFacePlaneArrays(UserCtx *user, PetscBool dual, FacePlaneArrays *arrays)
Opens a family's face-plane arrays for reading; MetricComputeFacePlanes() must have run.
Definition Metric.c:376
PetscBool dual
Dual-cell planes (from lCent) rather than grid-cell planes.
Definition Metric.h:529
Read-only flat arrays of one family of face planes (grid cells or dual cells).
Definition Metric.h:528
PetscErrorCode UpdateParticleWeights(PetscReal *d, Particle *particle)
Updates a particle's interpolation weights based on distances to cell faces.
const char * BCFaceToString(BCFace face)
Returns the canonical log token for a boundary-face enum value.
Definition logging.c:640
const char * ParticleLocationStatusToString(ParticleLocationStatus level)
A function that outputs the name of the current level in the ParticleLocation enum.
Definition logging.c:1905
PetscMPIInt rank
Definition variables.h:919
BoundaryFaceConfig boundary_faces[6]
Definition variables.h:1182
PetscInt64 reflectionCount
Definition variables.h:296
@ LOST
The search failed for a particle believed to be inside the domain.
Definition variables.h:190
@ NEEDS_LOCATION
Definition variables.h:187
@ ACTIVE_AND_LOCATED
Definition variables.h:188
@ EXITED
The particle crossed a domain-boundary face whose particle policy removes it.
Definition variables.h:192
@ MIGRATING_OUT
Definition variables.h:189
PetscInt64 wrapCount
Definition variables.h:298
PetscInt64 boundaryClampCount
Definition variables.h:290
PetscInt KM
Definition variables.h:1171
ParticleBoundaryPolicy
What happens to a particle that crosses a domain-boundary face.
Definition variables.h:336
@ PARTICLE_BOUNDARY_REFLECT
The particle is mirrored about the face plane and stays.
Definition variables.h:338
@ PARTICLE_BOUNDARY_WRAP
Periodic faces: the particle re-enters through the paired face.
Definition variables.h:339
PetscInt64 traversalStepsSum
Definition variables.h:285
PetscInt currentSettlementPass
Definition variables.h:299
PetscInt64 reSearchCount
Definition variables.h:286
PetscMPIInt destination_rank
Definition variables.h:243
PetscInt64 maxTraversalSteps
Definition variables.h:287
ParticleBoundaryPolicy particle_policy
What a particle crossing this face becomes (BC param particle_policy).
Definition variables.h:428
PetscInt JM
Definition variables.h:1171
SearchMetricsState searchMetrics
Definition variables.h:1073
PetscInt IM
Definition variables.h:1171
Cmpnts periodic_translation[3]
Definition variables.h:1178
Cmpnts weights
Definition variables.h:241
PetscBool periodic_translation_valid[3]
Definition variables.h:1179
PetscInt64 searchAttempts
Definition variables.h:281
PetscInt64 reflectionFallbackCount
Definition variables.h:297
PetscInt64 tieBreakCount
Definition variables.h:289
PetscInt64 blockedWalkRetryCount
Definition variables.h:295
PetscInt64 maxTraversalFailCount
Definition variables.h:288
BCFace
Identifies the six logical faces of a structured computational block.
Definition variables.h:308
Defines the vertices of a single hexahedral grid cell.
Definition variables.h:218
#define DISTANCE_THRESHOLD
#define MAX_TRAVERSAL
PetscErrorCode EvaluateParticlePositionInPlanes(const CellFacePlanes *planes, PetscReal *d, const Cmpnts p, PetscInt *position, const PetscReal threshold)
Implementation of EvaluateParticlePositionInPlanes().
#define BLOCKED_WALK_GUARD_CELLS
PetscErrorCode ReflectParticleAcrossCellFace(const CellFacePlanes *planes, PetscInt face, Cmpnts *p)
Implementation of ReflectParticleAcrossCellFace().
#define REFLECTION_CAP
PetscErrorCode PlaceParticleInsideCell(const Cell *cell, Cmpnts *p, PetscBool *placed)
Implementation of PlaceParticleInsideCell().
#define REPEAT_COUNT_THRESHOLD
PetscErrorCode UpdateCellIndicesBasedOnDistances(PetscReal d[NUM_FACES], PetscInt *idx, PetscInt *idy, PetscInt *idz)
Implementation of UpdateCellIndicesBasedOnDistances().
PetscErrorCode FindOwnerOfCell(UserCtx *user, PetscInt i, PetscInt j, PetscInt k, PetscMPIInt *owner_rank)
Implementation of FindOwnerOfCell().
PetscErrorCode RetrieveCurrentCell(UserCtx *user, PetscInt idx, PetscInt idy, PetscInt idz, Cell *cell)
Implementation of RetrieveCurrentCell().
static const BCFace kCellFaceDomainFace[NUM_FACES]
static void ResetStuckDetection(PetscInt *repeated, PetscInt *prev_i, PetscInt *prev_j, PetscInt *prev_k)
Forget the cell the stuck-walk detector compared against, after the particle moved without the walk s...
PetscErrorCode InitializeTraversalParameters(UserCtx *user, Particle *particle, PetscInt *idx, PetscInt *idy, PetscInt *idz, PetscInt *traversal_steps)
Implementation of InitializeTraversalParameters().
Here is the call graph for this function:

Variable Documentation

◆ kCellFaceDomainFace

const BCFace kCellFaceDomainFace[NUM_FACES]
static
Initial value:
@ 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

Definition at line 21 of file walkingsearch.c.