PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
test_runtime_kernels.c
Go to the documentation of this file.
1/**
2 * @file test_runtime_kernels.c
3 * @brief C unit tests for runtime, particle, wall, and walltime-guard helpers.
4 */
5
6#include "test_support.h"
7
8#include "BC_Handlers.h"
9#include "ParticleMotion.h"
10#include "ParticlePhysics.h"
11#include "ParticleSwarm.h"
12#include "interpolation.h"
13#include "initialcondition.h"
14#include "les.h"
15#include "runloop.h"
16#include "setup.h"
17#include "wallfunction.h"
18#include "walkingsearch.h"
19
20/**
21 * @brief Synchronizes the minimal runtime fixture's global fields into their persistent local ghosts.
22 */
23static PetscErrorCode SyncRuntimeFieldGhosts(UserCtx *user)
24{
25 PetscFunctionBeginUser;
26 PetscCall(DMGlobalToLocalBegin(user->da, user->P, INSERT_VALUES, user->lP));
27 PetscCall(DMGlobalToLocalEnd(user->da, user->P, INSERT_VALUES, user->lP));
28 PetscCall(DMGlobalToLocalBegin(user->da, user->Psi, INSERT_VALUES, user->lPsi));
29 PetscCall(DMGlobalToLocalEnd(user->da, user->Psi, INSERT_VALUES, user->lPsi));
30 PetscCall(DMGlobalToLocalBegin(user->da, user->Diffusivity, INSERT_VALUES, user->lDiffusivity));
31 PetscCall(DMGlobalToLocalEnd(user->da, user->Diffusivity, INSERT_VALUES, user->lDiffusivity));
32 PetscCall(DMGlobalToLocalBegin(user->fda, user->Ucat, INSERT_VALUES, user->lUcat));
33 PetscCall(DMGlobalToLocalEnd(user->fda, user->Ucat, INSERT_VALUES, user->lUcat));
34 PetscCall(DMGlobalToLocalBegin(user->fda, user->Ucont, INSERT_VALUES, user->lUcont));
35 PetscCall(DMGlobalToLocalEnd(user->fda, user->Ucont, INSERT_VALUES, user->lUcont));
36 PetscCall(DMGlobalToLocalBegin(user->fda, user->DiffusivityGradient, INSERT_VALUES, user->lDiffusivityGradient));
37 PetscCall(DMGlobalToLocalEnd(user->fda, user->DiffusivityGradient, INSERT_VALUES, user->lDiffusivityGradient));
38 PetscFunctionReturn(0);
39}
40
41/**
42 * @brief Seeds one localized swarm particle with the cell, position, weight, and status data used by runtime tests.
43 */
44static PetscErrorCode SeedSingleParticle(UserCtx *user,
45 PetscInt ci,
46 PetscInt cj,
47 PetscInt ck,
48 PetscReal x,
49 PetscReal y,
50 PetscReal z,
51 PetscReal wx,
52 PetscReal wy,
53 PetscReal wz,
54 PetscInt status_value)
55{
56 PetscReal *positions = NULL;
57 PetscReal *weights = NULL;
58 PetscInt *cell_ids = NULL;
59 PetscInt *status = NULL;
60
61 PetscFunctionBeginUser;
62 PetscCall(DMSwarmGetField(user->swarm, "position", NULL, NULL, (void **)&positions));
63 PetscCall(DMSwarmGetField(user->swarm, "weight", NULL, NULL, (void **)&weights));
64 PetscCall(DMSwarmGetField(user->swarm, "DMSwarm_CellID", NULL, NULL, (void **)&cell_ids));
65 PetscCall(DMSwarmGetField(user->swarm, "DMSwarm_location_status", NULL, NULL, (void **)&status));
66
67 positions[0] = x;
68 positions[1] = y;
69 positions[2] = z;
70 weights[0] = wx;
71 weights[1] = wy;
72 weights[2] = wz;
73 cell_ids[0] = ci;
74 cell_ids[1] = cj;
75 cell_ids[2] = ck;
76 status[0] = status_value;
77
78 PetscCall(DMSwarmRestoreField(user->swarm, "DMSwarm_location_status", NULL, NULL, (void **)&status));
79 PetscCall(DMSwarmRestoreField(user->swarm, "DMSwarm_CellID", NULL, NULL, (void **)&cell_ids));
80 PetscCall(DMSwarmRestoreField(user->swarm, "weight", NULL, NULL, (void **)&weights));
81 PetscCall(DMSwarmRestoreField(user->swarm, "position", NULL, NULL, (void **)&positions));
82 PetscFunctionReturn(0);
83}
84/**
85 * @brief Tests particle distribution remainder handling across ranks.
86 */
87
89{
90 PetscInt particles_per_rank = -1;
91 PetscInt remainder = -1;
92
93 PetscFunctionBeginUser;
94 PetscCall(DistributeParticles(10, 0, 3, &particles_per_rank, &remainder));
95 PetscCall(PicurvAssertIntEqual(4, particles_per_rank, "rank 0 should receive one remainder particle"));
96 PetscCall(PicurvAssertIntEqual(1, remainder, "remainder should be reported correctly"));
97
98 PetscCall(DistributeParticles(10, 2, 3, &particles_per_rank, &remainder));
99 PetscCall(PicurvAssertIntEqual(3, particles_per_rank, "last rank should receive base particle count"));
100 PetscCall(PicurvAssertIntEqual(1, remainder, "remainder should remain unchanged across ranks"));
101 PetscFunctionReturn(0);
102}
103/**
104 * @brief Tests basic particle-inside-bounding-box classification cases.
105 */
106
107static PetscErrorCode TestIsParticleInBoxBasicCases(void)
108{
109 BoundingBox bbox;
110 Cmpnts pos;
111
112 PetscFunctionBeginUser;
113 PetscCall(PetscMemzero(&bbox, sizeof(bbox)));
114
115 bbox.min_coords.x = 0.0;
116 bbox.min_coords.y = 0.0;
117 bbox.min_coords.z = 0.0;
118 bbox.max_coords.x = 1.0;
119 bbox.max_coords.y = 2.0;
120 bbox.max_coords.z = 3.0;
121
122 pos.x = 0.25;
123 pos.y = 1.0;
124 pos.z = 2.5;
125 PetscCall(PicurvAssertBool(IsParticleInBox(&bbox, &pos), "particle should be inside bounding box"));
126
127 pos.x = 1.0;
128 PetscCall(PicurvAssertBool(IsParticleInBox(&bbox, &pos), "particle on the box face should count as inside"));
129
130 pos.x = 1.5;
131 PetscCall(PicurvAssertBool((PetscBool)!IsParticleInBox(&bbox, &pos), "particle should be outside bounding box"));
132 PetscFunctionReturn(0);
133}
134/**
135 * @brief Tests particle weight updates against expected ratios.
136 */
137
139{
140 Particle particle;
141 PetscReal distances[NUM_FACES] = {1.0, 3.0, 2.0, 2.0, 4.0, 1.0};
142 PetscReal clamped[NUM_FACES] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
143
144 PetscFunctionBeginUser;
145 PetscCall(PetscMemzero(&particle, sizeof(particle)));
146 PetscCall(UpdateParticleWeights(distances, &particle));
147 PetscCall(PicurvAssertRealNear(0.25, particle.weights.x, 1.0e-12, "x interpolation weight"));
148 PetscCall(PicurvAssertRealNear(0.5, particle.weights.y, 1.0e-12, "y interpolation weight"));
149 PetscCall(PicurvAssertRealNear(0.2, particle.weights.z, 1.0e-12, "z interpolation weight"));
150
151 PetscCall(UpdateParticleWeights(clamped, &particle));
152 PetscCall(PicurvAssertRealNear(0.5, particle.weights.x, 1.0e-12, "clamped x weight remains centered"));
153 PetscCall(PicurvAssertRealNear(0.5, particle.weights.y, 1.0e-12, "clamped y weight remains centered"));
154 PetscCall(PicurvAssertRealNear(0.5, particle.weights.z, 1.0e-12, "clamped z weight remains centered"));
155 PetscFunctionReturn(0);
156}
157/**
158 * @brief Tests particle position updates without Brownian forcing.
159 */
160
162{
163 SimCtx *simCtx = NULL;
164 UserCtx *user = NULL;
165 Particle particle;
166
167 PetscFunctionBeginUser;
168 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
169 simCtx->dt = 0.25;
170
171 PetscCall(PetscMemzero(&particle, sizeof(particle)));
172 particle.loc.x = 1.0;
173 particle.loc.y = -2.0;
174 particle.loc.z = 3.0;
175 particle.vel.x = 0.5;
176 particle.vel.y = -1.0;
177 particle.vel.z = 2.0;
178 particle.diffusivitygradient.x = 0.1;
179 particle.diffusivitygradient.y = 0.2;
180 particle.diffusivitygradient.z = -0.3;
181 particle.diffusivity = 0.0;
182
183 PetscCall(UpdateParticlePosition(user, &particle));
184 PetscCall(PicurvAssertRealNear(1.15, particle.loc.x, 1.0e-12, "x position update"));
185 PetscCall(PicurvAssertRealNear(-2.2, particle.loc.y, 1.0e-12, "y position update"));
186 PetscCall(PicurvAssertRealNear(3.425, particle.loc.z, 1.0e-12, "z position update"));
187
188 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
189 PetscFunctionReturn(0);
190}
191/**
192 * @brief Tests particle position updates driven only by diffusivity-gradient drift.
193 */
194
196{
197 SimCtx *simCtx = NULL;
198 UserCtx *user = NULL;
199 Particle particle;
200
201 PetscFunctionBeginUser;
202 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
203 simCtx->dt = 0.5;
204
205 PetscCall(PetscMemzero(&particle, sizeof(particle)));
206 particle.loc.x = 0.25;
207 particle.loc.y = 0.5;
208 particle.loc.z = 0.75;
209 particle.vel.x = 0.0;
210 particle.vel.y = 0.0;
211 particle.vel.z = 0.0;
212 particle.diffusivitygradient.x = 0.2;
213 particle.diffusivitygradient.y = -0.1;
214 particle.diffusivitygradient.z = 0.3;
215 particle.diffusivity = 0.0;
216
217 PetscCall(UpdateParticlePosition(user, &particle));
218 PetscCall(PicurvAssertRealNear(0.35, particle.loc.x, 1.0e-12, "drift-only x position update"));
219 PetscCall(PicurvAssertRealNear(0.45, particle.loc.y, 1.0e-12, "drift-only y position update"));
220 PetscCall(PicurvAssertRealNear(0.90, particle.loc.z, 1.0e-12, "drift-only z position update"));
221
222 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
223 PetscFunctionReturn(0);
224}
225/**
226 * @brief Tests IEM relaxation updates for particle-carried fields.
227 */
228
229static PetscErrorCode TestUpdateParticleFieldIEMRelaxation(void)
230{
231 PetscReal psi = 1.0;
232 const PetscReal dt = 0.5;
233 const PetscReal diffusivity = 0.2;
234 const PetscReal mean_val = 3.0;
235 const PetscReal cell_vol = 8.0;
236 const PetscReal c_model = 2.0;
237 PetscReal unchanged = 7.0;
238
239 PetscFunctionBeginUser;
240 PetscCall(UpdateParticleField(PARTICLE_FIELD_ID_PSI, dt, &psi, diffusivity, mean_val, PetscPowReal(cell_vol, 0.6666667), c_model));
241 PetscCall(PicurvAssertRealNear(
242 mean_val + (1.0 - mean_val) * PetscExpReal(-(c_model * diffusivity / PetscPowReal(cell_vol, 0.6666667)) * dt),
243 psi,
244 1.0e-12,
245 "IEM update should match analytical relaxation"));
246
247 PetscCall(UpdateParticleField(PARTICLE_FIELD_ID_VELOCITY, dt, &unchanged, diffusivity, mean_val, PetscPowReal(cell_vol, 0.6666667), c_model));
248 PetscCall(PicurvAssertRealNear(7.0, unchanged, 1.0e-12, "unknown field should remain unchanged"));
249 PetscFunctionReturn(0);
250}
251/**
252 * @brief Tests spatially varying Cartesian-field conversion to contravariant fluxes.
253 */
254static PetscErrorCode TestCart2ContraConvertsCartesianField(void)
255{
256 SimCtx *simCtx = NULL;
257 UserCtx *user = NULL;
258 Cmpnts ***ucat = NULL;
259 Cmpnts ***ucont = NULL;
260
261 PetscFunctionBeginUser;
262 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 5, 5, 5));
263 PetscCall(DMDAVecGetArray(user->fda, user->Ucat, &ucat));
264 for (PetscInt k = 0; k < 6; k++)
265 for (PetscInt j = 0; j < 6; j++)
266 for (PetscInt i = 0; i < 6; i++)
267 ucat[k][j][i] = (Cmpnts){(PetscReal)i, 2.0, 3.0};
268 PetscCall(DMDAVecRestoreArray(user->fda, user->Ucat, &ucat));
269 PetscCall(UpdateLocalGhosts(user, FIELD_ID_UCAT));
270 PetscCall(Cart2Contra(user));
271
272 PetscCall(DMDAVecGetArrayRead(user->fda, user->Ucont, &ucont));
273 PetscCall(PicurvAssertRealNear(1.5, ucont[1][1][1].x, 1.0e-10,
274 "Xi flux uses face-interpolated Ucat"));
275 PetscCall(PicurvAssertRealNear(2.0, ucont[1][1][1].y, 1.0e-10,
276 "Eta flux uses Cartesian y velocity"));
277 PetscCall(PicurvAssertRealNear(3.0, ucont[1][1][1].z, 1.0e-10,
278 "Zeta flux uses Cartesian z velocity"));
279 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->Ucont, &ucont));
280
281 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
282 PetscFunctionReturn(0);
283}
284
285/** @brief Verifies periodic Ucat endpoints are repaired before Cart2Contra terminal faces. */
287{
288 SimCtx *simCtx=NULL; UserCtx *user=NULL; Cmpnts ***ucat=NULL,***ucont=NULL; PetscInt mx;
289 const FieldId cell_fields[] = {FIELD_ID_UCAT}, staggered_fields[] = {FIELD_ID_UCONT};
290 PetscFunctionBeginUser;
291 PetscCall(PicurvCreateMinimalContextsWithPeriodicity(&simCtx,&user,4,4,4,PETSC_TRUE,PETSC_FALSE,PETSC_FALSE));
294 mx=user->info.mx;
295 PetscCall(VecSet(user->Ucat,0.0));
296 PetscCall(DMDAVecGetArray(user->fda,user->Ucat,&ucat));
297 for(PetscInt k=1;k<user->info.mz-1;k++) for(PetscInt j=1;j<user->info.my-1;j++)
298 for(PetscInt i=1;i<mx-1;i++) ucat[k][j][i]=(Cmpnts){10.0+(PetscReal)i,2.0,3.0};
299 ucat[2][2][0]=(Cmpnts){-1000.0,-1000.0,-1000.0};
300 ucat[2][2][mx-1]=(Cmpnts){-2000.0,-2000.0,-2000.0};
301 PetscCall(DMDAVecRestoreArray(user->fda,user->Ucat,&ucat));
302 PetscCall(SynchronizePeriodicCellFields(user,1,cell_fields));
303 PetscCall(UpdateLocalGhosts(user, FIELD_ID_UCAT));
304 PetscCall(Cart2Contra(user));
305 PetscCall(SynchronizePeriodicStaggeredFields(user,1,staggered_fields));
306 PetscCall(DMDAVecGetArrayRead(user->fda,user->Ucont,&ucont));
307 PetscCall(PicurvAssertRealNear(0.5*((10.0+mx-2)+(10.0+1)),ucont[2][2][mx-2].x,1e-12,"terminal Xi face uses corrected periodic Ucat endpoint"));
308 PetscCall(DMDAVecRestoreArrayRead(user->fda,user->Ucont,&ucont));
309 PetscCall(PicurvDestroyMinimalContexts(&simCtx,&user));
310 PetscFunctionReturn(0);
311}
312
313/**
314 * @brief Tests loading a staged Ucat file IC and converting it to Ucont.
315 */
317{
318 SimCtx *simCtx = NULL;
319 UserCtx *user = NULL;
320 Cmpnts ***ucont = NULL;
321 char tmpdir[PETSC_MAX_PATH_LEN];
322
323 PetscFunctionBeginUser;
324 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
325 PetscCall(PicurvMakeTempDir(tmpdir, sizeof(tmpdir)));
326 PetscCall(VecSet(user->Ucat, 2.5));
327 PetscCall(PetscStrncpy(simCtx->_io_context_buffer, tmpdir, sizeof(simCtx->_io_context_buffer)));
329 PetscCall(WriteFieldData(user, "ufield00000_0", user->Ucat, "dat"));
330 simCtx->current_io_directory = NULL;
331
332 PetscCall(VecZeroEntries(user->Ucat));
333 PetscCall(VecZeroEntries(user->Ucont));
334 simCtx->initialConditionStaged = PETSC_TRUE;
336 PetscCall(PetscStrncpy(simCtx->initialConditionDirectory, tmpdir, sizeof(simCtx->initialConditionDirectory)));
337 PetscCall(PopulateInitialUcont(user));
338
339 PetscCall(PicurvAssertVecConstant(user->Ucat, 2.5, 1.0e-12, "file IC should restore Ucat"));
340 PetscCall(DMDAVecGetArrayRead(user->fda, user->Ucont, &ucont));
341 PetscCall(PicurvAssertRealNear(2.5, ucont[1][1][1].x, 1.0e-12, "file Ucat IC should populate interior Xi flux"));
342 PetscCall(PicurvAssertRealNear(2.5, ucont[1][1][1].y, 1.0e-12, "file Ucat IC should populate interior Eta flux"));
343 PetscCall(PicurvAssertRealNear(2.5, ucont[1][1][1].z, 1.0e-12, "file Ucat IC should populate interior Zeta flux"));
344 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->Ucont, &ucont));
345 PetscCall(PicurvRemoveTempDir(tmpdir));
346 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
347 PetscFunctionReturn(0);
348}
349
350/** @brief Tests LES output staging from local vectors on a multiply periodic DMDA. */
352{
353 SimCtx *simCtx = NULL;
354 UserCtx *user = NULL;
355 char tmpdir[PETSC_MAX_PATH_LEN];
356 char euler_dir[PETSC_MAX_PATH_LEN];
357 char block_dir[PETSC_MAX_PATH_LEN];
358
359 PetscFunctionBeginUser;
361 &simCtx, &user, 4, 4, 4, PETSC_TRUE, PETSC_TRUE, PETSC_TRUE));
362 PetscCall(DMCreateGlobalVector(user->da, &user->CS));
363 PetscCall(DMCreateLocalVector(user->da, &user->lCs));
364 PetscCall(DMCreateGlobalVector(user->da, &user->Nu_t));
365 PetscCall(DMCreateLocalVector(user->da, &user->lNu_t));
366 PetscCall(VecSet(user->CS, 0.0));
367 PetscCall(VecSet(user->lCs, 2.5));
368 PetscCall(VecSet(user->Nu_t, 0.0));
369 PetscCall(VecSet(user->lNu_t, 7.5));
370 simCtx->les = DYNAMIC_SMAGORINSKY;
371
372 PetscCall(PicurvMakeTempDir(tmpdir, sizeof(tmpdir)));
373 PetscCall(PetscSNPrintf(euler_dir, sizeof(euler_dir), "%s/eulerian", tmpdir));
374 PetscCall(PetscSNPrintf(block_dir, sizeof(block_dir), "%s/block_0000", euler_dir));
375 PetscCall(PicurvEnsureDir(euler_dir));
376 PetscCall(PicurvEnsureDir(block_dir));
377 PetscCall(WriteSimulationFields(user, tmpdir));
378
379 PetscCall(PicurvAssertVecConstant(user->CS, 2.5, 1.0e-12,
380 "checkpoint output should copy owned periodic lCs values"));
381 PetscCall(PicurvAssertVecConstant(user->Nu_t, 7.5, 1.0e-12,
382 "checkpoint output should copy owned periodic lNu_t values"));
383
384 PetscCall(PicurvRemoveTempDir(tmpdir));
385 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
386 PetscFunctionReturn(0);
387}
388
389/**
390 * @brief Stages a real Cartesian Fourier mode through the production file-IC path.
391 *
392 * The returned maximum is the native face-interpolation/backward-difference
393 * divergence. On the uniform periodic fixture its symbol is
394 * (sin(theta_x), sin(theta_y), sin(theta_z)).
395 */
396static PetscErrorCode StagedFourierModeMaxDivergence(UserCtx *user,
397 PetscInt mode_x,
398 PetscInt mode_y,
399 PetscInt mode_z,
400 Cmpnts amplitude,
401 const char *tmpdir,
402 PetscReal *max_divergence)
403{
404 SimCtx *simCtx = user->simCtx;
405 Cmpnts ***ucat = NULL, ***ucont = NULL;
406 PetscInt n_x = user->info.mx - 2, n_y = user->info.my - 2, n_z = user->info.mz - 2;
407 const FieldId staggered_fields[] = {FIELD_ID_UCONT};
408
409 PetscFunctionBeginUser;
410 PetscCall(VecZeroEntries(user->Ucat));
411 PetscCall(DMDAVecGetArray(user->fda, user->Ucat, &ucat));
412 for (PetscInt k = 0; k < user->info.mz; ++k) {
413 for (PetscInt j = 0; j < user->info.my; ++j) {
414 for (PetscInt i = 0; i < user->info.mx; ++i) {
415 PetscReal phase = 2.0 * PETSC_PI * (
416 (PetscReal)(mode_x * (i - 1)) / (PetscReal)n_x +
417 (PetscReal)(mode_y * (j - 1)) / (PetscReal)n_y +
418 (PetscReal)(mode_z * (k - 1)) / (PetscReal)n_z);
419 PetscReal wave = PetscCosReal(phase);
420 ucat[k][j][i] = (Cmpnts){amplitude.x * wave, amplitude.y * wave, amplitude.z * wave};
421 }
422 }
423 }
424 PetscCall(DMDAVecRestoreArray(user->fda, user->Ucat, &ucat));
425
426 PetscCall(PetscStrncpy(simCtx->_io_context_buffer, tmpdir, sizeof(simCtx->_io_context_buffer)));
428 PetscCall(WriteFieldData(user, "ufield00000_0", user->Ucat, "dat"));
429 simCtx->current_io_directory = NULL;
430 PetscCall(VecZeroEntries(user->Ucat));
431 PetscCall(VecZeroEntries(user->Ucont));
432 PetscCall(PopulateInitialUcont(user));
433 PetscCall(SynchronizePeriodicStaggeredFields(user, 1, staggered_fields));
434 PetscCall(UpdateLocalGhosts(user, FIELD_ID_UCONT));
435
436 *max_divergence = 0.0;
437 PetscCall(DMDAVecGetArrayRead(user->fda, user->lUcont, &ucont));
438 for (PetscInt k = 1; k < user->info.mz - 1; ++k) {
439 for (PetscInt j = 1; j < user->info.my - 1; ++j) {
440 for (PetscInt i = 1; i < user->info.mx - 1; ++i) {
441 PetscReal divergence =
442 ucont[k][j][i].x - ucont[k][j][i - 1].x +
443 ucont[k][j][i].y - ucont[k][j - 1][i].y +
444 ucont[k][j][i].z - ucont[k - 1][j][i].z;
445 *max_divergence = PetscMax(*max_divergence, PetscAbsReal(divergence));
446 }
447 }
448 }
449 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lUcont, &ucont));
450 PetscFunctionReturn(0);
451}
452
453/** @brief Cross-checks selected exact Fourier modes against PICurv's native discrete symbol. */
455{
456 SimCtx *simCtx = NULL;
457 UserCtx *user = NULL;
458 char tmpdir[PETSC_MAX_PATH_LEN];
459 PetscReal max_divergence = 0.0, sx, sy, sz;
460 PetscInt n;
461
462 PetscFunctionBeginUser;
464 &simCtx, &user, 9, 9, 9, PETSC_TRUE, PETSC_TRUE, PETSC_TRUE));
465 for (PetscInt face = 0; face < NUM_FACES; ++face)
467 PetscCall(PicurvMakeTempDir(tmpdir, sizeof(tmpdir)));
468 simCtx->initialConditionStaged = PETSC_TRUE;
470 PetscCall(PetscStrncpy(simCtx->initialConditionDirectory, tmpdir, sizeof(simCtx->initialConditionDirectory)));
471
473 user, 1, 0, 0, (Cmpnts){0.0, 1.0, 0.0}, tmpdir, &max_divergence));
474 PetscCall(PicurvAssertRealNear(0.0, max_divergence, 1.0e-12,
475 "axis-aligned transverse staged mode"));
476
477 n = user->info.mx - 2;
478 sx = PetscSinReal(2.0 * PETSC_PI / (PetscReal)n);
479 sy = PetscSinReal(4.0 * PETSC_PI / (PetscReal)n);
480 sz = PetscSinReal(6.0 * PETSC_PI / (PetscReal)n);
482 user, 1, 2, 0, (Cmpnts){sy, -sx, 0.0}, tmpdir, &max_divergence));
483 PetscCall(PicurvAssertRealNear(0.0, max_divergence, 1.0e-12,
484 "oblique first discrete transverse polarization"));
486 user, 1, 2, 3,
487 (Cmpnts){sz * sx, sz * sy, -(sx * sx + sy * sy)},
488 tmpdir, &max_divergence));
489 PetscCall(PicurvAssertRealNear(0.0, max_divergence, 1.0e-12,
490 "oblique second discrete transverse polarization"));
491
492 PetscCall(PicurvRemoveTempDir(tmpdir));
493 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
494 PetscFunctionReturn(0);
495}
496
497/**
498 * @brief Tests loading a staged Ucont file IC without Cartesian conversion.
499 */
501{
502 SimCtx *simCtx = NULL;
503 UserCtx *user = NULL;
504 char tmpdir[PETSC_MAX_PATH_LEN];
505
506 PetscFunctionBeginUser;
507 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
508 PetscCall(PicurvMakeTempDir(tmpdir, sizeof(tmpdir)));
509 PetscCall(VecSet(user->Ucont, 4.5));
510 PetscCall(PetscStrncpy(simCtx->_io_context_buffer, tmpdir, sizeof(simCtx->_io_context_buffer)));
512 PetscCall(WriteFieldData(user, "vfield00000_0", user->Ucont, "dat"));
513 simCtx->current_io_directory = NULL;
514
515 PetscCall(VecZeroEntries(user->Ucont));
516 simCtx->initialConditionStaged = PETSC_TRUE;
518 PetscCall(PetscStrncpy(simCtx->initialConditionDirectory, tmpdir, sizeof(simCtx->initialConditionDirectory)));
519 PetscCall(PopulateInitialUcont(user));
520
521 PetscCall(PicurvAssertVecConstant(user->Ucont, 4.5, 1.0e-12, "file Ucont IC should restore Ucont directly"));
522 PetscCall(PicurvRemoveTempDir(tmpdir));
523 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
524 PetscFunctionReturn(0);
525}
526/**
527 * @brief Tests direct interpolation from Eulerian fields to one localized swarm particle.
528 */
529
531{
532 SimCtx *simCtx = NULL;
533 UserCtx *user = NULL;
534 Cmpnts ***grad = NULL;
535 PetscReal *velocity = NULL;
536 PetscReal *diffusivity = NULL;
537 PetscReal *diffusivity_gradient = NULL;
538
539 PetscFunctionBeginUser;
540 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
541 PetscCall(PicurvCreateSwarmPair(user, 1, "ske"));
542 PetscCall(VecSet(user->Ucat, 2.0));
543 PetscCall(VecSet(user->Diffusivity, 0.25));
544
545 PetscCall(DMDAVecGetArray(user->fda, user->DiffusivityGradient, &grad));
546 for (PetscInt k = user->info.zs; k < user->info.zs + user->info.zm; ++k) {
547 for (PetscInt j = user->info.ys; j < user->info.ys + user->info.ym; ++j) {
548 for (PetscInt i = user->info.xs; i < user->info.xs + user->info.xm; ++i) {
549 grad[k][j][i].x = 0.1;
550 grad[k][j][i].y = 0.2;
551 grad[k][j][i].z = 0.3;
552 }
553 }
554 }
555 PetscCall(DMDAVecRestoreArray(user->fda, user->DiffusivityGradient, &grad));
556 PetscCall(SyncRuntimeFieldGhosts(user));
557 PetscCall(SeedSingleParticle(user, 0, 0, 0, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, ACTIVE_AND_LOCATED));
558
559 PetscCall(InterpolateAllFieldsToSwarm(user));
560
561 PetscCall(DMSwarmGetField(user->swarm, "velocity", NULL, NULL, (void **)&velocity));
562 PetscCall(DMSwarmGetField(user->swarm, "Diffusivity", NULL, NULL, (void **)&diffusivity));
563 PetscCall(DMSwarmGetField(user->swarm, "DiffusivityGradient", NULL, NULL, (void **)&diffusivity_gradient));
564 PetscCall(PicurvAssertRealNear(2.0, velocity[0], 1.0e-12, "Interpolated velocity x should match constant Eulerian field"));
565 PetscCall(PicurvAssertRealNear(2.0, velocity[1], 1.0e-12, "Interpolated velocity y should match constant Eulerian field"));
566 PetscCall(PicurvAssertRealNear(2.0, velocity[2], 1.0e-12, "Interpolated velocity z should match constant Eulerian field"));
567 PetscCall(PicurvAssertRealNear(0.25, diffusivity[0], 1.0e-12, "Interpolated scalar diffusivity should match constant Eulerian field"));
568 PetscCall(PicurvAssertRealNear(0.1, diffusivity_gradient[0], 1.0e-12, "Interpolated diffusivity-gradient x component"));
569 PetscCall(PicurvAssertRealNear(0.2, diffusivity_gradient[1], 1.0e-12, "Interpolated diffusivity-gradient y component"));
570 PetscCall(PicurvAssertRealNear(0.3, diffusivity_gradient[2], 1.0e-12, "Interpolated diffusivity-gradient z component"));
571 PetscCall(DMSwarmRestoreField(user->swarm, "DiffusivityGradient", NULL, NULL, (void **)&diffusivity_gradient));
572 PetscCall(DMSwarmRestoreField(user->swarm, "Diffusivity", NULL, NULL, (void **)&diffusivity));
573 PetscCall(DMSwarmRestoreField(user->swarm, "velocity", NULL, NULL, (void **)&velocity));
574
575 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
576 PetscFunctionReturn(0);
577}
578/**
579 * @brief Tests the corner-averaged (legacy) interpolation path on constant fields.
580 */
581
583{
584 SimCtx *simCtx = NULL;
585 UserCtx *user = NULL;
586 Cmpnts ***grad = NULL;
587 PetscReal *velocity = NULL;
588 PetscReal *diffusivity = NULL;
589 PetscReal *diffusivity_gradient = NULL;
590
591 PetscFunctionBeginUser;
592 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
594 PetscCall(PicurvCreateSwarmPair(user, 1, "ske"));
595 PetscCall(VecSet(user->Ucat, 2.0));
596 PetscCall(VecSet(user->Diffusivity, 0.25));
597
598 PetscCall(DMDAVecGetArray(user->fda, user->DiffusivityGradient, &grad));
599 for (PetscInt k = user->info.zs; k < user->info.zs + user->info.zm; ++k) {
600 for (PetscInt j = user->info.ys; j < user->info.ys + user->info.ym; ++j) {
601 for (PetscInt i = user->info.xs; i < user->info.xs + user->info.xm; ++i) {
602 grad[k][j][i].x = 0.1;
603 grad[k][j][i].y = 0.2;
604 grad[k][j][i].z = 0.3;
605 }
606 }
607 }
608 PetscCall(DMDAVecRestoreArray(user->fda, user->DiffusivityGradient, &grad));
609 PetscCall(SyncRuntimeFieldGhosts(user));
610 PetscCall(SeedSingleParticle(user, 0, 0, 0, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, ACTIVE_AND_LOCATED));
611
612 PetscCall(InterpolateAllFieldsToSwarm(user));
613
614 PetscCall(DMSwarmGetField(user->swarm, "velocity", NULL, NULL, (void **)&velocity));
615 PetscCall(DMSwarmGetField(user->swarm, "Diffusivity", NULL, NULL, (void **)&diffusivity));
616 PetscCall(DMSwarmGetField(user->swarm, "DiffusivityGradient", NULL, NULL, (void **)&diffusivity_gradient));
617 PetscCall(PicurvAssertRealNear(2.0, velocity[0], 1.0e-12, "CornerAveraged: interpolated velocity x should match constant Eulerian field"));
618 PetscCall(PicurvAssertRealNear(2.0, velocity[1], 1.0e-12, "CornerAveraged: interpolated velocity y should match constant Eulerian field"));
619 PetscCall(PicurvAssertRealNear(2.0, velocity[2], 1.0e-12, "CornerAveraged: interpolated velocity z should match constant Eulerian field"));
620 PetscCall(PicurvAssertRealNear(0.25, diffusivity[0], 1.0e-12, "CornerAveraged: interpolated scalar diffusivity should match constant Eulerian field"));
621 PetscCall(PicurvAssertRealNear(0.1, diffusivity_gradient[0], 1.0e-12, "CornerAveraged: interpolated diffusivity-gradient x component"));
622 PetscCall(PicurvAssertRealNear(0.2, diffusivity_gradient[1], 1.0e-12, "CornerAveraged: interpolated diffusivity-gradient y component"));
623 PetscCall(PicurvAssertRealNear(0.3, diffusivity_gradient[2], 1.0e-12, "CornerAveraged: interpolated diffusivity-gradient z component"));
624 PetscCall(DMSwarmRestoreField(user->swarm, "DiffusivityGradient", NULL, NULL, (void **)&diffusivity_gradient));
625 PetscCall(DMSwarmRestoreField(user->swarm, "Diffusivity", NULL, NULL, (void **)&diffusivity));
626 PetscCall(DMSwarmRestoreField(user->swarm, "velocity", NULL, NULL, (void **)&velocity));
627
628 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
629 PetscFunctionReturn(0);
630}
631/**
632 * @brief FaceFlux: constant face fluxes give that velocity; other fields still interpolate trilinearly.
633 */
635{
636 SimCtx *simCtx = NULL;
637 UserCtx *user = NULL;
638 PetscReal *velocity = NULL;
639 PetscReal *diffusivity = NULL;
640
641 PetscFunctionBeginUser;
642 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
644 PetscCall(PicurvCreateSwarmPair(user, 1, "ske"));
645 PetscCall(VecSet(user->Ucont, 2.0)); /* Unit face-area vectors: the fluxes are the velocity */
646 PetscCall(VecSet(user->Ucat, -7.0)); /* Not read for velocity */
647 PetscCall(VecSet(user->Diffusivity, 0.25));
648 PetscCall(SyncRuntimeFieldGhosts(user));
649 PetscCall(SeedSingleParticle(user, 1, 1, 1, 0.5, 0.5, 0.5, 0.2, 0.7, 0.4, ACTIVE_AND_LOCATED));
650
651 PetscCall(InterpolateAllFieldsToSwarm(user));
652
653 PetscCall(DMSwarmGetField(user->swarm, "velocity", NULL, NULL, (void **)&velocity));
654 PetscCall(DMSwarmGetField(user->swarm, "Diffusivity", NULL, NULL, (void **)&diffusivity));
655 for (PetscInt c = 0; c < 3; c++)
656 PetscCall(PicurvAssertRealNear(2.0, velocity[c], 1.0e-12, "FaceFlux: velocity should come from the constant face fluxes"));
657 PetscCall(PicurvAssertRealNear(0.25, diffusivity[0], 1.0e-12, "FaceFlux: diffusivity should still interpolate trilinearly"));
658 PetscCall(DMSwarmRestoreField(user->swarm, "Diffusivity", NULL, NULL, (void **)&diffusivity));
659 PetscCall(DMSwarmRestoreField(user->swarm, "velocity", NULL, NULL, (void **)&velocity));
660 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
661 PetscFunctionReturn(0);
662}
663/**
664 * @brief FaceFlux: divergence-free fluxes give a divergence-free velocity, zero at a wall face,
665 * and the Contra2Cart value at the cell centre.
666 *
667 * The fluxes come from a stream function psi(i, j) = i^2 j + 0.3 j^2 on cell edges, so every cell's
668 * discrete flux divergence is zero and the j = 0 wall face carries no flux. The velocity is linear
669 * in each weight, so one-sided differences of the weights give its divergence exactly.
670 */
671static PetscErrorCode TestFaceFluxVelocityIsDivergenceFree(void)
672{
673 SimCtx *simCtx = NULL;
674 UserCtx *user = NULL;
675 Cmpnts ***ucont = NULL, ***ucat = NULL;
676 PetscReal *pos = NULL, *wgt = NULL, *vel = NULL;
677 PetscInt *cell = NULL, *status = NULL;
678 const PetscReal d = 0.25, w0[3] = {0.3, 0.6, 0.45};
679
680 PetscFunctionBeginUser;
681 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 6, 6, 6));
683 PetscCall(DMDAVecGetArray(user->fda, user->Ucont, &ucont));
684 for (PetscInt k = user->info.zs; k < user->info.zs + user->info.zm; k++)
685 for (PetscInt j = user->info.ys; j < user->info.ys + user->info.ym; j++)
686 for (PetscInt i = user->info.xs; i < user->info.xs + user->info.xm; i++) {
687 const PetscReal psi = (PetscReal)(i * i * j) + 0.3 * j * j;
688 const PetscReal psi_jm = (PetscReal)(i * i * (j - 1)) + 0.3 * (j - 1) * (j - 1);
689 const PetscReal psi_im = (PetscReal)((i - 1) * (i - 1) * j) + 0.3 * j * j;
690 ucont[k][j][i].x = psi - psi_jm;
691 ucont[k][j][i].y = -(psi - psi_im);
692 ucont[k][j][i].z = 0.0;
693 }
694 PetscCall(DMDAVecRestoreArray(user->fda, user->Ucont, &ucont));
695 PetscCall(SyncRuntimeFieldGhosts(user));
696 PetscCall(Contra2Cart(user));
697
698 /* Particles in cell (2, 0, 2): at w0, w0 + d e_x, w0 + d e_y, w0 + d e_z, the centre, and on the j = 0 wall. */
699 PetscCall(PicurvCreateSwarmPair(user, 6, "ske"));
700 PetscCall(DMSwarmGetField(user->swarm, "position", NULL, NULL, (void **)&pos));
701 PetscCall(DMSwarmGetField(user->swarm, "weight", NULL, NULL, (void **)&wgt));
702 PetscCall(DMSwarmGetField(user->swarm, "DMSwarm_CellID", NULL, NULL, (void **)&cell));
703 PetscCall(DMSwarmGetField(user->swarm, "DMSwarm_location_status", NULL, NULL, (void **)&status));
704 for (PetscInt p = 0; p < 6; p++) {
705 for (PetscInt c = 0; c < 3; c++) {
706 wgt[3*p + c] = (p == 4) ? 0.5 : w0[c] + ((p == c + 1) ? d : 0.0);
707 pos[3*p + c] = 0.5;
708 }
709 if (p == 5) wgt[3*p + 1] = 0.0;
710 cell[3*p + 0] = 2; cell[3*p + 1] = 0; cell[3*p + 2] = 2;
711 status[p] = ACTIVE_AND_LOCATED;
712 }
713 PetscCall(DMSwarmRestoreField(user->swarm, "DMSwarm_location_status", NULL, NULL, (void **)&status));
714 PetscCall(DMSwarmRestoreField(user->swarm, "DMSwarm_CellID", NULL, NULL, (void **)&cell));
715 PetscCall(DMSwarmRestoreField(user->swarm, "weight", NULL, NULL, (void **)&wgt));
716 PetscCall(DMSwarmRestoreField(user->swarm, "position", NULL, NULL, (void **)&pos));
717
718 PetscCall(InterpolateAllFieldsToSwarm(user));
719
720 PetscCall(DMSwarmGetField(user->swarm, "velocity", NULL, NULL, (void **)&vel));
721 {
722 const PetscReal div = (vel[3*1 + 0] - vel[0]) / d + (vel[3*2 + 1] - vel[1]) / d + (vel[3*3 + 2] - vel[2]) / d;
723 const PetscReal scale = PetscAbsReal(vel[3*1 + 0] - vel[0]) / d;
724 PetscCall(PicurvAssertBool((PetscBool)(scale > 1.0), "the test field should vary across the cell"));
725 PetscCall(PicurvAssertRealNear(0.0, div, 1.0e-10 * scale, "FaceFlux velocity should be divergence-free"));
726 }
727 PetscCall(DMDAVecGetArrayRead(user->fda, user->Ucat, &ucat));
728 for (PetscInt c = 0; c < 3; c++)
729 PetscCall(PicurvAssertRealNear((&ucat[3][1][3].x)[c], vel[3*4 + c], 1.0e-12, "the cell-centre value should be Contra2Cart's"));
730 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->Ucat, &ucat));
731 PetscCall(PicurvAssertRealNear(0.0, vel[3*5 + 1], 1.0e-12, "the wall-normal velocity should vanish on the wall face"));
732 PetscCall(DMSwarmRestoreField(user->swarm, "velocity", NULL, NULL, (void **)&vel));
733 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
734 PetscFunctionReturn(0);
735}
736/**
737 * @brief Tests particle-to-grid scattering using known cell occupancy and scalar values.
738 */
739
741{
742 SimCtx *simCtx = NULL;
743 UserCtx *user = NULL;
744 PetscInt *cell_ids = NULL;
745 PetscReal *psi = NULL;
746 PetscReal ***psi_grid = NULL;
747
748 PetscFunctionBeginUser;
749 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
750 PetscCall(PicurvCreateSwarmPair(user, 2, "ske"));
751
752 PetscCall(DMSwarmGetField(user->swarm, "DMSwarm_CellID", NULL, NULL, (void **)&cell_ids));
753 cell_ids[0] = 0; cell_ids[1] = 0; cell_ids[2] = 0;
754 cell_ids[3] = 0; cell_ids[4] = 0; cell_ids[5] = 0;
755 PetscCall(DMSwarmRestoreField(user->swarm, "DMSwarm_CellID", NULL, NULL, (void **)&cell_ids));
756
757 PetscCall(DMSwarmGetField(user->swarm, "Psi", NULL, NULL, (void **)&psi));
758 psi[0] = 1.0;
759 psi[1] = 3.0;
760 PetscCall(DMSwarmRestoreField(user->swarm, "Psi", NULL, NULL, (void **)&psi));
761
763
764 PetscCall(DMDAVecGetArrayRead(user->da, user->Psi, &psi_grid));
765 PetscCall(PicurvAssertRealNear(2.0, psi_grid[1][1][1], 1.0e-12, "Scatter should average particle Psi values into the owning cell"));
766 PetscCall(DMDAVecRestoreArrayRead(user->da, user->Psi, &psi_grid));
767
768 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
769 PetscFunctionReturn(0);
770}
771/**
772 * @brief Tests particle counting by geometric cell IDs using the production +1 storage shift.
773 */
774
776{
777 SimCtx *simCtx = NULL;
778 UserCtx *user = NULL;
779 PetscInt *cell_ids = NULL;
780 PetscReal ***counts = NULL;
781
782 PetscFunctionBeginUser;
783 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
784 PetscCall(PicurvCreateSwarmPair(user, 3, "ske"));
785
786 PetscCall(DMSwarmGetField(user->swarm, "DMSwarm_CellID", NULL, NULL, (void **)&cell_ids));
787 cell_ids[0] = 0; cell_ids[1] = 0; cell_ids[2] = 0;
788 cell_ids[3] = 0; cell_ids[4] = 0; cell_ids[5] = 0;
789 cell_ids[6] = 1; cell_ids[7] = 0; cell_ids[8] = 0;
790 PetscCall(DMSwarmRestoreField(user->swarm, "DMSwarm_CellID", NULL, NULL, (void **)&cell_ids));
791
792 PetscCall(CalculateParticleCountPerCell(user));
793
794 PetscCall(DMDAVecGetArrayRead(user->da, user->ParticleCount, &counts));
795 PetscCall(PicurvAssertRealNear(2.0, counts[1][1][1], 1.0e-12, "Two particles in cell (0,0,0) should accumulate at shifted index (1,1,1)"));
796 PetscCall(PicurvAssertRealNear(1.0, counts[1][1][2], 1.0e-12, "One particle in cell (1,0,0) should accumulate at shifted index (2,1,1)"));
797 PetscCall(DMDAVecRestoreArrayRead(user->da, user->ParticleCount, &counts));
798
799 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
800 PetscFunctionReturn(0);
801}
802/**
803 * @brief Tests localized particle-status reset behavior for restart of the location workflow.
804 */
805
807{
808 SimCtx *simCtx = NULL;
809 UserCtx *user = NULL;
810 PetscInt *status = NULL;
811
812 PetscFunctionBeginUser;
813 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
814 PetscCall(PicurvCreateSwarmPair(user, 3, "ske"));
815
816 PetscCall(DMSwarmGetField(user->swarm, "DMSwarm_location_status", NULL, NULL, (void **)&status));
817 status[0] = ACTIVE_AND_LOCATED;
818 status[1] = LOST;
819 status[2] = NEEDS_LOCATION;
820 PetscCall(DMSwarmRestoreField(user->swarm, "DMSwarm_location_status", NULL, NULL, (void **)&status));
821
822 PetscCall(ResetAllParticleStatuses(user));
823
824 PetscCall(DMSwarmGetField(user->swarm, "DMSwarm_location_status", NULL, NULL, (void **)&status));
825 PetscCall(PicurvAssertIntEqual(NEEDS_LOCATION, status[0], "ACTIVE_AND_LOCATED particles should be reset to NEEDS_LOCATION"));
826 PetscCall(PicurvAssertIntEqual(LOST, status[1], "LOST particles should remain LOST"));
827 PetscCall(PicurvAssertIntEqual(NEEDS_LOCATION, status[2], "NEEDS_LOCATION particles should remain unchanged"));
828 PetscCall(DMSwarmRestoreField(user->swarm, "DMSwarm_location_status", NULL, NULL, (void **)&status));
829
830 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
831 PetscFunctionReturn(0);
832}
833/**
834 * @brief Tests removal of LOST and EXITED particles, their separate tallies, and that survivors keep the one-at-a-time removal order.
835 */
836
838{
839 SimCtx *simCtx = NULL;
840 UserCtx *user = NULL;
841 PetscInt *status = NULL;
842 PetscInt removed_local = 0;
843 PetscInt removed_global = 0;
844 PetscInt nlocal = 0;
845 PetscReal *psi = NULL;
846 PetscReal removed_psi = 0.0;
847 PetscInt exited_global = 0;
848 PetscReal exited_psi = 0.0;
849
850 PetscFunctionBeginUser;
851 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
852 PetscCall(PicurvCreateSwarmPair(user, 5, "ske"));
853 PetscCall(DMSwarmGetField(user->swarm, "Psi", NULL, NULL, (void **)&psi));
854 psi[0] = 0.5;
855 psi[1] = 2.0;
856 psi[2] = 3.0;
857 psi[3] = 7.0;
858 psi[4] = 11.0;
859 PetscCall(DMSwarmRestoreField(user->swarm, "Psi", NULL, NULL, (void **)&psi));
860
861 PetscCall(DMSwarmGetField(user->swarm, "DMSwarm_location_status", NULL, NULL, (void **)&status));
862 status[0] = ACTIVE_AND_LOCATED;
863 status[1] = LOST;
864 status[2] = EXITED;
865 status[3] = ACTIVE_AND_LOCATED;
866 status[4] = ACTIVE_AND_LOCATED;
867 PetscCall(DMSwarmRestoreField(user->swarm, "DMSwarm_location_status", NULL, NULL, (void **)&status));
868
869 PetscCall(CheckAndRemoveLostParticles(user, &removed_local, &removed_global, &removed_psi, &exited_global, &exited_psi));
870 PetscCall(DMSwarmGetLocalSize(user->swarm, &nlocal));
871 PetscCall(PicurvAssertRealNear(2.0, removed_psi, 0.0, "the LOST particle carried Psi 2"));
872 PetscCall(PicurvAssertRealNear(3.0, exited_psi, 0.0, "the EXITED particle carried Psi 3"));
873 PetscCall(PicurvAssertIntEqual(1, removed_local, "One LOST particle should be removed locally"));
874 PetscCall(PicurvAssertIntEqual(1, removed_global, "Global LOST-particle removal count should match the local single-rank result"));
875 PetscCall(PicurvAssertIntEqual(1, exited_global, "One EXITED particle should be removed"));
876 PetscCall(PicurvAssertIntEqual(3, nlocal, "Three located particles should remain"));
877
878 /* Backward one-at-a-time removal moves the last particle into slot 2, then the new
879 * last into slot 1: survivors end as Psi 0.5, 7, 11 (a forward scan would give 0.5, 11, 7). */
880 PetscCall(DMSwarmGetField(user->swarm, "Psi", NULL, NULL, (void **)&psi));
881 PetscCall(PicurvAssertRealNear(0.5, psi[0], 0.0, "survivor order must match one-at-a-time removal (slot 0)"));
882 PetscCall(PicurvAssertRealNear(7.0, psi[1], 0.0, "survivor order must match one-at-a-time removal (slot 1)"));
883 PetscCall(PicurvAssertRealNear(11.0, psi[2], 0.0, "survivor order must match one-at-a-time removal (slot 2)"));
884 PetscCall(DMSwarmRestoreField(user->swarm, "Psi", NULL, NULL, (void **)&psi));
885
886 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
887 PetscFunctionReturn(0);
888}
889/**
890 * @brief Tests that sorting by host cell orders points k-slowest, keeps ties and every field together, and puts unlocated points last.
891 */
893{
894 SimCtx *simCtx = NULL;
895 UserCtx *user = NULL;
896 PetscInt *cell = NULL;
897 PetscInt64 *pid = NULL;
898 PetscReal *psi = NULL, *pos = NULL;
899 /* Cells (i,j,k) per point; point 4 has no cell. Expected order by (k,j,i), stable:
900 * p3 (0,0,0), p1 (1,0,0), p5 (1,0,0), p0 (2,1,0), p2 (0,0,1), p4 unlocated. */
901 const PetscInt cells_in[6][3] = {{2, 1, 0}, {1, 0, 0}, {0, 0, 1}, {0, 0, 0}, {-1, -1, -1}, {1, 0, 0}};
902 const PetscInt expected[6] = {3, 1, 5, 0, 2, 4};
903
904 PetscFunctionBeginUser;
905 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
906 PetscCall(PicurvCreateSwarmPair(user, 6, "ske"));
907 PetscCall(DMSwarmGetField(user->swarm, "DMSwarm_CellID", NULL, NULL, (void **)&cell));
908 PetscCall(DMSwarmGetField(user->swarm, "DMSwarm_pid", NULL, NULL, (void **)&pid));
909 PetscCall(DMSwarmGetField(user->swarm, "Psi", NULL, NULL, (void **)&psi));
910 PetscCall(DMSwarmGetField(user->swarm, "position", NULL, NULL, (void **)&pos));
911 for (PetscInt p = 0; p < 6; ++p) {
912 for (int d = 0; d < 3; ++d) { cell[3 * p + d] = cells_in[p][d]; pos[3 * p + d] = 10.0 * p + d; }
913 pid[p] = 100 + p;
914 psi[p] = 0.5 + p;
915 }
916 PetscCall(DMSwarmRestoreField(user->swarm, "position", NULL, NULL, (void **)&pos));
917 PetscCall(DMSwarmRestoreField(user->swarm, "Psi", NULL, NULL, (void **)&psi));
918 PetscCall(DMSwarmRestoreField(user->swarm, "DMSwarm_pid", NULL, NULL, (void **)&pid));
919 PetscCall(DMSwarmRestoreField(user->swarm, "DMSwarm_CellID", NULL, NULL, (void **)&cell));
920
921 PetscCall(SortParticlesByCell(user->swarm));
922
923 PetscCall(DMSwarmGetField(user->swarm, "DMSwarm_CellID", NULL, NULL, (void **)&cell));
924 PetscCall(DMSwarmGetField(user->swarm, "DMSwarm_pid", NULL, NULL, (void **)&pid));
925 PetscCall(DMSwarmGetField(user->swarm, "Psi", NULL, NULL, (void **)&psi));
926 PetscCall(DMSwarmGetField(user->swarm, "position", NULL, NULL, (void **)&pos));
927 for (PetscInt q = 0; q < 6; ++q) {
928 const PetscInt p = expected[q];
929 PetscCall(PicurvAssertIntEqual(100 + p, (PetscInt)pid[q], "points must come out in (k,j,i) cell order, ties and unlocated points stable"));
930 PetscCall(PicurvAssertRealNear(0.5 + p, psi[q], 0.0, "Psi must move with its point"));
931 PetscCall(PicurvAssertRealNear(10.0 * p + 2, pos[3 * q + 2], 0.0, "position must move with its point"));
932 PetscCall(PicurvAssertIntEqual(cells_in[p][0], cell[3 * q], "CellID must move with its point"));
933 }
934 PetscCall(DMSwarmRestoreField(user->swarm, "position", NULL, NULL, (void **)&pos));
935 PetscCall(DMSwarmRestoreField(user->swarm, "Psi", NULL, NULL, (void **)&psi));
936 PetscCall(DMSwarmRestoreField(user->swarm, "DMSwarm_pid", NULL, NULL, (void **)&pid));
937 PetscCall(DMSwarmRestoreField(user->swarm, "DMSwarm_CellID", NULL, NULL, (void **)&cell));
938
939 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
940 PetscFunctionReturn(0);
941}
942/**
943 * @brief Tests that a Brownian increment is a function of (seed, PID, step) alone.
944 *
945 * The same key reproduces the increment whatever was drawn before it, which is what
946 * makes a restart and a different rank layout draw what the uninterrupted run drew;
947 * changing any one key changes it.
948 */
949
951{
952 SimCtx *simCtx = NULL;
953 UserCtx *user = NULL;
954 Cmpnts base, again, other_pid, other_step, other_seed, none;
955
956 PetscFunctionBeginUser;
957 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
958 simCtx->dt = 0.25;
959 simCtx->particleRandomSeed = 777;
960 simCtx->step = 12;
961 PetscCall(CalculateBrownianDisplacement(user, 41, 0.5, &base));
962 PetscCall(CalculateBrownianDisplacement(user, 42, 0.5, &other_pid));
963 PetscCall(CalculateBrownianDisplacement(user, 41, 0.5, &again));
964 simCtx->step = 13;
965 PetscCall(CalculateBrownianDisplacement(user, 41, 0.5, &other_step));
966 simCtx->step = 12;
967 simCtx->particleRandomSeed = 778;
968 PetscCall(CalculateBrownianDisplacement(user, 41, 0.5, &other_seed));
969 PetscCall(CalculateBrownianDisplacement(user, 41, 0.0, &none));
970
971 PetscCall(PicurvAssertBool((PetscBool)(base.x == again.x && base.y == again.y && base.z == again.z),
972 "the same (seed, PID, step) must reproduce the increment after other draws"));
973 PetscCall(PicurvAssertBool((PetscBool)(base.x != other_pid.x && base.x != other_step.x && base.x != other_seed.x),
974 "a different PID, step or seed must change the increment"));
975 PetscCall(PicurvAssertBool((PetscBool)(none.x == 0.0 && none.y == 0.0 && none.z == 0.0),
976 "zero diffusivity must give no increment"));
977 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
978 PetscFunctionReturn(0);
979}
980
981/**
982 * @brief Tests that increments over many particles have zero mean, variance 2 D dt, and
983 * uncorrelated components.
984 */
985
986static PetscErrorCode TestBrownianDisplacementMoments(void)
987{
988 SimCtx *simCtx = NULL;
989 UserCtx *user = NULL;
990 const PetscInt count = 40000;
991 const PetscReal diffusivity = 0.5;
992 PetscReal sum[3] = {0.0, 0.0, 0.0}, sum_sq[3] = {0.0, 0.0, 0.0}, sum_xy = 0.0, variance;
993
994 PetscFunctionBeginUser;
995 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
996 simCtx->dt = 0.25;
997 simCtx->particleRandomSeed = 12345;
998 simCtx->step = 3;
999 variance = 2.0 * diffusivity * simCtx->dt;
1000 for (PetscInt pid = 0; pid < count; ++pid) {
1001 Cmpnts d;
1002
1003 PetscCall(CalculateBrownianDisplacement(user, pid, diffusivity, &d));
1004 const PetscReal c[3] = {d.x, d.y, d.z};
1005 for (int a = 0; a < 3; ++a) { sum[a] += c[a]; sum_sq[a] += c[a] * c[a]; }
1006 sum_xy += d.x * d.y;
1007 }
1008 /* Five standard errors: the mean's is sqrt(var/N), the variance's sqrt(2/N) var. */
1009 for (int a = 0; a < 3; ++a) {
1010 PetscCall(PicurvAssertRealNear(0.0, sum[a] / count, 5.0 * PetscSqrtReal(variance / count), "Brownian increments must have zero mean"));
1011 PetscCall(PicurvAssertRealNear(variance, sum_sq[a] / count, 5.0 * PetscSqrtReal(2.0 / count) * variance, "Brownian increments must have variance 2 D dt"));
1012 }
1013 PetscCall(PicurvAssertRealNear(0.0, sum_xy / count, 5.0 * variance / PetscSqrtReal((PetscReal)count), "Brownian components must be uncorrelated"));
1014 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
1015 PetscFunctionReturn(0);
1016}
1017/**
1018 * @brief Tests swarm-wide particle position updates using the same transport path as the runtime loop.
1019 */
1021{
1022 SimCtx *simCtx = NULL;
1023 UserCtx *user = NULL;
1024 PetscReal *positions = NULL;
1025 PetscReal *velocities = NULL;
1026 PetscReal *diffusivity = NULL;
1027 Cmpnts *diffusivity_gradient = NULL;
1028 PetscReal *psi = NULL;
1029 PetscReal *weights = NULL;
1030 PetscInt *cell_ids = NULL;
1031 PetscInt *status = NULL;
1032 PetscInt64 *pid = NULL;
1033
1034 PetscFunctionBeginUser;
1035 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
1036 PetscCall(PicurvCreateSwarmPair(user, 1, "ske"));
1037 simCtx->dt = 0.25;
1038
1039 PetscCall(DMSwarmGetField(user->swarm, "position", NULL, NULL, (void **)&positions));
1040 PetscCall(DMSwarmGetField(user->swarm, "velocity", NULL, NULL, (void **)&velocities));
1041 PetscCall(DMSwarmGetField(user->swarm, "Diffusivity", NULL, NULL, (void **)&diffusivity));
1042 PetscCall(DMSwarmGetField(user->swarm, "DiffusivityGradient", NULL, NULL, (void **)&diffusivity_gradient));
1043 PetscCall(DMSwarmGetField(user->swarm, "Psi", NULL, NULL, (void **)&psi));
1044 PetscCall(DMSwarmGetField(user->swarm, "weight", NULL, NULL, (void **)&weights));
1045 PetscCall(DMSwarmGetField(user->swarm, "DMSwarm_CellID", NULL, NULL, (void **)&cell_ids));
1046 PetscCall(DMSwarmGetField(user->swarm, "DMSwarm_location_status", NULL, NULL, (void **)&status));
1047 PetscCall(DMSwarmGetField(user->swarm, "DMSwarm_pid", NULL, NULL, (void **)&pid));
1048
1049 positions[0] = 0.20; positions[1] = 0.30; positions[2] = 0.40;
1050 velocities[0] = 0.40; velocities[1] = -0.20; velocities[2] = 0.10;
1051 diffusivity[0] = 0.0;
1052 diffusivity_gradient[0].x = 0.10;
1053 diffusivity_gradient[0].y = 0.20;
1054 diffusivity_gradient[0].z = -0.10;
1055 psi[0] = 0.5;
1056 weights[0] = 0.5; weights[1] = 0.5; weights[2] = 0.5;
1057 cell_ids[0] = 0; cell_ids[1] = 0; cell_ids[2] = 0;
1058 status[0] = ACTIVE_AND_LOCATED;
1059 pid[0] = 7;
1060
1061 PetscCall(DMSwarmRestoreField(user->swarm, "DMSwarm_pid", NULL, NULL, (void **)&pid));
1062 PetscCall(DMSwarmRestoreField(user->swarm, "DMSwarm_location_status", NULL, NULL, (void **)&status));
1063 PetscCall(DMSwarmRestoreField(user->swarm, "DMSwarm_CellID", NULL, NULL, (void **)&cell_ids));
1064 PetscCall(DMSwarmRestoreField(user->swarm, "weight", NULL, NULL, (void **)&weights));
1065 PetscCall(DMSwarmRestoreField(user->swarm, "Psi", NULL, NULL, (void **)&psi));
1066 PetscCall(DMSwarmRestoreField(user->swarm, "DiffusivityGradient", NULL, NULL, (void **)&diffusivity_gradient));
1067 PetscCall(DMSwarmRestoreField(user->swarm, "Diffusivity", NULL, NULL, (void **)&diffusivity));
1068 PetscCall(DMSwarmRestoreField(user->swarm, "velocity", NULL, NULL, (void **)&velocities));
1069 PetscCall(DMSwarmRestoreField(user->swarm, "position", NULL, NULL, (void **)&positions));
1070
1071 PetscCall(UpdateAllParticlePositions(user));
1072
1073 PetscCall(DMSwarmGetField(user->swarm, "position", NULL, NULL, (void **)&positions));
1074 PetscCall(PicurvAssertRealNear(0.325, positions[0], 1.0e-12, "UpdateAllParticlePositions should advect x"));
1075 PetscCall(PicurvAssertRealNear(0.300, positions[1], 1.0e-12, "UpdateAllParticlePositions should advect y"));
1076 PetscCall(PicurvAssertRealNear(0.400, positions[2], 1.0e-12, "UpdateAllParticlePositions should advect z"));
1077 PetscCall(DMSwarmRestoreField(user->swarm, "position", NULL, NULL, (void **)&positions));
1078
1079 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
1080 PetscFunctionReturn(0);
1081}
1082/**
1083 * @brief Tests the location orchestrator fast path when a particle already carries a valid prior cell.
1084 */
1086{
1087 SimCtx *simCtx = NULL;
1088 UserCtx *user = NULL;
1089 PetscReal *positions = NULL;
1090 PetscReal *weights = NULL;
1091 PetscInt *cell_ids = NULL;
1092 PetscInt *status = NULL;
1093 PetscInt64 *pid = NULL;
1094
1095 PetscFunctionBeginUser;
1096 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
1097 PetscCall(SetupDomainCellDecompositionMap(user));
1098 PetscCall(PicurvCreateSwarmPair(user, 1, "ske"));
1099
1100 PetscCall(DMSwarmGetField(user->swarm, "position", NULL, NULL, (void **)&positions));
1101 PetscCall(DMSwarmGetField(user->swarm, "weight", NULL, NULL, (void **)&weights));
1102 PetscCall(DMSwarmGetField(user->swarm, "DMSwarm_CellID", NULL, NULL, (void **)&cell_ids));
1103 PetscCall(DMSwarmGetField(user->swarm, "DMSwarm_location_status", NULL, NULL, (void **)&status));
1104 PetscCall(DMSwarmGetField(user->swarm, "DMSwarm_pid", NULL, NULL, (void **)&pid));
1105 positions[0] = 0.375; positions[1] = 0.375; positions[2] = 0.375;
1106 weights[0] = 0.5; weights[1] = 0.5; weights[2] = 0.5;
1107 cell_ids[0] = 1; cell_ids[1] = 1; cell_ids[2] = 1;
1108 status[0] = NEEDS_LOCATION;
1109 pid[0] = 11;
1110 PetscCall(DMSwarmRestoreField(user->swarm, "DMSwarm_pid", NULL, NULL, (void **)&pid));
1111 PetscCall(DMSwarmRestoreField(user->swarm, "DMSwarm_location_status", NULL, NULL, (void **)&status));
1112 PetscCall(DMSwarmRestoreField(user->swarm, "DMSwarm_CellID", NULL, NULL, (void **)&cell_ids));
1113 PetscCall(DMSwarmRestoreField(user->swarm, "weight", NULL, NULL, (void **)&weights));
1114 PetscCall(DMSwarmRestoreField(user->swarm, "position", NULL, NULL, (void **)&positions));
1115
1116 PetscCall(LocateAllParticlesInGrid(user, simCtx->bboxlist));
1117
1118 PetscCall(DMSwarmGetField(user->swarm, "DMSwarm_CellID", NULL, NULL, (void **)&cell_ids));
1119 PetscCall(DMSwarmGetField(user->swarm, "DMSwarm_location_status", NULL, NULL, (void **)&status));
1120 PetscCall(PicurvAssertIntEqual(1, cell_ids[0], "prior-cell fast path should preserve the i cell id"));
1121 PetscCall(PicurvAssertIntEqual(1, cell_ids[1], "prior-cell fast path should preserve the j cell id"));
1122 PetscCall(PicurvAssertIntEqual(1, cell_ids[2], "prior-cell fast path should preserve the k cell id"));
1123 PetscCall(PicurvAssertIntEqual(ACTIVE_AND_LOCATED, status[0], "prior-cell fast path should mark the particle ACTIVE_AND_LOCATED"));
1124 PetscCall(PicurvAssertIntEqual(1, simCtx->searchMetrics.searchAttempts, "prior-cell fast path should record one search attempt"));
1125 PetscCall(PicurvAssertIntEqual(1, (PetscInt)simCtx->searchMetrics.searchPopulation, "prior-cell fast path should record one input particle"));
1126 PetscCall(PicurvAssertIntEqual(1, (PetscInt)simCtx->searchMetrics.searchLocatedCount, "prior-cell fast path should count one located particle"));
1127 PetscCall(PicurvAssertIntEqual(0, (PetscInt)simCtx->searchMetrics.searchLostCount, "prior-cell fast path should not lose the particle"));
1128 PetscCall(PicurvAssertIntEqual(0, (PetscInt)simCtx->searchMetrics.reSearchCount, "prior-cell fast path should not re-search on later passes"));
1129 PetscCall(PicurvAssertBool((PetscBool)(simCtx->searchMetrics.traversalStepsSum > 0), "prior-cell fast path should accumulate traversal steps"));
1130 PetscCall(PicurvAssertIntEqual(1, simCtx->searchMetrics.maxParticlePassDepth, "prior-cell fast path should report one settlement pass"));
1131 PetscCall(DMSwarmRestoreField(user->swarm, "DMSwarm_location_status", NULL, NULL, (void **)&status));
1132 PetscCall(DMSwarmRestoreField(user->swarm, "DMSwarm_CellID", NULL, NULL, (void **)&cell_ids));
1133
1134 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
1135 PetscFunctionReturn(0);
1136}
1137/**
1138 * @brief Tests the guess-then-verify orchestrator path for a local particle with an unknown prior cell.
1139 */
1141{
1142 SimCtx *simCtx = NULL;
1143 UserCtx *user = NULL;
1144 PetscReal *positions = NULL;
1145 PetscReal *weights = NULL;
1146 PetscInt *cell_ids = NULL;
1147 PetscInt *status = NULL;
1148 PetscInt64 *pid = NULL;
1149
1150 PetscFunctionBeginUser;
1151 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
1152 PetscCall(SetupDomainCellDecompositionMap(user));
1153 PetscCall(PicurvCreateSwarmPair(user, 1, "ske"));
1154
1155 PetscCall(DMSwarmGetField(user->swarm, "position", NULL, NULL, (void **)&positions));
1156 PetscCall(DMSwarmGetField(user->swarm, "weight", NULL, NULL, (void **)&weights));
1157 PetscCall(DMSwarmGetField(user->swarm, "DMSwarm_CellID", NULL, NULL, (void **)&cell_ids));
1158 PetscCall(DMSwarmGetField(user->swarm, "DMSwarm_location_status", NULL, NULL, (void **)&status));
1159 PetscCall(DMSwarmGetField(user->swarm, "DMSwarm_pid", NULL, NULL, (void **)&pid));
1160 positions[0] = 0.625; positions[1] = 0.625; positions[2] = 0.625;
1161 weights[0] = 0.5; weights[1] = 0.5; weights[2] = 0.5;
1162 cell_ids[0] = -1; cell_ids[1] = -1; cell_ids[2] = -1;
1163 status[0] = NEEDS_LOCATION;
1164 pid[0] = 22;
1165 PetscCall(DMSwarmRestoreField(user->swarm, "DMSwarm_pid", NULL, NULL, (void **)&pid));
1166 PetscCall(DMSwarmRestoreField(user->swarm, "DMSwarm_location_status", NULL, NULL, (void **)&status));
1167 PetscCall(DMSwarmRestoreField(user->swarm, "DMSwarm_CellID", NULL, NULL, (void **)&cell_ids));
1168 PetscCall(DMSwarmRestoreField(user->swarm, "weight", NULL, NULL, (void **)&weights));
1169 PetscCall(DMSwarmRestoreField(user->swarm, "position", NULL, NULL, (void **)&positions));
1170
1171 PetscCall(LocateAllParticlesInGrid(user, simCtx->bboxlist));
1172
1173 PetscCall(DMSwarmGetField(user->swarm, "DMSwarm_CellID", NULL, NULL, (void **)&cell_ids));
1174 PetscCall(DMSwarmGetField(user->swarm, "DMSwarm_location_status", NULL, NULL, (void **)&status));
1175 PetscCall(PicurvAssertIntEqual(2, cell_ids[0], "guess-path location should resolve the i cell id"));
1176 PetscCall(PicurvAssertIntEqual(2, cell_ids[1], "guess-path location should resolve the j cell id"));
1177 PetscCall(PicurvAssertIntEqual(2, cell_ids[2], "guess-path location should resolve the k cell id"));
1178 PetscCall(PicurvAssertIntEqual(ACTIVE_AND_LOCATED, status[0], "guess-path location should mark the particle ACTIVE_AND_LOCATED"));
1179 PetscCall(PicurvAssertIntEqual(1, simCtx->searchMetrics.searchAttempts, "guess-path location should perform one robust search"));
1180 PetscCall(PicurvAssertIntEqual(1, (PetscInt)simCtx->searchMetrics.searchPopulation, "guess-path location should count one input particle"));
1181 PetscCall(PicurvAssertIntEqual(1, (PetscInt)simCtx->searchMetrics.searchLocatedCount, "guess-path location should count one located particle"));
1182 PetscCall(PicurvAssertIntEqual(0, (PetscInt)simCtx->searchMetrics.searchLostCount, "guess-path location should not lose the particle"));
1183 PetscCall(PicurvAssertIntEqual(0, (PetscInt)simCtx->searchMetrics.reSearchCount, "guess-path location should not count later-pass re-searches"));
1184 PetscCall(PicurvAssertIntEqual(1, simCtx->searchMetrics.bboxGuessFallbackCount, "guess-path location should record one bbox fallback"));
1185 PetscCall(PicurvAssertIntEqual(0, simCtx->searchMetrics.bboxGuessSuccessCount, "guess-path local resolution should not count as remote bbox success"));
1186 PetscCall(DMSwarmRestoreField(user->swarm, "DMSwarm_location_status", NULL, NULL, (void **)&status));
1187 PetscCall(DMSwarmRestoreField(user->swarm, "DMSwarm_CellID", NULL, NULL, (void **)&cell_ids));
1188
1189 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
1190 PetscFunctionReturn(0);
1191}
1192/**
1193 * @brief Verifies that later settlement passes increment re-search metrics.
1194 */
1196{
1197 SimCtx *simCtx = NULL;
1198 UserCtx *user = NULL;
1199 Particle particle;
1201
1202 PetscFunctionBeginUser;
1203 PetscCall(PetscMemzero(&particle, sizeof(particle)));
1204 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
1205 PetscCall(SetupDomainCellDecompositionMap(user));
1206
1208 particle.PID = 33;
1209 particle.cell[0] = 1;
1210 particle.cell[1] = 1;
1211 particle.cell[2] = 1;
1212 particle.loc.x = 0.375;
1213 particle.loc.y = 0.375;
1214 particle.loc.z = 0.375;
1215 particle.weights.x = 0.5;
1216 particle.weights.y = 0.5;
1217 particle.weights.z = 0.5;
1218
1219 PetscCall(LocateParticleOrFindMigrationTarget(user, NULL, &particle, &status));
1220
1221 PetscCall(PicurvAssertIntEqual(ACTIVE_AND_LOCATED, status, "direct re-search test should locate the particle"));
1222 PetscCall(PicurvAssertIntEqual(1, (PetscInt)simCtx->searchMetrics.searchAttempts, "direct re-search test should record one robust walk"));
1223 PetscCall(PicurvAssertIntEqual(1, (PetscInt)simCtx->searchMetrics.reSearchCount, "direct re-search test should increment re_search_count on later passes"));
1224 PetscCall(PicurvAssertIntEqual(0, (PetscInt)simCtx->searchMetrics.maxTraversalFailCount, "direct re-search test should not hit MAX_TRAVERSAL"));
1225
1226 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
1227 PetscFunctionReturn(0);
1228}
1229/**
1230 * @brief Tests that a particle beyond a reflecting -Xi face is mirrored back and located, including after a tangential walk.
1231 */
1233{
1234 SimCtx *simCtx = NULL;
1235 UserCtx *user = NULL;
1236 Particle particle;
1238
1239 PetscFunctionBeginUser;
1240 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
1241 PetscCall(SetupDomainCellDecompositionMap(user));
1244
1245 /* Straight crossing of -Xi out of its previous cell (0,1,1). */
1246 PetscCall(PetscMemzero(&particle, sizeof(particle)));
1247 particle.PID = 41;
1248 particle.cell[0] = 0; particle.cell[1] = 1; particle.cell[2] = 1;
1249 particle.loc.x = -0.05; particle.loc.y = 0.375; particle.loc.z = 0.375;
1250 PetscCall(LocateParticleOrFindMigrationTarget(user, NULL, &particle, &status));
1251 PetscCall(PicurvAssertIntEqual(ACTIVE_AND_LOCATED, status, "a reflected particle should be located"));
1252 PetscCall(PicurvAssertRealNear(0.05, particle.loc.x, 1.0e-14, "x should mirror about the -Xi plane"));
1253 PetscCall(PicurvAssertIntEqual(0, particle.cell[0], "the particle stays in the boundary cell column"));
1254 PetscCall(PicurvAssertIntEqual(1, particle.cell[1], "a straight crossing keeps its j cell"));
1255 PetscCall(PicurvAssertIntEqual(1, (PetscInt)simCtx->searchMetrics.reflectionCount, "one reflection"));
1256
1257 /* Crossing -Xi while also moving one cell in +j: the walk moves along the wall first. */
1258 PetscCall(PetscMemzero(&particle, sizeof(particle)));
1259 particle.PID = 42;
1260 particle.cell[0] = 0; particle.cell[1] = 1; particle.cell[2] = 1;
1261 particle.loc.x = -0.05; particle.loc.y = 0.625; particle.loc.z = 0.375;
1262 PetscCall(LocateParticleOrFindMigrationTarget(user, NULL, &particle, &status));
1263 PetscCall(PicurvAssertIntEqual(ACTIVE_AND_LOCATED, status, "a tangential crossing should also be located"));
1264 PetscCall(PicurvAssertRealNear(0.05, particle.loc.x, 1.0e-14, "x should mirror about the -Xi plane"));
1265 PetscCall(PicurvAssertIntEqual(2, particle.cell[1], "the reflection happens in the boundary cell that holds the particle tangentially"));
1266 PetscCall(PicurvAssertIntEqual(2, (PetscInt)simCtx->searchMetrics.reflectionCount, "one reflection per particle"));
1267 PetscCall(PicurvAssertIntEqual(0, (PetscInt)simCtx->searchMetrics.reflectionFallbackCount, "no particle reached the cap"));
1268
1269 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
1270 PetscFunctionReturn(0);
1271}
1272/**
1273 * @brief Tests wall-model scalar helper kernels.
1274 */
1275
1276static PetscErrorCode TestWallModelScalarHelpers(void)
1277{
1278 const PetscReal expected_smooth_e = PetscExpReal(0.41 * 5.5);
1279 PetscReal e_coeff = 0.0;
1280 PetscReal utau = 0.0;
1281 PetscReal residual = 0.0;
1282
1283 PetscFunctionBeginUser;
1284 e_coeff = E_coeff(0.1, 0.0, 1.0e-3);
1285 PetscCall(PicurvAssertRealNear(expected_smooth_e, e_coeff, 1.0e-10, "smooth-wall E coefficient"));
1286
1287 utau = find_utau_hydset(1.0e-3, 1.0, 1.0e-2, 0.1, 0.0);
1288 PetscCall(PicurvAssertBool((PetscBool)(utau > 0.0), "friction velocity should remain positive"));
1289 residual = f_hydset(1.0e-3, 1.0, 1.0e-2, utau, 0.0);
1290 PetscCall(PicurvAssertBool((PetscBool)(PetscAbsReal(residual) < 1.0e-5), "Newton solve residual should be small"));
1291
1292 PetscCall(PicurvAssertRealNear(0.0, nu_t(0.0), 1.0e-12, "eddy viscosity ratio at wall"));
1293 PetscCall(PicurvAssertBool((PetscBool)(integrate_1(1.0e-3, 1.0e-2, 0.1, 0) > 0.0), "integral helper should be positive"));
1294 PetscFunctionReturn(0);
1295}
1296/**
1297 * @brief Tests closed-form and iterative wall-model velocity helpers against inverse reconstructions.
1298 */
1299
1300static PetscErrorCode TestWallModelVelocityHelpers(void)
1301{
1302 const PetscReal kinematic_viscosity = 1.0e-3;
1303 const PetscReal wall_distance = 2.0e-2;
1304 const PetscReal target_velocity = 1.0;
1305 PetscReal utau_werner = 0.0;
1306 PetscReal utau_cabot = 0.0;
1307 PetscReal wall_shear_velocity = 0.0;
1308 PetscReal wall_shear_normal = 0.0;
1309
1310 PetscFunctionBeginUser;
1311 utau_werner = find_utau_Werner(kinematic_viscosity, target_velocity, wall_distance, 0.1);
1312 PetscCall(PicurvAssertBool((PetscBool)(utau_werner > 0.0), "Werner-Wengle friction velocity should remain positive"));
1313 PetscCall(PicurvAssertRealNear(target_velocity, u_Werner(kinematic_viscosity, wall_distance, utau_werner), 1.0e-12,
1314 "Werner-Wengle inversion should reconstruct the target velocity"));
1315
1316 /* The pointwise pair the solver uses must invert exactly on BOTH sides of
1317 y+ = 11.81. The previous inverse round-tripped only in the sublayer, which is the
1318 one range the sample above happens to sit in, and so passed over the mismatch. */
1319 {
1320 const PetscReal yplus[5] = {2.0, 11.0, 11.81, 30.0, 500.0};
1321 const PetscReal u_tau = 0.05;
1322 const PetscReal nu = kinematic_viscosity;
1323
1324 for (PetscInt i = 0; i < 5; ++i) {
1325 const PetscReal y = yplus[i] * nu / u_tau;
1326 const PetscReal u = u_Werner(nu, y, u_tau);
1327 PetscCall(PicurvAssertRealNear(u_tau, find_utau_Werner(nu, u, y, 0.0), 1.0e-12 * u_tau,
1328 "find_utau_Werner must invert u_Werner exactly on both branches"));
1329 }
1330 }
1331
1332 /* The cell-integral pair: correct for a cell-averaged input, not wired into the
1333 solver. Its round trip must still hold on both sides of its own switch. */
1334 {
1335 const PetscReal A = 8.3, Bexp = 1.0 / 7.0;
1336 const PetscReal u_m = 0.5 * kinematic_viscosity / wall_distance *
1337 PetscPowReal(A, 2.0 / (1.0 - Bexp));
1338 const PetscReal samples[2] = {0.25 * u_m, 4.0 * u_m};
1339
1340 for (PetscInt i = 0; i < 2; ++i) {
1341 const PetscReal tau = taw_Werner(kinematic_viscosity, samples[i], wall_distance);
1342
1343 PetscCall(PicurvAssertBool((PetscBool)(tau > 0.0),
1344 "the explicit Werner-Wengle stress must be positive"));
1345 PetscCall(PicurvAssertRealNear(
1346 samples[i], u_Werner_explicit(kinematic_viscosity, wall_distance, tau),
1347 1.0e-9 + 1.0e-9 * samples[i],
1348 "the explicit Werner-Wengle pair must round-trip on both branches"));
1349 }
1350
1351 /* The branches meet at the switch, so approaching it from either side must give
1352 the same stress. A threshold written through the friction velocity, as the
1353 iterative residual's is, cannot satisfy this. */
1354 PetscCall(PicurvAssertRealNear(
1355 taw_Werner(kinematic_viscosity, u_m * (1.0 - 1.0e-9), wall_distance),
1356 taw_Werner(kinematic_viscosity, u_m * (1.0 + 1.0e-9), wall_distance), 1.0e-9,
1357 "the Werner-Wengle branches must be continuous at the transition speed"));
1358
1359 /* Nearer the wall is slower, whatever the branch. This is the property the
1360 previous mismatched pairing violated. */
1361 {
1362 const PetscReal tau = taw_Werner(kinematic_viscosity, 4.0 * u_m, wall_distance);
1363
1364 PetscCall(PicurvAssertBool(
1365 (PetscBool)(u_Werner_explicit(kinematic_viscosity, 0.5 * wall_distance, tau) <
1366 u_Werner_explicit(kinematic_viscosity, wall_distance, tau)),
1367 "a cell nearer the wall must be assigned the slower speed"));
1368 }
1369 }
1370
1371 find_utau_Cabot(kinematic_viscosity, target_velocity, wall_distance, 0.1, 0.0, 0.0,
1372 &utau_cabot, &wall_shear_velocity, &wall_shear_normal);
1373 PetscCall(PicurvAssertBool((PetscBool)(utau_cabot > 0.0), "Cabot friction velocity should remain positive"));
1374 PetscCall(PicurvAssertRealNear(target_velocity, u_Cabot(kinematic_viscosity, wall_distance, utau_cabot, 0.0, wall_shear_velocity), 1.0e-6,
1375 "Cabot inversion should reconstruct the target velocity when pressure gradient is zero"));
1376 PetscCall(PicurvAssertRealNear(0.0, wall_shear_normal, 1.0e-10,
1377 "zero normal pressure gradient should keep Cabot normal wall shear at zero"));
1378 PetscFunctionReturn(0);
1379}
1380/**
1381 * @brief Tests that the wall laws' branches meet, so each reference speed has one friction velocity.
1382 *
1383 * The log law switched from u+ = y+ to its logarithm at a fixed y+ = 11.81, where the two
1384 * differ by about 2.4%, and Werner-Wengle at the same rounded value, where its branches
1385 * differ by about 2e-5. Either jump makes the speed-to-u_tau map non-monotone near the
1386 * switch and the residual non-smooth for a finite-difference Jacobian.
1387 */
1388static PetscErrorCode TestWallLawBranchesAreContinuous(void)
1389{
1390 const double nu = 1.0e-3, y = 1.0e-2;
1391 const double edge = 11.81; /* only a probe location; the switches are computed */
1392 double previous_utau = 0.0;
1393
1394 PetscFunctionBeginUser;
1395 /* Profiles: sample u+ across the old switch at a fine step; no step may jump. */
1396 for (int law = 0; law < 2; ++law) {
1397 double previous = -1.0;
1398 for (int n = 0; n <= 400; ++n) {
1399 const double yplus = edge - 1.0 + 2.0 * n / 400.0;
1400 const double u_tau = yplus * nu / y;
1401 const double u = (law == 0) ? u_hydset_roughness(nu, y, u_tau, 0.0) : u_Werner(nu, y, u_tau);
1402 const double uplus = u / u_tau;
1403 if (previous > 0.0) {
1404 PetscCall(PicurvAssertBool((PetscBool)(PetscAbsReal(uplus - previous) < 1.0e-2),
1405 law == 0 ? "the log-law profile must not jump at its sublayer edge"
1406 : "the Werner-Wengle profile must not jump at its sublayer edge"));
1407 PetscCall(PicurvAssertBool((PetscBool)(uplus >= previous - 1.0e-12),
1408 "u+ must not decrease with y+"));
1409 }
1410 previous = uplus;
1411 }
1412 }
1413 /* Inverse: across the band of U y / nu where the old log law had two roots, the
1414 friction velocity must increase with the reference speed and reproduce it. */
1415 for (int n = 0; n <= 200; ++n) {
1416 const double U = (130.0 + 15.0 * n / 200.0) * nu / y;
1417 const double u_tau = find_utau_hydset(nu, U, y, 1.0e-3, 0.0);
1418 PetscCall(PicurvAssertRealNear(U, u_hydset_roughness(nu, y, u_tau, 0.0), 1.0e-6 * U,
1419 "the log-law friction velocity must reproduce the speed it inverts"));
1420 PetscCall(PicurvAssertBool((PetscBool)(u_tau > previous_utau), "the log-law friction velocity must increase with speed"));
1421 previous_utau = u_tau;
1422 }
1423 /* Forward and inverse are one relation at every y+, smooth and rough, including above
1424 y+ = 300 where the profile once returned -1 while the inverse kept the log branch.
1425 y+ = 100 is the control inside the old range. */
1426 {
1427 const double yplus_samples[] = {100.0, 299.0, 301.0, 500.0, 2000.0};
1428 const double roughness[] = {0.0, 5.0e-3};
1429 for (int r = 0; r < 2; ++r) {
1430 for (int n = 0; n < 5; ++n) {
1431 const double u_tau = yplus_samples[n] * nu / y;
1432 const double U = u_hydset_roughness(nu, y, u_tau, roughness[r]);
1433 PetscCall(PicurvAssertBool((PetscBool)(U > 0.0),
1434 "the log-law profile must be a speed at every y+, not a sentinel"));
1435 PetscCall(PicurvAssertRealNear(u_tau, find_utau_hydset(nu, U, y, 1.0e-3, roughness[r]), 1.0e-6 * u_tau,
1436 "the log-law inverse must recover the friction velocity of its profile"));
1437 }
1438 }
1439 }
1440 PetscFunctionReturn(0);
1441}
1442
1443/**
1444 * @brief Tests that the log law's friction velocity stays positive on a rough wall.
1445 *
1446 * Newton from a small guess could step onto the linear branch's mirror root at -u_tau; a
1447 * rough wall made that common, and the sign then corrupted u_tau, its minimum and y+.
1448 */
1450{
1451 const double nu = 1.0 / 4.0e4;
1452 const double roughness[4] = {1.0e-5, 1.0e-4, 1.0e-3, 1.0e-2};
1453 const double distance[3] = {1.0e-3, 1.0e-2, 3.0e-2};
1454 const double speed[6] = {1.0e-3, 1.0e-2, 0.1, 0.5, 1.0, 2.0};
1455
1456 PetscFunctionBeginUser;
1457 for (int r = 0; r < 4; ++r)
1458 for (int d = 0; d < 3; ++d)
1459 for (int s = 0; s < 6; ++s) {
1460 const double u_tau = find_utau_hydset(nu, speed[s], distance[d], 1.0e-3, roughness[r]);
1461 PetscCall(PicurvAssertBool((PetscBool)(u_tau > 0.0 && isfinite(u_tau)),
1462 "the log-law friction velocity must be positive and finite"));
1463 }
1464 PetscFunctionReturn(0);
1465}
1466
1467/**
1468 * @brief Tests Cabot's stress sign and its wall-layer integral at large y+.
1469 *
1470 * Cabot's momentum balance gives a signed stress; under an adverse pressure gradient strong
1471 * enough to exceed the reference speed's share it reverses, and the solver applies it in that
1472 * direction. Its wall-layer integrals were 30 uniform points, about a third
1473 * off at y+ = 1000; they must now agree with a resolved reference.
1474 */
1476{
1477 const double nu = 1.0e-3, y = 1.0e-2;
1478 double u_tau = 0.0, stress = 0.0, stress_normal = 0.0;
1479
1480 PetscFunctionBeginUser;
1481 /* Integral against a resolved trapezoid in log-spaced y (no closed form). */
1482 for (int mode = 0; mode < 2; ++mode) {
1483 const double u_tau_probe = 1000.0 * nu / y; /* y+ = 1000 at the end */
1484 const int fine = 200000;
1485 double reference_integral = 0.0, y_prev = 0.0, f_prev = 0.0;
1486 for (int n = 1; n <= fine; ++n) {
1487 const double yy = y * (double)n * (double)n / ((double)fine * (double)fine);
1488 const double f = ((mode == 0) ? 1.0 : yy) / ((1.0 + nu_t(yy * u_tau_probe / nu)) * nu);
1489 if (n == 1) f_prev = ((mode == 0) ? 1.0 : 0.0) / nu;
1490 reference_integral += 0.5 * (f + f_prev) * (yy - y_prev);
1491 y_prev = yy; f_prev = f;
1492 }
1493 PetscCall(PicurvAssertRealNear(reference_integral, integrate_1(nu, y, u_tau_probe, mode),
1494 2.0e-3 * PetscAbsReal(reference_integral),
1495 "Cabot's wall-layer integral must match a resolved reference at y+ = 1000"));
1496 }
1497
1498 /* No pressure gradient: the momentum-balance stress opposes the flow. */
1499 find_utau_Cabot(nu, 1.0, 2.0 * y, 0.01, 0.0, 0.0, &u_tau, &stress, &stress_normal);
1500 PetscCall(PicurvAssertBool((PetscBool)(u_tau > 0.0 && stress > 0.0),
1501 "with no pressure gradient Cabot's stress opposes the flow"));
1502 /* A strong adverse gradient along the flow reverses the wall-layer balance; the signed
1503 stress is what ApplyWallFunction orients the wall stress by. */
1504 find_utau_Cabot(nu, 1.0, 2.0 * y, 0.01, 1.0e3, 0.0, &u_tau, &stress, &stress_normal);
1505 PetscCall(PicurvAssertBool((PetscBool)(stress < 0.0),
1506 "an adverse gradient that reverses the balance must reverse Cabot's stress"));
1507 PetscFunctionReturn(0);
1508}
1509
1510/**
1511 * @brief Tests driven-flow validation when no driven handlers are present.
1512 */
1513
1515{
1516 SimCtx *simCtx = NULL;
1517 UserCtx *user = NULL;
1518
1519 PetscFunctionBeginUser;
1520 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
1521 PetscCall(Validate_DrivenFlowConfiguration(user));
1522 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
1523 PetscFunctionReturn(0);
1524}
1525/**
1526 * @brief Tests that the shared minimal fixture mirrors the production DA contract.
1527 */
1528
1530{
1531 SimCtx *simCtx = NULL;
1532 UserCtx *user = NULL;
1533 DM coord_dm = NULL;
1534 PetscInt mx = 0, my = 0, mz = 0;
1535
1536 PetscFunctionBeginUser;
1537 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 8, 6, 4));
1538
1539 PetscCall(DMDAGetInfo(user->da, NULL, &mx, &my, &mz, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL));
1540 PetscCall(PicurvAssertIntEqual(user->IM + 1, mx, "minimal fixture should size da with IM+1 nodes"));
1541 PetscCall(PicurvAssertIntEqual(user->JM + 1, my, "minimal fixture should size da with JM+1 nodes"));
1542 PetscCall(PicurvAssertIntEqual(user->KM + 1, mz, "minimal fixture should size da with KM+1 nodes"));
1543 PetscCall(PicurvAssertIntEqual(mx, user->info.mx, "user->info should be sourced from the production da"));
1544 PetscCall(PicurvAssertIntEqual(my, user->info.my, "user->info my should match the da dimensions"));
1545 PetscCall(PicurvAssertIntEqual(mz, user->info.mz, "user->info mz should match the da dimensions"));
1546
1547 PetscCall(DMGetCoordinateDM(user->da, &coord_dm));
1548 PetscCall(PicurvAssertBool((PetscBool)(coord_dm == user->fda),
1549 "minimal fixture should derive fda from the coordinate-DM path"));
1550
1551 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
1552 PetscFunctionReturn(0);
1553}
1554/**
1555 * @brief Tests that the shared swarm fixture registers the production field set.
1556 */
1557
1559{
1560 SimCtx *simCtx = NULL;
1561 UserCtx *user = NULL;
1562 PetscInt bs = 0;
1563 void *field_ptr = NULL;
1564
1565 PetscFunctionBeginUser;
1566 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
1567 PetscCall(PicurvCreateSwarmPair(user, 2, "ske"));
1568
1569 PetscCall(DMSwarmGetField(user->swarm, "position", &bs, NULL, &field_ptr));
1570 PetscCall(PicurvAssertIntEqual(3, bs, "solver swarm should register particle position"));
1571 PetscCall(PicurvAssertBool((PetscBool)(field_ptr != NULL), "position field should be retrievable"));
1572 PetscCall(DMSwarmRestoreField(user->swarm, "position", &bs, NULL, &field_ptr));
1573
1574 PetscCall(DMSwarmGetField(user->swarm, "velocity", &bs, NULL, &field_ptr));
1575 PetscCall(PicurvAssertIntEqual(3, bs, "solver swarm should register particle velocity"));
1576 PetscCall(DMSwarmRestoreField(user->swarm, "velocity", &bs, NULL, &field_ptr));
1577
1578 PetscCall(DMSwarmGetField(user->swarm, "DMSwarm_CellID", &bs, NULL, &field_ptr));
1579 PetscCall(PicurvAssertIntEqual(3, bs, "solver swarm should register DMSwarm_CellID"));
1580 PetscCall(DMSwarmRestoreField(user->swarm, "DMSwarm_CellID", &bs, NULL, &field_ptr));
1581
1582 PetscCall(DMSwarmGetField(user->swarm, "weight", &bs, NULL, &field_ptr));
1583 PetscCall(PicurvAssertIntEqual(3, bs, "solver swarm should register particle weight"));
1584 PetscCall(DMSwarmRestoreField(user->swarm, "weight", &bs, NULL, &field_ptr));
1585
1586 PetscCall(DMSwarmGetField(user->swarm, "Diffusivity", &bs, NULL, &field_ptr));
1587 PetscCall(PicurvAssertIntEqual(1, bs, "solver swarm should register particle diffusivity"));
1588 PetscCall(DMSwarmRestoreField(user->swarm, "Diffusivity", &bs, NULL, &field_ptr));
1589
1590 PetscCall(DMSwarmGetField(user->swarm, "DiffusivityGradient", &bs, NULL, &field_ptr));
1591 PetscCall(PicurvAssertIntEqual(3, bs, "solver swarm should register particle diffusivity gradients"));
1592 PetscCall(DMSwarmRestoreField(user->swarm, "DiffusivityGradient", &bs, NULL, &field_ptr));
1593
1594 PetscCall(DMSwarmGetField(user->swarm, "Psi", &bs, NULL, &field_ptr));
1595 PetscCall(PicurvAssertIntEqual(1, bs, "solver swarm should register particle scalar Psi"));
1596 PetscCall(DMSwarmRestoreField(user->swarm, "Psi", &bs, NULL, &field_ptr));
1597
1598 PetscCall(DMSwarmGetField(user->swarm, "DMSwarm_location_status", &bs, NULL, &field_ptr));
1599 PetscCall(PicurvAssertIntEqual(1, bs, "solver swarm should register particle location status"));
1600 PetscCall(DMSwarmRestoreField(user->swarm, "DMSwarm_location_status", &bs, NULL, &field_ptr));
1601
1602 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
1603 PetscFunctionReturn(0);
1604}
1605/**
1606 * @brief Tests solver history-vector shifting between time levels.
1607 */
1608
1610{
1611 SimCtx *simCtx = NULL;
1612 UserCtx *user = NULL;
1613
1614 PetscFunctionBeginUser;
1615 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 5, 5, 5));
1616
1617 PetscCall(VecSet(user->Ucont, 11.0));
1618 PetscCall(VecSet(user->Ucont_o, 7.0));
1619 PetscCall(VecSet(user->Ucont_rm1, 3.0));
1620 PetscCall(VecSet(user->Ucat, 5.0));
1621 PetscCall(VecSet(user->Ucat_o, -1.0));
1622 PetscCall(VecSet(user->P, 9.0));
1623 PetscCall(VecSet(user->P_o, -2.0));
1624
1625 PetscCall(UpdateSolverHistoryVectors(user, PETSC_FALSE));
1626
1627 PetscCall(PicurvAssertVecConstant(user->Ucont_o, 11.0, 1.0e-12, "Ucont_o should receive current Ucont"));
1628 PetscCall(PicurvAssertVecConstant(user->Ucont_rm1, 7.0, 1.0e-12, "Ucont_rm1 should receive prior Ucont_o"));
1629 PetscCall(PicurvAssertVecConstant(user->Ucat_o, 5.0, 1.0e-12, "Ucat_o should receive current Ucat"));
1630 PetscCall(PicurvAssertVecConstant(user->P_o, 9.0, 1.0e-12, "P_o should receive current P"));
1631 PetscCall(PicurvAssertVecConstant(user->lUcont_o, 11.0, 1.0e-12, "lUcont_o ghost sync should match Ucont_o"));
1632 PetscCall(PicurvAssertVecConstant(user->lUcont_rm1, 7.0, 1.0e-12, "lUcont_rm1 ghost sync should match Ucont_rm1"));
1633
1634 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
1635 PetscFunctionReturn(0);
1636}
1637/**
1638 * @brief Tests owned-cell range accounting on a single MPI rank.
1639 */
1640
1642{
1643 SimCtx *simCtx = NULL;
1644 UserCtx *user = NULL;
1645 PetscInt xs = -1, ys = -1, zs = -1;
1646 PetscInt xm = -1, ym = -1, zm = -1;
1647
1648 PetscFunctionBeginUser;
1649 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 8, 6, 4));
1650
1651 PetscCall(GetOwnedCellRange(&user->info, 0, &xs, &xm));
1652 PetscCall(GetOwnedCellRange(&user->info, 1, &ys, &ym));
1653 PetscCall(GetOwnedCellRange(&user->info, 2, &zs, &zm));
1654
1655 PetscCall(PicurvAssertIntEqual(0, xs, "single-rank x cell-start index"));
1656 PetscCall(PicurvAssertIntEqual(0, ys, "single-rank y cell-start index"));
1657 PetscCall(PicurvAssertIntEqual(0, zs, "single-rank z cell-start index"));
1658 PetscCall(PicurvAssertIntEqual(user->info.mx - 2, xm, "single-rank x owned cell count"));
1659 PetscCall(PicurvAssertIntEqual(user->info.my - 2, ym, "single-rank y owned cell count"));
1660 PetscCall(PicurvAssertIntEqual(user->info.mz - 2, zm, "single-rank z owned cell count"));
1661
1662 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
1663 PetscFunctionReturn(0);
1664}
1665/**
1666 * @brief Tests neighbor-rank discovery on a single MPI rank.
1667 */
1668
1670{
1671 SimCtx *simCtx = NULL;
1672 UserCtx *user = NULL;
1673
1674 PetscFunctionBeginUser;
1675 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 6, 6, 6));
1676 PetscCall(ComputeAndStoreNeighborRanks(user));
1677
1678 /* A non-periodic single-rank grid: no face, edge or corner neighbour, and itself at the centre. */
1679 for (PetscInt n = 0; n < 27; ++n) {
1680 PetscCall(PicurvAssertIntEqual(n == RANK_NEIGHBOR_INDEX(0, 0, 0) ? 0 : MPI_PROC_NULL, user->neighbors.rank[n],
1681 "single-rank neighbours should be null except the rank itself"));
1682 }
1683 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
1684
1685 /* Periodic in x: the rank is its own neighbour across both x faces, and nothing else exists. */
1686 PetscCall(PicurvCreateMinimalContextsWithPeriodicity(&simCtx, &user, 6, 6, 6, PETSC_TRUE, PETSC_FALSE, PETSC_FALSE));
1687 PetscCall(ComputeAndStoreNeighborRanks(user));
1688 for (PetscInt n = 0; n < 27; ++n) {
1689 const PetscBool along_x = (PetscBool)(n == RANK_NEIGHBOR_INDEX(-1, 0, 0) || n == RANK_NEIGHBOR_INDEX(0, 0, 0) ||
1690 n == RANK_NEIGHBOR_INDEX(1, 0, 0));
1691 PetscCall(PicurvAssertIntEqual(along_x ? 0 : MPI_PROC_NULL, user->neighbors.rank[n],
1692 "x-periodic single-rank neighbours should wrap to the rank along x only"));
1693 }
1694
1695 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
1696 PetscFunctionReturn(0);
1697}
1698/**
1699 * @brief Tests parsing of positive runtime walltime metadata values.
1700 */
1701
1703{
1704 PetscReal seconds = 0.0;
1705
1706 PetscFunctionBeginUser;
1707 PetscCall(PicurvAssertBool(RuntimeWalltimeGuardParsePositiveSeconds("300", &seconds), "plain positive seconds should parse"));
1708 PetscCall(PicurvAssertRealNear(300.0, seconds, 1.0e-12, "parsed walltime seconds"));
1709 PetscCall(PicurvAssertBool(RuntimeWalltimeGuardParsePositiveSeconds(" 42.5 ", &seconds), "whitespace-wrapped decimal seconds should parse"));
1710 PetscCall(PicurvAssertRealNear(42.5, seconds, 1.0e-12, "parsed decimal walltime seconds"));
1711 PetscCall(PicurvAssertBool((PetscBool)!RuntimeWalltimeGuardParsePositiveSeconds("nope", &seconds), "non-numeric metadata should fail parsing"));
1712 PetscCall(PicurvAssertBool((PetscBool)!RuntimeWalltimeGuardParsePositiveSeconds("-10", &seconds), "negative metadata should fail parsing"));
1713 PetscFunctionReturn(0);
1714}
1715/**
1716 * @brief Tests walltime-guard estimator helper calculations.
1717 */
1718
1720{
1721 PetscReal ewma_fast = 0.0;
1722 PetscReal ewma_slow = 0.0;
1723 PetscReal conservative_fast = 0.0;
1724 PetscReal conservative_slow = 0.0;
1725 PetscReal required_headroom = 0.0;
1726
1727 PetscFunctionBeginUser;
1728 ewma_fast = RuntimeWalltimeGuardUpdateEWMA(PETSC_TRUE, 4.0, 6.0, 0.5);
1729 ewma_slow = RuntimeWalltimeGuardUpdateEWMA(PETSC_TRUE, ewma_fast, 12.0, 0.5);
1730 conservative_fast = RuntimeWalltimeGuardConservativeEstimate(5.0, ewma_fast, 6.0);
1731 conservative_slow = RuntimeWalltimeGuardConservativeEstimate(5.0, ewma_slow, 12.0);
1732 required_headroom = RuntimeWalltimeGuardRequiredHeadroom(8.0, 2.0, conservative_slow);
1733
1734 PetscCall(PicurvAssertRealNear(5.0, ewma_fast, 1.0e-12, "EWMA after moderate step"));
1735 PetscCall(PicurvAssertRealNear(8.5, ewma_slow, 1.0e-12, "EWMA after newer slow step"));
1736 PetscCall(PicurvAssertRealNear(6.0, conservative_fast, 1.0e-12, "conservative estimate tracks latest moderate step"));
1737 PetscCall(PicurvAssertRealNear(12.0, conservative_slow, 1.0e-12, "conservative estimate tracks newest slow step"));
1738 PetscCall(PicurvAssertRealNear(24.0, required_headroom, 1.0e-12, "required headroom scales with conservative estimate"));
1739 PetscFunctionReturn(0);
1740}
1741/**
1742 * @brief Tests runtime walltime-guard shutdown trigger decisions.
1743 */
1744
1746{
1747 PetscBool should_trigger = PETSC_FALSE;
1748 PetscReal required_headroom = 0.0;
1749
1750 PetscFunctionBeginUser;
1751 should_trigger = RuntimeWalltimeGuardShouldTrigger(9, 10, 15.0, 5.0, 2.0, 6.0, 6.0, 6.0, &required_headroom);
1752 PetscCall(PicurvAssertBool((PetscBool)!should_trigger, "guard should not trigger before warmup completes"));
1753
1754 should_trigger = RuntimeWalltimeGuardShouldTrigger(10, 10, 40.0, 5.0, 2.0, 10.0, 12.0, 14.0, &required_headroom);
1755 PetscCall(PicurvAssertBool((PetscBool)!should_trigger, "guard should not trigger when remaining walltime exceeds required headroom"));
1756 PetscCall(PicurvAssertRealNear(28.0, required_headroom, 1.0e-12, "required headroom after warmup"));
1757
1758 should_trigger = RuntimeWalltimeGuardShouldTrigger(10, 10, 28.0, 5.0, 2.0, 10.0, 12.0, 14.0, &required_headroom);
1759 PetscCall(PicurvAssertBool(should_trigger, "guard should trigger when remaining walltime reaches required headroom"));
1760 PetscCall(PicurvAssertRealNear(28.0, required_headroom, 1.0e-12, "required headroom remains unchanged at trigger threshold"));
1761 PetscFunctionReturn(0);
1762}
1763/**
1764 * @brief Runs the unit-runtime PETSc test binary.
1765 */
1766
1767int main(int argc, char **argv)
1768{
1769 PetscErrorCode ierr;
1770 const PicurvTestCase cases[] = {
1771 {"distribute-particles-remainder-handling", TestDistributeParticlesRemainderHandling},
1772 {"is-particle-in-box-basic-cases", TestIsParticleInBoxBasicCases},
1773 {"update-particle-weights-computes-expected-ratios", TestUpdateParticleWeightsComputesExpectedRatios},
1774 {"update-particle-position-without-brownian-contribution", TestUpdateParticlePositionWithoutBrownianContribution},
1775 {"update-particle-position-diffusivity-gradient-only", TestUpdateParticlePositionDiffusivityGradientOnly},
1776 {"update-particle-field-iem-relaxation", TestUpdateParticleFieldIEMRelaxation},
1777 {"cart2contra-converts-cartesian-field", TestCart2ContraConvertsCartesianField},
1778 {"cart2contra-uses-finalized-periodic-ucat", TestCart2ContraUsesFinalizedPeriodicUcat},
1779 {"populate-initial-ucont-loads-staged-ucat", TestPopulateInitialUcontLoadsStagedUcat},
1780 {"write-les-fields-copies-owned-periodic-values", TestWriteLESFieldsCopiesOwnedPeriodicValues},
1781 {"staged-ucat-fourier-modes-use-picurv-discrete-symbol", TestStagedUcatFourierModesUsePicurvDiscreteSymbol},
1782 {"populate-initial-ucont-loads-staged-ucont", TestPopulateInitialUcontLoadsStagedUcont},
1783 {"interpolate-all-fields-to-swarm-constant-fields", TestInterpolateAllFieldsToSwarmConstantFields},
1784 {"interpolate-all-fields-to-swarm-corner-averaged-constant-fields", TestInterpolateAllFieldsToSwarmCornerAveragedConstantFields},
1785 {"interpolate-all-fields-to-swarm-face-flux-constant-fields", TestInterpolateAllFieldsToSwarmFaceFluxConstantFields},
1786 {"face-flux-velocity-is-divergence-free", TestFaceFluxVelocityIsDivergenceFree},
1787 {"scatter-all-particle-fields-to-euler-fields-averages-psi", TestScatterAllParticleFieldsToEulerFieldsAveragesPsi},
1788 {"calculate-particle-count-per-cell-counts-global-cell-ids", TestCalculateParticleCountPerCellCountsGlobalCellIDs},
1789 {"reset-all-particle-statuses-leaves-lost-particles-untouched", TestResetAllParticleStatusesLeavesLostParticlesUntouched},
1790 {"check-and-remove-lost-particles-removes-lost-entries", TestCheckAndRemoveLostParticlesRemovesLostEntries},
1791 {"sort-particles-by-cell-keeps-each-point-whole", TestSortParticlesByCellKeepsEachPointWhole},
1792 {"brownian-displacement-keyed-on-seed-particle-step", TestBrownianDisplacementIsKeyedOnSeedParticleAndStep},
1793 {"brownian-displacement-moments", TestBrownianDisplacementMoments},
1794 {"update-all-particle-positions-moves-swarm-entries", TestUpdateAllParticlePositionsMovesSwarmEntries},
1795 {"locate-particle-or-find-migration-target-reflects-at-wall", TestLocateParticleOrFindMigrationTargetReflectsAtWall},
1796 {"locate-all-particles-in-grid-prior-cell-fast-path", TestLocateAllParticlesInGridPriorCellFastPath},
1797 {"locate-all-particles-in-grid-guess-path-resolves-local-particle", TestLocateAllParticlesInGridGuessPathResolvesLocalParticle},
1798 {"locate-particle-or-find-migration-target-counts-research", TestLocateParticleOrFindMigrationTargetCountsReSearch},
1799 {"wall-law-branches-are-continuous", TestWallLawBranchesAreContinuous},
1800 {"log-law-friction-velocity-stays-positive-on-rough-walls", TestLogLawFrictionVelocityStaysPositiveOnRoughWalls},
1801 {"cabot-signed-stress-and-integral-accuracy", TestCabotSignedStressAndIntegralAccuracy},
1802 {"wall-model-scalar-helpers", TestWallModelScalarHelpers},
1803 {"wall-model-velocity-helpers", TestWallModelVelocityHelpers},
1804 {"validate-driven-flow-configuration-no-driven-handlers", TestValidateDrivenFlowConfigurationNoDrivenHandlers},
1805 {"minimal-fixture-mirrors-production-dm-layout", TestMinimalFixtureMirrorsProductionDMLayout},
1806 {"minimal-fixture-registers-production-swarm-fields", TestMinimalFixtureRegistersProductionSwarmFields},
1807 {"update-solver-history-vectors-shifts-states", TestUpdateSolverHistoryVectorsShiftsStates},
1808 {"get-owned-cell-range-single-rank-accounting", TestGetOwnedCellRangeSingleRankAccounting},
1809 {"compute-and-store-neighbor-ranks-single-rank", TestComputeAndStoreNeighborRanksSingleRank},
1810 {"runtime-walltime-guard-parses-positive-seconds", TestRuntimeWalltimeGuardParsesPositiveSeconds},
1811 {"runtime-walltime-guard-estimator-helpers", TestRuntimeWalltimeGuardEstimatorHelpers},
1812 {"runtime-walltime-guard-trigger-decision", TestRuntimeWalltimeGuardTriggerDecision},
1813 };
1814
1815 ierr = PetscInitialize(&argc, &argv, NULL, "PICurv runtime-kernel tests");
1816 if (ierr) {
1817 return (int)ierr;
1818 }
1819
1820 ierr = PicurvRunTests("unit-runtime", cases, sizeof(cases) / sizeof(cases[0]));
1821 if (ierr) {
1822 PetscFinalize();
1823 return (int)ierr;
1824 }
1825
1826 ierr = PetscFinalize();
1827 return (int)ierr;
1828}
PetscErrorCode Validate_DrivenFlowConfiguration(UserCtx *user)
(Private) Validates all consistency rules for a driven flow (channel/pipe) setup.
Definition BC_Handlers.c:15
PetscErrorCode SynchronizePeriodicStaggeredFields(UserCtx *user, PetscInt num_fields, const FieldId field_ids[])
Synchronizes persistent component-staggered vector fields.
PetscErrorCode SynchronizePeriodicCellFields(UserCtx *user, PetscInt num_fields, const FieldId field_ids[])
Synchronizes periodic endpoint cells for a list of cell-centered fields.
Header file for Particle Motion and migration related functions.
PetscErrorCode SortParticlesByCell(DM swarm)
Reorders the local swarm points so that points in the same host cell are contiguous.
PetscErrorCode UpdateAllParticlePositions(UserCtx *user)
Loops over all local particles in the DMSwarm, updating their positions based on velocity and the glo...
PetscErrorCode CalculateParticleCountPerCell(UserCtx *user)
Counts particles in each cell of the DMDA 'da' and stores the result in user->ParticleCount.
PetscErrorCode LocateAllParticlesInGrid(UserCtx *user, BoundingBox *bboxlist)
Orchestrates the complete particle location and migration process for one timestep.
PetscErrorCode CheckAndRemoveLostParticles(UserCtx *user, PetscInt *removedCountLocal, PetscInt *removedCountGlobal, PetscReal *removedScalarSumGlobal, PetscInt *exitedCountGlobal, PetscReal *exitedScalarSumGlobal)
Removes particles that the location algorithm flagged as LOST or EXITED.
PetscErrorCode UpdateParticlePosition(UserCtx *user, Particle *particle)
Updates a particle's position based on its velocity and the timestep dt (stored in user->dt).
PetscErrorCode ResetAllParticleStatuses(UserCtx *user)
Marks all local particles as NEEDS_LOCATION for the next settlement pass.
static PetscBool IsParticleInBox(const BoundingBox *bbox, const Cmpnts *pos)
Whether a position lies in an axis-aligned bounding box, faces included.
PetscErrorCode CalculateBrownianDisplacement(UserCtx *user, PetscInt64 pid, PetscReal diff_eff, Cmpnts *displacement)
Calculates the stochastic displacement vector (Brownian motion) for a single particle.
Header file for Particle related physics modules.
PetscErrorCode UpdateParticleField(ParticleFieldId field_id, PetscReal dt, PetscReal *psi_io, PetscReal diffusivity, PetscReal mean_val, PetscReal delta2, PetscReal C_model)
Updates a single particle's field based on its state and physics model.
Header file for Particle Swarm management functions.
PetscErrorCode UpdateParticleWeights(PetscReal *d, Particle *particle)
Updates a particle's interpolation weights based on distances to cell faces.
PetscErrorCode DistributeParticles(PetscInt numParticles, PetscMPIInt rank, PetscMPIInt size, PetscInt *particlesPerProcess, PetscInt *remainder)
Distributes particles evenly across MPI processes, handling any remainders.
FieldId
Compile-time identity for a catalogued Eulerian field.
@ FIELD_ID_UCAT
@ FIELD_ID_UCONT
PetscErrorCode ScatterAllParticleFieldsToEulerFields(UserCtx *user)
Scatters a predefined set of particle fields to their corresponding Eulerian fields.
PetscErrorCode PopulateInitialUcont(UserCtx *user)
Populate Ucont for one fresh-start block from the initial source (-ic_source_*).
PetscErrorCode InterpolateAllFieldsToSwarm(UserCtx *user)
Interpolates the Eulerian fields the particles carry to every local particle.
PetscErrorCode WriteSimulationFields(UserCtx *user, const char *checkpoint_directory)
Writes simulation fields to files.
Definition io.c:1954
PetscErrorCode WriteFieldData(UserCtx *user, const char *field_name, Vec field_vec, const char *ext)
Writes data from a specific PETSc vector to a file.
Definition io.c:1901
@ PARTICLE_FIELD_ID_PSI
@ PARTICLE_FIELD_ID_VELOCITY
PetscReal RuntimeWalltimeGuardUpdateEWMA(PetscBool has_previous, PetscReal previous_ewma_seconds, PetscReal latest_step_seconds, PetscReal alpha)
Update an EWMA estimate for timestep wall-clock duration.
Definition runloop.c:194
PetscReal RuntimeWalltimeGuardConservativeEstimate(PetscReal warmup_average_seconds, PetscReal ewma_seconds, PetscReal latest_step_seconds)
Return the conservative timestep estimate used by the walltime guard.
Definition runloop.c:209
PetscReal RuntimeWalltimeGuardRequiredHeadroom(PetscReal min_seconds, PetscReal multiplier, PetscReal conservative_estimate_seconds)
Compute the required shutdown headroom from timestep estimate and floor.
Definition runloop.c:223
PetscBool RuntimeWalltimeGuardShouldTrigger(PetscInt completed_steps, PetscInt warmup_steps, PetscReal remaining_seconds, PetscReal min_seconds, PetscReal multiplier, PetscReal warmup_average_seconds, PetscReal ewma_seconds, PetscReal latest_step_seconds, PetscReal *required_headroom_seconds_out)
Decide whether the runtime walltime guard should stop before another step.
Definition runloop.c:237
PetscErrorCode UpdateSolverHistoryVectors(UserCtx *user, PetscBool preserve_previous_state)
Copies the current time step's solution fields into history vectors (e.g., U(t_n) -> U_o,...
Definition runloop.c:376
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 ComputeAndStoreNeighborRanks(UserCtx *user)
Computes and stores the Cartesian neighbor ranks for the DMDA decomposition.
Definition setup.c:3116
PetscErrorCode Contra2Cart(UserCtx *user)
Reconstructs Cartesian velocity (Ucat) at cell centers from contravariant velocity (Ucont) defined on...
Definition setup.c:3313
PetscErrorCode UpdateLocalGhosts(UserCtx *user, FieldId field_id)
Updates the local vector (including ghost points) from its corresponding global vector.
Definition setup.c:2593
PetscErrorCode Cart2Contra(UserCtx *user)
Convert the ghosted Cartesian velocity field to contravariant face fluxes.
Definition setup.c:3396
PetscErrorCode SetupDomainCellDecompositionMap(UserCtx *user)
Creates and distributes a map of the domain's cell decomposition to all ranks.
Definition setup.c:3467
PetscBool RuntimeWalltimeGuardParsePositiveSeconds(const char *text, PetscReal *seconds_out)
Parse a positive floating-point seconds value from runtime metadata.
Definition setup.c:144
static PetscErrorCode TestUpdateParticleFieldIEMRelaxation(void)
Tests IEM relaxation updates for particle-carried fields.
static PetscErrorCode TestLogLawFrictionVelocityStaysPositiveOnRoughWalls(void)
Tests that the log law's friction velocity stays positive on a rough wall.
static PetscErrorCode TestMinimalFixtureMirrorsProductionDMLayout(void)
Tests that the shared minimal fixture mirrors the production DA contract.
static PetscErrorCode TestFaceFluxVelocityIsDivergenceFree(void)
FaceFlux: divergence-free fluxes give a divergence-free velocity, zero at a wall face,...
static PetscErrorCode TestUpdateParticlePositionDiffusivityGradientOnly(void)
Tests particle position updates driven only by diffusivity-gradient drift.
static PetscErrorCode TestLocateAllParticlesInGridGuessPathResolvesLocalParticle(void)
Tests the guess-then-verify orchestrator path for a local particle with an unknown prior cell.
static PetscErrorCode TestWallModelVelocityHelpers(void)
Tests closed-form and iterative wall-model velocity helpers against inverse reconstructions.
static PetscErrorCode TestLocateParticleOrFindMigrationTargetCountsReSearch(void)
Verifies that later settlement passes increment re-search metrics.
static PetscErrorCode TestRuntimeWalltimeGuardParsesPositiveSeconds(void)
Tests parsing of positive runtime walltime metadata values.
static PetscErrorCode TestCart2ContraUsesFinalizedPeriodicUcat(void)
Verifies periodic Ucat endpoints are repaired before Cart2Contra terminal faces.
int main(int argc, char **argv)
Runs the unit-runtime PETSc test binary.
static PetscErrorCode TestInterpolateAllFieldsToSwarmConstantFields(void)
Tests direct interpolation from Eulerian fields to one localized swarm particle.
static PetscErrorCode SyncRuntimeFieldGhosts(UserCtx *user)
Synchronizes the minimal runtime fixture's global fields into their persistent local ghosts.
static PetscErrorCode TestStagedUcatFourierModesUsePicurvDiscreteSymbol(void)
Cross-checks selected exact Fourier modes against PICurv's native discrete symbol.
static PetscErrorCode TestCabotSignedStressAndIntegralAccuracy(void)
Tests Cabot's stress sign and its wall-layer integral at large y+.
static PetscErrorCode TestDistributeParticlesRemainderHandling(void)
Tests particle distribution remainder handling across ranks.
static PetscErrorCode TestResetAllParticleStatusesLeavesLostParticlesUntouched(void)
Tests localized particle-status reset behavior for restart of the location workflow.
static PetscErrorCode SeedSingleParticle(UserCtx *user, PetscInt ci, PetscInt cj, PetscInt ck, PetscReal x, PetscReal y, PetscReal z, PetscReal wx, PetscReal wy, PetscReal wz, PetscInt status_value)
Seeds one localized swarm particle with the cell, position, weight, and status data used by runtime t...
static PetscErrorCode TestPopulateInitialUcontLoadsStagedUcat(void)
Tests loading a staged Ucat file IC and converting it to Ucont.
static PetscErrorCode TestPopulateInitialUcontLoadsStagedUcont(void)
Tests loading a staged Ucont file IC without Cartesian conversion.
static PetscErrorCode TestInterpolateAllFieldsToSwarmFaceFluxConstantFields(void)
FaceFlux: constant face fluxes give that velocity; other fields still interpolate trilinearly.
static PetscErrorCode TestInterpolateAllFieldsToSwarmCornerAveragedConstantFields(void)
Tests the corner-averaged (legacy) interpolation path on constant fields.
static PetscErrorCode TestGetOwnedCellRangeSingleRankAccounting(void)
Tests owned-cell range accounting on a single MPI rank.
static PetscErrorCode TestUpdateParticlePositionWithoutBrownianContribution(void)
Tests particle position updates without Brownian forcing.
static PetscErrorCode TestComputeAndStoreNeighborRanksSingleRank(void)
Tests neighbor-rank discovery on a single MPI rank.
static PetscErrorCode TestCalculateParticleCountPerCellCountsGlobalCellIDs(void)
Tests particle counting by geometric cell IDs using the production +1 storage shift.
static PetscErrorCode TestSortParticlesByCellKeepsEachPointWhole(void)
Tests that sorting by host cell orders points k-slowest, keeps ties and every field together,...
static PetscErrorCode TestWriteLESFieldsCopiesOwnedPeriodicValues(void)
Tests LES output staging from local vectors on a multiply periodic DMDA.
static PetscErrorCode TestValidateDrivenFlowConfigurationNoDrivenHandlers(void)
Tests driven-flow validation when no driven handlers are present.
static PetscErrorCode TestMinimalFixtureRegistersProductionSwarmFields(void)
Tests that the shared swarm fixture registers the production field set.
static PetscErrorCode TestLocateAllParticlesInGridPriorCellFastPath(void)
Tests the location orchestrator fast path when a particle already carries a valid prior cell.
static PetscErrorCode TestScatterAllParticleFieldsToEulerFieldsAveragesPsi(void)
Tests particle-to-grid scattering using known cell occupancy and scalar values.
static PetscErrorCode TestBrownianDisplacementMoments(void)
Tests that increments over many particles have zero mean, variance 2 D dt, and uncorrelated component...
static PetscErrorCode TestUpdateSolverHistoryVectorsShiftsStates(void)
Tests solver history-vector shifting between time levels.
static PetscErrorCode TestUpdateParticleWeightsComputesExpectedRatios(void)
Tests particle weight updates against expected ratios.
static PetscErrorCode StagedFourierModeMaxDivergence(UserCtx *user, PetscInt mode_x, PetscInt mode_y, PetscInt mode_z, Cmpnts amplitude, const char *tmpdir, PetscReal *max_divergence)
Stages a real Cartesian Fourier mode through the production file-IC path.
static PetscErrorCode TestWallLawBranchesAreContinuous(void)
Tests that the wall laws' branches meet, so each reference speed has one friction velocity.
static PetscErrorCode TestLocateParticleOrFindMigrationTargetReflectsAtWall(void)
Tests that a particle beyond a reflecting -Xi face is mirrored back and located, including after a ta...
static PetscErrorCode TestCart2ContraConvertsCartesianField(void)
Tests spatially varying Cartesian-field conversion to contravariant fluxes.
static PetscErrorCode TestCheckAndRemoveLostParticlesRemovesLostEntries(void)
Tests removal of LOST and EXITED particles, their separate tallies, and that survivors keep the one-a...
static PetscErrorCode TestRuntimeWalltimeGuardEstimatorHelpers(void)
Tests walltime-guard estimator helper calculations.
static PetscErrorCode TestIsParticleInBoxBasicCases(void)
Tests basic particle-inside-bounding-box classification cases.
static PetscErrorCode TestRuntimeWalltimeGuardTriggerDecision(void)
Tests runtime walltime-guard shutdown trigger decisions.
static PetscErrorCode TestBrownianDisplacementIsKeyedOnSeedParticleAndStep(void)
Tests that a Brownian increment is a function of (seed, PID, step) alone.
static PetscErrorCode TestUpdateAllParticlePositionsMovesSwarmEntries(void)
Tests swarm-wide particle position updates using the same transport path as the runtime loop.
static PetscErrorCode TestWallModelScalarHelpers(void)
Tests wall-model scalar helper kernels.
PetscErrorCode PicurvMakeTempDir(char *path, size_t path_len)
Creates a unique temporary directory for one test case.
PetscErrorCode PicurvCreateMinimalContexts(SimCtx **simCtx_out, UserCtx **user_out, PetscInt mx, PetscInt my, PetscInt mz)
Builds minimal SimCtx and UserCtx fixtures for C unit tests.
PetscErrorCode PicurvEnsureDir(const char *path)
Ensures a directory exists for test output.
PetscErrorCode PicurvAssertRealNear(PetscReal expected, PetscReal actual, PetscReal tol, const char *context)
Asserts that two real values agree within tolerance.
PetscErrorCode PicurvDestroyMinimalContexts(SimCtx **simCtx_ptr, UserCtx **user_ptr)
Destroys minimal SimCtx/UserCtx fixtures and all owned PETSc objects.
PetscErrorCode PicurvCreateMinimalContextsWithPeriodicity(SimCtx **simCtx_out, UserCtx **user_out, PetscInt mx, PetscInt my, PetscInt mz, PetscBool x_periodic, PetscBool y_periodic, PetscBool z_periodic)
Builds minimal SimCtx and UserCtx fixtures for C unit tests with configurable periodicity.
PetscErrorCode PicurvCreateSwarmPair(UserCtx *user, PetscInt nlocal, const char *post_field_name)
Creates matched solver and post-processing swarms for tests.
PetscErrorCode PicurvRunTests(const char *suite_name, const PicurvTestCase *cases, size_t case_count)
Runs a named C test suite and prints pass/fail progress markers.
PetscErrorCode PicurvAssertVecConstant(Vec vec, PetscScalar expected, PetscReal tol, const char *context)
Asserts that a PETSc vector is spatially constant within tolerance.
PetscErrorCode PicurvAssertIntEqual(PetscInt expected, PetscInt actual, const char *context)
Asserts that two integer values are equal.
PetscErrorCode PicurvAssertBool(PetscBool value, const char *context)
Asserts that one boolean condition is true.
PetscErrorCode PicurvRemoveTempDir(const char *path)
Recursively removes a temporary directory created by PicurvMakeTempDir.
Shared declarations for the PICurv C test fixture and assertion layer.
Named test case descriptor consumed by PicurvRunTests.
@ DYNAMIC_SMAGORINSKY
Definition variables.h:586
Vec lDiffusivityGradient
Definition variables.h:1201
@ PERIODIC
Definition variables.h:325
Cmpnts vel
Definition variables.h:240
#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
BoundaryFaceConfig boundary_faces[6]
Definition variables.h:1182
PetscInt64 searchLocatedCount
Definition variables.h:283
PetscInt64 reflectionCount
Definition variables.h:296
PetscInt64 searchLostCount
Definition variables.h:284
PetscInt cell[3]
Definition variables.h:238
SimCtx * simCtx
Back-pointer to the master simulation context.
Definition variables.h:1160
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
@ NEEDS_LOCATION
Definition variables.h:187
@ ACTIVE_AND_LOCATED
Definition variables.h:188
@ EXITED
The particle crossed a domain-boundary face whose particle policy removes it.
Definition variables.h:192
PetscInt KM
Definition variables.h:1171
@ PARTICLE_BOUNDARY_REFLECT
The particle is mirrored about the face plane and stays.
Definition variables.h:338
PetscInt64 traversalStepsSum
Definition variables.h:285
Vec lUcont_rm1
Definition variables.h:1207
Cmpnts max_coords
Maximum x, y, z coordinates of the bounding box.
Definition variables.h:214
Cmpnts diffusivitygradient
Definition variables.h:245
PetscInt64 searchPopulation
Definition variables.h:282
PetscReal dt
Definition variables.h:933
RankNeighbors neighbors
Definition variables.h:1174
PetscInt currentSettlementPass
Definition variables.h:299
Vec DiffusivityGradient
Definition variables.h:1201
Vec Ucont
Definition variables.h:1197
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
PetscInt64 reSearchCount
Definition variables.h:286
char * current_io_directory
Definition variables.h:944
Vec lUcont_o
Definition variables.h:1204
PetscInt64 bboxGuessFallbackCount
Definition variables.h:292
InterpolationMethod interpolationMethod
Definition variables.h:1055
Vec Ucat_o
Definition variables.h:1204
PetscInt64 bboxGuessSuccessCount
Definition variables.h:291
BoundingBox * bboxlist
Definition variables.h:1053
Vec lNu_t
Definition variables.h:1259
PetscInt64 maxParticlePassDepth
Definition variables.h:293
ParticleBoundaryPolicy particle_policy
What a particle crossing this face becomes (BC param particle_policy).
Definition variables.h:428
PetscScalar z
Definition variables.h:145
@ INTERP_CORNER_AVERAGED
Definition variables.h:762
@ INTERP_FACE_FLUX
Definition variables.h:763
Vec ParticleCount
Definition variables.h:1276
Vec Ucont_o
Definition variables.h:1204
PetscInt JM
Definition variables.h:1171
PetscInt particleRandomSeed
Base seed for every particle RNG stream (-particle_random_seed).
Definition variables.h:1050
char initialConditionDirectory[PETSC_MAX_PATH_LEN]
Definition variables.h:979
PetscBool initialConditionStaged
Definition variables.h:977
Vec Ucont_rm1
Definition variables.h:1207
SearchMetricsState searchMetrics
Definition variables.h:1073
PetscReal diffusivity
Definition variables.h:244
Vec lUcont
Definition variables.h:1197
PetscInt step
Definition variables.h:924
Vec Diffusivity
Definition variables.h:1200
DMDALocalInfo info
Definition variables.h:1169
Vec lUcat
Definition variables.h:1197
PetscMPIInt rank[27]
Definition variables.h:259
PetscScalar y
Definition variables.h:145
@ IC_FIELD_UCONT
Definition variables.h:203
@ IC_FIELD_UCAT
Definition variables.h:202
PetscInt IM
Definition variables.h:1171
char _io_context_buffer[PETSC_MAX_PATH_LEN]
Definition variables.h:943
Cmpnts weights
Definition variables.h:241
@ NUM_FACES
Definition variables.h:197
PetscInt les
Active LES closure; an LESModelType value.
Definition variables.h:1041
Vec lDiffusivity
Definition variables.h:1200
BCType mathematical_type
Definition variables.h:426
PetscInt64 searchAttempts
Definition variables.h:281
InitialConditionField initialConditionField
Definition variables.h:978
PetscInt64 reflectionFallbackCount
Definition variables.h:297
PetscInt64 PID
Definition variables.h:237
PetscInt64 maxTraversalFailCount
Definition variables.h:288
@ BC_FACE_NEG_X
Definition variables.h:309
@ BC_FACE_POS_X
Definition variables.h:309
Defines a 3D axis-aligned bounding box.
Definition variables.h:212
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
Header file for particle location functions using the walking search algorithm.
PetscErrorCode LocateParticleOrFindMigrationTarget(UserCtx *user, const struct FacePlaneArrays *planes, Particle *particle, ParticleLocationStatus *status_out)
double u_Werner(double kinematic_viscosity, double wall_distance, double friction_velocity)
Computes velocity using Werner-Wengle wall function.
double u_hydset_roughness(double kinematic_viscosity, double wall_distance, double friction_velocity, double roughness_height)
Computes velocity from log-law for rough walls.
double u_Werner_explicit(double kinematic_viscosity, double wall_distance, double wall_shear_stress)
Wall-parallel velocity at a distance, from the Werner-Wengle wall stress.
double find_utau_hydset(double kinematic_viscosity, double known_velocity, double wall_distance, double initial_guess, double roughness_height)
Solves for friction velocity using Newton-Raphson iteration.
double u_Cabot(double kinematic_viscosity, double wall_distance, double friction_velocity, double pressure_gradient_tangent, double wall_shear_stress)
Computes velocity using Cabot wall function.
void find_utau_Cabot(double kinematic_viscosity, double velocity, double wall_distance, double initial_guess, double pressure_gradient_tangent, double pressure_gradient_normal, double *friction_velocity, double *wall_shear_velocity, double *wall_shear_normal)
Solves for friction velocity using Cabot wall function.
double integrate_1(double kinematic_viscosity, double wall_distance, double friction_velocity, int integration_mode)
Integrates eddy viscosity profile from wall to distance y.
double f_hydset(double kinematic_viscosity, double known_velocity, double wall_distance, double friction_velocity_guess, double roughness_height)
Residual function for friction velocity equation (log-law with roughness)
double E_coeff(double friction_velocity, double roughness_height, double kinematic_viscosity)
Computes roughness-modified log-law coefficient E.
double taw_Werner(double kinematic_viscosity, double velocity, double wall_distance)
Wall shear stress from the cell-integrated Werner-Wengle relation.
double nu_t(double yplus)
Computes turbulent eddy viscosity ratio (ν_t / ν)
double find_utau_Werner(double kinematic_viscosity, double velocity, double wall_distance, double initial_guess)
Friction velocity from a point velocity, inverting u_Werner() exactly.