PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
Macros | Functions
ParticleMotion.c File Reference
#include "ParticleMotion.h"
#include "particle_field_catalog.h"
#include "ParticleInitialConditions.h"
Include dependency graph for ParticleMotion.c:

Go to the source code of this file.

Macros

#define ERROR_MSG_BUFFER_SIZE   256
 

Functions

PetscErrorCode CalculateBrownianDisplacement (UserCtx *user, PetscInt64 pid, PetscReal diff_eff, Cmpnts *displacement)
 Implementation of CalculateBrownianDisplacement().
 
PetscErrorCode UpdateParticlePosition (UserCtx *user, Particle *particle)
 Implementation of UpdateParticlePosition().
 
PetscErrorCode UpdateAllParticlePositions (UserCtx *user)
 Implementation of UpdateAllParticlePositions().
 
PetscErrorCode CheckAndRemoveLostParticles (UserCtx *user, PetscInt *removedCountLocal, PetscInt *removedCountGlobal, PetscReal *removedScalarSumGlobal, PetscInt *exitedCountGlobal, PetscReal *exitedScalarSumGlobal)
 Implementation of CheckAndRemoveLostParticles().
 
PetscErrorCode SetMigrationRanks (UserCtx *user, const MigrationInfo *migrationList, PetscInt migrationCount)
 Implementation of SetMigrationRanks().
 
PetscErrorCode RemoveFlaggedParticles (DM swarm, PetscInt n_scan, PetscBool remove[], PetscBool scan_backward)
 Implementation of RemoveFlaggedParticles().
 
static PICURV_ALWAYS_INLINE void GatherSwarmRecords (char *out, const char *in, const PetscInt *order, PetscInt n, size_t bytes)
 Copies n fixed-size records into out in the order order[] gives (out[p] = in[order[p]]).
 
PetscErrorCode SortParticlesByCell (DM swarm)
 Implementation of SortParticlesByCell().
 
PetscErrorCode PerformMigration (UserCtx *user, PetscInt *n_survivors)
 Implementation of PerformMigration().
 
PetscErrorCode CalculateParticleCountPerCell (UserCtx *user)
 Implementation of CalculateParticleCountPerCell().
 
PetscErrorCode ResizeSwarmGlobally (DM swarm, PetscInt N_target)
 Implementation of ResizeSwarmGlobally().
 
PetscErrorCode PreCheckAndResizeSwarm (UserCtx *user, PetscInt ti, const char *ext)
 Implementation of PreCheckAndResizeSwarm().
 
PetscErrorCode GetLocalPIDSnapshot (const PetscInt64 pid_field[], PetscInt n_local, PetscInt64 **pids_snapshot_out)
 Implementation of GetLocalPIDSnapshot().
 
PetscErrorCode AddToMigrationList (MigrationInfo **migration_list_p, PetscInt *capacity_p, PetscInt *count_p, PetscInt particle_local_idx, PetscMPIInt destination_rank)
 Implementation of AddToMigrationList().
 
static PetscErrorCode VerifyNewcomersAgainstPIDs (UserCtx *user, PetscInt n_before, const PetscInt64 pids_before[], PetscInt first_newcomer)
 Requires the position-identified newcomers to be exactly the PID-identified ones, when -picurv_verify_ghost_updates is set.
 
PetscErrorCode FlagNewcomersForLocation (DM swarm, PetscInt n_local_before, PetscInt first_newcomer)
 Implementation of FlagNewcomersForLocation().
 
PetscErrorCode MigrateRestartParticlesUsingCellID (UserCtx *user)
 Implementation of MigrateRestartParticlesUsingCellID().
 
static PetscErrorCode GuessParticleOwnerWithBBox (UserCtx *user, const Particle *particle, const BoundingBox *bboxlist, PetscMPIInt *guess_rank_out)
 Select the rank whose gathered bounding box is the best owner candidate for a particle.
 
PetscErrorCode LocateAllParticlesInGrid (UserCtx *user, BoundingBox *bboxlist)
 Implementation of LocateAllParticlesInGrid().
 
PetscErrorCode ResetAllParticleStatuses (UserCtx *user)
 Implementation of ResetAllParticleStatuses().
 

Macro Definition Documentation

◆ ERROR_MSG_BUFFER_SIZE

#define ERROR_MSG_BUFFER_SIZE   256

Definition at line 9 of file ParticleMotion.c.

Function Documentation

◆ CalculateBrownianDisplacement()

PetscErrorCode CalculateBrownianDisplacement ( UserCtx *  user,
PetscInt64  pid,
PetscReal  diff_eff,
Cmpnts *  displacement 
)

Implementation of CalculateBrownianDisplacement().

Calculates the stochastic displacement vector (Brownian motion) for a single particle.

See also
CalculateBrownianDisplacement()

Definition at line 16 of file ParticleMotion.c.

17{
18 const SimCtx *simCtx = user->simCtx;
19 uint64_t hash;
20 PetscReal n[4], sigma;
21
22 PetscFunctionBeginUser;
23 displacement->x = displacement->y = displacement->z = 0.0;
24 if (diff_eff <= 1.0e-12) PetscFunctionReturn(0);
25
26 /* Keyed on (seed, PID, step) alone, so the increment is independent of rank layout
27 * and particle order, and a restart reproduces it. */
28 hash = PicurvDrawHash(simCtx->particleRandomSeed, PICURV_DRAW_SPACE_BROWNIAN, 0, pid, simCtx->step);
29 PicurvNormalPairFromHash(hash, &n[0]);
30 PicurvNormalPairFromHash(PicurvMix64(hash ^ 1u), &n[2]);
31
32 sigma = PetscSqrtReal(2.0 * diff_eff * simCtx->dt);
33 displacement->x = sigma * n[0];
34 displacement->y = sigma * n[1];
35 displacement->z = sigma * n[2];
36 PetscFunctionReturn(0);
37}
uint64_t PicurvMix64(uint64_t z)
splitmix64 finalizer: a bijective mix of 64 bits.
Definition expression.c:589
uint64_t PicurvDrawHash(PetscInt64 seed, PicurvDrawSpace space, uint64_t stream, PetscInt64 id, PetscInt64 salt)
Hash that keys a draw: a pure function of its arguments, so a draw does not depend on the rank that m...
Definition expression.c:610
void PicurvNormalPairFromHash(uint64_t hash, PetscReal normal[2])
Two independent standard normal deviates from a hash, by Box-Muller from two uniforms it yields.
Definition expression.c:640
@ PICURV_DRAW_SPACE_BROWNIAN
Brownian increments; the salt is the step.
Definition expression.h:32
SimCtx * simCtx
Back-pointer to the master simulation context.
Definition variables.h:1160
PetscReal dt
Definition variables.h:933
PetscScalar x
Definition variables.h:145
PetscScalar z
Definition variables.h:145
PetscInt particleRandomSeed
Base seed for every particle RNG stream (-particle_random_seed).
Definition variables.h:1050
PetscInt step
Definition variables.h:924
PetscScalar y
Definition variables.h:145
The master context for the entire simulation.
Definition variables.h:916
Here is the call graph for this function:
Here is the caller graph for this function:

◆ UpdateParticlePosition()

PetscErrorCode UpdateParticlePosition ( UserCtx *  user,
Particle *  particle 
)

Implementation of UpdateParticlePosition().

Updates a particle's position based on its velocity and the timestep dt (stored in user->dt).

See also
UpdateParticlePosition()

Definition at line 43 of file ParticleMotion.c.

44{
45 PetscFunctionBeginUser; // PETSc macro for error/stack tracing
47
48 PetscErrorCode ierr;
49 PetscReal dt = user->simCtx->dt;
50 Cmpnts brownian_disp;
51
52 // 2. Calculate the stochastic kick
53 ierr = CalculateBrownianDisplacement(user, particle->PID, particle->diffusivity, &brownian_disp); CHKERRQ(ierr);
54
55 // --- Update Position ---
56 // X_new = X_old + ((U_convection + U_diffusivitygradient) * dt) + dX_brownian
57
58 particle->loc.x += ((particle->vel.x + particle->diffusivitygradient.x) * dt) + brownian_disp.x;
59 particle->loc.y += ((particle->vel.y + particle->diffusivitygradient.y) * dt) + brownian_disp.y;
60 particle->loc.z += ((particle->vel.z + particle->diffusivitygradient.z) * dt) + brownian_disp.z;
61
63 PetscFunctionReturn(0);
64}
PetscErrorCode CalculateBrownianDisplacement(UserCtx *user, PetscInt64 pid, PetscReal diff_eff, Cmpnts *displacement)
Implementation of CalculateBrownianDisplacement().
#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
Cmpnts vel
Definition variables.h:240
Cmpnts diffusivitygradient
Definition variables.h:245
Cmpnts loc
Definition variables.h:239
PetscReal diffusivity
Definition variables.h:244
PetscInt64 PID
Definition variables.h:237
A 3D point or vector with PetscScalar components.
Definition variables.h:144
Here is the call graph for this function:
Here is the caller graph for this function:

◆ UpdateAllParticlePositions()

PetscErrorCode UpdateAllParticlePositions ( UserCtx *  user)

Implementation of UpdateAllParticlePositions().

Loops over all local particles in the DMSwarm, updating their positions based on velocity and the global timestep user->dt.

See also
UpdateAllParticlePositions()

Definition at line 70 of file ParticleMotion.c.

