PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
ParticleSwarm.c
Go to the documentation of this file.
1 // ParticleSwarm.c
2
3#include "ParticleSwarm.h"
5#include "ParticleMotion.h"
7
8#define INTERPOLATION_DISTANCE_TOLERANCE 1.0e-14
9
10/**
11 * @brief Implementation of \ref InitializeSwarm().
12 * @details Full API contract (arguments, ownership, side effects) is documented with
13 * the header declaration in `include/ParticleSwarm.h`.
14 * @see InitializeSwarm()
15 */
16PetscErrorCode InitializeSwarm(UserCtx* user) {
17 PetscErrorCode ierr; // Error code for PETSc functions
18
19 PetscFunctionBeginUser;
21 // Create the DMSwarm object for particle management
22 ierr = DMCreate(PETSC_COMM_WORLD, &user->swarm); CHKERRQ(ierr);
23 ierr = DMSetType(user->swarm, DMSWARM); CHKERRQ(ierr);
24 ierr = DMSetDimension(user->swarm, 3); CHKERRQ(ierr);
25 ierr = DMSwarmSetType(user->swarm, DMSWARM_BASIC); CHKERRQ(ierr);
26 LOG_ALLOW(LOCAL,LOG_INFO, "DMSwarm created and configured.\n");
27
29 PetscFunctionReturn(0);
30}
31
32
33/**
34 * @brief Implementation of \ref RegisterSwarmField().
35 * @see RegisterSwarmField()
36 */
37PetscErrorCode RegisterSwarmField(DM swarm, const char *fieldName, PetscInt fieldDim, PetscDataType dtype)
38{
39 PetscErrorCode ierr;
40 PetscFunctionBeginUser;
42
43 ierr = DMSwarmRegisterPetscDatatypeField(swarm, fieldName, fieldDim, dtype); CHKERRQ(ierr);
44 // PetscDataTypes is an extern char* [] defined in petscsystypes.h that gives string names for PetscDataType enums
45 LOG_ALLOW(LOCAL,LOG_DEBUG,"Registered field '%s' with dimension=%" PetscInt_FMT ", type=%s.\n",
46 fieldName, fieldDim, PetscDataTypes[dtype]);
47
49 PetscFunctionReturn(0);
50}
51
52
53/**
54 * @brief Implementation of \ref RegisterParticleFields().
55 * @details Full API contract (arguments, ownership, side effects) is documented with
56 * the header declaration in `include/ParticleSwarm.h`.
57 * @see RegisterParticleFields()
58 */
59
60PetscErrorCode RegisterParticleFields(DM swarm)
61{
62 PetscErrorCode ierr;
63 PetscFunctionBeginUser;
65
66 for (PetscInt raw_id = 0; raw_id < PARTICLE_FIELD_ID_COUNT; ++raw_id) {
67 const ParticleFieldDescriptor *descriptor = NULL;
68
69 ierr = ParticleFieldGetDescriptor((ParticleFieldId)raw_id, &descriptor); CHKERRQ(ierr);
70 if (descriptor->registration == PARTICLE_FIELD_REGISTRATION_PETSC) continue;
71
72 ierr = RegisterSwarmField(swarm, descriptor->canonical_name,
73 descriptor->components, descriptor->data_type); CHKERRQ(ierr);
74 }
75
76 // Finalize the field registration after all fields have been added
77 ierr = DMSwarmFinalizeFieldRegister(swarm); CHKERRQ(ierr);
78 LOG_ALLOW(LOCAL,LOG_INFO,"RegisterParticleFields - Finalized field registration.\n");
79
81 PetscFunctionReturn(0);
82}
83
84/**
85 * @brief The owned cells a seeding mode places particles in, and which particles each gets.
86 * @details Volumetric seeding uses the rank's owned cells and surface seeding the owned cells
87 * that touch the inlet face, so both are a box of cells from `origin` with `n` cells
88 * per axis (none when the rank owns no part of the target). Cell `c`, in i-fastest
89 * order, seeds the particles with IDs `pid_lo[c]` to `pid_hi[c] - 1`.
90 */
91typedef struct {
92 PetscInt face; /**< -1 for the volume, otherwise the BCFace the points lie on */
93 PetscInt origin[3]; /**< Origin node of the box's first cell */
94 PetscInt n[3]; /**< Cells per axis */
95 PetscInt64 *pid_lo; /**< First particle ID of each cell */
96 PetscInt64 *pid_hi; /**< One past the last particle ID of each cell */
97 PetscReal *bound; /**< Largest measure density in each cell (NULL when not built) */
98 PetscInt count; /**< Particles this rank seeds */
99 PetscReal total; /**< Measure of every cell on every rank: the domain's volume or the face's area */
101
102/* A seeding point's logical coordinates stay at or below 1 - SEEDING_LOGIC_MARGIN, for
103 MetricLogicalToPhysical(); a point on a face lies SEEDING_FACE_OFFSET of the cell inside it. */
104#define SEEDING_LOGIC_MARGIN 1.0e-7
105#define SEEDING_FACE_OFFSET 1.0e-6
106
107/** @brief Origin node of cell `c` of a seeding table, cells numbered i fastest. */
108static inline void SeedingCellOrigin(const SeedingCellTable *table, PetscInt c, PetscInt origin[3])
109{
110 origin[0] = table->origin[0] + c % table->n[0];
111 origin[1] = table->origin[1] + (c / table->n[0]) % table->n[1];
112 origin[2] = table->origin[2] + c / (table->n[0] * table->n[1]);
113}
114
115/**
116 * @brief Logical seeding coordinates from `u`: each clamped to [0, 1 - SEEDING_LOGIC_MARGIN], and
117 * for `face` >= 0 the normal one replaced by the point just inside that face.
118 */
119static inline void SeedingLogicalPoint(const PetscReal u[3], PetscInt face, PetscReal logic[3])
120{
121 for (PetscInt d = 0; d < 3; ++d) logic[d] = PetscMax(PetscMin(u[d], 1.0 - SEEDING_LOGIC_MARGIN), 0.0);
122 if (face >= 0) logic[face / 2] = (face % 2) ? 1.0 - SEEDING_FACE_OFFSET : SEEDING_FACE_OFFSET;
123}
124
125/**
126 * @brief Measure density at a logical point: the Jacobian determinant for the volume, or the
127 * area element |dx/ds x dx/dt| across the face for a face, with the normal coordinate
128 * on the face itself.
129 */
130static PetscErrorCode SeedingMeasureDensity(UserCtx *user, const Cmpnts ***coor, PetscInt face,
131 PetscInt i, PetscInt j, PetscInt k, const PetscReal logic[3],
132 PetscReal *density)
133{
134 PetscReal J[3][3], detJ, l[3] = {logic[0], logic[1], logic[2]};
135
136 PetscFunctionBeginUser;
138 if (face < 0) {
139 PetscCall(MetricJacobian(user, coor, i, j, k, l[0], l[1], l[2], J, &detJ));
140 *density = detJ;
141 } else {
142 const PetscInt a = face / 2, b = (a + 1) % 3, c = (a + 2) % 3;
143 Cmpnts cross;
144 l[a] = (face % 2) ? 1.0 : 0.0;
145 PetscCall(MetricJacobian(user, coor, i, j, k, l[0], l[1], l[2], J, NULL));
146 cross.x = J[1][b] * J[2][c] - J[2][b] * J[1][c];
147 cross.y = J[2][b] * J[0][c] - J[0][b] * J[2][c];
148 cross.z = J[0][b] * J[1][c] - J[1][b] * J[0][c];
149 *density = PetscSqrtReal(cross.x * cross.x + cross.y * cross.y + cross.z * cross.z);
150 }
152 PetscFunctionReturn(0);
153}
154
155/**
156 * @brief Decide which particles each owned cell seeds, the same way at every rank layout.
157 * @details Collective. The cells are those volumetric (`face` < 0) or surface seeding uses,
158 * and each cell's measure is its volume or its area on the face, integrated with 2x2x2
159 * Gauss points: exact for the volume (the determinant has degree 2 in each
160 * coordinate) and for the area of a planar face, where the points coincide in pairs
161 * and give the 2x2 rule.
162 *
163 * Particles are stratified over the measure in global cell order (i fastest): with
164 * P(c) the measure of all cells before cell c, T the total and N the particle count,
165 * cell c seeds the IDs floor(N P(c) / T) to floor(N (P(c) + m_c) / T) - 1, so each
166 * cell holds its expected share to within one, the IDs are 0..N-1, and both depend
167 * only on the grid. For the result to be identical at any rank layout the measures
168 * are summed as integers, each cell's measure quantised against the largest cell
169 * (an exact maximum) to 2^Q units, with Q chosen so the total fits 63 bits. P(c) is
170 * the sum of the (j,k) rows before the cell's row, from one reduction over the rows,
171 * plus the cells before it in its row, from a scan over the ranks sharing the row.
172 * @param[in] user Grid context.
173 * @param[in] coor Ghosted node-coordinate array.
174 * @param[in] face -1 for the volume, otherwise the BCFace to seed on.
175 * @param[in] numParticles Global particle count.
176 * @param[in] build_bound PETSC_TRUE to also tabulate each cell's largest measure density on
177 * a 3x3x3 lattice, the envelope DrawSeedingPoint samples against.
178 * @param[out] table The owned cells and their particles; free with FreeSeedingCellTable.
179 * @return PetscErrorCode 0 on success; an error for a cell whose measure is not positive.
180 */
181static PetscErrorCode BuildSeedingCellTable(UserCtx *user, const Cmpnts ***coor, PetscInt face,
182 PetscInt numParticles, PetscBool build_bound,
183 SeedingCellTable *table)
184{
185 const PetscReal gauss[2] = {0.5 - 0.5 / PetscSqrtReal(3.0), 0.5 + 0.5 / PetscSqrtReal(3.0)};
186 const PetscInt nodes[3] = {user->info.mx, user->info.my, user->info.mz};
187 PetscInt start, n_cells, n_rows_local, global_cells[3], global_origin[3] = {0, 0, 0}, quantum_bits = 62;
188 PetscInt64 n_global_cells;
189 PetscReal local_max = 0.0, global_max = 0.0;
190 PetscReal *measure = NULL;
191 uint64_t *rows = NULL, *row_before = NULL, *segment = NULL, *segment_before = NULL, *quanta = NULL;
192 uint64_t total = 0;
193 MPI_Comm row_comm = MPI_COMM_NULL;
194 PetscMPIInt row_rank = 0;
195
196 PetscFunctionBeginUser;
198 PetscCall(PetscMemzero(table, sizeof(*table)));
199 table->face = face;
200 table->origin[0] = user->info.xs; table->origin[1] = user->info.ys; table->origin[2] = user->info.zs;
201 PetscCall(GetOwnedCellRange(&user->info, 0, &start, &table->n[0]));
202 PetscCall(GetOwnedCellRange(&user->info, 1, &start, &table->n[1]));
203 PetscCall(GetOwnedCellRange(&user->info, 2, &start, &table->n[2]));
204 for (PetscInt d = 0; d < 3; ++d) global_cells[d] = nodes[d] - 2;
205 if (face >= 0) {
206 const PetscInt a = face / 2;
207 PetscBool holds_face = PETSC_FALSE;
208 PetscCall(CanRankServiceFace(&user->info, user->IM, user->JM, user->KM, (BCFace)face, &holds_face));
209 global_cells[a] = 1;
210 if (face % 2) global_origin[a] = nodes[a] - 3; /* origin node of the last cell */
211 if (holds_face) {
212 table->n[a] = 1;
213 table->origin[a] = global_origin[a];
214 } else {
215 table->n[0] = table->n[1] = table->n[2] = 0;
216 }
217 }
218 n_cells = table->n[0] * table->n[1] * table->n[2];
219 n_rows_local = table->n[1] * table->n[2];
220 n_global_cells = (PetscInt64)global_cells[0] * global_cells[1] * global_cells[2];
221 while (quantum_bits > 0 && ((PetscInt64)1 << (62 - quantum_bits)) < n_global_cells) --quantum_bits;
222
223 // --- 1. Cell measures, and the density envelope ---
224 PetscCall(PetscMalloc2(n_cells, &measure, n_cells, &quanta));
225 PetscCall(PetscMalloc2(n_cells, &table->pid_lo, n_cells, &table->pid_hi));
226 if (build_bound) PetscCall(PetscMalloc1(n_cells, &table->bound));
227 for (PetscInt c = 0; c < n_cells; ++c) {
228 PetscInt origin[3];
229 PetscReal density = 0.0;
230 SeedingCellOrigin(table, c, origin);
231 const PetscInt i = origin[0], j = origin[1], k = origin[2];
232 measure[c] = 0.0;
233 for (PetscInt g = 0; g < 8; ++g) {
234 const PetscReal l[3] = {gauss[g & 1], gauss[(g >> 1) & 1], gauss[(g >> 2) & 1]};
235 PetscCall(SeedingMeasureDensity(user, coor, face, i, j, k, l, &density));
236 measure[c] += 0.125 * density;
237 }
238 PetscCheck(measure[c] > 0.0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE,
239 "Cell with origin node (%d,%d,%d) has %s %g; particle seeding needs positive %s.",
240 (int)i, (int)j, (int)k, face < 0 ? "volume" : "inlet area", (double)measure[c],
241 face < 0 ? "volumes" : "areas");
242 local_max = PetscMax(local_max, measure[c]);
243 if (build_bound) {
244 table->bound[c] = 0.0;
245 for (PetscInt q = 0; q < 27; ++q) {
246 const PetscReal l[3] = {0.5 * (q % 3), 0.5 * ((q / 3) % 3), 0.5 * (q / 9)};
247 PetscCall(SeedingMeasureDensity(user, coor, face, i, j, k, l, &density));
248 table->bound[c] = PetscMax(table->bound[c], density);
249 }
250 }
251 }
252 {
253 PetscInt64 local_cells = n_cells, owned_cells = 0;
254 PetscCallMPI(MPI_Allreduce(&local_cells, &owned_cells, 1, MPIU_INT64, MPI_SUM, PETSC_COMM_WORLD));
255 PetscCheck(owned_cells == n_global_cells, PETSC_COMM_WORLD, PETSC_ERR_PLIB,
256 "Seeding cells owned across ranks (%" PetscInt64_FMT ") differ from the global count (%" PetscInt64_FMT ").",
257 owned_cells, n_global_cells);
258 }
259 PetscCallMPI(MPI_Allreduce(&local_max, &global_max, 1, MPIU_REAL, MPI_MAX, PETSC_COMM_WORLD));
260 PetscCheck(global_max > 0.0, PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONGSTATE,
261 face < 0 ? "Volumetric particle seeding found no owned volume on any rank."
262 : "Surface particle seeding found no inlet area on any rank; it needs an INLET face.");
263 {
264 uint64_t local_total = 0;
265 for (PetscInt c = 0; c < n_cells; ++c) {
266 quanta[c] = (uint64_t)PetscMax(1.0, PetscFloorReal(ldexp((double)(measure[c] / global_max), (int)quantum_bits) + 0.5));
267 local_total += quanta[c];
268 }
269 PetscCallMPI(MPI_Allreduce(&local_total, &total, 1, MPI_UINT64_T, MPI_SUM, PETSC_COMM_WORLD));
270 table->total = (PetscReal)ldexp((double)total, -(int)quantum_bits) * global_max;
271 }
272
273 if (numParticles == 0) {
274 // Nothing to place (an inlet's table): every cell's range is empty. numParticles is the
275 // same on every rank, so all of them skip the reductions below.
276 PetscCall(PetscArrayzero(table->pid_lo, n_cells));
277 PetscCall(PetscArrayzero(table->pid_hi, n_cells));
278 PetscCall(PetscFree2(measure, quanta));
280 PetscFunctionReturn(0);
281 }
282
283 // --- 2. Integer measures, summed over rows and over each rank's segment of a row ---
284 const PetscInt n_rows = global_cells[1] * global_cells[2];
285 PetscCall(PetscCalloc4(n_rows, &rows, n_rows, &row_before, n_rows_local, &segment, n_rows_local, &segment_before));
286 for (PetscInt c = 0; c < n_cells; ++c) {
287 const PetscInt lj = (c / table->n[0]) % table->n[1], lk = c / (table->n[0] * table->n[1]);
288 const PetscInt row = (table->origin[1] + lj - global_origin[1]) + global_cells[1] * (table->origin[2] + lk - global_origin[2]);
289 rows[row] += quanta[c];
290 segment[lj + table->n[1] * lk] += quanta[c];
291 }
292 PetscCallMPI(MPI_Allreduce(MPI_IN_PLACE, rows, (PetscMPIInt)n_rows, MPI_UINT64_T, MPI_SUM, PETSC_COMM_WORLD));
293 total = 0;
294 for (PetscInt r = 0; r < n_rows; ++r) { row_before[r] = total; total += rows[r]; }
295 // Ranks with the same j and k ranges share rows; their order along i is the order in the row.
296 PetscCallMPI(MPI_Comm_split(PETSC_COMM_WORLD, n_cells > 0 ? (PetscMPIInt)(table->origin[1] + nodes[1] * table->origin[2]) : MPI_UNDEFINED,
297 (PetscMPIInt)table->origin[0], &row_comm));
298 if (row_comm != MPI_COMM_NULL) {
299 PetscCallMPI(MPI_Exscan(segment, segment_before, (PetscMPIInt)n_rows_local, MPI_UINT64_T, MPI_SUM, row_comm));
300 PetscCallMPI(MPI_Comm_rank(row_comm, &row_rank));
301 if (row_rank == 0) PetscCall(PetscArrayzero(segment_before, n_rows_local)); /* MPI_Exscan leaves rank 0's result undefined */
302 PetscCallMPI(MPI_Comm_free(&row_comm));
303 }
304
305 // --- 3. Stratified particle IDs: floor(N P / T) at each cell boundary ---
306 for (PetscInt lrow = 0; lrow < n_rows_local; ++lrow) {
307 const PetscInt lj = lrow % table->n[1], lk = lrow / table->n[1];
308 const PetscInt row = (table->origin[1] + lj - global_origin[1]) + global_cells[1] * (table->origin[2] + lk - global_origin[2]);
309 uint64_t before = row_before[row] + segment_before[lrow];
310 for (PetscInt li = 0; li < table->n[0]; ++li) {
311 const PetscInt c = li + table->n[0] * lrow;
312 table->pid_lo[c] = (PetscInt64)(((unsigned __int128)numParticles * before) / total);
313 before += quanta[c];
314 table->pid_hi[c] = (PetscInt64)(((unsigned __int128)numParticles * before) / total);
315 table->count += (PetscInt)(table->pid_hi[c] - table->pid_lo[c]);
316 }
317 }
318 PetscCall(PetscFree4(rows, row_before, segment, segment_before));
319 PetscCall(PetscFree2(measure, quanta));
321 PetscFunctionReturn(0);
322}
323
324/** @brief Free the arrays of a SeedingCellTable. */
325static PetscErrorCode FreeSeedingCellTable(SeedingCellTable *table)
326{
327 PetscFunctionBeginUser;
329 PetscCall(PetscFree2(table->pid_lo, table->pid_hi));
330 PetscCall(PetscFree(table->bound));
332 PetscFunctionReturn(0);
333}
334
335/**
336 * @brief Draw one particle's seeding point inside its cell, uniform in the cell's measure, or
337 * on a face in proportion to the flux through it.
338 * @details Uniform logical coordinates are accepted with probability density / `bound`, times
339 * the inward normal velocity / `flux_bound` when `velocity` is given. Every draw is
340 * keyed on the run seed, the particle ID and the attempt, so the point depends only on
341 * the particle, not on the rank that seeds it. A surface point is put just inside the
342 * cell, SEEDING_FACE_OFFSET of the cell from the face, where its velocity is taken.
343 * @param[in] user Grid context.
344 * @param[in] coor Ghosted node-coordinate array.
345 * @param[in] table A table built with `build_bound` set.
346 * @param[in] c The cell, an index into the table.
347 * @param[in] pid The particle's ID.
348 * @param[in] velocity NULL, or for a face table the velocity the swarm would give the point.
349 * @param[in] normal The face's inward unit normal, read with `velocity`.
350 * @param[in] flux_bound An upper bound of the inward normal velocity over the face cell, read
351 * with `velocity`.
352 * @param[out] ci_metric_lnode_out,cj_metric_lnode_out,ck_metric_lnode_out Origin node of the cell.
353 * @param[out] xi_metric_logic_out,eta_metric_logic_out,zta_metric_logic_out Logical point in it.
354 * @param[out] velocity_out The point's velocity, set with `velocity`; or NULL.
355 * @return PetscErrorCode 0 on success.
356 */
357static PetscErrorCode DrawSeedingPoint(
358 UserCtx *user, const Cmpnts ***coor, const SeedingCellTable *table, PetscInt c, PetscInt64 pid,
359 const VelocityPointInterpolator *velocity, Cmpnts normal, PetscReal flux_bound,
360 PetscInt *ci_metric_lnode_out, PetscInt *cj_metric_lnode_out, PetscInt *ck_metric_lnode_out,
361 PetscReal *xi_metric_logic_out, PetscReal *eta_metric_logic_out, PetscReal *zta_metric_logic_out,
362 Cmpnts *velocity_out)
363{
364 PetscReal logic[3], u[4];
365
366 PetscFunctionBeginUser;
368 {
369 PetscInt origin[3];
370 SeedingCellOrigin(table, c, origin);
371 *ci_metric_lnode_out = origin[0]; *cj_metric_lnode_out = origin[1]; *ck_metric_lnode_out = origin[2];
372 }
373
374 // Accept uniform logicals with probability density / bound; a cell whose density varies
375 // little accepts almost every draw. The cap only guards a degenerate envelope.
376 for (PetscInt attempt = 0; attempt < 1000; ++attempt) {
377 PetscReal density;
379 SeedingLogicalPoint(u, table->face, logic);
380 PetscCall(SeedingMeasureDensity(user, coor, table->face, *ci_metric_lnode_out, *cj_metric_lnode_out,
381 *ck_metric_lnode_out, logic, &density));
382 if (velocity) {
383 const PetscInt cell[3] = {*ci_metric_lnode_out, *cj_metric_lnode_out, *ck_metric_lnode_out};
384 Cmpnts point;
385 PetscCall(MetricLogicalToPhysical(user, coor, cell[0], cell[1], cell[2], logic[0], logic[1], logic[2], &point));
386 PetscCall(InterpolateVelocityAtPoint(velocity, cell, logic, point, velocity_out));
387 const PetscReal u_n = PetscMax(velocity_out->x * normal.x + velocity_out->y * normal.y + velocity_out->z * normal.z, 0.0);
388 if (u_n > flux_bound) {
389 LOG_ALLOW(LOCAL, LOG_WARNING, "Rank %d: inward velocity %g exceeds the bound %g in face cell (%" PetscInt_FMT ",%" PetscInt_FMT ",%" PetscInt_FMT "); placement there is biased.\n",
390 user->simCtx->rank, (double)u_n, (double)flux_bound, cell[0], cell[1], cell[2]);
391 }
392 density *= u_n / flux_bound;
393 }
394 if (u[3] * table->bound[c] <= density) break;
395 if (attempt == 999) {
396 LOG_ALLOW(LOCAL, LOG_WARNING, "Rank %d: 1000 rejected draws in cell (%" PetscInt_FMT ",%" PetscInt_FMT ",%" PetscInt_FMT "); accepting the last one.\n",
397 user->simCtx->rank, *ci_metric_lnode_out, *cj_metric_lnode_out, *ck_metric_lnode_out);
398 }
399 }
400 *xi_metric_logic_out = logic[0]; *eta_metric_logic_out = logic[1]; *zta_metric_logic_out = logic[2];
401
403 PetscFunctionReturn(0);
404}
405
406
407/**
408 * @brief Initialize position-independent particle fields after a particle is created.
409 */
410static PetscErrorCode InitializeParticleBasicProperties(UserCtx *user,
411 PetscInt particlesPerProcess)
412{
413 PetscErrorCode ierr;
414 DM swarm = user->swarm;
415 PetscReal *positions_field = NULL; // Pointer to swarm field for physical positions (x,y,z)
416 PetscInt64 *particleIDs = NULL; // Pointer to swarm field for Particle IDs
417 PetscInt *cellIDs_petsc = NULL; // Pointer to swarm field for DMSwarm_CellID (i,j,k of containing cell)
418 PetscInt *status_field = NULL; // Pointer to swarm field for DMSwarm_location_status(NEEDS_LOCATION etc)
419 PetscMPIInt rank,size; // MPI rank of the current process, and total number of ranks.
420 const Cmpnts ***coor_nodes_local_array; // Read-only access to local node coordinates (from user->da)
421 Vec Coor_local; // Local vector for node coordinates
422 // Owned cells and the particles each seeds, for volumetric and surface seeding
423 SeedingCellTable seed_table;
424
425 PetscFunctionBeginUser;
426
428
429 // --- 1. Input Validation and Basic Setup ---
430 if (!user) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Null user.");
431 SimCtx *simCtx = user->simCtx;
432 rank = simCtx->rank;
433 size = simCtx->size;
434
435 // Get DMDA information for the node-centered coordinate grid (user->da)
436 Coor_local = user->lCoor;
437 if (!Coor_local) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_PLIB, "user->lCoor is NULL: grid coordinates are not set up.");
438 ierr = DMDAVecGetArrayRead(user->fda, Coor_local, (void*)&coor_nodes_local_array); CHKERRQ(ierr);
439 ierr = PetscMemzero(&seed_table, sizeof(seed_table)); CHKERRQ(ierr);
440
441 LOG_ALLOW(LOCAL, LOG_INFO, "Rank %d: Initializing %" PetscInt_FMT " particles. Mode: %s.\n",
442 rank, particlesPerProcess, ParticleInitializationToString(simCtx->ParticleInitialization));
443
444 // --- 2. Seeding Table for Volumetric and Surface Initialization ---
445 // Volume seeds the owned cells, Surface the owned cells on the inlet face; the table names
446 // each cell's particles, the same split CreateParticleSwarm sized the swarm with.
447 const PetscBool seeds_from_table = (PetscBool)(simCtx->ParticleInitialization == PARTICLE_INIT_VOLUME ||
449 PetscInt seed_cell = 0; // Cell the next table-seeded particle goes in
450 PetscInt64 seed_pid = 0; // That particle's ID
451 if (seeds_from_table) {
452 const PetscInt face = (simCtx->ParticleInitialization == PARTICLE_INIT_SURFACE_RANDOM) ? (PetscInt)user->identifiedInletBCFace : -1;
453 ierr = BuildSeedingCellTable(user, coor_nodes_local_array, face, simCtx->np, PETSC_TRUE, &seed_table); CHKERRQ(ierr);
454 PetscCheck(seed_table.count == particlesPerProcess, PETSC_COMM_SELF, PETSC_ERR_PLIB,
455 "Seeding table holds %" PetscInt_FMT " particles but the swarm was sized for %" PetscInt_FMT ".",
456 seed_table.count, particlesPerProcess);
457 if (seed_table.n[0] * seed_table.n[1] * seed_table.n[2] > 0) seed_pid = seed_table.pid_lo[0];
458 LOG_ALLOW(LOCAL, LOG_INFO, "Rank %d: Seeding %" PetscInt_FMT " particles stratified over %" PetscInt_FMT " owned cells by %s.\n",
459 rank, particlesPerProcess, seed_table.n[0] * seed_table.n[1] * seed_table.n[2],
460 face < 0 ? "volume" : "inlet area");
461 }
462
463 // --- 3. Get Access to Swarm Fields ---
464 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_POSITION), NULL, NULL, (void**)&positions_field); CHKERRQ(ierr);
465 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_PID), NULL, NULL, (void**)&particleIDs); CHKERRQ(ierr);
466 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_CELL_ID), NULL, NULL, (void**)&cellIDs_petsc); CHKERRQ(ierr);
467 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_LOCATION_STATUS),NULL,NULL,(void**)&status_field); CHKERRQ(ierr);
468
469 // --- 4. Determine Starting Global PID for this Rank (point source) ---
470 // Point-source PIDs are consecutive across ranks in rank order, so each rank starts where
471 // the ranks before it end. Table seeding takes each particle's ID from its cell instead.
472 PetscInt base_pid_for_rank = 0;
473 {
474 PetscInt local_count = particlesPerProcess;
475 ierr = MPI_Exscan(&local_count, &base_pid_for_rank, 1, MPIU_INT, MPI_SUM, PETSC_COMM_WORLD); CHKERRMPI(ierr);
476 if (rank == 0) base_pid_for_rank = 0; /* MPI_Exscan leaves rank 0's result undefined */
477 }
478
479 // --- 4b. Locate the Point Source Once ---
480 // Every rank places its share at the same point, so its cell is found by one search per rank;
481 // the lowest rank that holds it shares the cell, and settlement then routes the particles there.
482 PetscInt point_cell[3] = {-1, -1, -1};
484 Particle probe;
486 PetscMPIInt candidate, owner = size;
487 ierr = PetscMemzero(&probe, sizeof(probe)); CHKERRQ(ierr);
488 probe.PID = -1;
489 probe.cell[0] = -1; probe.cell[1] = -1; probe.cell[2] = -1;
490 probe.loc.x = simCtx->psrc_x; probe.loc.y = simCtx->psrc_y; probe.loc.z = simCtx->psrc_z;
491 ierr = LocateParticleOrFindMigrationTarget(user, NULL, &probe, &probe_status); CHKERRQ(ierr);
492 candidate = (probe_status == ACTIVE_AND_LOCATED) ? rank : size;
493 ierr = MPI_Allreduce(&candidate, &owner, 1, MPI_INT, MPI_MIN, PETSC_COMM_WORLD); CHKERRMPI(ierr);
494 if (owner < size) {
495 if (rank == owner) { point_cell[0] = probe.cell[0]; point_cell[1] = probe.cell[1]; point_cell[2] = probe.cell[2]; }
496 ierr = MPI_Bcast(point_cell, 3, MPIU_INT, owner, PETSC_COMM_WORLD); CHKERRMPI(ierr);
497 LOG_ALLOW(GLOBAL, LOG_INFO, "Point source (%.6e, %.6e, %.6e) lies in cell (%" PetscInt_FMT ",%" PetscInt_FMT ",%" PetscInt_FMT ") on rank %d.\n",
498 simCtx->psrc_x, simCtx->psrc_y, simCtx->psrc_z, point_cell[0], point_cell[1], point_cell[2], owner);
499 } else {
500 LOG_ALLOW(GLOBAL, LOG_WARNING, "Point source (%.6e, %.6e, %.6e) was not located on any rank; its particles will be searched for.\n",
501 simCtx->psrc_x, simCtx->psrc_y, simCtx->psrc_z);
502 }
503 }
504
505 // --- 5. Loop Over Particles to Initialize ---
506 for (PetscInt p = 0; p < particlesPerProcess; p++) {
507 PetscInt ci_metric_lnode, cj_metric_lnode, ck_metric_lnode;
508 PetscReal xi_metric_logic = 0.0, eta_metric_logic = 0.0, zta_metric_logic = 0.0;
509 Cmpnts phys_coords = {0.0, 0.0, 0.0};
510 PetscBool particle_placed_by_this_rank = PETSC_FALSE;
511 PetscInt64 pid = (PetscInt64)base_pid_for_rank + p;
512
513 if (seeds_from_table) { // --- 5.a. Volumetric or Surface Initialization ---
514 while (seed_pid == seed_table.pid_hi[seed_cell]) seed_pid = seed_table.pid_lo[++seed_cell]; // skip filled (or empty) cells
515 pid = seed_pid++;
516 ierr = DrawSeedingPoint(user, coor_nodes_local_array, &seed_table, seed_cell, pid, NULL, (Cmpnts){0.0, 0.0, 0.0}, 0.0,
517 &ci_metric_lnode, &cj_metric_lnode, &ck_metric_lnode,
518 &xi_metric_logic, &eta_metric_logic, &zta_metric_logic, NULL); CHKERRQ(ierr);
519 ierr = MetricLogicalToPhysical(user, coor_nodes_local_array,
520 ci_metric_lnode, cj_metric_lnode, ck_metric_lnode,
521 xi_metric_logic, eta_metric_logic, zta_metric_logic,
522 &phys_coords); CHKERRQ(ierr);
523 particle_placed_by_this_rank = PETSC_TRUE;
524 }else if(simCtx->ParticleInitialization == PARTICLE_INIT_POINT_SOURCE){ // --- 5.c. Point Source Initialization ---
525 // All particles placed at the user-specified fixed point (psrc_x, psrc_y, psrc_z).
526 // No random number generation or logical-to-physical conversion needed.
527 phys_coords.x = simCtx->psrc_x;
528 phys_coords.y = simCtx->psrc_y;
529 phys_coords.z = simCtx->psrc_z;
530 ci_metric_lnode = point_cell[0]; cj_metric_lnode = point_cell[1]; ck_metric_lnode = point_cell[2];
531 particle_placed_by_this_rank = (PetscBool)(point_cell[0] >= 0);
532 }else {
533 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Unknown ParticleInitialization mode %d.", simCtx->ParticleInitialization);
534 }
535
536 // --- 5.c. Store Particle Properties ---
537 positions_field[3*p+0] = phys_coords.x;
538 positions_field[3*p+1] = phys_coords.y;
539 positions_field[3*p+2] = phys_coords.z;
540
541 particleIDs[p] = pid;
542 // Start the first settlement's walk in the cell the particle was placed in; a point-source
543 // particle no rank located has no cell and is located by search.
544 if (particle_placed_by_this_rank) {
545 cellIDs_petsc[3*p+0] = ci_metric_lnode; cellIDs_petsc[3*p+1] = cj_metric_lnode; cellIDs_petsc[3*p+2] = ck_metric_lnode;
546 } else {
547 cellIDs_petsc[3*p+0] = -1; cellIDs_petsc[3*p+1] = -1; cellIDs_petsc[3*p+2] = -1;
548 }
549 status_field[p] = UNINITIALIZED;
550
551 // --- 5.d. The particle's seed line ---
552 if (seeds_from_table) {
553 LOG_PARTICLE(simCtx, particleIDs[p], "seed",
554 "%s placement on rank %d at (%.6e, %.6e, %.6e): cell (%" PetscInt_FMT ",%" PetscInt_FMT ",%" PetscInt_FMT ") logical (%.4f, %.4f, %.4f)\n",
556 phys_coords.x, phys_coords.y, phys_coords.z, ci_metric_lnode, cj_metric_lnode, ck_metric_lnode,
557 xi_metric_logic, eta_metric_logic, zta_metric_logic);
558 } else if (particle_placed_by_this_rank) {
559 LOG_PARTICLE(simCtx, particleIDs[p], "seed",
560 "%s placement on rank %d at (%.6e, %.6e, %.6e): cell (%" PetscInt_FMT ",%" PetscInt_FMT ",%" PetscInt_FMT ")\n",
562 phys_coords.x, phys_coords.y, phys_coords.z, ci_metric_lnode, cj_metric_lnode, ck_metric_lnode);
563 } else {
564 // A point source no rank located.
565 LOG_PARTICLE(simCtx, particleIDs[p], "seed",
566 "%s: not placed by rank %d; parked at (%.6e, %.6e, %.6e) for the settlement to locate\n",
568 phys_coords.x, phys_coords.y, phys_coords.z);
569 }
570 }
571
572 // --- 6. Restore Pointers and Cleanup ---
573 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_POSITION), NULL, NULL, (void**)&positions_field); CHKERRQ(ierr);
574 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_PID), NULL, NULL, (void**)&particleIDs); CHKERRQ(ierr);
575 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_CELL_ID), NULL, NULL, (void**)&cellIDs_petsc); CHKERRQ(ierr);
576 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_LOCATION_STATUS), NULL, NULL, (void**)&status_field); CHKERRQ(ierr);
577 ierr = DMDAVecRestoreArrayRead(user->fda, Coor_local, (void*)&coor_nodes_local_array); CHKERRQ(ierr);
578 ierr = FreeSeedingCellTable(&seed_table); CHKERRQ(ierr);
579
580 LOG_ALLOW(LOCAL, LOG_INFO, "Rank %d: Completed processing for %" PetscInt_FMT " particles.\n",
581 rank, particlesPerProcess);
582
584
585 PetscFunctionReturn(0);
586}
587
588/**
589 * @brief Set local particles `first` to `end` - 1 of every field the particle catalog marks
590 * PARTICLE_FIELD_CAPABILITY_DEFAULT_INITIALIZE to the field's catalog default.
591 */
592static PetscErrorCode InitializeDefaultParticleFields(DM swarm, PetscInt first, PetscInt end)
593{
594 PetscFunctionBeginUser;
596 for (PetscInt raw_id = 0; raw_id < PARTICLE_FIELD_ID_COUNT; ++raw_id) {
597 const ParticleFieldDescriptor *descriptor = NULL;
598 PetscReal *field = NULL;
599
600 PetscCall(ParticleFieldGetDescriptor((ParticleFieldId)raw_id, &descriptor));
601 if (!(descriptor->capabilities & PARTICLE_FIELD_CAPABILITY_DEFAULT_INITIALIZE)) continue;
602 PetscCheck(descriptor->data_type == PETSC_REAL, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG,
603 "Default initialization supports only PETSC_REAL particle fields; '%s' uses %s.",
604 descriptor->canonical_name, PetscDataTypes[descriptor->data_type]);
605 PetscCall(DMSwarmGetField(swarm, descriptor->canonical_name, NULL, NULL, (void **)&field));
606 for (PetscInt p = first; p < end; ++p) {
607 for (PetscInt d = 0; d < descriptor->components; ++d) field[descriptor->components * p + d] = descriptor->default_real_value;
608 }
609 PetscCall(DMSwarmRestoreField(swarm, descriptor->canonical_name, NULL, NULL, (void **)&field));
610 }
612 PetscFunctionReturn(0);
613}
614
615
616/**
617 * @brief Implementation of \ref AssignInitialPropertiesToSwarm().
618 * @see AssignInitialPropertiesToSwarm()
619 */
621 PetscInt particlesPerProcess)
622{
623 PetscErrorCode ierr;
624 PetscFunctionBeginUser;
625
627
628 // --- 0. Input Validation ---
629 if (!user) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Null user.");
630 SimCtx *simCtx = user->simCtx;
631
632 LOG_ALLOW(GLOBAL, LOG_INFO, "Initializing swarm with %" PetscInt_FMT " particles per process. Mode: %s.\n",
633 particlesPerProcess, ParticleInitializationToString(simCtx->ParticleInitialization));
634
635 // --- 1. Surface seeding needs the INLET face the boundary conditions identified ---
637 if (user->inletFaceDefined == PETSC_FALSE) {
638 LOG_ALLOW(GLOBAL, LOG_ERROR, "Particle Initialization on inlet surface selected, but no INLET face was identified from bcs.dat. Cannot proceed.\n");
639 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONGSTATE, "Surface particle seeding requires an INLET face in the boundary conditions.");
640 }
641 LOG_ALLOW(GLOBAL, LOG_INFO, "Inlet face for surface seeding = %s\n", BCFaceToString((BCFace)user->identifiedInletBCFace));
642 }
643
644 // --- 2. Initialize Basic Particle Properties (Position, PID, Cell IDs placeholder) ---
645 // Placement draws are keyed on (seed, PID), so no generator state is passed in.
646 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Calling InitializeParticleBasicProperties.\n");
647 ierr = InitializeParticleBasicProperties(user, particlesPerProcess); CHKERRQ(ierr);
648 LOG_ALLOW(GLOBAL, LOG_INFO, "Successfully initialized basic particle properties.\n");
649
650 // --- 3. The catalog's default-initialized fields: velocity, weight, Diffusivity, DiffusivityGradient, Psi ---
651 {
652 PetscInt n_local = 0;
653 ierr = DMSwarmGetLocalSize(user->swarm, &n_local); CHKERRQ(ierr);
654 ierr = InitializeDefaultParticleFields(user->swarm, 0, n_local); CHKERRQ(ierr);
655 }
656 LOG_ALLOW(GLOBAL, LOG_INFO, "Successfully completed all swarm property initialization.\n");
657
658
660
661 PetscFunctionReturn(0);
662}
663
664
665/**
666 * @brief Implementation of \ref DistributeParticles().
667 * @details Full API contract (arguments, ownership, side effects) is documented with
668 * the header declaration in `include/ParticleSwarm.h`.
669 * @see DistributeParticles()
670 */
671PetscErrorCode DistributeParticles(PetscInt numParticles, PetscMPIInt rank, PetscMPIInt size, PetscInt* particlesPerProcess, PetscInt* remainder) {
672
673 PetscFunctionBeginUser;
674
676 // Calculate the base number of particles per process
677 *particlesPerProcess = numParticles / size;
678 *remainder = numParticles % size;
679
680 // Distribute the remainder particles to the first 'remainder' ranks
681 if (rank < *remainder) {
682 *particlesPerProcess += 1;
683 LOG_ALLOW_SYNC(GLOBAL,LOG_INFO,"Rank %d receives an extra particle. Total: %" PetscInt_FMT "\n", rank, *particlesPerProcess);
684 } else {
685 LOG_ALLOW_SYNC(GLOBAL,LOG_INFO, "Rank %d receives %" PetscInt_FMT " particles.\n", rank, *particlesPerProcess);
686 }
687
689 PetscFunctionReturn(0);
690}
691
692
693/**
694 * @brief Number of particles this rank seeds for volumetric or surface seeding.
695 * @details Collective. The count is the rank's share of the stratified split
696 * BuildSeedingCellTable makes, so a rank seeds in proportion to the volume or inlet
697 * area it owns, none if it owns no part of the inlet, and the counts sum to
698 * `numParticles` exactly.
699 * @param[in] user Finest-level context whose DMDA ownership defines the split.
700 * @param[in] face -1 for the volume, otherwise the inlet BCFace.
701 * @param[in] numParticles Global particle count.
702 * @param[out] localCount Particles this rank seeds.
703 * @return PetscErrorCode 0 on success.
704 */
705static PetscErrorCode DistributeParticlesByOwnedMeasure(UserCtx *user, PetscInt face, PetscInt numParticles, PetscInt *localCount)
706{
707 SeedingCellTable table;
708 const Cmpnts ***coor = NULL;
709
710 PetscFunctionBeginUser;
712 PetscCall(DMDAVecGetArrayRead(user->fda, user->lCoor, (void *)&coor));
713 PetscCall(BuildSeedingCellTable(user, coor, face, numParticles, PETSC_FALSE, &table));
714 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lCoor, (void *)&coor));
715 *localCount = table.count;
716 PetscCall(FreeSeedingCellTable(&table));
718 PetscFunctionReturn(0);
719}
720
721/**
722 * @brief Implementation of \ref CreateParticleSwarm().
723 * @see CreateParticleSwarm()
724 */
725PetscErrorCode CreateParticleSwarm(UserCtx *user, PetscInt numParticles, PetscInt *particlesPerProcess) {
726 PetscErrorCode ierr; // PETSc error handling variable
727 PetscMPIInt rank, size; // Variables to store MPI rank and size
728 PetscInt remainder = 0; // Remainder of particles after division
729
730 PetscFunctionBeginUser;
732 // Validate input parameters
733 if (numParticles < 0) {
734 LOG_ALLOW(GLOBAL,LOG_DEBUG, "Number of particles must not be negative. Given: %" PetscInt_FMT "\n", numParticles);
736 return PETSC_ERR_ARG_OUTOFRANGE;
737 }
738
739 // Retrieve MPI rank and size
740 rank = user->simCtx->rank;
741 size = user->simCtx->size;
742 LOG_ALLOW(GLOBAL,LOG_INFO," Domain dimensions: [%.2f,%.2f],[%.2f,%.2f],[%.2f,%.2f] \n",
743 user->Min_X,user->Max_X,user->Min_Y,user->Max_Y, user->Min_Z,user->Max_Z);
744 LOG_ALLOW_SYNC(GLOBAL,LOG_DEBUG, "[Rank %d] Local Bounding Box: [%.2f,%.2f],[%.2f,%.2f],[%.2f,%.2f] \n",
745 rank,user->bbox.min_coords.x,user->bbox.max_coords.x,
746 user->bbox.min_coords.y,user->bbox.max_coords.y,
747 user->bbox.min_coords.z,user->bbox.max_coords.z);
748 // Distribute particles among MPI processes
750 ierr = DistributeParticlesByOwnedMeasure(user, -1, numParticles, particlesPerProcess); CHKERRQ(ierr);
752 PetscCheck(user->inletFaceDefined, PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONGSTATE,
753 "Surface particle seeding needs an INLET face.");
754 ierr = DistributeParticlesByOwnedMeasure(user, (PetscInt)user->identifiedInletBCFace, numParticles, particlesPerProcess); CHKERRQ(ierr);
755 } else {
756 ierr = DistributeParticles(numParticles, rank, size, particlesPerProcess, &remainder); CHKERRQ(ierr);
757 }
758
759 // Initialize the DMSwarm - creates the swarm, sets the type and dimension
760 ierr = InitializeSwarm(user); CHKERRQ(ierr);
761
762 if (user->da) {
763 ierr = DMSwarmSetCellDM(user->swarm, user->da); CHKERRQ(ierr);
764 LOG_ALLOW(LOCAL,LOG_INFO,"Associated DMSwarm with Cell DM (user->da).\n");
765 } else {
766 // If user->da is essential for your simulation logic with particles, this should be a fatal error.
767 LOG_ALLOW(GLOBAL, LOG_WARNING, "user->da (Cell DM for Swarm) is NULL. Cell-based swarm operations might fail.\n");
768 // SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONGSTATE, "user->da (Cell DM) is NULL but required.");
769 }
770
771 // Register particle fields (position, velocity, CellID, weight, etc.)
772 ierr = RegisterParticleFields(user->swarm); CHKERRQ(ierr);
773
774 // Set the local number of particles for this rank and spare capacity for arrivals (10% of the
775 // local count; PETSc reallocates beyond it). Every resize zeroes the whole spare region, so a
776 // buffer sized to the global count would cost each rank memory and work of order numParticles.
777 ierr = DMSwarmSetLocalSizes(user->swarm, *particlesPerProcess, *particlesPerProcess / 10); CHKERRQ(ierr);
778 LOG_ALLOW(GLOBAL,LOG_INFO, "Set local swarm size: %" PetscInt_FMT " particles.\n", *particlesPerProcess);
779
780 // Optionally, LOG_ALLOW detailed DM info in debug mode
781 if (get_log_level() >= LOG_DEBUG && is_function_allowed(__func__)) {
782 LOG_ALLOW(GLOBAL,LOG_DEBUG,"Viewing DMSwarm:\n");
783 ierr = DMView(user->swarm, PETSC_VIEWER_STDOUT_WORLD); CHKERRQ(ierr);
784 }
785
786 LOG_ALLOW(GLOBAL,LOG_INFO, "Particle swarm creation and initialization complete.\n");
787
789 PetscFunctionReturn(0);
790}
791
792// NOTE: The following two functions are helpers for unpacking and updating particle data
793// between DMSwarm fields and the Particle struct used in simulation logic.
794// While Swarm fields store data in arrays, the Particle struct provides a convenient
795// way to manipulate individual particle properties during simulation steps.
796
797
798/**
799 * @brief Implementation of \ref UnpackSwarmFields().
800 * @details Full API contract (arguments, ownership, side effects) is documented with
801 * the header declaration in `include/ParticleSwarm.h`.
802 * @see UnpackSwarmFields()
803 */
804PetscErrorCode UnpackSwarmFields(PetscInt i, const PetscInt64 *PIDs, const PetscReal *weights,
805 const PetscReal *positions, const PetscInt *cellIndices,
806 PetscReal *velocities,PetscInt *LocStatus,PetscReal *diffusivity, Cmpnts *diffusivitygradient, PetscReal *psi, Particle *particle) {
807 PetscFunctionBeginUser;
808
810
811 // The particle's values are reported by the stage that uses them, not here: this runs
812 // several times per particle per step.
813 if (particle == NULL) {
814 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Output Particle pointer is NULL. \n");
815 }
816 if(PIDs == NULL){
817 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Input PIDs pointer is NULL.\n");
818 }
819 if(positions == NULL){
820 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Input positions pointer is NULL.\n");
821 }
822 if(cellIndices == NULL){
823 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Input cellIndices pointer is NULL.\n");
824 }
825 if(LocStatus == NULL){
826 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Input LocStatus pointer is NULL.\n");
827 }
828
829 particle->PID = PIDs[i];
830
831 // A NULL optional field is one the caller does not need; it takes the default shown.
832 if(weights == NULL){
833 particle->weights.x = 1.0;
834 particle->weights.y = 1.0;
835 particle->weights.z = 1.0;
836 }else{
837 particle->weights.x = weights[3 * i];
838 particle->weights.y = weights[3 * i + 1];
839 particle->weights.z = weights[3 * i + 2];
840 }
841
842 particle->loc.x = positions[3 * i];
843 particle->loc.y = positions[3 * i + 1];
844 particle->loc.z = positions[3 * i + 2];
845
846 if(velocities == NULL){
847 particle->vel.x = 0.0;
848 particle->vel.y = 0.0;
849 particle->vel.z = 0.0;
850 }else{
851 particle->vel.x = velocities[3 * i];
852 particle->vel.y = velocities[3 * i + 1];
853 particle->vel.z = velocities[3 * i + 2];
854 }
855
856 particle->diffusivity = (diffusivity == NULL) ? 1.0 : diffusivity[i];
857
858 if(diffusivitygradient == NULL){
859 particle->diffusivitygradient.x = 0.0;
860 particle->diffusivitygradient.y = 0.0;
861 particle->diffusivitygradient.z = 0.0;
862 }else{
863 particle->diffusivitygradient = diffusivitygradient[i];
864 }
865
866 particle->psi = (psi == NULL) ? 0.0 : psi[i];
867
868 particle->cell[0] = cellIndices[3 * i];
869 particle->cell[1] = cellIndices[3 * i + 1];
870 particle->cell[2] = cellIndices[3 * i + 2];
871
872 particle->location_status = (ParticleLocationStatus)LocStatus[i];
873
874 // The destination_rank is only set by the location search, not read from the swarm,
875 // so we initialize it to a known invalid state.
876 particle->destination_rank = MPI_PROC_NULL;
877
879
880 PetscFunctionReturn(0);
881}
882
883/**
884 * @brief Implementation of \ref UpdateSwarmFields().
885 * @see UpdateSwarmFields()
886 */
887PetscErrorCode UpdateSwarmFields(PetscInt i, const Particle *particle,
888 PetscReal *positions,
889 PetscReal *velocities,
890 PetscReal *weights,
891 PetscInt *cellIndices,
892 PetscInt *status,
893 PetscReal *diffusivity,
894 Cmpnts *diffusivitygradient,
895 PetscReal *psi)
896{
897 PetscFunctionBeginUser;
899
900 if (!particle) {
901 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Input Particle pointer is NULL.\n");
902 }
903
904 // --- 1. Position (x, y, z) ---
905 if (positions) {
906 positions[3 * i + 0] = particle->loc.x;
907 positions[3 * i + 1] = particle->loc.y;
908 positions[3 * i + 2] = particle->loc.z;
909 }
910
911 // --- 2. Velocity (u, v, w) ---
912 if (velocities) {
913 velocities[3 * i + 0] = particle->vel.x;
914 velocities[3 * i + 1] = particle->vel.y;
915 velocities[3 * i + 2] = particle->vel.z;
916 }
917
918 // --- 3. Weights (i, j, k) ---
919 if (weights) {
920 weights[3 * i + 0] = particle->weights.x;
921 weights[3 * i + 1] = particle->weights.y;
922 weights[3 * i + 2] = particle->weights.z;
923 }
924
925 // --- 4. Cell Indices (i, j, k) ---
926 if (cellIndices) {
927 cellIndices[3 * i + 0] = particle->cell[0];
928 cellIndices[3 * i + 1] = particle->cell[1];
929 cellIndices[3 * i + 2] = particle->cell[2];
930 }
931
932 // --- 5. Status ---
933 if (status) {
934 status[i] = (PetscInt)particle->location_status;
935 }
936
937 // --- 6. Diffusivity ---
938 if (diffusivity) {
939 diffusivity[i] = particle->diffusivity;
940 }
941
942 if(diffusivitygradient){
943 diffusivitygradient[i].x = particle->diffusivitygradient.x;
944 diffusivitygradient[i].y = particle->diffusivitygradient.y;
945 diffusivitygradient[i].z = particle->diffusivitygradient.z;
946 }
947 // --- 7. Psi ---
948 if (psi) {
949 psi[i] = particle->psi;
950 }
951
953 PetscFunctionReturn(0);
954}
955
956/**
957 * @brief Implementation of \ref UpdateParticleWeights().
958 * @see UpdateParticleWeights()
959 */
960PetscErrorCode UpdateParticleWeights(PetscReal *d, Particle *particle) {
961
962 PetscFunctionBeginUser;
964
965 // Validate input pointers
966 if (!d || !particle) {
967 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
968 "Null pointer argument (d or particle).");
969 }
970
971
972 // Validate distances
973 for (PetscInt i = LEFT; i < NUM_FACES; i++) {
975 // A particle on a face: benign, so reported only to a VERBOSE run of this function.
977 "face distance d[%" PetscInt_FMT "] = %g <= %g; "
978 "clamping to avoid zero/negative.\n",
979 i, (double)d[i], INTERPOLATION_DISTANCE_TOLERANCE);
981 }
982 }
983
984 // Compute and update the particle's weights
985 particle->weights.x = d[LEFT] / (d[LEFT] + d[RIGHT]);
986 particle->weights.y = d[BOTTOM] / (d[BOTTOM] + d[TOP]);
987 particle->weights.z = d[BACK] / (d[FRONT] + d[BACK]);
988
989
990
992 PetscFunctionReturn(0);
993}
994
995/**
996 * @brief Implementation of \ref InitializeParticleSwarm().
997 * @details Full API contract (arguments, ownership, side effects) is documented with
998 * the header declaration in `include/ParticleSwarm.h`.
999 * @see InitializeParticleSwarm()
1000 */
1001
1002PetscErrorCode InitializeParticleSwarm(SimCtx *simCtx)
1003{
1004 PetscErrorCode ierr;
1005 PetscInt particlesPerProcess = 0;
1006 UserCtx *user = simCtx->usermg.mgctx[simCtx->usermg.mglevels - 1].user;
1007
1008 PetscFunctionBeginUser;
1010
1011 LOG_ALLOW(GLOBAL, LOG_INFO, "Starting particle swarm setup for %" PetscInt_FMT " particles.\n", simCtx->np);
1012
1013 // --- Phase 1: Create the DMSwarm Object (Always required) ---
1014 // This creates the container and registers the fields. It does not add particles yet.
1015 ierr = CreateParticleSwarm(user, simCtx->np, &particlesPerProcess); CHKERRQ(ierr);
1016 LOG_ALLOW(GLOBAL, LOG_INFO, "DMSwarm object and fields created successfully.\n");
1017
1018
1019 // --- Phase 2: Decide whether to Initialize new particles or Load existing ones ---
1020 PetscBool should_initialize_new_particles = PETSC_FALSE;
1021 if(simCtx->exec_mode == EXEC_MODE_POSTPROCESSOR){
1022 should_initialize_new_particles = PETSC_TRUE;
1023 }else{
1024 if (simCtx->StartStep == 0) {
1025 should_initialize_new_particles = PETSC_TRUE; // Standard fresh start
1026 } else {
1027 // It's a restart, so check the user's requested particle mode.
1028 if (strcmp(simCtx->particleRestartMode, "init") == 0) {
1029 should_initialize_new_particles = PETSC_TRUE; // User wants to re-initialize particles in a restarted flow.
1030 }
1031 }
1032 }
1033
1034 // --- Phase 3: Execute the chosen particle setup path ---
1035 if (should_initialize_new_particles) {
1036 // --- PATH A: Generate a fresh population of particles ---
1037 LOG_ALLOW(GLOBAL, LOG_INFO, "Mode: INITIALIZE. Generating new particle population.\n");
1038 ierr = AssignInitialPropertiesToSwarm(user, particlesPerProcess); CHKERRQ(ierr);
1039
1040 } else {
1041 // --- PATH B: Load particle population from restart files ---
1042 // This path is only taken if simCtx->StartStep > 0 AND simCtx->particleRestartMode == "load"
1043 LOG_ALLOW(GLOBAL, LOG_INFO, "Mode: LOAD. Loading particle population from files for step %" PetscInt_FMT ".\n", simCtx->StartStep);
1044
1045 ierr = PreCheckAndResizeSwarm(user, simCtx->StartStep, "dat"); CHKERRQ(ierr);
1046
1047 ierr = ReadAllSwarmFields(user, simCtx->StartStep); CHKERRQ(ierr);
1048 // Note: We check for file-open errors inside ReadAllSwarmFields now.
1049
1050 LOG_ALLOW(GLOBAL, LOG_INFO, "Particle data loaded. CellID and status are preserved from file.\n");
1051 }
1052
1053 LOG_ALLOW(GLOBAL, LOG_INFO, "Particle swarm setup complete.\n");
1054
1056 PetscFunctionReturn(0);
1057}
1058
1059/* ------------------------------------------------------------------------- */
1060/* Injection at inlets */
1061/* ------------------------------------------------------------------------- */
1062
1063/* A checkpoint stores a particle ID as a double, so every ID stays below 2^53. Seeded IDs stay
1064 below the base; an injected ID is base + (step * faces + face cell) * per_cell + k, which
1065 depends only on the grid, and so stays unique when a restart changes the rate or the inlets. */
1066#define PARTICLE_INLET_PID_BASE ((PetscInt64)1 << 40)
1067#define PARTICLE_INLET_PIDS_PER_CELL ((PetscInt64)1 << 10)
1068#define PARTICLE_PID_LIMIT ((PetscInt64)1 << 53)
1069#define PARTICLE_INLET_FACE_COUNT 6
1070#define PARTICLE_INLET_SUMS 4
1071
1072/** @brief One inlet face that injects particles. */
1075 PicurvExpression *particles_per_cell; /**< Mean particles per cell the entering fluid carries, in `t`. */
1076 ParticleFieldPlan *plan; /**< This inlet's field values; NULL uses the case's. */
1077 SeedingCellTable table; /**< The owned cells on the face; built at the first injection. */
1078 PetscReal cells_per_volume; /**< The grid's cells over its volume, set with the table. */
1079 PetscBool table_built;
1080};
1081
1082/**
1083 * @brief Implementation of \ref ParticleInletsCreate().
1084 * @see ParticleInletsCreate()
1085 */
1086PetscErrorCode ParticleInletsCreate(SimCtx *simCtx)
1087{
1088 static const char *const names[] = {"t"};
1089 PetscInt count = 0;
1090 PetscBool found = PETSC_FALSE;
1091
1092 PetscFunctionBeginUser;
1094 PetscCall(PetscOptionsGetInt(NULL, NULL, "-particle_inlet_count", &count, &found));
1095 if (!found || count == 0) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
1096 PetscCheck(count > 0 && count <= PARTICLE_INLET_FACE_COUNT, PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE,
1097 "-particle_inlet_count must be between 0 and %d (got %" PetscInt_FMT ").",
1099 PetscCheck((PetscInt64)simCtx->np < PARTICLE_INLET_PID_BASE, PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE,
1100 "Injected particle IDs start at %" PetscInt64_FMT ", so a run with particle inlets seeds fewer "
1101 "particles than that (got %" PetscInt_FMT ").", PARTICLE_INLET_PID_BASE, simCtx->np);
1102 PetscCall(PetscCalloc1(count, &simCtx->particleInlets));
1103 simCtx->particleInletCount = count;
1104 for (PetscInt n = 0; n < count; ++n) {
1105 struct ParticleInlet *inlet = &simCtx->particleInlets[n];
1106 char option[256], text[4096];
1107 PetscInt face = -1;
1108
1109 PetscCall(PetscSNPrintf(option, sizeof(option), "-particle_inlet_%" PetscInt_FMT "_face", n));
1110 PetscCall(PetscOptionsGetInt(NULL, NULL, option, &face, &found));
1111 PetscCheck(found && face >= 0 && face < PARTICLE_INLET_FACE_COUNT, PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONG,
1112 "%s must name a face from 0 to %d.", option, PARTICLE_INLET_FACE_COUNT - 1);
1113 inlet->face = (BCFace)face;
1114 PetscCall(PetscSNPrintf(option, sizeof(option), "-particle_inlet_%" PetscInt_FMT "_particles_per_cell", n));
1115 PetscCall(PetscOptionsGetString(NULL, NULL, option, text, sizeof(text), &found));
1116 PetscCheck(found, PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONG, "%s is missing.", option);
1117 PetscCall(PicurvExpressionCompile(text, names, 1, PETSC_FALSE, &inlet->particles_per_cell));
1118 PetscCall(PetscSNPrintf(option, sizeof(option), "particle_inlet_%" PetscInt_FMT "_fields", n));
1119 PetscCall(ParticleFieldPlanCreate(option, &inlet->plan));
1120 PetscCheck(!inlet->plan || !VerificationScalarOverrideActive(simCtx), PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONG,
1121 "An inlet's particle field values cannot be combined with the verification scalar source, "
1122 "which prescribes Psi at every step.");
1123 }
1125 PetscFunctionReturn(0);
1126}
1127
1128/**
1129 * @brief Implementation of \ref ParticleInletsDestroy().
1130 * @see ParticleInletsDestroy()
1131 */
1132PetscErrorCode ParticleInletsDestroy(SimCtx *simCtx)
1133{
1134 PetscFunctionBeginUser;
1136 for (PetscInt n = 0; n < simCtx->particleInletCount; ++n) {
1137 struct ParticleInlet *inlet = &simCtx->particleInlets[n];
1138 PetscCall(PicurvExpressionDestroy(&inlet->particles_per_cell));
1139 PetscCall(ParticleFieldPlanDestroy(&inlet->plan));
1140 if (inlet->table_built) PetscCall(FreeSeedingCellTable(&inlet->table));
1141 }
1142 PetscCall(PetscFree(simCtx->particleInlets));
1143 simCtx->particleInletCount = 0;
1145 PetscFunctionReturn(0);
1146}
1147
1148/**
1149 * @brief Add one inlet's particles for this step.
1150 * @param[in,out] user Grid context holding the swarm.
1151 * @param[in,out] inlet The inlet.
1152 * @param[in] event Time of the step, and the identity keying field draws.
1153 * @param[in] first_id This step's first face-cell identity.
1154 * @param[in] velocity The velocity the swarm gives a point, which places the particles.
1155 * @param[in,out] sums Adds this rank's flow rate [m^3/s], expected and added particles, and Psi added.
1156 * @return PetscErrorCode 0 on success.
1157 */
1158static PetscErrorCode InjectAtInlet(UserCtx *user, struct ParticleInlet *inlet, const ParticleFieldEvent *event,
1159 PetscInt64 first_id, const VelocityPointInterpolator *velocity,
1160 PetscReal sums[PARTICLE_INLET_SUMS])
1161{
1162 SimCtx *simCtx = user->simCtx;
1163 DM swarm = user->swarm;
1164 const SeedingCellTable *table = &inlet->table;
1165 const PetscInt nodes[3] = {user->info.mx, user->info.my, user->info.mz};
1166 const PetscInt normal = (PetscInt)inlet->face / 2, a = (normal == 0) ? 1 : 0, b = (normal == 2) ? 1 : 2;
1167 const PetscBool negative = (PetscBool)((PetscInt)inlet->face % 2 == 0);
1168 const PetscReal sign = negative ? 1.0 : -1.0, L_ref = simCtx->scaling.L_ref;
1169 const PetscInt64 seed = (PetscInt64)simCtx->particleRandomSeed;
1170 const PetscInt n_cells = table->n[0] * table->n[1] * table->n[2];
1171 const Vec metric_vec = (normal == 0) ? user->lCsi : (normal == 1) ? user->lEta : user->lZet;
1172 const Cmpnts ***coor = NULL, ***ucont = NULL, ***metric = NULL;
1173 const PetscReal ***diffusivity = NULL;
1174 PetscInt64 *cell_id = NULL;
1175 PetscInt *count = NULL;
1176 Cmpnts *travel = NULL, *inward = NULL, *normal_of = NULL;
1177 PetscReal *flux_bound = NULL;
1178 PetscInt first = 0, n_new = 0;
1179 PetscReal density = 0.0;
1180 ParticleFieldPlan *plan = inlet->plan ? inlet->plan : simCtx->particleFieldPlan;
1181
1182 PetscFunctionBeginUser;
1184 PetscCall(PicurvExpressionEvaluate(inlet->particles_per_cell, &event->physical_time, NULL, &density));
1185 PetscCheck(!PetscIsInfOrNanReal(density) && density >= 0.0, PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE,
1186 "The particles per cell of inlet %s is %g at t = %g; it must be finite and not negative.",
1187 BCFaceToString(inlet->face), (double)density, (double)event->physical_time);
1188 density *= inlet->cells_per_volume; /* particles per unit of the solver's volume */
1189
1190 // --- 1. How many enter each face cell: the mean's integer part, and one more by chance ---
1191 PetscCall(PetscMalloc5(n_cells, &count, n_cells, &cell_id, n_cells, &travel, n_cells, &normal_of, n_cells, &flux_bound));
1192 PetscCall(DMDAVecGetArrayRead(user->fda, user->lCoor, (void *)&coor));
1193 PetscCall(DMDAVecGetArrayRead(user->fda, user->lUcont, (void *)&ucont));
1194 PetscCall(DMDAVecGetArrayRead(user->fda, metric_vec, (void *)&metric));
1195 for (PetscInt c = 0; c < n_cells; ++c) {
1196 PetscInt origin[3];
1197 SeedingCellOrigin(table, c, origin);
1198 PetscInt f[3] = {origin[0] + 1, origin[1] + 1, origin[2] + 1};
1199 f[normal] = negative ? 0 : nodes[normal] - 2;
1200 const Cmpnts u = ucont[f[2]][f[1]][f[0]], m = metric[f[2]][f[1]][f[0]];
1201 const PetscReal flux = PetscMax(sign * ((normal == 0) ? u.x : (normal == 1) ? u.y : u.z), 0.0);
1202 const PetscReal expected = density * flux * simCtx->dt;
1203 const PetscReal whole = PetscFloorReal(expected);
1204 /* u_n dt along the inward unit normal: (flux / |m|) dt (sign m / |m|). */
1205 const PetscReal along_m = sign * flux * simCtx->dt / (m.x * m.x + m.y * m.y + m.z * m.z);
1206
1207 PetscCheck(whole < (PetscReal)PARTICLE_INLET_PIDS_PER_CELL, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE,
1208 "Inlet %s would inject %g particles through one face cell in one step; the limit is %" PetscInt64_FMT
1209 ". Lower particles_per_cell or the time step.", BCFaceToString(inlet->face), (double)expected,
1211 cell_id[c] = first_id + PicurvFaceCellId(nodes, inlet->face, origin[a], origin[b]);
1212 count[c] = (PetscInt)whole;
1213 if (PicurvUnitFromHash(PicurvDrawHash(seed, PICURV_DRAW_SPACE_INLET, 0, cell_id[c], 0)) < expected - whole) count[c]++;
1214 travel[c].x = along_m * m.x; travel[c].y = along_m * m.y; travel[c].z = along_m * m.z;
1215 n_new += count[c];
1216 /* The flux through a face cell varies across it as the swarm's velocity does, and the
1217 * particles leaving the inlet layer leave a gap that varies the same way, so the new ones
1218 * are placed in proportion to the inward velocity. Each method's velocity on a face cell
1219 * is bilinear between the corners, edge midpoints and centre, so its largest value there
1220 * bounds it; the margin covers curved cells. */
1221 {
1222 const PetscReal norm_m = PetscSqrtReal(m.x * m.x + m.y * m.y + m.z * m.z);
1223 normal_of[c].x = sign * m.x / norm_m; normal_of[c].y = sign * m.y / norm_m; normal_of[c].z = sign * m.z / norm_m;
1224 flux_bound[c] = 0.0;
1225 for (PetscInt q = 0; count[c] > 0 && q < 9; ++q) {
1226 PetscReal lattice[3], logic[3];
1227 Cmpnts point, u_q;
1228 lattice[a] = 0.5 * (q % 3); lattice[b] = 0.5 * (q / 3); lattice[normal] = 0.0;
1229 SeedingLogicalPoint(lattice, (PetscInt)inlet->face, logic);
1230 PetscCall(MetricLogicalToPhysical(user, coor, origin[0], origin[1], origin[2], logic[0], logic[1], logic[2], &point));
1231 PetscCall(InterpolateVelocityAtPoint(velocity, origin, logic, point, &u_q));
1232 flux_bound[c] = PetscMax(flux_bound[c], u_q.x * normal_of[c].x + u_q.y * normal_of[c].y + u_q.z * normal_of[c].z);
1233 }
1234 flux_bound[c] *= 1.1;
1235 }
1236 sums[0] += flux * simCtx->scaling.U_ref * L_ref * L_ref;
1237 sums[1] += expected;
1238 }
1239 sums[2] += (PetscReal)n_new;
1240 PetscCall(DMDAVecRestoreArrayRead(user->fda, metric_vec, (void *)&metric));
1241 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lUcont, (void *)&ucont));
1242
1243 // --- 2. Where: on the face, by area and inward velocity, keyed on the particle's ID ---
1244 PetscCall(DMSwarmGetLocalSize(swarm, &first));
1245 PetscCall(PetscMalloc1(n_new, &inward));
1246 if (n_new > 0) {
1247 PetscReal *positions = NULL, *weights = NULL;
1248 PetscInt *cell = NULL, *status = NULL;
1249 PetscInt64 *pids = NULL;
1250 PetscInt p = first;
1251
1252 PetscCall(DMSwarmSetLocalSizes(swarm, first + n_new, -1));
1253 PetscCall(InitializeDefaultParticleFields(swarm, first, first + n_new));
1254 PetscCall(DMDAVecGetArrayRead(user->da, user->lDiffusivity, (void *)&diffusivity));
1255 PetscCall(DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_POSITION), NULL, NULL, (void **)&positions));
1256 PetscCall(DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_WEIGHT), NULL, NULL, (void **)&weights));
1257 PetscCall(DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_CELL_ID), NULL, NULL, (void **)&cell));
1258 PetscCall(DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_PID), NULL, NULL, (void **)&pids));
1259 PetscCall(DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_LOCATION_STATUS), NULL, NULL, (void **)&status));
1260 for (PetscInt c = 0; c < n_cells; ++c) {
1261 for (PetscInt k = 0; k < count[c]; ++k, ++p) {
1262 const PetscInt64 pid = PARTICLE_INLET_PID_BASE + cell_id[c] * PARTICLE_INLET_PIDS_PER_CELL + k;
1263 const PetscReal share = PicurvUnitFromHash(PicurvDrawHash(seed, PICURV_DRAW_SPACE_INLET, 1, pid, 0));
1264 const PetscBool weighted = (PetscBool)(flux_bound[c] > 0.0);
1265 PetscInt ci, cj, ck;
1266 PetscReal xi, eta, zta;
1267 Cmpnts point, kick, u_p;
1268
1269 /* Without any inward velocity on the face cell, its count still came from the
1270 * flux: those particles are spread by area, and travel at the cell's mean. */
1271 PetscCall(DrawSeedingPoint(user, coor, table, c, pid, weighted ? velocity : NULL, normal_of[c], flux_bound[c],
1272 &ci, &cj, &ck, &xi, &eta, &zta, &u_p));
1273 if (!weighted) { u_p.x = travel[c].x / simCtx->dt; u_p.y = travel[c].y / simCtx->dt; u_p.z = travel[c].z / simCtx->dt; }
1274 PetscCall(MetricLogicalToPhysical(user, coor, ci, cj, ck, xi, eta, zta, &point));
1275 positions[3 * p + 0] = point.x; positions[3 * p + 1] = point.y; positions[3 * p + 2] = point.z;
1276 weights[3 * p + 0] = xi; weights[3 * p + 1] = eta; weights[3 * p + 2] = zta;
1277 cell[3 * p + 0] = ci; cell[3 * p + 1] = cj; cell[3 * p + 2] = ck;
1278 pids[p] = pid;
1279 status[p] = NEEDS_LOCATION;
1280 /* This step's Brownian kick, as every other particle had. Without it they refill
1281 * the inlet layer that this share also fills, and the first cell runs dense. */
1282 PetscCall(CalculateBrownianDisplacement(user, pid, diffusivity[ck + 1][cj + 1][ci + 1], &kick));
1283 inward[p - first].x = share * u_p.x * simCtx->dt + kick.x;
1284 inward[p - first].y = share * u_p.y * simCtx->dt + kick.y;
1285 inward[p - first].z = share * u_p.z * simCtx->dt + kick.z;
1286 LOG_PARTICLE(simCtx, pid, "inject", "through %s on rank %d at (%.6e, %.6e, %.6e): cell (%" PetscInt_FMT ",%" PetscInt_FMT ",%" PetscInt_FMT ")\n",
1287 BCFaceToString(inlet->face), (int)simCtx->rank, point.x, point.y, point.z, ci, cj, ck);
1288 }
1289 }
1290 PetscCall(DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_LOCATION_STATUS), NULL, NULL, (void **)&status));
1291 PetscCall(DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_PID), NULL, NULL, (void **)&pids));
1292 PetscCall(DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_CELL_ID), NULL, NULL, (void **)&cell));
1293 PetscCall(DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_WEIGHT), NULL, NULL, (void **)&weights));
1294 PetscCall(DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_POSITION), NULL, NULL, (void **)&positions));
1295 PetscCall(DMDAVecRestoreArrayRead(user->da, user->lDiffusivity, (void *)&diffusivity));
1296 }
1297 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lCoor, (void *)&coor));
1298
1299 // --- 3. What it carries, set where it crossed the face. Every rank calls this: see the plan. ---
1300 PetscCall(ParticleFieldPlanApply(user, plan, event, first, first + n_new));
1301
1302 // --- 4. How far it has come since; the search that follows finds its cell ---
1303 if (n_new > 0) {
1304 PetscReal *positions = NULL, *psi = NULL;
1305
1306 PetscCall(DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_POSITION), NULL, NULL, (void **)&positions));
1307 PetscCall(DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_PSI), NULL, NULL, (void **)&psi));
1308 for (PetscInt q = 0; q < n_new; ++q) {
1309 positions[3 * (first + q) + 0] += inward[q].x;
1310 positions[3 * (first + q) + 1] += inward[q].y;
1311 positions[3 * (first + q) + 2] += inward[q].z;
1312 sums[3] += psi[first + q];
1313 }
1314 PetscCall(DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_PSI), NULL, NULL, (void **)&psi));
1315 PetscCall(DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_POSITION), NULL, NULL, (void **)&positions));
1316 }
1317 PetscCall(PetscFree(inward));
1318 PetscCall(PetscFree5(count, cell_id, travel, normal_of, flux_bound));
1320 PetscFunctionReturn(0);
1321}
1322
1323/**
1324 * @brief Implementation of \ref InjectParticlesAtInlets().
1325 * @see InjectParticlesAtInlets()
1326 */
1328{
1329 SimCtx *simCtx = user->simCtx;
1330 PetscReal local[PARTICLE_INLET_FACE_COUNT][PARTICLE_INLET_SUMS] = {{0.0}};
1332 ParticleFieldEvent event = {0.0, 0};
1333 PetscInt64 faces = 0, first_id;
1334 VelocityPointInterpolator *velocity = NULL;
1335
1336 PetscFunctionBeginUser;
1338 if (simCtx->particleInletCount == 0) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
1339 {
1340 const PetscInt64 cells[3] = {user->info.mx - 2, user->info.my - 2, user->info.mz - 2};
1341 faces = 2 * (cells[0] * cells[1] + cells[1] * cells[2] + cells[2] * cells[0]);
1342 }
1343 first_id = (PetscInt64)simCtx->step * faces;
1344 PetscCheck((__int128)(simCtx->step + 1) * faces * PARTICLE_INLET_PIDS_PER_CELL + PARTICLE_INLET_PID_BASE < (__int128)PARTICLE_PID_LIMIT,
1345 PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE,
1346 "Step %" PetscInt_FMT " on a grid with %" PetscInt64_FMT " boundary face cells passes the last particle ID a "
1347 "checkpoint can store (2^53).", simCtx->step, faces);
1348 PetscCall(PicurvPhysicalTime(simCtx, simCtx->ti, &event.physical_time));
1349 PetscCall(InterpolateVelocityAtPointBegin(user, &velocity));
1350
1351 PetscReal cells_per_volume = 0.0;
1352 PetscBool have_cells_per_volume = PETSC_FALSE; /* computed when an inlet first needs it */
1353 for (PetscInt n = 0; n < simCtx->particleInletCount; ++n) {
1354 struct ParticleInlet *inlet = &simCtx->particleInlets[n];
1355
1356 if (!inlet->table_built) {
1357 const Cmpnts ***coor = NULL;
1358 PetscCheck(user->boundary_faces[inlet->face].mathematical_type == INLET, PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONG,
1359 "Face %s injects particles but is not an INLET.", BCFaceToString(inlet->face));
1360 PetscCall(DMDAVecGetArrayRead(user->fda, user->lCoor, (void *)&coor));
1361 PetscCall(BuildSeedingCellTable(user, coor, (PetscInt)inlet->face, 0, PETSC_TRUE, &inlet->table));
1362 if (!have_cells_per_volume) {
1363 /* particles_per_cell is a mean over the grid: cells over volume makes it a density,
1364 with the volume Volume seeding measures. table_built is the same on every rank,
1365 so all reduce. */
1366 SeedingCellTable volume;
1367
1368 PetscCall(BuildSeedingCellTable(user, coor, -1, 0, PETSC_FALSE, &volume));
1369 cells_per_volume = (PetscReal)(user->info.mx - 2) * (user->info.my - 2) * (user->info.mz - 2) / volume.total;
1370 PetscCall(FreeSeedingCellTable(&volume));
1371 have_cells_per_volume = PETSC_TRUE;
1372 }
1373 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lCoor, (void *)&coor));
1375 inlet->table_built = PETSC_TRUE;
1376 }
1377 PetscCall(InjectAtInlet(user, inlet, &event, first_id, velocity, local[n]));
1378 }
1379 PetscCall(InterpolateVelocityAtPointEnd(&velocity));
1380
1381 PetscCallMPI(MPI_Allreduce(local, global, PARTICLE_INLET_FACE_COUNT * PARTICLE_INLET_SUMS, MPIU_REAL, MPI_SUM, PETSC_COMM_WORLD));
1382 if (simCtx->rank == 0) {
1383 FILE *file = NULL;
1384
1385 PetscCall(PicurvOpenDiagnosticsCsv(simCtx, simCtx->analysis_dir, "particle_injection.csv",
1386 "step,physical_time,face,flow_rate,expected,injected,psi", &file));
1387 for (PetscInt n = 0; n < simCtx->particleInletCount; ++n) {
1388 fprintf(file, "%d,%.10e,%s,%.10e,%.10e,%.0f,%.10e\n", (int)simCtx->step, (double)event.physical_time,
1389 BCFaceToString(simCtx->particleInlets[n].face), (double)global[n][0], (double)global[n][1],
1390 (double)global[n][2], (double)global[n][3]);
1391 }
1392 PetscCheck(fclose(file) == 0, PETSC_COMM_SELF, PETSC_ERR_FILE_WRITE, "Unable to close the particle-injection diagnostics file.");
1393 }
1394 {
1395 PetscInt n_local = 0;
1396 PetscInt64 local_total, total = 0;
1397 char object[128];
1398
1399 PetscCall(DMSwarmGetLocalSize(user->swarm, &n_local));
1400 local_total = n_local;
1401 PetscCallMPI(MPI_Allreduce(&local_total, &total, 1, MPIU_INT64, MPI_SUM, PETSC_COMM_WORLD));
1402 PetscCall(PetscSNPrintf(object, sizeof(object), "the %" PetscInt64_FMT " particles after injection (three components each)", total));
1403 PetscCall(PicurvCheckPetscIntRange(PETSC_COMM_WORLD, 3 * total, object));
1404 }
1406 PetscFunctionReturn(0);
1407}
PetscErrorCode CanRankServiceFace(const DMDALocalInfo *info, PetscInt IM_nodes_global, PetscInt JM_nodes_global, PetscInt KM_nodes_global, BCFace face_id, PetscBool *can_service_out)
Determines if the current MPI rank owns any part of a specified global face.
Definition Boundaries.c:22
PetscErrorCode MetricJacobian(UserCtx *user, const Cmpnts ***X, PetscInt i, PetscInt j, PetscInt k, PetscReal xi, PetscReal eta, PetscReal zta, PetscReal J[3][3], PetscReal *detJ)
Evaluates the trilinear mapping Jacobian and its determinant in one cell.
Definition Metric.c:502
PetscErrorCode MetricLogicalToPhysical(UserCtx *user, const Cmpnts ***X, PetscInt i, PetscInt j, PetscInt k, PetscReal xi, PetscReal eta, PetscReal zta, Cmpnts *Xp)
Maps a logical point inside one hexahedral cell to physical space.
Definition Metric.c:475
Configured initial values of particle-carried fields.
PetscErrorCode ParticleFieldPlanApply(UserCtx *user, ParticleFieldPlan *plan, const ParticleFieldEvent *event, PetscInt first, PetscInt end)
Write the plan's values into swarm entries [first, end) of this rank.
PetscErrorCode ParticleFieldPlanDestroy(ParticleFieldPlan **plan)
Free a plan and its compiled expressions.
PetscErrorCode ParticleFieldPlanCreate(const char *prefix, ParticleFieldPlan **plan)
Read a plan from the options database.
PetscReal physical_time
Time, in seconds, the evaluated particles appear at.
When and why a plan is applied.
Header file for Particle Motion and migration related functions.
static void ParticleUniformsFromHash(uint64_t hash, PetscReal u[4])
Four uniforms in [0,1) from one keyed draw hash.
PetscErrorCode PreCheckAndResizeSwarm(UserCtx *user, PetscInt ti, const char *ext)
Checks particle count in the reference file and resizes the swarm if needed.
PetscErrorCode CalculateBrownianDisplacement(UserCtx *user, PetscInt64 pid, PetscReal diff_eff, Cmpnts *displacement)
Calculates the stochastic displacement vector (Brownian motion) for a single particle.
PetscErrorCode UpdateParticleWeights(PetscReal *d, Particle *particle)
Implementation of UpdateParticleWeights().
#define PARTICLE_INLET_PID_BASE
#define PARTICLE_INLET_SUMS
PetscErrorCode CreateParticleSwarm(UserCtx *user, PetscInt numParticles, PetscInt *particlesPerProcess)
Implementation of CreateParticleSwarm().
PetscInt64 * pid_hi
One past the last particle ID of each cell.
PetscErrorCode InjectParticlesAtInlets(UserCtx *user)
Implementation of InjectParticlesAtInlets().
PetscReal cells_per_volume
The grid's cells over its volume, set with the table.
PetscErrorCode DistributeParticles(PetscInt numParticles, PetscMPIInt rank, PetscMPIInt size, PetscInt *particlesPerProcess, PetscInt *remainder)
Implementation of DistributeParticles().
#define INTERPOLATION_DISTANCE_TOLERANCE
static PetscErrorCode DistributeParticlesByOwnedMeasure(UserCtx *user, PetscInt face, PetscInt numParticles, PetscInt *localCount)
Number of particles this rank seeds for volumetric or surface seeding.
#define SEEDING_FACE_OFFSET
PetscErrorCode ParticleInletsDestroy(SimCtx *simCtx)
Implementation of ParticleInletsDestroy().
SeedingCellTable table
The owned cells on the face; built at the first injection.
PetscInt face
-1 for the volume, otherwise the BCFace the points lie on
static PetscErrorCode BuildSeedingCellTable(UserCtx *user, const Cmpnts ***coor, PetscInt face, PetscInt numParticles, PetscBool build_bound, SeedingCellTable *table)
Decide which particles each owned cell seeds, the same way at every rank layout.
ParticleFieldPlan * plan
This inlet's field values; NULL uses the case's.
PetscInt origin[3]
Origin node of the box's first cell.
static PetscErrorCode FreeSeedingCellTable(SeedingCellTable *table)
Free the arrays of a SeedingCellTable.
PicurvExpression * particles_per_cell
Mean particles per cell the entering fluid carries, in t.
#define PARTICLE_INLET_PIDS_PER_CELL
PetscBool table_built
static PetscErrorCode InitializeParticleBasicProperties(UserCtx *user, PetscInt particlesPerProcess)
Initialize position-independent particle fields after a particle is created.
PetscInt64 * pid_lo
First particle ID of each cell.
static void SeedingCellOrigin(const SeedingCellTable *table, PetscInt c, PetscInt origin[3])
Origin node of cell c of a seeding table, cells numbered i fastest.
PetscInt count
Particles this rank seeds.
PetscReal total
Measure of every cell on every rank: the domain's volume or the face's area.
#define PARTICLE_INLET_FACE_COUNT
PetscInt n[3]
Cells per axis.
PetscReal * bound
Largest measure density in each cell (NULL when not built)
#define SEEDING_LOGIC_MARGIN
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)
Implementation of UnpackSwarmFields().
PetscErrorCode ParticleInletsCreate(SimCtx *simCtx)
Implementation of ParticleInletsCreate().
PetscErrorCode InitializeSwarm(UserCtx *user)
Implementation of InitializeSwarm().
static void SeedingLogicalPoint(const PetscReal u[3], PetscInt face, PetscReal logic[3])
Logical seeding coordinates from u: each clamped to [0, 1 - SEEDING_LOGIC_MARGIN],...
PetscErrorCode AssignInitialPropertiesToSwarm(UserCtx *user, PetscInt particlesPerProcess)
Implementation of AssignInitialPropertiesToSwarm().
PetscErrorCode UpdateSwarmFields(PetscInt i, const Particle *particle, PetscReal *positions, PetscReal *velocities, PetscReal *weights, PetscInt *cellIndices, PetscInt *status, PetscReal *diffusivity, Cmpnts *diffusivitygradient, PetscReal *psi)
Implementation of UpdateSwarmFields().
static PetscErrorCode SeedingMeasureDensity(UserCtx *user, const Cmpnts ***coor, PetscInt face, PetscInt i, PetscInt j, PetscInt k, const PetscReal logic[3], PetscReal *density)
Measure density at a logical point: the Jacobian determinant for the volume, or the area element |dx/...
PetscErrorCode InitializeParticleSwarm(SimCtx *simCtx)
Implementation of InitializeParticleSwarm().
PetscErrorCode RegisterSwarmField(DM swarm, const char *fieldName, PetscInt fieldDim, PetscDataType dtype)
Implementation of RegisterSwarmField().
static PetscErrorCode InitializeDefaultParticleFields(DM swarm, PetscInt first, PetscInt end)
Set local particles first to end - 1 of every field the particle catalog marks PARTICLE_FIELD_CAPABIL...
#define PARTICLE_PID_LIMIT
static PetscErrorCode DrawSeedingPoint(UserCtx *user, const Cmpnts ***coor, const SeedingCellTable *table, PetscInt c, PetscInt64 pid, const VelocityPointInterpolator *velocity, Cmpnts normal, PetscReal flux_bound, PetscInt *ci_metric_lnode_out, PetscInt *cj_metric_lnode_out, PetscInt *ck_metric_lnode_out, PetscReal *xi_metric_logic_out, PetscReal *eta_metric_logic_out, PetscReal *zta_metric_logic_out, Cmpnts *velocity_out)
Draw one particle's seeding point inside its cell, uniform in the cell's measure, or on a face in pro...
PetscErrorCode RegisterParticleFields(DM swarm)
Implementation of RegisterParticleFields().
static PetscErrorCode InjectAtInlet(UserCtx *user, struct ParticleInlet *inlet, const ParticleFieldEvent *event, PetscInt64 first_id, const VelocityPointInterpolator *velocity, PetscReal sums[4])
Add one inlet's particles for this step.
One inlet face that injects particles.
The owned cells a seeding mode places particles in, and which particles each gets.
Header file for Particle Swarm management functions.
PetscErrorCode PicurvExpressionEvaluate(const PicurvExpression *expression, const PetscReal *values, const PicurvExpressionDrawKey *key, PetscReal *result)
Evaluate a compiled expression.
Definition expression.c:724
PetscErrorCode PicurvExpressionDestroy(PicurvExpression **expression)
Free a compiled expression.
Definition expression.c:818
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
static PetscInt64 PicurvFaceCellId(const PetscInt nodes[3], BCFace face, PetscInt p, PetscInt q)
Global identity of a boundary face cell, unique over the six faces of a block and independent of the ...
Definition expression.h:275
@ PICURV_DRAW_SPACE_INLET
Injection at an inlet: stream 0 counts per face cell, stream 1 distance in.
Definition expression.h:34
@ PICURV_DRAW_SPACE_PLACEMENT
Seeding points; the salt is the rejection attempt.
Definition expression.h:33
PetscReal PicurvUnitFromHash(uint64_t hash)
Uniform on [0, 1) from the top 53 bits of a hash.
Definition expression.c:601
PetscErrorCode PicurvExpressionCompile(const char *text, const char *const *names, PetscInt name_count, PetscBool allow_random, PicurvExpression **expression)
Compile one expression against a list of variable names.
Definition expression.c:551
The arrays one method's point evaluation reads.
PetscErrorCode InterpolateVelocityAtPoint(const VelocityPointInterpolator *interp, const PetscInt cell[3], const PetscReal weights[3], Cmpnts point, Cmpnts *u)
The velocity a particle at a point would be given: the value the swarm pass of the configured method ...
PetscErrorCode InterpolateVelocityAtPointEnd(VelocityPointInterpolator **interp)
Closes the arrays InterpolateVelocityAtPointBegin() opened.
PetscErrorCode InterpolateVelocityAtPointBegin(UserCtx *user, VelocityPointInterpolator **interp)
Opens the arrays for evaluating the particle velocity at points, with the configured interpolation me...
PetscErrorCode ReadAllSwarmFields(UserCtx *user, PetscInt ti)
Reads multiple fields (positions, velocity, CellID, and weight) into a DMSwarm.
Definition io.c:1815
PetscErrorCode PicurvPhysicalTime(const SimCtx *simCtx, PetscReal solver_time, PetscReal *physical)
Convert a solver time to physical seconds, t * L_ref / U_ref.
Definition io.c:2986
#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
PetscBool is_function_allowed(const char *functionName)
Checks if a given function is in the allow-list.
Definition logging.c:207
#define LOG_ALLOW_SYNC(scope, level, fmt,...)
Synchronized logging macro that checks both the log level and whether the calling function is in the ...
Definition logging.h:273
#define 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
const char * BCFaceToString(BCFace face)
Returns the canonical log token for a boundary-face enum value.
Definition logging.c:640
static PetscErrorCode PicurvOpenDiagnosticsCsv(SimCtx *simCtx, const char *dir, const char *filename, const char *header, FILE **file)
Opens a per-step diagnostics CSV: PicurvOpenRunCsv() with the common settings.
Definition logging.h:1197
#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_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
#define PROFILE_FUNCTION_END
Marks the end of a profiled code block.
Definition logging.h:1029
@ LOG_ERROR
Critical errors that may halt the program.
Definition logging.h:29
@ LOG_INFO
Informational messages about program execution.
Definition logging.h:31
@ LOG_WARNING
Non-critical issues that warrant attention.
Definition logging.h:30
@ LOG_DEBUG
Detailed debugging information.
Definition logging.h:32
@ LOG_VERBOSE
Extremely detailed logs, typically for development use only.
Definition logging.h:34
#define PROFILE_FUNCTION_BEGIN
Marks the beginning of a profiled function: an always-on aggregate timer.
Definition logging.h:1000
const char * ParticleInitializationToString(ParticleInitializationType ParticleInitialization)
Returns the canonical log token for a particle-initialization mode.
Definition logging.c:662
static LogLevel get_log_level(void)
Retrieves the current logging level from the environment variable LOG_LEVEL.
Definition logging.h:496
const char * ParticleFieldName(ParticleFieldId field_id)
Return the canonical PETSc DMSwarm name for an ID.
ParticleFieldId
Compile-time identity for a persistent solver-particle field.
@ 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_COUNT
ParticleFieldRegistration registration
@ PARTICLE_FIELD_CAPABILITY_DEFAULT_INITIALIZE
@ PARTICLE_FIELD_REGISTRATION_PETSC
PetscErrorCode ParticleFieldGetDescriptor(ParticleFieldId field_id, const ParticleFieldDescriptor **descriptor)
Return immutable metadata for a valid particle field ID.
Immutable metadata for one persistent particle field.
PetscErrorCode GetOwnedCellRange(const DMDALocalInfo *info_nodes, PetscInt dim, PetscInt *xs_cell_global_out, PetscInt *xm_cell_local_out)
Determines the global starting index and number of CELLS owned by the current processor in a specifie...
Definition setup.c:3021
PetscErrorCode PicurvCheckPetscIntRange(MPI_Comm comm, PetscInt64 entries, const char *object)
Refuse a PETSc object whose global size this build's PetscInt cannot index.
Definition setup.c:102
PetscInt particleInletCount
Entries of particleInlets.
Definition variables.h:1065
@ INLET
Definition variables.h:323
Cmpnts vel
Definition variables.h:240
UserCtx * user
Definition variables.h:768
PetscBool inletFaceDefined
Definition variables.h:1183
PetscMPIInt rank
Definition variables.h:919
BoundaryFaceConfig boundary_faces[6]
Definition variables.h:1182
BCFace identifiedInletBCFace
Definition variables.h:1184
PetscInt cell[3]
Definition variables.h:238
SimCtx * simCtx
Back-pointer to the master simulation context.
Definition variables.h:1160
@ PARTICLE_INIT_SURFACE_RANDOM
Random placement on the inlet face.
Definition variables.h:747
@ PARTICLE_INIT_POINT_SOURCE
All particles at a fixed (psrc_x,psrc_y,psrc_z) — for validation.
Definition variables.h:749
@ PARTICLE_INIT_VOLUME
Random volumetric distribution across the domain.
Definition variables.h:748
ParticleLocationStatus
Defines the state of a particle with respect to its location and migration status during the iterativ...
Definition variables.h:186
@ NEEDS_LOCATION
Definition variables.h:187
@ ACTIVE_AND_LOCATED
Definition variables.h:188
@ UNINITIALIZED
Definition variables.h:191
PetscReal Min_X
Definition variables.h:1172
PetscInt KM
Definition variables.h:1171
UserMG usermg
Definition variables.h:1082
PetscReal L_ref
Definition variables.h:898
PetscReal psrc_x
Definition variables.h:1002
Cmpnts max_coords
Maximum x, y, z coordinates of the bounding box.
Definition variables.h:214
Cmpnts diffusivitygradient
Definition variables.h:245
PetscReal dt
Definition variables.h:933
PetscInt np
Definition variables.h:1049
PetscReal Max_Y
Definition variables.h:1172
PetscInt StartStep
Definition variables.h:926
Cmpnts min_coords
Minimum x, y, z coordinates of the bounding box.
Definition variables.h:213
PetscScalar x
Definition variables.h:145
Cmpnts loc
Definition variables.h:239
PetscMPIInt destination_rank
Definition variables.h:243
PetscReal psrc_z
Point source location for PARTICLE_INIT_POINT_SOURCE.
Definition variables.h:1002
ParticleLocationStatus location_status
Definition variables.h:242
char analysis_dir[PETSC_MAX_PATH_LEN]
Definition variables.h:942
char particleRestartMode[16]
Definition variables.h:1056
ParticleInitializationType ParticleInitialization
Definition variables.h:1054
PetscScalar z
Definition variables.h:145
ScalingCtx scaling
Definition variables.h:1003
PetscInt JM
Definition variables.h:1171
PetscInt mglevels
Definition variables.h:775
PetscReal Min_Z
Definition variables.h:1172
PetscReal psrc_y
Definition variables.h:1002
Vec lCoor
Definition variables.h:1243
PetscInt particleRandomSeed
Base seed for every particle RNG stream (-particle_random_seed).
Definition variables.h:1050
PetscReal Max_X
Definition variables.h:1172
PetscReal Min_Y
Definition variables.h:1172
PetscReal diffusivity
Definition variables.h:244
Vec lUcont
Definition variables.h:1197
PetscInt step
Definition variables.h:924
PetscReal psi
Definition variables.h:246
DMDALocalInfo info
Definition variables.h:1169
PetscScalar y
Definition variables.h:145
PetscMPIInt size
Definition variables.h:920
@ EXEC_MODE_POSTPROCESSOR
Definition variables.h:889
PetscInt IM
Definition variables.h:1171
Cmpnts weights
Definition variables.h:241
@ 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
MGCtx * mgctx
Definition variables.h:778
Vec lDiffusivity
Definition variables.h:1200
BCType mathematical_type
Definition variables.h:426
ExecutionMode exec_mode
Definition variables.h:937
BoundingBox bbox
Definition variables.h:1173
PetscReal ti
Definition variables.h:925
PetscReal Max_Z
Definition variables.h:1172
PetscInt64 PID
Definition variables.h:237
PetscReal U_ref
Definition variables.h:899
struct ParticleInlet * particleInlets
Inlet faces that inject particles, or NULL.
Definition variables.h:1064
struct ParticleFieldPlan * particleFieldPlan
Configured initial particle-field values, or NULL.
Definition variables.h:1063
BCFace
Identifies the six logical faces of a structured computational block.
Definition variables.h:308
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
The master context for the entire simulation.
Definition variables.h:916
User-defined context containing data specific to a single computational grid level.
Definition variables.h:1157
PetscBool VerificationScalarOverrideActive(const SimCtx *simCtx)
Reports whether a verification-only scalar override is active.
PetscErrorCode LocateParticleOrFindMigrationTarget(UserCtx *user, const struct FacePlaneArrays *planes, Particle *particle, ParticleLocationStatus *status_out)