PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
walkingsearch.h
Go to the documentation of this file.
1/**
2 * @file walkingsearch.h
3 * @brief Header file for particle location functions using the walking search algorithm.
4 *
5 * This file contains declarations of functions that implement the walking search algorithm
6 * to locate particles within a computational grid. It includes functions for computing
7 * distances to cell faces, determining particle positions relative to cells, and updating
8 * traversal parameters.
9 */
10
11#ifndef WALKINGSEARCH_H
12#define WALKINGSEARCH_H
13
14// Include necessary headers
15#include <petsc.h>
16#include <stdbool.h>
17#include <math.h>
18#include "variables.h" // Common type definitions
19#include "logging.h" // Logging macros and definitions
20#include "setup.h" // utility functions
21
22// --------------------- Function Declarations ---------------------
23
24/**
25 * @brief Estimates a characteristic length of the cell for threshold scaling.
26 *
27 * For a hexahedral cell with vertices cell->vertices[0..7], we approximate
28 * the cell size by some measure—e.g. average edge length or diagonal.
29 * @param[in] cell A pointer to the Cell structure
30 * @param[out] cellSize A pointer to a PetscReal where the characteristic size is stored.
31 *
32 * @return PetscErrorCode 0 on success, non-zero on failure.
33 */
34 PetscErrorCode GetCellCharacteristicSize(const Cell *cell, PetscReal *cellSize);
35
36/**
37 * @brief Computes the signed distances from a point to each face of a cubic cell.
38 *
39 * This function calculates the signed distances from a specified point `p` to each of the six
40 * faces of a cubic cell. The cell is defined by its eight vertices, and the distances are
41 * stored in the memory location pointed to by `d`.
42 *
43 * @param[in] p The target point in 3D space.
44 * @param[in] cell Pointer to a `Cell` structure that defines the cubic cell via its vertices.
45 * @param[out] d A pointer to an array of six `PetscReal` values where the computed signed distances will be stored.
46 * @param[in] threshold A `PetscReal` value that specifies the minimum distance below which a computed distance is considered to be zero.
47 * @param[out] normals Optional, may be NULL: an array of six `Cmpnts` receiving each face plane's unit outward normal, in the same order as `d`.
48 *
49 * @return PetscErrorCode Returns 0 on success, non-zero on failure.
50 */
51PetscErrorCode CalculateDistancesToCellFaces(const Cmpnts p, const Cell *cell, PetscReal *d, const PetscReal threshold, Cmpnts *normals);
52
53/**
54 * @brief Signed distances from a point to precomputed cell face planes.
55 *
56 * @param[in] p The target point.
57 * @param[in] planes Face planes from MetricBuildCellFacePlanes().
58 * @param[out] d Six signed distances, positive inside, indexed by `Face`; below `threshold` set to 0.
59 * @param[in] threshold Absolute distance below which a distance is zero.
60 * @param[out] normals Optional, may be NULL: each face's unit outward normal, in the order of `d`.
61 *
62 * @return PetscErrorCode 0 on success, or PETSC_ERR_USER for a degenerate face; faces are checked
63 * in BACK, FRONT, BOTTOM, TOP, LEFT, RIGHT order and the first degenerate one is reported.
64 */
65PetscErrorCode CalculateDistancesToCellFacePlanes(const Cmpnts p, const CellFacePlanes *planes, PetscReal *d,
66 const PetscReal threshold, Cmpnts *normals);
67
68/**
69 * @brief Classifies a point based on precomputed face distances.
70 *
71 * Given an array of six distances d[NUM_FACES] from the point to each face
72 * of a hexahedral cell, this function determines:
73 * 0 => inside
74 * 1 => on a single face
75 * 2 => on an edge (2 faces = 0)
76 * 3 => on a corner (3+ faces = 0)
77 * -1 => outside
78 *
79 * @param[in] d Array of six face distances.
80 * @param[out] result Pointer to an integer classification: {0,1,2,3,-1}.
81 *
82 * @return PetscErrorCode Returns 0 on success, non-zero on failure.
83 */
84 PetscErrorCode DeterminePointPosition(PetscReal *d, PetscInt *result);
85
86/**
87 * @brief Initializes traversal parameters for locating a particle.
88 *
89 * This function sets the initial cell indices based on the local grid boundaries
90 * and initializes the traversal step counter.
91 *
92 * @param[in] user Pointer to the user-defined context containing grid information.
93 * @param[in] particle Pointer to the Particle structure containing its location.
94 * @param[out] idx Pointer to store the initial i-index of the cell.
95 * @param[out] idy Pointer to store the initial j-index of the cell.
96 * @param[out] idz Pointer to store the initial k-index of the cell.
97 * @param[out] traversal_steps Pointer to store the initial traversal step count.
98 *
99 * @return PetscErrorCode Returns 0 on success, non-zero on failure.
100 */
101PetscErrorCode InitializeTraversalParameters(UserCtx *user, Particle *particle, PetscInt *idx, PetscInt *idy, PetscInt *idz, PetscInt *traversal_steps);
102
103/**
104 * @brief Checks if the current cell indices are within the local grid boundaries.
105 *
106 * @param[in] user Pointer to the user-defined context containing grid information.
107 * @param[in] idx The i-index of the current cell.
108 * @param[in] idy The j-index of the current cell.
109 * @param[in] idz The k-index of the current cell.
110 * @param[out] is_within Pointer to a PetscBool that will be set to PETSC_TRUE if within bounds, else PETSC_FALSE.
111 *
112 * @return PetscErrorCode Returns 0 on success, non-zero on failure.
113 */
114PetscErrorCode CheckCellWithinLocalGrid(UserCtx *user, PetscInt idx, PetscInt idy, PetscInt idz, PetscBool *is_within);
115
116/**
117 * @brief Retrieves the coordinates of the eight vertices of the current cell.
118 *
119 * 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),
120 * (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
121 * MetricBuildCellFacePlanes() reads.
122 *
123 * @param[in] user Pointer to the user-defined context containing grid information.
124 * @param[in] idx The i-index of the current cell.
125 * @param[in] idy The j-index of the current cell.
126 * @param[in] idz The k-index of the current cell.
127 * @param[out] cell Pointer to a Cell structure to store the cell's vertices.
128 *
129 * @return PetscErrorCode Returns 0 on success, non-zero on failure.
130 */
131PetscErrorCode RetrieveCurrentCell(UserCtx *user, PetscInt idx, PetscInt idy, PetscInt idz, Cell *cell);
132
133/**
134 * @brief Classifies a point against a cell's precomputed face planes.
135 *
136 * Computes the signed distances to the six face planes, zeroing those below
137 * `threshold * planes->size`, then classifies them with DeterminePointPosition().
138 *
139 * @param[in] planes Face planes with `size` set, e.g. from MetricGatherCellFacePlanes().
140 * @param[out] d Six signed face distances, thresholded at `threshold * planes->size`.
141 * @param[in] p The particle position.
142 * @param[out] position 0 inside, 1 to 3 on a face, edge or corner, -1 outside.
143 * @param[in] threshold Base threshold, scaled by the cell size.
144 *
145 * @return PetscErrorCode 0 on success, or PETSC_ERR_USER for a degenerate face.
146 */
147PetscErrorCode EvaluateParticlePositionInPlanes(const CellFacePlanes *planes, PetscReal *d, const Cmpnts p,
148 PetscInt *position, const PetscReal threshold);
149
150
151/**
152 * @brief Finds the MPI rank that owns a given global cell index.
153 * @ingroup DomainInfo
154 *
155 * The DMDA decomposition is a tensor product of per-axis ranges, with rank
156 * i + m (j + n k) on process grid m x n x p, so the owner is found by a binary search of
157 * the range starts along each axis in the pre-computed decomposition map
158 * (`user->RankCellInfoMap`): O(log m + log n + log p), not O(ranks). It is the definitive
159 * method for resolving cell ownership in the "Walk and Handoff" migration algorithm.
160 *
161 * If the provided indices are outside the range of any rank (e.g., negative or
162 * beyond the global domain), the function will not find an owner and `owner_rank`
163 * will be set to -1.
164 *
165 * @param[in] user Pointer to the UserCtx structure, which must contain the
166 * initialized `RankCellInfoMap` and `num_ranks`.
167 * @param[in] i Global i-index of the cell to find.
168 * @param[in] j Global j-index of the cell to find.
169 * @param[in] k Global k-index of the cell to find.
170 * @param[out] owner_rank Pointer to a `PetscMPIInt` where the resulting owner rank will
171 * be stored. It is set to -1 if no owner is found.
172 *
173 * @return PetscErrorCode 0 on success, or a non-zero PETSc error code on failure.
174 */
175PetscErrorCode FindOwnerOfCell(UserCtx *user, PetscInt i, PetscInt j, PetscInt k, PetscMPIInt *owner_rank);
176
177/**
178 * @brief Mirrors a point about the plane of one face of a cell.
179 *
180 * The plane is the one the walking search tested the point against, so a point outside the
181 * face by |d| ends inside it by |d|: p' = p + 2 d n, with d < 0 outside. Only the position changes.
182 *
183 * @param[in] planes The cell's face planes (MetricGatherCellFacePlanes() or MetricBuildCellFacePlanes()).
184 * @param[in] face The face index (LEFT, RIGHT, BOTTOM, TOP, FRONT or BACK).
185 * @param[in,out] p The point to mirror.
186 *
187 * @return PetscErrorCode 0 on success, or a non-zero PETSc error code (including a degenerate face).
188 */
189PetscErrorCode ReflectParticleAcrossCellFace(const CellFacePlanes *planes, PetscInt face, Cmpnts *p);
190
191/**
192 * @brief Moves a point to just inside a cell along the segment toward the cell centroid.
193 *
194 * The terminal action when reflections reach their cap. Plane distances are linear along the
195 * segment, so the entry parameter is the largest d_p / (d_p - d_c) over the faces the point is
196 * outside of; the point is placed a relative 1e-6 of the remaining segment beyond it.
197 *
198 * @param[in] cell The cell to place the point in.
199 * @param[in,out] p The point; unchanged when it cannot be placed.
200 * @param[out] placed PETSC_FALSE when the centroid is not inside every face plane the point
201 * is outside of (a cell warped that far), in which case `p` is unchanged.
202 *
203 * @return PetscErrorCode 0 on success, or a non-zero PETSc error code on failure.
204 */
205PetscErrorCode PlaceParticleInsideCell(const Cell *cell, Cmpnts *p, PetscBool *placed);
206
207/**
208 * @brief Locates a particle's host cell or identifies its migration target using a robust walk search.
209 * @ingroup ParticleLocation
210 *
211 * This is the core search engine. It starts from a guess cell and walks through
212 * the grid. It returns a definitive, actionable status indicating the outcome:
213 * - `ACTIVE_AND_LOCATED`: The particle was found in a cell on the current rank.
214 * - `MIGRATING_OUT`: The particle was found to belong to another rank. `particle->destination_rank` is set.
215 * - `EXITED`: The particle lies beyond a domain-boundary face of the boundary cell the walk reached,
216 * with every face it is outside of on the domain boundary and at least one of them using the
217 * `remove` particle policy. When all of them use `reflect`, the particle is instead mirrored
218 * about the most-crossed face (`ReflectParticleAcrossCellFace`) and the search continues; after
219 * `REFLECTION_CAP` reflections it is placed just inside the cell (`PlaceParticleInsideCell`).
220 * - `NEEDS_LOCATION` (with `cell` reset to -1): a pass-1 walk from the previous-step cell ended more
221 * than `BLOCKED_WALK_GUARD_CELLS` cell sizes beyond the boundary, so the walk was most likely blocked
222 * by a non-convex boundary; the caller searches the particle again from scratch.
223 * - `LOST`: The search failed for a particle believed to be inside the domain.
224 *
225 * This function is globally aware and can walk across MPI rank boundaries. It contains
226 * robust checks for global domain boundaries and a tie-breaker for numerically "stuck"
227 * particles on cell faces. A face lies on the domain boundary when the cell index is at the
228 * extreme of that axis, the same test the boundary-condition handlers use.
229 *
230 * @param[in] user Pointer to the UserCtx containing all grid and domain info.
231 * @param[in] planes The block's primal face-plane arrays, already open with
232 * `MetricGetFacePlaneArrays()`, or NULL to open and close them here.
233 * A caller searching many particles opens them once and passes them.
234 * @param[in,out] particle Pointer to the Particle struct. Its fields are updated based
235 * on the search outcome.
236 * @param[out] status_out The final, actionable status of the particle after the search.
237 *
238 * @return PetscErrorCode 0 on success, or a non-zero PETSc error code on failure.
239 *
240 * @note Testing status:
241 * This function is exercised indirectly by the orchestrator tests, but
242 * direct branch pinning for boundary clamp, ghost-region handoff,
243 * tie-breaker, `LOST`, and `MIGRATING_OUT` outcomes is still part of the
244 * next-gap test backlog.
245 */
246struct FacePlaneArrays; /* Metric.h; not included here, since Metric.h includes setup.h, which includes this header */
248 const struct FacePlaneArrays *planes,
249 Particle *particle,
250 ParticleLocationStatus *status_out);
251
252/**
253 * @brief Updates the cell indices based on the signed distances to each face.
254 *
255 * This function modifies the cell indices (`idx`, `idy`, `idz`) to move towards the direction
256 * where the particle is likely to be located, based on positive distances indicating
257 * that the particle is outside in that particular direction.
258 *
259 * @param[in] d An array of six `PetscReal` values representing the signed distances to each face:
260 * - d[LEFT]: Left Face
261 * - d[RIGHT]: Right Face
262 * - d[BOTTOM]: Bottom Face
263 * - d[TOP]: Top Face
264 * - d[FRONT]: Front Face
265 * - d[BACK]: Back Face
266 * @param[out] idx Pointer to the i-index of the cell to be updated.
267 * @param[out] idy Pointer to the j-index of the cell to be updated.
268 * @param[out] idz Pointer to the k-index of the cell to be updated.
269 *
270 * @return PetscErrorCode Returns 0 on success, non-zero on failure.
271 */
272PetscErrorCode UpdateCellIndicesBasedOnDistances( PetscReal d[NUM_FACES], PetscInt *idx, PetscInt *idy, PetscInt *idz);
273
274#endif // WALKINGSEARCH_H
Read-only flat arrays of one family of face planes (grid cells or dual cells).
Definition Metric.h:528
Logging utilities and macros for PETSc-based applications.
Main header file for a complex fluid dynamics solver.
ParticleLocationStatus
Defines the state of a particle with respect to its location and migration status during the iterativ...
Definition variables.h:186
@ NUM_FACES
Definition variables.h:197
Defines the vertices of a single hexahedral grid cell.
Definition variables.h:218
The six face planes of one hexahedron, indexed by Face, and its characteristic size.
Definition variables.h:229
A 3D point or vector with PetscScalar components.
Definition variables.h:144
Defines a particle's core properties for Lagrangian tracking.
Definition variables.h:236
User-defined context containing data specific to a single computational grid level.
Definition variables.h:1157
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 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 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 GetCellCharacteristicSize(const Cell *cell, PetscReal *cellSize)
Estimates a characteristic length of the cell for threshold scaling.
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 DeterminePointPosition(PetscReal *d, PetscInt *result)
Classifies a point based on precomputed face distances.
PetscErrorCode UpdateCellIndicesBasedOnDistances(PetscReal d[NUM_FACES], PetscInt *idx, PetscInt *idy, PetscInt *idz)
Updates the cell indices based on the signed distances to each face.
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 LocateParticleOrFindMigrationTarget(UserCtx *user, const struct FacePlaneArrays *planes, Particle *particle, ParticleLocationStatus *status_out)
PetscErrorCode RetrieveCurrentCell(UserCtx *user, PetscInt idx, PetscInt idy, PetscInt idz, Cell *cell)
Retrieves the coordinates of the eight vertices of the current cell.
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.