71{
72 PetscErrorCode ierr;
73 DM swarm = user->swarm;
74 PetscInt nLocal, p;
75 PetscReal *pos = NULL;
76 PetscReal *vel = NULL;
77 PetscReal *diffusivity = NULL;
78 Cmpnts *diffusivitygradient = NULL;
79 PetscReal *psi = NULL;
80 PetscReal *weights = NULL;
81 PetscInt *cell = NULL;
82 PetscInt *status = NULL;
83 PetscInt64 *pid = NULL;
84 PetscMPIInt rank;
85
86 rank = user->simCtx->rank;
87
88 PetscFunctionBeginUser; // PETSc macro for error/stack tracing
89
91
92 // 1) Get the number of local particles
93 ierr = DMSwarmGetLocalSize(swarm, &nLocal); CHKERRQ(ierr);
94 if (nLocal == 0) {
95 LOG_ALLOW(LOCAL,LOG_DEBUG,"[Rank %d] No particles to move/transport. \n",rank);
97 PetscFunctionReturn(0); // nothing to do, no fields held
98 }
99 // 2) Access the "position" and "velocity" fields
100 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_POSITION), NULL, NULL, (void**)&pos); CHKERRQ(ierr);
101 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_VELOCITY), NULL, NULL, (void**)&vel); CHKERRQ(ierr);
102 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_DIFFUSIVITY), NULL, NULL, (void**)&diffusivity); CHKERRQ(ierr);
103 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_DIFFUSIVITY_GRADIENT), NULL, NULL, (void**)&diffusivitygradient); CHKERRQ(ierr);
104 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_PSI), NULL, NULL, (void**)&psi); CHKERRQ(ierr);
105 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_WEIGHT), NULL, NULL, (void**)&weights); CHKERRQ(ierr);
106 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_CELL_ID), NULL, NULL, (void**)&cell); CHKERRQ(ierr);
107 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_LOCATION_STATUS), NULL, NULL, (void**)&status); CHKERRQ(ierr);
108 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_PID), NULL, NULL, (void**)&pid); CHKERRQ(ierr);
109
110 LOG_ALLOW(GLOBAL,LOG_DEBUG," [Rank %d] No.of Particles to update: %" PetscInt_FMT ".\n",rank,nLocal);
111
112 // 3) Loop over all local particles, updating each position by velocity * dt
113 for (p = 0; p < nLocal; p++) {
114 // update temporary particle struct
115 Particle particle;
116
117 // Unpack: Use the helper to read from swarm arrays into the particle struct
118 ierr = UnpackSwarmFields(p, pid, weights, pos, cell, vel, status, diffusivity, diffusivitygradient, psi, &particle); CHKERRQ(ierr);
119
120 // Update position based on velocity and Brownian motion
121 const Cmpnts old_loc = particle.loc;
122 ierr = UpdateParticlePosition(user, &particle); CHKERRQ(ierr);
123 LOG_PARTICLE(user->simCtx, particle.PID, "advect",
124 "(%.6e, %.6e, %.6e) -> (%.6e, %.6e, %.6e) | vel (%.6e, %.6e, %.6e) | diffusivity %.6e gradient (%.6e, %.6e, %.6e) | dt %.6e\n",
125 old_loc.x, old_loc.y, old_loc.z, particle.loc.x, particle.loc.y, particle.loc.z,
126 particle.vel.x, particle.vel.y, particle.vel.z, particle.diffusivity,
127 particle.diffusivitygradient.x, particle.diffusivitygradient.y, particle.diffusivitygradient.z,
128 user->simCtx->dt);
129
130 // Update swarm fields
131 ierr = UpdateSwarmFields(p, &particle, pos, vel, weights, cell, status, diffusivity, diffusivitygradient, psi); CHKERRQ(ierr);
132 }
133
134 // 4) Restore the fields
135 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_POSITION), NULL, NULL, (void**)&pos); CHKERRQ(ierr);
136 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_VELOCITY), NULL, NULL, (void**)&vel); CHKERRQ(ierr);
137 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_DIFFUSIVITY), NULL, NULL, (void**)&diffusivity); CHKERRQ(ierr);
138 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_DIFFUSIVITY_GRADIENT), NULL, NULL, (void**)&diffusivitygradient); CHKERRQ(ierr);
139 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_PSI), NULL, NULL, (void**)&psi); CHKERRQ(ierr);
140 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_WEIGHT), NULL, NULL, (void**)&weights); CHKERRQ(ierr);
141 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_CELL_ID), NULL, NULL, (void**)&cell); CHKERRQ(ierr);
142 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_LOCATION_STATUS), NULL, NULL, (void**)&status); CHKERRQ(ierr);
143 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_PID), NULL, NULL, (void**)&pid); CHKERRQ(ierr);
144
145
146 LOG_ALLOW(LOCAL,LOG_DEBUG,"Particle moved/transported successfully on Rank %d.\n",rank);
147
149
150 PetscFunctionReturn(0);
151}
PetscErrorCode UpdateParticlePosition(UserCtx *user, Particle *particle)
Implementation of UpdateParticlePosition().
PetscErrorCode UnpackSwarmFields(PetscInt i, const PetscInt64 *PIDs, const PetscReal *weights, const PetscReal *positions, const PetscInt *cellIndices, PetscReal *velocities, PetscInt *LocStatus, PetscReal *diffusivity, Cmpnts *diffusivitygradient, PetscReal *psi, Particle *particle)
Initializes a Particle struct with data from DMSwarm fields.
PetscErrorCode UpdateSwarmFields(PetscInt i, const Particle *particle, PetscReal *positions, PetscReal *velocities, PetscReal *weights, PetscInt *cellIndices, PetscInt *status, PetscReal *diffusivity, Cmpnts *diffusivitygradient, PetscReal *psi)
Updates DMSwarm data arrays from a Particle struct.
#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
#define LOCAL
Logging scope definitions for controlling message output.
Definition logging.h:45
#define GLOBAL
Scope for global logging across all processes.
Definition logging.h:46
#define LOG_ALLOW(scope, level, fmt,...)
Logging macro that checks both the log level and whether the calling function is in the allowed-funct...
Definition logging.h:214
#define PROFILE_FUNCTION_END
Marks the end of a profiled code block.
Definition logging.h:1029
@ LOG_DEBUG
Detailed debugging information.
Definition logging.h:32
#define PROFILE_FUNCTION_BEGIN
Marks the beginning of a profiled function: an always-on aggregate timer.
Definition logging.h:1000
const char * ParticleFieldName(ParticleFieldId field_id)
Return the canonical PETSc DMSwarm name for an ID.
@ PARTICLE_FIELD_ID_LOCATION_STATUS
@ PARTICLE_FIELD_ID_WEIGHT
@ PARTICLE_FIELD_ID_POSITION
@ PARTICLE_FIELD_ID_PID
@ PARTICLE_FIELD_ID_CELL_ID
@ PARTICLE_FIELD_ID_PSI
@ PARTICLE_FIELD_ID_DIFFUSIVITY_GRADIENT
@ PARTICLE_FIELD_ID_DIFFUSIVITY
@ PARTICLE_FIELD_ID_VELOCITY
PetscMPIInt rank
Definition variables.h:919
Defines a particle's core properties for Lagrangian tracking.
Definition variables.h:236
Here is the call graph for this function:
Here is the caller graph for this function:

◆ CheckAndRemoveLostParticles()

PetscErrorCode CheckAndRemoveLostParticles ( UserCtx *  user,
PetscInt *  removedCountLocal,
PetscInt *  removedCountGlobal,
PetscReal *  removedScalarSumGlobal,
PetscInt *  exitedCountGlobal,
PetscReal *  exitedScalarSumGlobal 
)

Implementation of CheckAndRemoveLostParticles().

Removes particles that the location algorithm flagged as LOST or EXITED.

See also
CheckAndRemoveLostParticles()

Definition at line 158 of file ParticleMotion.c.

164{
165 PetscErrorCode ierr;
166 DM swarm = user->swarm;
167 PetscInt nLocalInitial;
168 PetscInt *status_p = NULL;
169 PetscInt64 *pid_p = NULL; // For better logging
170 PetscReal *pos_p = NULL; // For better logging
171 PetscReal *psi_p = NULL;
172 PetscBool *remove = NULL;
173 PetscReal local_psi[2] = {0.0, 0.0}; // Psi carried out by LOST and by EXITED particles
174 PetscReal global_psi[2] = {0.0, 0.0};
175 PetscInt local_count[2] = {0, 0}; // LOST and EXITED particles removed on this rank
176 PetscInt global_count[2] = {0, 0};
177 PetscMPIInt rank;
178
179 PetscFunctionBeginUser;
181 rank = user->simCtx->rank;
182 LOG_ALLOW(LOCAL, LOG_INFO, "Rank %d: Checking for and removing LOST and EXITED particles...\n", rank);
183
184 // Initialize output parameters to ensure clean state
185 *removedCountLocal = 0;
186 if (removedCountGlobal) *removedCountGlobal = 0;
187 if (removedScalarSumGlobal) *removedScalarSumGlobal = 0.0;
188 if (exitedCountGlobal) *exitedCountGlobal = 0;
189 if (exitedScalarSumGlobal) *exitedScalarSumGlobal = 0.0;
190
191 ierr = DMSwarmGetLocalSize(swarm, &nLocalInitial); CHKERRQ(ierr);
192
193 // Only proceed if there are particles to check on this rank.
194 // All ranks will still participate in the final collective MPI_Allreduce.
195 if (nLocalInitial > 0) {
196 // Get access to all swarm fields once before the loop begins.
197 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_LOCATION_STATUS), NULL, NULL, (void **)&status_p); CHKERRQ(ierr);
198 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_PID), NULL, NULL, (void **)&pid_p); CHKERRQ(ierr);
199 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_POSITION), NULL, NULL, (void **)&pos_p); CHKERRQ(ierr);
200 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_PSI), NULL, NULL, (void **)&psi_p); CHKERRQ(ierr);
201 ierr = PetscMalloc1(nLocalInitial, &remove); CHKERRQ(ierr);
202
203 // --- Flag LOST and EXITED particles BACKWARDS, the order the removal below fills their slots in ---
204 for (PetscInt p = nLocalInitial - 1; p >= 0; p--) {
205 remove[p] = (PetscBool)(status_p[p] == LOST || status_p[p] == EXITED);
206 if (remove[p]) {
207 const PetscInt kind = (status_p[p] == LOST) ? 0 : 1;
208 LOG_PARTICLE(user->simCtx, pid_p[p], "remove", "%s at (%.6e, %.6e, %.6e) carrying psi %.6e: removed from rank %d\n",
210 pos_p[3*p], pos_p[3*p+1], pos_p[3*p+2], psi_p[p], (int)rank);
211 // The scalar a removed particle carries leaves the domain with it.
212 local_psi[kind] += psi_p[p];
213 local_count[kind]++;
214 }
215 }
216
217 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_LOCATION_STATUS), NULL, NULL, (void **)&status_p); CHKERRQ(ierr);
218 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_PID), NULL, NULL, (void **)&pid_p); CHKERRQ(ierr);
219 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_POSITION), NULL, NULL, (void **)&pos_p); CHKERRQ(ierr);
220 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_PSI), NULL, NULL, (void **)&psi_p); CHKERRQ(ierr);
221 ierr = RemoveFlaggedParticles(swarm, nLocalInitial, remove, PETSC_TRUE); CHKERRQ(ierr);
222 ierr = PetscFree(remove); CHKERRQ(ierr);
223 } // End of if (nLocalInitial > 0)
224
225 PetscInt nLocalFinal;
226 ierr = DMSwarmGetLocalSize(swarm, &nLocalFinal); CHKERRQ(ierr);
227 LOG_ALLOW(LOCAL, LOG_INFO, "Rank %d: Finished removing %" PetscInt_FMT " LOST and %" PetscInt_FMT " EXITED particles. Final local size: %" PetscInt_FMT ".\n",
228 rank, local_count[0], local_count[1], nLocalFinal);
229
230 // --- Synchronize counts across all ranks (one reduction for both kinds) ---
231 *removedCountLocal = local_count[0];
232 if (removedCountGlobal || exitedCountGlobal) {
233 ierr = MPI_Allreduce(local_count, global_count, 2, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)swarm)); CHKERRMPI(ierr);
234 if (removedCountGlobal) *removedCountGlobal = global_count[0];
235 if (exitedCountGlobal) *exitedCountGlobal = global_count[1];
236 LOG_ALLOW(GLOBAL, LOG_INFO, "Removed %" PetscInt_FMT " LOST and %" PetscInt_FMT " EXITED particles globally.\n", global_count[0], global_count[1]);
237 }
238 if (removedScalarSumGlobal || exitedScalarSumGlobal) {
239 ierr = MPI_Allreduce(local_psi, global_psi, 2, MPIU_REAL, MPI_SUM,
240 PetscObjectComm((PetscObject)swarm)); CHKERRMPI(ierr);
241 if (removedScalarSumGlobal) *removedScalarSumGlobal = global_psi[0];
242 if (exitedScalarSumGlobal) *exitedScalarSumGlobal = global_psi[1];
243 }
244
246 PetscFunctionReturn(0);
247}
PetscErrorCode RemoveFlaggedParticles(DM swarm, PetscInt n_scan, PetscBool remove[], PetscBool scan_backward)
Implementation of RemoveFlaggedParticles().
const char * ParticleLocationStatusToString(ParticleLocationStatus level)
A function that outputs the name of the current level in the ParticleLocation enum.
Definition logging.c:1905
@ LOG_INFO
Informational messages about program execution.
Definition logging.h:31
ParticleLocationStatus
Defines the state of a particle with respect to its location and migration status during the iterativ...
Definition variables.h:186
@ LOST
The search failed for a particle believed to be inside the domain.
Definition variables.h:190
@ EXITED
The particle crossed a domain-boundary face whose particle policy removes it.
Definition variables.h:192
Here is the call graph for this function:
Here is the caller graph for this function:

