PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
test_mpi_kernels.c
Go to the documentation of this file.
1/**
2 * @file test_mpi_kernels.c
3 * @brief C unit tests for MPI collective helper routines.
4 */
5
6#include "test_support.h"
7
8#include "ParticleMotion.h"
9#include "ParticleSwarm.h"
10#include "ParticlePhysics.h"
11#include "runloop.h"
12#include "expression.h"
13#include "initialcondition.h"
14#include "Boundaries.h"
15#include "grid.h"
16#include "Metric.h"
17#include "walkingsearch.h"
18#include "setup.h"
19#include "statistics_target.h"
21#include "statistics_window.h"
22#include "io.h"
23#include "field_catalog.h"
24#include "les.h"
25#include "logging.h"
26
27#include <stdlib.h>
28
29/**
30 * @brief Marks both x boundary faces as geometric periodic boundaries.
31 */
41
42/**
43 * @brief Returns a deterministic scalar value for periodic-transfer assertions.
44 */
45static PetscReal PeriodicScalarValue(PetscInt i, PetscInt j, PetscInt k, PetscReal offset)
46{
47 return offset + (PetscReal)(i + 10 * j + 100 * k);
48}
49/**
50 * @brief Tests collective particle distribution consistency across MPI ranks.
51 */
52
54{
55 PetscMPIInt rank = 0, size = 1;
56 PetscInt local_particles = 0;
57 PetscInt remainder = 0;
58 PetscInt global_particles = 0;
59 PetscInt remainder_min = 0, remainder_max = 0;
60 const PetscInt total_particles = 137;
61
62 PetscFunctionBeginUser;
63 PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank));
64 PetscCallMPI(MPI_Comm_size(PETSC_COMM_WORLD, &size));
65 PetscCall(PicurvAssertBool((PetscBool)(size >= 2), "unit-mpi requires at least two MPI ranks"));
66
67 PetscCall(DistributeParticles(total_particles, rank, size, &local_particles, &remainder));
68
69 PetscCall(PicurvAssertIntEqual(
70 total_particles / size + (((PetscInt)rank < remainder) ? 1 : 0),
71 local_particles,
72 "local particle share should match quotient+remainder policy"));
73
74 PetscCallMPI(MPI_Allreduce(&local_particles, &global_particles, 1, MPIU_INT, MPI_SUM, PETSC_COMM_WORLD));
75 PetscCall(PicurvAssertIntEqual(total_particles, global_particles, "distributed particle count must conserve total particles"));
76
77 PetscCallMPI(MPI_Allreduce(&remainder, &remainder_min, 1, MPIU_INT, MPI_MIN, PETSC_COMM_WORLD));
78 PetscCallMPI(MPI_Allreduce(&remainder, &remainder_max, 1, MPIU_INT, MPI_MAX, PETSC_COMM_WORLD));
79 PetscCall(PicurvAssertIntEqual(remainder_min, remainder_max, "all ranks should report the same remainder"));
80 PetscFunctionReturn(0);
81}
82/**
83 * @brief Tests multi-rank bounding-box gather and broadcast helpers.
84 */
85
86static PetscErrorCode TestBoundingBoxCollectivesMultiRank(void)
87{
88 SimCtx *simCtx = NULL;
89 UserCtx *user = NULL;
90 BoundingBox local_bbox;
91 BoundingBox *boxes = NULL;
92 PetscMPIInt rank = 0, size = 1;
93 PetscReal global_min_x = 0.0;
94 PetscReal global_max_x = 0.0;
95 PetscReal expected_global_max_x = 0.0;
96
97 PetscFunctionBeginUser;
98 PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank));
99 PetscCallMPI(MPI_Comm_size(PETSC_COMM_WORLD, &size));
100 PetscCall(PicurvAssertBool((PetscBool)(size >= 2), "unit-mpi requires at least two MPI ranks"));
101
102 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 8, 6, 4));
103 expected_global_max_x = ((PetscReal)(user->IM - 1) / (PetscReal)user->IM) + 1.0e-6;
104 PetscCall(ComputeLocalBoundingBox(user, &local_bbox));
105 PetscCall(GatherAllBoundingBoxes(user, &boxes));
106 PetscCall(BroadcastAllBoundingBoxes(user, &boxes));
107 PetscCall(PicurvAssertBool((PetscBool)(boxes != NULL), "all ranks should hold the gathered bounding-box table"));
108
109 for (PetscMPIInt r = 0; r < size; ++r) {
110 PetscCall(PicurvAssertBool((PetscBool)(boxes[r].min_coords.x <= boxes[r].max_coords.x), "bbox x-range should be valid"));
111 PetscCall(PicurvAssertBool((PetscBool)(boxes[r].min_coords.y <= boxes[r].max_coords.y), "bbox y-range should be valid"));
112 PetscCall(PicurvAssertBool((PetscBool)(boxes[r].min_coords.z <= boxes[r].max_coords.z), "bbox z-range should be valid"));
113 }
114
115 PetscCall(PicurvAssertRealNear(local_bbox.min_coords.x, boxes[rank].min_coords.x, 1.0e-10, "local bbox min x preserved"));
116 PetscCall(PicurvAssertRealNear(local_bbox.max_coords.x, boxes[rank].max_coords.x, 1.0e-10, "local bbox max x preserved"));
117
118 PetscCallMPI(MPI_Allreduce(&local_bbox.min_coords.x, &global_min_x, 1, MPIU_REAL, MPI_MIN, PETSC_COMM_WORLD));
119 PetscCallMPI(MPI_Allreduce(&local_bbox.max_coords.x, &global_max_x, 1, MPIU_REAL, MPI_MAX, PETSC_COMM_WORLD));
120 PetscCall(PicurvAssertBool((PetscBool)(global_min_x <= 0.0), "global min x should include domain start"));
121 PetscCall(PicurvAssertRealNear(expected_global_max_x, global_max_x, 1.0e-10, "global max x should match the normalized physical-node domain end"));
122
123 free(boxes);
124 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
125 PetscFunctionReturn(0);
126}
127/** @brief Width of cell n (1-based interior index) along an axis in the line-fraction test. */
128static PetscReal LineFractionTestWidth(PetscInt axis, PetscInt n)
129{
130 if (axis == 0) return PetscPowReal(1.3, (PetscReal)n); /* geometric stretching */
131 if (axis == 1) return 0.5; /* uniform */
132 return 1.0 + 0.1 * (PetscReal)n; /* linear growth */
133}
134
135/**
136 * @brief Grid-line fractions follow arc length on a stretched orthogonal grid, and the
137 * lines that cross ranks are summed in order.
138 */
139static PetscErrorCode TestGridLineFractionsFollowArcLength(void)
140{
141 SimCtx *simCtx = NULL;
142 UserCtx *user = NULL;
143 Vec fraction, length;
144 Cmpnts ***csi, ***eta, ***zet;
145 const Cmpnts ***frac, ***len;
146 PetscReal ***aj;
147
148 PetscFunctionBeginUser;
149 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 9, 7, 8));
150 const DMDALocalInfo info = user->info;
151 const PetscInt mx = info.mx, my = info.my, mz = info.mz, n_nodes[3] = {mx, my, mz};
152
153 /* An orthogonal box cell of widths (dx, dy, dz) has face-area vectors (dy dz, 0, 0),
154 (0, dx dz, 0), (0, 0, dx dy) and inverse volume 1/(dx dy dz). */
155 PetscCall(DMDAVecGetArray(user->fda, user->Csi, &csi));
156 PetscCall(DMDAVecGetArray(user->fda, user->Eta, &eta));
157 PetscCall(DMDAVecGetArray(user->fda, user->Zet, &zet));
158 PetscCall(DMDAVecGetArray(user->da, user->Aj, &aj));
159 for (PetscInt k = info.zs; k < info.zs + info.zm; ++k)
160 for (PetscInt j = info.ys; j < info.ys + info.ym; ++j)
161 for (PetscInt i = info.xs; i < info.xs + info.xm; ++i) {
162 const PetscReal dx = LineFractionTestWidth(0, i), dy = LineFractionTestWidth(1, j), dz = LineFractionTestWidth(2, k);
163 csi[k][j][i] = (Cmpnts){dy * dz, 0.0, 0.0};
164 eta[k][j][i] = (Cmpnts){0.0, dx * dz, 0.0};
165 zet[k][j][i] = (Cmpnts){0.0, 0.0, dx * dy};
166 aj[k][j][i] = 1.0 / (dx * dy * dz);
167 }
168 PetscCall(DMDAVecRestoreArray(user->da, user->Aj, &aj));
169 PetscCall(DMDAVecRestoreArray(user->fda, user->Zet, &zet));
170 PetscCall(DMDAVecRestoreArray(user->fda, user->Eta, &eta));
171 PetscCall(DMDAVecRestoreArray(user->fda, user->Csi, &csi));
172 PetscCall(DMGlobalToLocal(user->fda, user->Csi, INSERT_VALUES, user->lCsi));
173 PetscCall(DMGlobalToLocal(user->fda, user->Eta, INSERT_VALUES, user->lEta));
174 PetscCall(DMGlobalToLocal(user->fda, user->Zet, INSERT_VALUES, user->lZet));
175 PetscCall(DMGlobalToLocal(user->da, user->Aj, INSERT_VALUES, user->lAj));
176
177 PetscCall(DMCreateGlobalVector(user->fda, &fraction));
178 PetscCall(DMCreateGlobalVector(user->fda, &length));
179 PetscCall(ComputeGridLineFractions(user, fraction, length));
180 PetscCall(DMDAVecGetArrayRead(user->fda, fraction, &frac));
181 PetscCall(DMDAVecGetArrayRead(user->fda, length, &len));
182 for (PetscInt k = PetscMax(1, info.zs); k < PetscMin(mz - 1, info.zs + info.zm); ++k)
183 for (PetscInt j = PetscMax(1, info.ys); j < PetscMin(my - 1, info.ys + info.ym); ++j)
184 for (PetscInt i = PetscMax(1, info.xs); i < PetscMin(mx - 1, info.xs + info.xm); ++i) {
185 const PetscInt idx[3] = {i, j, k};
186 const PetscReal got_f[3] = {frac[k][j][i].x, frac[k][j][i].y, frac[k][j][i].z};
187 const PetscReal got_l[3] = {len[k][j][i].x, len[k][j][i].y, len[k][j][i].z};
188 for (PetscInt axis = 0; axis < 3; ++axis) {
189 PetscReal before = 0.0, total = 0.0;
190 for (PetscInt n = 1; n < n_nodes[axis] - 1; ++n) {
191 if (n < idx[axis]) before += LineFractionTestWidth(axis, n);
192 total += LineFractionTestWidth(axis, n);
193 }
194 const PetscReal expected = (before + 0.5 * LineFractionTestWidth(axis, idx[axis])) / total;
195 PetscCall(PicurvAssertRealNear(expected, got_f[axis], 1.0e-12, "arc-length fraction"));
196 PetscCall(PicurvAssertRealNear(total, got_l[axis], 1.0e-12, "grid-line length"));
197 }
198 }
199 PetscCall(DMDAVecRestoreArrayRead(user->fda, length, &len));
200 PetscCall(DMDAVecRestoreArrayRead(user->fda, fraction, &frac));
201 PetscCall(VecDestroy(&fraction));
202 PetscCall(VecDestroy(&length));
203 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
204 PetscFunctionReturn(0);
205}
206
207/**
208 * @brief Tests distributed synchronization of persistent cell-centered scalar fields.
209 */
210
212{
213 SimCtx *simCtx = NULL;
214 UserCtx *user = NULL;
215 PetscReal ***p = NULL;
216 PetscReal ***cs = NULL;
217 PetscReal ***diffusivity = NULL;
218 Cmpnts ***ucat = NULL;
220 PetscInt xs, xe, ys, ye, zs, ze, mx;
221
222 PetscFunctionBeginUser;
223 PetscCall(PicurvCreateMinimalContextsWithPeriodicity(&simCtx, &user, 8, 6, 6, PETSC_TRUE, PETSC_FALSE, PETSC_FALSE));
224 MarkXPeriodic(user);
225 PetscCall(PicurvAssertBool((PetscBool)(user->info.xm < user->info.mx),
226 "periodic cell synchronization test requires the x axis to be partitioned"));
227 PetscCall(DMCreateGlobalVector(user->da, &user->CS));
228 PetscCall(DMCreateLocalVector(user->da, &user->lCs));
229
230 xs = user->info.xs;
231 xe = xs + user->info.xm;
232 ys = user->info.ys;
233 ye = ys + user->info.ym;
234 zs = user->info.zs;
235 ze = zs + user->info.zm;
236 mx = user->info.mx;
237
238 PetscCall(DMDAVecGetArray(user->da, user->P, &p));
239 PetscCall(DMDAVecGetArray(user->da, user->CS, &cs));
240 PetscCall(DMDAVecGetArray(user->da, user->Diffusivity, &diffusivity));
241 PetscCall(DMDAVecGetArray(user->fda, user->Ucat, &ucat));
242 for (PetscInt k = zs; k < ze; ++k) {
243 for (PetscInt j = ys; j < ye; ++j) {
244 for (PetscInt i = xs; i < xe; ++i) {
245 p[k][j][i] = PeriodicScalarValue(i, j, k, 0.0);
246 cs[k][j][i] = PeriodicScalarValue(i, j, k, 1000.0);
247 diffusivity[k][j][i] = PeriodicScalarValue(i, j, k, 2000.0);
248 ucat[k][j][i] = (Cmpnts){PeriodicScalarValue(i,j,k,3000.0),0.0,0.0};
249 }
250 }
251 }
252 PetscCall(DMDAVecRestoreArray(user->da, user->P, &p));
253 PetscCall(DMDAVecRestoreArray(user->da, user->CS, &cs));
254 PetscCall(DMDAVecRestoreArray(user->da, user->Diffusivity, &diffusivity));
255 PetscCall(DMDAVecRestoreArray(user->fda, user->Ucat, &ucat));
256
257 PetscCall(SynchronizePeriodicCellFields(user, 4, fields));
258
259 PetscCall(DMDAVecGetArrayRead(user->da, user->P, &p));
260 PetscCall(DMDAVecGetArrayRead(user->da, user->CS, &cs));
261 PetscCall(DMDAVecGetArrayRead(user->da, user->Diffusivity, &diffusivity));
262 PetscCall(DMDAVecGetArrayRead(user->fda, user->Ucat, &ucat));
263 if (xs == 0) {
264 for (PetscInt k = zs; k < ze; ++k) {
265 for (PetscInt j = ys; j < ye; ++j) {
266 PetscCall(PicurvAssertRealNear(PeriodicScalarValue(mx - 2, j, k, 0.0), p[k][j][0], 1.0e-12,
267 "distributed P negative endpoint should copy the opposite interior"));
268 PetscCall(PicurvAssertRealNear(PeriodicScalarValue(mx - 2, j, k, 1000.0), cs[k][j][0], 1.0e-12,
269 "distributed CS negative endpoint should copy the opposite interior"));
270 PetscCall(PicurvAssertRealNear(PeriodicScalarValue(mx - 2, j, k, 2000.0), diffusivity[k][j][0], 1.0e-12,
271 "distributed Diffusivity negative endpoint should copy the opposite interior"));
272 PetscCall(PicurvAssertRealNear(PeriodicScalarValue(mx-2,j,k,3000.0),ucat[k][j][0].x,1e-12,
273 "distributed Ucat negative endpoint should copy the opposite interior"));
274 }
275 }
276 }
277 if (xe == mx) {
278 for (PetscInt k = zs; k < ze; ++k) {
279 for (PetscInt j = ys; j < ye; ++j) {
280 PetscCall(PicurvAssertRealNear(PeriodicScalarValue(1, j, k, 0.0), p[k][j][mx - 1], 1.0e-12,
281 "distributed P positive endpoint should copy the opposite interior"));
282 PetscCall(PicurvAssertRealNear(PeriodicScalarValue(1, j, k, 1000.0), cs[k][j][mx - 1], 1.0e-12,
283 "distributed CS positive endpoint should copy the opposite interior"));
284 PetscCall(PicurvAssertRealNear(PeriodicScalarValue(1, j, k, 2000.0), diffusivity[k][j][mx - 1], 1.0e-12,
285 "distributed Diffusivity positive endpoint should copy the opposite interior"));
286 PetscCall(PicurvAssertRealNear(PeriodicScalarValue(1,j,k,3000.0),ucat[k][j][mx-1].x,1e-12,
287 "distributed Ucat positive endpoint should copy the leading interior"));
288 }
289 }
290 }
291 PetscCall(DMDAVecRestoreArrayRead(user->da, user->P, &p));
292 PetscCall(DMDAVecRestoreArrayRead(user->da, user->CS, &cs));
293 PetscCall(DMDAVecRestoreArrayRead(user->da, user->Diffusivity, &diffusivity));
294 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->Ucat, &ucat));
295 PetscCall(DMDAVecGetArrayRead(user->fda,user->lUcat,&ucat));
296 if(xs==0) PetscCall(PicurvAssertRealNear(PeriodicScalarValue(1,2,2,3000.0),ucat[2][2][-1].x,1e-12,
297 "distributed local Ucat negative ghost follows corrected global endpoint"));
298 if(xe==mx) PetscCall(PicurvAssertRealNear(PeriodicScalarValue(mx-2,2,2,3000.0),ucat[2][2][mx].x,1e-12,
299 "distributed local Ucat positive ghost follows corrected global endpoint"));
300 PetscCall(DMDAVecRestoreArrayRead(user->fda,user->lUcat,&ucat));
301
302 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
303 PetscFunctionReturn(0);
304}
305/**
306 * @brief Tests periodic seam translation discovery when seam nodes are on different ranks.
307 */
309{
310 SimCtx *simCtx = NULL;
311 UserCtx *user = NULL;
312 PetscReal expected_translation = 0.0;
313
314 PetscFunctionBeginUser;
315 PetscCall(PicurvCreateMinimalContextsWithPeriodicity(&simCtx, &user, 8, 6, 6, PETSC_TRUE, PETSC_FALSE, PETSC_FALSE));
316 MarkXPeriodic(user);
317 PetscCall(PicurvAssertBool((PetscBool)(user->info.xm < user->info.mx),
318 "periodic geometry validation test requires the x axis to be partitioned"));
319
320 expected_translation = (PetscReal)(user->info.mx - 2) / (PetscReal)user->info.mx;
321 PetscCall(ValidatePeriodicGeometry(user));
322
324 "distributed X-periodic translation should be marked valid"));
325 PetscCall(PicurvAssertRealNear(expected_translation, user->periodic_translation[0].x, 1.0e-12,
326 "distributed X-periodic translation"));
327 PetscCall(PicurvAssertRealNear(0.0, user->periodic_translation[0].y, 1.0e-12,
328 "distributed X-periodic translation y component"));
329 PetscCall(PicurvAssertRealNear(0.0, user->periodic_translation[0].z, 1.0e-12,
330 "distributed X-periodic translation z component"));
331
332 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
333 PetscFunctionReturn(0);
334}
335
336/**
337 * @brief Tests translated face-center ghosts when the periodic axis is partitioned.
338 */
340{
341 SimCtx *simCtx = NULL;
342 UserCtx *user = NULL;
343 Cmpnts ***centx = NULL;
344 const Cmpnts ***lcentx = NULL;
345 const FieldId fields[] = {FIELD_ID_CENTX};
346 PetscReal translation, spacing;
347 PetscInt xs, xe, mx;
348
349 PetscFunctionBeginUser;
350 PetscCall(PicurvCreateMinimalContextsWithPeriodicity(&simCtx, &user, 8, 6, 6, PETSC_TRUE, PETSC_FALSE, PETSC_FALSE));
351 MarkXPeriodic(user);
352 PetscCall(ValidatePeriodicGeometry(user));
353 PetscCall(PicurvAssertBool((PetscBool)(user->info.xm < user->info.mx),
354 "face-center coordinate test requires the x axis to be partitioned"));
355 translation = user->periodic_translation[0].x;
356 spacing = translation / (PetscReal)(user->info.mx - 2);
357 xs = user->info.xs;
358 xe = xs + user->info.xm;
359 mx = user->info.mx;
360
361 PetscCall(DMDAVecGetArray(user->fda, user->Centx, &centx));
362 for (PetscInt k = user->info.zs; k < user->info.zs + user->info.zm; k++) {
363 for (PetscInt j = user->info.ys; j < user->info.ys + user->info.ym; j++) {
364 for (PetscInt i = xs; i < xe; i++) {
365 centx[k][j][i] = (Cmpnts){spacing * i, 2.0 + j, 3.0 + k};
366 }
367 }
368 }
369 PetscCall(DMDAVecRestoreArray(user->fda, user->Centx, &centx));
370
371 PetscCall(SynchronizePeriodicFaceFields(user, 'i', 1, fields));
372 PetscCall(DMDAVecGetArrayRead(user->fda, user->lCentx, &lcentx));
373 if (xs == 0) {
374 PetscCall(PicurvAssertRealNear(-spacing, lcentx[2][2][-1].x, 1.0e-12,
375 "distributed translated Centx negative adjacent ghost"));
376 PetscCall(PicurvAssertRealNear(0.0, lcentx[2][2][0].x, 1.0e-12,
377 "distributed translated Centx negative endpoint"));
378 }
379 if (xe == mx) {
380 PetscCall(PicurvAssertRealNear(translation + spacing, lcentx[2][2][mx - 1].x, 1.0e-12,
381 "distributed translated Centx positive endpoint"));
382 PetscCall(PicurvAssertRealNear(translation + 2.0 * spacing, lcentx[2][2][mx].x, 1.0e-12,
383 "distributed translated Centx positive adjacent ghost"));
384 }
385 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lCentx, &lcentx));
386
387 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
388 PetscFunctionReturn(0);
389}
390/**
391 * @brief Tests persistent I-face synchronization across an MPI-partitioned seam.
392 */
394{
395 SimCtx *simCtx = NULL;
396 UserCtx *user = NULL;
397 PetscReal ***iaj = NULL;
398 const FieldId fields[] = {FIELD_ID_IAJ};
399 PetscInt xs, xe, ys, ye, zs, ze, mx;
400
401 PetscFunctionBeginUser;
402 PetscCall(PicurvCreateMinimalContextsWithPeriodicity(&simCtx, &user, 8, 6, 6, PETSC_TRUE, PETSC_FALSE, PETSC_FALSE));
403 MarkXPeriodic(user);
404 PetscCall(PicurvAssertBool((PetscBool)(user->info.xm < user->info.mx),
405 "periodic face synchronization test requires the x axis to be partitioned"));
406
407 xs = user->info.xs; xe = xs + user->info.xm;
408 ys = user->info.ys; ye = ys + user->info.ym;
409 zs = user->info.zs; ze = zs + user->info.zm;
410 mx = user->info.mx;
411
412 PetscCall(DMDAVecGetArray(user->da, user->IAj, &iaj));
413 for (PetscInt k = zs; k < ze; k++) for (PetscInt j = ys; j < ye; j++) for (PetscInt i = xs; i < xe; i++) {
414 iaj[k][j][i] = PeriodicScalarValue(i, j, k, 3000.0);
415 }
416 PetscCall(DMDAVecRestoreArray(user->da, user->IAj, &iaj));
417
418 PetscCall(SynchronizePeriodicFaceFields(user, 'i', 1, fields));
419
420 PetscCall(DMDAVecGetArrayRead(user->da, user->IAj, &iaj));
421 if (xs == 0) {
422 for (PetscInt k = zs; k < ze; k++) for (PetscInt j = ys; j < ye; j++) {
423 PetscCall(PicurvAssertRealNear(PeriodicScalarValue(mx - 2, j, k, 3000.0), iaj[k][j][0], 1.0e-12,
424 "distributed I-face negative seam should copy the opposite physical seam"));
425 }
426 }
427 if (xe == mx) {
428 for (PetscInt k = zs; k < ze; k++) for (PetscInt j = ys; j < ye; j++) {
429 PetscCall(PicurvAssertRealNear(PeriodicScalarValue(1, j, k, 3000.0), iaj[k][j][mx - 1], 1.0e-12,
430 "distributed I-face positive dummy should copy the leading physical face"));
431 }
432 }
433 PetscCall(DMDAVecRestoreArrayRead(user->da, user->IAj, &iaj));
434
435 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
436 PetscFunctionReturn(0);
437}
438/**
439 * @brief Tests persistent Ucont synchronization across an MPI-partitioned seam.
440 */
442{
443 SimCtx *simCtx = NULL;
444 UserCtx *user = NULL;
445 Cmpnts ***ucont = NULL;
446 const FieldId fields[] = {FIELD_ID_UCONT};
447 PetscInt xs, xe, ys, ye, zs, ze, mx;
448
449 PetscFunctionBeginUser;
450 PetscCall(PicurvCreateMinimalContextsWithPeriodicity(&simCtx, &user, 8, 6, 6, PETSC_TRUE, PETSC_FALSE, PETSC_FALSE));
451 MarkXPeriodic(user);
452 PetscCall(PicurvAssertBool((PetscBool)(user->info.xm < user->info.mx),
453 "periodic staggered synchronization test requires the x axis to be partitioned"));
454
455 xs = user->info.xs; xe = xs + user->info.xm;
456 ys = user->info.ys; ye = ys + user->info.ym;
457 zs = user->info.zs; ze = zs + user->info.zm;
458 mx = user->info.mx;
459
460 PetscCall(DMDAVecGetArray(user->fda, user->Ucont, &ucont));
461 for (PetscInt k = zs; k < ze; k++) for (PetscInt j = ys; j < ye; j++) for (PetscInt i = xs; i < xe; i++) {
462 PetscReal value = PeriodicScalarValue(i, j, k, 0.0);
463 ucont[k][j][i] = (Cmpnts){value + 1000.0, value + 2000.0, value + 3000.0};
464 }
465 PetscCall(DMDAVecRestoreArray(user->fda, user->Ucont, &ucont));
466
467 PetscCall(SynchronizePeriodicStaggeredFields(user, 1, fields));
468
469 PetscCall(DMDAVecGetArrayRead(user->fda, user->Ucont, &ucont));
470 if (xs == 0) {
471 for (PetscInt k = zs; k < ze; k++) for (PetscInt j = ys; j < ye; j++) {
472 PetscReal expected = PeriodicScalarValue(mx - 2, j, k, 0.0);
473 PetscCall(PicurvAssertRealNear(expected + 1000.0, ucont[k][j][0].x, 1.0e-12,
474 "distributed Ucont.x negative seam"));
475 PetscCall(PicurvAssertRealNear(expected + 2000.0, ucont[k][j][0].y, 1.0e-12,
476 "distributed Ucont.y negative X endpoint"));
477 }
478 }
479 if (xe == mx) {
480 for (PetscInt k = zs; k < ze; k++) for (PetscInt j = ys; j < ye; j++) {
481 PetscReal expected = PeriodicScalarValue(1, j, k, 0.0);
482 PetscCall(PicurvAssertRealNear(expected + 2000.0, ucont[k][j][mx - 1].y, 1.0e-12,
483 "distributed Ucont.y positive X dummy"));
484 PetscCall(PicurvAssertRealNear(expected + 3000.0, ucont[k][j][mx - 1].z, 1.0e-12,
485 "distributed Ucont.z positive X dummy"));
486 }
487 }
488 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->Ucont, &ucont));
489
490 PetscCall(DMDAVecGetArrayRead(user->fda, user->lUcont, &ucont));
491 if (xs == 0) {
492 for (PetscInt k = zs; k < ze; k++) for (PetscInt j = ys; j < ye; j++) {
493 PetscCall(PicurvAssertRealNear(PeriodicScalarValue(mx - 3, j, k, 1000.0), ucont[k][j][-1].x, 1.0e-12,
494 "distributed Ucont.x negative adjacent ghost repair"));
495 PetscCall(PicurvAssertRealNear(PeriodicScalarValue(1, j, k, 2000.0), ucont[k][j][-1].y, 1.0e-12,
496 "distributed Ucont.y tangential X wraparound"));
497 }
498 }
499 if (xe == mx) {
500 for (PetscInt k = zs; k < ze; k++) for (PetscInt j = ys; j < ye; j++) {
501 PetscCall(PicurvAssertRealNear(PeriodicScalarValue(2, j, k, 1000.0), ucont[k][j][mx].x, 1.0e-12,
502 "distributed Ucont.x positive adjacent ghost repair"));
503 PetscCall(PicurvAssertRealNear(PeriodicScalarValue(mx - 2, j, k, 2000.0), ucont[k][j][mx].y, 1.0e-12,
504 "distributed Ucont.y positive tangential X wraparound"));
505 }
506 }
507 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lUcont, &ucont));
508
509 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
510 PetscFunctionReturn(0);
511}
512/**
513 * @brief A profiled function that takes a measurable time; the profiling macros name it by __func__.
514 */
515static PetscErrorCode ProfiledOnRankOneOnly(void)
516{
517 PetscLogDouble start = 0.0, now = 0.0;
518
519 PetscFunctionBeginUser;
521 /* Spin until the clock advances: a zero elapsed time ties both ranks and the maximum falls to rank 0. */
522 PetscCall(PetscTime(&start));
523 do PetscCall(PetscTime(&now)); while (now <= start);
525 PetscFunctionReturn(0);
526}
527
528/**
529 * @brief The final profiling summary reduces each function's total time over ranks.
530 *
531 * A function profiled on rank 1 only must reach rank 0's summary with its maximum on rank 1,
532 * its minimum (zero) on rank 0 and one call in total.
533 */
534static PetscErrorCode TestProfilingSummaryReducesOverRanks(void)
535{
536 SimCtx simCtx;
537 PetscMPIInt rank = 0, size = 1;
538 char tmpdir[PETSC_MAX_PATH_LEN], summary_path[PETSC_MAX_PATH_LEN + 64], line[1024];
539
540 PetscFunctionBeginUser;
541 PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank));
542 PetscCallMPI(MPI_Comm_size(PETSC_COMM_WORLD, &size));
543 PetscCall(PicurvAssertBool((PetscBool)(size >= 2), "the profiling summary test needs a second rank"));
544 PetscCall(PetscMemzero(&simCtx, sizeof(simCtx)));
545 if (rank == 0) PetscCall(PicurvMakeTempDir(tmpdir, sizeof(tmpdir)));
546 PetscCallMPI(MPI_Bcast(tmpdir, PETSC_MAX_PATH_LEN, MPI_CHAR, 0, PETSC_COMM_WORLD));
547 PetscCall(PetscStrncpy(simCtx.log_dir, tmpdir, sizeof(simCtx.log_dir)));
548 simCtx.rank = rank;
550 simCtx.profilingFinalSummary = PETSC_TRUE;
551
552 if (rank == 1) PetscCall(ProfiledOnRankOneOnly());
553 PetscCall(ProfilingFinalize(&simCtx));
554
555 if (rank == 0) {
556 PetscBool found = PETSC_FALSE;
557 FILE *f;
558 PetscCall(PetscSNPrintf(summary_path, sizeof(summary_path), "%s/ProfilingSummary_Solver.csv", tmpdir));
559 f = fopen(summary_path, "r");
560 PetscCheck(f, PETSC_COMM_SELF, PETSC_ERR_FILE_OPEN, "Cannot open %s", summary_path);
561 while (fgets(line, sizeof(line), f)) {
562 char name[256];
563 double max_time, mean_time, min_time;
564 int max_rank, min_rank;
565 long long calls;
566 double avg_ms, min_calls, max_calls;
567 int min_calls_rank, max_calls_rank;
568 if (sscanf(line, "picurv,%255[^,],%lf,%d,%lf,%lf,%d,%lld,%lf,%lf,%d,%lf,%d", name, &max_time,
569 &max_rank, &mean_time, &min_time, &min_rank, &calls, &avg_ms, &min_calls, &min_calls_rank,
570 &max_calls, &max_calls_rank) == 12 && strcmp(name, "ProfiledOnRankOneOnly") == 0) {
571 found = PETSC_TRUE;
572 PetscCall(PicurvAssertIntEqual(1, max_rank, "the maximum should come from the rank that profiled it"));
573 PetscCall(PicurvAssertIntEqual(0, min_rank, "the minimum should come from the rank that did not"));
574 PetscCall(PicurvAssertRealNear(0.0, min_time, 0.0, "a rank that never called it contributes zero time"));
575 PetscCall(PicurvAssertIntEqual(1, (PetscInt)calls, "calls should be summed over ranks"));
576 PetscCall(PicurvAssertIntEqual(0, (PetscInt)min_calls, "the fewest calls per rank should be the uncalled rank's zero"));
577 PetscCall(PicurvAssertIntEqual(0, min_calls_rank, "the fewest calls should come from rank 0"));
578 PetscCall(PicurvAssertIntEqual(1, (PetscInt)max_calls, "the most calls per rank should be rank 1's one"));
579 PetscCall(PicurvAssertIntEqual(1, max_calls_rank, "the most calls should come from rank 1"));
580 }
581 }
582 fclose(f);
583 PetscCall(PicurvAssertBool(found, "the summary should list a function profiled on another rank"));
584 PetscCall(PicurvRemoveTempDir(tmpdir));
585 }
586 PetscFunctionReturn(0);
587}
588/**
589 * @brief The per-axis owner lookup agrees with a scan of every rank's cell ranges.
590 *
591 * Checks every cell of the grid, plus cells just outside each face, which have no owner.
592 */
593static PetscErrorCode TestFindOwnerOfCellMatchesRankRanges(void)
594{
595 SimCtx *simCtx = NULL;
596 UserCtx *user = NULL;
597 PetscMPIInt size = 1;
598
599 PetscFunctionBeginUser;
600 PetscCallMPI(MPI_Comm_size(PETSC_COMM_WORLD, &size));
601 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 8, 6, 4));
602 PetscCall(SetupDomainCellDecompositionMap(user));
603
604 for (PetscInt k = -1; k <= user->KM - 1; ++k) {
605 for (PetscInt j = -1; j <= user->JM - 1; ++j) {
606 for (PetscInt i = -1; i <= user->IM - 1; ++i) {
607 PetscMPIInt owner, expected = -1;
608 for (PetscMPIInt r = 0; r < size; ++r) {
609 const RankCellInfo *info = &user->RankCellInfoMap[r];
610 if (i >= info->xs_cell && i < info->xs_cell + info->xm_cell &&
611 j >= info->ys_cell && j < info->ys_cell + info->ym_cell &&
612 k >= info->zs_cell && k < info->zs_cell + info->zm_cell) expected = r;
613 }
614 PetscCall(FindOwnerOfCell(user, i, j, k, &owner));
615 PetscCall(PicurvAssertIntEqual(expected, owner, "owner lookup should match the rank cell ranges"));
616 }
617 }
618 }
619
620 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
621 PetscFunctionReturn(0);
622}
623/**
624 * @brief Tests restart fast-path migration using preloaded cell ownership metadata.
625 */
626
628{
629 SimCtx *simCtx = NULL;
630 UserCtx *user = NULL;
631 PetscMPIInt rank = 0, size = 1;
632 PetscInt *cell_ids = NULL;
633 PetscReal *positions = NULL;
634 PetscInt nlocal = 0;
635
636 PetscFunctionBeginUser;
637 PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank));
638 PetscCallMPI(MPI_Comm_size(PETSC_COMM_WORLD, &size));
639 /* Two ranks only: it places particles on rank 0 for rank 1 to own. */
640 if (size != 2) {
641 PetscCall(PetscPrintf(PETSC_COMM_WORLD, " [SKIP] needs exactly two ranks\n"));
642 PetscFunctionReturn(0);
643 }
644
645 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 8, 4, 4));
646 PetscCall(PicurvCreateSwarmPair(user, 1, "ske"));
647 PetscCall(SetupDomainCellDecompositionMap(user));
648
649 PetscCall(DMSwarmGetField(user->swarm, "DMSwarm_CellID", NULL, NULL, (void **)&cell_ids));
650 PetscCall(DMSwarmGetField(user->swarm, "position", NULL, NULL, (void **)&positions));
651 if (rank == 0) {
652 cell_ids[0] = user->RankCellInfoMap[1].xs_cell;
653 cell_ids[1] = user->RankCellInfoMap[1].ys_cell;
654 cell_ids[2] = user->RankCellInfoMap[1].zs_cell;
655 positions[0] = 0.875;
656 positions[1] = 0.5;
657 positions[2] = 0.5;
658 } else {
659 cell_ids[0] = user->RankCellInfoMap[1].xs_cell;
660 cell_ids[1] = user->RankCellInfoMap[1].ys_cell;
661 cell_ids[2] = user->RankCellInfoMap[1].zs_cell;
662 positions[0] = 0.95;
663 positions[1] = 0.5;
664 positions[2] = 0.5;
665 }
666 PetscCall(DMSwarmRestoreField(user->swarm, "position", NULL, NULL, (void **)&positions));
667 PetscCall(DMSwarmRestoreField(user->swarm, "DMSwarm_CellID", NULL, NULL, (void **)&cell_ids));
668
669 PetscCall(MigrateRestartParticlesUsingCellID(user));
670 PetscCall(DMSwarmGetLocalSize(user->swarm, &nlocal));
671 PetscCall(PicurvAssertIntEqual((rank == 0) ? 0 : 2, nlocal,
672 "restart migration should move the foreign particle onto the owning rank"));
673
674 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
675 PetscFunctionReturn(0);
676}
677/**
678 * @brief A particle that left the domain is classified once and never re-searched in later passes.
679 *
680 * Rank 0 holds one particle beyond the -Xi face and one that has moved into rank 1, so the
681 * settlement needs a second pass. The leaving particle must end EXITED after pass 1 and be
682 * skipped afterwards: re-searching it is what used to count it as lost once per pass and, on
683 * curved boundaries, migrate it between ranks until the pass limit aborted the run.
684 */
686{
687 SimCtx *simCtx = NULL;
688 UserCtx *user = NULL;
689 PetscMPIInt rank = 0, size = 1;
690 PetscInt *cell_ids = NULL, *status = NULL;
691 PetscReal *positions = NULL;
692 PetscInt nlocal = 0;
693 PetscInt64 local_counts[2], global_counts[2];
694
695 PetscFunctionBeginUser;
696 PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank));
697 PetscCallMPI(MPI_Comm_size(PETSC_COMM_WORLD, &size));
698 /* Two ranks only: it moves a particle from rank 0 to rank 1. */
699 if (size != 2) {
700 PetscCall(PetscPrintf(PETSC_COMM_WORLD, " [SKIP] needs exactly two ranks\n"));
701 PetscFunctionReturn(0);
702 }
703
704 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 8, 4, 4));
705 PetscCall(PicurvCreateSwarmPair(user, (rank == 0) ? 2 : 0, "ske"));
706 PetscCall(SetupDomainCellDecompositionMap(user));
707
708 if (rank == 0) {
709 PetscCall(DMSwarmGetField(user->swarm, "DMSwarm_CellID", NULL, NULL, (void **)&cell_ids));
710 PetscCall(DMSwarmGetField(user->swarm, "position", NULL, NULL, (void **)&positions));
711 PetscCall(DMSwarmGetField(user->swarm, "DMSwarm_location_status", NULL, NULL, (void **)&status));
712 /* Particle 0 left through -Xi from boundary cell (0,1,1), well inside the blocked-walk guard. */
713 cell_ids[0] = 0; cell_ids[1] = 1; cell_ids[2] = 1;
714 positions[0] = -0.05; positions[1] = 0.5; positions[2] = 0.5;
715 /* Particle 1 moved from rank 0's last owned cell into rank 1's subdomain. */
716 cell_ids[3] = user->RankCellInfoMap[rank].xs_cell + user->RankCellInfoMap[rank].xm_cell - 1; cell_ids[4] = 1; cell_ids[5] = 1;
717 positions[3] = 0.875; positions[4] = 0.5; positions[5] = 0.5;
718 status[0] = NEEDS_LOCATION;
719 status[1] = NEEDS_LOCATION;
720 PetscCall(DMSwarmRestoreField(user->swarm, "DMSwarm_location_status", NULL, NULL, (void **)&status));
721 PetscCall(DMSwarmRestoreField(user->swarm, "position", NULL, NULL, (void **)&positions));
722 PetscCall(DMSwarmRestoreField(user->swarm, "DMSwarm_CellID", NULL, NULL, (void **)&cell_ids));
723 }
724
725 PetscCall(LocateAllParticlesInGrid(user, simCtx->bboxlist));
726
728 "one migration and one confirming pass should settle both particles"));
729 PetscCall(DMSwarmGetLocalSize(user->swarm, &nlocal));
730 PetscCall(PicurvAssertIntEqual(1, nlocal, "each rank should hold one particle after settlement"));
731 PetscCall(DMSwarmGetField(user->swarm, "DMSwarm_location_status", NULL, NULL, (void **)&status));
732 PetscCall(PicurvAssertIntEqual((rank == 0) ? EXITED : ACTIVE_AND_LOCATED, status[0],
733 "the leaving particle should be EXITED and the migrated one located"));
734 PetscCall(DMSwarmRestoreField(user->swarm, "DMSwarm_location_status", NULL, NULL, (void **)&status));
735
736 local_counts[0] = simCtx->searchMetrics.searchExitedCount;
737 local_counts[1] = simCtx->searchMetrics.searchLostCount;
738 PetscCallMPI(MPI_Allreduce(local_counts, global_counts, 2, MPIU_INT64, MPI_SUM, PETSC_COMM_WORLD));
739 PetscCall(PicurvAssertIntEqual(1, (PetscInt)global_counts[0], "the exit should be counted once, not once per pass"));
740 PetscCall(PicurvAssertIntEqual(0, (PetscInt)global_counts[1], "no search failed"));
741
742 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
743 PetscFunctionReturn(0);
744}
745/**
746 * @brief Spatial target domains must not depend on how ranks divide the block.
747 *
748 * The global point count is a function of layout, global dimensions, and
749 * periodicity alone. Summing the per-rank counts must therefore reproduce the
750 * same analytic totals a single rank computes, with no point counted twice at a
751 * decomposition seam and none dropped.
752 */
754{
755 SimCtx *simCtx = NULL;
756 UserCtx *user = NULL;
758 PetscInt local = 0, global = 0, rank_count = 0;
759 PetscMPIInt size = 0;
760 const PetscInt n = 6; /* DMDA is n + 1 = 7 per dimension */
761 const PetscInt cell = 5; /* cell-like span [1, 6) */
762 const PetscInt node = 6; /* node-like nonperiodic span [0, 6) */
763
764 PetscFunctionBeginUser;
765 PetscCallMPI(MPI_Comm_size(PETSC_COMM_WORLD, &size));
766 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, n, n, n));
767
769 PetscCall(SpatialTargetPlanLocalPointCount(&plan, &local));
770 PetscCall(SpatialTargetPlanGlobalPointCount(&plan, PETSC_COMM_WORLD, &global));
771 PetscCall(PicurvAssertIntEqual(cell * cell * cell, global,
772 "cell-centered global count must be decomposition independent"));
773
774 /* Every rank must contribute a non-negative count, and the ranks together
775 * must contribute the whole domain exactly once. */
776 PetscCall(PicurvAssertBool((PetscBool)(local >= 0), "local point count must be non-negative"));
777 PetscCallMPI(MPI_Allreduce(&local, &rank_count, 1, MPIU_INT, MPI_SUM, PETSC_COMM_WORLD));
778 PetscCall(PicurvAssertIntEqual(global, rank_count,
779 "summed local counts must equal the reduced global count"));
780
782 PetscCall(SpatialTargetPlanGlobalPointCount(&plan, PETSC_COMM_WORLD, &global));
783 PetscCall(PicurvAssertIntEqual(node * cell * cell, global,
784 "I-face global count must be decomposition independent"));
785
787 PetscCall(SpatialTargetPlanGlobalPointCount(&plan, PETSC_COMM_WORLD, &global));
788 PetscCall(PicurvAssertIntEqual(node * node * node, global,
789 "node-centered global count must be decomposition independent"));
790
791 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
792
793 /* Fully periodic: duplicate planes must be dropped once globally, not once per rank. */
794 PetscCall(PicurvCreateMinimalContextsWithPeriodicity(&simCtx, &user, n, n, n,
795 PETSC_TRUE, PETSC_TRUE, PETSC_TRUE));
797 PetscCall(SpatialTargetPlanGlobalPointCount(&plan, PETSC_COMM_WORLD, &global));
798 PetscCall(PicurvAssertIntEqual(cell * cell * cell, global,
799 "fully periodic node-centered count must drop duplicates exactly once"));
800 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
801 PetscFunctionReturn(0);
802}
803
804/**
805 * @brief Statistics payloads must survive a checkpoint round trip under decomposition.
806 *
807 * The write path gathers each accumulator into natural ordering before it reaches
808 * disk, and the read path scatters it back. That pairing is where a decomposition
809 * bug would live, so this drives the whole cycle on more than one rank and requires
810 * an exact match: the format stores IEEE doubles, and natural ordering is defined
811 * to be independent of how ranks divide the block.
812 */
814{
815 SimCtx *simCtx = NULL;
816 UserCtx *user = NULL;
817 PicurvWindow window;
818 PicurvWindowStorage storage;
819 PicurvWindowDefinition definition;
820 Vec *reference = NULL;
821 char tmpdir[PETSC_MAX_PATH_LEN];
822 PetscInt payload_count = 0;
823 PetscMPIInt size = 0;
824
825 PetscFunctionBeginUser;
826 PetscCallMPI(MPI_Comm_size(PETSC_COMM_WORLD, &size));
827 PetscCall(PicurvAssertBool((PetscBool)(size >= 2), "unit-mpi requires at least two MPI ranks"));
828
829 memset(&definition, 0, sizeof(definition));
830 strncpy(definition.name, "production", PICURV_WINDOW_NAME_LENGTH - 1);
833 definition.step_cadence = 1;
834 /* Psi is particle-sampled, so the window also carries the occupied sample set and
835 * Ucat's occupied-state mean for the Ucat-Psi pair; every payload must round-trip. */
836 definition.field_count = 3;
837 definition.fields[0].field_id = FIELD_ID_UCAT; definition.fields[0].want_second = PETSC_TRUE;
838 definition.fields[1].field_id = FIELD_ID_P; definition.fields[1].want_second = PETSC_TRUE;
839 definition.fields[2].field_id = FIELD_ID_PSI; definition.fields[2].want_second = PETSC_TRUE;
840 definition.covariance_count = 2;
841 definition.covariances[0].first = FIELD_ID_UCAT;
842 definition.covariances[0].second = FIELD_ID_P;
843 definition.covariances[1].first = FIELD_ID_UCAT;
844 definition.covariances[1].second = FIELD_ID_PSI;
845
846 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 6, 6, 6));
847 tmpdir[0] = '\0';
848 if (simCtx->rank == 0) PetscCall(PicurvMakeTempDir(tmpdir, sizeof(tmpdir)));
849 PetscCallMPI(MPI_Bcast(tmpdir, sizeof(tmpdir), MPI_CHAR, 0, PETSC_COMM_WORLD));
850 PetscCall(PetscStrncpy(simCtx->output_dir, tmpdir, sizeof(simCtx->output_dir)));
851 PetscCall(PetscStrncpy(simCtx->restart_dir, tmpdir, sizeof(simCtx->restart_dir)));
852 PetscCall(PicurvPopulateIdentityMetrics(user));
853 PetscCall(VecSet(user->Nvert, 0.0));
854
855 PetscCall(PicurvWindowInit(&window, &definition));
856 PetscCall(PicurvWindowStorageCreate(user, &definition, &storage));
857 simCtx->fieldStatisticsEnabled = PETSC_TRUE;
858 simCtx->fieldStatisticsWindowCount = 1;
859 simCtx->fieldStatisticsWindows = &window;
860 user->fieldStatisticsStorage = &storage;
861
862 /* A spatially varying field makes the assertion meaningful: a payload gathered
863 * or scattered through the wrong owner comes back permuted, which a uniform
864 * field could not reveal. */
865 for (PetscInt s = 0; s < 4; ++s) {
866 PetscBool accepted = PETSC_FALSE;
867 PetscReal weight = 0.0;
868 PetscReal ***p = NULL, ***psi = NULL, ***particles = NULL;
869 Cmpnts ***ucat = NULL;
870 const DMDALocalInfo info = user->info;
871
872 PetscCall(DMDAVecGetArray(user->da, user->P, &p));
873 PetscCall(DMDAVecGetArray(user->da, user->Psi, &psi));
874 PetscCall(DMDAVecGetArray(user->da, user->ParticleCount, &particles));
875 PetscCall(DMDAVecGetArray(user->fda, user->Ucat, &ucat));
876 for (PetscInt k = info.zs; k < info.zs + info.zm; ++k)
877 for (PetscInt j = info.ys; j < info.ys + info.ym; ++j)
878 for (PetscInt i = info.xs; i < info.xs + info.xm; ++i) {
879 const PetscReal tag = (PetscReal)(100 * k + 10 * j + i);
880
881 p[k][j][i] = tag + 0.25 * (PetscReal)s;
882 /* Occupancy varies with both the point and the state. */
883 particles[k][j][i] = ((i + j + k + s) % 3) ? 2.0 : 0.0;
884 psi[k][j][i] = 0.01 * tag + (PetscReal)s;
885 ucat[k][j][i].x = tag;
886 ucat[k][j][i].y = tag + 1.0 + (PetscReal)s;
887 ucat[k][j][i].z = tag - 1.0;
888 }
889 PetscCall(DMDAVecRestoreArray(user->fda, user->Ucat, &ucat));
890 PetscCall(DMDAVecRestoreArray(user->da, user->ParticleCount, &particles));
891 PetscCall(DMDAVecRestoreArray(user->da, user->Psi, &psi));
892 PetscCall(DMDAVecRestoreArray(user->da, user->P, &p));
893
894 PetscCall(PicurvWindowOfferState(&window, s, 0.5 * (PetscReal)s, &accepted, &weight));
895 if (accepted) PetscCall(PicurvWindowAccumulate(user, &definition, &storage, weight));
896 }
897 PetscCall(PicurvAssertIntEqual(3, window.sample_count, "three intervals are represented"));
898
899 PetscCall(WriteCheckpointBundle(simCtx, "test"));
900
901 PetscCall(PicurvWindowStoragePayloadCount(&storage, &payload_count));
902 /* Six occupancy vectors, three means, Ucat's occupied-state mean, three second
903 * moments and two co-moments. */
904 PetscCall(PicurvAssertIntEqual(15, payload_count, "the occupied sample set adds its own payloads"));
905 PetscCall(PetscCalloc1((size_t)payload_count, &reference));
906 for (PetscInt index = 0; index < payload_count; ++index) {
908
909 PetscCall(PicurvWindowStoragePayload(user, &definition, &storage, index, &payload));
910 PetscCall(VecDuplicate(payload.vec, &reference[index]));
911 PetscCall(VecCopy(payload.vec, reference[index]));
912 PetscCall(VecZeroEntries(payload.vec));
913 }
914 PetscCall(PicurvWindowInit(&window, &definition));
915
916 simCtx->fieldStatisticsContinue = PETSC_TRUE;
917 PetscCall(RestoreFieldStatisticsState(simCtx, simCtx->step));
918 PetscCall(PicurvAssertIntEqual(3, window.sample_count, "window bookkeeping survives on every rank"));
919 PetscCall(PicurvAssertRealNear(1.5, window.total_weight, 1.0e-12,
920 "physical-time weights survive on every rank"));
921
922 for (PetscInt index = 0; index < payload_count; ++index) {
924 PetscReal difference = 0.0;
925 char context[192];
926
927 PetscCall(PicurvWindowStoragePayload(user, &definition, &storage, index, &payload));
928 PetscCall(VecAXPY(reference[index], -1.0, payload.vec));
929 PetscCall(VecNorm(reference[index], NORM_INFINITY, &difference));
930 PetscCall(PetscSNPrintf(context, sizeof(context),
931 "payload '%s' round trips exactly across %d ranks",
932 payload.name, (int)size));
933 PetscCall(PicurvAssertBool((PetscBool)(difference == 0.0), context));
934 PetscCall(VecDestroy(&reference[index]));
935 }
936 PetscCall(PetscFree(reference));
937
938 PetscCallMPI(MPI_Barrier(PETSC_COMM_WORLD));
939 if (simCtx->rank == 0) PetscCall(PicurvRemoveTempDir(tmpdir));
940 PetscCallMPI(MPI_Barrier(PETSC_COMM_WORLD));
941 simCtx->fieldStatisticsEnabled = PETSC_FALSE;
942 simCtx->fieldStatisticsWindowCount = 0;
943 simCtx->fieldStatisticsWindows = NULL;
944 user->fieldStatisticsStorage = NULL;
945 PetscCall(PicurvWindowStorageDestroy(&storage));
946 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
947 PetscFunctionReturn(0);
948}
949
950/**
951 * @brief Tests that LES coefficient averaging does not depend on the decomposition.
952 *
953 * The averaged coefficient is a physical property of the block, so splitting the same
954 * field across more ranks must not change it. This case catches a wrong communicator,
955 * a halo entry counted as if it were owned, or a layout boundary plane included in one
956 * decomposition but not another. The reference is computed from the analytic
957 * definition over the interior index box rather than from a single-rank run, so the
958 * test does not merely compare one decomposition against itself.
959 */
961{
962 SimCtx *simCtx = NULL;
963 UserCtx *user = NULL;
964 Vec numerator, denominator, ratio;
966 PetscReal ***num = NULL, ***den = NULL, ***out = NULL;
967 DMDALocalInfo info;
968 PetscInt xs, xe, ys, ye, zs, ze;
969 PetscReal sampled = 0.0;
970 PetscReal numerator_total = 0.0, denominator_total = 0.0;
971 const PetscBool all[3] = {PETSC_TRUE, PETSC_TRUE, PETSC_TRUE};
972
973 PetscFunctionBeginUser;
974 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 8, 8, 8));
975 PetscCall(DMDAGetLocalInfo(user->da, &info));
976 PetscCall(VecSet(user->lNvert, 0.0));
977 PetscCall(VecSet(user->lAj, 1.0));
978
979 xs = (info.xs == 0) ? 1 : info.xs;
980 ys = (info.ys == 0) ? 1 : info.ys;
981 zs = (info.zs == 0) ? 1 : info.zs;
982 xe = (info.xs + info.xm == info.mx) ? info.mx - 1 : info.xs + info.xm;
983 ye = (info.ys + info.ym == info.my) ? info.my - 1 : info.ys + info.ym;
984 ze = (info.zs + info.zm == info.mz) ? info.mz - 1 : info.zs + info.zm;
985
986 PetscCall(VecDuplicate(user->lNvert, &numerator));
987 PetscCall(VecDuplicate(user->lNvert, &denominator));
988 PetscCall(VecDuplicate(user->lNvert, &ratio));
989 PetscCall(VecSet(numerator, 0.0));
990 PetscCall(VecSet(denominator, 0.0));
991 PetscCall(VecSet(ratio, 0.0));
992
993 /* Each rank writes only the cells it owns, from a closed-form function of the
994 global indices, so the distributed sums are exactly the serial ones below. */
995 PetscCall(DMDAVecGetArray(user->da, numerator, &num));
996 PetscCall(DMDAVecGetArray(user->da, denominator, &den));
997 for (PetscInt k = zs; k < ze; ++k)
998 for (PetscInt j = ys; j < ye; ++j)
999 for (PetscInt i = xs; i < xe; ++i) {
1000 num[k][j][i] = (PetscReal)(i * j + k);
1001 den[k][j][i] = (PetscReal)(i + 1);
1002 }
1003 PetscCall(DMDAVecRestoreArray(user->da, numerator, &num));
1004 PetscCall(DMDAVecRestoreArray(user->da, denominator, &den));
1005
1006 PetscCall(SpatialTargetPlanCreate(user, FIELD_ID_CS,
1008 PetscCall(PicurvSpatialRatioAverage(user, &plan, numerator, denominator, NULL, all,
1009 PETSC_COMM_WORLD, ratio, NULL));
1010
1011 for (PetscInt k = 1; k < info.mz - 1; ++k)
1012 for (PetscInt j = 1; j < info.my - 1; ++j)
1013 for (PetscInt i = 1; i < info.mx - 1; ++i) {
1014 numerator_total += (PetscReal)(i * j + k);
1015 denominator_total += (PetscReal)(i + 1);
1016 }
1017
1018 PetscCall(DMDAVecGetArray(user->da, ratio, &out));
1019 sampled = out[zs][ys][xs];
1020 PetscCall(DMDAVecRestoreArray(user->da, ratio, &out));
1021
1022 PetscCall(PicurvAssertRealNear(numerator_total / denominator_total, sampled, 1.0e-10,
1023 "the globally averaged ratio must match the serial sums "
1024 "however the block is decomposed"));
1025
1026 PetscCall(VecDestroy(&numerator));
1027 PetscCall(VecDestroy(&denominator));
1028 PetscCall(VecDestroy(&ratio));
1029 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
1030 PetscFunctionReturn(0);
1031}
1032
1033/**
1034 * @brief Tests that injection follows the flux, is keyed on the grid, and carries no state.
1035 * @details An empty domain, with a different flux through each inlet face cell and outflow through
1036 * every third. The global count and identities are computed from the formula over all
1037 * face cells, so they hold whatever the decomposition. Each particle carries the value
1038 * at the face, sits within u dt of it, awaits location, and a second call for the same
1039 * step reproduces the first. With a diffusivity, each particle moves further by exactly
1040 * its own keyed Brownian displacement for the step.
1041 */
1043{
1044 const char *options = "-particle_inlet_count 1\n"
1045 "-particle_inlet_0_face 4\n"
1046 "-particle_inlet_0_particles_per_cell \"16.0 + 0*t\"\n"
1047 "-particle_inlet_0_fields_count 1\n"
1048 "-particle_inlet_0_fields_0_name Psi\n"
1049 "-particle_inlet_0_fields_0_expr_0 \"z + 1\"\n";
1050 SimCtx *simCtx = NULL;
1051 UserCtx *user = NULL;
1052 char tmpdir[PETSC_MAX_PATH_LEN];
1053 Cmpnts ***ucont = NULL;
1054 PetscReal positions_first = 0.0, positions_second = 0.0;
1055
1056 PetscFunctionBeginUser;
1057 PetscCall(PicurvBuildTinyRuntimeContextWithOptions(NULL, PETSC_FALSE, options, &simCtx, &user, tmpdir, sizeof(tmpdir)));
1058 PetscCall(PicurvAssertBool((PetscBool)(simCtx->np == 0 && ParticlesEnabled(simCtx)), "an inlet enables particles in an empty domain"));
1059 PetscCall(InitializeEulerianState(simCtx));
1060 PetscCall(InitializeParticleSwarm(simCtx));
1061
1062 const PetscInt nx = user->info.mx - 2, ny = user->info.my - 2, nz = user->info.mz - 2;
1063 const PetscInt64 faces = 2 * ((PetscInt64)nx * ny + (PetscInt64)ny * nz + (PetscInt64)nz * nx);
1064 const PetscInt64 face_start = 2 * ((PetscInt64)ny * nz + (PetscInt64)nz * nx);
1065 const PetscReal L = simCtx->scaling.L_ref;
1066 simCtx->step = 3;
1067 simCtx->dt = 0.1;
1068
1069 /* A flux per face cell that the decomposition cannot change: outflow through every third. */
1070#define TEST_INLET_FLUX(i_, j_) (((i_) % 3 == 0) ? -0.01 : 0.002 * ((i_) + 2 * (j_)))
1071 PetscCall(VecSet(user->lUcont, 0.0));
1072 PetscCall(DMDAVecGetArray(user->fda, user->lUcont, &ucont));
1073 if (user->info.gzs <= 0) {
1074 for (PetscInt j = user->info.gys; j < user->info.gys + user->info.gym; ++j)
1075 for (PetscInt i = user->info.gxs; i < user->info.gxs + user->info.gxm; ++i) {
1076 ucont[0][j][i].z = TEST_INLET_FLUX(i, j);
1077 }
1078 }
1079 PetscCall(DMDAVecRestoreArray(user->fda, user->lUcont, &ucont));
1080
1081 PetscInt64 expected_count = 0, expected_pid_sum = 0;
1082 for (PetscInt j = 1; j <= ny; ++j)
1083 for (PetscInt i = 1; i <= nx; ++i) {
1084 const PetscInt64 id = simCtx->step * faces + face_start + (i - 1) + (PetscInt64)nx * (j - 1);
1085 const PetscReal mean = PetscMax(TEST_INLET_FLUX(i, j), 0.0) * 16.0 * (PetscReal)(nx * ny * nz) * simCtx->dt; /* a unit box */
1086 const PetscReal whole = PetscFloorReal(mean);
1087 const uint64_t hash = PicurvDrawHash((PetscInt64)simCtx->particleRandomSeed, PICURV_DRAW_SPACE_INLET, 0, id, 0);
1088 const PetscInt n = (PetscInt)whole + ((PicurvUnitFromHash(hash) < mean - whole) ? 1 : 0);
1089 for (PetscInt k = 0; k < n; ++k) expected_pid_sum += ((PetscInt64)1 << 40) + id * 1024 + k;
1090 expected_count += n;
1091 }
1092 PetscCall(PicurvAssertBool((PetscBool)(expected_count > 0), "the fixture must inject something"));
1093
1094 for (PetscInt pass = 0; pass < 2; ++pass) {
1095 PetscInt nlocal = 0, nglobal = 0;
1096 PetscInt64 pid_sum = 0;
1097 PetscReal position_sum = 0.0;
1098 const PetscReal *position = NULL, *psi = NULL;
1099 const PetscInt64 *pid = NULL;
1100 const PetscInt *status = NULL;
1101
1102 PetscCall(DMSwarmSetLocalSizes(user->swarm, 0, -1));
1103 PetscCall(InjectParticlesAtInlets(user));
1104 PetscCall(DMSwarmGetLocalSize(user->swarm, &nlocal));
1105 PetscCall(DMSwarmGetSize(user->swarm, &nglobal));
1106 PetscCall(PicurvAssertIntEqual((PetscInt)expected_count, nglobal, "the count follows the flux through every face cell"));
1107 PetscCall(DMSwarmGetField(user->swarm, "position", NULL, NULL, (void **)&position));
1108 PetscCall(DMSwarmGetField(user->swarm, "Psi", NULL, NULL, (void **)&psi));
1109 PetscCall(DMSwarmGetField(user->swarm, "DMSwarm_pid", NULL, NULL, (void **)&pid));
1110 PetscCall(DMSwarmGetField(user->swarm, "DMSwarm_location_status", NULL, NULL, (void **)&status));
1111 for (PetscInt p = 0; p < nlocal; ++p) {
1112 PetscCall(PicurvAssertBool((PetscBool)(status[p] == NEEDS_LOCATION), "a new particle awaits location"));
1113 PetscCall(PicurvAssertBool((PetscBool)(position[3 * p + 2] > user->Min_Z), "a new particle is inside the inlet"));
1114 /* The value was set on the face, before the particle moved in. */
1115 PetscCall(PicurvAssertRealNear(user->Min_Z * L + 1.0, psi[p], 1.0e-3, "a new particle carries the value at the face"));
1116 pid_sum += pid[p];
1117 position_sum += position[3 * p] + 2.0 * position[3 * p + 1] + 3.0 * position[3 * p + 2];
1118 }
1119 PetscCall(DMSwarmRestoreField(user->swarm, "DMSwarm_location_status", NULL, NULL, (void **)&status));
1120 PetscCall(DMSwarmRestoreField(user->swarm, "DMSwarm_pid", NULL, NULL, (void **)&pid));
1121 PetscCall(DMSwarmRestoreField(user->swarm, "Psi", NULL, NULL, (void **)&psi));
1122 PetscCall(DMSwarmRestoreField(user->swarm, "position", NULL, NULL, (void **)&position));
1123 PetscCallMPI(MPI_Allreduce(MPI_IN_PLACE, &pid_sum, 1, MPIU_INT64, MPI_SUM, PETSC_COMM_WORLD));
1124 PetscCallMPI(MPI_Allreduce(MPI_IN_PLACE, &position_sum, 1, MPIU_REAL, MPI_SUM, PETSC_COMM_WORLD));
1125 PetscCall(PicurvAssertBool((PetscBool)(pid_sum == expected_pid_sum), "identities come from the grid position, the step and the count"));
1126 if (pass == 0) positions_first = position_sum; else positions_second = position_sum;
1127 }
1128 PetscCall(PicurvAssertRealNear(positions_first, positions_second, 1.0e-9, "injection carries no state from one call to the next"));
1129#undef TEST_INLET_FLUX
1130
1131 {
1132 const PetscReal diffusivity = 0.5;
1133 PetscInt nlocal = 0;
1134 PetscReal *without_kick = NULL;
1135 const PetscReal *position = NULL;
1136 const PetscInt64 *pid = NULL;
1137
1138 PetscCall(DMSwarmGetLocalSize(user->swarm, &nlocal));
1139 PetscCall(PetscMalloc1(3 * nlocal, &without_kick));
1140 PetscCall(DMSwarmGetField(user->swarm, "position", NULL, NULL, (void **)&position));
1141 PetscCall(PetscArraycpy(without_kick, position, 3 * nlocal));
1142 PetscCall(DMSwarmRestoreField(user->swarm, "position", NULL, NULL, (void **)&position));
1143
1144 PetscCall(VecSet(user->lDiffusivity, diffusivity));
1145 PetscCall(DMSwarmSetLocalSizes(user->swarm, 0, -1));
1146 PetscCall(InjectParticlesAtInlets(user));
1147 PetscCall(DMSwarmGetField(user->swarm, "position", NULL, NULL, (void **)&position));
1148 PetscCall(DMSwarmGetField(user->swarm, "DMSwarm_pid", NULL, NULL, (void **)&pid));
1149 for (PetscInt p = 0; p < nlocal; ++p) {
1150 Cmpnts kick;
1151
1152 PetscCall(CalculateBrownianDisplacement(user, pid[p], diffusivity, &kick));
1153 PetscCall(PicurvAssertRealNear(without_kick[3 * p + 0] + kick.x, position[3 * p + 0], 1.0e-12, "a new particle takes the step's Brownian displacement in x"));
1154 PetscCall(PicurvAssertRealNear(without_kick[3 * p + 1] + kick.y, position[3 * p + 1], 1.0e-12, "a new particle takes the step's Brownian displacement in y"));
1155 PetscCall(PicurvAssertRealNear(without_kick[3 * p + 2] + kick.z, position[3 * p + 2], 1.0e-12, "a new particle takes the step's Brownian displacement in z"));
1156 }
1157 PetscCall(DMSwarmRestoreField(user->swarm, "DMSwarm_pid", NULL, NULL, (void **)&pid));
1158 PetscCall(DMSwarmRestoreField(user->swarm, "position", NULL, NULL, (void **)&position));
1159 PetscCall(PetscFree(without_kick));
1160 }
1161
1162 PetscCall(PicurvDestroyRuntimeContext(&simCtx));
1163 PetscCall(PicurvRemoveTempDir(tmpdir));
1164 PetscFunctionReturn(0);
1165}
1166
1167/**
1168 * @brief Checks that IEM's linear reconstruction holds across subdomain seams.
1169 * @details Particles fill the box and carry Psi = 2 (x + y + z), so every cell's reconstruction
1170 * reproduces the line up to the noise of its gradient. A seam that hid a neighbour's
1171 * particles from the gradient would leave the cells beside it relaxing toward their
1172 * stepped mean, as far from the line as the stepped mean leaves every cell. Each cell's
1173 * particles are on its owner rank, so the stepped reference is computed there.
1174 */
1175static PetscErrorCode TestIEMReconstructionAcrossSeams(void)
1176{
1177 const char *options = "-numParticles 5000\n-pinit 1\n"
1178 "-particle_fields_count 1\n"
1179 "-particle_fields_0_name Psi\n"
1180 "-particle_fields_0_expr_0 \"2*(x + y + z)\"\n";
1181 SimCtx *simCtx = NULL;
1182 UserCtx *user = NULL;
1183 char tmpdir[PETSC_MAX_PATH_LEN];
1184 PetscInt nlocal = 0, *cell = NULL, ncells, cx_n[3];
1185 PetscReal *psi = NULL, *diffusivity = NULL, *pos = NULL, *cx = NULL, *cn = NULL;
1186 PetscReal sums[4] = {0.0, 0.0, 0.0, 0.0}; /* sum before, sum after, squared departure from the line, the same for the stepped mean */
1187 PetscReal decay;
1188
1189 PetscFunctionBeginUser;
1190 PetscCall(PicurvBuildTinyRuntimeContextWithOptions(NULL, PETSC_TRUE, options, &simCtx, &user, tmpdir, sizeof(tmpdir)));
1191 PetscCall(InitializeEulerianState(simCtx));
1192 PetscCall(InitializeParticleSwarm(simCtx));
1193 PetscCall(PerformInitializedParticleSetup(simCtx));
1194 simCtx->dt = 0.5;
1195 cx_n[0] = user->info.mx - 2; cx_n[1] = user->info.my - 2; cx_n[2] = user->info.mz - 2;
1196 ncells = cx_n[0] * cx_n[1] * cx_n[2];
1197 decay = PetscExpReal(-simCtx->iem_constant * 0.2 * 0.5 / PetscPowReal(1.0 / (PetscReal)ncells, 0.6666667));
1198
1199 PetscCall(DMSwarmGetLocalSize(user->swarm, &nlocal));
1200 PetscCall(DMSwarmGetField(user->swarm, "Psi", NULL, NULL, (void **)&psi));
1201 PetscCall(DMSwarmGetField(user->swarm, "Diffusivity", NULL, NULL, (void **)&diffusivity));
1202 PetscCall(DMSwarmGetField(user->swarm, "position", NULL, NULL, (void **)&pos));
1203 PetscCall(DMSwarmGetField(user->swarm, "DMSwarm_CellID", NULL, NULL, (void **)&cell));
1204 PetscCall(PetscCalloc2(3 * ncells, &cx, ncells, &cn));
1205 for (PetscInt p = 0; p < nlocal; ++p) {
1206 const PetscInt c = cell[3*p] + cx_n[0] * (cell[3*p+1] + cx_n[1] * cell[3*p+2]);
1207 diffusivity[p] = 0.2;
1208 sums[0] += psi[p];
1209 for (PetscInt d = 0; d < 3; ++d) cx[3*c + d] += pos[3*p + d];
1210 cn[c] += 1.0;
1211 }
1212 PetscCall(DMSwarmRestoreField(user->swarm, "DMSwarm_CellID", NULL, NULL, (void **)&cell));
1213 PetscCall(DMSwarmRestoreField(user->swarm, "position", NULL, NULL, (void **)&pos));
1214 PetscCall(DMSwarmRestoreField(user->swarm, "Diffusivity", NULL, NULL, (void **)&diffusivity));
1215 PetscCall(DMSwarmRestoreField(user->swarm, "Psi", NULL, NULL, (void **)&psi));
1216
1217 PetscCall(UpdateAllParticleFields(user));
1218
1219 PetscCall(DMSwarmGetField(user->swarm, "Psi", NULL, NULL, (void **)&psi));
1220 PetscCall(DMSwarmGetField(user->swarm, "position", NULL, NULL, (void **)&pos));
1221 PetscCall(DMSwarmGetField(user->swarm, "DMSwarm_CellID", NULL, NULL, (void **)&cell));
1222 for (PetscInt p = 0; p < nlocal; ++p) {
1223 const PetscInt c = cell[3*p] + cx_n[0] * (cell[3*p+1] + cx_n[1] * cell[3*p+2]);
1224 const PetscReal line = 2.0 * (pos[3*p] + pos[3*p+1] + pos[3*p+2]);
1225 const PetscReal mean = 2.0 * (cx[3*c] + cx[3*c+1] + cx[3*c+2]) / cn[c];
1226 const PetscReal stepped = mean + (line - mean) * decay;
1227 sums[1] += psi[p];
1228 sums[2] += (psi[p] - line) * (psi[p] - line);
1229 sums[3] += (stepped - line) * (stepped - line);
1230 }
1231 PetscCall(DMSwarmRestoreField(user->swarm, "DMSwarm_CellID", NULL, NULL, (void **)&cell));
1232 PetscCall(DMSwarmRestoreField(user->swarm, "position", NULL, NULL, (void **)&pos));
1233 PetscCall(DMSwarmRestoreField(user->swarm, "Psi", NULL, NULL, (void **)&psi));
1234 PetscCall(PetscFree2(cx, cn));
1235 PetscCallMPI(MPI_Allreduce(MPI_IN_PLACE, sums, 4, MPIU_REAL, MPI_SUM, PETSC_COMM_WORLD));
1236
1237 PetscCall(PicurvAssertRealNear(sums[0], sums[1], 1.0e-9, "the reconstruction keeps every cell's scalar sum"));
1238 PetscCall(PicurvAssertBool((PetscBool)(sums[3] > 0.0 && sums[2] < 0.05 * sums[3]),
1239 "relaxing toward the reconstruction must keep a linear field close to its line in every subdomain"));
1240
1241 PetscCall(PicurvDestroyRuntimeContext(&simCtx));
1242 PetscCall(PicurvRemoveTempDir(tmpdir));
1243 PetscFunctionReturn(0);
1244}
1245
1246/**
1247 * @brief Runs one IEM update on a seeded box after setting each particle's Psi, rate and place.
1248 * @details The particles fill the tiny periodic box. `step_lo`/`step_hi` < 0 keep the linear field
1249 * 2 (x + y + z); otherwise Psi is `step_lo` below x = L/2 and `step_hi` above it.
1250 * `vary_rate` gives each particle a diffusivity 0.2 (1 + 0.8 (f - 1/2)), f its position
1251 * across its cell in x, so the relaxation rate differs between particles in one cell;
1252 * `crowd` moves every particle into the low quarter of its cell along each axis. Returns
1253 * the largest change of a cell's Psi total and the Psi extrema before and after.
1254 */
1255static PetscErrorCode RunIEMOnSeededBox(PetscReal step_lo, PetscReal step_hi, PetscBool vary_rate, PetscBool crowd,
1256 PetscReal *max_cell_change, PetscReal before[2], PetscReal after[2])
1257{
1258 const char *options = "-numParticles 20000\n-pinit 1\n"
1259 "-particle_fields_count 1\n"
1260 "-particle_fields_0_name Psi\n"
1261 "-particle_fields_0_expr_0 \"2*(x + y + z)\"\n";
1262 SimCtx *simCtx = NULL;
1263 UserCtx *user = NULL;
1264 char tmpdir[PETSC_MAX_PATH_LEN];
1265 PetscInt nlocal = 0, *cell = NULL, n[3], ncells;
1266 PetscReal *psi = NULL, *dif = NULL, *pos = NULL, *t0 = NULL, *t1 = NULL, L[3] = {0.0, 0.0, 0.0}, h[3];
1267
1268 PetscFunctionBeginUser;
1269 PetscCall(PicurvBuildTinyRuntimeContextWithOptions(NULL, PETSC_TRUE, options, &simCtx, &user, tmpdir, sizeof(tmpdir)));
1270 PetscCall(InitializeEulerianState(simCtx));
1271 PetscCall(InitializeParticleSwarm(simCtx));
1272 PetscCall(PerformInitializedParticleSetup(simCtx));
1273 simCtx->dt = 0.5;
1274 n[0] = user->info.mx - 2; n[1] = user->info.my - 2; n[2] = user->info.mz - 2;
1275 ncells = n[0] * n[1] * n[2];
1276 before[0] = after[0] = PETSC_MAX_REAL;
1277 before[1] = after[1] = PETSC_MIN_REAL;
1278
1279 PetscCall(DMSwarmGetLocalSize(user->swarm, &nlocal));
1280 PetscCall(DMSwarmGetField(user->swarm, "position", NULL, NULL, (void **)&pos));
1281 for (PetscInt p = 0; p < nlocal; ++p) for (PetscInt d = 0; d < 3; ++d) L[d] = PetscMax(L[d], pos[3*p+d]);
1282 PetscCallMPI(MPI_Allreduce(MPI_IN_PLACE, L, 3, MPIU_REAL, MPI_MAX, PETSC_COMM_WORLD));
1283 for (PetscInt d = 0; d < 3; ++d) { L[d] = PetscCeilReal(L[d] * 1.0e6) / 1.0e6; h[d] = L[d] / (PetscReal)n[d]; }
1284 PetscCall(DMSwarmGetField(user->swarm, "Psi", NULL, NULL, (void **)&psi));
1285 PetscCall(DMSwarmGetField(user->swarm, "Diffusivity", NULL, NULL, (void **)&dif));
1286 PetscCall(DMSwarmGetField(user->swarm, "DMSwarm_CellID", NULL, NULL, (void **)&cell));
1287 PetscCall(PetscCalloc2(ncells, &t0, ncells, &t1));
1288 for (PetscInt p = 0; p < nlocal; ++p) {
1289 PetscReal f = 0.0;
1290 for (PetscInt d = 0; d < 3; ++d) {
1291 const PetscReal lo = cell[3*p+d] * h[d];
1292 if (crowd) pos[3*p+d] = lo + 0.25 * (pos[3*p+d] - lo);
1293 if (d == 0) f = (pos[3*p] - lo) / h[0];
1294 }
1295 dif[p] = vary_rate ? 0.2 * (1.0 + 0.8 * (f - 0.5)) : 0.2;
1296 psi[p] = (step_lo < 0.0) ? 2.0 * (pos[3*p] + pos[3*p+1] + pos[3*p+2]) : ((pos[3*p] > 0.5 * L[0]) ? step_hi : step_lo);
1297 t0[cell[3*p] + n[0] * (cell[3*p+1] + n[1] * cell[3*p+2])] += psi[p];
1298 before[0] = PetscMin(before[0], psi[p]); before[1] = PetscMax(before[1], psi[p]);
1299 }
1300 PetscCall(DMSwarmRestoreField(user->swarm, "DMSwarm_CellID", NULL, NULL, (void **)&cell));
1301 PetscCall(DMSwarmRestoreField(user->swarm, "Diffusivity", NULL, NULL, (void **)&dif));
1302 PetscCall(DMSwarmRestoreField(user->swarm, "Psi", NULL, NULL, (void **)&psi));
1303 PetscCall(DMSwarmRestoreField(user->swarm, "position", NULL, NULL, (void **)&pos));
1304
1305 PetscCall(UpdateAllParticleFields(user));
1306
1307 PetscCall(DMSwarmGetField(user->swarm, "Psi", NULL, NULL, (void **)&psi));
1308 PetscCall(DMSwarmGetField(user->swarm, "DMSwarm_CellID", NULL, NULL, (void **)&cell));
1309 for (PetscInt p = 0; p < nlocal; ++p) {
1310 t1[cell[3*p] + n[0] * (cell[3*p+1] + n[1] * cell[3*p+2])] += psi[p];
1311 after[0] = PetscMin(after[0], psi[p]); after[1] = PetscMax(after[1], psi[p]);
1312 }
1313 PetscCall(DMSwarmRestoreField(user->swarm, "DMSwarm_CellID", NULL, NULL, (void **)&cell));
1314 PetscCall(DMSwarmRestoreField(user->swarm, "Psi", NULL, NULL, (void **)&psi));
1315 PetscCallMPI(MPI_Allreduce(MPI_IN_PLACE, t0, ncells, MPIU_REAL, MPI_SUM, PETSC_COMM_WORLD));
1316 PetscCallMPI(MPI_Allreduce(MPI_IN_PLACE, t1, ncells, MPIU_REAL, MPI_SUM, PETSC_COMM_WORLD));
1317 PetscCallMPI(MPI_Allreduce(MPI_IN_PLACE, &before[0], 1, MPIU_REAL, MPI_MIN, PETSC_COMM_WORLD));
1318 PetscCallMPI(MPI_Allreduce(MPI_IN_PLACE, &after[0], 1, MPIU_REAL, MPI_MIN, PETSC_COMM_WORLD));
1319 PetscCallMPI(MPI_Allreduce(MPI_IN_PLACE, &before[1], 1, MPIU_REAL, MPI_MAX, PETSC_COMM_WORLD));
1320 PetscCallMPI(MPI_Allreduce(MPI_IN_PLACE, &after[1], 1, MPIU_REAL, MPI_MAX, PETSC_COMM_WORLD));
1321 *max_cell_change = 0.0;
1322 for (PetscInt c = 0; c < ncells; ++c) *max_cell_change = PetscMax(*max_cell_change, PetscAbsReal(t1[c] - t0[c]));
1323 PetscCall(PetscFree2(t0, t1));
1324 PetscCall(PicurvDestroyRuntimeContext(&simCtx));
1325 PetscCall(PicurvRemoveTempDir(tmpdir));
1326 PetscFunctionReturn(0);
1327}
1328
1329/**
1330 * @brief IEM keeps every cell's Psi total when the particles in a cell relax at different rates.
1331 * @details Each particle relaxes with its own diffusivity, which varies across every cell here, on
1332 * a linear field. Only a target whose mean and centroid are weighted by the particles'
1333 * relaxation weights keeps the totals; an unweighted mean and centroid change them by up to
1334 * a few percent of a cell's total in one step.
1335 */
1337{
1338 PetscReal change = 0.0, before[2], after[2];
1339
1340 PetscFunctionBeginUser;
1341 PetscCall(RunIEMOnSeededBox(-1.0, -1.0, PETSC_TRUE, PETSC_FALSE, &change, before, after));
1342 PetscCall(PicurvAssertBool((PetscBool)(change < 1.0e-9),
1343 "IEM must keep each cell's Psi total when rates vary within the cell"));
1344 PetscFunctionReturn(0);
1345}
1346
1347/**
1348 * @brief IEM keeps Psi within the particles' extrema and each cell's total, across a sharp front.
1349 * @details A step from `lo` to `hi` across x = L/2: the gradient at the front carries into the
1350 * neighbouring pure cells, so an unlimited linear target overshoots both values. Three
1351 * representatives: 0/1 with uniform rates; 0/1 with rates varying within cells and the
1352 * particles crowded into a corner of each cell; and 2/5, whose bounds are not [0, 1], so
1353 * a bound fixed at [0, 1] fails.
1354 */
1355static PetscErrorCode TestIEMStaysWithinParticleExtrema(void)
1356{
1357 const struct { PetscReal lo, hi; PetscBool vary, crowd; const char *what; } cases[] = {
1358 {0.0, 1.0, PETSC_FALSE, PETSC_FALSE, "0/1 step, uniform rates"},
1359 {0.0, 1.0, PETSC_TRUE, PETSC_TRUE, "0/1 step, varying rates, crowded particles"},
1360 {2.0, 5.0, PETSC_FALSE, PETSC_FALSE, "2/5 step, uniform rates"},
1361 };
1362
1363 PetscFunctionBeginUser;
1364 for (size_t c = 0; c < sizeof(cases) / sizeof(cases[0]); ++c) {
1365 PetscReal change = 0.0, before[2], after[2];
1366 char msg[256];
1367 PetscCall(RunIEMOnSeededBox(cases[c].lo, cases[c].hi, cases[c].vary, cases[c].crowd, &change, before, after));
1368 PetscCall(PetscSNPrintf(msg, sizeof(msg), "%s: Psi must stay within the particle extrema [%g, %g], got [%g, %g]",
1369 cases[c].what, (double)before[0], (double)before[1], (double)after[0], (double)after[1]));
1370 PetscCall(PicurvAssertBool((PetscBool)(after[0] >= before[0] - 1.0e-12 && after[1] <= before[1] + 1.0e-12), msg));
1371 PetscCall(PetscSNPrintf(msg, sizeof(msg), "%s: IEM must keep each cell's Psi total", cases[c].what));
1372 PetscCall(PicurvAssertBool((PetscBool)(change < 1.0e-9), msg));
1373 PetscCall(PetscSNPrintf(msg, sizeof(msg), "%s: the front must still mix (extrema reached inside the box)", cases[c].what));
1374 PetscCall(PicurvAssertBool((PetscBool)(before[0] == cases[c].lo && before[1] == cases[c].hi), msg));
1375 }
1376 PetscFunctionReturn(0);
1377}
1378
1379/**
1380 * @brief Velocity sources draw by global index, whatever the decomposition.
1381 * @details Every value is compared with a draw this test makes from the cell's or face cell's
1382 * global indices alone, so a key that depended on the rank layout would fail at any
1383 * rank count but one. A cell reads one draw per component; a face cell a new one each
1384 * step, and the same one when a step is revisited.
1385 */
1386static PetscErrorCode TestSourceDrawsAreKeyedOnTheGrid(void)
1387{
1388 const char *options = "-source_random_seed 77\n"
1389 "-ic_source_expr_0 \"uniform()\"\n"
1390 "-ic_source_expr_1 \"uniform()\"\n"
1391 "-ic_source_expr_2 \"1 + uniform(3)\"\n"
1392 "-face_source_0_expr_0 \"1 + 0.1*normal()\"\n";
1393 static const char *const kNames[] = {"t"};
1394 SimCtx *simCtx = NULL;
1395 UserCtx *user = NULL;
1396 char tmpdir[PETSC_MAX_PATH_LEN];
1397 PicurvExpression *cell[3] = {NULL, NULL, NULL}, *face = NULL;
1398 PetscReal worst = 0.0, changed = 0.0;
1399 PetscInt compared[2] = {0, 0};
1400
1401 PetscFunctionBeginUser;
1402 PetscCall(PicurvBuildTinyRuntimeContextWithOptions(NULL, PETSC_FALSE, options, &simCtx, &user, tmpdir, sizeof(tmpdir)));
1403 PetscCall(InitializeEulerianState(simCtx));
1404 PetscCall(PicurvExpressionCompile("uniform()", kNames, 1, PETSC_TRUE, &cell[0]));
1405 PetscCall(PicurvExpressionCompile("uniform()", kNames, 1, PETSC_TRUE, &cell[1]));
1406 PetscCall(PicurvExpressionCompile("1 + uniform(3)", kNames, 1, PETSC_TRUE, &cell[2]));
1407 PetscCall(PicurvExpressionCompile("1 + 0.1*normal()", kNames, 1, PETSC_TRUE, &face));
1408
1409 const DMDALocalInfo *info = &user->info;
1410 const PetscInt nodes[3] = {info->mx, info->my, info->mz};
1411 const PetscReal U_ref = simCtx->scaling.U_ref;
1412 const Cmpnts ***ucont = NULL, ***csi = NULL, ***eta = NULL, ***zet = NULL;
1413
1414 /* The initial field: each interior face is the draw of the cell behind it. */
1415 PetscCall(DMDAVecGetArrayRead(user->fda, user->Ucont, (void *)&ucont));
1416 PetscCall(DMDAVecGetArrayRead(user->fda, user->lCsi, (void *)&csi));
1417 PetscCall(DMDAVecGetArrayRead(user->fda, user->lEta, (void *)&eta));
1418 PetscCall(DMDAVecGetArrayRead(user->fda, user->lZet, (void *)&zet));
1419 for (PetscInt k = PetscMax(info->zs, 1); k < PetscMin(info->zs + info->zm, nodes[2] - 2); ++k)
1420 for (PetscInt j = PetscMax(info->ys, 1); j < PetscMin(info->ys + info->ym, nodes[1] - 2); ++j)
1421 for (PetscInt i = PetscMax(info->xs, 1); i < PetscMin(info->xs + info->xm, nodes[0] - 2); ++i) {
1422 PicurvExpressionDrawKey key = {77, i + (PetscInt64)nodes[0] * (j + (PetscInt64)nodes[1] * k),
1423 PICURV_DRAW_SALT_INITIAL_FIELD, 0, PETSC_TRUE};
1424 Cmpnts v;
1425 key.field = 0; PetscCall(PicurvExpressionEvaluate(cell[0], NULL, &key, &v.x));
1426 key.field = 1; PetscCall(PicurvExpressionEvaluate(cell[1], NULL, &key, &v.y));
1427 key.field = 2; PetscCall(PicurvExpressionEvaluate(cell[2], NULL, &key, &v.z));
1428 const Cmpnts m[3] = {csi[k][j][i], eta[k][j][i], zet[k][j][i]};
1429 const PetscReal found[3] = {ucont[k][j][i].x, ucont[k][j][i].y, ucont[k][j][i].z};
1430 for (PetscInt a = 0; a < 3; ++a) {
1431 const PetscReal expected = (v.x * m[a].x + v.y * m[a].y + v.z * m[a].z) / U_ref;
1432 worst = PetscMax(worst, PetscAbsReal(found[a] - expected));
1433 }
1434 compared[0]++;
1435 }
1436 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->Ucont, (void *)&ucont));
1437
1438 /* The inlet: a draw per face cell and step. */
1439 PetscReal *first = NULL;
1440 const PetscInt owned[2] = {PetscMin(info->xs + info->xm, nodes[0] - 1) - PetscMax(info->xs, 1),
1441 PetscMin(info->ys + info->ym, nodes[1] - 1) - PetscMax(info->ys, 1)};
1442 PetscCall(PetscCalloc1(owned[0] * owned[1], &first));
1443 for (PetscInt pass = 0; pass < 3; ++pass) {
1444 const PetscInt64 step = (pass == 1) ? 4 : 3;
1445 simCtx->step = step;
1446 PetscCall(BoundarySystem_ExecuteStep(user));
1447 if (info->zs != 0) continue;
1448 PetscCall(DMDAVecGetArrayRead(user->fda, user->Ucont, (void *)&ucont));
1449 for (PetscInt j = 1, n = 0; j < nodes[1] - 1; ++j)
1450 for (PetscInt i = 1; i < nodes[0] - 1; ++i) {
1451 if (j < info->ys || j >= info->ys + info->ym || i < info->xs || i >= info->xs + info->xm) continue;
1452 const PicurvExpressionDrawKey key = {77, PicurvFaceCellId(nodes, BC_FACE_NEG_Z, i - 1, j - 1), step, 0, PETSC_TRUE};
1453 const Cmpnts m = zet[0][j][i];
1454 PetscReal speed;
1455 PetscCall(PicurvExpressionEvaluate(face, NULL, &key, &speed));
1456 worst = PetscMax(worst, PetscAbsReal(ucont[0][j][i].z - speed / U_ref * PetscSqrtReal(m.x * m.x + m.y * m.y + m.z * m.z)));
1457 if (pass == 0) first[n] = ucont[0][j][i].z;
1458 if (pass == 1) changed += PetscAbsReal(ucont[0][j][i].z - first[n]);
1459 if (pass == 2) worst = PetscMax(worst, PetscAbsReal(ucont[0][j][i].z - first[n]));
1460 compared[1]++;
1461 ++n;
1462 }
1463 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->Ucont, (void *)&ucont));
1464 }
1465 PetscCall(PetscFree(first));
1466 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lZet, (void *)&zet));
1467 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lEta, (void *)&eta));
1468 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lCsi, (void *)&csi));
1469 PetscCallMPI(MPI_Allreduce(MPI_IN_PLACE, &worst, 1, MPIU_REAL, MPI_MAX, PETSC_COMM_WORLD));
1470 PetscCallMPI(MPI_Allreduce(MPI_IN_PLACE, &changed, 1, MPIU_REAL, MPI_SUM, PETSC_COMM_WORLD));
1471 PetscCallMPI(MPI_Allreduce(MPI_IN_PLACE, compared, 2, MPIU_INT, MPI_SUM, PETSC_COMM_WORLD));
1472 PetscCall(PicurvAssertIntEqual((nodes[0] - 3) * (nodes[1] - 3) * (nodes[2] - 3), compared[0], "every interior cell was compared"));
1473 PetscCall(PicurvAssertIntEqual(3 * (nodes[0] - 2) * (nodes[1] - 2), compared[1], "every inlet cell was compared on each pass"));
1474 PetscCall(PicurvAssertRealNear(0.0, worst, 1.0e-12, "a value is the draw its global index keys"));
1475 PetscCall(PicurvAssertBool((PetscBool)(changed > 0.0), "a later step draws anew"));
1476 for (PetscInt a = 0; a < 3; ++a) PetscCall(PicurvExpressionDestroy(&cell[a]));
1477 PetscCall(PicurvExpressionDestroy(&face));
1478 PetscCall(PicurvDestroyRuntimeContext(&simCtx));
1479 PetscCall(PicurvRemoveTempDir(tmpdir));
1480 PetscFunctionReturn(0);
1481}
1482
1483/**
1484 * @brief A filtered inflow draw at face cell (g0, g1) of -Zeta: the separable kernel applied to
1485 * the keyed normals on a lattice with a fixed padding beyond the face's edges.
1486 */
1487static PetscReal InflowOracle(PetscInt64 seed, PetscInt c, PetscInt g0, PetscInt g1, PetscInt64 step,
1488 const PetscInt cells[2], const PetscInt half[2], PetscReal *const kernel[2])
1489{
1490 PetscReal sum = 0.0;
1491 for (PetscInt k1 = -half[1]; k1 <= half[1]; ++k1)
1492 for (PetscInt k0 = -half[0]; k0 <= half[0]; ++k0) {
1493 const PetscInt64 pad = 1048576; /* the draw lattice's fixed padding beyond each face edge */
1494 const PetscInt64 id = ((PetscInt64)BC_FACE_NEG_Z * (cells[1] + 2 * pad) + (g1 + k1 + pad)) * (cells[0] + 2 * pad)
1495 + (g0 + k0 + pad);
1496 sum += kernel[0][k0 + half[0]] * kernel[1][k1 + half[1]]
1497 * PicurvNormalFromHash(PicurvDrawHash(seed, PICURV_DRAW_SPACE_INFLOW, (uint64_t)c, id, step));
1498 }
1499 return sum;
1500}
1501
1502/**
1503 * @brief Tests that an inlet's synthetic fluctuation is the digital filter of draws keyed on the
1504 * grid, scaled by the Cholesky factor of the Reynolds stresses, on any decomposition.
1505 * @details The oracle rebuilds the kernels from the grid spacing, filters the keyed normals at
1506 * each owned inlet cell, and checks the state in the dummy plane and the boundary
1507 * velocity at the first step and after one time-filter update. Lengths are chosen so
1508 * the halo passes the face's closed edges.
1509 */
1511{
1512 const char *options = "-source_random_seed 91\n"
1513 "-inflow_fluctuations true\n"
1514 "-face_source_0_fluct true\n"
1515 "-face_source_0_fluct_stress_0_frame cartesian\n"
1516 "-face_source_0_fluct_stress_0_expr_0 0.04\n"
1517 "-face_source_0_fluct_stress_0_expr_1 0.01\n"
1518 "-face_source_0_fluct_stress_0_expr_2 0.09\n"
1519 "-face_source_0_fluct_stress_1_frame cartesian\n"
1520 "-face_source_0_fluct_stress_1_expr_0 0.01\n"
1521 "-face_source_0_fluct_stress_1_expr_1 0.0\n"
1522 "-face_source_0_fluct_stress_1_expr_2 0.005\n"
1523 "-face_source_0_fluct_length 0.25,0.13\n"
1524 "-face_source_0_fluct_time 0.05\n";
1525 const PetscReal length[2] = {0.25, 0.13}, T = 0.05;
1526 SimCtx *simCtx = NULL;
1527 UserCtx *user = NULL;
1528 char tmpdir[PETSC_MAX_PATH_LEN];
1529 PetscReal worst = 0.0, moved = 0.0;
1530 PetscInt compared = 0;
1531 PetscReal *kernel[2] = {NULL, NULL};
1532 PetscInt half[2];
1533
1534 PetscFunctionBeginUser;
1535 PetscCall(PicurvBuildTinyRuntimeContextWithOptions(NULL, PETSC_FALSE, options, &simCtx, &user, tmpdir, sizeof(tmpdir)));
1536 PetscCall(InitializeEulerianState(simCtx));
1537
1538 const DMDALocalInfo *info = &user->info;
1539 const PetscInt nodes[3] = {info->mx, info->my, info->mz};
1540 const PetscInt cells[2] = {nodes[0] - 2, nodes[1] - 2};
1541 const PetscReal U_ref = simCtx->scaling.U_ref, U2 = U_ref * U_ref;
1542 const PetscReal decay = PetscExpReal(-PETSC_PI * simCtx->dt / (2.0 * T)), gain = PetscSqrtReal(1.0 - decay * decay);
1543 /* A = chol(R / U_ref^2) for R = [[0.04, 0.01, 0], [0.01, 0.01, 0.005], [0, 0.005, 0.09]]. */
1544 PetscReal A[3][3] = {{0.0}};
1545 A[0][0] = 0.2 / U_ref;
1546 A[1][0] = 0.01 / U2 / A[0][0];
1547 A[1][1] = PetscSqrtReal(0.01 / U2 - A[1][0] * A[1][0]);
1548 A[2][1] = 0.005 / U2 / A[1][1];
1549 A[2][2] = PetscSqrtReal(0.09 / U2 - A[2][1] * A[2][1]);
1550
1551 /* The unit box: h = 1 / cells, n = L / h, weights exp(-pi |k| / n) to a unit sum of squares. */
1552 for (PetscInt d = 0; d < 2; ++d) {
1553 const PetscReal n = length[d] * (PetscReal)cells[d];
1554 PetscReal norm = 0.0;
1555 half[d] = PetscMax(1, (PetscInt)PetscCeilReal(2.0 * n));
1556 PetscCall(PetscMalloc1(2 * half[d] + 1, &kernel[d]));
1557 for (PetscInt k = -half[d]; k <= half[d]; ++k) {
1558 kernel[d][k + half[d]] = PetscExpReal(-PETSC_PI * PetscAbsReal((PetscReal)k) / n);
1559 norm += kernel[d][k + half[d]] * kernel[d][k + half[d]];
1560 }
1561 for (PetscInt k = 0; k <= 2 * half[d]; ++k) kernel[d][k] /= PetscSqrtReal(norm);
1562 }
1563 PetscCall(PicurvAssertBool((PetscBool)(half[0] > cells[0] / 2), "the halo passes a closed edge of the face"));
1564
1565 PetscReal *previous = NULL;
1566 PetscCall(PetscCalloc1(3 * info->xm * info->ym, &previous));
1567 for (PetscInt pass = 0; pass < 2; ++pass) {
1568 if (pass == 1) {
1569 simCtx->step = 1;
1570 PetscCall(BoundarySystem_ExecuteStep(user));
1571 }
1572 if (info->zs != 0) continue;
1573 const Cmpnts ***state = NULL, ***ubcs = NULL;
1574 PetscCall(DMDAVecGetArrayRead(user->fda, user->InflowFluctuation, (void *)&state));
1575 PetscCall(DMDAVecGetArrayRead(user->fda, user->Bcs.Ubcs, (void *)&ubcs));
1576 for (PetscInt j = PetscMax(info->ys, 1); j < PetscMin(info->ys + info->ym, nodes[1] - 1); ++j)
1577 for (PetscInt i = PetscMax(info->xs, 1); i < PetscMin(info->xs + info->xm, nodes[0] - 1); ++i) {
1578 PetscReal *psi = &previous[3 * ((i - info->xs) + info->xm * (j - info->ys))];
1579 for (PetscInt c = 0; c < 3; ++c) {
1580 const PetscReal draw = InflowOracle(91, c, i - 1, j - 1, pass, cells, half, kernel);
1581 psi[c] = (pass == 0) ? draw : decay * psi[c] + gain * draw;
1582 }
1583 const PetscReal found[3] = {state[0][j][i].x, state[0][j][i].y, state[0][j][i].z};
1584 const PetscReal u[3] = {ubcs[0][j][i].x, ubcs[0][j][i].y, ubcs[0][j][i].z - 1.5 / U_ref};
1585 for (PetscInt c = 0; c < 3; ++c) {
1586 const PetscReal expected = A[c][0] * psi[0] + A[c][1] * psi[1] + A[c][2] * psi[2];
1587 worst = PetscMax(worst, PetscAbsReal(found[c] - psi[c]));
1588 worst = PetscMax(worst, PetscAbsReal(u[c] - expected));
1589 if (pass == 1) moved += PetscAbsReal(u[c]);
1590 }
1591 compared++;
1592 }
1593 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->Bcs.Ubcs, (void *)&ubcs));
1594 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->InflowFluctuation, (void *)&state));
1595 }
1596 PetscCall(PetscFree(previous));
1597 PetscCallMPI(MPI_Allreduce(MPI_IN_PLACE, &worst, 1, MPIU_REAL, MPI_MAX, PETSC_COMM_WORLD));
1598 PetscCallMPI(MPI_Allreduce(MPI_IN_PLACE, &moved, 1, MPIU_REAL, MPI_SUM, PETSC_COMM_WORLD));
1599 PetscCallMPI(MPI_Allreduce(MPI_IN_PLACE, &compared, 1, MPIU_INT, MPI_SUM, PETSC_COMM_WORLD));
1600 PetscCall(PicurvAssertIntEqual(2 * cells[0] * cells[1], compared, "every inlet cell was compared on each pass"));
1601 PetscCall(PicurvAssertRealNear(0.0, worst, 1.0e-12, "the state and inlet velocity are the filtered keyed draw"));
1602 PetscCall(PicurvAssertBool((PetscBool)(moved > 0.0), "the inlet carries a fluctuation"));
1603 for (PetscInt d = 0; d < 2; ++d) PetscCall(PetscFree(kernel[d]));
1604 PetscCall(PicurvDestroyRuntimeContext(&simCtx));
1605 PetscCall(PicurvRemoveTempDir(tmpdir));
1606 PetscFunctionReturn(0);
1607}
1608
1609/**
1610 * @brief Tests that a face that is not an INLET refuses to inject.
1611 */
1613{
1614 const char *options = "-particle_inlet_count 1\n-particle_inlet_0_face 0\n-particle_inlet_0_particles_per_cell \"1.0\"\n";
1615 SimCtx *simCtx = NULL;
1616 UserCtx *user = NULL;
1617 char tmpdir[PETSC_MAX_PATH_LEN];
1618 PetscErrorCode refused;
1619
1620 PetscFunctionBeginUser;
1621 PetscCall(PicurvBuildTinyRuntimeContextWithOptions(NULL, PETSC_FALSE, options, &simCtx, &user, tmpdir, sizeof(tmpdir)));
1622 PetscCall(InitializeEulerianState(simCtx));
1623 PetscCall(InitializeParticleSwarm(simCtx));
1624 simCtx->step = 1;
1625 PetscCall(PetscPushErrorHandler(PetscIgnoreErrorHandler, NULL));
1626 refused = InjectParticlesAtInlets(user);
1627 PetscCall(PetscPopErrorHandler());
1628 PetscCall(PicurvAssertBool((PetscBool)(refused != 0), "a wall does not inject particles"));
1629 PetscCall(PicurvDestroyRuntimeContext(&simCtx));
1630 PetscCall(PicurvRemoveTempDir(tmpdir));
1631 PetscFunctionReturn(0);
1632}
1633
1634/**
1635 * @brief Tests that, across a periodic seam and rank boundaries, the face planes the search and
1636 * interpolation read after a ghost update are each cell's own planes.
1637 * @details Every grid cell made of physical nodes and every dual cell the interpolation can form
1638 * must give, to rounding, the distances CalculateDistancesToCellFaces() computes from that
1639 * cell's own vertices, whatever the fields' sync classes do to the ghosts beyond.
1640 */
1642{
1643 SimCtx *simCtx = NULL;
1644 UserCtx *user = NULL;
1645 FacePlaneArrays arrays;
1646 CellFacePlanes shared;
1647 Cell cell;
1648 PetscReal d_shared[NUM_FACES], d_cell[NUM_FACES];
1649 const Cmpnts ***cent = NULL;
1655 PetscInt checked = 0, checked_global = 0;
1656
1657 PetscFunctionBeginUser;
1658 PetscCall(PicurvCreateMinimalContextsWithPeriodicity(&simCtx, &user, 8, 6, 6, PETSC_TRUE, PETSC_FALSE, PETSC_FALSE));
1659 MarkXPeriodic(user);
1660 for (size_t f = 0; f < sizeof(fields) / sizeof(fields[0]); ++f) PetscCall(UpdateLocalGhosts(user, fields[f]));
1661
1662 const DMDALocalInfo *info = &user->info;
1663 const PetscInt gs[3] = {info->gxs, info->gys, info->gzs};
1664 const PetscInt ge[3] = {info->gxs + info->gxm, info->gys + info->gym, info->gzs + info->gzm};
1665 const PetscInt mx[3] = {info->mx, info->my, info->mz};
1666 const Cmpnts p = {0.43, 0.38, 0.61};
1667
1668 /* Grid cells: origins whose nodes are physical (0..mx-2) and local. */
1669 PetscCall(MetricGetFacePlaneArrays(user, PETSC_FALSE, &arrays));
1670 for (PetscInt k = PetscMax(gs[2], 0); k + 1 <= PetscMin(ge[2] - 1, mx[2] - 2); ++k)
1671 for (PetscInt j = PetscMax(gs[1], 0); j + 1 <= PetscMin(ge[1] - 1, mx[1] - 2); ++j)
1672 for (PetscInt i = PetscMax(gs[0], 0); i + 1 <= PetscMin(ge[0] - 1, mx[0] - 2); ++i) {
1673 MetricGatherCellFacePlanes(&arrays, info, i, j, k, &shared);
1674 PetscCall(RetrieveCurrentCell(user, i, j, k, &cell));
1675 PetscCall(CalculateDistancesToCellFaces(p, &cell, d_cell, 0.0, NULL));
1676 PetscCall(CalculateDistancesToCellFacePlanes(p, &shared, d_shared, 0.0, NULL));
1677 for (PetscInt f = 0; f < NUM_FACES; ++f)
1678 PetscCall(PicurvAssertRealNear(d_cell[f], d_shared[f], 1.0e-14, "grid cell plane after ghost update"));
1679 checked++;
1680 }
1681 PetscCall(MetricRestoreFacePlaneArrays(user, &arrays));
1682
1683 /* Dual cells: centres 0..mx-1 on the periodic x axis, 1..mx-2 across the walls. */
1684 PetscCall(MetricGetFacePlaneArrays(user, PETSC_TRUE, &arrays));
1685 PetscCall(DMDAVecGetArrayRead(user->fda, user->lCent, (void *)&cent));
1686 for (PetscInt k = PetscMax(gs[2], 1); k + 1 <= PetscMin(ge[2] - 1, mx[2] - 2); ++k)
1687 for (PetscInt j = PetscMax(gs[1], 1); j + 1 <= PetscMin(ge[1] - 1, mx[1] - 2); ++j)
1688 for (PetscInt i = PetscMax(gs[0], 0); i + 1 <= PetscMin(ge[0] - 1, mx[0] - 1); ++i) {
1689 cell.vertices[0] = cent[k][j][i]; cell.vertices[1] = cent[k][j][i + 1];
1690 cell.vertices[2] = cent[k][j + 1][i + 1]; cell.vertices[3] = cent[k][j + 1][i];
1691 cell.vertices[4] = cent[k + 1][j + 1][i]; cell.vertices[5] = cent[k + 1][j + 1][i + 1];
1692 cell.vertices[6] = cent[k + 1][j][i + 1]; cell.vertices[7] = cent[k + 1][j][i];
1693 MetricGatherCellFacePlanes(&arrays, info, i, j, k, &shared);
1694 PetscCall(CalculateDistancesToCellFaces(p, &cell, d_cell, 0.0, NULL));
1695 PetscCall(CalculateDistancesToCellFacePlanes(p, &shared, d_shared, 0.0, NULL));
1696 for (PetscInt f = 0; f < NUM_FACES; ++f)
1697 PetscCall(PicurvAssertRealNear(d_cell[f], d_shared[f], 1.0e-14, "dual cell plane after ghost update"));
1698 checked++;
1699 }
1700 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lCent, (void *)&cent));
1701 PetscCall(MetricRestoreFacePlaneArrays(user, &arrays));
1702
1703 PetscCallMPI(MPI_Allreduce(&checked, &checked_global, 1, MPIU_INT, MPI_SUM, PETSC_COMM_WORLD));
1704 PetscCall(PicurvAssertBool((PetscBool)(checked_global > 0), "some cells were checked"));
1705 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
1706 PetscFunctionReturn(0);
1707}
1708
1709/**
1710 * @brief Runs the unit-mpi PETSc test binary.
1711 */
1712int main(int argc, char **argv)
1713{
1714 PetscErrorCode ierr;
1715 const PicurvTestCase cases[] = {
1716 {"distribute-particles-collective-consistency", TestDistributeParticlesCollectiveConsistency},
1717 {"bounding-box-collectives-multi-rank", TestBoundingBoxCollectivesMultiRank},
1718 {"periodic-cell-field-synchronization-multi-rank", TestPeriodicCellFieldSynchronizationMultiRank},
1719 {"periodic-geometry-validation-multi-rank", TestPeriodicGeometryValidationMultiRank},
1720 {"periodic-face-center-coordinates-multi-rank", TestPeriodicFaceCenterCoordinatesMultiRank},
1721 {"periodic-face-field-synchronization-multi-rank", TestPeriodicFaceFieldSynchronizationMultiRank},
1722 {"periodic-staggered-field-synchronization-multi-rank", TestPeriodicStaggeredFieldSynchronizationMultiRank},
1723 {"face-planes-survive-periodic-ghost-update", TestFacePlanesSurvivePeriodicGhostUpdate},
1724 {"spatial-target-decomposition-independent", TestSpatialTargetIsDecompositionIndependent},
1725 {"statistics-checkpoint-round-trip-multi-rank", TestStatisticsCheckpointRoundTripMultiRank},
1726 {"les-averaging-decomposition-independent", TestLESAveragingIsDecompositionIndependent},
1727 {"find-owner-of-cell-matches-rank-ranges", TestFindOwnerOfCellMatchesRankRanges},
1728 {"profiling-summary-reduces-over-ranks", TestProfilingSummaryReducesOverRanks},
1729 {"restart-cellid-migration-moves-particle-to-owner", TestRestartCellIdMigrationMovesParticleToOwner},
1730 {"settlement-classifies-exit-once-across-passes", TestSettlementClassifiesExitOnceAcrossPasses},
1731 {"grid-line-fractions-follow-arc-length", TestGridLineFractionsFollowArcLength},
1732 {"injection-follows-flux-and-is-keyed-on-the-grid", TestInjectionFollowsFluxAndIsKeyedOnTheGrid},
1733 {"injection-refuses-a-face-that-is-not-an-inlet", TestInjectionRefusesAFaceThatIsNotAnInlet},
1734 {"source-draws-are-keyed-on-the-grid", TestSourceDrawsAreKeyedOnTheGrid},
1735 {"inlet-fluctuation-is-the-filtered-keyed-draw", TestInletFluctuationIsTheFilteredKeyedDraw},
1736 {"iem-reconstruction-across-seams", TestIEMReconstructionAcrossSeams},
1737 {"iem-keeps-cell-totals-with-varying-rates", TestIEMKeepsCellTotalsWithVaryingRates},
1738 {"iem-stays-within-particle-extrema", TestIEMStaysWithinParticleExtrema},
1739 };
1740
1741 ierr = PetscInitialize(&argc, &argv, NULL, "PICurv MPI-focused runtime tests");
1742 if (ierr) {
1743 return (int)ierr;
1744 }
1745
1746 ierr = PicurvRunTests("unit-mpi", cases, sizeof(cases) / sizeof(cases[0]));
1747 if (ierr) {
1748 PetscFinalize();
1749 return (int)ierr;
1750 }
1751
1752 ierr = PetscFinalize();
1753 return (int)ierr;
1754}
PetscErrorCode SynchronizePeriodicStaggeredFields(UserCtx *user, PetscInt num_fields, const FieldId field_ids[])
Synchronizes persistent component-staggered vector fields.
PetscErrorCode BoundarySystem_ExecuteStep(UserCtx *user)
Executes one full boundary condition update cycle for a time step.
Definition Boundaries.c:600
PetscErrorCode SynchronizePeriodicFaceFields(UserCtx *user, char face_direction, PetscInt num_fields, const FieldId field_ids[])
Synchronizes persistent fields belonging to one face family.
PetscErrorCode SynchronizePeriodicCellFields(UserCtx *user, PetscInt num_fields, const FieldId field_ids[])
Synchronizes periodic endpoint cells for a list of cell-centered fields.
PetscErrorCode MetricRestoreFacePlaneArrays(UserCtx *user, FacePlaneArrays *arrays)
Closes arrays opened by MetricGetFacePlaneArrays().
Definition Metric.c:401
void MetricGatherCellFacePlanes(const FacePlaneArrays *arrays, const DMDALocalInfo *info, PetscInt i, PetscInt j, PetscInt k, CellFacePlanes *planes)
Assembles one cell's six outward face planes from the shared per-face planes.
Definition Metric.c:421
PetscErrorCode MetricGetFacePlaneArrays(UserCtx *user, PetscBool dual, FacePlaneArrays *arrays)
Opens a family's face-plane arrays for reading; MetricComputeFacePlanes() must have run.
Definition Metric.c:376
PetscErrorCode ComputeGridLineFractions(UserCtx *user, Vec fraction, Vec length)
Arc-length position of every owned cell centre along its three grid lines.
Definition Metric.c:1362
Read-only flat arrays of one family of face planes (grid cells or dual cells).
Definition Metric.h:528
Header file for Particle Motion and migration related functions.
PetscErrorCode MigrateRestartParticlesUsingCellID(UserCtx *user)
Fast-path migration for restart particles using preloaded Cell IDs.
PetscErrorCode LocateAllParticlesInGrid(UserCtx *user, BoundingBox *bboxlist)
Orchestrates the complete particle location and migration process for one timestep.
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 UpdateAllParticleFields(UserCtx *user)
Orchestrates the update of all physical properties for particles.
Header file for Particle Swarm management functions.
PetscErrorCode InjectParticlesAtInlets(UserCtx *user)
Add the particles that entered through each injecting inlet during this step.
PetscErrorCode DistributeParticles(PetscInt numParticles, PetscMPIInt rank, PetscMPIInt size, PetscInt *particlesPerProcess, PetscInt *remainder)
Distributes particles evenly across MPI processes, handling any remainders.
PetscErrorCode InitializeParticleSwarm(SimCtx *simCtx)
High-level particle initialization orchestrator for a simulation run.
The expression language shared by every configured field, the keyed hashes its random draws and other...
PetscReal PicurvNormalFromHash(uint64_t hash)
A standard normal deviate from a hash: the first of PicurvNormalPairFromHash()'s pair.
Definition expression.c:655
PetscErrorCode PicurvExpressionEvaluate(const PicurvExpression *expression, const PetscReal *values, const PicurvExpressionDrawKey *key, PetscReal *result)
Evaluate a compiled expression.
Definition expression.c:724
PetscErrorCode PicurvExpressionDestroy(PicurvExpression **expression)
Free a compiled expression.
Definition expression.c:818
uint64_t PicurvDrawHash(PetscInt64 seed, PicurvDrawSpace space, uint64_t stream, PetscInt64 id, PetscInt64 salt)
Hash that keys a draw: a pure function of its arguments, so a draw does not depend on the rank that m...
Definition expression.c:610
static PetscInt64 PicurvFaceCellId(const PetscInt nodes[3], BCFace face, PetscInt p, PetscInt q)
Global identity of a boundary face cell, unique over the six faces of a block and independent of the ...
Definition expression.h:275
@ PICURV_DRAW_SPACE_INLET
Injection at an inlet: stream 0 counts per face cell, stream 1 distance in.
Definition expression.h:34
@ PICURV_DRAW_SPACE_INFLOW
Synthetic inflow noise: stream per block and component, salt the step.
Definition expression.h:37
PetscReal PicurvUnitFromHash(uint64_t hash)
Uniform on [0, 1) from the top 53 bits of a hash.
Definition expression.c:601
PetscErrorCode PicurvExpressionCompile(const char *text, const char *const *names, PetscInt name_count, PetscBool allow_random, PicurvExpression **expression)
Compile one expression against a list of variable names.
Definition expression.c:551
#define PICURV_DRAW_SALT_INITIAL_FIELD
Salt of a cell's draws: the field is set once, and no step has this number.
Definition expression.h:95
PetscInt64 field
Field or component whose expression draws, the default stream's namespace.
Definition expression.h:90
What a random draw is keyed on, besides its stream.
Definition expression.h:85
Authoritative identities and storage metadata for persistent Eulerian fields.
FieldId
Compile-time identity for a catalogued Eulerian field.
@ FIELD_ID_DUAL_PLANE_CENTROID_I
@ FIELD_ID_PLANE_NORMAL_J
@ FIELD_ID_PSI
@ FIELD_ID_PLANE_CENTROID_I
@ FIELD_ID_CSI
@ FIELD_ID_IAJ
@ FIELD_ID_PLANE_NORMAL_K
@ FIELD_ID_UCAT
@ FIELD_ID_PLANE_CENTROID_K
@ FIELD_ID_COORDINATES
@ FIELD_ID_PLANE_NORMAL_I
@ FIELD_ID_DUAL_PLANE_CENTROID_J
@ FIELD_ID_DUAL_PLANE_CENTROID_K
@ FIELD_ID_UCONT
@ FIELD_ID_CS
@ FIELD_ID_PLANE_CENTROID_J
@ FIELD_ID_DUAL_PLANE_NORMAL_I
@ FIELD_ID_DUAL_PLANE_NORMAL_J
@ FIELD_ID_DUAL_PLANE_NORMAL_K
@ FIELD_ID_P
@ FIELD_ID_CENTX
@ FIELD_ID_DIFFUSIVITY
@ FIELD_ID_SEARCH_CELL_SIZE
Public interface for grid, solver, and metric setup routines.
PetscErrorCode BroadcastAllBoundingBoxes(UserCtx *user, BoundingBox **bboxlist)
Broadcasts the bounding box information collected on rank 0 to all other ranks.
Definition grid.c:1071
PetscErrorCode ValidatePeriodicGeometry(UserCtx *user)
Validates that configured geometric periodic seams match by translation.
Definition grid.c:450
PetscErrorCode ComputeLocalBoundingBox(UserCtx *user, BoundingBox *localBBox)
Computes the local bounding box of the grid on the current process.
Definition grid.c:869
PetscErrorCode GatherAllBoundingBoxes(UserCtx *user, BoundingBox **allBBoxes)
Gathers local bounding boxes from all MPI processes to rank 0.
Definition grid.c:1011
PetscErrorCode InitializeEulerianState(SimCtx *simCtx)
High-level orchestrator to set the complete initial state of the Eulerian solver.
Public interface for data input/output routines.
PetscErrorCode RestoreFieldStatisticsState(SimCtx *simCtx, PetscInt ti)
Restores field-statistics window state and accumulators from a checkpoint.
Definition io.c:1604
PetscErrorCode WriteCheckpointBundle(SimCtx *simCtx, const char *reason)
Write and atomically publish one complete checkpoint bundle.
Definition io.c:2501
Logging utilities and macros for PETSc-based applications.
#define PROFILE_FUNCTION_END
Marks the end of a profiled code block.
Definition logging.h:1029
PetscErrorCode ProfilingFinalize(SimCtx *simCtx)
Writes the end-of-run profiling summary across all ranks; collective on PETSC_COMM_WORLD.
Definition logging.c:2380
#define PROFILE_FUNCTION_BEGIN
Marks the beginning of a profiled function: an always-on aggregate timer.
Definition logging.h:1000
PetscErrorCode PerformInitializedParticleSetup(SimCtx *simCtx)
Finalizes the simulation setup at t=0, ensuring a consistent state before time marching.
Definition runloop.c:426
PetscErrorCode UpdateLocalGhosts(UserCtx *user, FieldId field_id)
Updates the local vector (including ghost points) from its corresponding global vector.
Definition setup.c:2593
PetscErrorCode SetupDomainCellDecompositionMap(UserCtx *user)
Creates and distributes a map of the domain's cell decomposition to all ranks.
Definition setup.c:3467
Per-window PETSc accumulator storage and pointwise application.
Vec vec
Borrowed accumulator vector; never owned by the caller.
PetscErrorCode PicurvWindowStorageCreate(UserCtx *user, const PicurvWindowDefinition *definition, PicurvWindowStorage *storage)
Allocates the accumulator state one window owns on one block.
PetscErrorCode PicurvWindowStoragePayload(UserCtx *user, const PicurvWindowDefinition *definition, const PicurvWindowStorage *storage, PetscInt index, PicurvStatisticsPayload *payload)
Resolves one enumerated payload of a window's storage.
char name[96]
File basename, no extension.
PetscErrorCode PicurvWindowAccumulate(UserCtx *user, const PicurvWindowDefinition *definition, PicurvWindowStorage *storage, PetscReal weight)
Applies one accepted completed state to a window's accumulators.
PetscErrorCode PicurvWindowStorageDestroy(PicurvWindowStorage *storage)
Releases accumulator state previously created for one window.
PetscErrorCode PicurvWindowStoragePayloadCount(const PicurvWindowStorage *storage, PetscInt *count)
Reports how many checkpointable vectors one window's storage holds.
One checkpointable accumulator vector, resolved by enumeration index.
Independent accumulator state for one window on one block.
Spatial target resolution for the field-statistics pipeline.
@ PICURV_STATISTICS_MASK_FLUID
PetscErrorCode SpatialTargetPlanLocalPointCount(const SpatialTargetPlan *plan, PetscInt *count)
Counts the points this rank contributes.
PetscErrorCode SpatialTargetPlanGlobalPointCount(const SpatialTargetPlan *plan, MPI_Comm comm, PetscInt *count)
Counts the points contributed across a communicator.
PetscErrorCode SpatialTargetPlanCreate(UserCtx *user, FieldId field_id, PicurvStatisticsMask mask, SpatialTargetPlan *plan)
Resolves the iteration domain for one field on one block.
PetscErrorCode PicurvSpatialRatioAverage(UserCtx *user, const SpatialTargetPlan *plan, Vec numerator, Vec denominator, Vec inclusion, const PetscBool average_direction[3], MPI_Comm comm, Vec ratio, PetscReal *reduced)
Averages two fields over a target domain and divides the results.
Resolved iteration domain for one field on one block.
Window lifecycle, scheduling, and weighting for the field-statistics pipeline.
PetscInt sample_count
PetscInt first
First member; must also appear in the field list.
PicurvWindowFieldRequest fields[16]
PicurvCadenceKind cadence_kind
PetscReal total_weight
PetscInt step_cadence
Used when cadence_kind is step; must be positive.
#define PICURV_WINDOW_NAME_LENGTH
Maximum stored length of a window name, including the terminator.
PetscErrorCode PicurvWindowInit(PicurvWindow *window, const PicurvWindowDefinition *definition)
Validates a definition and initializes a window to the pending state.
PetscErrorCode PicurvWindowOfferState(PicurvWindow *window, PetscInt step, PetscReal time, PetscBool *accepted, PetscReal *weight)
Offers one completed state to a window and reports the decision.
PetscBool want_second
Also keep the centered second moment.
PetscInt second
Second member; must also appear in the field list.
PicurvWindowCovarianceRequest covariances[16]
PetscInt field_id
Catalogued Eulerian field identity.
@ PICURV_WEIGHTING_PHYSICAL_TIME
Weight is the represented interval.
@ PICURV_CADENCE_STEP
Every n completed steps from activation.
Runtime state of one window.
The scientifically immutable definition of one window.
static void MarkXPeriodic(UserCtx *user)
Marks both x boundary faces as geometric periodic boundaries.
static PetscErrorCode TestSettlementClassifiesExitOnceAcrossPasses(void)
A particle that left the domain is classified once and never re-searched in later passes.
static PetscErrorCode TestSpatialTargetIsDecompositionIndependent(void)
Spatial target domains must not depend on how ranks divide the block.
static PetscErrorCode TestPeriodicFaceCenterCoordinatesMultiRank(void)
Tests translated face-center ghosts when the periodic axis is partitioned.
static PetscReal LineFractionTestWidth(PetscInt axis, PetscInt n)
Width of cell n (1-based interior index) along an axis in the line-fraction test.
int main(int argc, char **argv)
Runs the unit-mpi PETSc test binary.
static PetscErrorCode TestIEMReconstructionAcrossSeams(void)
Checks that IEM's linear reconstruction holds across subdomain seams.
static PetscErrorCode ProfiledOnRankOneOnly(void)
A profiled function that takes a measurable time; the profiling macros name it by func.
static PetscErrorCode TestProfilingSummaryReducesOverRanks(void)
The final profiling summary reduces each function's total time over ranks.
static PetscErrorCode TestPeriodicFaceFieldSynchronizationMultiRank(void)
Tests persistent I-face synchronization across an MPI-partitioned seam.
static PetscErrorCode TestRestartCellIdMigrationMovesParticleToOwner(void)
Tests restart fast-path migration using preloaded cell ownership metadata.
static PetscErrorCode TestInletFluctuationIsTheFilteredKeyedDraw(void)
Tests that an inlet's synthetic fluctuation is the digital filter of draws keyed on the grid,...
static PetscErrorCode RunIEMOnSeededBox(PetscReal step_lo, PetscReal step_hi, PetscBool vary_rate, PetscBool crowd, PetscReal *max_cell_change, PetscReal before[2], PetscReal after[2])
Runs one IEM update on a seeded box after setting each particle's Psi, rate and place.
static PetscErrorCode TestLESAveragingIsDecompositionIndependent(void)
Tests that LES coefficient averaging does not depend on the decomposition.
static PetscErrorCode TestPeriodicGeometryValidationMultiRank(void)
Tests periodic seam translation discovery when seam nodes are on different ranks.
static PetscErrorCode TestStatisticsCheckpointRoundTripMultiRank(void)
Statistics payloads must survive a checkpoint round trip under decomposition.
static PetscErrorCode TestFacePlanesSurvivePeriodicGhostUpdate(void)
Tests that, across a periodic seam and rank boundaries, the face planes the search and interpolation ...
static PetscErrorCode TestPeriodicStaggeredFieldSynchronizationMultiRank(void)
Tests persistent Ucont synchronization across an MPI-partitioned seam.
static PetscErrorCode TestInjectionRefusesAFaceThatIsNotAnInlet(void)
Tests that a face that is not an INLET refuses to inject.
static PetscReal InflowOracle(PetscInt64 seed, PetscInt c, PetscInt g0, PetscInt g1, PetscInt64 step, const PetscInt cells[2], const PetscInt half[2], PetscReal *const kernel[2])
A filtered inflow draw at face cell (g0, g1) of -Zeta: the separable kernel applied to the keyed norm...
static PetscErrorCode TestIEMStaysWithinParticleExtrema(void)
IEM keeps Psi within the particles' extrema and each cell's total, across a sharp front.
#define TEST_INLET_FLUX(i_, j_)
static PetscErrorCode TestFindOwnerOfCellMatchesRankRanges(void)
The per-axis owner lookup agrees with a scan of every rank's cell ranges.
static PetscReal PeriodicScalarValue(PetscInt i, PetscInt j, PetscInt k, PetscReal offset)
Returns a deterministic scalar value for periodic-transfer assertions.
static PetscErrorCode TestSourceDrawsAreKeyedOnTheGrid(void)
Velocity sources draw by global index, whatever the decomposition.
static PetscErrorCode TestIEMKeepsCellTotalsWithVaryingRates(void)
IEM keeps every cell's Psi total when the particles in a cell relax at different rates.
static PetscErrorCode TestGridLineFractionsFollowArcLength(void)
Grid-line fractions follow arc length on a stretched orthogonal grid, and the lines that cross ranks ...
static PetscErrorCode TestInjectionFollowsFluxAndIsKeyedOnTheGrid(void)
Tests that injection follows the flux, is keyed on the grid, and carries no state.
static PetscErrorCode TestPeriodicCellFieldSynchronizationMultiRank(void)
Tests distributed synchronization of persistent cell-centered scalar fields.
static PetscErrorCode TestDistributeParticlesCollectiveConsistency(void)
Tests collective particle distribution consistency across MPI ranks.
static PetscErrorCode TestBoundingBoxCollectivesMultiRank(void)
Tests multi-rank bounding-box gather and broadcast helpers.
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 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 PicurvDestroyRuntimeContext(SimCtx **simCtx_ptr)
Finalizes and frees a runtime context built by PicurvBuildTinyRuntimeContext.
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 PicurvBuildTinyRuntimeContextWithOptions(const char *bcs_contents, PetscBool enable_particles, const char *extra_options, SimCtx **simCtx_out, UserCtx **user_out, char *tmpdir, size_t tmpdir_len)
Builds the tiny runtime context with extra control-file options appended.
PetscErrorCode PicurvAssertIntEqual(PetscInt expected, PetscInt actual, const char *context)
Asserts that two integer values are equal.
PetscErrorCode PicurvPopulateIdentityMetrics(UserCtx *user)
Populates identity metric vectors on the minimal grid fixture.
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.
PetscInt fieldStatisticsWindowCount
Definition variables.h:989
Vec lCent
Definition variables.h:1244
@ PERIODIC
Definition variables.h:325
PetscInt ys_cell
Definition variables.h:264
PetscBool profilingFinalSummary
Definition variables.h:1107
PetscInt xs_cell
Definition variables.h:264
PetscMPIInt rank
Definition variables.h:919
BoundaryFaceConfig boundary_faces[6]
Definition variables.h:1182
PetscInt64 searchLostCount
Definition variables.h:284
Vec lNvert
Definition variables.h:1197
@ 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
PetscReal L_ref
Definition variables.h:898
Vec InflowFluctuation
Definition variables.h:1194
@ BC_HANDLER_PERIODIC_GEOMETRIC
Definition variables.h:352
PetscReal iem_constant
IEM mixing constant C_IEM in Omega = C_IEM Gamma / Delta^2 (default 2.0).
Definition variables.h:1006
BCHandlerType handler_type
Definition variables.h:427
PetscInt zm_cell
Definition variables.h:265
Cmpnts max_coords
Maximum x, y, z coordinates of the bounding box.
Definition variables.h:214
PetscInt zs_cell
Definition variables.h:264
char output_dir[PETSC_MAX_PATH_LEN]
Definition variables.h:940
PetscReal dt
Definition variables.h:933
static PetscBool ParticlesEnabled(const SimCtx *simCtx)
Whether the run carries particles: a seeded or restored population, or inlets that inject them.
Definition variables.h:1143
PetscInt np
Definition variables.h:1049
PetscBool fieldStatisticsEnabled
Definition variables.h:988
PetscInt64 searchExitedCount
Definition variables.h:294
Vec Ucont
Definition variables.h:1197
Cmpnts min_coords
Minimum x, y, z coordinates of the bounding box.
Definition variables.h:213
Vec Ubcs
Physical Cartesian velocity at boundary faces. Full 3D array but only boundary-face entries are meani...
Definition variables.h:172
PetscScalar x
Definition variables.h:145
Vec Centx
Definition variables.h:1252
PetscInt xm_cell
Definition variables.h:265
RankCellInfo * RankCellInfoMap
Definition variables.h:1274
PetscInt ym_cell
Definition variables.h:265
BoundingBox * bboxlist
Definition variables.h:1053
struct PicurvWindow * fieldStatisticsWindows
Definition variables.h:990
char log_dir[PETSC_MAX_PATH_LEN]
Definition variables.h:941
PetscScalar z
Definition variables.h:145
Vec ParticleCount
Definition variables.h:1276
ScalingCtx scaling
Definition variables.h:1003
PetscInt JM
Definition variables.h:1171
PetscReal Min_Z
Definition variables.h:1172
PetscInt particleRandomSeed
Base seed for every particle RNG stream (-particle_random_seed).
Definition variables.h:1050
struct PicurvWindowStorage * fieldStatisticsStorage
Definition variables.h:1222
Vec lCentx
Definition variables.h:1253
SearchMetricsState searchMetrics
Definition variables.h:1073
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
PetscInt migrationPassesLastStep
Definition variables.h:1066
PetscScalar y
Definition variables.h:145
@ EXEC_MODE_SOLVER
Definition variables.h:888
PetscInt IM
Definition variables.h:1171
Cmpnts periodic_translation[3]
Definition variables.h:1178
@ NUM_FACES
Definition variables.h:197
Vec Nvert
Definition variables.h:1197
PetscBool periodic_translation_valid[3]
Definition variables.h:1179
Vec lDiffusivity
Definition variables.h:1200
BCType mathematical_type
Definition variables.h:426
ExecutionMode exec_mode
Definition variables.h:937
PetscReal U_ref
Definition variables.h:899
char restart_dir[PETSC_MAX_PATH_LEN]
Definition variables.h:939
Cmpnts vertices[8]
Coordinates of the eight vertices of the cell.
Definition variables.h:219
PetscBool fieldStatisticsContinue
Definition variables.h:995
@ BC_FACE_NEG_X
Definition variables.h:309
@ BC_FACE_NEG_Z
Definition variables.h:311
@ BC_FACE_POS_X
Definition variables.h:309
Defines a 3D axis-aligned bounding box.
Definition variables.h:212
Defines the vertices of a single hexahedral grid cell.
Definition variables.h:218
The six face planes of one hexahedron, indexed by Face, and its characteristic size.
Definition variables.h:229
A 3D point or vector with PetscScalar components.
Definition variables.h:144
A lean struct to hold the global cell ownership range for a single MPI rank.
Definition variables.h:263
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
A generic C-style linked list node for integers.
Definition variables.h:498
Header file for particle location functions using the walking search algorithm.
PetscErrorCode CalculateDistancesToCellFacePlanes(const Cmpnts p, const CellFacePlanes *planes, PetscReal *d, const PetscReal threshold, Cmpnts *normals)
Signed distances from a point to precomputed cell face planes.
PetscErrorCode CalculateDistancesToCellFaces(const Cmpnts p, const Cell *cell, PetscReal *d, const PetscReal threshold, Cmpnts *normals)
Computes the signed distances from a point to each face of a cubic cell.
PetscErrorCode FindOwnerOfCell(UserCtx *user, PetscInt i, PetscInt j, PetscInt k, PetscMPIInt *owner_rank)
Finds the MPI rank that owns a given global cell index.
PetscErrorCode RetrieveCurrentCell(UserCtx *user, PetscInt idx, PetscInt idy, PetscInt idz, Cell *cell)
Retrieves the coordinates of the eight vertices of the current cell.