◆ SetMigrationRanks()

PetscErrorCode SetMigrationRanks ( UserCtx *  user,
const MigrationInfo *  migrationList,
PetscInt  migrationCount 
)

Implementation of SetMigrationRanks().

Writes migration destinations into the DMSwarm rank field for marked particles.

See also
SetMigrationRanks()

Definition at line 254 of file ParticleMotion.c.

255{
256 PetscErrorCode ierr;
257 DM swarm = user->swarm;
258 PetscInt p_idx;
259 PetscInt *rankField = NULL; // Field storing target rank
260
261 PetscFunctionBeginUser;
263
264 // Ensure the migration rank field exists
265 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_RANK), NULL, NULL, (void **)&rankField); CHKERRQ(ierr);
266
267 // Set the target rank for migrating particles
268 for(p_idx = 0; p_idx < migrationCount; ++p_idx) {
269 rankField[migrationList[p_idx].local_index] = migrationList[p_idx].target_rank;
270 }
271
272 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_RANK), NULL, NULL, (void **)&rankField); CHKERRQ(ierr);
273
275 PetscFunctionReturn(0);
276}
@ PARTICLE_FIELD_ID_RANK
PetscInt local_index
Definition variables.h:270
Here is the call graph for this function:
Here is the caller graph for this function:

◆ RemoveFlaggedParticles()

PetscErrorCode RemoveFlaggedParticles ( DM  swarm,
PetscInt  n_scan,
PetscBool  remove[],
PetscBool  scan_backward 
)

Implementation of RemoveFlaggedParticles().

Removes flagged swarm points in one pass, preserving the one-at-a-time removal order.

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

See also
RemoveFlaggedParticles()

Definition at line 284 of file ParticleMotion.c.

285{
286 PetscErrorCode ierr;
287 PetscInt n_local, n_kept = n_scan;
288
289 PetscFunctionBeginUser;
291 ierr = DMSwarmGetLocalSize(swarm, &n_local); CHKERRQ(ierr);
292
293 // Fill each flagged slot with the last kept point, as DMSwarmRemovePointAtIndex
294 // does, so the surviving order matches removing the points one at a time.
295 for (PetscInt k = 0; k < n_scan; ++k) {
296 PetscInt p = scan_backward ? n_scan - 1 - k : k;
297 while (p < n_kept && remove[p]) {
298 n_kept--;
299 if (p != n_kept) {
300 ierr = DMSwarmCopyPoint(swarm, n_kept, p); CHKERRQ(ierr);
301 remove[p] = remove[n_kept];
302 }
303 }
304 }
305
306 // Points after the scanned range (migration arrivals) move down behind the survivors.
307 for (PetscInt q = n_scan; n_kept < n_scan && q < n_local; ++q) {
308 ierr = DMSwarmCopyPoint(swarm, q, n_kept + q - n_scan); CHKERRQ(ierr);
309 }
310 ierr = DMSwarmSetLocalSizes(swarm, n_kept + n_local - n_scan, -1); CHKERRQ(ierr);
311
313 PetscFunctionReturn(0);
314}
Here is the caller graph for this function:

◆ GatherSwarmRecords()

static PICURV_ALWAYS_INLINE void GatherSwarmRecords ( char *  out,
const char *  in,
const PetscInt *  order,
PetscInt  n,
size_t  bytes 
)
static

Copies n fixed-size records into out in the order order[] gives (out[p] = in[order[p]]).

Always inlined, so a literal bytes at the call site becomes a fixed-size copy. Local to this translation unit.

Definition at line 321 of file ParticleMotion.c.

323{
324 for (PetscInt p = 0; p < n; ++p) memcpy(out + (size_t)p * bytes, in + (size_t)order[p] * bytes, bytes);
325}
Here is the caller graph for this function:

◆ SortParticlesByCell()

PetscErrorCode SortParticlesByCell ( DM  swarm)

Implementation of SortParticlesByCell().

Reorders the local swarm points so that points in the same host cell are contiguous.

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

See also
SortParticlesByCell()

Definition at line 333 of file ParticleMotion.c.

334{
335 PetscInt n_local, lo[3] = {PETSC_MAX_INT, PETSC_MAX_INT, PETSC_MAX_INT}, hi[3] = {-1, -1, -1};
336 PetscInt *cells = NULL, *order = NULL, *key = NULL;
337 PetscInt64 extent[3], nbuckets, *start = NULL;
338 PetscBool sorted = PETSC_TRUE;
339 char *buffer = NULL;
340 size_t max_bytes = 0;
341
342 PetscFunctionBeginUser;
344 PetscCall(DMSwarmGetLocalSize(swarm, &n_local));
345 if (n_local < 2) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
346
347 // Bucket key: the cell's offset in the bounding box of the local cells, i fastest; a point
348 // without a valid cell takes the bucket after the last.
349 PetscCall(DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_CELL_ID), NULL, NULL, (void **)&cells));
350 for (PetscInt p = 0; p < n_local; ++p) {
351 const PetscInt *c = &cells[3 * p];
352 if (c[0] < 0 || c[1] < 0 || c[2] < 0) continue;
353 for (int d = 0; d < 3; ++d) { lo[d] = PetscMin(lo[d], c[d]); hi[d] = PetscMax(hi[d], c[d]); }
354 }
355 for (int d = 0; d < 3; ++d) extent[d] = (hi[d] >= lo[d]) ? (PetscInt64)(hi[d] - lo[d] + 1) : 0;
356 nbuckets = extent[0] * extent[1] * extent[2] + 1;
357 PetscCall(PetscMalloc2(n_local, &key, n_local, &order));
358 PetscCall(PetscCalloc1(nbuckets + 1, &start));
359 for (PetscInt p = 0; p < n_local; ++p) {
360 const PetscInt *c = &cells[3 * p];
361 const PetscInt64 b = (c[0] < 0 || c[1] < 0 || c[2] < 0) ? nbuckets - 1
362 : ((PetscInt64)(c[2] - lo[2]) * extent[1] + (c[1] - lo[1])) * extent[0] + (c[0] - lo[0]);
363 key[p] = (PetscInt)b;
364 if (p > 0 && key[p] < key[p - 1]) sorted = PETSC_FALSE;
365 start[b + 1]++;
366 }
367 PetscCall(DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_CELL_ID), NULL, NULL, (void **)&cells));
368 if (sorted) {
369 PetscCall(PetscFree(start));
370 PetscCall(PetscFree2(key, order));
372 PetscFunctionReturn(0);
373 }
374
375 // Stable counting sort: order[new position] = old position.
376 for (PetscInt64 b = 0; b < nbuckets; ++b) start[b + 1] += start[b];
377 for (PetscInt p = 0; p < n_local; ++p) order[start[key[p]]++] = p;
378 PetscCall(PetscFree(start));
379
380 // Permute every catalogued field through one buffer sized for the widest.
381 for (PetscInt id = 0; id < PARTICLE_FIELD_ID_COUNT; ++id) {
382 PetscInt bs;
383 PetscDataType type;
384 size_t type_bytes;
385 void *data;
386 PetscCall(DMSwarmGetField(swarm, ParticleFieldName((ParticleFieldId)id), &bs, &type, &data));
387 PetscCall(PetscDataTypeGetSize(type, &type_bytes));
388 max_bytes = PetscMax(max_bytes, (size_t)bs * type_bytes);
389 PetscCall(DMSwarmRestoreField(swarm, ParticleFieldName((ParticleFieldId)id), &bs, &type, &data));
390 }
391 PetscCall(PetscMalloc1((size_t)n_local * max_bytes, &buffer));
392 for (PetscInt id = 0; id < PARTICLE_FIELD_ID_COUNT; ++id) {
393 PetscInt bs;
394 PetscDataType type;
395 size_t type_bytes, bytes;
396 char *data;
397 PetscCall(DMSwarmGetField(swarm, ParticleFieldName((ParticleFieldId)id), &bs, &type, (void **)&data));
398 PetscCall(PetscDataTypeGetSize(type, &type_bytes));
399 bytes = (size_t)bs * type_bytes;
400 // A size known at compile time lets each record copy compile to a few loads and stores
401 // instead of a library call per particle; these are the sizes the particle fields use.
402 switch (bytes) {
403 case 4: GatherSwarmRecords(buffer, data, order, n_local, 4); break;
404 case 8: GatherSwarmRecords(buffer, data, order, n_local, 8); break;
405 case 12: GatherSwarmRecords(buffer, data, order, n_local, 12); break;
406 case 24: GatherSwarmRecords(buffer, data, order, n_local, 24); break;
407 default: GatherSwarmRecords(buffer, data, order, n_local, bytes); break;
408 }
409 memcpy(data, buffer, (size_t)n_local * bytes);
410 PetscCall(DMSwarmRestoreField(swarm, ParticleFieldName((ParticleFieldId)id), &bs, &type, (void **)&data));
411 }
412 PetscCall(PetscFree(buffer));
413 PetscCall(PetscFree2(key, order));
415 PetscFunctionReturn(0);
416}
static PICURV_ALWAYS_INLINE void GatherSwarmRecords(char *out, const char *in, const PetscInt *order, PetscInt n, size_t bytes)
Copies n fixed-size records into out in the order order[] gives (out[p] = in[order[p]]).
ParticleFieldId
Compile-time identity for a persistent solver-particle field.
@ PARTICLE_FIELD_ID_COUNT
Here is the call graph for this function:
Here is the caller graph for this function:

◆ PerformMigration()

PetscErrorCode PerformMigration ( UserCtx *  user,
PetscInt *  n_survivors 
)

Implementation of PerformMigration().

Performs particle migration based on the pre-populated DMSwarmPICField_rank field.

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

See also
PerformMigration()

Definition at line 425 of file ParticleMotion.c.

426{
427 PetscErrorCode ierr;
428 DM swarm = user->swarm;
429 PetscMPIInt rank;
430 PetscInt nlocal_before;
431 PetscInt *rank_p = NULL;
432 PetscBool *sent = NULL;
433
434 PetscFunctionBeginUser;
436 rank = user->simCtx->rank;
437 LOG_ALLOW(GLOBAL, LOG_INFO, "Rank %d: Starting DMSwarmMigrate...\n", rank);
438 ierr = DMSwarmGetLocalSize(swarm, &nlocal_before); CHKERRQ(ierr);
439
440 // Perform the migration but keep the sent particles: PETSc would remove them one
441 // at a time, each removal re-zeroing the whole swarm buffer. Received particles
442 // are appended after the first nlocal_before entries.
443 ierr = DMSwarmMigrate(swarm, PETSC_FALSE); CHKERRQ(ierr);
444
445 // Remove every particle that was sent away (rank field not this rank) in one pass.
446 ierr = PetscMalloc1(nlocal_before, &sent); CHKERRQ(ierr);
447 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_RANK), NULL, NULL, (void **)&rank_p); CHKERRQ(ierr);
448 PetscInt n_sent = 0;
449 for (PetscInt p = 0; p < nlocal_before; ++p) {
450 sent[p] = (PetscBool)(rank_p[p] != rank);
451 if (sent[p]) n_sent++;
452 }
453 if (n_survivors) *n_survivors = nlocal_before - n_sent;
454 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_RANK), NULL, NULL, (void **)&rank_p); CHKERRQ(ierr);
455 ierr = RemoveFlaggedParticles(swarm, nlocal_before, sent, PETSC_FALSE); CHKERRQ(ierr);
456 ierr = PetscFree(sent); CHKERRQ(ierr);
457
458 LOG_ALLOW(GLOBAL, LOG_INFO, "Rank %d: Migration complete.\n", rank);
460 PetscFunctionReturn(0);
461}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ CalculateParticleCountPerCell()

PetscErrorCode CalculateParticleCountPerCell ( UserCtx *  user)

Implementation of CalculateParticleCountPerCell().

Counts particles in each cell of the DMDA 'da' and stores the result in user->ParticleCount.

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

See also
CalculateParticleCountPerCell()

Definition at line 473 of file ParticleMotion.c.

473 {
474 PetscErrorCode ierr;
475 DM da = user->da;
476 DM swarm = user->swarm;
477 Vec countVec = user->ParticleCount;
478 Vec localcountVec = user->lParticleCount;
479 PetscInt nlocal, p;
480 PetscInt *global_cell_id_arr; // Read GLOBAL cell IDs
481 PetscScalar ***count_arr_3d; // Use 3D accessor
482 PetscInt64 *PID_arr;
483 PetscMPIInt rank;
484 char msg[ERROR_MSG_BUFFER_SIZE];
485 PetscInt particles_counted_locally = 0;
486
487 PetscFunctionBeginUser;
489 rank = user->simCtx->rank;
490
491 // --- Input Validation ---
492 if (!da) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "UserCtx->da is NULL.");
493 if (!swarm) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "UserCtx->swarm is NULL.");
494 if (!countVec) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "UserCtx->ParticleCount is NULL.");
495 // Check DOF of da
496 PetscInt count_dof;
497 count_dof = user->info.dof;
498 if (count_dof != 1) {
499 PetscSNPrintf(msg, sizeof(msg), "countDM must have DOF=1, got %" PetscInt_FMT ".", count_dof);
500 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "%s", msg);
501 }
502
503 // --- Zero the local count vector ---
504 ierr = VecSet(localcountVec, 0.0); CHKERRQ(ierr);
505
506 // --- Get Particle Data ---
507 LOG_ALLOW(GLOBAL,LOG_DEBUG, "Accessing particle data.\n");
508 ierr = DMSwarmGetLocalSize(swarm, &nlocal); CHKERRQ(ierr);
509 ierr = DMSwarmGetField(swarm,ParticleFieldName(PARTICLE_FIELD_ID_CELL_ID), NULL, NULL, (void **)&global_cell_id_arr); CHKERRQ(ierr);
510 ierr = DMSwarmGetField(swarm,ParticleFieldName(PARTICLE_FIELD_ID_PID),NULL,NULL,(void **)&PID_arr);CHKERRQ(ierr);
511
512 // --- Get Grid Vector Array using DMDA accessor ---
513 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Accessing ParticleCount vector array (using DMDAVecGetArray).\n");
514 ierr = DMDAVecGetArray(da, localcountVec, &count_arr_3d); CHKERRQ(ierr);
515
516 // Get local owned + ghosted range for writing into ghost slots.
517 PetscInt gxs, gys, gzs, gxm, gym, gzm;
518 gxs = user->info.gxs; gys = user->info.gys; gzs = user->info.gzs;
519 gxm = user->info.gxm; gym = user->info.gym; gzm = user->info.gzm;
520
521 // --- Accumulate Counts Locally ---
522 LOG_ALLOW(LOCAL, LOG_DEBUG, "CalculateParticleCountPerCell (Rank %d): Processing %" PetscInt_FMT " local particles using GLOBAL CellIDs.\n",rank,nlocal);
523 for (p = 0; p < nlocal; p++) {
524 // Read the GLOBAL indices stored for this particle
525 PetscInt i_geom = global_cell_id_arr[p * 3 + 0]; // Global i index
526 PetscInt j_geom = global_cell_id_arr[p * 3 + 1]; // Global j index
527 PetscInt k_geom = global_cell_id_arr[p * 3 + 2]; // Global k index
528
529 // Apply the shift to ensure ParticleCount follows the indexing convention for cell-centered data in this codebase.
530 PetscInt i = (PetscInt)i_geom + 1; // Shift for cell-centered
531 PetscInt j = (PetscInt)j_geom + 1; // Shift for cell-centered
532 PetscInt k = (PetscInt)k_geom + 1; // Shift for cell-centered
533
534 // *** Bounds check is implicitly handled by DMDAVecGetArray for owned+ghost region ***
535 // However, accessing outside this region using global indices WILL cause an error.
536 // A preliminary check might still be wise if global IDs could be wild.
537 // We rely on LocateAllParticles to provide valid global indices [0..IM-1] etc.
538
540 "[Rank %d] Read CellID for p=%" PetscInt_FMT ", PID = %" PetscInt64_FMT ": (%" PetscInt_FMT ", %" PetscInt_FMT ", %" PetscInt_FMT ")\n",
541 rank, p, PID_arr[p], i, j, k);
542
543 // Check if the global index (i,j,k) falls within the local + ghost range
544 if (i >= gxs && i < gxs + gxm &&
545 j >= gys && j < gys + gym && // Adjust based on actual ghost width
546 k >= gzs && k < gzs + gzm ) // This check prevents definite crashes but doesn't guarantee ownership
547 {
548
549 // Increment count at the location corresponding to GLOBAL index (I,J,K)
550 // LOG_ALLOW(LOCAL, LOG_DEBUG, "CalculateParticleCountPerCell (Rank %d): Particle %d with global CellID (%d, %d, %d) incremented with a particle.\n",rank, p, i, j, k);
551 count_arr_3d[k][j][i] += 1.0;
552 particles_counted_locally++;
553 } else {
554 // This particle's global ID is likely outside the range this rank handles (even ghosts)
555 // note: this is not necessarily an error if the particle is legitimately outside the local+ghost region
557 "(Rank %d): Skipping particle %" PetscInt64_FMT " with global CellID (%" PetscInt_FMT ", %" PetscInt_FMT ", %" PetscInt_FMT ") - likely outside local+ghost range.\n",
558 rank, PID_arr[p], i, j, k);
559 }
560 }
561 LOG_ALLOW(LOCAL, LOG_DEBUG, "(Rank %d): Local counting finished. Processed %" PetscInt_FMT " particles locally.\n", rank, particles_counted_locally);
562
563 // --- Restore Access ---
564 ierr = DMDAVecRestoreArray(da, localcountVec, &count_arr_3d); CHKERRQ(ierr);
565 ierr = DMSwarmRestoreField(swarm,ParticleFieldName(PARTICLE_FIELD_ID_CELL_ID), NULL, NULL, (void **)&global_cell_id_arr); CHKERRQ(ierr);
566 ierr = DMSwarmRestoreField(swarm,ParticleFieldName(PARTICLE_FIELD_ID_PID),NULL,NULL,(void **)&PID_arr);CHKERRQ(ierr);
567
568 // --- Assemble Global Vector ---
569 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Assembling global ParticleCount vector.\n");
570 ierr = VecZeroEntries(countVec); CHKERRQ(ierr); // Ensure global vector is zeroed before accumulation
571 ierr = DMLocalToGlobalBegin(da, localcountVec, ADD_VALUES, countVec); CHKERRQ(ierr);
572 ierr = DMLocalToGlobalEnd(da, localcountVec, ADD_VALUES, countVec); CHKERRQ(ierr);
573 // The ghost cells of localcountVec still hold only this rank's particles. A caller that
574 // reads neighbour counts refreshes them with UpdateLocalGhosts(user, FIELD_ID_PARTICLE_COUNT).
575
576 // The total and the fullest cell are reductions, so they are taken only when they are
577 // printed; the level and the allow-list are the same on every rank.
579 PetscReal total_counted_particles = 0.0, max_count_in_cell = 0.0;
580 ierr = VecSum(countVec, &total_counted_particles); CHKERRQ(ierr);
581 ierr = VecMax(countVec, NULL, &max_count_in_cell); CHKERRQ(ierr);
582 LOG_ALLOW(GLOBAL, LOG_INFO, "Total counted globally = %.0f, Max count in cell = %.0f\n",
583 total_counted_particles, max_count_in_cell);
584 }
585
586 LOG_ALLOW(GLOBAL, LOG_INFO, "Particle counting complete.\n");
587
588
590 PetscFunctionReturn(0);
591}
#define ERROR_MSG_BUFFER_SIZE
#define LOG_LOOP_ALLOW(scope, level, iterVar, interval, fmt,...)
Logs a message inside a loop, but only every interval iterations.
Definition logging.h:380
@ LOG_VERBOSE
Extremely detailed logs, typically for development use only.
Definition logging.h:34
#define LOG_LEVEL_ADMITS(level)
True when a code-level diagnostic at level prints from the calling function.
Definition logging.h:198
Vec lParticleCount
Definition variables.h:1276
Vec ParticleCount
Definition variables.h:1276
DMDALocalInfo info
Definition variables.h:1169
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ResizeSwarmGlobally()

PetscErrorCode ResizeSwarmGlobally ( DM  swarm,
PetscInt  N_target 
)

Implementation of ResizeSwarmGlobally().

Resizes a swarm collectively to a target global particle count.

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

See also
ResizeSwarmGlobally()

Definition at line 602 of file ParticleMotion.c.

603{
604 PetscErrorCode ierr;
605 PetscInt N_current, N_final, nlocal_current, nlocal_target;
606 PetscMPIInt rank, size;
607 MPI_Comm comm;
608
609 PetscFunctionBeginUser;
611 ierr = PetscObjectGetComm((PetscObject)swarm, &comm); CHKERRQ(ierr);
612 ierr = MPI_Comm_rank(comm, &rank); CHKERRQ(ierr);
613 ierr = MPI_Comm_size(comm, &size); CHKERRQ(ierr);
614 PetscCheck(N_target >= 0, comm, PETSC_ERR_ARG_OUTOFRANGE,
615 "Target swarm size must be nonnegative; got %" PetscInt_FMT ".", N_target);
616 ierr = DMSwarmGetSize(swarm, &N_current); CHKERRQ(ierr);
617 ierr = DMSwarmGetLocalSize(swarm, &nlocal_current); CHKERRQ(ierr);
618 nlocal_target = N_target / size + (rank < N_target % size ? 1 : 0);
619
620 if (nlocal_current != nlocal_target) {
622 "Rank %d: resizing local swarm share from %" PetscInt_FMT
623 " to %" PetscInt_FMT ".\n",
624 rank, nlocal_current, nlocal_target);
625 ierr = DMSwarmSetLocalSizes(swarm, nlocal_target, -1); CHKERRQ(ierr);
626 }
627
628 // Verify final size
629 ierr = DMSwarmGetSize(swarm, &N_final); CHKERRQ(ierr);
630 if (N_final != N_target) {
631 SETERRQ(comm, PETSC_ERR_PLIB,
632 "Failed to resize swarm: expected %" PetscInt_FMT
633 " particles, got %" PetscInt_FMT, N_target, N_final);
634 }
636 "Swarm resized from %" PetscInt_FMT " to %" PetscInt_FMT " particles.\n",
637 N_current, N_final);
639 PetscFunctionReturn(0);
640}
Here is the caller graph for this function:

◆ PreCheckAndResizeSwarm()

PetscErrorCode PreCheckAndResizeSwarm ( UserCtx *  user,
PetscInt  ti,
const char *  ext 
)

Implementation of PreCheckAndResizeSwarm().

Checks particle count in the reference file and resizes the swarm if needed.

See also
PreCheckAndResizeSwarm()

Definition at line 646 of file ParticleMotion.c.

649{
650 PetscErrorCode ierr;
651 PetscInt N_file = 0;
652 PetscInt N_current = 0;
653
654 PetscFunctionBeginUser;
656 (void)ext;
657 ierr = ReadCheckpointParticleCount(user, ti, &N_file); CHKERRQ(ierr);
659 "Committed checkpoint step %" PetscInt_FMT " records %" PetscInt_FMT " particles.\n", ti, N_file);
660
661
662 // --- Now all ranks have the correct N_file, compare and resize if needed ---
663 ierr = DMSwarmGetSize(user->swarm, &N_current); CHKERRQ(ierr);
664
665 if (N_file != N_current) {
666 LOG_ALLOW(GLOBAL, LOG_INFO, "Swarm size %" PetscInt_FMT " differs from file size %" PetscInt_FMT ". Resizing swarm globally.\n", N_current, N_file);
667 ierr = ResizeSwarmGlobally(user->swarm, N_file); CHKERRQ(ierr);
668 } else {
669 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Swarm size (%" PetscInt_FMT ") already matches file size. No resize needed.\n", N_current);
670 }
671
672 // Also update the context
673 user->simCtx->np = N_file;
674
676 PetscFunctionReturn(0);
677}
PetscErrorCode ResizeSwarmGlobally(DM swarm, PetscInt N_target)
Implementation of ResizeSwarmGlobally().
PetscErrorCode ReadCheckpointParticleCount(UserCtx *user, PetscInt ti, PetscInt *particle_count)
Read the particle count from a validated committed checkpoint.
Definition io.c:1868
PetscInt np
Definition variables.h:1049
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GetLocalPIDSnapshot()

PetscErrorCode GetLocalPIDSnapshot ( const PetscInt64  pid_field[],
PetscInt  n_local,
PetscInt64 **  pids_snapshot_out 
)

Implementation of GetLocalPIDSnapshot().

Creates a sorted snapshot of all Particle IDs (PIDs) from a raw data array.

See also
GetLocalPIDSnapshot()

Definition at line 684 of file ParticleMotion.c.

687{
688 PetscErrorCode ierr;
689 PetscMPIInt rank;
690
691 PetscFunctionBeginUser;
692
694
695 // --- 1. Input Validation ---
696 if (!pids_snapshot_out) {
697 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Output pointer pids_snapshot_out is NULL.");
698 }
699 // If n_local > 0, pid_field must not be NULL.
700 if (n_local > 0 && !pid_field) {
701 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Input pid_field pointer is NULL for n_local > 0.");
702 }
703
704 rank = PetscGlobalRank;
705 LOG_ALLOW(LOCAL, LOG_DEBUG, "[Rank %d]: Creating PID snapshot for %" PetscInt_FMT " local particles.\n", rank, n_local);
706
707 // If there are no local particles, the snapshot is empty (NULL).
708 if (n_local == 0) {
709 *pids_snapshot_out = NULL;
710
712 PetscFunctionReturn(0);
713 }
714
715 // --- 2. Allocate Memory for the Snapshot ---
716 ierr = PetscMalloc1(n_local, pids_snapshot_out); CHKERRQ(ierr);
717
718 // --- 3. Copy Data ---
719 // Perform a fast memory copy from the provided array to our new snapshot array.
720 ierr = PetscMemcpy(*pids_snapshot_out, pid_field, n_local * sizeof(PetscInt64)); CHKERRQ(ierr);
721 LOG_ALLOW(LOCAL, LOG_DEBUG, "[Rank %d]: Copied %" PetscInt_FMT " PIDs.\n", rank, n_local);
722
723 // --- 4. Sort the Snapshot Array ---
724 // Sorting enables fast binary search lookups later.
725 ierr = PetscSortInt64(n_local, *pids_snapshot_out); CHKERRQ(ierr);
726 LOG_ALLOW(LOCAL, LOG_DEBUG, "[Rank %d]: PID snapshot sorted successfully.\n", rank);
727
728
730 PetscFunctionReturn(0);
731}
Here is the caller graph for this function:

◆ AddToMigrationList()

PetscErrorCode AddToMigrationList ( MigrationInfo **  migration_list_p,
PetscInt *  capacity_p,
PetscInt *  count_p,
PetscInt  particle_local_idx,
PetscMPIInt  destination_rank 
)

Implementation of AddToMigrationList().

Safely adds a new migration task to a dynamically sized list.

See also
AddToMigrationList()

Definition at line 737 of file ParticleMotion.c.

742{
743 PetscErrorCode ierr;
744 PetscMPIInt rank;
745
746 PetscFunctionBeginUser;
747
749
750 // --- 1. Input Validation ---
751 if (!migration_list_p || !capacity_p || !count_p) {
752 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Null pointer provided to AddToMigrationList for list management.");
753 }
754
755 // --- 2. Check if the list needs to be resized ---
756 if (*count_p >= *capacity_p) {
757 PetscInt old_capacity = *capacity_p;
758 // Start with a reasonable base capacity, then double for subsequent reallocations.
759 PetscInt new_capacity = (old_capacity == 0) ? 16 : old_capacity * 2;
760
761 // Use PetscRealloc for safe memory reallocation.
762 // It handles allocating new memory, copying old data, and freeing the old block.
763 // The first argument to PetscRealloc is the new size in BYTES.
764 ierr = PetscRealloc(new_capacity * sizeof(MigrationInfo), migration_list_p); CHKERRQ(ierr);
765
766 *capacity_p = new_capacity; // Update the capacity tracker
767
768 rank = PetscGlobalRank;
769 LOG_ALLOW(LOCAL, LOG_DEBUG, "[Rank %d]: Reallocated migrationList capacity from %" PetscInt_FMT " to %" PetscInt_FMT ".\n",
770 rank, old_capacity, new_capacity);
771 }
772
773 // --- 3. Add the new migration data to the list ---
774 // Dereference the pointer-to-a-pointer to get the actual array.
775 MigrationInfo *list = *migration_list_p;
776
777 list[*count_p].local_index = particle_local_idx;
778 list[*count_p].target_rank = destination_rank;
779
780 // --- 4. Increment the count of items in the list ---
781 (*count_p)++;
782
783
785 PetscFunctionReturn(0);
786}
Information needed to migrate a single particle between MPI ranks.
Definition variables.h:269
Head of a generic C-style linked list.
Definition variables.h:504
Here is the caller graph for this function:

◆ VerifyNewcomersAgainstPIDs()

static PetscErrorCode VerifyNewcomersAgainstPIDs ( UserCtx *  user,
PetscInt  n_before,
const PetscInt64  pids_before[],
PetscInt  first_newcomer 
)
static

Requires the position-identified newcomers to be exactly the PID-identified ones, when -picurv_verify_ghost_updates is set.

A particle is a newcomer by PID when its PID is absent from the sorted pre-migration snapshot, and by position when it lies at or after the survivor count. The two must agree for every local particle.

Parameters
[in]userBlock context owning the swarm.
[in]n_beforeNumber of local particles before the migration.
[in]pids_beforeSorted PIDs of those particles (NULL when the check is off or n_before is 0).
[in]first_newcomerSurvivor count reported by PerformMigration().
Returns
0 when the check is off or passes; an error otherwise.

Definition at line 800 of file ParticleMotion.c.

802{
803 PetscInt n_after, mismatches = 0;
804 PetscInt64 *pid = NULL;
805
806 PetscFunctionBeginUser;
808 if (!user->simCtx->verifyGhostUpdates) { PROFILE_HELPER_END; PetscFunctionReturn(0); }
809 PetscCall(DMSwarmGetLocalSize(user->swarm, &n_after));
810 PetscCall(DMSwarmGetField(user->swarm, ParticleFieldName(PARTICLE_FIELD_ID_PID), NULL, NULL, (void **)&pid));
811 for (PetscInt p = 0; p < n_after; ++p) {
812 PetscBool was_here = PETSC_FALSE;
813 if (n_before > 0) PetscCall(BinarySearchInt64(n_before, pids_before, pid[p], &was_here));
814 if ((PetscBool)(p >= first_newcomer) == was_here) mismatches++;
815 }
816 PetscCall(DMSwarmRestoreField(user->swarm, ParticleFieldName(PARTICLE_FIELD_ID_PID), NULL, NULL, (void **)&pid));
817 PetscCheck(mismatches == 0, PETSC_COMM_SELF, PETSC_ERR_PLIB,
818 "Newcomer verification failed: %" PetscInt_FMT " of %" PetscInt_FMT " local particles disagree between position (first newcomer %" PetscInt_FMT ") and PID snapshot.",
819 mismatches, n_after, first_newcomer);
821 PetscFunctionReturn(0);
822}
PetscErrorCode BinarySearchInt64(PetscInt n, const PetscInt64 arr[], PetscInt64 key, PetscBool *found)
Performs a binary search for a key in a sorted array of PetscInt64.
Definition setup.c:3532
PetscBool verifyGhostUpdates
-picurv_verify_ghost_updates: test-only cross-checks of skipped or partial ghost updates,...
Definition variables.h:1108
Here is the call graph for this function:
Here is the caller graph for this function:

◆ FlagNewcomersForLocation()

PetscErrorCode FlagNewcomersForLocation ( DM  swarm,
PetscInt  n_local_before,
PetscInt  first_newcomer 
)

Implementation of FlagNewcomersForLocation().

Identifies newly arrived particles after migration and flags them for a location search.

See also
FlagNewcomersForLocation()

Definition at line 828 of file ParticleMotion.c.

829{
830 PetscMPIInt rank;
831 PetscInt n_local_after;
832 PetscInt *status = NULL;
833
834 PetscFunctionBeginUser;
836 PetscCheck(swarm, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Input DMSwarm is NULL in FlagNewcomersForLocation.");
837 rank = PetscGlobalRank;
838 PetscCall(DMSwarmGetLocalSize(swarm, &n_local_after));
839 LOG_ALLOW(LOCAL, LOG_DEBUG, "[Rank %d]: Checking for newcomers. Size before: %" PetscInt_FMT ", Size after: %" PetscInt_FMT "\n",
840 rank, n_local_before, n_local_after);
841 PetscCheck(first_newcomer >= 0 && first_newcomer <= n_local_after, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE,
842 "First newcomer index %" PetscInt_FMT " outside the %" PetscInt_FMT " local particles.", first_newcomer, n_local_after);
843 // Each newcomer reports itself in its next locate line, on this rank.
844 PetscCall(DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_LOCATION_STATUS), NULL, NULL, (void **)&status));
845 for (PetscInt p = first_newcomer; p < n_local_after; ++p) {
846 status[p] = NEEDS_LOCATION;
847 }
848 PetscCall(DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_LOCATION_STATUS), NULL, NULL, (void **)&status));
849 if (n_local_after > first_newcomer) {
850 LOG_ALLOW(LOCAL, LOG_DEBUG, "[Rank %d]: Identified and flagged %" PetscInt_FMT " newcomers.\n", rank, n_local_after - first_newcomer);
851 }
853 PetscFunctionReturn(0);
854}
@ NEEDS_LOCATION
Definition variables.h:187
Here is the call graph for this function:
Here is the caller graph for this function:

◆ MigrateRestartParticlesUsingCellID()

PetscErrorCode MigrateRestartParticlesUsingCellID ( UserCtx *  user)

Implementation of MigrateRestartParticlesUsingCellID().

Fast-path migration for restart particles using preloaded Cell IDs.

See also
MigrateRestartParticlesUsingCellID()

Definition at line 860 of file ParticleMotion.c.

861{
862 PetscErrorCode ierr;
863 DM swarm = user->swarm;
864 PetscInt nlocal;
865 PetscInt *cell_p = NULL;
866 PetscInt64 *pid_p = NULL;
867 PetscMPIInt rank;
868
869 MigrationInfo *migrationList = NULL;
870 PetscInt local_migration_count = 0;
871 PetscInt migrationListCapacity = 0;
872 PetscInt global_migration_count = 0;
873
874 PetscFunctionBeginUser;
876 rank = user->simCtx->rank;
877
878 ierr = DMSwarmGetLocalSize(swarm, &nlocal); CHKERRQ(ierr);
879 LOG_ALLOW(LOCAL, LOG_DEBUG, "Checking %" PetscInt_FMT " restart particles for direct migration using CellIDs.\n", nlocal);
880
881 if (nlocal > 0) {
882 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_CELL_ID), NULL, NULL, (void**)&cell_p); CHKERRQ(ierr);
883 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_PID), NULL, NULL, (void**)&pid_p); CHKERRQ(ierr);
884
885 // Note: We do NOT need to modify the status field here.
886 // We trust the loaded status (ACTIVE_AND_LOCATED) is correct for the destination rank.
887
888 for (PetscInt p_idx = 0; p_idx < nlocal; ++p_idx) {
889 PetscInt ci = cell_p[3*p_idx + 0];
890 PetscInt cj = cell_p[3*p_idx + 1];
891 PetscInt ck = cell_p[3*p_idx + 2];
892
893 /* Skip particles with invalid Cell IDs (will be handled by LocateAllParticles) */
894 if (ci < 0 || cj < 0 || ck < 0) {
895 continue;
896 }
897
898 PetscMPIInt owner_rank;
899 ierr = FindOwnerOfCell(user, ci, cj, ck, &owner_rank); CHKERRQ(ierr);
900
901 if (owner_rank != -1 && owner_rank != rank) {
902 /* Particle belongs to another rank - migrate it */
903 ierr = AddToMigrationList(&migrationList, &migrationListCapacity, &local_migration_count,
904 p_idx, owner_rank); CHKERRQ(ierr);
905
906 LOG_PARTICLE(user->simCtx, pid_p[p_idx], "restart", "saved cell (%" PetscInt_FMT ",%" PetscInt_FMT ",%" PetscInt_FMT ") belongs to rank %d: migrating from rank %d\n",
907 ci, cj, ck, owner_rank, (int)rank);
908 }
909 }
910
911 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_CELL_ID), NULL, NULL, (void**)&cell_p); CHKERRQ(ierr);
912 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_PID), NULL, NULL, (void**)&pid_p); CHKERRQ(ierr);
913 }
914
915 /* Check if any rank needs to migrate particles */
916 ierr = MPI_Allreduce(&local_migration_count, &global_migration_count, 1, MPIU_INT, MPI_SUM, PETSC_COMM_WORLD); CHKERRQ(ierr);
917
918 if (global_migration_count > 0) {
919 LOG_ALLOW(GLOBAL, LOG_INFO, "Fast restart migration: Directly migrating %" PetscInt_FMT " particles using CellIDs.\n", global_migration_count);
920 ierr = SetMigrationRanks(user, migrationList, local_migration_count); CHKERRQ(ierr);
921 ierr = PerformMigration(user, NULL); CHKERRQ(ierr);
922 /* We do NOT flag newcomers here. We trust their loaded status (ACTIVE_AND_LOCATED) */
923 /* is valid for their destination rank. */
924 } else {
925 LOG_ALLOW(GLOBAL, LOG_INFO, "Fast restart migration: All particles are already on correct ranks.\n");
926 }
927
928 ierr = PetscFree(migrationList); CHKERRQ(ierr);
929
931 PetscFunctionReturn(0);
932}
PetscErrorCode AddToMigrationList(MigrationInfo **migration_list_p, PetscInt *capacity_p, PetscInt *count_p, PetscInt particle_local_idx, PetscMPIInt destination_rank)
Implementation of AddToMigrationList().
PetscErrorCode SetMigrationRanks(UserCtx *user, const MigrationInfo *migrationList, PetscInt migrationCount)
Implementation of SetMigrationRanks().
PetscErrorCode PerformMigration(UserCtx *user, PetscInt *n_survivors)
Implementation of PerformMigration().
PetscErrorCode FindOwnerOfCell(UserCtx *user, PetscInt i, PetscInt j, PetscInt k, PetscMPIInt *owner_rank)
Finds the MPI rank that owns a given global cell index.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GuessParticleOwnerWithBBox()

static PetscErrorCode GuessParticleOwnerWithBBox ( UserCtx *  user,
const Particle *  particle,
const BoundingBox *  bboxlist,
PetscMPIInt *  guess_rank_out 
)
static

Select the rank whose gathered bounding box is the best owner candidate for a particle.

Tries this rank, then the neighbour across the face, edge or corner the particle left by (from the stored DMDAGetNeighbors() ranks, wrapped on periodic axes), then, because the bounding boxes of curvilinear subdomains overlap, the face neighbours on each axis it left by, and finally every rank. The guess only picks where the walk runs next; the walk decides the owner.

Note
Testing status: The current direct surface reaches this helper through orchestrator tests, but direction-complete immediate-neighbor coverage and the explicit "not found in any rank" path are still targeted for future bespoke tests.

Definition at line 947 of file ParticleMotion.c.

951{
952 PetscMPIInt rank, size;
953 const PetscMPIInt *neighbor;
954 const BoundingBox *localBBox;
955
956 PetscFunctionBeginUser;
957
959
960 if (!user || !particle || !guess_rank_out || !bboxlist) {
961 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Null pointer provided to GuessParticleOwnerWithBBox.");
962 }
963 neighbor = user->neighbors.rank;
964 localBBox = &user->bbox;
965 rank = user->simCtx->rank;
966 size = user->simCtx->size;
967
968 *guess_rank_out = MPI_PROC_NULL; // Default to "not found"
969
970 // The caller reports the guess's result in the particle's locate line.
971 // --- 1. This rank: initial placement leaves particles "lost" that are physically local ---
972 if (IsParticleInBox(localBBox, &particle->loc)) {
973 *guess_rank_out = rank;
975 PetscFunctionReturn(0);
976 }
977
978 // --- 2. The neighbour across the face, edge or corner it left by ---
979 const PetscBool low[3] = {particle->loc.x < localBBox->min_coords.x, particle->loc.y < localBBox->min_coords.y,
980 particle->loc.z < localBBox->min_coords.z};
981 const PetscBool high[3] = {particle->loc.x > localBBox->max_coords.x, particle->loc.y > localBBox->max_coords.y,
982 particle->loc.z > localBBox->max_coords.z};
983 PetscInt step[3];
984 for (PetscInt d = 0; d < 3; ++d) step[d] = high[d] ? 1 : (low[d] ? -1 : 0);
985 const PetscMPIInt across = neighbor[RANK_NEIGHBOR_INDEX(step[0], step[1], step[2])];
986 if (across != MPI_PROC_NULL && across != rank && IsParticleInBox(&bboxlist[across], &particle->loc)) {
987 *guess_rank_out = across;
989 PetscFunctionReturn(0);
990 }
991
992 // --- 3. Bounding boxes of curvilinear subdomains overlap, so a face neighbour may hold a
993 // particle that left across an edge or corner. A face neighbour that is the one
994 // tried above, which it is when only one axis was left by, is not tried again. ---
995 for (PetscInt d = 0; d < 3; ++d) {
996 for (PetscInt side = -1; side <= 1; side += 2) {
997 PetscInt offset[3] = {0, 0, 0};
998 if (!((side < 0) ? low[d] : high[d])) continue;
999 offset[d] = side;
1000 const PetscMPIInt face = neighbor[RANK_NEIGHBOR_INDEX(offset[0], offset[1], offset[2])];
1001 if (face != MPI_PROC_NULL && face != across && IsParticleInBox(&bboxlist[face], &particle->loc)) {
1002 *guess_rank_out = face;
1004 PetscFunctionReturn(0);
1005 }
1006 }
1007 }
1008
1009 // --- 4. Every other rank ---
1010 for (PetscMPIInt r = 0; r < size; ++r) {
1011 if (r == rank) continue;
1012 if (IsParticleInBox(&bboxlist[r], &particle->loc)) {
1013 *guess_rank_out = r;
1015 PetscFunctionReturn(0);
1016 }
1017 }
1018
1019 // Not in any rank's bounding box: guess_rank_out stays MPI_PROC_NULL, signaling failure to the caller.
1021 PetscFunctionReturn(0);
1022}
static PetscBool IsParticleInBox(const BoundingBox *bbox, const Cmpnts *pos)
Whether a position lies in an axis-aligned bounding box, faces included.
#define RANK_NEIGHBOR_INDEX(di, dj, dk)
Index in RankNeighbors::rank of the neighbour offset (di, dj, dk), each -1, 0 or 1.
Definition variables.h:250
Cmpnts max_coords
Maximum x, y, z coordinates of the bounding box.
Definition variables.h:214
RankNeighbors neighbors
Definition variables.h:1174
Cmpnts min_coords
Minimum x, y, z coordinates of the bounding box.
Definition variables.h:213
PetscMPIInt rank[27]
Definition variables.h:259
PetscMPIInt size
Definition variables.h:920
BoundingBox bbox
Definition variables.h:1173
Defines a 3D axis-aligned bounding box.
Definition variables.h:212
Here is the call graph for this function:
Here is the caller graph for this function:

◆ LocateAllParticlesInGrid()

PetscErrorCode LocateAllParticlesInGrid ( UserCtx *  user,
BoundingBox *  bboxlist 
)

Implementation of LocateAllParticlesInGrid().

Orchestrates the complete particle location and migration process for one timestep.

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

See also
LocateAllParticlesInGrid()

Definition at line 1030 of file ParticleMotion.c.

1031{
1032 PetscErrorCode ierr;
1033 PetscInt passes = 0;
1034 const PetscInt MAX_MIGRATION_PASSES = 50; // Safety break for runaway loops
1035 PetscInt global_migrations_this_pass;
1036 PetscMPIInt rank;
1037 PetscInt total_migrated_this_timestep = 0;
1038
1039 PetscFunctionBeginUser;
1041 rank = user->simCtx->rank;
1042 ierr = ResetSearchMetrics(user->simCtx); CHKERRQ(ierr);
1043 LOG_ALLOW(GLOBAL, LOG_INFO, "LocateAllParticlesInGrid (Orchestrator) - Beginning particle settlement process.\n");
1044
1045 // This loop ensures that particles that jump across multiple ranks are
1046 // handled correctly in successive, iterative handoffs.
1047 do {
1048 passes++;
1050 LOG_ALLOW(GLOBAL, LOG_INFO, "Starting migration pass %" PetscInt_FMT ".\n", passes);
1051
1052 // --- STAGE 1: PER-PASS INITIALIZATION ---
1053 MigrationInfo *migrationList = NULL;
1054 PetscInt local_migration_count = 0;
1055 PetscInt migrationListCapacity = 0;
1056 PetscInt nlocal_before;
1057 PetscInt64 *pids_before_snapshot = NULL;
1058 PetscInt local_lost_count = 0;
1059
1060 ierr = DMSwarmGetLocalSize(user->swarm, &nlocal_before); CHKERRQ(ierr);
1061 if (passes == 1) {
1062 user->simCtx->searchMetrics.searchPopulation += (PetscInt64)nlocal_before;
1063 }
1064 LOG_ALLOW(LOCAL, LOG_DEBUG, "[Rank %d] Pass %" PetscInt_FMT " begins with %" PetscInt_FMT " local particles.\n", rank, passes, nlocal_before);
1065
1066
1067 // --- STAGE 2: PRE-MIGRATION SNAPSHOT & MAIN PROCESSING LOOP ---
1068 if (nlocal_before > 0) {
1069 // Get pointers to all fields needed for this pass
1070 PetscReal *pos_p, *weights_p, *vel_p;
1071 PetscInt *cell_p, *status_p;
1072 PetscInt64 *pid_p;
1073 ierr = DMSwarmGetField(user->swarm, ParticleFieldName(PARTICLE_FIELD_ID_POSITION), NULL, NULL, (void**)&pos_p); CHKERRQ(ierr);
1074 ierr = DMSwarmGetField(user->swarm, ParticleFieldName(PARTICLE_FIELD_ID_VELOCITY), NULL, NULL, (void**)&vel_p); CHKERRQ(ierr);
1075 ierr = DMSwarmGetField(user->swarm, ParticleFieldName(PARTICLE_FIELD_ID_WEIGHT), NULL, NULL, (void**)&weights_p); CHKERRQ(ierr);
1076 ierr = DMSwarmGetField(user->swarm, ParticleFieldName(PARTICLE_FIELD_ID_CELL_ID), NULL, NULL, (void**)&cell_p); CHKERRQ(ierr);
1077 ierr = DMSwarmGetField(user->swarm, ParticleFieldName(PARTICLE_FIELD_ID_PID), NULL, NULL, (void**)&pid_p); CHKERRQ(ierr);
1078 ierr = DMSwarmGetField(user->swarm, ParticleFieldName(PARTICLE_FIELD_ID_LOCATION_STATUS), NULL, NULL, (void**)&status_p); CHKERRQ(ierr);
1079 // Opened once for the pass rather than by each particle's walk.
1080 FacePlaneArrays plane_arrays;
1081 ierr = MetricGetFacePlaneArrays(user, PETSC_FALSE, &plane_arrays); CHKERRQ(ierr);
1082
1083 // Newcomers are identified by position after migration; the sorted PID snapshot is
1084 // taken only to cross-check that under -picurv_verify_ghost_updates.
1085 if (user->simCtx->verifyGhostUpdates) {
1086 ierr = GetLocalPIDSnapshot(pid_p, nlocal_before, &pids_before_snapshot); CHKERRQ(ierr);
1087 }
1088
1089 for (PetscInt p_idx = 0; p_idx < nlocal_before; p_idx++) {
1090
1091 // LOST and EXITED are final within one settlement: only pass 1 searches them, so a
1092 // particle beyond the boundary is never re-walked and re-migrated pass after pass.
1093 if (status_p[p_idx] == ACTIVE_AND_LOCATED ||
1094 (passes > 1 && (status_p[p_idx] == LOST || status_p[p_idx] == EXITED))) {
1095 continue;
1096 }
1097
1098 // UNPACK: Create a temporary C struct for easier processing using our helper.
1099 Particle current_particle;
1100 ierr = UnpackSwarmFields(p_idx, pid_p, weights_p, pos_p, cell_p, vel_p, status_p,NULL,NULL,NULL,&current_particle); CHKERRQ(ierr);
1101
1102 ParticleLocationStatus final_status = (ParticleLocationStatus)status_p[p_idx];
1103 const PetscBool walk_from_prior_cell = (PetscBool)(current_particle.cell[0] >= 0);
1104
1105 // CASE 1: Particle has a valid prior cell index.
1106 // It has moved, so we only need to run the robust walk from its last known location.
1107 if (walk_from_prior_cell) {
1108 ierr = LocateParticleOrFindMigrationTarget(user, &plane_arrays, &current_particle, &final_status); CHKERRQ(ierr);
1109 }
1110
1111 // CASE 2: Particle has no valid cell (cell = -1), or its walk from the prior cell was
1112 // blocked by the domain boundary and is retried here, in the same pass. Strategy: Guess -> Verify.
1113 if (!walk_from_prior_cell || final_status == NEEDS_LOCATION) {
1114 PetscMPIInt guessed_owner_rank = MPI_PROC_NULL;
1115 ierr = GuessParticleOwnerWithBBox(user, &current_particle, bboxlist, &guessed_owner_rank); CHKERRQ(ierr);
1116
1117 // If the guess finds a DIFFERENT rank, we can mark for migration and skip the walk.
1118 if (guessed_owner_rank != MPI_PROC_NULL && guessed_owner_rank != rank) {
1120 LOG_PARTICLE(user->simCtx, current_particle.PID, "locate", "pass %" PetscInt_FMT ": bounding box of rank %d holds (%.6e, %.6e, %.6e): migrating there unwalked\n",
1121 passes, guessed_owner_rank, current_particle.loc.x, current_particle.loc.y, current_particle.loc.z);
1122 final_status = MIGRATING_OUT;
1123 current_particle.destination_rank = guessed_owner_rank;
1124 } else {
1125 // The guess either found no owner or found this rank; either way the walk decides.
1127 LOG_PARTICLE(user->simCtx, current_particle.PID, "locate", "pass %" PetscInt_FMT ": bounding-box guess %s; walking\n",
1128 passes, (guessed_owner_rank == rank) ? "found this rank" : "found no rank");
1129 ierr = LocateParticleOrFindMigrationTarget(user, &plane_arrays, &current_particle, &final_status); CHKERRQ(ierr);
1130 }
1131 }
1132
1133 // --- PROCESS THE FINAL, DEFINITIVE STATUS ---
1134 current_particle.location_status = final_status;
1135 ierr = UpdateSwarmFields(p_idx, &current_particle, pos_p, vel_p, weights_p, cell_p, status_p,NULL,NULL,NULL); CHKERRQ(ierr);
1136
1137 if (final_status == MIGRATING_OUT) {
1138 ierr = AddToMigrationList(&migrationList, &migrationListCapacity, &local_migration_count, p_idx, current_particle.destination_rank); CHKERRQ(ierr);
1139 } else if (final_status == LOST) {
1140 local_lost_count++;
1142 } else if (final_status == EXITED) {
1144 } else if (final_status == ACTIVE_AND_LOCATED) {
1146 }
1147
1148 } // End of main particle processing loop
1149
1150 // Restore all the fields acquired for this pass.
1151 ierr = DMSwarmRestoreField(user->swarm, ParticleFieldName(PARTICLE_FIELD_ID_POSITION), NULL, NULL, (void**)&pos_p); CHKERRQ(ierr);
1152 ierr = DMSwarmRestoreField(user->swarm, ParticleFieldName(PARTICLE_FIELD_ID_VELOCITY), NULL, NULL, (void**)&vel_p); CHKERRQ(ierr);
1153 ierr = DMSwarmRestoreField(user->swarm, ParticleFieldName(PARTICLE_FIELD_ID_WEIGHT), NULL, NULL, (void**)&weights_p); CHKERRQ(ierr);
1154 ierr = DMSwarmRestoreField(user->swarm, ParticleFieldName(PARTICLE_FIELD_ID_CELL_ID), NULL, NULL, (void**)&cell_p); CHKERRQ(ierr);
1155 ierr = DMSwarmRestoreField(user->swarm, ParticleFieldName(PARTICLE_FIELD_ID_PID), NULL, NULL, (void**)&pid_p); CHKERRQ(ierr);
1156 ierr = DMSwarmRestoreField(user->swarm, ParticleFieldName(PARTICLE_FIELD_ID_LOCATION_STATUS), NULL, NULL, (void**)&status_p); CHKERRQ(ierr);
1157 ierr = MetricRestoreFacePlaneArrays(user, &plane_arrays); CHKERRQ(ierr);
1158 }
1159
1160 // --- STAGE 3: ACTION & MPI COMMUNICATION ---
1161 LOG_ALLOW(LOCAL, LOG_DEBUG, "[Rank %d] Pass %" PetscInt_FMT ": Identified %" PetscInt_FMT " particles to migrate out.\n", rank, passes, local_migration_count);
1162
1163 // --- STAGE 3: SYNCHRONIZE AND DECIDE ---
1164 // FIRST, determine if any rank wants to migrate. This call is safe because
1165 // all ranks have finished their local work and can participate.
1166 ierr = MPI_Allreduce(&local_migration_count, &global_migrations_this_pass, 1, MPIU_INT, MPI_SUM, PETSC_COMM_WORLD); CHKERRQ(ierr);
1167
1168 total_migrated_this_timestep += global_migrations_this_pass;
1169
1170 if(global_migrations_this_pass > 0 ){
1171
1172 LOG_ALLOW(GLOBAL, LOG_INFO, "Pass %" PetscInt_FMT ": Migrating %" PetscInt_FMT " particles globally.\n", passes, global_migrations_this_pass);
1173
1174 ierr = SetMigrationRanks(user, migrationList, local_migration_count); CHKERRQ(ierr);
1175 PetscInt n_survivors = 0;
1176 ierr = PerformMigration(user, &n_survivors); CHKERRQ(ierr);
1177
1178 // --- STAGE 4: POST-MIGRATION RESET ---
1179 // The received particles follow the survivors; flag them with NEEDS_LOCATION so
1180 // they are processed in the next pass.
1181 ierr = FlagNewcomersForLocation(user->swarm, nlocal_before, n_survivors); CHKERRQ(ierr);
1182 ierr = VerifyNewcomersAgainstPIDs(user, nlocal_before, pids_before_snapshot, n_survivors); CHKERRQ(ierr);
1183 }
1184 // --- STAGE 5: LOOP SYNCHRONIZATION AND CLEANUP ---
1185
1186 ierr = PetscFree(pids_before_snapshot);
1187 ierr = PetscFree(migrationList);
1188
1189 LOG_ALLOW(GLOBAL, LOG_INFO, "End of pass %" PetscInt_FMT ". Total particles migrated globally: %" PetscInt_FMT ".\n", passes, global_migrations_this_pass);
1190
1191 } while (global_migrations_this_pass > 0 && passes < MAX_MIGRATION_PASSES);
1192
1193 // --- FINAL CHECKS ---
1194 if (passes >= MAX_MIGRATION_PASSES) {
1195 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_CONV_FAILED, "Particle migration failed to converge after %" PetscInt_FMT " passes. Check for particles oscillating between ranks.", MAX_MIGRATION_PASSES);
1196 }
1197
1198 user->simCtx->particlesMigratedLastStep = total_migrated_this_timestep;
1199 user->simCtx->migrationPassesLastStep = passes;
1200 user->simCtx->searchMetrics.maxParticlePassDepth = PetscMax(user->simCtx->searchMetrics.maxParticlePassDepth, (PetscInt64)passes);
1202
1203 LOG_ALLOW(GLOBAL, LOG_INFO, "Particle Location completed in %" PetscInt_FMT " passes.\n", passes);
1204
1206 PetscFunctionReturn(0);
1207}
PetscErrorCode MetricRestoreFacePlaneArrays(UserCtx *user, FacePlaneArrays *arrays)
Closes arrays opened by MetricGetFacePlaneArrays().
Definition Metric.c:401
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
Read-only flat arrays of one family of face planes (grid cells or dual cells).
Definition Metric.h:528
static PetscErrorCode VerifyNewcomersAgainstPIDs(UserCtx *user, PetscInt n_before, const PetscInt64 pids_before[], PetscInt first_newcomer)
Requires the position-identified newcomers to be exactly the PID-identified ones, when -picurv_verify...
PetscErrorCode GetLocalPIDSnapshot(const PetscInt64 pid_field[], PetscInt n_local, PetscInt64 **pids_snapshot_out)
Implementation of GetLocalPIDSnapshot().
static PetscErrorCode GuessParticleOwnerWithBBox(UserCtx *user, const Particle *particle, const BoundingBox *bboxlist, PetscMPIInt *guess_rank_out)
Select the rank whose gathered bounding box is the best owner candidate for a particle.
PetscErrorCode FlagNewcomersForLocation(DM swarm, PetscInt n_local_before, PetscInt first_newcomer)
Implementation of FlagNewcomersForLocation().
PetscErrorCode ResetSearchMetrics(SimCtx *simCtx)
Resets the aggregate per-timestep search instrumentation counters.
Definition logging.c:3252
PetscInt64 searchLocatedCount
Definition variables.h:283
PetscInt64 searchLostCount
Definition variables.h:284
PetscInt cell[3]
Definition variables.h:238
@ ACTIVE_AND_LOCATED
Definition variables.h:188
@ MIGRATING_OUT
Definition variables.h:189
PetscInt64 searchPopulation
Definition variables.h:282
PetscInt currentSettlementPass
Definition variables.h:299
PetscInt64 searchExitedCount
Definition variables.h:294
PetscMPIInt destination_rank
Definition variables.h:243
PetscInt64 bboxGuessFallbackCount
Definition variables.h:292
ParticleLocationStatus location_status
Definition variables.h:242
PetscInt64 bboxGuessSuccessCount
Definition variables.h:291
PetscInt64 maxParticlePassDepth
Definition variables.h:293
PetscInt particlesMigratedLastStep
Definition variables.h:1067
SearchMetricsState searchMetrics
Definition variables.h:1073
PetscInt migrationPassesLastStep
Definition variables.h:1066
PetscErrorCode LocateParticleOrFindMigrationTarget(UserCtx *user, const struct FacePlaneArrays *planes, Particle *particle, ParticleLocationStatus *status_out)
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ResetAllParticleStatuses()

PetscErrorCode ResetAllParticleStatuses ( UserCtx *  user)

Implementation of ResetAllParticleStatuses().

Marks all local particles as NEEDS_LOCATION for the next settlement pass.

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

See also
ResetAllParticleStatuses()

Definition at line 1216 of file ParticleMotion.c.

1217{
1218 PetscErrorCode ierr;
1219 PetscInt n_local;
1220 PetscInt *status_p;
1221
1222 PetscFunctionBeginUser;
1223
1225
1226 ierr = DMSwarmGetLocalSize(user->swarm, &n_local); CHKERRQ(ierr);
1227
1228 if (n_local > 0) {
1229 // Get write access to the status field
1230 ierr = DMSwarmGetField(user->swarm, ParticleFieldName(PARTICLE_FIELD_ID_LOCATION_STATUS), NULL, NULL, (void**)&status_p); CHKERRQ(ierr);
1231
1232 for (PetscInt p = 0; p < n_local; ++p) {
1233 // Only reset particles that are considered settled. This is a small optimization
1234 // to avoid changing the status of a LOST particle, though resetting all would also be fine.
1235 if (status_p[p] == ACTIVE_AND_LOCATED) {
1236 status_p[p] = NEEDS_LOCATION;
1237 }
1238 }
1239
1240 // Restore the field
1241 ierr = DMSwarmRestoreField(user->swarm, ParticleFieldName(PARTICLE_FIELD_ID_LOCATION_STATUS), NULL, NULL, (void**)&status_p); CHKERRQ(ierr);
1242 }
1243
1244
1246 PetscFunctionReturn(0);
1247}
Here is the call graph for this function:
Here is the caller graph for this function: